@xzzpig/pi-subagents 0.7.0 → 0.9.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -2,11 +2,21 @@ import { createHash } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
+ import { findConfiguredProjectRoot } from "../../agents/agents.ts";
5
6
  import { getAgentDir, getProjectConfigDir } from "../../shared/utils.ts";
7
+ import { isMcpServerDefinition, loadAgentPluginMcpServers, loadPackageMcpServers, type McpServerDefinition } from "./mcp-config-sources.ts";
8
+ import {
9
+ normalizeMcpDirectToolSelectors,
10
+ parseMcpDirectToolSelectors,
11
+ planMcpDirectToolGrant,
12
+ } from "./mcp-direct-tool-grant.ts";
13
+ import type { McpToolPrefix, ResolvedMcpDirectToolSelection } from "./mcp-direct-tool-grant.ts";
14
+
15
+ export { formatUnresolvedMcpDirectToolSelectors } from "./mcp-direct-tool-grant.ts";
16
+ export type { ResolvedMcpDirectToolSelection } from "./mcp-direct-tool-grant.ts";
6
17
 
7
18
  const CACHE_VERSION = 1;
8
19
  const CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
9
- const BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls", "mcp"]);
10
20
  const GENERIC_GLOBAL_CONFIG_PATH = path.join(os.homedir(), ".config", "mcp", "mcp.json");
11
21
  const IMPORT_PATHS = {
12
22
  cursor: [path.join(os.homedir(), ".cursor", "mcp.json")],
@@ -21,39 +31,41 @@ const IMPORT_PATHS = {
21
31
  vscode: [".vscode/mcp.json"],
22
32
  } as const;
23
33
 
24
- type ToolPrefix = "server" | "none" | "short";
25
34
  type ImportKind = keyof typeof IMPORT_PATHS;
26
35
 
27
- interface ServerEntry {
28
- command?: string;
29
- args?: string[];
30
- socket?: string;
31
- env?: Record<string, string>;
32
- cwd?: string;
33
- url?: string;
34
- headers?: Record<string, string>;
35
- requestHeadersCommand?: {
36
- command: string;
37
- args?: string[];
38
- env?: Record<string, string>;
39
- timeoutMs?: number;
40
- };
41
- auth?: "oauth" | "bearer" | false;
42
- bearerToken?: string;
43
- bearerTokenEnv?: string;
44
- exposeResources?: boolean;
45
- includeTools?: string[];
46
- excludeTools?: string[];
47
- protocolVersion?: string;
48
- directTools?: boolean | string[];
49
- }
36
+ type ServerEntry = McpServerDefinition;
50
37
 
51
- interface McpConfig {
38
+ export interface McpConfig {
52
39
  mcpServers: Record<string, ServerEntry>;
53
40
  imports?: ImportKind[];
54
41
  settings?: {
55
- toolPrefix?: ToolPrefix;
42
+ toolPrefix?: McpToolPrefix;
56
43
  directTools?: boolean;
44
+ agentPluginPaths?: unknown;
45
+ };
46
+ }
47
+
48
+ export const MCP_RUNTIME_SNAPSHOT_EVENT = "pi-mcp-adapter:runtime-snapshot:v1" as const;
49
+ export const MCP_RUNTIME_SNAPSHOT_VERSION = 1 as const;
50
+
51
+ export interface McpRuntimeServerSnapshot {
52
+ readonly name: string;
53
+ readonly definition: ServerEntry;
54
+ readonly runtime: true;
55
+ readonly persisted: false;
56
+ }
57
+
58
+ interface McpRuntimeSnapshotRequest {
59
+ version: typeof MCP_RUNTIME_SNAPSHOT_VERSION;
60
+ name: string;
61
+ result?:
62
+ | { ok: true; snapshot: McpRuntimeServerSnapshot }
63
+ | { ok: false; error: Error };
64
+ }
65
+
66
+ export interface McpRuntimeSnapshotHost {
67
+ events: {
68
+ emit(event: string, request: McpRuntimeSnapshotRequest): void;
57
69
  };
58
70
  }
59
71
 
@@ -78,19 +90,60 @@ interface MetadataCache {
78
90
  servers: Record<string, ServerCacheEntry>;
79
91
  }
80
92
 
81
- export interface ResolvedMcpDirectToolSelection { name: string; selector: string }
82
-
83
- export function resolveMcpDirectToolSelections(mcpDirectTools: string[] | undefined, cwd = process.cwd()): ResolvedMcpDirectToolSelection[] {
84
- if (!mcpDirectTools?.length) return [];
85
-
86
- try {
87
- const config = loadMcpConfig(cwd);
88
- const cache = loadMetadataCache();
89
- if (!cache) return [];
90
- return resolveDirectToolSelections(config, cache, getToolPrefix(config.settings?.toolPrefix), mcpDirectTools);
91
- } catch {
92
- return [];
93
+ export interface McpDirectToolResolution {
94
+ selections: ResolvedMcpDirectToolSelection[];
95
+ unresolvedSelectors: string[];
96
+ /** Normal loaded config plus the selected runtime server definitions. */
97
+ mcpConfig?: McpConfig;
98
+ runtimeServerNames?: string[];
99
+ }
100
+
101
+ export function resolveMcpDirectToolResolution(
102
+ mcpDirectTools: string[] | undefined,
103
+ cwd = process.cwd(),
104
+ runtimeSnapshotHost?: McpRuntimeSnapshotHost,
105
+ configOverride?: McpConfig,
106
+ ): McpDirectToolResolution {
107
+ const selectors = normalizeMcpDirectToolSelectors(mcpDirectTools);
108
+ if (selectors.length === 0) return { selections: [], unresolvedSelectors: [] };
109
+
110
+ const config = configOverride ?? loadMcpConfig(cwd);
111
+ const { servers: selectedServers, tools: selectedTools } = parseMcpDirectToolSelectors(selectors);
112
+ const runtimeSelectionServers = new Set([...selectedServers, ...selectedTools.keys()]);
113
+ const runtimeServers = resolveRuntimeMcpServers(config, runtimeSelectionServers, runtimeSnapshotHost);
114
+ const resolvedConfig = Object.keys(runtimeServers).length > 0
115
+ ? mergeConfigs(config, { mcpServers: runtimeServers })
116
+ : config;
117
+ validateSelectedServerDefinitions(resolvedConfig, selectors);
118
+ const runtime = Object.keys(runtimeServers).length > 0
119
+ ? { mcpConfig: resolvedConfig, runtimeServerNames: Object.keys(runtimeServers) }
120
+ : {};
121
+ const cache = loadMetadataCache();
122
+ if (!cache) return { selections: [], unresolvedSelectors: selectors, ...runtime };
123
+ const validMetadata: Record<string, ServerCacheEntry> = {};
124
+ for (const [serverName, definition] of Object.entries(resolvedConfig.mcpServers)) {
125
+ const serverCache = cache.servers[serverName];
126
+ if (isServerCacheValid(serverCache, definition)) validMetadata[serverName] = serverCache;
93
127
  }
128
+ const grant = planMcpDirectToolGrant({
129
+ selectors,
130
+ servers: resolvedConfig.mcpServers,
131
+ metadata: validMetadata,
132
+ toolPrefix: resolvedConfig.settings?.toolPrefix,
133
+ });
134
+ return {
135
+ selections: grant.selections,
136
+ unresolvedSelectors: grant.unresolvedSelectors,
137
+ ...runtime,
138
+ };
139
+ }
140
+
141
+ export function resolveMcpDirectToolSelections(
142
+ mcpDirectTools: string[] | undefined,
143
+ cwd = process.cwd(),
144
+ runtimeSnapshotHost?: McpRuntimeSnapshotHost,
145
+ ): ResolvedMcpDirectToolSelection[] {
146
+ return resolveMcpDirectToolResolution(mcpDirectTools, cwd, runtimeSnapshotHost).selections;
94
147
  }
95
148
 
96
149
  function loadMetadataCache(): MetadataCache | null {
@@ -102,28 +155,116 @@ function loadMetadataCache(): MetadataCache | null {
102
155
  return null;
103
156
  }
104
157
 
105
- if (!parsed || typeof parsed !== "object") return null;
106
- const raw = parsed as Record<string, unknown>;
107
- if (raw.version !== CACHE_VERSION || !raw.servers || typeof raw.servers !== "object" || Array.isArray(raw.servers)) {
108
- return null;
158
+ if (!isRecord(parsed) || parsed.version !== CACHE_VERSION || !isRecord(parsed.servers)) return null;
159
+ const servers: Record<string, ServerCacheEntry> = {};
160
+ for (const [name, value] of Object.entries(parsed.servers)) {
161
+ const entry = parseServerCacheEntry(value);
162
+ if (entry) servers[name] = entry;
163
+ }
164
+ return { version: CACHE_VERSION, servers };
165
+ }
166
+
167
+ function parseServerCacheEntry(value: unknown): ServerCacheEntry | undefined {
168
+ if (!isRecord(value)) return undefined;
169
+ if (value.configHash !== undefined && typeof value.configHash !== "string") return undefined;
170
+ if (value.cachedAt !== undefined && (typeof value.cachedAt !== "number" || !Number.isFinite(value.cachedAt))) return undefined;
171
+ if (value.tools !== undefined && !Array.isArray(value.tools)) return undefined;
172
+ if (value.resources !== undefined && !Array.isArray(value.resources)) return undefined;
173
+ const tools = value.tools?.map(parseCachedTool);
174
+ const resources = value.resources?.map(parseCachedResource);
175
+ if (tools && !tools.every((entry): entry is CachedTool => entry !== undefined)) return undefined;
176
+ if (resources && !resources.every((entry): entry is CachedResource => entry !== undefined)) return undefined;
177
+ return {
178
+ ...(value.configHash !== undefined ? { configHash: value.configHash } : {}),
179
+ ...(value.cachedAt !== undefined ? { cachedAt: value.cachedAt } : {}),
180
+ ...(tools ? { tools } : {}),
181
+ ...(resources ? { resources } : {}),
182
+ };
183
+ }
184
+
185
+ function parseCachedTool(value: unknown): CachedTool | undefined {
186
+ if (!isRecord(value) || (value.name !== undefined && typeof value.name !== "string")) return undefined;
187
+ return value.name === undefined ? {} : { name: value.name };
188
+ }
189
+
190
+ function parseCachedResource(value: unknown): CachedResource | undefined {
191
+ if (!isRecord(value)) return undefined;
192
+ if (value.uri !== undefined && typeof value.uri !== "string") return undefined;
193
+ if (value.name !== undefined && typeof value.name !== "string") return undefined;
194
+ return {
195
+ ...(value.uri !== undefined ? { uri: value.uri } : {}),
196
+ ...(value.name !== undefined ? { name: value.name } : {}),
197
+ };
198
+ }
199
+
200
+ function resolveRuntimeMcpServers(
201
+ config: McpConfig,
202
+ selectedServers: ReadonlySet<string>,
203
+ runtimeSnapshotHost: McpRuntimeSnapshotHost | undefined,
204
+ ): Record<string, ServerEntry> {
205
+ if (!runtimeSnapshotHost) return {};
206
+ const runtimeServers: Record<string, ServerEntry> = {};
207
+ for (const serverName of selectedServers) {
208
+ if (Object.hasOwn(config.mcpServers, serverName)) continue;
209
+ try {
210
+ const snapshot = getRuntimeMcpServerSnapshot(runtimeSnapshotHost, serverName);
211
+ runtimeServers[serverName] = snapshot.definition;
212
+ } catch {
213
+ // Missing, disposed, or shadowed runtime servers remain unresolved below.
214
+ }
215
+ }
216
+ return runtimeServers;
217
+ }
218
+
219
+ function getRuntimeMcpServerSnapshot(
220
+ host: McpRuntimeSnapshotHost,
221
+ name: string,
222
+ ): McpRuntimeServerSnapshot {
223
+ const request: McpRuntimeSnapshotRequest = {
224
+ version: MCP_RUNTIME_SNAPSHOT_VERSION,
225
+ name,
226
+ };
227
+ host.events.emit(MCP_RUNTIME_SNAPSHOT_EVENT, request);
228
+ if (!request.result) throw new Error("pi-mcp-adapter is not installed for this Pi instance");
229
+ if (!request.result.ok) throw request.result.error;
230
+ const snapshot = request.result.snapshot;
231
+ if (
232
+ !snapshot ||
233
+ snapshot.name !== name ||
234
+ snapshot.runtime !== true ||
235
+ snapshot.persisted !== false ||
236
+ !isMcpServerDefinition(snapshot.definition)
237
+ ) {
238
+ throw new Error(`Invalid MCP runtime snapshot for server "${name}"`);
109
239
  }
110
- return raw as unknown as MetadataCache;
240
+ return snapshot;
111
241
  }
112
242
 
113
243
  function loadMcpConfig(cwd: string): McpConfig {
244
+ const resolvedCwd = path.resolve(cwd);
245
+ const projectRoot = findConfiguredProjectRoot(resolvedCwd) ?? resolvedCwd;
114
246
  let config: McpConfig = { mcpServers: {} };
115
- for (const sourcePath of getConfigPaths(cwd)) {
247
+ for (const sourcePath of getConfigPaths(projectRoot)) {
116
248
  const loaded = readConfig(sourcePath);
117
249
  if (!loaded) continue;
118
- config = mergeConfigs(config, expandImports(loaded, cwd));
250
+ config = mergeConfigs(config, expandImports(loaded, projectRoot));
119
251
  }
120
- return config;
252
+
253
+ const packageServers = loadPackageMcpServers(projectRoot);
254
+ const pluginServers = loadAgentPluginMcpServers(config.settings?.agentPluginPaths, projectRoot);
255
+ const packageOnlyServers = Object.fromEntries(
256
+ Object.entries(packageServers).filter(([name]) => !Object.hasOwn(pluginServers, name)),
257
+ );
258
+ return mergeConfigs(
259
+ { mcpServers: packageOnlyServers },
260
+ mergeConfigs({ mcpServers: pluginServers }, config),
261
+ );
121
262
  }
122
263
 
123
- function getConfigPaths(cwd: string): string[] {
264
+ function getConfigPaths(projectRoot: string): string[] {
124
265
  const piGlobalPath = path.join(getAgentDir(), "mcp.json");
125
- const projectPath = path.resolve(cwd, ".mcp.json");
126
- const projectPiPath = path.resolve(getProjectConfigDir(cwd), "mcp.json");
266
+ const projectPath = path.resolve(projectRoot, ".mcp.json");
267
+ const projectPiPath = path.resolve(getProjectConfigDir(projectRoot), "mcp.json");
127
268
  const sources: string[] = [];
128
269
  if (GENERIC_GLOBAL_CONFIG_PATH !== piGlobalPath) sources.push(GENERIC_GLOBAL_CONFIG_PATH);
129
270
  sources.push(piGlobalPath);
@@ -143,18 +284,33 @@ function readConfig(configPath: string): McpConfig | null {
143
284
  }
144
285
 
145
286
  function validateConfig(raw: unknown): McpConfig {
146
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { mcpServers: {} };
147
- const obj = raw as Record<string, unknown>;
287
+ if (!isRecord(raw)) return { mcpServers: {} };
288
+ const obj = raw;
148
289
  const servers = obj.mcpServers ?? obj["mcp-servers"] ?? {};
149
290
  return {
150
- mcpServers: servers && typeof servers === "object" && !Array.isArray(servers) ? servers as Record<string, ServerEntry> : {},
291
+ mcpServers: parseServerEntries(servers),
151
292
  imports: Array.isArray(obj.imports) ? obj.imports.filter((value): value is ImportKind => isImportKind(value)) : undefined,
152
- settings: obj.settings && typeof obj.settings === "object" && !Array.isArray(obj.settings)
153
- ? obj.settings as McpConfig["settings"]
154
- : undefined,
293
+ settings: parseSettings(obj.settings),
155
294
  };
156
295
  }
157
296
 
297
+ function parseServerEntries(value: unknown): Record<string, ServerEntry> {
298
+ if (!isRecord(value)) return {};
299
+ return Object.fromEntries(Object.entries(value).filter((entry): entry is [string, ServerEntry] => isMcpServerDefinition(entry[1])));
300
+ }
301
+
302
+ function parseSettings(value: unknown): McpConfig["settings"] | undefined {
303
+ if (!isRecord(value)) return undefined;
304
+ const toolPrefix = value.toolPrefix === "server" || value.toolPrefix === "short" || value.toolPrefix === "none" ? value.toolPrefix : undefined;
305
+ const directTools = typeof value.directTools === "boolean" ? value.directTools : undefined;
306
+ const settings: NonNullable<McpConfig["settings"]> = {
307
+ ...(toolPrefix ? { toolPrefix } : {}),
308
+ ...(directTools !== undefined ? { directTools } : {}),
309
+ ...(value.agentPluginPaths !== undefined ? { agentPluginPaths: value.agentPluginPaths } : {}),
310
+ };
311
+ return Object.keys(settings).length ? settings : undefined;
312
+ }
313
+
158
314
  function mergeConfigs(base: McpConfig, next: McpConfig): McpConfig {
159
315
  const imports = [...(base.imports ?? []), ...(next.imports ?? [])];
160
316
  return {
@@ -198,76 +354,24 @@ function resolveImportPath(importKind: ImportKind, cwd: string): string | null {
198
354
  }
199
355
 
200
356
  function extractServers(config: unknown, kind: ImportKind): Record<string, ServerEntry> {
201
- if (!config || typeof config !== "object" || Array.isArray(config)) return {};
202
- const obj = config as Record<string, unknown>;
357
+ if (!isRecord(config)) return {};
358
+ const obj = config;
203
359
  const servers = kind === "cursor" || kind === "windsurf" || kind === "vscode"
204
360
  ? obj.mcpServers ?? obj["mcp-servers"]
205
361
  : obj.mcpServers;
206
- return servers && typeof servers === "object" && !Array.isArray(servers) ? servers as Record<string, ServerEntry> : {};
207
- }
208
-
209
- function resolveDirectToolSelections(config: McpConfig, cache: MetadataCache, prefix: ToolPrefix, envOverride: string[]): ResolvedMcpDirectToolSelection[] {
210
- const names: ResolvedMcpDirectToolSelection[] = [];
211
- const seenNames = new Set<string>();
212
- const { servers: selectedServers, tools: selectedTools } = parseSelections(envOverride);
213
-
214
- for (const [serverName, definition] of Object.entries(config.mcpServers)) {
215
- const serverCache = cache.servers[serverName];
216
- if (!isServerCacheValid(serverCache, definition)) continue;
217
-
218
- const toolFilter = selectedServers.has(serverName)
219
- ? true
220
- : selectedTools.get(serverName);
221
- if (!toolFilter) continue;
222
-
223
- for (const tool of Array.isArray(serverCache.tools) ? serverCache.tools : []) {
224
- if (typeof tool?.name !== "string" || !tool.name) continue;
225
- if (toolFilter !== true && !toolFilter.has(tool.name)) continue;
226
- if (isToolExcluded(tool.name, serverName, prefix, definition.excludeTools)) continue;
227
- const prefixedName = formatToolName(tool.name, serverName, prefix);
228
- if (BUILTIN_TOOL_NAMES.has(prefixedName) || seenNames.has(prefixedName)) continue;
229
- seenNames.add(prefixedName);
230
- names.push({ name: prefixedName, selector: `${serverName}/${tool.name}` });
231
- }
232
-
233
- if (definition.exposeResources === false) continue;
234
- for (const resource of Array.isArray(serverCache.resources) ? serverCache.resources : []) {
235
- if (typeof resource?.name !== "string" || !resource.name || typeof resource.uri !== "string" || !resource.uri) continue;
236
- const baseName = `get_${resourceNameToToolName(resource.name)}`;
237
- if (toolFilter !== true && !toolFilter.has(baseName)) continue;
238
- if (isToolExcluded(baseName, serverName, prefix, definition.excludeTools)) continue;
239
- const prefixedName = formatToolName(baseName, serverName, prefix);
240
- if (BUILTIN_TOOL_NAMES.has(prefixedName) || seenNames.has(prefixedName)) continue;
241
- seenNames.add(prefixedName);
242
- names.push({ name: prefixedName, selector: `${serverName}/${baseName}` });
243
- }
244
- }
245
-
246
- return names;
362
+ return parseServerEntries(servers);
247
363
  }
248
364
 
249
365
  export function resolveMcpDirectToolNames(mcpDirectTools: string[] | undefined, cwd = process.cwd()): string[] {
250
366
  return resolveMcpDirectToolSelections(mcpDirectTools, cwd).map((selection) => selection.name);
251
367
  }
252
368
 
253
- function parseSelections(selections: string[]): { servers: Set<string>; tools: Map<string, Set<string>> } {
254
- const servers = new Set<string>();
255
- const tools = new Map<string, Set<string>>();
256
- for (let item of selections) {
257
- item = item.replace(/\/+$/, "");
258
- if (item.includes("/")) {
259
- const [server, tool] = item.split("/", 2);
260
- if (server && tool) {
261
- if (!tools.has(server)) tools.set(server, new Set());
262
- tools.get(server)!.add(tool);
263
- } else if (server) {
264
- servers.add(server);
265
- }
266
- } else if (item) {
267
- servers.add(item);
268
- }
369
+ function validateSelectedServerDefinitions(config: McpConfig, selectors: string[]): void {
370
+ const { servers, tools } = parseMcpDirectToolSelectors(selectors);
371
+ for (const serverName of new Set([...servers, ...tools.keys()])) {
372
+ const definition = config.mcpServers[serverName];
373
+ if (definition) computeMcpServerHash(definition);
269
374
  }
270
- return { servers, tools };
271
375
  }
272
376
 
273
377
  function isServerCacheValid(entry: ServerCacheEntry | undefined, definition: ServerEntry): entry is ServerCacheEntry {
@@ -304,52 +408,12 @@ export function computeMcpServerHash(definition: ServerEntry): string {
304
408
  return createHash("sha256").update(stableStringify(identity)).digest("hex");
305
409
  }
306
410
 
307
- function getToolPrefix(value: unknown): ToolPrefix {
308
- return value === "none" || value === "short" || value === "server" ? value : "server";
309
- }
310
-
311
411
  function isImportKind(value: unknown): value is ImportKind {
312
412
  return typeof value === "string" && Object.hasOwn(IMPORT_PATHS, value);
313
413
  }
314
414
 
315
- function getServerPrefix(serverName: string, mode: ToolPrefix): string {
316
- if (mode === "none") return "";
317
- if (mode === "short") {
318
- const short = serverName.replace(/-?mcp$/i, "").replace(/-/g, "_");
319
- return short || "mcp";
320
- }
321
- return serverName.replace(/-/g, "_");
322
- }
323
-
324
- function formatToolName(toolName: string, serverName: string, prefix: ToolPrefix): string {
325
- const serverPrefix = getServerPrefix(serverName, prefix);
326
- return serverPrefix ? `${serverPrefix}_${toolName}` : toolName;
327
- }
328
-
329
- function isToolExcluded(toolName: string, serverName: string, prefix: ToolPrefix, excludeTools: unknown): boolean {
330
- if (!Array.isArray(excludeTools) || excludeTools.length === 0) return false;
331
- const candidates = new Set([
332
- normalizeToolName(toolName),
333
- normalizeToolName(formatToolName(toolName, serverName, prefix)),
334
- normalizeToolName(formatToolName(toolName, serverName, "server")),
335
- normalizeToolName(formatToolName(toolName, serverName, "short")),
336
- ]);
337
- return excludeTools.some((excluded) => typeof excluded === "string" && candidates.has(normalizeToolName(excluded)));
338
- }
339
-
340
- function normalizeToolName(value: string): string {
341
- return value.replace(/-/g, "_");
342
- }
343
-
344
- function resourceNameToToolName(name: string): string {
345
- let result = name
346
- .replace(/[^a-zA-Z0-9]/g, "_")
347
- .replace(/_+/g, "_")
348
- .replace(/^_+/, "")
349
- .replace(/_+$/, "")
350
- .toLowerCase();
351
- if (!result || /^\d/.test(result)) result = `resource${result ? `_${result}` : ""}`;
352
- return result;
415
+ function isRecord(value: unknown): value is Record<string, unknown> {
416
+ return value !== null && typeof value === "object" && !Array.isArray(value);
353
417
  }
354
418
 
355
419
  function interpolateEnvRecord(values: Record<string, string> | undefined): Record<string, string> | undefined {
@@ -0,0 +1,194 @@
1
+ const BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls", "mcp"]);
2
+
3
+ export type McpToolPrefix = "server" | "none" | "short";
4
+
5
+ export interface McpGrantServerFacts {
6
+ readonly exposeResources?: boolean;
7
+ readonly includeTools?: readonly unknown[];
8
+ readonly excludeTools?: readonly unknown[];
9
+ }
10
+
11
+ export interface McpGrantToolMetadata {
12
+ readonly name?: string;
13
+ }
14
+
15
+ export interface McpGrantResourceMetadata {
16
+ readonly name?: string;
17
+ readonly uri?: string;
18
+ }
19
+
20
+ export interface McpGrantServerMetadata {
21
+ readonly tools?: readonly McpGrantToolMetadata[];
22
+ readonly resources?: readonly McpGrantResourceMetadata[];
23
+ }
24
+
25
+ export interface McpDirectToolGrantInput {
26
+ readonly selectors?: readonly string[];
27
+ readonly servers: Readonly<Record<string, McpGrantServerFacts>>;
28
+ /** Cache entries already validated by the source-loading adapter. */
29
+ readonly metadata: Readonly<Record<string, McpGrantServerMetadata>>;
30
+ readonly toolPrefix?: unknown;
31
+ }
32
+
33
+ export interface ResolvedMcpDirectToolSelection {
34
+ name: string;
35
+ selector: string;
36
+ }
37
+
38
+ export interface McpDirectToolGrant {
39
+ selections: ResolvedMcpDirectToolSelection[];
40
+ unresolvedSelectors: string[];
41
+ }
42
+
43
+ export function normalizeMcpDirectToolSelectors(selectors: readonly string[] | undefined): string[] {
44
+ return [...new Set((selectors ?? []).map((selector) => selector.replace(/\/+$/, "")).filter(Boolean))];
45
+ }
46
+
47
+ export function parseMcpDirectToolSelectors(selectors: readonly string[]): {
48
+ servers: Set<string>;
49
+ tools: Map<string, Set<string>>;
50
+ } {
51
+ const servers = new Set<string>();
52
+ const tools = new Map<string, Set<string>>();
53
+ for (const item of selectors) {
54
+ if (item.includes("/")) {
55
+ const [server, tool] = item.split("/", 2);
56
+ if (server && tool) {
57
+ if (!tools.has(server)) tools.set(server, new Set());
58
+ tools.get(server)!.add(tool);
59
+ } else if (server) {
60
+ servers.add(server);
61
+ }
62
+ } else if (item) {
63
+ servers.add(item);
64
+ }
65
+ }
66
+ return { servers, tools };
67
+ }
68
+
69
+ export function planMcpDirectToolGrant(input: McpDirectToolGrantInput): McpDirectToolGrant {
70
+ const selectors = normalizeMcpDirectToolSelectors(input.selectors);
71
+ if (selectors.length === 0) return { selections: [], unresolvedSelectors: [] };
72
+
73
+ const { servers: selectedServers, tools: selectedTools } = parseMcpDirectToolSelectors(selectors);
74
+ const selections: ResolvedMcpDirectToolSelection[] = [];
75
+ const seenNames = new Set<string>();
76
+ const prefix = normalizeMcpToolPrefix(input.toolPrefix);
77
+
78
+ for (const [serverName, server] of Object.entries(input.servers)) {
79
+ const metadata = input.metadata[serverName];
80
+ if (!metadata) continue;
81
+
82
+ const toolFilter: true | ReadonlySet<string> | undefined = selectedServers.has(serverName)
83
+ ? true
84
+ : selectedTools.get(serverName);
85
+ if (!toolFilter) continue;
86
+
87
+ for (const tool of Array.isArray(metadata.tools) ? metadata.tools : []) {
88
+ if (typeof tool?.name !== "string" || !tool.name) continue;
89
+ if (toolFilter !== true && !toolFilter.has(tool.name)) continue;
90
+ if (!isToolAllowed(tool.name, serverName, prefix, server.includeTools, server.excludeTools)) continue;
91
+ const name = formatToolName(tool.name, serverName, prefix);
92
+ if (BUILTIN_TOOL_NAMES.has(name) || seenNames.has(name)) continue;
93
+ seenNames.add(name);
94
+ selections.push({ name, selector: `${serverName}/${tool.name}` });
95
+ }
96
+
97
+ if (server.exposeResources === false) continue;
98
+ for (const resource of Array.isArray(metadata.resources) ? metadata.resources : []) {
99
+ if (typeof resource?.name !== "string" || !resource.name || typeof resource.uri !== "string" || !resource.uri) continue;
100
+ const baseName = `get_${resourceNameToToolName(resource.name)}`;
101
+ if (toolFilter !== true && !toolFilter.has(baseName)) continue;
102
+ if (!isToolAllowed(baseName, serverName, prefix, server.includeTools, server.excludeTools)) continue;
103
+ const name = formatToolName(baseName, serverName, prefix);
104
+ if (BUILTIN_TOOL_NAMES.has(name) || seenNames.has(name)) continue;
105
+ seenNames.add(name);
106
+ selections.push({ name, selector: `${serverName}/${baseName}` });
107
+ }
108
+ }
109
+
110
+ const unresolvedSelectors = selectors.filter((selector) =>
111
+ selector.includes("/")
112
+ ? !selections.some((selection) => selection.selector === selector)
113
+ : !selections.some((selection) => selection.selector.startsWith(`${selector}/`)),
114
+ );
115
+ return { selections, unresolvedSelectors };
116
+ }
117
+
118
+ export function normalizeMcpToolPrefix(value: unknown): McpToolPrefix {
119
+ return value === "none" || value === "short" || value === "server" ? value : "server";
120
+ }
121
+
122
+ export function formatUnresolvedMcpDirectToolSelectors(selectors: readonly string[]): string {
123
+ return `Unresolved MCP direct-tool selectors: ${selectors.join(", ")}. Direct MCP tools require a matching configured server and fresh metadata cache; runtime-registered servers require a host/pi-mcp-adapter handoff before child launch.`;
124
+ }
125
+
126
+ function getServerPrefix(serverName: string, mode: McpToolPrefix): string {
127
+ if (mode === "none") return "";
128
+ if (mode === "short") return serverName.replace(/-?mcp$/i, "") || "mcp";
129
+ return serverName;
130
+ }
131
+
132
+ function formatToolName(toolName: string, serverName: string, prefix: McpToolPrefix): string {
133
+ const serverPrefix = getServerPrefix(serverName, prefix);
134
+ return serverPrefix ? `${serverPrefix}_${toolName}` : toolName;
135
+ }
136
+
137
+ function isToolAllowed(
138
+ toolName: string,
139
+ serverName: string,
140
+ prefix: McpToolPrefix,
141
+ includeTools: readonly unknown[] | undefined,
142
+ excludeTools: readonly unknown[] | undefined,
143
+ ): boolean {
144
+ const candidates = toolNameCandidates(toolName, serverName, prefix);
145
+ return (!Array.isArray(includeTools) || includeTools.length === 0 || matchesToolPatterns(candidates, includeTools))
146
+ && !matchesToolPatterns(candidates, excludeTools);
147
+ }
148
+
149
+ function toolNameCandidates(toolName: string, serverName: string, prefix: McpToolPrefix): Set<string> {
150
+ return new Set([
151
+ toolName,
152
+ `mcp_${toolName}`,
153
+ formatToolName(toolName, serverName, prefix),
154
+ formatToolName(toolName, serverName, "server"),
155
+ formatToolName(toolName, serverName, "short"),
156
+ formatToolName(toolName, serverName, "none"),
157
+ ]);
158
+ }
159
+
160
+ function matchesToolPatterns(candidates: ReadonlySet<string>, patterns: readonly unknown[] | undefined): boolean {
161
+ if (!Array.isArray(patterns) || patterns.length === 0) return false;
162
+ for (const pattern of patterns) {
163
+ if (typeof pattern !== "string") continue;
164
+ const normalizedPattern = normalizeToolName(pattern);
165
+ const matcher = normalizedPattern.includes("*") || normalizedPattern.includes("?")
166
+ ? globToRegExp(normalizedPattern)
167
+ : undefined;
168
+ for (const candidate of candidates) {
169
+ const normalizedCandidate = normalizeToolName(candidate);
170
+ if (matcher ? matcher.test(normalizedCandidate) : normalizedCandidate === normalizedPattern) return true;
171
+ }
172
+ }
173
+ return false;
174
+ }
175
+
176
+ function globToRegExp(pattern: string): RegExp {
177
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
178
+ return new RegExp(`^${escaped}$`);
179
+ }
180
+
181
+ function normalizeToolName(value: string): string {
182
+ return value.replace(/-/g, "_");
183
+ }
184
+
185
+ function resourceNameToToolName(name: string): string {
186
+ let result = name
187
+ .replace(/[^a-zA-Z0-9]/g, "_")
188
+ .replace(/_+/g, "_")
189
+ .replace(/^_+/, "")
190
+ .replace(/_+$/, "")
191
+ .toLowerCase();
192
+ if (!result || /^\d/.test(result)) result = `resource${result ? `_${result}` : ""}`;
193
+ return result;
194
+ }