@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -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 +195 -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 +7 -6
  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 +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -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 +42 -21
  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 +77 -21
  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 +65 -29
  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 +7 -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 +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -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 +204 -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 +718 -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 +489 -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 +1223 -402
  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 +364 -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 +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -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 +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  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 +20 -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/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. 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,11 +1,12 @@
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
+ import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
9
10
 
10
11
  export const RUNTIME_AGENT_REGISTRY_KEY = "pi-subagents.runtime-agents.v1";
11
12
 
@@ -20,18 +21,20 @@ export interface RuntimeAgentDefinition {
20
21
  systemPrompt: string;
21
22
  aliases?: readonly string[];
22
23
  tools?: readonly string[];
24
+ excludeTools?: readonly string[];
25
+ allowNestedSubagents?: boolean;
23
26
  mcpDirectTools?: readonly string[];
24
27
  model?: string;
25
28
  fallbackModels?: readonly string[];
26
29
  thinking?: string | false;
27
30
  systemPromptMode?: "append" | "replace";
28
31
  inheritProjectContext?: boolean;
32
+ inheritGlobalContext?: boolean;
29
33
  inheritSkills?: boolean;
30
34
  defaultContext?: AgentDefaultContext;
31
35
  defaultAsync?: boolean;
32
36
  defaultTimeoutMs?: number;
33
37
  defaultToolTimeoutMs?: number;
34
- defaultTurnBudget?: TurnBudgetConfig;
35
38
  defaultAcceptance?: AcceptanceInput;
36
39
  acceptanceRole?: AcceptanceRole;
37
40
  runner?: AgentRunnerConfig;
@@ -39,6 +42,7 @@ export interface RuntimeAgentDefinition {
39
42
  skillPath?: readonly string[];
40
43
  extensions?: readonly string[];
41
44
  subagentOnlyExtensions?: readonly string[];
45
+ mutationTools?: readonly string[];
42
46
  output?: string;
43
47
  outputMode?: OutputMode;
44
48
  defaultReads?: readonly string[];
@@ -48,6 +52,7 @@ export interface RuntimeAgentDefinition {
48
52
  maxSubagentDepth?: number;
49
53
  completionGuard?: boolean;
50
54
  toolBudget?: ToolBudgetConfig;
55
+ sandbox?: string;
51
56
  permissions?: PermissionRules;
52
57
  }
53
58
 
@@ -133,8 +138,8 @@ function validateStringList(value: unknown, field: string): string[] | undefined
133
138
 
134
139
  function validatePositiveInteger(value: unknown, field: string): number | undefined {
135
140
  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;
141
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw new Error(`${field} must be a positive integer when provided.`);
142
+ return value;
138
143
  }
139
144
 
140
145
  function validateBoolean(value: unknown, field: string): boolean | undefined {
@@ -170,18 +175,15 @@ function validateRunner(value: unknown): AgentRunnerConfig | undefined {
170
175
  if (runner.type !== "external-cli") throw new Error("Runtime agent definition runner.type must be 'pi', 'external-cli', or 'external-job'.");
171
176
  if (typeof runner.command !== "string" || !runner.command.trim()) throw new Error("Runtime agent definition external-cli runner requires a non-empty command string.");
172
177
  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.");
178
+ 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}.`);
179
+ 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
180
  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"]);
181
+ const capabilities = parseExternalCliCapabilityNarrowing(runner.capabilities, "Runtime agent definition external-cli runner capabilities");
182
+ const supported = new Set(["type", "adapter", "command", "args", "promptDelivery", "capabilities"]);
175
183
  const unknown = Object.keys(runner).filter((key) => !supported.has(key));
176
184
  if (unknown.length > 0) throw new Error(`Runtime agent definition external-cli runner has unsupported fields: ${unknown.join(", ")}.`);
177
185
  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;
186
+ 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
187
  }
186
188
 
187
189
  function validateAcceptance(value: unknown): AcceptanceInput | undefined {
@@ -200,11 +202,11 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
200
202
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Runtime agent definition must be an object.");
201
203
  const definition = value as Record<string, unknown>;
202
204
  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",
207
- "maxSubagentDepth", "completionGuard", "toolBudget", "permissions",
205
+ "description", "systemPrompt", "aliases", "tools", "excludeTools", "allowNestedSubagents", "mcpDirectTools", "model", "fallbackModels", "thinking",
206
+ "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "defaultContext", "defaultAsync", "defaultTimeoutMs",
207
+ "defaultToolTimeoutMs", "defaultAcceptance", "acceptanceRole", "runner", "skills", "skillPath",
208
+ "extensions", "subagentOnlyExtensions", "mutationTools", "output", "outputMode", "defaultReads", "defaultProgress", "injectToContext", "interactive",
209
+ "maxSubagentDepth", "completionGuard", "toolBudget", "sandbox", "permissions",
208
210
  ]);
209
211
  const unknown = Object.keys(definition).filter((key) => !supported.has(key));
210
212
  if (unknown.length > 0) throw new Error(`Runtime agent definition has unknown fields: ${unknown.join(", ")}.`);
@@ -220,21 +222,24 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
220
222
  if (outputMode !== undefined && outputMode !== "inline" && outputMode !== "file-only") throw new Error("Runtime agent definition outputMode must be 'inline' or 'file-only'.");
221
223
  const aliases = validateStringList(definition.aliases, "Runtime agent definition aliases");
222
224
  const tools = validateStringList(definition.tools, "Runtime agent definition tools");
225
+ const excludeTools = validateStringList(definition.excludeTools, "Runtime agent definition excludeTools");
226
+ const allowNestedSubagents = validateBoolean(definition.allowNestedSubagents, "Runtime agent definition allowNestedSubagents");
223
227
  const mcpDirectTools = validateStringList(definition.mcpDirectTools, "Runtime agent definition mcpDirectTools");
224
228
  const model = validateOptionalString(definition.model, "Runtime agent definition model");
225
229
  const fallbackModels = validateStringList(definition.fallbackModels, "Runtime agent definition fallbackModels");
226
230
  const inheritProjectContext = validateBoolean(definition.inheritProjectContext, "Runtime agent definition inheritProjectContext");
231
+ const inheritGlobalContext = validateBoolean(definition.inheritGlobalContext, "Runtime agent definition inheritGlobalContext");
227
232
  const inheritSkills = validateBoolean(definition.inheritSkills, "Runtime agent definition inheritSkills");
228
233
  const defaultAsync = validateBoolean(definition.defaultAsync, "Runtime agent definition defaultAsync");
229
234
  const defaultTimeoutMs = validatePositiveInteger(definition.defaultTimeoutMs, "Runtime agent definition defaultTimeoutMs");
230
235
  const defaultToolTimeoutMs = validatePositiveInteger(definition.defaultToolTimeoutMs, "Runtime agent definition defaultToolTimeoutMs");
231
- const defaultTurnBudget = validateTurnBudget(definition.defaultTurnBudget);
232
236
  const defaultAcceptance = validateAcceptance(definition.defaultAcceptance);
233
237
  const runner = validateRunner(definition.runner);
234
238
  const skills = validateStringList(definition.skills, "Runtime agent definition skills");
235
239
  const skillPath = validateStringList(definition.skillPath, "Runtime agent definition skillPath");
236
240
  const extensions = validateStringList(definition.extensions, "Runtime agent definition extensions");
237
241
  const subagentOnlyExtensions = validateStringList(definition.subagentOnlyExtensions, "Runtime agent definition subagentOnlyExtensions");
242
+ const mutationTools = validateStringList(definition.mutationTools, "Runtime agent definition mutationTools");
238
243
  const output = validateOptionalString(definition.output, "Runtime agent definition output");
239
244
  const defaultReads = validateStringList(definition.defaultReads, "Runtime agent definition defaultReads");
240
245
  const defaultProgress = validateBoolean(definition.defaultProgress, "Runtime agent definition defaultProgress");
@@ -243,24 +248,32 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
243
248
  const maxSubagentDepth = validatePositiveInteger(definition.maxSubagentDepth, "Runtime agent definition maxSubagentDepth");
244
249
  const completionGuard = validateBoolean(definition.completionGuard, "Runtime agent definition completionGuard");
245
250
  const toolBudget = validateToolBudget(definition.toolBudget);
251
+ const sandbox = definition.sandbox === undefined
252
+ ? undefined
253
+ : validateSandboxProfileName(definition.sandbox, "Runtime agent definition sandbox");
254
+ if (sandbox && (runner?.type === "external-cli" || runner?.type === "external-job")) {
255
+ throw new Error(`Runtime agent definition runner.type='${runner.type}' cannot use sandbox profiles because it does not run a native Pi child.`);
256
+ }
246
257
  const permissions = validatePermissionRules(definition.permissions, "Runtime agent definition permissions");
247
258
  return {
248
259
  description: validateString(definition.description, "Runtime agent definition description", MAX_DESCRIPTION_LENGTH),
249
260
  systemPrompt: validateString(definition.systemPrompt, "Runtime agent definition systemPrompt", MAX_SYSTEM_PROMPT_LENGTH),
250
261
  ...(aliases ? { aliases } : {}),
251
262
  ...(tools ? { tools } : {}),
263
+ ...(excludeTools ? { excludeTools } : {}),
264
+ ...(allowNestedSubagents !== undefined ? { allowNestedSubagents } : {}),
252
265
  ...(mcpDirectTools ? { mcpDirectTools } : {}),
253
266
  ...(model ? { model } : {}),
254
267
  ...(fallbackModels ? { fallbackModels } : {}),
255
268
  ...(thinking !== undefined ? { thinking: thinking as string | false } : {}),
256
269
  ...(systemPromptMode !== undefined ? { systemPromptMode: systemPromptMode as "append" | "replace" } : {}),
257
270
  ...(inheritProjectContext !== undefined ? { inheritProjectContext } : {}),
271
+ ...(inheritGlobalContext !== undefined ? { inheritGlobalContext } : {}),
258
272
  ...(inheritSkills !== undefined ? { inheritSkills } : {}),
259
273
  ...(defaultContext !== undefined ? { defaultContext: defaultContext as AgentDefaultContext } : {}),
260
274
  ...(defaultAsync !== undefined ? { defaultAsync } : {}),
261
275
  ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
262
276
  ...(defaultToolTimeoutMs !== undefined ? { defaultToolTimeoutMs } : {}),
263
- ...(defaultTurnBudget !== undefined ? { defaultTurnBudget } : {}),
264
277
  ...(defaultAcceptance !== undefined ? { defaultAcceptance } : {}),
265
278
  ...(acceptanceRole !== undefined ? { acceptanceRole: acceptanceRole as AcceptanceRole } : {}),
266
279
  ...(runner !== undefined ? { runner } : {}),
@@ -268,6 +281,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
268
281
  ...(skillPath ? { skillPath } : {}),
269
282
  ...(extensions ? { extensions } : {}),
270
283
  ...(subagentOnlyExtensions ? { subagentOnlyExtensions } : {}),
284
+ ...(mutationTools ? { mutationTools } : {}),
271
285
  ...(output ? { output } : {}),
272
286
  ...(outputMode !== undefined ? { outputMode: outputMode as OutputMode } : {}),
273
287
  ...(defaultReads ? { defaultReads } : {}),
@@ -277,6 +291,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
277
291
  ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
278
292
  ...(completionGuard !== undefined ? { completionGuard } : {}),
279
293
  ...(toolBudget !== undefined ? { toolBudget } : {}),
294
+ ...(sandbox !== undefined ? { sandbox } : {}),
280
295
  ...(permissions !== undefined ? { permissions } : {}),
281
296
  };
282
297
  }
@@ -327,18 +342,20 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
327
342
  ...(aliases ? { aliases } : {}),
328
343
  ...(definition.runner !== undefined ? { runner: definition.runner } : {}),
329
344
  ...(definition.tools !== undefined ? { tools: [...definition.tools] } : {}),
345
+ ...(definition.excludeTools !== undefined ? { excludeTools: [...definition.excludeTools] } : {}),
346
+ ...(definition.allowNestedSubagents !== undefined ? { allowNestedSubagents: definition.allowNestedSubagents } : {}),
330
347
  ...(definition.mcpDirectTools !== undefined ? { mcpDirectTools: [...definition.mcpDirectTools] } : {}),
331
348
  ...(definition.model !== undefined ? { model: definition.model } : {}),
332
349
  ...(definition.fallbackModels !== undefined ? { fallbackModels: [...definition.fallbackModels] } : {}),
333
350
  ...(definition.thinking !== undefined ? { thinking: definition.thinking } : {}),
334
351
  systemPromptMode: definition.systemPromptMode ?? defaultSystemPromptMode(name),
335
352
  inheritProjectContext: definition.inheritProjectContext ?? defaultInheritProjectContext(name),
353
+ inheritGlobalContext: definition.inheritGlobalContext ?? false,
336
354
  inheritSkills: definition.inheritSkills ?? defaultInheritSkills(),
337
355
  ...(definition.defaultContext !== undefined ? { defaultContext: definition.defaultContext } : {}),
338
356
  ...(definition.defaultAsync !== undefined ? { defaultAsync: definition.defaultAsync } : {}),
339
357
  ...(definition.defaultTimeoutMs !== undefined ? { defaultTimeoutMs: definition.defaultTimeoutMs } : {}),
340
358
  ...(definition.defaultToolTimeoutMs !== undefined ? { defaultToolTimeoutMs: definition.defaultToolTimeoutMs } : {}),
341
- ...(definition.defaultTurnBudget !== undefined ? { defaultTurnBudget: definition.defaultTurnBudget } : {}),
342
359
  ...(definition.defaultAcceptance !== undefined ? { defaultAcceptance: definition.defaultAcceptance } : {}),
343
360
  ...(definition.acceptanceRole !== undefined ? { acceptanceRole: definition.acceptanceRole } : {}),
344
361
  systemPrompt: definition.systemPrompt,
@@ -348,6 +365,7 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
348
365
  ...(definition.skillPath !== undefined ? { skillPath: [...definition.skillPath] } : {}),
349
366
  ...(definition.extensions !== undefined ? { extensions: [...definition.extensions] } : {}),
350
367
  ...(definition.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: [...definition.subagentOnlyExtensions] } : {}),
368
+ ...(definition.mutationTools !== undefined ? { mutationTools: [...definition.mutationTools] } : {}),
351
369
  ...(definition.output !== undefined ? { output: definition.output } : {}),
352
370
  ...(definition.outputMode !== undefined ? { outputMode: definition.outputMode } : {}),
353
371
  ...(definition.defaultReads !== undefined ? { defaultReads: [...definition.defaultReads] } : {}),
@@ -357,6 +375,7 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
357
375
  ...(definition.maxSubagentDepth !== undefined ? { maxSubagentDepth: definition.maxSubagentDepth } : {}),
358
376
  ...(definition.completionGuard !== undefined ? { completionGuard: definition.completionGuard } : {}),
359
377
  ...(definition.toolBudget !== undefined ? { toolBudget: definition.toolBudget } : {}),
378
+ ...(definition.sandbox !== undefined ? { sandbox: definition.sandbox } : {}),
360
379
  ...(definition.permissions !== undefined ? { permissions: definition.permissions } : {}),
361
380
  };
362
381
  assertNoIdentityCollisions([agent], `Runtime agent '${name}'`);
@@ -368,6 +387,8 @@ export function registerRuntimeAgent(input: RegisterRuntimeAgentInput): RuntimeA
368
387
  const name = validateString(input.name, "Runtime agent name", MAX_AGENT_NAME_LENGTH);
369
388
  const definition = validateDefinition(input.definition);
370
389
  const agent = toAgentConfig(name, definition);
390
+ const profileError = validateCodeOwnedProfileRunner(agent);
391
+ if (profileError) throw new Error(profileError);
371
392
  assertNoBuiltinCollision(agent);
372
393
  const current = registry();
373
394
  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
  }