@luxass/pi-subagents 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-PRESENT Lucas Nørgård
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,96 @@
1
- # Temporary Holding Version
1
+ # @luxass/pi-subagents
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Delegate tasks to named [Pi](https://pi.dev) agents. Each agent works in its own conversation, and its result comes back to the main conversation by itself.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pi install npm:@luxass/pi-subagents
9
+ ```
10
+
11
+ To try it from this repository, run `pi -e ./packages/pi-subagents`.
12
+
13
+ ## Use
14
+
15
+ Ask Pi to delegate a task, or start a prompt with an agent type, such as `@explorer review authentication`. The main model starts the agent and gives it a unique task name, such as `auth-review`. Agents run in the background by default. Their results appear in the chat when they finish.
16
+
17
+ In Rex, the extension reports how many subagents are running, even after Pi's main turn ends. It clears the report when the last subagent stops. Queued subagents do not count as running.
18
+
19
+ Two agent types are built in. `general-purpose` has Pi's default tools: `read`, `bash`, `edit`, and `write`. `explorer` is told not to change files and has `read`, `grep`, `find`, `ls`, and `bash`. Its instructions are not a sandbox, because `bash` can still change files.
20
+
21
+ To give an agent a correction, or to continue a finished agent, ask the main model. You cannot send messages to an agent directly.
22
+
23
+ | Control | Action |
24
+ | --------- | ---------------------------------------------------------------------------- |
25
+ | `/agents` | Show every agent of the session beside the selected agent's conversation. |
26
+ | Ctrl+B | While a foreground agent runs, move all foreground agents to the background. |
27
+
28
+ Run `/agents` to open a panel with every agent of the session. Each agent has two lines: its task name and type, then the start of its prompt, its status, and elapsed time. Unfinished agents come first, and the newest first in each group. Under the list are the selected agent's model and thinking level, and its answer, or its latest output while it works. The answer takes as many lines as it needs, up to the height of the panel. From 104 columns, the list and the answer are side by side.
29
+
30
+ | Key | Action |
31
+ | ------------------- | ------------------------------------------------------------ |
32
+ | Up / Down | Select an agent, or scroll the answer when it has the focus. |
33
+ | Tab | Move the focus between the list and the answer. |
34
+ | `1` / `2` / `3` | Show all, active, or finished agents. |
35
+ | Enter | Open the agent's whole conversation. |
36
+ | `x`, then `y` | Stop the selected agent. `n` or Esc keeps it running. |
37
+ | `f` | Switch between the floating panel and fullscreen. |
38
+ | Page Up / Page Down | Scroll the answer without following new output. |
39
+ | End / Home | Follow new output again, or go to the start of the answer. |
40
+ | Esc | Close the panel. |
41
+
42
+ The conversation view shows tool calls the way Pi does, collapsed at first. Up, Down, Page Up, Page Down, Home, and End scroll it. Pi's tool expansion key opens and closes all tool calls. `t` and `T` move to the next and previous tool call, and Enter opens or closes that one. `f` switches fullscreen, and Esc goes back to the panel.
43
+
44
+ In Pi's fullscreen terminal mode, the mouse wheel scrolls the answer and the conversation. Everything else uses the keys.
45
+
46
+ ## Agent types
47
+
48
+ Add an agent type as a Markdown file. Files in later folders replace types with the same name from earlier ones:
49
+
50
+ 1. `~/.pi/agent/agents/`
51
+ 2. `~/.agents/agents/`
52
+ 3. `.agents/agents/` in the project
53
+ 4. `.pi/agents/` in the project
54
+
55
+ Project folders load only when you trust the project. The file body is added after Pi's system prompt. If `PI_CODING_AGENT_DIR` moves Pi's folder, the first folder is `agents/` inside it.
56
+
57
+ ```markdown
58
+ ---
59
+ description: Review code changes for bugs.
60
+ tools: [read, grep, find, ls, bash]
61
+ model: anthropic/claude-sonnet-4-5
62
+ thinking: high
63
+ max_turns: 30
64
+ skills: [review-checklist]
65
+ ---
66
+
67
+ Review the changes you are asked about and report concrete problems with file paths.
68
+ ```
69
+
70
+ Only `description` is required. `name` defaults to the file name. `model` is `provider/id`, or a name such as `opus 5.5`. `skills` adds the full text of those skills to the prompt. The file's `thinking` and `max_turns` win over the same values in an `Agent` call. The file's `model` is the type's default, and a model you ask for wins over it. A file with any other field is skipped with a warning.
71
+
72
+ A model name ignores case, spaces, dots, and hyphens, so `opus 5.5` finds `claude-opus-5-5`. If a name fits models on several providers, the agent does not start, and the error lists the choices. Use `provider/id`, or set `preferredProviders`. The tool result names the model each agent runs on.
73
+
74
+ Extension tools, such as `codemode`, load their extension only in that agent. A `mcp__server__*` pattern loads Pi's MCP support and codemode, and connects every server in `mcp.json`. Agents cannot start, steer, or stop other agents, and they have no UI, so a tool that asks you a question fails inside an agent.
75
+
76
+ ## Settings
77
+
78
+ Set these under `subagents` in Pi's `settings.json`. Project settings apply only in trusted projects.
79
+
80
+ | Setting | Default | Meaning |
81
+ | --------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------- |
82
+ | `maxConcurrent` | `8` | Background agents that run at once. More wait in a queue. |
83
+ | `maxTurns` | `0` | Turn limit when the file and the call set none. `0` means no limit. |
84
+ | `backgroundByDefault` | `true` | Whether `Agent` calls run in the background unless they say otherwise. |
85
+ | `disabledAgents` | `[]` | Agent types that cannot start or continue. |
86
+ | `preferredProviders` | `[]` | Providers to choose from, in order, when a model name fits models on several providers. |
87
+ | `widget` | `"background"` | Agents counted in the line above the editor: `"background"`, `"all"`, or `"off"`. |
88
+ | `delivery.mode` | `"grouped"` | `"grouped"` reports agents of one request together, after at most 60 seconds. `"immediate"` reports each result when it is ready. |
89
+
90
+ Agent conversations are saved under `~/.pi/agent/subagents/<session id>/`. After `/reload` or a resumed session, finished agents can still be read and continued. Agents that were running or queued show as interrupted and can also be continued. An agent that never started begins with the new prompt only. A result that finished but was not yet delivered arrives after the reload.
91
+
92
+ ## Costs
93
+
94
+ The cost in Pi's footer counts only the main session. The footer's status line shows what agents cost in the session, for example `agents $0.123`. It appears when an agent has used a model, and it includes agents that are still running.
95
+
96
+ When a run ends, its token usage and cost are saved in the session as a `subagents-usage` entry. A run stopped by `/reload` or by quitting Pi saves what it used up to then. [`@luxass/pi-cost-explorer`](../pi-cost-explorer/README.md) adds these entries to `/cost` as the source "Agents".
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@luxass/pi-subagents",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Delegate tasks to named Pi agents and follow their conversations.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-extension",
8
+ "pi-package",
9
+ "subagents"
10
+ ],
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/luxass/agent-extensions",
15
+ "directory": "packages/pi-subagents"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "type": "module",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "devDependencies": {
27
+ "@earendil-works/pi-ai": "1.6.0",
28
+ "@earendil-works/pi-coding-agent": "1.6.0",
29
+ "@earendil-works/pi-schema": "1.6.0",
30
+ "@earendil-works/pi-tui": "1.6.0"
31
+ },
32
+ "peerDependencies": {
33
+ "@earendil-works/pi-ai": "*",
34
+ "@earendil-works/pi-coding-agent": "*",
35
+ "@earendil-works/pi-schema": "*",
36
+ "@earendil-works/pi-tui": "*",
37
+ "typebox": "*"
38
+ },
39
+ "pi": {
40
+ "image": "https://raw.githubusercontent.com/luxass/agent-extensions/main/packages/pi-subagents/docs/cover.png",
41
+ "extensions": [
42
+ "./src/index.ts"
43
+ ]
44
+ },
45
+ "scripts": {
46
+ "lint": "oxlint .",
47
+ "lint:fix": "oxlint --fix .",
48
+ "fmt": "oxfmt .",
49
+ "fmt:check": "oxfmt --check .",
50
+ "typecheck": "tsc -p tsconfig.json"
51
+ }
6
52
  }
@@ -0,0 +1,10 @@
1
+ ---
2
+ description: Read-only search. Finds files, traces code, and answers questions about the project without changing files.
3
+ tools: [read, grep, find, ls, bash]
4
+ ---
5
+
6
+ Explore the project and answer the question you were given. Do not change files. Use bash only for commands that read, never for commands that modify the project, and do not create temporary files.
7
+
8
+ Match the depth of your search to the request. Answer a narrow question quickly. When asked to be thorough, search across folders and naming variations. Run independent searches and reads in parallel.
9
+
10
+ Report concrete findings with file paths and line numbers. Say what you looked for but could not find.
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: Research or change code for a self-contained task, with Pi's default tools.
3
+ ---
4
+
5
+ Complete the task assigned to you, and stay within it. Read the relevant code before you change it, and follow the project's existing conventions.
6
+
7
+ When you finish, report what you found and what you changed, with file paths. If you ran checks, report their results. If you could not finish, say what remains and why.
package/src/agents.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { basename, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
7
+ import { arr, compile, int, obj, oneOf, opt, str, type Static } from "@earendil-works/pi-schema";
8
+
9
+ const SUBAGENT_NAME_PATTERN = "^[a-z0-9]+(?:-[a-z0-9]+)*$";
10
+
11
+ const agentSchema = obj({
12
+ name: opt(str({ pattern: SUBAGENT_NAME_PATTERN })),
13
+ description: str({ minLength: 1 }),
14
+ tools: opt(arr(str({ minLength: 1 }))),
15
+ model: opt(str({ minLength: 1 })),
16
+ thinking: opt(oneOf(["off", "minimal", "low", "medium", "high", "xhigh", "max"])),
17
+ max_turns: opt(int({ minimum: 0 })),
18
+ skills: opt(arr(str({ minLength: 1 }))),
19
+ });
20
+ const validateAgent = compile(agentSchema);
21
+
22
+ /** A validated agent type from a Markdown file. */
23
+ export interface SubagentDefinition extends Static<typeof agentSchema> {
24
+ name: string;
25
+ body: string;
26
+ file: string;
27
+ }
28
+
29
+ /** Tools an agent gets when its file leaves out `tools`. */
30
+ export const DEFAULT_SUBAGENT_TOOLS = ["read", "bash", "edit", "write"];
31
+
32
+ /** Task and type names: lowercase words joined by hyphens. */
33
+ export function isSubagentName(name: string): boolean {
34
+ return new RegExp(SUBAGENT_NAME_PATTERN).test(name);
35
+ }
36
+
37
+ /** Agent coordination stays in the main session, so agents cannot use these tools. */
38
+ export function isSubagentControlTool(name: string): boolean {
39
+ return (
40
+ name === "Agent" ||
41
+ name.startsWith("Agent(") ||
42
+ name === "get_subagent_result" ||
43
+ name === "steer_subagent" ||
44
+ name === "stop_subagent"
45
+ );
46
+ }
47
+
48
+ /** Loads agent types in precedence order. Project folders load only when trusted. */
49
+ export async function loadSubagentDefinitions(
50
+ cwd: string,
51
+ trusted: boolean,
52
+ warn: (message: string) => void,
53
+ ): Promise<Map<string, SubagentDefinition>> {
54
+ const directories = [
55
+ fileURLToPath(new URL("./agents/", import.meta.url)),
56
+ // Pi's own folder, ~/.pi/agent unless PI_CODING_AGENT_DIR moves it. Agent conversations and
57
+ // skills are found through the same lookup.
58
+ join(getAgentDir(), "agents"),
59
+ // The cross-tool folder is not Pi's, so it stays in the home folder.
60
+ join(homedir(), ".agents/agents"),
61
+ ...(trusted ? [join(cwd, ".agents/agents"), join(cwd, ".pi/agents")] : []),
62
+ ];
63
+ const definitions = new Map<string, SubagentDefinition>();
64
+ for (const directory of directories) {
65
+ let filenames: string[];
66
+ try {
67
+ filenames = (await readdir(directory)).filter((name) => name.endsWith(".md")).toSorted();
68
+ } catch (error) {
69
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
70
+ warn(`Cannot read agent directory ${directory}: ${String(error)}`);
71
+ }
72
+ continue;
73
+ }
74
+ for (const filename of filenames) {
75
+ const file = join(directory, filename);
76
+ const definition = await readSubagentDefinition(file, warn);
77
+ if (definition) definitions.set(definition.name, definition);
78
+ }
79
+ }
80
+ return definitions;
81
+ }
82
+
83
+ async function readSubagentDefinition(
84
+ file: string,
85
+ warn: (message: string) => void,
86
+ ): Promise<SubagentDefinition | undefined> {
87
+ let frontmatter: Record<string, unknown>;
88
+ let body: string;
89
+ try {
90
+ ({ frontmatter, body } = parseFrontmatter(await readFile(file, "utf8")));
91
+ } catch (error) {
92
+ warn(`Skipping agent ${file}: invalid frontmatter (${String(error)}).`);
93
+ return undefined;
94
+ }
95
+ const fields: Record<string, unknown> = { ...frontmatter };
96
+ fields.name ??= basename(file, ".md");
97
+ // Accept "read, grep" as well as a YAML list, as other agent files do.
98
+ for (const key of ["tools", "skills"]) {
99
+ const value = fields[key];
100
+ if (typeof value === "string") {
101
+ fields[key] = value
102
+ .split(",")
103
+ .map((item) => item.trim())
104
+ .filter(Boolean);
105
+ }
106
+ }
107
+ const problems = validateAgent.errors(fields).map((error) => {
108
+ const field = error.path.slice(1).split("/")[0] || "frontmatter";
109
+ return `${field} (${error.message})`;
110
+ });
111
+ const valid = fields as Static<typeof agentSchema>;
112
+ const control = Array.isArray(valid.tools) ? valid.tools.filter(isSubagentControlTool) : [];
113
+ if (control.length)
114
+ problems.push(`tools (agents cannot coordinate agents: ${control.join(", ")})`);
115
+ if (problems.length) {
116
+ warn(`Skipping agent ${file}: ${[...new Set(problems)].join(", ")}.`);
117
+ return undefined;
118
+ }
119
+ return { ...valid, name: String(fields.name), body: body.trim(), file };
120
+ }
package/src/costs.ts ADDED
@@ -0,0 +1,52 @@
1
+ import type { Usage } from "@earendil-works/pi-ai";
2
+
3
+ /**
4
+ * Custom entry type that stores what one agent run used, in the main session. It is written once
5
+ * per run, when the run ends. Its data is a `SubagentRunUsage`.
6
+ */
7
+ export const SUBAGENT_USAGE_ENTRY = "subagents-usage";
8
+
9
+ /** What one agent run used. A run that used no tokens saves none. */
10
+ export interface SubagentRunUsage {
11
+ sessionId: string;
12
+ id: string;
13
+ name: string;
14
+ agentType: string;
15
+ /** Counts starts and continuations of the agent, from 1. */
16
+ run: number;
17
+ provider: string;
18
+ model: string;
19
+ /** The sum of every model reply in the run, with Pi's cost for each. */
20
+ usage: Usage;
21
+ }
22
+
23
+ /** A usage total that starts at zero. */
24
+ export function emptySubagentUsage(): Usage {
25
+ return {
26
+ input: 0,
27
+ output: 0,
28
+ cacheRead: 0,
29
+ cacheWrite: 0,
30
+ totalTokens: 0,
31
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
32
+ };
33
+ }
34
+
35
+ /** Whether a usage total holds any tokens. A reply stopped before it began reports none. */
36
+ export function hasSubagentUsage(usage: Usage): boolean {
37
+ return usage.input + usage.output + usage.cacheRead + usage.cacheWrite > 0;
38
+ }
39
+
40
+ /** Adds one model reply's usage to a run's total. */
41
+ export function addSubagentUsage(total: Usage, usage: Usage): void {
42
+ total.input += usage.input;
43
+ total.output += usage.output;
44
+ total.cacheRead += usage.cacheRead;
45
+ total.cacheWrite += usage.cacheWrite;
46
+ total.totalTokens += usage.totalTokens;
47
+ total.cost.input += usage.cost.input;
48
+ total.cost.output += usage.cost.output;
49
+ total.cost.cacheRead += usage.cost.cacheRead;
50
+ total.cost.cacheWrite += usage.cost.cacheWrite;
51
+ total.cost.total += usage.cost.total;
52
+ }
package/src/index.ts ADDED
@@ -0,0 +1,114 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { loadSubagentDefinitions } from "./agents.ts";
4
+ import { SubagentManager } from "./manager.ts";
5
+ import {
6
+ SUBAGENT_MENTION_MESSAGE,
7
+ subagentMentionAutocomplete,
8
+ subagentMentionInstruction,
9
+ } from "./mentions.ts";
10
+ import { SUBAGENT_RESULT_MESSAGE, SubagentDelivery } from "./results.ts";
11
+ import { readSubagentSettings } from "./settings.ts";
12
+ import { reportSubagentsToRex } from "./terminal-status.ts";
13
+ import { registerAgentTool, registerSubagentTools } from "./tools.ts";
14
+ import { renderSubagentResultMessage } from "./ui/agent-card.ts";
15
+ import { installBackgroundShortcut } from "./ui/background-shortcut.ts";
16
+ import { installSubagentCostStatus, SUBAGENT_COST_STATUS } from "./ui/cost-status.ts";
17
+ import { openSubagentViewer } from "./ui/viewer.ts";
18
+ import { installSubagentWidget } from "./ui/widget.ts";
19
+
20
+ /** Pi entry point for @luxass/pi-subagents. */
21
+ export default function piSubagents(pi: ExtensionAPI): void {
22
+ let manager: SubagentManager | undefined;
23
+ let delivery: SubagentDelivery | undefined;
24
+ let removeShortcut: (() => void) | undefined;
25
+ let stopRexStatus: (() => void) | undefined;
26
+
27
+ pi.registerMessageRenderer(SUBAGENT_RESULT_MESSAGE, renderSubagentResultMessage);
28
+
29
+ // Registered here, not in session_start: on /reload Pi redraws the chat before session_start,
30
+ // and it can only draw the calls of tools it already knows.
31
+ registerSubagentTools(pi, () => manager);
32
+
33
+ pi.registerCommand("agents", {
34
+ description: "Show agents and their conversations",
35
+ handler: async (_args, ctx) => {
36
+ if (ctx.mode !== "tui") {
37
+ ctx.ui.notify("/agents needs the interactive terminal.", "error");
38
+ return;
39
+ }
40
+ if (!manager) return;
41
+ await openSubagentViewer(ctx, manager);
42
+ },
43
+ });
44
+
45
+ // The manager waits for session_start because the factory has no ExtensionContext: no working
46
+ // directory, no session id, and no trust decision yet. Pi runs this factory before it asks about
47
+ // project trust, so project agents and settings could not be filtered there. Pi also runs
48
+ // factories in invocations that never start a session. /new, /resume, /fork, and /reload load a
49
+ // new runtime, so this runs again for each session.
50
+ pi.on("session_start", async (_event, ctx: ExtensionContext) => {
51
+ const warn = (message: string) => {
52
+ if (ctx.hasUI) ctx.ui.notify(message, "warning");
53
+ else console.error(`[pi-subagents] ${message}`);
54
+ };
55
+ const settings = readSubagentSettings(
56
+ (pi.getSettings() as Record<string, unknown>).subagents,
57
+ warn,
58
+ );
59
+ const definitions = await loadSubagentDefinitions(ctx.cwd, ctx.isProjectTrusted(), warn);
60
+ const sessionId = ctx.sessionManager.getSessionId();
61
+ manager = new SubagentManager(pi, ctx, sessionId, definitions, settings);
62
+ manager.restore();
63
+ delivery = new SubagentDelivery(pi, ctx, manager);
64
+ // Again, now that the agent types are known, so the description can list them.
65
+ registerAgentTool(pi, () => manager, manager.availableTypes());
66
+ if (ctx.mode === "tui") {
67
+ const current = manager;
68
+ ctx.ui.addAutocompleteProvider(subagentMentionAutocomplete(() => current.availableTypes()));
69
+ installSubagentWidget(ctx, current);
70
+ installSubagentCostStatus(ctx, current);
71
+ removeShortcut = installBackgroundShortcut(pi, ctx, current);
72
+ stopRexStatus = reportSubagentsToRex(current);
73
+ }
74
+ // Last, so the tools exist when a restored result starts a main-model turn.
75
+ delivery.deliverRestored();
76
+ });
77
+
78
+ // A leading type mention asks the main model to start that type. The instruction stays hidden.
79
+ pi.on("before_agent_start", (event, ctx) => {
80
+ if (!manager || event.messageType !== "user" || ctx.mode !== "tui") return undefined;
81
+ const instruction = subagentMentionInstruction(event.prompt, manager.availableTypes());
82
+ if (!instruction) return undefined;
83
+ return {
84
+ message: { customType: SUBAGENT_MENTION_MESSAGE, content: instruction, display: false },
85
+ };
86
+ });
87
+
88
+ // Requests are counted per agent_start, so grouping follows the user's request, not each turn.
89
+ pi.on("agent_start", () => {
90
+ if (manager) manager.requestId++;
91
+ delivery?.agentStarted();
92
+ });
93
+
94
+ pi.on("turn_end", (event) => delivery?.turnEnded(event));
95
+
96
+ pi.on("agent_settled", () => delivery?.agentSettled());
97
+
98
+ pi.on("session_shutdown", async (_event, ctx) => {
99
+ // Delivery stops first, so aborted runs never deliver.
100
+ delivery?.dispose();
101
+ removeShortcut?.();
102
+ removeShortcut = undefined;
103
+ stopRexStatus?.();
104
+ stopRexStatus = undefined;
105
+ if (ctx.mode === "tui") {
106
+ ctx.ui.setWidget("subagents", undefined);
107
+ ctx.ui.setStatus(SUBAGENT_COST_STATUS, undefined);
108
+ }
109
+ delivery = undefined;
110
+ const current = manager;
111
+ manager = undefined;
112
+ await current?.shutdown();
113
+ });
114
+ }