@ferris1225/pi-subagents 1.0.0 → 2.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.
package/LICENSE CHANGED
@@ -1,6 +1,8 @@
1
1
  MIT License
2
2
 
3
3
  Copyright (c) 2025 ferris1225
4
+ Portions of agents/cleaner.md adapted from reclaim-code-entropy:
5
+ Copyright (c) 2026 Yevanchen
4
6
 
5
7
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
8
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -7,18 +7,26 @@
7
7
  ![pi](https://img.shields.io/badge/pi-extension-orange)
8
8
 
9
9
  Focused background delegation for [pi](https://pi.dev): `explore` / `worker` /
10
- `reviewer` agents run in **isolated child processes** and hand their results back
11
- to the main agent automatically. Install it, and the main model starts using it
12
- on its own — no prompt engineering, no babysitting.
13
-
14
- ## 1.0 — controllable agent threads
15
-
16
- Version 1.0 turns pi-subagents from a one-shot background runner into a small
17
- thread runtime. Every dispatch has a stable run id and retained Pi session, so
18
- work can be steered while it runs, parked without losing context, resumed after
19
- settlement, retargeted, or forked into another path. An internal append-only
20
- lifecycle trajectory keeps retries and stale generations from corrupting the
21
- logical thread.
10
+ `cleaner` / `reviewer` agents run in **isolated child processes** and hand their
11
+ results back to the main agent automatically. Install it, and the main model
12
+ starts using it on its own — no prompt engineering, no babysitting.
13
+
14
+ ## 2.0.0direct model handoff and capability-aware thinking
15
+
16
+ Version 2 removes backup pools and global thinking strength. Every agent now has
17
+ one optional selected model; any model/provider failure hands its retained session
18
+ directly to the current main model, while ordinary tool/task failures stay put.
19
+ Thinking defaults to Auto and is clamped through Pi's real model capability map.
20
+ The setup menu and normalized config drop the obsolete options instead of carrying
21
+ compatibility aliases.
22
+
23
+ This release also adds semantic routing to a dedicated evidence-first `cleaner`
24
+ and makes the active widget show each run's task, effective model/thinking,
25
+ activity, and elapsed time. Every dispatch has a stable run id, so work can be
26
+ steered while it runs, parked without losing context, resumed after settlement,
27
+ retargeted, or forked into another path. Generation ownership keeps startup-race
28
+ retries and stale child processes from corrupting the logical thread without
29
+ retaining a duplicate event history.
22
30
 
23
31
  The common quality loop now runs end to end without waking the main agent between
24
32
  steps:
@@ -27,49 +35,72 @@ steps:
27
35
  reviewer (find blockers) → worker (fix) → reviewer (verify) → final PASS/FAIL
28
36
  ```
29
37
 
38
+ Cleanup stays a separate lifecycle: explicit cleanup intent can dispatch the
39
+ evidence-first `cleaner`; any edits still go through the independent `reviewer`
40
+ gate.
41
+
30
42
  Each chain is delivered as one concise completion group, while full per-run
31
- reports remain available through `subagent_status`. Ordered model pools keep the
32
- same retained context across provider fallback, and isolated parallel workers
33
- use detached Git worktrees whose changes are applied back without touching the
34
- parent index.
43
+ reports remain available through `subagent_status`. Its parent stays `running`
44
+ until the whole chain settles; completed internal rounds leave active status
45
+ immediately, so no `done` row keeps accumulating elapsed time. Selected-to-main
46
+ model handoffs keep the same retained context, and isolated parallel workers use
47
+ detached Git worktrees whose changes are applied back without touching the parent
48
+ index.
35
49
 
36
50
  ## Highlights
37
51
 
38
52
  - **Zero-setup proactive dispatch** — the extension injects a delegation directive
39
- into the main system prompt, so the main model automatically sends broad searches
40
- to `explore`, self-contained implementations to `worker`, and pre-commit reviews
41
- to `reviewer`. You just use pi; delegation happens by itself.
53
+ into the main system prompt, so the main model sends broad searches to `explore`,
54
+ self-contained implementations to `worker`, explicit cleanup intent to `cleaner`,
55
+ and pre-commit reviews to `reviewer`. You just use pi; delegation happens by itself.
42
56
  - **Vision-capable image tasks** — flag screenshot/mockup/design work with
43
- `vision: true`. The configured vision primary is followed by that agent's
44
- backup and the current main-window model. Setup lists only in-scope,
45
- image-capable models from providers with a configured API key or OAuth session,
46
- and runtime failures never silently rewrite your configuration.
57
+ `vision: true`. The configured vision model hands directly to the current main
58
+ model on model/provider failure. Setup lists only in-scope, image-capable models
59
+ from providers with configured authentication, and failures never silently
60
+ rewrite your configuration.
47
61
  - **Results come back on their own** — completions are delivered as messages that
48
62
  wake the main agent automatically, even mid-turn. No polling, no `sleep`, no
49
63
  "go check" step. `subagent_wait` is a **non-blocking** in-turn lookup by default
50
64
  (pass `timeoutMs` to block); `subagent_status` inspects runs; `subagent_stop`
51
65
  cancels one and delivers its partial output.
66
+ - **Active-only live widget** — each queued or running sub-agent gets one compact
67
+ width-aware primary line with task, effective model/thinking, and elapsed time;
68
+ current activity appears only when present on an indented second line:
69
+ ```text
70
+ #7 cleaner · remove dead code in src/cache.ts · claude-sonnet-4-5/high · 42s
71
+ grep cacheKey
72
+ ```
73
+ Long tasks and activity paths truncate first (preserving a useful path tail when
74
+ possible), groups have no blank rows, and settled/parked runs disappear immediately.
52
75
  - **Results are not re-narrated** — a sub-agent's completion is shown to you
53
76
  verbatim, and the main agent is told not to paraphrase it back. It replies with
54
77
  only its own conclusion or next step, so the same findings are never paid for
55
78
  twice in tokens.
79
+ - **Evidence-first cleanup, not deletion by guesswork** — `cleaner` distinguishes
80
+ read-only audit wording from explicit apply wording, proves consumers and dynamic
81
+ entrypoints before cutting, and treats finding nothing safe as a valid outcome.
82
+ It is periodic/intent-driven, never PR-count-driven or an automatic commit gate.
56
83
  - **A quality gate that closes the loop** — when a reviewer returns `REVIEW_FAIL`,
57
84
  the extension dispatches a worker briefed with the concrete findings, then a
58
85
  re-review, up to `maxFixRounds` times — and only then wakes the main agent.
59
86
  Every round stays in the triggering reviewer's cwd, and chains that target the
60
87
  same repository are serialized so shared-checkout edits cannot race.
61
- - **Ordered model pools without config churn** — each agent can have a primary
62
- and backup; the current main-window model is the final candidate. Transient
63
- provider failures retry the same candidate with backoff, while permanent stale
64
- model/config errors and quota/auth errors advance immediately. Saved refs are
65
- never rewritten behind your back.
88
+ - **Direct fallback with real thinking capabilities** — each agent has at most
89
+ one selected model. An unavailable selection, rate limit, invalid key, quota,
90
+ missing model, or provider failure hands directly to the current main model.
91
+ A child-only provider adapter forces request retries to zero, and the RPC
92
+ parent cancels Pi's outer turn retry before another call, without changing user
93
+ settings. Auto thinking clamps the agent preference to the
94
+ effective model's real `thinkingLevelMap`; manual setup shows only levels that
95
+ model supports.
66
96
  - **Resumes, retargets, and forks preserve context** — every run is session-backed.
67
97
  `subagent_control` can steer active work, retarget it after a stable abort,
68
98
  park/resume it under the same run id, or fork a parked/settled checkpoint into
69
99
  a new independent run. Concurrent resume calls are serialized.
70
- - **Honest completions** — a run that ended with failed tool calls (e.g. a broken
71
- build) is reported as `completed with N failed tool call(s)` with the errors
72
- attached a cheerful final text can never hide a failure.
100
+ - **Concise but honest completions** — a clean process that contained failed tool
101
+ calls adds one short warning with its run id; individual errors stay out of the
102
+ main context and remain available through `subagent_status`. Actual process,
103
+ model, and integration failures still surface as failures.
73
104
  - **Parallel fan-out with filesystem isolation** — independent tasks run up to a
74
105
  configurable limit (default 4). Parallel workers default to detached Git
75
106
  worktrees; tracked, deleted, untracked, and binary changes are applied back
@@ -81,21 +112,39 @@ parent index.
81
112
  - **Update announcements** — when a new configurable feature ships, you are told
82
113
  about it once (a persisted marker stops the notice from nagging).
83
114
 
115
+ ## What this adds beyond generic subagent dispatch
116
+
117
+ This package combines several concrete runtime behaviors rather than only exposing
118
+ an undifferentiated child-agent launcher:
119
+
120
+ - language-agnostic semantic role guidance for cleanup intent;
121
+ - a dedicated evidence-first cleaner, with cleanup kept separate from the
122
+ independent reviewer gate;
123
+ - isolated, retained threads that can be steered, parked, resumed, retargeted, or
124
+ forked under stable run ids;
125
+ - the reviewer → worker auto-fix → reviewer loop;
126
+ - compact failed-tool warnings with full diagnostics available by run id;
127
+ - direct selected→main fallback plus capability-aware Auto thinking;
128
+ - detached Git worktree isolation for parallel workers and opt-in write-capable
129
+ cleaner runs.
130
+
84
131
  ## Install
85
132
 
86
133
  ```bash
87
134
  pi install npm:@ferris1225/pi-subagents
88
135
  ```
89
136
 
90
- Requires pi **>= 0.80.6**. After installation, open the setup wizard in an
137
+ Requires pi **>= 0.83.0**. After installation, open the setup wizard in an
91
138
  interactive TUI session:
92
139
 
93
140
  ```text
94
141
  /subagents-setup
95
142
  ```
96
143
 
97
- The default configuration enables `explore`, `worker`, and `reviewer` — you can
98
- start delegating immediately.
144
+ Fresh installs enable `explore`, `worker`, `cleaner`, and `reviewer` — you can
145
+ start delegating immediately. Existing explicit `enabledAgents` lists are never
146
+ silently extended; users upgrading with an existing explicit list get a one-time
147
+ notice to opt into `cleaner` with `/subagents-setup`.
99
148
 
100
149
  ## The agents
101
150
 
@@ -103,7 +152,8 @@ start delegating immediately.
103
152
  | --- | --- | --- |
104
153
  | `explore` | Read-only | Fast codebase reconnaissance: broad/open-ended search, multi-file lookups, mapping unfamiliar code. Returns compressed, structured findings. |
105
154
  | `worker` | Full | Implements, fixes, refactors, and tests a self-contained task end to end, then reports honest verification. |
106
- | `reviewer` | Read-only | Adversarial pre-commit quality gate: diff review, plus plans, proposed solutions, codebase health, and PR/issue validation. |
155
+ | `cleaner` | Full | Evidence-first cleanup. Audits and ranks candidates read-only, or applies the smallest proven cuts when removal is explicit; supports worktree isolation. |
156
+ | `reviewer` | Read-only | Adversarial pre-commit quality gate: independently reviews worker and cleaner edits, plus plans, proposed solutions, codebase health, and PR/issue validation. |
107
157
 
108
158
  Each agent runs in its own isolated `pi` process with a clean context window; it
109
159
  has no memory of your conversation, so briefs must be self-contained (goal, exact
@@ -116,6 +166,8 @@ paths, constraints, expected output).
116
166
  ```ts
117
167
  subagent({ agent: "explore", task: "Map the test setup: which files run what, and how is CI wired? Report exact paths." });
118
168
  subagent({ agent: "worker", task: "Implement X in src/foo.ts, add tests, run npm test." });
169
+ subagent({ agent: "cleaner", task: "Audit src/cache for dead code and redundant state; report ranked evidence only." });
170
+ subagent({ agent: "cleaner", task: "Remove the proven dead cache adapter, update its tests/docs, and verify the smallest then broad checks." });
119
171
  subagent({ agent: "reviewer", task: "Review the diff of src/index.ts and tests/load.test.ts for correctness and edge cases." });
120
172
  ```
121
173
 
@@ -124,12 +176,33 @@ subagent({ agent: "reviewer", task: "Review the diff of src/index.ts and tests/l
124
176
  ```ts
125
177
  subagent({
126
178
  tasks: [
127
- { agent: "explore", task: "Where is the model fallback logic?" },
179
+ { agent: "explore", task: "Where is the selected-to-main handoff logic?" },
128
180
  { agent: "worker", task: "Add unit tests for models.ts." },
129
181
  ],
130
182
  });
131
183
  ```
132
184
 
185
+ ### Cleanup routing and lifecycle
186
+
187
+ The injected guidance routes `cleaner` by explicit semantic intent: **code cleanup**,
188
+ **dead code**, **代码清理**, **精简**, **清理冗余**, **简化**, or **去除过度设计**.
189
+ Requested periodic maintenance passes also qualify; PR counts do not, and cleaner is
190
+ never run automatically as the pre-commit gate.
191
+
192
+ - **Audit mode:** audit/find/report/review or 审计/查找/检查/报告 wording produces
193
+ read-only ranked evidence.
194
+ - **Apply mode:** explicit remove/clean/simplify/refactor or 清理/删除/移除/精简/简化/重构
195
+ wording permits the smallest proven edits plus narrow-then-broad verification.
196
+
197
+ ```text
198
+ explicit cleanup intent → cleaner (audit or apply)
199
+ cleaner apply → reviewer gate → worker auto-fix (on REVIEW_FAIL) → reviewer
200
+ ```
201
+
202
+ `reviewer` remains the independent gate for non-trivial cleaner edits. The auto-fix
203
+ portion runs only when enabled by `maxFixRounds`; cleaner itself is not a pre-commit
204
+ hook or a PR-count scheduler.
205
+
133
206
  ### Vision tasks (screenshots / mockups / designs)
134
207
 
135
208
  When a task may require viewing images — frontend work, UI review, design
@@ -144,11 +217,10 @@ subagent({
144
217
  ```
145
218
 
146
219
  The sub-agent reads images with its `read` tool. Runtime order for a
147
- vision-flagged run is configured `visionModel` → that agent's configured backup
148
- current main-window model (deduplicated). A stale configured ref is attempted
149
- once, then skipped as a permanent candidate error; it is not rewritten. A
150
- vision-flagged auto-fix chain keeps the flag for worker/re-review rounds because
151
- they may need to inspect the same images.
220
+ vision-flagged run is `visionModel` → current main-window model. A stale or
221
+ currently unavailable vision selection is skipped immediately without rewriting
222
+ it. A vision-flagged auto-fix chain keeps the flag for worker/re-review rounds
223
+ because they may need to inspect the same images.
152
224
 
153
225
  ### Controlling and stopping
154
226
 
@@ -180,8 +252,10 @@ subagent_control({ action: "fork", id: 7, objective: "Try the smaller alternativ
180
252
 
181
253
  Single tasks default to `isolation: "shared"`. Parallel `worker` tasks default
182
254
  to `isolation: "worktree"`; opt into shared mode only when a worker must see the
183
- caller's live uncommitted tree. Worktree mode requires a Git repository with a
184
- committed `HEAD` and is rejected for read-only agents.
255
+ caller's live uncommitted tree. `cleaner` is also write-capable and supports
256
+ worktree mode when explicitly requested (its default remains shared). Worktree
257
+ mode requires a Git repository with a committed `HEAD` and is rejected for the
258
+ read-only `explore` and `reviewer` agents.
185
259
 
186
260
  A parked isolated thread keeps its current worktree. Resume it there; fork is
187
261
  available after that isolated checkpoint settles and its seed is integrated.
@@ -201,26 +275,23 @@ sessions show the recovery paths again until the artifacts are removed.
201
275
  ## Configuration
202
276
 
203
277
  Stored at `~/.pi/agent/pi-subagents.json` (follows `PI_CODING_AGENT_DIR` when
204
- set). The `/subagents-setup` wizard drives every field interactively — models, the
205
- default plus each enabled agent's thinking level, the vision model, concurrency,
206
- fix rounds, idle timeout, scope, and injection with a per-agent "configure
207
- one" menu when the config already exists. Model pickers show only models in the
208
- current session scope that are available through a configured API key or OAuth
209
- session. `notifyOnReviewPass` and `maxResultLines` are edited directly in the file.
278
+ set). `/subagents-setup` has five top-level choices: enable agents, configure one
279
+ agent's model/thinking, choose a vision model, runtime settings, or full setup.
280
+ There is no backup pool or global thinking menu. Model pickers show only in-scope
281
+ models with configured authentication and display their real supported thinking
282
+ levels. Thinking defaults to **Auto**; manual overrides show only levels supported
283
+ by that agent's effective model. `notifyOnReviewPass` and `maxResultLines` remain
284
+ direct-file settings.
210
285
 
211
286
  ```json
212
287
  {
213
- "enabledAgents": ["explore", "worker", "reviewer"],
288
+ "enabledAgents": ["explore", "worker", "cleaner", "reviewer"],
214
289
  "agentModels": {
215
290
  "explore": "anthropic/claude-haiku-4-5"
216
291
  },
217
- "agentBackupModels": {
218
- "explore": "openai/gpt-5-mini"
219
- },
220
292
  "agentThinkingLevels": {
221
- "explore": "low"
293
+ "reviewer": "high"
222
294
  },
223
- "thinkingLevel": "high",
224
295
  "visionModel": "anthropic/claude-sonnet-4-5",
225
296
  "notifyOnReviewPass": false,
226
297
  "maxResultLines": 80,
@@ -235,45 +306,64 @@ session. `notifyOnReviewPass` and `maxResultLines` are edited directly in the fi
235
306
  | Field | Description |
236
307
  | --- | --- |
237
308
  | `enabledAgents` | Agent names exposed to discovery and prompt injection. An empty array disables all agents. |
238
- | `agentModels` | Optional primary `provider/model-id` override per agent. |
239
- | `agentBackupModels` | Optional backup per agent, tried after its primary and before the current main-window model. |
240
- | `agentThinkingLevels` | Optional thinking level per agent; agents without an entry use the agent's frontmatter `thinking`, then `thinkingLevel`. |
241
- | `thinkingLevel` | Default thinking level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` (default `high`). |
309
+ | `agentModels` | Optional selected `provider/model-id` per agent. Missing = current main model. Model-level failure hands directly to current main. |
310
+ | `agentThinkingLevels` | Optional manual preference per agent. Missing = Auto (agent frontmatter preference, or `high`, clamped to the effective model's supported levels). |
242
311
  | `visionModel` | Optional vision-capable model for `vision: true` tasks (screenshots/mockups/designs). Unset = falls back to the main session's current model. |
243
312
  | `notifyOnReviewPass` | When `true`, a passing reviewer result is delivered without waking the main agent (default `false`). |
244
- | `maxResultLines` | Max lines of a sub-agent result carried in the completion message (default `80`). Longer results are truncated; the full text is written to a temp file whose path is included in the message. |
313
+ | `maxResultLines` | Max lines of a sub-agent result carried in the completion message (default `80`). Longer results are truncated; full text is written to an extension-named temporary `.md`. At session start and on each write, only recognized result files older than 7 days are removed; each canonical project path has its own newest-50 bucket. |
245
314
  | `proactiveInjection` | Whether to add the delegation directive to the main system prompt. |
246
315
  | `agentScope` | `user`, `project`, or `both`; controls which user/project agent directories are discovered. |
247
316
  | `maxConcurrency` | Max sub-agent processes running at once (1–16, default 4), and the max tasks one parallel `subagent` call accepts. Extra work waits in the queue. |
248
317
  | `maxFixRounds` | Auto-fix rounds when a reviewer returns `REVIEW_FAIL` (default 2; `0` disables the loop). |
249
- | `idleTimeoutSec` | Idle watchdog: a sub-agent whose stdout goes silent for this long is terminated and retried. `0` disables it. Default 90. |
318
+ | `idleTimeoutSec` | Idle watchdog: a sub-agent whose stdout goes silent for this long is terminated; a selected model then hands to current main. `0` disables it. Default 90. |
250
319
 
251
- ### Model precedence and fallback
252
-
253
- Normal run pool:
320
+ ### Model routing and thinking
254
321
 
255
322
  ```text
256
- configured agent primaryconfigured agent backup → current main-window model
323
+ selected agent/vision model → current main-window model
257
324
  ```
258
325
 
259
- If no primary is configured, the current main-window model is primary; the
260
- agent frontmatter model is used only when no current main model exists. For
261
- vision runs, `visionModel` replaces the first slot while the selected agent's
262
- backup and current main model remain the fallbacks. Duplicate refs are removed.
263
-
264
- Each candidate gets startup-race retries. Provider failures retry the same
265
- candidate up to five times only when transient (timeouts, network, 429, 5xx).
266
- Permanent model/config failures (`model not found`, unknown provider, 404) and
267
- quota/auth/billing failures skip that delay and advance immediately. No runtime
268
- outcome rewrites `pi-subagents.json`. If the whole pool fails, the result is
269
- handed to the main window with its retained run id and session.
326
+ Without a selected model, current main runs immediately; agent frontmatter model
327
+ is used only when no main model exists. A selection missing from Pi's live
328
+ available catalog is skipped. Any model-level runtime failure rate limit,
329
+ quota, invalid key/auth, missing model, provider error, or idle model stream
330
+ hands directly to current main, including stream errors that retain partial text.
331
+ A child-only Pi extension wraps the selected provider's registered API stream
332
+ with `maxRetries: 0`; if Pi schedules its separate outer turn retry, the RPC parent
333
+ immediately sends `abort_retry` before another provider call. This uses supported
334
+ extension/RPC surfaces in Node and standalone/Bun builds, never rewrites global or
335
+ project settings, and does not alter descendant tool environments. Tool/test
336
+ failures stay on the same model because they are task failures, not model
337
+ availability failures. Only a truly
338
+ zero-activity process startup race can retry; an accepted prompt or any
339
+ agent/turn/stream/tool activity forbids replay.
340
+
341
+ Auto thinking starts from the Agent's declared preference (`low` for `explore`,
342
+ `high` for the other built-ins) and uses Pi's capability map to clamp it to the
343
+ actual model. Non-reasoning models resolve to `off`; `xhigh`/`max` appear in setup
344
+ only when that model explicitly supports them. A selected→main handoff re-clamps
345
+ thinking for the main model.
346
+
347
+ ### Choosing an explore model
348
+
349
+ Choose a competent fast code model for `explore`, not automatically the cheapest
350
+ model. Cheap reconnaissance is useful for mechanical symbol/path discovery, but
351
+ a missed dynamic entrypoint or ownership edge can cost more through downstream
352
+ rework. Direct main-model handoff handles provider/runtime failure; it cannot
353
+ detect a plausible but incomplete answer.
354
+
355
+ `explore` therefore returns an index of exact paths, lines, symbols, and explicit
356
+ uncertainty. The main agent, worker, or cleaner must re-read load-bearing files
357
+ before editing or deciding deletion, security, compatibility, persistence, or
358
+ dynamic reachability. Prefer a stronger model or direct specialist for complex
359
+ dynamic loading, concurrency, migrations, and security-sensitive code.
270
360
 
271
361
  ### Resuming retained context
272
362
 
273
- Every run stores its Pi session in a private temp directory. Same-model retries
274
- and pool fallbacks resume that session, so searches, reads, reasoning, and edits
275
- remain in context. A parked, completed, or failed thread can later be resumed
276
- under its stable id:
363
+ Every run stores its Pi session in a private temp directory. A selected→main
364
+ handoff resumes that same session, so searches, reads, reasoning, and edits remain
365
+ in context. A parked, completed, or failed thread can later be resumed under its
366
+ stable id:
277
367
 
278
368
  ```ts
279
369
  subagent_control({ action: "resume", id: 7 });
@@ -286,11 +376,14 @@ sessions live until the parent Pi session shuts down.
286
376
 
287
377
  ### Configuration migration
288
378
 
289
- The config file migrates itself on load — no manual steps after an upgrade:
290
- schema upgrades are normalized and saved back, removed agents are stripped,
291
- legacy keys (`maxParallelTasks`, `maxSubagentDepth`) are folded in or dropped,
292
- and new fields are filled with defaults. New features are announced to you once
293
- after an update via a toast (marker persisted in `announcedFeatures`).
379
+ The config file normalizes itself on load — no manual steps after an upgrade.
380
+ Configured non-empty agent names are preserved, while invalid and obsolete keys
381
+ are removed. This release deletes `agentBackupModels` and global `thinkingLevel`
382
+ in addition to older `maxParallelTasks` / `maxSubagentDepth`; per-agent thinking
383
+ preferences remain and are capability-clamped at runtime. A pre-existing explicit
384
+ `enabledAgents` array is still preserved without appending `cleaner`. Existing
385
+ configs without it receive a one-time `/subagents-setup` notice, tracked internally
386
+ in `announcedFeatures`.
294
387
 
295
388
  ## Agent discovery and overrides
296
389
 
@@ -305,14 +398,15 @@ after an update via a toast (marker persisted in `announcedFeatures`).
305
398
 
306
399
  ## How it stays reliable
307
400
 
308
- - **Ordered model resilience** — transient failures retry the same candidate,
309
- then advance through configured backup and current-main candidates. Permanent
310
- stale-model/config and quota/auth/billing errors skip same-model backoff.
401
+ - **Direct model recovery** — unavailable selections skip immediately; any
402
+ selected-model provider/auth/quota/rate-limit failure hands directly to current
403
+ main with thinking re-clamped to the main model.
311
404
  - **Startup-race retries** — a silent zero-activity child exit (concurrent pi
312
405
  startup lock contention) is relaunched with backoff; only clean silent exits
313
406
  qualify, so real work is never duplicated.
314
- - **Idle watchdog** — a stalled provider stream (no output for `idleTimeoutSec`)
315
- terminates the child and retries via the normal fallback path.
407
+ - **Idle watchdog** — a stalled selected-model stream (no output for
408
+ `idleTimeoutSec`) terminates the child and hands the retained session to current
409
+ main.
316
410
  - **Dispatch failures surface** — partial parallel startup reports every failed
317
411
  item and reason; if none start, the tool throws so Pi records a real tool error.
318
412
  Dispatch crashes likewise produce a failed result instead of a silent hang.
@@ -328,11 +422,10 @@ npm test
328
422
  ```
329
423
 
330
424
  The source is modular: `dispatch.ts` (dispatch, controls, isolation, auto-fix),
331
- `rpc-run.ts` / `spawn.ts` (persistent child transport + model pools),
332
- `worktree.ts` / `session-fork.ts` (filesystem/session branching),
333
- `trajectory.ts` (internal lifecycle history), `tools.ts`
334
- (wait/status/control/stop), `announcements.ts` (recovery and feature notices),
335
- and `runtime.ts` (session-scoped ownership). No runtime dependencies beyond pi peer
425
+ `rpc-run.ts` / `spawn.ts` (persistent child transport + selected→main handoff),
426
+ `worktree.ts` / `session-fork.ts` (filesystem/session branching), `tools.ts`
427
+ (wait/status/control/stop), `widget.ts` (active-only TUI status), `announcements.ts`
428
+ (recovery and feature notices), and `runtime.ts` (session-scoped ownership). No runtime dependencies beyond pi peer
336
429
  dependencies.
337
430
 
338
431
  ## License
@@ -0,0 +1,51 @@
1
+ ---
2
+ name: cleaner
3
+ description: Evidence-first code cleanup agent with full tools. Use for explicit or periodic cleanup intent in any language, such as code cleanup, dead code, reducing redundancy, simplifying, or removing over-engineering. Audit/find/inspect/report wording means read-only ranked evidence; explicit remove/clean/simplify/refactor wording enables the smallest proven edits plus verification. Never trigger from PR counts or use it as the pre-commit gate; reviewer remains the gate and reviews cleaner edits.
4
+ model: claude-sonnet-4-5
5
+ thinking: high
6
+ # Model selection: REASONING + CODEBASE TRACING. Cleanup requires proving reachability
7
+ # and ownership before editing. No `tools` field => all tools (write-capable).
8
+ ---
9
+
10
+ You are a cleaner agent: an evidence-first specialist for reducing accidental codebase complexity. You have full tools but edit only in apply mode. You have NOT got the caller's conversation history; the task brief is your complete input.
11
+
12
+ A candidate is not a deletion. Static tools, search counts, apparent duplication, and prior reconnaissance only produce leads. Never inherit deletion proof from an `explore` report: re-read load-bearing files and repeat the decisive searches yourself. Remove code only after proving consumers, reachability, ownership, history, boundaries, and verification. A result with no safe cuts is valid.
13
+
14
+ ## Choose the mode
15
+ - **Audit mode** — cleanup wording such as audit, find, inspect, review, or report: do not edit. Return a short ranked set of evidence-backed candidates.
16
+ - **Apply mode** — explicit cleanup wording such as remove, clean up, simplify, or refactor: make only the smallest proven cuts, then verify them.
17
+ - If wording conflicts or would remove a user capability, public API, persisted format, wire contract, or compatibility path, stop at evidence and state the product tradeoff unless the brief explicitly approves it.
18
+ - This agent is for explicit cleanup intent, including periodic maintenance passes. It is never scheduled by PR count and never replaces `reviewer` as the pre-commit gate.
19
+
20
+ ## Evidence-first workflow
21
+ 1. Read repository instructions, manifests, architecture/decision records, and test guidance. Inspect `git status` and preserve unrelated work. Identify generated, vendored, fixture, migration, and published surfaces.
22
+ 2. Trace real runtime paths through entrypoints, configuration, registries, dynamic imports, dependency injection, events, queues, persistence, processes, and protocols. Start with central production surfaces, not isolated unused-looking symbols.
23
+ 3. In apply mode, discover narrow and broad checks and run a proportional baseline when feasible. Record an already-red baseline; it cannot prove a regression later.
24
+ 4. Survey for unconsumed APIs/config, duplicate facts or lifecycle state, speculative abstractions, forwarding-only layers, abandoned compatibility/support residue, and hand-rolled infrastructure already covered by the platform or installed dependencies.
25
+ 5. For each candidate, search symbols, paths, strings, alternate call forms, docs, tests, and package metadata across the repository. Inspect callers and callees. Distinguish production consumers from support-only references and ambiguous dynamic/plugin/reflection/codegen entrypoints.
26
+ 6. Read relevant history and decisions. Map stateful or asynchronous ownership: who creates, mutates, cancels, disposes, and observes each state or terminal outcome. State what behavior a cut gives up, even when the answer is none observable.
27
+ 7. Reject or downgrade the cut when a real consumer exists; dynamic/external reachability is unresolved; current rationale still holds; complexity merely moves elsewhere; or the change is actually a product/API decision.
28
+
29
+ Never simplify away authorization, validation at trust boundaries, security controls, accessibility basics, data-loss protection, durable-data compatibility, public contracts, or resource-quiescence cleanup without explicit approval.
30
+
31
+ ## Apply proven cuts
32
+ - Work within one ownership boundary at a time and keep batches reviewable.
33
+ - Delete an obsolete contract end to end: declaration, implementation, callers, branches, exports, config, dependencies, dedicated tests, docs, examples, snapshots, and generated inventories.
34
+ - Preserve tests of surviving observable behavior. Prefer deletion, then platform features, then dependencies already present; do not add replacement glue that erases the net reduction.
35
+ - Re-search removed names and stale documentation. Run the narrowest decisive check first, then the repository's relevant broad type/lint/test/build gates. Inspect the complete diff and run `git diff --check` when available.
36
+ - Do not weaken a meaningful check to force a cut through. Repair or revert only the current batch when evidence fails.
37
+
38
+ ## Report
39
+ For an audit, rank candidates by confidence, risk, and estimated net maintenance reduction using compact evidence:
40
+
41
+ ```text
42
+ [confidence / risk] candidate
43
+ evidence: consumers, dynamic/public/compatibility checks, history and owner
44
+ cut: exact contracts, artifacts, dependencies, and concepts removed
45
+ tradeoff: observable behavior lost, or none proven
46
+ verify: smallest decisive check; estimated net reduction
47
+ ```
48
+
49
+ For applied work, report exact files/contracts removed, measurable net reduction, tradeoffs, and every check actually run with its result. Name valuable candidates kept and why. Never equate green tests with proof, or deletion volume with value.
50
+
51
+ Finish by recommending a fresh `reviewer` pass over any edits. The reviewer, not cleaner, is the pre-commit gate.
package/agents/explore.md CHANGED
@@ -4,16 +4,17 @@ description: Fast read-only codebase reconnaissance. Use PROACTIVELY for broad o
4
4
  tools: read, grep, find, ls, bash
5
5
  model: claude-haiku-4-5
6
6
  thinking: low
7
- # Model selection: SPEED over depth. Pick the fastest available model.
8
- # What matters: fast grep/find/read, structured output. What doesn't: deep reasoning.
7
+ # Model selection: SPEED with reliable code comprehension. Pick a competent fast
8
+ # model, not automatically the cheapest; missed architecture costs more in rework.
9
9
  ---
10
10
 
11
- You are an explore agent: a fast, read-only reconnaissance specialist. You investigate a codebase and return compressed, structured findings that another agent can act on WITHOUT re-reading the files you explored. You have NOT got the caller's conversation history — the task brief is your only input.
11
+ You are an explore agent: a fast, read-only reconnaissance specialist. You investigate a codebase and return compressed, structured findings so another agent does not repeat the whole search. The caller still re-reads load-bearing sections before acting. You have NOT got the caller's conversation history — the task brief is your only input.
12
12
 
13
13
  ## Hard constraints
14
14
  - You are READ-ONLY. Never create, edit, or delete files; never run mutating commands.
15
15
  - Bash is for read-only inspection only: `grep`, `find`, `ls`, `cat`, `git log/show/diff/status`. No installs, builds, or state changes.
16
16
  - Assume tool permissions are not perfectly enforceable; keep every command strictly read-only by intent.
17
+ - Treat every finding as a retrieval lead, never sufficient proof for deletion, security claims, public/API compatibility, persistence, or other load-bearing decisions.
17
18
 
18
19
  ## When invoked
19
20
  1. Orient with `grep`/`find` to locate the relevant code fast. Prefer bare identifiers as patterns; scope by path and exclude noisy dirs (node_modules, dist, generated).
@@ -29,6 +30,7 @@ You are an explore agent: a fast, read-only reconnaissance specialist. You inves
29
30
 
30
31
  ## Collaboration
31
32
  - Your output feeds `worker` (or the main agent directly). Hand off compressed context: exact locations + the minimum code needed to proceed. Flag anything ambiguous so the caller can decide.
33
+ - The caller must re-read load-bearing files before editing or making safety/reachability decisions. Make that verification boundary explicit instead of presenting reconnaissance as a final judgment.
32
34
 
33
35
  ## Output format
34
36
  ## Files Retrieved
@@ -41,4 +43,4 @@ A brief explanation of how the pieces connect.
41
43
  Which file to look at first, and why.
42
44
 
43
45
  ## Quality standards
44
- Terse and factual. Exact paths and line numbers. Compress — do not narrate your search process or pad with prose.
46
+ Terse and factual. Exact paths and line numbers. Compress — do not narrate your search process or pad with prose. State uncertainty and missing coverage; a plausible guess is more expensive than an honest gap.
@@ -60,5 +60,7 @@ Understand the context first, then verify: the fix addresses the root cause, cha
60
60
  One of: APPROVE / APPROVE_WITH_NITS / REQUEST_CHANGES, plus a 2-3 sentence rationale.
61
61
  End with exactly one machine-readable line: `VERDICT: REVIEW_PASS` for APPROVE or APPROVE_WITH_NITS; `VERDICT: REVIEW_FAIL` for REQUEST_CHANGES.
62
62
 
63
+ REQUEST_CHANGES (or review-blocking concern) on this extension automatically starts an auto-fix loop: a worker is briefed with your findings, then you re-review, up to the configured round limit. Choose REVIEW_PASS when nothing objectively blocks the change (style preferences, optional refactors, or items the caller can knowingly accept are not blockers) — do not force a verdict that would trigger another loop just to hedge.
64
+
63
65
  ## Quality standards
64
66
  Specific file paths and line numbers. No vague feedback. A clean report means you looked hard, not that you found nothing to say.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ferris1225/pi-subagents",
3
- "version": "1.0.0",
4
- "description": "Controllable background sub-agent threads for pi: explore, worker, reviewer, auto-fix chains, model pools, and Git worktree isolation.",
3
+ "version": "2.0.0",
4
+ "description": "Controllable background sub-agent threads for pi: specialized roles, capability-aware thinking, direct main-model fallback, auto-fix chains, and Git worktree isolation.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "publishConfig": {
@@ -12,7 +12,9 @@
12
12
  "pi-extension",
13
13
  "subagent",
14
14
  "sub-agent",
15
- "delegation"
15
+ "delegation",
16
+ "code-cleanup",
17
+ "dead-code"
16
18
  ],
17
19
  "files": [
18
20
  "src",
@@ -31,10 +33,10 @@
31
33
  "prepack": "npm run check && npm test"
32
34
  },
33
35
  "peerDependencies": {
34
- "@earendil-works/pi-agent-core": ">=0.80.6",
35
- "@earendil-works/pi-ai": ">=0.80.6",
36
- "@earendil-works/pi-coding-agent": ">=0.80.6",
37
- "@earendil-works/pi-tui": ">=0.80.6",
36
+ "@earendil-works/pi-agent-core": ">=0.83.0",
37
+ "@earendil-works/pi-ai": ">=0.83.0",
38
+ "@earendil-works/pi-coding-agent": ">=0.83.0",
39
+ "@earendil-works/pi-tui": ">=0.83.0",
38
40
  "typebox": "*"
39
41
  },
40
42
  "devDependencies": {
package/src/agents.ts CHANGED
@@ -31,11 +31,6 @@ export interface AgentConfig {
31
31
  filePath: string;
32
32
  }
33
33
 
34
- export interface AgentDiscoveryResult {
35
- agents: AgentConfig[];
36
- projectAgentsDir: string | null;
37
- }
38
-
39
34
  const here = dirname(fileURLToPath(import.meta.url));
40
35
  /** <package>/agents — the agents shipped with this extension. */
41
36
  export const BUILTIN_AGENTS_DIR = join(here, "..", "agents");
@@ -135,7 +130,7 @@ export interface DiscoverOptions {
135
130
  * Discover agents across scopes and apply the enabled-name filter.
136
131
  * Override priority for the same name: project > user > builtin.
137
132
  */
138
- export function discoverAgents(cwd: string, options: DiscoverOptions = {}): AgentDiscoveryResult {
133
+ export function discoverAgents(cwd: string, options: DiscoverOptions = {}): { agents: AgentConfig[] } {
139
134
  const scope = options.scope ?? "user";
140
135
  const builtinDir = options.builtinDir ?? BUILTIN_AGENTS_DIR;
141
136
  const projectAgentsDir = findNearestProjectAgentsDir(cwd);
@@ -160,7 +155,7 @@ export function discoverAgents(cwd: string, options: DiscoverOptions = {}): Agen
160
155
  agents = agents.filter((agent) => enabled.has(agent.name));
161
156
  }
162
157
 
163
- return { agents, projectAgentsDir };
158
+ return { agents };
164
159
  }
165
160
 
166
161
  /** One-line catalog entry for system-prompt injection and error messages. */