@ai-sdk/harness-claude-code 0.0.0-cca10482-20260708215408

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