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
28 changes: 28 additions & 0 deletions bin/codex-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,34 @@ test('successful run is unchanged in both modes', async (t) => {
assert.ok(sse.trimEnd().endsWith('data: [DONE]'));
});

test('CLI transport: cached_input_tokens surfaces as prompt_tokens_details.cached_tokens (#3114)', async (t) => {
const { port, stop } = await startProxy();
t.after(stop);

// Non-stream: the exec stub's turn.completed carries cached_input_tokens 93.
const plainRes = await post(port, { messages: TURN1 });
assert.equal(plainRes.status, 200);
const plain = JSON.parse(await plainRes.text());
assert.equal(plain.usage.prompt_tokens_details.cached_tokens, 93, 'CLI transport must surface cached_input_tokens as prompt_tokens_details.cached_tokens (opencode #394)');

// The resumed turn's stub usage has NO cached_input_tokens: the detail
// object must be omitted entirely, not emitted as 0.
const r2 = await post(port, { messages: TURN2 });
assert.equal(r2.status, 200);
const resumed = JSON.parse(await r2.text());
assert.equal(resumed.choices[0].message.content, 'resumed answer');
assert.equal(resumed.usage.prompt_tokens_details, undefined, 'absent cache value must omit prompt_tokens_details entirely');

// Stream: the end chunk carries the same cached_tokens for a fresh run.
const streamRes = await post(port, { messages: [{ role: 'user', content: 'gamma streaming question' }], stream: true });
assert.equal(streamRes.status, 200);
const sse = await streamRes.text();
const events = sse.split('\n').filter(l => l.startsWith('data: ') && !l.includes('[DONE]')).map(l => JSON.parse(l.slice('data: '.length)));
const endChunk = events.find(e => e.usage);
assert.ok(endChunk, 'stream end chunk must carry usage');
assert.equal(endChunk.usage.prompt_tokens_details.cached_tokens, 93, 'streaming CLI transport must surface cached_tokens');
});

test('execution failure with no output: 500 non-stream, SSE error + [DONE] stream (#676)', async (t) => {
const { port, stop } = await startProxy();
t.after(stop);
Expand Down
104 changes: 104 additions & 0 deletions bin/commandcode-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,107 @@ test('chat vs agency spawn contract', async (t) => {
assert.ok(stdin.includes('Do ALL file work inside'), 'agency prompt must carry the workdir steer');
assert.ok(stdin.includes('write_file'), 'agency prompt must name the requested tool');
});

// ---------------------------------------------------------------------------
// ACP-speaking stub (#3114): answers the ACP handshake for real so the proxy
// stays on the ACP path, and returns prompt usage carrying cacheReadTokens
// (omitted when the prompt contains NOCACHE). Spawn (-p) invocations keep
// the canned NDJSON behaviour.
// ---------------------------------------------------------------------------
const ACP_STUB = `#!/usr/bin/env node
const args = process.argv.slice(2);
if (args[0] !== 'acp') {
let stdin = '';
process.stdin.on('data', (c) => { stdin += c; });
process.stdin.on('end', () => {
process.stdout.write(JSON.stringify({ type: 'event', event: { type: 'text_delta', delta: 'STUB-OK' } }) + '\\n');
process.stdout.write(JSON.stringify({ type: 'event', event: { type: 'run_end', result: { finalText: 'STUB-OK', usage: { inputTokens: 10, outputTokens: 2 } } } }) + '\\n');
process.exit(0);
});
return;
}
let buf = '';
process.stdin.on('data', (c) => {
buf += c.toString('utf8');
const lines = buf.split('\\n');
buf = lines.pop();
for (const line of lines) {
const t = line.trim();
if (!t || !t.startsWith('{')) continue;
let m;
try { m = JSON.parse(t); } catch { continue; }
if (m.id === undefined || !m.method) continue;
const reply = (result) => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: m.id, result }) + '\\n');
if (m.method === 'initialize') {
reply({ protocolVersion: 1, agentInfo: { name: 'stub-acp', version: '0' }, agentCapabilities: { loadSession: false } });
} else if (m.method === 'session/new') {
reply({ sessionId: 'stub-acp-session-1' });
} else if (m.method === 'session/prompt') {
const sessionId = m.params.sessionId;
const text = (m.params.prompt && m.params.prompt[0] && m.params.prompt[0].text) || '';
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', method: 'session/update', params: { sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'ACP-OK' } } } }) + '\\n');
const usage = text.includes('NOCACHE')
? { inputTokens: 50, outputTokens: 4 }
: { inputTokens: 50, outputTokens: 4, cacheReadTokens: 77 };
reply({ stopReason: 'end_turn', usage });
} else {
reply({});
}
}
});
`;

test('ACP prompt usage cacheReadTokens surfaces as prompt_tokens_details.cached_tokens (#3114)', async (t) => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-proxy-acp-test-'));
const stubHome = path.join(tmp, 'home');
const stubBin = path.join(stubHome, 'tools', 'command-code', 'bin');
fs.mkdirSync(stubBin, { recursive: true });
fs.writeFileSync(path.join(stubBin, 'commandcode'), ACP_STUB, { mode: 0o755 });

const port = 18949;
const env = {
...process.env,
HOME: stubHome,
COMMANDCODE_PROXY_PORT: String(port),
COMMANDCODE_PROXY_HOST: '127.0.0.1',
COMMANDCODE_PROXY_EGRESS: '',
COMMANDCODE_PROXY_TIMEOUT_MS: '30000',
COMMANDCODE_PROXY_WORKDIR: path.join(tmp, 'work'),
};
const child = spawn('node', [path.join(binDir, 'commandcode-proxy.mjs')], { env, stdio: ['ignore', 'pipe', 'pipe'] });
let logged = '';
child.stdout.on('data', (c) => { logged += c; });
child.stderr.on('data', (c) => { logged += c; });
t.after(() => { try { child.kill('SIGKILL'); } catch {} });
t.after(() => { if (process.env.CC_TEST_DEBUG) console.log(logged); });

await waitFor(`http://127.0.0.1:${port}/health`);

const chat = async (body) => {
const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const text = await res.text();
assert.equal(res.status, 200, `expected 200, got ${res.status}: ${text.slice(0, 500)}`);
return text;
};

// Non-streaming: ACP usage cacheReadTokens 77 must surface as cached_tokens.
const plain = JSON.parse(await chat({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'hi cached' }], stream: false }));
assert.equal(plain.choices[0].message.content, 'ACP-OK');
assert.equal(plain.usage.prompt_tokens_details.cached_tokens, 77, 'ACP cacheReadTokens must surface as prompt_tokens_details.cached_tokens (opencode #394)');

// Streaming: the end chunk carries the same cached_tokens.
const sse = await chat({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'hi cached stream' }], stream: true });
const events = sse.split('\n').filter(l => l.startsWith('data: ') && !l.includes('[DONE]')).map(l => JSON.parse(l.slice('data: '.length)));
const endChunk = events.find(e => e.usage);
assert.ok(endChunk, 'stream end chunk must carry usage');
assert.equal(endChunk.usage.prompt_tokens_details.cached_tokens, 77, 'streaming ACP path must surface cached_tokens');

// Zero/absent cache value: prompt_tokens_details omitted entirely.
const noCache = JSON.parse(await chat({ model: 'deepseek/deepseek-v4-flash', messages: [{ role: 'user', content: 'NOCACHE please' }], stream: false }));
assert.equal(noCache.choices[0].message.content, 'ACP-OK');
assert.equal(noCache.usage.prompt_tokens_details, undefined, 'absent cacheReadTokens must omit prompt_tokens_details entirely');
});