pi-subagent-manager 0.6.0 → 0.8.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.
@@ -0,0 +1,64 @@
1
+ # Tools and UI
2
+
3
+ ## Model-facing tools
4
+
5
+ | Tool | Purpose |
6
+ | -------------- | ---------------------------------------------------- |
7
+ | `agent_types` | List types and what they're for |
8
+ | `agent_spawn` | Start `{path, type, task, wait?}`. Waits by default. |
9
+ | `agent_wait` | Wait for settlement; optional `timeoutMs` |
10
+ | `agent_steer` | Send `{path, message}`; queues input or resumes |
11
+ | `agent_status` | Inspect one path or list visible threads |
12
+ | `agent_update` | Child: report progress |
13
+ | `agent_pause` | Child: pause without an answer |
14
+ | `agent_stop` | Cancel a descendant and its subtree |
15
+ | `agent_output` | Page through long final answers by character offset |
16
+
17
+ ```json
18
+ {
19
+ "path": "controller-security-research",
20
+ "type": "architect",
21
+ "task": "Investigate controller security and plan the change",
22
+ "wait": false
23
+ }
24
+ ```
25
+
26
+ Then `agent_wait` or `agent_status` on `/root/controller-security-research`.
27
+
28
+ ## Parallel and nested work
29
+
30
+ - Launch **all independent siblings with `wait: false`, then wait**. Spawning one foreground child and waiting before the next is sequential.
31
+ - Nesting works the same way: `/root` launches `team-a` and `team-b`; each launches its own workers.
32
+ - Only `architect` delegates among bundled types. A custom coordinator needs `agent_spawn` and `agent_wait` in `tools.allow`.
33
+ - Limits are shared across the tree — see [settings](settings.md#max-levels-maxlevels).
34
+
35
+ ## Commands
36
+
37
+ | Command | Does |
38
+ | ----------------------------- | ---------------------------------------------------------------------------------- |
39
+ | `/agents`, `/agents settings` | [Settings](settings.md) dialog. **Agent definitions** jumps to the type editor. |
40
+ | `/agents types` | Type browser and editor — see [custom agents](custom-agents.md#editing-in-the-tui) |
41
+ | `/agents tree [path]` | Live full tree; optional path preselects. `/agents status` is an alias. |
42
+ | `/agents import` | [Import picker](importing-agents.md) |
43
+ | `/agents reload` | Reload definitions and settings; show diagnostics |
44
+
45
+ ### `/agents tree` keys
46
+
47
+ | Key | Action |
48
+ | ----------- | ----------------- |
49
+ | ↑↓ | Select |
50
+ | ←→ | Collapse / expand |
51
+ | PgUp / PgDn | Scroll |
52
+ | Enter | Inspect thread |
53
+ | Esc | Close |
54
+
55
+ Refreshes every second and keeps your selection.
56
+
57
+ ## Agents widget
58
+
59
+ A compact tree above the input editor, at most ten lines.
60
+
61
+ - Each row: colored type pill, path, state, task, active time, input `↑` / output `↓` tokens.
62
+ - A second, indented line shows latest activity.
63
+ - Active branches are shown first; overflow is counted, not listed.
64
+ - Time freezes while paused and resumes on continue.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
package/src/index.ts CHANGED
@@ -9,6 +9,7 @@ import { loadManagerSettings } from "./prefs/settings.ts";
9
9
  import { configureAgents } from "./ui/settings-ui.ts";
10
10
  import { showAgentStatus, showAgentTree } from "./ui/status-ui.ts";
11
11
  import { createDriverFactory } from "./orch/runtime.ts";
12
+ import { createInheritedToolSource } from "./orch/inherited-tools.ts";
12
13
  import { subagentPrompt } from "./orch/prompt.ts";
13
14
  import { agentTools } from "./orch/tools.ts";
14
15
  import { editAgentTypes, updateWidget } from "./ui/ui.ts";
@@ -24,6 +25,7 @@ type RootNotification = {
24
25
 
25
26
  export default function piSubagent(pi: ExtensionAPI): void {
26
27
  let context: ExtensionContext | undefined;
28
+ const inheritedTools = createInheritedToolSource(pi);
27
29
  let store = new ConfigStore({
28
30
  cwd: process.cwd(),
29
31
  agentDir: getAgentDir(),
@@ -181,8 +183,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
181
183
  ...tool,
182
184
  // Hidden tools are neither model-visible nor discoverable/callable via codemode.
183
185
  exposure: enabled ? "direct" : "hidden",
186
+ prepareLoadout: inheritedTools.captureLoadout,
184
187
  execute: (...args) => {
185
188
  if (limits.subagentMode === "off") throw new Error("Subagent Mode is off");
189
+ inheritedTools.captureContext(args[4]);
186
190
  return tool.execute(...args);
187
191
  },
188
192
  });
@@ -213,6 +217,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
213
217
  const token = ++generation;
214
218
  // session_start already belongs to the replacement session: never append the old registry here.
215
219
  if (manager) await manager.shutdown();
220
+ inheritedTools.reset();
216
221
  context = ctx;
217
222
  store = new ConfigStore({
218
223
  cwd: ctx.cwd,
@@ -224,7 +229,12 @@ export default function piSubagent(pi: ExtensionAPI): void {
224
229
  syncTools();
225
230
  const instance = new ThreadManager({
226
231
  ...limits,
227
- createDriver: createDriverFactory(requireContext, () => limits.scopedModelFiltering),
232
+ createDriver: createDriverFactory(
233
+ requireContext,
234
+ () => limits.modelSelection,
235
+ () => limits.toolFiltering,
236
+ () => inheritedTools.snapshot(),
237
+ ),
228
238
  rootSnapshot: () => buildSessionContext(requireContext().sessionManager.getBranch()).messages,
229
239
  getType: (name) => store.get(name),
230
240
  toolsFor: (path) => agentTools(requireManager, path, () => store.list()),
@@ -0,0 +1,84 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionToolContext,
4
+ ToolDefinition,
5
+ ToolLoadout,
6
+ } from "@earendil-works/pi-coding-agent";
7
+
8
+ /** A snapshot of the root's reachable tools, without loading its extensions again. */
9
+ export interface InheritedToolSource {
10
+ tools: ToolDefinition[];
11
+ activeNames: string[];
12
+ }
13
+
14
+ /**
15
+ * Capture the public loadout API and a root execution bridge. Keep the bridge alive for
16
+ * detached children, but always pass their signal rather than the spawning call's signal.
17
+ * Built-ins and manager controls are replaced with child-local implementations by runtime.
18
+ */
19
+ export function createInheritedToolSource(pi: ExtensionAPI) {
20
+ let loadout: ToolLoadout | undefined;
21
+ let context: ExtensionToolContext | undefined;
22
+ return {
23
+ captureLoadout(next: ToolLoadout) {
24
+ loadout = next;
25
+ return undefined;
26
+ },
27
+ captureContext(next: ExtensionToolContext) {
28
+ context = next;
29
+ },
30
+ reset() {
31
+ // session_start is emitted after the replacement loadout is prepared; do not
32
+ // discard that fresh snapshot (or an unchanged loadout on /tree).
33
+ context = undefined;
34
+ },
35
+ snapshot(): InheritedToolSource {
36
+ if (!loadout) return { tools: [], activeNames: [] };
37
+ const rootContext = context;
38
+ const callable = new Set(loadout.callable.map((tool) => tool.name));
39
+ const active = new Set(loadout.declared.map((tool) => tool.name));
40
+ const info = new Map(pi.getAllTools().map((tool) => [tool.name, tool]));
41
+ const tools: ToolDefinition[] = [];
42
+ for (const tool of loadout.registered) {
43
+ const exposure = loadout.getExposure(tool.name);
44
+ // Inactive direct tools and hidden tools are not available in the root either.
45
+ if (!callable.has(tool.name) && !active.has(tool.name)) continue;
46
+ if (exposure === "hidden") continue;
47
+ const metadata = info.get(tool.name);
48
+ tools.push({
49
+ ...tool,
50
+ // The root execution pipeline applies argument preparation. Running it in
51
+ // the child too would corrupt non-idempotent preparation shims.
52
+ prepareArguments: undefined,
53
+ label: tool.label,
54
+ exposure,
55
+ namespace: loadout.getNamespace(tool.name),
56
+ annotations: metadata?.annotations,
57
+ promptGuidelines: metadata?.promptGuidelines,
58
+ defaultActive: active.has(tool.name),
59
+ async execute(_id, args, signal, onUpdate) {
60
+ if (!callable.has(tool.name)) {
61
+ // The SDK rejects nested model-only execution. Calling its captured
62
+ // wrapper directly would bypass root permission/result hooks. Known
63
+ // SDK orchestrators are instead recreated locally by runtime.
64
+ throw new Error(
65
+ `Cannot safely inherit model-only tool ${tool.name}: the SDK does not ` +
66
+ "provide a hook-preserving execution bridge. Run it in the main session.",
67
+ );
68
+ }
69
+ const bridge = rootContext ?? context;
70
+ if (!bridge) {
71
+ throw new Error(
72
+ "Inherited tool execution needs a main-session agent_* tool call first. " +
73
+ "Use agent_steer to resume this child instead of the thread dialog.",
74
+ );
75
+ }
76
+ const outcome = await bridge.executeTool(tool.name, args, { signal, onUpdate });
77
+ return { ...outcome.result, isError: outcome.isError };
78
+ },
79
+ });
80
+ }
81
+ return { tools, activeNames: [...active] };
82
+ },
83
+ };
84
+ }
@@ -4,6 +4,8 @@ import { existsSync } from "node:fs";
4
4
  import { mkdir, readFile, realpath } from "node:fs/promises";
5
5
  import {
6
6
  createAgentSession,
7
+ createCodemodeExtension,
8
+ createToolSearchExtension,
7
9
  DefaultResourceLoader,
8
10
  getAgentDir,
9
11
  ModelRuntime,
@@ -19,6 +21,8 @@ import {
19
21
  DurableMailbox,
20
22
  } from "./mailbox.ts";
21
23
  import { selectTools } from "../prefs/config.ts";
24
+ import type { InheritedToolSource } from "./inherited-tools.ts";
25
+ import type { ModelSelectionMode, ToolFilteringMode } from "../prefs/settings.ts";
22
26
  import { modelIdentity, getModelPreferences, selectPreferredModel } from "../prefs/models.ts";
23
27
  import {
24
28
  THINKING_LEVELS,
@@ -130,16 +134,20 @@ async function assertAcceptedSessionFile(
130
134
  }
131
135
  }
132
136
 
133
- /** Isolated SDK sessions; neither external extensions nor the CLI's MCP factories are loaded. */
137
+ /** Isolated SDK sessions with filtered root tool bridges, not reloaded root extensions. */
134
138
  export function createDriverFactory(
135
139
  getRootContext: () => ExtensionContext,
136
- getScopedModelFiltering: () => boolean = () => true,
140
+ getModelSelection: () => ModelSelectionMode = () => "pick-first-scoped",
141
+ getToolFiltering: () => ToolFilteringMode = () => "allowed",
142
+ getInheritedTools: () => InheritedToolSource = () => ({ tools: [], activeNames: [] }),
137
143
  ): DriverFactory {
138
144
  // Keep resolved settings even after disposal: descendants inherit settings, not the caller's history.
139
145
  const resolved = new Map<string, { provider: string; id: string; thinking: ThinkingLevel }>();
140
146
  return async (options) => {
141
147
  options.signal.throwIfAborted();
142
148
  const ctx = getRootContext();
149
+ // Tool policy is a startup snapshot; retained live sessions keep their selected set.
150
+ const toolFiltering = getToolFiltering();
143
151
  const rootId = ctx.sessionManager.getSessionId();
144
152
  if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(rootId))
145
153
  throw new Error("Unsafe root session id for subagent storage");
@@ -205,11 +213,14 @@ export function createDriverFactory(
205
213
  }
206
214
  const parent = options.parentPath ? resolved.get(`${rootId}:${options.parentPath}`) : undefined;
207
215
  const restored = options.sessionFile ? sessionManager.buildSessionContext() : undefined;
208
- const modelPreferences = getModelPreferences(options.type);
216
+ const modelSelection = getModelSelection();
217
+ // Use Current ignores definition preferences, including for restored/nested sessions.
218
+ const modelPreferences =
219
+ modelSelection === "use-current" ? undefined : getModelPreferences(options.type);
209
220
  const normalizeScopedModels = (
210
221
  scopedModels: ExtensionContext["scopedModels"] | null | undefined,
211
222
  ): readonly ScopedModel[] => scopedModels ?? [];
212
- const filteringEnabled = getScopedModelFiltering;
223
+ const filteringEnabled = () => getModelSelection() === "pick-first-scoped";
213
224
  const selectModelPreference = (
214
225
  candidates: readonly { model: { provider: string; id: string } }[],
215
226
  filtering = filteringEnabled(),
@@ -228,13 +239,26 @@ export function createDriverFactory(
228
239
  }
229
240
  };
230
241
  const availableModelCandidates = () =>
231
- ctx.modelRegistry.getAvailable().map((model) => ({ model }));
242
+ getRootContext()
243
+ .modelRegistry.getAvailable()
244
+ .map((model) => ({ model }));
245
+ const availableScopedModels = (scopedModels: readonly ScopedModel[]) => {
246
+ const available = new Set(
247
+ availableModelCandidates().map(({ model }) => modelIdentity(model)),
248
+ );
249
+ return scopedModels.filter(({ model }) => available.has(modelIdentity(model)));
250
+ };
232
251
  const initialScopedModels = normalizeScopedModels(ctx.scopedModels);
233
252
  let provider = parent?.provider ?? ctx.model?.provider;
234
253
  let id = parent?.id ?? ctx.model?.id;
235
- if (modelPreferences !== undefined) {
236
- const filtering = filteringEnabled();
237
- const candidates = filtering ? initialScopedModels : availableModelCandidates();
254
+ if (modelSelection === "use-current") {
255
+ provider = ctx.model?.provider;
256
+ id = ctx.model?.id;
257
+ } else if (modelPreferences !== undefined) {
258
+ const filtering = modelSelection === "pick-first-scoped";
259
+ const candidates = filtering
260
+ ? availableScopedModels(initialScopedModels)
261
+ : availableModelCandidates();
238
262
  ({ provider, id } = parseModelIdentity(selectModelPreference(candidates, filtering)!));
239
263
  } else if (restored?.model) {
240
264
  provider = restored.model.provider;
@@ -296,11 +320,23 @@ export function createDriverFactory(
296
320
  : undefined;
297
321
  const thinkingLevel =
298
322
  savedThinking ?? options.type.thinkingLevel ?? parent?.thinking ?? ctx.thinkingLevel ?? "off";
299
- const toolNames = selectTools(options.type.tools, [
300
- ...BUILTINS,
301
- ...options.tools.map((tool) => tool.name),
302
- ]);
323
+ const inherited = getInheritedTools();
324
+ const localNames = new Set([...BUILTINS, ...options.tools.map((tool) => tool.name)]);
325
+ const externalTools = inherited.tools.filter((tool) => !localNames.has(tool.name));
326
+ const toolNames = selectTools(
327
+ options.type.tools,
328
+ [...localNames, ...externalTools.map((tool) => tool.name)],
329
+ toolFiltering,
330
+ );
303
331
  const allowed = new Set(toolNames);
332
+ const rootActive = new Set(inherited.activeNames);
333
+ // Preserve deferred/codemode exposure rather than flooding model declarations with MCP tools.
334
+ const activeToolNames = toolNames.filter(
335
+ (name) => localNames.has(name) || rootActive.has(name) || options.type.tools?.allow?.includes(name) && toolFiltering === "allowed",
336
+ );
337
+ const customTools = [...options.tools, ...externalTools].filter(
338
+ (tool) => allowed.has(tool.name) && tool.name !== "codemode" && tool.name !== "tool_search",
339
+ );
304
340
  const settingsManager = SettingsManager.inMemory({ cacheWarming: "off" });
305
341
  let parkQueue = () => {};
306
342
  const pauseBoundary = () => {
@@ -333,6 +369,10 @@ export function createDriverFactory(
333
369
  ].join("\n\n"),
334
370
  appendSystemPromptOverride: () => [],
335
371
  extensionFactories: [
372
+ // These orchestrators must see the CHILD loadout. Forwarding root codemode would
373
+ // let scripts discover/call tools outside the child's allow/block policy.
374
+ ...(allowed.has("codemode") ? [createCodemodeExtension()] : []),
375
+ ...(allowed.has("tool_search") ? [createToolSearchExtension()] : []),
336
376
  (pi) => {
337
377
  pi.on("turn_end", pauseBoundary);
338
378
  pi.on("agent_before_settle", pauseBoundary);
@@ -357,8 +397,10 @@ export function createDriverFactory(
357
397
  settingsManager,
358
398
  resourceLoader: loader,
359
399
  sessionManager,
400
+ // SDK `tools` is both a registry allowlist and an initial active list.
401
+ // Register every permitted deferred tool, then narrow declarations after bind.
360
402
  tools: toolNames,
361
- customTools: options.tools.filter((tool) => allowed.has(tool.name)),
403
+ customTools,
362
404
  });
363
405
  let lastScopedModelsKey = "";
364
406
  const updateResolved = () => {
@@ -375,7 +417,10 @@ export function createDriverFactory(
375
417
  liveScopedModels: readonly ScopedModel[],
376
418
  ) => {
377
419
  if (!filteringEnabled() || modelPreferences === undefined) return;
378
- const preferredIdentity = selectModelPreference(liveScopedModels, true);
420
+ const preferredIdentity = selectModelPreference(
421
+ availableScopedModels(liveScopedModels),
422
+ true,
423
+ );
379
424
  if (!preferredIdentity) return;
380
425
  if (!currentIdentity) throw new Error(`Subagent ${options.path} has no selected model`);
381
426
  if (currentIdentity !== preferredIdentity) {
@@ -402,7 +447,10 @@ export function createDriverFactory(
402
447
  updateResolved();
403
448
  return;
404
449
  }
405
- const preferredIdentity = selectModelPreference(liveScopedModels, true);
450
+ const preferredIdentity = selectModelPreference(
451
+ availableScopedModels(liveScopedModels),
452
+ true,
453
+ );
406
454
  if (!preferredIdentity) {
407
455
  updateResolved();
408
456
  return;
@@ -421,6 +469,7 @@ export function createDriverFactory(
421
469
  await enforceScopedModelPolicy();
422
470
  options.signal.throwIfAborted();
423
471
  await session.bindExtensions({ mode: "print" });
472
+ session.setActiveToolsByName(activeToolNames);
424
473
  options.signal.throwIfAborted();
425
474
  } catch (error) {
426
475
  session.dispose();
@@ -13,6 +13,7 @@ import { randomUUID } from "node:crypto";
13
13
  import { isMap, isScalar, parseDocument, stringify } from "yaml";
14
14
  import { getModelPreferences } from "./models.js";
15
15
  import { THINKING_LEVELS, type AgentType } from "../types.js";
16
+ import type { ToolFilteringMode } from "./settings.ts";
16
17
 
17
18
  // Pi semantic color tokens, resolved as concrete colors for agent name backgrounds.
18
19
  export const AGENT_COLORS = [
@@ -257,14 +258,22 @@ export function serializeAgentType(type: AgentType): string {
257
258
  export function selectTools(
258
259
  policy: AgentType["tools"],
259
260
  available: string[],
261
+ mode: ToolFilteringMode = "allowed",
260
262
  ): string[] {
261
- const validated = policy === undefined ? {} : toolPolicy(policy);
262
263
  const names = new Set(available);
264
+ if (mode === "all") return [...names];
265
+ // Ignored lists do not participate in validation or tool selection.
266
+ const relevantPolicy =
267
+ mode === "all-except-blocked"
268
+ ? policy?.block === undefined
269
+ ? {}
270
+ : { block: policy.block }
271
+ : policy;
272
+ const validated = relevantPolicy === undefined ? {} : toolPolicy(relevantPolicy);
263
273
  for (const name of [...(validated.allow ?? []), ...(validated.block ?? [])]) {
264
274
  if (!names.has(name)) throw new Error(`Unavailable tool name: ${name}`);
265
275
  }
266
- const allow =
267
- validated.allow === undefined ? names : new Set(validated.allow);
276
+ const allow = mode === "all-except-blocked" ? names : new Set(validated.allow ?? []);
268
277
  const block = new Set(validated.block ?? []);
269
278
  return [...names].filter((name) => allow.has(name) && !block.has(name));
270
279
  }
@@ -16,24 +16,36 @@ import { dirname, join, resolve } from "node:path";
16
16
  export const SUBAGENT_MODES = ["off", "opportunistic", "orchestration"] as const;
17
17
  export type SubagentMode = (typeof SUBAGENT_MODES)[number];
18
18
 
19
+ export const TOOL_FILTERING_MODES = ["allowed", "all-except-blocked", "all"] as const;
20
+ export type ToolFilteringMode = (typeof TOOL_FILTERING_MODES)[number];
21
+
22
+ export const MODEL_SELECTION_MODES = [
23
+ "pick-first-available",
24
+ "pick-first-scoped",
25
+ "use-current",
26
+ ] as const;
27
+ export type ModelSelectionMode = (typeof MODEL_SELECTION_MODES)[number];
28
+
19
29
  export interface ManagerSettings {
20
30
  subagentMode: SubagentMode;
31
+ toolFiltering: ToolFilteringMode;
21
32
  maxLevels: number;
22
33
  maxConcurrent: number;
23
34
  maxThreads: number;
24
- scopedModelFiltering: boolean;
35
+ modelSelection: ModelSelectionMode;
25
36
  }
26
37
 
27
38
  export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
28
39
  maxLevels: 3,
29
40
  maxConcurrent: 16,
30
41
  maxThreads: 64,
31
- scopedModelFiltering: true,
42
+ modelSelection: "pick-first-scoped",
32
43
  subagentMode: "opportunistic",
44
+ toolFiltering: "allowed",
33
45
  };
34
46
 
35
47
  const KEYS = [
36
- "maxLevels", "maxConcurrent", "maxThreads", "scopedModelFiltering", "subagentMode",
48
+ "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering",
37
49
  ] as const;
38
50
  const MAX_LEVELS = 32;
39
51
 
@@ -72,9 +84,10 @@ function positiveSafeInteger(value: unknown): value is number {
72
84
 
73
85
  function requirement(key: (typeof KEYS)[number]): string {
74
86
  if (key === "subagentMode") return "subagentMode must be off, opportunistic or orchestration";
75
- return key === "scopedModelFiltering"
76
- ? "scopedModelFiltering must be a boolean"
77
- : `${key} must be a positive safe integer`;
87
+ if (key === "toolFiltering") return "toolFiltering must be allowed, all-except-blocked or all";
88
+ if (key === "modelSelection")
89
+ return "modelSelection must be pick-first-available, pick-first-scoped or use-current";
90
+ return `${key} must be a positive safe integer`;
78
91
  }
79
92
 
80
93
  function parseSettings(content: string): Partial<ManagerSettings> {
@@ -90,9 +103,16 @@ function parseSettings(content: string): Partial<ManagerSettings> {
90
103
  }
91
104
  const record = parsed as Record<string, unknown>;
92
105
  for (const key of Object.keys(record)) {
93
- if (!isSupportedKey(key)) throw new Error(`Unknown settings key: ${key}`);
106
+ if (!isSupportedKey(key) && key !== "scopedModelFiltering")
107
+ throw new Error(`Unknown settings key: ${key}`);
94
108
  }
95
109
  const layer: Partial<ManagerSettings> = {};
110
+ if (Object.hasOwn(record, "scopedModelFiltering")) {
111
+ if (typeof record.scopedModelFiltering !== "boolean")
112
+ throw new Error("scopedModelFiltering must be a boolean");
113
+ if (!Object.hasOwn(record, "modelSelection"))
114
+ layer.modelSelection = record.scopedModelFiltering ? "pick-first-scoped" : "pick-first-available";
115
+ }
96
116
  for (const key of KEYS) {
97
117
  if (!Object.hasOwn(record, key)) continue;
98
118
  const value = record[key];
@@ -101,9 +121,16 @@ function parseSettings(content: string): Partial<ManagerSettings> {
101
121
  layer.subagentMode = value as SubagentMode;
102
122
  continue;
103
123
  }
104
- if (key === "scopedModelFiltering") {
105
- if (typeof value !== "boolean") throw new Error(requirement(key));
106
- layer.scopedModelFiltering = value;
124
+ if (key === "toolFiltering") {
125
+ if (!TOOL_FILTERING_MODES.includes(value as ToolFilteringMode))
126
+ throw new Error(requirement(key));
127
+ layer.toolFiltering = value as ToolFilteringMode;
128
+ continue;
129
+ }
130
+ if (key === "modelSelection") {
131
+ if (!MODEL_SELECTION_MODES.includes(value as ModelSelectionMode))
132
+ throw new Error(requirement(key));
133
+ layer.modelSelection = value as ModelSelectionMode;
107
134
  continue;
108
135
  }
109
136
  if (!positiveSafeInteger(value)) throw new Error(requirement(key));
@@ -409,7 +409,7 @@ export class OrderedModelEditorComponent extends Container {
409
409
 
410
410
  private withScopeWarning(text: string): string {
411
411
  if (this.scopedIdentities.size === 0) {
412
- return `No scoped models: explicit preferences cannot run. Configure /scoped-models. ${text}`;
412
+ return `No scoped models: Pick First (scoped) cannot run explicit preferences. Configure /scoped-models or change Model Picking. ${text}`;
413
413
  }
414
414
  return text;
415
415
  }
@@ -10,7 +10,9 @@ import {
10
10
  DEFAULT_MANAGER_SETTINGS,
11
11
  saveManagerSettings,
12
12
  type ManagerSettings,
13
+ type ModelSelectionMode,
13
14
  type SubagentMode,
15
+ type ToolFilteringMode,
14
16
  } from "../prefs/settings.ts";
15
17
  import { editAgentTypes } from "./ui.ts";
16
18
 
@@ -56,11 +58,53 @@ const MODE_OPTIONS = [
56
58
  const MODE_HELP =
57
59
  "Off: no subagent tools or prompt guidance.\nOpportunistic: delegate only parallelizable or very large tasks.\nOrchestration: /root delegates all execution and only coordinates and synthesizes results.";
58
60
 
59
- const SCOPED_MODEL_FILTERING = {
60
- id: "scopedModelFiltering",
61
- label: "Scoped model filtering",
62
- help: "On: agents can use only models selected in /scoped-models.\nOff: agents can use any available model.\nSave and apply to activate changes.",
63
- } as const;
61
+ const TOOL_FILTERING_OPTIONS = [
62
+ {
63
+ id: "allowed",
64
+ label: "Allowed (except blocked)",
65
+ value: "Allow list minus block list",
66
+ help: "Only tools in the agent YAML allow list are available, minus its block list.\nBlocked tools take precedence. A missing or empty allow list means no tools.",
67
+ },
68
+ {
69
+ id: "all-except-blocked",
70
+ label: "All except blocked",
71
+ value: "Ignore allow list",
72
+ help: "All available tools except those in the agent YAML block list.\nThe allow list is completely ignored.",
73
+ },
74
+ {
75
+ id: "all",
76
+ label: "All",
77
+ value: "Ignore both lists",
78
+ help: "All available tools.\nThe agent YAML allow and block lists are completely ignored.",
79
+ },
80
+ ] as const;
81
+
82
+ const TOOL_FILTERING_HELP =
83
+ "Allowed (except blocked): only allow-listed tools, minus blocked tools; a missing or empty allow list means no tools.\nAll except blocked: ignore the allow list; block-listed tools remain blocked.\nAll: ignore both lists.\nSave and apply to affect agents when their sessions start.";
84
+
85
+ const MODEL_SELECTION_OPTIONS = [
86
+ {
87
+ id: "pick-first-available",
88
+ label: "Pick First (available)",
89
+ value: "First available model in the agent's list",
90
+ help: "Pick First (available):\nPick the first model in the agent's models list available in Pi with an enabled, authenticated provider.\nSkip missing models and providers without credentials; try the next preference.",
91
+ },
92
+ {
93
+ id: "pick-first-scoped",
94
+ label: "Pick First (scoped)",
95
+ value: "First available preference in the session scope",
96
+ help: "Pick First (scoped):\nPick the first available model in the agent's models list that is also selected in the current session's /scoped-models.\nSkip unavailable models and providers without credentials.",
97
+ },
98
+ {
99
+ id: "use-current",
100
+ label: "Use Current",
101
+ value: "Use the main session's current model",
102
+ help: "Use Current:\nIgnore the agent's models list and use the main session's current model.\nKeep each agent's configured thinking level, not the main session's thinking level.",
103
+ },
104
+ ] as const;
105
+
106
+ const MODEL_SELECTION_HELP =
107
+ "Pick First (available): first preference with an enabled, authenticated provider in Pi.\nPick First (scoped): same, limited to the current session's /scoped-models.\nUse Current: ignore models and use the main session's current model; keep the agent's thinking level.\nOnly the models list affects runtime picking; modelSuggestions are search hints.\nSave and apply to affect agents when their sessions start.";
64
108
 
65
109
  export async function configureAgents(
66
110
  ctx: ExtensionCommandContext,
@@ -101,15 +145,21 @@ async function configureAgentsDialog(
101
145
  value: MODE_OPTIONS.find((mode) => mode.id === draft.subagentMode)!.label,
102
146
  help: MODE_HELP,
103
147
  },
148
+ {
149
+ id: "toolFiltering",
150
+ label: "Tool Filtering",
151
+ value: TOOL_FILTERING_OPTIONS.find((mode) => mode.id === draft.toolFiltering)!.label,
152
+ help: TOOL_FILTERING_HELP,
153
+ },
104
154
  ...FIELDS.map((field) => ({
105
155
  ...field,
106
156
  value: String(draft[field.id]),
107
157
  })),
108
158
  {
109
- id: SCOPED_MODEL_FILTERING.id,
110
- label: SCOPED_MODEL_FILTERING.label,
111
- value: draft.scopedModelFiltering ? "on" : "off",
112
- help: SCOPED_MODEL_FILTERING.help,
159
+ id: "modelSelection",
160
+ label: "Model Picking",
161
+ value: MODEL_SELECTION_OPTIONS.find((mode) => mode.id === draft.modelSelection)!.label,
162
+ help: MODEL_SELECTION_HELP,
113
163
  },
114
164
  {
115
165
  id: "scope",
@@ -174,8 +224,18 @@ async function configureAgentsDialog(
174
224
  });
175
225
  if (MODE_OPTIONS.some((option) => option.id === mode))
176
226
  draft.subagentMode = mode as SubagentMode;
177
- } else if (action === "scopedModelFiltering") {
178
- draft.scopedModelFiltering = !draft.scopedModelFiltering;
227
+ } else if (action === "toolFiltering") {
228
+ const mode = await dialogMenu(ctx, "Tool Filtering", [...TOOL_FILTERING_OPTIONS], {
229
+ selectedId: draft.toolFiltering,
230
+ });
231
+ if (TOOL_FILTERING_OPTIONS.some((option) => option.id === mode))
232
+ draft.toolFiltering = mode as ToolFilteringMode;
233
+ } else if (action === "modelSelection") {
234
+ const mode = await dialogMenu(ctx, "Model Picking", [...MODEL_SELECTION_OPTIONS], {
235
+ selectedId: draft.modelSelection,
236
+ });
237
+ if (MODEL_SELECTION_OPTIONS.some((option) => option.id === mode))
238
+ draft.modelSelection = mode as ModelSelectionMode;
179
239
  } else if (action === "scope") {
180
240
  if (!ctx.isProjectTrusted())
181
241
  ctx.ui.notify(