Repository navigation
Expand file tree
/
Copy pathstream.ts
More file actions
719 lines (629 loc) · 25.2 KB
/
Copy pathstream.ts
File metadata and controls
719 lines (629 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
import { type ChildProcessWithoutNullStreams } from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";
import { isDeepStrictEqual } from "node:util";
import {
createAssistantMessageEventStream,
type Api,
type AssistantMessage,
type AssistantMessageEventStream,
type Message,
type Model,
type SimpleStreamOptions,
type StopReason,
type StreamFunction,
type ThinkingLevel,
type ToolCall,
type ToolResultMessage,
type TranscriptContext,
} from "@earendil-works/pi-ai";
import { getCurrentTools } from "@earendil-works/pi-ai/utils/transcript";
import type { AnthropicEffort } from "@earendil-works/pi-ai/api/anthropic-messages";
import { parseStreamingJson, parseToolCallArguments } from "@earendil-works/pi-ai/utils/json-parse";
import { externalCliEnv } from "../../core/auth-env.ts";
import type { LhMessage } from "../../core/native-messages.ts";
import { ClaudeLaunchError, createClaudeLauncher } from "./launch.ts";
import { parseCliLine, type CliBlock, type CliEvent, type CliUsage } from "./cli-events.ts";
import { ClaudeCodeError } from "./constants.ts";
import { ContextWindowProbe } from "./context-window.ts";
import { addLiveProcess, getLiveProcess, removeLiveProcess, type LiveProcess } from "./live-processes.ts";
import { configurationForReuse, conversationForReuse } from "./reuse-context.ts";
import { BRIDGE_SERVER_NAME, createToolBridge, toolNameFromMcp, type PendingToolCall, type ToolBridge } from "./tool-bridge.ts";
import { toClaudeInput, toStreamJsonLine } from "./transcript.ts";
type RunClaudeOptions = { cwd: string; env: NodeJS.ProcessEnv; signal?: AbortSignal };
type ClaudeChild = ChildProcessWithoutNullStreams | null;
export type RunClaude = (args: string[], options: RunClaudeOptions) => ClaudeChild | Promise<ClaudeChild>;
// A held MCP call lasts until pi calls back with the tool result, which for a question tool is
// whenever the learner answers; this must outlast the live-process idle timeout so the CLI never
// times out first.
// A held call sends no progress, so the CLI's separate idle timeout (300 s by default) needs
// the same bound, or it aborts an unanswered question first.
const MCP_TOOL_TIMEOUT_MS = 30 * 60_000;
const PRIVATE_FILE_MODE = 0o600;
const EFFORTS: Record<ThinkingLevel, AnthropicEffort> = {
minimal: "low",
low: "low",
medium: "medium",
high: "high",
xhigh: "xhigh",
max: "max",
};
const STOP_REASONS: Record<string, StopReason> = {
end_turn: "stop",
pause_turn: "stop",
stop_sequence: "stop",
max_tokens: "length",
tool_use: "toolUse",
refusal: "error",
};
const REFUSAL_MESSAGE = "The model refused to complete the request";
const ABORT_MESSAGE = "Request was aborted";
const START_FAILED_MESSAGE = "claude CLI failed to start";
const NO_STOP_REASON_MESSAGE = "claude CLI ended the message without a stop reason";
const NOT_SIGNED_IN_ERROR = "authentication_failed";
export function toEffort(level: ThinkingLevel | undefined): AnthropicEffort {
return level ? EFFORTS[level] : "medium";
}
type ClaudeArgsInput = {
model: string;
effort: AnthropicEffort;
systemPromptFile: string;
mcpConfigFile: string;
allowedTools: string[];
};
export function toClaudeArgs(input: ClaudeArgsInput): string[] {
return [
"-p",
"--input-format",
"stream-json",
"--output-format",
"stream-json",
"--verbose",
"--include-partial-messages",
"--model",
input.model,
"--effort",
input.effort,
"--system-prompt-file",
input.systemPromptFile,
"--tools",
"",
"--strict-mcp-config",
"--mcp-config",
input.mcpConfigFile,
// Keep native user auth/routing, but override its instruction channels.
// Settings env can replace inherited env, so pin the memory switch here too.
"--setting-sources",
"user",
"--settings",
JSON.stringify({ disableAllHooks: true, outputStyle: "default", env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1" } }),
"--disable-slash-commands",
"--no-session-persistence",
"--permission-prompts",
"none",
...(input.allowedTools.length > 0 ? ["--allowedTools", input.allowedTools.join(",")] : []),
];
}
function createOutput(model: Model<Api>): AssistantMessage {
return {
role: "assistant",
content: [],
api: model.api,
provider: model.provider,
model: model.id,
usage: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
stopReason: "pending",
timestamp: Date.now(),
};
}
function getAssistantErrorMessage(error: string, text: string): string {
return error === NOT_SIGNED_IN_ERROR ? ClaudeCodeError.NotSignedIn : text || error;
}
class ClaudeTurn {
private readonly output: AssistantMessage & Pick<LhMessage, "cliContextWindow">;
private readonly contentIndexes = new Map<number, number>();
private readonly partialJson = new Map<number, string>();
private readonly toolBlocks = new Map<number, ToolCall>();
private readonly intents: ToolCall[] = [];
/** The current message called a harness tool by its bare name; the CLI rejects that call itself. */
skippedBareCall = false;
started = false;
finished = false;
constructor(
private readonly stream: AssistantMessageEventStream,
model: Model<Api>,
private readonly harnessToolNames: ReadonlySet<string>,
) {
this.output = createOutput(model);
}
handle(event: CliEvent): void {
if (this.finished) return;
switch (event.type) {
case "messageStart":
this.skippedBareCall = false;
this.updateUsage(event.usage);
this.start();
return;
case "blockStart":
this.startBlock(event.index, event.block);
return;
case "textDelta": {
const found = this.getBlock(event.index);
if (!found) return;
const { contentIndex, block } = found;
if (block.type !== "text") return;
block.text += event.text;
this.stream.push({ type: "text_delta", contentIndex, delta: event.text, partial: this.output });
return;
}
case "thinkingDelta": {
const found = this.getBlock(event.index);
if (!found) return;
const { contentIndex, block } = found;
if (block.type !== "thinking") return;
block.thinking += event.thinking;
this.stream.push({ type: "thinking_delta", contentIndex, delta: event.thinking, partial: this.output });
return;
}
case "toolInputDelta": {
const found = this.getBlock(event.index);
if (!found) return;
const { block } = found;
if (block.type !== "toolCall") return;
const partialJson = (this.partialJson.get(event.index) ?? "") + event.partialJson;
this.partialJson.set(event.index, partialJson);
block.arguments = parseStreamingJson(partialJson);
return;
}
case "blockStop":
this.stopBlock(event.index);
return;
case "messageDelta":
this.updateUsage(event.usage);
if (event.stopReason) this.setStopReason(event.stopReason);
return;
case "messageStop":
// Tool intent is not execution admission. The process publishes only
// calls that actually reach the authenticated MCP bridge.
if (this.output.stopReason !== "toolUse") this.finish();
return;
case "assistantError":
this.fail(getAssistantErrorMessage(event.error, event.text), "error");
return;
case "resultError":
this.fail(event.text, "error");
return;
}
}
get waitingForAdmission(): boolean { return !this.finished && this.output.stopReason === "toolUse"; }
getIntents(): ToolCall[] { return this.intents; }
getMessage(): AssistantMessage { return this.output; }
setContextWindow(tokens: number | undefined): void {
if (!this.finished && tokens !== undefined) this.output.cliContextWindow = tokens;
}
admit(calls: ToolCall[]): void {
this.start();
for (const call of calls) {
const contentIndex = this.output.content.length;
this.output.content.push(call);
this.stream.push({ type: "toolcall_start", contentIndex, partial: this.output });
this.stream.push({ type: "toolcall_end", contentIndex, toolCall: call, partial: this.output });
}
this.output.stopReason = "toolUse";
this.finish();
}
fail(message: string, reason: "aborted" | "error"): void {
if (this.finished) return;
this.finished = true;
this.output.stopReason = reason;
this.output.errorMessage = message;
this.stream.push({ type: "error", reason, error: this.output });
this.stream.end();
}
private start(): void {
if (this.started) return;
this.started = true;
this.stream.push({ type: "start", partial: this.output });
}
private startBlock(index: number, block: CliBlock): void {
const contentIndex = this.output.content.length;
this.contentIndexes.set(index, contentIndex);
switch (block.type) {
case "text":
this.output.content.push({ type: "text", text: "" });
this.stream.push({ type: "text_start", contentIndex, partial: this.output });
return;
case "thinking":
this.output.content.push({ type: "thinking", thinking: "" });
this.stream.push({ type: "thinking_start", contentIndex, partial: this.output });
return;
case "toolUse":
if (!block.name.startsWith(`mcp__${BRIDGE_SERVER_NAME}__`)) {
// Models sometimes call a harness tool by its bare name. With --tools "" the CLI has no such
// tool, answers it with an error result and the model retries under the MCP name.
if (this.harnessToolNames.has(block.name)) {
this.skippedBareCall = true;
return;
}
this.fail("claude CLI emitted an unsupported native tool call", "error");
return;
}
this.toolBlocks.set(index, { type: "toolCall", id: block.id, name: toolNameFromMcp(block.name), arguments: {} });
return;
}
}
private getBlock(index: number): { contentIndex: number; block: AssistantMessage["content"][number] } | null {
const tool = this.toolBlocks.get(index);
if (tool) return { contentIndex: -1, block: tool };
const contentIndex = this.contentIndexes.get(index);
if (contentIndex === undefined) return null;
const block = this.output.content[contentIndex];
return block ? { contentIndex, block } : null;
}
private stopBlock(index: number): void {
const found = this.getBlock(index);
if (!found) return;
const { contentIndex, block } = found;
this.contentIndexes.delete(index);
switch (block.type) {
case "text":
this.stream.push({ type: "text_end", contentIndex, content: block.text, partial: this.output });
return;
case "thinking":
this.stream.push({ type: "thinking_end", contentIndex, content: block.thinking, partial: this.output });
return;
case "toolCall":
Object.assign(block, parseToolCallArguments(this.partialJson.get(index) ?? ""));
this.partialJson.delete(index);
this.toolBlocks.delete(index);
this.intents.push(block);
return;
}
}
private updateUsage(usage: CliUsage): void {
Object.assign(this.output.usage, usage);
const { input, output, cacheRead, cacheWrite } = this.output.usage;
this.output.usage.totalTokens = input + output + cacheRead + cacheWrite;
}
private setStopReason(stopReason: string): void {
const mapped = STOP_REASONS[stopReason];
if (!mapped) {
this.output.stopReason = "error";
this.output.errorMessage = `Unhandled stop reason: ${stopReason}`;
return;
}
this.output.stopReason = mapped;
}
private finish(): void {
const { stopReason } = this.output;
if (stopReason === "error") {
this.fail(this.output.errorMessage ?? REFUSAL_MESSAGE, "error");
return;
}
if (stopReason === "pending" || stopReason === "aborted") {
this.fail(this.output.errorMessage ?? NO_STOP_REASON_MESSAGE, "error");
return;
}
this.finished = true;
this.stream.push({ type: "done", reason: stopReason, message: this.output });
this.stream.end();
}
}
type TurnFiles = { cwd: string; privateDir: string; systemPromptFile: string; mcpConfigFile: string };
async function createTurnFiles(systemPrompt: string, mcpConfig: string): Promise<TurnFiles> {
const cwd = await mkdtemp(join(tmpdir(), "claude-code-cwd-"));
let privateDir: string | undefined;
try {
privateDir = await mkdtemp(join(tmpdir(), "claude-code-private-"));
const systemPromptFile = join(privateDir, "system-prompt.md");
const mcpConfigFile = join(privateDir, "mcp.json");
await writeFile(systemPromptFile, systemPrompt, { mode: PRIVATE_FILE_MODE });
await writeFile(mcpConfigFile, mcpConfig, { mode: PRIVATE_FILE_MODE });
return { cwd, privateDir, systemPromptFile, mcpConfigFile };
} catch (error) {
await Promise.all([rm(cwd, { recursive: true, force: true }), ...(privateDir ? [rm(privateDir, { recursive: true, force: true })] : [])]);
throw error;
}
}
async function removeTurnResources(bridge: ToolBridge, files: TurnFiles): Promise<void> {
await Promise.all([
bridge.close(),
rm(files.cwd, { recursive: true, force: true }),
rm(files.privateDir, { recursive: true, force: true }),
]);
}
class ClaudeProcess implements LiveProcess {
toolCallIds: string[] = [];
private stderr = "";
private closed = false;
private stopping = false;
private killTimer: NodeJS.Timeout | undefined;
private signal: AbortSignal | undefined;
private sourceCalls: ToolCall[] = [];
private sourceComplete = false;
private admitted: PendingToolCall[] = [];
private readonly cancelledIds = new Set<string>();
private pendingError: string | undefined;
private contextWindow: number | undefined;
private contextProbe: ContextWindowProbe | undefined;
constructor(
private readonly child: ChildProcessWithoutNullStreams,
private readonly bridge: ToolBridge,
private readonly files: TurnFiles,
private turn: ClaudeTurn,
readonly owner: symbol,
readonly sessionId: string | undefined,
private readonly configuration: unknown,
private conversation: unknown[],
) {}
start(stdinLine: string, signal: AbortSignal | undefined): void {
this.child.once("close", (code: number | null) => this.handleClose(`claude CLI exited with code ${code}`));
this.child.once("error", (error) => {
console.error("claude CLI process failed:", error);
this.turn.fail(START_FAILED_MESSAGE, "error");
this.handleClose(START_FAILED_MESSAGE);
});
this.child.stderr.setEncoding("utf8");
this.child.stderr.on("data", (chunk: string) => { this.stderr = (this.stderr + chunk).slice(-65_536); });
this.child.stdin.on("error", (error) => console.error("claude CLI stdin closed early:", error));
this.contextProbe = new ContextWindowProbe(
(line) => this.child.stdin.write(`${line}\n`),
() => { if (!this.stopping) this.child.stdin.write(`${stdinLine}\n`); },
(tokens) => { this.contextWindow = tokens; this.turn.setContextWindow(tokens); },
);
createInterface({ input: this.child.stdout }).on("line", (line) => {
try { this.handleLine(line); }
catch { this.fail("claude CLI emitted malformed stream output"); }
});
this.setSignal(signal);
if (!this.stopping) this.contextProbe.start();
}
canContinue(owner: symbol, sessionId: string | undefined, configuration: unknown, messages: Message[], results: ToolResultMessage[]): boolean {
const conversation = conversationForReuse(messages);
return !this.stopping && owner === this.owner && !!sessionId && sessionId === this.sessionId
&& isDeepStrictEqual(configuration, this.configuration)
&& isDeepStrictEqual(conversation.slice(0, this.conversation.length), this.conversation)
&& conversation.length === this.conversation.length + this.admitted.length
&& results.length === this.admitted.length
&& new Set(results.map((result) => result.toolCallId)).size === results.length
&& this.admitted.every((call) => results.some((result) => result.toolCallId === call.id && result.toolName === call.name));
}
continueTurn(turn: ClaudeTurn, messages: Message[], results: ToolResultMessage[], signal: AbortSignal | undefined): void {
removeLiveProcess(this);
const admitted = this.admitted;
this.admitted = [];
this.conversation = structuredClone(conversationForReuse(messages));
this.turn = turn;
this.turn.setContextWindow(this.contextWindow);
this.sourceComplete = this.sourceCalls.length > 0;
this.setSignal(signal);
if (this.stopping) return;
for (const call of admitted) {
const result = results.find((candidate) => candidate.toolCallId === call.id)!;
this.bridge.resolveToolCall(call, result);
}
this.flushAdmissions();
}
kill(): void {
removeLiveProcess(this);
if (this.stopping || this.closed) return;
this.stopping = true;
this.contextProbe?.close();
this.child.kill();
this.killTimer = setTimeout(() => this.child.kill("SIGKILL"), 1000);
this.killTimer.unref();
}
fail(message: string): void {
// A parallel request can fail after the admitted slice was handed to
// Pi. Retain that failure for its continuation instead of silently
// replaying and hiding the compatibility error.
if (this.sessionId && this.turn.finished && this.toolCallIds.length > 0) this.pendingError = message;
this.turn.fail(message, "error");
this.kill();
if (this.pendingError) addLiveProcess(this);
}
consumeFailure(owner: symbol, turn: ClaudeTurn): boolean {
if (owner !== this.owner || !this.pendingError) return false;
const message = this.pendingError;
this.pendingError = undefined;
this.kill();
turn.fail(message, "error");
return true;
}
cancelCall(call: PendingToolCall): void {
this.cancelledIds.add(call.id);
// Already admitted work belongs to Pi and cannot be undone. A queued
// request, however, must never become executable after cancellation.
this.sourceCalls = this.sourceCalls.filter((intent) => intent.id !== call.id);
}
/** Only authenticated MCP requests, never stdout intent alone, admit side effects. */
flushAdmissions(): void {
if (this.stopping || this.turn.finished || !this.sourceComplete) return;
const pending = this.bridge.getPendingToolCalls();
if (pending.length === 0) return;
const calls: ToolCall[] = [];
for (const call of pending) {
const intent = this.sourceCalls.find((candidate) => candidate.id === call.id);
if (!intent || intent.name !== call.name || !isDeepStrictEqual(intent.arguments, call.arguments)) {
this.fail("claude CLI compatibility error: MCP call does not match its streamed tool intent");
return;
}
calls.push(intent);
}
this.sourceCalls = this.sourceCalls.filter((call) => !pending.some((admitted) => admitted.id === call.id));
this.admitted = pending;
this.toolCallIds = pending.map((call) => call.id);
this.turn.admit(calls);
this.conversation.push(...structuredClone(conversationForReuse([this.turn.getMessage()])));
if (this.sessionId) addLiveProcess(this);
else this.kill(); // No trusted scope: return the batch, then use fresh replay.
}
private readonly abort = () => {
this.turn.fail(ABORT_MESSAGE, "aborted");
this.kill();
};
private setSignal(signal: AbortSignal | undefined): void {
this.signal?.removeEventListener("abort", this.abort);
this.signal = signal;
signal?.addEventListener("abort", this.abort, { once: true });
if (signal?.aborted) this.abort();
}
private handleLine(line: string): void {
if (this.stopping || !line.trim()) return;
if (this.contextProbe?.handle(JSON.parse(line))) return;
const event = parseCliLine(line);
if (!event) return;
if (event.type === "toolResults") {
if (event.ids.some((id) => this.sourceCalls.some((call) => call.id === id))) {
this.fail("claude CLI refused a harness tool call before MCP admission");
}
return;
}
// Moving on before held calls were answered means the CLI did not
// honor this tool wait. Never execute further stdout-only intentions.
if (this.turn.finished) {
this.fail("claude CLI moved on while harness tool calls were waiting for results");
return;
}
if (event.type === "messageStart" && this.sourceComplete && this.sourceCalls.length > 0) {
this.fail("claude CLI moved on without admitting its harness tool calls");
return;
}
if (event.type === "messageStart") this.contextProbe?.refresh();
this.turn.handle(event);
if (this.turn.finished) { this.kill(); return; }
if (event.type === "messageStop" && this.turn.waitingForAdmission) {
const intents = this.turn.getIntents();
// Only rejected bare calls: keep the turn open for the model's retry in its next message.
if (intents.length === 0 && this.turn.skippedBareCall) return;
if (intents.length === 0 || new Set(intents.map((call) => call.id)).size !== intents.length) {
this.fail("claude CLI emitted an invalid tool batch");
return;
}
this.sourceCalls = intents.filter((call) => !this.cancelledIds.has(call.id));
this.sourceComplete = true;
this.flushAdmissions();
}
}
private handleClose(message: string): void {
if (this.closed) return;
this.closed = true;
this.contextProbe?.close();
clearTimeout(this.killTimer);
removeLiveProcess(this);
if (this.pendingError) addLiveProcess(this);
this.signal?.removeEventListener("abort", this.abort);
if (this.stderr.trim()) console.error("claude CLI stderr:", this.stderr.trim());
this.turn.fail(message, "error");
removeTurnResources(this.bridge, this.files).catch((error: unknown) => {
console.error("claude CLI cleanup failed:", error);
});
}
}
function continueLiveProcess(turn: ClaudeTurn, owner: symbol, sessionId: string | undefined, configuration: unknown, messages: Message[], signal: AbortSignal | undefined): boolean {
const assistantIndex = messages.findLastIndex((message) => message.role === "assistant");
const assistant = messages[assistantIndex];
if (assistant?.role !== "assistant") return false;
const ids = assistant.content.flatMap((block) => block.type === "toolCall" ? [block.id] : []);
const process = getLiveProcess(ids, owner, sessionId);
if (!(process instanceof ClaudeProcess)) return false;
if (process.consumeFailure(owner, turn)) return true;
const trailing = messages.slice(assistantIndex + 1);
const results = trailing.filter((message) => message.role === "toolResult");
if (trailing.length !== results.length || !process.canContinue(owner, sessionId, configuration, messages, results)) {
process.kill();
return false;
}
process.continueTurn(turn, messages, results, signal);
return true;
}
function toClaudeEnv(): NodeJS.ProcessEnv {
// Preserve native CLI auth/routing, including launch-environment credentials.
// Claude Code chooses the account and billing method, not LearnHarness.
// Loading user settings also loads ~/.claude/CLAUDE.md and memory files;
// the tutor's system prompt must not inherit them.
return {
...externalCliEnv(),
MCP_TOOL_TIMEOUT: String(MCP_TOOL_TIMEOUT_MS),
CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT: String(MCP_TOOL_TIMEOUT_MS),
CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1",
};
}
async function startProcess(
runClaude: RunClaude,
turn: ClaudeTurn,
model: Model<Api>,
context: TranscriptContext,
options: SimpleStreamOptions | undefined,
owner: symbol,
configuration: unknown,
env: NodeJS.ProcessEnv,
): Promise<void> {
if (options?.signal?.aborted) { turn.fail(ABORT_MESSAGE, "aborted"); return; }
const input = toClaudeInput(context.messages);
let cliProcess: ClaudeProcess | undefined;
const bridge = await createToolBridge(input.tools, {
onCall: () => cliProcess?.flushAdmissions(),
onError: (error) => cliProcess?.fail(error.message),
onCancel: (call) => cliProcess?.cancelCall(call),
});
let files: TurnFiles;
try {
files = await createTurnFiles(input.systemPrompt, bridge.mcpConfig);
} catch (error) {
await bridge.close();
throw error;
}
if (options?.signal?.aborted) {
turn.fail(ABORT_MESSAGE, "aborted");
await removeTurnResources(bridge, files);
return;
}
let child: ChildProcessWithoutNullStreams | null;
try {
const args = toClaudeArgs({
model: model.id,
effort: toEffort(options?.reasoning),
systemPromptFile: files.systemPromptFile,
mcpConfigFile: files.mcpConfigFile,
allowedTools: bridge.allowedTools,
});
child = await runClaude(args, { cwd: files.cwd, env, signal: options?.signal });
} catch (error) {
await removeTurnResources(bridge, files);
throw error;
}
if (!child) {
turn.fail(ClaudeCodeError.CliNotFound, "error");
await removeTurnResources(bridge, files);
return;
}
cliProcess = new ClaudeProcess(child, bridge, files, turn, owner, options?.sessionId, configuration, structuredClone(conversationForReuse(context.messages)));
cliProcess.start(toStreamJsonLine(input.userContent), options?.signal);
}
export function createClaudeCodeStreamFunction(runClaude: RunClaude): StreamFunction<Api, SimpleStreamOptions> {
const owner = Symbol("claude-code stream owner");
return (model, context, options) => {
const stream = createAssistantMessageEventStream();
const turn = new ClaudeTurn(stream, model, new Set(getCurrentTools(context.messages).map((tool) => tool.name)));
const env = toClaudeEnv();
// An existing child must not retain stale authentication/routing after env changes.
const configuration = { request: configurationForReuse(model, context, toEffort(options?.reasoning)), env };
if (continueLiveProcess(turn, owner, options?.sessionId, configuration, context.messages, options?.signal)) return stream;
startProcess(runClaude, turn, model, context, options, owner, configuration, env).catch((error: unknown) => {
console.error("claude CLI turn failed:", error);
turn.fail(options?.signal?.aborted ? ABORT_MESSAGE : error instanceof ClaudeLaunchError ? error.message : START_FAILED_MESSAGE, options?.signal?.aborted ? "aborted" : "error");
});
return stream;
};
}
export const streamClaudeCode = createClaudeCodeStreamFunction(createClaudeLauncher());