@ferris1225/pi-subagents 5.0.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 5.0.1
4
+
5
+ ### Changes
6
+
7
+ - Add independent `reviewer` and `critic` roles with their own model and
8
+ thinking settings. `artisan` now owns implementation only; reviews report the
9
+ smallest fix per confirmed defect so the same turn can apply it and confirm
10
+ only that fix.
11
+ - Replace the nested `/subagents-setup` screens with a role grid: one row per
12
+ role, Model / Thinking / Reset as columns.
13
+ - Run children through Pi RPC so a running child can be steered. Add
14
+ `subagent_message`: `context: "session"` continues a private copy of the
15
+ retained session for rework (same prompt-cache key); `context: "summary"`
16
+ starts a new next step from a bounded summary of objective, result and
17
+ touched files.
18
+ - Fix `subagent_stop` ignoring `all` when an unknown `workflow` was also sent,
19
+ and remove stopped runs and graphs from the widget instead of showing them as
20
+ failures.
21
+ - Stop restore from signalling recorded child or owner PIDs, so another Pi
22
+ window or project is never disturbed.
23
+ - Add `/subagents-cleanup` (and `dry-run`) to report per-project usage and
24
+ reclaim unclaimed sessions, worktrees and result artifacts while keeping
25
+ parked recovery work.
3
26
  ## 5.0.0
4
27
 
5
28
  ### Breaking changes
package/README.md CHANGED
@@ -11,13 +11,14 @@ Requires **Pi >= 1.0.0** and **Node.js >= 22.19.0**.
11
11
  pi install npm:@ferris1225/pi-subagents
12
12
  ```
13
13
 
14
- Run `/subagents-setup` for a grouped role settings panel. Edit **Model** and
15
- **Thinking** independently; **Reset role** restores that role's defaults. Each
16
- selection saves immediately, Esc returns without applying a picker selection,
17
- and the panel keeps your focus. Model pickers support search, paste, and paging.
18
-
19
- Both roles follow the main model by default; thinking defaults to `low` for scout
20
- and `high` for artisan. The panel distinguishes defaults from overrides and
14
+ Run `/subagents-setup` for a role grid: one row per role with **Model**,
15
+ **Thinking**, and **Reset** as columns. ↑/↓ moves between roles, ←/→ between
16
+ columns, and Enter edits the focused cell. Each selection saves immediately;
17
+ Esc returns without applying a picker selection, and the grid keeps the focused
18
+ cell. Model pickers support search, paste, and paging.
19
+
20
+ All roles follow the main model by default; thinking defaults to `low` for scout
21
+ and `high` for artisan, reviewer, and critic. The panel distinguishes defaults from overrides and
21
22
  shows the effective level when model capabilities clamp a preference. Changing
22
23
  a model preserves the thinking preference. Settings live in
23
24
  `~/.pi/agent/pi-subagents.json` as `agentModels` and `agentThinkingLevels`.
@@ -27,7 +28,12 @@ a model preserves the thinking preference. Settings live in
27
28
  | Agent | Use for | Access |
28
29
  | --- | --- | --- |
29
30
  | `scout` | Code, documentation, and web research with citations | Read-only tools; no commands or edits |
30
- | `artisan` | Implementation with tests, or reviews and validation that need commands | Parent's tool surface, including codemode |
31
+ | `artisan` | Implementation and fixes with tests and checks | Parent's tool surface, including codemode |
32
+ | `reviewer` | Code review for correctness and regressions | Parent's tool surface; instructed not to edit |
33
+ | `critic` | Adversarial review of changes or findings | Parent's tool surface; instructed not to edit |
34
+
35
+ Reviewer and critic may run checks, so their no-edit boundary is an instruction,
36
+ not a tool-enforced restriction. Configure each role independently.
31
37
 
32
38
  Children receive a self-contained brief and project instructions, but no parent
33
39
  conversation. They cannot delegate or release. Main owns planning, integration,
@@ -43,7 +49,7 @@ research, or an independent check. Free process slots are not a team-size target
43
49
  Use one owner per deliverable, including its regression tests. Brief the child
44
50
  with the outcome, done condition, relevant paths, established evidence, write
45
51
  boundaries, required checks, and a compact expected result. Scout retrieves
46
- sources; artisan can execute commands. This policy applies the context-isolation,
52
+ sources; artisan implements, while reviewer and critic can execute checks. This policy applies the context-isolation,
47
53
  focused-role, and coordination-cost guidance in the official
48
54
  [Codex subagents](https://developers.openai.com/codex/subagents) and
49
55
  [Claude Code subagents](https://code.claude.com/docs/en/sub-agents) docs to Pi's
@@ -111,7 +117,7 @@ subagent_workflow({
111
117
  },
112
118
  {
113
119
  id: "review",
114
- agent: "artisan",
120
+ agent: "critic",
115
121
  isolation: "shared",
116
122
  dependsOn: ["fix"],
117
123
  task: "Try to disprove this fix: inspect callers and edge cases, then run focused checks. Do not edit files.\n{{fix}}",
@@ -148,6 +154,8 @@ See the [workflow skill](./skills/workflow/SKILL.md) for graph authoring details
148
154
  | --- | --- |
149
155
  | `subagent_status({ id: 12 })` | Inspect a run's progress, result, and recovery paths |
150
156
  | `subagent_status({ workflow: 3 })` | Inspect graph nodes and dependencies |
157
+ | `subagent_message({ id: 12, message: "Check the caller too" })` | Steer a running child, or start a follow-up from its completed session |
158
+ | `subagent_message({ id: 12, message: "Add the test", context: "summary" })` | Start a new next step with only a bounded summary of the earlier run |
151
159
  | `subagent_stop({ id: "12" })` | Stop a run and retire its retained session |
152
160
  | `subagent_stop({ workflow: 3 })` | Stop a graph and finalize its active nodes |
153
161
  | `subagent_stop({ all: true })` | Stop all active runs and graphs |
@@ -173,12 +181,41 @@ work without completion wake-ups. New/resume/fork/reload ends old children and r
173
181
  for manual recovery. Runs do not resume automatically; main finishes incomplete
174
182
  work from partial changes and artifacts.
175
183
 
176
- Children use Pi's native `--mode json` CLI, retries, and session persistence.
184
+ A steering message is queued at the next Pi steering boundary; acknowledgement
185
+ does not mean the child has acted on it. To continue a successfully completed
186
+ run, choose the context that fits the follow-up:
187
+
188
+ - `context: "session"` (default) for rework — revising, fixing or extending the
189
+ same deliverable. It continues a private copy of the retained session, so the
190
+ earlier reasoning stays available and the provider prompt-cache key
191
+ (`sessionId`) is unchanged.
192
+ - `context: "summary"` for a new next step — the new run never sees the old
193
+ transcript and is briefed with the objective, the final result and the files
194
+ the run touched. Cheaper, no cache reuse, and it cannot rely on detail the
195
+ summary omits.
196
+
197
+ Both start a new run with the role, workspace and scope preserved. Queueing,
198
+ admission and isolation still apply. Pending runs cannot be steered, and fixed
199
+ workflow graphs cannot be edited.
200
+
201
+ Children use Pi's native `--mode rpc` CLI, retries, and session persistence.
177
202
  A settled provider failure can hand off once to the main model in the same
178
203
  session. State and full-result files live under
179
204
  `~/.pi/agent/ferris-pi-subagents/`, grouped by project. `PI_CODING_AGENT_DIR`
180
205
  overrides the agent directory.
181
206
 
207
+ ## Storage and cleanup
208
+
209
+ Each project root holds `sessions/`, `worktrees/`, `tmp/` and `results/`. Startup
210
+ hygiene already drops temp leftovers, artifacts whose Pi process is gone, result
211
+ files past their retention window, and project roots idle for three days. Parked
212
+ recovery work and anything a manifest still references always survive.
213
+
214
+ Long orchestration sessions still accumulate settled sessions and worktrees, so
215
+ run `/subagents-cleanup` to reclaim them. It reports per-project usage and freed
216
+ bytes, and keeps parked recovery records plus every referenced artifact. Use
217
+ `/subagents-cleanup dry-run` to measure without deleting anything.
218
+
182
219
  ## Development
183
220
 
184
221
  ```bash
package/index.ts CHANGED
@@ -36,6 +36,8 @@ import { registerLookupTools } from "./src/lifecycle/tools.ts";
36
36
  import { registerWorkflowTool, restoreWorkflowState } from "./src/workflow/tool.ts";
37
37
  import { registerAnnouncements } from "./src/presentation/announcements.ts";
38
38
  import { clearActiveRunsWidget } from "./src/presentation/widget.ts";
39
+ import { formatBytes, measureDurableUsage, runStorageCleanup } from "./src/isolation/cleanup.ts";
40
+ import { getSubagentsRoot } from "./src/execution/spawn.ts";
39
41
 
40
42
  export default function (pi: ExtensionAPI): void {
41
43
  const configPath = getConfigPath(getAgentDir());
@@ -74,7 +76,7 @@ export default function (pi: ExtensionAPI): void {
74
76
  const dispatchCore = createDispatchCore(runtime);
75
77
  registerSubagentTool(pi, runtime, dispatchCore);
76
78
  registerWorkflowTool(pi, runtime, dispatchCore);
77
- registerLookupTools(pi, runtime);
79
+ registerLookupTools(pi, runtime, dispatchCore);
78
80
  registerCancellationHooks(pi, runtime);
79
81
 
80
82
  pi.registerCommand("subagents-setup", {
@@ -84,6 +86,27 @@ export default function (pi: ExtensionAPI): void {
84
86
  },
85
87
  });
86
88
 
89
+ pi.registerCommand("subagents-cleanup", {
90
+ description: "Report and reclaim pi-subagents storage; /subagents-cleanup dry-run only reports",
91
+ handler: async (args, ctx) => {
92
+ const root = getSubagentsRoot(configPath);
93
+ if (args.trim() === "dry-run") {
94
+ const usage = measureDurableUsage(root);
95
+ const detail = usage.projects.slice(0, 5).map((project) =>
96
+ `${project.path.split(/[\\/]/u).at(-1)} ${formatBytes(project.bytes)} (${project.sessions} sessions, ${project.worktrees} worktrees)`);
97
+ ctx.ui.notify(`pi-subagents storage: ${formatBytes(usage.totalBytes)} in ${usage.projects.length} project(s)${detail.length ? " · " + detail.join(" · ") : ""}.`, "info");
98
+ return;
99
+ }
100
+ const result = await runStorageCleanup(configPath);
101
+ ctx.ui.notify(
102
+ `pi-subagents cleanup: freed ${formatBytes(result.freedBytes)} (${formatBytes(result.before.totalBytes)} → ${formatBytes(result.after.totalBytes)})`
103
+ + `${result.removedProjects.length ? `; removed ${result.removedProjects.length} idle project root${result.removedProjects.length === 1 ? "" : "s"}` : ""}`
104
+ + `; kept ${result.parkedRecords} parked recovery record${result.parkedRecords === 1 ? "" : "s"} and every referenced artifact.`,
105
+ "info",
106
+ );
107
+ },
108
+ });
109
+
87
110
  pi.on("session_start", async (_event, ctx) => {
88
111
  await bootstrapDurableState(runtime, ctx.cwd);
89
112
  await restoreWorkflowState(runtime, ctx);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ferris1225/pi-subagents",
3
- "version": "5.0.0",
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.",
3
+ "version": "5.0.1",
4
+ "description": "A managed sub-agent team for pi: research, implementation, independent review, interactive follow-ups, and Git worktree isolation.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -55,7 +55,7 @@ subagent_workflow({
55
55
  { id: "map", agent: "scout", task: "Trace the refresh race in src/auth. Cite path:line and test coverage gaps." },
56
56
  { id: "fix", agent: "artisan", task: "Fix the race and add its regression tests. Evidence:\n{{map}}", dependsOn: ["map"],
57
57
  scope: { paths: ["src/auth", "test/auth.test.ts"] } },
58
- { id: "review", agent: "artisan", isolation: "shared",
58
+ { id: "review", agent: "critic", isolation: "shared",
59
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
60
  dependsOn: ["fix"] },
61
61
  ],
@@ -85,7 +85,7 @@ The shapes that are worth writing, in the order they usually appear:
85
85
  confirmation tries to disprove their findings against callers, invariants,
86
86
  and focused reproductions. Use different lenses for independent reviewers.
87
87
  Distinguish reproduced, source-supported, disproved, and unverified findings.
88
- Use artisan when commands are required; scout cannot execute a reproduction.
88
+ Use reviewer or critic when commands are required; scout cannot execute a reproduction.
89
89
  - **A closing gate.** The last node runs the project's own checks. Prefer
90
90
  commands over opinions: the repository's test suite, typecheck, build, or the
91
91
  verification line its README names. Ask for the strongest tier it has, not the
@@ -16,7 +16,7 @@ import { dirname, join } from "node:path";
16
16
  import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
17
17
 
18
18
  /** Full catalog of agents shipped with the package; all of them always run. */
19
- export const BUILTIN_AGENT_NAMES = ["scout", "artisan"] as const;
19
+ export const BUILTIN_AGENT_NAMES = ["scout", "artisan", "reviewer", "critic"] as const;
20
20
 
21
21
  /** Thinking levels accepted by pi's `--thinking` option. */
22
22
  const THINKING_LEVEL_VALUES = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
@@ -30,6 +30,8 @@ export function roleThinkingLevel(agentName: string): ThinkingLevel {
30
30
  case "scout":
31
31
  return "low";
32
32
  case "artisan":
33
+ case "reviewer":
34
+ case "critic":
33
35
  return "high";
34
36
  default:
35
37
  return DEFAULT_THINKING_LEVEL;
@@ -50,8 +52,16 @@ export const AGENT_PROFILES: Record<(typeof BUILTIN_AGENT_NAMES)[number], AgentP
50
52
  remark: "Bounded code, documentation, or web research with citations. No commands or edits.",
51
53
  },
52
54
  artisan: {
53
- summary: "Engineering · implementation & checks",
54
- remark: "One substantial change with its tests, or review and validation requiring commands.",
55
+ summary: "Implement · code & checks",
56
+ remark: "Implement one substantial change with its tests and verification.",
57
+ },
58
+ reviewer: {
59
+ summary: "Review · correctness",
60
+ remark: "Review code for actionable defects and verify findings without editing files.",
61
+ },
62
+ critic: {
63
+ summary: "Challenge · adversarial review",
64
+ remark: "Challenge changes or findings with counterexamples and independent verification.",
55
65
  },
56
66
  };
57
67
 
@@ -24,7 +24,7 @@ import {
24
24
  resolveThinkingLevel,
25
25
  supportedThinkingLevels,
26
26
  } from "./models.ts";
27
- import { promptSelectOne, promptSettings, type SettingsRow } from "./ui.ts";
27
+ import { promptRoleGrid, promptSelectOne, type RoleGridFocus, type RoleGridRow } from "./ui.ts";
28
28
 
29
29
  const ROLE_DEFAULT = "__role_default__";
30
30
  const THINKING_LEVEL_HINTS: Record<ThinkingLevel, string> = {
@@ -50,36 +50,29 @@ function roleModel(ctx: ExtensionContext, config: SubagentsConfig, name: string)
50
50
  return findModelByRef(availableModelsInScope(ctx), config.agentModels[name]) ?? ctx.model;
51
51
  }
52
52
 
53
- function settingsRows(ctx: ExtensionContext, config: SubagentsConfig): SettingsRow[] {
54
- return BUILTIN_AGENT_NAMES.flatMap((name) => {
53
+ /** One row per role: every model and thinking choice stays visible together. */
54
+ function roleRows(ctx: ExtensionContext, config: SubagentsConfig): RoleGridRow[] {
55
+ const mainRef = currentModelRef(ctx) ?? "Pi default";
56
+ return BUILTIN_AGENT_NAMES.map((name) => {
55
57
  const profile = agentProfile(name)!;
56
- const group = name + " · " + profile.summary;
57
58
  const selected = config.agentModels[name];
58
59
  const available = !selected || Boolean(findModelByRef(availableModelsInScope(ctx), selected));
59
60
  const preferred = config.agentThinkingLevels[name] ?? roleThinkingLevel(name);
60
61
  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
- ];
62
+ const clamped = effective !== preferred ? " (" + preferred + " requested)" : "";
63
+ const overridden = Boolean(config.agentThinkingLevels[name]);
64
+ return {
65
+ role: name,
66
+ thinkingOverridden: overridden,
67
+ model: selected ? selected + (available ? "" : " (unavailable)") : "Follow main",
68
+ thinking: effective + clamped,
69
+ description: profile.remark + " Model: " + (selected
70
+ ? (available ? "falls back to main if it fails." : "unavailable; using main.")
71
+ : "follows main (" + mainRef + ") dynamically.")
72
+ + " Thinking: role default " + roleThinkingLevel(name) + ", clamped to the model-supported levels. Reset restores " + name + " to Follow main and that default. * marks an override.",
73
+ };
80
74
  });
81
75
  }
82
-
83
76
  async function editSetting(
84
77
  ctx: ExtensionContext,
85
78
  config: SubagentsConfig,
@@ -126,7 +119,8 @@ async function editSetting(
126
119
  return next;
127
120
  }
128
121
 
129
- /** The same compact panel serves first install and later edits. */
122
+
123
+ /** The same role overview serves first install and later edits. */
130
124
  export async function runSetup(ctx: ExtensionContext, configPath: string = getConfigPath()): Promise<void> {
131
125
  if (ctx.mode !== "tui") {
132
126
  ctx.ui.notify("/subagents-setup requires Pi's interactive TUI.", "error");
@@ -134,26 +128,24 @@ export async function runSetup(ctx: ExtensionContext, configPath: string = getCo
134
128
  }
135
129
  try {
136
130
  let config = await loadConfig(configPath);
137
- let focus: string | undefined;
131
+ let focus: RoleGridFocus = {};
138
132
  let status = "Changes save immediately";
139
133
  while (true) {
140
- const choice = await promptSettings(ctx, settingsRows(ctx, config), focus, status);
134
+ const choice = await promptRoleGrid(ctx, roleRows(ctx, config), focus, status);
141
135
  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!);
136
+ focus = { row: choice.row, column: choice.column };
137
+ const next = await editSetting(ctx, config, choice.role, choice.field);
146
138
  if (!next) continue;
147
139
  await saveConfig(next, configPath);
148
140
  config = next;
149
- status = "Saved " + name + (field === "reset" ? " defaults" : " " + field);
141
+ status = "Saved " + choice.role + (choice.field === "reset" ? " defaults" : " " + choice.field);
150
142
  }
151
143
  } catch (error) {
152
144
  ctx.ui.notify("pi-subagents setup failed: " + errorMessage(error), "error");
153
145
  }
154
146
  }
155
147
 
156
- /** Write shipped defaults once so both roles work immediately. */
148
+ /** Write shipped defaults once so every role works immediately. */
157
149
  export async function ensureDefaultConfig(
158
150
  ctx: ExtensionContext,
159
151
  configPath: string = getConfigPath(),
@@ -161,7 +153,7 @@ export async function ensureDefaultConfig(
161
153
  if (await configExists(configPath)) return;
162
154
  await saveConfig(DEFAULT_CONFIG, configPath);
163
155
  ctx.ui.notify(
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.",
156
+ "pi-subagents: wrote " + configPath + " with all roles enabled; each follows the main model. Run /subagents-setup to pick a model and thinking level per role.",
165
157
  "info",
166
158
  );
167
159
  }
@@ -3,6 +3,7 @@
3
3
  import {
4
4
  Input,
5
5
  fuzzyFilter,
6
+ matchesKey,
6
7
  truncateToWidth,
7
8
  visibleWidth,
8
9
  wrapTextWithAnsi,
@@ -172,6 +173,148 @@ export function promptSelectOne(
172
173
  return openPicker(ctx, items, { title, hint, searchable: true, initialValue });
173
174
  }
174
175
 
176
+ /** One role per row, with Model, Thinking and Reset side by side: the whole
177
+ * configuration is visible at once, so a model choice and its clamped thinking
178
+ * level are compared in place instead of through nested screens. */
179
+ export interface RoleGridRow {
180
+ role: string;
181
+ model: string;
182
+ thinking: string;
183
+ /** Whether the thinking level is a user override (shown with a marker). */
184
+ thinkingOverridden?: boolean;
185
+ /** Why this row matters; shown for the focused row only. */
186
+ description: string;
187
+ }
188
+
189
+ export interface RoleGridFocus {
190
+ row?: number;
191
+ column?: number;
192
+ }
193
+
194
+ const GRID_COLUMNS = ["model", "thinking", "reset"] as const;
195
+ export type RoleGridColumn = (typeof GRID_COLUMNS)[number];
196
+
197
+ export interface RoleGridChoice {
198
+ row: number;
199
+ column: number;
200
+ role: string;
201
+ field: RoleGridColumn;
202
+ }
203
+
204
+ class RoleGrid implements Component {
205
+ private row: number;
206
+ private column: number;
207
+ private readonly rows: RoleGridRow[];
208
+ private readonly status: string;
209
+ private readonly tui: TUI;
210
+ private readonly theme: Theme;
211
+ private readonly keybindings: KeybindingsManager;
212
+ private readonly done: (choice: RoleGridChoice | undefined) => void;
213
+
214
+ constructor(
215
+ rows: RoleGridRow[],
216
+ status: string,
217
+ focus: RoleGridFocus,
218
+ tui: TUI,
219
+ theme: Theme,
220
+ keybindings: KeybindingsManager,
221
+ done: (choice: RoleGridChoice | undefined) => void,
222
+ ) {
223
+ this.rows = rows;
224
+ this.status = status;
225
+ this.tui = tui;
226
+ this.theme = theme;
227
+ this.keybindings = keybindings;
228
+ this.done = done;
229
+ this.row = Math.min(Math.max(0, focus.row ?? 0), Math.max(0, rows.length - 1));
230
+ this.column = Math.min(Math.max(0, focus.column ?? 0), GRID_COLUMNS.length - 1);
231
+ }
232
+
233
+ /** Column budget: the role name and the action stay readable, the two
234
+ * measured values share what is left. */
235
+ private widths(width: number): number[] {
236
+ const role = Math.min(12, Math.max(4, Math.floor(width * 0.16)));
237
+ const reset = 6;
238
+ const gap = 2;
239
+ // The row prefix ("› ") and the three gaps also spend columns.
240
+ const available = Math.max(0, width - 2 - role - reset - gap * 3);
241
+ const model = Math.max(0, Math.floor(available * 0.55));
242
+ const thinking = Math.max(0, available - model);
243
+ return [role, model, thinking, reset];
244
+ }
245
+
246
+ render(width: number): string[] {
247
+ if (width <= 0) return [""];
248
+ const theme = this.theme;
249
+ const dim = (text: string) => theme.fg("dim", text);
250
+ const [roleWidth, modelWidth, thinkingWidth, resetWidth] = this.widths(width);
251
+ const cell = (text: string, size: number, active: boolean): string => {
252
+ const fitted = truncateToWidth(text, size, "…");
253
+ const pad = " ".repeat(Math.max(0, size - visibleWidth(fitted)));
254
+ return active ? theme.fg("accent", theme.bold(fitted)) + pad : fitted + pad;
255
+ };
256
+ const lines = [theme.fg("border", "─".repeat(width)), theme.fg("accent", theme.bold("Subagents · Roles")), dim("Model · Thinking · Reset per role · " + this.status), ""];
257
+ const header = ["Role", "Model", "Thinking", ""]
258
+ .map((title, index) => cell(title, [roleWidth, modelWidth, thinkingWidth, resetWidth][index]!, false))
259
+ .join(" ");
260
+ lines.push(dim(header));
261
+ for (const [index, row] of this.rows.entries()) {
262
+ const selected = index === this.row;
263
+ const cells = [row.role, row.model, row.thinking + (row.thinkingOverridden ? "*" : ""), "reset"]
264
+ .map((text, column) => cell(text, [roleWidth, modelWidth, thinkingWidth, resetWidth][column]!, selected && this.column === column));
265
+ lines.push((selected ? theme.fg("accent", "› ") : " ") + cells.join(" "));
266
+ }
267
+ const focused = this.rows[this.row];
268
+ lines.push("", theme.fg("border", "─".repeat(width)));
269
+ if (focused) lines.push(...wrapTextWithAnsi(focused.description, Math.max(1, width)).slice(0, 3).map(dim));
270
+ lines.push(dim("↑/↓ role · ←/→ column · Enter edit · Esc close"));
271
+ return lines.map((line) => truncateToWidth(line, width, "…"));
272
+ }
273
+
274
+ handleInput(data: string): void {
275
+ const kb = this.keybindings;
276
+ const rows = this.rows.length;
277
+ if (kb.matches(data, "tui.select.up")) {
278
+ if (rows) this.row = (this.row - 1 + rows) % rows;
279
+ } else if (kb.matches(data, "tui.select.down")) {
280
+ if (rows) this.row = (this.row + 1) % rows;
281
+ } else if (matchesKey(data, "left") || kb.matches(data, "tui.editor.cursorLeft")) {
282
+ this.column = (this.column - 1 + GRID_COLUMNS.length) % GRID_COLUMNS.length;
283
+ } else if (matchesKey(data, "right") || kb.matches(data, "tui.editor.cursorRight")) {
284
+ this.column = (this.column + 1) % GRID_COLUMNS.length;
285
+ } else if (kb.matches(data, "tui.select.confirm")) {
286
+ const focused = this.rows[this.row];
287
+ if (focused) {
288
+ this.done({ row: this.row, column: this.column, role: focused.role, field: GRID_COLUMNS[this.column]! });
289
+ return;
290
+ }
291
+ } else if (kb.matches(data, "tui.select.cancel")) {
292
+ this.done(undefined);
293
+ return;
294
+ } else {
295
+ return;
296
+ }
297
+ this.tui.requestRender();
298
+ }
299
+
300
+ invalidate(): void {}
301
+ }
302
+
303
+ /** Role × setting grid. Esc closes without a change. */
304
+ export function promptRoleGrid(
305
+ ctx: PickerContext,
306
+ rows: RoleGridRow[],
307
+ focus: RoleGridFocus = {},
308
+ status = "Changes save immediately",
309
+ ): Promise<RoleGridChoice | undefined> {
310
+ if (ctx.mode !== "tui") {
311
+ ctx.ui.notify("/subagents-setup requires Pi's interactive TUI.", "error");
312
+ return Promise.resolve(undefined);
313
+ }
314
+ return ctx.ui.custom<RoleGridChoice | undefined>((tui, theme, keybindings, done) =>
315
+ new RoleGrid(rows, status, focus, tui, theme, keybindings, done));
316
+ }
317
+
175
318
  export function promptSettings(
176
319
  ctx: PickerContext,
177
320
  items: SettingsRow[],
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Agent catalog and tool resolution.
3
3
  *
4
- * The catalog is exactly the two built-in roles shipped as code in
5
- * builtin-agents.ts (scout, artisan). Both are always enabled; there are no
4
+ * The catalog consists of the built-in roles shipped as code in
5
+ * builtin-agents.ts. All are always enabled; there are no
6
6
  * user or project role files and nothing to discover on disk. The rest of this
7
7
  * module resolves each role against the parent's live tool surface.
8
8
  */
@@ -28,6 +28,7 @@ export const SUBAGENT_TOOL_NAMES = [
28
28
  "subagent",
29
29
  "subagent_workflow",
30
30
  "subagent_status",
31
+ "subagent_message",
31
32
  "subagent_stop",
32
33
  ] as const;
33
34
  const SUBAGENT_TOOL_NAME_SET = new Set<string>(SUBAGENT_TOOL_NAMES);
@@ -114,7 +115,7 @@ export function isWriteCapableAgent(
114
115
  return agent.tools.some((tool) => !isReadOnlyToolName(tool, toolIndex));
115
116
  }
116
117
 
117
- /** The fixed built-in catalog: scout and artisan, in that order. */
118
+ /** The fixed built-in catalog, in setup order. */
118
119
  export function loadBuiltinAgents(): AgentConfig[] {
119
120
  return BUILTIN_AGENTS.map((agent) => ({ ...agent }));
120
121
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Built-in role definitions.
3
3
  *
4
- * The two built-in roles ship as code and are the whole catalog: both are
4
+ * The built-in roles ship as code and are the whole catalog: all are
5
5
  * always enabled and there are no user or project role files.
6
6
  *
7
7
  * Role prompts stay tool-agnostic: the host decides whether a child reaches its
@@ -30,11 +30,11 @@ const SCOUT_SYSTEM_PROMPT = `Answer the brief's bounded research question. Follo
30
30
  Lead with the answer. Return only findings needed for the brief, with decisive citations rather than raw search logs or whole files. Cite repository facts as \`path:line-range\` and external facts as source URLs. Distinguish inference from verified facts, and name unresolved gaps.
31
31
  `;
32
32
 
33
- const ARTISAN_SYSTEM_PROMPT = `Complete the brief's bounded engineering task: implementation, fix, review, validation, tests, or docs. Follow the brief within loaded project instructions; this role supplies the working method. The leaf boundary below still wins. You have no interactive clarification; resolve routine details, state material assumptions, and finish the authorized outcome.
33
+ const ARTISAN_SYSTEM_PROMPT = `Complete the brief's bounded engineering task: implementation, fix, tests, or docs. Follow the brief within loaded project instructions; this role supplies the working method. The leaf boundary below still wins. You have no interactive clarification; resolve routine details, state material assumptions, and finish the authorized outcome.
34
34
 
35
35
  ## Rules
36
36
 
37
- - Read what the task needs, then deliver it. For a review or validation, honor the brief's edit boundary, seek counterexamples, and distinguish reproduced findings from source-supported conclusions. For implementation, complete the change. Reach the tools this session declares the way it declares them — directly, or through its script tool when that is the only interface. Continue through affected tests, docs, comments, local cleanup, and verification. Do not stop at a plan or a first draft.
37
+ - Read what the task needs, then complete the change. Reach the tools this session declares the way it declares them — directly, or through its script tool when that is the only interface. Continue through affected tests, docs, comments, local cleanup, and verification. Do not stop at a plan or a first draft.
38
38
  - For a reported defect, confirm current behavior and fix the root cause. If the premise is disproved, or finishing requires a wider scope or an approval boundary, report the blocker with evidence.
39
39
  - Own only the brief's scope and done condition, including the change and its regression tests. Make the smallest coherent change. Preserve unrelated work, other agents' changes, and project conventions. Report a required change outside your write boundary instead of expanding it silently.
40
40
  - Run the checks and gates the brief or project requires. Tests should catch the relevant failure. Skip a test that only mirrors a reversible, low-impact edit. Fix failures caused by your change. Repeat or broaden checks only for new edits, failures, or unresolved concerns. Main owns the final integrated gate.
@@ -45,6 +45,20 @@ const ARTISAN_SYSTEM_PROMPT = `Complete the brief's bounded engineering task: im
45
45
  Lead with the outcome. Keep the handoff compact: changed paths, checks as \`command → result\`, and material blockers or follow-ups. Summarize evidence instead of dumping logs or whole files. State unrun checks and pre-existing failures accurately.
46
46
  `;
47
47
 
48
+ const REVIEW_SYSTEM_PROMPT = (method: string) => `Complete the brief's bounded code review. Follow the brief within loaded project instructions; this role supplies the working method. The leaf boundary below still wins. You have no interactive clarification; state material assumptions and finish.
49
+
50
+ ## Rules
51
+
52
+ - ${method}
53
+ - Inspect the relevant code and callers. Run safe focused checks when useful and available. Do not edit files or change Git state: another agent applies the fix, and a reviewer that edits its own finding cannot be trusted to have judged it. Your tools can write, so this is an instruction rather than a tool-enforced boundary.
54
+ - Make every finding directly actionable so the fix needs no second investigation: exact location, trigger, consequence, evidence, and the smallest change that resolves it. Report actionable defects only; leave style preferences out.
55
+ - You are a leaf: do not dispatch agents, bump versions, commit, push, publish, tag, or release.
56
+
57
+ ## Output
58
+
59
+ Lead with findings ordered by severity, then checks performed and material gaps. State clearly when no findings were found.
60
+ `;
61
+
48
62
  export const BUILTIN_AGENTS: readonly BuiltinAgentDefinition[] = [
49
63
  {
50
64
  name: "scout",
@@ -54,7 +68,17 @@ export const BUILTIN_AGENTS: readonly BuiltinAgentDefinition[] = [
54
68
  },
55
69
  {
56
70
  name: "artisan",
57
- description: "Use for a substantial change with its checks, or a review or validation that needs command execution.",
71
+ description: "Use for a substantial implementation or fix with its tests and checks.",
58
72
  systemPrompt: ARTISAN_SYSTEM_PROMPT,
59
73
  },
74
+ {
75
+ name: "reviewer",
76
+ description: "Use for code review: find actionable correctness defects and verify findings with focused checks.",
77
+ systemPrompt: REVIEW_SYSTEM_PROMPT("Review the change for correctness, regressions, and missing coverage against the stated requirements."),
78
+ },
79
+ {
80
+ name: "critic",
81
+ description: "Use for adversarial review: challenge a change or findings with counterexamples and independent verification.",
82
+ systemPrompt: REVIEW_SYSTEM_PROMPT("Try to disprove the proposed change or findings. Seek counterexamples, broken assumptions, and evidence that would invalidate them."),
83
+ },
60
84
  ];