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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.3.26",
3
+ "version": "0.3.28",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -0,0 +1,661 @@
1
+ // Antigravity (`agy`) harness adapter: subagent launch spec, transcript.jsonl RunSource/TraceSource,
2
+ // sandbox-safe hooks.json installer, and doctor checks.
3
+
4
+ import { basename, dirname, 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 { checkInject, checkStop, checkTool } from "../../core/guards.ts";
8
+ import type { SpawnProfile } from "../../core/runner.ts";
9
+ import {
10
+ buildSessionStartContext,
11
+ canonicalHookTool,
12
+ hasHookCommand,
13
+ hookAgent,
14
+ hookAgentId,
15
+ isHookActive,
16
+ LEGACY_PRE_TOOL_CMD,
17
+ LEGACY_STOP_CMD,
18
+ parseHookPayload,
19
+ resolveHookPaths,
20
+ upgradeHookEntries,
21
+ } from "../hook-bridge.ts";
22
+ import type { HarnessAdapter } from "../index.ts";
23
+ import {
24
+ addUsageTotals,
25
+ asObj,
26
+ buildRunRecord,
27
+ collectOwnerTurns,
28
+ collectTraceRuns,
29
+ createTraceSource,
30
+ createTranscriptRunSource,
31
+ defaultAdapterStubs,
32
+ extractHookPrompt,
33
+ findFiles,
34
+ isInsideWorkRoot,
35
+ isNum,
36
+ isWriteHookTool,
37
+ liveHerdrSubagents,
38
+ nativeSpawnBlockReason,
39
+ num,
40
+ parseIsoSec,
41
+ parseJsonlRecords,
42
+ readJsonConfigObject,
43
+ runAdapterDoctorCli,
44
+ runAdapterInstallCli,
45
+ runHookDoctorChecks,
46
+ skipPermissionsArgs,
47
+ spawnHarnessMain,
48
+ statMtimeSec,
49
+ str,
50
+ subagentLaunchSpecFrom,
51
+ subSpawnBlockReason,
52
+ writeJsonConfigObject,
53
+ applyHookChatCommand,
54
+ } from "../shared.ts";
55
+
56
+ /** Hook command wired into Antigravity's SessionStart lifecycle. */
57
+ export const AGY_SESSION_START_CMD = "neurastream adapter hook agy session-start";
58
+
59
+ /** Hook command wired into Antigravity's UserPromptSubmit lifecycle. */
60
+ export const AGY_USER_PROMPT_CMD = "neurastream adapter hook agy user-prompt";
61
+
62
+ /** Hook command wired into Antigravity's PreToolUse lifecycle. */
63
+ export const AGY_PRE_TOOL_CMD = "neurastream adapter hook agy pre-tool";
64
+
65
+ /** Hook command wired into Antigravity's Stop lifecycle. */
66
+ export const AGY_STOP_CMD = "neurastream adapter hook agy stop";
67
+
68
+ const AGY_TOOL_MAP: Record<string, string> = {
69
+ run_command: "bash",
70
+ write_file: "write",
71
+ write_to_file: "write",
72
+ edit_file: "edit",
73
+ replace_file_content: "edit",
74
+ multi_replace_file_content: "edit",
75
+ read_file: "read",
76
+ view_file: "read",
77
+ view_file_outline: "read",
78
+ view_code_item: "read",
79
+ grep_search: "grep",
80
+ find_by_name: "find",
81
+ list_dir: "find",
82
+ };
83
+
84
+ /** Path to Antigravity's hooks configuration file under `home`. */
85
+ export function agyHooksFile(home: string): string {
86
+ return join(home, ".gemini", "config", "hooks.json");
87
+ }
88
+
89
+ /** Default Antigravity brain root containing conversation transcript directories. */
90
+ export function agyBrainRoot(home: string): string {
91
+ return join(home, ".gemini", "antigravity", "brain");
92
+ }
93
+
94
+ function agySessionsRoot(cfg: Config): string {
95
+ return cfg.adapter?.name === "agy" && cfg.adapter.sessions ? cfg.adapter.sessions : agyBrainRoot(cfg.paths.home);
96
+ }
97
+
98
+ /**
99
+ * Recursively discovers `transcript.jsonl` files beneath `root`.
100
+ *
101
+ * Args:
102
+ * root (string): Root directory to search
103
+ * maxDepth (number): Maximum recursion depth
104
+ *
105
+ * Returns:
106
+ * string[]: Sorted list of discovered transcript file paths
107
+ */
108
+ export function findAgyTranscripts(root: string, maxDepth = 4): string[] {
109
+ return findFiles(root, (name) => name === "transcript.jsonl", maxDepth);
110
+ }
111
+
112
+ /**
113
+ * Derives a stable run id from an Antigravity `transcript.jsonl` file path.
114
+ *
115
+ * Args:
116
+ * file (string): Full path to `transcript.jsonl`
117
+ * root (string): Sessions root directory
118
+ *
119
+ * Returns:
120
+ * string: Conversation/run identifier
121
+ */
122
+ export function agyRunIdFromPath(file: string, root: string): string {
123
+ const dir = dirname(file);
124
+ const parent = dirname(dir);
125
+ if (basename(dir) === "logs" && basename(parent) === ".system_generated") {
126
+ const conv = basename(dirname(parent));
127
+ if (conv && conv !== ".") return conv;
128
+ }
129
+ if (dir !== root) {
130
+ const conv = basename(dir);
131
+ if (conv && conv !== ".") return conv;
132
+ }
133
+ return "agy";
134
+ }
135
+
136
+ function usageFromStep(step: Record<string, unknown>): TraceUsage | undefined {
137
+ const u = asObj(step.usage);
138
+ const hasTopLevel =
139
+ isNum(step.input_tokens) ||
140
+ isNum(step.output_tokens) ||
141
+ isNum(step.cache_read_tokens) ||
142
+ isNum(step.cache_write_tokens);
143
+ if (!u && !hasTopLevel) return undefined;
144
+ const costObj = u ? asObj(u.cost) : null;
145
+ const cost = costObj ? num(costObj.total) : num(u?.cost ?? step.cost);
146
+ const input = num(u?.input ?? u?.prompt_tokens ?? step.input_tokens);
147
+ const output = num(u?.output ?? u?.completion_tokens ?? step.output_tokens);
148
+ const cacheRead = num(u?.cacheRead ?? u?.cache_read ?? step.cache_read_tokens);
149
+ const cacheWrite = num(u?.cacheWrite ?? u?.cache_write ?? step.cache_write_tokens);
150
+ const totalTokens = num(u?.totalTokens ?? step.total_tokens) || input + output + cacheRead + cacheWrite;
151
+ return { input, output, cacheRead, cacheWrite, totalTokens, cost };
152
+ }
153
+
154
+ function modelOfStep(step: Record<string, unknown>): string | undefined {
155
+ const provider = str(step.provider);
156
+ const model = str(step.model);
157
+ if (provider && model) return model.includes("/") ? model : `${provider}/${model}`;
158
+ return model;
159
+ }
160
+
161
+ function statusFromSteps(steps: Record<string, unknown>[]): { status: Run["status"]; detail: string } {
162
+ const last = steps.at(-1);
163
+ const raw = typeof last?.status === "string" ? last.status.toUpperCase() : "";
164
+ if (raw === "ERROR" || raw === "FAILED") return { status: "died", detail: "DIED: error" };
165
+ if (raw === "WAITING") return { status: "waiting", detail: "WAITING: input" };
166
+ if (raw === "RUNNING" || raw === "IN_PROGRESS") return { status: "running", detail: "RUNNING" };
167
+ return { status: "done", detail: "done" };
168
+ }
169
+
170
+ function buildRunFromTranscript(file: string, root: string, since: number): Run | null {
171
+ const mtimeSec = statMtimeSec(file);
172
+ if (mtimeSec === null) return null;
173
+ const steps = parseJsonlRecords(file);
174
+ let startedAt: number | null = null;
175
+ let lastTs: number | null = null;
176
+ let model = "?";
177
+ let calls = 0;
178
+ const totals = { tokens: 0, cacheRead: 0, cost: 0, inputTokens: 0, prefillTokens: 0 };
179
+
180
+ for (const step of steps) {
181
+ const ts = parseIsoSec(step.created_at);
182
+ if (ts !== null) {
183
+ if (startedAt === null) startedAt = ts;
184
+ lastTs = ts;
185
+ }
186
+ const stepModel = modelOfStep(step);
187
+ if (stepModel) model = stepModel;
188
+ const type = typeof step.type === "string" ? step.type : "";
189
+ const source = typeof step.source === "string" ? step.source : "";
190
+ const usage = usageFromStep(step);
191
+ if (type === "PLANNER_RESPONSE" || source === "MODEL" || usage) calls++;
192
+ if (usage) addUsageTotals(totals, usage);
193
+ }
194
+
195
+ const lastWriteAt = lastTs ?? mtimeSec;
196
+ if (lastWriteAt < since) return null;
197
+ const { status, detail } = statusFromSteps(steps);
198
+ return buildRunRecord({
199
+ id: agyRunIdFromPath(file, root),
200
+ model,
201
+ calls,
202
+ ...totals,
203
+ status,
204
+ detail,
205
+ startedAt,
206
+ lastWriteAt,
207
+ });
208
+ }
209
+
210
+ /**
211
+ * Parses an Antigravity `transcript.jsonl` file into core `TraceEvent` items.
212
+ *
213
+ * Args:
214
+ * file (string): Path to `transcript.jsonl`
215
+ * runId (string): Run identifier assigned to emitted events
216
+ *
217
+ * Returns:
218
+ * TraceEvent[]: Normalized trace events in file order
219
+ */
220
+ export function parseAgyTraceFile(file: string, runId: string): TraceEvent[] {
221
+ const events: TraceEvent[] = [];
222
+ for (const step of parseJsonlRecords(file)) {
223
+ const ts = parseIsoSec(step.created_at);
224
+ const model = modelOfStep(step);
225
+ const provider = str(step.provider);
226
+ const usage = usageFromStep(step);
227
+ const type = typeof step.type === "string" ? step.type : "";
228
+ const source = typeof step.source === "string" ? step.source : "";
229
+ const content = typeof step.content === "string" ? step.content : "";
230
+
231
+ if (type === "PLANNER_RESPONSE" || source === "MODEL") {
232
+ if (content.trim()) events.push({ kind: "assistantText", ts, runId, text: content, model, provider, usage });
233
+ const toolCalls = Array.isArray(step.tool_calls) ? step.tool_calls : [];
234
+ for (const rawCall of toolCalls) {
235
+ const call = asObj(rawCall);
236
+ if (!call) continue;
237
+ const tool = typeof call.name === "string" ? call.name : typeof call.tool === "string" ? call.tool : "?";
238
+ const args = asObj(call.arguments) ?? asObj(call.args) ?? asObj(call.input) ?? {};
239
+ const callId = typeof call.id === "string" ? call.id : undefined;
240
+ events.push({ kind: "toolCall", ts, runId, tool, args, callId, model, provider, usage });
241
+ }
242
+ continue;
243
+ }
244
+
245
+ if (type === "TOOL_RESULT" || step.role === "tool") {
246
+ const tool = typeof step.tool_name === "string" ? step.tool_name : typeof step.tool === "string" ? step.tool : undefined;
247
+ const callId = typeof step.call_id === "string" ? step.call_id : typeof step.toolCallId === "string" ? step.toolCallId : undefined;
248
+ const statusRaw = typeof step.status === "string" ? step.status.toUpperCase() : "";
249
+ const isError = step.is_error === true || statusRaw === "ERROR";
250
+ events.push({ kind: "toolResult", ts, runId, tool, callId, isError, text: content });
251
+ continue;
252
+ }
253
+
254
+ if (usage) events.push({ kind: "usage", ts, runId, model, provider, usage });
255
+ }
256
+ return events;
257
+ }
258
+
259
+ /**
260
+ * Creates a `RunSource` backed by Antigravity `transcript.jsonl` files under `cfg`.
261
+ *
262
+ * Args:
263
+ * cfg (Config): Loaded neurastream configuration
264
+ *
265
+ * Returns:
266
+ * RunSource: RunSource reading Antigravity conversation transcripts
267
+ */
268
+ export function agyRunSource(cfg: Config): RunSource {
269
+ const root = agySessionsRoot(cfg);
270
+ return createTranscriptRunSource(
271
+ () => findAgyTranscripts(root),
272
+ (file, since) => buildRunFromTranscript(file, root, since),
273
+ );
274
+ }
275
+
276
+ /**
277
+ * Lists Antigravity trace runs discovered under `root`.
278
+ *
279
+ * Args:
280
+ * root (string): Sessions root directory
281
+ *
282
+ * Returns:
283
+ * TraceRun[]: Discovered trace runs sorted by run id
284
+ */
285
+ export function agyTraceRuns(root: string): TraceRun[] {
286
+ return collectTraceRuns(findAgyTranscripts(root), (file) => agyRunIdFromPath(file, root));
287
+ }
288
+
289
+ /**
290
+ * Creates a `TraceSource` over Antigravity `transcript.jsonl` files under `root`.
291
+ *
292
+ * Args:
293
+ * root (string): Sessions root directory
294
+ *
295
+ * Returns:
296
+ * TraceSource: TraceSource returning events for a requested run id
297
+ */
298
+ export function agyTraceSource(root: string): TraceSource {
299
+ return createTraceSource(root, agyTraceRuns, parseAgyTraceFile);
300
+ }
301
+
302
+ /**
303
+ * Extracts owner prompts (`USER_INPUT`) and Main replies (`PLANNER_RESPONSE`) from Antigravity
304
+ * `transcript.jsonl` files at or after Unix second `since`.
305
+ *
306
+ * Args:
307
+ * cfg (Config): Loaded neurastream configuration
308
+ * since (number): Minimum Unix timestamp in seconds
309
+ *
310
+ * Returns:
311
+ * OwnerTurn[]: Extracted turns sorted ascending by timestamp
312
+ */
313
+ export function agyOwnerTurns(cfg: Config, since: number): OwnerTurn[] {
314
+ return collectOwnerTurns(findAgyTranscripts(agySessionsRoot(cfg)), since, (step, cutoff): OwnerTurn | null => {
315
+ const at = parseIsoSec(step.created_at);
316
+ if (at === null || at < cutoff) return null;
317
+ const type = typeof step.type === "string" ? step.type : "";
318
+ const text = typeof step.content === "string" ? step.content.trim() : "";
319
+ if (!text) return null;
320
+ if (type === "USER_INPUT") return { at, role: "owner", text };
321
+ if (type === "PLANNER_RESPONSE") return { at, role: "main", text };
322
+ return null;
323
+ });
324
+ }
325
+
326
+ function hasAgyHook(
327
+ doc: Record<string, unknown>,
328
+ field: "SessionStart" | "UserPromptSubmit" | "PreToolUse" | "Stop",
329
+ command: string,
330
+ ): boolean {
331
+ const agyField = field === "UserPromptSubmit" ? "PreInvocation" : field;
332
+ if (Array.isArray(doc[agyField]) && hasHookCommand(doc[agyField], command)) return true;
333
+ for (const value of Object.values(doc)) {
334
+ const group = asObj(value);
335
+ if (group && Array.isArray(group[agyField]) && hasHookCommand(group[agyField], command)) return true;
336
+ }
337
+ return false;
338
+ }
339
+
340
+ function agyPromptTurnKey(payload: Record<string, unknown>): { convId: string; key: string } | null {
341
+ const convId = str(payload.conversationId);
342
+ if (!convId) return null;
343
+ const transcriptPath = str(payload.transcriptPath);
344
+ if (transcriptPath) {
345
+ let lastStep: number | null = null;
346
+ for (const rec of parseJsonlRecords(transcriptPath)) {
347
+ if (rec.type === "USER_INPUT" && isNum(rec.step_index)) lastStep = rec.step_index;
348
+ }
349
+ if (lastStep !== null) return { convId, key: `step:${lastStep}` };
350
+ }
351
+ const prompt = extractHookPrompt(payload);
352
+ return prompt ? { convId, key: `prompt:${prompt}` } : null;
353
+ }
354
+
355
+ function isDuplicateAgyPrompt(payload: Record<string, unknown>, cfg: Config): boolean {
356
+ const turn = agyPromptTurnKey(payload);
357
+ if (!turn) return false;
358
+ const stateFile = join(cfg.paths.queue_state, "agy-last-prompt.json");
359
+ let prev: Record<string, unknown> = {};
360
+ try {
361
+ prev = readJsonConfigObject(stateFile, "agy pre-invocation");
362
+ } catch {
363
+ prev = {};
364
+ }
365
+ if (prev[turn.convId] === turn.key) return true;
366
+ try {
367
+ writeJsonConfigObject(stateFile, { ...prev, [turn.convId]: turn.key });
368
+ } catch {
369
+ // best-effort dedup state
370
+ }
371
+ return false;
372
+ }
373
+
374
+ /**
375
+ * Translates Antigravity `SessionStart`, `PreInvocation` (`user-prompt`), `PreToolUse`, and `Stop`
376
+ * hook payloads into core guard calls and native protojson JSON.
377
+ *
378
+ * Args:
379
+ * event (string): Hook lifecycle event (`"session-start"`, `"user-prompt"`, `"pre-invocation"`, `"pre-tool"`, or `"stop"`)
380
+ * stdinText (string): Raw JSON payload from Antigravity
381
+ * cfg (Config | undefined): Loaded config when active; undefined on inactive fast-path
382
+ * env (NodeJS.ProcessEnv): Process environment variables
383
+ *
384
+ * Returns:
385
+ * { code: number; stdout: string }: Exit code and protojson-compatible JSON stdout
386
+ */
387
+ export function handleAgyHook(
388
+ event: string,
389
+ stdinText: string,
390
+ cfg: Config | undefined,
391
+ env: NodeJS.ProcessEnv = process.env,
392
+ ): { code: number; stdout: string } {
393
+ if (event === "session-start") {
394
+ if (!isHookActive(env) || !cfg) return { code: 0, stdout: "{}" };
395
+ const text = buildSessionStartContext(cfg, env);
396
+ return {
397
+ code: 0,
398
+ stdout: text ? JSON.stringify({ injectSteps: [{ systemMessage: { systemMessage: text } }] }) : "{}",
399
+ };
400
+ }
401
+
402
+ if (event === "user-prompt" || event === "pre-invocation") {
403
+ if (!isHookActive(env) || !cfg || hookAgent(env) !== "main") return { code: 0, stdout: "{}" };
404
+ const payload = parseHookPayload(stdinText);
405
+ if (isDuplicateAgyPrompt(payload, cfg)) return { code: 0, stdout: "{}" };
406
+ const prompt = extractHookPrompt(payload);
407
+ const cmdNote = applyHookChatCommand(prompt, cfg);
408
+ const injected = checkInject({ inject: prompt, agent: "main" }, cfg).inject;
409
+ const text = [cmdNote, injected].filter(Boolean).join("\n");
410
+ return {
411
+ code: 0,
412
+ stdout: text ? JSON.stringify({ injectSteps: [{ systemMessage: { systemMessage: text } }] }) : "{}",
413
+ };
414
+ }
415
+
416
+ if (event === "pre-tool") {
417
+ if (!isHookActive(env) || !cfg) return { code: 0, stdout: JSON.stringify({ decision: "allow" }) };
418
+ const payload = parseHookPayload(stdinText);
419
+ const toolCall = asObj(payload.toolCall) ?? {};
420
+ const rawTool = typeof toolCall.name === "string" ? toolCall.name : typeof payload.tool === "string" ? payload.tool : "";
421
+ const agent = hookAgent(env);
422
+ if (rawTool === "invoke_subagent") {
423
+ if (agent === "sub") {
424
+ return { code: 0, stdout: JSON.stringify({ decision: "deny", reason: subSpawnBlockReason(rawTool) }) };
425
+ }
426
+ if (agent === "main" && env.HERDR_ENV === "1") {
427
+ return { code: 0, stdout: JSON.stringify({ decision: "deny", reason: nativeSpawnBlockReason(rawTool) }) };
428
+ }
429
+ }
430
+ const rawArgs = asObj(toolCall.args) ?? asObj(payload.args) ?? {};
431
+ const ws = Array.isArray(payload.workspacePaths) ? payload.workspacePaths : [];
432
+ const cwd = (typeof ws[0] === "string" && ws[0]) || (typeof rawArgs.Cwd === "string" && rawArgs.Cwd) || process.cwd();
433
+ const command =
434
+ typeof rawArgs.CommandLine === "string"
435
+ ? rawArgs.CommandLine
436
+ : typeof rawArgs.command === "string"
437
+ ? rawArgs.command
438
+ : "";
439
+ const tool = canonicalHookTool(rawTool, cfg, AGY_TOOL_MAP);
440
+ const pathVal =
441
+ rawArgs.TargetFile ??
442
+ rawArgs.AbsolutePath ??
443
+ rawArgs.Path ??
444
+ rawArgs.DirectoryPath ??
445
+ rawArgs.SearchPath ??
446
+ rawArgs.SearchDirectory ??
447
+ rawArgs.path;
448
+ const input: Record<string, unknown> = {
449
+ ...rawArgs,
450
+ ...(command && typeof rawArgs.command !== "string" ? { command } : {}),
451
+ ...(typeof pathVal === "string" && typeof rawArgs.path !== "string" ? { path: pathVal } : {}),
452
+ };
453
+ const paths = resolveHookPaths(
454
+ [
455
+ rawArgs.Path,
456
+ rawArgs.TargetFile,
457
+ rawArgs.AbsolutePath,
458
+ rawArgs.DirectoryPath,
459
+ rawArgs.SearchPath,
460
+ rawArgs.SearchDirectory,
461
+ rawArgs.path,
462
+ rawArgs.file,
463
+ rawArgs.file_path,
464
+ ],
465
+ cwd,
466
+ );
467
+ const writes = isWriteHookTool(tool, cfg)
468
+ ? resolveHookPaths([rawArgs.TargetFile, rawArgs.AbsolutePath, rawArgs.Path, rawArgs.path, rawArgs.file, rawArgs.file_path], cwd)
469
+ : resolveHookPaths([rawArgs.TargetFile], cwd);
470
+ const agentId = hookAgentId(env, typeof payload.conversationId === "string" ? payload.conversationId : undefined, "agy");
471
+ const decision = checkTool({ tool, input, cwd, agent, agentId, calls: 0, paths, writes, command }, cfg);
472
+ return decision.allow
473
+ ? { code: 0, stdout: JSON.stringify({ decision: "allow" }) }
474
+ : { code: 0, stdout: JSON.stringify({ decision: "deny", reason: decision.reason }) };
475
+ }
476
+
477
+ if (event === "stop") {
478
+ if (!isHookActive(env) || !cfg) return { code: 0, stdout: "{}" };
479
+ const decision = checkStop({ agent: hookAgent(env), callsSinceStop: 0, idleStops: 0, ledgerText: "", liveAgents: liveHerdrSubagents(env, cfg) }, cfg);
480
+ return decision.allow
481
+ ? { code: 0, stdout: "{}" }
482
+ : { code: 0, stdout: JSON.stringify({ decision: "continue", reason: decision.reason }) };
483
+ }
484
+
485
+ return { code: 2, stdout: "" };
486
+ }
487
+
488
+ /**
489
+ * Installs or merges the `"neurastream"` `SessionStart`, `UserPromptSubmit`, `PreToolUse`, and
490
+ * `Stop` hooks pointing to `neurastream adapter hook agy <event>` inside `$HOME/.gemini/config/hooks.json`,
491
+ * upgrading legacy `neurastream guard ...` entries without touching existing top-level groups or live HOME.
492
+ *
493
+ * Args:
494
+ * home (string): Sandbox or caller HOME directory
495
+ *
496
+ * Returns:
497
+ * { hooksFile: string; changed: boolean }: Path written and whether hooks.json changed
498
+ */
499
+ export function installAgy(home: string): { hooksFile: string; changed: boolean } {
500
+ const file = agyHooksFile(home);
501
+ const rootDoc = readJsonConfigObject(file, "agy install");
502
+ const nsObj = rootDoc.neurastream === undefined ? {} : asObj(rootDoc.neurastream);
503
+ if (!nsObj) throw new Error(`agy install: ${file} "neurastream" field must be an object`);
504
+
505
+ const existingSessionStart = nsObj.SessionStart === undefined ? [] : nsObj.SessionStart;
506
+ if (!Array.isArray(existingSessionStart)) throw new Error(`agy install: ${file} "neurastream.SessionStart" must be an array`);
507
+ const existingPreInvocation = nsObj.PreInvocation === undefined ? [] : nsObj.PreInvocation;
508
+ if (!Array.isArray(existingPreInvocation)) throw new Error(`agy install: ${file} "neurastream.PreInvocation" must be an array`);
509
+ const existingPreTool = nsObj.PreToolUse === undefined ? [] : nsObj.PreToolUse;
510
+ if (!Array.isArray(existingPreTool)) throw new Error(`agy install: ${file} "neurastream.PreToolUse" must be an array`);
511
+ const existingStop = nsObj.Stop === undefined ? [] : nsObj.Stop;
512
+ if (!Array.isArray(existingStop)) throw new Error(`agy install: ${file} "neurastream.Stop" must be an array`);
513
+
514
+ // Clean up legacy unsupported UserPromptSubmit entry written by earlier installer versions.
515
+ let legacyUserPromptChanged = false;
516
+ const nextNsBase: Record<string, unknown> = { ...nsObj };
517
+ if (Array.isArray(nsObj.UserPromptSubmit)) {
518
+ const filtered = nsObj.UserPromptSubmit.filter((entry) => {
519
+ const obj = asObj(entry);
520
+ return !obj || obj.command !== AGY_USER_PROMPT_CMD;
521
+ });
522
+ if (filtered.length !== nsObj.UserPromptSubmit.length) {
523
+ legacyUserPromptChanged = true;
524
+ if (filtered.length > 0) nextNsBase.UserPromptSubmit = filtered;
525
+ else delete nextNsBase.UserPromptSubmit;
526
+ }
527
+ }
528
+
529
+ const sessionStartUp = upgradeHookEntries(existingSessionStart, { legacyCmds: [], newCmd: AGY_SESSION_START_CMD, grouped: false });
530
+ const preInvocationUp = upgradeHookEntries(existingPreInvocation, { legacyCmds: [], newCmd: AGY_USER_PROMPT_CMD, grouped: false });
531
+ const preToolUp = upgradeHookEntries(existingPreTool, {
532
+ legacyCmds: [LEGACY_PRE_TOOL_CMD],
533
+ newCmd: AGY_PRE_TOOL_CMD,
534
+ grouped: true,
535
+ matcher: "*",
536
+ });
537
+ const stopUp = upgradeHookEntries(existingStop, { legacyCmds: [LEGACY_STOP_CMD], newCmd: AGY_STOP_CMD, grouped: false });
538
+
539
+ if (!sessionStartUp.changed && !preInvocationUp.changed && !preToolUp.changed && !stopUp.changed && !legacyUserPromptChanged) {
540
+ return { hooksFile: file, changed: false };
541
+ }
542
+
543
+ writeJsonConfigObject(file, {
544
+ ...rootDoc,
545
+ neurastream: {
546
+ ...nextNsBase,
547
+ SessionStart: sessionStartUp.next,
548
+ PreInvocation: preInvocationUp.next,
549
+ PreToolUse: preToolUp.next,
550
+ Stop: stopUp.next,
551
+ },
552
+ });
553
+ return { hooksFile: file, changed: true };
554
+ }
555
+
556
+ /**
557
+ * Checks Antigravity (`agy`) binary availability on `PATH` and hook wiring under `home`.
558
+ *
559
+ * Args:
560
+ * home (string): Sandbox or caller HOME directory
561
+ * env (NodeJS.ProcessEnv): Environment whose `PATH` is inspected
562
+ *
563
+ * Returns:
564
+ * { ok: string[]; problems: string[] }: Diagnostic status lines
565
+ */
566
+ export function doctorAgy(home: string, env: NodeJS.ProcessEnv = process.env): { ok: string[]; problems: string[] } {
567
+ return runHookDoctorChecks({
568
+ name: "agy",
569
+ bin: "agy",
570
+ hooksFile: agyHooksFile(home),
571
+ env,
572
+ cmds: {
573
+ sessionStart: AGY_SESSION_START_CMD,
574
+ userPrompt: AGY_USER_PROMPT_CMD,
575
+ preTool: AGY_PRE_TOOL_CMD,
576
+ stop: AGY_STOP_CMD,
577
+ },
578
+ hasHook: hasAgyHook,
579
+ });
580
+ }
581
+
582
+ /**
583
+ * CLI handler for `neurastream adapter install agy`.
584
+ *
585
+ * Args:
586
+ * args (string[]): Arguments passed to `neurastream adapter`
587
+ *
588
+ * Returns:
589
+ * number: Process exit code
590
+ */
591
+ export function runAgyInstall(args: string[]): number {
592
+ return runAdapterInstallCli(args, "agy", installAgy);
593
+ }
594
+
595
+ /**
596
+ * CLI handler for `neurastream doctor` when `harness: agy`.
597
+ *
598
+ * Returns:
599
+ * number: 0 if healthy, 1 if problems were found
600
+ */
601
+ export function runAgyDoctor(): number {
602
+ return runAdapterDoctorCli("agy", doctorAgy);
603
+ }
604
+
605
+ /**
606
+ * Adds a subagent working directory to `<home>/.gemini/antigravity-cli/settings.json`'s
607
+ * `trustedWorkspaces` array when it falls inside `cfg.paths.work_roots`, preventing
608
+ * interactive workspace-trust dialog hangs during headless spawns.
609
+ *
610
+ * Args:
611
+ * cwd (string): Subagent working directory path
612
+ * cfg (Config): Loaded neurastream configuration
613
+ *
614
+ * Returns:
615
+ * void
616
+ */
617
+ export function ensureAgyTrustedWorkspace(cwd: string, cfg: Config): void {
618
+ const resolvedCwd = resolve(cwd);
619
+ if (!cfg.paths.work_roots.some((root) => isInsideWorkRoot(resolvedCwd, root))) return;
620
+
621
+ const file = join(cfg.paths.home, ".gemini", "antigravity-cli", "settings.json");
622
+ const doc = readJsonConfigObject(file, "agy prepareSubagentCwd");
623
+ const raw = doc.trustedWorkspaces;
624
+ if (raw !== undefined && !Array.isArray(raw)) {
625
+ throw new Error(`agy prepareSubagentCwd: ${file} "trustedWorkspaces" field must be an array`);
626
+ }
627
+ const list = (raw ?? []).filter((v): v is string => typeof v === "string");
628
+ if (list.some((p) => resolve(p) === resolvedCwd)) return;
629
+
630
+ writeJsonConfigObject(file, {
631
+ ...doc,
632
+ trustedWorkspaces: [...list, resolvedCwd],
633
+ });
634
+ }
635
+
636
+ /** Registered Antigravity (`agy`) HarnessAdapter. */
637
+ export const agyAdapter: HarnessAdapter = {
638
+ ...defaultAdapterStubs("agy"),
639
+ name: "agy",
640
+ bin: "agy",
641
+ runSource: agyRunSource,
642
+ ownerTurns: agyOwnerTurns,
643
+ scoreTraces: (cfg) => agyTraceSource(agySessionsRoot(cfg)),
644
+ traceRuns: agyTraceRuns,
645
+ traceSource: agyTraceSource,
646
+ traceStart(file: string): number | null {
647
+ const first = parseJsonlRecords(file)[0];
648
+ const sec = first ? parseIsoSec(first.created_at) : null;
649
+ return sec === null ? null : Math.round(sec * 1000);
650
+ },
651
+ launchMain: (args, cfg) => {
652
+ ensureAgyTrustedWorkspace(process.cwd(), cfg);
653
+ return spawnHarnessMain("agy", args, cfg);
654
+ },
655
+ install: runAgyInstall,
656
+ doctor: runAgyDoctor,
657
+ subagentLaunchSpec: (profile: SpawnProfile) =>
658
+ subagentLaunchSpecFrom("agy", profile, true, skipPermissionsArgs(profile.args)),
659
+ prepareSubagentCwd: ensureAgyTrustedWorkspace,
660
+ handleHook: handleAgyHook,
661
+ };