@xzzpig/pi-subagents 0.9.0 → 0.11.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.
@@ -20,6 +20,7 @@ import { isSafeNestedPathId, sanitizeNestedPath, type NestedPathEntry } from "./
20
20
  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
+ import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
23
24
 
24
25
  export const NESTED_EVENTS_DIR = path.join(TEMP_ROOT_DIR, "nested-subagent-events");
25
26
  const ROUTE_FILE = "route.json";
@@ -136,7 +137,17 @@ export function resolveNestedRoute(route: NestedRoute): NestedRoute {
136
137
  const { rootRunId, capabilityToken } = route;
137
138
  validateRouteShape(route);
138
139
  const routeFile = path.join(commonRouteRoot(route), ROUTE_FILE);
139
- const metadata = JSON.parse(fs.readFileSync(routeFile, "utf-8")) as { rootRunId?: unknown; capabilityToken?: unknown };
140
+ let metadata: { rootRunId?: unknown; capabilityToken?: unknown };
141
+ try {
142
+ const parsed: unknown = JSON.parse(fs.readFileSync(routeFile, "utf-8"));
143
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
144
+ throw new Error("route metadata must be an object");
145
+ }
146
+ metadata = parsed as { rootRunId?: unknown; capabilityToken?: unknown };
147
+ } catch (error) {
148
+ const message = error instanceof Error ? error.message : String(error);
149
+ throw new Error(`Nested event route metadata is unreadable: ${message}`);
150
+ }
140
151
  if (metadata.rootRunId !== rootRunId || metadata.capabilityToken !== capabilityToken) {
141
152
  throw new Error("Nested event route metadata does not match the provided root id and capability token.");
142
153
  }
@@ -291,6 +302,14 @@ function sanitizeState(value: unknown, fallback: NestedRunState): NestedRunState
291
302
  : fallback;
292
303
  }
293
304
 
305
+ function sandboxProfileValue(value: unknown): string | undefined {
306
+ try {
307
+ return validateSandboxProfileName(value);
308
+ } catch {
309
+ return undefined;
310
+ }
311
+ }
312
+
294
313
  function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefined {
295
314
  if (!input || typeof input !== "object") return undefined;
296
315
  const raw = input as Record<string, unknown>;
@@ -301,12 +320,14 @@ function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefi
301
320
  : "pending";
302
321
  const model = stringValue(raw.model);
303
322
  const thinking = THINKING_LEVELS.find((level) => level === raw.thinking);
323
+ const sandbox = sandboxProfileValue(raw.sandbox);
304
324
  return {
305
325
  agent,
306
326
  status,
307
327
  ...(model ? { model } : {}),
308
328
  ...(thinking ? { thinking } : {}),
309
329
  ...(stringValue(raw.sessionName, 256) ? { sessionName: stringValue(raw.sessionName, 256) } : {}),
330
+ ...(sandbox ? { sandbox } : {}),
310
331
  ...(stringValue(raw.sessionFile, 2048) ? { sessionFile: stringValue(raw.sessionFile, 2048) } : {}),
311
332
  ...(raw.activityState === "active_long_running" || raw.activityState === "needs_attention" ? { activityState: raw.activityState } : {}),
312
333
  ...(clampNumber(raw.lastActivityAt) !== undefined ? { lastActivityAt: clampNumber(raw.lastActivityAt) } : {}),
@@ -339,6 +360,7 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
339
360
  : undefined;
340
361
  const totalTokens = sanitizeTokenUsage(raw.totalTokens);
341
362
  const totalCost = sanitizeCost(raw.totalCost);
363
+ const sandbox = sandboxProfileValue(raw.sandbox);
342
364
  return {
343
365
  id: raw.id,
344
366
  parentRunId: raw.parentRunId,
@@ -362,7 +384,9 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
362
384
  ...(stringValue(raw.capabilityToken, 128) ? { capabilityToken: stringValue(raw.capabilityToken, 128) } : {}),
363
385
  ...(raw.mode === "single" || raw.mode === "parallel" || raw.mode === "chain" ? { mode: raw.mode } : {}),
364
386
  ...(stringValue(raw.agent, 128) ? { agent: stringValue(raw.agent, 128) } : {}),
387
+ ...(sandbox ? { sandbox } : {}),
365
388
  ...(Array.isArray(raw.agents) ? { agents: raw.agents.map((agent) => stringValue(agent, 128)).filter((agent): agent is string => Boolean(agent)).slice(0, MAX_STEPS) } : {}),
389
+
366
390
  ...(clampNumber(raw.currentStep) !== undefined ? { currentStep: clampNumber(raw.currentStep) } : {}),
367
391
  ...(clampNumber(raw.chainStepCount) !== undefined ? { chainStepCount: clampNumber(raw.chainStepCount) } : {}),
368
392
  ...(raw.activityState === "active_long_running" || raw.activityState === "needs_attention" ? { activityState: raw.activityState } : {}),
@@ -768,7 +792,7 @@ export function projectNestedEvents(route: NestedRoute): NestedRegistry {
768
792
  return registry;
769
793
  }
770
794
 
771
- function writeRouteRecord(dir: string, ts: number, payload: object): string {
795
+ function writeRouteRecord<T extends object>(dir: string, ts: number, payload: T): string {
772
796
  const content = `${JSON.stringify(payload)}\n`;
773
797
  if (Buffer.byteLength(content, "utf-8") > MAX_EVENT_BYTES) throw new Error("Nested route record exceeds the maximum size.");
774
798
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -986,6 +1010,7 @@ export function hasLiveNestedDescendants(children: NestedRunSummary[] | undefine
986
1010
  }
987
1011
 
988
1012
  export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: string, fallback: { id: string; parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }>; mode?: SubagentRunMode; ts: number }): NestedRunSummary {
1013
+ const sandbox = sandboxProfileValue(status.sandbox);
989
1014
  return {
990
1015
  id: status.runId || fallback.id,
991
1016
  parentRunId: fallback.parentRunId,
@@ -996,6 +1021,7 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
996
1021
  ...(status.pid ? { pid: status.pid } : {}),
997
1022
  ...(status.sessionId ? { sessionId: status.sessionId } : {}),
998
1023
  mode: status.mode ?? fallback.mode,
1024
+ ...(sandbox ? { sandbox } : {}),
999
1025
  ...(status.steps?.length === 1 && status.steps[0]?.model ? { model: status.steps[0].model } : {}),
1000
1026
  ...(status.steps?.length === 1 && status.steps[0]?.thinking ? { thinking: status.steps[0].thinking } : {}),
1001
1027
  ...(status.steps?.length === 1 && status.steps[0]?.sessionName ? { sessionName: status.steps[0].sessionName } : {}),
@@ -1027,34 +1053,40 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
1027
1053
  ...(status.endedAt !== undefined ? { endedAt: status.endedAt } : {}),
1028
1054
  lastUpdate: status.lastUpdate ?? fallback.ts,
1029
1055
  ...(status.sessionFile ? { sessionFile: status.sessionFile } : {}),
1030
- ...(status.steps?.length ? { steps: status.steps.map((step, index) => ({
1031
- agent: step.agent,
1032
- ...(step.sessionName ? { sessionName: step.sessionName } : {}),
1033
- status: step.status,
1034
- ...(step.model ? { model: step.model } : {}),
1035
- ...(step.thinking ? { thinking: step.thinking } : {}),
1036
- ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
1037
- ...(step.activityState ? { activityState: step.activityState } : {}),
1038
- ...(step.lastActivityAt !== undefined ? { lastActivityAt: step.lastActivityAt } : {}),
1039
- ...(step.currentTool ? { currentTool: step.currentTool } : {}),
1040
- ...(step.currentToolStartedAt !== undefined ? { currentToolStartedAt: step.currentToolStartedAt } : {}),
1041
- ...(step.currentPath ? { currentPath: step.currentPath } : {}),
1042
- ...(step.turnCount !== undefined ? { turnCount: step.turnCount } : {}),
1043
- ...(step.toolCount !== undefined ? { toolCount: step.toolCount } : {}),
1044
- ...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
1045
- ...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),
1046
- ...(step.error ? { error: step.error } : {}),
1047
- ...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
1048
- ...runtimeAcknowledgedEntry(step.runtimeAcknowledgedExtensions),
1049
- ...(step.timedOut !== undefined ? { timedOut: step.timedOut } : {}),
1050
- ...(step.stopped !== undefined ? { stopped: step.stopped } : {}),
1051
- ...(step.turnBudget ? { turnBudget: step.turnBudget } : {}),
1052
- ...(step.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: step.turnBudgetExceeded } : {}),
1053
- ...(step.wrapUpRequested !== undefined ? { wrapUpRequested: step.wrapUpRequested } : {}),
1054
- ...(step.processTerminal ? { processTerminal: sanitizeProcessTerminal(step.processTerminal, { runId: status.runId || fallback.id, runnerProcessInstanceId: step.processTerminal.runnerProcessInstanceId }, `${asyncDir}/status.json step ${index}`) } : {}),
1055
- ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
1056
- ...(step.capabilityAudit ? { capabilityAudit: step.capabilityAudit } : {}),
1057
- })).slice(0, MAX_STEPS) } : {}),
1056
+ ...(status.steps?.length ? {
1057
+ steps: status.steps.map((step, index) => {
1058
+ const stepSandbox = sandboxProfileValue(step.sandbox);
1059
+ return {
1060
+ agent: step.agent,
1061
+ ...(step.sessionName ? { sessionName: step.sessionName } : {}),
1062
+ status: step.status,
1063
+ ...(step.model ? { model: step.model } : {}),
1064
+ ...(step.thinking ? { thinking: step.thinking } : {}),
1065
+ ...(stepSandbox ? { sandbox: stepSandbox } : {}),
1066
+ ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
1067
+ ...(step.activityState ? { activityState: step.activityState } : {}),
1068
+ ...(step.lastActivityAt !== undefined ? { lastActivityAt: step.lastActivityAt } : {}),
1069
+ ...(step.currentTool ? { currentTool: step.currentTool } : {}),
1070
+ ...(step.currentToolStartedAt !== undefined ? { currentToolStartedAt: step.currentToolStartedAt } : {}),
1071
+ ...(step.currentPath ? { currentPath: step.currentPath } : {}),
1072
+ ...(step.turnCount !== undefined ? { turnCount: step.turnCount } : {}),
1073
+ ...(step.toolCount !== undefined ? { toolCount: step.toolCount } : {}),
1074
+ ...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
1075
+ ...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),
1076
+ ...(step.error ? { error: step.error } : {}),
1077
+ ...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
1078
+ ...runtimeAcknowledgedEntry(step.runtimeAcknowledgedExtensions),
1079
+ ...(step.timedOut !== undefined ? { timedOut: step.timedOut } : {}),
1080
+ ...(step.stopped !== undefined ? { stopped: step.stopped } : {}),
1081
+ ...(step.turnBudget ? { turnBudget: step.turnBudget } : {}),
1082
+ ...(step.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: step.turnBudgetExceeded } : {}),
1083
+ ...(step.wrapUpRequested !== undefined ? { wrapUpRequested: step.wrapUpRequested } : {}),
1084
+ ...(step.processTerminal ? { processTerminal: sanitizeProcessTerminal(step.processTerminal, { runId: status.runId || fallback.id, runnerProcessInstanceId: step.processTerminal.runnerProcessInstanceId }, `${asyncDir}/status.json step ${index}`) } : {}),
1085
+ ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
1086
+ ...(step.capabilityAudit ? { capabilityAudit: step.capabilityAudit } : {}),
1087
+ };
1088
+ }).slice(0, MAX_STEPS),
1089
+ } : {}),
1058
1090
  };
1059
1091
  }
1060
1092
 
@@ -5,6 +5,10 @@ export interface RunnerSubagentStep {
5
5
  parentSessionId?: string;
6
6
  /** Resolved opt-in rules for native Pi child tool calls. */
7
7
  permissionRules?: import("./permissions.ts").PermissionRules;
8
+ /** Parent-authoritative trust state for profile-aware project config merging. */
9
+ projectTrusted?: boolean;
10
+ /** Exact trusted parent cwd; project config applies only when it matches this child cwd. */
11
+ trustedProjectCwd?: string;
8
12
  agent: string;
9
13
  /** Human-readable display name for the child session, derived internally at launch. */
10
14
  sessionName?: string;
@@ -49,6 +53,7 @@ export interface RunnerSubagentStep {
49
53
  mcpDirectTools?: string[];
50
54
  mutationTools?: string[];
51
55
  completionGuard?: boolean;
56
+ sandbox?: string;
52
57
  systemPrompt?: string | null;
53
58
  systemPromptMode?: "append" | "replace";
54
59
  inheritProjectContext: boolean;
@@ -0,0 +1,85 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { SANDBOX_DIAGNOSTICS_PATH_ENV } from "./sandbox-startup-diagnostics.ts";
5
+
6
+ const SANDBOX_PROFILE_ENV = "PI_SUBAGENT_SANDBOX_PROFILE";
7
+ const SANDBOX_STARTUP_ACK_PATH_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_PATH";
8
+ const SANDBOX_STARTUP_ACK_TOKEN_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_TOKEN";
9
+ const MAX_ACK_BYTES = 4096;
10
+
11
+ function startupAcknowledgementError(profile: string, ackPath: string | undefined, token: string | undefined): string | undefined {
12
+ if (!ackPath || !token) {
13
+ return `Sandbox profile '${profile}' is missing its required startup acknowledgement channel.`;
14
+ }
15
+ try {
16
+ const stat = fs.lstatSync(ackPath);
17
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_ACK_BYTES) {
18
+ return `Sandbox profile '${profile}' did not produce a valid startup acknowledgement.`;
19
+ }
20
+ const parsed: unknown = JSON.parse(fs.readFileSync(ackPath, "utf-8"));
21
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
22
+ return `Sandbox profile '${profile}' did not produce a valid startup acknowledgement.`;
23
+ }
24
+ const acknowledgement = parsed as { version?: unknown; profile?: unknown; token?: unknown };
25
+ if (acknowledgement.version !== 1 || acknowledgement.profile !== profile || acknowledgement.token !== token) {
26
+ return `Sandbox profile '${profile}' did not acknowledge successful startup.`;
27
+ }
28
+ return undefined;
29
+ } catch {
30
+ return `Sandbox profile '${profile}' did not acknowledge successful startup.`;
31
+ }
32
+ }
33
+
34
+ export default function registerSandboxProfileGuard(pi: ExtensionAPI): void {
35
+ // Env values are captured at registration, inside the launch env window; the
36
+ // host restores transient sandbox keys after the session is created.
37
+ const profile = process.env[SANDBOX_PROFILE_ENV];
38
+ if (!profile) return;
39
+ const ackPath = process.env[SANDBOX_STARTUP_ACK_PATH_ENV];
40
+ const token = process.env[SANDBOX_STARTUP_ACK_TOKEN_ENV];
41
+ const diagnosticsPath = process.env[SANDBOX_DIAGNOSTICS_PATH_ENV];
42
+ let validated = false;
43
+
44
+ // The guard owns the acknowledgement check, so it is also the component that
45
+ // knows the child was refused before its first turn. Publish that reason for
46
+ // the launcher instead of leaving the caller with an empty session.
47
+ const publishDiagnostic = (reason: string): void => {
48
+ if (!diagnosticsPath) return;
49
+ try {
50
+ fs.mkdirSync(path.dirname(diagnosticsPath), { recursive: true, mode: 0o700 });
51
+ fs.writeFileSync(
52
+ diagnosticsPath,
53
+ JSON.stringify({ version: 1, profile, reason }),
54
+ { mode: 0o600 },
55
+ );
56
+ } catch {
57
+ // The stderr diagnostic below remains the fallback channel.
58
+ }
59
+ };
60
+
61
+ const check = (): string | undefined => {
62
+ if (validated) return undefined;
63
+ const failure = startupAcknowledgementError(profile, ackPath, token);
64
+ if (!failure) validated = true;
65
+ return failure;
66
+ };
67
+
68
+ const clearAcknowledgement = (): void => {
69
+ if (!ackPath || !validated) return;
70
+ try { fs.rmSync(ackPath, { force: true }); } catch { /* best effort */ }
71
+ };
72
+
73
+ pi.on("input", (_event, ctx: ExtensionContext) => {
74
+ const failure = check();
75
+ if (failure) {
76
+ process.stderr.write(`pi-subagents: ${failure}\n`);
77
+ publishDiagnostic(failure);
78
+ if (ctx.hasUI) ctx.ui.notify(failure, "error");
79
+ else process.exitCode = 1;
80
+ return { action: "handled" as const };
81
+ }
82
+ clearAcknowledgement();
83
+ return undefined;
84
+ });
85
+ }
@@ -0,0 +1,54 @@
1
+ import * as fs from "node:fs";
2
+
3
+ /**
4
+ * A child extension that refuses to start (for example a required sandbox
5
+ * profile that cannot initialize) blocks the first model turn, so the child
6
+ * session ends with no messages and no tool result to inspect. The launcher
7
+ * hands the extension this path through the transient launch environment and
8
+ * reads it back, so the caller sees the real reason instead of an invented
9
+ * empty-output message.
10
+ */
11
+ export const SANDBOX_DIAGNOSTICS_PATH_ENV = "PI_SUBAGENT_SANDBOX_DIAGNOSTICS_PATH";
12
+
13
+ const MAX_DIAGNOSTIC_BYTES = 8192;
14
+
15
+ export interface SandboxStartupDiagnostic {
16
+ version: 1;
17
+ profile?: string;
18
+ reason: string;
19
+ }
20
+
21
+ /**
22
+ * Read the startup diagnostic a blocked child extension wrote. The file is
23
+ * treated as untrusted input: only a bounded, well-formed record is accepted.
24
+ */
25
+ export function readSandboxStartupDiagnostic(
26
+ diagnosticsPath: string | undefined,
27
+ ): SandboxStartupDiagnostic | undefined {
28
+ if (!diagnosticsPath) return undefined;
29
+ try {
30
+ const stat = fs.lstatSync(diagnosticsPath);
31
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_DIAGNOSTIC_BYTES) return undefined;
32
+ const parsed: unknown = JSON.parse(fs.readFileSync(diagnosticsPath, "utf-8"));
33
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
34
+ const record = parsed as { version?: unknown; profile?: unknown; reason?: unknown };
35
+ if (record.version !== 1) return undefined;
36
+ if (typeof record.reason !== "string" || !record.reason.trim()) return undefined;
37
+ const profile = typeof record.profile === "string" && record.profile.trim() ? record.profile : undefined;
38
+ const diagnostic: SandboxStartupDiagnostic = { version: 1, reason: record.reason.trim() };
39
+ if (profile !== undefined) diagnostic.profile = profile;
40
+ return diagnostic;
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ }
45
+
46
+ /** Best-effort removal so a stale diagnostic cannot describe a later attempt. */
47
+ export function clearSandboxStartupDiagnostic(diagnosticsPath: string | undefined): void {
48
+ if (!diagnosticsPath) return;
49
+ try {
50
+ fs.rmSync(diagnosticsPath, { force: true });
51
+ } catch {
52
+ // Best effort: the diagnostics directory lives in the transient temp root.
53
+ }
54
+ }
@@ -71,6 +71,7 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
71
71
  maxSubagentDepth: agent.maxSubagentDepth,
72
72
  completionGuard: agent.completionGuard,
73
73
  toolBudget: agent.toolBudget,
74
+ sandbox: agent.sandbox,
74
75
  memory: agent.memory,
75
76
  };
76
77
  }
@@ -100,6 +101,7 @@ export interface LaunchBindingInput {
100
101
  mcpDirectTools?: string[];
101
102
  outputPath?: string;
102
103
  outputMode?: string;
104
+ sandbox?: string;
103
105
  structuredOutputSchema?: unknown;
104
106
  extensionBindings?: ExtensionBindings;
105
107
  }
@@ -128,6 +130,7 @@ export function projectLaunchBinding(input: LaunchBindingInput): Record<string,
128
130
  mcpDirectTools: input.mcpDirectTools,
129
131
  outputPath: input.outputPath,
130
132
  outputMode: input.outputMode,
133
+ sandbox: input.sandbox,
131
134
  structuredOutputSchema: input.structuredOutputSchema,
132
135
  extensionBindings: input.extensionBindings,
133
136
  };
@@ -0,0 +1,23 @@
1
+ /** Shared wire contract for selecting a pi-sandbox profile in a child Pi process. */
2
+ export const SUBAGENT_SANDBOX_PROFILE_ENV = "PI_SUBAGENT_SANDBOX_PROFILE";
3
+ /** Parent-authoritative project trust snapshot for profile-aware child config loading. */
4
+ export const SUBAGENT_SANDBOX_PROJECT_TRUST_ENV = "PI_SUBAGENT_SANDBOX_PROJECT_TRUSTED";
5
+
6
+ const MAX_SANDBOX_PROFILE_NAME_LENGTH = 128;
7
+ const SANDBOX_PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
8
+
9
+ export function validateSandboxProfileName(value: unknown, label = "sandbox profile"): string {
10
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) {
11
+ throw new Error(`${label} must be a non-empty profile name without surrounding whitespace.`);
12
+ }
13
+ if (value === "false") {
14
+ throw new Error(`${label} must select a named profile; the literal false is not supported.`);
15
+ }
16
+ if (value.length > MAX_SANDBOX_PROFILE_NAME_LENGTH) {
17
+ throw new Error(`${label} must be at most ${MAX_SANDBOX_PROFILE_NAME_LENGTH} characters.`);
18
+ }
19
+ if (!SANDBOX_PROFILE_NAME_PATTERN.test(value)) {
20
+ throw new Error(`${label} must contain only letters, digits, underscores, or hyphens and start with a letter or digit.`);
21
+ }
22
+ return value;
23
+ }
@@ -786,6 +786,7 @@ export interface SteeringRecoveryDescriptor {
786
786
  sourceRunId: string;
787
787
  agentContract?: AgentContract;
788
788
  agent: string;
789
+ sandbox?: string;
789
790
  sessionFile?: string;
790
791
  /** Git ref used to allocate managed worktrees for this run. */
791
792
  baseRef?: string;
@@ -839,7 +840,7 @@ export interface SteeringRecoveryDescriptor {
839
840
 
840
841
  export type PublicNestedStepSummary = Pick<
841
842
  NestedStepSummary,
842
- "agent" | "sessionName" | "status" | "model" | "thinking" | "sessionFile" | "transcriptPath" | "transcriptError" | "activityState" | "lastActivityAt" | "currentTool" | "currentToolStartedAt" | "currentPath" | "turnCount" | "toolCount" | "toolBudget" | "toolBudgetBlocked" | "startedAt" | "endedAt" | "error" | "timedOut" | "stopped"
843
+ "agent" | "sessionName" | "status" | "model" | "thinking" | "sandbox" | "sessionFile" | "transcriptPath" | "transcriptError" | "activityState" | "lastActivityAt" | "currentTool" | "currentToolStartedAt" | "currentPath" | "turnCount" | "toolCount" | "toolBudget" | "toolBudgetBlocked" | "startedAt" | "endedAt" | "error" | "timedOut" | "stopped"
843
844
  > & {
844
845
  children?: PublicNestedRunSummary[];
845
846
  };
@@ -852,7 +853,7 @@ export type CostSummary = {
852
853
 
853
854
  export type PublicNestedRunSummary = Pick<
854
855
  NestedRunSummary,
855
- "id" | "parentRunId" | "parentStepIndex" | "parentAgent" | "depth" | "path" | "asyncDir" | "sessionId" | "sessionFile" | "intercomTarget" | "ownerIntercomTarget" | "leafIntercomTarget" | "ownerState" | "mode" | "state" | "agent" | "sessionName" | "agents" | "model" | "thinking" | "currentStep" | "chainStepCount" | "parallelGroups" | "activityState" | "lastActivityAt" | "currentTool" | "currentToolStartedAt" | "currentPath" | "turnCount" | "toolCount" | "toolBudget" | "toolBudgetBlocked" | "totalTokens" | "totalCost" | "startedAt" | "endedAt" | "lastUpdate" | "error" | "timeoutMs" | "deadlineAt" | "timedOut" | "stopped" | "turnBudget" | "turnBudgetExceeded" | "wrapUpRequested"
856
+ "id" | "parentRunId" | "parentStepIndex" | "parentAgent" | "depth" | "path" | "asyncDir" | "sessionId" | "sessionFile" | "intercomTarget" | "ownerIntercomTarget" | "leafIntercomTarget" | "ownerState" | "mode" | "state" | "agent" | "sessionName" | "agents" | "model" | "thinking" | "sandbox" | "currentStep" | "chainStepCount" | "parallelGroups" | "activityState" | "lastActivityAt" | "currentTool" | "currentToolStartedAt" | "currentPath" | "turnCount" | "toolCount" | "toolBudget" | "toolBudgetBlocked" | "totalTokens" | "totalCost" | "startedAt" | "endedAt" | "lastUpdate" | "error" | "timeoutMs" | "deadlineAt" | "timedOut" | "stopped" | "turnBudget" | "turnBudgetExceeded" | "wrapUpRequested"
856
857
  > & {
857
858
  steps?: PublicNestedStepSummary[];
858
859
  children?: PublicNestedRunSummary[];
@@ -1240,6 +1241,7 @@ export interface SingleResult {
1240
1241
  wrapUpRequested?: boolean;
1241
1242
  toolBudget?: ToolBudgetState;
1242
1243
  toolBudgetBlocked?: boolean;
1244
+ sandbox?: string;
1243
1245
  messages?: Message[];
1244
1246
  usage: Usage;
1245
1247
  model?: string;
@@ -1256,6 +1258,13 @@ export interface SingleResult {
1256
1258
  * a signal to reduce input size or re-decompose the task.
1257
1259
  */
1258
1260
  contextOverflow?: boolean;
1261
+ /**
1262
+ * True when the child never reached its first model turn because a startup
1263
+ * guard blocked it (for example a required sandbox profile that failed to
1264
+ * initialize). Retrying another model cannot succeed, and the failure must
1265
+ * not be recorded as a model exclusion.
1266
+ */
1267
+ startupBlocked?: boolean;
1259
1268
  sessionFile?: string;
1260
1269
  skills?: string[];
1261
1270
  skillsWarning?: string;
@@ -1565,6 +1574,7 @@ export interface NestedStepSummary {
1565
1574
  wrapUpRequested?: boolean;
1566
1575
  toolBudget?: ToolBudgetState;
1567
1576
  toolBudgetBlocked?: boolean;
1577
+ sandbox?: string;
1568
1578
  processTerminal?: ProcessTerminalV1;
1569
1579
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
1570
1580
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
@@ -1594,6 +1604,7 @@ export interface NestedRunSummary extends NestedRunAddress {
1594
1604
  agent?: string;
1595
1605
  /** Human-readable display name for the child session, when derived at launch. */
1596
1606
  sessionName?: string;
1607
+ sandbox?: string;
1597
1608
  agents?: string[];
1598
1609
  model?: string;
1599
1610
  thinking?: string;
@@ -1657,6 +1668,7 @@ export interface AsyncStartedEvent {
1657
1668
  workflowGraph?: WorkflowGraphSnapshot;
1658
1669
  preflight?: WorkflowPreflightV1;
1659
1670
  launchContractDigest?: string;
1671
+ sandbox?: string;
1660
1672
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
1661
1673
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
1662
1674
  usageBudget?: UsageBudgetState;
@@ -1828,6 +1840,7 @@ export interface AsyncStatus {
1828
1840
  runFanoutBudget?: RunFanoutBudgetSnapshot;
1829
1841
  runFanoutBudgetDescriptor?: RunFanoutBudgetDescriptor;
1830
1842
  launchContractDigest?: string;
1843
+ sandbox?: string;
1831
1844
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
1832
1845
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
1833
1846
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
@@ -1919,6 +1932,7 @@ export interface AsyncStatus {
1919
1932
  acceptance?: AcceptanceLedger;
1920
1933
  agentContract?: AgentContract;
1921
1934
  launchContractDigest?: string;
1935
+ sandbox?: string;
1922
1936
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
1923
1937
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
1924
1938
  execution?: ExecutionProjection;
@@ -2054,6 +2068,7 @@ export interface ForegroundResumeChild {
2054
2068
  outputMode?: OutputMode;
2055
2069
  };
2056
2070
  launchContractDigest?: string;
2071
+ sandbox?: string;
2057
2072
  /** Private retained launch authority. Never project into status or result output. */
2058
2073
  extensionBindings?: ExtensionBindings;
2059
2074
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
@@ -2360,6 +2375,8 @@ export interface RunSyncOptions {
2360
2375
  configToolTimeoutMs?: number;
2361
2376
  usageBudget?: UsageBudgetConfig;
2362
2377
  toolBudget?: ResolvedToolBudget;
2378
+ /** Selected global sandbox profile, when this child requested one. */
2379
+ sandbox?: string;
2363
2380
  allowZeroToolBudget?: boolean;
2364
2381
  allowIntercomDetach?: boolean;
2365
2382
  intercomEvents?: IntercomEventBus;
@@ -2393,6 +2410,10 @@ export interface RunSyncOptions {
2393
2410
  /** Effective parent default wait window propagated to the child runtime. */
2394
2411
  waitToolDefaultTimeoutMs?: number;
2395
2412
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
2413
+ /** Whether project-scoped agent/config inputs were trusted by the host. */
2414
+ projectTrusted?: boolean;
2415
+ /** Exact trusted parent cwd; project config applies only when it matches this child cwd. */
2416
+ trustedProjectCwd?: string;
2396
2417
  runFanoutBudget?: RunFanoutBudgetDescriptor;
2397
2418
  nestedRoute?: NestedRouteInfo;
2398
2419
  /** Override the agent's default model (format: "provider/id" or just "id") */
@@ -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
+ }