@ferris1225/pi-subagents 4.3.33 → 5.0.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +32 -349
  2. package/README.md +130 -549
  3. package/index.ts +4 -2
  4. package/package.json +1 -1
  5. package/skills/workflow/SKILL.md +52 -31
  6. package/src/configuration/config.ts +4 -4
  7. package/src/configuration/setup.ts +88 -229
  8. package/src/configuration/ui.ts +107 -129
  9. package/src/delegation/builtin-agents.ts +9 -9
  10. package/src/delegation/dispatch.ts +9 -6
  11. package/src/delegation/prompt.ts +7 -8
  12. package/src/execution/cli-run.ts +364 -0
  13. package/src/execution/process-tree.ts +1 -1
  14. package/src/execution/{rpc-control.ts → run-control.ts} +15 -33
  15. package/src/execution/spawn.ts +33 -185
  16. package/src/isolation/temp-hygiene.ts +2 -3
  17. package/src/lifecycle/cancellation.ts +36 -0
  18. package/src/lifecycle/completion.ts +1 -1
  19. package/src/lifecycle/dispatch-core.ts +0 -1
  20. package/src/lifecycle/durable.ts +1 -1
  21. package/src/lifecycle/runtime.ts +42 -29
  22. package/src/lifecycle/stop.ts +175 -0
  23. package/src/lifecycle/thread-lifecycle.ts +21 -15
  24. package/src/lifecycle/thread-restore.ts +3 -3
  25. package/src/lifecycle/tools.ts +18 -173
  26. package/src/presentation/format.ts +2 -5
  27. package/src/presentation/monitor.ts +16 -1
  28. package/src/presentation/widget.ts +140 -175
  29. package/src/workflow/engine.ts +101 -32
  30. package/src/workflow/files.ts +10 -32
  31. package/src/workflow/plan.ts +61 -13
  32. package/src/workflow/state.ts +4 -3
  33. package/src/workflow/tool.ts +38 -10
  34. package/workflows/code-review.md +12 -7
  35. package/workflows/migration.md +14 -26
  36. package/workflows/research.md +6 -5
  37. package/src/execution/rpc-run.ts +0 -889
package/index.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * The heavy lifting lives in focused modules:
6
6
  * - delegation/ — built-in roles, routing prompts, and tool contract
7
7
  * - configuration/ — persisted settings, model routes, and setup UI
8
- * - execution/ — process queue, RPC transport/control, and model handoff
8
+ * - execution/ — process queue, native JSON CLI/control, and model handoff
9
9
  * - lifecycle/ — durable threads, restoration, controls, and delivery
10
10
  * - workflow/ — dependency-graph plans, discovery, and the graph runner
11
11
  * - isolation/ — Git worktrees, recovery, and temporary-state hygiene
@@ -29,6 +29,7 @@ import { registerSubagentTool } from "./src/delegation/dispatch.ts";
29
29
  import { buildDelegationDirective, installDelegationSections } from "./src/delegation/prompt.ts";
30
30
  import { currentSubagentDepth } from "./src/execution/spawn.ts";
31
31
  import { createDispatchCore } from "./src/lifecycle/dispatch-core.ts";
32
+ import { registerCancellationHooks } from "./src/lifecycle/cancellation.ts";
32
33
  import { createRuntime } from "./src/lifecycle/runtime.ts";
33
34
  import { bootstrapDurableState } from "./src/lifecycle/thread-restore.ts";
34
35
  import { registerLookupTools } from "./src/lifecycle/tools.ts";
@@ -74,6 +75,7 @@ export default function (pi: ExtensionAPI): void {
74
75
  registerSubagentTool(pi, runtime, dispatchCore);
75
76
  registerWorkflowTool(pi, runtime, dispatchCore);
76
77
  registerLookupTools(pi, runtime);
78
+ registerCancellationHooks(pi, runtime);
77
79
 
78
80
  pi.registerCommand("subagents-setup", {
79
81
  description: "Configure pi-subagents: model and thinking per role",
@@ -90,7 +92,7 @@ export default function (pi: ExtensionAPI): void {
90
92
 
91
93
  // Install the routing contract as prompt sections when the host can diff them.
92
94
  // A full systemPrompt return forces an opaque prompt and invalidates the cache.
93
- pi.on("before_agent_start", async (event, ctx) => {
95
+ pi.on("before_agent_start", async (event) => {
94
96
  await runtime.durableRestore;
95
97
  const agents = loadBuiltinAgents();
96
98
  const sources = [...runtime.threads.values()];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ferris1225/pi-subagents",
3
- "version": "4.3.33",
3
+ "version": "5.0.0",
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",
@@ -34,25 +34,32 @@ answer to know what phase two is, you cannot write the graph yet: run phase one
34
34
  with `subagent` and write the graph afterwards. If every phase is a one-line
35
35
  read, the graph is overhead — do it in main.
36
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.
37
+ Choose proactively from task structure; the user does not need to name the
38
+ tool. Use a graph for two or more substantial phases with known dependency
39
+ edges and write scopes when scheduling saves coordination. Independent phases
40
+ without edges use a parallel `subagent` batch. Honor an explicit user choice.
41
+
42
+ After a discovery phase, reassess the remaining work: use a graph if its plan
43
+ is now clear, or keep the next bounded step in main or a single child. A graph
44
+ schedules a fixed plan; it does not decide what a discovery result means or
45
+ change its nodes at runtime. Never add survey, implementation, review,
46
+ confirmation, and gate nodes merely to follow a template.
39
47
 
40
48
  ## 2. Shape
41
49
 
42
50
  ```ts
43
51
  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
52
+ name: "auth-fix",
53
+ description: "Fix the refresh race and challenge the result.",
46
54
  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"] },
55
+ { id: "map", agent: "scout", task: "Trace the refresh race in src/auth. Cite path:line and test coverage gaps." },
56
+ { id: "fix", agent: "artisan", task: "Fix the race and add its regression tests. Evidence:\n{{map}}", dependsOn: ["map"],
57
+ scope: { paths: ["src/auth", "test/auth.test.ts"] } },
58
+ { id: "review", agent: "artisan", isolation: "shared",
59
+ task: "Try to disprove the fix: inspect callers and edge cases, then run the documented checks. Report evidence and unresolved risks; do not edit files.\n{{fix}}",
60
+ dependsOn: ["fix"] },
54
61
  ],
55
- })
62
+ });
56
63
  ```
57
64
 
58
65
  - `id` — identifies the node in `dependsOn` and in placeholders. Unique per graph.
@@ -70,22 +77,24 @@ completion message arrives when it settles. Do not poll it.
70
77
  The shapes that are worth writing, in the order they usually appear:
71
78
 
72
79
  - **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.
80
+ and quote it. Reuse established evidence and verify decisive or conflicting claims.
74
81
  - **Fan-out with a join.** Independent slices of one plan run at the same time; a
75
82
  join node depends on all of them. Declare disjoint `scope.paths` per slice —
76
83
  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.
84
+ - **Adversarial review and confirmation.** Reviewers seek counterexamples;
85
+ confirmation tries to disprove their findings against callers, invariants,
86
+ and focused reproductions. Use different lenses for independent reviewers.
87
+ Distinguish reproduced, source-supported, disproved, and unverified findings.
88
+ Use artisan when commands are required; scout cannot execute a reproduction.
81
89
  - **A closing gate.** The last node runs the project's own checks. Prefer
82
90
  commands over opinions: the repository's test suite, typecheck, build, or the
83
91
  verification line its README names. Ask for the strongest tier it has, not the
84
92
  fastest one.
85
93
 
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.
94
+ Choose depth for the risk. A reviewer, independent confirmer, and synthesis
95
+ node are reasonable for a large or sensitive change; a focused review can
96
+ combine stages or leave synthesis to main. Every extra node should answer a
97
+ different question. Keep a fix and its regression tests with one owner.
89
98
 
90
99
  ## 4. What the runtime guarantees, and what it does not
91
100
 
@@ -104,7 +113,12 @@ piece of work.
104
113
  - **An interrupted graph is explained, not resumed.** If the session ends
105
114
  mid-graph, the next session's start notice and `subagent_status({ workflow })`
106
115
  report which nodes completed and which were still running, with their run ids.
107
- - **Capacity is pacing, not refusal.** `maxConcurrentAgents` limits simultaneous
116
+ Checkpoints are written during execution, so a process crash also leaves the
117
+ graph shape.
118
+ - **Parent cancellation ends owned work.** Escape and conversation-tree navigation
119
+ stop unfinished graphs and runs without completion wake-ups. New/resume/fork
120
+ tears down the old Pi runtime and retains interruption evidence.
121
+ - **Capacity is pacing, not refusal.** The automatic process limit bounds simultaneous
108
122
  child processes; a wider graph queues and starts as slots free. Queue position
109
123
  never changes dependency order.
110
124
 
@@ -167,23 +181,31 @@ node expects to write:
167
181
  A Markdown definition carries prose plus one ```json fenced block with the plan
168
182
  (or a bare node array); JSON carries the plan object. Project definitions load
169
183
  only in a trusted project. Same-name precedence: project > user > builtin.
184
+ Explicit file paths also require project trust. A call-level `name` overrides a
185
+ saved graph's name. Customize unfilled question, target, and slice placeholders
186
+ in a copy of a shipped template before execution.
170
187
 
171
188
  Save a graph when it will run again, when a reviewer should read the plan before
172
189
  it runs, or when the phases are long enough that you want them in version
173
190
  control. Run it by name; do not restate it inline.
174
191
 
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.
192
+ **A phase stays owned after it settles, and across reloads.** Derived phase ids
193
+ are `<workflow-slug>.<node-id>`; an interrupted run keeps its claim until it is
194
+ retired. Re-running the same shape is therefore rejected **before any node
195
+ starts**, naming the owning runs. Three ways forward: retire the owner with
196
+ `subagent_stop({ id })` (destructive — it drops that run's retained session),
197
+ give a genuinely different deliverable its own brief and phase id. Renaming the
198
+ graph does not bypass exact task matching. Prefer reusing the owner's evidence
199
+ and finishing incomplete work in main. A new session alone does not help: a retained interrupted run is
200
+ restored with its claim intact.
179
201
 
180
202
  ## 9. Cost
181
203
 
182
204
  Every node is a full model session with its own context, and the summary carries
183
205
  each node's answer. Budget accordingly:
184
206
 
185
- - Prefer the fewest nodes that still give each phase one owner and each claim one
186
- confirmer.
207
+ - Give each phase one owner. Add separate review, confirmation, and synthesis
208
+ when their distinct work justifies the cost; combine them for bounded tasks.
187
209
  - Keep node answers short: conclusions, paths, `command → result`.
188
210
  - Do not add a node to fill a free process slot, and do not split one tightly
189
211
  coupled change across nodes.
@@ -207,16 +229,15 @@ each node's answer. Budget accordingly:
207
229
  One completion message per graph:
208
230
 
209
231
  ```text
210
- ### workflow auth-fix completed (4/4 completed)
232
+ ### workflow auth-fix completed (3/3 completed)
211
233
  - map (scout) completed · run #12 · 1m02s
212
234
  - fix (artisan) completed · run #13 · 4m11s
213
- - tests (artisan) completed · run #15 · 2m40s
214
- - gate (artisan) completed · run #16 · 6m05s
235
+ - review (artisan) completed · run #15 · 2m40s
215
236
 
216
237
  Node answers:
217
238
  #### map
218
239
  …
219
- Totals: 4 nodes · anthropic/claude-sonnet-4: ↓48.0k $0.8200
240
+ Totals: 3 nodes · anthropic/claude-sonnet-4: ↓48.0k $0.8200
220
241
  ```
221
242
 
222
243
  - Node answers are clipped here; the full report file is named when that happens.
@@ -46,12 +46,12 @@ export interface AgentProfile {
46
46
 
47
47
  export const AGENT_PROFILES: Record<(typeof BUILTIN_AGENT_NAMES)[number], AgentProfile> = {
48
48
  scout: {
49
- summary: "lightweight research",
50
- remark: "Use for unfamiliar code, a wide lookup, or external facts. Read-only; returns citations.",
49
+ summary: "Research · read-only",
50
+ remark: "Bounded code, documentation, or web research with citations. No commands or edits.",
51
51
  },
52
52
  artisan: {
53
- summary: "implement the change",
54
- remark: "Use for one substantial implementation, fix, refactor, test, or docs change, including its checks.",
53
+ summary: "Engineering · implementation & checks",
54
+ remark: "One substantial change with its tests, or review and validation requiring commands.",
55
55
  },
56
56
  };
57
57
 
@@ -1,16 +1,8 @@
1
- /**
2
- * Interactive configuration wizard for /subagents-setup.
3
- *
4
- * The catalog is fixed: scout and artisan are always enabled. The menu lets the
5
- * user pick a model and thinking level for each role — that is the entire
6
- * configuration surface.
7
- */
1
+ /** Role-based settings. Each field saves independently; Esc always goes back. */
8
2
 
9
3
  import { stat } from "node:fs/promises";
10
- import type { Api, Model } from "@earendil-works/pi-ai";
11
4
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
5
  import {
13
- AGENT_PROFILES,
14
6
  BUILTIN_AGENT_NAMES,
15
7
  DEFAULT_CONFIG,
16
8
  agentProfile,
@@ -29,12 +21,12 @@ import {
29
21
  buildModelPickerItems,
30
22
  currentModelRef,
31
23
  findModelByRef,
32
- modelRef,
33
24
  resolveThinkingLevel,
34
25
  supportedThinkingLevels,
35
26
  } from "./models.ts";
36
- import { promptSelectOne } from "./ui.ts";
27
+ import { promptSelectOne, promptSettings, type SettingsRow } from "./ui.ts";
37
28
 
29
+ const ROLE_DEFAULT = "__role_default__";
38
30
  const THINKING_LEVEL_HINTS: Record<ThinkingLevel, string> = {
39
31
  off: "no reasoning tokens",
40
32
  minimal: "minimal reasoning",
@@ -54,247 +46,114 @@ async function configExists(configPath: string): Promise<boolean> {
54
46
  }
55
47
  }
56
48
 
57
- async function pickConfiguredModel(
58
- ctx: ExtensionContext,
59
- title: string,
60
- configuredRef: string | undefined,
61
- escNote: string,
62
- ): Promise<string | undefined> {
63
- const models = availableModelsInScope(ctx);
64
- const items = buildModelPickerItems({
65
- models,
66
- configuredRef,
67
- mainRef: currentModelRef(ctx),
68
- });
69
- return promptSelectOne(
70
- ctx,
71
- title,
72
- `Type to filter by provider, model, or capability • ↑/↓ • Enter selects • Esc ${escNote}`,
73
- items,
74
- configuredRef ?? CURRENT_MAIN_MODEL,
75
- );
76
- }
77
-
78
- async function pickAgentModel(
79
- ctx: ExtensionContext,
80
- agentName: string,
81
- agentModels: Readonly<Record<string, string>>,
82
- escNote = "returns to the role list",
83
- ): Promise<string | undefined> {
84
- const profile = agentProfile(agentName);
85
- const duty = profile ? ` — ${profile.summary}` : "";
86
- return pickConfiguredModel(
87
- ctx,
88
- `Model for ${agentName}${duty}?`,
89
- agentModels[agentName],
90
- escNote,
91
- );
92
- }
93
-
94
- function effectiveModelForChoice(
95
- ctx: ExtensionContext,
96
- agentName: string,
97
- choice: string,
98
- agentModels: Readonly<Record<string, string>>,
99
- ): Model<Api> | undefined {
100
- const selectedModels = applyAgentModelChoice({ ...agentModels }, agentName, choice);
101
- const ref = selectedModels[agentName];
102
- return findModelByRef(availableModelsInScope(ctx), ref) ?? ctx.model;
49
+ function roleModel(ctx: ExtensionContext, config: SubagentsConfig, name: string) {
50
+ return findModelByRef(availableModelsInScope(ctx), config.agentModels[name]) ?? ctx.model;
103
51
  }
104
52
 
105
- /** The role default is marked; picking it clears a stored override. */
106
- async function pickAgentStrength(
107
- ctx: ExtensionContext,
108
- agentName: string,
109
- model: Model<Api> | undefined,
110
- current: ThinkingLevel | undefined,
111
- escNote = "returns to model selection",
112
- ): Promise<ThinkingLevel | undefined> {
113
- const supported = supportedThinkingLevels(model);
114
- const roleDefault = resolveThinkingLevel(model, roleThinkingLevel(agentName));
115
- if (supported.length <= 1) return roleDefault;
116
-
117
- const currentEffective = current ? resolveThinkingLevel(model, current) : roleDefault;
118
- const modelName = model ? modelRef(model) : "current main model";
119
- const options = supported.map((level) => {
120
- const tags = [
121
- level === roleDefault ? "role default" : "",
122
- current !== undefined && currentEffective === level ? "current" : "",
123
- ].filter(Boolean);
124
- return {
125
- value: level,
126
- label: `${level} — ${THINKING_LEVEL_HINTS[level]}${tags.length ? ` (${tags.join(", ")})` : ""}`,
127
- };
53
+ function settingsRows(ctx: ExtensionContext, config: SubagentsConfig): SettingsRow[] {
54
+ return BUILTIN_AGENT_NAMES.flatMap((name) => {
55
+ const profile = agentProfile(name)!;
56
+ const group = name + " · " + profile.summary;
57
+ const selected = config.agentModels[name];
58
+ const available = !selected || Boolean(findModelByRef(availableModelsInScope(ctx), selected));
59
+ const preferred = config.agentThinkingLevels[name] ?? roleThinkingLevel(name);
60
+ const effective = resolveThinkingLevel(roleModel(ctx, config, name), preferred);
61
+ const source = config.agentThinkingLevels[name] ? "override" : "role default";
62
+ return [
63
+ {
64
+ value: name + ".model", group, label: "Model",
65
+ currentValue: selected ? selected + (available ? "" : " (unavailable)") : "Follow main",
66
+ description: profile.remark + " " + (selected
67
+ ? (available ? "Falls back to main if the selected model fails." : "Unavailable selection; using main.")
68
+ : "Uses the main model dynamically.") + " Main: " + (currentModelRef(ctx) ?? "Pi default"),
69
+ },
70
+ {
71
+ value: name + ".thinking", group, label: "Thinking",
72
+ currentValue: effective + " · " + source + (effective !== preferred ? " (" + preferred + " requested)" : ""),
73
+ description: "Role default: " + roleThinkingLevel(name) + ". Levels follow the effective model's capabilities; unsupported preferences are clamped at runtime.",
74
+ },
75
+ {
76
+ value: name + ".reset", group, label: "Reset role", currentValue: "",
77
+ description: "Restore " + name + " to Follow main and role-default thinking (" + roleThinkingLevel(name) + "). Saves immediately.",
78
+ },
79
+ ];
128
80
  });
129
- return promptSelectOne(
130
- ctx,
131
- `Thinking for ${agentName}?`,
132
- `${agentName} defaults to ${roleDefault} on ${modelName} • Enter selects • Esc ${escNote}`,
133
- options,
134
- currentEffective,
135
- ) as Promise<ThinkingLevel | undefined>;
136
- }
137
-
138
- function applyThinkingChoice(
139
- levels: Record<string, ThinkingLevel>,
140
- agentName: string,
141
- strength: ThinkingLevel,
142
- model: Model<Api> | undefined,
143
- ): Record<string, ThinkingLevel> {
144
- const next = { ...levels };
145
- const roleDefault = resolveThinkingLevel(model, roleThinkingLevel(agentName));
146
- if (strength === roleDefault) delete next[agentName];
147
- else next[agentName] = resolveThinkingLevel(model, strength);
148
- return next;
149
81
  }
150
82
 
151
- interface RoleChoice {
152
- model: string;
153
- strength: ThinkingLevel;
154
- }
155
-
156
- /** Model then thinking for one fixed role. Esc on the model picker backs out to
157
- * the menu; Esc on the thinking picker re-asks the model. */
158
- async function configureOneRole(
83
+ async function editSetting(
159
84
  ctx: ExtensionContext,
160
- agentName: string,
161
85
  config: SubagentsConfig,
162
- ): Promise<RoleChoice | undefined> {
163
- const profile = agentProfile(agentName);
164
- if (profile) ctx.ui.notify(`${agentName}: ${profile.remark}`, "info");
165
- while (true) {
166
- const modelChoice = await pickAgentModel(ctx, agentName, config.agentModels);
167
- if (modelChoice === undefined) return undefined;
168
- const model = effectiveModelForChoice(ctx, agentName, modelChoice, config.agentModels);
169
- const strength = await pickAgentStrength(
170
- ctx,
171
- agentName,
172
- model,
173
- config.agentThinkingLevels[agentName],
174
- );
175
- if (strength === undefined) continue;
176
- return { model: modelChoice, strength };
177
- }
178
- }
179
-
180
- async function applyRoleChoice(
181
- ctx: ExtensionContext,
182
- configPath: string,
183
- config: SubagentsConfig,
184
- agentName: string,
185
- choice: RoleChoice,
186
- ): Promise<SubagentsConfig> {
187
- const agentModels = applyAgentModelChoice({ ...config.agentModels }, agentName, choice.model);
188
- const model = effectiveModelForChoice(ctx, agentName, choice.model, agentModels);
86
+ name: string,
87
+ field: string,
88
+ ): Promise<SubagentsConfig | undefined> {
189
89
  const next: SubagentsConfig = {
190
- agentModels,
191
- agentThinkingLevels: applyThinkingChoice(
192
- { ...config.agentThinkingLevels },
193
- agentName,
194
- choice.strength,
195
- model,
196
- ),
90
+ agentModels: { ...config.agentModels },
91
+ agentThinkingLevels: { ...config.agentThinkingLevels },
197
92
  };
198
- await saveConfig(next, configPath);
199
- return next;
200
- }
201
-
202
- async function introduceSetup(ctx: ExtensionContext): Promise<boolean> {
203
- const lines = BUILTIN_AGENT_NAMES.map((name) => {
204
- const profile = AGENT_PROFILES[name];
205
- return `${name} — ${profile.summary}. ${profile.remark}`;
206
- });
207
- const defaults = BUILTIN_AGENT_NAMES.map((name) => `${name} ${roleThinkingLevel(name)}`).join(", ");
208
- ctx.ui.notify(
209
- `pi-subagents: ${lines.join(" ")} Pick a model and its thinking level for each role next. Thinking starts at the role default (${defaults}).`,
210
- "info",
211
- );
212
- const choice = await ctx.ui.select("How to configure pi-subagents", [
213
- "Continue — pick a model, then its thinking level, for each role",
214
- ]);
215
- return choice !== undefined;
216
- }
217
-
218
- /** Walk both roles in order — model, then thinking — and save once at the end. */
219
- async function runFullSetup(ctx: ExtensionContext, configPath: string, base: SubagentsConfig): Promise<boolean> {
220
- if (!(await introduceSetup(ctx))) return false;
221
-
222
- let agentModels = { ...base.agentModels };
223
- let agentThinkingLevels = { ...base.agentThinkingLevels };
224
- for (const agentName of BUILTIN_AGENT_NAMES) {
225
- const profile = agentProfile(agentName);
226
- if (profile) ctx.ui.notify(`${agentName}: ${profile.remark}`, "info");
227
- const choice = await pickAgentModel(ctx, agentName, agentModels);
228
- if (choice === undefined) return false;
229
- agentModels = applyAgentModelChoice(agentModels, agentName, choice);
230
- // Thinking follows the model immediately: the supported levels come from
231
- // the model just picked, so this is the only moment the choice is exact.
232
- const model = effectiveModelForChoice(ctx, agentName, choice, agentModels);
233
- const strength = await pickAgentStrength(ctx, agentName, model, agentThinkingLevels[agentName]);
234
- if (strength === undefined) return false;
235
- agentThinkingLevels = applyThinkingChoice(agentThinkingLevels, agentName, strength, model);
236
- }
237
-
238
- await saveConfig({ agentModels, agentThinkingLevels }, configPath);
239
- ctx.ui.notify(`pi-subagents saved to ${configPath}.`, "info");
240
- return true;
241
- }
242
-
243
- function roleRow(name: string, config: SubagentsConfig): string {
244
- const profile = AGENT_PROFILES[name as keyof typeof AGENT_PROFILES];
245
- const model = config.agentModels[name] ?? "current main model";
246
- const thinking = config.agentThinkingLevels[name] ?? roleThinkingLevel(name);
247
- return `${name} — ${profile.summary} · model: ${model} · thinking: ${thinking}`;
248
- }
249
-
250
- /** Menu: one row per fixed role showing its current route, plus a both-roles
251
- * walk. Esc exits; saving happens after each change so a later Esc loses
252
- * nothing. */
253
- async function runMenu(ctx: ExtensionContext, configPath: string, config: SubagentsConfig): Promise<void> {
254
- while (true) {
255
- const rows = BUILTIN_AGENT_NAMES.map((name) => roleRow(name, config));
256
- const choice = await ctx.ui.select("pi-subagents settings", [
257
- ...rows,
258
- "Both roles — walk model and thinking for each",
259
- ]);
260
- if (choice === undefined) return;
261
- if (choice.startsWith("Both")) {
262
- if (await runFullSetup(ctx, configPath, config)) return;
263
- continue;
93
+ if (field === "reset") {
94
+ delete next.agentModels[name];
95
+ delete next.agentThinkingLevels[name];
96
+ } else if (field === "model") {
97
+ const choice = await promptSelectOne(ctx, name + " · Model",
98
+ "Search provider, model, or capability · Esc back without changes",
99
+ buildModelPickerItems({ models: availableModelsInScope(ctx), configuredRef: config.agentModels[name], mainRef: currentModelRef(ctx) }),
100
+ config.agentModels[name] ?? CURRENT_MAIN_MODEL);
101
+ if (choice === undefined) return undefined;
102
+ next.agentModels = applyAgentModelChoice(next.agentModels, name, choice);
103
+ } else if (field === "thinking") {
104
+ const model = roleModel(ctx, config, name);
105
+ const preferredDefault = roleThinkingLevel(name);
106
+ const effectiveDefault = resolveThinkingLevel(model, preferredDefault);
107
+ const supported = supportedThinkingLevels(model);
108
+ if (!supported.length) {
109
+ ctx.ui.notify("Choose a model before changing thinking; its supported levels are not available yet.", "info");
110
+ return undefined;
264
111
  }
265
- const agentName = BUILTIN_AGENT_NAMES.find((name) => choice.startsWith(name));
266
- if (!agentName) continue;
267
- const picked = await configureOneRole(ctx, agentName, config);
268
- if (!picked) continue;
269
- config = await applyRoleChoice(ctx, configPath, config, agentName, picked);
270
- ctx.ui.notify(`pi-subagents updated. Saved to ${configPath}`, "info");
112
+ const options = [
113
+ { value: ROLE_DEFAULT, label: "Role default", description: preferredDefault + (effectiveDefault !== preferredDefault ? " → " + effectiveDefault + " on this model" : "") },
114
+ ...supported.map((level) => ({ value: level, label: level, description: THINKING_LEVEL_HINTS[level] })),
115
+ ];
116
+ const current = config.agentThinkingLevels[name];
117
+ const choice = await promptSelectOne(ctx, name + " · Thinking",
118
+ "Choose reasoning effort · Role default follows model capabilities · Esc back",
119
+ options, current && supported.includes(current) ? current : ROLE_DEFAULT);
120
+ if (choice === undefined) return undefined;
121
+ if (choice === ROLE_DEFAULT) delete next.agentThinkingLevels[name];
122
+ else next.agentThinkingLevels[name] = choice as ThinkingLevel;
123
+ } else {
124
+ return undefined;
271
125
  }
126
+ return next;
272
127
  }
273
128
 
274
- /** Entry point for the /subagents-setup command. */
129
+ /** The same compact panel serves first install and later edits. */
275
130
  export async function runSetup(ctx: ExtensionContext, configPath: string = getConfigPath()): Promise<void> {
276
131
  if (ctx.mode !== "tui") {
277
132
  ctx.ui.notify("/subagents-setup requires Pi's interactive TUI.", "error");
278
133
  return;
279
134
  }
280
135
  try {
281
- const exists = await configExists(configPath);
282
- const config = await loadConfig(configPath);
283
- if (exists) await runMenu(ctx, configPath, config);
284
- else if (!(await runFullSetup(ctx, configPath, DEFAULT_CONFIG))) {
285
- ctx.ui.notify("pi-subagents setup cancelled.", "info");
136
+ let config = await loadConfig(configPath);
137
+ let focus: string | undefined;
138
+ let status = "Changes save immediately";
139
+ while (true) {
140
+ const choice = await promptSettings(ctx, settingsRows(ctx, config), focus, status);
141
+ if (choice === undefined) return;
142
+ focus = choice;
143
+ const [name, field] = choice.split(".");
144
+ if (!BUILTIN_AGENT_NAMES.some((role) => role === name)) continue;
145
+ const next = await editSetting(ctx, config, name!, field!);
146
+ if (!next) continue;
147
+ await saveConfig(next, configPath);
148
+ config = next;
149
+ status = "Saved " + name + (field === "reset" ? " defaults" : " " + field);
286
150
  }
287
151
  } catch (error) {
288
- ctx.ui.notify(`pi-subagents setup failed: ${errorMessage(error)}`, "error");
152
+ ctx.ui.notify("pi-subagents setup failed: " + errorMessage(error), "error");
289
153
  }
290
154
  }
291
155
 
292
- /**
293
- * First start: write the shipped defaults so both roles work immediately — no
294
- * model overrides means each child follows the main model — then announce the
295
- * command that customizes them. The file is the marker: once it exists, later
296
- * sessions stay silent.
297
- */
156
+ /** Write shipped defaults once so both roles work immediately. */
298
157
  export async function ensureDefaultConfig(
299
158
  ctx: ExtensionContext,
300
159
  configPath: string = getConfigPath(),
@@ -302,7 +161,7 @@ export async function ensureDefaultConfig(
302
161
  if (await configExists(configPath)) return;
303
162
  await saveConfig(DEFAULT_CONFIG, configPath);
304
163
  ctx.ui.notify(
305
- `pi-subagents: wrote ${configPath} with scout and artisan enabled; both follow the main model. Run /subagents-setup to pick a model and thinking level per role.`,
164
+ "pi-subagents: wrote " + configPath + " with scout and artisan enabled; both follow the main model. Run /subagents-setup to pick a model and thinking level per role.",
306
165
  "info",
307
166
  );
308
167
  }