@juanbenjumea/pi-agy 0.6.10 → 0.7.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.
@@ -2,6 +2,10 @@ import { keyHint, type Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { stripTerminalSequences, Text, truncateToWidth } from "@earendil-works/pi-tui";
3
3
 
4
4
  import type { AgyExecutionDetails } from "./execute.js";
5
+ import {
6
+ normalizeAgyDeniedActions,
7
+ summarizeAgyDeniedActions,
8
+ } from "./stream.js";
5
9
 
6
10
  export const AGY_RUN_ENTRY_TYPE = "agy-run-receipt";
7
11
 
@@ -47,6 +51,7 @@ function firstText(content: unknown): string {
47
51
 
48
52
  function stripSyntheticResultSections(value: string): string {
49
53
  const markers = [
54
+ "\n\n## agy denied actions",
50
55
  "\n\n## agy quota snapshot",
51
56
  "\n\n## agy subagents observed",
52
57
  "\n\n## git diff --stat",
@@ -140,6 +145,18 @@ function formatAgyResult(
140
145
  }
141
146
  if (metadata.length) lines.push(theme.fg("dim", metadata.join(" · ")));
142
147
 
148
+ const denied = normalizeAgyDeniedActions(details.denied_actions) ?? [];
149
+ if (denied.length) {
150
+ const count = `${denied.length} denied action${denied.length === 1 ? "" : "s"}`;
151
+ const summary = summarizeAgyDeniedActions(denied, 3);
152
+ lines.push(theme.fg("warning", `⚠ ${count}${summary ? ` · ${summary}` : ""}`));
153
+ if (expanded) {
154
+ for (const entry of denied) {
155
+ lines.push(theme.fg("toolOutput", `↳ denied ${summarizeAgyDeniedActions([entry], 1)}`));
156
+ }
157
+ }
158
+ }
159
+
143
160
  const subagents = Array.isArray(details.subagents) ? details.subagents.slice(0, 32) : [];
144
161
  if (subagents.length) {
145
162
  const done = subagents.filter((entry) => entry?.status === "done").length;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Transient-failure classification for agy runs.
3
+ *
4
+ * Split out of `lib/cli.ts`: pure string matching with no process or catalog
5
+ * state. `cli.ts` re-exports the classifier for existing importers.
6
+ */
7
+
8
+ const TRANSIENT_FAILURE_PATTERN =
9
+ /rate.?limit|resource[_ -]?exhausted|429|overloaded|temporarily unavailable|network|connection (reset|refused)|econnreset|etimedout|socket hang up|\b50[023]\b/i;
10
+
11
+ function parseStructuredRetryability(message: string): boolean | undefined {
12
+ for (const line of message.split(/\r?\n/)) {
13
+ const match = line.match(/^\s*AGY_ERROR:\s*(\{.*\})\s*$/);
14
+ if (!match) continue;
15
+ try {
16
+ const parsed: unknown = JSON.parse(match[1]);
17
+ if (
18
+ typeof parsed === "object" &&
19
+ parsed !== null &&
20
+ typeof (parsed as { retryable?: unknown }).retryable === "boolean"
21
+ ) {
22
+ return (parsed as { retryable: boolean }).retryable;
23
+ }
24
+ } catch {
25
+ // Malformed structured diagnostics fall back to legacy text matching.
26
+ }
27
+ }
28
+ return undefined;
29
+ }
30
+
31
+ /** Heuristic for transient agy failures that are safe to retry once. */
32
+ export function isTransientAgyFailure(message: string): boolean {
33
+ return parseStructuredRetryability(message) ?? TRANSIENT_FAILURE_PATTERN.test(message);
34
+ }
@@ -0,0 +1,411 @@
1
+ /**
2
+ * Process primitives for running the agy CLI.
3
+ *
4
+ * Split out of `lib/cli.ts`: child-process spawning, bounded output capture,
5
+ * process-tree termination, and the preflight command runner. No catalog,
6
+ * arg-building, or stream-parsing state — `cli.ts` imports `runPreflightCommand`
7
+ * for its inspect checks and re-exports `killProcessTree` for existing importers.
8
+ */
9
+
10
+ import { createRequire } from "node:module";
11
+
12
+ const _require = createRequire(import.meta.url);
13
+
14
+ import type { ChildProcess } from "node:child_process";
15
+
16
+ // Ported from upstream pi-agy 0.3.4: Windows ENOENT errors must not suggest
17
+ // a bash one-liner.
18
+ export const INSTALL_HINT =
19
+ process.platform === "win32"
20
+ ? "Install agy: irm https://antigravity.google/cli/install.ps1 | iex"
21
+ : "Install agy: curl -fsSL https://antigravity.google/cli/install.sh | bash";
22
+
23
+ const PREFLIGHT_TIMEOUT_MS = 10_000;
24
+ // Raw stdout capture bound; only the non-streaming/parse-failure fallback —
25
+ // the stream-json path accumulates results incrementally and is not capped by
26
+ // it. Large enough that plain-text fallbacks rarely truncate.
27
+ export const MAX_CAPTURE_BYTES = 1024 * 1024;
28
+
29
+ export function getSpawn() {
30
+ return _require("node:child_process").spawn;
31
+ }
32
+
33
+ export function appendBounded(chunks: Buffer[], total: number, data: Buffer): number {
34
+ const remaining = MAX_CAPTURE_BYTES - total;
35
+ if (remaining > 0) chunks.push(data.subarray(0, remaining));
36
+ return Math.min(MAX_CAPTURE_BYTES, total + data.length);
37
+ }
38
+
39
+ /**
40
+ * Terminate a spawned agy process and any tools it started. Node's `signal`
41
+ * and `timeout` spawn options only kill the direct child, so cancel/timeout
42
+ * must kill the whole process group — otherwise a nested tool can keep
43
+ * modifying files after Pi reported cancellation.
44
+ */
45
+ export function killProcessTree(child: ChildProcess): void {
46
+ try {
47
+ if (child.exitCode !== null || child.signalCode !== null) return;
48
+ if (child.pid && process.platform !== "win32") {
49
+ try {
50
+ process.kill(-child.pid, "SIGTERM");
51
+ } catch {
52
+ child.kill("SIGTERM");
53
+ }
54
+ } else {
55
+ child.kill("SIGTERM");
56
+ }
57
+ } catch {
58
+ return;
59
+ }
60
+ const escalate = setTimeout(() => {
61
+ try {
62
+ if (child.exitCode === null && child.signalCode === null) {
63
+ if (child.pid && process.platform !== "win32") {
64
+ try {
65
+ process.kill(-child.pid, "SIGKILL");
66
+ return;
67
+ } catch {
68
+ // Fall through to direct kill.
69
+ }
70
+ }
71
+ child.kill("SIGKILL");
72
+ }
73
+ } catch {
74
+ // Best effort: the close handler reports the real outcome.
75
+ }
76
+ }, 2000);
77
+ (escalate as unknown as { unref?: () => void }).unref?.();
78
+ }
79
+
80
+ export async function runPreflightCommand(
81
+ args: string[],
82
+ cwd: string,
83
+ signal: AbortSignal | undefined,
84
+ label: string,
85
+ capture: boolean,
86
+ timeoutMs?: number,
87
+ ): Promise<string> {
88
+ if (signal?.aborted) throw new Error(`${label} was cancelled`);
89
+ const spawn = getSpawn();
90
+ const timeout = Math.max(1, Math.min(PREFLIGHT_TIMEOUT_MS, timeoutMs ?? PREFLIGHT_TIMEOUT_MS));
91
+ const child = spawn("agy", args, {
92
+ cwd,
93
+ stdio: ["ignore", capture ? "pipe" : "ignore", "pipe"],
94
+ // Managed manually below so cancellation kills the process group.
95
+ detached: process.platform !== "win32",
96
+ });
97
+ let timedOut = false;
98
+ const onAbort = () => killProcessTree(child);
99
+ signal?.addEventListener("abort", onAbort, { once: true });
100
+ const timer = setTimeout(() => {
101
+ timedOut = true;
102
+ killProcessTree(child);
103
+ }, timeout);
104
+ (timer as unknown as { unref?: () => void }).unref?.();
105
+
106
+ const stderr: Buffer[] = [];
107
+ let stderrBytes = 0;
108
+ child.stderr.on("data", (d: Buffer) => {
109
+ stderrBytes = appendBounded(stderr, stderrBytes, d);
110
+ });
111
+
112
+ const stdout: Buffer[] = [];
113
+ let stdoutBytes = 0;
114
+ if (capture) {
115
+ child.stdout?.on("data", (d: Buffer) => {
116
+ stdoutBytes = appendBounded(stdout, stdoutBytes, d);
117
+ });
118
+ }
119
+
120
+ let settled = false;
121
+
122
+ await new Promise<void>((resolve, reject) => {
123
+ const done = (fn: () => void) => {
124
+ if (settled) return;
125
+ settled = true;
126
+ clearTimeout(timer);
127
+ signal?.removeEventListener("abort", onAbort);
128
+ fn();
129
+ };
130
+
131
+ child.on("error", (err: Error) => {
132
+ done(() => {
133
+ if (signal?.aborted && !timedOut) reject(new Error(`${label} was cancelled`));
134
+ else if (timedOut) reject(new Error(`${label} timed out`));
135
+ else if ((err as NodeJS.ErrnoException).code === "ENOENT") {
136
+ reject(new Error(`Antigravity CLI is not installed. ${INSTALL_HINT}`));
137
+ } else reject(new Error(`${label} failed: ${err.message}`));
138
+ });
139
+ });
140
+
141
+ child.on("close", (code: number | null) => {
142
+ done(() => {
143
+ if (signal?.aborted && !timedOut) {
144
+ reject(new Error(`${label} was cancelled`));
145
+ return;
146
+ }
147
+ if (code === 0 && !timedOut) resolve();
148
+ else if (timedOut || code === null) {
149
+ reject(new Error(`${label} timed out`));
150
+ } else {
151
+ const msg = Buffer.concat(stderr).toString("utf8").trim();
152
+ const status = `exit ${code}`;
153
+ // A failing --version probe usually means the CLI is present but
154
+ // not authenticated; every failure names the check that failed.
155
+ const authHint =
156
+ args[0] === "--version"
157
+ ? " — Antigravity CLI is not authenticated or not working"
158
+ : "";
159
+ reject(
160
+ new Error(
161
+ `${label} failed${authHint} (${status}). ${msg || "Run 'agy' interactively to authenticate."}`,
162
+ ),
163
+ );
164
+ }
165
+ });
166
+ });
167
+ });
168
+
169
+ const stdoutText = capture ? Buffer.concat(stdout).toString("utf8") : "";
170
+ // Stdout only: stderr diagnostics must never leak into catalog parsing.
171
+ return stdoutText;
172
+ }
173
+
174
+ import { StringDecoder } from "node:string_decoder";
175
+
176
+ import { buildAgyArgs } from "./args.js";
177
+ import {
178
+ accumulateRunResult,
179
+ appendStreamChunk,
180
+ finalizeRunResult,
181
+ formatStepProgress,
182
+ parseStreamLine,
183
+ summarizeAgyDeniedActions,
184
+ type AgyProgressHandler,
185
+ type AgyRunResult,
186
+ type AgyStreamLine,
187
+ } from "./stream.js";
188
+ import type { AgyOptions } from "./cli.js";
189
+
190
+ export function spawnAgy(options: AgyOptions, signal: AbortSignal): Promise<string> {
191
+ return spawnAgyInternal(options, signal).then((result) => result.response);
192
+ }
193
+
194
+ /** Real agy work (tool steps / model responses), as opposed to lifecycle chatter. */
195
+ function isActivityProgress(parsed: AgyStreamLine): boolean {
196
+ const step = parsed.step_update;
197
+ return (
198
+ step?.step_type === "tool" ||
199
+ step?.step_type === "subagent" ||
200
+ step?.step_type === "agent_response"
201
+ );
202
+ }
203
+
204
+ export function spawnAgyStream(
205
+ options: AgyOptions,
206
+ signal: AbortSignal,
207
+ onProgress?: AgyProgressHandler,
208
+ ): Promise<AgyRunResult> {
209
+ return spawnAgyInternal(options, signal, onProgress);
210
+ }
211
+
212
+ function spawnAgyInternal(
213
+ options: AgyOptions,
214
+ signal: AbortSignal,
215
+ onProgress?: AgyProgressHandler,
216
+ ): Promise<AgyRunResult> {
217
+ const spawn = getSpawn();
218
+ const args = buildAgyArgs(options);
219
+ // The parent process owns the hard deadline; agy's second-based timeout is
220
+ // rounded up, so do not add grace time here.
221
+ const alignedTimeout = Math.max(1, options.timeout_ms);
222
+
223
+ return new Promise<AgyRunResult>((resolve, reject) => {
224
+ if (signal.aborted) {
225
+ reject(withConversationId("agy was cancelled", { response: "" }));
226
+ return;
227
+ }
228
+ const child = spawn("agy", args, {
229
+ cwd: options.dir,
230
+ stdio: ["ignore", "pipe", "pipe"],
231
+ // Managed manually so abort/timeout kills nested tool processes too.
232
+ detached: process.platform !== "win32",
233
+ });
234
+ let timedOut = false;
235
+ const onAbort = () => killProcessTree(child);
236
+ signal.addEventListener("abort", onAbort, { once: true });
237
+ const timer = setTimeout(() => {
238
+ timedOut = true;
239
+ killProcessTree(child);
240
+ }, alignedTimeout);
241
+ (timer as unknown as { unref?: () => void }).unref?.();
242
+
243
+ const stdout: Buffer[] = [];
244
+ const stderr: Buffer[] = [];
245
+ let stdoutBytes = 0;
246
+ let stderrBytes = 0;
247
+ let stdoutTruncated = false;
248
+ let lineBuffer = "";
249
+ let runResult: AgyRunResult = { response: "" };
250
+ const decoder = new StringDecoder("utf8");
251
+
252
+ const processStdoutText = (text: string): void => {
253
+ if (!text) return;
254
+ const chunk = appendStreamChunk(lineBuffer, text, onProgress);
255
+ lineBuffer = chunk.lineBuffer;
256
+ for (const line of chunk.lines) {
257
+ runResult = processStreamLine(line, runResult, onProgress);
258
+ }
259
+ };
260
+
261
+ child.stdout.on("data", (d: Buffer) => {
262
+ const before = stdoutBytes;
263
+ stdoutBytes = appendBounded(stdout, stdoutBytes, d);
264
+ // The raw buffer is only a fallback; flag overflow so a verbatim
265
+ // response is never served as silently truncated text.
266
+ if (before + d.length > stdoutBytes) stdoutTruncated = true;
267
+ processStdoutText(decoder.write(d));
268
+ });
269
+
270
+ child.stderr.on("data", (d: Buffer) => {
271
+ stderrBytes = appendBounded(stderr, stderrBytes, d);
272
+ });
273
+
274
+ let settled = false;
275
+ const done = (fn: () => void) => {
276
+ if (settled) return;
277
+ settled = true;
278
+ clearTimeout(timer);
279
+ signal.removeEventListener("abort", onAbort);
280
+ fn();
281
+ };
282
+
283
+ child.on("error", (err: Error) => {
284
+ done(() => {
285
+ const message =
286
+ signal.aborted && !timedOut
287
+ ? "agy was cancelled"
288
+ : timedOut
289
+ ? "agy timed out"
290
+ : (err as NodeJS.ErrnoException).code === "ENOENT"
291
+ ? `Antigravity CLI not found in PATH. ${INSTALL_HINT}`
292
+ : `agy spawn failed: ${err.message}`;
293
+ reject(withConversationId(message, runResult));
294
+ });
295
+ });
296
+
297
+ child.on("close", (code: number | null, sig: string | null) => {
298
+ done(() => {
299
+ const out = Buffer.concat(stdout).toString("utf8");
300
+ const err = Buffer.concat(stderr).toString("utf8");
301
+
302
+ // Flush a partial UTF-8 sequence before handling the final record.
303
+ processStdoutText(decoder.end());
304
+
305
+ // JSONL producers normally terminate every record with a newline, but
306
+ // process failures can leave the final record unterminated. Parse it
307
+ // before handling the exit code so retry logic sees real activity and
308
+ // users still receive the terminal progress update. The remainder is
309
+ // bounded by appendStreamChunk, so no length check is needed here.
310
+ if (lineBuffer.trim()) {
311
+ runResult = processStreamLine(lineBuffer, runResult, onProgress);
312
+ }
313
+
314
+ // Finalization also parses whole top-level JSON envelopes, including
315
+ // pretty-printed output that cannot be consumed one line at a time.
316
+ const finalized = finalizeRunResult(out, runResult);
317
+
318
+ // Terminal status is authoritative when present. agy can emit an
319
+ // ERROR envelope with response: "" and even exit 0; response
320
+ // completeness must never turn that failed turn into success.
321
+ const terminalFailure = terminalFailureMessage(finalized, err);
322
+ if (terminalFailure) {
323
+ reject(withConversationId(terminalFailure, finalized));
324
+ return;
325
+ }
326
+
327
+ // Headless permission denials are intentionally nonfatal in agy and
328
+ // can therefore arrive as SUCCESS with an empty response. Never turn
329
+ // that incomplete delegation into a silent successful tool result.
330
+ if (finalized.denied_actions?.length && !finalized.response.trim()) {
331
+ const denied = summarizeAgyDeniedActions(finalized.denied_actions);
332
+ reject(withConversationId(`agy denied tool actions: ${denied}`, finalized));
333
+ return;
334
+ }
335
+
336
+ // A fully delivered successful result outranks the kill: when
337
+ // cancellation or timeout lands after the response arrived, the work
338
+ // is done and the response must not be discarded.
339
+ if (finalized.response_complete) {
340
+ resolve(finalized);
341
+ return;
342
+ }
343
+
344
+ if (sig === "SIGTERM" || sig === "SIGKILL" || code === null) {
345
+ reject(
346
+ withConversationId(
347
+ signal.aborted && !timedOut ? "agy was cancelled" : "agy timed out",
348
+ finalized,
349
+ ),
350
+ );
351
+ return;
352
+ }
353
+
354
+ if (code !== 0) {
355
+ const detail = (err || out).slice(0, 2000).trim();
356
+ reject(withConversationId(`agy exited with code ${code}:\n${detail || "(no output)"}`, finalized));
357
+ return;
358
+ }
359
+
360
+ // agy writes diagnostics to stderr even on successful runs. Keep it
361
+ // out of the response so JSON/stream parsing remains deterministic.
362
+ // Only responses served verbatim from the bounded raw capture can be
363
+ // incomplete; anything parsed from a record was delivered in full.
364
+ if (stdoutTruncated && !finalized.response_complete) {
365
+ finalized.response += `\n\n(raw stdout capture was truncated at the ${MAX_CAPTURE_BYTES / 1024} KB fallback bound)`;
366
+ }
367
+ resolve(finalized);
368
+ });
369
+ });
370
+ });
371
+ }
372
+
373
+ const SUCCESSFUL_TERMINAL_STATUSES = new Set(["SUCCESS", "OK"]);
374
+
375
+ function terminalFailureMessage(runResult: AgyRunResult, stderr: string): string | undefined {
376
+ if (runResult.terminal_status === undefined) return undefined;
377
+ const status = runResult.terminal_status
378
+ .trim()
379
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, "")
380
+ .slice(0, 64);
381
+ if (SUCCESSFUL_TERMINAL_STATUSES.has(status.toUpperCase())) return undefined;
382
+
383
+ const detail = runResult.terminal_error?.trim();
384
+ let message = `agy reported terminal status ${status || "(empty)"}`;
385
+ if (detail) message += `: ${detail}`;
386
+ const stderrDetail = stderr.trim().slice(0, 2_000);
387
+ if (stderrDetail && !message.includes(stderrDetail)) message += `\n${stderrDetail}`;
388
+ return message;
389
+ }
390
+
391
+ function withConversationId(message: string, runResult: AgyRunResult): Error {
392
+ const error = new Error(message) as Error & { conversation_id?: string };
393
+ if (runResult.conversation_id) error.conversation_id = runResult.conversation_id;
394
+ return error;
395
+ }
396
+
397
+ function processStreamLine(
398
+ line: string,
399
+ current: AgyRunResult,
400
+ onProgress?: AgyProgressHandler,
401
+ ): AgyRunResult {
402
+ const parsed = parseStreamLine(line);
403
+ if (!parsed) return current;
404
+
405
+ const next = accumulateRunResult(parsed, current);
406
+ const activity = isActivityProgress(parsed);
407
+ const progress = formatStepProgress(parsed);
408
+ if (progress) onProgress?.(progress, activity ? "activity" : "status");
409
+ else if (activity) onProgress?.("agy: working…", "activity");
410
+ return next;
411
+ }
@@ -14,6 +14,11 @@ export interface AgyUsage {
14
14
  total_tokens?: number;
15
15
  }
16
16
 
17
+ export interface AgyDeniedAction {
18
+ action?: string;
19
+ display_name?: string;
20
+ }
21
+
17
22
  export interface AgyStepUpdate {
18
23
  conversation_id?: string;
19
24
  step_index?: number;
@@ -42,6 +47,7 @@ export interface AgyStreamLine {
42
47
  status?: string;
43
48
  response?: string;
44
49
  error?: string;
50
+ denied_actions?: unknown;
45
51
  duration_seconds?: number;
46
52
  usage?: AgyUsage;
47
53
  init?: { model?: string; cwd?: string };
@@ -51,6 +57,7 @@ export interface AgyStreamLine {
51
57
  status?: string;
52
58
  response?: string;
53
59
  error?: string;
60
+ denied_actions?: unknown;
54
61
  duration_seconds?: number;
55
62
  usage?: AgyUsage;
56
63
  };
@@ -64,6 +71,8 @@ export interface AgyRunResult {
64
71
  terminal_status?: string;
65
72
  /** Bounded terminal error detail from the result envelope. */
66
73
  terminal_error?: string;
74
+ /** Bounded permission refusals reported by headless agy. */
75
+ denied_actions?: AgyDeniedAction[];
67
76
  conversation_id?: string;
68
77
  usage?: AgyUsage;
69
78
  duration_seconds?: number;
@@ -222,6 +231,58 @@ function capTerminalError(error: string): string {
222
231
  .slice(0, 2_000);
223
232
  }
224
233
 
234
+ const MAX_DENIED_ACTIONS = 32;
235
+ const MAX_DENIED_ACTION_CHARS = 120;
236
+
237
+ function cleanDeniedActionField(value: unknown): string | undefined {
238
+ if (typeof value !== "string") return undefined;
239
+ const clean = stripTerminalSequences(value)
240
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
241
+ .replace(/\s+/g, " ")
242
+ .trim()
243
+ .slice(0, MAX_DENIED_ACTION_CHARS);
244
+ return clean || undefined;
245
+ }
246
+
247
+ export function normalizeAgyDeniedActions(value: unknown): AgyDeniedAction[] | undefined {
248
+ if (!Array.isArray(value)) return undefined;
249
+ const denied: AgyDeniedAction[] = [];
250
+ const seen = new Set<string>();
251
+ for (const item of value) {
252
+ let action: string | undefined;
253
+ let displayName: string | undefined;
254
+ if (typeof item === "string") {
255
+ action = cleanDeniedActionField(item);
256
+ } else if (typeof item === "object" && item !== null && !Array.isArray(item)) {
257
+ const record = item as Record<string, unknown>;
258
+ action = cleanDeniedActionField(record.action);
259
+ displayName = cleanDeniedActionField(record.display_name);
260
+ }
261
+ if (!action && !displayName) continue;
262
+ const key = `${action ?? ""}\u0000${displayName ?? ""}`;
263
+ if (seen.has(key)) continue;
264
+ seen.add(key);
265
+ denied.push({
266
+ ...(action ? { action } : {}),
267
+ ...(displayName ? { display_name: displayName } : {}),
268
+ });
269
+ if (denied.length >= MAX_DENIED_ACTIONS) break;
270
+ }
271
+ return denied.length ? denied : undefined;
272
+ }
273
+
274
+ export function summarizeAgyDeniedActions(value: unknown, max = 12): string {
275
+ const denied = normalizeAgyDeniedActions(value) ?? [];
276
+ const shown = denied.slice(0, Math.max(0, max));
277
+ const labels = shown.map(({ action, display_name: displayName }) =>
278
+ displayName && action && displayName !== action
279
+ ? `${displayName} (${action})`
280
+ : displayName ?? action ?? "unknown action",
281
+ );
282
+ if (denied.length > shown.length) labels.push(`… ${denied.length - shown.length} more`);
283
+ return labels.join(", ");
284
+ }
285
+
225
286
  export function accumulateRunResult(parsed: AgyStreamLine, current: AgyRunResult): AgyRunResult {
226
287
  const next = { ...current };
227
288
 
@@ -238,6 +299,8 @@ export function accumulateRunResult(parsed: AgyStreamLine, current: AgyRunResult
238
299
  next.response_complete = true;
239
300
  }
240
301
  if (typeof parsed.error === "string") next.terminal_error = capTerminalError(parsed.error);
302
+ const topLevelDenied = normalizeAgyDeniedActions(parsed.denied_actions);
303
+ if (topLevelDenied) next.denied_actions = topLevelDenied;
241
304
  if (typeof parsed.duration_seconds === "number" && Number.isFinite(parsed.duration_seconds)) {
242
305
  next.duration_seconds = parsed.duration_seconds;
243
306
  }
@@ -264,6 +327,8 @@ export function accumulateRunResult(parsed: AgyStreamLine, current: AgyRunResult
264
327
  if (typeof parsed.result.error === "string") {
265
328
  next.terminal_error = capTerminalError(parsed.result.error);
266
329
  }
330
+ const denied = normalizeAgyDeniedActions(parsed.result.denied_actions);
331
+ if (denied) next.denied_actions = denied;
267
332
  if (typeof parsed.result.usage === "object" && parsed.result.usage !== null) {
268
333
  next.usage = parsed.result.usage;
269
334
  }
@@ -331,6 +396,11 @@ function mergeJsonEnvelope(parsed: unknown, current: AgyRunResult): AgyRunResult
331
396
  next.terminal_error = capTerminalError(record.error);
332
397
  found = true;
333
398
  }
399
+ const denied = normalizeAgyDeniedActions(record.denied_actions);
400
+ if (denied) {
401
+ next.denied_actions = denied;
402
+ found = true;
403
+ }
334
404
  if (typeof record.duration_seconds === "number") {
335
405
  next.duration_seconds = record.duration_seconds;
336
406
  found = true;