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
20 changes: 14 additions & 6 deletions src/runtime/claudeCodeSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ const count = (value: unknown): value is number => typeof value === 'number' &&
const sessionId = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu;
const tools = ['Read', 'Grep', 'Glob', 'Edit', 'Write', 'Bash', 'WebSearch', 'WebFetch'];
const maxFrameBytes = 8 * 1024 * 1024;
// A valid handoff usually ends the native turn within seconds; wait that long for its usage-bearing result.
const submissionResultGraceMs = 10_000;

/** Context occupancy is the latest actual API request, not the invocation's additive totals. */
function requestInputTokens(value: unknown): number | undefined {
Expand Down Expand Up @@ -154,7 +156,7 @@ export async function createClaudeCodeMathSession(options: MathAgentOptions): Pr
let apiFailure: MathAgentFailureDiagnostic | undefined;
let interrupted = false, timedOut = false, submitted = false, invalid = false, pending = '';
const decoder = new StringDecoder('utf8');
let cancelTimeout: (() => void) | undefined, outputWatcher: NodeJS.Timeout | undefined;
let cancelTimeout: (() => void) | undefined, outputWatcher: NodeJS.Timeout | undefined, resultGrace: NodeJS.Timeout | undefined;
const partial = new Map<number, { id: string; type: string; text?: string }>();
const incomplete = () => {
if (usageReported) return;
Expand All @@ -175,7 +177,7 @@ export async function createClaudeCodeMathSession(options: MathAgentOptions): Pr
const output = options.completedOutput!;
output.validate(JSON.parse(readMathText(output.file, 2_000_000)));
submitted = true; cancelTimeout?.(); clearInterval(outputWatcher);
void stop();
resultGrace = setTimeout(() => { void stop(); }, submissionResultGraceMs);
} catch { /* Missing, partial, rejected and stale handoffs do not stop the writer. */ }
};
const frame = (value: unknown) => {
Expand Down Expand Up @@ -240,6 +242,7 @@ export async function createClaudeCodeMathSession(options: MathAgentOptions): Pr
} else if (typeof event.result === 'string') completedResponse = { turnId: messageId, text: event.result };
else if (options.outputSchema && object(event.structured_output))
completedResponse = { turnId: messageId, text: JSON.stringify(event.structured_output) };
if (submitted) void stop();
}
};
const consume = (chunk: Buffer) => {
Expand All @@ -259,15 +262,20 @@ export async function createClaudeCodeMathSession(options: MathAgentOptions): Pr
if (pending.trim() && !invalid) {
try { frame(JSON.parse(pending + decoder.end())); } catch { failed('math_claude_protocol_invalid'); }
}
settled = true; active = undefined; cancelTimeout?.(); clearInterval(outputWatcher);
settled = true; active = undefined; cancelTimeout?.(); clearInterval(outputWatcher); clearTimeout(resultGrace);
if (!terminal) incomplete();
if (submitted) {
// The validated handoff is the turn's outcome; shutdown during the result grace is not a failure.
lastError = undefined; diagnostic = undefined; completedResponse = undefined;
resolve('submitted'); return;
}
if (timedOut) lastError = 'math_model_request_timeout';
else if (interrupted) lastError = 'math_model_request_stopped';
else if (!terminal && !submitted && !lastError) lastError = 'math_model_request_failed';
else if (exitCode !== 0 && !submitted && !lastError) lastError = 'math_model_request_failed';
else if (!terminal && !lastError) lastError = 'math_model_request_failed';
else if (exitCode !== 0 && !lastError) lastError = 'math_model_request_failed';
if (lastError && !diagnostic) diagnostic = { code: 'other' };
if (lastError) completedResponse = undefined;
resolve(interrupted ? 'interrupted' : lastError ? 'failed' : submitted ? 'submitted' : 'completed');
resolve(interrupted ? 'interrupted' : lastError ? 'failed' : 'completed');
};
active = { interrupt: () => { interrupted = true; } };
owned.stdout!.on('data', consume);
Expand Down
31 changes: 21 additions & 10 deletions src/runtime/cliSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import { prepareSealedHarness, sealedRolePath, sealedRoleText } from './sealedHa

type Json = Record<string, unknown>;
const maxBytes = 8 * 1024 * 1024;
// A valid handoff usually ends the native turn within seconds; wait that long for its final usage.
const submissionResultGraceMs = 10_000;
const count = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
const validSessionId = (value: unknown): value is string => typeof value === 'string' && value.length > 0 &&
Buffer.byteLength(value) <= 1024 && !value.startsWith('-') && !/[\u0000-\u0020\u007f]/u.test(value);
Expand Down Expand Up @@ -69,7 +71,7 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
if (active) throw new Error('math_cli_turn_active');
if (workspace !== options.workspace) throw new Error('math_cli_workspace_changed');
if (options.signal?.aborted) throw new Error('math_model_request_stopped');
let interrupted = false;
let interrupted = false, promptFile = '';
active = { interrupt: () => { interrupted = true; } };
try {
assertMathAgentSkillsCurrent(options.skills ?? []);
Expand All @@ -86,7 +88,6 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
'\n\nResearch request:\n' + message;
const prompt = sealed ? sealedRoleText(hostPrompt, options) : hostPrompt;
if (Buffer.byteLength(prompt) > maxBytes) throw new Error('math_cli_prompt_too_large');
let promptFile = '';
if (configuration.prompt === 'file') {
const directory = path.join(workspace, '.scratch', 'cli-prompts');
assertMathCanonicalPath(directory); fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
Expand Down Expand Up @@ -117,7 +118,7 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
let timedOut = false, submitted = false, invalid = false;
let pending = '', text = '', usageValue: unknown, usageMatched = false;
const decoder = new TextDecoder('utf-8', { fatal: true });
let cancelTimeout: (() => void) | undefined, outputWatcher: NodeJS.Timeout | undefined;
let cancelTimeout: (() => void) | undefined, outputWatcher: NodeJS.Timeout | undefined, resultGrace: NodeJS.Timeout | undefined;
const begin = () => {
if (started || !bound) return;
started = true;
Expand Down Expand Up @@ -196,18 +197,22 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
try {
pending += decoder.decode();
if (output.format === 'text') text = pending;
else if (!submitted && !interrupted && !timedOut && (output.format === 'json' || pending.trim())) frame(JSON.parse(pending));
else if (!interrupted && !timedOut && (output.format === 'json' || pending.trim())) frame(JSON.parse(pending));
} catch { invalid = true; lastError = 'math_cli_protocol_invalid'; diagnostic = { code: 'other' }; }
}
settled = true; cancelTimeout?.(); clearInterval(outputWatcher);
settled = true; cancelTimeout?.(); clearInterval(outputWatcher); clearTimeout(resultGrace);
if (!started && !lastError) { lastError = 'math_cli_session_id_missing'; diagnostic = { code: 'other' }; }
account();
if (submitted) {
// The validated handoff is the turn's outcome; shutdown during the usage grace is not a failure.
lastError = undefined; diagnostic = undefined; resolve('submitted'); return;
}
if (timedOut) lastError = 'math_model_request_timeout';
else if (interrupted) lastError = 'math_model_request_stopped';
else if (!submitted && exitCode !== 0 && !invalid && !lastError) lastError = 'math_cli_command_failed';
else if (exitCode !== 0 && !invalid && !lastError) lastError = 'math_cli_command_failed';
if (lastError && !diagnostic) diagnostic = { code: 'other' };
if (!lastError && !submitted && text.trim()) completedResponse = { turnId: messageId, text };
resolve(interrupted ? 'interrupted' : lastError ? 'failed' : submitted ? 'submitted' : 'completed');
if (!lastError && text.trim()) completedResponse = { turnId: messageId, text };
resolve(interrupted ? 'interrupted' : lastError ? 'failed' : 'completed');
};
owned.stdout!.on('data', consume); owned.stderr!.resume();
owned.stdin!.on('error', () => {});
Expand All @@ -221,7 +226,9 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
try {
const output = options.completedOutput!;
output.validate(JSON.parse(readMathText(output.file, 2_000_000)));
submitted = true; cancelTimeout?.(); clearInterval(outputWatcher); void stop();
submitted = true; cancelTimeout?.(); clearInterval(outputWatcher);
// Let a native turn that is already ending print its final usage before the writer is stopped.
resultGrace = setTimeout(() => { void stop(); }, submissionResultGraceMs);
} catch { /* Missing, partial, stale or rejected completion files keep the writer running. */ }
}, 100);
outputWatcher.unref();
Expand All @@ -230,7 +237,11 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
timedOut = true; void stop();
}, options.turnTimeoutMs);
});
} finally { active = undefined; }
} finally {
active = undefined;
// The prompt is consumed by the time the writer has exited; never accumulate one copy per turn.
if (promptFile) try { fs.rmSync(promptFile, { force: true }); } catch { /* Cleanup never replaces the turn outcome. */ }
}
},
interrupt,
async close() { closed = true; options.signal?.removeEventListener('abort', abort);
Expand Down
13 changes: 13 additions & 0 deletions tests/claudeCodeSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,19 @@ describe('Claude Code stream-json adapter without provider calls', () => {
expect(session.lastError).toBeUndefined();
expect(session.lastCompletedResponse).toBeUndefined();
expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' });
}, 30_000);

it.each(['submit-then-result', 'submit-then-error'])('records the native result usage that follows a valid completion file (%s)', async prompt => {
const file = path.join(workspace, 'completed.json');
const validate = vi.fn((value: unknown) => { if ((value as { checked?: boolean }).checked !== true) throw new Error('rejected'); });
const session = await open({ ...options, completedOutput: { file, validate } }), started = Date.now();
expect(await session.run(prompt, 'turn-submit', workspace, vi.fn())).toBe('submitted');
expect(Date.now() - started).toBeLessThan(5_000);
expect(options.onUsage).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ inputTokens: 31, outputTokens: 5 }), { turnId: 'turn-submit' });
expect(options.onUsageIncomplete).not.toHaveBeenCalled();
expect(session.lastError).toBeUndefined(); expect(session.lastFailureDiagnostic).toBeUndefined();
expect(session.lastCompletedResponse).toBeUndefined();
expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' });
});

it('stops a background writer in the owned namespace before a freeze is confirmed', async () => {
Expand Down
21 changes: 18 additions & 3 deletions tests/cliSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ describe('configured headless CLI sessions with isolated local children', () =>
for (const name of ['NEVER_CREATED', 'SHOULD_NOT_EXIST', 'ALSO_NOT_CREATED']) expect(fs.existsSync(path.join(workspace, name))).toBe(false);
if (mode === 'file') {
expect(call.promptFile.startsWith(path.join(workspace, '.scratch/cli-prompts') + '/')).toBe(true);
expect(fs.lstatSync(call.promptFile).mode & 0o777).toBe(0o400);
expect(fs.readFileSync(call.promptFile, 'utf8')).toBe(call.prompt);
expect(call.promptMode).toBe(0o400);
expect(fs.existsSync(call.promptFile)).toBe(false);
}
});

Expand Down Expand Up @@ -276,6 +276,21 @@ describe('configured headless CLI sessions with isolated local children', () =>
fs.writeFileSync(file, '{"current":true}'); expect(await run).toBe('submitted');
expect(session.lastCompletedResponse).toBeUndefined(); expect(options.onUsage).not.toHaveBeenCalled();
expect(options.onUsageIncomplete).toHaveBeenCalledOnce(); expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' });
}, 30_000);

it.each(['jsonl', 'json'])('keeps the final %s usage that a submitting turn prints after its completion file', async format => {
scenario('submit-then-final'); const file = path.join(workspace, 'completed.json');
configuration.output = structured(format);
configuration.args = (configuration.args as string[]).map(value => value === 'jsonl' ? format : value);
const validate = vi.fn((value: unknown) => { if ((value as { current?: boolean }).current !== true) throw new Error('stale'); });
const session = await open({ ...options, completedOutput: { file, validate } }), started = Date.now();
expect(await session.run('Submit fixture.', 'submit-turn', workspace, vi.fn())).toBe('submitted');
expect(Date.now() - started).toBeLessThan(5_000);
expect(options.onUsage).toHaveBeenCalledExactlyOnceWith({ inputTokens: 11, outputTokens: 5, totalTokens: 16,
cachedInputTokens: 2, reasoningOutputTokens: 1 }, { turnId: 'submit-turn' });
expect(options.onUsageIncomplete).not.toHaveBeenCalled();
expect(session.lastError).toBeUndefined(); expect(session.lastCompletedResponse).toBeUndefined();
expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' });
});

it('reaps a detached background writer before freezing sources', async () => {
Expand Down Expand Up @@ -305,7 +320,7 @@ describe('configured headless CLI sessions with isolated local children', () =>
fs.writeFileSync(file, '{"current":true}');
expect(await run).toBe('submitted'); expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' });
expect(options.onUsageIncomplete).toHaveBeenCalledOnce();
});
}, 30_000);

it('shares actual filesystem isolation for arbitrary shell-capable CLI children', async () => {
scenario('isolation'); const hidden = path.join(root, 'hidden'); fs.mkdirSync(hidden);
Expand Down
8 changes: 8 additions & 0 deletions tests/fixtures/claudeCodeProtocolPeer.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ process.stdin.on('end', () => {
return;
}
if (prompt === 'wait') { setInterval(() => {}, 1000); return; }
if (prompt === 'submit-then-result' || prompt === 'submit-then-error') {
// The handoff file lands first; the native result carrying the turn's usage follows, and the writer stays alive.
fs.writeFileSync(path.join(process.cwd(), 'completed.json'), '{"turn":"current","checked":true}');
setTimeout(() => send({ type: 'result', subtype: 'success', is_error: prompt === 'submit-then-error',
result: 'private provider secret', usage }), 400);
setInterval(() => {}, 1000);
return;
}
if (prompt === 'isolation') {
const outcome = {};
try { outcome.hidden = fs.readFileSync(process.env.CLAUDE_PEER_HIDDEN, 'utf8'); } catch { outcome.hidden = 'denied'; }
Expand Down
7 changes: 7 additions & 0 deletions tests/fixtures/cliProtocolPeer.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ process.stdin.on('end', () => {
const id = argument('--resume') || argument('--session-id') || 'native-' + crypto.randomUUID();
const returnedId = scenario === 'foreign-id' ? 'foreign-native-session' : id;
fs.appendFileSync(path.join(profile, 'cli-peer-calls.jsonl'), JSON.stringify({ args, prompt, stdin, promptFile: file,
promptMode: file ? fs.lstatSync(file).mode & 0o777 : undefined,
cwd: process.cwd(), home: process.env.HOME, cache: process.env.XDG_CACHE_HOME, fixtureEnvironment: process.env.CLI_FIXTURE_VALUE }) + '\n');
const send = value => process.stdout.write(JSON.stringify(value) + '\n');
const init = { kind: 'init', ...(scenario !== 'missing-id' ? { session: { id: returnedId } } : {}) };
Expand Down Expand Up @@ -52,6 +53,12 @@ process.stdin.on('end', () => {
if (scenario === 'bad-output-subset') final.stats.reasoning = 6;
if (scenario === 'overflow-usage') final.stats.input = Number.MAX_SAFE_INTEGER;
if (scenario === 'nonzero') { process.stderr.write('private provider secret\n'); process.exitCode = 19; }
if (scenario === 'submit-then-final') {
// The native turn hands off through the completion file, then ends with its usage-bearing final record.
fs.writeFileSync(path.join(process.cwd(), 'completed.json'), '{"current":true}');
setTimeout(() => { if (format === 'json') process.stdout.write(JSON.stringify(final)); else send(final); }, 400);
return;
}
if (format === 'text') process.stdout.write(final.result.text);
else if (format === 'json') process.stdout.write(JSON.stringify(final));
else {
Expand Down
Loading