oira666_pi-subagent 0.5.10 → 0.5.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +21 -12
  2. package/agents.ts +17 -19
  3. package/budget.ts +2 -1
  4. package/config.ts +14 -57
  5. package/docs/configuration.md +61 -9
  6. package/docs/sessions.md +3 -3
  7. package/extension/events.ts +2 -1
  8. package/extension/execution.ts +5 -2
  9. package/extension/expand-command.ts +2 -1
  10. package/extension/launch-tool.ts +49 -12
  11. package/extension/models.ts +5 -4
  12. package/extension/policy.ts +18 -11
  13. package/extension/prompt-hook.ts +12 -11
  14. package/extension/prompts.ts +4 -3
  15. package/extension/provider.ts +8 -5
  16. package/extension/resume-offer.ts +4 -3
  17. package/extension/resume-tool.ts +7 -3
  18. package/extension/runtime.ts +11 -2
  19. package/extension/schemas.ts +82 -20
  20. package/extension/session-start.ts +34 -19
  21. package/extension/state.ts +21 -4
  22. package/extension/tool-registration.ts +26 -5
  23. package/index.ts +4 -2
  24. package/intelligence.ts +5 -3
  25. package/package.json +2 -2
  26. package/render.ts +34 -25
  27. package/resume.ts +10 -3
  28. package/runner/arguments.ts +25 -24
  29. package/runner/attempt.ts +4 -3
  30. package/runner/constants.ts +8 -2
  31. package/runner/extension-policy.ts +24 -13
  32. package/runner/launch.ts +7 -3
  33. package/runner/options.ts +2 -0
  34. package/runner/parallel.ts +24 -5
  35. package/runner/resource-paths.ts +10 -0
  36. package/runner/single.ts +20 -7
  37. package/settings.ts +89 -0
  38. package/storage/config-files.ts +52 -0
  39. package/types/contracts.ts +1 -1
  40. package/ui/agent-label.ts +11 -0
  41. package/ui/detail-lines.ts +12 -26
  42. package/ui/detail-model.ts +1 -0
  43. package/ui/detail-transcript.ts +1 -0
  44. package/ui/pager-view.ts +2 -5
  45. package/ui/picker.ts +2 -3
  46. package/ui/tree-build.ts +11 -12
  47. package/ui/tree-format.ts +4 -3
  48. package/agents/code-architect.md +0 -24
  49. package/agents/code-reviwer.md +0 -23
  50. package/agents/code-writer.md +0 -17
  51. package/agents/team-of-subagents.md +0 -14
package/README.md CHANGED
@@ -18,6 +18,20 @@ To remove it:
18
18
  pi remove npm:oira666_pi-subagent
19
19
  ```
20
20
 
21
+ ## Configuration
22
+
23
+ Use either `pi-subagent.json` or `pi-subagents.json`. Both filenames are permanently supported. User-configurable extension options have grouped JSON settings, with precedence **environment > JSON > defaults**.
24
+
25
+ ```json
26
+ {
27
+ "limits": { "total": 50, "parallel": 30, "concurrency": 8 },
28
+ "delegation": { "depth": 3, "preventCycles": true },
29
+ "runner": { "startupTimeoutMs": 120000 }
30
+ }
31
+ ```
32
+
33
+ See [settings files](docs/configuration.md#settings-files) for locations, all settings, environment mappings, and trust rules.
34
+
21
35
  ## Extension controls
22
36
 
23
37
  Exclude extensions from child agents without changing which extensions the parent loads:
@@ -32,7 +46,7 @@ The originally requested hyphenated name is also supported. Use `env` because mo
32
46
  env 'PI-SUBAGENT-EXCLUDE-EXTENSIONS=oira666_pi-free-swarm' pi
33
47
  ```
34
48
 
35
- Both variables accept comma-separated lists; whitespace and empty entries are ignored, and the two lists are combined. Entries match a package source, package name (including `npm:@scope/name@version`, ignoring the version), or an extension file/directory path. Automatic and settings-listed extension paths use the nearest owning `package.json` after resolving symlinks; loose hooks do not inherit the current workspace's or Pi configuration directory's package name. Relative paths resolve from the worker's working directory; `~/` and symlinks are supported. Commas inside paths are not supported. These variables are inherited by nested workers.
49
+ Both variables accept comma-separated lists; whitespace and empty entries are ignored, and the two lists are combined. Entries match a package source, package name (including `npm:@scope/name@version`, ignoring the version), or an extension file/directory path. Automatic and settings-listed extension paths use the nearest owning `package.json` after resolving symlinks; loose hooks do not inherit the current workspace's or Pi configuration directory's package name. Relative paths resolve from the worker's working directory; `~/` and symlinks are supported. Commas inside paths are not supported in environment lists; use the JSON `extension.exclude` array for those paths. These variables are inherited by nested workers.
36
50
 
37
51
  When a list is nonempty, the runner discovers enabled extensions without executing them, then launches the child with `--no-extensions` and explicit paths for every remaining extension, including authentication providers. This covers automatic user/project extensions and forwarded `-e` sources. An original `--no-extensions` still suppresses automatic extensions. Project resources are included only when the parent's live context trusts that working directory; unknown trust fails closed. The same trust decision is passed to the child. With no exclusions, launch behavior is unchanged and no extra discovery runs.
38
52
 
@@ -51,13 +65,13 @@ PI_SUBAGENT_DISABLED=1 pi
51
65
  ```json
52
66
  {
53
67
  "tasks": [
54
- { "agent": "code-writer", "task": "Implement the API", "max_subagents_allowed": 0 },
55
- { "agent": "code-reviwer", "task": "Review the design", "max_subagents_allowed": 0 }
68
+ { "task": "Implement the API", "max_subagents_allowed": 0 },
69
+ { "task": "Review the design", "max_subagents_allowed": 0 }
56
70
  ]
57
71
  }
58
72
  ```
59
73
 
60
- Call `subagents` with one or more tasks. Tasks run in parallel, subject to the concurrency limit. Every task requires an agent type, task text, and a descendant allowance. Use `0` for a worker that will not delegate, or `1` to let it launch one subagent. The caller reserves one slot for the worker plus its descendant allowance.
74
+ Call `subagents` with one or more tasks. Tasks run in parallel, subject to the concurrency limit. Every task requires task text and a descendant allowance. The `agent` argument exists only when user-created agent definitions are available. The `intelligence` argument exists only when two or more enabled presets are configured. These choices are independent; with neither, task items contain only `task` and `max_subagents_allowed`. Use `0` for a worker that will not delegate, or `1` to let it launch one subagent. The caller reserves one slot for the worker plus its descendant allowance.
61
75
 
62
76
  Workers with zero descendant allowance receive neither active delegation tools nor added delegation guidance. Raising `max_subagents_allowed` on resume restores the tools, subject to the depth limit. This uses Pi's documented `getActiveTools()` and `setActiveTools()` APIs during `session_start`. Workers that spent a positive allowance keep their tools so they can resume existing children.
63
77
 
@@ -73,12 +87,7 @@ Delegate only when parallel work or context isolation saves enough effort to cov
73
87
 
74
88
  ## Agent definitions
75
89
 
76
- Bundled agents:
77
-
78
- - `code-writer`: implementation and refactoring.
79
- - `code-reviwer`: code review. The spelling is retained for compatibility.
80
- - `code-architect`: technical design.
81
- - `team-lead`: coordination of a large subproject, launchable only by the main agent.
90
+ There are no bundled agents. Without user-created definitions, every task uses the same default worker, with no agent-specific system prompt or instructions. It receives the parent's task text unchanged. Pi's normal system prompt and delegation limits still apply.
82
91
 
83
92
  Create Markdown files in `~/.pi/agent/agents/`, `$PI_CODING_AGENT_DIR/agents/`, or the project's `.pi/agents/` directory:
84
93
 
@@ -95,7 +104,7 @@ tools: read,write
95
104
  Write clear, concise technical documentation.
96
105
  ```
97
106
 
98
- The body is appended to Pi's system prompt. Project definitions override user/environment definitions, which override bundled definitions of the same name. Custom definitions replace the bundled instructions too.
107
+ The body is appended to Pi's system prompt. Project definitions override user/environment definitions of the same name.
99
108
 
100
109
  See [configuration](docs/configuration.md) for frontmatter, layer restrictions, prompt overrides, and environment settings.
101
110
 
@@ -105,7 +114,7 @@ Collapsed results show each child's name, task, status, and most recent activity
105
114
 
106
115
  `/subagent-expand <name>` opens a saved worker transcript. With no name, it opens a searchable picker. Name completion is fuzzy. Each task or resume shows its actual provider/model and thinking level from the worker's session, not the parent's settings. Selected presets also appear as an intelligence label, kept separately for each run. Missing historical model/thinking metadata appears as `unknown`.
107
116
 
108
- [Model presets](docs/configuration.md#caller-selected-intelligence) show labels such as `Nicolas (Junior/code-writer)` in regular tool results. One enabled preset applies automatically to new launches without exposing an `intelligence` argument. Two or more require an explicit `intelligence` choice on every launch item. Omitted or `null` choices reject the whole launch batch before any worker starts. Zero or disabled presets keep the existing launch defaults and show no intelligence label. Named resumes do not accept `intelligence`; they retain the original effective model, thinking, and label, even after configuration or parent settings change.
117
+ [Model presets](docs/configuration.md#caller-selected-intelligence) show labels such as `Nicolas (Junior/code-writer)` in regular tool results. One enabled preset applies automatically to new launches without exposing an `intelligence` argument. Two or more require an explicit `intelligence` choice on every launch item. Omitted or `null` choices reject the whole launch batch before any worker starts. Zero or disabled presets keep the existing launch defaults and show no intelligence label. Without an agent type, labels show `Nicolas (Junior)`; without either qualifier, they show just `Nicolas`. Named resumes do not accept `intelligence`; they retain the original effective model, thinking, and label, even after configuration or parent settings change.
109
118
 
110
119
  | Key | Action |
111
120
  | --- | --- |
package/agents.ts CHANGED
@@ -7,25 +7,22 @@
7
7
  * Lookup locations:
8
8
  * - User agents: ~/.pi/agent/agents/*.md (or $PI_CODING_AGENT_DIR/agents/ when env var is set)
9
9
  * - Project agents: .pi/agents/*.md (walks up from cwd)
10
- * - Bundled agents: ./agents/*.md (included unless PI_SUBAGENT_HIDE_BUILTIN_AGENTS is true)
11
10
  */
12
11
 
13
12
  import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
14
13
  import * as fs from "node:fs";
15
14
  import * as path from "node:path";
16
- import { fileURLToPath } from "node:url";
17
- import { parseBoolean } from "./shared.js";
15
+ import type { SubagentSettings } from "./settings.js";
18
16
 
19
17
  export type AgentScope = "user" | "project" | "both";
20
- export type AgentSource = "user" | "project" | "builtin";
18
+ // "builtin" remains valid for historical session records, not discovery.
19
+ export type AgentSource = "user" | "project" | "builtin" | "default";
21
20
  export type LayerSetting = boolean | "only";
22
21
  export interface LayerRule {
23
22
  layers: number[];
24
23
  setting: LayerSetting;
25
24
  }
26
25
 
27
- export const SUBAGENT_HIDE_BUILTIN_AGENTS_ENV = "PI_SUBAGENT_HIDE_BUILTIN_AGENTS";
28
-
29
26
  export interface AgentConfig {
30
27
  name: string;
31
28
  description: string;
@@ -47,7 +44,14 @@ export interface AgentDiscoveryResult {
47
44
  projectAgentsDir: string | null;
48
45
  }
49
46
 
50
- const BUNDLED_AGENTS_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "agents");
47
+ /** Internal fallback, never advertised as a user-defined agent type. */
48
+ export const DEFAULT_AGENT: AgentConfig = {
49
+ name: "",
50
+ description: "",
51
+ systemPrompt: "",
52
+ source: "default",
53
+ filePath: "",
54
+ };
51
55
 
52
56
  // ---------------------------------------------------------------------------
53
57
  // Internal helpers
@@ -196,10 +200,6 @@ function dedupeAgents(...layers: AgentConfig[][]): AgentConfig[] {
196
200
  return Array.from(agentMap.values());
197
201
  }
198
202
 
199
- function hideBuiltinAgents(): boolean {
200
- return parseBoolean(process.env[SUBAGENT_HIDE_BUILTIN_AGENTS_ENV]) === true;
201
- }
202
-
203
203
  // ---------------------------------------------------------------------------
204
204
  // Public API
205
205
  // ---------------------------------------------------------------------------
@@ -247,19 +247,17 @@ export function filterAdvertisedAgents(
247
247
  /**
248
248
  * Discover all available agents according to the requested scope.
249
249
  *
250
- * Built-in agents are included at the lowest priority unless
251
- * PI_SUBAGENT_HIDE_BUILTIN_AGENTS is true. Custom agents with the same name
252
- * override their built-in counterpart.
250
+ * Only user-created definitions count. Project definitions override user
251
+ * definitions with the same name.
253
252
  */
254
- export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryResult {
253
+ export function discoverAgents(cwd: string, scope: AgentScope, _settings?: SubagentSettings): AgentDiscoveryResult {
255
254
  const userDir = path.join(getAgentDir(), "agents");
256
255
  const projectAgentsDir = findNearestProjectAgentsDir(cwd);
257
256
 
258
- const builtinAgents = hideBuiltinAgents() ? [] : loadAgentsFromDir(BUNDLED_AGENTS_DIR, "builtin");
259
257
  const userAgents = loadAgentsFromDir(userDir, "user");
260
258
  const projectAgents = projectAgentsDir ? loadAgentsFromDir(projectAgentsDir, "project") : [];
261
259
 
262
- if (scope === "user") return { agents: dedupeAgents(builtinAgents, userAgents), projectAgentsDir };
263
- if (scope === "project") return { agents: dedupeAgents(builtinAgents, projectAgents), projectAgentsDir };
264
- return { agents: dedupeAgents(builtinAgents, userAgents, projectAgents), projectAgentsDir };
260
+ if (scope === "user") return { agents: dedupeAgents(userAgents), projectAgentsDir };
261
+ if (scope === "project") return { agents: dedupeAgents(projectAgents), projectAgentsDir };
262
+ return { agents: dedupeAgents(userAgents, projectAgents), projectAgentsDir };
265
263
  }
package/budget.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { configuredEnv } from "./settings.js";
1
2
  import * as path from "node:path";
2
3
  import { createHash } from "node:crypto";
3
4
 
@@ -25,7 +26,7 @@ export const SUBAGENT_BUDGET_DIR_ENV = "PI_SUBAGENT_BUDGET_DIR";
25
26
  export const SUBAGENT_BUDGET_CUSTOM_TYPE = "pi-subagent-budget";
26
27
  export const DEFAULT_MAX_TOTAL_AGENTS = 50;
27
28
 
28
- export function configuredTotalBudget(value = process.env[SUBAGENT_MAX_TOTAL_AGENTS_ENV]): number {
29
+ export function configuredTotalBudget(value = configuredEnv(SUBAGENT_MAX_TOTAL_AGENTS_ENV)): number {
29
30
  if (value === undefined) return DEFAULT_MAX_TOTAL_AGENTS;
30
31
  if (!/^\d+$/.test(value.trim()) || !isBudgetAmount(Number(value))) {
31
32
  throw new SubagentBudgetError(
package/config.ts CHANGED
@@ -1,39 +1,12 @@
1
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
2
- import * as fs from "node:fs";
3
- import * as os from "node:os";
4
- import * as path from "node:path";
5
-
6
1
  import { intelligenceEnabled, parseIntelligencePresets, type IntelligencePreset } from "./intelligence.js";
7
-
8
- export const PI_SUBAGENTS_CONFIG_FILE = "pi-subagents.json";
9
- export const PI_SUBAGENT_CONFIG_FILE = "pi-subagent.json";
2
+ import { configPaths, readConfig } from "./storage/config-files.js";
3
+ import { readSettings, type SubagentSettings } from "./settings.js";
4
+ export { PI_SUBAGENTS_CONFIG_FILE, PI_SUBAGENT_CONFIG_FILE, findProjectConfig } from "./storage/config-files.js";
10
5
 
11
6
  export interface PiSubagentsConfig {
12
7
  toolPrompts: Record<string, string>;
13
8
  intelligencePresets: IntelligencePreset[];
14
- }
15
-
16
- function readConfig(filePath: string): Record<string, unknown> {
17
- if (!fs.existsSync(filePath)) return {};
18
-
19
- try {
20
- const parsed = JSON.parse(fs.readFileSync(filePath, "utf8")) as unknown;
21
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
22
- console.warn(`[pi-subagent] Ignoring invalid config "${filePath}". Expected a JSON object.`);
23
- return {};
24
- }
25
-
26
- return parsed as Record<string, unknown>;
27
- } catch {
28
- // Do not expose configuration contents in parser errors.
29
- console.warn(`[pi-subagent] Failed to read config "${filePath}".`);
30
- return {};
31
- }
32
- }
33
-
34
- function configAtLocation(dir: string): string {
35
- const singular = path.join(dir, PI_SUBAGENT_CONFIG_FILE);
36
- return fs.existsSync(singular) ? singular : path.join(dir, PI_SUBAGENTS_CONFIG_FILE);
9
+ settings: SubagentSettings;
37
10
  }
38
11
 
39
12
  function readToolPrompts(config: Record<string, unknown>, filePath: string): Record<string, string> {
@@ -59,37 +32,17 @@ function readToolPrompts(config: Record<string, unknown>, filePath: string): Rec
59
32
  return result;
60
33
  }
61
34
 
62
- /** Find the nearest project-local config while walking up from cwd. */
63
- export function findProjectConfig(cwd: string): string | null {
64
- let dir = path.resolve(cwd);
65
- while (true) {
66
- const candidate = configAtLocation(path.join(dir, ".pi"));
67
- if (fs.existsSync(candidate)) return candidate;
68
- const parent = path.dirname(dir);
69
- if (parent === dir) return null;
70
- dir = parent;
71
- }
72
- }
73
-
74
- /**
75
- * Load configuration from lowest to highest priority:
76
- * ~/.pi/pi-subagents.json
77
- * $PI_CODING_AGENT_DIR/pi-subagents.json (normally ~/.pi/agent/pi-subagents.json)
78
- * nearest project .pi/pi-subagents.json (trusted projects only)
79
- * pi-subagent.json replaces pi-subagents.json at each location when present.
80
- */
35
+ /** Load personal settings, then the nearest project configuration when trusted. */
81
36
  export function loadPiSubagentsConfig(cwd?: string, includeProject = false): PiSubagentsConfig {
82
- const paths = [configAtLocation(path.join(os.homedir(), ".pi")), configAtLocation(getAgentDir())];
83
- if (cwd && includeProject) {
84
- const projectConfig = findProjectConfig(cwd);
85
- if (projectConfig) paths.push(projectConfig);
86
- }
87
-
37
+ const paths = configPaths(cwd, includeProject);
38
+ const personalPaths = new Set(configPaths());
39
+ const settings: SubagentSettings = {};
88
40
  const toolPrompts: Record<string, string> = {};
89
41
  let intelligencePresets: IntelligencePreset[] = [];
90
42
  for (const filePath of new Set(paths)) {
91
43
  const config = readConfig(filePath);
92
44
  Object.assign(toolPrompts, readToolPrompts(config, filePath));
45
+ Object.assign(settings, readSettings(config, filePath, personalPaths.has(filePath)));
93
46
  if (Object.hasOwn(config, "subagents-models")) {
94
47
  intelligencePresets = [];
95
48
  try {
@@ -99,5 +52,9 @@ export function loadPiSubagentsConfig(cwd?: string, includeProject = false): PiS
99
52
  }
100
53
  }
101
54
  }
102
- return { toolPrompts, intelligencePresets: intelligenceEnabled(intelligencePresets) ? intelligencePresets : [] };
55
+ return {
56
+ toolPrompts,
57
+ settings,
58
+ intelligencePresets: intelligenceEnabled(intelligencePresets, settings) ? intelligencePresets : [],
59
+ };
103
60
  }
@@ -35,15 +35,68 @@ second-layer: disabled
35
35
 
36
36
  At maximum depth 1, combining `first-layer: only` with `last-layer: disabled` blocks all launches of that definition.
37
37
 
38
- ## Tool descriptions
38
+ ## Settings files
39
+
40
+ `pi-subagent.json` and `pi-subagents.json` are both permanently supported filenames with the same format. Either name works at each location below:
41
+
42
+ 1. `~/.pi/`
43
+ 2. `$PI_CODING_AGENT_DIR/`, normally `~/.pi/agent/`
44
+ 3. The nearest trusted project `.pi/` containing either filename, walking upward from the working directory
45
+
46
+ Later locations override earlier ones per setting. If both filenames exist at one location, only `pi-subagent.json` is read there. Use either name; no migration is needed.
39
47
 
40
- Use `pi-subagent.json` to configure model presets or replace either tool's full model-facing description. Files load in this order, with later values overriding earlier values per tool:
48
+ For each setting, an explicitly set environment variable wins over JSON, then the built-in default applies. Empty or invalid environment values still take precedence and use that variable's existing parsing rules. Explicit `false`, `0`, and empty arrays in JSON are not treated as missing. CLI delegation flags retain their existing priority; children cannot loosen inherited delegation limits. Existing session budgets are not reset by configuration changes.
41
49
 
42
- 1. `~/.pi/pi-subagent.json`
43
- 2. `$PI_CODING_AGENT_DIR/pi-subagent.json`, normally `~/.pi/agent/pi-subagent.json`
44
- 3. The nearest trusted `.pi/pi-subagent.json`, walking upward from the working directory
50
+ ```json
51
+ {
52
+ "extension": { "disabled": false, "exclude": [] },
53
+ "agents": { "confirmProject": "ask" },
54
+ "limits": { "total": 50, "parallel": 30, "concurrency": 8 },
55
+ "delegation": { "depth": 3, "preventCycles": true },
56
+ "resume": { "disabled": false, "disableAuto": false, "prompt": true },
57
+ "models": { "intelligence": true },
58
+ "runner": {
59
+ "startupTimeoutMs": 120000,
60
+ "idleTimeoutMs": 1200000,
61
+ "startupRetries": 2
62
+ }
63
+ }
64
+ ```
65
+
66
+ | JSON setting | Environment variable | Default |
67
+ | --- | --- | --- |
68
+ | `extension.disabled` | `PI_SUBAGENT_DISABLED` / `PI-SUBAGENT-DISABLED` | `false` |
69
+ | `extension.exclude` | `PI_SUBAGENT_EXCLUDE_EXTENSIONS` / `PI-SUBAGENT-EXCLUDE-EXTENSIONS` | `[]` |
70
+ | `agents.confirmProject` | `PI_SUBAGENT_CONFIRM_PROJECT_AGENTS` | `"ask"` |
71
+ | `limits.total` | `PI_SUBAGENT_MAX_TOTAL_AGENTS` | `50` |
72
+ | `limits.parallel` | `PI_SUBAGENT_MAX_PARALLEL_TASKS` | `30` |
73
+ | `limits.concurrency` | `PI_SUBAGENT_MAX_CONCURRENCY` | `8` |
74
+ | `delegation.depth` | `PI_SUBAGENT_MAX_DEPTH` | `3` |
75
+ | `delegation.preventCycles` | `PI_SUBAGENT_PREVENT_CYCLES` | `true` |
76
+ | `resume.disabled` | `DISABLE_RESUMABLE_SUBAGENTS` | `false` |
77
+ | `resume.disableAuto` | `PI_SUBAGENT_DISABLE_RESUME` | `false` |
78
+ | `resume.prompt` | `PI_SUBAGENT_RESUME_PROMPT` | `true` |
79
+ | `models.intelligence` | `PI_SUBAGENT_INTELLIGENCE` | `true` |
80
+ | `models.fallback` | `PI_SUBAGENT_FALLBACK_MODEL` | No configured fallback |
81
+ | `runner.startupTimeoutMs` | `PI_SUBAGENT_STARTUP_TIMEOUT` | `120000` |
82
+ | `runner.idleTimeoutMs` | `PI_SUBAGENT_IDLE_TIMEOUT` | `1200000` |
83
+ | `runner.startupRetries` | `PI_SUBAGENT_STARTUP_RETRIES` | `2` |
84
+ | `runner.command` | `PI_SUBAGENT_PI_COMMAND` | Current runtime |
85
+ | `runner.argsPrefix` | `PI_SUBAGENT_PI_ARGS_PREFIX` | Current entrypoint |
86
+
87
+ JSON switches require booleans; counts and timeouts require non-negative safe integers. `agents.confirmProject` accepts `true`, `false`, `"ask"`, `"never"`, or `"session"`. `models.fallback` and `runner.command` accept non-empty strings. `extension.exclude` and `runner.argsPrefix` accept arrays of strings. Invalid settings warn and are ignored, except an invalid `limits.total` blocks new launches.
88
+
89
+ `extension.exclude` entries follow the matching rules in the README. JSON arrays preserve commas inside paths. Setting either environment alias replaces the JSON list; when both aliases are set, their CSV lists combine. Either disabling alias set to `1` or `true` disables the extension, regardless of JSON.
90
+
91
+ `runner.command` and `runner.argsPrefix` are personal-only settings. Project files cannot change the executable or its startup arguments, even in trusted projects. The prefix applies only with an explicit command. For example, a personal file can contain `"runner": { "command": "node", "argsPrefix": ["/absolute/path/to/pi.js"] }`.
92
+
93
+ JSON `extension.disabled` disables session features after project settings resolve, so a trusted project can override a personal value. Environment disabling prevents registration altogether. Reload Pi after changing settings.
94
+
95
+ Only user-configurable extension variables have JSON counterparts. Inherited runtime metadata stays internal: `PI_SUBAGENT_DEPTH`, `PI_SUBAGENT_STACK`, `PI_SUBAGENT_BUDGET_DIR`, `PI_SUBAGENT_NAMES_FILE`, `PI_SUBAGENT_SESSION_ROOT`, and `PI_SUBAGENT_RUN_INTELLIGENCE`. OS and Pi SDK variables such as `HOME`, `PATH`, `PI_CODING_AGENT_DIR`, provider credentials, and proxy settings remain environment variables.
96
+
97
+ ## Tool descriptions
45
98
 
46
- The legacy filename `pi-subagents.json` is also supported. At each location, the singular filename takes precedence over the plural filename.
99
+ In either settings filename, use `tool-prompts` to replace either tool's full model-facing description:
47
100
 
48
101
  ```json
49
102
  {
@@ -58,7 +111,7 @@ Missing descriptions retain their defaults. Overrides change written guidance, n
58
111
 
59
112
  ## Caller-selected intelligence
60
113
 
61
- Define named model presets in `pi-subagent.json`. With two or more enabled presets, the calling model must choose a configured `intelligence` preset for every launch item. With exactly one enabled preset, the launch tool hides the argument and automatically uses that preset. With no presets, the argument is absent and existing model/thinking defaults apply to launches. Named resumes never offer or accept an intelligence choice. No router or separate model-selection request is used.
114
+ Define named model presets in `pi-subagent.json` or `pi-subagents.json`. With two or more enabled presets, the calling model must choose a configured `intelligence` preset for every launch item. With exactly one enabled preset, the launch tool hides the argument and automatically uses that preset. With no presets, the argument is absent and existing model/thinking defaults apply to launches. Named resumes never offer or accept an intelligence choice. No router or separate model-selection request is used.
62
115
 
63
116
  ```json
64
117
  {
@@ -102,7 +155,7 @@ A selected or automatic preset overrides the parent model and agent model/thinki
102
155
 
103
156
  `resume_subagents` retains the original effective model, thinking level, and intelligence label. This also applies to private forks and after restart, preset changes, disabling intelligence, changing the parent model, or editing/deleting the agent definition. A worker launched without a preset remains unlabelled. Pass only `{ subagent, task }` and an optional `max_subagents_allowed`; any `intelligence` argument, including `null`, rejects the resume batch.
104
157
 
105
- Tool result rows show the selected preset, for example `Nicolas (Junior/code-writer)`. Display names capitalize only the first character; configured spelling and argument values otherwise stay unchanged. Runs without a preset show `Nicolas (code-writer)`. Durable results retain their own preset name, and the name registry retains the initial choice. The `/subagent-expand` picker shows the initial preset beside each agent type and lets you search by preset name. Its transcript view shows each task's or resume's recorded intelligence alongside its actual transcript model and thinking level. Later resumes do not relabel earlier work. Missing model or thinking metadata remains `unknown`, even when a preset name is known.
158
+ Tool result rows show the selected preset, for example `Nicolas (Junior/code-writer)`. Display names capitalize only the first character; configured spelling and argument values otherwise stay unchanged. Runs without a preset show `Nicolas (code-writer)`. Runs without an agent type show `Nicolas (Junior)`, or just `Nicolas` when neither qualifier exists. Agent types come only from user-created definitions. With no available types, the launch schema omits `agent` and uses a default worker without agent-specific instructions. Durable results retain their own preset name, and the name registry retains the initial choice. The `/subagent-expand` picker shows the initial preset beside each agent type and lets you search by preset name. Its transcript view shows each task's or resume's recorded intelligence alongside its actual transcript model and thinking level. Later resumes do not relabel earlier work. Missing model or thinking metadata remains `unknown`, even when a preset name is known.
106
159
 
107
160
  `PI_SUBAGENT_INTELLIGENCE=true` enables presets when they exist, which is the default. Set it to `false` or `0` to treat the configuration as having no presets for new launches: the launch tool hides the argument and no automatic preset applies. Named resumes still retain their original settings. Unknown choices or attempts to pass a named hidden argument fail before launching workers. When the argument is hidden, omission or `null` still uses the automatic sole preset or existing defaults.
108
161
 
@@ -119,7 +172,6 @@ The old `smart-decision` block is ignored. Remove it and its router credentials
119
172
  | `PI_SUBAGENT_MAX_CONCURRENCY` | `8` | Simultaneously running workers per call |
120
173
  | `PI_SUBAGENT_MAX_DEPTH` / `--subagent-max-depth` | `3` | Maximum delegation depth; `0` blocks delegation |
121
174
  | `PI_SUBAGENT_PREVENT_CYCLES` / `--subagent-prevent-cycles` | `true` | Block agent types already in the delegation stack |
122
- | `PI_SUBAGENT_HIDE_BUILTIN_AGENTS` | `false` | Hide bundled definitions when set to `true`, `on`, `yes`, or `1` |
123
175
  | `PI_SUBAGENT_CONFIRM_PROJECT_AGENTS` | `ask` | `true` / `ask` prompts for approval; `false` / `never` trusts projects; `session` remembers approval |
124
176
  | `PI_CODING_AGENT_DIR` | `~/.pi/agent` | Agent definitions and configuration directory |
125
177
 
package/docs/sessions.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Agent allowances
4
4
 
5
- A new main session has 50 agent slots by default. Set `PI_SUBAGENT_MAX_TOTAL_AGENTS` before starting a new session to change this. `0` blocks new launches but permits named resumes. Invalid values block launches.
5
+ A new main session has 50 agent slots by default. Set `limits.total` in either settings filename or `PI_SUBAGENT_MAX_TOTAL_AGENTS` before starting a new session to change this. The environment takes precedence. `0` blocks new launches but permits named resumes. Invalid values block launches.
6
6
 
7
7
  `max_subagents_allowed` caps all descendants a worker may launch, excluding the worker itself. Each task reserves `1 + max_subagents_allowed` slots from the caller. Two tasks with descendant caps of `3` and `0` reserve five slots. Use `0` for a direct worker; `1` lets the worker launch one subagent.
8
8
 
@@ -14,7 +14,7 @@ A new main session has 50 agent slots by default. Set `PI_SUBAGENT_MAX_TOTAL_AGE
14
14
 
15
15
  The main agent sees its remaining count only below 30, to avoid presenting larger caps as spending targets. Delegating workers see their branch allowance. Enforcement is the same regardless of prompt visibility.
16
16
 
17
- Budgets persist across reloads, restarts, compaction, and forks. Changing the environment does not enlarge an existing tree. Workers from older sessions without recorded reservations may resume but cannot launch new descendants.
17
+ Budgets persist across reloads, restarts, compaction, and forks. Changing the environment or JSON settings does not enlarge an existing tree. Workers from older sessions without recorded reservations may resume but cannot launch new descendants.
18
18
 
19
19
  Older recorded calls and ledgers remain resumable. The extension converts their allowances to descendant caps without changing reserved or remaining slots. New calls use only `max_subagents_allowed`.
20
20
 
@@ -72,4 +72,4 @@ Interrupted `resume_subagents` calls are not replayed automatically. The model c
72
72
  | `PI_SUBAGENT_NAMES_FILE` | Internal | Shared registry path, propagated to children |
73
73
  | `PI_SUBAGENT_BUDGET_DIR` | Internal | Reserved branch ledger, propagated and saved in session metadata |
74
74
 
75
- Internal storage paths should normally be left to the extension.
75
+ The recovery controls also have JSON settings: `resume.prompt`, `resume.disableAuto`, and `resume.disabled`, respectively. See [settings files](configuration.md#settings-files). Internal storage paths are managed by the extension and have no JSON counterpart.
@@ -1,3 +1,4 @@
1
+ import { configuredEnv } from "../settings.js";
1
2
  import { SUBAGENT_RESUME_DISABLE_ENV, parseBooleanEnv } from "../resume.js";
2
3
  import { RESUME_PROVIDER } from "../shared.js";
3
4
  import { isSubagentToolName, subagentDetailsHaveErrors } from "../types.js";
@@ -23,7 +24,7 @@ export function registerSessionEvents(state: ExtensionState): void {
23
24
  if (ctx.model?.provider === RESUME_PROVIDER) return;
24
25
  if (typeof ctx.isIdle === "function" && !ctx.isIdle()) return;
25
26
 
26
- const resumeDisabled = parseBooleanEnv(process.env[SUBAGENT_RESUME_DISABLE_ENV]) === true;
27
+ const resumeDisabled = parseBooleanEnv(configuredEnv(SUBAGENT_RESUME_DISABLE_ENV, state.settings)) === true;
27
28
  if (resumeDisabled) return;
28
29
 
29
30
  await maybeOfferSubagentResume(state, ctx, { deferInteractivePrompt: false });
@@ -3,13 +3,14 @@ import { type SubagentBudget } from "../budget.js";
3
3
  import { isFinishedResult } from "../resume.js";
4
4
  import { executeParallelSubprocess, runAgentSubprocess } from "../runner.js";
5
5
  import { type SingleResult, getFinalOutput, isResultError } from "../types.js";
6
+ import { formatSubagentLabel } from "../ui/agent-label.js";
6
7
  import { updateLatestBroadcastTargets } from "./broadcast.js";
7
8
  import type { ProgressUpdate } from "./contracts.js";
8
9
  import { makeDetailsFactory } from "./details.js";
9
10
  import type { ExtensionState } from "./state.js";
10
11
 
11
12
  export function formatNameSuffix(result: SingleResult | undefined): string {
12
- return result?.name ? `\n\n(subagent: ${result.name} (${result.agent}) — resume with the name ${result.name})` : "";
13
+ return result?.name ? `\n\n(subagent: ${formatSubagentLabel(result)} — resume with the name ${result.name})` : "";
13
14
  }
14
15
 
15
16
  export async function executeSingle(
@@ -47,6 +48,7 @@ export async function executeSingle(
47
48
  try {
48
49
  result = await runAgentSubprocess({
49
50
  cwd: defaultCwd,
51
+ settings: state.settings,
50
52
  projectTrusted: state.latestSessionCtx?.cwd === defaultCwd && state.latestSessionCtx.isProjectTrusted(),
51
53
  agents,
52
54
  agentName,
@@ -88,7 +90,7 @@ export async function executeSingle(
88
90
  content: [
89
91
  {
90
92
  type: "text" as const,
91
- text: `${result.name ? `${result.name} (${result.agent})` : `Agent ${result.agent}`} ${result.stopReason || "failed"}: ${errorMsg}`,
93
+ text: `${formatSubagentLabel(result)} ${result.stopReason || "failed"}: ${errorMsg}`,
92
94
  },
93
95
  ],
94
96
  details: makeDetails("single")([result]),
@@ -159,6 +161,7 @@ export async function executeParallel(
159
161
  },
160
162
  {
161
163
  ...extras,
164
+ settings: state.settings,
162
165
  namesFile: state.currentNamesFile || undefined,
163
166
  intelligencePresets: state.intelligencePresets,
164
167
  projectTrusted: state.latestSessionCtx?.cwd === defaultCwd && state.latestSessionCtx.isProjectTrusted(),
@@ -16,7 +16,7 @@ export function resolveDetailSessionDir(state: ExtensionState, record: SubagentN
16
16
  }
17
17
 
18
18
  export function readCurrentRegistry(state: ExtensionState): NamesRegistry | undefined {
19
- if (!state.currentNamesFile) return undefined;
19
+ if (state.disabled || !state.currentNamesFile) return undefined;
20
20
  try {
21
21
  return readNamesRegistry(state.currentNamesFile);
22
22
  } catch {
@@ -50,6 +50,7 @@ export function registerSubagentExpandCommand(state: ExtensionState): void {
50
50
  return items.length > 0 ? items : null;
51
51
  },
52
52
  handler: async (args: string, ctx: SessionContext) => {
53
+ if (state.disabled) return;
53
54
  const name = (args ?? "").trim().split(/\s+/)[0] ?? "";
54
55
  const uiAvailable = ctx?.mode === "tui" && ctx?.ui && typeof ctx.ui.custom === "function";
55
56
  if (!uiAvailable) {
@@ -2,7 +2,7 @@ import { createIntelligenceSchemas, validatePreparedArguments } from "./schemas.
2
2
  import { selectIntelligence } from "../intelligence.js";
3
3
  import { resolveLaunchModelSettings } from "../runner/arguments.js";
4
4
  import * as path from "node:path";
5
- import { discoverAgents } from "../agents.js";
5
+ import { DEFAULT_AGENT, discoverAgents } from "../agents.js";
6
6
  import {
7
7
  createBudget,
8
8
  isBranchBudgetAmount,
@@ -31,15 +31,21 @@ import {
31
31
  import { trackProgress } from "./progress.js";
32
32
  import { getSubagentsToolDescription } from "./prompts.js";
33
33
  import { ensureBudget, getParentModelForSubagent, getSessionDirForTask } from "./runtime.js";
34
- import { findRecoveryPlanIndex, prepareIntelligenceArguments, prepareRecoveryArguments } from "./schemas.js";
34
+ import {
35
+ findRecoveryPlanIndex,
36
+ getPreparedRecoveryPlan,
37
+ prepareIntelligenceArguments,
38
+ prepareRecoveryArguments,
39
+ } from "./schemas.js";
35
40
  import type { ExtensionState } from "./state.js";
36
41
 
37
42
  export function registerSubagentsTool(state: ExtensionState) {
38
- const parameters = createIntelligenceSchemas(state.intelligencePresets).subagents;
43
+ const hasAgentTypes = state.discoveredAgents.length > 0;
44
+ const parameters = createIntelligenceSchemas(state.intelligencePresets, state.settings, hasAgentTypes).subagents;
39
45
  state.pi.registerTool({
40
46
  name: SUBAGENT_TOOL_NAME,
41
47
  label: "Subagents",
42
- description: state.configuredToolPrompts[SUBAGENT_TOOL_NAME] ?? getSubagentsToolDescription(),
48
+ description: state.configuredToolPrompts[SUBAGENT_TOOL_NAME] ?? getSubagentsToolDescription(hasAgentTypes),
43
49
  parameters,
44
50
  prepareArguments(args) {
45
51
  return validatePreparedArguments(
@@ -48,6 +54,8 @@ export function registerSubagentsTool(state: ExtensionState) {
48
54
  prepareIntelligenceArguments(args, "tasks"),
49
55
  state.pendingResumePlans,
50
56
  state.intelligencePresets,
57
+ state.settings,
58
+ hasAgentTypes,
51
59
  ),
52
60
  );
53
61
  },
@@ -55,14 +63,17 @@ export function registerSubagentsTool(state: ExtensionState) {
55
63
  async execute(toolCallId, params, signal, onUpdate, ctx) {
56
64
  const toolResult = await (async () => {
57
65
  try {
66
+ if (!state.canDelegate) throw new Error("Subagent delegation is disabled for this session.");
58
67
  recordToolCallStart(toolCallId);
59
68
  updateLatestBroadcastTargets(state, undefined);
60
- const discovery = discoverAgents(ctx.cwd, "both");
61
- const agents = filterAgentsForCurrentLayer(discovery.agents, state.currentDepth, state.maxDepth);
69
+ const discovery = discoverAgents(ctx.cwd, "both", state.settings);
70
+ const agents = hasAgentTypes
71
+ ? filterAgentsForCurrentLayer(discovery.agents, state.currentDepth, state.maxDepth)
72
+ : [DEFAULT_AGENT];
62
73
 
63
74
  const makeDetails = makeDetailsFactory(discovery.projectAgentsDir, DEFAULT_DELEGATION_MODE);
64
75
 
65
- const tasks = params.tasks ?? [];
76
+ const tasks = (params.tasks ?? []).map((task) => ({ ...task, agent: task.agent ?? DEFAULT_AGENT.name }));
66
77
  if (tasks.length === 0) {
67
78
  return {
68
79
  content: [
@@ -77,7 +88,7 @@ export function registerSubagentsTool(state: ExtensionState) {
77
88
  }
78
89
 
79
90
  for (const [index, task] of tasks.entries()) {
80
- selectIntelligence(state.intelligencePresets, task.intelligence);
91
+ selectIntelligence(state.intelligencePresets, task.intelligence, state.settings);
81
92
  if (!isBranchBudgetAmount(task.max_subagents_allowed)) {
82
93
  throw new SubagentBudgetError(
83
94
  `tasks[${index}].max_subagents_allowed is required. Use a non-negative safe integer below Number.MAX_SAFE_INTEGER, excluding the assigned agent. Use 0 for a direct worker.`,
@@ -103,7 +114,7 @@ export function registerSubagentsTool(state: ExtensionState) {
103
114
  if (state.preventCycles) {
104
115
  const stack = new Set(state.ancestorAgentStack);
105
116
  tasks.forEach((task, index) => {
106
- if (stack.has(task.agent)) cyclicTaskIndexes.add(index);
117
+ if (hasAgentTypes && stack.has(task.agent)) cyclicTaskIndexes.add(index);
107
118
  });
108
119
  }
109
120
  const requested = new Set<string>();
@@ -112,7 +123,7 @@ export function registerSubagentsTool(state: ExtensionState) {
112
123
  });
113
124
 
114
125
  const requestedProjectAgents = getRequestedProjectAgents(agents, requested);
115
- const projectAgentConfirmationSetting = getProjectAgentConfirmationSetting();
126
+ const projectAgentConfirmationSetting = getProjectAgentConfirmationSetting(state.settings);
116
127
  const projectAgentSessionKey = getProjectAgentSessionKey(discovery.projectAgentsDir);
117
128
  const shouldConfirmProjectAgents =
118
129
  requestedProjectAgents.length > 0 &&
@@ -155,8 +166,32 @@ export function registerSubagentsTool(state: ExtensionState) {
155
166
  }
156
167
  }
157
168
 
158
- const resumePlanIndex = findRecoveryPlanIndex(tasks, state.pendingResumePlans, state.intelligencePresets);
169
+ const boundPlan = state.recoveryPlansByToolCallId?.get(toolCallId) ?? getPreparedRecoveryPlan(params);
170
+ const resumePlanIndex = boundPlan
171
+ ? state.pendingResumePlans.indexOf(boundPlan)
172
+ : findRecoveryPlanIndex(
173
+ tasks,
174
+ state.pendingResumePlans,
175
+ state.intelligencePresets,
176
+ state.settings,
177
+ hasAgentTypes,
178
+ );
179
+ if (
180
+ boundPlan &&
181
+ (resumePlanIndex < 0 ||
182
+ findRecoveryPlanIndex(tasks, [boundPlan], state.intelligencePresets, state.settings, hasAgentTypes) < 0)
183
+ ) {
184
+ throw new Error("Subagent recovery plan is no longer pending or its arguments have changed.");
185
+ }
159
186
  const resumePlan = resumePlanIndex >= 0 ? state.pendingResumePlans[resumePlanIndex] : null;
187
+ if (resumePlan) {
188
+ tasks.forEach((task, index) => {
189
+ if (!hasAgentTypes) task.agent = resumePlan.tasks[index].agent;
190
+ if (!agents.some((agent) => agent.name === task.agent)) {
191
+ agents.push({ ...DEFAULT_AGENT, name: task.agent });
192
+ }
193
+ });
194
+ }
160
195
  if (launchGeneration !== state.lifecycleGeneration || signal?.aborted)
161
196
  throw new SubagentBudgetError("Launch canceled or session changed. No slots were reserved.");
162
197
  const budgets: Array<SubagentBudget | undefined> = tasks.map(() => undefined);
@@ -197,6 +232,7 @@ export function registerSubagentsTool(state: ExtensionState) {
197
232
  }
198
233
 
199
234
  if (resumePlanIndex >= 0) state.pendingResumePlans.splice(resumePlanIndex, 1);
235
+ state.recoveryPlansByToolCallId?.delete(toolCallId);
200
236
 
201
237
  // Assign random durable human names unique across the whole tree. Resumed
202
238
  // runs keep the names already recorded in the previous results.
@@ -214,7 +250,7 @@ export function registerSubagentsTool(state: ExtensionState) {
214
250
  state.currentOwnerId,
215
251
  pendingAllocation.map(({ task, index }) => {
216
252
  const agentConfig = agents.find((agent) => agent.name === task.agent);
217
- const preset = selectIntelligence(state.intelligencePresets, task.intelligence);
253
+ const preset = selectIntelligence(state.intelligencePresets, task.intelligence, state.settings);
218
254
  return {
219
255
  agent: task.agent,
220
256
  task: task.task,
@@ -223,6 +259,7 @@ export function registerSubagentsTool(state: ExtensionState) {
223
259
  agentConfig ?? {},
224
260
  formatModelFlag(getParentModelForSubagent(state, ctx)),
225
261
  preset,
262
+ state.settings,
226
263
  ),
227
264
  tools: agentConfig?.tools,
228
265
  sessionDir: