pi-subagent-manager 0.12.0 → 0.14.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. `/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 (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, 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).
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
 
@@ -11,6 +11,41 @@ An agent type is one Markdown file: YAML frontmatter on top, system prompt below
11
11
 
12
12
  Precedence: **project > user > bundled**. A file with the same `name` as a bundled agent replaces it.
13
13
 
14
+ ## Tweak settings or fork the agent?
15
+
16
+ Two ways to customize a bundled agent. Pick one per agent — a scope (user or
17
+ project) cannot hold both a `.md` and a `.yml` for the same name.
18
+
19
+ | | Tweak settings (`<name>.yml`) | Fork agent (`<name>.md`) |
20
+ |---|---|---|
21
+ | What it is | Settings-only override merged on top of the bundled definition | Full copy that replaces the bundled definition |
22
+ | System prompt | Stays bundled; you keep receiving prompt updates | Copied; you own it, bundled prompt updates no longer apply |
23
+ | Editable | Settings (models, tools, thinking, color, icon, description) | Everything, including name and system prompt |
24
+ | File | Plain YAML mapping, no frontmatter, no Markdown body | YAML frontmatter on top, system prompt below |
25
+
26
+ `~/.pi/agent/subagent-manager/agents/coder.yml`:
27
+
28
+ ```yaml
29
+ name: coder
30
+ thinkingLevel: low
31
+ tools:
32
+ allow:
33
+ - read
34
+ - grep
35
+ - agent_update
36
+ - agent_pause
37
+ ```
38
+
39
+ Only listed fields override; everything else follows the base definition, so
40
+ untouched settings keep tracking bundled updates. Set an optional field to
41
+ `null` to clear it back to the base state (e.g. `icon: null`). `name`, when
42
+ present, must match the filename. Overrides need a base agent to merge onto —
43
+ a `.yml` without a matching bundled or forked definition is rejected.
44
+
45
+ In `/agents types`, editing a bundled agent asks you to pick one mode first,
46
+ and settings stay locked until you choose. Overrides cannot rename the agent
47
+ or edit the system prompt — fork it instead.
48
+
14
49
  These are the only locations read. Other packages' `~/.pi/agent/agents` or `.pi/agents` are ignored — use [`/agents import`](importing-agents.md) for those.
15
50
 
16
51
  ## 2. Write the file
package/docs/settings.md CHANGED
@@ -50,16 +50,16 @@ Controls the subagent status display above the input box. Choose **Status Widget
50
50
 
51
51
  | Option | Display |
52
52
  | ------------------ | ------- |
53
- | `full` (default) | The existing multi-line tree with agent details, activity and navigation hints. |
53
+ | `full` (default) | A compact tree with one row per agent, task/state, metrics and navigation hints. |
54
54
  | `minimal` | One line of theme-colored status counts plus cumulative input `↑` / output `↓` tokens for agents currently starting or running. |
55
55
 
56
- Minimal mode groups starting agents with running agents and excludes the main conversation. Token totals exclude completed, stopped, failed and paused agents. The fullscreen tree remains available via `/agents tree` in either mode.
56
+ Minimal mode groups starting agents with running agents and excludes the main conversation. Token totals exclude completed, stopped, failed and paused agents. The fullscreen tree remains available via `/agents tree` in either mode. In full mode, press **Right (→)** at the end of the main draft (or in an empty input) to collapse to one line for this session only, without saving preferences. Session startup/switch/reload restores the configured mode. **Left (←)** at the start of the draft still opens the full dialog while agents are active.
57
57
 
58
58
  ## [labs] Nerd Font icons (`nerdFontIcons`)
59
59
 
60
60
  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
61
 
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. Types without icons remain text-only; turning it off restores text-only labels without removing configured icons. The minimal widget remains an aggregate count, with no per-agent icons. Saved settings apply immediately to newly rendered widgets and dialogs.
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
63
 
64
64
  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
65
 
@@ -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",
@@ -68,11 +73,13 @@ The fullscreen watcher renders steer and agent messages (including thinking) as
68
73
  - **Ctrl+R** (or **r** with transcript controls focused) retries an unavailable observation without starting a turn. Starting threads are watchable; stopped/completed threads remain readable.
69
74
  - Frames are sanitized, viewport-bounded and coalesced during bursts. Exit, root replacement and shutdown release observers/timers. Streaming deltas never enter persisted thread events.
70
75
 
71
- #### Left-arrow entry
76
+ #### Arrow-key shortcuts
72
77
 
73
78
  While any subagent is **starting or running**, press physical **Left (←)** at the beginning of the main draft (or in an empty input) to open the subagent browser. With no active subagents, or elsewhere in the draft, Left retains normal cursor movement. `/agents tree` remains available regardless of agent activity. Down is always native editing/history navigation. Autocomplete, jumps, paste and configured shortcuts take precedence. Navigating preserves the main draft/cursor and does not require the root to be idle.
74
79
 
75
- Left-arrow entry is enabled by default in the TUI; `/agents tree` remains available everywhere. Pi has one custom-editor slot: installation is skipped if another factory owns it or an existing draft is nonempty, since the host cannot transfer cursor/undo/expanded-paste state. Load order can still let a later editor replace ours. Initial startup uses Pi's history hydration; replacement installations seed history once. Session-tree rebuilds keep the existing editor instance.
80
+ Press physical **Right (→)** at the end of the main draft (or in an empty input) to collapse the full widget to a single status line for this session. This does not save settings or change the configured **Status Widget** mode. Refreshes, agent resumes, new main turns and session-tree navigation keep it collapsed; starting, switching or reloading a session restores the configured mode. Left still opens the full dialog while subagents are active, without expanding the widget. Elsewhere in the draft Right retains normal cursor movement; autocomplete, jumps, paste and shortcuts take precedence.
81
+
82
+ Arrow-key shortcuts are enabled by default in the TUI; `/agents tree` remains available everywhere. Pi has one custom-editor slot: installation is skipped if another factory owns it or an existing draft is nonempty, since the host cannot transfer cursor/undo/expanded-paste state. Load order can still let a later editor replace ours. Initial startup uses Pi's history hydration; replacement installations seed history once. Session-tree rebuilds keep the existing editor instance.
76
83
 
77
84
  While navigation is open, the host fullscreen search shortcut is temporarily disabled through public keybindings to avoid stacking a second host overlay. The prior binding owner is restored only if no other extension replaced it. **Known host limitation:** if an unrelated extension stacks another overlay above navigation, Pi's custom-UI completion can close the newer overlay instead. Avoid concurrent extension-owned overlays; a host identity-targeted completion API is needed to remove this limitation. No private host access or unsupported overlay-lifecycle workaround is used.
78
85
 
@@ -85,15 +92,16 @@ The widget above the input editor has two display modes, selected with **Status
85
92
  - **Full** (default): the existing compact tree, at most twelve lines.
86
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.
87
94
 
88
- 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.
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.
89
96
 
90
97
  In full mode:
91
98
 
92
- - Each row: colored type pill, path, state, task, active time, input `↑` / output `↓` tokens.
93
- - A second, indented line shows latest activity.
99
+ - One row per agent: colored type pill, path, state, task, active time, input `↑` / output `↓` tokens.
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`.
94
101
  - Active branches are shown first; the most recent agents within each state are preferred when previews overflow. Overflow is counted, not listed.
95
102
  - Time freezes while paused and resumes on continue.
96
- - A small status strip below the previews shows the running count (including starting agents) and **Press ← to open subagent browser**, including when agents overflow. Full and minimal modes show the hint only while subagents are starting or running. RPC output omits the keyboard hint.
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.
104
+ - 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.
97
105
 
98
106
  ### Interrupts and stopping agents
99
107
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.12.0",
3
+ "version": "0.14.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,8 @@ 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>();
55
+ let widgetCollapsed = false;
54
56
  let summaryRunning = false;
55
57
  let suspendingSummaries = false;
56
58
  let summaryTimer: ReturnType<typeof setTimeout> | undefined;
@@ -95,6 +97,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
95
97
  (thread.state === "starting" || thread.state === "running")),
96
98
  openTree: () => manager && context
97
99
  ? navigation.open(context, manager.scope("/root"), undefined, limits.nerdFontIcons) : undefined,
100
+ canCollapse: () => manager !== undefined && context?.mode === "tui" &&
101
+ limits.subagentMode !== "off" && !navigation.isOpen && !widgetCollapsed &&
102
+ limits.widgetMode === "full" && widgetThreads().some((thread) => thread.path !== "/root"),
103
+ collapseWidget: () => {
104
+ widgetCollapsed = true;
105
+ if (context) refreshWidget(context);
106
+ },
98
107
  onError: (error) => context?.ui.notify(
99
108
  error instanceof Error ? error.message : String(error), "error"),
100
109
  });
@@ -130,6 +139,12 @@ export default function piSubagent(pi: ExtensionAPI): void {
130
139
  if (!manager) throw new Error("Subagent threads are not initialized; start a Pi session first");
131
140
  return manager;
132
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
+ });
133
148
  const requireContext = () => {
134
149
  if (!context) throw new Error("No active Pi session");
135
150
  return context;
@@ -281,7 +296,22 @@ export default function piSubagent(pi: ExtensionAPI): void {
281
296
  }
282
297
  };
283
298
 
284
- 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");
285
315
  let toolsEnabled: boolean | undefined;
286
316
  const syncTools = () => {
287
317
  const enabled = limits.subagentMode !== "off";
@@ -304,9 +334,18 @@ export default function piSubagent(pi: ExtensionAPI): void {
304
334
  const refreshWidget = (ctx: ExtensionContext) => {
305
335
  if (limits.subagentMode === "off") {
306
336
  if (ctx.hasUI) ctx.ui.setWidget("pi-subagent", undefined);
307
- } else updateWidget(ctx, requireManager().list(), limits.widgetMode, limits.nerdFontIcons, rootTurnEnded);
337
+ } else updateWidget(ctx, widgetThreads(), widgetCollapsed ? "minimal" : limits.widgetMode,
338
+ limits.nerdFontIcons, rootTurnEnded);
308
339
  };
309
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
+ }
310
349
  rootTurnEnded = false;
311
350
  if (manager) refreshWidget(ctx);
312
351
  });
@@ -344,6 +383,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
344
383
  inheritedTools.reset();
345
384
  context = ctx;
346
385
  rootTurnEnded = false;
386
+ if (installEditor) {
387
+ widgetCollapsed = false;
388
+ hiddenWidgetThreads.clear();
389
+ }
347
390
  store = new ConfigStore({
348
391
  cwd: ctx.cwd,
349
392
  agentDir: getAgentDir(),
@@ -352,17 +395,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
352
395
  persistenceSignature = "";
353
396
  const settingsDiagnostics = loadLimits(ctx);
354
397
  syncTools();
398
+ driverFactory = makeDriverFactory();
355
399
  const instance = new ThreadManager({
356
400
  ...limits,
357
- createDriver: createDriverFactory(
358
- requireContext,
359
- () => limits.modelSelection,
360
- () => limits.toolFiltering,
361
- () => inheritedTools.snapshot(),
362
- ),
401
+ createDriver: driverFactory,
363
402
  rootSnapshot: () => buildSessionContext(requireContext().sessionManager.getBranch()).messages,
364
403
  getType: (name) => store.get(name),
365
- toolsFor: (path) => agentTools(requireManager, path, () => store.list()),
404
+ toolsFor,
366
405
  onEvent: (event) => {
367
406
  if (token !== generation) return;
368
407
  refreshWidget(requireContext());
@@ -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",