@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -5,6 +5,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
5
  import {
6
6
  type AgentConfig,
7
7
  type AgentDiscoveryDiagnostic,
8
+ type AgentDiscoveryAllResult,
8
9
  type AgentScope,
9
10
  type AgentSource,
10
11
  defaultInheritProjectContext,
@@ -47,7 +48,11 @@ export const AGENT_MANAGEMENT_API_VERSION = 1 as const;
47
48
 
48
49
  type ManagementAction = "list" | "get" | "models" | "create" | "update" | "delete" | "eject" | "disable" | "enable" | "reset";
49
50
  type ManagementScope = "user" | "project";
50
- type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { isProjectTrusted?: ExtensionContext["isProjectTrusted"]; model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string; runtimeAgentOwner?: RuntimeAgentOwner; onAgentsChanged?: () => void };
51
+ type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { isProjectTrusted?: ExtensionContext["isProjectTrusted"]; model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string; runtimeAgentOwner?: RuntimeAgentOwner; onAgentsChanged?: () => void; discoverAgentsAll?: typeof discoverAgentsAll };
52
+
53
+ function discoverCatalog(ctx: ManagementContext, cwd: string = ctx.cwd, provider?: string): AgentDiscoveryAllResult {
54
+ return (ctx.discoverAgentsAll ?? discoverAgentsAll)(cwd, provider);
55
+ }
51
56
 
52
57
  interface ManagementParams {
53
58
  action?: string;
@@ -62,11 +67,7 @@ function result(text: string, isError = false, details?: Partial<Details>): Agen
62
67
  }
63
68
 
64
69
  function jsonDetails<T>(value: T): T {
65
- try {
66
- return JSON.parse(JSON.stringify(value)) as T;
67
- } catch (error) {
68
- throw new Error(`Failed to serialize agent management details: ${error instanceof Error ? error.message : String(error)}`);
69
- }
70
+ return JSON.parse(JSON.stringify(value)) as T;
70
71
  }
71
72
 
72
73
  function presentDetails<T extends Record<string, unknown>>(value: T): T | undefined {
@@ -135,44 +136,53 @@ function parsePackageConfig(value: unknown): { packageName?: string; error?: str
135
136
  return parsePackageName(value, "config.package");
136
137
  }
137
138
 
138
- function allAgents(d: { builtin: AgentConfig[]; package: AgentConfig[]; user: AgentConfig[]; project: AgentConfig[] }): AgentConfig[] {
139
+ type DiscoveredAgentSets = Pick<AgentDiscoveryAllResult, "builtin" | "package" | "user" | "project" | "cwd">;
140
+
141
+ function allAgents(d: DiscoveredAgentSets): AgentConfig[] {
139
142
  return [...d.builtin, ...d.package, ...d.user, ...d.project];
140
143
  }
141
144
 
142
145
  function effectiveAgentsForScope(
143
146
  scope: AgentScope,
144
- d: { builtin: AgentConfig[]; package: AgentConfig[]; user: AgentConfig[]; project: AgentConfig[] },
147
+ d: DiscoveredAgentSets,
145
148
  runtimeAgentOwner?: RuntimeAgentOwner,
149
+ preferredModelProvider?: string,
146
150
  ): AgentConfig[] {
147
151
  let agents = mergeAgentsForScope(scope, d.user, d.project, d.builtin, d.package);
148
152
  if (runtimeAgentOwner) {
149
- agents = mergeRuntimeAgents(runtimeAgentOwner, { agents }, allAgents(d)).agents;
153
+ agents = mergeRuntimeAgents(runtimeAgentOwner, { agents }, allAgents(d), { cwd: d.cwd, scope, preferredModelProvider }).agents;
150
154
  }
151
155
  return agents;
152
156
  }
153
157
 
154
158
  function availableAgentNamesFromDiscovery(
155
- d: { builtin: AgentConfig[]; package: AgentConfig[]; user: AgentConfig[]; project: AgentConfig[] },
159
+ d: DiscoveredAgentSets,
156
160
  runtimeAgentOwner?: RuntimeAgentOwner,
161
+ preferredModelProvider?: string,
157
162
  ): string[] {
158
- const agents = runtimeAgentOwner ? effectiveAgentsForScope("both", d, runtimeAgentOwner) : allAgents(d);
163
+ const agents = runtimeAgentOwner ? effectiveAgentsForScope("both", d, runtimeAgentOwner, preferredModelProvider) : allAgents(d);
159
164
  return [...new Set(agents.map((agent) => agent.name))].sort((a, b) => a.localeCompare(b));
160
165
  }
161
166
 
167
+ function availableAgentNames(ctx: ManagementContext, cwd: string = ctx.cwd): string[] {
168
+ return availableAgentNamesFromDiscovery(discoverCatalog(ctx, cwd));
169
+ }
170
+
162
171
  // [fork] Exported for agents/agent-eject.ts.
163
- export function availableAgentNames(cwd: string): string[] {
172
+ export function availableAgentNamesForCwd(cwd: string): string[] {
164
173
  return availableAgentNamesFromDiscovery(discoverAgentsAll(cwd));
165
174
  }
166
175
 
167
176
  function findAgentsInDiscovery(
168
177
  name: string,
169
- d: { builtin: AgentConfig[]; package: AgentConfig[]; user: AgentConfig[]; project: AgentConfig[] },
178
+ d: DiscoveredAgentSets,
170
179
  scope: AgentScope = "both",
171
180
  runtimeAgentOwner?: RuntimeAgentOwner,
181
+ preferredModelProvider?: string,
172
182
  ): AgentConfig[] {
173
183
  const raw = name.trim();
174
184
  const sanitized = sanitizeName(raw);
175
- const scoped = effectiveAgentsForScope(scope, d, runtimeAgentOwner);
185
+ const scoped = effectiveAgentsForScope(scope, d, runtimeAgentOwner, preferredModelProvider);
176
186
  let resolved = resolveAgentName(raw, scoped);
177
187
  if (!resolved.agent && !resolved.error && sanitized !== raw) resolved = resolveAgentName(sanitized, scoped);
178
188
  if (resolved.agent) return scoped.filter((agent) => agent.name === resolved.agent!.name).sort((a, b) => a.source.localeCompare(b.source));
@@ -182,8 +192,8 @@ function findAgentsInDiscovery(
182
192
  .sort((a, b) => a.source.localeCompare(b.source));
183
193
  }
184
194
 
185
- function findAgents(name: string, cwd: string, scope: AgentScope = "both"): AgentConfig[] {
186
- return findAgentsInDiscovery(name, discoverAgentsAll(cwd), scope);
195
+ function findAgents(name: string, ctx: ManagementContext, scope: AgentScope = "both"): AgentConfig[] {
196
+ return findAgentsInDiscovery(name, discoverCatalog(ctx), scope);
187
197
  }
188
198
 
189
199
  function diagnosticsForScope(diagnostics: AgentDiscoveryDiagnostic[] | undefined, scope: AgentScope): AgentDiscoveryDiagnostic[] | undefined {
@@ -210,8 +220,16 @@ function resolveEffectiveAgent(d: ReturnType<typeof discoverAgentsAll>, name: st
210
220
  return { agent: matches.reduce((best, agent) => (AGENT_SOURCE_PRECEDENCE[agent.source] > AGENT_SOURCE_PRECEDENCE[best.source] ? agent : best)) };
211
221
  }
212
222
 
223
+ function nameExistsInScope(ctx: ManagementContext, scope: ManagementScope, name: string, excludePath?: string): boolean {
224
+ const d = discoverCatalog(ctx);
225
+ for (const a of scope === "user" ? d.user : d.project) {
226
+ if (a.name === name && a.filePath !== excludePath) return true;
227
+ }
228
+ return false;
229
+ }
230
+
213
231
  // [fork] Exported for agents/agent-eject.ts.
214
- export function nameExistsInScope(cwd: string, scope: ManagementScope, name: string, excludePath?: string): boolean {
232
+ export function nameExistsInScopeForCwd(cwd: string, scope: ManagementScope, name: string, excludePath?: string): boolean {
215
233
  const d = discoverAgentsAll(cwd);
216
234
  for (const a of scope === "user" ? d.user : d.project) {
217
235
  if (a.name === name && a.filePath !== excludePath) return true;
@@ -289,9 +307,9 @@ export function editableAgentConfig(agent: AgentConfig): AgentConfig {
289
307
  excludeTools: _excludeTools,
290
308
  mcpDirectTools: _mcpDirectTools,
291
309
  allowNestedSubagents: _allowNestedSubagents,
310
+ allowedAgents: _allowedAgents,
292
311
  subagentOnlyExtensions: _subagentOnlyExtensions,
293
312
  mutationTools: _mutationTools,
294
- completionGuard: _completionGuard,
295
313
  toolBudget: _toolBudget,
296
314
  ...editable
297
315
  } = withoutExtensions;
@@ -325,10 +343,10 @@ export function editableAgentConfig(agent: AgentConfig): AgentConfig {
325
343
  ...(base.excludeTools !== undefined ? { excludeTools: [...base.excludeTools] } : {}),
326
344
  ...(base.mcpDirectTools !== undefined ? { mcpDirectTools: [...base.mcpDirectTools] } : {}),
327
345
  ...(base.allowNestedSubagents !== undefined ? { allowNestedSubagents: base.allowNestedSubagents } : {}),
346
+ ...(base.allowedAgents !== undefined ? { allowedAgents: [...base.allowedAgents] } : {}),
328
347
  ...(base.extensions !== undefined ? { extensions: [...base.extensions] } : {}),
329
348
  ...(base.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: [...base.subagentOnlyExtensions] } : {}),
330
349
  ...(base.mutationTools !== undefined ? { mutationTools: [...base.mutationTools] } : {}),
331
- ...(base.completionGuard !== undefined ? { completionGuard: base.completionGuard } : {}),
332
350
  ...(base.toolBudget !== undefined ? { toolBudget: base.toolBudget } : {}),
333
351
  }, agent.filePath);
334
352
  }
@@ -393,10 +411,6 @@ export function preservedAgentFrontmatterFields(agent: AgentConfig, cfg: Record<
393
411
  if (hasKey(cfg, "reads")) changed("defaultReads");
394
412
  if (hasKey(cfg, "progress")) changed("defaultProgress");
395
413
  if (hasKey(cfg, "maxSubagentDepth")) changed("maxSubagentDepth");
396
- if (hasKey(cfg, "completionGuard")) {
397
- changed("completionGuard");
398
- if (cfg.completionGuard === true) fields.add("completionGuard");
399
- }
400
414
  if (hasKey(cfg, "toolBudget")) changed("toolBudget");
401
415
  if (hasKey(cfg, "sandbox")) changed("sandbox");
402
416
  if (hasKey(cfg, "permissionProfile")) changed("permission-profile");
@@ -610,10 +624,6 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
610
624
  target.maxSubagentDepth = cfg.maxSubagentDepth;
611
625
  } else return "config.maxSubagentDepth must be an integer >= 0 or false when provided.";
612
626
  }
613
- if (hasKey(cfg, "completionGuard")) {
614
- if (typeof cfg.completionGuard !== "boolean") return "config.completionGuard must be a boolean when provided.";
615
- target.completionGuard = cfg.completionGuard;
616
- }
617
627
  if (hasKey(cfg, "toolBudget")) {
618
628
  if (cfg.toolBudget === false || cfg.toolBudget === "") delete target.toolBudget;
619
629
  else {
@@ -649,7 +659,6 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
649
659
  target.mutationTools?.length ? "mutationTools" : undefined,
650
660
  target.skills?.length || target.skillPath?.length ? "skills" : undefined,
651
661
  target.maxSubagentDepth !== undefined ? "maxSubagentDepth" : undefined,
652
- target.completionGuard !== undefined ? "completionGuard" : undefined,
653
662
  target.toolBudget ? "toolBudget" : undefined,
654
663
  target.sandbox ? "sandbox" : undefined,
655
664
  target.permissionProfile ? "permissionProfile" : undefined,
@@ -663,6 +672,7 @@ function resolveTarget<T extends { name: string; source: AgentSource; filePath:
663
672
  name: string,
664
673
  matches: T[],
665
674
  cwd: string,
675
+ ctx: ManagementContext,
666
676
  scopeHint?: string,
667
677
  ): T | AgentToolResult<Details> {
668
678
  const distinctNames = [...new Set(matches.map((match) => match.name))];
@@ -670,7 +680,7 @@ function resolveTarget<T extends { name: string; source: AgentSource; filePath:
670
680
  const mutable = matches.filter((match): match is T & { source: ManagementScope } => isMutableSource(match.source));
671
681
  if (mutable.length === 0) {
672
682
  if (matches.length > 0) return result(`Agent '${name}' is read-only and cannot be modified. Create a same-named agent in user or project scope to override it.`, true);
673
- return result(`Agent '${name}' not found. Available: ${availableAgentNames(cwd).join(", ") || "none"}.`, true);
683
+ return result(`Agent '${name}' not found. Available: ${availableAgentNames(ctx, cwd).join(", ") || "none"}.`, true);
674
684
  }
675
685
  if (mutable.length === 1) return mutable[0]!;
676
686
  const scope = asDisambiguationScope(scopeHint);
@@ -684,8 +694,8 @@ function resolveTarget<T extends { name: string; source: AgentSource; filePath:
684
694
  return scoped[0]!;
685
695
  }
686
696
 
687
- function renamePath(currentPath: string, newName: string, scope: ManagementScope, cwd: string): { filePath?: string; error?: string } {
688
- if (nameExistsInScope(cwd, scope, newName, currentPath)) return { error: `Name '${newName}' already exists in ${scope} scope.` };
697
+ function renamePath(currentPath: string, newName: string, scope: ManagementScope, ctx: ManagementContext): { filePath?: string; error?: string } {
698
+ if (nameExistsInScope(ctx, scope, newName, currentPath)) return { error: `Name '${newName}' already exists in ${scope} scope.` };
689
699
  const filePath = path.join(path.dirname(currentPath), `${newName}.md`);
690
700
  if (fs.existsSync(filePath) && filePath !== currentPath) return { error: `File already exists at ${filePath} but is not a valid agent definition. Remove or rename it first.` };
691
701
  fs.renameSync(currentPath, filePath);
@@ -993,7 +1003,6 @@ function formatAgentDetail(agent: AgentConfig): string {
993
1003
  if (agent.defaultReads?.length) lines.push(`Reads: ${agent.defaultReads.join(", ")}`);
994
1004
  if (agent.defaultProgress) lines.push("Progress: true");
995
1005
  if (agent.maxSubagentDepth !== undefined) lines.push(`Max subagent depth: ${agent.maxSubagentDepth}`);
996
- if (agent.completionGuard === false) lines.push("Completion guard: false");
997
1006
  if (agent.toolBudget) lines.push(`Tool budget: ${JSON.stringify(agent.toolBudget)}`);
998
1007
  if (agent.sandbox) lines.push(`Sandbox profile: ${agent.sandbox}`);
999
1008
  if (agent.permissionProfile) lines.push(`Permission profile: ${agent.permissionProfile}`);
@@ -1004,8 +1013,8 @@ function formatAgentDetail(agent: AgentConfig): string {
1004
1013
 
1005
1014
  export function handleList(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
1006
1015
  const scope = normalizeListScope(params.agentScope) ?? "both";
1007
- const d = discoverAgentsAll(ctx.cwd, ctx.model?.provider);
1008
- let scopedAgents = effectiveAgentsForScope(scope, d, ctx.runtimeAgentOwner);
1016
+ const d = discoverCatalog(ctx, ctx.cwd, ctx.model?.provider);
1017
+ let scopedAgents = effectiveAgentsForScope(scope, d, ctx.runtimeAgentOwner, ctx.model?.provider);
1009
1018
  scopedAgents = scopedAgents
1010
1019
  .sort((a, b) => a.name.localeCompare(b.name));
1011
1020
  const capabilityCeiling = resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
@@ -1060,8 +1069,8 @@ function handleModels(params: ManagementParams, ctx: ManagementContext): AgentTo
1060
1069
  const scope = normalizeListScope(params.agentScope);
1061
1070
  if (!scope) return result("agentScope must be 'user', 'project', or 'both' for models.", true);
1062
1071
 
1063
- const discovered = discoverAgentsAll(ctx.cwd, ctx.model?.provider);
1064
- const effectiveAgents = effectiveAgentsForScope(scope, discovered, ctx.runtimeAgentOwner)
1072
+ const discovered = discoverCatalog(ctx, ctx.cwd, ctx.model?.provider);
1073
+ const effectiveAgents = effectiveAgentsForScope(scope, discovered, ctx.runtimeAgentOwner, ctx.model?.provider)
1065
1074
  .sort((a, b) => a.name.localeCompare(b.name));
1066
1075
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
1067
1076
  const currentModel = ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined;
@@ -1070,7 +1079,7 @@ function handleModels(params: ManagementParams, ctx: ManagementContext): AgentTo
1070
1079
 
1071
1080
  let selectedAgents = effectiveAgents;
1072
1081
  if (requestedAgent) {
1073
- const matches = findAgentsInDiscovery(requestedAgent, discovered, scope, ctx.runtimeAgentOwner);
1082
+ const matches = findAgentsInDiscovery(requestedAgent, discovered, scope, ctx.runtimeAgentOwner, ctx.model?.provider);
1074
1083
  const diagnostics = diagnosticsForScope(discovered.agentDiagnostics, scope);
1075
1084
  const normalizedName = sanitizeName(requestedAgent);
1076
1085
  const diagnostic = findBlockingAgentDiagnostic(requestedAgent, matches, diagnostics)
@@ -1079,7 +1088,7 @@ function handleModels(params: ManagementParams, ctx: ManagementContext): AgentTo
1079
1088
  const distinctNames = [...new Set(matches.map((agent) => agent.name))];
1080
1089
  if (distinctNames.length > 1) return result(`Ambiguous agent alias or name '${params.agent}': ${distinctNames.sort((a, b) => a.localeCompare(b)).join(", ")}`, true);
1081
1090
  if (!matches.length) {
1082
- return result(`Agent '${params.agent}' not found. Available: ${availableAgentNamesFromDiscovery(discovered, ctx.runtimeAgentOwner).join(", ") || "none"}.`, true);
1091
+ return result(`Agent '${params.agent}' not found. Available: ${availableAgentNamesFromDiscovery(discovered, ctx.runtimeAgentOwner, ctx.model?.provider).join(", ") || "none"}.`, true);
1083
1092
  }
1084
1093
  selectedAgents = [matches[0]!];
1085
1094
  }
@@ -1156,7 +1165,7 @@ function handleGet(params: ManagementParams, ctx: ManagementContext): AgentToolR
1156
1165
  if (!params.agent) return result("Specify 'agent' for get.", true);
1157
1166
  const scope = normalizeListScope(params.agentScope);
1158
1167
  if (!scope) return result("agentScope must be 'user', 'project', or 'both' for get.", true);
1159
- const discovered = discoverAgentsAll(ctx.cwd, ctx.model?.provider);
1168
+ const discovered = discoverCatalog(ctx, ctx.cwd, ctx.model?.provider);
1160
1169
  const matches = findAgentsInDiscovery(params.agent, discovered, scope);
1161
1170
  const diagnostics = diagnosticsForScope(discovered.agentDiagnostics, scope);
1162
1171
  const rawName = params.agent.trim();
@@ -1187,12 +1196,12 @@ export function handleCreate(params: ManagementParams, ctx: ManagementContext):
1187
1196
  const scopeRaw = cfg.scope ?? "user";
1188
1197
  if (scopeRaw !== "user" && scopeRaw !== "project") return result("config.scope must be 'user' or 'project'.", true);
1189
1198
  const scope = scopeRaw;
1190
- if (hasKey(cfg, "steps")) return result("Durable chain definitions were removed; use workflowScript or /prompt-workflow for repeatable workflows.", true);
1191
- const d = discoverAgentsAll(ctx.cwd);
1199
+ if (hasKey(cfg, "steps")) return result("Durable chain definitions were removed; use a workflow script or /prompt-workflow for repeatable workflows.", true);
1200
+ const d = discoverCatalog(ctx);
1192
1201
  const projectConfigDir = getProjectConfigDir(ctx.cwd);
1193
1202
  const targetDir = scope === "user" ? d.userDir : d.projectDir ?? path.join(projectConfigDir, "agents");
1194
1203
  fs.mkdirSync(targetDir, { recursive: true });
1195
- if (nameExistsInScope(ctx.cwd, scope, runtimeName)) return result(`Name '${runtimeName}' already exists in ${scope} scope. Use update instead.`, true);
1204
+ if (nameExistsInScope(ctx, scope, runtimeName)) return result(`Name '${runtimeName}' already exists in ${scope} scope. Use update instead.`, true);
1196
1205
  const targetPath = path.join(targetDir, `${runtimeName}.md`);
1197
1206
  if (fs.existsSync(targetPath)) return result(`File already exists at ${targetPath} but is not a valid agent definition. Remove or rename it first.`, true);
1198
1207
  const warnings: string[] = [];
@@ -1229,10 +1238,10 @@ export function handleUpdate(params: ManagementParams, ctx: ManagementContext):
1229
1238
  if (parsedConfig.status === "error") return result(parsedConfig.message, true);
1230
1239
  if (parsedConfig.status === "missing") return result("config required for update.", true);
1231
1240
  const cfg = parsedConfig.value;
1232
- if (hasKey(cfg, "steps")) return result("Durable chain definitions were removed; use workflowScript or /prompt-workflow for repeatable workflows.", true);
1241
+ if (hasKey(cfg, "steps")) return result("Durable chain definitions were removed; use a workflow script or /prompt-workflow for repeatable workflows.", true);
1233
1242
  const warnings: string[] = [];
1234
1243
  const scopeHint = asDisambiguationScope(params.agentScope);
1235
- const targetOrError = resolveTarget(params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
1244
+ const targetOrError = resolveTarget(params.agent, findAgents(params.agent, ctx, scopeHint ?? "both"), ctx.cwd, ctx, scopeHint);
1236
1245
  if ("content" in targetOrError) return targetOrError;
1237
1246
  const target = targetOrError;
1238
1247
  if (target.source !== "user" && target.source !== "project") return result(`Cannot update ${target.source} agent '${target.name}'. Eject it to user or project scope first.`, true);
@@ -1276,7 +1285,7 @@ export function handleUpdate(params: ManagementParams, ctx: ManagementContext):
1276
1285
  if (sw) warnings.push(sw);
1277
1286
  }
1278
1287
  if (updated.name !== oldName) {
1279
- const renamed = renamePath(target.filePath, updated.name, target.source, ctx.cwd);
1288
+ const renamed = renamePath(target.filePath, updated.name, target.source, ctx);
1280
1289
  if (renamed.error) return result(renamed.error, true);
1281
1290
  updated.filePath = renamed.filePath!;
1282
1291
  }
@@ -1291,7 +1300,7 @@ export function handleUpdate(params: ManagementParams, ctx: ManagementContext):
1291
1300
  function handleDelete(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
1292
1301
  if (!params.agent) return result("Specify 'agent' for delete.", true);
1293
1302
  const scopeHint = asDisambiguationScope(params.agentScope);
1294
- const targetOrError = resolveTarget(params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
1303
+ const targetOrError = resolveTarget(params.agent, findAgents(params.agent, ctx, scopeHint ?? "both"), ctx.cwd, ctx, scopeHint);
1295
1304
  if ("content" in targetOrError) return targetOrError;
1296
1305
  const target = targetOrError;
1297
1306
  fs.unlinkSync(target.filePath);
@@ -1322,18 +1331,18 @@ function handleDisable(params: ManagementParams, ctx: ManagementContext): AgentT
1322
1331
  const parsedScope = actionScope(params.agentScope, "disable");
1323
1332
  if (parsedScope.error) return parsedScope.error;
1324
1333
  const scope = parsedScope.scope!;
1325
- const d = discoverAgentsAll(ctx.cwd);
1334
+ const d = discoverCatalog(ctx);
1326
1335
  if (scope === "project" && d.projectSettingsPath === null) {
1327
1336
  return result("Project override is not available here: no project config root (.pi or .agents) was found above the cwd. Use agentScope: 'user' or run from inside a project.", true);
1328
1337
  }
1329
1338
  const effective = resolveEffectiveAgent(d, raw);
1330
1339
  if (effective.error) return result(effective.error, true);
1331
1340
  if (!effective.agent) {
1332
- return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx.cwd).join(", ") || "none"}.`, true);
1341
+ return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx).join(", ") || "none"}.`, true);
1333
1342
  }
1334
1343
  const runtimeName = effective.agent.name;
1335
1344
  const settingsPath = mergeBuiltinAgentOverride(ctx.cwd, runtimeName, scope, { disabled: true });
1336
- const after = resolveEffectiveAgent(discoverAgentsAll(ctx.cwd), raw).agent;
1345
+ const after = resolveEffectiveAgent(discoverCatalog(ctx), raw).agent;
1337
1346
  if (after?.disabled === true) {
1338
1347
  ctx.onAgentsChanged?.();
1339
1348
  return result(`Disabled agent '${runtimeName}' via ${scope} settings override at ${settingsPath}. It is now hidden from runtime discovery and { action: "list" }.`);
@@ -1347,18 +1356,18 @@ function handleEnable(params: ManagementParams, ctx: ManagementContext): AgentTo
1347
1356
  const parsedScope = actionScope(params.agentScope, "enable");
1348
1357
  if (parsedScope.error) return parsedScope.error;
1349
1358
  const scope = parsedScope.scope!;
1350
- const d = discoverAgentsAll(ctx.cwd);
1359
+ const d = discoverCatalog(ctx);
1351
1360
  if (scope === "project" && d.projectSettingsPath === null) {
1352
1361
  return result("Project override is not available here: no project config root (.pi or .agents) was found above the cwd. Use agentScope: 'user' or run from inside a project.", true);
1353
1362
  }
1354
1363
  const effective = resolveEffectiveAgent(d, raw);
1355
1364
  if (effective.error) return result(effective.error, true);
1356
1365
  if (!effective.agent) {
1357
- return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx.cwd).join(", ") || "none"}.`, true);
1366
+ return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx).join(", ") || "none"}.`, true);
1358
1367
  }
1359
1368
  const runtimeName = effective.agent.name;
1360
1369
  const { path: settingsPath, removed } = removeBuiltinAgentOverrideFields(ctx.cwd, runtimeName, scope, ["disabled"]);
1361
- const after = resolveEffectiveAgent(discoverAgentsAll(ctx.cwd), raw).agent;
1370
+ const after = resolveEffectiveAgent(discoverCatalog(ctx), raw).agent;
1362
1371
  if (after && after.disabled !== true) {
1363
1372
  if (removed) ctx.onAgentsChanged?.();
1364
1373
  if (removed) return result(`Enabled agent '${runtimeName}' (removed disabled override at ${settingsPath}).`);
@@ -1377,7 +1386,7 @@ function handleReset(params: ManagementParams, ctx: ManagementContext): AgentToo
1377
1386
  const parsedScope = actionScope(params.agentScope, "reset");
1378
1387
  if (parsedScope.error) return parsedScope.error;
1379
1388
  const scope = parsedScope.scope!;
1380
- const d = discoverAgentsAll(ctx.cwd);
1389
+ const d = discoverCatalog(ctx);
1381
1390
  if (scope === "project" && d.projectSettingsPath === null) {
1382
1391
  return result("Project override is not available here: no project config root (.pi or .agents) was found above the cwd. Use agentScope: 'user' or run from inside a project.", true);
1383
1392
  }
@@ -1387,7 +1396,7 @@ function handleReset(params: ManagementParams, ctx: ManagementContext): AgentToo
1387
1396
  if (custom) {
1388
1397
  return result(`Agent '${raw}' has no bundled default to reset to. Use { action: "delete", agent: "${custom.name}" } to remove the custom ${custom.source} agent.`, true);
1389
1398
  }
1390
- return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx.cwd).join(", ") || "none"}.`, true);
1399
+ return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx).join(", ") || "none"}.`, true);
1391
1400
  }
1392
1401
  const runtimeName = bundled.name;
1393
1402
  const custom = (scope === "user" ? d.user : d.project).find((a) => a.name === raw || a.name === sanitized);
@@ -12,15 +12,17 @@
12
12
  * never collide with the owner's `~/.pi/agent/memory/{project}/` system.
13
13
  */
14
14
 
15
+ import { spawnSync } from "node:child_process";
15
16
  import * as fs from "node:fs";
16
17
  import * as path from "node:path";
17
18
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
18
- import { findNearestProjectRoot, type AgentConfig, type AgentMemoryConfig } from "./agents.ts";
19
+ import { findNearestGitRoot, findNearestProjectRoot, type AgentConfig, type AgentMemoryConfig } from "./agents.ts";
19
20
 
20
21
  export const AGENT_MEMORY_DIR_NAME = "agent-memory";
21
22
  export const AGENT_MEMORY_FILE = "MEMORY.md";
22
23
  export const MAX_MEMORY_LINES = 200;
23
24
  const MAX_MEMORY_BYTES = 16 * 1024;
25
+ const MAX_GITDIR_FILE_BYTES = 4 * 1024;
24
26
 
25
27
  const WRITE_TOOLS = new Set(["edit", "write", "bash"]);
26
28
 
@@ -70,6 +72,91 @@ function isWithin(child: string, parent: string): boolean {
70
72
  return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
71
73
  }
72
74
 
75
+ function comparablePath(candidate: string): string {
76
+ let canonical: string;
77
+ try {
78
+ canonical = fs.realpathSync.native(candidate);
79
+ } catch {
80
+ canonical = fs.realpathSync(candidate);
81
+ }
82
+ const normalized = path.normalize(canonical);
83
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
84
+ }
85
+
86
+ function samePath(left: string, right: string): boolean {
87
+ if (comparablePath(left) === comparablePath(right)) return true;
88
+ if (process.platform !== "win32") return false;
89
+ // Git for Windows and Node can spell the same temp path through different
90
+ // drive or 8.3 aliases, so use filesystem identity as the fail-closed fallback.
91
+ const leftStat = fs.statSync(left);
92
+ const rightStat = fs.statSync(right);
93
+ return leftStat.dev !== 0 && leftStat.ino !== 0 && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
94
+ }
95
+
96
+ function readBoundedRegularFile(file: string): string | undefined {
97
+ const stat = fs.lstatSync(file);
98
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_GITDIR_FILE_BYTES) return undefined;
99
+ return fs.readFileSync(file, "utf8");
100
+ }
101
+
102
+ function gitConfirmsWorktree(projectRoot: string, commonGitDir: string): boolean {
103
+ const result = spawnSync("git", ["-C", projectRoot, "rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel"], {
104
+ encoding: "utf8",
105
+ timeout: 2_000,
106
+ maxBuffer: MAX_GITDIR_FILE_BYTES * 2,
107
+ windowsHide: true,
108
+ });
109
+ if (result.status !== 0) return false;
110
+ const lines = result.stdout.trim().split(/\r?\n/);
111
+ if (lines.length !== 2) return false;
112
+ try {
113
+ return samePath(lines[0]!, commonGitDir) && samePath(lines[1]!, projectRoot);
114
+ } catch {
115
+ return false;
116
+ }
117
+ }
118
+
119
+ function resolveLinkedWorktreeMain(worktreeRoot: string): string {
120
+ const marker = path.join(worktreeRoot, ".git");
121
+ try {
122
+ const gitdir = readBoundedRegularFile(marker)?.match(/^gitdir:\s*(.+?)\s*$/m)?.[1];
123
+ if (!gitdir) return worktreeRoot;
124
+ const worktreeGitDir = fs.realpathSync(path.resolve(worktreeRoot, gitdir));
125
+ const backlink = readBoundedRegularFile(path.join(worktreeGitDir, "gitdir"))?.trim();
126
+ if (!backlink || !samePath(path.resolve(worktreeGitDir, backlink), marker)) return worktreeRoot;
127
+ const worktreesDir = path.dirname(worktreeGitDir);
128
+ const commonGitDir = path.dirname(worktreesDir);
129
+ if (path.basename(worktreesDir) !== "worktrees" || path.basename(commonGitDir) !== ".git") return worktreeRoot;
130
+ const main = fs.realpathSync(path.dirname(commonGitDir));
131
+ const commonStat = fs.lstatSync(commonGitDir);
132
+ if (commonStat.isSymbolicLink() || !commonStat.isDirectory()) return worktreeRoot;
133
+ const relativeGitDir = path.relative(fs.realpathSync(commonGitDir), worktreeGitDir).split(path.sep);
134
+ return relativeGitDir.length === 2 && relativeGitDir[0] === "worktrees" && gitConfirmsWorktree(worktreeRoot, commonGitDir)
135
+ ? main
136
+ : worktreeRoot;
137
+ } catch {
138
+ return worktreeRoot;
139
+ }
140
+ }
141
+
142
+ /** Map the selected project path from a verified linked worktree onto the main checkout. */
143
+ function resolveProjectMemoryRoot(projectRoot: string): string {
144
+ const gitRoot = findNearestGitRoot(projectRoot);
145
+ if (!gitRoot) return projectRoot;
146
+ const main = resolveLinkedWorktreeMain(gitRoot);
147
+ try {
148
+ if (samePath(main, gitRoot)) return projectRoot;
149
+ const relativeProject = path.relative(fs.realpathSync(gitRoot), fs.realpathSync(projectRoot));
150
+ if (relativeProject.startsWith("..") || path.isAbsolute(relativeProject)) return projectRoot;
151
+ const mapped = path.resolve(main, relativeProject);
152
+ if (!fs.existsSync(mapped)) return mapped;
153
+ const canonical = fs.realpathSync(mapped);
154
+ return samePath(canonical, main) || isWithin(canonical, main) ? canonical : projectRoot;
155
+ } catch {
156
+ return projectRoot;
157
+ }
158
+ }
159
+
73
160
  /**
74
161
  * Resolve a memory directory under `rootDir` for the given scoped path.
75
162
  *
@@ -198,9 +285,9 @@ export function buildAgentMemoryInjection(agent: AgentConfig, cwd: string): stri
198
285
  if (memory.scope === "user") {
199
286
  rootDir = path.join(getAgentDir(), AGENT_MEMORY_DIR_NAME);
200
287
  } else {
201
- const projectRoot = findNearestProjectRoot(cwd);
288
+ const projectRoot = findNearestProjectRoot(cwd) ?? findNearestGitRoot(cwd);
202
289
  if (!projectRoot) return "";
203
- rootDir = path.join(getProjectConfigDir(projectRoot), AGENT_MEMORY_DIR_NAME);
290
+ rootDir = path.join(getProjectConfigDir(resolveProjectMemoryRoot(projectRoot)), AGENT_MEMORY_DIR_NAME);
204
291
  }
205
292
 
206
293
  const resolved = resolveMemoryDir(rootDir, memory.path);
@@ -12,6 +12,7 @@ export const KNOWN_FIELDS = new Set([
12
12
  "tools",
13
13
  "excludeTools",
14
14
  "allowNestedSubagents",
15
+ "allowedAgents",
15
16
  "model",
16
17
  "fast",
17
18
  "thinking",
@@ -40,7 +41,6 @@ export const KNOWN_FIELDS = new Set([
40
41
  "injectToContext",
41
42
  "interactive",
42
43
  "maxSubagentDepth",
43
- "completionGuard",
44
44
  "toolBudget",
45
45
  "sandbox",
46
46
  "permission-profile",
@@ -82,6 +82,9 @@ export function serializeAgent(config: AgentConfig, options: SerializeAgentOptio
82
82
  if (config.allowNestedSubagents === true || preserve("allowNestedSubagents")) {
83
83
  lines.push(`allowNestedSubagents: ${config.allowNestedSubagents === undefined ? "" : config.allowNestedSubagents ? "true" : "false"}`);
84
84
  }
85
+ if (config.allowedAgents !== undefined || preserve("allowedAgents")) {
86
+ lines.push(`allowedAgents: ${joinComma(config.allowedAgents) ?? ""}`);
87
+ }
85
88
 
86
89
  if (config.model || preserve("model")) lines.push(`model: ${config.model ?? ""}`);
87
90
  if (config.fast === true || preserve("fast")) lines.push(`fast: ${config.fast === undefined ? "" : config.fast ? "true" : "false"}`);
@@ -144,9 +147,6 @@ export function serializeAgent(config: AgentConfig, options: SerializeAgentOptio
144
147
  if (typeof maxSubagentDepth === "number" && Number.isInteger(maxSubagentDepth) && maxSubagentDepth >= 0) {
145
148
  lines.push(`maxSubagentDepth: ${maxSubagentDepth}`);
146
149
  }
147
- if (config.completionGuard === false || preserve("completionGuard")) {
148
- lines.push(`completionGuard: ${config.completionGuard === undefined ? "" : config.completionGuard ? "true" : "false"}`);
149
- }
150
150
  if (config.toolBudget || preserve("toolBudget")) {
151
151
  lines.push(`toolBudget: ${config.toolBudget ? JSON.stringify(config.toolBudget) : ""}`);
152
152
  }