@restranger/repi-subagents 0.0.0-stage → 0.0.1-562ada7

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/src/prompt.ts ADDED
@@ -0,0 +1,184 @@
1
+ import { formatTokens, runDuration, sanitize, truncate } from "./format.js";
2
+ import { describeToolSpec } from "./tool-policy.js";
3
+ import type { AgentDefinition, SubagentRunSnapshot } from "./types.js";
4
+
5
+ /**
6
+ * Prompt sections injected through `before_agent_start`.
7
+ *
8
+ * Section names are what Pi wraps the body in (`<name>…</name>`) and diffs across turns, so they are
9
+ * stable and lowercase; only the bodies change. Keeping the catalog in the prompt (instead of only
10
+ * in the tool description) is what stops the model from calling `subagent_list` every time it is
11
+ * asked to delegate: the list it sees is complete, and the section says so.
12
+ */
13
+ export const AGENT_SECTION = "repi_subagents";
14
+ export const ACTIVE_RUNS_SECTION = "repi_subagent_runs";
15
+
16
+ /**
17
+ * Behavioural rules shipped as the `subagent` tool's `promptGuidelines`.
18
+ *
19
+ * The catalog below answers *who* is available; these answer *when* and *how* to delegate, which
20
+ * is what makes the model reach for the tool instead of grinding through an inline read/grep loop.
21
+ * They are rendered by Pi in the ordinary `<rules>` block next to the built-in tool rules, and they
22
+ * disappear with the tool, so a session that disables `subagent` is not told to use it.
23
+ *
24
+ * Each line mirrors one failure mode seen in practice: no rules at all (the model never delegates),
25
+ * delegating single-file lookups, serializing independent questions, terse briefs that produce
26
+ * generic work, and "based on your findings, fix it" follow-ups that push synthesis onto the child.
27
+ */
28
+ export const SUBAGENT_GUIDELINES: readonly string[] = [
29
+ "Use subagent for broad multi-file exploration, open-ended research, planning, and multi-step work that would flood this context with raw output.",
30
+ "Keep single-file reads and one-off lookups inline; do not delegate work you can finish in a step or two.",
31
+ "Fan out: launch one subagent per independent question in the same turn instead of serializing them.",
32
+ "Write self-contained briefs — the child sees neither this conversation nor AGENTS.md — with the goal, exact paths, build and test commands, already ruled-out options, and the report format you expect.",
33
+ "Never delegate understanding: read the child report and write the concrete spec yourself before any follow-up work.",
34
+ "Collect before reporting: call subagent_wait for the background runs whose result you depend on, including `verification`.",
35
+ ];
36
+
37
+ const MAX_PROMPT_AGENTS = 24;
38
+ const MAX_PROMPT_RUNS = 10;
39
+ /** Finished-but-uncollected runs are capped harder: they are a nudge, not a backlog view. */
40
+ const MAX_FINISHED_PROMPT_RUNS = 3;
41
+ const MAX_DESCRIPTION_CHARS = 240;
42
+
43
+ /** A run is either in flight or finished and still waiting for the parent to read its result. */
44
+ function isActiveRun(run: SubagentRunSnapshot): boolean {
45
+ return run.status === "running" || run.status === "queued";
46
+ }
47
+
48
+ function isUncollectedRun(run: SubagentRunSnapshot): boolean {
49
+ return !isActiveRun(run) && run.finishedAt !== undefined && run.collected !== true;
50
+ }
51
+
52
+ /**
53
+ * Format run duration rounded to whole seconds (e.g. `4s` or `2m15s`).
54
+ * Does not include sub-second precision so that prompt sections remain stable
55
+ * across rapid agent starts and turns without busting the LLM prompt cache.
56
+ */
57
+ export function formatPromptDuration(ms: number): string {
58
+ const rounded = Math.max(0, Math.round(ms / 1000));
59
+ if (rounded < 60) {
60
+ return `${rounded}s`;
61
+ }
62
+ const minutes = Math.floor(rounded / 60);
63
+ const rest = rounded % 60;
64
+ return `${minutes}m${rest.toString().padStart(2, "0")}s`;
65
+ }
66
+
67
+ /**
68
+ * One sanitized, width-aware line: a multi-line or coloured description must not break the section
69
+ * layout or smuggle terminal escapes into the prompt.
70
+ */
71
+ function oneLine(value: string, max: number): string {
72
+ return truncate(sanitize(value).replace(/\s+/gu, " ").trim(), max);
73
+ }
74
+
75
+ /**
76
+ * Shorten a description without dropping the instruction that usually sits at its end.
77
+ *
78
+ * Agent authors (and the ported defaults) spell out *how* to call the agent in the last sentence —
79
+ * "specify the thoroughness level", "pass the original task and files changed". Cutting at an
80
+ * arbitrary character throws exactly that away, so prefer the last sentence boundary that still
81
+ * fits and only fall back to the hard truncate when there is none.
82
+ */
83
+ function clampDescription(value: string, max: number): string {
84
+ const text = sanitize(value).replace(/\s+/gu, " ").trim();
85
+ if (text.length <= max) {
86
+ return text;
87
+ }
88
+ const cut = text.slice(0, max);
89
+ const boundary = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("; "), cut.lastIndexOf(" — "));
90
+ if (boundary >= Math.floor(max * 0.55)) {
91
+ return cut.slice(0, boundary + 1);
92
+ }
93
+ return truncate(text, max);
94
+ }
95
+
96
+ /**
97
+ * Catalog of declared agents for the system prompt.
98
+ *
99
+ * Returns `undefined` when nothing is declared, so the section disappears (Pi patches the prompt
100
+ * delta) instead of leaving an empty block behind.
101
+ */
102
+ export function formatAgentPromptSection(agents: readonly AgentDefinition[]): string | undefined {
103
+ if (agents.length === 0) {
104
+ return undefined;
105
+ }
106
+ const visible = agents.slice(0, MAX_PROMPT_AGENTS);
107
+ const hidden = agents.length - visible.length;
108
+ const lines = [
109
+ hidden > 0
110
+ ? "Declared subagents you can launch with the `subagent` tool. The catalog below is truncated:"
111
+ : "Declared subagents you can launch with the `subagent` tool. This catalog is complete for the current workspace:",
112
+ ...visible.map(
113
+ (agent) =>
114
+ `- ${oneLine(agent.name, 80)} — ${clampDescription(agent.description, MAX_DESCRIPTION_CHARS)} (${describeToolSpec(agent)})`,
115
+ ),
116
+ ];
117
+ if (hidden > 0) {
118
+ lines.push(`- … and ${hidden} more (use \`subagent_list\` to see them)`);
119
+ }
120
+ // The closing instruction has to match the catalog above: telling the model not to call
121
+ // `subagent_list` while also admitting the list is truncated leaves the hidden agents
122
+ // unreachable. `subagent_status` is mentioned only to scope it to runs, not agents.
123
+ lines.push(
124
+ hidden > 0
125
+ ? `The catalog above is truncated, so \`subagent_list\` is the way to see the ${hidden} remaining agent${hidden === 1 ? "" : "s"}. Launch work with subagent; use background: true (or async: true) for work you do not want to wait for.`
126
+ : "Do not call subagent_list to discover agents — the list above is authoritative. subagent_status only inspects runs, not agents. Launch work with subagent; use background: true (or async: true) for work you do not want to wait for.",
127
+ );
128
+ return lines.join("\n");
129
+ }
130
+
131
+ /**
132
+ * Runs the parent still owes attention to: in flight, plus finished runs whose result has not
133
+ * been collected yet.
134
+ *
135
+ * Without the second group a background `verification` run that finishes between turns vanishes
136
+ * from the prompt before the model can read its verdict, and the model reports completion without
137
+ * ever seeing PASS/FAIL. Finished runs drop out as soon as the parent calls `subagent_wait` (or
138
+ * inspects the run), so the reminder is self-clearing instead of permanent.
139
+ */
140
+ export function formatActiveRunsPromptSection(runs: readonly SubagentRunSnapshot[], now: number): string | undefined {
141
+ const active = runs.filter(isActiveRun);
142
+ const uncollected = runs.filter(isUncollectedRun).slice(-MAX_FINISHED_PROMPT_RUNS);
143
+ const visible = [...active, ...uncollected].slice(0, MAX_PROMPT_RUNS);
144
+ if (visible.length === 0) {
145
+ return undefined;
146
+ }
147
+ const lines = visible.map((run) => {
148
+ const running = isActiveRun(run);
149
+ const parts = [
150
+ run.id,
151
+ oneLine(run.agent, 80),
152
+ run.status,
153
+ `background: ${run.background ? "yes" : "no"}`,
154
+ formatPromptDuration(runDuration(run, now)),
155
+ ];
156
+ if (running) {
157
+ if (run.maxTurns !== undefined) {
158
+ parts.push(`turn ${run.turns}/${run.maxTurns}`);
159
+ }
160
+ const tokens = run.usage?.total ?? ((run.usage?.input ?? 0) + (run.usage?.output ?? 0) || undefined);
161
+ if (tokens !== undefined && tokens > 0) {
162
+ parts.push(`${formatTokens(tokens)} tok`);
163
+ }
164
+ }
165
+ if (run.description) {
166
+ parts.push(oneLine(run.description, 80));
167
+ }
168
+ return `- ${parts.join(" · ")}${running ? "" : " (finished, result not collected)"}`;
169
+ });
170
+ const total = active.length + uncollected.length;
171
+ if (total > visible.length) {
172
+ lines.push(`- … and ${total - visible.length} more runs`);
173
+ }
174
+ const closing = ["Do not start a duplicate run for work listed above."];
175
+ if (uncollected.length > 0) {
176
+ closing.push(
177
+ "Finished runs above were not collected: call subagent_wait with their ids before relying on their results.",
178
+ );
179
+ } else {
180
+ closing.push("Inspect a run with subagent_status or collect it with subagent_wait.");
181
+ }
182
+ lines.push(closing.join(" "));
183
+ return lines.join("\n");
184
+ }
@@ -0,0 +1,71 @@
1
+ import { type DiscoverAgentsOptions, discoverAgents } from "./discovery.js";
2
+ import type { AgentDefinition, AgentDiagnostic, AgentScanResult } from "./types.js";
3
+
4
+ /**
5
+ * Per-session view of the declarative agent files.
6
+ *
7
+ * The registry is deliberately small: discovery owns filesystem I/O, the registry owns lookup and
8
+ * reload semantics, and the tool/manager never touch disk directly.
9
+ */
10
+ export class AgentRegistry {
11
+ private scan: AgentScanResult;
12
+ private readonly options: DiscoverAgentsOptions;
13
+
14
+ constructor(options: DiscoverAgentsOptions) {
15
+ this.options = options;
16
+ this.scan = discoverAgents(options);
17
+ }
18
+
19
+ reload(overrides?: Partial<DiscoverAgentsOptions>): AgentScanResult {
20
+ this.scan = discoverAgents({ ...this.options, ...overrides });
21
+ return this.scan;
22
+ }
23
+
24
+ list(): readonly AgentDefinition[] {
25
+ return this.scan.agents;
26
+ }
27
+
28
+ get(name: string): AgentDefinition | undefined {
29
+ const key = name.trim().toLowerCase();
30
+ return this.scan.agents.find((agent) => agent.name.toLowerCase() === key);
31
+ }
32
+
33
+ /**
34
+ * Replace an agent's fallback models in memory (used by `re:subagents@1`).
35
+ *
36
+ * Returns false for an unknown name so a caller can report it instead of silently writing an
37
+ * override that discovery will ignore on the next scan.
38
+ */
39
+ setFallbackModels(name: string, fallbackModels: readonly string[]): boolean {
40
+ const key = name.trim().toLowerCase();
41
+ const index = this.scan.agents.findIndex((agent) => agent.name.toLowerCase() === key);
42
+ if (index === -1) {
43
+ return false;
44
+ }
45
+ const agents = this.scan.agents.map((agent, current) =>
46
+ current === index ? { ...agent, fallbackModels: [...fallbackModels] } : agent,
47
+ );
48
+ this.scan = { ...this.scan, agents };
49
+ return true;
50
+ }
51
+
52
+ diagnostics(): readonly AgentDiagnostic[] {
53
+ return this.scan.diagnostics;
54
+ }
55
+
56
+ directories(): readonly string[] {
57
+ return this.scan.directories;
58
+ }
59
+
60
+ configFiles(): readonly string[] {
61
+ return this.scan.configFiles ?? [];
62
+ }
63
+
64
+ maxConcurrent(): number | undefined {
65
+ return this.scan.maxConcurrent;
66
+ }
67
+
68
+ snapshot(): AgentScanResult {
69
+ return this.scan;
70
+ }
71
+ }
package/src/session.ts ADDED
@@ -0,0 +1,304 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import type { PermissionService } from "@restranger/repi-lib";
5
+ import { type SubagentConfirmationRequest, createSubagentGuardExtension } from "./child-guard.js";
6
+ import type { ChildBuiltinExtension } from "./extensions.js";
7
+ import type { AgentDefinition } from "./types.js";
8
+
9
+ export interface ChildSession {
10
+ readonly sessionId?: string;
11
+ prompt(text: string): Promise<void>;
12
+ abort(): Promise<void> | void;
13
+ dispose(): void;
14
+ subscribe(handler: (event: unknown) => void): () => void;
15
+ steer?(text: string): Promise<unknown>;
16
+ getLastAssistantText?(): string | undefined;
17
+ getAllTools?(): readonly { readonly name: string }[];
18
+ readonly messages?: readonly unknown[];
19
+ }
20
+
21
+ export interface CreateChildSessionOptions {
22
+ readonly runId: string;
23
+ readonly agent: AgentDefinition;
24
+ readonly cwd: string;
25
+ readonly parentSessionId: string;
26
+ readonly permission?: PermissionService;
27
+ /** Parent-side approval for permission decisions that need a human. */
28
+ readonly requestConfirmation?: (request: SubagentConfirmationRequest) => Promise<boolean>;
29
+ /** Resolved allowlist; `undefined` means every tool the child session exposes. */
30
+ readonly tools?: readonly string[];
31
+ readonly excludeTools: readonly string[];
32
+ /** Extension module files that provide the child's requested tools. */
33
+ readonly extensionPaths?: readonly string[];
34
+ /** Host built-ins the child re-creates through SDK factories. */
35
+ readonly builtinExtensions?: readonly ChildBuiltinExtension[];
36
+ /**
37
+ * Parent ModelRuntime. Sharing it keeps extension-registered providers, OAuth credentials
38
+ * and request hooks usable in the child; a fresh runtime only knows built-in providers.
39
+ */
40
+ readonly modelRuntime?: unknown;
41
+ readonly model?: unknown;
42
+ readonly thinking?: string;
43
+ readonly signal?: AbortSignal;
44
+ readonly onDiagnostic?: (message: string) => void;
45
+ }
46
+
47
+ export interface ChildSessionFactory {
48
+ create(options: CreateChildSessionOptions): Promise<ChildSession>;
49
+ }
50
+
51
+ interface HostAgentSession {
52
+ readonly sessionId?: string;
53
+ readonly messages?: readonly unknown[];
54
+ prompt(text: string): Promise<void>;
55
+ abort(): Promise<void>;
56
+ dispose(): void;
57
+ subscribe(handler: (event: unknown) => void): () => void;
58
+ steer?(text: string): Promise<unknown>;
59
+ getLastAssistantText?(): string | undefined;
60
+ getAllTools?(): readonly { readonly name: string }[];
61
+ bindExtensions?(bindings: Record<string, unknown>): Promise<void>;
62
+ }
63
+
64
+ interface HostSdk {
65
+ DefaultResourceLoader: new (
66
+ options: Record<string, unknown>,
67
+ ) => {
68
+ reload(): Promise<void>;
69
+ getExtensions?(): {
70
+ errors?: readonly unknown[];
71
+ };
72
+ };
73
+ SessionManager: {
74
+ inMemory(cwd?: string): unknown;
75
+ };
76
+ createAgentSession(options: Record<string, unknown>): Promise<{
77
+ session: HostAgentSession;
78
+ modelFallbackMessage?: string;
79
+ }>;
80
+ createCodemodeExtension?: (options?: Record<string, unknown>) => unknown;
81
+ createToolSearchExtension?: () => unknown;
82
+ createMcpExtension?: (options?: Record<string, unknown>) => unknown;
83
+ }
84
+
85
+ const HOST_PACKAGE = "@earendil-works/pi-coding-agent";
86
+ let hostSdk: Promise<HostSdk> | undefined;
87
+
88
+ async function loadHostSdk(): Promise<HostSdk> {
89
+ hostSdk ??= import(HOST_PACKAGE) as Promise<HostSdk>;
90
+ return hostSdk;
91
+ }
92
+
93
+ /** Test hook to inject a mock HostSdk without needing the actual peer dependency. */
94
+ export function _setHostSdkForTest(sdk: HostSdk | undefined): void {
95
+ hostSdk = sdk ? Promise.resolve(sdk) : undefined;
96
+ }
97
+
98
+ /**
99
+ * Create a child Pi session in-process.
100
+ *
101
+ * The child is deliberately assembled from a *scoped* resource loader. Ambient
102
+ * package/user/project extensions stay disabled (`noExtensions: true`), but the loader receives
103
+ * exactly the extension modules that registered the tools the agent asked for
104
+ * (`additionalExtensionPaths`) plus recreated host built-ins. This forwards the useful plugin
105
+ * surface without starting a second copy of every unrelated ambient extension in the parent
106
+ * process, and without loading `@restranger/repi-subagents` recursively.
107
+ *
108
+ * The temporary `agentDir` keeps global *settings* discovery out of the child, while the loader
109
+ * `cwd` stays the real project directory so the system prompt's `<cwd>` matches tool execution.
110
+ * `noContextFiles`/`noSkills`/... still keep project skills, prompts, themes and AGENTS.md out of
111
+ * the prompt; the child never inherits the parent's conversation.
112
+ *
113
+ * This is resource scoping, not a security sandbox: the child runs in the parent process, so it
114
+ * shares the process environment (API keys included) and provider credentials. A child that needs
115
+ * a narrower surface must be restricted through `tools`/`excludeTools` and the permission engine,
116
+ * which is what `subagent-guard` does.
117
+ */
118
+ export function createChildSessionFactory(): ChildSessionFactory {
119
+ return {
120
+ async create(options) {
121
+ if (options.signal?.aborted) {
122
+ throw abortError();
123
+ }
124
+ const sdk = await loadHostSdk();
125
+ const tempAgentDir = mkdtempSync(join(tmpdir(), "repi-subagents-"));
126
+ try {
127
+ const systemPrompt = options.agent.systemPrompt.trim();
128
+ const extensionFactories: unknown[] = [
129
+ createSubagentGuardExtension({
130
+ allowedTools: options.tools,
131
+ permission: options.permission,
132
+ ...(options.requestConfirmation ? { requestConfirmation: options.requestConfirmation } : {}),
133
+ parentSessionId: options.parentSessionId,
134
+ cwd: options.cwd,
135
+ ...(options.signal ? { signal: options.signal } : {}),
136
+ }),
137
+ ];
138
+ for (const builtin of options.builtinExtensions ?? []) {
139
+ const factory = createBuiltinExtension(sdk, builtin);
140
+ if (factory) {
141
+ extensionFactories.push(factory);
142
+ } else {
143
+ options.onDiagnostic?.(
144
+ `Host does not export the ${builtin} built-in extension; child tool may be unavailable.`,
145
+ );
146
+ }
147
+ }
148
+ const loaderOptions: Record<string, unknown> = {
149
+ cwd: options.cwd,
150
+ agentDir: tempAgentDir,
151
+ noExtensions: true,
152
+ noSkills: true,
153
+ noPromptTemplates: true,
154
+ noThemes: true,
155
+ noContextFiles: true,
156
+ ...(options.extensionPaths && options.extensionPaths.length > 0
157
+ ? { additionalExtensionPaths: [...options.extensionPaths] }
158
+ : {}),
159
+ extensionFactories,
160
+ };
161
+ if (options.agent.promptMode === "replace") {
162
+ loaderOptions.systemPromptOverride = () => systemPrompt;
163
+ loaderOptions.appendSystemPromptOverride = () => [];
164
+ } else if (systemPrompt.length > 0) {
165
+ loaderOptions.appendSystemPromptOverride = (base: string[]) => [...base, systemPrompt];
166
+ }
167
+
168
+ const loader = new sdk.DefaultResourceLoader(loaderOptions);
169
+ await loader.reload();
170
+
171
+ const extensionErrors = loader.getExtensions?.()?.errors;
172
+ if (Array.isArray(extensionErrors)) {
173
+ for (const err of extensionErrors) {
174
+ const errObj = err as { message?: unknown; error?: unknown } | null | undefined;
175
+ const message =
176
+ errObj?.message ??
177
+ (errObj?.error && typeof errObj.error === "object" && "message" in errObj.error
178
+ ? (errObj.error as { message?: unknown }).message
179
+ : undefined) ??
180
+ err;
181
+ options.onDiagnostic?.(`Child extension failed to load: ${message ?? err}`);
182
+ }
183
+ }
184
+
185
+ const sessionManager = sdk.SessionManager.inMemory(options.cwd);
186
+ const createOptions: Record<string, unknown> = {
187
+ cwd: options.cwd,
188
+ sessionManager,
189
+ resourceLoader: loader,
190
+ excludeTools: [...options.excludeTools],
191
+ };
192
+ if (options.modelRuntime !== undefined) {
193
+ createOptions.modelRuntime = options.modelRuntime;
194
+ }
195
+ if (options.model !== undefined) {
196
+ createOptions.model = options.model;
197
+ }
198
+ if (options.thinking !== undefined) {
199
+ createOptions.thinkingLevel = options.thinking;
200
+ }
201
+ if (options.tools !== undefined) {
202
+ createOptions.tools = [...options.tools];
203
+ }
204
+
205
+ const created = await sdk.createAgentSession(createOptions);
206
+ if (created.modelFallbackMessage) {
207
+ options.onDiagnostic?.(created.modelFallbackMessage);
208
+ }
209
+ const session = created.session;
210
+ try {
211
+ await session.bindExtensions?.({});
212
+ } catch (err) {
213
+ session.dispose();
214
+ throw err;
215
+ }
216
+ return new HostChildSession(session, tempAgentDir, options.signal);
217
+ } catch (err) {
218
+ rmSync(tempAgentDir, { recursive: true, force: true });
219
+ throw err;
220
+ }
221
+ },
222
+ };
223
+ }
224
+
225
+ class HostChildSession implements ChildSession {
226
+ private disposed = false;
227
+ private readonly removeAbort: (() => void) | undefined;
228
+
229
+ constructor(
230
+ private readonly session: HostAgentSession,
231
+ private readonly tempAgentDir: string,
232
+ signal?: AbortSignal,
233
+ ) {
234
+ if (signal) {
235
+ const onAbort = (): void => {
236
+ void Promise.resolve(this.session.abort()).catch(() => undefined);
237
+ };
238
+ signal.addEventListener("abort", onAbort, { once: true });
239
+ this.removeAbort = () => signal.removeEventListener("abort", onAbort);
240
+ }
241
+ }
242
+
243
+ get sessionId(): string | undefined {
244
+ return this.session.sessionId;
245
+ }
246
+
247
+ get messages(): readonly unknown[] | undefined {
248
+ return this.session.messages;
249
+ }
250
+
251
+ prompt(text: string): Promise<void> {
252
+ return this.session.prompt(text);
253
+ }
254
+
255
+ abort(): Promise<void> {
256
+ return this.session.abort();
257
+ }
258
+
259
+ steer(text: string): Promise<unknown> {
260
+ return this.session.steer ? this.session.steer(text) : Promise.resolve(undefined);
261
+ }
262
+
263
+ getLastAssistantText(): string | undefined {
264
+ return this.session.getLastAssistantText?.();
265
+ }
266
+
267
+ getAllTools(): readonly { readonly name: string }[] {
268
+ return this.session.getAllTools?.() ?? [];
269
+ }
270
+
271
+ subscribe(handler: (event: unknown) => void): () => void {
272
+ return this.session.subscribe(handler);
273
+ }
274
+
275
+ dispose(): void {
276
+ if (this.disposed) {
277
+ return;
278
+ }
279
+ this.disposed = true;
280
+ this.removeAbort?.();
281
+ try {
282
+ this.session.dispose();
283
+ } finally {
284
+ rmSync(this.tempAgentDir, { recursive: true, force: true });
285
+ }
286
+ }
287
+ }
288
+
289
+ function createBuiltinExtension(sdk: HostSdk, name: ChildBuiltinExtension): unknown {
290
+ switch (name) {
291
+ case "codemode":
292
+ return sdk.createCodemodeExtension?.({ mode: "on" });
293
+ case "tool_search":
294
+ return sdk.createToolSearchExtension?.();
295
+ case "mcp":
296
+ return sdk.createMcpExtension?.();
297
+ }
298
+ }
299
+
300
+ function abortError(): Error {
301
+ const error = new Error("Subagent run was aborted.");
302
+ error.name = "AbortError";
303
+ return error;
304
+ }
@@ -0,0 +1,65 @@
1
+ import type { PiUiCustomComponent, PiUiCustomTheme, PiUiCustomTui } from "@restranger/repi-lib";
2
+ import { formatStatusWidget, widgetLineBudget } from "./format.js";
3
+ import type { SubagentRunSnapshot } from "./types.js";
4
+
5
+ export interface FleetStatusWidgetOptions {
6
+ readonly runs: () => readonly SubagentRunSnapshot[];
7
+ /** Suppress widget painting while modal inspector is open. */
8
+ readonly isInspectorOpen?: () => boolean;
9
+ readonly now?: () => number;
10
+ }
11
+
12
+ /**
13
+ * Live fleet tree above the editor: one header with the totals plus a `● agent · status · time ·
14
+ * turn · tokens` row per active child, its two most recent finished steps and the tool it is
15
+ * running right now. Queued children get a bare row; finished children disappear (their result is
16
+ * in the tool call, `/subagents fleet` owns history), so the widget is gone as soon as the last child settles.
17
+ *
18
+ * The height is capped from the terminal's row count instead of a constant, so a short window never
19
+ * pushes Pi's editor off the screen, and the plugin's spinner timer only asks for frames.
20
+ */
21
+ export class FleetStatusWidget implements PiUiCustomComponent {
22
+ private tui?: PiUiCustomTui;
23
+ private theme?: PiUiCustomTheme;
24
+
25
+ constructor(private readonly options: FleetStatusWidgetOptions) {}
26
+
27
+ attach(tui: PiUiCustomTui, theme: PiUiCustomTheme): void {
28
+ this.tui = tui;
29
+ this.theme = theme;
30
+ }
31
+
32
+ /**
33
+ * Pi's `Container.invalidate()` walks its children and calls this; without it the whole UI throws
34
+ * on the first invalidate (session switch, shutdown, `switchTuiMode`).
35
+ */
36
+ invalidate(): void {
37
+ // Every line is computed in `render()`, so there is nothing cached to drop.
38
+ }
39
+
40
+ dispose(): void {
41
+ this.tui = undefined;
42
+ this.theme = undefined;
43
+ }
44
+
45
+ /** A tick asks for one frame; a host that already dropped the component is not an error. */
46
+ refresh(): void {
47
+ try {
48
+ this.tui?.requestRender();
49
+ } catch {
50
+ // Detached or stale TUI: the plugin unmounts on the next sync.
51
+ }
52
+ }
53
+
54
+ render(width: number): string[] {
55
+ if (this.options.isInspectorOpen?.()) {
56
+ return [];
57
+ }
58
+ return formatStatusWidget(this.options.runs(), {
59
+ width,
60
+ maxLines: widgetLineBudget(this.tui?.terminal?.rows),
61
+ ...(this.theme ? { theme: this.theme } : {}),
62
+ ...(this.options.now ? { now: this.options.now() } : {}),
63
+ });
64
+ }
65
+ }