@leing2021/super-pi 0.22.1 → 0.23.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 (110) hide show
  1. package/README.md +253 -211
  2. package/extensions/ce-core/index.ts +190 -7
  3. package/extensions/ce-core/tools/parallel-subagent.ts +3 -3
  4. package/extensions/ce-core/tools/subagent.ts +2 -2
  5. package/package.json +4 -20
  6. package/rules/common/naming.md +154 -0
  7. package/skills/02-plan/SKILL.md +3 -2
  8. package/skills/03-work/SKILL.md +9 -6
  9. package/skills/04-review/SKILL.md +3 -2
  10. package/skills/06-next/SKILL.md +38 -10
  11. package/skills/06-next/references/recommendation-logic.md +2 -2
  12. package/skills/07-worktree/SKILL.md +9 -8
  13. package/skills/{09-help → 08-help}/SKILL.md +3 -3
  14. package/skills/{09-help → 08-help}/references/workflow-sequence.md +2 -1
  15. package/skills/references/language-detection.md +44 -0
  16. package/LICENSE +0 -21
  17. package/THIRD-PARTY-NOTICES.md +0 -35
  18. package/extensions/subagent/__tests__/async-job-tracker.test.ts +0 -21
  19. package/extensions/subagent/__tests__/execution-activity.test.ts +0 -15
  20. package/extensions/subagent/__tests__/parallel-render-stress.test.ts +0 -82
  21. package/extensions/subagent/__tests__/render-dedup.test.ts +0 -98
  22. package/extensions/subagent/__tests__/render-widget.test.ts +0 -28
  23. package/extensions/subagent/__tests__/throttle.test.ts +0 -90
  24. package/extensions/subagent/agent-management.ts +0 -596
  25. package/extensions/subagent/agent-manager-chain-detail.ts +0 -163
  26. package/extensions/subagent/agent-manager-detail.ts +0 -232
  27. package/extensions/subagent/agent-manager-edit.ts +0 -391
  28. package/extensions/subagent/agent-manager-list.ts +0 -279
  29. package/extensions/subagent/agent-manager-parallel.ts +0 -305
  30. package/extensions/subagent/agent-manager.ts +0 -706
  31. package/extensions/subagent/agent-scope.ts +0 -9
  32. package/extensions/subagent/agent-selection.ts +0 -26
  33. package/extensions/subagent/agent-serializer.ts +0 -124
  34. package/extensions/subagent/agent-templates.ts +0 -63
  35. package/extensions/subagent/agents/context-builder.md +0 -37
  36. package/extensions/subagent/agents/delegate.md +0 -9
  37. package/extensions/subagent/agents/oracle.md +0 -73
  38. package/extensions/subagent/agents/planner.md +0 -52
  39. package/extensions/subagent/agents/researcher.md +0 -50
  40. package/extensions/subagent/agents/reviewer.md +0 -38
  41. package/extensions/subagent/agents/scout.md +0 -48
  42. package/extensions/subagent/agents/worker.md +0 -52
  43. package/extensions/subagent/agents.ts +0 -762
  44. package/extensions/subagent/artifacts.ts +0 -101
  45. package/extensions/subagent/async-execution.ts +0 -521
  46. package/extensions/subagent/async-job-tracker.ts +0 -240
  47. package/extensions/subagent/async-status.ts +0 -242
  48. package/extensions/subagent/chain-clarify.ts +0 -1365
  49. package/extensions/subagent/chain-execution.ts +0 -854
  50. package/extensions/subagent/chain-serializer.ts +0 -127
  51. package/extensions/subagent/completion-dedupe.ts +0 -66
  52. package/extensions/subagent/doctor.ts +0 -201
  53. package/extensions/subagent/execution.ts +0 -748
  54. package/extensions/subagent/file-coalescer.ts +0 -43
  55. package/extensions/subagent/fork-context.ts +0 -64
  56. package/extensions/subagent/formatters.ts +0 -123
  57. package/extensions/subagent/frontmatter.ts +0 -32
  58. package/extensions/subagent/index.ts +0 -586
  59. package/extensions/subagent/intercom-bridge.ts +0 -241
  60. package/extensions/subagent/jsonl-writer.ts +0 -84
  61. package/extensions/subagent/model-fallback.ts +0 -109
  62. package/extensions/subagent/notify.ts +0 -111
  63. package/extensions/subagent/parallel-utils.ts +0 -109
  64. package/extensions/subagent/pi-args.ts +0 -139
  65. package/extensions/subagent/pi-spawn.ts +0 -101
  66. package/extensions/subagent/post-exit-stdio-guard.ts +0 -88
  67. package/extensions/subagent/prompt-template-bridge.ts +0 -400
  68. package/extensions/subagent/prompts/gather-context-and-clarify.md +0 -13
  69. package/extensions/subagent/prompts/parallel-cleanup.md +0 -42
  70. package/extensions/subagent/prompts/parallel-research.md +0 -50
  71. package/extensions/subagent/prompts/parallel-review.md +0 -40
  72. package/extensions/subagent/render-helpers.ts +0 -83
  73. package/extensions/subagent/render.ts +0 -908
  74. package/extensions/subagent/result-intercom.ts +0 -238
  75. package/extensions/subagent/result-watcher.ts +0 -172
  76. package/extensions/subagent/run-history.ts +0 -58
  77. package/extensions/subagent/run-status.ts +0 -137
  78. package/extensions/subagent/schemas.ts +0 -165
  79. package/extensions/subagent/session-tokens.ts +0 -51
  80. package/extensions/subagent/settings.ts +0 -368
  81. package/extensions/subagent/single-output.ts +0 -98
  82. package/extensions/subagent/skills.ts +0 -627
  83. package/extensions/subagent/slash-bridge.ts +0 -177
  84. package/extensions/subagent/slash-commands.ts +0 -304
  85. package/extensions/subagent/slash-live-state.ts +0 -295
  86. package/extensions/subagent/subagent-control.ts +0 -151
  87. package/extensions/subagent/subagent-executor.ts +0 -1915
  88. package/extensions/subagent/subagent-prompt-runtime.ts +0 -76
  89. package/extensions/subagent/subagent-runner.ts +0 -1471
  90. package/extensions/subagent/subagents-status.ts +0 -473
  91. package/extensions/subagent/text-editor.ts +0 -273
  92. package/extensions/subagent/throttle.ts +0 -77
  93. package/extensions/subagent/top-level-async.ts +0 -16
  94. package/extensions/subagent/types.ts +0 -624
  95. package/extensions/subagent/utils.ts +0 -457
  96. package/extensions/subagent/worktree.ts +0 -580
  97. package/extensions/super-pi-extension/agents/ce-oracle.md +0 -109
  98. package/extensions/super-pi-extension/agents/ce-planner.md +0 -116
  99. package/extensions/super-pi-extension/agents/ce-reviewer.md +0 -99
  100. package/extensions/super-pi-extension/agents/ce-scout.md +0 -80
  101. package/extensions/super-pi-extension/agents/ce-worker.md +0 -78
  102. package/extensions/super-pi-extension/chains/ce-parallel-review.chain.md +0 -34
  103. package/extensions/super-pi-extension/chains/ce-review-only.chain.md +0 -12
  104. package/extensions/super-pi-extension/chains/ce-standard.chain.md +0 -28
  105. package/extensions/super-pi-extension/index.ts +0 -129
  106. package/extensions/super-pi-extension/model-sync.ts +0 -204
  107. package/skills/08-status/SKILL.md +0 -41
  108. package/skills/08-status/references/artifact-locations.md +0 -10
  109. package/skills/10-rules/SKILL.md +0 -76
  110. package/skills/pi-subagents/SKILL.md +0 -566
@@ -1,586 +0,0 @@
1
- // SPDX-FileCopyrightText: 2025 Nico Bailon
2
- // SPDX-License-Identifier: MIT
3
- // Source: https://github.com/nicobailon/pi-subagents
4
- /**
5
- * Subagent Tool
6
- *
7
- * Full-featured subagent with sync and async modes.
8
- * - Sync (default): Streams output, renders markdown, tracks usage
9
- * - Async: Background execution, emits events when done
10
- *
11
- * Modes: single (agent + task), parallel (tasks[]), chain (chain[] with {previous})
12
- * Toggle: async parameter (default: false, configurable via config.json)
13
- *
14
- * Config file: ~/.pi/agent/extensions/subagent/config.json
15
- * { "asyncByDefault": true, "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
16
- */
17
-
18
- import * as fs from "node:fs";
19
- import * as os from "node:os";
20
- import * as path from "node:path";
21
- import type { AgentToolResult } from "@mariozechner/pi-agent-core";
22
- import { type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@mariozechner/pi-coding-agent";
23
- import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@mariozechner/pi-tui";
24
- import { discoverAgents } from "./agents.ts";
25
- import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "./artifacts.ts";
26
- import { cleanupOldChainDirs } from "./settings.ts";
27
- import { renderWidget, renderSubagentResult, stopResultAnimations, stopWidgetAnimation, syncResultAnimation } from "./render.ts";
28
- import { SubagentParams } from "./schemas.ts";
29
- import { createSubagentExecutor } from "./subagent-executor.ts";
30
- import { createAsyncJobTracker } from "./async-job-tracker.ts";
31
- import { controlNotificationKey, formatControlNoticeMessage } from "./subagent-control.ts";
32
- import { createResultWatcher } from "./result-watcher.ts";
33
- import { registerSlashCommands } from "./slash-commands.ts";
34
- import { registerPromptTemplateDelegationBridge } from "./prompt-template-bridge.ts";
35
- import { registerSlashSubagentBridge } from "./slash-bridge.ts";
36
- import { clearSlashSnapshots, getSlashRenderableSnapshot, resolveSlashMessageDetails, restoreSlashFinalSnapshots, type SlashMessageDetails } from "./slash-live-state.ts";
37
- import { inspectSubagentStatus } from "./run-status.ts";
38
- import registerSubagentNotify, { type SubagentNotifyDetails } from "./notify.ts";
39
- import { formatDuration, shortenPath } from "./formatters.ts";
40
- import {
41
- type ControlEvent,
42
- type Details,
43
- type ExtensionConfig,
44
- type SubagentState,
45
- ASYNC_DIR,
46
- DEFAULT_ARTIFACT_CONFIG,
47
- RESULTS_DIR,
48
- SLASH_RESULT_TYPE,
49
- SUBAGENT_ASYNC_COMPLETE_EVENT,
50
- SUBAGENT_ASYNC_STARTED_EVENT,
51
- SUBAGENT_CONTROL_EVENT,
52
- WIDGET_KEY,
53
- } from "./types.ts";
54
-
55
- /**
56
- * Derive subagent session base directory from parent session file.
57
- * If parent session is ~/.pi/agent/sessions/abc123.jsonl,
58
- * returns ~/.pi/agent/sessions/abc123/ as the base.
59
- * Callers add runId to create the actual session root: abc123/{runId}/
60
- * Falls back to a unique temp directory if no parent session.
61
- */
62
- function getSubagentSessionRoot(parentSessionFile: string | null): string {
63
- if (parentSessionFile) {
64
- const baseName = path.basename(parentSessionFile, ".jsonl");
65
- const sessionsDir = path.dirname(parentSessionFile);
66
- return path.join(sessionsDir, baseName);
67
- }
68
- return fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-session-"));
69
- }
70
-
71
- function loadConfig(): ExtensionConfig {
72
- const configPath = path.join(os.homedir(), ".pi", "agent", "extensions", "subagent", "config.json");
73
- try {
74
- if (fs.existsSync(configPath)) {
75
- return JSON.parse(fs.readFileSync(configPath, "utf-8")) as ExtensionConfig;
76
- }
77
- } catch (error) {
78
- console.error(`Failed to load subagent config from '${configPath}':`, error);
79
- }
80
- return {};
81
- }
82
-
83
- function expandTilde(p: string): string {
84
- return p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
85
- }
86
-
87
- /**
88
- * Create a directory and verify it is actually accessible.
89
- * On Windows with Azure AD/Entra ID, directories created shortly after
90
- * wake-from-sleep can end up with broken NTFS ACLs (null DACL) when the
91
- * cloud SID cannot be resolved without network connectivity. This leaves
92
- * the directory completely inaccessible to the creating user.
93
- */
94
- function ensureAccessibleDir(dirPath: string): void {
95
- fs.mkdirSync(dirPath, { recursive: true });
96
- try {
97
- fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
98
- } catch {
99
- try {
100
- fs.rmSync(dirPath, { recursive: true, force: true });
101
- } catch {
102
- // Best effort: retry mkdir/access even if cleanup fails.
103
- }
104
- fs.mkdirSync(dirPath, { recursive: true });
105
- fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
106
- }
107
- }
108
-
109
- function isSlashResultRunning(result: { details?: Details }): boolean {
110
- return result.details?.progress?.some((entry) => entry.status === "running")
111
- || result.details?.results.some((entry) => entry.progress?.status === "running")
112
- || false;
113
- }
114
-
115
- function isSlashResultError(result: { details?: Details }): boolean {
116
- return result.details?.results.some((entry) => entry.exitCode !== 0 && entry.progress?.status !== "running") || false;
117
- }
118
-
119
- function rebuildSlashResultContainer(
120
- container: Container,
121
- result: AgentToolResult<Details>,
122
- options: { expanded: boolean },
123
- theme: ExtensionContext["ui"]["theme"],
124
- ): void {
125
- container.clear();
126
- container.addChild(new Spacer(1));
127
- const boxTheme = isSlashResultRunning(result) ? "toolPendingBg" : isSlashResultError(result) ? "toolErrorBg" : "toolSuccessBg";
128
- const box = new Box(1, 1, (text: string) => theme.bg(boxTheme, text));
129
- box.addChild(renderSubagentResult(result, options, theme));
130
- container.addChild(box);
131
- }
132
-
133
- function createSlashResultComponent(
134
- details: SlashMessageDetails,
135
- options: { expanded: boolean },
136
- theme: ExtensionContext["ui"]["theme"],
137
- requestRender: () => void,
138
- ): Container {
139
- const container = new Container();
140
- const animationState: { subagentResultAnimationTimer?: ReturnType<typeof setInterval> } = {};
141
- let lastVersion = -1;
142
- container.render = (width: number): string[] => {
143
- const snapshot = getSlashRenderableSnapshot(details);
144
- syncResultAnimation(snapshot.result, { state: animationState, invalidate: requestRender });
145
- if (snapshot.version !== lastVersion || isSlashResultRunning(snapshot.result)) {
146
- lastVersion = snapshot.version;
147
- rebuildSlashResultContainer(container, snapshot.result, options, theme);
148
- }
149
- return Container.prototype.render.call(container, width);
150
- };
151
- return container;
152
- }
153
-
154
- const SUBAGENT_CONTROL_MESSAGE_TYPE = "subagent_control_notice";
155
-
156
- interface SubagentControlMessageDetails {
157
- event: ControlEvent;
158
- source?: "foreground" | "async";
159
- asyncDir?: string;
160
- childIntercomTarget?: string;
161
- noticeText?: string;
162
- }
163
-
164
- function controlNoticeTarget(details: SubagentControlMessageDetails): string | undefined {
165
- return details.childIntercomTarget;
166
- }
167
-
168
- function formatSubagentControlNotice(details: SubagentControlMessageDetails, content?: string): string {
169
- return details.noticeText ?? content ?? formatControlNoticeMessage(details.event, controlNoticeTarget(details));
170
- }
171
-
172
- function parseSubagentNotifyContent(content: string): SubagentNotifyDetails | undefined {
173
- const lines = content.split("\n");
174
- const header = lines[0] ?? "";
175
- const match = header.match(/^Background task (completed|failed|paused): \*\*(.+?)\*\*(?:\s+(\([^)]*\)))?$/);
176
- if (!match) return undefined;
177
- const body = lines.slice(2);
178
- let sessionIndex = -1;
179
- for (let i = body.length - 1; i >= 1; i--) {
180
- if (body[i - 1]?.trim() === "" && /^(Session|Session file|Session share error):\s+/.test(body[i]!)) {
181
- sessionIndex = i;
182
- break;
183
- }
184
- }
185
- const sessionLine = sessionIndex >= 0 ? body[sessionIndex] : undefined;
186
- const resultLines = sessionIndex >= 0 ? body.slice(0, sessionIndex) : body;
187
- const resultPreview = resultLines.join("\n").trim() || "(no output)";
188
- let sessionLabel: string | undefined;
189
- let sessionValue: string | undefined;
190
- if (sessionLine) {
191
- const separator = sessionLine.indexOf(":");
192
- sessionLabel = sessionLine.slice(0, separator).toLowerCase();
193
- sessionValue = sessionLine.slice(separator + 1).trim();
194
- }
195
- return {
196
- agent: match[2]!,
197
- status: match[1] as SubagentNotifyDetails["status"],
198
- ...(match[3] ? { taskInfo: match[3] } : {}),
199
- resultPreview,
200
- ...(sessionLabel && sessionValue ? { sessionLabel, sessionValue } : {}),
201
- };
202
- }
203
-
204
- class SubagentControlNoticeComponent implements Component {
205
- constructor(
206
- private readonly details: SubagentControlMessageDetails,
207
- private readonly theme: ExtensionContext["ui"]["theme"],
208
- ) {}
209
-
210
- invalidate(): void {}
211
-
212
- render(width: number): string[] {
213
- const eventLabel = this.details.event.type.replaceAll("_", " ");
214
- if (width < 3) return [truncateToWidth(`Subagent ${eventLabel}`, width)];
215
- const bodyWidth = Math.max(1, Math.min(width - 2, 68));
216
- const borderChar = "─";
217
- const header = ` ⚠ Subagent ${eventLabel}: ${this.details.event.agent} `;
218
- const headerText = truncateToWidth(header, bodyWidth, "");
219
- const headerPadding = Math.max(0, bodyWidth - visibleWidth(headerText));
220
- const lines = [this.theme.fg("accent", `╭${headerText}${borderChar.repeat(headerPadding)}╮`)];
221
-
222
- for (const line of wrapTextWithAnsi(formatSubagentControlNotice(this.details), bodyWidth)) {
223
- const text = truncateToWidth(line, bodyWidth, "");
224
- const padding = Math.max(0, bodyWidth - visibleWidth(text));
225
- lines.push(this.theme.fg("accent", `│${text}${" ".repeat(padding)}│`));
226
- }
227
- lines.push(this.theme.fg("accent", `╰${borderChar.repeat(bodyWidth)}╯`));
228
- return lines;
229
- }
230
- }
231
-
232
- export default function registerSubagentExtension(pi: ExtensionAPI): void {
233
- const globalStore = globalThis as Record<string, unknown>;
234
- const runtimeCleanupStoreKey = "__piSubagentRuntimeCleanup";
235
- const previousRuntimeCleanup = globalStore[runtimeCleanupStoreKey];
236
- if (typeof previousRuntimeCleanup === "function") {
237
- try {
238
- previousRuntimeCleanup();
239
- } catch {
240
- // Best effort cleanup for stale timers from an older reload.
241
- }
242
- }
243
-
244
- ensureAccessibleDir(RESULTS_DIR);
245
- ensureAccessibleDir(ASYNC_DIR);
246
- cleanupOldChainDirs();
247
-
248
- const config = loadConfig();
249
- const asyncByDefault = config.asyncByDefault === true;
250
- const tempArtifactsDir = getArtifactsDir(null);
251
- cleanupAllArtifactDirs(DEFAULT_ARTIFACT_CONFIG.cleanupDays);
252
-
253
- const state: SubagentState = {
254
- baseCwd: process.cwd(),
255
- currentSessionId: null,
256
- asyncJobs: new Map(),
257
- foregroundControls: new Map(),
258
- lastForegroundControlId: null,
259
- cleanupTimers: new Map(),
260
- lastUiContext: null,
261
- poller: null,
262
- completionSeen: new Map(),
263
- watcher: null,
264
- watcherRestartTimer: null,
265
- resultFileCoalescer: {
266
- schedule: () => false,
267
- clear: () => {},
268
- },
269
- };
270
-
271
- const { startResultWatcher, primeExistingResults, stopResultWatcher } = createResultWatcher(
272
- pi,
273
- state,
274
- RESULTS_DIR,
275
- 10 * 60 * 1000,
276
- );
277
- startResultWatcher();
278
- primeExistingResults();
279
-
280
- const runtimeCleanup = () => {
281
- stopWidgetAnimation();
282
- stopResultAnimations();
283
- if (state.poller) {
284
- clearInterval(state.poller);
285
- state.poller = null;
286
- }
287
- };
288
- globalStore[runtimeCleanupStoreKey] = runtimeCleanup;
289
-
290
- const { ensurePoller, handleStarted, handleComplete, resetJobs } = createAsyncJobTracker(pi, state, ASYNC_DIR);
291
- const executor = createSubagentExecutor({
292
- pi,
293
- state,
294
- config,
295
- asyncByDefault,
296
- tempArtifactsDir,
297
- getSubagentSessionRoot,
298
- expandTilde,
299
- discoverAgents,
300
- });
301
-
302
- pi.registerMessageRenderer<SlashMessageDetails>(SLASH_RESULT_TYPE, (message, options, theme) => {
303
- const details = resolveSlashMessageDetails(message.details);
304
- if (!details) return undefined;
305
- return createSlashResultComponent(details, options, theme, () => state.lastUiContext?.ui.requestRender?.());
306
- });
307
-
308
- pi.registerMessageRenderer<SubagentNotifyDetails>("subagent-notify", (message, options, theme) => {
309
- const content = typeof message.content === "string" ? message.content : "";
310
- const details = (message.details as SubagentNotifyDetails | undefined) ?? parseSubagentNotifyContent(content);
311
- if (!details) return new Text(content, 0, 0);
312
- const icon = details.status === "completed"
313
- ? theme.fg("success", "✓")
314
- : details.status === "paused"
315
- ? theme.fg("warning", "■")
316
- : theme.fg("error", "✗");
317
- const parts: string[] = [];
318
- if (details.taskInfo) parts.push(details.taskInfo);
319
- if (details.durationMs !== undefined) parts.push(formatDuration(details.durationMs));
320
- let text = `${icon} ${theme.bold(details.agent)} ${theme.fg("dim", details.status)}`;
321
- if (parts.length > 0) text += ` ${theme.fg("dim", "·")} ${parts.map((part) => theme.fg("dim", part)).join(` ${theme.fg("dim", "·")} `)}`;
322
- const trimmedPreview = details.resultPreview.trim();
323
- const previewLines = options.expanded
324
- ? trimmedPreview.split("\n").filter((line) => line.trim())
325
- : [trimmedPreview.split("\n", 1)[0] ?? ""].filter((line) => line.trim());
326
- for (const line of previewLines.length > 0 ? previewLines : ["(no output)"]) {
327
- text += `\n ${theme.fg("dim", `⎿ ${line}`)}`;
328
- }
329
- if (!options.expanded && trimmedPreview.includes("\n")) {
330
- text += `\n ${theme.fg("dim", "Ctrl+O full notification")}`;
331
- }
332
- if (details.sessionLabel && details.sessionValue) {
333
- text += `\n ${theme.fg("muted", `${details.sessionLabel}: ${shortenPath(details.sessionValue)}`)}`;
334
- }
335
- return new Text(text, 0, 0);
336
- });
337
-
338
- pi.registerMessageRenderer<SubagentControlMessageDetails>(SUBAGENT_CONTROL_MESSAGE_TYPE, (message, _options, theme) => {
339
- const details = message.details as SubagentControlMessageDetails | undefined;
340
- if (!details?.event) return undefined;
341
- const content = typeof message.content === "string" ? message.content : undefined;
342
- return new SubagentControlNoticeComponent({ ...details, noticeText: formatSubagentControlNotice(details, content) }, theme);
343
- });
344
-
345
- const slashBridge = registerSlashSubagentBridge({
346
- events: pi.events,
347
- getContext: () => state.lastUiContext,
348
- execute: (id, params, signal, onUpdate, ctx) =>
349
- executor.execute(id, params, signal, onUpdate, ctx),
350
- });
351
-
352
- const promptTemplateBridge = registerPromptTemplateDelegationBridge({
353
- events: pi.events,
354
- getContext: () => state.lastUiContext,
355
- execute: async (requestId, request, signal, ctx, onUpdate) => {
356
- if (request.tasks && request.tasks.length > 0) {
357
- return executor.execute(
358
- requestId,
359
- {
360
- tasks: request.tasks,
361
- context: request.context,
362
- cwd: request.cwd,
363
- worktree: request.worktree,
364
- async: false,
365
- clarify: false,
366
- },
367
- signal,
368
- onUpdate,
369
- ctx,
370
- );
371
- }
372
- return executor.execute(
373
- requestId,
374
- {
375
- agent: request.agent,
376
- task: request.task,
377
- context: request.context,
378
- cwd: request.cwd,
379
- model: request.model,
380
- async: false,
381
- clarify: false,
382
- },
383
- signal,
384
- onUpdate,
385
- ctx,
386
- );
387
- },
388
- });
389
-
390
- function effectiveParallelTaskCount(tasks: Array<{ count?: unknown }> | undefined): number {
391
- if (!tasks || tasks.length === 0) return 0;
392
- return tasks.reduce((total, task) => {
393
- const count = typeof task.count === "number" && Number.isInteger(task.count) && task.count >= 1 ? task.count : 1;
394
- return total + count;
395
- }, 0);
396
- }
397
-
398
- const tool: ToolDefinition<typeof SubagentParams, Details> = {
399
- name: "subagent",
400
- label: "Subagent",
401
- description: `Delegate to subagents or manage agent definitions.
402
-
403
- EXECUTION (use exactly ONE mode):
404
- • Before executing, use { action: "list" } to inspect configured agents/chains. Only execute agents listed as executable/non-disabled.
405
- • SINGLE: { agent, task? } - one task; omit task for self-contained agents
406
- • CHAIN: { chain: [{agent:"agent-a"}, {parallel:[{agent:"agent-b",count:3}]}] } - sequential pipeline with optional parallel fan-out
407
- • PARALLEL: { tasks: [{agent,task,count?,output?,reads?,progress?}, ...], concurrency?: number, worktree?: true } - concurrent execution (worktree: isolate each task in a git worktree)
408
- • Optional context: { context: "fresh" | "fork" } (default: "fresh")
409
-
410
- CHAIN TEMPLATE VARIABLES (use in task strings):
411
- • {task} - The original task/request from the user
412
- • {previous} - Text response from the previous step (empty for first step)
413
- • {chain_dir} - Shared directory for chain files (e.g., <tmpdir>/pi-subagents-<scope>/chain-runs/abc123/)
414
-
415
- Example: { chain: [{agent:"agent-a", task:"Analyze {task}"}, {agent:"agent-b", task:"Plan based on {previous}"}] }
416
-
417
- MANAGEMENT (use action field, omit agent/task/chain/tasks):
418
- • { action: "list" } - discover executable agents/chains and any disabled builtins
419
- • { action: "get", agent: "name" } - full detail
420
- • { action: "create", config: { name, systemPrompt, systemPromptMode, inheritProjectContext, inheritSkills, ... } }
421
- • { action: "update", agent: "name", config: { ... } } - merge
422
- • { action: "delete", agent: "name" }
423
- • Use chainName for chain operations
424
-
425
- CONTROL:
426
- • { action: "status", id: "..." } - inspect an async/background run by id or prefix
427
- • { action: "interrupt", id?: "..." } - soft-interrupt the current child turn and leave the run paused
428
-
429
- DIAGNOSTICS:
430
- • { action: "doctor" } - read-only report for runtime paths, discovery, sessions, and intercom`,
431
- parameters: SubagentParams,
432
-
433
- execute(id, params, signal, onUpdate, ctx) {
434
- return executor.execute(id, params, signal, onUpdate, ctx);
435
- },
436
-
437
- renderCall(args, theme) {
438
- if (args.action) {
439
- const target = args.agent || args.chainName || "";
440
- return new Text(
441
- `${theme.fg("toolTitle", theme.bold("subagent "))}${args.action}${target ? ` ${theme.fg("accent", target)}` : ""}`,
442
- 0, 0,
443
- );
444
- }
445
- const isParallel = (args.tasks?.length ?? 0) > 0;
446
- const parallelCount = effectiveParallelTaskCount(args.tasks as Array<{ count?: unknown }> | undefined);
447
- const asyncLabel = args.async === true && !isParallel ? theme.fg("warning", " [async]") : "";
448
- if (args.chain?.length)
449
- return new Text(
450
- `${theme.fg("toolTitle", theme.bold("subagent "))}chain (${args.chain.length})${asyncLabel}`,
451
- 0,
452
- 0,
453
- );
454
- if (isParallel)
455
- return new Text(
456
- `${theme.fg("toolTitle", theme.bold("subagent "))}parallel (${parallelCount})`,
457
- 0,
458
- 0,
459
- );
460
- return new Text(
461
- `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent || "?")}${asyncLabel}`,
462
- 0,
463
- 0,
464
- );
465
- },
466
-
467
- renderResult(result, options, theme, context) {
468
- syncResultAnimation(result, context);
469
- return renderSubagentResult(result, options, theme);
470
- },
471
-
472
- };
473
-
474
- pi.registerTool(tool);
475
- registerSlashCommands(pi, state);
476
-
477
- const eventUnsubscribeStoreKey = "__piSubagentEventUnsubscribes";
478
- const controlNoticeSeenStoreKey = "__piSubagentVisibleControlNotices";
479
- const previousEventUnsubscribes = globalStore[eventUnsubscribeStoreKey];
480
- if (Array.isArray(previousEventUnsubscribes)) {
481
- for (const unsubscribe of previousEventUnsubscribes) {
482
- if (typeof unsubscribe !== "function") continue;
483
- try {
484
- unsubscribe();
485
- } catch {
486
- // Best effort cleanup for stale handlers from an older reload.
487
- }
488
- }
489
- }
490
- registerSubagentNotify(pi);
491
-
492
- const existingVisibleControlNotices = globalStore[controlNoticeSeenStoreKey];
493
- const visibleControlNotices = existingVisibleControlNotices instanceof Set ? existingVisibleControlNotices as Set<string> : new Set<string>();
494
- globalStore[controlNoticeSeenStoreKey] = visibleControlNotices;
495
- const controlEventHandler = (payload: unknown) => {
496
- const details = payload as SubagentControlMessageDetails;
497
- if (!details?.event) return;
498
- const childIntercomTarget = controlNoticeTarget(details);
499
- const key = controlNotificationKey(details.event, childIntercomTarget);
500
- if (visibleControlNotices.has(key)) return;
501
- visibleControlNotices.add(key);
502
- const noticeText = details.noticeText ?? formatControlNoticeMessage(details.event, childIntercomTarget);
503
- pi.sendMessage(
504
- {
505
- customType: SUBAGENT_CONTROL_MESSAGE_TYPE,
506
- content: noticeText,
507
- display: true,
508
- details: { ...details, childIntercomTarget, noticeText },
509
- },
510
- { triggerTurn: true },
511
- );
512
- };
513
- const eventUnsubscribes = [
514
- pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, handleStarted),
515
- pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, handleComplete),
516
- pi.events.on(SUBAGENT_CONTROL_EVENT, controlEventHandler),
517
- ];
518
- globalStore[eventUnsubscribeStoreKey] = eventUnsubscribes;
519
-
520
- pi.on("tool_result", (event, ctx) => {
521
- if (event.toolName !== "subagent") return;
522
- if (!ctx.hasUI) return;
523
- state.lastUiContext = ctx;
524
- if (state.asyncJobs.size > 0) {
525
- renderWidget(ctx, Array.from(state.asyncJobs.values()));
526
- ensurePoller();
527
- }
528
- });
529
-
530
- const cleanupSessionArtifacts = (ctx: ExtensionContext) => {
531
- try {
532
- const sessionFile = ctx.sessionManager.getSessionFile();
533
- if (sessionFile) {
534
- cleanupOldArtifacts(getArtifactsDir(sessionFile), DEFAULT_ARTIFACT_CONFIG.cleanupDays);
535
- }
536
- } catch {
537
- // Cleanup failures should not block session lifecycle events.
538
- }
539
- };
540
-
541
- const resetSessionState = (ctx: ExtensionContext) => {
542
- state.baseCwd = ctx.cwd;
543
- state.currentSessionId = ctx.sessionManager.getSessionFile() ?? `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
544
- state.lastUiContext = ctx;
545
- cleanupSessionArtifacts(ctx);
546
- resetJobs(ctx);
547
- restoreSlashFinalSnapshots(ctx.sessionManager.getEntries());
548
- };
549
-
550
- pi.on("session_start", (_event, ctx) => {
551
- resetSessionState(ctx);
552
- });
553
- pi.on("session_shutdown", () => {
554
- for (const unsubscribe of eventUnsubscribes) {
555
- try {
556
- unsubscribe();
557
- } catch {
558
- // Best effort cleanup during shutdown.
559
- }
560
- }
561
- if (globalStore[eventUnsubscribeStoreKey] === eventUnsubscribes) {
562
- delete globalStore[eventUnsubscribeStoreKey];
563
- }
564
- stopResultWatcher();
565
- if (state.poller) clearInterval(state.poller);
566
- state.poller = null;
567
- for (const timer of state.cleanupTimers.values()) {
568
- clearTimeout(timer);
569
- }
570
- state.cleanupTimers.clear();
571
- state.asyncJobs.clear();
572
- clearSlashSnapshots();
573
- slashBridge.cancelAll();
574
- slashBridge.dispose();
575
- promptTemplateBridge.cancelAll();
576
- promptTemplateBridge.dispose();
577
- stopWidgetAnimation();
578
- stopResultAnimations();
579
- if (globalStore[runtimeCleanupStoreKey] === runtimeCleanup) {
580
- delete globalStore[runtimeCleanupStoreKey];
581
- }
582
- if (state.lastUiContext?.hasUI) {
583
- state.lastUiContext.ui.setWidget(WIDGET_KEY, undefined);
584
- }
585
- });
586
- }