@xzzpig/pi-subagents 0.11.0 → 0.13.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,22 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.13.0] - 2026-09-11
4
+
5
+ ### Changed
6
+
7
+ - **Sandbox profile env is pinned per child launch.** Every child launch now writes `PI_SUBAGENT_PERMISSION_PROFILE` explicitly (cleared when the child declares no profile) and drops launcher-owned `PI_SUBAGENT_*PROFILE*` keys from the runner's inherited environment, so a spawned child can neither inherit a host-session role selection nor override its own. The launch also sets `PI_SUBAGENT_PERMISSION_PROFILE_PINNED=1` to tell the permission system that this process owns a launched selection.
8
+
9
+ ### Added
10
+
11
+ - **Public agent discovery API.** `pi-subagents/agents` now exports `discoverAgentsWithRuntime(pi, cwd, scope, preferredModelProvider?)` alongside the existing registration surface, plus the `AgentConfig`, `AgentDiscoveryDiagnostic`, `AgentDiscoveryResult`, and `AgentScope` types. It returns the same merged view the subagent executor uses — builtin, package, user, and project agent files combined with agents registered at runtime — so an independent extension can offer the launcher's agent list instead of re-implementing discovery. The extension's own runtime discovery now calls the same function.
12
+
13
+ ## [0.12.0] - 2026-09-11
14
+
15
+ ### Added
16
+
17
+ - **`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.
18
+ - **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).
19
+
3
20
  ## [0.11.0] - 2026-09-11
4
21
 
5
22
  ### Added
@@ -680,6 +697,7 @@
680
697
  - Keep `worktree: true` workflow children on the single-child path while preserving managed patch handoffs.
681
698
 
682
699
  ### Removed
700
+
683
701
  - Remove unused foreground chain and parallel execution and durable chain management surfaces.
684
702
  - Remove legacy subagent tool compatibility fields for append-step control, schedule aliases, async recovery metadata, and string mission goals.
685
703
  - Remove chain approval checkpoint steps and the `approve-checkpoint` / `reject-checkpoint` controls.
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.
@@ -101,6 +101,41 @@ The installed owner applies the existing runtime-agent validation, collision che
101
101
 
102
102
  This contract is process-local. It does not register agents in child sessions or other Pi processes, and it does not change package discovery or package resolution.
103
103
 
104
+ ## Agent discovery from independent extensions
105
+
106
+ An extension that wants to offer the same agent list the subagent launcher uses
107
+ — a session role picker, for example — can call the exported discovery helper
108
+ instead of re-implementing agent loading:
109
+
110
+ ```typescript
111
+ import { discoverAgentsWithRuntime } from "pi-subagents/agents";
112
+
113
+ const result = discoverAgentsWithRuntime(pi, cwd, "both");
114
+ for (const agent of result.agents) {
115
+ // agent.name, agent.description, agent.aliases, agent.source,
116
+ // agent.sandbox, agent.permissionProfile, agent.override?.scope, agent.disabled
117
+ }
118
+ result.agentDiagnostics; // loader problems, per source
119
+ result.projectAgentsDir; // where project agents came from
120
+ ```
121
+
122
+ The result is the merged view: builtin, package, user, and project agent files
123
+ plus anything registered at runtime through the contract above. With nothing
124
+ registered, it is exactly `discoverAgents(cwd, scope)`.
125
+
126
+ `scope` is `"user" | "project" | "both"`. Pass the caller's `cwd` so project
127
+ layering resolves against the right tree, and pass the caller's `ExtensionAPI`
128
+ because the runtime registry is keyed on it.
129
+
130
+ Two notes for consumers of an optional dependency:
131
+
132
+ - Treat the module as optional. A package that is not installed cannot be
133
+ imported, so load it dynamically and report the failure rather than failing
134
+ extension load.
135
+ - `agent.source === "project"` (or `agent.override?.scope === "project"`) means
136
+ the definition comes from the current project. Gate such an agent behind the
137
+ host's project-trust decision before adopting it for anything.
138
+
104
139
  ## External jobs in FleetView
105
140
 
106
141
  Use `pi-subagents/external-runs` to publish display-only current-session jobs owned by another extension:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xzzpig/pi-subagents",
3
- "version": "0.11.0",
3
+ "version": "0.13.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}'`);
@@ -0,0 +1,39 @@
1
+ import {
2
+ discoverAgentSnapshot,
3
+ discoverAgents,
4
+ type AgentConfig,
5
+ type AgentDiscoveryResult,
6
+ type AgentScope,
7
+ } from "./agents.ts";
8
+ import { listRuntimeAgentConfigs, mergeRuntimeAgents, type RuntimeAgentOwner } from "./runtime-agent-registry.ts";
9
+
10
+ /**
11
+ * Discover agents exactly as the runtime sees them: file-based discovery
12
+ * (builtin, package, user, project) merged with agents registered in-process
13
+ * through the runtime agent registry.
14
+ *
15
+ * Callers outside this extension — for example an extension that lets the user
16
+ * pick a role for the interactive session — need the same merged view the
17
+ * subagent executor uses. When nothing is registered at runtime this is a thin
18
+ * wrapper around `discoverAgents`, so the registry stays a pure addition.
19
+ */
20
+ export function discoverAgentsWithRuntime(
21
+ pi: RuntimeAgentOwner,
22
+ cwd: string,
23
+ scope: AgentScope,
24
+ preferredModelProvider?: string,
25
+ ): AgentDiscoveryResult {
26
+ if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider);
27
+ const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false });
28
+ const discovered = snapshot.effective;
29
+ const all = snapshot.all;
30
+ const configuredAgents: AgentConfig[] = [...all.builtin, ...all.package, ...all.user, ...all.project];
31
+ const merged = mergeRuntimeAgents(pi, discovered, configuredAgents);
32
+ if (discovered.maxThinking === undefined) return merged;
33
+ return {
34
+ ...merged,
35
+ agents: merged.agents.map((agent) =>
36
+ agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking },
37
+ ),
38
+ };
39
+ }
package/src/api/agents.ts CHANGED
@@ -8,5 +8,12 @@ export {
8
8
  type RuntimeAgentRegistrationRequest,
9
9
  type RuntimeAgentRegistrationResult,
10
10
  } from "../agents/runtime-agent-events.ts";
11
+ export { discoverAgentsWithRuntime } from "../agents/runtime-discovery.ts";
11
12
 
12
13
  export type { RegisterRuntimeAgentInput, RuntimeAgentDefinition, RuntimeAgentRegistration };
14
+ export type {
15
+ AgentConfig,
16
+ AgentDiscoveryDiagnostic,
17
+ AgentDiscoveryResult,
18
+ AgentScope,
19
+ } from "../agents/agents.ts";
@@ -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 } : {}),
@@ -19,9 +19,10 @@ import * as path from "node:path";
19
19
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
20
  import { keyText, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
21
21
  import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
22
- import { discoverAgentSnapshot, discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
22
+ import { discoverAgentsAll, type AgentScope } from "../agents/agents.ts";
23
23
  import { mergeAgentsForScope } from "../agents/agent-selection.ts";
24
- import { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
24
+ import { clearRuntimeAgentsForPi } from "../agents/runtime-agent-registry.ts";
25
+ import { discoverAgentsWithRuntime } from "../agents/runtime-discovery.ts";
25
26
  import { registerRuntimeAgentEventListener } from "../agents/runtime-agent-events.ts";
26
27
  import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
27
28
  import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
@@ -535,24 +536,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
535
536
  if (scheduledRunManager.observedCompletionRunIds().size > 0) return true;
536
537
  return missionObserverResultCandidateFiles(DIRS.results).length > 0;
537
538
  };
538
- const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) => {
539
- if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider);
540
- const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false });
541
- const discovered = snapshot.effective;
542
- const all = snapshot.all;
543
- const configuredAgents: AgentConfig[] = [
544
- ...all.builtin,
545
- ...all.package,
546
- ...all.user,
547
- ...all.project,
548
- ];
549
- const merged = mergeRuntimeAgents(pi, discovered, configuredAgents);
550
- if (discovered.maxThinking === undefined) return merged;
551
- return {
552
- ...merged,
553
- agents: merged.agents.map((agent) => agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking }),
554
- };
555
- };
539
+ const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) =>
540
+ discoverAgentsWithRuntime(pi, cwd, scope, preferredModelProvider);
556
541
  const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
557
542
  widgetEnabled: asyncWidgetEnabled,
558
543
  onJobTerminal: () => refreshResultDelivery(),
@@ -28,7 +28,7 @@ import { backgroundProcessOptions } from "../shared/background-process-options.t
28
28
  import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
29
29
  import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
30
30
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, PROMPT_REDACTED, resolveChildCwd } from "../../shared/utils.ts";
31
- import { buildModelCandidates, inheritsParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveSubagentModelOverride, type AvailableModelInfo, type ModelOrigin, type ParentModel } from "../shared/model-fallback.ts";
31
+ import { buildModelCandidates, resolveEffectiveSubagentModel, resolveModelOrigin, resolveSubagentModelOverride, type AvailableModelInfo, type ModelOrigin, type ParentModel } from "../shared/model-fallback.ts";
32
32
  import { resolveToolTimeoutMs, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
33
33
  import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
34
34
  import { findModelInfo, resolveEffectiveThinking } from "../../shared/model-info.ts";
@@ -82,7 +82,7 @@ import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.ts";
82
82
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
83
83
  import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
84
84
  import { resolvePermissionRules, type PermissionConfig } from "../shared/permissions.ts";
85
- import { normalizeExtensionBindings, omitExtensionBindingsEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
85
+ import { normalizeExtensionBindings, omitExtensionBindingsEnv, omitInheritedProfileEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
86
86
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
87
87
 
88
88
  const require = createRequire(import.meta.url);
@@ -602,7 +602,7 @@ function spawnRunner(cfg: Record<string, unknown>, suffix: string, cwd: string,
602
602
  ...backgroundProcessOptions(),
603
603
  stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
604
604
  env: {
605
- ...omitExtensionBindingsEnv(process.env),
605
+ ...omitInheritedProfileEnv(omitExtensionBindingsEnv(process.env)),
606
606
  [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot,
607
607
  [JITI_ALIAS_ENV]: JSON.stringify(hostPeerAliases.aliases),
608
608
  },
@@ -770,7 +770,7 @@ function profileProjectTrustedForCwd(ctx: AsyncExecutionContext, cwd: string): b
770
770
  && path.resolve(ctx.trustedProjectCwd) === path.resolve(cwd);
771
771
  }
772
772
 
773
- function profileProjectTrustError(agent: AgentConfig, ctx: AsyncExecutionContext, cwd: string): string {
773
+ function profileProjectTrustError(agent: AgentConfig, ctx: AsyncExecutionContext): string {
774
774
  if (ctx.projectTrusted !== true) {
775
775
  return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
776
776
  }
@@ -788,7 +788,6 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
788
788
  maxSubagentDepth,
789
789
  worktreeBaseDir,
790
790
  worktreeProvider,
791
- worktreeBranchPrefix,
792
791
  asyncDir,
793
792
  } = params;
794
793
  const outputBaseDir = params.outputBaseDir;
@@ -905,7 +904,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
905
904
  const { stepCwd, instructionCwd, readExistenceCwd, behavior, namespaceOutputPath, outputPath, skillNames } = launchPlan;
906
905
  const profileChildCwd = behaviorCwd ?? stepCwd;
907
906
  if (a.sandbox && (a.source === "project" || a.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, profileChildCwd)) {
908
- throw new AsyncStartValidationError(profileProjectTrustError(a, ctx, profileChildCwd));
907
+ throw new AsyncStartValidationError(profileProjectTrustError(a, ctx));
909
908
  }
910
909
  const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
911
910
  skillNames,
@@ -1656,7 +1655,7 @@ export function executeAsyncSingle(
1656
1655
  ? resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s0`, 0, worktreeBaseDir)
1657
1656
  : runnerCwd;
1658
1657
  if (sandbox && (agentConfig.source === "project" || agentConfig.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, instructionCwd)) {
1659
- return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx, instructionCwd));
1658
+ return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx));
1660
1659
  }
1661
1660
  const readExistenceCwd = params.worktree === true ? runnerCwd : instructionCwd;
1662
1661
  const skillNames = params.skills ?? agentConfig.skills ?? [];