neurastream 0.3.25 → 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,1039 @@
1
+ // Shared utilities, JSONL/file discovery, run builders, hook CLI wrappers, and default
2
+ // HarnessAdapter stubs reused across native harness adapters (`agy`, `claude`, `codex`).
3
+
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
+ import type { OwnerTurn, Run, RunSource, TraceRun, TraceSource, TraceUsage } from "../core/adapter.ts";
9
+ import { currentTier } from "../core/autonomy.ts";
10
+ import type { Config } from "../core/config.ts";
11
+ import {
12
+ checkInject,
13
+ checkStop,
14
+ checkTool,
15
+ mainCallsCapOn,
16
+ readStaffing,
17
+ mainEditLimit,
18
+ nextLimitResetMs,
19
+ openQueue,
20
+ readWindow,
21
+ } from "../core/guards.ts";
22
+ import type { SpawnProfile } from "../core/runner.ts";
23
+ import {
24
+ buildSessionStartContext,
25
+ canonicalHookTool,
26
+ hasHookCommand,
27
+ hookAgent,
28
+ hookAgentId,
29
+ isHookActive,
30
+ parseHookPayload,
31
+ resolveHookPaths,
32
+ upgradeHookEntries,
33
+ } from "./hook-bridge.ts";
34
+ import type { HarnessAdapter } from "./index.ts";
35
+
36
+ /**
37
+ * Narrows an unknown value to a plain string-keyed object, excluding null and arrays.
38
+ *
39
+ * Args:
40
+ * v (unknown): Candidate value
41
+ *
42
+ * Returns:
43
+ * Record<string, unknown> | null: Plain object record or null
44
+ */
45
+ export function asObj(v: unknown): Record<string, unknown> | null {
46
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
47
+ }
48
+
49
+ /**
50
+ * Returns `v` when it is a non-empty trimmed string, otherwise `undefined`.
51
+ *
52
+ * Args:
53
+ * v (unknown): Candidate string value
54
+ *
55
+ * Returns:
56
+ * string | undefined: Non-empty string or undefined
57
+ */
58
+ export function str(v: unknown): string | undefined {
59
+ return typeof v === "string" && v.trim() !== "" ? v : undefined;
60
+ }
61
+
62
+ /**
63
+ * Type guard verifying `v` is a finite number.
64
+ *
65
+ * Args:
66
+ * v (unknown): Candidate numeric value
67
+ *
68
+ * Returns:
69
+ * boolean: True when `v` is a finite number
70
+ */
71
+ export function isNum(v: unknown): v is number {
72
+ return typeof v === "number" && Number.isFinite(v);
73
+ }
74
+
75
+ /**
76
+ * Converts a finite number to itself or defaults non-numeric values to `0`.
77
+ *
78
+ * Args:
79
+ * v (unknown): Candidate numeric value
80
+ *
81
+ * Returns:
82
+ * number: Finite number or `0`
83
+ */
84
+ export function num(v: unknown): number {
85
+ return isNum(v) ? v : 0;
86
+ }
87
+
88
+ /**
89
+ * Parses an ISO-8601 timestamp string into Unix epoch seconds, or `null` when invalid.
90
+ *
91
+ * Args:
92
+ * raw (unknown): Raw timestamp value
93
+ *
94
+ * Returns:
95
+ * number | null: Unix timestamp in seconds, or null
96
+ */
97
+ export function parseIsoSec(raw: unknown): number | null {
98
+ if (typeof raw !== "string" || !raw.trim()) return null;
99
+ const ms = Date.parse(raw);
100
+ return Number.isFinite(ms) ? ms / 1000 : null;
101
+ }
102
+
103
+ /**
104
+ * Resolves the active home directory, preferring `process.env.HOME` over `os.homedir()`.
105
+ *
106
+ * Returns:
107
+ * string: Home directory path
108
+ */
109
+ export function currentHome(): string {
110
+ return process.env.HOME && process.env.HOME.trim() !== "" ? process.env.HOME : homedir();
111
+ }
112
+
113
+ /**
114
+ * Checks whether an executable file named `bin` exists in any directory on `env.PATH`.
115
+ *
116
+ * Args:
117
+ * bin (string): Executable name to locate
118
+ * env (NodeJS.ProcessEnv): Environment providing `PATH`
119
+ *
120
+ * Returns:
121
+ * boolean: True if `bin` exists on `PATH`
122
+ */
123
+ export function binOnPath(bin: string, env: NodeJS.ProcessEnv): boolean {
124
+ for (const dir of (env.PATH ?? "").split(":")) {
125
+ if (!dir) continue;
126
+ try {
127
+ if (statSync(join(dir, bin)).isFile()) return true;
128
+ } catch {}
129
+ }
130
+ return false;
131
+ }
132
+
133
+ /**
134
+ * Recursively discovers files beneath `root` whose filename satisfies `predicate`, skipping
135
+ * `.git` and `node_modules` up to `maxDepth`.
136
+ *
137
+ * Args:
138
+ * root (string): Root directory to walk
139
+ * predicate ((name: string) => boolean): Filename matcher
140
+ * maxDepth (number): Maximum recursion depth
141
+ *
142
+ * Returns:
143
+ * string[]: Sorted list of matching file paths
144
+ */
145
+ export function findFiles(root: string, predicate: (name: string) => boolean, maxDepth = 5): string[] {
146
+ if (!existsSync(root)) return [];
147
+ const out: string[] = [];
148
+ const walk = (dir: string, depth: number): void => {
149
+ if (depth > maxDepth) return;
150
+ let entries;
151
+ try {
152
+ entries = readdirSync(dir, { withFileTypes: true });
153
+ } catch {
154
+ return;
155
+ }
156
+ for (const entry of entries) {
157
+ if (entry.name === ".git" || entry.name === "node_modules") continue;
158
+ const full = join(dir, entry.name);
159
+ if (entry.isDirectory()) walk(full, depth + 1);
160
+ else if (entry.isFile() && predicate(entry.name)) out.push(full);
161
+ }
162
+ };
163
+ walk(root, 0);
164
+ return out.sort();
165
+ }
166
+
167
+ /**
168
+ * Reads a JSONL file into parsed object records, silently skipping missing files and malformed lines.
169
+ *
170
+ * Args:
171
+ * file (string): Path to the `.jsonl` file
172
+ *
173
+ * Returns:
174
+ * Record<string, unknown>[]: Parsed JSON object lines in file order
175
+ */
176
+ export function parseJsonlRecords(file: string): Record<string, unknown>[] {
177
+ let text: string;
178
+ try {
179
+ text = readFileSync(file, "utf8");
180
+ } catch {
181
+ return [];
182
+ }
183
+ const records: Record<string, unknown>[] = [];
184
+ for (const line of text.split("\n")) {
185
+ if (!line.trim()) continue;
186
+ try {
187
+ const obj = asObj(JSON.parse(line));
188
+ if (obj) records.push(obj);
189
+ } catch {
190
+ // skip malformed jsonl lines gracefully
191
+ }
192
+ }
193
+ return records;
194
+ }
195
+
196
+ /**
197
+ * Reads a file's modification time in Unix seconds, returning `null` if the file cannot be stat'd.
198
+ *
199
+ * Args:
200
+ * file (string): File path to stat
201
+ *
202
+ * Returns:
203
+ * number | null: Modification time in seconds, or null
204
+ */
205
+ export function statMtimeSec(file: string): number | null {
206
+ try {
207
+ return statSync(file).mtimeMs / 1000;
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Aggregates accumulated token, cost, timing, and status metrics into a core `Run` record.
215
+ *
216
+ * Args:
217
+ * params (object): Aggregated run metrics and status fields
218
+ *
219
+ * Returns:
220
+ * Run: Normalized core `Run` object
221
+ */
222
+ export function buildRunRecord(params: {
223
+ id: string;
224
+ model: string;
225
+ calls: number;
226
+ tokens: number;
227
+ cacheRead: number;
228
+ cost: number;
229
+ inputTokens: number;
230
+ prefillTokens: number;
231
+ status: Run["status"];
232
+ detail: string;
233
+ startedAt: number | null;
234
+ lastWriteAt: number;
235
+ }): Run {
236
+ const ended = params.status === "done" || params.status === "died";
237
+ const durationHours =
238
+ params.startedAt !== null && params.lastWriteAt >= params.startedAt ? (params.lastWriteAt - params.startedAt) / 3600 : 0;
239
+ return {
240
+ id: params.id,
241
+ kind: "sub",
242
+ model: params.model,
243
+ calls: params.calls,
244
+ tokens: params.tokens,
245
+ cacheRead: params.cacheRead,
246
+ cost: params.cost,
247
+ inputTokens: params.inputTokens,
248
+ prefillTokens: params.prefillTokens,
249
+ status: params.status,
250
+ statusDetail: params.detail,
251
+ startedAt: params.startedAt,
252
+ lastWriteAt: params.lastWriteAt,
253
+ endedAt: ended ? params.lastWriteAt : null,
254
+ messages: [],
255
+ scoreModel: params.model,
256
+ scoreCost: params.cost,
257
+ scoreHours: durationHours,
258
+ scoreRunning: params.status === "running" || params.status === "waiting",
259
+ scoreSurvived: params.status !== "died",
260
+ scoreEnd: params.detail,
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Accumulates token and cost totals from a single `TraceUsage` entry into mutable run counters.
266
+ *
267
+ * Args:
268
+ * totals (object): Mutable run token and cost totals
269
+ * usage (TraceUsage): Usage record from one model call
270
+ */
271
+ export function addUsageTotals(
272
+ totals: { tokens: number; cacheRead: number; cost: number; inputTokens: number; prefillTokens: number },
273
+ usage: TraceUsage,
274
+ ): void {
275
+ totals.tokens += usage.totalTokens;
276
+ totals.cacheRead += usage.cacheRead;
277
+ totals.cost += usage.cost;
278
+ const prefill = usage.input + usage.cacheRead + usage.cacheWrite;
279
+ totals.inputTokens = prefill;
280
+ totals.prefillTokens += prefill;
281
+ }
282
+
283
+ /**
284
+ * Deduplicates candidate trace files by `runId` (keeping the newest mtime) and sorts by `runId`.
285
+ *
286
+ * Args:
287
+ * files (string[]): Discovered transcript file paths
288
+ * idForFile ((file: string) => string): Function resolving the run id for a file
289
+ *
290
+ * Returns:
291
+ * TraceRun[]: Deduplicated trace runs sorted ascending by `runId`
292
+ */
293
+ export function collectTraceRuns(files: string[], idForFile: (file: string) => string): TraceRun[] {
294
+ const byId = new Map<string, TraceRun>();
295
+ for (const file of files) {
296
+ const mtimeSec = statMtimeSec(file);
297
+ if (mtimeSec === null) continue;
298
+ const runId = idForFile(file);
299
+ const prev = byId.get(runId);
300
+ if (!prev || mtimeSec > prev.mtimeSec) {
301
+ byId.set(runId, { runId, file, mtimeSec });
302
+ }
303
+ }
304
+ return [...byId.values()].sort((a, b) => (a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : 0));
305
+ }
306
+
307
+ /**
308
+ * Creates a `TraceSource` backed by `traceRuns(root)` and a per-file trace parser.
309
+ *
310
+ * Args:
311
+ * root (string): Sessions root directory
312
+ * traceRunsFn ((root: string) => TraceRun[]): Function listing trace runs under `root`
313
+ * parseFileFn ((file: string, runId: string) => ReturnType<TraceSource["events"]>): Trace parser
314
+ *
315
+ * Returns:
316
+ * TraceSource: TraceSource returning parsed events for a requested run id
317
+ */
318
+ export function createTraceSource(
319
+ root: string,
320
+ traceRunsFn: (root: string) => TraceRun[],
321
+ parseFileFn: (file: string, runId: string) => ReturnType<TraceSource["events"]>,
322
+ ): TraceSource {
323
+ return {
324
+ events(runId: string) {
325
+ const match = traceRunsFn(root).find((r) => r.runId === runId);
326
+ return match ? parseFileFn(match.file, runId) : [];
327
+ },
328
+ };
329
+ }
330
+
331
+ /**
332
+ * Returns true if `tool` is treated as a write/mutation tool for guard checks.
333
+ *
334
+ * Args:
335
+ * tool (string): Canonical tool name
336
+ * cfg (Config): Loaded neurastream configuration
337
+ *
338
+ * Returns:
339
+ * boolean: Whether `tool` performs file writes
340
+ */
341
+ export function isWriteHookTool(tool: string, cfg: Config): boolean {
342
+ return cfg.guards.write_tools.includes(tool) || tool === "write" || tool === "edit" || tool === "ast_edit";
343
+ }
344
+
345
+ /**
346
+ * Reads an existing JSON config file into a plain object, returning `{}` when missing.
347
+ *
348
+ * Args:
349
+ * file (string): Path to the JSON file
350
+ * label (string): Prefix used in descriptive validation errors
351
+ *
352
+ * Returns:
353
+ * Record<string, unknown>: Parsed root JSON object
354
+ */
355
+ export function readJsonConfigObject(file: string, label: string): Record<string, unknown> {
356
+ if (!existsSync(file)) return {};
357
+ let parsed: unknown;
358
+ try {
359
+ parsed = JSON.parse(readFileSync(file, "utf8"));
360
+ } catch (err) {
361
+ throw new Error(`${label}: invalid JSON in ${file}: ${err instanceof Error ? err.message : String(err)}`, {
362
+ cause: err,
363
+ });
364
+ }
365
+ const obj = asObj(parsed);
366
+ if (!obj) throw new Error(`${label}: ${file} must contain a JSON object`);
367
+ return { ...obj };
368
+ }
369
+
370
+ /**
371
+ * Returns true when `target` is equal to or nested inside `root`.
372
+ *
373
+ * Args:
374
+ * target (string): Resolved target directory path
375
+ * root (string): Configured work root directory path
376
+ *
377
+ * Returns:
378
+ * boolean: True when `target` is inside `root`
379
+ */
380
+ export function isInsideWorkRoot(target: string, root: string): boolean {
381
+ if (!root.trim()) return false;
382
+ const rel = relative(resolve(root), target);
383
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
384
+ }
385
+
386
+ /**
387
+ * Writes a JSON document with 2-space indentation and trailing newline, creating parent directories.
388
+ *
389
+ * Args:
390
+ * file (string): Target JSON file path
391
+ * doc (Record<string, unknown>): JSON-serializable root object
392
+ */
393
+ export function writeJsonConfigObject(file: string, doc: Record<string, unknown>): void {
394
+ mkdirSync(dirname(file), { recursive: true });
395
+ writeFileSync(file, `${JSON.stringify(doc, null, 2)}\n`);
396
+ }
397
+
398
+ /**
399
+ * Idempotently merges grouped `SessionStart`, `UserPromptSubmit`, `PreToolUse`, and `Stop` hooks
400
+ * under `rootDoc.hooks` while upgrading legacy `neurastream guard ...` entries and preserving
401
+ * unrelated keys/hooks.
402
+ *
403
+ * Args:
404
+ * opts (object): Target file path, error label, legacy command strings, and new command strings
405
+ *
406
+ * Returns:
407
+ * { hooksFile: string; changed: boolean }: Target path and whether the file changed
408
+ */
409
+ export function installGroupedHooksJson(opts: {
410
+ file: string;
411
+ label: string;
412
+ legacyPreToolCmd: string;
413
+ legacyStopCmd: string;
414
+ cmds: { sessionStart: string; userPrompt: string; preTool: string; stop: string };
415
+ }): { hooksFile: string; changed: boolean } {
416
+ const rootDoc = readJsonConfigObject(opts.file, opts.label);
417
+ const hooksObj = rootDoc.hooks === undefined ? {} : asObj(rootDoc.hooks);
418
+ if (!hooksObj) throw new Error(`${opts.label}: ${opts.file} "hooks" field must be an object`);
419
+
420
+ const sessionStartArr = hooksObj.SessionStart === undefined ? [] : hooksObj.SessionStart;
421
+ if (!Array.isArray(sessionStartArr)) throw new Error(`${opts.label}: ${opts.file} "hooks.SessionStart" must be an array`);
422
+ const userPromptArr = hooksObj.UserPromptSubmit === undefined ? [] : hooksObj.UserPromptSubmit;
423
+ if (!Array.isArray(userPromptArr)) throw new Error(`${opts.label}: ${opts.file} "hooks.UserPromptSubmit" must be an array`);
424
+ const preToolArr = hooksObj.PreToolUse === undefined ? [] : hooksObj.PreToolUse;
425
+ if (!Array.isArray(preToolArr)) throw new Error(`${opts.label}: ${opts.file} "hooks.PreToolUse" must be an array`);
426
+ const stopArr = hooksObj.Stop === undefined ? [] : hooksObj.Stop;
427
+ if (!Array.isArray(stopArr)) throw new Error(`${opts.label}: ${opts.file} "hooks.Stop" must be an array`);
428
+
429
+ const sessionStartUp = upgradeHookEntries(sessionStartArr, { legacyCmds: [], newCmd: opts.cmds.sessionStart, grouped: true });
430
+ const userPromptUp = upgradeHookEntries(userPromptArr, { legacyCmds: [], newCmd: opts.cmds.userPrompt, grouped: true });
431
+ const preToolUp = upgradeHookEntries(preToolArr, {
432
+ legacyCmds: [opts.legacyPreToolCmd],
433
+ newCmd: opts.cmds.preTool,
434
+ grouped: true,
435
+ matcher: "*",
436
+ });
437
+ const stopUp = upgradeHookEntries(stopArr, { legacyCmds: [opts.legacyStopCmd], newCmd: opts.cmds.stop, grouped: true });
438
+
439
+ if (!sessionStartUp.changed && !userPromptUp.changed && !preToolUp.changed && !stopUp.changed) {
440
+ return { hooksFile: opts.file, changed: false };
441
+ }
442
+
443
+ writeJsonConfigObject(opts.file, {
444
+ ...rootDoc,
445
+ hooks: {
446
+ ...hooksObj,
447
+ SessionStart: sessionStartUp.next,
448
+ UserPromptSubmit: userPromptUp.next,
449
+ PreToolUse: preToolUp.next,
450
+ Stop: stopUp.next,
451
+ },
452
+ });
453
+ return { hooksFile: opts.file, changed: true };
454
+ }
455
+
456
+ /**
457
+ * Runs standard doctor diagnostics checking binary availability and
458
+ * `SessionStart`/`UserPromptSubmit`/`PreToolUse`/`Stop` hook wiring for a native harness adapter.
459
+ *
460
+ * Args:
461
+ * opts (object): Harness name, binary, hooks file path, environment, commands, and hook detector
462
+ *
463
+ * Returns:
464
+ * { ok: string[]; problems: string[] }: Diagnostic status lines
465
+ */
466
+ export function runHookDoctorChecks(opts: {
467
+ name: string;
468
+ bin: string;
469
+ hooksFile: string;
470
+ env: NodeJS.ProcessEnv;
471
+ cmds: { sessionStart: string; userPrompt: string; preTool: string; stop: string };
472
+ hasHook?: (
473
+ doc: Record<string, unknown>,
474
+ field: "SessionStart" | "UserPromptSubmit" | "PreToolUse" | "Stop",
475
+ command: string,
476
+ ) => boolean;
477
+ }): { ok: string[]; problems: string[] } {
478
+ const ok: string[] = [];
479
+ const problems: string[] = [];
480
+
481
+ if (binOnPath(opts.bin, opts.env)) ok.push(`${opts.name}: binary found on PATH`);
482
+ else problems.push(`${opts.name}: binary not found on PATH`);
483
+
484
+ if (!existsSync(opts.hooksFile)) {
485
+ problems.push(`missing: ${opts.hooksFile} — run: neurastream adapter install ${opts.name}`);
486
+ return { ok, problems };
487
+ }
488
+
489
+ const checkField =
490
+ opts.hasHook ??
491
+ ((
492
+ doc: Record<string, unknown>,
493
+ field: "SessionStart" | "UserPromptSubmit" | "PreToolUse" | "Stop",
494
+ command: string,
495
+ ): boolean => {
496
+ const hooks = asObj(doc.hooks);
497
+ const arr = hooks && Array.isArray(hooks[field]) ? hooks[field] : [];
498
+ return hasHookCommand(arr, command);
499
+ });
500
+
501
+ try {
502
+ const doc = asObj(JSON.parse(readFileSync(opts.hooksFile, "utf8")));
503
+ const checks: ["SessionStart" | "UserPromptSubmit" | "PreToolUse" | "Stop", string][] = [
504
+ ["SessionStart", opts.cmds.sessionStart],
505
+ ["UserPromptSubmit", opts.cmds.userPrompt],
506
+ ["PreToolUse", opts.cmds.preTool],
507
+ ["Stop", opts.cmds.stop],
508
+ ];
509
+ for (const [field, cmd] of checks) {
510
+ if (doc && checkField(doc, field, cmd)) ok.push(`${opts.name}: ${field} hook wired in ${opts.hooksFile}`);
511
+ else problems.push(`${opts.name}: ${field} hook missing in ${opts.hooksFile} — run: neurastream adapter install ${opts.name}`);
512
+ }
513
+ } catch (err) {
514
+ problems.push(`${opts.name}: unreadable ${opts.hooksFile}: ${err instanceof Error ? err.message : String(err)}`);
515
+ }
516
+ return { ok, problems };
517
+ }
518
+
519
+ /**
520
+ * Shared CLI handler for `neurastream adapter install <name>`.
521
+ *
522
+ * Args:
523
+ * args (string[]): Arguments passed to `neurastream adapter`
524
+ * name (string): Adapter name
525
+ * installFn ((home: string) => { hooksFile: string; changed: boolean }): Installer function
526
+ *
527
+ * Returns:
528
+ * number: Process exit code
529
+ */
530
+ export function runAdapterInstallCli(
531
+ args: string[],
532
+ name: string,
533
+ installFn: (home: string) => { hooksFile: string; changed: boolean },
534
+ ): number {
535
+ if (args[0] !== "install" || (args.length !== 1 && (args.length !== 2 || args[1] !== name))) {
536
+ console.error(`usage: neurastream adapter install ${name}`);
537
+ return 2;
538
+ }
539
+ try {
540
+ const res = installFn(currentHome());
541
+ console.log(
542
+ `neurastream adapter install ${name}: ${res.changed ? "wired" : "already wired"} SessionStart + UserPromptSubmit + PreToolUse + Stop hooks in ${res.hooksFile}`,
543
+ );
544
+ return 0;
545
+ } catch (err) {
546
+ console.error(err instanceof Error ? err.message : String(err));
547
+ return 1;
548
+ }
549
+ }
550
+
551
+ /**
552
+ * Shared CLI handler for `neurastream doctor` on a native harness adapter.
553
+ *
554
+ * Args:
555
+ * name (string): Adapter name
556
+ * doctorFn ((home: string, env: NodeJS.ProcessEnv) => { ok: string[]; problems: string[] }): Doctor check function
557
+ *
558
+ * Returns:
559
+ * number: 0 if healthy, 1 if problems were found
560
+ */
561
+ export function runAdapterDoctorCli(
562
+ name: string,
563
+ doctorFn: (home: string, env: NodeJS.ProcessEnv) => { ok: string[]; problems: string[] },
564
+ ): number {
565
+ const report = doctorFn(currentHome(), process.env);
566
+ if (report.problems.length === 0) console.log(`neurastream doctor (${name}): ok`);
567
+ else console.log(`neurastream doctor (${name}): ${report.problems.length} problem(s)`);
568
+ for (const line of report.ok) console.log(line);
569
+ for (const line of report.problems) console.log(line);
570
+ return report.problems.length === 0 ? 0 : 1;
571
+ }
572
+
573
+ /** Wake prompt delivered when Main's per-turn call or edit-window cap resets with plans open. */
574
+ export const LIMIT_WAKE_TEXT = "main-guard: the call/edit limit has reset — continue the queue where you stopped.";
575
+
576
+ /** Injectable dependencies and options for `startPaneLimitWake`. */
577
+ export interface PaneLimitWakeOptions {
578
+ cfg: Config | (() => Config);
579
+ env?: NodeJS.ProcessEnv;
580
+ pollMs?: number;
581
+ nowMs?: () => number;
582
+ exec?: (args: string[], env: NodeJS.ProcessEnv) => { code: number; stdout: string };
583
+ }
584
+
585
+ /** Handle returned by `startPaneLimitWake` to stop polling or drive a synchronous tick in tests. */
586
+ export interface PaneLimitWake {
587
+ stop(): void;
588
+ tick(): void;
589
+ }
590
+
591
+ function defaultHerdrSyncExec(args: string[], env: NodeJS.ProcessEnv): { code: number; stdout: string } {
592
+ try {
593
+ const res = spawnSync("herdr", args, { timeout: 3000, encoding: "utf8", env });
594
+ return {
595
+ code: res.error ? 1 : (res.status ?? 1),
596
+ stdout: typeof res.stdout === "string" ? res.stdout : "",
597
+ };
598
+ } catch {
599
+ return { code: 1, stdout: "" };
600
+ }
601
+ }
602
+
603
+ function parseHerdrPaneId(stdout: string): string | undefined {
604
+ const trimmed = stdout.trim();
605
+ if (!trimmed) return undefined;
606
+ if (!trimmed.startsWith("{")) return str(trimmed);
607
+ try {
608
+ const parsed = asObj(JSON.parse(trimmed));
609
+ const result = asObj(parsed?.result);
610
+ const resultPane = asObj(result?.pane);
611
+ const topPane = asObj(parsed?.pane);
612
+ return (
613
+ str(resultPane?.pane_id) ??
614
+ str(resultPane?.paneId) ??
615
+ str(result?.pane_id) ??
616
+ str(result?.paneId) ??
617
+ str(topPane?.pane_id) ??
618
+ str(topPane?.paneId) ??
619
+ str(parsed?.pane_id) ??
620
+ str(parsed?.paneId)
621
+ );
622
+ } catch {
623
+ return undefined;
624
+ }
625
+ }
626
+
627
+ function hasOpenQueuePlans(cfg: Config): boolean {
628
+ try {
629
+ return openQueue(cfg.paths, cfg.review.agents).length > 0;
630
+ } catch {
631
+ return false;
632
+ }
633
+ }
634
+
635
+ function stillLimitCapped(cfg: Config): boolean {
636
+ const w = readWindow(cfg.paths);
637
+ const tier = currentTier(cfg);
638
+ return (mainCallsCapOn(cfg, tier) && w.mainCalls >= cfg.guards.main_max_calls) || w.used.length >= mainEditLimit(cfg, tier);
639
+ }
640
+
641
+ /**
642
+ * Starts a lightweight unref'd limit-wake poller for `HERDR_ENV=1` Main sessions so that when
643
+ * Main hits its per-turn call cap or edit-window cap with open plans, one continuation prompt
644
+ * (`LIMIT_WAKE_TEXT`) is delivered into Main's `herdr` pane upon window reset (and cancelled
645
+ * automatically if `mainCalls`/edit-window resets early).
646
+ *
647
+ * Args:
648
+ * opts (PaneLimitWakeOptions): Config provider, environment, poll interval, clock, and exec seam
649
+ *
650
+ * Returns:
651
+ * PaneLimitWake: Handle with `stop()` and `tick()`
652
+ */
653
+ export function startPaneLimitWake(opts: PaneLimitWakeOptions): PaneLimitWake {
654
+ const env = opts.env ?? process.env;
655
+ if (env.HERDR_ENV !== "1") {
656
+ return { stop: () => {}, tick: () => {} };
657
+ }
658
+
659
+ const getCfg = typeof opts.cfg === "function" ? opts.cfg : () => opts.cfg as Config;
660
+ const nowMs = opts.nowMs ?? Date.now;
661
+ const exec = opts.exec ?? defaultHerdrSyncExec;
662
+ const pollMs = opts.pollMs ?? 15_000;
663
+
664
+ let cachedPaneId = str(env.HERDR_PANE_ID);
665
+ const resolvePaneId = (): string | undefined => {
666
+ if (cachedPaneId) return cachedPaneId;
667
+ const res = exec(["pane", "current"], env);
668
+ if (res.code === 0) cachedPaneId = parseHerdrPaneId(res.stdout);
669
+ return cachedPaneId;
670
+ };
671
+
672
+ let wakeAt: number | null = null;
673
+ let stopped = false;
674
+
675
+ const tick = (): void => {
676
+ if (stopped) return;
677
+ const now = nowMs();
678
+ const cfg = getCfg();
679
+ const reset = nextLimitResetMs(cfg, now);
680
+ if (reset !== null) {
681
+ if (hasOpenQueuePlans(cfg)) {
682
+ wakeAt = wakeAt === null ? reset : Math.max(wakeAt, reset);
683
+ resolvePaneId();
684
+ } else {
685
+ wakeAt = null;
686
+ }
687
+ return;
688
+ }
689
+ if (wakeAt === null) return;
690
+ if (!stillLimitCapped(cfg) || now < wakeAt) {
691
+ wakeAt = null;
692
+ return;
693
+ }
694
+ wakeAt = null;
695
+ if (!hasOpenQueuePlans(cfg)) return;
696
+ const paneId = resolvePaneId();
697
+ if (!paneId) return;
698
+ const promptRes = exec(["agent", "prompt", paneId, LIMIT_WAKE_TEXT], env);
699
+ if (promptRes.code !== 0) {
700
+ exec(["pane", "send-text", paneId, LIMIT_WAKE_TEXT], env);
701
+ exec(["pane", "send-keys", paneId, "Enter"], env);
702
+ }
703
+ };
704
+
705
+ const timer = setInterval(tick, pollMs);
706
+ if (typeof timer.unref === "function") timer.unref();
707
+
708
+ return {
709
+ tick,
710
+ stop() {
711
+ if (stopped) return;
712
+ stopped = true;
713
+ wakeAt = null;
714
+ clearInterval(timer);
715
+ },
716
+ };
717
+ }
718
+
719
+ /**
720
+ * Spawns a native harness binary as Main with `NEURASTREAM_MAIN_LAUNCHER=1`, arming
721
+ * `startPaneLimitWake` for `HERDR_ENV=1` sessions until the child exits.
722
+ *
723
+ * Args:
724
+ * bin (string): Harness executable name
725
+ * args (string[]): CLI arguments forwarded to the harness binary
726
+ * cfg (Config | undefined): Loaded neurastream configuration enabling pane limit-wake
727
+ *
728
+ * Returns:
729
+ * Promise<number>: Process exit code (127 when spawning fails)
730
+ */
731
+ export async function spawnHarnessMain(bin: string, args: string[], cfg?: Config): Promise<number> {
732
+ const env: NodeJS.ProcessEnv = { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1", NEURASTREAM_HARNESS: bin };
733
+ const wake = cfg ? startPaneLimitWake({ cfg, env }) : null;
734
+ const { promise, resolve } = Promise.withResolvers<number>();
735
+ let settled = false;
736
+ const finish = (code: number): void => {
737
+ if (settled) return;
738
+ settled = true;
739
+ wake?.stop();
740
+ resolve(code);
741
+ };
742
+ const child = spawn(bin, args, { stdio: "inherit", env });
743
+ child.on("error", (err) => {
744
+ console.error(`neurastream main (${bin}): cannot start ${bin}: ${err.message}`);
745
+ finish(127);
746
+ });
747
+ child.on("close", (code) => finish(code ?? 1));
748
+ return promise;
749
+ }
750
+
751
+ /**
752
+ * Returns default no-op method implementations shared by harness adapters that do not support
753
+ * omp-specific trace/dump/provider features.
754
+ *
755
+ * Args:
756
+ * name (string): Harness adapter name used in unsupported `complete()` error messages
757
+ *
758
+ * Returns:
759
+ * object: Default stub methods compatible with `HarnessAdapter`
760
+ */
761
+ export function defaultAdapterStubs(
762
+ name: string,
763
+ ): Pick<
764
+ HarnessAdapter,
765
+ | "ownerTurns"
766
+ | "completedResults"
767
+ | "episodes"
768
+ | "dumps"
769
+ | "dumpModel"
770
+ | "dumpParts"
771
+ | "dumpPromptTokens"
772
+ | "spawnBriefsIn"
773
+ | "subagentTraces"
774
+ | "providers"
775
+ | "complete"
776
+ > {
777
+ return {
778
+ ownerTurns: () => [],
779
+ completedResults: () => [],
780
+ episodes: () => [],
781
+ dumps: () => [],
782
+ dumpModel: () => undefined,
783
+ dumpParts: () => ({ system: 0, messages: 0, tools: [] }),
784
+ dumpPromptTokens: () => null,
785
+ spawnBriefsIn: () => [],
786
+ subagentTraces: () => [],
787
+ providers: () => [],
788
+ complete: () => Promise.reject(new Error(`${name} adapter does not support stateless complete()`)),
789
+ };
790
+ }
791
+
792
+ /**
793
+ * Returns `["--dangerously-skip-permissions"]` unless already present in `args`.
794
+ *
795
+ * Args:
796
+ * args (readonly string[]): Existing profile CLI arguments
797
+ *
798
+ * Returns:
799
+ * string[]: Default permission flag array or empty array
800
+ */
801
+ export function skipPermissionsArgs(args: readonly string[]): string[] {
802
+ return args.includes("--dangerously-skip-permissions") ? [] : ["--dangerously-skip-permissions"];
803
+ }
804
+
805
+ /**
806
+ * Builds a runner launch specification from a `SpawnProfile`, optionally prepending `--model`
807
+ * and adapter-default CLI flags before `profile.args`.
808
+ *
809
+ * Args:
810
+ * kind (string): Runner agent kind (e.g. `"agy"`, `"claude"`, `"codex"`)
811
+ * profile (SpawnProfile): Resolved subagent spawn profile
812
+ * includeModelFlag (boolean): Whether to prepend `--model <model>` when `profile.model` is set
813
+ * defaultArgs (readonly string[]): Adapter-default CLI flags prepended before `profile.args`
814
+ *
815
+ * Returns:
816
+ * { kind: string; args: string[]; env?: Record<string, string> }: Subagent launch spec
817
+ */
818
+ export function subagentLaunchSpecFrom(
819
+ kind: string,
820
+ profile: SpawnProfile,
821
+ includeModelFlag = true,
822
+ defaultArgs: readonly string[] = [],
823
+ ): { kind: string; args: string[]; env?: Record<string, string> } {
824
+ return {
825
+ kind,
826
+ args: [...(includeModelFlag && profile.model ? ["--model", profile.model] : []), ...defaultArgs, ...profile.args],
827
+ ...(Object.keys(profile.env).length > 0 ? { env: { ...profile.env } } : {}),
828
+ };
829
+ }
830
+
831
+ /**
832
+ * Collects and sorts `OwnerTurn` entries at or after `since` across JSONL transcript `files`.
833
+ *
834
+ * Args:
835
+ * files (string[]): Discovered JSONL transcript paths
836
+ * since (number): Minimum Unix timestamp (seconds)
837
+ * extract ((rec: Record<string, unknown>, since: number) => OwnerTurn | null): Per-record extractor
838
+ *
839
+ * Returns:
840
+ * OwnerTurn[]: Extracted turns sorted ascending by `at`
841
+ */
842
+ export function collectOwnerTurns(
843
+ files: string[],
844
+ since: number,
845
+ extract: (rec: Record<string, unknown>, since: number) => OwnerTurn | null,
846
+ ): OwnerTurn[] {
847
+ const out: OwnerTurn[] = [];
848
+ for (const file of files) {
849
+ for (const rec of parseJsonlRecords(file)) {
850
+ const turn = extract(rec, since);
851
+ if (turn) out.push(turn);
852
+ }
853
+ }
854
+ out.sort((a, b) => a.at - b.at);
855
+ return out;
856
+ }
857
+
858
+ /**
859
+ * Creates a `RunSource` from a transcript file finder and per-file `Run` builder, sorted newest-first.
860
+ *
861
+ * Args:
862
+ * findFilesFn (() => string[]): Function returning transcript paths
863
+ * buildRunFn ((file: string, since: number) => Run | null): Per-file run builder
864
+ *
865
+ * Returns:
866
+ * RunSource: RunSource returning sorted runs with `mainSession` returning `null`
867
+ */
868
+ export function createTranscriptRunSource(
869
+ findFilesFn: () => string[],
870
+ buildRunFn: (file: string, since: number) => Run | null,
871
+ ): RunSource {
872
+ return {
873
+ listRuns(since: number): Run[] {
874
+ const runs: Run[] = [];
875
+ for (const file of findFilesFn()) {
876
+ const run = buildRunFn(file, since);
877
+ if (run) runs.push(run);
878
+ }
879
+ runs.sort((a, b) => b.lastWriteAt - a.lastWriteAt);
880
+ return runs;
881
+ },
882
+ mainSession: () => null,
883
+ };
884
+ }
885
+
886
+ /**
887
+ * Builds the refusal reason when Main invokes a harness-native subagent tool inside a managed
888
+ * `herdr` terminal session (`HERDR_ENV=1`).
889
+ *
890
+ * Args:
891
+ * rawTool (string): Native subagent tool name blocked by the hook
892
+ *
893
+ * Returns:
894
+ * string: Actionable refusal message pointing to `neurastream spawn`
895
+ */
896
+ export function nativeSpawnBlockReason(rawTool: string): string {
897
+ return `neurastream: native subagent tool "${rawTool}" is blocked inside a managed terminal session (HERDR_ENV=1). Spawn helpers via: neurastream spawn --agent <profile> --plan <plan.md> --cwd <worktree> --brief "<brief>"`;
898
+ }
899
+
900
+ /**
901
+ * Extracts owner prompt text from a `UserPromptSubmit` hook payload (`prompt`, `userPrompt`,
902
+ * `user_prompt`, or `message`).
903
+ *
904
+ * Args:
905
+ * payload (Record<string, unknown>): Parsed hook stdin JSON object
906
+ *
907
+ * Returns:
908
+ * string: Extracted prompt text, or `""` when absent
909
+ */
910
+ export function extractHookPrompt(payload: Record<string, unknown>): string {
911
+ const direct =
912
+ str(payload.lastUserInput) ??
913
+ str(payload.prompt) ??
914
+ str(payload.userPrompt) ??
915
+ str(payload.user_prompt) ??
916
+ str(payload.message);
917
+ if (direct) return direct;
918
+ const msg = asObj(payload.message);
919
+ return msg ? (str(msg.content) ?? str(msg.text) ?? "") : "";
920
+ }
921
+
922
+ /**
923
+ * Evaluates `session-start`, `user-prompt`, `pre-tool`, or `stop` hooks for Claude/Codex-style
924
+ * payloads, delegating only the `pre-tool` deny JSON formatting to the caller.
925
+ *
926
+ * Args:
927
+ * opts (object): Event name, stdin payload, config, env, tool alias map, extra path extractor, and deny formatter
928
+ *
929
+ * Returns:
930
+ * { code: number; stdout: string }: Exit code and JSON stdout
931
+ */
932
+ export function handleStandardHook(opts: {
933
+ event: string;
934
+ stdinText: string;
935
+ cfg: Config | undefined;
936
+ env: NodeJS.ProcessEnv;
937
+ defaultId: string;
938
+ toolMap: Record<string, string>;
939
+ nativeSpawnTools?: readonly string[];
940
+ extraPaths?: (toolInput: Record<string, unknown>) => string[];
941
+ fallbackSessionId?: (payload: Record<string, unknown>) => string | undefined;
942
+ formatPreToolDeny: (reason: string) => string;
943
+ }): { code: number; stdout: string } {
944
+ const { event, stdinText, cfg, env } = opts;
945
+ if (event === "session-start") {
946
+ if (!isHookActive(env) || !cfg) return { code: 0, stdout: "" };
947
+ const text = buildSessionStartContext(cfg, env);
948
+ if (!text) return { code: 0, stdout: "" };
949
+ return {
950
+ code: 0,
951
+ stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: text } }),
952
+ };
953
+ }
954
+
955
+ if (event === "user-prompt") {
956
+ if (!isHookActive(env) || !cfg || hookAgent(env) !== "main") return { code: 0, stdout: "" };
957
+ const prompt = extractHookPrompt(parseHookPayload(stdinText));
958
+ const text = checkInject({ inject: prompt, agent: "main" }, cfg).inject;
959
+ if (!text) return { code: 0, stdout: "" };
960
+ return {
961
+ code: 0,
962
+ stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: text } }),
963
+ };
964
+ }
965
+
966
+ if (event === "pre-tool") {
967
+ if (!isHookActive(env) || !cfg) return { code: 0, stdout: "" };
968
+ const payload = parseHookPayload(stdinText);
969
+ const rawTool = str(payload.tool_name) ?? str(payload.tool) ?? "";
970
+ const agent = hookAgent(env);
971
+ if (agent === "main" && env.HERDR_ENV === "1" && opts.nativeSpawnTools?.includes(rawTool)) {
972
+ return { code: 0, stdout: opts.formatPreToolDeny(nativeSpawnBlockReason(rawTool)) };
973
+ }
974
+ const toolInput = asObj(payload.tool_input) ?? asObj(payload.input) ?? {};
975
+ const cwd = str(payload.cwd) ?? process.cwd();
976
+ const command =
977
+ typeof toolInput.command === "string" ? toolInput.command : typeof toolInput.cmd === "string" ? toolInput.cmd : "";
978
+ const tool = canonicalHookTool(rawTool, cfg, opts.toolMap);
979
+ const extra = opts.extraPaths ? opts.extraPaths(toolInput) : [];
980
+ const pathVal = toolInput.file_path ?? toolInput.path ?? toolInput.file ?? extra[0];
981
+ const input: Record<string, unknown> = {
982
+ ...toolInput,
983
+ ...(command && typeof toolInput.command !== "string" ? { command } : {}),
984
+ ...(typeof pathVal === "string" && typeof toolInput.path !== "string" ? { path: pathVal } : {}),
985
+ };
986
+ const paths = resolveHookPaths([toolInput.file_path, toolInput.path, toolInput.file, ...extra], cwd);
987
+ const writes = isWriteHookTool(tool, cfg) ? paths : [];
988
+ const agentId = hookAgentId(env, opts.fallbackSessionId ? opts.fallbackSessionId(payload) : str(payload.session_id), opts.defaultId);
989
+ const decision = checkTool({ tool, input, cwd, agent, agentId, calls: 0, paths, writes, command }, cfg);
990
+ return decision.allow ? { code: 0, stdout: "" } : { code: 0, stdout: opts.formatPreToolDeny(decision.reason) };
991
+ }
992
+
993
+ if (event === "stop") {
994
+ if (!isHookActive(env) || !cfg) return { code: 0, stdout: "" };
995
+ const decision = checkStop({ agent: hookAgent(env), callsSinceStop: 0, idleStops: 0, ledgerText: "", liveAgents: liveHerdrSubagents(env, cfg) }, cfg);
996
+ return decision.allow ? { code: 0, stdout: "" } : { code: 0, stdout: JSON.stringify({ decision: "block", reason: decision.reason }) };
997
+ }
998
+
999
+ return { code: 2, stdout: "" };
1000
+ }
1001
+
1002
+ /**
1003
+ * Returns the names of live working `herdr` panes that were spawned by `neurastream spawn`
1004
+ * (intersected against `staffing.json`, excluding Main's own pane) so native-harness Stop hooks
1005
+ * (`agy`, `claude`, `codex`) pass structured live helper names to `checkStop`.
1006
+ *
1007
+ * Args:
1008
+ * env (Record<string, string | undefined>): Process environment map
1009
+ * cfg (Config): Loaded neurastream configuration
1010
+ *
1011
+ * Returns:
1012
+ * string[]: Live staffed subagent names, or `[]` outside `herdr`
1013
+ */
1014
+ export function liveHerdrSubagents(env: Record<string, string | undefined>, cfg: Config): string[] {
1015
+ if (env.HERDR_ENV !== "1") return [];
1016
+ const staffed = new Set(Object.values(readStaffing(cfg.paths)).flat());
1017
+ if (staffed.size === 0) return [];
1018
+ const bin = env.HERDR_BIN_PATH || "herdr";
1019
+ const r = spawnSync(bin, ["agent", "list"], { encoding: "utf8", timeout: 2000 });
1020
+ if (r.status !== 0 || !r.stdout) return [];
1021
+ try {
1022
+ const parsed = JSON.parse(r.stdout) as { result?: { agents?: Array<Record<string, unknown>> } };
1023
+ const agents = parsed.result?.agents;
1024
+ if (!Array.isArray(agents)) return [];
1025
+ const selfPane = env.HERDR_PANE_ID;
1026
+ const live: string[] = [];
1027
+ for (const item of agents) {
1028
+ if (item.agent_status !== "working") continue;
1029
+ const paneId = typeof item.pane_id === "string" ? item.pane_id : "";
1030
+ if (selfPane && paneId === selfPane) continue;
1031
+ const name = typeof item.name === "string" ? item.name : "";
1032
+ if (!name || !staffed.has(name)) continue;
1033
+ if (!live.includes(name)) live.push(name);
1034
+ }
1035
+ return live;
1036
+ } catch {
1037
+ return [];
1038
+ }
1039
+ }