@xzzpig/pi-subagents 0.10.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.
@@ -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;
@@ -860,7 +860,7 @@ export function registerSlashCommands(
860
860
  }
861
861
  fleetOpen = true;
862
862
  try {
863
- await openSubagentFleet(ctx, state, { asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: options.fleetKeybindings });
863
+ await openSubagentFleet(ctx, state, { asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: options.fleetKeybindings, events: pi.events });
864
864
  } finally {
865
865
  fleetOpen = false;
866
866
  }
@@ -11,6 +11,16 @@ import {
11
11
  type BuiltinAgentOverrideBase,
12
12
  } from "../agents/agents.ts";
13
13
  import { serializeAgent } from "../agents/agent-serializer.ts";
14
+ import { emitUiSpanSilent, type UiSpanSilentEvents } from "../ui-silent-marker.ts";
15
+
16
+ /** Event bus captured for the duration of one admin flow. */
17
+ let adminDialogEvents: UiSpanSilentEvents | undefined;
18
+
19
+ /** Claims the next dialog span as silent (pi-notify protocol). */
20
+ function markAdminDialogSilent(): void {
21
+ emitUiSpanSilent(adminDialogEvents, "admin");
22
+ }
23
+
14
24
  import { editableAgentConfig, preservedAgentFrontmatterFields } from "../agents/agent-management.ts";
15
25
  import { findModelInfo, getSupportedThinkingLevels, toModelInfo } from "../shared/model-info.ts";
16
26
  import { SelectorComponent, type SelectorItem, type SelectorResult } from "./selector.ts";
@@ -203,6 +213,7 @@ function metadataFor(agent: AgentConfig): string {
203
213
  }
204
214
 
205
215
  async function selectFromList(ctx: ExtensionContext, title: string, subtitle: string | undefined, items: SelectorItem[]): Promise<string | undefined> {
216
+ markAdminDialogSilent();
206
217
  if (typeof ctx.ui.custom === "function") {
207
218
  const result = await ctx.ui.custom<SelectorResult>(
208
219
  (tui, theme, kb, done) => new SelectorComponent(tui, theme, kb, { title, subtitle, items, done }),
@@ -257,6 +268,7 @@ async function chooseOverrideScope(ctx: ExtensionContext, agent: AgentConfig): P
257
268
  return agent.source === "project" && agent.override.scope === "user" && d.projectSettingsPath ? "project" : agent.override.scope;
258
269
  }
259
270
  if (!d.projectSettingsPath || !ctx.hasUI) return "user";
271
+ markAdminDialogSilent();
260
272
  const choice = await ctx.ui.select(`Save subagent override for ${agent.name}`, ["user", "project"]);
261
273
  return choice === "user" || choice === "project" ? choice : undefined;
262
274
  }
@@ -373,6 +385,7 @@ async function editSystemPrompt(ctx: ExtensionContext, agent: AgentConfig): Prom
373
385
  const readOnlyMessage = readOnlyAgentMessage(agent, "systemPrompt");
374
386
  if (readOnlyMessage) return readOnlyMessage;
375
387
  }
388
+ markAdminDialogSilent();
376
389
  const edited = await ctx.ui.editor(`Edit '${agent.name}' system prompt`, agent.systemPrompt ?? "");
377
390
  if (edited === undefined) return null;
378
391
  const projectOwnsLowerScopeOverride = agent.source === "project" && agent.override?.scope === "user" && discoverAgentsAll(ctx.cwd).projectSettingsPath;
@@ -383,6 +396,15 @@ async function editSystemPrompt(ctx: ExtensionContext, agent: AgentConfig): Prom
383
396
  }
384
397
 
385
398
  export async function openSubagentsAdmin(pi: ExtensionAPI, ctx: ExtensionContext, args = ""): Promise<void> {
399
+ adminDialogEvents = pi.events;
400
+ try {
401
+ return await runAdminFlow(pi, ctx, args);
402
+ } finally {
403
+ adminDialogEvents = undefined;
404
+ }
405
+ }
406
+
407
+ async function runAdminFlow(pi: ExtensionAPI, ctx: ExtensionContext, args = ""): Promise<void> {
386
408
  const selection = await selectAgent(ctx, args);
387
409
  if (selection.kind === "cancelled") return;
388
410
  if (selection.kind === "ambiguous") {
@@ -411,6 +433,7 @@ export async function openSubagentsAdmin(pi: ExtensionAPI, ctx: ExtensionContext
411
433
  else if (requestedAction === "prompt" || requestedAction === "system-prompt" || requestedAction === "edit") action = "Edit system prompt";
412
434
  else if (requestedAction === "details" || requestedAction === "info") action = "Show details";
413
435
  if (!action) {
436
+ markAdminDialogSilent();
414
437
  action = await ctx.ui.select(
415
438
  `Administer ${agent.name}\n${metadataSummary(agent)}`,
416
439
  ["Change model", "Change thinking level", "Edit system prompt", "Show details", "Done"],
package/src/tui/fleet.ts CHANGED
@@ -1,9 +1,14 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
- import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import {
5
+ getMarkdownTheme,
6
+ type ExtensionAPI,
7
+ type ExtensionContext,
8
+ } from "@earendil-works/pi-coding-agent";
5
9
  import { matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type MarkdownTheme } from "@earendil-works/pi-tui";
6
10
  import { snapshotExternalRuns, type ExternalRun } from "../api/external-runs.ts";
11
+ import { emitUiSpanSilent, type UiSpanSilentEvents } from "../ui-silent-marker.ts";
7
12
  import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
8
13
  import { formatDuration, formatModelThinking, formatTokens, formatTokenUsage, shortenPath } from "../shared/formatters.ts";
9
14
  import { DIRS, type AsyncJobState, type AsyncJobStep, type Details, type FleetKeybindingAction, type FleetKeybindingsConfig, type ForegroundChildControl, type ForegroundResumeChild, type ForegroundResumeRun, type ForegroundRunControl, type SubagentState } from "../shared/types.ts";
@@ -115,6 +120,8 @@ export interface FleetViewOptions {
115
120
  actions?: FleetActionHandlers;
116
121
  copyText?: (text: string) => Promise<void> | void;
117
122
  herdrClient?: HerdrClient;
123
+ /** Event bus used to claim the fleet dialog as a silent span. */
124
+ events?: UiSpanSilentEvents;
118
125
  }
119
126
 
120
127
  function belongsToCurrentSession(sessionId: string | undefined, currentSessionId: string | null): boolean {
@@ -1518,6 +1525,9 @@ export async function openSubagentFleet(ctx: ExtensionContext, state: SubagentSt
1518
1525
  return control.promptAuditRedo(input.index, input.guidance);
1519
1526
  },
1520
1527
  } satisfies FleetActionHandlers;
1528
+ // The fleet inspector is a user-initiated monitoring panel, not an
1529
+ // agent-waiting prompt: claim the dialog span as silent.
1530
+ emitUiSpanSilent(options.events, "fleet");
1521
1531
  try {
1522
1532
  await ctx.ui.custom<undefined>(
1523
1533
  (tui, theme, _keybindings, done) => new SubagentFleetComponent(tui, theme, state, done, { ...options, actions, copyText }),
@@ -1530,3 +1540,30 @@ export async function openSubagentFleet(ctx: ExtensionContext, state: SubagentSt
1530
1540
  state.fleetInspectorOpen = wasOpen;
1531
1541
  }
1532
1542
  }
1543
+
1544
+ export interface OpenFleetFromStatusOptions {
1545
+ itemKey?: string;
1546
+ asyncDirRoot: string;
1547
+ resultsDir: string;
1548
+ fleetKeybindings?: FleetKeybindingsConfig;
1549
+ }
1550
+
1551
+ /**
1552
+ * Opens the fleet inspector from the idle status widget, claiming the
1553
+ * dialog as a silent span (pi-notify protocol). Shared by the status-widget
1554
+ * path so the marker wiring is testable in one place.
1555
+ */
1556
+ export function openSubagentFleetFromStatus(
1557
+ ctx: ExtensionContext,
1558
+ state: SubagentState,
1559
+ pi: ExtensionAPI,
1560
+ options: OpenFleetFromStatusOptions,
1561
+ ): Promise<void> {
1562
+ return openSubagentFleet(ctx, state, {
1563
+ initialKey: options.itemKey,
1564
+ asyncDirRoot: options.asyncDirRoot,
1565
+ resultsDir: options.resultsDir,
1566
+ fleetKeybindings: options.fleetKeybindings,
1567
+ events: pi.events,
1568
+ });
1569
+ }