@xzzpig/pi-subagents 0.13.0 → 0.15.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 (202) hide show
  1. package/CHANGELOG.md +243 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +93 -15
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +67 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +19 -0
  19. package/node_modules/@xzzpig/pi-components/README.md +28 -0
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +46 -4
  21. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +65 -17
  22. package/node_modules/@xzzpig/pi-components/package.json +1 -1
  23. package/node_modules/@xzzpig/pi-components/src/transcript.ts +107 -14
  24. package/package.json +10 -5
  25. package/prompts/parallel-review.md +1 -1
  26. package/runner-peer-loader.mjs +24 -0
  27. package/runner-peer-preload.mjs +36 -0
  28. package/skills/pi-subagents/SKILL.md +34 -22
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  30. package/skills/pi-subagents/references/execution-controls.md +27 -8
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  33. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  34. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  35. package/src/agents/advertised-agent-prompt.ts +94 -0
  36. package/src/agents/agent-management.ts +71 -59
  37. package/src/agents/agent-serializer.ts +6 -3
  38. package/src/agents/agents.ts +198 -72
  39. package/src/agents/builtin-names.ts +1 -0
  40. package/src/agents/chain-serializer.ts +5 -0
  41. package/src/agents/runtime-agent-registry.ts +7 -6
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +110 -71
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +32 -13
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +766 -432
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +896 -397
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +44 -16
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +145 -14
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +19 -10
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  148. package/src/runs/shared/run-fanout-budget.ts +8 -8
  149. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  150. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  151. package/src/runs/shared/task-intent.ts +46 -13
  152. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  153. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  154. package/src/runs/shared/worktree-setup-command.ts +213 -0
  155. package/src/runs/shared/worktree.ts +437 -214
  156. package/src/shared/child-cache-retention.ts +43 -0
  157. package/src/shared/fork-context.ts +15 -72
  158. package/src/shared/launch-contract.ts +70 -8
  159. package/src/shared/model-response-aliases.ts +13 -0
  160. package/src/shared/opencode-session-headers.ts +30 -0
  161. package/src/shared/pruned-fork.ts +1 -1
  162. package/src/shared/required-child-extensions.ts +81 -0
  163. package/src/shared/settings.ts +5 -2
  164. package/src/shared/shortcuts.ts +0 -4
  165. package/src/shared/types.ts +164 -90
  166. package/src/shared/utils.ts +10 -2
  167. package/src/shared/watch-strategy.ts +2 -0
  168. package/src/shared/workflow-child-permit.ts +18 -13
  169. package/src/slash/delegation-adapters.ts +3 -1
  170. package/src/slash/delegation-request.ts +14 -0
  171. package/src/slash/slash-commands.ts +2 -7
  172. package/src/slash/subagents-admin.ts +31 -14
  173. package/src/tui/fleet-native-transcript.ts +50 -6
  174. package/src/tui/fleet-status.ts +165 -20
  175. package/src/tui/fleet.ts +52 -21
  176. package/src/tui/render.ts +210 -50
  177. package/src/watchdog/child-status.ts +28 -28
  178. package/src/watchdog/lsp-diagnostics.ts +1 -1
  179. package/src/watchdog/model-selection.ts +21 -1
  180. package/src/watchdog/permission-arbiter.ts +5 -2
  181. package/src/watchdog/register-child.ts +10 -2
  182. package/src/watchdog/register-main.ts +39 -35
  183. package/src/watchdog/render.ts +1 -1
  184. package/src/watchdog/review.ts +122 -74
  185. package/src/watchdog/rules.ts +1 -1
  186. package/src/watchdog/runtime.ts +100 -27
  187. package/src/watchdog/scope.ts +1 -1
  188. package/src/watchdog/settings.ts +3 -0
  189. package/src/watchdog/tool-actions.ts +13 -12
  190. package/src/watchdog/turn-delta.ts +23 -0
  191. package/src/watchdog/types.ts +5 -3
  192. package/src/watchdog/warning-format.ts +1 -1
  193. package/src/workflows/chat-progress.ts +3 -3
  194. package/src/workflows/scripted-workflow.ts +349 -26
  195. package/src/workflows/workflow-checklist.ts +17 -20
  196. package/src/workflows/workflow-child-summary.ts +57 -8
  197. package/src/workflows/workflow-preflight.ts +19 -19
  198. package/src/workflows/workflow-receipt.ts +24 -6
  199. package/src/workflows/workflow-resources.ts +108 -22
  200. package/src/workflows/workflow-settlement.ts +3 -0
  201. package/src/runs/shared/model-exclusions.ts +0 -373
  202. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -8,7 +8,7 @@ import { parse as parseYaml } from "yaml";
8
8
  import * as os from "node:os";
9
9
  import * as path from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
- import type { AcceptanceInput, AcceptanceRole, AgentRunnerConfig, OutputMode, ToolBudgetConfig } from "../shared/types.ts";
11
+ import type { AcceptanceInput, AcceptanceRole, AgentRunnerConfig, JsonSchemaObject, OutputMode, ToolBudgetConfig } from "../shared/types.ts";
12
12
  import { CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL, isCodeOwnedExternalCliAdapterId, parseExternalCliCapabilityNarrowing, validateCodeOwnedProfileRunner } from "../runs/shared/external-cli-contract.ts";
13
13
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
14
14
  import { expandHomePath } from "../shared/settings.ts";
@@ -26,6 +26,7 @@ import { validatePermissionRules, type PermissionRules } from "../runs/shared/pe
26
26
  import { parseThinkingLevel, type ThinkingLevel } from "../shared/thinking-ceiling.ts";
27
27
  import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
28
28
  import { validatePermissionProfileName } from "../shared/permission-profile.ts";
29
+ import { assertJsonSchemaObject } from "../runs/shared/structured-output.ts";
29
30
 
30
31
  export type AgentScope = "user" | "project" | "both";
31
32
 
@@ -54,12 +55,12 @@ export function defaultInheritSkills(): boolean {
54
55
 
55
56
  export interface BuiltinAgentOverrideBase {
56
57
  description?: string;
58
+ machine?: string;
57
59
  output?: string;
58
60
  outputMode?: OutputMode;
59
61
  defaultReads?: string[];
60
62
  model?: string;
61
63
  modelProvider?: string;
62
- fallbackModels?: string[];
63
64
  fast?: boolean;
64
65
  thinking?: string | false;
65
66
  systemPromptMode: SystemPromptMode;
@@ -87,12 +88,12 @@ export interface BuiltinAgentOverrideBase {
87
88
 
88
89
  interface BuiltinAgentOverrideConfig {
89
90
  description?: string;
91
+ machine?: string | false;
90
92
  output?: string | false;
91
93
  outputMode?: OutputMode;
92
94
  defaultReads?: string[] | false;
93
95
  model?: string | false;
94
96
  defaultProvider?: string | false;
95
- fallbackModels?: string[] | false;
96
97
  fast?: boolean;
97
98
  thinking?: string | false;
98
99
  systemPromptMode?: SystemPromptMode;
@@ -141,6 +142,7 @@ export interface AgentConfig {
141
142
  packageSourceVersion?: string;
142
143
  packageSourceRoot?: string;
143
144
  description: string;
145
+ advertise?: boolean;
144
146
  aliases?: string[];
145
147
  tools?: string[];
146
148
  excludeTools?: string[];
@@ -148,7 +150,6 @@ export interface AgentConfig {
148
150
  mcpDirectTools?: string[];
149
151
  model?: string;
150
152
  modelProvider?: string;
151
- fallbackModels?: string[];
152
153
  fast?: boolean;
153
154
  thinking?: string | false;
154
155
  systemPromptMode: SystemPromptMode;
@@ -173,6 +174,7 @@ export interface AgentConfig {
173
174
  mutationTools?: string[];
174
175
  output?: string;
175
176
  outputMode?: OutputMode;
177
+ outputSchema?: JsonSchemaObject;
176
178
  defaultReads?: string[];
177
179
  defaultProgress?: boolean;
178
180
  injectToContext?: boolean;
@@ -184,11 +186,18 @@ export interface AgentConfig {
184
186
  permissionProfile?: string;
185
187
  permissions?: PermissionRules;
186
188
  memory?: AgentMemoryConfig;
189
+ machine?: string;
187
190
  disabled?: boolean;
188
191
  extraFields?: Record<string, string>;
189
192
  override?: BuiltinAgentOverrideInfo;
190
193
  modelSource?: AgentModelSourceInfo;
191
194
  maxThinking?: ThinkingLevel;
195
+ /**
196
+ * Digest of the parsed definition, set when a runtime overlay such as the
197
+ * Intercom bridge rewrites launch-affecting fields. Launch identity reads
198
+ * this instead of re-hashing the overlaid copy.
199
+ */
200
+ definitionDigest?: string;
192
201
  }
193
202
 
194
203
  type ProjectRootResolution = "nearest" | "git-root";
@@ -197,6 +206,7 @@ interface SubagentSettings {
197
206
  overrides: Record<string, BuiltinAgentOverrideConfig>;
198
207
  providerOverrides: Record<string, Record<string, BuiltinAgentOverrideConfig>>;
199
208
  agentScanDirs?: string[];
209
+ agentExcludeDirs?: string[];
200
210
  defaultModel?: string;
201
211
  defaultProvider?: string;
202
212
  defaultThinking?: string;
@@ -218,6 +228,7 @@ export interface ChainStepConfig {
218
228
  label?: string;
219
229
  as?: string;
220
230
  outputSchema?: string | Record<string, unknown>;
231
+ machine?: string;
221
232
  output?: string | false;
222
233
  outputMode?: OutputMode;
223
234
  reads?: string[] | false;
@@ -605,8 +616,8 @@ function collectSettingsPackageRoots(settingsFile: string, baseDir: string): str
605
616
  for (const entry of packages) {
606
617
  const packageSource = typeof entry === "string"
607
618
  ? entry
608
- : typeof entry === "object" && entry !== null && typeof (entry as { source?: unknown }).source === "string"
609
- ? (entry as { source: string }).source
619
+ : typeof entry === "object" && entry !== null && "source" in entry && typeof entry.source === "string"
620
+ ? entry.source
610
621
  : undefined;
611
622
  if (!packageSource) continue;
612
623
  const packageRoot = resolveSettingsPackageRoot(packageSource, baseDir);
@@ -714,12 +725,20 @@ function effectiveAgentMatch(matches: AgentConfig[]): { agent?: AgentConfig; err
714
725
 
715
726
  export function resolveAgentName(name: string, agents: AgentConfig[]): { agent?: AgentConfig; error?: string } {
716
727
  const raw = name.trim();
717
- const exact = agents.filter((agent) => agent.name === raw || agent.localName === raw);
718
- if (exact.length === 1) return exact[0] ? { agent: exact[0] } : {};
719
- if (exact.length > 1) {
720
- const effective = effectiveAgentMatch(exact);
728
+ const canonical = agents.filter((agent) => agent.name === raw);
729
+ if (canonical.length === 1) return canonical[0] ? { agent: canonical[0] } : {};
730
+ if (canonical.length > 1) {
731
+ const effective = effectiveAgentMatch(canonical);
721
732
  if (effective.agent) return effective;
722
- return { error: `Ambiguous agent name '${name}': ${exact.map((agent) => agent.name).join(", ")}` };
733
+ return { error: `Ambiguous agent name '${name}': ${canonical.map((agent) => agent.name).join(", ")}` };
734
+ }
735
+
736
+ const local = agents.filter((agent) => agent.localName === raw);
737
+ if (local.length === 1) return local[0] ? { agent: local[0] } : {};
738
+ if (local.length > 1) {
739
+ const effective = effectiveAgentMatch(local);
740
+ if (effective.agent) return effective;
741
+ return { error: `Ambiguous local agent name '${name}': ${local.map((agent) => agent.name).join(", ")}` };
723
742
  }
724
743
 
725
744
  const aliases = agents.filter((agent) => agent.aliases?.includes(raw));
@@ -769,12 +788,12 @@ function arraysEqual(a: string[] | undefined, b: string[] | undefined): boolean
769
788
  function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
770
789
  return {
771
790
  description: agent.description,
791
+ ...(agent.machine !== undefined ? { machine: agent.machine } : {}),
772
792
  ...(agent.output !== undefined ? { output: agent.output } : {}),
773
793
  ...(agent.outputMode !== undefined ? { outputMode: agent.outputMode } : {}),
774
794
  ...(agent.defaultReads !== undefined ? { defaultReads: [...agent.defaultReads] } : {}),
775
795
  ...(agent.model !== undefined ? { model: agent.model } : {}),
776
796
  ...(agent.modelProvider !== undefined ? { modelProvider: agent.modelProvider } : {}),
777
- ...(agent.fallbackModels ? { fallbackModels: [...agent.fallbackModels] } : {}),
778
797
  ...(agent.fast !== undefined ? { fast: agent.fast } : {}),
779
798
  ...(agent.thinking !== undefined ? { thinking: agent.thinking } : {}),
780
799
  systemPromptMode: agent.systemPromptMode,
@@ -804,14 +823,12 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
804
823
  function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentOverrideConfig {
805
824
  return {
806
825
  ...(override.description !== undefined ? { description: override.description } : {}),
826
+ ...(override.machine !== undefined ? { machine: override.machine } : {}),
807
827
  ...(override.output !== undefined ? { output: override.output } : {}),
808
828
  ...(override.outputMode !== undefined ? { outputMode: override.outputMode } : {}),
809
829
  ...(override.defaultReads !== undefined ? { defaultReads: override.defaultReads === false ? false : [...override.defaultReads] } : {}),
810
830
  ...(override.model !== undefined ? { model: override.model } : {}),
811
831
  ...(override.defaultProvider !== undefined ? { defaultProvider: override.defaultProvider } : {}),
812
- ...(override.fallbackModels !== undefined
813
- ? { fallbackModels: override.fallbackModels === false ? false : [...override.fallbackModels] }
814
- : {}),
815
832
  ...(override.fast !== undefined ? { fast: override.fast } : {}),
816
833
  ...(override.thinking !== undefined ? { thinking: override.thinking } : {}),
817
834
  ...(override.systemPromptMode !== undefined ? { systemPromptMode: override.systemPromptMode } : {}),
@@ -842,8 +859,17 @@ function isProjectRootCandidate(dir: string): boolean {
842
859
 
843
860
  function findProjectRootCandidates(cwd: string): string[] {
844
861
  const roots: string[] = [];
862
+ const windowsProfile = process.env.HOMEDRIVE && process.env.HOMEPATH
863
+ ? `${process.env.HOMEDRIVE}${process.env.HOMEPATH}`
864
+ : undefined;
865
+ const homeDirs = new Set([os.homedir(), process.env.HOME, process.env.USERPROFILE, windowsProfile]
866
+ .filter((value): value is string => Boolean(value?.trim()))
867
+ .filter(isDirectory)
868
+ .map((value) => fs.realpathSync.native(value)));
845
869
  let currentDir = cwd;
846
870
  while (true) {
871
+ // ~/.pi and ~/.agents are user configuration, never an implicit project.
872
+ if (isDirectory(currentDir) && homeDirs.has(fs.realpathSync.native(currentDir))) return roots;
847
873
  if (isProjectRootCandidate(currentDir)) roots.push(currentDir);
848
874
 
849
875
  const parentDir = path.dirname(currentDir);
@@ -975,6 +1001,15 @@ function parseToolsOverride(
975
1001
  throw new Error(`Builtin override '${meta.name}' in '${meta.filePath}' has invalid 'tools'; expected an array of strings, "inherit", or false.`);
976
1002
  }
977
1003
 
1004
+ function validateOptionalMachine(value: unknown, label: string): string | undefined {
1005
+ if (value === undefined || value === false) return undefined;
1006
+ if (typeof value !== "string" || !value.trim()) throw new Error(label + " must be a non-empty string or false.");
1007
+ const machine = value.trim();
1008
+ if (machine.length > 128) throw new Error(label + " must be 128 characters or fewer.");
1009
+ if (/[\u0000-\u001f\u007f]/u.test(machine)) throw new Error(label + " contains control characters.");
1010
+ return machine;
1011
+ }
1012
+
978
1013
  function parseBuiltinOverrideEntry(
979
1014
  name: string,
980
1015
  value: unknown,
@@ -985,6 +1020,9 @@ function parseBuiltinOverrideEntry(
985
1020
  }
986
1021
 
987
1022
  const input = value as Record<string, unknown>;
1023
+ if (Object.hasOwn(input, "fallbackModels")) {
1024
+ throw new Error(`Builtin override '${name}' in '${filePath}' uses removed field 'fallbackModels'; configure one model instead.`);
1025
+ }
988
1026
  const override: BuiltinAgentOverrideConfig = {};
989
1027
 
990
1028
  if ("description" in input) {
@@ -1110,11 +1148,15 @@ function parseBuiltinOverrideEntry(
1110
1148
  else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'systemPrompt'; expected a string.`);
1111
1149
  }
1112
1150
 
1151
+ if (input.machine === false) override.machine = false;
1152
+ else {
1153
+ const machine = validateOptionalMachine(input.machine, `Builtin override '${name}' in '${filePath}' field 'machine'`);
1154
+ if (machine !== undefined) override.machine = machine;
1155
+ }
1156
+
1113
1157
  const defaultReads = parseOverrideStringArrayOrFalse(input.defaultReads, { filePath, name, field: "defaultReads" });
1114
1158
  if (defaultReads !== undefined) override.defaultReads = defaultReads;
1115
1159
 
1116
- const fallbackModels = parseOverrideStringArrayOrFalse(input.fallbackModels, { filePath, name, field: "fallbackModels" });
1117
- if (fallbackModels !== undefined) override.fallbackModels = fallbackModels;
1118
1160
 
1119
1161
  if ("defaultProvider" in input) {
1120
1162
  if (input.defaultProvider === false) override.defaultProvider = false;
@@ -1225,6 +1267,14 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
1225
1267
  }
1226
1268
  agentScanDirs = subagentsObject.agentScanDirs.map((item) => item.trim());
1227
1269
  }
1270
+ let agentExcludeDirs: string[] | undefined;
1271
+ if ("agentExcludeDirs" in subagentsObject) {
1272
+ if (!Array.isArray(subagentsObject.agentExcludeDirs)
1273
+ || subagentsObject.agentExcludeDirs.some((item) => typeof item !== "string" || !item.trim())) {
1274
+ throw new Error(`Subagent settings in '${filePath}' have invalid 'agentExcludeDirs'; expected an array of non-empty strings.`);
1275
+ }
1276
+ agentExcludeDirs = subagentsObject.agentExcludeDirs.map((item) => item.trim());
1277
+ }
1228
1278
  const modelScope = parseModelScopeConfig(subagentsObject.modelScope, { filePath });
1229
1279
 
1230
1280
  const parsed: Record<string, BuiltinAgentOverrideConfig> = {};
@@ -1240,7 +1290,7 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
1240
1290
  ...(maxThinking !== undefined ? { maxThinking } : {}),
1241
1291
  ...(defaultExtensions !== undefined ? { defaultExtensions } : {}),
1242
1292
  ...(agentScanDirs !== undefined ? { agentScanDirs } : {}),
1243
- ...(injectAgents !== undefined ? { injectAgents } : {}),
1293
+ ...(agentExcludeDirs !== undefined ? { agentExcludeDirs } : {}),
1244
1294
  ...(disableBuiltins !== undefined ? { disableBuiltins } : {}),
1245
1295
  ...(disableThinking !== undefined ? { disableThinking } : {}),
1246
1296
  ...(modelScope !== undefined ? { modelScope } : {}),
@@ -1420,6 +1470,7 @@ function applyBuiltinOverride(
1420
1470
  };
1421
1471
 
1422
1472
  if (override.description !== undefined) next.description = override.description;
1473
+ if (override.machine !== undefined) { if (override.machine === false) delete next.machine; else next.machine = override.machine; }
1423
1474
  if (override.output !== undefined) { if (override.output === false) delete next.output; else next.output = override.output; }
1424
1475
  if (override.outputMode !== undefined) next.outputMode = override.outputMode;
1425
1476
  if (override.defaultReads !== undefined) { if (override.defaultReads === false) delete next.defaultReads; else next.defaultReads = [...override.defaultReads]; }
@@ -1431,7 +1482,6 @@ function applyBuiltinOverride(
1431
1482
  if (override.defaultProvider === false) delete next.modelProvider;
1432
1483
  else next.modelProvider = override.defaultProvider;
1433
1484
  }
1434
- if (override.fallbackModels !== undefined) { if (override.fallbackModels === false) delete next.fallbackModels; else next.fallbackModels = [...override.fallbackModels]; }
1435
1485
  if (override.fast !== undefined) next.fast = override.fast;
1436
1486
  if (override.thinking !== undefined) { if (override.thinking === false) delete next.thinking; else next.thinking = override.thinking; }
1437
1487
  if (override.systemPromptMode !== undefined) next.systemPromptMode = override.systemPromptMode;
@@ -1554,9 +1604,10 @@ function applyCustomAgentOverrides(
1554
1604
 
1555
1605
  export function buildBuiltinOverrideConfig(
1556
1606
  base: BuiltinAgentOverrideBase,
1557
- draft: Pick<AgentConfig, "model" | "modelProvider" | "fallbackModels" | "fast" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritGlobalContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "allowNestedSubagents" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "mutationTools" | "completionGuard" | "toolBudget" | "sandbox" | "permissionProfile"> & Partial<Pick<AgentConfig, "description" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
1607
+ draft: Pick<AgentConfig, "model" | "modelProvider" | "fast" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritGlobalContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "allowNestedSubagents" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "mutationTools" | "completionGuard" | "toolBudget" | "sandbox" | "permissionProfile"> & Partial<Pick<AgentConfig, "description" | "machine" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
1558
1608
  ): BuiltinAgentOverrideConfig | undefined {
1559
1609
  const override: BuiltinAgentOverrideConfig = {};
1610
+ if (draft.machine !== base.machine) override.machine = draft.machine ?? false;
1560
1611
 
1561
1612
  if (draft.description !== undefined) {
1562
1613
  const description = draft.description.trim();
@@ -1567,7 +1618,6 @@ export function buildBuiltinOverrideConfig(
1567
1618
  if (!arraysEqual(draft.defaultReads, base.defaultReads)) override.defaultReads = draft.defaultReads ? [...draft.defaultReads] : false;
1568
1619
  if (draft.model !== base.model) override.model = draft.model ?? false;
1569
1620
  if (draft.modelProvider !== base.modelProvider) override.defaultProvider = draft.modelProvider ?? false;
1570
- if (!arraysEqual(draft.fallbackModels, base.fallbackModels)) override.fallbackModels = draft.fallbackModels ? [...draft.fallbackModels] : false;
1571
1621
  if (draft.fast !== base.fast) override.fast = draft.fast === true;
1572
1622
  if (draft.thinking !== base.thinking) override.thinking = draft.thinking ?? false;
1573
1623
  if (draft.systemPromptMode !== base.systemPromptMode) override.systemPromptMode = draft.systemPromptMode;
@@ -1624,21 +1674,25 @@ export function saveBuiltinAgentOverride(
1624
1674
  return filePath;
1625
1675
  }
1626
1676
 
1627
- export function removeBuiltinAgentOverride(cwd: string, name: string, scope: "user" | "project"): { path: string; removed: boolean } {
1677
+ export function removeBuiltinAgentOverride(cwd: string, name: string, scope: "user" | "project", options?: { preserveMachine?: boolean }): { path: string; removed: boolean; machinePreserved: boolean } {
1628
1678
  const filePath = scope === "project" ? getProjectAgentSettingsPath(cwd) : getUserAgentSettingsPath();
1629
1679
  if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
1630
- if (!fs.existsSync(filePath)) return { path: filePath, removed: false };
1680
+ if (!fs.existsSync(filePath)) return { path: filePath, removed: false, machinePreserved: false };
1631
1681
 
1632
1682
  const settings = readSettingsFileStrict(filePath);
1633
1683
  const subagents = settings.subagents;
1634
- if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false };
1684
+ if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false, machinePreserved: false };
1635
1685
  const nextSubagents = { ...(subagents as Record<string, unknown>) };
1636
1686
  const agentOverrides = nextSubagents.agentOverrides;
1637
- if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false };
1687
+ if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false, machinePreserved: false };
1638
1688
 
1639
1689
  const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
1640
- if (!Object.prototype.hasOwnProperty.call(nextOverrides, name)) return { path: filePath, removed: false };
1641
- delete nextOverrides[name];
1690
+ const current = nextOverrides[name];
1691
+ if (!Object.prototype.hasOwnProperty.call(nextOverrides, name)) return { path: filePath, removed: false, machinePreserved: false };
1692
+ const configuredMachine = current && typeof current === "object" && !Array.isArray(current) ? (current as Record<string, unknown>).machine : undefined;
1693
+ const machine = configuredMachine === false || (typeof configuredMachine === "string" && configuredMachine.trim()) ? configuredMachine : undefined;
1694
+ if (options?.preserveMachine && machine !== undefined) nextOverrides[name] = { machine };
1695
+ else delete nextOverrides[name];
1642
1696
  if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
1643
1697
  else delete nextSubagents.agentOverrides;
1644
1698
 
@@ -1646,7 +1700,7 @@ export function removeBuiltinAgentOverride(cwd: string, name: string, scope: "us
1646
1700
  else delete settings.subagents;
1647
1701
 
1648
1702
  writeSettingsFile(filePath, settings);
1649
- return { path: filePath, removed: true };
1703
+ return { path: filePath, removed: true, machinePreserved: options?.preserveMachine === true && machine !== undefined };
1650
1704
  }
1651
1705
 
1652
1706
  export function mergeBuiltinAgentOverride(
@@ -1818,8 +1872,9 @@ const DEFAULT_AGENT_DEFINITION_INSPECTION_FS: AgentDefinitionInspectionFs = {
1818
1872
  * state. A nested unreadable directory makes the whole inspection unavailable,
1819
1873
  * preventing a partial traversal from being reported as empty or complete.
1820
1874
  */
1821
- export function inspectAgentDefinitionDirectory(dir: string, operations: AgentDefinitionInspectionFs = DEFAULT_AGENT_DEFINITION_INSPECTION_FS): AgentDefinitionInspection {
1875
+ export function inspectAgentDefinitionDirectory(dir: string, operations: AgentDefinitionInspectionFs = DEFAULT_AGENT_DEFINITION_INSPECTION_FS, isExcluded: (filePath: string) => boolean = () => false): AgentDefinitionInspection {
1822
1876
  const root = path.resolve(dir);
1877
+ if (isExcluded(root)) return rememberAgentDefinitionInspection({ files: [], state: "empty" }, []);
1823
1878
  try {
1824
1879
  if (!operations.existsSync(root)) return rememberAgentDefinitionInspection({ files: [], state: "absent" }, [root]);
1825
1880
  if (!operations.statSync(root).isDirectory()) return rememberAgentDefinitionInspection({ files: [], state: "not-directory" }, [root]);
@@ -1851,6 +1906,7 @@ export function inspectAgentDefinitionDirectory(dir: string, operations: AgentDe
1851
1906
  }
1852
1907
  for (const entry of entries) {
1853
1908
  const filePath = path.join(current, entry.name);
1909
+ if (isExcluded(filePath)) continue;
1854
1910
  let isDirectory = entry.isDirectory();
1855
1911
  if (entry.isSymbolicLink()) {
1856
1912
  try {
@@ -1950,7 +2006,7 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
1950
2006
 
1951
2007
  function validateExternalRunnerProfile(frontmatter: Record<string, string>, agentName: string, runner: AgentRunnerConfig | undefined): void {
1952
2008
  if (runner?.type !== "external-cli" && runner?.type !== "external-job") return;
1953
- const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "sandbox", "permission-profile", "permission", "permissions"]
2009
+ const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "sandbox", "permission-profile", "permission", "permissions"]
1954
2010
  .filter((field) => frontmatter[field] !== undefined);
1955
2011
  if (unsupported.length > 0) {
1956
2012
  throw new Error(`Agent '${agentName}' uses runner.type='${runner.type}' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
@@ -2028,6 +2084,12 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2028
2084
 
2029
2085
  const runner = parseAgentRunnerFrontmatter(frontmatter.runner, localName);
2030
2086
  validateExternalRunnerProfile(frontmatter, localName, runner);
2087
+ let advertise: boolean | undefined;
2088
+ if (frontmatter.advertise !== undefined) {
2089
+ if (frontmatter.advertise === "true") advertise = true;
2090
+ else if (frontmatter.advertise === "false") advertise = false;
2091
+ else throw new Error(`Agent '${localName}' has invalid advertise frontmatter; expected true or false.`);
2092
+ }
2031
2093
  const rawTools = parseFrontmatterList(frontmatter.tools);
2032
2094
  const parsedTools = splitToolList(rawTools);
2033
2095
  const tools = parsedTools.tools ?? [];
@@ -2040,7 +2102,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2040
2102
  const skillStr = frontmatter.skill || frontmatter.skills;
2041
2103
  const skills = parseFrontmatterList(skillStr);
2042
2104
  const skillPath = parseFrontmatterList(frontmatter.skillPath);
2043
- const fallbackModels = parseFrontmatterList(frontmatter.fallbackModels);
2105
+ if (frontmatter.fallbackModels !== undefined) throw new Error(`Agent '${filePath}' uses removed frontmatter field 'fallbackModels'. Configure one model instead.`);
2044
2106
  const systemPromptMode = frontmatter.systemPromptMode === "replace"
2045
2107
  ? "replace"
2046
2108
  : frontmatter.systemPromptMode === "append"
@@ -2139,6 +2201,12 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2139
2201
  }
2140
2202
  toolBudget = parsed as ToolBudgetConfig;
2141
2203
  }
2204
+ let outputSchema: JsonSchemaObject | undefined;
2205
+ if (frontmatter.outputSchema !== undefined && frontmatter.outputSchema.trim()) {
2206
+ const parsed: unknown = JSON.parse(frontmatter.outputSchema);
2207
+ assertJsonSchemaObject(parsed, `Agent '${localName}' outputSchema`);
2208
+ outputSchema = parsed;
2209
+ }
2142
2210
  const completionGuard = frontmatter.completionGuard === "false"
2143
2211
  ? false
2144
2212
  : frontmatter.completionGuard === "true"
@@ -2149,6 +2217,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2149
2217
  ? parsedMaxSubagentDepth
2150
2218
  : undefined;
2151
2219
  const memory = parseMemoryFrontmatter(frontmatter.memory);
2220
+ const machine = validateOptionalMachine(frontmatter.machine, `Agent '${runtimeName}' frontmatter 'machine'`);
2152
2221
  const agent: AgentConfig = {
2153
2222
  name: runtimeName,
2154
2223
  ...(runner !== undefined ? { runner } : {}),
@@ -2158,13 +2227,13 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2158
2227
  ...(packageSource?.packageVersion ? { packageSourceVersion: packageSource.packageVersion } : {}),
2159
2228
  ...(packageSource?.packageRoot ? { packageSourceRoot: packageSource.packageRoot } : {}),
2160
2229
  description: frontmatter.description,
2230
+ ...(advertise !== undefined ? { advertise } : {}),
2161
2231
  ...(aliases !== undefined ? { aliases } : {}),
2162
2232
  ...(rawTools !== undefined ? { tools } : {}),
2163
2233
  ...(excludeTools !== undefined ? { excludeTools } : {}),
2164
2234
  ...(allowNestedSubagents !== undefined ? { allowNestedSubagents } : {}),
2165
2235
  ...(mcpDirectTools.length > 0 ? { mcpDirectTools } : {}),
2166
2236
  ...(frontmatter.model !== undefined ? { model: frontmatter.model } : {}),
2167
- ...(fallbackModels?.length ? { fallbackModels } : {}),
2168
2237
  ...(fast !== undefined ? { fast } : {}),
2169
2238
  ...(frontmatter.thinking !== undefined ? { thinking: frontmatter.thinking === "false" ? false : frontmatter.thinking } : {}),
2170
2239
  systemPromptMode,
@@ -2186,8 +2255,10 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2186
2255
  ...(extensions !== undefined ? { extensions } : {}),
2187
2256
  ...(subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions } : {}),
2188
2257
  ...(mutationTools?.length ? { mutationTools } : {}),
2258
+ ...(machine !== undefined ? { machine } : {}),
2189
2259
  ...(frontmatter.output !== undefined ? { output: frontmatter.output } : {}),
2190
2260
  ...(outputMode !== undefined ? { outputMode } : {}),
2261
+ ...(outputSchema !== undefined ? { outputSchema } : {}),
2191
2262
  ...(defaultReads?.length ? { defaultReads } : {}),
2192
2263
  defaultProgress: frontmatter.defaultProgress === "true",
2193
2264
  injectToContext: frontmatter.injectToContext === "true",
@@ -2310,31 +2381,60 @@ interface AgentScanDirs {
2310
2381
  watchPaths: string[];
2311
2382
  }
2312
2383
 
2313
- function readConfiguredAgentScanDirs(filePath: string | null): string[] {
2384
+ function readConfiguredAgentScanDirs(filePath: string | null, key: "agentScanDirs" | "agentExcludeDirs" = "agentScanDirs"): string[] {
2314
2385
  if (!filePath) return [];
2315
2386
  try {
2316
2387
  const settings = readSettingsFileStrict(filePath);
2317
2388
  const subagents = settings.subagents;
2318
2389
  if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return [];
2319
- const dirs = (subagents as { agentScanDirs?: unknown }).agentScanDirs;
2390
+ const dirs = (subagents as Record<string, unknown>)[key];
2320
2391
  return Array.isArray(dirs) ? dirs.filter((dir): dir is string => typeof dir === "string" && dir.trim().length > 0) : [];
2321
2392
  } catch {
2322
2393
  return [];
2323
2394
  }
2324
2395
  }
2325
2396
 
2326
- function expandAgentScanDirPattern(pattern: string): AgentScanDirs {
2397
+ // Resolve existing ancestors to canonicalize missing descendants of symlinks.
2398
+ function canonicalAgentPath(filePath: string): string {
2399
+ const resolved = path.resolve(filePath);
2400
+ try {
2401
+ return fs.realpathSync(resolved);
2402
+ } catch {
2403
+ const parent = path.dirname(resolved);
2404
+ return parent === resolved ? resolved : path.join(canonicalAgentPath(parent), path.basename(resolved));
2405
+ }
2406
+ }
2407
+
2408
+ function agentExclusionRoots(userSettingsPath: string, projectSettingsPath: string | null): Array<{ resolved: string; real: string }> {
2409
+ return [userSettingsPath, projectSettingsPath].flatMap((settingsPath) => settingsPath
2410
+ ? readConfiguredAgentScanDirs(settingsPath, "agentExcludeDirs").map((entry) => {
2411
+ const resolved = path.resolve(path.dirname(settingsPath), expandHomePath(entry.trim()).replace(/[\\/]+/g, path.sep));
2412
+ return { resolved, real: canonicalAgentPath(resolved) };
2413
+ }) : []);
2414
+ }
2415
+
2416
+ function agentExclusions(roots: Array<{ resolved: string; real: string }>): (filePath: string) => boolean {
2417
+ return (filePath) => {
2418
+ if (!roots.length) return false;
2419
+ if (roots.some((root) => isPathWithin(root.resolved, filePath))) return true;
2420
+ const real = canonicalAgentPath(filePath);
2421
+ return roots.some((root) => isPathWithin(root.real, real));
2422
+ };
2423
+ }
2424
+
2425
+ function expandAgentScanDirPattern(pattern: string, isExcluded: (filePath: string) => boolean): AgentScanDirs {
2327
2426
  const expanded = expandHomePath(pattern.trim()).replace(/[\\/]+/g, path.sep);
2328
2427
  if (!expanded) return { dirs: [], watchPaths: [] };
2329
2428
  const wildcardMatches = [...expanded.matchAll(/\*/g)];
2330
2429
  if (wildcardMatches.length === 0) {
2331
2430
  const dir = path.resolve(expanded);
2332
- return { dirs: fs.existsSync(dir) ? [dir] : [], watchPaths: [dir] };
2431
+ return { dirs: !isExcluded(dir) && fs.existsSync(dir) ? [dir] : [], watchPaths: [dir] };
2333
2432
  }
2334
2433
  const parts = expanded.split(path.sep);
2335
2434
  const wildcardIndex = parts.findIndex((part) => part.includes("*"));
2336
2435
  if (wildcardMatches.length !== 1 || wildcardIndex === -1 || parts[wildcardIndex] !== "*") return { dirs: [], watchPaths: [] };
2337
2436
  const base = path.resolve(parts.slice(0, wildcardIndex).join(path.sep) || path.sep);
2437
+ if (isExcluded(base)) return { dirs: [], watchPaths: [base] };
2338
2438
  const rest = parts.slice(wildcardIndex + 1);
2339
2439
  let entries: fs.Dirent[];
2340
2440
  try {
@@ -2344,16 +2444,16 @@ function expandAgentScanDirPattern(pattern: string): AgentScanDirs {
2344
2444
  }
2345
2445
  const candidateDirs = entries.filter((entry) => entry.isDirectory()).map((entry) => path.join(base, entry.name, ...rest));
2346
2446
  return {
2347
- dirs: candidateDirs.filter((dir) => fs.existsSync(dir)),
2447
+ dirs: candidateDirs.filter((dir) => !isExcluded(dir) && fs.existsSync(dir)),
2348
2448
  watchPaths: [base, ...candidateDirs],
2349
2449
  };
2350
2450
  }
2351
2451
 
2352
- function settingsAgentScanDirs(entries: string[]): AgentScanDirs {
2452
+ function settingsAgentScanDirs(entries: string[], isExcluded: (filePath: string) => boolean): AgentScanDirs {
2353
2453
  const dirs = new Set<string>();
2354
2454
  const watchPaths = new Set<string>();
2355
2455
  for (const entry of entries) {
2356
- const expanded = expandAgentScanDirPattern(entry);
2456
+ const expanded = expandAgentScanDirPattern(entry, isExcluded);
2357
2457
  for (const dir of expanded.dirs) dirs.add(dir);
2358
2458
  for (const watchPath of expanded.watchPaths) watchPaths.add(watchPath);
2359
2459
  }
@@ -2421,6 +2521,10 @@ interface AgentDiscoverySources {
2421
2521
  userChains?: ReturnType<typeof loadChainsFromDir>;
2422
2522
  projectChainLoaded?: Array<{ dir: string; loaded: ReturnType<typeof loadChainsFromDir> }>;
2423
2523
  packageChainLoaded?: Array<{ entry: PackageChainPath; loaded: ReturnType<typeof loadChainsFromDir> }>;
2524
+ isExcluded: (filePath: string) => boolean;
2525
+ exclusionRoots: Array<{ resolved: string; real: string }>;
2526
+ identityWatchPaths: string[];
2527
+ chainWatchPaths?: Set<string>;
2424
2528
  watchPaths: string[];
2425
2529
  }
2426
2530
 
@@ -2433,7 +2537,7 @@ const agentDiscoveryCache = new Map<string, AgentDiscoveryCacheEntry>();
2433
2537
 
2434
2538
  function isPathWithin(root: string, candidate: string): boolean {
2435
2539
  const relative = path.relative(path.resolve(root), path.resolve(candidate));
2436
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2540
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
2437
2541
  }
2438
2542
 
2439
2543
  function addDirectoryWatchPaths(paths: Set<string>, root: string, files: readonly string[], directories: readonly string[] = []): void {
@@ -2456,13 +2560,14 @@ function addDirectoryWatchPaths(paths: Set<string>, root: string, files: readonl
2456
2560
  }
2457
2561
  }
2458
2562
 
2459
- function watchPathSignature(filePath: string): string {
2563
+ function watchPathSignature(filePath: string, isExcluded?: (filePath: string) => boolean): string {
2460
2564
  try {
2461
2565
  const stat = fs.statSync(filePath);
2462
2566
  if (stat.isDirectory()) {
2463
2567
  const entries = fs.readdirSync(filePath, { withFileTypes: true })
2568
+ .filter((entry) => !isExcluded || !isExcluded(path.join(filePath, entry.name)))
2464
2569
  .sort((left, right) => left.name.localeCompare(right.name))
2465
- .map((entry) => `${entry.name}:${entry.isDirectory() ? "d" : entry.isSymbolicLink() ? "l" : "f"}`)
2570
+ .map((entry) => `${entry.name}:${entry.isDirectory() ? "d" : entry.isSymbolicLink() ? (isExcluded ? `l:${canonicalAgentPath(path.join(filePath, entry.name))}` : "l") : "f"}`)
2466
2571
  .join("|");
2467
2572
  return `directory:${entries}`;
2468
2573
  }
@@ -2472,10 +2577,17 @@ function watchPathSignature(filePath: string): string {
2472
2577
  }
2473
2578
  }
2474
2579
 
2475
- function discoveryFingerprint(paths: readonly string[]): string {
2476
- return [...new Set(paths)]
2580
+ function discoveryFingerprint(sources: AgentDiscoverySources): string {
2581
+ const exclusionIdentity = JSON.stringify(sources.exclusionRoots.map((root) => ({ resolved: root.resolved, real: canonicalAgentPath(root.resolved) })));
2582
+ // A retargeted exclusion needs a fresh scan before fingerprinting old roots.
2583
+ if (exclusionIdentity !== JSON.stringify(sources.exclusionRoots)) return exclusionIdentity;
2584
+ const rootIdentities = JSON.stringify(sources.identityWatchPaths.map((root) => [root, canonicalAgentPath(root)]));
2585
+ // Package metadata can redirect agents outside an excluded tree without chains.
2586
+ const unfilteredPaths = new Set([...sources.packageSubagentPaths.watchPaths, ...(sources.chainWatchPaths ?? [])]);
2587
+ return exclusionIdentity + "\n" + rootIdentities + "\n" + [...new Set([...sources.watchPaths, ...unfilteredPaths])]
2588
+ .filter((filePath) => unfilteredPaths.has(filePath) || filePath === sources.userSettingsPath || filePath === sources.projectSettingsPath || !sources.isExcluded(filePath))
2477
2589
  .sort((left, right) => left.localeCompare(right))
2478
- .map((filePath) => `${filePath}:${watchPathSignature(filePath)}`)
2590
+ .map((filePath) => `${filePath}:${watchPathSignature(filePath, sources.exclusionRoots.length && !unfilteredPaths.has(filePath) ? sources.isExcluded : undefined)}`)
2479
2591
  .join("\n");
2480
2592
  }
2481
2593
 
@@ -2521,21 +2633,23 @@ function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string
2521
2633
  const userSettingsPath = getUserAgentSettingsPath();
2522
2634
  const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
2523
2635
  const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd);
2524
- const userScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(userSettingsPath));
2525
- const projectScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(projectSettingsPath));
2636
+ const exclusionRoots = agentExclusionRoots(userSettingsPath, projectSettingsPath);
2637
+ const isExcluded = agentExclusions(exclusionRoots);
2638
+ const userScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(userSettingsPath), isExcluded);
2639
+ const projectScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(projectSettingsPath), isExcluded);
2526
2640
 
2527
2641
  const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
2528
- const userLoaded = [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].map((dir, discoveryPriority): LoadedAgentDirectory => {
2529
- const inspection = inspectAgentDefinitionDirectory(dir);
2642
+ const userLoaded = [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].filter((dir) => !isExcluded(dir)).map((dir, discoveryPriority): LoadedAgentDirectory => {
2643
+ const inspection = inspectAgentDefinitionDirectory(dir, undefined, isExcluded);
2530
2644
  return { dir, inspection, loaded: loadAgentsFromDir(dir, "user", discoveryPriority, undefined, inspection) };
2531
2645
  });
2532
- const projectInspections = new Map(projectCandidateDirs.map((dir) => [dir, inspectAgentDefinitionDirectory(dir)]));
2533
- const projectLoaded = [...projectScanDirs.dirs, ...projectAgentDirs].map((dir, discoveryPriority): LoadedAgentDirectory => {
2534
- const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir);
2646
+ const projectInspections = new Map(projectCandidateDirs.filter((dir) => !isExcluded(dir)).map((dir) => [dir, inspectAgentDefinitionDirectory(dir, undefined, isExcluded)]));
2647
+ const projectLoaded = [...projectScanDirs.dirs, ...projectAgentDirs].filter((dir) => !isExcluded(dir)).map((dir, discoveryPriority): LoadedAgentDirectory => {
2648
+ const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir, undefined, isExcluded);
2535
2649
  return { dir, inspection, loaded: loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : discoveryPriority, undefined, inspection) };
2536
2650
  });
2537
- const packageLoaded = packageSubagentPaths.agents.map((entry, index): LoadedAgentDirectory => {
2538
- const inspection = inspectAgentDefinitionDirectory(entry.dir);
2651
+ const packageLoaded = packageSubagentPaths.agents.filter((entry) => !isExcluded(entry.dir)).map((entry, index): LoadedAgentDirectory => {
2652
+ const inspection = inspectAgentDefinitionDirectory(entry.dir, undefined, isExcluded);
2539
2653
  return { dir: entry.dir, inspection, packageEntry: entry, loaded: loadAgentsFromDir(entry.dir, "package", packageSubagentPaths.agents.length - index, entry, inspection) };
2540
2654
  });
2541
2655
 
@@ -2565,7 +2679,7 @@ function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string
2565
2679
  userDirNew,
2566
2680
  userChainDir,
2567
2681
  projectAgentDirs,
2568
- projectCandidateDirs,
2682
+ projectCandidateDirs: projectCandidateDirs.filter((dir) => !isExcluded(dir)),
2569
2683
  projectAgentsDir,
2570
2684
  projectChainDirs,
2571
2685
  projectChainDir,
@@ -2577,7 +2691,17 @@ function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string
2577
2691
  projectLoaded,
2578
2692
  projectInspections,
2579
2693
  packageLoaded,
2580
- watchPaths: [...watchPaths],
2694
+ isExcluded,
2695
+ exclusionRoots,
2696
+ // Aliases outside excluded lexical subtrees can be retargeted into allowed
2697
+ // storage. Watch only their identity, never the excluded target's contents.
2698
+ identityWatchPaths: [...new Set([
2699
+ ...userScanDirs.watchPaths, ...projectScanDirs.watchPaths,
2700
+ ...extraUserAgentDirs(), userDirOld, userDirNew, ...projectCandidateDirs,
2701
+ ...packageSubagentPaths.agents.map((entry) => entry.dir),
2702
+ ])]
2703
+ .filter((dir) => !exclusionRoots.some((root) => isPathWithin(root.resolved, dir)) && isExcluded(dir)),
2704
+ watchPaths: [...watchPaths].filter((filePath) => !isExcluded(filePath) || filePath === userSettingsPath || filePath === projectSettingsPath),
2581
2705
  };
2582
2706
  }
2583
2707
 
@@ -2586,29 +2710,30 @@ function ensureDiscoveryChains(sources: AgentDiscoverySources): void {
2586
2710
  sources.packageChainLoaded = sources.packageSubagentPaths.chains.map((entry) => ({ entry, loaded: loadChainsFromDir(entry.dir, "package") }));
2587
2711
  sources.userChains = loadChainsFromDir(sources.userChainDir, "user");
2588
2712
  sources.projectChainLoaded = sources.projectChainDirs.map((dir) => ({ dir, loaded: loadChainsFromDir(dir, "project") }));
2589
- const watchPaths = new Set(sources.watchPaths);
2713
+ const watchPaths = new Set(sources.packageSubagentPaths.watchPaths);
2590
2714
  addDirectoryWatchPaths(watchPaths, sources.userChainDir, sources.userChains.files, sources.userChains.directories);
2591
2715
  for (const chain of sources.projectChainLoaded) addDirectoryWatchPaths(watchPaths, chain.dir, chain.loaded.files, chain.loaded.directories);
2592
2716
  for (const chain of sources.packageChainLoaded) addDirectoryWatchPaths(watchPaths, chain.entry.dir, chain.loaded.files, chain.loaded.directories);
2593
- sources.watchPaths = [...watchPaths];
2717
+ sources.chainWatchPaths = watchPaths;
2718
+ sources.watchPaths = [...new Set([...sources.watchPaths, ...watchPaths])];
2594
2719
  }
2595
2720
 
2596
2721
  function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false): AgentDiscoverySources {
2597
2722
  const key = discoveryCacheKey(cwd, preferredModelProvider);
2598
2723
  const cached = agentDiscoveryCache.get(key);
2599
- if (cached && cached.fingerprint === discoveryFingerprint(cached.sources.watchPaths)) {
2724
+ if (cached && cached.fingerprint === discoveryFingerprint(cached.sources)) {
2600
2725
  if (includeChains) {
2601
2726
  ensureDiscoveryChains(cached.sources);
2602
- cached.fingerprint = discoveryFingerprint(cached.sources.watchPaths);
2727
+ cached.fingerprint = discoveryFingerprint(cached.sources);
2603
2728
  }
2604
2729
  return cached.sources;
2605
2730
  }
2606
2731
  const sources = buildAgentDiscoverySources(cwd, preferredModelProvider);
2607
- const entry = { sources, fingerprint: discoveryFingerprint(sources.watchPaths) };
2732
+ const entry = { sources, fingerprint: discoveryFingerprint(sources) };
2608
2733
  agentDiscoveryCache.set(key, entry);
2609
2734
  if (includeChains) {
2610
2735
  ensureDiscoveryChains(sources);
2611
- entry.fingerprint = discoveryFingerprint(sources.watchPaths);
2736
+ entry.fingerprint = discoveryFingerprint(sources);
2612
2737
  }
2613
2738
  return sources;
2614
2739
  }
@@ -2817,27 +2942,28 @@ function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelPr
2817
2942
  ? projectSettings.injectAgents
2818
2943
  : userSettings.injectAgents;
2819
2944
  const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: scope !== "project", includeProject: scope !== "user" });
2945
+ const isExcluded = agentExclusions(agentExclusionRoots(userSettingsPath, projectSettingsPath));
2820
2946
  const directories: AgentDefinitionDirectoryReport[] = [reportAgentDefinitionDirectory("builtin", BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION)];
2821
2947
  const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
2822
2948
  const builtinAgents = applyBuiltinOverrides(applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2823
- const userScanDirs = settingsAgentScanDirs(userSettings.agentScanDirs ?? []);
2824
- const projectScanDirs = settingsAgentScanDirs(projectSettings.agentScanDirs ?? []);
2825
- const userLoaded = scope === "project" ? [] : [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].map((dir, discoveryPriority) => {
2826
- const inspection = inspectAgentDefinitionDirectory(dir);
2949
+ const userScanDirs = settingsAgentScanDirs(userSettings.agentScanDirs ?? [], isExcluded);
2950
+ const projectScanDirs = settingsAgentScanDirs(projectSettings.agentScanDirs ?? [], isExcluded);
2951
+ const userLoaded = scope === "project" ? [] : [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].filter((dir) => !isExcluded(dir)).map((dir, discoveryPriority) => {
2952
+ const inspection = inspectAgentDefinitionDirectory(dir, undefined, isExcluded);
2827
2953
  directories.push(reportAgentDefinitionDirectory("user", dir, inspection));
2828
2954
  return loadAgentsFromDir(dir, "user", discoveryPriority, undefined, inspection);
2829
2955
  });
2830
2956
  const userAgents = applyCustomAgentOverrides(applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2831
- const projectInspections = scope === "user" ? new Map<string, AgentDefinitionInspection>() : new Map(projectCandidateDirs.map((dir) => [dir, inspectAgentDefinitionDirectory(dir)]));
2832
- if (scope !== "user") for (const dir of projectCandidateDirs) directories.push(reportAgentDefinitionDirectory("project", dir, projectInspections.get(dir)!));
2833
- const projectLoaded = scope === "user" ? [] : [...projectScanDirs.dirs, ...projectAgentDirs].map((dir, discoveryPriority) => {
2834
- const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir);
2957
+ const projectInspections = scope === "user" ? new Map<string, AgentDefinitionInspection>() : new Map(projectCandidateDirs.filter((dir) => !isExcluded(dir)).map((dir) => [dir, inspectAgentDefinitionDirectory(dir, undefined, isExcluded)]));
2958
+ if (scope !== "user") for (const [dir, inspection] of projectInspections) directories.push(reportAgentDefinitionDirectory("project", dir, inspection));
2959
+ const projectLoaded = scope === "user" ? [] : [...projectScanDirs.dirs, ...projectAgentDirs].filter((dir) => !isExcluded(dir)).map((dir, discoveryPriority) => {
2960
+ const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir, undefined, isExcluded);
2835
2961
  if (!projectInspections.has(dir)) directories.push(reportAgentDefinitionDirectory("project", dir, inspection));
2836
2962
  return loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : discoveryPriority, undefined, inspection);
2837
2963
  });
2838
2964
  const projectAgents = applyCustomAgentOverrides(applySubagentDefaults(projectLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2839
- const packageLoaded = packageSubagentPaths.agents.map((entry, index) => {
2840
- const inspection = inspectAgentDefinitionDirectory(entry.dir);
2965
+ const packageLoaded = packageSubagentPaths.agents.filter((entry) => !isExcluded(entry.dir)).map((entry, index) => {
2966
+ const inspection = inspectAgentDefinitionDirectory(entry.dir, undefined, isExcluded);
2841
2967
  directories.push(reportAgentDefinitionDirectory("package", entry.dir, inspection));
2842
2968
  return loadAgentsFromDir(entry.dir, "package", packageSubagentPaths.agents.length - index, entry, inspection);
2843
2969
  });