@lune_99/pi-subagent 0.0.0-stage → 0.2.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 (47) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/LICENSE +21 -0
  3. package/README.md +185 -2
  4. package/docs/capture.json +30 -0
  5. package/docs/previews.md +22 -0
  6. package/docs/reference.md +264 -0
  7. package/docs/subagent-auto-tiers.png +0 -0
  8. package/docs/subagent-inspector.png +0 -0
  9. package/docs/subagent-overview.png +0 -0
  10. package/package.json +82 -5
  11. package/skills/create-lune-subagent/SKILL.md +190 -0
  12. package/src/auto-model.ts +601 -0
  13. package/src/catalog.ts +111 -0
  14. package/src/definition-file.ts +147 -0
  15. package/src/definitions.ts +330 -0
  16. package/src/dock/dock-alert.ts +78 -0
  17. package/src/dock/dock-contribution.ts +328 -0
  18. package/src/extension-tools.ts +46 -0
  19. package/src/index.ts +194 -0
  20. package/src/inspector/details.ts +119 -0
  21. package/src/inspector/inspector.ts +677 -0
  22. package/src/inspector/layout.ts +119 -0
  23. package/src/inspector/transcript.ts +735 -0
  24. package/src/inspector/viewport.ts +62 -0
  25. package/src/inspector/wrap.ts +136 -0
  26. package/src/models.ts +69 -0
  27. package/src/notify/notification-box.ts +408 -0
  28. package/src/notify/notifier.ts +586 -0
  29. package/src/paths.ts +34 -0
  30. package/src/render/lune-theme.ts +68 -0
  31. package/src/render/text.ts +121 -0
  32. package/src/run/guide.ts +31 -0
  33. package/src/run/report-tool.ts +90 -0
  34. package/src/run/run-file.ts +194 -0
  35. package/src/run/run-manager.ts +935 -0
  36. package/src/run/run-session.ts +307 -0
  37. package/src/run/run.ts +773 -0
  38. package/src/run/session-start.ts +283 -0
  39. package/src/run/types.ts +175 -0
  40. package/src/run/worktree.ts +138 -0
  41. package/src/schema.ts +9 -0
  42. package/src/settings/agents-menu.ts +376 -0
  43. package/src/settings/panel.ts +221 -0
  44. package/src/settings/schema.ts +75 -0
  45. package/src/settings/thinking-choices.ts +92 -0
  46. package/src/tools/format.ts +397 -0
  47. package/src/tools/subagent-tools.ts +355 -0
@@ -0,0 +1,935 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { existsSync, rmSync } from "node:fs";
3
+
4
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
5
+ import type {
6
+ ExtensionAPI,
7
+ ExtensionContext,
8
+ ModelRuntime,
9
+ SessionBeforeTreeEvent,
10
+ SessionBeforeTreeResult,
11
+ Theme,
12
+ } from "@earendil-works/pi-coding-agent";
13
+ import {
14
+ chooseAutoModel,
15
+ DEFAULT_AUTO_MODEL_SETTINGS,
16
+ type AutoModelSettings,
17
+ } from "../auto-model.ts";
18
+ import type { AgentDefinition } from "../definitions.ts";
19
+ import type { ExtensionTool } from "../extension-tools.ts";
20
+ import {
21
+ AUTO_MODEL,
22
+ allowedModelRefs,
23
+ allowedModels,
24
+ formatModelRef,
25
+ parseModelRef,
26
+ type ModelRef,
27
+ } from "../models.ts";
28
+ import {
29
+ RUN_NOTIFICATION_TYPE,
30
+ RunNotifier,
31
+ buildRunNotification,
32
+ deliveredTurns,
33
+ type RunNotice,
34
+ } from "../notify/notifier.ts";
35
+ import { runSessionFile, runWorktreePath } from "../paths.ts";
36
+ import { displayLine } from "../render/text.ts";
37
+ import { SUBAGENT_GUIDE } from "./guide.ts";
38
+ import { REPORT_TOOL_NAME } from "./report-tool.ts";
39
+ import { createRunFile } from "./run-file.ts";
40
+ import { Run, type RunChange, type RunHost, type SendOutcome } from "./run.ts";
41
+ import type { LiveSession } from "./run-session.ts";
42
+ import { SessionSink, startRunSession } from "./session-start.ts";
43
+ import {
44
+ RUN_ENTRY_TYPE,
45
+ type AutoModelChoice,
46
+ type Isolation,
47
+ type RunSnapshot,
48
+ type SpawnEntryData,
49
+ type StopSource,
50
+ type TurnRecord,
51
+ type ValueSource,
52
+ } from "./types.ts";
53
+ import { createRunWorktree, removeRunWorktree, type CreatedWorktree } from "./worktree.ts";
54
+
55
+ export interface StartParams {
56
+ task: string;
57
+ title?: string;
58
+ agent?: string;
59
+ model?: string;
60
+ thinking?: ThinkingLevel;
61
+ tools?: string[];
62
+ isolation?: Isolation;
63
+ }
64
+
65
+ /** The run settings that only an inline start takes; a named agent runs with its definition's. */
66
+ export const INLINE_SETTINGS = ["model", "thinking", "tools", "isolation"] as const;
67
+
68
+ /**
69
+ * Why a start may not go ahead because it names an agent and sets its settings too, or
70
+ * `undefined`. The definition is the user's, so the main agent gives only the task and a title.
71
+ */
72
+ export function agentSettingsProblem(params: Omit<StartParams, "task">): string | undefined {
73
+ if (params.agent === undefined) {
74
+ return undefined;
75
+ }
76
+
77
+ const set = INLINE_SETTINGS.filter((field) => params[field] !== undefined);
78
+
79
+ return set.length > 0
80
+ ? `The agent "${params.agent}" runs with the model, thinking, tools and isolation of ` +
81
+ `its definition; give only task and title with agent, and leave out ${set.join(", ")}.`
82
+ : undefined;
83
+ }
84
+
85
+ /**
86
+ * Why an inline start may not go ahead because it names a model while Auto mode only is on, or
87
+ * `undefined`. Agent runs keep their definition's model.
88
+ */
89
+ export function autoOnlyProblem(
90
+ params: Omit<StartParams, "task">,
91
+ autoOnly: boolean,
92
+ ): string | undefined {
93
+ return autoOnly &&
94
+ params.agent === undefined &&
95
+ params.model !== undefined &&
96
+ params.model !== AUTO_MODEL
97
+ ? `Auto mode only is on, so an inline run uses model ${AUTO_MODEL}; leave out ` +
98
+ `model "${String(params.model)}".`
99
+ : undefined;
100
+ }
101
+
102
+ export interface ProgressOptions {
103
+ signal?: AbortSignal;
104
+ onProgress?: (text: string) => void;
105
+ }
106
+
107
+ export type ManagerListener = (change: RunChange, run: Run | undefined) => void;
108
+
109
+ /**
110
+ * All runs of one parent session, on every branch, and their lifecycle.
111
+ *
112
+ * Created at the parent's `session_start` and shut down with it: Pi replaces the extension runtime
113
+ * on /new, /resume, /fork and /reload, and runs never outlive the session that owns them.
114
+ */
115
+ export class RunManager implements RunHost {
116
+ readonly agentDir: string;
117
+ readonly modelRuntime: ModelRuntime | undefined;
118
+ readonly sessionId: string;
119
+ /** The run the inspector showed when it closed. Memory only, so it ends with the session. */
120
+ inspectorRunId: string | undefined;
121
+
122
+ private readonly pi: ExtensionAPI;
123
+ private readonly ctx: ExtensionContext;
124
+ /** Start values follow edits from the settings panel; names stay as the roster lists them. */
125
+ private readonly definitions: AgentDefinition[];
126
+ private readonly listExtensionTools: () => readonly ExtensionTool[];
127
+ private readonly autoModelSettings: (ctx: ExtensionContext) => Promise<AutoModelSettings>;
128
+ private readonly modelSelection: (ctx: ExtensionContext) => Promise<readonly ModelRef[]>;
129
+ private readonly autoOnly: (ctx: ExtensionContext) => Promise<boolean>;
130
+ private readonly runs = new Map<string, Run>();
131
+ /** Ended turns of runs on another branch; sent when their branch is active again. */
132
+ private readonly deferred = new Map<string, RunNotice[]>();
133
+ private readonly notifier: RunNotifier;
134
+ private readonly listeners = new Set<ManagerListener>();
135
+ private readonly reservedIds = new Set<string>();
136
+ private inlineCount = 0;
137
+ private shuttingDown = false;
138
+
139
+ constructor(options: {
140
+ pi: ExtensionAPI;
141
+ ctx: ExtensionContext;
142
+ agentDir: string;
143
+ definitions: readonly AgentDefinition[];
144
+ /** The parent's extension tools at the time of a start or resume; none when left out. */
145
+ extensionTools?: () => readonly ExtensionTool[];
146
+ /** Read at each `model: auto` start; the defaults when left out. */
147
+ autoModelSettings?: (ctx: ExtensionContext) => Promise<AutoModelSettings>;
148
+ /** A nonempty selection replaces the parent's scope for new runs. */
149
+ modelSelection?: (ctx: ExtensionContext) => Promise<readonly ModelRef[]>;
150
+ /** Read at each start; when true, inline runs use `model: auto`. Off when left out. */
151
+ autoOnly?: (ctx: ExtensionContext) => Promise<boolean>;
152
+ /** Tests only: a runtime with an offline provider. Runs otherwise create their own. */
153
+ modelRuntime?: ModelRuntime;
154
+ }) {
155
+ this.pi = options.pi;
156
+ this.ctx = options.ctx;
157
+ this.agentDir = options.agentDir;
158
+ this.modelRuntime = options.modelRuntime;
159
+ this.definitions = [...options.definitions];
160
+ this.listExtensionTools = options.extensionTools ?? (() => []);
161
+ this.autoModelSettings =
162
+ options.autoModelSettings ?? (async () => DEFAULT_AUTO_MODEL_SETTINGS);
163
+ this.modelSelection = options.modelSelection ?? (async () => []);
164
+ this.autoOnly = options.autoOnly ?? (async () => false);
165
+ this.sessionId = options.ctx.sessionManager.getSessionId();
166
+ this.notifier = new RunNotifier(
167
+ options.pi,
168
+ options.ctx.hasUI ? options.ctx.ui : undefined,
169
+ {
170
+ deliverable: (notice) => {
171
+ const run = this.runs.get(notice.runId);
172
+
173
+ return run !== undefined && this.isOnBranch(run);
174
+ },
175
+ hold: (notice) => this.defer(notice),
176
+ },
177
+ {
178
+ busy: () => !this.ctx.isIdle(),
179
+ aborting: () => this.ctx.signal?.aborted === true,
180
+ abortClearsQueues: () => this.ctx.mode === "tui",
181
+ // The whole file: a notice that reached another branch must not be sent again.
182
+ deliveredTurns: () => deliveredTurns(this.ctx.sessionManager.getEntries()),
183
+ },
184
+ );
185
+ }
186
+
187
+ // RunHost
188
+
189
+ projectTrusted(): boolean {
190
+ return this.ctx.isProjectTrusted();
191
+ }
192
+
193
+ theme(): Theme {
194
+ return this.ctx.ui.theme;
195
+ }
196
+
197
+ extensionTools(): readonly ExtensionTool[] {
198
+ return this.listExtensionTools();
199
+ }
200
+
201
+ onChange(run: Run, change: RunChange): void {
202
+ this.emit(change, run);
203
+ }
204
+
205
+ onTurnEnd(run: Run, record: TurnRecord): void {
206
+ // The main agent asked for the stop itself; a shutdown has nobody left to tell.
207
+ if (
208
+ this.shuttingDown ||
209
+ record.stoppedBy === "main-agent" ||
210
+ record.stoppedBy === "shutdown"
211
+ ) {
212
+ return;
213
+ }
214
+
215
+ const notice: RunNotice = {
216
+ runId: run.id,
217
+ name: run.name,
218
+ title: run.snapshot?.title,
219
+ record,
220
+ };
221
+
222
+ // The notifier checks the branch again when the batch goes out.
223
+ if (this.isOnBranch(run)) {
224
+ this.notifier.push(notice);
225
+ } else {
226
+ this.defer(notice);
227
+ }
228
+ }
229
+
230
+ // Queries
231
+
232
+ subscribe(listener: ManagerListener): () => void {
233
+ this.listeners.add(listener);
234
+
235
+ return () => {
236
+ this.listeners.delete(listener);
237
+ };
238
+ }
239
+
240
+ /** Read every run of this session tree from its file; restored runs are not live. */
241
+ restore(): void {
242
+ for (const entry of this.ctx.sessionManager.getEntries()) {
243
+ if (entry.type !== "custom" || entry.customType !== RUN_ENTRY_TYPE) {
244
+ continue;
245
+ }
246
+
247
+ const data = entry.data as Partial<SpawnEntryData> | undefined;
248
+
249
+ if (
250
+ typeof data?.runId !== "string" ||
251
+ typeof data.sessionFile !== "string" ||
252
+ typeof data.parentSessionId !== "string" ||
253
+ this.runs.has(data.runId)
254
+ ) {
255
+ continue;
256
+ }
257
+
258
+ const run = Run.restore(
259
+ {
260
+ id: data.runId,
261
+ file: data.sessionFile,
262
+ spawnEntryId: entry.id,
263
+ parentSessionId: data.parentSessionId,
264
+ readOnly: data.parentSessionId !== this.sessionId,
265
+ },
266
+ this,
267
+ );
268
+
269
+ this.runs.set(run.id, run);
270
+ this.countInlineName(run);
271
+ }
272
+ }
273
+
274
+ /** Runs whose `subagent_start` is on the active branch, in start order. */
275
+ branchRuns(): Run[] {
276
+ return this.runsByBranch().here;
277
+ }
278
+
279
+ /** Runs started on other branches; the inspector lists them so a report can be copied over. */
280
+ otherBranchRuns(): Run[] {
281
+ return this.runsByBranch().elsewhere;
282
+ }
283
+
284
+ /** Both lists from one walk of the active branch, for views that redraw on every frame. */
285
+ runsByBranch(): { here: Run[]; elsewhere: Run[] } {
286
+ const ids = new Set(this.ctx.sessionManager.getBranch().map((entry) => entry.id));
287
+ const here: Run[] = [];
288
+ const elsewhere: Run[] = [];
289
+
290
+ for (const run of this.runs.values()) {
291
+ (ids.has(run.spawnEntryId) ? here : elsewhere).push(run);
292
+ }
293
+
294
+ return { here, elsewhere };
295
+ }
296
+
297
+ isOnBranch(run: Run): boolean {
298
+ return this.ctx.sessionManager.getBranch().some((entry) => entry.id === run.spawnEntryId);
299
+ }
300
+
301
+ /** Whether an ended turn of this run waits for its branch to become active. */
302
+ hasDeferred(run: Run): boolean {
303
+ return this.deferred.has(run.id);
304
+ }
305
+
306
+ /** The run with this ID on the active branch; the tools never reach runs on other branches. */
307
+ branchRun(runId: string): Run {
308
+ const run = this.runs.get(runId);
309
+
310
+ if (run && this.isOnBranch(run)) {
311
+ return run;
312
+ }
313
+
314
+ const known = this.branchRuns();
315
+ // A model that read a name or title as the handle gets that run's ID spelled out, never aliased.
316
+ const matches = known.filter(
317
+ (other) => other.name === runId || other.snapshot?.title === runId,
318
+ );
319
+ const hint =
320
+ matches.length === 1
321
+ ? ` "${runId}" is a run ${matches[0]!.name === runId ? "name" : "title"}, not an ID; pass ${matches[0]!.id}.`
322
+ : "";
323
+
324
+ throw new Error(
325
+ `No subagent run "${runId}" on the current branch.${hint}` +
326
+ (known.length > 0
327
+ ? ` Runs here: ${known.map((other) => other.id).join(", ")}.`
328
+ : " There are no runs here."),
329
+ );
330
+ }
331
+
332
+ // Operations
333
+
334
+ async start(
335
+ params: StartParams,
336
+ ctx: ExtensionContext,
337
+ options: ProgressOptions = {},
338
+ ): Promise<Run> {
339
+ this.assertActive();
340
+
341
+ const autoOnly = params.agent === undefined && (await this.autoOnly(ctx));
342
+ const problem = agentSettingsProblem(params) ?? autoOnlyProblem(params, autoOnly);
343
+
344
+ if (problem) {
345
+ throw new Error(problem);
346
+ }
347
+
348
+ const definition = this.resolveDefinition(params.agent);
349
+ const taskTools = params.tools ?? definition?.tools;
350
+ const toolsSource: ValueSource =
351
+ params.tools !== undefined
352
+ ? "call"
353
+ : definition?.tools !== undefined
354
+ ? "definition"
355
+ : "settings";
356
+ const isolation = params.isolation ?? definition?.isolation ?? "shared";
357
+ const isolationSource: ValueSource =
358
+ params.isolation !== undefined
359
+ ? "call"
360
+ : definition?.isolation !== undefined
361
+ ? "definition"
362
+ : "default";
363
+ const explicitThinking = params.thinking ?? definition?.thinking;
364
+ const model = await this.resolveModel(params, definition, ctx, {
365
+ tools: taskTools,
366
+ isolation,
367
+ autoOnly,
368
+ options,
369
+ });
370
+ const thinking = model.thinking ?? explicitThinking ?? ctx.thinkingLevel;
371
+ const thinkingSource: ValueSource =
372
+ params.thinking !== undefined
373
+ ? "call"
374
+ : definition?.thinking !== undefined
375
+ ? "definition"
376
+ : model.thinking !== undefined
377
+ ? "auto"
378
+ : ctx.thinkingLevel !== undefined
379
+ ? "parent"
380
+ : "settings";
381
+
382
+ this.assertActive();
383
+
384
+ const runId = this.reserveRunId();
385
+ const name = definition?.name ?? `run-${++this.inlineCount}`;
386
+ const title = typeof params.title === "string" ? displayLine(params.title) : undefined;
387
+ const file = runSessionFile(this.sessionId, runId, this.agentDir);
388
+ let worktree: CreatedWorktree | undefined;
389
+ let fileCreated = false;
390
+ let live: LiveSession | undefined;
391
+
392
+ // Everything before the spawn entry is undone on failure; nothing refers to it yet.
393
+ const undo = async (error: unknown): Promise<never> => {
394
+ const problems: string[] = [];
395
+
396
+ if (live) {
397
+ await live.close();
398
+ }
399
+
400
+ if (fileCreated) {
401
+ try {
402
+ rmSync(file, { force: true });
403
+ } catch (removeError) {
404
+ problems.push(
405
+ `The run file ${file} could not be removed: ${message(removeError)}`,
406
+ );
407
+ }
408
+ }
409
+
410
+ if (worktree) {
411
+ try {
412
+ await removeRunWorktree(worktree.repoRoot, worktree.path);
413
+ } catch (removeError) {
414
+ problems.push(
415
+ `The worktree ${worktree.path} could not be removed: ${message(removeError)}`,
416
+ );
417
+ }
418
+ }
419
+
420
+ this.reservedIds.delete(runId);
421
+
422
+ throw new Error([message(error), ...problems].join("\n"), { cause: error });
423
+ };
424
+
425
+ let cwd = ctx.cwd;
426
+ let spawnEntryId: string;
427
+ const sink = new SessionSink();
428
+
429
+ try {
430
+ if (isolation === "worktree") {
431
+ options.onProgress?.("Creating the worktree");
432
+ worktree = await createRunWorktree(
433
+ ctx.cwd,
434
+ runWorktreePath(this.sessionId, runId, this.agentDir),
435
+ options.signal,
436
+ );
437
+ cwd = worktree.cwd;
438
+ }
439
+
440
+ live = await startRunSession({
441
+ cwd,
442
+ agentDir: this.agentDir,
443
+ projectTrusted: ctx.isProjectTrusted(),
444
+ modelRuntime: this.modelRuntime,
445
+ appendSystemPrompt: [definition?.body ?? "", SUBAGENT_GUIDE],
446
+ model: model.ref,
447
+ thinkingLevel: thinking,
448
+ // An explicit selection is the allowlist; otherwise `+report` keeps the run's own
449
+ // defaultTools selection and adds the protocol tool to it.
450
+ tools: taskTools
451
+ ? [...new Set([...taskTools, REPORT_TOOL_NAME])]
452
+ : [`+${REPORT_TOOL_NAME}`],
453
+ check: taskTools ?? "default",
454
+ extensionTools: this.extensionTools(),
455
+ reason: "startup",
456
+ theme: ctx.ui.theme,
457
+ openSessionManager: () => {
458
+ const manager = createRunFile(file, {
459
+ runId,
460
+ cwd,
461
+ parentSessionFile: this.ctx.sessionManager.getSessionFile(),
462
+ });
463
+
464
+ fileCreated = true;
465
+
466
+ return manager;
467
+ },
468
+ sink,
469
+ signal: options.signal,
470
+ onProgress: options.onProgress,
471
+ });
472
+
473
+ this.assertActive();
474
+ this.pi.appendEntry<SpawnEntryData>(RUN_ENTRY_TYPE, {
475
+ runId,
476
+ sessionFile: file,
477
+ parentSessionId: this.sessionId,
478
+ });
479
+ spawnEntryId = this.findSpawnEntryId(runId);
480
+ } catch (error) {
481
+ return undo(error);
482
+ }
483
+
484
+ const session = live.session;
485
+ const snapshot: RunSnapshot = {
486
+ runId,
487
+ name,
488
+ ...(title ? { title } : {}),
489
+ ...(definition
490
+ ? {
491
+ definition: {
492
+ name: definition.name,
493
+ body: definition.body,
494
+ file: definition.file,
495
+ },
496
+ }
497
+ : {}),
498
+ task: params.task,
499
+ model: formatModelRef(session.model ?? model.ref),
500
+ ...(model.auto ? { autoModel: model.auto } : {}),
501
+ thinking: session.thinkingLevel,
502
+ // An MCP name in an allowlist would hide the run's other MCP tools when it reopens,
503
+ // and the default selection never names one.
504
+ tools: taskTools
505
+ ? [...new Set([...taskTools, REPORT_TOOL_NAME])]
506
+ : session.getActiveToolNames().filter((tool) => !tool.startsWith("mcp__")),
507
+ sources: {
508
+ model: model.source,
509
+ thinking: thinkingSource,
510
+ tools: toolsSource,
511
+ isolation: isolationSource,
512
+ },
513
+ isolation,
514
+ cwd,
515
+ ...(worktree
516
+ ? {
517
+ worktree: {
518
+ repoRoot: worktree.repoRoot,
519
+ path: worktree.path,
520
+ baseCommit: worktree.baseCommit,
521
+ },
522
+ }
523
+ : {}),
524
+ parentSessionId: this.sessionId,
525
+ parentSessionFile: this.ctx.sessionManager.getSessionFile(),
526
+ spawnEntryId,
527
+ createdAt: new Date().toISOString(),
528
+ };
529
+
530
+ const identity = {
531
+ id: runId,
532
+ file,
533
+ spawnEntryId: snapshot.spawnEntryId,
534
+ parentSessionId: this.sessionId,
535
+ readOnly: false,
536
+ };
537
+
538
+ try {
539
+ session.sessionManager.appendCustomEntry(RUN_ENTRY_TYPE, snapshot);
540
+ } catch (error) {
541
+ // The spawn entry exists already, so the run stays listed, as failed, with this error.
542
+ await live.close();
543
+ this.runs.set(runId, Run.restore(identity, this));
544
+ this.reservedIds.delete(runId);
545
+ this.emit("state", this.runs.get(runId));
546
+
547
+ throw new Error(`Run ${runId} could not record its snapshot: ${message(error)}`, {
548
+ cause: error,
549
+ });
550
+ }
551
+
552
+ const run = Run.started(identity, snapshot, live, sink, this);
553
+
554
+ this.runs.set(runId, run);
555
+ this.reservedIds.delete(runId);
556
+ this.emit("state", run);
557
+
558
+ try {
559
+ await run.startTask(params.task);
560
+ } catch (error) {
561
+ throw new Error(
562
+ `Run ${runId} could not start its task: ${message(error)}\n` +
563
+ "The run is kept as failed; continue it with subagent_send once the cause is fixed.",
564
+ { cause: error },
565
+ );
566
+ }
567
+
568
+ return run;
569
+ }
570
+
571
+ async send(
572
+ run: Run,
573
+ text: string,
574
+ from: "main-agent" | "user",
575
+ options: ProgressOptions = {},
576
+ ): Promise<SendOutcome> {
577
+ this.assertActive();
578
+
579
+ return run.send(text, from, options);
580
+ }
581
+
582
+ async stop(run: Run, by: StopSource): Promise<boolean> {
583
+ this.assertActive();
584
+
585
+ return run.stop(by);
586
+ }
587
+
588
+ /**
589
+ * Copy the last turn of a run on another branch to the active branch as a custom message. It
590
+ * does not trigger a turn: while the main agent works, Pi holds it until the turn ends.
591
+ */
592
+ copyReport(run: Run): void {
593
+ if (this.isOnBranch(run)) {
594
+ throw new Error(
595
+ `Run ${run.id} is on this branch; its turns reach the main agent already.`,
596
+ );
597
+ }
598
+
599
+ if (!run.lastTurn) {
600
+ throw new Error(`Run ${run.id} has no ended turn to copy.`);
601
+ }
602
+
603
+ const { content, details } = buildRunNotification([
604
+ {
605
+ runId: run.id,
606
+ name: run.name,
607
+ title: run.snapshot?.title,
608
+ record: run.lastTurn,
609
+ copied: true,
610
+ },
611
+ ]);
612
+
613
+ this.pi.sendMessage({ customType: RUN_NOTIFICATION_TYPE, content, display: true, details });
614
+ }
615
+
616
+ /**
617
+ * Leaving a branch with running runs asks once whether to stop them. Without a UI they keep
618
+ * running. A navigation that goes ahead holds every notification until it ends.
619
+ */
620
+ async beforeTree(
621
+ event: SessionBeforeTreeEvent,
622
+ ctx: ExtensionContext,
623
+ ): Promise<SessionBeforeTreeResult | undefined> {
624
+ const running = this.runsLeaving(event.preparation, ctx);
625
+ let stopping = false;
626
+
627
+ if (running.length > 0 && ctx.hasUI) {
628
+ const keep = "Keep them running";
629
+ const stop = "Stop them";
630
+ const choice = await ctx.ui.select(
631
+ `${running.length} subagent run${running.length === 1 ? " is" : "s are"} still ` +
632
+ `running on the branch you are leaving: ${running.map((run) => run.title).join(", ")}.`,
633
+ [keep, stop],
634
+ { signal: event.signal },
635
+ );
636
+
637
+ if (choice === undefined) {
638
+ return { cancel: true };
639
+ }
640
+
641
+ stopping = choice === stop;
642
+ }
643
+
644
+ this.holdNotifications(event.signal);
645
+
646
+ if (stopping) {
647
+ await Promise.all(running.map((run) => run.stop("branch")));
648
+ }
649
+
650
+ return undefined;
651
+ }
652
+
653
+ /** After navigation: send what waited for the branch that is now active. */
654
+ afterTree(): void {
655
+ for (const [runId, notices] of this.deferred) {
656
+ const run = this.runs.get(runId);
657
+
658
+ if (run && this.isOnBranch(run)) {
659
+ for (const notice of notices) {
660
+ this.notifier.push(notice);
661
+ }
662
+
663
+ this.deferred.delete(runId);
664
+ }
665
+ }
666
+
667
+ this.notifier.resume();
668
+ this.emit("state", undefined);
669
+ }
670
+
671
+ /**
672
+ * Called when the main agent starts a turn. A navigation that another extension cancelled, or
673
+ * that failed, ends without `session_tree`, and its held notices must not wait forever.
674
+ */
675
+ resumeNotifications(): void {
676
+ this.notifier.resume();
677
+ }
678
+
679
+ /** Called when a run of the main agent settles, to confirm the notices sent to it. */
680
+ mainAgentSettled(aborted: boolean): void {
681
+ this.notifier.settled(aborted);
682
+ }
683
+
684
+ /**
685
+ * Stop notifying, interrupt running runs, then shut down every live session, idle ones included,
686
+ * so the built-ins close their connections before the sessions are disposed.
687
+ */
688
+ async shutdown(): Promise<void> {
689
+ this.shuttingDown = true;
690
+ this.notifier.dispose();
691
+ this.deferred.clear();
692
+
693
+ await Promise.all(
694
+ [...this.runs.values()].map(async (run) => {
695
+ try {
696
+ await run.stop("shutdown");
697
+ } catch (error) {
698
+ console.error(`Stopping subagent run ${run.id} failed: ${message(error)}`);
699
+ }
700
+
701
+ try {
702
+ await run.close();
703
+ } catch (error) {
704
+ console.error(`Closing subagent run ${run.id} failed: ${message(error)}`);
705
+ }
706
+ }),
707
+ );
708
+
709
+ this.listeners.clear();
710
+ }
711
+
712
+ private assertActive(): void {
713
+ if (this.shuttingDown) {
714
+ throw new Error("The parent session is shutting down.");
715
+ }
716
+ }
717
+
718
+ /** Keep an ended turn of a run on another branch until that branch is active again. */
719
+ private defer(notice: RunNotice): void {
720
+ this.deferred.set(notice.runId, [...(this.deferred.get(notice.runId) ?? []), notice]);
721
+ this.emit("state", this.runs.get(notice.runId));
722
+ }
723
+
724
+ /**
725
+ * Notices wait while the session tree changes: sent then, one could land on the branch being
726
+ * left, or start a turn of the main agent during the navigation. Pi emits `session_tree` only
727
+ * after a completed navigation, so an aborted one releases them through its signal.
728
+ */
729
+ private holdNotifications(signal: AbortSignal): void {
730
+ this.notifier.pause();
731
+ signal.addEventListener("abort", () => this.notifier.resume(), { once: true });
732
+ }
733
+
734
+ /** Running runs whose spawn entry is on the part of the branch that the navigation leaves. */
735
+ private runsLeaving(
736
+ preparation: SessionBeforeTreeEvent["preparation"],
737
+ ctx: ExtensionContext,
738
+ ): Run[] {
739
+ const { oldLeafId, commonAncestorId } = preparation;
740
+
741
+ if (!oldLeafId) {
742
+ return [];
743
+ }
744
+
745
+ const path = ctx.sessionManager.getBranch(oldLeafId);
746
+ const start = commonAncestorId
747
+ ? path.findIndex((entry) => entry.id === commonAncestorId) + 1
748
+ : 0;
749
+ const leaving = new Set(path.slice(start).map((entry) => entry.id));
750
+
751
+ return [...this.runs.values()].filter(
752
+ (run) => run.state === "running" && leaving.has(run.spawnEntryId),
753
+ );
754
+ }
755
+
756
+ private emit(change: RunChange, run: Run | undefined): void {
757
+ for (const listener of this.listeners) {
758
+ listener(change, run);
759
+ }
760
+ }
761
+
762
+ private resolveDefinition(agent: string | undefined): AgentDefinition | undefined {
763
+ if (agent === undefined) {
764
+ return undefined;
765
+ }
766
+
767
+ const definition = this.definitions.find((candidate) => candidate.name === agent);
768
+
769
+ if (!definition) {
770
+ const names = this.definitions.map((candidate) => candidate.name);
771
+
772
+ throw new Error(
773
+ `No subagent definition named "${agent}".` +
774
+ (names.length > 0 ? ` Loaded: ${names.join(", ")}.` : " None are loaded."),
775
+ );
776
+ }
777
+
778
+ return definition;
779
+ }
780
+
781
+ /**
782
+ * Replace the start values of the loaded definition that `previousFile` held, after the
783
+ * settings panel edited it. Its name and description stay as loaded: the roster in the main
784
+ * agent's prompt and the `agent` enum list them, and both stay fixed for the session.
785
+ */
786
+ applyDefinitionEdit(previousFile: string, edited: AgentDefinition): void {
787
+ const index = this.definitions.findIndex((definition) => definition.file === previousFile);
788
+
789
+ if (index === -1) {
790
+ return;
791
+ }
792
+
793
+ const loaded = this.definitions[index]!;
794
+
795
+ this.definitions[index] = {
796
+ ...edited,
797
+ name: loaded.name,
798
+ description: loaded.description,
799
+ };
800
+ }
801
+
802
+ /**
803
+ * Requested models must be in the subagent allowlist. The parent's own current model is used
804
+ * as it is, since Pi lets a session's default model sit outside its scope.
805
+ */
806
+ private async resolveModel(
807
+ params: StartParams,
808
+ definition: AgentDefinition | undefined,
809
+ ctx: ExtensionContext,
810
+ run: {
811
+ tools?: readonly string[];
812
+ isolation: Isolation;
813
+ autoOnly: boolean;
814
+ options: ProgressOptions;
815
+ },
816
+ ): Promise<{
817
+ ref: { provider: string; id: string };
818
+ source: ValueSource;
819
+ auto?: AutoModelChoice;
820
+ /** The thinking level selected together with the auto model. */
821
+ thinking?: ThinkingLevel;
822
+ }> {
823
+ const requested =
824
+ params.model ?? definition?.model ?? (run.autoOnly ? AUTO_MODEL : undefined);
825
+
826
+ if (requested === undefined) {
827
+ if (!ctx.model) {
828
+ throw new Error("The main agent has no current model for the run to inherit.");
829
+ }
830
+
831
+ return { ref: { provider: ctx.model.provider, id: ctx.model.id }, source: "parent" };
832
+ }
833
+
834
+ const source: ValueSource =
835
+ params.model !== undefined
836
+ ? "call"
837
+ : definition?.model !== undefined
838
+ ? "definition"
839
+ : "settings";
840
+ if (
841
+ requested === AUTO_MODEL &&
842
+ (params.thinking !== undefined || definition?.thinking !== undefined)
843
+ ) {
844
+ throw new Error(
845
+ "Model auto chooses both the model and thinking level; leave out thinking.",
846
+ );
847
+ }
848
+
849
+ const selection = await this.modelSelection(ctx);
850
+
851
+ if (requested === AUTO_MODEL) {
852
+ run.options.onProgress?.("Choosing a model and thinking level");
853
+
854
+ const { ref, choice, thinking } = await chooseAutoModel({
855
+ ctx,
856
+ settings: await this.autoModelSettings(ctx),
857
+ models: allowedModels(ctx, selection),
858
+ task: params.task,
859
+ definition,
860
+ tools: run.tools,
861
+ isolation: run.isolation,
862
+ signal: run.options.signal,
863
+ });
864
+
865
+ return { ref, source, auto: choice, ...(thinking ? { thinking } : {}) };
866
+ }
867
+
868
+ const ref = parseModelRef(requested);
869
+
870
+ if (!ref) {
871
+ throw new Error(`Invalid model "${requested}": use provider/id.`);
872
+ }
873
+
874
+ const allowed = allowedModelRefs(ctx, selection);
875
+
876
+ if (!allowed.includes(requested)) {
877
+ throw new Error(
878
+ `The model ${requested} is not in the allowed set` +
879
+ (allowed.length > 0
880
+ ? `: ${allowed.join(", ")}.`
881
+ : "; no models are available."),
882
+ );
883
+ }
884
+
885
+ return { ref, source };
886
+ }
887
+
888
+ private reserveRunId(): string {
889
+ for (;;) {
890
+ const id = randomBytes(4).toString("hex");
891
+
892
+ if (
893
+ !this.runs.has(id) &&
894
+ !this.reservedIds.has(id) &&
895
+ !existsSync(runSessionFile(this.sessionId, id, this.agentDir))
896
+ ) {
897
+ this.reservedIds.add(id);
898
+
899
+ return id;
900
+ }
901
+ }
902
+ }
903
+
904
+ /** Inherited runs count too, so a new inline run never shares a name with one in the list. */
905
+ private countInlineName(run: Run): void {
906
+ const match = /^run-(\d+)$/.exec(run.name);
907
+
908
+ if (match) {
909
+ this.inlineCount = Math.max(this.inlineCount, Number(match[1]));
910
+ }
911
+ }
912
+
913
+ /** `pi.appendEntry()` returns nothing, so the new entry is found by its run ID. */
914
+ private findSpawnEntryId(runId: string): string {
915
+ const entries = this.ctx.sessionManager.getEntries();
916
+
917
+ for (let index = entries.length - 1; index >= 0; index--) {
918
+ const entry = entries[index]!;
919
+
920
+ if (
921
+ entry.type === "custom" &&
922
+ entry.customType === RUN_ENTRY_TYPE &&
923
+ (entry.data as Partial<SpawnEntryData> | undefined)?.runId === runId
924
+ ) {
925
+ return entry.id;
926
+ }
927
+ }
928
+
929
+ throw new Error(`The spawn entry of run ${runId} is missing from the parent session.`);
930
+ }
931
+ }
932
+
933
+ function message(error: unknown): string {
934
+ return error instanceof Error ? error.message : String(error);
935
+ }