@xzzpig/pi-subagents 0.9.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.10.0] - 2026-09-10 (fork release)
4
+
5
+ ### Added
6
+
7
+ - **`sandbox: <profile-name>` for native agents.** Agent frontmatter (or a
8
+ builtin override) may select one named `pi-sandbox` profile from the user's
9
+ global `<agentDir>/sandbox.json`. The selector is a scalar name only: objects,
10
+ empty values, path-like names, and the literal `false` are rejected, and the
11
+ field is refused for `external-cli` and `external-job` runners. The launcher
12
+ resolves and injects the installed `pi-sandbox` extension plus a startup guard
13
+ even when `extensions` is an explicit allowlist; a missing package, unreadable
14
+ manifest, capability-ceiling denial, unknown profile, or failed sandbox
15
+ initialization fails the launch before the child's first model turn.
16
+ - **Startup acknowledgement is verified before the first turn.** The guard
17
+ blocks the child when the profile never acknowledged successful startup, and
18
+ only the validated profile identity is persisted in async status, nested-event,
19
+ and intercom projections. The project trust decision travels with the child as
20
+ a boolean; a project-scoped selector is rejected unless the project is trusted
21
+ and the child cwd matches the trusted project root exactly.
22
+ - **A blocked child reports its real reason.** A startup block publishes its
23
+ failure through the child startup diagnostics channel (including the available
24
+ profile names), so callers see the profile error instead of "Subagent produced
25
+ no output (possible model cold-start or empty response)", and the failure is
26
+ classified as `startupBlocked` rather than a retryable model failure — it no
27
+ longer records a 24-hour model exclusion or triggers pointless model fallback.
28
+
29
+ ### Changed
30
+
31
+ - **Sandbox configuration is never injected into the child.** Only the selected
32
+ profile name, the trust snapshot, the startup acknowledgement channel, and the
33
+ diagnostics path cross the launch boundary, and those keys are restored on the
34
+ host immediately after the child session is created. Launches without a
35
+ `sandbox` selector keep the previous behavior unchanged.
36
+
3
37
  ## [0.9.0] - 2026-09-05 (fork release)
4
38
 
5
39
  ### Changed
package/docs/agents.md CHANGED
@@ -210,7 +210,7 @@ You can override selected agent fields without copying the whole agent. Override
210
210
  }
211
211
  ```
212
212
 
213
- Supported override fields: `description`, `output`, `outputMode`, `defaultReads`, `model`, `defaultProvider`, `fallbackModels`, `thinking`, `systemPromptMode`, `inheritProjectContext`, `inheritGlobalContext`, `inheritSkills`, `defaultContext`, `acceptanceRole`, `disabled`, `skills`, `tools`, and `systemPrompt`.
213
+ Supported override fields: `description`, `output`, `outputMode`, `defaultReads`, `model`, `defaultProvider`, `fallbackModels`, `thinking`, `systemPromptMode`, `inheritProjectContext`, `inheritGlobalContext`, `inheritSkills`, `defaultContext`, `acceptanceRole`, `disabled`, `skills`, `tools`, `sandbox`, and `systemPrompt`.
214
214
 
215
215
  - `description` replaces the discovered description for builtin and custom agents, which lets list output show deployment-specific routing or model metadata.
216
216
  - Use `output: false`, `defaultReads: false`, `defaultContext: false`, or `acceptanceRole: false` to clear an inherited value.
@@ -259,6 +259,7 @@ tools: read, grep, find, ls, bash, mcp:chrome-devtools
259
259
  excludeTools: bash
260
260
  extensions:
261
261
  subagentOnlyExtensions: ./tools/child-only-search.ts
262
+ sandbox: reviewer-strict
262
263
  model: claude-haiku-4-5
263
264
  fallbackModels: openai-codex/gpt-5.6-luna:low, anthropic/claude-sonnet-4
264
265
  thinking: high
@@ -308,6 +309,7 @@ Field notes:
308
309
  | `allowNestedSubagents` | Set `true` to authorize the child-safe nested `subagent` runtime without making omitted `tools` an allowlist. Inherited depth and capability ceilings remain authoritative. |
309
310
  | `extensions` | Omitted means a background child loads the parent's ambient extensions; empty means no ambient extensions; list values load exactly those extensions. Foreground children never load ambient extensions, so for them only listed values apply. |
310
311
  | `subagentOnlyExtensions` | Extension paths loaded only in this agent's child sessions. Tools registered there are unavailable to the main agent unless also installed through normal Pi extension configuration. |
312
+ | `sandbox` | Optional named `pi-sandbox` profile for a native Pi child. It must be a non-empty safe name defined in the user's global `<agentDir>/sandbox.json`; it is a selector only, never an inline network or filesystem policy. |
311
313
  | `model` | Default model. Bare ids prefer the current provider when possible, then unique registry matches. |
312
314
  | `fallbackModels` | Ordered backup models for provider/model failures such as quota, auth, provider-reported timeout, or unavailable model. Expiration of the run-level `timeoutMs` / `maxRuntimeMs` deadline is terminal and does not trigger fallback. Ordinary task failures do not trigger fallback. |
313
315
  | `thinking` | Appended as a `:level` suffix at runtime unless a suffix is already present. |
@@ -333,6 +335,48 @@ Field notes:
333
335
  | `injectToContext` | Advertise this agent in the parent system prompt at session start so the main agent can select it without calling `{ action: "list" }` first. See [Context injection](#context-injection). |
334
336
  | `memory` | Opt-in role-specific persistent memory. See below. |
335
337
 
338
+ ### Sandbox profiles
339
+
340
+ Use `sandbox: <profile-name>` only for a native Pi child. The profile is resolved
341
+ from the global `pi-sandbox` configuration, never from an agent file or a project
342
+ profile registry:
343
+
344
+ ```yaml
345
+ ---
346
+ name: security-reviewer
347
+ description: Review changes with a constrained filesystem and no network
348
+ sandbox: reviewer-strict
349
+ extensions: ./review-tools.ts
350
+ ---
351
+
352
+ Review the requested change.
353
+ ```
354
+
355
+ `pi-subagents` validates the scalar name and passes only that name to the child.
356
+ It automatically resolves and injects the installed `pi-sandbox` extension and a
357
+ startup guard even when `extensions` is an explicit allowlist; an explicit empty
358
+ allowlist does not remove these required runtime extensions. The guard requires
359
+ `pi-sandbox` to acknowledge successful profile initialization before the child
360
+ can enter its first model turn. The launch fails before the model's first turn when the package or manifest is missing, a capability ceiling denies child
361
+ extensions, the profile cannot be loaded, or sandbox initialization fails. A
362
+ blocked child publishes that reason through its startup diagnostics, so the
363
+ caller sees the profile error (and the available profile names) instead of a
364
+ generic empty-output message; a startup block is never recorded as a model
365
+ failure and never excludes the model from later runs.
366
+
367
+ The field is rejected for `external-cli` and `external-job` runners because they
368
+ do not host a Pi child extension. It also cannot be an object, `false`, an empty
369
+ value, or an inline allow/deny policy. Define the actual network and filesystem
370
+ rules in global `pi-sandbox` `profiles` instead.
371
+
372
+ A profile chosen by a project-scoped agent or project override is used only when
373
+ the host marks that project trusted. Otherwise the launch reports an actionable
374
+ trust error. In a headless child, accesses outside the profile's preconfigured
375
+ network/read/write rules are blocked; pi-sandbox does not use Permission System
376
+ or supervisor forwarding to ask the parent for an approval. See
377
+ [`pi-sandbox`'s README](https://github.com/xzzpig/pi-extensions/tree/main/packages/pi-sandbox#named-profiles-for-subagents)
378
+ for profile inheritance and merge rules.
379
+
336
380
  ## Context injection
337
381
 
338
382
  By default the parent agent learns which agents exist only by calling `subagent({ action: "list" })`. Context injection pre-declares selected agents in the parent system prompt through a compact `<available_subagents>` block, so routing decisions can happen without a discovery round trip.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xzzpig/pi-subagents",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
5
5
  "author": "Nico Bailon",
6
6
  "license": "MIT",
@@ -109,8 +109,8 @@
109
109
  "scripts": {
110
110
  "typecheck": "tsc --noEmit",
111
111
  "test": "npm run test:unit",
112
- "test:unit": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL node --experimental-strip-types --import ./test/support/isolated-temp-root.mjs --test test/unit/*.test.ts",
113
- "test:integration": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL node --experimental-strip-types --import ./test/support/register-loader.mjs --test test/integration/*.test.ts",
112
+ "test:unit": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --import ./test/support/isolated-temp-root.mjs --test test/unit/*.test.ts",
113
+ "test:integration": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --import ./test/support/register-loader.mjs --test test/integration/*.test.ts",
114
114
  "test:all": "npm run test:unit && npm run test:integration"
115
115
  }
116
116
  }
@@ -41,6 +41,7 @@ import { previewDisplayText } from "../shared/display-text.ts";
41
41
  import { capabilityCeilingAgentRestrictionSources, isAgentAllowedByCapabilityCeiling, resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
42
42
  import { mergeRuntimeAgents, type RuntimeAgentOwner } from "./runtime-agent-registry.ts";
43
43
  import { listExternalJobProviders } from "../api/external-job-provider.ts";
44
+ import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
44
45
 
45
46
  export const AGENT_MANAGEMENT_API_VERSION = 1 as const;
46
47
 
@@ -98,7 +99,7 @@ export type EjectAgentDefinitionResult =
98
99
 
99
100
  type ManagementAction = "list" | "get" | "models" | "create" | "update" | "delete" | "eject" | "disable" | "enable" | "reset";
100
101
  type ManagementScope = "user" | "project";
101
- type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string; runtimeAgentOwner?: RuntimeAgentOwner };
102
+ type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { isProjectTrusted?: ExtensionContext["isProjectTrusted"]; model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string; runtimeAgentOwner?: RuntimeAgentOwner };
102
103
 
103
104
  interface ManagementParams {
104
105
  action?: string;
@@ -451,6 +452,7 @@ export function preservedAgentFrontmatterFields(agent: AgentConfig, cfg: Record<
451
452
  if (cfg.completionGuard === true) fields.add("completionGuard");
452
453
  }
453
454
  if (hasKey(cfg, "toolBudget")) changed("toolBudget");
455
+ if (hasKey(cfg, "sandbox")) changed("sandbox");
454
456
 
455
457
  return fields;
456
458
  }
@@ -682,6 +684,14 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
682
684
  target.toolBudget = cfg.toolBudget as ToolBudgetConfig;
683
685
  }
684
686
  }
687
+ if (hasKey(cfg, "sandbox")) {
688
+ if (typeof cfg.sandbox !== "string") return "config.sandbox must be a non-empty sandbox profile name when provided.";
689
+ try {
690
+ target.sandbox = validateSandboxProfileName(cfg.sandbox, "config.sandbox");
691
+ } catch (error) {
692
+ return error instanceof Error ? error.message : String(error);
693
+ }
694
+ }
685
695
  if (target.runner?.type === "external-cli" || target.runner?.type === "external-job") {
686
696
  const unsupported = [
687
697
  target.tools?.length || target.mcpDirectTools?.length ? "tools" : undefined,
@@ -696,6 +706,7 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
696
706
  target.maxSubagentDepth !== undefined ? "maxSubagentDepth" : undefined,
697
707
  target.completionGuard !== undefined ? "completionGuard" : undefined,
698
708
  target.toolBudget ? "toolBudget" : undefined,
709
+ target.sandbox ? "sandbox" : undefined,
699
710
  ].filter((field): field is string => Boolean(field));
700
711
  if (unsupported.length > 0) return `config.runner type '${target.runner.type}' does not support Pi-only fields: ${unsupported.join(", ")}.`;
701
712
  }
@@ -996,6 +1007,7 @@ function formatAgentDetail(agent: AgentConfig): string {
996
1007
  if (agent.maxSubagentDepth !== undefined) lines.push(`Max subagent depth: ${agent.maxSubagentDepth}`);
997
1008
  if (agent.completionGuard === false) lines.push("Completion guard: false");
998
1009
  if (agent.toolBudget) lines.push(`Tool budget: ${JSON.stringify(agent.toolBudget)}`);
1010
+ if (agent.sandbox) lines.push(`Sandbox profile: ${agent.sandbox}`);
999
1011
  if (agent.memory) lines.push(`Memory: ${agent.memory.scope} scope, path: ${agent.memory.path}`);
1000
1012
  if (agent.systemPrompt.trim()) lines.push("", "System Prompt:", agent.systemPrompt);
1001
1013
  return lines.join("\n");
@@ -1423,6 +1435,7 @@ function validateEjectedAgentLaunchPreflight(agent: AgentConfig, cwd: string): s
1423
1435
  cwd,
1424
1436
  requireReadTool: resolvedSkills.resolved.length > 0,
1425
1437
  agentName: agent.name,
1438
+ sandbox: agent.sandbox,
1426
1439
  });
1427
1440
  } catch (error) {
1428
1441
  return error instanceof Error ? error.message : String(error);
@@ -40,6 +40,7 @@ export const KNOWN_FIELDS = new Set([
40
40
  "maxSubagentDepth",
41
41
  "completionGuard",
42
42
  "toolBudget",
43
+ "sandbox",
43
44
  "permission",
44
45
  "permissions",
45
46
  "memory",
@@ -145,6 +146,7 @@ export function serializeAgent(config: AgentConfig, options: SerializeAgentOptio
145
146
  if (config.toolBudget || preserve("toolBudget")) {
146
147
  lines.push(`toolBudget: ${config.toolBudget ? JSON.stringify(config.toolBudget) : ""}`);
147
148
  }
149
+ if (config.sandbox) lines.push(`sandbox: ${config.sandbox}`);
148
150
  if (config.permissions || preserve("permission", "permissions")) {
149
151
  const key = preserve("permission") && !preserve("permissions") ? "permission" : "permissions";
150
152
  lines.push(`${key}:`);
@@ -24,6 +24,7 @@ import { parseMemoryFrontmatter } from "./agent-memory.ts";
24
24
  import { validateAcceptanceInput } from "../runs/shared/acceptance.ts";
25
25
  import { validatePermissionRules, type PermissionRules } from "../runs/shared/permissions.ts";
26
26
  import { parseThinkingLevel, type ThinkingLevel } from "../shared/thinking-ceiling.ts";
27
+ import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
27
28
 
28
29
  export type AgentScope = "user" | "project" | "both";
29
30
 
@@ -79,6 +80,7 @@ export interface BuiltinAgentOverrideBase {
79
80
  mutationTools?: string[];
80
81
  completionGuard?: boolean;
81
82
  toolBudget?: ToolBudgetConfig;
83
+ sandbox?: string;
82
84
  }
83
85
 
84
86
  interface BuiltinAgentOverrideConfig {
@@ -108,6 +110,7 @@ interface BuiltinAgentOverrideConfig {
108
110
  mutationTools?: string[] | false;
109
111
  completionGuard?: boolean;
110
112
  toolBudget?: ToolBudgetConfig | false;
113
+ sandbox?: string;
111
114
  }
112
115
 
113
116
  interface BuiltinAgentOverrideInfo {
@@ -174,6 +177,7 @@ export interface AgentConfig {
174
177
  maxSubagentDepth?: number;
175
178
  completionGuard?: boolean;
176
179
  toolBudget?: ToolBudgetConfig;
180
+ sandbox?: string;
177
181
  permissions?: PermissionRules;
178
182
  memory?: AgentMemoryConfig;
179
183
  disabled?: boolean;
@@ -788,6 +792,7 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
788
792
  ...(agent.mutationTools ? { mutationTools: [...agent.mutationTools] } : {}),
789
793
  ...(agent.completionGuard !== undefined ? { completionGuard: agent.completionGuard } : {}),
790
794
  ...(agent.toolBudget !== undefined ? { toolBudget: agent.toolBudget } : {}),
795
+ ...(agent.sandbox !== undefined ? { sandbox: agent.sandbox } : {}),
791
796
  };
792
797
  }
793
798
 
@@ -821,6 +826,7 @@ function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentO
821
826
  ...(override.mutationTools !== undefined ? { mutationTools: override.mutationTools === false ? false : [...override.mutationTools] } : {}),
822
827
  ...(override.completionGuard !== undefined ? { completionGuard: override.completionGuard } : {}),
823
828
  ...(override.toolBudget !== undefined ? { toolBudget: override.toolBudget === false ? false : { ...override.toolBudget, ...(Array.isArray(override.toolBudget.block) ? { block: [...override.toolBudget.block] } : {}) } } : {}),
829
+ ...(override.sandbox !== undefined ? { sandbox: override.sandbox } : {}),
824
830
  };
825
831
  }
826
832
 
@@ -1085,6 +1091,10 @@ function parseBuiltinOverrideEntry(
1085
1091
  }
1086
1092
  }
1087
1093
 
1094
+ if ("sandbox" in input) {
1095
+ override.sandbox = validateSandboxProfileName(input.sandbox, `Builtin override '${name}' in '${filePath}' sandbox`);
1096
+ }
1097
+
1088
1098
  if ("systemPrompt" in input) {
1089
1099
  if (typeof input.systemPrompt === "string") override.systemPrompt = input.systemPrompt;
1090
1100
  else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'systemPrompt'; expected a string.`);
@@ -1431,6 +1441,7 @@ function applyBuiltinOverride(
1431
1441
  if (override.mutationTools !== undefined) { if (override.mutationTools === false) delete next.mutationTools; else next.mutationTools = [...override.mutationTools]; }
1432
1442
  if (override.completionGuard !== undefined) next.completionGuard = override.completionGuard;
1433
1443
  if (override.toolBudget !== undefined) { if (override.toolBudget === false) delete next.toolBudget; else next.toolBudget = override.toolBudget; }
1444
+ if (override.sandbox !== undefined) next.sandbox = override.sandbox;
1434
1445
 
1435
1446
  return next;
1436
1447
  }
@@ -1532,7 +1543,7 @@ function applyCustomAgentOverrides(
1532
1543
 
1533
1544
  export function buildBuiltinOverrideConfig(
1534
1545
  base: BuiltinAgentOverrideBase,
1535
- draft: Pick<AgentConfig, "model" | "modelProvider" | "fallbackModels" | "fast" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritGlobalContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "allowNestedSubagents" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "mutationTools" | "completionGuard" | "toolBudget"> & Partial<Pick<AgentConfig, "description" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
1546
+ draft: Pick<AgentConfig, "model" | "modelProvider" | "fallbackModels" | "fast" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritGlobalContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "allowNestedSubagents" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "mutationTools" | "completionGuard" | "toolBudget" | "sandbox"> & Partial<Pick<AgentConfig, "description" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
1536
1547
  ): BuiltinAgentOverrideConfig | undefined {
1537
1548
  const override: BuiltinAgentOverrideConfig = {};
1538
1549
 
@@ -1572,6 +1583,7 @@ export function buildBuiltinOverrideConfig(
1572
1583
  override.completionGuard = draft.completionGuard !== false;
1573
1584
  }
1574
1585
  if (JSON.stringify(draft.toolBudget) !== JSON.stringify(base.toolBudget)) override.toolBudget = draft.toolBudget ?? false;
1586
+ if (draft.sandbox !== undefined && draft.sandbox !== base.sandbox) override.sandbox = draft.sandbox;
1575
1587
 
1576
1588
  return Object.keys(override).length > 0 ? override : undefined;
1577
1589
  }
@@ -1926,7 +1938,7 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
1926
1938
 
1927
1939
  function validateExternalRunnerProfile(frontmatter: Record<string, string>, agentName: string, runner: AgentRunnerConfig | undefined): void {
1928
1940
  if (runner?.type !== "external-cli" && runner?.type !== "external-job") return;
1929
- const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "permission", "permissions"]
1941
+ const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "sandbox", "permission", "permissions"]
1930
1942
  .filter((field) => frontmatter[field] !== undefined);
1931
1943
  if (unsupported.length > 0) {
1932
1944
  throw new Error(`Agent '${agentName}' uses runner.type='${runner.type}' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
@@ -2094,6 +2106,9 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2094
2106
  }
2095
2107
 
2096
2108
  const parsedMaxSubagentDepth = Number(frontmatter.maxSubagentDepth);
2109
+ const sandbox = frontmatter.sandbox !== undefined
2110
+ ? validateSandboxProfileName(frontmatter.sandbox, `Agent '${localName}' sandbox`)
2111
+ : undefined;
2097
2112
  if (frontmatter.permission !== undefined && frontmatter.permissions !== undefined) {
2098
2113
  throw new Error(`Agent '${localName}' cannot declare both permission and permissions frontmatter.`);
2099
2114
  }
@@ -2165,6 +2180,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2165
2180
  ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
2166
2181
  ...(completionGuard !== undefined ? { completionGuard } : {}),
2167
2182
  ...(toolBudget !== undefined ? { toolBudget } : {}),
2183
+ ...(sandbox !== undefined ? { sandbox } : {}),
2168
2184
  ...(permissions !== undefined ? { permissions } : {}),
2169
2185
  ...(memory !== undefined ? { memory } : {}),
2170
2186
  ...(Object.keys(extraFields).length > 0 ? { extraFields } : {}),
@@ -6,6 +6,7 @@ import { validatePermissionRules, type PermissionRules } from "../runs/shared/pe
6
6
  import { validateToolBudgetConfig } from "../runs/shared/tool-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
 
@@ -51,6 +52,7 @@ export interface RuntimeAgentDefinition {
51
52
  maxSubagentDepth?: number;
52
53
  completionGuard?: boolean;
53
54
  toolBudget?: ToolBudgetConfig;
55
+ sandbox?: string;
54
56
  permissions?: PermissionRules;
55
57
  }
56
58
 
@@ -204,7 +206,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
204
206
  "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "defaultContext", "defaultAsync", "defaultTimeoutMs",
205
207
  "defaultToolTimeoutMs", "defaultAcceptance", "acceptanceRole", "runner", "skills", "skillPath",
206
208
  "extensions", "subagentOnlyExtensions", "mutationTools", "output", "outputMode", "defaultReads", "defaultProgress", "injectToContext", "interactive",
207
- "maxSubagentDepth", "completionGuard", "toolBudget", "permissions",
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(", ")}.`);
@@ -246,6 +248,12 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
246
248
  const maxSubagentDepth = validatePositiveInteger(definition.maxSubagentDepth, "Runtime agent definition maxSubagentDepth");
247
249
  const completionGuard = validateBoolean(definition.completionGuard, "Runtime agent definition completionGuard");
248
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
+ }
249
257
  const permissions = validatePermissionRules(definition.permissions, "Runtime agent definition permissions");
250
258
  return {
251
259
  description: validateString(definition.description, "Runtime agent definition description", MAX_DESCRIPTION_LENGTH),
@@ -283,6 +291,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
283
291
  ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
284
292
  ...(completionGuard !== undefined ? { completionGuard } : {}),
285
293
  ...(toolBudget !== undefined ? { toolBudget } : {}),
294
+ ...(sandbox !== undefined ? { sandbox } : {}),
286
295
  ...(permissions !== undefined ? { permissions } : {}),
287
296
  };
288
297
  }
@@ -366,6 +375,7 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
366
375
  ...(definition.maxSubagentDepth !== undefined ? { maxSubagentDepth: definition.maxSubagentDepth } : {}),
367
376
  ...(definition.completionGuard !== undefined ? { completionGuard: definition.completionGuard } : {}),
368
377
  ...(definition.toolBudget !== undefined ? { toolBudget: definition.toolBudget } : {}),
378
+ ...(definition.sandbox !== undefined ? { sandbox: definition.sandbox } : {}),
369
379
  ...(definition.permissions !== undefined ? { permissions: definition.permissions } : {}),
370
380
  };
371
381
  assertNoIdentityCollisions([agent], `Runtime agent '${name}'`);
@@ -38,7 +38,9 @@ export type SubagentLaunchContractReasonCode =
38
38
  | "unsupported_mode"
39
39
  | "restricted_agent"
40
40
  | "thinking_ceiling"
41
- | "invalid_extension_bindings";
41
+ | "invalid_extension_bindings"
42
+ | "untrusted_project"
43
+ | "sandbox_unavailable";
42
44
 
43
45
  export type SubagentLaunchContractDiagnosticCode = SubagentLaunchContractReasonCode | "host_required" | "snapshot_warning" | "workspace_scope_authority";
44
46
 
@@ -79,6 +81,10 @@ export interface SubagentLaunchContractInput {
79
81
  nestedRootRunId?: string;
80
82
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
81
83
  inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
84
+ /** Host-affirmed trust state for a project-scoped profile selection. */
85
+ projectTrusted?: boolean;
86
+ /** Exact trusted project cwd. When omitted, an affirmative trust assertion applies only to `cwd`. */
87
+ trustedProjectCwd?: string;
82
88
  }
83
89
 
84
90
  export interface SubagentLaunchContractAgentCandidate {
@@ -155,6 +161,7 @@ export interface SubagentLaunchContract {
155
161
  modelCandidates: string[];
156
162
  thinking?: string;
157
163
  thinkingCeiling?: ThinkingLevel;
164
+ sandbox?: string;
158
165
  systemPromptMode: AgentConfig["systemPromptMode"];
159
166
  inheritProjectContext: boolean;
160
167
  inheritGlobalContext: boolean;
@@ -280,6 +287,21 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
280
287
  return { ok: false, code: "missing_agent", message: formatUnknownAgentError(input.agent, unknownAgentDiagnosticContext(discovered)), diagnostics };
281
288
  }
282
289
  const agent = resolvedAgent.agent;
290
+ const trustedProjectCwd = input.projectTrusted === true
291
+ ? path.resolve(input.trustedProjectCwd ?? effectiveCwd)
292
+ : undefined;
293
+ if (agent.sandbox && (agent.source === "project" || agent.override?.scope === "project") && input.projectTrusted !== true) {
294
+ const message = `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
295
+ return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
296
+ }
297
+ if (agent.sandbox && (agent.source === "project" || agent.override?.scope === "project") && trustedProjectCwd !== effectiveCwd) {
298
+ const message = `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but cwd '${effectiveCwd}' does not match trusted project cwd '${trustedProjectCwd}'. Launch from the trusted project cwd and retry.`;
299
+ return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
300
+ }
301
+ if (agent.sandbox && (agent.runner?.type === "external-cli" || agent.runner?.type === "external-job")) {
302
+ const message = `Agent '${agent.name}' requests sandbox profile '${agent.sandbox}', but runner.type='${agent.runner.type}' cannot load the native pi-sandbox extension.`;
303
+ return { ok: false, code: "unsupported_mode", message, diagnostics: [{ code: "unsupported_mode", severity: "error", message }] };
304
+ }
283
305
  let extensionBindings: ExtensionBindings | undefined;
284
306
  try {
285
307
  extensionBindings = normalizeExtensionBindings(input.extensionBindings)?.value;
@@ -374,11 +396,13 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
374
396
  capabilityCeiling: effectiveCapabilityCeiling,
375
397
  agentName: agent.name,
376
398
  permissionRules,
399
+ sandbox: agent.sandbox,
377
400
  });
378
401
  } catch (error) {
379
402
  const message = error instanceof Error ? error.message : String(error);
380
- diagnostics.push({ code: "denied_required_tool", severity: "error", message });
381
- return { ok: false, code: "denied_required_tool", message, diagnostics };
403
+ const code: SubagentLaunchContractReasonCode = agent.sandbox ? "sandbox_unavailable" : "denied_required_tool";
404
+ diagnostics.push({ code, severity: "error", message });
405
+ return { ok: false, code, message, diagnostics };
382
406
  }
383
407
  const artifactsEnabled = input.artifacts !== false;
384
408
  const artifactsDir = artifactsEnabled ? getArtifactsDir(input.parentSessionFile ?? null, effectiveCwd, input.artifactDir) : undefined;
@@ -428,6 +452,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
428
452
  modelCandidates,
429
453
  ...(resolveEffectiveThinking(model, effectiveThinkingConfig) ? { thinking: resolveEffectiveThinking(model, effectiveThinkingConfig) } : {}),
430
454
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
455
+ ...(agent.sandbox ? { sandbox: agent.sandbox } : {}),
431
456
  systemPromptMode: agent.systemPromptMode,
432
457
  inheritProjectContext: agent.inheritProjectContext,
433
458
  inheritGlobalContext: agent.inheritGlobalContext,
@@ -489,6 +514,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
489
514
  inheritProjectContext: agent.inheritProjectContext,
490
515
  inheritGlobalContext: agent.inheritGlobalContext,
491
516
  inheritSkills: agent.inheritSkills,
517
+ sandbox: agent.sandbox,
492
518
  skills: requestedSkills,
493
519
  tools: toolPlan.effectiveToolAllowlist,
494
520
  ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
@@ -4,25 +4,25 @@
4
4
 
5
5
  import { Type } from "typebox";
6
6
 
7
- function keepTopLevelParameterDescriptions<T>(schema: T): T {
8
- return pruneNestedDescriptions(schema, []) as T;
7
+ function keepTopLevelParameterDescriptions<T extends object>(schema: T): T {
8
+ return pruneNestedDescriptions(schema, []);
9
9
  }
10
10
 
11
- function pruneNestedDescriptions(value: unknown, path: string[]): unknown {
12
- if (!value || typeof value !== "object") return value;
13
-
14
- const result = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
11
+ function pruneNestedDescriptions<T extends object>(value: T, path: string[]): T {
12
+ const result: object = Array.isArray(value)
13
+ ? []
14
+ : Object.create(Object.getPrototypeOf(value));
15
15
  for (const key of Reflect.ownKeys(value)) {
16
16
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
17
17
  if (!descriptor) continue;
18
18
  if (key === "description" && !isTopLevelParameterDescription(path)) continue;
19
- if ("value" in descriptor) {
19
+ if ("value" in descriptor && descriptor.value && typeof descriptor.value === "object") {
20
20
  const nextPath = typeof key === "string" ? [...path, key] : path;
21
21
  descriptor.value = pruneNestedDescriptions(descriptor.value, nextPath);
22
22
  }
23
23
  Object.defineProperty(result, key, descriptor);
24
24
  }
25
- return result;
25
+ return result as T;
26
26
  }
27
27
 
28
28
  function isTopLevelParameterDescription(path: string[]): boolean {
@@ -116,6 +116,7 @@ function compactNestedRun(run: NestedRunSummary | PublicNestedRunSummary, depth
116
116
  ...(run.agents?.length ? { agents: run.agents.slice(0, 12) } : {}),
117
117
  ...(run.model ? { model: run.model } : {}),
118
118
  ...(run.thinking ? { thinking: run.thinking } : {}),
119
+ ...(run.sandbox ? { sandbox: run.sandbox } : {}),
119
120
  ...(run.currentStep !== undefined ? { currentStep: run.currentStep } : {}),
120
121
  ...(run.chainStepCount !== undefined ? { chainStepCount: run.chainStepCount } : {}),
121
122
  ...(run.parallelGroups?.length ? { parallelGroups: run.parallelGroups.slice(0, 8) } : {}),
@@ -137,7 +138,9 @@ function compactNestedRun(run: NestedRunSummary | PublicNestedRunSummary, depth
137
138
  status: step.status,
138
139
  ...(step.model ? { model: step.model } : {}),
139
140
  ...(step.thinking ? { thinking: step.thinking } : {}),
141
+ ...(step.sandbox ? { sandbox: step.sandbox } : {}),
140
142
  ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
143
+
141
144
  ...(step.activityState ? { activityState: step.activityState } : {}),
142
145
  ...(step.lastActivityAt !== undefined ? { lastActivityAt: step.lastActivityAt } : {}),
143
146
  ...(step.currentTool ? { currentTool: step.currentTool } : {}),
@@ -321,6 +324,8 @@ export async function deliverSubagentResultIntercomEvent(
321
324
  payload: SubagentResultIntercomPayload,
322
325
  timeoutMs = 500,
323
326
  ): Promise<boolean> {
327
+ // SAFETY: SubagentResultIntercomPayload is a plain object assembled above from
328
+ // bounded public result fields; the event transport accepts generic JSON-like metadata.
324
329
  return deliverSubagentIntercomMessageEvent(events, payload.to, payload.message, timeoutMs, payload as unknown as Record<string, unknown>);
325
330
  }
326
331