@xzzpig/pi-subagents 0.15.0 → 0.15.1

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.
@@ -10,7 +10,6 @@ import {
10
10
  defaultInheritProjectContext,
11
11
  defaultInheritSkills,
12
12
  defaultSystemPromptMode,
13
- discoverAgents,
14
13
  discoverAgentsAll,
15
14
  buildRuntimeName,
16
15
  findBlockingAgentDiagnostic,
@@ -23,12 +22,11 @@ import {
23
22
  } from "./agents.ts";
24
23
  import { serializeAgent } from "./agent-serializer.ts";
25
24
  import { mergeAgentsForScope } from "./agent-selection.ts";
26
- import { discoverAvailableSkills, resolveSkills, resolveSkillsWithFallback } from "./skills.ts";
25
+ import { discoverAvailableSkills, resolveSkills } from "./skills.ts";
27
26
  import {
28
27
  buildProactiveSkillSubagentRecommendationLines,
29
28
  } from "./proactive-skills.ts";
30
29
  import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.ts";
31
- import { resolvePiLaunchToolPlan } from "../runs/shared/child-tool-plan.ts";
32
30
  import { resolveEffectiveThinking, toModelInfo } from "../shared/model-info.ts";
33
31
  import { resolveSubagentModelOverride, type ParentModel } from "../runs/shared/model-resolution.ts";
34
32
  import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
@@ -43,61 +41,10 @@ import { mergeRuntimeAgents, type RuntimeAgentOwner } from "./runtime-agent-regi
43
41
  import { listExternalJobProviders } from "../api/external-job-provider.ts";
44
42
  import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
45
43
  import { validatePermissionProfileName } from "../shared/permission-profile.ts";
44
+ import { ejectAgentDefinition } from "./agent-eject.ts";
46
45
 
47
46
  export const AGENT_MANAGEMENT_API_VERSION = 1 as const;
48
47
 
49
- export type AgentEjectionScope = "user" | "project";
50
-
51
- export type AgentEjectionErrorCode =
52
- | "invalid_agent"
53
- | "untrusted_project"
54
- | "missing_project_root"
55
- | "missing_source"
56
- | "existing_custom"
57
- | "name_conflict"
58
- | "existing_file"
59
- | "source_read_failed"
60
- | "resource_missing"
61
- | "write_failed"
62
- | "rediscovery_failed"
63
- | "preflight_failed";
64
-
65
- export interface EjectAgentDefinitionInput {
66
- cwd: string;
67
- agent: string;
68
- scope: AgentEjectionScope;
69
- /** Direct project-scope API callers must affirm host project trust. */
70
- projectTrusted?: boolean;
71
- }
72
-
73
- export interface EjectAgentDefinitionVerification {
74
- agent: string;
75
- scope: AgentEjectionScope;
76
- targetPath: string;
77
- source: "builtin" | "package";
78
- resourcePaths: string[];
79
- launchPreflighted: true;
80
- }
81
-
82
- export type EjectAgentDefinitionResult =
83
- | {
84
- ok: true;
85
- code: "ejected";
86
- message: string;
87
- agent: string;
88
- source: "builtin" | "package";
89
- scope: AgentEjectionScope;
90
- targetPath: string;
91
- verification: EjectAgentDefinitionVerification;
92
- }
93
- | {
94
- ok: false;
95
- code: AgentEjectionErrorCode;
96
- message: string;
97
- scope?: AgentEjectionScope;
98
- targetPath?: string;
99
- };
100
-
101
48
  type ManagementAction = "list" | "get" | "models" | "create" | "update" | "delete" | "eject" | "disable" | "enable" | "reset";
102
49
  type ManagementScope = "user" | "project";
103
50
  type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { isProjectTrusted?: ExtensionContext["isProjectTrusted"]; model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string; runtimeAgentOwner?: RuntimeAgentOwner; onAgentsChanged?: () => void };
@@ -179,7 +126,8 @@ function normalizeListScope(scope: unknown): AgentScope | undefined {
179
126
  return undefined;
180
127
  }
181
128
 
182
- function sanitizeName(name: string): string {
129
+ // [fork] Exported for agents/agent-eject.ts.
130
+ export function sanitizeName(name: string): string {
183
131
  return name.toLowerCase().trim().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
184
132
  }
185
133
 
@@ -211,7 +159,8 @@ function availableAgentNamesFromDiscovery(
211
159
  return [...new Set(agents.map((agent) => agent.name))].sort((a, b) => a.localeCompare(b));
212
160
  }
213
161
 
214
- function availableAgentNames(cwd: string): string[] {
162
+ // [fork] Exported for agents/agent-eject.ts.
163
+ export function availableAgentNames(cwd: string): string[] {
215
164
  return availableAgentNamesFromDiscovery(discoverAgentsAll(cwd));
216
165
  }
217
166
 
@@ -261,7 +210,8 @@ function resolveEffectiveAgent(d: ReturnType<typeof discoverAgentsAll>, name: st
261
210
  return { agent: matches.reduce((best, agent) => (AGENT_SOURCE_PRECEDENCE[agent.source] > AGENT_SOURCE_PRECEDENCE[best.source] ? agent : best)) };
262
211
  }
263
212
 
264
- function nameExistsInScope(cwd: string, scope: ManagementScope, name: string, excludePath?: string): boolean {
213
+ // [fork] Exported for agents/agent-eject.ts.
214
+ export function nameExistsInScope(cwd: string, scope: ManagementScope, name: string, excludePath?: string): boolean {
265
215
  const d = discoverAgentsAll(cwd);
266
216
  for (const a of scope === "user" ? d.user : d.project) {
267
217
  if (a.name === name && a.filePath !== excludePath) return true;
@@ -1349,276 +1299,6 @@ function handleDelete(params: ManagementParams, ctx: ManagementContext): AgentTo
1349
1299
  return result(`Deleted agent '${target.name}' at ${target.filePath}.`);
1350
1300
  }
1351
1301
 
1352
- function isRelativeAgentResourcePath(value: string): boolean {
1353
- return value === "." || value === ".." || value.startsWith("./") || value.startsWith("../");
1354
- }
1355
-
1356
- /**
1357
- * Upstream v0.53.0 resolves agent-frontmatter extension paths to absolute
1358
- * paths at discovery time, so a portable resource is any entry that is a
1359
- * path (relative or absolute) rather than a bare tool name.
1360
- */
1361
- function isAgentResourcePath(value: string): boolean {
1362
- return isRelativeAgentResourcePath(value) || path.isAbsolute(value);
1363
- }
1364
-
1365
- function resolvePortableAgentResources(
1366
- entries: string[] | undefined,
1367
- sourceFilePath: string,
1368
- ): { entries: string[] | undefined; resourcePaths: string[] } {
1369
- const baseDir = path.dirname(sourceFilePath);
1370
- const resourcePaths = (entries ?? []).flatMap((entry) =>
1371
- isAgentResourcePath(entry) ? [path.resolve(baseDir, entry)] : [],
1372
- );
1373
- return {
1374
- entries: entries?.map((entry) => isAgentResourcePath(entry) ? path.resolve(baseDir, entry) : entry),
1375
- resourcePaths,
1376
- };
1377
- }
1378
-
1379
- function portableEjectedAgentContent(source: AgentConfig): {
1380
- content?: string;
1381
- resourcePaths?: string[];
1382
- error?: EjectAgentDefinitionResult;
1383
- } {
1384
- let sourceContent: string;
1385
- try {
1386
- sourceContent = fs.readFileSync(source.filePath, "utf-8");
1387
- } catch (error) {
1388
- const message = error instanceof Error ? error.message : String(error);
1389
- return {
1390
- error: {
1391
- ok: false,
1392
- code: "source_read_failed",
1393
- message: `Failed to read source agent at ${source.filePath}: ${message}`,
1394
- },
1395
- };
1396
- }
1397
-
1398
- const extensions = resolvePortableAgentResources(source.extensions, source.filePath);
1399
- const subagentOnlyExtensions = resolvePortableAgentResources(source.subagentOnlyExtensions, source.filePath);
1400
- const skillPath = resolvePortableAgentResources(source.skillPath, source.filePath);
1401
- const tools = resolvePortableAgentResources(source.tools, source.filePath);
1402
- const resourcePaths = [...new Set([
1403
- ...extensions.resourcePaths,
1404
- ...subagentOnlyExtensions.resourcePaths,
1405
- ...skillPath.resourcePaths,
1406
- ...tools.resourcePaths,
1407
- ])].sort((a, b) => a.localeCompare(b));
1408
- const missingResources = resourcePaths.filter((resourcePath) => !fs.existsSync(resourcePath));
1409
- if (missingResources.length > 0) {
1410
- return {
1411
- error: {
1412
- ok: false,
1413
- code: "resource_missing",
1414
- message: `Agent '${source.name}' cannot be ejected because its relative resource path(s) do not exist: ${missingResources.join(", ")}.`,
1415
- },
1416
- };
1417
- }
1418
- if (resourcePaths.length === 0) return { content: sourceContent, resourcePaths };
1419
-
1420
- const { frontmatter } = parseFrontmatter(sourceContent);
1421
- const portableAgent: AgentConfig = {
1422
- ...source,
1423
- ...(source.extensions !== undefined ? { extensions: extensions.entries! } : {}),
1424
- ...(source.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: subagentOnlyExtensions.entries! } : {}),
1425
- ...(source.skillPath !== undefined ? { skillPath: skillPath.entries! } : {}),
1426
- ...(source.tools !== undefined ? { tools: tools.entries! } : {}),
1427
- };
1428
- return {
1429
- content: serializeAgent(portableAgent, { preserveFrontmatterFields: new Set(Object.keys(frontmatter)) }),
1430
- resourcePaths,
1431
- };
1432
- }
1433
-
1434
- function cleanupEjectedFile(targetPath: string, expectedContent: string): void {
1435
- try {
1436
- if (fs.readFileSync(targetPath, "utf-8") === expectedContent) fs.unlinkSync(targetPath);
1437
- } catch {
1438
- // The service only cleans the file it created during this call.
1439
- }
1440
- }
1441
-
1442
- function validateEjectedAgentLaunchPreflight(agent: AgentConfig, cwd: string): string | undefined {
1443
- const resolvedSkills = resolveSkillsWithFallback(
1444
- agent.skills ?? [],
1445
- cwd,
1446
- undefined,
1447
- agent.skillPath,
1448
- agent.filePath ? path.dirname(agent.filePath) : cwd,
1449
- );
1450
- if (resolvedSkills.missing.length > 0) {
1451
- return `Missing skills: ${resolvedSkills.missing.join(", ")}`;
1452
- }
1453
- try {
1454
- resolvePiLaunchToolPlan({
1455
- tools: agent.tools,
1456
- extensions: agent.extensions,
1457
- subagentOnlyExtensions: agent.subagentOnlyExtensions,
1458
- mcpDirectTools: agent.mcpDirectTools,
1459
- cwd,
1460
- requireReadTool: resolvedSkills.resolved.length > 0,
1461
- agentName: agent.name,
1462
- sandbox: agent.sandbox,
1463
- permissionProfile: agent.permissionProfile,
1464
- });
1465
- } catch (error) {
1466
- return error instanceof Error ? error.message : String(error);
1467
- }
1468
- return undefined;
1469
- }
1470
-
1471
- /**
1472
- * Shared extraction of the existing eject handler. It deliberately owns only
1473
- * agent-definition copying, no-overwrite checks, project-trust input, and
1474
- * portable package-relative resource paths.
1475
- */
1476
- export function ejectAgentDefinition(input: EjectAgentDefinitionInput): EjectAgentDefinitionResult {
1477
- const raw = input.agent.trim();
1478
- const sanitized = sanitizeName(raw);
1479
- if (!raw || !sanitized) {
1480
- return { ok: false, code: "invalid_agent", message: "agent must be a non-empty valid agent name." };
1481
- }
1482
- if (input.scope !== "user" && input.scope !== "project") {
1483
- return { ok: false, code: "invalid_agent", message: "scope must be 'user' or 'project'." };
1484
- }
1485
- if (input.scope === "project" && input.projectTrusted !== true) {
1486
- return {
1487
- ok: false,
1488
- code: "untrusted_project",
1489
- scope: input.scope,
1490
- message: "Project scope ejection requires a trusted project. Trust the project and retry.",
1491
- };
1492
- }
1493
-
1494
- let discovered: ReturnType<typeof discoverAgentsAll>;
1495
- try {
1496
- discovered = discoverAgentsAll(input.cwd);
1497
- } catch (error) {
1498
- return {
1499
- ok: false,
1500
- code: "rediscovery_failed",
1501
- scope: input.scope,
1502
- message: `Unable to discover agents before ejecting: ${error instanceof Error ? error.message : String(error)}`,
1503
- };
1504
- }
1505
- if (input.scope === "project" && discovered.projectDir === null) {
1506
- return {
1507
- ok: false,
1508
- code: "missing_project_root",
1509
- scope: input.scope,
1510
- message: "Project scope ejection is not available here: no project config root (.pi or .agents) was found above the cwd.",
1511
- };
1512
- }
1513
-
1514
- const existingCustom = (input.scope === "user" ? discovered.user : discovered.project)
1515
- .find((candidate) => candidate.name === raw || candidate.name === sanitized);
1516
- if (existingCustom) {
1517
- return {
1518
- ok: false,
1519
- code: "existing_custom",
1520
- scope: input.scope,
1521
- targetPath: existingCustom.filePath,
1522
- message: `Agent '${existingCustom.name}' is already a custom ${input.scope} agent at ${existingCustom.filePath}. Edit it with { action: "update", agent: "${existingCustom.name}" } or delete it first.`,
1523
- };
1524
- }
1525
- const bundledCandidates = input.scope === "user"
1526
- ? discoverAgents(input.cwd, "user").agents.filter((candidate) => candidate.source === "builtin" || candidate.source === "package")
1527
- : [...discovered.package, ...discovered.builtin];
1528
- const source = bundledCandidates.find((candidate) => candidate.name === raw || candidate.name === sanitized);
1529
- if (!source) {
1530
- return {
1531
- ok: false,
1532
- code: "missing_source",
1533
- scope: input.scope,
1534
- message: `Agent '${raw}' not found or is not a bundled/package agent. eject copies a builtin or package agent to ${input.scope} scope so it can be customized. Available: ${availableAgentNames(input.cwd).join(", ") || "none"}.`,
1535
- };
1536
- }
1537
- const runtimeName = source.name;
1538
- if (nameExistsInScope(input.cwd, input.scope, runtimeName)) {
1539
- return {
1540
- ok: false,
1541
- code: "name_conflict",
1542
- scope: input.scope,
1543
- message: `An agent or chain named '${runtimeName}' already exists in ${input.scope} scope. Remove or rename it first.`,
1544
- };
1545
- }
1546
-
1547
- const targetDir = input.scope === "user" ? discovered.userDir : discovered.projectDir!;
1548
- const targetPath = path.join(targetDir, `${runtimeName}.md`);
1549
- if (fs.existsSync(targetPath)) {
1550
- return {
1551
- ok: false,
1552
- code: "existing_file",
1553
- scope: input.scope,
1554
- targetPath,
1555
- message: `File already exists at ${targetPath} but is not a valid agent definition. Remove or rename it first.`,
1556
- };
1557
- }
1558
-
1559
- const portable = portableEjectedAgentContent(source);
1560
- if (portable.error) return { ...portable.error, scope: input.scope, targetPath };
1561
- const content = portable.content!;
1562
- try {
1563
- fs.mkdirSync(targetDir, { recursive: true });
1564
- fs.writeFileSync(targetPath, content, { encoding: "utf-8", flag: "wx" });
1565
- } catch (error) {
1566
- const message = error instanceof Error ? error.message : String(error);
1567
- return {
1568
- ok: false,
1569
- code: "write_failed",
1570
- scope: input.scope,
1571
- targetPath,
1572
- message: `Failed to write ejected agent '${runtimeName}' at ${targetPath}: ${message}`,
1573
- };
1574
- }
1575
-
1576
- const rediscovered = discoverAgentsAll(input.cwd);
1577
- const copied = (input.scope === "user" ? rediscovered.user : rediscovered.project)
1578
- .find((candidate) => candidate.name === runtimeName && path.resolve(candidate.filePath) === path.resolve(targetPath));
1579
- if (!copied) {
1580
- cleanupEjectedFile(targetPath, content);
1581
- return {
1582
- ok: false,
1583
- code: "rediscovery_failed",
1584
- scope: input.scope,
1585
- targetPath,
1586
- message: `Ejected agent '${runtimeName}' could not be rediscovered at ${targetPath}; no file was kept.`,
1587
- };
1588
- }
1589
-
1590
- const preflightError = validateEjectedAgentLaunchPreflight(copied, input.cwd);
1591
- if (preflightError) {
1592
- cleanupEjectedFile(targetPath, content);
1593
- return {
1594
- ok: false,
1595
- code: "preflight_failed",
1596
- scope: input.scope,
1597
- targetPath,
1598
- message: `Ejected agent '${runtimeName}' failed launch preflight at ${targetPath}: ${preflightError}. No file was kept.`,
1599
- };
1600
- }
1601
-
1602
- const sourceKind = source.source as "builtin" | "package";
1603
- return {
1604
- ok: true,
1605
- code: "ejected",
1606
- message: `Ejected agent '${runtimeName}' from ${sourceKind} to ${input.scope} scope at ${targetPath}. Edit it there to customize; it shadows the bundled ${sourceKind} agent of the same name.`,
1607
- agent: runtimeName,
1608
- source: sourceKind,
1609
- scope: input.scope,
1610
- targetPath,
1611
- verification: {
1612
- agent: copied.name,
1613
- scope: input.scope,
1614
- targetPath,
1615
- source: sourceKind,
1616
- resourcePaths: portable.resourcePaths ?? [],
1617
- launchPreflighted: true,
1618
- },
1619
- };
1620
- }
1621
-
1622
1302
  function handleEject(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
1623
1303
  if (!params.agent) return result("Specify 'agent' for eject.", true);
1624
1304
  const parsedScope = actionScope(params.agentScope, "eject");
@@ -1,9 +1,9 @@
1
+ export { AGENT_MANAGEMENT_API_VERSION } from "../agents/agent-management.ts";
1
2
  export {
2
- AGENT_MANAGEMENT_API_VERSION,
3
3
  ejectAgentDefinition,
4
4
  type AgentEjectionErrorCode,
5
5
  type AgentEjectionScope,
6
6
  type EjectAgentDefinitionInput,
7
7
  type EjectAgentDefinitionResult,
8
8
  type EjectAgentDefinitionVerification,
9
- } from "../agents/agent-management.ts";
9
+ } from "../agents/agent-eject.ts";
@@ -26,6 +26,7 @@ import { processTerminalCandidatePath, processTerminalPath } from "../runs/backg
26
26
  import { resultFilePath } from "../runs/background/result-files.ts";
27
27
  import { nestedResultsPath } from "../runs/shared/nested-events.ts";
28
28
  import { normalizeExtensionBindings, type ExtensionBindings } from "../runs/shared/extension-bindings.ts";
29
+ import { projectScopedProfileTrustError } from "../runs/shared/sandbox-profile-guard.ts";
29
30
  import { resolveRequiredChildExtensions } from "../shared/required-child-extensions.ts";
30
31
 
31
32
  // v3: the contract reports the resolved Intercom bridge state and binds its
@@ -352,21 +353,26 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
352
353
  const trustedProjectCwd = input.projectTrusted === true
353
354
  ? path.resolve(input.trustedProjectCwd ?? effectiveCwd)
354
355
  : undefined;
355
- if (agent.sandbox && (agent.source === "project" || agent.override?.scope === "project") && input.projectTrusted !== true) {
356
- const message = `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
357
- return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
358
- }
359
- if (agent.permissionProfile && (agent.source === "project" || agent.override?.scope === "project") && input.projectTrusted !== true) {
360
- const message = `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but the project is not trusted. Trust the project and retry.`;
361
- return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
362
- }
363
- if (agent.sandbox && (agent.source === "project" || agent.override?.scope === "project") && trustedProjectCwd !== effectiveCwd) {
364
- const message = `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but cwd '${effectiveCwd}' does not match trusted project cwd '${trustedProjectCwd}'. Launch from the trusted project cwd and retry.`;
365
- return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
366
- }
367
- if (agent.permissionProfile && (agent.source === "project" || agent.override?.scope === "project") && trustedProjectCwd !== effectiveCwd) {
368
- const message = `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but cwd '${effectiveCwd}' does not match trusted project cwd '${trustedProjectCwd}'. Launch from the trusted project cwd and retry.`;
369
- return { ok: false, code: "untrusted_project", message, diagnostics: [{ code: "untrusted_project", severity: "error", message }] };
356
+ const projectScoped = agent.source === "project" || agent.override?.scope === "project";
357
+ const profileTrustError = projectScopedProfileTrustError({
358
+ kind: "sandbox",
359
+ agentName: agent.name,
360
+ profileName: agent.sandbox ?? "",
361
+ projectScoped: Boolean(agent.sandbox) && projectScoped,
362
+ trustedCwd: trustedProjectCwd,
363
+ effectiveCwd,
364
+ messageStyle: "preflight",
365
+ }) ?? projectScopedProfileTrustError({
366
+ kind: "permission",
367
+ agentName: agent.name,
368
+ profileName: agent.permissionProfile ?? "",
369
+ projectScoped: Boolean(agent.permissionProfile) && projectScoped,
370
+ trustedCwd: trustedProjectCwd,
371
+ effectiveCwd,
372
+ messageStyle: "preflight",
373
+ });
374
+ if (profileTrustError) {
375
+ return { ok: false, code: "untrusted_project", message: profileTrustError, diagnostics: [{ code: "untrusted_project", severity: "error", message: profileTrustError }] };
370
376
  }
371
377
  if (agent.sandbox && (agent.runner?.type === "external-cli" || agent.runner?.type === "external-job")) {
372
378
  const message = `Agent '${agent.name}' requests sandbox profile '${agent.sandbox}', but runner.type='${agent.runner.type}' cannot load the native pi-sandbox extension.`;
@@ -25,8 +25,8 @@ import { formatWorkflowPreflightPlanSummary, formatWorkflowPreflightWarningSumma
25
25
  import { workflowGraphStageNodes } from "../shared/workflow-graph.ts";
26
26
  import { formatTimeoutRecoveryLines, projectTimeoutRecovery } from "../shared/mutation-evidence.ts";
27
27
  import { formatWorkflowChecklistText, projectWorkflowChecklist } from "../../workflows/workflow-checklist.ts";
28
- import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
29
- import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
28
+ import { validateSandboxProfileNameOptional } from "../../shared/sandbox-profile.ts";
29
+ import { validatePermissionProfileNameOptional } from "../../shared/permission-profile.ts";
30
30
  import type { RawDrainStatusObserver } from "../shared/readonly-drain-observation.ts";
31
31
  import { childWatchdogProgressForModel } from "../../watchdog/child-status.ts";
32
32
 
@@ -211,22 +211,6 @@ function isolateCorruptActiveRun(asyncDir: string, runId: string, error: unknown
211
211
  console.error(`[pi-subagents] Skipping corrupt active async run '${runId}' at '${statusPath}': ${getErrorMessage(error)}; ${markerAction}.`);
212
212
  }
213
213
 
214
- function sandboxProfileValue(value: unknown): string | undefined {
215
- try {
216
- return validateSandboxProfileName(value);
217
- } catch {
218
- return undefined;
219
- }
220
- }
221
-
222
- function permissionProfileValue(value: unknown): string | undefined {
223
- try {
224
- return validatePermissionProfileName(value);
225
- } catch {
226
- return undefined;
227
- }
228
- }
229
-
230
214
  function isNotFoundError(error: unknown): boolean {
231
215
  return typeof error === "object"
232
216
  && error !== null
@@ -351,8 +335,8 @@ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string
351
335
  const stepActivityState = step.activityState;
352
336
  const stepLastActivityAt = step.lastActivityAt;
353
337
  const timeoutRecovery = projectTimeoutRecovery(step.timeoutRecovery);
354
- const sandbox = sandboxProfileValue(step.sandbox);
355
- const permissionProfile = permissionProfileValue(step.permissionProfile);
338
+ const sandbox = validateSandboxProfileNameOptional(step.sandbox);
339
+ const permissionProfile = validatePermissionProfileNameOptional(step.permissionProfile);
356
340
  return {
357
341
  index,
358
342
  childId: asyncStatusChildIdentity(step, index),
@@ -423,8 +407,8 @@ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string
423
407
  };
424
408
  });
425
409
  attachRootChildrenToSteps(status.runId || path.basename(asyncDir), summarizedSteps, nestedChildren);
426
- const sandbox = sandboxProfileValue(status.sandbox);
427
- const permissionProfile = permissionProfileValue(status.permissionProfile);
410
+ const sandbox = validateSandboxProfileNameOptional(status.sandbox);
411
+ const permissionProfile = validatePermissionProfileNameOptional(status.permissionProfile);
428
412
  return {
429
413
  id: status.runId || path.basename(asyncDir),
430
414
  asyncDir,
@@ -141,8 +141,8 @@ import { attachContractProjections, isAgentContract } from "../shared/agent-cont
141
141
  import { waitForImportedAsyncRoot } from "./chain-root-attachment.ts";
142
142
  import { appendRunnerStepsToStatus, consumeChainAppendRequests, countPendingChainAppendRequests, statusStepDescription } from "./chain-append.ts";
143
143
  import { asyncStatusChildIdentity } from "../shared/child-identity.ts";
144
- import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
145
- import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
144
+ import { validateSandboxProfileNameOptional } from "../../shared/sandbox-profile.ts";
145
+ import { validatePermissionProfileNameOptional } from "../../shared/permission-profile.ts";
146
146
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
147
147
  import { toolTimeoutCallKey } from "../shared/tool-timeout.ts";
148
148
  import { usageBudgetExceededMessage, usageBudgetState } from "../shared/usage-budget.ts";
@@ -297,21 +297,13 @@ interface StepResult {
297
297
  function commonSandboxProfile(steps: readonly RunnerStatusStep[]): string | undefined {
298
298
  const profile = steps[0]?.sandbox;
299
299
  if (!profile || !steps.every((step) => step.sandbox === profile)) return undefined;
300
- try {
301
- return validateSandboxProfileName(profile);
302
- } catch {
303
- return undefined;
304
- }
300
+ return validateSandboxProfileNameOptional(profile);
305
301
  }
306
302
 
307
303
  function commonPermissionProfile(steps: readonly RunnerStatusStep[]): string | undefined {
308
304
  const profile = steps[0]?.permissionProfile;
309
305
  if (!profile || !steps.every((step) => step.permissionProfile === profile)) return undefined;
310
- try {
311
- return validatePermissionProfileName(profile);
312
- } catch {
313
- return undefined;
314
- }
306
+ return validatePermissionProfileNameOptional(profile);
315
307
  }
316
308
 
317
309
  function persistStepArtifacts(input: {
@@ -31,6 +31,7 @@ import { applyWatchdogLaunchRules } from "../../watchdog/rules.ts";
31
31
  import { childWatchdogProgressForModel } from "../../watchdog/child-status.ts";
32
32
  import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
33
33
  import { getHostBuiltinToolNames } from "../shared/child-tool-plan.ts";
34
+ import { projectScopedProfileTrustError } from "../shared/sandbox-profile-guard.ts";
34
35
  import { projectChainOutputSchemas, resolveEffectiveOutputSchema } from "../shared/child-launch-plan.ts";
35
36
  import { formatRetainedChildren, listRetainedChildren } from "../background/retained-children.ts";
36
37
  import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
@@ -562,23 +563,27 @@ function trustedProjectCwd(ctx: ExtensionContext): string | undefined {
562
563
  }
563
564
 
564
565
  function sandboxProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
565
- if (!agent.sandbox || (agent.source !== "project" && agent.override?.scope !== "project")) return undefined;
566
- const trustedCwd = trustedProjectCwd(ctx);
567
- if (trustedCwd && trustedCwd === path.resolve(childCwd)) return undefined;
568
- if (!trustedCwd) {
569
- return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
570
- }
571
- 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.`;
566
+ return projectScopedProfileTrustError({
567
+ kind: "sandbox",
568
+ agentName: agent.name,
569
+ profileName: agent.sandbox ?? "",
570
+ projectScoped: Boolean(agent.sandbox) && (agent.source === "project" || agent.override?.scope === "project"),
571
+ trustedCwd: trustedProjectCwd(ctx),
572
+ effectiveCwd: path.resolve(childCwd),
573
+ messageStyle: "executor",
574
+ });
572
575
  }
573
576
 
574
577
  function permissionProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
575
- if (!agent.permissionProfile || (agent.source !== "project" && agent.override?.scope !== "project")) return undefined;
576
- const trustedCwd = trustedProjectCwd(ctx);
577
- if (trustedCwd && trustedCwd === path.resolve(childCwd)) return undefined;
578
- if (!trustedCwd) {
579
- return `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but the project is not trusted. Trust the project and retry.`;
580
- }
581
- return `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but child cwd '${path.resolve(childCwd)}' does not match the trusted project cwd '${trustedCwd}'. Launch from the trusted project cwd and retry.`;
578
+ return projectScopedProfileTrustError({
579
+ kind: "permission",
580
+ agentName: agent.name,
581
+ profileName: agent.permissionProfile ?? "",
582
+ projectScoped: Boolean(agent.permissionProfile) && (agent.source === "project" || agent.override?.scope === "project"),
583
+ trustedCwd: trustedProjectCwd(ctx),
584
+ effectiveCwd: path.resolve(childCwd),
585
+ messageStyle: "executor",
586
+ });
582
587
  }
583
588
 
584
589
  export function removeForegroundControlIfIdle(state: SubagentState, runId: string, trackRetainedNestedRoute?: (rootRunId: string) => void): boolean {