@xzzpig/pi-subagents 0.20.0 → 0.21.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.
Files changed (140) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -9,7 +9,8 @@ import * as os from "node:os";
9
9
  import * as path from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import { createAtomicJsonWriter } from "../shared/atomic-json.ts";
12
- import type { AcceptanceInput, AcceptanceRole, AgentRunnerConfig, JsonSchemaObject, OutputMode, ToolBudgetConfig } from "../shared/types.ts";
12
+ import { resolveSettingsWriteTarget, withSettingsFileLease } from "../shared/settings-file-lease.ts";
13
+ import { RUNNER_LAUNCHER_NAME_PATTERN, RUNNER_LAUNCHER_NAME_RULE, type AcceptanceInput, type AcceptanceRole, type AgentRunnerConfig, type JsonSchemaObject, type OutputMode, type ToolBudgetConfig } from "../shared/types.ts";
13
14
  import { CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL, isCodeOwnedExternalCliAdapterId, parseExternalCliCapabilityNarrowing, validateCodeOwnedProfileRunner } from "../runs/shared/external-cli-contract.ts";
14
15
  import { isClaudeCodeAdapterId } from "../runs/shared/claude-code-adapter.ts";
15
16
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
@@ -17,6 +18,8 @@ import { expandHomePath } from "../shared/settings.ts";
17
18
  import { KNOWN_FIELDS } from "./agent-serializer.ts";
18
19
  import { parseChain, parseJsonChain } from "./chain-serializer.ts";
19
20
  import { mergeAgentsForScope } from "./agent-selection.ts";
21
+ import { projectScopeRequiresTrustMessage } from "./agent-scope.ts";
22
+ import { closestMatch } from "../shared/edit-distance.ts";
20
23
  import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.ts";
21
24
  import { buildRuntimeName, parsePackageName } from "./identity.ts";
22
25
  import { parseModelScopeConfig, type ModelScopeConfig } from "../runs/shared/model-scope.ts";
@@ -191,6 +194,8 @@ export interface AgentConfig {
191
194
  permissions?: PermissionRules;
192
195
  memory?: AgentMemoryConfig;
193
196
  machine?: string;
197
+ /** Name of a user-configured `runnerLaunchers` entry that wraps this agent's background runner. */
198
+ launcher?: string;
194
199
  disabled?: boolean;
195
200
  extraFields?: Record<string, string>;
196
201
  override?: BuiltinAgentOverrideInfo;
@@ -324,10 +329,13 @@ export interface UnknownAgentDiagnosticContext {
324
329
  scope: AgentScope;
325
330
  directories: readonly AgentDefinitionDirectoryReport[];
326
331
  agents: readonly AgentConfig[];
332
+ disabledAgents?: readonly string[];
327
333
  }
328
334
 
329
335
  export interface AgentDiscoveryResult {
330
336
  agents: AgentConfig[];
337
+ /** Names that resolved to a disabled definition, which discovery leaves out of `agents`. */
338
+ disabledAgents?: string[];
331
339
  agentDiagnostics?: AgentDiscoveryDiagnostic[];
332
340
  projectAgentsDir: string | null;
333
341
  cwd: string;
@@ -339,15 +347,36 @@ export interface AgentDiscoveryResult {
339
347
  }
340
348
 
341
349
  /** Create formatter input from the exact discovery operation used for resolution. */
342
- export function unknownAgentDiagnosticContext(discovered: Pick<AgentDiscoveryResult, "cwd" | "scope" | "directories" | "agents">): UnknownAgentDiagnosticContext {
350
+ export function unknownAgentDiagnosticContext(discovered: Pick<AgentDiscoveryResult, "cwd" | "scope" | "directories" | "agents" | "disabledAgents">): UnknownAgentDiagnosticContext {
343
351
  return {
344
352
  cwd: discovered.cwd,
345
353
  scope: discovered.scope,
346
354
  directories: discovered.directories,
347
355
  agents: discovered.agents,
356
+ ...(discovered.disabledAgents?.length ? { disabledAgents: discovered.disabledAgents } : {}),
348
357
  };
349
358
  }
350
359
 
360
+ const MAX_LISTED_AGENTS = 30;
361
+ const MAX_LISTED_DESCRIPTION_CHARS = 80;
362
+
363
+ /** One line per agent the caller can launch instead, so a wrong name needs no separate list call. */
364
+ export function formatAvailableAgentLines(agents: readonly AgentConfig[]): string[] {
365
+ const sorted = [...agents].sort((left, right) => left.name.localeCompare(right.name) || left.source.localeCompare(right.source));
366
+ const lines = sorted.slice(0, MAX_LISTED_AGENTS).map((agent) => {
367
+ const description = agent.description.replace(/\s+/gu, " ").trim();
368
+ const short = description.length > MAX_LISTED_DESCRIPTION_CHARS ? `${description.slice(0, MAX_LISTED_DESCRIPTION_CHARS - 1).trimEnd()}…` : description;
369
+ return `- ${agent.name} (${agent.source})${short ? ` — ${short}` : ""}`;
370
+ });
371
+ if (sorted.length > MAX_LISTED_AGENTS) lines.push(`+${sorted.length - MAX_LISTED_AGENTS} more; {action:"list"}`);
372
+ return lines.length ? lines : ["- (none)"];
373
+ }
374
+
375
+ /** The closest agent name or alias when `name` looks like a typo of one. */
376
+ export function suggestAgentName(name: string, agents: readonly AgentConfig[]): string | undefined {
377
+ return closestMatch(name.trim(), new Set(agents.flatMap((agent) => [agent.name, ...(agent.localName ? [agent.localName] : []), ...(agent.aliases ?? [])])));
378
+ }
379
+
351
380
  /** Render local discovery evidence without exposing filesystem error details. */
352
381
  export function formatUnknownAgentError(name: string, context: UnknownAgentDiagnosticContext, prefix = "Unknown agent"): string {
353
382
  const directories = context.directories.map((directory) => {
@@ -358,16 +387,15 @@ export function formatUnknownAgentError(name: string, context: UnknownAgentDiagn
358
387
  : directory.state;
359
388
  return `- ${directory.source}: ${directory.path} (${state})`;
360
389
  });
361
- const agents = [...context.agents]
362
- .sort((left, right) => left.name.localeCompare(right.name) || left.source.localeCompare(right.source))
363
- .map((agent) => `- ${agent.name} (${agent.source})`);
390
+ const disabled = context.disabledAgents?.includes(name.trim()) === true;
391
+ const suggestion = disabled ? undefined : suggestAgentName(name, context.agents);
364
392
  return [
365
- `${prefix}: ${name}`,
393
+ disabled ? `${prefix}: ${name} is disabled by a settings override.` : `${prefix}: ${name}${suggestion ? `. Did you mean '${suggestion}'?` : ""}`,
366
394
  `Effective cwd: ${path.resolve(context.cwd)}`,
367
395
  "Consulted agent-definition directories:",
368
396
  ...(directories.length ? directories : ["- (none)"]),
369
- "Discovered agents:",
370
- ...(agents.length ? agents : ["- (none)"]),
397
+ "Available agents:",
398
+ ...formatAvailableAgentLines(context.agents),
371
399
  ].join("\n");
372
400
  }
373
401
 
@@ -631,13 +659,10 @@ function collectSettingsPackageRoots(settingsFile: string, baseDir: string): str
631
659
  return roots;
632
660
  }
633
661
 
634
- function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolean; includeProject: boolean; globalNpmRoot?: string | null } = { includeUser: true, includeProject: true }): PackageSubagentPaths {
662
+ function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolean; includeProject: boolean; globalNpmRoot?: string | null; projectTrusted?: boolean }): PackageSubagentPaths {
635
663
  const agentDir = getAgentDir();
636
- const projectRoot = findConfiguredProjectRoot(cwd) ?? cwd;
637
- const packageRoots: Array<{ root: string; scope: PackageScope }> = [
638
- { root: projectRoot, scope: "root" },
639
- ];
640
- const watchPaths: string[] = [path.join(projectRoot, "package.json")];
664
+ const packageRoots: Array<{ root: string; scope: PackageScope }> = [];
665
+ const watchPaths: string[] = [];
641
666
  const settingsErrors: Partial<Record<PackageSettingsScope, Error>> = {};
642
667
  const collectScopedSettingsRoots = (scope: PackageSettingsScope, settingsFile: string, baseDir: string): string[] => {
643
668
  try {
@@ -652,11 +677,17 @@ function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolea
652
677
  return [];
653
678
  }
654
679
  };
655
- if (options.includeProject) {
656
- const projectConfigDir = getProjectConfigDir(projectRoot);
657
- const nodeModulesDir = path.join(projectConfigDir, "npm", "node_modules");
658
- packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "project" as const })));
659
- packageRoots.push(...collectScopedSettingsRoots("project", path.join(projectConfigDir, "settings.json"), projectConfigDir).map((root) => ({ root, scope: "project" as const })));
680
+ // Resolving the project root reads project settings, which an untrusted project does not supply.
681
+ if (options.projectTrusted !== false) {
682
+ const projectRoot = findConfiguredProjectRoot(cwd) ?? cwd;
683
+ packageRoots.push({ root: projectRoot, scope: "root" });
684
+ watchPaths.push(path.join(projectRoot, "package.json"));
685
+ if (options.includeProject) {
686
+ const projectConfigDir = getProjectConfigDir(projectRoot);
687
+ const nodeModulesDir = path.join(projectConfigDir, "npm", "node_modules");
688
+ packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "project" as const })));
689
+ packageRoots.push(...collectScopedSettingsRoots("project", path.join(projectConfigDir, "settings.json"), projectConfigDir).map((root) => ({ root, scope: "project" as const })));
690
+ }
660
691
  }
661
692
 
662
693
  if (options.includeUser) {
@@ -999,32 +1030,6 @@ function writeSettingsFile(filePath: string, settings: Record<string, unknown>):
999
1030
  writeAtomicSettings(targetPath, settings);
1000
1031
  }
1001
1032
 
1002
- function resolveSettingsWriteTarget(filePath: string): string {
1003
- let targetPath = filePath;
1004
- for (;;) {
1005
- try {
1006
- return fs.realpathSync.native(targetPath);
1007
- } catch (error) {
1008
- if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
1009
- // A trailing separator requires a directory; it cannot name a new settings file.
1010
- if (targetPath.endsWith("/") || targetPath.endsWith(path.sep)) throw error;
1011
- }
1012
-
1013
- // A missing target is allowed only when its physical parent already exists.
1014
- const parentPath = fs.realpathSync.native(path.dirname(targetPath));
1015
- const unresolvedPath = path.join(parentPath, path.basename(targetPath));
1016
- let linkText: string;
1017
- try {
1018
- linkText = fs.readlinkSync(unresolvedPath);
1019
- } catch (error) {
1020
- if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
1021
- return unresolvedPath;
1022
- }
1023
- // Keep link text intact so the filesystem follows directory links before "..".
1024
- targetPath = path.isAbsolute(linkText) ? linkText : `${parentPath}${path.sep}${linkText}`;
1025
- }
1026
- }
1027
-
1028
1033
  function parseOverrideStringArrayOrFalse(
1029
1034
  value: unknown,
1030
1035
  meta: { filePath: string; name: string; field: string },
@@ -1079,6 +1084,9 @@ function parseBuiltinOverrideEntry(
1079
1084
  if (Object.hasOwn(input, "fallbackModels")) {
1080
1085
  throw new Error(`Builtin override '${name}' in '${filePath}' uses removed field 'fallbackModels'; configure one model instead.`);
1081
1086
  }
1087
+ if (Object.hasOwn(input, "launcher")) {
1088
+ throw new Error(`Builtin override '${name}' in '${filePath}' sets 'launcher', which settings overrides do not support; set 'launcher' in a user agent file instead.`);
1089
+ }
1082
1090
  const override: BuiltinAgentOverrideConfig = {};
1083
1091
 
1084
1092
  if ("description" in input) {
@@ -1696,6 +1704,7 @@ export interface RuntimeAgentSettingsContext {
1696
1704
  cwd: string;
1697
1705
  scope: AgentScope;
1698
1706
  preferredModelProvider?: string;
1707
+ projectTrusted?: boolean;
1699
1708
  }
1700
1709
 
1701
1710
  function runtimeAgentOverrides(settings: SubagentSettings): SubagentSettings {
@@ -1722,7 +1731,7 @@ function runtimeAgentOverrides(settings: SubagentSettings): SubagentSettings {
1722
1731
  */
1723
1732
  export function applyRuntimeAgentSettings(agents: AgentConfig[], context: RuntimeAgentSettingsContext): AgentConfig[] {
1724
1733
  if (agents.length === 0) return agents;
1725
- const sources = getAgentDiscoverySources(context.cwd, context.preferredModelProvider);
1734
+ const sources = getAgentDiscoverySources(context.cwd, context.preferredModelProvider, false, undefined, context.projectTrusted !== false);
1726
1735
  const { user, project } = settingsForScope(sources, context.scope);
1727
1736
  const defaultProvider = resolveSubagentDefaultProvider(user, project, sources.projectSettingsPath);
1728
1737
  const defaultModel = resolveSubagentDefaultModel(user, project, sources.userSettingsPath, sources.projectSettingsPath, defaultProvider);
@@ -1785,19 +1794,21 @@ export function saveBuiltinAgentOverride(
1785
1794
  const filePath = scope === "project" ? getProjectAgentSettingsPath(cwd) : getUserAgentSettingsPath();
1786
1795
  if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
1787
1796
 
1788
- const settings = readSettingsFileStrict(filePath);
1789
- const subagents = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
1790
- ? { ...(settings.subagents as Record<string, unknown>) }
1791
- : {};
1792
- const agentOverrides = subagents.agentOverrides && typeof subagents.agentOverrides === "object" && !Array.isArray(subagents.agentOverrides)
1793
- ? { ...(subagents.agentOverrides as Record<string, unknown>) }
1794
- : {};
1795
-
1796
- agentOverrides[name] = cloneOverrideValue(override);
1797
- subagents.agentOverrides = agentOverrides;
1798
- settings.subagents = subagents;
1799
- writeSettingsFile(filePath, settings);
1800
- return filePath;
1797
+ return withSettingsFileLease(filePath, () => {
1798
+ const settings = readSettingsFileStrict(filePath);
1799
+ const subagents = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
1800
+ ? { ...(settings.subagents as Record<string, unknown>) }
1801
+ : {};
1802
+ const agentOverrides = subagents.agentOverrides && typeof subagents.agentOverrides === "object" && !Array.isArray(subagents.agentOverrides)
1803
+ ? { ...(subagents.agentOverrides as Record<string, unknown>) }
1804
+ : {};
1805
+
1806
+ agentOverrides[name] = cloneOverrideValue(override);
1807
+ subagents.agentOverrides = agentOverrides;
1808
+ settings.subagents = subagents;
1809
+ writeSettingsFile(filePath, settings);
1810
+ return filePath;
1811
+ });
1801
1812
  }
1802
1813
 
1803
1814
  export function removeBuiltinAgentOverride(cwd: string, name: string, scope: "user" | "project", options?: { preserveMachine?: boolean }): { path: string; removed: boolean; machinePreserved: boolean } {
@@ -1805,28 +1816,30 @@ export function removeBuiltinAgentOverride(cwd: string, name: string, scope: "us
1805
1816
  if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
1806
1817
  if (!fs.existsSync(filePath)) return { path: filePath, removed: false, machinePreserved: false };
1807
1818
 
1808
- const settings = readSettingsFileStrict(filePath);
1809
- const subagents = settings.subagents;
1810
- if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false, machinePreserved: false };
1811
- const nextSubagents = { ...(subagents as Record<string, unknown>) };
1812
- const agentOverrides = nextSubagents.agentOverrides;
1813
- if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false, machinePreserved: false };
1819
+ return withSettingsFileLease(filePath, () => {
1820
+ const settings = readSettingsFileStrict(filePath);
1821
+ const subagents = settings.subagents;
1822
+ if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false, machinePreserved: false };
1823
+ const nextSubagents = { ...(subagents as Record<string, unknown>) };
1824
+ const agentOverrides = nextSubagents.agentOverrides;
1825
+ if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false, machinePreserved: false };
1814
1826
 
1815
- const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
1816
- const current = nextOverrides[name];
1817
- if (!Object.prototype.hasOwnProperty.call(nextOverrides, name)) return { path: filePath, removed: false, machinePreserved: false };
1818
- const configuredMachine = current && typeof current === "object" && !Array.isArray(current) ? (current as Record<string, unknown>).machine : undefined;
1819
- const machine = configuredMachine === false || (typeof configuredMachine === "string" && configuredMachine.trim()) ? configuredMachine : undefined;
1820
- if (options?.preserveMachine && machine !== undefined) nextOverrides[name] = { machine };
1821
- else delete nextOverrides[name];
1822
- if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
1823
- else delete nextSubagents.agentOverrides;
1827
+ const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
1828
+ const current = nextOverrides[name];
1829
+ if (!Object.prototype.hasOwnProperty.call(nextOverrides, name)) return { path: filePath, removed: false, machinePreserved: false };
1830
+ const configuredMachine = current && typeof current === "object" && !Array.isArray(current) ? (current as Record<string, unknown>).machine : undefined;
1831
+ const machine = configuredMachine === false || (typeof configuredMachine === "string" && configuredMachine.trim()) ? configuredMachine : undefined;
1832
+ if (options?.preserveMachine && machine !== undefined) nextOverrides[name] = { machine };
1833
+ else delete nextOverrides[name];
1834
+ if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
1835
+ else delete nextSubagents.agentOverrides;
1824
1836
 
1825
- if (Object.keys(nextSubagents).length > 0) settings.subagents = nextSubagents;
1826
- else delete settings.subagents;
1837
+ if (Object.keys(nextSubagents).length > 0) settings.subagents = nextSubagents;
1838
+ else delete settings.subagents;
1827
1839
 
1828
- writeSettingsFile(filePath, settings);
1829
- return { path: filePath, removed: true, machinePreserved: options?.preserveMachine === true && machine !== undefined };
1840
+ writeSettingsFile(filePath, settings);
1841
+ return { path: filePath, removed: true, machinePreserved: options?.preserveMachine === true && machine !== undefined };
1842
+ });
1830
1843
  }
1831
1844
 
1832
1845
  export function mergeBuiltinAgentOverride(
@@ -1838,23 +1851,25 @@ export function mergeBuiltinAgentOverride(
1838
1851
  const filePath = scope === "project" ? getProjectAgentSettingsPath(cwd) : getUserAgentSettingsPath();
1839
1852
  if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
1840
1853
 
1841
- const settings = readSettingsFileStrict(filePath);
1842
- const subagents = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
1843
- ? { ...(settings.subagents as Record<string, unknown>) }
1844
- : {};
1845
- const agentOverrides = subagents.agentOverrides && typeof subagents.agentOverrides === "object" && !Array.isArray(subagents.agentOverrides)
1846
- ? { ...(subagents.agentOverrides as Record<string, unknown>) }
1847
- : {};
1848
-
1849
- const existing = agentOverrides[name];
1850
- const base = existing && typeof existing === "object" && !Array.isArray(existing)
1851
- ? existing as Record<string, unknown>
1852
- : {};
1853
- agentOverrides[name] = { ...base, ...cloneOverrideValue(fields) };
1854
- subagents.agentOverrides = agentOverrides;
1855
- settings.subagents = subagents;
1856
- writeSettingsFile(filePath, settings);
1857
- return filePath;
1854
+ return withSettingsFileLease(filePath, () => {
1855
+ const settings = readSettingsFileStrict(filePath);
1856
+ const subagents = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
1857
+ ? { ...(settings.subagents as Record<string, unknown>) }
1858
+ : {};
1859
+ const agentOverrides = subagents.agentOverrides && typeof subagents.agentOverrides === "object" && !Array.isArray(subagents.agentOverrides)
1860
+ ? { ...(subagents.agentOverrides as Record<string, unknown>) }
1861
+ : {};
1862
+
1863
+ const existing = agentOverrides[name];
1864
+ const base = existing && typeof existing === "object" && !Array.isArray(existing)
1865
+ ? existing as Record<string, unknown>
1866
+ : {};
1867
+ agentOverrides[name] = { ...base, ...cloneOverrideValue(fields) };
1868
+ subagents.agentOverrides = agentOverrides;
1869
+ settings.subagents = subagents;
1870
+ writeSettingsFile(filePath, settings);
1871
+ return filePath;
1872
+ });
1858
1873
  }
1859
1874
 
1860
1875
  export function removeBuiltinAgentOverrideFields(
@@ -1867,38 +1882,40 @@ export function removeBuiltinAgentOverrideFields(
1867
1882
  if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
1868
1883
  if (!fs.existsSync(filePath)) return { path: filePath, removed: false };
1869
1884
 
1870
- const settings = readSettingsFileStrict(filePath);
1871
- const subagents = settings.subagents;
1872
- if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false };
1873
- const agentOverrides = (subagents as Record<string, unknown>).agentOverrides;
1874
- if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false };
1875
-
1876
- const entry = (agentOverrides as Record<string, unknown>)[name];
1877
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) return { path: filePath, removed: false };
1878
-
1879
- const nextEntry: Record<string, unknown> = { ...(entry as Record<string, unknown>) };
1880
- let removed = false;
1881
- for (const field of fields) {
1882
- if (Object.prototype.hasOwnProperty.call(nextEntry, field)) {
1883
- delete nextEntry[field];
1884
- removed = true;
1885
+ return withSettingsFileLease(filePath, () => {
1886
+ const settings = readSettingsFileStrict(filePath);
1887
+ const subagents = settings.subagents;
1888
+ if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false };
1889
+ const agentOverrides = (subagents as Record<string, unknown>).agentOverrides;
1890
+ if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false };
1891
+
1892
+ const entry = (agentOverrides as Record<string, unknown>)[name];
1893
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return { path: filePath, removed: false };
1894
+
1895
+ const nextEntry: Record<string, unknown> = { ...(entry as Record<string, unknown>) };
1896
+ let removed = false;
1897
+ for (const field of fields) {
1898
+ if (Object.prototype.hasOwnProperty.call(nextEntry, field)) {
1899
+ delete nextEntry[field];
1900
+ removed = true;
1901
+ }
1885
1902
  }
1886
- }
1887
- if (!removed) return { path: filePath, removed: false };
1903
+ if (!removed) return { path: filePath, removed: false };
1888
1904
 
1889
- const nextSubagents = { ...(subagents as Record<string, unknown>) };
1890
- if (Object.keys(nextEntry).length > 0) {
1891
- (nextSubagents.agentOverrides as Record<string, unknown>)[name] = nextEntry;
1892
- } else {
1893
- const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
1894
- delete nextOverrides[name];
1895
- if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
1896
- else delete nextSubagents.agentOverrides;
1897
- }
1898
- if (Object.keys(nextSubagents).length > 0) settings.subagents = nextSubagents;
1899
- else delete settings.subagents;
1900
- writeSettingsFile(filePath, settings);
1901
- return { path: filePath, removed: true };
1905
+ const nextSubagents = { ...(subagents as Record<string, unknown>) };
1906
+ if (Object.keys(nextEntry).length > 0) {
1907
+ (nextSubagents.agentOverrides as Record<string, unknown>)[name] = nextEntry;
1908
+ } else {
1909
+ const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
1910
+ delete nextOverrides[name];
1911
+ if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
1912
+ else delete nextSubagents.agentOverrides;
1913
+ }
1914
+ if (Object.keys(nextSubagents).length > 0) settings.subagents = nextSubagents;
1915
+ else delete settings.subagents;
1916
+ writeSettingsFile(filePath, settings);
1917
+ return { path: filePath, removed: true };
1918
+ });
1902
1919
  }
1903
1920
 
1904
1921
  const DISCOVERY_PRUNED_DIR_NAMES = new Set([".git", "node_modules", ".pi", "sync-backups"]);
@@ -2344,6 +2361,13 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2344
2361
  : undefined;
2345
2362
  const memory = parseMemoryFrontmatter(frontmatter.memory);
2346
2363
  const machine = validateOptionalMachine(frontmatter.machine, `Agent '${runtimeName}' frontmatter 'machine'`);
2364
+ const launcher = frontmatter.launcher;
2365
+ if (launcher !== undefined && !RUNNER_LAUNCHER_NAME_PATTERN.test(launcher)) {
2366
+ throw new Error(`Agent '${runtimeName}' frontmatter 'launcher' ${JSON.stringify(launcher)} is invalid; launcher names ${RUNNER_LAUNCHER_NAME_RULE}.`);
2367
+ }
2368
+ if (launcher !== undefined && (runner?.type === "external-cli" || runner?.type === "external-job" || machine !== undefined)) {
2369
+ throw new Error(`Agent '${runtimeName}' sets 'launcher', which wraps the local Pi background runner, so it cannot be combined with ${machine !== undefined ? "'machine'" : `runner.type='${runner!.type}'`}.`);
2370
+ }
2347
2371
  const agent: AgentConfig = {
2348
2372
  name: runtimeName,
2349
2373
  ...(runner !== undefined ? { runner } : {}),
@@ -2383,6 +2407,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2383
2407
  ...(subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions } : {}),
2384
2408
  ...(mutationTools?.length ? { mutationTools } : {}),
2385
2409
  ...(machine !== undefined ? { machine } : {}),
2410
+ ...(launcher !== undefined ? { launcher } : {}),
2386
2411
  ...(frontmatter.output !== undefined ? { output: frontmatter.output } : {}),
2387
2412
  ...(outputMode !== undefined ? { outputMode } : {}),
2388
2413
  ...(outputSchema !== undefined ? { outputSchema } : {}),
@@ -2619,6 +2644,8 @@ export interface AgentDiscoverySnapshot {
2619
2644
  /** Undefined uses synchronous npm lookup; null skips global npm discovery. */
2620
2645
  export interface AgentDiscoveryOptions {
2621
2646
  globalNpmRoot?: string | null;
2647
+ /** False when the session declined project trust: project settings, agents, chains and packages are ignored. Defaults to true. */
2648
+ projectTrusted?: boolean;
2622
2649
  }
2623
2650
 
2624
2651
  interface LoadedAgentDirectory {
@@ -2723,11 +2750,12 @@ function discoveryFingerprint(sources: AgentDiscoverySources): string {
2723
2750
  .join("\n");
2724
2751
  }
2725
2752
 
2726
- function discoveryCacheKey(cwd: string, preferredModelProvider: string | undefined, globalNpmRoot?: string | null): string {
2753
+ function discoveryCacheKey(cwd: string, preferredModelProvider: string | undefined, globalNpmRoot: string | null | undefined, projectTrusted: boolean): string {
2727
2754
  return JSON.stringify([
2728
2755
  path.resolve(cwd),
2729
2756
  preferredModelProvider ?? null,
2730
2757
  globalNpmRoot === undefined ? ["default"] : ["override", globalNpmRoot],
2758
+ projectTrusted,
2731
2759
  getProjectConfigDir(path.resolve(cwd)),
2732
2760
  getAgentDir(),
2733
2761
  os.homedir(),
@@ -2756,16 +2784,19 @@ function packageEntryIncluded(scope: AgentScope, packageScopes: PackageSubagentP
2756
2784
  return packageScopes.has(scope);
2757
2785
  }
2758
2786
 
2759
- function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string, globalNpmRoot?: string | null): AgentDiscoverySources {
2787
+ function buildAgentDiscoverySources(cwd: string, preferredModelProvider: string | undefined, globalNpmRoot: string | null | undefined, projectTrusted: boolean): AgentDiscoverySources {
2760
2788
  const effectiveCwd = path.resolve(cwd);
2761
2789
  const userDirOld = path.join(getAgentDir(), "agents");
2762
2790
  const userDirNew = path.join(os.homedir(), ".agents");
2763
2791
  const userChainDir = getUserChainDir();
2764
- const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(effectiveCwd);
2765
- const { readDirs: projectChainDirs, preferredDir: projectChainDir } = resolveNearestProjectChainDirs(effectiveCwd);
2792
+ // The project's settings choose its root, so an untrusted project contributes no directories or settings at all.
2793
+ const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = projectTrusted
2794
+ ? resolveNearestProjectAgentDirs(effectiveCwd)
2795
+ : { readDirs: [], candidateDirs: [], preferredDir: null };
2796
+ const { readDirs: projectChainDirs, preferredDir: projectChainDir } = projectTrusted ? resolveNearestProjectChainDirs(effectiveCwd) : { readDirs: [], preferredDir: null };
2766
2797
  const userSettingsPath = getUserAgentSettingsPath();
2767
- const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
2768
- const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: true, includeProject: true, globalNpmRoot });
2798
+ const projectSettingsPath = projectTrusted ? getProjectAgentSettingsPath(effectiveCwd) : null;
2799
+ const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: true, includeProject: true, globalNpmRoot, projectTrusted });
2769
2800
  const exclusionRoots = agentExclusionRoots(userSettingsPath, projectSettingsPath);
2770
2801
  const isExcluded = agentExclusions(exclusionRoots);
2771
2802
  const userScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(userSettingsPath), isExcluded);
@@ -2851,8 +2882,8 @@ function ensureDiscoveryChains(sources: AgentDiscoverySources): void {
2851
2882
  sources.watchPaths = [...new Set([...sources.watchPaths, ...watchPaths])];
2852
2883
  }
2853
2884
 
2854
- function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false, globalNpmRoot?: string | null): AgentDiscoverySources {
2855
- const key = discoveryCacheKey(cwd, preferredModelProvider, globalNpmRoot);
2885
+ function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false, globalNpmRoot?: string | null, projectTrusted = true): AgentDiscoverySources {
2886
+ const key = discoveryCacheKey(cwd, preferredModelProvider, globalNpmRoot, projectTrusted);
2856
2887
  const cached = agentDiscoveryCache.get(key);
2857
2888
  if (cached && cached.fingerprint === discoveryFingerprint(cached.sources)) {
2858
2889
  if (includeChains) {
@@ -2861,7 +2892,7 @@ function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string,
2861
2892
  }
2862
2893
  return cached.sources;
2863
2894
  }
2864
- const sources = buildAgentDiscoverySources(cwd, preferredModelProvider, globalNpmRoot);
2895
+ const sources = buildAgentDiscoverySources(cwd, preferredModelProvider, globalNpmRoot, projectTrusted);
2865
2896
  const entry = { sources, fingerprint: discoveryFingerprint(sources) };
2866
2897
  agentDiscoveryCache.set(key, entry);
2867
2898
  if (includeChains) {
@@ -2981,12 +3012,12 @@ function buildEffectiveDiscovery(sources: AgentDiscoverySources, scope: AgentSco
2981
3012
  const injectAgents = effectiveProjectSettings.injectAgents !== undefined
2982
3013
  ? effectiveProjectSettings.injectAgents
2983
3014
  : effectiveUserSettings.injectAgents;
2984
- const agents = applySubagentMaxThinking(
2985
- mergeAgentsForScope(scope, configured.user, configured.project, configured.builtin, configured.package).filter((agent) => agent.disabled !== true),
2986
- configured.maxThinking,
2987
- );
3015
+ const merged = mergeAgentsForScope(scope, configured.user, configured.project, configured.builtin, configured.package);
3016
+ const agents = applySubagentMaxThinking(merged.filter((agent) => agent.disabled !== true), configured.maxThinking);
3017
+ const disabledAgents = merged.filter((agent) => agent.disabled === true).map((agent) => agent.name);
2988
3018
  return {
2989
3019
  agents,
3020
+ ...(disabledAgents.length ? { disabledAgents } : {}),
2990
3021
  agentDiagnostics: discoveryDiagnostics(sources, scope),
2991
3022
  projectAgentsDir: sources.projectAgentsDir,
2992
3023
  cwd: sources.cwd,
@@ -3054,8 +3085,18 @@ export function discoverAgentSnapshot(
3054
3085
  options: AgentDiscoveryOptions & { includeChains?: boolean } = {},
3055
3086
  ): AgentDiscoverySnapshot {
3056
3087
  const includeChains = options.includeChains !== false;
3057
- const sources = getAgentDiscoverySources(cwd, preferredModelProvider, includeChains, options.globalNpmRoot);
3058
- return { effective: buildEffectiveDiscovery(sources, scope), all: buildAllDiscovery(sources, includeChains, scope) };
3088
+ const projectTrusted = options.projectTrusted !== false;
3089
+ const trustedScope = trustedDiscoveryScope(cwd, scope, projectTrusted);
3090
+ const sources = getAgentDiscoverySources(cwd, preferredModelProvider, includeChains, options.globalNpmRoot, projectTrusted);
3091
+ return { effective: buildEffectiveDiscovery(sources, trustedScope), all: buildAllDiscovery(sources, includeChains, trustedScope) };
3092
+ }
3093
+
3094
+ // Pi loads nothing from an untrusted project's `.pi` directory, so declined trust leaves user scope.
3095
+ // A trusted lookup keeps its scope as given, including an omitted one from untyped callers.
3096
+ function trustedDiscoveryScope(cwd: string, scope: AgentScope, projectTrusted: boolean): AgentScope {
3097
+ if (projectTrusted) return scope;
3098
+ if (scope === "project") throw new Error(projectScopeRequiresTrustMessage(path.resolve(cwd)));
3099
+ return "user";
3059
3100
  }
3060
3101
 
3061
3102
  function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelProvider?: string, options: AgentDiscoveryOptions = {}): AgentDiscoveryResult {
@@ -3107,15 +3148,20 @@ function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelPr
3107
3148
  const packageMap = new Map<string, AgentConfig>();
3108
3149
  for (const loaded of packageLoaded) for (const agent of loaded.agents) if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
3109
3150
  const packageAgents = applyCustomAgentOverrides(applyDefaults(Array.from(packageMap.values())), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
3110
- const agents = applySubagentMaxThinking(mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents).filter((agent) => agent.disabled !== true), maxThinking);
3151
+ const merged = mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents);
3152
+ const agents = applySubagentMaxThinking(merged.filter((agent) => agent.disabled !== true), maxThinking);
3153
+ const disabledAgents = merged.filter((agent) => agent.disabled === true).map((agent) => agent.name);
3111
3154
  const agentDiagnostics = [...builtinLoaded.diagnostics, ...userLoaded.flatMap((loaded) => loaded.diagnostics), ...projectLoaded.flatMap((loaded) => loaded.diagnostics), ...packageLoaded.flatMap((loaded) => loaded.diagnostics)];
3112
- return { agents, agentDiagnostics, projectAgentsDir, cwd: effectiveCwd, scope, directories, ...(modelScope !== undefined ? { modelScope } : {}), ...(injectAgents?.length ? { injectAgents } : {}), ...(maxThinking !== undefined ? { maxThinking } : {}) };
3155
+ return { agents, ...(disabledAgents.length ? { disabledAgents } : {}), agentDiagnostics, projectAgentsDir, cwd: effectiveCwd, scope, directories, ...(injectAgents?.length ? { injectAgents } : {}), ...(modelScope !== undefined ? { modelScope } : {}), ...(maxThinking !== undefined ? { maxThinking } : {}) };
3113
3156
  }
3114
3157
 
3115
3158
  export function discoverAgents(cwd: string, scope: AgentScope, preferredModelProvider?: string, options: AgentDiscoveryOptions = {}): AgentDiscoveryResult {
3116
- if (scope !== "both") return discoverAgentsUncached(cwd, scope, preferredModelProvider, options);
3117
- const sources = getAgentDiscoverySources(cwd, preferredModelProvider, false, options.globalNpmRoot);
3118
- return buildEffectiveDiscovery(sources, scope);
3159
+ const projectTrusted = options.projectTrusted !== false;
3160
+ const trustedScope = trustedDiscoveryScope(cwd, scope, projectTrusted);
3161
+ // The uncached path always loads the project's own package.json entries.
3162
+ if (projectTrusted && trustedScope !== "both") return discoverAgentsUncached(cwd, trustedScope, preferredModelProvider, options);
3163
+ const sources = getAgentDiscoverySources(cwd, preferredModelProvider, false, options.globalNpmRoot, projectTrusted);
3164
+ return buildEffectiveDiscovery(sources, trustedScope);
3119
3165
  }
3120
3166
 
3121
3167
  export function discoverAgentsAll(cwd: string, preferredModelProvider?: string, options: AgentDiscoveryOptions = {}): AgentDiscoveryAllResult {
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { discoverAgentSnapshot, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryAllResult, type AgentScope, type AgentSource } from "../agents/agents.ts";
5
- import { resolveExecutionAgentScope } from "../agents/agent-scope.ts";
5
+ import { projectScopeRequiresTrustMessage, resolveExecutionAgentScope } from "../agents/agent-scope.ts";
6
6
  import { normalizeSkillInput, resolveSkillsWithFallback } from "../agents/skills.ts";
7
7
  import { inheritsParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, type AvailableModelInfo, type ParentModel } from "../runs/shared/model-resolution.ts";
8
8
  import { resolveModelScopesForAgent } from "../runs/shared/model-scope.ts";
@@ -67,6 +67,8 @@ export interface SubagentLaunchContractInput {
67
67
  cwd: string;
68
68
  task?: string;
69
69
  agentScope?: AgentScope;
70
+ /** False when the parent session declined project trust; project agents and project subagent settings are then ignored. Defaults to true. */
71
+ projectTrusted?: boolean;
70
72
  context?: "fresh" | "fork";
71
73
  model?: string;
72
74
  fast?: boolean;
@@ -98,8 +100,6 @@ export interface SubagentLaunchContractInput {
98
100
  nestedRootRunId?: string;
99
101
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
100
102
  inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
101
- /** Host-affirmed trust state for a project-scoped profile selection. */
102
- projectTrusted?: boolean;
103
103
  /** Exact trusted project cwd. When omitted, an affirmative trust assertion applies only to `cwd`. */
104
104
  trustedProjectCwd?: string;
105
105
  /** Builtin tool names the host runtime provides; used to intersect agent-declared tools. */
@@ -323,8 +323,12 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
323
323
  return { ok: false, code: "invalid_intercom_bridge", message: "orchestratorTarget must be a non-empty string when provided.", diagnostics };
324
324
  }
325
325
  const scope = resolveExecutionAgentScope(input.agentScope);
326
+ if (input.projectTrusted === false && scope === "project") {
327
+ const message = projectScopeRequiresTrustMessage(effectiveCwd);
328
+ return { ok: false, code: "restricted_agent", message, diagnostics: [...diagnostics, { code: "restricted_agent", severity: "error", message }] };
329
+ }
326
330
  const parentProvider = input.preferredProvider ?? input.parentModel?.provider;
327
- const discovery = discoverAgentSnapshot(effectiveCwd, scope, parentProvider, { includeChains: false });
331
+ const discovery = discoverAgentSnapshot(effectiveCwd, scope, parentProvider, { includeChains: false, projectTrusted: input.projectTrusted });
328
332
  const discovered = discovery.effective;
329
333
  const resolvedAgent = resolveAgentName(input.agent, discovered.agents);
330
334
  const ambiguousCandidates = resolvedAgent.error