oira666_pi-subagent 0.7.5 → 0.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -117,6 +117,12 @@ Delegate only when parallel work or context isolation saves enough effort to cov
117
117
 
118
118
  Do not use Bash `sleep` or polling loops to wait for workers. Continue useful work, or end the turn and let completion steering wake the lead. Keep the session open. While the lead is idle and worker work remains, an animated `Waiting for subagents - don't close the session` line appears above the unchanged `Running N` line. Active lead turns keep Pi's normal `Working` indicator.
119
119
 
120
+ ### Interrupting work
121
+
122
+ When Pi aborts the main agent, pi-subagent also stops running, queued, and parked subagent work, including detached descendants. This follows Pi's abort signal, not raw Escape keys. Escape handled by a focused overlay or dialog therefore stops no agents. Idle Escape retains Pi's normal behavior.
123
+
124
+ Press **Alt+W** to abort only the main agent and keep subagents running. This exception ends when that run settles; a later normal abort stops subagents again. Your terminal must send Alt/Option+W as a Meta key sequence, such as `ESC w`, or use the Kitty keyboard protocol. Kitty is not required for this binding. Pi 1.4.0 does not match modified Escape shortcuts, so Shift+Escape and Alt+Escape cannot be used for this action.
125
+
120
126
  ## Agent definitions
121
127
 
122
128
  There are no bundled agents. Without user-created definitions, every task uses the same default worker, with no agent-specific system prompt or instructions. It receives the parent's task text unchanged. Pi's normal system prompt and delegation limits still apply.
@@ -175,6 +181,8 @@ npm run check
175
181
 
176
182
  `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
183
 
184
+ `npm run test:evergreen` typechecks and runs all unit/integration tests in an isolated temporary workspace, then runs real-Pi delegation and saved-worker resume e2e tests. Set `EVERGREEN_E2E_MODEL` to an authenticated `provider/model[:thinking]`; `EVERGREEN_PI_BIN` selects the globally installed Pi executable (defaults to `pi` on PATH). E2E keeps sessions enabled, ignores stdin, and uses a disposable agent directory with copies of your auth/model configuration. It makes real model calls and requires network access. See [EVERGREEN.md](EVERGREEN.md) for intent coverage and Pi upgrade risks.
185
+
178
186
  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.
179
187
 
180
188
  Source organization:
package/docs/usage.md CHANGED
@@ -16,7 +16,7 @@ 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.
19
+ When Pi aborts the main agent, all running, queued, and parked subagent work stops, including detached descendants. In the interactive TUI, Escape uses Pi's normal interrupt handling. Escape consumed by a focused overlay or dialog stops no agents; idle Escape retains Pi's normal behavior. Alt+W aborts only the main agent and leaves subagents running for that run. A later normal abort stops them again. Alt+W requires a terminal that reports Alt/Meta+W, through a legacy Meta sequence or the Kitty keyboard protocol. Explicitly stopped workers do not automatically resume; their usage and spent budget still count.
20
20
 
21
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.
22
22
 
@@ -1,4 +1,3 @@
1
- import { isKeyRelease, matchesKey } from "@earendil-works/pi-tui";
2
1
  import { persistWorkerStops } from "../storage/worker-stops.js";
3
2
  import { releaseCompletionDelivery } from "./async-jobs.js";
4
3
  import { cachedSchedulerFor } from "./scheduler.js";
@@ -6,93 +5,92 @@ import { clearSyntheticResumeState, restoreModelAfterResumeFailure } from "./run
6
5
  import { stopBranches } from "./stop-tool.js";
7
6
  import type { ExtensionState } from "./state.js";
8
7
 
9
- /** Escape must reach detached workers even when the main agent has no active turn. */
8
+ /** Follow Pi's settled abort signal, never raw terminal input. */
10
9
  export function registerSubagentInterrupt(state: ExtensionState): void {
11
- let unsubscribe = () => {};
10
+ let keepSubagents = false;
12
11
  let startingResumeEpoch: number | undefined;
13
- state.onSessionReadyForInterrupt = (ctx) => {
12
+ state.onSessionReadyForInterrupt = () => {
13
+ keepSubagents = false;
14
14
  startingResumeEpoch = undefined;
15
- unsubscribe();
16
- unsubscribe = () => {};
17
- if (ctx.mode !== "tui" || !ctx.hasUI || state.currentDepth !== 0) return;
15
+ };
16
+ state.pi.registerShortcut("alt+w", {
17
+ description: "Interrupt only the main agent, leaving subagents running",
18
+ handler: (ctx) => {
19
+ if (ctx.isIdle()) return;
20
+ keepSubagents = true;
21
+ ctx.abort();
22
+ },
23
+ });
24
+ state.pi.on("agent_settled", (event, ctx) => {
25
+ const keep = keepSubagents;
26
+ keepSubagents = false;
27
+ if (!event.aborted || keep || !state.sessionActive || state.currentDepth !== 0) return;
18
28
  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;
29
+ // Also cancel an outstanding resume confirmation, even before plans are armed.
30
+ state.interruptEpoch = (state.interruptEpoch ?? 0) + 1;
31
+ const context = state.latestSessionCtx ?? ctx;
32
+ const scheduler = cachedSchedulerFor(state);
33
+ const deliveries = [...state.pendingCompletionDeliveries.keys()];
34
+ const names = new Set<string>();
35
+ let hasWork = !!(
36
+ state.backgroundJobs.size ||
37
+ state.activeSubagents.size ||
38
+ deliveries.length ||
39
+ state.pendingResumePlans.length ||
40
+ state.pendingInteractiveResumePrompt ||
41
+ state.pendingAutomaticResume
42
+ );
43
+ const errors: string[] = [];
44
+ const attempt = (operation: () => void) => {
64
45
  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");
46
+ operation();
47
+ } catch (error) {
48
+ errors.push(error instanceof Error ? error.message : String(error));
49
+ }
50
+ };
51
+ // Gather local work before reading the ledger, so a disk error cannot hide local handles.
52
+ for (const entry of scheduler?.snapshot() ?? []) names.add(entry.name);
53
+ for (const worker of state.activeSubagents.values()) if (worker.name) names.add(worker.name);
54
+ for (const job of state.backgroundJobs.values()) for (const name of job.names) names.add(name);
55
+ for (const plan of state.pendingResumePlans)
56
+ for (const result of plan.details?.results ?? []) if (result.name) names.add(result.name);
57
+ attempt(() => {
58
+ // Include broker-owned descendants and parked parents, not just local handles.
59
+ for (const entry of scheduler?.treeStore?.snapshot() ?? []) {
60
+ if (["queued", "running", "parking", "suspended", "waking", "stopping"].includes(entry.status))
61
+ names.add(entry.name);
91
62
  }
92
- // Preserve native Escape handling for dialogs, compaction, and the main editor.
93
- return undefined;
94
63
  });
95
- };
64
+ hasWork ||= names.size > 0;
65
+ if (!hasWork && !errors.length) return;
66
+ try {
67
+ state.pendingInteractiveResumePrompt = null;
68
+ state.pendingResumePlans = [];
69
+ clearSyntheticResumeState(state);
70
+ attempt(() => {
71
+ if (!names.size) return;
72
+ const stopped = stopBranches(state, [...names]);
73
+ errors.push(...stopped.statuses.flatMap((status) => (status.error ? [status.error] : [])));
74
+ // Synchronous markers precede completion microtasks and automatic recovery.
75
+ persistWorkerStops(state.currentNamesFile, stopped.stoppedNames);
76
+ });
77
+ // Fallbacks are independent: a failed kill or ledger write must not skip other workers.
78
+ if (errors.length) {
79
+ for (const worker of state.activeSubagents.values()) attempt(() => worker.handle.kill?.());
80
+ for (const job of state.backgroundJobs.values()) attempt(() => job.controller.abort());
81
+ } else {
82
+ for (const worker of state.activeSubagents.values()) if (!worker.name) attempt(() => worker.handle.kill?.());
83
+ }
84
+ } finally {
85
+ // Pi has already aborted. Replay interrupted accounting without starting another turn.
86
+ for (const id of deliveries) {
87
+ attempt(() => state.pendingCompletionInterrupts?.get(id)?.());
88
+ releaseCompletionDelivery(state, id, generation);
89
+ }
90
+ void restoreModelAfterResumeFailure(state, context);
91
+ if (errors.length) context.ui.notify(`Failed to stop some subagent work: ${errors.join("; ")}`, "error");
92
+ }
93
+ });
96
94
  state.pi.on("input", (event) => {
97
95
  const pending = state.pendingAutomaticResume;
98
96
  if (
@@ -119,9 +117,8 @@ export function registerSubagentInterrupt(state: ExtensionState): void {
119
117
  if (epoch !== undefined && epoch !== (state.interruptEpoch ?? 0)) ctx.abort();
120
118
  });
121
119
  state.pi.on("session_shutdown", () => {
120
+ keepSubagents = false;
122
121
  startingResumeEpoch = undefined;
123
122
  state.pendingAutomaticResume = undefined;
124
- unsubscribe();
125
- unsubscribe = () => {};
126
123
  });
127
124
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oira666_pi-subagent",
3
- "version": "0.7.5",
3
+ "version": "0.7.6",
4
4
  "description": "Subagent extension for Pi coding agent. Delegate tasks to specialized agents.",
5
5
  "type": "module",
6
6
  "main": "index.ts",
@@ -57,6 +57,7 @@
57
57
  "scripts": {
58
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",
59
59
  "test": "node --import tsx/esm --test test/*.test.ts",
60
+ "test:evergreen": "npm run pretest && node scripts/evergreen.mjs",
60
61
  "typecheck": "tsc --noEmit",
61
62
  "format": "prettier --write \"*.ts\" \"{extension,runner,storage,types,ui,test}/**/*.ts\" \"scripts/*.mjs\" package.json tsconfig.json .prettierrc.json",
62
63
  "format:check": "prettier --check \"*.ts\" \"{extension,runner,storage,types,ui,test}/**/*.ts\" \"scripts/*.mjs\" package.json tsconfig.json .prettierrc.json",