@gotgenes/pi-subagents 1.0.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.
Files changed (86) hide show
  1. package/.markdownlint-cli2.yaml +19 -0
  2. package/.prettierignore +5 -0
  3. package/.release-please-manifest.json +3 -0
  4. package/AGENTS.md +85 -0
  5. package/CHANGELOG.md +495 -0
  6. package/LICENSE +21 -0
  7. package/README.md +528 -0
  8. package/dist/agent-manager.d.ts +108 -0
  9. package/dist/agent-manager.js +390 -0
  10. package/dist/agent-runner.d.ts +93 -0
  11. package/dist/agent-runner.js +428 -0
  12. package/dist/agent-types.d.ts +48 -0
  13. package/dist/agent-types.js +136 -0
  14. package/dist/context.d.ts +12 -0
  15. package/dist/context.js +56 -0
  16. package/dist/cross-extension-rpc.d.ts +46 -0
  17. package/dist/cross-extension-rpc.js +54 -0
  18. package/dist/custom-agents.d.ts +14 -0
  19. package/dist/custom-agents.js +127 -0
  20. package/dist/default-agents.d.ts +7 -0
  21. package/dist/default-agents.js +119 -0
  22. package/dist/env.d.ts +6 -0
  23. package/dist/env.js +28 -0
  24. package/dist/group-join.d.ts +32 -0
  25. package/dist/group-join.js +116 -0
  26. package/dist/index.d.ts +13 -0
  27. package/dist/index.js +1731 -0
  28. package/dist/invocation-config.d.ts +22 -0
  29. package/dist/invocation-config.js +15 -0
  30. package/dist/memory.d.ts +49 -0
  31. package/dist/memory.js +151 -0
  32. package/dist/model-resolver.d.ts +19 -0
  33. package/dist/model-resolver.js +62 -0
  34. package/dist/output-file.d.ts +24 -0
  35. package/dist/output-file.js +86 -0
  36. package/dist/prompts.d.ts +29 -0
  37. package/dist/prompts.js +72 -0
  38. package/dist/schedule-store.d.ts +36 -0
  39. package/dist/schedule-store.js +144 -0
  40. package/dist/schedule.d.ts +109 -0
  41. package/dist/schedule.js +338 -0
  42. package/dist/settings.d.ts +66 -0
  43. package/dist/settings.js +130 -0
  44. package/dist/skill-loader.d.ts +24 -0
  45. package/dist/skill-loader.js +93 -0
  46. package/dist/types.d.ts +164 -0
  47. package/dist/types.js +5 -0
  48. package/dist/ui/agent-widget.d.ts +134 -0
  49. package/dist/ui/agent-widget.js +451 -0
  50. package/dist/ui/conversation-viewer.d.ts +35 -0
  51. package/dist/ui/conversation-viewer.js +252 -0
  52. package/dist/ui/schedule-menu.d.ts +16 -0
  53. package/dist/ui/schedule-menu.js +95 -0
  54. package/dist/usage.d.ts +50 -0
  55. package/dist/usage.js +49 -0
  56. package/dist/worktree.d.ts +36 -0
  57. package/dist/worktree.js +139 -0
  58. package/docs/decisions/0001-deferred-patches.md +75 -0
  59. package/package.json +68 -0
  60. package/prek.toml +24 -0
  61. package/release-please-config.json +22 -0
  62. package/src/agent-manager.ts +482 -0
  63. package/src/agent-runner.ts +625 -0
  64. package/src/agent-types.ts +164 -0
  65. package/src/context.ts +58 -0
  66. package/src/cross-extension-rpc.ts +95 -0
  67. package/src/custom-agents.ts +136 -0
  68. package/src/default-agents.ts +123 -0
  69. package/src/env.ts +33 -0
  70. package/src/group-join.ts +141 -0
  71. package/src/index.ts +1894 -0
  72. package/src/invocation-config.ts +40 -0
  73. package/src/memory.ts +165 -0
  74. package/src/model-resolver.ts +81 -0
  75. package/src/output-file.ts +96 -0
  76. package/src/prompts.ts +105 -0
  77. package/src/schedule-store.ts +143 -0
  78. package/src/schedule.ts +365 -0
  79. package/src/settings.ts +186 -0
  80. package/src/skill-loader.ts +102 -0
  81. package/src/types.ts +176 -0
  82. package/src/ui/agent-widget.ts +533 -0
  83. package/src/ui/conversation-viewer.ts +261 -0
  84. package/src/ui/schedule-menu.ts +104 -0
  85. package/src/usage.ts +60 -0
  86. package/src/worktree.ts +162 -0
package/dist/index.js ADDED
@@ -0,0 +1,1731 @@
1
+ /**
2
+ * pi-agents — A pi extension providing Claude Code-style autonomous sub-agents.
3
+ *
4
+ * Tools:
5
+ * Agent — LLM-callable: spawn a sub-agent
6
+ * get_subagent_result — LLM-callable: check background agent status/result
7
+ * steer_subagent — LLM-callable: send a steering message to a running agent
8
+ *
9
+ * Commands:
10
+ * /agents — Interactive agent management menu
11
+ */
12
+ import { existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { defineTool, getAgentDir } from "@earendil-works/pi-coding-agent";
15
+ import { Text } from "@earendil-works/pi-tui";
16
+ import { Type } from "@sinclair/typebox";
17
+ import { AgentManager } from "./agent-manager.js";
18
+ import { getAgentConversation, getDefaultMaxTurns, getGraceTurns, normalizeMaxTurns, setDefaultMaxTurns, setGraceTurns, steerAgent } from "./agent-runner.js";
19
+ import { BUILTIN_TOOL_NAMES, getAgentConfig, getAllTypes, getAvailableTypes, getDefaultAgentNames, getUserAgentNames, registerAgents, resolveType } from "./agent-types.js";
20
+ import { registerRpcHandlers } from "./cross-extension-rpc.js";
21
+ import { loadCustomAgents } from "./custom-agents.js";
22
+ import { GroupJoinManager } from "./group-join.js";
23
+ import { resolveAgentInvocationConfig, resolveJoinMode } from "./invocation-config.js";
24
+ import { resolveModel } from "./model-resolver.js";
25
+ import { createOutputFilePath, streamToOutputFile, writeInitialEntry } from "./output-file.js";
26
+ import { SubagentScheduler } from "./schedule.js";
27
+ import { resolveStorePath, ScheduleStore } from "./schedule-store.js";
28
+ import { applyAndEmitLoaded, saveAndEmitChanged } from "./settings.js";
29
+ import { AgentWidget, buildInvocationTags, describeActivity, formatDuration, formatMs, formatTokens, formatTurns, getDisplayName, getPromptModeLabel, SPINNER, } from "./ui/agent-widget.js";
30
+ import { showSchedulesMenu } from "./ui/schedule-menu.js";
31
+ import { addUsage, getLifetimeTotal, getSessionContextPercent } from "./usage.js";
32
+ // ---- Shared helpers ----
33
+ /** Tool execute return value for a text response. */
34
+ function textResult(msg, details) {
35
+ return { content: [{ type: "text", text: msg }], details: details };
36
+ }
37
+ /** Format an agent's lifetime token total, or "" when zero. */
38
+ function formatLifetimeTokens(o) {
39
+ const t = getLifetimeTotal(o.lifetimeUsage);
40
+ return t > 0 ? formatTokens(t) : "";
41
+ }
42
+ /**
43
+ * Create an AgentActivity state and spawn callbacks for tracking tool usage.
44
+ * Used by both foreground and background paths to avoid duplication.
45
+ */
46
+ function createActivityTracker(maxTurns, onStreamUpdate) {
47
+ const state = {
48
+ activeTools: new Map(),
49
+ toolUses: 0,
50
+ turnCount: 1,
51
+ maxTurns,
52
+ responseText: "",
53
+ session: undefined,
54
+ lifetimeUsage: { input: 0, output: 0, cacheWrite: 0 },
55
+ };
56
+ const callbacks = {
57
+ onToolActivity: (activity) => {
58
+ if (activity.type === "start") {
59
+ state.activeTools.set(activity.toolName + "_" + Date.now(), activity.toolName);
60
+ }
61
+ else {
62
+ for (const [key, name] of state.activeTools) {
63
+ if (name === activity.toolName) {
64
+ state.activeTools.delete(key);
65
+ break;
66
+ }
67
+ }
68
+ state.toolUses++;
69
+ }
70
+ onStreamUpdate?.();
71
+ },
72
+ onTextDelta: (_delta, fullText) => {
73
+ state.responseText = fullText;
74
+ onStreamUpdate?.();
75
+ },
76
+ onTurnEnd: (turnCount) => {
77
+ state.turnCount = turnCount;
78
+ onStreamUpdate?.();
79
+ },
80
+ onSessionCreated: (session) => {
81
+ state.session = session;
82
+ },
83
+ onAssistantUsage: (usage) => {
84
+ addUsage(state.lifetimeUsage, usage);
85
+ onStreamUpdate?.();
86
+ },
87
+ };
88
+ return { state, callbacks };
89
+ }
90
+ /** Human-readable status label for agent completion. */
91
+ function getStatusLabel(status, error) {
92
+ switch (status) {
93
+ case "error": return `Error: ${error ?? "unknown"}`;
94
+ case "aborted": return "Aborted (max turns exceeded)";
95
+ case "steered": return "Wrapped up (turn limit)";
96
+ case "stopped": return "Stopped";
97
+ default: return "Done";
98
+ }
99
+ }
100
+ /** Parenthetical status note for completed agent result text. */
101
+ function getStatusNote(status) {
102
+ switch (status) {
103
+ case "aborted": return " (aborted — max turns exceeded, output may be incomplete)";
104
+ case "steered": return " (wrapped up — reached turn limit)";
105
+ case "stopped": return " (stopped by user)";
106
+ default: return "";
107
+ }
108
+ }
109
+ /** Escape XML special characters to prevent injection in structured notifications. */
110
+ function escapeXml(s) {
111
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
112
+ }
113
+ /** Format a structured task notification matching Claude Code's <task-notification> XML. */
114
+ function formatTaskNotification(record, resultMaxLen) {
115
+ const status = getStatusLabel(record.status, record.error);
116
+ const durationMs = record.completedAt ? record.completedAt - record.startedAt : 0;
117
+ const totalTokens = getLifetimeTotal(record.lifetimeUsage);
118
+ const contextPercent = getSessionContextPercent(record.session);
119
+ const ctxXml = contextPercent !== null ? `<context_percent>${Math.round(contextPercent)}</context_percent>` : "";
120
+ const compactXml = record.compactionCount ? `<compactions>${record.compactionCount}</compactions>` : "";
121
+ const resultPreview = record.result
122
+ ? record.result.length > resultMaxLen
123
+ ? record.result.slice(0, resultMaxLen) + "\n...(truncated, use get_subagent_result for full output)"
124
+ : record.result
125
+ : "No output.";
126
+ return [
127
+ `<task-notification>`,
128
+ `<task-id>${record.id}</task-id>`,
129
+ record.toolCallId ? `<tool-use-id>${escapeXml(record.toolCallId)}</tool-use-id>` : null,
130
+ record.outputFile ? `<output-file>${escapeXml(record.outputFile)}</output-file>` : null,
131
+ `<status>${escapeXml(status)}</status>`,
132
+ `<summary>Agent "${escapeXml(record.description)}" ${record.status}</summary>`,
133
+ `<result>${escapeXml(resultPreview)}</result>`,
134
+ `<usage><total_tokens>${totalTokens}</total_tokens><tool_uses>${record.toolUses}</tool_uses>${ctxXml}${compactXml}<duration_ms>${durationMs}</duration_ms></usage>`,
135
+ `</task-notification>`,
136
+ ].filter(Boolean).join('\n');
137
+ }
138
+ /** Build AgentDetails from a base + record-specific fields. */
139
+ function buildDetails(base, record, activity, overrides) {
140
+ return {
141
+ ...base,
142
+ toolUses: record.toolUses,
143
+ tokens: formatLifetimeTokens(record),
144
+ turnCount: activity?.turnCount,
145
+ maxTurns: activity?.maxTurns,
146
+ durationMs: (record.completedAt ?? Date.now()) - record.startedAt,
147
+ status: record.status,
148
+ agentId: record.id,
149
+ error: record.error,
150
+ ...overrides,
151
+ };
152
+ }
153
+ /** Build notification details for the custom message renderer. */
154
+ function buildNotificationDetails(record, resultMaxLen, activity) {
155
+ const totalTokens = getLifetimeTotal(record.lifetimeUsage);
156
+ return {
157
+ id: record.id,
158
+ description: record.description,
159
+ status: record.status,
160
+ toolUses: record.toolUses,
161
+ turnCount: activity?.turnCount ?? 0,
162
+ maxTurns: activity?.maxTurns,
163
+ totalTokens,
164
+ durationMs: record.completedAt ? record.completedAt - record.startedAt : 0,
165
+ outputFile: record.outputFile,
166
+ error: record.error,
167
+ resultPreview: record.result
168
+ ? record.result.length > resultMaxLen
169
+ ? record.result.slice(0, resultMaxLen) + "…"
170
+ : record.result
171
+ : "No output.",
172
+ };
173
+ }
174
+ export default function (pi) {
175
+ // ---- Register custom notification renderer ----
176
+ pi.registerMessageRenderer("subagent-notification", (message, { expanded }, theme) => {
177
+ const d = message.details;
178
+ if (!d)
179
+ return undefined;
180
+ function renderOne(d) {
181
+ const isError = d.status === "error" || d.status === "stopped" || d.status === "aborted";
182
+ const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
183
+ const statusText = isError ? d.status
184
+ : d.status === "steered" ? "completed (steered)"
185
+ : "completed";
186
+ // Line 1: icon + agent description + status
187
+ let line = `${icon} ${theme.bold(d.description)} ${theme.fg("dim", statusText)}`;
188
+ // Line 2: stats
189
+ const parts = [];
190
+ if (d.turnCount > 0)
191
+ parts.push(formatTurns(d.turnCount, d.maxTurns));
192
+ if (d.toolUses > 0)
193
+ parts.push(`${d.toolUses} tool use${d.toolUses === 1 ? "" : "s"}`);
194
+ if (d.totalTokens > 0)
195
+ parts.push(formatTokens(d.totalTokens));
196
+ if (d.durationMs > 0)
197
+ parts.push(formatMs(d.durationMs));
198
+ if (parts.length) {
199
+ line += "\n " + parts.map(p => theme.fg("dim", p)).join(" " + theme.fg("dim", "·") + " ");
200
+ }
201
+ // Line 3: result preview (collapsed) or full (expanded)
202
+ if (expanded) {
203
+ const lines = d.resultPreview.split("\n").slice(0, 30);
204
+ for (const l of lines)
205
+ line += "\n" + theme.fg("dim", ` ${l}`);
206
+ }
207
+ else {
208
+ const preview = d.resultPreview.split("\n")[0]?.slice(0, 80) ?? "";
209
+ line += "\n " + theme.fg("dim", `⎿ ${preview}`);
210
+ }
211
+ // Line 4: output file link (if present)
212
+ if (d.outputFile) {
213
+ line += "\n " + theme.fg("muted", `transcript: ${d.outputFile}`);
214
+ }
215
+ return line;
216
+ }
217
+ const all = [d, ...(d.others ?? [])];
218
+ return new Text(all.map(renderOne).join("\n"), 0, 0);
219
+ });
220
+ /** Reload agents from .pi/agents/*.md and merge with defaults (called on init and each Agent invocation). */
221
+ const reloadCustomAgents = () => {
222
+ const userAgents = loadCustomAgents(process.cwd());
223
+ registerAgents(userAgents);
224
+ };
225
+ // Initial load
226
+ reloadCustomAgents();
227
+ // ---- Agent activity tracking + widget ----
228
+ const agentActivity = new Map();
229
+ // ---- Cancellable pending notifications ----
230
+ // Holds notifications briefly so get_subagent_result can cancel them
231
+ // before they reach pi.sendMessage (fire-and-forget).
232
+ const pendingNudges = new Map();
233
+ const NUDGE_HOLD_MS = 200;
234
+ function scheduleNudge(key, send, delay = NUDGE_HOLD_MS) {
235
+ cancelNudge(key);
236
+ pendingNudges.set(key, setTimeout(() => {
237
+ pendingNudges.delete(key);
238
+ try {
239
+ send();
240
+ }
241
+ catch { /* ignore stale completion side-effect errors */ }
242
+ }, delay));
243
+ }
244
+ function cancelNudge(key) {
245
+ const timer = pendingNudges.get(key);
246
+ if (timer != null) {
247
+ clearTimeout(timer);
248
+ pendingNudges.delete(key);
249
+ }
250
+ }
251
+ // ---- Individual nudge helper (async join mode) ----
252
+ function emitIndividualNudge(record) {
253
+ if (record.resultConsumed)
254
+ return; // re-check at send time
255
+ const notification = formatTaskNotification(record, 500);
256
+ const footer = record.outputFile ? `\nFull transcript available at: ${record.outputFile}` : '';
257
+ pi.sendMessage({
258
+ customType: "subagent-notification",
259
+ content: notification + footer,
260
+ display: true,
261
+ details: buildNotificationDetails(record, 500, agentActivity.get(record.id)),
262
+ }, { deliverAs: "followUp", triggerTurn: true });
263
+ }
264
+ function sendIndividualNudge(record) {
265
+ agentActivity.delete(record.id);
266
+ widget.markFinished(record.id);
267
+ scheduleNudge(record.id, () => emitIndividualNudge(record));
268
+ widget.update();
269
+ }
270
+ // ---- Group join manager ----
271
+ const groupJoin = new GroupJoinManager((records, partial) => {
272
+ for (const r of records) {
273
+ agentActivity.delete(r.id);
274
+ widget.markFinished(r.id);
275
+ }
276
+ const groupKey = `group:${records.map(r => r.id).join(",")}`;
277
+ scheduleNudge(groupKey, () => {
278
+ // Re-check at send time
279
+ const unconsumed = records.filter(r => !r.resultConsumed);
280
+ if (unconsumed.length === 0) {
281
+ widget.update();
282
+ return;
283
+ }
284
+ const notifications = unconsumed.map(r => formatTaskNotification(r, 300)).join('\n\n');
285
+ const label = partial
286
+ ? `${unconsumed.length} agent(s) finished (partial — others still running)`
287
+ : `${unconsumed.length} agent(s) finished`;
288
+ const [first, ...rest] = unconsumed;
289
+ const details = buildNotificationDetails(first, 300, agentActivity.get(first.id));
290
+ if (rest.length > 0) {
291
+ details.others = rest.map(r => buildNotificationDetails(r, 300, agentActivity.get(r.id)));
292
+ }
293
+ pi.sendMessage({
294
+ customType: "subagent-notification",
295
+ content: `Background agent group completed: ${label}\n\n${notifications}\n\nUse get_subagent_result for full output.`,
296
+ display: true,
297
+ details,
298
+ }, { deliverAs: "followUp", triggerTurn: true });
299
+ });
300
+ widget.update();
301
+ }, 30_000);
302
+ /** Helper: build event data for lifecycle events from an AgentRecord. */
303
+ function buildEventData(record) {
304
+ const durationMs = record.completedAt ? record.completedAt - record.startedAt : Date.now() - record.startedAt;
305
+ // All three fields are lifetime-accumulated (Σ over every assistant message_end),
306
+ // so they survive compaction together — input + output ≤ total always.
307
+ // tokens is omitted when nothing was ever produced (e.g. agent errored before
308
+ // any message_end fired), preserving prior payload shape.
309
+ const u = record.lifetimeUsage;
310
+ const total = getLifetimeTotal(u);
311
+ const tokens = total > 0
312
+ ? { input: u.input, output: u.output, total }
313
+ : undefined;
314
+ return {
315
+ id: record.id,
316
+ type: record.type,
317
+ description: record.description,
318
+ result: record.result,
319
+ error: record.error,
320
+ status: record.status,
321
+ toolUses: record.toolUses,
322
+ durationMs,
323
+ tokens,
324
+ };
325
+ }
326
+ // Background completion: route through group join or send individual nudge
327
+ const manager = new AgentManager((record) => {
328
+ // Emit lifecycle event based on terminal status
329
+ const isError = record.status === "error" || record.status === "stopped" || record.status === "aborted";
330
+ const eventData = buildEventData(record);
331
+ if (isError) {
332
+ pi.events.emit("subagents:failed", eventData);
333
+ }
334
+ else {
335
+ pi.events.emit("subagents:completed", eventData);
336
+ }
337
+ // Persist final record for cross-extension history reconstruction
338
+ pi.appendEntry("subagents:record", {
339
+ id: record.id, type: record.type, description: record.description,
340
+ status: record.status, result: record.result, error: record.error,
341
+ startedAt: record.startedAt, completedAt: record.completedAt,
342
+ });
343
+ // Skip notification if result was already consumed via get_subagent_result
344
+ if (record.resultConsumed) {
345
+ agentActivity.delete(record.id);
346
+ widget.markFinished(record.id);
347
+ widget.update();
348
+ return;
349
+ }
350
+ // If this agent is pending batch finalization (debounce window still open),
351
+ // don't send an individual nudge — finalizeBatch will pick it up retroactively.
352
+ if (currentBatchAgents.some(a => a.id === record.id)) {
353
+ widget.update();
354
+ return;
355
+ }
356
+ const result = groupJoin.onAgentComplete(record);
357
+ if (result === 'pass') {
358
+ sendIndividualNudge(record);
359
+ }
360
+ // 'held' → do nothing, group will fire later
361
+ // 'delivered' → group callback already fired
362
+ widget.update();
363
+ }, undefined, (record) => {
364
+ // Emit started event when agent transitions to running (including from queue)
365
+ pi.events.emit("subagents:started", {
366
+ id: record.id,
367
+ type: record.type,
368
+ description: record.description,
369
+ });
370
+ }, (record, info) => {
371
+ // Emit compacted event when agent's session compacts (preserves count on record).
372
+ pi.events.emit("subagents:compacted", {
373
+ id: record.id,
374
+ type: record.type,
375
+ description: record.description,
376
+ reason: info.reason,
377
+ tokensBefore: info.tokensBefore,
378
+ compactionCount: record.compactionCount,
379
+ });
380
+ });
381
+ // Expose manager via Symbol.for() global registry for cross-package access.
382
+ // Standard Node.js pattern for cross-package singletons (used by OpenTelemetry, etc.).
383
+ const MANAGER_KEY = Symbol.for("pi-subagents:manager");
384
+ globalThis[MANAGER_KEY] = {
385
+ waitForAll: () => manager.waitForAll(),
386
+ hasRunning: () => manager.hasRunning(),
387
+ spawn: (piRef, ctx, type, prompt, options) => manager.spawn(piRef, ctx, type, prompt, options),
388
+ getRecord: (id) => manager.getRecord(id),
389
+ };
390
+ // --- Cross-extension RPC via pi.events ---
391
+ let currentCtx;
392
+ // ---- Subagent scheduler ----
393
+ // Session-scoped: store is constructed inside session_start once sessionId
394
+ // is available. Mirrors pi-chonky-tasks's session-scoped task store —
395
+ // schedules reset on /new, restore on /resume.
396
+ const scheduler = new SubagentScheduler();
397
+ function startScheduler(ctx) {
398
+ try {
399
+ const sessionId = ctx.sessionManager?.getSessionId?.();
400
+ if (!sessionId)
401
+ return; // sessionId not yet available — try again on next event
402
+ const path = resolveStorePath(ctx.cwd, sessionId);
403
+ const store = new ScheduleStore(path);
404
+ scheduler.start(pi, ctx, manager, store);
405
+ pi.events.emit("subagents:scheduler_ready", { sessionId, jobCount: store.list().length });
406
+ }
407
+ catch (err) {
408
+ // Scheduling is non-essential — log and move on so the rest of the
409
+ // extension keeps working if e.g. .pi/ is unwritable.
410
+ console.warn("[pi-subagents] Failed to start scheduler:", err);
411
+ }
412
+ }
413
+ // Capture ctx from session_start for RPC spawn handler + start the scheduler.
414
+ pi.on("session_start", async (_event, ctx) => {
415
+ currentCtx = ctx;
416
+ manager.clearCompleted();
417
+ if (isSchedulingEnabled() && !scheduler.isActive())
418
+ startScheduler(ctx);
419
+ });
420
+ pi.on("session_before_switch", () => {
421
+ manager.clearCompleted();
422
+ scheduler.stop();
423
+ });
424
+ const { unsubPing: unsubPingRpc, unsubSpawn: unsubSpawnRpc, unsubStop: unsubStopRpc } = registerRpcHandlers({
425
+ events: pi.events,
426
+ pi,
427
+ getCtx: () => currentCtx,
428
+ manager,
429
+ });
430
+ // Broadcast readiness so extensions loaded after us can discover us
431
+ pi.events.emit("subagents:ready", {});
432
+ // On shutdown, abort all agents immediately and clean up.
433
+ // If the session is going down, there's nothing left to consume agent results.
434
+ pi.on("session_shutdown", async () => {
435
+ unsubSpawnRpc();
436
+ unsubStopRpc();
437
+ unsubPingRpc();
438
+ currentCtx = undefined;
439
+ delete globalThis[MANAGER_KEY];
440
+ scheduler.stop();
441
+ manager.abortAll();
442
+ for (const timer of pendingNudges.values())
443
+ clearTimeout(timer);
444
+ pendingNudges.clear();
445
+ manager.dispose();
446
+ });
447
+ // Live widget: show running agents above editor
448
+ const widget = new AgentWidget(manager, agentActivity);
449
+ // ---- Join mode configuration ----
450
+ let defaultJoinMode = 'smart';
451
+ function getDefaultJoinMode() { return defaultJoinMode; }
452
+ function setDefaultJoinMode(mode) { defaultJoinMode = mode; }
453
+ // Master switch for the schedule subagent feature. Defaults to enabled.
454
+ // Read once at extension init (before tool registration) so the Agent tool's
455
+ // param schema reflects the persisted setting. Runtime toggles via /agents
456
+ // → Settings short-circuit the menu entry + the execute-time addJob path
457
+ // immediately, but the schema-level removal only takes effect on next
458
+ // extension load (next pi session). Documented in CHANGELOG/README.
459
+ let schedulingEnabled = true;
460
+ function isSchedulingEnabled() { return schedulingEnabled; }
461
+ function setSchedulingEnabled(b) { schedulingEnabled = b; }
462
+ // ---- Batch tracking for smart join mode ----
463
+ // Collects background agent IDs spawned in the current turn for smart grouping.
464
+ // Uses a debounced timer: each new agent resets the 100ms window so that all
465
+ // parallel tool calls (which may be dispatched across multiple microtasks by the
466
+ // framework) are captured in the same batch.
467
+ let currentBatchAgents = [];
468
+ let batchFinalizeTimer;
469
+ let batchCounter = 0;
470
+ /** Finalize the current batch: if 2+ smart-mode agents, register as a group. */
471
+ function finalizeBatch() {
472
+ batchFinalizeTimer = undefined;
473
+ const batchAgents = [...currentBatchAgents];
474
+ currentBatchAgents = [];
475
+ const smartAgents = batchAgents.filter(a => a.joinMode === 'smart' || a.joinMode === 'group');
476
+ if (smartAgents.length >= 2) {
477
+ const groupId = `batch-${++batchCounter}`;
478
+ const ids = smartAgents.map(a => a.id);
479
+ groupJoin.registerGroup(groupId, ids);
480
+ // Retroactively process agents that already completed during the debounce window.
481
+ // Their onComplete fired but was deferred (agent was in currentBatchAgents),
482
+ // so we feed them into the group now.
483
+ for (const id of ids) {
484
+ const record = manager.getRecord(id);
485
+ if (!record)
486
+ continue;
487
+ record.groupId = groupId;
488
+ if (record.completedAt != null && !record.resultConsumed) {
489
+ groupJoin.onAgentComplete(record);
490
+ }
491
+ }
492
+ }
493
+ else {
494
+ // No group formed — send individual nudges for any agents that completed
495
+ // during the debounce window and had their notification deferred.
496
+ for (const { id } of batchAgents) {
497
+ const record = manager.getRecord(id);
498
+ if (record?.completedAt != null && !record.resultConsumed) {
499
+ sendIndividualNudge(record);
500
+ }
501
+ }
502
+ }
503
+ }
504
+ // Grab UI context from first tool execution + clear lingering widget on new turn
505
+ pi.on("tool_execution_start", async (_event, ctx) => {
506
+ widget.setUICtx(ctx.ui);
507
+ widget.onTurnStart();
508
+ });
509
+ /** Build the full type list text dynamically from the unified registry. */
510
+ const buildTypeListText = () => {
511
+ const defaultNames = getDefaultAgentNames();
512
+ const userNames = getUserAgentNames();
513
+ const defaultDescs = defaultNames.map((name) => {
514
+ const cfg = getAgentConfig(name);
515
+ const modelSuffix = cfg?.model ? ` (${getModelLabelFromConfig(cfg.model)})` : "";
516
+ return `- ${name}: ${cfg?.description ?? name}${modelSuffix}`;
517
+ });
518
+ const customDescs = userNames.map((name) => {
519
+ const cfg = getAgentConfig(name);
520
+ return `- ${name}: ${cfg?.description ?? name}`;
521
+ });
522
+ return [
523
+ "Default agents:",
524
+ ...defaultDescs,
525
+ ...(customDescs.length > 0 ? ["", "Custom agents:", ...customDescs] : []),
526
+ "",
527
+ `Custom agents can be defined in .pi/agents/<name>.md (project) or ${getAgentDir()}/agents/<name>.md (global) — they are picked up automatically. Project-level agents override global ones. Creating a .md file with the same name as a default agent overrides it.`,
528
+ ].join("\n");
529
+ };
530
+ /** Derive a short model label from a model string. */
531
+ function getModelLabelFromConfig(model) {
532
+ // Strip provider prefix (e.g. "anthropic/claude-sonnet-4-6" → "claude-sonnet-4-6")
533
+ const name = model.includes("/") ? model.split("/").pop() : model;
534
+ // Strip trailing date suffix (e.g. "claude-haiku-4-5-20251001" → "claude-haiku-4-5")
535
+ return name.replace(/-\d{8}$/, "");
536
+ }
537
+ const typeListText = buildTypeListText();
538
+ // Apply persisted settings on startup and emit `subagents:settings_loaded`.
539
+ // Global + project merged; missing → defaults; corrupt file emits a warning
540
+ // to stderr and falls back to defaults.
541
+ applyAndEmitLoaded({
542
+ setMaxConcurrent: (n) => manager.setMaxConcurrent(n),
543
+ setDefaultMaxTurns,
544
+ setGraceTurns,
545
+ setDefaultJoinMode,
546
+ setSchedulingEnabled,
547
+ }, (event, payload) => pi.events.emit(event, payload));
548
+ // ---- Agent tool ----
549
+ // Schedule param + its guideline are gated on `schedulingEnabled` (read once
550
+ // at registration; flipping the setting later requires next pi session for
551
+ // the schema to update). Defining the shape once and spreading it via Partial
552
+ // preserves Type.Object's inference when present and produces a
553
+ // `schedule`-free schema when absent — zero LLM-context cost in disabled mode.
554
+ const scheduleParamShape = {
555
+ schedule: Type.Optional(Type.String({
556
+ description: 'Opt-in only — fire later instead of now. Omit to run immediately (the default, almost always correct). ' +
557
+ 'Formats: 6-field cron ("0 0 9 * * 1" = 9am Mon), interval ("5m"/"1h"), one-shot ("+10m" or ISO). ' +
558
+ 'Forces run_in_background; incompatible with inherit_context and resume. Returns job ID.',
559
+ })),
560
+ };
561
+ const scheduleParam = isSchedulingEnabled() ? scheduleParamShape : {};
562
+ const scheduleGuideline = isSchedulingEnabled()
563
+ ? `\n- Use \`schedule\` only when the user explicitly asked for scheduled / recurring / delayed execution (e.g. "every Monday", "in an hour"). Don't auto-schedule from vague intent like "monitor X" — run once now or ask.`
564
+ : "";
565
+ pi.registerTool(defineTool({
566
+ name: "Agent",
567
+ label: "Agent",
568
+ description: `Launch a new agent to handle complex, multi-step tasks autonomously.
569
+
570
+ The Agent tool launches specialized agents that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
571
+
572
+ Available agent types:
573
+ ${typeListText}
574
+
575
+ Guidelines:
576
+ - For parallel work, use run_in_background: true on each agent. Foreground calls run sequentially — only one executes at a time.
577
+ - Use Explore for codebase searches and code understanding.
578
+ - Use Plan for architecture and implementation planning.
579
+ - Use general-purpose for complex tasks that need file editing.
580
+ - Provide clear, detailed prompts so the agent can work autonomously.
581
+ - Agent results are returned as text — summarize them for the user.
582
+ - Use run_in_background for work you don't need immediately. You will be notified when it completes.
583
+ - Use resume with an agent ID to continue a previous agent's work.
584
+ - Use steer_subagent to send mid-run messages to a running background agent.
585
+ - Use model to specify a different model (as "provider/modelId", or fuzzy e.g. "haiku", "sonnet").
586
+ - Use thinking to control extended thinking level.
587
+ - Use inherit_context if the agent needs the parent conversation history.
588
+ - Use isolation: "worktree" to run the agent in an isolated git worktree (safe parallel file modifications).${scheduleGuideline}`,
589
+ parameters: Type.Object({
590
+ prompt: Type.String({
591
+ description: "The task for the agent to perform.",
592
+ }),
593
+ description: Type.String({
594
+ description: "A short (3-5 word) description of the task (shown in UI).",
595
+ }),
596
+ subagent_type: Type.String({
597
+ description: `The type of specialized agent to use. Available types: ${getAvailableTypes().join(", ")}. Custom agents from .pi/agents/*.md (project) or ${getAgentDir()}/agents/*.md (global) are also available.`,
598
+ }),
599
+ model: Type.Optional(Type.String({
600
+ description: 'Optional model override. Accepts "provider/modelId" or fuzzy name (e.g. "haiku", "sonnet"). Omit to use the agent type\'s default.',
601
+ })),
602
+ thinking: Type.Optional(Type.String({
603
+ description: "Thinking level: off, minimal, low, medium, high, xhigh. Overrides agent default.",
604
+ })),
605
+ max_turns: Type.Optional(Type.Number({
606
+ description: "Maximum number of agentic turns before stopping. Omit for unlimited (default).",
607
+ minimum: 1,
608
+ })),
609
+ run_in_background: Type.Optional(Type.Boolean({
610
+ description: "Set to true to run in background. Returns agent ID immediately. You will be notified on completion.",
611
+ })),
612
+ resume: Type.Optional(Type.String({
613
+ description: "Optional agent ID to resume from. Continues from previous context.",
614
+ })),
615
+ isolated: Type.Optional(Type.Boolean({
616
+ description: "If true, agent gets no extension/MCP tools — only built-in tools.",
617
+ })),
618
+ inherit_context: Type.Optional(Type.Boolean({
619
+ description: "If true, fork parent conversation into the agent. Default: false (fresh context).",
620
+ })),
621
+ isolation: Type.Optional(Type.Literal("worktree", {
622
+ description: 'Set to "worktree" to run the agent in a temporary git worktree (isolated copy of the repo). Changes are saved to a branch on completion.',
623
+ })),
624
+ ...scheduleParam,
625
+ }),
626
+ // ---- Custom rendering: Claude Code style ----
627
+ renderCall(args, theme) {
628
+ const displayName = args.subagent_type ? getDisplayName(args.subagent_type) : "Agent";
629
+ const desc = args.description ?? "";
630
+ return new Text("▸ " + theme.fg("toolTitle", theme.bold(displayName)) + (desc ? " " + theme.fg("muted", desc) : ""), 0, 0);
631
+ },
632
+ renderResult(result, { expanded, isPartial }, theme) {
633
+ const details = result.details;
634
+ if (!details) {
635
+ const text = result.content[0]?.type === "text" ? result.content[0].text : "";
636
+ return new Text(text, 0, 0);
637
+ }
638
+ // Helper: build "haiku · thinking: high · ⟳5≤30 · 3 tool uses · 33.8k tokens" stats string
639
+ const stats = (d) => {
640
+ const parts = [];
641
+ if (d.modelName)
642
+ parts.push(d.modelName);
643
+ if (d.tags)
644
+ parts.push(...d.tags);
645
+ if (d.turnCount != null && d.turnCount > 0) {
646
+ parts.push(formatTurns(d.turnCount, d.maxTurns));
647
+ }
648
+ if (d.toolUses > 0)
649
+ parts.push(`${d.toolUses} tool use${d.toolUses === 1 ? "" : "s"}`);
650
+ if (d.tokens)
651
+ parts.push(d.tokens);
652
+ return parts.map(p => theme.fg("dim", p)).join(" " + theme.fg("dim", "·") + " ");
653
+ };
654
+ // ---- While running (streaming) ----
655
+ if (isPartial || details.status === "running") {
656
+ const frame = SPINNER[details.spinnerFrame ?? 0];
657
+ const s = stats(details);
658
+ let line = theme.fg("accent", frame) + (s ? " " + s : "");
659
+ line += "\n" + theme.fg("dim", ` ⎿ ${details.activity ?? "thinking…"}`);
660
+ return new Text(line, 0, 0);
661
+ }
662
+ // ---- Background agent launched ----
663
+ if (details.status === "background") {
664
+ return new Text(theme.fg("dim", ` ⎿ Running in background (ID: ${details.agentId})`), 0, 0);
665
+ }
666
+ // ---- Completed / Steered ----
667
+ if (details.status === "completed" || details.status === "steered") {
668
+ const duration = formatMs(details.durationMs);
669
+ const isSteered = details.status === "steered";
670
+ const icon = isSteered ? theme.fg("warning", "✓") : theme.fg("success", "✓");
671
+ const s = stats(details);
672
+ let line = icon + (s ? " " + s : "");
673
+ line += " " + theme.fg("dim", "·") + " " + theme.fg("dim", duration);
674
+ if (expanded) {
675
+ const resultText = result.content[0]?.type === "text" ? result.content[0].text : "";
676
+ if (resultText) {
677
+ const lines = resultText.split("\n").slice(0, 50);
678
+ for (const l of lines) {
679
+ line += "\n" + theme.fg("dim", ` ${l}`);
680
+ }
681
+ if (resultText.split("\n").length > 50) {
682
+ line += "\n" + theme.fg("muted", " ... (use get_subagent_result with verbose for full output)");
683
+ }
684
+ }
685
+ }
686
+ else {
687
+ const doneText = isSteered ? "Wrapped up (turn limit)" : "Done";
688
+ line += "\n" + theme.fg("dim", ` ⎿ ${doneText}`);
689
+ }
690
+ return new Text(line, 0, 0);
691
+ }
692
+ // ---- Stopped (user-initiated abort) ----
693
+ if (details.status === "stopped") {
694
+ const s = stats(details);
695
+ let line = theme.fg("dim", "■") + (s ? " " + s : "");
696
+ line += "\n" + theme.fg("dim", " ⎿ Stopped");
697
+ return new Text(line, 0, 0);
698
+ }
699
+ // ---- Error / Aborted (hard max_turns) ----
700
+ const s = stats(details);
701
+ let line = theme.fg("error", "✗") + (s ? " " + s : "");
702
+ if (details.status === "error") {
703
+ line += "\n" + theme.fg("error", ` ⎿ Error: ${details.error ?? "unknown"}`);
704
+ }
705
+ else {
706
+ line += "\n" + theme.fg("warning", " ⎿ Aborted (max turns exceeded)");
707
+ }
708
+ return new Text(line, 0, 0);
709
+ },
710
+ // ---- Execute ----
711
+ execute: async (toolCallId, params, signal, onUpdate, ctx) => {
712
+ // Ensure we have UI context for widget rendering
713
+ widget.setUICtx(ctx.ui);
714
+ // Reload custom agents so new .pi/agents/*.md files are picked up without restart
715
+ reloadCustomAgents();
716
+ const rawType = params.subagent_type;
717
+ const resolved = resolveType(rawType);
718
+ const subagentType = resolved ?? "general-purpose";
719
+ const fellBack = resolved === undefined;
720
+ const displayName = getDisplayName(subagentType);
721
+ // Get agent config (if any)
722
+ const customConfig = getAgentConfig(subagentType);
723
+ const resolvedConfig = resolveAgentInvocationConfig(customConfig, params);
724
+ // Resolve model from agent config first; tool-call params only fill gaps.
725
+ let model = ctx.model;
726
+ if (resolvedConfig.modelInput) {
727
+ const resolved = resolveModel(resolvedConfig.modelInput, ctx.modelRegistry);
728
+ if (typeof resolved === "string") {
729
+ if (resolvedConfig.modelFromParams)
730
+ return textResult(resolved);
731
+ // config-specified: silent fallback to parent
732
+ }
733
+ else {
734
+ model = resolved;
735
+ }
736
+ }
737
+ const thinking = resolvedConfig.thinking;
738
+ const inheritContext = resolvedConfig.inheritContext;
739
+ const runInBackground = resolvedConfig.runInBackground;
740
+ const isolated = resolvedConfig.isolated;
741
+ const isolation = resolvedConfig.isolation;
742
+ const parentModelId = ctx.model?.id;
743
+ const effectiveModelId = model?.id;
744
+ const modelName = effectiveModelId && effectiveModelId !== parentModelId
745
+ ? (model?.name ?? effectiveModelId).replace(/^Claude\s+/i, "").toLowerCase()
746
+ : undefined;
747
+ const effectiveMaxTurns = normalizeMaxTurns(resolvedConfig.maxTurns ?? getDefaultMaxTurns());
748
+ const agentInvocation = {
749
+ modelName,
750
+ thinking,
751
+ // Explicit value only — the default fallback would just add noise.
752
+ // Normalize so `0` (unlimited) doesn't surface as a misleading "max turns: 0".
753
+ maxTurns: normalizeMaxTurns(resolvedConfig.maxTurns),
754
+ isolated,
755
+ inheritContext,
756
+ runInBackground,
757
+ isolation,
758
+ };
759
+ // Tool-result render shows the mode label too; viewer's header already does.
760
+ const modeLabel = getPromptModeLabel(subagentType);
761
+ const { tags: invocationTags } = buildInvocationTags(agentInvocation);
762
+ const agentTags = modeLabel ? [modeLabel, ...invocationTags] : invocationTags;
763
+ const detailBase = {
764
+ displayName,
765
+ description: params.description,
766
+ subagentType,
767
+ modelName,
768
+ tags: agentTags.length > 0 ? agentTags : undefined,
769
+ };
770
+ // ---- Schedule: register a job, don't spawn now ----
771
+ if (params.schedule) {
772
+ if (!isSchedulingEnabled()) {
773
+ return textResult("Scheduling is disabled in this project. Enable via /agents → Settings → Scheduling.");
774
+ }
775
+ if (params.resume) {
776
+ return textResult("Cannot combine `schedule` with `resume` — schedules create fresh agents.");
777
+ }
778
+ if (params.inherit_context) {
779
+ return textResult("Cannot combine `schedule` with `inherit_context` — there is no parent conversation at fire time.");
780
+ }
781
+ if (params.run_in_background === false) {
782
+ return textResult("Cannot combine `schedule` with `run_in_background: false` — scheduled jobs always run in background.");
783
+ }
784
+ if (!scheduler.isActive()) {
785
+ return textResult("Scheduler is not active in this session yet. Try again after the session has fully started.");
786
+ }
787
+ try {
788
+ const job = scheduler.addJob({
789
+ name: params.description,
790
+ description: params.description,
791
+ schedule: params.schedule,
792
+ subagent_type: subagentType,
793
+ prompt: params.prompt,
794
+ model: params.model,
795
+ thinking: thinking,
796
+ max_turns: effectiveMaxTurns,
797
+ isolated: isolated,
798
+ isolation: isolation,
799
+ });
800
+ const next = scheduler.getNextRun(job.id);
801
+ return textResult(`Scheduled "${job.name}" (id: ${job.id}, type: ${job.scheduleType}). ` +
802
+ `Next run: ${next ?? "(unknown)"}. ` +
803
+ `Manage via /agents → Scheduled jobs.`);
804
+ }
805
+ catch (err) {
806
+ return textResult(err instanceof Error ? err.message : String(err));
807
+ }
808
+ }
809
+ // Resume existing agent
810
+ if (params.resume) {
811
+ const existing = manager.getRecord(params.resume);
812
+ if (!existing) {
813
+ return textResult(`Agent not found: "${params.resume}". It may have been cleaned up.`);
814
+ }
815
+ if (!existing.session) {
816
+ return textResult(`Agent "${params.resume}" has no active session to resume.`);
817
+ }
818
+ const record = await manager.resume(params.resume, params.prompt, signal);
819
+ if (!record) {
820
+ return textResult(`Failed to resume agent "${params.resume}".`);
821
+ }
822
+ return textResult(record.result?.trim() || record.error?.trim() || "No output.", buildDetails(detailBase, record));
823
+ }
824
+ // Background execution
825
+ if (runInBackground) {
826
+ const { state: bgState, callbacks: bgCallbacks } = createActivityTracker(effectiveMaxTurns);
827
+ // Wrap onSessionCreated to wire output file streaming.
828
+ // The callback lazily reads record.outputFile (set right after spawn)
829
+ // rather than closing over a value that doesn't exist yet.
830
+ let id;
831
+ const origBgOnSession = bgCallbacks.onSessionCreated;
832
+ bgCallbacks.onSessionCreated = (session) => {
833
+ origBgOnSession(session);
834
+ const rec = manager.getRecord(id);
835
+ if (rec?.outputFile) {
836
+ rec.outputCleanup = streamToOutputFile(session, rec.outputFile, id, ctx.cwd);
837
+ }
838
+ };
839
+ try {
840
+ id = manager.spawn(pi, ctx, subagentType, params.prompt, {
841
+ description: params.description,
842
+ model,
843
+ maxTurns: effectiveMaxTurns,
844
+ isolated,
845
+ inheritContext,
846
+ thinkingLevel: thinking,
847
+ isBackground: true,
848
+ isolation,
849
+ invocation: agentInvocation,
850
+ ...bgCallbacks,
851
+ });
852
+ }
853
+ catch (err) {
854
+ return textResult(err instanceof Error ? err.message : String(err));
855
+ }
856
+ // Set output file + join mode synchronously after spawn, before the
857
+ // event loop yields — onSessionCreated is async so this is safe.
858
+ const joinMode = resolveJoinMode(defaultJoinMode, true);
859
+ const record = manager.getRecord(id);
860
+ if (record && joinMode) {
861
+ record.joinMode = joinMode;
862
+ record.toolCallId = toolCallId;
863
+ record.outputFile = createOutputFilePath(ctx.cwd, id, ctx.sessionManager.getSessionId());
864
+ writeInitialEntry(record.outputFile, id, params.prompt, ctx.cwd);
865
+ }
866
+ if (joinMode == null || joinMode === 'async') {
867
+ // Foreground/no join mode or explicit async — not part of any batch
868
+ }
869
+ else {
870
+ // smart or group — add to current batch
871
+ currentBatchAgents.push({ id, joinMode });
872
+ // Debounce: reset timer on each new agent so parallel tool calls
873
+ // dispatched across multiple event loop ticks are captured together
874
+ if (batchFinalizeTimer)
875
+ clearTimeout(batchFinalizeTimer);
876
+ batchFinalizeTimer = setTimeout(finalizeBatch, 100);
877
+ }
878
+ agentActivity.set(id, bgState);
879
+ widget.ensureTimer();
880
+ widget.update();
881
+ // Emit created event
882
+ pi.events.emit("subagents:created", {
883
+ id,
884
+ type: subagentType,
885
+ description: params.description,
886
+ isBackground: true,
887
+ });
888
+ const isQueued = record?.status === "queued";
889
+ return textResult(`Agent ${isQueued ? "queued" : "started"} in background.\n` +
890
+ `Agent ID: ${id}\n` +
891
+ `Type: ${displayName}\n` +
892
+ `Description: ${params.description}\n` +
893
+ (record?.outputFile ? `Output file: ${record.outputFile}\n` : "") +
894
+ (isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
895
+ `\nYou will be notified when this agent completes.\n` +
896
+ `Use get_subagent_result to retrieve full results, or steer_subagent to send it messages.\n` +
897
+ `Do not duplicate this agent's work.`, { ...detailBase, toolUses: 0, tokens: "", durationMs: 0, status: "background", agentId: id });
898
+ }
899
+ // Foreground (synchronous) execution — stream progress via onUpdate
900
+ let spinnerFrame = 0;
901
+ const startedAt = Date.now();
902
+ let fgId;
903
+ const streamUpdate = () => {
904
+ const details = {
905
+ ...detailBase,
906
+ toolUses: fgState.toolUses,
907
+ tokens: formatLifetimeTokens(fgState),
908
+ turnCount: fgState.turnCount,
909
+ maxTurns: fgState.maxTurns,
910
+ durationMs: Date.now() - startedAt,
911
+ status: "running",
912
+ activity: describeActivity(fgState.activeTools, fgState.responseText),
913
+ spinnerFrame: spinnerFrame % SPINNER.length,
914
+ };
915
+ onUpdate?.({
916
+ content: [{ type: "text", text: `${fgState.toolUses} tool uses...` }],
917
+ details: details,
918
+ });
919
+ };
920
+ const { state: fgState, callbacks: fgCallbacks } = createActivityTracker(effectiveMaxTurns, streamUpdate);
921
+ // Wire session creation to register in widget
922
+ const origOnSession = fgCallbacks.onSessionCreated;
923
+ fgCallbacks.onSessionCreated = (session) => {
924
+ origOnSession(session);
925
+ for (const a of manager.listAgents()) {
926
+ if (a.session === session) {
927
+ fgId = a.id;
928
+ agentActivity.set(a.id, fgState);
929
+ widget.ensureTimer();
930
+ break;
931
+ }
932
+ }
933
+ };
934
+ // Animate spinner at ~80ms (smooth rotation through 10 braille frames)
935
+ const spinnerInterval = setInterval(() => {
936
+ spinnerFrame++;
937
+ streamUpdate();
938
+ }, 80);
939
+ streamUpdate();
940
+ let record;
941
+ try {
942
+ record = await manager.spawnAndWait(pi, ctx, subagentType, params.prompt, {
943
+ description: params.description,
944
+ model,
945
+ maxTurns: effectiveMaxTurns,
946
+ isolated,
947
+ inheritContext,
948
+ thinkingLevel: thinking,
949
+ isolation,
950
+ invocation: agentInvocation,
951
+ signal,
952
+ ...fgCallbacks,
953
+ });
954
+ }
955
+ catch (err) {
956
+ clearInterval(spinnerInterval);
957
+ return textResult(err instanceof Error ? err.message : String(err));
958
+ }
959
+ clearInterval(spinnerInterval);
960
+ // Clean up foreground agent from widget
961
+ if (fgId) {
962
+ agentActivity.delete(fgId);
963
+ widget.markFinished(fgId);
964
+ }
965
+ // Get final token count
966
+ const tokenText = formatLifetimeTokens(fgState);
967
+ const details = buildDetails(detailBase, record, fgState, { tokens: tokenText });
968
+ const fallbackNote = fellBack
969
+ ? `Note: Unknown agent type "${rawType}" — using general-purpose.\n\n`
970
+ : "";
971
+ if (record.status === "error") {
972
+ return textResult(`${fallbackNote}Agent failed: ${record.error}`, details);
973
+ }
974
+ const durationMs = (record.completedAt ?? Date.now()) - record.startedAt;
975
+ const statsParts = [`${record.toolUses} tool uses`];
976
+ if (tokenText)
977
+ statsParts.push(tokenText);
978
+ return textResult(`${fallbackNote}Agent completed in ${formatMs(durationMs)} (${statsParts.join(", ")})${getStatusNote(record.status)}.\n\n` +
979
+ (record.result?.trim() || "No output."), details);
980
+ },
981
+ }));
982
+ // ---- get_subagent_result tool ----
983
+ pi.registerTool(defineTool({
984
+ name: "get_subagent_result",
985
+ label: "Get Agent Result",
986
+ description: "Check status and retrieve results from a background agent. Use the agent ID returned by Agent with run_in_background.",
987
+ parameters: Type.Object({
988
+ agent_id: Type.String({
989
+ description: "The agent ID to check.",
990
+ }),
991
+ wait: Type.Optional(Type.Boolean({
992
+ description: "If true, wait for the agent to complete before returning. Default: false.",
993
+ })),
994
+ verbose: Type.Optional(Type.Boolean({
995
+ description: "If true, include the agent's full conversation (messages + tool calls). Default: false.",
996
+ })),
997
+ }),
998
+ execute: async (_toolCallId, params, _signal, _onUpdate, _ctx) => {
999
+ const record = manager.getRecord(params.agent_id);
1000
+ if (!record) {
1001
+ return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
1002
+ }
1003
+ // Wait for completion if requested.
1004
+ // Pre-mark resultConsumed BEFORE awaiting: onComplete fires inside .then()
1005
+ // (attached earlier at spawn time) and always runs before this await resumes.
1006
+ // Setting the flag here prevents a redundant follow-up notification.
1007
+ if (params.wait && record.status === "running" && record.promise) {
1008
+ record.resultConsumed = true;
1009
+ cancelNudge(params.agent_id);
1010
+ await record.promise;
1011
+ }
1012
+ const displayName = getDisplayName(record.type);
1013
+ const duration = formatDuration(record.startedAt, record.completedAt);
1014
+ const tokens = formatLifetimeTokens(record);
1015
+ const contextPercent = getSessionContextPercent(record.session);
1016
+ const statsParts = [`Tool uses: ${record.toolUses}`];
1017
+ if (tokens)
1018
+ statsParts.push(tokens);
1019
+ if (contextPercent !== null)
1020
+ statsParts.push(`Context: ${Math.round(contextPercent)}%`);
1021
+ if (record.compactionCount)
1022
+ statsParts.push(`Compactions: ${record.compactionCount}`);
1023
+ statsParts.push(`Duration: ${duration}`);
1024
+ let output = `Agent: ${record.id}\n` +
1025
+ `Type: ${displayName} | Status: ${record.status} | ${statsParts.join(" | ")}\n` +
1026
+ `Description: ${record.description}\n\n`;
1027
+ if (record.status === "running") {
1028
+ output += "Agent is still running. Use wait: true or check back later.";
1029
+ }
1030
+ else if (record.status === "error") {
1031
+ output += `Error: ${record.error}`;
1032
+ }
1033
+ else {
1034
+ output += record.result?.trim() || "No output.";
1035
+ }
1036
+ // Mark result as consumed — suppresses the completion notification
1037
+ if (record.status !== "running" && record.status !== "queued") {
1038
+ record.resultConsumed = true;
1039
+ cancelNudge(params.agent_id);
1040
+ }
1041
+ // Verbose: include full conversation
1042
+ if (params.verbose && record.session) {
1043
+ const conversation = getAgentConversation(record.session);
1044
+ if (conversation) {
1045
+ output += `\n\n--- Agent Conversation ---\n${conversation}`;
1046
+ }
1047
+ }
1048
+ return textResult(output);
1049
+ },
1050
+ }));
1051
+ // ---- steer_subagent tool ----
1052
+ pi.registerTool(defineTool({
1053
+ name: "steer_subagent",
1054
+ label: "Steer Agent",
1055
+ description: "Send a steering message to a running agent. The message will interrupt the agent after its current tool execution " +
1056
+ "and be injected into its conversation, allowing you to redirect its work mid-run. Only works on running agents.",
1057
+ parameters: Type.Object({
1058
+ agent_id: Type.String({
1059
+ description: "The agent ID to steer (must be currently running).",
1060
+ }),
1061
+ message: Type.String({
1062
+ description: "The steering message to send. This will appear as a user message in the agent's conversation.",
1063
+ }),
1064
+ }),
1065
+ execute: async (_toolCallId, params, _signal, _onUpdate, _ctx) => {
1066
+ const record = manager.getRecord(params.agent_id);
1067
+ if (!record) {
1068
+ return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
1069
+ }
1070
+ if (record.status !== "running") {
1071
+ return textResult(`Agent "${params.agent_id}" is not running (status: ${record.status}). Cannot steer a non-running agent.`);
1072
+ }
1073
+ if (!record.session) {
1074
+ // Session not ready yet — queue the steer for delivery once initialized
1075
+ if (!record.pendingSteers)
1076
+ record.pendingSteers = [];
1077
+ record.pendingSteers.push(params.message);
1078
+ pi.events.emit("subagents:steered", { id: record.id, message: params.message });
1079
+ return textResult(`Steering message queued for agent ${record.id}. It will be delivered once the session initializes.`);
1080
+ }
1081
+ try {
1082
+ await steerAgent(record.session, params.message);
1083
+ pi.events.emit("subagents:steered", { id: record.id, message: params.message });
1084
+ const tokens = formatLifetimeTokens(record);
1085
+ const contextPercent = getSessionContextPercent(record.session);
1086
+ const stateParts = [];
1087
+ if (tokens)
1088
+ stateParts.push(tokens);
1089
+ stateParts.push(`${record.toolUses} tool ${record.toolUses === 1 ? "use" : "uses"}`);
1090
+ if (contextPercent !== null)
1091
+ stateParts.push(`context ${Math.round(contextPercent)}% full`);
1092
+ if (record.compactionCount)
1093
+ stateParts.push(`${record.compactionCount} compaction${record.compactionCount === 1 ? "" : "s"}`);
1094
+ return textResult(`Steering message sent to agent ${record.id}. The agent will process it after its current tool execution.\n` +
1095
+ `Current state: ${stateParts.join(" · ")}`);
1096
+ }
1097
+ catch (err) {
1098
+ return textResult(`Failed to steer agent: ${err instanceof Error ? err.message : String(err)}`);
1099
+ }
1100
+ },
1101
+ }));
1102
+ // ---- /agents interactive menu ----
1103
+ const projectAgentsDir = () => join(process.cwd(), ".pi", "agents");
1104
+ const personalAgentsDir = () => join(getAgentDir(), "agents");
1105
+ /** Find the file path of a custom agent by name (project first, then global). */
1106
+ function findAgentFile(name) {
1107
+ const projectPath = join(projectAgentsDir(), `${name}.md`);
1108
+ if (existsSync(projectPath))
1109
+ return { path: projectPath, location: "project" };
1110
+ const personalPath = join(personalAgentsDir(), `${name}.md`);
1111
+ if (existsSync(personalPath))
1112
+ return { path: personalPath, location: "personal" };
1113
+ return undefined;
1114
+ }
1115
+ function getModelLabel(type, registry) {
1116
+ const cfg = getAgentConfig(type);
1117
+ if (!cfg?.model)
1118
+ return "inherit";
1119
+ // If registry provided, check if the model actually resolves
1120
+ if (registry) {
1121
+ const resolved = resolveModel(cfg.model, registry);
1122
+ if (typeof resolved === "string")
1123
+ return "inherit"; // model not available
1124
+ }
1125
+ return getModelLabelFromConfig(cfg.model);
1126
+ }
1127
+ async function showAgentsMenu(ctx) {
1128
+ reloadCustomAgents();
1129
+ const allNames = getAllTypes();
1130
+ // Build select options
1131
+ const options = [];
1132
+ // Running agents entry (only if there are active agents)
1133
+ const agents = manager.listAgents();
1134
+ if (agents.length > 0) {
1135
+ const running = agents.filter(a => a.status === "running" || a.status === "queued").length;
1136
+ const done = agents.filter(a => a.status === "completed" || a.status === "steered").length;
1137
+ options.push(`Running agents (${agents.length}) — ${running} running, ${done} done`);
1138
+ }
1139
+ // Agent types list
1140
+ if (allNames.length > 0) {
1141
+ options.push(`Agent types (${allNames.length})`);
1142
+ }
1143
+ // Scheduled jobs entry (always present when scheduler is active)
1144
+ if (scheduler.isActive()) {
1145
+ const jobCount = scheduler.list().length;
1146
+ options.push(`Scheduled jobs (${jobCount})`);
1147
+ }
1148
+ // Actions
1149
+ options.push("Create new agent");
1150
+ options.push("Settings");
1151
+ const noAgentsMsg = allNames.length === 0 && agents.length === 0
1152
+ ? "No agents found. Create specialized subagents that can be delegated to.\n\n" +
1153
+ "Each subagent has its own context window, custom system prompt, and specific tools.\n\n" +
1154
+ "Try creating: Code Reviewer, Security Auditor, Test Writer, or Documentation Writer.\n\n"
1155
+ : "";
1156
+ if (noAgentsMsg) {
1157
+ ctx.ui.notify(noAgentsMsg, "info");
1158
+ }
1159
+ const choice = await ctx.ui.select("Agents", options);
1160
+ if (!choice)
1161
+ return;
1162
+ if (choice.startsWith("Running agents (")) {
1163
+ await showRunningAgents(ctx);
1164
+ await showAgentsMenu(ctx);
1165
+ }
1166
+ else if (choice.startsWith("Agent types (")) {
1167
+ await showAllAgentsList(ctx);
1168
+ await showAgentsMenu(ctx);
1169
+ }
1170
+ else if (choice.startsWith("Scheduled jobs (")) {
1171
+ await showSchedulesMenu(ctx, scheduler);
1172
+ await showAgentsMenu(ctx);
1173
+ }
1174
+ else if (choice === "Create new agent") {
1175
+ await showCreateWizard(ctx);
1176
+ }
1177
+ else if (choice === "Settings") {
1178
+ await showSettings(ctx);
1179
+ await showAgentsMenu(ctx);
1180
+ }
1181
+ }
1182
+ async function showAllAgentsList(ctx) {
1183
+ const allNames = getAllTypes();
1184
+ if (allNames.length === 0) {
1185
+ ctx.ui.notify("No agents.", "info");
1186
+ return;
1187
+ }
1188
+ // Source indicators: defaults unmarked, custom agents get • (project) or ◦ (global)
1189
+ // Disabled agents get ✕ prefix
1190
+ const sourceIndicator = (cfg) => {
1191
+ const disabled = cfg?.enabled === false;
1192
+ if (cfg?.source === "project")
1193
+ return disabled ? "✕• " : "• ";
1194
+ if (cfg?.source === "global")
1195
+ return disabled ? "✕◦ " : "◦ ";
1196
+ if (disabled)
1197
+ return "✕ ";
1198
+ return " ";
1199
+ };
1200
+ const entries = allNames.map(name => {
1201
+ const cfg = getAgentConfig(name);
1202
+ const disabled = cfg?.enabled === false;
1203
+ const model = getModelLabel(name, ctx.modelRegistry);
1204
+ const indicator = sourceIndicator(cfg);
1205
+ const prefix = `${indicator}${name} · ${model}`;
1206
+ const desc = disabled ? "(disabled)" : (cfg?.description ?? name);
1207
+ return { name, prefix, desc };
1208
+ });
1209
+ const maxPrefix = Math.max(...entries.map(e => e.prefix.length));
1210
+ const hasCustom = allNames.some(n => { const c = getAgentConfig(n); return c && !c.isDefault && c.enabled !== false; });
1211
+ const hasDisabled = allNames.some(n => getAgentConfig(n)?.enabled === false);
1212
+ const legendParts = [];
1213
+ if (hasCustom)
1214
+ legendParts.push("• = project ◦ = global");
1215
+ if (hasDisabled)
1216
+ legendParts.push("✕ = disabled");
1217
+ const legend = legendParts.length ? "\n" + legendParts.join(" ") : "";
1218
+ const options = entries.map(({ prefix, desc }) => `${prefix.padEnd(maxPrefix)} — ${desc}`);
1219
+ if (legend)
1220
+ options.push(legend);
1221
+ const choice = await ctx.ui.select("Agent types", options);
1222
+ if (!choice)
1223
+ return;
1224
+ const agentName = choice.split(" · ")[0].replace(/^[•◦✕\s]+/, "").trim();
1225
+ if (getAgentConfig(agentName)) {
1226
+ await showAgentDetail(ctx, agentName);
1227
+ await showAllAgentsList(ctx);
1228
+ }
1229
+ }
1230
+ async function showRunningAgents(ctx) {
1231
+ const agents = manager.listAgents();
1232
+ if (agents.length === 0) {
1233
+ ctx.ui.notify("No agents.", "info");
1234
+ return;
1235
+ }
1236
+ const options = agents.map(a => {
1237
+ const dn = getDisplayName(a.type);
1238
+ const dur = formatDuration(a.startedAt, a.completedAt);
1239
+ return `${dn} (${a.description}) · ${a.toolUses} tools · ${a.status} · ${dur}`;
1240
+ });
1241
+ const choice = await ctx.ui.select("Running agents", options);
1242
+ if (!choice)
1243
+ return;
1244
+ // Find the selected agent by matching the option index
1245
+ const idx = options.indexOf(choice);
1246
+ if (idx < 0)
1247
+ return;
1248
+ const record = agents[idx];
1249
+ await viewAgentConversation(ctx, record);
1250
+ // Back-navigation: re-show the list
1251
+ await showRunningAgents(ctx);
1252
+ }
1253
+ async function viewAgentConversation(ctx, record) {
1254
+ if (!record.session) {
1255
+ ctx.ui.notify(`Agent is ${record.status === "queued" ? "queued" : "expired"} — no session available.`, "info");
1256
+ return;
1257
+ }
1258
+ const { ConversationViewer, VIEWPORT_HEIGHT_PCT } = await import("./ui/conversation-viewer.js");
1259
+ const session = record.session;
1260
+ const activity = agentActivity.get(record.id);
1261
+ await ctx.ui.custom((tui, theme, _keybindings, done) => {
1262
+ return new ConversationViewer(tui, session, record, activity, theme, done);
1263
+ }, {
1264
+ overlay: true,
1265
+ overlayOptions: { anchor: "center", width: "90%", maxHeight: `${VIEWPORT_HEIGHT_PCT}%` },
1266
+ });
1267
+ }
1268
+ async function showAgentDetail(ctx, name) {
1269
+ const cfg = getAgentConfig(name);
1270
+ if (!cfg) {
1271
+ ctx.ui.notify(`Agent config not found for "${name}".`, "warning");
1272
+ return;
1273
+ }
1274
+ const file = findAgentFile(name);
1275
+ const isDefault = cfg.isDefault === true;
1276
+ const disabled = cfg.enabled === false;
1277
+ let menuOptions;
1278
+ if (disabled && file) {
1279
+ // Disabled agent with a file — offer Enable
1280
+ menuOptions = isDefault
1281
+ ? ["Enable", "Edit", "Reset to default", "Delete", "Back"]
1282
+ : ["Enable", "Edit", "Delete", "Back"];
1283
+ }
1284
+ else if (isDefault && !file) {
1285
+ // Default agent with no .md override
1286
+ menuOptions = ["Eject (export as .md)", "Disable", "Back"];
1287
+ }
1288
+ else if (isDefault && file) {
1289
+ // Default agent with .md override (ejected)
1290
+ menuOptions = ["Edit", "Disable", "Reset to default", "Delete", "Back"];
1291
+ }
1292
+ else {
1293
+ // User-defined agent
1294
+ menuOptions = ["Edit", "Disable", "Delete", "Back"];
1295
+ }
1296
+ const choice = await ctx.ui.select(name, menuOptions);
1297
+ if (!choice || choice === "Back")
1298
+ return;
1299
+ if (choice === "Edit" && file) {
1300
+ const content = readFileSync(file.path, "utf-8");
1301
+ const edited = await ctx.ui.editor(`Edit ${name}`, content);
1302
+ if (edited !== undefined && edited !== content) {
1303
+ const { writeFileSync } = await import("node:fs");
1304
+ writeFileSync(file.path, edited, "utf-8");
1305
+ reloadCustomAgents();
1306
+ ctx.ui.notify(`Updated ${file.path}`, "info");
1307
+ }
1308
+ }
1309
+ else if (choice === "Delete") {
1310
+ if (file) {
1311
+ const confirmed = await ctx.ui.confirm("Delete agent", `Delete ${name} from ${file.location} (${file.path})?`);
1312
+ if (confirmed) {
1313
+ unlinkSync(file.path);
1314
+ reloadCustomAgents();
1315
+ ctx.ui.notify(`Deleted ${file.path}`, "info");
1316
+ }
1317
+ }
1318
+ }
1319
+ else if (choice === "Reset to default" && file) {
1320
+ const confirmed = await ctx.ui.confirm("Reset to default", `Delete override ${file.path} and restore embedded default?`);
1321
+ if (confirmed) {
1322
+ unlinkSync(file.path);
1323
+ reloadCustomAgents();
1324
+ ctx.ui.notify(`Restored default ${name}`, "info");
1325
+ }
1326
+ }
1327
+ else if (choice.startsWith("Eject")) {
1328
+ await ejectAgent(ctx, name, cfg);
1329
+ }
1330
+ else if (choice === "Disable") {
1331
+ await disableAgent(ctx, name);
1332
+ }
1333
+ else if (choice === "Enable") {
1334
+ await enableAgent(ctx, name);
1335
+ }
1336
+ }
1337
+ /** Eject a default agent: write its embedded config as a .md file. */
1338
+ async function ejectAgent(ctx, name, cfg) {
1339
+ const location = await ctx.ui.select("Choose location", [
1340
+ "Project (.pi/agents/)",
1341
+ `Personal (${personalAgentsDir()})`,
1342
+ ]);
1343
+ if (!location)
1344
+ return;
1345
+ const targetDir = location.startsWith("Project") ? projectAgentsDir() : personalAgentsDir();
1346
+ mkdirSync(targetDir, { recursive: true });
1347
+ const targetPath = join(targetDir, `${name}.md`);
1348
+ if (existsSync(targetPath)) {
1349
+ const overwrite = await ctx.ui.confirm("Overwrite", `${targetPath} already exists. Overwrite?`);
1350
+ if (!overwrite)
1351
+ return;
1352
+ }
1353
+ // Build the .md file content
1354
+ const fmFields = [];
1355
+ fmFields.push(`description: ${cfg.description}`);
1356
+ if (cfg.displayName)
1357
+ fmFields.push(`display_name: ${cfg.displayName}`);
1358
+ fmFields.push(`tools: ${cfg.builtinToolNames?.join(", ") || "all"}`);
1359
+ if (cfg.model)
1360
+ fmFields.push(`model: ${cfg.model}`);
1361
+ if (cfg.thinking)
1362
+ fmFields.push(`thinking: ${cfg.thinking}`);
1363
+ if (cfg.maxTurns)
1364
+ fmFields.push(`max_turns: ${cfg.maxTurns}`);
1365
+ fmFields.push(`prompt_mode: ${cfg.promptMode}`);
1366
+ if (cfg.extensions === false)
1367
+ fmFields.push("extensions: false");
1368
+ else if (Array.isArray(cfg.extensions))
1369
+ fmFields.push(`extensions: ${cfg.extensions.join(", ")}`);
1370
+ if (cfg.skills === false)
1371
+ fmFields.push("skills: false");
1372
+ else if (Array.isArray(cfg.skills))
1373
+ fmFields.push(`skills: ${cfg.skills.join(", ")}`);
1374
+ if (cfg.disallowedTools?.length)
1375
+ fmFields.push(`disallowed_tools: ${cfg.disallowedTools.join(", ")}`);
1376
+ if (cfg.inheritContext)
1377
+ fmFields.push("inherit_context: true");
1378
+ if (cfg.runInBackground)
1379
+ fmFields.push("run_in_background: true");
1380
+ if (cfg.isolated)
1381
+ fmFields.push("isolated: true");
1382
+ if (cfg.memory)
1383
+ fmFields.push(`memory: ${cfg.memory}`);
1384
+ if (cfg.isolation)
1385
+ fmFields.push(`isolation: ${cfg.isolation}`);
1386
+ const content = `---\n${fmFields.join("\n")}\n---\n\n${cfg.systemPrompt}\n`;
1387
+ const { writeFileSync } = await import("node:fs");
1388
+ writeFileSync(targetPath, content, "utf-8");
1389
+ reloadCustomAgents();
1390
+ ctx.ui.notify(`Ejected ${name} to ${targetPath}`, "info");
1391
+ }
1392
+ /** Disable an agent: set enabled: false in its .md file, or create a stub for built-in defaults. */
1393
+ async function disableAgent(ctx, name) {
1394
+ const file = findAgentFile(name);
1395
+ if (file) {
1396
+ // Existing file — set enabled: false in frontmatter (idempotent)
1397
+ const content = readFileSync(file.path, "utf-8");
1398
+ if (content.includes("\nenabled: false\n")) {
1399
+ ctx.ui.notify(`${name} is already disabled.`, "info");
1400
+ return;
1401
+ }
1402
+ const updated = content.replace(/^---\n/, "---\nenabled: false\n");
1403
+ const { writeFileSync } = await import("node:fs");
1404
+ writeFileSync(file.path, updated, "utf-8");
1405
+ reloadCustomAgents();
1406
+ ctx.ui.notify(`Disabled ${name} (${file.path})`, "info");
1407
+ return;
1408
+ }
1409
+ // No file (built-in default) — create a stub
1410
+ const location = await ctx.ui.select("Choose location", [
1411
+ "Project (.pi/agents/)",
1412
+ `Personal (${personalAgentsDir()})`,
1413
+ ]);
1414
+ if (!location)
1415
+ return;
1416
+ const targetDir = location.startsWith("Project") ? projectAgentsDir() : personalAgentsDir();
1417
+ mkdirSync(targetDir, { recursive: true });
1418
+ const targetPath = join(targetDir, `${name}.md`);
1419
+ const { writeFileSync } = await import("node:fs");
1420
+ writeFileSync(targetPath, "---\nenabled: false\n---\n", "utf-8");
1421
+ reloadCustomAgents();
1422
+ ctx.ui.notify(`Disabled ${name} (${targetPath})`, "info");
1423
+ }
1424
+ /** Enable a disabled agent by removing enabled: false from its frontmatter. */
1425
+ async function enableAgent(ctx, name) {
1426
+ const file = findAgentFile(name);
1427
+ if (!file)
1428
+ return;
1429
+ const content = readFileSync(file.path, "utf-8");
1430
+ const updated = content.replace(/^(---\n)enabled: false\n/, "$1");
1431
+ const { writeFileSync } = await import("node:fs");
1432
+ // If the file was just a stub ("---\n---\n"), delete it to restore the built-in default
1433
+ if (updated.trim() === "---\n---" || updated.trim() === "---\n---\n") {
1434
+ unlinkSync(file.path);
1435
+ reloadCustomAgents();
1436
+ ctx.ui.notify(`Enabled ${name} (removed ${file.path})`, "info");
1437
+ }
1438
+ else {
1439
+ writeFileSync(file.path, updated, "utf-8");
1440
+ reloadCustomAgents();
1441
+ ctx.ui.notify(`Enabled ${name} (${file.path})`, "info");
1442
+ }
1443
+ }
1444
+ async function showCreateWizard(ctx) {
1445
+ const location = await ctx.ui.select("Choose location", [
1446
+ "Project (.pi/agents/)",
1447
+ `Personal (${personalAgentsDir()})`,
1448
+ ]);
1449
+ if (!location)
1450
+ return;
1451
+ const targetDir = location.startsWith("Project") ? projectAgentsDir() : personalAgentsDir();
1452
+ const method = await ctx.ui.select("Creation method", [
1453
+ "Generate with Claude (recommended)",
1454
+ "Manual configuration",
1455
+ ]);
1456
+ if (!method)
1457
+ return;
1458
+ if (method.startsWith("Generate")) {
1459
+ await showGenerateWizard(ctx, targetDir);
1460
+ }
1461
+ else {
1462
+ await showManualWizard(ctx, targetDir);
1463
+ }
1464
+ }
1465
+ async function showGenerateWizard(ctx, targetDir) {
1466
+ const description = await ctx.ui.input("Describe what this agent should do");
1467
+ if (!description)
1468
+ return;
1469
+ const name = await ctx.ui.input("Agent name (filename, no spaces)");
1470
+ if (!name)
1471
+ return;
1472
+ mkdirSync(targetDir, { recursive: true });
1473
+ const targetPath = join(targetDir, `${name}.md`);
1474
+ if (existsSync(targetPath)) {
1475
+ const overwrite = await ctx.ui.confirm("Overwrite", `${targetPath} already exists. Overwrite?`);
1476
+ if (!overwrite)
1477
+ return;
1478
+ }
1479
+ ctx.ui.notify("Generating agent definition...", "info");
1480
+ const generatePrompt = `Create a custom pi sub-agent definition file based on this description: "${description}"
1481
+
1482
+ Write a markdown file to: ${targetPath}
1483
+
1484
+ The file format is a markdown file with YAML frontmatter and a system prompt body:
1485
+
1486
+ \`\`\`markdown
1487
+ ---
1488
+ description: <one-line description shown in UI>
1489
+ tools: <comma-separated built-in tools: read, bash, edit, write, grep, find, ls. Use "none" for no tools. Omit for all tools>
1490
+ model: <optional model as "provider/modelId", e.g. "anthropic/claude-haiku-4-5-20251001". Omit to inherit parent model>
1491
+ thinking: <optional thinking level: off, minimal, low, medium, high, xhigh. Omit to inherit>
1492
+ max_turns: <optional max agentic turns. 0 or omit for unlimited (default)>
1493
+ prompt_mode: <"replace" (body IS the full system prompt) or "append" (body is appended to default prompt). Default: replace>
1494
+ extensions: <true (inherit all MCP/extension tools), false (none), or comma-separated names. Default: true>
1495
+ skills: <true (inherit all), false (none), or comma-separated skill names to preload into prompt. Default: true>
1496
+ disallowed_tools: <comma-separated tool names to block, even if otherwise available. Omit for none>
1497
+ inherit_context: <true to fork parent conversation into agent so it sees chat history. Default: false>
1498
+ run_in_background: <true to run in background by default. Default: false>
1499
+ isolated: <true for no extension/MCP tools, only built-in tools. Default: false>
1500
+ memory: <"user" (global), "project" (per-project), or "local" (gitignored per-project) for persistent memory. Omit for none>
1501
+ isolation: <"worktree" to run in isolated git worktree. Omit for normal>
1502
+ ---
1503
+
1504
+ <system prompt body — instructions for the agent>
1505
+ \`\`\`
1506
+
1507
+ Guidelines for choosing settings:
1508
+ - For read-only tasks (review, analysis): tools: read, bash, grep, find, ls
1509
+ - For code modification tasks: include edit, write
1510
+ - Use prompt_mode: append if the agent should keep the default system prompt and add specialization on top
1511
+ - Use prompt_mode: replace for fully custom agents with their own personality/instructions
1512
+ - Set inherit_context: true if the agent needs to know what was discussed in the parent conversation
1513
+ - Set isolated: true if the agent should NOT have access to MCP servers or other extensions
1514
+ - Only include frontmatter fields that differ from defaults — omit fields where the default is fine
1515
+
1516
+ Write the file using the write tool. Only write the file, nothing else.`;
1517
+ const record = await manager.spawnAndWait(pi, ctx, "general-purpose", generatePrompt, {
1518
+ description: `Generate ${name} agent`,
1519
+ maxTurns: 5,
1520
+ });
1521
+ if (record.status === "error") {
1522
+ ctx.ui.notify(`Generation failed: ${record.error}`, "warning");
1523
+ return;
1524
+ }
1525
+ reloadCustomAgents();
1526
+ if (existsSync(targetPath)) {
1527
+ ctx.ui.notify(`Created ${targetPath}`, "info");
1528
+ }
1529
+ else {
1530
+ ctx.ui.notify("Agent generation completed but file was not created. Check the agent output.", "warning");
1531
+ }
1532
+ }
1533
+ async function showManualWizard(ctx, targetDir) {
1534
+ // 1. Name
1535
+ const name = await ctx.ui.input("Agent name (filename, no spaces)");
1536
+ if (!name)
1537
+ return;
1538
+ // 2. Description
1539
+ const description = await ctx.ui.input("Description (one line)");
1540
+ if (!description)
1541
+ return;
1542
+ // 3. Tools
1543
+ const toolChoice = await ctx.ui.select("Tools", ["all", "none", "read-only (read, bash, grep, find, ls)", "custom..."]);
1544
+ if (!toolChoice)
1545
+ return;
1546
+ let tools;
1547
+ if (toolChoice === "all") {
1548
+ tools = BUILTIN_TOOL_NAMES.join(", ");
1549
+ }
1550
+ else if (toolChoice === "none") {
1551
+ tools = "none";
1552
+ }
1553
+ else if (toolChoice.startsWith("read-only")) {
1554
+ tools = "read, bash, grep, find, ls";
1555
+ }
1556
+ else {
1557
+ const customTools = await ctx.ui.input("Tools (comma-separated)", BUILTIN_TOOL_NAMES.join(", "));
1558
+ if (!customTools)
1559
+ return;
1560
+ tools = customTools;
1561
+ }
1562
+ // 4. Model
1563
+ const modelChoice = await ctx.ui.select("Model", [
1564
+ "inherit (parent model)",
1565
+ "haiku",
1566
+ "sonnet",
1567
+ "opus",
1568
+ "custom...",
1569
+ ]);
1570
+ if (!modelChoice)
1571
+ return;
1572
+ let modelLine = "";
1573
+ if (modelChoice === "haiku")
1574
+ modelLine = "\nmodel: anthropic/claude-haiku-4-5-20251001";
1575
+ else if (modelChoice === "sonnet")
1576
+ modelLine = "\nmodel: anthropic/claude-sonnet-4-6";
1577
+ else if (modelChoice === "opus")
1578
+ modelLine = "\nmodel: anthropic/claude-opus-4-6";
1579
+ else if (modelChoice === "custom...") {
1580
+ const customModel = await ctx.ui.input("Model (provider/modelId)");
1581
+ if (customModel)
1582
+ modelLine = `\nmodel: ${customModel}`;
1583
+ }
1584
+ // 5. Thinking
1585
+ const thinkingChoice = await ctx.ui.select("Thinking level", [
1586
+ "inherit",
1587
+ "off",
1588
+ "minimal",
1589
+ "low",
1590
+ "medium",
1591
+ "high",
1592
+ "xhigh",
1593
+ ]);
1594
+ if (!thinkingChoice)
1595
+ return;
1596
+ let thinkingLine = "";
1597
+ if (thinkingChoice !== "inherit")
1598
+ thinkingLine = `\nthinking: ${thinkingChoice}`;
1599
+ // 6. System prompt
1600
+ const systemPrompt = await ctx.ui.editor("System prompt", "");
1601
+ if (systemPrompt === undefined)
1602
+ return;
1603
+ // Build the file
1604
+ const content = `---
1605
+ description: ${description}
1606
+ tools: ${tools}${modelLine}${thinkingLine}
1607
+ prompt_mode: replace
1608
+ ---
1609
+
1610
+ ${systemPrompt}
1611
+ `;
1612
+ mkdirSync(targetDir, { recursive: true });
1613
+ const targetPath = join(targetDir, `${name}.md`);
1614
+ if (existsSync(targetPath)) {
1615
+ const overwrite = await ctx.ui.confirm("Overwrite", `${targetPath} already exists. Overwrite?`);
1616
+ if (!overwrite)
1617
+ return;
1618
+ }
1619
+ const { writeFileSync } = await import("node:fs");
1620
+ writeFileSync(targetPath, content, "utf-8");
1621
+ reloadCustomAgents();
1622
+ ctx.ui.notify(`Created ${targetPath}`, "info");
1623
+ }
1624
+ function snapshotSettings() {
1625
+ return {
1626
+ maxConcurrent: manager.getMaxConcurrent(),
1627
+ // 0 = unlimited — per SubagentsSettings.defaultMaxTurns docstring and
1628
+ // normalizeMaxTurns() in agent-runner.ts (which maps 0 → undefined).
1629
+ defaultMaxTurns: getDefaultMaxTurns() ?? 0,
1630
+ graceTurns: getGraceTurns(),
1631
+ defaultJoinMode: getDefaultJoinMode(),
1632
+ schedulingEnabled: isSchedulingEnabled(),
1633
+ };
1634
+ }
1635
+ async function showSettings(ctx) {
1636
+ const choice = await ctx.ui.select("Settings", [
1637
+ `Max concurrency (current: ${manager.getMaxConcurrent()})`,
1638
+ `Default max turns (current: ${getDefaultMaxTurns() ?? "unlimited"})`,
1639
+ `Grace turns (current: ${getGraceTurns()})`,
1640
+ `Join mode (current: ${getDefaultJoinMode()})`,
1641
+ `Scheduling (current: ${isSchedulingEnabled() ? "enabled" : "disabled"})`,
1642
+ ]);
1643
+ if (!choice)
1644
+ return;
1645
+ if (choice.startsWith("Max concurrency")) {
1646
+ const val = await ctx.ui.input("Max concurrent background agents", String(manager.getMaxConcurrent()));
1647
+ if (val) {
1648
+ const n = parseInt(val, 10);
1649
+ if (n >= 1) {
1650
+ manager.setMaxConcurrent(n);
1651
+ notifyApplied(ctx, `Max concurrency set to ${n}`);
1652
+ }
1653
+ else {
1654
+ ctx.ui.notify("Must be a positive integer.", "warning");
1655
+ }
1656
+ }
1657
+ }
1658
+ else if (choice.startsWith("Default max turns")) {
1659
+ const val = await ctx.ui.input("Default max turns before wrap-up (0 = unlimited)", String(getDefaultMaxTurns() ?? 0));
1660
+ if (val) {
1661
+ const n = parseInt(val, 10);
1662
+ if (n === 0) {
1663
+ setDefaultMaxTurns(undefined);
1664
+ notifyApplied(ctx, "Default max turns set to unlimited");
1665
+ }
1666
+ else if (n >= 1) {
1667
+ setDefaultMaxTurns(n);
1668
+ notifyApplied(ctx, `Default max turns set to ${n}`);
1669
+ }
1670
+ else {
1671
+ ctx.ui.notify("Must be 0 (unlimited) or a positive integer.", "warning");
1672
+ }
1673
+ }
1674
+ }
1675
+ else if (choice.startsWith("Grace turns")) {
1676
+ const val = await ctx.ui.input("Grace turns after wrap-up steer", String(getGraceTurns()));
1677
+ if (val) {
1678
+ const n = parseInt(val, 10);
1679
+ if (n >= 1) {
1680
+ setGraceTurns(n);
1681
+ notifyApplied(ctx, `Grace turns set to ${n}`);
1682
+ }
1683
+ else {
1684
+ ctx.ui.notify("Must be a positive integer.", "warning");
1685
+ }
1686
+ }
1687
+ }
1688
+ else if (choice.startsWith("Join mode")) {
1689
+ const val = await ctx.ui.select("Default join mode for background agents", [
1690
+ "smart — auto-group 2+ agents in same turn (default)",
1691
+ "async — always notify individually",
1692
+ "group — always group background agents",
1693
+ ]);
1694
+ if (val) {
1695
+ const mode = val.split(" ")[0];
1696
+ setDefaultJoinMode(mode);
1697
+ notifyApplied(ctx, `Default join mode set to ${mode}`);
1698
+ }
1699
+ }
1700
+ else if (choice.startsWith("Scheduling")) {
1701
+ const val = await ctx.ui.select("Schedule subagent feature", [
1702
+ "enabled — Agent tool accepts a `schedule` param; /agents → Scheduled jobs visible",
1703
+ "disabled — `schedule` removed from Agent tool spec (no LLM-context cost); menu hidden",
1704
+ ]);
1705
+ if (val) {
1706
+ const enabled = val.startsWith("enabled");
1707
+ if (enabled === isSchedulingEnabled()) {
1708
+ ctx.ui.notify(`Scheduling already ${enabled ? "enabled" : "disabled"}.`, "info");
1709
+ }
1710
+ else {
1711
+ setSchedulingEnabled(enabled);
1712
+ if (!enabled)
1713
+ scheduler.stop(); // immediate kill — outstanding fires stop ticking
1714
+ notifyApplied(ctx, `Scheduling ${enabled ? "enabled" : "disabled"}. Tool spec change takes effect on next pi session.`);
1715
+ }
1716
+ }
1717
+ }
1718
+ }
1719
+ // Persist the current snapshot, emit `subagents:settings_changed`, and surface
1720
+ // the right toast. Successful saves show info; persistence failures downgrade
1721
+ // to warning so users aren't silently reverted on restart. Event fires regardless
1722
+ // of outcome so listeners see the in-memory change.
1723
+ function notifyApplied(ctx, successMsg) {
1724
+ const { message, level } = saveAndEmitChanged(snapshotSettings(), successMsg, (event, payload) => pi.events.emit(event, payload));
1725
+ ctx.ui.notify(message, level);
1726
+ }
1727
+ pi.registerCommand("agents", {
1728
+ description: "Manage agents",
1729
+ handler: async (_args, ctx) => { await showAgentsMenu(ctx); },
1730
+ });
1731
+ }