@aibridge/driver-agy 0.9.2 → 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.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
- import { isNotFound, type RunResult, runCaptured, stripAnsi } from '@aibridge/proc';
5
- import { buildAgyPrintArgs } from './agy.ts';
4
+ import { isNotFound, probeVersion, type RunResult, runCaptured, stripAnsi } from '@aibridge/proc';
5
+ import { agySupportsStreamJson, buildAgyPrintArgs } from './agy.ts';
6
6
  import { INSTALL_HINT } from './probe.ts';
7
7
 
8
8
  export interface DelegationTask {
@@ -15,6 +15,7 @@ export interface DelegationTask {
15
15
  readonly onStdout?: (chunk: string) => void;
16
16
  readonly onStderr?: (chunk: string) => void;
17
17
  readonly onSpawn?: (pid: number) => void;
18
+ readonly onActivity?: () => void;
18
19
  }
19
20
 
20
21
  export type DelegationResult =
@@ -27,11 +28,274 @@ export type DelegationResult =
27
28
  };
28
29
 
29
30
  const NOISE_RE = /^Shell cwd was reset[^\n]*$/gm;
31
+ const MESSAGE_STREAM_ARGS = ['--output-format', 'stream-json'] as const;
32
+ const RAW_FALLBACK_MAX_CHARS = 8192;
33
+ const READABLE_LOG_FLUSH_CHARS = 4096;
34
+ const AGY_PRINT_TIMEOUT_RE =
35
+ /^\[agy\] print timeout after \S+ with turn in progress; returning partial output\s*$/i;
36
+ const TOOL_SUMMARY_MAX = 200;
30
37
 
31
38
  function clean(s: string): string {
32
39
  return stripAnsi(s).replace(NOISE_RE, '').trim();
33
40
  }
34
41
 
42
+ type StreamLine =
43
+ | { readonly kind: 'init' }
44
+ | {
45
+ readonly kind: 'step';
46
+ readonly state: string | undefined;
47
+ readonly stepType: string | undefined;
48
+ readonly textDelta: string | undefined;
49
+ readonly toolName: string | undefined;
50
+ readonly toolInfo: unknown;
51
+ }
52
+ | {
53
+ readonly kind: 'result';
54
+ readonly status: string | undefined;
55
+ readonly response: string | undefined;
56
+ readonly error: string | undefined;
57
+ }
58
+ | { readonly kind: 'frame' }
59
+ | { readonly kind: 'raw'; readonly line: string }
60
+ | { readonly kind: 'blank' };
61
+
62
+ function classifyLine(line: string): StreamLine {
63
+ const trimmed = line.trim();
64
+ if (trimmed.length === 0) return { kind: 'blank' };
65
+ if (!trimmed.startsWith('{')) return { kind: 'raw', line };
66
+
67
+ let parsed: unknown;
68
+ try {
69
+ parsed = JSON.parse(trimmed);
70
+ } catch {
71
+ return { kind: 'raw', line };
72
+ }
73
+
74
+ if (
75
+ typeof parsed !== 'object' ||
76
+ parsed === null ||
77
+ !('event' in parsed) ||
78
+ typeof (parsed as { event?: unknown }).event !== 'string'
79
+ ) {
80
+ return { kind: 'raw', line };
81
+ }
82
+
83
+ const event = (parsed as { event: string }).event;
84
+ if (event === 'init') {
85
+ return { kind: 'init' };
86
+ }
87
+
88
+ if (event === 'step_update') {
89
+ const stepUpdate = (parsed as { step_update?: unknown }).step_update;
90
+ if (typeof stepUpdate === 'object' && stepUpdate !== null) {
91
+ const su = stepUpdate as {
92
+ state?: unknown;
93
+ step_type?: unknown;
94
+ text_delta?: unknown;
95
+ tool_name?: unknown;
96
+ tool_info?: unknown;
97
+ };
98
+ return {
99
+ kind: 'step',
100
+ state: typeof su.state === 'string' ? su.state : undefined,
101
+ stepType: typeof su.step_type === 'string' ? su.step_type : undefined,
102
+ textDelta: typeof su.text_delta === 'string' ? su.text_delta : undefined,
103
+ toolName: typeof su.tool_name === 'string' ? su.tool_name : undefined,
104
+ toolInfo: su.tool_info,
105
+ };
106
+ }
107
+ return {
108
+ kind: 'step',
109
+ state: undefined,
110
+ stepType: undefined,
111
+ textDelta: undefined,
112
+ toolName: undefined,
113
+ toolInfo: undefined,
114
+ };
115
+ }
116
+
117
+ if (event === 'result') {
118
+ const res = (parsed as { result?: unknown }).result;
119
+ if (typeof res === 'object' && res !== null) {
120
+ const r = res as { status?: unknown; response?: unknown; error?: unknown };
121
+ return {
122
+ kind: 'result',
123
+ status: typeof r.status === 'string' ? r.status : undefined,
124
+ response: typeof r.response === 'string' ? r.response : undefined,
125
+ error: typeof r.error === 'string' ? r.error : undefined,
126
+ };
127
+ }
128
+ return {
129
+ kind: 'result',
130
+ status: undefined,
131
+ response: undefined,
132
+ error: undefined,
133
+ };
134
+ }
135
+
136
+ return { kind: 'frame' };
137
+ }
138
+
139
+ function formatToolSummary(toolInfo: unknown): string | null {
140
+ if (typeof toolInfo !== 'object' || toolInfo === null) return null;
141
+ const obj = toolInfo as Record<string, unknown>;
142
+ const raw =
143
+ typeof obj.summary === 'string'
144
+ ? obj.summary
145
+ : typeof obj.message === 'string'
146
+ ? obj.message
147
+ : null;
148
+ if (!raw) return null;
149
+ const firstLine = raw.split('\n')[0]?.trim();
150
+ if (!firstLine) return null;
151
+ return firstLine.slice(0, TOOL_SUMMARY_MAX);
152
+ }
153
+
154
+ interface StreamSnapshot {
155
+ readonly sawProtocol: boolean;
156
+ readonly text: string | null;
157
+ readonly resultStatus: string | null;
158
+ readonly resultError: string | null;
159
+ readonly rawFallback: string;
160
+ readonly rawTruncated: boolean;
161
+ }
162
+
163
+ interface LogForwarder {
164
+ readonly onChunk: (chunk: string) => void;
165
+ readonly flush: () => void;
166
+ readonly snapshot: () => StreamSnapshot;
167
+ }
168
+
169
+ function logForwarder(
170
+ onStdout: ((chunk: string) => void) | undefined,
171
+ onActivity: (() => void) | undefined,
172
+ ): LogForwarder {
173
+ let pending = '';
174
+ let readableBuffer = '';
175
+ let loggedAgentText = '';
176
+ let sawProtocol = false;
177
+ let resultStatus: string | null = null;
178
+ let resultResponse: string | null = null;
179
+ let resultError: string | null = null;
180
+ let rawFallback = '';
181
+ let rawTruncated = false;
182
+
183
+ const flushReadable = (): void => {
184
+ if (readableBuffer.length === 0) return;
185
+ const toSend = readableBuffer.endsWith('\n') ? readableBuffer : `${readableBuffer}\n`;
186
+ readableBuffer = '';
187
+ onStdout?.(toSend);
188
+ };
189
+
190
+ const emit = (rawLine: string): void => {
191
+ const line = stripAnsi(rawLine);
192
+ const classified = classifyLine(line);
193
+
194
+ if (classified.kind === 'blank') {
195
+ return;
196
+ }
197
+
198
+ if (classified.kind === 'init' || classified.kind === 'frame') {
199
+ sawProtocol = true;
200
+ return;
201
+ }
202
+
203
+ if (classified.kind === 'step') {
204
+ sawProtocol = true;
205
+ if (classified.stepType === 'agent_response' && classified.textDelta) {
206
+ loggedAgentText += classified.textDelta;
207
+ readableBuffer += classified.textDelta;
208
+ if (readableBuffer.includes('\n') || readableBuffer.length >= READABLE_LOG_FLUSH_CHARS) {
209
+ flushReadable();
210
+ }
211
+ }
212
+
213
+ if (classified.state === 'DONE' && classified.stepType === 'agent_response') {
214
+ if (readableBuffer.length > 0 && !readableBuffer.endsWith('\n')) {
215
+ readableBuffer += '\n';
216
+ }
217
+ flushReadable();
218
+ }
219
+
220
+ if (classified.toolName) {
221
+ flushReadable();
222
+ if (classified.state === 'ACTIVE') {
223
+ onStdout?.(`tool ${classified.toolName}\n`);
224
+ } else if (classified.state === 'DONE') {
225
+ const summary = formatToolSummary(classified.toolInfo);
226
+ if (summary) {
227
+ onStdout?.(`tool ${classified.toolName} done: ${summary}\n`);
228
+ } else {
229
+ onStdout?.(`tool ${classified.toolName} done\n`);
230
+ }
231
+ }
232
+ }
233
+ return;
234
+ }
235
+
236
+ if (classified.kind === 'result') {
237
+ sawProtocol = true;
238
+ resultStatus = classified.status ?? null;
239
+ resultResponse = classified.response ?? null;
240
+ resultError = classified.error ?? null;
241
+
242
+ flushReadable();
243
+
244
+ if (classified.response && classified.response.length > 0) {
245
+ const cleanResp = clean(classified.response);
246
+ const cleanLogged = clean(loggedAgentText);
247
+ if (cleanResp.length > 0 && !cleanLogged.endsWith(cleanResp)) {
248
+ readableBuffer += classified.response;
249
+ flushReadable();
250
+ }
251
+ }
252
+ return;
253
+ }
254
+
255
+ if (classified.kind === 'raw') {
256
+ flushReadable();
257
+ onStdout?.(`${rawLine}\n`);
258
+ if (!sawProtocol) {
259
+ if (!rawTruncated) {
260
+ const candidate = `${rawLine}\n`;
261
+ if (rawFallback.length + candidate.length > RAW_FALLBACK_MAX_CHARS) {
262
+ rawTruncated = true;
263
+ } else {
264
+ rawFallback += candidate;
265
+ }
266
+ }
267
+ }
268
+ }
269
+ };
270
+
271
+ return {
272
+ onChunk: (chunk: string): void => {
273
+ onActivity?.();
274
+ pending += chunk;
275
+ for (let nl = pending.indexOf('\n'); nl !== -1; nl = pending.indexOf('\n')) {
276
+ emit(pending.slice(0, nl));
277
+ pending = pending.slice(nl + 1);
278
+ }
279
+ },
280
+ flush: (): void => {
281
+ if (pending.length > 0) {
282
+ const line = pending;
283
+ pending = '';
284
+ emit(line);
285
+ }
286
+ flushReadable();
287
+ },
288
+ snapshot: (): StreamSnapshot => ({
289
+ sawProtocol,
290
+ text: resultResponse && resultResponse.length > 0 ? resultResponse : null,
291
+ resultStatus,
292
+ resultError,
293
+ rawFallback,
294
+ rawTruncated,
295
+ }),
296
+ };
297
+ }
298
+
35
299
  export async function run(
36
300
  task: DelegationTask,
37
301
  exec: typeof runCaptured = runCaptured,
@@ -54,23 +318,52 @@ export async function run(
54
318
  addDirs.push(task.cwd, tempDir);
55
319
  }
56
320
 
57
- const args = buildAgyPrintArgs(taskPrompt, {
58
- model: task.backendModel,
59
- printTimeoutSec: task.timeoutSec,
60
- skipPermissions: task.tools,
61
- addDirs: addDirs.length > 0 ? addDirs : undefined,
62
- });
63
-
64
321
  try {
65
322
  let result: RunResult;
323
+ let useStreamJson = false;
324
+ let forwarder: LogForwarder | undefined;
325
+
66
326
  try {
67
- result = await exec('agy', args, {
68
- cwd: task.cwd,
69
- timeoutMs: (task.timeoutSec + 20) * 1000,
70
- onStdout: task.onStdout,
71
- onStderr: task.onStderr,
72
- onSpawn: task.onSpawn,
73
- });
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
+ }
334
+
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
+ }
74
367
  } catch (err) {
75
368
  if (isNotFound(err)) {
76
369
  return {
@@ -88,6 +381,8 @@ export async function run(
88
381
  };
89
382
  }
90
383
 
384
+ forwarder?.flush();
385
+
91
386
  if (result.timedOut) {
92
387
  return {
93
388
  ok: false,
@@ -97,19 +392,58 @@ export async function run(
97
392
  };
98
393
  }
99
394
 
100
- let response = '';
395
+ let fileAnswer = '';
101
396
  if (answerPath && existsSync(answerPath)) {
102
- response = clean(readFileSync(answerPath, 'utf8'));
103
- if (response.length > 0) {
104
- task.onStdout?.(`\n--- final answer ---\n${response}\n`);
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;
409
+
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
+ }
426
+
427
+ if (snap) {
428
+ resolvedAnswer = clean(
429
+ snap.text ?? (snap.sawProtocol || snap.rawTruncated ? '' : snap.rawFallback),
430
+ );
431
+ } else {
432
+ resolvedAnswer = clean(result.stdout);
105
433
  }
106
434
  }
107
- if (response.length === 0) {
108
- response = clean(result.stdout);
435
+
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
+ };
109
443
  }
110
444
 
111
- if (result.code !== 0 || response.length === 0) {
112
- const detail = clean(result.stderr) || `exit code ${result.code}`;
445
+ if (resultStatus === 'ERROR' || result.code !== 0 || resolvedAnswer.length === 0) {
446
+ const detail = clean(resultError || result.stderr) || `exit code ${result.code}`;
113
447
  return {
114
448
  ok: false,
115
449
  kind: 'no-answer',
@@ -118,7 +452,7 @@ export async function run(
118
452
  };
119
453
  }
120
454
 
121
- return { ok: true, response, exitCode: result.code ?? 0 };
455
+ return { ok: true, response: resolvedAnswer, exitCode: result.code ?? 0 };
122
456
  } finally {
123
457
  if (tempDir) rmSync(tempDir, { recursive: true, force: true });
124
458
  }