From 37df65a3f154432d7d9782b52ab70d7d72d67975 Mon Sep 17 00:00:00 2001 From: wjhauannn Date: Mon, 16 Nov 2026 14:14:49 +0800 Subject: [PATCH] agy-cli: a thinking+text assistant tail is accepted, the newest history turn outlasts an oversized first one, and a live drop logs its reason (#1202) wjhauannn's PR, reviewed at 3b85727243488a64d90f25a2f28f5cc5c3b9b471: - assistantTextOf skips thinking / redacted_thinking blocks, so a trailing assistant prefill carrying thinking + text is no longer a 400; thinking + tool_use is still refused. - renderInitialPromptParts: when an oversized history[0] leaves no room for any later entry, history[0] is clipped so the newest history turn before is kept (clipped to the room left if needed). - A live tool-turn drop logs a drop_live event with its reason (interrupted, image_result, history_mismatch, tools_grew, work_dir, instructions), and session_new records that reason, not no_live. Run at the reviewed head cherry-picked onto origin/main 3d9ac97f (agy-cli 0.1.74, #1051), HOME=$(mktemp -d), mote: packages/agy-cli bun test 36 pass 0 fail; test/repeat-batch.mjs 51 pass 0 fail; bun scripts/check.mjs agy-cli ok. Broken by hand (mica): origin/main's index.mjs with the PR's tests: the three new tests fail (A16 newest history turn, thinking+text tail, drop_live reason), 48 pass. The PR's version bump (0.1.74) is already on main; the release is the next commit's 0.1.75. --- packages/agy-cli/index.mjs | 78 ++++++++++++++++++--- packages/agy-cli/test/repeat-batch.mjs | 93 ++++++++++++++++++++++++++ 2 files changed, 161 insertions(+), 10 deletions(-) diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index fa220ca..300dad4 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -3247,7 +3247,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo const candidate = findLiveContinuedProc(opts) if (candidate && lockedKeys.has(candidate.convKey)) existing = rekeyProc(candidate, convKey) } - let why = "no_live" + let why = forceNew && opts.dropReason ? opts.dropReason : "no_live" let key = convKey if (existing && !existing.dead && existing.turn && isFreshConversation && !forceNew && !opts.hasToolResults && !existing.turn.cancelRequested && existing.turn.model !== opts.model) { @@ -4097,15 +4097,17 @@ 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". +// Concatenated text of an assistant message, skipping thinking metadata blocks, +// or null when the message carries tool/non-text blocks. 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 + if (!block) return null + if (block.type === "thinking" || block.type === "redacted_thinking") continue + if (block.type !== "text" || typeof block.text !== "string") return null text += block.text } return text @@ -4935,6 +4937,34 @@ function keptSliceBytes(indices, totalLength, entries, noteBytes) { return bytes } +function clipHistoryEntryParts(parts, limit) { + if (limit <= 0) return [] + const needNewline = parts.at(-1)?.type === "text" && parts.at(-1).text.endsWith("\n") + const textLimit = needNewline ? Math.max(0, limit - 1) : limit + const clipped = clipPartsToBytes(parts, textLimit) + if (needNewline) { + const last = clipped.at(-1) + if (last?.type === "text" && !last.text.endsWith("\n")) last.text += "\n" + } + return promptTextBytes(clipped) <= limit ? clipped : clipPartsToBytes(clipped, limit) +} + +function clipHistoryEntry(entry, limit) { + const parts = clipHistoryEntryParts(entry.parts, limit) + return { parts, bytes: promptTextBytes(parts) } +} + +function fillHistoryTail(entries, floor, left, noteBytes) { + const tail = [] + for (let i = entries.length - 1; i > floor; i--) { + const cost = entries[i].bytes - (i === floor + 1 ? noteBytes : 0) + if (cost > left) break + left -= cost + tail.unshift(i) + } + return { tail, left } +} + // `reserveBytes` is text the caller appends after . function renderInitialPromptParts(body, callerWorkDir, instructionsInSession, reserveBytes = 0) { const { history, messages: current } = trailingMessages(body) @@ -5012,13 +5042,27 @@ function renderInitialPromptParts(body, callerWorkDir, instructionsInSession, re } } let left = room - keptSliceBytes(keep, entries.length, entries, noteBytes) - const tail = [] const floor = keep.length ? keep.at(-1) : -1 - for (let i = entries.length - 1; i > floor; i--) { - const cost = entries[i].bytes - (i === floor + 1 ? noteBytes : 0) - if (cost > left) break - left -= cost - tail.unshift(i) + let { tail, left: remainingLeft } = fillHistoryTail(entries, floor, left, noteBytes) + const lastIdx = entries.length - 1 + if (lastIdx >= 0 && tail.length === 0 && !keep.includes(lastIdx)) { + // Never let an oversized history[0] squeeze out the newest turn before . + if (keep.length === 1 && keep[0] === 0 && lastIdx > 0 && room >= 4096 + noteBytes && + entries[0].bytes > Math.floor((room - noteBytes) / 2) && + remainingLeft < Math.min(entries[lastIdx].bytes, Math.floor((room - noteBytes) / 2))) { + const reservedLast = Math.min(entries[lastIdx].bytes, Math.floor((room - noteBytes) / 2)) + entries[0] = clipHistoryEntry(entries[0], Math.max(2048, room - noteBytes - reservedLast)) + left = room - keptSliceBytes(keep, entries.length, entries, noteBytes) + ;({ tail, left: remainingLeft } = fillHistoryTail(entries, floor, left, noteBytes)) + } + if (tail.length === 0 && !keep.includes(lastIdx)) { + const gapSaved = keep.length === 0 ? 0 : (lastIdx === floor + 1 ? noteBytes : 0) + const avail = remainingLeft + gapSaved + if (avail >= 512) { + entries[lastIdx] = clipHistoryEntry(entries[lastIdx], avail) + tail.unshift(lastIdx) + } + } } const keptIndices = [...keep, ...tail] kept = [] @@ -6561,6 +6605,20 @@ export const AntigravityBridgePlugin = async () => { // A changed context, a tool catalog that grew, or a // user-interrupted tool turn needs a new session. Replay the // real results without resolving the old process's calls. + const dropReason = interrupted ? "interrupted" + : imageResult ? "image_result" + : !historyMatches ? "history_mismatch" + : proc.toolsGrew(tools) ? "tools_grew" + : proc.workDir !== workDir ? "work_dir" + : "instructions" + logBridgeEvent(proc, turn, "drop_live", dropReason, acquireOpts, { + history: trailingMessages(body).history.length, + expected_history: Array.isArray(proc.expectedMessages) ? proc.expectedMessages.length : null, + tools_grew: !!proc.toolsGrew(tools), + work_dir_changed: proc.workDir !== workDir, + instructions_changed: !sameInstructions(proc.instructions, instructions), + }) + acquireOpts.dropReason = dropReason dropFromPool(proc) proc.abandonTurn(turn) await proc.stop() diff --git a/packages/agy-cli/test/repeat-batch.mjs b/packages/agy-cli/test/repeat-batch.mjs index 72eaf84..712e1c2 100644 --- a/packages/agy-cli/test/repeat-batch.mjs +++ b/packages/agy-cli/test/repeat-batch.mjs @@ -1197,6 +1197,99 @@ test("#1165: with agy's sign-in in a file under ~/.gemini (no keyring, Docker), }) }) +test("assistant tail with thinking+text blocks is accepted while thinking+tool_use is still rejected", async () => { + await withKit({}, async (kit) => { + scriptedAgent(kit) + const accepted = await kit.request(baseBody({ + metadata: { user_id: "thinking-tail-ok" }, + messages: [ + { role: "user", content: "summarize" }, + { role: "assistant", content: [ + { type: "thinking", thinking: "internal reasoning" }, + { type: "text", text: "partial reply" }, + ] }, + ], + })) + assert.equal(accepted.status, 200, await accepted.clone().text()) + const parsed = await readSse(accepted) + assert.equal(parsed.stopReason, "end_turn") + assert.ok(prompts(kit).at(-1).includes("partial reply")) + + const rejected = await errorOf(await kit.request(baseBody({ + metadata: { user_id: "thinking-tail-tool" }, + messages: [ + { role: "user", content: "read file" }, + { role: "assistant", content: [ + { type: "thinking", thinking: "need Read" }, + { type: "tool_use", id: "toolu_tail", name: "Read", input: { path: "/a" } }, + ] }, + ], + }))) + assert.equal(rejected.status, 400) + assert.match(rejected.body.error.message, /not from the user or a tool-result/) + }) +}) + +test("live tool-turn drop logs drop_live and carries exact reason into session_new", async () => { + const stderr = captureStderr() + try { + await withKit({}, async (kit) => { + scriptedAgent(kit) + const body1 = baseBody({ metadata: { user_id: "drop-reason" }, messages: [{ role: "user", content: "TOOL read" }] }) + const first = await readSse(await kit.request(body1)) + assert.equal(first.stopReason, "tool_use") + const call = first.content.find((block) => block.type === "tool_use") + const tampered = baseBody({ + metadata: { user_id: "drop-reason" }, + messages: [ + { role: "user", content: "ALTERED opening" }, + { role: "assistant", content: [call] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: call.id, content: "ok" }] }, + ], + }) + const second = await readSse(await kit.request(tampered)) + assert.equal(second.stopReason, "end_turn") + }) + } finally { + stderr.restore() + } + const drops = stderr.lines.filter((row) => row.action === "drop_live") + assert.equal(drops.length, 1) + assert.equal(drops[0].reason, "history_mismatch") + const sessionNews = stderr.lines.filter((row) => row.action === "session_new") + assert.equal(sessionNews.at(-1)?.reason, "history_mismatch") +}) + +test("A16: oversized history[0] cannot evict the newest history reply before ", async () => { + await withKit({ env: { AGY_BRIDGE_MAX_PROMPT_BYTES: String(16 * 1024) } }, async (kit) => { + scriptedAgent(kit) + const hugeOpening = Array.from({ length: 4 }, (_, i) => ({ + type: "text", + text: `ANCHOR-${i} ` + "a".repeat(3 * 1024), + })) + const messages = [{ role: "user", content: hugeOpening }] + for (let i = 0; i < 6; i++) { + messages.push({ role: "assistant", content: `mid reply ${i} ` + "m".repeat(512) }) + messages.push({ role: "user", content: `mid user ${i}` }) + } + messages.push({ + role: "assistant", + content: [ + { type: "text", text: "NEWEST HEAD " + "n".repeat(2 * 1024) }, + { type: "text", text: "t".repeat(4 * 1024) + " NEWEST TAIL" }, + ], + }) + messages.push({ role: "user", content: "CURRENT QUESTION" }) + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "anchor-vs-tail" }, messages }))) + assert.equal(parsed.stopReason, "end_turn") + const prompt = prompts(kit).at(-1) + assert.ok(bytes(prompt) <= 16 * 1024, `initial prompt is ${bytes(prompt)} bytes`) + assert.ok(prompt.includes("ANCHOR-0"), "opening anchor head is kept") + assert.ok(prompt.includes("NEWEST HEAD") && prompt.includes("NEWEST TAIL"), "newest history turn keeps head and tail") + assert.ok(prompt.includes("\nCURRENT QUESTION\n")) + }) +}) + test("#1165: a folder AGY_BRIDGE_GEMINI_DIR names is used even with a file sign-in", async () => { await withKit({ acpHelp: GEMINI_DIR_HELP }, async (kit) => { const named = path.join(kit.env.HOME, "named-agy")