Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions bin/agy-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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`);
Expand Down Expand Up @@ -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));
}
Expand Down
15 changes: 14 additions & 1 deletion bin/agy-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
`;

Expand Down Expand Up @@ -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);
Expand Down
56 changes: 55 additions & 1 deletion bin/muse-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -71,12 +72,13 @@ 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 } });
} 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;
Expand Down Expand Up @@ -370,6 +372,58 @@ 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);
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);
Expand Down