@fitchmultz/pi-mcp-adapter 5.0.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 (176) hide show
  1. package/CHANGELOG.md +750 -0
  2. package/LICENSE +21 -0
  3. package/OAUTH.md +462 -0
  4. package/README.md +820 -0
  5. package/abort.ts +34 -0
  6. package/agent-dir.ts +24 -0
  7. package/app-bridge.bundle.js +67 -0
  8. package/banner.png +0 -0
  9. package/checkpoint.ts +55 -0
  10. package/cli.js +222 -0
  11. package/commands.ts +619 -0
  12. package/config.ts +1204 -0
  13. package/consent-manager.ts +25 -0
  14. package/direct-tools.ts +408 -0
  15. package/dist/abort.d.ts +2 -0
  16. package/dist/abort.js +35 -0
  17. package/dist/agent-dir.d.ts +3 -0
  18. package/dist/agent-dir.js +21 -0
  19. package/dist/app-bridge.bundle.js +67 -0
  20. package/dist/checkpoint.d.ts +18 -0
  21. package/dist/checkpoint.js +53 -0
  22. package/dist/commands.d.ts +20 -0
  23. package/dist/commands.js +521 -0
  24. package/dist/config.d.ts +109 -0
  25. package/dist/config.js +1013 -0
  26. package/dist/consent-manager.d.ts +8 -0
  27. package/dist/consent-manager.js +21 -0
  28. package/dist/direct-tools.d.ts +10 -0
  29. package/dist/direct-tools.js +350 -0
  30. package/dist/docs/client-metadata.json +14 -0
  31. package/dist/elicitation-handler.d.ts +17 -0
  32. package/dist/elicitation-handler.js +308 -0
  33. package/dist/error-signal.d.ts +15 -0
  34. package/dist/error-signal.js +21 -0
  35. package/dist/glimpse-ui.d.ts +9 -0
  36. package/dist/glimpse-ui.js +75 -0
  37. package/dist/host-html-template.d.ts +15 -0
  38. package/dist/host-html-template.js +429 -0
  39. package/dist/index.d.ts +7 -0
  40. package/dist/index.js +840 -0
  41. package/dist/init.d.ts +25 -0
  42. package/dist/init.js +562 -0
  43. package/dist/legacy-migration.d.ts +18 -0
  44. package/dist/legacy-migration.js +45 -0
  45. package/dist/lifecycle.d.ts +40 -0
  46. package/dist/lifecycle.js +167 -0
  47. package/dist/logger.d.ts +38 -0
  48. package/dist/logger.js +102 -0
  49. package/dist/mcp-auth-flow.d.ts +113 -0
  50. package/dist/mcp-auth-flow.js +834 -0
  51. package/dist/mcp-auth.d.ts +127 -0
  52. package/dist/mcp-auth.js +658 -0
  53. package/dist/mcp-callback-server.d.ts +56 -0
  54. package/dist/mcp-callback-server.js +371 -0
  55. package/dist/mcp-code.d.ts +51 -0
  56. package/dist/mcp-code.js +366 -0
  57. package/dist/mcp-keyring-helper.cjs +89 -0
  58. package/dist/mcp-oauth-provider.d.ts +154 -0
  59. package/dist/mcp-oauth-provider.js +672 -0
  60. package/dist/mcp-output-guard.d.ts +59 -0
  61. package/dist/mcp-output-guard.js +332 -0
  62. package/dist/mcp-panel.d.ts +66 -0
  63. package/dist/mcp-panel.js +889 -0
  64. package/dist/mcp-script-worker.mjs +128 -0
  65. package/dist/mcp-setup-panel.d.ts +84 -0
  66. package/dist/mcp-setup-panel.js +561 -0
  67. package/dist/mcp-status.d.ts +11 -0
  68. package/dist/mcp-status.js +96 -0
  69. package/dist/mcp-trace.d.ts +95 -0
  70. package/dist/mcp-trace.js +233 -0
  71. package/dist/metadata-cache.d.ts +18 -0
  72. package/dist/metadata-cache.js +277 -0
  73. package/dist/npx-resolver.d.ts +6 -0
  74. package/dist/npx-resolver.js +448 -0
  75. package/dist/onboarding-state.d.ts +11 -0
  76. package/dist/onboarding-state.js +47 -0
  77. package/dist/panel-keys.d.ts +16 -0
  78. package/dist/panel-keys.js +15 -0
  79. package/dist/prompts.d.ts +56 -0
  80. package/dist/prompts.js +284 -0
  81. package/dist/proxy-modes.d.ts +38 -0
  82. package/dist/proxy-modes.js +1235 -0
  83. package/dist/resource-tools.d.ts +1 -0
  84. package/dist/resource-tools.js +14 -0
  85. package/dist/runtime-owner.d.ts +18 -0
  86. package/dist/runtime-owner.js +117 -0
  87. package/dist/sampling-handler.d.ts +15 -0
  88. package/dist/sampling-handler.js +211 -0
  89. package/dist/search-ranking.d.ts +20 -0
  90. package/dist/search-ranking.js +180 -0
  91. package/dist/server-manager.d.ts +114 -0
  92. package/dist/server-manager.js +1175 -0
  93. package/dist/session-recovery.d.ts +31 -0
  94. package/dist/session-recovery.js +310 -0
  95. package/dist/state.d.ts +63 -0
  96. package/dist/state.js +1 -0
  97. package/dist/tool-approval.d.ts +10 -0
  98. package/dist/tool-approval.js +42 -0
  99. package/dist/tool-metadata.d.ts +9 -0
  100. package/dist/tool-metadata.js +193 -0
  101. package/dist/tool-registrar.d.ts +10 -0
  102. package/dist/tool-registrar.js +64 -0
  103. package/dist/tool-result-renderer.d.ts +45 -0
  104. package/dist/tool-result-renderer.js +224 -0
  105. package/dist/ts-shape.d.ts +2 -0
  106. package/dist/ts-shape.js +147 -0
  107. package/dist/types.d.ts +516 -0
  108. package/dist/types.js +168 -0
  109. package/dist/ui-resource-handler.d.ts +17 -0
  110. package/dist/ui-resource-handler.js +209 -0
  111. package/dist/ui-server.d.ts +51 -0
  112. package/dist/ui-server.js +669 -0
  113. package/dist/ui-session.d.ts +39 -0
  114. package/dist/ui-session.js +463 -0
  115. package/dist/ui-stream-types.d.ts +104 -0
  116. package/dist/ui-stream-types.js +58 -0
  117. package/dist/ui-tool-visibility.d.ts +4 -0
  118. package/dist/ui-tool-visibility.js +26 -0
  119. package/dist/unix-socket-transport.d.ts +15 -0
  120. package/dist/unix-socket-transport.js +84 -0
  121. package/dist/utils.d.ts +30 -0
  122. package/dist/utils.js +276 -0
  123. package/docs/client-metadata.json +14 -0
  124. package/elicitation-handler.ts +349 -0
  125. package/error-signal.ts +21 -0
  126. package/glimpse-ui.ts +80 -0
  127. package/host-html-template.ts +456 -0
  128. package/index.ts +900 -0
  129. package/init.ts +627 -0
  130. package/legacy-migration.ts +47 -0
  131. package/lifecycle.ts +165 -0
  132. package/logger.ts +127 -0
  133. package/mcp-auth-flow.ts +975 -0
  134. package/mcp-auth.ts +793 -0
  135. package/mcp-callback-server.ts +450 -0
  136. package/mcp-code.ts +386 -0
  137. package/mcp-keyring-helper.cjs +89 -0
  138. package/mcp-oauth-provider.ts +774 -0
  139. package/mcp-output-guard.ts +412 -0
  140. package/mcp-panel.ts +978 -0
  141. package/mcp-script-worker.mjs +128 -0
  142. package/mcp-setup-panel.ts +666 -0
  143. package/mcp-status.ts +109 -0
  144. package/mcp-trace.ts +295 -0
  145. package/metadata-cache.ts +333 -0
  146. package/npx-resolver.ts +488 -0
  147. package/onboarding-state.ts +58 -0
  148. package/package.json +182 -0
  149. package/panel-keys.ts +37 -0
  150. package/prompts.ts +337 -0
  151. package/proxy-modes.ts +1361 -0
  152. package/resource-tools.ts +17 -0
  153. package/runtime-owner.ts +123 -0
  154. package/sampling-handler.ts +273 -0
  155. package/scripts/build.mjs +131 -0
  156. package/scripts/prepare.mjs +102 -0
  157. package/search-ranking.ts +196 -0
  158. package/server-manager.ts +1320 -0
  159. package/session-recovery.ts +316 -0
  160. package/skills/mcp-scripting/SKILL.md +38 -0
  161. package/state.ts +64 -0
  162. package/tool-approval.ts +78 -0
  163. package/tool-metadata.ts +235 -0
  164. package/tool-registrar.ts +69 -0
  165. package/tool-result-renderer.ts +286 -0
  166. package/ts-shape.ts +145 -0
  167. package/tsconfig.build.json +13 -0
  168. package/tsconfig.json +16 -0
  169. package/types.ts +810 -0
  170. package/ui-resource-handler.ts +249 -0
  171. package/ui-server.ts +808 -0
  172. package/ui-session.ts +568 -0
  173. package/ui-stream-types.ts +89 -0
  174. package/ui-tool-visibility.ts +25 -0
  175. package/unix-socket-transport.ts +85 -0
  176. package/utils.ts +309 -0
package/mcp-code.ts ADDED
@@ -0,0 +1,386 @@
1
+ import type { ToolInfo } from "@earendil-works/pi-coding-agent";
2
+ import { formatWithOptions } from "node:util";
3
+ import { Worker } from "node:worker_threads";
4
+ import { guardMcpOutput, guardedMcpDetails, resolveMcpOutputGuardOptions } from "./mcp-output-guard.ts";
5
+ import { executeCall } from "./proxy-modes.ts";
6
+ import { combineAbortSignals } from "./runtime-owner.ts";
7
+ import { paginate, rankSuggestions, rankToolMatches } from "./search-ranking.ts";
8
+ import type { McpExtensionState } from "./state.ts";
9
+ import { findToolByName } from "./tool-metadata.ts";
10
+ import { renderTsShape } from "./ts-shape.ts";
11
+ import type { ContentBlock, McpOperationContext } from "./types.ts";
12
+
13
+ export const DEFAULT_MCP_SCRIPT_TIMEOUT_MS = 30_000;
14
+
15
+ class McpScriptTimeoutError extends Error {
16
+ constructor(timeoutMs: number) {
17
+ super(`mcp_script timed out after ${timeoutMs}ms`);
18
+ this.name = "McpScriptTimeoutError";
19
+ }
20
+ }
21
+
22
+ type SearchInput = { query?: unknown; server?: unknown; limit?: unknown; offset?: unknown };
23
+ type DescribeInput = { path?: unknown };
24
+ type WorkerMessage =
25
+ | { type: "emit"; block: unknown }
26
+ | { type: "call"; id: number; path: string; args?: unknown }
27
+ | { type: "search"; id: number; input?: unknown }
28
+ | { type: "describe"; id: number; input?: unknown }
29
+ | { type: "done"; returnBlock?: unknown }
30
+ | { type: "error"; message: string };
31
+
32
+ type WorkerResultMessage = { type: "result"; id: number; envelope: unknown };
33
+
34
+ function needsInspectableFormatting(value: unknown, stack = new WeakSet<object>()): boolean {
35
+ if (value === undefined || typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") return true;
36
+ if (typeof value !== "object" || value === null) return false;
37
+ if (stack.has(value)) return true;
38
+ if (value instanceof Map || value instanceof Set || value instanceof WeakMap || value instanceof WeakSet) return true;
39
+ stack.add(value);
40
+ try {
41
+ return Object.values(value).some((entry) => needsInspectableFormatting(entry, stack));
42
+ } finally {
43
+ stack.delete(value);
44
+ }
45
+ }
46
+
47
+ function formatValue(value: unknown): string {
48
+ if (typeof value === "string") return value;
49
+ try {
50
+ if (!needsInspectableFormatting(value)) {
51
+ const json = JSON.stringify(value, null, 2);
52
+ if (json !== undefined) return json;
53
+ }
54
+ return formatWithOptions({ colors: false, depth: 6 }, value);
55
+ } catch {
56
+ return "[unserializable value]";
57
+ }
58
+ }
59
+
60
+ function toContentBlock(value: unknown): ContentBlock {
61
+ if (typeof value === "object" && value !== null) {
62
+ const block = value as Record<string, unknown>;
63
+ if (block.type === "text" && typeof block.text === "string") {
64
+ return { type: "text", text: block.text };
65
+ }
66
+ if (block.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string") {
67
+ return { type: "image", data: block.data, mimeType: block.mimeType };
68
+ }
69
+ }
70
+ return { type: "text", text: formatValue(value) };
71
+ }
72
+
73
+ function textFromContent(content: ContentBlock[]): string {
74
+ return content
75
+ .filter((block) => block.type === "text")
76
+ .map((block) => block.text)
77
+ .join("\n");
78
+ }
79
+
80
+ function abortReasonError(reason: unknown): Error {
81
+ return reason instanceof Error ? reason : new Error(String(reason ?? "MCP request aborted"));
82
+ }
83
+
84
+ function parseWorkerMessage(value: unknown): WorkerMessage | null {
85
+ if (typeof value !== "object" || value === null) return null;
86
+ const message = value as Record<string, unknown>;
87
+ if (message.type === "emit" && "block" in message) return { type: "emit", block: message.block };
88
+ if (message.type === "call" && typeof message.id === "number" && typeof message.path === "string") {
89
+ return "args" in message
90
+ ? { type: "call", id: message.id, path: message.path, args: message.args }
91
+ : { type: "call", id: message.id, path: message.path };
92
+ }
93
+ if ((message.type === "search" || message.type === "describe") && typeof message.id === "number") {
94
+ return "input" in message
95
+ ? { type: message.type, id: message.id, input: message.input }
96
+ : { type: message.type, id: message.id };
97
+ }
98
+ if (message.type === "done") {
99
+ return "returnBlock" in message ? { type: "done", returnBlock: message.returnBlock } : { type: "done" };
100
+ }
101
+ if (message.type === "error" && typeof message.message === "string") {
102
+ return { type: "error", message: message.message };
103
+ }
104
+ return null;
105
+ }
106
+
107
+ class McpScriptCaptureError extends Error {
108
+ constructor(readonly recovery: unknown, message: string) {
109
+ super(message);
110
+ }
111
+ }
112
+
113
+ export const runMcpScript: typeof runMcpScriptOperation = async (...args) => {
114
+ const state = args[0];
115
+ state.owner?.beforeActivity();
116
+ state.activeScripts = (state.activeScripts ?? 0) + 1;
117
+ try { return await runMcpScriptOperation(...args); }
118
+ finally { state.activeScripts--; }
119
+ };
120
+
121
+ async function runMcpScriptOperation(
122
+ state: McpExtensionState,
123
+ code: string,
124
+ timeoutMs: number | null = DEFAULT_MCP_SCRIPT_TIMEOUT_MS,
125
+ getPiTools?: () => ToolInfo[],
126
+ signal?: AbortSignal,
127
+ toolCallId?: string,
128
+ beforeDispatch?: (signal: AbortSignal | undefined, operation: McpOperationContext) => Promise<void>,
129
+ ) {
130
+ const resolvedTimeoutMs = timeoutMs === null ? null : Number.isFinite(timeoutMs) && timeoutMs > 0
131
+ ? Math.floor(timeoutMs)
132
+ : DEFAULT_MCP_SCRIPT_TIMEOUT_MS;
133
+ const output: ContentBlock[] = [];
134
+ const externalSignal = combineAbortSignals(state.owner?.signal, signal);
135
+ const timeoutController = new AbortController();
136
+ const callSignal = combineAbortSignals(externalSignal, timeoutController.signal);
137
+
138
+ type ScriptOperation =
139
+ | { operation: "call"; path: string; ok: true; durationMs: number }
140
+ | { operation: "call"; path: string; ok: false; error: string; durationMs: number; recovery?: unknown }
141
+ | { operation: "search"; query: string; ok: true; durationMs: number }
142
+ | { operation: "search"; query: string; ok: false; error: string; durationMs: number }
143
+ | { operation: "describe"; path: string; ok: true; durationMs: number }
144
+ | { operation: "describe"; path: string; ok: false; error: string; durationMs: number };
145
+ type TrackedScriptOperation = ScriptOperation & { startedAt: number };
146
+ const calls: TrackedScriptOperation[] = [];
147
+ const snapshotCalls = (): ScriptOperation[] => calls.map(({ startedAt, ...operation }) => ({
148
+ ...operation,
149
+ durationMs: "error" in operation && operation.error === "incomplete"
150
+ ? Math.max(0, Date.now() - startedAt)
151
+ : operation.durationMs,
152
+ }));
153
+ let callsSnapshot: ScriptOperation[] | undefined;
154
+ const callTool = async (innerCallId: number, path: string, args?: Record<string, unknown>) => {
155
+ // Record before dispatch so calls still in flight at timeout/abort appear in the trace.
156
+ const startedAt = Date.now();
157
+ const index = calls.push({ operation: "call", path, ok: false, error: "incomplete", durationMs: 0, startedAt }) - 1;
158
+ let rawResult: unknown;
159
+ let hasRawResult = false;
160
+ const result = await executeCall(state, path, args, undefined, getPiTools, callSignal, (raw) => {
161
+ rawResult = raw;
162
+ hasRawResult = true;
163
+ }, { ...(toolCallId !== undefined ? { toolCallId } : {}), innerCallId }, beforeDispatch);
164
+ const details = result.details;
165
+ if (details.error !== undefined) {
166
+ const errorCode = String(details.error);
167
+ const suggestions = Array.isArray(details.suggestions)
168
+ ? details.suggestions.filter((suggestion): suggestion is string => typeof suggestion === "string")
169
+ : [];
170
+ const message = errorCode === "tool_not_found"
171
+ ? `Tool "${path}" not found. Use await tools.search({ query: "..." }) inside mcp_script.${suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : ""}`
172
+ : typeof details.message === "string"
173
+ ? details.message
174
+ : textFromContent(result.content);
175
+ calls[index] = {
176
+ operation: "call", path, ok: false, error: errorCode, durationMs: Date.now() - startedAt, startedAt,
177
+ ...(errorCode === "ambiguous_outcome" ? { recovery: details.recovery } : {}),
178
+ };
179
+ if (errorCode === "call_capture_failed") throw new McpScriptCaptureError(details.recovery, message);
180
+ if (errorCode === "ambiguous_outcome") output.push({ type: "text", text: message });
181
+ return {
182
+ ok: false as const,
183
+ error: { code: errorCode, message, ...(details.recovery ? { recovery: details.recovery } : {}) },
184
+ };
185
+ }
186
+ calls[index] = { operation: "call", path, ok: true, durationMs: Date.now() - startedAt, startedAt };
187
+ return {
188
+ ok: true as const,
189
+ data: hasRawResult ? rawResult : details.mcpResult !== undefined ? details.mcpResult : textFromContent(result.content),
190
+ };
191
+ };
192
+
193
+ const searchTools = (input?: SearchInput) => {
194
+ const startedAt = Date.now();
195
+ const query = typeof input?.query === "string" ? input.query : "";
196
+ let error: unknown;
197
+ try {
198
+ if (query.trim() === "") {
199
+ return { items: [], total: 0, hasMore: false, nextOffset: null };
200
+ }
201
+ const server = typeof input?.server === "string" ? input.server : undefined;
202
+ const limit = typeof input?.limit === "number" ? input.limit : 12;
203
+ const offset = typeof input?.offset === "number" ? input.offset : 0;
204
+ const page = paginate(rankToolMatches(state, query, server), offset, limit);
205
+ return {
206
+ ...page,
207
+ items: page.items.map(({ server: matchServer, tool, score }) => ({
208
+ path: tool.name,
209
+ name: tool.originalName,
210
+ server: matchServer,
211
+ ...(tool.description ? { description: tool.description } : {}),
212
+ score,
213
+ })),
214
+ };
215
+ } catch (caught) {
216
+ error = caught;
217
+ throw caught;
218
+ } finally {
219
+ calls.push(error === undefined
220
+ ? { operation: "search", query, ok: true, durationMs: Date.now() - startedAt, startedAt }
221
+ : { operation: "search", query, ok: false, error: error instanceof Error ? error.message : String(error), durationMs: Date.now() - startedAt, startedAt });
222
+ }
223
+ };
224
+
225
+ const describeTool = (input?: DescribeInput) => {
226
+ const startedAt = Date.now();
227
+ const path = typeof input?.path === "string" ? input.path : "";
228
+ let error: unknown;
229
+ try {
230
+ for (const [server, metadata] of state.toolMetadata) {
231
+ const tool = findToolByName(metadata, path);
232
+ if (!tool) continue;
233
+ const inputTypeScript = tool.inputSchema ? renderTsShape(tool.inputSchema) : null;
234
+ return {
235
+ path: tool.name,
236
+ name: tool.originalName,
237
+ server,
238
+ ...(tool.description ? { description: tool.description } : {}),
239
+ ...(inputTypeScript ? { inputTypeScript } : tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
240
+ ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),
241
+ };
242
+ }
243
+ const suggestions = path ? rankSuggestions(state, path, 5) : [];
244
+ error = "tool_not_found";
245
+ return {
246
+ path,
247
+ error: {
248
+ code: "tool_not_found",
249
+ message: `Tool not found: ${path}`,
250
+ suggestions,
251
+ },
252
+ };
253
+ } catch (caught) {
254
+ error = caught;
255
+ throw caught;
256
+ } finally {
257
+ calls.push(error === undefined
258
+ ? { operation: "describe", path, ok: true, durationMs: Date.now() - startedAt, startedAt }
259
+ : { operation: "describe", path, ok: false, error: error instanceof Error ? error.message : String(error), durationMs: Date.now() - startedAt, startedAt });
260
+ }
261
+ };
262
+
263
+ let worker: Worker | undefined;
264
+ let timer: ReturnType<typeof setTimeout> | undefined;
265
+ let removeAbortListener = () => {};
266
+ let errorCode: "timeout" | "aborted" | "script_error" | "call_capture_failed" | undefined;
267
+ let recovery: unknown;
268
+ let errorMessage: string | undefined;
269
+
270
+ try {
271
+ if (externalSignal?.aborted) {
272
+ throw abortReasonError(externalSignal.reason);
273
+ }
274
+
275
+ worker = new Worker(new URL("./mcp-script-worker.mjs", import.meta.url), {
276
+ workerData: { code },
277
+ env: {},
278
+ });
279
+ const activeWorker = worker;
280
+ const execution = new Promise<void>((resolve, reject) => {
281
+ let completed = false;
282
+ activeWorker.on("message", (value: unknown) => {
283
+ const message = parseWorkerMessage(value);
284
+ if (!message || completed) return;
285
+ if (message.type === "emit") {
286
+ output.push(toContentBlock(message.block));
287
+ return;
288
+ }
289
+ if (message.type === "done") {
290
+ completed = true;
291
+ if ("returnBlock" in message) output.push(toContentBlock(message.returnBlock));
292
+ resolve();
293
+ return;
294
+ }
295
+ if (message.type === "error") {
296
+ completed = true;
297
+ reject(new Error(message.message));
298
+ return;
299
+ }
300
+
301
+ void (async () => {
302
+ let envelope: unknown;
303
+ if (message.type === "call") {
304
+ envelope = await callTool(message.id, message.path, message.args as Record<string, unknown> | undefined);
305
+ } else if (message.type === "search") {
306
+ envelope = searchTools(message.input as SearchInput | undefined);
307
+ } else {
308
+ envelope = describeTool(message.input as DescribeInput | undefined);
309
+ }
310
+ const response: WorkerResultMessage = { type: "result", id: message.id, envelope };
311
+ activeWorker.postMessage(response);
312
+ })().catch(reject);
313
+ });
314
+ activeWorker.once("error", reject);
315
+ activeWorker.once("exit", (code) => {
316
+ if (!completed && code !== 0) reject(new Error(`mcp_script worker exited with code ${code}`));
317
+ });
318
+ });
319
+ const timeout = new Promise<never>((_resolve, reject) => {
320
+ if (resolvedTimeoutMs === null) return;
321
+ const timeoutError = new McpScriptTimeoutError(resolvedTimeoutMs);
322
+ timer = setTimeout(() => {
323
+ callsSnapshot = snapshotCalls();
324
+ timeoutController.abort(timeoutError);
325
+ void activeWorker.terminate();
326
+ reject(timeoutError);
327
+ }, resolvedTimeoutMs);
328
+ });
329
+ const aborted = externalSignal
330
+ ? new Promise<never>((_resolve, reject) => {
331
+ const onAbort = () => {
332
+ callsSnapshot = snapshotCalls();
333
+ void activeWorker.terminate();
334
+ reject(abortReasonError(externalSignal.reason));
335
+ };
336
+ externalSignal.addEventListener("abort", onAbort, { once: true });
337
+ removeAbortListener = () => externalSignal.removeEventListener("abort", onAbort);
338
+ })
339
+ : new Promise<never>(() => {});
340
+
341
+ await Promise.race([execution, timeout, aborted]);
342
+ } catch (error) {
343
+ if (error instanceof McpScriptCaptureError) {
344
+ errorCode = "call_capture_failed";
345
+ errorMessage = error.message;
346
+ recovery = error.recovery;
347
+ } else if (error instanceof McpScriptTimeoutError) {
348
+ errorCode = "timeout";
349
+ errorMessage = `mcp_script timed out after ${resolvedTimeoutMs}ms`;
350
+ } else if (externalSignal?.aborted) {
351
+ errorCode = "aborted";
352
+ errorMessage = error instanceof Error ? error.message : String(error);
353
+ } else {
354
+ errorCode = "script_error";
355
+ errorMessage = error instanceof Error ? error.message : String(error);
356
+ }
357
+ output.push({ type: "text", text: errorMessage });
358
+ } finally {
359
+ clearTimeout(timer);
360
+ removeAbortListener();
361
+ // "incomplete" means the call had not settled when the script finished
362
+ // (deadline, abort, or early return). Snapshot before aborting stragglers.
363
+ callsSnapshot ??= snapshotCalls();
364
+ // A script may finish without awaiting every call; abort leftovers so
365
+ // parent-side dispatches do not outlive the script.
366
+ timeoutController.abort(new Error("mcp_script finished"));
367
+ await worker?.terminate();
368
+ }
369
+
370
+ // Snapshot before the asynchronous output guard; the terminated worker can no longer emit.
371
+ const guarded = await guardMcpOutput(
372
+ output.length > 0 ? [...output] : [{ type: "text", text: "(no output)" }],
373
+ resolveMcpOutputGuardOptions(state.config.settings, state.outputDirectory),
374
+ );
375
+ return {
376
+ content: guarded.content,
377
+ details: {
378
+ mode: "script",
379
+ ...(errorCode ? { error: errorCode, message: errorMessage } : {}),
380
+ timeoutMs: resolvedTimeoutMs,
381
+ ...(recovery !== undefined ? { recovery } : {}),
382
+ ...(callsSnapshot.length > 0 ? { calls: callsSnapshot } : {}),
383
+ ...guardedMcpDetails(guarded),
384
+ },
385
+ };
386
+ }
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { createRequire } = require('node:module');
5
+ const { dirname, join } = require('node:path');
6
+
7
+ const requireFromHere = createRequire(__filename);
8
+
9
+ function loadKeyringEntryClass() {
10
+ try {
11
+ return requireFromHere('@napi-rs/keyring').Entry;
12
+ } catch (loaderError) {
13
+ const suffixes = getNativeBindingSuffixes(process.platform, process.arch);
14
+ let lastError;
15
+ for (const suffix of suffixes) {
16
+ try {
17
+ const packageJsonPath = requireFromHere.resolve(`@napi-rs/keyring-${suffix}/package.json`);
18
+ return requireFromHere(join(dirname(packageJsonPath), `keyring.${suffix}.node`)).Entry;
19
+ } catch (error) {
20
+ lastError = error;
21
+ }
22
+ }
23
+ const error = new Error(`Failed to load @napi-rs/keyring in recovery helper: ${lastError?.message ?? loaderError.message}`);
24
+ error.cause = loaderError;
25
+ throw error;
26
+ }
27
+ }
28
+
29
+ function getNativeBindingSuffixes(platform, arch) {
30
+ if (platform === 'linux') {
31
+ if (arch === 'arm64') return ['linux-arm64-gnu', 'linux-arm64-musl'];
32
+ if (arch === 'arm') return ['linux-arm-gnueabihf'];
33
+ if (arch === 'riscv64') return ['linux-riscv64-gnu'];
34
+ if (arch === 'x64') return ['linux-x64-gnu', 'linux-x64-musl'];
35
+ }
36
+ return [];
37
+ }
38
+
39
+ function readStdin() {
40
+ return new Promise((resolve, reject) => {
41
+ let input = '';
42
+ process.stdin.setEncoding('utf8');
43
+ process.stdin.on('data', chunk => {
44
+ input += chunk;
45
+ if (input.length > 1024 * 1024) {
46
+ reject(new Error('request too large'));
47
+ process.stdin.destroy();
48
+ }
49
+ });
50
+ process.stdin.on('error', reject);
51
+ process.stdin.on('end', () => resolve(input));
52
+ });
53
+ }
54
+
55
+ function writeResponse(response) {
56
+ process.stdout.write(`${JSON.stringify(response)}\n`);
57
+ }
58
+
59
+ (async () => {
60
+ try {
61
+ const request = JSON.parse(await readStdin());
62
+ if (!request || typeof request !== 'object') throw new Error('invalid request');
63
+ const { operation, service, account, payload } = request;
64
+ if (!['read', 'write', 'remove'].includes(operation)) throw new Error('invalid operation');
65
+ if (typeof service !== 'string' || !service) throw new Error('invalid service');
66
+ if (typeof account !== 'string' || !account) throw new Error('invalid account');
67
+
68
+ const Entry = loadKeyringEntryClass();
69
+ const entry = new Entry(service, account);
70
+
71
+ if (operation === 'read') {
72
+ const value = entry.getPassword();
73
+ writeResponse(value === null ? { ok: true, found: false } : { ok: true, found: true, value });
74
+ return;
75
+ }
76
+ if (operation === 'write') {
77
+ if (typeof payload !== 'string') throw new Error('invalid payload');
78
+ entry.setPassword(payload);
79
+ writeResponse({ ok: true });
80
+ return;
81
+ }
82
+
83
+ entry.deleteCredential();
84
+ writeResponse({ ok: true });
85
+ } catch (error) {
86
+ writeResponse({ ok: false, error: error instanceof Error ? error.message : String(error) });
87
+ process.exitCode = 1;
88
+ }
89
+ })();