@ferris1225/pi-subagents 7.0.4 → 7.0.6
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 +20 -0
- package/README.md +46 -22
- package/package.json +6 -2
- package/src/configuration/setup.ts +4 -2
- package/src/configuration/ui.ts +65 -68
- package/src/delegation/builtin-agents.ts +18 -33
- package/src/delegation/dispatch.ts +74 -166
- package/src/delegation/prompt.ts +35 -22
- package/src/execution/run-control.ts +0 -3
- package/src/execution/spawn.ts +2 -0
- package/src/isolation/cleanup.ts +1 -4
- package/src/isolation/worktree.ts +0 -3
- package/src/lifecycle/await-results.ts +4 -2
- package/src/lifecycle/cancellation.ts +61 -10
- package/src/lifecycle/dispatch-core.ts +0 -2
- package/src/lifecycle/runtime.ts +19 -6
- package/src/lifecycle/stop.ts +11 -5
- package/src/lifecycle/thread-lifecycle.ts +1 -1
- package/src/lifecycle/thread-restore.ts +1 -1
- package/src/lifecycle/tools.ts +8 -3
|
@@ -6,34 +6,70 @@
|
|
|
6
6
|
* user turn without waking the parent. Branch navigation abandons the
|
|
7
7
|
* conversation, so it stops everything and discards results. */
|
|
8
8
|
|
|
9
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
10
|
-
import
|
|
9
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
11
|
+
import { formatDuration, formatTaskSummary } from "../presentation/monitor.ts";
|
|
12
|
+
import { formatUsage } from "../presentation/format.ts";
|
|
13
|
+
import { CANCELLATION_STATS_ENTRY, type SubagentRuntime, type SubagentThread } from "./runtime.ts";
|
|
11
14
|
import { stopThreads } from "./stop.ts";
|
|
12
15
|
|
|
13
16
|
const cancellations = new WeakMap<SubagentRuntime, Promise<void>>();
|
|
14
17
|
|
|
18
|
+
interface CancellationOptions {
|
|
19
|
+
context?: Pick<ExtensionContext, "mode" | "ui">;
|
|
20
|
+
notifyParent?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function showTuiNotice(context: CancellationOptions["context"], text: string): void {
|
|
24
|
+
if (context?.mode !== "tui") return;
|
|
25
|
+
try {
|
|
26
|
+
context.ui.notify(text, "info");
|
|
27
|
+
} catch {
|
|
28
|
+
/* The terminal may have closed during cancellation. */
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function formatStoppedRun(runtime: SubagentRuntime, thread: SubagentThread): string {
|
|
33
|
+
const result = runtime.settledRuns.get(thread.id);
|
|
34
|
+
return [
|
|
35
|
+
`#${thread.id} ${thread.agentName}`,
|
|
36
|
+
formatDuration(thread.elapsedMs),
|
|
37
|
+
result?.model ? formatTaskSummary(result.model, 60, false) : undefined,
|
|
38
|
+
result && formatUsage(result.usage),
|
|
39
|
+
result?.integrationStatus && `worktree ${result.integrationStatus.replaceAll("_", " ")}`,
|
|
40
|
+
].filter(Boolean).join(" · ");
|
|
41
|
+
}
|
|
42
|
+
|
|
15
43
|
/** The child has settled and only Git integration and delivery remain. */
|
|
16
44
|
export function isSettlingThread(thread: SubagentThread): boolean {
|
|
17
45
|
return !thread.retired && thread.lifecycleOperation === "settle";
|
|
18
46
|
}
|
|
19
47
|
|
|
20
|
-
export function cancelActiveWork(
|
|
48
|
+
export function cancelActiveWork(
|
|
49
|
+
runtime: SubagentRuntime,
|
|
50
|
+
reason: string,
|
|
51
|
+
{ context, notifyParent = true }: CancellationOptions = {},
|
|
52
|
+
): Promise<void> {
|
|
21
53
|
const existing = cancellations.get(runtime);
|
|
22
54
|
if (existing) return existing;
|
|
23
55
|
runtime.suppressCompletions = true;
|
|
24
|
-
|
|
56
|
+
const deferredCount = notifyParent ? runtime.deferPendingCompletions() : 0;
|
|
25
57
|
runtime.discardCompletions();
|
|
26
58
|
const threads = [...runtime.threads.values()];
|
|
27
59
|
// Only a parent cancellation keeps finished work; an abandoned branch stops it.
|
|
28
|
-
const
|
|
29
|
-
|
|
60
|
+
const settlingThreads = notifyParent ? threads.filter(isSettlingThread) : [];
|
|
61
|
+
for (const thread of settlingThreads) runtime.deferRunDelivery(thread.id);
|
|
30
62
|
const activeThreads = threads
|
|
31
|
-
.filter((thread) => !thread.retired && !(
|
|
63
|
+
.filter((thread) => !thread.retired && !(notifyParent && isSettlingThread(thread))
|
|
32
64
|
&& (thread.lifecycleOperation !== undefined || ["queued", "running", "interrupting"].includes(thread.state)));
|
|
33
65
|
const threadIds = activeThreads.map((thread) => thread.id);
|
|
66
|
+
const runCount = `${threadIds.length} subagent run${threadIds.length === 1 ? "" : "s"}`;
|
|
34
67
|
const done = stopThreads(runtime, threadIds, reason).then(() => {
|
|
35
68
|
if (notifyParent && runtime.sessionActive && threadIds.length > 0) {
|
|
36
|
-
|
|
69
|
+
const stats = context?.mode === "tui"
|
|
70
|
+
? [`Stopped ${runCount}`, ...activeThreads.map((thread) => formatStoppedRun(runtime, thread))]
|
|
71
|
+
: undefined;
|
|
72
|
+
runtime.recordCancellation(threadIds, stats);
|
|
37
73
|
}
|
|
38
74
|
}).finally(() => {
|
|
39
75
|
runtime.discardCompletions();
|
|
@@ -41,12 +77,27 @@ export function cancelActiveWork(runtime: SubagentRuntime, reason: string, notif
|
|
|
41
77
|
cancellations.delete(runtime);
|
|
42
78
|
});
|
|
43
79
|
cancellations.set(runtime, done);
|
|
80
|
+
if (notifyParent && runtime.sessionActive) {
|
|
81
|
+
const notices: string[] = [];
|
|
82
|
+
if (threadIds.length) notices.push(`Stopping ${runCount} · ${threadIds.map((id) => `#${id}`).join(", ")}`);
|
|
83
|
+
for (const thread of settlingThreads) {
|
|
84
|
+
const progress = thread.isolation === "worktree" ? "applying worktree changes" : "finalizing its result";
|
|
85
|
+
notices.push(`#${thread.id} ${thread.agentName} finished and is ${progress}.`);
|
|
86
|
+
}
|
|
87
|
+
if (deferredCount) notices.push(`${deferredCount} completed subagent result${deferredCount === 1 ? "" : "s"} ready for your next message.`);
|
|
88
|
+
if (notices.length) showTuiNotice(context, notices.join("\n"));
|
|
89
|
+
}
|
|
44
90
|
return done;
|
|
45
91
|
}
|
|
46
92
|
|
|
47
93
|
export function registerCancellationHooks(pi: ExtensionAPI, runtime: SubagentRuntime): void {
|
|
48
|
-
pi.
|
|
49
|
-
|
|
94
|
+
pi.registerEntryRenderer<string[]>(CANCELLATION_STATS_ENTRY, (entry, _options, theme) => {
|
|
95
|
+
if (!Array.isArray(entry.data) || !entry.data.length) return undefined;
|
|
96
|
+
const [title, ...runs] = entry.data;
|
|
97
|
+
return new Text([theme.bold(title!), ...runs].join("\n"), 0, 0);
|
|
98
|
+
});
|
|
99
|
+
pi.on("agent_settled", (event, context) => event.aborted ? cancelActiveWork(runtime, "Parent run was cancelled.", { context }) : undefined);
|
|
100
|
+
pi.on("session_before_tree", () => cancelActiveWork(runtime, "Parent navigated to another conversation branch.", { notifyParent: false }));
|
|
50
101
|
// Pi emits session_shutdown for new/resume/fork/reload. The runtime's
|
|
51
102
|
// shutdown path stops children, retains recovery evidence, and disables delivery.
|
|
52
103
|
}
|
|
@@ -22,7 +22,6 @@ export interface DispatchCore {
|
|
|
22
22
|
startBackground: StartBackgroundInternal;
|
|
23
23
|
/** Stamp a terminal monitor state and toast the result once. */
|
|
24
24
|
finishRun: (runId: number, status: "done" | "failed", opts?: { silent?: boolean }) => void;
|
|
25
|
-
makeLiveHandler: (runId: number, generation?: number) => (event: SubagentLiveEvent) => void;
|
|
26
25
|
makeDetails: (mode: "single" | "parallel") => (results: SingleResult[]) => SubagentDetails;
|
|
27
26
|
}
|
|
28
27
|
|
|
@@ -145,7 +144,6 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
|
|
|
145
144
|
},
|
|
146
145
|
startBackground,
|
|
147
146
|
finishRun,
|
|
148
|
-
makeLiveHandler,
|
|
149
147
|
makeDetails,
|
|
150
148
|
};
|
|
151
149
|
}
|
package/src/lifecycle/runtime.ts
CHANGED
|
@@ -25,6 +25,8 @@ import type { RunControl, SteeringReceipt } from "../execution/run-control.ts";
|
|
|
25
25
|
import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
|
|
26
26
|
import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
|
|
27
27
|
|
|
28
|
+
export const CANCELLATION_STATS_ENTRY = "subagent-cancellation-stats";
|
|
29
|
+
|
|
28
30
|
export type ThreadState = "queued" | "running" | "interrupting" | "parked" | "completed" | "failed" | "stopped";
|
|
29
31
|
|
|
30
32
|
type ThreadLifecycleOperation = "stop" | "settle";
|
|
@@ -86,13 +88,13 @@ export interface SubagentRuntime {
|
|
|
86
88
|
/** Cancelling a parent must not wake it again with old child results. */
|
|
87
89
|
suppressCompletions: boolean;
|
|
88
90
|
discardCompletions: () => void;
|
|
89
|
-
/** Hand held completions to the next user turn
|
|
90
|
-
deferPendingCompletions: () =>
|
|
91
|
+
/** Hand held completions to the next user turn and return the number queued. */
|
|
92
|
+
deferPendingCompletions: () => number;
|
|
91
93
|
/** Route a run that already finished its child to the next user turn, even
|
|
92
94
|
* while completions are suppressed: its result is real and must not be lost. */
|
|
93
95
|
deferRunDelivery: (runId: number) => void;
|
|
94
|
-
/**
|
|
95
|
-
recordCancellation: (runIds: number[]) => void;
|
|
96
|
+
/** Show optional terminal stats and queue the cancellation receipt for the next user turn. */
|
|
97
|
+
recordCancellation: (runIds: number[], stats?: string[]) => void;
|
|
96
98
|
/** Resolves when the load-time durable restore pass has finished. Everything
|
|
97
99
|
* that answers "which threads exist" awaits it — the lookup tools, a fresh
|
|
98
100
|
* dispatch before it allocates a run id, and the restored-thread notice — so
|
|
@@ -160,13 +162,23 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
160
162
|
getToolInfos: () => pi.getAllTools(),
|
|
161
163
|
sessionActive: true,
|
|
162
164
|
suppressCompletions: false,
|
|
163
|
-
recordCancellation: (runIds) => {
|
|
165
|
+
recordCancellation: (runIds, stats) => {
|
|
164
166
|
if (!runIds.length) return;
|
|
167
|
+
let display = true;
|
|
168
|
+
if (stats) {
|
|
169
|
+
try {
|
|
170
|
+
// Custom entries render immediately and stay out of model context.
|
|
171
|
+
pi.appendEntry(CANCELLATION_STATS_ENTRY, stats);
|
|
172
|
+
display = false;
|
|
173
|
+
} catch {
|
|
174
|
+
/* Keep the next-turn receipt visible if the entry could not be saved. */
|
|
175
|
+
}
|
|
176
|
+
}
|
|
165
177
|
const targets = "runs " + runIds.map((id) => `#${id}`).join(", ");
|
|
166
178
|
pi.sendMessage({
|
|
167
179
|
customType: "subagent-cancelled",
|
|
168
180
|
content: `Parent cancellation stopped ${targets}. These runs are already cancelled; no further subagent_stop is needed. Do not restart cancelled work unless the user requests it. Partial edits and retained integration artifacts may remain; inspect them only if continuing the task.`,
|
|
169
|
-
display
|
|
181
|
+
display,
|
|
170
182
|
details: { runIds },
|
|
171
183
|
}, { deliverAs: "nextTurn", triggerTurn: false });
|
|
172
184
|
},
|
|
@@ -179,6 +191,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
179
191
|
const pending = [...runtime.completionBatcher.dispose(), ...heldCompletions];
|
|
180
192
|
heldCompletions = [];
|
|
181
193
|
sendNextTurn(pending);
|
|
194
|
+
return pending.length;
|
|
182
195
|
},
|
|
183
196
|
deferRunDelivery: (runId) => {
|
|
184
197
|
deferredRuns.add(runId);
|
package/src/lifecycle/stop.ts
CHANGED
|
@@ -63,10 +63,15 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
|
|
|
63
63
|
// An isolated stop may need the repository lane for final integration;
|
|
64
64
|
// cancelling all holders first prevents stop-all from waiting behind a
|
|
65
65
|
// later run that this same operation has not interrupted yet.
|
|
66
|
-
const
|
|
66
|
+
const interruptions = claimed.map(({ runId, thread, stopMessage, controller }) => {
|
|
67
67
|
const stopping = thread.control.stop(stopMessage).catch(() => undefined);
|
|
68
68
|
runtime.backgroundQueue.cancel(controller);
|
|
69
|
-
|
|
69
|
+
// Capture each duration as its child stops. A sibling may spend much
|
|
70
|
+
// longer integrating its worktree before we can remove this monitor row.
|
|
71
|
+
const captureElapsed = quiesced(stopping).then(() => {
|
|
72
|
+
thread.elapsedMs = monitor.getElapsedMs(runId) ?? thread.elapsedMs;
|
|
73
|
+
});
|
|
74
|
+
return { stopping, captureElapsed };
|
|
70
75
|
});
|
|
71
76
|
|
|
72
77
|
const stopped: string[] = [];
|
|
@@ -93,7 +98,8 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
|
|
|
93
98
|
// unkillable child can stall even process termination. Stop owns the
|
|
94
99
|
// lifecycle synchronously, so a stuck tail settles silently after we
|
|
95
100
|
// proceed; none of its late paths can publish a second result.
|
|
96
|
-
|
|
101
|
+
const interruption = interruptions[claimIndex]!;
|
|
102
|
+
await interruption.captureElapsed;
|
|
97
103
|
if (!(await quiesced(completion))) runtime.backgroundQueue.cancel(controller);
|
|
98
104
|
if (runtime.runControllers.get(runId) === controller) runtime.runControllers.delete(runId);
|
|
99
105
|
if (thread.queueController === controller) thread.queueController = undefined;
|
|
@@ -127,7 +133,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
|
|
|
127
133
|
exitCode: 1,
|
|
128
134
|
messages: [],
|
|
129
135
|
stderr: stopMessage,
|
|
130
|
-
usage: emptyUsage(),
|
|
136
|
+
usage: run?.usage ?? emptyUsage(),
|
|
131
137
|
model: run?.model,
|
|
132
138
|
thinking: run?.thinking,
|
|
133
139
|
projectCwd: thread.cwd,
|
|
@@ -186,7 +192,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
|
|
|
186
192
|
if (thread.durableId) await removeThreadRecord(runtime.configPath, thread.durableId, thread.cwd).catch(() => undefined);
|
|
187
193
|
// Returning from a bounded stop retires context, but cannot release a
|
|
188
194
|
// writer or phase lease while a child or Git tail can still change files.
|
|
189
|
-
void Promise.allSettled([
|
|
195
|
+
void Promise.allSettled([interruption.stopping, completion, finalizationCompletion]).then(() => {
|
|
190
196
|
if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
|
|
191
197
|
thread.lifecycleOperation = undefined;
|
|
192
198
|
}
|
|
@@ -140,7 +140,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
140
140
|
};
|
|
141
141
|
|
|
142
142
|
let thread!: SubagentThread;
|
|
143
|
-
const control = new RunControl(task,
|
|
143
|
+
const control = new RunControl(task, (phase) => {
|
|
144
144
|
if (runtime.threads.get(runId)?.generation !== generation || phase === "settled") return;
|
|
145
145
|
const state: ThreadState =
|
|
146
146
|
phase === "queued" || phase === "starting"
|
|
@@ -58,7 +58,7 @@ function createRestoredThread(
|
|
|
58
58
|
isolation: record.isolation,
|
|
59
59
|
worktree,
|
|
60
60
|
state,
|
|
61
|
-
control: new RunControl(record.task
|
|
61
|
+
control: new RunControl(record.task),
|
|
62
62
|
generationCompletion: Promise.resolve(),
|
|
63
63
|
lifecycleVersion: 0,
|
|
64
64
|
elapsedMs: record.elapsedMs,
|
package/src/lifecycle/tools.ts
CHANGED
|
@@ -237,7 +237,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
237
237
|
let fallbackReason = context === "auto" && !sourceFile ? "Retained session is unavailable." : undefined;
|
|
238
238
|
let copyDir: string | undefined;
|
|
239
239
|
try {
|
|
240
|
-
|
|
240
|
+
const config = await loadConfig(runtime.configPath);
|
|
241
241
|
if (sourceFile) {
|
|
242
242
|
const root = join(getProjectRoot(runtime.configPath, thread.cwd), "sessions");
|
|
243
243
|
await mkdir(root, { recursive: true });
|
|
@@ -253,8 +253,13 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
253
253
|
fallbackReason = "Retained session became unavailable before it could be copied.";
|
|
254
254
|
}
|
|
255
255
|
}
|
|
256
|
+
// Another dispatch can update the shared environment while the session
|
|
257
|
+
// is copied. Set this caller's context immediately before admission.
|
|
258
|
+
dispatchCore.setEnvironment({ ctx, config, agents: loadBuiltinAgents() });
|
|
256
259
|
if (_signal?.aborted) throw new Error("Follow-up cancelled before dispatch.");
|
|
257
|
-
if (thread.retired || thread.lifecycleOperation || thread.state !== "completed")
|
|
260
|
+
if (runtime.threads.get(thread.id) !== thread || thread.retired || thread.lifecycleOperation || thread.state !== "completed") {
|
|
261
|
+
throw new Error("The source run changed while the follow-up was prepared.");
|
|
262
|
+
}
|
|
258
263
|
const selectedContext = copyDir ? "session" : "summary";
|
|
259
264
|
const task = copyDir
|
|
260
265
|
? `Follow-up to run #${thread.id}:\n${params.message}`
|
|
@@ -273,7 +278,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
273
278
|
const blocks = await awaitRunResults(runtime, [result.runId], _signal, DEFAULT_MAX_RESULT_LINES, thread.cwd, (text) => {
|
|
274
279
|
onUpdate?.({ content: [{ type: "text", text }], details });
|
|
275
280
|
});
|
|
276
|
-
if (_signal?.aborted) await cancelActiveWork(runtime, "Parent run was cancelled.");
|
|
281
|
+
if (_signal?.aborted) await cancelActiveWork(runtime, "Parent run was cancelled.", { context: ctx });
|
|
277
282
|
else runtime.completeAwaitDelivery([result.runId]);
|
|
278
283
|
const settled = runtime.settledRuns.get(result.runId);
|
|
279
284
|
return {
|