pi-subagent-manager 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +139 -2
- package/agents/researcher.md +14 -0
- package/agents/worker.md +6 -0
- package/package.json +61 -4
- package/src/config.ts +355 -0
- package/src/index.ts +216 -0
- package/src/mailbox.ts +261 -0
- package/src/manager.ts +576 -0
- package/src/paths.ts +73 -0
- package/src/runtime.ts +390 -0
- package/src/tools.ts +130 -0
- package/src/types.ts +114 -0
- package/src/ui.ts +391 -0
package/src/ui.ts
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { parse as parseShell } from "shell-quote";
|
|
7
|
+
import {
|
|
8
|
+
type ExtensionCommandContext,
|
|
9
|
+
type ExtensionContext,
|
|
10
|
+
type Theme,
|
|
11
|
+
type ThemeColor,
|
|
12
|
+
} from "@earendil-works/pi-coding-agent";
|
|
13
|
+
import { stripTerminalSequences, truncateToWidth } from "@earendil-works/pi-tui";
|
|
14
|
+
import { AGENT_COLORS, ConfigStore, parseAgentType, serializeAgentType } from "./config.ts";
|
|
15
|
+
import { THINKING_LEVELS, type AgentType, type ThreadService, type ThreadView } from "./types.ts";
|
|
16
|
+
|
|
17
|
+
export type ThreadController = Pick<
|
|
18
|
+
ThreadService,
|
|
19
|
+
"list" | "get" | "output" | "transcript" | "steer" | "stop"
|
|
20
|
+
>;
|
|
21
|
+
|
|
22
|
+
/** Plain terminal-safe text: never pass agent-supplied terminal commands through. */
|
|
23
|
+
export function sanitizeText(text: string): string {
|
|
24
|
+
return stripTerminalSequences(text).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function renderThreads(
|
|
28
|
+
threads: ThreadView[],
|
|
29
|
+
width: number,
|
|
30
|
+
theme: Pick<Theme, "fg">,
|
|
31
|
+
): string[] {
|
|
32
|
+
const priority = (thread: ThreadView) =>
|
|
33
|
+
thread.state === "starting" || thread.state === "running"
|
|
34
|
+
? 0
|
|
35
|
+
: thread.state === "paused"
|
|
36
|
+
? 1
|
|
37
|
+
: 2;
|
|
38
|
+
const visible = threads
|
|
39
|
+
.filter((thread) => thread.path !== "/root")
|
|
40
|
+
.sort(
|
|
41
|
+
(a, b) => priority(a) - priority(b) || b.updatedAt - a.updatedAt || b.createdAt - a.createdAt,
|
|
42
|
+
);
|
|
43
|
+
const limit = visible.length > 8 ? 7 : 8;
|
|
44
|
+
const lines = visible.slice(0, limit).map((thread) => {
|
|
45
|
+
const color: ThemeColor = AGENT_COLORS.includes(thread.color as (typeof AGENT_COLORS)[number])
|
|
46
|
+
? (thread.color as ThemeColor)
|
|
47
|
+
: thread.state === "failed"
|
|
48
|
+
? "error"
|
|
49
|
+
: thread.state === "paused"
|
|
50
|
+
? "warning"
|
|
51
|
+
: "accent";
|
|
52
|
+
const label = `${sanitizeText(thread.path)} [${sanitizeText(thread.state)}]`;
|
|
53
|
+
return truncateToWidth(
|
|
54
|
+
`${theme.fg(color, label)} ${sanitizeText(thread.status || thread.task)}`,
|
|
55
|
+
Math.max(0, width),
|
|
56
|
+
);
|
|
57
|
+
});
|
|
58
|
+
if (visible.length > limit) {
|
|
59
|
+
lines.push(
|
|
60
|
+
truncateToWidth(
|
|
61
|
+
theme.fg("muted", `+${visible.length - limit} more threads · /agents thread`),
|
|
62
|
+
Math.max(0, width),
|
|
63
|
+
),
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
return lines;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function updateWidget(ctx: ExtensionContext, threads: ThreadView[]): void {
|
|
70
|
+
if (!ctx.hasUI) return;
|
|
71
|
+
if (!threads.some((thread) => thread.path !== "/root")) {
|
|
72
|
+
ctx.ui.setWidget("pi-subagent", undefined, { placement: "belowEditor" });
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
ctx.ui.setWidget(
|
|
76
|
+
"pi-subagent",
|
|
77
|
+
() => ({
|
|
78
|
+
render: (width) => renderThreads(threads, width, ctx.ui.theme),
|
|
79
|
+
invalidate: () => {},
|
|
80
|
+
}),
|
|
81
|
+
{ placement: "belowEditor" },
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function showThreads(
|
|
86
|
+
ctx: ExtensionCommandContext,
|
|
87
|
+
controller: ThreadController,
|
|
88
|
+
path?: string,
|
|
89
|
+
): Promise<void> {
|
|
90
|
+
if (!ctx.hasUI) return;
|
|
91
|
+
let selectedPath = path;
|
|
92
|
+
while (true) {
|
|
93
|
+
try {
|
|
94
|
+
if (!selectedPath) {
|
|
95
|
+
const threads = controller.list().filter((thread) => thread.path !== "/root");
|
|
96
|
+
if (!threads.length) {
|
|
97
|
+
ctx.ui.notify("No subagent threads.", "info");
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const labels = threads.map(
|
|
101
|
+
(thread) =>
|
|
102
|
+
`${sanitizeText(thread.path)} [${sanitizeText(thread.state)}] ${sanitizeText(thread.status)}`,
|
|
103
|
+
);
|
|
104
|
+
const selected = await ctx.ui.select("Subagent threads", labels);
|
|
105
|
+
if (selected === undefined) return;
|
|
106
|
+
selectedPath = threads[labels.indexOf(selected)]?.path;
|
|
107
|
+
if (!selectedPath) return;
|
|
108
|
+
}
|
|
109
|
+
if (selectedPath === "/root")
|
|
110
|
+
throw new Error("/root is the current Pi thread, not a subagent.");
|
|
111
|
+
const thread = controller.get(selectedPath);
|
|
112
|
+
const children = controller.list().filter((child) => child.parent === selectedPath);
|
|
113
|
+
const title = `${sanitizeText(thread.path)} [${sanitizeText(thread.state)}] ${sanitizeText(thread.status)}`;
|
|
114
|
+
const action = await ctx.ui.select(title, [
|
|
115
|
+
"View output",
|
|
116
|
+
"View transcript",
|
|
117
|
+
"Send input / resume",
|
|
118
|
+
"Stop",
|
|
119
|
+
...(children.length ? ["Children"] : []),
|
|
120
|
+
"Back",
|
|
121
|
+
]);
|
|
122
|
+
if (!action || action === "Back") {
|
|
123
|
+
if (path) return;
|
|
124
|
+
selectedPath = undefined;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (action === "View output" || action === "View transcript") {
|
|
128
|
+
const text =
|
|
129
|
+
action === "View output"
|
|
130
|
+
? controller.output(selectedPath)
|
|
131
|
+
: await controller.transcript(selectedPath);
|
|
132
|
+
// Built-in editor is a portable viewer; edits are explicitly discarded.
|
|
133
|
+
await ctx.ui.editor(
|
|
134
|
+
`${sanitizeText(selectedPath)} — READ ONLY (changes discarded)`,
|
|
135
|
+
text.split("\n").map(sanitizeText).join("\n"),
|
|
136
|
+
);
|
|
137
|
+
} else if (action === "Send input / resume") {
|
|
138
|
+
const message = await ctx.ui.editor("Send input / resume retained session", "");
|
|
139
|
+
if (message?.trim()) await controller.steer(selectedPath, message);
|
|
140
|
+
} else if (action === "Stop") {
|
|
141
|
+
if (
|
|
142
|
+
await ctx.ui.confirm(
|
|
143
|
+
"Stop thread",
|
|
144
|
+
`Stop ${sanitizeText(selectedPath)} and its descendants?`,
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
await controller.stop(selectedPath);
|
|
148
|
+
} else if (action === "Children") {
|
|
149
|
+
const labels = children.map(
|
|
150
|
+
(child) =>
|
|
151
|
+
`${sanitizeText(child.path)} [${sanitizeText(child.state)}] ${sanitizeText(child.status)}`,
|
|
152
|
+
);
|
|
153
|
+
const selected = await ctx.ui.select("Children", labels);
|
|
154
|
+
if (selected !== undefined)
|
|
155
|
+
selectedPath = children[labels.indexOf(selected)]?.path ?? selectedPath;
|
|
156
|
+
}
|
|
157
|
+
} catch (error) {
|
|
158
|
+
ctx.ui.notify(sanitizeText(error instanceof Error ? error.message : String(error)), "error");
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Parse editor argv, rejecting shell operators instead of evaluating a shell command. */
|
|
165
|
+
export function editorArguments(command: string): string[] {
|
|
166
|
+
const args = parseShell(command, process.env);
|
|
167
|
+
if (!args.length || args.some((arg) => typeof arg !== "string") || !args[0]) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
"VISUAL/EDITOR must be an executable and arguments, without shell operators or globs.",
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
return args as string[];
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function externalEdit(ctx: ExtensionCommandContext, text: string): Promise<string> {
|
|
176
|
+
if (ctx.mode !== "tui") throw new Error("External editing requires interactive TUI mode.");
|
|
177
|
+
const [command, ...args] = editorArguments(process.env.VISUAL || process.env.EDITOR || "vi");
|
|
178
|
+
const directory = await mkdtemp(join(tmpdir(), "pi-subagent-"));
|
|
179
|
+
const file = join(directory, "agent.md");
|
|
180
|
+
try {
|
|
181
|
+
await writeFile(file, text, "utf8");
|
|
182
|
+
await ctx.ui.custom<void>((tui, _theme, _keys, done) => {
|
|
183
|
+
tui.stop();
|
|
184
|
+
try {
|
|
185
|
+
const result = spawnSync(command!, [...args, file], {
|
|
186
|
+
stdio: "inherit",
|
|
187
|
+
env: process.env,
|
|
188
|
+
});
|
|
189
|
+
if (result.error) throw result.error;
|
|
190
|
+
if (result.status !== 0)
|
|
191
|
+
throw new Error(`Editor exited with status ${result.status ?? result.signal}.`);
|
|
192
|
+
} finally {
|
|
193
|
+
tui.start();
|
|
194
|
+
tui.requestRender(true);
|
|
195
|
+
}
|
|
196
|
+
done();
|
|
197
|
+
return { render: () => [], invalidate: () => {} };
|
|
198
|
+
});
|
|
199
|
+
return await readFile(file, "utf8");
|
|
200
|
+
} finally {
|
|
201
|
+
await rm(directory, { recursive: true, force: true });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function editToolList(
|
|
206
|
+
ctx: ExtensionCommandContext,
|
|
207
|
+
type: AgentType,
|
|
208
|
+
field: "allow" | "block",
|
|
209
|
+
): Promise<void> {
|
|
210
|
+
const mode = await ctx.ui.select(
|
|
211
|
+
`tools.${field} (${type.tools?.[field]?.join(", ") ?? "unset"})`,
|
|
212
|
+
["Unset (use default policy)", "Empty list", "Enter exact tool names"],
|
|
213
|
+
);
|
|
214
|
+
if (!mode) return;
|
|
215
|
+
if (mode === "Unset (use default policy)") {
|
|
216
|
+
if (type.tools) delete type.tools[field];
|
|
217
|
+
} else {
|
|
218
|
+
const value =
|
|
219
|
+
mode === "Empty list"
|
|
220
|
+
? ""
|
|
221
|
+
: await ctx.ui.input(
|
|
222
|
+
`tools.${field}: comma-separated exact names`,
|
|
223
|
+
type.tools?.[field]?.join(", "),
|
|
224
|
+
);
|
|
225
|
+
if (value === undefined) return;
|
|
226
|
+
type.tools ??= {};
|
|
227
|
+
type.tools[field] = value
|
|
228
|
+
.split(",")
|
|
229
|
+
.map((name) => name.trim())
|
|
230
|
+
.filter(Boolean);
|
|
231
|
+
}
|
|
232
|
+
if (type.tools && !Object.keys(type.tools).length) delete type.tools;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function editDocument(
|
|
236
|
+
ctx: ExtensionCommandContext,
|
|
237
|
+
type: AgentType,
|
|
238
|
+
external: boolean,
|
|
239
|
+
): Promise<AgentType | undefined> {
|
|
240
|
+
const original = serializeAgentType(type);
|
|
241
|
+
let text = original;
|
|
242
|
+
while (true) {
|
|
243
|
+
try {
|
|
244
|
+
if (external) {
|
|
245
|
+
text = await externalEdit(ctx, text);
|
|
246
|
+
} else {
|
|
247
|
+
const end = text.indexOf("\n---", 4);
|
|
248
|
+
const yaml = await ctx.ui.editor(
|
|
249
|
+
"Agent frontmatter YAML (Markdown body preserved)",
|
|
250
|
+
text.slice(4, end),
|
|
251
|
+
);
|
|
252
|
+
if (yaml === undefined) return;
|
|
253
|
+
text = `---\n${yaml.replace(/\n?$/, "\n")}---\n${type.systemPrompt}`;
|
|
254
|
+
}
|
|
255
|
+
return {
|
|
256
|
+
...parseAgentType(text),
|
|
257
|
+
filePath: type.filePath,
|
|
258
|
+
source: type.source,
|
|
259
|
+
};
|
|
260
|
+
} catch (error) {
|
|
261
|
+
const diagnostic = sanitizeText(error instanceof Error ? error.message : String(error));
|
|
262
|
+
ctx.ui.notify(`Edit not accepted: ${diagnostic}. Original definition is unchanged.`, "error");
|
|
263
|
+
if (
|
|
264
|
+
!(await ctx.ui.confirm(
|
|
265
|
+
"Invalid edit — retry?",
|
|
266
|
+
`${diagnostic}\nRetry editing, or cancel to restore the previous definition.`,
|
|
267
|
+
))
|
|
268
|
+
)
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Avoid treating a renamed definition as permission to overwrite another file. */
|
|
275
|
+
function assertSaveDestination(
|
|
276
|
+
store: ConfigStore,
|
|
277
|
+
type: AgentType,
|
|
278
|
+
original: AgentType | undefined,
|
|
279
|
+
scope: "user" | "project",
|
|
280
|
+
): void {
|
|
281
|
+
const entries = store.list();
|
|
282
|
+
const sameName = entries.find((entry) => entry.name === type.name);
|
|
283
|
+
if (sameName && (!original || type.name !== original.name)) {
|
|
284
|
+
throw new Error(`Agent type ${type.name} already exists; choose a different name.`);
|
|
285
|
+
}
|
|
286
|
+
const destination = store.destination(type.name, scope, original);
|
|
287
|
+
if (
|
|
288
|
+
existsSync(destination) &&
|
|
289
|
+
(!original?.filePath || resolve(original.filePath) !== destination)
|
|
290
|
+
) {
|
|
291
|
+
throw new Error(
|
|
292
|
+
`Refusing to overwrite existing definition ${destination}. Edit that definition instead.`,
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export async function editAgentTypes(
|
|
298
|
+
ctx: ExtensionCommandContext,
|
|
299
|
+
store: ConfigStore,
|
|
300
|
+
): Promise<void> {
|
|
301
|
+
if (!ctx.hasUI) return;
|
|
302
|
+
while (true) {
|
|
303
|
+
const types = store.list();
|
|
304
|
+
const names = types.map((type) => type.name);
|
|
305
|
+
const selection = await ctx.ui.select("Agent types", ["Create new type", ...names]);
|
|
306
|
+
if (selection === undefined) return;
|
|
307
|
+
const original = selection === "Create new type" ? undefined : store.get(selection);
|
|
308
|
+
let draft: AgentType = original
|
|
309
|
+
? structuredClone(original)
|
|
310
|
+
: { name: "new-agent", description: "New agent", systemPrompt: "" };
|
|
311
|
+
while (true) {
|
|
312
|
+
const field = await ctx.ui.select(`Edit ${sanitizeText(draft.name)} (unsaved)`, [
|
|
313
|
+
"name",
|
|
314
|
+
"description",
|
|
315
|
+
"model",
|
|
316
|
+
"thinkingLevel",
|
|
317
|
+
"tools.allow",
|
|
318
|
+
"tools.block",
|
|
319
|
+
"color",
|
|
320
|
+
"Edit frontmatter YAML",
|
|
321
|
+
"External editor (entire Markdown)",
|
|
322
|
+
"Save",
|
|
323
|
+
"Cancel",
|
|
324
|
+
]);
|
|
325
|
+
if (!field || field === "Cancel") break;
|
|
326
|
+
try {
|
|
327
|
+
if (field === "Save") {
|
|
328
|
+
// Round-trip before saving: no partial or invalid configuration is accepted.
|
|
329
|
+
const validated = parseAgentType(serializeAgentType(draft));
|
|
330
|
+
const scopeChoice = await ctx.ui.select(
|
|
331
|
+
"Save scope",
|
|
332
|
+
store.canSaveProject() ? ["Global", "Trusted project"] : ["Global"],
|
|
333
|
+
);
|
|
334
|
+
if (!scopeChoice) continue;
|
|
335
|
+
const scope = scopeChoice === "Global" ? "user" : "project";
|
|
336
|
+
assertSaveDestination(store, validated, original, scope);
|
|
337
|
+
const saved = store.save(validated, scope, original);
|
|
338
|
+
ctx.ui.notify(
|
|
339
|
+
`Saved ${sanitizeText(saved.filePath ?? saved.name)}${original && original.name !== saved.name ? " (original file retained)" : ""}.`,
|
|
340
|
+
"info",
|
|
341
|
+
);
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
if (field === "External editor (entire Markdown)" || field === "Edit frontmatter YAML") {
|
|
345
|
+
const edited = await editDocument(
|
|
346
|
+
ctx,
|
|
347
|
+
draft,
|
|
348
|
+
field === "External editor (entire Markdown)",
|
|
349
|
+
);
|
|
350
|
+
if (edited) draft = edited;
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
const candidate = structuredClone(draft);
|
|
354
|
+
if (field === "name" || field === "description" || field === "model") {
|
|
355
|
+
const value = await ctx.ui.input(
|
|
356
|
+
`Agent ${field}${field === "model" ? " (provider/id, blank = default)" : ""}`,
|
|
357
|
+
candidate[field] ?? "",
|
|
358
|
+
);
|
|
359
|
+
if (value === undefined) continue;
|
|
360
|
+
if (field === "model" && !value.trim()) delete candidate.model;
|
|
361
|
+
else candidate[field] = value;
|
|
362
|
+
} else if (field === "thinkingLevel") {
|
|
363
|
+
const value = await ctx.ui.select("Thinking level", [
|
|
364
|
+
"Default (inherit)",
|
|
365
|
+
...THINKING_LEVELS,
|
|
366
|
+
]);
|
|
367
|
+
if (!value) continue;
|
|
368
|
+
if (value === "Default (inherit)") delete candidate.thinkingLevel;
|
|
369
|
+
else candidate.thinkingLevel = value as AgentType["thinkingLevel"];
|
|
370
|
+
} else if (field === "color") {
|
|
371
|
+
const value = await ctx.ui.select("Pi semantic foreground color", [
|
|
372
|
+
"Default",
|
|
373
|
+
...AGENT_COLORS,
|
|
374
|
+
]);
|
|
375
|
+
if (!value) continue;
|
|
376
|
+
if (value === "Default") delete candidate.color;
|
|
377
|
+
else candidate.color = value;
|
|
378
|
+
} else if (field === "tools.allow" || field === "tools.block") {
|
|
379
|
+
await editToolList(ctx, candidate, field === "tools.allow" ? "allow" : "block");
|
|
380
|
+
}
|
|
381
|
+
parseAgentType(serializeAgentType(candidate));
|
|
382
|
+
draft = candidate;
|
|
383
|
+
} catch (error) {
|
|
384
|
+
ctx.ui.notify(
|
|
385
|
+
sanitizeText(error instanceof Error ? error.message : String(error)),
|
|
386
|
+
"error",
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|