@ferris1225/pi-subagents 5.0.0 → 5.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +53 -11
- package/index.ts +24 -1
- package/package.json +2 -2
- package/skills/workflow/SKILL.md +2 -2
- package/src/configuration/config.ts +13 -3
- package/src/configuration/setup.ts +26 -34
- package/src/configuration/ui.ts +143 -0
- package/src/delegation/agents.ts +4 -3
- package/src/delegation/builtin-agents.ts +28 -4
- package/src/delegation/prompt.ts +10 -5
- package/src/execution/cli-run.ts +47 -7
- package/src/execution/run-control.ts +8 -0
- package/src/isolation/cleanup.ts +332 -0
- package/src/isolation/temp-hygiene.ts +0 -23
- package/src/lifecycle/dispatch-core.ts +4 -0
- package/src/lifecycle/durable.ts +4 -0
- package/src/lifecycle/stop.ts +3 -2
- package/src/lifecycle/thread-lifecycle.ts +3 -0
- package/src/lifecycle/thread-restore.ts +9 -12
- package/src/lifecycle/thread-shared.ts +2 -0
- package/src/lifecycle/tools.ts +129 -10
- package/src/presentation/widget.ts +3 -2
- package/workflows/code-review.md +5 -5
|
@@ -151,6 +151,8 @@ export interface DispatchEnvironment {
|
|
|
151
151
|
|
|
152
152
|
/** Admission metadata for a fresh one-shot run. */
|
|
153
153
|
export interface StartBackgroundOptions {
|
|
154
|
+
/** A private copy of a settled session used for a follow-up run. */
|
|
155
|
+
resumeSession?: { sessionId: string; sessionDir: string };
|
|
154
156
|
phaseId?: string;
|
|
155
157
|
scope?: PhaseScope;
|
|
156
158
|
/** A false hint cannot downgrade a live write-capable role. */
|
package/src/lifecycle/tools.ts
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
/** Read-only run inspection and destructive cancellation of one-shot runs. */
|
|
2
2
|
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { copyFile, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import type { Message } from "@earendil-works/pi-ai";
|
|
3
7
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
4
8
|
import { Text } from "@earendil-works/pi-tui";
|
|
5
9
|
import { Type } from "typebox";
|
|
6
|
-
import { DEFAULT_MAX_RESULT_LINES } from "../configuration/config.ts";
|
|
10
|
+
import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
|
|
11
|
+
import { loadBuiltinAgents } from "../delegation/agents.ts";
|
|
12
|
+
import { getProjectRoot, getResultOutput, sessionExists } from "../execution/spawn.ts";
|
|
13
|
+
import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
|
|
14
|
+
import type { DispatchCore } from "./dispatch-core.ts";
|
|
7
15
|
import { stopThreads } from "./stop.ts";
|
|
8
16
|
import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
|
|
9
17
|
import { emptyUsage } from "../execution/run-control.ts";
|
|
10
18
|
import { formatDuration, formatTaskSummary, monitor, runWaitLabel } from "../presentation/monitor.ts";
|
|
11
|
-
import type { SubagentRuntime } from "./runtime.ts";
|
|
19
|
+
import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
|
|
12
20
|
import { projectResultsRoot } from "./thread-shared.ts";
|
|
13
21
|
import { getResultError } from "../execution/spawn.ts";
|
|
14
22
|
import {
|
|
@@ -29,7 +37,53 @@ function renderFirstLine(result: { content?: unknown }, label: string, theme: an
|
|
|
29
37
|
return new Text(`${theme.fg("toolTitle", theme.bold(label))}${theme.fg("dim", firstLine.slice(0, 60))}`, 0, 0);
|
|
30
38
|
}
|
|
31
39
|
|
|
32
|
-
|
|
40
|
+
/** Files a finished run read or changed, recovered from its recorded tool
|
|
41
|
+
* calls. A new child cannot see that history, so naming the paths is the
|
|
42
|
+
* difference between a useful brief and a blind restart. */
|
|
43
|
+
function touchedPaths(messages: readonly Message[] | undefined): string[] {
|
|
44
|
+
const paths = new Set<string>();
|
|
45
|
+
const visit = (value: unknown, depth: number): void => {
|
|
46
|
+
if (depth > 3 || !value || typeof value !== "object") return;
|
|
47
|
+
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
|
|
48
|
+
if (/^(path|paths|file|files|file_path|target|pattern)$/u.test(key)) {
|
|
49
|
+
for (const candidate of Array.isArray(child) ? child : [child]) {
|
|
50
|
+
if (typeof candidate === "string" && candidate.length <= 200 && /[\\/.]/u.test(candidate)) paths.add(candidate);
|
|
51
|
+
}
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
visit(child, depth + 1);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
for (const message of messages ?? []) {
|
|
58
|
+
const content = (message as { content?: unknown }).content;
|
|
59
|
+
if (Array.isArray(content)) for (const part of content) visit(part, 0);
|
|
60
|
+
}
|
|
61
|
+
return [...paths].slice(0, 20);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Brief for a summary follow-up: what the run was asked, what it delivered,
|
|
65
|
+
* which files it touched, and the new instruction — bounded so a long result
|
|
66
|
+
* cannot become the whole context. */
|
|
67
|
+
function buildSummaryFollowUp(thread: SubagentThread, message: string): string {
|
|
68
|
+
const prior = thread.lastResult ? getResultOutput(thread.lastResult) : "(no recorded result)";
|
|
69
|
+
const bounded = prior.length > 4_000 ? prior.slice(0, 4_000) + "\n…(truncated; read the files for detail)" : prior;
|
|
70
|
+
const files = touchedPaths(thread.lastResult?.messages);
|
|
71
|
+
return [
|
|
72
|
+
`Earlier run #${thread.id} (${thread.agentName}) was briefed with:`,
|
|
73
|
+
formatTaskSummary(thread.task, 1_200, false),
|
|
74
|
+
"",
|
|
75
|
+
"It finished with:",
|
|
76
|
+
bounded,
|
|
77
|
+
...(files.length ? ["", "Files it touched:", files.map((path) => `- ${path}`).join("\n")] : []),
|
|
78
|
+
"",
|
|
79
|
+
"Continue with this instruction:",
|
|
80
|
+
message,
|
|
81
|
+
"",
|
|
82
|
+
"You did not witness the earlier session. Verify the files before relying on them, and state any assumption this summary does not support.",
|
|
83
|
+
].join("\n");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime, dispatchCore?: DispatchCore): void {
|
|
33
87
|
pi.registerTool({
|
|
34
88
|
name: "subagent_status",
|
|
35
89
|
label: "Subagent Status",
|
|
@@ -111,18 +165,19 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
111
165
|
// Workflow graphs are reported beside individual runs: which nodes have
|
|
112
166
|
// started, which one is waiting on a dependency, and what a graph that
|
|
113
167
|
// outlived its session left behind.
|
|
168
|
+
const workflowId = params.id === undefined ? params.workflow : undefined;
|
|
114
169
|
const workflowRuns = [...runtime.workflows.values()]
|
|
115
|
-
.filter((run) =>
|
|
170
|
+
.filter((run) => workflowId === undefined || run.id === workflowId)
|
|
116
171
|
.sort((left, right) => left.id - right.id);
|
|
117
172
|
const retainedWorkflows = (await readRetainedWorkflows(runtime, ctx?.cwd ?? process.cwd()).catch(() => []))
|
|
118
|
-
.filter((record) =>
|
|
173
|
+
.filter((record) => workflowId === undefined || record.id === workflowId)
|
|
119
174
|
.filter((record) => !workflowRuns.some((run) => run.id === record.id));
|
|
120
|
-
const workflowSections = [
|
|
175
|
+
const workflowSections = params.id === undefined ? [
|
|
121
176
|
...workflowRuns.map((run) => formatWorkflowStatus(run).join("\n")),
|
|
122
177
|
...retainedWorkflows.map((record) => formatRetainedWorkflow(record).join("\n")),
|
|
123
|
-
];
|
|
178
|
+
] : [];
|
|
124
179
|
const sections = [text, ...workflowSections].filter((section) => section.trim().length > 0);
|
|
125
|
-
const unknownWorkflow =
|
|
180
|
+
const unknownWorkflow = workflowId !== undefined && workflowRuns.length === 0 && retainedWorkflows.length === 0;
|
|
126
181
|
return {
|
|
127
182
|
content: [{
|
|
128
183
|
type: "text",
|
|
@@ -147,6 +202,70 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
147
202
|
},
|
|
148
203
|
});
|
|
149
204
|
|
|
205
|
+
pi.registerTool({
|
|
206
|
+
name: "subagent_message",
|
|
207
|
+
label: "Subagent Message",
|
|
208
|
+
description: "Send a steering message to a running subagent, or continue a completed run. Use context \"session\" (default) to redo or revise the same work: it continues a private copy of the retained session, so earlier reasoning and the provider prompt-cache key survive. Use context \"summary\" for a new next step: it starts fresh with a bounded summary (objective, result, touched files) instead of loading the old transcript. Running messages are queued by Pi and acknowledged, not guaranteed to have been acted on yet.",
|
|
209
|
+
exposure: "model-only",
|
|
210
|
+
executionMode: "sequential",
|
|
211
|
+
parameters: Type.Object({
|
|
212
|
+
id: Type.Integer({ minimum: 1, description: "Exact run id in this parent session." }),
|
|
213
|
+
message: Type.String({ minLength: 1, pattern: "\\S", description: "Additional instruction or follow-up question." }),
|
|
214
|
+
context: Type.Optional(Type.String({ enum: ["session", "summary"], description: "session (default) continues the retained session, preserving its history and provider prompt-cache key. summary starts a fresh run briefed with a bounded summary of the earlier work: cheaper context, no cache reuse, and no access to details the summary omits." })),
|
|
215
|
+
}),
|
|
216
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
217
|
+
await runtime.durableRestore;
|
|
218
|
+
const thread = runtime.threads.get(params.id);
|
|
219
|
+
const fail = (message: string) => ({ content: [{ type: "text" as const, text: message }], details: {}, isError: true });
|
|
220
|
+
if (!thread || thread.retired) return fail(`No available run matches #${params.id} in this session.`);
|
|
221
|
+
if (thread.state === "running" && !thread.lifecycleOperation) {
|
|
222
|
+
try {
|
|
223
|
+
await thread.control.steer(params.message);
|
|
224
|
+
return { content: [{ type: "text" as const, text: `Steering queued for #${thread.id}; it has not necessarily been acted on yet.` }], details: { id: thread.id } };
|
|
225
|
+
} catch (error) { return fail(`Could not send to #${thread.id}: ${error instanceof Error ? error.message : String(error)}`); }
|
|
226
|
+
}
|
|
227
|
+
if (thread.state !== "completed" || thread.lifecycleOperation) {
|
|
228
|
+
return fail(`Run #${thread.id} is ${thread.state}; wait for a running or successfully completed run.`);
|
|
229
|
+
}
|
|
230
|
+
if (!dispatchCore) return fail("Follow-up dispatch is unavailable in this process.");
|
|
231
|
+
const useSummary = params.context === "summary";
|
|
232
|
+
if (!useSummary && (!thread.sessionDir || !thread.sessionId || !sessionExists(thread.sessionDir, thread.sessionId))) {
|
|
233
|
+
return fail(`Run #${thread.id} has no available session to continue; retry with context: "summary".`);
|
|
234
|
+
}
|
|
235
|
+
let copyDir: string | undefined;
|
|
236
|
+
try {
|
|
237
|
+
dispatchCore.setEnvironment({ ctx, config: await loadConfig(runtime.configPath), agents: loadBuiltinAgents() });
|
|
238
|
+
if (useSummary) {
|
|
239
|
+
const task = buildSummaryFollowUp(thread, params.message);
|
|
240
|
+
const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
|
|
241
|
+
phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
|
|
242
|
+
});
|
|
243
|
+
if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
|
|
244
|
+
return { content: [{ type: "text" as const, text: `Started follow-up #${result.runId} from #${thread.id} with a summary only; results arrive automatically.` }], details: { id: result.runId, sourceId: thread.id } };
|
|
245
|
+
}
|
|
246
|
+
const root = join(getProjectRoot(runtime.configPath, thread.cwd), "sessions");
|
|
247
|
+
await mkdir(root, { recursive: true });
|
|
248
|
+
copyDir = await mkdtemp(join(root, "pi-subagent-session-"));
|
|
249
|
+
writeTempOwnerMarker(copyDir);
|
|
250
|
+
const file = (await readdir(thread.sessionDir!)).find((name) => name.endsWith(`_${thread.sessionId}.jsonl`));
|
|
251
|
+
if (!file) throw new Error("The retained session file is missing; retry with context: \"summary\".");
|
|
252
|
+
await copyFile(join(thread.sessionDir!, file), join(copyDir, file));
|
|
253
|
+
if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while its session was copied.");
|
|
254
|
+
const task = `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`;
|
|
255
|
+
const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
|
|
256
|
+
phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
|
|
257
|
+
resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir },
|
|
258
|
+
});
|
|
259
|
+
if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
|
|
260
|
+
copyDir = undefined;
|
|
261
|
+
return { content: [{ type: "text" as const, text: `Started follow-up #${result.runId} from #${thread.id} with its retained session; results arrive automatically.` }], details: { id: result.runId, sourceId: thread.id } };
|
|
262
|
+
} catch (error) {
|
|
263
|
+
if (copyDir) await rm(copyDir, { recursive: true, force: true }).catch(() => undefined);
|
|
264
|
+
return fail(`Could not continue #${thread.id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
|
|
150
269
|
// Cancel one or more active runs: aborts the queue controller, which
|
|
151
270
|
// terminates the child and delivers an aborted result (with whatever partial
|
|
152
271
|
// output it produced) so the main agent always knows the run stopped.
|
|
@@ -166,7 +285,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
166
285
|
pi.registerTool({
|
|
167
286
|
name: "subagent_stop",
|
|
168
287
|
label: "Subagent Stop",
|
|
169
|
-
description: "Destructively stop and retire one run by id/prefix, or
|
|
288
|
+
description: "Destructively stop and retire one run by id/prefix, one workflow by workflow id, or this session’s active runs and workflows with all: true. all takes precedence over id and workflow; id takes precedence over workflow. Other Pi sessions and projects are not targeted. Delivers partial results; stopped runs cannot resume.",
|
|
170
289
|
exposure: "model-only",
|
|
171
290
|
executionMode: "sequential",
|
|
172
291
|
annotations: {
|
|
@@ -182,7 +301,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
182
301
|
// A graph stop owns its own lifecycle: dependents must not start, and the
|
|
183
302
|
// graph's own summary reports what had already completed. Stopping the
|
|
184
303
|
// nodes one by one first would let the runner dispatch the next layer.
|
|
185
|
-
if (params.workflow !== undefined) {
|
|
304
|
+
if (params.all !== true && !params.id?.trim() && params.workflow !== undefined) {
|
|
186
305
|
const graph = runtime.workflows.get(params.workflow);
|
|
187
306
|
if (!graph) {
|
|
188
307
|
const known = [...runtime.workflows.keys()].map((id) => `#${id}`).join(", ");
|
|
@@ -150,8 +150,9 @@ export function formatSubagentWidgetLines(
|
|
|
150
150
|
): string[] {
|
|
151
151
|
if (width <= 0) return [];
|
|
152
152
|
const graphIds = new Set(workflows.map((graph) => graph.id));
|
|
153
|
+
const visibleWorkflows = workflows.filter((graph) => graph.state !== "stopped");
|
|
153
154
|
const standalone = runs.filter((run) => (!run.workflow || !graphIds.has(run.workflow.workflowId)) && (isRunActiveStatus(run.status) || run.status === "failed"));
|
|
154
|
-
const groups =
|
|
155
|
+
const groups = visibleWorkflows.map((graph) => workflowGroup(graph, runs, theme, width, now));
|
|
155
156
|
if (standalone.length) {
|
|
156
157
|
const rows = standalone.map((run) => runRow(run, theme, width, now));
|
|
157
158
|
groups.push({ rows, priority: Math.min(...rows.map((row) => row.priority)) });
|
|
@@ -161,7 +162,7 @@ export function formatSubagentWidgetLines(
|
|
|
161
162
|
const counts = ["failed", "blocked", "interrupting", "running", "queued", "waiting"]
|
|
162
163
|
.map((state) => ({ state, count: states.filter((value) => value === state).length }))
|
|
163
164
|
.filter(({ count }) => count > 0).map(({ state, count }) => count + " " + state);
|
|
164
|
-
if (
|
|
165
|
+
if (visibleWorkflows.length) counts.push(visibleWorkflows.length + " workflow" + (visibleWorkflows.length === 1 ? "" : "s"));
|
|
165
166
|
const overview = theme.fg("accent", theme.bold("Subagents")) + theme.fg("dim", " " + counts.join(SEPARATOR));
|
|
166
167
|
return renderBoard(groups, theme, width, overview);
|
|
167
168
|
}
|
package/workflows/code-review.md
CHANGED
|
@@ -26,27 +26,27 @@ Run it with `subagent_workflow({ "workflow": "code-review" })`, or by path with
|
|
|
26
26
|
"nodes": [
|
|
27
27
|
{
|
|
28
28
|
"id": "map",
|
|
29
|
-
"agent": "
|
|
29
|
+
"agent": "reviewer",
|
|
30
30
|
"isolation": "shared",
|
|
31
31
|
"task": "Read git diff and git status to establish what changed for a review of the working tree against HEAD, including staged and untracked changes. Stay read-only; do not edit files, install dependencies, or change Git state. Report: the changed files, what each change is trying to do, the call sites and tests that depend on them, and the checks the repository defines (package.json scripts, CI config, README verification line). Cite path:line for everything. Do not review quality yet."
|
|
32
32
|
},
|
|
33
33
|
{
|
|
34
34
|
"id": "correctness",
|
|
35
|
-
"agent": "
|
|
35
|
+
"agent": "reviewer",
|
|
36
36
|
"isolation": "shared",
|
|
37
|
-
"task": "You are the correctness reviewer. Using this map:\n\n{{map}}\n\nRead the changed code yourself and report what is wrong: logic errors, unhandled cases, broken invariants, missing tests that would catch a real failure. For each finding give path:line, what breaks,
|
|
37
|
+
"task": "You are the correctness reviewer. Using this map:\n\n{{map}}\n\nRead the changed code yourself and report what is wrong: logic errors, unhandled cases, broken invariants, missing tests that would catch a real failure. For each finding give path:line, what breaks, the concrete input or state that breaks it, and the smallest change that fixes it. Do not edit any file. Do not report style preferences.",
|
|
38
38
|
"dependsOn": ["map"]
|
|
39
39
|
},
|
|
40
40
|
{
|
|
41
41
|
"id": "risk",
|
|
42
|
-
"agent": "
|
|
42
|
+
"agent": "reviewer",
|
|
43
43
|
"isolation": "shared",
|
|
44
44
|
"task": "You are the risk reviewer, with a different lens from the correctness reviewer. Using this map:\n\n{{map}}\n\nLook for what this change breaks outside its own diff: migrations and backward compatibility, concurrency and ordering, error paths, resource lifetime, security and data loss, and behaviour other modules rely on. Give path:line for each risk and say how likely it is to bite. Do not edit any file.",
|
|
45
45
|
"dependsOn": ["map"]
|
|
46
46
|
},
|
|
47
47
|
{
|
|
48
48
|
"id": "confirm",
|
|
49
|
-
"agent": "
|
|
49
|
+
"agent": "critic",
|
|
50
50
|
"isolation": "shared",
|
|
51
51
|
"task": "Two reviewers reported findings. Your job is to try to disprove them, not to agree.\n\nCorrectness findings:\n{{correctness}}\n\nRisk findings:\n{{risk}}\n\nFor each finding, look for a counterexample in callers, invariants, and tests. Run a safe focused reproduction when needed and available. Do not edit files, install dependencies, or change Git state. Classify it as reproduced (command and result), source-supported (code evidence, not executed), disproved (counterevidence), or unverified (missing evidence). Return surviving findings with severity and the evidence that would falsify them.",
|
|
52
52
|
"dependsOn": ["correctness", "risk"]
|