pi-session-subagents 0.0.0-stage → 0.1.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,23 @@
1
+ # Changelog
2
+
3
+ ## [0.1.1](https://github.com/rbajaj1997/pi-session-subagents/compare/v0.1.0...v0.1.1) (2026-11-15)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * require Node.js 24 ([#2](https://github.com/rbajaj1997/pi-session-subagents/issues/2)) ([b2d8749](https://github.com/rbajaj1997/pi-session-subagents/commit/b2d8749eeadafac621834c0fc18b1ce05fca744a))
9
+
10
+ ## [0.1.0] - 2026-11-15
11
+
12
+ Initial release.
13
+
14
+ - Create session-scoped workers with their own conversations. A worker can start idle without a model call, run a task, and take follow-up tasks in the same context.
15
+ - Start, steer, inspect, wait for, and stop workers through six tools: `spawn_subagent`, `list_subagents`, `inspect_subagent`, `message_subagent`, `await_subagents`, and `stop_subagent`.
16
+ - Choose each worker's name, model, thinking level, tools, and working directory. The model and thinking level default to the parent's. Tools must be a subset of the parent's active tools. A model query that matches nothing fails the spawn. A working directory other than the parent's loads project resources only with a saved trust decision.
17
+ - Set an optional deadline per task with `timeoutMs`. `await_subagents` can wait for named workers and stop waiting after a timeout.
18
+ - Turn the tools on and off with `/subagents on|off`. `/subagents <request>` turns them on and sends the request.
19
+ - Deliver success and failure reports to the parent with the first 12,000 characters of the result. Read longer results in pages with `inspect_subagent`. A report cleared by Escape in the TUI is sent once with the parent's next turn, without starting one.
20
+ - Save each worker's conversation under `~/.pi/agent/subagent-sessions/`. Reports and `inspect_subagent` show the path for `pi --session <path>`.
21
+ - Show a live worker widget and a read-only inspector built from Pi's own message and tool components. In fullscreen mode, clicking a worker in the widget opens its inspector.
22
+ - Give each worker its own model runtime, so its extension providers are registered before its model is chosen and do not affect other workers. Workers load configured extensions, plus Pi's codemode, tool search, and MCP extensions when their tools need them. Worker extensions receive `session_shutdown` when the worker is removed.
23
+ - Keep the parent's system prompt unchanged as workers start and finish, so the prompt cache stays valid.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rohit Bajaj
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,217 @@
1
- # Temporary Holding Version
1
+ # pi-session-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
+ Reusable subagents for the current Pi session. Create workers, give them tasks, steer their work, and inspect their conversations using Pi's native message and tool rendering.
4
+
5
+ ## What "session subagents" means
6
+
7
+ Each worker has its own conversation. It can start idle, complete a task, and accept a follow-up in the same context. Completed workers stay available until you stop them or the parent session ends.
8
+
9
+ ```text
10
+ Create worker
11
+ optionally start a task
12
+ return result
13
+ retain conversation
14
+ accept follow-up tasks
15
+ stop when removed or the parent session ends
16
+ ```
17
+
18
+ This is conversational reuse, not a background job service. Workers do not survive reloads, session switches, or process exit. Their conversations are saved to disk, so you can review a worker's work later (see [Reviewing past work](#reviewing-past-work)).
19
+
20
+ ## Requirements
21
+
22
+ - Pi 1.5.2 is the SDK and TUI compatibility target. Older versions are not supported; other versions have not been validated.
23
+ - Node.js 24 or newer.
24
+ - Model credentials and configuration available to Pi.
25
+
26
+ ## Install
27
+
28
+ From npm:
29
+
30
+ ```sh
31
+ pi install npm:pi-session-subagents
32
+ ```
33
+
34
+ From GitHub:
35
+
36
+ ```sh
37
+ pi install git:github.com/rbajaj1997/pi-session-subagents
38
+ ```
39
+
40
+ From a local checkout, run this from the repository root:
41
+
42
+ ```sh
43
+ pi install .
44
+ ```
45
+
46
+ Restart Pi or use `/reload` after changing enabled extensions. Keep only one copy of this extension enabled, since duplicate copies register the same tools and commands.
47
+
48
+ ## Quick start
49
+
50
+ Create two idle workers without assigning readiness-acknowledgment tasks:
51
+
52
+ ```text
53
+ /subagents Create two idle workers named scout and reviewer using Haiku. Keep them ready without assigning tasks.
54
+ ```
55
+
56
+ Then ask Pi to use an existing worker:
57
+
58
+ ```text
59
+ Have scout inspect the authentication code and summarize its structure.
60
+ ```
61
+
62
+ After it finishes, continue its conversation:
63
+
64
+ ```text
65
+ Ask scout to examine the token-refresh path in more detail.
66
+ ```
67
+
68
+ The follow-up uses scout's existing context. For unrelated work that needs a fresh context, create another worker.
69
+
70
+ Workers can be limited and given deadlines:
71
+
72
+ ```text
73
+ Spawn a read-only worker with only read, grep, find, and ls, low thinking, and a 5 minute timeout to map the database layer.
74
+ ```
75
+
76
+ `/subagents <request>` turns the worker tools on and sends the request. To turn them on without a request, use `/subagents on`. To stop and remove all workers and turn the tools off, use `/subagents off`. It stops workers right away, even while the parent waits in `await_subagents`, and turns the tools off once the parent's current run ends. The tools also turn off on reload or session switch.
77
+
78
+ ## Commands and tools
79
+
80
+ | Command | Purpose |
81
+ | --- | --- |
82
+ | `/subagents on` | Turn the worker tools on. |
83
+ | `/subagents off` | Stop and remove workers, then turn the tools off. |
84
+ | `/subagents <request>` | Turn the worker tools on and send the request. |
85
+ | `/subagents:inspect [name]` | Open a live, read-only conversation inspector. Interactive TUI only. |
86
+
87
+ | Tool | Purpose |
88
+ | --- | --- |
89
+ | `spawn_subagent` | Create a worker. Omit `task`, or leave it blank, to keep it idle without a model call. |
90
+ | `list_subagents` | List workers and their statuses. |
91
+ | `inspect_subagent` | Read status, capabilities, the session file path, recent conversation lines, or paginated result text. |
92
+ | `message_subagent` | Start an idle worker, continue a completed worker, or steer a running one. |
93
+ | `await_subagents` | Wait for named workers, or all running ones. |
94
+ | `stop_subagent` | Stop a worker, remove it, and wait until its session is closed. |
95
+
96
+ Only the parent uses these tools. Workers do not load this extension, so they cannot spawn other workers or message siblings.
97
+
98
+ ## Worker options
99
+
100
+ `spawn_subagent` accepts:
101
+
102
+ | Option | Default | Meaning |
103
+ | --- | --- | --- |
104
+ | `name` | `worker`, `worker-2`, ... | Short name used to address the worker. |
105
+ | `task` | none | Task to start right away. Without it the worker stays idle. |
106
+ | `model` | parent's model | Fuzzy name or `provider/id`. A query that matches no available model, or has no letters or digits, fails the spawn. |
107
+ | `thinking` | parent's level | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`. |
108
+ | `tools` | parent's active tools | Subset of the parent's active tools. Naming a tool the parent does not have active fails the spawn. |
109
+ | `cwd` | parent's cwd | Working directory, absolute or relative to the parent's. It must exist. |
110
+ | `timeoutMs` | no limit | Deadline for the initial task. |
111
+
112
+ `message_subagent` also accepts `timeoutMs` for the task it starts. It is ignored when the message steers a running worker. A steering message belongs to the current task: if the worker finishes while the message is still being processed, the message starts another turn of that task, and the report waits for it. When a deadline expires, the run is aborted and reported as an error, steering messages it has not read yet are dropped, and the worker stays available for follow-ups.
113
+
114
+ If you press Escape while `spawn_subagent` is still creating a worker, the worker is discarded before its task starts. Once `spawn_subagent` returns, the worker runs on its own until it finishes or you stop it.
115
+
116
+ `await_subagents` accepts `names` and `timeoutMs`. With a timeout it stops waiting when the time is up and lists the workers still running. Those workers keep running.
117
+
118
+ Waiting is rarely needed, because completion reports arrive on their own. While `await_subagents` runs, the parent's turn stays open and messages you send are held until it returns. The tool guidelines tell the model to end its turn while workers run, and to wait only when it needs the results together or you ask it to.
119
+
120
+ ## Results and reports
121
+
122
+ Success and failure both produce completion reports. A report steers a running parent or wakes an idle one. Workers you stop, and workers disposed during parent shutdown, do not send reports.
123
+
124
+ In the TUI, Escape clears the parent's queued messages, including reports it has not read yet. Each cleared report is kept and sent once with the parent's next turn, usually your next message. It does not start a turn on its own. Other modes keep queued messages on abort, so their reports arrive with the next run unchanged. An RPC client that calls `clear_queue` drops queued reports for good.
125
+
126
+ The model-visible report contains the first 12,000 UTF-16 code units of the result, keeping line breaks and surrogate pairs intact at page boundaries. The full result stays in the expandable report card, which renders it as Markdown, and in the worker's session file.
127
+
128
+ For longer results, call `inspect_subagent` with `includeResult: true`, the report's `runId`, and the continuation `resultOffset`. Starting another assignment clears the latest result, but earlier output stays in the conversation. Run ids are unique within the parent session, across all workers, so a `runId` that is not the worker's latest returns an error rather than a later assignment's output, even when a new worker reuses a removed worker's name.
129
+
130
+ `inspect_subagent` with `tailLines` returns the last lines of the conversation as plain text, up to 50KB.
131
+
132
+ ## Inspection
133
+
134
+ The main widget and the inspector need the interactive TUI. In RPC mode, use `list_subagents` and `inspect_subagent`. The main widget shows worker status and activity. In fullscreen mode, Pi's default, click a worker in the widget to open its inspector. In regular mode the terminal handles the mouse, so use `/subagents:inspect [name]`. The inspector renders the worker's full session branch, including messages before compaction, with Pi's native assistant, user, custom-message, tool, and summary components. Tool cards use registered renderers, including edit diffs. Inline tool images are off in the inspector.
135
+
136
+ - Arrows or `j`/`k` scroll. PageUp/PageDown page. Home/End jump.
137
+ - Scrolling up pauses following. End resumes it.
138
+ - Mouse-wheel scrolling and native click controls work in fullscreen mode.
139
+ - `t` or the configured `app.tools.expand` shortcut expands or collapses tool cards.
140
+ - The configured `app.thinking.toggle` shortcut changes thinking visibility inside the inspector only.
141
+ - Escape or `q` closes the inspector without stopping the worker.
142
+
143
+ ## Reviewing past work
144
+
145
+ Each worker that runs a task writes its conversation to a session file under `~/.pi/agent/subagent-sessions/`, outside Pi's normal session list, so `pi -r` is not affected. Pi writes the file once the conversation starts, so a worker that stays idle leaves no file. All of a worker's tasks go into the same file, and the file records the parent session's path.
146
+
147
+ The completion report card shows `Session: pi --session <path>`, and the model-visible report and `inspect_subagent` include the path. After a worker is removed, or after Pi restarts, open its file with:
148
+
149
+ ```sh
150
+ pi --session <path>
151
+ ```
152
+
153
+ This opens the worker's conversation as a normal session. A prompt typed there continues it. This extension does not delete these files.
154
+
155
+ ## Configuration and limitations
156
+
157
+ There is no package-specific configuration file or role library. Workers are configured per spawn (see [Worker options](#worker-options)).
158
+
159
+ Each worker has its own `ModelRuntime`, separate from the parent's and from other workers'. It discovers configured credentials, providers, and extensions for its working directory, and registers the providers its extensions declare before its model is chosen, so a model from an extension provider works on the first spawn. A worker's provider registrations do not affect other workers and end with it. Credentials come from the shared `auth.json`, which Pi writes under a file lock. Removing a worker waits for its credential writes, such as an OAuth token refresh. Parent-only runtime keys, virtual models, provider registrations, and tool implementations are not copied. A resolved model missing from the worker runtime causes creation to fail.
160
+
161
+ A worker in the parent's working directory uses the parent's project trust decision. A worker in another directory loads that directory's project settings, extensions, skills, and MCP servers only if `~/.pi/agent/trust.json` has a saved yes for it or a parent directory, for example from `/trust`. Workers never show the trust prompt. When untrusted project resources are skipped, the spawn result lists a warning.
162
+
163
+ Spawn results and inspection report the worker's enabled tools, callable tools, missing requested tools, and extension diagnostics. When a worker's tools include `codemode` or `tool_search`, the worker also loads Pi's codemode, tool search, and MCP extensions, so each such worker opens its own MCP connections. Worker extensions receive `session_shutdown` when the worker is removed.
164
+
165
+ The parent's system prompt does not change as workers start and finish, so the prompt cache stays valid. The model learns about workers from the tool guidelines and `list_subagents`.
166
+
167
+ Idle workers make no model calls but still use memory. Follow-ups include existing conversation context and are billed normally. There is no package-level concurrency cap. A host that exits disposes its workers; do not assume jobs outlive the parent process.
168
+
169
+ ## Permissions
170
+
171
+ Separate conversation context is not filesystem or process isolation. Workers share the host's operating-system permissions and can work in the same directory. Coordinate parallel writes to avoid conflicts.
172
+
173
+ Tool allowlists are not a security sandbox. Loaded extensions run with host permissions. Review extensions and project trust settings before delegating work.
174
+
175
+ ## Development
176
+
177
+ ```sh
178
+ npm install
179
+ npm run check # Biome lint and format check, then tsc
180
+ npm run format # apply Biome formatting and safe fixes
181
+ npm test
182
+ ```
183
+
184
+ Formatting and linting follow Pi's own Biome setup: tabs, a 120-character line width, double quotes, semicolons, and the recommended lint rules. Biome is pinned to the version Pi uses. `.vscode/` makes Biome the formatter on save, so editor formatting matches `npm run check`. Install the recommended Biome extension.
185
+
186
+ The package ships TypeScript source through `pi.extensions`. Pi loads it directly, so no compilation or bundling step is required. Pi-provided imports are peer dependencies, with pinned development copies for local typechecking. There are no additional runtime dependencies.
187
+
188
+ `npm test` uses Node's built-in test runner with tsx to run the TypeScript tests. The tests use normal imports, and `tsc --noEmit` checks both `src/` and `tests/`. Tests exercise commands, the roster, worker lifecycle and steering, deadlines, report delivery, model selection, result pagination, transcript inspection, the widget, the inspector, and session cleanup. They use a controlled Pi session substitute and temporary directories, without model calls or credentials. Live provider discovery, trust configuration, and interactive TUI behavior still need checks in Pi.
189
+
190
+ ```text
191
+ src/
192
+ index.ts Wiring: tools, commands, session events
193
+ copy.ts Every sentence the model reads; tool names come from here
194
+ tools.ts The six tool definitions and the text they return
195
+ roster.ts The session's workers: naming, spawning, messaging, waiting, stopping
196
+ worker.ts One worker and its run; stats and status are derived from its session
197
+ worker-session.ts Builds and shuts down a worker's Pi session
198
+ report.ts Completion reports: model JSON, card, delivery, resend after Escape
199
+ model-resolver.ts Model selection
200
+ text.ts Plain-text helpers for model-facing strings
201
+ ui/
202
+ widget.ts Worker list above the editor
203
+ conversation-viewer.ts Framed read-only inspector using Pi's own components
204
+ tests/ TypeScript behavior tests, run with node --test through tsx
205
+ ```
206
+
207
+ CI runs `npm run check`, `npm test`, and `npm pack --dry-run` on Node 24 for every push to `main` and every pull request.
208
+
209
+ ## Releasing
210
+
211
+ Releases use [release-please](https://github.com/googleapis/release-please) and [Conventional Commits](https://www.conventionalcommits.org/). Write commit messages such as `feat: add ask_parent tool` or `fix: resend reports after Escape`. `feat` bumps the minor version, `fix` bumps the patch version, and a breaking change also bumps the minor version until 1.0.0.
212
+
213
+ Each push to `main` updates a release pull request that bumps the version in `package.json` and adds the changes to `CHANGELOG.md`. Merging it tags the release, creates a GitHub release, and publishes the package to npm from GitHub Actions with trusted publishing and provenance. No npm token is stored in the repository.
214
+
215
+ ## License
216
+
217
+ MIT. See [LICENSE](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
- "name": "pi-session-subagents",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "pi-session-subagents",
3
+ "version": "0.1.1",
4
+ "description": "Session-scoped subagents for Pi with idle workers, steering, and native transcript inspection.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Rohit Bajaj",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/rbajaj1997/pi-session-subagents.git"
11
+ },
12
+ "homepage": "https://github.com/rbajaj1997/pi-session-subagents#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/rbajaj1997/pi-session-subagents/issues"
15
+ },
16
+ "keywords": [
17
+ "pi-package",
18
+ "pi",
19
+ "subagents",
20
+ "session-workers"
21
+ ],
22
+ "engines": {
23
+ "node": ">=24.0.0"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "files": [
29
+ "src/",
30
+ "README.md",
31
+ "CHANGELOG.md",
32
+ "LICENSE"
33
+ ],
34
+ "pi": {
35
+ "extensions": [
36
+ "./src/index.ts"
37
+ ]
38
+ },
39
+ "scripts": {
40
+ "check": "biome check && tsc --noEmit",
41
+ "format": "biome check --write",
42
+ "test": "node --import tsx --test --test-timeout=10000 tests/*.test.ts"
43
+ },
44
+ "peerDependencies": {
45
+ "@earendil-works/pi-agent-core": "*",
46
+ "@earendil-works/pi-ai": "*",
47
+ "@earendil-works/pi-coding-agent": "*",
48
+ "@earendil-works/pi-tui": "*",
49
+ "typebox": "*"
50
+ },
51
+ "devDependencies": {
52
+ "@biomejs/biome": "2.3.5",
53
+ "@earendil-works/pi-agent-core": "1.5.2",
54
+ "@earendil-works/pi-ai": "1.5.2",
55
+ "@earendil-works/pi-coding-agent": "1.5.2",
56
+ "@earendil-works/pi-tui": "1.5.2",
57
+ "@types/node": "^24.19.2",
58
+ "tsx": "^4.23.15",
59
+ "typebox": "1.3.27",
60
+ "typescript": "^5.9.0"
61
+ }
62
+ }
package/src/copy.ts ADDED
@@ -0,0 +1,79 @@
1
+ import { RESULT_PAGE_CHARS } from "./text";
2
+
3
+ interface ToolCopy {
4
+ label: string;
5
+ description: string;
6
+ promptSnippet: string;
7
+ promptGuidelines?: string[];
8
+ }
9
+
10
+ export const TOOL_COPY = {
11
+ spawn_subagent: {
12
+ label: "Spawn Subagent",
13
+ description:
14
+ "Create a session-scoped subagent with its own independent context window. Provide a task to start work immediately, or omit it to create an idle worker without a model call.",
15
+ promptSnippet: "Spawn an independent worker, optionally starting a task. Omit task to keep it idle.",
16
+ promptGuidelines: [
17
+ "Use spawn_subagent when a task can run independently in a separate context window.",
18
+ "Subagents do not share context with the parent or with each other.",
19
+ "Workers independently discover configured tools and providers. Check enabled and missing tools in the spawn result before assigning work that depends on a capability.",
20
+ "When asked to keep workers ready or on standby, omit task. Do not assign a readiness acknowledgment task. Start an idle worker later with message_subagent.",
21
+ "When the user wants a specific subagent name or role label, set the optional name field to that brief label.",
22
+ "Completion reports from workers arrive on their own and start a new turn when you are idle. While workers run, end your turn instead of waiting, so the user can keep talking to you.",
23
+ "Use await_subagents only when you cannot continue without the workers' results, such as combining several results in one answer, or when the user asks you to wait. Messages the user sends are held until await_subagents returns.",
24
+ "Do not use spawn_subagent as a probe or test. If the goal is to inspect, wait on, message, or stop an existing subagent, use those tools directly.",
25
+ ],
26
+ },
27
+ list_subagents: {
28
+ label: "List Subagents",
29
+ description: "List all active subagents in the current session.",
30
+ promptSnippet: "List known subagents and their statuses.",
31
+ },
32
+ inspect_subagent: {
33
+ label: "Inspect Subagent",
34
+ description: `Inspect a subagent's status and actual capabilities. Optionally read the last result in ${RESULT_PAGE_CHARS.toLocaleString("en-US")}-character pages or include a recent transcript tail.`,
35
+ promptSnippet:
36
+ "Inspect worker status and capabilities, or read its full result with includeResult and resultOffset.",
37
+ },
38
+ message_subagent: {
39
+ label: "Message Subagent",
40
+ description:
41
+ "Send an instruction to a subagent. Starts an idle worker or continues a completed worker. If it is already running, the message steers its current work.",
42
+ promptSnippet: "Start an idle worker, continue a completed worker, or steer a busy worker.",
43
+ },
44
+ await_subagents: {
45
+ label: "Await Subagents",
46
+ description:
47
+ "Wait until the named subagents, or all running ones, finish. With timeoutMs, return when it expires and list the workers still running.",
48
+ promptSnippet: "Block until running subagents finish. Only when you need their results now.",
49
+ },
50
+ stop_subagent: {
51
+ label: "Stop Subagent",
52
+ description: "Stop a subagent and remove it from the roster.",
53
+ promptSnippet: "Stop a subagent and clear it from the active subagent list.",
54
+ },
55
+ } satisfies Record<string, ToolCopy>;
56
+
57
+ export type ToolName = keyof typeof TOOL_COPY;
58
+ export const TOOL_NAMES = Object.keys(TOOL_COPY) as ToolName[];
59
+ export const isSubagentTool = (name: string): name is ToolName => (TOOL_NAMES as string[]).includes(name);
60
+
61
+ export const WORKER_SYSTEM_PROMPT = [
62
+ "You are a session-scoped worker subagent created by a parent pi session.",
63
+ "",
64
+ "Important rules:",
65
+ "- You have your own isolated context window and conversation history.",
66
+ "- Do not assume access to the parent agent's hidden reasoning or other subagents' context.",
67
+ "- Focus only on the current delegated task.",
68
+ "- If you receive a later instruction, treat it as a continuation or steering update from the parent.",
69
+ "- When you finish, end with a concise final answer describing the result.",
70
+ ].join("\n");
71
+
72
+ export const LATE_STEER_TURN_MESSAGE = "The parent sent another instruction as you finished.";
73
+
74
+ export const READ_MORE_HINT =
75
+ "Use inspect_subagent with includeResult: true, this runId, and resultOffset: nextResultOffset.";
76
+
77
+ export function timeoutMessage(duration: string): string {
78
+ return `Timed out after ${duration}. Its conversation is intact; send a follow-up with message_subagent to continue.`;
79
+ }
package/src/index.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { isSubagentTool, TOOL_NAMES } from "./copy";
3
+ import { registerReportDelivery } from "./report";
4
+ import { Roster } from "./roster";
5
+ import { subagentTools } from "./tools";
6
+ import { openInspector } from "./ui/conversation-viewer";
7
+
8
+ export default function (pi: ExtensionAPI) {
9
+ const roster = new Roster(pi);
10
+
11
+ function setEnabled(enabled: boolean): void {
12
+ const others = pi.getActiveTools().filter((name) => !isSubagentTool(name));
13
+ pi.setActiveTools(enabled ? [...others, ...TOOL_NAMES] : others);
14
+ }
15
+
16
+ for (const tool of subagentTools(roster)) pi.registerTool(tool);
17
+ registerReportDelivery(pi, roster.reports);
18
+
19
+ pi.registerCommand("subagents:inspect", {
20
+ description: "Inspect subagents in a live read-only overlay",
21
+ getArgumentCompletions: (prefix) => roster.completions(prefix),
22
+ handler: (args, ctx) => openInspector(ctx, roster.list(), args),
23
+ });
24
+
25
+ pi.registerCommand("subagents", {
26
+ description:
27
+ "Use 'on' to enable the subagent tools, 'off' to stop all workers and disable them, or pass a request to enable them and send it",
28
+ handler: async (args, ctx) => {
29
+ const request = args?.trim() || "";
30
+ if (!request) {
31
+ if (ctx.hasUI) ctx.ui.notify("Usage: /subagents on, /subagents off, or /subagents <request>", "info");
32
+ return;
33
+ }
34
+ const command = request.toLowerCase();
35
+ if (command === "off") {
36
+ try {
37
+ await roster.stopAll();
38
+ } finally {
39
+ await ctx.waitForIdle();
40
+ setEnabled(false);
41
+ }
42
+ if (ctx.hasUI) ctx.ui.notify("Subagent mode off. All subagents stopped and tools disabled.", "info");
43
+ return;
44
+ }
45
+ await ctx.waitForIdle();
46
+ if (!pi.getActiveTools().some(isSubagentTool)) {
47
+ setEnabled(true);
48
+ if (ctx.hasUI)
49
+ ctx.ui.notify("Subagent mode on. Use /subagents off to stop all workers and disable the tools.", "info");
50
+ }
51
+ if (command !== "on") pi.sendUserMessage(request);
52
+ },
53
+ });
54
+
55
+ pi.on("session_start", async (_event, ctx) => {
56
+ roster.attach(ctx);
57
+ setEnabled(false);
58
+ });
59
+
60
+ pi.on("session_shutdown", async () => {
61
+ await roster.dispose();
62
+ });
63
+ }
@@ -0,0 +1,43 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { normalizeName } from "./text";
3
+
4
+ export type WorkerModel = NonNullable<ExtensionContext["model"]>;
5
+
6
+ export function resolveModel(
7
+ modelQuery: string | undefined,
8
+ available: readonly WorkerModel[],
9
+ fallback: WorkerModel | undefined,
10
+ ): WorkerModel {
11
+ if (!modelQuery?.trim()) {
12
+ const model = fallback ?? available[0];
13
+ if (!model) throw new Error("No model available for subagent.");
14
+ return model;
15
+ }
16
+
17
+ const norm = normalizeName(modelQuery);
18
+ if (!norm) throw new Error(`No available model matches "${modelQuery}".`);
19
+ let best: { model: WorkerModel; score: number } | null = null;
20
+
21
+ for (const model of available) {
22
+ const pieces = [
23
+ `${model.provider || ""}/${model.id || ""}`,
24
+ String(model.id || ""),
25
+ String(model.name || ""),
26
+ String(model.provider || ""),
27
+ ];
28
+ let score = 0;
29
+ for (const piece of pieces.map(normalizeName)) {
30
+ if (!piece) continue;
31
+ if (piece === norm) score = Math.max(score, 1000);
32
+ else if (piece.startsWith(norm)) score = Math.max(score, 850);
33
+ else if (piece.includes(norm)) score = Math.max(score, 700);
34
+ }
35
+ const joined = normalizeName(pieces.join(" "));
36
+ if (joined === norm) score = Math.max(score, 950);
37
+ else if (joined.includes(norm)) score = Math.max(score, 650);
38
+ if (!best || score > best.score) best = { model, score };
39
+ }
40
+
41
+ if (!best || best.score === 0) throw new Error(`No available model matches "${modelQuery}".`);
42
+ return best.model;
43
+ }
package/src/report.ts ADDED
@@ -0,0 +1,143 @@
1
+ import {
2
+ type ExtensionAPI,
3
+ type ExtensionContext,
4
+ getMarkdownTheme,
5
+ type MessageRenderer,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { Container, Markdown, Text, TruncatedText } from "@earendil-works/pi-tui";
8
+ import { READ_MORE_HINT } from "./copy";
9
+ import { clip, formatDuration, getResultPage } from "./text";
10
+ import type { Worker } from "./worker";
11
+
12
+ export const REPORT_MESSAGE_TYPE = "subagent-report";
13
+
14
+ export interface SubagentReport {
15
+ agent: string;
16
+ runId: number;
17
+ model: string;
18
+ task: string;
19
+ status: "done" | "error";
20
+ outcome: string;
21
+ error?: string;
22
+ toolUses: number;
23
+ turns: number;
24
+ tokens: number;
25
+ duration: string;
26
+ sessionPath?: string;
27
+ }
28
+
29
+ export function buildReport(worker: Worker): SubagentReport {
30
+ const stats = worker.stats();
31
+ return {
32
+ agent: worker.name,
33
+ runId: worker.runId,
34
+ model: worker.info.modelLabel,
35
+ task: worker.task,
36
+ status: worker.error ? "error" : "done",
37
+ outcome: stats.outcome,
38
+ error: worker.error || undefined,
39
+ toolUses: stats.toolUses,
40
+ turns: stats.turns,
41
+ tokens: stats.tokens,
42
+ duration: formatDuration(stats.durationMs),
43
+ sessionPath: worker.session.sessionManager.getSessionFile(),
44
+ };
45
+ }
46
+
47
+ export class ReportOutbox {
48
+ private readonly clearableByEscape = new Map<number, SubagentReport>();
49
+
50
+ constructor(private readonly pi: ExtensionAPI) {}
51
+
52
+ deliver(report: SubagentReport, ctx: ExtensionContext | undefined): void {
53
+ if (ctx && !ctx.isIdle()) this.clearableByEscape.set(report.runId, report);
54
+ this.pi.sendMessage<SubagentReport>(reportMessage(report), { deliverAs: "steer", triggerTurn: true });
55
+ if (ctx?.hasUI)
56
+ ctx.ui.notify(
57
+ `${report.agent} ${report.status === "error" ? "failed" : "completed"}`,
58
+ report.status === "error" ? "error" : "info",
59
+ );
60
+ }
61
+
62
+ delivered(report: SubagentReport): void {
63
+ this.clearableByEscape.delete(report.runId);
64
+ }
65
+
66
+ resendClearedByEscape(): void {
67
+ for (const report of this.clearableByEscape.values())
68
+ this.pi.sendMessage<SubagentReport>(reportMessage(report), { deliverAs: "nextTurn" });
69
+ this.clearableByEscape.clear();
70
+ }
71
+
72
+ clear(): void {
73
+ this.clearableByEscape.clear();
74
+ }
75
+ }
76
+
77
+ function reportMessage(report: SubagentReport) {
78
+ const page = getResultPage(report.outcome);
79
+ const truncated = page.nextOffset !== undefined;
80
+ return {
81
+ customType: REPORT_MESSAGE_TYPE,
82
+ content: JSON.stringify({
83
+ agent: report.agent,
84
+ runId: report.runId,
85
+ status: report.status,
86
+ task: clip(report.task, 1_000),
87
+ result: page.content,
88
+ error: report.error ? clip(report.error, 2_000) : undefined,
89
+ truncated,
90
+ nextResultOffset: page.nextOffset,
91
+ sessionPath: report.sessionPath,
92
+ ...(truncated ? { readMore: READ_MORE_HINT } : {}),
93
+ }),
94
+ display: true,
95
+ details: report,
96
+ };
97
+ }
98
+
99
+ export function registerReportDelivery(pi: ExtensionAPI, outbox: ReportOutbox): void {
100
+ pi.registerMessageRenderer(REPORT_MESSAGE_TYPE, renderReport);
101
+ pi.on("message_end", async (event) => {
102
+ const message = event.message;
103
+ if (message.role === "custom" && message.customType === REPORT_MESSAGE_TYPE && message.details) {
104
+ outbox.delivered(message.details as SubagentReport);
105
+ }
106
+ });
107
+ // Escape in the TUI drops queued custom messages, including unread reports.
108
+ pi.on("agent_settled", async (event, ctx) => {
109
+ if (event.aborted && ctx.mode === "tui") outbox.resendClearedByEscape();
110
+ });
111
+ }
112
+
113
+ const renderReport: MessageRenderer<SubagentReport> = (message, options, theme) => {
114
+ const report = message.details;
115
+ const failed = report?.status === "error";
116
+ const outcome = report?.outcome || report?.error || "";
117
+ const card = new Container();
118
+ card.addChild(
119
+ new Text(
120
+ theme.fg(
121
+ failed ? "error" : "success",
122
+ `${failed ? "✗" : "✓"} ${report?.agent || "subagent"} ${failed ? "failed" : "completed"}`,
123
+ ) + theme.fg("dim", ` ${options.keyHint("app.tools.expand", options.expanded ? "to collapse" : "to expand")}`),
124
+ options.outputPad,
125
+ 0,
126
+ ),
127
+ );
128
+ card.addChild(
129
+ new TruncatedText(theme.fg("muted", `Task: ${(report?.task || "").replace(/\s+/g, " ")}`), options.outputPad, 0),
130
+ );
131
+ card.addChild(
132
+ options.expanded
133
+ ? new Markdown(outcome, options.outputPad, 0, getMarkdownTheme())
134
+ : new TruncatedText(outcome.replace(/\s+/g, " "), options.outputPad, 0),
135
+ );
136
+ if (failed && report?.error && outcome !== report.error)
137
+ card.addChild(new Text(theme.fg("error", report.error), options.outputPad, 0));
138
+ if (report?.sessionPath)
139
+ card.addChild(
140
+ new TruncatedText(theme.fg("dim", `Session: pi --session ${report.sessionPath}`), options.outputPad, 0),
141
+ );
142
+ return card;
143
+ };