@xzzpig/pi-subagents 0.11.0 → 0.12.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,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.12.0] - 2026-09-11
4
+
5
+ ### Added
6
+
7
+ - **`permission-profile` agent frontmatter.** A custom agent can select a named `pi-permission-system` permission profile (global-only `profiles` registry) with `permission-profile: <name>` — a validated scalar selector, never an inline policy. The field is serialized, round-tripped through eject/settings overrides, and propagated through foreground/background/async/workflow launches, recovery descriptors, and status projections alongside the sandbox profile.
8
+ - **Transient profile channel.** When the field is set, the child receives the bare validated name via the transient `PI_SUBAGENT_PERMISSION_PROFILE` env var and `pi-subagents` injects the installed `pi-permission-system` extension into the child launch even under an explicit `extensions` allowlist, so the child's permission system applies the selected profile. Launch fails closed when the package is missing, a capability ceiling denies child extensions, or the runner is not a native Pi child (`external-cli`/`external-job` reject the field).
9
+
3
10
  ## [0.11.0] - 2026-09-11
4
11
 
5
12
  ### Added
package/docs/agents.md CHANGED
@@ -260,6 +260,7 @@ excludeTools: bash
260
260
  extensions:
261
261
  subagentOnlyExtensions: ./tools/child-only-search.ts
262
262
  sandbox: reviewer-strict
263
+ permission-profile: reviewer
263
264
  model: claude-haiku-4-5
264
265
  fallbackModels: openai-codex/gpt-5.6-luna:low, anthropic/claude-sonnet-4
265
266
  thinking: high
@@ -310,6 +311,7 @@ Field notes:
310
311
  | `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. |
311
312
  | `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
313
  | `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. |
314
+ | `permission-profile` | Optional named permission profile for a native Pi child. The name must be a non-empty safe identifier defined in the global `pi-permission-system` config's `profiles` registry; only the validated name is passed to the child. See below. |
313
315
  | `model` | Default model. Bare ids prefer the current provider when possible, then unique registry matches. |
314
316
  | `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. |
315
317
  | `thinking` | Appended as a `:level` suffix at runtime unless a suffix is already present. |
@@ -377,6 +379,50 @@ or supervisor forwarding to ask the parent for an approval. See
377
379
  [`pi-sandbox`'s README](https://github.com/xzzpig/pi-extensions/tree/main/packages/pi-sandbox#named-profiles-for-subagents)
378
380
  for profile inheritance and merge rules.
379
381
 
382
+ ### Permission profiles
383
+
384
+ Use `permission-profile: <name>` to select a named policy profile from the
385
+ **global-only** `profiles` registry in `pi-permission-system`'s config
386
+ (`<agentDir>/extensions/pi-permission-system/config.json`). It is a selector
387
+ only — the actual rules (tool scalars, `bash`/`mcp`/`skill`/`external_directory`
388
+ pattern maps, `'*'` fallback) live in that registry and always resolve from the
389
+ child's own global config:
390
+
391
+ ```yaml
392
+ ---
393
+ name: reviewer
394
+ description: Review changes without write access
395
+ permission-profile: reviewer
396
+ ---
397
+ Review the requested change and report findings.
398
+ ```
399
+
400
+ `pi-subagents` validates the scalar name (same grammar as sandbox profiles),
401
+ passes only that name to the child via the transient
402
+ `PI_SUBAGENT_PERMISSION_PROFILE` environment variable, and injects the
403
+ installed `pi-permission-system` extension into the child launch even when
404
+ `extensions` is an explicit allowlist, so the child's permission system applies
405
+ the selected profile. The env channel carries a bare validated name — raw
406
+ policy is never transmitted — and the rules are always read from the child's
407
+ own global config, so the profile means the same policy regardless of which
408
+ host launches the agent. Selection precedence inside the permission system is
409
+ env > project agent file > global agent file.
410
+
411
+ The launch fails closed when a profile is declared but `pi-permission-system`
412
+ is not installed, when a capability ceiling denies child extensions, or when
413
+ the runner is not a native Pi child (the field is rejected for `external-cli`
414
+ and `external-job` runners). At runtime, selecting an unknown profile or an
415
+ empty ruleset clamps that agent's `allow` rules to `ask` with an explicit
416
+ `Permission profile '<name>' could not be resolved` diagnostic — it never
417
+ silently degrades to the unselected baseline. An agent without the field keeps
418
+ its pre-change behavior exactly.
419
+
420
+ The profile merges between the project config and the agent's own `permission:`
421
+ block: patterns the profile does not mention keep the lower scopes' rules
422
+ (global denies survive), and `permission:` overrides the profile per pattern.
423
+ A profile selected by a **project** agent file participates only when the host
424
+ marks that project trusted.
425
+
380
426
  ## Context injection
381
427
 
382
428
  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.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
5
5
  "author": "Nico Bailon",
6
6
  "license": "MIT",
@@ -42,6 +42,7 @@ import { capabilityCeilingAgentRestrictionSources, isAgentAllowedByCapabilityCei
42
42
  import { mergeRuntimeAgents, type RuntimeAgentOwner } from "./runtime-agent-registry.ts";
43
43
  import { listExternalJobProviders } from "../api/external-job-provider.ts";
44
44
  import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
45
+ import { validatePermissionProfileName } from "../shared/permission-profile.ts";
45
46
 
46
47
  export const AGENT_MANAGEMENT_API_VERSION = 1 as const;
47
48
 
@@ -114,7 +115,11 @@ function result(text: string, isError = false, details?: Partial<Details>): Agen
114
115
  }
115
116
 
116
117
  function jsonDetails<T>(value: T): T {
117
- return JSON.parse(JSON.stringify(value)) as T;
118
+ try {
119
+ return JSON.parse(JSON.stringify(value)) as T;
120
+ } catch (error) {
121
+ throw new Error(`Failed to serialize agent management details: ${error instanceof Error ? error.message : String(error)}`);
122
+ }
118
123
  }
119
124
 
120
125
  function presentDetails<T extends Record<string, unknown>>(value: T): T | undefined {
@@ -453,6 +458,7 @@ export function preservedAgentFrontmatterFields(agent: AgentConfig, cfg: Record<
453
458
  }
454
459
  if (hasKey(cfg, "toolBudget")) changed("toolBudget");
455
460
  if (hasKey(cfg, "sandbox")) changed("sandbox");
461
+ if (hasKey(cfg, "permissionProfile")) changed("permission-profile");
456
462
 
457
463
  return fields;
458
464
  }
@@ -692,6 +698,14 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
692
698
  return error instanceof Error ? error.message : String(error);
693
699
  }
694
700
  }
701
+ if (hasKey(cfg, "permissionProfile")) {
702
+ if (typeof cfg.permissionProfile !== "string") return "config.permissionProfile must be a non-empty permission profile name when provided.";
703
+ try {
704
+ target.permissionProfile = validatePermissionProfileName(cfg.permissionProfile, "config.permissionProfile");
705
+ } catch (error) {
706
+ return error instanceof Error ? error.message : String(error);
707
+ }
708
+ }
695
709
  if (target.runner?.type === "external-cli" || target.runner?.type === "external-job") {
696
710
  const unsupported = [
697
711
  target.tools?.length || target.mcpDirectTools?.length ? "tools" : undefined,
@@ -707,6 +721,7 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
707
721
  target.completionGuard !== undefined ? "completionGuard" : undefined,
708
722
  target.toolBudget ? "toolBudget" : undefined,
709
723
  target.sandbox ? "sandbox" : undefined,
724
+ target.permissionProfile ? "permissionProfile" : undefined,
710
725
  ].filter((field): field is string => Boolean(field));
711
726
  if (unsupported.length > 0) return `config.runner type '${target.runner.type}' does not support Pi-only fields: ${unsupported.join(", ")}.`;
712
727
  }
@@ -1008,6 +1023,7 @@ function formatAgentDetail(agent: AgentConfig): string {
1008
1023
  if (agent.completionGuard === false) lines.push("Completion guard: false");
1009
1024
  if (agent.toolBudget) lines.push(`Tool budget: ${JSON.stringify(agent.toolBudget)}`);
1010
1025
  if (agent.sandbox) lines.push(`Sandbox profile: ${agent.sandbox}`);
1026
+ if (agent.permissionProfile) lines.push(`Permission profile: ${agent.permissionProfile}`);
1011
1027
  if (agent.memory) lines.push(`Memory: ${agent.memory.scope} scope, path: ${agent.memory.path}`);
1012
1028
  if (agent.systemPrompt.trim()) lines.push("", "System Prompt:", agent.systemPrompt);
1013
1029
  return lines.join("\n");
@@ -1436,6 +1452,7 @@ function validateEjectedAgentLaunchPreflight(agent: AgentConfig, cwd: string): s
1436
1452
  requireReadTool: resolvedSkills.resolved.length > 0,
1437
1453
  agentName: agent.name,
1438
1454
  sandbox: agent.sandbox,
1455
+ permissionProfile: agent.permissionProfile,
1439
1456
  });
1440
1457
  } catch (error) {
1441
1458
  return error instanceof Error ? error.message : String(error);
@@ -41,6 +41,7 @@ export const KNOWN_FIELDS = new Set([
41
41
  "completionGuard",
42
42
  "toolBudget",
43
43
  "sandbox",
44
+ "permission-profile",
44
45
  "permission",
45
46
  "permissions",
46
47
  "memory",
@@ -147,6 +148,7 @@ export function serializeAgent(config: AgentConfig, options: SerializeAgentOptio
147
148
  lines.push(`toolBudget: ${config.toolBudget ? JSON.stringify(config.toolBudget) : ""}`);
148
149
  }
149
150
  if (config.sandbox) lines.push(`sandbox: ${config.sandbox}`);
151
+ if (config.permissionProfile || preserve("permission-profile")) lines.push(`permission-profile: ${config.permissionProfile ?? ""}`);
150
152
  if (config.permissions || preserve("permission", "permissions")) {
151
153
  const key = preserve("permission") && !preserve("permissions") ? "permission" : "permissions";
152
154
  lines.push(`${key}:`);
@@ -25,6 +25,7 @@ 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
27
  import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
28
+ import { validatePermissionProfileName } from "../shared/permission-profile.ts";
28
29
 
29
30
  export type AgentScope = "user" | "project" | "both";
30
31
 
@@ -81,6 +82,7 @@ export interface BuiltinAgentOverrideBase {
81
82
  completionGuard?: boolean;
82
83
  toolBudget?: ToolBudgetConfig;
83
84
  sandbox?: string;
85
+ permissionProfile?: string;
84
86
  }
85
87
 
86
88
  interface BuiltinAgentOverrideConfig {
@@ -111,6 +113,7 @@ interface BuiltinAgentOverrideConfig {
111
113
  completionGuard?: boolean;
112
114
  toolBudget?: ToolBudgetConfig | false;
113
115
  sandbox?: string;
116
+ permissionProfile?: string;
114
117
  }
115
118
 
116
119
  interface BuiltinAgentOverrideInfo {
@@ -178,6 +181,7 @@ export interface AgentConfig {
178
181
  completionGuard?: boolean;
179
182
  toolBudget?: ToolBudgetConfig;
180
183
  sandbox?: string;
184
+ permissionProfile?: string;
181
185
  permissions?: PermissionRules;
182
186
  memory?: AgentMemoryConfig;
183
187
  disabled?: boolean;
@@ -793,6 +797,7 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
793
797
  ...(agent.completionGuard !== undefined ? { completionGuard: agent.completionGuard } : {}),
794
798
  ...(agent.toolBudget !== undefined ? { toolBudget: agent.toolBudget } : {}),
795
799
  ...(agent.sandbox !== undefined ? { sandbox: agent.sandbox } : {}),
800
+ ...(agent.permissionProfile !== undefined ? { permissionProfile: agent.permissionProfile } : {}),
796
801
  };
797
802
  }
798
803
 
@@ -827,6 +832,7 @@ function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentO
827
832
  ...(override.completionGuard !== undefined ? { completionGuard: override.completionGuard } : {}),
828
833
  ...(override.toolBudget !== undefined ? { toolBudget: override.toolBudget === false ? false : { ...override.toolBudget, ...(Array.isArray(override.toolBudget.block) ? { block: [...override.toolBudget.block] } : {}) } } : {}),
829
834
  ...(override.sandbox !== undefined ? { sandbox: override.sandbox } : {}),
835
+ ...(override.permissionProfile !== undefined ? { permissionProfile: override.permissionProfile } : {}),
830
836
  };
831
837
  }
832
838
 
@@ -1095,6 +1101,10 @@ function parseBuiltinOverrideEntry(
1095
1101
  override.sandbox = validateSandboxProfileName(input.sandbox, `Builtin override '${name}' in '${filePath}' sandbox`);
1096
1102
  }
1097
1103
 
1104
+ if ("permissionProfile" in input) {
1105
+ override.permissionProfile = validatePermissionProfileName(input.permissionProfile, `Builtin override '${name}' in '${filePath}' permission-profile`);
1106
+ }
1107
+
1098
1108
  if ("systemPrompt" in input) {
1099
1109
  if (typeof input.systemPrompt === "string") override.systemPrompt = input.systemPrompt;
1100
1110
  else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'systemPrompt'; expected a string.`);
@@ -1442,6 +1452,7 @@ function applyBuiltinOverride(
1442
1452
  if (override.completionGuard !== undefined) next.completionGuard = override.completionGuard;
1443
1453
  if (override.toolBudget !== undefined) { if (override.toolBudget === false) delete next.toolBudget; else next.toolBudget = override.toolBudget; }
1444
1454
  if (override.sandbox !== undefined) next.sandbox = override.sandbox;
1455
+ if (override.permissionProfile !== undefined) next.permissionProfile = override.permissionProfile;
1445
1456
 
1446
1457
  return next;
1447
1458
  }
@@ -1543,7 +1554,7 @@ function applyCustomAgentOverrides(
1543
1554
 
1544
1555
  export function buildBuiltinOverrideConfig(
1545
1556
  base: BuiltinAgentOverrideBase,
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">>,
1557
+ 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" | "permissionProfile"> & Partial<Pick<AgentConfig, "description" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
1547
1558
  ): BuiltinAgentOverrideConfig | undefined {
1548
1559
  const override: BuiltinAgentOverrideConfig = {};
1549
1560
 
@@ -1584,6 +1595,7 @@ export function buildBuiltinOverrideConfig(
1584
1595
  }
1585
1596
  if (JSON.stringify(draft.toolBudget) !== JSON.stringify(base.toolBudget)) override.toolBudget = draft.toolBudget ?? false;
1586
1597
  if (draft.sandbox !== undefined && draft.sandbox !== base.sandbox) override.sandbox = draft.sandbox;
1598
+ if (draft.permissionProfile !== undefined && draft.permissionProfile !== base.permissionProfile) override.permissionProfile = draft.permissionProfile;
1587
1599
 
1588
1600
  return Object.keys(override).length > 0 ? override : undefined;
1589
1601
  }
@@ -1938,7 +1950,7 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
1938
1950
 
1939
1951
  function validateExternalRunnerProfile(frontmatter: Record<string, string>, agentName: string, runner: AgentRunnerConfig | undefined): void {
1940
1952
  if (runner?.type !== "external-cli" && runner?.type !== "external-job") return;
1941
- const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "sandbox", "permission", "permissions"]
1953
+ const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "sandbox", "permission-profile", "permission", "permissions"]
1942
1954
  .filter((field) => frontmatter[field] !== undefined);
1943
1955
  if (unsupported.length > 0) {
1944
1956
  throw new Error(`Agent '${agentName}' uses runner.type='${runner.type}' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
@@ -2109,6 +2121,9 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2109
2121
  const sandbox = frontmatter.sandbox !== undefined
2110
2122
  ? validateSandboxProfileName(frontmatter.sandbox, `Agent '${localName}' sandbox`)
2111
2123
  : undefined;
2124
+ const permissionProfile = frontmatter["permission-profile"] !== undefined
2125
+ ? validatePermissionProfileName(frontmatter["permission-profile"], `Agent '${localName}' permission-profile`)
2126
+ : undefined;
2112
2127
  if (frontmatter.permission !== undefined && frontmatter.permissions !== undefined) {
2113
2128
  throw new Error(`Agent '${localName}' cannot declare both permission and permissions frontmatter.`);
2114
2129
  }
@@ -2181,6 +2196,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2181
2196
  ...(completionGuard !== undefined ? { completionGuard } : {}),
2182
2197
  ...(toolBudget !== undefined ? { toolBudget } : {}),
2183
2198
  ...(sandbox !== undefined ? { sandbox } : {}),
2199
+ ...(permissionProfile !== undefined ? { permissionProfile } : {}),
2184
2200
  ...(permissions !== undefined ? { permissions } : {}),
2185
2201
  ...(memory !== undefined ? { memory } : {}),
2186
2202
  ...(Object.keys(extraFields).length > 0 ? { extraFields } : {}),
@@ -7,6 +7,7 @@ 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
9
  import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
10
+ import { validatePermissionProfileName } from "../shared/permission-profile.ts";
10
11
 
11
12
  export const RUNTIME_AGENT_REGISTRY_KEY = "pi-subagents.runtime-agents.v1";
12
13
 
@@ -53,6 +54,7 @@ export interface RuntimeAgentDefinition {
53
54
  completionGuard?: boolean;
54
55
  toolBudget?: ToolBudgetConfig;
55
56
  sandbox?: string;
57
+ permissionProfile?: string;
56
58
  permissions?: PermissionRules;
57
59
  }
58
60
 
@@ -206,7 +208,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
206
208
  "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "defaultContext", "defaultAsync", "defaultTimeoutMs",
207
209
  "defaultToolTimeoutMs", "defaultAcceptance", "acceptanceRole", "runner", "skills", "skillPath",
208
210
  "extensions", "subagentOnlyExtensions", "mutationTools", "output", "outputMode", "defaultReads", "defaultProgress", "injectToContext", "interactive",
209
- "maxSubagentDepth", "completionGuard", "toolBudget", "sandbox", "permissions",
211
+ "maxSubagentDepth", "completionGuard", "toolBudget", "sandbox", "permissionProfile", "permissions",
210
212
  ]);
211
213
  const unknown = Object.keys(definition).filter((key) => !supported.has(key));
212
214
  if (unknown.length > 0) throw new Error(`Runtime agent definition has unknown fields: ${unknown.join(", ")}.`);
@@ -254,6 +256,12 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
254
256
  if (sandbox && (runner?.type === "external-cli" || runner?.type === "external-job")) {
255
257
  throw new Error(`Runtime agent definition runner.type='${runner.type}' cannot use sandbox profiles because it does not run a native Pi child.`);
256
258
  }
259
+ const permissionProfile = definition.permissionProfile === undefined
260
+ ? undefined
261
+ : validatePermissionProfileName(definition.permissionProfile, "Runtime agent definition permissionProfile");
262
+ if (permissionProfile && (runner?.type === "external-cli" || runner?.type === "external-job")) {
263
+ throw new Error(`Runtime agent definition runner.type='${runner.type}' cannot use permission profiles because it does not run a native Pi child.`);
264
+ }
257
265
  const permissions = validatePermissionRules(definition.permissions, "Runtime agent definition permissions");
258
266
  return {
259
267
  description: validateString(definition.description, "Runtime agent definition description", MAX_DESCRIPTION_LENGTH),
@@ -292,6 +300,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
292
300
  ...(completionGuard !== undefined ? { completionGuard } : {}),
293
301
  ...(toolBudget !== undefined ? { toolBudget } : {}),
294
302
  ...(sandbox !== undefined ? { sandbox } : {}),
303
+ ...(permissionProfile !== undefined ? { permissionProfile } : {}),
295
304
  ...(permissions !== undefined ? { permissions } : {}),
296
305
  };
297
306
  }
@@ -376,6 +385,7 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
376
385
  ...(definition.completionGuard !== undefined ? { completionGuard: definition.completionGuard } : {}),
377
386
  ...(definition.toolBudget !== undefined ? { toolBudget: definition.toolBudget } : {}),
378
387
  ...(definition.sandbox !== undefined ? { sandbox: definition.sandbox } : {}),
388
+ ...(definition.permissionProfile !== undefined ? { permissionProfile: definition.permissionProfile } : {}),
379
389
  ...(definition.permissions !== undefined ? { permissions: definition.permissions } : {}),
380
390
  };
381
391
  assertNoIdentityCollisions([agent], `Runtime agent '${name}'`);
@@ -40,7 +40,8 @@ export type SubagentLaunchContractReasonCode =
40
40
  | "thinking_ceiling"
41
41
  | "invalid_extension_bindings"
42
42
  | "untrusted_project"
43
- | "sandbox_unavailable";
43
+ | "sandbox_unavailable"
44
+ | "permission_profile_unavailable";
44
45
 
45
46
  export type SubagentLaunchContractDiagnosticCode = SubagentLaunchContractReasonCode | "host_required" | "snapshot_warning" | "workspace_scope_authority";
46
47
 
@@ -294,14 +295,26 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
294
295
  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
296
  return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
296
297
  }
298
+ if (agent.permissionProfile && (agent.source === "project" || agent.override?.scope === "project") && input.projectTrusted !== true) {
299
+ const message = `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but the project is not trusted. Trust the project and retry.`;
300
+ return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
301
+ }
297
302
  if (agent.sandbox && (agent.source === "project" || agent.override?.scope === "project") && trustedProjectCwd !== effectiveCwd) {
298
303
  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
304
  return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
300
305
  }
306
+ if (agent.permissionProfile && (agent.source === "project" || agent.override?.scope === "project") && trustedProjectCwd !== effectiveCwd) {
307
+ const message = `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but cwd '${effectiveCwd}' does not match trusted project cwd '${trustedProjectCwd}'. Launch from the trusted project cwd and retry.`;
308
+ return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
309
+ }
301
310
  if (agent.sandbox && (agent.runner?.type === "external-cli" || agent.runner?.type === "external-job")) {
302
311
  const message = `Agent '${agent.name}' requests sandbox profile '${agent.sandbox}', but runner.type='${agent.runner.type}' cannot load the native pi-sandbox extension.`;
303
312
  return { ok: false, code: "unsupported_mode", message, diagnostics: [{ code: "unsupported_mode", severity: "error", message }] };
304
313
  }
314
+ if (agent.permissionProfile && (agent.runner?.type === "external-cli" || agent.runner?.type === "external-job")) {
315
+ const message = `Agent '${agent.name}' requests permission profile '${agent.permissionProfile}', but runner.type='${agent.runner.type}' cannot load the native pi-permission-system extension.`;
316
+ return { ok: false, code: "unsupported_mode", message, diagnostics: [{ code: "unsupported_mode", severity: "error", message }] };
317
+ }
305
318
  let extensionBindings: ExtensionBindings | undefined;
306
319
  try {
307
320
  extensionBindings = normalizeExtensionBindings(input.extensionBindings)?.value;
@@ -397,10 +410,11 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
397
410
  agentName: agent.name,
398
411
  permissionRules,
399
412
  sandbox: agent.sandbox,
413
+ permissionProfile: agent.permissionProfile,
400
414
  });
401
415
  } catch (error) {
402
416
  const message = error instanceof Error ? error.message : String(error);
403
- const code: SubagentLaunchContractReasonCode = agent.sandbox ? "sandbox_unavailable" : "denied_required_tool";
417
+ const code: SubagentLaunchContractReasonCode = agent.sandbox ? "sandbox_unavailable" : agent.permissionProfile ? "permission_profile_unavailable" : "denied_required_tool";
404
418
  diagnostics.push({ code, severity: "error", message });
405
419
  return { ok: false, code, message, diagnostics };
406
420
  }
@@ -453,6 +467,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
453
467
  ...(resolveEffectiveThinking(model, effectiveThinkingConfig) ? { thinking: resolveEffectiveThinking(model, effectiveThinkingConfig) } : {}),
454
468
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
455
469
  ...(agent.sandbox ? { sandbox: agent.sandbox } : {}),
470
+ ...(agent.permissionProfile ? { permissionProfile: agent.permissionProfile } : {}),
456
471
  systemPromptMode: agent.systemPromptMode,
457
472
  inheritProjectContext: agent.inheritProjectContext,
458
473
  inheritGlobalContext: agent.inheritGlobalContext,
@@ -515,6 +530,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
515
530
  inheritGlobalContext: agent.inheritGlobalContext,
516
531
  inheritSkills: agent.inheritSkills,
517
532
  sandbox: agent.sandbox,
533
+ permissionProfile: agent.permissionProfile,
518
534
  skills: requestedSkills,
519
535
  tools: toolPlan.effectiveToolAllowlist,
520
536
  ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
@@ -16,6 +16,7 @@ import { normalizeWorktreeBaseRef } from "../shared/worktree.ts";
16
16
  import { intersectThinkingCeilings, parseThinkingLevel, type ThinkingLevel } from "../../shared/thinking-ceiling.ts";
17
17
  import { assertWorkflowGraphHostSteps } from "../shared/host-step-status.ts";
18
18
  import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
19
+ import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
19
20
 
20
21
  export interface AsyncResumeParams {
21
22
  id?: string;
@@ -57,6 +58,7 @@ export type AsyncResumeTarget = {
57
58
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
58
59
  launchContractDigest?: string;
59
60
  sandbox?: string;
61
+ permissionProfile?: string;
60
62
  runner?: NonNullable<AsyncStatus["steps"]>[number]["runner"];
61
63
  externalJob?: NonNullable<AsyncStatus["steps"]>[number]["externalJob"];
62
64
  };
@@ -76,8 +78,9 @@ interface AsyncResultFile {
76
78
  thinking?: string;
77
79
  launchContractDigest?: string;
78
80
  sandbox?: string;
81
+ permissionProfile?: string;
79
82
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
80
- results?: Array<{ agent?: string; sessionName?: string; success?: boolean; sessionFile?: string; intercomTarget?: string; model?: string; thinking?: string; launchContractDigest?: string; sandbox?: string; capabilityCeiling?: ResolvedSubagentCapabilityCeiling }>;
83
+ results?: Array<{ agent?: string; sessionName?: string; success?: boolean; sessionFile?: string; intercomTarget?: string; model?: string; thinking?: string; launchContractDigest?: string; sandbox?: string; permissionProfile?: string; capabilityCeiling?: ResolvedSubagentCapabilityCeiling }>;
81
84
  }
82
85
 
83
86
  export interface AsyncRunLocation {
@@ -122,10 +125,13 @@ function validateResultFile(value: unknown, resultPath: string): AsyncResultFile
122
125
  const sandbox = child.sandbox === undefined
123
126
  ? undefined
124
127
  : validateSandboxProfileName(child.sandbox, `async result file '${resultPath}' results[${index}].sandbox`);
128
+ const permissionProfile = child.permissionProfile === undefined
129
+ ? undefined
130
+ : validatePermissionProfileName(child.permissionProfile, `async result file '${resultPath}' results[${index}].permissionProfile`);
125
131
  const capabilityCeiling = child.capabilityCeiling === undefined ? undefined : parseSubagentCapabilityCeiling(child.capabilityCeiling, `async result file '${resultPath}' results[${index}].capabilityCeiling`);
126
132
  const success = child.success;
127
133
  if (success !== undefined && typeof success !== "boolean") throw new Error(`Invalid async result file '${resultPath}': results[${index}].success must be a boolean.`);
128
- return { agent, sessionName, sessionFile, intercomTarget, model, thinking, launchContractDigest, ...(sandbox ? { sandbox } : {}), ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(typeof success === "boolean" ? { success } : {}) };
134
+ return { agent, sessionName, sessionFile, intercomTarget, model, thinking, launchContractDigest, ...(sandbox ? { sandbox } : {}), ...(permissionProfile ? { permissionProfile } : {}), ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(typeof success === "boolean" ? { success } : {}) };
129
135
  });
130
136
  }
131
137
  const success = data.success;
@@ -143,6 +149,7 @@ function validateResultFile(value: unknown, resultPath: string): AsyncResultFile
143
149
  thinking: validateOptionalString(data, "thinking", resultPath),
144
150
  launchContractDigest: validateOptionalString(data, "launchContractDigest", resultPath),
145
151
  ...(data.sandbox === undefined ? {} : { sandbox: validateSandboxProfileName(data.sandbox, `async result file '${resultPath}' sandbox`) }),
152
+ ...(data.permissionProfile === undefined ? {} : { permissionProfile: validatePermissionProfileName(data.permissionProfile, `async result file '${resultPath}' permissionProfile`) }),
146
153
  ...(data.capabilityCeiling === undefined ? {} : { capabilityCeiling: parseSubagentCapabilityCeiling(data.capabilityCeiling, `async result file '${resultPath}' capabilityCeiling`) }),
147
154
  ...(typeof success === "boolean" ? { success } : {}),
148
155
  ...(results ? { results } : {}),
@@ -290,6 +297,7 @@ function validateStatusForResume(status: AsyncStatus | null, source: string): vo
290
297
  if (stepRecord.thinkingCeiling !== undefined) stepRecord.thinkingCeiling = parseThinkingLevel(stepRecord.thinkingCeiling, `async status '${source}' steps[${index}].thinkingCeiling`);
291
298
  if (stepRecord.launchContractDigest !== undefined && typeof stepRecord.launchContractDigest !== "string") throw new Error(`Invalid async status '${source}': steps[${index}].launchContractDigest must be a string.`);
292
299
  if (stepRecord.sandbox !== undefined) stepRecord.sandbox = validateSandboxProfileName(stepRecord.sandbox, `async status '${source}' steps[${index}].sandbox`);
300
+ if (stepRecord.permissionProfile !== undefined) stepRecord.permissionProfile = validatePermissionProfileName(stepRecord.permissionProfile, `async status '${source}' steps[${index}].permissionProfile`);
293
301
  if (stepRecord.capabilityCeiling !== undefined) stepRecord.capabilityCeiling = parseSubagentCapabilityCeiling(stepRecord.capabilityCeiling, `async status '${source}' steps[${index}].capabilityCeiling`);
294
302
  });
295
303
  }
@@ -325,7 +333,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
325
333
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': expected an object.`);
326
334
  const parsed = value as Record<string, unknown>;
327
335
  const allowedFields = new Set([
328
- "version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sandbox", "sessionFile", "cwd", "model", "modelProvider", "modelOverrideFromParent", "modelOrigin", "fallbackModels", "thinking", "thinkingCeiling", "tools", "allowNestedSubagents", "extensions",
336
+ "version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sandbox", "permissionProfile", "sessionFile", "cwd", "model", "modelProvider", "modelOverrideFromParent", "modelOrigin", "fallbackModels", "thinking", "thinkingCeiling", "tools", "allowNestedSubagents", "extensions",
329
337
  "subagentOnlyExtensions", "mcpDirectTools", "excludeTools", "mutationTools", "systemPrompt", "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills",
330
338
  "skillPath", "agentFilePath", "completionGuard", "memory", "outputPath", "outputMode", "structuredOutputSchema", "acceptance", "sessionDir", "artifactConfig",
331
339
  "artifactsDir", "maxOutput", "controlConfig", "context", "intercomBridge", "absoluteDeadlineAt", "initialTurnBudget", "initialToolBudget", "maxSubagentDepth", "share", "capabilityCeiling",
@@ -384,6 +392,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
384
392
  }
385
393
  }
386
394
  if (parsed.sandbox !== undefined) parsed.sandbox = validateSandboxProfileName(parsed.sandbox, `async recovery descriptor '${descriptorPath}' sandbox`);
395
+ if (parsed.permissionProfile !== undefined) parsed.permissionProfile = validatePermissionProfileName(parsed.permissionProfile, `async recovery descriptor '${descriptorPath}' permissionProfile`);
387
396
  if (parsed.completionGuard !== undefined && typeof parsed.completionGuard !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': completionGuard must be a boolean.`);
388
397
  if (parsed.structuredOutputSchema !== undefined && (!parsed.structuredOutputSchema || typeof parsed.structuredOutputSchema !== "object" || Array.isArray(parsed.structuredOutputSchema))) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': structuredOutputSchema must be an object.`);
389
398
  if (parsed.memory !== undefined) {
@@ -517,6 +526,7 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
517
526
  model: selectedStep.model,
518
527
  thinking: selectedStep.thinking,
519
528
  sandbox: selectedStep.sandbox ?? result?.results?.[requestedIndex]?.sandbox ?? result?.sandbox ?? recoveryDescriptor?.sandbox,
529
+ permissionProfile: selectedStep.permissionProfile ?? result?.results?.[requestedIndex]?.permissionProfile ?? result?.permissionProfile ?? recoveryDescriptor?.permissionProfile,
520
530
  launchContractDigest: selectedStep.launchContractDigest ?? result?.results?.[requestedIndex]?.launchContractDigest ?? result?.launchContractDigest ?? recoveryDescriptor?.launchContractDigest,
521
531
  ...(selectedStep.runner ? { runner: selectedStep.runner } : {}),
522
532
  ...(selectedStep.externalJob ? { externalJob: selectedStep.externalJob } : {}),
@@ -550,6 +560,7 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
550
560
  model: selected.step.model,
551
561
  thinking: selected.step.thinking,
552
562
  sandbox: selected.step.sandbox ?? result?.results?.[selected.index]?.sandbox ?? result?.sandbox ?? recoveryDescriptor?.sandbox,
563
+ permissionProfile: selected.step.permissionProfile ?? result?.results?.[selected.index]?.permissionProfile ?? result?.permissionProfile ?? recoveryDescriptor?.permissionProfile,
553
564
  launchContractDigest: selected.step.launchContractDigest ?? result?.results?.[selected.index]?.launchContractDigest ?? result?.launchContractDigest ?? recoveryDescriptor?.launchContractDigest,
554
565
  ...(selected.step.runner ? { runner: selected.step.runner } : {}),
555
566
  ...(selected.step.externalJob ? { externalJob: selected.step.externalJob } : {}),
@@ -598,6 +609,7 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
598
609
  ...(stepModel ? { model: stepModel } : {}),
599
610
  ...(stepThinking ? { thinking: stepThinking } : {}),
600
611
  sandbox: statusSteps[index]?.sandbox ?? resultSteps[index]?.sandbox ?? result?.sandbox ?? recoveryDescriptor?.sandbox,
612
+ permissionProfile: statusSteps[index]?.permissionProfile ?? resultSteps[index]?.permissionProfile ?? result?.permissionProfile ?? recoveryDescriptor?.permissionProfile,
601
613
  launchContractDigest: statusSteps[index]?.launchContractDigest ?? resultSteps[index]?.launchContractDigest ?? result?.launchContractDigest ?? recoveryDescriptor?.launchContractDigest,
602
614
  ...(statusSteps[index]?.runner ? { runner: statusSteps[index]!.runner } : {}),
603
615
  ...(statusSteps[index]?.externalJob ? { externalJob: statusSteps[index]!.externalJob } : {}),
@@ -623,6 +635,7 @@ export function applySteeringRecoveryAgentConfig(agentConfig: AgentConfig, descr
623
635
  mcpDirectTools: descriptor.mcpDirectTools ? [...descriptor.mcpDirectTools] : undefined,
624
636
  mutationTools: descriptor.mutationTools ? [...descriptor.mutationTools] : undefined,
625
637
  sandbox: descriptor.sandbox ?? agentConfig.sandbox,
638
+ permissionProfile: descriptor.permissionProfile ?? agentConfig.permissionProfile,
626
639
  systemPrompt: descriptor.systemPrompt ?? agentConfig.systemPrompt,
627
640
  systemPromptMode: descriptor.systemPromptMode,
628
641
  inheritProjectContext: descriptor.inheritProjectContext,
@@ -26,6 +26,7 @@ import { workflowGraphStageNodes } from "../shared/workflow-graph.ts";
26
26
  import { formatTimeoutRecoveryLines, projectTimeoutRecovery } from "../shared/mutation-evidence.ts";
27
27
  import { formatWorkflowChecklistText, projectWorkflowChecklist } from "../../workflows/workflow-checklist.ts";
28
28
  import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
29
+ import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
29
30
 
30
31
  interface AsyncRunStepSummary {
31
32
  index: number;
@@ -67,6 +68,7 @@ interface AsyncRunStepSummary {
67
68
  contextLimit?: number;
68
69
  thinking?: string;
69
70
  sandbox?: string;
71
+ permissionProfile?: string;
70
72
  attemptedModels?: string[];
71
73
  sessionFile?: string;
72
74
  transcriptPath?: string;
@@ -109,6 +111,7 @@ export interface AsyncRunSummary {
109
111
  mode: SubagentRunMode;
110
112
  context?: ContextSummary;
111
113
  sandbox?: string;
114
+ permissionProfile?: string;
112
115
  cwd?: string;
113
116
  sessionRoot?: string;
114
117
  startedAt: number;
@@ -214,6 +217,14 @@ function sandboxProfileValue(value: unknown): string | undefined {
214
217
  }
215
218
  }
216
219
 
220
+ function permissionProfileValue(value: unknown): string | undefined {
221
+ try {
222
+ return validatePermissionProfileName(value);
223
+ } catch {
224
+ return undefined;
225
+ }
226
+ }
227
+
217
228
  function isNotFoundError(error: unknown): boolean {
218
229
  return typeof error === "object"
219
230
  && error !== null
@@ -339,6 +350,7 @@ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string
339
350
  const stepLastActivityAt = step.lastActivityAt;
340
351
  const timeoutRecovery = projectTimeoutRecovery(step.timeoutRecovery);
341
352
  const sandbox = sandboxProfileValue(step.sandbox);
353
+ const permissionProfile = permissionProfileValue(step.permissionProfile);
342
354
  return {
343
355
  index,
344
356
  childId: asyncStatusChildIdentity(step, index),
@@ -378,6 +390,7 @@ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string
378
390
  ...(step.contextLimit !== undefined ? { contextLimit: step.contextLimit } : {}),
379
391
  ...(step.thinking ? { thinking: step.thinking } : {}),
380
392
  ...(sandbox ? { sandbox } : {}),
393
+ ...(permissionProfile ? { permissionProfile } : {}),
381
394
  ...(step.thinkingCeiling ? { thinkingCeiling: step.thinkingCeiling } : {}),
382
395
  ...(step.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
383
396
  ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
@@ -409,6 +422,7 @@ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string
409
422
  });
410
423
  attachRootChildrenToSteps(status.runId || path.basename(asyncDir), summarizedSteps, nestedChildren);
411
424
  const sandbox = sandboxProfileValue(status.sandbox);
425
+ const permissionProfile = permissionProfileValue(status.permissionProfile);
412
426
  return {
413
427
  id: status.runId || path.basename(asyncDir),
414
428
  asyncDir,
@@ -427,6 +441,7 @@ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string
427
441
  mode: status.mode,
428
442
  ...(summarizeContextModes(summarizedSteps.map((step) => step.context)) ? { context: summarizeContextModes(summarizedSteps.map((step) => step.context)) } : {}),
429
443
  ...(sandbox ? { sandbox } : {}),
444
+ ...(permissionProfile ? { permissionProfile } : {}),
430
445
  cwd: status.cwd,
431
446
  ...(status.sessionRoot ? { sessionRoot: status.sessionRoot } : {}),
432
447
  startedAt: status.startedAt,
@@ -130,8 +130,9 @@ import { normalizeExtensionBindings } from "../shared/extension-bindings.ts";
130
130
  import { appendRunnerStepsToStatus, consumeChainAppendRequests, countPendingChainAppendRequests, statusStepDescription } from "./chain-append.ts";
131
131
  import { asyncStatusChildIdentity } from "../shared/child-identity.ts";
132
132
  import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
133
+ import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
133
134
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
134
- import { effectiveToolTimeoutMs, formatToolTimeoutMessage, toolTimeoutCallKey } from "../shared/tool-timeout.ts";
135
+ import { toolTimeoutCallKey } from "../shared/tool-timeout.ts";
135
136
  import { usageBudgetExceededMessage, usageBudgetState } from "../shared/usage-budget.ts";
136
137
  import { formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
137
138
  import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
@@ -224,6 +225,7 @@ interface StepResult {
224
225
  sessionName?: string;
225
226
  context?: "fresh" | "fork";
226
227
  sandbox?: string;
228
+ permissionProfile?: string;
227
229
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
228
230
  capabilityAudit?: import("../shared/capability-ceiling.ts").SubagentCapabilityAudit;
229
231
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
@@ -284,6 +286,16 @@ function commonSandboxProfile(steps: readonly RunnerStatusStep[]): string | unde
284
286
  }
285
287
  }
286
288
 
289
+ function commonPermissionProfile(steps: readonly RunnerStatusStep[]): string | undefined {
290
+ const profile = steps[0]?.permissionProfile;
291
+ if (!profile || !steps.every((step) => step.permissionProfile === profile)) return undefined;
292
+ try {
293
+ return validatePermissionProfileName(profile);
294
+ } catch {
295
+ return undefined;
296
+ }
297
+ }
298
+
287
299
  function persistStepArtifacts(input: {
288
300
  artifactPaths: ArtifactPaths;
289
301
  artifactConfig?: Partial<ArtifactConfig>;
@@ -796,6 +808,7 @@ async function runSingleStepInner(
796
808
  inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
797
809
  permissionRules: step.permissionRules,
798
810
  sandbox: step.sandbox,
811
+ permissionProfile: step.permissionProfile,
799
812
  }));
800
813
  const contractTools = resolvedTaskToolPlan.explicitToolAllowlist ? resolvedTaskToolPlan.effectiveToolAllowlist : undefined;
801
814
  const contractError = validateImplementationToolContract({
@@ -1109,6 +1122,7 @@ async function runSingleStepInner(
1109
1122
  projectTrusted: step.projectTrusted,
1110
1123
  trustedProjectCwd: step.trustedProjectCwd,
1111
1124
  sandbox: step.sandbox,
1125
+ permissionProfile: step.permissionProfile,
1112
1126
  permissionAuditPath: step.permissionRules && ctx.artifactsDir
1113
1127
  ? path.join(ctx.artifactsDir, "permission-audit", `${ctx.id}-${ctx.flatIndex}.jsonl`)
1114
1128
  : undefined,
@@ -1148,6 +1162,7 @@ async function runSingleStepInner(
1148
1162
  inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
1149
1163
  permissionRules: step.permissionRules,
1150
1164
  sandbox: step.sandbox,
1165
+ permissionProfile: step.permissionProfile,
1151
1166
  }));
1152
1167
  launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
1153
1168
  actualLaunchContractDigest = launchBindingDigest(omitUndefinedProperties({
@@ -1164,6 +1179,7 @@ async function runSingleStepInner(
1164
1179
  inheritGlobalContext: step.inheritGlobalContext,
1165
1180
  inheritSkills: step.inheritSkills,
1166
1181
  sandbox: step.sandbox,
1182
+ permissionProfile: step.permissionProfile,
1167
1183
  skills: step.skills,
1168
1184
  tools: toolPlan.effectiveToolAllowlist,
1169
1185
  ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
@@ -1535,6 +1551,7 @@ async function runSingleStepInner(
1535
1551
  ...(childSessionName ? { sessionName: childSessionName } : {}),
1536
1552
  context: step.context,
1537
1553
  ...(step.sandbox ? { sandbox: step.sandbox } : {}),
1554
+ ...(step.permissionProfile ? { permissionProfile: step.permissionProfile } : {}),
1538
1555
  ...(step.agentContract ? { agentContract: step.agentContract } : {}),
1539
1556
  launchContractDigest: actualLaunchContractDigest,
1540
1557
  output: outputForSummary,
@@ -2016,6 +2033,7 @@ async function runSubagent(
2016
2033
  }
2017
2034
  }
2018
2035
  const initialSandbox = commonSandboxProfile(initialStatusSteps);
2036
+ const initialPermissionProfile = commonPermissionProfile(initialStatusSteps);
2019
2037
  const initialAgentLabel = initialStatusSteps.length === 1
2020
2038
  ? initialStatusSteps[0]!.agent
2021
2039
  : (config.resultMode ?? (flatSteps.length > 1 ? "chain" : "single")) === "parallel"
@@ -2052,6 +2070,7 @@ async function runSubagent(
2052
2070
  parallelGroups,
2053
2071
  workflowGraph: config.workflowGraph,
2054
2072
  ...(initialSandbox ? { sandbox: initialSandbox } : {}),
2073
+ ...(initialPermissionProfile ? { permissionProfile: initialPermissionProfile } : {}),
2055
2074
  ...(config.launchContractDigest ? { launchContractDigest: config.launchContractDigest } : {}),
2056
2075
  ...(config.launchResolvedExtensions ? { launchResolvedExtensions: config.launchResolvedExtensions } : {}),
2057
2076
  ...(config.capabilityCeiling ? { capabilityCeiling: config.capabilityCeiling } : {}),
@@ -389,6 +389,7 @@ async function runSingleAttempt(
389
389
  : undefined;
390
390
  const permissionRules = resolvePermissionRules(options.permissions, agent.permissions);
391
391
  const sandbox = options.sandbox ?? agent.sandbox;
392
+ const permissionProfile = options.permissionProfile ?? agent.permissionProfile;
392
393
  const permissionAuditPath = permissionRules && options.artifactsDir
393
394
  ? path.join(options.artifactsDir, "permission-audit", `${options.runId}-${options.index ?? 0}.jsonl`)
394
395
  : undefined;
@@ -428,6 +429,7 @@ async function runSingleAttempt(
428
429
  permissionRules,
429
430
  permissionAuditPath,
430
431
  sandbox,
432
+ permissionProfile,
431
433
  projectTrusted: options.projectTrusted,
432
434
  trustedProjectCwd: options.trustedProjectCwd,
433
435
  childWatchdog,
@@ -492,6 +494,7 @@ async function runSingleAttempt(
492
494
  inheritGlobalContext: agent.inheritGlobalContext,
493
495
  inheritSkills: agent.inheritSkills,
494
496
  sandbox,
497
+ permissionProfile,
495
498
  skills: shared.resolvedSkillNames ?? [],
496
499
  tools: toolPlan.effectiveToolAllowlist,
497
500
  ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
@@ -509,6 +512,7 @@ async function runSingleAttempt(
509
512
  ...(childSessionName ? { sessionName: childSessionName } : {}),
510
513
  ...(options.agentContract ? { agentContract: options.agentContract } : {}),
511
514
  ...(sandbox ? { sandbox } : {}),
515
+ ...(permissionProfile ? { permissionProfile } : {}),
512
516
  launchContractDigest,
513
517
  launchResolvedExtensions,
514
518
  exitCode: 0,
@@ -544,6 +544,16 @@ function sandboxProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, chi
544
544
  return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but child cwd '${path.resolve(childCwd)}' does not match the trusted project cwd '${trustedCwd}'. Launch from the trusted project cwd and retry.`;
545
545
  }
546
546
 
547
+ function permissionProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
548
+ if (!agent.permissionProfile || (agent.source !== "project" && agent.override?.scope !== "project")) return undefined;
549
+ const trustedCwd = trustedProjectCwd(ctx);
550
+ if (trustedCwd && trustedCwd === path.resolve(childCwd)) return undefined;
551
+ if (!trustedCwd) {
552
+ return `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but the project is not trusted. Trust the project and retry.`;
553
+ }
554
+ return `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but child cwd '${path.resolve(childCwd)}' does not match the trusted project cwd '${trustedCwd}'. Launch from the trusted project cwd and retry.`;
555
+ }
556
+
547
557
  function removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {
548
558
  const control = state.foregroundControls.get(runId);
549
559
  if (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;
@@ -792,6 +802,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
792
802
  ...(result.acceptance ? { acceptance: result.acceptance } : {}),
793
803
  ...(Object.keys(resumeContract).length ? { resumeContract } : {}),
794
804
  ...(result.sandbox ? { sandbox: result.sandbox } : {}),
805
+ ...(result.permissionProfile ? { permissionProfile: result.permissionProfile } : {}),
795
806
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
796
807
  ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
797
808
  ...(result.launchResolvedExtensions ? { launchResolvedExtensions: result.launchResolvedExtensions } : {}),
@@ -874,6 +885,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
874
885
  ...(input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {}),
875
886
  ...(input.result.acceptance ? { acceptance: input.result.acceptance } : {}),
876
887
  ...(input.result.sandbox ? { sandbox: input.result.sandbox } : {}),
888
+ ...(input.result.permissionProfile ? { permissionProfile: input.result.permissionProfile } : {}),
877
889
  ...(input.result.launchContractDigest ? { launchContractDigest: input.result.launchContractDigest } : {}),
878
890
  ...(input.result.launchResolvedExtensions ? { launchResolvedExtensions: input.result.launchResolvedExtensions } : {}),
879
891
  ...(input.result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: input.result.runtimeAcknowledgedExtensions } : {}),
@@ -913,7 +925,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
913
925
  });
914
926
  }
915
927
 
916
- function resolveForegroundResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { exactOnly?: boolean } = {}): { runId: string; mode: SubagentRunMode; state: "complete"; agent: string; index: number; cwd: string; sessionFile: string; model?: string; thinking?: string; sandbox?: string; launchContractDigest?: string; resumeContract?: ForegroundResumeChild["resumeContract"]; extensionBindings?: ExtensionBindings; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
928
+ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { exactOnly?: boolean } = {}): { runId: string; mode: SubagentRunMode; state: "complete"; agent: string; index: number; cwd: string; sessionFile: string; model?: string; thinking?: string; sandbox?: string; permissionProfile?: string; launchContractDigest?: string; resumeContract?: ForegroundResumeChild["resumeContract"]; extensionBindings?: ExtensionBindings; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
917
929
  const requested = (params.id ?? params.runId)?.trim();
918
930
  if (!requested || !state.foregroundRuns?.size || !state.currentSessionId) return undefined;
919
931
  const direct = state.foregroundRuns.get(requested);
@@ -944,6 +956,7 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
944
956
  ...(child.model ? { model: child.model } : {}),
945
957
  ...(child.thinking ? { thinking: child.thinking } : {}),
946
958
  ...(child.sandbox ? { sandbox: child.sandbox } : {}),
959
+ ...(child.permissionProfile ? { permissionProfile: child.permissionProfile } : {}),
947
960
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
948
961
  ...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
949
962
  ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
@@ -965,6 +978,7 @@ type NestedResumeSourceTarget = {
965
978
  model?: string;
966
979
  thinking?: AgentConfig["thinking"];
967
980
  sandbox?: string;
981
+ permissionProfile?: string;
968
982
  launchContractDigest?: string;
969
983
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
970
984
  recoveryDescriptor?: SteeringRecoveryDescriptor;
@@ -3269,6 +3283,12 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3269
3283
  if (sandboxTrustError) {
3270
3284
  return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single" as const, results: [] } };
3271
3285
  }
3286
+ const permissionProfileTrustErrorForAgent = params.worktree === true
3287
+ ? permissionProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3288
+ : permissionProfileTrustError(a, ctx, effectiveCwd);
3289
+ if (permissionProfileTrustErrorForAgent) {
3290
+ return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }], isError: true, details: { mode: "single" as const, results: [] } };
3291
+ }
3272
3292
  const rawOutput = params.output !== undefined ? params.output : a.output;
3273
3293
  const effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output);
3274
3294
  const effectiveOutputMode = params.outputMode ?? a.outputMode ?? "inline";
@@ -3782,6 +3802,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3782
3802
  if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3783
3803
  return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single", results: [] } };
3784
3804
  }
3805
+ const permissionProfileTrustErrorForLaunch = permissionProfileTrustError(agentConfig, ctx, singleCwd);
3806
+ if (permissionProfileTrustErrorForLaunch) {
3807
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3808
+ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }], isError: true, details: { mode: "single", results: [] } };
3809
+ }
3785
3810
 
3786
3811
  const authoredTask = task;
3787
3812
  if (shouldForkAgent(contextPolicy, params.agent!)) {
@@ -18,6 +18,7 @@ import {
18
18
  type RunFanoutBudgetDescriptor,
19
19
  } from "../../shared/types.ts";
20
20
  import { SUBAGENT_SANDBOX_PROFILE_ENV, SUBAGENT_SANDBOX_PROJECT_TRUST_ENV } from "../../shared/sandbox-profile.ts";
21
+ import { SUBAGENT_PERMISSION_PROFILE_ENV } from "../../shared/permission-profile.ts";
21
22
  import type { NestedPathEntry } from "./nested-path.ts";
22
23
  import type { McpRuntimeSnapshotHost } from "./mcp-direct-tool-allowlist.ts";
23
24
  import type { PermissionRules } from "./permissions.ts";
@@ -120,6 +121,8 @@ export interface BuildInProcessChildLaunchInput {
120
121
  runtimeSnapshotHost?: McpRuntimeSnapshotHost;
121
122
  /** A validated global pi-sandbox profile selected by the agent definition. */
122
123
  sandbox?: string;
124
+ /** A validated global pi-permission-system profile selected by the agent definition. */
125
+ permissionProfile?: string;
123
126
  /** Parent-authoritative trust state for profile-aware project config merging. */
124
127
  projectTrusted?: boolean;
125
128
  /** Exact trusted parent cwd; profile project config applies only when the child cwd matches it. */
@@ -211,6 +214,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
211
214
  permissionRules: input.permissionRules,
212
215
  runtimeSnapshotHost: input.runtimeSnapshotHost,
213
216
  sandbox: input.sandbox,
217
+ permissionProfile: input.permissionProfile,
214
218
  });
215
219
 
216
220
  // A selected profile is validated by resolvePiLaunchToolPlan; the child
@@ -235,6 +239,20 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
235
239
  : undefined;
236
240
  if (sandboxAckPath) fs.mkdirSync(path.dirname(sandboxAckPath), { recursive: true, mode: 0o700 });
237
241
 
242
+ // A selected permission profile travels as a bare validated name (the rules
243
+ // live in the child's global pi-permission-system config). The key is
244
+ // transient like the sandbox keys: restored on the host once the child
245
+ // session exists.
246
+ const permissionProfileEnv: Record<string, string | undefined> | undefined =
247
+ input.permissionProfile !== undefined
248
+ ? { [SUBAGENT_PERMISSION_PROFILE_ENV]: input.permissionProfile }
249
+ : undefined;
250
+ const childEnv: Record<string, string | undefined> | undefined =
251
+ sandboxEnv !== undefined || permissionProfileEnv !== undefined
252
+ ? { ...(sandboxEnv ?? {}), ...(permissionProfileEnv ?? {}) }
253
+ : undefined;
254
+ const transientProcessEnv = childEnv ? Object.keys(childEnv) : undefined;
255
+
238
256
  const inherited = input.inherited;
239
257
  const fanout = toolPlan.fanoutAuthorized;
240
258
  const inheritedRoute = inherited?.nestedRoute;
@@ -337,8 +355,8 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
337
355
  extensionPaths,
338
356
  ambientExtensions,
339
357
  hooks: createChildHooks(config),
340
- ...(input.host === "runner" || sandboxEnv ? { processEnv: childProcessEnv(input, toolPlan, sandboxEnv) } : {}),
341
- ...(sandboxEnv ? { transientProcessEnv: Object.keys(sandboxEnv) } : {}),
358
+ ...(input.host === "runner" || childEnv ? { processEnv: childProcessEnv(input, toolPlan, childEnv) } : {}),
359
+ ...(transientProcessEnv ? { transientProcessEnv } : {}),
342
360
  runtime: config,
343
361
  noSkills: !input.inheritSkills,
344
362
  noContextFiles: !input.inheritProjectContext,
@@ -21,6 +21,7 @@ import {
21
21
  import { THINKING_LEVELS } from "../../shared/model-info.ts";
22
22
  import { getAgentDir } from "../../shared/utils.ts";
23
23
  import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
24
+ import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
24
25
  import type { PermissionRules } from "./permissions.ts";
25
26
  import {
26
27
  capabilityCeilingAgentRestrictionSources,
@@ -158,6 +159,8 @@ export interface ResolvePiLaunchToolPlanInput {
158
159
  runtimeSnapshotHost?: McpRuntimeSnapshotHost;
159
160
  /** A validated global pi-sandbox profile selected by the agent definition. */
160
161
  sandbox?: string;
162
+ /** A validated global pi-permission-system profile selected by the agent definition. */
163
+ permissionProfile?: string;
161
164
  }
162
165
 
163
166
  export interface PiLaunchToolPlan {
@@ -482,6 +485,24 @@ export function resolvePiLaunchToolPlan(
482
485
  if (sandboxProfile && capabilityCeiling?.denyExtensions) {
483
486
  throw new Error(`Sandbox profile '${sandboxProfile}' requires the pi-sandbox child extension, but this launch denies child extensions.`);
484
487
  }
488
+ const permissionProfile = input.permissionProfile === undefined
489
+ ? undefined
490
+ : validatePermissionProfileName(input.permissionProfile, "permission profile");
491
+ if (permissionProfile && capabilityCeiling?.denyExtensions) {
492
+ throw new Error(`Permission profile '${permissionProfile}' requires the pi-permission-system child extension, but this launch denies child extensions.`);
493
+ }
494
+ // A permission-profile-only agent has no native `permissionRules` yet still
495
+ // needs the permission system in the child to resolve the profile: without
496
+ // it the selection would silently degrade to no policy at all. Resolve the
497
+ // extension eagerly for this path and fail the launch when the package is
498
+ // missing (the rules-only path keeps its soft resolution as before).
499
+ const permSystemExtForProfile = permissionProfile !== undefined && permSystemExt === undefined
500
+ ? resolvePermissionSystemExtension()
501
+ : undefined;
502
+ if (permissionProfile !== undefined && permSystemExt === undefined && permSystemExtForProfile === undefined) {
503
+ throw new Error(`Permission profile '${permissionProfile}' cannot be enabled: pi-permission-system is not installed; cannot launch a child with a permission profile.`);
504
+ }
505
+ const effectivePermSystemExt = permSystemExt ?? permSystemExtForProfile;
485
506
  let sandboxExtension: string | undefined;
486
507
  if (sandboxProfile) {
487
508
  try {
@@ -497,7 +518,7 @@ export function resolvePiLaunchToolPlan(
497
518
  PROMPT_RUNTIME_EXTENSION_PATH,
498
519
  ...fastModeExtensions,
499
520
  ...(fanoutAuthorized ? [FANOUT_CHILD_EXTENSION_PATH] : []),
500
- ...(permSystemExt ? [permSystemExt] : []),
521
+ ...(effectivePermSystemExt ? [effectivePermSystemExt] : []),
501
522
  ...(sandboxExtension ? [sandboxExtension, SANDBOX_PROFILE_GUARD_EXTENSION_PATH] : []),
502
523
  ];
503
524
  const disableAmbientExtensions =
@@ -21,6 +21,7 @@ import { writeAtomicJson } from "../../shared/atomic-json.ts";
21
21
  import { sanitizeProcessTerminal } from "../background/process-terminal.ts";
22
22
  import { THINKING_LEVELS } from "../../shared/model-info.ts";
23
23
  import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
24
+ import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
24
25
 
25
26
  export const NESTED_EVENTS_DIR = path.join(TEMP_ROOT_DIR, "nested-subagent-events");
26
27
  const ROUTE_FILE = "route.json";
@@ -310,6 +311,14 @@ function sandboxProfileValue(value: unknown): string | undefined {
310
311
  }
311
312
  }
312
313
 
314
+ function permissionProfileValue(value: unknown): string | undefined {
315
+ try {
316
+ return validatePermissionProfileName(value);
317
+ } catch {
318
+ return undefined;
319
+ }
320
+ }
321
+
313
322
  function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefined {
314
323
  if (!input || typeof input !== "object") return undefined;
315
324
  const raw = input as Record<string, unknown>;
@@ -321,6 +330,7 @@ function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefi
321
330
  const model = stringValue(raw.model);
322
331
  const thinking = THINKING_LEVELS.find((level) => level === raw.thinking);
323
332
  const sandbox = sandboxProfileValue(raw.sandbox);
333
+ const permissionProfile = permissionProfileValue(raw.permissionProfile);
324
334
  return {
325
335
  agent,
326
336
  status,
@@ -328,6 +338,7 @@ function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefi
328
338
  ...(thinking ? { thinking } : {}),
329
339
  ...(stringValue(raw.sessionName, 256) ? { sessionName: stringValue(raw.sessionName, 256) } : {}),
330
340
  ...(sandbox ? { sandbox } : {}),
341
+ ...(permissionProfile ? { permissionProfile } : {}),
331
342
  ...(stringValue(raw.sessionFile, 2048) ? { sessionFile: stringValue(raw.sessionFile, 2048) } : {}),
332
343
  ...(raw.activityState === "active_long_running" || raw.activityState === "needs_attention" ? { activityState: raw.activityState } : {}),
333
344
  ...(clampNumber(raw.lastActivityAt) !== undefined ? { lastActivityAt: clampNumber(raw.lastActivityAt) } : {}),
@@ -361,6 +372,7 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
361
372
  const totalTokens = sanitizeTokenUsage(raw.totalTokens);
362
373
  const totalCost = sanitizeCost(raw.totalCost);
363
374
  const sandbox = sandboxProfileValue(raw.sandbox);
375
+ const permissionProfile = permissionProfileValue(raw.permissionProfile);
364
376
  return {
365
377
  id: raw.id,
366
378
  parentRunId: raw.parentRunId,
@@ -385,6 +397,7 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
385
397
  ...(raw.mode === "single" || raw.mode === "parallel" || raw.mode === "chain" ? { mode: raw.mode } : {}),
386
398
  ...(stringValue(raw.agent, 128) ? { agent: stringValue(raw.agent, 128) } : {}),
387
399
  ...(sandbox ? { sandbox } : {}),
400
+ ...(permissionProfile ? { permissionProfile } : {}),
388
401
  ...(Array.isArray(raw.agents) ? { agents: raw.agents.map((agent) => stringValue(agent, 128)).filter((agent): agent is string => Boolean(agent)).slice(0, MAX_STEPS) } : {}),
389
402
 
390
403
  ...(clampNumber(raw.currentStep) !== undefined ? { currentStep: clampNumber(raw.currentStep) } : {}),
@@ -54,6 +54,7 @@ export interface RunnerSubagentStep {
54
54
  mutationTools?: string[];
55
55
  completionGuard?: boolean;
56
56
  sandbox?: string;
57
+ permissionProfile?: string;
57
58
  systemPrompt?: string | null;
58
59
  systemPromptMode?: "append" | "replace";
59
60
  inheritProjectContext: boolean;
@@ -72,6 +72,7 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
72
72
  completionGuard: agent.completionGuard,
73
73
  toolBudget: agent.toolBudget,
74
74
  sandbox: agent.sandbox,
75
+ permissionProfile: agent.permissionProfile,
75
76
  memory: agent.memory,
76
77
  };
77
78
  }
@@ -102,6 +103,7 @@ export interface LaunchBindingInput {
102
103
  outputPath?: string;
103
104
  outputMode?: string;
104
105
  sandbox?: string;
106
+ permissionProfile?: string;
105
107
  structuredOutputSchema?: unknown;
106
108
  extensionBindings?: ExtensionBindings;
107
109
  }
@@ -131,6 +133,7 @@ export function projectLaunchBinding(input: LaunchBindingInput): Record<string,
131
133
  outputPath: input.outputPath,
132
134
  outputMode: input.outputMode,
133
135
  sandbox: input.sandbox,
136
+ permissionProfile: input.permissionProfile,
134
137
  structuredOutputSchema: input.structuredOutputSchema,
135
138
  extensionBindings: input.extensionBindings,
136
139
  };
@@ -0,0 +1,30 @@
1
+ /** Shared wire contract for selecting a pi-permission-system profile in a child Pi process. */
2
+ export const SUBAGENT_PERMISSION_PROFILE_ENV = "PI_SUBAGENT_PERMISSION_PROFILE";
3
+
4
+ const MAX_PERMISSION_PROFILE_NAME_LENGTH = 128;
5
+ const PERMISSION_PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
6
+
7
+ /**
8
+ * Validate a raw `permission-profile` selection value into a normalized name.
9
+ * Only a bare identifier is accepted — objects (agent files must never carry
10
+ * inline policy), the literal `false`, path components, whitespace, and
11
+ * over-long values are all rejected at agent-load time.
12
+ */
13
+ export function validatePermissionProfileName(
14
+ value: unknown,
15
+ label = "permission profile",
16
+ ): string {
17
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) {
18
+ throw new Error(`${label} must be a non-empty profile name without surrounding whitespace.`);
19
+ }
20
+ if (value === "false") {
21
+ throw new Error(`${label} must select a named profile; the literal false is not supported.`);
22
+ }
23
+ if (value.length > MAX_PERMISSION_PROFILE_NAME_LENGTH) {
24
+ throw new Error(`${label} must be at most ${MAX_PERMISSION_PROFILE_NAME_LENGTH} characters.`);
25
+ }
26
+ if (!PERMISSION_PROFILE_NAME_PATTERN.test(value)) {
27
+ throw new Error(`${label} must contain only letters, digits, underscores, or hyphens and start with a letter or digit.`);
28
+ }
29
+ return value;
30
+ }
@@ -787,6 +787,7 @@ export interface SteeringRecoveryDescriptor {
787
787
  agentContract?: AgentContract;
788
788
  agent: string;
789
789
  sandbox?: string;
790
+ permissionProfile?: string;
790
791
  sessionFile?: string;
791
792
  /** Git ref used to allocate managed worktrees for this run. */
792
793
  baseRef?: string;
@@ -1242,6 +1243,7 @@ export interface SingleResult {
1242
1243
  toolBudget?: ToolBudgetState;
1243
1244
  toolBudgetBlocked?: boolean;
1244
1245
  sandbox?: string;
1246
+ permissionProfile?: string;
1245
1247
  messages?: Message[];
1246
1248
  usage: Usage;
1247
1249
  model?: string;
@@ -1575,6 +1577,7 @@ export interface NestedStepSummary {
1575
1577
  toolBudget?: ToolBudgetState;
1576
1578
  toolBudgetBlocked?: boolean;
1577
1579
  sandbox?: string;
1580
+ permissionProfile?: string;
1578
1581
  processTerminal?: ProcessTerminalV1;
1579
1582
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
1580
1583
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
@@ -1605,6 +1608,7 @@ export interface NestedRunSummary extends NestedRunAddress {
1605
1608
  /** Human-readable display name for the child session, when derived at launch. */
1606
1609
  sessionName?: string;
1607
1610
  sandbox?: string;
1611
+ permissionProfile?: string;
1608
1612
  agents?: string[];
1609
1613
  model?: string;
1610
1614
  thinking?: string;
@@ -1669,6 +1673,7 @@ export interface AsyncStartedEvent {
1669
1673
  preflight?: WorkflowPreflightV1;
1670
1674
  launchContractDigest?: string;
1671
1675
  sandbox?: string;
1676
+ permissionProfile?: string;
1672
1677
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
1673
1678
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
1674
1679
  usageBudget?: UsageBudgetState;
@@ -1841,6 +1846,7 @@ export interface AsyncStatus {
1841
1846
  runFanoutBudgetDescriptor?: RunFanoutBudgetDescriptor;
1842
1847
  launchContractDigest?: string;
1843
1848
  sandbox?: string;
1849
+ permissionProfile?: string;
1844
1850
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
1845
1851
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
1846
1852
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
@@ -1933,6 +1939,7 @@ export interface AsyncStatus {
1933
1939
  agentContract?: AgentContract;
1934
1940
  launchContractDigest?: string;
1935
1941
  sandbox?: string;
1942
+ permissionProfile?: string;
1936
1943
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
1937
1944
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
1938
1945
  execution?: ExecutionProjection;
@@ -2069,6 +2076,7 @@ export interface ForegroundResumeChild {
2069
2076
  };
2070
2077
  launchContractDigest?: string;
2071
2078
  sandbox?: string;
2079
+ permissionProfile?: string;
2072
2080
  /** Private retained launch authority. Never project into status or result output. */
2073
2081
  extensionBindings?: ExtensionBindings;
2074
2082
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
@@ -2377,6 +2385,8 @@ export interface RunSyncOptions {
2377
2385
  toolBudget?: ResolvedToolBudget;
2378
2386
  /** Selected global sandbox profile, when this child requested one. */
2379
2387
  sandbox?: string;
2388
+ /** Selected global pi-permission-system profile, when this child requested one. */
2389
+ permissionProfile?: string;
2380
2390
  allowZeroToolBudget?: boolean;
2381
2391
  allowIntercomDetach?: boolean;
2382
2392
  intercomEvents?: IntercomEventBus;