@jalaxy33/pi-tmux-subagent 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jalaxy33
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,31 @@
1
- # Temporary Holding Version
1
+ # pi-tmux-subagent
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
+ Forked from [badlogic/pi-subagent](https://github.com/badlogic/pi-subagent). Observable, persistent Pi subagents for independent reviews, investigations, and delegated implementation. Each one runs in its own tmux session with a dedicated Pi session, so you can watch it work, steer it, wait for its result, or attach to its terminal.
4
+
5
+ ## Requirements
6
+
7
+ - Pi
8
+ - tmux
9
+
10
+ Windows is not supported, because tmux has no native Windows build. Run Pi inside WSL2 instead. When tmux is missing, the extension registers no tool or command and reports the reason on session start.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pi install npm:@jalaxy33/pi-tmux-subagent
16
+ # or from source
17
+ pi install git:github.com/jalaxy33/pi-tmux-subagent
18
+ ```
19
+
20
+ Run `/reload` in an existing Pi session. The extension registers the `subagent` tool and its skill; there is no symlink to create and no `PATH` entry to add. The checkout also contains `subagent.ts`, which offers the same commands as a CLI for scripts.
21
+
22
+ ## Usage
23
+
24
+ Ask for a subagent in plain language:
25
+
26
+ > Start a subagent named review that checks the current diff independently, then stop it once it has reported back.
27
+
28
+ - It inherits your provider, model, thinking level, and working directory. Ask for files, another model, or another directory when you need them.
29
+ - Restrict its tools by naming them, for example "give it only `read`, `grep`, `find`, and `ls`". That set is read-only; `bash` can also write files, so leave it out for reviews.
30
+ - Ask Pi to wait for the result, forward instructions while it works, rename the run, or stop it.
31
+ - `/subagent` lists this session's runs and attaches to one.
package/commands.ts ADDED
@@ -0,0 +1,364 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { existsSync, mkdirSync, readdirSync, renameSync, writeFileSync } from "node:fs";
3
+ import { spawnSync } from "node:child_process";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import {
7
+ assistantText,
8
+ effectiveRunState,
9
+ getRunsDir,
10
+ inboxDir,
11
+ launchRun,
12
+ listRuns,
13
+ readLatestAssistant,
14
+ readMetadata,
15
+ removeRunDir,
16
+ runDisplayName,
17
+ isValidRunName,
18
+ type InboxMessage,
19
+ type RunMetadata,
20
+ tmuxSessionExists,
21
+ tmuxUnavailableReason,
22
+ updateMetadata,
23
+ waitForRunShutdown,
24
+ writeMetadata,
25
+ } from "./shared.ts";
26
+
27
+ /** Session values the caller passes in: the CLI reads them from the environment, the tool from its context. */
28
+ export interface CommandContext {
29
+ sessionId?: string;
30
+ sessionFile?: string;
31
+ provider?: string;
32
+ model?: string;
33
+ thinking?: string;
34
+ cwd: string;
35
+ }
36
+
37
+ export interface CommandResult {
38
+ output: string;
39
+ ok: boolean;
40
+ }
41
+
42
+ const VALID_THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
43
+ const extensionPath = join(dirname(fileURLToPath(import.meta.url)), "index.ts");
44
+
45
+ function fail(message: string): never {
46
+ throw new Error(message);
47
+ }
48
+
49
+ function usage(): never {
50
+ fail(`Usage:
51
+ subagent spawn [--name <name>] [--provider <provider>] [--model <model>] [--thinking <level>]
52
+ [--cwd <dir>] [--tools <names>] [--no-extensions] [--no-skills]
53
+ [--no-prompt-templates] [--no-context-files] (--prompt <text> | --file <path>)...
54
+ subagent status <handle>
55
+ subagent rename <handle> <name>
56
+ subagent send <handle> [--follow-up] <message>
57
+ subagent wait <handle> [--timeout <seconds>]
58
+ subagent stop <handle>
59
+ subagent list`);
60
+ }
61
+
62
+ function valueAfter(args: string[], index: number, option: string): string {
63
+ const value = args[index + 1];
64
+ if (!value || value.startsWith("--")) fail(`${option} requires a value`);
65
+ return value;
66
+ }
67
+
68
+ function normalizeRunName(value: string): string {
69
+ const name = value.trim();
70
+ if (!isValidRunName(name)) fail("Subagent name must be a single line of 1 to 64 characters");
71
+ return name;
72
+ }
73
+
74
+ function runDirForHandle(handle: string): string {
75
+ if (!/^[a-z0-9]+$/.test(handle)) fail(`Invalid subagent handle: ${handle}`);
76
+ return join(getRunsDir(), handle);
77
+ }
78
+
79
+ function getRun(handle: string): RunMetadata {
80
+ const metadata = readMetadata(runDirForHandle(handle));
81
+ if (!metadata) fail(`Unknown subagent: ${handle}`);
82
+ return metadata;
83
+ }
84
+
85
+ function generateHandle(): string {
86
+ mkdirSync(getRunsDir(), { recursive: true, mode: 0o700 });
87
+ for (let attempt = 0; attempt < 100; attempt++) {
88
+ const handle = randomBytes(3).toString("hex");
89
+ if (!existsSync(runDirForHandle(handle))) return handle;
90
+ }
91
+ fail("Could not allocate a unique subagent handle");
92
+ }
93
+
94
+ function spawnSubagent(args: string[], context: CommandContext): string {
95
+ if (process.env.PI_SUBAGENT_RUN_DIR) fail("Nested subagents are disabled");
96
+ const unavailable = tmuxUnavailableReason();
97
+ if (unavailable) fail(unavailable);
98
+ let name: string | undefined;
99
+ let provider = context.provider;
100
+ let model = context.model;
101
+ let thinking = context.thinking || "medium";
102
+ let cwd = context.cwd;
103
+ let tools: string | undefined;
104
+ let noExtensions = false;
105
+ let noSkills = false;
106
+ let noPromptTemplates = false;
107
+ let noContextFiles = false;
108
+ const prompts: string[] = [];
109
+ const files: string[] = [];
110
+
111
+ for (let i = 0; i < args.length; i++) {
112
+ const arg = args[i];
113
+ switch (arg) {
114
+ case "--name":
115
+ name = normalizeRunName(valueAfter(args, i, arg));
116
+ i++;
117
+ break;
118
+ case "--provider":
119
+ provider = valueAfter(args, i, arg);
120
+ i++;
121
+ break;
122
+ case "--model":
123
+ model = valueAfter(args, i, arg);
124
+ i++;
125
+ break;
126
+ case "--thinking":
127
+ thinking = valueAfter(args, i, arg);
128
+ i++;
129
+ break;
130
+ case "--cwd":
131
+ cwd = resolve(context.cwd, valueAfter(args, i, arg));
132
+ i++;
133
+ break;
134
+ case "--tools":
135
+ tools = valueAfter(args, i, arg);
136
+ i++;
137
+ break;
138
+ case "--no-extensions":
139
+ noExtensions = true;
140
+ break;
141
+ case "--no-skills":
142
+ noSkills = true;
143
+ break;
144
+ case "--no-prompt-templates":
145
+ noPromptTemplates = true;
146
+ break;
147
+ case "--no-context-files":
148
+ noContextFiles = true;
149
+ break;
150
+ case "--prompt":
151
+ prompts.push(valueAfter(args, i, arg));
152
+ i++;
153
+ break;
154
+ case "--file": {
155
+ const file = resolve(context.cwd, valueAfter(args, i, arg));
156
+ if (!existsSync(file)) fail(`File not found: ${file}`);
157
+ files.push(file);
158
+ i++;
159
+ break;
160
+ }
161
+ default:
162
+ fail(`Unknown spawn argument: ${arg}`);
163
+ }
164
+ }
165
+
166
+ if (!provider) fail("No provider specified and no provider in the calling session");
167
+ if (!model) fail("No model specified and no model in the calling session");
168
+ if (!VALID_THINKING_LEVELS.has(thinking)) fail(`Invalid thinking level: ${thinking}`);
169
+ if (tools !== undefined && !tools.split(",").some((name) => name.trim()))
170
+ fail("--tools requires at least one tool name");
171
+ if (prompts.length === 0 && files.length === 0) fail("spawn requires at least one --prompt or --file");
172
+ if (!existsSync(cwd)) fail(`Working directory not found: ${cwd}`);
173
+
174
+ const handle = generateHandle();
175
+ const runDir = runDirForHandle(handle);
176
+ const sessionFile = join(runDir, "session.jsonl");
177
+ const tmuxSession = `pi-subagent-${handle}`;
178
+ mkdirSync(inboxDir(runDir), { recursive: true, mode: 0o700 });
179
+ writeFileSync(sessionFile, "", { mode: 0o600 });
180
+
181
+ const launchArgs: string[] = ["--extension", extensionPath];
182
+ if (tools) launchArgs.push("--tools", tools);
183
+ // The bridge must load even when the parent got this extension through -e or a package, so pass it explicitly.
184
+ if (noExtensions) launchArgs.push("--no-extensions");
185
+ if (noSkills) launchArgs.push("--no-skills");
186
+ if (noPromptTemplates) launchArgs.push("--no-prompt-templates");
187
+ if (noContextFiles) launchArgs.push("--no-context-files");
188
+
189
+ const now = new Date().toISOString();
190
+ const metadata: RunMetadata = {
191
+ version: 1,
192
+ handle,
193
+ name,
194
+ parentSessionId: context.sessionId,
195
+ parentSessionFile: context.sessionFile,
196
+ tmuxSession,
197
+ runDir,
198
+ sessionFile,
199
+ cwd,
200
+ provider,
201
+ model,
202
+ thinking,
203
+ launchArgs,
204
+ state: "starting",
205
+ hasStarted: false,
206
+ createdAt: now,
207
+ updatedAt: now,
208
+ };
209
+ writeMetadata(metadata);
210
+
211
+ const initialArgs = files.map((file) => `@${file}`);
212
+ if (prompts.length > 0) initialArgs.push(`Task:\n${prompts.join("\n\n")}`);
213
+ try {
214
+ launchRun(metadata, initialArgs);
215
+ } catch (error) {
216
+ removeRunDir(runDir);
217
+ throw error;
218
+ }
219
+
220
+ return `Spawned ${runDisplayName(metadata)}\nState: busy\nAttach: tmux attach -t ${tmuxSession}\n`;
221
+ }
222
+
223
+ function statusSubagent(args: string[]): string {
224
+ if (args.length !== 1) usage();
225
+ const metadata = getRun(args[0]);
226
+ return `${runDisplayName(metadata)}: ${effectiveRunState(metadata)} (${metadata.provider}/${metadata.model}, ${metadata.thinking})\nAttach: tmux attach -t ${metadata.tmuxSession}\n`;
227
+ }
228
+
229
+ function renameSubagent(args: string[]): string {
230
+ if (args.length !== 2) usage();
231
+ const metadata = getRun(args[0]);
232
+ const name = normalizeRunName(args[1]);
233
+ const updated = updateMetadata(metadata.runDir, { name });
234
+ if (!updated) fail(`Could not rename subagent: ${metadata.handle}`);
235
+ return `Renamed ${runDisplayName(updated)}\n`;
236
+ }
237
+
238
+ function sendSubagent(args: string[]): string {
239
+ const handle = args.shift();
240
+ if (!handle) usage();
241
+ let followUp = false;
242
+ const messageParts: string[] = [];
243
+ for (const arg of args) {
244
+ if (arg === "--follow-up") followUp = true;
245
+ else if (arg.startsWith("--")) fail(`Unknown send argument: ${arg}`);
246
+ else messageParts.push(arg);
247
+ }
248
+ const message = messageParts.join(" ").trim();
249
+ if (!message) fail("send requires a message");
250
+ const metadata = getRun(handle);
251
+ if (!tmuxSessionExists(metadata.tmuxSession)) fail(`${handle} is not running`);
252
+
253
+ const queueDir = inboxDir(metadata.runDir);
254
+ mkdirSync(queueDir, { recursive: true, mode: 0o700 });
255
+ const id = `${Date.now()}-${randomBytes(4).toString("hex")}`;
256
+ const target = join(queueDir, `${id}.json`);
257
+ const temporary = `${target}.tmp`;
258
+ const payload: InboxMessage = { message, delivery: followUp ? "followUp" : "auto" };
259
+ writeFileSync(temporary, `${JSON.stringify(payload)}\n`, { encoding: "utf8", mode: 0o600 });
260
+ renameSync(temporary, target);
261
+
262
+ const state = effectiveRunState(metadata);
263
+ const verb = followUp && state === "busy" ? "Queued follow-up for" : state === "idle" ? "Prompted" : "Steered";
264
+ return `${verb} ${runDisplayName(metadata)}\n`;
265
+ }
266
+
267
+ function parseTimeout(args: string[]): number {
268
+ if (args.length === 0) return 1800;
269
+ if (args.length !== 2 || args[0] !== "--timeout") usage();
270
+ const timeout = Number(args[1]);
271
+ if (!Number.isInteger(timeout) || timeout <= 0) fail("--timeout must be a positive integer");
272
+ return timeout;
273
+ }
274
+
275
+ function delay(ms: number, signal?: AbortSignal): Promise<void> {
276
+ return new Promise((resolveDelay, rejectDelay) => {
277
+ if (signal?.aborted) {
278
+ rejectDelay(new Error("Subagent wait cancelled"));
279
+ return;
280
+ }
281
+ const onAbort = (): void => {
282
+ clearTimeout(timer);
283
+ rejectDelay(new Error("Subagent wait cancelled"));
284
+ };
285
+ const timer = setTimeout(() => {
286
+ signal?.removeEventListener("abort", onAbort);
287
+ resolveDelay();
288
+ }, ms);
289
+ signal?.addEventListener("abort", onAbort, { once: true });
290
+ });
291
+ }
292
+
293
+ async function waitSubagent(args: string[], signal?: AbortSignal): Promise<CommandResult> {
294
+ const handle = args.shift();
295
+ if (!handle) usage();
296
+ const timeoutSeconds = parseTimeout(args);
297
+ const deadline = Date.now() + timeoutSeconds * 1000;
298
+
299
+ while (Date.now() < deadline) {
300
+ const metadata = getRun(handle);
301
+ const pending = existsSync(inboxDir(metadata.runDir))
302
+ ? readdirSync(inboxDir(metadata.runDir)).some((file) => file.endsWith(".json"))
303
+ : false;
304
+ const state = effectiveRunState(metadata);
305
+ if (state === "error") fail(metadata.error || `${handle} failed`);
306
+ if (state === "exited") fail(`${handle} exited before finishing`);
307
+ if (metadata.hasStarted && state === "idle" && !pending) {
308
+ const message = readLatestAssistant(metadata.sessionFile);
309
+ if (!message) fail(`${handle} finished without an assistant response`);
310
+ const broken = message.stopReason === "error" || message.stopReason === "aborted";
311
+ return { output: `${handle} finished\n\n${assistantText(message)}\n`, ok: !broken };
312
+ }
313
+ await delay(500, signal);
314
+ }
315
+ fail(`Timed out after ${timeoutSeconds}s waiting for ${handle}`);
316
+ }
317
+
318
+ async function stopSubagent(args: string[]): Promise<string> {
319
+ if (args.length !== 1) usage();
320
+ const metadata = getRun(args[0]);
321
+ const wasRunning = tmuxSessionExists(metadata.tmuxSession);
322
+ spawnSync("tmux", ["kill-session", "-t", metadata.tmuxSession], { stdio: "ignore" });
323
+ if (wasRunning) await waitForRunShutdown(metadata.runDir);
324
+ removeRunDir(metadata.runDir);
325
+ return `Stopped ${runDisplayName(metadata)}\n`;
326
+ }
327
+
328
+ function listSubagents(args: string[], context: CommandContext): string {
329
+ if (args.length !== 0) usage();
330
+ const runs = listRuns(context.sessionId);
331
+ if (runs.length === 0) return "No subagents\n";
332
+ return runs
333
+ .map(
334
+ (metadata) =>
335
+ `${runDisplayName(metadata)} ${effectiveRunState(metadata).padEnd(8)} ${metadata.provider}/${metadata.model} ${metadata.thinking}\n`,
336
+ )
337
+ .join("");
338
+ }
339
+
340
+ export async function runSubagentCommand(
341
+ argv: string[],
342
+ context: CommandContext,
343
+ signal?: AbortSignal,
344
+ ): Promise<CommandResult> {
345
+ const args = [...argv];
346
+ switch (args.shift()) {
347
+ case "spawn":
348
+ return { output: spawnSubagent(args, context), ok: true };
349
+ case "status":
350
+ return { output: statusSubagent(args), ok: true };
351
+ case "rename":
352
+ return { output: renameSubagent(args), ok: true };
353
+ case "send":
354
+ return { output: sendSubagent(args), ok: true };
355
+ case "wait":
356
+ return waitSubagent(args, signal);
357
+ case "stop":
358
+ return { output: await stopSubagent(args), ok: true };
359
+ case "list":
360
+ return { output: listSubagents(args, context), ok: true };
361
+ default:
362
+ usage();
363
+ }
364
+ }
package/index.ts ADDED
@@ -0,0 +1,426 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, readdirSync, unlinkSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { defineTool, DynamicBorder, type ExtensionAPI, type ExtensionContext, keyHint } from "@earendil-works/pi-coding-agent";
6
+ import { Container, type SelectItem, SelectList, Text, type TUI } from "@earendil-works/pi-tui";
7
+ import { Type, type Static } from "typebox";
8
+ import { runSubagentCommand } from "./commands.ts";
9
+ import {
10
+ effectiveRunState,
11
+ inboxDir,
12
+ launchRun,
13
+ listRuns,
14
+ readMetadata,
15
+ removeRunDir,
16
+ runDisplayName,
17
+ type InboxMessage,
18
+ type RunMetadata,
19
+ tmuxSessionExists,
20
+ tmuxUnavailableReason,
21
+ updateMetadata,
22
+ waitForRunShutdown,
23
+ } from "./shared.ts";
24
+
25
+ const packageDir = dirname(fileURLToPath(import.meta.url));
26
+
27
+ function isInboxMessage(value: unknown): value is InboxMessage {
28
+ if (typeof value !== "object" || value === null) return false;
29
+ const message = value as Record<string, unknown>;
30
+ return typeof message.message === "string" && (message.delivery === "auto" || message.delivery === "followUp");
31
+ }
32
+
33
+ function displayState(metadata: RunMetadata): string {
34
+ return effectiveRunState(metadata).padEnd(8);
35
+ }
36
+
37
+ const subagentParameters = Type.Object({
38
+ action: Type.Union(
39
+ [
40
+ Type.Literal("spawn"),
41
+ Type.Literal("list"),
42
+ Type.Literal("status"),
43
+ Type.Literal("wait"),
44
+ Type.Literal("send"),
45
+ Type.Literal("rename"),
46
+ Type.Literal("stop"),
47
+ ],
48
+ { description: "Command to run" },
49
+ ),
50
+ handle: Type.Optional(
51
+ Type.String({ description: "Subagent handle from spawn. Required for every action except spawn and list." }),
52
+ ),
53
+ name: Type.Optional(
54
+ Type.String({ description: "spawn: display name, 1 to 64 characters. rename: the new name." }),
55
+ ),
56
+ prompt: Type.Optional(Type.String({ description: "spawn: task text for the subagent's first user turn." })),
57
+ files: Type.Optional(
58
+ Type.Array(Type.String(), { description: "spawn: files to hand to the subagent as @-references." }),
59
+ ),
60
+ provider: Type.Optional(Type.String({ description: "spawn: model provider. Defaults to the calling session's." })),
61
+ model: Type.Optional(Type.String({ description: "spawn: model id. Defaults to the calling session's." })),
62
+ thinking: Type.Optional(Type.String({ description: "spawn: thinking level. Defaults to the calling session's." })),
63
+ cwd: Type.Optional(Type.String({ description: "spawn: working directory. Defaults to the calling session's." })),
64
+ tools: Type.Optional(
65
+ Type.String({ description: "spawn: comma-separated tool allowlist, for example read,grep,find,ls." }),
66
+ ),
67
+ noExtensions: Type.Optional(
68
+ Type.Boolean({ description: "spawn: disable extension discovery except the control bridge." }),
69
+ ),
70
+ noSkills: Type.Optional(Type.Boolean({ description: "spawn: disable skills." })),
71
+ noPromptTemplates: Type.Optional(Type.Boolean({ description: "spawn: disable prompt templates." })),
72
+ noContextFiles: Type.Optional(Type.Boolean({ description: "spawn: ignore repository instruction files." })),
73
+ message: Type.Optional(Type.String({ description: "send: message for the subagent." })),
74
+ followUp: Type.Optional(
75
+ Type.Boolean({ description: "send: queue the message after the current turn instead of steering it." }),
76
+ ),
77
+ timeoutSeconds: Type.Optional(Type.Number({ description: "wait: timeout in seconds. Defaults to 1800." })),
78
+ });
79
+
80
+ type SubagentToolParams = Static<typeof subagentParameters>;
81
+
82
+ const subagentTool = defineTool({
83
+ name: "subagent",
84
+ label: "Subagent",
85
+ description: `Manage observable Pi subagents. Each subagent runs in its own tmux session with its own Pi session and context, so it can investigate or implement work without crowding this conversation.
86
+
87
+ Actions:
88
+ - spawn: start a subagent; returns its handle and tmux attach command.
89
+ - list: show the subagents spawned by this session with their state.
90
+ - status: show one subagent's state.
91
+ - wait: block until the subagent finishes its turn and return its final message.
92
+ - send: steer a running subagent, or queue a follow-up with followUp.
93
+ - rename: change the display name.
94
+ - stop: terminate the subagent and delete its transcript.
95
+
96
+ Spawn for work that benefits from an independent context, then wait for the result. Stop every subagent when its work is no longer needed.`,
97
+ promptSnippet: "spawn and manage observable Pi subagents with their own session and tmux terminal",
98
+ promptGuidelines: [
99
+ "Use the subagent tool for independent reviews, investigations, and delegated implementation instead of doing everything in one context. Stop subagents you no longer need.",
100
+ ],
101
+ parameters: subagentParameters,
102
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
103
+ const result = await runSubagentCommand(
104
+ buildArgv(params),
105
+ {
106
+ sessionId: ctx.sessionManager.getSessionId(),
107
+ sessionFile: ctx.sessionManager.getSessionFile(),
108
+ provider: ctx.model?.provider,
109
+ model: ctx.model?.id,
110
+ thinking: ctx.thinkingLevel,
111
+ cwd: ctx.cwd,
112
+ },
113
+ signal,
114
+ );
115
+ return {
116
+ content: [{ type: "text" as const, text: result.output }],
117
+ details: { action: params.action, ok: result.ok },
118
+ isError: !result.ok,
119
+ };
120
+ },
121
+ });
122
+
123
+ function buildArgv(params: SubagentToolParams): string[] {
124
+ const argv: string[] = [params.action];
125
+ switch (params.action) {
126
+ case "spawn":
127
+ if (params.name) argv.push("--name", params.name);
128
+ if (params.provider) argv.push("--provider", params.provider);
129
+ if (params.model) argv.push("--model", params.model);
130
+ if (params.thinking) argv.push("--thinking", params.thinking);
131
+ if (params.cwd) argv.push("--cwd", params.cwd);
132
+ if (params.tools) argv.push("--tools", params.tools);
133
+ if (params.noExtensions) argv.push("--no-extensions");
134
+ if (params.noSkills) argv.push("--no-skills");
135
+ if (params.noPromptTemplates) argv.push("--no-prompt-templates");
136
+ if (params.noContextFiles) argv.push("--no-context-files");
137
+ for (const file of params.files ?? []) argv.push("--file", file);
138
+ if (params.prompt) argv.push("--prompt", params.prompt);
139
+ return argv;
140
+ case "list":
141
+ return argv;
142
+ case "rename":
143
+ if (!params.handle || !params.name) throw new Error("rename requires handle and name");
144
+ return [...argv, params.handle, params.name];
145
+ case "send":
146
+ if (!params.handle || !params.message) throw new Error("send requires handle and message");
147
+ return [...argv, params.handle, ...(params.followUp ? ["--follow-up"] : []), params.message];
148
+ case "wait":
149
+ if (!params.handle) throw new Error("wait requires a handle");
150
+ return [...argv, params.handle, ...(params.timeoutSeconds != null ? ["--timeout", String(params.timeoutSeconds)] : [])];
151
+ default:
152
+ if (!params.handle) throw new Error(`${params.action} requires a handle`);
153
+ return [...argv, params.handle];
154
+ }
155
+ }
156
+
157
+ export default function subagentExtension(pi: ExtensionAPI) {
158
+ const runDir = process.env.PI_SUBAGENT_RUN_DIR;
159
+ const unavailable = runDir ? undefined : tmuxUnavailableReason();
160
+ if (unavailable) {
161
+ // Nothing here can work without tmux, so register no tool or skill and explain once per session.
162
+ pi.on("session_start", (_event, ctx) => {
163
+ if (ctx.hasUI) ctx.ui.notify(unavailable, "warning");
164
+ });
165
+ return;
166
+ }
167
+ if (!runDir) {
168
+ pi.on("resources_discover", () => ({ skillPaths: [join(packageDir, "skills")] }));
169
+ pi.registerTool(subagentTool);
170
+ }
171
+
172
+ pi.registerCommand("subagent", {
173
+ description: "Select and attach to a subagent spawned by this session",
174
+ handler: async (_args, ctx) => {
175
+ const runs = listRuns(ctx.sessionManager.getSessionId()).filter((run) => effectiveRunState(run) !== "exited");
176
+ if (runs.length === 0) {
177
+ ctx.ui.notify("No active subagents spawned by this session", "info");
178
+ return;
179
+ }
180
+
181
+ const items: SelectItem[] = runs.map((run) => ({
182
+ value: run.handle,
183
+ label: `${runDisplayName(run)} ${displayState(run)} ${run.provider}/${run.model} ${run.thinking}`,
184
+ }));
185
+ let tui: TUI | undefined;
186
+ const selected = await ctx.ui.custom<string | undefined>((customTui, theme, _keybindings, done) => {
187
+ tui = customTui;
188
+ const list = new SelectList(items, Math.min(items.length, 10), {
189
+ selectedPrefix: (text) => theme.fg("accent", text),
190
+ selectedText: (text) => theme.fg("accent", text),
191
+ description: (text) => theme.fg("muted", text),
192
+ scrollInfo: (text) => theme.fg("dim", text),
193
+ noMatch: (text) => theme.fg("warning", text),
194
+ });
195
+ list.onSelect = (item) => done(item.value);
196
+ list.onCancel = () => done(undefined);
197
+
198
+ const container = new Container();
199
+ container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
200
+ container.addChild(new Text(theme.fg("accent", theme.bold("Attach to subagent")), 1, 0));
201
+ container.addChild(list);
202
+ container.addChild(
203
+ new Text(
204
+ theme.fg(
205
+ "dim",
206
+ `${keyHint("tui.select.confirm", "attach")} ${keyHint("tui.select.cancel", "cancel")}`,
207
+ ),
208
+ 1,
209
+ 0,
210
+ ),
211
+ );
212
+ container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
213
+
214
+ return {
215
+ render: (width) => container.render(width),
216
+ invalidate: () => container.invalidate(),
217
+ handleInput: (data) => {
218
+ list.handleInput(data);
219
+ customTui.requestRender();
220
+ },
221
+ };
222
+ });
223
+ if (!selected || !tui) return;
224
+ const run = runs.find((candidate) => candidate.handle === selected);
225
+ if (!run) return;
226
+
227
+ if (process.env.TMUX) {
228
+ const exitCode = await new Promise<number | null>((resolveExit) => {
229
+ const child = spawn("tmux", ["switch-client", "-t", run.tmuxSession], { stdio: "inherit" });
230
+ child.on("error", () => resolveExit(null));
231
+ child.on("close", resolveExit);
232
+ });
233
+ if (exitCode !== 0) ctx.ui.notify(`Could not switch to ${run.handle}`, "error");
234
+ return;
235
+ }
236
+
237
+ tui.stop();
238
+ try {
239
+ const exitCode = await new Promise<number | null>((resolveExit) => {
240
+ const child = spawn("tmux", ["attach-session", "-t", run.tmuxSession], { stdio: "inherit" });
241
+ child.on("error", () => resolveExit(null));
242
+ child.on("close", resolveExit);
243
+ });
244
+ if (exitCode !== 0) process.stderr.write(`Could not attach to ${run.handle}\n`);
245
+ } finally {
246
+ tui.start();
247
+ tui.requestRender(true);
248
+ }
249
+ },
250
+ });
251
+
252
+ if (!runDir) {
253
+ let widgetTimer: ReturnType<typeof setInterval> | undefined;
254
+ let widgetContext: ExtensionContext | undefined;
255
+
256
+ const refreshWidget = (): void => {
257
+ if (!widgetContext) return;
258
+ const activeRuns = listRuns(widgetContext.sessionManager.getSessionId())
259
+ .map((run) => ({ run, state: effectiveRunState(run) }))
260
+ .filter(({ state }) => state !== "exited");
261
+ if (activeRuns.length === 0) {
262
+ widgetContext.ui.setWidget("subagents", undefined);
263
+ return;
264
+ }
265
+
266
+ const visible = activeRuns.slice(0, 5).map(({ run, state }) => {
267
+ const color =
268
+ state === "busy" ? "warning" : state === "idle" ? "success" : state === "error" ? "error" : "muted";
269
+ return widgetContext!.ui.theme.fg(color, `${run.name ?? run.handle}:${state}`);
270
+ });
271
+ if (activeRuns.length > visible.length) {
272
+ visible.push(widgetContext.ui.theme.fg("muted", `+${activeRuns.length - visible.length}`));
273
+ }
274
+ widgetContext.ui.setWidget(
275
+ "subagents",
276
+ [widgetContext.ui.theme.fg("dim", "subagents: ") + visible.join(widgetContext.ui.theme.fg("dim", " | "))],
277
+ { placement: "belowEditor" },
278
+ );
279
+ };
280
+
281
+ pi.on("session_start", (_event, ctx) => {
282
+ // Relaunch children that were suspended when this session was last quit or switched away from.
283
+ for (const run of listRuns(ctx.sessionManager.getSessionId())) {
284
+ if (!run.suspended || tmuxSessionExists(run.tmuxSession)) continue;
285
+ if (!existsSync(run.sessionFile)) {
286
+ removeRunDir(run.runDir);
287
+ continue;
288
+ }
289
+ const starting = updateMetadata(run.runDir, { state: "starting", error: undefined }) ?? run;
290
+ try {
291
+ launchRun(starting);
292
+ } catch (error) {
293
+ const message = error instanceof Error ? error.message : String(error);
294
+ updateMetadata(run.runDir, { state: "error", error: message });
295
+ if (ctx.hasUI) ctx.ui.notify(`Could not resume subagent ${runDisplayName(run)}: ${message}`, "error");
296
+ }
297
+ }
298
+
299
+ if (!ctx.hasUI) return;
300
+ widgetContext = ctx;
301
+ refreshWidget();
302
+ widgetTimer = setInterval(refreshWidget, 1000);
303
+ widgetTimer.unref();
304
+ });
305
+
306
+ pi.on("session_shutdown", async (event, ctx) => {
307
+ if (widgetTimer) clearInterval(widgetTimer);
308
+ widgetTimer = undefined;
309
+ widgetContext = undefined;
310
+ ctx.ui.setWidget("subagents", undefined);
311
+ if (event.reason === "reload") return;
312
+ // Suspend running children: stop the process but keep transcript and metadata so resuming this
313
+ // session relaunches them. Children that already exited on their own are discarded.
314
+ for (const run of listRuns(ctx.sessionManager.getSessionId())) {
315
+ if (!tmuxSessionExists(run.tmuxSession)) {
316
+ if (!run.suspended) removeRunDir(run.runDir);
317
+ continue;
318
+ }
319
+ updateMetadata(run.runDir, { suspended: true });
320
+ spawnSync("tmux", ["kill-session", "-t", run.tmuxSession], { stdio: "ignore" });
321
+ await waitForRunShutdown(run.runDir);
322
+ }
323
+ });
324
+ return;
325
+ }
326
+
327
+ let currentContext: ExtensionContext | undefined;
328
+ let timer: ReturnType<typeof setInterval> | undefined;
329
+ let processing = false;
330
+ let sessionName: string | undefined;
331
+
332
+ const syncSessionName = (): void => {
333
+ const metadata = readMetadata(runDir);
334
+ if (!metadata) return;
335
+ const next = `subagent ${metadata.name ?? metadata.handle}`;
336
+ if (next === sessionName) return;
337
+ pi.setSessionName(next);
338
+ sessionName = next;
339
+ };
340
+
341
+ const processInbox = async (): Promise<void> => {
342
+ if (processing || !currentContext) return;
343
+ syncSessionName();
344
+ const queueDir = inboxDir(runDir);
345
+ if (!existsSync(queueDir)) return;
346
+ processing = true;
347
+ try {
348
+ for (const name of readdirSync(queueDir)
349
+ .filter((entry) => entry.endsWith(".json"))
350
+ .sort()) {
351
+ const path = join(queueDir, name);
352
+ let payload: InboxMessage;
353
+ try {
354
+ const value: unknown = JSON.parse(readFileSync(path, "utf8"));
355
+ if (!isInboxMessage(value)) throw new Error("Invalid inbox message");
356
+ payload = value;
357
+ } catch (error) {
358
+ unlinkSync(path);
359
+ updateMetadata(runDir, {
360
+ state: "error",
361
+ error: error instanceof Error ? error.message : String(error),
362
+ });
363
+ continue;
364
+ }
365
+
366
+ updateMetadata(runDir, { state: "busy", error: undefined });
367
+ try {
368
+ if (currentContext.isIdle()) {
369
+ pi.sendUserMessage(payload.message);
370
+ } else {
371
+ pi.sendUserMessage(payload.message, {
372
+ deliverAs: payload.delivery === "followUp" ? "followUp" : "steer",
373
+ });
374
+ }
375
+ unlinkSync(path);
376
+ } catch (error) {
377
+ updateMetadata(runDir, {
378
+ state: currentContext.isIdle() ? "idle" : "busy",
379
+ error: error instanceof Error ? error.message : String(error),
380
+ });
381
+ return;
382
+ }
383
+ }
384
+ } finally {
385
+ processing = false;
386
+ }
387
+ };
388
+
389
+ pi.on("session_start", (_event, ctx) => {
390
+ currentContext = ctx;
391
+ const metadata = readMetadata(runDir);
392
+ if (!metadata) return;
393
+ updateMetadata(runDir, {
394
+ childSessionId: ctx.sessionManager.getSessionId(),
395
+ sessionFile: ctx.sessionManager.getSessionFile() ?? metadata.sessionFile,
396
+ state: ctx.isIdle() ? "idle" : "busy",
397
+ suspended: undefined,
398
+ error: undefined,
399
+ });
400
+ syncSessionName();
401
+ if (!timer) {
402
+ timer = setInterval(() => void processInbox(), 250);
403
+ timer.unref();
404
+ }
405
+ void processInbox();
406
+ });
407
+
408
+ pi.on("agent_start", (_event, ctx) => {
409
+ currentContext = ctx;
410
+ updateMetadata(runDir, { state: "busy", hasStarted: true, error: undefined });
411
+ });
412
+
413
+ pi.on("agent_settled", (_event, ctx) => {
414
+ currentContext = ctx;
415
+ if (ctx.isIdle()) updateMetadata(runDir, { state: "idle" });
416
+ });
417
+
418
+ pi.on("session_shutdown", (event) => {
419
+ currentContext = undefined;
420
+ if (timer) {
421
+ clearInterval(timer);
422
+ timer = undefined;
423
+ }
424
+ if (event.reason === "quit") updateMetadata(runDir, { state: "exited" });
425
+ });
426
+ }
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@jalaxy33/pi-tmux-subagent",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Observable Pi subagents that run in their own tmux session.",
5
+ "keywords": ["pi-package", "pi", "subagent", "tmux"],
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/jalaxy33/pi-tmux-subagent.git"
10
+ },
11
+ "type": "module",
12
+ "bin": {
13
+ "subagent": "subagent.ts"
14
+ },
15
+ "files": ["index.ts", "commands.ts", "shared.ts", "subagent.ts", "skills"],
16
+ "pi": {
17
+ "extensions": ["./index.ts"]
18
+ },
19
+ "engines": {
20
+ "node": ">=22.19.0"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "registry": "https://registry.npmjs.org/"
25
+ },
26
+ "peerDependencies": {
27
+ "@earendil-works/pi-coding-agent": "*",
28
+ "@earendil-works/pi-tui": "*",
29
+ "typebox": "*"
30
+ }
31
+ }
package/shared.ts ADDED
@@ -0,0 +1,304 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import {
3
+ accessSync,
4
+ constants,
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ readdirSync,
9
+ renameSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import { dirname, join } from "node:path";
15
+
16
+ export type RunState = "starting" | "busy" | "idle" | "exited" | "error";
17
+
18
+ export interface RunMetadata {
19
+ version: 1;
20
+ handle: string;
21
+ name?: string;
22
+ parentSessionId?: string;
23
+ parentSessionFile?: string;
24
+ childSessionId?: string;
25
+ tmuxSession: string;
26
+ runDir: string;
27
+ sessionFile: string;
28
+ cwd: string;
29
+ provider: string;
30
+ model: string;
31
+ thinking: string;
32
+ /** Extra pi CLI flags (tools, isolation) reused when the run is relaunched. */
33
+ launchArgs?: string[];
34
+ /** Set by the parent when it stops the child on quit or session switch; the child is relaunched on resume. */
35
+ suspended?: boolean;
36
+ state: RunState;
37
+ hasStarted: boolean;
38
+ createdAt: string;
39
+ updatedAt: string;
40
+ error?: string;
41
+ }
42
+
43
+ export interface InboxMessage {
44
+ message: string;
45
+ delivery: "auto" | "followUp";
46
+ }
47
+
48
+ interface SessionEntry {
49
+ type: string;
50
+ id: string;
51
+ parentId: string | null;
52
+ message?: unknown;
53
+ }
54
+
55
+ interface AssistantMessage {
56
+ role: "assistant";
57
+ content?: unknown;
58
+ stopReason?: string;
59
+ errorMessage?: string;
60
+ }
61
+
62
+ interface AssistantEntry extends SessionEntry {
63
+ type: "message";
64
+ message: AssistantMessage;
65
+ }
66
+
67
+ export function getAgentDir(): string {
68
+ return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
69
+ }
70
+
71
+ export function getRunsDir(): string {
72
+ return join(getAgentDir(), "subagents");
73
+ }
74
+
75
+ export function metadataPath(runDir: string): string {
76
+ return join(runDir, "metadata.json");
77
+ }
78
+
79
+ export function inboxDir(runDir: string): string {
80
+ return join(runDir, "inbox");
81
+ }
82
+
83
+ export function isValidRunName(value: unknown): value is string {
84
+ return (
85
+ typeof value === "string" &&
86
+ value.length > 0 &&
87
+ value.length <= 64 &&
88
+ value.trim() === value &&
89
+ !/[\u0000-\u001f\u007f]/.test(value)
90
+ );
91
+ }
92
+
93
+ export function runDisplayName(metadata: RunMetadata): string {
94
+ return metadata.name ? `${metadata.name} (${metadata.handle})` : metadata.handle;
95
+ }
96
+
97
+ export function readMetadata(runDir: string): RunMetadata | undefined {
98
+ try {
99
+ const value: unknown = JSON.parse(readFileSync(metadataPath(runDir), "utf8"));
100
+ if (typeof value !== "object" || value === null) return undefined;
101
+ const metadata = value as Partial<RunMetadata>;
102
+ if (
103
+ metadata.version !== 1 ||
104
+ typeof metadata.handle !== "string" ||
105
+ (metadata.name !== undefined && !isValidRunName(metadata.name)) ||
106
+ typeof metadata.tmuxSession !== "string" ||
107
+ typeof metadata.sessionFile !== "string" ||
108
+ typeof metadata.runDir !== "string"
109
+ ) {
110
+ return undefined;
111
+ }
112
+ return metadata as RunMetadata;
113
+ } catch {
114
+ return undefined;
115
+ }
116
+ }
117
+
118
+ export function writeMetadata(metadata: RunMetadata): void {
119
+ mkdirSync(dirname(metadataPath(metadata.runDir)), { recursive: true, mode: 0o700 });
120
+ const target = metadataPath(metadata.runDir);
121
+ const temporary = `${target}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
122
+ writeFileSync(temporary, `${JSON.stringify(metadata, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
123
+ renameSync(temporary, target);
124
+ }
125
+
126
+ export function updateMetadata(runDir: string, patch: Partial<RunMetadata>): RunMetadata | undefined {
127
+ const current = readMetadata(runDir);
128
+ if (!current) return undefined;
129
+ const next: RunMetadata = {
130
+ ...current,
131
+ ...patch,
132
+ version: 1,
133
+ handle: current.handle,
134
+ runDir: current.runDir,
135
+ updatedAt: new Date().toISOString(),
136
+ };
137
+ writeMetadata(next);
138
+ return next;
139
+ }
140
+
141
+ export async function waitForRunShutdown(runDir: string, timeoutMs = 2000): Promise<void> {
142
+ const deadline = Date.now() + timeoutMs;
143
+ while (Date.now() < deadline) {
144
+ const metadata = readMetadata(runDir);
145
+ if (!metadata || metadata.state === "exited") return;
146
+ await new Promise<void>((resolveDelay) => setTimeout(resolveDelay, 50));
147
+ }
148
+ }
149
+
150
+ export function removeRunDir(runDir: string): void {
151
+ rmSync(runDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
152
+ }
153
+
154
+ export function tmuxSessionExists(session: string): boolean {
155
+ return spawnSync("tmux", ["has-session", "-t", session], { stdio: "ignore" }).status === 0;
156
+ }
157
+
158
+ /** Why subagents cannot run here, or undefined when tmux is usable. */
159
+ export function tmuxUnavailableReason(): string | undefined {
160
+ if (process.platform === "win32") {
161
+ return "Subagents need tmux, which has no native Windows build. Run Pi inside WSL2 or on macOS/Linux.";
162
+ }
163
+ const probe = spawnSync("tmux", ["-V"], { encoding: "utf8", timeout: 5000 });
164
+ const code = (probe.error as NodeJS.ErrnoException | undefined)?.code;
165
+ if (code === "ENOENT") {
166
+ return "Subagents need tmux, but it is not installed or not on PATH. Install tmux, then run /reload.";
167
+ }
168
+ if (probe.error) {
169
+ return `Subagents need tmux, but tmux cannot run here: ${probe.error.message}`;
170
+ }
171
+ if (probe.status !== 0) {
172
+ const detail = probe.stderr.trim() || `exit code ${probe.status}`;
173
+ return `Subagents need tmux, but "tmux -V" failed: ${detail}`;
174
+ }
175
+ return undefined;
176
+ }
177
+
178
+ /** Start the child pi process for a run in its tmux session. `initialArgs` are only passed on first spawn. */
179
+ export function launchRun(metadata: RunMetadata, initialArgs: string[] = []): void {
180
+ let launcher = "pi";
181
+ const testLauncher = join(metadata.cwd, "pi-test.sh");
182
+ try {
183
+ accessSync(testLauncher, constants.X_OK);
184
+ launcher = testLauncher;
185
+ } catch {
186
+ // Use the installed pi executable.
187
+ }
188
+
189
+ const result = spawnSync(
190
+ "tmux",
191
+ [
192
+ "new-session",
193
+ "-d",
194
+ "-s",
195
+ metadata.tmuxSession,
196
+ "-x",
197
+ "120",
198
+ "-y",
199
+ "40",
200
+ "-c",
201
+ metadata.cwd,
202
+ "--",
203
+ "env",
204
+ `PI_SUBAGENT_RUN_DIR=${metadata.runDir}`,
205
+ launcher,
206
+ "--session",
207
+ metadata.sessionFile,
208
+ "--provider",
209
+ metadata.provider,
210
+ "--model",
211
+ metadata.model,
212
+ "--thinking",
213
+ metadata.thinking,
214
+ ...(metadata.launchArgs ?? []),
215
+ ...initialArgs,
216
+ ],
217
+ { encoding: "utf8" },
218
+ );
219
+ if (result.error) throw new Error(result.error.message);
220
+ if (result.status !== 0) throw new Error(result.stderr.trim() || "Failed to create tmux session");
221
+ }
222
+
223
+ export function effectiveRunState(metadata: RunMetadata): RunState {
224
+ if (
225
+ (metadata.state === "starting" || metadata.state === "busy" || metadata.state === "idle") &&
226
+ !tmuxSessionExists(metadata.tmuxSession)
227
+ ) {
228
+ return "exited";
229
+ }
230
+ return metadata.state;
231
+ }
232
+
233
+ export function listRuns(parentSessionId?: string): RunMetadata[] {
234
+ const root = getRunsDir();
235
+ if (!existsSync(root)) return [];
236
+ const runs: RunMetadata[] = [];
237
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
238
+ if (!entry.isDirectory()) continue;
239
+ const metadata = readMetadata(join(root, entry.name));
240
+ if (!metadata) continue;
241
+ if (parentSessionId && metadata.parentSessionId !== parentSessionId) continue;
242
+ runs.push(metadata);
243
+ }
244
+ return runs.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
245
+ }
246
+
247
+ function isSessionEntry(value: unknown): value is SessionEntry {
248
+ if (typeof value !== "object" || value === null) return false;
249
+ const entry = value as Record<string, unknown>;
250
+ return (
251
+ typeof entry.type === "string" &&
252
+ typeof entry.id === "string" &&
253
+ (entry.parentId === null || typeof entry.parentId === "string")
254
+ );
255
+ }
256
+
257
+ function activeBranch(entries: SessionEntry[]): SessionEntry[] {
258
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
259
+ const branch: SessionEntry[] = [];
260
+ const seen = new Set<string>();
261
+ let current = entries.at(-1);
262
+ while (current && !seen.has(current.id)) {
263
+ branch.push(current);
264
+ seen.add(current.id);
265
+ current = current.parentId === null ? undefined : byId.get(current.parentId);
266
+ }
267
+ return branch.reverse();
268
+ }
269
+
270
+ function isAssistantEntry(entry: SessionEntry): entry is AssistantEntry {
271
+ if (entry.type !== "message" || typeof entry.message !== "object" || entry.message === null) return false;
272
+ return (entry.message as Record<string, unknown>).role === "assistant";
273
+ }
274
+
275
+ export function readLatestAssistant(sessionFile: string): AssistantMessage | undefined {
276
+ let content: string;
277
+ try {
278
+ content = readFileSync(sessionFile, "utf8");
279
+ } catch {
280
+ return undefined;
281
+ }
282
+ const entries: SessionEntry[] = [];
283
+ for (const line of content.split("\n")) {
284
+ if (!line.trim()) continue;
285
+ try {
286
+ const value: unknown = JSON.parse(line);
287
+ if (isSessionEntry(value)) entries.push(value);
288
+ } catch {
289
+ // The final JSONL record may still be in the process of being appended.
290
+ }
291
+ }
292
+ return activeBranch(entries).findLast(isAssistantEntry)?.message;
293
+ }
294
+
295
+ export function assistantText(message: AssistantMessage): string {
296
+ if (!Array.isArray(message.content)) return message.errorMessage ?? "(no response text)";
297
+ const parts: string[] = [];
298
+ for (const item of message.content) {
299
+ if (typeof item !== "object" || item === null) continue;
300
+ const block = item as Record<string, unknown>;
301
+ if (block.type === "text" && typeof block.text === "string") parts.push(block.text);
302
+ }
303
+ return parts.join("\n").trim() || message.errorMessage || "(no response text)";
304
+ }
@@ -0,0 +1,72 @@
1
+ ---
2
+ name: subagent
3
+ description: Spawn and communicate with observable Pi subagents for second opinions, independent investigations, and delegated implementation work.
4
+ ---
5
+
6
+ # Subagent
7
+
8
+ Use the `subagent` tool to delegate work to a separate Pi process with its own context and tmux session. Managed subagents cannot spawn nested subagents, and this skill is not loaded into their sessions.
9
+
10
+ ## Spawn
11
+
12
+ Give each child a short, descriptive name. The name appears in the parent UI, while the returned handle remains its stable identifier:
13
+
14
+ ```json
15
+ { "action": "spawn", "name": "implementation", "prompt": "Complete task" }
16
+ ```
17
+
18
+ The child inherits the calling session's provider, model, thinking level, and working directory. Set `provider`, `model`, `thinking`, or `cwd` only when deliberately choosing something different, for example a faster model for simple investigation or a stronger model for difficult review. Never pass the current provider and model back just to restate them.
19
+
20
+ `prompt` becomes the first user turn. `files` passes file paths as `@`-references, and both are combined when you provide several. Spawn returns the handle and the exact tmux attach command; keep the handle for later calls.
21
+
22
+ ## Tools
23
+
24
+ The child starts with the calling session's default tools: `read`, `bash`, `edit`, and `write`, plus whatever `defaultTools` and installed extensions add. `grep`, `find`, `ls`, and `codemode` are off unless named.
25
+
26
+ `tools` narrows that selection, in one of two forms:
27
+
28
+ - Plain names replace it: `"read,grep,find,ls"` is read-only. Add `bash` only when the child must run commands, since `bash` can also write files.
29
+ - Only `+name`/`-name` entries edit it: `"+codemode,-write"`. Do not mix the forms.
30
+
31
+ Omit `tools` for implementation work. It does not filter MCP tools; use `noExtensions` or `mcp__<server>__*` entries for that.
32
+
33
+ ## Isolation flags
34
+
35
+ - `noExtensions` - Disable normal extension discovery. Use for an independent run that should not inherit unrelated extension behavior or extension-provided tools. The subagent control bridge is still explicitly loaded.
36
+ - `noSkills` - Hide installed skills from the child. Use for tightly specified tasks that should rely only on the supplied prompt and files.
37
+ - `noPromptTemplates` - Disable prompt-template commands. Usually unnecessary, but useful when testing a minimal child environment.
38
+ - `noContextFiles` - Ignore repository instruction files such as `AGENTS.md` and `CLAUDE.md`. Use only when those instructions would bias an independent investigation. Do not use for implementation unless intentionally bypassing repository guidance.
39
+
40
+ Subagents persist after their current turn completes: waiting, completion, and becoming idle do not terminate them. They survive `/reload`. When the spawning Pi session quits or is replaced, they are suspended and relaunched idle with their history when that session is resumed. They are only removed by `stop`.
41
+
42
+ ## Inspect and wait
43
+
44
+ ```json
45
+ { "action": "list" }
46
+ { "action": "status", "handle": "a1b2c3" }
47
+ { "action": "wait", "handle": "a1b2c3" }
48
+ ```
49
+
50
+ Run `list` at any time to rediscover active subagents and their handles, names, and current states if you no longer remember them.
51
+
52
+ `wait` follows the durable session state and returns the latest final assistant response. Do not infer completion from captured terminal text. The default deadline is 1800 seconds; raise it with `timeoutSeconds` for long work.
53
+
54
+ ## Communicate
55
+
56
+ ```json
57
+ { "action": "rename", "handle": "a1b2c3", "name": "new name" }
58
+ { "action": "send", "handle": "a1b2c3", "message": "message" }
59
+ { "action": "send", "handle": "a1b2c3", "message": "message", "followUp": true }
60
+ ```
61
+
62
+ `send` without `followUp` prompts an idle subagent and steers a busy one. With `followUp`, a busy subagent finishes its current turn first. Names are 1–64 characters and need not be unique. Messages use the extension's control inbox; do not use `tmux send-keys`.
63
+
64
+ ## Stop
65
+
66
+ ```json
67
+ { "action": "stop", "handle": "a1b2c3" }
68
+ ```
69
+
70
+ Explicitly stop every subagent when it is no longer needed; do not leave completed subagents idle. This terminates tmux and removes the run transcript and metadata. Keep an idle subagent alive only when concrete follow-up work is expected, then stop it afterward.
71
+
72
+ The interactive `/subagent` command lists active subagents spawned by the current Pi session. Selecting one suspends the current Pi TUI and attaches to its tmux session; detaching returns to the parent Pi. When the parent already runs inside tmux, selection switches the current tmux client instead.
package/subagent.ts ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env -S node --experimental-strip-types
2
+
3
+ import { runSubagentCommand } from "./commands.ts";
4
+
5
+ try {
6
+ const result = await runSubagentCommand(process.argv.slice(2), {
7
+ sessionId: process.env.PI_SESSION_ID,
8
+ sessionFile: process.env.PI_SESSION_FILE,
9
+ provider: process.env.PI_PROVIDER,
10
+ model: process.env.PI_MODEL,
11
+ thinking: process.env.PI_REASONING_LEVEL,
12
+ cwd: process.cwd(),
13
+ });
14
+ process.stdout.write(result.output);
15
+ if (!result.ok) process.exitCode = 1;
16
+ } catch (error) {
17
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
18
+ process.exitCode = 1;
19
+ }