diff --git a/packages/agy-cli/agy-cli.test.mjs b/packages/agy-cli/agy-cli.test.mjs index 8a717b9..e3b8060 100644 --- a/packages/agy-cli/agy-cli.test.mjs +++ b/packages/agy-cli/agy-cli.test.mjs @@ -23,6 +23,7 @@ for (const [name, mocks] of [ ["step-usage.mjs", false], ["tool-schema.mjs", false], ["usage-settlement.mjs", false], + ["steer-in-session.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 be4580d..37de1bd 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -72,6 +72,15 @@ function ideCallDeadline() { return positiveTimeout(process.env.AGY_BRIDGE_IDE_CALL_DEADLINE_MS, 150_000) } const CANCEL_SETTLE_MS = 15_000 +const MAX_MCP_COMMIT_WAIT_MS = 60_000 +function mcpCommitWaitMs() { + const raw = process.env.AGY_BRIDGE_MCP_COMMIT_WAIT_MS + if (raw !== undefined && raw.trim() !== "") { + const parsed = Number(raw) + if (Number.isFinite(parsed) && parsed >= 0) return Math.min(Math.floor(parsed), MAX_MCP_COMMIT_WAIT_MS) + } + return 5_000 +} const RECLAIM_STOP_TIMEOUT_MS = 10_000 // Repeated unmatched tool results against the same turn that made no progress: // attempts below the limit stay 409 (a live turn may still be waiting), the @@ -914,6 +923,11 @@ class Turn { this.done = false this.finalized = false this.cancelRequested = false + this.steering = false + this.promptInFlight = false + this.activeAcpToolCalls = new Set() + this.acpToolWaiters = [] + this.cancelledMcpSockets = new Set() this.agentError = false this.heldText = "" this.timer = null @@ -1122,6 +1136,7 @@ class Turn { if (this.done) return this.done = true clearTimeout(this.timer) + this.notifyAcpTools() this.push({ type: "result", result }) } @@ -1129,6 +1144,7 @@ class Turn { if (this.done || this.finalized) return this.done = true clearTimeout(this.timer) + this.notifyAcpTools() for (const waiter of this.lateWaiters.splice(0)) waiter.reject(error) this.push({ type: "error", error }) clearTimeout(this.cleanupTimer) @@ -1138,6 +1154,78 @@ class Turn { this.cleanupTimer.unref() } + noteAcpToolUpdate(update) { + const type = update?.sessionUpdate + const id = update?.toolCallId + if (!id) return + if (type === "tool_call") { + if (!update.status || update.status === "in_progress" || update.status === "pending") { + this.activeAcpToolCalls.add(id) + } else { + this.activeAcpToolCalls.delete(id) + } + this.notifyAcpTools() + return + } + if (type === "tool_call_update" && update.status && + update.status !== "in_progress" && update.status !== "pending") { + this.activeAcpToolCalls.delete(id) + this.notifyAcpTools() + } + } + + notifyAcpTools() { + for (const check of [...this.acpToolWaiters]) check() + } + + // Waits until agy finishes recording the MCP responses for `pendingIds` + // (emits tool_call_update, moves on to generation, or closes the turn) so a + // follow-up session/cancel does not abort an in-flight MCP tool execution. + waitAcpToolsCommitted(pendingIds, timeoutMs) { + const remaining = () => { + if (this.done || this.finalized || this.sawGenerationOutput) return false + for (const id of pendingIds) { + if (this.activeAcpToolCalls.has(id)) return true + } + return false + } + if (!remaining()) return Promise.resolve(true) + return new Promise((resolve) => { + let settled = false + const finish = (ok) => { + if (settled) return + settled = true + clearTimeout(timer) + const idx = this.acpToolWaiters.indexOf(check) + if (idx >= 0) this.acpToolWaiters.splice(idx, 1) + resolve(ok) + } + const check = () => { + if (!remaining()) finish(true) + } + const timer = setTimeout(() => finish(!remaining()), timeoutMs) + timer.unref?.() + this.acpToolWaiters.push(check) + }) + } + + // Preserves SQLite step-usage tracking across a steered tool turn when the + // cancelled prompt ended cleanly after its already-measured tool step(s), + // with no unconsumed or pending generation row left in the store. + reconcileCancelledStepUsage(rawUsage) { + if (this.stepUsageReconciled || this.sawGenerationOutput || !this.stepsFile || this.stepCursor == null) return + const measuredPrompt = this.measured?.prompt ?? 0 + if (measuredPrompt <= 0 || !rawUsage || typeof rawUsage !== "object") return + const acp = promptUsage(rawUsage) + const expected = acp.promptInput + acp.write + if (expected <= 0) return + if (Math.abs(measuredPrompt - expected) > Math.max(16, Math.ceil(expected * 0.01))) return + const tail = modelUsageAfter(this.stepsFile, this.stepCursor) + if (tail && !tail.pending && tail.steps.length === 0) { + this.stepUsageReconciled = true + } + } + // True while the client still owes a result, including calls agy stopped waiting for. hasPendingMcp() { return this.calls.some((call) => (call.mcpSeen && !call.mcpResponded) || (call.deferred && !call.result)) @@ -1494,17 +1582,26 @@ class Proc { if (!turn || turn.done || turn.finalized) return const update = params.update ?? {} turn.arm() + turn.noteAcpToolUpdate(update) if (turn.cancelRequested) return if (update.sessionUpdate === "agent_message_chunk") { const text = update.content?.type === "text" ? update.content.text : "" if (text) { turn.sawGenerationOutput = true + if (turn.steering) { + turn.notifyAcpTools() + return + } turn.pushText(text) } } else if (update.sessionUpdate === "agent_thought_chunk") { const text = update.content?.type === "text" ? update.content.text : "" if (text) { turn.sawGenerationOutput = true + if (turn.steering) { + turn.notifyAcpTools() + return + } turn.push({ type: "thinking", text }) } } @@ -1571,22 +1668,35 @@ class Proc { return historyKey(stripToolUseInputs(expectedAssistant)) === historyKey(stripToolUseInputs(actualAssistant)) } - // Answers the pending calls with the results the client sent, cancels what - // agy was doing next, and leaves the session at `history`, ready for the - // steer's prompt. False when anything is off; the caller then replays in a - // new session, as before. + // Answers the pending calls with the results the client sent, waits for agy + // to commit those MCP responses before cancelling what it would do next, and + // leaves the session at `history`, ready for the steer's prompt. False when + // anything is off; the caller then replays in a new session, as before. async steerInSession(turn, results, history) { - if (this.dead || this.stopping || this.retiring || this.turn !== turn || turn.done || turn.finalized || - !Array.isArray(history)) return false + if (this.dead || this.stopping || this.retiring || this.turn !== turn || turn.steering || turn.done || + turn.finalized || !Array.isArray(history)) return false // An image in a result is replayed in the prompt, as before. if (results.some((item) => item.result.content.some((part) => part.type !== "text"))) return false + const deliveringLiveMcp = results.some(({ call }) => + (!call.deferred && !call.mcpResponded && call.ready && !turn.done) || + (call.deferred && !call.result && turn.awaitCalls.some((waiter) => waiter.target === call))) + // ACP toolCallIds come from agy's session/update notifications and are + // distinct from the bridge's toolu_ IDs, so snapshot all in-flight ACP IDs. + const pendingAcpIds = deliveringLiveMcp ? new Set(turn.activeAcpToolCalls) : new Set() + turn.steering = true try { this.continueWith(results) } catch { + turn.steering = false return false } - if (!this.cancelTurn(turn, [])) return false + if (pendingAcpIds.size && !(await turn.waitAcpToolsCommitted(pendingAcpIds, mcpCommitWaitMs()))) { + return false + } + if (this.dead || this.stopping || this.retiring) return false + if (!turn.done && !turn.finalized && !this.cancelTurn(turn, [])) return false await Promise.race([turn.settled, new Promise((resolve) => setTimeout(resolve, CANCEL_SETTLE_MS))]) + if (turn.done && !turn.finalized) this.finalizeTurn(turn) if (!turn.finalized || this.dead || this.stopping || this.historyInvalid || this.turn) return false this.expectedMessages = history.map((message) => ({ ...message })) return true @@ -1628,12 +1738,19 @@ class Proc { unpark(this.convKey) this.hasSentFirstTurn = true const promptNumber = turn.beginPrompt(promptParts, lateCalls) - const result = await this.conn.request("session/prompt", { - sessionId: this.sessionId, - prompt: promptParts.length ? promptParts : [{ type: "text", text: "" }], - }) + turn.promptInFlight = true + let result + try { + result = await this.conn.request("session/prompt", { + sessionId: this.sessionId, + prompt: promptParts.length ? promptParts : [{ type: "text", text: "" }], + }) + } finally { + turn.promptInFlight = false + } usage = turn.recordPromptUsage(promptNumber, result?.usage) if (turn.cancelRequested) { + turn.reconcileCancelledStepUsage(usage) turn.complete({ stopReason: "cancelled" }) return } @@ -1736,9 +1853,19 @@ class Proc { acceptMcpCall(message, socket) { const turn = this.turn - if (!turn || turn.done || turn.finalized || turn.cancelRequested) { + if (!turn || turn.done || turn.finalized) { throw new Error("agy bridge: no active turn for MCP call") } + if (turn.cancelRequested || turn.steering) { + // Hold any trailing sibling MCP call quiet while session/cancel is on its + // way so agy aborts it via cancellation instead of advancing to a new step. + turn.cancelledMcpSockets.add(socket) + socket.once("close", () => turn.cancelledMcpSockets.delete(socket)) + return null + } + if (!turn.promptInFlight) { + throw new Error("agy bridge: no prompt in flight for MCP call") + } const name = message.name const args = message.arguments ?? {} if (!args || typeof args !== "object" || Array.isArray(args)) throw new Error("agy bridge: invalid tool arguments") @@ -1889,6 +2016,12 @@ class Proc { finalizeTurn(turn) { if (turn.finalized) return turn.finalized = true + turn.notifyAcpTools() + for (const socket of turn.cancelledMcpSockets) { + try { socket.destroy() } catch {} + } + turn.cancelledMcpSockets.clear() + turn.steering = false if (turn.stepsFile && turn.promptCount > 0 && !turn.stepUsageReconciled) { this.stepUsageTrusted = false } @@ -2300,7 +2433,7 @@ async function evictLRU() { let victim = null for (const proc of pool.values()) { const turn = proc.turn - if (proc.retiring || !turn || turn.attached || turn.cancelRequested) continue + if (proc.retiring || !turn || turn.attached || turn.cancelRequested || turn.steering) continue const since = turn.clientProgressAt ?? turn.lastProgressAt if (!staleTurnVerdict(proc, turn, now).stale && now - since < bound) continue if (!victim || since < victim.since) victim = { proc, turn, since } @@ -2545,6 +2678,7 @@ function noteNoProgressRepeat(convKey, turn, now = Date.now()) { function staleTurnVerdict(proc, turn, now = Date.now()) { if (!turn || turn.cancelRequested) return { stale: false, reason: "cancelling" } if (turn.attached) return { stale: false, reason: "attached" } + if (turn.steering) return { stale: false, reason: "steering" } if (turn.finalized) return { stale: true, reason: "finalized" } if (proc.dead || proc.stopping) return { stale: true, reason: "dead" } if (turn.done) return { stale: true, reason: "done" } @@ -2555,7 +2689,7 @@ function staleTurnVerdict(proc, turn, now = Date.now()) { // A pending tool turn only owns its own line of history, not a sibling request // that continues its base without carrying any of the emitted tool calls. function lineageVerdict(proc, turn, opts) { - if (!turn || turn.attached || turn.cancelRequested || turn.done || turn.finalized) return null + if (!turn || turn.attached || turn.cancelRequested || turn.steering || turn.done || turn.finalized) return null if (proc.dead || proc.stopping || proc.retiring || !turn.hasPendingMcp()) return null const history = opts.history const base = turn.baseHistory @@ -2650,7 +2784,7 @@ async function recoverStaleTurn(ctx) { const verdict = staleTurnVerdict(current, held) // Lineage supersession belongs to acquisition of a new prompt. Unmatched // results alone reclaim an unexpired owner only at the repeat limit. - if (!verdict.stale && (!forced || verdict.reason === "attached")) { + if (!verdict.stale && (!forced || verdict.reason === "attached" || verdict.reason === "steering")) { logBridgeEvent(current, held, "reject_active", verdict.reason, ctx.acquireOpts, extra) return { kind: "active" } } @@ -5226,6 +5360,7 @@ export const AntigravityBridgePlugin = async () => { } if (proc.turn !== turn) return jsonError(409, "agy bridge: the tool response has already completed") if (turn.attached) throw new BusyError("agy bridge: this conversation already has an active response") + if (turn.steering) throw new BusyError("agy bridge: this conversation is already steering this tool turn") noProgressRepeats.delete(convKey) // matched results are real progress const rawResults = matches.map(({ block, match }) => ({ block, @@ -5260,7 +5395,11 @@ export const AntigravityBridgePlugin = async () => { sameInstructions(proc.instructions, instructions) && await proc.steerInSession(turn, rawResults, trailingMessages(body).history)) { keptSession = true - answeredIds = new Set(rawResults.map((item) => item.block.tool_use_id)) + answeredIds = new Set( + rawResults + .filter((item) => !item.call.deferred || item.call.lateDelivered) + .map((item) => item.block.tool_use_id), + ) } else if (interrupted || !historyMatches || proc.toolsGrew(tools) || proc.workDir !== workDir || !sameInstructions(proc.instructions, instructions)) { // A changed context, a tool catalog that grew, or a @@ -5286,7 +5425,7 @@ export const AntigravityBridgePlugin = async () => { let attempts if (!verdict.stale) { // An attached stream is live progress; only a quiet turn counts. - if (verdict.reason === "attached") noProgressRepeats.delete(convKey) + if (verdict.reason === "attached" || verdict.reason === "steering") noProgressRepeats.delete(convKey) else attempts = noteNoProgressRepeat(convKey, held.turn) if (attempts == null || attempts < NO_PROGRESS_REPEAT_LIMIT) { logBridgeEvent(held, held.turn, "reject_active", verdict.reason, acquireOpts, diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index c4d0e93..f7fa4f6 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.30", + "version": "0.1.31", "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/smoke.mjs b/packages/agy-cli/test/smoke.mjs index b09ca76..99b6598 100644 --- a/packages/agy-cli/test/smoke.mjs +++ b/packages/agy-cli/test/smoke.mjs @@ -109,12 +109,13 @@ let mcpReady = null let nextMcpId = 0 const mcpPending = new Map() let cancelWaiter = null +let activePromptScope = null function update(value) { send({ jsonrpc: "2.0", method: "session/update", params: { sessionId: session.id, update: value } }) } -const chunk = text => update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text } }) -const thought = text => update({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text } }) +const chunk = text => { if (!activePromptScope?.cancelled) update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text } }) } +const thought = text => { if (!activePromptScope?.cancelled) update({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text } }) } function mcpRequest(method, params) { return new Promise((resolve, reject) => { @@ -163,15 +164,58 @@ function saveState() { } async function invoke(name, args) { - update({ sessionUpdate: "tool_call", toolCallId: "call_" + (++nextMcpId), name: "mcp_ide-tools_" + name, status: "in_progress", kind: "other", rawInput: args }) + const scope = activePromptScope + if (scope?.cancelled) { + return { content: [{ type: "text", text: "Tool execution was canceled" }], isError: true } + } + const callId = "call_" + (++nextMcpId) + update({ sessionUpdate: "tool_call", toolCallId: callId, name: "mcp_ide-tools_" + name, status: "in_progress", kind: "other", rawInput: args }) log({ type: "mcpPending", convId: session.id, name, arguments: args }) let result + let cancelledDuringCall = false try { - result = await mcpRequest("tools/call", { name, arguments: args, _meta: { progressToken: "pt-" + nextMcpId } }) + const callPromise = mcpRequest("tools/call", { name, arguments: args, _meta: { progressToken: "pt-" + nextMcpId } }) + if (scope) { + let onCancel + const cancelPromise = new Promise(resolve => { + onCancel = () => { + cancelledDuringCall = true + resolve({ content: [{ type: "text", text: "Tool execution was canceled" }], isError: true }) + } + scope.listeners.add(onCancel) + }) + try { + result = await Promise.race([callPromise, cancelPromise]) + } finally { + scope.listeners.delete(onCancel) + } + if (cancelledDuringCall) { + callPromise.catch(() => {}) + mcp?.stdin?.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/cancelled", params: { reason: "context canceled" } }) + "\n") + log({ type: "mcpCanceled", convId: session.id, name }) + } + } else { + result = await callPromise + } } catch (error) { result = { content: [{ type: "text", text: error.message }], isError: true } } log({ type: "mcpResult", convId: session.id, name, result }) + update({ + sessionUpdate: "tool_call_update", + toolCallId: callId, + name: "mcp_ide-tools_" + name, + status: result?.isError ? "failed" : "completed", + }) + // Real agy enters an upstream model generation after recording tool_call_update; + // session/cancel arriving right after tool_call_update aborts before streaming. + if (scope && !scope.cancelled) { + await new Promise(resolve => { + const onCancel = () => { clearTimeout(timer); scope.listeners.delete(onCancel); resolve() } + const timer = setTimeout(() => { scope.listeners.delete(onCancel); resolve() }, 15) + scope.listeners.add(onCancel) + }) + } return result } @@ -181,6 +225,20 @@ function finish(reply, extra = {}) { const cached = extra.cached || 0 const thought = extra.thought || 0 const input = extra.input ?? 10 + if (activePromptScope?.cancelled) { + log({ type: "cancelled", convId: session.id, prompt: session.prompts }) + return { + stopReason: "cancelled", + usage: { + inputTokens: extra.exclusive ? input : input + cached, + outputTokens: thought, + cachedReadTokens: cached, + cachedWriteTokens: 0, + thoughtTokens: thought, + totalTokens: input + cached + thought, + }, + } + } log({ type: "result", convId: session.id, prompt: session.prompts, response: reply }) return { stopReason: "end_turn", @@ -434,8 +492,15 @@ async function handle(message) { model = params.modelId log({ type: "setModel", convId: session.id, model }) return {} - case "session/prompt": - return prompt(params) + case "session/prompt": { + const scope = { cancelled: false, listeners: new Set() } + activePromptScope = scope + try { + return await prompt(params) + } finally { + if (activePromptScope === scope) activePromptScope = null + } + } default: throw { code: -32601, message: "unknown method " + message.method } } @@ -447,6 +512,10 @@ readline.createInterface({ input: process.stdin }).on("line", line => { if (message.method === "session/cancel") { log({ type: "cancel", convId: session?.id }) cancelWaiter?.() + if (activePromptScope && !activePromptScope.cancelled) { + activePromptScope.cancelled = true + for (const fn of [...activePromptScope.listeners]) fn() + } return } if (!message.method && pendingClient.has(message.id)) { @@ -1917,11 +1986,37 @@ for (const location of ["inline", "system", "developer", "user"]) { inits().length === initsBefore && replay.text.includes("New instruction after Esc") && !replay.text.includes("partial tool output") && fs.existsSync(old.cwd), `got ${response.status} ${JSON.stringify({ replay: replay.convId, old: old.convId, n: inits().length, before: initsBefore })} ${replay.text}`) + check("steering commits the real MCP tool output before session/cancel instead of cancelling MCP execution", + mcpResultText(old.convId).includes("partial tool output") && + !mcpResultText(old.convId).includes("Tool execution was canceled") && + !logs().some(event => event.type === "mcpCanceled" && event.convId === old.convId), + mcpResultText(old.convId)) const third = nextTurn(second, final, "MEMORY after interrupted tool turn") const thirdRes = await callFetch(third) await readSSE(thirdRes) check("turn after a user-interrupted tool turn reuses the same session", thirdRes.status === 200 && lastOf("user").convId === replay.convId) + + // Steering after the first call of a sequential multi-tool prompt commits call #1 and cancels before call #2 runs. + const multiFirst = { model, messages: [{ role: "user", content: "TWOSTEP steer after first call" }], tools: [echoTool] } + const multiEvents = (await readSSE(await callFetch(multiFirst))).events + const multiConv = inits().at(-1).convId + const multiBefore = inits().length + const multiSecond = continuation(multiFirst, multiEvents, "first-steered-output") + multiSecond.messages.at(-1).content.push( + { type: "text", text: "[Request interrupted by user]\n" }, + { type: "text", text: "Skip second call and reply immediately" }, + ) + const multiRes = await callFetch(multiSecond) + const multiFinal = (await readSSE(multiRes)).events + const multiPending = logs().filter(event => event.type === "mcpPending" && event.convId === multiConv) + check("steering a sequential multi-tool turn commits the first MCP result and cancels before the second MCP call", + multiRes.status === 200 && stopOf(multiFinal) === "end_turn" && + lastOf("user").convId === multiConv && inits().length === multiBefore && + mcpResultText(multiConv).includes("first-steered-output") && + !logs().some(event => event.type === "mcpCanceled" && event.convId === multiConv) && + multiPending.length === 1, + JSON.stringify({ status: multiRes.status, pending: multiPending.length, mcp: mcpResultText(multiConv) })) } { diff --git a/packages/agy-cli/test/steer-in-session.mjs b/packages/agy-cli/test/steer-in-session.mjs new file mode 100644 index 0000000..bc92482 --- /dev/null +++ b/packages/agy-cli/test/steer-in-session.mjs @@ -0,0 +1,615 @@ +// Adversarial regressions for in-session tool steering (`Proc.steerInSession`): +// MCP commit barrier (`waitAcpToolsCommitted`), concurrent request re-entrancy +// (`turn.steering` busy guard), held trailing sibling MCP calls, generation +// chunk wakeup + suppression, natural turn completion / child crash wakeup, +// deferred (`LONGTOOL`) self-poll vs non-polled `withoutAnswered` filtering, +// `AGY_BRIDGE_MCP_COMMIT_WAIT_MS` bounds, and stale MCP socket rejection before +// the next `session/prompt` starts (`turn.promptInFlight`). + +import { test } from "node:test" +import assert from "node:assert/strict" +import { + baseBody, continueWithToolResults, createBridgeKit, readSse, sleep, +} from "./testkit.mjs" + +const USAGE = { inputTokens: 100, cachedReadTokens: 0, cachedWriteTokens: 0, outputTokens: 5, totalTokens: 105 } + +async function withKit(options, fn) { + const kit = await createBridgeKit(options) + try { + return await fn(kit) + } finally { + await kit.dispose() + } +} + +function steerBody(body, prev, text = "Steer to new instruction", resultFn = () => "REAL_RESULT_42") { + const next = continueWithToolResults(body, prev, resultFn) + next.messages.at(-1).content.push({ type: "text", text }) + return next +} + +function cancelCount(kit) { + return kit.acpLog.filter((entry) => entry.method === "session/cancel").length +} + +async function settleResponse(resPromise) { + const res = await resPromise + if (res.status !== 200) { + return { status: res.status, body: await res.text() } + } + const parsed = await readSse(res) + return { + status: 200, + stopReason: parsed.stopReason, + text: parsed.content.filter((b) => b.type === "text").map((b) => b.text).join(""), + tools: parsed.content.filter((b) => b.type === "tool_use").map((b) => b.input), + error: parsed.error, + } +} + +test("steerInSession: duplicate steer and plain continuation during waitAcpToolsCommitted return 503 without early cancel", async () => { + // Duplicate steer hitting waitAcpToolsCommitted window + await withKit({}, async (kit) => { + let cancelBeforeCommit = null + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + const reply = await agent.tool("Read", { path: "/a" }) + assert.equal(reply?.result?.content?.[0]?.text, "REAL_RESULT_42") + await sleep(140) + cancelBeforeCommit = agent.cancelPending + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text(`steered:${agent.index}`) + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + const steered = steerBody(body, first) + const reqA = kit.request(steered) + await sleep(30) + const reqB = kit.request(steered) + const [resA, resB] = await Promise.all([settleResponse(reqA), settleResponse(reqB)]) + + assert.equal(cancelBeforeCommit, false, "duplicate steer must not trigger session/cancel before tool_call_update") + assert.equal(resA.status, 200) + assert.equal(resA.stopReason, "end_turn") + assert.equal(resA.text, "steered:1") + assert.equal(resB.status, 503) + assert.match(resB.body, /already steering/) + assert.equal(kit.acpSpawns.length, 1) + }) + + // Plain non-steer continuation hitting waitAcpToolsCommitted window + await withKit({}, async (kit) => { + let cancelBeforeCommit = null + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + await sleep(140) + cancelBeforeCommit = agent.cancelPending + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text(`steered:${agent.index}`) + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + const reqA = kit.request(steerBody(body, first)) + await sleep(30) + const reqB = kit.request(continueWithToolResults(body, first, () => "REAL_RESULT_42")) + const [resA, resB] = await Promise.all([settleResponse(reqA), settleResponse(reqB)]) + + assert.equal(cancelBeforeCommit, false) + assert.equal(resA.status, 200) + assert.equal(resA.text, "steered:1") + assert.equal(resB.status, 503) + assert.match(resB.body, /already steering/) + assert.equal(kit.acpSpawns.length, 1) + }) +}) + +test("steerInSession: parallel same-name tool calls wait until every in-flight ACP toolCallId commits", async () => { + await withKit({}, async (kit) => { + let cancelAfterSecondOnly = null + let seenReplies = null + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + agent.update({ sessionUpdate: "tool_call", toolCallId: "c2", status: "in_progress" }) + const replies = await agent.tools([["Read", { path: "/a" }], ["Read", { path: "/b" }]]) + seenReplies = replies.map((r) => r?.result?.content?.[0]?.text) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c2", status: "completed" }) + await sleep(80) + cancelAfterSecondOnly = agent.cancelPending + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("parallel steered") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + assert.equal(first.content.filter((b) => b.type === "tool_use").length, 2) + + const res = await settleResponse(kit.request(steerBody(body, first, "Steer", (_b, i) => `RES_${i}`))) + assert.deepEqual(seenReplies, ["RES_0", "RES_1"]) + assert.equal(cancelAfterSecondOnly, false, "must wait for c1 even after c2 completed") + assert.equal(res.status, 200) + assert.equal(res.text, "parallel steered") + assert.equal(kit.acpSpawns.length, 1) + }) +}) + +test("steerInSession: trailing sibling MCP call during steer is held quiet and its socket destroyed on finalize", async () => { + await withKit({}, async (kit) => { + let heldPromise = null + let heldSettledBeforeCancel = false + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + agent.update({ sessionUpdate: "tool_call", toolCallId: "c2", status: "in_progress" }) + heldPromise = agent.tool("Read", { path: "/late-sibling" }).then((reply) => { + if (!agent.cancelPending) heldSettledBeforeCancel = true + return reply + }) + await sleep(40) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("steered cleanly") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + const res = await settleResponse(kit.request(steerBody(body, first))) + assert.equal(res.status, 200) + assert.equal(res.text, "steered cleanly") + assert.equal(kit.acpSpawns.length, 1, "held sibling call must not break cancelTurn or force a new session") + assert.equal(heldSettledBeforeCancel, false, "held sibling socket must stay quiet until cancel/finalize") + + const heldOutcome = await Promise.race([heldPromise, sleep(250).then(() => "hung")]) + assert.equal(heldOutcome, null, "finalizeTurn must destroy held sibling sockets so MCP helpers never hang") + }) +}) + +test("steerInSession: generation output (text or thought) wakes commit wait early and is suppressed on steered turn", async () => { + for (const kind of ["text", "thought"]) { + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "2500" } }, async (kit) => { + kit.prompts.push(async (agent) => { + // Deliberately omit tool_call_update: moving on to generation proves MCP committed. + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + if (kind === "text") await agent.text("STALE_POST_TOOL_TEXT") + else await agent.thought("STALE_POST_TOOL_THOUGHT") + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text(`steered-${kind}`) + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + const [proc] = [...kit.module.__agyTestAllProcs] + const turn1 = proc.turn + + const startedAt = Date.now() + const res = await settleResponse(kit.request(steerBody(body, first))) + const elapsed = Date.now() - startedAt + + assert.equal(res.status, 200) + assert.equal(res.text, `steered-${kind}`) + assert.equal(kit.acpSpawns.length, 1, `${kind} chunk must resolve waitAcpToolsCommitted and keep session`) + assert.ok(elapsed < 800, `${kind} chunk should wake waitAcpToolsCommitted immediately, took ${elapsed}ms`) + assert.equal( + turn1.events.some((ev) => ev.type === "text" || ev.type === "thinking"), + false, + `steered turn must suppress ${kind} chunks from the cancelled step`, + ) + }) + } +}) + +test("steerInSession: natural end_turn and child crash during commit wait wake immediately and handle session state cleanly", async () => { + // Natural end_turn without tool_call_update or chunks: wakes immediately, finalizes turn1, reuses session + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "2500" } }, async (kit) => { + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + await sleep(20) + return { stopReason: "end_turn", usage: USAGE } + }) + let prompt2Text = "" + kit.defaultPrompt = async (agent) => { + prompt2Text = JSON.stringify(agent.prompt) + await agent.text("steered after natural end") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + const startedAt = Date.now() + const res = await settleResponse(kit.request(steerBody(body, first))) + const elapsed = Date.now() - startedAt + + assert.equal(res.status, 200) + assert.equal(res.text, "steered after natural end") + assert.equal(kit.acpSpawns.length, 1, "natural completion must finalize turn1 and keep the live session") + assert.equal(cancelCount(kit), 0) + assert.ok(elapsed < 800, `Turn.complete() must wake waitAcpToolsCommitted immediately, took ${elapsed}ms`) + assert.equal(prompt2Text.includes("REAL_RESULT_42"), false) + assert.equal(prompt2Text.includes("Steer to new instruction"), true) + }) + + // Child SIGKILL during commit wait: wakes immediately and replays in a fresh session + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "2500" } }, async (kit) => { + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + await sleep(20) + for (const child of [...kit.children]) child.kill("SIGKILL") + return new Promise(() => {}) + }) + kit.defaultPrompt = async (agent) => { + await agent.text("replayed after crash") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + const startedAt = Date.now() + const res = await settleResponse(kit.request(steerBody(body, first))) + const elapsed = Date.now() - startedAt + + assert.equal(res.status, 200) + assert.equal(res.text, "replayed after crash") + assert.equal(kit.acpSpawns.length, 2) + assert.ok(elapsed < 1000, `Turn.fail() must wake waitAcpToolsCommitted immediately, took ${elapsed}ms`) + }) +}) + +test("steerInSession: deferred LONGTOOL result goes via MCP when self-polled, or in steer prompt when unpolled", async () => { + // Unpolled deferred call: agy received "still running" and moved on without polling -> steer prompt MUST carry REAL_RESULT + await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "50" } }, async (kit) => { + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + const firstReply = await agent.tool("Read", { path: "/long" }) + assert.match(firstReply?.result?.content?.[0]?.text || "", /still running/) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + let prompt2 = "" + kit.defaultPrompt = async (agent) => { + prompt2 = JSON.stringify(agent.prompt) + await agent.text("steered unpolled") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + await sleep(90) + const res = await settleResponse(kit.request(steerBody(body, first, "Steer", () => "LONG_RESULT_77"))) + + assert.equal(res.status, 200) + assert.equal(res.text, "steered unpolled") + assert.equal(kit.acpSpawns.length, 1) + assert.equal((prompt2.match(/LONG_RESULT_77/g) || []).length, 1, "unpolled deferred result must be sent in steer prompt") + }) + + // Self-polled deferred call: waiter is active when steer arrives -> delivered via MCP poll, NOT duplicated in steer prompt + await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "180" } }, async (kit) => { + let pollReplyText = null + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/long" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + agent.update({ sessionUpdate: "tool_call", toolCallId: "c2", status: "in_progress" }) + const pollReply = await agent.tool("Read", { path: "/long" }) + pollReplyText = pollReply?.result?.content?.[0]?.text + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c2", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + let prompt2 = "" + kit.defaultPrompt = async (agent) => { + prompt2 = JSON.stringify(agent.prompt) + await agent.text("steered polled") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + await sleep(240) + const res = await settleResponse(kit.request(steerBody(body, first, "Steer", () => "LONG_RESULT_77"))) + + assert.equal(res.status, 200) + assert.equal(res.text, "steered polled") + assert.equal(pollReplyText, "LONG_RESULT_77") + assert.equal(kit.acpSpawns.length, 1) + assert.equal((prompt2.match(/LONG_RESULT_77/g) || []).length, 0, "live self-polled result must not be duplicated in steer prompt") + }) +}) + +test("steerInSession: AGY_BRIDGE_MCP_COMMIT_WAIT_MS clamps int32 overflow and supports 0ms immediate fallback", async () => { + // > 2^31 - 1 must clamp to 60s instead of overflowing setTimeout to 1ms + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "3000000000" } }, async (kit) => { + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + await sleep(80) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("clamped ok") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + const res = await settleResponse(kit.request(steerBody(body, first))) + assert.equal(res.status, 200) + assert.equal(res.text, "clamped ok") + assert.equal(kit.acpSpawns.length, 1, "clamped timeout must not fire at 1ms before tool_call_update") + }) + + // "0" immediately falls back to replay without waiting 5s when uncommitted + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "0" } }, async (kit) => { + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("zero-wait replay") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + const startedAt = Date.now() + const res = await settleResponse(kit.request(steerBody(body, first))) + const elapsed = Date.now() - startedAt + + assert.equal(res.status, 200) + assert.equal(res.text, "zero-wait replay") + assert.equal(kit.acpSpawns.length, 2) + assert.ok(elapsed < 800, `0ms commit wait should fall back immediately, took ${elapsed}ms`) + }) +}) + +test("steerInSession: stale MCP socket arriving before next session/prompt is rejected instead of leaking a phantom tool_use", async () => { + await withKit({}, async (kit) => { + let agent1 = null + kit.prompts.push(async (agent) => { + agent1 = agent + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await sleep(15) + await agent.text("clean next turn") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody() + const first = await readSse(await kit.request(body)) + const [proc] = [...kit.module.__agyTestAllProcs] + const origStartTurn = proc.startTurn + let staleCall = null + proc.startTurn = function (...args) { + const nextTurn = origStartTurn.apply(this, args) + staleCall = agent1.tool("Read", { path: "/STALE_FROM_CANCELLED_TURN" }) + proc.startTurn = origStartTurn + return nextTurn + } + + const res = await settleResponse(kit.request(steerBody(body, first))) + const staleReply = await staleCall + + assert.equal(res.status, 200) + assert.equal(res.stopReason, "end_turn") + assert.equal(res.tools.length, 0, "stale MCP call must never leak into the next turn as tool_use") + assert.equal(res.text, "clean next turn") + assert.match(staleReply?.error?.message || "", /no prompt in flight/) + assert.equal(kit.acpSpawns.length, 1) + }) +}) + +test("steerInSession: pool pressure and repeated unmatched tool results cannot evict or reclaim an active steer", async () => { + // Pool pressure (evictLRU) while steering + await withKit({ env: { AGY_BRIDGE_MAX_PROCS: "1", AGY_BRIDGE_DETACHED_EVICT_MS: "10" } }, async (kit) => { + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + await sleep(120) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("survived pool pressure") + return { stopReason: "end_turn", usage: USAGE } + } + + const body1 = baseBody({ messages: [{ role: "user", content: "conversation one" }] }) + const first = await readSse(await kit.request(body1)) + const steerReq = kit.request(steerBody(body1, first)) + await sleep(25) + kit.clock.advance(60_000) + const body2 = baseBody({ messages: [{ role: "user", content: "conversation two" }] }) + const otherRes = await settleResponse(kit.request(body2)) + const steerRes = await settleResponse(steerReq) + + assert.equal(otherRes.status, 503, "pool pressure must reject new conversation rather than evicting steering turn") + assert.match(otherRes.body, /unfinished responses/) + assert.equal(steerRes.status, 200) + assert.equal(steerRes.text, "survived pool pressure") + assert.equal(kit.acpSpawns.length, 1) + }) + + // 3x unmatched tool results (NO_PROGRESS_REPEAT_LIMIT) while steering must stay 409 and never reclaim + await withKit({}, async (kit) => { + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + await sleep(150) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("survived unmatched repeats") + return { stopReason: "end_turn", usage: USAGE } + } + + const body = baseBody({ messages: [{ role: "user", content: "conversation repeat guard" }] }) + const first = await readSse(await kit.request(body)) + const steerReq = kit.request(steerBody(body, first)) + await sleep(25) + + const bogus = continueWithToolResults(body, first, () => "BOGUS") + for (const block of bogus.messages.at(-1).content) { + if (block.type === "tool_result") block.tool_use_id = "toolu_unmatched_bogus_id" + } + const boguses = [] + for (let i = 0; i < 3; i++) { + boguses.push(await settleResponse(kit.request(bogus))) + } + const steerRes = await settleResponse(steerReq) + + assert.deepEqual(boguses.map((r) => r.status), [409, 409, 409]) + assert.equal(steerRes.status, 200) + assert.equal(steerRes.text, "survived unmatched repeats") + assert.equal(kit.acpSpawns.length, 1) + }) +}) + +test("steerInSession: deferred self-poll commit wait, foreign ACP tool isolation, failed status commit, and waitLate promptInFlight guard", async () => { + // 1. Self-polled deferred call must wait for agy's ACP tool_call_update on the poll before session/cancel + await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "180" } }, async (kit) => { + let cancelBeforeCommit = null + let pollText = null + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/long" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + agent.update({ sessionUpdate: "tool_call", toolCallId: "c2", status: "in_progress" }) + const poll = await agent.tool("Read", { path: "/long" }) + pollText = poll?.result?.content?.[0]?.text + await sleep(120) + cancelBeforeCommit = agent.cancelPending + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c2", status: "completed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("polled deferred ok") + return { stopReason: "end_turn", usage: USAGE } + } + const body = baseBody() + const first = await readSse(await kit.request(body)) + await sleep(240) + const res = await settleResponse(kit.request(steerBody(body, first, "Steer", () => "LONG_77"))) + assert.equal(res.status, 200) + assert.equal(pollText, "LONG_77") + assert.equal(cancelBeforeCommit, false, "session/cancel went out before the polled call's tool_call_update") + assert.equal(kit.acpSpawns.length, 1) + }) + + // 2. Unrelated agy-internal ACP tool in flight must not stall a steer that delivers no live MCP socket + await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "50", AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "1500" } }, async (kit) => { + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/long" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "completed" }) + agent.update({ sessionUpdate: "tool_call", toolCallId: "internal9", status: "in_progress" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("unpolled deferred ok") + return { stopReason: "end_turn", usage: USAGE } + } + const body = baseBody() + const first = await readSse(await kit.request(body)) + await sleep(90) + const t0 = Date.now() + const res = await settleResponse(kit.request(steerBody(body, first, "Steer", () => "LONG_77"))) + const elapsed = Date.now() - t0 + assert.equal(res.status, 200) + assert.equal(kit.acpSpawns.length, 1) + assert.ok(elapsed < 800, `stalled ${elapsed}ms on a foreign ACP tool`) + }) + + // 3. Stale MCP call arriving during waitLate between two prompts of the same turn is rejected + await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "50" } }, async (kit) => { + let agent1 = null + kit.prompts.push(async (agent) => { + agent1 = agent + await agent.tool("Read", { path: "/long" }) + return { stopReason: "end_turn", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("late ok") + return { stopReason: "end_turn", usage: USAGE } + } + const body = baseBody() + await readSse(await kit.request(body)) + await sleep(120) + const [proc] = [...kit.module.__agyTestAllProcs] + assert.ok(proc.turn && !proc.turn.done, "turn should be waiting for the late result") + const outcome = await Promise.race([ + agent1.tool("Read", { path: "/STALE_BETWEEN_PROMPTS" }), + sleep(300).then(() => "accepted-and-pending"), + ]) + assert.match(outcome?.error?.message || String(outcome), /no prompt in flight/) + }) + + // 4. tool_call_update with status "failed" (e.g. client tool_result is_error) counts as committed + await withKit({ env: { AGY_BRIDGE_MCP_COMMIT_WAIT_MS: "1500" } }, async (kit) => { + kit.prompts.push(async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", status: "in_progress" }) + await agent.tool("Read", { path: "/a" }) + await sleep(30) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", status: "failed" }) + await agent.waitCancel() + return { stopReason: "cancelled", usage: USAGE } + }) + kit.defaultPrompt = async (agent) => { + await agent.text("failed tool committed") + return { stopReason: "end_turn", usage: USAGE } + } + const body = baseBody() + const first = await readSse(await kit.request(body)) + const t0 = Date.now() + const res = await settleResponse(kit.request(steerBody(body, first))) + const elapsed = Date.now() - t0 + assert.equal(res.status, 200) + assert.equal(kit.acpSpawns.length, 1) + assert.ok(elapsed < 800, `failed status did not count as commit: ${elapsed}ms`) + }) +}) + + diff --git a/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index f1dcf40..74cc6bf 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -314,6 +314,8 @@ class FakeAgy { index, prompt: params.prompt, sessionId: this.sessionId, + get cancelPending() { return self.cancelPending }, + update(u) { self.update(u) }, async text(text) { self.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text } }); await tick() }, async thought(text) { self.update({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text } }); await tick() }, // 同一批调用在同一个同步块里投递,等价于 agy 并行发起;返回各自的 MCP 回包。 diff --git a/packages/agy-cli/test/usage-settlement.mjs b/packages/agy-cli/test/usage-settlement.mjs index b3a72dc..3373878 100644 --- a/packages/agy-cli/test/usage-settlement.mjs +++ b/packages/agy-cli/test/usage-settlement.mjs @@ -1912,3 +1912,358 @@ test("SQLite field 3 已含 field 9(thinking):单步/多步落盘、steps } }) }) + +test("同会话工具中途 steer:等待 tool_call_update 提交后再发 session/cancel,且保留 SQLite stepUsageTrusted(含未消费新生成回退保护)", { skip: !openSqlite }, async () => { + const varint = (n) => { const out = []; while (n > 127) { out.push((n & 127) | 128); n = Math.floor(n / 128) } out.push(n); return out } + const field = (n, bytes) => [n * 8 + 2, ...varint(bytes.length), ...bytes] + const usageBytes = ({ input, output, write = 0, read = 0, thinking = 0 }) => [ + 0x10, ...varint(input), 0x18, ...varint(output), + ...(write ? [0x20, ...varint(write)] : []), + ...(read ? [0x28, ...varint(read)] : []), + ...(thinking ? [0x48, ...varint(thinking)] : []), + ] + const genBlob = (stats) => new Uint8Array(field(1, field(4, usageBytes(stats)))) + + // 子场景 1:正常 steer 等待 tool_call_update 后再取消,不取消在途 MCP 调用,且后续多步工具回合继续精确读取 gen_metadata + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + let cancelBeforeCommit = null + let mcpReply = null + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (0, ?)", genBlob({ input: 2400, read: 14_600, output: 35, thinking: 10 })) + } finally { + db.close() + } + agent.update({ sessionUpdate: "tool_call", toolCallId: "call_steer_1", name: "mcp_ide-tools_Read", status: "in_progress" }) + mcpReply = await agent.tool("Read", { path: "/secret.txt" }) + await sleep(15) + cancelBeforeCommit = agent.cancelPending + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "call_steer_1", name: "mcp_ide-tools_Read", status: "completed" }) + await agent.waitCancel() + return { + stopReason: "cancelled", + usage: { inputTokens: 2400, cachedReadTokens: 14_600, cachedWriteTokens: 0, outputTokens: 35, thoughtTokens: 10, totalTokens: 17_035 }, + } + }) + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const writeGen = (idx, stats) => { + const db = openSqlite(dbFile) + try { + db.run("INSERT INTO gen_metadata VALUES (?, ?)", idx, genBlob(stats)) + } finally { + db.close() + } + } + writeGen(1, { input: 350, read: 16_800, output: 48, thinking: 12 }) + await agent.tool("Read", { path: "/after-steer.txt" }) + writeGen(2, { input: 220, read: 17_200, output: 25, thinking: 5 }) + await agent.text("steered done") + return { + stopReason: "end_turn", + usage: { + inputTokens: 350 + 220, + cachedReadTokens: 16_800 + 17_200, + cachedWriteTokens: 0, + outputTokens: 48 + 25, + thoughtTokens: 12 + 5, + totalTokens: 350 + 220 + 16_800 + 17_200 + 48 + 25, + }, + } + }) + + const body1 = baseBody() + const first = await readSse(await kit.request(body1)) + assert.equal(first.stopReason, "tool_use") + assert.deepEqual(plain(first.usage), { + input_tokens: 2400, + cache_read_input_tokens: 14_600, + cache_creation_input_tokens: 0, + output_tokens: 35, + output_tokens_details: { thinking_tokens: 10 }, + }) + + const steeredBody = continueWithToolResults(body1, first, () => "SECRET_98421") + steeredBody.messages.at(-1).content.push({ type: "text", text: "Steer to new instruction" }) + const second = await readSse(await kit.request(steeredBody)) + assert.equal(second.stopReason, "tool_use") + assert.equal(cancelBeforeCommit, false, "session/cancel 不能早于 tool_call_update 发出") + assert.equal(mcpReply?.result?.content?.[0]?.text, "SECRET_98421") + assert.equal(kit.acpSpawns.length, 1, "steer 应复用同一 agy 会话") + assert.deepEqual(plain(second.usage), { + input_tokens: 350, + cache_read_input_tokens: 16_800, + cache_creation_input_tokens: 0, + output_tokens: 48, + output_tokens_details: { thinking_tokens: 12 }, + }) + + const third = await readSse(await kit.request(continueWithToolResults(steeredBody, second, () => "AFTER_STEER_OK"))) + assert.equal(third.stopReason, "end_turn") + assert.deepEqual(plain(third.usage), { + input_tokens: 220, + cache_read_input_tokens: 17_200, + cache_creation_input_tokens: 0, + output_tokens: 25, + output_tokens_details: { thinking_tokens: 5 }, + }) + }) + + // 子场景 2:若取消落地前 gen_metadata 已留下未消费的额外生成行,必须拒绝信任游标并回退 stepUsageTrusted = false + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (0, ?)", genBlob({ input: 2000, read: 10_000, output: 30, thinking: 5 })) + } finally { + db.close() + } + agent.update({ sessionUpdate: "tool_call", toolCallId: "call_steer_dirty", name: "mcp_ide-tools_Read", status: "in_progress" }) + await agent.tool("Read", { path: "/dirty.txt" }) + const db2 = openSqlite(dbFile) + try { + // 模拟取消前已插入一笔未消费的新生成行 + db2.run("INSERT INTO gen_metadata VALUES (1, ?)", genBlob({ input: 88_888, read: 0, output: 9 })) + } finally { + db2.close() + } + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "call_steer_dirty", name: "mcp_ide-tools_Read", status: "completed" }) + await agent.waitCancel() + return { + stopReason: "cancelled", + usage: { inputTokens: 2000, cachedReadTokens: 10_000, cachedWriteTokens: 0, outputTokens: 30, thoughtTokens: 5, totalTokens: 12_030 }, + } + }) + + kit.prompts.push(async (agent) => { + // 第二轮正常写入与其 ACP 用量完全吻合的 gen_metadata 行:若第一轮错误标记了 + // stepUsageReconciled = true,第二轮将把 proc.stepUsageTrusted 保持为 true。 + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.run("INSERT INTO gen_metadata VALUES (2, ?)", genBlob({ input: 500, read: 11_500, output: 12 })) + } finally { + db.close() + } + await agent.text("safe fallback") + return { + stopReason: "end_turn", + usage: { inputTokens: 500, cachedReadTokens: 11_500, cachedWriteTokens: 0, outputTokens: 12, totalTokens: 12_012 }, + } + }) + + const body1 = baseBody() + const first = await readSse(await kit.request(body1)) + const [proc] = [...kit.module.__agyTestAllProcs] + const turn1 = proc.turn + const steeredBody = continueWithToolResults(body1, first, () => "OK") + steeredBody.messages.at(-1).content.push({ type: "text", text: "Steer after dirty tail" }) + const second = await readSse(await kit.request(steeredBody)) + assert.equal(second.stopReason, "end_turn") + assert.equal(turn1.stepUsageReconciled, false, "存在未消费尾行时不得标记 stepUsageReconciled") + assert.equal(proc.stepUsageTrusted, false, "存在未消费 gen_metadata 尾行时必须关闭 stepUsageTrusted") + assert.notEqual(second.usage.input_tokens, 88_888, "不能把上一轮残留行误算到新回合") + }) + + // 子场景 3:尾部虽无新行,但 ACP 累计输入远超已测量的工具步(说明第 2 轮模型调用尚未刷盘即被取消),必须拒绝信任 + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (0, ?)", genBlob({ input: 2000, read: 10_000, output: 30, thinking: 5 })) + } finally { + db.close() + } + agent.update({ sessionUpdate: "tool_call", toolCallId: "call_steer_unflushed", name: "mcp_ide-tools_Read", status: "in_progress" }) + await agent.tool("Read", { path: "/unflushed.txt" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "call_steer_unflushed", name: "mcp_ide-tools_Read", status: "completed" }) + await agent.waitCancel() + return { + stopReason: "cancelled", + usage: { inputTokens: 15_000, cachedReadTokens: 10_000, cachedWriteTokens: 0, outputTokens: 50, thoughtTokens: 5, totalTokens: 25_050 }, + } + }) + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.run("INSERT INTO gen_metadata VALUES (1, ?)", genBlob({ input: 600, read: 12_000, output: 15 })) + } finally { + db.close() + } + await agent.text("after mismatch") + return { + stopReason: "end_turn", + usage: { inputTokens: 600, cachedReadTokens: 12_000, cachedWriteTokens: 0, outputTokens: 15, totalTokens: 12_615 }, + } + }) + + const body1 = baseBody() + const first = await readSse(await kit.request(body1)) + const [proc] = [...kit.module.__agyTestAllProcs] + const turn1 = proc.turn + const steeredBody = continueWithToolResults(body1, first, () => "OK") + steeredBody.messages.at(-1).content.push({ type: "text", text: "Steer after unflushed call" }) + const second = await readSse(await kit.request(steeredBody)) + assert.equal(second.stopReason, "end_turn") + assert.equal(turn1.stepUsageReconciled, false, "measuredPrompt 与 ACP 累计输入失配时不得标记 stepUsageReconciled") + assert.equal(proc.stepUsageTrusted, false, "measuredPrompt 与 ACP 累计输入失配时必须关闭 stepUsageTrusted") + }) + + // 子场景 4:同一 Turn 跨多个 prompt(LONGTOOL 延迟回传进入第 2 个 prompt 后再发起工具调用并被 steer),按累计 usage 对账并继续保持 stepUsageTrusted + await withKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "50" } }, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (0, ?)", genBlob({ input: 1500, read: 8500, output: 20, thinking: 4 })) + } finally { + db.close() + } + agent.update({ sessionUpdate: "tool_call", toolCallId: "call_long_1", name: "mcp_ide-tools_Read", status: "in_progress" }) + await agent.tool("Read", { path: "/slow.txt" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "call_long_1", name: "mcp_ide-tools_Read", status: "completed" }) + return { + stopReason: "end_turn", + usage: { inputTokens: 1500, cachedReadTokens: 8500, cachedWriteTokens: 0, outputTokens: 20, thoughtTokens: 4, totalTokens: 10_020 }, + } + }) + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.run("INSERT INTO gen_metadata VALUES (1, ?)", genBlob({ input: 1200, read: 9800, output: 25, thinking: 6 })) + } finally { + db.close() + } + agent.update({ sessionUpdate: "tool_call", toolCallId: "call_step_2", name: "mcp_ide-tools_Read", status: "in_progress" }) + await agent.tool("Read", { path: "/step2.txt" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "call_step_2", name: "mcp_ide-tools_Read", status: "completed" }) + await agent.waitCancel() + return { + stopReason: "cancelled", + usage: { inputTokens: 1200, cachedReadTokens: 9800, cachedWriteTokens: 0, outputTokens: 25, thoughtTokens: 6, totalTokens: 11_025 }, + } + }) + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.run("INSERT INTO gen_metadata VALUES (2, ?)", genBlob({ input: 410, read: 20_900, output: 18, thinking: 3 })) + } finally { + db.close() + } + await agent.text("multi-prompt steer done") + return { + stopReason: "end_turn", + usage: { inputTokens: 410, cachedReadTokens: 20_900, cachedWriteTokens: 0, outputTokens: 18, thoughtTokens: 3, totalTokens: 21_318 }, + } + }) + + const body1 = baseBody() + const first = await readSse(await kit.request(body1)) + assert.equal(first.stopReason, "tool_use") + await sleep(90) + + const body2 = continueWithToolResults(body1, first, () => "SLOW_DONE") + const second = await readSse(await kit.request(body2)) + assert.equal(second.stopReason, "tool_use") + + const [proc] = [...kit.module.__agyTestAllProcs] + const turn1 = proc.turn + const steeredBody = continueWithToolResults(body2, second, () => "STEP2_DONE") + steeredBody.messages.at(-1).content.push({ type: "text", text: "Steer after multi-prompt turn" }) + const third = await readSse(await kit.request(steeredBody)) + assert.equal(third.stopReason, "end_turn") + assert.equal(turn1.stepUsageReconciled, true, "多 prompt Turn 应按累计 usage 完成对账") + assert.equal(proc.stepUsageTrusted, true, "多 prompt Turn steer 后应继续保持 stepUsageTrusted") + assert.deepEqual(plain(third.usage), { + input_tokens: 410, + cache_read_input_tokens: 20_900, + cache_creation_input_tokens: 0, + output_tokens: 18, + output_tokens_details: { thinking_tokens: 3 }, + }) + }) + + // 子场景 5:若被取消回合在工具提交后已开始(被抑制的)正文生成,其生成步的 gen_metadata 行可能延后刷盘;即使当前 ACP usage 仍等于工具步读数也不得标记 stepUsageReconciled + await withKit({}, async (kit) => { + const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.exec("PRAGMA journal_mode = WAL") + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + db.run("INSERT INTO gen_metadata VALUES (0, ?)", genBlob({ input: 2400, read: 14_600, output: 35, thinking: 10 })) + } finally { + db.close() + } + agent.update({ sessionUpdate: "tool_call", toolCallId: "call_post_gen", name: "mcp_ide-tools_Read", status: "in_progress" }) + await agent.tool("Read", { path: "/post-gen.txt" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "call_post_gen", name: "mcp_ide-tools_Read", status: "completed" }) + await agent.text("POST_TOOL_GENERATION") + await agent.waitCancel() + return { + stopReason: "cancelled", + usage: { inputTokens: 2400, cachedReadTokens: 14_600, cachedWriteTokens: 0, outputTokens: 35, thoughtTokens: 10, totalTokens: 17_035 }, + } + }) + + kit.prompts.push(async (agent) => { + const dbFile = path.join(convDir, `${agent.sessionId}.db`) + const db = openSqlite(dbFile) + try { + db.run("INSERT INTO gen_metadata VALUES (1, ?)", genBlob({ input: 420, read: 15_000, output: 11 })) + } finally { + db.close() + } + await agent.text("after post-tool generation") + return { + stopReason: "end_turn", + usage: { inputTokens: 420, cachedReadTokens: 15_000, cachedWriteTokens: 0, outputTokens: 11, totalTokens: 15_420 }, + } + }) + + const body1 = baseBody() + const first = await readSse(await kit.request(body1)) + const [proc] = [...kit.module.__agyTestAllProcs] + const turn1 = proc.turn + const steeredBody = continueWithToolResults(body1, first, () => "OK") + steeredBody.messages.at(-1).content.push({ type: "text", text: "Steer after post-tool text started" }) + const second = await readSse(await kit.request(steeredBody)) + assert.equal(second.stopReason, "end_turn") + assert.equal(turn1.stepUsageReconciled, false, "已进入生成输出的取消回合不得标记 stepUsageReconciled") + assert.equal(proc.stepUsageTrusted, false, "已进入生成输出的取消回合必须关闭 stepUsageTrusted") + }) +})