oira666_pi-subagent 0.7.1 → 0.7.3
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 +1 -1
- package/docs/usage.md +4 -2
- package/extension/async-jobs.ts +15 -2
- package/extension/completion.ts +27 -24
- package/extension/events.ts +8 -2
- package/extension/execution.ts +9 -1
- package/extension/interrupt.ts +125 -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 +6 -0
- package/extension/stop-tool.ts +6 -2
- package/extension/usage.ts +2 -1
- package/index.ts +2 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -162,7 +162,7 @@ A live single line above the editor shows `Running N: Name elapsed · Name elaps
|
|
|
162
162
|
|
|
163
163
|
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
164
|
|
|
165
|
-
The `WITH SUBS`
|
|
165
|
+
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
166
|
|
|
167
167
|
## Development
|
|
168
168
|
|
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
|
@@ -60,6 +60,7 @@ export function releaseCompletionDelivery(state: ExtensionState, token: string,
|
|
|
60
60
|
if (generation !== state.lifecycleGeneration || state.pendingCompletionDeliveries?.get(token) !== generation) return;
|
|
61
61
|
const count = pendingCount(state);
|
|
62
62
|
state.pendingCompletionDeliveries.delete(token);
|
|
63
|
+
state.pendingCompletionInterrupts?.delete(token);
|
|
63
64
|
recordCount(state, count - 1);
|
|
64
65
|
emitBackgroundCount(state);
|
|
65
66
|
}
|
|
@@ -98,8 +99,18 @@ export function registerAsyncDeliveryEvents(state: ExtensionState): void {
|
|
|
98
99
|
});
|
|
99
100
|
}
|
|
100
101
|
|
|
101
|
-
export function notifyLead(
|
|
102
|
-
|
|
102
|
+
export function notifyLead(
|
|
103
|
+
state: ExtensionState,
|
|
104
|
+
content: string,
|
|
105
|
+
generation = state.lifecycleGeneration,
|
|
106
|
+
interruptEpoch = state.interruptEpoch ?? 0,
|
|
107
|
+
): void {
|
|
108
|
+
if (
|
|
109
|
+
!state.sessionActive ||
|
|
110
|
+
state.lifecycleGeneration !== generation ||
|
|
111
|
+
(state.interruptEpoch ?? 0) !== interruptEpoch
|
|
112
|
+
)
|
|
113
|
+
return;
|
|
103
114
|
// Custom messages use Pi\'s distinct customMessageBg instead of userMessageBg.
|
|
104
115
|
state.pi.sendMessage(
|
|
105
116
|
{ customType: SUBAGENT_MESSAGE_TYPE, content, display: true, details: undefined },
|
|
@@ -118,6 +129,7 @@ export function startBackground(
|
|
|
118
129
|
cleanup?: () => Promise<void>,
|
|
119
130
|
): void {
|
|
120
131
|
const generation = state.lifecycleGeneration;
|
|
132
|
+
const interruptEpoch = state.interruptEpoch ?? 0;
|
|
121
133
|
const controller = new AbortController();
|
|
122
134
|
const job: BackgroundJob = { names, controller, promise: Promise.resolve() };
|
|
123
135
|
state.backgroundJobs.set(key, job);
|
|
@@ -137,6 +149,7 @@ export function startBackground(
|
|
|
137
149
|
state,
|
|
138
150
|
`Subagent job ${names.join(", ") || key} failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
139
151
|
generation,
|
|
152
|
+
interruptEpoch,
|
|
140
153
|
);
|
|
141
154
|
})
|
|
142
155
|
.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,30 @@ 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
|
+
try {
|
|
51
|
+
const silent = interrupted || interruptEpoch !== (state.interruptEpoch ?? 0) || explicitlyStopped(state, result);
|
|
52
|
+
state.pi.sendMessage(
|
|
53
|
+
{
|
|
54
|
+
customType: SUBAGENT_COMPLETION_TYPE,
|
|
55
|
+
content: silent ? `Subagent ${result.name} stopped as requested.` : content,
|
|
56
|
+
display: !silent,
|
|
57
|
+
details: Object.assign(details, { asyncDeliveryId: deliveryId }, silent ? { silentStopped: true } : {}),
|
|
58
|
+
},
|
|
59
|
+
silent ? { triggerTurn: false } : { deliverAs: "steer", triggerTurn: true },
|
|
60
|
+
);
|
|
61
|
+
delivered = true;
|
|
62
|
+
// Interrupted deliveries are durable accounting only, with no continuation to await.
|
|
63
|
+
if (silent) releaseCompletionDelivery(state, deliveryId, generation);
|
|
64
|
+
// Normal sendMessage returns before queued messages are consumed.
|
|
65
|
+
// Keep its interrupt callback until message_start releases the delivery.
|
|
66
|
+
} catch (error) {
|
|
67
|
+
releaseCompletionDelivery(state, deliveryId, generation);
|
|
68
|
+
console.error("[pi-subagent] Completion delivery failed:", error);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
(state.pendingCompletionInterrupts ??= new Map()).set(deliveryId, () => deliver(true));
|
|
72
|
+
scheduleSessionTask(state, () => deliver(), 0);
|
|
70
73
|
}
|
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,125 @@
|
|
|
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 = event.prompt === pending?.prompt ? pending.interruptEpoch : undefined;
|
|
110
|
+
if (startingResumeEpoch !== undefined) state.pendingAutomaticResume = undefined;
|
|
111
|
+
});
|
|
112
|
+
state.pi.on("agent_start", (_event, ctx) => {
|
|
113
|
+
const epoch = startingResumeEpoch;
|
|
114
|
+
startingResumeEpoch = undefined;
|
|
115
|
+
// Pi can await prompt preflight after submission. Abort at loop entry if Escape
|
|
116
|
+
// canceled that automatic prompt while it was outside the active agent loop.
|
|
117
|
+
if (epoch !== undefined && epoch !== (state.interruptEpoch ?? 0)) ctx.abort();
|
|
118
|
+
});
|
|
119
|
+
state.pi.on("session_shutdown", () => {
|
|
120
|
+
startingResumeEpoch = undefined;
|
|
121
|
+
state.pendingAutomaticResume = undefined;
|
|
122
|
+
unsubscribe();
|
|
123
|
+
unsubscribe = () => {};
|
|
124
|
+
});
|
|
125
|
+
}
|
|
@@ -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
|
@@ -19,6 +19,10 @@ export interface ExtensionState extends DelegationDepthConfig {
|
|
|
19
19
|
backgroundJobs: Map<string, BackgroundJob>;
|
|
20
20
|
/** Delivery token -> session generation, retained until the completion is consumed. */
|
|
21
21
|
pendingCompletionDeliveries: Map<string, number>;
|
|
22
|
+
pendingCompletionInterrupts: Map<string, () => void>;
|
|
23
|
+
interruptEpoch: number;
|
|
24
|
+
onSessionReadyForInterrupt?: (ctx: SessionContext) => void;
|
|
25
|
+
pendingAutomaticResume?: { prompt: string; interruptEpoch: number };
|
|
22
26
|
pi: ExtensionAPI;
|
|
23
27
|
settings?: SubagentSettings;
|
|
24
28
|
sessionSettings?: SubagentSettings;
|
|
@@ -88,6 +92,8 @@ export function createExtensionState(pi: ExtensionAPI): ExtensionState {
|
|
|
88
92
|
approvedProjectAgentDirsForSession: new Set(),
|
|
89
93
|
backgroundJobs: new Map(),
|
|
90
94
|
pendingCompletionDeliveries: new Map(),
|
|
95
|
+
pendingCompletionInterrupts: new Map(),
|
|
96
|
+
interruptEpoch: 0,
|
|
91
97
|
activeSubagents: new Map(),
|
|
92
98
|
activeResumeNames: new Set(),
|
|
93
99
|
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);
|