diff --git a/packages/agy-cli/README.en.md b/packages/agy-cli/README.en.md index 4e72629..379fec6 100644 --- a/packages/agy-cli/README.en.md +++ b/packages/agy-cli/README.en.md @@ -81,9 +81,35 @@ MCP server. The control port listens on loopback only, with a token per process. - **Isolation**: your global MCP configuration is never read. Every agy process runs with a temporary agent, and every permission request agy raises (shell, file edits, browser) is refused. Real actions happen on the client side. +- **Assistant prefill**: requests that end with a text-only assistant message + (SillyTavern presets, "continue"/"impersonate", bot frameworks) are served + instead of rejected; the session ledger stays aligned across turns. See + "Assistant prefill" below. - **Usage visibility**: Magpie shows the agy subscription usage windows. They are informational only; running out of quota does not block requests automatically. +## Assistant prefill + +A client request that ends with a **text-only assistant message** (a +SillyTavern preset prefill, a "continue" / "impersonate" turn, a bot +framework's assembled context) used to be rejected with a 400. The prefill now +becomes part of the current turn: + +- The prefill stays in the tail, so the session ledger (expectedMessages, + client bytes) stays aligned with the client's own history across turns — the + session is reused after a prefill turn instead of replaying from scratch; +- The prefill text renders as a continuation carrier (a note line plus the + fragment itself), telling the model to continue from where the fragment + stops; +- `AGY_BRIDGE_PREFILL=0` restores the stock 400 reject; + `AGY_BRIDGE_PREFILL_CARRIER_NOTE` overrides the carrier's note line. + +Known limits: a prefill alongside a live tool_result, or directly after an +unanswered tool_use, is still rejected; a +contiguous assistant tail with no user message before it is treated as one +prefill run (that turn degrades to a fresh session and self-heals on the next +turn); the models a client gets remain agy's decision. + ## Requirements - The Antigravity CLI (`agy`) with the `acp` subcommand. Signing in from Magpie @@ -183,6 +209,8 @@ measurable data shows "Limits not available" rather than a fake 0% or 100%. | `AGY_BRIDGE_USAGE_TIMEOUT_MS` | 15000 | Total time budget for a usage query, capped at 18000 | | `AGY_BRIDGE_MCP_TRACE` | unset | Writes MCP channel traffic to the given file; for debugging only | | `AGY_CLI_DISABLE_AUTO_UPDATE` | `true` for the plugin's agy processes | agy's own variable. When you set it, agy gets your value; see "Requirements" | +| `AGY_BRIDGE_PREFILL` | on | Set to `0` to restore the stock 400 reject for assistant prefill tails; see "Assistant prefill" | +| `AGY_BRIDGE_PREFILL_CARRIER_NOTE` | English system note | The note line rendered before a prefill fragment (sent to the model) | ## Minimal agent (`AGY_BRIDGE_MINIMAL_AGENT=1`) diff --git a/packages/agy-cli/README.md b/packages/agy-cli/README.md index 4376af8..4ce3c3f 100644 --- a/packages/agy-cli/README.md +++ b/packages/agy-cli/README.md @@ -60,8 +60,27 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy 就用 `session/resume` 接上上下文。状态文件只存会话 ID 与哈希,不存消息原文。 - **隔离运行**:不读取你的全局 MCP 配置。每个 agy 进程使用临时 agent。agy 发起的权限 请求(shell、写文件、浏览器等)一律拒绝,真正的操作都在客户端侧完成。 +- **助手预填**:以 assistant 结尾的预填请求(SillyTavern 预设、继续写、bot 框架)不再 + 400 拒绝:预填留在本轮并渲染为续写载体,会话跨轮保持对齐,见下文「助手预填」。 - **额度查看**:在 Magpie 里查看 agy 订阅的用量窗口,仅作展示,额度耗尽时不会自动拦截请求。 +## 助手预填(assistant prefill) + +客户端的请求以一条**纯文本 assistant 消息**结尾时(SillyTavern 预设的预填、 +「继续写 / Impersonate」、bot 框架的拼装),旧版会直接 400 拒绝。现在这段 +预填被当作本轮的一部分: + +- 预填留在本轮尾部,会话账本(expectedMessages,客户端原字节)与客户端自己 + 的历史跨轮对齐——预填轮之后会话照常复用,不再整段重放; +- 预填文本渲染为一条续写载体(提示行 + 原文),发给 agy 让模型从停下的地方 + 接着写; +- `AGY_BRIDGE_PREFILL=0` 恢复原来的 400 拒绝;`AGY_BRIDGE_PREFILL_CARRIER_NOTE` + 自定义载体提示行。 + +已知限制:与 live tool_result 共存的预填、以及未应答 tool_use 后紧跟的预填仍被 400 拒绝;前面没有 user 消息的 +连续 assistant 尾整段视为预填(该轮降级为新会话,下一轮自愈);向客户端开放 +哪些模型仍由 agy 决定。 + ## 环境要求 - Antigravity CLI(`agy`),带 `acp` 子命令。在 Magpie 里登录需要 1.5.0 起的 agy(`agy acp --login`);更早的版本请先在终端运行一次 `agy` 登录。 @@ -141,6 +160,8 @@ magpie quota refresh agy-cli --json | `AGY_BRIDGE_USAGE_TIMEOUT_MS` | 15000 | 额度查询的总时间预算,最高 18000 | | `AGY_BRIDGE_MCP_TRACE` | 未设置 | 把 MCP 通道流量写入指定文件,仅用于排查 | | `AGY_CLI_DISABLE_AUTO_UPDATE` | 插件启动的 agy 设为 `true` | agy 自己的变量。你设置了就原样传给 agy,见「环境要求」 | +| `AGY_BRIDGE_PREFILL` | 开启 | 设为 `0` 恢复对 assistant 预填尾巴的原生 400 拒绝,见「助手预填」 | +| `AGY_BRIDGE_PREFILL_CARRIER_NOTE` | 英文系统提示行 | 预填片段渲染时的提示行文本(发给模型) | ## 精简 agent(`AGY_BRIDGE_MINIMAL_AGENT=1`) diff --git a/packages/agy-cli/agy-cli.test.mjs b/packages/agy-cli/agy-cli.test.mjs index 8fe555b..426c579 100644 --- a/packages/agy-cli/agy-cli.test.mjs +++ b/packages/agy-cli/agy-cli.test.mjs @@ -17,6 +17,7 @@ function run(args, timeout) { for (const [name, mocks] of [ ["platform.mjs", true], ["compat.mjs", true], + ["prefill.mjs", false], ["usage.mjs", true], ["catalog.mjs", false], ["usage-settlement.mjs", false], diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index 60290a4..6d4f0d8 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -2537,8 +2537,63 @@ function historyKey(messages) { return stableJSON(rows.filter(row => row.content.length)) } +// Assistant-prefill support: a trailing text-only assistant message is a +// client-side prefill (chat/roleplay frontends, "continue"/"impersonate" +// flows, bot frameworks). Keep the run in the tail so the session ledger +// (expectedMessages, client bytes) stays aligned with the client's own +// history across turns, and render it as a continuation carrier instead of +// the system-reminder treatment. AGY_BRIDGE_PREFILL=0 restores the stock +// reject; AGY_BRIDGE_PREFILL_CARRIER_NOTE overrides the carrier's note line. +const prefillTailEnabled = () => process.env.AGY_BRIDGE_PREFILL !== "0" +const prefillCarrierNote = () => process.env.AGY_BRIDGE_PREFILL_CARRIER_NOTE + || "(system note: the fragment below is part of your own unfinished reply; continue exactly from where it stops, and do not repeat it.)" + +// Concatenated text of an assistant message, or null when the message carries +// anything other than plain text blocks. An empty string means "no content". +function assistantTextOf(message) { + if (!message || message.role !== "assistant") return null + if (typeof message.content === "string") return message.content + if (!Array.isArray(message.content)) return null + let text = "" + for (const block of message.content) { + if (!block || block.type !== "text" || typeof block.text !== "string") return null + text += block.text + } + return text +} + +// History/tail positions for a request that ends with an assistant prefill +// run: runStart = first message of the trailing text-only assistant run, +// boundary = history split point (after the last assistant message before the +// run, the session ledger's newest entry). Returns null when the request does +// not end with a text-only assistant run. Known limits: a request combining a +// live tool_result with a prefill tail is rejected in validateBody; a run with +// no user message before it (contiguous assistant tail, e.g. a client re-sending +// a completed reply with a prefill appended) puts the whole run in the tail, so +// that one turn degrades to a fresh session (safe, self-healing). +function prefillRun(messages) { + const last = messages.at(-1) + if (!last || last.role !== "assistant") return null + if (assistantTextOf(last) === null) return null + let runStart = messages.length + while (runStart > 0 && messages[runStart - 1]?.role === "assistant" && assistantTextOf(messages[runStart - 1]) !== null) runStart-- + let boundary = runStart + while (boundary > 0 && messages[boundary - 1]?.role !== "assistant") boundary-- + return { runStart, boundary } +} + +function renderPrefillCarrierParts(message) { + const body = (assistantTextOf(message) || "").trim() + if (!body) return [] + return [{ type: "text", text: `${prefillCarrierNote()}\n${body}` }] +} + function trailingMessages(body) { body = canonicalBody(body) + const run = prefillTailEnabled() ? prefillRun(body.messages) : null + if (run) { + return { history: body.messages.slice(0, run.boundary), messages: body.messages.slice(run.boundary) } + } let start = body.messages.length while (start > 0 && body.messages[start - 1].role !== "assistant") start-- return { history: body.messages.slice(0, start), messages: body.messages.slice(start) } @@ -2993,7 +3048,14 @@ function renderTurnMessageParts(message) { } function renderTurnMessagesParts(messages) { - const groups = messages.map(renderTurnMessageParts).filter((group) => group.length > 0) + // A trailing assistant prefill run renders as a continuation carrier rather + // than the system-reminder treatment (see prefillRun above). + const run = prefillTailEnabled() && messages.length ? prefillRun(messages) : null + const prefillStart = run ? run.runStart : -1 + const groups = messages.map((message, index) => + prefillStart >= 0 && index >= prefillStart + ? renderPrefillCarrierParts(message) + : renderTurnMessageParts(message)).filter((group) => group.length > 0) const out = [] for (let i = 0; i < groups.length; i++) { if (i > 0) out.push({ type: "text", text: "\n\n" }) @@ -3185,10 +3247,17 @@ function validateBody(body) { } const trailing = trailingMessages(body) const lastRole = body.messages.at(-1)?.role - const validTailRole = lastRole === "user" || lastRole === "system" || lastRole === "developer" + // A text-only assistant tail is a client-side prefill (see prefillRun). + const prefillTail = prefillTailEnabled() && lastRole === "assistant" && assistantTextOf(body.messages.at(-1)) !== null + const validTailRole = lastRole === "user" || lastRole === "system" || lastRole === "developer" || prefillTail + if (prefillTail && extractToolResults(body).length) { + throw new UnsupportedContent("a request combining a live tool_result with an assistant prefill tail") + } if (!validTailRole || (!extractToolResults(body).length && !trailing.messages.some((message) => message.role === "user") && !trailing.history.length)) { - throw new UnsupportedContent("a request whose last message is not from the user or a tool-result notification") + throw new UnsupportedContent(prefillTail + ? "a request whose only messages are assistant prefill turns (no user turn to continue from)" + : "a request whose last message is not from the user or a tool-result notification") } if (body.system && typeof body.system !== "string") { if (!Array.isArray(body.system) || body.system.some((block) => block?.type !== "text")) { diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 5ed50a0..daf8a0b 100644 --- a/packages/agy-cli/package.json +++ b/packages/agy-cli/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.2", + "version": "0.1.3", "description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI", "type": "module", "main": "./opencode.mjs", diff --git a/packages/agy-cli/test/prefill.mjs b/packages/agy-cli/test/prefill.mjs new file mode 100644 index 0000000..5814302 --- /dev/null +++ b/packages/agy-cli/test/prefill.mjs @@ -0,0 +1,125 @@ +import assert from "node:assert/strict" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { pathToFileURL } from "node:url" +import { after, test } from "node:test" + +// Expose private seams from an isolated copy, without adding production exports. +// These cases cover the assistant-prefill tail: run positions, validation, the +// continuation carrier rendering, the cross-turn ledger alignment, and the +// AGY_BRIDGE_PREFILL=0 stock-behavior toggle. +const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "agy-prefill-tail-test-")) +const entry = new URL("../index.mjs", import.meta.url) +let source = fs.readFileSync(entry, "utf8") +source = source.replace(/from "(\.\/[^"\n]+)"/g, (_, target) => `from ${JSON.stringify(new URL(target, entry).href)}`) +fs.writeFileSync(path.join(workspace, "bridge.mjs"), source + "\nexport { trailingMessages, prefillRun, assistantTextOf, validateBody, renderTurnMessagesParts, renderInitialPromptParts };\n") +const { trailingMessages, prefillRun, assistantTextOf, validateBody, renderTurnMessagesParts, renderInitialPromptParts } = await import(pathToFileURL(path.join(workspace, "bridge.mjs")).href) +after(() => fs.rmSync(workspace, { recursive: true, force: true })) + +const U = text => ({ role: "user", content: text }) +const A = text => ({ role: "assistant", content: text }) +const S = text => ({ role: "system", content: text }) +const toolUseTail = () => ({ role: "assistant", content: [{ type: "text", text: "working" }, { type: "tool_use", id: "call_a", name: "Read", input: { path: "a" } }] }) +const join = parts => parts.map(part => part?.text || "").join("") + +test("assistantTextOf collects text blocks and refuses anything else", () => { + assert.equal(assistantTextOf(A("abc")), "abc") + assert.equal(assistantTextOf({ role: "assistant", content: [{ type: "text", text: "a" }, { type: "text", text: "b" }] }), "ab") + assert.equal(assistantTextOf({ role: "assistant", content: [{ type: "text", text: "a" }, { type: "tool_use", id: "x", name: "f", input: {} }] }), null) + assert.equal(assistantTextOf(A("")), "") +}) + +test("prefillRun locates the trailing text-only assistant run", () => { + assert.deepEqual(prefillRun([U("1"), A("p1"), A("r1"), U("2"), A("p2")]), { runStart: 4, boundary: 3 }) + assert.deepEqual(prefillRun([U("1"), A("p")]), { runStart: 1, boundary: 0 }) + assert.deepEqual(prefillRun([A("r"), A("p")]), { runStart: 0, boundary: 0 }) + assert.equal(prefillRun([U("1"), A("r1"), U("2")]), null, "a user tail is not a prefill") + assert.equal(prefillRun([U("1"), toolUseTail()]), null, "a tool_use tail is not a prefill") +}) + +test("trailingMessages keeps a prefill tail out of the replayed history", () => { + const { history, messages } = trailingMessages({ messages: [U("1"), A("p1"), A("r1"), U("2"), A("p2")] }) + assert.deepEqual(history, [U("1"), A("p1"), A("r1")]) + assert.deepEqual(messages, [U("2"), A("p2")]) + const fresh = trailingMessages({ messages: [U("1"), A("p")] }) + assert.deepEqual(fresh.history, []) + assert.deepEqual(fresh.messages, [U("1"), A("p")]) + const withSystem = trailingMessages({ messages: [S("sys"), U("1"), A("p1"), A("r1"), U("2"), A("p2")] }) + assert.deepEqual(withSystem.history, [U("1"), A("p1"), A("r1")], "a leading system message is promoted, not replayed") + const normal = trailingMessages({ messages: [U("1"), A("r1"), U("2")] }) + assert.deepEqual(normal.history, [U("1"), A("r1")]) + assert.deepEqual(normal.messages, [U("2")]) +}) + +test("the session ledger stays aligned with the client history across prefill turns", () => { + // turn 1: a fresh prefill request. startTurn records the client messages and + // recordAssistantResponse appends the reply. + const t1 = trailingMessages({ messages: [U("one"), A("")] }) + assert.deepEqual(t1.history, []) + const ledger = [...t1.messages, A("first reply")] + // turn 2: the client re-sends its history plus the next prefill. The patched + // boundary must land exactly on the ledger, or the session would be retired. + const t2 = trailingMessages({ messages: [...ledger, U("two"), A(" two")] }) + assert.deepEqual(t2.history, ledger, "cross-turn ledger alignment") + ledger.push(U("two"), A(" two"), A("second reply")) + // turn 3: a plain user turn (no prefill) keeps aligning with the ledger. + const t3 = trailingMessages({ messages: [...ledger, U("three")] }) + assert.deepEqual(t3.history, ledger) +}) + +test("validateBody serves a prefill tail and rejects the unsupported shapes", () => { + validateBody({ messages: [U("1"), A("p")] }) + validateBody({ messages: [U("1"), A("p1"), A("r1"), U("2"), A("p2")] }) + assert.throws(() => validateBody({ messages: [A("r"), A("p")] }), /no user turn to continue from/) + assert.throws(() => validateBody({ messages: [U("1"), toolUseTail()] }), /not from the user or a tool-result/) + assert.throws( + () => validateBody({ messages: [U("1"), A("r1"), { role: "user", content: [{ type: "tool_result", tool_use_id: "call_a", content: "done" }] }, A("p")] }), + /tool_result with an assistant prefill/, + ) +}) + +test("a trailing prefill run renders as a continuation carrier, not a system reminder", () => { + process.env.AGY_BRIDGE_PREFILL_CARRIER_NOTE = "CARRIER-NOTE-MARKER" + try { + const text = join(renderTurnMessagesParts([U("stay aside"), A("opening")])) + assert.ok(text.includes("CARRIER-NOTE-MARKER"), "the carrier note is rendered") + assert.ok(text.includes("opening"), "the prefill fragment is rendered") + assert.ok(!text.includes("system-reminder"), "the stock system-reminder wrap is replaced") + const normal = join(renderTurnMessagesParts([U("1"), A("r1"), U("2")])) + assert.ok(!normal.includes("CARRIER-NOTE-MARKER"), "a plain request renders without the carrier") + } finally { + delete process.env.AGY_BRIDGE_PREFILL_CARRIER_NOTE + } +}) + +test("a fresh session's initial prompt carries the prefill carrier too", () => { + process.env.AGY_BRIDGE_PREFILL_CARRIER_NOTE = "CARRIER-NOTE-MARKER" + try { + const text = join(renderInitialPromptParts({ messages: [U("one"), A("opening")] }, null, true)) + assert.ok(text.includes("CARRIER-NOTE-MARKER")) + assert.ok(text.includes("opening")) + } finally { + delete process.env.AGY_BRIDGE_PREFILL_CARRIER_NOTE + } +}) + +test("AGY_BRIDGE_PREFILL=0 restores the stock reject and the stock split", () => { + process.env.AGY_BRIDGE_PREFILL = "0" + try { + assert.throws(() => validateBody({ messages: [U("1"), A("p")] }), /not from the user or a tool-result/) + const { history, messages } = trailingMessages({ messages: [U("1"), A("p")] }) + assert.deepEqual(messages, []) + assert.deepEqual(history, [U("1"), A("p")]) + // prefillRun itself is pure geometry and stays toggle-agnostic: the + // callers (trailingMessages, validateBody, the renderer) gate on + // prefillTailEnabled, so only their behavior changes with the toggle. + } finally { + delete process.env.AGY_BRIDGE_PREFILL + } +}) + +test("the boundary transform is deterministic for identical requests", () => { + const body = { messages: [U("1"), A("p1"), A("r1"), U("2"), A("p2")] } + assert.deepEqual(trailingMessages(body), trailingMessages(body)) +}) diff --git a/packages/agy-cli/test/smoke.mjs b/packages/agy-cli/test/smoke.mjs index 73e55b6..2d7e3fa 100644 --- a/packages/agy-cli/test/smoke.mjs +++ b/packages/agy-cli/test/smoke.mjs @@ -1638,8 +1638,8 @@ for (const location of ["inline", "system", "developer", "user"]) { ], }) const nonTextPayload = await nonTextSystem.json() - check("assistant prefill and lone system messages return 400", - prefillOnly.status === 400 && prefillTail.status === 400 && loneSystem.status === 400, + check("an assistant prefill tail is served; an assistant-only request and a lone system stay 400", + prefillOnly.status === 400 && prefillTail.status === 200 && loneSystem.status === 400, `${prefillOnly.status},${prefillTail.status},${loneSystem.status}`) check("unsupported system content block error names the block type", nonTextSystem.status === 400 && nonTextPayload.error?.message?.includes('"audio_chunk"'),