From 2e161e5e20e7626c1616b0833b675e07bb1e3c32 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:36:25 +0800 Subject: [PATCH] Keep usage from submitting Claude/CLI turns and delete CLI prompt files The Claude Code and configured CLI adapters stopped the writer as soon as a valid completion file appeared, before the native result carrying the turn's usage arrived. Every submitting turn was recorded as usage incomplete, which blocks later dispatches under a finite budget. - After a valid handoff the writer now gets up to 10 s (Codex's cleanup deadline) to finish. Claude stops on its result frame; the CLI's final JSON is parsed after submission. - A validated handoff always resolves 'submitted'; an interrupt or provider error during the grace no longer reads as a failure. - The CLI's per-turn prompt file under .scratch/cli-prompts is removed once the writer has exited instead of accumulating one copy per turn. Co-Authored-By: Claude Opus 5.5 --- src/runtime/claudeCodeSession.ts | 20 ++++++++++----- src/runtime/cliSession.ts | 31 +++++++++++++++-------- tests/claudeCodeSession.test.ts | 13 ++++++++++ tests/cliSession.test.ts | 21 ++++++++++++--- tests/fixtures/claudeCodeProtocolPeer.cjs | 8 ++++++ tests/fixtures/cliProtocolPeer.cjs | 7 +++++ 6 files changed, 81 insertions(+), 19 deletions(-) diff --git a/src/runtime/claudeCodeSession.ts b/src/runtime/claudeCodeSession.ts index 8584ece8..13a0cb50 100644 --- a/src/runtime/claudeCodeSession.ts +++ b/src/runtime/claudeCodeSession.ts @@ -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 { @@ -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(); const incomplete = () => { if (usageReported) return; @@ -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) => { @@ -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) => { @@ -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); diff --git a/src/runtime/cliSession.ts b/src/runtime/cliSession.ts index db6ec69e..2aa7b4ef 100644 --- a/src/runtime/cliSession.ts +++ b/src/runtime/cliSession.ts @@ -17,6 +17,8 @@ import { prepareSealedHarness, sealedRolePath, sealedRoleText } from './sealedHa type Json = Record; 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); @@ -69,7 +71,7 @@ export async function createCliMathSession(options: MathAgentOptions): Promise { interrupted = true; } }; try { assertMathAgentSkillsCurrent(options.skills ?? []); @@ -86,7 +88,6 @@ export async function createCliMathSession(options: MathAgentOptions): Promise 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 }); @@ -117,7 +118,7 @@ export async function createCliMathSession(options: MathAgentOptions): Promise 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; @@ -196,18 +197,22 @@ export async function createCliMathSession(options: MathAgentOptions): Promise {}); @@ -221,7 +226,9 @@ export async function createCliMathSession(options: MathAgentOptions): Promise { void stop(); }, submissionResultGraceMs); } catch { /* Missing, partial, stale or rejected completion files keep the writer running. */ } }, 100); outputWatcher.unref(); @@ -230,7 +237,11 @@ export async function createCliMathSession(options: MathAgentOptions): Promise { 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 () => { diff --git a/tests/cliSession.test.ts b/tests/cliSession.test.ts index cb88c705..54cdd3b0 100644 --- a/tests/cliSession.test.ts +++ b/tests/cliSession.test.ts @@ -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); } }); @@ -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 () => { @@ -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); diff --git a/tests/fixtures/claudeCodeProtocolPeer.cjs b/tests/fixtures/claudeCodeProtocolPeer.cjs index a5939b0f..5f6a55dd 100644 --- a/tests/fixtures/claudeCodeProtocolPeer.cjs +++ b/tests/fixtures/claudeCodeProtocolPeer.cjs @@ -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'; } diff --git a/tests/fixtures/cliProtocolPeer.cjs b/tests/fixtures/cliProtocolPeer.cjs index 25e1603b..db53bfce 100644 --- a/tests/fixtures/cliProtocolPeer.cjs +++ b/tests/fixtures/cliProtocolPeer.cjs @@ -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 } } : {}) }; @@ -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 {