@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/src/run.test.ts CHANGED
@@ -3,20 +3,119 @@ import type { RunOptions, RunResult } from '@aibridge/proc';
3
3
  import { describe, expect, it } from 'vitest';
4
4
  import { run } from './run.ts';
5
5
 
6
- describe('agy driver run()', () => {
7
- it('builds args without tools and handles successful execution', async () => {
8
- let capturedCmd = '';
9
- let capturedArgs: readonly string[] = [];
10
-
11
- const fakeExec = async (
12
- cmd: string,
13
- args: readonly string[],
14
- _opts: RunOptions = {},
15
- ): Promise<RunResult> => {
16
- capturedCmd = cmd;
17
- capturedArgs = args;
18
- return { code: 0, signal: null, stdout: 'Hello world', stderr: '', timedOut: false };
6
+ interface FakeAgyConfig {
7
+ readonly version?: string | null;
8
+ readonly versionError?: Error;
9
+ readonly execError?: Error;
10
+ readonly stdout?: string;
11
+ readonly stderr?: string;
12
+ readonly code?: number | null;
13
+ readonly timedOut?: boolean;
14
+ readonly writeAnswerFile?: string;
15
+ readonly streamChunks?: readonly string[];
16
+ }
17
+
18
+ function fakeAgy(config: FakeAgyConfig = {}): {
19
+ readonly exec: (cmd: string, args: readonly string[], opts?: RunOptions) => Promise<RunResult>;
20
+ readonly calls: Array<{ cmd: string; args: readonly string[]; opts: RunOptions }>;
21
+ } {
22
+ const calls: Array<{ cmd: string; args: readonly string[]; opts: RunOptions }> = [];
23
+
24
+ const exec = async (
25
+ cmd: string,
26
+ args: readonly string[],
27
+ opts: RunOptions = {},
28
+ ): Promise<RunResult> => {
29
+ calls.push({ cmd, args, opts });
30
+
31
+ if (config.execError) {
32
+ throw config.execError;
33
+ }
34
+
35
+ if (args.length === 1 && args[0] === '--version') {
36
+ if (config.versionError) {
37
+ throw config.versionError;
38
+ }
39
+ if (config.version === null) {
40
+ return { code: 0, signal: null, stdout: '', stderr: '', timedOut: false };
41
+ }
42
+ return {
43
+ code: 0,
44
+ signal: null,
45
+ stdout: `${config.version ?? 'agy 1.2.3'}\n`,
46
+ stderr: '',
47
+ timedOut: false,
48
+ };
49
+ }
50
+
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
+ if (config.streamChunks) {
60
+ for (const chunk of config.streamChunks) {
61
+ opts.onStdout?.(chunk);
62
+ }
63
+ } else if (config.stdout !== undefined) {
64
+ if (opts.captureStdout === false) {
65
+ opts.onStdout?.(config.stdout);
66
+ } else {
67
+ opts.onStdout?.(config.stdout);
68
+ }
69
+ }
70
+
71
+ return {
72
+ code: config.code !== undefined ? config.code : 0,
73
+ signal: null,
74
+ stdout: opts.captureStdout === false ? '' : (config.stdout ?? ''),
75
+ stderr: config.stderr ?? '',
76
+ timedOut: config.timedOut ?? false,
19
77
  };
78
+ };
79
+
80
+ return { exec, calls };
81
+ }
82
+
83
+ describe('agy driver argv / version handling', () => {
84
+ it('passes stream-json and sets captureStdout: false on version >= 1.2.3 (no-tools)', async () => {
85
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: '' });
86
+
87
+ await run(
88
+ {
89
+ prompt: 'do something',
90
+ tools: false,
91
+ timeoutSec: 60,
92
+ cwd: '/test/cwd',
93
+ backendModel: 'gemini-3.7-flash-high',
94
+ },
95
+ fake.exec,
96
+ );
97
+
98
+ expect(fake.calls.length).toBe(2);
99
+ const runCall = fake.calls[1];
100
+ expect(runCall).toBeDefined();
101
+ if (runCall) {
102
+ expect(runCall.cmd).toBe('agy');
103
+ expect(runCall.args).toEqual([
104
+ '-p',
105
+ 'do something',
106
+ '--model',
107
+ 'gemini-3.7-flash-high',
108
+ '--print-timeout',
109
+ '60s',
110
+ '--output-format',
111
+ 'stream-json',
112
+ ]);
113
+ expect(runCall.opts.captureStdout).toBe(false);
114
+ }
115
+ });
116
+
117
+ it('keeps plain text args and captures stdout on version < 1.2.3 (1.2.2)', async () => {
118
+ const fake = fakeAgy({ version: 'agy 1.2.2', stdout: 'Hello world' });
20
119
 
21
120
  const res = await run(
22
121
  {
@@ -26,44 +125,52 @@ describe('agy driver run()', () => {
26
125
  cwd: '/test/cwd',
27
126
  backendModel: 'gemini-3.7-flash-high',
28
127
  },
29
- fakeExec,
128
+ fake.exec,
30
129
  );
31
130
 
32
- expect(capturedCmd).toEqual('agy');
33
- expect(capturedArgs).toEqual([
34
- '-p',
35
- 'do something',
36
- '--model',
37
- 'gemini-3.7-flash-high',
38
- '--print-timeout',
39
- '60s',
40
- ]);
131
+ const runCall = fake.calls[1];
132
+ expect(runCall).toBeDefined();
133
+ if (runCall) {
134
+ expect(runCall.args).toEqual([
135
+ '-p',
136
+ 'do something',
137
+ '--model',
138
+ 'gemini-3.7-flash-high',
139
+ '--print-timeout',
140
+ '60s',
141
+ ]);
142
+ expect(runCall.opts.captureStdout).toBeUndefined();
143
+ }
41
144
  expect(res).toEqual({ ok: true, response: 'Hello world', exitCode: 0 });
42
145
  });
43
146
 
44
- it('uses answer file protocol when tools=true', async () => {
45
- let capturedArgs: readonly string[] = [];
147
+ it('falls back to text mode when version is unparseable', async () => {
148
+ const fake = fakeAgy({ version: 'not-a-version', stdout: 'Text fallback' });
46
149
 
47
- const fakeExec = async (
48
- _cmd: string,
49
- args: readonly string[],
50
- _opts: RunOptions = {},
51
- ): Promise<RunResult> => {
52
- capturedArgs = args;
53
- // find answer path from prompt in args
54
- const prompt = args[1] ?? '';
55
- const match = prompt.match(/file (\/.*answer\.md)/);
56
- if (match?.[1]) {
57
- writeFileSync(match[1], 'Written answer from file');
58
- }
59
- return {
60
- code: 0,
61
- signal: null,
62
- stdout: 'Shell cwd was reset to /foo\n',
63
- stderr: '',
64
- timedOut: false,
65
- };
66
- };
150
+ const res = await run(
151
+ {
152
+ prompt: 'do something',
153
+ tools: false,
154
+ timeoutSec: 60,
155
+ cwd: '/test/cwd',
156
+ backendModel: 'gemini-3.7-flash-high',
157
+ },
158
+ fake.exec,
159
+ );
160
+
161
+ const runCall = fake.calls[1];
162
+ expect(runCall).toBeDefined();
163
+ if (runCall) {
164
+ expect(runCall.args).not.toContain('--output-format');
165
+ }
166
+ expect(res).toEqual({ ok: true, response: 'Text fallback', exitCode: 0 });
167
+ });
168
+
169
+ it('passes --dangerously-skip-permissions, add-dirs, and stream-json on version 1.2.3 tools mode', async () => {
170
+ const fake = fakeAgy({
171
+ version: 'agy 1.2.3',
172
+ writeAnswerFile: 'Written answer from file',
173
+ });
67
174
 
68
175
  const res = await run(
69
176
  {
@@ -73,82 +180,547 @@ describe('agy driver run()', () => {
73
180
  cwd: '/repo/root',
74
181
  backendModel: 'gemini-3.7-flash-high',
75
182
  },
76
- fakeExec,
183
+ fake.exec,
77
184
  );
78
185
 
79
- expect(capturedArgs).toContain('--dangerously-skip-permissions');
80
- expect(capturedArgs).toContain('/repo/root');
186
+ const runCall = fake.calls[1];
187
+ expect(runCall).toBeDefined();
188
+ if (runCall) {
189
+ const firstAddDir = runCall.args.indexOf('--add-dir');
190
+ const secondAddDir = runCall.args.indexOf('--add-dir', firstAddDir + 1);
191
+ 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-/);
196
+ expect(runCall.args.slice(-2)).toEqual(['--output-format', 'stream-json']);
197
+ expect(runCall.opts.captureStdout).toBe(false);
198
+ }
81
199
  expect(res).toEqual({ ok: true, response: 'Written answer from file', exitCode: 0 });
82
200
  });
201
+ });
83
202
 
84
- it('maps ENOENT spawn error to not-found', async () => {
85
- const fakeExec = async (): Promise<RunResult> => {
86
- const err = new Error('spawn agy ENOENT') as Error & { code?: string };
87
- err.code = 'ENOENT';
88
- throw err;
89
- };
203
+ describe('agy no-tools stream-json parsing (1.2.3)', () => {
204
+ const task = {
205
+ prompt: 'test prompt',
206
+ tools: false,
207
+ timeoutSec: 30,
208
+ cwd: '/work',
209
+ backendModel: 'gemini-3.7-flash-high',
210
+ };
211
+
212
+ const stepUpdate = (
213
+ stepType: string,
214
+ delta?: string,
215
+ state = 'ACTIVE',
216
+ extra: Record<string, unknown> = {},
217
+ ) =>
218
+ JSON.stringify({
219
+ event: 'step_update',
220
+ step_update: {
221
+ state,
222
+ step_type: stepType,
223
+ ...(delta !== undefined ? { text_delta: delta } : {}),
224
+ ...extra,
225
+ },
226
+ });
227
+
228
+ const resultFrame = (status: string, response?: string, error?: string) =>
229
+ JSON.stringify({
230
+ event: 'result',
231
+ result: {
232
+ status,
233
+ ...(response !== undefined ? { response } : {}),
234
+ ...(error !== undefined ? { error } : {}),
235
+ },
236
+ });
237
+
238
+ it('parses init -> step_update deltas -> result SUCCESS', async () => {
239
+ const log: string[] = [];
240
+ const stream = [
241
+ JSON.stringify({ event: 'init' }),
242
+ stepUpdate('agent_response', 'Hel'),
243
+ stepUpdate('agent_response', 'lo', 'DONE'),
244
+ resultFrame('SUCCESS', 'Hello'),
245
+ '',
246
+ ].join('\n');
247
+
248
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: stream });
249
+ const res = await run({ ...task, onStdout: c => log.push(c) }, fake.exec);
250
+
251
+ expect(res).toEqual({ ok: true, response: 'Hello', exitCode: 0 });
252
+ expect(log.join('')).toBe('Hello\n');
253
+ expect(log.join('')).not.toContain('event');
254
+ expect(log.join('')).not.toContain('init');
255
+ });
256
+
257
+ it('triggers onActivity on mid-line chunks', async () => {
258
+ let activityCount = 0;
259
+ const stream = [
260
+ JSON.stringify({ event: 'init' }),
261
+ stepUpdate('agent_response', 'Hello', 'DONE'),
262
+ resultFrame('SUCCESS', 'Hello'),
263
+ '',
264
+ ].join('\n');
265
+
266
+ const fake = fakeAgy({
267
+ version: 'agy 1.2.3',
268
+ streamChunks: [stream.slice(0, 10), stream.slice(10, 25), stream.slice(25)],
269
+ });
90
270
 
91
271
  const res = await run(
92
272
  {
93
- prompt: 'test',
94
- tools: false,
95
- timeoutSec: 30,
96
- cwd: '/test/cwd',
97
- backendModel: 'gemini-3.7-flash-high',
273
+ ...task,
274
+ onActivity: () => {
275
+ activityCount++;
276
+ },
98
277
  },
99
- fakeExec,
278
+ fake.exec,
100
279
  );
101
280
 
281
+ expect(res).toEqual({ ok: true, response: 'Hello', exitCode: 0 });
282
+ expect(activityCount).toBeGreaterThan(1);
283
+ });
284
+
285
+ it('maps protocol with empty SUCCESS response and no deltas to no-answer', async () => {
286
+ const stream = [JSON.stringify({ event: 'init' }), resultFrame('SUCCESS', ''), ''].join('\n');
287
+
288
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: stream });
289
+ const res = await run(task, fake.exec);
290
+
102
291
  expect(res.ok).toBe(false);
103
292
  if (!res.ok) {
104
- expect(res.kind).toBe('not-found');
105
- expect(res.exitCode).toBeNull();
293
+ expect(res.kind).toBe('no-answer');
294
+ expect(JSON.stringify(res)).not.toContain('event');
295
+ expect(JSON.stringify(res)).not.toContain('step_update');
106
296
  }
107
297
  });
108
298
 
109
- it('maps timeout correctly', async () => {
110
- const fakeExec = async (): Promise<RunResult> => {
111
- return { code: null, signal: 'SIGTERM', stdout: '', stderr: '', timedOut: true };
112
- };
299
+ it('prefers result.response over logged deltas when they differ', async () => {
300
+ const log: string[] = [];
301
+ const stream = [
302
+ JSON.stringify({ event: 'init' }),
303
+ stepUpdate('agent_response', 'draft\n', 'DONE'),
304
+ resultFrame('SUCCESS', 'PASS'),
305
+ '',
306
+ ].join('\n');
113
307
 
114
- const res = await run(
308
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: stream });
309
+ const res = await run({ ...task, onStdout: c => log.push(c) }, fake.exec);
310
+
311
+ expect(res).toEqual({ ok: true, response: 'PASS', exitCode: 0 });
312
+ expect(log.join('')).toContain('draft\n');
313
+ expect(log.join('')).toContain('PASS\n');
314
+ });
315
+
316
+ it('drops reasoning / thinking step_type from log and answer', async () => {
317
+ const log: string[] = [];
318
+ const stream = [
319
+ JSON.stringify({ event: 'init' }),
320
+ stepUpdate('reasoning', 'secret thinking'),
321
+ stepUpdate('agent_response', 'PASS', 'DONE'),
322
+ resultFrame('SUCCESS', 'PASS'),
323
+ '',
324
+ ].join('\n');
325
+
326
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: stream });
327
+ const res = await run({ ...task, onStdout: c => log.push(c) }, fake.exec);
328
+
329
+ expect(res).toEqual({ ok: true, response: 'PASS', exitCode: 0 });
330
+ expect(log.join('')).not.toContain('secret thinking');
331
+ expect(log.join('')).toBe('PASS\n');
332
+ });
333
+
334
+ it('batches many tiny agent-response deltas (bounded onStdout calls)', async () => {
335
+ let stdoutCallCount = 0;
336
+ const chunks: string[] = [`${JSON.stringify({ event: 'init' })}\n`];
337
+ for (let i = 0; i < 50; i++) {
338
+ chunks.push(`${stepUpdate('agent_response', `part${i}`)}\n`);
339
+ }
340
+ chunks.push(`${stepUpdate('agent_response', '\n', 'DONE')}\n`);
341
+ chunks.push(`${resultFrame('SUCCESS', 'all parts')}\n`);
342
+
343
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: chunks.join('') });
344
+ await run(
115
345
  {
116
- prompt: 'test',
117
- tools: false,
118
- timeoutSec: 10,
119
- cwd: '/test/cwd',
120
- backendModel: 'gemini-3.7-flash-high',
346
+ ...task,
347
+ onStdout: () => {
348
+ stdoutCallCount++;
349
+ },
121
350
  },
122
- fakeExec,
351
+ fake.exec,
123
352
  );
124
353
 
354
+ // Should flush only when newline/DONE/result hit, far fewer than 50 calls
355
+ expect(stdoutCallCount).toBeLessThan(10);
356
+ });
357
+
358
+ it('flushes an unterminated last NDJSON line', async () => {
359
+ const log: string[] = [];
360
+ const stream = `${JSON.stringify({ event: 'init' })}\n${resultFrame('SUCCESS', 'Done.')}`;
361
+
362
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: stream });
363
+ const res = await run({ ...task, onStdout: c => log.push(c) }, fake.exec);
364
+
365
+ expect(res).toEqual({ ok: true, response: 'Done.', exitCode: 0 });
366
+ expect(log.join('')).toBe('Done.\n');
367
+ });
368
+
369
+ it('passes non-protocol output through to log and uses as raw fallback', async () => {
370
+ const log: string[] = [];
371
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: 'not logged in\n', code: 1 });
372
+ const res = await run({ ...task, onStdout: c => log.push(c) }, fake.exec);
373
+
374
+ expect(res.ok).toBe(false);
375
+ expect(log.join('')).toBe('not logged in\n');
376
+ if (!res.ok) {
377
+ expect(res.kind).toBe('no-answer');
378
+ expect(JSON.stringify(res)).not.toContain('event');
379
+ }
380
+ });
381
+
382
+ it('strips ANSI prefixes before classifying result frame', async () => {
383
+ const stream = `\x1b[33m${resultFrame('SUCCESS', 'ANSI_OK')}\x1b[0m\n`;
384
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: stream });
385
+ const res = await run(task, fake.exec);
386
+
387
+ expect(res).toEqual({ ok: true, response: 'ANSI_OK', exitCode: 0 });
388
+ });
389
+
390
+ it('returns explicit no-answer when pre-protocol raw output exceeds 8192 chars', async () => {
391
+ const longRaw = `${'A'.repeat(5000)}\n${'B'.repeat(4000)}\n`;
392
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: longRaw });
393
+ const res = await run(task, fake.exec);
394
+
395
+ expect(res.ok).toBe(false);
396
+ if (!res.ok) {
397
+ expect(res.kind).toBe('no-answer');
398
+ expect(res.message).toContain(
399
+ 'returned more than 8192 characters without a recognized stream protocol',
400
+ );
401
+ }
402
+ });
403
+
404
+ it('valid result wins even after a long raw preamble > 8192 chars', async () => {
405
+ const longRawWithResult = [
406
+ 'A'.repeat(5000),
407
+ 'B'.repeat(4000),
408
+ resultFrame('SUCCESS', 'VALID_RESULT'),
409
+ '',
410
+ ].join('\n');
411
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: longRawWithResult });
412
+ const res = await run(task, fake.exec);
413
+
414
+ expect(res).toEqual({ ok: true, response: 'VALID_RESULT', exitCode: 0 });
415
+ });
416
+ });
417
+
418
+ describe('agy tools stream-json parsing', () => {
419
+ const task = {
420
+ prompt: 'tool task',
421
+ tools: true,
422
+ timeoutSec: 30,
423
+ cwd: '/work',
424
+ backendModel: 'gemini-3.7-flash-high',
425
+ };
426
+
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
+ it('logs tool ACTIVE and DONE concisely without dumping heavy payloads', async () => {
464
+ const log: string[] = [];
465
+ const stream = [
466
+ JSON.stringify({ event: 'init' }),
467
+ JSON.stringify({
468
+ event: 'step_update',
469
+ step_update: {
470
+ state: 'ACTIVE',
471
+ tool_name: 'read_file',
472
+ tool_info: { output: '10k'.repeat(5000) },
473
+ },
474
+ }),
475
+ JSON.stringify({
476
+ event: 'step_update',
477
+ step_update: {
478
+ state: 'DONE',
479
+ tool_name: 'read_file',
480
+ tool_info: { summary: 'read 100 lines from foo.ts', output: 'huge payload' },
481
+ },
482
+ }),
483
+ JSON.stringify({ event: 'result', result: { status: 'SUCCESS', response: 'done' } }),
484
+ '',
485
+ ].join('\n');
486
+
487
+ const fake = fakeAgy({ version: 'agy 1.2.3', stdout: stream });
488
+ const res = await run({ ...task, onStdout: c => log.push(c) }, fake.exec);
489
+
490
+ expect(res).toEqual({ ok: true, response: 'done', exitCode: 0 });
491
+ const logStr = log.join('');
492
+ expect(logStr).toContain('tool read_file\n');
493
+ expect(logStr).toContain('tool read_file done: read 100 lines from foo.ts\n');
494
+ expect(logStr).not.toContain('huge payload');
495
+ expect(logStr).not.toContain('10k10k');
496
+ });
497
+ });
498
+
499
+ describe('agy timeout and error handling', () => {
500
+ const task = {
501
+ prompt: 'test prompt',
502
+ tools: false,
503
+ timeoutSec: 1,
504
+ cwd: '/work',
505
+ backendModel: 'gemini-3.7-flash-high',
506
+ };
507
+
508
+ it('maps soft print-timeout stderr on stream path to timeout with ~1s message', async () => {
509
+ const stderr = '[agy] print timeout after 1s with turn in progress; returning partial output\n';
510
+ const stream = [
511
+ JSON.stringify({ event: 'init' }),
512
+ JSON.stringify({ event: 'result', result: { status: 'SUCCESS', response: 'partial' } }),
513
+ '',
514
+ ].join('\n');
515
+
516
+ const fake = fakeAgy({
517
+ version: 'agy 1.2.3',
518
+ stdout: stream,
519
+ stderr,
520
+ code: 0,
521
+ });
522
+
523
+ const res = await run(task, fake.exec);
524
+
125
525
  expect(res.ok).toBe(false);
126
526
  if (!res.ok) {
127
527
  expect(res.kind).toBe('timeout');
128
- expect(res.exitCode).toBeNull();
528
+ expect(res.message).toBe('aibridge: agy timed out after ~1s; raise --timeout.');
129
529
  }
130
530
  });
131
531
 
132
- it('maps no-answer when stdout is empty and no answer file', async () => {
133
- const fakeExec = async (): Promise<RunResult> => {
134
- return { code: 0, signal: null, stdout: '', stderr: 'error details', timedOut: false };
135
- };
532
+ it('maps soft print-timeout stderr on 1.2.2 text path to timeout', async () => {
533
+ const stderr = '[agy] print timeout after 1s with turn in progress; returning partial output\n';
534
+ const fake = fakeAgy({
535
+ version: 'agy 1.2.2',
536
+ stdout: 'partial',
537
+ stderr,
538
+ code: 0,
539
+ });
136
540
 
137
- const res = await run(
138
- {
139
- prompt: 'test',
140
- tools: false,
141
- timeoutSec: 10,
142
- cwd: '/test/cwd',
143
- backendModel: 'gemini-3.7-flash-high',
144
- },
145
- fakeExec,
146
- );
541
+ const res = await run(task, fake.exec);
542
+
543
+ expect(res.ok).toBe(false);
544
+ if (!res.ok) {
545
+ expect(res.kind).toBe('timeout');
546
+ expect(res.message).toBe('aibridge: agy timed out after ~1s; raise --timeout.');
547
+ }
548
+ });
549
+
550
+ it('answer file wins over soft print-timeout stderr in tools mode', async () => {
551
+ 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
+ });
558
+
559
+ const res = await run({ ...task, tools: true }, fake.exec);
560
+
561
+ expect(res).toEqual({ ok: true, response: 'Full finished answer', exitCode: 0 });
562
+ });
563
+
564
+ it('ERROR result frame overrides a non-empty answer file even with exit 0', async () => {
565
+ const stream = [
566
+ JSON.stringify({ event: 'init' }),
567
+ JSON.stringify({
568
+ event: 'result',
569
+ result: { status: 'ERROR', response: '', error: 'provider failed after writing file' },
570
+ }),
571
+ '',
572
+ ].join('\n');
573
+ const fake = fakeAgy({
574
+ version: 'agy 1.2.3',
575
+ stdout: stream,
576
+ code: 0,
577
+ writeAnswerFile: 'Apparently finished answer',
578
+ });
579
+
580
+ const res = await run({ ...task, tools: true }, fake.exec);
581
+
582
+ expect(res.ok).toBe(false);
583
+ if (!res.ok) {
584
+ expect(res.kind).toBe('no-answer');
585
+ expect(res.message).toContain('provider failed after writing file');
586
+ }
587
+ });
588
+
589
+ it('does not trigger soft timeout if stderr does not match exact terminal [agy] line or code != 0', async () => {
590
+ const stderr =
591
+ 'mid-stream [agy] print timeout after 1s with turn in progress; returning partial output\nsome other error\n';
592
+ const stream = [
593
+ JSON.stringify({ event: 'init' }),
594
+ JSON.stringify({ event: 'result', result: { status: 'SUCCESS', response: 'ok answer' } }),
595
+ '',
596
+ ].join('\n');
597
+
598
+ const fake = fakeAgy({
599
+ version: 'agy 1.2.3',
600
+ stdout: stream,
601
+ stderr,
602
+ code: 0,
603
+ });
604
+
605
+ const res = await run(task, fake.exec);
606
+ expect(res).toEqual({ ok: true, response: 'ok answer', exitCode: 0 });
607
+ });
608
+
609
+ it('maps hard process timedOut to timeout with ~21s message', async () => {
610
+ const fake = fakeAgy({
611
+ version: 'agy 1.2.3',
612
+ timedOut: true,
613
+ code: null,
614
+ });
615
+
616
+ const res = await run(task, fake.exec);
617
+
618
+ expect(res.ok).toBe(false);
619
+ if (!res.ok) {
620
+ expect(res.kind).toBe('timeout');
621
+ expect(res.message).toBe('aibridge: agy timed out after ~21s; raise --timeout.');
622
+ }
623
+ });
624
+
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
+ it('maps exit 1, error stderr, and ERROR frame to no-answer with detail', async () => {
643
+ const stderr = 'error: unknown model foo\n';
644
+ const stream = [
645
+ JSON.stringify({ event: 'init' }),
646
+ JSON.stringify({ event: 'result', result: { status: 'ERROR', error: 'unknown model foo' } }),
647
+ '',
648
+ ].join('\n');
649
+
650
+ const fake = fakeAgy({
651
+ version: 'agy 1.2.3',
652
+ stdout: stream,
653
+ stderr,
654
+ code: 1,
655
+ });
656
+
657
+ const res = await run(task, fake.exec);
147
658
 
148
659
  expect(res.ok).toBe(false);
149
660
  if (!res.ok) {
150
661
  expect(res.kind).toBe('no-answer');
151
- expect(res.exitCode).toBe(0);
662
+ expect(res.message).toContain('unknown model foo');
663
+ expect(JSON.stringify(res)).not.toContain('event');
664
+ }
665
+ });
666
+
667
+ it('maps empty SUCCESS with exit 0 and no print-timeout stderr to no-answer (quota death)', async () => {
668
+ const stream = [
669
+ JSON.stringify({ event: 'init' }),
670
+ JSON.stringify({ event: 'result', result: { status: 'SUCCESS', response: '' } }),
671
+ '',
672
+ ].join('\n');
673
+
674
+ const fake = fakeAgy({
675
+ version: 'agy 1.2.3',
676
+ stdout: stream,
677
+ code: 0,
678
+ });
679
+
680
+ const res = await run(task, fake.exec);
681
+
682
+ expect(res.ok).toBe(false);
683
+ if (!res.ok) {
684
+ expect(res.kind).toBe('no-answer');
685
+ }
686
+ });
687
+ });
688
+
689
+ describe('agy spawn failure handling', () => {
690
+ const task = {
691
+ prompt: 'test',
692
+ tools: false,
693
+ timeoutSec: 10,
694
+ cwd: '/work',
695
+ backendModel: 'gemini-3.7-flash-high',
696
+ };
697
+
698
+ it('maps ENOENT spawn error to not-found', async () => {
699
+ const err = new Error('spawn agy ENOENT') as Error & { code?: string };
700
+ err.code = 'ENOENT';
701
+ const fake = fakeAgy({ execError: err });
702
+
703
+ const res = await run(task, fake.exec);
704
+
705
+ expect(res.ok).toBe(false);
706
+ if (!res.ok) {
707
+ expect(res.kind).toBe('not-found');
708
+ expect(res.exitCode).toBeNull();
709
+ }
710
+ });
711
+
712
+ it('maps version probe EACCES rejection to kind: spawn without escaping', async () => {
713
+ const err = new Error('spawn agy EACCES') as Error & { code?: string };
714
+ err.code = 'EACCES';
715
+ const fake = fakeAgy({ versionError: err });
716
+
717
+ const res = await run(task, fake.exec);
718
+
719
+ expect(res.ok).toBe(false);
720
+ if (!res.ok) {
721
+ expect(res.kind).toBe('spawn');
722
+ expect(res.message).toContain('EACCES');
723
+ expect(res.exitCode).toBeNull();
152
724
  }
153
725
  });
154
726
  });