@juanbenjumea/pi-agy 0.5.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.
@@ -0,0 +1,594 @@
1
+ import { createRequire } from "node:module";
2
+
3
+ const _require = createRequire(import.meta.url);
4
+
5
+ import type { ChildProcess } from "node:child_process";
6
+ import { readFile } from "node:fs/promises";
7
+ import * as path from "node:path";
8
+
9
+ import {
10
+ accumulateRunResult,
11
+ appendStreamChunk,
12
+ finalizeRunResult,
13
+ formatStepProgress,
14
+ parseStreamLine,
15
+ type AgyProgressHandler,
16
+ type AgyRunResult,
17
+ type AgyStreamLine,
18
+ } from "./stream.js";
19
+
20
+ export { detectVerifyCommand } from "./verify.js";
21
+ export { parseJsonResponse } from "./parse.js";
22
+
23
+ const INSTALL_HINT = "Install agy: curl -fsSL https://antigravity.google/cli/install.sh | bash";
24
+
25
+ export type AgyModel =
26
+ | "flash-low"
27
+ | "flash-medium"
28
+ | "flash-high"
29
+ | "pro-low"
30
+ | "pro-high"
31
+ | "sonnet"
32
+ | "opus"
33
+ | "gpt-oss";
34
+
35
+ export const AGY_MODEL_ALIASES: readonly AgyModel[] = [
36
+ "flash-low",
37
+ "flash-medium",
38
+ "flash-high",
39
+ "pro-low",
40
+ "pro-high",
41
+ "sonnet",
42
+ "opus",
43
+ "gpt-oss",
44
+ ];
45
+
46
+ export function isAgyModel(value: unknown): value is AgyModel {
47
+ return typeof value === "string" && (AGY_MODEL_ALIASES as readonly string[]).includes(value);
48
+ }
49
+
50
+ export type AgyEffort = "low" | "medium" | "high";
51
+
52
+ export interface AgyOptions {
53
+ prompt: string;
54
+ model?: AgyModel;
55
+ tier?: "flash" | "flash-lo" | "pro";
56
+ effort?: AgyEffort;
57
+ mode?: "plan" | "accept-edits" | "sandbox";
58
+ dir: string;
59
+ timeout_ms: number;
60
+ conversation_id?: string;
61
+ continue?: boolean;
62
+ stream?: boolean;
63
+ skipPermissions?: boolean;
64
+ }
65
+
66
+ const PREFLIGHT_TIMEOUT_MS = 10_000;
67
+ // Raw stdout capture bound; only used as the non-streaming fallback — the
68
+ // stream-json path accumulates results incrementally and is not capped by it.
69
+ const MAX_CAPTURE_BYTES = 64 * 1024;
70
+ // Preview/experimental model ids must never win catalog resolution implicitly.
71
+ const UNSTABLE_MODEL_PATTERN = /(?:preview|experimental|beta|alpha|\brc\b|snapshot|\bnext\b)/i;
72
+
73
+ // Static fallback for when `agy models` output is unavailable. The live
74
+ // catalog (updated during preflight) overrides these per alias.
75
+ const MODEL_MAP: Record<AgyModel, string> = {
76
+ "flash-low": "gemini-3.8-flash-low",
77
+ "flash-medium": "gemini-3.8-flash-medium",
78
+ "flash-high": "gemini-3.8-flash-high",
79
+ "pro-low": "gemini-3.1-pro-low",
80
+ "pro-high": "gemini-3.1-pro-high",
81
+ sonnet: "claude-sonnet-4-6",
82
+ opus: "claude-opus-4-6-thinking",
83
+ "gpt-oss": "gpt-oss-120b-medium",
84
+ };
85
+
86
+ const TIER_MAP: Record<NonNullable<AgyOptions["tier"]>, AgyModel> = {
87
+ flash: "flash-high",
88
+ "flash-lo": "flash-low",
89
+ pro: "pro-high",
90
+ };
91
+
92
+ /** alias → pattern matching concrete model ids in `agy models` output. */
93
+ const UNSTABLE_SUFFIX = "(?:-(?:preview|experimental|beta|alpha|rc\\d*|snapshot|next))*";
94
+ const CATALOG_PATTERNS: Record<AgyModel, RegExp> = {
95
+ "flash-low": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-flash-low${UNSTABLE_SUFFIX}$`),
96
+ "flash-medium": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-flash-medium${UNSTABLE_SUFFIX}$`),
97
+ "flash-high": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-flash-high${UNSTABLE_SUFFIX}$`),
98
+ "pro-low": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-pro-low${UNSTABLE_SUFFIX}$`),
99
+ "pro-high": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-pro-high${UNSTABLE_SUFFIX}$`),
100
+ sonnet: /^claude-sonnet-[\w.-]+$/,
101
+ opus: /^claude-opus-[\w.-]+$/,
102
+ "gpt-oss": /^gpt-oss-[\w.-]+$/,
103
+ };
104
+
105
+ export type AgyModelCatalog = Partial<Record<AgyModel, string>>;
106
+
107
+ let modelCatalog: AgyModelCatalog = {};
108
+
109
+ export function isStableModelId(id: string): boolean {
110
+ return !UNSTABLE_MODEL_PATTERN.test(id);
111
+ }
112
+
113
+ /**
114
+ * Parse `agy models` output into alias → concrete model id. Newer model
115
+ * generations win over older ones so aliases track the latest catalog.
116
+ * Preview/experimental ids are ignored unless `allowPreview` is set, so an
117
+ * unstable catalog entry can never silently become the default model.
118
+ */
119
+ export function parseModelCatalog(output: string, allowPreview = false): AgyModelCatalog {
120
+ const allow = allowPreview || process.env.PI_AGY_ALLOW_PREVIEW === "1";
121
+ const found: AgyModelCatalog = {};
122
+ for (const line of output.split("\n")) {
123
+ const id = line.trim().split(/\s+/)[0] ?? "";
124
+ if (!id) continue;
125
+ if (!allow && !isStableModelId(id)) continue;
126
+ for (const [alias, pattern] of Object.entries(CATALOG_PATTERNS) as Array<[AgyModel, RegExp]>) {
127
+ if (pattern.test(id) && compareModelIds(id, found[alias] ?? "") > 0) {
128
+ found[alias] = id;
129
+ }
130
+ }
131
+ }
132
+ return found;
133
+ }
134
+
135
+ function compareModelIds(a: string, b: string): number {
136
+ if (!b) return 1;
137
+ const versionA = /^gemini-(\d+(?:\.\d+)*)-/.exec(a)?.[1];
138
+ const versionB = /^gemini-(\d+(?:\.\d+)*)-/.exec(b)?.[1];
139
+ if (versionA && versionB) return compareDottedVersions(versionA, versionB);
140
+ // Numeric-aware compare so claude-sonnet-4-10 sorts above claude-sonnet-4-6.
141
+ return compareNatural(a, b);
142
+ }
143
+
144
+ function compareNatural(a: string, b: string): number {
145
+ const sa = a.split(/(\d+)/);
146
+ const sb = b.split(/(\d+)/);
147
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
148
+ const pa = sa[i] ?? "";
149
+ const pb = sb[i] ?? "";
150
+ if (pa === pb) continue;
151
+ if (/^\d+$/.test(pa) && /^\d+$/.test(pb)) {
152
+ const na = Number(pa);
153
+ const nb = Number(pb);
154
+ if (na !== nb) return na < nb ? -1 : 1;
155
+ }
156
+ return pa < pb ? -1 : 1;
157
+ }
158
+ return 0;
159
+ }
160
+
161
+ function compareDottedVersions(a: string, b: string): number {
162
+ const pa = a.split(".").map(Number);
163
+ const pb = b.split(".").map(Number);
164
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
165
+ const delta = (pa[i] ?? 0) - (pb[i] ?? 0);
166
+ if (delta !== 0) return delta;
167
+ }
168
+ return 0;
169
+ }
170
+
171
+ /** Merge freshly observed catalog entries over the in-process catalog. */
172
+ export function updateModelCatalog(catalog: AgyModelCatalog): void {
173
+ modelCatalog = { ...modelCatalog, ...catalog };
174
+ }
175
+
176
+ export function getModelCatalog(): AgyModelCatalog {
177
+ return { ...modelCatalog };
178
+ }
179
+
180
+ /** Test helper — drop in-process catalog state. */
181
+ export function resetModelCatalog(): void {
182
+ modelCatalog = {};
183
+ }
184
+
185
+ /** Resolve explicit model or legacy tier to the internal alias. */
186
+ export function resolveAgyModelAlias(
187
+ model?: AgyModel,
188
+ tier?: AgyOptions["tier"],
189
+ ): AgyModel | undefined {
190
+ return model ?? (tier ? TIER_MAP[tier] : undefined);
191
+ }
192
+
193
+ /** Resolve a model alias to a concrete agy model id, preferring the live catalog. */
194
+ export function resolveAgyModelId(model?: AgyModel, tier?: AgyOptions["tier"]): string {
195
+ const alias = resolveAgyModelAlias(model, tier) ?? "flash-medium";
196
+ return modelCatalog[alias] ?? MODEL_MAP[alias];
197
+ }
198
+
199
+ const TRANSIENT_FAILURE_PATTERN =
200
+ /rate.?limit|429|overloaded|temporarily unavailable|network|connection (reset|refused)|econnreset|etimedout|socket hang up|\b50[023]\b/i;
201
+
202
+ /** Heuristic for transient agy failures that are safe to retry once. */
203
+ export function isTransientAgyFailure(message: string): boolean {
204
+ return TRANSIENT_FAILURE_PATTERN.test(message);
205
+ }
206
+
207
+ export function buildAgyArgs(options: AgyOptions): string[] {
208
+ if (options.continue && options.conversation_id) {
209
+ throw new Error("agy cannot use --continue and --conversation together");
210
+ }
211
+
212
+ const model = resolveAgyModelId(options.model, options.tier);
213
+ const timeoutSec = Math.ceil(options.timeout_ms / 1000);
214
+ const mode = options.mode ?? "accept-edits";
215
+ const writes = mode === "accept-edits";
216
+ const skipPermissions = options.skipPermissions ?? true;
217
+ const useStream = options.stream ?? true;
218
+ const structured = mode !== "accept-edits" || useStream;
219
+
220
+ const args = [
221
+ "--model",
222
+ model,
223
+ "--print-timeout",
224
+ `${timeoutSec}s`,
225
+ "--add-dir",
226
+ options.dir,
227
+ // Task text must never be interpreted as agy slash commands or skills.
228
+ "--disable-slash-commands",
229
+ ...(mode === "sandbox" ? ["--sandbox"] : ["--mode", mode]),
230
+ ...(writes && skipPermissions ? ["--dangerously-skip-permissions"] : []),
231
+ ...(options.effort ? ["--effort", options.effort] : []),
232
+ ];
233
+
234
+ if (options.continue) {
235
+ args.push("--continue");
236
+ } else if (options.conversation_id) {
237
+ args.push("--conversation", options.conversation_id);
238
+ }
239
+
240
+ if (structured) {
241
+ args.push("--output-format", useStream ? "stream-json" : "json");
242
+ }
243
+
244
+ args.push("-p", options.prompt);
245
+ return args;
246
+ }
247
+
248
+ export function buildAgyPrompt(
249
+ prompt: string,
250
+ mode: "plan" | "accept-edits" | "sandbox",
251
+ useDigest: boolean,
252
+ verifyCmd: string | null,
253
+ ): string {
254
+ const lines: string[] = [];
255
+ if (mode === "plan") lines.push("Explore and produce an implementation plan only; do not edit.");
256
+ else if (mode === "sandbox") lines.push("Work inside the sandbox; changes are isolated for preview.");
257
+ else if (verifyCmd) lines.push(`After editing, run \`${verifyCmd}\` and fix failures until it passes.`);
258
+ if (useDigest) lines.push("Use compact digests, not full file contents.");
259
+ lines.push(prompt);
260
+ return lines.join("\n");
261
+ }
262
+
263
+ function getSpawn() {
264
+ return _require("node:child_process").spawn;
265
+ }
266
+
267
+ function appendBounded(chunks: Buffer[], total: number, data: Buffer): number {
268
+ const remaining = MAX_CAPTURE_BYTES - total;
269
+ if (remaining > 0) chunks.push(data.subarray(0, remaining));
270
+ return Math.min(MAX_CAPTURE_BYTES, total + data.length);
271
+ }
272
+
273
+ export async function checkAgyHealth(
274
+ cwd: string,
275
+ signal?: AbortSignal,
276
+ timeoutMs?: number,
277
+ ): Promise<void> {
278
+ await runPreflightCommand(["--version"], cwd, signal, "agy health check", false, timeoutMs);
279
+ }
280
+
281
+ export async function checkAgyConnectivity(
282
+ cwd: string,
283
+ signal?: AbortSignal,
284
+ timeoutMs?: number,
285
+ ): Promise<void> {
286
+ const output = await runPreflightCommand(
287
+ ["models"],
288
+ cwd,
289
+ signal,
290
+ "agy connectivity check",
291
+ true,
292
+ timeoutMs,
293
+ );
294
+ const catalog = parseModelCatalog(output);
295
+ if (Object.keys(catalog).length > 0) updateModelCatalog(catalog);
296
+ }
297
+
298
+ /**
299
+ * Terminate a spawned agy process and any tools it started. Node's `signal`
300
+ * and `timeout` spawn options only kill the direct child, so cancel/timeout
301
+ * must kill the whole process group — otherwise a nested tool can keep
302
+ * modifying files after Pi reported cancellation.
303
+ */
304
+ export function killProcessTree(child: ChildProcess): void {
305
+ try {
306
+ if (child.exitCode !== null || child.signalCode !== null) return;
307
+ if (child.pid && process.platform !== "win32") {
308
+ try {
309
+ process.kill(-child.pid, "SIGTERM");
310
+ } catch {
311
+ child.kill("SIGTERM");
312
+ }
313
+ } else {
314
+ child.kill("SIGTERM");
315
+ }
316
+ } catch {
317
+ return;
318
+ }
319
+ const escalate = setTimeout(() => {
320
+ try {
321
+ if (child.exitCode === null && child.signalCode === null) {
322
+ if (child.pid && process.platform !== "win32") {
323
+ try {
324
+ process.kill(-child.pid, "SIGKILL");
325
+ return;
326
+ } catch {
327
+ // Fall through to direct kill.
328
+ }
329
+ }
330
+ child.kill("SIGKILL");
331
+ }
332
+ } catch {
333
+ // Best effort: the close handler reports the real outcome.
334
+ }
335
+ }, 2000);
336
+ (escalate as unknown as { unref?: () => void }).unref?.();
337
+ }
338
+
339
+ async function runPreflightCommand(
340
+ args: string[],
341
+ cwd: string,
342
+ signal: AbortSignal | undefined,
343
+ label: string,
344
+ capture: boolean,
345
+ timeoutMs?: number,
346
+ ): Promise<string> {
347
+ if (signal?.aborted) throw new Error(`${label} was cancelled`);
348
+ const spawn = getSpawn();
349
+ const timeout = Math.max(1, Math.min(PREFLIGHT_TIMEOUT_MS, timeoutMs ?? PREFLIGHT_TIMEOUT_MS));
350
+ const child = spawn("agy", args, {
351
+ cwd,
352
+ stdio: ["ignore", capture ? "pipe" : "ignore", "pipe"],
353
+ // Managed manually below so cancellation kills the process group.
354
+ detached: process.platform !== "win32",
355
+ });
356
+ let timedOut = false;
357
+ const onAbort = () => killProcessTree(child);
358
+ signal?.addEventListener("abort", onAbort, { once: true });
359
+ const timer = setTimeout(() => {
360
+ timedOut = true;
361
+ killProcessTree(child);
362
+ }, timeout);
363
+ (timer as unknown as { unref?: () => void }).unref?.();
364
+
365
+ const stderr: Buffer[] = [];
366
+ let stderrBytes = 0;
367
+ child.stderr.on("data", (d: Buffer) => {
368
+ stderrBytes = appendBounded(stderr, stderrBytes, d);
369
+ });
370
+
371
+ const stdout: Buffer[] = [];
372
+ let stdoutBytes = 0;
373
+ if (capture) {
374
+ child.stdout?.on("data", (d: Buffer) => {
375
+ stdoutBytes = appendBounded(stdout, stdoutBytes, d);
376
+ });
377
+ }
378
+
379
+ let settled = false;
380
+
381
+ await new Promise<void>((resolve, reject) => {
382
+ const done = (fn: () => void) => {
383
+ if (settled) return;
384
+ settled = true;
385
+ clearTimeout(timer);
386
+ signal?.removeEventListener("abort", onAbort);
387
+ fn();
388
+ };
389
+
390
+ child.on("error", (err: Error) => {
391
+ done(() => {
392
+ if (signal?.aborted && !timedOut) reject(new Error(`${label} was cancelled`));
393
+ else if (timedOut) reject(new Error(`${label} timed out`));
394
+ else if ((err as NodeJS.ErrnoException).code === "ENOENT") {
395
+ reject(new Error(`Antigravity CLI is not installed. ${INSTALL_HINT}`));
396
+ } else reject(new Error(`${label} failed: ${err.message}`));
397
+ });
398
+ });
399
+
400
+ child.on("close", (code: number | null) => {
401
+ done(() => {
402
+ if (signal?.aborted && !timedOut) {
403
+ reject(new Error(`${label} was cancelled`));
404
+ return;
405
+ }
406
+ if (code === 0 && !timedOut) resolve();
407
+ else if (timedOut || code === null) {
408
+ reject(new Error(`${label} timed out`));
409
+ } else {
410
+ const msg = Buffer.concat(stderr).toString("utf8").trim();
411
+ const status = `exit ${code}`;
412
+ const authHint =
413
+ args[0] === "--version"
414
+ ? "Antigravity CLI is not authenticated or not working"
415
+ : "agy connectivity check failed";
416
+ reject(new Error(`${authHint} (${status}). ${msg || "Run 'agy' interactively to authenticate."}`));
417
+ }
418
+ });
419
+ });
420
+ });
421
+
422
+ const stdoutText = capture ? Buffer.concat(stdout).toString("utf8") : "";
423
+ // Stdout only: stderr diagnostics must never leak into catalog parsing.
424
+ return stdoutText;
425
+ }
426
+
427
+ export function getAgyConversationId(error: unknown): string | undefined {
428
+ if (typeof error !== "object" || error === null) return undefined;
429
+ const conversationId = (error as { conversation_id?: unknown }).conversation_id;
430
+ return typeof conversationId === "string" ? conversationId : undefined;
431
+ }
432
+
433
+ export function spawnAgy(options: AgyOptions, signal: AbortSignal): Promise<string> {
434
+ return spawnAgyInternal(options, signal).then((result) => result.response);
435
+ }
436
+
437
+ /** Real agy work (tool steps / model responses), as opposed to lifecycle chatter. */
438
+ function isActivityProgress(parsed: AgyStreamLine): boolean {
439
+ const step = parsed.step_update;
440
+ return step?.step_type === "tool" || step?.step_type === "agent_response";
441
+ }
442
+
443
+ export function spawnAgyStream(
444
+ options: AgyOptions,
445
+ signal: AbortSignal,
446
+ onProgress?: AgyProgressHandler,
447
+ ): Promise<AgyRunResult> {
448
+ return spawnAgyInternal(options, signal, onProgress);
449
+ }
450
+
451
+ function spawnAgyInternal(
452
+ options: AgyOptions,
453
+ signal: AbortSignal,
454
+ onProgress?: AgyProgressHandler,
455
+ ): Promise<AgyRunResult> {
456
+ const spawn = getSpawn();
457
+ const args = buildAgyArgs(options);
458
+ // The parent process owns the hard deadline; agy's second-based timeout is
459
+ // rounded up, so do not add grace time here.
460
+ const alignedTimeout = Math.max(1, options.timeout_ms);
461
+
462
+ return new Promise<AgyRunResult>((resolve, reject) => {
463
+ if (signal.aborted) {
464
+ reject(withConversationId("agy was cancelled", { response: "" }));
465
+ return;
466
+ }
467
+ const child = spawn("agy", args, {
468
+ cwd: options.dir,
469
+ stdio: ["ignore", "pipe", "pipe"],
470
+ // Managed manually so abort/timeout kills nested tool processes too.
471
+ detached: process.platform !== "win32",
472
+ });
473
+ let timedOut = false;
474
+ const onAbort = () => killProcessTree(child);
475
+ signal.addEventListener("abort", onAbort, { once: true });
476
+ const timer = setTimeout(() => {
477
+ timedOut = true;
478
+ killProcessTree(child);
479
+ }, alignedTimeout);
480
+ (timer as unknown as { unref?: () => void }).unref?.();
481
+
482
+ const stdout: Buffer[] = [];
483
+ const stderr: Buffer[] = [];
484
+ let stdoutBytes = 0;
485
+ let stderrBytes = 0;
486
+ let lineBuffer = "";
487
+ let runResult: AgyRunResult = { response: "" };
488
+
489
+ child.stdout.on("data", (d: Buffer) => {
490
+ stdoutBytes = appendBounded(stdout, stdoutBytes, d);
491
+ const chunk = appendStreamChunk(lineBuffer, d.toString("utf8"), onProgress);
492
+ lineBuffer = chunk.lineBuffer;
493
+ for (const line of chunk.lines) {
494
+ runResult = processStreamLine(line, runResult, onProgress);
495
+ }
496
+ });
497
+
498
+ child.stderr.on("data", (d: Buffer) => {
499
+ stderrBytes = appendBounded(stderr, stderrBytes, d);
500
+ });
501
+
502
+ let settled = false;
503
+ const done = (fn: () => void) => {
504
+ if (settled) return;
505
+ settled = true;
506
+ clearTimeout(timer);
507
+ signal.removeEventListener("abort", onAbort);
508
+ fn();
509
+ };
510
+
511
+ child.on("error", (err: Error) => {
512
+ done(() => {
513
+ const message =
514
+ signal.aborted && !timedOut
515
+ ? "agy was cancelled"
516
+ : timedOut
517
+ ? "agy timed out"
518
+ : (err as NodeJS.ErrnoException).code === "ENOENT"
519
+ ? `Antigravity CLI not found in PATH. ${INSTALL_HINT}`
520
+ : `agy spawn failed: ${err.message}`;
521
+ reject(withConversationId(message, runResult));
522
+ });
523
+ });
524
+
525
+ child.on("close", (code: number | null, sig: string | null) => {
526
+ done(() => {
527
+ const out = Buffer.concat(stdout).toString("utf8");
528
+ const err = Buffer.concat(stderr).toString("utf8");
529
+
530
+ // JSONL producers normally terminate every record with a newline, but
531
+ // process failures can leave the final record unterminated. Parse it
532
+ // before handling the exit code so retry logic sees real activity and
533
+ // users still receive the terminal progress update. The remainder is
534
+ // bounded by appendStreamChunk, so no length check is needed here.
535
+ if (lineBuffer.trim()) {
536
+ runResult = processStreamLine(lineBuffer, runResult, onProgress);
537
+ }
538
+
539
+ if (sig === "SIGTERM" || sig === "SIGKILL" || code === null) {
540
+ reject(
541
+ withConversationId(
542
+ signal.aborted && !timedOut ? "agy was cancelled" : "agy timed out",
543
+ runResult,
544
+ ),
545
+ );
546
+ return;
547
+ }
548
+
549
+ if (code !== 0) {
550
+ const detail = (err || out).slice(0, 2000).trim();
551
+ reject(withConversationId(`agy exited with code ${code}:\n${detail || "(no output)"}`, runResult));
552
+ return;
553
+ }
554
+
555
+ // agy writes diagnostics to stderr even on successful runs. Keep it
556
+ // out of the response so JSON/stream parsing remains deterministic.
557
+ resolve(finalizeRunResult(out, runResult));
558
+ });
559
+ });
560
+ });
561
+ }
562
+
563
+ function withConversationId(message: string, runResult: AgyRunResult): Error {
564
+ const error = new Error(message) as Error & { conversation_id?: string };
565
+ if (runResult.conversation_id) error.conversation_id = runResult.conversation_id;
566
+ return error;
567
+ }
568
+
569
+ function processStreamLine(
570
+ line: string,
571
+ current: AgyRunResult,
572
+ onProgress?: AgyProgressHandler,
573
+ ): AgyRunResult {
574
+ const parsed = parseStreamLine(line);
575
+ if (!parsed) return current;
576
+
577
+ const next = accumulateRunResult(parsed, current);
578
+ const activity = isActivityProgress(parsed);
579
+ const progress = formatStepProgress(parsed);
580
+ if (progress) onProgress?.(progress, activity ? "activity" : "status");
581
+ else if (activity) onProgress?.("agy: working…", "activity");
582
+ return next;
583
+ }
584
+
585
+ // Re-export for tests that imported detectVerifyCommand from cli in upstream.
586
+ export async function detectVerifyCommandFromPackageJson(cwd: string): Promise<string | null> {
587
+ try {
588
+ const pkg = JSON.parse(await readFile(path.join(cwd, "package.json"), "utf8"));
589
+ if (pkg?.scripts?.test) return "npm test";
590
+ } catch {
591
+ // ignore
592
+ }
593
+ return null;
594
+ }