@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -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 +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  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 +29 -8
  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-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -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
 
@@ -26,33 +28,40 @@ export function readReplyWorkflowScript(sessionManager: Pick<ExtensionContext["s
26
28
 
27
29
  function scriptFromReply(content: AssistantMessage["content"]): ReplyWorkflowScript {
28
30
  const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent"
29
- && block.arguments?.workflow === true).length;
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}`;
@@ -524,7 +524,7 @@ function spawnParams(params: unknown, options: RegisterSubagentRpcBridgeOptions)
524
524
  const { script, ...input } = assertRecordParams(params, "spawn");
525
525
  if (Object.hasOwn(input, "workflowScript")) throw new SubagentRpcError("invalid_params", "RPC spawn workflowScript was removed; pass inline script text as script.");
526
526
  if (Object.hasOwn(input, "workflowScriptPath")) throw new SubagentRpcError("invalid_params", "RPC spawn workflowScriptPath was removed; pass the file as workflow: \"./path/to/script.js\".");
527
- if (input.workflow === true) throw new SubagentRpcError("invalid_params", "RPC spawn has no reply block for workflow: true; pass inline script text as script or a file as workflow: \"./path/to/script.js\".");
527
+ if (input.workflow === true || input.workflow === "true") throw new SubagentRpcError("invalid_params", "RPC spawn has no reply block for workflow: true; pass inline script text as script or a file as workflow: \"./path/to/script.js\".");
528
528
  if (script !== undefined) {
529
529
  if (typeof script !== "string" || !script.trim()) throw new SubagentRpcError("invalid_params", "RPC spawn script must be a non-empty string.");
530
530
  if (input.workflow !== undefined) throw new SubagentRpcError("invalid_params", "RPC spawn script cannot be combined with workflow.");
@@ -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,
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { Type } from "typebox";
6
6
  import type { DisabledFeatureSurface } from "../shared/disabled-features.ts";
7
+ import { MAX_ARGS_BYTES, MAX_ARGS_DEPTH, MAX_ARGS_FIELDS, MAX_ARGS_ITEMS } from "../workflows/workflow-resources.ts";
7
8
 
8
9
  function keepTopLevelParameterDescriptions<T extends object>(schema: T): T {
9
10
  return pruneNestedDescriptions(schema, []);
@@ -63,7 +64,6 @@ const AcceptanceOverride = Type.Unsafe({
63
64
  {
64
65
  type: "string",
65
66
  enum: ["reviewed"],
66
- deprecated: true,
67
67
  description: "Invalid as an explicit policy. Recognized only so preflight can explain that reviewed is an achieved status.",
68
68
  },
69
69
  {
@@ -159,7 +159,7 @@ const SubagentParamProperties = {
159
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." })),
160
160
  // Management action (when present, tool operates in management mode)
161
161
  action: Type.Optional(Type.String({ minLength: 1,
162
- 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\"}}."
163
163
  })),
164
164
  capabilities: Type.Optional(Type.Boolean({ description: "list: compact capability rows/details without system prompts." })),
165
165
  name: Type.Optional(Type.String({ description: "schedule.create name." })),
@@ -173,13 +173,14 @@ const SubagentParamProperties = {
173
173
  description: "Async directory for status/control."
174
174
  })),
175
175
  handoffPath: Type.Optional(Type.String({ description: "Existing manifest for worktree/lane actions." })),
176
- repo: Type.Optional(Type.String({ description: "worktree.cleanup repo; default cwd." })),
177
- 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." })),
178
178
  laneId: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Exact manifest run id for lane actions." })),
179
179
  merge: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordMerge evidence; read guide tool-reference." })),
180
180
  supersession: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordSupersession evidence; read guide tool-reference." })),
181
181
  index: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based child/transcript index." })),
182
182
  childId: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "Child-scoped stop identity." })),
183
+ toolCallId: Type.Optional(Type.String({ description: "Command tool-call id." })),
183
184
  view: Type.Optional(Type.String({
184
185
  enum: ["fleet", "transcript"],
185
186
  description: "status view: fleet overview or transcript tail with id/dir and optional index.",
@@ -187,22 +188,22 @@ const SubagentParamProperties = {
187
188
  lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "Transcript tail lines; default 80." })),
188
189
  topic: Type.Optional(Type.String()),
189
190
  message: Type.Optional(Type.String({ description: "resume/steer guidance or project.open prompt." })),
190
- 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)." })),
191
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." })),
192
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." })),
193
194
  scope: Type.Optional(Type.String({ enum: ["session", "user", "project"], description: "watchdog.configure scope; default session, persistent only if explicit." })),
194
195
  target: Type.Optional(Type.String({ enum: ["main", "children", "child"], description: "Watchdog target." })),
195
196
  focus: Type.Optional(Type.Boolean({ description: "Focus inspector.open/project.open pane." })),
196
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." })),
197
- at: Type.Optional(Type.String({ description: "schedule.create: delay (+10m) or zoned ISO timestamp." })),
198
- 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." })),
199
200
  sessionOnly: Type.Optional(Type.Boolean()),
200
201
  quiet: Type.Optional(Type.Boolean()),
201
- on: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "integer" }], description: "Reserved calendar selector." })),
202
- 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." })),
203
204
  overlap: Type.Optional(Type.String({ enum: ["skip"] })),
204
- catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed schedule occurrences; default latest." })),
205
- missionId: Type.Optional(Type.String()),
205
+ catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed; default latest." })),
206
+ missionId: Type.Optional(Type.String({ description: "Existing mission to attach to a workflow or schedule.create; read guide missions for lifecycle and retention." })),
206
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." })),
207
208
  missionUpdate: Type.Optional(Type.Unsafe({ ...MissionUpdateOverride, description: "Mission patch; read guide missions." })),
208
209
  missionStatus: Type.Optional(Type.String()),
@@ -222,7 +223,7 @@ const SubagentParamProperties = {
222
223
  anyOf: [{ type: "boolean" }, { type: "string", minLength: 1 }],
223
224
  description: "true: run the one ```js workflow block written in this same reply (false invalid). String with '/': script file read from request cwd. Other string: named workflow resource. Raw scripts (true or path) have no runs.host.",
224
225
  })),
225
- args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Bounded plain-JSON args for workflow; raw-script args are exposed deeply frozen and persisted, so do not include secrets." })),
226
+ args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: MAX_ARGS_FIELDS, additionalProperties: true, description: `Plain-JSON args for workflow; ${MAX_ARGS_FIELDS} fields/object, ${MAX_ARGS_ITEMS} items/array, depth ${MAX_ARGS_DEPTH}, ${MAX_ARGS_BYTES / 1024} KiB total; raw-script args are exposed deeply frozen and persisted, so do not include secrets.` })),
226
227
  globalConcurrencyLimit: Type.Optional(Type.Integer({ minimum: 1 })),
227
228
  maxSubagentSpawnsPerRun: Type.Optional(Type.Integer({ minimum: 1 })),
228
229
  preflight: Type.Optional(WorkflowPreflightOverride),
@@ -261,6 +262,7 @@ const SubagentParamProperties = {
261
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.",
262
263
  })),
263
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 })),
264
266
  skill: Type.Optional(SkillOverride),
265
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." })),
266
268
  fast: Type.Optional(Type.Boolean({ description: "Native OpenAI-Codex priority tier; default false, may cost more/quota." })),
@@ -272,19 +274,34 @@ const SubagentParamProperties = {
272
274
  { type: "string", minLength: 1 },
273
275
  { type: "object", properties: { command: { type: "string", minLength: 1 }, output: { type: "string", enum: ["json"] }, schema: { type: "object" }, timeoutMs: { type: "integer", minimum: 1 } }, required: ["command"], additionalProperties: false },
274
276
  ],
275
- description: "Host gate command run after the child finishes: a string, or { command, output: \"json\", schema?, timeoutMs? } whose passing stdout becomes structuredOutput (not with outputSchema). Cannot be combined with acceptance; an explicit acceptance of false is treated as omitted.",
277
+ description: "Host gate command run after the child finishes: a string, or an object; with output \"json\", passing stdout becomes structuredOutput (not with outputSchema). Cannot be combined with acceptance except false (treated as omitted).",
276
278
  })),
277
279
  };
278
280
 
279
- 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);
280
283
 
281
- 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));
282
299
 
283
300
  // Replaces workflow scripts when disabledFeatures lists "workflow-scripts". Kept small because every
284
301
  // field is sent on every request; the executor validates step shapes and placeholders strictly.
285
302
  const StructuredTask = { type: "object", properties: { agent: { type: "string", minLength: 1 }, task: { type: "string" } }, required: ["agent", "task"], additionalProperties: false };
286
303
  const StructuredWorkflowProperties = {
287
- 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\"}}." })),
288
305
  task: Type.Optional(Type.String({ description: "One-child task with agent, or the original request ({task}) with chain/tasks." })),
289
306
  tasks: Type.Optional(Type.Unsafe({ type: "array", minItems: 1, items: StructuredTask, description: "Parallel children; results in order." })),
290
307
  // Flattened step: {agent, task?, as?} or {parallel}; no object-shape union for provider converters.
@@ -299,7 +316,7 @@ const StructuredWorkflowProperties = {
299
316
  export function createSubagentParamsSchema(disabled?: DisabledFeatureSurface): typeof SubagentParams {
300
317
  if (!disabled || disabled.params.size === 0) return SubagentParams;
301
318
  const structured = disabled.features.has("workflow-scripts");
302
- const enabledProperties = Object.fromEntries(Object.entries(SubagentParamProperties).flatMap(([name, schema]) => {
319
+ const enabledProperties = Object.fromEntries(Object.entries(ModelTopLevelProperties).flatMap(([name, schema]) => {
303
320
  if (disabled.params.has(name)) return [];
304
321
  if (structured && name === "action") return [[name, StructuredWorkflowProperties.action]];
305
322
  if (structured && name === "task") return [[name, StructuredWorkflowProperties.task], ["tasks", StructuredWorkflowProperties.tasks], ["chain", StructuredWorkflowProperties.chain]];
@@ -310,22 +327,11 @@ export function createSubagentParamsSchema(disabled?: DisabledFeatureSurface): t
310
327
  }
311
328
 
312
329
  const SubagentWaitParamsSchema = Type.Object({
313
- id: Type.Optional(Type.String({
314
- 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.",
315
- })),
316
- nonBlocking: Type.Optional(Type.Boolean({
317
- 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.",
318
- })),
319
- all: Type.Optional(Type.Boolean({
320
- 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.",
321
- })),
322
- timeoutMs: Type.Optional(Type.Integer({
323
- minimum: 1,
324
- 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.",
325
- })),
326
- stopOnAttention: Type.Optional(Type.Boolean({
327
- 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.",
328
- })),
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." })),
329
335
  });
330
336
 
331
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;