@pymodel/antigravity-mcp 0.0.0-stage → 0.1.0

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,898 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * delegate-skills · antigravity-mcp · relay.mjs
4
+ *
5
+ * Dispatch a self-contained brief to the Google Antigravity CLI (`agy --print`),
6
+ * capture the run, and write a structured result the orchestrating agent can
7
+ * review. The orchestrator runs this one command and reads the result JSON -
8
+ * every Antigravity-specific mechanic lives in here, which keeps the skill
9
+ * orchestrator-agnostic.
10
+ *
11
+ * Trust posture: relay.mjs itself makes no network calls, reads or writes no
12
+ * credentials, and sends no telemetry; it has no dependencies (Node built-ins
13
+ * only). It shells out only to `agy` and `git`. The `agy` process it launches
14
+ * does authenticate - exactly as you do at the terminal. Read this file before
15
+ * you run it.
16
+ *
17
+ * Note: `agy --print` takes the prompt as a command-line argument, so the brief is
18
+ * visible in the host process list (`ps`, /proc). On a shared machine keep secrets
19
+ * out of the brief - reference them by a path or env var the workspace can read.
20
+ *
21
+ * It deliberately does NOT commit. Committing is always the orchestrator's job -
22
+ * after it reviews the diff and re-runs the project gates.
23
+ *
24
+ * Headless --print cannot answer a permission prompt, so this helper passes
25
+ * --dangerously-skip-permissions by default. Use it only for an authorized task.
26
+ * Pass --no-dangerously-skip-permissions to let agy auto-deny instead. --read-only
27
+ * requests plan mode and watches the supplied roots; it does not prevent writes.
28
+ * Pass --sandbox to enable Antigravity's terminal sandbox. Do not treat --sandbox
29
+ * as an enforced boundary while the bypass is on; treat the run as full access.
30
+ *
31
+ * Usage:
32
+ * node relay.mjs --brief <file> [options]
33
+ * cat brief.txt | node relay.mjs [options]
34
+ *
35
+ * Options:
36
+ * --brief <file> Path to the brief. If omitted, the brief is read from stdin.
37
+ * --cd <dir> Working root for Antigravity (default: current directory).
38
+ * --lane <name> Fleet lane from delegate-setup config (dials apply; explicit flags win).
39
+ * --model <name> Listed CLI ID/label or family selector (default: agy's configured default).
40
+ * --effort <level> low, medium, high, xhigh, or max; only listed variants are usable.
41
+ * Requires --model. An exact ID/label fixes its effort; selectors
42
+ * such as gemini-neon@latest may select a listed effort sibling.
43
+ * --project <id> Use an existing Antigravity project.
44
+ * --new-project Force a fresh Antigravity project (default for fresh runs).
45
+ * --resume-last Continue the most recent Antigravity conversation; send only the delta brief.
46
+ * --conversation <id> Continue a specific Antigravity conversation; send only the delta brief.
47
+ * --sandbox Enable Antigravity's terminal sandbox for this run.
48
+ * --read-only Request plan mode (`--mode plan`) and watch all supplied roots.
49
+ * Advisory only: no sandbox or write enforcement is provided.
50
+ * A write is a violation; unknown snapshot coverage is incomplete.
51
+ * --dangerously-skip-permissions
52
+ * Auto-approve Antigravity tool permission requests (default: on).
53
+ * --no-dangerously-skip-permissions
54
+ * Let agy auto-deny permission requests instead.
55
+ * --print-timeout <dur> Timeout agy itself applies to print mode (default: 30m).
56
+ * --timeout <dur> Relay-side watchdog, h/m/s like 30m (default: --print-timeout
57
+ * plus a 60s grace). On expiry the agy process tree is killed and
58
+ * result.json gets status "timeout". Set it explicitly when agy
59
+ * may hang past its own print timeout.
60
+ * --add-dir <dir> Add an extra workspace directory. Repeatable.
61
+ * --out-dir <dir> Artifact directory (default: a fresh system temp directory).
62
+ * Reuse clears old captures and publishes a new running result;
63
+ * concurrent reuse is refused. Other files are left intact.
64
+ * -h, --help Show this help.
65
+ *
66
+ * Result: written to <out-dir>/result.json and summarized on stdout -
67
+ * runId, status, exitCode, agyVersion, projectId, conversationId, finalMessage,
68
+ * requested/resolved/observed model facts, finishedReason, touchedFilesByRoot,
69
+ * readOnlyViolation, snapshotCoverage, and paths to the captured artifacts.
70
+ *
71
+ * Exit codes: a pre-run usage error (bad/missing args, empty brief) exits 2
72
+ * before any run and writes no result file; a missing `agy` binary exits 127;
73
+ * otherwise a partial result, permission denial, read-only violation, or unknown
74
+ * read-only coverage exits nonzero even when Antigravity exits zero.
75
+ * If the child dies on a signal, the exit code is 128 plus the signal number and
76
+ * `result.json` records the signal.
77
+ * Once the brief validates, `result.json` is written on every outcome -
78
+ * running, completed, incomplete, read_only_violation, failed, timeout (the relay watchdog fired after explicit --timeout,
79
+ * or after --print-timeout plus 60s grace), aborted (the relay itself was killed
80
+ * and forwarded the kill to agy), or agy_unavailable. An orchestrator that polls for the
81
+ * file must therefore also treat a non-zero exit with no file as a usage error.
82
+ */
83
+
84
+ import { spawn, execFileSync, spawnSync } from "node:child_process";
85
+ import { randomUUID } from "node:crypto";
86
+ import {
87
+ mkdirSync,
88
+ writeFileSync,
89
+ renameSync,
90
+ readFileSync,
91
+ existsSync,
92
+ appendFileSync,
93
+ mkdtempSync,
94
+ realpathSync,
95
+ rmSync,
96
+ } from "node:fs";
97
+ import { join, resolve, basename, dirname } from "node:path";
98
+ import { fileURLToPath } from "node:url";
99
+ import { constants, tmpdir } from "node:os";
100
+ import { StringDecoder } from "node:string_decoder";
101
+ import { EFFORTS, selectModel } from "./model-selection.mjs";
102
+ import { workspaceRoots, workspaceSnapshot, touchedFilesByRoot } from "./workspace.mjs";
103
+
104
+ const DEFAULT_PRINT_TIMEOUT = "30m";
105
+ const MAX_TIMER_MS = 2_147_483_647;
106
+ const MAX_TIMER_DURATION = "596h31m23s";
107
+ const VERSION_PROBE_TIMEOUT_MS = 10_000;
108
+
109
+ const IMPLEMENTER_KEY = "agy";
110
+
111
+ function applyFleetLane(opts, flagged) {
112
+ if (!opts.lane) return;
113
+ const script = join(
114
+ dirname(fileURLToPath(import.meta.url)),
115
+ "../../delegate-setup/scripts/lane.mjs",
116
+ );
117
+ if (!existsSync(script)) {
118
+ fail("--lane requires the delegate-setup skill installed beside this relay");
119
+ }
120
+ const r = spawnSync(
121
+ process.execPath,
122
+ [script, "resolve", "--cwd", opts.cd, "--lane", opts.lane, "--implementer", IMPLEMENTER_KEY],
123
+ { encoding: "utf8", env: process.env },
124
+ );
125
+ if (r.error) fail(`lane resolve failed: ${r.error.message}`);
126
+ if (r.status !== 0) {
127
+ fail((r.stderr || "lane resolve failed").trim().replace(/^lane\.mjs:\s*/, ""));
128
+ }
129
+ let resolved;
130
+ try {
131
+ const lines = (r.stdout || "").trim().split("\n").filter(Boolean);
132
+ resolved = JSON.parse(lines[lines.length - 1]);
133
+ } catch {
134
+ fail("lane resolve returned invalid JSON");
135
+ }
136
+ opts.laneSource = resolved.source;
137
+ for (const [field, value] of Object.entries(resolved.dials || {})) {
138
+ if (flagged.has(field)) continue;
139
+ if (
140
+ field === "autonomy" &&
141
+ (flagged.has("autonomy") || flagged.has("sandbox") || flagged.has("readOnly"))
142
+ )
143
+ continue;
144
+ if (field === "agent" && (flagged.has("agent") || flagged.has("readOnly"))) continue;
145
+ if (field === "sandbox" && (flagged.has("sandbox") || flagged.has("readOnly"))) continue;
146
+ if (field === "permissionMode" && (flagged.has("permissionMode") || flagged.has("readOnly")))
147
+ continue;
148
+ if (field === "planOnly" && (flagged.has("planOnly") || flagged.has("readOnly"))) continue;
149
+ if (field === "readOnly" && flagged.has("readOnly")) continue;
150
+ if (field === "force" && flagged.has("force")) continue;
151
+ opts[field] = value;
152
+ }
153
+ }
154
+
155
+ function fail(message, code = 2) {
156
+ process.stderr.write(`relay: ${message}\n`);
157
+ process.exit(code);
158
+ }
159
+
160
+ function parseArgs(argv) {
161
+ const flagged = new Set();
162
+ const opts = {
163
+ lane: null,
164
+ laneSource: null,
165
+ brief: null,
166
+ cd: process.cwd(),
167
+ model: null,
168
+ effort: null,
169
+ project: null,
170
+ newProject: false,
171
+ resumeLast: false,
172
+ conversation: null,
173
+ sandbox: false,
174
+ readOnly: false,
175
+ dangerouslySkipPermissions: true,
176
+ printTimeout: DEFAULT_PRINT_TIMEOUT,
177
+ timeout: null,
178
+ addDirs: [],
179
+ outDir: null,
180
+ };
181
+ for (let i = 0; i < argv.length; i += 1) {
182
+ const arg = argv[i];
183
+ const next = () => {
184
+ const value = argv[i + 1];
185
+ if (!value?.trim() || value.startsWith("--")) fail(`${arg} requires a value`);
186
+ i += 1;
187
+ return value;
188
+ };
189
+ switch (arg) {
190
+ case "-h":
191
+ case "--help":
192
+ process.stdout.write(headerComment());
193
+ process.exit(0);
194
+ break;
195
+ case "--brief":
196
+ opts.brief = next();
197
+ break;
198
+ case "--cd":
199
+ opts.cd = resolve(next());
200
+ break;
201
+ case "--lane":
202
+ opts.lane = next();
203
+ break;
204
+ case "--model":
205
+ opts.model = next();
206
+ flagged.add("model");
207
+ break;
208
+ case "--effort":
209
+ opts.effort = next();
210
+ flagged.add("effort");
211
+ break;
212
+ case "--project":
213
+ opts.project = next();
214
+ break;
215
+ case "--new-project":
216
+ opts.newProject = true;
217
+ break;
218
+ case "--resume-last":
219
+ opts.resumeLast = true;
220
+ break;
221
+ case "--conversation":
222
+ opts.conversation = next();
223
+ break;
224
+ case "--sandbox":
225
+ opts.sandbox = true;
226
+ flagged.add("sandbox");
227
+ break;
228
+ case "--read-only":
229
+ opts.readOnly = true;
230
+ flagged.add("readOnly");
231
+ break;
232
+ case "--dangerously-skip-permissions":
233
+ opts.dangerouslySkipPermissions = true;
234
+ flagged.add("dangerouslySkipPermissions");
235
+ break;
236
+ case "--no-dangerously-skip-permissions":
237
+ opts.dangerouslySkipPermissions = false;
238
+ flagged.add("dangerouslySkipPermissions");
239
+ break;
240
+ case "--print-timeout":
241
+ opts.printTimeout = next();
242
+ break;
243
+ case "--timeout":
244
+ opts.timeout = next();
245
+ flagged.add("timeout");
246
+ break;
247
+ case "--add-dir":
248
+ opts.addDirs.push(next());
249
+ break;
250
+ case "--out-dir":
251
+ opts.outDir = resolve(next());
252
+ break;
253
+ default:
254
+ fail(`unknown option: ${arg}`);
255
+ }
256
+ }
257
+ applyFleetLane(opts, flagged);
258
+ if (opts.effort !== null && !EFFORTS.includes(opts.effort)) {
259
+ fail(
260
+ `invalid --effort "${opts.effort}" (expected: ${EFFORTS.join(", ")}; must be listed for the model)`,
261
+ );
262
+ }
263
+ if (opts.effort && !opts.model) fail("--effort requires --model; the inherited model is unknown");
264
+ if (opts.resumeLast && opts.conversation) {
265
+ fail("--resume-last and --conversation are mutually exclusive; pass only one");
266
+ }
267
+ // A malformed --timeout must fail loudly: parseDuration returns null for it, and a null
268
+ // delay makes setTimeout fire on the next tick - a silent instant "timeout", the worst
269
+ // failure mode a watchdog has. Zero is rejected for the same reason.
270
+ if (opts.timeout !== null) {
271
+ const milliseconds = parseDuration(opts.timeout);
272
+ if (milliseconds === null || milliseconds <= 0 || milliseconds > MAX_TIMER_MS) {
273
+ fail(
274
+ `--timeout "${opts.timeout}" must be an h/m/s duration from 1s through ${MAX_TIMER_DURATION}`,
275
+ );
276
+ }
277
+ }
278
+ const printTimeoutMs = parseDuration(opts.printTimeout);
279
+ if (printTimeoutMs === null || printTimeoutMs <= 0 || printTimeoutMs + 60_000 > MAX_TIMER_MS) {
280
+ fail(
281
+ `--print-timeout "${opts.printTimeout}" must be an h/m/s duration from 1s through 596h30m23s so its 60s grace fits the relay watchdog limit`,
282
+ );
283
+ }
284
+ if (opts.project && (opts.resumeLast || opts.conversation)) {
285
+ fail("--project cannot be combined with --resume-last or --conversation");
286
+ }
287
+ if (opts.project && opts.newProject) {
288
+ fail("--project and --new-project are mutually exclusive");
289
+ }
290
+ if (opts.newProject && (opts.resumeLast || opts.conversation)) {
291
+ fail("--new-project cannot be combined with --resume-last or --conversation");
292
+ }
293
+ // agy requires absolute --add-dir paths; resolve a relative one against --cd
294
+ // (not the relay's own cwd) - and only after the loop, since --add-dir may
295
+ // appear before --cd on the command line. resolve() passes absolutes through.
296
+ opts.addDirs = opts.addDirs.map((dir) => resolve(opts.cd, dir));
297
+ return opts;
298
+ }
299
+
300
+ function headerComment() {
301
+ // The leading block comment doubles as --help text.
302
+ const src = readFileSync(new URL(import.meta.url), "utf8");
303
+ const match = src.match(/\/\*\*([\s\S]*?)\*\//);
304
+ if (!match) return "relay.mjs - dispatch a brief to agy --print\n";
305
+ return `${match[1].replace(/^\s*\* ?/gm, "").trim()}\n`;
306
+ }
307
+
308
+ function readBrief(opts) {
309
+ if (opts.brief) {
310
+ if (!existsSync(opts.brief)) fail(`brief file not found: ${opts.brief}`);
311
+ return readFileSync(opts.brief, "utf8");
312
+ }
313
+ if (process.stdin.isTTY) {
314
+ fail("no --brief given and stdin is a TTY; pass --brief <file> or pipe the brief on stdin");
315
+ }
316
+ let stdin = "";
317
+ try {
318
+ stdin = readFileSync(0, "utf8");
319
+ } catch {
320
+ stdin = "";
321
+ }
322
+ return stdin;
323
+ }
324
+
325
+ function killChild(child, signal = "SIGTERM") {
326
+ if (!child || !child.pid) return;
327
+ if (process.platform === "win32") {
328
+ if (signal !== "SIGTERM") return;
329
+ try {
330
+ execFileSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], {
331
+ stdio: ["ignore", "ignore", "inherit"],
332
+ });
333
+ } catch {
334
+ // The process tree already exited.
335
+ }
336
+ return;
337
+ }
338
+ try {
339
+ process.kill(-child.pid, signal);
340
+ } catch {
341
+ try {
342
+ child.kill(signal);
343
+ } catch {
344
+ // The process group already exited.
345
+ }
346
+ }
347
+ }
348
+
349
+ function agyVersion(timeoutMs) {
350
+ try {
351
+ const out = execFileSync("agy", ["changelog"], {
352
+ encoding: "utf8",
353
+ timeout: Math.min(timeoutMs, VERSION_PROBE_TIMEOUT_MS),
354
+ killSignal: "SIGKILL",
355
+ }).trim();
356
+ const firstLine = out.split("\n").find(Boolean) || "";
357
+ const match = firstLine.match(/^([^:\s]+):/);
358
+ return match ? match[1] : firstLine || null;
359
+ } catch (err) {
360
+ // Only a missing binary means "unavailable"; any other changelog failure
361
+ // (permissions, a broken subcommand) must not masquerade as exit 127.
362
+ if (err && err.code === "ENOENT") return null;
363
+ if (err && err.code === "ETIMEDOUT") throw err;
364
+ return "unknown";
365
+ }
366
+ }
367
+
368
+ function parseDuration(duration) {
369
+ const match = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(duration);
370
+ if (!match || (!match[1] && !match[2] && !match[3])) return null;
371
+ try {
372
+ const seconds =
373
+ BigInt(match[1] || 0) * 3600n + BigInt(match[2] || 0) * 60n + BigInt(match[3] || 0);
374
+ const milliseconds = seconds * 1000n;
375
+ if (milliseconds <= 0n || milliseconds > BigInt(MAX_TIMER_MS)) return null;
376
+ return Number(milliseconds);
377
+ } catch {
378
+ return null;
379
+ }
380
+ }
381
+
382
+ function readOnlyVerdict(opts, before, after) {
383
+ if (!opts.readOnly || before.digest === null || after.digest === null) return null;
384
+ return before.digest !== after.digest;
385
+ }
386
+
387
+ function prepareRunDir(opts, brief) {
388
+ let outDir = opts.outDir;
389
+ if (!outDir) {
390
+ const parent = join(tmpdir(), "delegate-relay");
391
+ mkdirSync(parent, { recursive: true });
392
+ outDir = mkdtempSync(join(parent, `${basename(opts.cd) || "repo"}-`));
393
+ } else {
394
+ mkdirSync(outDir, { recursive: true });
395
+ }
396
+ outDir = realpathSync.native(outDir);
397
+ const lockPath = join(outDir, ".relay-lock");
398
+ try {
399
+ mkdirSync(lockPath);
400
+ } catch (error) {
401
+ if (error.code === "EEXIST")
402
+ fail(`out-dir is locked: ${outDir}; inspect its active run before reuse`);
403
+ throw error;
404
+ }
405
+ process.once("exit", () => rmSync(lockPath, { recursive: true, force: true }));
406
+ const run = {
407
+ runId: randomUUID(),
408
+ startedAt: new Date().toISOString(),
409
+ lockPath,
410
+ briefPath: join(outDir, "brief.txt"),
411
+ finalPath: join(outDir, "final.txt"),
412
+ stdoutPath: join(outDir, "stdout.txt"),
413
+ logPath: join(outDir, "agy.log"),
414
+ stderrPath: join(outDir, "stderr.txt"),
415
+ resultPath: join(outDir, "result.json"),
416
+ };
417
+ // Replace prior completion before any metadata probe or model dispatch. A
418
+ // watcher can associate every capture with this runId instead of stale output.
419
+ makeResultWriter(opts, null, run)({ status: "running", exitCode: null, finalMessage: "" });
420
+ for (const file of [run.briefPath, run.finalPath, run.stdoutPath, run.logPath, run.stderrPath]) {
421
+ rmSync(file, { force: true });
422
+ }
423
+ writeFileSync(run.briefPath, brief, "utf8");
424
+ writeFileSync(run.stderrPath, "", "utf8");
425
+ return run;
426
+ }
427
+
428
+ function buildArgv(opts, brief, run) {
429
+ const argv = [];
430
+ if (opts.project) {
431
+ argv.push("--project", opts.project);
432
+ } else if (opts.conversation) {
433
+ argv.push("--conversation", opts.conversation);
434
+ } else if (opts.resumeLast) {
435
+ argv.push("--continue");
436
+ } else {
437
+ argv.push("--new-project");
438
+ }
439
+
440
+ // Keep explicit roots on continuations too. Older conversation state does not
441
+ // replace the caller's current workspace request.
442
+ argv.push("--add-dir", opts.cd);
443
+ for (const dir of opts.addDirs) argv.push("--add-dir", dir);
444
+ if (opts.selection?.model) argv.push("--model", opts.selection.model);
445
+ // Listed effort variants are complete CLI IDs; never invent an ID or combine
446
+ // a fixed variant with an independent --effort that can contradict it.
447
+ argv.push("--output-format", "json");
448
+ if (opts.readOnly) argv.push("--mode", "plan");
449
+ if (opts.sandbox) argv.push("--sandbox");
450
+ if (opts.dangerouslySkipPermissions) argv.push("--dangerously-skip-permissions");
451
+ if (opts.printTimeout) argv.push("--print-timeout", opts.printTimeout);
452
+ argv.push("--log-file", run.logPath);
453
+ // Use the --print=<brief> form, not a separate ["--print", brief] pair: agy's flag
454
+ // parser intercepts a value that is exactly a bare flag (a brief consisting only of
455
+ // "--help" or "-h" prints usage instead of running). The = form always binds the value.
456
+ argv.push(`--print=${brief}`);
457
+ return argv;
458
+ }
459
+
460
+ function parseIdsFromLog(logPath) {
461
+ if (!existsSync(logPath)) return { projectId: null, conversationId: null };
462
+ const text = readFileSync(logPath, "utf8");
463
+ const projectMatches = [
464
+ /project: created project "[^"]*" \(id=([0-9a-f-]+)\)/i,
465
+ /Conversation using project ID: ([0-9a-f-]+)/i,
466
+ /Backend project ID updated dynamically to: ([0-9a-f-]+)/i,
467
+ ];
468
+ const conversationMatches = [
469
+ /Print mode: conversation=([0-9a-f-]+)/i,
470
+ /Created conversation ([0-9a-f-]+)/i,
471
+ ];
472
+ const firstMatch = (patterns) => {
473
+ for (const pattern of patterns) {
474
+ const match = text.match(pattern);
475
+ if (match) return match[1];
476
+ }
477
+ return null;
478
+ };
479
+ return {
480
+ projectId: firstMatch(projectMatches),
481
+ conversationId: firstMatch(conversationMatches),
482
+ };
483
+ }
484
+
485
+ function makeResultWriter(opts, version, run) {
486
+ return (extra) => {
487
+ const running = extra.status === "running";
488
+ const ids = running ? { projectId: null, conversationId: null } : parseIdsFromLog(run.logPath);
489
+ const result = {
490
+ schema: "delegate-relay.result.v2",
491
+ runId: run.runId,
492
+ lane: opts.lane,
493
+ laneSource: opts.laneSource,
494
+ tool: "agy",
495
+ workdir: opts.cd,
496
+ requestedModel: opts.model,
497
+ requestedEffort: opts.effort,
498
+ resolvedModel: opts.selection?.model ?? null,
499
+ resolvedEffort: opts.selection?.effort ?? null,
500
+ observedModel: null,
501
+ // Compatibility fields identify the dispatched selection, not model observation.
502
+ model: opts.selection?.model ?? null,
503
+ effort: opts.selection?.effort ?? null,
504
+ project: opts.project,
505
+ sandbox: opts.sandbox,
506
+ readOnly: opts.readOnly,
507
+ readOnlyEnforced: false,
508
+ readOnlyViolation: null,
509
+ snapshotCoverage: null,
510
+ dangerouslySkipPermissions: opts.dangerouslySkipPermissions,
511
+ resumeRequested: Boolean(opts.resumeLast || opts.conversation),
512
+ requestedConversationId: opts.conversation,
513
+ resumed: opts.resumeLast || opts.conversation ? null : false,
514
+ agyVersion: version,
515
+ projectId: ids.projectId,
516
+ conversationId: ids.conversationId,
517
+ startedAt: run.startedAt,
518
+ finishedAt: running ? null : new Date().toISOString(),
519
+ briefPath: run.briefPath,
520
+ finalPath: !running && existsSync(run.finalPath) ? run.finalPath : null,
521
+ stdoutPath: !running && existsSync(run.stdoutPath) ? run.stdoutPath : null,
522
+ logPath: !running && existsSync(run.logPath) ? run.logPath : null,
523
+ stderrPath: run.stderrPath,
524
+ touchedFiles: null,
525
+ touchedFilesByRoot: [],
526
+ ...extra,
527
+ };
528
+ if (opts.conversation && result.conversationId) {
529
+ result.resumed = opts.conversation === result.conversationId;
530
+ }
531
+ // Publish atomically so a polling orchestrator never reads a half-written file
532
+ // (same idiom as claude-delegate's writeJsonAtomic and qoder-delegate).
533
+ const temporary = join(run.lockPath, "result.tmp");
534
+ writeFileSync(temporary, `${JSON.stringify(result, null, 2)}\n`, "utf8");
535
+ renameSync(temporary, run.resultPath);
536
+ return result;
537
+ };
538
+ }
539
+
540
+ function reportUnavailable(writeResult, resultPath) {
541
+ const result = writeResult({
542
+ status: "agy_unavailable",
543
+ exitCode: 127,
544
+ signal: null,
545
+ finalMessage: "",
546
+ touchedFiles: null,
547
+ });
548
+ printSummary(result, resultPath);
549
+ process.stderr.write(
550
+ "relay: `agy` not found on PATH. Install the Antigravity CLI and complete first-launch setup.\n",
551
+ );
552
+ process.exit(127);
553
+ }
554
+
555
+ function reportVersionTimeout(writeResult, run, timeoutMs, error) {
556
+ const stderr = String(error?.stderr || "").trim();
557
+ if (stderr) writeFileSync(run.stderrPath, `${stderr}\n`, "utf8");
558
+ const message = `agy changelog version preflight timed out after ${Math.min(timeoutMs, VERSION_PROBE_TIMEOUT_MS)}ms; agy was not dispatched`;
559
+ const result = writeResult({
560
+ status: "timeout",
561
+ exitCode: 124,
562
+ signal: null,
563
+ finalMessage: "",
564
+ touchedFiles: null,
565
+ ...(stderr ? { stderrTail: stderr.split("\n").slice(-20) } : {}),
566
+ error: message,
567
+ });
568
+ printSummary(result, run.resultPath);
569
+ process.stderr.write(`relay: ${message}\n`);
570
+ process.exit(result.exitCode);
571
+ }
572
+
573
+ function parseTerminalEnvelope(stdout) {
574
+ const shape = (value) => {
575
+ if (!value || typeof value !== "object") return null;
576
+ const result = value.event === "result" ? value.result : value;
577
+ return result && typeof result.status === "string" ? result : null;
578
+ };
579
+ // Accept a pretty-printed object as well as the final compact JSON/NDJSON line.
580
+ try {
581
+ const value = shape(JSON.parse(stdout));
582
+ if (value) return value;
583
+ } catch {
584
+ /* A CLI startup diagnostic may precede the envelope. */
585
+ }
586
+ for (const line of stdout.split("\n").reverse()) {
587
+ try {
588
+ const value = shape(JSON.parse(line));
589
+ if (value) return value;
590
+ } catch {
591
+ /* Skip non-JSON diagnostic lines. */
592
+ }
593
+ }
594
+ return null;
595
+ }
596
+
597
+ function dispatchToAgy(opts, brief, run, writeResult, watchdogMs) {
598
+ const relayArtifacts = [
599
+ run.lockPath,
600
+ run.briefPath,
601
+ run.finalPath,
602
+ run.stdoutPath,
603
+ run.logPath,
604
+ run.stderrPath,
605
+ run.resultPath,
606
+ ];
607
+ const snapshot = () =>
608
+ opts.readOnly
609
+ ? workspaceSnapshot(opts.roots, relayArtifacts)
610
+ : { digest: null, roots: opts.roots, reason: "read-only snapshot not requested" };
611
+ const before = snapshot();
612
+ const child = spawn("agy", buildArgv(opts, brief, run), {
613
+ cwd: opts.cd,
614
+ env: { ...process.env, PWD: opts.cd },
615
+ stdio: ["ignore", "pipe", "pipe"],
616
+ detached: process.platform !== "win32",
617
+ });
618
+ let stdout = "";
619
+ let settled = false;
620
+ let termination = null;
621
+ let sigkillTimer = null;
622
+ const stdoutDecoder = new StringDecoder("utf8");
623
+ const watchdogTimer = setTimeout(() => stop("timeout", "SIGTERM"), watchdogMs);
624
+
625
+ function stop(kind, signal) {
626
+ if (settled) return;
627
+ if (termination) {
628
+ killChild(child, "SIGKILL");
629
+ return;
630
+ }
631
+ termination = { kind, signal };
632
+ clearTimeout(watchdogTimer);
633
+ // A descendant holding stdout open must not prevent the parent's close event.
634
+ child.once("exit", () => {
635
+ child.stdout.destroy();
636
+ child.stderr.destroy();
637
+ });
638
+ killChild(child);
639
+ sigkillTimer = setTimeout(() => {
640
+ killChild(child, "SIGKILL");
641
+ child.stdout.destroy();
642
+ child.stderr.destroy();
643
+ }, 2000);
644
+ }
645
+
646
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
647
+ process.on(signal, () => stop("aborted", signal));
648
+ }
649
+ child.stdout.on("data", (chunk) => {
650
+ stdout += stdoutDecoder.write(chunk);
651
+ });
652
+ child.stderr.on("data", (chunk) => {
653
+ process.stderr.write(chunk);
654
+ appendFileSync(run.stderrPath, chunk);
655
+ });
656
+
657
+ function finish(code, signal, spawnError = null) {
658
+ if (settled) return;
659
+ settled = true;
660
+ clearTimeout(watchdogTimer);
661
+ if (sigkillTimer) clearTimeout(sigkillTimer);
662
+ // Always sweep the group after an abort or timeout, even if the leader exited
663
+ // promptly. Its descendants may have ignored TERM and detached their pipes.
664
+ if (termination) killChild(child, "SIGKILL");
665
+ stdout += stdoutDecoder.end();
666
+ writeFileSync(run.stdoutPath, stdout, "utf8");
667
+ const envelope = parseTerminalEnvelope(stdout);
668
+ const finalMessage = envelope
669
+ ? typeof envelope.response === "string"
670
+ ? envelope.response.trim()
671
+ : ""
672
+ : stdout.trim();
673
+ if (finalMessage) writeFileSync(run.finalPath, finalMessage, "utf8");
674
+ const after = snapshot();
675
+ const readOnlyViolation = readOnlyVerdict(opts, before, after);
676
+ const snapshotCoverage = opts.readOnly
677
+ ? {
678
+ roots: opts.roots,
679
+ complete: before.digest !== null && after.digest !== null,
680
+ beforeError: before.reason,
681
+ afterError: after.reason,
682
+ excludes: "relay artifacts and Git administrative files; Git HEAD and index are included",
683
+ }
684
+ : null;
685
+ const touched = touchedFilesByRoot(opts.roots);
686
+ const finishedReason =
687
+ typeof envelope?.finished_reason === "string" ? envelope.finished_reason : null;
688
+ const deniedActions = Array.isArray(envelope?.denied_actions) ? envelope.denied_actions : [];
689
+ const conversationId =
690
+ typeof envelope?.conversation_id === "string" && envelope.conversation_id
691
+ ? envelope.conversation_id
692
+ : parseIdsFromLog(run.logPath).conversationId;
693
+ const observedModel =
694
+ typeof envelope?.model_id === "string"
695
+ ? envelope.model_id
696
+ : typeof envelope?.model === "string"
697
+ ? envelope.model
698
+ : null;
699
+ const stderr = readFileSync(run.stderrPath, "utf8");
700
+ const permissionDenied =
701
+ deniedActions.length > 0 ||
702
+ /no output produced\s+[—-]\s+a tool required.+permission.+auto-denied/is.test(stderr);
703
+ const resumeUnknown = opts.conversation && !conversationId;
704
+ const resumeMismatch =
705
+ opts.conversation && conversationId && opts.conversation !== conversationId;
706
+ let status = "completed";
707
+ let exitCode = code ?? (constants.signals[signal] ? 128 + constants.signals[signal] : 1);
708
+ let error = null;
709
+ if (termination?.kind === "aborted") {
710
+ status = "aborted";
711
+ signal = termination.signal;
712
+ exitCode = 128 + (constants.signals[signal] || 15);
713
+ error = `the relay was stopped by ${signal}; its agy process group was terminated; inspect the roots before re-dispatching`;
714
+ } else if (termination?.kind === "timeout" || finishedReason === "print_timeout") {
715
+ status = "timeout";
716
+ exitCode = 124;
717
+ error =
718
+ finishedReason === "print_timeout"
719
+ ? "agy reported print_timeout; the response is incomplete"
720
+ : `agy exceeded the relay watchdog (${opts.timeout || `${opts.printTimeout} plus 60s grace`})`;
721
+ } else if (finishedReason === "interrupted") {
722
+ status = "aborted";
723
+ exitCode = exitCode || 130;
724
+ error = "agy reported an interrupted turn; inspect the roots before resuming";
725
+ } else if (
726
+ spawnError ||
727
+ code !== 0 ||
728
+ envelope?.status === "ERROR" ||
729
+ finishedReason === "error"
730
+ ) {
731
+ status = "failed";
732
+ exitCode = exitCode || 1;
733
+ error = spawnError?.message || envelope?.error || "agy did not complete successfully";
734
+ } else if (readOnlyViolation === true) {
735
+ status = "read_only_violation";
736
+ exitCode = 1;
737
+ error =
738
+ "the watched roots changed during an advisory read-only run; inspect the changes before using its answer";
739
+ } else if (
740
+ !envelope ||
741
+ envelope.status !== "SUCCESS" ||
742
+ finishedReason ||
743
+ permissionDenied ||
744
+ !finalMessage ||
745
+ (opts.readOnly && !snapshotCoverage?.complete) ||
746
+ resumeUnknown ||
747
+ resumeMismatch
748
+ ) {
749
+ status = "incomplete";
750
+ exitCode = 1;
751
+ if (resumeMismatch)
752
+ error = `requested conversation ${opts.conversation} was not resumed; agy reported ${conversationId}`;
753
+ else if (resumeUnknown)
754
+ error = "agy did not report a conversation ID; the requested continuation is unverified";
755
+ else if (permissionDenied)
756
+ error = "agy denied one or more required actions; the task is incomplete";
757
+ else if (opts.readOnly && !snapshotCoverage?.complete)
758
+ error = `read-only coverage is unknown: ${before.reason || after.reason}`;
759
+ else if (finishedReason)
760
+ error = `agy ended with finished_reason=${finishedReason}; completion is unverified`;
761
+ else if (!envelope || envelope.status !== "SUCCESS")
762
+ error = "no successful structured CLI result was received; completion is unverified";
763
+ else error = "agy returned no final report; completion is unverified";
764
+ }
765
+ const result = writeResult({
766
+ status,
767
+ exitCode,
768
+ childExitCode: code,
769
+ signal: signal ?? null,
770
+ finalMessage,
771
+ cliStatus: envelope?.status ?? null,
772
+ finishedReason,
773
+ deniedActions,
774
+ observedModel,
775
+ conversationId,
776
+ usage: envelope?.usage ?? null,
777
+ modelUsage: envelope?.model_usage ?? null,
778
+ touchedFiles: touched[0]?.files ?? null,
779
+ touchedFilesByRoot: touched,
780
+ readOnlyViolation,
781
+ snapshotCoverage,
782
+ ...(error ? { error, stderrTail: stderr.trim().split("\n").filter(Boolean).slice(-20) } : {}),
783
+ });
784
+ printSummary(result, run.resultPath);
785
+ process.exit(result.exitCode);
786
+ }
787
+ child.once("error", (error) => finish(null, null, error));
788
+ child.once("close", (code, signal) => finish(code, signal));
789
+ }
790
+
791
+ function main() {
792
+ const opts = parseArgs(process.argv.slice(2));
793
+ const brief = readBrief(opts);
794
+ if (!brief.trim()) fail("empty brief (pass --brief <file> or pipe the brief on stdin)");
795
+
796
+ // agy --print takes the prompt as a CLI argument, so the brief rides argv. The OS caps a
797
+ // single argument (~128KB on Linux via MAX_ARG_STRLEN), so a huge brief would fail to spawn
798
+ // with an opaque E2BIG. Reject it early with a clear message instead of a generic failure.
799
+ const briefBytes = Buffer.byteLength(brief, "utf8");
800
+ const MAX_BRIEF_BYTES = 120 * 1024;
801
+ if (briefBytes > MAX_BRIEF_BYTES) {
802
+ fail(
803
+ `brief is ${Math.round(briefBytes / 1024)}KB; agy passes the prompt as a CLI argument, which the OS caps (~128KB on Linux). Trim it, or have agy read large context from the workspace instead of inlining it.`,
804
+ );
805
+ }
806
+
807
+ const printTimeoutMs = parseDuration(opts.printTimeout);
808
+ // An explicit --timeout wins over the default print-timeout-plus-grace: agy can hang well
809
+ // past its own print timeout, which is exactly the case the grace window cannot cover.
810
+ const watchdogMs = opts.timeout !== null ? parseDuration(opts.timeout) : printTimeoutMs + 60_000;
811
+ const run = prepareRunDir(opts, brief);
812
+ let version;
813
+ try {
814
+ version = agyVersion(watchdogMs);
815
+ } catch (error) {
816
+ const writeResult = makeResultWriter(opts, "unknown", run);
817
+ reportVersionTimeout(writeResult, run, watchdogMs, error);
818
+ return;
819
+ }
820
+ const writeResult = makeResultWriter(opts, version, run);
821
+
822
+ if (!version) {
823
+ reportUnavailable(writeResult, run.resultPath);
824
+ return;
825
+ }
826
+ try {
827
+ opts.selection = selectModel(opts, watchdogMs);
828
+ opts.roots = workspaceRoots([opts.cd, ...opts.addDirs]);
829
+ } catch (error) {
830
+ const result = writeResult({
831
+ status: "failed",
832
+ exitCode: 1,
833
+ signal: null,
834
+ finalMessage: "",
835
+ error: `preflight failed; no task was dispatched: ${error.message}`,
836
+ });
837
+ printSummary(result, run.resultPath);
838
+ process.exit(1);
839
+ }
840
+ dispatchToAgy(opts, brief, run, writeResult, watchdogMs);
841
+ }
842
+
843
+ function printSummary(result, resultPath) {
844
+ const lines = [];
845
+ lines.push("");
846
+ lines.push(
847
+ `relay: ${result.status} (exit ${result.exitCode}${result.signal ? `, killed by ${result.signal}` : ""}) · agy ${result.agyVersion ?? "?"}`,
848
+ );
849
+ if (result.error) lines.push(`error: ${result.error}`);
850
+ if (result.readOnly) {
851
+ lines.push("read-only: watched, not enforced by this relay");
852
+ if (result.readOnlyViolation === true) lines.push("READ-ONLY VIOLATION: watched roots changed");
853
+ else if (result.readOnlyViolation === null) lines.push("read-only coverage: unknown");
854
+ }
855
+ lines.push(
856
+ `model: requested=${result.requestedModel ?? "CLI default"}; resolved=${result.resolvedModel ?? "unknown"}; observed=${result.observedModel ?? "unknown"}`,
857
+ );
858
+ if (result.signal === "SIGKILL" && result.status === "failed")
859
+ lines.push(
860
+ "hint: the host killed the process (commonly the OOM killer or a supervisor timeout) — this is not an agy error; check host memory and re-dispatch, or split the task into smaller briefs.",
861
+ );
862
+ if (result.signal === "SIGTERM" && result.status === "failed")
863
+ lines.push(
864
+ 'hint: something outside the relay terminated agy (a supervisor, the session ending, or a manual kill) — when the relay itself does the killing it reports status "timeout" or "aborted" instead; inspect the working tree before re-dispatching.',
865
+ );
866
+ if (result.resumed) lines.push("mode: resumed an existing conversation");
867
+ else if (result.resumeRequested)
868
+ lines.push(`mode: continuation ${result.resumed === false ? "not resumed" : "unverified"}`);
869
+ if (result.projectId) lines.push(`project id: ${result.projectId}`);
870
+ if (result.conversationId)
871
+ lines.push(
872
+ `conversation id (resume with: --conversation ${result.conversationId}): ${result.conversationId}`,
873
+ );
874
+ const touched = result.touchedFiles;
875
+ if (touched === null) {
876
+ lines.push("touched files: git unavailable - inspect the working tree directly");
877
+ } else {
878
+ lines.push(`touched files: ${touched.length}`);
879
+ for (const file of touched.slice(0, 40)) lines.push(` ${file}`);
880
+ if (touched.length > 40) lines.push(` ... and ${touched.length - 40} more`);
881
+ }
882
+ if (result.stderrTail && result.stderrTail.length) {
883
+ lines.push("last stderr:");
884
+ for (const line of result.stderrTail.slice(-8)) lines.push(` ${line}`);
885
+ }
886
+ lines.push("");
887
+ lines.push("--- agy final report ---");
888
+ lines.push(result.finalMessage || "(no final message captured)");
889
+ lines.push("--- end report ---");
890
+ lines.push("");
891
+ lines.push(`result: ${resultPath}`);
892
+ lines.push(
893
+ "relay does not commit. Review the diff, re-run the project gates yourself, then commit from the orchestrator.",
894
+ );
895
+ process.stdout.write(`${lines.join("\n")}\n`);
896
+ }
897
+
898
+ main();