pi-subagents 0.37.0 → 0.37.2

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.
@@ -0,0 +1,268 @@
1
+ # Pi Subagents: Prompting And Roles
2
+
3
+ This file is a detailed reference loaded from `skills/pi-subagents/SKILL.md`.
4
+
5
+ ## Capability ceilings
6
+
7
+ Parent extensions may register a session-scoped, out-of-band ceiling through `pi-subagents/capability-ceiling`. Child tools are intersected with every active registration and inherited snapshot; `denyExtensions` removes ambient/provider extension loading while retaining package protocol runtime. Do not add a model-visible ceiling field or rely on role selection for enforcement. Restricted schedules are rejected until their ceiling can be persisted safely.
8
+
9
+ ## When to Use
10
+
11
+ - **Complex work orchestration**: use Fable mode as the default parent-agent loop for complex work. Complex means the task has multiple moving parts, unclear acceptance, cross-cutting code, meaningful user-visible impact, expensive or irreversible validation, broad review surface, or the user asks for orchestration. Lightweight one-off delegation can stay lightweight.
12
+ - **Advisory review**: use fresh-context `reviewer` agents for adversarial code review, or fork to `oracle` when inherited decisions and drift matter
13
+ - **Implementation handoff**: have `oracle` advise, then `worker` implement only after an approved direction
14
+ - **Recon and planning**: use `scout` or `context-builder`, then `planner`
15
+ - **Parallel exploration**: run multiple non-conflicting tasks concurrently
16
+ - **Regular skill specialists**: when discovery shows proactive skill subagent suggestions and the current work is broad enough, launch a small fresh-context fanout that asks one subagent per relevant regularly used skill to apply that skill's perspective to the task
17
+ - **Long-running work**: launch async/background runs and inspect them later. For mutation-capable work, bound the delivery slice and elapsed runtime, then request checkpoints after active tool work returns. Reserve hard turn and tool-call caps for explicitly read-only children.
18
+ - **Subagent control**: watch needs-attention signals and soft-interrupt only when a delegated run is genuinely blocked
19
+ - **Agent authoring**: create, update, or override agents and chains for a project
20
+
21
+ ## Tool vs Slash Commands
22
+
23
+ Agents can use the `subagent(...)` tool directly for execution, management, status, and control.
24
+ Humans often use the slash-command layer instead:
25
+
26
+ - `/run` — launch a single agent
27
+ - `/chain` — launch a chain of steps
28
+ - `/parallel` — launch top-level parallel tasks
29
+ - `/run-chain` — launch a saved `.chain.md` or `.chain.json` workflow
30
+ - `/subagents` — interactive admin for inspecting agents and editing model, thinking, or system prompt
31
+ - `/subagents-stop [run-id]` — stop a current-session top-level async run; opens a selector when no id is given
32
+ - `/subagent-cost` — show parent plus child token usage and cost for the session
33
+ - `/subagents-fleet` — open the live, inspection-only foreground/async fleet; `Ctrl+Alt+F` opens it during an active foreground turn, `↑↓`/`jk` selects children, and `PgUp`/`PgDn` scrolls transcript detail
34
+ - `/subagents-watchdog` — inspect or configure the opt-in adversarial change watchdog (model, on/off, recommend-model, check)
35
+ - `/subagents-doctor` — diagnose setup, discovery, async paths, and intercom bridge state
36
+ - `/subagents-models [agent]` — show the live runtime-loaded builtin model mapping
37
+ - `/subagents-profiles`, `/subagents-load-profile`, `/subagents-refresh-provider-models`, `/subagents-generate-profiles`, `/subagents-check-profile` — manage model profiles and provider catalogs
38
+ - `/prompt-workflow` and `/chain-prompts` — run prompt templates through native subagent single/chain workflows
39
+
40
+ Prefer the tool when you are writing agent logic. Prefer the slash commands when
41
+ you are guiding a human through an interactive flow.
42
+
43
+ Packaged prompt shortcuts are also available for repeatable workflows. Treat them as reusable orchestration recipes, not just human slash commands. When the user asks for one of these shapes, or when the workflow clearly fits, apply the same pattern directly with `subagent(...)` and other tools:
44
+ - `/parallel-review` — fresh-context reviewers with distinct review angles, then synthesis
45
+ - `/review-loop` — parent-orchestrated worker, fresh-reviewer, and fix-worker cycles until clean or capped
46
+ - `/parallel-research` — combine `researcher` and `scout` for external evidence plus local code context
47
+ - `/parallel-context-build` — parallel `context-builder` passes that produce planning handoff context and meta-prompts
48
+ - `/parallel-handoff-plan` — external-reference research plus local `context-builder` passes, followed by a synthesis handoff plan and implementation-ready meta-prompt
49
+ - `/gather-context-and-clarify` — scout/research first, then ask the user clarifying questions with `interview`
50
+ - `/parallel-cleanup` — two fresh-context reviewers (deslop + verbosity passes) for an adversarial cleanup review of the current diff
51
+
52
+ ## Applying Prompt Techniques Without Slash Commands
53
+
54
+ The prompt templates in `prompts/` encode workflows the parent agent can run on demand. If the user provides a URL, issue, PR, plan, local file, screenshot, or freeform target, treat that target as the primary scope: read or fetch it before launching children, then include it explicitly in every child task. Do not depend on the parent conversation history when the recipe calls for fresh context.
55
+
56
+ ### Parallel review technique
57
+
58
+ Use this when the user wants adversarial review of a diff, plan, issue, file, or implemented work. Launch fresh-context `reviewer` agents with distinct angles generated from the actual target. Common angles are correctness/regressions, tests/validation, and simplicity/maintainability; adapt for TypeScript, UI, security, docs, or large structural changes. Reviewers should inspect files and diffs directly, return concise evidence-backed findings with file/line references, and avoid edits unless the user explicitly asks for a writer pass. The parent synthesizes fixes worth doing now, optional improvements, and feedback to ignore/defer before applying anything.
59
+
60
+ ### Proactive skill-specialist technique
61
+
62
+ Use this when `{ action: "list" }` reports proactive skill subagent suggestions and the user's task would benefit from perspectives the parent regularly uses. These suggestions are conservative: a skill is recommended only when it is available and referenced repeatedly by configured agents or saved chains. Treat the list as an opt-in hint for the current task, not a command to always fan out.
63
+
64
+ Default guardrails:
65
+ - Keep the fanout small: usually one or two skill-specialist children, never more than the listed recommendations or configured cap.
66
+ - Prefer `context: "fresh"` and include only the files, diff, plan, URL, or request details each child needs. Use forked context only when private/session history is essential and appropriate to share.
67
+ - Use read-only agents for analysis/review unless implementation was explicitly requested; do not create several writers in the same worktree.
68
+ - Skip proactive skill subagents for tiny questions, direct commands, highly private requests, or when the user asks not to delegate.
69
+ - Make cost and concurrency visible by using an ordinary `subagent(...)` call rather than hidden/background automation.
70
+
71
+ Example shape:
72
+
73
+ ```typescript
74
+ subagent({
75
+ tasks: [
76
+ { agent: "reviewer", task: "Apply the available 'deslop' skill to review the current diff for concrete cleanup findings only. Do not modify files.", skill: "deslop" },
77
+ { agent: "reviewer", task: "Apply the available 'accessibility' skill to review the UI changes for concrete issues only. Do not modify files.", skill: "accessibility" }
78
+ ],
79
+ context: "fresh",
80
+ concurrency: 2
81
+ })
82
+ ```
83
+
84
+ ### Review-loop technique
85
+
86
+ Use this when the user wants implementation or current diff review to continue until reviewers stop finding fixes worth doing now. Keep the loop in the parent session: one async `worker` implements or fixes, fresh-context `reviewer` agents inspect the actual repo and diff, the parent synthesizes accepted fixes, and one async forked `worker` applies them. The parent can express the sequence up front as an async/background chain when the workflow is known, or continue with explicit follow-up subagent runs after each async completion. For an initial chain, pass `async: true` so the main chat is unblocked; do not set `clarify: true` unless the user explicitly wants the foreground clarify UI. Treat an async implementation worker handoff as an intermediate state, not final completion, unless the user explicitly asked for worker-only work, review-only output, or to stop after implementation. Stop when reviewers find no blockers or fixes worth doing now, remaining feedback is optional or deferred, an unapproved product/scope/architecture decision appears, or the max review-round cap is reached. Default to 3 review rounds unless the user sets a different cap. Do not loop for optional polish, and do not let children launch subagents or decide the loop outcome.
87
+
88
+ As a conservative orchestration policy, do not pass `turnBudget` or a hard `toolBudget` to an implementation worker, fix worker, reviewer with edit authority, or other mutation-capable child. The default tool budget blocks read/search tools rather than mutation tools, but count limits still do not measure delivery safety. Use a narrow task plus an outer elapsed deadline with enough margin, then request a checkpoint after the current tool returns. The checkpoint should report changed files, build/test state, remaining work, and commit or PR state. An elapsed timeout is not a mutation-safe boundary and must not be used as the checkpoint trigger.
89
+
90
+ ### Parallel research technique
91
+
92
+ Use this when the question needs both external evidence and local implications. Combine `researcher` for official docs, specs, ecosystem behavior, recent changes, benchmarks, and primary sources with `scout` for repository files, patterns, constraints, tests, and likely integration points. Give each child a distinct angle: external evidence, local code context, and practical tradeoffs. Ask for source links or file ranges, confidence level, gaps, and decision implications. Do not ask these children to edit unless implementation was explicitly requested.
93
+
94
+ ### Parallel context-build technique
95
+
96
+ Use this before planning or implementation when a stronger handoff is needed. Run a chain with one parallel step of `context-builder` agents rather than top-level parallel tasks, so relative output files live under the temporary chain directory. Give every task a distinct output path such as `context-build/request-and-scope.md`, `context-build/codebase-and-patterns.md`, and `context-build/validation-and-risks.md`. Choose two or three builders: request/scope, codebase/patterns, and validation/risks. Each builder must read every relevant file needed to understand its slice, follow imports/callers/tests/docs/config, conduct tool-available web research when needed, and include a compact `meta-prompt` section. The parent synthesizes the outputs into important context, recommended next meta-prompt, open questions, assumptions, and artifact paths.
97
+
98
+ Example shape:
99
+
100
+ ```typescript
101
+ subagent({
102
+ chain: [{
103
+ parallel: [
104
+ { agent: "context-builder", task: "Build request/scope context for: ...", output: "context-build/request-and-scope.md" },
105
+ { agent: "context-builder", task: "Build codebase/pattern context for: ...", output: "context-build/codebase-and-patterns.md" },
106
+ { agent: "context-builder", task: "Build validation/risk context for: ...", output: "context-build/validation-and-risks.md" }
107
+ ]
108
+ }],
109
+ context: "fresh"
110
+ })
111
+ ```
112
+
113
+ ### Parallel handoff-plan technique
114
+
115
+ Use this when the user needs a solution brief or implementation-ready handoff from an external reference plus local code context, such as “study this library behavior, inspect our codebase, then produce a worker prompt.” Run a chain with a first parallel group and a second synthesis `context-builder` step. The first group usually includes `researcher` for external projects/docs/prompt guidance and `context-builder` for local code context; add a second `context-builder` for implementation strategy only when the scope is large enough to benefit. Use distinct output paths under `handoff/`, then have the synthesis `context-builder` read those outputs and write `handoff/final-handoff-plan.md` with the recommended approach, likely files, constraints, non-goals, validation, risks, unresolved questions, and final compact implementation-ready meta-prompt.
116
+
117
+ Example shape:
118
+
119
+ ```typescript
120
+ subagent({
121
+ chain: [
122
+ { parallel: [
123
+ { agent: "researcher", task: "Research the external reference and transferable implementation ideas for: ...", output: "handoff/external-reference.md" },
124
+ { agent: "context-builder", task: "Build local codebase context for: ...", output: "handoff/local-context.md" },
125
+ { agent: "context-builder", task: "Compare evidence and propose implementation strategy for: ...", output: "handoff/implementation-strategy.md" }
126
+ ] },
127
+ { agent: "context-builder", task: "Read {previous} and synthesize the final handoff plan and implementation-ready meta-prompt.", output: "handoff/final-handoff-plan.md" }
128
+ ],
129
+ context: "fresh"
130
+ })
131
+ ```
132
+
133
+ ### Gather-context-and-clarify technique
134
+
135
+ Use this at the start of non-trivial work. Launch `scout` for local context and `researcher` only when external docs, recent sources, ecosystem context, or primary evidence would materially improve understanding. Ask children for concise findings plus remaining clarification questions. Then synthesize what is known and use `interview` to ask the unresolved questions needed for shared understanding before planning or implementing.
136
+
137
+ ### Parallel cleanup technique
138
+
139
+ Use this after implementation when the user wants cleanup review or when a final pass would reduce AI-slop. Launch two fresh-context `reviewer` tasks with `output: false` and `progress: false`: one deslop pass and one verbosity pass. If the `deslop` or `verbosity-cleaner` skills are available, pass the relevant skill to that reviewer; otherwise inline the criteria. Both reviewers are review-only and should flag concrete issues with severity, file/line references, and smallest safe fixes. Phrase the constraint as “Do not modify project/source files; returning findings through the configured output artifact is allowed” when you use `output` or `outputMode: "file-only"`. The parent decides what to apply and asks before making changes unless cleanup was already authorized.
140
+
141
+ ### Staged fix orchestration technique
142
+
143
+ Use this when a broad diff has known reviewer findings across several items and the user wants the parent to “orchestrate subagents like a boss.” Keep the active worktree safe with a three-stage chain:
144
+
145
+ 1. A parallel read-only planning fanout, one planner/reviewer per issue cluster. Each child inspects the real diff and returns exact files, line refs, proposed fixes, and focused validation. They must not edit.
146
+ 2. One writer worker. It receives the planner summaries through `{previous}`, the parent’s accepted scope, stop rules, and verification contract. It is the only child allowed to edit the active worktree.
147
+ 3. A parallel read-only validation fanout. Validators inspect the worker diff from fresh context with distinct angles, report pass/fail, remaining blockers, and missing verification.
148
+
149
+ Prefer `async: true`, `context: "fresh"` for planners/validators, `outputMode: "file-only"` for large summaries, and per-stage output names that will not collide. Add `phase` and `label` to make async status readable, and use `as` plus `{outputs.name}` when a later step needs a specific earlier result instead of the whole `{previous}` blob. Use this pattern instead of launching several writer workers into a dirty worktree. Include non-blocking suggestions in the writer prompt only when they are small, safe, and do not expand product scope; otherwise record them as deferred.
150
+
151
+ When the first step can return a structured target list, prefer dynamic fanout instead of hand-authoring a static parallel group. Use `outputSchema` and `as` on the producer, then an `expand` step with `from: { output, path }`, an explicit `maxItems`, one `parallel` child template, and `collect.as`. Item templates may use `{item}` or a named item such as `{target.path}`. Do not use dynamic fanout for prose outputs, nested fanout, dynamic agent selection, reducers, `when` conditions, or arbitrary expressions; `.chain.md` does not support this syntax, so use direct JSON or a saved `.chain.json`.
152
+
153
+ Example shape:
154
+
155
+ ```typescript
156
+ subagent({
157
+ async: true,
158
+ context: "fresh",
159
+ chain: [
160
+ { parallel: [
161
+ { agent: "reviewer", phase: "Planning", label: "Deploy docs", as: "deployPlan", task: "Plan fixes for deploy docs/workflow. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/deploy.md", outputMode: "file-only" },
162
+ { agent: "reviewer", phase: "Planning", label: "Scheduler contract", as: "schedulerPlan", task: "Plan fixes for scheduler contract. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/scheduler.md", outputMode: "file-only" },
163
+ { agent: "reviewer", phase: "Planning", label: "Sandbox/security", as: "sandboxPlan", task: "Plan fixes for sandbox/security. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/sandbox.md", outputMode: "file-only" }
164
+ ], concurrency: 3 },
165
+ { agent: "worker", phase: "Implementation", label: "Apply accepted fixes", as: "workerResult", task: "Apply only the accepted fixes from these planning summaries. You are the sole writer for the active worktree. Run focused validation and report changed files, commands, failures, and remaining issues.\n\nDeploy plan:\n{outputs.deployPlan}\n\nScheduler plan:\n{outputs.schedulerPlan}\n\nSandbox plan:\n{outputs.sandboxPlan}", output: "worker/fixes.md", outputMode: "file-only", progress: true },
166
+ { parallel: [
167
+ { agent: "reviewer", phase: "Validation", label: "Deploy/scheduler validation", task: "Validate the post-worker diff for deploy and scheduler fixes. Start from the worker result: {outputs.workerResult}. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/deploy-scheduler.md", outputMode: "file-only" },
168
+ { agent: "reviewer", phase: "Validation", label: "Sandbox validation", task: "Validate the post-worker diff for sandbox/security fixes. Start from the worker result: {outputs.workerResult}. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/sandbox.md", outputMode: "file-only" }
169
+ ], concurrency: 2 }
170
+ ]
171
+ })
172
+ ```
173
+
174
+ ## Builtin Agents
175
+
176
+ Builtin agents load at the lowest priority. Project agents override user agents,
177
+ and user/project agents override builtins with the same name.
178
+
179
+ | Agent | Purpose | Model | Typical output / role |
180
+ |-------|---------|-------|------------------------|
181
+ | `scout` | Fast codebase recon | inherits default | Writes `context.md` handoff material |
182
+ | `planner` | Creates implementation plans | inherits default | Writes `plan.md` |
183
+ | `worker` | Implementation and approved oracle handoffs | inherits default | Single-writer implementation with decision escalation |
184
+ | `reviewer` | Review specialist | inherits default | Default recipes are review-only; tools include edit/write when a fix pass is explicit |
185
+ | `context-builder` | Requirements/codebase handoff builder | inherits default | Writes structured context files |
186
+ | `researcher` | Web research brief generator | inherits default | Writes `research.md` |
187
+ | `delegate` | Lightweight generic delegate | inherits default | No fixed output; generic delegated work |
188
+ | `oracle` | Decision-consistency advisory review | inherits default | Advisory review, intercom coordination |
189
+ | `advisor` | Claude Code-compatible alias for `oracle` | inherits default | Same advisory role as `oracle` |
190
+
191
+ Builtin `worker` and `delegate` use strict tool allowlists and do not inherit ambient parent extension tools. To give a child an extension tool, name it in `tools` and load its provider via `extensions`, a path-like `tools` entry, or `subagentOnlyExtensions`. Custom agents without an `extensions` field follow `subagents.defaultExtensions` when set.
192
+
193
+ Builtin agents inherit the current Pi default model unless a run, user setting, project setting, or `subagents.defaultModel` overrides `model`. Set `subagents.defaultModel` when subagents should use a different default model than the parent session. Override builtin defaults before copying full agent files when a small tweak is enough.
194
+
195
+ Set `subagents.defaultThinking` to apply a shared thinking level to builtin, package, user, and project agents whose frontmatter leaves `thinking` unset. Project settings win over user settings; explicit frontmatter (including `thinking: false`), `agentOverrides.<name>.thinking`, and per-run overrides remain more specific. This setting affects child agents only and does not change the parent session's default thinking level.
196
+
197
+ ```json
198
+ {
199
+ "subagents": {
200
+ "defaultThinking": "medium"
201
+ }
202
+ }
203
+ ```
204
+
205
+ For one run, use inline config:
206
+
207
+ ```text
208
+ /run reviewer[model=anthropic/claude-sonnet-4] "Review this diff"
209
+ ```
210
+
211
+ For persistent tweaks, edit `subagents.agentOverrides` in user or project settings. User overrides apply everywhere. Project overrides apply only in that repo and win over user overrides. Use `/subagents-models` or `subagent({ action: "models" })` to inspect the live mapping after settings and overrides load.
212
+
213
+ Model ids do not have to be exact. Separator variations (`claude-haiku-4.5` vs `claude-haiku-4-5`), case (`Claude-Sonnet-4`), and optional trailing date stamps (`claude-haiku-4-5-20251001`) all resolve to the same registry model. Exact `provider/id` wins; a qualified `provider/model` never switches providers. To constrain subagents to a budget or compliance profile, set `subagents.modelScope: { enforce: true, allow: ["anthropic/*", "openai/gpt-5-*"] }` in user or project settings. Out-of-scope models you pass explicitly error and abort; models inherited from frontmatter, `subagents.defaultModel`, agent frontmatter, or the parent session only warn.
214
+
215
+ For model fleets, use the profile commands instead of hand-editing repeated overrides: `/subagents-refresh-provider-models <provider>`, `/subagents-generate-profiles <provider>`, `/subagents-load-profile <name>`, and `/subagents-check-profile <name>`. Profiles live under `~/.pi/agent/profiles/pi-subagents/` and replace only `settings.subagents` when loaded.
216
+
217
+ ## Prompting role subagents
218
+
219
+ Builtin role agents inherit the current Pi default model unless you override them. When launching them, write the task prompt as a compact contract, not a long procedural script. Define the destination and let the role choose the efficient path.
220
+
221
+ A strong subagent prompt usually includes:
222
+ - **Goal**: the concrete outcome the child should produce.
223
+ - **Context/evidence**: relevant plan paths, files, diffs, decisions, or user constraints already approved.
224
+ - **Success criteria**: what must be true before the child can finish.
225
+ - **Hard constraints**: true invariants only, such as no edits for review-only tasks, one writer thread, child must not run subagents unless it is an explicitly assigned `tools: subagent` fanout child, or escalation for unapproved decisions.
226
+ - **Validation**: targeted checks to run, or the next-best check when validation is impossible.
227
+ - **Output**: the expected summary shape, artifact path, or finding format.
228
+ - **Stop rules**: when to ask via `intercom`, when to stop after enough evidence, and when not to keep searching.
229
+
230
+ Avoid carrying over old prompt habits that over-specify every step. Use `must`, `always`, and `never` for real invariants; for judgment calls, give decision rules. For example, tell a reviewer to inspect the staged diff directly and report only evidence-backed findings, rather than prescribing every file or command. Tell a researcher the retrieval budget: start with broad targeted searches, fetch only the strongest sources, search again only when a required fact is missing, then stop.
231
+
232
+ For implementation handoffs, name the approved scope and success criteria more clearly than the process. Good prompts say what to change, what not to change, where the evidence lives, how to validate, and when to escalate. They should not ask the child to create another subagent plan or continue the parent conversation.
233
+
234
+ Settings locations:
235
+ - User scope: `~/.pi/agent/settings.json`
236
+ - Project scope: `.pi/settings.json`
237
+
238
+ Direct settings example:
239
+
240
+ ```json
241
+ {
242
+ "subagents": {
243
+ "agentOverrides": {
244
+ "reviewer": {
245
+ "model": "anthropic/claude-sonnet-4",
246
+ "thinking": "high",
247
+ "fallbackModels": ["openai/gpt-5-mini"],
248
+ "acceptanceRole": "read-only"
249
+ }
250
+ }
251
+ }
252
+ }
253
+ ```
254
+
255
+ Useful override fields: `model`, `fallbackModels`, `thinking`,
256
+ `systemPromptMode`, `inheritProjectContext`, `inheritSkills`, `defaultContext`,
257
+ `acceptanceRole`, `disabled`, `skills`, `tools`, `extensions`, and `systemPrompt`.
258
+ Use `acceptanceRole: false` to clear an override. Create a user or project
259
+ agent with the same name only when you want a substantially different agent.
260
+
261
+ If a provider rejects model IDs with thinking suffixes, use
262
+ `subagents.disableThinking: true` in user or project settings to clear bundled
263
+ builtin thinking defaults globally. A higher-precedence per-agent `thinking`
264
+ override can opt one builtin back in. Existing custom-agent frontmatter remains authoritative.
265
+
266
+ Set `subagents.defaultExtensions` to give agents without an `extensions` field a shared child extension allowlist. Omit it to preserve ambient extension discovery, set it to `[]` to disable ambient extensions by default, or use `agentOverrides.<name>.extensions` for one agent. Explicit custom-agent frontmatter still wins.
267
+
268
+ Tool description modes live in `~/.pi/agent/extensions/subagent/config.json`, not `subagents` settings. Set `toolDescriptionMode` to `compact` to reduce tool-description prompt cost while keeping the execution, async/`subagent_wait`, child-safety, one-writer, management/action, and artifact/status guardrails. Set it to `custom` to read `subagent-tool-description.md` from the project config dir or agent dir; invalid custom files fall back to full mode and the safety guidance is still appended.
@@ -379,19 +379,21 @@ function chooseHigherPrioritySkill(existing: CachedSkillEntry | undefined, candi
379
379
  return candidate.order < existing.order ? candidate : existing;
380
380
  }
381
381
 
382
- function maybeReadSkillDescription(filePath: string): string | undefined {
383
- try {
384
- const content = fs.readFileSync(filePath, "utf-8");
385
- const normalized = content.replace(/\r\n/g, "\n");
386
- if (!normalized.startsWith("---")) return undefined;
382
+ function parseSkillDescription(content: string): string | undefined {
383
+ const normalized = content.replace(/\r\n/g, "\n");
384
+ if (!normalized.startsWith("---")) return undefined;
385
+
386
+ const endIndex = normalized.indexOf("\n---", 3);
387
+ if (endIndex === -1) return undefined;
387
388
 
388
- const endIndex = normalized.indexOf("\n---", 3);
389
- if (endIndex === -1) return undefined;
389
+ const frontmatter = normalized.slice(3, endIndex).trim();
390
+ const match = frontmatter.match(/^description:\s*(.+)$/m);
391
+ return match?.[1]?.trim().replace(/^['\"]|['\"]$/g, "");
392
+ }
390
393
 
391
- const frontmatter = normalized.slice(3, endIndex).trim();
392
- const match = frontmatter.match(/^description:\s*(.+)$/m);
393
- if (!match) return undefined;
394
- return match[1]?.trim().replace(/^['\"]|['\"]$/g, "");
394
+ function maybeReadSkillDescription(filePath: string): string | undefined {
395
+ try {
396
+ return parseSkillDescription(fs.readFileSync(filePath, "utf-8"));
395
397
  } catch {
396
398
  // Description parsing is best-effort metadata extraction.
397
399
  return undefined;
@@ -585,7 +587,7 @@ function readSkill(
585
587
 
586
588
  const raw = fs.readFileSync(skillPath, "utf-8");
587
589
  const content = stripSkillFrontmatter(raw);
588
- const description = maybeReadSkillDescription(skillPath);
590
+ const description = parseSkillDescription(raw);
589
591
  const skill: ResolvedSkill = {
590
592
  name: skillName,
591
593
  path: skillPath,
@@ -131,6 +131,7 @@ export interface SubagentDelegationStarted {
131
131
  }
132
132
 
133
133
  export interface SubagentDelegationUpdate extends SubagentDelegationStarted {
134
+ runId?: string;
134
135
  currentTool?: string;
135
136
  currentToolArgs?: string;
136
137
  recentOutput?: string;
@@ -230,6 +231,7 @@ export interface SubagentDelegationV2Started {
230
231
  }
231
232
 
232
233
  export interface SubagentDelegationV2Update extends SubagentDelegationV2Started {
234
+ runId?: string;
233
235
  currentTool?: string;
234
236
  currentToolArgs?: string;
235
237
  recentOutput?: string;
@@ -266,6 +268,7 @@ export interface SubagentDelegationV2TerminalResponse extends SubagentDelegation
266
268
  model?: string;
267
269
  thinking?: string;
268
270
  exitCode?: number;
271
+ launchContractDigest?: string;
269
272
  result?: SubagentDelegationV2Value;
270
273
  usage?: SubagentDelegationV2Usage;
271
274
  }
@@ -26,7 +26,7 @@ import { resolveCurrentSessionId } from "../shared/session-identity.ts";
26
26
  import { cleanupOldChainDirs } from "../shared/settings.ts";
27
27
  import { clearLegacyResultAnimationTimer, renderSubagentResult } from "../tui/render.ts";
28
28
  import { openSubagentFleet } from "../tui/fleet.ts";
29
- import { SubagentFleetStatus } from "../tui/fleet-status.ts";
29
+ import { SubagentFleetStatus, resolveFleetViewPlacement } from "../tui/fleet-status.ts";
30
30
  import { SubagentParams } from "./schemas.ts";
31
31
  import { validateChainInput } from "./chain-validation.ts";
32
32
  import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
@@ -143,10 +143,13 @@ function createSlashResultComponent(
143
143
  }
144
144
 
145
145
  class SubagentControlNoticeComponent implements Component {
146
- constructor(
147
- private readonly details: SubagentControlMessageDetails,
148
- private readonly theme: ExtensionContext["ui"]["theme"],
149
- ) {}
146
+ private readonly details: SubagentControlMessageDetails;
147
+ private readonly theme: ExtensionContext["ui"]["theme"];
148
+
149
+ constructor(details: SubagentControlMessageDetails, theme: ExtensionContext["ui"]["theme"]) {
150
+ this.details = details;
151
+ this.theme = theme;
152
+ }
150
153
 
151
154
  invalidate(): void {}
152
155
 
@@ -193,6 +196,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
193
196
  const waitToolConfig = resolveWaitToolConfig(config.waitTool);
194
197
  const asyncByDefault = config.asyncByDefault === true;
195
198
  const fleetViewEnabled = config.fleetView !== false;
199
+ const fleetViewPlacement = resolveFleetViewPlacement(config.fleetViewPlacement);
196
200
  const asyncWidgetEnabled = config.asyncWidget === true || (!fleetViewEnabled && config.asyncWidget !== false);
197
201
  const tempArtifactsDir = getArtifactsDir(null);
198
202
  cleanupAllArtifactDirs(DEFAULT_ARTIFACT_CONFIG.cleanupDays);
@@ -236,14 +240,17 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
236
240
  const ctx = state.lastUiContext;
237
241
  if (!ctx?.hasUI) return;
238
242
  await openSubagentFleet(ctx, state, { initialKey: itemKey });
239
- })
243
+ }, { placement: fleetViewPlacement })
240
244
  : undefined;
241
245
  const { startResultWatcher, primeExistingResults, stopResultWatcher } = createResultWatcher(
242
246
  pi,
243
247
  state,
244
248
  RESULTS_DIR,
245
249
  10 * 60 * 1000,
246
- { notifier: completionNotifier },
250
+ {
251
+ notifier: completionNotifier,
252
+ deliverIntercomResults: config.intercomBridge?.resultDelivery !== false,
253
+ },
247
254
  );
248
255
 
249
256
  const runtimeCleanup = () => {
@@ -6,6 +6,7 @@ import { resolveAsyncRunLocation } from "../runs/background/async-resume.ts";
6
6
  import { deliverStopRequest } from "../runs/background/control-channel.ts";
7
7
  import { reconcileAsyncRun } from "../runs/background/stale-run-reconciler.ts";
8
8
  import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
9
+ import { resolveCurrentSessionId } from "../shared/session-identity.ts";
9
10
  import {
10
11
  type Details,
11
12
  ASYNC_DIR,
@@ -23,7 +24,7 @@ export const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
23
24
  export const SUBAGENT_RPC_READY_EVENT = "subagents:rpc:v1:ready";
24
25
  export const SUBAGENT_RPC_REPLY_EVENT_PREFIX = "subagents:rpc:v1:reply:";
25
26
 
26
- export const SUBAGENT_RPC_METHODS = ["ping", "status", "spawn", "steer", "interrupt", "stop"] as const;
27
+ export const SUBAGENT_RPC_METHODS = ["ping", "status", "spawn", "steer", "interrupt", "stop", "resume"] as const;
27
28
  export type SubagentRpcMethod = typeof SUBAGENT_RPC_METHODS[number];
28
29
 
29
30
  export interface SubagentRpcRequestEnvelope {
@@ -183,6 +184,7 @@ function pingData(ctx: ExtensionContext | null) {
183
184
  nonRecoveringSteer: true,
184
185
  interrupt: true,
185
186
  stop: true,
187
+ resume: true,
186
188
  processTerminalProof: { version: 1, lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION },
187
189
  },
188
190
  events: {
@@ -238,6 +240,24 @@ function steerParams(params: unknown): SubagentParamsLike {
238
240
  };
239
241
  }
240
242
 
243
+ function resumeParams(params: unknown): SubagentParamsLike {
244
+ const input = assertRecordParams(params, "resume");
245
+ if (typeof input.message !== "string" || !input.message.trim())
246
+ throw new SubagentRpcError("invalid_params", "RPC resume requires a non-empty message.");
247
+ const target = normalizeTargetParams(input, "resume");
248
+ if (!target.id && !target.runId && !target.dir) throw new SubagentRpcError("invalid_params", "RPC resume requires id, runId, or dir.");
249
+ if (input.output !== undefined && (typeof input.output !== "string" || !input.output.trim()))
250
+ throw new SubagentRpcError("invalid_params", "RPC resume output must be a non-empty path.");
251
+ if (input.outputMode !== undefined && input.outputMode !== "file-only")
252
+ throw new SubagentRpcError("invalid_params", "RPC resume supports only file-only output mode.");
253
+ return {
254
+ action: "resume",
255
+ ...target,
256
+ message: input.message.trim(),
257
+ ...(typeof input.output === "string" ? { output: input.output.trim(), outputMode: "file-only" } : {}),
258
+ };
259
+ }
260
+
241
261
  function stopAsyncRun(
242
262
  params: unknown,
243
263
  options: RegisterSubagentRpcBridgeOptions,
@@ -257,7 +277,7 @@ function stopAsyncRun(
257
277
  throw new SubagentRpcError("not_found", "Async run not found or already completed; stop requires a live async run directory.");
258
278
  }
259
279
 
260
- const currentSessionId = ctx.sessionManager.getSessionId();
280
+ const currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
261
281
  const initialStatus = readStatus(location.asyncDir);
262
282
  const initialRunId = initialStatus?.runId ?? location.resolvedId ?? path.basename(location.asyncDir);
263
283
  if (!initialStatus) throw new SubagentRpcError("not_found", `Status file not found for async run '${initialRunId}'.`);
@@ -324,6 +344,9 @@ async function handleRequest(
324
344
  if (request.method === "stop") {
325
345
  return stopAsyncRun(request.params, options, ctx);
326
346
  }
347
+ if (request.method === "resume") {
348
+ return executeChecked(options, ctx, request.requestId, request.method, resumeParams(request.params));
349
+ }
327
350
  throw new SubagentRpcError("unsupported_method", `Unsupported subagent RPC method: ${String(request.method)}`);
328
351
  }
329
352
 
@@ -290,8 +290,8 @@ const SubagentParamsSchema = Type.Object({
290
290
  })),
291
291
  chainDir: Type.Optional(Type.String({ description: "Persistent chain artifact directory; defaults to user-scoped temp storage." })),
292
292
  async: Type.Optional(Type.Boolean({ description: "Run in background (default: false, or per config)" })),
293
- timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Optional run-level timeout in ms for foreground and async/background runs. Alias of maxRuntimeMs." })),
294
- maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias of timeoutMs for optional run-level timeout in foreground and async/background runs." })),
293
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Timeout for foreground and async/background runs; foreground defaults to 30m absent call/agent. Alias maxRuntimeMs." })),
294
+ maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias timeoutMs for foreground and async/background runs; foreground defaults to 30m absent call/agent." })),
295
295
  turnBudget: Type.Optional(TurnBudgetOverride),
296
296
  toolBudget: Type.Optional(ToolBudgetOverride),
297
297
  agentScope: Type.Optional(Type.String({ description: "Agent discovery scope: 'user', 'project', or 'both' (default: 'both'; project wins on name collisions)" })),
@@ -23,7 +23,7 @@ EXECUTION (use exactly ONE mode):
23
23
  • PARALLEL: { tasks: [{agent,task,count?,output?,reads?,progress?}, ...], concurrency?: number, worktree?: true } - concurrent execution (worktree: isolate each task in a git worktree)
24
24
  • Optional context: { context: "fresh" | "fork" } (explicit value overrides every child; when omitted, each requested agent uses its own defaultContext, otherwise "fresh"; inspect agent defaults via { action: "list" })
25
25
  • Fork thinking: model strings accept a thinking suffix (provider/model:off|minimal|low|medium|high|xhigh|max). Forking over a parent transcript that carries signed Anthropic thinking blocks forces thinking off only when a child's effective primary or fallback model resolves to the Anthropic provider or anthropic-messages API; unresolved models are treated conservatively. The result notes affected children, including on failures. Use fresh context when an Anthropic child needs thinking.
26
- • Optional timeout: { timeoutMs } or { maxRuntimeMs } sets a run-level max runtime for foreground and async/background runs
26
+ • Optional timeout: { timeoutMs } or { maxRuntimeMs } sets a run-level max runtime for foreground and async/background runs; foreground defaults to 30 minutes only when neither value nor an agent timeout is provided
27
27
  • Acceptance: omit acceptance for reviewer/read-only calls. Evidence levels end at verified. Use acceptance.review.required to require independent review of a writer result. Never request acceptance:"reviewed"; reviewed is achieved only after an independent reviewer result.
28
28
  • If { action: "list" } shows proactive skill subagent suggestions, consider a small fresh-context fanout for broad tasks where one of those skills would materially help
29
29
 
@@ -80,7 +80,7 @@ export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `To delegate work, call with {
80
80
  EXECUTE:
81
81
  • Before execution, call { action: "list" }; run only executable/non-disabled configured agents/chains.
82
82
  • SINGLE {agent, task?}; PARALLEL {tasks:[{agent,task,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{agent,task?},{parallel:[...]}]}.
83
- • context can be "fresh" or "fork"; omitted uses each agent defaultContext, otherwise fresh. timeoutMs/maxRuntimeMs apply to foreground and async/background runs.
83
+ • context can be "fresh" or "fork"; omitted uses each agent defaultContext, otherwise fresh. timeoutMs/maxRuntimeMs apply to foreground and async/background runs; foreground defaults to 30 minutes only when neither value nor an agent timeout is provided.
84
84
  • Omit acceptance for reviewer/read-only calls. Evidence levels end at verified; use acceptance.review.required for independent writer review. reviewed is an achieved status, never an explicit input.
85
85
  • Chain templates may use {task}, {previous}, {chain_dir}, and named outputs. Parallel worktree isolation requires a clean git repo.
86
86
  • Chain example: { chain: [{agent:"agent-a", task:"Analyze {task}"}, {parallel: [{agent:"agent-b", task:"Check {previous}", count: 3}]}] }
@@ -32,6 +32,7 @@ Do not use contact_supervisor or intercom for routine completion handoffs. If no
32
32
  export interface IntercomBridgeState {
33
33
  active: boolean;
34
34
  mode: IntercomBridgeMode;
35
+ resultDelivery: boolean;
35
36
  orchestratorTarget?: string;
36
37
  extensionDir: string;
37
38
  instruction: string;
@@ -78,11 +79,12 @@ export function resolveIntercomBridgeMode(value: unknown): IntercomBridgeMode {
78
79
 
79
80
  function resolveIntercomBridgeConfig(value: ExtensionConfig["intercomBridge"]): Required<IntercomBridgeConfig> {
80
81
  if (!value || typeof value !== "object" || Array.isArray(value)) {
81
- return { mode: "always", instructionFile: "" };
82
+ return { mode: "always", instructionFile: "", resultDelivery: true };
82
83
  }
83
84
  return {
84
85
  mode: resolveIntercomBridgeMode(value.mode),
85
86
  instructionFile: typeof value.instructionFile === "string" ? value.instructionFile : "",
87
+ resultDelivery: value.resultDelivery !== false,
86
88
  };
87
89
  }
88
90
 
@@ -146,11 +148,12 @@ export function resolveIntercomBridge(input: ResolveIntercomBridgeInput): Interc
146
148
  );
147
149
  const reason = inactiveReason(mode, input.context, orchestratorTarget);
148
150
  if (reason || !orchestratorTarget) {
149
- return { active: false, mode, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction };
151
+ return { active: false, mode, resultDelivery: config.resultDelivery, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction };
150
152
  }
151
153
  return {
152
154
  active: true,
153
155
  mode,
156
+ resultDelivery: config.resultDelivery,
154
157
  orchestratorTarget,
155
158
  extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
156
159
  instruction: buildIntercomBridgeInstruction(orchestratorTarget, resolveInstructionTemplate(config.instructionFile, settingsDir)),
@@ -60,6 +60,19 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
60
60
  renderWidget(ctx, options.widgetEnabled === false ? [] : jobs);
61
61
  ctx.ui.requestRender?.();
62
62
  };
63
+ const rerenderLastWidget = (jobs = Array.from(state.asyncJobs.values())) => {
64
+ const ctx = state.lastUiContext;
65
+ if (!ctx) return;
66
+ try {
67
+ if (ctx.hasUI) rerenderWidget(ctx, jobs);
68
+ } catch (error) {
69
+ if (error instanceof Error && error.message.includes("extension ctx is stale")) {
70
+ state.lastUiContext = null;
71
+ return;
72
+ }
73
+ throw error;
74
+ }
75
+ };
63
76
  const refreshWidget = (ctx: ExtensionContext) => rerenderWidget(ctx);
64
77
  const restoredControlEventCursor = (asyncDir: string) => {
65
78
  try {
@@ -131,9 +144,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
131
144
  const timer = setTimeout(() => {
132
145
  state.cleanupTimers.delete(asyncId);
133
146
  state.asyncJobs.delete(asyncId);
134
- if (state.lastUiContext) {
135
- rerenderWidget(state.lastUiContext);
136
- }
147
+ rerenderLastWidget();
137
148
  }, completionRetentionMs);
138
149
  state.cleanupTimers.set(asyncId, timer);
139
150
  };
@@ -254,7 +265,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
254
265
  if (state.poller) return;
255
266
  state.poller = setInterval(() => {
256
267
  if (state.asyncJobs.size === 0) {
257
- if (state.lastUiContext?.hasUI) rerenderWidget(state.lastUiContext, []);
268
+ rerenderLastWidget([]);
258
269
  if (state.poller) {
259
270
  clearInterval(state.poller);
260
271
  state.poller = null;
@@ -378,7 +389,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
378
389
  if (widgetRenderKey(job) !== widgetStateBefore) widgetChanged = true;
379
390
  }
380
391
 
381
- if (widgetChanged && state.lastUiContext?.hasUI) rerenderWidget(state.lastUiContext);
392
+ if (widgetChanged) rerenderLastWidget();
382
393
  }, pollIntervalMs);
383
394
  state.poller.unref?.();
384
395
  };
@@ -421,9 +432,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
421
432
  });
422
433
  rememberFleetJob(state, state.asyncJobs.get(info.id)!);
423
434
  ensurePoller();
424
- if (state.lastUiContext) {
425
- rerenderWidget(state.lastUiContext);
426
- }
435
+ rerenderLastWidget();
427
436
  };
428
437
 
429
438
  const handleComplete = (data: unknown) => {
@@ -446,9 +455,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
446
455
  }
447
456
  }
448
457
  if (job) rememberFleetJob(state, job);
449
- if (state.lastUiContext) {
450
- rerenderWidget(state.lastUiContext);
451
- }
458
+ rerenderLastWidget();
452
459
  if (!nestedRefreshFailed && !hasLiveNestedDescendants(job?.nestedChildren)) scheduleCleanup(asyncId);
453
460
  };
454
461
 
@@ -485,7 +492,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
485
492
  }
486
493
  if (runs.length === 0) return;
487
494
  ensurePoller();
488
- if (state.lastUiContext?.hasUI) rerenderWidget(state.lastUiContext);
495
+ rerenderLastWidget();
489
496
  };
490
497
 
491
498
  return { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs };