@xzzpig/pi-subagents 0.8.0 → 0.9.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 (218) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +151 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +5 -4
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +370 -114
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +12 -2
  35. package/src/agents/agents.ts +919 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +31 -20
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +48 -18
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +57 -21
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +2 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +366 -128
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +45 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +189 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +676 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +468 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1172 -400
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +314 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +342 -0
  115. package/src/runs/shared/child-tool-plan.ts +540 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +142 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +38 -48
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +15 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/single-output.ts +89 -22
  149. package/src/runs/shared/structured-output.ts +49 -9
  150. package/src/runs/shared/subagent-control.ts +6 -2
  151. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  152. package/src/runs/shared/task-intent.ts +21 -7
  153. package/src/runs/shared/tool-availability.ts +18 -62
  154. package/src/runs/shared/tool-budget.ts +0 -14
  155. package/src/runs/shared/tool-timeout.ts +1 -1
  156. package/src/runs/shared/workflow-graph.ts +16 -0
  157. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  158. package/src/runs/shared/worktree.ts +571 -62
  159. package/src/shared/atomic-json.ts +3 -1
  160. package/src/shared/child-session-name.ts +46 -0
  161. package/src/shared/extension-context.ts +24 -0
  162. package/src/shared/fork-context.ts +21 -12
  163. package/src/shared/fork-session-cwd.ts +27 -0
  164. package/src/shared/formatters.ts +18 -3
  165. package/src/shared/jsonl-writer.ts +11 -0
  166. package/src/shared/launch-contract.ts +8 -1
  167. package/src/shared/pruned-fork.ts +450 -0
  168. package/src/shared/session-file-trust.ts +19 -0
  169. package/src/shared/session-tokens.ts +14 -3
  170. package/src/shared/settings.ts +19 -105
  171. package/src/shared/shortcuts.ts +17 -0
  172. package/src/shared/thinking-ceiling.ts +0 -6
  173. package/src/shared/types.ts +524 -70
  174. package/src/shared/utils.ts +60 -93
  175. package/src/shared/workflow-child-permit.ts +207 -0
  176. package/src/slash/delegation-adapters.ts +1 -9
  177. package/src/slash/delegation-request.ts +0 -4
  178. package/src/slash/prompt-template-bridge.ts +37 -1
  179. package/src/slash/slash-bridge.ts +1 -2
  180. package/src/slash/slash-commands.ts +383 -116
  181. package/src/slash/slash-live-state.ts +22 -11
  182. package/src/slash/subagents-admin.ts +29 -12
  183. package/src/tui/fleet-native-transcript.ts +4 -0
  184. package/src/tui/fleet-status.ts +217 -82
  185. package/src/tui/fleet-transcript.ts +11 -5
  186. package/src/tui/fleet.ts +54 -28
  187. package/src/tui/render-helpers.ts +31 -0
  188. package/src/tui/render.ts +1429 -163
  189. package/src/watchdog/change-signature.ts +40 -1
  190. package/src/watchdog/child-status.ts +54 -34
  191. package/src/watchdog/diff-tool.ts +77 -0
  192. package/src/watchdog/emission-guard.ts +5 -3
  193. package/src/watchdog/guidance.ts +20 -0
  194. package/src/watchdog/register-child.ts +28 -25
  195. package/src/watchdog/register-main.ts +10 -9
  196. package/src/watchdog/render.ts +4 -5
  197. package/src/watchdog/review.ts +15 -4
  198. package/src/watchdog/rules.ts +70 -0
  199. package/src/watchdog/runtime.ts +75 -92
  200. package/src/watchdog/scope.ts +0 -11
  201. package/src/watchdog/settings.ts +48 -104
  202. package/src/watchdog/turn-delta.ts +1 -1
  203. package/src/watchdog/types.ts +18 -32
  204. package/src/watchdog/warning-format.ts +0 -1
  205. package/src/workflows/chat-progress.ts +7 -3
  206. package/src/workflows/host-command.ts +235 -0
  207. package/src/workflows/scripted-workflow.ts +988 -59
  208. package/src/workflows/workflow-checklist.ts +439 -0
  209. package/src/workflows/workflow-child-summary.ts +121 -0
  210. package/src/workflows/workflow-preflight.ts +297 -0
  211. package/src/workflows/workflow-receipt.ts +232 -6
  212. package/src/workflows/workflow-resources.ts +150 -0
  213. package/src/workflows/workflow-settlement.ts +246 -0
  214. package/src/runs/shared/child-protocol.ts +0 -401
  215. package/src/runs/shared/pi-args.ts +0 -935
  216. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  217. package/src/runs/shared/turn-budget.ts +0 -98
  218. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -1,5 +1,11 @@
1
1
  export const BUILTIN_AGENT_NAMES = [
2
2
  "advisor",
3
+ "claude-code",
4
+ "claude-code-writer",
5
+ "codex-exec",
6
+ "codex-exec-writer",
7
+ "cursor-agent",
8
+ "cursor-agent-writer",
3
9
  "delegate",
4
10
  "oracle",
5
11
  "researcher",
@@ -0,0 +1,70 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { registerRuntimeAgent, type RuntimeAgentDefinition, type RuntimeAgentRegistration } from "./runtime-agent-registry.ts";
3
+
4
+ export const RUNTIME_AGENT_REGISTER_EVENT = "pi-subagents:runtime-agent-register:v1";
5
+ export const RUNTIME_AGENT_REGISTER_VERSION = 1;
6
+
7
+ export type RuntimeAgentRegistrationResult =
8
+ | { ok: true; registration: RuntimeAgentRegistration }
9
+ | { ok: false; error: Error };
10
+
11
+ export interface RuntimeAgentRegistrationRequest {
12
+ version: 1;
13
+ name: string;
14
+ definition: RuntimeAgentDefinition;
15
+ result?: RuntimeAgentRegistrationResult;
16
+ }
17
+
18
+ export interface RegisterRuntimeAgentViaEventsInput {
19
+ pi: Pick<ExtensionAPI, "events">;
20
+ name: string;
21
+ definition: RuntimeAgentDefinition;
22
+ }
23
+
24
+ function errorFrom(value: unknown): Error {
25
+ return value instanceof Error ? value : new Error(String(value));
26
+ }
27
+
28
+ /** Register through the installed pi-subagents owner in this Pi process. */
29
+ export function registerAgentViaEvents(input: RegisterRuntimeAgentViaEventsInput): RuntimeAgentRegistration {
30
+ const request: RuntimeAgentRegistrationRequest = {
31
+ version: RUNTIME_AGENT_REGISTER_VERSION,
32
+ name: input.name,
33
+ definition: input.definition,
34
+ };
35
+ input.pi.events.emit(RUNTIME_AGENT_REGISTER_EVENT, request);
36
+ const result = request.result as unknown;
37
+ if (result === undefined) {
38
+ throw new Error("pi-subagents is not installed, not ready, or does not support runtime agent event registration.");
39
+ }
40
+ if (result && typeof result === "object" && !Array.isArray(result)) {
41
+ const candidate = result as Record<string, unknown>;
42
+ if (candidate.ok === true && candidate.registration && typeof candidate.registration === "object" && typeof (candidate.registration as { dispose?: unknown }).dispose === "function") {
43
+ return candidate.registration as RuntimeAgentRegistration;
44
+ }
45
+ if (candidate.ok === false && candidate.error instanceof Error) throw candidate.error;
46
+ }
47
+ throw new Error("pi-subagents returned a malformed runtime agent registration result.");
48
+ }
49
+
50
+ /** Install the process-local registration listener for the owning pi-subagents runtime. */
51
+ export function registerRuntimeAgentEventListener(pi: ExtensionAPI): () => void {
52
+ return pi.events.on(RUNTIME_AGENT_REGISTER_EVENT, (rawRequest) => {
53
+ if (!rawRequest || typeof rawRequest !== "object" || Array.isArray(rawRequest)) return;
54
+ const request = rawRequest as Record<string, unknown>;
55
+ if (request.result !== undefined) return;
56
+ try {
57
+ if (request.version !== RUNTIME_AGENT_REGISTER_VERSION) {
58
+ throw new Error(`Unsupported runtime agent registration event version '${String(request.version)}'.`);
59
+ }
60
+ const registration = registerRuntimeAgent({
61
+ pi,
62
+ name: request.name as string,
63
+ definition: request.definition as RuntimeAgentDefinition,
64
+ });
65
+ request.result = { ok: true, registration } satisfies RuntimeAgentRegistrationResult;
66
+ } catch (error) {
67
+ request.result = { ok: false, error: errorFrom(error) } satisfies RuntimeAgentRegistrationResult;
68
+ }
69
+ });
70
+ }
@@ -1,9 +1,9 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import type { AcceptanceInput, AcceptanceRole, AgentRunnerConfig, OutputMode, ToolBudgetConfig, TurnBudgetConfig } from "../shared/types.ts";
2
+ import type { AcceptanceInput, AcceptanceRole, AgentRunnerConfig, OutputMode, ToolBudgetConfig } from "../shared/types.ts";
3
+ import { CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL, isCodeOwnedExternalCliAdapterId, parseExternalCliCapabilityNarrowing, validateCodeOwnedProfileRunner } from "../runs/shared/external-cli-contract.ts";
3
4
  import { validateAcceptanceInput } from "../runs/shared/acceptance.ts";
4
5
  import { validatePermissionRules, type PermissionRules } from "../runs/shared/permissions.ts";
5
6
  import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
6
- import { resolveTurnBudgetConfig } from "../runs/shared/turn-budget.ts";
7
7
  import { BUILTIN_AGENT_NAMES } from "./builtin-names.ts";
8
8
  import type { AgentConfig, AgentDefaultContext, AgentDiscoveryDiagnostic } from "./agents.ts";
9
9
 
@@ -20,18 +20,20 @@ export interface RuntimeAgentDefinition {
20
20
  systemPrompt: string;
21
21
  aliases?: readonly string[];
22
22
  tools?: readonly string[];
23
+ excludeTools?: readonly string[];
24
+ allowNestedSubagents?: boolean;
23
25
  mcpDirectTools?: readonly string[];
24
26
  model?: string;
25
27
  fallbackModels?: readonly string[];
26
28
  thinking?: string | false;
27
29
  systemPromptMode?: "append" | "replace";
28
30
  inheritProjectContext?: boolean;
31
+ inheritGlobalContext?: boolean;
29
32
  inheritSkills?: boolean;
30
33
  defaultContext?: AgentDefaultContext;
31
34
  defaultAsync?: boolean;
32
35
  defaultTimeoutMs?: number;
33
36
  defaultToolTimeoutMs?: number;
34
- defaultTurnBudget?: TurnBudgetConfig;
35
37
  defaultAcceptance?: AcceptanceInput;
36
38
  acceptanceRole?: AcceptanceRole;
37
39
  runner?: AgentRunnerConfig;
@@ -39,6 +41,7 @@ export interface RuntimeAgentDefinition {
39
41
  skillPath?: readonly string[];
40
42
  extensions?: readonly string[];
41
43
  subagentOnlyExtensions?: readonly string[];
44
+ mutationTools?: readonly string[];
42
45
  output?: string;
43
46
  outputMode?: OutputMode;
44
47
  defaultReads?: readonly string[];
@@ -133,8 +136,8 @@ function validateStringList(value: unknown, field: string): string[] | undefined
133
136
 
134
137
  function validatePositiveInteger(value: unknown, field: string): number | undefined {
135
138
  if (value === undefined) return undefined;
136
- if (!Number.isInteger(value) || (value as number) <= 0) throw new Error(`${field} must be a positive integer when provided.`);
137
- return value as number;
139
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw new Error(`${field} must be a positive integer when provided.`);
140
+ return value;
138
141
  }
139
142
 
140
143
  function validateBoolean(value: unknown, field: string): boolean | undefined {
@@ -170,18 +173,15 @@ function validateRunner(value: unknown): AgentRunnerConfig | undefined {
170
173
  if (runner.type !== "external-cli") throw new Error("Runtime agent definition runner.type must be 'pi', 'external-cli', or 'external-job'.");
171
174
  if (typeof runner.command !== "string" || !runner.command.trim()) throw new Error("Runtime agent definition external-cli runner requires a non-empty command string.");
172
175
  if (runner.args !== undefined && (!Array.isArray(runner.args) || runner.args.some((arg) => typeof arg !== "string"))) throw new Error("Runtime agent definition external-cli runner args must be an array of strings.");
176
+ if (runner.adapter !== undefined && !isCodeOwnedExternalCliAdapterId(runner.adapter)) throw new Error(`Runtime agent definition external-cli runner adapter must be ${CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL}.`);
177
+ if (runner.adapter !== undefined && Array.isArray(runner.args) && runner.args.length > 0) throw new Error(`Runtime agent definition ${runner.adapter} adapter owns its argv; runner args are not supported.`);
173
178
  if (runner.promptDelivery !== undefined && runner.promptDelivery !== "stdin") throw new Error("Runtime agent definition external-cli runner promptDelivery must be 'stdin'.");
174
- const supported = new Set(["type", "command", "args", "promptDelivery"]);
179
+ const capabilities = parseExternalCliCapabilityNarrowing(runner.capabilities, "Runtime agent definition external-cli runner capabilities");
180
+ const supported = new Set(["type", "adapter", "command", "args", "promptDelivery", "capabilities"]);
175
181
  const unknown = Object.keys(runner).filter((key) => !supported.has(key));
176
182
  if (unknown.length > 0) throw new Error(`Runtime agent definition external-cli runner has unsupported fields: ${unknown.join(", ")}.`);
177
183
  const args = runner.args as string[] | undefined;
178
- return { type: "external-cli", command: runner.command.trim(), ...(args?.length ? { args } : {}), ...(runner.promptDelivery ? { promptDelivery: "stdin" as const } : {}) };
179
- }
180
-
181
- function validateTurnBudget(value: unknown): TurnBudgetConfig | undefined {
182
- const result = resolveTurnBudgetConfig(value, "Runtime agent definition defaultTurnBudget");
183
- if (result.error) throw new Error(result.error);
184
- return result.turnBudget;
184
+ return { type: "external-cli", ...(isCodeOwnedExternalCliAdapterId(runner.adapter) ? { adapter: runner.adapter } : {}), command: runner.command.trim(), ...(args?.length ? { args } : {}), ...(runner.promptDelivery ? { promptDelivery: "stdin" as const } : {}), ...(capabilities ? { capabilities } : {}) };
185
185
  }
186
186
 
187
187
  function validateAcceptance(value: unknown): AcceptanceInput | undefined {
@@ -200,10 +200,10 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
200
200
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Runtime agent definition must be an object.");
201
201
  const definition = value as Record<string, unknown>;
202
202
  const supported = new Set([
203
- "description", "systemPrompt", "aliases", "tools", "mcpDirectTools", "model", "fallbackModels", "thinking",
204
- "systemPromptMode", "inheritProjectContext", "inheritSkills", "defaultContext", "defaultAsync", "defaultTimeoutMs",
205
- "defaultToolTimeoutMs", "defaultTurnBudget", "defaultAcceptance", "acceptanceRole", "runner", "skills", "skillPath",
206
- "extensions", "subagentOnlyExtensions", "output", "outputMode", "defaultReads", "defaultProgress", "injectToContext", "interactive",
203
+ "description", "systemPrompt", "aliases", "tools", "excludeTools", "allowNestedSubagents", "mcpDirectTools", "model", "fallbackModels", "thinking",
204
+ "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "defaultContext", "defaultAsync", "defaultTimeoutMs",
205
+ "defaultToolTimeoutMs", "defaultAcceptance", "acceptanceRole", "runner", "skills", "skillPath",
206
+ "extensions", "subagentOnlyExtensions", "mutationTools", "output", "outputMode", "defaultReads", "defaultProgress", "injectToContext", "interactive",
207
207
  "maxSubagentDepth", "completionGuard", "toolBudget", "permissions",
208
208
  ]);
209
209
  const unknown = Object.keys(definition).filter((key) => !supported.has(key));
@@ -220,21 +220,24 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
220
220
  if (outputMode !== undefined && outputMode !== "inline" && outputMode !== "file-only") throw new Error("Runtime agent definition outputMode must be 'inline' or 'file-only'.");
221
221
  const aliases = validateStringList(definition.aliases, "Runtime agent definition aliases");
222
222
  const tools = validateStringList(definition.tools, "Runtime agent definition tools");
223
+ const excludeTools = validateStringList(definition.excludeTools, "Runtime agent definition excludeTools");
224
+ const allowNestedSubagents = validateBoolean(definition.allowNestedSubagents, "Runtime agent definition allowNestedSubagents");
223
225
  const mcpDirectTools = validateStringList(definition.mcpDirectTools, "Runtime agent definition mcpDirectTools");
224
226
  const model = validateOptionalString(definition.model, "Runtime agent definition model");
225
227
  const fallbackModels = validateStringList(definition.fallbackModels, "Runtime agent definition fallbackModels");
226
228
  const inheritProjectContext = validateBoolean(definition.inheritProjectContext, "Runtime agent definition inheritProjectContext");
229
+ const inheritGlobalContext = validateBoolean(definition.inheritGlobalContext, "Runtime agent definition inheritGlobalContext");
227
230
  const inheritSkills = validateBoolean(definition.inheritSkills, "Runtime agent definition inheritSkills");
228
231
  const defaultAsync = validateBoolean(definition.defaultAsync, "Runtime agent definition defaultAsync");
229
232
  const defaultTimeoutMs = validatePositiveInteger(definition.defaultTimeoutMs, "Runtime agent definition defaultTimeoutMs");
230
233
  const defaultToolTimeoutMs = validatePositiveInteger(definition.defaultToolTimeoutMs, "Runtime agent definition defaultToolTimeoutMs");
231
- const defaultTurnBudget = validateTurnBudget(definition.defaultTurnBudget);
232
234
  const defaultAcceptance = validateAcceptance(definition.defaultAcceptance);
233
235
  const runner = validateRunner(definition.runner);
234
236
  const skills = validateStringList(definition.skills, "Runtime agent definition skills");
235
237
  const skillPath = validateStringList(definition.skillPath, "Runtime agent definition skillPath");
236
238
  const extensions = validateStringList(definition.extensions, "Runtime agent definition extensions");
237
239
  const subagentOnlyExtensions = validateStringList(definition.subagentOnlyExtensions, "Runtime agent definition subagentOnlyExtensions");
240
+ const mutationTools = validateStringList(definition.mutationTools, "Runtime agent definition mutationTools");
238
241
  const output = validateOptionalString(definition.output, "Runtime agent definition output");
239
242
  const defaultReads = validateStringList(definition.defaultReads, "Runtime agent definition defaultReads");
240
243
  const defaultProgress = validateBoolean(definition.defaultProgress, "Runtime agent definition defaultProgress");
@@ -249,18 +252,20 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
249
252
  systemPrompt: validateString(definition.systemPrompt, "Runtime agent definition systemPrompt", MAX_SYSTEM_PROMPT_LENGTH),
250
253
  ...(aliases ? { aliases } : {}),
251
254
  ...(tools ? { tools } : {}),
255
+ ...(excludeTools ? { excludeTools } : {}),
256
+ ...(allowNestedSubagents !== undefined ? { allowNestedSubagents } : {}),
252
257
  ...(mcpDirectTools ? { mcpDirectTools } : {}),
253
258
  ...(model ? { model } : {}),
254
259
  ...(fallbackModels ? { fallbackModels } : {}),
255
260
  ...(thinking !== undefined ? { thinking: thinking as string | false } : {}),
256
261
  ...(systemPromptMode !== undefined ? { systemPromptMode: systemPromptMode as "append" | "replace" } : {}),
257
262
  ...(inheritProjectContext !== undefined ? { inheritProjectContext } : {}),
263
+ ...(inheritGlobalContext !== undefined ? { inheritGlobalContext } : {}),
258
264
  ...(inheritSkills !== undefined ? { inheritSkills } : {}),
259
265
  ...(defaultContext !== undefined ? { defaultContext: defaultContext as AgentDefaultContext } : {}),
260
266
  ...(defaultAsync !== undefined ? { defaultAsync } : {}),
261
267
  ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
262
268
  ...(defaultToolTimeoutMs !== undefined ? { defaultToolTimeoutMs } : {}),
263
- ...(defaultTurnBudget !== undefined ? { defaultTurnBudget } : {}),
264
269
  ...(defaultAcceptance !== undefined ? { defaultAcceptance } : {}),
265
270
  ...(acceptanceRole !== undefined ? { acceptanceRole: acceptanceRole as AcceptanceRole } : {}),
266
271
  ...(runner !== undefined ? { runner } : {}),
@@ -268,6 +273,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
268
273
  ...(skillPath ? { skillPath } : {}),
269
274
  ...(extensions ? { extensions } : {}),
270
275
  ...(subagentOnlyExtensions ? { subagentOnlyExtensions } : {}),
276
+ ...(mutationTools ? { mutationTools } : {}),
271
277
  ...(output ? { output } : {}),
272
278
  ...(outputMode !== undefined ? { outputMode: outputMode as OutputMode } : {}),
273
279
  ...(defaultReads ? { defaultReads } : {}),
@@ -327,18 +333,20 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
327
333
  ...(aliases ? { aliases } : {}),
328
334
  ...(definition.runner !== undefined ? { runner: definition.runner } : {}),
329
335
  ...(definition.tools !== undefined ? { tools: [...definition.tools] } : {}),
336
+ ...(definition.excludeTools !== undefined ? { excludeTools: [...definition.excludeTools] } : {}),
337
+ ...(definition.allowNestedSubagents !== undefined ? { allowNestedSubagents: definition.allowNestedSubagents } : {}),
330
338
  ...(definition.mcpDirectTools !== undefined ? { mcpDirectTools: [...definition.mcpDirectTools] } : {}),
331
339
  ...(definition.model !== undefined ? { model: definition.model } : {}),
332
340
  ...(definition.fallbackModels !== undefined ? { fallbackModels: [...definition.fallbackModels] } : {}),
333
341
  ...(definition.thinking !== undefined ? { thinking: definition.thinking } : {}),
334
342
  systemPromptMode: definition.systemPromptMode ?? defaultSystemPromptMode(name),
335
343
  inheritProjectContext: definition.inheritProjectContext ?? defaultInheritProjectContext(name),
344
+ inheritGlobalContext: definition.inheritGlobalContext ?? false,
336
345
  inheritSkills: definition.inheritSkills ?? defaultInheritSkills(),
337
346
  ...(definition.defaultContext !== undefined ? { defaultContext: definition.defaultContext } : {}),
338
347
  ...(definition.defaultAsync !== undefined ? { defaultAsync: definition.defaultAsync } : {}),
339
348
  ...(definition.defaultTimeoutMs !== undefined ? { defaultTimeoutMs: definition.defaultTimeoutMs } : {}),
340
349
  ...(definition.defaultToolTimeoutMs !== undefined ? { defaultToolTimeoutMs: definition.defaultToolTimeoutMs } : {}),
341
- ...(definition.defaultTurnBudget !== undefined ? { defaultTurnBudget: definition.defaultTurnBudget } : {}),
342
350
  ...(definition.defaultAcceptance !== undefined ? { defaultAcceptance: definition.defaultAcceptance } : {}),
343
351
  ...(definition.acceptanceRole !== undefined ? { acceptanceRole: definition.acceptanceRole } : {}),
344
352
  systemPrompt: definition.systemPrompt,
@@ -348,6 +356,7 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
348
356
  ...(definition.skillPath !== undefined ? { skillPath: [...definition.skillPath] } : {}),
349
357
  ...(definition.extensions !== undefined ? { extensions: [...definition.extensions] } : {}),
350
358
  ...(definition.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: [...definition.subagentOnlyExtensions] } : {}),
359
+ ...(definition.mutationTools !== undefined ? { mutationTools: [...definition.mutationTools] } : {}),
351
360
  ...(definition.output !== undefined ? { output: definition.output } : {}),
352
361
  ...(definition.outputMode !== undefined ? { outputMode: definition.outputMode } : {}),
353
362
  ...(definition.defaultReads !== undefined ? { defaultReads: [...definition.defaultReads] } : {}),
@@ -368,6 +377,8 @@ export function registerRuntimeAgent(input: RegisterRuntimeAgentInput): RuntimeA
368
377
  const name = validateString(input.name, "Runtime agent name", MAX_AGENT_NAME_LENGTH);
369
378
  const definition = validateDefinition(input.definition);
370
379
  const agent = toAgentConfig(name, definition);
380
+ const profileError = validateCodeOwnedProfileRunner(agent);
381
+ if (profileError) throw new Error(profileError);
371
382
  assertNoBuiltinCollision(agent);
372
383
  const current = registry();
373
384
  const records = current.byPi.get(pi) ?? [];
package/src/api/agents.ts CHANGED
@@ -1,7 +1,12 @@
1
- import { registerRuntimeAgent, type RegisterRuntimeAgentInput, type RuntimeAgentDefinition, type RuntimeAgentRegistration } from "../agents/runtime-agent-registry.ts";
1
+ import type { RegisterRuntimeAgentInput, RuntimeAgentDefinition, RuntimeAgentRegistration } from "../agents/runtime-agent-registry.ts";
2
+ export { registerRuntimeAgent as registerAgent } from "../agents/runtime-agent-registry.ts";
3
+ export {
4
+ RUNTIME_AGENT_REGISTER_EVENT,
5
+ RUNTIME_AGENT_REGISTER_VERSION,
6
+ registerAgentViaEvents,
7
+ type RegisterRuntimeAgentViaEventsInput,
8
+ type RuntimeAgentRegistrationRequest,
9
+ type RuntimeAgentRegistrationResult,
10
+ } from "../agents/runtime-agent-events.ts";
2
11
 
3
12
  export type { RegisterRuntimeAgentInput, RuntimeAgentDefinition, RuntimeAgentRegistration };
4
-
5
- export function registerAgent(input: RegisterRuntimeAgentInput): RuntimeAgentRegistration {
6
- return registerRuntimeAgent(input);
7
- }
@@ -4,7 +4,11 @@ export const BACKGROUND_WORK_REGISTRY_KEY = "pi-subagents.background-work.v1";
4
4
  const MAX_PROVIDER_NAME_LENGTH = 128;
5
5
  const MAX_PROVIDERS = 100;
6
6
  const MAX_ITEM_ID_LENGTH = 256;
7
- const MAX_SESSION_ID_LENGTH = 256;
7
+ /**
8
+ * A Pi session id is the session file path, which routinely exceeds a short
9
+ * identity budget in nested worktrees, so it is bounded like the other paths.
10
+ */
11
+ const MAX_SESSION_ID_LENGTH = 4_096;
8
12
  const MAX_WAKE_CHANNEL_LENGTH = 256;
9
13
  const MAX_ITEMS_PER_PROVIDER = 10_000;
10
14
 
@@ -18,9 +22,14 @@ export interface BackgroundWorkReconcileContext {
18
22
  nowMs: number;
19
23
  }
20
24
 
25
+ export interface BackgroundWorkListContext {
26
+ sessionId: string;
27
+ nowMs: number;
28
+ }
29
+
21
30
  export interface BackgroundWorkProvider {
22
31
  name: string;
23
- listActiveWork(): readonly BackgroundWorkItem[];
32
+ listActiveWork(context?: BackgroundWorkListContext): readonly BackgroundWorkItem[];
24
33
  wakeChannels?: readonly string[];
25
34
  reconcile?(context: BackgroundWorkReconcileContext): void;
26
35
  }
@@ -167,7 +176,7 @@ export function snapshotBackgroundWork(sessionId: string, nowMs = Date.now()): B
167
176
  }
168
177
  let active: readonly BackgroundWorkItem[];
169
178
  try {
170
- active = provider.listActiveWork();
179
+ active = provider.listActiveWork({ sessionId, nowMs });
171
180
  } catch (error) {
172
181
  throw new Error(
173
182
  `Background-work provider '${provider.name}' listActiveWork failed: ${error instanceof Error ? error.message : String(error)}`,
@@ -1,5 +1,4 @@
1
1
  export {
2
- SUBAGENT_CAPABILITY_CEILING_ENV,
3
2
  SUBAGENT_CAPABILITY_CEILING_REGISTRY_KEY,
4
3
  SUBAGENT_CAPABILITY_CEILING_VERSION,
5
4
  decodeSubagentCapabilityCeiling,
@@ -2,4 +2,4 @@ export {
2
2
  resolvePiLaunchToolPlan,
3
3
  type PiLaunchToolPlan,
4
4
  type ResolvePiLaunchToolPlanInput,
5
- } from "../runs/shared/pi-args.ts";
5
+ } from "../runs/shared/child-tool-plan.ts";
@@ -7,11 +7,6 @@ export const SUBAGENT_DELEGATION_UPDATE_EVENT = "prompt-template:subagent:update
7
7
  export const SUBAGENT_DELEGATION_RESPONSE_EVENT = "prompt-template:subagent:response";
8
8
  export const SUBAGENT_DELEGATION_CANCEL_EVENT = "prompt-template:subagent:cancel";
9
9
 
10
- export interface SubagentDelegationTurnBudget {
11
- maxTurns: number;
12
- graceTurns?: number;
13
- }
14
-
15
10
  export interface SubagentDelegationToolBudget {
16
11
  soft?: number;
17
12
  hard: number;
@@ -37,7 +32,6 @@ export interface SubagentDelegationRequest {
37
32
  model?: string;
38
33
  thinking?: SubagentDelegationThinking;
39
34
  timeoutMs?: number;
40
- turnBudget?: SubagentDelegationTurnBudget;
41
35
  toolBudget?: SubagentDelegationToolBudget;
42
36
  skill?: string | string[] | boolean;
43
37
  artifacts?: boolean;
@@ -69,7 +63,6 @@ export type SubagentDelegationStatus =
69
63
  | "timed_out"
70
64
  | "cancelled"
71
65
  | "interrupted"
72
- | "turn_budget_exhausted"
73
66
  | "tool_budget_exhausted"
74
67
  | "structured_output_failed"
75
68
  | "acceptance_failed"
@@ -48,7 +48,16 @@ interface ExternalRunRegistry {
48
48
  runs: Map<string, ExternalRun>;
49
49
  }
50
50
 
51
- const RUN_FIELDS = new Set([
51
+ interface TrustedExternalRunRecord {
52
+ value: unknown;
53
+ normalized: ExternalRun;
54
+ keys: readonly string[];
55
+ values: readonly unknown[];
56
+ }
57
+
58
+ const trustedRecordsByRegistry = new WeakMap<object, Map<string, TrustedExternalRunRecord>>();
59
+
60
+ const RUN_FIELD_NAMES = [
52
61
  "id",
53
62
  "sessionId",
54
63
  "source",
@@ -61,7 +70,8 @@ const RUN_FIELDS = new Set([
61
70
  "preview",
62
71
  "reportPath",
63
72
  "transcriptPath",
64
- ]);
73
+ ] as const satisfies readonly (keyof ExternalRun)[];
74
+ const RUN_FIELDS = new Set<string>(RUN_FIELD_NAMES);
65
75
  const UPDATE_FIELDS = new Set([...RUN_FIELDS].filter((field) => field !== "id" && field !== "sessionId" && field !== "source"));
66
76
 
67
77
  function registry(): ExternalRunRegistry {
@@ -79,6 +89,14 @@ function registry(): ExternalRunRegistry {
79
89
  return candidate as ExternalRunRegistry;
80
90
  }
81
91
 
92
+ function trustedRecords(current: ExternalRunRegistry): Map<string, TrustedExternalRunRecord> {
93
+ const cached = trustedRecordsByRegistry.get(current);
94
+ if (cached) return cached;
95
+ const records = new Map<string, TrustedExternalRunRecord>();
96
+ trustedRecordsByRegistry.set(current, records);
97
+ return records;
98
+ }
99
+
82
100
  function inputObject(value: unknown, field: string, allowed: Set<string>): Record<string, unknown> {
83
101
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${field} must be an object.`);
84
102
  const input = value as Record<string, unknown>;
@@ -150,6 +168,41 @@ function clone(run: ExternalRun): ExternalRun {
150
168
  return { ...run };
151
169
  }
152
170
 
171
+ function trustedRecord(value: unknown, normalized: ExternalRun): TrustedExternalRunRecord {
172
+ const candidate = value as ExternalRun;
173
+ return {
174
+ value,
175
+ normalized,
176
+ keys: Object.keys(candidate),
177
+ values: RUN_FIELD_NAMES.map((field) => candidate[field]),
178
+ };
179
+ }
180
+
181
+ function trustedRecordValue(value: unknown, record: TrustedExternalRunRecord | undefined): ExternalRun | undefined {
182
+ if (!record || record.value !== value || !value || typeof value !== "object") return undefined;
183
+ try {
184
+ const candidate = value as ExternalRun;
185
+ const keys = Object.keys(candidate);
186
+ if (keys.length !== record.keys.length || keys.some((key, index) => key !== record.keys[index])) return undefined;
187
+ for (const [index, field] of RUN_FIELD_NAMES.entries()) {
188
+ if (candidate[field] !== record.values[index]) return undefined;
189
+ }
190
+ return record.normalized;
191
+ } catch {
192
+ return undefined;
193
+ }
194
+ }
195
+
196
+ function rememberTrustedRecord(current: ExternalRunRegistry, cacheKey: string, value: unknown, normalized: ExternalRun): void {
197
+ trustedRecords(current).set(cacheKey, trustedRecord(value, normalized));
198
+ }
199
+
200
+ function normalizeCachedRecord(current: ExternalRunRegistry, cacheKey: string, value: unknown): ExternalRun {
201
+ const run = validateRun(value);
202
+ rememberTrustedRecord(current, cacheKey, value, run);
203
+ return run;
204
+ }
205
+
153
206
  /** Register one current-session external job. pi-subagents never controls the job. */
154
207
  export function registerExternalRun(input: ExternalRun): ExternalRun {
155
208
  const run = validateRun(input);
@@ -158,6 +211,7 @@ export function registerExternalRun(input: ExternalRun): ExternalRun {
158
211
  if (current.runs.has(runKey)) throw new Error(`External run '${run.id}' is already registered for session '${run.sessionId}'.`);
159
212
  if (current.runs.size >= EXTERNAL_RUN_LIMITS.maxCachedRuns) throw new Error(`External-run registry supports at most ${EXTERNAL_RUN_LIMITS.maxCachedRuns} cached runs.`);
160
213
  current.runs.set(runKey, run);
214
+ rememberTrustedRecord(current, runKey, run, run);
161
215
  return clone(run);
162
216
  }
163
217
 
@@ -172,12 +226,17 @@ export function updateExternalRun(sessionId: string, id: string, update: Externa
172
226
  if (!previous) throw new Error(`External run '${safeId}' is not registered for session '${safeSessionId}'.`);
173
227
  const next = validateRun({ ...previous, ...patch });
174
228
  current.runs.set(runKey, next);
229
+ rememberTrustedRecord(current, runKey, next, next);
175
230
  return clone(next);
176
231
  }
177
232
 
178
233
  /** Remove a cached external job. The caller remains responsible for its process and artifacts. */
179
234
  export function unregisterExternalRun(sessionId: string, id: string): boolean {
180
- return registry().runs.delete(key(identity(sessionId, "External run sessionId", EXTERNAL_RUN_LIMITS.maxSessionIdLength), identity(id, "External run id")));
235
+ const current = registry();
236
+ const runKey = key(identity(sessionId, "External run sessionId", EXTERNAL_RUN_LIMITS.maxSessionIdLength), identity(id, "External run id"));
237
+ const deleted = current.runs.delete(runKey);
238
+ if (deleted) trustedRecords(current).delete(runKey);
239
+ return deleted;
181
240
  }
182
241
 
183
242
  function snapshotBytes(runs: readonly ExternalRun[]): number {
@@ -192,15 +251,19 @@ function getErrorMessage(error: unknown): string {
192
251
  export function snapshotExternalRuns(sessionId: string, options: ExternalRunSnapshotOptions = {}): readonly ExternalRun[] {
193
252
  const safeSessionId = identity(sessionId, "External-run snapshot sessionId", EXTERNAL_RUN_LIMITS.maxSessionIdLength);
194
253
  const current = registry();
254
+ const trusted = trustedRecords(current);
255
+ const sessionPrefix = `${safeSessionId}\0`;
195
256
  const runs: ExternalRun[] = [];
196
257
  for (const [cacheKey, value] of current.runs.entries()) {
258
+ if (typeof cacheKey !== "string" || !cacheKey.startsWith(sessionPrefix)) continue;
197
259
  try {
198
- const run = validateRun(value);
260
+ const run = trustedRecordValue(value, trusted.get(cacheKey)) ?? normalizeCachedRecord(current, cacheKey, value);
199
261
  if (run.sessionId === safeSessionId) runs.push(run);
200
262
  } catch (error) {
201
263
  const message = `Malformed cached external run '${cacheKey}': ${getErrorMessage(error)}`;
202
264
  if (!options.ignoreMalformed) throw new Error(message, { cause: error instanceof Error ? error : undefined });
203
265
  current.runs.delete(cacheKey);
266
+ trusted.delete(cacheKey);
204
267
  options.onMalformedRecord?.(message);
205
268
  }
206
269
  }