oira666_pi-subagent 0.7.1 → 0.7.4
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/README.md +7 -3
- package/docs/usage.md +4 -2
- package/extension/async-jobs.ts +44 -2
- package/extension/completion.ts +31 -24
- package/extension/events.ts +8 -2
- package/extension/execution.ts +9 -1
- package/extension/interrupt.ts +126 -0
- package/extension/resume-offer.ts +13 -3
- package/extension/runtime.ts +29 -14
- package/extension/scheduler.ts +5 -0
- package/extension/session-start.ts +4 -0
- package/extension/state.ts +7 -0
- package/extension/stop-tool.ts +6 -2
- package/extension/usage.ts +2 -1
- package/index.ts +2 -0
- package/package.json +11 -10
- package/resume.ts +2 -2
package/README.md
CHANGED
|
@@ -4,7 +4,9 @@ Delegate tasks to agents running in separate Pi processes. Each worker has its o
|
|
|
4
4
|
|
|
5
5
|
Launches return immediately. Completion and worker messages arrive as steering that wakes an idle lead.
|
|
6
6
|
|
|
7
|
-
Requires Pi
|
|
7
|
+
Requires Pi 1.4.0 or newer, using the `@earendil-works` SDK packages. Only the latest npm Pi release is tested.
|
|
8
|
+
|
|
9
|
+
Tested against Pi 1.4.0
|
|
8
10
|
|
|
9
11
|
## Install
|
|
10
12
|
|
|
@@ -162,7 +164,7 @@ A live single line above the editor shows `Running N: Name elapsed · Name elaps
|
|
|
162
164
|
|
|
163
165
|
A worker that has settled its own turn but still has descendants reports `Idle, waiting for children.` to the lead via steering, followed by its own last answer. While live it counts toward the cap. If parked, its process exits and the root broker later resumes its saved context. `Finished` means the whole subtree has settled, not just the worker's own turn.
|
|
164
166
|
|
|
165
|
-
The `WITH SUBS`
|
|
167
|
+
The single-line dim `WITH SUBS` widget below the editor includes recursive worker usage. It appears only after at least one subagent has been used; no usage summary is added to the status footer. Resuming a named worker adds usage without increasing the unique-worker count. See [usage accounting](docs/usage.md) for programmatic results.
|
|
166
168
|
|
|
167
169
|
## Development
|
|
168
170
|
|
|
@@ -171,7 +173,9 @@ npm ci
|
|
|
171
173
|
npm run check
|
|
172
174
|
```
|
|
173
175
|
|
|
174
|
-
|
|
176
|
+
`npm test` first installs the four declared Pi SDK packages at `@latest` with `--save-dev --ignore-scripts`, then typechecks before running tests. `npm run check` uses that same path and also checks formatting and file size. Network access is required, and a newer Pi release can update `package.json` and `package-lock.json`. Keep those changes together.
|
|
177
|
+
|
|
178
|
+
Tests use the real SDK packages installed as development dependencies. SDK/loader integration tests exercise extension loading and argument validation. Terminal rendering tests use test themes, including ANSI styling, width limits and theme invalidation. They do not verify every installed theme or a live interactive terminal. Prompt guidance tests check generated text, not model behavior. No host loader or permissive type shims are needed. Run tests outside a delegated worker environment, or unset inherited `PI_SUBAGENT_*` storage and budget variables first.
|
|
175
179
|
|
|
176
180
|
Source organization:
|
|
177
181
|
|
package/docs/usage.md
CHANGED
|
@@ -16,6 +16,8 @@ Completion is a custom message with `customType: "subagent_completion"`, display
|
|
|
16
16
|
|
|
17
17
|
A worker that settles while descendants remain active sends `Idle, waiting for children.` and its own last answer as ordinary lead steering. That is not a final completion or a final usage total. If parked, the parent saves context and exits while the root broker preserves child execution. `Finished` still waits for subtree settlement.
|
|
18
18
|
|
|
19
|
+
In the interactive TUI, press Escape to interrupt the main agent and stop all running, queued, and parked subagent work, including detached descendants. This also works while the main agent is idle. Explicitly stopped workers do not automatically resume; their usage and spent budget still count. Escape keeps its normal behavior when there is no subagent work.
|
|
20
|
+
|
|
19
21
|
Do not run Bash `sleep` or polling loops while waiting for workers. Do other work, or end the turn and wait for completion steering. Keep the session open. When the lead is idle with running, queued, or parked work pending, the TUI shows an animated `Waiting for subagents - don't close the session` line above `Running N`. It disappears when the lead becomes busy or all worker work finishes; Pi's native `Working` indicator is unchanged.
|
|
20
22
|
|
|
21
23
|
## Result data
|
|
@@ -49,12 +51,12 @@ A tool-result-only cost accumulator misses async completions. Launch and messagi
|
|
|
49
51
|
|
|
50
52
|
Sum one lead stream's recursive worker totals. Do not also sum its children's streams, since recursive totals already include descendants. Lead-only model usage can be added separately. Repeated completions or overlapping summaries must not add the same worker run twice.
|
|
51
53
|
|
|
52
|
-
## Interactive
|
|
54
|
+
## Interactive usage widget
|
|
53
55
|
|
|
54
56
|
The `WITH SUBS` line includes the parent's billed session entries and recursive worker usage. Parent accounting follows Pi's session-statistics rules using `ctx.sessionManager.getEntries()`, including off-branch retries, compacted history, branch summaries, and tool-reported usage. Durable worker summaries add delegated cost once. Async delivery retains this accounting across idle periods and recovery.
|
|
55
57
|
|
|
56
58
|
The worker count tracks unique identities, not invocations. Messaging and named resumes add usage without increasing the count. Older compact history can recover identities from the name registry. This usage count is separate from budget reservations: launching reserves `1 + max_subagents_allowed` slots, including for queued launches, while messaging an existing worker allocates no new budget slot. A resumed idle worker still needs concurrency capacity. A cap increase can reserve additional descendant capacity from its original launcher.
|
|
57
59
|
|
|
58
|
-
Pi renders
|
|
60
|
+
Pi renders combined usage as a single dim widget line below the editor, clipped to the terminal width. It appears only after at least one worker has been used, including workers recovered from a saved session, and stays visible after workers finish. Empty sessions and sessions with only parent usage show no usage widget. The extension does not add this summary to the status footer. This is separate from the live `Running N` line above the editor, which shows names, elapsed times, overflow, and idle count using live handles and snapshots without session metadata or disk reads on ticks.
|
|
59
61
|
|
|
60
62
|
The main `index.ts` entry retains its default registration export and named exports `selectParentModelForSubagent`, `getSubagentsToolDescription`, `collectCombinedUsageStatusLine`, and `collectLiveUsageSummary`. Existing root entry-point imports remain supported.
|
package/extension/async-jobs.ts
CHANGED
|
@@ -34,6 +34,7 @@ function recordCount(state: ExtensionState, count: number): void {
|
|
|
34
34
|
|
|
35
35
|
/** Pending delivery is work too: a queued message has not started its continuation yet. */
|
|
36
36
|
function emitBackgroundCount(state: ExtensionState): void {
|
|
37
|
+
state.onBackgroundChanged?.();
|
|
37
38
|
if (state.currentDepth > 0) {
|
|
38
39
|
const running = state.backgroundJobs.size + pendingCount(state);
|
|
39
40
|
if (state.latestSessionCtx?.mode === "rpc") {
|
|
@@ -60,12 +61,40 @@ export function releaseCompletionDelivery(state: ExtensionState, token: string,
|
|
|
60
61
|
if (generation !== state.lifecycleGeneration || state.pendingCompletionDeliveries?.get(token) !== generation) return;
|
|
61
62
|
const count = pendingCount(state);
|
|
62
63
|
state.pendingCompletionDeliveries.delete(token);
|
|
64
|
+
state.pendingCompletionInterrupts?.delete(token);
|
|
63
65
|
recordCount(state, count - 1);
|
|
64
66
|
emitBackgroundCount(state);
|
|
65
67
|
}
|
|
66
68
|
|
|
67
69
|
/** Register once from registerSessionEvents. Starting an unrelated run must not drain this counter. */
|
|
68
70
|
export function registerAsyncDeliveryEvents(state: ExtensionState): void {
|
|
71
|
+
state.pi.on("agent_before_settle", async (event, ctx) => {
|
|
72
|
+
if (ctx.mode !== "print" && ctx.mode !== "json") return;
|
|
73
|
+
if (event.outcome === "aborted" || event.context.pendingMessages.length > 0) return;
|
|
74
|
+
const generation = state.lifecycleGeneration;
|
|
75
|
+
const signal = ctx.signal;
|
|
76
|
+
while (
|
|
77
|
+
state.sessionActive &&
|
|
78
|
+
generation === state.lifecycleGeneration &&
|
|
79
|
+
!signal?.aborted &&
|
|
80
|
+
(state.backgroundJobs.size > 0 || pendingCount(state) > 0)
|
|
81
|
+
) {
|
|
82
|
+
// Keep Pi's run open until delivery queues a continuation, not until the whole batch finishes.
|
|
83
|
+
let wake: (() => void) | undefined;
|
|
84
|
+
try {
|
|
85
|
+
const queued = await new Promise<boolean>((resolve) => {
|
|
86
|
+
state.onBackgroundChanged = (messageQueued = false) => resolve(messageQueued);
|
|
87
|
+
wake = () => resolve(false);
|
|
88
|
+
signal?.addEventListener("abort", wake, { once: true });
|
|
89
|
+
});
|
|
90
|
+
if (queued) return;
|
|
91
|
+
} finally {
|
|
92
|
+
state.onBackgroundChanged = undefined;
|
|
93
|
+
if (wake) signal?.removeEventListener("abort", wake);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
// Pi drains messages queued by sendMessage before settling, without an extra synthetic prompt.
|
|
97
|
+
});
|
|
69
98
|
state.pi.on("context", (event) => {
|
|
70
99
|
const messages = event.messages.filter(
|
|
71
100
|
(message) =>
|
|
@@ -98,8 +127,18 @@ export function registerAsyncDeliveryEvents(state: ExtensionState): void {
|
|
|
98
127
|
});
|
|
99
128
|
}
|
|
100
129
|
|
|
101
|
-
export function notifyLead(
|
|
102
|
-
|
|
130
|
+
export function notifyLead(
|
|
131
|
+
state: ExtensionState,
|
|
132
|
+
content: string,
|
|
133
|
+
generation = state.lifecycleGeneration,
|
|
134
|
+
interruptEpoch = state.interruptEpoch ?? 0,
|
|
135
|
+
): void {
|
|
136
|
+
if (
|
|
137
|
+
!state.sessionActive ||
|
|
138
|
+
state.lifecycleGeneration !== generation ||
|
|
139
|
+
(state.interruptEpoch ?? 0) !== interruptEpoch
|
|
140
|
+
)
|
|
141
|
+
return;
|
|
103
142
|
// Custom messages use Pi\'s distinct customMessageBg instead of userMessageBg.
|
|
104
143
|
state.pi.sendMessage(
|
|
105
144
|
{ customType: SUBAGENT_MESSAGE_TYPE, content, display: true, details: undefined },
|
|
@@ -108,6 +147,7 @@ export function notifyLead(state: ExtensionState, content: string, generation =
|
|
|
108
147
|
triggerTurn: true,
|
|
109
148
|
},
|
|
110
149
|
);
|
|
150
|
+
state.onBackgroundChanged?.(true);
|
|
111
151
|
}
|
|
112
152
|
|
|
113
153
|
export function startBackground(
|
|
@@ -118,6 +158,7 @@ export function startBackground(
|
|
|
118
158
|
cleanup?: () => Promise<void>,
|
|
119
159
|
): void {
|
|
120
160
|
const generation = state.lifecycleGeneration;
|
|
161
|
+
const interruptEpoch = state.interruptEpoch ?? 0;
|
|
121
162
|
const controller = new AbortController();
|
|
122
163
|
const job: BackgroundJob = { names, controller, promise: Promise.resolve() };
|
|
123
164
|
state.backgroundJobs.set(key, job);
|
|
@@ -137,6 +178,7 @@ export function startBackground(
|
|
|
137
178
|
state,
|
|
138
179
|
`Subagent job ${names.join(", ") || key} failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
139
180
|
generation,
|
|
181
|
+
interruptEpoch,
|
|
140
182
|
);
|
|
141
183
|
})
|
|
142
184
|
.finally(async () => {
|
package/extension/completion.ts
CHANGED
|
@@ -29,6 +29,7 @@ export function publishCompletion(
|
|
|
29
29
|
generation: number,
|
|
30
30
|
executionKey?: AsyncExecutionKey,
|
|
31
31
|
brokerJobId?: string,
|
|
32
|
+
interruptEpoch = state.interruptEpoch ?? 0,
|
|
32
33
|
): void {
|
|
33
34
|
if (!state.sessionActive || generation !== state.lifecycleGeneration) return;
|
|
34
35
|
const failed = isResultError(result);
|
|
@@ -43,28 +44,34 @@ export function publishCompletion(
|
|
|
43
44
|
brokerJobId ? { brokerJobId } : {},
|
|
44
45
|
);
|
|
45
46
|
const deliveryId = retainCompletionDelivery(state, generation);
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
()
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
|
|
47
|
+
let delivered = false;
|
|
48
|
+
const deliver = (interrupted = false) => {
|
|
49
|
+
if (state.pendingCompletionDeliveries.get(deliveryId) !== generation || (delivered && !interrupted)) return;
|
|
50
|
+
let messageQueued = false;
|
|
51
|
+
try {
|
|
52
|
+
const silent = interrupted || interruptEpoch !== (state.interruptEpoch ?? 0) || explicitlyStopped(state, result);
|
|
53
|
+
state.pi.sendMessage(
|
|
54
|
+
{
|
|
55
|
+
customType: SUBAGENT_COMPLETION_TYPE,
|
|
56
|
+
content: silent ? `Subagent ${result.name} stopped as requested.` : content,
|
|
57
|
+
display: !silent,
|
|
58
|
+
details: Object.assign(details, { asyncDeliveryId: deliveryId }, silent ? { silentStopped: true } : {}),
|
|
59
|
+
},
|
|
60
|
+
silent ? { triggerTurn: false } : { deliverAs: "steer", triggerTurn: true },
|
|
61
|
+
);
|
|
62
|
+
delivered = true;
|
|
63
|
+
messageQueued = !silent;
|
|
64
|
+
// Interrupted deliveries are durable accounting only, with no continuation to await.
|
|
65
|
+
if (silent) releaseCompletionDelivery(state, deliveryId, generation);
|
|
66
|
+
// Normal sendMessage returns before queued messages are consumed.
|
|
67
|
+
// Keep its interrupt callback until message_start releases the delivery.
|
|
68
|
+
} catch (error) {
|
|
69
|
+
releaseCompletionDelivery(state, deliveryId, generation);
|
|
70
|
+
console.error("[pi-subagent] Completion delivery failed:", error);
|
|
71
|
+
} finally {
|
|
72
|
+
state.onBackgroundChanged?.(messageQueued);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
(state.pendingCompletionInterrupts ??= new Map()).set(deliveryId, () => deliver(true));
|
|
76
|
+
scheduleSessionTask(state, () => deliver(), 0);
|
|
70
77
|
}
|
package/extension/events.ts
CHANGED
|
@@ -7,7 +7,12 @@ import { isSubagentToolName, subagentDetailsHaveErrors } from "../types.js";
|
|
|
7
7
|
import { decodeNestedBroadcast, forwardNestedBroadcast } from "./broadcast.js";
|
|
8
8
|
import { RESUME_INTERACTIVE_DELAY_MS } from "./models.js";
|
|
9
9
|
import { maybeOfferSubagentResume } from "./resume-offer.js";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
restoreModelAfterResumeFailure,
|
|
12
|
+
scheduleSessionTask,
|
|
13
|
+
sendAutomaticResumePrompt,
|
|
14
|
+
updateCombinedUsageStatus,
|
|
15
|
+
} from "./runtime.js";
|
|
11
16
|
import type { ExtensionState } from "./state.js";
|
|
12
17
|
|
|
13
18
|
export function registerSessionEvents(state: ExtensionState): void {
|
|
@@ -72,13 +77,14 @@ export function registerSessionEvents(state: ExtensionState): void {
|
|
|
72
77
|
state,
|
|
73
78
|
() => {
|
|
74
79
|
try {
|
|
75
|
-
state
|
|
80
|
+
sendAutomaticResumePrompt(state, prompt);
|
|
76
81
|
} catch (err) {
|
|
77
82
|
console.error("[pi-subagent] Failed to start deferred resume turn:", err);
|
|
78
83
|
void restoreModelAfterResumeFailure(state, ctx);
|
|
79
84
|
}
|
|
80
85
|
},
|
|
81
86
|
RESUME_INTERACTIVE_DELAY_MS,
|
|
87
|
+
true,
|
|
82
88
|
);
|
|
83
89
|
});
|
|
84
90
|
|
package/extension/execution.ts
CHANGED
|
@@ -185,6 +185,7 @@ export async function executeParallel(
|
|
|
185
185
|
extras,
|
|
186
186
|
});
|
|
187
187
|
const generation = state.lifecycleGeneration;
|
|
188
|
+
const interruptEpoch = state.interruptEpoch ?? 0;
|
|
188
189
|
const scheduler = schedulerFor(state);
|
|
189
190
|
const taskIds = new Map<number, number>();
|
|
190
191
|
try {
|
|
@@ -248,10 +249,17 @@ export async function executeParallel(
|
|
|
248
249
|
result,
|
|
249
250
|
generation,
|
|
250
251
|
extras?.jobId ? { jobId: extras.jobId, taskIndex: index } : undefined,
|
|
252
|
+
undefined,
|
|
253
|
+
interruptEpoch,
|
|
251
254
|
);
|
|
252
255
|
},
|
|
253
256
|
onLeadMessage: (index, task, message) =>
|
|
254
|
-
notifyLead(
|
|
257
|
+
notifyLead(
|
|
258
|
+
state,
|
|
259
|
+
`Message from subagent ${extras?.names?.[index] ?? task.agent}:\n${message}`,
|
|
260
|
+
generation,
|
|
261
|
+
interruptEpoch,
|
|
262
|
+
),
|
|
255
263
|
settings: state.settings,
|
|
256
264
|
namesFile: state.currentNamesFile || undefined,
|
|
257
265
|
intelligencePresets: state.intelligencePresets,
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { isKeyRelease, matchesKey } from "@earendil-works/pi-tui";
|
|
2
|
+
import { persistWorkerStops } from "../storage/worker-stops.js";
|
|
3
|
+
import { releaseCompletionDelivery } from "./async-jobs.js";
|
|
4
|
+
import { cachedSchedulerFor } from "./scheduler.js";
|
|
5
|
+
import { clearSyntheticResumeState, restoreModelAfterResumeFailure } from "./runtime.js";
|
|
6
|
+
import { stopBranches } from "./stop-tool.js";
|
|
7
|
+
import type { ExtensionState } from "./state.js";
|
|
8
|
+
|
|
9
|
+
/** Escape must reach detached workers even when the main agent has no active turn. */
|
|
10
|
+
export function registerSubagentInterrupt(state: ExtensionState): void {
|
|
11
|
+
let unsubscribe = () => {};
|
|
12
|
+
let startingResumeEpoch: number | undefined;
|
|
13
|
+
state.onSessionReadyForInterrupt = (ctx) => {
|
|
14
|
+
startingResumeEpoch = undefined;
|
|
15
|
+
unsubscribe();
|
|
16
|
+
unsubscribe = () => {};
|
|
17
|
+
if (ctx.mode !== "tui" || !ctx.hasUI || state.currentDepth !== 0) return;
|
|
18
|
+
const generation = state.lifecycleGeneration;
|
|
19
|
+
unsubscribe = ctx.ui.onTerminalInput((data) => {
|
|
20
|
+
if (
|
|
21
|
+
!state.sessionActive ||
|
|
22
|
+
state.lifecycleGeneration !== generation ||
|
|
23
|
+
isKeyRelease(data) ||
|
|
24
|
+
!matchesKey(data, "escape")
|
|
25
|
+
)
|
|
26
|
+
return;
|
|
27
|
+
// Also cancel an outstanding resume confirmation, even before plans are armed.
|
|
28
|
+
state.interruptEpoch = (state.interruptEpoch ?? 0) + 1;
|
|
29
|
+
const context = state.latestSessionCtx ?? ctx;
|
|
30
|
+
const scheduler = cachedSchedulerFor(state);
|
|
31
|
+
const deliveries = [...state.pendingCompletionDeliveries.keys()];
|
|
32
|
+
const names = new Set<string>();
|
|
33
|
+
let hasWork = !!(
|
|
34
|
+
state.backgroundJobs.size ||
|
|
35
|
+
state.activeSubagents.size ||
|
|
36
|
+
deliveries.length ||
|
|
37
|
+
state.pendingResumePlans.length ||
|
|
38
|
+
state.pendingInteractiveResumePrompt ||
|
|
39
|
+
state.pendingAutomaticResume
|
|
40
|
+
);
|
|
41
|
+
const errors: string[] = [];
|
|
42
|
+
const attempt = (operation: () => void) => {
|
|
43
|
+
try {
|
|
44
|
+
operation();
|
|
45
|
+
} catch (error) {
|
|
46
|
+
errors.push(error instanceof Error ? error.message : String(error));
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
// Gather local work before reading the ledger, so a disk error cannot hide local handles.
|
|
50
|
+
for (const entry of scheduler?.snapshot() ?? []) names.add(entry.name);
|
|
51
|
+
for (const worker of state.activeSubagents.values()) if (worker.name) names.add(worker.name);
|
|
52
|
+
for (const job of state.backgroundJobs.values()) for (const name of job.names) names.add(name);
|
|
53
|
+
for (const plan of state.pendingResumePlans)
|
|
54
|
+
for (const result of plan.details?.results ?? []) if (result.name) names.add(result.name);
|
|
55
|
+
attempt(() => {
|
|
56
|
+
// Include broker-owned descendants and parked parents, not just local handles.
|
|
57
|
+
for (const entry of scheduler?.treeStore?.snapshot() ?? []) {
|
|
58
|
+
if (["queued", "running", "parking", "suspended", "waking", "stopping"].includes(entry.status))
|
|
59
|
+
names.add(entry.name);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
hasWork ||= names.size > 0;
|
|
63
|
+
if (!hasWork && !errors.length) return;
|
|
64
|
+
try {
|
|
65
|
+
state.pendingInteractiveResumePrompt = null;
|
|
66
|
+
state.pendingResumePlans = [];
|
|
67
|
+
clearSyntheticResumeState(state);
|
|
68
|
+
attempt(() => {
|
|
69
|
+
if (!names.size) return;
|
|
70
|
+
const stopped = stopBranches(state, [...names]);
|
|
71
|
+
errors.push(...stopped.statuses.flatMap((status) => (status.error ? [status.error] : [])));
|
|
72
|
+
// Synchronous markers precede completion microtasks and automatic recovery.
|
|
73
|
+
persistWorkerStops(state.currentNamesFile, stopped.stoppedNames);
|
|
74
|
+
});
|
|
75
|
+
// Fallbacks are independent: a failed kill or ledger write must not skip other workers.
|
|
76
|
+
if (errors.length) {
|
|
77
|
+
for (const worker of state.activeSubagents.values()) attempt(() => worker.handle.kill?.());
|
|
78
|
+
for (const job of state.backgroundJobs.values()) attempt(() => job.controller.abort());
|
|
79
|
+
} else {
|
|
80
|
+
for (const worker of state.activeSubagents.values()) if (!worker.name) attempt(() => worker.handle.kill?.());
|
|
81
|
+
}
|
|
82
|
+
} finally {
|
|
83
|
+
// Abort first, clearing Pi's queued steering before replaying accounting without a turn.
|
|
84
|
+
attempt(() => context.abort());
|
|
85
|
+
for (const id of deliveries) {
|
|
86
|
+
attempt(() => state.pendingCompletionInterrupts?.get(id)?.());
|
|
87
|
+
releaseCompletionDelivery(state, id, generation);
|
|
88
|
+
}
|
|
89
|
+
void restoreModelAfterResumeFailure(state, context);
|
|
90
|
+
if (errors.length) context.ui.notify(`Failed to stop some subagent work: ${errors.join("; ")}`, "error");
|
|
91
|
+
}
|
|
92
|
+
// Preserve native Escape handling for dialogs, compaction, and the main editor.
|
|
93
|
+
return undefined;
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
state.pi.on("input", (event) => {
|
|
97
|
+
const pending = state.pendingAutomaticResume;
|
|
98
|
+
if (
|
|
99
|
+
event.source === "extension" &&
|
|
100
|
+
event.text === pending?.prompt &&
|
|
101
|
+
pending.interruptEpoch !== (state.interruptEpoch ?? 0)
|
|
102
|
+
) {
|
|
103
|
+
state.pendingAutomaticResume = undefined;
|
|
104
|
+
return { action: "handled" as const };
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
state.pi.on("before_agent_start", (event) => {
|
|
108
|
+
const pending = state.pendingAutomaticResume;
|
|
109
|
+
startingResumeEpoch =
|
|
110
|
+
event.messageType === "user" && pending && event.prompt === pending.prompt ? pending.interruptEpoch : undefined;
|
|
111
|
+
if (startingResumeEpoch !== undefined) state.pendingAutomaticResume = undefined;
|
|
112
|
+
});
|
|
113
|
+
state.pi.on("agent_start", (_event, ctx) => {
|
|
114
|
+
const epoch = startingResumeEpoch;
|
|
115
|
+
startingResumeEpoch = undefined;
|
|
116
|
+
// Pi can await prompt preflight after submission. Abort at loop entry if Escape
|
|
117
|
+
// canceled that automatic prompt while it was outside the active agent loop.
|
|
118
|
+
if (epoch !== undefined && epoch !== (state.interruptEpoch ?? 0)) ctx.abort();
|
|
119
|
+
});
|
|
120
|
+
state.pi.on("session_shutdown", () => {
|
|
121
|
+
startingResumeEpoch = undefined;
|
|
122
|
+
state.pendingAutomaticResume = undefined;
|
|
123
|
+
unsubscribe();
|
|
124
|
+
unsubscribe = () => {};
|
|
125
|
+
});
|
|
126
|
+
}
|
|
@@ -4,7 +4,7 @@ import { RESUME_MODEL_ID, RESUME_PROVIDER } from "../shared.js";
|
|
|
4
4
|
import type { SessionContext } from "./contracts.js";
|
|
5
5
|
import { getRestorableModel, RESUME_INTERACTIVE_DELAY_MS, SUBAGENT_FALLBACK_MODEL_ENV } from "./models.js";
|
|
6
6
|
import { ensureSubagentToolActive, hasCliInitialPrompt, isRpcMode } from "./policy.js";
|
|
7
|
-
import { restoreModelAfterResumeFailure, scheduleSessionTask } from "./runtime.js";
|
|
7
|
+
import { restoreModelAfterResumeFailure, scheduleSessionTask, sendAutomaticResumePrompt } from "./runtime.js";
|
|
8
8
|
import type { ExtensionState } from "./state.js";
|
|
9
9
|
|
|
10
10
|
export async function maybeOfferSubagentResume(
|
|
@@ -12,6 +12,9 @@ export async function maybeOfferSubagentResume(
|
|
|
12
12
|
ctx: SessionContext,
|
|
13
13
|
opts: { deferInteractivePrompt: boolean },
|
|
14
14
|
): Promise<void> {
|
|
15
|
+
const generation = state.lifecycleGeneration;
|
|
16
|
+
const interruptEpoch = state.interruptEpoch ?? 0;
|
|
17
|
+
const canceled = () => generation !== state.lifecycleGeneration || interruptEpoch !== (state.interruptEpoch ?? 0);
|
|
15
18
|
const restorableModel = getRestorableModel(ctx, state.settings);
|
|
16
19
|
if (restorableModel) {
|
|
17
20
|
state.lastRestorableModel = restorableModel;
|
|
@@ -31,6 +34,7 @@ export async function maybeOfferSubagentResume(
|
|
|
31
34
|
`The resumed session has ${plans.length === 1 ? "an" : String(plans.length)} unfinished subagent call${plans.length === 1 ? "" : "s"} (${totalTaskCount} task${totalTaskCount === 1 ? "" : "s"}). Resume from saved subagent sessions?`,
|
|
32
35
|
);
|
|
33
36
|
}
|
|
37
|
+
if (canceled()) return;
|
|
34
38
|
if (!shouldResume) {
|
|
35
39
|
if (ctx.model?.provider === RESUME_PROVIDER) {
|
|
36
40
|
if (restorableModel) {
|
|
@@ -67,7 +71,12 @@ export async function maybeOfferSubagentResume(
|
|
|
67
71
|
state.resumeModelRegistry = ctx.modelRegistry;
|
|
68
72
|
ensureSubagentToolActive(state.pi);
|
|
69
73
|
const resumeModel = ctx.modelRegistry.find(RESUME_PROVIDER, RESUME_MODEL_ID);
|
|
70
|
-
|
|
74
|
+
const switched = resumeModel && (await state.pi.setModel(resumeModel));
|
|
75
|
+
if (canceled()) {
|
|
76
|
+
if (generation === state.lifecycleGeneration && restorableModel) await state.pi.setModel(restorableModel);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (!switched) {
|
|
71
80
|
ctx.ui.notify("Failed to switch to synthetic subagent resume model.", "error");
|
|
72
81
|
await restoreModelAfterResumeFailure(state, ctx);
|
|
73
82
|
return;
|
|
@@ -91,13 +100,14 @@ export async function maybeOfferSubagentResume(
|
|
|
91
100
|
state,
|
|
92
101
|
() => {
|
|
93
102
|
try {
|
|
94
|
-
state
|
|
103
|
+
sendAutomaticResumePrompt(state, `Resuming ${totalTaskCount} subagents...`);
|
|
95
104
|
} catch (err) {
|
|
96
105
|
console.error("[pi-subagent] Failed to start resume turn after tree navigation:", err);
|
|
97
106
|
void restoreModelAfterResumeFailure(state, ctx);
|
|
98
107
|
}
|
|
99
108
|
},
|
|
100
109
|
RESUME_INTERACTIVE_DELAY_MS,
|
|
110
|
+
true,
|
|
101
111
|
);
|
|
102
112
|
}
|
|
103
113
|
}
|
package/extension/runtime.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { truncateToWidth } from "@earendil-works/pi-tui";
|
|
1
2
|
import { configuredEnv, loadSubagentSettings } from "../settings.js";
|
|
2
3
|
import * as path from "node:path";
|
|
3
4
|
import {
|
|
@@ -38,16 +39,28 @@ export function getParentModelForSubagent(state: ExtensionState, ctx: SessionCon
|
|
|
38
39
|
);
|
|
39
40
|
}
|
|
40
41
|
|
|
41
|
-
export function scheduleSessionTask(
|
|
42
|
+
export function scheduleSessionTask(
|
|
43
|
+
state: ExtensionState,
|
|
44
|
+
callback: () => void,
|
|
45
|
+
delayMs: number,
|
|
46
|
+
cancelOnInterrupt = false,
|
|
47
|
+
): void {
|
|
42
48
|
const expectedGeneration = state.lifecycleGeneration;
|
|
49
|
+
const interruptEpoch = state.interruptEpoch ?? 0;
|
|
43
50
|
const timer = setTimeout(() => {
|
|
44
51
|
state.scheduledTasks.delete(timer);
|
|
45
52
|
if (!state.sessionActive || expectedGeneration !== state.lifecycleGeneration) return;
|
|
53
|
+
if (cancelOnInterrupt && interruptEpoch !== (state.interruptEpoch ?? 0)) return;
|
|
46
54
|
callback();
|
|
47
55
|
}, delayMs);
|
|
48
56
|
state.scheduledTasks.add(timer);
|
|
49
57
|
}
|
|
50
58
|
|
|
59
|
+
export function sendAutomaticResumePrompt(state: ExtensionState, prompt: string): void {
|
|
60
|
+
state.pendingAutomaticResume = { prompt, interruptEpoch: state.interruptEpoch ?? 0 };
|
|
61
|
+
state.pi.sendUserMessage(prompt, { deliverAs: "steer" });
|
|
62
|
+
}
|
|
63
|
+
|
|
51
64
|
export async function restoreVisibleModelForResume(
|
|
52
65
|
state: ExtensionState,
|
|
53
66
|
expectedGeneration = state.lifecycleGeneration,
|
|
@@ -126,23 +139,25 @@ export async function restoreModelAfterResumeFailure(
|
|
|
126
139
|
}
|
|
127
140
|
}
|
|
128
141
|
|
|
129
|
-
export function formatFooterStatusText(ctx: SessionContext, text: string): string {
|
|
130
|
-
return typeof ctx?.ui?.theme?.fg === "function" ? ctx.ui.theme.fg("dim", text) : text;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
142
|
export function updateCombinedUsageStatus(state: ExtensionState, ctx?: SessionContext): void {
|
|
134
143
|
const targetCtx = ctx ?? state.latestSessionCtx;
|
|
135
|
-
if (!targetCtx?.
|
|
144
|
+
if (targetCtx?.mode !== "tui" || !targetCtx.hasUI || typeof targetCtx.ui?.setWidget !== "function") return;
|
|
136
145
|
try {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
146
|
+
const line = state.disabled
|
|
147
|
+
? undefined
|
|
148
|
+
: collectCombinedUsageStatusLine(targetCtx, Array.from(state.activeSubagentUsageSummaries.values()), true);
|
|
149
|
+
targetCtx.ui.setWidget(
|
|
150
|
+
"subagent-usage",
|
|
151
|
+
line
|
|
152
|
+
? (_tui, theme) => ({
|
|
153
|
+
render: (width) => [theme.fg("dim", truncateToWidth(line, Math.max(0, width), ""))],
|
|
154
|
+
invalidate() {},
|
|
155
|
+
})
|
|
156
|
+
: undefined,
|
|
157
|
+
{ placement: "belowEditor" },
|
|
158
|
+
);
|
|
144
159
|
} catch (err) {
|
|
145
|
-
console.error("[pi-subagent] Failed to update combined subagent
|
|
160
|
+
console.error("[pi-subagent] Failed to update combined subagent usage widget:", err);
|
|
146
161
|
}
|
|
147
162
|
}
|
|
148
163
|
|
package/extension/scheduler.ts
CHANGED
|
@@ -56,6 +56,11 @@ export function schedulerFor(state: ExtensionState): WorkerScheduler {
|
|
|
56
56
|
return scheduler;
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
/** Input handling must not initialize a scheduler in sessions without workers. */
|
|
60
|
+
export function cachedSchedulerFor(state: ExtensionState): WorkerScheduler | undefined {
|
|
61
|
+
return schedulers.get(state);
|
|
62
|
+
}
|
|
63
|
+
|
|
59
64
|
/** UI reads must not initialize schedulers or touch the filesystem. */
|
|
60
65
|
export function cachedBrokerEndpoint(state: ExtensionState) {
|
|
61
66
|
return schedulers.get(state)?.brokerEndpoint;
|
|
@@ -43,6 +43,7 @@ export function registerSessionLifecycle(state: ExtensionState): void {
|
|
|
43
43
|
state.sessionActive = false;
|
|
44
44
|
state.lifecycleGeneration += 1;
|
|
45
45
|
state.pendingCompletionDeliveries.clear();
|
|
46
|
+
state.pendingCompletionInterrupts.clear();
|
|
46
47
|
await shutdownScheduler(state);
|
|
47
48
|
await stopBackgroundJobs(state);
|
|
48
49
|
state.sessionActive = true;
|
|
@@ -69,6 +70,7 @@ export function registerSessionLifecycle(state: ExtensionState): void {
|
|
|
69
70
|
state.canDelegate = !state.disabled && state.canDelegate;
|
|
70
71
|
state.maxTasksPerCall =
|
|
71
72
|
parseNonNegativeInt(configuredEnv(SUBAGENT_MAX_TASKS_PER_CALL_ENV, state.settings)) ?? DEFAULT_MAX_TASKS_PER_CALL;
|
|
73
|
+
state.pendingAutomaticResume = undefined;
|
|
72
74
|
state.currentBudget = undefined;
|
|
73
75
|
state.budgetSetupError = undefined;
|
|
74
76
|
try {
|
|
@@ -124,6 +126,7 @@ export function registerSessionLifecycle(state: ExtensionState): void {
|
|
|
124
126
|
state.pendingResumePlans = [];
|
|
125
127
|
state.pendingInteractiveResumePrompt = null;
|
|
126
128
|
state.modelToRestoreAfterResume = undefined;
|
|
129
|
+
state.onSessionReadyForInterrupt?.(ctx);
|
|
127
130
|
updateCombinedUsageStatus(state, ctx);
|
|
128
131
|
try {
|
|
129
132
|
// Always repair sessions left on the synthetic resume model, even in
|
|
@@ -225,6 +228,7 @@ export function registerSessionLifecycle(state: ExtensionState): void {
|
|
|
225
228
|
state.sessionActive = false;
|
|
226
229
|
state.lifecycleGeneration += 1;
|
|
227
230
|
state.pendingCompletionDeliveries.clear();
|
|
231
|
+
state.pendingCompletionInterrupts.clear();
|
|
228
232
|
if (parking) detachBrokerJobs(state);
|
|
229
233
|
else {
|
|
230
234
|
await shutdownScheduler(state);
|
package/extension/state.ts
CHANGED
|
@@ -17,8 +17,13 @@ import type { BackgroundJob } from "./async-jobs.js";
|
|
|
17
17
|
|
|
18
18
|
export interface ExtensionState extends DelegationDepthConfig {
|
|
19
19
|
backgroundJobs: Map<string, BackgroundJob>;
|
|
20
|
+
onBackgroundChanged?: (messageQueued?: boolean) => void;
|
|
20
21
|
/** Delivery token -> session generation, retained until the completion is consumed. */
|
|
21
22
|
pendingCompletionDeliveries: Map<string, number>;
|
|
23
|
+
pendingCompletionInterrupts: Map<string, () => void>;
|
|
24
|
+
interruptEpoch: number;
|
|
25
|
+
onSessionReadyForInterrupt?: (ctx: SessionContext) => void;
|
|
26
|
+
pendingAutomaticResume?: { prompt: string; interruptEpoch: number };
|
|
22
27
|
pi: ExtensionAPI;
|
|
23
28
|
settings?: SubagentSettings;
|
|
24
29
|
sessionSettings?: SubagentSettings;
|
|
@@ -88,6 +93,8 @@ export function createExtensionState(pi: ExtensionAPI): ExtensionState {
|
|
|
88
93
|
approvedProjectAgentDirsForSession: new Set(),
|
|
89
94
|
backgroundJobs: new Map(),
|
|
90
95
|
pendingCompletionDeliveries: new Map(),
|
|
96
|
+
pendingCompletionInterrupts: new Map(),
|
|
97
|
+
interruptEpoch: 0,
|
|
91
98
|
activeSubagents: new Map(),
|
|
92
99
|
activeResumeNames: new Set(),
|
|
93
100
|
forcedErrorToolCallIds: new Set(),
|
package/extension/stop-tool.ts
CHANGED
|
@@ -36,7 +36,7 @@ const statusText = {
|
|
|
36
36
|
};
|
|
37
37
|
|
|
38
38
|
/** Tombstone the entire branch before signaling any process, including remote descendants. */
|
|
39
|
-
function stopBranches(
|
|
39
|
+
export function stopBranches(
|
|
40
40
|
state: ExtensionState,
|
|
41
41
|
names: string[],
|
|
42
42
|
): { statuses: StopSubagentStatus[]; stoppedNames: string[] } {
|
|
@@ -60,7 +60,11 @@ function stopBranches(
|
|
|
60
60
|
for (const worker of state.activeSubagents.values()) {
|
|
61
61
|
if (worker.name !== name) continue;
|
|
62
62
|
running = true;
|
|
63
|
-
|
|
63
|
+
try {
|
|
64
|
+
worker.handle.kill?.();
|
|
65
|
+
} catch {
|
|
66
|
+
// Still abort scheduler work if one process handle fails to terminate.
|
|
67
|
+
}
|
|
64
68
|
}
|
|
65
69
|
const previous = scheduler.stop(name);
|
|
66
70
|
if (running || previous === "started" || previous === "stopping") statuses.set(name, { name, status: "stopped" });
|
package/extension/usage.ts
CHANGED
|
@@ -236,6 +236,7 @@ export const persistedUsageCache = new WeakMap<object, PersistedUsageTotals>();
|
|
|
236
236
|
export function collectCombinedUsageStatusLine(
|
|
237
237
|
ctx: unknown,
|
|
238
238
|
liveSummaries: SubagentUsageSummary[] = [],
|
|
239
|
+
requireSubagents = false,
|
|
239
240
|
): string | undefined {
|
|
240
241
|
const manager = isRecord(ctx) && isRecord(ctx.sessionManager) ? ctx.sessionManager : undefined;
|
|
241
242
|
const canReadEntries = typeof manager?.getEntries === "function" || typeof manager?.getBranch === "function";
|
|
@@ -345,5 +346,5 @@ export function collectCombinedUsageStatusLine(
|
|
|
345
346
|
...(subagents.subagentIds ?? []).map((id) => persisted.registeredNames?.aliases.get(id) ?? id),
|
|
346
347
|
]).size
|
|
347
348
|
: subagents.subagentCount;
|
|
348
|
-
return formatCombinedUsageStatusLine(parentUsage, uniqueCount);
|
|
349
|
+
return requireSubagents && uniqueCount === 0 ? undefined : formatCombinedUsageStatusLine(parentUsage, uniqueCount);
|
|
349
350
|
}
|
package/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
2
2
|
import { subagentDisabled } from "./runner/extension-policy.js";
|
|
3
3
|
import { registerSettingsCommands } from "./extension/settings-commands.js";
|
|
4
4
|
import { registerSessionEvents } from "./extension/events.js";
|
|
5
|
+
import { registerSubagentInterrupt } from "./extension/interrupt.js";
|
|
5
6
|
import { registerActivityWidget } from "./extension/activity-widget.js";
|
|
6
7
|
import { registerSubagentExpandCommand } from "./extension/expand-command.js";
|
|
7
8
|
import { registerMessageSubagentCommand } from "./extension/message-command.js";
|
|
@@ -31,6 +32,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
31
32
|
registerResumeProvider(state);
|
|
32
33
|
registerSessionLifecycle(state);
|
|
33
34
|
registerSessionEvents(state);
|
|
35
|
+
registerSubagentInterrupt(state);
|
|
34
36
|
registerPromptHook(state);
|
|
35
37
|
registerTools(state);
|
|
36
38
|
registerSubagentExpandCommand(state);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oira666_pi-subagent",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
4
4
|
"description": "Subagent extension for Pi coding agent. Delegate tasks to specialized agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.ts",
|
|
@@ -55,29 +55,30 @@
|
|
|
55
55
|
},
|
|
56
56
|
"license": "MIT",
|
|
57
57
|
"scripts": {
|
|
58
|
+
"pretest": "npm install --save-dev --ignore-scripts @earendil-works/pi-agent-core@latest @earendil-works/pi-ai@latest @earendil-works/pi-coding-agent@latest @earendil-works/pi-tui@latest && npm run typecheck",
|
|
58
59
|
"test": "node --import tsx/esm --test test/*.test.ts",
|
|
59
60
|
"typecheck": "tsc --noEmit",
|
|
60
61
|
"format": "prettier --write \"*.ts\" \"{extension,runner,storage,types,ui,test}/**/*.ts\" \"scripts/*.mjs\" package.json tsconfig.json .prettierrc.json",
|
|
61
62
|
"format:check": "prettier --check \"*.ts\" \"{extension,runner,storage,types,ui,test}/**/*.ts\" \"scripts/*.mjs\" package.json tsconfig.json .prettierrc.json",
|
|
62
63
|
"check:size": "node scripts/check-size.mjs",
|
|
63
|
-
"check": "npm
|
|
64
|
+
"check": "npm test && npm run format:check && npm run check:size"
|
|
64
65
|
},
|
|
65
66
|
"devDependencies": {
|
|
67
|
+
"@earendil-works/pi-agent-core": "^1.4.0",
|
|
68
|
+
"@earendil-works/pi-ai": "^1.4.0",
|
|
69
|
+
"@earendil-works/pi-coding-agent": "^1.4.0",
|
|
70
|
+
"@earendil-works/pi-tui": "^1.4.0",
|
|
66
71
|
"@sinclair/typebox": ">=0.34.0",
|
|
67
|
-
"@earendil-works/pi-agent-core": "^0.87.1",
|
|
68
|
-
"@earendil-works/pi-ai": "^0.87.1",
|
|
69
|
-
"@earendil-works/pi-coding-agent": "^0.87.1",
|
|
70
|
-
"@earendil-works/pi-tui": "^0.87.1",
|
|
71
72
|
"@types/node": "^25.2.3",
|
|
72
73
|
"prettier": "^3.9.6",
|
|
73
74
|
"tsx": "^4.23.13",
|
|
74
75
|
"typescript": "^5.9.3"
|
|
75
76
|
},
|
|
76
77
|
"peerDependencies": {
|
|
77
|
-
"@earendil-works/pi-agent-core": "
|
|
78
|
-
"@earendil-works/pi-ai": "
|
|
79
|
-
"@earendil-works/pi-coding-agent": "
|
|
80
|
-
"@earendil-works/pi-tui": "
|
|
78
|
+
"@earendil-works/pi-agent-core": ">=1.4.0",
|
|
79
|
+
"@earendil-works/pi-ai": ">=1.4.0",
|
|
80
|
+
"@earendil-works/pi-coding-agent": ">=1.4.0",
|
|
81
|
+
"@earendil-works/pi-tui": ">=1.4.0",
|
|
81
82
|
"@sinclair/typebox": "*"
|
|
82
83
|
},
|
|
83
84
|
"peerDependenciesMeta": {
|
package/resume.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as path from "node:path";
|
|
2
2
|
import { DEFAULT_AGENT } from "./agents.js";
|
|
3
3
|
import { excludeStoppedWorkers } from "./storage/stopped-workers.js";
|
|
4
|
-
import type
|
|
4
|
+
import { getAgentDir, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { parseBoolean, RESUME_PROVIDER } from "./shared.js";
|
|
6
6
|
import { isBudgetAmount } from "./budget.js";
|
|
7
7
|
import { isRecord, sanitizePathComponent } from "./storage/values.js";
|
|
@@ -55,7 +55,7 @@ export function getDefaultSubagentSessionRoot(ctx: ExtensionContext): string {
|
|
|
55
55
|
return path.join(mainSessionDir, "subagents");
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
return path.join(getAgentDir(), "sessions", "subagents");
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
export function buildSubagentSessionDir(
|