@aibridge/driver-agy 0.9.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/run.ts CHANGED
@@ -1,8 +1,5 @@
1
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
- import { isNotFound, type RunResult, runCaptured, stripAnsi } from '@aibridge/proc';
5
- import { buildAgyPrintArgs } from './agy.ts';
1
+ import { isNotFound, probeVersion, type RunResult, runCaptured, stripAnsi } from '@aibridge/proc';
2
+ import { agySupportsStreamJson, buildAgyPrintArgs } from './agy.ts';
6
3
  import { INSTALL_HINT } from './probe.ts';
7
4
 
8
5
  export interface DelegationTask {
@@ -15,6 +12,7 @@ export interface DelegationTask {
15
12
  readonly onStdout?: (chunk: string) => void;
16
13
  readonly onStderr?: (chunk: string) => void;
17
14
  readonly onSpawn?: (pid: number) => void;
15
+ readonly onActivity?: () => void;
18
16
  }
19
17
 
20
18
  export type DelegationResult =
@@ -27,99 +25,391 @@ export type DelegationResult =
27
25
  };
28
26
 
29
27
  const NOISE_RE = /^Shell cwd was reset[^\n]*$/gm;
28
+ const MESSAGE_STREAM_ARGS = ['--output-format', 'stream-json'] as const;
29
+ const RAW_FALLBACK_MAX_CHARS = 8192;
30
+ const READABLE_LOG_FLUSH_CHARS = 4096;
31
+ const AGY_PRINT_TIMEOUT_RE =
32
+ /^\[agy\] print timeout after \S+ with turn in progress; returning partial output\s*$/i;
33
+ const TOOL_SUMMARY_MAX = 200;
30
34
 
31
35
  function clean(s: string): string {
32
36
  return stripAnsi(s).replace(NOISE_RE, '').trim();
33
37
  }
34
38
 
39
+ type StreamLine =
40
+ | { readonly kind: 'init' }
41
+ | {
42
+ readonly kind: 'step';
43
+ readonly state: string | undefined;
44
+ readonly stepType: string | undefined;
45
+ readonly textDelta: string | undefined;
46
+ readonly toolName: string | undefined;
47
+ readonly toolInfo: unknown;
48
+ }
49
+ | {
50
+ readonly kind: 'result';
51
+ readonly status: string | undefined;
52
+ readonly response: string | undefined;
53
+ readonly error: string | undefined;
54
+ }
55
+ | { readonly kind: 'frame' }
56
+ | { readonly kind: 'raw'; readonly line: string }
57
+ | { readonly kind: 'blank' };
58
+
59
+ function classifyLine(line: string): StreamLine {
60
+ const trimmed = line.trim();
61
+ if (trimmed.length === 0) return { kind: 'blank' };
62
+ if (!trimmed.startsWith('{')) return { kind: 'raw', line };
63
+
64
+ let parsed: unknown;
65
+ try {
66
+ parsed = JSON.parse(trimmed);
67
+ } catch {
68
+ return { kind: 'raw', line };
69
+ }
70
+
71
+ if (
72
+ typeof parsed !== 'object' ||
73
+ parsed === null ||
74
+ !('event' in parsed) ||
75
+ typeof (parsed as { event?: unknown }).event !== 'string'
76
+ ) {
77
+ return { kind: 'raw', line };
78
+ }
79
+
80
+ const event = (parsed as { event: string }).event;
81
+ if (event === 'init') {
82
+ return { kind: 'init' };
83
+ }
84
+
85
+ if (event === 'step_update') {
86
+ const stepUpdate = (parsed as { step_update?: unknown }).step_update;
87
+ if (typeof stepUpdate === 'object' && stepUpdate !== null) {
88
+ const su = stepUpdate as {
89
+ state?: unknown;
90
+ step_type?: unknown;
91
+ text_delta?: unknown;
92
+ tool_name?: unknown;
93
+ tool_info?: unknown;
94
+ };
95
+ return {
96
+ kind: 'step',
97
+ state: typeof su.state === 'string' ? su.state : undefined,
98
+ stepType: typeof su.step_type === 'string' ? su.step_type : undefined,
99
+ textDelta: typeof su.text_delta === 'string' ? su.text_delta : undefined,
100
+ toolName: typeof su.tool_name === 'string' ? su.tool_name : undefined,
101
+ toolInfo: su.tool_info,
102
+ };
103
+ }
104
+ return {
105
+ kind: 'step',
106
+ state: undefined,
107
+ stepType: undefined,
108
+ textDelta: undefined,
109
+ toolName: undefined,
110
+ toolInfo: undefined,
111
+ };
112
+ }
113
+
114
+ if (event === 'result') {
115
+ const res = (parsed as { result?: unknown }).result;
116
+ if (typeof res === 'object' && res !== null) {
117
+ const r = res as { status?: unknown; response?: unknown; error?: unknown };
118
+ return {
119
+ kind: 'result',
120
+ status: typeof r.status === 'string' ? r.status : undefined,
121
+ response: typeof r.response === 'string' ? r.response : undefined,
122
+ error: typeof r.error === 'string' ? r.error : undefined,
123
+ };
124
+ }
125
+ return {
126
+ kind: 'result',
127
+ status: undefined,
128
+ response: undefined,
129
+ error: undefined,
130
+ };
131
+ }
132
+
133
+ return { kind: 'frame' };
134
+ }
135
+
136
+ function formatToolSummary(toolInfo: unknown): string | null {
137
+ if (typeof toolInfo !== 'object' || toolInfo === null) return null;
138
+ const obj = toolInfo as Record<string, unknown>;
139
+ const raw =
140
+ typeof obj.summary === 'string'
141
+ ? obj.summary
142
+ : typeof obj.message === 'string'
143
+ ? obj.message
144
+ : null;
145
+ if (!raw) return null;
146
+ const firstLine = raw.split('\n')[0]?.trim();
147
+ if (!firstLine) return null;
148
+ return firstLine.slice(0, TOOL_SUMMARY_MAX);
149
+ }
150
+
151
+ interface StreamSnapshot {
152
+ readonly sawProtocol: boolean;
153
+ readonly text: string | null;
154
+ readonly resultStatus: string | null;
155
+ readonly resultError: string | null;
156
+ readonly rawFallback: string;
157
+ readonly rawTruncated: boolean;
158
+ }
159
+
160
+ interface LogForwarder {
161
+ readonly onChunk: (chunk: string) => void;
162
+ readonly flush: () => void;
163
+ readonly snapshot: () => StreamSnapshot;
164
+ }
165
+
166
+ function logForwarder(
167
+ onStdout: ((chunk: string) => void) | undefined,
168
+ onActivity: (() => void) | undefined,
169
+ ): LogForwarder {
170
+ let pending = '';
171
+ let readableBuffer = '';
172
+ let loggedAgentText = '';
173
+ let sawProtocol = false;
174
+ let resultStatus: string | null = null;
175
+ let resultResponse: string | null = null;
176
+ let resultError: string | null = null;
177
+ let rawFallback = '';
178
+ let rawTruncated = false;
179
+
180
+ const flushReadable = (): void => {
181
+ if (readableBuffer.length === 0) return;
182
+ const toSend = readableBuffer.endsWith('\n') ? readableBuffer : `${readableBuffer}\n`;
183
+ readableBuffer = '';
184
+ onStdout?.(toSend);
185
+ };
186
+
187
+ const emit = (rawLine: string): void => {
188
+ const line = stripAnsi(rawLine);
189
+ const classified = classifyLine(line);
190
+
191
+ if (classified.kind === 'blank') {
192
+ return;
193
+ }
194
+
195
+ if (classified.kind === 'init' || classified.kind === 'frame') {
196
+ sawProtocol = true;
197
+ return;
198
+ }
199
+
200
+ if (classified.kind === 'step') {
201
+ sawProtocol = true;
202
+ if (classified.stepType === 'agent_response' && classified.textDelta) {
203
+ loggedAgentText += classified.textDelta;
204
+ readableBuffer += classified.textDelta;
205
+ if (readableBuffer.includes('\n') || readableBuffer.length >= READABLE_LOG_FLUSH_CHARS) {
206
+ flushReadable();
207
+ }
208
+ }
209
+
210
+ if (classified.state === 'DONE' && classified.stepType === 'agent_response') {
211
+ if (readableBuffer.length > 0 && !readableBuffer.endsWith('\n')) {
212
+ readableBuffer += '\n';
213
+ }
214
+ flushReadable();
215
+ }
216
+
217
+ if (classified.toolName) {
218
+ flushReadable();
219
+ if (classified.state === 'ACTIVE') {
220
+ onStdout?.(`tool ${classified.toolName}\n`);
221
+ } else if (classified.state === 'DONE') {
222
+ const summary = formatToolSummary(classified.toolInfo);
223
+ if (summary) {
224
+ onStdout?.(`tool ${classified.toolName} done: ${summary}\n`);
225
+ } else {
226
+ onStdout?.(`tool ${classified.toolName} done\n`);
227
+ }
228
+ }
229
+ }
230
+ return;
231
+ }
232
+
233
+ if (classified.kind === 'result') {
234
+ sawProtocol = true;
235
+ resultStatus = classified.status ?? null;
236
+ resultResponse = classified.response ?? null;
237
+ resultError = classified.error ?? null;
238
+
239
+ flushReadable();
240
+
241
+ if (classified.response && classified.response.length > 0) {
242
+ const cleanResp = clean(classified.response);
243
+ const cleanLogged = clean(loggedAgentText);
244
+ if (cleanResp.length > 0 && !cleanLogged.endsWith(cleanResp)) {
245
+ readableBuffer += classified.response;
246
+ flushReadable();
247
+ }
248
+ }
249
+ return;
250
+ }
251
+
252
+ if (classified.kind === 'raw') {
253
+ flushReadable();
254
+ onStdout?.(`${rawLine}\n`);
255
+ if (!sawProtocol) {
256
+ if (!rawTruncated) {
257
+ const candidate = `${rawLine}\n`;
258
+ if (rawFallback.length + candidate.length > RAW_FALLBACK_MAX_CHARS) {
259
+ rawTruncated = true;
260
+ } else {
261
+ rawFallback += candidate;
262
+ }
263
+ }
264
+ }
265
+ }
266
+ };
267
+
268
+ return {
269
+ onChunk: (chunk: string): void => {
270
+ onActivity?.();
271
+ pending += chunk;
272
+ for (let nl = pending.indexOf('\n'); nl !== -1; nl = pending.indexOf('\n')) {
273
+ emit(pending.slice(0, nl));
274
+ pending = pending.slice(nl + 1);
275
+ }
276
+ },
277
+ flush: (): void => {
278
+ if (pending.length > 0) {
279
+ const line = pending;
280
+ pending = '';
281
+ emit(line);
282
+ }
283
+ flushReadable();
284
+ },
285
+ snapshot: (): StreamSnapshot => ({
286
+ sawProtocol,
287
+ text: resultResponse && resultResponse.length > 0 ? resultResponse : null,
288
+ resultStatus,
289
+ resultError,
290
+ rawFallback,
291
+ rawTruncated,
292
+ }),
293
+ };
294
+ }
295
+
35
296
  export async function run(
36
297
  task: DelegationTask,
37
298
  exec: typeof runCaptured = runCaptured,
38
299
  ): Promise<DelegationResult> {
39
- let tempDir: string | undefined;
40
- let answerPath: string | undefined;
41
-
42
- let taskPrompt = task.prompt;
43
- const addDirs: string[] = [];
44
-
45
- if (task.tools) {
46
- tempDir = mkdtempSync(join(tmpdir(), 'aibridge-agy-'));
47
- answerPath = join(tempDir, 'answer.md');
48
- taskPrompt =
49
- `${task.prompt}\n\nYou are working in the repository rooted at ${task.cwd}; make ALL file ` +
50
- `edits there (any relative paths in the task are relative to that root). When the task ` +
51
- `is complete, write ONLY your final answer (the exact text you would otherwise print as ` +
52
- `your response, with no narration of your steps) to the file ${answerPath} — nothing else ` +
53
- `in that file. This is how your answer is captured; do not mention the file in the answer.`;
54
- addDirs.push(task.cwd, tempDir);
55
- }
300
+ // agy ignores its spawn cwd and treats the first --add-dir as the workspace.
301
+ const addDirs = task.tools ? [task.cwd] : undefined;
56
302
 
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
- });
303
+ let result: RunResult;
304
+ let useStreamJson = false;
305
+ let forwarder: LogForwarder | undefined;
63
306
 
64
307
  try {
65
- let result: RunResult;
66
- try {
308
+ const version = await probeVersion('agy', exec);
309
+ useStreamJson = agySupportsStreamJson(version);
310
+ if (!useStreamJson) {
311
+ task.onStderr?.(
312
+ `aibridge: agy version ${version ?? 'unavailable'} does not support stream-json (requires >= 1.2.3); using text compatibility mode.\n`,
313
+ );
314
+ }
315
+
316
+ const args = [
317
+ ...buildAgyPrintArgs(task.prompt, {
318
+ model: task.backendModel,
319
+ printTimeoutSec: task.timeoutSec,
320
+ skipPermissions: task.tools,
321
+ addDirs,
322
+ }),
323
+ ...(useStreamJson ? MESSAGE_STREAM_ARGS : []),
324
+ ];
325
+
326
+ if (useStreamJson) {
327
+ forwarder = logForwarder(task.onStdout, task.onActivity);
67
328
  result = await exec('agy', args, {
68
329
  cwd: task.cwd,
69
330
  timeoutMs: (task.timeoutSec + 20) * 1000,
70
- onStdout: task.onStdout,
331
+ captureStdout: false,
332
+ onStdout: forwarder.onChunk,
71
333
  onStderr: task.onStderr,
72
334
  onSpawn: task.onSpawn,
73
335
  });
74
- } catch (err) {
75
- if (isNotFound(err)) {
76
- return {
77
- ok: false,
78
- kind: 'not-found',
79
- message: `aibridge: "agy" not found on PATH. ${INSTALL_HINT}`,
80
- exitCode: null,
81
- };
82
- }
336
+ } else {
337
+ result = await exec('agy', args, {
338
+ cwd: task.cwd,
339
+ timeoutMs: (task.timeoutSec + 20) * 1000,
340
+ onStdout: chunk => {
341
+ task.onActivity?.();
342
+ task.onStdout?.(chunk);
343
+ },
344
+ onStderr: task.onStderr,
345
+ onSpawn: task.onSpawn,
346
+ });
347
+ }
348
+ } catch (err) {
349
+ if (isNotFound(err)) {
83
350
  return {
84
351
  ok: false,
85
- kind: 'spawn',
86
- message: `aibridge: failed to run agy: ${(err as Error).message}`,
352
+ kind: 'not-found',
353
+ message: `aibridge: "agy" not found on PATH. ${INSTALL_HINT}`,
87
354
  exitCode: null,
88
355
  };
89
356
  }
357
+ return {
358
+ ok: false,
359
+ kind: 'spawn',
360
+ message: `aibridge: failed to run agy: ${(err as Error).message}`,
361
+ exitCode: null,
362
+ };
363
+ }
90
364
 
91
- if (result.timedOut) {
92
- return {
93
- ok: false,
94
- kind: 'timeout',
95
- message: `aibridge: agy timed out after ~${task.timeoutSec + 20}s; raise --timeout.`,
96
- exitCode: result.code,
97
- };
98
- }
365
+ forwarder?.flush();
99
366
 
100
- let response = '';
101
- if (answerPath && existsSync(answerPath)) {
102
- response = clean(readFileSync(answerPath, 'utf8'));
103
- if (response.length > 0) {
104
- task.onStdout?.(`\n--- final answer ---\n${response}\n`);
105
- }
106
- }
107
- if (response.length === 0) {
108
- response = clean(result.stdout);
109
- }
367
+ if (result.timedOut) {
368
+ return {
369
+ ok: false,
370
+ kind: 'timeout',
371
+ message: `aibridge: agy timed out after ~${task.timeoutSec + 20}s; raise --timeout.`,
372
+ exitCode: result.code,
373
+ };
374
+ }
110
375
 
111
- if (result.code !== 0 || response.length === 0) {
112
- const detail = clean(result.stderr) || `exit code ${result.code}`;
113
- return {
114
- ok: false,
115
- kind: 'no-answer',
116
- message: `aibridge: agy returned no usable answer (${detail}).`,
117
- exitCode: result.code,
118
- };
119
- }
376
+ const stderrLines = stripAnsi(result.stderr)
377
+ .split('\n')
378
+ .map(l => l.trim())
379
+ .filter(l => l.length > 0);
380
+ const lastStderrLine = stderrLines[stderrLines.length - 1] ?? '';
381
+ if (result.code === 0 && AGY_PRINT_TIMEOUT_RE.test(lastStderrLine)) {
382
+ return {
383
+ ok: false,
384
+ kind: 'timeout',
385
+ message: `aibridge: agy timed out after ~${task.timeoutSec}s; raise --timeout.`,
386
+ exitCode: result.code,
387
+ };
388
+ }
389
+
390
+ const snap = useStreamJson && forwarder ? forwarder.snapshot() : undefined;
391
+ const resolvedAnswer = snap
392
+ ? clean(snap.text ?? (snap.sawProtocol || snap.rawTruncated ? '' : snap.rawFallback))
393
+ : clean(result.stdout);
120
394
 
121
- return { ok: true, response, exitCode: result.code ?? 0 };
122
- } finally {
123
- if (tempDir) rmSync(tempDir, { recursive: true, force: true });
395
+ if (snap && !snap.sawProtocol && snap.rawTruncated && resolvedAnswer.length === 0) {
396
+ return {
397
+ ok: false,
398
+ kind: 'no-answer',
399
+ message: `aibridge: agy returned more than ${RAW_FALLBACK_MAX_CHARS} characters without a recognized stream protocol; see the run log.`,
400
+ exitCode: result.code,
401
+ };
124
402
  }
403
+
404
+ if (snap?.resultStatus === 'ERROR' || result.code !== 0 || resolvedAnswer.length === 0) {
405
+ const detail = clean(snap?.resultError || result.stderr) || `exit code ${result.code}`;
406
+ return {
407
+ ok: false,
408
+ kind: 'no-answer',
409
+ message: `aibridge: agy returned no usable answer (${detail}).`,
410
+ exitCode: result.code,
411
+ };
412
+ }
413
+
414
+ return { ok: true, response: resolvedAnswer, exitCode: result.code ?? 0 };
125
415
  }