@ferris1225/pi-subagents 4.3.34 → 5.0.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +32 -359
  2. package/README.md +130 -557
  3. package/index.ts +4 -2
  4. package/package.json +1 -1
  5. package/skills/workflow/SKILL.md +46 -29
  6. package/src/configuration/config.ts +4 -4
  7. package/src/configuration/setup.ts +88 -229
  8. package/src/configuration/ui.ts +107 -129
  9. package/src/delegation/builtin-agents.ts +9 -9
  10. package/src/delegation/dispatch.ts +9 -6
  11. package/src/delegation/prompt.ts +7 -8
  12. package/src/execution/cli-run.ts +364 -0
  13. package/src/execution/process-tree.ts +1 -1
  14. package/src/execution/{rpc-control.ts → run-control.ts} +15 -33
  15. package/src/execution/spawn.ts +33 -185
  16. package/src/isolation/temp-hygiene.ts +2 -3
  17. package/src/lifecycle/cancellation.ts +36 -0
  18. package/src/lifecycle/completion.ts +1 -1
  19. package/src/lifecycle/dispatch-core.ts +0 -1
  20. package/src/lifecycle/durable.ts +1 -1
  21. package/src/lifecycle/runtime.ts +42 -29
  22. package/src/lifecycle/stop.ts +175 -0
  23. package/src/lifecycle/thread-lifecycle.ts +11 -14
  24. package/src/lifecycle/thread-restore.ts +3 -3
  25. package/src/lifecycle/tools.ts +18 -173
  26. package/src/presentation/format.ts +2 -5
  27. package/src/presentation/monitor.ts +16 -1
  28. package/src/presentation/widget.ts +140 -175
  29. package/src/workflow/engine.ts +68 -34
  30. package/src/workflow/files.ts +10 -32
  31. package/src/workflow/plan.ts +61 -13
  32. package/src/workflow/state.ts +4 -3
  33. package/src/workflow/tool.ts +23 -12
  34. package/workflows/code-review.md +12 -7
  35. package/workflows/migration.md +14 -26
  36. package/workflows/research.md +6 -5
  37. package/src/execution/rpc-run.ts +0 -889
@@ -0,0 +1,364 @@
1
+ /** Run a one-shot child using Pi's native JSON CLI and session persistence. */
2
+
3
+ import { spawn } from "node:child_process";
4
+ import { existsSync, readdirSync } from "node:fs";
5
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
6
+ import { basename, join } from "node:path";
7
+ import { StringDecoder } from "node:string_decoder";
8
+ import type { Message, Usage } from "@earendil-works/pi-ai";
9
+ import type { JsonAgentSessionEvent } from "@earendil-works/pi-coding-agent";
10
+ import { SUBAGENT_TOOL_NAMES, type AgentConfig } from "../delegation/agents.ts";
11
+ import type { ThinkingLevel } from "../configuration/config.ts";
12
+ import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
13
+ import { terminateProcessTree } from "./process-tree.ts";
14
+ import { asPlainTextPrompt, emptyUsage, type RunControl, type AttemptControl, type RunResult, type SubagentLiveEvent } from "./run-control.ts";
15
+
16
+ const DEPTH_ENV_VAR = "PI_SUBAGENT_DEPTH";
17
+ /** Every tool of an MCP server shares this prefix, whatever its exposure. */
18
+ const MCP_TOOL_PREFIX = "mcp__";
19
+ const SUBAGENT_KILL_GRACE_MS = 5_000;
20
+ const CLI_STARTUP_TIMEOUT_MS = 60_000;
21
+ export const CHILD_STDERR_MAX_CHARS = 32_000;
22
+
23
+
24
+ /** Append child stderr while keeping only the newest bounded tail. */
25
+ export function appendBoundedStderr(current: string, chunk: string, maxChars = CHILD_STDERR_MAX_CHARS): string {
26
+ const next = current + chunk;
27
+ return next.length <= maxChars ? next : next.slice(next.length - maxChars);
28
+ }
29
+
30
+ export function currentSubagentDepth(env: NodeJS.ProcessEnv = process.env): number {
31
+ const raw = env[DEPTH_ENV_VAR];
32
+ const parsed = raw === undefined ? 0 : Number.parseInt(raw, 10);
33
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
34
+ }
35
+
36
+ /** Match pi's `<timestamp>Z_<id>.jsonl` session-file convention. */
37
+ export function sessionExists(sessionDir: string, sessionId: string): boolean {
38
+ try {
39
+ return readdirSync(sessionDir).some((file) => file.endsWith(`_${sessionId}.jsonl`));
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+
45
+ /** Resolve how to invoke the same pi build as the current process. */
46
+ function getPiInvocation(args: string[]): { command: string; args: string[] } {
47
+ const currentScript = process.argv[1];
48
+ const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
49
+ if (currentScript && !isBunVirtualScript && existsSync(currentScript)) {
50
+ return { command: process.execPath, args: [currentScript, ...args] };
51
+ }
52
+ const execName = basename(process.execPath).toLowerCase();
53
+ const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
54
+ if (!isGenericRuntime) return { command: process.execPath, args };
55
+ return { command: "pi", args };
56
+ }
57
+
58
+ function extractToolErrorText(content: unknown): string {
59
+ const parts = Array.isArray(content) ? content : [];
60
+ const text = parts
61
+ .filter(
62
+ (part): part is { type: "text"; text: string } =>
63
+ typeof part === "object" &&
64
+ part !== null &&
65
+ (part as { type?: unknown }).type === "text" &&
66
+ typeof (part as { text?: unknown }).text === "string",
67
+ )
68
+ .map((part) => part.text)
69
+ .join("\n");
70
+ return text
71
+ .split("\n")
72
+ .map((line) => line.trim())
73
+ .filter(Boolean)
74
+ .slice(-3)
75
+ .map((line) => (line.length > 200 ? `${line.slice(0, 200)}…` : line))
76
+ .join("\n");
77
+ }
78
+
79
+ /** Hand the agent body to the child as a file rather than inline argv text.
80
+ * `--append-system-prompt` takes either, but a system prompt is unbounded — a
81
+ * role can carry a whole spec — while Windows caps a command line at
82
+ * 32767 characters, so inlining turns a long agent into an opaque spawn failure.
83
+ * The file lives in the run's scratch dir and is removed when the attempt ends. */
84
+ async function writePromptToTempFile(
85
+ scratchRoot: string,
86
+ agentName: string,
87
+ prompt: string,
88
+ ): Promise<{ dir: string; filePath: string }> {
89
+ await mkdir(scratchRoot, { recursive: true });
90
+ const dir = await mkdtemp(join(scratchRoot, "pi-subagents-"));
91
+ writeTempOwnerMarker(dir);
92
+ const safeName = agentName.replace(/[^\w.-]+/g, "_");
93
+ const filePath = join(dir, `prompt-${safeName}.md`);
94
+ try {
95
+ await writeFile(filePath, prompt, "utf8");
96
+ return { dir, filePath };
97
+ } catch (error) {
98
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
99
+ throw error;
100
+ }
101
+ }
102
+
103
+
104
+ export interface ChildLaunchOptions {
105
+ agent: Pick<AgentConfig, "model" | "tools">;
106
+ thinkingLevel: ThinkingLevel;
107
+ sessionDir?: string;
108
+ sessionId?: string;
109
+ /** The session directory already holds the session being resumed. */
110
+ resumeExistingSession?: boolean;
111
+ /** Appended system prompt file, when the role carries one. */
112
+ promptPath?: string;
113
+ }
114
+
115
+ /** Command line for one child attempt.
116
+ *
117
+ * An explicit role list is a strict intersection of the parent's tools, but pi
118
+ * keeps MCP tools unless a `--tools` entry names one, so a list that names none
119
+ * has to exclude them by pattern. Scout depends on that: its read-only boundary
120
+ * must not leak an MCP writer. */
121
+ export function buildChildLaunchArgs(options: ChildLaunchOptions): string[] {
122
+ const { agent, thinkingLevel } = options;
123
+ const excludedTools: string[] = [...SUBAGENT_TOOL_NAMES];
124
+ const args: string[] = ["--mode", "json"];
125
+ if (options.sessionDir && options.sessionId) {
126
+ args.push("--session-dir", options.sessionDir);
127
+ args.push(options.resumeExistingSession ? "--session" : "--session-id", options.sessionId);
128
+ } else {
129
+ args.push("--no-session");
130
+ }
131
+ if (agent.model) args.push("--model", agent.model);
132
+ args.push("--thinking", thinkingLevel);
133
+ if (agent.tools) {
134
+ if (agent.tools.length > 0) {
135
+ args.push("--tools", agent.tools.join(","));
136
+ if (!agent.tools.some((tool) => tool.startsWith(MCP_TOOL_PREFIX))) excludedTools.push(`${MCP_TOOL_PREFIX}*`);
137
+ } else {
138
+ args.push("--no-tools");
139
+ }
140
+ }
141
+ args.push("--exclude-tools", excludedTools.join(","));
142
+ if (options.promptPath) args.push("--append-system-prompt", options.promptPath);
143
+ return args;
144
+ }
145
+
146
+
147
+ export interface RunCliAttemptOptions {
148
+ defaultCwd: string;
149
+ agent: AgentConfig;
150
+ agentName: string;
151
+ task: string;
152
+ cwd?: string;
153
+ thinkingLevel: ThinkingLevel;
154
+ idleTimeoutMs: number;
155
+ sessionDir?: string;
156
+ sessionId?: string;
157
+ scratchRoot: string;
158
+ prompt: string;
159
+ signal?: AbortSignal;
160
+ onLive?: (event: SubagentLiveEvent) => void;
161
+ env?: NodeJS.ProcessEnv;
162
+ control?: RunControl;
163
+ startupTimeoutMs?: number;
164
+ }
165
+
166
+ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise<RunResult> {
167
+ const { agent, agentName, task, control, signal, onLive } = options;
168
+ const result: RunResult = {
169
+ agent: agentName, task, exitCode: 0, messages: [], stderr: "", usage: emptyUsage(),
170
+ model: agent.model, thinking: options.thinkingLevel,
171
+ sessionId: options.sessionId, sessionDir: options.sessionDir,
172
+ };
173
+ let promptFile: Awaited<ReturnType<typeof writePromptToTempFile>> | undefined;
174
+ try {
175
+ if (signal?.aborted || control?.isStopRequested()) {
176
+ return { ...result, exitCode: 1, stopReason: "aborted", errorMessage: control?.getStopMessage() ?? "Subagent was aborted" };
177
+ }
178
+ if (agent.systemPrompt.trim()) promptFile = await writePromptToTempFile(options.scratchRoot, agent.name, agent.systemPrompt);
179
+ const args = buildChildLaunchArgs({
180
+ agent, thinkingLevel: options.thinkingLevel,
181
+ sessionDir: options.sessionDir, sessionId: options.sessionId,
182
+ resumeExistingSession: Boolean(options.sessionDir && options.sessionId && sessionExists(options.sessionDir, options.sessionId)),
183
+ promptPath: promptFile?.filePath,
184
+ });
185
+ const invocation = getPiInvocation(args);
186
+ const processGroup = process.platform !== "win32";
187
+ const proc = spawn(invocation.command, invocation.args, {
188
+ cwd: options.cwd ?? options.defaultCwd, shell: false, stdio: ["pipe", "pipe", "pipe"],
189
+ env: { ...(options.env ?? process.env), [DEPTH_ENV_VAR]: String(currentSubagentDepth(options.env) + 1) },
190
+ detached: processGroup,
191
+ });
192
+ const token = control?.beginAttempt();
193
+ let closed = false;
194
+ let settled = false;
195
+ let stopping = false;
196
+ let lastActivityAt = Date.now();
197
+ let forceKillTimer: ReturnType<typeof setTimeout> | undefined;
198
+ let shutdownTimer: ReturnType<typeof setTimeout> | undefined;
199
+ let idleTimer: ReturnType<typeof setInterval> | undefined;
200
+ let startupTimer: ReturnType<typeof setTimeout> | undefined;
201
+ let resolveClosed!: () => void;
202
+ const processClosed = new Promise<void>((resolve) => { resolveClosed = resolve; });
203
+ const emit = (event: SubagentLiveEvent): void => {
204
+ try { onLive?.(event); } catch { /* Observers do not own the child lifecycle. */ }
205
+ };
206
+ const terminate = (): void => {
207
+ if (closed || forceKillTimer) return;
208
+ terminateProcessTree(proc, false, processGroup);
209
+ forceKillTimer = setTimeout(() => {
210
+ if (!closed) terminateProcessTree(proc, true, processGroup);
211
+ }, SUBAGENT_KILL_GRACE_MS);
212
+ };
213
+ const attempt: AttemptControl = {
214
+ async stop(reason = "Subagent was aborted") {
215
+ if (!closed) {
216
+ stopping = true;
217
+ result.exitCode = 1;
218
+ result.stopReason = "aborted";
219
+ result.errorMessage = reason;
220
+ if (token !== undefined) control?.updateAttemptPhase(token, "interrupting");
221
+ emit({ kind: "status", status: "interrupting" });
222
+ terminate();
223
+ }
224
+ await processClosed;
225
+ },
226
+ };
227
+ if (token !== undefined) control?.attach(token, attempt);
228
+ if (proc.pid !== undefined) control?.noteChildPid(proc.pid);
229
+ control?.markStarting();
230
+ const addUsage = (usage: Partial<Usage> | undefined): void => {
231
+ if (!usage) return;
232
+ result.usage.input += usage.input ?? 0;
233
+ result.usage.output += usage.output ?? 0;
234
+ result.usage.cacheRead += usage.cacheRead ?? 0;
235
+ result.usage.cacheWrite += usage.cacheWrite ?? 0;
236
+ result.usage.cost += usage.cost?.total ?? 0;
237
+ result.usage.contextTokens = usage.totalTokens ?? result.usage.contextTokens;
238
+ };
239
+ const processLine = (line: string): void => {
240
+ let event: JsonAgentSessionEvent;
241
+ try { event = JSON.parse(line); } catch { return; }
242
+ if (!event || typeof event !== "object") return;
243
+ if (event.type === "agent_start" || event.type === "turn_start") {
244
+ result.activityObserved = true;
245
+ if (startupTimer) clearTimeout(startupTimer);
246
+ if (!stopping) {
247
+ if (token !== undefined) control?.updateAttemptPhase(token, "running");
248
+ emit({ kind: "status", status: "running" });
249
+ }
250
+ } else if (event.type === "message_update") {
251
+ const type = event.assistantMessageEvent?.type;
252
+ if (type === "thinking_delta" || type === "text_delta") emit({ kind: type === "thinking_delta" ? "thinking" : "text" });
253
+ } else if (event.type === "tool_execution_start") {
254
+ result.activityObserved = true;
255
+ emit({ kind: "tool_start", toolCallId: event.toolCallId, toolName: event.toolName, args: event.args });
256
+ } else if (event.type === "tool_execution_end") {
257
+ emit({ kind: "tool_end", toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError });
258
+ if (event.isError) (result.failedTools ??= []).push({ toolName: event.toolName, error: extractToolErrorText(event.result?.content) });
259
+ } else if (event.type === "message_end" && event.message) {
260
+ result.activityObserved = true;
261
+ const message = event.message;
262
+ if (message.role === "assistant" || message.role === "user" || message.role === "toolResult") result.messages.push(message as Message);
263
+ if (message.role === "assistant") {
264
+ result.usage.turns++;
265
+ addUsage(message.usage);
266
+ if (message.provider && message.model) result.model = message.provider + "/" + message.model;
267
+ if (!stopping) {
268
+ result.stopReason = message.stopReason;
269
+ result.errorMessage = message.errorMessage;
270
+ }
271
+ } else if (message.role === "toolResult") addUsage(message.usage);
272
+ emit({ kind: "usage", usage: { ...result.usage }, model: result.model });
273
+ } else if (event.type === "compaction_end") {
274
+ addUsage(event.result?.usage);
275
+ emit({ kind: "usage", usage: { ...result.usage }, model: result.model });
276
+ } else if (event.type === "agent_settled") {
277
+ settled = true;
278
+ if (startupTimer) clearTimeout(startupTimer);
279
+ if (event.aborted && !stopping) {
280
+ result.stopReason = "aborted";
281
+ result.errorMessage ??= "Subagent was aborted";
282
+ }
283
+ // Pi normally exits itself. Bound a child extension's stuck disposal.
284
+ if (!closed) shutdownTimer ??= setTimeout(terminate, SUBAGENT_KILL_GRACE_MS);
285
+ }
286
+ };
287
+ const stdoutDecoder = new StringDecoder("utf8");
288
+ const stderrDecoder = new StringDecoder("utf8");
289
+ let stdoutBuffer = "";
290
+ proc.stdout.on("data", (chunk: Buffer) => {
291
+ lastActivityAt = Date.now();
292
+ stdoutBuffer += stdoutDecoder.write(chunk);
293
+ let start = 0;
294
+ for (let lf = stdoutBuffer.indexOf("\n"); lf !== -1; lf = stdoutBuffer.indexOf("\n", start)) {
295
+ processLine(stdoutBuffer.slice(start, lf));
296
+ start = lf + 1;
297
+ }
298
+ if (start) stdoutBuffer = stdoutBuffer.slice(start);
299
+ });
300
+ proc.stderr.on("data", (chunk: Buffer) => { result.stderr = appendBoundedStderr(result.stderr, stderrDecoder.write(chunk)); });
301
+ proc.stdin.on("error", (error) => {
302
+ if (stopping || closed) return;
303
+ result.dispatchFailed = true;
304
+ result.errorMessage ??= "Subagent stdin failed: " + error.message;
305
+ terminate();
306
+ });
307
+ proc.once("error", (error) => {
308
+ result.dispatchFailed = true;
309
+ result.errorMessage ??= "Failed to start the sub-agent process: " + error.message;
310
+ });
311
+ proc.once("close", (code, exitSignal) => {
312
+ closed = true;
313
+ if (startupTimer) clearTimeout(startupTimer);
314
+ if (idleTimer) clearInterval(idleTimer);
315
+ if (forceKillTimer) clearTimeout(forceKillTimer);
316
+ if (shutdownTimer) clearTimeout(shutdownTimer);
317
+ signal?.removeEventListener("abort", onAbort);
318
+ stdoutBuffer += stdoutDecoder.end();
319
+ result.stderr = appendBoundedStderr(result.stderr, stderrDecoder.end());
320
+ if (stdoutBuffer.trim()) processLine(stdoutBuffer);
321
+ // A settlement event does not excuse an abnormal process exit.
322
+ if (!stopping && (!settled || code !== 0)) {
323
+ const detail = exitSignal ? "signal=" + exitSignal : "code=" + code;
324
+ const error = "Subagent JSON process exited " + (settled ? "after settlement" : "before settling") + " (" + detail + ").";
325
+ result.errorMessage = [result.errorMessage, error, result.stderr.trim()].filter(Boolean).join("\n");
326
+ result.stopReason = "error";
327
+ if (!result.errorMessage.startsWith("Subagent idle timeout")) result.dispatchFailed = true;
328
+ }
329
+ if (!stopping && result.stopReason === "length") result.errorMessage = "Subagent answer was truncated at the model output limit.";
330
+ if (!stopping && settled && !result.messages.some((message) => message.role === "assistant")) {
331
+ result.stopReason = "error";
332
+ result.errorMessage ??= "Subagent settled without an assistant answer.";
333
+ result.dispatchFailed = true;
334
+ }
335
+ result.exitCode = result.dispatchFailed || result.stopReason === "error" || result.stopReason === "aborted" || result.stopReason === "length" ? 1 : 0;
336
+ resolveClosed();
337
+ });
338
+ const onAbort = (): void => { void attempt.stop("Subagent was aborted"); };
339
+ startupTimer = setTimeout(() => {
340
+ result.dispatchFailed = true;
341
+ result.errorMessage = "Subagent startup timeout before agent activity.";
342
+ terminate();
343
+ }, options.startupTimeoutMs ?? CLI_STARTUP_TIMEOUT_MS);
344
+ if (options.idleTimeoutMs > 0) {
345
+ idleTimer = setInterval(() => {
346
+ if (settled || stopping || closed || Date.now() - lastActivityAt < options.idleTimeoutMs) return;
347
+ result.errorMessage = "Subagent idle timeout: no activity for " + Math.ceil(options.idleTimeoutMs / 1000) + " seconds.";
348
+ result.stopReason = "error";
349
+ terminate();
350
+ }, Math.max(1, Math.min(10_000, Math.floor(options.idleTimeoutMs / 3))));
351
+ }
352
+ signal?.addEventListener("abort", onAbort, { once: true });
353
+ try {
354
+ if (signal?.aborted || control?.isStopRequested()) await attempt.stop(control?.getStopMessage());
355
+ else proc.stdin.end(asPlainTextPrompt(options.prompt));
356
+ await processClosed;
357
+ return result;
358
+ } finally {
359
+ if (token !== undefined) control?.detach(token);
360
+ }
361
+ } finally {
362
+ if (promptFile) await rm(promptFile.dir, { recursive: true, force: true }).catch(() => undefined);
363
+ }
364
+ }
@@ -1,4 +1,4 @@
1
- /** Process-tree termination shared by RPC children and Git commands. */
1
+ /** Process-tree termination shared by Pi children and Git commands. */
2
2
 
3
3
  import { spawn, type ChildProcess } from "node:child_process";
4
4
 
@@ -1,4 +1,4 @@
1
- /** Shared RPC result types and stable logical-run control. */
1
+ /** Shared one-shot result types and stable logical-run control. */
2
2
 
3
3
  import type { Message } from "@earendil-works/pi-ai";
4
4
  import type { ThinkingLevel } from "../configuration/config.ts";
@@ -14,7 +14,7 @@ export interface UsageStats {
14
14
  turns: number;
15
15
  }
16
16
 
17
- export interface RpcSingleResult {
17
+ export interface RunResult {
18
18
  agent: string;
19
19
  task: string;
20
20
  exitCode: number;
@@ -28,21 +28,8 @@ export interface RpcSingleResult {
28
28
  /** Selected model when this result handed off to the current main model. */
29
29
  modelFallbackFrom?: string;
30
30
  dispatchFailed?: boolean;
31
- /** An accepted generation failed because an RPC prompt was rejected before
32
- * model execution. This remains main-model handoff eligible even when an
33
- * earlier, aborted objective left assistant text in the session. */
34
- rpcPromptRejected?: boolean;
35
- /** Startup handshake failed before the initial prompt was dispatched. This
36
- * transport miss is safe to retry and is not a model/provider failure. */
37
- rpcStartupFailed?: boolean;
38
- /** The parent dispatched the initial prompt command. Until its response is
39
- * observed, Pi may already be running it, so startup retries must not replay it. */
40
- rpcPromptDispatched?: boolean;
41
- /** The child confirmed prompt acceptance (or emitted agent activity). */
42
- rpcPromptAccepted?: boolean;
43
- /** Pi emitted agent/turn/model/tool activity for this attempt. */
44
- rpcActivity?: boolean;
45
- startupRetries?: number;
31
+ /** Pi emitted agent, message, or tool activity for this attempt. */
32
+ activityObserved?: boolean;
46
33
  failedTools?: Array<{ toolName: string; error: string }>;
47
34
  sessionId?: string;
48
35
  sessionDir?: string;
@@ -73,12 +60,11 @@ export type SubagentLiveEvent =
73
60
  | { kind: "thinking" }
74
61
  | { kind: "text" };
75
62
 
76
- export type RpcControlPhase =
63
+ export type RunControlPhase =
77
64
  | "queued"
78
65
  | "starting"
79
66
  | "running"
80
67
  | "interrupting"
81
- | "retrying"
82
68
  | "settled"
83
69
  | "stopped";
84
70
 
@@ -86,8 +72,8 @@ export interface AttemptControl {
86
72
  stop(reason?: string): Promise<void>;
87
73
  }
88
74
 
89
- /** Prevent RPC prompt expansion when a message starts with a slash command. */
90
- export function asPlainTextRpcPrompt(message: string): string {
75
+ /** Prevent CLI prompt expansion when a message starts with a slash command. */
76
+ export function asPlainTextPrompt(message: string): string {
91
77
  if (!message.trimStart().startsWith("/")) return message;
92
78
  return `Treat the following as plain-text sub-agent instructions, not a Pi command:\n\n${message}`;
93
79
  }
@@ -95,11 +81,11 @@ export function asPlainTextRpcPrompt(message: string): string {
95
81
  /**
96
82
  * Stable control surface for a logical run generation. Startup/main-handoff attempts
97
83
  * attach and detach beneath it, so callers never retain a stale child handle.
98
- * Control calls are serialized to prevent overlapping abort/settle/prompt flows.
84
+ * Control calls are serialized to prevent overlapping stop and settlement flows.
99
85
  */
100
- export class RpcRunControl {
86
+ export class RunControl {
101
87
  private objective: string;
102
- private phase: RpcControlPhase = "queued";
88
+ private phase: RunControlPhase = "queued";
103
89
  private attempt?: { token: number; control: AttemptControl };
104
90
  private nextToken = 1;
105
91
  private serial: Promise<void> = Promise.resolve();
@@ -107,12 +93,12 @@ export class RpcRunControl {
107
93
  private stopMessage = "Subagent was aborted";
108
94
  private childPids = new Set<number>();
109
95
  readonly generation: number;
110
- private readonly onPhase?: (phase: RpcControlPhase) => void;
96
+ private readonly onPhase?: (phase: RunControlPhase) => void;
111
97
 
112
98
  constructor(
113
99
  objective: string,
114
100
  generation: number,
115
- onPhase?: (phase: RpcControlPhase) => void,
101
+ onPhase?: (phase: RunControlPhase) => void,
116
102
  ) {
117
103
  this.objective = objective;
118
104
  this.generation = generation;
@@ -123,7 +109,7 @@ export class RpcRunControl {
123
109
  return this.objective;
124
110
  }
125
111
 
126
- getPhase(): RpcControlPhase {
112
+ getPhase(): RunControlPhase {
127
113
  return this.phase;
128
114
  }
129
115
 
@@ -150,10 +136,6 @@ export class RpcRunControl {
150
136
  this.setPhase("starting");
151
137
  }
152
138
 
153
- markRetrying(): void {
154
- if (!this.stopRequested) this.setPhase("retrying");
155
- }
156
-
157
139
  markSettled(): void {
158
140
  this.attempt = undefined;
159
141
  if (!this.stopRequested) this.setPhase("settled");
@@ -172,7 +154,7 @@ export class RpcRunControl {
172
154
  if (this.attempt?.token === token) this.attempt = undefined;
173
155
  }
174
156
 
175
- updateAttemptPhase(token: number, phase: RpcControlPhase): void {
157
+ updateAttemptPhase(token: number, phase: RunControlPhase): void {
176
158
  if (this.attempt?.token !== token) return;
177
159
  this.setPhase(phase);
178
160
  }
@@ -192,7 +174,7 @@ export class RpcRunControl {
192
174
  });
193
175
  }
194
176
 
195
- private setPhase(phase: RpcControlPhase): void {
177
+ private setPhase(phase: RunControlPhase): void {
196
178
  if (this.phase === phase) return;
197
179
  this.phase = phase;
198
180
  try {