@ai-sdk/harness-claude-code 0.0.0-6b196531-20260710185421

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.
package/dist/index.js ADDED
@@ -0,0 +1,1208 @@
1
+ // src/claude-code-harness.ts
2
+ import { randomBytes } from "crypto";
3
+ import { readFile } from "fs/promises";
4
+ import { fileURLToPath } from "url";
5
+ import {
6
+ commonTool,
7
+ harnessV1DiagnosticFromBridgeFrame,
8
+ HarnessCapabilityUnsupportedError
9
+ } from "@ai-sdk/harness";
10
+ import {
11
+ classifyDiskLog,
12
+ createBridgeErrorHandler,
13
+ createBridgeStartupError,
14
+ drainBridgeProcessStream,
15
+ forwardBridgeProcessStream,
16
+ markBridgeStarting,
17
+ resolveSandboxHomeDir,
18
+ SandboxChannel,
19
+ shellQuote,
20
+ waitForBridgeReady,
21
+ writeSkills as writeHarnessSkills
22
+ } from "@ai-sdk/harness/utils";
23
+ import {
24
+ tool
25
+ } from "@ai-sdk/provider-utils";
26
+ import { WebSocket } from "ws";
27
+ import { z as z2 } from "zod/v4";
28
+
29
+ // src/claude-code-auth.ts
30
+ import { execFileSync } from "child_process";
31
+ import { readFileSync } from "fs";
32
+ import { homedir } from "os";
33
+ import { join } from "path";
34
+ import { getAiGatewayAuthFromEnv } from "@ai-sdk/harness/utils";
35
+ function resolveClaudeCodeEnv(auth, processEnv = process.env, options = {}) {
36
+ const readApiKey = options.readApiKeyHelper ?? readApiKeyHelper;
37
+ if (auth?.anthropic) {
38
+ return pickAnthropic({ explicit: auth.anthropic, processEnv, readApiKey });
39
+ }
40
+ const gatewayAuthFromEnv = getAiGatewayAuthFromEnv({ env: processEnv });
41
+ if (auth?.gateway) {
42
+ return pickGateway({
43
+ explicit: auth.gateway,
44
+ gatewayAuthFromEnv
45
+ });
46
+ }
47
+ if (gatewayAuthFromEnv.apiKey) {
48
+ return pickGateway({
49
+ explicit: {},
50
+ gatewayAuthFromEnv
51
+ });
52
+ }
53
+ return pickAnthropic({ processEnv, readApiKey });
54
+ }
55
+ function pickAnthropic({
56
+ explicit,
57
+ processEnv,
58
+ readApiKey
59
+ }) {
60
+ const env = {};
61
+ const helperKey = explicit ? void 0 : readApiKey();
62
+ const apiKey = explicit?.apiKey ?? processEnv.ANTHROPIC_API_KEY ?? helperKey;
63
+ const authToken = explicit?.authToken ?? processEnv.ANTHROPIC_AUTH_TOKEN ?? helperKey;
64
+ if (apiKey) env.ANTHROPIC_API_KEY = apiKey;
65
+ if (authToken) env.ANTHROPIC_AUTH_TOKEN = authToken;
66
+ const baseUrl = explicit?.baseUrl ?? processEnv.ANTHROPIC_BASE_URL;
67
+ if (baseUrl) env.ANTHROPIC_BASE_URL = baseUrl;
68
+ return env;
69
+ }
70
+ function readApiKeyHelper() {
71
+ const home = homedir();
72
+ if (!home) return void 0;
73
+ let raw;
74
+ try {
75
+ raw = readFileSync(join(home, ".claude", "settings.json"), "utf8");
76
+ } catch {
77
+ return void 0;
78
+ }
79
+ let settings;
80
+ try {
81
+ settings = JSON.parse(raw);
82
+ } catch {
83
+ return void 0;
84
+ }
85
+ const command = settings.apiKeyHelper;
86
+ if (typeof command !== "string" || command.length === 0) return void 0;
87
+ try {
88
+ const output = execFileSync("sh", ["-c", command], {
89
+ encoding: "utf8",
90
+ stdio: ["ignore", "pipe", "ignore"]
91
+ });
92
+ const trimmed = output.trim();
93
+ return trimmed.length > 0 ? trimmed : void 0;
94
+ } catch {
95
+ return void 0;
96
+ }
97
+ }
98
+ function pickGateway({
99
+ explicit,
100
+ gatewayAuthFromEnv
101
+ }) {
102
+ const apiKey = explicit.apiKey ?? gatewayAuthFromEnv.apiKey;
103
+ const baseUrl = explicit.baseUrl ?? gatewayAuthFromEnv.baseUrl;
104
+ const env = {};
105
+ if (apiKey) {
106
+ env.AI_GATEWAY_API_KEY = apiKey;
107
+ env.ANTHROPIC_API_KEY = apiKey;
108
+ }
109
+ env.AI_GATEWAY_BASE_URL = baseUrl;
110
+ env.ANTHROPIC_BASE_URL = baseUrl;
111
+ return env;
112
+ }
113
+
114
+ // src/claude-code-bridge-protocol.ts
115
+ import {
116
+ harnessV1BridgeInboundCommandSchemas,
117
+ harnessV1BridgeOutboundMessageSchema,
118
+ harnessV1BridgeReadySchema,
119
+ harnessV1BridgeStartBaseSchema
120
+ } from "@ai-sdk/harness";
121
+ import { z } from "zod/v4";
122
+ var outboundMessageSchema = harnessV1BridgeOutboundMessageSchema;
123
+ var thinkingDisplaySchema = z.enum(["summarized", "omitted"]).optional();
124
+ var thinkingSchema = z.discriminatedUnion("type", [
125
+ z.object({
126
+ type: z.literal("adaptive"),
127
+ display: thinkingDisplaySchema
128
+ }),
129
+ z.object({
130
+ type: z.literal("enabled"),
131
+ display: thinkingDisplaySchema
132
+ }),
133
+ z.object({ type: z.literal("disabled") })
134
+ ]);
135
+ var startMessageSchema = harnessV1BridgeStartBaseSchema.extend({
136
+ thinking: thinkingSchema,
137
+ maxTurns: z.number().optional(),
138
+ skills: z.array(z.string()).optional(),
139
+ // Resume signal. When true, the bridge passes `{ continue: true }` to the
140
+ // Claude SDK so the in-workdir thread state is rehydrated. The host sets this
141
+ // on the first prompt after a cross-process resume.
142
+ continue: z.boolean().optional()
143
+ });
144
+ var inboundMessageSchema = z.discriminatedUnion("type", [
145
+ startMessageSchema,
146
+ ...harnessV1BridgeInboundCommandSchemas
147
+ ]);
148
+
149
+ // src/version.ts
150
+ var VERSION = true ? "0.0.0-6b196531-20260710185421" : "0.0.0-test";
151
+
152
+ // src/claude-code-harness.ts
153
+ var CLAUDE_CODE_CLIENT_APP = `ai-sdk/harness-claude-code/${VERSION}`;
154
+ var CLAUDE_CODE_BUILTIN_TOOLS = {
155
+ read: commonTool("read", {
156
+ nativeName: "Read",
157
+ toolUseKind: "readonly",
158
+ description: "Read file contents (text, image, PDF, notebook)",
159
+ inputSchema: z2.object({
160
+ file_path: z2.string(),
161
+ offset: z2.number().optional(),
162
+ limit: z2.number().optional(),
163
+ pages: z2.string().optional()
164
+ })
165
+ }),
166
+ write: commonTool("write", {
167
+ nativeName: "Write",
168
+ toolUseKind: "edit",
169
+ description: "Overwrite or create a file at an absolute path",
170
+ inputSchema: z2.object({
171
+ file_path: z2.string(),
172
+ content: z2.string()
173
+ })
174
+ }),
175
+ edit: commonTool("edit", {
176
+ nativeName: "Edit",
177
+ toolUseKind: "edit",
178
+ description: "Edit a file by exact string replacement",
179
+ inputSchema: z2.object({
180
+ file_path: z2.string(),
181
+ old_string: z2.string(),
182
+ new_string: z2.string(),
183
+ replace_all: z2.boolean().optional()
184
+ })
185
+ }),
186
+ bash: commonTool("bash", {
187
+ nativeName: "Bash",
188
+ toolUseKind: "bash",
189
+ description: "Execute a shell command, optionally in background",
190
+ inputSchema: z2.object({
191
+ command: z2.string(),
192
+ timeout: z2.number().optional(),
193
+ description: z2.string().optional(),
194
+ run_in_background: z2.boolean().optional(),
195
+ dangerouslyDisableSandbox: z2.boolean().optional()
196
+ })
197
+ }),
198
+ glob: commonTool("glob", {
199
+ nativeName: "Glob",
200
+ toolUseKind: "readonly",
201
+ description: "Fast file-pattern search using glob syntax",
202
+ inputSchema: z2.object({
203
+ pattern: z2.string(),
204
+ path: z2.string().optional()
205
+ })
206
+ }),
207
+ grep: commonTool("grep", {
208
+ nativeName: "Grep",
209
+ toolUseKind: "readonly",
210
+ description: "Regex search over file contents via ripgrep",
211
+ inputSchema: z2.object({
212
+ pattern: z2.string(),
213
+ path: z2.string().optional(),
214
+ glob: z2.string().optional(),
215
+ output_mode: z2.enum(["content", "files_with_matches", "count"]).optional(),
216
+ "-B": z2.number().optional(),
217
+ "-A": z2.number().optional(),
218
+ "-C": z2.number().optional(),
219
+ context: z2.number().optional(),
220
+ "-n": z2.boolean().optional(),
221
+ "-i": z2.boolean().optional(),
222
+ "-o": z2.boolean().optional(),
223
+ type: z2.string().optional(),
224
+ head_limit: z2.number().optional(),
225
+ offset: z2.number().optional(),
226
+ multiline: z2.boolean().optional()
227
+ })
228
+ }),
229
+ webSearch: commonTool("webSearch", {
230
+ nativeName: "WebSearch",
231
+ toolUseKind: "readonly",
232
+ description: "Issue web search queries with optional domain filters",
233
+ inputSchema: z2.object({
234
+ query: z2.string(),
235
+ allowed_domains: z2.array(z2.string()).optional(),
236
+ blocked_domains: z2.array(z2.string()).optional()
237
+ })
238
+ }),
239
+ WebFetch: tool({
240
+ description: "Fetch a URL and run a prompt against its content",
241
+ inputSchema: z2.object({
242
+ url: z2.string(),
243
+ prompt: z2.string()
244
+ })
245
+ }),
246
+ NotebookEdit: tool({
247
+ description: "Edit, insert, or delete a Jupyter notebook cell",
248
+ inputSchema: z2.object({
249
+ notebook_path: z2.string(),
250
+ new_source: z2.string(),
251
+ cell_id: z2.string().optional(),
252
+ cell_type: z2.enum(["code", "markdown"]).optional(),
253
+ edit_mode: z2.enum(["replace", "insert", "delete"]).optional()
254
+ })
255
+ }),
256
+ TodoWrite: tool({
257
+ description: "Replace the session todo list",
258
+ inputSchema: z2.object({
259
+ todos: z2.array(
260
+ z2.object({
261
+ content: z2.string(),
262
+ status: z2.enum(["pending", "in_progress", "completed"]),
263
+ activeForm: z2.string()
264
+ })
265
+ )
266
+ })
267
+ }),
268
+ Agent: tool({
269
+ description: "Spawn a subagent with a task",
270
+ inputSchema: z2.object({
271
+ description: z2.string(),
272
+ prompt: z2.string(),
273
+ subagent_type: z2.string().optional(),
274
+ model: z2.enum(["sonnet", "opus", "haiku"]).optional(),
275
+ run_in_background: z2.boolean().optional(),
276
+ name: z2.string().optional(),
277
+ team_name: z2.string().optional(),
278
+ mode: z2.enum([
279
+ "acceptEdits",
280
+ "auto",
281
+ "bypassPermissions",
282
+ "default",
283
+ "dontAsk",
284
+ "plan"
285
+ ]).optional(),
286
+ isolation: z2.literal("worktree").optional()
287
+ })
288
+ }),
289
+ TaskCreate: tool({
290
+ description: "Create a task in the session-local task list",
291
+ inputSchema: z2.object({
292
+ subject: z2.string(),
293
+ description: z2.string(),
294
+ activeForm: z2.string().optional(),
295
+ metadata: z2.record(z2.string(), z2.unknown()).optional()
296
+ })
297
+ }),
298
+ TaskGet: tool({
299
+ description: "Retrieve a task by id",
300
+ inputSchema: z2.object({ taskId: z2.string() })
301
+ }),
302
+ TaskUpdate: tool({
303
+ description: "Update fields of an existing task",
304
+ inputSchema: z2.object({
305
+ taskId: z2.string(),
306
+ subject: z2.string().optional(),
307
+ description: z2.string().optional(),
308
+ activeForm: z2.string().optional(),
309
+ status: z2.union([
310
+ z2.enum(["pending", "in_progress", "completed"]),
311
+ z2.literal("deleted")
312
+ ]).optional(),
313
+ addBlocks: z2.array(z2.string()).optional(),
314
+ addBlockedBy: z2.array(z2.string()).optional(),
315
+ owner: z2.string().optional(),
316
+ metadata: z2.record(z2.string(), z2.unknown()).optional()
317
+ })
318
+ }),
319
+ TaskList: tool({
320
+ description: "Return all tasks in the session-local task list",
321
+ inputSchema: z2.object({})
322
+ }),
323
+ TaskStop: tool({
324
+ description: "Stop a running background task by id",
325
+ inputSchema: z2.object({
326
+ task_id: z2.string().optional(),
327
+ shell_id: z2.string().optional()
328
+ })
329
+ }),
330
+ TaskOutput: tool({
331
+ description: "Poll for output from a background task",
332
+ inputSchema: z2.object({
333
+ task_id: z2.string(),
334
+ block: z2.boolean(),
335
+ timeout: z2.number()
336
+ })
337
+ }),
338
+ Monitor: tool({
339
+ description: "Run and monitor a shell command",
340
+ inputSchema: z2.object({
341
+ command: z2.string(),
342
+ description: z2.string().optional(),
343
+ timeout_ms: z2.number().optional(),
344
+ persistent: z2.boolean().optional()
345
+ })
346
+ }),
347
+ ListMcpResources: tool({
348
+ description: "List resources available from MCP servers",
349
+ inputSchema: z2.object({ server: z2.string().optional() })
350
+ }),
351
+ ReadMcpResource: tool({
352
+ description: "Read a specific MCP resource by URI",
353
+ inputSchema: z2.object({ server: z2.string(), uri: z2.string() })
354
+ }),
355
+ ExitPlanMode: tool({
356
+ description: "Exit plan mode with optional permission approvals",
357
+ inputSchema: z2.looseObject({
358
+ allowedPrompts: z2.array(
359
+ z2.object({
360
+ tool: z2.literal("Bash"),
361
+ prompt: z2.string()
362
+ })
363
+ ).optional()
364
+ })
365
+ }),
366
+ EnterWorktree: tool({
367
+ description: "Create or enter an isolated git worktree",
368
+ inputSchema: z2.object({
369
+ name: z2.string().optional(),
370
+ path: z2.string().optional()
371
+ })
372
+ }),
373
+ ExitWorktree: tool({
374
+ description: "Exit the current worktree session",
375
+ inputSchema: z2.object({
376
+ action: z2.enum(["keep", "remove"]),
377
+ discard_changes: z2.boolean().optional()
378
+ })
379
+ }),
380
+ AskUserQuestion: tool({
381
+ description: "Ask the user multiple-choice questions via a structured UI",
382
+ inputSchema: z2.object({
383
+ questions: z2.array(
384
+ z2.object({
385
+ question: z2.string(),
386
+ header: z2.string(),
387
+ options: z2.array(
388
+ z2.object({
389
+ label: z2.string(),
390
+ description: z2.string(),
391
+ preview: z2.string().optional()
392
+ })
393
+ ),
394
+ multiSelect: z2.boolean()
395
+ })
396
+ ).min(1).max(4),
397
+ answers: z2.record(z2.string(), z2.string()).optional(),
398
+ annotations: z2.record(
399
+ z2.string(),
400
+ z2.object({
401
+ preview: z2.string().optional(),
402
+ notes: z2.string().optional()
403
+ })
404
+ ).optional(),
405
+ metadata: z2.object({ source: z2.string().optional() }).optional()
406
+ })
407
+ }),
408
+ Skill: tool({
409
+ description: "Activate a skill by name",
410
+ inputSchema: z2.object({
411
+ skill: z2.string(),
412
+ args: z2.string().optional()
413
+ })
414
+ })
415
+ };
416
+ var BOOTSTRAP_DIR = "/tmp/harness/claude-code";
417
+ var claudeCodeBridgeCoordsSchema = z2.object({
418
+ port: z2.number(),
419
+ token: z2.string(),
420
+ lastSeenEventId: z2.number(),
421
+ sandboxId: z2.string().optional()
422
+ });
423
+ var claudeCodeResumeStateSchema = z2.looseObject({
424
+ bridge: claudeCodeBridgeCoordsSchema.optional()
425
+ });
426
+ function createClaudeCode(settings = {}) {
427
+ let cachedBootstrap;
428
+ const thinking = settings.thinking ?? {
429
+ type: "adaptive",
430
+ display: "summarized"
431
+ };
432
+ return {
433
+ specificationVersion: "harness-v1",
434
+ harnessId: "claude-code",
435
+ builtinTools: CLAUDE_CODE_BUILTIN_TOOLS,
436
+ supportsBuiltinToolApprovals: true,
437
+ supportsBuiltinToolFiltering: true,
438
+ lifecycleStateSchema: claudeCodeResumeStateSchema,
439
+ getBootstrap: async () => {
440
+ if (cachedBootstrap != null) return cachedBootstrap;
441
+ const [pkg, lock, bridge] = await Promise.all([
442
+ readBridgeAsset("package.json"),
443
+ readBridgeAsset("pnpm-lock.yaml"),
444
+ readBridgeAsset("index.mjs")
445
+ ]);
446
+ cachedBootstrap = {
447
+ harnessId: "claude-code",
448
+ bootstrapDir: BOOTSTRAP_DIR,
449
+ files: [
450
+ { path: `${BOOTSTRAP_DIR}/package.json`, content: pkg },
451
+ { path: `${BOOTSTRAP_DIR}/pnpm-lock.yaml`, content: lock },
452
+ { path: `${BOOTSTRAP_DIR}/bridge.mjs`, content: bridge }
453
+ ],
454
+ commands: [
455
+ { command: `mkdir -p ${BOOTSTRAP_DIR}` },
456
+ {
457
+ command: `pnpm --dir ${BOOTSTRAP_DIR} install --frozen-lockfile --store-dir ${BOOTSTRAP_DIR}/.pnpm-store`
458
+ },
459
+ {
460
+ 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`
461
+ }
462
+ ]
463
+ };
464
+ return cachedBootstrap;
465
+ },
466
+ doStart: async (startOpts) => {
467
+ const sandboxSession = startOpts.sandboxSession;
468
+ const session = sandboxSession.restricted();
469
+ const sandboxId = sandboxSession.id;
470
+ const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
471
+ const isResume = lifecycleState != null;
472
+ const isContinue = startOpts.continueFrom != null;
473
+ const coords = isResume ? lifecycleState?.data?.bridge : void 0;
474
+ const workDir = startOpts.sessionWorkDir;
475
+ const sessionDataDir = `${sandboxSession.defaultWorkingDirectory}/.agent-runs/${startOpts.sessionId}`;
476
+ const bridgeStateDir = `${sessionDataDir}/bridge`;
477
+ const timeoutMs = settings.startupTimeoutMs ?? 12e4;
478
+ const report = startOpts.observability?.report;
479
+ const onDiagnostic = report ? (frame) => report(
480
+ harnessV1DiagnosticFromBridgeFrame(frame, {
481
+ sessionId: startOpts.sessionId,
482
+ timestamp: Date.now()
483
+ })
484
+ ) : void 0;
485
+ const onBridgeError = createBridgeErrorHandler({
486
+ harnessId: "claude-code",
487
+ sessionId: startOpts.sessionId
488
+ });
489
+ const buildConnect = (wsUrl2) => async () => {
490
+ return openBridgeWebSocket({ wsUrl: wsUrl2, timeoutMs });
491
+ };
492
+ if (coords) {
493
+ try {
494
+ const attachUrl = await sandboxSession.getPortUrl({
495
+ port: coords.port,
496
+ protocol: "ws"
497
+ }) + `?agent_bridge_token=${encodeURIComponent(coords.token)}`;
498
+ const attachChannel = new SandboxChannel({
499
+ connect: buildConnect(attachUrl),
500
+ outboundSchema: outboundMessageSchema,
501
+ initialLastSeenEventId: coords.lastSeenEventId,
502
+ onDiagnostic,
503
+ onBridgeError
504
+ });
505
+ await attachChannel.open(isContinue ? { resume: true } : void 0);
506
+ return createSession({
507
+ sessionId: startOpts.sessionId,
508
+ channel: attachChannel,
509
+ // The live bridge was spawned by another process; this one owns no
510
+ // process handle. The session lifecycle method decides whether the
511
+ // sandbox is left running, stopped, or destroyed.
512
+ proc: void 0,
513
+ model: settings.model,
514
+ maxTurns: settings.maxTurns,
515
+ thinking,
516
+ isResume: true,
517
+ continueOnFirstPrompt: false,
518
+ rerunContinue: false,
519
+ bridgePort: coords.port,
520
+ bridgeToken: coords.token,
521
+ sandboxId,
522
+ debug: startOpts.observability?.debug,
523
+ permissionMode: startOpts.permissionMode,
524
+ builtinToolFiltering: startOpts.builtinToolFiltering,
525
+ skills: startOpts.skills ?? []
526
+ });
527
+ } catch {
528
+ }
529
+ }
530
+ let respawnStrategy = isResume ? "rerun" : void 0;
531
+ if (coords && isContinue) {
532
+ const logRaw = await Promise.resolve(
533
+ session.readTextFile({
534
+ path: `${bridgeStateDir}/event-log.ndjson`,
535
+ abortSignal: startOpts.abortSignal
536
+ })
537
+ ).catch(() => null);
538
+ if (await classifyDiskLog(logRaw) === "replay") {
539
+ respawnStrategy = "replay";
540
+ }
541
+ }
542
+ const sandboxHomeDir = startOpts.skills && startOpts.skills.length > 0 ? await resolveSandboxHomeDir({
543
+ sandbox: session,
544
+ abortSignal: startOpts.abortSignal
545
+ }) : void 0;
546
+ const port = resolveBridgePort(sandboxSession, settings.port);
547
+ const token = randomBytes(32).toString("hex");
548
+ const env = {
549
+ ...resolveClaudeCodeEnv(settings.auth),
550
+ /*
551
+ * The Claude Agent SDK does not expose arbitrary model-request
552
+ * headers. It reads this environment variable and sends the value as
553
+ * `x-client-app`, while also appending `client-app/<value>` to
554
+ * `User-Agent`, so this is the attribution path for AI Gateway.
555
+ */
556
+ CLAUDE_AGENT_SDK_CLIENT_APP: CLAUDE_CODE_CLIENT_APP,
557
+ BRIDGE_CHANNEL_TOKEN: token,
558
+ BRIDGE_WS_PORT: String(port),
559
+ ...sandboxHomeDir ? { HOME: sandboxHomeDir } : {},
560
+ ...respawnStrategy === "replay" ? { BRIDGE_REPLAY_FROM_DISK: "1" } : {}
561
+ };
562
+ if (respawnStrategy === void 0) {
563
+ await session.run({
564
+ command: `mkdir -p ${shellQuote(workDir)} ${shellQuote(bridgeStateDir)}`,
565
+ abortSignal: startOpts.abortSignal
566
+ });
567
+ if (startOpts.skills && startOpts.skills.length > 0) {
568
+ if (!sandboxHomeDir) {
569
+ throw new Error("Unable to resolve sandbox HOME directory.");
570
+ }
571
+ await writeClaudeCodeSkills({
572
+ sandbox: session,
573
+ homeDir: sandboxHomeDir,
574
+ skills: startOpts.skills,
575
+ abortSignal: startOpts.abortSignal
576
+ });
577
+ }
578
+ }
579
+ await markBridgeStarting({
580
+ sandbox: session,
581
+ bridgeStateDir,
582
+ bridgeType: "claude-code",
583
+ abortSignal: startOpts.abortSignal
584
+ });
585
+ const proc = await session.spawn({
586
+ command: `node ${BOOTSTRAP_DIR}/bridge.mjs --workdir ${shellQuote(workDir)} --bridge-state-dir ${shellQuote(bridgeStateDir)}`,
587
+ env,
588
+ abortSignal: startOpts.abortSignal
589
+ });
590
+ const bridgeStartupStderr = [];
591
+ const bridgeStartupStderrDone = forwardBridgeProcessStream({
592
+ stream: proc.stderr,
593
+ streamName: "stderr",
594
+ source: "claude-code",
595
+ collectTail: bridgeStartupStderr
596
+ });
597
+ void bridgeStartupStderrDone;
598
+ const { port: boundPort } = await waitForBridgeReady({
599
+ proc,
600
+ sandbox: session,
601
+ bridgeStateDir,
602
+ bridgeType: "claude-code",
603
+ timeoutMs,
604
+ abortSignal: startOpts.abortSignal,
605
+ createTimeoutError: ({ proc: proc2, stdoutTail }) => createBridgeStartupError({
606
+ message: "claude-code bridge did not become ready in time.",
607
+ proc: proc2,
608
+ stdoutTail,
609
+ stderrTail: bridgeStartupStderr,
610
+ stderrDone: bridgeStartupStderrDone
611
+ }),
612
+ createExitError: ({ proc: proc2, stdoutTail }) => createBridgeStartupError({
613
+ message: "claude-code bridge exited before becoming ready.",
614
+ proc: proc2,
615
+ stdoutTail,
616
+ stderrTail: bridgeStartupStderr,
617
+ stderrDone: bridgeStartupStderrDone
618
+ })
619
+ });
620
+ void drainBridgeProcessStream(proc.stdout);
621
+ const wsUrl = await sandboxSession.getPortUrl({
622
+ port: boundPort,
623
+ protocol: "ws"
624
+ }) + `?agent_bridge_token=${encodeURIComponent(token)}`;
625
+ const channel = new SandboxChannel({
626
+ connect: buildConnect(wsUrl),
627
+ outboundSchema: outboundMessageSchema,
628
+ onDiagnostic,
629
+ onBridgeError,
630
+ // In replay mode the respawned bridge reloaded the finished turn from
631
+ // disk; seed the cursor and resume so it streams the tail (incl.
632
+ // `finish`) rather than starting empty.
633
+ ...respawnStrategy === "replay" ? { initialLastSeenEventId: coords?.lastSeenEventId ?? 0 } : {}
634
+ });
635
+ await channel.open(
636
+ respawnStrategy === "replay" ? { resume: true } : void 0
637
+ );
638
+ return createSession({
639
+ sessionId: startOpts.sessionId,
640
+ channel,
641
+ proc,
642
+ model: settings.model,
643
+ maxTurns: settings.maxTurns,
644
+ thinking,
645
+ isResume: respawnStrategy !== void 0,
646
+ continueOnFirstPrompt: respawnStrategy !== void 0,
647
+ rerunContinue: respawnStrategy === "rerun",
648
+ bridgePort: boundPort,
649
+ bridgeToken: token,
650
+ sandboxId,
651
+ debug: startOpts.observability?.debug,
652
+ permissionMode: startOpts.permissionMode,
653
+ builtinToolFiltering: startOpts.builtinToolFiltering,
654
+ skills: startOpts.skills ?? []
655
+ });
656
+ }
657
+ };
658
+ }
659
+ function resolveBridgePort(sandboxSession, override) {
660
+ if (override !== void 0) return override;
661
+ if (sandboxSession.ports.length > 0) return sandboxSession.ports[0];
662
+ throw new HarnessCapabilityUnsupportedError({
663
+ harnessId: "claude-code",
664
+ message: "The claude-code harness needs a TCP port exposed by the sandbox. Create the sandbox with `ports: [<port>]` or pass `createClaudeCode({ port })`."
665
+ });
666
+ }
667
+ async function writeClaudeCodeSkills({
668
+ sandbox,
669
+ homeDir,
670
+ skills,
671
+ abortSignal
672
+ }) {
673
+ await writeHarnessSkills({
674
+ sandbox,
675
+ rootDir: `${homeDir}/.claude/skills`,
676
+ skills,
677
+ abortSignal,
678
+ invalidSkillNameMessage: ({ name }) => `Invalid Claude Code skill name: ${name}`,
679
+ invalidSkillFilePathMessage: ({ skillName, filePath }) => `Invalid Claude Code skill file path for ${skillName}: ${filePath}`,
680
+ trailingNewline: true
681
+ });
682
+ }
683
+ async function readBridgeAsset(name) {
684
+ const candidates = [
685
+ new URL(`./bridge/${name}`, import.meta.url),
686
+ new URL(`../bridge/${name}`, import.meta.url)
687
+ ];
688
+ let lastErr;
689
+ for (const url of candidates) {
690
+ try {
691
+ return await readFile(fileURLToPath(url), "utf8");
692
+ } catch (err) {
693
+ const code = err.code;
694
+ if (code !== "ENOENT") throw err;
695
+ lastErr = err;
696
+ }
697
+ }
698
+ throw lastErr ?? new Error(`bridge asset not found: ${name}`);
699
+ }
700
+ async function waitForBridgeHello({
701
+ ws,
702
+ timeoutMs
703
+ }) {
704
+ await new Promise((resolve, reject) => {
705
+ let settled = false;
706
+ const cleanup = () => {
707
+ ws.off("message", onMessage);
708
+ ws.off("close", onClose);
709
+ ws.off("error", onError);
710
+ if (timer) clearTimeout(timer);
711
+ };
712
+ const settle = (err) => {
713
+ if (settled) return;
714
+ settled = true;
715
+ cleanup();
716
+ if (err) reject(err);
717
+ else resolve();
718
+ };
719
+ const onMessage = (raw) => {
720
+ try {
721
+ const text = typeof raw === "string" ? raw : raw.toString ? raw.toString("utf8") : String(raw);
722
+ const parsed = JSON.parse(text);
723
+ if (parsed?.type === "bridge-hello") settle();
724
+ } catch {
725
+ }
726
+ };
727
+ const onClose = () => {
728
+ settle(
729
+ new Error("claude-code bridge closed before sending bridge-hello")
730
+ );
731
+ };
732
+ const onError = (err) => settle(err);
733
+ const timer = setTimeout(
734
+ () => settle(
735
+ new Error(
736
+ `claude-code bridge did not send bridge-hello within ${timeoutMs}ms`
737
+ )
738
+ ),
739
+ timeoutMs
740
+ );
741
+ timer.unref?.();
742
+ ws.on("message", onMessage);
743
+ ws.on("close", onClose);
744
+ ws.on("error", onError);
745
+ });
746
+ }
747
+ async function openBridgeWebSocket({
748
+ wsUrl,
749
+ timeoutMs
750
+ }) {
751
+ const deadline = Date.now() + timeoutMs;
752
+ let attempt = 0;
753
+ let lastError;
754
+ while (Date.now() < deadline) {
755
+ attempt++;
756
+ let ws;
757
+ try {
758
+ const remaining = Math.max(1, deadline - Date.now());
759
+ ws = await openWebSocket({
760
+ url: wsUrl,
761
+ timeoutMs: Math.min(1e4, remaining)
762
+ });
763
+ await waitForBridgeHello({
764
+ ws,
765
+ timeoutMs: Math.min(5e3, Math.max(1, deadline - Date.now()))
766
+ });
767
+ return ws;
768
+ } catch (err) {
769
+ lastError = err;
770
+ try {
771
+ ws?.close();
772
+ } catch {
773
+ }
774
+ const remaining = deadline - Date.now();
775
+ if (remaining <= 0) break;
776
+ await sleep(Math.min(250 * attempt, 1e3, remaining));
777
+ }
778
+ }
779
+ throw new Error(
780
+ `claude-code bridge did not complete WebSocket handshake within ${timeoutMs}ms after ${attempt} attempt(s). Last error: ${formatUnknownError(lastError)}`
781
+ );
782
+ }
783
+ function openWebSocket({
784
+ url,
785
+ timeoutMs
786
+ }) {
787
+ return new Promise((resolve, reject) => {
788
+ const ws = new WebSocket(url);
789
+ const timer = setTimeout(() => {
790
+ cleanup();
791
+ try {
792
+ ws.terminate();
793
+ } catch {
794
+ }
795
+ reject(new Error(`WebSocket open timed out after ${timeoutMs}ms`));
796
+ }, timeoutMs);
797
+ timer.unref?.();
798
+ const cleanup = () => {
799
+ clearTimeout(timer);
800
+ ws.off("open", onOpen);
801
+ ws.off("error", onError);
802
+ };
803
+ const onOpen = () => {
804
+ cleanup();
805
+ resolve(ws);
806
+ };
807
+ const onError = (err) => {
808
+ cleanup();
809
+ reject(err);
810
+ };
811
+ ws.once("open", onOpen);
812
+ ws.once("error", onError);
813
+ });
814
+ }
815
+ function sleep(ms) {
816
+ return new Promise((resolve) => {
817
+ const timer = setTimeout(resolve, ms);
818
+ timer.unref?.();
819
+ });
820
+ }
821
+ function formatUnknownError(error) {
822
+ if (error instanceof Error) return error.message;
823
+ return String(error);
824
+ }
825
+ function createSession({
826
+ sessionId,
827
+ channel,
828
+ proc,
829
+ model,
830
+ maxTurns,
831
+ thinking,
832
+ isResume,
833
+ continueOnFirstPrompt,
834
+ rerunContinue,
835
+ bridgePort,
836
+ bridgeToken,
837
+ sandboxId,
838
+ debug,
839
+ permissionMode,
840
+ builtinToolFiltering,
841
+ skills
842
+ }) {
843
+ let stopped = false;
844
+ let stopPromise;
845
+ let pendingResumeFlag = continueOnFirstPrompt;
846
+ let instructionsApplied = isResume;
847
+ const wireTurn = (turnOpts) => {
848
+ let pendingResolve;
849
+ let pendingReject;
850
+ const done = new Promise((resolve, reject) => {
851
+ pendingResolve = resolve;
852
+ pendingReject = reject;
853
+ });
854
+ const unsubs = [];
855
+ const forward = (event) => {
856
+ try {
857
+ turnOpts.emit(event);
858
+ } catch {
859
+ }
860
+ };
861
+ let isSettled = false;
862
+ const settleSuccess = () => {
863
+ if (isSettled) return;
864
+ isSettled = true;
865
+ for (const u of unsubs) u();
866
+ pendingResolve();
867
+ };
868
+ const settleError = (err) => {
869
+ if (isSettled) return;
870
+ isSettled = true;
871
+ for (const u of unsubs) u();
872
+ pendingReject(err);
873
+ };
874
+ const eventTypes = [
875
+ "stream-start",
876
+ "text-start",
877
+ "text-delta",
878
+ "text-end",
879
+ "reasoning-start",
880
+ "reasoning-delta",
881
+ "reasoning-end",
882
+ "tool-call",
883
+ "tool-approval-request",
884
+ "tool-result",
885
+ "finish-step",
886
+ "raw"
887
+ ];
888
+ for (const type of eventTypes) {
889
+ unsubs.push(
890
+ channel.on(type, (msg) => {
891
+ forward(msg);
892
+ })
893
+ );
894
+ }
895
+ unsubs.push(
896
+ channel.on("finish", (msg) => {
897
+ forward(msg);
898
+ settleSuccess();
899
+ })
900
+ );
901
+ unsubs.push(
902
+ channel.on("error", (msg) => {
903
+ forward(msg);
904
+ settleError(msg.error);
905
+ })
906
+ );
907
+ const onClose = (_code, reason) => {
908
+ if (isSettled) return;
909
+ if (reason === "suspended") {
910
+ settleSuccess();
911
+ return;
912
+ }
913
+ settleError(
914
+ new Error("claude-code bridge closed before the turn finished.")
915
+ );
916
+ };
917
+ channel.onClose(onClose);
918
+ const onAbort = () => {
919
+ if (isSettled) return;
920
+ try {
921
+ channel.send({ type: "abort" });
922
+ } catch {
923
+ }
924
+ settleError(
925
+ turnOpts.abortSignal?.reason ?? new DOMException("Aborted", "AbortError")
926
+ );
927
+ };
928
+ if (turnOpts.abortSignal) {
929
+ if (turnOpts.abortSignal.aborted) {
930
+ onAbort();
931
+ } else {
932
+ turnOpts.abortSignal.addEventListener("abort", onAbort, {
933
+ once: true
934
+ });
935
+ }
936
+ }
937
+ return {
938
+ submitToolResult: async (input) => {
939
+ channel.send({
940
+ type: "tool-result",
941
+ toolCallId: input.toolCallId,
942
+ output: input.output,
943
+ isError: input.isError
944
+ });
945
+ },
946
+ submitToolApproval: async (input) => {
947
+ channel.send({
948
+ type: "tool-approval-response",
949
+ approvalId: input.approvalId,
950
+ approved: input.approved,
951
+ reason: input.reason
952
+ });
953
+ },
954
+ submitUserMessage: async (text) => {
955
+ channel.send({ type: "user-message", text });
956
+ },
957
+ done
958
+ };
959
+ };
960
+ return {
961
+ sessionId,
962
+ isResume,
963
+ modelId: model,
964
+ doPromptTurn: async (promptOpts) => {
965
+ const control = wireTurn({
966
+ emit: promptOpts.emit,
967
+ abortSignal: promptOpts.abortSignal
968
+ });
969
+ let promptText = extractUserText(promptOpts.prompt);
970
+ if (!instructionsApplied && promptOpts.instructions) {
971
+ promptText = frameInstructions(promptOpts.instructions, promptText);
972
+ }
973
+ instructionsApplied = true;
974
+ const startMessage = {
975
+ type: "start",
976
+ prompt: promptText,
977
+ tools: (promptOpts.tools ?? []).map((t) => ({
978
+ name: t.name,
979
+ description: t.description,
980
+ inputSchema: t.inputSchema
981
+ })),
982
+ model,
983
+ maxTurns,
984
+ thinking,
985
+ ...skills.length > 0 ? { skills: skills.map((skill) => skill.name) } : {},
986
+ ...permissionMode ? { permissionMode } : {},
987
+ ...builtinToolFiltering ? { builtinToolFiltering } : {},
988
+ ...debug ? { debug } : {},
989
+ ...pendingResumeFlag ? { continue: true } : {}
990
+ };
991
+ pendingResumeFlag = false;
992
+ channel.send(startMessage);
993
+ return control;
994
+ },
995
+ doContinueTurn: async (continueOpts) => {
996
+ const control = wireTurn({
997
+ emit: continueOpts.emit,
998
+ abortSignal: continueOpts.abortSignal
999
+ });
1000
+ if (rerunContinue) {
1001
+ pendingResumeFlag = false;
1002
+ channel.send({
1003
+ type: "start",
1004
+ /*
1005
+ * A continuation nudge rather than an empty prompt: `continue: true`
1006
+ * rehydrates the prior thread, and this is the new user turn that
1007
+ * drives it forward. It must be non-empty — an empty text block is
1008
+ * rejected by the Anthropic API once the SDK stamps it with
1009
+ * `cache_control`.
1010
+ */
1011
+ prompt: "Continue.",
1012
+ tools: (continueOpts.tools ?? []).map((t) => ({
1013
+ name: t.name,
1014
+ description: t.description,
1015
+ inputSchema: t.inputSchema
1016
+ })),
1017
+ model,
1018
+ maxTurns,
1019
+ thinking,
1020
+ ...skills.length > 0 ? { skills: skills.map((skill) => skill.name) } : {},
1021
+ ...permissionMode ? { permissionMode } : {},
1022
+ ...builtinToolFiltering ? { builtinToolFiltering } : {},
1023
+ ...debug ? { debug } : {},
1024
+ continue: true
1025
+ });
1026
+ }
1027
+ return control;
1028
+ },
1029
+ doCompact: async (customInstructions) => {
1030
+ const text = customInstructions && customInstructions.trim() ? `/compact ${customInstructions.trim()}` : "/compact";
1031
+ channel.send({ type: "user-message", text });
1032
+ },
1033
+ doDetach: async () => {
1034
+ if (stopped) {
1035
+ throw new Error(
1036
+ `claude-code session ${sessionId} is already stopped; cannot detach.`
1037
+ );
1038
+ }
1039
+ stopped = true;
1040
+ const lastSeenEventId = await channel.suspend();
1041
+ const payload = {
1042
+ type: "resume-session",
1043
+ harnessId: "claude-code",
1044
+ specificationVersion: "harness-v1",
1045
+ data: {
1046
+ bridge: {
1047
+ port: bridgePort,
1048
+ token: bridgeToken,
1049
+ lastSeenEventId,
1050
+ sandboxId
1051
+ }
1052
+ }
1053
+ };
1054
+ return payload;
1055
+ },
1056
+ doDestroy: async () => {
1057
+ if (stopped) return stopPromise;
1058
+ stopped = true;
1059
+ stopPromise = (async () => {
1060
+ channel.beginClose();
1061
+ try {
1062
+ if (!channel.isClosed()) {
1063
+ channel.send({ type: "shutdown" });
1064
+ }
1065
+ } catch {
1066
+ }
1067
+ let stopTimer;
1068
+ try {
1069
+ if (proc) {
1070
+ await Promise.race([
1071
+ proc.wait(),
1072
+ new Promise((resolve) => {
1073
+ stopTimer = setTimeout(resolve, 5e3);
1074
+ stopTimer.unref?.();
1075
+ })
1076
+ ]);
1077
+ }
1078
+ } finally {
1079
+ if (stopTimer) clearTimeout(stopTimer);
1080
+ try {
1081
+ await proc?.kill();
1082
+ } catch {
1083
+ }
1084
+ channel.close();
1085
+ }
1086
+ })();
1087
+ return stopPromise;
1088
+ },
1089
+ doStop: async () => {
1090
+ if (stopped) {
1091
+ throw new Error(
1092
+ `claude-code session ${sessionId} is already stopped; cannot stop.`
1093
+ );
1094
+ }
1095
+ stopped = true;
1096
+ channel.beginClose();
1097
+ const data = channel.isClosed() ? {} : await new Promise((resolve, reject) => {
1098
+ const timer = setTimeout(() => {
1099
+ unsub();
1100
+ reject(
1101
+ new Error(
1102
+ `claude-code session ${sessionId} did not reply to detach within 5s.`
1103
+ )
1104
+ );
1105
+ }, 5e3);
1106
+ timer.unref?.();
1107
+ const unsub = channel.on("bridge-detach", (msg) => {
1108
+ clearTimeout(timer);
1109
+ unsub();
1110
+ resolve(msg.data);
1111
+ });
1112
+ try {
1113
+ channel.send({ type: "detach" });
1114
+ } catch (err) {
1115
+ clearTimeout(timer);
1116
+ unsub();
1117
+ reject(err);
1118
+ }
1119
+ });
1120
+ let stopTimer;
1121
+ try {
1122
+ if (proc) {
1123
+ await Promise.race([
1124
+ proc.wait(),
1125
+ new Promise((resolve) => {
1126
+ stopTimer = setTimeout(resolve, 5e3);
1127
+ stopTimer.unref?.();
1128
+ })
1129
+ ]);
1130
+ }
1131
+ } finally {
1132
+ if (stopTimer) clearTimeout(stopTimer);
1133
+ try {
1134
+ await proc?.kill();
1135
+ } catch {
1136
+ }
1137
+ channel.close();
1138
+ }
1139
+ const payload = {
1140
+ type: "resume-session",
1141
+ harnessId: "claude-code",
1142
+ specificationVersion: "harness-v1",
1143
+ data: data ?? {}
1144
+ };
1145
+ return payload;
1146
+ },
1147
+ doSuspendTurn: async () => {
1148
+ if (stopped) {
1149
+ throw new Error(
1150
+ `claude-code session ${sessionId} is stopped; cannot suspend.`
1151
+ );
1152
+ }
1153
+ stopped = true;
1154
+ await channel.interrupt();
1155
+ const lastSeenEventId = await channel.suspend();
1156
+ const payload = {
1157
+ type: "continue-turn",
1158
+ harnessId: "claude-code",
1159
+ specificationVersion: "harness-v1",
1160
+ data: {
1161
+ bridge: {
1162
+ port: bridgePort,
1163
+ token: bridgeToken,
1164
+ lastSeenEventId,
1165
+ sandboxId
1166
+ }
1167
+ }
1168
+ };
1169
+ return payload;
1170
+ }
1171
+ };
1172
+ }
1173
+ function frameInstructions(instructions, userText) {
1174
+ return `<session-instructions>
1175
+ The block below is operating guidance from the system, not a message from the user \u2014 follow it, but do not mention it or attribute it to the user.
1176
+
1177
+ ${instructions}
1178
+ </session-instructions>
1179
+
1180
+ <user-message>
1181
+ ${userText}
1182
+ </user-message>`;
1183
+ }
1184
+ function extractUserText(prompt) {
1185
+ if (typeof prompt === "string") return prompt;
1186
+ const { content } = prompt;
1187
+ if (typeof content === "string") return content;
1188
+ const parts = [];
1189
+ for (const part of content) {
1190
+ if (part.type !== "text") {
1191
+ throw new HarnessCapabilityUnsupportedError({
1192
+ harnessId: "claude-code",
1193
+ 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.`
1194
+ });
1195
+ }
1196
+ parts.push(part.text);
1197
+ }
1198
+ return parts.join("\n\n");
1199
+ }
1200
+
1201
+ // src/index.ts
1202
+ var claudeCode = createClaudeCode();
1203
+ export {
1204
+ VERSION,
1205
+ claudeCode,
1206
+ createClaudeCode
1207
+ };
1208
+ //# sourceMappingURL=index.js.map