@ftrdotdev/pi-delegates 0.0.0-stage → 0.1.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 (116) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +57 -0
  4. package/README.md +448 -2
  5. package/ROADMAP.md +158 -0
  6. package/TESTING.md +1061 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +93 -4
  12. package/skills/pi-delegates/SKILL.md +147 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +156 -0
  17. package/src/domain/definitions.test.ts +41 -0
  18. package/src/domain/definitions.ts +161 -0
  19. package/src/domain/ids.ts +13 -0
  20. package/src/domain/names.ts +35 -0
  21. package/src/domain/orchestration/admission.ts +78 -0
  22. package/src/domain/orchestration/control.test.ts +1298 -0
  23. package/src/domain/orchestration/control.ts +436 -0
  24. package/src/domain/orchestration/fanout.test.ts +419 -0
  25. package/src/domain/orchestration/fanout.ts +334 -0
  26. package/src/domain/orchestration/gates.test.ts +686 -0
  27. package/src/domain/orchestration/gates.ts +360 -0
  28. package/src/domain/orchestration/launch.test.ts +173 -0
  29. package/src/domain/orchestration/launch.ts +581 -0
  30. package/src/domain/orchestration/requests.test.ts +700 -0
  31. package/src/domain/orchestration/requests.ts +769 -0
  32. package/src/domain/orchestration/review.test.ts +214 -0
  33. package/src/domain/orchestration/review.ts +168 -0
  34. package/src/domain/orchestration/run-wait.test.ts +262 -0
  35. package/src/domain/orchestration/run-wait.ts +256 -0
  36. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  37. package/src/domain/orchestration/workflow-section.ts +99 -0
  38. package/src/domain/orchestration/workflow.test.ts +1425 -0
  39. package/src/domain/orchestration/workflow.ts +705 -0
  40. package/src/domain/run-records.test.ts +27 -0
  41. package/src/domain/run-records.ts +527 -0
  42. package/src/domain/shapes.test.ts +165 -0
  43. package/src/domain/skills.test.ts +466 -0
  44. package/src/domain/skills.ts +97 -0
  45. package/src/domain/tool-schema.test.ts +46 -0
  46. package/src/domain/tool-schema.ts +20 -0
  47. package/src/domain/toolkit.test.ts +201 -0
  48. package/src/domain/toolkit.ts +379 -0
  49. package/src/domain/view.test.ts +739 -0
  50. package/src/domain/view.ts +459 -0
  51. package/src/example.test.ts +15 -0
  52. package/src/extension/commands.test.ts +481 -0
  53. package/src/extension/commands.ts +227 -0
  54. package/src/extension/entry.test.ts +1118 -0
  55. package/src/extension/entry.ts +342 -0
  56. package/src/extension/gate-alerts.test.ts +235 -0
  57. package/src/extension/gate-alerts.ts +143 -0
  58. package/src/extension/guard.test.ts +48 -0
  59. package/src/extension/guard.ts +31 -0
  60. package/src/extension/host-signals.test.ts +20 -0
  61. package/src/extension/host-signals.ts +13 -0
  62. package/src/extension/inspector-command.test.ts +1191 -0
  63. package/src/extension/inspector-command.ts +638 -0
  64. package/src/extension/prompt.test.ts +110 -0
  65. package/src/extension/prompt.ts +50 -0
  66. package/src/extension/request-alerts.test.ts +183 -0
  67. package/src/extension/request-alerts.ts +181 -0
  68. package/src/extension/revocation.test.ts +81 -0
  69. package/src/extension/revocation.ts +84 -0
  70. package/src/extension/shortcut.test.ts +64 -0
  71. package/src/extension/shortcut.ts +105 -0
  72. package/src/extension/tools.test.ts +993 -0
  73. package/src/extension/tools.ts +505 -0
  74. package/src/extension/version.test.ts +123 -0
  75. package/src/extension/version.ts +97 -0
  76. package/src/harness-policy.test.ts +74 -0
  77. package/src/package-manifest.test.ts +157 -0
  78. package/src/presentation/actions.test.ts +221 -0
  79. package/src/presentation/actions.ts +85 -0
  80. package/src/presentation/activity.test.ts +387 -0
  81. package/src/presentation/activity.ts +66 -0
  82. package/src/presentation/close.test.ts +361 -0
  83. package/src/presentation/inspector.test.ts +679 -0
  84. package/src/presentation/inspector.ts +440 -0
  85. package/src/presentation/overlay.test.ts +555 -0
  86. package/src/presentation/overlay.ts +229 -0
  87. package/src/presentation/repaint.test.ts +329 -0
  88. package/src/presentation/shortcut.ts +2 -0
  89. package/src/presentation/snapshot.test.ts +530 -0
  90. package/src/presentation/snapshot.ts +306 -0
  91. package/src/presentation/strip.test.ts +196 -0
  92. package/src/presentation/strip.ts +74 -0
  93. package/src/presentation/wording.test.ts +238 -0
  94. package/src/presentation/wording.ts +222 -0
  95. package/src/runtime/bridge.test.ts +131 -0
  96. package/src/runtime/bridge.ts +134 -0
  97. package/src/runtime/config.test.ts +44 -0
  98. package/src/runtime/config.ts +87 -0
  99. package/src/runtime/context.test.ts +19 -0
  100. package/src/runtime/context.ts +9 -0
  101. package/src/runtime/execution-env.test.ts +35 -0
  102. package/src/runtime/execution-env.ts +15 -0
  103. package/src/runtime/extensions.test.ts +86 -0
  104. package/src/runtime/extensions.ts +140 -0
  105. package/src/runtime/log.test.ts +128 -0
  106. package/src/runtime/log.ts +68 -0
  107. package/src/runtime/mcp.test.ts +1453 -0
  108. package/src/runtime/mcp.ts +938 -0
  109. package/src/runtime/models.test.ts +145 -0
  110. package/src/runtime/models.ts +259 -0
  111. package/src/runtime/observe.test.ts +50 -0
  112. package/src/runtime/observe.ts +150 -0
  113. package/src/runtime/session.test.ts +359 -0
  114. package/src/runtime/session.ts +425 -0
  115. package/src/runtime/timers.test.ts +31 -0
  116. package/src/runtime/timers.ts +10 -0
@@ -0,0 +1,938 @@
1
+ import type { Context } from "@earendil-works/chord/context";
2
+ import type { McpExposure, McpServerConfig, McpServerEntry } from "@earendil-works/pi-coding-agent";
3
+ import type { ToolExecutionResult, ToolRegistration } from "@earendil-works/pi-durable";
4
+ import {
5
+ createMcpToolName,
6
+ isMcpServerOverride,
7
+ limitMcpContent,
8
+ McpClient,
9
+ mcpNamespace,
10
+ normalizeMcpInputSchema,
11
+ StdioTransport,
12
+ StreamableHttpTransport,
13
+ toLlmContent,
14
+ validateMcpServerConfig,
15
+ type CallToolResult,
16
+ type McpOutputSaver,
17
+ type McpServerConfigResult,
18
+ type Tool,
19
+ } from "@earendil-works/pi-mcp";
20
+ import { mkdir, writeFile } from "node:fs/promises";
21
+ import { readFileSync } from "node:fs";
22
+ import { join } from "node:path";
23
+ import { Predicate } from "effect";
24
+ import { reasonOf, type LogSink } from "./log.ts";
25
+ import type { Timers } from "./timers.ts";
26
+
27
+ /** Where the two `mcp.json` files live; trust comes from the host, never from a file. */
28
+ export interface McpConfigSources {
29
+ readonly agentDir: string;
30
+ readonly cwd: string;
31
+ readonly projectTrusted: boolean;
32
+ }
33
+
34
+ export interface McpDiagnostic {
35
+ /** A stable identifier: `mcp.<problem>`. */
36
+ readonly code: string;
37
+ /** Display-only text that names the file and the problem, never a secret. */
38
+ readonly detail: string;
39
+ }
40
+
41
+ export interface McpConfigResult {
42
+ readonly servers: readonly McpServerEntry[];
43
+ readonly diagnostics: readonly McpDiagnostic[];
44
+ }
45
+
46
+ /** The four documented names, the `codemode-deferred` alias, and the `codemode` default. */
47
+ export const normalizeExposure = (
48
+ value: unknown,
49
+ ): { readonly kind: "ok"; readonly exposure: McpExposure } | { readonly kind: "invalid" } => {
50
+ if (value === "codemode-deferred") return { kind: "ok", exposure: "deferred" };
51
+ if (value === "codemode" || value === "deferred" || value === "direct" || value === "hidden") {
52
+ return { kind: "ok", exposure: value };
53
+ }
54
+ return { kind: "invalid" };
55
+ };
56
+
57
+ /** The only keys a project override may set; the host applies the same list. */
58
+ const OVERRIDE_KEYS = ["enabled", "exposure", "toolExposure"] as const;
59
+
60
+ const DEFAULT_EXPOSURE: McpExposure = "codemode";
61
+
62
+ const EXPOSURE_LIST = "codemode, deferred, direct or hidden";
63
+
64
+ /** A configured value as a diagnostic shows it; never a secret, only a name. */
65
+ const shown = (value: unknown): string =>
66
+ typeof value === "string" ? value : (JSON.stringify(value) ?? String(value));
67
+
68
+ const stripBom = (text: string): string => (text.startsWith("\uFEFF") ? text.slice(1) : text);
69
+
70
+ /** One `mcp.json`, parsed far enough to read its entries; every problem is a diagnostic. */
71
+ const readConfigFile = (
72
+ path: string,
73
+ diagnostics: McpDiagnostic[],
74
+ ): Readonly<Record<string, unknown>> => {
75
+ let text: string;
76
+ try {
77
+ text = readFileSync(path, "utf8");
78
+ } catch {
79
+ // A missing file is configuration, not degradation.
80
+ return {};
81
+ }
82
+ let parsed: unknown;
83
+ try {
84
+ parsed = JSON.parse(stripBom(text));
85
+ } catch (error) {
86
+ diagnostics.push({
87
+ code: "mcp.config_invalid",
88
+ detail: `${path} is not valid JSON: ${String(error)}`,
89
+ });
90
+ return {};
91
+ }
92
+ if (!Predicate.isObject(parsed)) {
93
+ diagnostics.push({
94
+ code: "mcp.config_invalid",
95
+ detail: `${path} must hold a JSON object.`,
96
+ });
97
+ return {};
98
+ }
99
+ if (parsed.mcpServers !== undefined && !Predicate.isObject(parsed.mcpServers)) {
100
+ diagnostics.push({
101
+ code: "mcp.config_invalid",
102
+ detail: `${path}: mcpServers must be an object.`,
103
+ });
104
+ return {};
105
+ }
106
+ if (parsed.autoEnableCodemode !== undefined && typeof parsed.autoEnableCodemode !== "boolean") {
107
+ // The toggle itself is not read: the package auto-selects per definition.
108
+ diagnostics.push({
109
+ code: "mcp.config_invalid",
110
+ detail: `${path}: autoEnableCodemode must be a boolean; the value is ignored.`,
111
+ });
112
+ }
113
+ return Predicate.isObject(parsed.mcpServers) ? parsed.mcpServers : {};
114
+ };
115
+
116
+ /**
117
+ * Resolves `exposure` and `toolExposure` from the validated entry. Both arrive unchecked: pi-mcp's
118
+ * validator keeps every field it does not know, and pi's values are not part of its shape.
119
+ */
120
+ const resolvedExposures = (
121
+ name: string,
122
+ raw: Readonly<Record<string, unknown>>,
123
+ path: string,
124
+ diagnostics: McpDiagnostic[],
125
+ ): { readonly exposure: McpExposure; readonly toolExposure?: Record<string, McpExposure> } => {
126
+ const configured = normalizeExposure(raw.exposure ?? DEFAULT_EXPOSURE);
127
+ if (configured.kind === "invalid") {
128
+ diagnostics.push({
129
+ code: "mcp.server_invalid",
130
+ detail: `${path}: server "${name}": exposure "${shown(raw.exposure)}" must be ${EXPOSURE_LIST}; using ${DEFAULT_EXPOSURE}.`,
131
+ });
132
+ }
133
+ const exposure = configured.kind === "ok" ? configured.exposure : DEFAULT_EXPOSURE;
134
+
135
+ let toolExposure: Record<string, McpExposure> | undefined;
136
+ if (raw.toolExposure !== undefined) {
137
+ if (!Predicate.isObject(raw.toolExposure)) {
138
+ diagnostics.push({
139
+ code: "mcp.server_invalid",
140
+ detail: `${path}: server "${name}": toolExposure must map tool names to an exposure.`,
141
+ });
142
+ } else {
143
+ toolExposure = {};
144
+ for (const [tool, value] of Object.entries(raw.toolExposure)) {
145
+ const normalized = normalizeExposure(value);
146
+ if (normalized.kind === "ok") toolExposure[tool] = normalized.exposure;
147
+ else {
148
+ diagnostics.push({
149
+ code: "mcp.server_invalid",
150
+ detail:
151
+ `${path}: server "${name}": toolExposure "${tool}" must be ${EXPOSURE_LIST}; ` +
152
+ `"${shown(value)}" is ignored.`,
153
+ });
154
+ }
155
+ }
156
+ }
157
+ }
158
+ return { exposure, ...(toolExposure === undefined ? {} : { toolExposure }) };
159
+ };
160
+
161
+ /** The keys every server may carry, copied from the validated record with their checked types. */
162
+ const sharedFields = (
163
+ raw: Readonly<Record<string, unknown>>,
164
+ exposure: McpExposure,
165
+ toolExposure: Record<string, McpExposure> | undefined,
166
+ ): Pick<McpServerConfig, "exposure" | "description" | "timeout" | "enabled" | "toolExposure"> => ({
167
+ ...(typeof raw.description === "string" ? { description: raw.description } : {}),
168
+ ...(typeof raw.enabled === "boolean" ? { enabled: raw.enabled } : {}),
169
+ ...(typeof raw.timeout === "number" ? { timeout: raw.timeout } : {}),
170
+ exposure,
171
+ ...(toolExposure === undefined ? {} : { toolExposure }),
172
+ });
173
+
174
+ /**
175
+ * The entry's config: the transport fields the validator checked, the resolved exposures, and the
176
+ * fields the validator kept unchecked (pi's `auth`, for example), so nothing is dropped or trusted
177
+ * on a cast. A validated config is never handed on unread.
178
+ */
179
+ const entryConfig = (
180
+ name: string,
181
+ validated: Exclude<McpServerConfigResult, { readonly kind: "invalid" }>,
182
+ path: string,
183
+ diagnostics: McpDiagnostic[],
184
+ ): McpServerConfig => {
185
+ // The record view carries pi's extra fields; the validator checked the transport ones.
186
+ const raw: Readonly<Record<string, unknown>> = validated.config;
187
+ const { exposure, toolExposure } = resolvedExposures(name, raw, path, diagnostics);
188
+ const shared = sharedFields(raw, exposure, toolExposure);
189
+ const config: McpServerConfig =
190
+ validated.kind === "stdio"
191
+ ? {
192
+ command: validated.config.command,
193
+ ...(validated.config.type === undefined ? {} : { type: validated.config.type }),
194
+ ...(validated.config.args === undefined ? {} : { args: validated.config.args }),
195
+ ...(validated.config.env === undefined ? {} : { env: validated.config.env }),
196
+ ...(validated.config.cwd === undefined ? {} : { cwd: validated.config.cwd }),
197
+ ...shared,
198
+ }
199
+ : {
200
+ url: validated.config.url,
201
+ ...(validated.config.type === undefined ? {} : { type: validated.config.type }),
202
+ ...(validated.config.headers === undefined ? {} : { headers: validated.config.headers }),
203
+ ...(validated.config.oauth === undefined ? {} : { oauth: validated.config.oauth }),
204
+ ...shared,
205
+ };
206
+ // Keep the fields this package does not read, so a later reader sees them.
207
+ const { exposure: _configured, toolExposure: _perTool, ...kept } = raw;
208
+ return Object.assign(config, kept);
209
+ };
210
+
211
+ /** Validates one entry and normalizes its exposure; an invalid entry is a diagnostic. */
212
+ const validatedEntry = (
213
+ name: string,
214
+ raw: unknown,
215
+ source: { readonly path: string; readonly scope: "global" | "project" },
216
+ diagnostics: McpDiagnostic[],
217
+ ): McpServerEntry | undefined => {
218
+ const result = validateMcpServerConfig(name, raw);
219
+ if (result.kind === "invalid") {
220
+ diagnostics.push({ code: "mcp.server_invalid", detail: `${source.path}: ${result.error}` });
221
+ return undefined;
222
+ }
223
+ return {
224
+ name,
225
+ config: entryConfig(name, result, source.path, diagnostics),
226
+ source: source.path,
227
+ scope: source.scope,
228
+ };
229
+ };
230
+
231
+ /**
232
+ * Reads `mcp.json` from the agent directory and, when the project is trusted,
233
+ * `<project>/.pi/mcp.json`. Project entries replace global entries of the same
234
+ * name; an override-only entry changes `enabled`, `exposure` and `toolExposure`
235
+ * and keeps the rest. Never throws: every problem is a diagnostic.
236
+ */
237
+ export const readMcpConfig = (sources: McpConfigSources): McpConfigResult => {
238
+ const diagnostics: McpDiagnostic[] = [];
239
+ const servers = new Map<string, McpServerEntry>();
240
+
241
+ const globalPath = join(sources.agentDir, "mcp.json");
242
+ for (const [name, raw] of Object.entries(readConfigFile(globalPath, diagnostics))) {
243
+ const entry = validatedEntry(name, raw, { path: globalPath, scope: "global" }, diagnostics);
244
+ if (entry !== undefined) servers.set(name, entry);
245
+ }
246
+
247
+ if (sources.projectTrusted) {
248
+ const projectPath = join(sources.cwd, ".pi", "mcp.json");
249
+ for (const [name, raw] of Object.entries(readConfigFile(projectPath, diagnostics))) {
250
+ if (Predicate.isObject(raw) && isMcpServerOverride(raw)) {
251
+ const base = servers.get(name);
252
+ const extra = Object.keys(raw).filter(
253
+ (key) => !OVERRIDE_KEYS.some((allowed) => allowed === key),
254
+ );
255
+ if (base === undefined) {
256
+ diagnostics.push({
257
+ code: "mcp.override_without_server",
258
+ detail:
259
+ `${projectPath}: server "${name}" needs "command" or "url", ` +
260
+ "or a global server to override.",
261
+ });
262
+ continue;
263
+ }
264
+ if (extra.length > 0) {
265
+ diagnostics.push({
266
+ code: "mcp.server_invalid",
267
+ detail:
268
+ `${projectPath}: server "${name}": an override can only set ` +
269
+ `${OVERRIDE_KEYS.join(", ")}.`,
270
+ });
271
+ continue;
272
+ }
273
+ const merged = validateMcpServerConfig(name, { ...base.config, ...raw });
274
+ if (merged.kind === "invalid") {
275
+ diagnostics.push({
276
+ code: "mcp.server_invalid",
277
+ detail: `${projectPath}: ${merged.error}`,
278
+ });
279
+ continue;
280
+ }
281
+ servers.set(name, {
282
+ ...base,
283
+ config: entryConfig(name, merged, projectPath, diagnostics),
284
+ override: projectPath,
285
+ });
286
+ continue;
287
+ }
288
+
289
+ // A repository cannot choose where a credential goes. The host applies the
290
+ // same rule to a URL server only; `auth` on a stdio entry is inert.
291
+ if (Predicate.isObject(raw) && raw.url !== undefined && raw.auth !== undefined) {
292
+ diagnostics.push({
293
+ code: "mcp.server_invalid",
294
+ detail:
295
+ `${projectPath}: server "${name}": auth is only allowed in the global mcp.json; ` +
296
+ "the entry is ignored.",
297
+ });
298
+ continue;
299
+ }
300
+ const entry = validatedEntry(name, raw, { path: projectPath, scope: "project" }, diagnostics);
301
+ if (entry === undefined) continue;
302
+ servers.set(name, entry);
303
+ }
304
+ }
305
+
306
+ // Names that differ only in `-` and `_` share a namespace, so only the first is installed.
307
+ const namespaces = new Map<string, string>();
308
+ const names = Array.from(servers.keys());
309
+ for (const name of names) {
310
+ const namespace = mcpNamespace(name);
311
+ const clash = namespaces.get(namespace);
312
+ if (clash === undefined) {
313
+ namespaces.set(namespace, name);
314
+ continue;
315
+ }
316
+ diagnostics.push({
317
+ code: "mcp.namespace_collision",
318
+ detail: `Server "${name}" conflicts with "${clash}": both use the namespace ${namespace}.`,
319
+ });
320
+ servers.delete(name);
321
+ }
322
+
323
+ return { servers: [...servers.values()], diagnostics };
324
+ };
325
+
326
+ /** How long one server gets to answer `initialize`; a slower server degrades. */
327
+ export const CONNECT_TIMEOUT_MS = 10_000;
328
+
329
+ /** The server's per-request timeout when the entry sets none, as the host documents. */
330
+ export const DEFAULT_TIMEOUT_SECONDS = 60;
331
+
332
+ /** One tool a connected server offers, with its durable name already allocated. */
333
+ export interface McpTool {
334
+ /** The durable tool name, `mcp__<server>__<tool>`. */
335
+ readonly name: string;
336
+ /** The name the server knows, which `call` takes. */
337
+ readonly serverName: string;
338
+ readonly description: string;
339
+ /** The server's JSON Schema, normalized and passed through as `parameters`. */
340
+ readonly parameters: object;
341
+ /** The effective exposure after `toolExposure`, never `hidden`: hidden tools are omitted. */
342
+ readonly exposure: Exclude<McpExposure, "hidden">;
343
+ }
344
+
345
+ /** One live server; the transport is pi-mcp's client, narrowed to the four calls used here. */
346
+ export interface McpConnection {
347
+ readonly server: string;
348
+ /** `mcp:<server>`, the extension that owns the namespace. */
349
+ readonly extension: string;
350
+ /** `mcp__<server>`. */
351
+ readonly namespace: string;
352
+ readonly tools: readonly McpTool[];
353
+ /** The server's per-request timeout in seconds, bounded around every call. */
354
+ readonly timeout: number;
355
+ /** Writes a bounded result's full text under the session and returns its path. */
356
+ readonly saveOutput: McpOutputSaver;
357
+ call(serverName: string, args: Record<string, unknown>): Promise<CallToolResult>;
358
+ close(): Promise<void>;
359
+ }
360
+
361
+ export interface McpPresence {
362
+ /** Configured servers with no live connection: unreferenced, disabled, refused or failed. */
363
+ readonly unconnected: readonly string[];
364
+ }
365
+
366
+ /** One server that was attempted and failed: the start notice reads this, never `presence`. */
367
+ export interface McpFailure {
368
+ readonly server: string;
369
+ /** `mcp.connect_failed`, `mcp.connect_timeout` or `mcp.list_tools_failed`. */
370
+ readonly code: string;
371
+ }
372
+
373
+ export interface McpHost {
374
+ readonly connections: readonly McpConnection[];
375
+ readonly diagnostics: readonly McpDiagnostic[];
376
+ readonly presence: McpPresence;
377
+ readonly failures: readonly McpFailure[];
378
+ close(): Promise<void>;
379
+ }
380
+
381
+ /** The four calls this package makes on a client; the rest of `McpClient` is not used. */
382
+ export interface McpClientPort {
383
+ listTools(): Promise<Tool[]>;
384
+ callTool(name: string, args?: Record<string, unknown>): Promise<CallToolResult>;
385
+ onClose(listener: () => void): () => void;
386
+ close(): Promise<void>;
387
+ }
388
+
389
+ /** The transport seam: tests inject a double and never start a process. */
390
+ export interface McpClientFactory {
391
+ connect(entry: McpServerEntry): Promise<McpClientPort>;
392
+ }
393
+
394
+ /** The part of a definition that can reference a server. */
395
+ export interface DefinitionSelection {
396
+ readonly tools: readonly string[];
397
+ readonly extensions: readonly string[];
398
+ }
399
+
400
+ /** The entries some definition references, by exact tool name, pattern or extension name. */
401
+ export const referencedServers = (
402
+ definitions: readonly DefinitionSelection[],
403
+ entries: readonly McpServerEntry[],
404
+ ): ReadonlySet<string> => {
405
+ const referenced = new Set<string>();
406
+ for (const entry of entries) {
407
+ const prefix = `${mcpNamespace(entry.name)}__`;
408
+ const extension = `mcp:${entry.name}`;
409
+ const named = definitions.some(
410
+ (definition) =>
411
+ definition.extensions.includes(extension) ||
412
+ definition.tools.some((name) => name.startsWith(prefix)),
413
+ );
414
+ if (named) referenced.add(entry.name);
415
+ }
416
+ return referenced;
417
+ };
418
+
419
+ const escapePattern = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
420
+
421
+ const patternMatches = (pattern: string, name: string): boolean =>
422
+ new RegExp(`^${pattern.split("*").map(escapePattern).join(".*")}$`).test(name);
423
+
424
+ /** An exact `toolExposure` name wins, then the first matching `*` pattern, then the server exposure. */
425
+ export const toolExposureFor = (config: McpServerConfig, serverToolName: string): McpExposure => {
426
+ const overrides = config.toolExposure;
427
+ if (overrides !== undefined) {
428
+ const exact = overrides[serverToolName];
429
+ if (exact !== undefined) return exact;
430
+ for (const [pattern, exposure] of Object.entries(overrides)) {
431
+ if (pattern.includes("*") && patternMatches(pattern, serverToolName)) return exposure;
432
+ }
433
+ }
434
+ return config.exposure ?? "codemode";
435
+ };
436
+
437
+ const CALLERS: Readonly<Record<Exclude<McpExposure, "hidden">, readonly ("model" | "tools")[]>> = {
438
+ direct: ["model", "tools"],
439
+ codemode: ["tools"],
440
+ deferred: ["model", "tools"],
441
+ };
442
+
443
+ const timeoutSeconds = (config: McpServerConfig): number =>
444
+ config.timeout ?? DEFAULT_TIMEOUT_SECONDS;
445
+
446
+ const errorResult = (
447
+ text: string,
448
+ ): { output: { type: "text"; text: string }[]; isError: true } => ({
449
+ output: [{ type: "text", text }],
450
+ isError: true,
451
+ });
452
+
453
+ /** The race outcomes one bounded call can have; an abandoned call never resurfaces. */
454
+ type CallOutcome =
455
+ | { readonly kind: "result"; readonly result: CallToolResult }
456
+ | { readonly kind: "error"; readonly error: unknown }
457
+ | { readonly kind: "timeout" }
458
+ | { readonly kind: "aborted" };
459
+
460
+ /**
461
+ * Bounds one server call by the server's timeout and the run's cancellation. The losing promise
462
+ * is abandoned: a call that never answers no longer holds the child.
463
+ */
464
+ const boundedCall = async (
465
+ call: Promise<CallToolResult>,
466
+ signal: AbortSignal | undefined,
467
+ timers: Timers,
468
+ timeoutMs: number,
469
+ ): Promise<CallOutcome> => {
470
+ let handle: unknown;
471
+ let onAbort: (() => void) | undefined;
472
+ const races: Promise<CallOutcome>[] = [
473
+ call.then(
474
+ (result) => ({ kind: "result" as const, result }),
475
+ (error: unknown) => ({ kind: "error" as const, error }),
476
+ ),
477
+ new Promise<CallOutcome>((resolve) => {
478
+ handle = timers.setTimeout(() => resolve({ kind: "timeout" }), timeoutMs);
479
+ }),
480
+ ];
481
+ if (signal !== undefined) {
482
+ races.push(
483
+ new Promise<CallOutcome>((resolve) => {
484
+ onAbort = () => resolve({ kind: "aborted" });
485
+ signal.addEventListener("abort", onAbort, { once: true });
486
+ }),
487
+ );
488
+ }
489
+ try {
490
+ return await Promise.race(races);
491
+ } finally {
492
+ timers.clearTimeout(handle);
493
+ if (onAbort !== undefined) signal?.removeEventListener("abort", onAbort);
494
+ }
495
+ };
496
+
497
+ /**
498
+ * One durable tool over one server tool. `replay: "unsafe"`: a call has external effects, so an
499
+ * interrupted execution never reruns. The exposure is readable from `callers` and `deferred`, so no
500
+ * marker field leaves the declared shape.
501
+ */
502
+ export const mcpTool = (
503
+ connection: McpConnection,
504
+ tool: McpTool,
505
+ options: {
506
+ readonly log: LogSink;
507
+ readonly timers: Timers;
508
+ /** The server's per-request timeout in seconds. */
509
+ readonly timeout: number;
510
+ },
511
+ ): ToolRegistration => ({
512
+ name: tool.name,
513
+ description: tool.description,
514
+ parameters: tool.parameters,
515
+ callers: CALLERS[tool.exposure],
516
+ ...(tool.exposure === "deferred" ? { deferred: true as const } : {}),
517
+ replay: "unsafe",
518
+ execute: async (args: Record<string, unknown>, _api: unknown, context: Context) => {
519
+ if (context.abortSignal?.aborted ?? false) {
520
+ return errorResult(`MCP server "${connection.server}" was not called: the run was aborted.`);
521
+ }
522
+ const outcome = await boundedCall(
523
+ connection.call(tool.serverName, args),
524
+ context.abortSignal,
525
+ options.timers,
526
+ options.timeout * 1000,
527
+ );
528
+ if (outcome.kind === "aborted") {
529
+ return errorResult(`MCP server "${connection.server}" was not called: the run was aborted.`);
530
+ }
531
+ if (outcome.kind === "timeout") {
532
+ options.log.write("warn", "mcp.call_timeout", {
533
+ server: connection.server,
534
+ detail: `${tool.serverName} did not answer within ${options.timeout} s`,
535
+ });
536
+ return errorResult(
537
+ `MCP server "${connection.server}" did not answer within ${options.timeout} s; ` +
538
+ `${tool.serverName} did not run.`,
539
+ );
540
+ }
541
+ if (outcome.kind === "error") {
542
+ return errorResult(`MCP server "${connection.server}" failed: ${reasonOf(outcome.error)}`);
543
+ }
544
+ return resultOf(connection, tool, outcome.result, options.log);
545
+ },
546
+ });
547
+
548
+ /**
549
+ * Converts a result to transcript content, cuts model-facing text to the limit and saves the full
550
+ * text under the session. The path stays valid after `close()`.
551
+ */
552
+ const resultOf = async (
553
+ connection: McpConnection,
554
+ tool: McpTool,
555
+ result: CallToolResult,
556
+ log: LogSink,
557
+ ): Promise<ToolExecutionResult> => {
558
+ const limited = await limitMcpContent(toLlmContent(result), connection.saveOutput);
559
+ if (limited.fullOutputPath !== undefined) {
560
+ log.write("info", "mcp.output_saved", {
561
+ server: connection.server,
562
+ path: limited.fullOutputPath,
563
+ });
564
+ }
565
+ return {
566
+ output: limited.content,
567
+ ...((result.isError ?? false) ? { isError: true } : {}),
568
+ ...(limited.fullOutputPath === undefined
569
+ ? {}
570
+ : {
571
+ diagnostics: [
572
+ {
573
+ severity: "info" as const,
574
+ code: "mcp.output_saved",
575
+ message: `The full result of ${tool.name} is saved at ${limited.fullOutputPath}.`,
576
+ },
577
+ ],
578
+ }),
579
+ };
580
+ };
581
+
582
+ /** The transport an entry describes; its environment values are already expanded. */
583
+ const transportFor = (config: McpServerConfig): StdioTransport | StreamableHttpTransport => {
584
+ if ("command" in config) {
585
+ return new StdioTransport({
586
+ command: config.command,
587
+ ...(config.args === undefined ? {} : { args: config.args }),
588
+ ...(config.env === undefined ? {} : { env: config.env }),
589
+ ...(config.cwd === undefined ? {} : { cwd: config.cwd }),
590
+ inheritEnv: true,
591
+ stderr: "pipe",
592
+ });
593
+ }
594
+ return new StreamableHttpTransport({
595
+ url: config.url,
596
+ ...(config.headers === undefined ? {} : { headers: config.headers }),
597
+ });
598
+ };
599
+
600
+ /** The real factory: one pi-mcp client over the entry's transport. */
601
+ const clientFactory = (): McpClientFactory => ({
602
+ connect: async (entry) => {
603
+ const client = new McpClient({ name: "@ftrdotdev/pi-delegates", version: "0.0.0" });
604
+ await client.connect(transportFor(entry.config));
605
+ return client;
606
+ },
607
+ });
608
+
609
+ /** A `${NAME}` reference; only these are expanded, and only in `env` and `headers`. */
610
+ const ENV_REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
611
+
612
+ /**
613
+ * Expands `${NAME}` from the process environment. A missing variable keeps its literal, and a `!`
614
+ * command is refused: the package never runs a command to build a server environment.
615
+ */
616
+ export const expandEnv = (
617
+ value: string,
618
+ env: Record<string, string | undefined>,
619
+ ): {
620
+ readonly value: string;
621
+ readonly missing: readonly string[];
622
+ readonly unsupported: boolean;
623
+ } => {
624
+ if (value.startsWith("!")) return { value, missing: [], unsupported: true };
625
+ const missing: string[] = [];
626
+ const expanded = value.replace(ENV_REFERENCE, (match, name: string) => {
627
+ const found = env[name];
628
+ if (found === undefined) {
629
+ missing.push(name);
630
+ return match;
631
+ }
632
+ return found;
633
+ });
634
+ return { value: expanded, missing, unsupported: false };
635
+ };
636
+
637
+ /**
638
+ * Expands one entry's `env` (stdio) or `headers` (HTTP). A `!` value skips the server; a missing
639
+ * variable keeps its literal. Diagnostics name the server and the variable, never a value.
640
+ */
641
+ const expandEntry = (
642
+ entry: McpServerEntry,
643
+ env: Record<string, string | undefined>,
644
+ diagnostics: McpDiagnostic[],
645
+ ): McpServerEntry | undefined => {
646
+ const config = entry.config;
647
+ // `env` is a stdio field and `headers` an HTTP one; the validator checked both are string maps.
648
+ const values = "command" in config ? config.env : config.headers;
649
+ if (values === undefined) return entry;
650
+ const expanded: Record<string, string> = {};
651
+ let refused = false;
652
+ for (const [key, value] of Object.entries(values)) {
653
+ // A value that is not a string never reaches `expandEnv`, which would assume one.
654
+ if (typeof value !== "string") {
655
+ diagnostics.push({
656
+ code: "mcp.server_invalid",
657
+ detail: `MCP server "${entry.name}": ${key} must be a string; the server is skipped.`,
658
+ });
659
+ refused = true;
660
+ continue;
661
+ }
662
+ const result = expandEnv(value, env);
663
+ if (result.unsupported) {
664
+ diagnostics.push({
665
+ code: "mcp.env_unsupported",
666
+ detail:
667
+ `MCP server "${entry.name}": ${key} starts with "!", which is not supported; ` +
668
+ "the server is skipped.",
669
+ });
670
+ refused = true;
671
+ continue;
672
+ }
673
+ for (const name of result.missing) {
674
+ diagnostics.push({
675
+ code: "mcp.env_missing",
676
+ detail:
677
+ `MCP server "${entry.name}": ${key} references ${name}, which is not set; ` +
678
+ "the literal is kept.",
679
+ });
680
+ }
681
+ expanded[key] = result.value;
682
+ }
683
+ if (refused) return undefined;
684
+ return "command" in config
685
+ ? { ...entry, config: { ...config, env: expanded } }
686
+ : { ...entry, config: { ...config, headers: expanded } };
687
+ };
688
+
689
+ /**
690
+ * The one writer for a bounded result: it saves the full text under `<sessionDir>/mcp/` and returns
691
+ * its path, which outlives `close()` and travels with the session.
692
+ */
693
+ export const sessionOutput = (sessionDir: string): McpOutputSaver => {
694
+ let counter = 0;
695
+ return async (data, extension) => {
696
+ const dir = join(sessionDir, "mcp");
697
+ await mkdir(dir, { recursive: true });
698
+ counter += 1;
699
+ const path = join(dir, `output-${counter}${extension}`);
700
+ await writeFile(path, data);
701
+ return path;
702
+ };
703
+ };
704
+
705
+ /** A server tool as the server lists it, before its durable name is allocated. */
706
+ interface ListedTool {
707
+ readonly serverName: string;
708
+ readonly description: string;
709
+ readonly parameters: object;
710
+ /** Never `hidden`: a hidden tool is left out before the list is built. */
711
+ readonly exposure: Exclude<McpExposure, "hidden">;
712
+ }
713
+
714
+ /** Whether a live client closed on its own, and whether the host asked it to close. */
715
+ interface Liveness {
716
+ lost: boolean;
717
+ closing: boolean;
718
+ }
719
+
720
+ type ConnectOutcome =
721
+ | {
722
+ readonly kind: "connected";
723
+ readonly entry: McpServerEntry;
724
+ readonly client: McpClientPort;
725
+ readonly tools: readonly ListedTool[];
726
+ readonly liveness: Liveness;
727
+ }
728
+ | {
729
+ readonly kind: "failed";
730
+ readonly entry: McpServerEntry;
731
+ readonly code: string;
732
+ readonly detail: string;
733
+ };
734
+
735
+ /**
736
+ * Registers the one drop listener: the first close that the host did not ask for marks the
737
+ * connection lost, writes one diagnostic and notifies once; later closes change nothing.
738
+ */
739
+ const watchLiveness = (
740
+ entry: McpServerEntry,
741
+ client: McpClientPort,
742
+ log: LogSink,
743
+ onLost: ((server: string) => void) | undefined,
744
+ ): Liveness => {
745
+ const liveness: Liveness = { lost: false, closing: false };
746
+ client.onClose(() => {
747
+ if (liveness.closing || liveness.lost) return;
748
+ liveness.lost = true;
749
+ log.write("warn", "mcp.connection_lost", {
750
+ server: entry.name,
751
+ detail: "the server closed the connection",
752
+ });
753
+ onLost?.(entry.name);
754
+ });
755
+ return liveness;
756
+ };
757
+
758
+ const raceConnect = async (
759
+ work: Promise<McpClientPort>,
760
+ timers: Timers,
761
+ ): Promise<
762
+ { kind: "value"; value: McpClientPort } | { kind: "error"; error: unknown } | { kind: "timeout" }
763
+ > => {
764
+ let handle: unknown;
765
+ const settled = work.then(
766
+ (value) => ({ kind: "value" as const, value }),
767
+ (error: unknown) => ({ kind: "error" as const, error }),
768
+ );
769
+ const deadline = new Promise<{ kind: "timeout" }>((resolve) => {
770
+ handle = timers.setTimeout(() => resolve({ kind: "timeout" }), CONNECT_TIMEOUT_MS);
771
+ });
772
+ try {
773
+ return await Promise.race([settled, deadline]);
774
+ } finally {
775
+ timers.clearTimeout(handle);
776
+ }
777
+ };
778
+
779
+ /** Connects one entry, lists its visible tools and degrades it on any failure. */
780
+ const connectOne = async (
781
+ entry: McpServerEntry,
782
+ factory: McpClientFactory,
783
+ timers: Timers,
784
+ log: LogSink,
785
+ onLost: ((server: string) => void) | undefined,
786
+ ): Promise<ConnectOutcome> => {
787
+ const connecting = factory.connect(entry);
788
+ const raced = await raceConnect(connecting, timers);
789
+ if (raced.kind === "timeout") {
790
+ // The losing connect is abandoned; a client that still arrives closes itself.
791
+ void connecting.then((client) => client.close()).catch(() => undefined);
792
+ return {
793
+ kind: "failed",
794
+ entry,
795
+ code: "mcp.connect_timeout",
796
+ detail: `MCP server "${entry.name}" did not connect within ${CONNECT_TIMEOUT_MS / 1000} s.`,
797
+ };
798
+ }
799
+ if (raced.kind === "error") {
800
+ return {
801
+ kind: "failed",
802
+ entry,
803
+ code: "mcp.connect_failed",
804
+ detail: `MCP server "${entry.name}" did not connect: ${reasonOf(raced.error)}`,
805
+ };
806
+ }
807
+ const client = raced.value;
808
+ let listed: readonly Tool[];
809
+ try {
810
+ listed = await client.listTools();
811
+ } catch (error) {
812
+ await client.close().catch(() => undefined);
813
+ return {
814
+ kind: "failed",
815
+ entry,
816
+ code: "mcp.list_tools_failed",
817
+ detail: `MCP server "${entry.name}" did not list its tools: ${reasonOf(error)}`,
818
+ };
819
+ }
820
+ const tools: ListedTool[] = [];
821
+ for (const tool of listed) {
822
+ const exposure = toolExposureFor(entry.config, tool.name);
823
+ // A hidden tool is never registered; the server still connects for its other tools.
824
+ if (exposure === "hidden") continue;
825
+ tools.push({
826
+ serverName: tool.name,
827
+ description: tool.description ?? tool.title ?? tool.name,
828
+ parameters: normalizeMcpInputSchema(tool.inputSchema),
829
+ exposure,
830
+ });
831
+ }
832
+ return {
833
+ kind: "connected",
834
+ entry,
835
+ client,
836
+ tools,
837
+ liveness: watchLiveness(entry, client, log, onLost),
838
+ };
839
+ };
840
+
841
+ /**
842
+ * Opens one connection for every enabled server that a definition references, concurrently, each
843
+ * racing a ten-second deadline. A server that fails yields one diagnostic, no extension and a
844
+ * place in `presence.unconnected`; the launch continues.
845
+ */
846
+ export const connectServers = async (
847
+ entries: readonly McpServerEntry[],
848
+ log: LogSink,
849
+ options: {
850
+ readonly referenced: ReadonlySet<string>;
851
+ readonly timers: Timers;
852
+ /** Where the output writer saves a bounded result. */
853
+ readonly sessionDir: string;
854
+ readonly factory?: McpClientFactory;
855
+ /** The process environment `env` and `headers` read; default `process.env`. */
856
+ readonly env?: Record<string, string | undefined>;
857
+ /** Called once when a live connection drops; the extension turns it into one notice. */
858
+ readonly onLost?: (server: string) => void;
859
+ },
860
+ ): Promise<McpHost> => {
861
+ const factory = options.factory ?? clientFactory();
862
+ const diagnostics: McpDiagnostic[] = [];
863
+ const attempted: McpServerEntry[] = [];
864
+ const env = options.env ?? process.env;
865
+ for (const entry of entries) {
866
+ if (entry.config.enabled === false || !options.referenced.has(entry.name)) continue;
867
+ const expanded = expandEntry(entry, env, diagnostics);
868
+ if (expanded !== undefined) attempted.push(expanded);
869
+ }
870
+ const outcomes = await Promise.all(
871
+ attempted.map((entry) => connectOne(entry, factory, options.timers, log, options.onLost)),
872
+ );
873
+
874
+ const failures: McpFailure[] = [];
875
+ const connections: McpConnection[] = [];
876
+ const livenessOf = new Map<string, Liveness>();
877
+ const saveOutput = sessionOutput(options.sessionDir);
878
+ // One set for every server, so a sanitization collision gets the hash suffix.
879
+ const taken = new Set<string>();
880
+ for (const outcome of outcomes) {
881
+ if (outcome.kind === "failed") {
882
+ diagnostics.push({ code: outcome.code, detail: outcome.detail });
883
+ failures.push({ server: outcome.entry.name, code: outcome.code });
884
+ continue;
885
+ }
886
+ const { entry, client, liveness } = outcome;
887
+ livenessOf.set(entry.name, liveness);
888
+ const tools: McpTool[] = outcome.tools.map((listed) => {
889
+ const name = createMcpToolName(entry.name, listed.serverName, (candidate) =>
890
+ taken.has(candidate),
891
+ );
892
+ taken.add(name);
893
+ return { ...listed, name };
894
+ });
895
+ connections.push({
896
+ server: entry.name,
897
+ extension: `mcp:${entry.name}`,
898
+ namespace: mcpNamespace(entry.name),
899
+ tools,
900
+ timeout: timeoutSeconds(entry.config),
901
+ saveOutput,
902
+ call: (serverName, args) =>
903
+ liveness.lost
904
+ ? Promise.reject(new Error(`MCP server "${entry.name}" disconnected`))
905
+ : client.callTool(serverName, args),
906
+ close: () => {
907
+ liveness.closing = true;
908
+ return client.close();
909
+ },
910
+ });
911
+ }
912
+
913
+ const connected = new Set(connections.map((connection) => connection.server));
914
+ let closing: Promise<void> | undefined;
915
+ return {
916
+ connections,
917
+ diagnostics,
918
+ failures,
919
+ presence: {
920
+ // Read at access: a server whose connection dropped is no longer live.
921
+ get unconnected(): readonly string[] {
922
+ return entries
923
+ .filter((entry) => {
924
+ if (!connected.has(entry.name)) return true;
925
+ return livenessOf.get(entry.name)?.lost ?? false;
926
+ })
927
+ .map((entry) => entry.name);
928
+ },
929
+ },
930
+ close: () => {
931
+ // Idempotent: a second close is a no-op, and one failing client never blocks the rest.
932
+ closing ??= Promise.all(
933
+ connections.map((connection) => connection.close().catch(() => undefined)),
934
+ ).then(() => undefined);
935
+ return closing;
936
+ },
937
+ };
938
+ };