From e7b27a72fa940d8b454f22ab2af660b09d077602 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 09:55:54 -0600 Subject: [PATCH 1/2] feat(agy-proxy): emit cached_tokens from agy cache_read_tokens; test muse warm-host kill degradation (#480) --- bin/agy-proxy.mjs | 24 +++++++++++++++++++----- bin/agy-proxy.test.mjs | 15 ++++++++++++++- bin/muse-proxy.test.mjs | 26 ++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/bin/agy-proxy.mjs b/bin/agy-proxy.mjs index 69936a8181..b22d98e02c 100755 --- a/bin/agy-proxy.mjs +++ b/bin/agy-proxy.mjs @@ -24,6 +24,16 @@ // or times out is killed and never reused; the next request respawns // (spares replenish automatically). Live session workers are evicted // after an idle TTL / past a live-worker cap. +// Cached-token accounting (#480, settled 2026-11-01): the agy CLI's +// stream-json `result.usage` DOES carry a cached-input figure — +// `cache_read_tokens`, cumulative over the session like its sibling +// counters (verified against the real CLI's result shape on the +// laptop: usage keys are input_tokens, output_tokens, +// thinking_tokens, cache_read_tokens, total_tokens). The per-turn +// delta is emitted as `prompt_tokens_details.cached_tokens` in both +// response shapes when > 0, matching the sibling proxies' +// opencode#394 contract; when the CLI reports none, the field is +// omitted entirely rather than reporting a fabricated zero split. // Failure semantics are unchanged from #678: a failed turn is an error // (502 non-stream, SSE error event + [DONE] stream), never a 'stop' // carrying partial output; a failed resume retries once as a fresh @@ -484,7 +494,7 @@ class AgyWorker { this.stderrTail = ''; this.turnWaiter = null; this.ready = false; // set when the init event arrives - this.prevUsage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 }; + this.prevUsage = { input_tokens: 0, output_tokens: 0, total_tokens: 0, cache_read_tokens: 0 }; const args = [ '--dangerously-skip-permissions', @@ -620,12 +630,14 @@ class AgyWorker { const deltaUsage = { input_tokens: Math.max(0, (cum.input_tokens || 0) - this.prevUsage.input_tokens), output_tokens: Math.max(0, (cum.output_tokens || 0) - this.prevUsage.output_tokens), - total_tokens: Math.max(0, (cum.total_tokens || 0) - this.prevUsage.total_tokens) + total_tokens: Math.max(0, (cum.total_tokens || 0) - this.prevUsage.total_tokens), + cache_read_tokens: Math.max(0, (cum.cache_read_tokens || 0) - this.prevUsage.cache_read_tokens) }; this.prevUsage = { input_tokens: cum.input_tokens || 0, output_tokens: cum.output_tokens || 0, - total_tokens: cum.total_tokens || 0 + total_tokens: cum.total_tokens || 0, + cache_read_tokens: cum.cache_read_tokens || 0 }; this.turns += 1; this.lastUsedAt = Date.now(); @@ -1056,7 +1068,8 @@ const server = http.createServer((req, res) => { usage: { prompt_tokens: result.usage?.input_tokens || 0, completion_tokens: result.usage?.output_tokens || 0, - total_tokens: result.usage?.total_tokens || 0 + total_tokens: result.usage?.total_tokens || 0, + ...(result.usage?.cache_read_tokens > 0 ? { prompt_tokens_details: { cached_tokens: result.usage.cache_read_tokens } } : {}) } }; res.write(`data: ${JSON.stringify(finishChunk)}\n\n`); @@ -1089,7 +1102,8 @@ const server = http.createServer((req, res) => { usage: { prompt_tokens: result.usage?.input_tokens || 0, completion_tokens: result.usage?.output_tokens || 0, - total_tokens: result.usage?.total_tokens || 0 + total_tokens: result.usage?.total_tokens || 0, + ...(result.usage?.cache_read_tokens > 0 ? { prompt_tokens_details: { cached_tokens: result.usage.cache_read_tokens } } : {}) } }, null, 2)); } diff --git a/bin/agy-proxy.test.mjs b/bin/agy-proxy.test.mjs index 2890e40021..f1fc92e882 100644 --- a/bin/agy-proxy.test.mjs +++ b/bin/agy-proxy.test.mjs @@ -82,7 +82,7 @@ while IFS= read -r line; do kill -9 $$ ;; esac printf '%s\\n' '{"event":"step_update","step_update":{"text_delta":"Hello world"}}' - printf '%s\\n' '{"event":"result","result":{"conversation_id":"stub-conv-1","status":"SUCCESS","response":"Hello world","usage":{"input_tokens":100,"output_tokens":3,"total_tokens":103}}}' + printf '%s\\n' '{"event":"result","result":{"conversation_id":"stub-conv-1","status":"SUCCESS","response":"Hello world","usage":{"input_tokens":100,"output_tokens":3,"total_tokens":103,"cache_read_tokens":77}}}' done `; @@ -171,6 +171,19 @@ test('successful run is unchanged in both modes', async (t) => { assert.ok(sse.trimEnd().endsWith('data: [DONE]')); }); +test('agy cache_read_tokens surfaces as prompt_tokens_details.cached_tokens in both shapes (#480)', async (t) => { + const { port, stop } = await startProxy(); + t.after(stop); + const messages = [{ role: 'user', content: 'hi' }]; + const plain = JSON.parse(await (await post(port, { messages })).text()); + assert.equal(plain.usage.prompt_tokens_details.cached_tokens, 77, 'non-streaming usage must surface the agy cache_read_tokens delta (opencode #394)'); + const streamRes = await post(port, { messages, stream: true }); + const events = parseSse(await streamRes.text()); + const finish = events.find(e => e.choices && e.choices[0].finish_reason === 'stop'); + assert.ok(finish, 'stream must carry a finish chunk'); + assert.equal(finish.usage.prompt_tokens_details.cached_tokens, 77, 'streaming finish chunk must surface cached_tokens'); +}); + test('execution failure with no output: 502 non-stream, SSE error + [DONE] stream (#678)', async (t) => { const { port, stop } = await startProxy(); t.after(stop); diff --git a/bin/muse-proxy.test.mjs b/bin/muse-proxy.test.mjs index 198f422fb8..63407c5fbb 100644 --- a/bin/muse-proxy.test.mjs +++ b/bin/muse-proxy.test.mjs @@ -77,6 +77,7 @@ if (args[0] === 'serve') { reply({ session: { sessionId: msg.params.sessionId } }); } else if (msg.method === 'turn/start') { const text = (msg.params.input || []).map(p => p.text || '').join(''); + if (text.includes('KILLHOST')) { log('KILLED ' + text); process.kill(process.pid, 'SIGKILL'); } log('TURN ' + text); const sid = msg.params.sessionId; const turnId = msg.params.commandId; @@ -370,6 +371,31 @@ test('warm serve path: streaming turn streams the MSP deltas (#480)', async (t) assert.equal(finish, 'stop'); }); +test('warm host killed mid-turn degrades to a successful cold exec request (#480)', async (t) => { + const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' }); + t.after(stop); + const turn1 = JSON.parse(await chat(port, { + model: 'muse-spark-1.3', + messages: [{ role: 'user', content: 'alpha one' }] + })); + assert.equal(turn1.choices[0].message.content, 'RE:alpha one', 'turn 1 must be served warm'); + // Turn 2's new message kills the warm serve host mid-turn (before any + // delta is committed); the request must degrade to the cold exec path + // and still answer, not surface a client-visible error (#480 spike + // criterion 4). + const turn2 = JSON.parse(await chat(port, { + model: 'muse-spark-1.3', + messages: [ + { role: 'user', content: 'alpha one' }, + { role: 'assistant', content: 'RE:alpha one' }, + { role: 'user', content: 'KILLHOST now' } + ] + })); + assert.equal(turn2.choices[0].message.content, 'Hello world', 'exec stub answer proves the cold fallback ran after the warm host died'); + const log = fs.readFileSync(logFile, 'utf-8'); + assert.match(log, /KILLED KILLHOST now/, 'the warm host must actually have been killed mid-turn'); +}); + test('warm serve failure falls back to the exec path (#480)', async (t) => { const { port, stop } = await startProxy({ MUSE_PROXY_WARM: '1', STUB_SERVE_FAIL: '1' }); t.after(stop); From 511515d45ddb694d40ed65dbf4c2664ea9b3aa72 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 09:57:47 -0600 Subject: [PATCH 2/2] test(muse-proxy): concurrent-conversation isolation for #480 (stub MSP session ids now unique per session) --- bin/muse-proxy.test.mjs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/bin/muse-proxy.test.mjs b/bin/muse-proxy.test.mjs index 63407c5fbb..7d52ffa8ce 100644 --- a/bin/muse-proxy.test.mjs +++ b/bin/muse-proxy.test.mjs @@ -57,6 +57,7 @@ if (args[0] === 'serve') { if (process.env.STUB_SERVE_FAIL === '1') process.exit(3); const log = (line) => { if (process.env.STUB_LOG) fs.appendFileSync(process.env.STUB_LOG, line + '\\n'); }; let buf = ''; + let stubSessN = 0; process.stdin.on('data', (d) => { buf += d.toString('utf-8'); let i; @@ -71,7 +72,7 @@ if (args[0] === 'serve') { reply({ serverInfo: { name: 'stub-muse', version: '0' } }); } else if (msg.method === 'session/start') { log('START ' + msg.params.modelId); - reply({ session: { sessionId: 'stub-session-1' } }); + reply({ session: { sessionId: 'stub-session-' + (++stubSessN) } }); } else if (msg.method === 'session/resume') { log('RESUME ' + msg.params.sessionId); reply({ session: { sessionId: msg.params.sessionId } }); @@ -371,6 +372,33 @@ test('warm serve path: streaming turn streams the MSP deltas (#480)', async (t) assert.equal(finish, 'stop'); }); +test('two concurrent conversations stay isolated: separate sessions, tail-only turns (#480)', async (t) => { + const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' }); + t.after(stop); + const convA = [{ role: 'user', content: 'alpha one' }]; + const convB = [{ role: 'user', content: 'gamma one' }]; + const [a1, b1] = await Promise.all([ + chat(port, { model: 'muse-spark-1.3', messages: convA }).then(r => JSON.parse(r)), + chat(port, { model: 'muse-spark-1.3', messages: convB }).then(r => JSON.parse(r)) + ]); + assert.equal(a1.choices[0].message.content, 'RE:alpha one'); + assert.equal(b1.choices[0].message.content, 'RE:gamma one'); + const a2 = JSON.parse(await chat(port, { + model: 'muse-spark-1.3', + messages: [...convA, { role: 'assistant', content: 'RE:alpha one' }, { role: 'user', content: 'alpha two' }] + })); + const b2 = JSON.parse(await chat(port, { + model: 'muse-spark-1.3', + messages: [...convB, { role: 'assistant', content: 'RE:gamma one' }, { role: 'user', content: 'gamma two' }] + })); + assert.equal(a2.choices[0].message.content, 'RE:alpha two'); + assert.equal(b2.choices[0].message.content, 'RE:gamma two'); + const log = fs.readFileSync(logFile, 'utf-8').trim().split('\n'); + assert.equal(log.filter(l => l.startsWith('START')).length, 2, 'each conversation key must own a separate MSP session'); + const turns = log.filter(l => l.startsWith('TURN')).map(l => l.slice(5)).sort(); + assert.deepEqual(turns, ['alpha one', 'alpha two', 'gamma one', 'gamma two'], 'every turn after the first must send only its own conversation\'s new tail — no cross-conversation history'); +}); + test('warm host killed mid-turn degrades to a successful cold exec request (#480)', async (t) => { const { port, stop, logFile } = await startProxy({ MUSE_PROXY_WARM: '1' }); t.after(stop);