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

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