@xzzpig/pi-subagents 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,6 +62,7 @@ import { arbitrateCompletionGuardRescue } from "../shared/llm-intent-arbiter.ts"
62
62
  import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
63
63
  import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
64
64
  import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts";
65
+ import { clearSandboxStartupDiagnostic, readSandboxStartupDiagnostic } from "../shared/sandbox-startup-diagnostics.ts";
65
66
  import { resolvePermissionRules } from "../shared/permissions.ts";
66
67
  import { applyThinkingSuffix, deriveForkPromptCacheKey } from "../shared/child-tool-plan.ts";
67
68
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
@@ -164,6 +165,7 @@ function persistSingleResultMetadata(input: {
164
165
  toolCount: target.progressSummary?.toolCount,
165
166
  error: target.error,
166
167
  agentContract: target.agentContract,
168
+ sandbox: target.sandbox,
167
169
  launchContractDigest: target.launchContractDigest,
168
170
  launchResolvedExtensions: target.launchResolvedExtensions,
169
171
  runtimeAcknowledgedExtensions: target.runtimeAcknowledgedExtensions,
@@ -386,6 +388,7 @@ async function runSingleAttempt(
386
388
  })
387
389
  : undefined;
388
390
  const permissionRules = resolvePermissionRules(options.permissions, agent.permissions);
391
+ const sandbox = options.sandbox ?? agent.sandbox;
389
392
  const permissionAuditPath = permissionRules && options.artifactsDir
390
393
  ? path.join(options.artifactsDir, "permission-audit", `${options.runId}-${options.index ?? 0}.jsonl`)
391
394
  : undefined;
@@ -424,6 +427,9 @@ async function runSingleAttempt(
424
427
  toolBudget: options.toolBudget,
425
428
  permissionRules,
426
429
  permissionAuditPath,
430
+ sandbox,
431
+ projectTrusted: options.projectTrusted,
432
+ trustedProjectCwd: options.trustedProjectCwd,
427
433
  childWatchdog,
428
434
  watchdogStatus: (event) => onWatchdogStatus?.(event),
429
435
  waitToolEnabled: options.waitToolEnabled,
@@ -485,6 +491,7 @@ async function runSingleAttempt(
485
491
  inheritProjectContext: agent.inheritProjectContext,
486
492
  inheritGlobalContext: agent.inheritGlobalContext,
487
493
  inheritSkills: agent.inheritSkills,
494
+ sandbox,
488
495
  skills: shared.resolvedSkillNames ?? [],
489
496
  tools: toolPlan.effectiveToolAllowlist,
490
497
  ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
@@ -501,6 +508,7 @@ async function runSingleAttempt(
501
508
  task: shared.originalTask ?? task,
502
509
  ...(childSessionName ? { sessionName: childSessionName } : {}),
503
510
  ...(options.agentContract ? { agentContract: options.agentContract } : {}),
511
+ ...(sandbox ? { sandbox } : {}),
504
512
  launchContractDigest,
505
513
  launchResolvedExtensions,
506
514
  exitCode: 0,
@@ -1187,6 +1195,10 @@ async function runSingleAttempt(
1187
1195
  handleToolResult(evt.message, evt, now);
1188
1196
  }
1189
1197
  };
1198
+ // SAFETY: this callback is only ever invoked with child-watchdog status events
1199
+ // (declared as ChildWatchdogStatusEvent above); those carry the session-event
1200
+ // fields `processEvent` needs, and `processEvent` re-validates the shape with
1201
+ // `isChildWatchdogStatusEvent` before touching watchdog-specific fields.
1190
1202
  onWatchdogStatus = (event) => processEvent(event as unknown as Parameters<typeof processEvent>[0]);
1191
1203
 
1192
1204
  fireUpdate();
@@ -1460,8 +1472,17 @@ async function runSingleAttempt(
1460
1472
  && hasEmptyTerminalAssistantResponse(messages)
1461
1473
  && (progress.toolCount > 0 || Boolean(finalText?.trim()));
1462
1474
  if ((missingOutput || terminalEmptyAfterUsefulWork) && (!errInfo.hasError || hasEmptyTerminalAssistantResponse(messages))) {
1475
+ // A startup guard can block the first turn, which leaves no message to
1476
+ // inspect. Prefer the reason the blocked child published.
1477
+ const sandboxDiagnostic = readSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1463
1478
  result.exitCode = 1;
1464
- result.error = formatEmptyTerminalAssistantResponseError(messages);
1479
+ if (sandboxDiagnostic) {
1480
+ result.error = sandboxDiagnostic.reason;
1481
+ result.startupBlocked = true;
1482
+ clearSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1483
+ } else {
1484
+ result.error = formatEmptyTerminalAssistantResponseError(messages);
1485
+ }
1465
1486
  } else if (errInfo.hasError) {
1466
1487
  result.exitCode = errInfo.exitCode ?? 1;
1467
1488
  result.error = errInfo.details
@@ -1985,7 +2006,7 @@ async function runSyncCompletionInner(
1985
2006
  if (intercomDetached || result.timedOut) break modelAttemptsLoop;
1986
2007
  if (attemptSucceeded) break modelAttemptsLoop;
1987
2008
 
1988
- const retryableModelFailure = isRetryableModelFailureAttempt({ error: result.error, messages: result.messages, toolCount: result.progressSummary?.toolCount });
2009
+ const retryableModelFailure = isRetryableModelFailureAttempt({ error: result.error, messages: result.messages, toolCount: result.progressSummary?.toolCount, ...(result.startupBlocked ? { startupBlocked: true } : {}) });
1989
2010
  if (retryableModelFailure) recordRetryableModelFailure(result.model ?? candidate, result.error);
1990
2011
  if (isContextOverflow(result.error)) {
1991
2012
  result.contextOverflow = true;
@@ -526,6 +526,24 @@ function loadWorkflowScriptPath(params: SubagentParamsLike, runtimeCwd: string):
526
526
  return { params: { ...rest, workflowScript } };
527
527
  }
528
528
 
529
+ function currentProjectTrusted(ctx: Pick<ExtensionContext, "isProjectTrusted">): boolean {
530
+ return ctx.isProjectTrusted?.() === true;
531
+ }
532
+
533
+ function trustedProjectCwd(ctx: ExtensionContext): string | undefined {
534
+ return currentProjectTrusted(ctx) ? path.resolve(ctx.cwd) : undefined;
535
+ }
536
+
537
+ function sandboxProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
538
+ if (!agent.sandbox || (agent.source !== "project" && agent.override?.scope !== "project")) return undefined;
539
+ const trustedCwd = trustedProjectCwd(ctx);
540
+ if (trustedCwd && trustedCwd === path.resolve(childCwd)) return undefined;
541
+ if (!trustedCwd) {
542
+ return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
543
+ }
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
+ }
546
+
529
547
  function removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {
530
548
  const control = state.foregroundControls.get(runId);
531
549
  if (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;
@@ -773,6 +791,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
773
791
  ...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),
774
792
  ...(result.acceptance ? { acceptance: result.acceptance } : {}),
775
793
  ...(Object.keys(resumeContract).length ? { resumeContract } : {}),
794
+ ...(result.sandbox ? { sandbox: result.sandbox } : {}),
776
795
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
777
796
  ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
778
797
  ...(result.launchResolvedExtensions ? { launchResolvedExtensions: result.launchResolvedExtensions } : {}),
@@ -854,6 +873,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
854
873
  ...(input.result.transcriptError ? { transcriptError: input.result.transcriptError } : {}),
855
874
  ...(input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {}),
856
875
  ...(input.result.acceptance ? { acceptance: input.result.acceptance } : {}),
876
+ ...(input.result.sandbox ? { sandbox: input.result.sandbox } : {}),
857
877
  ...(input.result.launchContractDigest ? { launchContractDigest: input.result.launchContractDigest } : {}),
858
878
  ...(input.result.launchResolvedExtensions ? { launchResolvedExtensions: input.result.launchResolvedExtensions } : {}),
859
879
  ...(input.result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: input.result.runtimeAcknowledgedExtensions } : {}),
@@ -893,7 +913,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
893
913
  });
894
914
  }
895
915
 
896
- 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; launchContractDigest?: string; resumeContract?: ForegroundResumeChild["resumeContract"]; extensionBindings?: ExtensionBindings; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
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 {
897
917
  const requested = (params.id ?? params.runId)?.trim();
898
918
  if (!requested || !state.foregroundRuns?.size || !state.currentSessionId) return undefined;
899
919
  const direct = state.foregroundRuns.get(requested);
@@ -923,6 +943,7 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
923
943
  sessionFile,
924
944
  ...(child.model ? { model: child.model } : {}),
925
945
  ...(child.thinking ? { thinking: child.thinking } : {}),
946
+ ...(child.sandbox ? { sandbox: child.sandbox } : {}),
926
947
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
927
948
  ...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
928
949
  ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
@@ -943,6 +964,7 @@ type NestedResumeSourceTarget = {
943
964
  sessionFile: string;
944
965
  model?: string;
945
966
  thinking?: AgentConfig["thinking"];
967
+ sandbox?: string;
946
968
  launchContractDigest?: string;
947
969
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
948
970
  recoveryDescriptor?: SteeringRecoveryDescriptor;
@@ -1313,6 +1335,8 @@ function appendStepToAsyncChain(input: {
1313
1335
  currentModelProvider: parentModel?.provider,
1314
1336
  currentModel: parentModel,
1315
1337
  modelScope: discoveredForAppend.modelScope,
1338
+ projectTrusted: currentProjectTrusted(input.ctx),
1339
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1316
1340
  interactive: input.ctx.hasUI,
1317
1341
  permissions: input.deps.config.permissions,
1318
1342
  childRuntime: input.deps.childRuntime,
@@ -1463,6 +1487,7 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
1463
1487
  index: 0,
1464
1488
  cwd: asyncDir ? path.dirname(asyncDir) : undefined,
1465
1489
  sessionFile: validateNestedSessionFile(run, trustedSessionRoots),
1490
+ ...(recoveryDescriptor?.sandbox ?? run.sandbox ? { sandbox: recoveryDescriptor?.sandbox ?? run.sandbox } : {}),
1466
1491
  ...(run.capabilityCeiling ? { capabilityCeiling: run.capabilityCeiling } : {}),
1467
1492
  ...(recoveryDescriptor ? { recoveryDescriptor } : {}),
1468
1493
  });
@@ -1947,10 +1972,12 @@ async function resumeAsyncRun(input: {
1947
1972
  currentModelProvider: parentModel?.provider,
1948
1973
  currentModel: parentModel,
1949
1974
  modelScope,
1950
- interactive: input.ctx.hasUI,
1975
+ projectTrusted: currentProjectTrusted(input.ctx),
1976
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1977
+ interactive: input.ctx.hasUI,
1951
1978
  permissions: input.deps.config.permissions,
1952
1979
  childRuntime: input.deps.childRuntime,
1953
- }),
1980
+ }),
1954
1981
  availableModels,
1955
1982
  cwd: effectiveCwd,
1956
1983
  maxOutput: input.params.maxOutput,
@@ -2047,6 +2074,7 @@ async function resumeAsyncRun(input: {
2047
2074
  goal: effectiveFollowUp,
2048
2075
  agentConfig,
2049
2076
  recoveryAgentConfig,
2077
+ ...(recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) } : {}),
2050
2078
  ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
2051
2079
  pi: input.deps.pi,
2052
2080
  cwd: input.requestCwd,
@@ -2055,6 +2083,8 @@ async function resumeAsyncRun(input: {
2055
2083
  currentModelProvider: parentModel?.provider,
2056
2084
  currentModel: parentModel,
2057
2085
  modelScope,
2086
+ projectTrusted: currentProjectTrusted(input.ctx),
2087
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2058
2088
  interactive: input.ctx.hasUI,
2059
2089
  permissions: input.deps.config.permissions,
2060
2090
  childRuntime: input.deps.childRuntime,
@@ -2913,7 +2943,7 @@ function toExecutionErrorResult(params: SubagentParamsLike, error: unknown, cont
2913
2943
  );
2914
2944
  }
2915
2945
 
2916
- type StaticLaunchSummary = { agent: string; model?: string; thinking?: string };
2946
+ type StaticLaunchSummary = { agent: string; model?: string; thinking?: string; sandbox?: string };
2917
2947
 
2918
2948
  function resolveStaticLaunchSummary(input: {
2919
2949
  agent: string;
@@ -2945,6 +2975,7 @@ function resolveStaticLaunchSummary(input: {
2945
2975
  agent: input.agent,
2946
2976
  ...(model ? { model } : {}),
2947
2977
  ...(thinking ? { thinking } : {}),
2978
+ ...(agentConfig?.sandbox ? { sandbox: agentConfig.sandbox } : {}),
2948
2979
  };
2949
2980
  }
2950
2981
 
@@ -3210,6 +3241,8 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3210
3241
  currentModelProvider: parentModel?.provider,
3211
3242
  currentModel: parentModel,
3212
3243
  modelScope: data.modelScope,
3244
+ projectTrusted: currentProjectTrusted(ctx),
3245
+ ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3213
3246
  interactive: ctx.hasUI,
3214
3247
  permissions: deps.config.permissions,
3215
3248
  childRuntime: deps.childRuntime,
@@ -3230,6 +3263,12 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3230
3263
  details: { mode: "single" as const, results: [] },
3231
3264
  };
3232
3265
  }
3266
+ const sandboxTrustError = params.worktree === true
3267
+ ? sandboxProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3268
+ : sandboxProfileTrustError(a, ctx, effectiveCwd);
3269
+ if (sandboxTrustError) {
3270
+ return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single" as const, results: [] } };
3271
+ }
3233
3272
  const rawOutput = params.output !== undefined ? params.output : a.output;
3234
3273
  const effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output);
3235
3274
  const effectiveOutputMode = params.outputMode ?? a.outputMode ?? "inline";
@@ -3738,6 +3777,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3738
3777
  );
3739
3778
  if (worktreeSetupError) return worktreeSetupError;
3740
3779
  const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3780
+ const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
3781
+ if (sandboxTrustError) {
3782
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3783
+ return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single", results: [] } };
3784
+ }
3741
3785
 
3742
3786
  const authoredTask = task;
3743
3787
  if (shouldForkAgent(contextPolicy, params.agent!)) {
@@ -3826,6 +3870,8 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3826
3870
  permissions: deps.config.permissions,
3827
3871
  runtimeSnapshotHost: deps.pi,
3828
3872
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
3873
+ projectTrusted: currentProjectTrusted(ctx),
3874
+ ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3829
3875
  llmIntentArbiter: createTaskMutationArbiter(ctx),
3830
3876
  childRuntime: deps.childRuntime,
3831
3877
  onChildSession: (controls) => { childSessionControls = controls; },
@@ -6823,6 +6869,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6823
6869
  agents: agentsForSummary,
6824
6870
  ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model) ? { model: type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model } : {}),
6825
6871
  ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking) ? { thinking: type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking } : {}),
6872
+ ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox) ? { sandbox: type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox } : {}),
6826
6873
  startedAt: foregroundControl?.startedAt ?? now,
6827
6874
  ...(state !== "running" ? { endedAt: now } : {}),
6828
6875
  lastUpdate: now,
@@ -6834,6 +6881,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6834
6881
  status: "running" as const,
6835
6882
  ...(launch.model ? { model: launch.model } : {}),
6836
6883
  ...(launch.thinking ? { thinking: launch.thinking } : {}),
6884
+ ...(launch.sandbox ? { sandbox: launch.sandbox } : {}),
6837
6885
  })) }
6838
6886
  : details?.results.length
6839
6887
  ? { steps: details.results.map((child) => ({
@@ -6842,6 +6890,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6842
6890
  status: child.interrupted || child.detached ? "paused" as const : child.exitCode === 0 ? "complete" as const : "failed" as const,
6843
6891
  ...(child.model ? { model: child.model } : {}),
6844
6892
  ...(child.thinking ? { thinking: child.thinking } : {}),
6893
+ ...(child.sandbox ? { sandbox: child.sandbox } : {}),
6845
6894
  ...(child.sessionFile ? { sessionFile: child.sessionFile } : {}),
6846
6895
  ...(child.error ? { error: child.error } : {}),
6847
6896
  })) }
@@ -6,15 +6,18 @@
6
6
  */
7
7
  import * as fs from "node:fs";
8
8
  import * as path from "node:path";
9
+ import { randomUUID } from "node:crypto";
9
10
  import type { ChildWatchdogConfig, ChildWatchdogStatusEvent } from "../../watchdog/child-status.ts";
10
11
  import type { ThinkingLevel } from "../../shared/model-info.ts";
11
12
  import { intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
12
13
  import {
14
+ TEMP_ROOT_DIR,
13
15
  resolveChildDepth,
14
16
  type LaunchResolvedChildExtensionsV1,
15
17
  type ResolvedToolBudget,
16
18
  type RunFanoutBudgetDescriptor,
17
19
  } from "../../shared/types.ts";
20
+ import { SUBAGENT_SANDBOX_PROFILE_ENV, SUBAGENT_SANDBOX_PROJECT_TRUST_ENV } from "../../shared/sandbox-profile.ts";
18
21
  import type { NestedPathEntry } from "./nested-path.ts";
19
22
  import type { McpRuntimeSnapshotHost } from "./mcp-direct-tool-allowlist.ts";
20
23
  import type { PermissionRules } from "./permissions.ts";
@@ -23,6 +26,7 @@ import type { ChildToolDiagnostic } from "./tool-availability.ts";
23
26
  import type { RuntimeAcknowledgedChildExtensionsV1 } from "../../shared/types.ts";
24
27
  import { projectRuntimeAcknowledgedExtensions } from "./runtime-acknowledged-extensions.ts";
25
28
  import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV, type ExtensionBindings } from "./extension-bindings.ts";
29
+ import { SANDBOX_DIAGNOSTICS_PATH_ENV } from "./sandbox-startup-diagnostics.ts";
26
30
  import type { ResolvedSubagentCapabilityCeiling, SubagentCapabilityAudit } from "./capability-ceiling.ts";
27
31
  import {
28
32
  isSubagentRuntimeExtensionPath,
@@ -38,6 +42,18 @@ import type { ChildSessionLaunch, ChildSessionStorage } from "./child-session.ts
38
42
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
39
43
  export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
40
44
 
45
+ const SANDBOX_STARTUP_ACK_PATH_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_PATH";
46
+ const SANDBOX_STARTUP_ACK_TOKEN_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_TOKEN";
47
+ // Marks an in-process child so child extensions never mutate the host process
48
+ // state (for example a profile-failure exit code) that a separate child process
49
+ // would legitimately own.
50
+ const IN_PROCESS_CHILD_ENV = "PI_SUBAGENT_SANDBOX_IN_PROCESS_CHILD";
51
+
52
+ function hasTrustedProfileProjectCwd(input: Pick<BuildInProcessChildLaunchInput, "cwd" | "projectTrusted" | "trustedProjectCwd">): boolean {
53
+ if (input.projectTrusted !== true || !input.cwd || !input.trustedProjectCwd) return false;
54
+ return path.resolve(input.cwd) === path.resolve(input.trustedProjectCwd);
55
+ }
56
+
41
57
  /**
42
58
  * The parts of the launching executor's own child runtime that a child it
43
59
  * launches inherits. Serialized into the background runner config; the
@@ -102,6 +118,12 @@ export interface BuildInProcessChildLaunchInput {
102
118
  thinkingCeiling?: ThinkingLevel;
103
119
  maxSubagentDepth?: number;
104
120
  runtimeSnapshotHost?: McpRuntimeSnapshotHost;
121
+ /** A validated global pi-sandbox profile selected by the agent definition. */
122
+ sandbox?: string;
123
+ /** Parent-authoritative trust state for profile-aware project config merging. */
124
+ projectTrusted?: boolean;
125
+ /** Exact trusted parent cwd; profile project config applies only when the child cwd matches it. */
126
+ trustedProjectCwd?: string;
105
127
  /** The launching executor's own child runtime when it is itself an in-process child. */
106
128
  inherited?: InheritedChildRuntime;
107
129
  /**
@@ -127,6 +149,9 @@ export interface InProcessChildLaunch {
127
149
  launchResolvedExtensions: LaunchResolvedChildExtensionsV1;
128
150
  warnings: string[];
129
151
  capabilityAudit?: SubagentCapabilityAudit;
152
+ /** Path a blocked child extension writes its startup failure to; see
153
+ * `readSandboxStartupDiagnostic`. Present only for sandbox-profile children. */
154
+ sandboxDiagnosticsPath?: string;
130
155
  }
131
156
 
132
157
  /** Escape XML-significant characters in a string for safe attribute interpolation. */
@@ -143,14 +168,14 @@ function inheritedCapabilityCeiling(inherited: InheritedChildRuntime | undefined
143
168
  }
144
169
 
145
170
  /** Environment values external child extensions read; only the runner applies them. */
146
- function childProcessEnv(input: BuildInProcessChildLaunchInput, toolPlan: PiLaunchToolPlan): Record<string, string | undefined> {
171
+ function childProcessEnv(input: BuildInProcessChildLaunchInput, toolPlan: PiLaunchToolPlan, sandboxEnv?: Record<string, string | undefined>): Record<string, string | undefined> {
147
172
  const env: Record<string, string | undefined> = {};
148
173
  env[PI_SUBAGENT_EXTENSION_BINDINGS_ENV] = encodeExtensionBindings(input.extensionBindings);
149
174
  if (!toolPlan.capabilityCeiling && input.mcpDirectTools?.length) env[MCP_DIRECT_TOOLS_ENV] = input.mcpDirectTools.join(",");
150
175
  else if (toolPlan.capabilityCeiling && toolPlan.effectiveMcpSelections.length && !toolPlan.capabilityCeiling.denyExtensions) {
151
176
  env[MCP_DIRECT_TOOLS_ENV] = toolPlan.effectiveMcpSelections.map((selection) => selection.selector).join(",");
152
177
  } else env[MCP_DIRECT_TOOLS_ENV] = "__none__";
153
- return env;
178
+ return sandboxEnv ? { ...env, ...sandboxEnv } : env;
154
179
  }
155
180
 
156
181
  function childStorage(input: BuildInProcessChildLaunchInput): ChildSessionStorage {
@@ -185,8 +210,31 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
185
210
  agentName: input.childAgentName,
186
211
  permissionRules: input.permissionRules,
187
212
  runtimeSnapshotHost: input.runtimeSnapshotHost,
213
+ sandbox: input.sandbox,
188
214
  });
189
215
 
216
+ // A selected profile is validated by resolvePiLaunchToolPlan; the child
217
+ // receives only the profile identity, trust snapshot, and startup ack
218
+ // channel through its environment. Transient keys are restored after the
219
+ // session is created so the host process never keeps them.
220
+ const sandboxAckPath = toolPlan.sandboxExtension && input.sandbox !== undefined
221
+ ? path.join(TEMP_ROOT_DIR, "sandbox-profile-acks", `${randomUUID()}.json`)
222
+ : undefined;
223
+ const sandboxDiagnosticsPath = sandboxAckPath
224
+ ? path.join(TEMP_ROOT_DIR, "sandbox-profile-diagnostics", `${randomUUID()}.json`)
225
+ : undefined;
226
+ const sandboxEnv: Record<string, string | undefined> | undefined = sandboxAckPath
227
+ ? {
228
+ [SUBAGENT_SANDBOX_PROFILE_ENV]: input.sandbox,
229
+ [SUBAGENT_SANDBOX_PROJECT_TRUST_ENV]: hasTrustedProfileProjectCwd(input) ? "1" : "0",
230
+ [SANDBOX_STARTUP_ACK_PATH_ENV]: sandboxAckPath,
231
+ [SANDBOX_STARTUP_ACK_TOKEN_ENV]: randomUUID(),
232
+ [SANDBOX_DIAGNOSTICS_PATH_ENV]: sandboxDiagnosticsPath,
233
+ ...(input.host === "parent" ? { [IN_PROCESS_CHILD_ENV]: "1" } : {}),
234
+ }
235
+ : undefined;
236
+ if (sandboxAckPath) fs.mkdirSync(path.dirname(sandboxAckPath), { recursive: true, mode: 0o700 });
237
+
190
238
  const inherited = input.inherited;
191
239
  const fanout = toolPlan.fanoutAuthorized;
192
240
  const inheritedRoute = inherited?.nestedRoute;
@@ -289,7 +337,8 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
289
337
  extensionPaths,
290
338
  ambientExtensions,
291
339
  hooks: createChildHooks(config),
292
- ...(input.host === "runner" ? { processEnv: childProcessEnv(input, toolPlan) } : {}),
340
+ ...(input.host === "runner" || sandboxEnv ? { processEnv: childProcessEnv(input, toolPlan, sandboxEnv) } : {}),
341
+ ...(sandboxEnv ? { transientProcessEnv: Object.keys(sandboxEnv) } : {}),
293
342
  runtime: config,
294
343
  noSkills: !input.inheritSkills,
295
344
  noContextFiles: !input.inheritProjectContext,
@@ -310,5 +359,6 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
310
359
  launchResolvedExtensions,
311
360
  warnings: toolPlan.warnings,
312
361
  ...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
362
+ ...(sandboxDiagnosticsPath ? { sandboxDiagnosticsPath } : {}),
313
363
  };
314
364
  }
@@ -71,6 +71,13 @@ export interface ChildSessionLaunch {
71
71
  * window one at a time. An undefined value removes the variable.
72
72
  */
73
73
  processEnv?: Record<string, string | undefined>;
74
+ /**
75
+ * `processEnv` keys restored to their pre-launch values once the session
76
+ * exists and its extensions have captured them. Sandbox profile selections
77
+ * use this so an in-process child cannot leak its profile into the host
78
+ * process or sibling launches.
79
+ */
80
+ transientProcessEnv?: string[];
74
81
  /** The typed runtime config the hooks were built from; informational for factories. */
75
82
  runtime: ChildRuntimeConfig;
76
83
  onExtensionError?: (error: ChildSessionExtensionError) => void;
@@ -151,6 +158,18 @@ function applyProcessEnv(values: Record<string, string | undefined> | undefined)
151
158
  }
152
159
  }
153
160
 
161
+ function captureProcessEnv(keys: readonly string[] | undefined): Array<[string, string | undefined]> {
162
+ if (!keys?.length) return [];
163
+ return keys.map((key) => [key, process.env[key]]);
164
+ }
165
+
166
+ function restoreProcessEnv(saved: Array<[string, string | undefined]>): void {
167
+ for (const [key, value] of saved) {
168
+ if (value === undefined) delete process.env[key];
169
+ else process.env[key] = value;
170
+ }
171
+ }
172
+
154
173
  function flushQueuedProviderRegistrations(loader: object, modelRuntime: ModelRuntimeInstance, onError: ((error: ChildSessionExtensionError) => void) | undefined): void {
155
174
  if (!("getExtensions" in loader) || typeof loader.getExtensions !== "function") return;
156
175
  const { runtime } = (loader as LoaderWithExtensions).getExtensions();
@@ -211,6 +230,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
211
230
  ...(launch.appendSystemPrompt !== undefined ? { appendSystemPrompt: [launch.appendSystemPrompt] } : {}),
212
231
  });
213
232
  const open = async () => {
233
+ const savedTransientEnv = captureProcessEnv(launch.transientProcessEnv);
214
234
  applyProcessEnv(launch.processEnv);
215
235
  if (!resetExtensionCacheOnReload(loader) && (launch.ambientExtensions || launch.extensionPaths.length)) launch.onExtensionError?.({ extensionPath: "<loader>", event: "load", error: new Error("pi's extension cache reset is unavailable; extensions loaded into this child share module state with other sessions in this process.") });
216
236
  await loader.reload();
@@ -239,6 +259,10 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
239
259
  settingsManager,
240
260
  sessionStartEvent: { type: "session_start", reason: "startup" },
241
261
  });
262
+ // Extensions captured module state from the launch env window
263
+ // (registration and session_start); restore transient keys so an
264
+ // in-process child cannot leak them into the host process.
265
+ restoreProcessEnv(savedTransientEnv);
242
266
  try {
243
267
  await session.bindExtensions({
244
268
  mode: "print",
@@ -20,6 +20,7 @@ import {
20
20
  } from "../../shared/types.ts";
21
21
  import { THINKING_LEVELS } from "../../shared/model-info.ts";
22
22
  import { getAgentDir } from "../../shared/utils.ts";
23
+ import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
23
24
  import type { PermissionRules } from "./permissions.ts";
24
25
  import {
25
26
  capabilityCeilingAgentRestrictionSources,
@@ -45,6 +46,10 @@ const FAST_MODE_EXTENSION_PATH = path.join(
45
46
  path.dirname(fileURLToPath(import.meta.url)),
46
47
  "fast-mode-extension.ts",
47
48
  );
49
+ const SANDBOX_PROFILE_GUARD_EXTENSION_PATH = path.join(
50
+ path.dirname(fileURLToPath(import.meta.url)),
51
+ "sandbox-profile-guard.ts",
52
+ );
48
53
  const SUBAGENT_RUNTIME_EXTENSION_PATHS = new Set([
49
54
  PROMPT_RUNTIME_EXTENSION_PATH,
50
55
  FANOUT_CHILD_EXTENSION_PATH,
@@ -151,6 +156,8 @@ export interface ResolvePiLaunchToolPlanInput {
151
156
  agentName?: string;
152
157
  permissionRules?: PermissionRules;
153
158
  runtimeSnapshotHost?: McpRuntimeSnapshotHost;
159
+ /** A validated global pi-sandbox profile selected by the agent definition. */
160
+ sandbox?: string;
154
161
  }
155
162
 
156
163
  export interface PiLaunchToolPlan {
@@ -167,6 +174,8 @@ export interface PiLaunchToolPlan {
167
174
  effectiveToolAllowlist: string[];
168
175
  requiredChildTools: string[];
169
176
  fanoutAuthorized: boolean;
177
+ /** Absolute path of the resolved pi-sandbox child extension when a sandbox profile is selected. */
178
+ sandboxExtension?: string;
170
179
  runtimeExtensions: string[];
171
180
  configuredExtensions: string[];
172
181
  extensionArgs: string[];
@@ -299,6 +308,72 @@ export function resolvePermissionSystemExtension(): string | undefined {
299
308
  return undefined;
300
309
  }
301
310
 
311
+ export function resolveSandboxExtensionForProfile(profileName: string): string {
312
+ validateSandboxProfileName(profileName, "sandbox profile");
313
+ return resolveSandboxExtension();
314
+ }
315
+
316
+ function resolveSandboxExtension(): string {
317
+ const agentDir = getAgentDir();
318
+ const candidates = [
319
+ path.join(agentDir, "npm", "node_modules", "@xzzpig", "pi-sandbox"),
320
+ path.join(agentDir, "npm", "node_modules", "pi-sandbox"),
321
+ path.join(agentDir, "extensions", "pi-sandbox"),
322
+ ];
323
+ const errors: Error[] = [];
324
+ let foundPackage = false;
325
+ for (const extDir of candidates) {
326
+ if (!fs.existsSync(extDir)) continue;
327
+ foundPackage = true;
328
+ const pkgPath = path.join(extDir, "package.json");
329
+ if (!fs.existsSync(pkgPath)) {
330
+ errors.push(new Error(`Sandbox package manifest is missing at ${pkgPath}.`));
331
+ continue;
332
+ }
333
+ try {
334
+ const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
335
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
336
+ throw new Error("manifest root must be an object");
337
+ }
338
+ const manifest = parsed as { name?: unknown; pi?: { extensions?: unknown } };
339
+ if (manifest.name !== "@xzzpig/pi-sandbox" && manifest.name !== "pi-sandbox") {
340
+ throw new Error(`Sandbox package manifest at ${pkgPath} must declare name '@xzzpig/pi-sandbox' or 'pi-sandbox'.`);
341
+ }
342
+ const extensions = manifest.pi?.extensions;
343
+ const entry = Array.isArray(extensions) ? extensions[0] : undefined;
344
+ if (typeof entry !== "string" || !entry.trim()) {
345
+ throw new Error(`Sandbox package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`);
346
+ }
347
+ if (path.isAbsolute(entry)) {
348
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must be relative to the package directory.`);
349
+ }
350
+ const resolved = path.resolve(extDir, entry);
351
+ const relative = path.relative(extDir, resolved);
352
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
353
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must remain inside ${extDir}.`);
354
+ }
355
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
356
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} does not resolve to a file at ${resolved}.`);
357
+ }
358
+ const realPackageRoot = fs.realpathSync(extDir);
359
+ const realEntry = fs.realpathSync(resolved);
360
+ const realRelative = path.relative(realPackageRoot, realEntry);
361
+ if (!realRelative || realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
362
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} resolves outside ${extDir}.`);
363
+ }
364
+ return resolved;
365
+ } catch (error) {
366
+ const message = error instanceof Error ? error.message : String(error);
367
+ errors.push(message.startsWith("Sandbox") ? new Error(message) : new Error(`Cannot read sandbox package manifest at ${pkgPath}: ${message}`));
368
+ }
369
+ }
370
+ if (errors.length > 0) throw errors[0]!;
371
+ if (!foundPackage) {
372
+ throw new Error(`pi-sandbox is not installed; cannot launch a child with sandbox profile.`);
373
+ }
374
+ throw new Error(`No usable pi-sandbox extension manifest was found under '${agentDir}'.`);
375
+ }
376
+
302
377
  export function resolvePiLaunchToolPlan(
303
378
  input: ResolvePiLaunchToolPlanInput,
304
379
  ): PiLaunchToolPlan {
@@ -401,6 +476,21 @@ export function resolvePiLaunchToolPlan(
401
476
  : hasPermissionRules(input.permissionRules)
402
477
  ? resolvePermissionSystemExtension()
403
478
  : undefined;
479
+ const sandboxProfile = input.sandbox === undefined
480
+ ? undefined
481
+ : validateSandboxProfileName(input.sandbox, "sandbox profile");
482
+ if (sandboxProfile && capabilityCeiling?.denyExtensions) {
483
+ throw new Error(`Sandbox profile '${sandboxProfile}' requires the pi-sandbox child extension, but this launch denies child extensions.`);
484
+ }
485
+ let sandboxExtension: string | undefined;
486
+ if (sandboxProfile) {
487
+ try {
488
+ sandboxExtension = resolveSandboxExtensionForProfile(sandboxProfile);
489
+ } catch (error) {
490
+ const message = error instanceof Error ? error.message : String(error);
491
+ throw new Error(`Sandbox profile '${sandboxProfile}' cannot be enabled: ${message}`);
492
+ }
493
+ }
404
494
  if (input.fast && capabilityCeiling?.denyExtensions) throw new Error("fast mode requires a child runtime extension, but this launch denies extensions.");
405
495
  const fastModeExtensions = resolveFastModeExtension({ fast: input.fast, model: input.model, modelCandidates: input.modelCandidates, agentName: input.agentName });
406
496
  const runtimeExtensions = [
@@ -408,6 +498,7 @@ export function resolvePiLaunchToolPlan(
408
498
  ...fastModeExtensions,
409
499
  ...(fanoutAuthorized ? [FANOUT_CHILD_EXTENSION_PATH] : []),
410
500
  ...(permSystemExt ? [permSystemExt] : []),
501
+ ...(sandboxExtension ? [sandboxExtension, SANDBOX_PROFILE_GUARD_EXTENSION_PATH] : []),
411
502
  ];
412
503
  const disableAmbientExtensions =
413
504
  capabilityCeiling?.denyExtensions === true ||
@@ -500,6 +591,7 @@ export function resolvePiLaunchToolPlan(
500
591
  effectiveToolAllowlist,
501
592
  requiredChildTools,
502
593
  fanoutAuthorized,
594
+ ...(sandboxExtension ? { sandboxExtension } : {}),
503
595
  runtimeExtensions,
504
596
  configuredExtensions,
505
597
  extensionArgs,
@@ -570,7 +570,11 @@ function messageError(message: unknown): string | undefined {
570
570
  return typeof value === "string" ? value : undefined;
571
571
  }
572
572
 
573
- export function isRetryableModelFailureAttempt(input: { error: string | undefined; messages?: readonly unknown[]; toolCount?: number }): boolean {
573
+ export function isRetryableModelFailureAttempt(input: { error: string | undefined; messages?: readonly unknown[]; toolCount?: number; startupBlocked?: boolean }): boolean {
574
+ // A startup guard blocked the child before its first model turn: no model
575
+ // change can fix it, and recording it as a model failure would poison the
576
+ // model registry with a long-lived exclusion for a policy decision.
577
+ if (input.startupBlocked === true) return false;
574
578
  if (!isRetryableModelFailure(input.error)) return false;
575
579
  if ((input.toolCount ?? 0) > 0) return false;
576
580
  if (input.error === "Subagent produced no output (possible model cold-start or empty response)." || /^Subagent produced no output after terminal assistant stopReason "[^"]+"\.$/.test(input.error ?? "")) return true;