@alis-build/harness-eval 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,563 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ import { spawn } from "node:child_process";
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ //#region src/types/stream.ts
7
+ /** Type guards. Prefer these over manual `e.type === "..."` checks at call sites. */
8
+ function isSystemInit(e) {
9
+ return e.type === "system" && e.subtype === "init";
10
+ }
11
+ function isSystemRetry(e) {
12
+ return e.type === "system" && e.subtype === "api_retry";
13
+ }
14
+ function isAssistantMessage(e) {
15
+ return e.type === "assistant";
16
+ }
17
+ function isUserMessage(e) {
18
+ return e.type === "user";
19
+ }
20
+ function isResult(e) {
21
+ return e.type === "result";
22
+ }
23
+ function isTextBlock(b) {
24
+ return b.type === "text";
25
+ }
26
+ function isToolUseBlock(b) {
27
+ return b.type === "tool_use";
28
+ }
29
+ function isToolResultBlock(b) {
30
+ return b.type === "tool_result";
31
+ }
32
+ //#endregion
33
+ //#region src/types/trajectory.ts
34
+ /**
35
+ * Extract the MCP namespace prefix from a tool name.
36
+ *
37
+ * Claude Code formats MCP tool names as `mcp__<server>__<tool>`. The namespace
38
+ * is the first two segments joined: `mcp__<server>`. Returns null for non-MCP
39
+ * tool names (built-ins like `Bash`, `Read`, `Edit`).
40
+ *
41
+ * @example
42
+ * namespaceOf("mcp__api__search_skills") // "mcp__api"
43
+ * namespaceOf("Bash") // null
44
+ */
45
+ function namespaceOf(toolName) {
46
+ if (!toolName.startsWith("mcp__")) return null;
47
+ const parts = toolName.split("__");
48
+ if (parts.length < 3) return null;
49
+ return `${parts[0]}__${parts[1]}`;
50
+ }
51
+ //#endregion
52
+ //#region src/trajectory/builder.ts
53
+ /**
54
+ * TrajectoryBuilder — consumes a stream of {@link StreamEvent} values and
55
+ * produces a {@link TrajectoryView}.
56
+ *
57
+ * State machine: the builder is a small, tolerant state machine. Invariants:
58
+ *
59
+ * - Exactly one `system/init` event opens the session. The builder requires
60
+ * it to be present before `build()`.
61
+ * - Each `assistant` event begins a new turn. Text blocks accumulate into
62
+ * the turn's text; `tool_use` blocks become `ToolCall` records.
63
+ * - `user` events with `tool_result` blocks deliver tool results back. We
64
+ * match them to pending calls by `tool_use_id`.
65
+ * - One `result` event closes the session and carries aggregate usage.
66
+ *
67
+ * The builder is *tolerant of partial streams*: a process killed mid-run
68
+ * produces a coherent (but flagged) view. Tool calls without matching results
69
+ * keep `result: null`. The `success` flag reflects whether a successful result
70
+ * event was actually observed.
71
+ *
72
+ * Why a class (not a reducer)?
73
+ * The internal `pendingCalls` map is mutable by design — we modify ToolCall
74
+ * objects in place when results arrive, so other parts of the view (which
75
+ * hold references to the same objects) see the update for free. A reducer
76
+ * would force a deep copy per result event, which is wasteful and would
77
+ * complicate identity-based queries.
78
+ */
79
+ var TrajectoryBuilder = class {
80
+ meta = null;
81
+ sessionStartTs = null;
82
+ turns = [];
83
+ allToolCalls = [];
84
+ /**
85
+ * tool_use_id → ToolCall, for matching results back to calls.
86
+ * Entries are removed once a result is observed.
87
+ */
88
+ pendingCalls = /* @__PURE__ */ new Map();
89
+ retries = [];
90
+ finalUsage = null;
91
+ finalCostUsd = 0;
92
+ finalDurationMs = 0;
93
+ finalNumTurns = 0;
94
+ finalResultText = "";
95
+ sawResultEvent = false;
96
+ resultIsError = false;
97
+ /**
98
+ * Consume one event. Safe to call with events in stream order.
99
+ *
100
+ * Unknown event types are silently ignored — the schema evolves and we
101
+ * don't want CI to break on a new event type we haven't modelled.
102
+ */
103
+ consume(event) {
104
+ if (isSystemInit(event)) {
105
+ this.meta = {
106
+ sessionId: event.session_id,
107
+ model: event.model,
108
+ cwd: event.cwd,
109
+ permissionMode: event.permissionMode,
110
+ availableTools: event.tools ?? [],
111
+ mcpServers: (event.mcp_servers ?? []).map((s) => ({
112
+ name: s.name,
113
+ status: s.status
114
+ }))
115
+ };
116
+ this.sessionStartTs = Date.now();
117
+ return;
118
+ }
119
+ if (event.type === "system" && event.subtype === "api_retry") {
120
+ this.retries.push({
121
+ offsetMs: this.sessionStartTs ? Date.now() - this.sessionStartTs : 0,
122
+ raw: event
123
+ });
124
+ return;
125
+ }
126
+ if (isAssistantMessage(event)) {
127
+ this.handleAssistantMessage(event);
128
+ return;
129
+ }
130
+ if (isUserMessage(event)) {
131
+ this.handleUserMessage(event);
132
+ return;
133
+ }
134
+ if (isResult(event)) {
135
+ this.sawResultEvent = true;
136
+ this.resultIsError = event.is_error;
137
+ this.finalUsage = event.usage ?? null;
138
+ this.finalCostUsd = event.total_cost_usd ?? 0;
139
+ this.finalDurationMs = event.duration_ms ?? 0;
140
+ this.finalNumTurns = event.num_turns ?? 0;
141
+ this.finalResultText = event.result ?? "";
142
+ return;
143
+ }
144
+ }
145
+ /**
146
+ * Finalize the view. Call after consuming the last event from the stream.
147
+ *
148
+ * Throws if no `system/init` was observed — at that point we have no model,
149
+ * no session id, and no available-tools list, which means assertions like
150
+ * "called any mcp__api__* tool" can't even be evaluated meaningfully.
151
+ */
152
+ build() {
153
+ if (this.meta === null) throw new Error("TrajectoryBuilder.build() called before any system/init event was observed. The harness may have failed to start, or the stream was truncated before init.");
154
+ const lastTurn = this.turns[this.turns.length - 1];
155
+ const accumulatedText = this.turns.map((t) => t.text).filter((t) => t.length > 0).join("\n\n").trim();
156
+ return {
157
+ meta: this.meta,
158
+ toolCalls: this.allToolCalls,
159
+ turns: this.turns,
160
+ finalResponse: accumulatedText || this.finalResultText,
161
+ finalStopReason: lastTurn?.stopReason ?? null,
162
+ usage: {
163
+ inputTokens: this.finalUsage?.input_tokens ?? 0,
164
+ outputTokens: this.finalUsage?.output_tokens ?? 0,
165
+ totalCostUsd: this.finalCostUsd,
166
+ durationMs: this.finalDurationMs,
167
+ numTurns: this.finalNumTurns || this.turns.length
168
+ },
169
+ retries: this.retries,
170
+ success: this.sawResultEvent && !this.resultIsError
171
+ };
172
+ }
173
+ handleAssistantMessage(event) {
174
+ const turnIndex = this.turns.length;
175
+ const textChunks = [];
176
+ const toolCallsThisTurn = [];
177
+ for (const block of event.message.content) {
178
+ if (isTextBlock(block)) {
179
+ textChunks.push(block.text);
180
+ continue;
181
+ }
182
+ if (isToolUseBlock(block)) {
183
+ const call = {
184
+ name: block.name,
185
+ namespace: namespaceOf(block.name),
186
+ callId: block.id,
187
+ args: block.input,
188
+ result: null,
189
+ isError: false,
190
+ turnIndex,
191
+ callIndex: this.allToolCalls.length
192
+ };
193
+ this.allToolCalls.push(call);
194
+ this.pendingCalls.set(block.id, call);
195
+ toolCallsThisTurn.push(call);
196
+ continue;
197
+ }
198
+ }
199
+ this.turns.push({
200
+ turnIndex,
201
+ text: textChunks.join("").trim(),
202
+ toolCalls: toolCallsThisTurn,
203
+ stopReason: event.message.stop_reason ?? null
204
+ });
205
+ }
206
+ handleUserMessage(event) {
207
+ const content = event.message.content;
208
+ if (typeof content === "string") return;
209
+ for (const block of content) {
210
+ if (!isToolResultBlock(block)) continue;
211
+ const call = this.pendingCalls.get(block.tool_use_id);
212
+ if (!call) continue;
213
+ call.result = block.content;
214
+ call.isError = block.is_error ?? false;
215
+ this.pendingCalls.delete(block.tool_use_id);
216
+ }
217
+ }
218
+ };
219
+ /**
220
+ * Convenience: drain an async iterable of events through a fresh builder.
221
+ *
222
+ * Suitable when you have the full event stream and just want the view.
223
+ * For interactive/incremental scenarios (e.g. surfacing partial state in a UI)
224
+ * instantiate {@link TrajectoryBuilder} directly and call `consume()` /
225
+ * `build()` yourself.
226
+ */
227
+ async function buildTrajectory(events) {
228
+ const builder = new TrajectoryBuilder();
229
+ for await (const event of events) builder.consume(event);
230
+ return builder.build();
231
+ }
232
+ //#endregion
233
+ //#region src/parsers/stream-json.ts
234
+ /**
235
+ * Parse a readable stream of NDJSON into a sequence of typed stream-json events.
236
+ *
237
+ * @example
238
+ * const child = spawn("claude", ["-p", prompt, "--output-format", "stream-json", "--verbose"]);
239
+ * for await (const result of parseStreamJson(child.stdout)) {
240
+ * if (result.ok) builder.consume(result.event);
241
+ * else console.warn("malformed stream line:", result.rawLine, result.error);
242
+ * }
243
+ */
244
+ async function* parseStreamJson(stream) {
245
+ let buffer = "";
246
+ stream.setEncoding("utf8");
247
+ for await (const chunk of stream) {
248
+ buffer += chunk;
249
+ let newlineIdx;
250
+ while ((newlineIdx = buffer.indexOf("\n")) !== -1) {
251
+ const line = buffer.slice(0, newlineIdx).trim();
252
+ buffer = buffer.slice(newlineIdx + 1);
253
+ if (line.length === 0) continue;
254
+ yield tryParseLine(line);
255
+ }
256
+ }
257
+ const trailing = buffer.trim();
258
+ if (trailing.length > 0) yield tryParseLine(trailing);
259
+ }
260
+ /**
261
+ * Parse a single line. Extracted as a helper so the generator stays readable.
262
+ *
263
+ * Note: we do not validate the event structure beyond `JSON.parse`. Runtime
264
+ * validation (e.g. zod) is overkill here — the schema is stable enough at
265
+ * runtime, and the TrajectoryBuilder is tolerant of missing fields. Adding
266
+ * validation would be premature.
267
+ */
268
+ function tryParseLine(line) {
269
+ try {
270
+ return {
271
+ ok: true,
272
+ event: JSON.parse(line),
273
+ rawLine: line
274
+ };
275
+ } catch (err) {
276
+ return {
277
+ ok: false,
278
+ error: err instanceof Error ? err : new Error(String(err)),
279
+ rawLine: line
280
+ };
281
+ }
282
+ }
283
+ //#endregion
284
+ //#region src/adapters/types.ts
285
+ /**
286
+ * Thrown when the harness fails to produce a usable trajectory.
287
+ *
288
+ * Most commonly this means the process failed before emitting a usable
289
+ * session init event. Inspect `diagnostics.stderr` for the cause.
290
+ */
291
+ var AdapterError = class extends Error {
292
+ diagnostics;
293
+ constructor(message, diagnostics) {
294
+ super(message);
295
+ this.diagnostics = diagnostics;
296
+ this.name = "AdapterError";
297
+ }
298
+ };
299
+ //#endregion
300
+ //#region src/adapters/claude-code/flags.ts
301
+ function pushRepeatableFlag(args, flag, values) {
302
+ if (!values) return;
303
+ for (const value of values) args.push(flag, value);
304
+ }
305
+ function pushOptionalFlag(args, flag, value) {
306
+ if (value === void 0) return;
307
+ if (typeof value === "boolean") {
308
+ if (value) args.push(flag);
309
+ return;
310
+ }
311
+ args.push(flag, String(value));
312
+ }
313
+ /** Append Claude Code CLI flags shared by harness runs and grading judges. */
314
+ function appendClaudeCodeFlags(args, config) {
315
+ pushRepeatableFlag(args, "--plugin-dir", config.pluginDirs);
316
+ pushRepeatableFlag(args, "--plugin-url", config.pluginUrls);
317
+ pushRepeatableFlag(args, "--add-dir", config.addDirs);
318
+ pushOptionalFlag(args, "--mcp-config", config.mcpConfig);
319
+ pushOptionalFlag(args, "--model", config.model);
320
+ pushOptionalFlag(args, "--permission-mode", config.permissionMode);
321
+ pushOptionalFlag(args, "--effort", config.effort);
322
+ pushOptionalFlag(args, "--agent", config.agent);
323
+ pushOptionalFlag(args, "--fallback-model", config.fallbackModel);
324
+ pushOptionalFlag(args, "--tools", config.tools);
325
+ pushOptionalFlag(args, "--settings", config.settings);
326
+ pushOptionalFlag(args, "--setting-sources", config.settingSources);
327
+ pushOptionalFlag(args, "--max-turns", config.maxTurns);
328
+ pushOptionalFlag(args, "--max-budget-usd", config.maxBudgetUsd);
329
+ pushOptionalFlag(args, "--system-prompt", config.systemPrompt);
330
+ pushOptionalFlag(args, "--system-prompt-file", config.systemPromptFile);
331
+ pushOptionalFlag(args, "--append-system-prompt", config.appendSystemPrompt);
332
+ pushOptionalFlag(args, "--append-system-prompt-file", config.appendSystemPromptFile);
333
+ pushOptionalFlag(args, "--debug", config.debug);
334
+ pushOptionalFlag(args, "--debug-file", config.debugFile);
335
+ if (config.allowedTools && config.allowedTools.length > 0) args.push("--allowedTools", config.allowedTools.join(","));
336
+ if (config.disallowedTools && config.disallowedTools.length > 0) args.push("--disallowedTools", config.disallowedTools.join(","));
337
+ pushOptionalFlag(args, "--strict-mcp-config", config.strictMcpConfig);
338
+ pushOptionalFlag(args, "--include-hook-events", config.includeHookEvents);
339
+ pushOptionalFlag(args, "--no-session-persistence", config.noSessionPersistence);
340
+ pushOptionalFlag(args, "--disable-slash-commands", config.disableSlashCommands);
341
+ pushOptionalFlag(args, "--bare", config.bare);
342
+ pushOptionalFlag(args, "--safe-mode", config.safeMode);
343
+ pushOptionalFlag(args, "--allow-dangerously-skip-permissions", config.allowDangerouslySkipPermissions);
344
+ pushOptionalFlag(args, "--dangerously-skip-permissions", config.dangerouslySkipPermissions);
345
+ }
346
+ /**
347
+ * Build the argument vector for spawning `claude`.
348
+ *
349
+ * Order matters only for flags that take values — value flags must come
350
+ * after their flag name. Everything else is order-independent.
351
+ */
352
+ function buildArgs(config) {
353
+ const args = [
354
+ "-p",
355
+ config.prompt,
356
+ "--output-format",
357
+ "stream-json",
358
+ "--verbose"
359
+ ];
360
+ appendClaudeCodeFlags(args, config);
361
+ return args;
362
+ }
363
+ /** Build args for an LLM judge subprocess (`--output-format json`). */
364
+ function buildJudgeArgs(prompt, config = {}) {
365
+ const args = [
366
+ "-p",
367
+ prompt,
368
+ "--output-format",
369
+ "json"
370
+ ];
371
+ const permissionMode = config.permissionMode ?? "bypassPermissions";
372
+ appendClaudeCodeFlags(args, {
373
+ ...config,
374
+ permissionMode
375
+ });
376
+ return args;
377
+ }
378
+ //#endregion
379
+ //#region src/adapters/claude-code/process.ts
380
+ /**
381
+ * Process management for the Claude Code adapter.
382
+ *
383
+ * This module owns spawning, timeout, abort signal handling, and process-tree
384
+ * teardown. The orchestrator (`index.ts`) consumes the returned handle —
385
+ * reading stdout and waiting for completion — but doesn't worry about how
386
+ * the process gets killed or how its config gets isolated.
387
+ *
388
+ * Why a separate module? Process management is the one part of the adapter
389
+ * with real I/O complexity (process groups, signal escalation, temp-dir
390
+ * lifecycle, env merging). Isolating it makes the orchestrator easy to read
391
+ * and lets us swap the spawning logic if we later need to, e.g., wrap claude
392
+ * in a sandbox runner.
393
+ */
394
+ /** Default hard timeout per run. Tunable via config.timeoutMs. */
395
+ const DEFAULT_TIMEOUT_MS = 300 * 1e3;
396
+ /**
397
+ * Grace period between SIGTERM and SIGKILL. Most processes shut down cleanly
398
+ * within a few seconds; this gives them that chance while preventing CI from
399
+ * hanging indefinitely on a stuck child.
400
+ */
401
+ const KILL_GRACE_MS = 5e3;
402
+ /**
403
+ * Spawn `claude` in headless mode with isolated config and a process-group
404
+ * lifecycle. See {@link SpawnedClaude} for how to consume the result.
405
+ */
406
+ async function spawnClaude(config) {
407
+ const binary = config.binary ?? "claude";
408
+ const args = buildArgs(config);
409
+ const tempConfigDir = config.isolateConfig !== false ? await mkdtemp(join(tmpdir(), "harness-eval-")) : null;
410
+ const env = {
411
+ ...process.env,
412
+ ...config.env
413
+ };
414
+ if (tempConfigDir) env.CLAUDE_CONFIG_DIR = tempConfigDir;
415
+ const child = spawn(binary, args, {
416
+ cwd: config.cwd ?? process.cwd(),
417
+ env,
418
+ stdio: [
419
+ "ignore",
420
+ "pipe",
421
+ "pipe"
422
+ ],
423
+ detached: true
424
+ });
425
+ let timedOut = false;
426
+ let killEscalation = null;
427
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
428
+ const scheduleKillEscalation = () => {
429
+ if (killEscalation) clearTimeout(killEscalation);
430
+ killEscalation = setTimeout(() => killTree(child, "SIGKILL"), KILL_GRACE_MS);
431
+ };
432
+ const timeoutTimer = setTimeout(() => {
433
+ timedOut = true;
434
+ killTree(child, "SIGTERM");
435
+ scheduleKillEscalation();
436
+ }, timeoutMs);
437
+ const onAbort = () => {
438
+ killTree(child, "SIGTERM");
439
+ scheduleKillEscalation();
440
+ };
441
+ config.signal?.addEventListener("abort", onAbort, { once: true });
442
+ const stderrChunks = [];
443
+ child.stderr?.setEncoding("utf8");
444
+ child.stderr?.on("data", (chunk) => {
445
+ stderrChunks.push(chunk);
446
+ });
447
+ const stderrCollected = new Promise((resolve) => {
448
+ const finalize = () => resolve(stderrChunks.join(""));
449
+ child.stderr?.on("end", finalize);
450
+ child.stderr?.on("error", finalize);
451
+ });
452
+ const done = new Promise((resolve) => {
453
+ let settled = false;
454
+ const finalize = (exitCode, signal) => {
455
+ if (settled) return;
456
+ settled = true;
457
+ clearTimeout(timeoutTimer);
458
+ if (killEscalation) clearTimeout(killEscalation);
459
+ config.signal?.removeEventListener("abort", onAbort);
460
+ resolve({
461
+ exitCode,
462
+ signal
463
+ });
464
+ };
465
+ child.on("close", (code, signal) => finalize(code, signal));
466
+ child.on("error", () => finalize(null, null));
467
+ });
468
+ const cleanup = async () => {
469
+ if (!tempConfigDir) return;
470
+ try {
471
+ await rm(tempConfigDir, {
472
+ recursive: true,
473
+ force: true
474
+ });
475
+ } catch {}
476
+ };
477
+ return {
478
+ stdout: child.stdout,
479
+ done,
480
+ stderrCollected,
481
+ timedOut: () => timedOut,
482
+ cleanup
483
+ };
484
+ }
485
+ /**
486
+ * Kill the child's process group, then fall back to the bare PID if the
487
+ * group is already gone. This catches MCP server subprocesses and tool
488
+ * processes spawned by claude.
489
+ *
490
+ * Why both? On some platforms the process group dies before we get here
491
+ * (the child itself already cleaned up), in which case `kill(-pid)` throws
492
+ * ESRCH. The fallback handles that edge case without leaking zombies in
493
+ * the common case.
494
+ */
495
+ function killTree(child, signal) {
496
+ if (child.pid === void 0) return;
497
+ try {
498
+ process.kill(-child.pid, signal);
499
+ } catch {
500
+ try {
501
+ child.kill(signal);
502
+ } catch {}
503
+ }
504
+ }
505
+ //#endregion
506
+ //#region src/adapters/claude-code/index.ts
507
+ /**
508
+ * Claude Code adapter — public API.
509
+ */
510
+ var claude_code_exports = /* @__PURE__ */ __exportAll({
511
+ AdapterError: () => AdapterError,
512
+ claudeCodeAdapter: () => claudeCodeAdapter,
513
+ runClaudeCode: () => runClaudeCode
514
+ });
515
+ /**
516
+ * Run Claude Code in headless mode and return a trajectory.
517
+ */
518
+ async function runClaudeCode(config) {
519
+ const startTs = Date.now();
520
+ const spawned = await spawnClaude(config);
521
+ const builder = new TrajectoryBuilder();
522
+ const rawEvents = [];
523
+ const parseErrors = [];
524
+ try {
525
+ for await (const result of parseStreamJson(spawned.stdout)) if (result.ok) {
526
+ builder.consume(result.event);
527
+ rawEvents.push(result.event);
528
+ } else parseErrors.push({
529
+ line: result.rawLine,
530
+ error: result.error.message
531
+ });
532
+ const [{ exitCode, signal }, stderr] = await Promise.all([spawned.done, spawned.stderrCollected]);
533
+ const diagnostics = {
534
+ exitCode,
535
+ signal,
536
+ stderr,
537
+ parseErrors,
538
+ timedOut: spawned.timedOut(),
539
+ durationMs: Date.now() - startTs
540
+ };
541
+ let view;
542
+ try {
543
+ view = builder.build();
544
+ } catch (err) {
545
+ throw new AdapterError(`harness produced no usable trajectory: ${err instanceof Error ? err.message : String(err)}`, diagnostics);
546
+ }
547
+ return {
548
+ view,
549
+ diagnostics,
550
+ rawEvents
551
+ };
552
+ } finally {
553
+ await spawned.cleanup();
554
+ }
555
+ }
556
+ const claudeCodeAdapter = {
557
+ id: "claude-code",
558
+ run: runClaudeCode
559
+ };
560
+ //#endregion
561
+ export { isUserMessage as _, AdapterError as a, buildTrajectory as c, isResult as d, isSystemInit as f, isToolUseBlock as g, isToolResultBlock as h, buildJudgeArgs as i, namespaceOf as l, isTextBlock as m, claude_code_exports as n, parseStreamJson as o, isSystemRetry as p, runClaudeCode as r, TrajectoryBuilder as s, claudeCodeAdapter as t, isAssistantMessage as u };
562
+
563
+ //# sourceMappingURL=claude-code-ycT0JQZF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-code-ycT0JQZF.js","names":[],"sources":["../src/types/stream.ts","../src/types/trajectory.ts","../src/trajectory/builder.ts","../src/parsers/stream-json.ts","../src/adapters/types.ts","../src/adapters/claude-code/flags.ts","../src/adapters/claude-code/process.ts","../src/adapters/claude-code/index.ts"],"sourcesContent":["/**\n * Discriminated union of events emitted by Claude Code's\n * `--output-format stream-json` mode.\n *\n * The format is NDJSON (one JSON object per line on stdout). Each line has\n * a required `type` field and often a `subtype` for further disambiguation.\n *\n * Source notes: the stream-json schema is not formally documented as of mid-2026.\n * These types are derived from:\n * - https://code.claude.com/docs/en/headless\n * - https://github.com/anthropics/claude-code/issues/24612 (event-types tracking issue)\n * - https://takopi.dev/reference/runners/claude/stream-json-cheatsheet/\n * - The `@anthropic-ai/claude-agent-sdk` TypeScript declaration files,\n * which are the de-facto source of truth.\n *\n * When adding new event types, prefer extending the union here rather than\n * branching on `any` in callers. Unknown events should be tolerated silently\n * by the builder (the schema evolves and we don't want CI to break on a new\n * event type we haven't modelled yet).\n */\n\n/** Top-level discriminated union of stream-json events. */\nexport type StreamEvent =\n | SystemInitEvent\n | SystemRetryEvent\n | SystemPluginInstallEvent\n | SystemCompactBoundaryEvent\n | SystemUnknownEvent\n | AssistantMessageEvent\n | UserMessageEvent\n | ResultEvent;\n\n// system events\n\n/** Emitted once at session start. Carries the session-level metadata. */\nexport interface SystemInitEvent {\n type: \"system\";\n subtype: \"init\";\n session_id: string;\n cwd: string;\n model: string;\n permissionMode?: string;\n apiKeySource?: string;\n /** Names of tools available in the session (built-in + MCP). */\n tools: string[];\n /** MCP servers configured for this session, with connection status. */\n mcp_servers: McpServerStatus[];\n}\n\nexport interface McpServerStatus {\n name: string;\n status: \"connected\" | \"disconnected\" | \"error\" | string;\n}\n\n/** Emitted when the API rate-limits us or otherwise asks for a retry. */\nexport interface SystemRetryEvent {\n type: \"system\";\n subtype: \"api_retry\";\n session_id: string;\n /** Implementation-defined retry payload (delay, reason, etc). */\n [key: string]: unknown;\n}\n\n/** Emitted while marketplace plugins are installing pre-session. */\nexport interface SystemPluginInstallEvent {\n type: \"system\";\n subtype: \"plugin_install\";\n session_id: string;\n [key: string]: unknown;\n}\n\n/** Emitted when Claude Code compacts the context window mid-session. */\nexport interface SystemCompactBoundaryEvent {\n type: \"system\";\n subtype: \"compact_boundary\";\n session_id: string;\n [key: string]: unknown;\n}\n\n/**\n * Catch-all for `type: \"system\"` events we haven't modelled.\n *\n * Keeps the union exhaustive while tolerating schema evolution. Callers should\n * either explicitly handle a known subtype or fall through to ignore.\n */\nexport interface SystemUnknownEvent {\n type: \"system\";\n subtype: string;\n session_id?: string;\n [key: string]: unknown;\n}\n\n// conversational events\n\n/** One assistant turn. The `message` field mirrors the Anthropic Messages API shape. */\nexport interface AssistantMessageEvent {\n type: \"assistant\";\n session_id: string;\n message: AssistantMessage;\n}\n\nexport interface AssistantMessage {\n id: string;\n type: \"message\";\n role: \"assistant\";\n content: ContentBlock[];\n model?: string;\n stop_reason?: StopReason | null;\n usage?: Usage;\n}\n\n/**\n * A user-role message in the stream.\n *\n * In stream-json these are usually *synthetic* — the harness injects them to\n * feed tool results back into the conversation after dispatching a tool. The\n * very first user message (the prompt) is also emitted here for completeness.\n */\nexport interface UserMessageEvent {\n type: \"user\";\n session_id: string;\n message: UserMessage;\n}\n\nexport interface UserMessage {\n role: \"user\";\n /** String for the initial prompt, array of blocks when carrying tool results. */\n content: ContentBlock[] | string;\n}\n\n// content blocks\n\nexport type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock;\n\nexport interface TextBlock {\n type: \"text\";\n text: string;\n}\n\nexport interface ToolUseBlock {\n type: \"tool_use\";\n /** Unique id assigned by the model; used to match tool_result back to this call. */\n id: string;\n /** Tool name. MCP tools follow the convention `mcp__<server>__<tool>`. */\n name: string;\n /** Arguments the model passed. Schema is per-tool. */\n input: unknown;\n}\n\nexport interface ToolResultBlock {\n type: \"tool_result\";\n /** The id of the corresponding tool_use block. */\n tool_use_id: string;\n /** Tool output. May be plain text or further content blocks for richer tools. */\n content: string | ContentBlock[];\n is_error?: boolean;\n}\n\n// result envelope\n\n/** Emitted once at session end. Carries aggregate usage and cost. */\nexport interface ResultEvent {\n type: \"result\";\n subtype: \"success\" | \"error\";\n session_id: string;\n total_cost_usd: number;\n is_error: boolean;\n duration_ms: number;\n duration_api_ms?: number;\n num_turns: number;\n /** The final text the harness returned, if any. */\n result?: string;\n usage?: Usage;\n}\n\n// shared scalars\n\n/**\n * Reasons the model can stop a turn. Open-ended string union because new\n * stop reasons appear over time.\n */\nexport type StopReason =\n | \"end_turn\"\n | \"tool_use\"\n | \"max_tokens\"\n | \"stop_sequence\"\n | (string & {});\n\nexport interface Usage {\n input_tokens: number;\n output_tokens: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n}\n\n// type guards\n\n/** Type guards. Prefer these over manual `e.type === \"...\"` checks at call sites. */\n\nexport function isSystemInit(e: StreamEvent): e is SystemInitEvent {\n return e.type === \"system\" && (e as SystemInitEvent).subtype === \"init\";\n}\n\nexport function isSystemRetry(e: StreamEvent): e is SystemRetryEvent {\n return e.type === \"system\" && (e as SystemRetryEvent).subtype === \"api_retry\";\n}\n\nexport function isAssistantMessage(e: StreamEvent): e is AssistantMessageEvent {\n return e.type === \"assistant\";\n}\n\nexport function isUserMessage(e: StreamEvent): e is UserMessageEvent {\n return e.type === \"user\";\n}\n\nexport function isResult(e: StreamEvent): e is ResultEvent {\n return e.type === \"result\";\n}\n\nexport function isTextBlock(b: ContentBlock): b is TextBlock {\n return b.type === \"text\";\n}\n\nexport function isToolUseBlock(b: ContentBlock): b is ToolUseBlock {\n return b.type === \"tool_use\";\n}\n\nexport function isToolResultBlock(b: ContentBlock): b is ToolResultBlock {\n return b.type === \"tool_result\";\n}\n","/**\n * TrajectoryView — the assertion-friendly projection of a Claude Code session.\n *\n * The view is derived from the stream of {@link StreamEvent} values produced by\n * the harness, but is optimized for the queries that the assertion DSL needs to\n * express:\n *\n * - did tool X get called? (look at `toolCalls`)\n * - did tool A come before tool B? (compare `turnIndex` / `callIndex`)\n * - was a tool called with arguments matching predicate P? (`toolCalls[i].args`)\n * - did the agent answer without using any tool? (`toolCalls.length === 0`)\n *\n * The view is reconstructable from the raw events (lossless w.r.t. assertions),\n * but operating on it directly is dramatically simpler than walking event\n * streams or OTel span trees.\n *\n * Design notes:\n * - `turnIndex` and `callIndex` are the right primitives for ordering.\n * Wall-clock timestamps from the stream are unreliable for sub-second\n * ordering and parallel tool dispatch.\n * - Parallel tool calls (multiple `tool_use` blocks in one assistant message)\n * share a `turnIndex` but have distinct `callIndex` values in emission order.\n * - `namespace` is precomputed so assertions like `called(pattern: \"mcp__api__*\")`\n * can do a cheap string check.\n */\n\nimport type { StopReason } from \"./stream\";\n\nexport interface TrajectoryView {\n /** Session metadata, captured from the `system/init` event. */\n meta: SessionMeta;\n\n /** Every tool call, in global emission order. */\n toolCalls: ToolCall[];\n\n /** Each assistant turn: text content + any tool calls emitted in that turn. */\n turns: AssistantTurn[];\n\n /** All assistant text concatenated across turns. Useful for `response_contains`. */\n finalResponse: string;\n\n /** Stop reason of the *last* assistant turn. */\n finalStopReason: StopReason | null;\n\n /** Aggregate usage and cost from the result event. */\n usage: UsageSummary;\n\n /** Retry events observed during the run (rate limits, transient errors). */\n retries: RetryRecord[];\n\n /** Whether the result envelope indicated success. */\n success: boolean;\n}\n\nexport interface SessionMeta {\n sessionId: string;\n model: string;\n cwd: string;\n permissionMode?: string;\n /** Tool names the harness reported as available at session start. */\n availableTools: string[];\n /** MCP servers configured for the session, with connection status. */\n mcpServers: { name: string; status: string }[];\n}\n\nexport interface ToolCall {\n /** Fully-qualified tool name, e.g. `\"mcp__api__search_skills\"` or `\"Bash\"`. */\n name: string;\n\n /**\n * Namespace prefix for MCP-style names (`\"mcp__api\"`), or null for built-ins.\n * Precomputed via {@link namespaceOf} for cheap pattern matching.\n */\n namespace: string | null;\n\n /** The `tool_use` block's `id`; matches a later `tool_result.tool_use_id`. */\n callId: string;\n\n /** Args the model emitted on this call. Tool-specific schema. */\n args: unknown;\n\n /** Tool result, or null if no result was observed (e.g. process killed). */\n result: unknown | null;\n\n /** Whether the tool reported an error in its result. */\n isError: boolean;\n\n /**\n * Which assistant turn produced this call. Parallel calls within a single\n * assistant message share a `turnIndex`.\n */\n turnIndex: number;\n\n /** Index in the global ordered tool-call sequence. */\n callIndex: number;\n}\n\nexport interface AssistantTurn {\n turnIndex: number;\n /** Text emitted in this turn (may be empty if turn was tool-only). */\n text: string;\n /** Tool calls emitted in this turn, in their block order. */\n toolCalls: ToolCall[];\n /** Stop reason reported by the model for this turn. */\n stopReason: StopReason | null;\n}\n\nexport interface UsageSummary {\n inputTokens: number;\n outputTokens: number;\n totalCostUsd: number;\n durationMs: number;\n numTurns: number;\n}\n\nexport interface RetryRecord {\n /** ms since session start (approximate; the stream doesn't include precise ts). */\n offsetMs: number;\n /** Raw payload from the `system/api_retry` event for diagnostics. */\n raw: unknown;\n}\n\n// helpers\n\n/**\n * Extract the MCP namespace prefix from a tool name.\n *\n * Claude Code formats MCP tool names as `mcp__<server>__<tool>`. The namespace\n * is the first two segments joined: `mcp__<server>`. Returns null for non-MCP\n * tool names (built-ins like `Bash`, `Read`, `Edit`).\n *\n * @example\n * namespaceOf(\"mcp__api__search_skills\") // \"mcp__api\"\n * namespaceOf(\"Bash\") // null\n */\nexport function namespaceOf(toolName: string): string | null {\n if (!toolName.startsWith(\"mcp__\")) return null;\n const parts = toolName.split(\"__\");\n if (parts.length < 3) return null;\n return `${parts[0]}__${parts[1]}`;\n}\n","/**\n * TrajectoryBuilder — consumes a stream of {@link StreamEvent} values and\n * produces a {@link TrajectoryView}.\n *\n * State machine: the builder is a small, tolerant state machine. Invariants:\n *\n * - Exactly one `system/init` event opens the session. The builder requires\n * it to be present before `build()`.\n * - Each `assistant` event begins a new turn. Text blocks accumulate into\n * the turn's text; `tool_use` blocks become `ToolCall` records.\n * - `user` events with `tool_result` blocks deliver tool results back. We\n * match them to pending calls by `tool_use_id`.\n * - One `result` event closes the session and carries aggregate usage.\n *\n * The builder is *tolerant of partial streams*: a process killed mid-run\n * produces a coherent (but flagged) view. Tool calls without matching results\n * keep `result: null`. The `success` flag reflects whether a successful result\n * event was actually observed.\n *\n * Why a class (not a reducer)?\n * The internal `pendingCalls` map is mutable by design — we modify ToolCall\n * objects in place when results arrive, so other parts of the view (which\n * hold references to the same objects) see the update for free. A reducer\n * would force a deep copy per result event, which is wasteful and would\n * complicate identity-based queries.\n */\n\nimport {\n isAssistantMessage,\n isResult,\n isSystemInit,\n isTextBlock,\n isToolResultBlock,\n isToolUseBlock,\n isUserMessage,\n type StreamEvent,\n type Usage,\n} from \"../types/stream\";\nimport {\n namespaceOf,\n type AssistantTurn,\n type RetryRecord,\n type SessionMeta,\n type ToolCall,\n type TrajectoryView,\n} from \"../types/trajectory\";\n\nexport class TrajectoryBuilder {\n private meta: SessionMeta | null = null;\n private sessionStartTs: number | null = null;\n\n private turns: AssistantTurn[] = [];\n private allToolCalls: ToolCall[] = [];\n\n /**\n * tool_use_id → ToolCall, for matching results back to calls.\n * Entries are removed once a result is observed.\n */\n private pendingCalls: Map<string, ToolCall> = new Map();\n\n private retries: RetryRecord[] = [];\n\n private finalUsage: Usage | null = null;\n private finalCostUsd = 0;\n private finalDurationMs = 0;\n private finalNumTurns = 0;\n private finalResultText = \"\";\n private sawResultEvent = false;\n private resultIsError = false;\n\n /**\n * Consume one event. Safe to call with events in stream order.\n *\n * Unknown event types are silently ignored — the schema evolves and we\n * don't want CI to break on a new event type we haven't modelled.\n */\n consume(event: StreamEvent): void {\n if (isSystemInit(event)) {\n this.meta = {\n sessionId: event.session_id,\n model: event.model,\n cwd: event.cwd,\n permissionMode: event.permissionMode,\n availableTools: event.tools ?? [],\n mcpServers: (event.mcp_servers ?? []).map((s) => ({\n name: s.name,\n status: s.status,\n })),\n };\n this.sessionStartTs = Date.now();\n return;\n }\n\n if (event.type === \"system\" && event.subtype === \"api_retry\") {\n this.retries.push({\n offsetMs: this.sessionStartTs ? Date.now() - this.sessionStartTs : 0,\n raw: event,\n });\n return;\n }\n\n if (isAssistantMessage(event)) {\n this.handleAssistantMessage(event);\n return;\n }\n\n if (isUserMessage(event)) {\n this.handleUserMessage(event);\n return;\n }\n\n if (isResult(event)) {\n this.sawResultEvent = true;\n this.resultIsError = event.is_error;\n this.finalUsage = event.usage ?? null;\n this.finalCostUsd = event.total_cost_usd ?? 0;\n this.finalDurationMs = event.duration_ms ?? 0;\n this.finalNumTurns = event.num_turns ?? 0;\n this.finalResultText = event.result ?? \"\";\n return;\n }\n\n // Unknown event: ignored. See class doc.\n }\n\n /**\n * Finalize the view. Call after consuming the last event from the stream.\n *\n * Throws if no `system/init` was observed — at that point we have no model,\n * no session id, and no available-tools list, which means assertions like\n * \"called any mcp__api__* tool\" can't even be evaluated meaningfully.\n */\n build(): TrajectoryView {\n if (this.meta === null) {\n throw new Error(\n \"TrajectoryBuilder.build() called before any system/init event was observed. \" +\n \"The harness may have failed to start, or the stream was truncated before init.\",\n );\n }\n\n const lastTurn = this.turns[this.turns.length - 1];\n\n // Prefer the assistant text we accumulated turn-by-turn over the\n // `result.result` field, because the latter is sometimes a summary\n // and the former is exactly what the model said.\n const accumulatedText = this.turns\n .map((t) => t.text)\n .filter((t) => t.length > 0)\n .join(\"\\n\\n\")\n .trim();\n\n return {\n meta: this.meta,\n toolCalls: this.allToolCalls,\n turns: this.turns,\n finalResponse: accumulatedText || this.finalResultText,\n finalStopReason: lastTurn?.stopReason ?? null,\n usage: {\n inputTokens: this.finalUsage?.input_tokens ?? 0,\n outputTokens: this.finalUsage?.output_tokens ?? 0,\n totalCostUsd: this.finalCostUsd,\n durationMs: this.finalDurationMs,\n // Fall back to observed turn count if the result event was missing.\n numTurns: this.finalNumTurns || this.turns.length,\n },\n retries: this.retries,\n // Successful = saw a non-error result envelope. Streams that ended without\n // a result event are reported as unsuccessful regardless of tool outcomes.\n success: this.sawResultEvent && !this.resultIsError,\n };\n }\n\n // private handlers\n\n private handleAssistantMessage(\n event: Extract<StreamEvent, { type: \"assistant\" }>,\n ): void {\n const turnIndex = this.turns.length;\n const textChunks: string[] = [];\n const toolCallsThisTurn: ToolCall[] = [];\n\n for (const block of event.message.content) {\n if (isTextBlock(block)) {\n textChunks.push(block.text);\n continue;\n }\n if (isToolUseBlock(block)) {\n const call: ToolCall = {\n name: block.name,\n namespace: namespaceOf(block.name),\n callId: block.id,\n args: block.input,\n result: null,\n isError: false,\n turnIndex,\n callIndex: this.allToolCalls.length,\n };\n this.allToolCalls.push(call);\n this.pendingCalls.set(block.id, call);\n toolCallsThisTurn.push(call);\n continue;\n }\n // tool_result blocks don't appear in assistant messages — those arrive\n // via user messages. If one does appear, ignore it; we'd rather drop\n // an unexpected block than crash the eval.\n }\n\n this.turns.push({\n turnIndex,\n text: textChunks.join(\"\").trim(),\n toolCalls: toolCallsThisTurn,\n stopReason: event.message.stop_reason ?? null,\n });\n }\n\n private handleUserMessage(\n event: Extract<StreamEvent, { type: \"user\" }>,\n ): void {\n const content = event.message.content;\n\n // The very first user message carries the prompt as a plain string. We\n // already know the prompt (the caller passed it to the adapter), so we\n // ignore this case — there's nothing assertion-relevant in it.\n if (typeof content === \"string\") return;\n\n for (const block of content) {\n if (!isToolResultBlock(block)) continue;\n\n const call = this.pendingCalls.get(block.tool_use_id);\n if (!call) {\n // Unmatched result: ignore. Can happen if events arrive out of order\n // or the corresponding tool_use was emitted in an earlier run that\n // we're resuming. Either way, dropping is safer than throwing.\n continue;\n }\n\n call.result = block.content;\n call.isError = block.is_error ?? false;\n this.pendingCalls.delete(block.tool_use_id);\n }\n }\n}\n\n/**\n * Convenience: drain an async iterable of events through a fresh builder.\n *\n * Suitable when you have the full event stream and just want the view.\n * For interactive/incremental scenarios (e.g. surfacing partial state in a UI)\n * instantiate {@link TrajectoryBuilder} directly and call `consume()` /\n * `build()` yourself.\n */\nexport async function buildTrajectory(\n events: AsyncIterable<StreamEvent>,\n): Promise<TrajectoryView> {\n const builder = new TrajectoryBuilder();\n for await (const event of events) {\n builder.consume(event);\n }\n return builder.build();\n}\n","/**\n * Line-buffered NDJSON parser for Claude Code's `--output-format stream-json`.\n *\n * Claude Code emits one JSON object per line on stdout. The parser:\n * - buffers across chunk boundaries (a single JSON line may arrive in two reads)\n * - skips empty lines (defensive — shouldn't occur, but harmless if it does)\n * - emits a discriminated `ParseResult` per line so callers can decide whether\n * a malformed line should abort the run or just be logged.\n *\n * Why a generator (and not a Transform stream)?\n * The eval adapter consumes events sequentially and synchronously updates a\n * builder. Async iteration is the simplest interface for that pattern and\n * composes cleanly with `for await` in the adapter. A Transform would force\n * the builder into event-handler style.\n */\n\nimport type { Readable } from \"node:stream\";\nimport type { StreamEvent } from \"../types/stream\";\n\n/**\n * Result of attempting to parse a single line.\n *\n * Successful parses yield `{ ok: true }` with the typed event and the raw line\n * (kept for diagnostics and OTel `events.attributes.raw`). Failed parses yield\n * `{ ok: false }` with the parse error and the raw line — callers can log,\n * skip, or fail the run as they see fit.\n */\nexport type ParseResult =\n | { ok: true; event: StreamEvent; rawLine: string }\n | { ok: false; error: Error; rawLine: string };\n\n/**\n * Parse a readable stream of NDJSON into a sequence of typed stream-json events.\n *\n * @example\n * const child = spawn(\"claude\", [\"-p\", prompt, \"--output-format\", \"stream-json\", \"--verbose\"]);\n * for await (const result of parseStreamJson(child.stdout)) {\n * if (result.ok) builder.consume(result.event);\n * else console.warn(\"malformed stream line:\", result.rawLine, result.error);\n * }\n */\nexport async function* parseStreamJson(\n stream: Readable,\n): AsyncGenerator<ParseResult, void, void> {\n let buffer = \"\";\n // The Node child_process stdout is a binary stream by default. Setting the\n // encoding here means `for await (const chunk of stream)` yields strings.\n stream.setEncoding(\"utf8\");\n\n for await (const chunk of stream) {\n buffer += chunk as string;\n\n // Drain every complete line currently in the buffer before reading more.\n // Multiple JSON objects can arrive in one chunk (e.g. when the harness\n // emits a burst of events at session start).\n let newlineIdx: number;\n while ((newlineIdx = buffer.indexOf(\"\\n\")) !== -1) {\n const line = buffer.slice(0, newlineIdx).trim();\n buffer = buffer.slice(newlineIdx + 1);\n if (line.length === 0) continue;\n yield tryParseLine(line);\n }\n }\n\n // Flush any trailing content that arrived without a final newline. Stream-json\n // typically ends with a newline-terminated `result` event, but a killed\n // process may not flush, so we still try to emit what we have.\n const trailing = buffer.trim();\n if (trailing.length > 0) {\n yield tryParseLine(trailing);\n }\n}\n\n/**\n * Parse a single line. Extracted as a helper so the generator stays readable.\n *\n * Note: we do not validate the event structure beyond `JSON.parse`. Runtime\n * validation (e.g. zod) is overkill here — the schema is stable enough at\n * runtime, and the TrajectoryBuilder is tolerant of missing fields. Adding\n * validation would be premature.\n */\nfunction tryParseLine(line: string): ParseResult {\n try {\n const event = JSON.parse(line) as StreamEvent;\n return { ok: true, event, rawLine: line };\n } catch (err) {\n return {\n ok: false,\n error: err instanceof Error ? err : new Error(String(err)),\n rawLine: line,\n };\n }\n}\n","/**\n * Generic harness adapter contract.\n *\n * Every harness adapter produces a {@link TrajectoryView} plus process\n * diagnostics. The runner and assertion engine depend only on these types —\n * not on any specific harness implementation.\n */\n\nimport type { TrajectoryView } from \"../types/trajectory\";\n\n/** Base config every adapter must accept. */\nexport interface BaseAdapterConfig {\n prompt: string;\n model?: string;\n timeoutMs?: number;\n signal?: AbortSignal;\n env?: Record<string, string>;\n cwd?: string;\n}\n\n/** Suite-level config: generic fields plus adapter-specific nested blocks. */\nexport type SuiteConfig = Partial<BaseAdapterConfig> & {\n /** Claude Code adapter options (when `adapter` is `claude-code`). */\n claudeCode?: Record<string, unknown>;\n};\n\n/** Generic harness adapter interface. */\nexport interface HarnessAdapter<\n TConfig extends BaseAdapterConfig = BaseAdapterConfig,\n> {\n readonly id: string;\n run(config: TConfig): Promise<AdapterResult>;\n}\n\n/** Successful adapter run. */\nexport interface AdapterResult {\n view: TrajectoryView;\n diagnostics: AdapterDiagnostics;\n}\n\n/** Process-level diagnostics from any adapter. */\nexport interface AdapterDiagnostics {\n exitCode: number | null;\n signal: NodeJS.Signals | null;\n stderr: string;\n parseErrors: ParseErrorRecord[];\n timedOut: boolean;\n durationMs: number;\n}\n\nexport interface ParseErrorRecord {\n line: string;\n error: string;\n}\n\n/**\n * Thrown when the harness fails to produce a usable trajectory.\n *\n * Most commonly this means the process failed before emitting a usable\n * session init event. Inspect `diagnostics.stderr` for the cause.\n */\nexport class AdapterError extends Error {\n constructor(\n message: string,\n public readonly diagnostics: Partial<AdapterDiagnostics>,\n ) {\n super(message);\n this.name = \"AdapterError\";\n }\n}\n","/**\n * Build CLI args for Claude Code judge subprocesses (JSON output, not stream-json).\n */\n\nimport type { ClaudeCodeAdapterConfig, ClaudeCodeOptions } from \"./types\";\n\nfunction pushRepeatableFlag(args: string[], flag: string, values?: string[]): void {\n if (!values) return;\n for (const value of values) {\n args.push(flag, value);\n }\n}\n\nfunction pushOptionalFlag(\n args: string[],\n flag: string,\n value: string | number | boolean | undefined,\n): void {\n if (value === undefined) return;\n if (typeof value === \"boolean\") {\n if (value) args.push(flag);\n return;\n }\n args.push(flag, String(value));\n}\n\n/** Append Claude Code CLI flags shared by harness runs and grading judges. */\nexport function appendClaudeCodeFlags(\n args: string[],\n config: ClaudeCodeOptions & { model?: string },\n): void {\n pushRepeatableFlag(args, \"--plugin-dir\", config.pluginDirs);\n pushRepeatableFlag(args, \"--plugin-url\", config.pluginUrls);\n pushRepeatableFlag(args, \"--add-dir\", config.addDirs);\n\n pushOptionalFlag(args, \"--mcp-config\", config.mcpConfig);\n pushOptionalFlag(args, \"--model\", config.model);\n pushOptionalFlag(args, \"--permission-mode\", config.permissionMode);\n pushOptionalFlag(args, \"--effort\", config.effort);\n pushOptionalFlag(args, \"--agent\", config.agent);\n pushOptionalFlag(args, \"--fallback-model\", config.fallbackModel);\n pushOptionalFlag(args, \"--tools\", config.tools);\n pushOptionalFlag(args, \"--settings\", config.settings);\n pushOptionalFlag(args, \"--setting-sources\", config.settingSources);\n pushOptionalFlag(args, \"--max-turns\", config.maxTurns);\n pushOptionalFlag(args, \"--max-budget-usd\", config.maxBudgetUsd);\n pushOptionalFlag(args, \"--system-prompt\", config.systemPrompt);\n pushOptionalFlag(args, \"--system-prompt-file\", config.systemPromptFile);\n pushOptionalFlag(args, \"--append-system-prompt\", config.appendSystemPrompt);\n pushOptionalFlag(\n args,\n \"--append-system-prompt-file\",\n config.appendSystemPromptFile,\n );\n pushOptionalFlag(args, \"--debug\", config.debug);\n pushOptionalFlag(args, \"--debug-file\", config.debugFile);\n\n if (config.allowedTools && config.allowedTools.length > 0) {\n args.push(\"--allowedTools\", config.allowedTools.join(\",\"));\n }\n\n if (config.disallowedTools && config.disallowedTools.length > 0) {\n args.push(\"--disallowedTools\", config.disallowedTools.join(\",\"));\n }\n\n pushOptionalFlag(args, \"--strict-mcp-config\", config.strictMcpConfig);\n pushOptionalFlag(args, \"--include-hook-events\", config.includeHookEvents);\n pushOptionalFlag(args, \"--no-session-persistence\", config.noSessionPersistence);\n pushOptionalFlag(args, \"--disable-slash-commands\", config.disableSlashCommands);\n pushOptionalFlag(args, \"--bare\", config.bare);\n pushOptionalFlag(args, \"--safe-mode\", config.safeMode);\n pushOptionalFlag(\n args,\n \"--allow-dangerously-skip-permissions\",\n config.allowDangerouslySkipPermissions,\n );\n pushOptionalFlag(\n args,\n \"--dangerously-skip-permissions\",\n config.dangerouslySkipPermissions,\n );\n}\n\n/**\n * Build the argument vector for spawning `claude`.\n *\n * Order matters only for flags that take values — value flags must come\n * after their flag name. Everything else is order-independent.\n */\nexport function buildArgs(config: ClaudeCodeAdapterConfig): string[] {\n const args: string[] = [\n \"-p\",\n config.prompt,\n \"--output-format\",\n \"stream-json\",\n \"--verbose\",\n ];\n\n appendClaudeCodeFlags(args, config);\n\n return args;\n}\n\n/** Build args for an LLM judge subprocess (`--output-format json`). */\nexport function buildJudgeArgs(\n prompt: string,\n config: ClaudeCodeOptions & { model?: string } = {},\n): string[] {\n const args: string[] = [\"-p\", prompt, \"--output-format\", \"json\"];\n const permissionMode = config.permissionMode ?? \"bypassPermissions\";\n appendClaudeCodeFlags(args, {\n ...config,\n permissionMode,\n });\n return args;\n}\n","/**\n * Process management for the Claude Code adapter.\n *\n * This module owns spawning, timeout, abort signal handling, and process-tree\n * teardown. The orchestrator (`index.ts`) consumes the returned handle —\n * reading stdout and waiting for completion — but doesn't worry about how\n * the process gets killed or how its config gets isolated.\n *\n * Why a separate module? Process management is the one part of the adapter\n * with real I/O complexity (process groups, signal escalation, temp-dir\n * lifecycle, env merging). Isolating it makes the orchestrator easy to read\n * and lets us swap the spawning logic if we later need to, e.g., wrap claude\n * in a sandbox runner.\n */\n\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { Readable } from \"node:stream\";\n\nimport { buildArgs } from \"./flags\";\nimport type { ClaudeCodeAdapterConfig } from \"./types\";\n\n/** Default hard timeout per run. Tunable via config.timeoutMs. */\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;\n\n/**\n * Grace period between SIGTERM and SIGKILL. Most processes shut down cleanly\n * within a few seconds; this gives them that chance while preventing CI from\n * hanging indefinitely on a stuck child.\n */\nconst KILL_GRACE_MS = 5_000;\n\n/**\n * Handle to a spawned `claude` process. The orchestrator drives it:\n * - Read `stdout` (typically via parseStreamJson).\n * - Await `done` to learn the exit state.\n * - Await `stderrCollected` for diagnostic stderr.\n * - Check `timedOut()` after exit to distinguish kill-by-timeout from\n * normal termination.\n * - Call `cleanup()` after all of the above to remove the temp config dir.\n */\nexport interface SpawnedClaude {\n stdout: Readable;\n done: Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>;\n stderrCollected: Promise<string>;\n timedOut: () => boolean;\n cleanup: () => Promise<void>;\n}\n\n/**\n * Spawn `claude` in headless mode with isolated config and a process-group\n * lifecycle. See {@link SpawnedClaude} for how to consume the result.\n */\nexport async function spawnClaude(\n config: ClaudeCodeAdapterConfig,\n): Promise<SpawnedClaude> {\n const binary = config.binary ?? \"claude\";\n const args = buildArgs(config);\n\n const isolateConfig = config.isolateConfig !== false;\n\n // Isolated runs use a fresh temp dir so plugins/settings don't leak between\n // reps. Non-isolated runs inherit the caller's Claude login and plugins.\n const tempConfigDir = isolateConfig\n ? await mkdtemp(join(tmpdir(), \"harness-eval-\"))\n : null;\n\n const env: Record<string, string | undefined> = {\n ...process.env,\n ...config.env,\n };\n if (tempConfigDir) {\n // Override after ...env so callers can't accidentally un-isolate.\n env.CLAUDE_CONFIG_DIR = tempConfigDir;\n }\n\n const child = spawn(binary, args, {\n cwd: config.cwd ?? process.cwd(),\n env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n // detached: true means the child becomes the leader of its own process\n // group. We exploit this to kill the entire group (including any MCP\n // server subprocesses and tool processes) on timeout/abort.\n detached: true,\n });\n\n\n let timedOut = false;\n let killEscalation: NodeJS.Timeout | null = null;\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n const scheduleKillEscalation = () => {\n if (killEscalation) clearTimeout(killEscalation);\n killEscalation = setTimeout(\n () => killTree(child, \"SIGKILL\"),\n KILL_GRACE_MS,\n );\n };\n\n const timeoutTimer = setTimeout(() => {\n timedOut = true;\n killTree(child, \"SIGTERM\");\n scheduleKillEscalation();\n }, timeoutMs);\n\n // External cancellation uses the same kill path.\n const onAbort = () => {\n killTree(child, \"SIGTERM\");\n scheduleKillEscalation();\n };\n config.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\n // Drain stderr eagerly so the OS-level buffer never fills and stalls the\n // child (Node child processes will block on a full pipe).\n const stderrChunks: string[] = [];\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (chunk: string) => {\n stderrChunks.push(chunk);\n });\n\n const stderrCollected = new Promise<string>((resolve) => {\n const finalize = () => resolve(stderrChunks.join(\"\"));\n child.stderr?.on(\"end\", finalize);\n // Errors during stderr capture shouldn't fail the whole run; we just\n // return what we've buffered so far.\n child.stderr?.on(\"error\", finalize);\n });\n\n\n const done = new Promise<{\n exitCode: number | null;\n signal: NodeJS.Signals | null;\n }>((resolve) => {\n let settled = false;\n const finalize = (\n exitCode: number | null,\n signal: NodeJS.Signals | null,\n ) => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutTimer);\n if (killEscalation) clearTimeout(killEscalation);\n config.signal?.removeEventListener(\"abort\", onAbort);\n resolve({ exitCode, signal });\n };\n\n child.on(\"close\", (code, signal) => finalize(code, signal));\n // ENOENT and other spawn failures emit `error` — `close` may not follow.\n child.on(\"error\", () => finalize(null, null));\n });\n\n\n const cleanup = async () => {\n if (!tempConfigDir) return;\n try {\n await rm(tempConfigDir, { recursive: true, force: true });\n } catch {\n // Best-effort. A leftover temp dir is annoying but not catastrophic;\n // we don't want to fail the run for it.\n }\n };\n\n // stdout is guaranteed non-null because we passed `stdio: [..., \"pipe\", ...]`.\n // The `!` is safe; the alternative would be a redundant runtime check that\n // could never fire.\n return {\n stdout: child.stdout!,\n done,\n stderrCollected,\n timedOut: () => timedOut,\n cleanup,\n };\n}\n\n/**\n * Kill the child's process group, then fall back to the bare PID if the\n * group is already gone. This catches MCP server subprocesses and tool\n * processes spawned by claude.\n *\n * Why both? On some platforms the process group dies before we get here\n * (the child itself already cleaned up), in which case `kill(-pid)` throws\n * ESRCH. The fallback handles that edge case without leaking zombies in\n * the common case.\n */\nfunction killTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (child.pid === undefined) return;\n try {\n // Negative PID = process group. Requires the child was spawned with\n // detached=true (which we do).\n process.kill(-child.pid, signal);\n } catch {\n try {\n child.kill(signal);\n } catch {\n // Nothing left to kill.\n }\n }\n}\n","/**\n * Claude Code adapter — public API.\n */\n\nimport { parseStreamJson } from \"../../parsers/stream-json\";\nimport { TrajectoryBuilder } from \"../../trajectory/builder\";\nimport type { StreamEvent } from \"../../types/stream\";\n\nimport { AdapterError } from \"../types\";\nimport { spawnClaude } from \"./process\";\nimport type {\n AdapterDiagnostics,\n ClaudeCodeAdapterConfig,\n ClaudeCodeAdapterResult,\n ParseErrorRecord,\n} from \"./types\";\nimport type { HarnessAdapter } from \"../types\";\n\nexport { AdapterError } from \"../types\";\nexport type {\n AdapterDiagnostics,\n AdapterResult,\n ClaudeCodeAdapterConfig,\n ClaudeCodeAdapterResult,\n ClaudeCodeOptions,\n ParseErrorRecord,\n PermissionMode,\n} from \"./types\";\n\n/**\n * Run Claude Code in headless mode and return a trajectory.\n */\nexport async function runClaudeCode(\n config: ClaudeCodeAdapterConfig,\n): Promise<ClaudeCodeAdapterResult> {\n const startTs = Date.now();\n const spawned = await spawnClaude(config);\n\n const builder = new TrajectoryBuilder();\n const rawEvents: StreamEvent[] = [];\n const parseErrors: ParseErrorRecord[] = [];\n\n try {\n for await (const result of parseStreamJson(spawned.stdout)) {\n if (result.ok) {\n builder.consume(result.event);\n rawEvents.push(result.event);\n } else {\n parseErrors.push({\n line: result.rawLine,\n error: result.error.message,\n });\n }\n }\n\n const [{ exitCode, signal }, stderr] = await Promise.all([\n spawned.done,\n spawned.stderrCollected,\n ]);\n\n const diagnostics: AdapterDiagnostics = {\n exitCode,\n signal,\n stderr,\n parseErrors,\n timedOut: spawned.timedOut(),\n durationMs: Date.now() - startTs,\n };\n\n let view;\n try {\n view = builder.build();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new AdapterError(\n `harness produced no usable trajectory: ${message}`,\n diagnostics,\n );\n }\n\n return { view, diagnostics, rawEvents };\n } finally {\n await spawned.cleanup();\n }\n}\n\nexport const claudeCodeAdapter: HarnessAdapter<ClaudeCodeAdapterConfig> = {\n id: \"claude-code\",\n run: runClaudeCode,\n};\n"],"mappings":";;;;;;;AAuMA,SAAgB,aAAa,GAAsC;CACjE,OAAO,EAAE,SAAS,YAAa,EAAsB,YAAY;AACnE;AAEA,SAAgB,cAAc,GAAuC;CACnE,OAAO,EAAE,SAAS,YAAa,EAAuB,YAAY;AACpE;AAEA,SAAgB,mBAAmB,GAA4C;CAC7E,OAAO,EAAE,SAAS;AACpB;AAEA,SAAgB,cAAc,GAAuC;CACnE,OAAO,EAAE,SAAS;AACpB;AAEA,SAAgB,SAAS,GAAkC;CACzD,OAAO,EAAE,SAAS;AACpB;AAEA,SAAgB,YAAY,GAAiC;CAC3D,OAAO,EAAE,SAAS;AACpB;AAEA,SAAgB,eAAe,GAAoC;CACjE,OAAO,EAAE,SAAS;AACpB;AAEA,SAAgB,kBAAkB,GAAuC;CACvE,OAAO,EAAE,SAAS;AACpB;;;;;;;;;;;;;;AC9FA,SAAgB,YAAY,UAAiC;CAC3D,IAAI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