agy-cli 0.1.16: keep conversationKey stable across volatile openings (#947)
conversationKey stays stable when only agent-injected opening fields change (Claude Code's billing header, known clock lines in the system prompt or a <system-reminder>), so a continued chat keeps its agy session and its prompt cache. It hashes the whole stripped first message. A flattened, growing first message reuses the live session only when it continues the whole previous opening plus that session's reply on a line boundary, and then sends agy only the new tail. Closes #945. Reviewed head 56c845720026819781e198bada948cce9b926806 (one commit on main 9204c07; main9e07c706has no agy-cli change since). Both points from the last review are fixed: - A reused flattened session no longer gets the opening again. A probe of four flattened turns with empty history (200 İ, ß, ffi, Dž, ς, 𝐀😀 in the opening, a reminder date that changes every turn, replies with thinking) ran in one fake agy session; prompts 2-4 were 28, 16 and 16 bytes and held only the new step. - The reminder scan folds only ASCII, so İ before a reminder no longer shifts indexes. An upper-case <SYSTEM-REMINDER> after İß keeps the key across a date change and reuses the session. Broken by hand, each went red: the old slice(history.length) prompt (5 red), toLowerCase() (2), no user-id check (1), join("") in systemText (1), compactIdentity in takeParked (1), no line-boundary check (2), findLiveContinuedProc returning null (6). Run at the head on main9e07c706: - Linux (WSL2 Ubuntu 24.04, Bun 1.4.2, temp HOME): bun test packages/agy-cli 11 pass, 0 fail; bun scripts/check.mjs exit 0. - Windows 11 (temp HOME and USERPROFILE): 10 pass, 1 fail; the one red is the smoke check "no call to the loaded tool reaches agy's validator in the old prompt", the only red at origin/main9e07c706too (9 pass, 1 fail), filed as #973. check.mjs exit 0 on both. - #971's loose matchesHistory/takeParked and 0.1.12's cache estimate are unchanged; compat, smoke and usage-settlement pass. Not blocking: if updateTools throws after a flattened reuse is picked, pendingFlattenedTurn stays on the process. After an agy error on a reused flattened turn, the same request again starts a new session with the full opening, as a fresh retry does on main. Not tried: a real agy or a real flattening client.
This commit is contained in:
@@ -22,6 +22,7 @@ for (const [name, mocks] of [
|
||||
["catalog.mjs", false],
|
||||
["usage-settlement.mjs", false],
|
||||
["repeat-batch.mjs", false],
|
||||
["conversation-key.mjs", false],
|
||||
]) {
|
||||
test(`test/${name}`, () => {
|
||||
const { code, output } = run(["test", ...(mocks ? ["--preload", hook] : []), `./${name}`], 240_000)
|
||||
|
||||
+391
-13
@@ -1081,6 +1081,9 @@ class Proc {
|
||||
this.toolsSignature = JSON.stringify(opts.tools)
|
||||
this.workDir = opts.workDir
|
||||
this.instructions = opts.instructions || ""
|
||||
this.userId = opts.userId || ""
|
||||
this.openingText = openingTextOf(opts.messages?.[0])
|
||||
this.openingImages = openingImagesOf(opts.messages?.[0])
|
||||
this.resumeFrom = opts.resume || null
|
||||
this.token = randomUUID()
|
||||
this.sessionId = null
|
||||
@@ -2059,7 +2062,7 @@ function park(proc) {
|
||||
historyHash: digest(historyKey(proc.expectedMessages)),
|
||||
historyHashSansInputs: digest(historyKey(stripToolUseInputs(proc.expectedMessages))),
|
||||
toolUseIdentitiesHash: digest(toolUseIdentitiesKey(proc.expectedMessages) ?? ""),
|
||||
instructionsHash: digest(compactIdentity(proc.instructions)),
|
||||
instructionsHash: digest(instructionsIdentity(proc.instructions)),
|
||||
workDir: proc.workDir,
|
||||
at: Date.now(),
|
||||
})
|
||||
@@ -2075,7 +2078,7 @@ function takeParked(convKey, opts) {
|
||||
unparked.add(convKey)
|
||||
saveParked()
|
||||
if (Date.now() - entry.at > RESUME_TTL_MS || (entry.workDir ?? null) !== (opts.workDir ?? null) ||
|
||||
entry.instructionsHash !== digest(compactIdentity(opts.instructions))) return null
|
||||
entry.instructionsHash !== digest(instructionsIdentity(opts.instructions))) return null
|
||||
const incoming = digest(historyKey(opts.history))
|
||||
if (entry.historyHash === incoming) return { sessionId: entry.sessionId, expectedMessages: opts.history }
|
||||
// Sans-inputs resume needs the hashes written by current park(). Old
|
||||
@@ -2165,12 +2168,41 @@ async function withAcquireLock(key, fn) {
|
||||
}
|
||||
}
|
||||
|
||||
async function withAcquireLocks(keys, fn) {
|
||||
const unique = [...new Set(keys.filter(Boolean))].sort()
|
||||
const run = (index) => {
|
||||
if (index >= unique.length) return fn()
|
||||
return withAcquireLock(unique[index], () => run(index + 1))
|
||||
}
|
||||
return run(0)
|
||||
}
|
||||
|
||||
async function acquireProc(agyPath, convKey, opts, isFreshConversation, forceNew = false) {
|
||||
return withAcquireLock(convKey, () => acquireProcLocked(agyPath, convKey, opts, isFreshConversation, forceNew))
|
||||
// Discover a live continued session's current key, lock it together with
|
||||
// the new key (sorted, to avoid deadlock), then pick again inside those
|
||||
// locks. A process is re-keyed only when its current key is already held.
|
||||
let extra = null
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const keys = extra && extra !== convKey ? [convKey, extra] : [convKey]
|
||||
const outcome = await withAcquireLocks(keys, async () => {
|
||||
const locked = new Set(keys)
|
||||
if (isFreshConversation && !forceNew && !pool.get(convKey)) {
|
||||
const candidate = findLiveContinuedProc(opts)
|
||||
const needed = candidate?.convKey
|
||||
if (needed && !locked.has(needed) && attempt < 2) return { retry: needed }
|
||||
}
|
||||
return { value: await acquireProcLocked(agyPath, convKey, opts, isFreshConversation, forceNew, locked) }
|
||||
})
|
||||
if (outcome.retry) {
|
||||
extra = outcome.retry
|
||||
continue
|
||||
}
|
||||
return outcome.value
|
||||
}
|
||||
}
|
||||
|
||||
// Caller holds the conversation lock; recovery must not acquire it recursively.
|
||||
async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, forceNew = false) {
|
||||
async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, forceNew = false, lockedKeys = new Set([convKey])) {
|
||||
await evictIdle()
|
||||
let existing = pool.get(convKey)
|
||||
if (existing?.turn?.cancelRequested) {
|
||||
@@ -2195,6 +2227,13 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo
|
||||
throw new ConflictError("agy bridge: this request carries the pending tool call but no matching result. Stop resending it; send the tool result or continue from the last self-consistent message.", "tool_state_conflict")
|
||||
}
|
||||
}
|
||||
// A flattened, growing first message changes conversationKey, so the live
|
||||
// session is under the previous key. Reuse it when the new opening continues
|
||||
// the whole previous opening (not just a shared prefix).
|
||||
if (!existing && !forceNew && isFreshConversation) {
|
||||
const candidate = findLiveContinuedProc(opts)
|
||||
if (candidate && lockedKeys.has(candidate.convKey)) existing = rekeyProc(candidate, convKey)
|
||||
}
|
||||
if (existing) {
|
||||
if (!existing.dead && existing.turn) {
|
||||
throw new BusyError("agy bridge: this conversation still has an unfinished response")
|
||||
@@ -2208,10 +2247,19 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo
|
||||
matchedHistory = opts.messages.slice(0, k)
|
||||
}
|
||||
}
|
||||
const continuedFresh = isFreshConversation && existing.hasSentFirstTurn &&
|
||||
isContinuedOpening(existing, Array.isArray(opts.messages) ? opts.messages[0] : null)
|
||||
const compatible = !forceNew && !existing.dead && !existing.retiring &&
|
||||
existing.workDir === opts.workDir && sameInstructions(existing.instructions, opts.instructions) &&
|
||||
existing.matchesHistory(matchedHistory)
|
||||
if (compatible && !(isFreshConversation && existing.hasSentFirstTurn)) {
|
||||
(existing.matchesHistory(matchedHistory) || continuedFresh)
|
||||
if (compatible && (!(isFreshConversation && existing.hasSentFirstTurn) || continuedFresh)) {
|
||||
if (continuedFresh) {
|
||||
const first = Array.isArray(opts.messages) ? opts.messages[0] : null
|
||||
// Snapshot the unsent tail before openingText advances to this turn.
|
||||
existing.pendingFlattenedTurn = flattenedContinuationMessage(existing, first)
|
||||
existing.openingText = openingTextOf(first) || existing.openingText
|
||||
existing.openingImages = openingImagesOf(first)
|
||||
}
|
||||
await existing.updateTools(opts.tools)
|
||||
return { proc: existing, history: matchedHistory }
|
||||
}
|
||||
@@ -2555,6 +2603,328 @@ function sameToolUseIdentities(left, right) {
|
||||
|
||||
// Compare conversation content, not transport metadata or client-assigned IDs.
|
||||
// Keep argument values, result contents and internal whitespace significant.
|
||||
|
||||
// Agent-injected Claude Code billing headers. Only whole header lines (and
|
||||
// a line that is just the rotating cch token) are removed, so user text that
|
||||
// happens to mention "cch=…" or the header name is left alone.
|
||||
function stripBillingHeader(text) {
|
||||
let s = String(text ?? "")
|
||||
s = s.replace(/^[ \t]*x-anthropic-billing-header:[^\n]*\n?/gmi, "")
|
||||
s = s.replace(/^[ \t]*cch=[0-9a-fA-F]+;?[ \t]*\n?/gmi, "")
|
||||
return s
|
||||
}
|
||||
|
||||
const ISO_DATE = String.raw`20\d{2}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2})?(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?`
|
||||
const LOCALE_DATE = String.raw`(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*,?\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2},?\s+\d{4}(?:\s+\d{2}:\d{2}(?::\d{2})?)?`
|
||||
const CLOCK_VALUE = String.raw`(?:${ISO_DATE}|${LOCALE_DATE}|\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AaPp][Mm])?)`
|
||||
const AGENT_CLOCK_LINE_RE = new RegExp(
|
||||
String.raw`^(?:#{1,6}\s*)?(?:(?:(?:current\s+)?(?:date|time|datetime|today|now)|today(?:'s)?\s+date|(?:the\s+)?current\s+(?:date|time|datetime))\s*[::]\s*${CLOCK_VALUE}|(?:(?:the\s+)?current\s+(?:date|time|datetime)|today(?:'s)?\s+date)\s+is\s+${CLOCK_VALUE})\s*\.?$`,
|
||||
"i",
|
||||
)
|
||||
|
||||
function isAgentClockLine(line) {
|
||||
return AGENT_CLOCK_LINE_RE.test(String(line ?? "").trim())
|
||||
}
|
||||
|
||||
function stripAgentClockLines(text) {
|
||||
const s = String(text ?? "")
|
||||
if (!s) return s
|
||||
return s.split(/(\n)/).map((part) => (part === "\n" || !isAgentClockLine(part) ? part : "")).join("")
|
||||
}
|
||||
|
||||
// System prompt and session instructions: billing headers plus known agent
|
||||
// clock lines. User text is never passed through this helper.
|
||||
function stripVolatileSystem(text) {
|
||||
return stripAgentClockLines(stripBillingHeader(text))
|
||||
}
|
||||
|
||||
function instructionsIdentity(text) {
|
||||
return compactIdentity(stripVolatileSystem(text))
|
||||
}
|
||||
|
||||
// Message text used for conversation/history identity: billing header lines,
|
||||
// and clock lines only inside <system-reminder> blocks (Claude Code injects
|
||||
// these on later turns too, so a mid-chat clock change must not rewrite the
|
||||
// history). Ordinary user/assistant text is left alone, including lines that
|
||||
// start with "Today:" or contain a date.
|
||||
// Walk closed <system-reminder>…</system-reminder> blocks with indexOf so an
|
||||
// unclosed opener does not rescan the rest of the string from every match
|
||||
// (the previous /[\s\S]*?/ regex was quadratic in the number of open tags).
|
||||
// Length-preserving ASCII fold. s.toLowerCase() maps İ (U+0130) to two
|
||||
// code units ("i" + combining dot), which would shift later indexes.
|
||||
function asciiLower(s) {
|
||||
return String(s ?? "").replace(/[A-Z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 32))
|
||||
}
|
||||
|
||||
function replaceClosedSystemReminders(text, replacer) {
|
||||
const s = String(text ?? "")
|
||||
if (!s) return s
|
||||
const open = "<system-reminder"
|
||||
const close = "</system-reminder>"
|
||||
const lower = asciiLower(s)
|
||||
let out = ""
|
||||
let i = 0
|
||||
while (i < s.length) {
|
||||
const start = lower.indexOf(open, i)
|
||||
if (start === -1) {
|
||||
out += s.slice(i)
|
||||
break
|
||||
}
|
||||
const afterName = start + open.length
|
||||
if (afterName < s.length && /[A-Za-z0-9_]/.test(s[afterName])) {
|
||||
out += s.slice(i, afterName)
|
||||
i = afterName
|
||||
continue
|
||||
}
|
||||
const gt = s.indexOf(">", afterName)
|
||||
if (gt === -1) {
|
||||
out += s.slice(i)
|
||||
break
|
||||
}
|
||||
const closeAt = lower.indexOf(close, gt + 1)
|
||||
if (closeAt === -1) {
|
||||
// No closer after this tag means none exists later either; keep the rest
|
||||
// verbatim so later openers do not rescan the same suffix.
|
||||
out += s.slice(i)
|
||||
break
|
||||
}
|
||||
const end = closeAt + close.length
|
||||
out += s.slice(i, start) + replacer(s.slice(start, end))
|
||||
i = end
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function stripVolatileOpening(text) {
|
||||
return replaceClosedSystemReminders(stripBillingHeader(text), (block) => stripAgentClockLines(block))
|
||||
}
|
||||
|
||||
function openingTextOf(message) {
|
||||
if (!message) return ""
|
||||
return compactIdentity(stripVolatileOpening(contentText(message.content)))
|
||||
}
|
||||
|
||||
function openingImagesOf(message) {
|
||||
const content = message?.content
|
||||
if (!Array.isArray(content)) return []
|
||||
const out = []
|
||||
for (const block of content) {
|
||||
if (block?.type !== "image") continue
|
||||
try {
|
||||
const image = parseUserImage(block)
|
||||
if (image) out.push(`${image.mimeType}:${digest(image.data)}`)
|
||||
} catch {
|
||||
const source = block.source || {}
|
||||
out.push(`invalid:${source.media_type || ""}:${digest(String(source.data || ""))}`)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function sameOpeningImagePrefix(prev, cur) {
|
||||
if (!Array.isArray(prev) || !Array.isArray(cur) || prev.length > cur.length) return false
|
||||
return prev.every((id, index) => id === cur[index])
|
||||
}
|
||||
|
||||
// Non-text, non-image blocks on an opening (documents, search results, etc.).
|
||||
function openingExtrasOf(message) {
|
||||
const content = message?.content
|
||||
if (!Array.isArray(content)) return []
|
||||
const out = []
|
||||
for (const block of content) {
|
||||
if (!block || typeof block === "string" || block.type === "text" || block.type === "image") continue
|
||||
out.push(digest(stableJSON(block)))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function sameOpeningExtraPrefix(prev, cur) {
|
||||
return sameOpeningImagePrefix(prev, cur)
|
||||
}
|
||||
|
||||
// Advance through `text` while ignoring whitespace until `compactPrefix` is
|
||||
// consumed. Returns the index of the first non-space after the prefix, and
|
||||
// whether a newline (a turn boundary) sits between the prefix and the rest.
|
||||
function consumeCompactPrefix(text, compactPrefix) {
|
||||
let i = 0
|
||||
let k = 0
|
||||
let lastWasNewline = true
|
||||
while (i < text.length && k < compactPrefix.length) {
|
||||
const ch = text[i]
|
||||
if (/\s/.test(ch)) {
|
||||
if (ch === "\n" || ch === "\r") lastWasNewline = true
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if (ch !== compactPrefix[k]) return null
|
||||
k++
|
||||
i++
|
||||
lastWasNewline = false
|
||||
}
|
||||
if (k < compactPrefix.length) return null
|
||||
let sawNewline = lastWasNewline
|
||||
let j = i
|
||||
while (j < text.length && (text[j] === " " || text[j] === "\t")) j++
|
||||
if (j < text.length && (text[j] === "\n" || text[j] === "\r")) {
|
||||
sawNewline = true
|
||||
while (j < text.length && /\s/.test(text[j])) j++
|
||||
}
|
||||
return { remainderIndex: j, boundary: sawNewline }
|
||||
}
|
||||
|
||||
function subsequentTranscriptOf(proc) {
|
||||
const messages = proc?.expectedMessages
|
||||
if (!Array.isArray(messages) || messages.length < 2) return ""
|
||||
const parts = []
|
||||
for (const message of messages.slice(1)) {
|
||||
if (!message) continue
|
||||
if (message.role === "assistant") {
|
||||
const text = assistantTextOf(message)
|
||||
if (typeof text === "string" && text.trim()) {
|
||||
parts.push(text)
|
||||
continue
|
||||
}
|
||||
const blocks = Array.isArray(message.content) ? message.content : []
|
||||
for (const block of blocks) {
|
||||
if (!block) continue
|
||||
if (block.type === "text" && typeof block.text === "string" && block.text.trim()) parts.push(block.text)
|
||||
else if (block.type === "tool_use") parts.push(`${block.name || ""}:${stableJSON(block.input ?? {})}`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
const text = contentText(message.content)
|
||||
if (text.trim()) parts.push(text)
|
||||
}
|
||||
return compactIdentity(parts.join("\n"))
|
||||
}
|
||||
|
||||
const FLAT_ROLE_LABEL_RE = /^(?:assistant|user|system|human|model)\s*:\s*/i
|
||||
|
||||
// Leftover text after an optional role label and the subsequent transcript,
|
||||
// or null if the remainder does not start with that transcript. The reply
|
||||
// must end on a line boundary (or the end of the string) so a longer
|
||||
// independent line that only starts with the reply is rejected, including
|
||||
// replies of 12 characters or more — length is not a substitute for a
|
||||
// turn boundary.
|
||||
function leftoverAfterSubsequent(remainder, subsequentCompact) {
|
||||
if (!subsequentCompact) return null
|
||||
let text = remainder
|
||||
if (FLAT_ROLE_LABEL_RE.test(text)) text = text.replace(FLAT_ROLE_LABEL_RE, "")
|
||||
if (!compactIdentity(text).startsWith(subsequentCompact)) return null
|
||||
const consumed = consumeCompactPrefix(text, subsequentCompact)
|
||||
if (!consumed) return null
|
||||
if (!consumed.boundary && consumed.remainderIndex < text.length) return null
|
||||
return text.slice(consumed.remainderIndex)
|
||||
}
|
||||
|
||||
function remainderHasSubsequent(remainder, subsequentCompact) {
|
||||
return leftoverAfterSubsequent(remainder, subsequentCompact) != null
|
||||
}
|
||||
|
||||
// The unsent tail of a flattened, growing first message: everything after
|
||||
// the previous opening and the live session's subsequent transcript (usually
|
||||
// the last assistant reply). Images and extra blocks already sent with the
|
||||
// previous opening are dropped; any new images, documents or search results
|
||||
// are kept. If the previous extras are not a prefix of the new ones, reuse
|
||||
// is refused rather than dropping content.
|
||||
function flattenedContinuationMessage(proc, firstMessage) {
|
||||
const prev = proc?.openingText || ""
|
||||
const cur = openingTextOf(firstMessage)
|
||||
if (!prev || !cur || cur === prev) return null
|
||||
// The new opening must continue the whole previous opening, not just a
|
||||
// shared prefix. A shared 8 KiB head with a different tail is a different chat.
|
||||
if (!(cur.startsWith(prev) && cur.length > prev.length + 4)) return null
|
||||
const prevOpening = Array.isArray(proc.expectedMessages) ? proc.expectedMessages[0] : null
|
||||
const prevImages = proc.openingImages || openingImagesOf(prevOpening)
|
||||
const curImages = openingImagesOf(firstMessage)
|
||||
if (!sameOpeningImagePrefix(prevImages, curImages)) return null
|
||||
const prevExtras = openingExtrasOf(prevOpening)
|
||||
const curExtras = openingExtrasOf(firstMessage)
|
||||
if (!sameOpeningExtraPrefix(prevExtras, curExtras)) return null
|
||||
// "Review README" must not attach "Review README and tests". Flattened
|
||||
// history appends later turns after a newline, and those turns are still
|
||||
// sitting on the live process, so require both a turn boundary and the
|
||||
// subsequent transcript (the assistant reply, not just a longer prompt).
|
||||
const curRaw = stripVolatileOpening(contentText(firstMessage?.content))
|
||||
const consumed = consumeCompactPrefix(curRaw, prev)
|
||||
if (!consumed?.boundary) return null
|
||||
const subsequent = subsequentTranscriptOf(proc)
|
||||
if (!subsequent) return null
|
||||
const leftover = leftoverAfterSubsequent(curRaw.slice(consumed.remainderIndex), subsequent)
|
||||
if (leftover == null) return null
|
||||
const newText = leftover.replace(/^\s+/, "")
|
||||
const keptBlocks = []
|
||||
if (Array.isArray(firstMessage?.content)) {
|
||||
let skippedImages = 0
|
||||
let skippedExtras = 0
|
||||
const skipImg = prevImages?.length || 0
|
||||
const skipEx = prevExtras?.length || 0
|
||||
for (const block of firstMessage.content) {
|
||||
if (!block || typeof block === "string" || block.type === "text") continue
|
||||
if (block.type === "image") {
|
||||
if (skippedImages < skipImg) {
|
||||
skippedImages++
|
||||
continue
|
||||
}
|
||||
keptBlocks.push(block)
|
||||
continue
|
||||
}
|
||||
if (skippedExtras < skipEx) {
|
||||
skippedExtras++
|
||||
continue
|
||||
}
|
||||
keptBlocks.push(block)
|
||||
}
|
||||
}
|
||||
if (!newText && !keptBlocks.length) return null
|
||||
if (!keptBlocks.length) return { role: "user", content: newText }
|
||||
const content = []
|
||||
if (newText) content.push({ type: "text", text: newText })
|
||||
content.push(...keptBlocks)
|
||||
return { role: "user", content }
|
||||
}
|
||||
|
||||
function isContinuedOpening(proc, firstMessage) {
|
||||
return flattenedContinuationMessage(proc, firstMessage) != null
|
||||
}
|
||||
|
||||
function findLiveContinuedProc(opts) {
|
||||
const first = Array.isArray(opts?.messages) ? opts.messages[0] : null
|
||||
if (!first) return null
|
||||
const userId = opts.userId || ""
|
||||
let best = null
|
||||
let bestLen = -1
|
||||
let tied = false
|
||||
for (const proc of pool.values()) {
|
||||
if (proc.dead || proc.retiring || proc.turn) continue
|
||||
if ((proc.userId || "") !== userId) continue
|
||||
if (proc.workDir !== opts.workDir) continue
|
||||
if (!sameInstructions(proc.instructions, opts.instructions)) continue
|
||||
if (!proc.hasSentFirstTurn) continue
|
||||
if (!isContinuedOpening(proc, first)) continue
|
||||
const len = (proc.openingText || "").length
|
||||
if (!best || len > bestLen) {
|
||||
best = proc
|
||||
bestLen = len
|
||||
tied = false
|
||||
} else if (len === bestLen) {
|
||||
tied = true
|
||||
}
|
||||
}
|
||||
return tied ? null : best
|
||||
}
|
||||
|
||||
function rekeyProc(proc, newKey) {
|
||||
if (!proc || proc.convKey === newKey) return proc
|
||||
const oldKey = proc.convKey
|
||||
dropFromPool(proc)
|
||||
unpark(oldKey)
|
||||
proc.convKey = newKey
|
||||
pool.set(newKey, proc)
|
||||
return proc
|
||||
}
|
||||
|
||||
|
||||
function historyKey(messages) {
|
||||
const rows = []
|
||||
const ids = new Map()
|
||||
@@ -2566,7 +2936,7 @@ function historyKey(messages) {
|
||||
block.type === "tool_addition" || block.type === "tool_removal") continue
|
||||
let value
|
||||
if (typeof block === "string" || block.type === "text") {
|
||||
value = { type: "text", text: stripMagpiePlaceholderNotice(typeof block === "string" ? block : block.text || "") }
|
||||
value = { type: "text", text: stripVolatileOpening(stripMagpiePlaceholderNotice(typeof block === "string" ? block : block.text || "")) }
|
||||
} else if (block.type === "document") {
|
||||
value = { type: "text", text: parseUserDocumentText(block) }
|
||||
} else if (block.type === "search_result") {
|
||||
@@ -2696,7 +3066,7 @@ function matchToolResults(body, blocks) {
|
||||
|
||||
function systemText(body) {
|
||||
if (!body.system) return ""
|
||||
return typeof body.system === "string" ? body.system : body.system.map((block) => block.text || "").join("")
|
||||
return typeof body.system === "string" ? body.system : body.system.map((block) => block.text || "").join("\n")
|
||||
}
|
||||
|
||||
function contentText(content) {
|
||||
@@ -2742,20 +3112,24 @@ function compactIdentity(text) {
|
||||
}
|
||||
|
||||
function sameInstructions(a, b) {
|
||||
return compactIdentity(a) === compactIdentity(b)
|
||||
return instructionsIdentity(a) === instructionsIdentity(b)
|
||||
}
|
||||
|
||||
// The model is not part of the key: agy switches models inside a live session.
|
||||
function conversationKey(rawBody) {
|
||||
const body = canonicalBody(rawBody)
|
||||
const system = historyKey([{ role: "system", content: compactIdentity(systemText(body)) }])
|
||||
const system = historyKey([{ role: "system", content: compactIdentity(stripVolatileSystem(systemText(body))) }])
|
||||
const first = body.messages?.[0]
|
||||
// Hash the whole stripped first message, including non-text blocks such as
|
||||
// images. A shared 8 KiB text prefix must not put two chats in one session.
|
||||
// Later assistant/user turns are not part of this hash, so attaching history
|
||||
// does not change the key. Agent billing headers and opening reminder clocks
|
||||
// are stripped; user text is not.
|
||||
const firstText = first ? historyKey([first]) : ""
|
||||
const discriminator = body.metadata?.user_id || ""
|
||||
const source = discriminator + "\n" + system + "\n===\n" + firstText
|
||||
return createHash("sha256").update(source).digest("hex")
|
||||
}
|
||||
|
||||
function appendSchemaHint(node, hint) {
|
||||
if (!hint) return
|
||||
if (typeof node.description === "string" && node.description.trim()) {
|
||||
@@ -4267,8 +4641,12 @@ function streamResponse(proc, turn, body, signal) {
|
||||
|
||||
async function beginTurn(proc, history, body, callerWorkDir, model, selection) {
|
||||
const reminder = outputFormatReminder(body)
|
||||
const flattened = proc.pendingFlattenedTurn
|
||||
proc.pendingFlattenedTurn = null
|
||||
const baseParts = proc.hasSentFirstTurn
|
||||
? renderContinuedTurnParts(body.messages.slice(history.length))
|
||||
? renderContinuedTurnParts(flattened
|
||||
? [flattened, ...body.messages.slice(1)]
|
||||
: body.messages.slice(history.length))
|
||||
: renderInitialPromptParts(body, callerWorkDir, proc.instructionsInSession,
|
||||
reminder.length ? promptTextBytes(reminder) + 2 : 0)
|
||||
const contentParts = mergePromptParts(baseParts, reminder)
|
||||
@@ -4404,7 +4782,7 @@ export const AntigravityBridgePlugin = async () => {
|
||||
}
|
||||
const acquireOpts = { model, selection, tools, workDir, instructions, history: trailing.history,
|
||||
messages: body.messages, layout, nonstream: body.stream === false, reqId, convKey,
|
||||
hasToolResults: resultBlocks.length > 0 }
|
||||
hasToolResults: resultBlocks.length > 0, userId: body.metadata?.user_id || "" }
|
||||
const begin = (proc, history) => beginTurn(proc, history, body, callerWorkDir, model, selection)
|
||||
if (resultBlocks.length) {
|
||||
const matches = matchToolResults(body, resultBlocks)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-agy-cli-auth",
|
||||
"version": "0.1.15",
|
||||
"version": "0.1.16",
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,725 @@
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { after, test } from "node:test"
|
||||
import { baseBody, createBridgeKit, readSse } from "./testkit.mjs"
|
||||
|
||||
// Expose private seams from an isolated copy, without adding production exports.
|
||||
const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "agy-convkey-test-"))
|
||||
const entry = new URL("../index.mjs", import.meta.url)
|
||||
let source = fs.readFileSync(entry, "utf8")
|
||||
source = source.replace(/from "(\.\/[^"\n]+)"/g, (_, target) => `from ${JSON.stringify(new URL(target, entry).href)}`)
|
||||
process.env.AGY_BRIDGE_STATE_FILE = path.join(workspace, "sessions.json")
|
||||
process.env.HOME = workspace
|
||||
fs.writeFileSync(
|
||||
path.join(workspace, "bridge.mjs"),
|
||||
source + "\nexport { conversationKey, stripVolatileOpening, stripVolatileSystem, isContinuedOpening, openingTextOf, sameInstructions, historyKey, takeParked, park, instructionsIdentity };\n",
|
||||
)
|
||||
const {
|
||||
conversationKey,
|
||||
stripVolatileOpening,
|
||||
stripVolatileSystem,
|
||||
isContinuedOpening,
|
||||
openingTextOf,
|
||||
sameInstructions,
|
||||
historyKey,
|
||||
takeParked,
|
||||
park,
|
||||
instructionsIdentity,
|
||||
} = await import(pathToFileURL(path.join(workspace, "bridge.mjs")).href)
|
||||
after(() => fs.rmSync(workspace, { recursive: true, force: true }))
|
||||
|
||||
function body({ system, first, rest = [], userId } = {}) {
|
||||
const messages = []
|
||||
if (first != null) messages.push(typeof first === "string" ? { role: "user", content: first } : first)
|
||||
messages.push(...rest)
|
||||
const out = { model: "agy-cli/test-model", messages }
|
||||
if (system != null) out.system = system
|
||||
if (userId != null) out.metadata = { user_id: userId }
|
||||
return out
|
||||
}
|
||||
|
||||
const STABLE = "Please review the following project files and propose a short fix.\n"
|
||||
|
||||
test("stripVolatileSystem removes billing headers, cch tokens, and known clock lines", () => {
|
||||
const raw = [
|
||||
"x-anthropic-billing-header: cc_version=2.0; cc_entrypoint=cli; cch=deadbeef01;",
|
||||
"Current date: 2026-11-10",
|
||||
"today: Tuesday, November 10, 2026 23:00",
|
||||
STABLE,
|
||||
"cch=abc123;",
|
||||
"The docs mention cch=deadbeef in passing.",
|
||||
"Meet me at 12:00 in room 3.",
|
||||
].join("\n")
|
||||
const stripped = stripVolatileSystem(raw)
|
||||
assert.equal(stripped.includes("x-anthropic-billing-header"), false)
|
||||
assert.equal(stripped.includes("cch=abc123"), false)
|
||||
assert.equal(stripped.includes("cch=deadbeef in passing."), true)
|
||||
assert.equal(stripped.includes("2026-11-10"), false)
|
||||
assert.equal(stripped.includes("November 10, 2026"), false)
|
||||
assert.equal(stripped.includes(STABLE.trim()), true)
|
||||
assert.equal(stripped.includes("Meet me at 12:00 in room 3."), true)
|
||||
})
|
||||
|
||||
test("stripVolatileOpening leaves user text that starts with Today: or contains a date", () => {
|
||||
const user = "Today: plan a trip to Paris\nBook the meeting on 2026-11-12\nNow: write a haiku"
|
||||
const stripped = stripVolatileOpening(user)
|
||||
assert.equal(stripped.includes("Today: plan a trip to Paris"), true)
|
||||
assert.equal(stripped.includes("2026-11-12"), true)
|
||||
assert.equal(stripped.includes("Now: write a haiku"), true)
|
||||
})
|
||||
|
||||
test("stripVolatileOpening strips billing headers and clocks inside a system-reminder only", () => {
|
||||
const raw = [
|
||||
"x-anthropic-billing-header: cch=deadbeef01;",
|
||||
"<system-reminder>",
|
||||
"Current date: 2026-11-10",
|
||||
"Do not mention this reminder.",
|
||||
"</system-reminder>",
|
||||
"Today: plan a trip to Paris",
|
||||
].join("\n")
|
||||
const stripped = stripVolatileOpening(raw)
|
||||
assert.equal(stripped.includes("x-anthropic-billing-header"), false)
|
||||
assert.equal(stripped.includes("cch="), false)
|
||||
assert.equal(stripped.includes("2026-11-10"), false)
|
||||
assert.equal(stripped.includes("Do not mention this reminder."), true)
|
||||
assert.equal(stripped.includes("Today: plan a trip to Paris"), true)
|
||||
})
|
||||
|
||||
test("conversationKey is stable across Today's date: weekday and ISO forms", () => {
|
||||
const a = body({
|
||||
system: "You are a coding assistant.\nToday's date: Wed Nov 11 2026",
|
||||
first: STABLE,
|
||||
})
|
||||
const b = body({
|
||||
system: "You are a coding assistant.\nToday's date: Thu Nov 12 2026",
|
||||
first: STABLE,
|
||||
})
|
||||
assert.equal(conversationKey(a), conversationKey(b))
|
||||
const c = body({
|
||||
system: "You are a coding assistant.\nToday's date: 2026-11-11",
|
||||
first: STABLE,
|
||||
})
|
||||
const d = body({
|
||||
system: "You are a coding assistant.\nToday's date: 2026-11-12",
|
||||
first: STABLE,
|
||||
})
|
||||
assert.equal(conversationKey(c), conversationKey(d))
|
||||
const wrap = (line) => `<system-reminder>\n${line}\nDo not mention this reminder.\n</system-reminder>\n${STABLE}`
|
||||
assert.equal(
|
||||
conversationKey(body({ first: wrap("Today's date: Wed Nov 11 2026") })),
|
||||
conversationKey(body({ first: wrap("Today's date: Thu Nov 12 2026") })),
|
||||
)
|
||||
assert.equal(
|
||||
conversationKey(body({ first: wrap("Today's date: 2026-11-11") })),
|
||||
conversationKey(body({ first: wrap("Today's date: 2026-11-12") })),
|
||||
)
|
||||
})
|
||||
|
||||
test("conversationKey distinguishes system blocks joined after a billing header", () => {
|
||||
const header = "x-anthropic-billing-header: cch=deadbeef01;"
|
||||
const a = body({ system: [{ text: header }, { text: "You are agent A." }], first: STABLE })
|
||||
const b = body({ system: [{ text: header }, { text: "You are agent B." }], first: STABLE })
|
||||
assert.notEqual(conversationKey(a), conversationKey(b))
|
||||
})
|
||||
|
||||
test("conversationKey is stable when only the system clock or billing header changes", () => {
|
||||
const a = body({
|
||||
system: "You are a coding assistant.\nCurrent date: 2026-11-10\nx-anthropic-billing-header: cch=aaa111;",
|
||||
first: STABLE + "File A contents.",
|
||||
userId: "user-1",
|
||||
})
|
||||
const b = body({
|
||||
system: "You are a coding assistant.\nCurrent date: 2026-11-11\nx-anthropic-billing-header: cch=bbb222;",
|
||||
first: STABLE + "File A contents.",
|
||||
userId: "user-1",
|
||||
})
|
||||
assert.equal(conversationKey(a), conversationKey(b))
|
||||
})
|
||||
|
||||
test("conversationKey is stable when only an opening system-reminder clock or cch token changes", () => {
|
||||
const wrap = (clock, token) =>
|
||||
`x-anthropic-billing-header: ${token}\n<system-reminder>\nCurrent time: ${clock}\n</system-reminder>\n${STABLE}`
|
||||
const a = body({ first: wrap("2026-11-10T01:02:03Z", "cch=111aaa;") })
|
||||
const b = body({ first: wrap("2026-11-10T09:08:07Z", "cch=222bbb;") })
|
||||
assert.equal(conversationKey(a), conversationKey(b))
|
||||
})
|
||||
|
||||
test("conversationKey stays the same after later assistant and user turns are attached", () => {
|
||||
const first = STABLE + "Please start with src/app.ts."
|
||||
const turn1 = body({ system: "Be concise.", first })
|
||||
const turn2 = body({
|
||||
system: "Be concise.",
|
||||
first,
|
||||
rest: [
|
||||
{ role: "assistant", content: "I will inspect src/app.ts." },
|
||||
{ role: "user", content: "Also check the tests." },
|
||||
],
|
||||
})
|
||||
assert.equal(conversationKey(turn1), conversationKey(turn2))
|
||||
})
|
||||
|
||||
test("conversationKey hashes the whole first message, so a shared 8 KiB prefix is not enough", () => {
|
||||
const log = "LOG " + "X".repeat(9000)
|
||||
const a = body({ system: "Same system", first: log + "\nQuestion A short" })
|
||||
const b = body({ system: "Same system", first: log + "\nQuestion B is a longer question than A" })
|
||||
assert.notEqual(conversationKey(a), conversationKey(b))
|
||||
// A flattened growing first message also changes the key (safer than sharing a prefix window).
|
||||
const opening = log + "\nQuestion A short"
|
||||
assert.notEqual(
|
||||
conversationKey(body({ first: opening })),
|
||||
conversationKey(body({ first: opening + "\n--- later flattened turn ---\nbeta suffix" })),
|
||||
)
|
||||
})
|
||||
|
||||
test("conversationKey keeps user Today:/Now:/Date lines and in-message dates", () => {
|
||||
assert.notEqual(
|
||||
conversationKey(body({ first: "Today: plan a trip to Paris" })),
|
||||
conversationKey(body({ first: "Today: plan a trip to Rome" })),
|
||||
)
|
||||
assert.notEqual(
|
||||
conversationKey(body({ first: "Now: delete the staging database" })),
|
||||
conversationKey(body({ first: "Now: write a haiku" })),
|
||||
)
|
||||
assert.notEqual(
|
||||
conversationKey(body({ first: "Book the meeting on 2026-11-12" })),
|
||||
conversationKey(body({ first: "Book the meeting on 2026-12-25" })),
|
||||
)
|
||||
assert.notEqual(
|
||||
conversationKey(body({ first: "Time: pack for the flight" })),
|
||||
conversationKey(body({ first: "Time: unpack the boxes" })),
|
||||
)
|
||||
assert.notEqual(
|
||||
conversationKey(body({ first: "Date: book the hall" })),
|
||||
conversationKey(body({ first: "Date: cancel the hall" })),
|
||||
)
|
||||
})
|
||||
|
||||
test("historyKey does not strip dates from later user or assistant messages", () => {
|
||||
const a = historyKey([
|
||||
{ role: "user", content: STABLE },
|
||||
{ role: "assistant", content: "Noted." },
|
||||
{ role: "user", content: "Book the meeting on 2026-11-12" },
|
||||
])
|
||||
const b = historyKey([
|
||||
{ role: "user", content: STABLE },
|
||||
{ role: "assistant", content: "Noted." },
|
||||
{ role: "user", content: "Book the meeting on 2026-12-25" },
|
||||
])
|
||||
assert.notEqual(a, b)
|
||||
})
|
||||
|
||||
test("historyKey still ignores clock lines inside later system-reminder blocks", () => {
|
||||
const wrap = (date) =>
|
||||
STABLE + "\n<system-reminder>\nCurrent date: " + date + "\n</system-reminder>"
|
||||
const a = historyKey([
|
||||
{ role: "user", content: STABLE },
|
||||
{ role: "assistant", content: "Noted." },
|
||||
{ role: "user", content: wrap("2026-11-12") },
|
||||
])
|
||||
const b = historyKey([
|
||||
{ role: "user", content: STABLE },
|
||||
{ role: "assistant", content: "Noted." },
|
||||
{ role: "user", content: wrap("2026-12-25") },
|
||||
])
|
||||
assert.equal(a, b)
|
||||
})
|
||||
|
||||
test("user prose that mentions cch= tokens is not collapsed by billing stripping", () => {
|
||||
assert.notEqual(
|
||||
conversationKey(body({ first: "the header used cch=aaa111 in the example" })),
|
||||
conversationKey(body({ first: "the header used cch=bbb222 in the example" })),
|
||||
)
|
||||
})
|
||||
|
||||
test("conversationKey changes for a genuinely different first message or user id", () => {
|
||||
const base = body({ system: "S", first: STABLE, userId: "a" })
|
||||
assert.notEqual(conversationKey(base), conversationKey(body({ system: "S", first: STABLE + "other", userId: "a" })))
|
||||
assert.notEqual(conversationKey(base), conversationKey(body({ system: "S", first: STABLE, userId: "b" })))
|
||||
assert.notEqual(conversationKey(base), conversationKey(body({ system: "Other system", first: STABLE, userId: "a" })))
|
||||
})
|
||||
|
||||
test("sameInstructions ignores volatile date and billing lines", () => {
|
||||
assert.equal(
|
||||
sameInstructions("Rules.\nCurrent date: 2026-11-10\n", "Rules.\nCurrent date: 2026-11-11\n"),
|
||||
true,
|
||||
)
|
||||
assert.equal(sameInstructions("Rules A", "Rules B"), false)
|
||||
})
|
||||
|
||||
const png = { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aXioAAAAASUVORK5CYII=" } }
|
||||
const gif = { type: "image", source: { type: "base64", media_type: "image/gif", data: "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" } }
|
||||
|
||||
test("conversationKey includes first-message images, so different pictures do not share a key", () => {
|
||||
const caption = { role: "user", content: [{ type: "text", text: "compare pictures " }, png, { type: "text", text: " and " }, gif] }
|
||||
const swapped = { role: "user", content: [{ type: "text", text: "compare pictures " }, gif, { type: "text", text: " and " }, png] }
|
||||
const same = { role: "user", content: [{ type: "text", text: "compare pictures " }, png, { type: "text", text: " and " }, gif] }
|
||||
assert.equal(conversationKey(body({ first: caption })), conversationKey(body({ first: same })))
|
||||
assert.notEqual(conversationKey(body({ first: caption })), conversationKey(body({ first: swapped })))
|
||||
const continued = body({
|
||||
first: caption,
|
||||
rest: [
|
||||
{ role: "assistant", content: "They differ." },
|
||||
{ role: "user", content: "recall the pictures" },
|
||||
],
|
||||
})
|
||||
assert.equal(conversationKey(body({ first: caption })), conversationKey(continued))
|
||||
})
|
||||
|
||||
function continuedProc(first, assistant = "done", images) {
|
||||
const opening = typeof first === "string" ? { role: "user", content: first } : first
|
||||
const proc = {
|
||||
openingText: openingTextOf(opening),
|
||||
expectedMessages: [opening, { role: "assistant", content: assistant }],
|
||||
}
|
||||
if (images !== undefined) proc.openingImages = images
|
||||
return proc
|
||||
}
|
||||
|
||||
test("isContinuedOpening requires the full previous opening, not a shared prefix", () => {
|
||||
const first = { role: "user", content: STABLE + "step one" }
|
||||
const grown = { role: "user", content: STABLE + "step one\n\nassistant: done\n\nstep two is longer than four chars" }
|
||||
const proc = continuedProc(first, "done")
|
||||
assert.equal(isContinuedOpening(proc, first), false)
|
||||
assert.equal(isContinuedOpening(proc, grown), true)
|
||||
assert.equal(isContinuedOpening(proc, { role: "user", content: "totally different task" }), false)
|
||||
assert.equal(isContinuedOpening({ openingText: "" }, grown), false)
|
||||
// A longer independent prompt that only shares a prefix is not a continuation,
|
||||
// even when it starts on a new line or extends the same sentence.
|
||||
assert.equal(isContinuedOpening(proc, { role: "user", content: STABLE + "step one and also the tests please" }), false)
|
||||
assert.equal(isContinuedOpening(proc, { role: "user", content: STABLE + "step one\nand also the tests please" }), false)
|
||||
assert.equal(isContinuedOpening(continuedProc(first, "ok"), { role: "user", content: STABLE + "step one\n\nokay, also look at the tests" }), false)
|
||||
const log = "LOG " + "X".repeat(9000)
|
||||
const chatA = { role: "user", content: log + "\nQuestion A short" }
|
||||
const chatB = { role: "user", content: log + "\nQuestion B is a longer question than A" }
|
||||
assert.equal(isContinuedOpening(continuedProc(chatA, "done"), chatB), false)
|
||||
// A 12-character reply must still end on a line boundary; a same-line
|
||||
// prefix extension is not a continuation.
|
||||
const longReply = "abcdefghijkl"
|
||||
assert.equal(longReply.length, 12)
|
||||
assert.equal(
|
||||
isContinuedOpening(continuedProc(first, longReply), {
|
||||
role: "user",
|
||||
content: STABLE + "step one\n\nassistant: " + longReply + "nop independent text",
|
||||
}),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
isContinuedOpening(continuedProc(first, longReply), {
|
||||
role: "user",
|
||||
content: STABLE + "step one\n\nassistant: " + longReply + "\n\nstep two is longer than four chars",
|
||||
}),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test("isContinuedOpening keeps first-message images in the continuation identity", () => {
|
||||
const first = { role: "user", content: [{ type: "text", text: STABLE + "compare pictures" }, png] }
|
||||
const grownSame = {
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: STABLE + "compare pictures\n\nassistant: done\n\nwhat changed" },
|
||||
png,
|
||||
],
|
||||
}
|
||||
const grownOther = {
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: STABLE + "compare pictures\n\nassistant: done\n\nwhat changed" },
|
||||
gif,
|
||||
],
|
||||
}
|
||||
const proc = continuedProc(first, "done")
|
||||
// openingImages is taken from the first expected message when not stored.
|
||||
assert.equal(isContinuedOpening(proc, grownSame), true)
|
||||
assert.equal(isContinuedOpening(proc, grownOther), false)
|
||||
})
|
||||
|
||||
test("takeParked uses the same instruction stripping, so a clock change still resumes", () => {
|
||||
const convKey = "test-parked-key"
|
||||
const history = [{ role: "user", content: STABLE }, { role: "assistant", content: "ok" }]
|
||||
park({
|
||||
convKey,
|
||||
sessionId: "sess-parked",
|
||||
expectedMessages: history,
|
||||
instructions: "Rules.\nCurrent date: 2026-11-10\n",
|
||||
workDir: "/tmp/agy-park-test",
|
||||
hasSentFirstTurn: true,
|
||||
historyInvalid: false,
|
||||
turn: null,
|
||||
dead: false,
|
||||
canPark() { return true },
|
||||
})
|
||||
const resumed = takeParked(convKey, {
|
||||
workDir: "/tmp/agy-park-test",
|
||||
instructions: "Rules.\nCurrent date: 2026-11-11\n",
|
||||
history,
|
||||
})
|
||||
assert.ok(resumed, "clock-only change must still take the parked session")
|
||||
assert.equal(resumed.sessionId, "sess-parked")
|
||||
assert.equal(
|
||||
instructionsIdentity("Rules.\nCurrent date: 2026-11-10\n"),
|
||||
instructionsIdentity("Rules.\nCurrent date: 2026-11-11\n"),
|
||||
)
|
||||
})
|
||||
|
||||
async function withKit(options, fn) {
|
||||
const kit = await createBridgeKit(options)
|
||||
try {
|
||||
return await fn(kit)
|
||||
} finally {
|
||||
await kit.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function promptSessions(kit) {
|
||||
return kit.acpLog
|
||||
.filter((entry) => entry.method === "session/prompt")
|
||||
.map((entry) => entry.params?.sessionId || entry.sessionId)
|
||||
}
|
||||
|
||||
function promptEntries(kit) {
|
||||
return kit.acpLog.filter((entry) => entry.method === "session/prompt")
|
||||
}
|
||||
|
||||
function promptText(entry) {
|
||||
const parts = entry?.params?.prompt || []
|
||||
return parts.map((part) => (part?.type === "text" ? part.text || "" : "")).join("")
|
||||
}
|
||||
|
||||
test("stripVolatileOpening is linear even with many unclosed system-reminder tags", () => {
|
||||
const unclosed = "<system-reminder>\n".repeat(20_000)
|
||||
const text = unclosed + "<system-reminder>\nToday's date: Wed Nov 11 2026\nKeep me.\n</system-reminder>\nuser text"
|
||||
const started = Date.now()
|
||||
const stripped = stripVolatileOpening(text)
|
||||
const elapsed = Date.now() - started
|
||||
assert.ok(elapsed < 500, `expected <500ms for 20k unclosed tags, took ${elapsed}ms`)
|
||||
assert.equal(stripped.includes("Today's date:"), false)
|
||||
assert.equal(stripped.includes("Wed Nov 11 2026"), false)
|
||||
assert.equal(stripped.includes("Keep me."), true)
|
||||
assert.equal(stripped.includes("user text"), true)
|
||||
})
|
||||
|
||||
test("stripVolatileOpening is linear when no system-reminder is ever closed", () => {
|
||||
const clock = "Today's date: Wed Nov 11 2026\n"
|
||||
const text = ("<system-reminder>\n" + clock).repeat(20_000) + "user text"
|
||||
const started = Date.now()
|
||||
const stripped = stripVolatileOpening(text)
|
||||
const elapsed = Date.now() - started
|
||||
assert.ok(elapsed < 500, `expected <500ms for 20k never-closed tags, took ${elapsed}ms`)
|
||||
assert.equal(stripped.includes("Today's date:"), true, "clocks in unclosed tags must stay")
|
||||
assert.equal(stripped.includes("user text"), true)
|
||||
})
|
||||
|
||||
test("conversationKey stays stable when İ precedes a dated system-reminder", () => {
|
||||
const wrap = (n, date) =>
|
||||
"İ".repeat(n) + `<system-reminder>\nToday's date: ${date}\nKeep me.\n</system-reminder>\n${STABLE}`
|
||||
for (const n of [4, 200]) {
|
||||
const a = wrap(n, "Wed Nov 11 2026")
|
||||
const b = wrap(n, "Thu Nov 12 2026")
|
||||
const stripped = stripVolatileOpening(a)
|
||||
assert.equal(stripped.includes("Today's date:"), false, `date must be stripped after ${n} İ`)
|
||||
assert.equal(stripped.includes("Wed Nov 11 2026"), false)
|
||||
assert.equal(stripped.includes("Keep me."), true)
|
||||
assert.equal(stripped.startsWith("İ".repeat(n)), true)
|
||||
assert.equal(
|
||||
conversationKey(body({ first: a })),
|
||||
conversationKey(body({ first: b })),
|
||||
`key must stay stable across a date change after ${n} İ`,
|
||||
)
|
||||
}
|
||||
const iso = (n, date) =>
|
||||
"İ".repeat(n) + `<system-reminder>\nToday's date: ${date}\nKeep me.\n</system-reminder>\n${STABLE}`
|
||||
assert.equal(
|
||||
conversationKey(body({ first: iso(4, "2026-11-11") })),
|
||||
conversationKey(body({ first: iso(4, "2026-11-12") })),
|
||||
)
|
||||
assert.equal(
|
||||
conversationKey(body({ first: iso(200, "2026-11-11") })),
|
||||
conversationKey(body({ first: iso(200, "2026-11-12") })),
|
||||
)
|
||||
})
|
||||
|
||||
test("two chats that share an 8 KiB first-message prefix get distinct fake agy sessions", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text("ok")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const log = "LOG " + "X".repeat(9000)
|
||||
const system = "You are a test agent."
|
||||
const chatA = baseBody({
|
||||
system,
|
||||
messages: [{ role: "user", content: log + "\nQuestion A short" }],
|
||||
})
|
||||
const chatB = baseBody({
|
||||
system,
|
||||
messages: [{ role: "user", content: log + "\nQuestion B is a longer question than A" }],
|
||||
})
|
||||
const first = await readSse(await kit.request(chatA))
|
||||
assert.equal(first.stopReason, "end_turn")
|
||||
const second = await readSse(await kit.request(chatB))
|
||||
assert.equal(second.stopReason, "end_turn")
|
||||
const sessions = promptSessions(kit)
|
||||
assert.equal(sessions.length, 2, `expected two prompts, got ${JSON.stringify(sessions)}`)
|
||||
assert.notEqual(sessions[0], sessions[1], `chat B must get its own session, got ${JSON.stringify(sessions)}`)
|
||||
})
|
||||
})
|
||||
|
||||
test("the same chat with only a system clock change reuses the fake agy session", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text("ok")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const firstMsg = STABLE + "Please start with src/app.ts."
|
||||
const turn1 = baseBody({
|
||||
system: "You are a test agent.\nCurrent date: 2026-11-10",
|
||||
messages: [{ role: "user", content: firstMsg }],
|
||||
})
|
||||
const parsed = await readSse(await kit.request(turn1))
|
||||
assert.equal(parsed.stopReason, "end_turn")
|
||||
const turn2 = baseBody({
|
||||
system: "You are a test agent.\nCurrent date: 2026-11-11",
|
||||
messages: [
|
||||
{ role: "user", content: firstMsg },
|
||||
{ role: "assistant", content: parsed.content?.map?.((b) => b.text).join("") || "ok" },
|
||||
{ role: "user", content: "continue" },
|
||||
],
|
||||
})
|
||||
const again = await readSse(await kit.request(turn2))
|
||||
assert.equal(again.stopReason, "end_turn")
|
||||
const sessions = promptSessions(kit)
|
||||
assert.equal(sessions.length, 2, `expected two prompts, got ${JSON.stringify(sessions)}`)
|
||||
assert.equal(sessions[0], sessions[1], `clock-only change must reuse the session, got ${JSON.stringify(sessions)}`)
|
||||
})
|
||||
})
|
||||
|
||||
test("a flattened growing first message reuses the live fake agy session", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text("ok")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const opening = STABLE + "step one"
|
||||
const first = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: opening }],
|
||||
})))
|
||||
assert.equal(first.stopReason, "end_turn")
|
||||
const reply = first.content?.map?.((b) => b.text).join("") || "ok"
|
||||
const grown = opening + "\n\nassistant: " + reply + "\n\nstep two is longer than four chars"
|
||||
const second = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: grown }],
|
||||
})))
|
||||
assert.equal(second.stopReason, "end_turn")
|
||||
const sessions = promptSessions(kit)
|
||||
assert.equal(sessions.length, 2, `expected two prompts, got ${JSON.stringify(sessions)}`)
|
||||
assert.equal(sessions[0], sessions[1], `flattened growth must reuse the session, got ${JSON.stringify(sessions)}`)
|
||||
// The key still changes; reuse is via isContinuedOpening, not a shared key.
|
||||
assert.notEqual(
|
||||
conversationKey(body({ system: "You are a test agent.", first: opening })),
|
||||
conversationKey(body({ system: "You are a test agent.", first: grown })),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
test("an independent prompt that only extends the previous opening gets its own session", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text("ok")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const opening = STABLE + "Review README"
|
||||
const first = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: opening }],
|
||||
})))
|
||||
assert.equal(first.stopReason, "end_turn")
|
||||
const other = opening + " and tests in detail please"
|
||||
const second = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: other }],
|
||||
})))
|
||||
assert.equal(second.stopReason, "end_turn")
|
||||
const sessions = promptSessions(kit)
|
||||
assert.equal(sessions.length, 2, `expected two prompts, got ${JSON.stringify(sessions)}`)
|
||||
assert.notEqual(sessions[0], sessions[1], `phrase extension must not reuse the session, got ${JSON.stringify(sessions)}`)
|
||||
})
|
||||
})
|
||||
|
||||
test("a reused flattened session sends only the new turn, not earlier openings or replies", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
const replies = ["reply-one-ok", "reply-two-ok", "reply-three-ok"]
|
||||
let n = 0
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text(replies[n++] || "ok")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const opening = STABLE + "step one"
|
||||
const first = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: opening }],
|
||||
})))
|
||||
assert.equal(first.stopReason, "end_turn")
|
||||
const reply1 = first.content?.map?.((b) => b.text).join("") || replies[0]
|
||||
const grown2 = opening + "\n\nassistant: " + reply1 + "\n\nstep two is longer than four chars"
|
||||
const second = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: grown2 }],
|
||||
})))
|
||||
assert.equal(second.stopReason, "end_turn")
|
||||
const reply2 = second.content?.map?.((b) => b.text).join("") || replies[1]
|
||||
const grown3 = grown2 + "\n\nassistant: " + reply2 + "\n\nstep three is also a new turn"
|
||||
const third = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: grown3 }],
|
||||
})))
|
||||
assert.equal(third.stopReason, "end_turn")
|
||||
const prompts = promptEntries(kit)
|
||||
assert.equal(prompts.length, 3, `expected three prompts, got ${prompts.length}`)
|
||||
const sessions = prompts.map((entry) => entry.params?.sessionId || entry.sessionId)
|
||||
assert.equal(sessions[0], sessions[1], `second turn must reuse the session, got ${JSON.stringify(sessions)}`)
|
||||
assert.equal(sessions[1], sessions[2], `third turn must reuse the session, got ${JSON.stringify(sessions)}`)
|
||||
const texts = prompts.map(promptText)
|
||||
const sizes = texts.map((text) => Buffer.byteLength(text, "utf8"))
|
||||
assert.equal(texts[1].includes("step two is longer than four chars"), true)
|
||||
assert.equal(texts[1].includes("step one"), false, `second prompt resent the opening: ${JSON.stringify(texts[1])}`)
|
||||
assert.equal(texts[1].includes(reply1), false, `second prompt resent the first reply: ${JSON.stringify(texts[1])}`)
|
||||
assert.equal(texts[1].includes(STABLE.trim()), false)
|
||||
assert.equal(texts[2].includes("step three is also a new turn"), true)
|
||||
assert.equal(texts[2].includes("step one"), false, `third prompt resent the opening: ${JSON.stringify(texts[2])}`)
|
||||
assert.equal(texts[2].includes("step two is longer than four chars"), false, `third prompt resent step two: ${JSON.stringify(texts[2])}`)
|
||||
assert.equal(texts[2].includes(reply1), false)
|
||||
assert.equal(texts[2].includes(reply2), false)
|
||||
assert.ok(sizes[1] < sizes[0], `second prompt (${sizes[1]}) should be smaller than the initial prompt (${sizes[0]})`)
|
||||
assert.ok(sizes[2] < sizes[0], `third prompt (${sizes[2]}) should stay smaller than the initial prompt (${sizes[0]})`)
|
||||
assert.ok(Math.abs(sizes[2] - sizes[1]) < 80, `prompt sizes must not grow quadratically: ${JSON.stringify(sizes)}`)
|
||||
})
|
||||
})
|
||||
|
||||
test("two metadata.user_id values that share a flattened opening do not share a session", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text("ok")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const opening = STABLE + "step one"
|
||||
const first = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
metadata: { user_id: "alice" },
|
||||
messages: [{ role: "user", content: opening }],
|
||||
})))
|
||||
assert.equal(first.stopReason, "end_turn")
|
||||
const reply = first.content?.map?.((b) => b.text).join("") || "ok"
|
||||
const grown = opening + "\n\nassistant: " + reply + "\n\nstep two is longer than four chars"
|
||||
const second = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
metadata: { user_id: "bob" },
|
||||
messages: [{ role: "user", content: grown }],
|
||||
})))
|
||||
assert.equal(second.stopReason, "end_turn")
|
||||
const sessions = promptSessions(kit)
|
||||
assert.equal(sessions.length, 2, `expected two prompts, got ${JSON.stringify(sessions)}`)
|
||||
assert.notEqual(sessions[0], sessions[1], `different user_id values must not share a session, got ${JSON.stringify(sessions)}`)
|
||||
})
|
||||
})
|
||||
|
||||
test("a 12-character reply prefix on the same line does not reuse the session", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text("abcdefghijkl")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const opening = STABLE + "step one"
|
||||
const first = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: opening }],
|
||||
})))
|
||||
assert.equal(first.stopReason, "end_turn")
|
||||
const reply = first.content?.map?.((b) => b.text).join("") || "abcdefghijkl"
|
||||
assert.ok(reply.length >= 12, `expected a long reply, got ${JSON.stringify(reply)}`)
|
||||
const other = opening + "\n\nassistant: " + reply + "nop independent text that only shares a prefix"
|
||||
const second = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: other }],
|
||||
})))
|
||||
assert.equal(second.stopReason, "end_turn")
|
||||
const sessions = promptSessions(kit)
|
||||
assert.equal(sessions.length, 2, `expected two prompts, got ${JSON.stringify(sessions)}`)
|
||||
assert.notEqual(sessions[0], sessions[1], `a same-line long-reply prefix must not reuse the session, got ${JSON.stringify(sessions)}`)
|
||||
})
|
||||
})
|
||||
|
||||
test("a reused flattened session also sends user messages after the first", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text("ok")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const opening = STABLE + "step one"
|
||||
const first = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: opening }],
|
||||
})))
|
||||
assert.equal(first.stopReason, "end_turn")
|
||||
const reply = first.content?.map?.((b) => b.text).join("") || "ok"
|
||||
const grown = opening + "\n\nassistant: " + reply + "\n\nstep two is longer than four chars"
|
||||
const second = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [
|
||||
{ role: "user", content: grown },
|
||||
{ role: "user", content: "and also the extra note after the flattened opening" },
|
||||
],
|
||||
})))
|
||||
assert.equal(second.stopReason, "end_turn")
|
||||
const prompts = promptEntries(kit)
|
||||
assert.equal(prompts.length, 2)
|
||||
const sessions = prompts.map((entry) => entry.params?.sessionId || entry.sessionId)
|
||||
assert.equal(sessions[0], sessions[1], `must reuse the session, got ${JSON.stringify(sessions)}`)
|
||||
const text = promptText(prompts[1])
|
||||
assert.equal(text.includes("step two is longer than four chars"), true, `missing new turn: ${JSON.stringify(text)}`)
|
||||
assert.equal(text.includes("and also the extra note after the flattened opening"), true, `dropped the trailing user message: ${JSON.stringify(text)}`)
|
||||
assert.equal(text.includes("step one"), false, `resent the opening: ${JSON.stringify(text)}`)
|
||||
assert.equal(text.includes(reply), false, `resent the first reply: ${JSON.stringify(text)}`)
|
||||
})
|
||||
})
|
||||
|
||||
test("a reused flattened session keeps a new document on the grown first message", async () => {
|
||||
await withKit({}, async (kit) => {
|
||||
kit.defaultPrompt = async (agent) => {
|
||||
await agent.text("ok")
|
||||
return { stopReason: "end_turn" }
|
||||
}
|
||||
const opening = STABLE + "step one"
|
||||
const first = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [{ role: "user", content: opening }],
|
||||
})))
|
||||
assert.equal(first.stopReason, "end_turn")
|
||||
const reply = first.content?.map?.((b) => b.text).join("") || "ok"
|
||||
const grown = {
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: opening + "\n\nassistant: " + reply + "\n\nstep two is longer than four chars" },
|
||||
{ type: "document", title: "notes.txt", source: { type: "text", data: "document body unique-xyz" } },
|
||||
],
|
||||
}
|
||||
const second = await readSse(await kit.request(baseBody({
|
||||
system: "You are a test agent.",
|
||||
messages: [grown],
|
||||
})))
|
||||
assert.equal(second.stopReason, "end_turn")
|
||||
const prompts = promptEntries(kit)
|
||||
assert.equal(prompts.length, 2)
|
||||
const sessions = prompts.map((entry) => entry.params?.sessionId || entry.sessionId)
|
||||
assert.equal(sessions[0], sessions[1], `must reuse the session, got ${JSON.stringify(sessions)}`)
|
||||
const text = promptText(prompts[1])
|
||||
assert.equal(text.includes("step two is longer than four chars"), true, `missing new turn: ${JSON.stringify(text)}`)
|
||||
assert.equal(text.includes("document body unique-xyz"), true, `dropped the new document: ${JSON.stringify(text)}`)
|
||||
assert.equal(text.includes("step one"), false, `resent the opening: ${JSON.stringify(text)}`)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user