@xzzpig/pi-subagents 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  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 +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  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 +38 -35
  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 +770 -444
  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 +915 -411
  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 +49 -85
  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 +149 -112
  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 +27 -34
  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/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -10,7 +10,6 @@ import {
10
10
  defaultInheritProjectContext,
11
11
  defaultInheritSkills,
12
12
  defaultSystemPromptMode,
13
- discoverAgents,
14
13
  discoverAgentsAll,
15
14
  buildRuntimeName,
16
15
  findBlockingAgentDiagnostic,
@@ -23,16 +22,15 @@ import {
23
22
  } from "./agents.ts";
24
23
  import { serializeAgent } from "./agent-serializer.ts";
25
24
  import { mergeAgentsForScope } from "./agent-selection.ts";
26
- import { discoverAvailableSkills, resolveSkills, resolveSkillsWithFallback } from "./skills.ts";
25
+ import { discoverAvailableSkills, resolveSkills } from "./skills.ts";
27
26
  import {
28
27
  buildProactiveSkillSubagentRecommendationLines,
29
28
  } from "./proactive-skills.ts";
30
29
  import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.ts";
31
- import { resolvePiLaunchToolPlan } from "../runs/shared/child-tool-plan.ts";
32
30
  import { resolveEffectiveThinking, toModelInfo } from "../shared/model-info.ts";
33
- import { resolveSubagentModelOverride, type ParentModel } from "../runs/shared/model-fallback.ts";
31
+ import { resolveSubagentModelOverride, type ParentModel } from "../runs/shared/model-resolution.ts";
34
32
  import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
35
- import { validateAcceptanceInput } from "../runs/shared/acceptance.ts";
33
+ import { formatReviewGateLabel, validateAcceptanceInput } from "../runs/shared/acceptance.ts";
36
34
  import { CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL, isCodeOwnedExternalCliAdapterId, resolveExternalCliRunnerStatus, validateCodeOwnedProfileRunner } from "../runs/shared/external-cli-contract.ts";
37
35
  import { resolveExternalCliBinaryAvailability, type ExternalCliBinaryAvailability } from "../runs/shared/external-cli-preflight.ts";
38
36
  import type { AcceptanceInput, AgentCapabilitiesSnapshot, AgentCapabilityRow, Details, ExtensionConfig, ToolBudgetConfig } from "../shared/types.ts";
@@ -43,64 +41,13 @@ import { mergeRuntimeAgents, type RuntimeAgentOwner } from "./runtime-agent-regi
43
41
  import { listExternalJobProviders } from "../api/external-job-provider.ts";
44
42
  import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
45
43
  import { validatePermissionProfileName } from "../shared/permission-profile.ts";
44
+ import { ejectAgentDefinition } from "./agent-eject.ts";
46
45
 
47
46
  export const AGENT_MANAGEMENT_API_VERSION = 1 as const;
48
47
 
49
- export type AgentEjectionScope = "user" | "project";
50
-
51
- export type AgentEjectionErrorCode =
52
- | "invalid_agent"
53
- | "untrusted_project"
54
- | "missing_project_root"
55
- | "missing_source"
56
- | "existing_custom"
57
- | "name_conflict"
58
- | "existing_file"
59
- | "source_read_failed"
60
- | "resource_missing"
61
- | "write_failed"
62
- | "rediscovery_failed"
63
- | "preflight_failed";
64
-
65
- export interface EjectAgentDefinitionInput {
66
- cwd: string;
67
- agent: string;
68
- scope: AgentEjectionScope;
69
- /** Direct project-scope API callers must affirm host project trust. */
70
- projectTrusted?: boolean;
71
- }
72
-
73
- export interface EjectAgentDefinitionVerification {
74
- agent: string;
75
- scope: AgentEjectionScope;
76
- targetPath: string;
77
- source: "builtin" | "package";
78
- resourcePaths: string[];
79
- launchPreflighted: true;
80
- }
81
-
82
- export type EjectAgentDefinitionResult =
83
- | {
84
- ok: true;
85
- code: "ejected";
86
- message: string;
87
- agent: string;
88
- source: "builtin" | "package";
89
- scope: AgentEjectionScope;
90
- targetPath: string;
91
- verification: EjectAgentDefinitionVerification;
92
- }
93
- | {
94
- ok: false;
95
- code: AgentEjectionErrorCode;
96
- message: string;
97
- scope?: AgentEjectionScope;
98
- targetPath?: string;
99
- };
100
-
101
48
  type ManagementAction = "list" | "get" | "models" | "create" | "update" | "delete" | "eject" | "disable" | "enable" | "reset";
102
49
  type ManagementScope = "user" | "project";
103
- type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { isProjectTrusted?: ExtensionContext["isProjectTrusted"]; model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string; runtimeAgentOwner?: RuntimeAgentOwner };
50
+ type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { isProjectTrusted?: ExtensionContext["isProjectTrusted"]; model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string; runtimeAgentOwner?: RuntimeAgentOwner; onAgentsChanged?: () => void };
104
51
 
105
52
  interface ManagementParams {
106
53
  action?: string;
@@ -179,7 +126,8 @@ function normalizeListScope(scope: unknown): AgentScope | undefined {
179
126
  return undefined;
180
127
  }
181
128
 
182
- function sanitizeName(name: string): string {
129
+ // [fork] Exported for agents/agent-eject.ts.
130
+ export function sanitizeName(name: string): string {
183
131
  return name.toLowerCase().trim().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
184
132
  }
185
133
 
@@ -211,7 +159,8 @@ function availableAgentNamesFromDiscovery(
211
159
  return [...new Set(agents.map((agent) => agent.name))].sort((a, b) => a.localeCompare(b));
212
160
  }
213
161
 
214
- function availableAgentNames(cwd: string): string[] {
162
+ // [fork] Exported for agents/agent-eject.ts.
163
+ export function availableAgentNames(cwd: string): string[] {
215
164
  return availableAgentNamesFromDiscovery(discoverAgentsAll(cwd));
216
165
  }
217
166
 
@@ -261,7 +210,8 @@ function resolveEffectiveAgent(d: ReturnType<typeof discoverAgentsAll>, name: st
261
210
  return { agent: matches.reduce((best, agent) => (AGENT_SOURCE_PRECEDENCE[agent.source] > AGENT_SOURCE_PRECEDENCE[best.source] ? agent : best)) };
262
211
  }
263
212
 
264
- function nameExistsInScope(cwd: string, scope: ManagementScope, name: string, excludePath?: string): boolean {
213
+ // [fork] Exported for agents/agent-eject.ts.
214
+ export function nameExistsInScope(cwd: string, scope: ManagementScope, name: string, excludePath?: string): boolean {
265
215
  const d = discoverAgentsAll(cwd);
266
216
  for (const a of scope === "user" ? d.user : d.project) {
267
217
  if (a.name === name && a.filePath !== excludePath) return true;
@@ -280,13 +230,6 @@ function modelWarning(ctx: ManagementContext, model: string | undefined): string
280
230
  return `Warning: model '${model}' is not in the current model registry. Run subagent({ action: "models" }) to list valid provider/id selectors, then use the exact provider/id form (bare ids resolve only when unique).`;
281
231
  }
282
232
 
283
- function fallbackModelsWarning(ctx: ManagementContext, fallbackModels: string[] | undefined): string | undefined {
284
- if (!fallbackModels || fallbackModels.length === 0) return undefined;
285
- const available = new Set(ctx.modelRegistry.getAvailable().flatMap((m) => [`${m.provider}/${m.id}`, m.id]));
286
- const missing = fallbackModels.filter((model) => !available.has(model));
287
- return missing.length ? `Warning: fallback models not in the current model registry: ${missing.join(", ")}.` : undefined;
288
- }
289
-
290
233
  function skillsWarning(cwd: string, agent: Pick<AgentConfig, "skills" | "skillPath" | "filePath">): string | undefined {
291
234
  if (!agent.skills?.length) return undefined;
292
235
  const { missing } = resolveSkills(
@@ -330,7 +273,6 @@ export function editableAgentConfig(agent: AgentConfig): AgentConfig {
330
273
  outputMode: _outputMode,
331
274
  defaultReads: _defaultReads,
332
275
  model: _model,
333
- fallbackModels: _fallbackModels,
334
276
  fast: _fast,
335
277
  thinking: _thinking,
336
278
  systemPromptMode: _systemPromptMode,
@@ -367,7 +309,6 @@ export function editableAgentConfig(agent: AgentConfig): AgentConfig {
367
309
  ...(base.outputMode !== undefined ? { outputMode: base.outputMode } : {}),
368
310
  ...(base.defaultReads !== undefined ? { defaultReads: [...base.defaultReads] } : {}),
369
311
  ...(base.model !== undefined && hasDeclaredField("model") ? { model: base.model } : {}),
370
- ...(base.fallbackModels !== undefined ? { fallbackModels: [...base.fallbackModels] } : {}),
371
312
  ...(base.fast !== undefined ? { fast: base.fast } : {}),
372
313
  ...(base.thinking !== undefined && hasDeclaredField("thinking") ? { thinking: base.thinking } : {}),
373
314
  systemPromptMode: base.systemPromptMode,
@@ -410,11 +351,11 @@ export function preservedAgentFrontmatterFields(agent: AgentConfig, cfg: Record<
410
351
  if (hasKey(cfg, "name")) changed("name");
411
352
  if (hasKey(cfg, "package")) changed("package");
412
353
  if (hasKey(cfg, "description")) changed("description");
354
+ if (hasKey(cfg, "advertise")) changed("advertise");
413
355
  if (hasKey(cfg, "aliases")) changed("alias", "aliases");
414
356
  if (hasKey(cfg, "systemPrompt")) changed("systemPrompt");
415
357
  if (hasKey(cfg, "runner")) changed("runner");
416
358
  if (hasKey(cfg, "model")) changed("model");
417
- if (hasKey(cfg, "fallbackModels")) changed("fallbackModels");
418
359
  if (hasKey(cfg, "tools")) changed("tools");
419
360
  if (hasKey(cfg, "excludeTools")) changed("excludeTools");
420
361
  if (hasKey(cfg, "skills")) changed("skill", "skills");
@@ -479,6 +420,11 @@ function parseTools(raw: string): { tools?: string[]; mcpDirectTools?: string[]
479
420
  }
480
421
 
481
422
  function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): string | undefined {
423
+ if (hasKey(cfg, "advertise")) {
424
+ if (cfg.advertise === "") delete target.advertise;
425
+ else if (typeof cfg.advertise === "boolean") target.advertise = cfg.advertise;
426
+ else return "config.advertise must be a boolean or empty string when provided.";
427
+ }
482
428
  if (hasKey(cfg, "aliases")) {
483
429
  if (cfg.aliases === false || cfg.aliases === "") delete target.aliases;
484
430
  else if (typeof cfg.aliases === "string") {
@@ -524,21 +470,7 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
524
470
  else delete target.model;
525
471
  } else return "config.model must be a string or false when provided.";
526
472
  }
527
- if (hasKey(cfg, "fallbackModels")) {
528
- if (cfg.fallbackModels === false || cfg.fallbackModels === "") delete target.fallbackModels;
529
- else if (typeof cfg.fallbackModels === "string") {
530
- const models = parseCsv(cfg.fallbackModels);
531
- if (models.length) target.fallbackModels = models;
532
- else delete target.fallbackModels;
533
- } else if (Array.isArray(cfg.fallbackModels)) {
534
- const models = cfg.fallbackModels
535
- .filter((value): value is string => typeof value === "string")
536
- .map((value) => value.trim())
537
- .filter(Boolean);
538
- if (models.length) target.fallbackModels = [...new Set(models)];
539
- else delete target.fallbackModels;
540
- } else return "config.fallbackModels must be a comma-separated string, string array, or false when provided.";
541
- }
473
+ if (hasKey(cfg, "fallbackModels")) return "config.fallbackModels was removed; configure one model instead.";
542
474
  if (hasKey(cfg, "tools")) {
543
475
  if (cfg.tools === false || cfg.tools === "") { delete target.tools; delete target.mcpDirectTools; }
544
476
  else if (typeof cfg.tools === "string") {
@@ -711,7 +643,6 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
711
643
  target.tools?.length || target.mcpDirectTools?.length ? "tools" : undefined,
712
644
  target.excludeTools?.length ? "excludeTools" : undefined,
713
645
  target.model ? "model" : undefined,
714
- target.fallbackModels?.length ? "fallbackModels" : undefined,
715
646
  target.thinking ? "thinking" : undefined,
716
647
  target.extensions?.length ? "extensions" : undefined,
717
648
  target.subagentOnlyExtensions?.length ? "subagentOnlyExtensions" : undefined,
@@ -789,13 +720,19 @@ function externalJobProviderSuffix(provider: string, names: Set<string> | undefi
789
720
 
790
721
  type ExternalCliAvailabilityByCommand = ReadonlyMap<string, ExternalCliBinaryAvailability>;
791
722
 
723
+ /** A placed agent checks only local ssh; machine catalog and remote CLI validation happen at launch. */
724
+ function externalCliAvailabilityKey(command: string, machine: string | undefined): string {
725
+ return machine ? `ssh@${machine}` : command;
726
+ }
727
+
792
728
  function externalCliAvailabilityForAgents(agents: readonly AgentConfig[]): ExternalCliAvailabilityByCommand {
793
729
  const availability = new Map<string, ExternalCliBinaryAvailability>();
794
730
  for (const agent of agents) {
795
731
  const runner = agent.runner;
796
- if (runner?.type === "external-cli" && !availability.has(runner.command)) {
797
- availability.set(runner.command, resolveExternalCliBinaryAvailability(runner.command, process.env));
798
- }
732
+ if (runner?.type !== "external-cli") continue;
733
+ const key = externalCliAvailabilityKey(runner.command, agent.machine);
734
+ if (availability.has(key)) continue;
735
+ availability.set(key, resolveExternalCliBinaryAvailability(agent.machine ? "ssh" : runner.command, process.env));
799
736
  }
800
737
  return availability;
801
738
  }
@@ -803,10 +740,13 @@ function externalCliAvailabilityForAgents(agents: readonly AgentConfig[]): Exter
803
740
  function runnerListBadge(agent: AgentConfig, providerNames: Set<string> | undefined, externalCliAvailability?: ExternalCliAvailabilityByCommand): string | undefined {
804
741
  if (agent.runner?.type === "external-job") return `external-job:${agent.runner.provider} ${externalJobProviderSuffix(agent.runner.provider, providerNames)}`;
805
742
  if (agent.runner?.type === "external-cli") {
806
- const availability = externalCliAvailability?.get(agent.runner.command);
807
- if (!availability) return "external-cli";
808
- return `external-cli:${agent.runner.command} ${availability.available ? "✓" : "missing"}`;
743
+ const placed = agent.machine ? `${agent.runner.command} @ ${agent.machine}` : agent.runner.command;
744
+ const availability = externalCliAvailability?.get(externalCliAvailabilityKey(agent.runner.command, agent.machine));
745
+ if (!availability) return `external-cli:${placed}`;
746
+ if (agent.machine) return `external-cli:${placed} saved Herdr placement; transport ${availability.available ? "✓" : "missing"}; machine not preflighted`;
747
+ return `external-cli:${placed} ${availability.available ? "✓" : "missing"}`;
809
748
  }
749
+ if (agent.machine) return `machine: ${agent.machine} (saved Herdr placement)`;
810
750
  return undefined;
811
751
  }
812
752
 
@@ -842,7 +782,39 @@ function formatAgentCapabilitiesLine(agent: AgentConfig, providerNames: Set<stri
842
782
  if (agent.modelProvider && !agent.model.includes("/")) model = `${agent.modelProvider}/${agent.model}`;
843
783
  }
844
784
  const thinking = agent.thinking === false ? "off" : agent.thinking ?? "default";
845
- return `- ${agent.name} (${agentListMetadata(agent, providerNames, externalCliAvailability)}): Description: ${previewDisplayText(agent.description, 240)}; Tools: ${tools}; Model: ${model}; Thinking: ${thinking}`;
785
+ const machine = agent.machine ? `; Machine: ${agent.machine} (saved Herdr placement)` : "";
786
+ const acceptance = formatAcceptanceSummary(agent);
787
+ return `- ${agent.name} (${agentListMetadata(agent, providerNames, externalCliAvailability)}): Description: ${previewDisplayText(agent.description, 240)}; Tools: ${tools}; Model: ${model}; Thinking: ${thinking}${machine}${acceptance ? `; ${acceptance}` : ""}`;
788
+ }
789
+
790
+ function formatAcceptanceSummary(agent: AgentConfig): string | undefined {
791
+ const policy = agent.defaultAcceptance;
792
+ const summary: string[] = [];
793
+ if (policy === false) summary.push("Acceptance: disabled");
794
+ else if (typeof policy === "string") summary.push(`Acceptance: ${policy}`);
795
+ else if (policy) {
796
+ const modifiers = [
797
+ ...(policy.evidence ?? []),
798
+ ...(policy.verify ?? []).map((command) => `verify: ${formatAcceptanceDisplayLabel(command.id)}`),
799
+ ...(policy.criteria?.length ? [`criteria: ${policy.criteria.length}`] : []),
800
+ ...(policy.stopRules?.length ? [`stopRules: ${policy.stopRules.length}`] : []),
801
+ ];
802
+ if (policy.review === false) modifiers.push("review: off");
803
+ else if (policy.review) {
804
+ const displayReview = policy.review.agent
805
+ ? { ...policy.review, agent: formatAcceptanceDisplayLabel(policy.review.agent) }
806
+ : policy.review;
807
+ modifiers.push(`review: ${formatReviewGateLabel(displayReview)}`);
808
+ }
809
+ if (policy.report) modifiers.push(`report: ${policy.report}`);
810
+ summary.push(`Acceptance: ${policy.level ?? "auto"}${modifiers.length > 0 ? ` (${modifiers.join(", ")})` : ""}`);
811
+ }
812
+ if (agent.acceptanceRole) summary.push(`Acceptance role: ${agent.acceptanceRole}`);
813
+ return summary.length > 0 ? summary.join("; ") : undefined;
814
+ }
815
+
816
+ function formatAcceptanceDisplayLabel(value: string): string {
817
+ return JSON.stringify(previewDisplayText(value, 80));
846
818
  }
847
819
 
848
820
  const EXTERNAL_JOB_CAPABILITIES = { stop: false, steer: false, resume: false, structuredOutput: false, toolEvents: false } as const;
@@ -856,11 +828,12 @@ function agentCapabilityRunner(agent: AgentConfig, providerNames: Set<string> |
856
828
  const runner = agent.runner;
857
829
  if (!runner || runner.type === "pi") return PI_AGENT_RUNNER;
858
830
  if (runner.type === "external-cli") {
859
- const availability = externalCliAvailability.get(runner.command)!;
831
+ const availability = externalCliAvailability.get(externalCliAvailabilityKey(runner.command, agent.machine))!;
860
832
  return {
861
833
  type: "external-cli",
862
834
  adapter: runner.adapter,
863
835
  command: runner.command,
836
+ ...(agent.machine ? { machine: agent.machine } : {}),
864
837
  ...availability,
865
838
  capabilities: resolveExternalCliRunnerStatus(runner).capabilities,
866
839
  };
@@ -888,8 +861,9 @@ function agentCapabilityRow(agent: AgentConfig, options: { executable: boolean;
888
861
  aliases: agent.aliases ? [...agent.aliases] : undefined,
889
862
  runner: agentCapabilityRunner(agent, options.providerNames, options.externalCliAvailability),
890
863
  tools: agentCapabilityTools(agent),
891
- model: presentDetails({ value: agent.model, fallbackModels: agent.fallbackModels, thinking: agent.thinking }),
864
+ model: presentDetails({ value: agent.model, thinking: agent.thinking }),
892
865
  execution: presentDetails({ defaultAsync: agent.defaultAsync, timeoutMs: agent.defaultTimeoutMs }),
866
+ acceptance: presentDetails({ policy: agent.defaultAcceptance, role: agent.acceptanceRole }),
893
867
  output: presentDetails({ path: agent.output, mode: agent.outputMode }),
894
868
  extensions: presentDetails({ names: agent.extensions, subagentOnly: agent.subagentOnlyExtensions, skills: agent.skills }),
895
869
  };
@@ -990,7 +964,6 @@ function formatAgentDetail(agent: AgentConfig): string {
990
964
  }
991
965
  if (agent.aliases?.length) lines.push(`Aliases: ${agent.aliases.join(", ")}`);
992
966
  if (agent.model) lines.push(`Model: ${agent.model}`);
993
- if (agent.fallbackModels?.length) lines.push(`Fallback models: ${agent.fallbackModels.join(", ")}`);
994
967
  if (tools.length) lines.push(`Tools: ${tools.join(", ")}`);
995
968
  if (agent.excludeTools?.length) lines.push(`Excluded tools: ${agent.excludeTools.join(", ")}`);
996
969
  if (agent.skills?.length) lines.push(`Skills: ${agent.skills.join(", ")}`);
@@ -1135,12 +1108,6 @@ function handleModels(params: ManagementParams, ctx: ManagementContext): AgentTo
1135
1108
  lines.push(` ${resolvedModel ?? "(unresolved)"}`);
1136
1109
  lines.push(`Source: ${source}`);
1137
1110
  lines.push(`Thinking: ${effectiveThinking ?? "default"}`);
1138
- if (agent.fallbackModels?.length) {
1139
- lines.push("Fallback models:");
1140
- for (const fallback of agent.fallbackModels) {
1141
- lines.push(` ${resolveSubagentModelOverride(fallback, currentModel, availableModels, agent.modelProvider ?? preferredProvider) ?? fallback}`);
1142
- }
1143
- }
1144
1111
  if (agent.override) {
1145
1112
  lines.push("Override file:");
1146
1113
  lines.push(` ${agent.override.path}`);
@@ -1160,12 +1127,6 @@ function handleModels(params: ManagementParams, ctx: ManagementContext): AgentTo
1160
1127
  lines.push(` ${resolvedModel ?? "(unresolved)"}`);
1161
1128
  lines.push(` source: ${source}`);
1162
1129
  lines.push(` thinking: ${effectiveThinking ?? "default"}`);
1163
- if (agent.fallbackModels?.length) {
1164
- lines.push(" fallback models:");
1165
- for (const fallback of agent.fallbackModels) {
1166
- lines.push(` ${resolveSubagentModelOverride(fallback, currentModel, availableModels, agent.modelProvider ?? preferredProvider) ?? fallback}`);
1167
- }
1168
- }
1169
1130
  if (agent.override) {
1170
1131
  lines.push(" override file:");
1171
1132
  lines.push(` ${agent.override.path}`);
@@ -1255,11 +1216,10 @@ export function handleCreate(params: ManagementParams, ctx: ManagementContext):
1255
1216
  if (profileError) return result(profileError, true);
1256
1217
  const mw = modelWarning(ctx, agent.model);
1257
1218
  if (mw) warnings.push(mw);
1258
- const fmw = fallbackModelsWarning(ctx, agent.fallbackModels);
1259
- if (fmw) warnings.push(fmw);
1260
1219
  const sw = skillsWarning(ctx.cwd, agent);
1261
1220
  if (sw) warnings.push(sw);
1262
1221
  fs.writeFileSync(targetPath, serializeAgent(agent), "utf-8");
1222
+ ctx.onAgentsChanged?.();
1263
1223
  return result([`Created agent '${runtimeName}' at ${targetPath}.`, ...warnings].join("\n"));
1264
1224
  }
1265
1225
 
@@ -1311,10 +1271,6 @@ export function handleUpdate(params: ManagementParams, ctx: ManagementContext):
1311
1271
  const mw = modelWarning(ctx, updated.model);
1312
1272
  if (mw) warnings.push(mw);
1313
1273
  }
1314
- if (hasKey(cfg, "fallbackModels")) {
1315
- const fmw = fallbackModelsWarning(ctx, updated.fallbackModels);
1316
- if (fmw) warnings.push(fmw);
1317
- }
1318
1274
  if (hasKey(cfg, "skills") || hasKey(cfg, "skillPath")) {
1319
1275
  const sw = skillsWarning(ctx.cwd, updated);
1320
1276
  if (sw) warnings.push(sw);
@@ -1325,6 +1281,7 @@ export function handleUpdate(params: ManagementParams, ctx: ManagementContext):
1325
1281
  updated.filePath = renamed.filePath!;
1326
1282
  }
1327
1283
  fs.writeFileSync(updated.filePath, serializeAgent(updated, { preserveFrontmatterFields }), "utf-8");
1284
+ ctx.onAgentsChanged?.();
1328
1285
  const headline = updated.name === oldName
1329
1286
  ? `Updated agent '${updated.name}' at ${updated.filePath}.`
1330
1287
  : `Updated agent '${oldName}' to '${updated.name}' at ${updated.filePath}.`;
@@ -1338,279 +1295,10 @@ function handleDelete(params: ManagementParams, ctx: ManagementContext): AgentTo
1338
1295
  if ("content" in targetOrError) return targetOrError;
1339
1296
  const target = targetOrError;
1340
1297
  fs.unlinkSync(target.filePath);
1298
+ ctx.onAgentsChanged?.();
1341
1299
  return result(`Deleted agent '${target.name}' at ${target.filePath}.`);
1342
1300
  }
1343
1301
 
1344
- function isRelativeAgentResourcePath(value: string): boolean {
1345
- return value === "." || value === ".." || value.startsWith("./") || value.startsWith("../");
1346
- }
1347
-
1348
- /**
1349
- * Upstream v0.53.0 resolves agent-frontmatter extension paths to absolute
1350
- * paths at discovery time, so a portable resource is any entry that is a
1351
- * path (relative or absolute) rather than a bare tool name.
1352
- */
1353
- function isAgentResourcePath(value: string): boolean {
1354
- return isRelativeAgentResourcePath(value) || path.isAbsolute(value);
1355
- }
1356
-
1357
- function resolvePortableAgentResources(
1358
- entries: string[] | undefined,
1359
- sourceFilePath: string,
1360
- ): { entries: string[] | undefined; resourcePaths: string[] } {
1361
- const baseDir = path.dirname(sourceFilePath);
1362
- const resourcePaths = (entries ?? []).flatMap((entry) =>
1363
- isAgentResourcePath(entry) ? [path.resolve(baseDir, entry)] : [],
1364
- );
1365
- return {
1366
- entries: entries?.map((entry) => isAgentResourcePath(entry) ? path.resolve(baseDir, entry) : entry),
1367
- resourcePaths,
1368
- };
1369
- }
1370
-
1371
- function portableEjectedAgentContent(source: AgentConfig): {
1372
- content?: string;
1373
- resourcePaths?: string[];
1374
- error?: EjectAgentDefinitionResult;
1375
- } {
1376
- let sourceContent: string;
1377
- try {
1378
- sourceContent = fs.readFileSync(source.filePath, "utf-8");
1379
- } catch (error) {
1380
- const message = error instanceof Error ? error.message : String(error);
1381
- return {
1382
- error: {
1383
- ok: false,
1384
- code: "source_read_failed",
1385
- message: `Failed to read source agent at ${source.filePath}: ${message}`,
1386
- },
1387
- };
1388
- }
1389
-
1390
- const extensions = resolvePortableAgentResources(source.extensions, source.filePath);
1391
- const subagentOnlyExtensions = resolvePortableAgentResources(source.subagentOnlyExtensions, source.filePath);
1392
- const skillPath = resolvePortableAgentResources(source.skillPath, source.filePath);
1393
- const tools = resolvePortableAgentResources(source.tools, source.filePath);
1394
- const resourcePaths = [...new Set([
1395
- ...extensions.resourcePaths,
1396
- ...subagentOnlyExtensions.resourcePaths,
1397
- ...skillPath.resourcePaths,
1398
- ...tools.resourcePaths,
1399
- ])].sort((a, b) => a.localeCompare(b));
1400
- const missingResources = resourcePaths.filter((resourcePath) => !fs.existsSync(resourcePath));
1401
- if (missingResources.length > 0) {
1402
- return {
1403
- error: {
1404
- ok: false,
1405
- code: "resource_missing",
1406
- message: `Agent '${source.name}' cannot be ejected because its relative resource path(s) do not exist: ${missingResources.join(", ")}.`,
1407
- },
1408
- };
1409
- }
1410
- if (resourcePaths.length === 0) return { content: sourceContent, resourcePaths };
1411
-
1412
- const { frontmatter } = parseFrontmatter(sourceContent);
1413
- const portableAgent: AgentConfig = {
1414
- ...source,
1415
- ...(source.extensions !== undefined ? { extensions: extensions.entries! } : {}),
1416
- ...(source.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: subagentOnlyExtensions.entries! } : {}),
1417
- ...(source.skillPath !== undefined ? { skillPath: skillPath.entries! } : {}),
1418
- ...(source.tools !== undefined ? { tools: tools.entries! } : {}),
1419
- };
1420
- return {
1421
- content: serializeAgent(portableAgent, { preserveFrontmatterFields: new Set(Object.keys(frontmatter)) }),
1422
- resourcePaths,
1423
- };
1424
- }
1425
-
1426
- function cleanupEjectedFile(targetPath: string, expectedContent: string): void {
1427
- try {
1428
- if (fs.readFileSync(targetPath, "utf-8") === expectedContent) fs.unlinkSync(targetPath);
1429
- } catch {
1430
- // The service only cleans the file it created during this call.
1431
- }
1432
- }
1433
-
1434
- function validateEjectedAgentLaunchPreflight(agent: AgentConfig, cwd: string): string | undefined {
1435
- const resolvedSkills = resolveSkillsWithFallback(
1436
- agent.skills ?? [],
1437
- cwd,
1438
- undefined,
1439
- agent.skillPath,
1440
- agent.filePath ? path.dirname(agent.filePath) : cwd,
1441
- );
1442
- if (resolvedSkills.missing.length > 0) {
1443
- return `Missing skills: ${resolvedSkills.missing.join(", ")}`;
1444
- }
1445
- try {
1446
- resolvePiLaunchToolPlan({
1447
- tools: agent.tools,
1448
- extensions: agent.extensions,
1449
- subagentOnlyExtensions: agent.subagentOnlyExtensions,
1450
- mcpDirectTools: agent.mcpDirectTools,
1451
- cwd,
1452
- requireReadTool: resolvedSkills.resolved.length > 0,
1453
- agentName: agent.name,
1454
- sandbox: agent.sandbox,
1455
- permissionProfile: agent.permissionProfile,
1456
- });
1457
- } catch (error) {
1458
- return error instanceof Error ? error.message : String(error);
1459
- }
1460
- return undefined;
1461
- }
1462
-
1463
- /**
1464
- * Shared extraction of the existing eject handler. It deliberately owns only
1465
- * agent-definition copying, no-overwrite checks, project-trust input, and
1466
- * portable package-relative resource paths.
1467
- */
1468
- export function ejectAgentDefinition(input: EjectAgentDefinitionInput): EjectAgentDefinitionResult {
1469
- const raw = input.agent.trim();
1470
- const sanitized = sanitizeName(raw);
1471
- if (!raw || !sanitized) {
1472
- return { ok: false, code: "invalid_agent", message: "agent must be a non-empty valid agent name." };
1473
- }
1474
- if (input.scope !== "user" && input.scope !== "project") {
1475
- return { ok: false, code: "invalid_agent", message: "scope must be 'user' or 'project'." };
1476
- }
1477
- if (input.scope === "project" && input.projectTrusted !== true) {
1478
- return {
1479
- ok: false,
1480
- code: "untrusted_project",
1481
- scope: input.scope,
1482
- message: "Project scope ejection requires a trusted project. Trust the project and retry.",
1483
- };
1484
- }
1485
-
1486
- let discovered: ReturnType<typeof discoverAgentsAll>;
1487
- try {
1488
- discovered = discoverAgentsAll(input.cwd);
1489
- } catch (error) {
1490
- return {
1491
- ok: false,
1492
- code: "rediscovery_failed",
1493
- scope: input.scope,
1494
- message: `Unable to discover agents before ejecting: ${error instanceof Error ? error.message : String(error)}`,
1495
- };
1496
- }
1497
- if (input.scope === "project" && discovered.projectDir === null) {
1498
- return {
1499
- ok: false,
1500
- code: "missing_project_root",
1501
- scope: input.scope,
1502
- message: "Project scope ejection is not available here: no project config root (.pi or .agents) was found above the cwd.",
1503
- };
1504
- }
1505
-
1506
- const existingCustom = (input.scope === "user" ? discovered.user : discovered.project)
1507
- .find((candidate) => candidate.name === raw || candidate.name === sanitized);
1508
- if (existingCustom) {
1509
- return {
1510
- ok: false,
1511
- code: "existing_custom",
1512
- scope: input.scope,
1513
- targetPath: existingCustom.filePath,
1514
- message: `Agent '${existingCustom.name}' is already a custom ${input.scope} agent at ${existingCustom.filePath}. Edit it with { action: "update", agent: "${existingCustom.name}" } or delete it first.`,
1515
- };
1516
- }
1517
- const bundledCandidates = input.scope === "user"
1518
- ? discoverAgents(input.cwd, "user").agents.filter((candidate) => candidate.source === "builtin" || candidate.source === "package")
1519
- : [...discovered.package, ...discovered.builtin];
1520
- const source = bundledCandidates.find((candidate) => candidate.name === raw || candidate.name === sanitized);
1521
- if (!source) {
1522
- return {
1523
- ok: false,
1524
- code: "missing_source",
1525
- scope: input.scope,
1526
- message: `Agent '${raw}' not found or is not a bundled/package agent. eject copies a builtin or package agent to ${input.scope} scope so it can be customized. Available: ${availableAgentNames(input.cwd).join(", ") || "none"}.`,
1527
- };
1528
- }
1529
- const runtimeName = source.name;
1530
- if (nameExistsInScope(input.cwd, input.scope, runtimeName)) {
1531
- return {
1532
- ok: false,
1533
- code: "name_conflict",
1534
- scope: input.scope,
1535
- message: `An agent or chain named '${runtimeName}' already exists in ${input.scope} scope. Remove or rename it first.`,
1536
- };
1537
- }
1538
-
1539
- const targetDir = input.scope === "user" ? discovered.userDir : discovered.projectDir!;
1540
- const targetPath = path.join(targetDir, `${runtimeName}.md`);
1541
- if (fs.existsSync(targetPath)) {
1542
- return {
1543
- ok: false,
1544
- code: "existing_file",
1545
- scope: input.scope,
1546
- targetPath,
1547
- message: `File already exists at ${targetPath} but is not a valid agent definition. Remove or rename it first.`,
1548
- };
1549
- }
1550
-
1551
- const portable = portableEjectedAgentContent(source);
1552
- if (portable.error) return { ...portable.error, scope: input.scope, targetPath };
1553
- const content = portable.content!;
1554
- try {
1555
- fs.mkdirSync(targetDir, { recursive: true });
1556
- fs.writeFileSync(targetPath, content, { encoding: "utf-8", flag: "wx" });
1557
- } catch (error) {
1558
- const message = error instanceof Error ? error.message : String(error);
1559
- return {
1560
- ok: false,
1561
- code: "write_failed",
1562
- scope: input.scope,
1563
- targetPath,
1564
- message: `Failed to write ejected agent '${runtimeName}' at ${targetPath}: ${message}`,
1565
- };
1566
- }
1567
-
1568
- const rediscovered = discoverAgentsAll(input.cwd);
1569
- const copied = (input.scope === "user" ? rediscovered.user : rediscovered.project)
1570
- .find((candidate) => candidate.name === runtimeName && path.resolve(candidate.filePath) === path.resolve(targetPath));
1571
- if (!copied) {
1572
- cleanupEjectedFile(targetPath, content);
1573
- return {
1574
- ok: false,
1575
- code: "rediscovery_failed",
1576
- scope: input.scope,
1577
- targetPath,
1578
- message: `Ejected agent '${runtimeName}' could not be rediscovered at ${targetPath}; no file was kept.`,
1579
- };
1580
- }
1581
-
1582
- const preflightError = validateEjectedAgentLaunchPreflight(copied, input.cwd);
1583
- if (preflightError) {
1584
- cleanupEjectedFile(targetPath, content);
1585
- return {
1586
- ok: false,
1587
- code: "preflight_failed",
1588
- scope: input.scope,
1589
- targetPath,
1590
- message: `Ejected agent '${runtimeName}' failed launch preflight at ${targetPath}: ${preflightError}. No file was kept.`,
1591
- };
1592
- }
1593
-
1594
- const sourceKind = source.source as "builtin" | "package";
1595
- return {
1596
- ok: true,
1597
- code: "ejected",
1598
- message: `Ejected agent '${runtimeName}' from ${sourceKind} to ${input.scope} scope at ${targetPath}. Edit it there to customize; it shadows the bundled ${sourceKind} agent of the same name.`,
1599
- agent: runtimeName,
1600
- source: sourceKind,
1601
- scope: input.scope,
1602
- targetPath,
1603
- verification: {
1604
- agent: copied.name,
1605
- scope: input.scope,
1606
- targetPath,
1607
- source: sourceKind,
1608
- resourcePaths: portable.resourcePaths ?? [],
1609
- launchPreflighted: true,
1610
- },
1611
- };
1612
- }
1613
-
1614
1302
  function handleEject(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
1615
1303
  if (!params.agent) return result("Specify 'agent' for eject.", true);
1616
1304
  const parsedScope = actionScope(params.agentScope, "eject");
@@ -1624,6 +1312,7 @@ function handleEject(params: ManagementParams, ctx: ManagementContext): AgentToo
1624
1312
  // must supply affirmative project trust themselves.
1625
1313
  ...(scope === "project" ? { projectTrusted: true } : {}),
1626
1314
  });
1315
+ if (ejected.ok) ctx.onAgentsChanged?.();
1627
1316
  return result(ejected.message, !ejected.ok);
1628
1317
  }
1629
1318
 
@@ -1646,6 +1335,7 @@ function handleDisable(params: ManagementParams, ctx: ManagementContext): AgentT
1646
1335
  const settingsPath = mergeBuiltinAgentOverride(ctx.cwd, runtimeName, scope, { disabled: true });
1647
1336
  const after = resolveEffectiveAgent(discoverAgentsAll(ctx.cwd), raw).agent;
1648
1337
  if (after?.disabled === true) {
1338
+ ctx.onAgentsChanged?.();
1649
1339
  return result(`Disabled agent '${runtimeName}' via ${scope} settings override at ${settingsPath}. It is now hidden from runtime discovery and { action: "list" }.`);
1650
1340
  }
1651
1341
  return result(`Wrote a disabled override for '${runtimeName}' at ${settingsPath}, but the agent is still enabled. A higher-precedence ${after?.override?.scope ?? "project"} override is likely winning. Try agentScope: '${after?.override?.scope ?? "project"}'.`, true);
@@ -1670,6 +1360,7 @@ function handleEnable(params: ManagementParams, ctx: ManagementContext): AgentTo
1670
1360
  const { path: settingsPath, removed } = removeBuiltinAgentOverrideFields(ctx.cwd, runtimeName, scope, ["disabled"]);
1671
1361
  const after = resolveEffectiveAgent(discoverAgentsAll(ctx.cwd), raw).agent;
1672
1362
  if (after && after.disabled !== true) {
1363
+ if (removed) ctx.onAgentsChanged?.();
1673
1364
  if (removed) return result(`Enabled agent '${runtimeName}' (removed disabled override at ${settingsPath}).`);
1674
1365
  return result(`Agent '${runtimeName}' is already enabled.`);
1675
1366
  }
@@ -1705,8 +1396,8 @@ function handleReset(params: ManagementParams, ctx: ManagementContext): AgentToo
1705
1396
  fs.unlinkSync(custom.filePath);
1706
1397
  lines.push(`Deleted custom ${scope} agent file at ${custom.filePath}.`);
1707
1398
  }
1708
- const overrideRemoval = removeBuiltinAgentOverride(ctx.cwd, runtimeName, scope);
1709
- if (overrideRemoval.removed) lines.push(`Removed ${scope} settings override at ${overrideRemoval.path}.`);
1399
+ const overrideRemoval = removeBuiltinAgentOverride(ctx.cwd, runtimeName, scope, { preserveMachine: true });
1400
+ if (overrideRemoval.removed) lines.push(`${overrideRemoval.machinePreserved ? "Cleared customization in" : "Removed"} ${scope} settings override at ${overrideRemoval.path}.${overrideRemoval.machinePreserved ? " Retained machine placement." : ""}`);
1710
1401
  if (lines.length === 0) {
1711
1402
  const otherScope = scope === "user" ? "project" : "user";
1712
1403
  const otherCustom = (otherScope === "user" ? d.user : d.project).find((a) => a.name === raw || a.name === sanitized);
@@ -1717,6 +1408,7 @@ function handleReset(params: ManagementParams, ctx: ManagementContext): AgentToo
1717
1408
  return result(`Agent '${runtimeName}' has no ${scope} customization to reset.${note} It is at its bundled ${bundled.source} default.`);
1718
1409
  }
1719
1410
  lines.push(`Reset agent '${runtimeName}' to its bundled ${bundled.source} default.`);
1411
+ ctx.onAgentsChanged?.();
1720
1412
  return result(lines.join("\n"));
1721
1413
  }
1722
1414