@ferris1225/pi-subagents 4.3.31 → 4.3.33

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 (41) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/LICENSE +1 -1
  3. package/README.md +215 -273
  4. package/index.ts +15 -14
  5. package/package.json +10 -10
  6. package/skills/workflow/SKILL.md +226 -0
  7. package/src/configuration/config.ts +17 -121
  8. package/src/configuration/models.ts +1 -1
  9. package/src/configuration/setup.ts +80 -176
  10. package/src/configuration/ui.ts +28 -66
  11. package/src/delegation/agents.ts +79 -209
  12. package/src/delegation/builtin-agents.ts +60 -0
  13. package/src/delegation/dispatch.ts +32 -149
  14. package/src/delegation/prompt.ts +7 -5
  15. package/src/execution/rpc-control.ts +6 -2
  16. package/src/execution/rpc-run.ts +60 -20
  17. package/src/execution/spawn.ts +17 -28
  18. package/src/isolation/git-command.ts +1 -2
  19. package/src/isolation/recovery.ts +1 -1
  20. package/src/isolation/temp-hygiene.ts +2 -2
  21. package/src/isolation/worktree.ts +31 -17
  22. package/src/lifecycle/completion.ts +1 -1
  23. package/src/lifecycle/dispatch-core.ts +142 -0
  24. package/src/lifecycle/durable.ts +3 -3
  25. package/src/lifecycle/runtime.ts +34 -1
  26. package/src/lifecycle/thread-lifecycle.ts +36 -25
  27. package/src/lifecycle/thread-shared.ts +11 -4
  28. package/src/lifecycle/tools.ts +84 -11
  29. package/src/presentation/monitor.ts +39 -17
  30. package/src/presentation/widget.ts +2 -2
  31. package/src/workflow/durable.ts +195 -0
  32. package/src/workflow/engine.ts +625 -0
  33. package/src/workflow/files.ts +217 -0
  34. package/src/workflow/plan.ts +340 -0
  35. package/src/workflow/state.ts +48 -0
  36. package/src/workflow/tool.ts +269 -0
  37. package/workflows/code-review.md +57 -0
  38. package/workflows/migration.md +52 -0
  39. package/workflows/research.md +47 -0
  40. package/agents/artisan.md +0 -18
  41. package/agents/scout.md +0 -19
package/index.ts CHANGED
@@ -3,10 +3,11 @@
3
3
  *
4
4
  * Assembly point: builds the shared runtime and registers everything.
5
5
  * The heavy lifting lives in focused modules:
6
- * - delegation/ — role discovery, routing prompts, and tool contract
6
+ * - delegation/ — built-in roles, routing prompts, and tool contract
7
7
  * - configuration/ — persisted settings, model routes, and setup UI
8
8
  * - execution/ — process queue, RPC transport/control, and model handoff
9
9
  * - lifecycle/ — durable threads, restoration, controls, and delivery
10
+ * - workflow/ — dependency-graph plans, discovery, and the graph runner
10
11
  * - isolation/ — Git worktrees, recovery, and temporary-state hygiene
11
12
  * - presentation/ — announcements, formatting, monitor, and the active-run
12
13
  * widget
@@ -21,21 +22,20 @@
21
22
 
22
23
  import { getAgentDir, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
23
24
  import { Text } from "@earendil-works/pi-tui";
24
- import { getConfigPath, loadConfig } from "./src/configuration/config.ts";
25
+ import { getConfigPath } from "./src/configuration/config.ts";
25
26
  import { runSetup } from "./src/configuration/setup.ts";
26
- import { discoverAgents } from "./src/delegation/agents.ts";
27
+ import { loadBuiltinAgents } from "./src/delegation/agents.ts";
27
28
  import { registerSubagentTool } from "./src/delegation/dispatch.ts";
28
29
  import { buildDelegationDirective, installDelegationSections } from "./src/delegation/prompt.ts";
29
30
  import { currentSubagentDepth } from "./src/execution/spawn.ts";
31
+ import { createDispatchCore } from "./src/lifecycle/dispatch-core.ts";
30
32
  import { createRuntime } from "./src/lifecycle/runtime.ts";
31
33
  import { bootstrapDurableState } from "./src/lifecycle/thread-restore.ts";
32
34
  import { registerLookupTools } from "./src/lifecycle/tools.ts";
35
+ import { registerWorkflowTool, restoreWorkflowState } from "./src/workflow/tool.ts";
33
36
  import { registerAnnouncements } from "./src/presentation/announcements.ts";
34
- import { matchRunIds } from "./src/presentation/format.ts";
35
37
  import { clearActiveRunsWidget } from "./src/presentation/widget.ts";
36
38
 
37
- export { matchRunIds };
38
-
39
39
  export default function (pi: ExtensionAPI): void {
40
40
  const configPath = getConfigPath(getAgentDir());
41
41
  const runtime = createRuntime(pi, configPath);
@@ -67,11 +67,16 @@ export default function (pi: ExtensionAPI): void {
67
67
  await runtime.shutdown();
68
68
  });
69
69
 
70
- registerSubagentTool(pi, runtime);
70
+ // One dispatcher serves both delegation tools, so a workflow node is an
71
+ // ordinary managed run: same queue pacing, admission, isolation, and
72
+ // durable checkpointing.
73
+ const dispatchCore = createDispatchCore(runtime);
74
+ registerSubagentTool(pi, runtime, dispatchCore);
75
+ registerWorkflowTool(pi, runtime, dispatchCore);
71
76
  registerLookupTools(pi, runtime);
72
77
 
73
78
  pi.registerCommand("subagents-setup", {
74
- description: "Configure pi-subagents: agents, models, and per-role thinking",
79
+ description: "Configure pi-subagents: model and thinking per role",
75
80
  handler: async (_args, ctx) => {
76
81
  await runSetup(ctx, configPath);
77
82
  },
@@ -79,6 +84,7 @@ export default function (pi: ExtensionAPI): void {
79
84
 
80
85
  pi.on("session_start", async (_event, ctx) => {
81
86
  await bootstrapDurableState(runtime, ctx.cwd);
87
+ await restoreWorkflowState(runtime, ctx);
82
88
  });
83
89
  registerAnnouncements(pi, runtime);
84
90
 
@@ -86,12 +92,7 @@ export default function (pi: ExtensionAPI): void {
86
92
  // A full systemPrompt return forces an opaque prompt and invalidates the cache.
87
93
  pi.on("before_agent_start", async (event, ctx) => {
88
94
  await runtime.durableRestore;
89
- const config = await loadConfig(configPath);
90
- const { agents } = discoverAgents(ctx.cwd, {
91
- scope: config.agentScope,
92
- enabledNames: config.enabledAgents,
93
- projectTrusted: ctx.isProjectTrusted?.() === true,
94
- });
95
+ const agents = loadBuiltinAgents();
95
96
  const sources = [...runtime.threads.values()];
96
97
  const sections = event.systemPromptOptions?.sections;
97
98
  if (sections) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ferris1225/pi-subagents",
3
- "version": "4.3.31",
3
+ "version": "4.3.33",
4
4
  "description": "A managed sub-agent team for pi: lightweight scout research and artisan implementation, one-shot runs, read-only status, and Git worktree isolation.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -25,7 +25,8 @@
25
25
  "files": [
26
26
  "index.ts",
27
27
  "src",
28
- "agents",
28
+ "skills",
29
+ "workflows",
29
30
  "README.md",
30
31
  "CHANGELOG.md",
31
32
  "LICENSE"
@@ -33,27 +34,26 @@
33
34
  "pi": {
34
35
  "extensions": [
35
36
  "./index.ts"
37
+ ],
38
+ "skills": [
39
+ "./skills"
36
40
  ]
37
41
  },
38
42
  "scripts": {
39
43
  "check": "tsc --noEmit && npm test",
40
- "test": "node --experimental-transform-types --test test/*.test.ts",
44
+ "test": "node --test test/*.test.ts",
41
45
  "prepack": "npm run check"
42
46
  },
43
47
  "peerDependencies": {
44
- "@earendil-works/pi-agent-core": ">=1.0.0",
45
48
  "@earendil-works/pi-ai": ">=1.0.0",
46
49
  "@earendil-works/pi-coding-agent": ">=1.0.0",
47
- "@earendil-works/pi-server": ">=1.0.0",
48
50
  "@earendil-works/pi-tui": ">=1.0.0",
49
51
  "typebox": "*"
50
52
  },
51
53
  "devDependencies": {
52
- "@earendil-works/pi-agent-core": "^1.3.0",
53
- "@earendil-works/pi-ai": "^1.3.0",
54
- "@earendil-works/pi-coding-agent": "^1.3.0",
55
- "@earendil-works/pi-server": "^1.1.0",
56
- "@earendil-works/pi-tui": "^1.3.0",
54
+ "@earendil-works/pi-ai": "^1.4.0",
55
+ "@earendil-works/pi-coding-agent": "^1.4.0",
56
+ "@earendil-works/pi-tui": "^1.4.0",
57
57
  "@types/node": "^22.10.0",
58
58
  "typebox": "^1.3.27",
59
59
  "typescript": "^5.9.0"
@@ -0,0 +1,226 @@
1
+ ---
2
+ name: workflow
3
+ description: Plan and run a multi-phase sub-agent job as a dependency graph with subagent_workflow — deciding when a graph is worth it, slicing phases, wiring dependsOn, writing briefs that survive their own placeholders, and reading the one summary it returns. Use for requests with several ordered phases (survey, parallel changes, then a gate), or when a saved graph under .pi/workflows/ should run by name.
4
+ ---
5
+
6
+ # Planning multi-agent work as a workflow
7
+
8
+ `subagent_workflow` runs a graph of ordinary sub-agent phases. You declare the
9
+ nodes and their prerequisites once; the runtime starts each node the moment its
10
+ prerequisites settle and a process slot frees, and wakes you once with a summary
11
+ of the whole graph. Nothing dispatches the next wave on your behalf except the
12
+ runtime.
13
+
14
+ Two things this changes about delegating: you stop paying a model turn between
15
+ waves, and the graph — not your attention — is what remembers which phase is
16
+ next. Two things it does not change: every node is still a one-shot leaf run
17
+ with its own context, and main still owns architecture, integration, the final
18
+ gate, and release.
19
+
20
+ ## 1. Is a graph the right tool?
21
+
22
+ | The request | The tool |
23
+ | --- | --- |
24
+ | One thing, one owner | `subagent` (single) |
25
+ | A few independent lookups nobody reads before the end | `subagent` (`tasks`), in parallel |
26
+ | One phase whose result you will read before deciding the next step | `subagent`; decide in main |
27
+ | A small edit already understood in the current context | main, no child |
28
+ | Several phases with real ordering, and the ordering is known now | `subagent_workflow` |
29
+ | The same multi-phase job you will run again on another change | `subagent_workflow` with a saved definition |
30
+
31
+ A graph earns its cost when **the dependency structure is already known** and
32
+ **the phases are each substantial**. If you would have to look at phase one's
33
+ answer to know what phase two is, you cannot write the graph yet: run phase one
34
+ with `subagent` and write the graph afterwards. If every phase is a one-line
35
+ read, the graph is overhead — do it in main.
36
+
37
+ A workflow is a forced choice, not a default. The user asking for "a workflow"
38
+ or naming a saved one is binding; otherwise apply the table.
39
+
40
+ ## 2. Shape
41
+
42
+ ```ts
43
+ subagent_workflow({
44
+ name: "auth-fix", // shown in the widget/status; namespaces phase ids
45
+ description: "Map the race, fix it, gate it.", // one line, becomes the summary's subtitle
46
+ nodes: [
47
+ { id: "map", agent: "scout", task: "Map the refresh race in src/auth. Cite path:line." },
48
+ { id: "fix", agent: "artisan", task: "Fix it. Evidence:\n{{map}}", dependsOn: ["map"],
49
+ scope: { paths: ["src/auth"] } },
50
+ { id: "tests", agent: "artisan", task: "Add regression tests for the race. Evidence:\n{{map}}",
51
+ dependsOn: ["map"], scope: { paths: ["test/auth.test.ts"] } },
52
+ { id: "gate", agent: "artisan", task: "Run the repository's checks and fix only what this change broke.\nFix:\n{{fix}}\nTests:\n{{tests}}",
53
+ dependsOn: ["fix", "tests"] },
54
+ ],
55
+ })
56
+ ```
57
+
58
+ - `id` — identifies the node in `dependsOn` and in placeholders. Unique per graph.
59
+ - `dependsOn` — start only after these complete. Omit for work that can begin now.
60
+ - `task` — the brief (section 5). Placeholders allowed only for nodes it waits for.
61
+ - `agent`, `scope`, `cwd`, `isolation`, `phaseId` — as for `subagent`.
62
+ - Or run a saved definition: `subagent_workflow({ workflow: "code-review" })` /
63
+ `subagent_workflow({ file: ".pi/workflows/code-review.md" })`.
64
+
65
+ The call returns a launch receipt and the graph runs in the background. One
66
+ completion message arrives when it settles. Do not poll it.
67
+
68
+ ## 3. Topology: fresh eyes, then deterministic proof
69
+
70
+ The shapes that are worth writing, in the order they usually appear:
71
+
72
+ - **Survey → act.** One read-only node establishes the facts; writers depend on it
73
+ and quote it. Never let a writer re-derive what a scout already established.
74
+ - **Fan-out with a join.** Independent slices of one plan run at the same time; a
75
+ join node depends on all of them. Declare disjoint `scope.paths` per slice —
76
+ the compiler rejects overlapping scopes between nodes with no dependency edge.
77
+ - **Independent confirmation.** A node that *produced* a finding cannot see its
78
+ own gap. Give every claim the user will act on a separate node that tries to
79
+ disprove it ("reproduce this, or say what the code actually does"), and a
80
+ different lens per reviewer rather than the same prompt twice.
81
+ - **A closing gate.** The last node runs the project's own checks. Prefer
82
+ commands over opinions: the repository's test suite, typecheck, build, or the
83
+ verification line its README names. Ask for the strongest tier it has, not the
84
+ fastest one.
85
+
86
+ One deliverable gets one confirmation mechanism. A reviewer loop plus a
87
+ confirmer plus a reader on the same artifact is four sessions re-reading one
88
+ piece of work.
89
+
90
+ ## 4. What the runtime guarantees, and what it does not
91
+
92
+ - **Dependents start on settlement, not on wall-clock.** A node's result is
93
+ registered only after its isolated worktree is integrated, so a dependent sees
94
+ the files its prerequisite actually left behind.
95
+ - **Failure is contained.** A failed node blocks only its dependents. Independent
96
+ branches keep running. The summary states completed, failed, and
97
+ never-ran-with-why.
98
+ - **No retries, no resumption.** Nodes are one-shot. Main finishes incomplete
99
+ work from the child's partial edits and retained artifacts; a different
100
+ deliverable needs a new graph. This mirrors the one-shot rule for `subagent`.
101
+ - **A stopped graph stops cleanly.** `subagent_stop({ workflow: id })` prevents
102
+ dependents from starting and cancels running nodes; the summary still reports
103
+ what had completed.
104
+ - **An interrupted graph is explained, not resumed.** If the session ends
105
+ mid-graph, the next session's start notice and `subagent_status({ workflow })`
106
+ report which nodes completed and which were still running, with their run ids.
107
+ - **Capacity is pacing, not refusal.** `maxConcurrentAgents` limits simultaneous
108
+ child processes; a wider graph queues and starts as slots free. Queue position
109
+ never changes dependency order.
110
+
111
+ ## 5. Briefs
112
+
113
+ A node has no access to your conversation. Its brief carries:
114
+
115
+ 1. the outcome and the done condition,
116
+ 2. the facts it needs, including upstream answers via placeholders,
117
+ 3. the boundary (what not to touch, what not to decide),
118
+ 4. the output you want back.
119
+
120
+ Write the brief the way you would brief a competent colleague who was not in the
121
+ meeting. Name paths and symbols; do not paste file contents — every node has its
122
+ own file tools, and a pasted file costs tokens it could have read.
123
+
124
+ Ask for failures, not approval. "Is this good?" gets a yes; "what would break
125
+ this, and what is missing?" gets findings. Say "do not edit any file" when a node
126
+ is only judging.
127
+
128
+ ## 6. Placeholders
129
+
130
+ | Placeholder | Expands to |
131
+ | --- | --- |
132
+ | `{{id}}` | that node's final answer (bounded; long answers are clipped with a pointer) |
133
+ | `{{id.status}}` | `completed` / `failed` / `blocked` / `stopped` |
134
+ | `{{id.runId}}` | that node's run id, for follow-up inspection |
135
+ | `{{id.error}}` | the failure reason, or `(no error reported)` |
136
+
137
+ A placeholder may only name a node the current node waits for — directly or
138
+ through the chain. That rule is enforced at compile time, because reading a
139
+ sibling's answer would mean reading something that may not have run yet. If you
140
+ want two branches to read each other, they are not independent: join them first.
141
+
142
+ Keep results narrow. A node that returns a whole file makes every dependent pay
143
+ for it; a node that returns paths and conclusions does not.
144
+
145
+ ## 7. Scope and isolation
146
+
147
+ `scope` is admission metadata, not access control. Declare the exact paths a
148
+ node expects to write:
149
+
150
+ - Two nodes with no dependency edge may not claim overlapping paths — the graph
151
+ is rejected before anything starts. A dependency edge makes the overlap
152
+ intentional (a fix, then its own test file).
153
+ - Externally, declared scopes are still checked against live runs at dispatch
154
+ time, so a node that conflicts with unrelated work fails alone.
155
+ - Write-capable nodes default to a detached Git worktree in a graph, and their
156
+ changes are integrated once, when the node settles. The checkout therefore
157
+ always looks like the graph's completed work — which is exactly what the next
158
+ node needs to read.
159
+
160
+ ## 8. Saved definitions
161
+
162
+ - Project: `.pi/workflows/<name>.json` or `.pi/workflows/<name>.md`
163
+ - User: `~/.pi/agent/workflows/`
164
+ - Shipped templates: this package's `workflows/` directory (`code-review`,
165
+ `research`, `migration`)
166
+
167
+ A Markdown definition carries prose plus one ```json fenced block with the plan
168
+ (or a bare node array); JSON carries the plan object. Project definitions load
169
+ only in a trusted project. Same-name precedence: project > user > builtin.
170
+
171
+ Save a graph when it will run again, when a reviewer should read the plan before
172
+ it runs, or when the phases are long enough that you want them in version
173
+ control. Run it by name; do not restate it inline.
174
+
175
+ **Re-running a graph in the same session is a duplicate phase.** Derived phase
176
+ ids are `<workflow-slug>.<node-id>`, and a settled phase stays owned for the
177
+ session. To run the same shape on new work, either start a new session or vary
178
+ the briefs (a new commit, a new target) so the phases are genuinely different.
179
+
180
+ ## 9. Cost
181
+
182
+ Every node is a full model session with its own context, and the summary carries
183
+ each node's answer. Budget accordingly:
184
+
185
+ - Prefer the fewest nodes that still give each phase one owner and each claim one
186
+ confirmer.
187
+ - Keep node answers short: conclusions, paths, `command → result`.
188
+ - Do not add a node to fill a free process slot, and do not split one tightly
189
+ coupled change across nodes.
190
+
191
+ ## 10. Anti-patterns
192
+
193
+ | What you wrote | What it costs |
194
+ | --- | --- |
195
+ | A graph for a task with no real ordering | A model turn saved, two sessions wasted |
196
+ | A node whose brief re-derives what a scout already established | Paying twice for the same reading |
197
+ | `{{sibling}}` from a node that does not wait for it | Compile error; add the dependency or join first |
198
+ | Two writers with overlapping `scope` and no edge between them | The whole graph is rejected before any node starts |
199
+ | A reviewer asked "is this good?" | It approves; ask what would break it |
200
+ | A gate node asked to judge quality instead of running the tests | An opinion where an exit code would have decided |
201
+ | Retrying a failed node inside another node | Duplicate phase; main finishes the work instead |
202
+ | Twenty nodes over one small change | Twenty contexts, one deliverable |
203
+ | Reporting unverified findings as facts | The summary cannot tell "seen" from "suspected" |
204
+
205
+ ## 11. Reading the summary
206
+
207
+ One completion message per graph:
208
+
209
+ ```text
210
+ ### workflow auth-fix completed (4/4 completed)
211
+ - map (scout) completed · run #12 · 1m02s
212
+ - fix (artisan) completed · run #13 · 4m11s
213
+ - tests (artisan) completed · run #15 · 2m40s
214
+ - gate (artisan) completed · run #16 · 6m05s
215
+
216
+ Node answers:
217
+ #### map
218
+ …
219
+ Totals: 4 nodes · anthropic/claude-sonnet-4: ↓48.0k $0.8200
220
+ ```
221
+
222
+ - Node answers are clipped here; the full report file is named when that happens.
223
+ - `failed` / `never ran (blocked)` lines say why, and each run keeps its own
224
+ retained artifacts.
225
+ - Main then does what children cannot: inspect the integrated diff, run the gate
226
+ if the graph's gate node could not, and report only checks that actually ran.
@@ -2,37 +2,29 @@
2
2
  * Configuration load/save for pi-subagents.
3
3
  *
4
4
  * Config lives at <agentDir>/pi-subagents.json (agentDir defaults to ~/.pi/agent
5
- * and honors PI_CODING_AGENT_DIR). Parsing is defensive: invalid fields fall back
6
- * to defaults instead of throwing, so a hand-edited or partially-written file can
7
- * never break the extension at runtime. Unknown keys from older versions are
8
- * dropped and the normalized shape persisted back on load.
5
+ * and honors PI_CODING_AGENT_DIR). The only user-tunable surface is the model
6
+ * and thinking level per role; the two built-in roles are always enabled and
7
+ * every operational default is a constant. Parsing is defensive: invalid
8
+ * fields fall back to defaults instead of throwing, so a hand-edited or
9
+ * partially-written file can never break the extension at runtime. Unknown
10
+ * keys from older versions are dropped and the normalized shape persisted back
11
+ * on load.
9
12
  */
10
13
 
11
14
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
12
15
  import { dirname, join } from "node:path";
13
16
  import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
14
- import { MAX_SUBAGENT_CONCURRENCY } from "../execution/background.ts";
15
17
 
16
- /** Full catalog of agents shipped with the package (selectable in /subagents-setup). */
18
+ /** Full catalog of agents shipped with the package; all of them always run. */
17
19
  export const BUILTIN_AGENT_NAMES = ["scout", "artisan"] as const;
18
20
 
19
- // Catalog assumed for configs written before built-in adoption tracking.
20
- // Keep this frozen so future built-ins are still recognized as new.
21
- const INITIAL_AGENT_NAMES = ["scout", "artisan"] as const;
22
-
23
- /** Agents enabled out of the box on a fresh install. */
24
- export const DEFAULT_ENABLED_AGENTS: readonly string[] = [...BUILTIN_AGENT_NAMES];
25
-
26
- export const AGENT_SCOPE_VALUES = ["user", "project", "both"] as const;
27
- export type AgentScope = (typeof AGENT_SCOPE_VALUES)[number];
28
-
29
21
  /** Thinking levels accepted by pi's `--thinking` option. */
30
- export const THINKING_LEVEL_VALUES = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
22
+ const THINKING_LEVEL_VALUES = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
31
23
  export type ThinkingLevel = (typeof THINKING_LEVEL_VALUES)[number];
32
24
  export const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
33
25
 
34
26
  /** Role-owned default reasoning strength. A `/subagents-setup` override wins;
35
- * there is no per-call or frontmatter thinking. */
27
+ * there is no per-call thinking. */
36
28
  export function roleThinkingLevel(agentName: string): ThinkingLevel {
37
29
  switch (agentName) {
38
30
  case "scout":
@@ -68,62 +60,28 @@ export function agentProfile(name: string): AgentProfile | undefined {
68
60
  }
69
61
 
70
62
  /** How many lines of a sub-agent result the completion message may carry.
71
- * Default: 40 — wide fan-outs multiply completion blocks, so deliveries stay
72
- * compact and the full text lives in the on-disk result artifact. */
63
+ * Wide fan-outs multiply completion blocks, so deliveries stay compact and the
64
+ * full text lives in the on-disk result artifact. */
73
65
  export const DEFAULT_MAX_RESULT_LINES = 40;
74
- /** Upper bound accepted for maxResultLines (defensive clamp). */
75
- export const MAX_RESULT_LINES_LIMIT = 2000;
76
66
 
77
67
  const CONFIG_FILE_NAME = "pi-subagents.json";
78
68
 
79
- /**
80
- * Default idle timeout in seconds: a sub-agent whose stdout (JSON event stream)
81
- * goes silent for this long is terminated; a selected model then hands the
82
- * retained session to current main. 0 disables the watchdog. Default: 1800.
83
- */
69
+ /** Idle timeout in seconds: a sub-agent whose stdout (JSON event stream) goes
70
+ * silent for this long is terminated; a configured agent model then hands
71
+ * off to the current main model. */
84
72
  export const DEFAULT_IDLE_TIMEOUT_SEC = 1800;
85
- /** Upper bound accepted for idleTimeoutSec (defensive clamp). 0 disables. */
86
- export const IDLE_TIMEOUT_SEC_LIMIT = 3600;
87
73
 
88
74
  export interface SubagentsConfig {
89
- /** Agent names that are discoverable and injected. Fresh-install default: every built-in agent. */
90
- enabledAgents: string[];
91
- /** Agent names already presented by setup. Built-ins use this catalog to opt in
92
- * once on upgrade without undoing a later explicit disable. */
93
- knownAgents: string[];
94
75
  /** Per-agent model override, keyed by agent name, as "provider/model-id". */
95
76
  agentModels: Record<string, string>;
96
77
  /** Optional per-agent thinking override from `/subagents-setup`. Missing =
97
78
  * the role default from `roleThinkingLevel`. */
98
79
  agentThinkingLevels: Record<string, ThinkingLevel>;
99
- /**
100
- * Max lines of a sub-agent result carried in the completion message. Longer
101
- * results are truncated; the full text is written to a temp file whose path
102
- * is included in the message. Default: 40.
103
- */
104
- maxResultLines: number;
105
- /** Maximum simultaneous child processes. 0 keeps automatic host capacity
106
- * (4–6); 1–6 selects an explicit limit, applied at the next dispatch. */
107
- maxConcurrentAgents: number;
108
- /** Which agent directories to discover from. Default: "user". */
109
- agentScope: AgentScope;
110
- /**
111
- * Idle timeout in seconds: a sub-agent whose stdout (JSON event stream) goes
112
- * silent for this long is terminated; a configured agent model then hands
113
- * off to the current main model. 0 disables the idle watchdog. Default: 1800.
114
- */
115
- idleTimeoutSec: number;
116
80
  }
117
81
 
118
82
  export const DEFAULT_CONFIG: SubagentsConfig = {
119
- enabledAgents: [...DEFAULT_ENABLED_AGENTS],
120
- knownAgents: [...BUILTIN_AGENT_NAMES],
121
83
  agentModels: {},
122
84
  agentThinkingLevels: {},
123
- maxResultLines: DEFAULT_MAX_RESULT_LINES,
124
- maxConcurrentAgents: 0,
125
- agentScope: "user",
126
- idleTimeoutSec: DEFAULT_IDLE_TIMEOUT_SEC,
127
85
  };
128
86
 
129
87
  export function getConfigPath(agentDir: string = getAgentDir()): string {
@@ -134,10 +92,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
134
92
  return typeof value === "object" && value !== null && !Array.isArray(value);
135
93
  }
136
94
 
137
- function isAgentScope(value: unknown): value is AgentScope {
138
- return typeof value === "string" && (AGENT_SCOPE_VALUES as readonly string[]).includes(value);
139
- }
140
-
141
95
  function isModelReference(value: unknown): value is string {
142
96
  if (typeof value !== "string") return false;
143
97
  const normalized = value.trim();
@@ -145,12 +99,6 @@ function isModelReference(value: unknown): value is string {
145
99
  return slash > 0 && slash < normalized.length - 1 && !/\s/u.test(normalized);
146
100
  }
147
101
 
148
- /** Clamp a raw value to a positive integer within [1, upper]; undefined when invalid. */
149
- function clampCount(value: unknown, upper: number): number | undefined {
150
- if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
151
- return Math.max(1, Math.min(upper, Math.round(value)));
152
- }
153
-
154
102
  /**
155
103
  * Merge a raw parsed JSON value over the defaults, dropping invalid fields.
156
104
  * Exported for tests.
@@ -159,22 +107,6 @@ export function normalizeConfig(raw: unknown): SubagentsConfig {
159
107
  const config = defaultConfig();
160
108
  if (!isRecord(raw)) return config;
161
109
 
162
- if (Array.isArray(raw.enabledAgents)) {
163
- const names = raw.enabledAgents.filter(
164
- (name): name is string => typeof name === "string" && name.trim().length > 0,
165
- );
166
- // An explicitly empty array is honored; duplicates collapse.
167
- config.enabledAgents = [...new Set(names.map((name) => name.trim()))];
168
- }
169
-
170
- const rawKnownAgents = Array.isArray(raw.knownAgents) ? raw.knownAgents : INITIAL_AGENT_NAMES;
171
- config.knownAgents = [...new Set(rawKnownAgents.filter(
172
- (name): name is string => typeof name === "string" && name.trim().length > 0,
173
- ).map((name) => name.trim()))];
174
- for (const name of config.enabledAgents) {
175
- if (!config.knownAgents.includes(name)) config.knownAgents.push(name);
176
- }
177
-
178
110
  if (isRecord(raw.agentModels)) {
179
111
  for (const [rawKey, value] of Object.entries(raw.agentModels)) {
180
112
  const key = rawKey.trim();
@@ -197,51 +129,16 @@ export function normalizeConfig(raw: unknown): SubagentsConfig {
197
129
  }
198
130
  }
199
131
 
200
- const maxResultLines = clampCount(raw.maxResultLines, MAX_RESULT_LINES_LIMIT);
201
- if (maxResultLines !== undefined) config.maxResultLines = maxResultLines;
202
-
203
- if (typeof raw.maxConcurrentAgents === "number" && Number.isFinite(raw.maxConcurrentAgents)) {
204
- config.maxConcurrentAgents = Math.max(0, Math.min(MAX_SUBAGENT_CONCURRENCY, Math.round(raw.maxConcurrentAgents)));
205
- }
206
-
207
- if (isAgentScope(raw.agentScope)) {
208
- config.agentScope = raw.agentScope;
209
- }
210
-
211
- // 0 disables the idle watchdog; otherwise clamp to [0, upper].
212
- if (typeof raw.idleTimeoutSec === "number" && Number.isFinite(raw.idleTimeoutSec)) {
213
- config.idleTimeoutSec = Math.max(0, Math.min(IDLE_TIMEOUT_SEC_LIMIT, Math.round(raw.idleTimeoutSec)));
214
- }
215
-
216
132
  return config;
217
133
  }
218
134
 
219
135
  function defaultConfig(): SubagentsConfig {
220
136
  return {
221
- ...DEFAULT_CONFIG,
222
- enabledAgents: [...DEFAULT_CONFIG.enabledAgents],
223
- knownAgents: [...DEFAULT_CONFIG.knownAgents],
224
137
  agentModels: {},
225
138
  agentThinkingLevels: {},
226
139
  };
227
140
  }
228
141
 
229
- function adoptNewBuiltins(config: SubagentsConfig): SubagentsConfig {
230
- const known = new Set(config.knownAgents);
231
- const fresh = BUILTIN_AGENT_NAMES.filter((name) => !known.has(name));
232
- if (fresh.length === 0) return config;
233
- return {
234
- ...config,
235
- enabledAgents: [...new Set([...config.enabledAgents, ...fresh])],
236
- knownAgents: [...known, ...fresh],
237
- };
238
- }
239
-
240
- export interface LoadConfigOptions {
241
- /** Disable read-time canonicalization for transactional UI sessions. */
242
- persistNormalization?: boolean;
243
- }
244
-
245
142
  /**
246
143
  * Load config. A missing file is a normal state and yields the defaults (not an error).
247
144
  * A corrupt file also falls back to defaults rather than throwing, so startup never breaks.
@@ -249,7 +146,6 @@ export interface LoadConfigOptions {
249
146
  */
250
147
  export async function loadConfig(
251
148
  configPath: string = getConfigPath(),
252
- options: LoadConfigOptions = {},
253
149
  ): Promise<SubagentsConfig> {
254
150
  let text: string;
255
151
  try {
@@ -266,10 +162,10 @@ export async function loadConfig(
266
162
  return defaultConfig();
267
163
  }
268
164
 
269
- const config = adoptNewBuiltins(normalizeConfig(parsed));
165
+ const config = normalizeConfig(parsed);
270
166
 
271
167
  // Persist the canonical shape when invalid or unknown fields were omitted.
272
- if (options.persistNormalization !== false && JSON.stringify(config) !== JSON.stringify(parsed)) {
168
+ if (JSON.stringify(config) !== JSON.stringify(parsed)) {
273
169
  try {
274
170
  await saveConfig(config, configPath);
275
171
  } catch {
@@ -64,7 +64,7 @@ const RENAMED_PROVIDER_IDS: Readonly<Record<string, string>> = {
64
64
  };
65
65
 
66
66
  /** Stored ref plus the renamed provider id, when Pi published one. */
67
- export function modelRefAliases(ref: string): readonly string[] {
67
+ function modelRefAliases(ref: string): readonly string[] {
68
68
  const normalized = ref.trim();
69
69
  const slash = normalized.indexOf("/");
70
70
  if (slash <= 0 || slash >= normalized.length - 1) return [normalized];