@xzzpig/pi-subagents 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/fork-supervisor-routing.md +77 -0
  13. package/docs/missions.md +34 -17
  14. package/docs/models.md +1 -1
  15. package/docs/observability.md +10 -5
  16. package/docs/tool-reference.md +117 -84
  17. package/docs/watchdog.md +8 -6
  18. package/docs/workflows.md +16 -7
  19. package/index.ts +5 -0
  20. package/package.json +6 -3
  21. package/prompts/council.md +1 -1
  22. package/skills/pi-subagents/SKILL.md +1 -1
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  24. package/skills/pi-subagents/references/execution-controls.md +16 -16
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  26. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  27. package/src/agents/advertised-agent-prompt.ts +9 -1
  28. package/src/agents/agent-management.ts +4 -0
  29. package/src/agents/agent-memory.ts +3 -3
  30. package/src/agents/agent-scope.ts +4 -0
  31. package/src/agents/agent-serializer.ts +8 -1
  32. package/src/agents/agents.ts +191 -145
  33. package/src/api/preflight.ts +8 -4
  34. package/src/api/supervisor-routing.ts +196 -0
  35. package/src/extension/config.ts +21 -2
  36. package/src/extension/context-injection.ts +6 -1
  37. package/src/extension/control-notices.ts +1 -9
  38. package/src/extension/declaration-pinning.ts +164 -0
  39. package/src/extension/doctor.ts +7 -10
  40. package/src/extension/fanout-child.ts +7 -8
  41. package/src/extension/index.ts +143 -134
  42. package/src/extension/reply-workflow-script.ts +20 -11
  43. package/src/extension/rpc.ts +11 -6
  44. package/src/extension/schemas.ts +34 -30
  45. package/src/extension/subagent-guide.ts +86 -6
  46. package/src/extension/subagent-options.ts +47 -0
  47. package/src/extension/tool-activation.ts +3 -2
  48. package/src/extension/tool-description.ts +51 -68
  49. package/src/inspectors/actions.ts +37 -11
  50. package/src/inspectors/plugins.ts +3 -2
  51. package/src/inspectors/tmux/actions.ts +204 -0
  52. package/src/inspectors/tmux/client.ts +85 -0
  53. package/src/inspectors/tmux/plugin.ts +21 -0
  54. package/src/integrations/herdr-status.ts +18 -49
  55. package/src/integrations/program-status.ts +215 -0
  56. package/src/intercom/fork-supervisor-routing.ts +533 -0
  57. package/src/intercom/native-supervisor-channel.ts +152 -13
  58. package/src/intercom/result-intercom.ts +3 -2
  59. package/src/intercom/supervisor-ui.ts +2 -174
  60. package/src/missions/store.ts +25 -5
  61. package/src/profiles/profiles.ts +24 -21
  62. package/src/runs/background/active-async-capacity.ts +58 -8
  63. package/src/runs/background/async-execution.ts +143 -38
  64. package/src/runs/background/async-job-tracker.ts +11 -4
  65. package/src/runs/background/async-resume.ts +5 -2
  66. package/src/runs/background/await-async-run.ts +14 -9
  67. package/src/runs/background/binary-bootstrap.ts +2 -1
  68. package/src/runs/background/calendar-schedule.ts +90 -0
  69. package/src/runs/background/chain-root-attachment.ts +9 -5
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +16 -2
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-child-launch.ts +1 -0
  79. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  80. package/src/runs/background/scheduled-runs.ts +256 -61
  81. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  82. package/src/runs/background/subagent-runner.ts +32 -12
  83. package/src/runs/background/subagent-wait.ts +38 -19
  84. package/src/runs/background/terminal-run-index.ts +46 -1
  85. package/src/runs/background/wait-completions.ts +1 -0
  86. package/src/runs/background/wait-tool.ts +33 -23
  87. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  88. package/src/runs/foreground/async-stop-action.ts +48 -22
  89. package/src/runs/foreground/execution.ts +94 -52
  90. package/src/runs/foreground/foreground-history.ts +1 -0
  91. package/src/runs/foreground/subagent-executor.ts +232 -77
  92. package/src/runs/shared/child-commands.ts +2 -1
  93. package/src/runs/shared/child-hooks.ts +4 -3
  94. package/src/runs/shared/child-launch.ts +3 -0
  95. package/src/runs/shared/child-session.ts +41 -24
  96. package/src/runs/shared/child-tool-plan.ts +13 -26
  97. package/src/runs/shared/dynamic-fanout.ts +1 -1
  98. package/src/runs/shared/fork-command-result.ts +10 -0
  99. package/src/runs/shared/herdr-placed-run.ts +5 -4
  100. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  101. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  102. package/src/runs/shared/model-resolution.ts +30 -1
  103. package/src/runs/shared/nested-events.ts +5 -0
  104. package/src/runs/shared/parallel-handoff.ts +56 -8
  105. package/src/runs/shared/parallel-utils.ts +2 -0
  106. package/src/runs/shared/partial-output.ts +48 -0
  107. package/src/runs/shared/runner-launcher.ts +25 -0
  108. package/src/runs/shared/single-output.ts +53 -0
  109. package/src/runs/shared/structured-output.ts +14 -7
  110. package/src/runs/shared/subagent-control.ts +3 -3
  111. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  112. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  113. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  114. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  115. package/src/runs/shared/worktree-lock.ts +29 -0
  116. package/src/runs/shared/worktree.ts +12 -1
  117. package/src/shared/atomic-json.ts +4 -2
  118. package/src/shared/edit-distance.ts +33 -0
  119. package/src/shared/file-lease.ts +74 -0
  120. package/src/shared/formatters.ts +1 -5
  121. package/src/shared/model-info.ts +22 -0
  122. package/src/shared/package-version.ts +17 -0
  123. package/src/shared/parent-wake.ts +79 -0
  124. package/src/shared/pruned-fork.ts +7 -1
  125. package/src/shared/runtime-module-path.ts +19 -0
  126. package/src/shared/settings-file-lease.ts +36 -0
  127. package/src/shared/types.ts +36 -2
  128. package/src/shared/utils.ts +8 -6
  129. package/src/slash/prompt-template-bridge.ts +21 -20
  130. package/src/slash/slash-commands.ts +3 -3
  131. package/src/slash/subagents-admin.ts +2 -1
  132. package/src/tui/fleet-native-transcript.ts +2 -0
  133. package/src/tui/fleet-transcript.ts +12 -3
  134. package/src/tui/fleet.ts +11 -8
  135. package/src/tui/render.ts +27 -19
  136. package/src/tui/subagent-messages.ts +305 -0
  137. package/src/watchdog/diff-tool.ts +2 -2
  138. package/src/watchdog/register-main.ts +2 -22
  139. package/src/watchdog/render.ts +2 -24
  140. package/src/watchdog/runtime.ts +6 -4
  141. package/src/watchdog/settings.ts +18 -13
  142. package/src/watchdog/tool-actions.ts +2 -2
  143. package/src/workflows/scripted-workflow.ts +20 -6
  144. package/src/workflows/workflow-resources.ts +11 -0
@@ -2,8 +2,10 @@ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
 
4
4
  const WORKFLOW_FENCE = /^```(?:js|javascript) workflow[ \t]*$/;
5
+ const PLAIN_JS_FENCE = /^```(?:js|javascript)[ \t]*$/;
5
6
  const OPEN_FENCE = /^(`{3,}|~{3,})/;
6
7
  const CLOSE_FENCE = /^(`{3,}|~{3,})[ \t]*$/;
8
+ const FILE_FALLBACK = "Or write the script to a file and pass its path, such as workflow: \"./script.js\".";
7
9
 
8
10
  export type ReplyWorkflowScript = { script: string } | { error: string };
9
11
 
@@ -28,31 +30,38 @@ function scriptFromReply(content: AssistantMessage["content"]): ReplyWorkflowScr
28
30
  const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent"
29
31
  && (block.arguments?.workflow === true || block.arguments?.workflow === "true")).length;
30
32
  if (replyCalls > 1) return { error: `This reply has ${replyCalls} subagent calls with workflow: true; a reply can carry only one. Pass other scripts as workflow file paths.` };
33
+ if (!content.some((block) => block.type === "text")) return { error: "The assistant message that issued this call has no text in the session, so the reply's visible text, including any ```js workflow block, never reached it. Write the script to a file and pass its path, such as workflow: \"./script.js\"." };
31
34
  const text = content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
32
- const { blocks, unclosed } = workflowBlocks(text);
33
- if (unclosed) return { error: "The ```js workflow block in this reply is not closed." };
34
- if (blocks.length !== 1) return { error: `workflow: true requires exactly one \`\`\`js workflow fenced block in the same reply as the tool call; found ${blocks.length}.` };
35
+ const { tagged, plain, unclosed } = workflowBlocks(text);
36
+ if (unclosed) return { error: "The script's fenced block in this reply is not closed." };
37
+ // Models often drop the workflow tag, so a lone plain js block is unambiguous enough to run.
38
+ const blocks = tagged.length > 0 ? tagged : plain.length === 1 ? plain : [];
39
+ if (blocks.length !== 1) {
40
+ const untagged = tagged.length === 0 && plain.length > 1 ? ` This reply has ${plain.length} untagged js blocks; open the script's block with the line "\`\`\`js workflow".` : "";
41
+ return { error: `workflow: true needs one fenced block in the same reply as the tool call, opened with the exact line "\`\`\`js workflow" and closed with "\`\`\`"; found ${tagged.length}.${untagged} ${FILE_FALLBACK}` };
42
+ }
35
43
  const script = blocks[0]!;
36
- if (!script.trim()) return { error: "The ```js workflow block in this reply is empty." };
44
+ if (!script.trim()) return { error: "The script's fenced block in this reply is empty." };
37
45
  return { script };
38
46
  }
39
47
 
40
- /** Collects ```js workflow / ```javascript workflow fenced blocks, skipping the bodies of other fences. */
41
- function workflowBlocks(text: string): { blocks: string[]; unclosed: boolean } {
48
+ /** Collects tagged (```js workflow) and plain (```js) fenced blocks, skipping the bodies of other fences. */
49
+ function workflowBlocks(text: string): { tagged: string[]; plain: string[]; unclosed: boolean } {
42
50
  const lines = text.split("\n");
43
- const blocks: string[] = [];
44
- let fence: { marker: string; tagged: boolean; start: number } | undefined;
51
+ const tagged: string[] = [];
52
+ const plain: string[] = [];
53
+ let fence: { marker: string; kind: "tagged" | "plain" | undefined; start: number } | undefined;
45
54
  for (let index = 0; index < lines.length; index++) {
46
55
  const line = lines[index]!.replace(/\r$/, "");
47
56
  if (!fence) {
48
57
  const open = OPEN_FENCE.exec(line);
49
- if (open) fence = { marker: open[1]!, tagged: WORKFLOW_FENCE.test(line), start: index + 1 };
58
+ if (open) fence = { marker: open[1]!, kind: WORKFLOW_FENCE.test(line) ? "tagged" : PLAIN_JS_FENCE.test(line) ? "plain" : undefined, start: index + 1 };
50
59
  continue;
51
60
  }
52
61
  const close = CLOSE_FENCE.exec(line);
53
62
  if (!close || close[1]![0] !== fence.marker[0] || close[1]!.length < fence.marker.length) continue;
54
- if (fence.tagged) blocks.push(lines.slice(fence.start, index).join("\n"));
63
+ if (fence.kind) (fence.kind === "tagged" ? tagged : plain).push(lines.slice(fence.start, index).join("\n"));
55
64
  fence = undefined;
56
65
  }
57
- return { blocks, unclosed: fence?.tagged === true };
66
+ return { tagged, plain, unclosed: fence?.kind === "tagged" || (fence?.kind === "plain" && tagged.length === 0) };
58
67
  }
@@ -3,7 +3,7 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import { Compile } from "typebox/compile";
5
5
  import { resolveAsyncRunLocation } from "../runs/background/async-resume.ts";
6
- import { deliverStopRequest } from "../runs/background/control-channel.ts";
6
+ import { deliverAsyncRunStop } from "../runs/foreground/async-stop-action.ts";
7
7
  import { reconcileAsyncRun } from "../runs/background/stale-run-reconciler.ts";
8
8
  import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
9
9
  import { resolveCurrentSessionId } from "../shared/session-identity.ts";
@@ -21,7 +21,7 @@ import {
21
21
  } from "../shared/types.ts";
22
22
  import { sanitizeDisplayText, truncateDisplayText } from "../shared/display-text.ts";
23
23
  import { readStatus } from "../shared/utils.ts";
24
- import { SubagentParams } from "./schemas.ts";
24
+ import { SubagentFlatParams } from "./schemas.ts";
25
25
  import { disabledFeatureUseError, type DisabledFeatureSurface } from "../shared/disabled-features.ts";
26
26
  import { normalizePublicSubagentExecution } from "./public-execution.ts";
27
27
  import { collectSubagentCost, SUBAGENT_COST_REPORT_VERSION } from "../slash/subagent-cost.ts";
@@ -336,7 +336,7 @@ class SubagentRpcError extends Error {
336
336
  }
337
337
  }
338
338
 
339
- const subagentParamsValidator = Compile(SubagentParams);
339
+ const subagentParamsValidator = Compile(SubagentFlatParams);
340
340
 
341
341
  export function subagentRpcReplyEvent(requestId: string): string {
342
342
  return `${SUBAGENT_RPC_REPLY_EVENT_PREFIX}${requestId}`;
@@ -685,8 +685,9 @@ function stopAsyncRun(
685
685
  if (status.sessionId !== currentSessionId) {
686
686
  throw new SubagentRpcError("not_found", `Async run '${runId}' was not found in the active session.`);
687
687
  }
688
- if (status.state !== "running") {
689
- throw new SubagentRpcError("invalid_state", `Async run ${runId} is ${status.state}; stop only supports running async runs.`);
688
+ const pausedWholeRun = status.state === "paused" && childId === undefined;
689
+ if (status.state !== "running" && status.state !== "queued" && !pausedWholeRun) {
690
+ throw new SubagentRpcError("invalid_state", `Async run ${runId} is ${status.state}; stop only supports running or queued async runs, or a paused whole run.`);
690
691
  }
691
692
  if (childId !== undefined) {
692
693
  const resolution = resolveAsyncStatusChild(status, childId);
@@ -698,19 +699,23 @@ function stopAsyncRun(
698
699
  }
699
700
 
700
701
  try {
701
- deliverStopRequest({
702
+ const failure = deliverAsyncRunStop({
702
703
  asyncDir: location.asyncDir,
704
+ status,
705
+ resultsDir,
703
706
  pid: status.pid,
704
707
  kill: options.kill,
705
708
  now: options.now,
706
709
  source: "rpc-stop",
707
710
  ...(child ? { targetIndex: child.index, childId: child.id } : {}),
708
711
  });
712
+ if (failure) throw new Error(`Stop request persisted for paused async run ${runId}, but terminal proof is not ready (${failure}). Retry stop after runner shutdown is observed.`);
709
713
  } catch (error) {
710
714
  throw new SubagentRpcError("execution_failed", error instanceof Error ? error.message : String(error));
711
715
  }
712
716
  if (child) emitChildStopping(runId, location.asyncDir, child);
713
717
 
718
+ // This is an acceptance receipt, not terminal proof, even when a proven paused run was sealed.
714
719
  return {
715
720
  runId,
716
721
  asyncDir: location.asyncDir,
@@ -64,7 +64,6 @@ const AcceptanceOverride = Type.Unsafe({
64
64
  {
65
65
  type: "string",
66
66
  enum: ["reviewed"],
67
- deprecated: true,
68
67
  description: "Invalid as an explicit policy. Recognized only so preflight can explain that reviewed is an achieved status.",
69
68
  },
70
69
  {
@@ -160,7 +159,7 @@ const SubagentParamProperties = {
160
159
  extensionBindings: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Child-only plain JSON; package.name/1; depth 16, 256 props, 16 KiB." })),
161
160
  // Management action (when present, tool operates in management mode)
162
161
  action: Type.Optional(Type.String({ minLength: 1,
163
- description: "Management/control only; omit for execution. validate accepts workflow: true or a script path. Discover actions with guide topic tool-reference."
162
+ description: "Management/control only; omit for execution. validate accepts workflow: true or a script path. Discover actions with {action:\"guide\",options:{topic:\"tool-reference\"}}."
164
163
  })),
165
164
  capabilities: Type.Optional(Type.Boolean({ description: "list: compact capability rows/details without system prompts." })),
166
165
  name: Type.Optional(Type.String({ description: "schedule.create name." })),
@@ -174,8 +173,8 @@ const SubagentParamProperties = {
174
173
  description: "Async directory for status/control."
175
174
  })),
176
175
  handoffPath: Type.Optional(Type.String({ description: "Existing manifest for worktree/lane actions." })),
177
- repo: Type.Optional(Type.String({ description: "worktree.cleanup repo; default cwd." })),
178
- planId: Type.Optional(Type.String({ description: "Reserved; cleanup is plan-only." })),
176
+ repo: Type.Optional(Type.String({ description: "Cleanup repo; apply requires it." })),
177
+ planId: Type.Optional(Type.String({ description: "Reviewed cleanup plan for apply." })),
179
178
  laneId: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Exact manifest run id for lane actions." })),
180
179
  merge: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordMerge evidence; read guide tool-reference." })),
181
180
  supersession: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordSupersession evidence; read guide tool-reference." })),
@@ -189,21 +188,21 @@ const SubagentParamProperties = {
189
188
  lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "Transcript tail lines; default 80." })),
190
189
  topic: Type.Optional(Type.String()),
191
190
  message: Type.Optional(Type.String({ description: "resume/steer guidance or project.open prompt." })),
192
- mode: Type.Optional(Type.String({ enum: ["steer", "follow_up", "auto", "plan", "apply"], description: "steer delivery mode; worktree.cleanup supports plan only, no apply/removal." })),
191
+ mode: Type.Optional(Type.String({ enum: ["steer", "follow_up", "auto", "plan", "apply"], description: "steer delivery; worktree.cleanup plan/apply (reviewed planId)." })),
193
192
  steeringRecovery: Type.Optional(Type.Boolean({ description: "steer: pause/revive after missed acknowledgment; default true in direct steer mode, forced false by extension RPC for exact ownership." })),
194
193
  additional: Type.Optional(Type.Integer({ minimum: 1, description: "grant-spawn-budget: root interactive parent + native user confirmation only; total grants capped at original configured cap." })),
195
194
  scope: Type.Optional(Type.String({ enum: ["session", "user", "project"], description: "watchdog.configure scope; default session, persistent only if explicit." })),
196
195
  target: Type.Optional(Type.String({ enum: ["main", "children", "child"], description: "Watchdog target." })),
197
196
  focus: Type.Optional(Type.Boolean({ description: "Focus inspector.open/project.open pane." })),
198
197
  thinking: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "boolean" }], description: "watchdog.configure only: off/minimal/low/medium/high/xhigh/max, inherit, false=off; true invalid. Dispatch ignores this; use model suffix." })),
199
- at: Type.Optional(Type.String({ description: "schedule.create: delay (+10m) or zoned ISO timestamp." })),
200
- every: Type.Optional(Type.String({ description: "schedule.create interval, e.g. 30m/6h/2d/2w." })),
198
+ at: Type.Optional(Type.String({ description: "Delay/ISO or local HH:mm." })),
199
+ every: Type.Optional(Type.String({ description: "Duration or day/week." })),
201
200
  sessionOnly: Type.Optional(Type.Boolean()),
202
201
  quiet: Type.Optional(Type.Boolean()),
203
- on: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "integer" }], description: "Reserved calendar selector." })),
204
- timezone: Type.Optional(Type.String()),
202
+ on: Type.Optional(Type.Array(Type.String({ enum: ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] }), { minItems: 1, description: "Weekly." })),
203
+ timezone: Type.Optional(Type.String({ description: "IANA/UTC." })),
205
204
  overlap: Type.Optional(Type.String({ enum: ["skip"] })),
206
- catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed schedule occurrences; default latest." })),
205
+ catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed; default latest." })),
207
206
  missionId: Type.Optional(Type.String({ description: "Existing mission to attach to a workflow or schedule.create; read guide missions for lifecycle and retention." })),
208
207
  mission: Type.Optional(Type.Unsafe({ ...MissionLaunchOverride, description: "false disables; true invalid. Object: exactly one non-empty title or summary; objective/labels optional; goal only true, requires budget.tokens." })),
209
208
  missionUpdate: Type.Optional(Type.Unsafe({ ...MissionUpdateOverride, description: "Mission patch; read guide missions." })),
@@ -263,6 +262,7 @@ const SubagentParamProperties = {
263
262
  description: "Child output path or false; relative workflow paths use managed artifact routing. Bind durable output here, not task prose; return outputReference/outputPathMapping/artifactPaths.",
264
263
  })),
265
264
  outputMode: Type.Optional(OutputModeOverride),
265
+ maxOutput: Type.Optional(Type.Object({ bytes: Type.Optional(Type.Integer({ minimum: 1 })), lines: Type.Optional(Type.Integer({ minimum: 1 })) }, { additionalProperties: false })),
266
266
  skill: Type.Optional(SkillOverride),
267
267
  model: Type.Optional(Type.String({ description: "Child model provider/id; bare id only if unique. Suffix :off/minimal/low/medium/high/xhigh/max overrides agent thinking default." })),
268
268
  fast: Type.Optional(Type.Boolean({ description: "Native OpenAI-Codex priority tier; default false, may cost more/quota." })),
@@ -278,15 +278,30 @@ const SubagentParamProperties = {
278
278
  })),
279
279
  };
280
280
 
281
- const SubagentParamsSchema = Type.Object(SubagentParamProperties);
281
+ /** Full flat parameter shape accepted by RPC, slash, scheduled and workflow callers. */
282
+ export const SubagentFlatParams = Type.Object(SubagentParamProperties);
282
283
 
283
- export const SubagentParams = keepTopLevelParameterDescriptions(SubagentParamsSchema);
284
+ // Management/control fields go inside one opaque `options` object, so they are not sent on every request.
285
+ const { runId: _runId, maxRuntimeMs: _maxRuntimeMs, isolation: _isolation, ...ModelProperties } = SubagentParamProperties;
286
+ const { agent, task, workflow, args, async, model, cwd, worktree, output, action, id, message, ...SubagentOptionProperties } = ModelProperties;
287
+
288
+ export const SUBAGENT_OPTION_KEYS: readonly string[] = Object.keys(SubagentOptionProperties);
289
+
290
+ /** Values the model passes in `options`, checked with the same property schemas as flat callers. */
291
+ export const SubagentOptionParams = Type.Object(SubagentOptionProperties, { additionalProperties: false });
292
+
293
+ const ModelTopLevelProperties = {
294
+ agent, task, workflow, args, async, model, cwd, worktree, output, action, id, message,
295
+ options: Type.Optional(Type.Unsafe<Record<string, unknown>>({ type: "object", additionalProperties: true, description: "Every field not listed here, such as acceptance, timeoutMs, context, view and index; guide tool-reference/parameter-reference." })),
296
+ };
297
+
298
+ export const SubagentParams = keepTopLevelParameterDescriptions(Type.Object(ModelTopLevelProperties));
284
299
 
285
300
  // Replaces workflow scripts when disabledFeatures lists "workflow-scripts". Kept small because every
286
301
  // field is sent on every request; the executor validates step shapes and placeholders strictly.
287
302
  const StructuredTask = { type: "object", properties: { agent: { type: "string", minLength: 1 }, task: { type: "string" } }, required: ["agent", "task"], additionalProperties: false };
288
303
  const StructuredWorkflowProperties = {
289
- action: Type.Optional(Type.String({ minLength: 1, description: "Management/control only; omit for execution. Discover actions with guide topic tool-reference." })),
304
+ action: Type.Optional(Type.String({ minLength: 1, description: "Management/control only; omit for execution. Discover actions with {action:\"guide\",options:{topic:\"tool-reference\"}}." })),
290
305
  task: Type.Optional(Type.String({ description: "One-child task with agent, or the original request ({task}) with chain/tasks." })),
291
306
  tasks: Type.Optional(Type.Unsafe({ type: "array", minItems: 1, items: StructuredTask, description: "Parallel children; results in order." })),
292
307
  // Flattened step: {agent, task?, as?} or {parallel}; no object-shape union for provider converters.
@@ -301,7 +316,7 @@ const StructuredWorkflowProperties = {
301
316
  export function createSubagentParamsSchema(disabled?: DisabledFeatureSurface): typeof SubagentParams {
302
317
  if (!disabled || disabled.params.size === 0) return SubagentParams;
303
318
  const structured = disabled.features.has("workflow-scripts");
304
- const enabledProperties = Object.fromEntries(Object.entries(SubagentParamProperties).flatMap(([name, schema]) => {
319
+ const enabledProperties = Object.fromEntries(Object.entries(ModelTopLevelProperties).flatMap(([name, schema]) => {
305
320
  if (disabled.params.has(name)) return [];
306
321
  if (structured && name === "action") return [[name, StructuredWorkflowProperties.action]];
307
322
  if (structured && name === "task") return [[name, StructuredWorkflowProperties.task], ["tasks", StructuredWorkflowProperties.tasks], ["chain", StructuredWorkflowProperties.chain]];
@@ -312,22 +327,11 @@ export function createSubagentParamsSchema(disabled?: DisabledFeatureSurface): t
312
327
  }
313
328
 
314
329
  const SubagentWaitParamsSchema = Type.Object({
315
- id: Type.Optional(Type.String({
316
- description: "Async run or remembered detached foreground run id/prefix to wait for one specific run. Ordinary async subagent runs already notify this session natively; use bg_wait for provider, detached, or other background work without native notification, or when same-turn blocking results are truly needed. Omit to wait across every active async run started in this session only when a same-turn wait is truly needed.",
317
- })),
318
- nonBlocking: Type.Optional(Type.Boolean({
319
- description: "When true, resolve id to one exact run, persist a wake subscription, and return immediately. Use this only for provider, detached, or other background work without a native completion notification; ordinary async subagent runs already notify this session natively and do not need a subscription. The originating session is woken on completion, failure, attention, reconciliation failure, or timeout. Requires id and cannot be combined with all.",
320
- })),
321
- all: Type.Optional(Type.Boolean({
322
- description: "Wait for ALL active runs to finish. Ordinary async subagent runs already notify this session natively; use all only when a same-turn result from tracked background work is truly needed. Default false: return when the first tracked run or provider item finishes or needs attention. Ignored when id targets a single run.",
323
- })),
324
- timeoutMs: Type.Optional(Type.Integer({
325
- minimum: 1,
326
- description: "Give up waiting after this many milliseconds (the runs keep going regardless). Ordinary async subagent runs already notify this session natively; use a wait timeout only when same-turn results are truly needed for provider, detached, or other background work without native notification. Defaults to config waitTool.defaultTimeoutMs, then 1800000 (30 minutes). Window expiry is a non-error active-work result.",
327
- })),
328
- stopOnAttention: Type.Optional(Type.Boolean({
329
- description: "For a blocking wait that is truly needed, stop when a run needs attention by default. Set false to keep waiting through idle or long-thinking attention; supervisor/contact requests still stop the wait.",
330
- })),
330
+ id: Type.Optional(Type.String({ description: "Run id or prefix." })),
331
+ nonBlocking: Type.Optional(Type.Boolean({ description: "Subscribe to id's wake and return immediately; requires id, not with all." })),
332
+ all: Type.Optional(Type.Boolean({ description: "Wait for all work active at call time." })),
333
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Max wait; default waitTool.defaultTimeoutMs, then 30 min." })),
334
+ stopOnAttention: Type.Optional(Type.Boolean({ description: "false: keep waiting through idle or long-thinking attention." })),
331
335
  });
332
336
 
333
337
  export const SubagentWaitParams = keepTopLevelParameterDescriptions(SubagentWaitParamsSchema);
@@ -18,6 +18,10 @@ export const SUBAGENT_GUIDE_TOPICS = [
18
18
 
19
19
  export type SubagentGuideTopic = (typeof SUBAGENT_GUIDE_TOPICS)[number];
20
20
 
21
+ // Guide output stays in the parent's history and is re-sent on every later turn, so docs-backed
22
+ // topics return a table of contents or one section, never a whole document.
23
+ const SUBAGENT_GUIDE_SECTION_MAX_CHARS = 8000;
24
+
21
25
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
22
26
 
23
27
  // /council must work under `pi --no-skills`, which drops the package skills from context,
@@ -28,20 +32,96 @@ const COUNCIL_FILES = [
28
32
  "skills/pi-subagents/references/execution-controls.md",
29
33
  ];
30
34
 
35
+ interface GuideSection {
36
+ address: string;
37
+ title: string;
38
+ level: number;
39
+ start: number;
40
+ end: number;
41
+ children: GuideSection[];
42
+ }
43
+
31
44
  function isGuideTopic(value: string): value is SubagentGuideTopic {
32
45
  return (SUBAGENT_GUIDE_TOPICS as readonly string[]).includes(value);
33
46
  }
34
47
 
35
- export function readSubagentGuide(topic = "overview", root = packageRoot): string {
36
- if (!isGuideTopic(topic)) {
37
- return `Unknown subagents guide topic '${topic}'. Valid topics: ${SUBAGENT_GUIDE_TOPICS.join(", ")}. No files were changed.`;
48
+ function headingSlug(title: string): string {
49
+ return title.toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").trim().replace(/\s/g, "-");
50
+ }
51
+
52
+ function parseSections(topic: string, lines: string[]): GuideSection[] {
53
+ const sections: GuideSection[] = [];
54
+ let fence: string | undefined;
55
+ lines.forEach((line, index) => {
56
+ const marker = /^\s*(```+|~~~+)/.exec(line)?.[1];
57
+ if (marker) {
58
+ if (!fence) fence = marker;
59
+ else if (marker.startsWith(fence)) fence = undefined;
60
+ return;
61
+ }
62
+ const heading = fence ? undefined : /^(#{2,6})\s+(.+?)\s*#*\s*$/.exec(line);
63
+ if (heading) sections.push({ address: "", title: heading[2]!, level: heading[1]!.length, start: index, end: lines.length, children: [] });
64
+ });
65
+ const used = new Set<string>();
66
+ const parents: GuideSection[] = [];
67
+ for (const [index, section] of sections.entries()) {
68
+ const next = sections.slice(index + 1).find((other) => other.level <= section.level);
69
+ if (next) section.end = next.start;
70
+ while (parents.length && parents.at(-1)!.level >= section.level) parents.pop();
71
+ const parent = parents.at(-1);
72
+ parent?.children.push(section);
73
+ let slug = headingSlug(section.title);
74
+ if (used.has(slug) && parent) slug = `${parent.address.slice(topic.length + 1)}-${slug}`;
75
+ for (let suffix = 2, base = slug; used.has(slug); suffix++) slug = `${base}-${suffix}`;
76
+ used.add(slug);
77
+ section.address = `${topic}/${slug}`;
78
+ parents.push(section);
38
79
  }
39
- const files = topic === "overview" ? ["README.md"] : topic === "council" ? COUNCIL_FILES : [path.join("docs", `${topic}.md`)];
80
+ return sections;
81
+ }
82
+
83
+ function tableOfContents(topic: string, sections: GuideSection[]): string {
84
+ const rows = sections.map((section) => `${" ".repeat(section.level - 2)}${section.address} — ${section.title}`);
85
+ return `Sections of guide topic '${topic}'. Read one with {action:"guide",options:{topic:"<section address>"}}:\n${rows.join("\n")}`;
86
+ }
87
+
88
+ function sectionText(lines: string[], section: GuideSection): string {
89
+ const text = lines.slice(section.start, section.end).join("\n").trim();
90
+ if (text.length <= SUBAGENT_GUIDE_SECTION_MAX_CHARS || !section.children.length) return text;
91
+ const intro = lines.slice(section.start, section.children[0]!.start).join("\n").trim();
92
+ return `${intro}\n\nSubsections (read one with {action:"guide",options:{topic:"<address>"}}):\n${section.children.map((child) => `${child.address} — ${child.title}`).join("\n")}`;
93
+ }
94
+
95
+ function readGuideFiles(topic: string, files: string[], root: string): string[] {
40
96
  try {
41
- const contents = files.map((file) => fs.readFileSync(path.join(root, file), "utf-8"));
42
- return files.length === 1 ? contents[0]! : contents.map((content, index) => `<!-- ${files[index]} -->\n\n${content}`).join("\n\n");
97
+ // Windows checkouts can convert docs to CRLF; sections and their boundaries are defined on LF lines.
98
+ return files.map((file) => fs.readFileSync(path.join(root, file), "utf-8").replace(/\r\n/g, "\n"));
43
99
  } catch (error) {
44
100
  const message = error instanceof Error ? error.message : String(error);
45
101
  throw new Error(`Failed to read packaged subagents guide '${topic}': ${message}`, { cause: error instanceof Error ? error : undefined });
46
102
  }
47
103
  }
104
+
105
+ /** Reads a guide topic. Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
106
+ export function readSubagentGuide(topic = "overview", root = packageRoot): string {
107
+ const separator = topic.indexOf("/");
108
+ const name = separator === -1 ? topic : topic.slice(0, separator);
109
+ const sectioned = isGuideTopic(name) && name !== "overview" && name !== "council";
110
+ if (!isGuideTopic(name) || (separator !== -1 && !sectioned)) {
111
+ return `Unknown subagents guide topic '${topic}'. Valid topics: ${SUBAGENT_GUIDE_TOPICS.join(", ")}. No files were changed.`;
112
+ }
113
+ if (!sectioned) {
114
+ const files = name === "overview" ? ["README.md"] : COUNCIL_FILES;
115
+ const contents = readGuideFiles(name, files, root);
116
+ return files.length === 1 ? contents[0]! : contents.map((content, index) => `<!-- ${files[index]} -->\n\n${content}`).join("\n\n");
117
+ }
118
+ const lines = readGuideFiles(name, [path.join("docs", `${name}.md`)], root)[0]!.split("\n");
119
+ const sections = parseSections(name, lines);
120
+ if (separator === -1) {
121
+ const intro = lines.slice(0, sections[0]?.start ?? lines.length).join("\n").trim();
122
+ return `${intro}\n\n${tableOfContents(name, sections)}`;
123
+ }
124
+ const section = sections.find((candidate) => candidate.address === topic);
125
+ if (!section) return `Unknown section '${topic}'. No files were changed.\n\n${tableOfContents(name, sections)}`;
126
+ return sectionText(lines, section);
127
+ }
@@ -0,0 +1,47 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { Compile } from "typebox/compile";
3
+ import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
4
+ import type { DisabledFeatureSurface } from "../shared/disabled-features.ts";
5
+ import { closestMatch } from "../shared/edit-distance.ts";
6
+ import { removedModelWorkflowFieldError } from "./public-execution.ts";
7
+ import { SUBAGENT_OPTION_KEYS, SubagentOptionParams, createSubagentParamsSchema } from "./schemas.ts";
8
+
9
+ const optionKeys = new Set(SUBAGENT_OPTION_KEYS);
10
+ const ALIAS_HINTS: Record<string, string> = { runId: "id (top-level)", maxRuntimeMs: "options.timeoutMs", isolation: "worktree (top-level)" };
11
+ const optionsValidator = Compile(SubagentOptionParams);
12
+
13
+ /**
14
+ * Lowers a model tool call's `options` into the flat params the executor reads.
15
+ * Management fields given at the top level keep working, as in the flat shape older sessions declared.
16
+ */
17
+ export function flattenSubagentToolOptions(params: Record<string, unknown>, disabled?: DisabledFeatureSurface): SubagentParamsLike {
18
+ const removedTopLevel = removedModelWorkflowFieldError(params);
19
+ if (removedTopLevel) throw new Error(removedTopLevel);
20
+ const { options, ...topLevel } = params;
21
+ if (options === undefined) return topLevel;
22
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("subagent: options must be an object.");
23
+ const removedField = removedModelWorkflowFieldError(options);
24
+ if (removedField) throw new Error(removedField);
25
+ const entries = Object.entries(options);
26
+ const enabledKeys = SUBAGENT_OPTION_KEYS.filter((key) => !disabled?.params.has(key));
27
+ const unknown = entries.map(([key]) => key).filter((key) => !optionKeys.has(key));
28
+ if (unknown.length > 0) {
29
+ const fields = Object.keys(createSubagentParamsSchema(disabled).properties);
30
+ const hints = unknown.map((key) => {
31
+ if (Object.hasOwn(ALIAS_HINTS, key)) return `unknown options key '${key}'; use ${ALIAS_HINTS[key]}.`;
32
+ if (fields.includes(key)) return `'${key}' is a top-level field, not an option.`;
33
+ const suggestion = closestMatch(key, enabledKeys);
34
+ return `unknown options key '${key}'.${suggestion ? ` Did you mean '${suggestion}'?` : ""}`;
35
+ });
36
+ throw new Error(`subagent: ${hints.join(" ")} Valid options: ${enabledKeys.sort().join(", ")}.`);
37
+ }
38
+ const disabledKey = entries.find(([key]) => disabled?.params.has(key))?.[0];
39
+ if (disabledKey) throw new Error(`subagent option 'options.${disabledKey}' is disabled by config ${disabled!.params.get(disabledKey)}.`);
40
+ if (!optionsValidator.Check(options)) {
41
+ const errors = [...optionsValidator.Errors(options)].slice(0, 4).map((error) => `options${error.instancePath.replaceAll("/", ".")} ${error.message}`);
42
+ throw new Error(`subagent: ${errors.join("; ")}.`);
43
+ }
44
+ const conflicts = entries.filter(([key, value]) => topLevel[key] !== undefined && !isDeepStrictEqual(topLevel[key], value)).map(([key]) => `'${key}'`);
45
+ if (conflicts.length > 0) throw new Error(`subagent: ${conflicts.join(", ")} given both at the top level and in options with different values; give each once.`);
46
+ return { ...topLevel, ...options } as SubagentParamsLike;
47
+ }
@@ -2,6 +2,7 @@ import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-w
2
2
  import { Type } from "typebox";
3
3
  import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
4
4
  import type { ToolActivationMode } from "../shared/types.ts";
5
+ import { registerPinnedTool } from "./declaration-pinning.ts";
5
6
 
6
7
  interface ActivationDetails {
7
8
  enabled?: string[];
@@ -124,12 +125,12 @@ export function registerSubagentToolActivation(
124
125
  };
125
126
  const advertised = await options.advertisedPrompt();
126
127
  return {
127
- content: [{ type: "text", text: `Enabled: subagent. If your tool list includes subagent (possibly prefixed), call subagent({action:\"list\",capabilities:true}). Otherwise, wait for the next user prompt; do not retry now. Start Pi with --exclude-tools subagents_enable to keep subagent always available.${advertised ? `\n\n${advertised}` : ""}` }],
128
+ content: [{ type: "text", text: `Enabled: subagent. If your tool list includes subagent (possibly prefixed), call it now. Otherwise, wait for the next user prompt; do not retry now. Start Pi with --exclude-tools subagents_enable to keep subagent always available.${advertised ? `\n\n${advertised}` : ""}` }],
128
129
  details: { enabled: [SUBAGENT_NAME] },
129
130
  };
130
131
  },
131
132
  };
132
- pi.registerTool(loader);
133
+ registerPinnedTool(pi, loader);
133
134
 
134
135
  // Decided at session start and tree navigation only; switching models keeps the session's tools.
135
136
  let loaderSelected = true;