@ai-sdk/harness-claude-code 0.0.0 → 1.0.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1536 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { fileURLToPath } from 'node:url';
4
+ import {
5
+ commonTool,
6
+ harnessV1DiagnosticFromBridgeFrame,
7
+ HarnessCapabilityUnsupportedError,
8
+ type HarnessV1,
9
+ type HarnessV1Bootstrap,
10
+ type HarnessV1DebugConfig,
11
+ type HarnessV1BuiltinTool,
12
+ type HarnessV1ContinueTurnState,
13
+ type HarnessV1PermissionMode,
14
+ type HarnessV1Prompt,
15
+ type HarnessV1PromptControl,
16
+ type HarnessV1ResumeSessionState,
17
+ type HarnessV1NetworkSandboxSession,
18
+ type HarnessV1Session,
19
+ type HarnessV1Skill,
20
+ type HarnessV1StreamPart,
21
+ } from '@ai-sdk/harness';
22
+ import { classifyDiskLog, SandboxChannel } from '@ai-sdk/harness/utils';
23
+ import {
24
+ safeParseJSON,
25
+ tool,
26
+ type Experimental_SandboxSession,
27
+ type Experimental_SandboxProcess,
28
+ } from '@ai-sdk/provider-utils';
29
+ import { WebSocket } from 'ws';
30
+ import { z } from 'zod';
31
+ import {
32
+ resolveClaudeCodeEnv,
33
+ type ClaudeCodeAuthOptions,
34
+ } from './claude-code-auth';
35
+ import {
36
+ bridgeReadySchema,
37
+ outboundMessageSchema,
38
+ type InboundMessage,
39
+ type OutboundMessage,
40
+ } from './claude-code-bridge-protocol';
41
+
42
+ type ClaudeCodeChannel = SandboxChannel<OutboundMessage, InboundMessage>;
43
+ type ClaudeCodeRespawnStrategy = 'replay' | 'rerun';
44
+
45
+ export type ClaudeCodeHarnessSettings = {
46
+ readonly auth?: ClaudeCodeAuthOptions;
47
+ /**
48
+ * Anthropic model id the underlying `claude` CLI should use. Leaving this
49
+ * unset defers to the CLI's default.
50
+ */
51
+ readonly model?: string;
52
+ /**
53
+ * Hard cap on how many internal turns the CLI can take before yielding
54
+ * back to the caller. Unset means the CLI's default.
55
+ */
56
+ readonly maxTurns?: number;
57
+ /**
58
+ * Controls extended-thinking behavior. `'off'` disables thinking,
59
+ * `'on'` forces it on, `'adaptive'` lets the runtime decide.
60
+ */
61
+ readonly thinking?: 'off' | 'on' | 'adaptive';
62
+ /**
63
+ * Override the port the bridge binds inside the sandbox. By default the
64
+ * adapter uses the first port the sandbox declares via `sandbox.ports`.
65
+ * Only set this if the sandbox declares multiple ports and the first one
66
+ * is reserved for something else.
67
+ */
68
+ readonly port?: number;
69
+ /** Maximum milliseconds to wait for the bridge to advertise its port. Defaults to 120000. */
70
+ readonly startupTimeoutMs?: number;
71
+ };
72
+
73
+ /*
74
+ * Every native tool the Claude Code CLI can invoke, declared as a `ToolSet`
75
+ * keyed by what the bridge emits as `toolName` on the wire
76
+ * (`commonName ?? nativeName`). Schemas transcribed from
77
+ * `@anthropic-ai/claude-agent-sdk`'s `agentSdkTypes.d.ts`.
78
+ *
79
+ * `MCP` (the generic proxy tool inside the Claude Code SDK) is intentionally
80
+ * omitted — the bridge filters out `mcp__harness-tools__*` tool names before
81
+ * emitting them, and other MCP invocations come through with their own
82
+ * server-tool names rather than the literal `'Mcp'` token.
83
+ */
84
+ const CLAUDE_CODE_BUILTIN_TOOLS = {
85
+ read: commonTool('read', {
86
+ nativeName: 'Read',
87
+ toolUseKind: 'readonly',
88
+ description: 'Read file contents (text, image, PDF, notebook)',
89
+ inputSchema: z.object({
90
+ file_path: z.string(),
91
+ offset: z.number().optional(),
92
+ limit: z.number().optional(),
93
+ pages: z.string().optional(),
94
+ }),
95
+ }),
96
+ write: commonTool('write', {
97
+ nativeName: 'Write',
98
+ toolUseKind: 'edit',
99
+ description: 'Overwrite or create a file at an absolute path',
100
+ inputSchema: z.object({
101
+ file_path: z.string(),
102
+ content: z.string(),
103
+ }),
104
+ }),
105
+ edit: commonTool('edit', {
106
+ nativeName: 'Edit',
107
+ toolUseKind: 'edit',
108
+ description: 'Edit a file by exact string replacement',
109
+ inputSchema: z.object({
110
+ file_path: z.string(),
111
+ old_string: z.string(),
112
+ new_string: z.string(),
113
+ replace_all: z.boolean().optional(),
114
+ }),
115
+ }),
116
+ bash: commonTool('bash', {
117
+ nativeName: 'Bash',
118
+ toolUseKind: 'bash',
119
+ description: 'Execute a shell command, optionally in background',
120
+ inputSchema: z.object({
121
+ command: z.string(),
122
+ timeout: z.number().optional(),
123
+ description: z.string().optional(),
124
+ run_in_background: z.boolean().optional(),
125
+ dangerouslyDisableSandbox: z.boolean().optional(),
126
+ }),
127
+ }),
128
+ glob: commonTool('glob', {
129
+ nativeName: 'Glob',
130
+ toolUseKind: 'readonly',
131
+ description: 'Fast file-pattern search using glob syntax',
132
+ inputSchema: z.object({
133
+ pattern: z.string(),
134
+ path: z.string().optional(),
135
+ }),
136
+ }),
137
+ grep: commonTool('grep', {
138
+ nativeName: 'Grep',
139
+ toolUseKind: 'readonly',
140
+ description: 'Regex search over file contents via ripgrep',
141
+ inputSchema: z.object({
142
+ pattern: z.string(),
143
+ path: z.string().optional(),
144
+ glob: z.string().optional(),
145
+ output_mode: z
146
+ .enum(['content', 'files_with_matches', 'count'])
147
+ .optional(),
148
+ '-B': z.number().optional(),
149
+ '-A': z.number().optional(),
150
+ '-C': z.number().optional(),
151
+ context: z.number().optional(),
152
+ '-n': z.boolean().optional(),
153
+ '-i': z.boolean().optional(),
154
+ '-o': z.boolean().optional(),
155
+ type: z.string().optional(),
156
+ head_limit: z.number().optional(),
157
+ offset: z.number().optional(),
158
+ multiline: z.boolean().optional(),
159
+ }),
160
+ }),
161
+ webSearch: commonTool('webSearch', {
162
+ nativeName: 'WebSearch',
163
+ toolUseKind: 'readonly',
164
+ description: 'Issue web search queries with optional domain filters',
165
+ inputSchema: z.object({
166
+ query: z.string(),
167
+ allowed_domains: z.array(z.string()).optional(),
168
+ blocked_domains: z.array(z.string()).optional(),
169
+ }),
170
+ }),
171
+
172
+ WebFetch: tool({
173
+ description: 'Fetch a URL and run a prompt against its content',
174
+ inputSchema: z.object({
175
+ url: z.string(),
176
+ prompt: z.string(),
177
+ }),
178
+ }),
179
+ NotebookEdit: tool({
180
+ description: 'Edit, insert, or delete a Jupyter notebook cell',
181
+ inputSchema: z.object({
182
+ notebook_path: z.string(),
183
+ new_source: z.string(),
184
+ cell_id: z.string().optional(),
185
+ cell_type: z.enum(['code', 'markdown']).optional(),
186
+ edit_mode: z.enum(['replace', 'insert', 'delete']).optional(),
187
+ }),
188
+ }),
189
+ TodoWrite: tool({
190
+ description: 'Replace the session todo list',
191
+ inputSchema: z.object({
192
+ todos: z.array(
193
+ z.object({
194
+ content: z.string(),
195
+ status: z.enum(['pending', 'in_progress', 'completed']),
196
+ activeForm: z.string(),
197
+ }),
198
+ ),
199
+ }),
200
+ }),
201
+ Agent: tool({
202
+ description: 'Spawn a subagent with a task',
203
+ inputSchema: z.object({
204
+ description: z.string(),
205
+ prompt: z.string(),
206
+ subagent_type: z.string().optional(),
207
+ model: z.enum(['sonnet', 'opus', 'haiku']).optional(),
208
+ run_in_background: z.boolean().optional(),
209
+ name: z.string().optional(),
210
+ team_name: z.string().optional(),
211
+ mode: z
212
+ .enum([
213
+ 'acceptEdits',
214
+ 'auto',
215
+ 'bypassPermissions',
216
+ 'default',
217
+ 'dontAsk',
218
+ 'plan',
219
+ ])
220
+ .optional(),
221
+ isolation: z.literal('worktree').optional(),
222
+ }),
223
+ }),
224
+ TaskCreate: tool({
225
+ description: 'Create a task in the session-local task list',
226
+ inputSchema: z.object({
227
+ subject: z.string(),
228
+ description: z.string(),
229
+ activeForm: z.string().optional(),
230
+ metadata: z.record(z.unknown()).optional(),
231
+ }),
232
+ }),
233
+ TaskGet: tool({
234
+ description: 'Retrieve a task by id',
235
+ inputSchema: z.object({ taskId: z.string() }),
236
+ }),
237
+ TaskUpdate: tool({
238
+ description: 'Update fields of an existing task',
239
+ inputSchema: z.object({
240
+ taskId: z.string(),
241
+ subject: z.string().optional(),
242
+ description: z.string().optional(),
243
+ activeForm: z.string().optional(),
244
+ status: z
245
+ .union([
246
+ z.enum(['pending', 'in_progress', 'completed']),
247
+ z.literal('deleted'),
248
+ ])
249
+ .optional(),
250
+ addBlocks: z.array(z.string()).optional(),
251
+ addBlockedBy: z.array(z.string()).optional(),
252
+ owner: z.string().optional(),
253
+ metadata: z.record(z.unknown()).optional(),
254
+ }),
255
+ }),
256
+ TaskList: tool({
257
+ description: 'Return all tasks in the session-local task list',
258
+ inputSchema: z.object({}),
259
+ }),
260
+ TaskStop: tool({
261
+ description: 'Stop a running background task by id',
262
+ inputSchema: z.object({
263
+ task_id: z.string().optional(),
264
+ shell_id: z.string().optional(),
265
+ }),
266
+ }),
267
+ TaskOutput: tool({
268
+ description: 'Poll for output from a background task',
269
+ inputSchema: z.object({
270
+ task_id: z.string(),
271
+ block: z.boolean(),
272
+ timeout: z.number(),
273
+ }),
274
+ }),
275
+ ListMcpResources: tool({
276
+ description: 'List resources available from MCP servers',
277
+ inputSchema: z.object({ server: z.string().optional() }),
278
+ }),
279
+ ReadMcpResource: tool({
280
+ description: 'Read a specific MCP resource by URI',
281
+ inputSchema: z.object({ server: z.string(), uri: z.string() }),
282
+ }),
283
+ ExitPlanMode: tool({
284
+ description: 'Exit plan mode with optional permission approvals',
285
+ inputSchema: z
286
+ .object({
287
+ allowedPrompts: z
288
+ .array(
289
+ z.object({
290
+ tool: z.literal('Bash'),
291
+ prompt: z.string(),
292
+ }),
293
+ )
294
+ .optional(),
295
+ })
296
+ .passthrough(),
297
+ }),
298
+ EnterWorktree: tool({
299
+ description: 'Create or enter an isolated git worktree',
300
+ inputSchema: z.object({
301
+ name: z.string().optional(),
302
+ path: z.string().optional(),
303
+ }),
304
+ }),
305
+ ExitWorktree: tool({
306
+ description: 'Exit the current worktree session',
307
+ inputSchema: z.object({
308
+ action: z.enum(['keep', 'remove']),
309
+ discard_changes: z.boolean().optional(),
310
+ }),
311
+ }),
312
+ AskUserQuestion: tool({
313
+ description: 'Ask the user multiple-choice questions via a structured UI',
314
+ inputSchema: z.object({
315
+ questions: z
316
+ .array(
317
+ z.object({
318
+ question: z.string(),
319
+ header: z.string(),
320
+ options: z.array(
321
+ z.object({
322
+ label: z.string(),
323
+ description: z.string(),
324
+ preview: z.string().optional(),
325
+ }),
326
+ ),
327
+ multiSelect: z.boolean(),
328
+ }),
329
+ )
330
+ .min(1)
331
+ .max(4),
332
+ answers: z.record(z.string()).optional(),
333
+ annotations: z
334
+ .record(
335
+ z.object({
336
+ preview: z.string().optional(),
337
+ notes: z.string().optional(),
338
+ }),
339
+ )
340
+ .optional(),
341
+ metadata: z.object({ source: z.string().optional() }).optional(),
342
+ }),
343
+ }),
344
+ Skill: tool({
345
+ description: 'Activate a skill by name',
346
+ inputSchema: z.object({
347
+ skill: z.string(),
348
+ args: z.string().optional(),
349
+ }),
350
+ }),
351
+ } as const satisfies Record<string, HarnessV1BuiltinTool<any, any>>;
352
+
353
+ /*
354
+ * Bootstrap lives in /tmp because it's pure derived state — the harness can
355
+ * reinstall the CLI and bridge files on any fresh sandbox from the recipe.
356
+ * Persistence comes from the sandbox provider's snapshot, not the path.
357
+ *
358
+ * The session work dir (`startOpts.sessionWorkDir`) and the bridge-state dir
359
+ * derived from `sandboxSession.defaultWorkingDirectory` both live under the sandbox's
360
+ * default working directory — the provider's persistent mount — so the
361
+ * workdir's CLI state (Claude's `~/.claude/projects/<dir>/*.jsonl` thread
362
+ * history is keyed by working directory) and the bridge state files survive
363
+ * both detach -> attach/replay and stop -> snapshot -> resume cycles.
364
+ */
365
+ const BOOTSTRAP_DIR = '/tmp/harness/claude-code';
366
+
367
+ /**
368
+ * Live bridge coordinates returned by `doDetach()` and `doSuspendTurn()`. A
369
+ * future process uses them to reopen a socket to the still-running bridge
370
+ * (`attach`) instead of re-spawning it. Absent on a `doStop()` payload.
371
+ */
372
+ const bridgeCoordsSchema = z.object({
373
+ port: z.number(),
374
+ token: z.string(),
375
+ lastSeenEventId: z.number(),
376
+ sandboxId: z.string().optional(),
377
+ });
378
+
379
+ /**
380
+ * Schema for the adapter-specific portion of lifecycle state `data`.
381
+ *
382
+ * A `doStop()` payload is structurally empty (`{}`): the framework derives the
383
+ * sandbox via `provider.resumeSession({ sessionId })`, and the Claude SDK's
384
+ * `{ continue: true }` flag rehydrates the thread from the workdir. A
385
+ * `doDetach()` payload additionally carries `bridge` coordinates for
386
+ * cross-process `attach`. `.passthrough()` keeps both shapes valid.
387
+ */
388
+ const claudeCodeResumeStateSchema = z
389
+ .object({ bridge: bridgeCoordsSchema.optional() })
390
+ .passthrough();
391
+
392
+ type ClaudeCodeBridgeCoords = z.infer<typeof bridgeCoordsSchema>;
393
+
394
+ export function createClaudeCode(
395
+ settings: ClaudeCodeHarnessSettings = {},
396
+ ): HarnessV1<typeof CLAUDE_CODE_BUILTIN_TOOLS> {
397
+ let cachedBootstrap: HarnessV1Bootstrap | undefined;
398
+
399
+ return {
400
+ specificationVersion: 'harness-v1',
401
+ harnessId: 'claude-code',
402
+ builtinTools: CLAUDE_CODE_BUILTIN_TOOLS,
403
+ supportsBuiltinToolApprovals: true,
404
+ lifecycleStateSchema: claudeCodeResumeStateSchema,
405
+ getBootstrap: async () => {
406
+ if (cachedBootstrap != null) return cachedBootstrap;
407
+ const [pkg, lock, bridge] = await Promise.all([
408
+ readBridgeAsset('package.json'),
409
+ readBridgeAsset('pnpm-lock.yaml'),
410
+ readBridgeAsset('index.mjs'),
411
+ ]);
412
+ cachedBootstrap = {
413
+ harnessId: 'claude-code',
414
+ bootstrapDir: BOOTSTRAP_DIR,
415
+ files: [
416
+ { path: `${BOOTSTRAP_DIR}/package.json`, content: pkg },
417
+ { path: `${BOOTSTRAP_DIR}/pnpm-lock.yaml`, content: lock },
418
+ { path: `${BOOTSTRAP_DIR}/bridge.mjs`, content: bridge },
419
+ ],
420
+ commands: [
421
+ { command: `mkdir -p ${BOOTSTRAP_DIR}` },
422
+ {
423
+ command: `pnpm --dir ${BOOTSTRAP_DIR} install --frozen-lockfile --store-dir ${BOOTSTRAP_DIR}/.pnpm-store`,
424
+ },
425
+ {
426
+ command: `cd ${BOOTSTRAP_DIR} && if [ -f node_modules/@anthropic-ai/claude-code/install.cjs ]; then node node_modules/@anthropic-ai/claude-code/install.cjs; fi && ./node_modules/.bin/claude --version`,
427
+ },
428
+ ],
429
+ };
430
+ return cachedBootstrap;
431
+ },
432
+ doStart: async startOpts => {
433
+ const sandboxSession = startOpts.sandboxSession;
434
+ const session = sandboxSession.restricted();
435
+ const sandboxId = sandboxSession.id;
436
+ const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
437
+ const isResume = lifecycleState != null;
438
+ const isContinue = startOpts.continueFrom != null;
439
+ const coords = isResume
440
+ ? (lifecycleState?.data as { bridge?: ClaudeCodeBridgeCoords })?.bridge
441
+ : undefined;
442
+
443
+ const workDir = startOpts.sessionWorkDir;
444
+ const sessionDataDir = `${sandboxSession.defaultWorkingDirectory}/.agent-runs/${startOpts.sessionId}`;
445
+ const bridgeStateDir = `${sessionDataDir}/bridge`;
446
+ const timeoutMs = settings.startupTimeoutMs ?? 120_000;
447
+
448
+ // Normalize each forwarded bridge diagnostics frame into the general
449
+ // `HarnessV1Diagnostic` and report it. The adapter does no telemetry work
450
+ // beyond this transport→emission mapping.
451
+ const report = startOpts.observability?.report;
452
+ const onDiagnostic = report
453
+ ? (frame: Parameters<typeof harnessV1DiagnosticFromBridgeFrame>[0]) =>
454
+ report(
455
+ harnessV1DiagnosticFromBridgeFrame(frame, {
456
+ sessionId: startOpts.sessionId,
457
+ timestamp: Date.now(),
458
+ }),
459
+ )
460
+ : undefined;
461
+
462
+ // Builds the `connect` thunk a `SandboxChannel` re-invokes on every
463
+ // (re)connect: open the socket, then wait for `bridge-hello` so the
464
+ // end-to-end link is proven live before any frame is sent.
465
+ const buildConnect = (wsUrl: string) => async (): Promise<WebSocket> => {
466
+ return openBridgeWebSocket({ wsUrl, timeoutMs });
467
+ };
468
+
469
+ /*
470
+ * Rung 1 — ATTACH. When lifecycle state carries live bridge coordinates,
471
+ * try to reopen a socket to the still-running bridge. Parked sessions wait
472
+ * for the next `start`; suspended turns request replay of everything past
473
+ * the persisted cursor. No spawn, no fresh token (the existing bridge
474
+ * still authorises the persisted one). If the bridge is gone the open
475
+ * throws and we fall through to a spawn-based recovery.
476
+ */
477
+ if (coords) {
478
+ try {
479
+ const attachUrl =
480
+ (await sandboxSession.getPortUrl({
481
+ port: coords.port,
482
+ protocol: 'ws',
483
+ })) + `?agent_bridge_token=${encodeURIComponent(coords.token)}`;
484
+ const attachChannel: ClaudeCodeChannel = new SandboxChannel({
485
+ connect: buildConnect(attachUrl),
486
+ outboundSchema: outboundMessageSchema,
487
+ initialLastSeenEventId: coords.lastSeenEventId,
488
+ onDiagnostic,
489
+ });
490
+ await attachChannel.open(isContinue ? { resume: true } : undefined);
491
+ return createSession({
492
+ sessionId: startOpts.sessionId,
493
+ channel: attachChannel,
494
+ // The live bridge was spawned by another process; this one owns no
495
+ // process handle. The session lifecycle method decides whether the
496
+ // sandbox is left running, stopped, or destroyed.
497
+ proc: undefined,
498
+ model: settings.model,
499
+ maxTurns: settings.maxTurns,
500
+ thinking: settings.thinking,
501
+ isResume: true,
502
+ continueOnFirstPrompt: false,
503
+ rerunContinue: false,
504
+ bridgePort: coords.port,
505
+ bridgeToken: coords.token,
506
+ sandboxId,
507
+ debug: startOpts.observability?.debug,
508
+ permissionMode: startOpts.permissionMode,
509
+ });
510
+ } catch {
511
+ // Bridge no longer reachable — recover by respawning below.
512
+ }
513
+ }
514
+
515
+ /*
516
+ * Rungs 2/3 — REPLAY vs RERUN. Respawn the bridge. `replay` is only sound
517
+ * for `continueFrom`: those coordinates include the cursor the on-disk
518
+ * log is replayed *from*. `resumeFrom` is a between-turn resume; even when
519
+ * it carries bridge coordinates, replaying the previous turn would
520
+ * re-deliver stale events into the next turn. Those resumes always `rerun`
521
+ * when attach is unavailable (the CLI continues its own thread from the
522
+ * workdir snapshot via `continue: true`).
523
+ */
524
+ let respawnStrategy: ClaudeCodeRespawnStrategy | undefined = isResume
525
+ ? 'rerun'
526
+ : undefined;
527
+ if (coords && isContinue) {
528
+ const logRaw = await Promise.resolve(
529
+ session.readTextFile({
530
+ path: `${bridgeStateDir}/event-log.ndjson`,
531
+ abortSignal: startOpts.abortSignal,
532
+ }),
533
+ ).catch(() => null);
534
+ if ((await classifyDiskLog(logRaw)) === 'replay') {
535
+ respawnStrategy = 'replay';
536
+ }
537
+ }
538
+
539
+ const port = resolveBridgePort(sandboxSession, settings.port);
540
+ const token = randomBytes(32).toString('hex');
541
+ const env = {
542
+ ...resolveClaudeCodeEnv(settings.auth),
543
+ BRIDGE_CHANNEL_TOKEN: token,
544
+ BRIDGE_WS_PORT: String(port),
545
+ ...(respawnStrategy === 'replay'
546
+ ? { BRIDGE_REPLAY_FROM_DISK: '1' }
547
+ : {}),
548
+ };
549
+
550
+ /*
551
+ * On a fresh start the workdir, skill files, and bridge-state directory
552
+ * must be created. On any resume they already exist in the
553
+ * sandbox snapshot, so skip the rewrite. The env is sent fresh on every
554
+ * spawn — `BRIDGE_CHANNEL_TOKEN` rotates per start.
555
+ */
556
+ if (respawnStrategy === undefined) {
557
+ await session.run({
558
+ command: `mkdir -p ${workDir} ${bridgeStateDir}`,
559
+ abortSignal: startOpts.abortSignal,
560
+ });
561
+
562
+ if (startOpts.skills && startOpts.skills.length > 0) {
563
+ await writeSkills({
564
+ sandbox: session,
565
+ workdir: workDir,
566
+ skills: startOpts.skills,
567
+ abortSignal: startOpts.abortSignal,
568
+ });
569
+ }
570
+ }
571
+
572
+ const proc = await session.spawn({
573
+ command: `node ${BOOTSTRAP_DIR}/bridge.mjs --workdir ${workDir} --bridge-state-dir ${bridgeStateDir}`,
574
+ env,
575
+ abortSignal: startOpts.abortSignal,
576
+ });
577
+
578
+ const bridgeStartupStderr: string[] = [];
579
+ /*
580
+ * Bridge stderr is the only diagnostic channel for sandbox-side crashes
581
+ * and startup failures. Start forwarding before `bridge-ready`, otherwise
582
+ * module-resolution, auth, and syntax errors can be lost behind the
583
+ * generic startup failure below.
584
+ */
585
+ const bridgeStartupStderrDone = forwardBridgeStderr({
586
+ stream: proc.stderr,
587
+ collectTail: bridgeStartupStderr,
588
+ });
589
+ void bridgeStartupStderrDone;
590
+ const { port: boundPort } = await waitForBridgeReady({
591
+ proc,
592
+ timeoutMs,
593
+ abortSignal: startOpts.abortSignal,
594
+ stderrTail: bridgeStartupStderr,
595
+ stderrDone: bridgeStartupStderrDone,
596
+ });
597
+ void drainRest(proc.stdout);
598
+
599
+ const wsUrl =
600
+ (await sandboxSession.getPortUrl({
601
+ port: boundPort,
602
+ protocol: 'ws',
603
+ })) + `?agent_bridge_token=${encodeURIComponent(token)}`;
604
+
605
+ const channel: ClaudeCodeChannel = new SandboxChannel({
606
+ connect: buildConnect(wsUrl),
607
+ outboundSchema: outboundMessageSchema,
608
+ onDiagnostic,
609
+ // In replay mode the respawned bridge reloaded the finished turn from
610
+ // disk; seed the cursor and resume so it streams the tail (incl.
611
+ // `finish`) rather than starting empty.
612
+ ...(respawnStrategy === 'replay'
613
+ ? { initialLastSeenEventId: coords?.lastSeenEventId ?? 0 }
614
+ : {}),
615
+ });
616
+ await channel.open(
617
+ respawnStrategy === 'replay' ? { resume: true } : undefined,
618
+ );
619
+
620
+ return createSession({
621
+ sessionId: startOpts.sessionId,
622
+ channel,
623
+ proc,
624
+ model: settings.model,
625
+ maxTurns: settings.maxTurns,
626
+ thinking: settings.thinking,
627
+ isResume: respawnStrategy !== undefined,
628
+ continueOnFirstPrompt: respawnStrategy !== undefined,
629
+ rerunContinue: respawnStrategy === 'rerun',
630
+ bridgePort: boundPort,
631
+ bridgeToken: token,
632
+ sandboxId,
633
+ debug: startOpts.observability?.debug,
634
+ permissionMode: startOpts.permissionMode,
635
+ });
636
+ },
637
+ };
638
+ }
639
+
640
+ function resolveBridgePort(
641
+ sandboxSession: HarnessV1NetworkSandboxSession,
642
+ override: number | undefined,
643
+ ): number {
644
+ if (override !== undefined) return override;
645
+ if (sandboxSession.ports.length > 0) return sandboxSession.ports[0];
646
+ throw new HarnessCapabilityUnsupportedError({
647
+ harnessId: 'claude-code',
648
+ message:
649
+ 'The claude-code harness needs a TCP port exposed by the sandbox. ' +
650
+ 'Create the sandbox with `ports: [<port>]` or pass `createClaudeCode({ port })`.',
651
+ });
652
+ }
653
+
654
+ /**
655
+ * Materialise skill files into `${workdir}/.claude/skills/<name>.md`. The
656
+ * `claude` CLI auto-discovers skills from that directory on startup, so the
657
+ * files have to be in place before the bridge is spawned. Each file uses
658
+ * the YAML-frontmatter shape the CLI expects.
659
+ */
660
+ async function writeSkills({
661
+ sandbox,
662
+ workdir,
663
+ skills,
664
+ abortSignal,
665
+ }: {
666
+ sandbox: Experimental_SandboxSession;
667
+ workdir: string;
668
+ skills: ReadonlyArray<HarnessV1Skill>;
669
+ abortSignal?: AbortSignal;
670
+ }): Promise<void> {
671
+ await sandbox.run({
672
+ command: `mkdir -p ${workdir}/.claude/skills`,
673
+ abortSignal,
674
+ });
675
+ for (const skill of skills) {
676
+ const path = `${workdir}/.claude/skills/${skill.name}.md`;
677
+ const content = `---\nname: ${skill.name}\ndescription: ${skill.description}\n---\n\n${skill.content}\n`;
678
+ await sandbox.writeTextFile({ path, content, abortSignal });
679
+ }
680
+ }
681
+
682
+ async function readBridgeAsset(name: string): Promise<string> {
683
+ const candidates = [
684
+ new URL(`./bridge/${name}`, import.meta.url),
685
+ new URL(`../bridge/${name}`, import.meta.url),
686
+ ];
687
+ let lastErr: unknown;
688
+ for (const url of candidates) {
689
+ try {
690
+ return await readFile(fileURLToPath(url), 'utf8');
691
+ } catch (err) {
692
+ const code = (err as NodeJS.ErrnoException).code;
693
+ if (code !== 'ENOENT') throw err;
694
+ lastErr = err;
695
+ }
696
+ }
697
+ throw lastErr ?? new Error(`bridge asset not found: ${name}`);
698
+ }
699
+
700
+ async function waitForBridgeReady({
701
+ proc,
702
+ timeoutMs,
703
+ abortSignal,
704
+ stderrTail,
705
+ stderrDone,
706
+ }: {
707
+ proc: Experimental_SandboxProcess;
708
+ timeoutMs: number;
709
+ abortSignal: AbortSignal | undefined;
710
+ stderrTail: string[];
711
+ stderrDone: Promise<void>;
712
+ }): Promise<{ port: number }> {
713
+ const reader = proc.stdout.pipeThrough(new TextDecoderStream()).getReader();
714
+
715
+ const decoder = lineDecoder();
716
+ const stdoutTail: string[] = [];
717
+
718
+ const deadline = Date.now() + timeoutMs;
719
+ try {
720
+ while (true) {
721
+ if (abortSignal?.aborted) {
722
+ await proc.kill();
723
+ throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');
724
+ }
725
+ const remaining = deadline - Date.now();
726
+ if (remaining <= 0) {
727
+ await proc.kill();
728
+ throw await createBridgeStartupError({
729
+ message: 'claude-code bridge did not become ready in time.',
730
+ proc,
731
+ stdoutTail,
732
+ stderrTail,
733
+ stderrDone,
734
+ });
735
+ }
736
+ const { value, done } = (await Promise.race([
737
+ reader.read(),
738
+ new Promise(resolve =>
739
+ setTimeout(
740
+ () => resolve({ value: undefined, done: false }),
741
+ remaining,
742
+ ),
743
+ ),
744
+ ])) as ReadableStreamReadResult<string>;
745
+ if (done) {
746
+ for (const line of decoder.flush()) {
747
+ stdoutTail.push(line);
748
+ if (stdoutTail.length > 20) stdoutTail.shift();
749
+ }
750
+ throw await createBridgeStartupError({
751
+ message: 'claude-code bridge exited before becoming ready.',
752
+ proc,
753
+ stdoutTail,
754
+ stderrTail,
755
+ stderrDone,
756
+ });
757
+ }
758
+ if (value === undefined) continue;
759
+ for (const line of decoder.push(value)) {
760
+ stdoutTail.push(line);
761
+ if (stdoutTail.length > 20) stdoutTail.shift();
762
+ const parsed = await safeParseJSON({
763
+ text: line,
764
+ schema: bridgeReadySchema,
765
+ });
766
+ if (parsed.success) return { port: parsed.value.port };
767
+ }
768
+ }
769
+ } finally {
770
+ reader.releaseLock();
771
+ }
772
+ }
773
+
774
+ async function createBridgeStartupError({
775
+ message,
776
+ proc,
777
+ stdoutTail,
778
+ stderrTail,
779
+ stderrDone,
780
+ }: {
781
+ message: string;
782
+ proc: Experimental_SandboxProcess;
783
+ stdoutTail: string[];
784
+ stderrTail: string[];
785
+ stderrDone: Promise<void>;
786
+ }): Promise<Error> {
787
+ await Promise.race([
788
+ stderrDone,
789
+ new Promise<void>(resolve => setTimeout(resolve, 250)),
790
+ ]).catch(() => {});
791
+
792
+ let exitStatus = '';
793
+ try {
794
+ const result = (await Promise.race([
795
+ proc.wait(),
796
+ new Promise<undefined>(resolve => setTimeout(resolve, 250)),
797
+ ])) as { exitCode?: number } | undefined;
798
+ if (result?.exitCode !== undefined) {
799
+ exitStatus = ` Exit code: ${result.exitCode}.`;
800
+ }
801
+ } catch {}
802
+
803
+ const details: string[] = [];
804
+ if (stdoutTail.length > 0) {
805
+ details.push(`stdout:\n${stdoutTail.join('\n')}`);
806
+ }
807
+ if (stderrTail.length > 0) {
808
+ details.push(`stderr:\n${stderrTail.join('\n')}`);
809
+ }
810
+
811
+ return new Error(
812
+ `${message}${exitStatus}${
813
+ details.length > 0 ? `\n\n${details.join('\n\n')}` : ''
814
+ }`,
815
+ );
816
+ }
817
+
818
+ function lineDecoder() {
819
+ let buffer = '';
820
+ return {
821
+ push(chunk: string): string[] {
822
+ buffer += chunk;
823
+ const lines: string[] = [];
824
+ let nl: number;
825
+ while ((nl = buffer.indexOf('\n')) !== -1) {
826
+ const raw = buffer.slice(0, nl);
827
+ buffer = buffer.slice(nl + 1);
828
+ const line = raw.replace(/\r$/, '').trim();
829
+ if (line.length > 0) lines.push(line);
830
+ }
831
+ return lines;
832
+ },
833
+ flush(): string[] {
834
+ const line = buffer.replace(/\r$/, '').trim();
835
+ buffer = '';
836
+ return line.length > 0 ? [line] : [];
837
+ },
838
+ };
839
+ }
840
+
841
+ async function forwardBridgeStderr({
842
+ stream,
843
+ collectTail,
844
+ }: {
845
+ stream: ReadableStream<Uint8Array>;
846
+ collectTail?: string[];
847
+ }): Promise<void> {
848
+ try {
849
+ const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
850
+ const decoder = lineDecoder();
851
+ while (true) {
852
+ const { value, done } = await reader.read();
853
+ if (done) {
854
+ for (const line of decoder.flush()) {
855
+ const trimmed = line.trim();
856
+ if (!trimmed) continue;
857
+ if (collectTail) {
858
+ collectTail.push(trimmed);
859
+ if (collectTail.length > 20) collectTail.shift();
860
+ }
861
+ // eslint-disable-next-line no-console
862
+ console.log(`[bridge stderr] ${trimmed}`);
863
+ }
864
+ return;
865
+ }
866
+ if (value) {
867
+ for (const line of decoder.push(value)) {
868
+ const trimmed = line.trim();
869
+ if (!trimmed) continue;
870
+ if (collectTail) {
871
+ collectTail.push(trimmed);
872
+ if (collectTail.length > 20) collectTail.shift();
873
+ }
874
+ // eslint-disable-next-line no-console
875
+ console.log(`[bridge stderr] ${trimmed}`);
876
+ }
877
+ }
878
+ }
879
+ } catch {
880
+ // Reader errors are non-fatal — best-effort diagnostic only.
881
+ }
882
+ }
883
+
884
+ async function drainRest(stream: ReadableStream<Uint8Array>): Promise<void> {
885
+ try {
886
+ const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
887
+ while (true) {
888
+ const { done } = await reader.read();
889
+ if (done) return;
890
+ }
891
+ } catch {}
892
+ }
893
+
894
+ /**
895
+ * Wait for the bridge's `bridge-hello` message to arrive on the freshly
896
+ * opened WebSocket before any other host-side code touches it.
897
+ *
898
+ * Some sandbox runtimes (Vercel in particular) complete the WS upgrade
899
+ * with the host long before the connection is actually forwarded to the
900
+ * sandbox-side bridge. Anything sent in that gap is silently dropped —
901
+ * including the `start` message we send next. The bridge emits
902
+ * `bridge-hello` the instant it accepts the connection, so receiving it
903
+ * is the only reliable evidence that the end-to-end link is live.
904
+ */
905
+ async function waitForBridgeHello({
906
+ ws,
907
+ timeoutMs,
908
+ }: {
909
+ ws: WebSocket;
910
+ timeoutMs: number;
911
+ }): Promise<void> {
912
+ await new Promise<void>((resolve, reject) => {
913
+ let settled = false;
914
+ const cleanup = () => {
915
+ ws.off('message', onMessage);
916
+ ws.off('close', onClose);
917
+ ws.off('error', onError);
918
+ if (timer) clearTimeout(timer);
919
+ };
920
+ const settle = (err?: unknown) => {
921
+ if (settled) return;
922
+ settled = true;
923
+ cleanup();
924
+ if (err) reject(err);
925
+ else resolve();
926
+ };
927
+ const onMessage = (raw: unknown) => {
928
+ try {
929
+ const text =
930
+ typeof raw === 'string'
931
+ ? raw
932
+ : (raw as Buffer | ArrayBufferLike).toString
933
+ ? (raw as Buffer).toString('utf8')
934
+ : String(raw);
935
+ const parsed = JSON.parse(text) as { type?: unknown };
936
+ if (parsed?.type === 'bridge-hello') settle();
937
+ } catch {
938
+ // Ignore malformed frames while waiting.
939
+ }
940
+ };
941
+ const onClose = () => {
942
+ settle(
943
+ new Error('claude-code bridge closed before sending bridge-hello'),
944
+ );
945
+ };
946
+ const onError = (err: Error) => settle(err);
947
+ const timer = setTimeout(
948
+ () =>
949
+ settle(
950
+ new Error(
951
+ `claude-code bridge did not send bridge-hello within ${timeoutMs}ms`,
952
+ ),
953
+ ),
954
+ timeoutMs,
955
+ );
956
+ timer.unref?.();
957
+ ws.on('message', onMessage);
958
+ ws.on('close', onClose);
959
+ ws.on('error', onError);
960
+ });
961
+ }
962
+
963
+ async function openBridgeWebSocket({
964
+ wsUrl,
965
+ timeoutMs,
966
+ }: {
967
+ wsUrl: string;
968
+ timeoutMs: number;
969
+ }): Promise<WebSocket> {
970
+ const deadline = Date.now() + timeoutMs;
971
+ let attempt = 0;
972
+ let lastError: unknown;
973
+
974
+ while (Date.now() < deadline) {
975
+ attempt++;
976
+ let ws: WebSocket | undefined;
977
+ try {
978
+ const remaining = Math.max(1, deadline - Date.now());
979
+ ws = await openWebSocket({
980
+ url: wsUrl,
981
+ timeoutMs: Math.min(10_000, remaining),
982
+ });
983
+ await waitForBridgeHello({
984
+ ws,
985
+ timeoutMs: Math.min(5_000, Math.max(1, deadline - Date.now())),
986
+ });
987
+ return ws;
988
+ } catch (err) {
989
+ lastError = err;
990
+ try {
991
+ ws?.close();
992
+ } catch {}
993
+ const remaining = deadline - Date.now();
994
+ if (remaining <= 0) break;
995
+ await sleep(Math.min(250 * attempt, 1_000, remaining));
996
+ }
997
+ }
998
+
999
+ throw new Error(
1000
+ `claude-code bridge did not complete WebSocket handshake within ${timeoutMs}ms after ${attempt} attempt(s). Last error: ${formatUnknownError(lastError)}`,
1001
+ );
1002
+ }
1003
+
1004
+ function openWebSocket({
1005
+ url,
1006
+ timeoutMs,
1007
+ }: {
1008
+ url: string;
1009
+ timeoutMs: number;
1010
+ }): Promise<WebSocket> {
1011
+ return new Promise((resolve, reject) => {
1012
+ const ws = new WebSocket(url);
1013
+ const timer = setTimeout(() => {
1014
+ cleanup();
1015
+ try {
1016
+ ws.terminate();
1017
+ } catch {}
1018
+ reject(new Error(`WebSocket open timed out after ${timeoutMs}ms`));
1019
+ }, timeoutMs);
1020
+ timer.unref?.();
1021
+ const cleanup = () => {
1022
+ clearTimeout(timer);
1023
+ ws.off('open', onOpen);
1024
+ ws.off('error', onError);
1025
+ };
1026
+ const onOpen = () => {
1027
+ cleanup();
1028
+ resolve(ws);
1029
+ };
1030
+ const onError = (err: Error) => {
1031
+ cleanup();
1032
+ reject(err);
1033
+ };
1034
+ ws.once('open', onOpen);
1035
+ ws.once('error', onError);
1036
+ });
1037
+ }
1038
+
1039
+ function sleep(ms: number): Promise<void> {
1040
+ return new Promise(resolve => {
1041
+ const timer = setTimeout(resolve, ms);
1042
+ timer.unref?.();
1043
+ });
1044
+ }
1045
+
1046
+ function formatUnknownError(error: unknown): string {
1047
+ if (error instanceof Error) return error.message;
1048
+ return String(error);
1049
+ }
1050
+
1051
+ function createSession({
1052
+ sessionId,
1053
+ channel,
1054
+ proc,
1055
+ model,
1056
+ maxTurns,
1057
+ thinking,
1058
+ isResume,
1059
+ continueOnFirstPrompt,
1060
+ rerunContinue,
1061
+ bridgePort,
1062
+ bridgeToken,
1063
+ sandboxId,
1064
+ debug,
1065
+ permissionMode,
1066
+ }: {
1067
+ sessionId: string;
1068
+ channel: ClaudeCodeChannel;
1069
+ /** Undefined on `attach` — the live bridge was spawned by another process. */
1070
+ proc: Experimental_SandboxProcess | undefined;
1071
+ model: string | undefined;
1072
+ maxTurns: number | undefined;
1073
+ thinking: 'off' | 'on' | 'adaptive' | undefined;
1074
+ isResume: boolean;
1075
+ continueOnFirstPrompt: boolean;
1076
+ rerunContinue: boolean;
1077
+ bridgePort: number;
1078
+ bridgeToken: string;
1079
+ sandboxId: string;
1080
+ debug: HarnessV1DebugConfig | undefined;
1081
+ permissionMode: HarnessV1PermissionMode | undefined;
1082
+ }): HarnessV1Session {
1083
+ let stopped = false;
1084
+ let stopPromise: Promise<void> | undefined;
1085
+ /*
1086
+ * Force the Claude SDK's `continue: true` on the first prompt only when the
1087
+ * bridge was respawned (rerun/replay): a fresh bridge process treats its
1088
+ * first turn as new, so it must be told to rehydrate the workdir thread. An
1089
+ * `attach`ed bridge is already past its first turn and continues on its own.
1090
+ */
1091
+ let pendingResumeFlag = continueOnFirstPrompt;
1092
+ /*
1093
+ * Instructions are prepended to the first user message of a fresh session
1094
+ * only. A resumed session (attach/replay/rerun) already carried them in its
1095
+ * original first message (preserved in the workdir snapshot), so it starts
1096
+ * "applied".
1097
+ */
1098
+ let instructionsApplied = isResume;
1099
+
1100
+ /*
1101
+ * Wire the channel into one turn's worth of events and return the control
1102
+ * surface. Shared by `doPromptTurn` (which sends a `start` afterwards) and
1103
+ * `doContinueTurn` (which attaches to an already-running/replayed turn, or sends
1104
+ * a rerun `start`). The only difference between the two entry points is the
1105
+ * `start` message, not the listener/abort/settle plumbing.
1106
+ */
1107
+ const wireTurn = (turnOpts: {
1108
+ emit: (event: HarnessV1StreamPart) => void;
1109
+ abortSignal?: AbortSignal;
1110
+ }): HarnessV1PromptControl => {
1111
+ let pendingResolve: (() => void) | undefined;
1112
+ let pendingReject: ((err: unknown) => void) | undefined;
1113
+ const done = new Promise<void>((resolve, reject) => {
1114
+ pendingResolve = resolve;
1115
+ pendingReject = reject;
1116
+ });
1117
+
1118
+ const unsubs: Array<() => void> = [];
1119
+ const forward = (event: HarnessV1StreamPart) => {
1120
+ try {
1121
+ turnOpts.emit(event);
1122
+ } catch {}
1123
+ };
1124
+
1125
+ let isSettled = false;
1126
+ const settleSuccess = () => {
1127
+ if (isSettled) return;
1128
+ isSettled = true;
1129
+ for (const u of unsubs) u();
1130
+ pendingResolve!();
1131
+ };
1132
+ const settleError = (err: unknown) => {
1133
+ if (isSettled) return;
1134
+ isSettled = true;
1135
+ for (const u of unsubs) u();
1136
+ pendingReject!(err);
1137
+ };
1138
+
1139
+ const eventTypes = [
1140
+ 'stream-start',
1141
+ 'text-start',
1142
+ 'text-delta',
1143
+ 'text-end',
1144
+ 'reasoning-start',
1145
+ 'reasoning-delta',
1146
+ 'reasoning-end',
1147
+ 'tool-call',
1148
+ 'tool-approval-request',
1149
+ 'tool-result',
1150
+ 'finish-step',
1151
+ 'raw',
1152
+ ] as const;
1153
+ for (const type of eventTypes) {
1154
+ unsubs.push(
1155
+ channel.on(type, msg => {
1156
+ forward(msg);
1157
+ }),
1158
+ );
1159
+ }
1160
+ unsubs.push(
1161
+ channel.on('finish', msg => {
1162
+ forward(msg);
1163
+ settleSuccess();
1164
+ }),
1165
+ );
1166
+ unsubs.push(
1167
+ channel.on('error', msg => {
1168
+ forward(msg);
1169
+ settleError(msg.error);
1170
+ }),
1171
+ );
1172
+
1173
+ /*
1174
+ * A `'suspended'` close is a graceful slice-boundary freeze the host
1175
+ * initiated (`doSuspendTurn`): the turn keeps running in the bridge and its
1176
+ * tail is replayed to the next process, so wind this turn down cleanly
1177
+ * rather than failing it. Any other close mid-turn is an unexpected drop.
1178
+ */
1179
+ const onClose = (_code?: number, reason?: string) => {
1180
+ if (isSettled) return;
1181
+ if (reason === 'suspended') {
1182
+ settleSuccess();
1183
+ return;
1184
+ }
1185
+ settleError(
1186
+ new Error('claude-code bridge closed before the turn finished.'),
1187
+ );
1188
+ };
1189
+ channel.onClose(onClose);
1190
+
1191
+ const onAbort = () => {
1192
+ if (isSettled) return;
1193
+ try {
1194
+ channel.send({ type: 'abort' });
1195
+ } catch {}
1196
+ settleError(
1197
+ turnOpts.abortSignal?.reason ??
1198
+ new DOMException('Aborted', 'AbortError'),
1199
+ );
1200
+ };
1201
+ if (turnOpts.abortSignal) {
1202
+ if (turnOpts.abortSignal.aborted) {
1203
+ onAbort();
1204
+ } else {
1205
+ turnOpts.abortSignal.addEventListener('abort', onAbort, {
1206
+ once: true,
1207
+ });
1208
+ }
1209
+ }
1210
+
1211
+ return {
1212
+ submitToolResult: async input => {
1213
+ channel.send({
1214
+ type: 'tool-result',
1215
+ toolCallId: input.toolCallId,
1216
+ output: input.output,
1217
+ isError: input.isError,
1218
+ });
1219
+ },
1220
+ submitToolApproval: async input => {
1221
+ channel.send({
1222
+ type: 'tool-approval-response',
1223
+ approvalId: input.approvalId,
1224
+ approved: input.approved,
1225
+ reason: input.reason,
1226
+ });
1227
+ },
1228
+ submitUserMessage: async text => {
1229
+ channel.send({ type: 'user-message', text });
1230
+ },
1231
+ done,
1232
+ };
1233
+ };
1234
+
1235
+ return {
1236
+ sessionId,
1237
+ isResume,
1238
+ modelId: model,
1239
+ doPromptTurn: async promptOpts => {
1240
+ const control = wireTurn({
1241
+ emit: promptOpts.emit,
1242
+ abortSignal: promptOpts.abortSignal,
1243
+ });
1244
+
1245
+ let promptText = extractUserText(promptOpts.prompt);
1246
+ if (!instructionsApplied && promptOpts.instructions) {
1247
+ promptText = frameInstructions(promptOpts.instructions, promptText);
1248
+ }
1249
+ instructionsApplied = true;
1250
+
1251
+ const startMessage = {
1252
+ type: 'start' as const,
1253
+ prompt: promptText,
1254
+ tools: (promptOpts.tools ?? []).map(t => ({
1255
+ name: t.name,
1256
+ description: t.description,
1257
+ inputSchema: t.inputSchema,
1258
+ })),
1259
+ model,
1260
+ maxTurns,
1261
+ thinking,
1262
+ ...(permissionMode ? { permissionMode } : {}),
1263
+ ...(debug ? { debug } : {}),
1264
+ ...(pendingResumeFlag ? { continue: true } : {}),
1265
+ };
1266
+ pendingResumeFlag = false;
1267
+ channel.send(startMessage);
1268
+
1269
+ return control;
1270
+ },
1271
+ doContinueTurn: async continueOpts => {
1272
+ const control = wireTurn({
1273
+ emit: continueOpts.emit,
1274
+ abortSignal: continueOpts.abortSignal,
1275
+ });
1276
+
1277
+ /*
1278
+ * attach / replay: the still-running (or disk-replayed) turn streams into
1279
+ * the wired listeners — `doStart` opened the channel with `{ resume: true }`
1280
+ * so the bridge replays everything past the persisted cursor (including a
1281
+ * `finish` if the turn ended during the gap). No `start` is sent: issuing
1282
+ * one would clear the bridge's replay log and begin a new turn. Lossless.
1283
+ *
1284
+ * rerun: the bridge was respawned with no in-flight turn to attach to, so
1285
+ * re-drive the runtime's own thread from the workdir snapshot via
1286
+ * `continue: true`. Lossy — work in flight at the interruption is
1287
+ * recomputed. This is the rare bridge-died fallback; the common slice path
1288
+ * is `attach`.
1289
+ */
1290
+ if (rerunContinue) {
1291
+ pendingResumeFlag = false;
1292
+ channel.send({
1293
+ type: 'start' as const,
1294
+ /*
1295
+ * A continuation nudge rather than an empty prompt: `continue: true`
1296
+ * rehydrates the prior thread, and this is the new user turn that
1297
+ * drives it forward. It must be non-empty — an empty text block is
1298
+ * rejected by the Anthropic API once the SDK stamps it with
1299
+ * `cache_control`.
1300
+ */
1301
+ prompt: 'Continue.',
1302
+ tools: (continueOpts.tools ?? []).map(t => ({
1303
+ name: t.name,
1304
+ description: t.description,
1305
+ inputSchema: t.inputSchema,
1306
+ })),
1307
+ model,
1308
+ maxTurns,
1309
+ thinking,
1310
+ ...(permissionMode ? { permissionMode } : {}),
1311
+ ...(debug ? { debug } : {}),
1312
+ continue: true,
1313
+ });
1314
+ }
1315
+
1316
+ return control;
1317
+ },
1318
+ doCompact: async (customInstructions?: string) => {
1319
+ /*
1320
+ * Claude Code has no SDK/control method for compaction — the supported
1321
+ * trigger is the `/compact` slash command submitted as user input. Ride
1322
+ * the existing user-message rail; the bridge feeds it into the streaming
1323
+ * query input and Claude's native compaction handles the rest, emitting a
1324
+ * `compact_boundary` + `PostCompact` we observe as a `compaction` event.
1325
+ */
1326
+ const text =
1327
+ customInstructions && customInstructions.trim()
1328
+ ? `/compact ${customInstructions.trim()}`
1329
+ : '/compact';
1330
+ channel.send({ type: 'user-message', text });
1331
+ },
1332
+ doDetach: async () => {
1333
+ if (stopped) {
1334
+ throw new Error(
1335
+ `claude-code session ${sessionId} is already stopped; cannot detach.`,
1336
+ );
1337
+ }
1338
+ stopped = true;
1339
+ const lastSeenEventId = await channel.suspend();
1340
+ const payload: HarnessV1ResumeSessionState = {
1341
+ type: 'resume-session',
1342
+ harnessId: 'claude-code',
1343
+ specificationVersion: 'harness-v1',
1344
+ data: {
1345
+ bridge: {
1346
+ port: bridgePort,
1347
+ token: bridgeToken,
1348
+ lastSeenEventId,
1349
+ sandboxId,
1350
+ },
1351
+ },
1352
+ };
1353
+ return payload;
1354
+ },
1355
+ doDestroy: async () => {
1356
+ if (stopped) return stopPromise;
1357
+ stopped = true;
1358
+ stopPromise = (async () => {
1359
+ // Tell the channel we are tearing down so the bridge's post-shutdown
1360
+ // socket close finalises instead of triggering a reconnect.
1361
+ channel.beginClose();
1362
+ try {
1363
+ if (!channel.isClosed()) {
1364
+ channel.send({ type: 'shutdown' });
1365
+ }
1366
+ } catch {}
1367
+ let stopTimer: ReturnType<typeof setTimeout> | undefined;
1368
+ try {
1369
+ if (proc) {
1370
+ await Promise.race([
1371
+ proc.wait(),
1372
+ new Promise<void>(resolve => {
1373
+ stopTimer = setTimeout(resolve, 5000);
1374
+ stopTimer.unref?.();
1375
+ }),
1376
+ ]);
1377
+ }
1378
+ } finally {
1379
+ if (stopTimer) clearTimeout(stopTimer);
1380
+ try {
1381
+ await proc?.kill();
1382
+ } catch {}
1383
+ channel.close();
1384
+ }
1385
+ })();
1386
+ return stopPromise;
1387
+ },
1388
+ doStop: async () => {
1389
+ if (stopped) {
1390
+ throw new Error(
1391
+ `claude-code session ${sessionId} is already stopped; cannot stop.`,
1392
+ );
1393
+ }
1394
+ stopped = true;
1395
+ /*
1396
+ * If the bridge's channel already closed (e.g. mid-turn WS drop)
1397
+ * there is no one to ack a `detach` message. Synthesize an empty
1398
+ * payload — for Claude Code the resume state structurally is `{}`
1399
+ * (the conversation lives in the workdir, captured by the sandbox
1400
+ * snapshot during the subsequent `sandboxSession.stop()`), so we
1401
+ * lose nothing by skipping the round-trip.
1402
+ */
1403
+ // Tell the channel we are tearing down so the bridge's post-detach
1404
+ // socket close finalises instead of triggering a reconnect.
1405
+ channel.beginClose();
1406
+ const data: unknown = channel.isClosed()
1407
+ ? {}
1408
+ : await new Promise<unknown>((resolve, reject) => {
1409
+ const timer = setTimeout(() => {
1410
+ unsub();
1411
+ reject(
1412
+ new Error(
1413
+ `claude-code session ${sessionId} did not reply to detach within 5s.`,
1414
+ ),
1415
+ );
1416
+ }, 5000);
1417
+ timer.unref?.();
1418
+ const unsub = channel.on('bridge-detach', msg => {
1419
+ clearTimeout(timer);
1420
+ unsub();
1421
+ resolve(msg.data);
1422
+ });
1423
+ try {
1424
+ channel.send({ type: 'detach' });
1425
+ } catch (err) {
1426
+ clearTimeout(timer);
1427
+ unsub();
1428
+ reject(err);
1429
+ }
1430
+ });
1431
+
1432
+ // The bridge exits itself ~50ms after sending bridge-detach. Give
1433
+ // it a moment, then ensure the process is reaped and the channel
1434
+ // closed.
1435
+ let stopTimer: ReturnType<typeof setTimeout> | undefined;
1436
+ try {
1437
+ if (proc) {
1438
+ await Promise.race([
1439
+ proc.wait(),
1440
+ new Promise<void>(resolve => {
1441
+ stopTimer = setTimeout(resolve, 5000);
1442
+ stopTimer.unref?.();
1443
+ }),
1444
+ ]);
1445
+ }
1446
+ } finally {
1447
+ if (stopTimer) clearTimeout(stopTimer);
1448
+ try {
1449
+ await proc?.kill();
1450
+ } catch {}
1451
+ channel.close();
1452
+ }
1453
+
1454
+ const payload: HarnessV1ResumeSessionState = {
1455
+ type: 'resume-session',
1456
+ harnessId: 'claude-code',
1457
+ specificationVersion: 'harness-v1',
1458
+ data: (data ?? {}) as HarnessV1ResumeSessionState['data'],
1459
+ };
1460
+ return payload;
1461
+ },
1462
+ doSuspendTurn: async () => {
1463
+ if (stopped) {
1464
+ throw new Error(
1465
+ `claude-code session ${sessionId} is stopped; cannot suspend.`,
1466
+ );
1467
+ }
1468
+ stopped = true;
1469
+ /*
1470
+ * Gracefully freeze the active turn at a precise cursor. `channel.suspend`
1471
+ * stops processing inbound frames (the cursor stops advancing exactly at
1472
+ * the last delivered event), drains what was already dispatched, then
1473
+ * closes the host socket with reason `'suspended'` — which `wireTurn`'s
1474
+ * `onClose` treats as a clean turn end. The bridge keeps the turn running
1475
+ * and accumulates events past the cursor for the next slice to replay. The
1476
+ * sandbox process is deliberately left alive (no `shutdown`/`detach`).
1477
+ */
1478
+ const lastSeenEventId = await channel.suspend();
1479
+ const payload: HarnessV1ContinueTurnState = {
1480
+ type: 'continue-turn',
1481
+ harnessId: 'claude-code',
1482
+ specificationVersion: 'harness-v1',
1483
+ data: {
1484
+ bridge: {
1485
+ port: bridgePort,
1486
+ token: bridgeToken,
1487
+ lastSeenEventId,
1488
+ sandboxId,
1489
+ },
1490
+ },
1491
+ };
1492
+ return payload;
1493
+ },
1494
+ };
1495
+ }
1496
+
1497
+ /*
1498
+ * Frame session instructions and the user's text so the runtime treats the
1499
+ * instructions as system-provided operating guidance, not something the user
1500
+ * wrote. Without the wrapper the agent can echo the prepended text back as if
1501
+ * the user had asked for it, which is confusing since the user never typed it.
1502
+ * Applied only to the first user message of a fresh session.
1503
+ */
1504
+ function frameInstructions(instructions: string, userText: string): string {
1505
+ return (
1506
+ '<session-instructions>\n' +
1507
+ 'The block below is operating guidance from the system, not a message from the user — follow it, but do not mention it or attribute it to the user.\n\n' +
1508
+ `${instructions}\n` +
1509
+ '</session-instructions>\n\n' +
1510
+ `<user-message>\n${userText}\n</user-message>`
1511
+ );
1512
+ }
1513
+
1514
+ /*
1515
+ * Reduce a `HarnessV1Prompt` to the plain user text the bridge forwards
1516
+ * to the Claude SDK. File and image parts on the message are not yet
1517
+ * supported by the underlying runtime — throw rather than silently drop
1518
+ * them so callers learn about the gap instead of seeing mysteriously
1519
+ * truncated prompts.
1520
+ */
1521
+ function extractUserText(prompt: HarnessV1Prompt): string {
1522
+ if (typeof prompt === 'string') return prompt;
1523
+ const { content } = prompt;
1524
+ if (typeof content === 'string') return content;
1525
+ const parts: string[] = [];
1526
+ for (const part of content) {
1527
+ if (part.type !== 'text') {
1528
+ throw new HarnessCapabilityUnsupportedError({
1529
+ harnessId: 'claude-code',
1530
+ message: `The claude-code harness does not yet support user message parts of type '${part.type}'. Pass a string or a user message whose content contains only text parts.`,
1531
+ });
1532
+ }
1533
+ parts.push(part.text);
1534
+ }
1535
+ return parts.join('\n\n');
1536
+ }