@aibridge/driver-agy 0.9.1 → 0.9.3

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Driver for the Antigravity (`agy`) CLI. It builds print-mode commands, checks
4
4
  availability, runs delegated tasks, captures answer files, and reads quota
5
- windows.
5
+ windows. Delegation `run()` uses `--output-format stream-json` when agy is ≥ 1.2.3; image generation does not.
6
6
 
7
7
  ```ts
8
8
  import { probe, run, fetchAgyQuota } from '@aibridge/driver-agy';
package/dist/index.d.mts CHANGED
@@ -20,6 +20,8 @@ interface AgyPrintArgs {
20
20
  * Assemble the `agy -p …` argv.
21
21
  */
22
22
  declare function buildAgyPrintArgs(prompt: string, opts: AgyPrintArgs): string[];
23
+ declare const MIN_AGY_STREAM_JSON: readonly [number, number, number];
24
+ declare function agySupportsStreamJson(versionLine: string | null): boolean;
23
25
  //#endregion
24
26
  //#region src/agyQuota.d.ts
25
27
  /**
@@ -27,11 +29,15 @@ declare function buildAgyPrintArgs(prompt: string, opts: AgyPrintArgs): string[]
27
29
  * token — no separate login. Mechanism learned from
28
30
  * github.com/skainguyen1412/antigravity-usage (reimplemented, not vendored):
29
31
  *
30
- * 1. Read `~/.gemini/antigravity-cli/antigravity-oauth-token`
31
- * ({ token: { access_token, refresh_token, expiry } }) — agy refreshes
32
- * this file itself whenever it runs. If expired, refresh in-memory via
33
- * Google's token endpoint with Antigravity's installed-app client
34
- * (public by design for installed apps); we NEVER write agy's file.
32
+ * 1. Read agy's credential — the OS keyring entry (go-keyring, service
33
+ * `gemini`, account `antigravity`) first, then the fallback file
34
+ * `~/.gemini/antigravity-cli/antigravity-oauth-token`. Both hold
35
+ * { token: { access_token, refresh_token, expiry }, auth_method }; agy
36
+ * only writes the file when the keyring is bypassed or unreachable, so
37
+ * the file goes stale once the keyring works. If expired, refresh
38
+ * in-memory via Google's token endpoint with Antigravity's installed-app
39
+ * client (public by design for installed apps); we NEVER write agy's
40
+ * store.
35
41
  * 2. POST cloudcode-pa.googleapis.com/v1internal:loadCodeAssist
36
42
  * (metadata ideType ANTIGRAVITY / pluginType GEMINI) → project id.
37
43
  * 3. POST /v1internal:fetchAvailableModels { project } — the
@@ -139,6 +145,7 @@ interface DelegationTask {
139
145
  readonly onStdout?: (chunk: string) => void;
140
146
  readonly onStderr?: (chunk: string) => void;
141
147
  readonly onSpawn?: (pid: number) => void;
148
+ readonly onActivity?: () => void;
142
149
  }
143
150
  type DelegationResult = {
144
151
  readonly ok: true;
@@ -152,4 +159,4 @@ type DelegationResult = {
152
159
  };
153
160
  declare function run(task: DelegationTask, exec?: typeof runCaptured): Promise<DelegationResult>;
154
161
  //#endregion
155
- export { AGY_CANONICAL_TO_NATIVE, type AgyModelQuota, type AgyPrintArgs, type AgyQuotaBucket, type AgyQuotaGroup, type AgyQuotaSnapshot, type Availability, type DelegationResult, type DelegationTask, type ImageGenRequest, type ImageResult, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, generateImage, parseModels, parseQuotaGroups, probe, run };
162
+ export { AGY_CANONICAL_TO_NATIVE, type AgyModelQuota, type AgyPrintArgs, type AgyQuotaBucket, type AgyQuotaGroup, type AgyQuotaSnapshot, type Availability, type DelegationResult, type DelegationTask, type ImageGenRequest, type ImageResult, MIN_AGY_STREAM_JSON, agySupportsStreamJson, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, generateImage, parseModels, parseQuotaGroups, probe, run };
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
+ import { AuthExpiredError, isNotFound, probeVersion, runCaptured, semverGte, stripAnsi } from "@aibridge/proc";
1
2
  import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
2
3
  import { homedir, tmpdir } from "node:os";
3
4
  import { join } from "node:path";
4
- import { AuthExpiredError, isNotFound, runCaptured, stripAnsi } from "@aibridge/proc";
5
5
  //#region src/agy.ts
6
6
  /**
7
7
  * Assemble the `agy -p …` argv.
@@ -19,6 +19,22 @@ function buildAgyPrintArgs(prompt, opts) {
19
19
  for (const dir of opts.addDirs ?? []) args.push("--add-dir", dir);
20
20
  return args;
21
21
  }
22
+ const MIN_AGY_STREAM_JSON = [
23
+ 1,
24
+ 2,
25
+ 3
26
+ ];
27
+ const STRICT_AGY_VERSION_RE = /^(?:agy(?: version)?\s+)?(\d+)\.(\d+)\.(\d+)(?:\s.*)?$/i;
28
+ function agySupportsStreamJson(versionLine) {
29
+ if (!versionLine) return false;
30
+ const m = versionLine.trim().match(STRICT_AGY_VERSION_RE);
31
+ if (!m) return false;
32
+ return semverGte([
33
+ Number(m[1]),
34
+ Number(m[2]),
35
+ Number(m[3])
36
+ ], MIN_AGY_STREAM_JSON);
37
+ }
22
38
  //#endregion
23
39
  //#region src/registry.ts
24
40
  const AGY_CANONICAL_TO_NATIVE = {
@@ -36,11 +52,15 @@ const AGY_CANONICAL_TO_NATIVE = {
36
52
  * token — no separate login. Mechanism learned from
37
53
  * github.com/skainguyen1412/antigravity-usage (reimplemented, not vendored):
38
54
  *
39
- * 1. Read `~/.gemini/antigravity-cli/antigravity-oauth-token`
40
- * ({ token: { access_token, refresh_token, expiry } }) — agy refreshes
41
- * this file itself whenever it runs. If expired, refresh in-memory via
42
- * Google's token endpoint with Antigravity's installed-app client
43
- * (public by design for installed apps); we NEVER write agy's file.
55
+ * 1. Read agy's credential — the OS keyring entry (go-keyring, service
56
+ * `gemini`, account `antigravity`) first, then the fallback file
57
+ * `~/.gemini/antigravity-cli/antigravity-oauth-token`. Both hold
58
+ * { token: { access_token, refresh_token, expiry }, auth_method }; agy
59
+ * only writes the file when the keyring is bypassed or unreachable, so
60
+ * the file goes stale once the keyring works. If expired, refresh
61
+ * in-memory via Google's token endpoint with Antigravity's installed-app
62
+ * client (public by design for installed apps); we NEVER write agy's
63
+ * store.
44
64
  * 2. POST cloudcode-pa.googleapis.com/v1internal:loadCodeAssist
45
65
  * (metadata ideType ANTIGRAVITY / pluginType GEMINI) → project id.
46
66
  * 3. POST /v1internal:fetchAvailableModels { project } — the
@@ -70,9 +90,53 @@ function parseQuotaGroups(groups) {
70
90
  function agyTokenPath() {
71
91
  return process.env.AGY_OAUTH_TOKEN_PATH ?? join(homedir(), ".gemini", "antigravity-cli", "antigravity-oauth-token");
72
92
  }
93
+ const KEYRING_B64_PREFIX = "go-keyring-base64:";
94
+ /**
95
+ * go-keyring base64-wraps the secret on macOS (`go-keyring-base64:` prefix)
96
+ * and stores it raw on Linux. Returns undefined unless the result parses as
97
+ * the token JSON, so a malformed keyring entry falls through to the file.
98
+ */
99
+ function decodeKeyringSecret(raw) {
100
+ const s = raw.trim();
101
+ const json = s.startsWith(KEYRING_B64_PREFIX) ? Buffer.from(s.slice(18), "base64").toString("utf8") : s;
102
+ try {
103
+ const parsed = JSON.parse(json);
104
+ return parsed && typeof parsed === "object" ? parsed : void 0;
105
+ } catch {
106
+ return;
107
+ }
108
+ }
109
+ async function readKeyringCredential() {
110
+ const cmd = {
111
+ darwin: ["security", [
112
+ "find-generic-password",
113
+ "-s",
114
+ "gemini",
115
+ "-a",
116
+ "antigravity",
117
+ "-w"
118
+ ]],
119
+ linux: ["secret-tool", [
120
+ "lookup",
121
+ "service",
122
+ "gemini",
123
+ "username",
124
+ "antigravity"
125
+ ]]
126
+ }[process.platform];
127
+ if (!cmd) return void 0;
128
+ const res = await runCaptured(cmd[0], cmd[1], { timeoutMs: 5e3 }).catch(() => void 0);
129
+ return res?.code === 0 ? decodeKeyringSecret(res.stdout) : void 0;
130
+ }
131
+ async function readAgyCredential() {
132
+ if (!process.env.AGY_OAUTH_TOKEN_PATH) {
133
+ const fromKeyring = await readKeyringCredential();
134
+ if (fromKeyring) return fromKeyring;
135
+ }
136
+ return JSON.parse(readFileSync(agyTokenPath(), "utf8"));
137
+ }
73
138
  async function getAccessToken() {
74
- const raw = readFileSync(agyTokenPath(), "utf8");
75
- const parsed = JSON.parse(raw);
139
+ const parsed = await readAgyCredential();
76
140
  const access = parsed.token?.access_token;
77
141
  const refresh = parsed.token?.refresh_token;
78
142
  const expiry = parsed.token?.expiry;
@@ -199,7 +263,7 @@ async function generateImage(req, exec = runCaptured) {
199
263
  let instruction;
200
264
  if (req.imagePaths.length > 0) {
201
265
  const refs = req.imagePaths.map((p) => JSON.stringify(p)).join(", ");
202
- instruction = `Call the generate_image tool once with ImageName="aibridge-render", Prompt=${JSON.stringify(req.prompt)}, and ImagePaths=[${refs}]. Change only what the instruction asks, using the references for subject/identity.${req.aspectRatio ? ` Pass AspectRatio='${req.aspectRatio}' only if applicable.` : ""} After the tool returns, print ONLY the absolute filesystem path of the saved image on a single line. No other text.`;
266
+ instruction = `Call the generate_image tool once with ImageName="aibridge-render", Prompt=${JSON.stringify(req.prompt)}, and ImagePaths=[${refs}]. Change only what the instruction asks, using the references for subject/identity.${req.aspectRatio ? ` Pass AspectRatio='${req.aspectRatio}'.` : ""} After the tool returns, print ONLY the absolute filesystem path of the saved image on a single line. No other text.`;
203
267
  } else instruction = `Call the generate_image tool once with ImageName="aibridge-render" and Prompt=${JSON.stringify(req.prompt)}.${req.aspectRatio ? ` Pass AspectRatio='${req.aspectRatio}'.` : ""} After the tool returns, print ONLY the absolute filesystem path of the saved image on a single line. No other text.`;
204
268
  const beforePaths = brainImagePaths();
205
269
  let result;
@@ -314,9 +378,187 @@ function mtime(path) {
314
378
  //#endregion
315
379
  //#region src/run.ts
316
380
  const NOISE_RE = /^Shell cwd was reset[^\n]*$/gm;
381
+ const MESSAGE_STREAM_ARGS = ["--output-format", "stream-json"];
382
+ const RAW_FALLBACK_MAX_CHARS = 8192;
383
+ const READABLE_LOG_FLUSH_CHARS = 4096;
384
+ const AGY_PRINT_TIMEOUT_RE = /^\[agy\] print timeout after \S+ with turn in progress; returning partial output\s*$/i;
385
+ const TOOL_SUMMARY_MAX = 200;
317
386
  function clean(s) {
318
387
  return stripAnsi(s).replace(NOISE_RE, "").trim();
319
388
  }
389
+ function classifyLine(line) {
390
+ const trimmed = line.trim();
391
+ if (trimmed.length === 0) return { kind: "blank" };
392
+ if (!trimmed.startsWith("{")) return {
393
+ kind: "raw",
394
+ line
395
+ };
396
+ let parsed;
397
+ try {
398
+ parsed = JSON.parse(trimmed);
399
+ } catch {
400
+ return {
401
+ kind: "raw",
402
+ line
403
+ };
404
+ }
405
+ if (typeof parsed !== "object" || parsed === null || !("event" in parsed) || typeof parsed.event !== "string") return {
406
+ kind: "raw",
407
+ line
408
+ };
409
+ const event = parsed.event;
410
+ if (event === "init") return { kind: "init" };
411
+ if (event === "step_update") {
412
+ const stepUpdate = parsed.step_update;
413
+ if (typeof stepUpdate === "object" && stepUpdate !== null) {
414
+ const su = stepUpdate;
415
+ return {
416
+ kind: "step",
417
+ state: typeof su.state === "string" ? su.state : void 0,
418
+ stepType: typeof su.step_type === "string" ? su.step_type : void 0,
419
+ textDelta: typeof su.text_delta === "string" ? su.text_delta : void 0,
420
+ toolName: typeof su.tool_name === "string" ? su.tool_name : void 0,
421
+ toolInfo: su.tool_info
422
+ };
423
+ }
424
+ return {
425
+ kind: "step",
426
+ state: void 0,
427
+ stepType: void 0,
428
+ textDelta: void 0,
429
+ toolName: void 0,
430
+ toolInfo: void 0
431
+ };
432
+ }
433
+ if (event === "result") {
434
+ const res = parsed.result;
435
+ if (typeof res === "object" && res !== null) {
436
+ const r = res;
437
+ return {
438
+ kind: "result",
439
+ status: typeof r.status === "string" ? r.status : void 0,
440
+ response: typeof r.response === "string" ? r.response : void 0,
441
+ error: typeof r.error === "string" ? r.error : void 0
442
+ };
443
+ }
444
+ return {
445
+ kind: "result",
446
+ status: void 0,
447
+ response: void 0,
448
+ error: void 0
449
+ };
450
+ }
451
+ return { kind: "frame" };
452
+ }
453
+ function formatToolSummary(toolInfo) {
454
+ if (typeof toolInfo !== "object" || toolInfo === null) return null;
455
+ const obj = toolInfo;
456
+ const raw = typeof obj.summary === "string" ? obj.summary : typeof obj.message === "string" ? obj.message : null;
457
+ if (!raw) return null;
458
+ const firstLine = raw.split("\n")[0]?.trim();
459
+ if (!firstLine) return null;
460
+ return firstLine.slice(0, TOOL_SUMMARY_MAX);
461
+ }
462
+ function logForwarder(onStdout, onActivity) {
463
+ let pending = "";
464
+ let readableBuffer = "";
465
+ let loggedAgentText = "";
466
+ let sawProtocol = false;
467
+ let resultStatus = null;
468
+ let resultResponse = null;
469
+ let resultError = null;
470
+ let rawFallback = "";
471
+ let rawTruncated = false;
472
+ const flushReadable = () => {
473
+ if (readableBuffer.length === 0) return;
474
+ const toSend = readableBuffer.endsWith("\n") ? readableBuffer : `${readableBuffer}\n`;
475
+ readableBuffer = "";
476
+ onStdout?.(toSend);
477
+ };
478
+ const emit = (rawLine) => {
479
+ const classified = classifyLine(stripAnsi(rawLine));
480
+ if (classified.kind === "blank") return;
481
+ if (classified.kind === "init" || classified.kind === "frame") {
482
+ sawProtocol = true;
483
+ return;
484
+ }
485
+ if (classified.kind === "step") {
486
+ sawProtocol = true;
487
+ if (classified.stepType === "agent_response" && classified.textDelta) {
488
+ loggedAgentText += classified.textDelta;
489
+ readableBuffer += classified.textDelta;
490
+ if (readableBuffer.includes("\n") || readableBuffer.length >= READABLE_LOG_FLUSH_CHARS) flushReadable();
491
+ }
492
+ if (classified.state === "DONE" && classified.stepType === "agent_response") {
493
+ if (readableBuffer.length > 0 && !readableBuffer.endsWith("\n")) readableBuffer += "\n";
494
+ flushReadable();
495
+ }
496
+ if (classified.toolName) {
497
+ flushReadable();
498
+ if (classified.state === "ACTIVE") onStdout?.(`tool ${classified.toolName}\n`);
499
+ else if (classified.state === "DONE") {
500
+ const summary = formatToolSummary(classified.toolInfo);
501
+ if (summary) onStdout?.(`tool ${classified.toolName} done: ${summary}\n`);
502
+ else onStdout?.(`tool ${classified.toolName} done\n`);
503
+ }
504
+ }
505
+ return;
506
+ }
507
+ if (classified.kind === "result") {
508
+ sawProtocol = true;
509
+ resultStatus = classified.status ?? null;
510
+ resultResponse = classified.response ?? null;
511
+ resultError = classified.error ?? null;
512
+ flushReadable();
513
+ if (classified.response && classified.response.length > 0) {
514
+ const cleanResp = clean(classified.response);
515
+ const cleanLogged = clean(loggedAgentText);
516
+ if (cleanResp.length > 0 && !cleanLogged.endsWith(cleanResp)) {
517
+ readableBuffer += classified.response;
518
+ flushReadable();
519
+ }
520
+ }
521
+ return;
522
+ }
523
+ if (classified.kind === "raw") {
524
+ flushReadable();
525
+ onStdout?.(`${rawLine}\n`);
526
+ if (!sawProtocol) {
527
+ if (!rawTruncated) {
528
+ const candidate = `${rawLine}\n`;
529
+ if (rawFallback.length + candidate.length > RAW_FALLBACK_MAX_CHARS) rawTruncated = true;
530
+ else rawFallback += candidate;
531
+ }
532
+ }
533
+ }
534
+ };
535
+ return {
536
+ onChunk: (chunk) => {
537
+ onActivity?.();
538
+ pending += chunk;
539
+ for (let nl = pending.indexOf("\n"); nl !== -1; nl = pending.indexOf("\n")) {
540
+ emit(pending.slice(0, nl));
541
+ pending = pending.slice(nl + 1);
542
+ }
543
+ },
544
+ flush: () => {
545
+ if (pending.length > 0) {
546
+ const line = pending;
547
+ pending = "";
548
+ emit(line);
549
+ }
550
+ flushReadable();
551
+ },
552
+ snapshot: () => ({
553
+ sawProtocol,
554
+ text: resultResponse && resultResponse.length > 0 ? resultResponse : null,
555
+ resultStatus,
556
+ resultError,
557
+ rawFallback,
558
+ rawTruncated
559
+ })
560
+ };
561
+ }
320
562
  async function run(task, exec = runCaptured) {
321
563
  let tempDir;
322
564
  let answerPath;
@@ -328,19 +570,37 @@ async function run(task, exec = runCaptured) {
328
570
  taskPrompt = `${task.prompt}\n\nYou are working in the repository rooted at ${task.cwd}; make ALL file edits there (any relative paths in the task are relative to that root). When the task is complete, write ONLY your final answer (the exact text you would otherwise print as your response, with no narration of your steps) to the file ${answerPath} — nothing else in that file. This is how your answer is captured; do not mention the file in the answer.`;
329
571
  addDirs.push(task.cwd, tempDir);
330
572
  }
331
- const args = buildAgyPrintArgs(taskPrompt, {
332
- model: task.backendModel,
333
- printTimeoutSec: task.timeoutSec,
334
- skipPermissions: task.tools,
335
- addDirs: addDirs.length > 0 ? addDirs : void 0
336
- });
337
573
  try {
338
574
  let result;
575
+ let useStreamJson = false;
576
+ let forwarder;
339
577
  try {
340
- result = await exec("agy", args, {
578
+ const version = await probeVersion("agy", exec);
579
+ useStreamJson = agySupportsStreamJson(version);
580
+ if (!useStreamJson) task.onStderr?.(`aibridge: agy version ${version ?? "unavailable"} does not support stream-json (requires >= 1.2.3); using text compatibility mode.\n`);
581
+ const args = [...buildAgyPrintArgs(taskPrompt, {
582
+ model: task.backendModel,
583
+ printTimeoutSec: task.timeoutSec,
584
+ skipPermissions: task.tools,
585
+ addDirs: addDirs.length > 0 ? addDirs : void 0
586
+ }), ...useStreamJson ? MESSAGE_STREAM_ARGS : []];
587
+ if (useStreamJson) {
588
+ forwarder = logForwarder(task.onStdout, task.onActivity);
589
+ result = await exec("agy", args, {
590
+ cwd: task.cwd,
591
+ timeoutMs: (task.timeoutSec + 20) * 1e3,
592
+ captureStdout: false,
593
+ onStdout: forwarder.onChunk,
594
+ onStderr: task.onStderr,
595
+ onSpawn: task.onSpawn
596
+ });
597
+ } else result = await exec("agy", args, {
341
598
  cwd: task.cwd,
342
599
  timeoutMs: (task.timeoutSec + 20) * 1e3,
343
- onStdout: task.onStdout,
600
+ onStdout: (chunk) => {
601
+ task.onActivity?.();
602
+ task.onStdout?.(chunk);
603
+ },
344
604
  onStderr: task.onStderr,
345
605
  onSpawn: task.onSpawn
346
606
  });
@@ -358,27 +618,52 @@ async function run(task, exec = runCaptured) {
358
618
  exitCode: null
359
619
  };
360
620
  }
621
+ forwarder?.flush();
361
622
  if (result.timedOut) return {
362
623
  ok: false,
363
624
  kind: "timeout",
364
625
  message: `aibridge: agy timed out after ~${task.timeoutSec + 20}s; raise --timeout.`,
365
626
  exitCode: result.code
366
627
  };
367
- let response = "";
628
+ let fileAnswer = "";
368
629
  if (answerPath && existsSync(answerPath)) {
369
- response = clean(readFileSync(answerPath, "utf8"));
370
- if (response.length > 0) task.onStdout?.(`\n--- final answer ---\n${response}\n`);
630
+ fileAnswer = clean(readFileSync(answerPath, "utf8"));
631
+ if (fileAnswer.length > 0) task.onStdout?.(`\n--- final answer ---\n${fileAnswer}\n`);
632
+ }
633
+ const snap = useStreamJson && forwarder ? forwarder.snapshot() : void 0;
634
+ let resolvedAnswer = "";
635
+ const sawProtocol = snap?.sawProtocol ?? false;
636
+ const rawTruncated = snap?.rawTruncated ?? false;
637
+ const resultError = snap?.resultError ?? null;
638
+ const resultStatus = snap?.resultStatus ?? null;
639
+ if (fileAnswer.length > 0) resolvedAnswer = fileAnswer;
640
+ else {
641
+ const stderrLines = stripAnsi(result.stderr).split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
642
+ const lastStderrLine = stderrLines[stderrLines.length - 1] ?? "";
643
+ if (result.code === 0 && AGY_PRINT_TIMEOUT_RE.test(lastStderrLine)) return {
644
+ ok: false,
645
+ kind: "timeout",
646
+ message: `aibridge: agy timed out after ~${task.timeoutSec}s; raise --timeout.`,
647
+ exitCode: result.code
648
+ };
649
+ if (snap) resolvedAnswer = clean(snap.text ?? (snap.sawProtocol || snap.rawTruncated ? "" : snap.rawFallback));
650
+ else resolvedAnswer = clean(result.stdout);
371
651
  }
372
- if (response.length === 0) response = clean(result.stdout);
373
- if (result.code !== 0 || response.length === 0) return {
652
+ if (useStreamJson && !sawProtocol && rawTruncated && resolvedAnswer.length === 0) return {
653
+ ok: false,
654
+ kind: "no-answer",
655
+ message: `aibridge: agy returned more than ${RAW_FALLBACK_MAX_CHARS} characters without a recognized stream protocol; see the run log.`,
656
+ exitCode: result.code
657
+ };
658
+ if (resultStatus === "ERROR" || result.code !== 0 || resolvedAnswer.length === 0) return {
374
659
  ok: false,
375
660
  kind: "no-answer",
376
- message: `aibridge: agy returned no usable answer (${clean(result.stderr) || `exit code ${result.code}`}).`,
661
+ message: `aibridge: agy returned no usable answer (${clean(resultError || result.stderr) || `exit code ${result.code}`}).`,
377
662
  exitCode: result.code
378
663
  };
379
664
  return {
380
665
  ok: true,
381
- response,
666
+ response: resolvedAnswer,
382
667
  exitCode: result.code ?? 0
383
668
  };
384
669
  } finally {
@@ -389,4 +674,4 @@ async function run(task, exec = runCaptured) {
389
674
  }
390
675
  }
391
676
  //#endregion
392
- export { AGY_CANONICAL_TO_NATIVE, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, generateImage, parseModels, parseQuotaGroups, probe, run };
677
+ export { AGY_CANONICAL_TO_NATIVE, MIN_AGY_STREAM_JSON, agySupportsStreamJson, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, generateImage, parseModels, parseQuotaGroups, probe, run };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibridge/driver-agy",
3
- "version": "0.9.1",
3
+ "version": "0.9.3",
4
4
  "description": "Antigravity (agy) CLI driver for aibridge",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  "src"
33
33
  ],
34
34
  "dependencies": {
35
- "@aibridge/proc": "0.9.0"
35
+ "@aibridge/proc": "0.9.1"
36
36
  },
37
37
  "devDependencies": {
38
38
  "tsdown": "0.22.14"
package/src/agy.test.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { buildAgyPrintArgs } from './agy.ts';
2
+ import { agySupportsStreamJson, buildAgyPrintArgs } from './agy.ts';
3
3
 
4
4
  describe('buildAgyPrintArgs', () => {
5
5
  it('assembles default agy args', () => {
@@ -39,3 +39,25 @@ describe('buildAgyPrintArgs', () => {
39
39
  ]);
40
40
  });
41
41
  });
42
+
43
+ describe('agySupportsStreamJson', () => {
44
+ it('accepts versions >= 1.2.3 with supported prefix shapes', () => {
45
+ expect(agySupportsStreamJson('agy 1.2.3')).toBe(true);
46
+ expect(agySupportsStreamJson('agy version 1.2.3')).toBe(true);
47
+ expect(agySupportsStreamJson('1.2.3')).toBe(true);
48
+ expect(agySupportsStreamJson('1.3.0')).toBe(true);
49
+ });
50
+
51
+ it('rejects versions < 1.2.3', () => {
52
+ expect(agySupportsStreamJson('1.2.2')).toBe(false);
53
+ expect(agySupportsStreamJson('1.1.8')).toBe(false);
54
+ expect(agySupportsStreamJson('agy version 1.0.0')).toBe(false);
55
+ });
56
+
57
+ it('rejects null, invalid strings, prereleases, and embedded build strings', () => {
58
+ expect(agySupportsStreamJson(null)).toBe(false);
59
+ expect(agySupportsStreamJson('not-a-version')).toBe(false);
60
+ expect(agySupportsStreamJson('1.2.3-rc.1')).toBe(false);
61
+ expect(agySupportsStreamJson('agy build 2026.09.15 version 1.2.2')).toBe(false);
62
+ });
63
+ });
package/src/agy.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { semverGte } from '@aibridge/proc';
2
+
1
3
  /**
2
4
  * Helper for building Antigravity CLI (`agy`) print arguments.
3
5
  *
@@ -32,3 +34,17 @@ export function buildAgyPrintArgs(prompt: string, opts: AgyPrintArgs): string[]
32
34
 
33
35
  return args;
34
36
  }
37
+
38
+ export const MIN_AGY_STREAM_JSON: readonly [number, number, number] = [1, 2, 3];
39
+
40
+ const STRICT_AGY_VERSION_RE = /^(?:agy(?: version)?\s+)?(\d+)\.(\d+)\.(\d+)(?:\s.*)?$/i;
41
+
42
+ export function agySupportsStreamJson(versionLine: string | null): boolean {
43
+ if (!versionLine) return false;
44
+ const m = versionLine.trim().match(STRICT_AGY_VERSION_RE);
45
+ if (!m) return false;
46
+ const major = Number(m[1]);
47
+ const minor = Number(m[2]);
48
+ const patch = Number(m[3]);
49
+ return semverGte([major, minor, patch], MIN_AGY_STREAM_JSON);
50
+ }
@@ -1,6 +1,6 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { test } from 'vitest';
3
- import { findModelQuota, parseModels, parseQuotaGroups } from './agyQuota.ts';
3
+ import { decodeKeyringSecret, findModelQuota, parseModels, parseQuotaGroups } from './agyQuota.ts';
4
4
 
5
5
  test('parseQuotaGroups preserves fractions or defaults to 0 if absent', () => {
6
6
  const groups = [
@@ -124,3 +124,20 @@ test('findModelQuota hits modelId id-form', () => {
124
124
  const found = findModelQuota(snapshot, 'gemini-3.7-flash-high');
125
125
  assert.equal(found?.modelId, 'gemini-3.7-flash-high');
126
126
  });
127
+
128
+ test('decodeKeyringSecret accepts raw JSON (linux) and go-keyring base64 (macOS)', () => {
129
+ const token = {
130
+ token: { access_token: 'a', refresh_token: 'r', expiry: '2026-01-01T00:00:00Z' },
131
+ };
132
+ const json = JSON.stringify(token);
133
+ assert.deepEqual(decodeKeyringSecret(`${json}\n`), token);
134
+ const b64 = Buffer.from(json).toString('base64');
135
+ assert.deepEqual(decodeKeyringSecret(`go-keyring-base64:${b64}\n`), token);
136
+ });
137
+
138
+ test('decodeKeyringSecret returns undefined for malformed payloads so the file fallback runs', () => {
139
+ assert.equal(decodeKeyringSecret(''), undefined);
140
+ assert.equal(decodeKeyringSecret('not json'), undefined);
141
+ assert.equal(decodeKeyringSecret('go-keyring-base64:!!!'), undefined);
142
+ assert.equal(decodeKeyringSecret('"a string"'), undefined);
143
+ });
package/src/agyQuota.ts CHANGED
@@ -3,11 +3,15 @@
3
3
  * token — no separate login. Mechanism learned from
4
4
  * github.com/skainguyen1412/antigravity-usage (reimplemented, not vendored):
5
5
  *
6
- * 1. Read `~/.gemini/antigravity-cli/antigravity-oauth-token`
7
- * ({ token: { access_token, refresh_token, expiry } }) — agy refreshes
8
- * this file itself whenever it runs. If expired, refresh in-memory via
9
- * Google's token endpoint with Antigravity's installed-app client
10
- * (public by design for installed apps); we NEVER write agy's file.
6
+ * 1. Read agy's credential — the OS keyring entry (go-keyring, service
7
+ * `gemini`, account `antigravity`) first, then the fallback file
8
+ * `~/.gemini/antigravity-cli/antigravity-oauth-token`. Both hold
9
+ * { token: { access_token, refresh_token, expiry }, auth_method }; agy
10
+ * only writes the file when the keyring is bypassed or unreachable, so
11
+ * the file goes stale once the keyring works. If expired, refresh
12
+ * in-memory via Google's token endpoint with Antigravity's installed-app
13
+ * client (public by design for installed apps); we NEVER write agy's
14
+ * store.
11
15
  * 2. POST cloudcode-pa.googleapis.com/v1internal:loadCodeAssist
12
16
  * (metadata ideType ANTIGRAVITY / pluginType GEMINI) → project id.
13
17
  * 3. POST /v1internal:fetchAvailableModels { project } — the
@@ -21,7 +25,7 @@
21
25
  import { readFileSync } from 'node:fs';
22
26
  import { homedir } from 'node:os';
23
27
  import { join } from 'node:path';
24
- import { AuthExpiredError } from '@aibridge/proc';
28
+ import { AuthExpiredError, runCaptured } from '@aibridge/proc';
25
29
  import { AGY_CANONICAL_TO_NATIVE } from './registry.ts';
26
30
 
27
31
  const CLOUDCODE_BASE = 'https://cloudcode-pa.googleapis.com';
@@ -95,9 +99,50 @@ interface AgyTokenFile {
95
99
  token?: { access_token?: string; refresh_token?: string; expiry?: string };
96
100
  }
97
101
 
102
+ const KEYRING_B64_PREFIX = 'go-keyring-base64:';
103
+
104
+ /**
105
+ * go-keyring base64-wraps the secret on macOS (`go-keyring-base64:` prefix)
106
+ * and stores it raw on Linux. Returns undefined unless the result parses as
107
+ * the token JSON, so a malformed keyring entry falls through to the file.
108
+ */
109
+ export function decodeKeyringSecret(raw: string): AgyTokenFile | undefined {
110
+ const s = raw.trim();
111
+ const json = s.startsWith(KEYRING_B64_PREFIX)
112
+ ? Buffer.from(s.slice(KEYRING_B64_PREFIX.length), 'base64').toString('utf8')
113
+ : s;
114
+ try {
115
+ const parsed: unknown = JSON.parse(json);
116
+ return parsed && typeof parsed === 'object' ? (parsed as AgyTokenFile) : undefined;
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ }
121
+
122
+ async function readKeyringCredential(): Promise<AgyTokenFile | undefined> {
123
+ const lookup: Record<string, [string, string[]]> = {
124
+ darwin: ['security', ['find-generic-password', '-s', 'gemini', '-a', 'antigravity', '-w']],
125
+ linux: ['secret-tool', ['lookup', 'service', 'gemini', 'username', 'antigravity']],
126
+ };
127
+ const cmd = lookup[process.platform];
128
+ if (!cmd) return undefined;
129
+ // ponytail: a locked keyring may pop a desktop unlock prompt that the 5s
130
+ // timeout then abandons; the file fallback covers it. Surface the reason in
131
+ // the preflight warning if this ever needs diagnosing.
132
+ const res = await runCaptured(cmd[0], cmd[1], { timeoutMs: 5_000 }).catch(() => undefined);
133
+ return res?.code === 0 ? decodeKeyringSecret(res.stdout) : undefined;
134
+ }
135
+
136
+ async function readAgyCredential(): Promise<AgyTokenFile> {
137
+ if (!process.env.AGY_OAUTH_TOKEN_PATH) {
138
+ const fromKeyring = await readKeyringCredential();
139
+ if (fromKeyring) return fromKeyring;
140
+ }
141
+ return JSON.parse(readFileSync(agyTokenPath(), 'utf8')) as AgyTokenFile;
142
+ }
143
+
98
144
  async function getAccessToken(): Promise<string> {
99
- const raw = readFileSync(agyTokenPath(), 'utf8');
100
- const parsed = JSON.parse(raw) as AgyTokenFile;
145
+ const parsed = await readAgyCredential();
101
146
  const access = parsed.token?.access_token;
102
147
  const refresh = parsed.token?.refresh_token;
103
148
  const expiry = parsed.token?.expiry;
@@ -26,7 +26,7 @@ describe('generateImage', () => {
26
26
  return {
27
27
  code: 0,
28
28
  signal: null,
29
- stdout: 'agy version 1.0.0\n',
29
+ stdout: 'agy 1.2.3\n',
30
30
  stderr: '',
31
31
  timedOut: false,
32
32
  };
@@ -47,6 +47,8 @@ describe('generateImage', () => {
47
47
  expect(capturedArgs).toContain('--model');
48
48
  expect(capturedArgs).toContain('gemini-3.7-flash-high');
49
49
  expect(capturedArgs).toContain('--dangerously-skip-permissions');
50
+ expect(capturedArgs).not.toContain('--output-format');
51
+ expect(capturedArgs).not.toContain('stream-json');
50
52
 
51
53
  const promptIdx = capturedArgs.indexOf('-p');
52
54
  expect(promptIdx).toBeGreaterThan(-1);