diff --git a/packages/agy-cli/agy-cli.test.mjs b/packages/agy-cli/agy-cli.test.mjs index f96a9b4..b7bb4c9 100644 --- a/packages/agy-cli/agy-cli.test.mjs +++ b/packages/agy-cli/agy-cli.test.mjs @@ -26,6 +26,7 @@ for (const [name, mocks] of [ ["tool-summary.mjs", false], ["usage-settlement.mjs", false], ["steer-in-session.mjs", false], + ["dropped-call.mjs", false], ["repeat-batch.mjs", false], ["conversation-key.mjs", false], ["windows-nc.mjs", false], diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index d295ed2..9a7d32a 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -98,6 +98,7 @@ const NO_PROGRESS_REPEAT_WINDOW_MS = 10 * 60 * 1000 const NO_PROGRESS_REPEAT_MAX_ENTRIES = 256 const POOL_PRESSURE_NOTE = "agy bridge: this tool call was closed to free an agy process for another conversation; stop this turn" const SUPERSEDED_NOTE = "agy bridge: this tool call was superseded because the client conversation continued without it; stop this turn" +const DROPPED_NOTE = "agy bridge: cancelled by the client, not executed; the conversation continues with the next message" const SELF_POLL_IDLE_TIMEOUT_MS = positiveTimeout(process.env.AGY_BRIDGE_SELF_POLL_IDLE_TIMEOUT_MS, 20 * 60 * 1000) const SELF_POLL_LIMIT = positiveTimeout(process.env.AGY_BRIDGE_SELF_POLL_LIMIT, 8) // A conflict retrying can never fix: SDKs that honour this header (Anthropic @@ -3322,7 +3323,13 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo existing = null } if (existing && !existing.dead && existing.turn) { - const lineage = lineageVerdict(existing, existing.turn, opts) + let lineage = lineageVerdict(existing, existing.turn, opts) + if (lineage === "dropped") { + const held = existing.turn + const kept = await keepDroppedTurn(existing, held, opts) + logBridgeEvent(existing, held, kept ? "kept" : "keep_failed", "lineage_dropped", opts) + if (!kept) lineage = "fork" + } if (lineage === "fork" || lineage === "answered") { const orphan = existing.turn logBridgeEvent(existing, orphan, "superseded", lineage === "fork" ? "lineage_fork" : "lineage_answered", opts, @@ -3581,9 +3588,35 @@ function lineageVerdict(proc, turn, opts) { if (!carried && !recorded && Array.isArray(expected) && expected.length > base.length && history.length === expected.length && historyKey(withoutInputs(history)) === historyKey(withoutInputs(expected))) return null + // Codex keeps the text of a reply it interrupts (a sub-agent's message at a + // sampling boundary) but drops the reply's tool calls, then sends on (#1231). + // The client's history is this session's with only the pending calls taken + // out, so the session can answer them as cancelled and go on, keeping its + // cached prefix, instead of replaying the conversation in a new one. + if (!carried && !recorded && !opts.hasToolResults && droppedPendingCalls(turn, expected, base, history)) return "dropped" return carried || recorded ? "conflict" : "fork" } +// The recorded history with the turn's unanswered calls removed is exactly the +// client's, and the reply that carried them kept something else (its text). +function droppedPendingCalls(turn, expected, base, history) { + if (!Array.isArray(expected) || expected.length <= base.length || history.length !== expected.length) return false + const pending = new Set(turn.calls.filter((call) => call.id && !call.result && !call.mcpResponded).map((call) => call.id)) + if (!pending.size) return false + let removed = 0 + const stripped = expected.map((message) => { + if (message?.role !== "assistant" || !Array.isArray(message.content)) return message + const content = message.content.filter((block) => !(block?.type === "tool_use" && pending.has(block.id))) + removed += message.content.length - content.length + return { ...message, content } + }) + if (removed !== pending.size) return false + const last = stripped.at(-1) + if (last?.role !== "assistant" || !last.content.some((block) => block?.type === "text" && block.text?.trim())) return false + if (stripped.slice(base.length).some((message) => Array.isArray(message.content) && !message.content.length)) return false + return historyKey(stripped) === historyKey(history) +} + // Every tool_use of the turn's calls in messages has a tool_result after it. function carriedAnswered(messages, ids) { const open = new Set() @@ -3616,6 +3649,24 @@ function replayHistoryProblem(body, resultBlocks) { return answered.size === ids.size ? null : "missing_tool_result" } +// Answers the calls the client dropped as cancelled and leaves the session at +// the client's history, ready for its next message. False when the session +// can't take it as it is; the caller then replays, as for a fork. +async function keepDroppedTurn(proc, turn, opts) { + if (proc.toolsGrew(opts.tools) || proc.workDir !== opts.workDir || + !sameInstructions(proc.instructions, opts.instructions)) return false + const results = turn.calls.filter((call) => call.id && !call.result && !call.mcpResponded).map((call) => ({ + block: { tool_use_id: call.id }, + call, + result: { content: [{ type: "text", text: DROPPED_NOTE }], isError: true }, + })) + try { + return await proc.steerInSession(turn, results, opts.history) + } catch { + return false + } +} + async function reclaimStaleTurn(proc, turn, note = "agy bridge: stale tool turn closed") { noProgressRepeats.delete(proc.convKey) turn.closeNote = note diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 6c60ba7..a9205be 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.82", + "version": "0.1.83", "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/dropped-call.mjs b/packages/agy-cli/test/dropped-call.mjs new file mode 100644 index 0000000..58b9f74 --- /dev/null +++ b/packages/agy-cli/test/dropped-call.mjs @@ -0,0 +1,100 @@ +// #1231: Codex delivers a sub-agent message at a sampling boundary by keeping +// the interrupted reply's text, dropping its tool call, and sending on. The +// live session answers the dropped call as cancelled and takes the new message +// as its next prompt instead of replaying the conversation in a new session. + +import { test } from "node:test" +import assert from "node:assert/strict" +import { baseBody, createBridgeKit, readSse, sleep } from "./testkit.mjs" + +const USAGE = { inputTokens: 100, cachedReadTokens: 0, cachedWriteTokens: 0, outputTokens: 5, totalTokens: 105 } + +async function withKit(fn) { + const kit = await createBridgeKit({}) + try { return await fn(kit) } finally { await kit.dispose() } +} + +function interruptedTurn(kit, seen) { + kit.prompts.push(async (agent) => { + await agent.text("Let me read the file.") + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + seen.reply = await agent.tool("Read", { path: "/a" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "failed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + seen.prompts.push(JSON.stringify(agent.prompt)) + await agent.text("went on") + return { stopReason: "end_turn", usage: USAGE } + } +} + +function sentOn(body, assistant, text) { + return { ...body, messages: [...body.messages, { role: "assistant", content: assistant }, { role: "user", content: text }] } +} + +test("#1231 a dropped pending call is answered as cancelled and the live session goes on", async () => { + await withKit(async (kit) => { + const seen = { prompts: [] } + interruptedTurn(kit, seen) + const body = baseBody() + const first = await readSse(await kit.request(body)) + assert.equal(first.stopReason, "tool_use") + await sleep(20) + const next = sentOn(body, [{ type: "text", text: "Let me read the file." }], "SUBAGENT_MESSAGE arrived") + const res = await kit.request(next) + assert.equal(res.status, 200, await (res.status === 200 ? "" : res.text())) + const parsed = await readSse(res) + assert.equal(parsed.stopReason, "end_turn") + assert.equal(kit.acpSpawns.length, 1, "the live session is kept, no replay") + assert.equal(seen.reply?.result?.isError, true) + assert.match(seen.reply.result.content[0].text, /not executed/) + assert.equal(seen.prompts.length, 1) + assert.ok(seen.prompts[0].includes("SUBAGENT_MESSAGE")) + assert.ok(!seen.prompts[0].includes("start the task"), "only the new message is sent, not a replay") + + // The session's history is the client's: its next message continues it. + const third = sentOn(next, parsed.content.map((b) => ({ type: "text", text: b.text })), "and again") + const again = await readSse(await kit.request(third)) + assert.equal(again.stopReason, "end_turn") + assert.equal(kit.acpSpawns.length, 1) + }) +}) + +test("#1231 a reply whose text changed too is a fork and replays", async () => { + await withKit(async (kit) => { + const seen = { prompts: [] } + interruptedTurn(kit, seen) + const body = baseBody() + await readSse(await kit.request(body)) + await sleep(20) + const res = await kit.request(sentOn(body, [{ type: "text", text: "Something else entirely." }], "SUBAGENT_MESSAGE arrived")) + assert.equal(res.status, 200) + await readSse(res) + assert.equal(kit.acpSpawns.length, 2, "a different branch is replayed in a new session") + assert.match(seen.reply?.result?.content?.[0]?.text ?? "", /superseded/) + }) +}) + +test("#1231 a reply that was only the tool call is a fork and replays", async () => { + await withKit(async (kit) => { + const seen = { prompts: [] } + kit.prompts.push(async (agent) => { + seen.reply = await agent.tool("Read", { path: "/a" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("went on") + return { stopReason: "end_turn", usage: USAGE } + } + const body = baseBody() + await readSse(await kit.request(body)) + await sleep(20) + const res = await kit.request({ ...body, messages: [...body.messages, { role: "user", content: "SUBAGENT_MESSAGE arrived" }] }) + assert.equal(res.status, 200) + await readSse(res) + assert.equal(kit.acpSpawns.length, 2) + }) +})