neurastream 0.3.26 → 0.3.27

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,545 @@
1
+ // Claude Code (`claude`) harness adapter: subagent launch spec, project JSONL RunSource/TraceSource,
2
+ // sandbox-safe settings.json hook installer (SessionStart + PreToolUse + Stop), and doctor checks.
3
+
4
+ import { basename, join, resolve } from "node:path";
5
+ import type { OwnerTurn, Run, RunSource, TraceEvent, TraceRun, TraceSource, TraceUsage } from "../../core/adapter.ts";
6
+ import type { Config } from "../../core/config.ts";
7
+ import type { SpawnProfile } from "../../core/runner.ts";
8
+ import { LEGACY_PRE_TOOL_CMD, LEGACY_STOP_CMD } from "../hook-bridge.ts";
9
+ import type { HarnessAdapter } from "../index.ts";
10
+ import {
11
+ addUsageTotals,
12
+ asObj,
13
+ buildRunRecord,
14
+ collectOwnerTurns,
15
+ collectTraceRuns,
16
+ createTraceSource,
17
+ createTranscriptRunSource,
18
+ defaultAdapterStubs,
19
+ findFiles,
20
+ handleStandardHook,
21
+ installGroupedHooksJson,
22
+ isInsideWorkRoot,
23
+ num,
24
+ parseIsoSec,
25
+ parseJsonlRecords,
26
+ readJsonConfigObject,
27
+ runAdapterDoctorCli,
28
+ runAdapterInstallCli,
29
+ runHookDoctorChecks,
30
+ skipPermissionsArgs,
31
+ spawnHarnessMain,
32
+ statMtimeSec,
33
+ str,
34
+ subagentLaunchSpecFrom,
35
+ writeJsonConfigObject,
36
+ } from "../shared.ts";
37
+
38
+ /** Hook command wired into Claude Code's SessionStart lifecycle. */
39
+ export const CLAUDE_SESSION_START_CMD = "neurastream adapter hook claude session-start";
40
+
41
+ /** Hook command wired into Claude Code's UserPromptSubmit lifecycle. */
42
+ export const CLAUDE_USER_PROMPT_CMD = "neurastream adapter hook claude user-prompt";
43
+
44
+ /** Hook command wired into Claude Code's PreToolUse lifecycle. */
45
+ export const CLAUDE_PRE_TOOL_CMD = "neurastream adapter hook claude pre-tool";
46
+
47
+ /** Hook command wired into Claude Code's Stop lifecycle. */
48
+ export const CLAUDE_STOP_CMD = "neurastream adapter hook claude stop";
49
+
50
+ const CLAUDE_TOOL_MAP: Record<string, string> = {
51
+ Bash: "bash",
52
+ Write: "write",
53
+ Edit: "edit",
54
+ MultiEdit: "edit",
55
+ Read: "read",
56
+ Grep: "grep",
57
+ Glob: "glob",
58
+ Find: "find",
59
+ Task: "task",
60
+ Agent: "task",
61
+ };
62
+
63
+ /**
64
+ * Returns the path to Claude Code's settings file under `home`.
65
+ *
66
+ * Args:
67
+ * home (string): Sandbox or caller HOME directory
68
+ *
69
+ * Returns:
70
+ * string: Path to `$HOME/.claude/settings.json`
71
+ */
72
+ export function claudeSettingsFile(home: string): string {
73
+ return join(home, ".claude", "settings.json");
74
+ }
75
+
76
+ /**
77
+ * Returns the default Claude Code projects root containing session JSONL files.
78
+ *
79
+ * Args:
80
+ * home (string): Sandbox or caller HOME directory
81
+ *
82
+ * Returns:
83
+ * string: Path to `$HOME/.claude/projects`
84
+ */
85
+ export function claudeProjectsRoot(home: string): string {
86
+ return join(home, ".claude", "projects");
87
+ }
88
+
89
+ function claudeSessionsRoot(cfg: Config): string {
90
+ return cfg.adapter?.name === "claude" && cfg.adapter.sessions ? cfg.adapter.sessions : claudeProjectsRoot(cfg.paths.home);
91
+ }
92
+
93
+ /**
94
+ * Recursively discovers `*.jsonl` session transcripts beneath `root`.
95
+ *
96
+ * Args:
97
+ * root (string): Root directory to search
98
+ * maxDepth (number): Maximum recursion depth
99
+ *
100
+ * Returns:
101
+ * string[]: Sorted list of discovered JSONL transcript file paths
102
+ */
103
+ export function findClaudeTranscripts(root: string, maxDepth = 5): string[] {
104
+ return findFiles(root, (name) => name.endsWith(".jsonl"), maxDepth);
105
+ }
106
+
107
+ /**
108
+ * Derives a stable run id from a Claude Code JSONL file path (falling back to the file stem).
109
+ *
110
+ * Args:
111
+ * file (string): Full path to a `.jsonl` session file
112
+ * _root (string): Projects root directory
113
+ *
114
+ * Returns:
115
+ * string: Session/run identifier
116
+ */
117
+ export function claudeRunIdFromPath(file: string, _root?: string): string {
118
+ const stem = basename(file, ".jsonl");
119
+ return stem && stem !== "." ? stem : "claude";
120
+ }
121
+
122
+ function claudeRunId(records: Record<string, unknown>[], file: string): string {
123
+ for (const rec of records) {
124
+ const sid = str(rec.sessionId);
125
+ if (sid) return sid;
126
+ }
127
+ return claudeRunIdFromPath(file);
128
+ }
129
+
130
+ function usageFromClaudeRecord(rec: Record<string, unknown>, msg: Record<string, unknown>): TraceUsage | undefined {
131
+ const u = asObj(msg.usage);
132
+ if (!u) return undefined;
133
+ const input = num(u.input_tokens);
134
+ const output = num(u.output_tokens);
135
+ const cacheRead = num(u.cache_read_input_tokens);
136
+ const cacheWrite = num(u.cache_creation_input_tokens);
137
+ const totalTokens = num(u.total_tokens) || input + output + cacheRead + cacheWrite;
138
+ const cost = num(u.cost ?? rec.costUSD ?? rec.cost);
139
+ return { input, output, cacheRead, cacheWrite, totalTokens, cost };
140
+ }
141
+
142
+ function textFromToolResultContent(content: unknown): string {
143
+ if (typeof content === "string") return content;
144
+ if (!Array.isArray(content)) return "";
145
+ const parts: string[] = [];
146
+ for (const item of content) {
147
+ const obj = asObj(item);
148
+ if (!obj) continue;
149
+ if (obj.type === "text" && typeof obj.text === "string") parts.push(obj.text);
150
+ else if (typeof obj.content === "string") parts.push(obj.content);
151
+ }
152
+ return parts.join("\n");
153
+ }
154
+
155
+ function statusFromClaudeRecords(records: Record<string, unknown>[]): { status: Run["status"]; detail: string } {
156
+ const last = records.at(-1);
157
+ if (!last) return { status: "done", detail: "done" };
158
+ const rawStatus = typeof last.status === "string" ? last.status.toUpperCase() : "";
159
+ const subtype = typeof last.subtype === "string" ? last.subtype : "";
160
+ if (
161
+ last.isApiErrorMessage === true ||
162
+ last.type === "error" ||
163
+ subtype === "error_during_execution" ||
164
+ rawStatus === "ERROR" ||
165
+ rawStatus === "FAILED"
166
+ ) {
167
+ return { status: "died", detail: "DIED: error" };
168
+ }
169
+ if (rawStatus === "WAITING") return { status: "waiting", detail: "WAITING: input" };
170
+ const msg = asObj(last.message);
171
+ if (rawStatus === "RUNNING" || rawStatus === "IN_PROGRESS" || (last.type === "assistant" && msg?.stop_reason === "tool_use")) {
172
+ return { status: "running", detail: "RUNNING" };
173
+ }
174
+ return { status: "done", detail: "done" };
175
+ }
176
+
177
+ function buildRunFromClaudeFile(file: string, since: number): Run | null {
178
+ const mtimeSec = statMtimeSec(file);
179
+ if (mtimeSec === null) return null;
180
+ const records = parseJsonlRecords(file);
181
+ let startedAt: number | null = null;
182
+ let lastTs: number | null = null;
183
+ let model = "?";
184
+ let calls = 0;
185
+ const totals = { tokens: 0, cacheRead: 0, cost: 0, inputTokens: 0, prefillTokens: 0 };
186
+
187
+ for (const rec of records) {
188
+ const ts = parseIsoSec(rec.timestamp);
189
+ if (ts !== null) {
190
+ if (startedAt === null) startedAt = ts;
191
+ lastTs = ts;
192
+ }
193
+ if (rec.type === "assistant") {
194
+ const msg = asObj(rec.message) ?? rec;
195
+ const recModel = str(msg.model) ?? str(rec.model);
196
+ if (recModel) model = recModel;
197
+ const usage = usageFromClaudeRecord(rec, msg);
198
+ calls++;
199
+ if (usage) addUsageTotals(totals, usage);
200
+ }
201
+ }
202
+
203
+ const lastWriteAt = lastTs ?? mtimeSec;
204
+ if (lastWriteAt < since) return null;
205
+ const { status, detail } = statusFromClaudeRecords(records);
206
+ return buildRunRecord({
207
+ id: claudeRunId(records, file),
208
+ model,
209
+ calls,
210
+ ...totals,
211
+ status,
212
+ detail,
213
+ startedAt,
214
+ lastWriteAt,
215
+ });
216
+ }
217
+
218
+ /**
219
+ * Parses a Claude Code session JSONL file into core `TraceEvent` items.
220
+ *
221
+ * Args:
222
+ * file (string): Path to the `.jsonl` session file
223
+ * runId (string): Run identifier assigned to emitted events
224
+ *
225
+ * Returns:
226
+ * TraceEvent[]: Normalized trace events in file order
227
+ */
228
+ export function parseClaudeTraceFile(file: string, runId: string): TraceEvent[] {
229
+ const records = parseJsonlRecords(file);
230
+ const events: TraceEvent[] = [];
231
+ const toolByCallId = new Map<string, string>();
232
+
233
+ for (const rec of records) {
234
+ const ts = parseIsoSec(rec.timestamp);
235
+ const type = typeof rec.type === "string" ? rec.type : "";
236
+ const msg = asObj(rec.message) ?? rec;
237
+
238
+ if (type === "assistant") {
239
+ const model = str(msg.model) ?? str(rec.model);
240
+ const usage = usageFromClaudeRecord(rec, msg);
241
+ const content = msg.content;
242
+ let emitted = false;
243
+
244
+ if (typeof content === "string") {
245
+ if (content.trim()) {
246
+ events.push({ kind: "assistantText", ts, runId, text: content, model, usage });
247
+ emitted = true;
248
+ }
249
+ } else if (Array.isArray(content)) {
250
+ for (const rawBlock of content) {
251
+ const block = asObj(rawBlock);
252
+ if (!block) continue;
253
+ if (block.type === "text" && typeof block.text === "string" && block.text.trim()) {
254
+ events.push({ kind: "assistantText", ts, runId, text: block.text, model, usage });
255
+ emitted = true;
256
+ } else if (block.type === "tool_use") {
257
+ const tool = str(block.name) ?? "?";
258
+ const callId = str(block.id);
259
+ if (callId) toolByCallId.set(callId, tool);
260
+ const args = asObj(block.input) ?? {};
261
+ events.push({ kind: "toolCall", ts, runId, tool, args, callId, model, usage });
262
+ emitted = true;
263
+ }
264
+ }
265
+ }
266
+
267
+ if (!emitted && usage) events.push({ kind: "usage", ts, runId, model, usage });
268
+ continue;
269
+ }
270
+
271
+ if (type === "user") {
272
+ const content = msg.content;
273
+ if (!Array.isArray(content)) continue;
274
+ for (const rawBlock of content) {
275
+ const block = asObj(rawBlock);
276
+ if (!block || block.type !== "tool_result") continue;
277
+ const callId = str(block.tool_use_id) ?? str(block.call_id);
278
+ const tool = str(block.name) ?? str(block.tool_name) ?? (callId ? toolByCallId.get(callId) : undefined);
279
+ const isError = block.is_error === true;
280
+ const text = textFromToolResultContent(block.content);
281
+ events.push({ kind: "toolResult", ts, runId, tool, callId, isError, text });
282
+ }
283
+ }
284
+ }
285
+ return events;
286
+ }
287
+
288
+ /**
289
+ * Creates a `RunSource` backed by Claude Code project JSONL files under `cfg`.
290
+ *
291
+ * Args:
292
+ * cfg (Config): Loaded neurastream configuration
293
+ *
294
+ * Returns:
295
+ * RunSource: RunSource reading Claude Code project sessions
296
+ */
297
+ export function claudeRunSource(cfg: Config): RunSource {
298
+ const root = claudeSessionsRoot(cfg);
299
+ return createTranscriptRunSource(() => findClaudeTranscripts(root), buildRunFromClaudeFile);
300
+ }
301
+
302
+ /**
303
+ * Lists Claude Code trace runs discovered under `root`.
304
+ *
305
+ * Args:
306
+ * root (string): Claude projects root directory
307
+ *
308
+ * Returns:
309
+ * TraceRun[]: Discovered trace runs sorted by run id
310
+ */
311
+ export function claudeTraceRuns(root: string): TraceRun[] {
312
+ return collectTraceRuns(findClaudeTranscripts(root), (file) => claudeRunId(parseJsonlRecords(file), file));
313
+ }
314
+
315
+ /**
316
+ * Creates a `TraceSource` over Claude Code project JSONL files under `root`.
317
+ *
318
+ * Args:
319
+ * root (string): Claude projects root directory
320
+ *
321
+ * Returns:
322
+ * TraceSource: TraceSource returning events for a requested run id
323
+ */
324
+ export function claudeTraceSource(root: string): TraceSource {
325
+ return createTraceSource(root, claudeTraceRuns, parseClaudeTraceFile);
326
+ }
327
+
328
+ function claudeMessageText(content: unknown, allowRawStrings: boolean): string {
329
+ if (typeof content === "string") return content.trim();
330
+ if (!Array.isArray(content)) return "";
331
+ const parts: string[] = [];
332
+ for (const item of content) {
333
+ if (allowRawStrings && typeof item === "string") {
334
+ if (item.trim()) parts.push(item);
335
+ continue;
336
+ }
337
+ const block = asObj(item);
338
+ if (!block || block.type === "tool_result") continue;
339
+ if (block.type === "text" && typeof block.text === "string" && block.text.trim()) {
340
+ parts.push(block.text);
341
+ }
342
+ }
343
+ return parts.join("\n").trim();
344
+ }
345
+
346
+ /**
347
+ * Extracts owner prompts (`type === "user"`, excluding `tool_result` blocks) and Main replies
348
+ * (`type === "assistant"` text) from Claude Code project JSONL files at or after `since`.
349
+ *
350
+ * Args:
351
+ * cfg (Config): Loaded neurastream configuration
352
+ * since (number): Minimum Unix timestamp in seconds
353
+ *
354
+ * Returns:
355
+ * OwnerTurn[]: Extracted turns sorted ascending by timestamp
356
+ */
357
+ export function claudeOwnerTurns(cfg: Config, since: number): OwnerTurn[] {
358
+ return collectOwnerTurns(findClaudeTranscripts(claudeSessionsRoot(cfg)), since, (rec, cutoff): OwnerTurn | null => {
359
+ const at = parseIsoSec(rec.timestamp);
360
+ if (at === null || at < cutoff) return null;
361
+ const type = typeof rec.type === "string" ? rec.type : "";
362
+ if (type !== "user" && type !== "assistant") return null;
363
+ const msg = asObj(rec.message) ?? rec;
364
+ const text = claudeMessageText(msg.content, type === "user");
365
+ if (!text) return null;
366
+ return { at, role: type === "user" ? "owner" : "main", text };
367
+ });
368
+ }
369
+
370
+ /**
371
+ * Translates Claude Code `SessionStart`, `UserPromptSubmit`, `PreToolUse`, and `Stop` hook payloads
372
+ * into core guard calls and Claude hook JSON.
373
+ *
374
+ * Args:
375
+ * event (string): Hook lifecycle event (`"session-start"`, `"user-prompt"`, `"pre-tool"`, or `"stop"`)
376
+ * stdinText (string): Raw JSON payload from Claude Code
377
+ * cfg (Config | undefined): Loaded config when active; undefined on inactive fast-path
378
+ * env (NodeJS.ProcessEnv): Process environment variables
379
+ *
380
+ * Returns:
381
+ * { code: number; stdout: string }: Exit code and Claude Code hook JSON (empty on allow/inactive)
382
+ */
383
+ export function handleClaudeHook(
384
+ event: string,
385
+ stdinText: string,
386
+ cfg: Config | undefined,
387
+ env: NodeJS.ProcessEnv = process.env,
388
+ ): { code: number; stdout: string } {
389
+ return handleStandardHook({
390
+ event,
391
+ stdinText,
392
+ cfg,
393
+ env,
394
+ defaultId: "claude",
395
+ toolMap: CLAUDE_TOOL_MAP,
396
+ nativeSpawnTools: ["Agent", "Task"],
397
+ formatPreToolDeny: (reason) =>
398
+ JSON.stringify({
399
+ hookSpecificOutput: {
400
+ hookEventName: "PreToolUse",
401
+ permissionDecision: "deny",
402
+ permissionDecisionReason: reason,
403
+ },
404
+ }),
405
+ });
406
+ }
407
+
408
+ /**
409
+ * Idempotently merges `SessionStart`, `UserPromptSubmit`, `PreToolUse`, and `Stop` hooks into
410
+ * `$HOME/.claude/settings.json`, upgrading legacy `neurastream guard ...` entries while preserving
411
+ * all existing keys and hooks.
412
+ *
413
+ * Args:
414
+ * home (string): Sandbox or caller HOME directory
415
+ *
416
+ * Returns:
417
+ * { hooksFile: string; changed: boolean }: Settings path and whether the file changed
418
+ */
419
+ export function installClaude(home: string): { hooksFile: string; changed: boolean } {
420
+ return installGroupedHooksJson({
421
+ file: claudeSettingsFile(home),
422
+ label: "claude install",
423
+ legacyPreToolCmd: LEGACY_PRE_TOOL_CMD,
424
+ legacyStopCmd: LEGACY_STOP_CMD,
425
+ cmds: {
426
+ sessionStart: CLAUDE_SESSION_START_CMD,
427
+ userPrompt: CLAUDE_USER_PROMPT_CMD,
428
+ preTool: CLAUDE_PRE_TOOL_CMD,
429
+ stop: CLAUDE_STOP_CMD,
430
+ },
431
+ });
432
+ }
433
+
434
+ /**
435
+ * Checks Claude Code (`claude`) binary availability on `PATH` and hook wiring under `home`.
436
+ *
437
+ * Args:
438
+ * home (string): Sandbox or caller HOME directory
439
+ * env (NodeJS.ProcessEnv): Environment whose `PATH` is inspected
440
+ *
441
+ * Returns:
442
+ * { ok: string[]; problems: string[] }: Diagnostic status lines
443
+ */
444
+ export function doctorClaude(home: string, env: NodeJS.ProcessEnv = process.env): { ok: string[]; problems: string[] } {
445
+ return runHookDoctorChecks({
446
+ name: "claude",
447
+ bin: "claude",
448
+ hooksFile: claudeSettingsFile(home),
449
+ env,
450
+ cmds: {
451
+ sessionStart: CLAUDE_SESSION_START_CMD,
452
+ userPrompt: CLAUDE_USER_PROMPT_CMD,
453
+ preTool: CLAUDE_PRE_TOOL_CMD,
454
+ stop: CLAUDE_STOP_CMD,
455
+ },
456
+ });
457
+ }
458
+
459
+ /**
460
+ * CLI handler for `neurastream adapter install claude`.
461
+ *
462
+ * Args:
463
+ * args (string[]): Arguments passed to `neurastream adapter`
464
+ *
465
+ * Returns:
466
+ * number: Process exit code
467
+ */
468
+ export function runClaudeInstall(args: string[]): number {
469
+ return runAdapterInstallCli(args, "claude", installClaude);
470
+ }
471
+
472
+ /**
473
+ * CLI handler for `neurastream doctor` when `harness: claude`.
474
+ *
475
+ * Returns:
476
+ * number: 0 if healthy, 1 if problems were found
477
+ */
478
+ export function runClaudeDoctor(): number {
479
+ return runAdapterDoctorCli("claude", doctorClaude);
480
+ }
481
+
482
+ /**
483
+ * Ensures `cwd` is marked trusted in `$HOME/.claude.json` (`projects[resolvedCwd].hasTrustDialogAccepted = true`)
484
+ * when `cwd` sits inside `cfg.paths.work_roots`, preserving all existing keys and avoiding writes when unchanged.
485
+ *
486
+ * Args:
487
+ * cwd (string): Working directory where a `claude` subagent will be started
488
+ * cfg (Config): Loaded neurastream configuration providing `paths.home` and `paths.work_roots`
489
+ *
490
+ * Returns:
491
+ * void
492
+ */
493
+ export function ensureClaudeTrustedDir(cwd: string, cfg: Config): void {
494
+ const resolvedCwd = resolve(cwd);
495
+ if (!cfg.paths.work_roots.some((root) => isInsideWorkRoot(resolvedCwd, root))) return;
496
+
497
+ const file = join(cfg.paths.home, ".claude.json");
498
+ const doc = readJsonConfigObject(file, "claude prepareSubagentCwd");
499
+ const projects = doc.projects === undefined ? {} : asObj(doc.projects);
500
+ if (!projects) {
501
+ throw new Error(`claude prepareSubagentCwd: ${file} "projects" field must be an object`);
502
+ }
503
+ const entry = projects[resolvedCwd] === undefined ? {} : asObj(projects[resolvedCwd]);
504
+ if (!entry) {
505
+ throw new Error(`claude prepareSubagentCwd: ${file} "projects[${resolvedCwd}]" must be an object`);
506
+ }
507
+ if (entry.hasTrustDialogAccepted === true) return;
508
+
509
+ writeJsonConfigObject(file, {
510
+ ...doc,
511
+ projects: {
512
+ ...projects,
513
+ [resolvedCwd]: {
514
+ ...entry,
515
+ hasTrustDialogAccepted: true,
516
+ },
517
+ },
518
+ });
519
+ }
520
+
521
+ /** Registered Claude Code (`claude`) HarnessAdapter. */
522
+ export const claudeAdapter: HarnessAdapter = {
523
+ ...defaultAdapterStubs("claude"),
524
+ name: "claude",
525
+ bin: "claude",
526
+ runSource: claudeRunSource,
527
+ ownerTurns: claudeOwnerTurns,
528
+ scoreTraces: (cfg) => claudeTraceSource(claudeSessionsRoot(cfg)),
529
+ traceRuns: claudeTraceRuns,
530
+ traceSource: claudeTraceSource,
531
+ traceStart(file: string): number | null {
532
+ for (const rec of parseJsonlRecords(file)) {
533
+ const sec = parseIsoSec(rec.timestamp);
534
+ if (sec !== null) return Math.round(sec * 1000);
535
+ }
536
+ return null;
537
+ },
538
+ launchMain: (args, cfg) => spawnHarnessMain("claude", args, cfg),
539
+ install: runClaudeInstall,
540
+ doctor: runClaudeDoctor,
541
+ subagentLaunchSpec: (profile: SpawnProfile) =>
542
+ subagentLaunchSpecFrom("claude", profile, true, skipPermissionsArgs(profile.args)),
543
+ prepareSubagentCwd: ensureClaudeTrustedDir,
544
+ handleHook: handleClaudeHook,
545
+ };