pi-subagent-manager 0.13.0 → 0.15.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.
package/README.md CHANGED
@@ -72,9 +72,9 @@ They inherit your current model until you set preferences. Details: [docs/defaul
72
72
  | `/agents import` | Import agents from other subagent extensions |
73
73
  | `/agents reload` | Reload definitions and settings |
74
74
 
75
- A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line; `/agents tree` still opens the full tree. While subagents are starting or running, press **Left** at the start of the main draft to open it; otherwise Left stays native. Press **Right** at the end of the draft (or in an empty input) to collapse the widget to one line for this session only, without changing saved settings. `/agents tree` remains available regardless of agent activity. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
75
+ A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line. A fresh prompt hides previously settled agents from the widget; they reappear only when resumed, and `/agents tree` always keeps them available. While subagents are starting or running, press **Left** at the start of the main draft to open it; otherwise Left stays native. Press **Right** at the end of the draft (or in an empty input) to collapse the widget to one line for this session only, without changing saved settings. `/agents tree` remains available regardless of agent activity. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
76
76
 
77
- Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Font icons** in `/agents` to show role-specific icons beside agent names, with animated progress glyphs for starting/running agents and static icons for settled agents (off by default; requires a Nerd Font in your terminal). Custom agent types can set an optional `icon` or use **[labs] Icon** in `/agents types`. See [icon setup](docs/settings.md#labs-nerd-font-icons-nerdfonticons).
77
+ Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Font icons** in `/agents` to show role-specific icons beside agent names (off by default; requires a Nerd Font in your terminal). Loaders appear **before**, never instead of, the role icon. Choose Circle, Braille, or Hourglass under **[labs] Loader style**, with previews of every animation frame and each family's completed, paused, failed, and stopped icons. Custom agent types can set an optional `icon` or use **[labs] Icon** in `/agents types`. See [icon setup](docs/settings.md#labs-nerd-font-icons-nerdfonticons).
78
78
 
79
79
  Enable **[labs] Final Recap** in `/agents` to automatically ask the idle main agent to summarize detached-agent results, keeping the final response in the main thread. It is off by default and suppressed by Subagent Mode Off. **Enabling it may cause extra model turns and uses more tokens and context.** See [Final Recap](docs/settings.md#labs-final-recap-finalrecap).
80
80
 
@@ -46,6 +46,9 @@ In `/agents types`, editing a bundled agent asks you to pick one mode first,
46
46
  and settings stay locked until you choose. Overrides cannot rename the agent
47
47
  or edit the system prompt — fork it instead.
48
48
 
49
+ To undo a fork or override, choose **Reset to bundled** (after Save) in the editor.
50
+ It deletes the `.md`/`.yml` file after confirmation and the shipped agent applies again.
51
+
49
52
  These are the only locations read. Other packages' `~/.pi/agent/agents` or `.pi/agents` are ignored — use [`/agents import`](importing-agents.md) for those.
50
53
 
51
54
  ## 2. Write the file
package/docs/settings.md CHANGED
@@ -16,6 +16,7 @@ All keys are optional. Defaults:
16
16
  "subagentMode": "opportunistic",
17
17
  "widgetMode": "full",
18
18
  "nerdFontIcons": false,
19
+ "loaderStyle": "circle",
19
20
  "finalRecap": false,
20
21
  "modelSelection": "pick-first-scoped",
21
22
  "toolFiltering": "allowed",
@@ -59,10 +60,16 @@ Minimal mode groups starting agents with running agents and excludes the main co
59
60
 
60
61
  Experimental features are tagged **[labs]** in settings. **[labs] Nerd Font icons** is an on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"nerdFontIcons": true` in your settings file. Configure a [Nerd Font](https://www.nerdfonts.com/) in your terminal first; unsupported fonts may show boxes or incorrect glyphs. The extension does not install or detect fonts.
61
62
 
62
- When enabled, an agent type’s optional `icon` appears before its readable name in the full widget, thread browsers, live watcher header, and type picker. Starting/running agents use a cycling Nerd Font progress glyph in the widget, fullscreen tree and live watcher header; paused/completed/stopped/failed agents retain static role icons. Active agents without a configured icon also show the progress glyph. The one-line minimal widget animates its aggregate running count, not individual agents. Turning the setting off restores text-only labels without removing configured icons; RPC output remains static. Saved settings apply immediately to newly rendered widgets and dialogs.
63
+ When enabled, an agent type’s optional `icon` appears before its readable name in the full widget, thread browsers, live watcher header, and type picker. Starting/running agents show the selected loader **before the original role icon**, never replacing it. Completed, paused, failed, and stopped agents show that loader family's corresponding static state icon before the role icon. Agents without a configured role icon still show their loader/state indicator. The one-line minimal widget uses the same family's indicators for aggregate status counts. Turning the setting off restores text-only labels without removing configured icons; RPC output keeps state indicators static. Saved settings apply immediately to newly rendered widgets and dialogs.
63
64
 
64
65
  All six bundled agents have [role-specific icons](default-agents.md#nerd-font-icons). Add or change an icon with **[labs] Icon** in `/agents types`, or the optional `icon` frontmatter field in [your own agent](custom-agents.md#icons-labs). Retained threads keep the icon from their saved agent definition.
65
66
 
67
+ ## [labs] Loader style (`loaderStyle`)
68
+
69
+ Choose **Circle** (default), **Braille**, or **Hourglass** in `/agents` settings and save with **Ctrl+S**, or set `"loaderStyle": "circle"`, `"braille"`, or `"hourglass"` in your settings file. Loaders are displayed when **[labs] Nerd Font icons** is enabled.
70
+
71
+ The Labs preview shows every family's running animation frames and completed, paused, failed, and stopped icons, so you can compare all states before choosing. Starting uses the running animation. State indicators always precede the unchanged role icon; the selected family also applies to the minimal widget's counts. In non-animated output, active agents use the family's first frame.
72
+
66
73
  ## [labs] Final Recap (`finalRecap`)
67
74
 
68
75
  **[labs] Final Recap** is an experimental on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"finalRecap": true` in your settings file.
@@ -4,7 +4,7 @@
4
4
 
5
5
  | Tool | Purpose |
6
6
  | -------------- | ---------------------------------------------------- |
7
- | `agent_types` | List types and what they're for |
7
+ | `agent_types` | Names, descriptions, resolved models and thinking |
8
8
  | `agent_spawn` | Start `{path, type, task, wait?}`. Waits by default. |
9
9
  | `agent_wait` | Wait for settlement; optional `timeoutMs` |
10
10
  | `agent_steer` | Send `{path, message}`; queues input or resumes |
@@ -14,6 +14,11 @@
14
14
  | `agent_stop` | Cancel a descendant and its subtree |
15
15
  | `agent_output` | Page through long final answers by character offset |
16
16
 
17
+ `agent_types` returns one compact line per type, with the model and effective thinking level
18
+ that a new child of the caller would use under current settings. Unresolvable types are
19
+ marked unavailable with a reason. Preference lists, advisory model suggestions and UI metadata
20
+ are omitted. Spawning under another parent path can change inherited settings.
21
+
17
22
  ```json
18
23
  {
19
24
  "path": "controller-security-research",
@@ -87,16 +92,16 @@ The widget above the input editor has two display modes, selected with **Status
87
92
  - **Full** (default): the existing compact tree, at most twelve lines.
88
93
  - **Minimal**: a summary line such as `3 running, 2 stopped, 1 failed, 1 paused ↑12k ↓3k`, with semantic theme colors. Starting agents count as running; completed agents are counted when present. Token totals include only currently starting/running agents, not the main conversation or settled threads. Use `/agents tree` for details.
89
94
 
90
- Once the main turn has ended and no subagents are starting or running, either mode collapses to a single status-count line without the browser hint. The full tree remains available via `/agents tree`; **Left** at the start of the draft opens it only while subagents are starting or running. A new main turn or active subagent restores the configured display mode unless Right has collapsed the widget for this session.
95
+ Once the main turn has ended and no subagents are starting or running, either mode collapses to a single status-count line without the browser hint. The full tree remains available via `/agents tree`; **Left** at the start of the draft opens it only while subagents are starting or running. A fresh main prompt hides agents that were already settled (completed, failed, stopped or paused); they remain in `/agents tree` and reappear in the widget only when resumed. Agents still starting or running remain visible, and new agents appear normally. Automatic Final Recap turns keep the current task's results visible. Visible agents use the configured display mode unless Right has collapsed the widget for this session.
91
96
 
92
97
  In full mode:
93
98
 
94
99
  - One row per agent: colored type pill, path, state, task, active time, input `↑` / output `↓` tokens.
95
100
  - Activity and lifecycle messages (such as `Completed; session retained`) are omitted to save space; detailed status remains available in `/agents tree` and `agent_status`.
96
- - Active branches are shown first; the most recent agents within each state are preferred when previews overflow. Overflow is counted, not listed.
101
+ - Agents are ordered newest-started first (spawn or resume); a branch ranks by its most recently started agent. The most recently started agents are preferred when previews overflow. Overflow is counted, not listed.
97
102
  - Time freezes while paused and resumes on continue.
98
103
  - A small status strip below the previews shows the running count (including starting agents) and **Press ← to open subagent browser**, including when agents overflow. The full footer also shows **→ collapse**. Minimal mode keeps **← browser** inline so it stays one line. Browser hints appear only while subagents are starting or running; RPC output omits keyboard hints.
99
- - With **[labs] Nerd Font icons** enabled, starting/running agents show a cycling progress glyph in the widget and fullscreen tree/live-view headers. Settled agents retain static role icons. The minimal summary also animates its running count. Animation timers stop on settlement or disposal; RPC output stays static.
104
+ - With **[labs] Nerd Font icons** enabled, the selected Circle, Braille, or Hourglass loader appears before the preserved role icon in the widget and fullscreen tree/live-view headers. Each family provides completed, paused, failed, and stopped state icons. The minimal summary uses the same indicators for its status counts. Preview all families and states under **[labs] Loader style**. Animation timers stop on settlement or disposal; RPC output stays static.
100
105
 
101
106
  ### Interrupts and stopping agents
102
107
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
package/src/index.ts CHANGED
@@ -51,6 +51,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
51
51
  };
52
52
  let generation = 0;
53
53
  let rootTurnEnded = false;
54
+ const hiddenWidgetThreads = new Set<string>();
54
55
  let widgetCollapsed = false;
55
56
  let summaryRunning = false;
56
57
  let suspendingSummaries = false;
@@ -95,10 +96,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
95
96
  manager.list().some((thread) => thread.path !== "/root" &&
96
97
  (thread.state === "starting" || thread.state === "running")),
97
98
  openTree: () => manager && context
98
- ? navigation.open(context, manager.scope("/root"), undefined, limits.nerdFontIcons) : undefined,
99
+ ? navigation.open(context, manager.scope("/root"), undefined, limits.nerdFontIcons, limits.loaderStyle) : undefined,
99
100
  canCollapse: () => manager !== undefined && context?.mode === "tui" &&
100
101
  limits.subagentMode !== "off" && !navigation.isOpen && !widgetCollapsed &&
101
- limits.widgetMode === "full" && manager.list().some((thread) => thread.path !== "/root"),
102
+ limits.widgetMode === "full" && widgetThreads().some((thread) => thread.path !== "/root"),
102
103
  collapseWidget: () => {
103
104
  widgetCollapsed = true;
104
105
  if (context) refreshWidget(context);
@@ -138,6 +139,12 @@ export default function piSubagent(pi: ExtensionAPI): void {
138
139
  if (!manager) throw new Error("Subagent threads are not initialized; start a Pi session first");
139
140
  return manager;
140
141
  };
142
+ const widgetThreads = () => requireManager().list().filter((thread) => {
143
+ // Resuming a retained session makes it visible for this task, even after it settles again.
144
+ if (thread.state === "starting" || thread.state === "running")
145
+ hiddenWidgetThreads.delete(thread.path);
146
+ return !hiddenWidgetThreads.has(thread.path);
147
+ });
141
148
  const requireContext = () => {
142
149
  if (!context) throw new Error("No active Pi session");
143
150
  return context;
@@ -289,7 +296,22 @@ export default function piSubagent(pi: ExtensionAPI): void {
289
296
  }
290
297
  };
291
298
 
292
- const rootTools = agentTools(requireManager, "/root", () => store.list());
299
+ const makeDriverFactory = () =>
300
+ createDriverFactory(
301
+ requireContext,
302
+ () => limits.modelSelection,
303
+ () => limits.toolFiltering,
304
+ () => inheritedTools.snapshot(),
305
+ );
306
+ let driverFactory = makeDriverFactory();
307
+ const toolsFor = (path: string) =>
308
+ agentTools(
309
+ requireManager,
310
+ path,
311
+ () => store.list(),
312
+ (type) => driverFactory.resolveAgentSettings(type, path),
313
+ );
314
+ const rootTools = toolsFor("/root");
293
315
  let toolsEnabled: boolean | undefined;
294
316
  const syncTools = () => {
295
317
  const enabled = limits.subagentMode !== "off";
@@ -312,10 +334,18 @@ export default function piSubagent(pi: ExtensionAPI): void {
312
334
  const refreshWidget = (ctx: ExtensionContext) => {
313
335
  if (limits.subagentMode === "off") {
314
336
  if (ctx.hasUI) ctx.ui.setWidget("pi-subagent", undefined);
315
- } else updateWidget(ctx, requireManager().list(), widgetCollapsed ? "minimal" : limits.widgetMode,
316
- limits.nerdFontIcons, rootTurnEnded);
337
+ } else updateWidget(ctx, widgetThreads(), widgetCollapsed ? "minimal" : limits.widgetMode,
338
+ limits.nerdFontIcons, rootTurnEnded, limits.loaderStyle);
317
339
  };
318
340
  pi.on("agent_start", async (_event, ctx) => {
341
+ // A new task must not resurrect the previous task's settled agents. Automatic
342
+ // final-recap turns still belong to that task and keep its results visible.
343
+ if (manager && !summaryRunning) {
344
+ for (const thread of manager.list()) {
345
+ if (thread.state !== "starting" && thread.state !== "running")
346
+ hiddenWidgetThreads.add(thread.path);
347
+ }
348
+ }
319
349
  rootTurnEnded = false;
320
350
  if (manager) refreshWidget(ctx);
321
351
  });
@@ -353,7 +383,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
353
383
  inheritedTools.reset();
354
384
  context = ctx;
355
385
  rootTurnEnded = false;
356
- if (installEditor) widgetCollapsed = false;
386
+ if (installEditor) {
387
+ widgetCollapsed = false;
388
+ hiddenWidgetThreads.clear();
389
+ }
357
390
  store = new ConfigStore({
358
391
  cwd: ctx.cwd,
359
392
  agentDir: getAgentDir(),
@@ -362,17 +395,17 @@ export default function piSubagent(pi: ExtensionAPI): void {
362
395
  persistenceSignature = "";
363
396
  const settingsDiagnostics = loadLimits(ctx);
364
397
  syncTools();
398
+ driverFactory = makeDriverFactory();
365
399
  const instance = new ThreadManager({
366
400
  ...limits,
367
- createDriver: createDriverFactory(
368
- requireContext,
369
- () => limits.modelSelection,
370
- () => limits.toolFiltering,
371
- () => inheritedTools.snapshot(),
372
- ),
401
+ createDriver: driverFactory,
373
402
  rootSnapshot: () => buildSessionContext(requireContext().sessionManager.getBranch()).messages,
374
403
  getType: (name) => store.get(name),
375
- toolsFor: (path) => agentTools(requireManager, path, () => store.list()),
404
+ toolsFor,
405
+ onEventError: (error, event) => {
406
+ const message = error instanceof Error ? error.message : String(error);
407
+ context?.ui.notify(`Subagent ${event.kind} notification failed: ${message}`, "warning");
408
+ },
376
409
  onEvent: (event) => {
377
410
  if (token !== generation) return;
378
411
  refreshWidget(requireContext());
@@ -501,9 +534,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
501
534
  },
502
535
  });
503
536
  } else if (command === "status") {
504
- await showAgentStatus(ctx, requireManager().scope("/root"), undefined, limits.nerdFontIcons);
537
+ await showAgentStatus(ctx, requireManager().scope("/root"), undefined, limits.nerdFontIcons, limits.loaderStyle);
505
538
  } else if (command === "tree") {
506
- await navigation.open(ctx, requireManager().scope("/root"), rest.join(" ") || undefined, limits.nerdFontIcons);
539
+ await navigation.open(ctx, requireManager().scope("/root"), rest.join(" ") || undefined, limits.nerdFontIcons, limits.loaderStyle);
507
540
  } else
508
541
  ctx.ui.notify(
509
542
  "Usage: /agents [tree [path] | status | settings | types | import | reload]",
@@ -7,6 +7,7 @@ import type {
7
7
  SavedThread,
8
8
  SavedThreadView,
9
9
  ThreadService,
10
+ ThreadEvent,
10
11
  ThreadView,
11
12
  TranscriptListener,
12
13
  TranscriptObservation,
@@ -143,6 +144,7 @@ export class ThreadManager {
143
144
  output: current.output,
144
145
  error: current.error,
145
146
  createdAt: current.createdAt,
147
+ ...(current.lastStartedAt !== undefined ? { lastStartedAt: current.lastStartedAt } : {}),
146
148
  sessionFile: current.sessionFile,
147
149
  // Settled totals only. startedAt and partial usage must not churn persistence.
148
150
  elapsedMs: record.view.elapsedMs ?? 0,
@@ -357,7 +359,7 @@ export class ThreadManager {
357
359
  throw new Error("Progress message must contain 1–8000 characters");
358
360
  record.view.status = message;
359
361
  this.touch(record);
360
- this.options.onEvent?.({
362
+ this.emit({
361
363
  kind: "update",
362
364
  thread: this.view(record),
363
365
  message,
@@ -475,6 +477,7 @@ export class ThreadManager {
475
477
  record.view.state = "starting";
476
478
  record.view.status = "Starting";
477
479
  record.view.startedAt = Date.now();
480
+ record.view.lastStartedAt = record.view.startedAt;
478
481
  delete record.view.output;
479
482
  delete record.view.error;
480
483
  const epoch = this.epoch;
@@ -519,7 +522,7 @@ export class ThreadManager {
519
522
  markStarted(); // Failed/cancelled initialization must also release callers waiting to steer.
520
523
  this.touch(record);
521
524
  if (!this.disposed && epoch === this.epoch)
522
- this.options.onEvent?.({
525
+ this.emit({
523
526
  kind: "settled",
524
527
  thread: this.view(record),
525
528
  recipient: record.view.parent ?? record.view.owner,
@@ -639,10 +642,24 @@ export class ThreadManager {
639
642
  }
640
643
  }
641
644
  }
645
+ private emit(event: ThreadEvent): void {
646
+ try {
647
+ this.options.onEvent?.(event);
648
+ } catch (error) {
649
+ // Widgets/persistence/delivery run on the runner's event path. An exception
650
+ // here must not orphan a prompt promise or reject detached settlement.
651
+ try {
652
+ if (this.options.onEventError) this.options.onEventError(error, event);
653
+ else console.warn(`Subagent ${event.kind} notification failed: ${errorText(error)}`);
654
+ } catch {
655
+ /* A failing diagnostic sink must not turn a notification into a crash. */
656
+ }
657
+ }
658
+ }
642
659
  private touch(record: Record): void {
643
660
  record.view.updatedAt = Date.now();
644
661
  this.publishTranscript(record);
645
- if (!this.disposed) this.options.onEvent?.({ kind: "change", thread: this.view(record) });
662
+ if (!this.disposed) this.emit({ kind: "change", thread: this.view(record) });
646
663
  }
647
664
  /** Fold driver-cumulative usage into persisted totals. Partials only refresh the live view. */
648
665
  private applyUsage(
@@ -656,7 +673,7 @@ export class ThreadManager {
656
673
  if (input === record.liveInputTokens && output === record.liveOutputTokens) return;
657
674
  record.liveInputTokens = input;
658
675
  record.liveOutputTokens = output;
659
- if (!this.disposed) this.options.onEvent?.({ kind: "metrics", thread: this.view(record) });
676
+ if (!this.disposed) this.emit({ kind: "metrics", thread: this.view(record) });
660
677
  return;
661
678
  }
662
679
  record.view.inputTokens =
@@ -6,13 +6,18 @@ export function subagentPrompt(settings: ManagerSettings): string | undefined {
6
6
  const policy =
7
7
  settings.subagentMode === "orchestration"
8
8
  ? "Orchestration mode: /root only coordinates. Delegate every user task to subagents, even small or sequential tasks. Do not inspect/edit files, run commands, research, or execute task work yourself. Only plan, assign, monitor, clarify, and synthesize subagent results for the user. This restriction applies only to /root; subagents execute the work."
9
- : "Opportunistic mode: do ordinary tasks yourself. Delegate only when work can be parallelized or a task is very large; do not spawn agents for small, straightforward tasks.";
9
+ : "Opportunistic mode: do ordinary tasks yourself. Delegate only when work can be parallelized, is long-running, or is very large; do not spawn agents for small, quick, straightforward tasks.";
10
+ const waitingPolicy =
11
+ settings.subagentMode === "orchestration"
12
+ ? "As an orchestrator, you must NEVER be blocked waiting for subagents. ALWAYS start every subagent in async/background mode with wait:false, even for small or sequential tasks. NEVER call agent_wait or use a foreground spawn. End your turn after assigning work so you remain free to talk to the user while subagents work. Check agent_status and collect available results with agent_output without blocking; if results are not ready, report that and leave the conversation free."
13
+ : "For independent parallel work, spawn all siblings with wait:false before agent_wait. Only await synchronous tasks whose results are needed in the current turn. For long-running tasks, create background agents with wait:false and do not immediately call agent_wait; end your turn so you remain free to talk to the user while they work. Await background results when the user asks you to collect them.";
10
14
  return [
11
15
  "## pi-subagent",
12
16
  "You are /root, the main conversation (L1).",
13
17
  policy,
14
- "Call agent_types before choosing a type. Name children by task using kebab-case paths (e.g. /root/security-review), not type names. Paths determine context ancestry; independent roots inherit no history.",
15
- "For independent parallel work, spawn all siblings with wait:false before agent_wait. Use agent_status to inspect, agent_wait to wait, and agent_output for full results. Detached notifications do not resume your turn.",
18
+ "Call agent_types before choosing a type. Use task-based kebab-case paths, not type names. Choose context via agent_spawn path: /root/task forks the lexical parent's conversation; /task starts fresh with no inherited history. Use fresh agents for adversarial review or clean-slate research; give them a self-contained task without the current thread's conclusions.",
19
+ waitingPolicy,
20
+ "Use agent_status to inspect and agent_output for full results. Detached notifications do not resume your turn.",
16
21
  "Use agent_steer to send input or resume retained sessions. Paused agents have no final answer; completed agents hand back results. Both retain their session.",
17
22
  `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
18
23
  ].join("\n");
@@ -1,5 +1,6 @@
1
1
  import path from "node:path";
2
2
  import type { AssistantMessage } from "@earendil-works/pi-ai";
3
+ import { clampThinkingLevel } from "@earendil-works/pi-ai/compat";
3
4
  import { existsSync } from "node:fs";
4
5
  import { mkdir, readFile, realpath } from "node:fs/promises";
5
6
  import {
@@ -24,9 +25,16 @@ import { selectTools } from "../prefs/config.ts";
24
25
  import { TranscriptChannel } from "./transcript.ts";
25
26
  import type { InheritedToolSource } from "./inherited-tools.ts";
26
27
  import type { ModelSelectionMode, ToolFilteringMode } from "../prefs/settings.ts";
27
- import { modelIdentity, getModelPreferences, selectPreferredModel } from "../prefs/models.ts";
28
+ import {
29
+ modelIdentity,
30
+ getModelPreferences,
31
+ selectPreferredModel,
32
+ ModelPreferenceError,
33
+ } from "../prefs/models.ts";
28
34
  import {
29
35
  THINKING_LEVELS,
36
+ type AgentType,
37
+ type ResolvedAgentSettings,
30
38
  type DriverFactory,
31
39
  type DriverOptions,
32
40
  type ThinkingLevel,
@@ -141,10 +149,99 @@ export function createDriverFactory(
141
149
  getModelSelection: () => ModelSelectionMode = () => "pick-first-scoped",
142
150
  getToolFiltering: () => ToolFilteringMode = () => "allowed",
143
151
  getInheritedTools: () => InheritedToolSource = () => ({ tools: [], activeNames: [] }),
144
- ): DriverFactory {
152
+ ): DriverFactory & {
153
+ resolveAgentSettings(type: AgentType, parentPath: string): ResolvedAgentSettings;
154
+ } {
145
155
  // Keep resolved settings even after disposal: descendants inherit settings, not the caller's history.
146
156
  const resolved = new Map<string, { provider: string; id: string; thinking: ThinkingLevel }>();
147
- return async (options) => {
157
+ const normalizeScopedModels = (
158
+ scopedModels: ExtensionContext["scopedModels"] | null | undefined,
159
+ ): readonly ScopedModel[] => scopedModels ?? [];
160
+ const availableModelCandidates = () =>
161
+ getRootContext()
162
+ .modelRegistry.getAvailable()
163
+ .map((model) => ({ model }));
164
+ const availableScopedModels = (scopedModels: readonly ScopedModel[]) => {
165
+ const available = new Set(availableModelCandidates().map(({ model }) => modelIdentity(model)));
166
+ return scopedModels.filter(({ model }) => available.has(modelIdentity(model)));
167
+ };
168
+ const selectTypeModelPreference = (
169
+ type: AgentType,
170
+ candidates: readonly { model: { provider: string; id: string } }[],
171
+ filtering: boolean,
172
+ ) => {
173
+ try {
174
+ return selectPreferredModel(type, candidates, filtering);
175
+ } catch (error) {
176
+ if (
177
+ filtering &&
178
+ candidates.length === 0 &&
179
+ error instanceof Error &&
180
+ !error.message.includes("[]")
181
+ ) {
182
+ const message = `${error.message} Current /scoped-models scope: [].`;
183
+ throw error instanceof ModelPreferenceError
184
+ ? new ModelPreferenceError(message, error.scopedModelFiltering)
185
+ : new Error(message);
186
+ }
187
+ throw error;
188
+ }
189
+ };
190
+ // Discovery and new/restored drivers share model selection and thinking inheritance.
191
+ const resolveInitialSettings = (
192
+ type: AgentType,
193
+ parentPath?: string | null,
194
+ restored?: ReturnType<SessionManager["buildSessionContext"]>,
195
+ ) => {
196
+ const ctx = getRootContext();
197
+ const parent = parentPath
198
+ ? resolved.get(`${ctx.sessionManager.getSessionId()}:${parentPath}`)
199
+ : undefined;
200
+ const mode = getModelSelection();
201
+ const preferences = mode === "use-current" ? undefined : getModelPreferences(type);
202
+ let provider = parent?.provider ?? ctx.model?.provider;
203
+ let id = parent?.id ?? ctx.model?.id;
204
+ if (mode === "use-current") {
205
+ provider = ctx.model?.provider;
206
+ id = ctx.model?.id;
207
+ } else if (preferences !== undefined) {
208
+ const filtering = mode === "pick-first-scoped";
209
+ const candidates = filtering
210
+ ? availableScopedModels(normalizeScopedModels(ctx.scopedModels))
211
+ : availableModelCandidates();
212
+ ({ provider, id } = parseModelIdentity(
213
+ selectTypeModelPreference(type, candidates, filtering)!,
214
+ ));
215
+ } else if (restored?.model) {
216
+ provider = restored.model.provider;
217
+ id = restored.model.modelId;
218
+ }
219
+ const savedThinking =
220
+ restored && THINKING_LEVELS.includes(restored.thinkingLevel as ThinkingLevel)
221
+ ? (restored.thinkingLevel as ThinkingLevel)
222
+ : undefined;
223
+ const thinkingLevel =
224
+ savedThinking ?? type.thinkingLevel ?? parent?.thinking ?? ctx.thinkingLevel ?? "off";
225
+ return { provider, id, thinkingLevel };
226
+ };
227
+ const resolveAgentSettings = (type: AgentType, parentPath: string): ResolvedAgentSettings => {
228
+ const ctx = getRootContext();
229
+ const { provider, id, thinkingLevel } = resolveInitialSettings(type, parentPath);
230
+ const model =
231
+ normalizeScopedModels(ctx.scopedModels).find(
232
+ ({ model }) => model.provider === provider && model.id === id,
233
+ )?.model ?? (provider && id ? ctx.modelRegistry.find(provider, id) : undefined);
234
+ if (!model)
235
+ throw new Error(
236
+ `Subagent model ${provider ?? "(unset)"}/${id ?? "(unset)"} is unavailable; select a physical model in the root or agent type`,
237
+ );
238
+ if (model.api === "pi-virtual")
239
+ throw new Error(
240
+ `Virtual model ${provider}/${id} cannot be reproduced through the public registry API. Set this agent type's model to a physical provider/model-id.`,
241
+ );
242
+ return { model: modelIdentity(model), thinkingLevel: clampThinkingLevel(model, thinkingLevel) };
243
+ };
244
+ const createDriver: DriverFactory = async (options) => {
148
245
  options.signal.throwIfAborted();
149
246
  const ctx = getRootContext();
150
247
  // Tool policy is a startup snapshot; retained live sessions keep their selected set.
@@ -213,59 +310,22 @@ export function createDriverFactory(
213
310
  }
214
311
  }
215
312
  }
216
- const parent = options.parentPath ? resolved.get(`${rootId}:${options.parentPath}`) : undefined;
217
313
  const restored = options.sessionFile ? sessionManager.buildSessionContext() : undefined;
218
314
  const modelSelection = getModelSelection();
219
315
  // Use Current ignores definition preferences, including for restored/nested sessions.
220
316
  const modelPreferences =
221
317
  modelSelection === "use-current" ? undefined : getModelPreferences(options.type);
222
- const normalizeScopedModels = (
223
- scopedModels: ExtensionContext["scopedModels"] | null | undefined,
224
- ): readonly ScopedModel[] => scopedModels ?? [];
225
318
  const filteringEnabled = () => getModelSelection() === "pick-first-scoped";
226
319
  const selectModelPreference = (
227
320
  candidates: readonly { model: { provider: string; id: string } }[],
228
321
  filtering = filteringEnabled(),
229
- ) => {
230
- try {
231
- return selectPreferredModel(options.type, candidates, filtering);
232
- } catch (error) {
233
- if (
234
- filtering &&
235
- candidates.length === 0 &&
236
- error instanceof Error &&
237
- !error.message.includes("[]")
238
- )
239
- throw new Error(`${error.message} Current /scoped-models scope: [].`);
240
- throw error;
241
- }
242
- };
243
- const availableModelCandidates = () =>
244
- getRootContext()
245
- .modelRegistry.getAvailable()
246
- .map((model) => ({ model }));
247
- const availableScopedModels = (scopedModels: readonly ScopedModel[]) => {
248
- const available = new Set(
249
- availableModelCandidates().map(({ model }) => modelIdentity(model)),
250
- );
251
- return scopedModels.filter(({ model }) => available.has(modelIdentity(model)));
252
- };
322
+ ) => selectTypeModelPreference(options.type, candidates, filtering);
253
323
  const initialScopedModels = normalizeScopedModels(ctx.scopedModels);
254
- let provider = parent?.provider ?? ctx.model?.provider;
255
- let id = parent?.id ?? ctx.model?.id;
256
- if (modelSelection === "use-current") {
257
- provider = ctx.model?.provider;
258
- id = ctx.model?.id;
259
- } else if (modelPreferences !== undefined) {
260
- const filtering = modelSelection === "pick-first-scoped";
261
- const candidates = filtering
262
- ? availableScopedModels(initialScopedModels)
263
- : availableModelCandidates();
264
- ({ provider, id } = parseModelIdentity(selectModelPreference(candidates, filtering)!));
265
- } else if (restored?.model) {
266
- provider = restored.model.provider;
267
- id = restored.model.modelId;
268
- }
324
+ const { provider, id, thinkingLevel } = resolveInitialSettings(
325
+ options.type,
326
+ options.parentPath,
327
+ restored,
328
+ );
269
329
  options.signal.throwIfAborted();
270
330
  const runtime = await ModelRuntime.create({
271
331
  authPath: path.join(agentDir, "auth.json"),
@@ -316,12 +376,6 @@ export function createDriverFactory(
316
376
  return runtimeModel;
317
377
  };
318
378
  const model = await resolveRuntimeModel(provider, id, initialScopedModels);
319
- const savedThinking =
320
- restored && THINKING_LEVELS.includes(restored.thinkingLevel as ThinkingLevel)
321
- ? (restored.thinkingLevel as ThinkingLevel)
322
- : undefined;
323
- const thinkingLevel =
324
- savedThinking ?? options.type.thinkingLevel ?? parent?.thinking ?? ctx.thinkingLevel ?? "off";
325
379
  const inherited = getInheritedTools();
326
380
  const localNames = new Set([...BUILTINS, ...options.tools.map((tool) => tool.name)]);
327
381
  const externalTools = inherited.tools.filter((tool) => !localNames.has(tool.name));
@@ -725,4 +779,5 @@ export function createDriverFactory(
725
779
  },
726
780
  };
727
781
  };
782
+ return Object.assign(createDriver, { resolveAgentSettings });
728
783
  }
package/src/orch/tools.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Type } from "typebox";
2
2
  import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
3
- import { getModelPreferences } from "../prefs/models.ts";
4
3
  import type { ThreadManager } from "./manager.ts";
5
- import type { AgentType, ThreadView } from "../types.ts";
4
+ import { ModelPreferenceError } from "../prefs/models.ts";
5
+ import type { AgentType, ResolvedAgentSettings, ThreadView } from "../types.ts";
6
6
 
7
7
  const path = Type.String({ description: "Absolute agent path, or name relative to the caller" });
8
8
  const text = Type.String({ minLength: 1 });
@@ -23,6 +23,7 @@ export function agentTools(
23
23
  getManager: () => ThreadManager,
24
24
  caller: string,
25
25
  getTypes: () => AgentType[],
26
+ resolveSettings: (type: AgentType) => ResolvedAgentSettings,
26
27
  ): ToolDefinition[] {
27
28
  const threads = () => getManager().scope(caller);
28
29
  const make = (
@@ -40,22 +41,43 @@ export function agentTools(
40
41
  return [
41
42
  make(
42
43
  "agent_types",
43
- "List current agent types and their task descriptions. Reflects configuration reloads; call this before choosing a type. modelSuggestions are advisory display names, not model pins.",
44
+ "List agent names, descriptions, resolved models and thinking levels for new children of this caller. Reflects current configuration; call before choosing a type. Other parent paths may inherit different settings.",
44
45
  Type.Object({}),
45
- () =>
46
- result(
47
- getTypes().map(
48
- ({ name, description, thinkingLevel, color, icon, modelSuggestions, ...type }) => ({
46
+ () => {
47
+ const entries = getTypes().map((type) => {
48
+ const { name, description } = type;
49
+ try {
50
+ return { name, description, ...resolveSettings(type) };
51
+ } catch (error) {
52
+ return {
49
53
  name,
50
54
  description,
51
- models: getModelPreferences(type),
52
- modelSuggestions: modelSuggestions === undefined ? undefined : [...modelSuggestions],
53
- thinkingLevel,
54
- color,
55
- icon,
56
- }),
57
- ),
58
- ),
55
+ error:
56
+ error instanceof ModelPreferenceError
57
+ ? error.summary
58
+ : error instanceof Error
59
+ ? error.message
60
+ : String(error),
61
+ };
62
+ }
63
+ });
64
+ return {
65
+ content: [
66
+ {
67
+ type: "text" as const,
68
+ text:
69
+ entries
70
+ .map((entry) =>
71
+ "error" in entry
72
+ ? `${entry.name} (unavailable): ${entry.description}\n ${entry.error}`
73
+ : `${entry.name} (${entry.model}, thinking: ${entry.thinkingLevel}): ${entry.description}`,
74
+ )
75
+ .join("\n") || "No agent types available.",
76
+ },
77
+ ],
78
+ details: entries,
79
+ };
80
+ },
59
81
  ),
60
82
  make(
61
83
  "agent_spawn",