pi-herdr-subagents 0.1.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.
- package/.github/workflows/publish.yml +55 -0
- package/.pi/settings.json +8 -0
- package/.pi/skills/run-integration-tests/SKILL.md +28 -0
- package/LICENSE +21 -0
- package/README.md +483 -0
- package/RELEASING.md +103 -0
- package/agents/planner.md +546 -0
- package/agents/reviewer.md +150 -0
- package/agents/scout.md +104 -0
- package/agents/visual-tester.md +197 -0
- package/agents/worker.md +103 -0
- package/config.json.example +5 -0
- package/package.json +34 -0
- package/pi-extension/subagents/activity.ts +511 -0
- package/pi-extension/subagents/completion.ts +114 -0
- package/pi-extension/subagents/herdr.ts +200 -0
- package/pi-extension/subagents/index.ts +2182 -0
- package/pi-extension/subagents/plan-skill.md +203 -0
- package/pi-extension/subagents/plugin/.claude-plugin/plugin.json +5 -0
- package/pi-extension/subagents/plugin/hooks/hooks.json +15 -0
- package/pi-extension/subagents/plugin/hooks/on-stop.sh +68 -0
- package/pi-extension/subagents/session.ts +180 -0
- package/pi-extension/subagents/status.ts +513 -0
- package/pi-extension/subagents/subagent-done.ts +324 -0
- package/pi-extension/subagents/terminal.ts +106 -0
- package/test/integration/agents/test-echo.md +13 -0
- package/test/integration/agents/test-ping.md +11 -0
- package/test/integration/harness.ts +319 -0
- package/test/integration/mux-surface.test.ts +225 -0
- package/test/integration/subagent-lifecycle.test.ts +329 -0
- package/test/system-prompt-mode.test.ts +163 -0
- package/test/test.ts +2190 -0
|
@@ -0,0 +1,2182 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { keyHint } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
4
|
+
import { Box, Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import {
|
|
8
|
+
readdirSync,
|
|
9
|
+
readFileSync,
|
|
10
|
+
writeFileSync,
|
|
11
|
+
existsSync,
|
|
12
|
+
mkdirSync,
|
|
13
|
+
copyFileSync,
|
|
14
|
+
unlinkSync,
|
|
15
|
+
} from "node:fs";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import {
|
|
18
|
+
isTerminalAvailable,
|
|
19
|
+
terminalSetupHint,
|
|
20
|
+
createSubagentPane,
|
|
21
|
+
runScriptInPane,
|
|
22
|
+
closePane,
|
|
23
|
+
interruptPane,
|
|
24
|
+
shellQuote,
|
|
25
|
+
renameCurrentTab,
|
|
26
|
+
renameCurrentWorkspace,
|
|
27
|
+
readPane,
|
|
28
|
+
readPaneAsync,
|
|
29
|
+
} from "./terminal.ts";
|
|
30
|
+
import { waitForCompletion } from "./completion.ts";
|
|
31
|
+
|
|
32
|
+
import {
|
|
33
|
+
findLastAssistantMessage,
|
|
34
|
+
getNewEntries,
|
|
35
|
+
seedSubagentSessionFile,
|
|
36
|
+
} from "./session.ts";
|
|
37
|
+
import {
|
|
38
|
+
type StatusSnapshot,
|
|
39
|
+
type SubagentStatusState,
|
|
40
|
+
advanceStatusState,
|
|
41
|
+
capStatusLines,
|
|
42
|
+
classifyStatus,
|
|
43
|
+
createStatusState,
|
|
44
|
+
forceStatusAfterInterrupt,
|
|
45
|
+
formatStatusAggregate,
|
|
46
|
+
formatTransitionLine,
|
|
47
|
+
observeStatus,
|
|
48
|
+
loadStatusConfig,
|
|
49
|
+
} from "./status.ts";
|
|
50
|
+
import {
|
|
51
|
+
getSubagentActivityFile,
|
|
52
|
+
readSubagentActivityFile,
|
|
53
|
+
type ActivityReadResult,
|
|
54
|
+
type SubagentActivityState,
|
|
55
|
+
} from "./activity.ts";
|
|
56
|
+
|
|
57
|
+
/** Absolute path to `pi-extension/subagents`. https://github.com/nodejs/node/issues/37845 */
|
|
58
|
+
const SUBAGENTS_DIR = dirname(fileURLToPath(import.meta.url));
|
|
59
|
+
|
|
60
|
+
// Survive /reload: clear timers and abort poll loops from the previous module load.
|
|
61
|
+
// /reload re-imports this file, giving fresh module-level state, but closures from
|
|
62
|
+
// the old module keep running. These global symbols preserve reload compatibility.
|
|
63
|
+
const WIDGET_INTERVAL_KEY = Symbol.for("pi-subagents/widget-interval");
|
|
64
|
+
const STATUS_INTERVAL_KEY = Symbol.for("pi-subagents/status-interval");
|
|
65
|
+
const POLL_ABORT_KEY = Symbol.for("pi-subagents/poll-abort-controller");
|
|
66
|
+
|
|
67
|
+
{
|
|
68
|
+
const prevInterval = (globalThis as any)[WIDGET_INTERVAL_KEY];
|
|
69
|
+
if (prevInterval) {
|
|
70
|
+
clearInterval(prevInterval);
|
|
71
|
+
(globalThis as any)[WIDGET_INTERVAL_KEY] = null;
|
|
72
|
+
}
|
|
73
|
+
const prevStatusInterval = (globalThis as any)[STATUS_INTERVAL_KEY];
|
|
74
|
+
if (prevStatusInterval) {
|
|
75
|
+
clearInterval(prevStatusInterval);
|
|
76
|
+
(globalThis as any)[STATUS_INTERVAL_KEY] = null;
|
|
77
|
+
}
|
|
78
|
+
const prevAbort = (globalThis as any)[POLL_ABORT_KEY] as AbortController | undefined;
|
|
79
|
+
if (prevAbort) prevAbort.abort();
|
|
80
|
+
(globalThis as any)[POLL_ABORT_KEY] = new AbortController();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function getModuleAbortSignal(): AbortSignal {
|
|
84
|
+
return ((globalThis as any)[POLL_ABORT_KEY] as AbortController).signal;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const SubagentParams = Type.Object({
|
|
88
|
+
name: Type.String({ description: "Display name for the subagent" }),
|
|
89
|
+
task: Type.String({ description: "Task/prompt for the sub-agent" }),
|
|
90
|
+
agent: Type.Optional(
|
|
91
|
+
Type.String({
|
|
92
|
+
description:
|
|
93
|
+
"Agent name to load defaults from (e.g. 'worker', 'scout', 'reviewer'). Reads ~/.pi/agent/agents/<name>.md for model, tools, skills.",
|
|
94
|
+
}),
|
|
95
|
+
),
|
|
96
|
+
systemPrompt: Type.Optional(
|
|
97
|
+
Type.String({ description: "Appended to system prompt (role instructions)" }),
|
|
98
|
+
),
|
|
99
|
+
model: Type.Optional(Type.String({ description: "Model override (overrides agent default)" })),
|
|
100
|
+
skills: Type.Optional(
|
|
101
|
+
Type.String({ description: "Comma-separated skills (overrides agent default)" }),
|
|
102
|
+
),
|
|
103
|
+
tools: Type.Optional(
|
|
104
|
+
Type.String({ description: "Comma-separated tools (overrides agent default)" }),
|
|
105
|
+
),
|
|
106
|
+
cwd: Type.Optional(
|
|
107
|
+
Type.String({
|
|
108
|
+
description:
|
|
109
|
+
"Working directory for the sub-agent. The agent starts in this folder and picks up its local .pi/ config, CLAUDE.md, skills, and extensions. Use for role-specific subfolders.",
|
|
110
|
+
}),
|
|
111
|
+
),
|
|
112
|
+
fork: Type.Optional(
|
|
113
|
+
Type.Boolean({
|
|
114
|
+
description:
|
|
115
|
+
"Force the full-context fork mode for this spawn. The sub-agent inherits the current session conversation, overriding any agent frontmatter session-mode.",
|
|
116
|
+
}),
|
|
117
|
+
),
|
|
118
|
+
interactive: Type.Optional(
|
|
119
|
+
Type.Boolean({
|
|
120
|
+
description:
|
|
121
|
+
"Mark the subagent as interactive (long-running, user drives the conversation in its own pane). When true, the main session is not woken by status transitions (stalled/recovered) for this subagent. If omitted, falls back to the agent's `interactive` frontmatter, otherwise the inverse of `auto-exit` (agents that auto-exit are autonomous and get stall pings; agents that don't are interactive and stay quiet).",
|
|
122
|
+
}),
|
|
123
|
+
),
|
|
124
|
+
resumeSessionId: Type.Optional(
|
|
125
|
+
Type.String({
|
|
126
|
+
description:
|
|
127
|
+
"Resume a previous Claude Code session by its ID. Loads the conversation history and continues where it left off. The session ID is returned in details of every claude tool call. Use this to retry cancelled runs or ask follow-up questions.",
|
|
128
|
+
}),
|
|
129
|
+
),
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
type SubagentSessionMode = "standalone" | "lineage-only" | "fork";
|
|
133
|
+
|
|
134
|
+
interface AgentDefaults {
|
|
135
|
+
model?: string;
|
|
136
|
+
tools?: string;
|
|
137
|
+
skills?: string;
|
|
138
|
+
thinking?: string;
|
|
139
|
+
denyTools?: string;
|
|
140
|
+
spawning?: boolean;
|
|
141
|
+
autoExit?: boolean;
|
|
142
|
+
interactive?: boolean;
|
|
143
|
+
systemPromptMode?: "append" | "replace";
|
|
144
|
+
sessionMode?: SubagentSessionMode;
|
|
145
|
+
cwd?: string;
|
|
146
|
+
cli?: string;
|
|
147
|
+
body?: string;
|
|
148
|
+
disableModelInvocation?: boolean;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
type AgentSource = "package" | "global" | "project";
|
|
152
|
+
|
|
153
|
+
interface AgentDefinition extends AgentDefaults {
|
|
154
|
+
name: string;
|
|
155
|
+
description?: string;
|
|
156
|
+
disableModelInvocation: boolean;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
interface ListedAgentDefinition extends AgentDefinition {
|
|
160
|
+
source: AgentSource;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Tools that are gated by `spawning: false` */
|
|
164
|
+
const SPAWNING_TOOLS = new Set([
|
|
165
|
+
"subagent",
|
|
166
|
+
"subagent_interrupt",
|
|
167
|
+
"subagents_list",
|
|
168
|
+
"subagent_resume",
|
|
169
|
+
]);
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Resolve the effective set of denied tool names from agent defaults.
|
|
173
|
+
* `spawning: false` expands to all SPAWNING_TOOLS.
|
|
174
|
+
* `deny-tools` adds individual tool names on top.
|
|
175
|
+
*/
|
|
176
|
+
function resolveDenyTools(agentDefs: AgentDefaults | null): Set<string> {
|
|
177
|
+
const denied = new Set<string>();
|
|
178
|
+
if (!agentDefs) return denied;
|
|
179
|
+
|
|
180
|
+
// spawning: false → deny all spawning tools
|
|
181
|
+
if (agentDefs.spawning === false) {
|
|
182
|
+
for (const t of SPAWNING_TOOLS) denied.add(t);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// deny-tools: explicit list
|
|
186
|
+
if (agentDefs.denyTools) {
|
|
187
|
+
for (const t of agentDefs.denyTools
|
|
188
|
+
.split(",")
|
|
189
|
+
.map((s) => s.trim())
|
|
190
|
+
.filter(Boolean)) {
|
|
191
|
+
denied.add(t);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return denied;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Resolve the global agent config directory, respecting PI_CODING_AGENT_DIR. */
|
|
199
|
+
function getAgentConfigDir(): string {
|
|
200
|
+
return process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function getBundledAgentsDir(): string {
|
|
204
|
+
return join(SUBAGENTS_DIR, "../../agents");
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function getFrontmatterValue(frontmatter: string, key: string): string | undefined {
|
|
208
|
+
const match = frontmatter.match(new RegExp(`^${key}:\\s*(.+)$`, "m"));
|
|
209
|
+
return match ? match[1].trim() : undefined;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function parseOptionalBoolean(value: string | undefined): boolean | undefined {
|
|
213
|
+
return value != null ? value === "true" : undefined;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function parseSessionMode(value: string | undefined): SubagentSessionMode | undefined {
|
|
217
|
+
if (value === "standalone" || value === "lineage-only" || value === "fork") {
|
|
218
|
+
return value;
|
|
219
|
+
}
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function parseAgentDefinition(content: string, fallbackName: string): AgentDefinition | null {
|
|
224
|
+
const match = content.match(/^---\n([\s\S]*?)\n---/);
|
|
225
|
+
if (!match) return null;
|
|
226
|
+
|
|
227
|
+
const frontmatter = match[1];
|
|
228
|
+
const body = content.replace(/^---\n[\s\S]*?\n---\n*/, "").trim();
|
|
229
|
+
const systemPromptMode = getFrontmatterValue(frontmatter, "system-prompt");
|
|
230
|
+
|
|
231
|
+
return {
|
|
232
|
+
name: getFrontmatterValue(frontmatter, "name") ?? fallbackName,
|
|
233
|
+
description: getFrontmatterValue(frontmatter, "description"),
|
|
234
|
+
model: getFrontmatterValue(frontmatter, "model"),
|
|
235
|
+
tools: getFrontmatterValue(frontmatter, "tools"),
|
|
236
|
+
systemPromptMode:
|
|
237
|
+
systemPromptMode === "replace"
|
|
238
|
+
? "replace"
|
|
239
|
+
: systemPromptMode === "append"
|
|
240
|
+
? "append"
|
|
241
|
+
: undefined,
|
|
242
|
+
skills: getFrontmatterValue(frontmatter, "skill") ?? getFrontmatterValue(frontmatter, "skills"),
|
|
243
|
+
thinking: getFrontmatterValue(frontmatter, "thinking"),
|
|
244
|
+
denyTools: getFrontmatterValue(frontmatter, "deny-tools"),
|
|
245
|
+
spawning: parseOptionalBoolean(getFrontmatterValue(frontmatter, "spawning")),
|
|
246
|
+
autoExit: parseOptionalBoolean(getFrontmatterValue(frontmatter, "auto-exit")),
|
|
247
|
+
interactive: parseOptionalBoolean(getFrontmatterValue(frontmatter, "interactive")),
|
|
248
|
+
sessionMode: parseSessionMode(getFrontmatterValue(frontmatter, "session-mode")),
|
|
249
|
+
cwd: getFrontmatterValue(frontmatter, "cwd"),
|
|
250
|
+
cli: getFrontmatterValue(frontmatter, "cli"),
|
|
251
|
+
body: body || undefined,
|
|
252
|
+
disableModelInvocation:
|
|
253
|
+
getFrontmatterValue(frontmatter, "disable-model-invocation")?.toLowerCase() === "true",
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function discoverAgentDefinitions(): ListedAgentDefinition[] {
|
|
258
|
+
const agents = new Map<string, ListedAgentDefinition>();
|
|
259
|
+
const dirs: Array<{ path: string; source: AgentSource }> = [
|
|
260
|
+
{ path: getBundledAgentsDir(), source: "package" },
|
|
261
|
+
{ path: join(getAgentConfigDir(), "agents"), source: "global" },
|
|
262
|
+
{ path: join(process.cwd(), ".pi", "agents"), source: "project" },
|
|
263
|
+
];
|
|
264
|
+
|
|
265
|
+
for (const { path: dir, source } of dirs) {
|
|
266
|
+
if (!existsSync(dir)) continue;
|
|
267
|
+
for (const file of readdirSync(dir).filter((entry) => entry.endsWith(".md"))) {
|
|
268
|
+
const parsed = parseAgentDefinition(
|
|
269
|
+
readFileSync(join(dir, file), "utf8"),
|
|
270
|
+
file.replace(/\.md$/, ""),
|
|
271
|
+
);
|
|
272
|
+
if (!parsed) continue;
|
|
273
|
+
agents.set(parsed.name, { ...parsed, source });
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
return [...agents.values()];
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function resolveSubagentPaths(
|
|
281
|
+
params: Static<typeof SubagentParams>,
|
|
282
|
+
agentDefs: AgentDefaults | null,
|
|
283
|
+
): { effectiveCwd: string | null; localAgentDir: string | null; effectiveAgentDir: string } {
|
|
284
|
+
const rawCwd = params.cwd ?? agentDefs?.cwd ?? null;
|
|
285
|
+
const cwdIsFromAgent = !params.cwd && agentDefs?.cwd != null;
|
|
286
|
+
const cwdBase = cwdIsFromAgent ? getAgentConfigDir() : process.cwd();
|
|
287
|
+
const effectiveCwd = rawCwd
|
|
288
|
+
? rawCwd.startsWith("/")
|
|
289
|
+
? rawCwd
|
|
290
|
+
: join(cwdBase, rawCwd)
|
|
291
|
+
: null;
|
|
292
|
+
const localAgentDir = effectiveCwd ? join(effectiveCwd, ".pi", "agent") : null;
|
|
293
|
+
const effectiveAgentDir =
|
|
294
|
+
localAgentDir && existsSync(localAgentDir) ? localAgentDir : getAgentConfigDir();
|
|
295
|
+
return { effectiveCwd, localAgentDir, effectiveAgentDir };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function getDefaultSessionDirFor(cwd: string, agentDir: string): string {
|
|
299
|
+
const safePath = `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
|
|
300
|
+
const sessionDir = join(agentDir, "sessions", safePath);
|
|
301
|
+
if (!existsSync(sessionDir)) {
|
|
302
|
+
mkdirSync(sessionDir, { recursive: true });
|
|
303
|
+
}
|
|
304
|
+
return sessionDir;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function resolveEffectiveSessionMode(
|
|
308
|
+
params: Static<typeof SubagentParams>,
|
|
309
|
+
agentDefs: AgentDefaults | null,
|
|
310
|
+
): SubagentSessionMode {
|
|
311
|
+
if (params.fork) return "fork";
|
|
312
|
+
return agentDefs?.sessionMode ?? "standalone";
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function resolveLaunchBehavior(
|
|
316
|
+
params: Static<typeof SubagentParams>,
|
|
317
|
+
agentDefs: AgentDefaults | null,
|
|
318
|
+
): {
|
|
319
|
+
sessionMode: SubagentSessionMode;
|
|
320
|
+
seededSessionMode: "lineage-only" | "fork" | null;
|
|
321
|
+
inheritsConversationContext: boolean;
|
|
322
|
+
taskDelivery: "direct" | "artifact";
|
|
323
|
+
} {
|
|
324
|
+
const sessionMode = resolveEffectiveSessionMode(params, agentDefs);
|
|
325
|
+
const inheritsConversationContext = sessionMode === "fork";
|
|
326
|
+
return {
|
|
327
|
+
sessionMode,
|
|
328
|
+
seededSessionMode: sessionMode === "standalone" ? null : sessionMode,
|
|
329
|
+
inheritsConversationContext,
|
|
330
|
+
taskDelivery: inheritsConversationContext ? "direct" : "artifact",
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Decide whether a subagent is interactive (user-driven, long-running).
|
|
336
|
+
*
|
|
337
|
+
* Resolution order:
|
|
338
|
+
* 1. Explicit `interactive` tool parameter wins.
|
|
339
|
+
* 2. Explicit `interactive` frontmatter field on the agent.
|
|
340
|
+
* 3. Default: the inverse of `auto-exit`. Agents that auto-exit are
|
|
341
|
+
* autonomous (scout, worker, reviewer) and the parent session should be
|
|
342
|
+
* woken on stall/recovery transitions. Agents that don't auto-exit are
|
|
343
|
+
* driven by the user in their own pane (planner, iterate/fork) and
|
|
344
|
+
* stall pings are noise.
|
|
345
|
+
*
|
|
346
|
+
* When no agent defs exist at all (bare `subagent({ name, task })` call,
|
|
347
|
+
* typical for `/iterate` with `fork: true`), `autoExit` is undefined and the
|
|
348
|
+
* subagent is treated as interactive — matching the intent of iterate.
|
|
349
|
+
*/
|
|
350
|
+
function resolveEffectiveInteractive(
|
|
351
|
+
params: Static<typeof SubagentParams>,
|
|
352
|
+
agentDefs: AgentDefaults | null,
|
|
353
|
+
): boolean {
|
|
354
|
+
if (params.interactive != null) return params.interactive;
|
|
355
|
+
if (agentDefs?.interactive != null) return agentDefs.interactive;
|
|
356
|
+
return !(agentDefs?.autoExit ?? false);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function loadAgentDefaults(agentName: string): AgentDefaults | null {
|
|
360
|
+
const configDir = getAgentConfigDir();
|
|
361
|
+
const paths = [
|
|
362
|
+
join(process.cwd(), ".pi", "agents", `${agentName}.md`),
|
|
363
|
+
join(configDir, "agents", `${agentName}.md`),
|
|
364
|
+
join(getBundledAgentsDir(), `${agentName}.md`),
|
|
365
|
+
];
|
|
366
|
+
|
|
367
|
+
for (const p of paths) {
|
|
368
|
+
if (!existsSync(p)) continue;
|
|
369
|
+
const parsed = parseAgentDefinition(readFileSync(p, "utf8"), agentName);
|
|
370
|
+
if (parsed) return parsed;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function formatElapsed(seconds: number): string {
|
|
377
|
+
if (seconds < 60) return `${seconds}s`;
|
|
378
|
+
const m = Math.floor(seconds / 60);
|
|
379
|
+
const s = seconds % 60;
|
|
380
|
+
return `${m}m ${s}s`;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Wait long enough for a freshly created pane to finish shell startup.
|
|
385
|
+
*
|
|
386
|
+
* Some environments do extra shell-init work before the prompt is ready
|
|
387
|
+
* (for example direnv/devenv), so the delay is configurable for users who hit
|
|
388
|
+
* dropped commands. Keep the historical default at 500ms.
|
|
389
|
+
*/
|
|
390
|
+
function getShellReadyDelayMs(): number {
|
|
391
|
+
const raw = process.env.PI_SUBAGENT_SHELL_READY_DELAY_MS?.trim();
|
|
392
|
+
const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;
|
|
393
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 500;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function muxUnavailableResult() {
|
|
397
|
+
return {
|
|
398
|
+
content: [
|
|
399
|
+
{
|
|
400
|
+
type: "text" as const,
|
|
401
|
+
text: `Subagents require herdr. ${terminalSetupHint()}`,
|
|
402
|
+
},
|
|
403
|
+
],
|
|
404
|
+
details: { error: "herdr not available" },
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Build the internal artifact directory path for the current session.
|
|
410
|
+
* Used by the subagents extension to stash task files, system prompts, and
|
|
411
|
+
* launch scripts for sub-agents. Path convention:
|
|
412
|
+
* <sessionDir>/artifacts/<session-id>/
|
|
413
|
+
*/
|
|
414
|
+
function getArtifactDir(sessionDir: string, sessionId: string): string {
|
|
415
|
+
return join(sessionDir, "artifacts", sessionId);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const statusConfig = loadStatusConfig();
|
|
419
|
+
|
|
420
|
+
function formatWidgetRightLabel(snapshot: StatusSnapshot): string {
|
|
421
|
+
if (snapshot.kind === "starting") return " starting… ";
|
|
422
|
+
if (snapshot.kind === "running") return ` running ${snapshot.elapsedText} `;
|
|
423
|
+
if (snapshot.kind === "active") {
|
|
424
|
+
const label = snapshot.activityLabel ?? snapshot.activeScope;
|
|
425
|
+
const duration = snapshot.activeDurationText ? ` ${snapshot.activeDurationText}` : "";
|
|
426
|
+
return label ? ` active · ${label}${duration} ` : " active ";
|
|
427
|
+
}
|
|
428
|
+
if (snapshot.kind === "waiting") {
|
|
429
|
+
const duration = snapshot.waitingDurationText ? ` ${snapshot.waitingDurationText}` : "";
|
|
430
|
+
const detail = snapshot.statusLabel ? ` · ${snapshot.statusLabel}` : "";
|
|
431
|
+
return ` waiting${duration}${detail} `;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const detail = snapshot.statusLabel ? ` · ${snapshot.statusLabel}` : "";
|
|
435
|
+
const duration = snapshot.snapshotProblemText ? ` ${snapshot.snapshotProblemText}` : "";
|
|
436
|
+
return ` stalled${detail}${duration} `;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function resolveResultPresentation(
|
|
440
|
+
result: Pick<
|
|
441
|
+
SubagentResult,
|
|
442
|
+
"exitCode" | "elapsed" | "summary" | "sessionFile" | "errorMessage"
|
|
443
|
+
>,
|
|
444
|
+
name: string,
|
|
445
|
+
): string {
|
|
446
|
+
const sessionRef = result.sessionFile
|
|
447
|
+
? `\n\nSession: ${result.sessionFile}\nResume: pi --session ${result.sessionFile}`
|
|
448
|
+
: "";
|
|
449
|
+
|
|
450
|
+
if (result.errorMessage) {
|
|
451
|
+
// Auto-retry exhausted or other agent-loop error. The subagent did not
|
|
452
|
+
// produce a usable result — surface the underlying provider/network
|
|
453
|
+
// failure so the orchestrator can decide whether to retry, resume, or
|
|
454
|
+
// change approach instead of silently treating the run as completed.
|
|
455
|
+
return (
|
|
456
|
+
`Sub-agent "${name}" failed after ${formatElapsed(result.elapsed)} ` +
|
|
457
|
+
`(provider/agent error — auto-retry exhausted).\n\n` +
|
|
458
|
+
`Error: ${result.errorMessage}\n\n` +
|
|
459
|
+
`The subagent did not produce a result. You can retry by spawning a new ` +
|
|
460
|
+
`subagent or resume the session with subagent_resume.${sessionRef}`
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
return result.exitCode !== 0
|
|
465
|
+
? `Sub-agent "${name}" failed (exit code ${result.exitCode}).\n\n${result.summary}${sessionRef}`
|
|
466
|
+
: `Sub-agent "${name}" completed (${formatElapsed(result.elapsed)}).\n\n${result.summary}${sessionRef}`;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Result from running a single subagent.
|
|
471
|
+
*/
|
|
472
|
+
interface SubagentResult {
|
|
473
|
+
name: string;
|
|
474
|
+
task: string;
|
|
475
|
+
summary: string;
|
|
476
|
+
sessionFile?: string;
|
|
477
|
+
claudeSessionId?: string;
|
|
478
|
+
exitCode: number;
|
|
479
|
+
elapsed: number;
|
|
480
|
+
error?: string;
|
|
481
|
+
/** Provider/agent error message when auto-retry exhausted (overload, rate limit, etc.). */
|
|
482
|
+
errorMessage?: string;
|
|
483
|
+
ping?: { name: string; message: string };
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* State for a launched (but not yet completed) subagent.
|
|
488
|
+
*/
|
|
489
|
+
interface RunningSubagent {
|
|
490
|
+
id: string;
|
|
491
|
+
name: string;
|
|
492
|
+
task: string;
|
|
493
|
+
agent?: string;
|
|
494
|
+
surface: string;
|
|
495
|
+
startTime: number;
|
|
496
|
+
sessionFile: string;
|
|
497
|
+
launchScriptFile?: string;
|
|
498
|
+
activityFile?: string;
|
|
499
|
+
activity?: SubagentActivityState;
|
|
500
|
+
activityRead?: {
|
|
501
|
+
ok: boolean;
|
|
502
|
+
reason?: "missing" | "invalid" | "wrong-id";
|
|
503
|
+
error?: string;
|
|
504
|
+
};
|
|
505
|
+
abortController?: AbortController;
|
|
506
|
+
cli?: string;
|
|
507
|
+
sentinelFile?: string;
|
|
508
|
+
statusState: SubagentStatusState;
|
|
509
|
+
/**
|
|
510
|
+
* When true, status transitions (stalled/recovered) do not wake the parent
|
|
511
|
+
* session via a steer message. The widget still updates locally. Used for
|
|
512
|
+
* long-running agents where the user drives the conversation in the
|
|
513
|
+
* subagent's pane (e.g. planner).
|
|
514
|
+
*/
|
|
515
|
+
interactive: boolean;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** All currently running subagents, keyed by id. */
|
|
519
|
+
const runningSubagents = new Map<string, RunningSubagent>();
|
|
520
|
+
|
|
521
|
+
// ── Widget management ──
|
|
522
|
+
|
|
523
|
+
/** Latest ExtensionContext from session_start, used for widget updates. */
|
|
524
|
+
let latestCtx: ExtensionContext | null = null;
|
|
525
|
+
|
|
526
|
+
/** Interval timer for widget re-renders. */
|
|
527
|
+
let widgetInterval: ReturnType<typeof setInterval> | null = null;
|
|
528
|
+
|
|
529
|
+
/** Interval timer for status transition checks. */
|
|
530
|
+
let statusInterval: ReturnType<typeof setInterval> | null = null;
|
|
531
|
+
|
|
532
|
+
function formatElapsedMMSS(startTime: number): string {
|
|
533
|
+
const seconds = Math.floor((Date.now() - startTime) / 1000);
|
|
534
|
+
const m = Math.floor(seconds / 60);
|
|
535
|
+
const s = seconds % 60;
|
|
536
|
+
return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const ACCENT = "\x1b[38;2;77;163;255m";
|
|
540
|
+
const RST = "\x1b[0m";
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Build a bordered content line: │left right│
|
|
544
|
+
* Left content is truncated if needed, right is preserved, padded to fill width.
|
|
545
|
+
*/
|
|
546
|
+
function borderLine(left: string, right: string, width: number): string {
|
|
547
|
+
if (width <= 0) return "";
|
|
548
|
+
if (width === 1) return `${ACCENT}│${RST}`;
|
|
549
|
+
|
|
550
|
+
// width = total visible chars for the whole line including │ and │
|
|
551
|
+
const contentWidth = Math.max(0, width - 2); // space inside the two │ chars
|
|
552
|
+
const rightVis = visibleWidth(right);
|
|
553
|
+
|
|
554
|
+
// If the status chunk alone is too wide, prefer preserving it in compact form
|
|
555
|
+
// rather than overflowing the terminal.
|
|
556
|
+
if (rightVis >= contentWidth) {
|
|
557
|
+
const truncRight = truncateToWidth(right, contentWidth);
|
|
558
|
+
const rightPad = Math.max(0, contentWidth - visibleWidth(truncRight));
|
|
559
|
+
return `${ACCENT}│${RST}${truncRight}${" ".repeat(rightPad)}${ACCENT}│${RST}`;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const maxLeft = Math.max(0, contentWidth - rightVis);
|
|
563
|
+
const truncLeft = truncateToWidth(left, maxLeft);
|
|
564
|
+
const leftVis = visibleWidth(truncLeft);
|
|
565
|
+
const pad = Math.max(0, contentWidth - leftVis - rightVis);
|
|
566
|
+
return `${ACCENT}│${RST}${truncLeft}${" ".repeat(pad)}${right}${ACCENT}│${RST}`;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Build the bordered top line: ╭─ Title ──── info ─╮
|
|
571
|
+
* All chars are accounted for within `width`.
|
|
572
|
+
*/
|
|
573
|
+
function borderTop(title: string, info: string, width: number): string {
|
|
574
|
+
if (width <= 0) return "";
|
|
575
|
+
if (width === 1) return `${ACCENT}╭${RST}`;
|
|
576
|
+
|
|
577
|
+
// ╭─ Title ───...─── info ─╮
|
|
578
|
+
// overhead: ╭─ (2) + space around title (2) + space around info (2) + ─╮ (2) = but we simplify
|
|
579
|
+
const inner = Math.max(0, width - 2); // inside ╭ and ╮
|
|
580
|
+
const titlePart = `─ ${title} `;
|
|
581
|
+
const infoPart = ` ${info} ─`;
|
|
582
|
+
const fillLen = Math.max(0, inner - titlePart.length - infoPart.length);
|
|
583
|
+
const fill = "─".repeat(fillLen);
|
|
584
|
+
const content = `${titlePart}${fill}${infoPart}`.slice(0, inner).padEnd(inner, "─");
|
|
585
|
+
return `${ACCENT}╭${content}╮${RST}`;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Build the bordered bottom line: ╰──────────────────╯
|
|
590
|
+
*/
|
|
591
|
+
function borderBottom(width: number): string {
|
|
592
|
+
if (width <= 0) return "";
|
|
593
|
+
if (width === 1) return `${ACCENT}╰${RST}`;
|
|
594
|
+
|
|
595
|
+
const inner = Math.max(0, width - 2);
|
|
596
|
+
return `${ACCENT}╰${"─".repeat(inner)}╯${RST}`;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function renderSubagentWidgetLines(agents: RunningSubagent[], width: number): string[] {
|
|
600
|
+
const count = agents.length;
|
|
601
|
+
const title = "Subagents";
|
|
602
|
+
const info = `${count} running`;
|
|
603
|
+
|
|
604
|
+
const lines: string[] = [borderTop(title, info, width)];
|
|
605
|
+
|
|
606
|
+
for (const agent of agents) {
|
|
607
|
+
const elapsed = formatElapsedMMSS(agent.startTime);
|
|
608
|
+
const agentTag = agent.agent ? ` (${agent.agent})` : "";
|
|
609
|
+
const left = ` ${elapsed} ${agent.name}${agentTag} `;
|
|
610
|
+
const snapshot = classifyStatus(agent.statusState, Date.now());
|
|
611
|
+
const right = statusConfig.enabled
|
|
612
|
+
? formatWidgetRightLabel(snapshot)
|
|
613
|
+
: agent.cli === "claude"
|
|
614
|
+
? " running… "
|
|
615
|
+
: " starting… ";
|
|
616
|
+
|
|
617
|
+
lines.push(borderLine(left, right, width));
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
lines.push(borderBottom(width));
|
|
621
|
+
return lines;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function updateWidget() {
|
|
625
|
+
if (!latestCtx?.hasUI) return;
|
|
626
|
+
|
|
627
|
+
if (runningSubagents.size === 0) {
|
|
628
|
+
latestCtx.ui.setWidget("subagent-status", undefined);
|
|
629
|
+
if (widgetInterval) {
|
|
630
|
+
clearInterval(widgetInterval);
|
|
631
|
+
widgetInterval = null;
|
|
632
|
+
(globalThis as any)[WIDGET_INTERVAL_KEY] = null;
|
|
633
|
+
}
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
latestCtx.ui.setWidget(
|
|
638
|
+
"subagent-status",
|
|
639
|
+
(_tui: any, _theme: any) => {
|
|
640
|
+
return {
|
|
641
|
+
invalidate() {},
|
|
642
|
+
render(width: number) {
|
|
643
|
+
return renderSubagentWidgetLines(Array.from(runningSubagents.values()), width);
|
|
644
|
+
},
|
|
645
|
+
};
|
|
646
|
+
},
|
|
647
|
+
{ placement: "aboveEditor" },
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Build the positional prompt args for a Pi CLI subagent launch.
|
|
653
|
+
*
|
|
654
|
+
* In artifact-backed launches (lineage-only, standalone), Pi's buildInitialMessage()
|
|
655
|
+
* concatenates @file content with messages[0] into one initial prompt. That breaks
|
|
656
|
+
* /skill: expansion because the message no longer starts with "/skill:". Only
|
|
657
|
+
* messages[1..] are sent as separate follow-up prompts where /skill: is recognized.
|
|
658
|
+
*
|
|
659
|
+
* When there are skill prompts AND artifact-backed delivery, we prepend an empty
|
|
660
|
+
* first positional message so that /skill: args land in messages[1..] and arrive
|
|
661
|
+
* as standalone prompts in the child session.
|
|
662
|
+
*/
|
|
663
|
+
const SUBAGENT_CONTROL_TOOLS = ["caller_ping", "subagent_done"] as const;
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Build the child --tools allowlist.
|
|
667
|
+
*
|
|
668
|
+
* Pi 0.70+ applies --tools to built-in, extension, and custom tools. If a
|
|
669
|
+
* subagent definition restricts tools to e.g. "read,bash,write", the child
|
|
670
|
+
* control tools from subagent-done.ts would otherwise be hidden, leaving a
|
|
671
|
+
* manually resumed or user-touched subagent unable to call subagent_done.
|
|
672
|
+
*/
|
|
673
|
+
function buildSubagentToolAllowlist(effectiveTools?: string): string | null {
|
|
674
|
+
const requested = (effectiveTools ?? "")
|
|
675
|
+
.split(",")
|
|
676
|
+
.map((tool) => tool.trim())
|
|
677
|
+
.filter(Boolean);
|
|
678
|
+
|
|
679
|
+
if (requested.length === 0) return null;
|
|
680
|
+
|
|
681
|
+
const allow = new Set(requested);
|
|
682
|
+
for (const tool of SUBAGENT_CONTROL_TOOLS) {
|
|
683
|
+
allow.add(tool);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
return [...allow].join(",");
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function buildPiPromptArgs(params: {
|
|
690
|
+
effectiveSkills?: string;
|
|
691
|
+
taskDelivery: "direct" | "artifact";
|
|
692
|
+
taskArg: string;
|
|
693
|
+
}): string[] {
|
|
694
|
+
const skillPrompts = (params.effectiveSkills ?? "")
|
|
695
|
+
.split(",")
|
|
696
|
+
.map((s) => s.trim())
|
|
697
|
+
.filter(Boolean)
|
|
698
|
+
.map((skill) => `/skill:${skill}`);
|
|
699
|
+
|
|
700
|
+
const needsSeparator = params.taskDelivery === "artifact" && skillPrompts.length > 0;
|
|
701
|
+
|
|
702
|
+
return [
|
|
703
|
+
...(needsSeparator ? [""] : []),
|
|
704
|
+
...skillPrompts,
|
|
705
|
+
params.taskArg,
|
|
706
|
+
];
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function activityLabel(activity: SubagentActivityState): string | undefined {
|
|
710
|
+
if (activity.phase !== "active") return undefined;
|
|
711
|
+
if (activity.activeScope === "tool") return activity.toolName ?? "tool";
|
|
712
|
+
if (activity.activeScope === "provider") return "provider";
|
|
713
|
+
if (activity.activeScope === "streaming") return "streaming";
|
|
714
|
+
return activity.activeScope;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function observeRunningSubagent(running: RunningSubagent, observedAt = Date.now()) {
|
|
718
|
+
if (running.cli === "claude") return;
|
|
719
|
+
|
|
720
|
+
const activityFile = running.activityFile;
|
|
721
|
+
const read: ActivityReadResult = activityFile
|
|
722
|
+
? readSubagentActivityFile(activityFile, running.id)
|
|
723
|
+
: { ok: false, reason: "missing" };
|
|
724
|
+
|
|
725
|
+
running.activityRead = read.ok
|
|
726
|
+
? { ok: true }
|
|
727
|
+
: { ok: false, reason: read.reason, error: read.error };
|
|
728
|
+
|
|
729
|
+
if (read.ok) {
|
|
730
|
+
running.activity = read.activity;
|
|
731
|
+
running.statusState = observeStatus(running.statusState, {
|
|
732
|
+
snapshot: "present",
|
|
733
|
+
updatedAt: read.activity.updatedAt,
|
|
734
|
+
sequence: read.activity.sequence,
|
|
735
|
+
phase: read.activity.phase,
|
|
736
|
+
active: read.activity.phase === "active",
|
|
737
|
+
activeScope: read.activity.activeScope,
|
|
738
|
+
activeSince: read.activity.activeSince,
|
|
739
|
+
waitingSince: read.activity.waitingSince,
|
|
740
|
+
latestEvent: read.activity.latestEvent,
|
|
741
|
+
activityLabel: activityLabel(read.activity),
|
|
742
|
+
}, observedAt);
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
running.statusState = observeStatus(running.statusState, {
|
|
747
|
+
snapshot: read.reason,
|
|
748
|
+
snapshotError: read.error,
|
|
749
|
+
}, observedAt);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function resolveInterruptTarget(params: { id?: string; name?: string }):
|
|
753
|
+
| { running: RunningSubagent }
|
|
754
|
+
| { error: string } {
|
|
755
|
+
const requestedId = params.id?.trim();
|
|
756
|
+
if (requestedId) {
|
|
757
|
+
const running = runningSubagents.get(requestedId);
|
|
758
|
+
return running ? { running } : { error: `No running subagent with id "${requestedId}".` };
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
const requestedName = params.name?.trim();
|
|
762
|
+
if (!requestedName) {
|
|
763
|
+
return { error: "Provide a running subagent id or exact display name." };
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
const matches = Array.from(runningSubagents.values()).filter((running) => running.name === requestedName);
|
|
767
|
+
if (matches.length === 1) return { running: matches[0] };
|
|
768
|
+
if (matches.length === 0) {
|
|
769
|
+
return { error: `No running subagent named "${requestedName}".` };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const candidates = matches.map((running) => `${running.name} [${running.id}]`).join(", ");
|
|
773
|
+
return { error: `Ambiguous subagent name "${requestedName}". Matches: ${candidates}` };
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
function requestSubagentInterrupt(
|
|
777
|
+
running: RunningSubagent,
|
|
778
|
+
interruptPaneKey: (surface: string) => void = interruptPane,
|
|
779
|
+
): { ok: true } | { error: string } {
|
|
780
|
+
try {
|
|
781
|
+
interruptPaneKey(running.surface);
|
|
782
|
+
return { ok: true };
|
|
783
|
+
} catch (error: any) {
|
|
784
|
+
return {
|
|
785
|
+
error:
|
|
786
|
+
`Failed to send Escape to subagent "${running.name}" via herdr: ` +
|
|
787
|
+
`${error?.message ?? String(error)}`,
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
function handleSubagentInterrupt(
|
|
793
|
+
params: { id?: string; name?: string },
|
|
794
|
+
interruptPaneKey: (surface: string) => void = interruptPane,
|
|
795
|
+
) {
|
|
796
|
+
const resolved = resolveInterruptTarget(params);
|
|
797
|
+
if ("error" in resolved) {
|
|
798
|
+
return {
|
|
799
|
+
content: [{ type: "text" as const, text: resolved.error }],
|
|
800
|
+
details: { error: resolved.error },
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
const running = resolved.running;
|
|
805
|
+
if (running.cli === "claude") {
|
|
806
|
+
return {
|
|
807
|
+
content: [{
|
|
808
|
+
type: "text" as const,
|
|
809
|
+
text:
|
|
810
|
+
"Turn-only Escape interrupt is currently supported only for Pi-backed subagents. Claude-backed semantics have not been verified yet.",
|
|
811
|
+
}],
|
|
812
|
+
details: { error: "claude interrupt unsupported", id: running.id, name: running.name },
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
const now = Date.now();
|
|
817
|
+
observeRunningSubagent(running, now);
|
|
818
|
+
|
|
819
|
+
const interruption = requestSubagentInterrupt(running, interruptPaneKey);
|
|
820
|
+
if ("error" in interruption) {
|
|
821
|
+
return {
|
|
822
|
+
content: [{ type: "text" as const, text: interruption.error }],
|
|
823
|
+
details: { error: interruption.error, id: running.id, name: running.name },
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
running.statusState = forceStatusAfterInterrupt(running.statusState, now);
|
|
828
|
+
updateWidget();
|
|
829
|
+
|
|
830
|
+
return {
|
|
831
|
+
content: [{ type: "text" as const, text: `Interrupt requested for subagent "${running.name}".` }],
|
|
832
|
+
details: { id: running.id, name: running.name, status: "interrupt_requested" },
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
function startStatusRefresh(pi: ExtensionAPI) {
|
|
837
|
+
if (!statusConfig.enabled || statusInterval) return;
|
|
838
|
+
|
|
839
|
+
statusInterval = setInterval(() => {
|
|
840
|
+
if (runningSubagents.size === 0) {
|
|
841
|
+
if (statusInterval) {
|
|
842
|
+
clearInterval(statusInterval);
|
|
843
|
+
statusInterval = null;
|
|
844
|
+
(globalThis as any)[STATUS_INTERVAL_KEY] = null;
|
|
845
|
+
}
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
const transitionLines: string[] = [];
|
|
850
|
+
const now = Date.now();
|
|
851
|
+
let shouldRefreshWidget = false;
|
|
852
|
+
|
|
853
|
+
for (const running of runningSubagents.values()) {
|
|
854
|
+
observeRunningSubagent(running, now);
|
|
855
|
+
const { nextState, snapshot, transition } = advanceStatusState(running.statusState, now);
|
|
856
|
+
if (nextState.currentKind !== running.statusState.currentKind) {
|
|
857
|
+
shouldRefreshWidget = true;
|
|
858
|
+
}
|
|
859
|
+
running.statusState = nextState;
|
|
860
|
+
|
|
861
|
+
// Interactive subagents (long-running, user-driven) intentionally don't
|
|
862
|
+
// wake the parent session on stalled/recovered transitions — the user is
|
|
863
|
+
// working in the subagent's pane, and a steer message here would burn an
|
|
864
|
+
// orchestrator turn on a no-op "still waiting" ping. Widget still updates.
|
|
865
|
+
if (transition && !running.interactive) {
|
|
866
|
+
transitionLines.push(formatTransitionLine(running.name, snapshot, transition));
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
if (shouldRefreshWidget) updateWidget();
|
|
871
|
+
|
|
872
|
+
if (transitionLines.length > 0) {
|
|
873
|
+
const capped = capStatusLines(transitionLines, statusConfig.lineLimit);
|
|
874
|
+
pi.sendMessage(
|
|
875
|
+
{
|
|
876
|
+
customType: "subagent_status",
|
|
877
|
+
content: formatStatusAggregate(transitionLines, statusConfig.lineLimit),
|
|
878
|
+
display: true,
|
|
879
|
+
details: { lines: capped.visibleLines, overflow: capped.overflow },
|
|
880
|
+
},
|
|
881
|
+
{ triggerTurn: true, deliverAs: "steer" },
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
}, 1000);
|
|
885
|
+
|
|
886
|
+
(globalThis as any)[STATUS_INTERVAL_KEY] = statusInterval;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
function resolveResumeLaunchBehavior(params: { autoExit?: boolean }): { autoExit: boolean; interactive: boolean } {
|
|
890
|
+
const autoExit = params.autoExit ?? true;
|
|
891
|
+
return { autoExit, interactive: !autoExit };
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
export const __test__ = {
|
|
895
|
+
borderLine,
|
|
896
|
+
getShellReadyDelayMs,
|
|
897
|
+
renderSubagentWidgetLines,
|
|
898
|
+
loadAgentDefaults,
|
|
899
|
+
discoverAgentDefinitions,
|
|
900
|
+
resolveEffectiveSessionMode,
|
|
901
|
+
resolveLaunchBehavior,
|
|
902
|
+
resolveEffectiveInteractive,
|
|
903
|
+
buildSubagentToolAllowlist,
|
|
904
|
+
buildPiPromptArgs,
|
|
905
|
+
formatWidgetRightLabel,
|
|
906
|
+
observeRunningSubagent,
|
|
907
|
+
resolveDenyTools,
|
|
908
|
+
resolveInterruptTarget,
|
|
909
|
+
requestSubagentInterrupt,
|
|
910
|
+
handleSubagentInterrupt,
|
|
911
|
+
resolveResultPresentation,
|
|
912
|
+
resolveResumeLaunchBehavior,
|
|
913
|
+
runningSubagents,
|
|
914
|
+
formatElapsed,
|
|
915
|
+
};
|
|
916
|
+
|
|
917
|
+
function startWidgetRefresh() {
|
|
918
|
+
if (widgetInterval) return;
|
|
919
|
+
updateWidget(); // immediate first render
|
|
920
|
+
widgetInterval = setInterval(() => {
|
|
921
|
+
updateWidget();
|
|
922
|
+
}, 1000);
|
|
923
|
+
(globalThis as any)[WIDGET_INTERVAL_KEY] = widgetInterval;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* Launch a subagent: creates the herdr pane, builds the command, and
|
|
928
|
+
* sends it. Returns a RunningSubagent — does NOT poll.
|
|
929
|
+
*
|
|
930
|
+
* Call watchSubagent() on the returned object to observe completion.
|
|
931
|
+
*/
|
|
932
|
+
async function launchSubagent(
|
|
933
|
+
params: typeof SubagentParams.static,
|
|
934
|
+
ctx: { sessionManager: { getSessionFile(): string | null; getSessionId(): string; getSessionDir(): string }; cwd: string },
|
|
935
|
+
options?: { surface?: string },
|
|
936
|
+
): Promise<RunningSubagent> {
|
|
937
|
+
const startTime = Date.now();
|
|
938
|
+
const id = Math.random().toString(16).slice(2, 10);
|
|
939
|
+
|
|
940
|
+
const agentDefs = params.agent ? loadAgentDefaults(params.agent) : null;
|
|
941
|
+
const effectiveModel = params.model ?? agentDefs?.model;
|
|
942
|
+
const effectiveTools = params.tools ?? agentDefs?.tools;
|
|
943
|
+
const effectiveSkills = params.skills ?? agentDefs?.skills;
|
|
944
|
+
const effectiveThinking = agentDefs?.thinking;
|
|
945
|
+
const effectiveInteractive = resolveEffectiveInteractive(params, agentDefs);
|
|
946
|
+
|
|
947
|
+
const sessionFile = ctx.sessionManager.getSessionFile();
|
|
948
|
+
if (!sessionFile) throw new Error("No session file");
|
|
949
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
950
|
+
const artifactDir = getArtifactDir(ctx.sessionManager.getSessionDir(), sessionId);
|
|
951
|
+
|
|
952
|
+
const { effectiveCwd, localAgentDir, effectiveAgentDir } = resolveSubagentPaths(params, agentDefs);
|
|
953
|
+
const targetCwdForSession = effectiveCwd ?? ctx.cwd;
|
|
954
|
+
const sessionDir = getDefaultSessionDirFor(targetCwdForSession, effectiveAgentDir);
|
|
955
|
+
|
|
956
|
+
// Generate a deterministic session file path for this subagent.
|
|
957
|
+
// This eliminates race conditions when multiple agents launch simultaneously —
|
|
958
|
+
// each agent knows exactly which file is theirs.
|
|
959
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 23) + "Z";
|
|
960
|
+
const uuid = [
|
|
961
|
+
id,
|
|
962
|
+
Math.random().toString(16).slice(2, 10),
|
|
963
|
+
Math.random().toString(16).slice(2, 10),
|
|
964
|
+
Math.random().toString(16).slice(2, 6),
|
|
965
|
+
].join("-");
|
|
966
|
+
const subagentSessionFile = join(sessionDir, `${timestamp}_${uuid}.jsonl`);
|
|
967
|
+
|
|
968
|
+
// Use pre-created surface (parallel mode) or create a new one.
|
|
969
|
+
// For new surfaces, pause briefly so the shell is ready before sending the command.
|
|
970
|
+
const surfacePreCreated = !!options?.surface;
|
|
971
|
+
const surface = options?.surface ?? createSubagentPane(params.name);
|
|
972
|
+
if (!surfacePreCreated) {
|
|
973
|
+
await new Promise<void>((resolve) => setTimeout(resolve, getShellReadyDelayMs()));
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
const launchBehavior = resolveLaunchBehavior(params, agentDefs);
|
|
977
|
+
|
|
978
|
+
if (launchBehavior.seededSessionMode) {
|
|
979
|
+
seedSubagentSessionFile({
|
|
980
|
+
mode: launchBehavior.seededSessionMode,
|
|
981
|
+
parentSessionFile: sessionFile,
|
|
982
|
+
childSessionFile: subagentSessionFile,
|
|
983
|
+
childCwd: targetCwdForSession,
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
const activityFile = getSubagentActivityFile(artifactDir, id);
|
|
988
|
+
mkdirSync(dirname(activityFile), { recursive: true });
|
|
989
|
+
const { inheritsConversationContext } = launchBehavior;
|
|
990
|
+
|
|
991
|
+
// Build the task message
|
|
992
|
+
// Only full-context fork mode inherits prior conversation state.
|
|
993
|
+
// Blank-session modes need the wrapper instructions and artifact-backed handoff.
|
|
994
|
+
const modeHint = agentDefs?.autoExit
|
|
995
|
+
? "Complete your task autonomously."
|
|
996
|
+
: "Complete your task. When finished, call the subagent_done tool. The user can interact with you at any time.";
|
|
997
|
+
const summaryInstruction = agentDefs?.autoExit
|
|
998
|
+
? "Your FINAL assistant message should summarize what you accomplished."
|
|
999
|
+
: "Your FINAL assistant message (before calling subagent_done or before the user exits) should summarize what you accomplished.";
|
|
1000
|
+
const denySet = resolveDenyTools(agentDefs);
|
|
1001
|
+
const identity = agentDefs?.body ?? params.systemPrompt ?? null;
|
|
1002
|
+
const systemPromptMode = agentDefs?.systemPromptMode;
|
|
1003
|
+
const identityInSystemPrompt = systemPromptMode && identity;
|
|
1004
|
+
const roleBlock = identity && !identityInSystemPrompt ? `\n\n${identity}` : "";
|
|
1005
|
+
const fullTask = inheritsConversationContext
|
|
1006
|
+
? params.task
|
|
1007
|
+
: `${roleBlock}\n\n${modeHint}\n\n${params.task}\n\n${summaryInstruction}`;
|
|
1008
|
+
// ── Claude Code CLI path ──
|
|
1009
|
+
if (agentDefs?.cli === "claude") {
|
|
1010
|
+
const sentinelFile = `/tmp/pi-claude-${id}-done`;
|
|
1011
|
+
const pluginDir = join(SUBAGENTS_DIR, "plugin");
|
|
1012
|
+
|
|
1013
|
+
const cmdParts: string[] = [];
|
|
1014
|
+
cmdParts.push(`PI_CLAUDE_SENTINEL=${shellQuote(sentinelFile)}`);
|
|
1015
|
+
cmdParts.push("claude");
|
|
1016
|
+
cmdParts.push("--dangerously-skip-permissions");
|
|
1017
|
+
|
|
1018
|
+
if (existsSync(pluginDir)) {
|
|
1019
|
+
cmdParts.push("--plugin-dir", shellQuote(pluginDir));
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
if (effectiveModel) {
|
|
1023
|
+
cmdParts.push("--model", shellQuote(effectiveModel));
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
const sp = params.systemPrompt ?? agentDefs.body;
|
|
1027
|
+
if (sp) {
|
|
1028
|
+
cmdParts.push("--append-system-prompt", shellQuote(sp));
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
if (params.resumeSessionId) {
|
|
1032
|
+
cmdParts.push("--resume", shellQuote(params.resumeSessionId));
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
// Always pass the task as the prompt — even for resumed sessions,
|
|
1036
|
+
// the caller's task is the follow-up instruction.
|
|
1037
|
+
cmdParts.push(shellQuote(params.task));
|
|
1038
|
+
|
|
1039
|
+
const cdPrefix = effectiveCwd ? `cd ${shellQuote(effectiveCwd)} && ` : "";
|
|
1040
|
+
const command = `${cdPrefix}${cmdParts.join(" ")}; echo '__SUBAGENT_DONE_'$?'__'`;
|
|
1041
|
+
|
|
1042
|
+
const launchScriptName = `${(params.name || "subagent")
|
|
1043
|
+
.toLowerCase()
|
|
1044
|
+
.replace(/[^a-z0-9\s-]/g, "")
|
|
1045
|
+
.replace(/\s+/g, "-")
|
|
1046
|
+
.replace(/-+/g, "-")
|
|
1047
|
+
.replace(/^-|-$/g, "") || "subagent"}-${id}.sh`;
|
|
1048
|
+
const launchScriptFile = join(artifactDir, "subagent-scripts", launchScriptName);
|
|
1049
|
+
|
|
1050
|
+
runScriptInPane(surface, command, {
|
|
1051
|
+
scriptPath: launchScriptFile,
|
|
1052
|
+
scriptPreamble: [
|
|
1053
|
+
`# Claude Code subagent launch script for ${params.name}`,
|
|
1054
|
+
`# Generated: ${new Date().toISOString()}`,
|
|
1055
|
+
`# Surface: ${surface}`,
|
|
1056
|
+
].join("\n"),
|
|
1057
|
+
});
|
|
1058
|
+
|
|
1059
|
+
const running: RunningSubagent = {
|
|
1060
|
+
id,
|
|
1061
|
+
name: params.name,
|
|
1062
|
+
task: params.task,
|
|
1063
|
+
agent: params.agent,
|
|
1064
|
+
surface,
|
|
1065
|
+
startTime,
|
|
1066
|
+
sessionFile: subagentSessionFile,
|
|
1067
|
+
launchScriptFile,
|
|
1068
|
+
cli: "claude",
|
|
1069
|
+
sentinelFile,
|
|
1070
|
+
interactive: effectiveInteractive,
|
|
1071
|
+
statusState: createStatusState({
|
|
1072
|
+
source: "claude",
|
|
1073
|
+
startTimeMs: startTime,
|
|
1074
|
+
}),
|
|
1075
|
+
};
|
|
1076
|
+
|
|
1077
|
+
runningSubagents.set(id, running);
|
|
1078
|
+
return running;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// ── Pi CLI path ──
|
|
1082
|
+
|
|
1083
|
+
// Build pi command
|
|
1084
|
+
const parts: string[] = ["pi"];
|
|
1085
|
+
parts.push("--session", shellQuote(subagentSessionFile));
|
|
1086
|
+
|
|
1087
|
+
const subagentDonePath = join(SUBAGENTS_DIR, "subagent-done.ts");
|
|
1088
|
+
parts.push("-e", shellQuote(subagentDonePath));
|
|
1089
|
+
|
|
1090
|
+
if (effectiveModel) {
|
|
1091
|
+
const model = effectiveThinking ? `${effectiveModel}:${effectiveThinking}` : effectiveModel;
|
|
1092
|
+
parts.push("--model", shellQuote(model));
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
// Pass agent body as system prompt via file to avoid shell escaping issues
|
|
1096
|
+
// with multiline content. Pi's --append-system-prompt and --system-prompt
|
|
1097
|
+
// auto-detect file paths and read their contents.
|
|
1098
|
+
if (identityInSystemPrompt && identity) {
|
|
1099
|
+
const flag = systemPromptMode === "replace" ? "--system-prompt" : "--append-system-prompt";
|
|
1100
|
+
const spTimestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
1101
|
+
const spSafeName = params.name
|
|
1102
|
+
.toLowerCase()
|
|
1103
|
+
.replace(/[^a-z0-9\s-]/g, "")
|
|
1104
|
+
.replace(/\s+/g, "-")
|
|
1105
|
+
.replace(/-+/g, "-")
|
|
1106
|
+
.replace(/^-|-$/g, "");
|
|
1107
|
+
const syspromptPath = join(artifactDir, `context/${spSafeName || "subagent"}-sysprompt-${spTimestamp}.md`);
|
|
1108
|
+
mkdirSync(dirname(syspromptPath), { recursive: true });
|
|
1109
|
+
writeFileSync(syspromptPath, identity, "utf8");
|
|
1110
|
+
parts.push(flag, shellQuote(syspromptPath));
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
const toolAllowlist = buildSubagentToolAllowlist(effectiveTools);
|
|
1114
|
+
if (toolAllowlist) {
|
|
1115
|
+
parts.push("--tools", shellQuote(toolAllowlist));
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
// Build env prefix: denied tools + subagent identity + config dir propagation
|
|
1119
|
+
const envParts: string[] = [];
|
|
1120
|
+
|
|
1121
|
+
// If the target cwd has its own .pi/agent/, use that as the config root.
|
|
1122
|
+
// Otherwise propagate the current/global agent dir.
|
|
1123
|
+
if (localAgentDir && existsSync(localAgentDir)) {
|
|
1124
|
+
envParts.push(`PI_CODING_AGENT_DIR=${shellQuote(localAgentDir)}`);
|
|
1125
|
+
} else if (process.env.PI_CODING_AGENT_DIR) {
|
|
1126
|
+
envParts.push(`PI_CODING_AGENT_DIR=${shellQuote(process.env.PI_CODING_AGENT_DIR)}`);
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
if (denySet.size > 0) {
|
|
1130
|
+
envParts.push(`PI_DENY_TOOLS=${shellQuote([...denySet].join(","))}`);
|
|
1131
|
+
}
|
|
1132
|
+
envParts.push(`PI_SUBAGENT_NAME=${shellQuote(params.name)}`);
|
|
1133
|
+
if (params.agent) {
|
|
1134
|
+
envParts.push(`PI_SUBAGENT_AGENT=${shellQuote(params.agent)}`);
|
|
1135
|
+
}
|
|
1136
|
+
if (agentDefs?.autoExit) {
|
|
1137
|
+
envParts.push(`PI_SUBAGENT_AUTO_EXIT=1`);
|
|
1138
|
+
}
|
|
1139
|
+
envParts.push(`PI_SUBAGENT_SESSION=${shellQuote(subagentSessionFile)}`);
|
|
1140
|
+
envParts.push(`PI_SUBAGENT_ID=${shellQuote(id)}`);
|
|
1141
|
+
envParts.push(`PI_SUBAGENT_ACTIVITY_FILE=${shellQuote(activityFile)}`);
|
|
1142
|
+
envParts.push(`PI_SUBAGENT_SURFACE=${shellQuote(surface)}`);
|
|
1143
|
+
const envPrefix = envParts.join(" ") + " ";
|
|
1144
|
+
|
|
1145
|
+
// Pass task and skill prompts to the sub-agent.
|
|
1146
|
+
// Only full-context fork mode gets a direct task argument because it already
|
|
1147
|
+
// inherits the parent conversation. Blank-session modes use artifact-backed
|
|
1148
|
+
// handoff so the wrapper instructions arrive as the initial user message.
|
|
1149
|
+
let taskArg: string;
|
|
1150
|
+
if (launchBehavior.taskDelivery === "direct") {
|
|
1151
|
+
taskArg = fullTask;
|
|
1152
|
+
} else {
|
|
1153
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
1154
|
+
const safeName = params.name
|
|
1155
|
+
.toLowerCase()
|
|
1156
|
+
.replace(/[^a-z0-9\s-]/g, "") // strip everything except alphanumeric, spaces, hyphens
|
|
1157
|
+
.replace(/\s+/g, "-") // spaces to hyphens
|
|
1158
|
+
.replace(/-+/g, "-") // collapse multiple hyphens
|
|
1159
|
+
.replace(/^-|-$/g, ""); // trim leading/trailing hyphens
|
|
1160
|
+
const artifactName = `context/${safeName || "subagent"}-${timestamp}.md`;
|
|
1161
|
+
const artifactPath = join(artifactDir, artifactName);
|
|
1162
|
+
mkdirSync(dirname(artifactPath), { recursive: true });
|
|
1163
|
+
writeFileSync(artifactPath, fullTask, "utf8");
|
|
1164
|
+
taskArg = `@${artifactPath}`;
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
for (const promptArg of buildPiPromptArgs({
|
|
1168
|
+
effectiveSkills,
|
|
1169
|
+
taskDelivery: launchBehavior.taskDelivery,
|
|
1170
|
+
taskArg,
|
|
1171
|
+
})) {
|
|
1172
|
+
parts.push(shellQuote(promptArg));
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
// Resolve cwd — param overrides agent default, supports absolute and relative paths.
|
|
1176
|
+
// This was already computed above so session placement, PI_CODING_AGENT_DIR, and cd agree.
|
|
1177
|
+
const cdPrefix = effectiveCwd ? `cd ${shellQuote(effectiveCwd)} && ` : "";
|
|
1178
|
+
|
|
1179
|
+
const piCommand = cdPrefix + envPrefix + parts.join(" ");
|
|
1180
|
+
const command = `${piCommand}; echo '__SUBAGENT_DONE_'$?'__'`;
|
|
1181
|
+
const launchScriptName = `${(params.name || "subagent")
|
|
1182
|
+
.toLowerCase()
|
|
1183
|
+
.replace(/[^a-z0-9\s-]/g, "")
|
|
1184
|
+
.replace(/\s+/g, "-")
|
|
1185
|
+
.replace(/-+/g, "-")
|
|
1186
|
+
.replace(/^-|-$/g, "") || "subagent"}-${id}.sh`;
|
|
1187
|
+
const launchScriptFile = join(artifactDir, "subagent-scripts", launchScriptName);
|
|
1188
|
+
runScriptInPane(surface, command, {
|
|
1189
|
+
scriptPath: launchScriptFile,
|
|
1190
|
+
scriptPreamble: [
|
|
1191
|
+
`# Subagent launch script for ${params.name}`,
|
|
1192
|
+
`# Generated: ${new Date().toISOString()}`,
|
|
1193
|
+
`# Session: ${subagentSessionFile}`,
|
|
1194
|
+
`# Surface: ${surface}`,
|
|
1195
|
+
].join("\n"),
|
|
1196
|
+
});
|
|
1197
|
+
|
|
1198
|
+
const running: RunningSubagent = {
|
|
1199
|
+
id,
|
|
1200
|
+
name: params.name,
|
|
1201
|
+
task: params.task,
|
|
1202
|
+
agent: params.agent,
|
|
1203
|
+
surface,
|
|
1204
|
+
startTime,
|
|
1205
|
+
sessionFile: subagentSessionFile,
|
|
1206
|
+
launchScriptFile,
|
|
1207
|
+
activityFile,
|
|
1208
|
+
interactive: effectiveInteractive,
|
|
1209
|
+
statusState: createStatusState({
|
|
1210
|
+
source: "pi",
|
|
1211
|
+
startTimeMs: startTime,
|
|
1212
|
+
}),
|
|
1213
|
+
};
|
|
1214
|
+
|
|
1215
|
+
runningSubagents.set(id, running);
|
|
1216
|
+
return running;
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
/**
|
|
1220
|
+
* Watch a launched subagent until it exits. Polls for completion, extracts
|
|
1221
|
+
* the summary from the session file, cleans up the surface,
|
|
1222
|
+
* and removes the entry from runningSubagents.
|
|
1223
|
+
*/
|
|
1224
|
+
const CLAUDE_SESSIONS_DIR = join(
|
|
1225
|
+
process.env.HOME ?? "/tmp",
|
|
1226
|
+
".pi", "agent", "sessions", "claude-code",
|
|
1227
|
+
);
|
|
1228
|
+
|
|
1229
|
+
function copyClaudeSession(sentinelFile: string): string | null {
|
|
1230
|
+
try {
|
|
1231
|
+
const transcriptFile = sentinelFile + ".transcript";
|
|
1232
|
+
if (!existsSync(transcriptFile)) return null;
|
|
1233
|
+
const transcriptPath = readFileSync(transcriptFile, "utf-8").trim();
|
|
1234
|
+
if (!transcriptPath || !existsSync(transcriptPath)) return null;
|
|
1235
|
+
mkdirSync(CLAUDE_SESSIONS_DIR, { recursive: true });
|
|
1236
|
+
const filename = transcriptPath.split("/").pop() ?? `claude-${Date.now()}.jsonl`;
|
|
1237
|
+
const dest = join(CLAUDE_SESSIONS_DIR, filename);
|
|
1238
|
+
copyFileSync(transcriptPath, dest);
|
|
1239
|
+
return filename;
|
|
1240
|
+
} catch {
|
|
1241
|
+
return null;
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
async function watchSubagent(
|
|
1246
|
+
running: RunningSubagent,
|
|
1247
|
+
signal: AbortSignal,
|
|
1248
|
+
): Promise<SubagentResult> {
|
|
1249
|
+
const { name, task, surface, startTime, sessionFile } = running;
|
|
1250
|
+
|
|
1251
|
+
try {
|
|
1252
|
+
const result = await waitForCompletion(AbortSignal.any([signal, getModuleAbortSignal()]), {
|
|
1253
|
+
intervalMs: 1000,
|
|
1254
|
+
sessionFile,
|
|
1255
|
+
sentinelFile: running.sentinelFile,
|
|
1256
|
+
readTerminalTail: () => readPaneAsync(surface, 5),
|
|
1257
|
+
onTick() {
|
|
1258
|
+
observeRunningSubagent(running);
|
|
1259
|
+
},
|
|
1260
|
+
});
|
|
1261
|
+
|
|
1262
|
+
const elapsed = Math.floor((Date.now() - startTime) / 1000);
|
|
1263
|
+
|
|
1264
|
+
if (running.cli === "claude") {
|
|
1265
|
+
// Claude Code result extraction
|
|
1266
|
+
let summary = "";
|
|
1267
|
+
|
|
1268
|
+
if (running.sentinelFile) {
|
|
1269
|
+
try {
|
|
1270
|
+
summary = readFileSync(running.sentinelFile, "utf-8").trim();
|
|
1271
|
+
} catch {}
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
if (!summary) {
|
|
1275
|
+
summary = readPane(surface, 200)
|
|
1276
|
+
.replace(/__SUBAGENT_DONE_\d+__/, "")
|
|
1277
|
+
.trimEnd();
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
if (!summary) {
|
|
1281
|
+
summary = result.exitCode !== 0
|
|
1282
|
+
? `Claude Code exited with code ${result.exitCode}`
|
|
1283
|
+
: "Claude Code exited without output";
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// Copy Claude session transcript
|
|
1287
|
+
let sessionId: string | null = null;
|
|
1288
|
+
if (running.sentinelFile) {
|
|
1289
|
+
sessionId = copyClaudeSession(running.sentinelFile);
|
|
1290
|
+
try { unlinkSync(running.sentinelFile); } catch {}
|
|
1291
|
+
try { unlinkSync(running.sentinelFile + ".transcript"); } catch {}
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
closePane(surface);
|
|
1295
|
+
runningSubagents.delete(running.id);
|
|
1296
|
+
|
|
1297
|
+
return { name, task, summary, exitCode: result.exitCode, elapsed, ...(sessionId ? { claudeSessionId: sessionId } : {}) };
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
// Pi subagent result extraction
|
|
1301
|
+
let summary: string;
|
|
1302
|
+
if (existsSync(sessionFile)) {
|
|
1303
|
+
const allEntries = getNewEntries(sessionFile, 0);
|
|
1304
|
+
summary =
|
|
1305
|
+
findLastAssistantMessage(allEntries) ??
|
|
1306
|
+
(result.errorMessage
|
|
1307
|
+
? `Subagent error: ${result.errorMessage}`
|
|
1308
|
+
: result.exitCode !== 0
|
|
1309
|
+
? `Sub-agent exited with code ${result.exitCode}`
|
|
1310
|
+
: "Sub-agent exited without output");
|
|
1311
|
+
} else {
|
|
1312
|
+
summary = result.errorMessage
|
|
1313
|
+
? `Subagent error: ${result.errorMessage}`
|
|
1314
|
+
: result.exitCode !== 0
|
|
1315
|
+
? `Sub-agent exited with code ${result.exitCode}`
|
|
1316
|
+
: "Sub-agent exited without output";
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
closePane(surface);
|
|
1320
|
+
runningSubagents.delete(running.id);
|
|
1321
|
+
|
|
1322
|
+
return {
|
|
1323
|
+
name,
|
|
1324
|
+
task,
|
|
1325
|
+
summary,
|
|
1326
|
+
sessionFile,
|
|
1327
|
+
exitCode: result.exitCode,
|
|
1328
|
+
elapsed,
|
|
1329
|
+
ping: result.ping,
|
|
1330
|
+
...(result.errorMessage ? { errorMessage: result.errorMessage } : {}),
|
|
1331
|
+
};
|
|
1332
|
+
} catch (err: any) {
|
|
1333
|
+
try {
|
|
1334
|
+
closePane(surface);
|
|
1335
|
+
} catch {}
|
|
1336
|
+
runningSubagents.delete(running.id);
|
|
1337
|
+
|
|
1338
|
+
if (signal.aborted) {
|
|
1339
|
+
return {
|
|
1340
|
+
name,
|
|
1341
|
+
task,
|
|
1342
|
+
summary: "Subagent cancelled.",
|
|
1343
|
+
exitCode: 1,
|
|
1344
|
+
elapsed: Math.floor((Date.now() - startTime) / 1000),
|
|
1345
|
+
error: "cancelled",
|
|
1346
|
+
sessionFile,
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
return {
|
|
1350
|
+
name,
|
|
1351
|
+
task,
|
|
1352
|
+
summary: `Subagent error: ${err?.message ?? String(err)}`,
|
|
1353
|
+
exitCode: 1,
|
|
1354
|
+
elapsed: Math.floor((Date.now() - startTime) / 1000),
|
|
1355
|
+
error: err?.message ?? String(err),
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
export default function subagentsExtension(pi: ExtensionAPI) {
|
|
1361
|
+
// Capture the UI context for widget updates
|
|
1362
|
+
pi.on("session_start", (_event, ctx) => {
|
|
1363
|
+
latestCtx = ctx;
|
|
1364
|
+
});
|
|
1365
|
+
|
|
1366
|
+
// Clean up on session shutdown
|
|
1367
|
+
pi.on("session_shutdown", (_event, _ctx) => {
|
|
1368
|
+
if (widgetInterval) {
|
|
1369
|
+
clearInterval(widgetInterval);
|
|
1370
|
+
widgetInterval = null;
|
|
1371
|
+
(globalThis as any)[WIDGET_INTERVAL_KEY] = null;
|
|
1372
|
+
}
|
|
1373
|
+
if (statusInterval) {
|
|
1374
|
+
clearInterval(statusInterval);
|
|
1375
|
+
statusInterval = null;
|
|
1376
|
+
(globalThis as any)[STATUS_INTERVAL_KEY] = null;
|
|
1377
|
+
}
|
|
1378
|
+
const moduleAbort = (globalThis as any)[POLL_ABORT_KEY] as AbortController | undefined;
|
|
1379
|
+
if (moduleAbort) moduleAbort.abort();
|
|
1380
|
+
for (const [_id, agent] of runningSubagents) {
|
|
1381
|
+
agent.abortController?.abort();
|
|
1382
|
+
}
|
|
1383
|
+
runningSubagents.clear();
|
|
1384
|
+
});
|
|
1385
|
+
|
|
1386
|
+
// Tools denied via PI_DENY_TOOLS env var (set by parent agent based on frontmatter)
|
|
1387
|
+
const deniedTools = new Set(
|
|
1388
|
+
(process.env.PI_DENY_TOOLS ?? "")
|
|
1389
|
+
.split(",")
|
|
1390
|
+
.map((s) => s.trim())
|
|
1391
|
+
.filter(Boolean),
|
|
1392
|
+
);
|
|
1393
|
+
|
|
1394
|
+
const shouldRegister = (name: string) => !deniedTools.has(name);
|
|
1395
|
+
|
|
1396
|
+
// ── subagent tool ──
|
|
1397
|
+
if (shouldRegister("subagent"))
|
|
1398
|
+
pi.registerTool({
|
|
1399
|
+
name: "subagent",
|
|
1400
|
+
label: "Subagent",
|
|
1401
|
+
description:
|
|
1402
|
+
"Spawn a sub-agent in a dedicated terminal herdr pane. " +
|
|
1403
|
+
"This is a fire-and-forget async tool: the call returns immediately with only an acknowledgement. " +
|
|
1404
|
+
"When the sub-agent finishes, the harness AUTOMATICALLY delivers its result as a steer message that wakes you up and starts a new turn — you do not need to do anything to receive it. " +
|
|
1405
|
+
"DO NOT write polling loops, sleep/wait commands, tail/watch scripts, or repeatedly read session/log files to detect completion. DO NOT call subagents_list or any other tool to 'check' status. All of that is wasted work — the harness handles delivery for you. " +
|
|
1406
|
+
"DO NOT fabricate, assume, or summarize results after calling this tool. " +
|
|
1407
|
+
"After spawning, either end your turn immediately, or work on other independent tasks (including spawning more subagents in parallel). The harness will wake you with the result when it is ready.",
|
|
1408
|
+
promptSnippet:
|
|
1409
|
+
"Spawn a sub-agent in a dedicated terminal herdr pane. " +
|
|
1410
|
+
"This is a fire-and-forget async tool: the call returns immediately with only an acknowledgement. " +
|
|
1411
|
+
"When the sub-agent finishes, the harness AUTOMATICALLY delivers its result as a steer message that wakes you up and starts a new turn — you do not need to do anything to receive it. " +
|
|
1412
|
+
"DO NOT write polling loops, sleep/wait commands, tail/watch scripts, or repeatedly read session/log files to detect completion. DO NOT call subagents_list or any other tool to 'check' status. All of that is wasted work — the harness handles delivery for you. " +
|
|
1413
|
+
"DO NOT fabricate, assume, or summarize results after calling this tool. " +
|
|
1414
|
+
"After spawning, either end your turn immediately, or work on other independent tasks (including spawning more subagents in parallel). The harness will wake you with the result when it is ready.",
|
|
1415
|
+
parameters: SubagentParams,
|
|
1416
|
+
|
|
1417
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1418
|
+
// Prevent self-spawning (e.g. planner spawning another planner)
|
|
1419
|
+
const currentAgent = process.env.PI_SUBAGENT_AGENT;
|
|
1420
|
+
if (params.agent && currentAgent && params.agent === currentAgent) {
|
|
1421
|
+
return {
|
|
1422
|
+
content: [
|
|
1423
|
+
{
|
|
1424
|
+
type: "text",
|
|
1425
|
+
text: `You are the ${currentAgent} agent — do not start another ${currentAgent}. You were spawned to do this work yourself. Complete the task directly.`,
|
|
1426
|
+
},
|
|
1427
|
+
],
|
|
1428
|
+
details: { error: "self-spawn blocked" },
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
// Validate prerequisites
|
|
1433
|
+
if (!isTerminalAvailable()) {
|
|
1434
|
+
return muxUnavailableResult();
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
if (!ctx.sessionManager.getSessionFile()) {
|
|
1438
|
+
return {
|
|
1439
|
+
content: [
|
|
1440
|
+
{
|
|
1441
|
+
type: "text",
|
|
1442
|
+
text: "Error: no session file. Start pi with a persistent session to use subagents.",
|
|
1443
|
+
},
|
|
1444
|
+
],
|
|
1445
|
+
details: { error: "no session file" },
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
// Launch the subagent (creates pane, sends command)
|
|
1450
|
+
const running = await launchSubagent(params, ctx);
|
|
1451
|
+
|
|
1452
|
+
// Create a separate AbortController for the watcher
|
|
1453
|
+
// (the tool's signal completes when we return)
|
|
1454
|
+
const watcherAbort = new AbortController();
|
|
1455
|
+
running.abortController = watcherAbort;
|
|
1456
|
+
|
|
1457
|
+
// Start widget refresh and status supervision when the first agent launches
|
|
1458
|
+
startWidgetRefresh();
|
|
1459
|
+
startStatusRefresh(pi);
|
|
1460
|
+
|
|
1461
|
+
// Fire-and-forget: start watching in background
|
|
1462
|
+
watchSubagent(running, watcherAbort.signal)
|
|
1463
|
+
.then((result) => {
|
|
1464
|
+
updateWidget(); // reflect removal from Map immediately
|
|
1465
|
+
|
|
1466
|
+
if (result.ping) {
|
|
1467
|
+
// Subagent is requesting help — steer a ping message with session path for resume
|
|
1468
|
+
const sessionRef = `\n\nSession: ${result.sessionFile}\nResume: pi --session ${result.sessionFile}`;
|
|
1469
|
+
pi.sendMessage(
|
|
1470
|
+
{
|
|
1471
|
+
customType: "subagent_ping",
|
|
1472
|
+
content: `Sub-agent "${result.ping.name}" needs help (${formatElapsed(result.elapsed)}):\n\n${result.ping.message}${sessionRef}`,
|
|
1473
|
+
display: true,
|
|
1474
|
+
details: {
|
|
1475
|
+
name: result.ping.name,
|
|
1476
|
+
message: result.ping.message,
|
|
1477
|
+
agent: running.agent,
|
|
1478
|
+
sessionFile: result.sessionFile,
|
|
1479
|
+
},
|
|
1480
|
+
},
|
|
1481
|
+
{ triggerTurn: true, deliverAs: "steer" },
|
|
1482
|
+
);
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
const presentation = resolveResultPresentation(result, running.name);
|
|
1487
|
+
|
|
1488
|
+
pi.sendMessage(
|
|
1489
|
+
{
|
|
1490
|
+
customType: "subagent_result",
|
|
1491
|
+
content: presentation,
|
|
1492
|
+
display: true,
|
|
1493
|
+
details: {
|
|
1494
|
+
name: running.name,
|
|
1495
|
+
task: running.task,
|
|
1496
|
+
agent: running.agent,
|
|
1497
|
+
exitCode: result.exitCode,
|
|
1498
|
+
elapsed: result.elapsed,
|
|
1499
|
+
sessionFile: result.sessionFile,
|
|
1500
|
+
...(result.errorMessage ? { errorMessage: result.errorMessage } : {}),
|
|
1501
|
+
...(result.claudeSessionId ? { claudeSessionId: result.claudeSessionId } : {}),
|
|
1502
|
+
},
|
|
1503
|
+
},
|
|
1504
|
+
{ triggerTurn: true, deliverAs: "steer" },
|
|
1505
|
+
);
|
|
1506
|
+
})
|
|
1507
|
+
.catch((err) => {
|
|
1508
|
+
updateWidget();
|
|
1509
|
+
pi.sendMessage(
|
|
1510
|
+
{
|
|
1511
|
+
customType: "subagent_result",
|
|
1512
|
+
content: `Sub-agent "${running.name}" error: ${err?.message ?? String(err)}`,
|
|
1513
|
+
display: true,
|
|
1514
|
+
details: { name: running.name, task: running.task, error: err?.message },
|
|
1515
|
+
},
|
|
1516
|
+
{ triggerTurn: true, deliverAs: "steer" },
|
|
1517
|
+
);
|
|
1518
|
+
});
|
|
1519
|
+
|
|
1520
|
+
// Return immediately
|
|
1521
|
+
return {
|
|
1522
|
+
content: [
|
|
1523
|
+
{
|
|
1524
|
+
type: "text",
|
|
1525
|
+
text:
|
|
1526
|
+
`Sub-agent "${params.name}" launched and is now running in the background. ` +
|
|
1527
|
+
`Do NOT generate or assume any results — you have no idea what the sub-agent will do or produce. ` +
|
|
1528
|
+
`The results will be delivered to you automatically as a steer message when the sub-agent finishes. ` +
|
|
1529
|
+
`Until then, move on to other work or tell the user you're waiting.`,
|
|
1530
|
+
},
|
|
1531
|
+
],
|
|
1532
|
+
details: {
|
|
1533
|
+
id: running.id,
|
|
1534
|
+
name: params.name,
|
|
1535
|
+
task: params.task,
|
|
1536
|
+
agent: params.agent,
|
|
1537
|
+
sessionFile: running.sessionFile,
|
|
1538
|
+
launchScriptFile: running.launchScriptFile,
|
|
1539
|
+
status: "started",
|
|
1540
|
+
},
|
|
1541
|
+
};
|
|
1542
|
+
},
|
|
1543
|
+
|
|
1544
|
+
renderCall(args, theme) {
|
|
1545
|
+
const partialArgs = args as Record<string, unknown>;
|
|
1546
|
+
const name = typeof partialArgs.name === "string" && partialArgs.name ? partialArgs.name : "(unnamed)";
|
|
1547
|
+
const task = typeof partialArgs.task === "string" ? partialArgs.task : "";
|
|
1548
|
+
const agent = typeof partialArgs.agent === "string" && partialArgs.agent
|
|
1549
|
+
? theme.fg("dim", ` (${partialArgs.agent})`)
|
|
1550
|
+
: "";
|
|
1551
|
+
const cwdHint = typeof partialArgs.cwd === "string" && partialArgs.cwd
|
|
1552
|
+
? theme.fg("dim", ` in ${partialArgs.cwd}`)
|
|
1553
|
+
: "";
|
|
1554
|
+
let text =
|
|
1555
|
+
"▸ " +
|
|
1556
|
+
theme.fg("toolTitle", theme.bold(name)) +
|
|
1557
|
+
agent +
|
|
1558
|
+
cwdHint;
|
|
1559
|
+
|
|
1560
|
+
// Show a one-line task preview. renderCall is called repeatedly as the
|
|
1561
|
+
// LLM generates tool arguments, so args.task grows token by token.
|
|
1562
|
+
// We keep it compact here — Ctrl+O on renderResult expands the full content.
|
|
1563
|
+
if (task) {
|
|
1564
|
+
const firstLine = task.split("\n").find((l: string) => l.trim()) ?? "";
|
|
1565
|
+
const preview = firstLine.length > 100 ? firstLine.slice(0, 100) + "…" : firstLine;
|
|
1566
|
+
if (preview) {
|
|
1567
|
+
text += "\n" + theme.fg("toolOutput", preview);
|
|
1568
|
+
}
|
|
1569
|
+
const totalLines = task.split("\n").length;
|
|
1570
|
+
if (totalLines > 1) {
|
|
1571
|
+
text += theme.fg("muted", ` (${totalLines} lines)`);
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
return new Text(text, 0, 0);
|
|
1576
|
+
},
|
|
1577
|
+
|
|
1578
|
+
renderResult(result, _opts, theme) {
|
|
1579
|
+
const details = result.details as any;
|
|
1580
|
+
const name = details?.name ?? "(unnamed)";
|
|
1581
|
+
|
|
1582
|
+
// "Started" result — tool returned immediately
|
|
1583
|
+
if (details?.status === "started") {
|
|
1584
|
+
return new Text(
|
|
1585
|
+
theme.fg("accent", "▸") +
|
|
1586
|
+
" " +
|
|
1587
|
+
theme.fg("toolTitle", theme.bold(name)) +
|
|
1588
|
+
theme.fg("dim", " — started"),
|
|
1589
|
+
0,
|
|
1590
|
+
0,
|
|
1591
|
+
);
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
// Fallback (shouldn't happen)
|
|
1595
|
+
const text = typeof result.content[0]?.text === "string" ? result.content[0].text : "";
|
|
1596
|
+
return new Text(theme.fg("dim", text), 0, 0);
|
|
1597
|
+
},
|
|
1598
|
+
});
|
|
1599
|
+
|
|
1600
|
+
// ── subagent_interrupt tool ──
|
|
1601
|
+
if (shouldRegister("subagent_interrupt"))
|
|
1602
|
+
pi.registerTool({
|
|
1603
|
+
name: "subagent_interrupt",
|
|
1604
|
+
label: "Interrupt Subagent",
|
|
1605
|
+
description:
|
|
1606
|
+
"Send Escape to the active turn of a currently running Pi-backed subagent. " +
|
|
1607
|
+
"The child pane, session, watcher, and running entry remain alive; this returns only a local acknowledgement " +
|
|
1608
|
+
"and does not emit a subagent_result solely because of this request.",
|
|
1609
|
+
promptSnippet:
|
|
1610
|
+
"Send Escape to the active turn of a currently running Pi-backed subagent. " +
|
|
1611
|
+
"The child pane, session, watcher, and running entry remain alive; this returns only a local acknowledgement " +
|
|
1612
|
+
"and does not emit a subagent_result solely because of this request.",
|
|
1613
|
+
parameters: Type.Object({
|
|
1614
|
+
id: Type.Optional(Type.String({ description: "Exact running subagent id" })),
|
|
1615
|
+
name: Type.Optional(Type.String({ description: "Exact running subagent display name" })),
|
|
1616
|
+
}),
|
|
1617
|
+
|
|
1618
|
+
async execute(_toolCallId, params) {
|
|
1619
|
+
return handleSubagentInterrupt(params);
|
|
1620
|
+
},
|
|
1621
|
+
|
|
1622
|
+
renderCall(args, theme) {
|
|
1623
|
+
const target = args.id ? `${args.id}` : args.name ?? "(unknown)";
|
|
1624
|
+
return new Text(
|
|
1625
|
+
theme.fg("accent", "▸") +
|
|
1626
|
+
" " +
|
|
1627
|
+
theme.fg("toolTitle", theme.bold(target)) +
|
|
1628
|
+
theme.fg("dim", " — interrupt turn"),
|
|
1629
|
+
0,
|
|
1630
|
+
0,
|
|
1631
|
+
);
|
|
1632
|
+
},
|
|
1633
|
+
|
|
1634
|
+
renderResult(result, _opts, theme) {
|
|
1635
|
+
const details = result.details as any;
|
|
1636
|
+
if (details?.status === "interrupt_requested") {
|
|
1637
|
+
return new Text(
|
|
1638
|
+
theme.fg("accent", "▸") +
|
|
1639
|
+
" " +
|
|
1640
|
+
theme.fg("toolTitle", theme.bold(details.name ?? details.id ?? "subagent")) +
|
|
1641
|
+
theme.fg("dim", " — interrupt requested"),
|
|
1642
|
+
0,
|
|
1643
|
+
0,
|
|
1644
|
+
);
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
const text = typeof result.content[0]?.text === "string" ? result.content[0].text : "";
|
|
1648
|
+
return new Text(theme.fg("dim", text), 0, 0);
|
|
1649
|
+
},
|
|
1650
|
+
});
|
|
1651
|
+
|
|
1652
|
+
// ── subagents_list tool ──
|
|
1653
|
+
if (shouldRegister("subagents_list"))
|
|
1654
|
+
pi.registerTool({
|
|
1655
|
+
name: "subagents_list",
|
|
1656
|
+
label: "List Subagents",
|
|
1657
|
+
description:
|
|
1658
|
+
"List all available subagent definitions. " +
|
|
1659
|
+
"Scans project-local .pi/agents/ and global ~/.pi/agent/agents/. " +
|
|
1660
|
+
"Project-local agents override global ones with the same name.",
|
|
1661
|
+
promptSnippet:
|
|
1662
|
+
"List all available subagent definitions. " +
|
|
1663
|
+
"Scans project-local .pi/agents/ and global ~/.pi/agent/agents/. " +
|
|
1664
|
+
"Project-local agents override global ones with the same name.",
|
|
1665
|
+
parameters: Type.Object({}),
|
|
1666
|
+
|
|
1667
|
+
async execute() {
|
|
1668
|
+
const list = discoverAgentDefinitions().filter((agent) => !agent.disableModelInvocation);
|
|
1669
|
+
|
|
1670
|
+
if (list.length === 0) {
|
|
1671
|
+
return {
|
|
1672
|
+
content: [{ type: "text", text: "No subagent definitions found." }],
|
|
1673
|
+
details: { agents: [] },
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
const lines = list.map((a) => {
|
|
1678
|
+
const badge = a.source === "project" ? " (project)" : "";
|
|
1679
|
+
const desc = a.description ? ` — ${a.description}` : "";
|
|
1680
|
+
const model = a.model ? ` [${a.model}]` : "";
|
|
1681
|
+
return `• ${a.name}${badge}${model}${desc}`;
|
|
1682
|
+
});
|
|
1683
|
+
|
|
1684
|
+
return {
|
|
1685
|
+
content: [{ type: "text", text: lines.join("\n") }],
|
|
1686
|
+
details: { agents: list },
|
|
1687
|
+
};
|
|
1688
|
+
},
|
|
1689
|
+
|
|
1690
|
+
renderResult(result, _opts, theme) {
|
|
1691
|
+
const details = result.details as any;
|
|
1692
|
+
const agents = details?.agents ?? [];
|
|
1693
|
+
if (agents.length === 0) {
|
|
1694
|
+
return new Text(theme.fg("dim", "No subagent definitions found."), 0, 0);
|
|
1695
|
+
}
|
|
1696
|
+
const lines = agents.map((a: any) => {
|
|
1697
|
+
const badge = a.source === "project" ? theme.fg("accent", " (project)") : "";
|
|
1698
|
+
const desc = a.description ? theme.fg("dim", ` — ${a.description}`) : "";
|
|
1699
|
+
const model = a.model ? theme.fg("dim", ` [${a.model}]`) : "";
|
|
1700
|
+
return ` ${theme.fg("toolTitle", theme.bold(a.name))}${badge}${model}${desc}`;
|
|
1701
|
+
});
|
|
1702
|
+
return new Text(lines.join("\n"), 0, 0);
|
|
1703
|
+
},
|
|
1704
|
+
});
|
|
1705
|
+
|
|
1706
|
+
|
|
1707
|
+
|
|
1708
|
+
// ── subagent_resume tool ──
|
|
1709
|
+
if (shouldRegister("subagent_resume"))
|
|
1710
|
+
pi.registerTool({
|
|
1711
|
+
name: "subagent_resume",
|
|
1712
|
+
label: "Resume Subagent",
|
|
1713
|
+
description:
|
|
1714
|
+
"Resume a previous sub-agent session in a new herdr pane. " +
|
|
1715
|
+
"This is a fire-and-forget async tool: the call returns immediately with only an acknowledgement. " +
|
|
1716
|
+
"When the resumed sub-agent finishes, the harness AUTOMATICALLY delivers its result as a steer message that wakes you up and starts a new turn — you do not need to do anything to receive it. " +
|
|
1717
|
+
"DO NOT write polling loops, sleep/wait commands, tail/watch scripts, or repeatedly read session/log files to detect completion. DO NOT poll for status. All of that is wasted work — the harness handles delivery for you. " +
|
|
1718
|
+
"DO NOT fabricate or assume results. After resuming, either end your turn or work on other independent tasks; the harness will wake you when the result is ready. " +
|
|
1719
|
+
"Use when a sub-agent was cancelled or needs follow-up work.",
|
|
1720
|
+
promptSnippet:
|
|
1721
|
+
"Resume a previous sub-agent session in a new herdr pane. " +
|
|
1722
|
+
"This is a fire-and-forget async tool: the call returns immediately with only an acknowledgement. " +
|
|
1723
|
+
"When the resumed sub-agent finishes, the harness AUTOMATICALLY delivers its result as a steer message that wakes you up and starts a new turn — you do not need to do anything to receive it. " +
|
|
1724
|
+
"DO NOT write polling loops, sleep/wait commands, tail/watch scripts, or repeatedly read session/log files to detect completion. DO NOT poll for status. All of that is wasted work — the harness handles delivery for you. " +
|
|
1725
|
+
"DO NOT fabricate or assume results. After resuming, either end your turn or work on other independent tasks; the harness will wake you when the result is ready. " +
|
|
1726
|
+
"Use when a sub-agent was cancelled or needs follow-up work.",
|
|
1727
|
+
parameters: Type.Object({
|
|
1728
|
+
sessionPath: Type.String({ description: "Path to the session .jsonl file to resume" }),
|
|
1729
|
+
name: Type.Optional(
|
|
1730
|
+
Type.String({ description: "Display name for the terminal tab. Default: 'Resume'" }),
|
|
1731
|
+
),
|
|
1732
|
+
message: Type.Optional(
|
|
1733
|
+
Type.String({
|
|
1734
|
+
description: "Optional message to send after resuming (e.g. follow-up instructions)",
|
|
1735
|
+
}),
|
|
1736
|
+
),
|
|
1737
|
+
autoExit: Type.Optional(
|
|
1738
|
+
Type.Boolean({
|
|
1739
|
+
description:
|
|
1740
|
+
"Whether the resumed session should automatically exit after completing its response. Defaults to true for autonomous follow-up work; set false for interactive resumed sessions.",
|
|
1741
|
+
}),
|
|
1742
|
+
),
|
|
1743
|
+
}),
|
|
1744
|
+
|
|
1745
|
+
renderCall(args, theme) {
|
|
1746
|
+
const name = args.name ?? "Resume";
|
|
1747
|
+
const text =
|
|
1748
|
+
"▸ " +
|
|
1749
|
+
theme.fg("toolTitle", theme.bold(name)) +
|
|
1750
|
+
theme.fg("dim", " — resuming session");
|
|
1751
|
+
return new Text(text, 0, 0);
|
|
1752
|
+
},
|
|
1753
|
+
|
|
1754
|
+
renderResult(result, _opts, theme) {
|
|
1755
|
+
const details = result.details as any;
|
|
1756
|
+
const name = details?.name ?? "Resume";
|
|
1757
|
+
|
|
1758
|
+
if (details?.status === "started") {
|
|
1759
|
+
return new Text(
|
|
1760
|
+
theme.fg("accent", "▸") +
|
|
1761
|
+
" " +
|
|
1762
|
+
theme.fg("toolTitle", theme.bold(name)) +
|
|
1763
|
+
theme.fg("dim", " — resumed"),
|
|
1764
|
+
0,
|
|
1765
|
+
0,
|
|
1766
|
+
);
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
// Fallback
|
|
1770
|
+
const text = typeof result.content[0]?.text === "string" ? result.content[0].text : "";
|
|
1771
|
+
return new Text(theme.fg("dim", text), 0, 0);
|
|
1772
|
+
},
|
|
1773
|
+
|
|
1774
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1775
|
+
const name = params.name ?? "Resume";
|
|
1776
|
+
const { autoExit, interactive } = resolveResumeLaunchBehavior(params);
|
|
1777
|
+
const startTime = Date.now();
|
|
1778
|
+
const id = Math.random().toString(16).slice(2, 10);
|
|
1779
|
+
|
|
1780
|
+
if (!isTerminalAvailable()) {
|
|
1781
|
+
return muxUnavailableResult();
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
if (!existsSync(params.sessionPath)) {
|
|
1785
|
+
return {
|
|
1786
|
+
content: [
|
|
1787
|
+
{ type: "text", text: `Error: session file not found: ${params.sessionPath}` },
|
|
1788
|
+
],
|
|
1789
|
+
details: { error: "session not found" },
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
// Record entry count before resuming so we can extract new messages
|
|
1794
|
+
const entryCountBefore = getNewEntries(params.sessionPath, 0).length;
|
|
1795
|
+
|
|
1796
|
+
const surface = createSubagentPane(name);
|
|
1797
|
+
await new Promise<void>((resolve) => setTimeout(resolve, getShellReadyDelayMs()));
|
|
1798
|
+
|
|
1799
|
+
// Build pi resume command
|
|
1800
|
+
const parts = ["pi", "--session", shellQuote(params.sessionPath)];
|
|
1801
|
+
|
|
1802
|
+
// Load subagent-done extension so the agent can self-terminate if needed
|
|
1803
|
+
const subagentDonePath = join(SUBAGENTS_DIR, "subagent-done.ts");
|
|
1804
|
+
parts.push("-e", shellQuote(subagentDonePath));
|
|
1805
|
+
|
|
1806
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
1807
|
+
const artifactDir = getArtifactDir(ctx.sessionManager.getSessionDir(), sessionId);
|
|
1808
|
+
const activityFile = getSubagentActivityFile(artifactDir, id);
|
|
1809
|
+
mkdirSync(dirname(activityFile), { recursive: true });
|
|
1810
|
+
|
|
1811
|
+
let resumeMsgFile: string | undefined;
|
|
1812
|
+
if (params.message) {
|
|
1813
|
+
const msgTimestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
1814
|
+
resumeMsgFile = join(
|
|
1815
|
+
artifactDir,
|
|
1816
|
+
"subagent-resume",
|
|
1817
|
+
`${name
|
|
1818
|
+
.toLowerCase()
|
|
1819
|
+
.replace(/[^a-z0-9\s-]/g, "")
|
|
1820
|
+
.replace(/\s+/g, "-")
|
|
1821
|
+
.replace(/-+/g, "-")
|
|
1822
|
+
.replace(/^-|-$/g, "") || "resume"}-${msgTimestamp}.md`,
|
|
1823
|
+
);
|
|
1824
|
+
mkdirSync(dirname(resumeMsgFile), { recursive: true });
|
|
1825
|
+
writeFileSync(resumeMsgFile, params.message, "utf8");
|
|
1826
|
+
parts.push(shellQuote(`@${resumeMsgFile}`));
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
// Build env prefix — propagate PI_CODING_AGENT_DIR for config isolation
|
|
1830
|
+
const resumeEnvParts: string[] = [];
|
|
1831
|
+
if (process.env.PI_CODING_AGENT_DIR) {
|
|
1832
|
+
resumeEnvParts.push(`PI_CODING_AGENT_DIR=${shellQuote(process.env.PI_CODING_AGENT_DIR)}`);
|
|
1833
|
+
}
|
|
1834
|
+
resumeEnvParts.push(`PI_SUBAGENT_NAME=${shellQuote(name)}`);
|
|
1835
|
+
resumeEnvParts.push(`PI_SUBAGENT_SESSION=${shellQuote(params.sessionPath)}`);
|
|
1836
|
+
resumeEnvParts.push(`PI_SUBAGENT_ID=${shellQuote(id)}`);
|
|
1837
|
+
resumeEnvParts.push(`PI_SUBAGENT_ACTIVITY_FILE=${shellQuote(activityFile)}`);
|
|
1838
|
+
if (autoExit) {
|
|
1839
|
+
resumeEnvParts.push(`PI_SUBAGENT_AUTO_EXIT=1`);
|
|
1840
|
+
}
|
|
1841
|
+
const resumeEnvPrefix = resumeEnvParts.join(" ") + " ";
|
|
1842
|
+
|
|
1843
|
+
const command = `${resumeEnvPrefix}${parts.join(" ")}; echo '__SUBAGENT_DONE_'$?'__'`;
|
|
1844
|
+
const launchScriptFile = join(
|
|
1845
|
+
artifactDir,
|
|
1846
|
+
"subagent-scripts",
|
|
1847
|
+
`${name
|
|
1848
|
+
.toLowerCase()
|
|
1849
|
+
.replace(/[^a-z0-9\s-]/g, "")
|
|
1850
|
+
.replace(/\s+/g, "-")
|
|
1851
|
+
.replace(/-+/g, "-")
|
|
1852
|
+
.replace(/^-|-$/g, "") || "resume"}-resume-${Date.now()}.sh`,
|
|
1853
|
+
);
|
|
1854
|
+
runScriptInPane(surface, command, {
|
|
1855
|
+
scriptPath: launchScriptFile,
|
|
1856
|
+
scriptPreamble: [
|
|
1857
|
+
`# Subagent resume script for ${name}`,
|
|
1858
|
+
`# Generated: ${new Date().toISOString()}`,
|
|
1859
|
+
`# Session: ${params.sessionPath}`,
|
|
1860
|
+
`# Surface: ${surface}`,
|
|
1861
|
+
...(resumeMsgFile ? [`# Resume message file: ${resumeMsgFile}`] : []),
|
|
1862
|
+
].join("\n"),
|
|
1863
|
+
});
|
|
1864
|
+
|
|
1865
|
+
// Register as a running subagent for widget tracking
|
|
1866
|
+
const running: RunningSubagent = {
|
|
1867
|
+
id,
|
|
1868
|
+
name,
|
|
1869
|
+
task: params.message ?? "resumed session",
|
|
1870
|
+
surface,
|
|
1871
|
+
startTime,
|
|
1872
|
+
sessionFile: params.sessionPath,
|
|
1873
|
+
launchScriptFile,
|
|
1874
|
+
activityFile,
|
|
1875
|
+
interactive,
|
|
1876
|
+
statusState: createStatusState({
|
|
1877
|
+
source: "pi",
|
|
1878
|
+
startTimeMs: startTime,
|
|
1879
|
+
}),
|
|
1880
|
+
};
|
|
1881
|
+
runningSubagents.set(id, running);
|
|
1882
|
+
startWidgetRefresh();
|
|
1883
|
+
startStatusRefresh(pi);
|
|
1884
|
+
|
|
1885
|
+
// Fire-and-forget watcher
|
|
1886
|
+
const watcherAbort = new AbortController();
|
|
1887
|
+
running.abortController = watcherAbort;
|
|
1888
|
+
|
|
1889
|
+
watchSubagent(running, watcherAbort.signal)
|
|
1890
|
+
.then((result) => {
|
|
1891
|
+
updateWidget();
|
|
1892
|
+
|
|
1893
|
+
if (result.ping) {
|
|
1894
|
+
const sessionRef = `\n\nSession: ${params.sessionPath}\nResume: pi --session ${params.sessionPath}`;
|
|
1895
|
+
pi.sendMessage(
|
|
1896
|
+
{
|
|
1897
|
+
customType: "subagent_ping",
|
|
1898
|
+
content: `Sub-agent "${result.ping.name}" needs help (${formatElapsed(result.elapsed)}):\n\n${result.ping.message}${sessionRef}`,
|
|
1899
|
+
display: true,
|
|
1900
|
+
details: {
|
|
1901
|
+
name: result.ping.name,
|
|
1902
|
+
message: result.ping.message,
|
|
1903
|
+
sessionFile: params.sessionPath,
|
|
1904
|
+
},
|
|
1905
|
+
},
|
|
1906
|
+
{ triggerTurn: true, deliverAs: "steer" },
|
|
1907
|
+
);
|
|
1908
|
+
return;
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
const allEntries = getNewEntries(params.sessionPath, entryCountBefore);
|
|
1912
|
+
const summary = findLastAssistantMessage(allEntries) ??
|
|
1913
|
+
(result.errorMessage
|
|
1914
|
+
? `Subagent error: ${result.errorMessage}`
|
|
1915
|
+
: result.exitCode !== 0
|
|
1916
|
+
? `Resumed session exited with code ${result.exitCode}`
|
|
1917
|
+
: "Resumed session exited without new output");
|
|
1918
|
+
const presentation = resolveResultPresentation(
|
|
1919
|
+
{ ...result, summary, sessionFile: params.sessionPath },
|
|
1920
|
+
name,
|
|
1921
|
+
);
|
|
1922
|
+
|
|
1923
|
+
pi.sendMessage(
|
|
1924
|
+
{
|
|
1925
|
+
customType: "subagent_result",
|
|
1926
|
+
content: presentation,
|
|
1927
|
+
display: true,
|
|
1928
|
+
details: {
|
|
1929
|
+
name,
|
|
1930
|
+
task: params.message ?? "resumed session",
|
|
1931
|
+
exitCode: result.exitCode,
|
|
1932
|
+
elapsed: result.elapsed,
|
|
1933
|
+
sessionFile: params.sessionPath,
|
|
1934
|
+
...(result.errorMessage ? { errorMessage: result.errorMessage } : {}),
|
|
1935
|
+
},
|
|
1936
|
+
},
|
|
1937
|
+
{ triggerTurn: true, deliverAs: "steer" },
|
|
1938
|
+
);
|
|
1939
|
+
})
|
|
1940
|
+
.catch((err) => {
|
|
1941
|
+
updateWidget();
|
|
1942
|
+
pi.sendMessage(
|
|
1943
|
+
{
|
|
1944
|
+
customType: "subagent_result",
|
|
1945
|
+
content: `Resume error: ${err?.message ?? String(err)}`,
|
|
1946
|
+
display: true,
|
|
1947
|
+
details: { name, error: err?.message },
|
|
1948
|
+
},
|
|
1949
|
+
{ triggerTurn: true, deliverAs: "steer" },
|
|
1950
|
+
);
|
|
1951
|
+
});
|
|
1952
|
+
|
|
1953
|
+
return {
|
|
1954
|
+
content: [{ type: "text", text: `Session "${name}" resumed.` }],
|
|
1955
|
+
details: {
|
|
1956
|
+
id,
|
|
1957
|
+
name,
|
|
1958
|
+
sessionPath: params.sessionPath,
|
|
1959
|
+
launchScriptFile,
|
|
1960
|
+
status: "started",
|
|
1961
|
+
},
|
|
1962
|
+
};
|
|
1963
|
+
},
|
|
1964
|
+
});
|
|
1965
|
+
|
|
1966
|
+
// /iterate command — fork the session into a subagent
|
|
1967
|
+
pi.registerCommand("iterate", {
|
|
1968
|
+
description: "Fork session into a subagent for focused work (bugfixes, iteration)",
|
|
1969
|
+
handler: async (args, _ctx) => {
|
|
1970
|
+
const task = args.trim() || "";
|
|
1971
|
+
const toolCall = task
|
|
1972
|
+
? `Use subagent to fork a session. fork: true, name: "Iterate", task: ${JSON.stringify(task)}`
|
|
1973
|
+
: `Use subagent to fork a session. fork: true, name: "Iterate", task: "The user wants to do some hands-on work. Help them with whatever they need."`;
|
|
1974
|
+
pi.sendUserMessage(toolCall);
|
|
1975
|
+
},
|
|
1976
|
+
});
|
|
1977
|
+
|
|
1978
|
+
// /subagent command — spawn a subagent by name
|
|
1979
|
+
pi.registerCommand("subagent", {
|
|
1980
|
+
description: "Spawn a subagent: /subagent <agent> <task>",
|
|
1981
|
+
handler: async (args, ctx) => {
|
|
1982
|
+
const trimmed = args.trim();
|
|
1983
|
+
if (!trimmed) {
|
|
1984
|
+
ctx.ui.notify("Usage: /subagent <agent> [task]", "warning");
|
|
1985
|
+
return;
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
const spaceIdx = trimmed.indexOf(" ");
|
|
1989
|
+
const agentName = spaceIdx === -1 ? trimmed : trimmed.slice(0, spaceIdx);
|
|
1990
|
+
const task = spaceIdx === -1 ? "" : trimmed.slice(spaceIdx + 1).trim();
|
|
1991
|
+
|
|
1992
|
+
const defs = loadAgentDefaults(agentName);
|
|
1993
|
+
if (!defs) {
|
|
1994
|
+
ctx.ui.notify(
|
|
1995
|
+
`Agent "${agentName}" not found in ~/.pi/agent/agents/ or .pi/agents/`,
|
|
1996
|
+
"error",
|
|
1997
|
+
);
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
const taskText = task || `You are the ${agentName} agent. Wait for instructions.`;
|
|
2002
|
+
const displayName = agentName[0].toUpperCase() + agentName.slice(1);
|
|
2003
|
+
const toolCall = `Use subagent with agent: "${agentName}", name: "${displayName}", task: ${JSON.stringify(taskText)}`;
|
|
2004
|
+
pi.sendUserMessage(toolCall);
|
|
2005
|
+
},
|
|
2006
|
+
});
|
|
2007
|
+
|
|
2008
|
+
// ── subagent_result message renderer ──
|
|
2009
|
+
pi.registerMessageRenderer("subagent_result", (message, options, theme) => {
|
|
2010
|
+
const details = message.details as any;
|
|
2011
|
+
if (!details) return undefined;
|
|
2012
|
+
|
|
2013
|
+
return {
|
|
2014
|
+
render(width: number): string[] {
|
|
2015
|
+
const name = details.name ?? "subagent";
|
|
2016
|
+
const exitCode = details.exitCode ?? 0;
|
|
2017
|
+
const errorMessage = typeof details.errorMessage === "string" ? details.errorMessage : "";
|
|
2018
|
+
const failed = exitCode !== 0 || !!errorMessage;
|
|
2019
|
+
const elapsed = details.elapsed != null ? formatElapsed(details.elapsed) : "?";
|
|
2020
|
+
const bgFn = failed
|
|
2021
|
+
? (text: string) => theme.bg("toolErrorBg", text)
|
|
2022
|
+
: (text: string) => theme.bg("toolSuccessBg", text);
|
|
2023
|
+
const icon = failed
|
|
2024
|
+
? theme.fg("error", "✗")
|
|
2025
|
+
: theme.fg("success", "✓");
|
|
2026
|
+
const status = errorMessage
|
|
2027
|
+
? "failed (provider/agent error)"
|
|
2028
|
+
: failed
|
|
2029
|
+
? `failed (exit ${exitCode})`
|
|
2030
|
+
: "completed";
|
|
2031
|
+
const agentTag = details.agent ? theme.fg("dim", ` (${details.agent})`) : "";
|
|
2032
|
+
|
|
2033
|
+
const header = `${icon} ${theme.fg("toolTitle", theme.bold(name))}${agentTag} ${theme.fg("dim", "—")} ${status} ${theme.fg("dim", `(${elapsed})`)}`;
|
|
2034
|
+
const rawContent = typeof message.content === "string" ? message.content : "";
|
|
2035
|
+
|
|
2036
|
+
// Clean summary (remove session ref and leading label for display)
|
|
2037
|
+
const summary = rawContent
|
|
2038
|
+
.replace(/\n\nSession: .+\nResume: .+$/, "")
|
|
2039
|
+
.replace(`Sub-agent "${name}" completed (${elapsed}).\n\n`, "")
|
|
2040
|
+
.replace(`Sub-agent "${name}" failed (exit code ${exitCode}).\n\n`, "")
|
|
2041
|
+
.replace(
|
|
2042
|
+
new RegExp(
|
|
2043
|
+
`^Sub-agent "${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}" failed after ${elapsed} \\(provider/agent error — auto-retry exhausted\\)\\.\\n\\n`,
|
|
2044
|
+
),
|
|
2045
|
+
"",
|
|
2046
|
+
);
|
|
2047
|
+
|
|
2048
|
+
// Build content for the box
|
|
2049
|
+
const contentLines = [header];
|
|
2050
|
+
|
|
2051
|
+
if (options.expanded) {
|
|
2052
|
+
// Full view: complete summary + session info
|
|
2053
|
+
if (summary) {
|
|
2054
|
+
for (const line of summary.split("\n")) {
|
|
2055
|
+
contentLines.push(line.slice(0, width - 6));
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
if (details.sessionFile) {
|
|
2059
|
+
contentLines.push("");
|
|
2060
|
+
contentLines.push(theme.fg("dim", `Session: ${details.sessionFile}`));
|
|
2061
|
+
contentLines.push(theme.fg("dim", `Resume: pi --session ${details.sessionFile}`));
|
|
2062
|
+
}
|
|
2063
|
+
} else {
|
|
2064
|
+
// Collapsed: preview + expand hint
|
|
2065
|
+
if (summary) {
|
|
2066
|
+
const previewLines = summary.split("\n").slice(0, 5);
|
|
2067
|
+
for (const line of previewLines) {
|
|
2068
|
+
contentLines.push(theme.fg("dim", line.slice(0, width - 6)));
|
|
2069
|
+
}
|
|
2070
|
+
const totalLines = summary.split("\n").length;
|
|
2071
|
+
if (totalLines > 5) {
|
|
2072
|
+
contentLines.push(theme.fg("muted", `… ${totalLines - 5} more lines`));
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
contentLines.push(theme.fg("muted", keyHint("app.tools.expand", "to expand")));
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
// Render via Box for background + padding, with blank line above for separation
|
|
2079
|
+
const box = new Box(1, 1, bgFn);
|
|
2080
|
+
box.addChild(new Text(contentLines.join("\n"), 0, 0));
|
|
2081
|
+
return ["", ...box.render(width)];
|
|
2082
|
+
},
|
|
2083
|
+
};
|
|
2084
|
+
});
|
|
2085
|
+
|
|
2086
|
+
// ── subagent_status message renderer ──
|
|
2087
|
+
pi.registerMessageRenderer("subagent_status", (message, options, theme) => {
|
|
2088
|
+
const details = message.details as any;
|
|
2089
|
+
const lines = Array.isArray(details?.lines) ? details.lines : [];
|
|
2090
|
+
const overflow = typeof details?.overflow === "number" ? details.overflow : 0;
|
|
2091
|
+
if (lines.length === 0 && overflow === 0) return undefined;
|
|
2092
|
+
|
|
2093
|
+
return {
|
|
2094
|
+
render(width: number): string[] {
|
|
2095
|
+
const lineWidth = Math.max(0, width - 6);
|
|
2096
|
+
const contentLines = [
|
|
2097
|
+
`${theme.fg("accent", "•")} ${theme.fg("toolTitle", theme.bold("Subagent status"))}`,
|
|
2098
|
+
...lines.map((line: string) => theme.fg("dim", truncateToWidth(line, lineWidth))),
|
|
2099
|
+
];
|
|
2100
|
+
|
|
2101
|
+
if (overflow > 0) {
|
|
2102
|
+
contentLines.push(theme.fg("muted", `+${overflow} more running.`));
|
|
2103
|
+
}
|
|
2104
|
+
if (!options.expanded) {
|
|
2105
|
+
contentLines.push(theme.fg("muted", keyHint("app.tools.expand", "to expand")));
|
|
2106
|
+
}
|
|
2107
|
+
|
|
2108
|
+
const box = new Box(1, 1, (text: string) => theme.bg("customMessageBg", text));
|
|
2109
|
+
box.addChild(new Text(contentLines.join("\n"), 0, 0));
|
|
2110
|
+
return ["", ...box.render(width)];
|
|
2111
|
+
},
|
|
2112
|
+
};
|
|
2113
|
+
});
|
|
2114
|
+
|
|
2115
|
+
// ── subagent_ping message renderer ──
|
|
2116
|
+
pi.registerMessageRenderer("subagent_ping", (message, options, theme) => {
|
|
2117
|
+
const details = message.details as any;
|
|
2118
|
+
if (!details) return undefined;
|
|
2119
|
+
|
|
2120
|
+
return {
|
|
2121
|
+
render(width: number): string[] {
|
|
2122
|
+
const name = details.name ?? "subagent";
|
|
2123
|
+
const agentTag = details.agent ? theme.fg("dim", ` (${details.agent})`) : "";
|
|
2124
|
+
const bgFn = (text: string) => theme.bg("toolSuccessBg", text);
|
|
2125
|
+
|
|
2126
|
+
const icon = theme.fg("accent", "?");
|
|
2127
|
+
const header = `${icon} ${theme.fg("toolTitle", theme.bold(name))}${agentTag} ${theme.fg("dim", "— needs help")}`;
|
|
2128
|
+
|
|
2129
|
+
const contentLines = [header];
|
|
2130
|
+
|
|
2131
|
+
if (options.expanded) {
|
|
2132
|
+
contentLines.push("");
|
|
2133
|
+
contentLines.push(details.message ?? "");
|
|
2134
|
+
if (details.sessionFile) {
|
|
2135
|
+
contentLines.push("");
|
|
2136
|
+
contentLines.push(theme.fg("dim", `Session: ${details.sessionFile}`));
|
|
2137
|
+
}
|
|
2138
|
+
} else {
|
|
2139
|
+
const preview = (details.message ?? "").split("\n")[0].slice(0, width - 10);
|
|
2140
|
+
contentLines.push(theme.fg("dim", preview));
|
|
2141
|
+
contentLines.push(theme.fg("muted", keyHint("app.tools.expand", "to expand")));
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
const box = new Box(1, 1, bgFn);
|
|
2145
|
+
box.addChild(new Text(contentLines.join("\n"), 0, 0));
|
|
2146
|
+
return ["", ...box.render(width)];
|
|
2147
|
+
},
|
|
2148
|
+
};
|
|
2149
|
+
});
|
|
2150
|
+
|
|
2151
|
+
// /plan command — start the full planning workflow
|
|
2152
|
+
pi.registerCommand("plan", {
|
|
2153
|
+
description: "Start a planning session: /plan <what to build>",
|
|
2154
|
+
handler: async (args, ctx) => {
|
|
2155
|
+
const task = args.trim();
|
|
2156
|
+
if (!task) {
|
|
2157
|
+
ctx.ui.notify("Usage: /plan <what to build>", "warning");
|
|
2158
|
+
return;
|
|
2159
|
+
}
|
|
2160
|
+
|
|
2161
|
+
// Rename workspace and tab to show this is a planning session
|
|
2162
|
+
if (isTerminalAvailable()) {
|
|
2163
|
+
try {
|
|
2164
|
+
const label = task.length > 40 ? task.slice(0, 40) + "..." : task;
|
|
2165
|
+
renameCurrentWorkspace(`🎯 ${label}`);
|
|
2166
|
+
renameCurrentTab(`🎯 Plan: ${label}`);
|
|
2167
|
+
} catch {
|
|
2168
|
+
// non-critical -- do not block the plan
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
// Load the plan skill from the subagents extension directory
|
|
2173
|
+
const planSkillPath = join(SUBAGENTS_DIR, "plan-skill.md");
|
|
2174
|
+
let content = readFileSync(planSkillPath, "utf8");
|
|
2175
|
+
content = content.replace(/^---\n[\s\S]*?\n---\n*/, "");
|
|
2176
|
+
pi.sendUserMessage(
|
|
2177
|
+
`<skill name="plan" location="${planSkillPath}">\n${content.trim()}\n</skill>\n\n${task}`,
|
|
2178
|
+
);
|
|
2179
|
+
},
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
// test
|