@aibridge/driver-agy 0.9.3 → 0.10.1

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
@@ -1,7 +1,7 @@
1
1
  # @aibridge/driver-agy
2
2
 
3
3
  Driver for the Antigravity (`agy`) CLI. It builds print-mode commands, checks
4
- availability, runs delegated tasks, captures answer files, and reads quota
4
+ availability, runs delegated tasks, captures their answers, and reads quota
5
5
  windows. Delegation `run()` uses `--output-format stream-json` when agy is ≥ 1.2.3; image generation does not.
6
6
 
7
7
  ```ts
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AuthExpiredError, isNotFound, probeVersion, runCaptured, semverGte, stripAnsi } from "@aibridge/proc";
2
- import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
3
- import { homedir, tmpdir } from "node:os";
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  //#region src/agy.ts
6
6
  /**
@@ -559,119 +559,103 @@ function logForwarder(onStdout, onActivity) {
559
559
  })
560
560
  };
561
561
  }
562
- async function run(task, exec = runCaptured) {
563
- let tempDir;
564
- let answerPath;
565
- let taskPrompt = task.prompt;
566
- const addDirs = [];
567
- if (task.tools) {
568
- tempDir = mkdtempSync(join(tmpdir(), "aibridge-agy-"));
569
- answerPath = join(tempDir, "answer.md");
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.`;
571
- addDirs.push(task.cwd, tempDir);
562
+ const AGY_ERROR_PREFIX = "AGY_ERROR:";
563
+ /**
564
+ * agy 1.5 reports a print timeout as exit 3 plus a machine-readable stderr line:
565
+ * `AGY_ERROR: {"status":"DEADLINE_EXCEEDED","reason":"print_timeout",…}`.
566
+ */
567
+ function isPrintTimeoutError(stderrLine) {
568
+ if (!stderrLine.startsWith(AGY_ERROR_PREFIX)) return false;
569
+ try {
570
+ const parsed = JSON.parse(stderrLine.slice(10));
571
+ return typeof parsed === "object" && parsed !== null && parsed.reason === "print_timeout";
572
+ } catch {
573
+ return false;
572
574
  }
575
+ }
576
+ async function run(task, exec = runCaptured) {
577
+ const addDirs = task.tools ? [task.cwd] : void 0;
578
+ let result;
579
+ let useStreamJson = false;
580
+ let forwarder;
573
581
  try {
574
- let result;
575
- let useStreamJson = false;
576
- let forwarder;
577
- try {
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, {
582
+ const version = await probeVersion("agy", exec);
583
+ useStreamJson = agySupportsStreamJson(version);
584
+ if (!useStreamJson) task.onStderr?.(`aibridge: agy version ${version ?? "unavailable"} does not support stream-json (requires >= 1.2.3); using text compatibility mode.\n`);
585
+ const args = [...buildAgyPrintArgs(task.prompt, {
586
+ model: task.backendModel,
587
+ printTimeoutSec: task.timeoutSec,
588
+ skipPermissions: task.tools,
589
+ addDirs
590
+ }), ...useStreamJson ? MESSAGE_STREAM_ARGS : []];
591
+ if (useStreamJson) {
592
+ forwarder = logForwarder(task.onStdout, task.onActivity);
593
+ result = await exec("agy", args, {
598
594
  cwd: task.cwd,
599
595
  timeoutMs: (task.timeoutSec + 20) * 1e3,
600
- onStdout: (chunk) => {
601
- task.onActivity?.();
602
- task.onStdout?.(chunk);
603
- },
596
+ captureStdout: false,
597
+ onStdout: forwarder.onChunk,
604
598
  onStderr: task.onStderr,
605
599
  onSpawn: task.onSpawn
606
600
  });
607
- } catch (err) {
608
- if (isNotFound(err)) return {
609
- ok: false,
610
- kind: "not-found",
611
- message: `aibridge: "agy" not found on PATH. ${INSTALL_HINT}`,
612
- exitCode: null
613
- };
614
- return {
615
- ok: false,
616
- kind: "spawn",
617
- message: `aibridge: failed to run agy: ${err.message}`,
618
- exitCode: null
619
- };
620
- }
621
- forwarder?.flush();
622
- if (result.timedOut) return {
623
- ok: false,
624
- kind: "timeout",
625
- message: `aibridge: agy timed out after ~${task.timeoutSec + 20}s; raise --timeout.`,
626
- exitCode: result.code
627
- };
628
- let fileAnswer = "";
629
- if (answerPath && existsSync(answerPath)) {
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);
651
- }
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 {
601
+ } else result = await exec("agy", args, {
602
+ cwd: task.cwd,
603
+ timeoutMs: (task.timeoutSec + 20) * 1e3,
604
+ onStdout: (chunk) => {
605
+ task.onActivity?.();
606
+ task.onStdout?.(chunk);
607
+ },
608
+ onStderr: task.onStderr,
609
+ onSpawn: task.onSpawn
610
+ });
611
+ } catch (err) {
612
+ if (isNotFound(err)) return {
659
613
  ok: false,
660
- kind: "no-answer",
661
- message: `aibridge: agy returned no usable answer (${clean(resultError || result.stderr) || `exit code ${result.code}`}).`,
662
- exitCode: result.code
614
+ kind: "not-found",
615
+ message: `aibridge: "agy" not found on PATH. ${INSTALL_HINT}`,
616
+ exitCode: null
663
617
  };
664
618
  return {
665
- ok: true,
666
- response: resolvedAnswer,
667
- exitCode: result.code ?? 0
619
+ ok: false,
620
+ kind: "spawn",
621
+ message: `aibridge: failed to run agy: ${err.message}`,
622
+ exitCode: null
668
623
  };
669
- } finally {
670
- if (tempDir) rmSync(tempDir, {
671
- recursive: true,
672
- force: true
673
- });
674
624
  }
625
+ forwarder?.flush();
626
+ if (result.timedOut) return {
627
+ ok: false,
628
+ kind: "timeout",
629
+ message: `aibridge: agy timed out after ~${task.timeoutSec + 20}s; raise --timeout.`,
630
+ exitCode: result.code
631
+ };
632
+ const stderrLines = stripAnsi(result.stderr).split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
633
+ const lastStderrLine = stderrLines[stderrLines.length - 1] ?? "";
634
+ if (result.code === 0 && AGY_PRINT_TIMEOUT_RE.test(lastStderrLine) || stderrLines.some(isPrintTimeoutError)) return {
635
+ ok: false,
636
+ kind: "timeout",
637
+ message: `aibridge: agy timed out after ~${task.timeoutSec}s; raise --timeout.`,
638
+ exitCode: result.code
639
+ };
640
+ const snap = useStreamJson && forwarder ? forwarder.snapshot() : void 0;
641
+ const resolvedAnswer = snap ? clean(snap.text ?? (snap.sawProtocol || snap.rawTruncated ? "" : snap.rawFallback)) : clean(result.stdout);
642
+ if (snap && !snap.sawProtocol && snap.rawTruncated && resolvedAnswer.length === 0) return {
643
+ ok: false,
644
+ kind: "no-answer",
645
+ message: `aibridge: agy returned more than ${RAW_FALLBACK_MAX_CHARS} characters without a recognized stream protocol; see the run log.`,
646
+ exitCode: result.code
647
+ };
648
+ if (snap?.resultStatus === "ERROR" || result.code !== 0 || resolvedAnswer.length === 0) return {
649
+ ok: false,
650
+ kind: "no-answer",
651
+ message: `aibridge: agy returned no usable answer (${clean(snap?.resultError || result.stderr) || `exit code ${result.code}`}).`,
652
+ exitCode: result.code
653
+ };
654
+ return {
655
+ ok: true,
656
+ response: resolvedAnswer,
657
+ exitCode: result.code ?? 0
658
+ };
675
659
  }
676
660
  //#endregion
677
661
  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.3",
3
+ "version": "0.10.1",
4
4
  "description": "Antigravity (agy) CLI driver for aibridge",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/agy.test.ts CHANGED
@@ -4,14 +4,14 @@ import { agySupportsStreamJson, buildAgyPrintArgs } from './agy.ts';
4
4
  describe('buildAgyPrintArgs', () => {
5
5
  it('assembles default agy args', () => {
6
6
  const args = buildAgyPrintArgs('test prompt', {
7
- model: 'gemini-3.7-flash-high',
7
+ model: 'gemini-3.8-flash-high',
8
8
  printTimeoutSec: 600,
9
9
  });
10
10
  expect(args).toEqual([
11
11
  '-p',
12
12
  'test prompt',
13
13
  '--model',
14
- 'gemini-3.7-flash-high',
14
+ 'gemini-3.8-flash-high',
15
15
  '--print-timeout',
16
16
  '600s',
17
17
  ]);
@@ -19,7 +19,7 @@ describe('buildAgyPrintArgs', () => {
19
19
 
20
20
  it('preserves order of skipPermissions and addDirs', () => {
21
21
  const args = buildAgyPrintArgs('test prompt', {
22
- model: 'gemini-3.7-flash-high',
22
+ model: 'gemini-3.8-flash-high',
23
23
  printTimeoutSec: 600,
24
24
  skipPermissions: true,
25
25
  addDirs: ['/work/repo', '/tmp/answer-dir'],
@@ -28,7 +28,7 @@ describe('buildAgyPrintArgs', () => {
28
28
  '-p',
29
29
  'test prompt',
30
30
  '--model',
31
- 'gemini-3.7-flash-high',
31
+ 'gemini-3.8-flash-high',
32
32
  '--print-timeout',
33
33
  '600s',
34
34
  '--dangerously-skip-permissions',
@@ -112,7 +112,7 @@ test('findModelQuota hits modelId id-form', () => {
112
112
  groups: [],
113
113
  models: [
114
114
  {
115
- modelId: 'gemini-3.7-flash-high',
115
+ modelId: 'gemini-3.8-flash-high',
116
116
  label: 'Gemini 3.7 Flash (High)',
117
117
  remainingFraction: 0.9,
118
118
  exhausted: false,
@@ -121,8 +121,8 @@ test('findModelQuota hits modelId id-form', () => {
121
121
  ],
122
122
  };
123
123
 
124
- const found = findModelQuota(snapshot, 'gemini-3.7-flash-high');
125
- assert.equal(found?.modelId, 'gemini-3.7-flash-high');
124
+ const found = findModelQuota(snapshot, 'gemini-3.8-flash-high');
125
+ assert.equal(found?.modelId, 'gemini-3.8-flash-high');
126
126
  });
127
127
 
128
128
  test('decodeKeyringSecret accepts raw JSON (linux) and go-keyring base64 (macOS)', () => {
@@ -9,7 +9,7 @@ describe('generateImage', () => {
9
9
  const baseReq: ImageGenRequest = {
10
10
  prompt: 'A futuristic city skyline',
11
11
  workDir: '/tmp/work',
12
- backendModel: 'gemini-3.7-flash-high',
12
+ backendModel: 'gemini-3.8-flash-high',
13
13
  aspectRatio: undefined,
14
14
  imagePaths: [],
15
15
  timeoutSec: 600,
@@ -45,7 +45,7 @@ describe('generateImage', () => {
45
45
 
46
46
  expect(capturedCmd).toBe('agy');
47
47
  expect(capturedArgs).toContain('--model');
48
- expect(capturedArgs).toContain('gemini-3.7-flash-high');
48
+ expect(capturedArgs).toContain('gemini-3.8-flash-high');
49
49
  expect(capturedArgs).toContain('--dangerously-skip-permissions');
50
50
  expect(capturedArgs).not.toContain('--output-format');
51
51
  expect(capturedArgs).not.toContain('stream-json');
package/src/run.test.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { writeFileSync } from 'node:fs';
2
1
  import type { RunOptions, RunResult } from '@aibridge/proc';
3
2
  import { describe, expect, it } from 'vitest';
4
3
  import { run } from './run.ts';
@@ -11,7 +10,6 @@ interface FakeAgyConfig {
11
10
  readonly stderr?: string;
12
11
  readonly code?: number | null;
13
12
  readonly timedOut?: boolean;
14
- readonly writeAnswerFile?: string;
15
13
  readonly streamChunks?: readonly string[];
16
14
  }
17
15
 
@@ -48,14 +46,6 @@ function fakeAgy(config: FakeAgyConfig = {}): {
48
46
  };
49
47
  }
50
48
 
51
- if (config.writeAnswerFile !== undefined) {
52
- const prompt = args[1] ?? '';
53
- const match = prompt.match(/file (\/.*answer\.md)/);
54
- if (match?.[1]) {
55
- writeFileSync(match[1], config.writeAnswerFile);
56
- }
57
- }
58
-
59
49
  if (config.streamChunks) {
60
50
  for (const chunk of config.streamChunks) {
61
51
  opts.onStdout?.(chunk);
@@ -90,7 +80,7 @@ describe('agy driver argv / version handling', () => {
90
80
  tools: false,
91
81
  timeoutSec: 60,
92
82
  cwd: '/test/cwd',
93
- backendModel: 'gemini-3.7-flash-high',
83
+ backendModel: 'gemini-3.8-flash-high',
94
84
  },
95
85
  fake.exec,
96
86
  );
@@ -104,7 +94,7 @@ describe('agy driver argv / version handling', () => {
104
94
  '-p',
105
95
  'do something',
106
96
  '--model',
107
- 'gemini-3.7-flash-high',
97
+ 'gemini-3.8-flash-high',
108
98
  '--print-timeout',
109
99
  '60s',
110
100
  '--output-format',
@@ -123,7 +113,7 @@ describe('agy driver argv / version handling', () => {
123
113
  tools: false,
124
114
  timeoutSec: 60,
125
115
  cwd: '/test/cwd',
126
- backendModel: 'gemini-3.7-flash-high',
116
+ backendModel: 'gemini-3.8-flash-high',
127
117
  },
128
118
  fake.exec,
129
119
  );
@@ -135,7 +125,7 @@ describe('agy driver argv / version handling', () => {
135
125
  '-p',
136
126
  'do something',
137
127
  '--model',
138
- 'gemini-3.7-flash-high',
128
+ 'gemini-3.8-flash-high',
139
129
  '--print-timeout',
140
130
  '60s',
141
131
  ]);
@@ -153,7 +143,7 @@ describe('agy driver argv / version handling', () => {
153
143
  tools: false,
154
144
  timeoutSec: 60,
155
145
  cwd: '/test/cwd',
156
- backendModel: 'gemini-3.7-flash-high',
146
+ backendModel: 'gemini-3.8-flash-high',
157
147
  },
158
148
  fake.exec,
159
149
  );
@@ -166,10 +156,10 @@ describe('agy driver argv / version handling', () => {
166
156
  expect(res).toEqual({ ok: true, response: 'Text fallback', exitCode: 0 });
167
157
  });
168
158
 
169
- it('passes --dangerously-skip-permissions, add-dirs, and stream-json on version 1.2.3 tools mode', async () => {
159
+ it('passes the prompt verbatim with --dangerously-skip-permissions, cwd as the only add-dir, and stream-json in tools mode', async () => {
170
160
  const fake = fakeAgy({
171
161
  version: 'agy 1.2.3',
172
- writeAnswerFile: 'Written answer from file',
162
+ stdout: `${JSON.stringify({ event: 'result', result: { status: 'SUCCESS', response: 'from stream' } })}\n`,
173
163
  });
174
164
 
175
165
  const res = await run(
@@ -178,7 +168,7 @@ describe('agy driver argv / version handling', () => {
178
168
  tools: true,
179
169
  timeoutSec: 100,
180
170
  cwd: '/repo/root',
181
- backendModel: 'gemini-3.7-flash-high',
171
+ backendModel: 'gemini-3.8-flash-high',
182
172
  },
183
173
  fake.exec,
184
174
  );
@@ -186,17 +176,16 @@ describe('agy driver argv / version handling', () => {
186
176
  const runCall = fake.calls[1];
187
177
  expect(runCall).toBeDefined();
188
178
  if (runCall) {
189
- const firstAddDir = runCall.args.indexOf('--add-dir');
190
- const secondAddDir = runCall.args.indexOf('--add-dir', firstAddDir + 1);
179
+ expect(runCall.args.slice(0, 2)).toEqual(['-p', 'do tool task']);
191
180
  expect(runCall.args).toContain('--dangerously-skip-permissions');
192
- expect(firstAddDir).toBeGreaterThan(-1);
193
- expect(runCall.args[firstAddDir + 1]).toBe('/repo/root');
194
- expect(secondAddDir).toBeGreaterThan(firstAddDir);
195
- expect(runCall.args[secondAddDir + 1]).toMatch(/aibridge-agy-/);
181
+ const addDirs = runCall.args.flatMap((a, i) =>
182
+ a === '--add-dir' ? [runCall.args[i + 1]] : [],
183
+ );
184
+ expect(addDirs).toEqual(['/repo/root']);
196
185
  expect(runCall.args.slice(-2)).toEqual(['--output-format', 'stream-json']);
197
186
  expect(runCall.opts.captureStdout).toBe(false);
198
187
  }
199
- expect(res).toEqual({ ok: true, response: 'Written answer from file', exitCode: 0 });
188
+ expect(res).toEqual({ ok: true, response: 'from stream', exitCode: 0 });
200
189
  });
201
190
  });
202
191
 
@@ -206,7 +195,7 @@ describe('agy no-tools stream-json parsing (1.2.3)', () => {
206
195
  tools: false,
207
196
  timeoutSec: 30,
208
197
  cwd: '/work',
209
- backendModel: 'gemini-3.7-flash-high',
198
+ backendModel: 'gemini-3.8-flash-high',
210
199
  };
211
200
 
212
201
  const stepUpdate = (
@@ -421,45 +410,9 @@ describe('agy tools stream-json parsing', () => {
421
410
  tools: true,
422
411
  timeoutSec: 30,
423
412
  cwd: '/work',
424
- backendModel: 'gemini-3.7-flash-high',
413
+ backendModel: 'gemini-3.8-flash-high',
425
414
  };
426
415
 
427
- it('authoritative answer file wins over result.response and emits banner', async () => {
428
- const log: string[] = [];
429
- const stream = [
430
- JSON.stringify({ event: 'init' }),
431
- JSON.stringify({
432
- event: 'result',
433
- result: { status: 'SUCCESS', response: 'something else' },
434
- }),
435
- '',
436
- ].join('\n');
437
-
438
- const fake = fakeAgy({
439
- version: 'agy 1.2.3',
440
- stdout: stream,
441
- writeAnswerFile: 'Written answer from file',
442
- });
443
-
444
- const res = await run({ ...task, onStdout: c => log.push(c) }, fake.exec);
445
-
446
- expect(res).toEqual({ ok: true, response: 'Written answer from file', exitCode: 0 });
447
- expect(log.join('')).toContain('--- final answer ---\nWritten answer from file\n');
448
- });
449
-
450
- it('returns result.response when no answer file is created in tools mode', async () => {
451
- const stream = [
452
- JSON.stringify({ event: 'init' }),
453
- JSON.stringify({ event: 'result', result: { status: 'SUCCESS', response: 'from stream' } }),
454
- '',
455
- ].join('\n');
456
-
457
- const fake = fakeAgy({ version: 'agy 1.2.3', stdout: stream });
458
- const res = await run(task, fake.exec);
459
-
460
- expect(res).toEqual({ ok: true, response: 'from stream', exitCode: 0 });
461
- });
462
-
463
416
  it('logs tool ACTIVE and DONE concisely without dumping heavy payloads', async () => {
464
417
  const log: string[] = [];
465
418
  const stream = [
@@ -502,9 +455,45 @@ describe('agy timeout and error handling', () => {
502
455
  tools: false,
503
456
  timeoutSec: 1,
504
457
  cwd: '/work',
505
- backendModel: 'gemini-3.7-flash-high',
458
+ backendModel: 'gemini-3.8-flash-high',
506
459
  };
507
460
 
461
+ it('maps the agy 1.5 AGY_ERROR print_timeout line (exit 3) to timeout', async () => {
462
+ const stderr = [
463
+ '[agy] print timeout after 1s with turn in progress; returning partial output',
464
+ 'error: print timeout after 1s with the turn still in progress; the response is partial',
465
+ 'AGY_ERROR: {"short_error":"print timeout after 1s with the turn still in progress; the response is partial","status":"DEADLINE_EXCEEDED","retryable":false,"reason":"print_timeout"}',
466
+ '',
467
+ ].join('\n');
468
+ const stream = [
469
+ JSON.stringify({ event: 'init' }),
470
+ JSON.stringify({
471
+ event: 'result',
472
+ result: { status: 'ERROR', response: '', error: 'print timeout after 1s' },
473
+ }),
474
+ '',
475
+ ].join('\n');
476
+
477
+ const res = await run(
478
+ task,
479
+ fakeAgy({ version: 'agy 1.5.15', stdout: stream, stderr, code: 3 }).exec,
480
+ );
481
+
482
+ expect(res.ok).toBe(false);
483
+ if (!res.ok) expect(res.kind).toBe('timeout');
484
+ });
485
+
486
+ it('keeps another AGY_ERROR reason as no-answer', async () => {
487
+ const stderr = 'AGY_ERROR: {"status":"NOT_FOUND","reason":"unknown_model"}\n';
488
+ const res = await run(
489
+ task,
490
+ fakeAgy({ version: 'agy 1.5.15', stdout: '', stderr, code: 1 }).exec,
491
+ );
492
+
493
+ expect(res.ok).toBe(false);
494
+ if (!res.ok) expect(res.kind).toBe('no-answer');
495
+ });
496
+
508
497
  it('maps soft print-timeout stderr on stream path to timeout with ~1s message', async () => {
509
498
  const stderr = '[agy] print timeout after 1s with turn in progress; returning partial output\n';
510
499
  const stream = [
@@ -547,21 +536,17 @@ describe('agy timeout and error handling', () => {
547
536
  }
548
537
  });
549
538
 
550
- it('answer file wins over soft print-timeout stderr in tools mode', async () => {
539
+ it('maps soft print-timeout stderr to timeout in tools mode too', async () => {
551
540
  const stderr = '[agy] print timeout after 1s with turn in progress; returning partial output\n';
552
- const fake = fakeAgy({
553
- version: 'agy 1.2.3',
554
- stderr,
555
- code: 0,
556
- writeAnswerFile: 'Full finished answer',
557
- });
541
+ const fake = fakeAgy({ version: 'agy 1.2.3', stderr, code: 0 });
558
542
 
559
543
  const res = await run({ ...task, tools: true }, fake.exec);
560
544
 
561
- expect(res).toEqual({ ok: true, response: 'Full finished answer', exitCode: 0 });
545
+ expect(res.ok).toBe(false);
546
+ if (!res.ok) expect(res.kind).toBe('timeout');
562
547
  });
563
548
 
564
- it('ERROR result frame overrides a non-empty answer file even with exit 0', async () => {
549
+ it('ERROR result frame is no-answer even with exit 0', async () => {
565
550
  const stream = [
566
551
  JSON.stringify({ event: 'init' }),
567
552
  JSON.stringify({
@@ -574,7 +559,6 @@ describe('agy timeout and error handling', () => {
574
559
  version: 'agy 1.2.3',
575
560
  stdout: stream,
576
561
  code: 0,
577
- writeAnswerFile: 'Apparently finished answer',
578
562
  });
579
563
 
580
564
  const res = await run({ ...task, tools: true }, fake.exec);
@@ -622,23 +606,6 @@ describe('agy timeout and error handling', () => {
622
606
  }
623
607
  });
624
608
 
625
- it('hard process timeout wins over a non-empty answer file', async () => {
626
- const fake = fakeAgy({
627
- version: 'agy 1.2.3',
628
- timedOut: true,
629
- code: null,
630
- writeAnswerFile: 'Possibly torn answer',
631
- });
632
-
633
- const res = await run({ ...task, tools: true }, fake.exec);
634
-
635
- expect(res.ok).toBe(false);
636
- if (!res.ok) {
637
- expect(res.kind).toBe('timeout');
638
- expect(res.message).toBe('aibridge: agy timed out after ~21s; raise --timeout.');
639
- }
640
- });
641
-
642
609
  it('maps exit 1, error stderr, and ERROR frame to no-answer with detail', async () => {
643
610
  const stderr = 'error: unknown model foo\n';
644
611
  const stream = [
@@ -692,7 +659,7 @@ describe('agy spawn failure handling', () => {
692
659
  tools: false,
693
660
  timeoutSec: 10,
694
661
  cwd: '/work',
695
- backendModel: 'gemini-3.7-flash-high',
662
+ backendModel: 'gemini-3.8-flash-high',
696
663
  };
697
664
 
698
665
  it('maps ENOENT spawn error to not-found', async () => {
package/src/run.ts CHANGED
@@ -1,6 +1,3 @@
1
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
1
  import { isNotFound, probeVersion, type RunResult, runCaptured, stripAnsi } from '@aibridge/proc';
5
2
  import { agySupportsStreamJson, buildAgyPrintArgs } from './agy.ts';
6
3
  import { INSTALL_HINT } from './probe.ts';
@@ -296,164 +293,146 @@ function logForwarder(
296
293
  };
297
294
  }
298
295
 
296
+ const AGY_ERROR_PREFIX = 'AGY_ERROR:';
297
+
298
+ /**
299
+ * agy 1.5 reports a print timeout as exit 3 plus a machine-readable stderr line:
300
+ * `AGY_ERROR: {"status":"DEADLINE_EXCEEDED","reason":"print_timeout",…}`.
301
+ */
302
+ function isPrintTimeoutError(stderrLine: string): boolean {
303
+ if (!stderrLine.startsWith(AGY_ERROR_PREFIX)) return false;
304
+ try {
305
+ const parsed: unknown = JSON.parse(stderrLine.slice(AGY_ERROR_PREFIX.length));
306
+ return (
307
+ typeof parsed === 'object' &&
308
+ parsed !== null &&
309
+ (parsed as { reason?: unknown }).reason === 'print_timeout'
310
+ );
311
+ } catch {
312
+ return false;
313
+ }
314
+ }
315
+
299
316
  export async function run(
300
317
  task: DelegationTask,
301
318
  exec: typeof runCaptured = runCaptured,
302
319
  ): Promise<DelegationResult> {
303
- let tempDir: string | undefined;
304
- let answerPath: string | undefined;
305
-
306
- let taskPrompt = task.prompt;
307
- const addDirs: string[] = [];
308
-
309
- if (task.tools) {
310
- tempDir = mkdtempSync(join(tmpdir(), 'aibridge-agy-'));
311
- answerPath = join(tempDir, 'answer.md');
312
- taskPrompt =
313
- `${task.prompt}\n\nYou are working in the repository rooted at ${task.cwd}; make ALL file ` +
314
- `edits there (any relative paths in the task are relative to that root). When the task ` +
315
- `is complete, write ONLY your final answer (the exact text you would otherwise print as ` +
316
- `your response, with no narration of your steps) to the file ${answerPath} — nothing else ` +
317
- `in that file. This is how your answer is captured; do not mention the file in the answer.`;
318
- addDirs.push(task.cwd, tempDir);
319
- }
320
+ // agy ignores its spawn cwd and treats the first --add-dir as the workspace.
321
+ const addDirs = task.tools ? [task.cwd] : undefined;
320
322
 
321
- try {
322
- let result: RunResult;
323
- let useStreamJson = false;
324
- let forwarder: LogForwarder | undefined;
325
-
326
- try {
327
- const version = await probeVersion('agy', exec);
328
- useStreamJson = agySupportsStreamJson(version);
329
- if (!useStreamJson) {
330
- task.onStderr?.(
331
- `aibridge: agy version ${version ?? 'unavailable'} does not support stream-json (requires >= 1.2.3); using text compatibility mode.\n`,
332
- );
333
- }
323
+ let result: RunResult;
324
+ let useStreamJson = false;
325
+ let forwarder: LogForwarder | undefined;
334
326
 
335
- const args = [
336
- ...buildAgyPrintArgs(taskPrompt, {
337
- model: task.backendModel,
338
- printTimeoutSec: task.timeoutSec,
339
- skipPermissions: task.tools,
340
- addDirs: addDirs.length > 0 ? addDirs : undefined,
341
- }),
342
- ...(useStreamJson ? MESSAGE_STREAM_ARGS : []),
343
- ];
344
-
345
- if (useStreamJson) {
346
- forwarder = logForwarder(task.onStdout, task.onActivity);
347
- result = await exec('agy', args, {
348
- cwd: task.cwd,
349
- timeoutMs: (task.timeoutSec + 20) * 1000,
350
- captureStdout: false,
351
- onStdout: forwarder.onChunk,
352
- onStderr: task.onStderr,
353
- onSpawn: task.onSpawn,
354
- });
355
- } else {
356
- result = await exec('agy', args, {
357
- cwd: task.cwd,
358
- timeoutMs: (task.timeoutSec + 20) * 1000,
359
- onStdout: chunk => {
360
- task.onActivity?.();
361
- task.onStdout?.(chunk);
362
- },
363
- onStderr: task.onStderr,
364
- onSpawn: task.onSpawn,
365
- });
366
- }
367
- } catch (err) {
368
- if (isNotFound(err)) {
369
- return {
370
- ok: false,
371
- kind: 'not-found',
372
- message: `aibridge: "agy" not found on PATH. ${INSTALL_HINT}`,
373
- exitCode: null,
374
- };
375
- }
376
- return {
377
- ok: false,
378
- kind: 'spawn',
379
- message: `aibridge: failed to run agy: ${(err as Error).message}`,
380
- exitCode: null,
381
- };
327
+ try {
328
+ const version = await probeVersion('agy', exec);
329
+ useStreamJson = agySupportsStreamJson(version);
330
+ if (!useStreamJson) {
331
+ task.onStderr?.(
332
+ `aibridge: agy version ${version ?? 'unavailable'} does not support stream-json (requires >= 1.2.3); using text compatibility mode.\n`,
333
+ );
382
334
  }
383
335
 
384
- forwarder?.flush();
385
-
386
- if (result.timedOut) {
336
+ const args = [
337
+ ...buildAgyPrintArgs(task.prompt, {
338
+ model: task.backendModel,
339
+ printTimeoutSec: task.timeoutSec,
340
+ skipPermissions: task.tools,
341
+ addDirs,
342
+ }),
343
+ ...(useStreamJson ? MESSAGE_STREAM_ARGS : []),
344
+ ];
345
+
346
+ if (useStreamJson) {
347
+ forwarder = logForwarder(task.onStdout, task.onActivity);
348
+ result = await exec('agy', args, {
349
+ cwd: task.cwd,
350
+ timeoutMs: (task.timeoutSec + 20) * 1000,
351
+ captureStdout: false,
352
+ onStdout: forwarder.onChunk,
353
+ onStderr: task.onStderr,
354
+ onSpawn: task.onSpawn,
355
+ });
356
+ } else {
357
+ result = await exec('agy', args, {
358
+ cwd: task.cwd,
359
+ timeoutMs: (task.timeoutSec + 20) * 1000,
360
+ onStdout: chunk => {
361
+ task.onActivity?.();
362
+ task.onStdout?.(chunk);
363
+ },
364
+ onStderr: task.onStderr,
365
+ onSpawn: task.onSpawn,
366
+ });
367
+ }
368
+ } catch (err) {
369
+ if (isNotFound(err)) {
387
370
  return {
388
371
  ok: false,
389
- kind: 'timeout',
390
- message: `aibridge: agy timed out after ~${task.timeoutSec + 20}s; raise --timeout.`,
391
- exitCode: result.code,
372
+ kind: 'not-found',
373
+ message: `aibridge: "agy" not found on PATH. ${INSTALL_HINT}`,
374
+ exitCode: null,
392
375
  };
393
376
  }
377
+ return {
378
+ ok: false,
379
+ kind: 'spawn',
380
+ message: `aibridge: failed to run agy: ${(err as Error).message}`,
381
+ exitCode: null,
382
+ };
383
+ }
394
384
 
395
- let fileAnswer = '';
396
- if (answerPath && existsSync(answerPath)) {
397
- fileAnswer = clean(readFileSync(answerPath, 'utf8'));
398
- if (fileAnswer.length > 0) {
399
- task.onStdout?.(`\n--- final answer ---\n${fileAnswer}\n`);
400
- }
401
- }
402
-
403
- const snap = useStreamJson && forwarder ? forwarder.snapshot() : undefined;
404
- let resolvedAnswer = '';
405
- const sawProtocol = snap?.sawProtocol ?? false;
406
- const rawTruncated = snap?.rawTruncated ?? false;
407
- const resultError = snap?.resultError ?? null;
408
- const resultStatus = snap?.resultStatus ?? null;
385
+ forwarder?.flush();
409
386
 
410
- if (fileAnswer.length > 0) {
411
- resolvedAnswer = fileAnswer;
412
- } else {
413
- const stderrLines = stripAnsi(result.stderr)
414
- .split('\n')
415
- .map(l => l.trim())
416
- .filter(l => l.length > 0);
417
- const lastStderrLine = stderrLines[stderrLines.length - 1] ?? '';
418
- if (result.code === 0 && AGY_PRINT_TIMEOUT_RE.test(lastStderrLine)) {
419
- return {
420
- ok: false,
421
- kind: 'timeout',
422
- message: `aibridge: agy timed out after ~${task.timeoutSec}s; raise --timeout.`,
423
- exitCode: result.code,
424
- };
425
- }
387
+ if (result.timedOut) {
388
+ return {
389
+ ok: false,
390
+ kind: 'timeout',
391
+ message: `aibridge: agy timed out after ~${task.timeoutSec + 20}s; raise --timeout.`,
392
+ exitCode: result.code,
393
+ };
394
+ }
426
395
 
427
- if (snap) {
428
- resolvedAnswer = clean(
429
- snap.text ?? (snap.sawProtocol || snap.rawTruncated ? '' : snap.rawFallback),
430
- );
431
- } else {
432
- resolvedAnswer = clean(result.stdout);
433
- }
434
- }
396
+ const stderrLines = stripAnsi(result.stderr)
397
+ .split('\n')
398
+ .map(l => l.trim())
399
+ .filter(l => l.length > 0);
400
+ const lastStderrLine = stderrLines[stderrLines.length - 1] ?? '';
401
+ if (
402
+ (result.code === 0 && AGY_PRINT_TIMEOUT_RE.test(lastStderrLine)) ||
403
+ stderrLines.some(isPrintTimeoutError)
404
+ ) {
405
+ return {
406
+ ok: false,
407
+ kind: 'timeout',
408
+ message: `aibridge: agy timed out after ~${task.timeoutSec}s; raise --timeout.`,
409
+ exitCode: result.code,
410
+ };
411
+ }
435
412
 
436
- if (useStreamJson && !sawProtocol && rawTruncated && resolvedAnswer.length === 0) {
437
- return {
438
- ok: false,
439
- kind: 'no-answer',
440
- message: `aibridge: agy returned more than ${RAW_FALLBACK_MAX_CHARS} characters without a recognized stream protocol; see the run log.`,
441
- exitCode: result.code,
442
- };
443
- }
413
+ const snap = useStreamJson && forwarder ? forwarder.snapshot() : undefined;
414
+ const resolvedAnswer = snap
415
+ ? clean(snap.text ?? (snap.sawProtocol || snap.rawTruncated ? '' : snap.rawFallback))
416
+ : clean(result.stdout);
444
417
 
445
- if (resultStatus === 'ERROR' || result.code !== 0 || resolvedAnswer.length === 0) {
446
- const detail = clean(resultError || result.stderr) || `exit code ${result.code}`;
447
- return {
448
- ok: false,
449
- kind: 'no-answer',
450
- message: `aibridge: agy returned no usable answer (${detail}).`,
451
- exitCode: result.code,
452
- };
453
- }
418
+ if (snap && !snap.sawProtocol && snap.rawTruncated && resolvedAnswer.length === 0) {
419
+ return {
420
+ ok: false,
421
+ kind: 'no-answer',
422
+ message: `aibridge: agy returned more than ${RAW_FALLBACK_MAX_CHARS} characters without a recognized stream protocol; see the run log.`,
423
+ exitCode: result.code,
424
+ };
425
+ }
454
426
 
455
- return { ok: true, response: resolvedAnswer, exitCode: result.code ?? 0 };
456
- } finally {
457
- if (tempDir) rmSync(tempDir, { recursive: true, force: true });
427
+ if (snap?.resultStatus === 'ERROR' || result.code !== 0 || resolvedAnswer.length === 0) {
428
+ const detail = clean(snap?.resultError || result.stderr) || `exit code ${result.code}`;
429
+ return {
430
+ ok: false,
431
+ kind: 'no-answer',
432
+ message: `aibridge: agy returned no usable answer (${detail}).`,
433
+ exitCode: result.code,
434
+ };
458
435
  }
436
+
437
+ return { ok: true, response: resolvedAnswer, exitCode: result.code ?? 0 };
459
438
  }