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