neurastream 0.3.26 → 0.3.28

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