diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index 71f767d..08991f9 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -3789,6 +3789,25 @@ function clipPartsToBytes(parts, limit) { return out } +// Claude Code's own user-role notes: reminders, context notices, local +// command output and interrupt markers. A user message of these alone is +// not the prompt that started a tool loop (#1055). +const LOCAL_COMMAND_RE = /<(local-command-caveat|local-command-stdout|local-command-stderr)>[\s\S]*?<\/\1>/g +function isMetaOnlyUserText(text) { + return !text.replace(SYSTEM_REMINDER_RE, "").replace(CONTEXT_NOTICE_RE, "").replace(LOCAL_COMMAND_RE, "") + .replace(/\[Request interrupted by user(?: for tool use)?\]/g, "") + .replace(/\[(?:SYSTEM NOTIFICATION|MESSAGE FROM NON-USER SOURCE) - NOT USER INPUT\]/g, "").trim() +} + +// A user message with no tool result and something the user wrote or attached. +function isUserTask(message) { + if (message.role !== "user") return false + if (typeof message.content === "string") return !isMetaOnlyUserText(message.content) + if (!Array.isArray(message.content) || message.content.some((block) => block?.type === "tool_result")) return false + return message.content.some((block) => block?.type === "image") || + !isMetaOnlyUserText(message.content.filter((block) => block?.type !== "image").map(blockText).join("\n")) +} + // `reserveBytes` is text the caller appends after . function renderInitialPromptParts(body, callerWorkDir, instructionsInSession, reserveBytes = 0) { const { history, messages: current } = trailingMessages(body) @@ -3818,12 +3837,17 @@ function renderInitialPromptParts(body, callerWorkDir, instructionsInSession, re headParts = clipPartsToBytes(headParts, Math.max(0, budget - frame - promptTextBytes(turn))) } let room = budget - frame - promptTextBytes(headParts) - promptTextBytes(turn) - const entries = history.map((message) => { - const parts = renderHistoryEntry(clipHistoryMessage(message)) + const render = (message) => { + const parts = renderHistoryEntry(message) return { parts, bytes: promptTextBytes(parts) } - }) + } + const overRoom = (list) => list.reduce((sum, entry) => sum + entry.bytes, 0) > room + // A replay that fits is sent whole; only one that does not has its big + // blocks clipped first (#1055). + let entries = history.map(render) + if (overRoom(entries)) entries = history.map((message) => render(clipHistoryMessage(message))) let kept = entries - if (entries.reduce((sum, entry) => sum + entry.bytes, 0) > room) { + if (overRoom(entries)) { // Keep the opening anchor message and the newest messages that still fit; // the early middle of the conversation gives way to one omission note. room -= utf8Bytes(HISTORY_OMITTED_NOTE) @@ -3834,9 +3858,7 @@ function renderInitialPromptParts(body, callerWorkDir, instructionsInSession, re let task = -1 if (current.some((message) => Array.isArray(message.content) && message.content.some((block) => block?.type === "tool_result"))) { - task = history.findLastIndex((message) => message.role === "user" && (typeof message.content === "string" - ? !!message.content.trim() - : Array.isArray(message.content) && !message.content.some((block) => block?.type === "tool_result"))) + task = history.findLastIndex(isUserTask) if (task <= 0 || entries[task].bytes + utf8Bytes(HISTORY_OMITTED_NOTE) > room) task = -1 else room -= entries[task].bytes + utf8Bytes(HISTORY_OMITTED_NOTE) } diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index f7010c5..cf275d6 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.26", + "version": "0.1.27", "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/repeat-batch.mjs b/packages/agy-cli/test/repeat-batch.mjs index f7eee6d..e7dfd30 100644 --- a/packages/agy-cli/test/repeat-batch.mjs +++ b/packages/agy-cli/test/repeat-batch.mjs @@ -447,6 +447,62 @@ test("A16: mid tool loop, a trimmed replay keeps the user prompt that started th }) }) +test("A16: a replay that fits the budget keeps every big history block whole (#1055)", async () => { + await withKit({}, async (kit) => { + scriptedAgent(kit) + // One 20 KiB tool result and one 20 KiB tool-call input: over the 12 KiB + // block clip, while the whole replay is far under 112 KiB. + const big = (label) => `${label} head ` + "file line with some words. ".repeat(380) + ` ${label} MIDDLE ` + + "file line with some words. ".repeat(380) + ` ${label} tail` + const messages = [ + { role: "user", content: "TOOL read and write it" }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_read", name: "Read", input: { path: "/repo/a.txt" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_read", content: big("result") }] }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_write", name: "Write", input: { path: "/repo/b.txt", content: big("input") } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_write", content: "written" }] }, + { role: "assistant", content: "done" }, + { role: "user", content: "LATEST: and now?" }, + ] + assert.ok(bytes(JSON.stringify(messages)) < 64 * 1024, "fixture must fit the budget") + await readSse(await kit.request(baseBody({ metadata: { user_id: "budget-fits" }, messages }))) + const prompt = prompts(kit).at(-1) + assert.ok(prompt.includes("result MIDDLE") && prompt.includes("input MIDDLE"), "big blocks are kept whole") + assert.ok(!prompt.includes("omitted"), "nothing is clipped or dropped") + assert.ok(!prompt.includes("truncated_arguments")) + }) +}) + +test("A16: mid tool loop, the pinned prompt is the user's task, not a Claude Code note after it (#1055)", async () => { + for (const meta of [ + "\nThe date has changed. Today's date is now 2026-11-13.\n", + [{ type: "text", text: "[Request interrupted by user for tool use]" }], + "Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages.\nSet model to gemini", + ]) { + await withKit({}, async (kit) => { + scriptedAgent(kit) + const big = (label) => `${label} head ` + "tool output line with some words. ".repeat(560) + ` ${label} tail` + const messages = [ + { role: "user", content: "ANCHOR opening request" }, + { role: "assistant", content: "ANCHOR reply" }, + { role: "user", content: [{ type: "text", text: "context" }, { type: "text", text: "TASK START: rename parseConfig to loadConfig everywhere" }] }, + ] + for (let index = 0; index < 16; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_step${index}`, name: "Read", input: { path: `/repo/${index}.txt` } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_step${index}`, content: big(`step-${index}`) }] }) + if (index === 3) messages.push({ role: "user", content: meta }) + } + messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_last", name: "Read", input: { path: "/repo/last.txt" } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_last", content: "LAST RESULT" }] }) + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "budget-task-meta" }, messages }))) + assert.equal(parsed.stopReason, "end_turn") + const prompt = prompts(kit).at(-1) + assert.ok(bytes(prompt) <= 112 * 1024, `initial prompt is ${bytes(prompt)} bytes`) + assert.ok(prompt.includes("TASK START: rename parseConfig to loadConfig everywhere"), `the loop's prompt is kept past ${JSON.stringify(meta).slice(0, 40)}`) + assert.ok(prompt.includes("step-15 tail") && prompt.includes("LAST RESULT"), "the newest steps are kept") + }) + } +}) + // ----------------------------------------------- agy's error marker (#1052) function markerAgent(kit, chunks) {