@xzzpig/pi-subagents 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +1 -1
- package/docs/agents.md +3 -125
- package/docs/extension-api.md +0 -55
- package/docs/fork-extensions.md +192 -0
- package/package.json +1 -1
- package/src/agents/agent-eject.ts +339 -0
- package/src/agents/agent-management.ts +8 -328
- package/src/api/agent-management.ts +2 -2
- package/src/api/preflight.ts +21 -15
- package/src/runs/background/async-status.ts +6 -22
- package/src/runs/background/subagent-runner.ts +4 -12
- package/src/runs/foreground/subagent-executor.ts +19 -14
- package/src/runs/shared/child-launch.ts +5 -69
- package/src/runs/shared/child-tool-plan.ts +7 -101
- package/src/runs/shared/nested-events.ts +8 -24
- package/src/runs/shared/profile-extensions.ts +134 -0
- package/src/runs/shared/profile-launch-env.ts +121 -0
- package/src/runs/shared/sandbox-profile-guard.ts +34 -0
- package/src/shared/permission-profile.ts +14 -0
- package/src/shared/sandbox-profile.ts +14 -0
|
@@ -6,20 +6,16 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import * as fs from "node:fs";
|
|
8
8
|
import * as path from "node:path";
|
|
9
|
-
import { randomUUID } from "node:crypto";
|
|
10
9
|
import type { ChildWatchdogConfig, ChildWatchdogStatusEvent } from "../../watchdog/child-status.ts";
|
|
11
10
|
import type { ThinkingLevel } from "../../shared/model-info.ts";
|
|
12
11
|
import { intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
|
|
13
12
|
import {
|
|
14
|
-
TEMP_ROOT_DIR,
|
|
15
13
|
resolveChildDepth,
|
|
16
14
|
type LaunchResolvedChildExtensions,
|
|
17
15
|
type ResolvedToolBudget,
|
|
18
16
|
type RunFanoutBudgetDescriptor,
|
|
19
17
|
type HerdrMachineReference,
|
|
20
18
|
} from "../../shared/types.ts";
|
|
21
|
-
import { SUBAGENT_SANDBOX_PROFILE_ENV, SUBAGENT_SANDBOX_PROJECT_TRUST_ENV } from "../../shared/sandbox-profile.ts";
|
|
22
|
-
import { SUBAGENT_PERMISSION_PROFILE_ENV, SUBAGENT_PERMISSION_PROFILE_PINNED_ENV } from "../../shared/permission-profile.ts";
|
|
23
19
|
import type { NestedPathEntry } from "./nested-path.ts";
|
|
24
20
|
import type { McpRuntimeSnapshotHost } from "./mcp-direct-tool-allowlist.ts";
|
|
25
21
|
import type { PermissionRules } from "./permissions.ts";
|
|
@@ -27,8 +23,8 @@ import type { StructuredOutputRuntime } from "./structured-output.ts";
|
|
|
27
23
|
import type { ChildToolDiagnostic } from "./tool-availability.ts";
|
|
28
24
|
import type { RuntimeAcknowledgedChildExtensions } from "../../shared/types.ts";
|
|
29
25
|
import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV, type ExtensionBindings } from "./extension-bindings.ts";
|
|
30
|
-
import { SANDBOX_DIAGNOSTICS_PATH_ENV } from "./sandbox-startup-diagnostics.ts";
|
|
31
26
|
import type { ResolvedSubagentCapabilityCeiling, SubagentCapabilityAudit } from "./capability-ceiling.ts";
|
|
27
|
+
import { buildProfileLaunchEnv } from "./profile-launch-env.ts";
|
|
32
28
|
import {
|
|
33
29
|
isSubagentRuntimeExtensionPath,
|
|
34
30
|
projectLaunchResolvedChildExtensions,
|
|
@@ -46,18 +42,6 @@ import { resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } f
|
|
|
46
42
|
/** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
|
|
47
43
|
export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
|
|
48
44
|
|
|
49
|
-
const SANDBOX_STARTUP_ACK_PATH_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_PATH";
|
|
50
|
-
const SANDBOX_STARTUP_ACK_TOKEN_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_TOKEN";
|
|
51
|
-
// Marks an in-process child so child extensions never mutate the host process
|
|
52
|
-
// state (for example a profile-failure exit code) that a separate child process
|
|
53
|
-
// would legitimately own.
|
|
54
|
-
const IN_PROCESS_CHILD_ENV = "PI_SUBAGENT_SANDBOX_IN_PROCESS_CHILD";
|
|
55
|
-
|
|
56
|
-
function hasTrustedProfileProjectCwd(input: Pick<BuildInProcessChildLaunchInput, "cwd" | "projectTrusted" | "trustedProjectCwd">): boolean {
|
|
57
|
-
if (input.projectTrusted !== true || !input.cwd || !input.trustedProjectCwd) return false;
|
|
58
|
-
return path.resolve(input.cwd) === path.resolve(input.trustedProjectCwd);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
45
|
/**
|
|
62
46
|
* The parts of the launching executor's own child runtime that a child it
|
|
63
47
|
* launches inherits. Serialized into the background runner config; the
|
|
@@ -241,58 +225,10 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
|
|
|
241
225
|
hostAvailableBuiltins: input.hostAvailableBuiltins,
|
|
242
226
|
});
|
|
243
227
|
|
|
244
|
-
//
|
|
245
|
-
//
|
|
246
|
-
//
|
|
247
|
-
|
|
248
|
-
const sandboxAckPath = toolPlan.sandboxExtension && input.sandbox !== undefined
|
|
249
|
-
? path.join(TEMP_ROOT_DIR, "sandbox-profile-acks", `${randomUUID()}.json`)
|
|
250
|
-
: undefined;
|
|
251
|
-
const sandboxDiagnosticsPath = sandboxAckPath
|
|
252
|
-
? path.join(TEMP_ROOT_DIR, "sandbox-profile-diagnostics", `${randomUUID()}.json`)
|
|
253
|
-
: undefined;
|
|
254
|
-
const sandboxEnv: Record<string, string | undefined> | undefined = sandboxAckPath
|
|
255
|
-
? {
|
|
256
|
-
[SUBAGENT_SANDBOX_PROFILE_ENV]: input.sandbox,
|
|
257
|
-
[SUBAGENT_SANDBOX_PROJECT_TRUST_ENV]: hasTrustedProfileProjectCwd(input) ? "1" : "0",
|
|
258
|
-
[SANDBOX_STARTUP_ACK_PATH_ENV]: sandboxAckPath,
|
|
259
|
-
[SANDBOX_STARTUP_ACK_TOKEN_ENV]: randomUUID(),
|
|
260
|
-
[SANDBOX_DIAGNOSTICS_PATH_ENV]: sandboxDiagnosticsPath,
|
|
261
|
-
...(input.host === "parent" ? { [IN_PROCESS_CHILD_ENV]: "1" } : {}),
|
|
262
|
-
}
|
|
263
|
-
: undefined;
|
|
264
|
-
if (sandboxAckPath) fs.mkdirSync(path.dirname(sandboxAckPath), { recursive: true, mode: 0o700 });
|
|
265
|
-
|
|
266
|
-
// A selected permission profile travels as a bare validated name (the rules
|
|
267
|
-
// live in the child's global pi-permission-system config). The key is
|
|
268
|
-
// transient like the sandbox keys: restored on the host once the child
|
|
269
|
-
// session exists.
|
|
270
|
-
const permissionProfileEnv: Record<string, string | undefined> | undefined =
|
|
271
|
-
input.permissionProfile !== undefined
|
|
272
|
-
? { [SUBAGENT_PERMISSION_PROFILE_ENV]: input.permissionProfile }
|
|
273
|
-
: undefined;
|
|
274
|
-
const childEnv: Record<string, string | undefined> | undefined =
|
|
275
|
-
sandboxEnv !== undefined || permissionProfileEnv !== undefined
|
|
276
|
-
? { ...(sandboxEnv ?? {}), ...(permissionProfileEnv ?? {}) }
|
|
277
|
-
: undefined;
|
|
278
|
-
// The profile key is pinned for every launch, `undefined` included: a child
|
|
279
|
-
// that declares no profile must not inherit the host session's role
|
|
280
|
-
// selection, and one that declares a profile must not be overridden by it
|
|
281
|
-
// (the launcher env wins inside pi-permission-system). It is kept out of
|
|
282
|
-
// `childEnv` so a plain in-process child does not also start receiving the
|
|
283
|
-
// binding and MCP values that only a runner-hosted child used to get.
|
|
284
|
-
const profilePin: Record<string, string | undefined> = {
|
|
285
|
-
[SUBAGENT_PERMISSION_PROFILE_ENV]: input.permissionProfile,
|
|
286
|
-
// Present for every child launch: it is what tells pi-permission-system
|
|
287
|
-
// this selection is authoritative for the child (see the constant).
|
|
288
|
-
[SUBAGENT_PERMISSION_PROFILE_PINNED_ENV]: "1",
|
|
289
|
-
};
|
|
290
|
-
const transientProcessEnv = [
|
|
291
|
-
...new Set([
|
|
292
|
-
...(childEnv ? Object.keys(childEnv) : []),
|
|
293
|
-
...Object.keys(profilePin),
|
|
294
|
-
]),
|
|
295
|
-
];
|
|
228
|
+
// Profile env construction (ack/diagnostics paths, sandbox and permission
|
|
229
|
+
// profile keys, the pinned profile, and the transient host key list) lives
|
|
230
|
+
// in the fork-only profile-launch-env module.
|
|
231
|
+
const { childEnv, profilePin, transientProcessEnv, sandboxDiagnosticsPath } = buildProfileLaunchEnv(input, toolPlan);
|
|
296
232
|
|
|
297
233
|
const inherited = input.inherited;
|
|
298
234
|
const fanout = toolPlan.fanoutAuthorized;
|
|
@@ -21,9 +21,8 @@ import {
|
|
|
21
21
|
} from "../../shared/types.ts";
|
|
22
22
|
import { THINKING_LEVELS } from "../../shared/model-info.ts";
|
|
23
23
|
import { getAgentDir } from "../../shared/utils.ts";
|
|
24
|
-
import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
|
|
25
|
-
import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
|
|
26
24
|
import type { PermissionRules } from "./permissions.ts";
|
|
25
|
+
import { resolveProfileExtensions } from "./profile-extensions.ts";
|
|
27
26
|
import { snapshotRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
|
|
28
27
|
import {
|
|
29
28
|
capabilityCeilingAgentRestrictionSources,
|
|
@@ -362,72 +361,6 @@ export function resolvePermissionSystemExtension(): string | undefined {
|
|
|
362
361
|
return undefined;
|
|
363
362
|
}
|
|
364
363
|
|
|
365
|
-
export function resolveSandboxExtensionForProfile(profileName: string): string {
|
|
366
|
-
validateSandboxProfileName(profileName, "sandbox profile");
|
|
367
|
-
return resolveSandboxExtension();
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
function resolveSandboxExtension(): string {
|
|
371
|
-
const agentDir = getAgentDir();
|
|
372
|
-
const candidates = [
|
|
373
|
-
path.join(agentDir, "npm", "node_modules", "@xzzpig", "pi-sandbox"),
|
|
374
|
-
path.join(agentDir, "npm", "node_modules", "pi-sandbox"),
|
|
375
|
-
path.join(agentDir, "extensions", "pi-sandbox"),
|
|
376
|
-
];
|
|
377
|
-
const errors: Error[] = [];
|
|
378
|
-
let foundPackage = false;
|
|
379
|
-
for (const extDir of candidates) {
|
|
380
|
-
if (!fs.existsSync(extDir)) continue;
|
|
381
|
-
foundPackage = true;
|
|
382
|
-
const pkgPath = path.join(extDir, "package.json");
|
|
383
|
-
if (!fs.existsSync(pkgPath)) {
|
|
384
|
-
errors.push(new Error(`Sandbox package manifest is missing at ${pkgPath}.`));
|
|
385
|
-
continue;
|
|
386
|
-
}
|
|
387
|
-
try {
|
|
388
|
-
const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
389
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
390
|
-
throw new Error("manifest root must be an object");
|
|
391
|
-
}
|
|
392
|
-
const manifest = parsed as { name?: unknown; pi?: { extensions?: unknown } };
|
|
393
|
-
if (manifest.name !== "@xzzpig/pi-sandbox" && manifest.name !== "pi-sandbox") {
|
|
394
|
-
throw new Error(`Sandbox package manifest at ${pkgPath} must declare name '@xzzpig/pi-sandbox' or 'pi-sandbox'.`);
|
|
395
|
-
}
|
|
396
|
-
const extensions = manifest.pi?.extensions;
|
|
397
|
-
const entry = Array.isArray(extensions) ? extensions[0] : undefined;
|
|
398
|
-
if (typeof entry !== "string" || !entry.trim()) {
|
|
399
|
-
throw new Error(`Sandbox package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`);
|
|
400
|
-
}
|
|
401
|
-
if (path.isAbsolute(entry)) {
|
|
402
|
-
throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must be relative to the package directory.`);
|
|
403
|
-
}
|
|
404
|
-
const resolved = path.resolve(extDir, entry);
|
|
405
|
-
const relative = path.relative(extDir, resolved);
|
|
406
|
-
if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
407
|
-
throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must remain inside ${extDir}.`);
|
|
408
|
-
}
|
|
409
|
-
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
|
|
410
|
-
throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} does not resolve to a file at ${resolved}.`);
|
|
411
|
-
}
|
|
412
|
-
const realPackageRoot = fs.realpathSync(extDir);
|
|
413
|
-
const realEntry = fs.realpathSync(resolved);
|
|
414
|
-
const realRelative = path.relative(realPackageRoot, realEntry);
|
|
415
|
-
if (!realRelative || realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
|
|
416
|
-
throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} resolves outside ${extDir}.`);
|
|
417
|
-
}
|
|
418
|
-
return resolved;
|
|
419
|
-
} catch (error) {
|
|
420
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
421
|
-
errors.push(message.startsWith("Sandbox") ? new Error(message) : new Error(`Cannot read sandbox package manifest at ${pkgPath}: ${message}`));
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
if (errors.length > 0) throw errors[0]!;
|
|
425
|
-
if (!foundPackage) {
|
|
426
|
-
throw new Error(`pi-sandbox is not installed; cannot launch a child with sandbox profile.`);
|
|
427
|
-
}
|
|
428
|
-
throw new Error(`No usable pi-sandbox extension manifest was found under '${agentDir}'.`);
|
|
429
|
-
}
|
|
430
|
-
|
|
431
364
|
/**
|
|
432
365
|
* Extract the names of builtin tools the host provides. Use this to pass
|
|
433
366
|
* `hostAvailableBuiltins` to `resolvePiLaunchToolPlan` so child tool plans
|
|
@@ -579,39 +512,12 @@ export function resolvePiLaunchToolPlan(
|
|
|
579
512
|
: hasPermissionRules(input.permissionRules)
|
|
580
513
|
? resolvePermissionSystemExtension()
|
|
581
514
|
: undefined;
|
|
582
|
-
const
|
|
583
|
-
|
|
584
|
-
:
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
}
|
|
588
|
-
const permissionProfile = input.permissionProfile === undefined
|
|
589
|
-
? undefined
|
|
590
|
-
: validatePermissionProfileName(input.permissionProfile, "permission profile");
|
|
591
|
-
if (permissionProfile && capabilityCeiling?.denyExtensions) {
|
|
592
|
-
throw new Error(`Permission profile '${permissionProfile}' requires the pi-permission-system child extension, but this launch denies child extensions.`);
|
|
593
|
-
}
|
|
594
|
-
// A permission-profile-only agent has no native `permissionRules` yet still
|
|
595
|
-
// needs the permission system in the child to resolve the profile: without
|
|
596
|
-
// it the selection would silently degrade to no policy at all. Resolve the
|
|
597
|
-
// extension eagerly for this path and fail the launch when the package is
|
|
598
|
-
// missing (the rules-only path keeps its soft resolution as before).
|
|
599
|
-
const permSystemExtForProfile = permissionProfile !== undefined && permSystemExt === undefined
|
|
600
|
-
? resolvePermissionSystemExtension()
|
|
601
|
-
: undefined;
|
|
602
|
-
if (permissionProfile !== undefined && permSystemExt === undefined && permSystemExtForProfile === undefined) {
|
|
603
|
-
throw new Error(`Permission profile '${permissionProfile}' cannot be enabled: pi-permission-system is not installed; cannot launch a child with a permission profile.`);
|
|
604
|
-
}
|
|
605
|
-
const effectivePermSystemExt = permSystemExt ?? permSystemExtForProfile;
|
|
606
|
-
let sandboxExtension: string | undefined;
|
|
607
|
-
if (sandboxProfile) {
|
|
608
|
-
try {
|
|
609
|
-
sandboxExtension = resolveSandboxExtensionForProfile(sandboxProfile);
|
|
610
|
-
} catch (error) {
|
|
611
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
612
|
-
throw new Error(`Sandbox profile '${sandboxProfile}' cannot be enabled: ${message}`);
|
|
613
|
-
}
|
|
614
|
-
}
|
|
515
|
+
const { sandboxExtension, effectivePermSystemExt } = resolveProfileExtensions({
|
|
516
|
+
sandbox: input.sandbox,
|
|
517
|
+
permissionProfile: input.permissionProfile,
|
|
518
|
+
capabilityCeiling,
|
|
519
|
+
permSystemExt,
|
|
520
|
+
});
|
|
615
521
|
if (input.fast && capabilityCeiling?.denyExtensions) throw new Error("fast mode requires a child runtime extension, but this launch denies extensions.");
|
|
616
522
|
const fastModeExtensions = resolveFastModeExtension({ fast: input.fast, model: input.model, agentName: input.agentName });
|
|
617
523
|
const runtimeExtensions = [
|
|
@@ -20,8 +20,8 @@ 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 {
|
|
24
|
-
import {
|
|
23
|
+
import { validateSandboxProfileNameOptional } from "../../shared/sandbox-profile.ts";
|
|
24
|
+
import { validatePermissionProfileNameOptional } from "../../shared/permission-profile.ts";
|
|
25
25
|
|
|
26
26
|
export const NESTED_EVENTS_DIR = path.join(TEMP_ROOT_DIR, "nested-subagent-events");
|
|
27
27
|
const ROUTE_FILE = "route.json";
|
|
@@ -305,22 +305,6 @@ function sanitizeState(value: unknown, fallback: NestedRunState): NestedRunState
|
|
|
305
305
|
: fallback;
|
|
306
306
|
}
|
|
307
307
|
|
|
308
|
-
function sandboxProfileValue(value: unknown): string | undefined {
|
|
309
|
-
try {
|
|
310
|
-
return validateSandboxProfileName(value);
|
|
311
|
-
} catch {
|
|
312
|
-
return undefined;
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
function permissionProfileValue(value: unknown): string | undefined {
|
|
317
|
-
try {
|
|
318
|
-
return validatePermissionProfileName(value);
|
|
319
|
-
} catch {
|
|
320
|
-
return undefined;
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
324
308
|
function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefined {
|
|
325
309
|
if (!input || typeof input !== "object") return undefined;
|
|
326
310
|
const raw = input as Record<string, unknown>;
|
|
@@ -331,8 +315,8 @@ function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefi
|
|
|
331
315
|
: "pending";
|
|
332
316
|
const model = stringValue(raw.model);
|
|
333
317
|
const thinking = THINKING_LEVELS.find((level) => level === raw.thinking);
|
|
334
|
-
const sandbox =
|
|
335
|
-
const permissionProfile =
|
|
318
|
+
const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
|
|
319
|
+
const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
|
|
336
320
|
return {
|
|
337
321
|
agent,
|
|
338
322
|
status,
|
|
@@ -373,8 +357,8 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
|
|
|
373
357
|
: undefined;
|
|
374
358
|
const totalTokens = sanitizeTokenUsage(raw.totalTokens);
|
|
375
359
|
const totalCost = sanitizeCost(raw.totalCost);
|
|
376
|
-
const sandbox =
|
|
377
|
-
const permissionProfile =
|
|
360
|
+
const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
|
|
361
|
+
const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
|
|
378
362
|
return {
|
|
379
363
|
id: raw.id,
|
|
380
364
|
parentRunId: raw.parentRunId,
|
|
@@ -1025,7 +1009,7 @@ export function hasLiveNestedDescendants(children: NestedRunSummary[] | undefine
|
|
|
1025
1009
|
}
|
|
1026
1010
|
|
|
1027
1011
|
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 {
|
|
1028
|
-
const sandbox =
|
|
1012
|
+
const sandbox = validateSandboxProfileNameOptional(status.sandbox);
|
|
1029
1013
|
return {
|
|
1030
1014
|
id: status.runId || fallback.id,
|
|
1031
1015
|
parentRunId: fallback.parentRunId,
|
|
@@ -1070,7 +1054,7 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
|
|
|
1070
1054
|
...(status.sessionFile ? { sessionFile: status.sessionFile } : {}),
|
|
1071
1055
|
...(status.steps?.length ? {
|
|
1072
1056
|
steps: status.steps.map((step, index) => {
|
|
1073
|
-
const stepSandbox =
|
|
1057
|
+
const stepSandbox = validateSandboxProfileNameOptional(step.sandbox);
|
|
1074
1058
|
return {
|
|
1075
1059
|
agent: step.agent,
|
|
1076
1060
|
...(step.sessionName ? { sessionName: step.sessionName } : {}),
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [fork] Sandbox/permission-profile child-extension resolution. Split out of
|
|
3
|
+
* child-tool-plan.ts so the shared tool planner keeps only the call site: the
|
|
4
|
+
* profile validation, the sandbox extension lookup, and the permission-system
|
|
5
|
+
* fallback for profile-only agents live here.
|
|
6
|
+
*/
|
|
7
|
+
import * as fs from "node:fs";
|
|
8
|
+
import * as path from "node:path";
|
|
9
|
+
import { getAgentDir } from "../../shared/utils.ts";
|
|
10
|
+
import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
|
|
11
|
+
import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
|
|
12
|
+
import type { ResolvedSubagentCapabilityCeiling } from "./capability-ceiling.ts";
|
|
13
|
+
import { resolvePermissionSystemExtension } from "./child-tool-plan.ts";
|
|
14
|
+
|
|
15
|
+
export function resolveSandboxExtensionForProfile(profileName: string): string {
|
|
16
|
+
validateSandboxProfileName(profileName, "sandbox profile");
|
|
17
|
+
return resolveSandboxExtension();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function resolveSandboxExtension(): string {
|
|
21
|
+
const agentDir = getAgentDir();
|
|
22
|
+
const candidates = [
|
|
23
|
+
path.join(agentDir, "npm", "node_modules", "@xzzpig", "pi-sandbox"),
|
|
24
|
+
path.join(agentDir, "npm", "node_modules", "pi-sandbox"),
|
|
25
|
+
path.join(agentDir, "extensions", "pi-sandbox"),
|
|
26
|
+
];
|
|
27
|
+
const errors: Error[] = [];
|
|
28
|
+
let foundPackage = false;
|
|
29
|
+
for (const extDir of candidates) {
|
|
30
|
+
if (!fs.existsSync(extDir)) continue;
|
|
31
|
+
foundPackage = true;
|
|
32
|
+
const pkgPath = path.join(extDir, "package.json");
|
|
33
|
+
if (!fs.existsSync(pkgPath)) {
|
|
34
|
+
errors.push(new Error(`Sandbox package manifest is missing at ${pkgPath}.`));
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
39
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
40
|
+
throw new Error("manifest root must be an object");
|
|
41
|
+
}
|
|
42
|
+
const manifest = parsed as { name?: unknown; pi?: { extensions?: unknown } };
|
|
43
|
+
if (manifest.name !== "@xzzpig/pi-sandbox" && manifest.name !== "pi-sandbox") {
|
|
44
|
+
throw new Error(`Sandbox package manifest at ${pkgPath} must declare name '@xzzpig/pi-sandbox' or 'pi-sandbox'.`);
|
|
45
|
+
}
|
|
46
|
+
const extensions = manifest.pi?.extensions;
|
|
47
|
+
const entry = Array.isArray(extensions) ? extensions[0] : undefined;
|
|
48
|
+
if (typeof entry !== "string" || !entry.trim()) {
|
|
49
|
+
throw new Error(`Sandbox package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`);
|
|
50
|
+
}
|
|
51
|
+
if (path.isAbsolute(entry)) {
|
|
52
|
+
throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must be relative to the package directory.`);
|
|
53
|
+
}
|
|
54
|
+
const resolved = path.resolve(extDir, entry);
|
|
55
|
+
const relative = path.relative(extDir, resolved);
|
|
56
|
+
if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
57
|
+
throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must remain inside ${extDir}.`);
|
|
58
|
+
}
|
|
59
|
+
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
|
|
60
|
+
throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} does not resolve to a file at ${resolved}.`);
|
|
61
|
+
}
|
|
62
|
+
const realPackageRoot = fs.realpathSync(extDir);
|
|
63
|
+
const realEntry = fs.realpathSync(resolved);
|
|
64
|
+
const realRelative = path.relative(realPackageRoot, realEntry);
|
|
65
|
+
if (!realRelative || realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
|
|
66
|
+
throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} resolves outside ${extDir}.`);
|
|
67
|
+
}
|
|
68
|
+
return resolved;
|
|
69
|
+
} catch (error) {
|
|
70
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
71
|
+
errors.push(message.startsWith("Sandbox") ? new Error(message) : new Error(`Cannot read sandbox package manifest at ${pkgPath}: ${message}`));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (errors.length > 0) throw errors[0]!;
|
|
75
|
+
if (!foundPackage) {
|
|
76
|
+
throw new Error(`pi-sandbox is not installed; cannot launch a child with sandbox profile.`);
|
|
77
|
+
}
|
|
78
|
+
throw new Error(`No usable pi-sandbox extension manifest was found under '${agentDir}'.`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface ResolvedProfileExtensions {
|
|
82
|
+
/** Absolute path of the resolved pi-sandbox child extension when a sandbox profile is selected. */
|
|
83
|
+
sandboxExtension?: string;
|
|
84
|
+
/** The permission-system child extension a launch must load: rules-driven or profile-driven. */
|
|
85
|
+
effectivePermSystemExt?: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Validate the selected sandbox/permission profiles and resolve the child
|
|
90
|
+
* extensions they require. `permSystemExt` is the rules-driven permission-system
|
|
91
|
+
* resolution the tool plan already computed; when only a permission profile is
|
|
92
|
+
* selected the extension is resolved eagerly here and a missing package fails
|
|
93
|
+
* the launch instead of silently degrading to no policy at all.
|
|
94
|
+
*/
|
|
95
|
+
export function resolveProfileExtensions(input: {
|
|
96
|
+
sandbox?: string;
|
|
97
|
+
permissionProfile?: string;
|
|
98
|
+
capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
99
|
+
permSystemExt?: string;
|
|
100
|
+
}): ResolvedProfileExtensions {
|
|
101
|
+
const { capabilityCeiling, permSystemExt } = input;
|
|
102
|
+
const sandboxProfile = input.sandbox === undefined
|
|
103
|
+
? undefined
|
|
104
|
+
: validateSandboxProfileName(input.sandbox, "sandbox profile");
|
|
105
|
+
if (sandboxProfile && capabilityCeiling?.denyExtensions) {
|
|
106
|
+
throw new Error(`Sandbox profile '${sandboxProfile}' requires the pi-sandbox child extension, but this launch denies child extensions.`);
|
|
107
|
+
}
|
|
108
|
+
const permissionProfile = input.permissionProfile === undefined
|
|
109
|
+
? undefined
|
|
110
|
+
: validatePermissionProfileName(input.permissionProfile, "permission profile");
|
|
111
|
+
if (permissionProfile && capabilityCeiling?.denyExtensions) {
|
|
112
|
+
throw new Error(`Permission profile '${permissionProfile}' requires the pi-permission-system child extension, but this launch denies child extensions.`);
|
|
113
|
+
}
|
|
114
|
+
const permSystemExtForProfile = permissionProfile !== undefined && permSystemExt === undefined
|
|
115
|
+
? resolvePermissionSystemExtension()
|
|
116
|
+
: undefined;
|
|
117
|
+
if (permissionProfile !== undefined && permSystemExt === undefined && permSystemExtForProfile === undefined) {
|
|
118
|
+
throw new Error(`Permission profile '${permissionProfile}' cannot be enabled: pi-permission-system is not installed; cannot launch a child with a permission profile.`);
|
|
119
|
+
}
|
|
120
|
+
const effectivePermSystemExt = permSystemExt ?? permSystemExtForProfile;
|
|
121
|
+
let sandboxExtension: string | undefined;
|
|
122
|
+
if (sandboxProfile) {
|
|
123
|
+
try {
|
|
124
|
+
sandboxExtension = resolveSandboxExtensionForProfile(sandboxProfile);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
127
|
+
throw new Error(`Sandbox profile '${sandboxProfile}' cannot be enabled: ${message}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
...(sandboxExtension ? { sandboxExtension } : {}),
|
|
132
|
+
...(effectivePermSystemExt ? { effectivePermSystemExt } : {}),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [fork] Launch-environment construction for sandbox/permission-profile child
|
|
3
|
+
* launches: the transient env keys the child reads, the pinned permission
|
|
4
|
+
* profile, and the startup-diagnostics channel. Split out of child-launch.ts
|
|
5
|
+
* so the shared launcher keeps only the call site and the final processEnv
|
|
6
|
+
* assembly.
|
|
7
|
+
*/
|
|
8
|
+
import * as fs from "node:fs";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { TEMP_ROOT_DIR } from "../../shared/types.ts";
|
|
12
|
+
import { SUBAGENT_SANDBOX_PROFILE_ENV, SUBAGENT_SANDBOX_PROJECT_TRUST_ENV } from "../../shared/sandbox-profile.ts";
|
|
13
|
+
import { SUBAGENT_PERMISSION_PROFILE_ENV, SUBAGENT_PERMISSION_PROFILE_PINNED_ENV } from "../../shared/permission-profile.ts";
|
|
14
|
+
import { SANDBOX_DIAGNOSTICS_PATH_ENV } from "./sandbox-startup-diagnostics.ts";
|
|
15
|
+
import type { PiLaunchToolPlan } from "./child-tool-plan.ts";
|
|
16
|
+
|
|
17
|
+
const SANDBOX_STARTUP_ACK_PATH_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_PATH";
|
|
18
|
+
const SANDBOX_STARTUP_ACK_TOKEN_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_TOKEN";
|
|
19
|
+
// Marks an in-process child so child extensions never mutate the host process
|
|
20
|
+
// state (for example a profile-failure exit code) that a separate child process
|
|
21
|
+
// would legitimately own.
|
|
22
|
+
const IN_PROCESS_CHILD_ENV = "PI_SUBAGENT_SANDBOX_IN_PROCESS_CHILD";
|
|
23
|
+
|
|
24
|
+
/** Structural subset of the child-launch input the profile env needs. */
|
|
25
|
+
export interface ProfileLaunchEnvInput {
|
|
26
|
+
cwd: string;
|
|
27
|
+
/** A validated global pi-sandbox profile selected by the agent definition. */
|
|
28
|
+
sandbox?: string;
|
|
29
|
+
/** A validated global pi-permission-system profile selected by the agent definition. */
|
|
30
|
+
permissionProfile?: string;
|
|
31
|
+
/** Parent-authoritative trust state for profile-aware project config merging. */
|
|
32
|
+
projectTrusted?: boolean;
|
|
33
|
+
/** Trusted project cwd; profile project config applies when the child cwd is within it
|
|
34
|
+
* (equal or a subdirectory), mirroring the platform's ancestor-inheriting trust decisions. */
|
|
35
|
+
trustedProjectCwd?: string;
|
|
36
|
+
host: "parent" | "runner";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ProfileLaunchEnv {
|
|
40
|
+
/** Transient env keys the child reads; only a runner-hosted child applies them. */
|
|
41
|
+
childEnv: Record<string, string | undefined> | undefined;
|
|
42
|
+
/** Pinned permission-profile selection; applied to every child launch. */
|
|
43
|
+
profilePin: Record<string, string | undefined>;
|
|
44
|
+
/** Host process env keys to restore once the child session exists. */
|
|
45
|
+
transientProcessEnv: string[];
|
|
46
|
+
/** Path a blocked child extension writes its startup failure to. */
|
|
47
|
+
sandboxDiagnosticsPath?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function hasTrustedProfileProjectCwd(input: Pick<ProfileLaunchEnvInput, "cwd" | "projectTrusted" | "trustedProjectCwd">): boolean {
|
|
51
|
+
if (input.projectTrusted !== true || !input.cwd || !input.trustedProjectCwd) return false;
|
|
52
|
+
// Platform trust is ancestor-inheriting (findNearestTrustEntry walks up from
|
|
53
|
+
// the child cwd): a child launched anywhere inside the trusted project tree —
|
|
54
|
+
// the project root or any subdirectory — inherits the trust decision observed
|
|
55
|
+
// at the trusted project cwd, so its project config participates without a
|
|
56
|
+
// separate trust decision (spec: 子目录启动继承信任).
|
|
57
|
+
const trusted = path.resolve(input.trustedProjectCwd);
|
|
58
|
+
const child = path.resolve(input.cwd);
|
|
59
|
+
return child === trusted || child.startsWith(`${trusted}${path.sep}`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function buildProfileLaunchEnv(input: ProfileLaunchEnvInput, toolPlan: Pick<PiLaunchToolPlan, "sandboxExtension">): ProfileLaunchEnv {
|
|
63
|
+
// A selected profile is validated by resolvePiLaunchToolPlan; the child
|
|
64
|
+
// receives only the profile identity, trust snapshot, and startup ack
|
|
65
|
+
// channel through its environment. Transient keys are restored after the
|
|
66
|
+
// session is created so the host process never keeps them.
|
|
67
|
+
const sandboxAckPath = toolPlan.sandboxExtension && input.sandbox !== undefined
|
|
68
|
+
? path.join(TEMP_ROOT_DIR, "sandbox-profile-acks", `${randomUUID()}.json`)
|
|
69
|
+
: undefined;
|
|
70
|
+
const sandboxDiagnosticsPath = sandboxAckPath
|
|
71
|
+
? path.join(TEMP_ROOT_DIR, "sandbox-profile-diagnostics", `${randomUUID()}.json`)
|
|
72
|
+
: undefined;
|
|
73
|
+
const sandboxEnv: Record<string, string | undefined> | undefined = sandboxAckPath
|
|
74
|
+
? {
|
|
75
|
+
[SUBAGENT_SANDBOX_PROFILE_ENV]: input.sandbox,
|
|
76
|
+
[SUBAGENT_SANDBOX_PROJECT_TRUST_ENV]: hasTrustedProfileProjectCwd(input) ? "1" : "0",
|
|
77
|
+
[SANDBOX_STARTUP_ACK_PATH_ENV]: sandboxAckPath,
|
|
78
|
+
[SANDBOX_STARTUP_ACK_TOKEN_ENV]: randomUUID(),
|
|
79
|
+
[SANDBOX_DIAGNOSTICS_PATH_ENV]: sandboxDiagnosticsPath,
|
|
80
|
+
...(input.host === "parent" ? { [IN_PROCESS_CHILD_ENV]: "1" } : {}),
|
|
81
|
+
}
|
|
82
|
+
: undefined;
|
|
83
|
+
if (sandboxAckPath) fs.mkdirSync(path.dirname(sandboxAckPath), { recursive: true, mode: 0o700 });
|
|
84
|
+
|
|
85
|
+
// A selected permission profile travels as a bare validated name (the rules
|
|
86
|
+
// live in the child's global pi-permission-system config). The key is
|
|
87
|
+
// transient like the sandbox keys: restored on the host once the child
|
|
88
|
+
// session exists.
|
|
89
|
+
const permissionProfileEnv: Record<string, string | undefined> | undefined =
|
|
90
|
+
input.permissionProfile !== undefined
|
|
91
|
+
? { [SUBAGENT_PERMISSION_PROFILE_ENV]: input.permissionProfile }
|
|
92
|
+
: undefined;
|
|
93
|
+
const childEnv: Record<string, string | undefined> | undefined =
|
|
94
|
+
sandboxEnv !== undefined || permissionProfileEnv !== undefined
|
|
95
|
+
? { ...(sandboxEnv ?? {}), ...(permissionProfileEnv ?? {}) }
|
|
96
|
+
: undefined;
|
|
97
|
+
// The profile key is pinned for every launch, `undefined` included: a child
|
|
98
|
+
// that declares no profile must not inherit the host session's role
|
|
99
|
+
// selection, and one that declares a profile must not be overridden by it
|
|
100
|
+
// (the launcher env wins inside pi-permission-system). It is kept out of
|
|
101
|
+
// `childEnv` so a plain in-process child does not also start receiving the
|
|
102
|
+
// binding and MCP values that only a runner-hosted child used to get.
|
|
103
|
+
const profilePin: Record<string, string | undefined> = {
|
|
104
|
+
[SUBAGENT_PERMISSION_PROFILE_ENV]: input.permissionProfile,
|
|
105
|
+
// Present for every child launch: it is what tells pi-permission-system
|
|
106
|
+
// this selection is authoritative for the child (see the constant).
|
|
107
|
+
[SUBAGENT_PERMISSION_PROFILE_PINNED_ENV]: "1",
|
|
108
|
+
};
|
|
109
|
+
const transientProcessEnv = [
|
|
110
|
+
...new Set([
|
|
111
|
+
...(childEnv ? Object.keys(childEnv) : []),
|
|
112
|
+
...Object.keys(profilePin),
|
|
113
|
+
]),
|
|
114
|
+
];
|
|
115
|
+
return {
|
|
116
|
+
childEnv,
|
|
117
|
+
profilePin,
|
|
118
|
+
transientProcessEnv,
|
|
119
|
+
...(sandboxDiagnosticsPath ? { sandboxDiagnosticsPath } : {}),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -83,3 +83,37 @@ export default function registerSandboxProfileGuard(pi: ExtensionAPI): void {
|
|
|
83
83
|
return undefined;
|
|
84
84
|
});
|
|
85
85
|
}
|
|
86
|
+
|
|
87
|
+
export type ProjectScopedProfileKind = "sandbox" | "permission";
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* [fork] Shared project-trust gate for project-scoped sandbox/permission
|
|
91
|
+
* profile selections. Returns the error message to surface when the selection
|
|
92
|
+
* is not permitted under the current project-trust state, or undefined when
|
|
93
|
+
* the launch may proceed. The messages are byte-identical to the original
|
|
94
|
+
* preflight and executor copies that this helper replaces.
|
|
95
|
+
*/
|
|
96
|
+
export function projectScopedProfileTrustError(options: {
|
|
97
|
+
kind: ProjectScopedProfileKind;
|
|
98
|
+
agentName: string;
|
|
99
|
+
profileName: string;
|
|
100
|
+
/** True when the selection is project-scoped (agent source or override scope). */
|
|
101
|
+
projectScoped: boolean;
|
|
102
|
+
/** Resolved trusted project cwd, or undefined when the project is not trusted. */
|
|
103
|
+
trustedCwd: string | undefined;
|
|
104
|
+
/** cwd that must match the trusted project cwd, already in comparison form. */
|
|
105
|
+
effectiveCwd: string;
|
|
106
|
+
/** "preflight" compares raw cwds; "executor" resolves the child cwd and says "child cwd". */
|
|
107
|
+
messageStyle: "preflight" | "executor";
|
|
108
|
+
}): string | undefined {
|
|
109
|
+
if (!options.projectScoped) return undefined;
|
|
110
|
+
const label = options.kind === "sandbox" ? "sandbox profile" : "permission profile";
|
|
111
|
+
if (options.trustedCwd === undefined) {
|
|
112
|
+
return `Agent '${options.agentName}' selects ${label} '${options.profileName}' from project scope, but the project is not trusted. Trust the project and retry.`;
|
|
113
|
+
}
|
|
114
|
+
if (options.trustedCwd === options.effectiveCwd) return undefined;
|
|
115
|
+
if (options.messageStyle === "executor") {
|
|
116
|
+
return `Agent '${options.agentName}' selects ${label} '${options.profileName}' from project scope, but child cwd '${options.effectiveCwd}' does not match the trusted project cwd '${options.trustedCwd}'. Launch from the trusted project cwd and retry.`;
|
|
117
|
+
}
|
|
118
|
+
return `Agent '${options.agentName}' selects ${label} '${options.profileName}' from project scope, but cwd '${options.effectiveCwd}' does not match trusted project cwd '${options.trustedCwd}'. Launch from the trusted project cwd and retry.`;
|
|
119
|
+
}
|
|
@@ -40,3 +40,17 @@ export function validatePermissionProfileName(
|
|
|
40
40
|
}
|
|
41
41
|
return value;
|
|
42
42
|
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* [fork] Validate an optional permission-profile selector: like
|
|
46
|
+
* {@link validatePermissionProfileName} but returns `undefined` instead of
|
|
47
|
+
* throwing when the value is absent or invalid. Stored/status readers use this
|
|
48
|
+
* to tolerate corrupt or legacy payloads without failing the whole report.
|
|
49
|
+
*/
|
|
50
|
+
export function validatePermissionProfileNameOptional(value: unknown): string | undefined {
|
|
51
|
+
try {
|
|
52
|
+
return validatePermissionProfileName(value);
|
|
53
|
+
} catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -21,3 +21,17 @@ export function validateSandboxProfileName(value: unknown, label = "sandbox prof
|
|
|
21
21
|
}
|
|
22
22
|
return value;
|
|
23
23
|
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* [fork] Validate an optional sandbox profile selector: like
|
|
27
|
+
* {@link validateSandboxProfileName} but returns `undefined` instead of
|
|
28
|
+
* throwing when the value is absent or invalid. Stored/status readers use this
|
|
29
|
+
* to tolerate corrupt or legacy payloads without failing the whole report.
|
|
30
|
+
*/
|
|
31
|
+
export function validateSandboxProfileNameOptional(value: unknown): string | undefined {
|
|
32
|
+
try {
|
|
33
|
+
return validateSandboxProfileName(value);
|
|
34
|
+
} catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|