@ai-sdk/harness-claude-code 0.0.0-07500555-20260730161446

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,1218 @@
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-07500555-20260730161446" : "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: {
409
+ ...tool({
410
+ description: "Activate a skill by name",
411
+ inputSchema: z2.object({
412
+ skill: z2.string(),
413
+ args: z2.string().optional()
414
+ })
415
+ }),
416
+ toolUseKind: "readonly"
417
+ },
418
+ ToolSearch: tool({
419
+ description: "Search deferred MCP / catalog tools so the model can load them on demand",
420
+ inputSchema: z2.object({
421
+ query: z2.string(),
422
+ max_results: z2.number().optional()
423
+ })
424
+ })
425
+ };
426
+ var BOOTSTRAP_DIR = "/tmp/harness/claude-code";
427
+ var claudeCodeBridgeCoordsSchema = z2.object({
428
+ port: z2.number(),
429
+ token: z2.string(),
430
+ lastSeenEventId: z2.number(),
431
+ sandboxId: z2.string().optional()
432
+ });
433
+ var claudeCodeResumeStateSchema = z2.looseObject({
434
+ bridge: claudeCodeBridgeCoordsSchema.optional()
435
+ });
436
+ function createClaudeCode(settings = {}) {
437
+ let cachedBootstrap;
438
+ const thinking = settings.thinking ?? {
439
+ type: "adaptive",
440
+ display: "summarized"
441
+ };
442
+ return {
443
+ specificationVersion: "harness-v1",
444
+ harnessId: "claude-code",
445
+ builtinTools: CLAUDE_CODE_BUILTIN_TOOLS,
446
+ supportsBuiltinToolApprovals: true,
447
+ supportsBuiltinToolFiltering: true,
448
+ lifecycleStateSchema: claudeCodeResumeStateSchema,
449
+ getBootstrap: async () => {
450
+ if (cachedBootstrap != null) return cachedBootstrap;
451
+ const [pkg, lock, bridge] = await Promise.all([
452
+ readBridgeAsset("package.json"),
453
+ readBridgeAsset("pnpm-lock.yaml"),
454
+ readBridgeAsset("index.mjs")
455
+ ]);
456
+ cachedBootstrap = {
457
+ harnessId: "claude-code",
458
+ bootstrapDir: BOOTSTRAP_DIR,
459
+ files: [
460
+ { path: `${BOOTSTRAP_DIR}/package.json`, content: pkg },
461
+ { path: `${BOOTSTRAP_DIR}/pnpm-lock.yaml`, content: lock },
462
+ { path: `${BOOTSTRAP_DIR}/bridge.mjs`, content: bridge }
463
+ ],
464
+ commands: [
465
+ { command: `mkdir -p ${BOOTSTRAP_DIR}` },
466
+ {
467
+ command: `pnpm --dir ${BOOTSTRAP_DIR} install --frozen-lockfile --store-dir ${BOOTSTRAP_DIR}/.pnpm-store`
468
+ },
469
+ {
470
+ 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`
471
+ }
472
+ ]
473
+ };
474
+ return cachedBootstrap;
475
+ },
476
+ doStart: async (startOpts) => {
477
+ const sandboxSession = startOpts.sandboxSession;
478
+ const session = sandboxSession.restricted();
479
+ const sandboxId = sandboxSession.id;
480
+ const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
481
+ const isResume = lifecycleState != null;
482
+ const isContinue = startOpts.continueFrom != null;
483
+ const coords = isResume ? lifecycleState?.data?.bridge : void 0;
484
+ const workDir = startOpts.sessionWorkDir;
485
+ const sessionDataDir = `${sandboxSession.defaultWorkingDirectory}/.agent-runs/${startOpts.sessionId}`;
486
+ const bridgeStateDir = `${sessionDataDir}/bridge`;
487
+ const timeoutMs = settings.startupTimeoutMs ?? 12e4;
488
+ const report = startOpts.observability?.report;
489
+ const onDiagnostic = report ? (frame) => report(
490
+ harnessV1DiagnosticFromBridgeFrame(frame, {
491
+ sessionId: startOpts.sessionId,
492
+ timestamp: Date.now()
493
+ })
494
+ ) : void 0;
495
+ const onBridgeError = createBridgeErrorHandler({
496
+ harnessId: "claude-code",
497
+ sessionId: startOpts.sessionId
498
+ });
499
+ const buildConnect = (wsUrl2) => async () => {
500
+ return openBridgeWebSocket({ wsUrl: wsUrl2, timeoutMs });
501
+ };
502
+ if (coords) {
503
+ try {
504
+ const attachUrl = await sandboxSession.getPortUrl({
505
+ port: coords.port,
506
+ protocol: "ws"
507
+ }) + `?agent_bridge_token=${encodeURIComponent(coords.token)}`;
508
+ const attachChannel = new SandboxChannel({
509
+ connect: buildConnect(attachUrl),
510
+ outboundSchema: outboundMessageSchema,
511
+ initialLastSeenEventId: coords.lastSeenEventId,
512
+ onDiagnostic,
513
+ onBridgeError
514
+ });
515
+ await attachChannel.open(isContinue ? { resume: true } : void 0);
516
+ return createSession({
517
+ sessionId: startOpts.sessionId,
518
+ channel: attachChannel,
519
+ // The live bridge was spawned by another process; this one owns no
520
+ // process handle. The session lifecycle method decides whether the
521
+ // sandbox is left running, stopped, or destroyed.
522
+ proc: void 0,
523
+ model: settings.model,
524
+ maxTurns: settings.maxTurns,
525
+ thinking,
526
+ isResume: true,
527
+ continueOnFirstPrompt: false,
528
+ rerunContinue: false,
529
+ bridgePort: coords.port,
530
+ bridgeToken: coords.token,
531
+ sandboxId,
532
+ debug: startOpts.observability?.debug,
533
+ permissionMode: startOpts.permissionMode,
534
+ builtinToolFiltering: startOpts.builtinToolFiltering,
535
+ skills: startOpts.skills ?? []
536
+ });
537
+ } catch {
538
+ }
539
+ }
540
+ let respawnStrategy = isResume ? "rerun" : void 0;
541
+ if (coords && isContinue) {
542
+ const logRaw = await Promise.resolve(
543
+ session.readTextFile({
544
+ path: `${bridgeStateDir}/event-log.ndjson`,
545
+ abortSignal: startOpts.abortSignal
546
+ })
547
+ ).catch(() => null);
548
+ if (await classifyDiskLog(logRaw) === "replay") {
549
+ respawnStrategy = "replay";
550
+ }
551
+ }
552
+ const sandboxHomeDir = startOpts.skills && startOpts.skills.length > 0 ? await resolveSandboxHomeDir({
553
+ sandbox: session,
554
+ abortSignal: startOpts.abortSignal
555
+ }) : void 0;
556
+ const port = resolveBridgePort(sandboxSession, settings.port);
557
+ const token = randomBytes(32).toString("hex");
558
+ const env = {
559
+ ...resolveClaudeCodeEnv(settings.auth),
560
+ /*
561
+ * The Claude Agent SDK does not expose arbitrary model-request
562
+ * headers. It reads this environment variable and sends the value as
563
+ * `x-client-app`, while also appending `client-app/<value>` to
564
+ * `User-Agent`, so this is the attribution path for AI Gateway.
565
+ */
566
+ CLAUDE_AGENT_SDK_CLIENT_APP: CLAUDE_CODE_CLIENT_APP,
567
+ BRIDGE_CHANNEL_TOKEN: token,
568
+ BRIDGE_WS_PORT: String(port),
569
+ ...sandboxHomeDir ? { HOME: sandboxHomeDir } : {},
570
+ ...respawnStrategy === "replay" ? { BRIDGE_REPLAY_FROM_DISK: "1" } : {}
571
+ };
572
+ if (respawnStrategy === void 0) {
573
+ await session.run({
574
+ command: `mkdir -p ${shellQuote(workDir)} ${shellQuote(bridgeStateDir)}`,
575
+ abortSignal: startOpts.abortSignal
576
+ });
577
+ if (startOpts.skills && startOpts.skills.length > 0) {
578
+ if (!sandboxHomeDir) {
579
+ throw new Error("Unable to resolve sandbox HOME directory.");
580
+ }
581
+ await writeClaudeCodeSkills({
582
+ sandbox: session,
583
+ homeDir: sandboxHomeDir,
584
+ skills: startOpts.skills,
585
+ abortSignal: startOpts.abortSignal
586
+ });
587
+ }
588
+ }
589
+ await markBridgeStarting({
590
+ sandbox: session,
591
+ bridgeStateDir,
592
+ bridgeType: "claude-code",
593
+ abortSignal: startOpts.abortSignal
594
+ });
595
+ const proc = await session.spawn({
596
+ command: `node ${BOOTSTRAP_DIR}/bridge.mjs --workdir ${shellQuote(workDir)} --bridge-state-dir ${shellQuote(bridgeStateDir)}`,
597
+ env,
598
+ abortSignal: startOpts.abortSignal
599
+ });
600
+ const bridgeStartupStderr = [];
601
+ const bridgeStartupStderrDone = forwardBridgeProcessStream({
602
+ stream: proc.stderr,
603
+ streamName: "stderr",
604
+ source: "claude-code",
605
+ collectTail: bridgeStartupStderr
606
+ });
607
+ void bridgeStartupStderrDone;
608
+ const { port: boundPort } = await waitForBridgeReady({
609
+ proc,
610
+ sandbox: session,
611
+ bridgeStateDir,
612
+ bridgeType: "claude-code",
613
+ timeoutMs,
614
+ abortSignal: startOpts.abortSignal,
615
+ createTimeoutError: ({ proc: proc2, stdoutTail }) => createBridgeStartupError({
616
+ message: "claude-code bridge did not become ready in time.",
617
+ proc: proc2,
618
+ stdoutTail,
619
+ stderrTail: bridgeStartupStderr,
620
+ stderrDone: bridgeStartupStderrDone
621
+ }),
622
+ createExitError: ({ proc: proc2, stdoutTail }) => createBridgeStartupError({
623
+ message: "claude-code bridge exited before becoming ready.",
624
+ proc: proc2,
625
+ stdoutTail,
626
+ stderrTail: bridgeStartupStderr,
627
+ stderrDone: bridgeStartupStderrDone
628
+ })
629
+ });
630
+ void drainBridgeProcessStream(proc.stdout);
631
+ const wsUrl = await sandboxSession.getPortUrl({
632
+ port: boundPort,
633
+ protocol: "ws"
634
+ }) + `?agent_bridge_token=${encodeURIComponent(token)}`;
635
+ const channel = new SandboxChannel({
636
+ connect: buildConnect(wsUrl),
637
+ outboundSchema: outboundMessageSchema,
638
+ onDiagnostic,
639
+ onBridgeError,
640
+ // In replay mode the respawned bridge reloaded the finished turn from
641
+ // disk; seed the cursor and resume so it streams the tail (incl.
642
+ // `finish`) rather than starting empty.
643
+ ...respawnStrategy === "replay" ? { initialLastSeenEventId: coords?.lastSeenEventId ?? 0 } : {}
644
+ });
645
+ await channel.open(
646
+ respawnStrategy === "replay" ? { resume: true } : void 0
647
+ );
648
+ return createSession({
649
+ sessionId: startOpts.sessionId,
650
+ channel,
651
+ proc,
652
+ model: settings.model,
653
+ maxTurns: settings.maxTurns,
654
+ thinking,
655
+ isResume: respawnStrategy !== void 0,
656
+ continueOnFirstPrompt: respawnStrategy !== void 0,
657
+ rerunContinue: respawnStrategy === "rerun",
658
+ bridgePort: boundPort,
659
+ bridgeToken: token,
660
+ sandboxId,
661
+ debug: startOpts.observability?.debug,
662
+ permissionMode: startOpts.permissionMode,
663
+ builtinToolFiltering: startOpts.builtinToolFiltering,
664
+ skills: startOpts.skills ?? []
665
+ });
666
+ }
667
+ };
668
+ }
669
+ function resolveBridgePort(sandboxSession, override) {
670
+ if (override !== void 0) return override;
671
+ if (sandboxSession.ports.length > 0) return sandboxSession.ports[0];
672
+ throw new HarnessCapabilityUnsupportedError({
673
+ harnessId: "claude-code",
674
+ message: "The claude-code harness needs a TCP port exposed by the sandbox. Create the sandbox with `ports: [<port>]` or pass `createClaudeCode({ port })`."
675
+ });
676
+ }
677
+ async function writeClaudeCodeSkills({
678
+ sandbox,
679
+ homeDir,
680
+ skills,
681
+ abortSignal
682
+ }) {
683
+ await writeHarnessSkills({
684
+ sandbox,
685
+ rootDir: `${homeDir}/.claude/skills`,
686
+ skills,
687
+ abortSignal,
688
+ invalidSkillNameMessage: ({ name }) => `Invalid Claude Code skill name: ${name}`,
689
+ invalidSkillFilePathMessage: ({ skillName, filePath }) => `Invalid Claude Code skill file path for ${skillName}: ${filePath}`,
690
+ trailingNewline: true
691
+ });
692
+ }
693
+ async function readBridgeAsset(name) {
694
+ const candidates = [
695
+ new URL(`./bridge/${name}`, import.meta.url),
696
+ new URL(`../bridge/${name}`, import.meta.url)
697
+ ];
698
+ let lastErr;
699
+ for (const url of candidates) {
700
+ try {
701
+ return await readFile(fileURLToPath(url), "utf8");
702
+ } catch (err) {
703
+ const code = err.code;
704
+ if (code !== "ENOENT") throw err;
705
+ lastErr = err;
706
+ }
707
+ }
708
+ throw lastErr ?? new Error(`bridge asset not found: ${name}`);
709
+ }
710
+ async function waitForBridgeHello({
711
+ ws,
712
+ timeoutMs
713
+ }) {
714
+ await new Promise((resolve, reject) => {
715
+ let settled = false;
716
+ const cleanup = () => {
717
+ ws.off("message", onMessage);
718
+ ws.off("close", onClose);
719
+ ws.off("error", onError);
720
+ if (timer) clearTimeout(timer);
721
+ };
722
+ const settle = (err) => {
723
+ if (settled) return;
724
+ settled = true;
725
+ cleanup();
726
+ if (err) reject(err);
727
+ else resolve();
728
+ };
729
+ const onMessage = (raw) => {
730
+ try {
731
+ const text = typeof raw === "string" ? raw : raw.toString ? raw.toString("utf8") : String(raw);
732
+ const parsed = JSON.parse(text);
733
+ if (parsed?.type === "bridge-hello") settle();
734
+ } catch {
735
+ }
736
+ };
737
+ const onClose = () => {
738
+ settle(
739
+ new Error("claude-code bridge closed before sending bridge-hello")
740
+ );
741
+ };
742
+ const onError = (err) => settle(err);
743
+ const timer = setTimeout(
744
+ () => settle(
745
+ new Error(
746
+ `claude-code bridge did not send bridge-hello within ${timeoutMs}ms`
747
+ )
748
+ ),
749
+ timeoutMs
750
+ );
751
+ timer.unref?.();
752
+ ws.on("message", onMessage);
753
+ ws.on("close", onClose);
754
+ ws.on("error", onError);
755
+ });
756
+ }
757
+ async function openBridgeWebSocket({
758
+ wsUrl,
759
+ timeoutMs
760
+ }) {
761
+ const deadline = Date.now() + timeoutMs;
762
+ let attempt = 0;
763
+ let lastError;
764
+ while (Date.now() < deadline) {
765
+ attempt++;
766
+ let ws;
767
+ try {
768
+ const remaining = Math.max(1, deadline - Date.now());
769
+ ws = await openWebSocket({
770
+ url: wsUrl,
771
+ timeoutMs: Math.min(1e4, remaining)
772
+ });
773
+ await waitForBridgeHello({
774
+ ws,
775
+ timeoutMs: Math.min(5e3, Math.max(1, deadline - Date.now()))
776
+ });
777
+ return ws;
778
+ } catch (err) {
779
+ lastError = err;
780
+ try {
781
+ ws?.close();
782
+ } catch {
783
+ }
784
+ const remaining = deadline - Date.now();
785
+ if (remaining <= 0) break;
786
+ await sleep(Math.min(250 * attempt, 1e3, remaining));
787
+ }
788
+ }
789
+ throw new Error(
790
+ `claude-code bridge did not complete WebSocket handshake within ${timeoutMs}ms after ${attempt} attempt(s). Last error: ${formatUnknownError(lastError)}`
791
+ );
792
+ }
793
+ function openWebSocket({
794
+ url,
795
+ timeoutMs
796
+ }) {
797
+ return new Promise((resolve, reject) => {
798
+ const ws = new WebSocket(url);
799
+ const timer = setTimeout(() => {
800
+ cleanup();
801
+ try {
802
+ ws.terminate();
803
+ } catch {
804
+ }
805
+ reject(new Error(`WebSocket open timed out after ${timeoutMs}ms`));
806
+ }, timeoutMs);
807
+ timer.unref?.();
808
+ const cleanup = () => {
809
+ clearTimeout(timer);
810
+ ws.off("open", onOpen);
811
+ ws.off("error", onError);
812
+ };
813
+ const onOpen = () => {
814
+ cleanup();
815
+ resolve(ws);
816
+ };
817
+ const onError = (err) => {
818
+ cleanup();
819
+ reject(err);
820
+ };
821
+ ws.once("open", onOpen);
822
+ ws.once("error", onError);
823
+ });
824
+ }
825
+ function sleep(ms) {
826
+ return new Promise((resolve) => {
827
+ const timer = setTimeout(resolve, ms);
828
+ timer.unref?.();
829
+ });
830
+ }
831
+ function formatUnknownError(error) {
832
+ if (error instanceof Error) return error.message;
833
+ return String(error);
834
+ }
835
+ function createSession({
836
+ sessionId,
837
+ channel,
838
+ proc,
839
+ model,
840
+ maxTurns,
841
+ thinking,
842
+ isResume,
843
+ continueOnFirstPrompt,
844
+ rerunContinue,
845
+ bridgePort,
846
+ bridgeToken,
847
+ sandboxId,
848
+ debug,
849
+ permissionMode,
850
+ builtinToolFiltering,
851
+ skills
852
+ }) {
853
+ let stopped = false;
854
+ let stopPromise;
855
+ let pendingResumeFlag = continueOnFirstPrompt;
856
+ let instructionsApplied = isResume;
857
+ const wireTurn = (turnOpts) => {
858
+ let pendingResolve;
859
+ let pendingReject;
860
+ const done = new Promise((resolve, reject) => {
861
+ pendingResolve = resolve;
862
+ pendingReject = reject;
863
+ });
864
+ const unsubs = [];
865
+ const forward = (event) => {
866
+ try {
867
+ turnOpts.emit(event);
868
+ } catch {
869
+ }
870
+ };
871
+ let isSettled = false;
872
+ const settleSuccess = () => {
873
+ if (isSettled) return;
874
+ isSettled = true;
875
+ for (const u of unsubs) u();
876
+ pendingResolve();
877
+ };
878
+ const settleError = (err) => {
879
+ if (isSettled) return;
880
+ isSettled = true;
881
+ for (const u of unsubs) u();
882
+ pendingReject(err);
883
+ };
884
+ const eventTypes = [
885
+ "stream-start",
886
+ "text-start",
887
+ "text-delta",
888
+ "text-end",
889
+ "reasoning-start",
890
+ "reasoning-delta",
891
+ "reasoning-end",
892
+ "tool-call",
893
+ "tool-approval-request",
894
+ "tool-result",
895
+ "finish-step",
896
+ "raw"
897
+ ];
898
+ for (const type of eventTypes) {
899
+ unsubs.push(
900
+ channel.on(type, (msg) => {
901
+ forward(msg);
902
+ })
903
+ );
904
+ }
905
+ unsubs.push(
906
+ channel.on("finish", (msg) => {
907
+ forward(msg);
908
+ settleSuccess();
909
+ })
910
+ );
911
+ unsubs.push(
912
+ channel.on("error", (msg) => {
913
+ forward(msg);
914
+ settleError(msg.error);
915
+ })
916
+ );
917
+ const onClose = (_code, reason) => {
918
+ if (isSettled) return;
919
+ if (reason === "suspended") {
920
+ settleSuccess();
921
+ return;
922
+ }
923
+ settleError(
924
+ new Error("claude-code bridge closed before the turn finished.")
925
+ );
926
+ };
927
+ channel.onClose(onClose);
928
+ const onAbort = () => {
929
+ if (isSettled) return;
930
+ try {
931
+ channel.send({ type: "abort" });
932
+ } catch {
933
+ }
934
+ settleError(
935
+ turnOpts.abortSignal?.reason ?? new DOMException("Aborted", "AbortError")
936
+ );
937
+ };
938
+ if (turnOpts.abortSignal) {
939
+ if (turnOpts.abortSignal.aborted) {
940
+ onAbort();
941
+ } else {
942
+ turnOpts.abortSignal.addEventListener("abort", onAbort, {
943
+ once: true
944
+ });
945
+ }
946
+ }
947
+ return {
948
+ submitToolResult: async (input) => {
949
+ channel.send({
950
+ type: "tool-result",
951
+ toolCallId: input.toolCallId,
952
+ output: input.output,
953
+ isError: input.isError
954
+ });
955
+ },
956
+ submitToolApproval: async (input) => {
957
+ channel.send({
958
+ type: "tool-approval-response",
959
+ approvalId: input.approvalId,
960
+ approved: input.approved,
961
+ reason: input.reason
962
+ });
963
+ },
964
+ submitUserMessage: async (text) => {
965
+ channel.send({ type: "user-message", text });
966
+ },
967
+ done
968
+ };
969
+ };
970
+ return {
971
+ sessionId,
972
+ isResume,
973
+ modelId: model,
974
+ doPromptTurn: async (promptOpts) => {
975
+ const control = wireTurn({
976
+ emit: promptOpts.emit,
977
+ abortSignal: promptOpts.abortSignal
978
+ });
979
+ let promptText = extractUserText(promptOpts.prompt);
980
+ if (!instructionsApplied && promptOpts.instructions) {
981
+ promptText = frameInstructions(promptOpts.instructions, promptText);
982
+ }
983
+ instructionsApplied = true;
984
+ const startMessage = {
985
+ type: "start",
986
+ prompt: promptText,
987
+ tools: (promptOpts.tools ?? []).map((t) => ({
988
+ name: t.name,
989
+ description: t.description,
990
+ inputSchema: t.inputSchema
991
+ })),
992
+ model,
993
+ maxTurns,
994
+ thinking,
995
+ ...skills.length > 0 ? { skills: skills.map((skill) => skill.name) } : {},
996
+ ...permissionMode ? { permissionMode } : {},
997
+ ...builtinToolFiltering ? { builtinToolFiltering } : {},
998
+ ...debug ? { debug } : {},
999
+ ...pendingResumeFlag ? { continue: true } : {}
1000
+ };
1001
+ pendingResumeFlag = false;
1002
+ channel.send(startMessage);
1003
+ return control;
1004
+ },
1005
+ doContinueTurn: async (continueOpts) => {
1006
+ const control = wireTurn({
1007
+ emit: continueOpts.emit,
1008
+ abortSignal: continueOpts.abortSignal
1009
+ });
1010
+ if (rerunContinue) {
1011
+ pendingResumeFlag = false;
1012
+ channel.send({
1013
+ type: "start",
1014
+ /*
1015
+ * A continuation nudge rather than an empty prompt: `continue: true`
1016
+ * rehydrates the prior thread, and this is the new user turn that
1017
+ * drives it forward. It must be non-empty — an empty text block is
1018
+ * rejected by the Anthropic API once the SDK stamps it with
1019
+ * `cache_control`.
1020
+ */
1021
+ prompt: "Continue.",
1022
+ tools: (continueOpts.tools ?? []).map((t) => ({
1023
+ name: t.name,
1024
+ description: t.description,
1025
+ inputSchema: t.inputSchema
1026
+ })),
1027
+ model,
1028
+ maxTurns,
1029
+ thinking,
1030
+ ...skills.length > 0 ? { skills: skills.map((skill) => skill.name) } : {},
1031
+ ...permissionMode ? { permissionMode } : {},
1032
+ ...builtinToolFiltering ? { builtinToolFiltering } : {},
1033
+ ...debug ? { debug } : {},
1034
+ continue: true
1035
+ });
1036
+ }
1037
+ return control;
1038
+ },
1039
+ doCompact: async (customInstructions) => {
1040
+ const text = customInstructions && customInstructions.trim() ? `/compact ${customInstructions.trim()}` : "/compact";
1041
+ channel.send({ type: "user-message", text });
1042
+ },
1043
+ doDetach: async () => {
1044
+ if (stopped) {
1045
+ throw new Error(
1046
+ `claude-code session ${sessionId} is already stopped; cannot detach.`
1047
+ );
1048
+ }
1049
+ stopped = true;
1050
+ const lastSeenEventId = await channel.suspend();
1051
+ const payload = {
1052
+ type: "resume-session",
1053
+ harnessId: "claude-code",
1054
+ specificationVersion: "harness-v1",
1055
+ data: {
1056
+ bridge: {
1057
+ port: bridgePort,
1058
+ token: bridgeToken,
1059
+ lastSeenEventId,
1060
+ sandboxId
1061
+ }
1062
+ }
1063
+ };
1064
+ return payload;
1065
+ },
1066
+ doDestroy: async () => {
1067
+ if (stopped) return stopPromise;
1068
+ stopped = true;
1069
+ stopPromise = (async () => {
1070
+ channel.beginClose();
1071
+ try {
1072
+ if (!channel.isClosed()) {
1073
+ channel.send({ type: "shutdown" });
1074
+ }
1075
+ } catch {
1076
+ }
1077
+ let stopTimer;
1078
+ try {
1079
+ if (proc) {
1080
+ await Promise.race([
1081
+ proc.wait(),
1082
+ new Promise((resolve) => {
1083
+ stopTimer = setTimeout(resolve, 5e3);
1084
+ stopTimer.unref?.();
1085
+ })
1086
+ ]);
1087
+ }
1088
+ } finally {
1089
+ if (stopTimer) clearTimeout(stopTimer);
1090
+ try {
1091
+ await proc?.kill();
1092
+ } catch {
1093
+ }
1094
+ channel.close();
1095
+ }
1096
+ })();
1097
+ return stopPromise;
1098
+ },
1099
+ doStop: async () => {
1100
+ if (stopped) {
1101
+ throw new Error(
1102
+ `claude-code session ${sessionId} is already stopped; cannot stop.`
1103
+ );
1104
+ }
1105
+ stopped = true;
1106
+ channel.beginClose();
1107
+ const data = channel.isClosed() ? {} : await new Promise((resolve, reject) => {
1108
+ const timer = setTimeout(() => {
1109
+ unsub();
1110
+ reject(
1111
+ new Error(
1112
+ `claude-code session ${sessionId} did not reply to detach within 5s.`
1113
+ )
1114
+ );
1115
+ }, 5e3);
1116
+ timer.unref?.();
1117
+ const unsub = channel.on("bridge-detach", (msg) => {
1118
+ clearTimeout(timer);
1119
+ unsub();
1120
+ resolve(msg.data);
1121
+ });
1122
+ try {
1123
+ channel.send({ type: "detach" });
1124
+ } catch (err) {
1125
+ clearTimeout(timer);
1126
+ unsub();
1127
+ reject(err);
1128
+ }
1129
+ });
1130
+ let stopTimer;
1131
+ try {
1132
+ if (proc) {
1133
+ await Promise.race([
1134
+ proc.wait(),
1135
+ new Promise((resolve) => {
1136
+ stopTimer = setTimeout(resolve, 5e3);
1137
+ stopTimer.unref?.();
1138
+ })
1139
+ ]);
1140
+ }
1141
+ } finally {
1142
+ if (stopTimer) clearTimeout(stopTimer);
1143
+ try {
1144
+ await proc?.kill();
1145
+ } catch {
1146
+ }
1147
+ channel.close();
1148
+ }
1149
+ const payload = {
1150
+ type: "resume-session",
1151
+ harnessId: "claude-code",
1152
+ specificationVersion: "harness-v1",
1153
+ data: data ?? {}
1154
+ };
1155
+ return payload;
1156
+ },
1157
+ doSuspendTurn: async () => {
1158
+ if (stopped) {
1159
+ throw new Error(
1160
+ `claude-code session ${sessionId} is stopped; cannot suspend.`
1161
+ );
1162
+ }
1163
+ stopped = true;
1164
+ await channel.interrupt();
1165
+ const lastSeenEventId = await channel.suspend();
1166
+ const payload = {
1167
+ type: "continue-turn",
1168
+ harnessId: "claude-code",
1169
+ specificationVersion: "harness-v1",
1170
+ data: {
1171
+ bridge: {
1172
+ port: bridgePort,
1173
+ token: bridgeToken,
1174
+ lastSeenEventId,
1175
+ sandboxId
1176
+ }
1177
+ }
1178
+ };
1179
+ return payload;
1180
+ }
1181
+ };
1182
+ }
1183
+ function frameInstructions(instructions, userText) {
1184
+ return `<session-instructions>
1185
+ 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.
1186
+
1187
+ ${instructions}
1188
+ </session-instructions>
1189
+
1190
+ <user-message>
1191
+ ${userText}
1192
+ </user-message>`;
1193
+ }
1194
+ function extractUserText(prompt) {
1195
+ if (typeof prompt === "string") return prompt;
1196
+ const { content } = prompt;
1197
+ if (typeof content === "string") return content;
1198
+ const parts = [];
1199
+ for (const part of content) {
1200
+ if (part.type !== "text") {
1201
+ throw new HarnessCapabilityUnsupportedError({
1202
+ harnessId: "claude-code",
1203
+ 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.`
1204
+ });
1205
+ }
1206
+ parts.push(part.text);
1207
+ }
1208
+ return parts.join("\n\n");
1209
+ }
1210
+
1211
+ // src/index.ts
1212
+ var claudeCode = createClaudeCode();
1213
+ export {
1214
+ VERSION,
1215
+ claudeCode,
1216
+ createClaudeCode
1217
+ };
1218
+ //# sourceMappingURL=index.js.map