agy-cli 0.1.83: a pending call Codex dropped is answered as cancelled, and the live session goes on (#1231)

Codex delivers a sub-agent message at a sampling boundary by keeping the
interrupted reply's text, dropping its tool call, and sending the history
on with the new message. Since 0.1.74 lineageVerdict called that a fork:
the pending call was closed with SUPERSEDED_NOTE and the conversation was
replayed in a new session, losing agy's cached prefix and, for a long
history, the turns past the 112 KiB prompt budget.

Now lineageVerdict returns "dropped" when the recorded history with the
turn's unanswered calls taken out is exactly the client's history, and
the reply that carried them kept some text. keepDroppedTurn answers those
calls with "cancelled by the client, not executed" through the existing
steerInSession (MCP commit wait, session/cancel, history set to the
client's), and the new trailing message goes in as the next prompt in
the same session. A changed reply text, a reply that was only the call,
grown tools, another work dir or other instructions still replay as
before; so does a steer that fails.

Run (mote, HOME=$(mktemp -d)):
- node --test test/dropped-call.mjs: 3 pass (kept session; changed text
  replays; call-only reply replays).
- bun test (agy-cli): 38 pass, 0 fail.
- bun scripts/check.mjs agy-cli: ok.

Broken by hand: origin/main's index.mjs with the new test: the kept-
session case fails (a second agy session is started); the two replay
cases pass on both.

Not tried: a real Codex session with a sub-agent message arriving
mid-sampling against a real agy; the fake reproduces the request shape
the issue describes. Part 1 (history seed through systemPrompt.append,
opt-in) is not in this change.
This commit is contained in:
yetone
2026-11-17 01:49:29 +08:00
parent 36dc4007fc
commit f10738917f
4 changed files with 154 additions and 2 deletions
+1
View File
@@ -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],
+52 -1
View File
@@ -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
+1 -1
View File
@@ -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",
+100
View File
@@ -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)
})
})