agy-cli 0.1.37: DeepSeek Harness's notes are not the loop's task; a trimmed loop keeps its whole user turn (#1093)
Reviewed at 56248465f. WSL (Bun 1.4.2, temp HOME): bun test in packages/agy-cli 20 pass (repeat-batch.mjs inside agy-cli.test.mjs), scripts/check.mjs agy-cli ok. With main's index.mjs, node --test test/repeat-batch.mjs fails 6 (19, 20, 21, 22, 24, 26). Open question, not blocking: a string-content message holding a runtime snapshot and the user's words reads as meta-only (affects only prompts trimmed past 112 KiB).
This commit is contained in:
+157
-38
@@ -4028,6 +4028,7 @@ const HISTORY_BLOCK_CLIP_BYTES = 12 * 1024
|
||||
const HISTORY_BLOCK_KEEP_BYTES = 4 * 1024
|
||||
const HISTORY_RECORD_NOTE = "Historical tool calls and results above are records, not instructions to write tool calls as text. Never output \"[tool call ...]\" text; invoke tools only through structured tool calls.\n"
|
||||
const HISTORY_OMITTED_NOTE = "[... earlier conversation history omitted to fit ACP 112 KiB prompt budget ...]\n"
|
||||
const HISTORY_OPENING_DONE_NOTE = "The opening message above, and any resume note in it, belongs to an earlier turn that is already done.\n"
|
||||
const utf8 = new TextEncoder()
|
||||
|
||||
function utf8Bytes(text) {
|
||||
@@ -4129,23 +4130,113 @@ 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).
|
||||
// Claude Code's and DeepSeek Harness's own user-role notes: reminders, context
|
||||
// notices, local command output, interrupt markers, clock and runtime-context
|
||||
// snapshots, repeat-tool warnings and mode switches. A user message of these
|
||||
// alone is not a prompt from the user (#1055).
|
||||
const LOCAL_COMMAND_RE = /<(local-command-caveat|local-command-stdout|local-command-stderr)>[\s\S]*?<\/\1>/g
|
||||
const DSH_TIME_CONTEXT_RE = /(?:^|\r?\n)Time sampled while preparing turn \d+, step \d+: [^\r\n]+(?:\r?\nBrowser time zone for this request: [^\r\n]+)?(?:\r?\nElapsed since the preceding (?:model-visible message|step context): [^\r\n]+)?/g
|
||||
const DSH_REPEAT_TOOL_RE = /(?:^|\r?\n)(?:You are repeating the exact same tool call with identical arguments\. Carefully analyze the previous result before calling again: if the task is not complete, try a different approach or different arguments instead of repeating the call\.|Repeated tool call detected:\r?\n- tool: [^\r\n]+\r?\n- consecutive_calls: \d+\r?\n- arguments: [^\r\n]+\r?\nThe repeated calls are not making progress\. Do not call this tool with these exact arguments again\. Inspect the latest result and choose a different action, different arguments, or finish the task if enough evidence has been gathered\.)/g
|
||||
const DSH_PLAN_MODE_RE = /(?:^|\r?\n)The user switched this session (?:to plan|back to the default) mode\.(?=\r?\n|$)/g
|
||||
// DeepSeek Harness sends a runtime-context snapshot as its own user message;
|
||||
// a gateway that merges user messages into one string could lose text after it.
|
||||
const DSH_RUNTIME_SNAPSHOT_RE = /^Current runtime context(?:\. This snapshot supersedes earlier runtime-context snapshots\.(?:\r?\n[\s\S]*)?|: none\. Earlier runtime-context snapshots no longer apply\.)$/
|
||||
|
||||
function isMetaOnlyUserText(text) {
|
||||
return !text.replace(SYSTEM_REMINDER_RE, "").replace(CONTEXT_NOTICE_RE, "").replace(LOCAL_COMMAND_RE, "")
|
||||
const rest = stripMagpiePlaceholderNotice(text)
|
||||
.replace(SYSTEM_REMINDER_RE, "")
|
||||
.replace(CONTEXT_NOTICE_RE, "")
|
||||
.replace(LOCAL_COMMAND_RE, "")
|
||||
.replace(DSH_TIME_CONTEXT_RE, "")
|
||||
.replace(DSH_REPEAT_TOOL_RE, "")
|
||||
.replace(DSH_PLAN_MODE_RE, "")
|
||||
.replace(/\[Request interrupted by user(?: for tool use)?\]/g, "")
|
||||
.replace(/\[(?:SYSTEM NOTIFICATION|MESSAGE FROM NON-USER SOURCE) - NOT USER INPUT\]/g, "").trim()
|
||||
.replace(/\[(?:SYSTEM NOTIFICATION|MESSAGE FROM NON-USER SOURCE) - NOT USER INPUT\]/g, "")
|
||||
.trim()
|
||||
return !rest || DSH_RUNTIME_SNAPSHOT_RE.test(rest)
|
||||
}
|
||||
|
||||
function isToolResultMessage(message) {
|
||||
return Array.isArray(message?.content) && message.content.some((block) => block?.type === "tool_result")
|
||||
}
|
||||
|
||||
// A user message with no tool result and something the user wrote or attached.
|
||||
function isUserTask(message) {
|
||||
if (message.role !== "user") return false
|
||||
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"))
|
||||
if (!Array.isArray(message.content) || isToolResultMessage(message)) return false
|
||||
if (message.content.some((block) => block?.type === "image")) return true
|
||||
return message.content.some((block) => !isMetaOnlyUserText(blockText(block)))
|
||||
}
|
||||
|
||||
// Index right after the last completed assistant reply (an assistant run with
|
||||
// no tool_use), or 0 when the conversation is still in its first turn.
|
||||
function lastCompletedTurnEnd(history) {
|
||||
for (let end = history.length; end > 0;) {
|
||||
if (history[end - 1].role !== "assistant") {
|
||||
end--
|
||||
continue
|
||||
}
|
||||
let start = end - 1
|
||||
while (start > 0 && history[start - 1].role === "assistant") start--
|
||||
const hasToolUse = history.slice(start, end).some((message) =>
|
||||
Array.isArray(message.content) && message.content.some((block) => block?.type === "tool_use"))
|
||||
if (!hasToolUse) return end
|
||||
end = start
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Bounds of the non-assistant, non-tool_result run around `index` when at
|
||||
// least one message in it is a user task; null when the run is meta-only.
|
||||
function userTurnRun(history, index) {
|
||||
if (index < 0 || index >= history.length) return null
|
||||
let start = index
|
||||
while (start > 0 && history[start - 1].role !== "assistant" && !isToolResultMessage(history[start - 1])) start--
|
||||
let end = index + 1
|
||||
while (end < history.length && history[end].role !== "assistant" && !isToolResultMessage(history[end])) end++
|
||||
const all = []
|
||||
const tasks = []
|
||||
const rest = []
|
||||
for (let i = start; i < end; i++) {
|
||||
if (i === 0) continue
|
||||
all.push(i)
|
||||
if (isUserTask(history[i])) tasks.push(i)
|
||||
else rest.push(i)
|
||||
}
|
||||
const hasTask = tasks.length > 0 || (start === 0 && end > 0 && isUserTask(history[0]))
|
||||
return hasTask ? { all, tasks, rest } : null
|
||||
}
|
||||
|
||||
// The user-turn run that opened the active tool loop, if any.
|
||||
function loopOpeningRun(history, loopStart) {
|
||||
for (let i = loopStart; i < history.length; i++) {
|
||||
if (history[i].role === "assistant" || isToolResultMessage(history[i])) break
|
||||
if (isUserTask(history[i])) return userTurnRun(history, i)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// The latest user-turn run at or after `loopStart`, never reaching back into
|
||||
// an earlier completed turn.
|
||||
function latestLoopTaskRun(history, loopStart) {
|
||||
for (let i = history.length - 1; i >= loopStart; i--) {
|
||||
if (isUserTask(history[i])) return userTurnRun(history, i)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Byte size of `indices` (sorted, unique) plus an omission note for each gap.
|
||||
function keptSliceBytes(indices, totalLength, entries, noteBytes) {
|
||||
let bytes = 0
|
||||
let next = 0
|
||||
for (const i of indices) {
|
||||
if (i > next) bytes += noteBytes
|
||||
bytes += entries[i].bytes
|
||||
next = i + 1
|
||||
}
|
||||
if (next < totalLength) bytes += noteBytes
|
||||
return bytes
|
||||
}
|
||||
|
||||
// `reserveBytes` is text the caller appends after </current_turn>.
|
||||
@@ -4187,43 +4278,71 @@ function renderInitialPromptParts(body, callerWorkDir, instructionsInSession, re
|
||||
let entries = history.map(render)
|
||||
if (overRoom(entries)) entries = history.map((message) => render(clipHistoryMessage(message)))
|
||||
let kept = entries
|
||||
let showOpeningDone = false
|
||||
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)
|
||||
const anchor = entries[0] && entries[0].bytes <= room ? entries[0] : null
|
||||
if (anchor) room -= anchor.bytes
|
||||
// Mid tool loop, the user's prompt that started it says what the loop is
|
||||
// for: it stays too, after the anchor, with a note for each gap (#1053).
|
||||
let task = -1
|
||||
if (current.some((message) => 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)
|
||||
const noteBytes = utf8Bytes(HISTORY_OMITTED_NOTE)
|
||||
const inToolLoop = current.some(isToolResultMessage)
|
||||
const loopStart = inToolLoop ? lastCompletedTurnEnd(history) : history.length
|
||||
const openingDoneBytes = utf8Bytes(HISTORY_OPENING_DONE_NOTE)
|
||||
let reservedOpeningDone = false
|
||||
if (room < noteBytes) {
|
||||
kept = []
|
||||
} else {
|
||||
if (inToolLoop && loopStart > 0 && room >= noteBytes + openingDoneBytes) {
|
||||
reservedOpeningDone = true
|
||||
room -= openingDoneBytes
|
||||
}
|
||||
// Keep the opening anchor message and the newest messages that still fit;
|
||||
// the early middle of the conversation gives way to omission notes.
|
||||
let keep = []
|
||||
if (entries.length && keptSliceBytes([0], entries.length, entries, noteBytes) <= room) {
|
||||
keep.push(0)
|
||||
}
|
||||
// Mid tool loop, the user's prompt run that started it says what the loop is
|
||||
// for (plus any later user steer run): keep it after the anchor, with a note
|
||||
// for each gap (#1053, #1055).
|
||||
if (inToolLoop) {
|
||||
const runs = [loopOpeningRun(history, loopStart), latestLoopTaskRun(history, loopStart)].filter(Boolean)
|
||||
const whole = [...new Set([...keep, ...runs.flatMap((run) => run.all)])].sort((a, b) => a - b)
|
||||
if (whole.length > keep.length && keptSliceBytes(whole, entries.length, entries, noteBytes) <= room) {
|
||||
keep = whole
|
||||
} else {
|
||||
const order = [...new Set([...runs.flatMap((run) => run.tasks), ...runs.flatMap((run) => run.rest)])]
|
||||
for (const idx of order) {
|
||||
if (keep.includes(idx)) continue
|
||||
const nextKeep = [...keep, idx].sort((a, b) => a - b)
|
||||
if (keptSliceBytes(nextKeep, entries.length, entries, noteBytes) <= room) keep = nextKeep
|
||||
}
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
const keptIndices = [...keep, ...tail]
|
||||
kept = []
|
||||
let next = 0
|
||||
for (const i of keptIndices) {
|
||||
if (i > next) kept.push(null)
|
||||
kept.push(entries[i])
|
||||
next = i + 1
|
||||
}
|
||||
if (next < entries.length) kept.push(null)
|
||||
showOpeningDone = reservedOpeningDone && keep.includes(0) && kept.includes(null) &&
|
||||
keptIndices.some((i) => i >= loopStart && isUserTask(history[i]))
|
||||
}
|
||||
const keep = [...(anchor ? [0] : []), ...(task > 0 ? [task] : [])]
|
||||
const tail = []
|
||||
for (let i = entries.length - 1; i > Math.max(task, anchor ? 0 : -1); i--) {
|
||||
if (entries[i].bytes > room) break
|
||||
room -= entries[i].bytes
|
||||
tail.unshift(i)
|
||||
}
|
||||
kept = []
|
||||
let next = 0
|
||||
for (const i of [...keep, ...tail]) {
|
||||
if (i > next) kept.push(null)
|
||||
kept.push(entries[i])
|
||||
next = i + 1
|
||||
}
|
||||
if (next < entries.length) kept.push(null)
|
||||
if (room < 0) kept = []
|
||||
}
|
||||
const out = []
|
||||
appendPrompt(out, headParts)
|
||||
if (history.length) {
|
||||
appendPrompt(out, historyOpen)
|
||||
for (const entry of kept) appendPrompt(out, entry ? entry.parts : HISTORY_OMITTED_NOTE)
|
||||
if (showOpeningDone) appendPrompt(out, HISTORY_OPENING_DONE_NOTE)
|
||||
appendPrompt(out, historyClose)
|
||||
}
|
||||
appendPrompt(out, turnOpen)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-agy-cli-auth",
|
||||
"version": "0.1.36",
|
||||
"version": "0.1.37",
|
||||
"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",
|
||||
|
||||
@@ -405,6 +405,7 @@ test("A16: a replay of more than 128 KiB of history stays within 112 KiB and kee
|
||||
assert.ok(prompt.includes("ANCHOR opening request"), "the anchor message is kept")
|
||||
assert.ok(prompt.includes("NEWEST assistant reply"), "the newest history is kept")
|
||||
assert.ok(prompt.includes("[... earlier conversation history omitted to fit ACP 112 KiB prompt budget ...]"))
|
||||
assert.ok(!prompt.includes("belongs to an earlier turn that is already done"), "non-loop replay adds no loop handoff note")
|
||||
assert.ok(prompt.includes("bytes of this history block omitted"), "oversized history blocks keep only head and tail")
|
||||
assert.ok(prompt.includes('Never output "[tool call ...]" text'))
|
||||
})
|
||||
@@ -518,7 +519,7 @@ test("A16: mid tool loop, the pinned prompt is the user's task, not a Claude Cod
|
||||
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 })
|
||||
if (index === 1) 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" }] })
|
||||
@@ -527,11 +528,264 @@ test("A16: mid tool loop, the pinned prompt is the user's task, not a Claude Cod
|
||||
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)}`)
|
||||
const noteText = typeof meta === "string" ? meta : meta[0].text
|
||||
assert.ok(!prompt.includes(noteText), "the note is not pinned as the loop's task")
|
||||
assert.ok(prompt.includes("step-15 tail") && prompt.includes("LAST RESULT"), "the newest steps are kept")
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test("A16: mid tool loop, DeepSeek Harness runtime metadata after a tool result does not displace the user's task", async () => {
|
||||
const metaSamples = [
|
||||
"Time sampled while preparing turn 19, step 1: 2026-11-13T15:24:33+08:00[Asia/Shanghai]\nBrowser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: 12m 17s.",
|
||||
"Time sampled while preparing turn 19, step 5: 2026-11-13T15:35:00+08:00[Asia/Shanghai]\nElapsed since the preceding step context: 10m 2s.",
|
||||
"Time sampled while preparing turn 1, step 1: 2026-11-13T08:00:00Z",
|
||||
"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\ncwd: /repo\nmode: default",
|
||||
"Current runtime context: none. Earlier runtime-context snapshots no longer apply.",
|
||||
"You are repeating the exact same tool call with identical arguments. Carefully analyze the previous result before calling again: if the task is not complete, try a different approach or different arguments instead of repeating the call.",
|
||||
"Repeated tool call detected:\n- tool: Read\n- consecutive_calls: 5\n- arguments: {\"path\":\"a\"}\nThe repeated calls are not making progress. Do not call this tool with these exact arguments again. Inspect the latest result and choose a different action, different arguments, or finish the task if enough evidence has been gathered.",
|
||||
"The user switched this session to plan mode.",
|
||||
"The user switched this session back to the default mode.",
|
||||
]
|
||||
const big = (label) => `${label} head ` + "tool output line with some words. ".repeat(560) + ` ${label} tail`
|
||||
for (const meta of metaSamples) {
|
||||
await withKit({}, async (kit) => {
|
||||
scriptedAgent(kit)
|
||||
const messages = [
|
||||
{ role: "user", content: "ANCHOR opening request" },
|
||||
{ role: "assistant", content: "ANCHOR reply" },
|
||||
{ role: "user", content: "TASK START: rename parseConfig to loadConfig everywhere" },
|
||||
]
|
||||
for (let index = 0; index < 16; index++) {
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_dsh_meta_${index}`, name: "Read", input: { path: `/repo/${index}.txt` } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_dsh_meta_${index}`, content: big(`step-${index}`) }] })
|
||||
if (index === 1) messages.push({ role: "user", content: meta })
|
||||
}
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_dsh_meta_last", name: "Read", input: { path: "/repo/last.txt" } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_dsh_meta_last", content: "LAST RESULT" }] })
|
||||
const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "dsh-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"), `kept past ${meta.slice(0, 40)}`)
|
||||
assert.ok(!prompt.includes(meta), "the note is not pinned as the loop's task")
|
||||
assert.ok(prompt.includes("LAST RESULT"))
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test("A16: mid tool loop with an opening handoff note and DeepSeek Harness companions keeps the whole user turn and marks the opening turn done", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
scriptedAgent(kit)
|
||||
const big = (label) => `${label} head ` + "tool output line with some words. ".repeat(560) + ` ${label} tail`
|
||||
const handoff = "[Handoff · part 5]\n" + "Morning summary line. ".repeat(700) +
|
||||
"\n## Progress\n### In progress\n- Earlier task: draft the release summary\n\nYou were in the middle of a turn. Go on with it now from where you stopped."
|
||||
const realPrompt = "REAL TASK: fix the race condition in the session router and summarize what changed"
|
||||
const skillCompanion = '<skill_content name="router">\n# Router conventions\nKeep existing exports.\n</skill_content>'
|
||||
const timeCompanion = "Time sampled while preparing turn 19, step 1: 2026-11-13T15:24:33+08:00[Asia/Shanghai]\nBrowser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: 12m 17s."
|
||||
const messages = [
|
||||
{ role: "user", content: handoff },
|
||||
{ role: "assistant", content: "Turn 1 reply: release summary drafted." },
|
||||
{ role: "user", content: "Follow-up question from midday" },
|
||||
{ role: "assistant", content: "Turn 2 reply: midday question answered." },
|
||||
{ role: "user", content: realPrompt },
|
||||
{ role: "user", content: skillCompanion },
|
||||
{ role: "user", content: timeCompanion },
|
||||
]
|
||||
const midLoopMeta = [
|
||||
"Time sampled while preparing turn 19, step 5: 2026-11-13T15:35:00+08:00[Asia/Shanghai]\nElapsed since the preceding step context: 10m 2s.",
|
||||
"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\ncwd: /repo",
|
||||
"The user switched this session back to the default mode.",
|
||||
"Repeated tool call detected:\n- tool: Read\n- consecutive_calls: 5\n- arguments: {\"path\":\"/repo/a.txt\"}\nThe repeated calls are not making progress. Do not call this tool with these exact arguments again. Inspect the latest result and choose a different action, different arguments, or finish the task if enough evidence has been gathered.",
|
||||
]
|
||||
for (let index = 0; index < 16; index++) {
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_dsh_${index}`, name: "Read", input: { path: `/repo/${index}.txt` } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_dsh_${index}`, content: big(`step-${index}`) }] })
|
||||
if (index < midLoopMeta.length) messages.push({ role: "user", content: midLoopMeta[index] })
|
||||
}
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_dsh_last", name: "Read", input: { path: "/repo/last.txt" } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_dsh_last", content: "LAST RESULT" }] })
|
||||
const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "dsh-handoff" }, 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("[Handoff · part 5]"), "opening anchor stays present")
|
||||
assert.ok(prompt.includes(`Human: ${realPrompt}`), "real Turn 19 user prompt stays pinned")
|
||||
assert.ok(prompt.includes("Router conventions"), "skill companion in the same turn stays attached")
|
||||
const between = prompt.slice(prompt.indexOf(realPrompt), prompt.indexOf("Router conventions"))
|
||||
assert.ok(!between.includes("omitted"), "no omission note is inserted inside a kept user turn")
|
||||
assert.ok(prompt.includes("The opening message above, and any resume note in it, belongs to an earlier turn that is already done."),
|
||||
"omitted history disambiguates prior handoff note from active loop")
|
||||
assert.ok(prompt.includes("LAST RESULT"), "current turn result stays intact")
|
||||
})
|
||||
})
|
||||
|
||||
test("A16: mid tool loop keeps a multi-message user turn whole without an omission marker inside it", async () => {
|
||||
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: "USER PART 1: inspect group handler" },
|
||||
{ role: "user", content: "Time sampled while preparing turn 2, step 1: 2026-11-13T15:24:33Z" },
|
||||
{ role: "user", content: "USER PART 2: fix the null check and report back" },
|
||||
]
|
||||
for (let index = 0; index < 16; index++) {
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_multi_${index}`, name: "Read", input: { path: `/repo/${index}.txt` } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_multi_${index}`, content: big(`multi-${index}`) }] })
|
||||
}
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_multi_last", name: "Read", input: { path: "/repo/last.txt" } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_multi_last", content: "LAST RESULT" }] })
|
||||
await readSse(await kit.request(baseBody({ metadata: { user_id: "multi-user" }, messages })))
|
||||
const prompt = prompts(kit).at(-1)
|
||||
assert.ok(bytes(prompt) <= 112 * 1024, `initial prompt is ${bytes(prompt)} bytes`)
|
||||
assert.ok(prompt.includes("Human: USER PART 1: inspect group handler"))
|
||||
assert.ok(prompt.includes("Human: USER PART 2: fix the null check and report back"))
|
||||
const between = prompt.slice(prompt.indexOf("USER PART 1"), prompt.indexOf("USER PART 2"))
|
||||
assert.ok(between.includes("Time sampled while preparing turn 2, step 1"))
|
||||
assert.ok(!between.includes("omitted"), "meta message between user parts leaves the run contiguous")
|
||||
})
|
||||
})
|
||||
|
||||
test("A16: mid tool loop keeps both the loop-opening prompt and a mid-loop user steer", async () => {
|
||||
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: "LOOP OPENER: refactor group router" },
|
||||
]
|
||||
for (let index = 0; index < 4; index++) {
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_steer_a_${index}`, name: "Read", input: { path: `/repo/a${index}.txt` } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_steer_a_${index}`, content: big(`sa-${index}`) }] })
|
||||
}
|
||||
messages.push({ role: "user", content: "MID LOOP STEER: keep backward-compatible exports" })
|
||||
messages.push({ role: "user", content: "Time sampled while preparing turn 2, step 5: 2026-11-13T15:35:00Z" })
|
||||
for (let index = 0; index < 14; index++) {
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_steer_b_${index}`, name: "Read", input: { path: `/repo/b${index}.txt` } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_steer_b_${index}`, content: big(`sb-${index}`) }] })
|
||||
}
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_steer_last", name: "Read", input: { path: "/repo/last.txt" } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_steer_last", content: "LAST RESULT" }] })
|
||||
await readSse(await kit.request(baseBody({ metadata: { user_id: "loop-steer" }, messages })))
|
||||
const prompt = prompts(kit).at(-1)
|
||||
assert.ok(bytes(prompt) <= 112 * 1024, `initial prompt is ${bytes(prompt)} bytes`)
|
||||
assert.ok(prompt.includes("Human: LOOP OPENER: refactor group router"), "loop opener is kept")
|
||||
assert.ok(prompt.includes("Human: MID LOOP STEER: keep backward-compatible exports"), "mid-loop steer is kept")
|
||||
assert.ok(prompt.indexOf("LOOP OPENER") < prompt.indexOf("MID LOOP STEER"))
|
||||
})
|
||||
})
|
||||
|
||||
test("A16: turn-1 oversized tool loop does not mark its own opening handoff as already done", async () => {
|
||||
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: "[Handoff · part 5]\nCarry on this task.\n\nYou were in the middle of a turn. Go on with it now from where you stopped.",
|
||||
},
|
||||
{ role: "user", content: "Time sampled while preparing turn 1, step 1: 2026-11-13T08:19:00Z" },
|
||||
]
|
||||
for (let index = 0; index < 16; index++) {
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_t1_${index}`, name: "Read", input: { path: `/repo/${index}.txt` } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_t1_${index}`, content: big(`t1-${index}`) }] })
|
||||
}
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_t1_last", name: "Read", input: { path: "/repo/last.txt" } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_t1_last", content: "LAST RESULT" }] })
|
||||
const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "turn1-handoff" }, 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("[Handoff · part 5]"), "opening handoff stays pinned")
|
||||
assert.ok(prompt.includes("LAST RESULT"), "current result stays present")
|
||||
assert.ok(!prompt.includes("already done"), "must not tell the model turn-1 opening handoff is already done")
|
||||
})
|
||||
})
|
||||
|
||||
test("A16: a tool loop opened by a meta-only notification neither pins a prior turn's prompt nor marks an active Human request", async () => {
|
||||
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: "OLD TASK 2 (already done)" },
|
||||
{ role: "assistant", content: "done 2" },
|
||||
{ role: "user", content: "<task-notification><status>completed</status><summary>worker finished</summary></task-notification>" },
|
||||
]
|
||||
for (let index = 0; index < 16; index++) {
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_meta_loop_${index}`, name: "Read", input: { path: `/repo/${index}.txt` } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_meta_loop_${index}`, content: big(`ml-${index}`) }] })
|
||||
}
|
||||
messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_meta_loop_last", name: "Read", input: { path: "/repo/last.txt" } }] })
|
||||
messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_meta_loop_last", content: "LAST RESULT" }] })
|
||||
const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "meta-opened-loop" }, 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("OLD TASK 2 (already done)"), "must not pin an already-completed earlier turn")
|
||||
assert.ok(!prompt.includes("belongs to an earlier turn that is already done"),
|
||||
"must not emit opening-done note when no active-loop user task is pinned")
|
||||
assert.ok(prompt.includes("LAST RESULT"))
|
||||
})
|
||||
})
|
||||
|
||||
test("A16: when a tight budget cannot fit the loop-opening prompt, the opening-done note is omitted", async () => {
|
||||
await withKit({ env: { AGY_BRIDGE_MAX_PROMPT_BYTES: String(8 * 1024) } }, async (kit) => {
|
||||
scriptedAgent(kit)
|
||||
const hugeOpener = "HUGE OPENER " + "x".repeat(8 * 1024)
|
||||
const messages = [
|
||||
{ role: "user", content: "ANCHOR opening request" },
|
||||
{ role: "assistant", content: "ANCHOR reply" },
|
||||
{ role: "user", content: hugeOpener },
|
||||
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_tight_0", name: "Read", input: { path: "/repo/0.txt" } }] },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_tight_0", content: "step 0 output" }] },
|
||||
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_tight_last", name: "Read", input: { path: "/repo/last.txt" } }] },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_tight_last", content: "y".repeat(4 * 1024) + " LAST RESULT" }] },
|
||||
]
|
||||
const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "tight-opener" }, messages })))
|
||||
assert.equal(parsed.stopReason, "end_turn")
|
||||
const prompt = prompts(kit).at(-1)
|
||||
assert.ok(bytes(prompt) <= 8 * 1024, `initial prompt is ${bytes(prompt)} bytes`)
|
||||
assert.ok(prompt.includes("ANCHOR opening request"), "anchor fits tight room")
|
||||
assert.ok(!prompt.includes("HUGE OPENER"), "oversized opener did not fit")
|
||||
assert.ok(!prompt.includes("belongs to an earlier turn that is already done"),
|
||||
"must not emit opening-done note when opener did not fit")
|
||||
assert.ok(prompt.includes("LAST RESULT"))
|
||||
})
|
||||
})
|
||||
|
||||
test("A16: under a tight budget, a mid-loop user steer beats an opening meta companion", async () => {
|
||||
await withKit({ env: { AGY_BRIDGE_MAX_PROMPT_BYTES: String(8 * 1024) } }, async (kit) => {
|
||||
scriptedAgent(kit)
|
||||
const bigReminder = "<system-reminder>" + "r".repeat(4200) + "</system-reminder>"
|
||||
const steer = "MID LOOP STEER: keep backward-compatible exports " + "s".repeat(900)
|
||||
const messages = [
|
||||
{ role: "user", content: "ANCHOR opening request" },
|
||||
{ role: "assistant", content: "ANCHOR reply" },
|
||||
{ role: "user", content: "LOOP OPENER: refactor group router" },
|
||||
{ role: "user", content: bigReminder },
|
||||
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_ts_0", name: "Read", input: { path: "/repo/0.txt" } }] },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_ts_0", content: "z".repeat(4000) }] },
|
||||
{ role: "user", content: steer },
|
||||
{ role: "user", content: "Time sampled while preparing turn 2, step 2: 2026-11-13T15:35:00Z" },
|
||||
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_ts_last", name: "Read", input: { path: "/repo/last.txt" } }] },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_ts_last", content: "y".repeat(3000) + " LAST RESULT" }] },
|
||||
]
|
||||
const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "tight-steer" }, messages })))
|
||||
assert.equal(parsed.stopReason, "end_turn")
|
||||
const prompt = prompts(kit).at(-1)
|
||||
assert.ok(bytes(prompt) <= 8 * 1024, `initial prompt is ${bytes(prompt)} bytes`)
|
||||
assert.ok(prompt.includes("Human: LOOP OPENER: refactor group router"), "loop opener is kept")
|
||||
assert.ok(prompt.includes("Human: MID LOOP STEER: keep backward-compatible exports"), "mid-loop steer beats opening reminder")
|
||||
assert.ok(!prompt.includes(bigReminder), "oversized opening reminder gave way to fit the steer")
|
||||
assert.ok(prompt.includes("LAST RESULT"))
|
||||
})
|
||||
})
|
||||
|
||||
// ----------------------------------------------- agy's error marker (#1052)
|
||||
|
||||
function markerAgent(kit, chunks) {
|
||||
|
||||
Reference in New Issue
Block a user