oira666_pi-subagent 0.7.0 → 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 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` footer includes recursive worker usage. Resuming a named worker adds usage without increasing the unique-worker count. See [usage accounting](docs/usage.md) for programmatic results.
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 footer
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 this extension's combined usage through its normal `ctx.ui.setStatus()` footer line. 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.
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.
@@ -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(state: ExtensionState, content: string, generation = state.lifecycleGeneration): void {
102
- if (!state.sessionActive || state.lifecycleGeneration !== generation) return;
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 () => {
@@ -3,6 +3,7 @@ import { ackBrokerJob, listBrokerJobs, watchBrokerJob } from "../broker/files.js
3
3
  import { steerBrokerJob } from "../broker/commands.js";
4
4
  import { WORKER_TOKEN_ENV } from "../runner/tree-admission.js";
5
5
  import { branchEntries } from "../resume.js";
6
+ import { sessionEntryMessage } from "../storage/session-entries.js";
6
7
  import { buildSubagentDetails, DEFAULT_DELEGATION_MODE } from "../types.js";
7
8
  import { startBackground, notifyLead } from "./async-jobs.js";
8
9
  import { publishCompletion } from "./completion.js";
@@ -50,8 +51,9 @@ export function brokerProxyHandle(endpoint: BrokerEndpoint, spec: BrokerJobSpec)
50
51
  function consumedIds(ctx: SessionContext): Set<string> {
51
52
  const consumed = new Set<string>();
52
53
  for (const entry of branchEntries(ctx)) {
53
- if (entry.type === "message" && entry.message.role === "custom") {
54
- const details = entry.message.details;
54
+ const message = sessionEntryMessage(entry);
55
+ if (message?.role === "custom") {
56
+ const details = message.details;
55
57
  if (details && typeof details === "object" && "brokerJobId" in details && typeof details.brokerJobId === "string")
56
58
  consumed.add(details.brokerJobId);
57
59
  }
@@ -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
- scheduleSessionTask(
47
- state,
48
- () => {
49
- if (state.pendingCompletionDeliveries.get(deliveryId) !== generation) return;
50
- try {
51
- const silent = 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
- // sendMessage returns before queued messages are consumed. Only the
62
- // matching message_start handler may release a successful delivery.
63
- } catch (error) {
64
- releaseCompletionDelivery(state, deliveryId, generation);
65
- console.error("[pi-subagent] Completion delivery failed:", error);
66
- }
67
- },
68
- 0,
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
  }
@@ -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 { restoreModelAfterResumeFailure, scheduleSessionTask, updateCombinedUsageStatus } from "./runtime.js";
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.pi.sendUserMessage(prompt, { deliverAs: "steer" });
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
 
@@ -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(state, `Message from subagent ${extras?.names?.[index] ?? task.agent}:\n${message}`, generation),
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
- if (!resumeModel || !(await state.pi.setModel(resumeModel))) {
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.pi.sendUserMessage(`Resuming ${totalTaskCount} subagents...`, { deliverAs: "steer" });
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
  }
@@ -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(state: ExtensionState, callback: () => void, delayMs: number): void {
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?.ui) return;
144
+ if (targetCtx?.mode !== "tui" || !targetCtx.hasUI || typeof targetCtx.ui?.setWidget !== "function") return;
136
145
  try {
137
- if (state.disabled) {
138
- targetCtx.ui.setStatus?.("subagent-usage", undefined);
139
- return;
140
- }
141
- const line = collectCombinedUsageStatusLine(targetCtx, Array.from(state.activeSubagentUsageSummaries.values()));
142
- if (typeof targetCtx.ui.setStatus !== "function") return;
143
- targetCtx.ui.setStatus("subagent-usage", line ? formatFooterStatusText(targetCtx, line) : undefined);
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 status line:", err);
160
+ console.error("[pi-subagent] Failed to update combined subagent usage widget:", err);
146
161
  }
147
162
  }
148
163
 
@@ -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);
@@ -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(),
@@ -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
- worker.handle.kill?.();
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" });
@@ -1,4 +1,5 @@
1
1
  import * as fs from "node:fs";
2
+ import { sessionEntryMessage } from "../storage/session-entries.js";
2
3
  import { findPersistedNamesIdentity } from "../names.js";
3
4
  import { RESUME_PROVIDER } from "../shared.js";
4
5
  import { formatCombinedUsageStatusLine } from "../tree.js";
@@ -235,6 +236,7 @@ export const persistedUsageCache = new WeakMap<object, PersistedUsageTotals>();
235
236
  export function collectCombinedUsageStatusLine(
236
237
  ctx: unknown,
237
238
  liveSummaries: SubagentUsageSummary[] = [],
239
+ requireSubagents = false,
238
240
  ): string | undefined {
239
241
  const manager = isRecord(ctx) && isRecord(ctx.sessionManager) ? ctx.sessionManager : undefined;
240
242
  const canReadEntries = typeof manager?.getEntries === "function" || typeof manager?.getBranch === "function";
@@ -284,9 +286,8 @@ export function collectCombinedUsageStatusLine(
284
286
  addRawUsage(entry.usage, false);
285
287
  continue;
286
288
  }
287
- if (entry?.type !== "message") continue;
288
- const msg = entry.message;
289
- if (!isRecord(msg)) continue;
289
+ const msg = sessionEntryMessage(entry);
290
+ if (!msg) continue;
290
291
  if (
291
292
  (msg.role === "toolResult" && isSubagentToolName(msg.toolName)) ||
292
293
  (msg.role === "custom" && msg.customType === "subagent_completion")
@@ -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.0",
3
+ "version": "0.7.3",
4
4
  "description": "Subagent extension for Pi coding agent. Delegate tasks to specialized agents.",
5
5
  "type": "module",
6
6
  "main": "index.ts",
package/resume.ts CHANGED
@@ -5,6 +5,7 @@ import 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";
8
+ import { sessionEntryMessages } from "./storage/session-entries.js";
8
9
  import {
9
10
  asyncJobId,
10
11
  getNestedSubagentResults,
@@ -253,9 +254,7 @@ export function findLatestResumableSubagentCalls(ctx: ExtensionContext): Resumab
253
254
 
254
255
  // Completion messages may arrive long after the launch tool returned. Merge
255
256
  // by launch ID and task index rather than treating them as unrelated progress.
256
- for (const nested of getNestedSubagentResults(
257
- entries.flatMap((entry) => (entry.type === "message" ? [entry.message] : [])),
258
- )) {
257
+ for (const nested of getNestedSubagentResults(sessionEntryMessages(entries))) {
259
258
  const recorded = results.get(nested.toolCallId);
260
259
  if (recorded && asyncJobId(nested.details)) {
261
260
  results.set(nested.toolCallId, { ...recorded, details: nested.details, isError: nested.isError });
@@ -0,0 +1,32 @@
1
+ import { isRecord } from "./values.js";
2
+
3
+ /**
4
+ * Return the agent message a persisted session entry contributes.
5
+ *
6
+ * Pi stores `pi.sendMessage()` output (e.g. async subagent completions) as
7
+ * `custom_message` entries rather than `message` entries, and only converts
8
+ * them to `{ role: "custom" }` messages when it builds the LLM context. Code
9
+ * that scans raw session entries must apply the same conversion or it will
10
+ * never see those messages.
11
+ */
12
+ export function sessionEntryMessage(entry: unknown): Record<string, unknown> | undefined {
13
+ if (!isRecord(entry)) return undefined;
14
+ if (entry.type === "message") return isRecord(entry.message) ? entry.message : undefined;
15
+ if (entry.type !== "custom_message" || typeof entry.customType !== "string") return undefined;
16
+ const timestamp = typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : entry.timestamp;
17
+ return {
18
+ role: "custom",
19
+ customType: entry.customType,
20
+ content: entry.content ?? [],
21
+ display: entry.display,
22
+ details: entry.details,
23
+ timestamp,
24
+ };
25
+ }
26
+
27
+ export function sessionEntryMessages(entries: readonly unknown[]): Record<string, unknown>[] {
28
+ return entries.flatMap((entry) => {
29
+ const message = sessionEntryMessage(entry);
30
+ return message ? [message] : [];
31
+ });
32
+ }
package/ui/session.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { asRecord } from "./value.js";
4
+ import { sessionEntryMessages } from "../storage/session-entries.js";
4
5
 
5
6
  export function sessionFilesIn(sessionDir: string): string[] {
6
7
  try {
@@ -40,5 +41,5 @@ export function readSessionEntries(file: string): Record<string, unknown>[] {
40
41
  }
41
42
 
42
43
  export function readSessionMessages(file: string): unknown[] {
43
- return readSessionEntries(file).filter((entry) => entry.type === "message" && entry.message);
44
+ return sessionEntryMessages(readSessionEntries(file));
44
45
  }
package/ui/tree-build.ts CHANGED
@@ -236,7 +236,7 @@ function loadNestedNodesFromSession(sessionDir: string): TreeNode[] {
236
236
  const files = sessionFilesIn(sessionDir);
237
237
  const file = files[files.length - 1];
238
238
  if (!file) return [];
239
- const messages = readSessionMessages(file).map((entry) => asRecord(entry).message);
239
+ const messages = readSessionMessages(file);
240
240
  return buildNestedChildren({ exitCode: 0, messages }, true);
241
241
  }
242
242