@juanbenjumea/pi-agy 0.6.4 → 0.6.6

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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.6
4
+
5
+ - Surface agy's native and legacy subagent spawn steps as bounded live progress and structured per-run observations (`details.subagents`) with ACTIVE/DONE/ERROR correlation, multi-spawn support, and retry-safe activity tracking.
6
+ - Append a compact observed-subagent summary to tool content and render the structured roster in native results and durable `/agy` receipts without duplicating the synthetic appendix.
7
+ - Keep diagnostics truthful and bounded: retain at most 32 sanitized observations, print at most 12, label unfinished entries `active at last event`, ignore send/manage events, and deliberately withhold nested conversation ids/log URIs as lifecycle handles.
8
+ - Add captured native-stream, legacy fallback, missing-step-index, control-safety, roster-bound, execution, and rendering coverage.
9
+
10
+ ## 0.6.5
11
+
12
+ - Add `agy_agents` and `/agy agents` to list configured custom agy agents through the CLI's read-only `agy agents` subcommand without spending a model turn; parsing is control-safe and capped at 200 names.
13
+ - Add validated custom-agent selection to `agy_execute` (`agent`) and `/agy` (`agent=name`), passed as a distinct `--agent` argv value with no shell interpolation.
14
+ - Persist custom-agent identity with conversation history and restore it automatically for known `conversation_id`, `continue=true`, `/agy continue`, and `/agy sessions` resumes.
15
+ - Show the effective custom agent in write confirmations, progress, native tool cards, durable receipts, history output, and session-picker labels; add focused discovery, validation, argv, rendering, and continuity coverage.
16
+
3
17
  ## 0.6.4
4
18
 
5
19
  - Add bounded active-tool progress details from agy's existing stream (`TargetFile`, task id, human-facing action/summary, and async threshold) while deliberately never exposing full `CommandLine` values that may contain secrets.
package/README.md CHANGED
@@ -24,11 +24,13 @@ Requires Node.js >= 20.3.
24
24
  |---------|----------|-----------|
25
25
  | Live progress | Final text only | `stream-json` → Pi `onUpdate` cards |
26
26
  | Model aliases | Hardcoded ids | Live `agy models` catalog (newest stable generation wins; preview/experimental ignored), static map fallback |
27
- | Conversation resume | None | `conversation_id`, `continue`, session store with task summaries, `/agy sessions` picker, `agy_history` discovery tool — runs that time out or are cancelled are recorded too |
27
+ | Conversation resume | None | `conversation_id`, `continue`, session store with task summaries and custom-agent identity, `/agy sessions` picker, `agy_history` discovery tool — runs that time out or are cancelled are recorded too |
28
28
  | Verify injection | `npm test` only | `just ci` first, then `npm test`/`uv run pytest` |
29
29
  | Post-write summary | None | Appends `git diff --stat` for newly-dirty files only; pre-existing dirt (including renames and unstaged edits) is listed separately and never misattributed |
30
30
  | Preflight | Every call | Health/model checks cached 5 min per process; model quotas refresh every minute |
31
31
  | Quota discovery | None | Read-only `/usage` probe exposes model-specific remaining quota and reset times to agents |
32
+ | Custom agents | None | Read-only `agy_agents` / `/agy agents` discovery plus validated `agent` / `agent=name` selection via `--agent` |
33
+ | Subagent visibility | None | Native stream progress plus a capped per-run roster in result details/receipts; observations never claim live lifecycle control |
32
34
  | Concurrency | Unlocked | Per-directory lock (in-process + filesystem, symlink-aware), lock wait counts against the timeout |
33
35
  | Transient failures | Fatal | One retry when agy fails before doing any work |
34
36
  | Cancellation | Direct child only | Full process-tree kill on cancel/timeout via detached process groups; a fully delivered result is preserved |
@@ -44,6 +46,9 @@ outlive the run.
44
46
 
45
47
  Active tool updates show bounded intent (for example a tool action or async
46
48
  threshold) but never echo full command lines, which may contain secrets.
49
+ Subagent spawn steps likewise produce bounded progress and a final per-run
50
+ observation roster (maximum 32). An `active at last event` entry describes the
51
+ last stream record only; it does not claim that a controllable process remains live.
47
52
  Background commands are intentionally not detached or managed out-of-band:
48
53
  agy exposes no reliable headless task lifecycle or task-to-process ownership,
49
54
  so timeout/cancellation still kills the full process tree and prevents work from
@@ -70,6 +75,7 @@ The deadline never discards finished work:
70
75
  | `continue` | `--continue` most recent conversation |
71
76
  | `new_session` | Force fresh session; set `false` to reuse last ID for dir |
72
77
  | `effort` | Reasoning effort via `--effort` where supported; `gpt-oss` accepts it, while Claude thinking models reject it and Gemini aliases already encode it |
78
+ | `agent` | Optional configured custom agy agent name; discover names with `agy_agents` |
73
79
  | `stream` | Use `stream-json` (default `true`) |
74
80
  | `context` | Optional Pi history handoff: `none` (default), `summary`, or `recent` |
75
81
  | `mode` | `accept-edits` by default; use `plan` for exploration/review |
@@ -89,6 +95,12 @@ headless `/usage` continue without failing the task. The extension requires
89
95
  agy 1.1.11+ before invoking `/usage`; older versions are refused safely because
90
96
  that command could otherwise consume model quota as a prompt.
91
97
 
98
+ When agy emits `subagent` stream steps, `agy_execute` returns a capped,
99
+ control-safe `details.subagents` list and appends the same observed summary to
100
+ tool content. Native rendering deduplicates that synthetic appendix and shows
101
+ compact/expanded roster metadata. Conversation ids and log URIs from nested
102
+ subagents are deliberately not exposed as lifecycle handles.
103
+
92
104
  Context handoff is opt-in and text-only. `summary` sends up to 12,000
93
105
  characters from the latest durable summaries and four conversational messages;
94
106
  `recent` sends up to 40,000 characters from the recent conversational tail.
@@ -96,10 +108,16 @@ Both exclude Pi system prompts, thinking, tool arguments, tool results, images,
96
108
  and custom extension messages. The current delegated task is appended after the
97
109
  reference context and remains authoritative.
98
110
 
111
+ The `agy_agents` tool runs the read-only `agy agents` subcommand and returns
112
+ configured custom-agent names without spending a model turn. Pass an exact
113
+ name as `agy_execute agent`; initial selection is always explicit, while known
114
+ conversation resumes restore their recorded agent.
115
+
99
116
  The `agy_history` tool lists recorded conversations for a directory — ids,
100
- models, ages, and one-line task summaries — so agents can find a
117
+ models, custom agents, ages, and one-line task summaries — so agents can find a
101
118
  `conversation_id` to resume; `/agy sessions` offers the same in the TUI
102
- picker. Summaries are stored locally (first ~80 chars of each prompt).
119
+ picker. Summaries are stored locally (first ~80 chars of each prompt), and a
120
+ recorded custom agent is restored when that conversation resumes.
103
121
 
104
122
  ## Human-callable `/agy` command
105
123
 
@@ -108,6 +126,8 @@ Run agy directly from the Pi TUI — fast path when fully specified, wizard othe
108
126
  ```
109
127
  /agy flash fix git conflicts # fully specified → runs immediately
110
128
  /agy plan sonnet review the diff # mode + model + prompt
129
+ /agy agents # list configured custom agents (read-only)
130
+ /agy plan agent=gsd-debugger investigate the crash
111
131
  /agy context=summary plan sonnet review our earlier decision
112
132
  /agy plan # wizard: model select → task editor
113
133
  /agy # wizard: mode → model → task editor
@@ -118,10 +138,10 @@ Run agy directly from the Pi TUI — fast path when fully specified, wizard othe
118
138
  /agy usage # inspect model quotas and reset times
119
139
  ```
120
140
 
121
- Leading option tokens (`plan`, a model alias, `continue`, `context=summary`,
122
- `context=recent`, `timeout=…`) are
123
- consumed in any order; the remainder is the prompt. `/agy continue` reuses the
124
- last model when the session store recorded one. `timeout=` caps at 10m.
141
+ Leading option tokens (`plan`, a model alias, `agent=name`, `continue`,
142
+ `context=summary`, `context=recent`, `timeout=…`) are consumed in any order;
143
+ the remainder is the prompt. `/agy continue` reuses the last model and custom
144
+ agent when the session store recorded them. `timeout=` caps at 10m.
125
145
 
126
146
  First token optional: `accept-edits` / `plan` / `sandbox` mode prefix, then a
127
147
  model alias (`flash`, `pro`, `sonnet`, `opus`, `gpt-oss`, …), then the prompt.
@@ -141,7 +161,8 @@ is appended to Pi's transcript. Receipts are TUI-only custom entries: they are
141
161
  not sent to the primary model, and context handoff excludes them. Stored task
142
162
  text is capped at 500 characters and result text at 8,000 characters. Stripped-down
143
163
  hosts fall back to a normal notification. `/agy usage` performs the same read-only
144
- quota check without starting a model turn.
164
+ quota check without starting a model turn; `/agy agents` likewise lists custom
165
+ agents without inference.
145
166
 
146
167
  ## Config
147
168
 
@@ -3,7 +3,9 @@ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-c
3
3
  import {
4
4
  checkAgyUsage,
5
5
  formatAgyUsage,
6
+ inspectAgyAgents,
6
7
  isAgyModel,
8
+ normalizeAgyAgentName,
7
9
  resolveAgyModelId,
8
10
  type AgyModel,
9
11
  } from "./lib/cli.js";
@@ -60,6 +62,7 @@ const MAX_TIMEOUT_MS = 600_000;
60
62
  export interface AgyCommandArgs {
61
63
  mode?: "plan" | "accept-edits" | "sandbox";
62
64
  model?: AgyModel;
65
+ agent?: string;
63
66
  prompt?: string;
64
67
  continue?: boolean;
65
68
  timeout_ms?: number;
@@ -68,7 +71,7 @@ export interface AgyCommandArgs {
68
71
  }
69
72
 
70
73
  /**
71
- * Parse `/agy [mode] [model] [continue] [timeout=10m] <prompt>` — leading
74
+ * Parse `/agy [mode] [model] [agent=name] [continue] [timeout=10m] <prompt>` — leading
72
75
  * option tokens are consumed in any order; the remainder is the prompt.
73
76
  */
74
77
  export function parseAgyCommandArgs(args: string): AgyCommandArgs {
@@ -87,6 +90,12 @@ export function parseAgyCommandArgs(args: string): AgyCommandArgs {
87
90
  parsed.model = MODEL_ALIASES[value];
88
91
  } else if (value === "continue") {
89
92
  parsed.continue = true;
93
+ } else if (value.startsWith("agent=")) {
94
+ try {
95
+ parsed.agent = normalizeAgyAgentName(token.value.slice("agent=".length));
96
+ } catch (error) {
97
+ parsed.error = error instanceof Error ? error.message : String(error);
98
+ }
90
99
  } else if (value.startsWith("context=")) {
91
100
  const context = value.slice("context=".length);
92
101
  if (context === "none" || context === "summary" || context === "recent") {
@@ -124,6 +133,7 @@ function readToken(value: string): { value: string; end: number } | undefined {
124
133
  interface InteractiveRun {
125
134
  mode: "plan" | "accept-edits" | "sandbox";
126
135
  model: AgyModel;
136
+ agent?: string;
127
137
  prompt: string;
128
138
  conversation_id?: string;
129
139
  continue?: boolean;
@@ -143,7 +153,7 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
143
153
 
144
154
  pi.registerCommand("agy", {
145
155
  description:
146
- "Run agy directly: /agy [mode] [model] [continue] [context=summary|recent] [timeout=10m] <prompt>; use /agy doctor for diagnostics or /agy usage for quotas.",
156
+ "Run agy directly: /agy [mode] [model] [agent=name] [continue] [context=summary|recent] [timeout=10m] <prompt>; use /agy agents to list custom agents.",
147
157
  getArgumentCompletions: (prefix: string) => {
148
158
  const tokens = prefix.trim().split(/\s+/).filter(Boolean);
149
159
  const p = prefix.toLowerCase();
@@ -159,6 +169,7 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
159
169
  ...(tokens[0] === "usage" || tokens[0] === "quota"
160
170
  ? []
161
171
  : [
172
+ { value: "agent=", label: "agent=" },
162
173
  { value: "continue", label: "continue" },
163
174
  { value: "timeout=10m", label: "timeout=10m" },
164
175
  ]),
@@ -180,6 +191,8 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
180
191
  const extras = [
181
192
  "continue",
182
193
  "sessions",
194
+ "agents",
195
+ "agent=",
183
196
  "doctor",
184
197
  "usage",
185
198
  "quota",
@@ -206,6 +219,15 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
206
219
  await runSessionsPicker(pi, ctx);
207
220
  return;
208
221
  }
222
+ const agentsMatch = /^agents(?:\s+(.+))?$/.exec(command);
223
+ if (agentsMatch) {
224
+ if (agentsMatch[1]) {
225
+ ctx.ui.notify("agy: agents takes no arguments", "error");
226
+ return;
227
+ }
228
+ await showAgents(ctx);
229
+ return;
230
+ }
209
231
  const doctorMatch = /^doctor(?:\s+(.+))?$/.exec(command);
210
232
  if (doctorMatch) {
211
233
  if (doctorMatch[1]) {
@@ -243,9 +265,17 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
243
265
  }
244
266
 
245
267
  let model = parsed.model;
246
- if (!model && parsed.continue) {
268
+ let agent = parsed.agent;
269
+ if (parsed.continue && (!model || !agent)) {
247
270
  const prior = await getSession(ctx.cwd);
248
- if (prior?.last_model && isAgyModel(prior.last_model)) model = prior.last_model;
271
+ if (!model && prior?.last_model && isAgyModel(prior.last_model)) model = prior.last_model;
272
+ if (!agent && prior?.last_agent) {
273
+ try {
274
+ agent = normalizeAgyAgentName(prior.last_agent);
275
+ } catch {
276
+ // Ignore malformed legacy session metadata.
277
+ }
278
+ }
249
279
  }
250
280
  if (!model) {
251
281
  const pick = await ctx.ui.select("agy model", MODEL_OPTIONS);
@@ -269,6 +299,7 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
269
299
  await executeConfirmedRun(pi, ctx, {
270
300
  mode,
271
301
  model,
302
+ agent,
272
303
  prompt,
273
304
  continue: parsed.continue,
274
305
  timeout_ms: parsed.timeout_ms,
@@ -298,6 +329,27 @@ async function showDoctor(ctx: ExtensionCommandContext): Promise<void> {
298
329
  }
299
330
  }
300
331
 
332
+ /** `/agy agents` — list configured custom agents without inference. */
333
+ async function showAgents(ctx: ExtensionCommandContext): Promise<void> {
334
+ try {
335
+ await ctx.waitForIdle();
336
+ ctx.ui.setStatus("agy", "agy: discovering custom agents…");
337
+ const agents = await inspectAgyAgents(ctx.cwd, ctx.signal);
338
+ ctx.ui.notify(
339
+ agents.length ? `configured agy agents:\n${agents.map((agent) => `- ${agent}`).join("\n")}` : "No custom agy agents are configured.",
340
+ "info",
341
+ );
342
+ } catch (error) {
343
+ if (ctx.signal?.aborted) ctx.ui.notify("agy: agent discovery cancelled", "info");
344
+ else {
345
+ const message = error instanceof Error ? error.message : String(error);
346
+ ctx.ui.notify(`agy agent discovery failed: ${message}`, "error");
347
+ }
348
+ } finally {
349
+ ctx.ui.setStatus("agy", undefined);
350
+ }
351
+ }
352
+
301
353
  /** `/agy usage` — show model quotas without starting an agent turn. */
302
354
  async function showUsage(
303
355
  ctx: ExtensionCommandContext,
@@ -328,8 +380,9 @@ async function runSessionsPicker(
328
380
  const options = history.map((entry, index) => {
329
381
  const id = entry.conversation_id.slice(0, 8);
330
382
  const model = entry.model ?? "unknown model";
383
+ const agent = entry.agent ? ` · agent ${entry.agent}` : "";
331
384
  const summary = entry.summary ? `${entry.summary.slice(0, 50)} · ` : "";
332
- return `${index + 1}. ${summary}${model} · ${describeWhen(entry.updated_at)} · ${id}…`;
385
+ return `${index + 1}. ${summary}${model}${agent} · ${describeWhen(entry.updated_at)} · ${id}…`;
333
386
  });
334
387
  const pick = await ctx.ui.select("resume agy conversation", options);
335
388
  if (!pick) {
@@ -358,6 +411,7 @@ async function runSessionsPicker(
358
411
  await executeConfirmedRun(pi, ctx, {
359
412
  mode,
360
413
  model: isAgyModel(entry.model) ? entry.model : "flash-medium",
414
+ agent: entry.agent,
361
415
  prompt: text.trim(),
362
416
  conversation_id: entry.conversation_id,
363
417
  });
@@ -379,6 +433,7 @@ async function executeConfirmedRun(
379
433
  if (run.mode === "accept-edits") {
380
434
  const dirt = await describePreRunDirt(cwd, ctx.signal).catch(() => null);
381
435
  const dirtLine = dirt ? `\nworkspace: ${dirt}` : "";
436
+ const agentLine = run.agent ? `\nagent: ${run.agent}` : "";
382
437
  const contextLine =
383
438
  contextMode === "none"
384
439
  ? "\ncontext: none"
@@ -391,7 +446,7 @@ async function executeConfirmedRun(
391
446
  : "";
392
447
  const ok = await ctx.ui.confirm(
393
448
  "Run agy (accept-edits)?",
394
- `model: ${run.model} (${resolveAgyModelId(run.model)})\ndir: ${cwd}${dirtLine}${contextLine}\n\ntask: ${run.prompt.slice(0, 200)}${run.prompt.length > 200 ? "…" : ""}\n\nThis grants agy permission to modify files and run commands.${warning}`,
449
+ `model: ${run.model} (${resolveAgyModelId(run.model)})${agentLine}\ndir: ${cwd}${dirtLine}${contextLine}\n\ntask: ${run.prompt.slice(0, 200)}${run.prompt.length > 200 ? "…" : ""}\n\nThis grants agy permission to modify files and run commands.${warning}`,
395
450
  );
396
451
  if (!ok) {
397
452
  ctx.ui.notify("agy: cancelled", "info");
@@ -403,11 +458,12 @@ async function executeConfirmedRun(
403
458
  // a second LLM turn and the command works even when tools are limited.
404
459
  const status = createStatusThrottler(ctx);
405
460
  try {
406
- status(`starting (${run.model} · ${run.mode})`);
461
+ status(`starting (${run.model} · ${run.mode}${run.agent ? ` · agent ${run.agent}` : ""})`);
407
462
  const result = await executeAgyTask(
408
463
  {
409
464
  prompt: run.prompt,
410
465
  model: run.model,
466
+ agent: run.agent,
411
467
  mode: run.mode,
412
468
  dir: cwd,
413
469
  timeout_ms: run.timeout_ms ?? DEFAULT_TIMEOUT_MS,
@@ -7,7 +7,9 @@ import {
7
7
  checkAgyUsage,
8
8
  findAgyQuotaEntries,
9
9
  formatAgyUsage,
10
+ inspectAgyAgents,
10
11
  isAgyQuotaExhausted,
12
+ normalizeAgyAgentName,
11
13
  resolveAgyModelAlias,
12
14
  resolveAgyModelId,
13
15
  type AgyModel,
@@ -22,7 +24,7 @@ import {
22
24
  } from "./lib/execute.js";
23
25
  import { describeWhen, truncate } from "./lib/output.js";
24
26
  import { renderAgyCall, renderAgyResult } from "./lib/render.js";
25
- import { getHistory } from "./lib/sessions.js";
27
+ import { getHistory, getSession } from "./lib/sessions.js";
26
28
 
27
29
  const DEFAULT_TIMEOUT_MS = 300_000;
28
30
  const MAX_TIMEOUT_MS = 600_000;
@@ -52,6 +54,7 @@ export default function piAgyExtension(pi: ExtensionAPI) {
52
54
  "Use gpt-oss when an open-model alternative is specifically desired.",
53
55
  "For consequential work, use one family to produce and the opposite family to cross-review in mode=plan; do not spend both quota groups on trivial tasks.",
54
56
  "Reuse conversation_id or continue=true for multi-step plan→implement→review handoffs.",
57
+ "Use agent only when the user requests a configured custom agy agent; call agy_agents first if the exact name is unknown.",
55
58
  "Keep agy_execute context=none unless the delegated task depends on prior Pi discussion; use summary before recent to minimize disclosure.",
56
59
  "Use agy_usage before choosing a model when quota availability matters; agy_execute also refreshes and returns a quota snapshot.",
57
60
  "Batch related work, prefer digest output for non-write calls, and avoid parallel agy_execute calls within one shared-quota group or directory.",
@@ -85,6 +88,13 @@ export default function piAgyExtension(pi: ExtensionAPI) {
85
88
  "Reasoning effort passed to agy (--effort). Optional; mostly useful for sonnet/opus/gpt-oss since Gemini aliases encode effort in the model id.",
86
89
  }),
87
90
  ),
91
+ agent: Type.Optional(
92
+ Type.String({
93
+ description: "Configured custom agy agent name. Use agy_agents to discover names.",
94
+ minLength: 1,
95
+ maxLength: 128,
96
+ }),
97
+ ),
88
98
  tier: Type.Optional(
89
99
  Type.Union(
90
100
  [Type.Literal("flash"), Type.Literal("flash-lo"), Type.Literal("pro")],
@@ -156,6 +166,19 @@ export default function piAgyExtension(pi: ExtensionAPI) {
156
166
  const mode = resolveAgyMode(params.mode);
157
167
  const model = params.model as AgyModel | undefined;
158
168
  const contextMode = (params.context ?? "none") as AgyContextMode;
169
+ let agent = normalizeAgyAgentName(params.agent);
170
+ if (!agent && params.conversation_id) {
171
+ agent = (await getHistory(cwd)).find(
172
+ (entry) => entry.conversation_id === params.conversation_id,
173
+ )?.agent;
174
+ } else if (!agent && (params.continue || params.new_session === false)) {
175
+ const storedAgent = (await getSession(cwd))?.last_agent;
176
+ try {
177
+ agent = normalizeAgyAgentName(storedAgent);
178
+ } catch {
179
+ // Ignore malformed legacy session metadata.
180
+ }
181
+ }
159
182
  const contextText =
160
183
  contextMode === "none"
161
184
  ? undefined
@@ -165,6 +188,7 @@ export default function piAgyExtension(pi: ExtensionAPI) {
165
188
  model,
166
189
  tier: params.tier,
167
190
  effort: params.effort,
191
+ agent,
168
192
  mode,
169
193
  dir: cwd,
170
194
  digest: params.digest,
@@ -190,6 +214,7 @@ export default function piAgyExtension(pi: ExtensionAPI) {
190
214
  const excerpt =
191
215
  params.prompt.slice(0, 200) + (params.prompt.length > 200 ? "…" : "");
192
216
  const dirtLine = dirt ? `\nworkspace: ${dirt}` : "";
217
+ const agentLine = agent ? `\nagent: ${agent}` : "";
193
218
  const contextLine =
194
219
  contextMode === "none"
195
220
  ? "\ncontext: none"
@@ -202,7 +227,7 @@ export default function piAgyExtension(pi: ExtensionAPI) {
202
227
  : "";
203
228
  const approved = await ctx.ui.confirm(
204
229
  "Run agy (accept-edits)?",
205
- `model: ${modelLabel}\ndir: ${cwd}${dirtLine}${contextLine}\n\ntask: ${excerpt}\n\nThis grants agy permission to modify files and run commands.${warning}`,
230
+ `model: ${modelLabel}${agentLine}\ndir: ${cwd}${dirtLine}${contextLine}\n\ntask: ${excerpt}\n\nThis grants agy permission to modify files and run commands.${warning}`,
206
231
  );
207
232
  if (!approved) throw new Error("agy accept-edits cancelled by user");
208
233
  }
@@ -230,6 +255,44 @@ export default function piAgyExtension(pi: ExtensionAPI) {
230
255
  },
231
256
  });
232
257
 
258
+ pi.registerTool({
259
+ name: "agy_agents",
260
+ label: "Antigravity Agents",
261
+ description:
262
+ "List configured custom agy agents without spending a model turn. Use the returned name as agy_execute agent.",
263
+ promptSnippet: "Discover configured custom agy agents before selecting one",
264
+ parameters: Type.Object({
265
+ dir: Type.Optional(
266
+ Type.String({
267
+ description: "Working directory used for the agy CLI check. Defaults to current project root.",
268
+ }),
269
+ ),
270
+ }),
271
+
272
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
273
+ const cwd = params.dir ? path.resolve(ctx.cwd, params.dir) : ctx.cwd;
274
+ if (params.dir) {
275
+ try {
276
+ const info = await stat(cwd);
277
+ if (!info.isDirectory()) throw new Error(`Working directory is not a directory: ${cwd}`);
278
+ } catch (error) {
279
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
280
+ throw new Error(`Working directory does not exist: ${cwd}`);
281
+ }
282
+ throw error;
283
+ }
284
+ }
285
+ const agents = await inspectAgyAgents(cwd, signal);
286
+ const text = agents.length
287
+ ? `configured agy agents:\n${agents.map((agent) => `- ${agent}`).join("\n")}`
288
+ : "No custom agy agents are configured.";
289
+ return {
290
+ content: [{ type: "text", text }],
291
+ details: { cwd, agents },
292
+ };
293
+ },
294
+ });
295
+
233
296
  pi.registerTool({
234
297
  name: "agy_history",
235
298
  label: "Antigravity Conversations",
@@ -267,12 +330,13 @@ export default function piAgyExtension(pi: ExtensionAPI) {
267
330
  }
268
331
  const lines = limited.map((entry, index) => {
269
332
  const model = entry.model ?? "unknown model";
333
+ const agent = entry.agent ? ` · agent ${entry.agent}` : "";
270
334
  const summary = entry.summary ? ` · ${entry.summary}` : "";
271
- return `${index + 1}. ${entry.conversation_id} · ${model} · ${describeWhen(entry.updated_at)}${summary}`;
335
+ return `${index + 1}. ${entry.conversation_id} · ${model}${agent} · ${describeWhen(entry.updated_at)}${summary}`;
272
336
  });
273
337
  const text =
274
338
  `agy conversations for ${cwd} (most recent first):\n${lines.join("\n")}\n\n` +
275
- "Resume with agy_execute conversation_id=<id>, or continue=true for the most recent.";
339
+ "Resume with agy_execute conversation_id=<id>, or continue=true for the most recent; recorded agents are restored automatically.";
276
340
  return {
277
341
  content: [{ type: "text", text }],
278
342
  details: { dir: cwd, conversations: limited },
@@ -78,6 +78,8 @@ export interface AgyOptions {
78
78
  model?: AgyModel;
79
79
  tier?: "flash" | "flash-lo" | "pro";
80
80
  effort?: AgyEffort;
81
+ /** Optional custom agent name passed to `agy --agent`. */
82
+ agent?: string;
81
83
  mode?: "plan" | "accept-edits" | "sandbox";
82
84
  dir: string;
83
85
  timeout_ms: number;
@@ -239,12 +241,59 @@ export function isTransientAgyFailure(message: string): boolean {
239
241
  return TRANSIENT_FAILURE_PATTERN.test(message);
240
242
  }
241
243
 
244
+ const MAX_AGENT_NAME_LENGTH = 128;
245
+ const MAX_AGENT_COUNT = 200;
246
+
247
+ export function normalizeAgyAgentName(value?: string): string | undefined {
248
+ if (value === undefined) return undefined;
249
+ const agent = value.trim();
250
+ if (!agent) throw new Error("agy agent must not be empty");
251
+ if (/[\x00-\x1f\x7f]/.test(agent)) {
252
+ throw new Error("agy agent must not contain control characters");
253
+ }
254
+ if (agent.length > MAX_AGENT_NAME_LENGTH) {
255
+ throw new Error(`agy agent must be at most ${MAX_AGENT_NAME_LENGTH} characters`);
256
+ }
257
+ return agent;
258
+ }
259
+
260
+ /** Parse the intentionally simple, line-oriented output of `agy agents`. */
261
+ export function parseAgyAgents(output: string): string[] {
262
+ const agents: string[] = [];
263
+ for (const raw of output.split(/\r?\n/)) {
264
+ const line = raw.trim();
265
+ if (
266
+ !line ||
267
+ /^available\s+agents:?$/i.test(line) ||
268
+ /^name\s+/i.test(line) ||
269
+ /^(?:no|zero)\s+(?:custom\s+)?agents?\b/i.test(line)
270
+ ) {
271
+ continue;
272
+ }
273
+ const candidate = line
274
+ .split(/\t|\s{2,}/, 1)[0]
275
+ ?.replace(/^[-*]\s*/, "")
276
+ .trim();
277
+ try {
278
+ const agent = normalizeAgyAgentName(candidate);
279
+ if (agent && !agents.includes(agent)) {
280
+ agents.push(agent);
281
+ if (agents.length >= MAX_AGENT_COUNT) break;
282
+ }
283
+ } catch {
284
+ // Ignore malformed diagnostics and overlong names from CLI output.
285
+ }
286
+ }
287
+ return agents;
288
+ }
289
+
242
290
  export function buildAgyArgs(options: AgyOptions): string[] {
243
291
  if (options.continue && options.conversation_id) {
244
292
  throw new Error("agy cannot use --continue and --conversation together");
245
293
  }
246
294
 
247
295
  const model = resolveAgyModelId(options.model, options.tier);
296
+ const agent = normalizeAgyAgentName(options.agent);
248
297
  const timeoutSec = Math.ceil(options.timeout_ms / 1000);
249
298
  const mode = options.mode ?? "accept-edits";
250
299
  const writes = mode === "accept-edits";
@@ -266,6 +315,7 @@ export function buildAgyArgs(options: AgyOptions): string[] {
266
315
  ...(options.effort && supportsAgyEffort(options.model, options.tier)
267
316
  ? ["--effort", options.effort]
268
317
  : []),
318
+ ...(agent ? ["--agent", agent] : []),
269
319
  ];
270
320
 
271
321
  if (options.continue) {
@@ -366,6 +416,23 @@ export async function checkAgyConnectivity(
366
416
  await inspectAgyModels(cwd, signal, timeoutMs);
367
417
  }
368
418
 
419
+ /** List configured custom agents without spending a model turn. */
420
+ export async function inspectAgyAgents(
421
+ cwd: string,
422
+ signal?: AbortSignal,
423
+ timeoutMs?: number,
424
+ ): Promise<string[]> {
425
+ const output = await runPreflightCommand(
426
+ ["agents"],
427
+ cwd,
428
+ signal,
429
+ "agy agents check",
430
+ true,
431
+ timeoutMs,
432
+ );
433
+ return parseAgyAgents(output);
434
+ }
435
+
369
436
  /**
370
437
  * Refresh model-specific quotas without spending a model turn. Newer agy
371
438
  * versions answer read-only `/usage` in print mode; older versions may not,
@@ -956,7 +1023,11 @@ export function spawnAgy(options: AgyOptions, signal: AbortSignal): Promise<stri
956
1023
  /** Real agy work (tool steps / model responses), as opposed to lifecycle chatter. */
957
1024
  function isActivityProgress(parsed: AgyStreamLine): boolean {
958
1025
  const step = parsed.step_update;
959
- return step?.step_type === "tool" || step?.step_type === "agent_response";
1026
+ return (
1027
+ step?.step_type === "tool" ||
1028
+ step?.step_type === "subagent" ||
1029
+ step?.step_type === "agent_response"
1030
+ );
960
1031
  }
961
1032
 
962
1033
  export function spawnAgyStream(
@@ -8,6 +8,7 @@ import {
8
8
  getAgyConversationId,
9
9
  isAgyQuotaExhausted,
10
10
  isTransientAgyFailure,
11
+ normalizeAgyAgentName,
11
12
  resolveAgyModelAlias,
12
13
  resolveAgyModelId,
13
14
  spawnAgyStream,
@@ -18,6 +19,10 @@ import {
18
19
  import { loadAgyConfig, resolveDefaultModel } from "./config.js";
19
20
  import type { AgyContextMode } from "./context.js";
20
21
  import type { AgyUsage } from "./stream.js";
22
+ import {
23
+ formatAgySubagentObservations,
24
+ type AgyObservedSubagent,
25
+ } from "./subagents.js";
21
26
  import { withDirLock } from "./lock.js";
22
27
  import {
23
28
  captureGitBaseline,
@@ -25,7 +30,7 @@ import {
25
30
  type GitBaseline,
26
31
  } from "./postflight.js";
27
32
  import { resetPreflightCache, runPreflight } from "./preflight.js";
28
- import { getSession, saveSession, conversationSummary } from "./sessions.js";
33
+ import { getHistory, getSession, saveSession, conversationSummary } from "./sessions.js";
29
34
 
30
35
  export type AgyMode = "plan" | "accept-edits" | "sandbox";
31
36
 
@@ -34,6 +39,7 @@ export interface AgyExecutionOptions {
34
39
  model?: AgyModel;
35
40
  tier?: "flash" | "flash-lo" | "pro";
36
41
  effort?: AgyEffort;
42
+ agent?: string;
37
43
  mode: AgyMode;
38
44
  dir: string;
39
45
  digest?: boolean;
@@ -55,8 +61,11 @@ export interface AgyExecutionDetails {
55
61
  verify_cmd: string | null;
56
62
  permissions_skipped?: boolean;
57
63
  effort?: AgyEffort;
64
+ agent?: string;
58
65
  usage?: AgyUsage;
59
66
  duration_seconds?: number;
67
+ /** Stream observations only; entries do not imply a live controllable process. */
68
+ subagents?: AgyObservedSubagent[];
60
69
  changed_files?: string[];
61
70
  preexisting_files?: string[];
62
71
  context_mode?: AgyContextMode;
@@ -77,6 +86,7 @@ export async function executeAgyTask(
77
86
  onProgress?: (message: string) => void,
78
87
  ): Promise<AgyExecutionResult> {
79
88
  validateAgyExecutionOptions(options);
89
+ let agent = normalizeAgyAgentName(options.agent);
80
90
  const startedAt = Date.now();
81
91
  const budgetController = new AbortController();
82
92
  const abortSignal = signal
@@ -108,16 +118,32 @@ export async function executeAgyTask(
108
118
  }
109
119
 
110
120
  let conversationId = options.conversation_id;
121
+ const resumesLatest = options.continue || options.new_session === false;
122
+ const prior =
123
+ (!conversationId && options.new_session !== true) || (!agent && resumesLatest)
124
+ ? await getSession(options.dir)
125
+ : undefined;
111
126
  if (
112
127
  !conversationId &&
113
128
  !options.continue &&
114
- options.new_session !== true
129
+ prior?.last_conversation_id &&
130
+ options.new_session === false
115
131
  ) {
116
- const prior = await getSession(options.dir);
117
- if (prior?.last_conversation_id && options.new_session === false) {
118
- conversationId = prior.last_conversation_id;
132
+ conversationId = prior.last_conversation_id;
133
+ }
134
+ if (!agent && resumesLatest && prior?.last_agent) {
135
+ try {
136
+ agent = normalizeAgyAgentName(prior.last_agent);
137
+ } catch {
138
+ // Ignore malformed legacy store data rather than blocking a resume.
119
139
  }
120
140
  }
141
+ if (!agent && conversationId) {
142
+ const recorded = (await getHistory(options.dir)).find(
143
+ (entry) => entry.conversation_id === conversationId,
144
+ );
145
+ if (recorded?.agent) agent = normalizeAgyAgentName(recorded.agent);
146
+ }
121
147
 
122
148
  const useDigest = options.digest ?? options.mode !== "accept-edits";
123
149
  const verifyCmd =
@@ -182,7 +208,7 @@ export async function executeAgyTask(
182
208
  // Emitted via onProgress directly: progress tracking (and therefore
183
209
  // retry eligibility) must only reflect activity from agy itself.
184
210
  onProgress?.(
185
- `agy: starting (${effectiveModel}, ${options.mode}${options.effort ? `, effort ${options.effort}` : ""})…`,
211
+ `agy: starting (${effectiveModel}, ${options.mode}${agent ? `, agent ${agent}` : ""}${options.effort ? `, effort ${options.effort}` : ""})…`,
186
212
  );
187
213
 
188
214
  return spawnAgyStream(
@@ -190,6 +216,7 @@ export async function executeAgyTask(
190
216
  prompt: finalPrompt,
191
217
  model,
192
218
  effort: options.effort,
219
+ agent,
193
220
  mode: options.mode,
194
221
  dir: options.dir,
195
222
  timeout_ms: runTimeoutMs,
@@ -213,6 +240,7 @@ export async function executeAgyTask(
213
240
  effectiveModel,
214
241
  AbortSignal.timeout(10_000),
215
242
  conversationSummary(options.prompt),
243
+ agent,
216
244
  );
217
245
  } catch (error) {
218
246
  const reason = error instanceof Error ? error.message : String(error);
@@ -221,6 +249,8 @@ export async function executeAgyTask(
221
249
  }
222
250
 
223
251
  let text = run.response;
252
+ const subagentSummary = formatAgySubagentObservations(run.subagents);
253
+ if (subagentSummary) text = `${text}\n\n## ${subagentSummary}`;
224
254
  const quotaSummary = quota?.models.length
225
255
  ? formatAgyUsage(quota, resolveAgyModelId(model, options.tier))
226
256
  : undefined;
@@ -256,8 +286,10 @@ export async function executeAgyTask(
256
286
  verify_cmd: verifyCmd,
257
287
  permissions_skipped: options.mode === "accept-edits" ? skipPermissions : false,
258
288
  effort: options.effort,
289
+ agent,
259
290
  usage: run.usage,
260
291
  duration_seconds: run.duration_seconds,
292
+ subagents: run.subagents,
261
293
  changed_files: changedFiles,
262
294
  preexisting_files: preexistingFiles,
263
295
  context_mode: options.context ?? "none",
@@ -285,6 +317,7 @@ export async function executeAgyTask(
285
317
  effectiveModel,
286
318
  AbortSignal.timeout(10_000),
287
319
  conversationSummary(options.prompt),
320
+ agent,
288
321
  );
289
322
  conversationPersisted = true;
290
323
  } catch {
@@ -307,6 +340,7 @@ export async function executeAgyTask(
307
340
 
308
341
  export function validateAgyExecutionOptions(options: AgyExecutionOptions): void {
309
342
  if (!options.prompt?.trim()) throw new Error("agy prompt must not be empty");
343
+ normalizeAgyAgentName(options.agent);
310
344
  if (!Number.isFinite(options.timeout_ms) || options.timeout_ms <= 0) {
311
345
  throw new Error("agy timeout_ms must be a positive finite number");
312
346
  }
@@ -48,6 +48,7 @@ function firstText(content: unknown): string {
48
48
  function stripSyntheticResultSections(value: string): string {
49
49
  const markers = [
50
50
  "\n\n## agy quota snapshot",
51
+ "\n\n## agy subagents observed",
51
52
  "\n\n## git diff --stat",
52
53
  "\n\n## git diff --cached --stat",
53
54
  "\n\nagy made no newly-dirty files",
@@ -64,6 +65,7 @@ export function renderAgyCall(
64
65
  model?: unknown;
65
66
  tier?: unknown;
66
67
  mode?: unknown;
68
+ agent?: unknown;
67
69
  context?: unknown;
68
70
  prompt?: unknown;
69
71
  } | undefined,
@@ -73,12 +75,13 @@ export function renderAgyCall(
73
75
  const model = callArgs.model ?? callArgs.tier ?? "default";
74
76
  const mode = callArgs.mode ?? "accept-edits";
75
77
  const contextMode = callArgs.context ?? "none";
78
+ const agent = callArgs.agent ? oneLine(callArgs.agent, 128) : "";
76
79
  const header =
77
80
  theme.fg("toolTitle", theme.bold("agy ")) +
78
81
  theme.fg("accent", String(model)) +
79
82
  theme.fg(
80
83
  "dim",
81
- ` · ${String(mode)}${contextMode === "none" ? "" : ` · context ${String(contextMode)}`}`,
84
+ ` · ${String(mode)}${agent ? ` · agent ${agent}` : ""}${contextMode === "none" ? "" : ` · context ${String(contextMode)}`}`,
82
85
  );
83
86
  const promptLine = oneLine(callArgs.prompt, 180);
84
87
  return new Text(
@@ -123,7 +126,10 @@ function formatAgyResult(
123
126
  : "";
124
127
  const lines = [
125
128
  theme.fg("success", "✓ agy") +
126
- theme.fg("muted", ` · ${details.model} · ${details.mode}${duration}`),
129
+ theme.fg(
130
+ "muted",
131
+ ` · ${details.model} · ${details.mode}${details.agent ? ` · agent ${oneLine(details.agent, 128)}` : ""}${duration}`,
132
+ ),
127
133
  ];
128
134
 
129
135
  const metadata: string[] = [];
@@ -134,6 +140,27 @@ function formatAgyResult(
134
140
  }
135
141
  if (metadata.length) lines.push(theme.fg("dim", metadata.join(" · ")));
136
142
 
143
+ const subagents = Array.isArray(details.subagents) ? details.subagents.slice(0, 32) : [];
144
+ if (subagents.length) {
145
+ const done = subagents.filter((entry) => entry?.status === "done").length;
146
+ const errors = subagents.filter((entry) => entry?.status === "error").length;
147
+ lines.push(
148
+ theme.fg(
149
+ "muted",
150
+ `${subagents.length} subagent${subagents.length === 1 ? "" : "s"} observed${done ? ` · ${done} done` : ""}${errors ? ` · ${errors} error${errors === 1 ? "" : "s"}` : ""}`,
151
+ ),
152
+ );
153
+ if (expanded) {
154
+ for (const entry of subagents) {
155
+ if (!entry || typeof entry !== "object") continue;
156
+ const name = oneLine(entry.name ?? "subagent", 80);
157
+ const status = entry.status === "active" ? "active at last event" : oneLine(entry.status, 30);
158
+ const task = entry.task ? ` · ${oneLine(entry.task, 120)}` : "";
159
+ lines.push(theme.fg("toolOutput", `↳ ${name} · ${status}${task}`));
160
+ }
161
+ }
162
+ }
163
+
137
164
  const changed = details.changed_files ?? [];
138
165
  const preexisting = details.preexisting_files ?? [];
139
166
  if (changed.length || preexisting.length) {
@@ -16,6 +16,7 @@ import { randomUUID } from "node:crypto";
16
16
  export interface AgyConversationEntry {
17
17
  conversation_id: string;
18
18
  model?: string;
19
+ agent?: string;
19
20
  updated_at: string;
20
21
  /** Short task excerpt so humans and agents can tell conversations apart. */
21
22
  summary?: string;
@@ -24,6 +25,7 @@ export interface AgyConversationEntry {
24
25
  export interface AgySessionRecord {
25
26
  last_conversation_id?: string;
26
27
  last_model?: string;
28
+ last_agent?: string;
27
29
  updated_at?: string;
28
30
  /** Recent conversations for the directory, most recent first. */
29
31
  history?: AgyConversationEntry[];
@@ -69,6 +71,7 @@ export interface AgySessionStore {
69
71
  model?: string,
70
72
  signal?: AbortSignal,
71
73
  summary?: string,
74
+ agent?: string,
72
75
  ): Promise<void>;
73
76
  }
74
77
 
@@ -160,6 +163,12 @@ export function createSessionStore(
160
163
  updated_at: entry.updated_at,
161
164
  };
162
165
  if (typeof entry.model === "string") normalized.model = entry.model;
166
+ if (typeof entry.agent === "string") {
167
+ const agent = entry.agent.trim();
168
+ if (agent && agent.length <= 128 && !/[\x00-\x1f\x7f]/.test(agent)) {
169
+ normalized.agent = agent;
170
+ }
171
+ }
163
172
  if (typeof entry.summary === "string") normalized.summary = entry.summary;
164
173
  return normalized;
165
174
  })
@@ -245,6 +254,7 @@ export function createSessionStore(
245
254
  model?: string,
246
255
  signal?: AbortSignal,
247
256
  summary?: string,
257
+ agent?: string,
248
258
  ): Promise<void> {
249
259
  const operation = waitForMutation(signal).then(() =>
250
260
  withStoreLock(async () => {
@@ -255,9 +265,10 @@ export function createSessionStore(
255
265
  store[key] = {
256
266
  last_conversation_id: conversationId,
257
267
  last_model: model,
268
+ last_agent: agent,
258
269
  updated_at: updatedAt,
259
270
  history: [
260
- { conversation_id: conversationId, model, updated_at: updatedAt, summary },
271
+ { conversation_id: conversationId, model, agent, updated_at: updatedAt, summary },
261
272
  ...(Array.isArray(record.history) ? record.history : []).filter(
262
273
  (entry) =>
263
274
  entry &&
@@ -295,6 +306,7 @@ export function saveSession(
295
306
  model?: string,
296
307
  signal?: AbortSignal,
297
308
  summary?: string,
309
+ agent?: string,
298
310
  ): Promise<void> {
299
- return defaultStore.saveSession(dir, conversationId, model, signal, summary);
311
+ return defaultStore.saveSession(dir, conversationId, model, signal, summary, agent);
300
312
  }
@@ -1,5 +1,11 @@
1
1
  import { stripTerminalSequences } from "@earendil-works/pi-tui";
2
2
 
3
+ import {
4
+ formatAgySubagentProgress,
5
+ observeAgySubagents,
6
+ type AgyObservedSubagent,
7
+ } from "./subagents.js";
8
+
3
9
  export interface AgyUsage {
4
10
  input_tokens?: number;
5
11
  output_tokens?: number;
@@ -20,7 +26,10 @@ export interface AgyStepUpdate {
20
26
  tool_info?: {
21
27
  name?: string;
22
28
  parameters?: Record<string, unknown>;
29
+ error?: { message?: unknown };
23
30
  };
31
+ subagent_info?: { subagents?: unknown };
32
+ error?: { message?: unknown };
24
33
  }
25
34
 
26
35
  export interface AgyStreamLine {
@@ -51,6 +60,8 @@ export interface AgyRunResult {
51
60
  conversation_id?: string;
52
61
  usage?: AgyUsage;
53
62
  duration_seconds?: number;
63
+ /** Bounded observations from subagent stream steps; not live lifecycle state. */
64
+ subagents?: AgyObservedSubagent[];
54
65
  }
55
66
 
56
67
  export type AgyProgressHandler = (
@@ -108,6 +119,9 @@ export function formatStepProgress(parsed: AgyStreamLine): string | null {
108
119
  const step = parsed.step_update;
109
120
  if (!step) return null;
110
121
 
122
+ const subagentProgress = formatAgySubagentProgress(step);
123
+ if (subagentProgress) return subagentProgress;
124
+
111
125
  if (step.step_type === "tool" && step.state === "ACTIVE") {
112
126
  const name =
113
127
  compactProgressValue(step.tool_name ?? step.tool_info?.name, 40) ?? "tool";
@@ -216,6 +230,7 @@ export function accumulateRunResult(parsed: AgyStreamLine, current: AgyRunResult
216
230
 
217
231
  const step = parsed.step_update;
218
232
  if (typeof step?.conversation_id === "string") next.conversation_id = step.conversation_id;
233
+ if (step) next.subagents = observeAgySubagents(next.subagents, step);
219
234
 
220
235
  if (parsed.result) {
221
236
  if (typeof parsed.result.conversation_id === "string") {
@@ -0,0 +1,236 @@
1
+ import { stripTerminalSequences } from "@earendil-works/pi-tui";
2
+
3
+ export type AgyObservedSubagentStatus = "active" | "done" | "error";
4
+
5
+ export interface AgyObservedSubagent {
6
+ /** Correlation data from the agy stream; not an internal lifecycle handle. */
7
+ step_index?: number;
8
+ slot: number;
9
+ name: string;
10
+ type?: string;
11
+ task?: string;
12
+ status: AgyObservedSubagentStatus;
13
+ duration_seconds?: number;
14
+ error?: string;
15
+ }
16
+
17
+ export interface AgySubagentStep {
18
+ step_index?: number;
19
+ state?: string;
20
+ step_type?: string;
21
+ tool_name?: string;
22
+ duration_seconds?: number;
23
+ subagent_info?: { subagents?: unknown };
24
+ tool_info?: {
25
+ name?: string;
26
+ parameters?: Record<string, unknown>;
27
+ error?: { message?: unknown };
28
+ };
29
+ error?: { message?: unknown };
30
+ }
31
+
32
+ export const MAX_OBSERVED_SUBAGENTS = 32;
33
+ const MAX_REPORTED_SUBAGENTS = 12;
34
+
35
+ const SPAWN_TOOLS = new Set([
36
+ "invoke_subagent",
37
+ "run_subagent",
38
+ "define_subagent",
39
+ "browser_subagent",
40
+ ]);
41
+ const NON_SPAWN_SUBAGENT_TOOLS = new Set(["send_message", "manage_subagents"]);
42
+
43
+ function clean(value: unknown, max: number): string | undefined {
44
+ if (typeof value !== "string") return undefined;
45
+ const text = stripTerminalSequences(value)
46
+ .replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]+/g, " ")
47
+ .replace(/\s+/g, " ")
48
+ .trim();
49
+ if (!text) return undefined;
50
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
51
+ }
52
+
53
+ function pick(record: Record<string, unknown>, keys: string[], max: number): string | undefined {
54
+ for (const key of keys) {
55
+ const value = clean(record[key], max);
56
+ if (value) return value;
57
+ }
58
+ return undefined;
59
+ }
60
+
61
+ interface Candidate {
62
+ slot: number;
63
+ name: string;
64
+ type?: string;
65
+ task?: string;
66
+ }
67
+
68
+ function candidatesFromArray(raw: unknown[]): Candidate[] {
69
+ return raw.slice(0, MAX_OBSERVED_SUBAGENTS).flatMap((value, slot) => {
70
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return [];
71
+ const record = value as Record<string, unknown>;
72
+ const type = pick(record, ["type_name", "type", "Type"], 40);
73
+ const name = pick(record, ["role", "name", "Name"], 80) ?? type ?? "subagent";
74
+ const task = pick(record, ["initial_prompt", "task", "Task", "prompt", "Prompt"], 120);
75
+ return [{ slot, name, type, task }];
76
+ });
77
+ }
78
+
79
+ function candidates(step: AgySubagentStep): Candidate[] {
80
+ const tool = clean(step.tool_name ?? step.tool_info?.name, 40);
81
+ const raw = step.subagent_info?.subagents;
82
+ if (Array.isArray(raw)) return candidatesFromArray(raw);
83
+
84
+ if (!tool || !SPAWN_TOOLS.has(tool)) return [];
85
+ const parameters = step.tool_info?.parameters ?? {};
86
+ const nested = parameters.Subagents ?? parameters.subagents;
87
+ if (Array.isArray(nested)) return candidatesFromArray(nested);
88
+ const type = pick(parameters, ["Type", "type"], 40);
89
+ return [{
90
+ slot: 0,
91
+ name:
92
+ pick(parameters, ["Name", "name", "Role", "role", "Agent", "agent"], 80) ??
93
+ type ??
94
+ tool,
95
+ type,
96
+ task: pick(
97
+ parameters,
98
+ ["Task", "task", "Prompt", "prompt", "Instruction", "instruction", "Goal", "goal"],
99
+ 120,
100
+ ),
101
+ }];
102
+ }
103
+
104
+ function isSpawnStep(step: AgySubagentStep, tool: string | undefined): boolean {
105
+ if (tool && NON_SPAWN_SUBAGENT_TOOLS.has(tool)) return false;
106
+ return step.step_type === "subagent" || Boolean(tool && SPAWN_TOOLS.has(tool));
107
+ }
108
+
109
+ function statusFor(state: string | undefined): AgyObservedSubagentStatus | undefined {
110
+ if (state === "ACTIVE") return "active";
111
+ if (state === "DONE") return "done";
112
+ if (state === "ERROR") return "error";
113
+ return undefined;
114
+ }
115
+
116
+ function sameEntry(
117
+ entry: AgyObservedSubagent,
118
+ step: AgySubagentStep,
119
+ candidate: Candidate,
120
+ ): boolean {
121
+ if (typeof step.step_index === "number") {
122
+ return entry.step_index === step.step_index && entry.slot === candidate.slot;
123
+ }
124
+ return entry.step_index === undefined && entry.slot === candidate.slot && entry.name === candidate.name;
125
+ }
126
+
127
+ /**
128
+ * Fold one agy stream step into a bounded observation list. This records what
129
+ * the stream reported; it never claims the subagent is still live or exposes a
130
+ * controllable lifecycle handle.
131
+ */
132
+ export function observeAgySubagents(
133
+ current: AgyObservedSubagent[] | undefined,
134
+ step: AgySubagentStep,
135
+ ): AgyObservedSubagent[] | undefined {
136
+ const tool = clean(step.tool_name ?? step.tool_info?.name, 40);
137
+ if (!isSpawnStep(step, tool)) return current;
138
+
139
+ const status = statusFor(step.state);
140
+ if (!status) return current;
141
+ const next = (current ?? []).map((entry) => ({ ...entry }));
142
+ const found = candidates(step);
143
+ const duration =
144
+ typeof step.duration_seconds === "number" &&
145
+ Number.isFinite(step.duration_seconds) &&
146
+ step.duration_seconds >= 0
147
+ ? step.duration_seconds
148
+ : undefined;
149
+ const error =
150
+ status === "error"
151
+ ? clean(step.error?.message ?? step.tool_info?.error?.message, 120) ?? "subagent step error"
152
+ : undefined;
153
+
154
+ // Completion records can omit their original payload. Update every entry
155
+ // correlated to the step rather than inventing a nameless replacement.
156
+ if (found.length === 0 && typeof step.step_index === "number") {
157
+ for (const entry of next) {
158
+ if (entry.step_index !== step.step_index) continue;
159
+ entry.status = status;
160
+ if (duration !== undefined) entry.duration_seconds = duration;
161
+ if (error) entry.error = error;
162
+ }
163
+ return next.length ? next : undefined;
164
+ }
165
+
166
+ for (const candidate of found) {
167
+ const existing = next.find((entry) => sameEntry(entry, step, candidate));
168
+ if (existing) {
169
+ existing.name = candidate.name;
170
+ existing.type = candidate.type ?? existing.type;
171
+ existing.task = candidate.task ?? existing.task;
172
+ existing.status = status;
173
+ if (duration !== undefined) existing.duration_seconds = duration;
174
+ if (error) existing.error = error;
175
+ continue;
176
+ }
177
+ if (next.length >= MAX_OBSERVED_SUBAGENTS) break;
178
+ next.push({
179
+ ...(typeof step.step_index === "number" ? { step_index: step.step_index } : {}),
180
+ slot: candidate.slot,
181
+ name: candidate.name,
182
+ type: candidate.type,
183
+ task: candidate.task,
184
+ status,
185
+ duration_seconds: duration,
186
+ error,
187
+ });
188
+ }
189
+ return next.length ? next : undefined;
190
+ }
191
+
192
+ function formatDuration(seconds: number): string {
193
+ if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)}s`;
194
+ return `${Math.floor(seconds / 60)}m${Math.round(seconds % 60)}s`;
195
+ }
196
+
197
+ /** Bounded final report suitable for tool content and native rendering. */
198
+ export function formatAgySubagentObservations(
199
+ entries: readonly AgyObservedSubagent[] | undefined,
200
+ ): string | undefined {
201
+ if (!entries?.length) return undefined;
202
+ const lines = [`agy subagents observed: ${entries.length}`];
203
+ for (const entry of entries.slice(0, MAX_REPORTED_SUBAGENTS)) {
204
+ const status = entry.status === "active" ? "active at last event" : entry.status;
205
+ const parts = [
206
+ `- ${clean(entry.name, 80) ?? "subagent"}`,
207
+ status,
208
+ typeof entry.duration_seconds === "number"
209
+ ? formatDuration(entry.duration_seconds)
210
+ : undefined,
211
+ entry.type ? `type ${clean(entry.type, 40)}` : undefined,
212
+ entry.task ? `“${clean(entry.task, 120)}”` : undefined,
213
+ entry.error ? clean(entry.error, 120) : undefined,
214
+ ].filter((part): part is string => Boolean(part));
215
+ lines.push(parts.join(" · "));
216
+ }
217
+ if (entries.length > MAX_REPORTED_SUBAGENTS) {
218
+ lines.push(`- … ${entries.length - MAX_REPORTED_SUBAGENTS} more in structured details`);
219
+ }
220
+ return lines.join("\n");
221
+ }
222
+
223
+ /** Compact progress text for a native subagent stream step. */
224
+ export function formatAgySubagentProgress(step: AgySubagentStep): string | undefined {
225
+ const tool = clean(step.tool_name ?? step.tool_info?.name, 40);
226
+ if (!isSpawnStep(step, tool)) return undefined;
227
+ const found = candidates(step);
228
+ if (found.length === 0) return undefined;
229
+ const first = found[0];
230
+ const extra = found.length > 1 ? ` +${found.length - 1}` : "";
231
+ const task = first.task ? ` — ${first.task}` : "";
232
+ if (step.state === "ACTIVE") return `▸ subagent ${first.name}${extra}${task}`;
233
+ if (step.state === "DONE") return `✓ subagent ${first.name}${extra} completed`;
234
+ if (step.state === "ERROR") return `✗ subagent ${first.name}${extra} errored`;
235
+ return undefined;
236
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juanbenjumea/pi-agy",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "description": "Reliable Antigravity delegation for Pi — quota-aware runs, resumable tasks, repo verification, cancellation, and trustworthy diff summaries.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -3,7 +3,7 @@ name: agy-delegate
3
3
  description: >
4
4
  Delegate bulk implementation, scaffolding, repetitive refactors, and
5
5
  exhaustive test generation to the Antigravity CLI (agy).
6
- argument-hint: "prompt=\"...\" [model=flash-low|flash-medium|flash-high|pro-low|pro-high|sonnet|opus|gpt-oss] [mode=plan|accept-edits|sandbox]"
6
+ argument-hint: "prompt=\"...\" [model=flash-low|flash-medium|flash-high|pro-low|pro-high|sonnet|opus|gpt-oss] [agent=name] [mode=plan|accept-edits|sandbox]"
7
7
  license: MIT
8
8
  ---
9
9
 
@@ -43,6 +43,8 @@ agy_execute prompt="Plan the migration to ESM" model=sonnet mode=plan digest=tru
43
43
  agy_execute prompt="Review our earlier API decision" model=sonnet mode=plan context=summary
44
44
  agy_execute prompt="Implement the approved plan" conversation_id=<id> mode=accept-edits
45
45
  agy_execute prompt="Adversarial review the diff" model=opus effort=high mode=plan
46
+ agy_agents
47
+ agy_execute prompt="Investigate the crash" agent=gsd-debugger mode=plan
46
48
  agy_history
47
49
  agy_usage
48
50
  ```
@@ -62,6 +64,7 @@ agy_usage
62
64
  - **Run `just ci`** (or the project gate) after write modes in this repo.
63
65
  - **Never use agy for irreversible production changes or persistent background servers/watchers.** Delegations are bounded; timeout/cancellation kills the full process tree rather than releasing unowned work.
64
66
  - Reuse `conversation_id` or `continue=true` for multi-step plan → implement → review.
67
+ - Use `agent` only when the user requests a configured custom agent; call `agy_agents` first when the exact name is unknown. Recorded agent identity is restored on resume.
65
68
  - Keep `context=none` (default) unless the task depends on prior Pi discussion; prefer `summary` over `recent` to minimize disclosure. Context handoff excludes system prompts, thinking, tool arguments/results, images, and custom messages.
66
69
  - Use `flash-medium` by default, `flash-low` for trivial/high-volume work, and `flash-high` for difficult agentic work.
67
70
  - Escalate within the Gemini quota group to `pro-low` or `pro-high` only when needed.
@@ -74,7 +77,9 @@ agy_usage
74
77
  ## Enhancements over upstream pi-agy
75
78
 
76
79
  - **Quota discovery** — `agy_usage` and `/agy usage` report model-specific remaining quota and reset times; executions refresh quota snapshots, automatically fall back when an implicit default is exhausted, and return machine-readable `quota_status` as well.
80
+ - **Custom-agent selection** — `agy_agents` and `/agy agents` list configured agents without inference; `agent` / `agent=name` passes a validated `--agent` and persists its identity with resumable conversations.
77
81
  - **Streaming progress and receipts** — live tool steps via `stream-json` and Pi `onUpdate`; direct `/agy` runs persist bounded, expandable TUI-only receipts without feeding them to the primary model.
82
+ - **Observed subagents** — native subagent stream steps produce bounded progress and a capped per-run roster in result details/receipts. `active at last event` is diagnostic history, never a claim of live lifecycle control.
78
83
  - **Conversation continuity** — `conversation_id`, `continue`, session store under `$PI_CODING_AGENT_DIR/agy-sessions.json` (or `~/.pi/agent/agy-sessions.json` by default) with one-line task summaries; runs that time out or are cancelled are recorded too and stay resumable, and the `agy_history` tool lets agents list past conversations.
79
84
  - **Optional Pi context handoff** — `context=summary|recent` sends bounded text-only history while excluding system prompts, thinking, tool calls/results, images, and custom messages; default is `none`.
80
85
  - **Repo-aware verify** — prefers `just ci` when a justfile defines `ci:`.