@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/plugin.ts ADDED
@@ -0,0 +1,568 @@
1
+ import {
2
+ type Disposable,
3
+ PERMISSIONS_CONTRACT_ID,
4
+ type PermissionService,
5
+ type PiBeforeAgentStartEvent,
6
+ type PiContext,
7
+ type PiExtensionAPI,
8
+ SHIMMER_INTERVAL_MS,
9
+ SUBAGENTS_CONTRACT_ID,
10
+ type SubagentsService,
11
+ allPiToolNames,
12
+ getService,
13
+ getSessionId,
14
+ publishService,
15
+ } from "@restranger/repi-lib";
16
+ import type { SubagentConfirmationRequest } from "./child-guard.js";
17
+ import { registerSubagentsCommand } from "./command.js";
18
+ import { resolveChildExtensions } from "./extensions.js";
19
+ import type { FleetView } from "./fleet-ui.js";
20
+ import { SPINNER_FRAMES, formatStatusWidget, linesComponent } from "./format.js";
21
+ import { SubagentManager } from "./manager.js";
22
+ import { saveAgentFallbackModels } from "./overrides.js";
23
+ import {
24
+ ACTIVE_RUNS_SECTION,
25
+ AGENT_SECTION,
26
+ formatActiveRunsPromptSection,
27
+ formatAgentPromptSection,
28
+ } from "./prompt.js";
29
+ import { AgentRegistry } from "./registry.js";
30
+ import { type ChildSessionFactory, createChildSessionFactory } from "./session.js";
31
+ import { FleetStatusWidget } from "./status-widget.js";
32
+ import { createSubagentTools } from "./tools.js";
33
+ import type { SubagentRunSnapshot } from "./types.js";
34
+
35
+ export interface SubagentsPluginOptions {
36
+ /** Initial cwd used for the tool description and discovery. Defaults to `process.cwd()`. */
37
+ readonly cwd?: string;
38
+ readonly homeDir?: string;
39
+ readonly env?: Readonly<Record<string, string | undefined>>;
40
+ readonly userDirs?: readonly string[];
41
+ readonly projectDirs?: readonly string[];
42
+ /** Override discovery entirely (tests and custom hosts). */
43
+ readonly registry?: AgentRegistry;
44
+ readonly sessionFactory?: ChildSessionFactory;
45
+ /** Explicit parent permission service; otherwise resolved from `re:permissions@1`. */
46
+ readonly permissionService?: PermissionService;
47
+ /**
48
+ * Extension modules that must never be instantiated inside a child (for example the parent's
49
+ * own UI or permission plugin). Matched after resolving relative paths.
50
+ */
51
+ readonly excludeExtensionPaths?: readonly string[];
52
+ readonly maxConcurrent?: number;
53
+ /** Widget refresh interval; 0 disables the spinner timer. */
54
+ readonly statusRefreshMs?: number;
55
+ readonly now?: () => number;
56
+ }
57
+
58
+ export interface ResolveMaxConcurrentOptions {
59
+ readonly explicit?: number;
60
+ readonly config?: number;
61
+ readonly default?: number;
62
+ }
63
+
64
+ export function resolveMaxConcurrent(options: ResolveMaxConcurrentOptions): number {
65
+ if (options.explicit !== undefined && !Number.isNaN(options.explicit)) {
66
+ return Math.max(1, Math.floor(options.explicit));
67
+ }
68
+ if (options.config !== undefined && !Number.isNaN(options.config)) {
69
+ return Math.max(1, Math.floor(options.config));
70
+ }
71
+ return options.default ?? 4;
72
+ }
73
+
74
+ interface SessionState {
75
+ /**
76
+ * Newest context seen for this session. Pi hands out a fresh proxy per event and invalidates the
77
+ * old one after `newSession`/`fork`/`switchSession`/`reload`, so this must be refreshed on every
78
+ * event instead of being captured once at `session_start`.
79
+ */
80
+ ctx: PiContext;
81
+ /** Same context, readable from closures created before `state` exists. */
82
+ readonly ctxRef: { ctx: PiContext };
83
+ readonly registry: AgentRegistry;
84
+ readonly manager: SubagentManager;
85
+ readonly notified: Set<string>;
86
+ /** Open fleet inspector, if any; refreshed from the manager's change callback. */
87
+ fleet?: FleetView;
88
+ widget?: FleetStatusWidget;
89
+ widgetMounted: boolean;
90
+ lastStatus?: string;
91
+ serviceRegistration?: Disposable;
92
+ }
93
+
94
+ const WIDGET_KEY = "repi-subagents";
95
+ const STATUS_KEY = "repi-subagents";
96
+
97
+ export interface SubagentsRuntime {
98
+ readonly managers: ReadonlyMap<string, SubagentManager>;
99
+ attach(pi: PiExtensionAPI): void;
100
+ dispose(): void;
101
+ }
102
+
103
+ /**
104
+ * Declarative subagents for Pi.
105
+ *
106
+ * The Markdown declarations own the agent catalogue: six adapted built-in defaults, user and
107
+ * project `.md` files, and JSON overrides. Each child session is scoped to the declaration's tool
108
+ * allowlist and delegates permission checks to the parent's `re:permissions@1` service.
109
+ */
110
+ export function createSubagentsRuntime(options: SubagentsPluginOptions = {}): SubagentsRuntime {
111
+ const sessions = new Map<string, SessionState>();
112
+ const sessionFactory = options.sessionFactory ?? createChildSessionFactory();
113
+ const now = options.now ?? (() => Date.now());
114
+ const initialRegistry =
115
+ options.registry ??
116
+ new AgentRegistry({
117
+ cwd: options.cwd ?? process.cwd(),
118
+ ...(options.homeDir ? { homeDir: options.homeDir } : {}),
119
+ ...(options.env ? { env: options.env } : {}),
120
+ ...(options.userDirs ? { userDirs: options.userDirs } : {}),
121
+ ...(options.projectDirs ? { projectDirs: options.projectDirs } : {}),
122
+ });
123
+ let descriptionRegistry = initialRegistry;
124
+ let attached = false;
125
+ let disposed = false;
126
+ let widgetTimer: ReturnType<typeof setInterval> | undefined;
127
+ let spinnerIndex = 0;
128
+ let piRef: PiExtensionAPI | undefined;
129
+ const defaultSessionId = "default";
130
+ /**
131
+ * Session whose runs `/subagents` should suggest. Argument completion gets no context from Pi,
132
+ * so the last session an event touched stands in for "the one the user is typing in".
133
+ */
134
+ let activeSessionId = defaultSessionId;
135
+
136
+ const buildRegistry = (ctx: PiContext): AgentRegistry => {
137
+ if (options.registry) {
138
+ return options.registry;
139
+ }
140
+ return new AgentRegistry({
141
+ cwd: ctx.cwd,
142
+ ...(options.homeDir ? { homeDir: options.homeDir } : {}),
143
+ ...(options.env ? { env: options.env } : {}),
144
+ ...(options.userDirs ? { userDirs: options.userDirs } : {}),
145
+ ...(options.projectDirs ? { projectDirs: options.projectDirs } : {}),
146
+ // Fail closed: a host that cannot answer the trust question must not load project agents.
147
+ workspaceTrusted: ctx.isProjectTrusted?.() === true,
148
+ });
149
+ };
150
+
151
+ /** Active runs shown by the persistent widget; finished runs disappear immediately. */
152
+ const widgetRuns = (state: SessionState, sessionId: string): SubagentRunSnapshot[] =>
153
+ state.manager.list(sessionId).filter((run) => run.status === "running" || run.status === "queued");
154
+
155
+ const spinnerFrame = (): string => SPINNER_FRAMES[spinnerIndex % SPINNER_FRAMES.length] ?? "⠋";
156
+
157
+ /**
158
+ * Ask the widget for a frame. Kept apart from the rest of `syncWidget` so a detached or stale
159
+ * TUI (Pi invalidates captured contexts after a session switch) cannot skip the unmount below.
160
+ */
161
+ const refreshWidget = (state: SessionState): void => {
162
+ state.widget?.refresh();
163
+ };
164
+
165
+ const syncWidget = (state: SessionState, sessionId: string): void => {
166
+ const ui = state.ctx.ui;
167
+ try {
168
+ const runs = widgetRuns(state, sessionId);
169
+ if (runs.length === 0 || state.fleet) {
170
+ refreshWidget(state);
171
+ if (state.widgetMounted) {
172
+ ui.setWidget?.(WIDGET_KEY, undefined);
173
+ state.widgetMounted = false;
174
+ }
175
+ } else if (!state.ctx.mode || state.ctx.mode === "tui") {
176
+ if (state.widgetMounted) {
177
+ refreshWidget(state);
178
+ } else {
179
+ ui.setWidget?.(
180
+ WIDGET_KEY,
181
+ (tui, theme) => {
182
+ state.widget?.attach(tui, theme);
183
+ return state.widget ?? linesComponent(() => []);
184
+ },
185
+ { placement: "aboveEditor" },
186
+ );
187
+ state.widgetMounted = true;
188
+ }
189
+ } else {
190
+ // RPC/print/JSON hosts drop component factories, so hand them plain lines.
191
+ ui.setWidget?.(WIDGET_KEY, formatStatusWidget(runs, { width: 100 }), {
192
+ placement: "aboveEditor",
193
+ });
194
+ state.widgetMounted = true;
195
+ }
196
+
197
+ const active = state.manager.activeCount(sessionId);
198
+ const status = active > 0 ? `${active} active` : undefined;
199
+ if (status !== state.lastStatus) {
200
+ ui.setStatus?.(STATUS_KEY, status);
201
+ state.lastStatus = status;
202
+ }
203
+ } catch {
204
+ // A host with a read-only or rejecting UI must not break the run.
205
+ }
206
+ };
207
+
208
+ const anyActive = (): boolean => {
209
+ for (const [sessionId, state] of sessions) {
210
+ if (state.manager.activeCount(sessionId) > 0) {
211
+ return true;
212
+ }
213
+ }
214
+ return false;
215
+ };
216
+
217
+ const refreshSession = (sessionId: string): void => {
218
+ const state = sessions.get(sessionId);
219
+ if (!state) {
220
+ return;
221
+ }
222
+ syncWidget(state, sessionId);
223
+ state.fleet?.refresh();
224
+ ensureWidgetTimer();
225
+ };
226
+
227
+ const ensureWidgetTimer = (): void => {
228
+ const interval = options.statusRefreshMs ?? SHIMMER_INTERVAL_MS;
229
+ if (interval <= 0 || !anyActive()) {
230
+ if (widgetTimer) {
231
+ clearInterval(widgetTimer);
232
+ widgetTimer = undefined;
233
+ }
234
+ return;
235
+ }
236
+ if (widgetTimer) {
237
+ return;
238
+ }
239
+ widgetTimer = setInterval(() => {
240
+ spinnerIndex++;
241
+ for (const sessionId of [...sessions.keys()]) {
242
+ refreshSession(sessionId);
243
+ }
244
+ if (!anyActive() && widgetTimer) {
245
+ clearInterval(widgetTimer);
246
+ widgetTimer = undefined;
247
+ }
248
+ }, interval);
249
+ widgetTimer.unref?.();
250
+ };
251
+
252
+ const notifyDiagnostics = (state: SessionState): void => {
253
+ const diagnostics = state.registry.diagnostics();
254
+ const unseen = diagnostics.filter((diagnostic) => {
255
+ const key = `${diagnostic.level}:${diagnostic.path}:${diagnostic.message}`;
256
+ if (state.notified.has(key)) {
257
+ return false;
258
+ }
259
+ state.notified.add(key);
260
+ return true;
261
+ });
262
+ if (unseen.length === 0) {
263
+ return;
264
+ }
265
+ const errors = unseen.filter((diagnostic) => diagnostic.level === "error");
266
+ if (errors.length > 0) {
267
+ state.ctx.ui.notify(
268
+ `Subagents: ${errors.length} agent error${errors.length === 1 ? "" : "s"}. Run /subagents for details.`,
269
+ "error",
270
+ );
271
+ return;
272
+ }
273
+ state.ctx.ui.notify(
274
+ `Subagents: ${unseen.length} agent warning${unseen.length === 1 ? "" : "s"}. Run /subagents for details.`,
275
+ "warning",
276
+ );
277
+ };
278
+
279
+ /**
280
+ * Route a child's `ask` permission decision to the parent UI.
281
+ *
282
+ * Dialogs are serialized per session: two children that ask at the same time would otherwise
283
+ * race for the same prompt slot and answer each other's question. A host without `confirm` (or
284
+ * a dialog that throws) returns `false`, so the guard keeps failing closed.
285
+ */
286
+ const confirmationChain = new Map<string, Promise<unknown>>();
287
+ const askParent = async (
288
+ sessionId: string,
289
+ ctx: PiContext,
290
+ request: SubagentConfirmationRequest,
291
+ ): Promise<boolean> => {
292
+ if (ctx.hasUI === false || typeof ctx.ui?.confirm !== "function") {
293
+ return false;
294
+ }
295
+ const previous = confirmationChain.get(sessionId) ?? Promise.resolve();
296
+ const next = previous.then(async () => {
297
+ try {
298
+ const message = [request.prompt, request.reason].filter(Boolean).join("\n\n");
299
+ return await ctx.ui.confirm(
300
+ `Subagent permission: ${request.tool}`,
301
+ message,
302
+ request.signal ? { signal: request.signal } : undefined,
303
+ );
304
+ } catch {
305
+ return false;
306
+ }
307
+ });
308
+ confirmationChain.set(
309
+ sessionId,
310
+ next.catch(() => undefined),
311
+ );
312
+ return next;
313
+ };
314
+
315
+ const ensureSession = (pi: PiExtensionAPI, ctx: PiContext): SessionState => {
316
+ const sessionId = getSessionId(ctx, defaultSessionId);
317
+ activeSessionId = sessionId;
318
+ const existing = sessions.get(sessionId);
319
+ if (existing) {
320
+ existing.ctx = ctx;
321
+ existing.ctxRef.ctx = ctx;
322
+ return existing;
323
+ }
324
+
325
+ const registry = buildRegistry(ctx);
326
+ descriptionRegistry = registry;
327
+ const ctxRef: { ctx: PiContext } = { ctx };
328
+ const maxConcurrent = resolveMaxConcurrent({
329
+ explicit: options.maxConcurrent,
330
+ config: registry.maxConcurrent(),
331
+ });
332
+ const manager = new SubagentManager({
333
+ createSession: sessionFactory,
334
+ agents: registry,
335
+ listParentTools: () => allPiToolNames(pi),
336
+ resolveChildExtensions: (tools) =>
337
+ resolveChildExtensions(pi.getAllTools?.(), tools, {
338
+ cwd: ctxRef.ctx.cwd,
339
+ ...(options.excludeExtensionPaths ? { excludePaths: options.excludeExtensionPaths } : {}),
340
+ }),
341
+ resolvePermission: (parentSessionId) =>
342
+ options.permissionService ?? getService<PermissionService>(PERMISSIONS_CONTRACT_ID, parentSessionId),
343
+ requestPermission: (request) => askParent(sessionId, ctxRef.ctx, request),
344
+ maxConcurrent,
345
+ now,
346
+ onChange: (changedSessionId) => refreshSession(changedSessionId),
347
+ });
348
+ const state: SessionState = {
349
+ ctx,
350
+ ctxRef,
351
+ registry,
352
+ manager,
353
+ notified: new Set<string>(),
354
+ widgetMounted: false,
355
+ };
356
+ state.widget = new FleetStatusWidget({
357
+ runs: () => manager.list(sessionId),
358
+ isInspectorOpen: () => Boolean(state.fleet),
359
+ now,
360
+ });
361
+ const subagentsService: SubagentsService = {
362
+ listAgents: () =>
363
+ registry.list().map((agent) => ({
364
+ name: agent.name,
365
+ description: agent.description,
366
+ ...(agent.model ? { model: agent.model } : {}),
367
+ ...(agent.fallbackModels ? { fallbackModels: agent.fallbackModels } : {}),
368
+ })),
369
+ // Applied in memory so a settings menu does not need a reload to take effect, and persisted
370
+ // here because this plugin owns `.repi/subagents.json`: another plugin must not write it.
371
+ setAgentFallbackModels: (agentName, fallbackModels) => {
372
+ registry.setFallbackModels(agentName, fallbackModels);
373
+ if (ctx.isProjectTrusted?.() === false) {
374
+ return;
375
+ }
376
+ try {
377
+ saveAgentFallbackModels(ctx.cwd, [{ name: agentName, fallbackModels }]);
378
+ } catch (err) {
379
+ ctx.ui.notify(
380
+ `Subagents: could not save the override for "${agentName}": ${err instanceof Error ? err.message : String(err)}`,
381
+ "warning",
382
+ );
383
+ }
384
+ },
385
+ };
386
+ state.serviceRegistration = publishService({
387
+ contract: SUBAGENTS_CONTRACT_ID,
388
+ sessionId,
389
+ owner: "@restranger/repi-subagents",
390
+ impl: subagentsService,
391
+ });
392
+ sessions.set(sessionId, state);
393
+ notifyDiagnostics(state);
394
+ refreshSession(sessionId);
395
+ return state;
396
+ };
397
+
398
+ const sessionFor = (ctx: PiContext | undefined): { sessionId: string; state: SessionState } | undefined => {
399
+ if (!ctx || !piRef) {
400
+ return undefined;
401
+ }
402
+ const sessionId = getSessionId(ctx, defaultSessionId);
403
+ const state = ensureSession(piRef, ctx);
404
+ return { sessionId, state };
405
+ };
406
+
407
+ const registerTools = (pi: PiExtensionAPI): void => {
408
+ for (const tool of createSubagentTools({
409
+ sessionFor: (ctx) => sessionFor(ctx),
410
+ // A getter: `/subagents reload` swaps the registry the description reads from.
411
+ descriptionRegistry: () => descriptionRegistry,
412
+ now,
413
+ spinnerFrame,
414
+ tickSpinner: () => {
415
+ spinnerIndex++;
416
+ },
417
+ })) {
418
+ pi.registerTool(tool);
419
+ }
420
+ };
421
+
422
+ const attach = (pi: PiExtensionAPI): void => {
423
+ if (disposed) {
424
+ throw new Error("Subagents runtime is disposed and cannot be attached.");
425
+ }
426
+ if (attached) {
427
+ throw new Error("Subagents runtime is already attached to a Pi extension API.");
428
+ }
429
+ attached = true;
430
+ piRef = pi;
431
+
432
+ registerTools(pi);
433
+ registerSubagentsCommand(pi, {
434
+ sessionFor: (ctx) => sessionFor(ctx),
435
+ getActiveRuns: () => sessions.get(activeSessionId)?.manager.list(activeSessionId) ?? [],
436
+ refreshSession,
437
+ notifyDiagnostics,
438
+ onReload: (registry) => {
439
+ descriptionRegistry = registry;
440
+ },
441
+ maxConcurrent: options.maxConcurrent,
442
+ now,
443
+ widgetKey: WIDGET_KEY,
444
+ });
445
+
446
+ pi.on("session_start", (_event, ctx) => {
447
+ if (!disposed) {
448
+ ensureSession(pi, ctx);
449
+ }
450
+ });
451
+
452
+ pi.on("before_agent_start", (event, ctx) => {
453
+ if (disposed) {
454
+ return undefined;
455
+ }
456
+ const state = ensureSession(pi, ctx);
457
+ const sections = (event as PiBeforeAgentStartEvent | undefined)?.systemPromptOptions?.sections;
458
+ if (!sections) {
459
+ return undefined;
460
+ }
461
+ // Prompt sections, not a tool call: the model sees the catalogue and the runs already in
462
+ // flight before it decides, so it has no reason to ask for the list first. Pi diffs the
463
+ // sections between turns, so only the bodies travel.
464
+ applyPromptSection(sections, AGENT_SECTION, formatAgentPromptSection(state.registry.list()));
465
+ applyPromptSection(
466
+ sections,
467
+ ACTIVE_RUNS_SECTION,
468
+ formatActiveRunsPromptSection(state.manager.list(getSessionId(ctx, defaultSessionId)), now()),
469
+ );
470
+ return undefined;
471
+ });
472
+
473
+ pi.on("turn_start", (_event, ctx) => {
474
+ if (disposed) {
475
+ return;
476
+ }
477
+ const sessionId = getSessionId(ctx, defaultSessionId);
478
+ const state = sessions.get(sessionId);
479
+ if (!state) {
480
+ return;
481
+ }
482
+ refreshSession(sessionId);
483
+ });
484
+
485
+ pi.on("session_shutdown", (_event, ctx) => {
486
+ const sessionId = getSessionId(ctx, defaultSessionId);
487
+ const state = sessions.get(sessionId);
488
+ if (!state) {
489
+ return;
490
+ }
491
+ state.widget?.dispose();
492
+ state.manager.dispose();
493
+ state.fleet?.dispose();
494
+ state.serviceRegistration?.dispose();
495
+ sessions.delete(sessionId);
496
+ try {
497
+ ctx.ui.setWidget?.(WIDGET_KEY, undefined);
498
+ ctx.ui.setStatus?.(STATUS_KEY, undefined);
499
+ } catch {
500
+ // ignore UI teardown failures
501
+ }
502
+ if (!anyActive() && widgetTimer) {
503
+ clearInterval(widgetTimer);
504
+ widgetTimer = undefined;
505
+ }
506
+ });
507
+ };
508
+
509
+ const dispose = (): void => {
510
+ if (disposed) {
511
+ return;
512
+ }
513
+ disposed = true;
514
+ if (widgetTimer) {
515
+ clearInterval(widgetTimer);
516
+ widgetTimer = undefined;
517
+ }
518
+ for (const state of sessions.values()) {
519
+ state.widget?.dispose();
520
+ state.manager.dispose();
521
+ state.fleet?.dispose();
522
+ state.serviceRegistration?.dispose();
523
+ state.widgetMounted = false;
524
+ // A host that unloads the runtime must not keep a stale "N active" line above the editor.
525
+ try {
526
+ state.ctx.ui.setWidget?.(WIDGET_KEY, undefined);
527
+ state.ctx.ui.setStatus?.(STATUS_KEY, undefined);
528
+ } catch {
529
+ // Stale context after a session switch: nothing left to tear down.
530
+ }
531
+ }
532
+ sessions.clear();
533
+ piRef = undefined;
534
+ };
535
+
536
+ return {
537
+ get managers() {
538
+ return new Map([...sessions].map(([sessionId, state]) => [sessionId, state.manager]));
539
+ },
540
+ attach,
541
+ dispose,
542
+ };
543
+ }
544
+
545
+ /** Return a Pi extension factory; useful for tests and composition in a custom host. */
546
+ export function createSubagentsPlugin(options: SubagentsPluginOptions = {}): (pi: unknown) => void {
547
+ const runtime = createSubagentsRuntime(options);
548
+ return (pi) => runtime.attach(pi as PiExtensionAPI);
549
+ }
550
+
551
+ /** Default Pi entry point (`pi.extensions`). */
552
+ export default function subagentsExtension(pi: unknown): void {
553
+ createSubagentsPlugin()(pi);
554
+ }
555
+
556
+ /**
557
+ * Write or clear one prompt section.
558
+ *
559
+ * Clearing matters: Pi keeps the previous section bodies across turns and diffs them, so a stale
560
+ * catalogue would keep advertising agents that are no longer on disk and runs that already ended.
561
+ */
562
+ function applyPromptSection(sections: Record<string, string>, name: string, body: string | undefined): void {
563
+ if (body === undefined) {
564
+ delete sections[name];
565
+ } else {
566
+ sections[name] = body;
567
+ }
568
+ }