@nathanstephenson/flow 0.1.6 → 0.1.8
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.
- package/README.md +122 -640
- package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +94 -0
- package/build/backend-worker-chunks/chunk-MLOUI3ZM.mjs +19752 -0
- package/build/backend-worker-chunks/chunk-UQDH2COY.mjs +15296 -0
- package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +30778 -0
- package/build/backend-worker-chunks/pi-M4OA2FGL.mjs +5730 -0
- package/build/backend-worker.mjs +4401 -0
- package/dist/backend/fake/index.js +2 -0
- package/dist/backend/mcp.js +34 -15
- package/dist/backend/pi/state.js +18 -0
- package/dist/backend/registry.js +2 -1
- package/dist/backend/worker/claude-state.js +24 -3
- package/dist/backend/worker/entry.js +70 -13
- package/dist/backend/worker/frames.js +34 -0
- package/dist/backend/worker/index.js +139 -16
- package/dist/backend/worker/launcher.js +22 -3
- package/dist/backend/worker/sandbox-mcp.js +86 -0
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +7 -6
- package/dist/cli/install-guard.js +1 -1
- package/dist/cli/main.js +3 -6
- package/dist/cli/update.js +3 -3
- package/dist/cli/web-update.js +9 -6
- package/dist/client/connection.js +5 -2
- package/dist/client/diff.js +6 -9
- package/dist/client/reduce.js +19 -0
- package/dist/client/tool-chains.js +12 -4
- package/dist/daemon/config-store.js +21 -14
- package/dist/daemon/config.js +48 -5
- package/dist/daemon/git.js +47 -0
- package/dist/daemon/host.js +208 -29
- package/dist/daemon/models.js +27 -24
- package/dist/daemon/release-checker.js +48 -34
- package/dist/daemon/runtime.js +10 -4
- package/dist/daemon/server.js +13 -1
- package/dist/daemon/shell.js +2 -1
- package/dist/daemon/skills.js +34 -31
- package/dist/daemon/summariser.js +33 -14
- package/dist/daemon/timings.js +14 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +5 -26
- package/dist/daemon/workflow-authoring-scope-reader.js +20 -9
- package/dist/daemon/workflow-builder-files.js +5 -5
- package/dist/daemon/workflow-builder-guidance.js +3 -3
- package/dist/daemon/workflow-builder-reader.js +21 -10
- package/dist/daemon/workflow-builder.js +66 -8
- package/dist/daemon/workflow-executions.js +10 -10
- package/dist/daemon/workflow-mcp-authoring-routes.js +18 -6
- package/dist/daemon/workflow-mcp-authoring.js +50 -23
- package/dist/isolation/filesystem.js +8 -9
- package/dist/isolation/sandbox-supervisor.js +50 -0
- package/dist/isolation/sandbox.js +165 -0
- package/dist/isolation/shared-sandbox.js +77 -0
- package/dist/workflows/executors.js +16 -4
- package/dist/workflows/json-schema.js +14 -4
- package/package.json +7 -4
- package/web/dist/assets/index-CiEgCpiO.js +40 -0
- package/web/dist/assets/index-ClwLFMZN.css +2 -0
- package/web/dist/assets/settings-mcp-CoRWT-D_.js +1 -0
- package/web/dist/assets/settings-secrets-BIO_hXZ1.js +1 -0
- package/web/dist/assets/settings-workflows-BXbj0TKs.js +23 -0
- package/web/dist/assets/switch-DIogWclb.js +1 -0
- package/web/dist/assets/workflow-api-BfExddae.js +6 -0
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +139 -0
- package/web/dist/assets/workflows-Bv0sj7d0.js +7 -0
- package/web/dist/assets/workflows-pane-C_Yg4pgr.js +1 -0
- package/web/dist/index.html +5 -5
- package/web/dist/assets/index-C_M0oDHN.js +0 -38
- package/web/dist/assets/index-D8CGXp1X.css +0 -2
- package/web/dist/assets/input-D9fbSfQF.js +0 -6
- package/web/dist/assets/settings-mcp-BvSvGrcs.js +0 -1
- package/web/dist/assets/settings-secrets-DlkU6W_Z.js +0 -1
- package/web/dist/assets/settings-workflows-DNGE-b_U.js +0 -23
- package/web/dist/assets/switch-DEvHojwW.js +0 -1
- package/web/dist/assets/workflow-editors-D6XT6pcb.js +0 -137
- package/web/dist/assets/workflows-LSCnXIxN.js +0 -7
- package/web/dist/assets/workflows-pane-BIlp7uyg.js +0 -1
|
@@ -0,0 +1,4401 @@
|
|
|
1
|
+
import { createRequire as __flowCreateRequire } from 'node:module'; const require = __flowCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
AjvJsonSchemaValidator,
|
|
4
|
+
AutoPermissionUnavailable,
|
|
5
|
+
CallToolResultSchema,
|
|
6
|
+
CompleteResultSchema,
|
|
7
|
+
CreateMessageRequestSchema,
|
|
8
|
+
CreateMessageResultSchema,
|
|
9
|
+
CreateMessageResultWithToolsSchema,
|
|
10
|
+
CreateTaskResultSchema,
|
|
11
|
+
ElicitRequestSchema,
|
|
12
|
+
ElicitResultSchema,
|
|
13
|
+
EmptyResultSchema,
|
|
14
|
+
ErrorCode,
|
|
15
|
+
GetPromptResultSchema,
|
|
16
|
+
InitializeResultSchema,
|
|
17
|
+
JSONRPCMessageSchema,
|
|
18
|
+
LATEST_PROTOCOL_VERSION,
|
|
19
|
+
ListChangedOptionsBaseSchema,
|
|
20
|
+
ListPromptsResultSchema,
|
|
21
|
+
ListResourceTemplatesResultSchema,
|
|
22
|
+
ListResourcesResultSchema,
|
|
23
|
+
ListToolsResultSchema,
|
|
24
|
+
McpError,
|
|
25
|
+
PromptListChangedNotificationSchema,
|
|
26
|
+
Protocol,
|
|
27
|
+
ReadResourceResultSchema,
|
|
28
|
+
ResourceListChangedNotificationSchema,
|
|
29
|
+
SUPPORTED_PROTOCOL_VERSIONS,
|
|
30
|
+
ToolListChangedNotificationSchema,
|
|
31
|
+
assertClientRequestTaskCapability,
|
|
32
|
+
assertToolsCallTaskCapability,
|
|
33
|
+
getLiteralValue,
|
|
34
|
+
getObjectShape,
|
|
35
|
+
isInitializedNotification,
|
|
36
|
+
isJSONRPCRequest,
|
|
37
|
+
isJSONRPCResultResponse,
|
|
38
|
+
mergeCapabilities,
|
|
39
|
+
safeParse
|
|
40
|
+
} from "./backend-worker-chunks/chunk-UQDH2COY.mjs";
|
|
41
|
+
import {
|
|
42
|
+
NEVER,
|
|
43
|
+
ZodIssueCode,
|
|
44
|
+
__commonJS,
|
|
45
|
+
__require,
|
|
46
|
+
__toESM,
|
|
47
|
+
any,
|
|
48
|
+
array,
|
|
49
|
+
boolean,
|
|
50
|
+
coerce_exports,
|
|
51
|
+
literal,
|
|
52
|
+
looseObject,
|
|
53
|
+
number,
|
|
54
|
+
object,
|
|
55
|
+
string,
|
|
56
|
+
url
|
|
57
|
+
} from "./backend-worker-chunks/chunk-MLOUI3ZM.mjs";
|
|
58
|
+
|
|
59
|
+
// node_modules/isexe/windows.js
|
|
60
|
+
var require_windows = __commonJS({
|
|
61
|
+
"node_modules/isexe/windows.js"(exports, module) {
|
|
62
|
+
module.exports = isexe;
|
|
63
|
+
isexe.sync = sync;
|
|
64
|
+
var fs = __require("fs");
|
|
65
|
+
function checkPathExt(path, options) {
|
|
66
|
+
var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
|
|
67
|
+
if (!pathext) {
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
pathext = pathext.split(";");
|
|
71
|
+
if (pathext.indexOf("") !== -1) {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
for (var i = 0; i < pathext.length; i++) {
|
|
75
|
+
var p = pathext[i].toLowerCase();
|
|
76
|
+
if (p && path.substr(-p.length).toLowerCase() === p) {
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
function checkStat(stat, path, options) {
|
|
83
|
+
if (!stat.isSymbolicLink() && !stat.isFile()) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
return checkPathExt(path, options);
|
|
87
|
+
}
|
|
88
|
+
function isexe(path, options, cb) {
|
|
89
|
+
fs.stat(path, function(er, stat) {
|
|
90
|
+
cb(er, er ? false : checkStat(stat, path, options));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
function sync(path, options) {
|
|
94
|
+
return checkStat(fs.statSync(path), path, options);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// node_modules/isexe/mode.js
|
|
100
|
+
var require_mode = __commonJS({
|
|
101
|
+
"node_modules/isexe/mode.js"(exports, module) {
|
|
102
|
+
module.exports = isexe;
|
|
103
|
+
isexe.sync = sync;
|
|
104
|
+
var fs = __require("fs");
|
|
105
|
+
function isexe(path, options, cb) {
|
|
106
|
+
fs.stat(path, function(er, stat) {
|
|
107
|
+
cb(er, er ? false : checkStat(stat, options));
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
function sync(path, options) {
|
|
111
|
+
return checkStat(fs.statSync(path), options);
|
|
112
|
+
}
|
|
113
|
+
function checkStat(stat, options) {
|
|
114
|
+
return stat.isFile() && checkMode(stat, options);
|
|
115
|
+
}
|
|
116
|
+
function checkMode(stat, options) {
|
|
117
|
+
var mod = stat.mode;
|
|
118
|
+
var uid = stat.uid;
|
|
119
|
+
var gid = stat.gid;
|
|
120
|
+
var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
|
|
121
|
+
var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
|
|
122
|
+
var u = parseInt("100", 8);
|
|
123
|
+
var g = parseInt("010", 8);
|
|
124
|
+
var o = parseInt("001", 8);
|
|
125
|
+
var ug = u | g;
|
|
126
|
+
var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
|
|
127
|
+
return ret;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
// node_modules/isexe/index.js
|
|
133
|
+
var require_isexe = __commonJS({
|
|
134
|
+
"node_modules/isexe/index.js"(exports, module) {
|
|
135
|
+
var fs = __require("fs");
|
|
136
|
+
var core;
|
|
137
|
+
if (process.platform === "win32" || global.TESTING_WINDOWS) {
|
|
138
|
+
core = require_windows();
|
|
139
|
+
} else {
|
|
140
|
+
core = require_mode();
|
|
141
|
+
}
|
|
142
|
+
module.exports = isexe;
|
|
143
|
+
isexe.sync = sync;
|
|
144
|
+
function isexe(path, options, cb) {
|
|
145
|
+
if (typeof options === "function") {
|
|
146
|
+
cb = options;
|
|
147
|
+
options = {};
|
|
148
|
+
}
|
|
149
|
+
if (!cb) {
|
|
150
|
+
if (typeof Promise !== "function") {
|
|
151
|
+
throw new TypeError("callback not provided");
|
|
152
|
+
}
|
|
153
|
+
return new Promise(function(resolve4, reject) {
|
|
154
|
+
isexe(path, options || {}, function(er, is) {
|
|
155
|
+
if (er) {
|
|
156
|
+
reject(er);
|
|
157
|
+
} else {
|
|
158
|
+
resolve4(is);
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
core(path, options || {}, function(er, is) {
|
|
164
|
+
if (er) {
|
|
165
|
+
if (er.code === "EACCES" || options && options.ignoreErrors) {
|
|
166
|
+
er = null;
|
|
167
|
+
is = false;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
cb(er, is);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
function sync(path, options) {
|
|
174
|
+
try {
|
|
175
|
+
return core.sync(path, options || {});
|
|
176
|
+
} catch (er) {
|
|
177
|
+
if (options && options.ignoreErrors || er.code === "EACCES") {
|
|
178
|
+
return false;
|
|
179
|
+
} else {
|
|
180
|
+
throw er;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
// node_modules/which/which.js
|
|
188
|
+
var require_which = __commonJS({
|
|
189
|
+
"node_modules/which/which.js"(exports, module) {
|
|
190
|
+
var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
|
|
191
|
+
var path = __require("path");
|
|
192
|
+
var COLON = isWindows ? ";" : ":";
|
|
193
|
+
var isexe = require_isexe();
|
|
194
|
+
var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
|
|
195
|
+
var getPathInfo = (cmd, opt) => {
|
|
196
|
+
const colon = opt.colon || COLON;
|
|
197
|
+
const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
|
|
198
|
+
// windows always checks the cwd first
|
|
199
|
+
...isWindows ? [process.cwd()] : [],
|
|
200
|
+
...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
|
|
201
|
+
"").split(colon)
|
|
202
|
+
];
|
|
203
|
+
const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
|
|
204
|
+
const pathExt = isWindows ? pathExtExe.split(colon) : [""];
|
|
205
|
+
if (isWindows) {
|
|
206
|
+
if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
|
|
207
|
+
pathExt.unshift("");
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
pathEnv,
|
|
211
|
+
pathExt,
|
|
212
|
+
pathExtExe
|
|
213
|
+
};
|
|
214
|
+
};
|
|
215
|
+
var which = (cmd, opt, cb) => {
|
|
216
|
+
if (typeof opt === "function") {
|
|
217
|
+
cb = opt;
|
|
218
|
+
opt = {};
|
|
219
|
+
}
|
|
220
|
+
if (!opt)
|
|
221
|
+
opt = {};
|
|
222
|
+
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
|
|
223
|
+
const found = [];
|
|
224
|
+
const step = (i) => new Promise((resolve4, reject) => {
|
|
225
|
+
if (i === pathEnv.length)
|
|
226
|
+
return opt.all && found.length ? resolve4(found) : reject(getNotFoundError(cmd));
|
|
227
|
+
const ppRaw = pathEnv[i];
|
|
228
|
+
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
229
|
+
const pCmd = path.join(pathPart, cmd);
|
|
230
|
+
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
231
|
+
resolve4(subStep(p, i, 0));
|
|
232
|
+
});
|
|
233
|
+
const subStep = (p, i, ii) => new Promise((resolve4, reject) => {
|
|
234
|
+
if (ii === pathExt.length)
|
|
235
|
+
return resolve4(step(i + 1));
|
|
236
|
+
const ext = pathExt[ii];
|
|
237
|
+
isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
|
|
238
|
+
if (!er && is) {
|
|
239
|
+
if (opt.all)
|
|
240
|
+
found.push(p + ext);
|
|
241
|
+
else
|
|
242
|
+
return resolve4(p + ext);
|
|
243
|
+
}
|
|
244
|
+
return resolve4(subStep(p, i, ii + 1));
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
|
|
248
|
+
};
|
|
249
|
+
var whichSync = (cmd, opt) => {
|
|
250
|
+
opt = opt || {};
|
|
251
|
+
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
|
|
252
|
+
const found = [];
|
|
253
|
+
for (let i = 0; i < pathEnv.length; i++) {
|
|
254
|
+
const ppRaw = pathEnv[i];
|
|
255
|
+
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
256
|
+
const pCmd = path.join(pathPart, cmd);
|
|
257
|
+
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
258
|
+
for (let j = 0; j < pathExt.length; j++) {
|
|
259
|
+
const cur = p + pathExt[j];
|
|
260
|
+
try {
|
|
261
|
+
const is = isexe.sync(cur, { pathExt: pathExtExe });
|
|
262
|
+
if (is) {
|
|
263
|
+
if (opt.all)
|
|
264
|
+
found.push(cur);
|
|
265
|
+
else
|
|
266
|
+
return cur;
|
|
267
|
+
}
|
|
268
|
+
} catch (ex) {
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (opt.all && found.length)
|
|
273
|
+
return found;
|
|
274
|
+
if (opt.nothrow)
|
|
275
|
+
return null;
|
|
276
|
+
throw getNotFoundError(cmd);
|
|
277
|
+
};
|
|
278
|
+
module.exports = which;
|
|
279
|
+
which.sync = whichSync;
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
// node_modules/path-key/index.js
|
|
284
|
+
var require_path_key = __commonJS({
|
|
285
|
+
"node_modules/path-key/index.js"(exports, module) {
|
|
286
|
+
"use strict";
|
|
287
|
+
var pathKey = (options = {}) => {
|
|
288
|
+
const environment = options.env || process.env;
|
|
289
|
+
const platform = options.platform || process.platform;
|
|
290
|
+
if (platform !== "win32") {
|
|
291
|
+
return "PATH";
|
|
292
|
+
}
|
|
293
|
+
return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
|
|
294
|
+
};
|
|
295
|
+
module.exports = pathKey;
|
|
296
|
+
module.exports.default = pathKey;
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
// node_modules/cross-spawn/lib/util/resolveCommand.js
|
|
301
|
+
var require_resolveCommand = __commonJS({
|
|
302
|
+
"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
|
|
303
|
+
"use strict";
|
|
304
|
+
var path = __require("path");
|
|
305
|
+
var which = require_which();
|
|
306
|
+
var getPathKey = require_path_key();
|
|
307
|
+
function resolveCommandAttempt(parsed, withoutPathExt) {
|
|
308
|
+
const env = parsed.options.env || process.env;
|
|
309
|
+
const cwd = process.cwd();
|
|
310
|
+
const hasCustomCwd = parsed.options.cwd != null;
|
|
311
|
+
const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
|
|
312
|
+
if (shouldSwitchCwd) {
|
|
313
|
+
try {
|
|
314
|
+
process.chdir(parsed.options.cwd);
|
|
315
|
+
} catch (err) {
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
let resolved;
|
|
319
|
+
try {
|
|
320
|
+
resolved = which.sync(parsed.command, {
|
|
321
|
+
path: env[getPathKey({ env })],
|
|
322
|
+
pathExt: withoutPathExt ? path.delimiter : void 0
|
|
323
|
+
});
|
|
324
|
+
} catch (e) {
|
|
325
|
+
} finally {
|
|
326
|
+
if (shouldSwitchCwd) {
|
|
327
|
+
process.chdir(cwd);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (resolved) {
|
|
331
|
+
resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
|
|
332
|
+
}
|
|
333
|
+
return resolved;
|
|
334
|
+
}
|
|
335
|
+
function resolveCommand(parsed) {
|
|
336
|
+
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
|
|
337
|
+
}
|
|
338
|
+
module.exports = resolveCommand;
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
// node_modules/cross-spawn/lib/util/escape.js
|
|
343
|
+
var require_escape = __commonJS({
|
|
344
|
+
"node_modules/cross-spawn/lib/util/escape.js"(exports, module) {
|
|
345
|
+
"use strict";
|
|
346
|
+
var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
|
|
347
|
+
function escapeCommand(arg) {
|
|
348
|
+
arg = arg.replace(metaCharsRegExp, "^$1");
|
|
349
|
+
return arg;
|
|
350
|
+
}
|
|
351
|
+
function escapeArgument(arg, doubleEscapeMetaChars) {
|
|
352
|
+
arg = `${arg}`;
|
|
353
|
+
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
|
|
354
|
+
arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
|
|
355
|
+
arg = `"${arg}"`;
|
|
356
|
+
arg = arg.replace(metaCharsRegExp, "^$1");
|
|
357
|
+
if (doubleEscapeMetaChars) {
|
|
358
|
+
arg = arg.replace(metaCharsRegExp, "^$1");
|
|
359
|
+
}
|
|
360
|
+
return arg;
|
|
361
|
+
}
|
|
362
|
+
module.exports.command = escapeCommand;
|
|
363
|
+
module.exports.argument = escapeArgument;
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
// node_modules/shebang-regex/index.js
|
|
368
|
+
var require_shebang_regex = __commonJS({
|
|
369
|
+
"node_modules/shebang-regex/index.js"(exports, module) {
|
|
370
|
+
"use strict";
|
|
371
|
+
module.exports = /^#!(.*)/;
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
// node_modules/shebang-command/index.js
|
|
376
|
+
var require_shebang_command = __commonJS({
|
|
377
|
+
"node_modules/shebang-command/index.js"(exports, module) {
|
|
378
|
+
"use strict";
|
|
379
|
+
var shebangRegex = require_shebang_regex();
|
|
380
|
+
module.exports = (string2 = "") => {
|
|
381
|
+
const match = string2.match(shebangRegex);
|
|
382
|
+
if (!match) {
|
|
383
|
+
return null;
|
|
384
|
+
}
|
|
385
|
+
const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
|
|
386
|
+
const binary = path.split("/").pop();
|
|
387
|
+
if (binary === "env") {
|
|
388
|
+
return argument;
|
|
389
|
+
}
|
|
390
|
+
return argument ? `${binary} ${argument}` : binary;
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
// node_modules/cross-spawn/lib/util/readShebang.js
|
|
396
|
+
var require_readShebang = __commonJS({
|
|
397
|
+
"node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
|
|
398
|
+
"use strict";
|
|
399
|
+
var fs = __require("fs");
|
|
400
|
+
var shebangCommand = require_shebang_command();
|
|
401
|
+
function readShebang(command) {
|
|
402
|
+
const size = 150;
|
|
403
|
+
const buffer = Buffer.alloc(size);
|
|
404
|
+
let fd;
|
|
405
|
+
try {
|
|
406
|
+
fd = fs.openSync(command, "r");
|
|
407
|
+
fs.readSync(fd, buffer, 0, size, 0);
|
|
408
|
+
fs.closeSync(fd);
|
|
409
|
+
} catch (e) {
|
|
410
|
+
}
|
|
411
|
+
return shebangCommand(buffer.toString());
|
|
412
|
+
}
|
|
413
|
+
module.exports = readShebang;
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
// node_modules/cross-spawn/lib/parse.js
|
|
418
|
+
var require_parse = __commonJS({
|
|
419
|
+
"node_modules/cross-spawn/lib/parse.js"(exports, module) {
|
|
420
|
+
"use strict";
|
|
421
|
+
var path = __require("path");
|
|
422
|
+
var resolveCommand = require_resolveCommand();
|
|
423
|
+
var escape = require_escape();
|
|
424
|
+
var readShebang = require_readShebang();
|
|
425
|
+
var isWin = process.platform === "win32";
|
|
426
|
+
var isExecutableRegExp = /\.(?:com|exe)$/i;
|
|
427
|
+
var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
|
|
428
|
+
function detectShebang(parsed) {
|
|
429
|
+
parsed.file = resolveCommand(parsed);
|
|
430
|
+
const shebang = parsed.file && readShebang(parsed.file);
|
|
431
|
+
if (shebang) {
|
|
432
|
+
parsed.args.unshift(parsed.file);
|
|
433
|
+
parsed.command = shebang;
|
|
434
|
+
return resolveCommand(parsed);
|
|
435
|
+
}
|
|
436
|
+
return parsed.file;
|
|
437
|
+
}
|
|
438
|
+
function parseNonShell(parsed) {
|
|
439
|
+
if (!isWin) {
|
|
440
|
+
return parsed;
|
|
441
|
+
}
|
|
442
|
+
const commandFile = detectShebang(parsed);
|
|
443
|
+
const needsShell = !isExecutableRegExp.test(commandFile);
|
|
444
|
+
if (parsed.options.forceShell || needsShell) {
|
|
445
|
+
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
|
|
446
|
+
parsed.command = path.normalize(parsed.command);
|
|
447
|
+
parsed.command = escape.command(parsed.command);
|
|
448
|
+
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
|
|
449
|
+
const shellCommand = [parsed.command].concat(parsed.args).join(" ");
|
|
450
|
+
parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
|
|
451
|
+
parsed.command = process.env.comspec || "cmd.exe";
|
|
452
|
+
parsed.options.windowsVerbatimArguments = true;
|
|
453
|
+
}
|
|
454
|
+
return parsed;
|
|
455
|
+
}
|
|
456
|
+
function parse(command, args, options) {
|
|
457
|
+
if (args && !Array.isArray(args)) {
|
|
458
|
+
options = args;
|
|
459
|
+
args = null;
|
|
460
|
+
}
|
|
461
|
+
args = args ? args.slice(0) : [];
|
|
462
|
+
options = Object.assign({}, options);
|
|
463
|
+
const parsed = {
|
|
464
|
+
command,
|
|
465
|
+
args,
|
|
466
|
+
options,
|
|
467
|
+
file: void 0,
|
|
468
|
+
original: {
|
|
469
|
+
command,
|
|
470
|
+
args
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
return options.shell ? parsed : parseNonShell(parsed);
|
|
474
|
+
}
|
|
475
|
+
module.exports = parse;
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
// node_modules/cross-spawn/lib/enoent.js
|
|
480
|
+
var require_enoent = __commonJS({
|
|
481
|
+
"node_modules/cross-spawn/lib/enoent.js"(exports, module) {
|
|
482
|
+
"use strict";
|
|
483
|
+
var isWin = process.platform === "win32";
|
|
484
|
+
function notFoundError(original, syscall) {
|
|
485
|
+
return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
|
|
486
|
+
code: "ENOENT",
|
|
487
|
+
errno: "ENOENT",
|
|
488
|
+
syscall: `${syscall} ${original.command}`,
|
|
489
|
+
path: original.command,
|
|
490
|
+
spawnargs: original.args
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
function hookChildProcess(cp, parsed) {
|
|
494
|
+
if (!isWin) {
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
const originalEmit = cp.emit;
|
|
498
|
+
cp.emit = function(name, arg1) {
|
|
499
|
+
if (name === "exit") {
|
|
500
|
+
const err = verifyENOENT(arg1, parsed);
|
|
501
|
+
if (err) {
|
|
502
|
+
return originalEmit.call(cp, "error", err);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
return originalEmit.apply(cp, arguments);
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
function verifyENOENT(status, parsed) {
|
|
509
|
+
if (isWin && status === 1 && !parsed.file) {
|
|
510
|
+
return notFoundError(parsed.original, "spawn");
|
|
511
|
+
}
|
|
512
|
+
return null;
|
|
513
|
+
}
|
|
514
|
+
function verifyENOENTSync(status, parsed) {
|
|
515
|
+
if (isWin && status === 1 && !parsed.file) {
|
|
516
|
+
return notFoundError(parsed.original, "spawnSync");
|
|
517
|
+
}
|
|
518
|
+
return null;
|
|
519
|
+
}
|
|
520
|
+
module.exports = {
|
|
521
|
+
hookChildProcess,
|
|
522
|
+
verifyENOENT,
|
|
523
|
+
verifyENOENTSync,
|
|
524
|
+
notFoundError
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
// node_modules/cross-spawn/index.js
|
|
530
|
+
var require_cross_spawn = __commonJS({
|
|
531
|
+
"node_modules/cross-spawn/index.js"(exports, module) {
|
|
532
|
+
"use strict";
|
|
533
|
+
var cp = __require("child_process");
|
|
534
|
+
var parse = require_parse();
|
|
535
|
+
var enoent = require_enoent();
|
|
536
|
+
function spawn5(command, args, options) {
|
|
537
|
+
const parsed = parse(command, args, options);
|
|
538
|
+
const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
|
|
539
|
+
enoent.hookChildProcess(spawned, parsed);
|
|
540
|
+
return spawned;
|
|
541
|
+
}
|
|
542
|
+
function spawnSync(command, args, options) {
|
|
543
|
+
const parsed = parse(command, args, options);
|
|
544
|
+
const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
|
|
545
|
+
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
|
|
546
|
+
return result;
|
|
547
|
+
}
|
|
548
|
+
module.exports = spawn5;
|
|
549
|
+
module.exports.spawn = spawn5;
|
|
550
|
+
module.exports.sync = spawnSync;
|
|
551
|
+
module.exports._parse = parse;
|
|
552
|
+
module.exports._enoent = enoent;
|
|
553
|
+
}
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
// node_modules/content-type/index.js
|
|
557
|
+
var require_content_type = __commonJS({
|
|
558
|
+
"node_modules/content-type/index.js"(exports) {
|
|
559
|
+
"use strict";
|
|
560
|
+
var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
|
|
561
|
+
var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/;
|
|
562
|
+
var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
563
|
+
var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
|
|
564
|
+
var QUOTE_REGEXP = /([\\"])/g;
|
|
565
|
+
var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
566
|
+
exports.format = format;
|
|
567
|
+
exports.parse = parse;
|
|
568
|
+
function format(obj) {
|
|
569
|
+
if (!obj || typeof obj !== "object") {
|
|
570
|
+
throw new TypeError("argument obj is required");
|
|
571
|
+
}
|
|
572
|
+
var parameters = obj.parameters;
|
|
573
|
+
var type = obj.type;
|
|
574
|
+
if (!type || !TYPE_REGEXP.test(type)) {
|
|
575
|
+
throw new TypeError("invalid type");
|
|
576
|
+
}
|
|
577
|
+
var string2 = type;
|
|
578
|
+
if (parameters && typeof parameters === "object") {
|
|
579
|
+
var param;
|
|
580
|
+
var params = Object.keys(parameters).sort();
|
|
581
|
+
for (var i = 0; i < params.length; i++) {
|
|
582
|
+
param = params[i];
|
|
583
|
+
if (!TOKEN_REGEXP.test(param)) {
|
|
584
|
+
throw new TypeError("invalid parameter name");
|
|
585
|
+
}
|
|
586
|
+
string2 += "; " + param + "=" + qstring(parameters[param]);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
return string2;
|
|
590
|
+
}
|
|
591
|
+
function parse(string2) {
|
|
592
|
+
if (!string2) {
|
|
593
|
+
throw new TypeError("argument string is required");
|
|
594
|
+
}
|
|
595
|
+
var header = typeof string2 === "object" ? getcontenttype(string2) : string2;
|
|
596
|
+
if (typeof header !== "string") {
|
|
597
|
+
throw new TypeError("argument string is required to be a string");
|
|
598
|
+
}
|
|
599
|
+
var index = header.indexOf(";");
|
|
600
|
+
var type = index !== -1 ? header.slice(0, index).trim() : header.trim();
|
|
601
|
+
if (!TYPE_REGEXP.test(type)) {
|
|
602
|
+
throw new TypeError("invalid media type");
|
|
603
|
+
}
|
|
604
|
+
var obj = new ContentType(type.toLowerCase());
|
|
605
|
+
if (index !== -1) {
|
|
606
|
+
var key;
|
|
607
|
+
var match;
|
|
608
|
+
var value;
|
|
609
|
+
PARAM_REGEXP.lastIndex = index;
|
|
610
|
+
while (match = PARAM_REGEXP.exec(header)) {
|
|
611
|
+
if (match.index !== index) {
|
|
612
|
+
throw new TypeError("invalid parameter format");
|
|
613
|
+
}
|
|
614
|
+
index += match[0].length;
|
|
615
|
+
key = match[1].toLowerCase();
|
|
616
|
+
value = match[2];
|
|
617
|
+
if (value.charCodeAt(0) === 34) {
|
|
618
|
+
value = value.slice(1, -1);
|
|
619
|
+
if (value.indexOf("\\") !== -1) {
|
|
620
|
+
value = value.replace(QESC_REGEXP, "$1");
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
obj.parameters[key] = value;
|
|
624
|
+
}
|
|
625
|
+
if (index !== header.length) {
|
|
626
|
+
throw new TypeError("invalid parameter format");
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
return obj;
|
|
630
|
+
}
|
|
631
|
+
function getcontenttype(obj) {
|
|
632
|
+
var header;
|
|
633
|
+
if (typeof obj.getHeader === "function") {
|
|
634
|
+
header = obj.getHeader("content-type");
|
|
635
|
+
} else if (typeof obj.headers === "object") {
|
|
636
|
+
header = obj.headers && obj.headers["content-type"];
|
|
637
|
+
}
|
|
638
|
+
if (typeof header !== "string") {
|
|
639
|
+
throw new TypeError("content-type header is missing from object");
|
|
640
|
+
}
|
|
641
|
+
return header;
|
|
642
|
+
}
|
|
643
|
+
function qstring(val) {
|
|
644
|
+
var str = String(val);
|
|
645
|
+
if (TOKEN_REGEXP.test(str)) {
|
|
646
|
+
return str;
|
|
647
|
+
}
|
|
648
|
+
if (str.length > 0 && !TEXT_REGEXP.test(str)) {
|
|
649
|
+
throw new TypeError("invalid parameter value");
|
|
650
|
+
}
|
|
651
|
+
return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"';
|
|
652
|
+
}
|
|
653
|
+
function ContentType(type) {
|
|
654
|
+
this.parameters = /* @__PURE__ */ Object.create(null);
|
|
655
|
+
this.type = type;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
// src/backend/mcp.ts
|
|
661
|
+
import { createHash } from "node:crypto";
|
|
662
|
+
import { closeSync as closeSync2, constants as constants2, existsSync as existsSync4, fstatSync as fstatSync2, openSync as openSync2, realpathSync as realpathSync4, statSync as statSync4 } from "node:fs";
|
|
663
|
+
import { dirname as dirname4, join as join4, resolve as resolve3 } from "node:path";
|
|
664
|
+
|
|
665
|
+
// src/isolation/filesystem.ts
|
|
666
|
+
import { spawn } from "node:child_process";
|
|
667
|
+
import { closeSync, constants, existsSync as existsSync3, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync as realpathSync3, rmSync, statSync as statSync3, writeFileSync } from "node:fs";
|
|
668
|
+
import { access } from "node:fs/promises";
|
|
669
|
+
import { homedir } from "node:os";
|
|
670
|
+
import { basename as basename3, dirname as dirname3, isAbsolute as isAbsolute2, join as join3, relative, resolve as resolve2, sep } from "node:path";
|
|
671
|
+
|
|
672
|
+
// src/isolation/toolchain-assets.ts
|
|
673
|
+
import { existsSync as existsSync2, readdirSync as readdirSync2, realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
|
|
674
|
+
import { basename as basename2, dirname as dirname2, isAbsolute, join as join2, resolve } from "node:path";
|
|
675
|
+
|
|
676
|
+
// src/isolation/node-assets.ts
|
|
677
|
+
import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
678
|
+
import { basename, dirname, join } from "node:path";
|
|
679
|
+
function nodeExecutionAssets(entries) {
|
|
680
|
+
const assets = /* @__PURE__ */ new Set();
|
|
681
|
+
const searched = /* @__PURE__ */ new Set();
|
|
682
|
+
const trees = /* @__PURE__ */ new Set();
|
|
683
|
+
const pending = [];
|
|
684
|
+
const addTree = (path) => {
|
|
685
|
+
if (!existsSync(path)) return;
|
|
686
|
+
const canonical2 = realpathSync(path);
|
|
687
|
+
if (!statSync(canonical2).isDirectory()) return;
|
|
688
|
+
assets.add(path);
|
|
689
|
+
assets.add(canonical2);
|
|
690
|
+
if (!trees.has(canonical2)) {
|
|
691
|
+
trees.add(canonical2);
|
|
692
|
+
pending.push(canonical2);
|
|
693
|
+
search(canonical2);
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
const search = (entry) => {
|
|
697
|
+
const canonical2 = realpathSync(entry);
|
|
698
|
+
const directory = statSync(canonical2).isDirectory() ? canonical2 : dirname(canonical2);
|
|
699
|
+
if (searched.has(directory)) return;
|
|
700
|
+
searched.add(directory);
|
|
701
|
+
for (let ancestor = directory; ; ancestor = dirname(ancestor)) {
|
|
702
|
+
if (basename(ancestor) !== "node_modules") addTree(join(ancestor, "node_modules"));
|
|
703
|
+
if (ancestor === dirname(ancestor)) break;
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
for (const entry of entries) search(entry);
|
|
707
|
+
const visitPackage = (path) => {
|
|
708
|
+
if (!existsSync(path)) return;
|
|
709
|
+
const canonical2 = realpathSync(path);
|
|
710
|
+
if (!statSync(canonical2).isDirectory()) return;
|
|
711
|
+
if (canonical2 !== path) {
|
|
712
|
+
assets.add(canonical2);
|
|
713
|
+
search(canonical2);
|
|
714
|
+
}
|
|
715
|
+
addTree(join(canonical2, "node_modules"));
|
|
716
|
+
};
|
|
717
|
+
for (let index = 0; index < pending.length; index++) {
|
|
718
|
+
const tree = pending[index];
|
|
719
|
+
for (const entry of readdirSync(tree, { withFileTypes: true })) {
|
|
720
|
+
if (entry.name.startsWith(".")) continue;
|
|
721
|
+
const path = join(tree, entry.name);
|
|
722
|
+
if (!existsSync(path)) continue;
|
|
723
|
+
if (entry.name.startsWith("@") && statSync(path).isDirectory()) {
|
|
724
|
+
const canonical2 = realpathSync(path);
|
|
725
|
+
if (canonical2 !== path) assets.add(canonical2);
|
|
726
|
+
for (const name of readdirSync(path)) visitPackage(join(path, name));
|
|
727
|
+
} else visitPackage(path);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return [...assets];
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// src/isolation/toolchain-assets.ts
|
|
734
|
+
function pathToolchainAssets(path, scope, hidden, protectedPath) {
|
|
735
|
+
const assets = /* @__PURE__ */ new Set();
|
|
736
|
+
const entries = path.split(":").map((entry) => {
|
|
737
|
+
const logical = isAbsolute(entry) ? entry : resolve(scope, entry || ".");
|
|
738
|
+
if (!existsSync2(logical) || !statSync2(logical).isDirectory()) return entry;
|
|
739
|
+
const directory = realpathSync2(logical);
|
|
740
|
+
if (protectedPath(directory)) return entry;
|
|
741
|
+
const masked = hidden(logical) || hidden(directory);
|
|
742
|
+
if (masked) assets.add(directory);
|
|
743
|
+
for (const entry2 of readdirSync2(directory, { withFileTypes: true })) {
|
|
744
|
+
if (!entry2.isSymbolicLink()) continue;
|
|
745
|
+
const candidate = join2(directory, entry2.name);
|
|
746
|
+
if (!existsSync2(candidate)) continue;
|
|
747
|
+
const target = realpathSync2(candidate);
|
|
748
|
+
if (!hidden(target) || protectedPath(target)) continue;
|
|
749
|
+
if (statSync2(target).isDirectory()) {
|
|
750
|
+
assets.add(target);
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
let root = dirname2(target);
|
|
754
|
+
for (let parent = root; parent !== dirname2(parent); parent = dirname2(parent)) {
|
|
755
|
+
if (existsSync2(join2(parent, "package.json"))) {
|
|
756
|
+
root = parent;
|
|
757
|
+
break;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
assets.add(root);
|
|
761
|
+
}
|
|
762
|
+
if (masked && basename2(directory) === "bin") {
|
|
763
|
+
const root = dirname2(directory);
|
|
764
|
+
if (existsSync2(join2(root, "pyvenv.cfg"))) assets.add(root);
|
|
765
|
+
else for (const name of ["lib", "lib64"]) {
|
|
766
|
+
const library = join2(root, name);
|
|
767
|
+
if (existsSync2(library) && statSync2(library).isDirectory() && hidden(library)) assets.add(realpathSync2(library));
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
return masked ? directory : entry;
|
|
771
|
+
});
|
|
772
|
+
const paths = [...assets];
|
|
773
|
+
return { path: entries.join(":"), assets: [...paths, ...nodeExecutionAssets(paths)] };
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// src/isolation/filesystem.ts
|
|
777
|
+
var virtualRoot = "/tmp/flow-isolation";
|
|
778
|
+
var virtualState = `${virtualRoot}/state`;
|
|
779
|
+
var virtualHome = `${virtualRoot}/home`;
|
|
780
|
+
function within(path, parent) {
|
|
781
|
+
const tail = relative(parent, path);
|
|
782
|
+
return tail === "" || tail !== ".." && !tail.startsWith(`..${sep}`) && !isAbsolute2(tail);
|
|
783
|
+
}
|
|
784
|
+
function canonical(path) {
|
|
785
|
+
const absolute = resolve2(path);
|
|
786
|
+
try {
|
|
787
|
+
return realpathSync3(absolute);
|
|
788
|
+
} catch (error) {
|
|
789
|
+
if (error.code !== "ENOENT") throw error;
|
|
790
|
+
const parent = dirname3(absolute);
|
|
791
|
+
if (parent === absolute) throw error;
|
|
792
|
+
return join3(canonical(parent), basename3(absolute));
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
function existingMask(path) {
|
|
796
|
+
while (!existsSync3(path)) {
|
|
797
|
+
const parent = dirname3(path);
|
|
798
|
+
if (parent === path) throw new Error(`Cannot mask protected path: ${path}`);
|
|
799
|
+
path = parent;
|
|
800
|
+
}
|
|
801
|
+
if (path === "/") throw new Error("Protected path has no safe existing ancestor");
|
|
802
|
+
return path;
|
|
803
|
+
}
|
|
804
|
+
function expandHome(path, home) {
|
|
805
|
+
return path === "~" ? home : path.startsWith("~/") ? join3(home, path.slice(2)) : path;
|
|
806
|
+
}
|
|
807
|
+
async function probeBoundary(command, args, env, fds) {
|
|
808
|
+
await new Promise((resolveProbe, reject) => {
|
|
809
|
+
const child = spawn(command, args, { env, stdio: ["ignore", "ignore", "pipe", ...fds] });
|
|
810
|
+
let stderr = "";
|
|
811
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), 1e4);
|
|
812
|
+
child.stderr?.on("data", (chunk) => {
|
|
813
|
+
stderr = (stderr + chunk.toString()).slice(-8192);
|
|
814
|
+
});
|
|
815
|
+
child.once("error", (error) => {
|
|
816
|
+
clearTimeout(timer);
|
|
817
|
+
reject(error);
|
|
818
|
+
});
|
|
819
|
+
child.once("close", (code, signal) => {
|
|
820
|
+
clearTimeout(timer);
|
|
821
|
+
if (code === 0) resolveProbe();
|
|
822
|
+
else reject(Object.assign(new Error("Boundary probe failed"), { code, signal, stderr }));
|
|
823
|
+
});
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
async function executable(command, env) {
|
|
827
|
+
const candidates = command.includes("/") ? [resolve2(command)] : (env.PATH ?? "/usr/bin:/bin").split(":").map((dir) => resolve2(dir, command));
|
|
828
|
+
for (const path of candidates) {
|
|
829
|
+
try {
|
|
830
|
+
await access(path, constants.X_OK);
|
|
831
|
+
if (statSync3(path).isFile()) return realpathSync3(path);
|
|
832
|
+
} catch {
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
throw new Error(`Executable not found: ${command}`);
|
|
836
|
+
}
|
|
837
|
+
function scrubEnvironment(inherited) {
|
|
838
|
+
const env = { ...inherited };
|
|
839
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(process.env), ...Object.keys(env)])) {
|
|
840
|
+
if (/^(FLOW_|LD_|DYLD_|XDG_|PI_SESSION_)/.test(key) || /^(NODE_OPTIONS|NODE_PATH|BASH_ENV|ENV|ZDOTDIR|TMPDIR|TMP|TEMP|PI_CODING_AGENT_DIR|PI_CODING_AGENT_SESSION_DIR|CLAUDE_CONFIG_DIR|CLAUDE_SECURESTORAGE_CONFIG_DIR|SSH_AUTH_SOCK|SSH_AGENT_PID|DBUS_SESSION_BUS_ADDRESS|DOCKER_HOST|CONTAINER_HOST|NODE_CHANNEL_FD|NODE_CHANNEL_SERIALIZATION_MODE)$/.test(key)) {
|
|
841
|
+
env[key] = void 0;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
Object.assign(env, {
|
|
845
|
+
HOME: virtualHome,
|
|
846
|
+
TMPDIR: "/tmp",
|
|
847
|
+
TMP: "/tmp",
|
|
848
|
+
TEMP: "/tmp",
|
|
849
|
+
XDG_CONFIG_HOME: `${virtualHome}/.config`,
|
|
850
|
+
XDG_CACHE_HOME: `${virtualHome}/.cache`,
|
|
851
|
+
XDG_DATA_HOME: `${virtualHome}/.local/share`,
|
|
852
|
+
XDG_STATE_HOME: `${virtualHome}/.local/state`,
|
|
853
|
+
XDG_RUNTIME_DIR: `${virtualRoot}/run`,
|
|
854
|
+
PI_CODING_AGENT_DIR: `${virtualHome}/.pi/agent`,
|
|
855
|
+
PI_CODING_AGENT_SESSION_DIR: `${virtualState}/sessions`,
|
|
856
|
+
CLAUDE_CONFIG_DIR: `${virtualHome}/.claude`
|
|
857
|
+
});
|
|
858
|
+
return env;
|
|
859
|
+
}
|
|
860
|
+
function scopeContext(options) {
|
|
861
|
+
const inherited = { ...process.env, ...options.env };
|
|
862
|
+
const home = canonical(homedir());
|
|
863
|
+
const credentialHome = canonical(inherited.HOME ?? home);
|
|
864
|
+
const piDir = canonical(expandHome(inherited.PI_CODING_AGENT_DIR ?? join3(credentialHome, ".pi/agent"), credentialHome));
|
|
865
|
+
for (const key of ["CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR"]) {
|
|
866
|
+
if (inherited[key] && !isAbsolute2(inherited[key])) throw new Error(`${key} must be absolute when filesystem isolation is enabled`);
|
|
867
|
+
}
|
|
868
|
+
const claudeDir = canonical(inherited.CLAUDE_CONFIG_DIR || join3(credentialHome, ".claude"));
|
|
869
|
+
const authRoot = inherited.CLAUDE_SECURESTORAGE_CONFIG_DIR;
|
|
870
|
+
const claudeAuthDir = canonical(authRoot === void 0 ? claudeDir : authRoot || join3(credentialHome, ".claude"));
|
|
871
|
+
const flowRoots = [...new Set([join3(home, ".flow"), inherited.FLOW_STATE_DIR, process.env.FLOW_STATE_DIR, options.stateRoot].filter((path) => !!path).map(canonical))];
|
|
872
|
+
const runtimePaths = [process.env, inherited].flatMap((env) => {
|
|
873
|
+
const sockets = [
|
|
874
|
+
env.SSH_AUTH_SOCK,
|
|
875
|
+
...[env.DOCKER_HOST, env.CONTAINER_HOST].map((value) => value?.startsWith("unix://") ? value.slice(7) : void 0),
|
|
876
|
+
env.DBUS_SESSION_BUS_ADDRESS?.match(/(?:^|;)unix:path=([^,;]+)/)?.[1]
|
|
877
|
+
];
|
|
878
|
+
const runtime = env.XDG_RUNTIME_DIR;
|
|
879
|
+
return [...sockets, ...runtime && !["/tmp", "/var/tmp", "/run"].some((root) => within(canonical(runtime), canonical(root))) ? [runtime] : []].filter((path) => !!path && isAbsolute2(path));
|
|
880
|
+
});
|
|
881
|
+
const hostCredentials = [home, credentialHome].flatMap((root) => [
|
|
882
|
+
".ssh",
|
|
883
|
+
".gnupg",
|
|
884
|
+
".aws",
|
|
885
|
+
".azure",
|
|
886
|
+
".kube",
|
|
887
|
+
".docker",
|
|
888
|
+
".config/gcloud",
|
|
889
|
+
".local/share/keyrings",
|
|
890
|
+
".netrc",
|
|
891
|
+
".npmrc",
|
|
892
|
+
".git-credentials",
|
|
893
|
+
".git-credential-cache",
|
|
894
|
+
".cache/git/credential"
|
|
895
|
+
].map((name) => join3(root, name)));
|
|
896
|
+
const protectedPaths = [...new Set([
|
|
897
|
+
...flowRoots,
|
|
898
|
+
...hostCredentials,
|
|
899
|
+
...runtimePaths,
|
|
900
|
+
join3(home, ".pi/agent"),
|
|
901
|
+
join3(home, ".claude"),
|
|
902
|
+
join3(home, ".claude.json"),
|
|
903
|
+
piDir,
|
|
904
|
+
claudeDir,
|
|
905
|
+
claudeAuthDir,
|
|
906
|
+
join3(credentialHome, ".claude.json"),
|
|
907
|
+
...options.protectedPaths ?? []
|
|
908
|
+
].map(canonical))];
|
|
909
|
+
const scope = realpathSync3(options.scope);
|
|
910
|
+
if (options.expectedScope !== void 0 && scope !== resolve2(options.expectedScope)) {
|
|
911
|
+
throw new Error("Scope changed since selection; refusing redirected execution");
|
|
912
|
+
}
|
|
913
|
+
if (!statSync3(scope).isDirectory()) throw new Error("Scope must be a directory");
|
|
914
|
+
const launcher = inherited.FLOW_BWRAP_PATH ?? "/usr/bin/bwrap";
|
|
915
|
+
if (isAbsolute2(launcher) && within(canonical(launcher), scope) || within(canonical(process.execPath), scope)) {
|
|
916
|
+
throw new Error("Unsafe Scope: would expose a trusted launch executable");
|
|
917
|
+
}
|
|
918
|
+
const temporary = relative(canonical("/tmp"), scope).split(sep)[0];
|
|
919
|
+
if (/^flow-isolation-[A-Za-z0-9]{6}$/.test(temporary ?? "")) throw new Error("Unsafe Scope: private isolation staging path");
|
|
920
|
+
if (within(home, scope) || within(credentialHome, scope) || within(canonical("/tmp"), scope) || within(canonical(virtualRoot), scope) || within(scope, canonical(virtualRoot)) || ["/proc", "/sys", "/dev", "/run", "/var/run", "/var/tmp"].some((path) => within(scope, canonical(path)))) {
|
|
921
|
+
throw new Error("Unsafe Scope: root, home, or reserved isolation path");
|
|
922
|
+
}
|
|
923
|
+
for (const path of protectedPaths) {
|
|
924
|
+
if (within(path, scope)) throw new Error(`Scope would expose protected host state: ${path}`);
|
|
925
|
+
if (within(scope, path)) {
|
|
926
|
+
const worktree = join3(path, "worktrees");
|
|
927
|
+
if (!flowRoots.includes(path) || !within(scope, worktree) || relative(worktree, scope).split(sep).length < 2) {
|
|
928
|
+
throw new Error(`Scope is inside protected host state: ${path}`);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
return { inherited, home, credentialHome, piDir, claudeDir, claudeAuthDir, flowRoots, protectedPaths, scope };
|
|
933
|
+
}
|
|
934
|
+
async function prepareFilesystemIsolation(options) {
|
|
935
|
+
if (process.platform !== "linux") throw new Error("Filesystem isolation unavailable; unrestricted launch refused: requires Linux and Bubblewrap");
|
|
936
|
+
let scratch;
|
|
937
|
+
const sources = [];
|
|
938
|
+
const cleanup = () => {
|
|
939
|
+
try {
|
|
940
|
+
if (scratch) {
|
|
941
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
942
|
+
scratch = void 0;
|
|
943
|
+
}
|
|
944
|
+
} finally {
|
|
945
|
+
for (const fd of sources.splice(0)) closeSync(fd);
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
const pinned = (path, expectedIdentity) => {
|
|
949
|
+
const before = statSync3(path, { bigint: true });
|
|
950
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | (before.isDirectory() ? constants.O_DIRECTORY : 0));
|
|
951
|
+
sources.push(fd);
|
|
952
|
+
const after = fstatSync(fd, { bigint: true });
|
|
953
|
+
if (expectedIdentity !== void 0 && `${after.dev}:${after.ino}` !== expectedIdentity) {
|
|
954
|
+
throw new Error("Scope changed since selection; refusing replaced directory");
|
|
955
|
+
}
|
|
956
|
+
if (before.dev !== after.dev || before.ino !== after.ino || realpathSync3(`/proc/self/fd/${fd}`) !== path) {
|
|
957
|
+
throw new Error(`Execution mount source changed during preparation: ${path}`);
|
|
958
|
+
}
|
|
959
|
+
return String(3 + sources.length - 1);
|
|
960
|
+
};
|
|
961
|
+
try {
|
|
962
|
+
const { inherited, home, credentialHome, piDir, claudeDir, claudeAuthDir, flowRoots, protectedPaths, scope } = scopeContext(options);
|
|
963
|
+
const env = scrubEnvironment(inherited);
|
|
964
|
+
if (options.credentials === "claude" && inherited.FLOW_CLAUDE_PATH) env.FLOW_CLAUDE_PATH = inherited.FLOW_CLAUDE_PATH;
|
|
965
|
+
const launcher = inherited.FLOW_BWRAP_PATH ?? "/usr/bin/bwrap";
|
|
966
|
+
if (!isAbsolute2(launcher)) throw new Error("FLOW_BWRAP_PATH must be an absolute trusted executable path");
|
|
967
|
+
const bwrap = await executable(launcher, env);
|
|
968
|
+
if (within(bwrap, scope)) throw new Error("Unsafe Scope: would expose the trusted isolation launcher");
|
|
969
|
+
if (flowRoots.some((root) => /^sessions\/[^/]+\/backend(?:\/|$)/.test(relative(root, bwrap)) || within(bwrap, join3(root, "worktrees"))) || /^flow-isolation-[A-Za-z0-9]{6}(?:\/|$)/.test(relative(canonical("/tmp"), bwrap))) {
|
|
970
|
+
throw new Error("Trusted launch executable must be outside writable backend state and scratch");
|
|
971
|
+
}
|
|
972
|
+
const command = await executable(options.command, env);
|
|
973
|
+
const maskRoots = [...protectedPaths.map(existingMask), canonical("/tmp"), canonical("/var/tmp"), canonical("/run")];
|
|
974
|
+
const tools = pathToolchainAssets(
|
|
975
|
+
env.PATH ?? "/usr/bin:/bin",
|
|
976
|
+
scope,
|
|
977
|
+
(path) => maskRoots.some((root) => within(path, root)),
|
|
978
|
+
(path) => protectedPaths.some((root) => within(path, root)) || ["/var/tmp", "/run"].some((root) => within(path, canonical(root)))
|
|
979
|
+
);
|
|
980
|
+
env.PATH = tools.path;
|
|
981
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
982
|
+
const readable = [...new Set([
|
|
983
|
+
command,
|
|
984
|
+
...tools.assets,
|
|
985
|
+
...options.readablePaths ?? [],
|
|
986
|
+
...env.FLOW_CLAUDE_PATH ? [await executable(env.FLOW_CLAUDE_PATH, env)] : []
|
|
987
|
+
].map((asset) => {
|
|
988
|
+
const source = realpathSync3(asset);
|
|
989
|
+
let logical = sep;
|
|
990
|
+
for (const name of resolve2(asset).split(sep).filter(Boolean)) {
|
|
991
|
+
logical = join3(logical, name);
|
|
992
|
+
if (lstatSync(logical).isSymbolicLink()) {
|
|
993
|
+
const destination = join3(canonical(dirname3(logical)), basename3(logical));
|
|
994
|
+
aliases.set(destination, realpathSync3(logical));
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
return source;
|
|
998
|
+
}))];
|
|
999
|
+
const validateAsset = (path) => {
|
|
1000
|
+
if ([home, credentialHome, "/", ...["/tmp", "/var/tmp", "/run", "/var/run", "/proc", "/dev", "/sys"].map(canonical)].includes(path) || protectedPaths.some((secret) => within(path, secret) || within(secret, path)) || within(path, virtualRoot) || ["/proc", "/dev", "/sys", "/run", "/var/tmp"].some((root) => within(path, canonical(root)))) {
|
|
1001
|
+
throw new Error(`Readable execution asset would expose protected state: ${path}`);
|
|
1002
|
+
}
|
|
1003
|
+
};
|
|
1004
|
+
readable.forEach(validateAsset);
|
|
1005
|
+
scratch = mkdtempSync(join3(canonical("/tmp"), "flow-isolation-"));
|
|
1006
|
+
const backend = options.stateDir ? realpathSync3(options.stateDir) : join3(scratch, "backend");
|
|
1007
|
+
if (options.stateDir) {
|
|
1008
|
+
if (basename3(backend) !== "backend" || !statSync3(backend).isDirectory() || within(home, backend) || within(credentialHome, backend) || within(scope, backend) || within(backend, scope) || within(backend, virtualRoot) || within(virtualRoot, backend)) {
|
|
1009
|
+
throw new Error("stateDir must be a dedicated backend directory, separate from Scope");
|
|
1010
|
+
}
|
|
1011
|
+
for (const path of protectedPaths) {
|
|
1012
|
+
if (within(path, backend)) throw new Error("stateDir would widen access to protected host state");
|
|
1013
|
+
if (within(backend, path) && (!flowRoots.includes(path) || !/^sessions\/[^/]+\/backend$/.test(relative(path, backend)))) {
|
|
1014
|
+
throw new Error("Inside host state, stateDir must be sessions/<id>/backend, never sessions or secrets");
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
} else mkdirSync(backend, { mode: 448 });
|
|
1018
|
+
for (const trusted of [bwrap, canonical(process.execPath)]) {
|
|
1019
|
+
if ([backend, scratch].some((writable) => within(trusted, writable))) {
|
|
1020
|
+
throw new Error("Trusted launch executable must be outside writable backend state and scratch");
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
const args = [
|
|
1024
|
+
"--unshare-user",
|
|
1025
|
+
"--unshare-pid",
|
|
1026
|
+
"--unshare-ipc",
|
|
1027
|
+
"--unshare-uts",
|
|
1028
|
+
"--die-with-parent",
|
|
1029
|
+
"--new-session",
|
|
1030
|
+
"--cap-drop",
|
|
1031
|
+
"ALL",
|
|
1032
|
+
"--ro-bind",
|
|
1033
|
+
"/",
|
|
1034
|
+
"/",
|
|
1035
|
+
"--tmpfs",
|
|
1036
|
+
"/tmp",
|
|
1037
|
+
"--tmpfs",
|
|
1038
|
+
"/var/tmp",
|
|
1039
|
+
"--tmpfs",
|
|
1040
|
+
canonical("/run")
|
|
1041
|
+
];
|
|
1042
|
+
const masks = [...new Set([...protectedPaths, backend, scratch].filter((path) => !["/tmp", "/var/tmp", "/run"].some((root) => within(path, canonical(root)))).map(existingMask))].sort((a, b) => a.length - b.length).filter((path, index, paths) => !paths.slice(0, index).some((parent) => within(path, parent)));
|
|
1043
|
+
const directoryMasks = [];
|
|
1044
|
+
for (const path of masks) {
|
|
1045
|
+
if (statSync3(path).isDirectory()) {
|
|
1046
|
+
args.push("--tmpfs", path);
|
|
1047
|
+
directoryMasks.push(path);
|
|
1048
|
+
} else args.push("--ro-bind", "/dev/null", path);
|
|
1049
|
+
}
|
|
1050
|
+
for (const path of readable) {
|
|
1051
|
+
if ((within(path, canonical("/tmp")) || masks.some((mask) => within(path, mask))) && !within(path, scope)) args.push("--ro-bind-fd", pinned(path), path);
|
|
1052
|
+
}
|
|
1053
|
+
for (const [destination, source] of aliases) {
|
|
1054
|
+
if (!within(destination, scope) && (within(destination, canonical("/tmp")) || masks.some((mask) => within(destination, mask))) && !readable.some((parent) => within(destination, parent) && statSync3(parent).isDirectory())) {
|
|
1055
|
+
validateAsset(destination);
|
|
1056
|
+
validateAsset(source);
|
|
1057
|
+
args.push("--symlink", source, destination);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
const privateHome = join3(scratch, "home");
|
|
1061
|
+
mkdirSync(join3(privateHome, ".pi/agent"), { recursive: true, mode: 448 });
|
|
1062
|
+
mkdirSync(join3(privateHome, ".claude"), { mode: 448 });
|
|
1063
|
+
args.push(
|
|
1064
|
+
"--bind-fd",
|
|
1065
|
+
pinned(scope, options.expectedScopeIdentity),
|
|
1066
|
+
scope,
|
|
1067
|
+
"--dir",
|
|
1068
|
+
virtualRoot,
|
|
1069
|
+
"--bind-fd",
|
|
1070
|
+
pinned(privateHome),
|
|
1071
|
+
virtualHome,
|
|
1072
|
+
"--dir",
|
|
1073
|
+
`${virtualRoot}/run`,
|
|
1074
|
+
"--bind-fd",
|
|
1075
|
+
pinned(backend),
|
|
1076
|
+
virtualState
|
|
1077
|
+
);
|
|
1078
|
+
for (const path of directoryMasks) args.push("--remount-ro", path);
|
|
1079
|
+
const stage = (source, destination) => {
|
|
1080
|
+
if (!existsSync3(source)) return;
|
|
1081
|
+
if (!statSync3(source).isFile() || realpathSync3(source) !== resolve2(source)) {
|
|
1082
|
+
throw new Error(`Credential must be a regular, non-symlink file: ${source}`);
|
|
1083
|
+
}
|
|
1084
|
+
writeFileSync(join3(privateHome, relative(virtualHome, destination)), readFileSync(source), { mode: 384 });
|
|
1085
|
+
};
|
|
1086
|
+
const resources = (label, directory, destination, names) => {
|
|
1087
|
+
for (const name of names) {
|
|
1088
|
+
const source = join3(directory, name);
|
|
1089
|
+
if (!existsSync3(source)) continue;
|
|
1090
|
+
const asset = realpathSync3(source);
|
|
1091
|
+
if (asset !== source || protectedPaths.some((secret) => secret !== directory && (within(asset, secret) || within(secret, asset)))) throw new Error(`Unsafe ${label} resource: ${source}`);
|
|
1092
|
+
args.push("--ro-bind-fd", pinned(asset), join3(destination, name));
|
|
1093
|
+
}
|
|
1094
|
+
};
|
|
1095
|
+
if (options.credentials === "pi") {
|
|
1096
|
+
for (const name of ["auth.json", "models.json", "settings.json"]) stage(join3(piDir, name), join3(env.PI_CODING_AGENT_DIR, name));
|
|
1097
|
+
if (!options.workflowBuilder) resources("Pi", piDir, env.PI_CODING_AGENT_DIR, ["AGENTS.md", "skills", "prompts", "themes", "extensions", "packages", "bin", "tools"]);
|
|
1098
|
+
} else if (options.credentials === "claude") {
|
|
1099
|
+
stage(join3(claudeAuthDir, ".credentials.json"), join3(env.CLAUDE_CONFIG_DIR, ".credentials.json"));
|
|
1100
|
+
const config = existsSync3(join3(claudeDir, ".claude.json")) ? join3(claudeDir, ".claude.json") : join3(credentialHome, ".claude.json");
|
|
1101
|
+
stage(config, join3(virtualHome, ".claude.json"));
|
|
1102
|
+
stage(config, join3(env.CLAUDE_CONFIG_DIR, ".claude.json"));
|
|
1103
|
+
if (!options.workflowBuilder) resources("Claude", claudeDir, env.CLAUDE_CONFIG_DIR, ["CLAUDE.md", "commands", "skills", "agents", "rules", "plugins"]);
|
|
1104
|
+
const projects = join3(backend, "claude-projects");
|
|
1105
|
+
if (!existsSync3(projects)) mkdirSync(projects, { mode: 448 });
|
|
1106
|
+
if (!statSync3(projects).isDirectory() || realpathSync3(projects) !== projects) {
|
|
1107
|
+
throw new Error("Unsafe Claude backend transcript directory");
|
|
1108
|
+
}
|
|
1109
|
+
args.push("--bind-fd", pinned(projects), join3(env.CLAUDE_CONFIG_DIR, "projects"));
|
|
1110
|
+
}
|
|
1111
|
+
args.push("--proc", "/proc", "--remount-ro", "/proc", "--dev", "/dev");
|
|
1112
|
+
args.push("--clearenv");
|
|
1113
|
+
for (const [key, value] of Object.entries(env)) if (value !== void 0) args.push("--setenv", key, value);
|
|
1114
|
+
args.push("--chdir", scope);
|
|
1115
|
+
try {
|
|
1116
|
+
await probeBoundary(bwrap, [...args, "--", "/bin/true"], env, sources);
|
|
1117
|
+
} catch (error) {
|
|
1118
|
+
const failure = error;
|
|
1119
|
+
throw new Error(`Bubblewrap namespace/mount probe failed (${failure.signal ?? failure.code ?? "unknown"}): ${(failure.stderr ?? "").trim().slice(-2048)}`);
|
|
1120
|
+
}
|
|
1121
|
+
if (options.worker) args.push("--setenv", "FLOW_BACKEND_WORKER", "1");
|
|
1122
|
+
args.push("--", command, ...options.args);
|
|
1123
|
+
return { command: bwrap, args, env, stdioFds: sources.slice(), scope, stateDir: virtualState, cleanup };
|
|
1124
|
+
} catch (error) {
|
|
1125
|
+
cleanup();
|
|
1126
|
+
throw new Error(`Filesystem isolation unavailable; unrestricted launch refused: ${error.message}`, { cause: error });
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
// src/isolation/sandbox-supervisor.ts
|
|
1131
|
+
function sandboxSupervisor() {
|
|
1132
|
+
const { spawn: spawn5 } = process.getBuiltinModule("node:child_process");
|
|
1133
|
+
const { readdirSync: readdirSync3, readFileSync: readFileSync2 } = process.getBuiltinModule("node:fs");
|
|
1134
|
+
const { constants: constants3 } = process.getBuiltinModule("node:os");
|
|
1135
|
+
const id = `${process.pid}-${Date.now()}`;
|
|
1136
|
+
const marker = `FLOW_SANDBOX_COMMAND=${id}`;
|
|
1137
|
+
const argv = process.argv.slice(1);
|
|
1138
|
+
if (argv[0] === "--") argv.shift();
|
|
1139
|
+
const child = spawn5(argv[0], argv.slice(1), { stdio: "pipe", env: { ...process.env, FLOW_SANDBOX_COMMAND: id } });
|
|
1140
|
+
child.stdout.pipe(process.stdout);
|
|
1141
|
+
child.stderr.pipe(process.stderr);
|
|
1142
|
+
const drained = Promise.all([child.stdout, child.stderr].map((stream) => new Promise((resolve4) => stream.once("close", resolve4))));
|
|
1143
|
+
const marked = () => readdirSync3("/proc").filter((entry) => /^\d+$/.test(entry) && Number(entry) !== process.pid).filter((pid) => {
|
|
1144
|
+
try {
|
|
1145
|
+
return readFileSync2(`/proc/${pid}/environ`, "latin1").split("\0").includes(marker);
|
|
1146
|
+
} catch {
|
|
1147
|
+
return false;
|
|
1148
|
+
}
|
|
1149
|
+
}).map(Number);
|
|
1150
|
+
const signalAll = (signal) => {
|
|
1151
|
+
for (const pid of marked()) {
|
|
1152
|
+
try {
|
|
1153
|
+
process.kill(pid, signal);
|
|
1154
|
+
} catch {
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
};
|
|
1158
|
+
let finishing = false;
|
|
1159
|
+
const finish = async (code) => {
|
|
1160
|
+
if (finishing) return;
|
|
1161
|
+
finishing = true;
|
|
1162
|
+
signalAll("SIGTERM");
|
|
1163
|
+
for (let wait = 0; wait < 40 && marked().length; wait++) await new Promise((resolve4) => setTimeout(resolve4, 50));
|
|
1164
|
+
signalAll("SIGKILL");
|
|
1165
|
+
await Promise.race([drained, new Promise((resolve4) => setTimeout(resolve4, 2e3))]);
|
|
1166
|
+
process.stdout.write("", () => process.exit(code));
|
|
1167
|
+
};
|
|
1168
|
+
child.on("error", () => void finish(127));
|
|
1169
|
+
child.on("exit", (code, signal) => void finish(code ?? 128 + (signal ? constants3.signals[signal] : 1)));
|
|
1170
|
+
child.stdin.on("error", () => {
|
|
1171
|
+
});
|
|
1172
|
+
process.stdin.pipe(child.stdin);
|
|
1173
|
+
process.stdin.on("end", () => {
|
|
1174
|
+
setTimeout(() => void finish(143), 5e3).unref();
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
var sandboxSupervisorSource = `(${sandboxSupervisor.toString()})()`;
|
|
1178
|
+
|
|
1179
|
+
// src/isolation/sandbox.ts
|
|
1180
|
+
function sandboxUnavailable() {
|
|
1181
|
+
return new Error("Sandbox isolation is unavailable; unrestricted launch refused");
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
// src/backend/mcp-stdio-supervisor.ts
|
|
1185
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1186
|
+
|
|
1187
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
|
|
1188
|
+
var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
|
|
1189
|
+
var ReadBuffer = class {
|
|
1190
|
+
constructor(options) {
|
|
1191
|
+
this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
|
|
1192
|
+
}
|
|
1193
|
+
append(chunk) {
|
|
1194
|
+
const newSize = (this._buffer?.length ?? 0) + chunk.length;
|
|
1195
|
+
if (newSize > this._maxBufferSize) {
|
|
1196
|
+
this.clear();
|
|
1197
|
+
throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
|
|
1198
|
+
}
|
|
1199
|
+
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
|
|
1200
|
+
}
|
|
1201
|
+
readMessage() {
|
|
1202
|
+
if (!this._buffer) {
|
|
1203
|
+
return null;
|
|
1204
|
+
}
|
|
1205
|
+
const index = this._buffer.indexOf("\n");
|
|
1206
|
+
if (index === -1) {
|
|
1207
|
+
return null;
|
|
1208
|
+
}
|
|
1209
|
+
const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
|
|
1210
|
+
this._buffer = this._buffer.subarray(index + 1);
|
|
1211
|
+
return deserializeMessage(line);
|
|
1212
|
+
}
|
|
1213
|
+
clear() {
|
|
1214
|
+
this._buffer = void 0;
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
function deserializeMessage(line) {
|
|
1218
|
+
return JSONRPCMessageSchema.parse(JSON.parse(line));
|
|
1219
|
+
}
|
|
1220
|
+
function serializeMessage(message) {
|
|
1221
|
+
return JSON.stringify(message) + "\n";
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// src/backend/mcp-stdio-supervisor.ts
|
|
1225
|
+
var SupervisedStdioTransport = class {
|
|
1226
|
+
onclose;
|
|
1227
|
+
onerror;
|
|
1228
|
+
onmessage;
|
|
1229
|
+
buffer = new ReadBuffer();
|
|
1230
|
+
child;
|
|
1231
|
+
started = false;
|
|
1232
|
+
closed = false;
|
|
1233
|
+
notified = false;
|
|
1234
|
+
closing;
|
|
1235
|
+
finishing;
|
|
1236
|
+
leaderExited = false;
|
|
1237
|
+
treeCleanup;
|
|
1238
|
+
resolveExit;
|
|
1239
|
+
/** Actual leader exit (not stdio 'close'), plus group cleanup. State must outlive this. */
|
|
1240
|
+
exited = new Promise((resolve4) => {
|
|
1241
|
+
this.resolveExit = resolve4;
|
|
1242
|
+
});
|
|
1243
|
+
launch;
|
|
1244
|
+
constructor(launch) {
|
|
1245
|
+
this.launch = launch;
|
|
1246
|
+
}
|
|
1247
|
+
async start() {
|
|
1248
|
+
if (this.started || this.closed) throw new Error("MCP transport already started or closed");
|
|
1249
|
+
this.started = true;
|
|
1250
|
+
try {
|
|
1251
|
+
const child = this.child = spawn2(this.launch.command, this.launch.args, {
|
|
1252
|
+
env: this.launch.env,
|
|
1253
|
+
cwd: this.launch.cwd,
|
|
1254
|
+
detached: process.platform !== "win32",
|
|
1255
|
+
windowsHide: true,
|
|
1256
|
+
stdio: ["pipe", "pipe", "pipe", ...this.launch.stdioFds ?? []]
|
|
1257
|
+
});
|
|
1258
|
+
child.stdin.on("error", (error) => this.onerror?.(error));
|
|
1259
|
+
child.stdout.on("error", (error) => this.onerror?.(error));
|
|
1260
|
+
child.stderr.on("error", (error) => this.onerror?.(error));
|
|
1261
|
+
child.stderr.resume();
|
|
1262
|
+
child.stdout.on("data", (chunk) => {
|
|
1263
|
+
try {
|
|
1264
|
+
this.buffer.append(chunk);
|
|
1265
|
+
} catch (error) {
|
|
1266
|
+
this.onerror?.(error);
|
|
1267
|
+
void this.close();
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
while (!this.closed) {
|
|
1271
|
+
try {
|
|
1272
|
+
const message = this.buffer.readMessage();
|
|
1273
|
+
if (message === null) break;
|
|
1274
|
+
this.onmessage?.(message);
|
|
1275
|
+
} catch (error) {
|
|
1276
|
+
this.onerror?.(error);
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
});
|
|
1280
|
+
child.once("exit", () => {
|
|
1281
|
+
void this.finishExit();
|
|
1282
|
+
});
|
|
1283
|
+
child.once("error", (error) => {
|
|
1284
|
+
this.onerror?.(error);
|
|
1285
|
+
if (!child.pid) void this.finishExit();
|
|
1286
|
+
});
|
|
1287
|
+
await new Promise((resolve4, reject) => {
|
|
1288
|
+
child.once("spawn", resolve4);
|
|
1289
|
+
child.once("error", reject);
|
|
1290
|
+
});
|
|
1291
|
+
} catch (error) {
|
|
1292
|
+
if (!this.child?.pid) await this.finishExit();
|
|
1293
|
+
throw error;
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
closePipes() {
|
|
1297
|
+
this.closed = true;
|
|
1298
|
+
this.child?.stdin?.destroy();
|
|
1299
|
+
this.child?.stdout?.destroy();
|
|
1300
|
+
this.child?.stderr?.destroy();
|
|
1301
|
+
this.buffer.clear();
|
|
1302
|
+
}
|
|
1303
|
+
killTree() {
|
|
1304
|
+
return this.treeCleanup ??= (async () => {
|
|
1305
|
+
const child = this.child;
|
|
1306
|
+
if (!child?.pid) return;
|
|
1307
|
+
if (process.platform !== "win32") {
|
|
1308
|
+
try {
|
|
1309
|
+
process.kill(-child.pid, "SIGKILL");
|
|
1310
|
+
} catch (error) {
|
|
1311
|
+
if (error.code !== "ESRCH") {
|
|
1312
|
+
this.onerror?.(error);
|
|
1313
|
+
child.kill("SIGKILL");
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
} else {
|
|
1317
|
+
const killer = spawn2("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
1318
|
+
await bounded(new Promise((resolve4) => {
|
|
1319
|
+
killer.once("error", () => resolve4());
|
|
1320
|
+
killer.once("exit", () => resolve4());
|
|
1321
|
+
}), 1e3);
|
|
1322
|
+
killer.kill();
|
|
1323
|
+
killer.unref();
|
|
1324
|
+
child.kill("SIGKILL");
|
|
1325
|
+
}
|
|
1326
|
+
})();
|
|
1327
|
+
}
|
|
1328
|
+
drainStdout() {
|
|
1329
|
+
const stdout = this.child?.stdout;
|
|
1330
|
+
if (this.closed || !stdout || stdout.destroyed || stdout.readableEnded) return Promise.resolve();
|
|
1331
|
+
return new Promise((resolve4) => {
|
|
1332
|
+
const done = () => {
|
|
1333
|
+
clearTimeout(timer);
|
|
1334
|
+
stdout.off("end", done);
|
|
1335
|
+
stdout.off("close", done);
|
|
1336
|
+
stdout.off("error", done);
|
|
1337
|
+
resolve4();
|
|
1338
|
+
};
|
|
1339
|
+
const timer = setTimeout(done, 1e3);
|
|
1340
|
+
stdout.once("end", done);
|
|
1341
|
+
stdout.once("close", done);
|
|
1342
|
+
stdout.once("error", done);
|
|
1343
|
+
stdout.resume();
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
finishExit() {
|
|
1347
|
+
return this.finishing ??= (async () => {
|
|
1348
|
+
this.leaderExited = true;
|
|
1349
|
+
await this.killTree();
|
|
1350
|
+
await this.drainStdout();
|
|
1351
|
+
this.closePipes();
|
|
1352
|
+
this.resolveExit();
|
|
1353
|
+
this.notifyClose();
|
|
1354
|
+
})();
|
|
1355
|
+
}
|
|
1356
|
+
notifyClose() {
|
|
1357
|
+
if (this.notified) return;
|
|
1358
|
+
this.notified = true;
|
|
1359
|
+
this.onclose?.();
|
|
1360
|
+
}
|
|
1361
|
+
close() {
|
|
1362
|
+
return this.closing ??= (async () => {
|
|
1363
|
+
this.closed = true;
|
|
1364
|
+
if (!this.started) {
|
|
1365
|
+
await this.finishExit();
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
this.child?.stdin?.end();
|
|
1369
|
+
await bounded(this.exited, 500);
|
|
1370
|
+
await this.killTree();
|
|
1371
|
+
this.closePipes();
|
|
1372
|
+
await bounded(this.exited, 1e3);
|
|
1373
|
+
this.child?.unref();
|
|
1374
|
+
this.notifyClose();
|
|
1375
|
+
})();
|
|
1376
|
+
}
|
|
1377
|
+
async send(message) {
|
|
1378
|
+
const stdin = this.child?.stdin;
|
|
1379
|
+
if (this.closed || this.leaderExited || !stdin || stdin.destroyed) throw new Error("MCP transport not connected");
|
|
1380
|
+
await new Promise((resolve4, reject) => {
|
|
1381
|
+
stdin.write(serializeMessage(message), (error) => error ? reject(error) : resolve4());
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
};
|
|
1385
|
+
async function bounded(promise, milliseconds) {
|
|
1386
|
+
let timer;
|
|
1387
|
+
try {
|
|
1388
|
+
await Promise.race([promise, new Promise((resolve4) => {
|
|
1389
|
+
timer = setTimeout(resolve4, milliseconds);
|
|
1390
|
+
})]);
|
|
1391
|
+
} finally {
|
|
1392
|
+
clearTimeout(timer);
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
|
|
1397
|
+
var ExperimentalClientTasks = class {
|
|
1398
|
+
constructor(_client) {
|
|
1399
|
+
this._client = _client;
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* Calls a tool and returns an AsyncGenerator that yields response messages.
|
|
1403
|
+
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
|
1404
|
+
*
|
|
1405
|
+
* This method provides streaming access to tool execution, allowing you to
|
|
1406
|
+
* observe intermediate task status updates for long-running tool calls.
|
|
1407
|
+
* Automatically validates structured output if the tool has an outputSchema.
|
|
1408
|
+
*
|
|
1409
|
+
* @example
|
|
1410
|
+
* ```typescript
|
|
1411
|
+
* const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
|
|
1412
|
+
* for await (const message of stream) {
|
|
1413
|
+
* switch (message.type) {
|
|
1414
|
+
* case 'taskCreated':
|
|
1415
|
+
* console.log('Tool execution started:', message.task.taskId);
|
|
1416
|
+
* break;
|
|
1417
|
+
* case 'taskStatus':
|
|
1418
|
+
* console.log('Tool status:', message.task.status);
|
|
1419
|
+
* break;
|
|
1420
|
+
* case 'result':
|
|
1421
|
+
* console.log('Tool result:', message.result);
|
|
1422
|
+
* break;
|
|
1423
|
+
* case 'error':
|
|
1424
|
+
* console.error('Tool error:', message.error);
|
|
1425
|
+
* break;
|
|
1426
|
+
* }
|
|
1427
|
+
* }
|
|
1428
|
+
* ```
|
|
1429
|
+
*
|
|
1430
|
+
* @param params - Tool call parameters (name and arguments)
|
|
1431
|
+
* @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
|
|
1432
|
+
* @param options - Optional request options (timeout, signal, task creation params, etc.)
|
|
1433
|
+
* @returns AsyncGenerator that yields ResponseMessage objects
|
|
1434
|
+
*
|
|
1435
|
+
* @experimental
|
|
1436
|
+
*/
|
|
1437
|
+
async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
|
|
1438
|
+
const clientInternal = this._client;
|
|
1439
|
+
const optionsWithTask = {
|
|
1440
|
+
...options,
|
|
1441
|
+
// We check if the tool is known to be a task during auto-configuration, but assume
|
|
1442
|
+
// the caller knows what they're doing if they pass this explicitly
|
|
1443
|
+
task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
|
|
1444
|
+
};
|
|
1445
|
+
const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
|
|
1446
|
+
const validator = clientInternal.getToolOutputValidator(params.name);
|
|
1447
|
+
for await (const message of stream) {
|
|
1448
|
+
if (message.type === "result" && validator) {
|
|
1449
|
+
const result = message.result;
|
|
1450
|
+
if (!result.structuredContent && !result.isError) {
|
|
1451
|
+
yield {
|
|
1452
|
+
type: "error",
|
|
1453
|
+
error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
|
|
1454
|
+
};
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
if (result.structuredContent) {
|
|
1458
|
+
try {
|
|
1459
|
+
const validationResult = validator(result.structuredContent);
|
|
1460
|
+
if (!validationResult.valid) {
|
|
1461
|
+
yield {
|
|
1462
|
+
type: "error",
|
|
1463
|
+
error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
|
|
1464
|
+
};
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
} catch (error) {
|
|
1468
|
+
if (error instanceof McpError) {
|
|
1469
|
+
yield { type: "error", error };
|
|
1470
|
+
return;
|
|
1471
|
+
}
|
|
1472
|
+
yield {
|
|
1473
|
+
type: "error",
|
|
1474
|
+
error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
|
|
1475
|
+
};
|
|
1476
|
+
return;
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
yield message;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
/**
|
|
1484
|
+
* Gets the current status of a task.
|
|
1485
|
+
*
|
|
1486
|
+
* @param taskId - The task identifier
|
|
1487
|
+
* @param options - Optional request options
|
|
1488
|
+
* @returns The task status
|
|
1489
|
+
*
|
|
1490
|
+
* @experimental
|
|
1491
|
+
*/
|
|
1492
|
+
async getTask(taskId, options) {
|
|
1493
|
+
return this._client.getTask({ taskId }, options);
|
|
1494
|
+
}
|
|
1495
|
+
/**
|
|
1496
|
+
* Retrieves the result of a completed task.
|
|
1497
|
+
*
|
|
1498
|
+
* @param taskId - The task identifier
|
|
1499
|
+
* @param resultSchema - Zod schema for validating the result
|
|
1500
|
+
* @param options - Optional request options
|
|
1501
|
+
* @returns The task result
|
|
1502
|
+
*
|
|
1503
|
+
* @experimental
|
|
1504
|
+
*/
|
|
1505
|
+
async getTaskResult(taskId, resultSchema, options) {
|
|
1506
|
+
return this._client.getTaskResult({ taskId }, resultSchema, options);
|
|
1507
|
+
}
|
|
1508
|
+
/**
|
|
1509
|
+
* Lists tasks with optional pagination.
|
|
1510
|
+
*
|
|
1511
|
+
* @param cursor - Optional pagination cursor
|
|
1512
|
+
* @param options - Optional request options
|
|
1513
|
+
* @returns List of tasks with optional next cursor
|
|
1514
|
+
*
|
|
1515
|
+
* @experimental
|
|
1516
|
+
*/
|
|
1517
|
+
async listTasks(cursor, options) {
|
|
1518
|
+
return this._client.listTasks(cursor ? { cursor } : void 0, options);
|
|
1519
|
+
}
|
|
1520
|
+
/**
|
|
1521
|
+
* Cancels a running task.
|
|
1522
|
+
*
|
|
1523
|
+
* @param taskId - The task identifier
|
|
1524
|
+
* @param options - Optional request options
|
|
1525
|
+
*
|
|
1526
|
+
* @experimental
|
|
1527
|
+
*/
|
|
1528
|
+
async cancelTask(taskId, options) {
|
|
1529
|
+
return this._client.cancelTask({ taskId }, options);
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* Sends a request and returns an AsyncGenerator that yields response messages.
|
|
1533
|
+
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
|
1534
|
+
*
|
|
1535
|
+
* This method provides streaming access to request processing, allowing you to
|
|
1536
|
+
* observe intermediate task status updates for task-augmented requests.
|
|
1537
|
+
*
|
|
1538
|
+
* @param request - The request to send
|
|
1539
|
+
* @param resultSchema - Zod schema for validating the result
|
|
1540
|
+
* @param options - Optional request options (timeout, signal, task creation params, etc.)
|
|
1541
|
+
* @returns AsyncGenerator that yields ResponseMessage objects
|
|
1542
|
+
*
|
|
1543
|
+
* @experimental
|
|
1544
|
+
*/
|
|
1545
|
+
requestStream(request, resultSchema, options) {
|
|
1546
|
+
return this._client.requestStream(request, resultSchema, options);
|
|
1547
|
+
}
|
|
1548
|
+
};
|
|
1549
|
+
|
|
1550
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
|
|
1551
|
+
function applyElicitationDefaults(schema, data) {
|
|
1552
|
+
if (!schema || data === null || typeof data !== "object")
|
|
1553
|
+
return;
|
|
1554
|
+
if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
|
|
1555
|
+
const obj = data;
|
|
1556
|
+
const props = schema.properties;
|
|
1557
|
+
for (const key of Object.keys(props)) {
|
|
1558
|
+
const propSchema = props[key];
|
|
1559
|
+
if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
|
|
1560
|
+
obj[key] = propSchema.default;
|
|
1561
|
+
}
|
|
1562
|
+
if (obj[key] !== void 0) {
|
|
1563
|
+
applyElicitationDefaults(propSchema, obj[key]);
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
if (Array.isArray(schema.anyOf)) {
|
|
1568
|
+
for (const sub of schema.anyOf) {
|
|
1569
|
+
if (typeof sub !== "boolean") {
|
|
1570
|
+
applyElicitationDefaults(sub, data);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
if (Array.isArray(schema.oneOf)) {
|
|
1575
|
+
for (const sub of schema.oneOf) {
|
|
1576
|
+
if (typeof sub !== "boolean") {
|
|
1577
|
+
applyElicitationDefaults(sub, data);
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
function getSupportedElicitationModes(capabilities) {
|
|
1583
|
+
if (!capabilities) {
|
|
1584
|
+
return { supportsFormMode: false, supportsUrlMode: false };
|
|
1585
|
+
}
|
|
1586
|
+
const hasFormCapability = capabilities.form !== void 0;
|
|
1587
|
+
const hasUrlCapability = capabilities.url !== void 0;
|
|
1588
|
+
const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
|
|
1589
|
+
const supportsUrlMode = hasUrlCapability;
|
|
1590
|
+
return { supportsFormMode, supportsUrlMode };
|
|
1591
|
+
}
|
|
1592
|
+
var Client = class extends Protocol {
|
|
1593
|
+
/**
|
|
1594
|
+
* Initializes this client with the given name and version information.
|
|
1595
|
+
*/
|
|
1596
|
+
constructor(_clientInfo, options) {
|
|
1597
|
+
super(options);
|
|
1598
|
+
this._clientInfo = _clientInfo;
|
|
1599
|
+
this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
|
|
1600
|
+
this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
|
|
1601
|
+
this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
|
|
1602
|
+
this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
|
|
1603
|
+
this._capabilities = options?.capabilities ?? {};
|
|
1604
|
+
this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
|
|
1605
|
+
if (options?.listChanged) {
|
|
1606
|
+
this._pendingListChangedConfig = options.listChanged;
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Set up handlers for list changed notifications based on config and server capabilities.
|
|
1611
|
+
* This should only be called after initialization when server capabilities are known.
|
|
1612
|
+
* Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
|
|
1613
|
+
* @internal
|
|
1614
|
+
*/
|
|
1615
|
+
_setupListChangedHandlers(config) {
|
|
1616
|
+
if (config.tools && this._serverCapabilities?.tools?.listChanged) {
|
|
1617
|
+
this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config.tools, async () => {
|
|
1618
|
+
const result = await this.listTools();
|
|
1619
|
+
return result.tools;
|
|
1620
|
+
});
|
|
1621
|
+
}
|
|
1622
|
+
if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {
|
|
1623
|
+
this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config.prompts, async () => {
|
|
1624
|
+
const result = await this.listPrompts();
|
|
1625
|
+
return result.prompts;
|
|
1626
|
+
});
|
|
1627
|
+
}
|
|
1628
|
+
if (config.resources && this._serverCapabilities?.resources?.listChanged) {
|
|
1629
|
+
this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config.resources, async () => {
|
|
1630
|
+
const result = await this.listResources();
|
|
1631
|
+
return result.resources;
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
/**
|
|
1636
|
+
* Access experimental features.
|
|
1637
|
+
*
|
|
1638
|
+
* WARNING: These APIs are experimental and may change without notice.
|
|
1639
|
+
*
|
|
1640
|
+
* @experimental
|
|
1641
|
+
*/
|
|
1642
|
+
get experimental() {
|
|
1643
|
+
if (!this._experimental) {
|
|
1644
|
+
this._experimental = {
|
|
1645
|
+
tasks: new ExperimentalClientTasks(this)
|
|
1646
|
+
};
|
|
1647
|
+
}
|
|
1648
|
+
return this._experimental;
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* Registers new capabilities. This can only be called before connecting to a transport.
|
|
1652
|
+
*
|
|
1653
|
+
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
|
|
1654
|
+
*/
|
|
1655
|
+
registerCapabilities(capabilities) {
|
|
1656
|
+
if (this.transport) {
|
|
1657
|
+
throw new Error("Cannot register capabilities after connecting to transport");
|
|
1658
|
+
}
|
|
1659
|
+
this._capabilities = mergeCapabilities(this._capabilities, capabilities);
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* Override request handler registration to enforce client-side validation for elicitation.
|
|
1663
|
+
*/
|
|
1664
|
+
setRequestHandler(requestSchema, handler) {
|
|
1665
|
+
const shape = getObjectShape(requestSchema);
|
|
1666
|
+
const methodSchema = shape?.method;
|
|
1667
|
+
if (!methodSchema) {
|
|
1668
|
+
throw new Error("Schema is missing a method literal");
|
|
1669
|
+
}
|
|
1670
|
+
const methodValue = getLiteralValue(methodSchema);
|
|
1671
|
+
if (typeof methodValue !== "string") {
|
|
1672
|
+
throw new Error("Schema method literal must be a string");
|
|
1673
|
+
}
|
|
1674
|
+
const method = methodValue;
|
|
1675
|
+
if (method === "elicitation/create") {
|
|
1676
|
+
const wrappedHandler = async (request, extra) => {
|
|
1677
|
+
const validatedRequest = safeParse(ElicitRequestSchema, request);
|
|
1678
|
+
if (!validatedRequest.success) {
|
|
1679
|
+
const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
|
|
1680
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
|
|
1681
|
+
}
|
|
1682
|
+
const { params } = validatedRequest.data;
|
|
1683
|
+
params.mode = params.mode ?? "form";
|
|
1684
|
+
const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
|
|
1685
|
+
if (params.mode === "form" && !supportsFormMode) {
|
|
1686
|
+
throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
|
|
1687
|
+
}
|
|
1688
|
+
if (params.mode === "url" && !supportsUrlMode) {
|
|
1689
|
+
throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
|
|
1690
|
+
}
|
|
1691
|
+
const result = await Promise.resolve(handler(request, extra));
|
|
1692
|
+
if (params.task) {
|
|
1693
|
+
const taskValidationResult = safeParse(CreateTaskResultSchema, result);
|
|
1694
|
+
if (!taskValidationResult.success) {
|
|
1695
|
+
const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
|
|
1696
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
|
|
1697
|
+
}
|
|
1698
|
+
return taskValidationResult.data;
|
|
1699
|
+
}
|
|
1700
|
+
const validationResult = safeParse(ElicitResultSchema, result);
|
|
1701
|
+
if (!validationResult.success) {
|
|
1702
|
+
const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
|
|
1703
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
|
|
1704
|
+
}
|
|
1705
|
+
const validatedResult = validationResult.data;
|
|
1706
|
+
const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
|
|
1707
|
+
if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
|
|
1708
|
+
if (this._capabilities.elicitation?.form?.applyDefaults) {
|
|
1709
|
+
try {
|
|
1710
|
+
applyElicitationDefaults(requestedSchema, validatedResult.content);
|
|
1711
|
+
} catch {
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
return validatedResult;
|
|
1716
|
+
};
|
|
1717
|
+
return super.setRequestHandler(requestSchema, wrappedHandler);
|
|
1718
|
+
}
|
|
1719
|
+
if (method === "sampling/createMessage") {
|
|
1720
|
+
const wrappedHandler = async (request, extra) => {
|
|
1721
|
+
const validatedRequest = safeParse(CreateMessageRequestSchema, request);
|
|
1722
|
+
if (!validatedRequest.success) {
|
|
1723
|
+
const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
|
|
1724
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
|
|
1725
|
+
}
|
|
1726
|
+
const { params } = validatedRequest.data;
|
|
1727
|
+
const result = await Promise.resolve(handler(request, extra));
|
|
1728
|
+
if (params.task) {
|
|
1729
|
+
const taskValidationResult = safeParse(CreateTaskResultSchema, result);
|
|
1730
|
+
if (!taskValidationResult.success) {
|
|
1731
|
+
const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
|
|
1732
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
|
|
1733
|
+
}
|
|
1734
|
+
return taskValidationResult.data;
|
|
1735
|
+
}
|
|
1736
|
+
const hasTools = params.tools || params.toolChoice;
|
|
1737
|
+
const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
|
|
1738
|
+
const validationResult = safeParse(resultSchema, result);
|
|
1739
|
+
if (!validationResult.success) {
|
|
1740
|
+
const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
|
|
1741
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
|
|
1742
|
+
}
|
|
1743
|
+
return validationResult.data;
|
|
1744
|
+
};
|
|
1745
|
+
return super.setRequestHandler(requestSchema, wrappedHandler);
|
|
1746
|
+
}
|
|
1747
|
+
return super.setRequestHandler(requestSchema, handler);
|
|
1748
|
+
}
|
|
1749
|
+
assertCapability(capability, method) {
|
|
1750
|
+
if (!this._serverCapabilities?.[capability]) {
|
|
1751
|
+
throw new Error(`Server does not support ${capability} (required for ${method})`);
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
async connect(transport, options) {
|
|
1755
|
+
await super.connect(transport);
|
|
1756
|
+
if (transport.sessionId !== void 0) {
|
|
1757
|
+
return;
|
|
1758
|
+
}
|
|
1759
|
+
try {
|
|
1760
|
+
const result = await this.request({
|
|
1761
|
+
method: "initialize",
|
|
1762
|
+
params: {
|
|
1763
|
+
protocolVersion: LATEST_PROTOCOL_VERSION,
|
|
1764
|
+
capabilities: this._capabilities,
|
|
1765
|
+
clientInfo: this._clientInfo
|
|
1766
|
+
}
|
|
1767
|
+
}, InitializeResultSchema, options);
|
|
1768
|
+
if (result === void 0) {
|
|
1769
|
+
throw new Error(`Server sent invalid initialize result: ${result}`);
|
|
1770
|
+
}
|
|
1771
|
+
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
|
|
1772
|
+
throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
|
|
1773
|
+
}
|
|
1774
|
+
this._serverCapabilities = result.capabilities;
|
|
1775
|
+
this._serverVersion = result.serverInfo;
|
|
1776
|
+
if (transport.setProtocolVersion) {
|
|
1777
|
+
transport.setProtocolVersion(result.protocolVersion);
|
|
1778
|
+
}
|
|
1779
|
+
this._instructions = result.instructions;
|
|
1780
|
+
await this.notification({
|
|
1781
|
+
method: "notifications/initialized"
|
|
1782
|
+
});
|
|
1783
|
+
if (this._pendingListChangedConfig) {
|
|
1784
|
+
this._setupListChangedHandlers(this._pendingListChangedConfig);
|
|
1785
|
+
this._pendingListChangedConfig = void 0;
|
|
1786
|
+
}
|
|
1787
|
+
} catch (error) {
|
|
1788
|
+
void this.close();
|
|
1789
|
+
throw error;
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
/**
|
|
1793
|
+
* After initialization has completed, this will be populated with the server's reported capabilities.
|
|
1794
|
+
*/
|
|
1795
|
+
getServerCapabilities() {
|
|
1796
|
+
return this._serverCapabilities;
|
|
1797
|
+
}
|
|
1798
|
+
/**
|
|
1799
|
+
* After initialization has completed, this will be populated with information about the server's name and version.
|
|
1800
|
+
*/
|
|
1801
|
+
getServerVersion() {
|
|
1802
|
+
return this._serverVersion;
|
|
1803
|
+
}
|
|
1804
|
+
/**
|
|
1805
|
+
* After initialization has completed, this may be populated with information about the server's instructions.
|
|
1806
|
+
*/
|
|
1807
|
+
getInstructions() {
|
|
1808
|
+
return this._instructions;
|
|
1809
|
+
}
|
|
1810
|
+
assertCapabilityForMethod(method) {
|
|
1811
|
+
switch (method) {
|
|
1812
|
+
case "logging/setLevel":
|
|
1813
|
+
if (!this._serverCapabilities?.logging) {
|
|
1814
|
+
throw new Error(`Server does not support logging (required for ${method})`);
|
|
1815
|
+
}
|
|
1816
|
+
break;
|
|
1817
|
+
case "prompts/get":
|
|
1818
|
+
case "prompts/list":
|
|
1819
|
+
if (!this._serverCapabilities?.prompts) {
|
|
1820
|
+
throw new Error(`Server does not support prompts (required for ${method})`);
|
|
1821
|
+
}
|
|
1822
|
+
break;
|
|
1823
|
+
case "resources/list":
|
|
1824
|
+
case "resources/templates/list":
|
|
1825
|
+
case "resources/read":
|
|
1826
|
+
case "resources/subscribe":
|
|
1827
|
+
case "resources/unsubscribe":
|
|
1828
|
+
if (!this._serverCapabilities?.resources) {
|
|
1829
|
+
throw new Error(`Server does not support resources (required for ${method})`);
|
|
1830
|
+
}
|
|
1831
|
+
if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) {
|
|
1832
|
+
throw new Error(`Server does not support resource subscriptions (required for ${method})`);
|
|
1833
|
+
}
|
|
1834
|
+
break;
|
|
1835
|
+
case "tools/call":
|
|
1836
|
+
case "tools/list":
|
|
1837
|
+
if (!this._serverCapabilities?.tools) {
|
|
1838
|
+
throw new Error(`Server does not support tools (required for ${method})`);
|
|
1839
|
+
}
|
|
1840
|
+
break;
|
|
1841
|
+
case "completion/complete":
|
|
1842
|
+
if (!this._serverCapabilities?.completions) {
|
|
1843
|
+
throw new Error(`Server does not support completions (required for ${method})`);
|
|
1844
|
+
}
|
|
1845
|
+
break;
|
|
1846
|
+
case "initialize":
|
|
1847
|
+
break;
|
|
1848
|
+
case "ping":
|
|
1849
|
+
break;
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
assertNotificationCapability(method) {
|
|
1853
|
+
switch (method) {
|
|
1854
|
+
case "notifications/roots/list_changed":
|
|
1855
|
+
if (!this._capabilities.roots?.listChanged) {
|
|
1856
|
+
throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
|
|
1857
|
+
}
|
|
1858
|
+
break;
|
|
1859
|
+
case "notifications/initialized":
|
|
1860
|
+
break;
|
|
1861
|
+
case "notifications/cancelled":
|
|
1862
|
+
break;
|
|
1863
|
+
case "notifications/progress":
|
|
1864
|
+
break;
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
assertRequestHandlerCapability(method) {
|
|
1868
|
+
if (!this._capabilities) {
|
|
1869
|
+
return;
|
|
1870
|
+
}
|
|
1871
|
+
switch (method) {
|
|
1872
|
+
case "sampling/createMessage":
|
|
1873
|
+
if (!this._capabilities.sampling) {
|
|
1874
|
+
throw new Error(`Client does not support sampling capability (required for ${method})`);
|
|
1875
|
+
}
|
|
1876
|
+
break;
|
|
1877
|
+
case "elicitation/create":
|
|
1878
|
+
if (!this._capabilities.elicitation) {
|
|
1879
|
+
throw new Error(`Client does not support elicitation capability (required for ${method})`);
|
|
1880
|
+
}
|
|
1881
|
+
break;
|
|
1882
|
+
case "roots/list":
|
|
1883
|
+
if (!this._capabilities.roots) {
|
|
1884
|
+
throw new Error(`Client does not support roots capability (required for ${method})`);
|
|
1885
|
+
}
|
|
1886
|
+
break;
|
|
1887
|
+
case "tasks/get":
|
|
1888
|
+
case "tasks/list":
|
|
1889
|
+
case "tasks/result":
|
|
1890
|
+
case "tasks/cancel":
|
|
1891
|
+
if (!this._capabilities.tasks) {
|
|
1892
|
+
throw new Error(`Client does not support tasks capability (required for ${method})`);
|
|
1893
|
+
}
|
|
1894
|
+
break;
|
|
1895
|
+
case "ping":
|
|
1896
|
+
break;
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
assertTaskCapability(method) {
|
|
1900
|
+
assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
|
|
1901
|
+
}
|
|
1902
|
+
assertTaskHandlerCapability(method) {
|
|
1903
|
+
if (!this._capabilities) {
|
|
1904
|
+
return;
|
|
1905
|
+
}
|
|
1906
|
+
assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
|
|
1907
|
+
}
|
|
1908
|
+
async ping(options) {
|
|
1909
|
+
return this.request({ method: "ping" }, EmptyResultSchema, options);
|
|
1910
|
+
}
|
|
1911
|
+
async complete(params, options) {
|
|
1912
|
+
return this.request({ method: "completion/complete", params }, CompleteResultSchema, options);
|
|
1913
|
+
}
|
|
1914
|
+
async setLoggingLevel(level, options) {
|
|
1915
|
+
return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options);
|
|
1916
|
+
}
|
|
1917
|
+
async getPrompt(params, options) {
|
|
1918
|
+
return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options);
|
|
1919
|
+
}
|
|
1920
|
+
async listPrompts(params, options) {
|
|
1921
|
+
return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options);
|
|
1922
|
+
}
|
|
1923
|
+
async listResources(params, options) {
|
|
1924
|
+
return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options);
|
|
1925
|
+
}
|
|
1926
|
+
async listResourceTemplates(params, options) {
|
|
1927
|
+
return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options);
|
|
1928
|
+
}
|
|
1929
|
+
async readResource(params, options) {
|
|
1930
|
+
return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options);
|
|
1931
|
+
}
|
|
1932
|
+
async subscribeResource(params, options) {
|
|
1933
|
+
return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options);
|
|
1934
|
+
}
|
|
1935
|
+
async unsubscribeResource(params, options) {
|
|
1936
|
+
return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options);
|
|
1937
|
+
}
|
|
1938
|
+
/**
|
|
1939
|
+
* Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
|
|
1940
|
+
*
|
|
1941
|
+
* For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
|
|
1942
|
+
*/
|
|
1943
|
+
async callTool(params, resultSchema = CallToolResultSchema, options) {
|
|
1944
|
+
if (this.isToolTaskRequired(params.name)) {
|
|
1945
|
+
throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
|
|
1946
|
+
}
|
|
1947
|
+
const result = await this.request({ method: "tools/call", params }, resultSchema, options);
|
|
1948
|
+
const validator = this.getToolOutputValidator(params.name);
|
|
1949
|
+
if (validator) {
|
|
1950
|
+
if (!result.structuredContent && !result.isError) {
|
|
1951
|
+
throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
|
|
1952
|
+
}
|
|
1953
|
+
if (result.structuredContent) {
|
|
1954
|
+
try {
|
|
1955
|
+
const validationResult = validator(result.structuredContent);
|
|
1956
|
+
if (!validationResult.valid) {
|
|
1957
|
+
throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
|
|
1958
|
+
}
|
|
1959
|
+
} catch (error) {
|
|
1960
|
+
if (error instanceof McpError) {
|
|
1961
|
+
throw error;
|
|
1962
|
+
}
|
|
1963
|
+
throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
return result;
|
|
1968
|
+
}
|
|
1969
|
+
isToolTask(toolName) {
|
|
1970
|
+
if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
|
|
1971
|
+
return false;
|
|
1972
|
+
}
|
|
1973
|
+
return this._cachedKnownTaskTools.has(toolName);
|
|
1974
|
+
}
|
|
1975
|
+
/**
|
|
1976
|
+
* Check if a tool requires task-based execution.
|
|
1977
|
+
* Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
|
|
1978
|
+
*/
|
|
1979
|
+
isToolTaskRequired(toolName) {
|
|
1980
|
+
return this._cachedRequiredTaskTools.has(toolName);
|
|
1981
|
+
}
|
|
1982
|
+
/**
|
|
1983
|
+
* Cache validators for tool output schemas.
|
|
1984
|
+
* Called after listTools() to pre-compile validators for better performance.
|
|
1985
|
+
*/
|
|
1986
|
+
cacheToolMetadata(tools) {
|
|
1987
|
+
this._cachedToolOutputValidators.clear();
|
|
1988
|
+
this._cachedKnownTaskTools.clear();
|
|
1989
|
+
this._cachedRequiredTaskTools.clear();
|
|
1990
|
+
for (const tool of tools) {
|
|
1991
|
+
if (tool.outputSchema) {
|
|
1992
|
+
const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
|
|
1993
|
+
this._cachedToolOutputValidators.set(tool.name, toolValidator);
|
|
1994
|
+
}
|
|
1995
|
+
const taskSupport = tool.execution?.taskSupport;
|
|
1996
|
+
if (taskSupport === "required" || taskSupport === "optional") {
|
|
1997
|
+
this._cachedKnownTaskTools.add(tool.name);
|
|
1998
|
+
}
|
|
1999
|
+
if (taskSupport === "required") {
|
|
2000
|
+
this._cachedRequiredTaskTools.add(tool.name);
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
/**
|
|
2005
|
+
* Get cached validator for a tool
|
|
2006
|
+
*/
|
|
2007
|
+
getToolOutputValidator(toolName) {
|
|
2008
|
+
return this._cachedToolOutputValidators.get(toolName);
|
|
2009
|
+
}
|
|
2010
|
+
async listTools(params, options) {
|
|
2011
|
+
const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options);
|
|
2012
|
+
this.cacheToolMetadata(result.tools);
|
|
2013
|
+
return result;
|
|
2014
|
+
}
|
|
2015
|
+
/**
|
|
2016
|
+
* Set up a single list changed handler.
|
|
2017
|
+
* @internal
|
|
2018
|
+
*/
|
|
2019
|
+
_setupListChangedHandler(listType, notificationSchema, options, fetcher) {
|
|
2020
|
+
const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
|
|
2021
|
+
if (!parseResult.success) {
|
|
2022
|
+
throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
|
|
2023
|
+
}
|
|
2024
|
+
if (typeof options.onChanged !== "function") {
|
|
2025
|
+
throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
|
|
2026
|
+
}
|
|
2027
|
+
const { autoRefresh, debounceMs } = parseResult.data;
|
|
2028
|
+
const { onChanged } = options;
|
|
2029
|
+
const refresh = async () => {
|
|
2030
|
+
if (!autoRefresh) {
|
|
2031
|
+
onChanged(null, null);
|
|
2032
|
+
return;
|
|
2033
|
+
}
|
|
2034
|
+
try {
|
|
2035
|
+
const items = await fetcher();
|
|
2036
|
+
onChanged(null, items);
|
|
2037
|
+
} catch (e) {
|
|
2038
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
2039
|
+
onChanged(error, null);
|
|
2040
|
+
}
|
|
2041
|
+
};
|
|
2042
|
+
const handler = () => {
|
|
2043
|
+
if (debounceMs) {
|
|
2044
|
+
const existingTimer = this._listChangedDebounceTimers.get(listType);
|
|
2045
|
+
if (existingTimer) {
|
|
2046
|
+
clearTimeout(existingTimer);
|
|
2047
|
+
}
|
|
2048
|
+
const timer = setTimeout(refresh, debounceMs);
|
|
2049
|
+
this._listChangedDebounceTimers.set(listType, timer);
|
|
2050
|
+
} else {
|
|
2051
|
+
refresh();
|
|
2052
|
+
}
|
|
2053
|
+
};
|
|
2054
|
+
this.setNotificationHandler(notificationSchema, handler);
|
|
2055
|
+
}
|
|
2056
|
+
async sendRootsListChanged() {
|
|
2057
|
+
return this.notification({ method: "notifications/roots/list_changed" });
|
|
2058
|
+
}
|
|
2059
|
+
};
|
|
2060
|
+
|
|
2061
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
|
|
2062
|
+
var import_cross_spawn = __toESM(require_cross_spawn(), 1);
|
|
2063
|
+
import process2 from "node:process";
|
|
2064
|
+
var DEFAULT_INHERITED_ENV_VARS = process2.platform === "win32" ? [
|
|
2065
|
+
"APPDATA",
|
|
2066
|
+
"HOMEDRIVE",
|
|
2067
|
+
"HOMEPATH",
|
|
2068
|
+
"LOCALAPPDATA",
|
|
2069
|
+
"PATH",
|
|
2070
|
+
"PROCESSOR_ARCHITECTURE",
|
|
2071
|
+
"SYSTEMDRIVE",
|
|
2072
|
+
"SYSTEMROOT",
|
|
2073
|
+
"TEMP",
|
|
2074
|
+
"USERNAME",
|
|
2075
|
+
"USERPROFILE",
|
|
2076
|
+
"PROGRAMFILES"
|
|
2077
|
+
] : (
|
|
2078
|
+
/* list inspired by the default env inheritance of sudo */
|
|
2079
|
+
["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"]
|
|
2080
|
+
);
|
|
2081
|
+
function getDefaultEnvironment() {
|
|
2082
|
+
const env = {};
|
|
2083
|
+
for (const key of DEFAULT_INHERITED_ENV_VARS) {
|
|
2084
|
+
const value = process2.env[key];
|
|
2085
|
+
if (value === void 0) {
|
|
2086
|
+
continue;
|
|
2087
|
+
}
|
|
2088
|
+
if (value.startsWith("()")) {
|
|
2089
|
+
continue;
|
|
2090
|
+
}
|
|
2091
|
+
env[key] = value;
|
|
2092
|
+
}
|
|
2093
|
+
return env;
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
|
|
2097
|
+
var import_content_type = __toESM(require_content_type(), 1);
|
|
2098
|
+
function mediaTypeEssence(header) {
|
|
2099
|
+
if (!header) {
|
|
2100
|
+
return void 0;
|
|
2101
|
+
}
|
|
2102
|
+
try {
|
|
2103
|
+
return import_content_type.default.parse(header).type;
|
|
2104
|
+
} catch {
|
|
2105
|
+
const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase();
|
|
2106
|
+
if (essence === "" || header.slice(essence.length).includes(",")) {
|
|
2107
|
+
return void 0;
|
|
2108
|
+
}
|
|
2109
|
+
return essence;
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
|
|
2114
|
+
function normalizeHeaders(headers) {
|
|
2115
|
+
if (!headers)
|
|
2116
|
+
return {};
|
|
2117
|
+
if (headers instanceof Headers) {
|
|
2118
|
+
return Object.fromEntries(headers.entries());
|
|
2119
|
+
}
|
|
2120
|
+
if (Array.isArray(headers)) {
|
|
2121
|
+
return Object.fromEntries(headers);
|
|
2122
|
+
}
|
|
2123
|
+
return { ...headers };
|
|
2124
|
+
}
|
|
2125
|
+
function createFetchWithInit(baseFetch = fetch, baseInit) {
|
|
2126
|
+
if (!baseInit) {
|
|
2127
|
+
return baseFetch;
|
|
2128
|
+
}
|
|
2129
|
+
return async (url2, init) => {
|
|
2130
|
+
const mergedInit = {
|
|
2131
|
+
...baseInit,
|
|
2132
|
+
...init,
|
|
2133
|
+
// Headers need special handling - merge instead of replace
|
|
2134
|
+
headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
|
|
2135
|
+
};
|
|
2136
|
+
return baseFetch(url2, mergedInit);
|
|
2137
|
+
};
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
// node_modules/pkce-challenge/dist/index.node.js
|
|
2141
|
+
var crypto;
|
|
2142
|
+
crypto = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
|
|
2143
|
+
globalThis.crypto ?? // Node.js >18
|
|
2144
|
+
import("node:crypto").then((m) => m.webcrypto);
|
|
2145
|
+
async function getRandomValues(size) {
|
|
2146
|
+
return (await crypto).getRandomValues(new Uint8Array(size));
|
|
2147
|
+
}
|
|
2148
|
+
async function random(size) {
|
|
2149
|
+
const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
|
|
2150
|
+
const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
|
|
2151
|
+
let result = "";
|
|
2152
|
+
while (result.length < size) {
|
|
2153
|
+
const randomBytes = await getRandomValues(size - result.length);
|
|
2154
|
+
for (const randomByte of randomBytes) {
|
|
2155
|
+
if (randomByte < evenDistCutoff) {
|
|
2156
|
+
result += mask[randomByte % mask.length];
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
return result;
|
|
2161
|
+
}
|
|
2162
|
+
async function generateVerifier(length) {
|
|
2163
|
+
return await random(length);
|
|
2164
|
+
}
|
|
2165
|
+
async function generateChallenge(code_verifier) {
|
|
2166
|
+
const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
|
|
2167
|
+
return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
|
|
2168
|
+
}
|
|
2169
|
+
async function pkceChallenge(length) {
|
|
2170
|
+
if (!length)
|
|
2171
|
+
length = 43;
|
|
2172
|
+
if (length < 43 || length > 128) {
|
|
2173
|
+
throw `Expected a length between 43 and 128. Received ${length}.`;
|
|
2174
|
+
}
|
|
2175
|
+
const verifier = await generateVerifier(length);
|
|
2176
|
+
const challenge = await generateChallenge(verifier);
|
|
2177
|
+
return {
|
|
2178
|
+
code_verifier: verifier,
|
|
2179
|
+
code_challenge: challenge
|
|
2180
|
+
};
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
|
|
2184
|
+
var SafeUrlSchema = url().superRefine((val, ctx) => {
|
|
2185
|
+
if (!URL.canParse(val)) {
|
|
2186
|
+
ctx.addIssue({
|
|
2187
|
+
code: ZodIssueCode.custom,
|
|
2188
|
+
message: "URL must be parseable",
|
|
2189
|
+
fatal: true
|
|
2190
|
+
});
|
|
2191
|
+
return NEVER;
|
|
2192
|
+
}
|
|
2193
|
+
}).refine((url2) => {
|
|
2194
|
+
const u = new URL(url2);
|
|
2195
|
+
return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
|
|
2196
|
+
}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
|
|
2197
|
+
var OAuthProtectedResourceMetadataSchema = looseObject({
|
|
2198
|
+
resource: string().url(),
|
|
2199
|
+
authorization_servers: array(SafeUrlSchema).optional(),
|
|
2200
|
+
jwks_uri: string().url().optional(),
|
|
2201
|
+
scopes_supported: array(string()).optional(),
|
|
2202
|
+
bearer_methods_supported: array(string()).optional(),
|
|
2203
|
+
resource_signing_alg_values_supported: array(string()).optional(),
|
|
2204
|
+
resource_name: string().optional(),
|
|
2205
|
+
resource_documentation: string().optional(),
|
|
2206
|
+
resource_policy_uri: string().url().optional(),
|
|
2207
|
+
resource_tos_uri: string().url().optional(),
|
|
2208
|
+
tls_client_certificate_bound_access_tokens: boolean().optional(),
|
|
2209
|
+
authorization_details_types_supported: array(string()).optional(),
|
|
2210
|
+
dpop_signing_alg_values_supported: array(string()).optional(),
|
|
2211
|
+
dpop_bound_access_tokens_required: boolean().optional()
|
|
2212
|
+
});
|
|
2213
|
+
var OAuthMetadataSchema = looseObject({
|
|
2214
|
+
issuer: string(),
|
|
2215
|
+
authorization_endpoint: SafeUrlSchema,
|
|
2216
|
+
token_endpoint: SafeUrlSchema,
|
|
2217
|
+
registration_endpoint: SafeUrlSchema.optional(),
|
|
2218
|
+
scopes_supported: array(string()).optional(),
|
|
2219
|
+
response_types_supported: array(string()),
|
|
2220
|
+
response_modes_supported: array(string()).optional(),
|
|
2221
|
+
grant_types_supported: array(string()).optional(),
|
|
2222
|
+
token_endpoint_auth_methods_supported: array(string()).optional(),
|
|
2223
|
+
token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
2224
|
+
service_documentation: SafeUrlSchema.optional(),
|
|
2225
|
+
revocation_endpoint: SafeUrlSchema.optional(),
|
|
2226
|
+
revocation_endpoint_auth_methods_supported: array(string()).optional(),
|
|
2227
|
+
revocation_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
2228
|
+
introspection_endpoint: string().optional(),
|
|
2229
|
+
introspection_endpoint_auth_methods_supported: array(string()).optional(),
|
|
2230
|
+
introspection_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
2231
|
+
code_challenge_methods_supported: array(string()).optional(),
|
|
2232
|
+
client_id_metadata_document_supported: boolean().optional()
|
|
2233
|
+
});
|
|
2234
|
+
var OpenIdProviderMetadataSchema = looseObject({
|
|
2235
|
+
issuer: string(),
|
|
2236
|
+
authorization_endpoint: SafeUrlSchema,
|
|
2237
|
+
token_endpoint: SafeUrlSchema,
|
|
2238
|
+
userinfo_endpoint: SafeUrlSchema.optional(),
|
|
2239
|
+
jwks_uri: SafeUrlSchema,
|
|
2240
|
+
registration_endpoint: SafeUrlSchema.optional(),
|
|
2241
|
+
scopes_supported: array(string()).optional(),
|
|
2242
|
+
response_types_supported: array(string()),
|
|
2243
|
+
response_modes_supported: array(string()).optional(),
|
|
2244
|
+
grant_types_supported: array(string()).optional(),
|
|
2245
|
+
acr_values_supported: array(string()).optional(),
|
|
2246
|
+
subject_types_supported: array(string()),
|
|
2247
|
+
id_token_signing_alg_values_supported: array(string()),
|
|
2248
|
+
id_token_encryption_alg_values_supported: array(string()).optional(),
|
|
2249
|
+
id_token_encryption_enc_values_supported: array(string()).optional(),
|
|
2250
|
+
userinfo_signing_alg_values_supported: array(string()).optional(),
|
|
2251
|
+
userinfo_encryption_alg_values_supported: array(string()).optional(),
|
|
2252
|
+
userinfo_encryption_enc_values_supported: array(string()).optional(),
|
|
2253
|
+
request_object_signing_alg_values_supported: array(string()).optional(),
|
|
2254
|
+
request_object_encryption_alg_values_supported: array(string()).optional(),
|
|
2255
|
+
request_object_encryption_enc_values_supported: array(string()).optional(),
|
|
2256
|
+
token_endpoint_auth_methods_supported: array(string()).optional(),
|
|
2257
|
+
token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
2258
|
+
display_values_supported: array(string()).optional(),
|
|
2259
|
+
claim_types_supported: array(string()).optional(),
|
|
2260
|
+
claims_supported: array(string()).optional(),
|
|
2261
|
+
service_documentation: string().optional(),
|
|
2262
|
+
claims_locales_supported: array(string()).optional(),
|
|
2263
|
+
ui_locales_supported: array(string()).optional(),
|
|
2264
|
+
claims_parameter_supported: boolean().optional(),
|
|
2265
|
+
request_parameter_supported: boolean().optional(),
|
|
2266
|
+
request_uri_parameter_supported: boolean().optional(),
|
|
2267
|
+
require_request_uri_registration: boolean().optional(),
|
|
2268
|
+
op_policy_uri: SafeUrlSchema.optional(),
|
|
2269
|
+
op_tos_uri: SafeUrlSchema.optional(),
|
|
2270
|
+
client_id_metadata_document_supported: boolean().optional()
|
|
2271
|
+
});
|
|
2272
|
+
var OpenIdProviderDiscoveryMetadataSchema = object({
|
|
2273
|
+
...OpenIdProviderMetadataSchema.shape,
|
|
2274
|
+
...OAuthMetadataSchema.pick({
|
|
2275
|
+
code_challenge_methods_supported: true
|
|
2276
|
+
}).shape
|
|
2277
|
+
});
|
|
2278
|
+
var OAuthTokensSchema = object({
|
|
2279
|
+
access_token: string(),
|
|
2280
|
+
id_token: string().optional(),
|
|
2281
|
+
// Optional for OAuth 2.1, but necessary in OpenID Connect
|
|
2282
|
+
token_type: string(),
|
|
2283
|
+
expires_in: coerce_exports.number().optional(),
|
|
2284
|
+
scope: string().optional(),
|
|
2285
|
+
refresh_token: string().optional(),
|
|
2286
|
+
/**
|
|
2287
|
+
* Not part of the wire format: the authorization server this value was obtained from, added by
|
|
2288
|
+
* the client's `auth()` before it is stored and compared when it is read back.
|
|
2289
|
+
*/
|
|
2290
|
+
issuer: string().optional().catch(void 0)
|
|
2291
|
+
}).strip();
|
|
2292
|
+
var OAuthErrorResponseSchema = object({
|
|
2293
|
+
error: string(),
|
|
2294
|
+
error_description: string().optional(),
|
|
2295
|
+
error_uri: string().optional()
|
|
2296
|
+
});
|
|
2297
|
+
var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0));
|
|
2298
|
+
var OAuthClientMetadataSchema = object({
|
|
2299
|
+
redirect_uris: array(SafeUrlSchema),
|
|
2300
|
+
token_endpoint_auth_method: string().optional(),
|
|
2301
|
+
grant_types: array(string()).optional(),
|
|
2302
|
+
response_types: array(string()).optional(),
|
|
2303
|
+
client_name: string().optional(),
|
|
2304
|
+
client_uri: SafeUrlSchema.optional(),
|
|
2305
|
+
logo_uri: OptionalSafeUrlSchema,
|
|
2306
|
+
scope: string().optional(),
|
|
2307
|
+
contacts: array(string()).optional(),
|
|
2308
|
+
tos_uri: OptionalSafeUrlSchema,
|
|
2309
|
+
policy_uri: string().optional(),
|
|
2310
|
+
jwks_uri: SafeUrlSchema.optional(),
|
|
2311
|
+
jwks: any().optional(),
|
|
2312
|
+
software_id: string().optional(),
|
|
2313
|
+
software_version: string().optional(),
|
|
2314
|
+
software_statement: string().optional()
|
|
2315
|
+
}).strip();
|
|
2316
|
+
var OAuthClientInformationSchema = object({
|
|
2317
|
+
client_id: string(),
|
|
2318
|
+
client_secret: string().optional(),
|
|
2319
|
+
client_id_issued_at: number().optional(),
|
|
2320
|
+
client_secret_expires_at: number().optional(),
|
|
2321
|
+
/**
|
|
2322
|
+
* Not part of the wire format: the authorization server this value was obtained from, added by
|
|
2323
|
+
* the client's `auth()` before it is stored and compared when it is read back.
|
|
2324
|
+
*/
|
|
2325
|
+
issuer: string().optional().catch(void 0)
|
|
2326
|
+
}).strip();
|
|
2327
|
+
var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
|
|
2328
|
+
var OAuthClientRegistrationErrorSchema = object({
|
|
2329
|
+
error: string(),
|
|
2330
|
+
error_description: string().optional()
|
|
2331
|
+
}).strip();
|
|
2332
|
+
var OAuthTokenRevocationRequestSchema = object({
|
|
2333
|
+
token: string(),
|
|
2334
|
+
token_type_hint: string().optional()
|
|
2335
|
+
}).strip();
|
|
2336
|
+
|
|
2337
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
|
|
2338
|
+
function resourceUrlFromServerUrl(url2) {
|
|
2339
|
+
const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href);
|
|
2340
|
+
resourceURL.hash = "";
|
|
2341
|
+
return resourceURL;
|
|
2342
|
+
}
|
|
2343
|
+
function checkResourceAllowed({ requestedResource, configuredResource }) {
|
|
2344
|
+
const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
|
|
2345
|
+
const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
|
|
2346
|
+
if (requested.origin !== configured.origin) {
|
|
2347
|
+
return false;
|
|
2348
|
+
}
|
|
2349
|
+
if (requested.pathname.length < configured.pathname.length) {
|
|
2350
|
+
return false;
|
|
2351
|
+
}
|
|
2352
|
+
const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
|
|
2353
|
+
const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
|
|
2354
|
+
return requestedPath.startsWith(configuredPath);
|
|
2355
|
+
}
|
|
2356
|
+
|
|
2357
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
|
|
2358
|
+
var OAuthError = class extends Error {
|
|
2359
|
+
constructor(message, errorUri) {
|
|
2360
|
+
super(message);
|
|
2361
|
+
this.errorUri = errorUri;
|
|
2362
|
+
this.name = this.constructor.name;
|
|
2363
|
+
}
|
|
2364
|
+
/**
|
|
2365
|
+
* Converts the error to a standard OAuth error response object
|
|
2366
|
+
*/
|
|
2367
|
+
toResponseObject() {
|
|
2368
|
+
const response = {
|
|
2369
|
+
error: this.errorCode,
|
|
2370
|
+
error_description: this.message
|
|
2371
|
+
};
|
|
2372
|
+
if (this.errorUri) {
|
|
2373
|
+
response.error_uri = this.errorUri;
|
|
2374
|
+
}
|
|
2375
|
+
return response;
|
|
2376
|
+
}
|
|
2377
|
+
get errorCode() {
|
|
2378
|
+
return this.constructor.errorCode;
|
|
2379
|
+
}
|
|
2380
|
+
};
|
|
2381
|
+
var InvalidRequestError = class extends OAuthError {
|
|
2382
|
+
};
|
|
2383
|
+
InvalidRequestError.errorCode = "invalid_request";
|
|
2384
|
+
var InvalidClientError = class extends OAuthError {
|
|
2385
|
+
};
|
|
2386
|
+
InvalidClientError.errorCode = "invalid_client";
|
|
2387
|
+
var InvalidGrantError = class extends OAuthError {
|
|
2388
|
+
};
|
|
2389
|
+
InvalidGrantError.errorCode = "invalid_grant";
|
|
2390
|
+
var UnauthorizedClientError = class extends OAuthError {
|
|
2391
|
+
};
|
|
2392
|
+
UnauthorizedClientError.errorCode = "unauthorized_client";
|
|
2393
|
+
var UnsupportedGrantTypeError = class extends OAuthError {
|
|
2394
|
+
};
|
|
2395
|
+
UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
|
|
2396
|
+
var InvalidScopeError = class extends OAuthError {
|
|
2397
|
+
};
|
|
2398
|
+
InvalidScopeError.errorCode = "invalid_scope";
|
|
2399
|
+
var AccessDeniedError = class extends OAuthError {
|
|
2400
|
+
};
|
|
2401
|
+
AccessDeniedError.errorCode = "access_denied";
|
|
2402
|
+
var ServerError = class extends OAuthError {
|
|
2403
|
+
};
|
|
2404
|
+
ServerError.errorCode = "server_error";
|
|
2405
|
+
var TemporarilyUnavailableError = class extends OAuthError {
|
|
2406
|
+
};
|
|
2407
|
+
TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
|
|
2408
|
+
var UnsupportedResponseTypeError = class extends OAuthError {
|
|
2409
|
+
};
|
|
2410
|
+
UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
|
|
2411
|
+
var UnsupportedTokenTypeError = class extends OAuthError {
|
|
2412
|
+
};
|
|
2413
|
+
UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
|
|
2414
|
+
var InvalidTokenError = class extends OAuthError {
|
|
2415
|
+
};
|
|
2416
|
+
InvalidTokenError.errorCode = "invalid_token";
|
|
2417
|
+
var MethodNotAllowedError = class extends OAuthError {
|
|
2418
|
+
};
|
|
2419
|
+
MethodNotAllowedError.errorCode = "method_not_allowed";
|
|
2420
|
+
var TooManyRequestsError = class extends OAuthError {
|
|
2421
|
+
};
|
|
2422
|
+
TooManyRequestsError.errorCode = "too_many_requests";
|
|
2423
|
+
var InvalidClientMetadataError = class extends OAuthError {
|
|
2424
|
+
};
|
|
2425
|
+
InvalidClientMetadataError.errorCode = "invalid_client_metadata";
|
|
2426
|
+
var InsufficientScopeError = class extends OAuthError {
|
|
2427
|
+
};
|
|
2428
|
+
InsufficientScopeError.errorCode = "insufficient_scope";
|
|
2429
|
+
var InvalidTargetError = class extends OAuthError {
|
|
2430
|
+
};
|
|
2431
|
+
InvalidTargetError.errorCode = "invalid_target";
|
|
2432
|
+
var OAUTH_ERRORS = {
|
|
2433
|
+
[InvalidRequestError.errorCode]: InvalidRequestError,
|
|
2434
|
+
[InvalidClientError.errorCode]: InvalidClientError,
|
|
2435
|
+
[InvalidGrantError.errorCode]: InvalidGrantError,
|
|
2436
|
+
[UnauthorizedClientError.errorCode]: UnauthorizedClientError,
|
|
2437
|
+
[UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
|
|
2438
|
+
[InvalidScopeError.errorCode]: InvalidScopeError,
|
|
2439
|
+
[AccessDeniedError.errorCode]: AccessDeniedError,
|
|
2440
|
+
[ServerError.errorCode]: ServerError,
|
|
2441
|
+
[TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
|
|
2442
|
+
[UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
|
|
2443
|
+
[UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
|
|
2444
|
+
[InvalidTokenError.errorCode]: InvalidTokenError,
|
|
2445
|
+
[MethodNotAllowedError.errorCode]: MethodNotAllowedError,
|
|
2446
|
+
[TooManyRequestsError.errorCode]: TooManyRequestsError,
|
|
2447
|
+
[InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
|
|
2448
|
+
[InsufficientScopeError.errorCode]: InsufficientScopeError,
|
|
2449
|
+
[InvalidTargetError.errorCode]: InvalidTargetError
|
|
2450
|
+
};
|
|
2451
|
+
|
|
2452
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
|
|
2453
|
+
var UnauthorizedError = class extends Error {
|
|
2454
|
+
constructor(message) {
|
|
2455
|
+
super(message ?? "Unauthorized");
|
|
2456
|
+
}
|
|
2457
|
+
};
|
|
2458
|
+
function isClientAuthMethod(method) {
|
|
2459
|
+
return ["client_secret_basic", "client_secret_post", "none"].includes(method);
|
|
2460
|
+
}
|
|
2461
|
+
var AUTHORIZATION_CODE_RESPONSE_TYPE = "code";
|
|
2462
|
+
var AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
|
|
2463
|
+
function selectClientAuthMethod(clientInformation, supportedMethods) {
|
|
2464
|
+
const hasClientSecret = clientInformation.client_secret !== void 0;
|
|
2465
|
+
if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) {
|
|
2466
|
+
return clientInformation.token_endpoint_auth_method;
|
|
2467
|
+
}
|
|
2468
|
+
if (supportedMethods.length === 0) {
|
|
2469
|
+
return hasClientSecret ? "client_secret_basic" : "none";
|
|
2470
|
+
}
|
|
2471
|
+
if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
|
|
2472
|
+
return "client_secret_basic";
|
|
2473
|
+
}
|
|
2474
|
+
if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
|
|
2475
|
+
return "client_secret_post";
|
|
2476
|
+
}
|
|
2477
|
+
if (supportedMethods.includes("none")) {
|
|
2478
|
+
return "none";
|
|
2479
|
+
}
|
|
2480
|
+
return hasClientSecret ? "client_secret_post" : "none";
|
|
2481
|
+
}
|
|
2482
|
+
function applyClientAuthentication(method, clientInformation, headers, params) {
|
|
2483
|
+
const { client_id, client_secret } = clientInformation;
|
|
2484
|
+
switch (method) {
|
|
2485
|
+
case "client_secret_basic":
|
|
2486
|
+
applyBasicAuth(client_id, client_secret, headers);
|
|
2487
|
+
return;
|
|
2488
|
+
case "client_secret_post":
|
|
2489
|
+
applyPostAuth(client_id, client_secret, params);
|
|
2490
|
+
return;
|
|
2491
|
+
case "none":
|
|
2492
|
+
applyPublicAuth(client_id, params);
|
|
2493
|
+
return;
|
|
2494
|
+
default:
|
|
2495
|
+
throw new Error(`Unsupported client authentication method: ${method}`);
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
function applyBasicAuth(clientId, clientSecret, headers) {
|
|
2499
|
+
if (!clientSecret) {
|
|
2500
|
+
throw new Error("client_secret_basic authentication requires a client_secret");
|
|
2501
|
+
}
|
|
2502
|
+
const credentials = btoa(`${clientId}:${clientSecret}`);
|
|
2503
|
+
headers.set("Authorization", `Basic ${credentials}`);
|
|
2504
|
+
}
|
|
2505
|
+
function applyPostAuth(clientId, clientSecret, params) {
|
|
2506
|
+
params.set("client_id", clientId);
|
|
2507
|
+
if (clientSecret) {
|
|
2508
|
+
params.set("client_secret", clientSecret);
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
function applyPublicAuth(clientId, params) {
|
|
2512
|
+
params.set("client_id", clientId);
|
|
2513
|
+
}
|
|
2514
|
+
async function parseErrorResponse(input) {
|
|
2515
|
+
const statusCode = input instanceof Response ? input.status : void 0;
|
|
2516
|
+
const body = input instanceof Response ? await input.text() : input;
|
|
2517
|
+
try {
|
|
2518
|
+
const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
|
|
2519
|
+
const { error, error_description, error_uri } = result;
|
|
2520
|
+
const errorClass = OAUTH_ERRORS[error] || ServerError;
|
|
2521
|
+
return new errorClass(error_description || "", error_uri);
|
|
2522
|
+
} catch (error) {
|
|
2523
|
+
const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
|
|
2524
|
+
return new ServerError(errorMessage);
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
function issuersMatch(a, b) {
|
|
2528
|
+
let [x, y] = [a, b];
|
|
2529
|
+
try {
|
|
2530
|
+
[x, y] = [new URL(a).href, new URL(b).href];
|
|
2531
|
+
} catch {
|
|
2532
|
+
}
|
|
2533
|
+
return x === y || x.endsWith("/") && x.slice(0, -1) === y || y.endsWith("/") && y.slice(0, -1) === x;
|
|
2534
|
+
}
|
|
2535
|
+
function discardIfIssuerMismatch(stored, issuer) {
|
|
2536
|
+
if (!stored)
|
|
2537
|
+
return void 0;
|
|
2538
|
+
if (typeof stored.issuer !== "string")
|
|
2539
|
+
return stored.issuer == null ? stored : { ...stored, issuer: void 0 };
|
|
2540
|
+
return issuersMatch(stored.issuer, issuer) ? stored : void 0;
|
|
2541
|
+
}
|
|
2542
|
+
var TokenResponseSchema = OAuthTokensSchema.omit({ issuer: true });
|
|
2543
|
+
var RegistrationResponseSchema = OAuthClientInformationFullSchema.omit({ issuer: true });
|
|
2544
|
+
function boundElsewhereError(stored, issuer) {
|
|
2545
|
+
return new Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`);
|
|
2546
|
+
}
|
|
2547
|
+
async function auth(provider, options) {
|
|
2548
|
+
try {
|
|
2549
|
+
return await authInternal(provider, options);
|
|
2550
|
+
} catch (error) {
|
|
2551
|
+
if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
|
|
2552
|
+
await provider.invalidateCredentials?.("all");
|
|
2553
|
+
return await authInternal(provider, options);
|
|
2554
|
+
} else if (error instanceof InvalidGrantError) {
|
|
2555
|
+
await provider.invalidateCredentials?.("tokens");
|
|
2556
|
+
return await authInternal(provider, options);
|
|
2557
|
+
}
|
|
2558
|
+
throw error;
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
|
|
2562
|
+
const cachedState = await provider.discoveryState?.();
|
|
2563
|
+
let resourceMetadata;
|
|
2564
|
+
let authorizationServerUrl;
|
|
2565
|
+
let metadata;
|
|
2566
|
+
let effectiveResourceMetadataUrl = resourceMetadataUrl;
|
|
2567
|
+
if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {
|
|
2568
|
+
effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
|
|
2569
|
+
}
|
|
2570
|
+
if (cachedState?.authorizationServerUrl) {
|
|
2571
|
+
authorizationServerUrl = cachedState.authorizationServerUrl;
|
|
2572
|
+
resourceMetadata = cachedState.resourceMetadata;
|
|
2573
|
+
metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
|
|
2574
|
+
if (!resourceMetadata) {
|
|
2575
|
+
try {
|
|
2576
|
+
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
|
|
2577
|
+
} catch {
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {
|
|
2581
|
+
await provider.saveDiscoveryState?.({
|
|
2582
|
+
authorizationServerUrl: String(authorizationServerUrl),
|
|
2583
|
+
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
|
|
2584
|
+
resourceMetadata,
|
|
2585
|
+
authorizationServerMetadata: metadata
|
|
2586
|
+
});
|
|
2587
|
+
}
|
|
2588
|
+
} else {
|
|
2589
|
+
const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
|
|
2590
|
+
authorizationServerUrl = serverInfo.authorizationServerUrl;
|
|
2591
|
+
metadata = serverInfo.authorizationServerMetadata;
|
|
2592
|
+
resourceMetadata = serverInfo.resourceMetadata;
|
|
2593
|
+
await provider.saveDiscoveryState?.({
|
|
2594
|
+
authorizationServerUrl: String(authorizationServerUrl),
|
|
2595
|
+
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
|
|
2596
|
+
resourceMetadata,
|
|
2597
|
+
authorizationServerMetadata: metadata
|
|
2598
|
+
});
|
|
2599
|
+
}
|
|
2600
|
+
const issuer = String(authorizationServerUrl);
|
|
2601
|
+
const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);
|
|
2602
|
+
const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;
|
|
2603
|
+
const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
|
|
2604
|
+
const storedClientInformation = await Promise.resolve(provider.clientInformation());
|
|
2605
|
+
let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer);
|
|
2606
|
+
const canRegisterAgain = provider.saveClientInformation !== void 0 && !!provider.redirectUrl;
|
|
2607
|
+
if (storedClientInformation && !clientInformation && !canRegisterAgain) {
|
|
2608
|
+
throw boundElsewhereError(storedClientInformation, issuer);
|
|
2609
|
+
}
|
|
2610
|
+
const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : void 0;
|
|
2611
|
+
const bindClientInformation = async () => {
|
|
2612
|
+
try {
|
|
2613
|
+
if (unstampedClientInformation)
|
|
2614
|
+
await provider.saveClientInformation?.({ ...unstampedClientInformation, issuer });
|
|
2615
|
+
} catch {
|
|
2616
|
+
}
|
|
2617
|
+
};
|
|
2618
|
+
if (!clientInformation) {
|
|
2619
|
+
if (authorizationCode !== void 0) {
|
|
2620
|
+
throw new Error("Existing OAuth client information is required when exchanging an authorization code");
|
|
2621
|
+
}
|
|
2622
|
+
const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
|
|
2623
|
+
const clientMetadataUrl = provider.clientMetadataUrl;
|
|
2624
|
+
if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
|
|
2625
|
+
throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
|
|
2626
|
+
}
|
|
2627
|
+
const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
|
|
2628
|
+
if (shouldUseUrlBasedClientId) {
|
|
2629
|
+
clientInformation = { client_id: clientMetadataUrl, issuer };
|
|
2630
|
+
await provider.saveClientInformation?.(clientInformation);
|
|
2631
|
+
} else {
|
|
2632
|
+
if (!provider.saveClientInformation) {
|
|
2633
|
+
throw new Error("OAuth client information must be saveable for dynamic registration");
|
|
2634
|
+
}
|
|
2635
|
+
const fullInformation = await registerClient(authorizationServerUrl, {
|
|
2636
|
+
metadata,
|
|
2637
|
+
clientMetadata: provider.clientMetadata,
|
|
2638
|
+
scope: resolvedScope,
|
|
2639
|
+
fetchFn
|
|
2640
|
+
});
|
|
2641
|
+
clientInformation = { ...fullInformation, issuer };
|
|
2642
|
+
await provider.saveClientInformation(clientInformation);
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
const nonInteractiveFlow = !provider.redirectUrl;
|
|
2646
|
+
if (authorizationCode !== void 0 || nonInteractiveFlow) {
|
|
2647
|
+
const tokens2 = await fetchToken(provider, authorizationServerUrl, {
|
|
2648
|
+
metadata,
|
|
2649
|
+
resource,
|
|
2650
|
+
authorizationCode,
|
|
2651
|
+
fetchFn
|
|
2652
|
+
});
|
|
2653
|
+
await bindClientInformation();
|
|
2654
|
+
await provider.saveTokens({ ...tokens2, issuer });
|
|
2655
|
+
return "AUTHORIZED";
|
|
2656
|
+
}
|
|
2657
|
+
const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);
|
|
2658
|
+
if (tokens?.refresh_token && tokens.issuer == null) {
|
|
2659
|
+
console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.");
|
|
2660
|
+
}
|
|
2661
|
+
if (tokens?.refresh_token) {
|
|
2662
|
+
try {
|
|
2663
|
+
const newTokens = await refreshAuthorization(authorizationServerUrl, {
|
|
2664
|
+
metadata,
|
|
2665
|
+
clientInformation,
|
|
2666
|
+
refreshToken: tokens.refresh_token,
|
|
2667
|
+
resource,
|
|
2668
|
+
addClientAuthentication: provider.addClientAuthentication,
|
|
2669
|
+
fetchFn
|
|
2670
|
+
});
|
|
2671
|
+
await bindClientInformation();
|
|
2672
|
+
await provider.saveTokens({ ...newTokens, issuer });
|
|
2673
|
+
return "AUTHORIZED";
|
|
2674
|
+
} catch (error) {
|
|
2675
|
+
if (!(error instanceof OAuthError) || error instanceof ServerError) {
|
|
2676
|
+
} else {
|
|
2677
|
+
throw error;
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
}
|
|
2681
|
+
const state = provider.state ? await provider.state() : void 0;
|
|
2682
|
+
const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
|
|
2683
|
+
metadata,
|
|
2684
|
+
clientInformation,
|
|
2685
|
+
state,
|
|
2686
|
+
redirectUrl: provider.redirectUrl,
|
|
2687
|
+
scope: resolvedScope,
|
|
2688
|
+
resource
|
|
2689
|
+
});
|
|
2690
|
+
await provider.saveCodeVerifier(codeVerifier);
|
|
2691
|
+
await provider.redirectToAuthorization(authorizationUrl);
|
|
2692
|
+
return "REDIRECT";
|
|
2693
|
+
}
|
|
2694
|
+
function isHttpsUrl(value) {
|
|
2695
|
+
if (!value)
|
|
2696
|
+
return false;
|
|
2697
|
+
try {
|
|
2698
|
+
const url2 = new URL(value);
|
|
2699
|
+
return url2.protocol === "https:" && url2.pathname !== "/";
|
|
2700
|
+
} catch {
|
|
2701
|
+
return false;
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2704
|
+
async function selectResourceURL(serverUrl, provider, resourceMetadata) {
|
|
2705
|
+
const defaultResource = resourceUrlFromServerUrl(serverUrl);
|
|
2706
|
+
if (provider.validateResourceURL) {
|
|
2707
|
+
return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
|
|
2708
|
+
}
|
|
2709
|
+
if (!resourceMetadata) {
|
|
2710
|
+
return void 0;
|
|
2711
|
+
}
|
|
2712
|
+
if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
|
|
2713
|
+
throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
|
|
2714
|
+
}
|
|
2715
|
+
return new URL(resourceMetadata.resource);
|
|
2716
|
+
}
|
|
2717
|
+
function extractWWWAuthenticateParams(res) {
|
|
2718
|
+
const authenticateHeader = res.headers.get("WWW-Authenticate");
|
|
2719
|
+
if (!authenticateHeader) {
|
|
2720
|
+
return {};
|
|
2721
|
+
}
|
|
2722
|
+
const [type, scheme] = authenticateHeader.split(" ");
|
|
2723
|
+
if (type.toLowerCase() !== "bearer" || !scheme) {
|
|
2724
|
+
return {};
|
|
2725
|
+
}
|
|
2726
|
+
const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
|
|
2727
|
+
let resourceMetadataUrl;
|
|
2728
|
+
if (resourceMetadataMatch) {
|
|
2729
|
+
try {
|
|
2730
|
+
resourceMetadataUrl = new URL(resourceMetadataMatch);
|
|
2731
|
+
} catch {
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
|
|
2735
|
+
const error = extractFieldFromWwwAuth(res, "error") || void 0;
|
|
2736
|
+
return {
|
|
2737
|
+
resourceMetadataUrl,
|
|
2738
|
+
scope,
|
|
2739
|
+
error
|
|
2740
|
+
};
|
|
2741
|
+
}
|
|
2742
|
+
function extractFieldFromWwwAuth(response, fieldName) {
|
|
2743
|
+
const wwwAuthHeader = response.headers.get("WWW-Authenticate");
|
|
2744
|
+
if (!wwwAuthHeader) {
|
|
2745
|
+
return null;
|
|
2746
|
+
}
|
|
2747
|
+
const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
|
|
2748
|
+
const match = wwwAuthHeader.match(pattern);
|
|
2749
|
+
if (match) {
|
|
2750
|
+
return match[1] || match[2];
|
|
2751
|
+
}
|
|
2752
|
+
return null;
|
|
2753
|
+
}
|
|
2754
|
+
async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
|
|
2755
|
+
const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
|
|
2756
|
+
protocolVersion: opts?.protocolVersion,
|
|
2757
|
+
metadataUrl: opts?.resourceMetadataUrl
|
|
2758
|
+
});
|
|
2759
|
+
if (!response || response.status === 404) {
|
|
2760
|
+
await response?.body?.cancel();
|
|
2761
|
+
throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
|
|
2762
|
+
}
|
|
2763
|
+
if (!response.ok) {
|
|
2764
|
+
await response.body?.cancel();
|
|
2765
|
+
throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
|
|
2766
|
+
}
|
|
2767
|
+
return OAuthProtectedResourceMetadataSchema.parse(await response.json());
|
|
2768
|
+
}
|
|
2769
|
+
async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
|
|
2770
|
+
try {
|
|
2771
|
+
return await fetchFn(url2, { headers });
|
|
2772
|
+
} catch (error) {
|
|
2773
|
+
if (error instanceof TypeError) {
|
|
2774
|
+
if (headers) {
|
|
2775
|
+
return fetchWithCorsRetry(url2, void 0, fetchFn);
|
|
2776
|
+
} else {
|
|
2777
|
+
return void 0;
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
throw error;
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
|
|
2784
|
+
if (pathname.endsWith("/")) {
|
|
2785
|
+
pathname = pathname.slice(0, -1);
|
|
2786
|
+
}
|
|
2787
|
+
return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
|
|
2788
|
+
}
|
|
2789
|
+
async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
|
|
2790
|
+
const headers = {
|
|
2791
|
+
"MCP-Protocol-Version": protocolVersion
|
|
2792
|
+
};
|
|
2793
|
+
return await fetchWithCorsRetry(url2, headers, fetchFn);
|
|
2794
|
+
}
|
|
2795
|
+
function shouldAttemptFallback(response, pathname) {
|
|
2796
|
+
return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
|
|
2797
|
+
}
|
|
2798
|
+
async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
|
|
2799
|
+
const issuer = new URL(serverUrl);
|
|
2800
|
+
const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;
|
|
2801
|
+
let url2;
|
|
2802
|
+
if (opts?.metadataUrl) {
|
|
2803
|
+
url2 = new URL(opts.metadataUrl);
|
|
2804
|
+
} else {
|
|
2805
|
+
const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
|
|
2806
|
+
url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
|
|
2807
|
+
url2.search = issuer.search;
|
|
2808
|
+
}
|
|
2809
|
+
let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
|
|
2810
|
+
if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
|
|
2811
|
+
const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
|
|
2812
|
+
response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
|
|
2813
|
+
}
|
|
2814
|
+
return response;
|
|
2815
|
+
}
|
|
2816
|
+
function buildDiscoveryUrls(authorizationServerUrl) {
|
|
2817
|
+
const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
|
|
2818
|
+
const hasPath = url2.pathname !== "/";
|
|
2819
|
+
const urlsToTry = [];
|
|
2820
|
+
if (!hasPath) {
|
|
2821
|
+
urlsToTry.push({
|
|
2822
|
+
url: new URL("/.well-known/oauth-authorization-server", url2.origin),
|
|
2823
|
+
type: "oauth"
|
|
2824
|
+
});
|
|
2825
|
+
urlsToTry.push({
|
|
2826
|
+
url: new URL(`/.well-known/openid-configuration`, url2.origin),
|
|
2827
|
+
type: "oidc"
|
|
2828
|
+
});
|
|
2829
|
+
return urlsToTry;
|
|
2830
|
+
}
|
|
2831
|
+
let pathname = url2.pathname;
|
|
2832
|
+
if (pathname.endsWith("/")) {
|
|
2833
|
+
pathname = pathname.slice(0, -1);
|
|
2834
|
+
}
|
|
2835
|
+
urlsToTry.push({
|
|
2836
|
+
url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin),
|
|
2837
|
+
type: "oauth"
|
|
2838
|
+
});
|
|
2839
|
+
urlsToTry.push({
|
|
2840
|
+
url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin),
|
|
2841
|
+
type: "oidc"
|
|
2842
|
+
});
|
|
2843
|
+
urlsToTry.push({
|
|
2844
|
+
url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin),
|
|
2845
|
+
type: "oidc"
|
|
2846
|
+
});
|
|
2847
|
+
return urlsToTry;
|
|
2848
|
+
}
|
|
2849
|
+
async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
|
|
2850
|
+
const headers = {
|
|
2851
|
+
"MCP-Protocol-Version": protocolVersion,
|
|
2852
|
+
Accept: "application/json"
|
|
2853
|
+
};
|
|
2854
|
+
const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
|
|
2855
|
+
for (const { url: endpointUrl, type } of urlsToTry) {
|
|
2856
|
+
const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
|
|
2857
|
+
if (!response) {
|
|
2858
|
+
continue;
|
|
2859
|
+
}
|
|
2860
|
+
if (!response.ok) {
|
|
2861
|
+
await response.body?.cancel();
|
|
2862
|
+
if (response.status >= 400 && response.status < 500) {
|
|
2863
|
+
continue;
|
|
2864
|
+
}
|
|
2865
|
+
throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
|
|
2866
|
+
}
|
|
2867
|
+
if (type === "oauth") {
|
|
2868
|
+
return OAuthMetadataSchema.parse(await response.json());
|
|
2869
|
+
} else {
|
|
2870
|
+
return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2873
|
+
return void 0;
|
|
2874
|
+
}
|
|
2875
|
+
async function discoverOAuthServerInfo(serverUrl, opts) {
|
|
2876
|
+
let resourceMetadata;
|
|
2877
|
+
let authorizationServerUrl;
|
|
2878
|
+
try {
|
|
2879
|
+
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
|
|
2880
|
+
if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
|
|
2881
|
+
authorizationServerUrl = resourceMetadata.authorization_servers[0];
|
|
2882
|
+
}
|
|
2883
|
+
} catch {
|
|
2884
|
+
}
|
|
2885
|
+
if (!authorizationServerUrl) {
|
|
2886
|
+
authorizationServerUrl = String(new URL("/", serverUrl));
|
|
2887
|
+
}
|
|
2888
|
+
const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
|
|
2889
|
+
return {
|
|
2890
|
+
authorizationServerUrl,
|
|
2891
|
+
authorizationServerMetadata,
|
|
2892
|
+
resourceMetadata
|
|
2893
|
+
};
|
|
2894
|
+
}
|
|
2895
|
+
function resourceIndicatorToString(resource) {
|
|
2896
|
+
return typeof resource === "string" ? resource : resource.href;
|
|
2897
|
+
}
|
|
2898
|
+
async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
|
|
2899
|
+
let authorizationUrl;
|
|
2900
|
+
if (metadata) {
|
|
2901
|
+
authorizationUrl = new URL(metadata.authorization_endpoint);
|
|
2902
|
+
if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
|
|
2903
|
+
throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
|
|
2904
|
+
}
|
|
2905
|
+
if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {
|
|
2906
|
+
throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
|
|
2907
|
+
}
|
|
2908
|
+
} else {
|
|
2909
|
+
authorizationUrl = new URL("/authorize", authorizationServerUrl);
|
|
2910
|
+
}
|
|
2911
|
+
const challenge = await pkceChallenge();
|
|
2912
|
+
const codeVerifier = challenge.code_verifier;
|
|
2913
|
+
const codeChallenge = challenge.code_challenge;
|
|
2914
|
+
authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE);
|
|
2915
|
+
authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
|
|
2916
|
+
authorizationUrl.searchParams.set("code_challenge", codeChallenge);
|
|
2917
|
+
authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD);
|
|
2918
|
+
authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
|
|
2919
|
+
if (state) {
|
|
2920
|
+
authorizationUrl.searchParams.set("state", state);
|
|
2921
|
+
}
|
|
2922
|
+
if (scope) {
|
|
2923
|
+
authorizationUrl.searchParams.set("scope", scope);
|
|
2924
|
+
}
|
|
2925
|
+
if (scope?.includes("offline_access")) {
|
|
2926
|
+
authorizationUrl.searchParams.append("prompt", "consent");
|
|
2927
|
+
}
|
|
2928
|
+
if (resource) {
|
|
2929
|
+
authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource));
|
|
2930
|
+
}
|
|
2931
|
+
return { authorizationUrl, codeVerifier };
|
|
2932
|
+
}
|
|
2933
|
+
function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
|
|
2934
|
+
return new URLSearchParams({
|
|
2935
|
+
grant_type: "authorization_code",
|
|
2936
|
+
code: authorizationCode,
|
|
2937
|
+
code_verifier: codeVerifier,
|
|
2938
|
+
redirect_uri: String(redirectUri)
|
|
2939
|
+
});
|
|
2940
|
+
}
|
|
2941
|
+
async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
|
|
2942
|
+
const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
|
|
2943
|
+
const headers = new Headers({
|
|
2944
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
2945
|
+
Accept: "application/json"
|
|
2946
|
+
});
|
|
2947
|
+
if (resource) {
|
|
2948
|
+
tokenRequestParams.set("resource", resourceIndicatorToString(resource));
|
|
2949
|
+
}
|
|
2950
|
+
if (addClientAuthentication) {
|
|
2951
|
+
await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
|
|
2952
|
+
} else if (clientInformation) {
|
|
2953
|
+
const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
|
|
2954
|
+
const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
|
|
2955
|
+
applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
|
|
2956
|
+
}
|
|
2957
|
+
const response = await (fetchFn ?? fetch)(tokenUrl, {
|
|
2958
|
+
method: "POST",
|
|
2959
|
+
headers,
|
|
2960
|
+
body: tokenRequestParams
|
|
2961
|
+
});
|
|
2962
|
+
if (!response.ok) {
|
|
2963
|
+
throw await parseErrorResponse(response);
|
|
2964
|
+
}
|
|
2965
|
+
return TokenResponseSchema.parse(await response.json());
|
|
2966
|
+
}
|
|
2967
|
+
async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
|
|
2968
|
+
const tokenRequestParams = new URLSearchParams({
|
|
2969
|
+
grant_type: "refresh_token",
|
|
2970
|
+
refresh_token: refreshToken
|
|
2971
|
+
});
|
|
2972
|
+
const tokens = await executeTokenRequest(authorizationServerUrl, {
|
|
2973
|
+
metadata,
|
|
2974
|
+
tokenRequestParams,
|
|
2975
|
+
clientInformation,
|
|
2976
|
+
addClientAuthentication,
|
|
2977
|
+
resource,
|
|
2978
|
+
fetchFn
|
|
2979
|
+
});
|
|
2980
|
+
return { refresh_token: refreshToken, ...tokens };
|
|
2981
|
+
}
|
|
2982
|
+
async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
|
|
2983
|
+
const readClientInformation = async () => {
|
|
2984
|
+
const storedClientInformation = await provider.clientInformation();
|
|
2985
|
+
const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));
|
|
2986
|
+
if (storedClientInformation && !checked) {
|
|
2987
|
+
throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));
|
|
2988
|
+
}
|
|
2989
|
+
return checked;
|
|
2990
|
+
};
|
|
2991
|
+
let clientInformation = await readClientInformation();
|
|
2992
|
+
const scope = provider.clientMetadata.scope;
|
|
2993
|
+
let tokenRequestParams;
|
|
2994
|
+
if (provider.prepareTokenRequest) {
|
|
2995
|
+
tokenRequestParams = await provider.prepareTokenRequest(scope);
|
|
2996
|
+
}
|
|
2997
|
+
if (!tokenRequestParams) {
|
|
2998
|
+
if (!authorizationCode) {
|
|
2999
|
+
throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
|
|
3000
|
+
}
|
|
3001
|
+
if (!provider.redirectUrl) {
|
|
3002
|
+
throw new Error("redirectUrl is required for authorization_code flow");
|
|
3003
|
+
}
|
|
3004
|
+
const codeVerifier = await provider.codeVerifier();
|
|
3005
|
+
tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
|
|
3006
|
+
}
|
|
3007
|
+
clientInformation ?? (clientInformation = await readClientInformation());
|
|
3008
|
+
return executeTokenRequest(authorizationServerUrl, {
|
|
3009
|
+
metadata,
|
|
3010
|
+
tokenRequestParams,
|
|
3011
|
+
clientInformation,
|
|
3012
|
+
addClientAuthentication: provider.addClientAuthentication,
|
|
3013
|
+
resource,
|
|
3014
|
+
fetchFn
|
|
3015
|
+
});
|
|
3016
|
+
}
|
|
3017
|
+
async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {
|
|
3018
|
+
let registrationUrl;
|
|
3019
|
+
if (metadata) {
|
|
3020
|
+
if (!metadata.registration_endpoint) {
|
|
3021
|
+
throw new Error("Incompatible auth server: does not support dynamic client registration");
|
|
3022
|
+
}
|
|
3023
|
+
registrationUrl = new URL(metadata.registration_endpoint);
|
|
3024
|
+
} else {
|
|
3025
|
+
registrationUrl = new URL("/register", authorizationServerUrl);
|
|
3026
|
+
}
|
|
3027
|
+
const response = await (fetchFn ?? fetch)(registrationUrl, {
|
|
3028
|
+
method: "POST",
|
|
3029
|
+
headers: {
|
|
3030
|
+
"Content-Type": "application/json"
|
|
3031
|
+
},
|
|
3032
|
+
body: JSON.stringify({
|
|
3033
|
+
...clientMetadata,
|
|
3034
|
+
...scope !== void 0 ? { scope } : {}
|
|
3035
|
+
})
|
|
3036
|
+
});
|
|
3037
|
+
if (!response.ok) {
|
|
3038
|
+
throw await parseErrorResponse(response);
|
|
3039
|
+
}
|
|
3040
|
+
return RegistrationResponseSchema.parse(await response.json());
|
|
3041
|
+
}
|
|
3042
|
+
|
|
3043
|
+
// node_modules/eventsource-parser/dist/index.js
|
|
3044
|
+
var ParseError = class extends Error {
|
|
3045
|
+
constructor(message, options) {
|
|
3046
|
+
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
|
|
3047
|
+
}
|
|
3048
|
+
};
|
|
3049
|
+
var LF = 10;
|
|
3050
|
+
var CR = 13;
|
|
3051
|
+
var SPACE = 32;
|
|
3052
|
+
function noop(_arg) {
|
|
3053
|
+
}
|
|
3054
|
+
function createParser(config) {
|
|
3055
|
+
if (typeof config == "function")
|
|
3056
|
+
throw new TypeError(
|
|
3057
|
+
"`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
|
|
3058
|
+
);
|
|
3059
|
+
const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];
|
|
3060
|
+
let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
|
|
3061
|
+
function feed(chunk) {
|
|
3062
|
+
if (terminated)
|
|
3063
|
+
throw new Error(
|
|
3064
|
+
"Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
|
|
3065
|
+
);
|
|
3066
|
+
if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
|
|
3067
|
+
const trailing2 = processLines(chunk);
|
|
3068
|
+
trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
|
|
3069
|
+
return;
|
|
3070
|
+
}
|
|
3071
|
+
if (chunk.indexOf(`
|
|
3072
|
+
`) === -1 && chunk.indexOf("\r") === -1) {
|
|
3073
|
+
pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
|
|
3074
|
+
return;
|
|
3075
|
+
}
|
|
3076
|
+
pendingFragments.push(chunk);
|
|
3077
|
+
const input = pendingFragments.join("");
|
|
3078
|
+
pendingFragments.length = 0, pendingFragmentsLength = 0;
|
|
3079
|
+
const trailing = processLines(input);
|
|
3080
|
+
trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
|
|
3081
|
+
}
|
|
3082
|
+
function checkBufferSize() {
|
|
3083
|
+
maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
|
|
3084
|
+
new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
|
|
3085
|
+
type: "max-buffer-size-exceeded"
|
|
3086
|
+
})
|
|
3087
|
+
)));
|
|
3088
|
+
}
|
|
3089
|
+
function processLines(chunk) {
|
|
3090
|
+
let searchIndex = 0;
|
|
3091
|
+
if (chunk.indexOf("\r") === -1) {
|
|
3092
|
+
let lfIndex = chunk.indexOf(`
|
|
3093
|
+
`, searchIndex);
|
|
3094
|
+
for (; lfIndex !== -1; ) {
|
|
3095
|
+
if (searchIndex === lfIndex) {
|
|
3096
|
+
dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
|
|
3097
|
+
`, searchIndex);
|
|
3098
|
+
continue;
|
|
3099
|
+
}
|
|
3100
|
+
const firstCharCode = chunk.charCodeAt(searchIndex);
|
|
3101
|
+
if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
|
|
3102
|
+
const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
|
|
3103
|
+
if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
|
|
3104
|
+
onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
|
|
3105
|
+
`, searchIndex);
|
|
3106
|
+
continue;
|
|
3107
|
+
}
|
|
3108
|
+
data = dataLines === 0 ? value : `${data}
|
|
3109
|
+
${value}`, dataLines++;
|
|
3110
|
+
} else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
|
|
3111
|
+
chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
|
|
3112
|
+
lfIndex
|
|
3113
|
+
) || void 0 : parseLine(chunk, searchIndex, lfIndex);
|
|
3114
|
+
searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
|
|
3115
|
+
`, searchIndex);
|
|
3116
|
+
}
|
|
3117
|
+
return chunk.slice(searchIndex);
|
|
3118
|
+
}
|
|
3119
|
+
for (; searchIndex < chunk.length; ) {
|
|
3120
|
+
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
|
|
3121
|
+
`, searchIndex);
|
|
3122
|
+
let lineEnd = -1;
|
|
3123
|
+
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
|
|
3124
|
+
break;
|
|
3125
|
+
parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
|
|
3126
|
+
}
|
|
3127
|
+
return chunk.slice(searchIndex);
|
|
3128
|
+
}
|
|
3129
|
+
function parseLine(chunk, start, end) {
|
|
3130
|
+
if (start === end) {
|
|
3131
|
+
dispatchEvent();
|
|
3132
|
+
return;
|
|
3133
|
+
}
|
|
3134
|
+
const firstCharCode = chunk.charCodeAt(start);
|
|
3135
|
+
if (isDataPrefix(chunk, start, firstCharCode)) {
|
|
3136
|
+
const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
|
|
3137
|
+
data = dataLines === 0 ? value2 : `${data}
|
|
3138
|
+
${value2}`, dataLines++;
|
|
3139
|
+
return;
|
|
3140
|
+
}
|
|
3141
|
+
if (isEventPrefix(chunk, start, firstCharCode)) {
|
|
3142
|
+
eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
|
|
3143
|
+
return;
|
|
3144
|
+
}
|
|
3145
|
+
if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
|
|
3146
|
+
const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
|
|
3147
|
+
value2.includes("\0") || (id = value2);
|
|
3148
|
+
return;
|
|
3149
|
+
}
|
|
3150
|
+
if (firstCharCode === 58) {
|
|
3151
|
+
if (onComment) {
|
|
3152
|
+
const line2 = chunk.slice(start, end);
|
|
3153
|
+
onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
|
|
3154
|
+
}
|
|
3155
|
+
return;
|
|
3156
|
+
}
|
|
3157
|
+
const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
|
|
3158
|
+
if (fieldSeparatorIndex === -1) {
|
|
3159
|
+
processField(line, "", line);
|
|
3160
|
+
return;
|
|
3161
|
+
}
|
|
3162
|
+
const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
|
|
3163
|
+
processField(field, value, line);
|
|
3164
|
+
}
|
|
3165
|
+
function processField(field, value, line) {
|
|
3166
|
+
switch (field) {
|
|
3167
|
+
case "event":
|
|
3168
|
+
eventType = value || void 0;
|
|
3169
|
+
break;
|
|
3170
|
+
case "data":
|
|
3171
|
+
data = dataLines === 0 ? value : `${data}
|
|
3172
|
+
${value}`, dataLines++;
|
|
3173
|
+
break;
|
|
3174
|
+
case "id":
|
|
3175
|
+
value.includes("\0") || (id = value);
|
|
3176
|
+
break;
|
|
3177
|
+
case "retry":
|
|
3178
|
+
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
|
|
3179
|
+
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
3180
|
+
type: "invalid-retry",
|
|
3181
|
+
value,
|
|
3182
|
+
line
|
|
3183
|
+
})
|
|
3184
|
+
);
|
|
3185
|
+
break;
|
|
3186
|
+
default:
|
|
3187
|
+
onError(
|
|
3188
|
+
new ParseError(
|
|
3189
|
+
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
|
|
3190
|
+
{ type: "unknown-field", field, value, line }
|
|
3191
|
+
)
|
|
3192
|
+
);
|
|
3193
|
+
break;
|
|
3194
|
+
}
|
|
3195
|
+
}
|
|
3196
|
+
function dispatchEvent() {
|
|
3197
|
+
dataLines > 0 && onEvent({
|
|
3198
|
+
id,
|
|
3199
|
+
event: eventType,
|
|
3200
|
+
data
|
|
3201
|
+
}), id = void 0, data = "", dataLines = 0, eventType = void 0;
|
|
3202
|
+
}
|
|
3203
|
+
function reset(options = {}) {
|
|
3204
|
+
if (options.consume && pendingFragments.length > 0) {
|
|
3205
|
+
const incompleteLine = pendingFragments.join("");
|
|
3206
|
+
parseLine(incompleteLine, 0, incompleteLine.length);
|
|
3207
|
+
}
|
|
3208
|
+
isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
|
|
3209
|
+
}
|
|
3210
|
+
return { feed, reset };
|
|
3211
|
+
}
|
|
3212
|
+
function isDataPrefix(chunk, i, firstCharCode) {
|
|
3213
|
+
return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
|
|
3214
|
+
}
|
|
3215
|
+
function isEventPrefix(chunk, i, firstCharCode) {
|
|
3216
|
+
return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
|
|
3217
|
+
}
|
|
3218
|
+
|
|
3219
|
+
// node_modules/eventsource-parser/dist/stream.js
|
|
3220
|
+
var EventSourceParserStream = class extends TransformStream {
|
|
3221
|
+
constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
|
|
3222
|
+
let parser;
|
|
3223
|
+
super({
|
|
3224
|
+
start(controller) {
|
|
3225
|
+
parser = createParser({
|
|
3226
|
+
onEvent: (event) => {
|
|
3227
|
+
controller.enqueue(event);
|
|
3228
|
+
},
|
|
3229
|
+
onError(error) {
|
|
3230
|
+
typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
|
|
3231
|
+
},
|
|
3232
|
+
onRetry,
|
|
3233
|
+
onComment,
|
|
3234
|
+
maxBufferSize
|
|
3235
|
+
});
|
|
3236
|
+
},
|
|
3237
|
+
transform(chunk) {
|
|
3238
|
+
parser.feed(chunk);
|
|
3239
|
+
}
|
|
3240
|
+
});
|
|
3241
|
+
}
|
|
3242
|
+
};
|
|
3243
|
+
|
|
3244
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
|
|
3245
|
+
var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
|
|
3246
|
+
initialReconnectionDelay: 1e3,
|
|
3247
|
+
maxReconnectionDelay: 3e4,
|
|
3248
|
+
reconnectionDelayGrowFactor: 1.5,
|
|
3249
|
+
maxRetries: 2
|
|
3250
|
+
};
|
|
3251
|
+
var StreamableHTTPError = class extends Error {
|
|
3252
|
+
constructor(code, message) {
|
|
3253
|
+
super(`Streamable HTTP error: ${message}`);
|
|
3254
|
+
this.code = code;
|
|
3255
|
+
}
|
|
3256
|
+
};
|
|
3257
|
+
var StreamableHTTPClientTransport = class {
|
|
3258
|
+
constructor(url2, opts) {
|
|
3259
|
+
this._hasCompletedAuthFlow = false;
|
|
3260
|
+
this._url = url2;
|
|
3261
|
+
this._resourceMetadataUrl = void 0;
|
|
3262
|
+
this._scope = void 0;
|
|
3263
|
+
this._requestInit = opts?.requestInit;
|
|
3264
|
+
this._authProvider = opts?.authProvider;
|
|
3265
|
+
this._fetch = opts?.fetch;
|
|
3266
|
+
this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
|
|
3267
|
+
this._sessionId = opts?.sessionId;
|
|
3268
|
+
this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
|
|
3269
|
+
}
|
|
3270
|
+
async _authThenStart() {
|
|
3271
|
+
if (!this._authProvider) {
|
|
3272
|
+
throw new UnauthorizedError("No auth provider");
|
|
3273
|
+
}
|
|
3274
|
+
let result;
|
|
3275
|
+
try {
|
|
3276
|
+
result = await auth(this._authProvider, {
|
|
3277
|
+
serverUrl: this._url,
|
|
3278
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
3279
|
+
scope: this._scope,
|
|
3280
|
+
fetchFn: this._fetchWithInit
|
|
3281
|
+
});
|
|
3282
|
+
} catch (error) {
|
|
3283
|
+
this.onerror?.(error);
|
|
3284
|
+
throw error;
|
|
3285
|
+
}
|
|
3286
|
+
if (result !== "AUTHORIZED") {
|
|
3287
|
+
throw new UnauthorizedError();
|
|
3288
|
+
}
|
|
3289
|
+
return await this._startOrAuthSse({ resumptionToken: void 0 });
|
|
3290
|
+
}
|
|
3291
|
+
async _commonHeaders() {
|
|
3292
|
+
const headers = {};
|
|
3293
|
+
if (this._authProvider) {
|
|
3294
|
+
const tokens = await this._authProvider.tokens();
|
|
3295
|
+
if (tokens) {
|
|
3296
|
+
headers["Authorization"] = `Bearer ${tokens.access_token}`;
|
|
3297
|
+
}
|
|
3298
|
+
}
|
|
3299
|
+
if (this._sessionId) {
|
|
3300
|
+
headers["mcp-session-id"] = this._sessionId;
|
|
3301
|
+
}
|
|
3302
|
+
if (this._protocolVersion) {
|
|
3303
|
+
headers["mcp-protocol-version"] = this._protocolVersion;
|
|
3304
|
+
}
|
|
3305
|
+
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
|
|
3306
|
+
return new Headers({
|
|
3307
|
+
...headers,
|
|
3308
|
+
...extraHeaders
|
|
3309
|
+
});
|
|
3310
|
+
}
|
|
3311
|
+
async _startOrAuthSse(options) {
|
|
3312
|
+
const { resumptionToken } = options;
|
|
3313
|
+
try {
|
|
3314
|
+
const headers = await this._commonHeaders();
|
|
3315
|
+
headers.set("Accept", "text/event-stream");
|
|
3316
|
+
if (resumptionToken) {
|
|
3317
|
+
headers.set("last-event-id", resumptionToken);
|
|
3318
|
+
}
|
|
3319
|
+
const response = await (this._fetch ?? fetch)(this._url, {
|
|
3320
|
+
method: "GET",
|
|
3321
|
+
headers,
|
|
3322
|
+
signal: this._abortController?.signal
|
|
3323
|
+
});
|
|
3324
|
+
if (!response.ok) {
|
|
3325
|
+
await response.body?.cancel();
|
|
3326
|
+
if (response.status === 401 && this._authProvider) {
|
|
3327
|
+
return await this._authThenStart();
|
|
3328
|
+
}
|
|
3329
|
+
if (response.status === 405) {
|
|
3330
|
+
return;
|
|
3331
|
+
}
|
|
3332
|
+
throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
|
|
3333
|
+
}
|
|
3334
|
+
this._handleSseStream(response.body, options, true);
|
|
3335
|
+
} catch (error) {
|
|
3336
|
+
this.onerror?.(error);
|
|
3337
|
+
throw error;
|
|
3338
|
+
}
|
|
3339
|
+
}
|
|
3340
|
+
/**
|
|
3341
|
+
* Calculates the next reconnection delay using backoff algorithm
|
|
3342
|
+
*
|
|
3343
|
+
* @param attempt Current reconnection attempt count for the specific stream
|
|
3344
|
+
* @returns Time to wait in milliseconds before next reconnection attempt
|
|
3345
|
+
*/
|
|
3346
|
+
_getNextReconnectionDelay(attempt) {
|
|
3347
|
+
if (this._serverRetryMs !== void 0) {
|
|
3348
|
+
return this._serverRetryMs;
|
|
3349
|
+
}
|
|
3350
|
+
const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
|
|
3351
|
+
const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
|
|
3352
|
+
const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
|
|
3353
|
+
return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
|
|
3354
|
+
}
|
|
3355
|
+
/**
|
|
3356
|
+
* Schedule a reconnection attempt using server-provided retry interval or backoff
|
|
3357
|
+
*
|
|
3358
|
+
* @param lastEventId The ID of the last received event for resumability
|
|
3359
|
+
* @param attemptCount Current reconnection attempt count for this specific stream
|
|
3360
|
+
*/
|
|
3361
|
+
_scheduleReconnection(options, attemptCount = 0) {
|
|
3362
|
+
const maxRetries = this._reconnectionOptions.maxRetries;
|
|
3363
|
+
if (attemptCount >= maxRetries) {
|
|
3364
|
+
this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
|
|
3365
|
+
return;
|
|
3366
|
+
}
|
|
3367
|
+
const delay = this._getNextReconnectionDelay(attemptCount);
|
|
3368
|
+
this._reconnectionTimeout = setTimeout(() => {
|
|
3369
|
+
this._startOrAuthSse(options).catch((error) => {
|
|
3370
|
+
this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
|
|
3371
|
+
this._scheduleReconnection(options, attemptCount + 1);
|
|
3372
|
+
});
|
|
3373
|
+
}, delay);
|
|
3374
|
+
}
|
|
3375
|
+
_handleSseStream(stream, options, isReconnectable) {
|
|
3376
|
+
if (!stream) {
|
|
3377
|
+
return;
|
|
3378
|
+
}
|
|
3379
|
+
const { onresumptiontoken, replayMessageId } = options;
|
|
3380
|
+
let lastEventId;
|
|
3381
|
+
let hasPrimingEvent = false;
|
|
3382
|
+
let receivedResponse = false;
|
|
3383
|
+
const processStream = async () => {
|
|
3384
|
+
try {
|
|
3385
|
+
const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
|
|
3386
|
+
onRetry: (retryMs) => {
|
|
3387
|
+
this._serverRetryMs = retryMs;
|
|
3388
|
+
}
|
|
3389
|
+
})).getReader();
|
|
3390
|
+
while (true) {
|
|
3391
|
+
const { value: event, done } = await reader.read();
|
|
3392
|
+
if (done) {
|
|
3393
|
+
break;
|
|
3394
|
+
}
|
|
3395
|
+
if (event.id) {
|
|
3396
|
+
lastEventId = event.id;
|
|
3397
|
+
hasPrimingEvent = true;
|
|
3398
|
+
onresumptiontoken?.(event.id);
|
|
3399
|
+
}
|
|
3400
|
+
if (!event.data) {
|
|
3401
|
+
continue;
|
|
3402
|
+
}
|
|
3403
|
+
if (!event.event || event.event === "message") {
|
|
3404
|
+
try {
|
|
3405
|
+
const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
|
|
3406
|
+
if (isJSONRPCResultResponse(message)) {
|
|
3407
|
+
receivedResponse = true;
|
|
3408
|
+
if (replayMessageId !== void 0) {
|
|
3409
|
+
message.id = replayMessageId;
|
|
3410
|
+
}
|
|
3411
|
+
}
|
|
3412
|
+
this.onmessage?.(message);
|
|
3413
|
+
} catch (error) {
|
|
3414
|
+
this.onerror?.(error);
|
|
3415
|
+
}
|
|
3416
|
+
}
|
|
3417
|
+
}
|
|
3418
|
+
const canResume = isReconnectable || hasPrimingEvent;
|
|
3419
|
+
const needsReconnect = canResume && !receivedResponse;
|
|
3420
|
+
if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
|
|
3421
|
+
this._scheduleReconnection({
|
|
3422
|
+
resumptionToken: lastEventId,
|
|
3423
|
+
onresumptiontoken,
|
|
3424
|
+
replayMessageId
|
|
3425
|
+
}, 0);
|
|
3426
|
+
}
|
|
3427
|
+
} catch (error) {
|
|
3428
|
+
this.onerror?.(new Error(`SSE stream disconnected: ${error}`));
|
|
3429
|
+
const canResume = isReconnectable || hasPrimingEvent;
|
|
3430
|
+
const needsReconnect = canResume && !receivedResponse;
|
|
3431
|
+
if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
|
|
3432
|
+
try {
|
|
3433
|
+
this._scheduleReconnection({
|
|
3434
|
+
resumptionToken: lastEventId,
|
|
3435
|
+
onresumptiontoken,
|
|
3436
|
+
replayMessageId
|
|
3437
|
+
}, 0);
|
|
3438
|
+
} catch (error2) {
|
|
3439
|
+
this.onerror?.(new Error(`Failed to reconnect: ${error2 instanceof Error ? error2.message : String(error2)}`));
|
|
3440
|
+
}
|
|
3441
|
+
}
|
|
3442
|
+
}
|
|
3443
|
+
};
|
|
3444
|
+
processStream();
|
|
3445
|
+
}
|
|
3446
|
+
async start() {
|
|
3447
|
+
if (this._abortController) {
|
|
3448
|
+
throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
|
|
3449
|
+
}
|
|
3450
|
+
this._abortController = new AbortController();
|
|
3451
|
+
}
|
|
3452
|
+
/**
|
|
3453
|
+
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
|
|
3454
|
+
*/
|
|
3455
|
+
async finishAuth(authorizationCode) {
|
|
3456
|
+
if (!this._authProvider) {
|
|
3457
|
+
throw new UnauthorizedError("No auth provider");
|
|
3458
|
+
}
|
|
3459
|
+
const result = await auth(this._authProvider, {
|
|
3460
|
+
serverUrl: this._url,
|
|
3461
|
+
authorizationCode,
|
|
3462
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
3463
|
+
scope: this._scope,
|
|
3464
|
+
fetchFn: this._fetchWithInit
|
|
3465
|
+
});
|
|
3466
|
+
if (result !== "AUTHORIZED") {
|
|
3467
|
+
throw new UnauthorizedError("Failed to authorize");
|
|
3468
|
+
}
|
|
3469
|
+
}
|
|
3470
|
+
async close() {
|
|
3471
|
+
if (this._reconnectionTimeout) {
|
|
3472
|
+
clearTimeout(this._reconnectionTimeout);
|
|
3473
|
+
this._reconnectionTimeout = void 0;
|
|
3474
|
+
}
|
|
3475
|
+
this._abortController?.abort();
|
|
3476
|
+
this.onclose?.();
|
|
3477
|
+
}
|
|
3478
|
+
async send(message, options) {
|
|
3479
|
+
try {
|
|
3480
|
+
const { resumptionToken, onresumptiontoken } = options || {};
|
|
3481
|
+
if (resumptionToken) {
|
|
3482
|
+
this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => this.onerror?.(err));
|
|
3483
|
+
return;
|
|
3484
|
+
}
|
|
3485
|
+
const headers = await this._commonHeaders();
|
|
3486
|
+
headers.set("content-type", "application/json");
|
|
3487
|
+
headers.set("accept", "application/json, text/event-stream");
|
|
3488
|
+
const init = {
|
|
3489
|
+
...this._requestInit,
|
|
3490
|
+
method: "POST",
|
|
3491
|
+
headers,
|
|
3492
|
+
body: JSON.stringify(message),
|
|
3493
|
+
signal: this._abortController?.signal
|
|
3494
|
+
};
|
|
3495
|
+
const response = await (this._fetch ?? fetch)(this._url, init);
|
|
3496
|
+
const sessionId = response.headers.get("mcp-session-id");
|
|
3497
|
+
if (sessionId) {
|
|
3498
|
+
this._sessionId = sessionId;
|
|
3499
|
+
}
|
|
3500
|
+
if (!response.ok) {
|
|
3501
|
+
const text = await response.text().catch(() => null);
|
|
3502
|
+
if (response.status === 401 && this._authProvider) {
|
|
3503
|
+
if (this._hasCompletedAuthFlow) {
|
|
3504
|
+
throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
|
|
3505
|
+
}
|
|
3506
|
+
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
3507
|
+
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
3508
|
+
this._scope = scope;
|
|
3509
|
+
const result = await auth(this._authProvider, {
|
|
3510
|
+
serverUrl: this._url,
|
|
3511
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
3512
|
+
scope: this._scope,
|
|
3513
|
+
fetchFn: this._fetchWithInit
|
|
3514
|
+
});
|
|
3515
|
+
if (result !== "AUTHORIZED") {
|
|
3516
|
+
throw new UnauthorizedError();
|
|
3517
|
+
}
|
|
3518
|
+
this._hasCompletedAuthFlow = true;
|
|
3519
|
+
return this.send(message);
|
|
3520
|
+
}
|
|
3521
|
+
if (response.status === 403 && this._authProvider) {
|
|
3522
|
+
const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
|
|
3523
|
+
if (error === "insufficient_scope") {
|
|
3524
|
+
const wwwAuthHeader = response.headers.get("WWW-Authenticate");
|
|
3525
|
+
if (this._lastUpscopingHeader === wwwAuthHeader) {
|
|
3526
|
+
throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
|
|
3527
|
+
}
|
|
3528
|
+
if (scope) {
|
|
3529
|
+
this._scope = scope;
|
|
3530
|
+
}
|
|
3531
|
+
if (resourceMetadataUrl) {
|
|
3532
|
+
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
3533
|
+
}
|
|
3534
|
+
this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
|
|
3535
|
+
const result = await auth(this._authProvider, {
|
|
3536
|
+
serverUrl: this._url,
|
|
3537
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
3538
|
+
scope: this._scope,
|
|
3539
|
+
fetchFn: this._fetch
|
|
3540
|
+
});
|
|
3541
|
+
if (result !== "AUTHORIZED") {
|
|
3542
|
+
throw new UnauthorizedError();
|
|
3543
|
+
}
|
|
3544
|
+
return this.send(message);
|
|
3545
|
+
}
|
|
3546
|
+
}
|
|
3547
|
+
throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
|
|
3548
|
+
}
|
|
3549
|
+
this._hasCompletedAuthFlow = false;
|
|
3550
|
+
this._lastUpscopingHeader = void 0;
|
|
3551
|
+
if (response.status === 202) {
|
|
3552
|
+
await response.body?.cancel();
|
|
3553
|
+
if (isInitializedNotification(message)) {
|
|
3554
|
+
this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
|
|
3555
|
+
}
|
|
3556
|
+
return;
|
|
3557
|
+
}
|
|
3558
|
+
const messages = Array.isArray(message) ? message : [message];
|
|
3559
|
+
const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
|
|
3560
|
+
const contentType2 = response.headers.get("content-type");
|
|
3561
|
+
const responseMediaType = mediaTypeEssence(contentType2);
|
|
3562
|
+
if (hasRequests) {
|
|
3563
|
+
if (responseMediaType === "text/event-stream") {
|
|
3564
|
+
this._handleSseStream(response.body, { onresumptiontoken }, false);
|
|
3565
|
+
} else if (responseMediaType === "application/json") {
|
|
3566
|
+
const data = await response.json();
|
|
3567
|
+
const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
|
|
3568
|
+
for (const msg of responseMessages) {
|
|
3569
|
+
this.onmessage?.(msg);
|
|
3570
|
+
}
|
|
3571
|
+
} else {
|
|
3572
|
+
await response.body?.cancel();
|
|
3573
|
+
throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType2}`);
|
|
3574
|
+
}
|
|
3575
|
+
} else {
|
|
3576
|
+
await response.body?.cancel();
|
|
3577
|
+
}
|
|
3578
|
+
} catch (error) {
|
|
3579
|
+
this.onerror?.(error);
|
|
3580
|
+
throw error;
|
|
3581
|
+
}
|
|
3582
|
+
}
|
|
3583
|
+
get sessionId() {
|
|
3584
|
+
return this._sessionId;
|
|
3585
|
+
}
|
|
3586
|
+
/**
|
|
3587
|
+
* Terminates the current session by sending a DELETE request to the server.
|
|
3588
|
+
*
|
|
3589
|
+
* Clients that no longer need a particular session
|
|
3590
|
+
* (e.g., because the user is leaving the client application) SHOULD send an
|
|
3591
|
+
* HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
|
|
3592
|
+
* terminate the session.
|
|
3593
|
+
*
|
|
3594
|
+
* The server MAY respond with HTTP 405 Method Not Allowed, indicating that
|
|
3595
|
+
* the server does not allow clients to terminate sessions.
|
|
3596
|
+
*/
|
|
3597
|
+
async terminateSession() {
|
|
3598
|
+
if (!this._sessionId) {
|
|
3599
|
+
return;
|
|
3600
|
+
}
|
|
3601
|
+
try {
|
|
3602
|
+
const headers = await this._commonHeaders();
|
|
3603
|
+
const init = {
|
|
3604
|
+
...this._requestInit,
|
|
3605
|
+
method: "DELETE",
|
|
3606
|
+
headers,
|
|
3607
|
+
signal: this._abortController?.signal
|
|
3608
|
+
};
|
|
3609
|
+
const response = await (this._fetch ?? fetch)(this._url, init);
|
|
3610
|
+
await response.body?.cancel();
|
|
3611
|
+
if (!response.ok && response.status !== 405) {
|
|
3612
|
+
throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
|
|
3613
|
+
}
|
|
3614
|
+
this._sessionId = void 0;
|
|
3615
|
+
} catch (error) {
|
|
3616
|
+
this.onerror?.(error);
|
|
3617
|
+
throw error;
|
|
3618
|
+
}
|
|
3619
|
+
}
|
|
3620
|
+
setProtocolVersion(version) {
|
|
3621
|
+
this._protocolVersion = version;
|
|
3622
|
+
}
|
|
3623
|
+
get protocolVersion() {
|
|
3624
|
+
return this._protocolVersion;
|
|
3625
|
+
}
|
|
3626
|
+
/**
|
|
3627
|
+
* Resume an SSE stream from a previous event ID.
|
|
3628
|
+
* Opens a GET SSE connection with Last-Event-ID header to replay missed events.
|
|
3629
|
+
*
|
|
3630
|
+
* @param lastEventId The event ID to resume from
|
|
3631
|
+
* @param options Optional callback to receive new resumption tokens
|
|
3632
|
+
*/
|
|
3633
|
+
async resumeStream(lastEventId, options) {
|
|
3634
|
+
await this._startOrAuthSse({
|
|
3635
|
+
resumptionToken: lastEventId,
|
|
3636
|
+
onresumptiontoken: options?.onresumptiontoken
|
|
3637
|
+
});
|
|
3638
|
+
}
|
|
3639
|
+
};
|
|
3640
|
+
|
|
3641
|
+
// src/backend/mcp.ts
|
|
3642
|
+
function executionAssets(connection, scope) {
|
|
3643
|
+
const paths = [];
|
|
3644
|
+
const command = connection.command.includes("/") ? resolve3(scope, connection.command) : (process.env.PATH ?? "/usr/bin:/bin").split(":").map((directory) => resolve3(directory, connection.command)).find((path) => existsSync4(path));
|
|
3645
|
+
for (const argument of [...command ? [command] : [], ...connection.args]) {
|
|
3646
|
+
if (argument.startsWith("-")) continue;
|
|
3647
|
+
const path = resolve3(scope, argument);
|
|
3648
|
+
if (!existsSync4(path)) continue;
|
|
3649
|
+
const canonical2 = realpathSync4(path);
|
|
3650
|
+
if (statSync4(canonical2).isDirectory()) {
|
|
3651
|
+
paths.push(canonical2);
|
|
3652
|
+
continue;
|
|
3653
|
+
}
|
|
3654
|
+
let root = dirname4(canonical2);
|
|
3655
|
+
for (let ancestor = root; ancestor !== dirname4(ancestor); ancestor = dirname4(ancestor)) {
|
|
3656
|
+
if (existsSync4(join4(ancestor, "package.json"))) {
|
|
3657
|
+
root = ancestor;
|
|
3658
|
+
break;
|
|
3659
|
+
}
|
|
3660
|
+
}
|
|
3661
|
+
paths.push(root === "/tmp" ? canonical2 : root);
|
|
3662
|
+
}
|
|
3663
|
+
return [.../* @__PURE__ */ new Set([...paths, ...nodeExecutionAssets(paths)])];
|
|
3664
|
+
}
|
|
3665
|
+
var McpSession = class {
|
|
3666
|
+
clients = /* @__PURE__ */ new Map();
|
|
3667
|
+
stops = /* @__PURE__ */ new Map();
|
|
3668
|
+
entries = /* @__PURE__ */ new Map();
|
|
3669
|
+
states = /* @__PURE__ */ new Map();
|
|
3670
|
+
pending = /* @__PURE__ */ new Map();
|
|
3671
|
+
activeCalls = /* @__PURE__ */ new Map();
|
|
3672
|
+
exits = /* @__PURE__ */ new Set();
|
|
3673
|
+
disposed = false;
|
|
3674
|
+
direct;
|
|
3675
|
+
connections;
|
|
3676
|
+
scope;
|
|
3677
|
+
auth;
|
|
3678
|
+
resolveSecret;
|
|
3679
|
+
protectedPaths;
|
|
3680
|
+
stateRoot;
|
|
3681
|
+
isolationMode;
|
|
3682
|
+
expectedScopeIdentity;
|
|
3683
|
+
/** Sandbox workers: the host owns OAuth, refreshes on request and returns only access tokens. */
|
|
3684
|
+
hostToken;
|
|
3685
|
+
/** Sandbox workers start local servers from host paths over the VM's shared file system. */
|
|
3686
|
+
connectTimeoutMs = 1e4;
|
|
3687
|
+
constructor(connections, scope, auth2, direct = false, resolveSecret, protectedPaths, stateRoot, isolationMode = "bubblewrap", expectedScopeIdentity, hostToken) {
|
|
3688
|
+
this.hostToken = hostToken;
|
|
3689
|
+
this.connections = structuredClone(connections);
|
|
3690
|
+
this.scope = scope;
|
|
3691
|
+
this.auth = auth2;
|
|
3692
|
+
this.direct = direct;
|
|
3693
|
+
this.resolveSecret = resolveSecret;
|
|
3694
|
+
this.protectedPaths = protectedPaths;
|
|
3695
|
+
this.stateRoot = stateRoot;
|
|
3696
|
+
this.isolationMode = isolationMode;
|
|
3697
|
+
this.expectedScopeIdentity = expectedScopeIdentity;
|
|
3698
|
+
}
|
|
3699
|
+
registrationFailed() {
|
|
3700
|
+
for (const [id] of this.states) this.states.set(id, { id, state: "failed", tools: 0 });
|
|
3701
|
+
}
|
|
3702
|
+
tools() {
|
|
3703
|
+
return [...this.entries.values()].flat();
|
|
3704
|
+
}
|
|
3705
|
+
status() {
|
|
3706
|
+
return [...this.states.values()].map((state) => ({ ...state }));
|
|
3707
|
+
}
|
|
3708
|
+
async open() {
|
|
3709
|
+
await Promise.all(
|
|
3710
|
+
this.connections.map((connection) => this.retry(connection.id))
|
|
3711
|
+
);
|
|
3712
|
+
}
|
|
3713
|
+
retry(id) {
|
|
3714
|
+
if (this.disposed)
|
|
3715
|
+
return Promise.reject(new Error("Backend Session stopped"));
|
|
3716
|
+
if (this.activeCalls.get(id))
|
|
3717
|
+
return Promise.reject(new Error("MCP tools are still running"));
|
|
3718
|
+
const pending = this.pending.get(id);
|
|
3719
|
+
if (pending) return pending;
|
|
3720
|
+
const connection = this.connections.find((entry) => entry.id === id);
|
|
3721
|
+
if (!connection) return Promise.reject(new Error("Unknown MCP connection"));
|
|
3722
|
+
const promise = this.connect(connection).finally(
|
|
3723
|
+
() => this.pending.delete(id)
|
|
3724
|
+
);
|
|
3725
|
+
this.pending.set(id, promise);
|
|
3726
|
+
return promise;
|
|
3727
|
+
}
|
|
3728
|
+
configuredHeaders(headers) {
|
|
3729
|
+
return Object.fromEntries(
|
|
3730
|
+
Object.entries(headers).map(([name, source]) => {
|
|
3731
|
+
if ("value" in source) return [name, source.value];
|
|
3732
|
+
if (!this.resolveSecret)
|
|
3733
|
+
throw new Error(`No secret resolver for header ${name}`);
|
|
3734
|
+
return [name, this.resolveSecret(source.secret)];
|
|
3735
|
+
})
|
|
3736
|
+
);
|
|
3737
|
+
}
|
|
3738
|
+
async connect(connection) {
|
|
3739
|
+
const { id } = connection;
|
|
3740
|
+
this.states.set(id, { id, state: "connecting", tools: 0 });
|
|
3741
|
+
this.entries.delete(id);
|
|
3742
|
+
await this.stops.get(id)?.();
|
|
3743
|
+
this.clients.delete(id);
|
|
3744
|
+
this.stops.delete(id);
|
|
3745
|
+
if (this.disposed) return;
|
|
3746
|
+
const client = new Client(
|
|
3747
|
+
{ name: "Flow", version: "1.0.0" },
|
|
3748
|
+
{ capabilities: {} }
|
|
3749
|
+
);
|
|
3750
|
+
this.clients.set(id, client);
|
|
3751
|
+
let isolation;
|
|
3752
|
+
let scopeFd;
|
|
3753
|
+
const cleanup = () => {
|
|
3754
|
+
isolation?.cleanup();
|
|
3755
|
+
if (scopeFd !== void 0) {
|
|
3756
|
+
closeSync2(scopeFd);
|
|
3757
|
+
scopeFd = void 0;
|
|
3758
|
+
}
|
|
3759
|
+
};
|
|
3760
|
+
let transport;
|
|
3761
|
+
let stopping;
|
|
3762
|
+
const stop = () => stopping ??= (async () => {
|
|
3763
|
+
await client.close().catch(() => {
|
|
3764
|
+
});
|
|
3765
|
+
await transport?.close();
|
|
3766
|
+
if (!(transport instanceof SupervisedStdioTransport)) cleanup();
|
|
3767
|
+
})();
|
|
3768
|
+
this.stops.set(id, stop);
|
|
3769
|
+
try {
|
|
3770
|
+
const tokens = this.direct && connection.transport === "http" && connection.oauth ? await this.auth?.(connection).tokens() : void 0;
|
|
3771
|
+
if (this.direct && connection.transport === "http" && connection.oauth && !tokens?.access_token) {
|
|
3772
|
+
this.states.set(id, { id, state: "failed", tools: 0 });
|
|
3773
|
+
return;
|
|
3774
|
+
}
|
|
3775
|
+
const configured = connection.transport === "http" ? this.configuredHeaders(connection.headers) : {};
|
|
3776
|
+
if (connection.transport === "stdio" && this.isolationMode === "sandbox") throw sandboxUnavailable();
|
|
3777
|
+
if (connection.transport === "stdio" && this.isolationMode === "none") {
|
|
3778
|
+
if (this.expectedScopeIdentity !== void 0 && process.platform !== "linux")
|
|
3779
|
+
throw new Error("Descriptor-bound MCP authoring requires Linux");
|
|
3780
|
+
const scope = realpathSync4(this.scope);
|
|
3781
|
+
if (!statSync4(scope).isDirectory()) throw new Error("Scope must be a directory");
|
|
3782
|
+
let cwd = scope;
|
|
3783
|
+
if (this.expectedScopeIdentity !== void 0) {
|
|
3784
|
+
if (scope !== resolve3(this.scope)) throw new Error("Scope redirected since selection");
|
|
3785
|
+
scopeFd = openSync2(scope, constants2.O_RDONLY | constants2.O_DIRECTORY | constants2.O_NOFOLLOW);
|
|
3786
|
+
const pinned = fstatSync2(scopeFd, { bigint: true });
|
|
3787
|
+
cwd = `/proc/${process.pid}/fd/${scopeFd}`;
|
|
3788
|
+
const bound = statSync4(cwd, { bigint: true });
|
|
3789
|
+
if (`${pinned.dev}:${pinned.ino}` !== this.expectedScopeIdentity || !pinned.isDirectory() || bound.dev !== pinned.dev || bound.ino !== pinned.ino) {
|
|
3790
|
+
throw new Error("Scope changed since selection");
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
transport = new SupervisedStdioTransport({
|
|
3794
|
+
command: connection.command,
|
|
3795
|
+
args: connection.args,
|
|
3796
|
+
env: getDefaultEnvironment(),
|
|
3797
|
+
cwd
|
|
3798
|
+
});
|
|
3799
|
+
} else if (connection.transport === "stdio") {
|
|
3800
|
+
isolation = await prepareFilesystemIsolation({
|
|
3801
|
+
scope: this.scope,
|
|
3802
|
+
expectedScope: resolve3(this.scope),
|
|
3803
|
+
...this.expectedScopeIdentity !== void 0 ? { expectedScopeIdentity: this.expectedScopeIdentity } : {},
|
|
3804
|
+
command: connection.command.includes("/") ? resolve3(this.scope, connection.command) : connection.command,
|
|
3805
|
+
args: connection.args,
|
|
3806
|
+
readablePaths: executionAssets(connection, this.scope),
|
|
3807
|
+
// Match the SDK's pre-isolation minimal environment, not all host/provider secrets.
|
|
3808
|
+
env: {
|
|
3809
|
+
...Object.fromEntries(Object.keys(process.env).map((key) => [key, void 0])),
|
|
3810
|
+
...getDefaultEnvironment(),
|
|
3811
|
+
FLOW_BWRAP_PATH: process.env.FLOW_BWRAP_PATH,
|
|
3812
|
+
PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR,
|
|
3813
|
+
CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR
|
|
3814
|
+
},
|
|
3815
|
+
...this.protectedPaths ? { protectedPaths: this.protectedPaths } : {},
|
|
3816
|
+
...this.stateRoot ? { stateRoot: this.stateRoot } : {},
|
|
3817
|
+
credentials: "none"
|
|
3818
|
+
});
|
|
3819
|
+
if (this.disposed) {
|
|
3820
|
+
isolation.cleanup();
|
|
3821
|
+
return;
|
|
3822
|
+
}
|
|
3823
|
+
transport = new SupervisedStdioTransport({
|
|
3824
|
+
command: isolation.command,
|
|
3825
|
+
args: isolation.args,
|
|
3826
|
+
stdioFds: isolation.stdioFds,
|
|
3827
|
+
env: isolation.env,
|
|
3828
|
+
cwd: isolation.scope
|
|
3829
|
+
});
|
|
3830
|
+
} else {
|
|
3831
|
+
transport = new StreamableHTTPClientTransport(new URL(connection.url), {
|
|
3832
|
+
...connection.oauth && this.auth && !this.direct ? { authProvider: this.auth(connection) } : {},
|
|
3833
|
+
// A Headers object rather than a spread, because header names are case-insensitive: a
|
|
3834
|
+
// configured `Authorization` must lose to the OAuth token, not travel beside it.
|
|
3835
|
+
fetch: async (input, init) => {
|
|
3836
|
+
const headers = new Headers(configured);
|
|
3837
|
+
new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
|
|
3838
|
+
if (tokens) headers.set("Authorization", `Bearer ${tokens.access_token}`);
|
|
3839
|
+
const send = async (refresh) => {
|
|
3840
|
+
if (refresh !== void 0) headers.set("Authorization", `Bearer ${await this.hostToken(id, refresh)}`);
|
|
3841
|
+
return fetch(input, {
|
|
3842
|
+
...init,
|
|
3843
|
+
headers,
|
|
3844
|
+
signal: this.direct ? init?.signal ?? null : init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4)
|
|
3845
|
+
});
|
|
3846
|
+
};
|
|
3847
|
+
if (!connection.oauth || !this.hostToken) return send();
|
|
3848
|
+
const response = await send(false);
|
|
3849
|
+
if (response.status !== 401) return response;
|
|
3850
|
+
await response.body?.cancel();
|
|
3851
|
+
return send(true);
|
|
3852
|
+
}
|
|
3853
|
+
});
|
|
3854
|
+
}
|
|
3855
|
+
if (transport instanceof SupervisedStdioTransport) {
|
|
3856
|
+
const exited = transport.exited;
|
|
3857
|
+
void exited.then(cleanup);
|
|
3858
|
+
this.exits.add(exited);
|
|
3859
|
+
void exited.then(() => this.exits.delete(exited));
|
|
3860
|
+
}
|
|
3861
|
+
if (this.disposed) {
|
|
3862
|
+
await stop();
|
|
3863
|
+
return;
|
|
3864
|
+
}
|
|
3865
|
+
const signal = AbortSignal.timeout(this.connectTimeoutMs);
|
|
3866
|
+
await client.connect(
|
|
3867
|
+
transport,
|
|
3868
|
+
{ timeout: this.connectTimeoutMs, signal }
|
|
3869
|
+
);
|
|
3870
|
+
const serverIdentity = createHash("sha256").update(JSON.stringify(client.getServerVersion() ?? null)).digest("hex");
|
|
3871
|
+
const tools = [];
|
|
3872
|
+
let cursor;
|
|
3873
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3874
|
+
do {
|
|
3875
|
+
const result = await client.listTools(cursor ? { cursor } : {}, {
|
|
3876
|
+
timeout: this.connectTimeoutMs,
|
|
3877
|
+
signal
|
|
3878
|
+
});
|
|
3879
|
+
for (const definition of result.tools) {
|
|
3880
|
+
const original = definition.name;
|
|
3881
|
+
const local = /^[A-Za-z0-9_-]+$/.test(original) && original.length <= 57 - id.length && !/^h[0-9a-f]{16}$/.test(original) ? original : `h${createHash("sha256").update(original).digest("hex").slice(0, 16)}`;
|
|
3882
|
+
const name = `mcp__${id}__${local}`;
|
|
3883
|
+
tools.push({
|
|
3884
|
+
name,
|
|
3885
|
+
connectionId: id,
|
|
3886
|
+
definition,
|
|
3887
|
+
serverIdentity,
|
|
3888
|
+
call: async (input, signal2, timeoutMs = 6e4) => {
|
|
3889
|
+
if (this.disposed) throw new Error("Backend Session stopped");
|
|
3890
|
+
this.activeCalls.set(id, (this.activeCalls.get(id) ?? 0) + 1);
|
|
3891
|
+
try {
|
|
3892
|
+
return await this.clients.get(id).callTool(
|
|
3893
|
+
{ name: definition.name, arguments: input },
|
|
3894
|
+
void 0,
|
|
3895
|
+
{ timeout: timeoutMs, ...signal2 ? { signal: signal2 } : {} }
|
|
3896
|
+
);
|
|
3897
|
+
} catch {
|
|
3898
|
+
if (!signal2?.aborted)
|
|
3899
|
+
this.states.set(id, { id, state: "failed", tools: 0 });
|
|
3900
|
+
throw new Error(
|
|
3901
|
+
"MCP tool call failed. Check the connection and Retry."
|
|
3902
|
+
);
|
|
3903
|
+
} finally {
|
|
3904
|
+
this.activeCalls.set(id, this.activeCalls.get(id) - 1);
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3907
|
+
});
|
|
3908
|
+
}
|
|
3909
|
+
cursor = result.nextCursor;
|
|
3910
|
+
if (seen.size >= 100) throw new Error("MCP tool list is too large");
|
|
3911
|
+
if (cursor && seen.has(cursor)) throw new Error("Repeated MCP cursor");
|
|
3912
|
+
if (cursor) seen.add(cursor);
|
|
3913
|
+
} while (cursor);
|
|
3914
|
+
if (this.disposed) {
|
|
3915
|
+
await stop();
|
|
3916
|
+
return;
|
|
3917
|
+
}
|
|
3918
|
+
this.entries.set(id, tools);
|
|
3919
|
+
this.states.set(id, { id, state: "connected", tools: tools.length });
|
|
3920
|
+
client.onclose = () => {
|
|
3921
|
+
this.entries.delete(id);
|
|
3922
|
+
if (!this.disposed)
|
|
3923
|
+
this.states.set(id, { id, state: "failed", tools: 0 });
|
|
3924
|
+
};
|
|
3925
|
+
} catch {
|
|
3926
|
+
await stop();
|
|
3927
|
+
this.entries.delete(id);
|
|
3928
|
+
this.states.set(id, { id, state: "failed", tools: 0 });
|
|
3929
|
+
if (connection.transport === "stdio" && this.expectedScopeIdentity !== void 0) {
|
|
3930
|
+
throw new Error(process.platform !== "linux" ? "Descriptor-bound MCP authoring requires Linux; launch refused." : "MCP authoring launch failed. Refresh the selected Scope and Retry.");
|
|
3931
|
+
}
|
|
3932
|
+
}
|
|
3933
|
+
}
|
|
3934
|
+
/** Ordinary callers retain bounded stdio close; authoring owns capacity until actual exit. */
|
|
3935
|
+
async dispose({ waitForExit = false } = {}) {
|
|
3936
|
+
this.disposed = true;
|
|
3937
|
+
this.entries.clear();
|
|
3938
|
+
await Promise.all([...this.stops.values()].map((stop) => stop()));
|
|
3939
|
+
await Promise.allSettled(this.pending.values());
|
|
3940
|
+
await Promise.all([...this.stops.values()].map((stop) => stop()));
|
|
3941
|
+
if (waitForExit) await Promise.all(this.exits);
|
|
3942
|
+
}
|
|
3943
|
+
};
|
|
3944
|
+
|
|
3945
|
+
// src/backend/worker/rpc.ts
|
|
3946
|
+
function errorText(error) {
|
|
3947
|
+
return error instanceof Error ? error.message : String(error);
|
|
3948
|
+
}
|
|
3949
|
+
var WorkerRpc = class {
|
|
3950
|
+
nextId = 0;
|
|
3951
|
+
failure;
|
|
3952
|
+
pending = /* @__PURE__ */ new Map();
|
|
3953
|
+
incoming = /* @__PURE__ */ new Map();
|
|
3954
|
+
send;
|
|
3955
|
+
dispatch;
|
|
3956
|
+
notification;
|
|
3957
|
+
constructor(send, dispatch, notification) {
|
|
3958
|
+
this.send = send;
|
|
3959
|
+
this.dispatch = dispatch;
|
|
3960
|
+
this.notification = notification;
|
|
3961
|
+
}
|
|
3962
|
+
call(method, args = [], signal) {
|
|
3963
|
+
if (this.failure) return Promise.reject(this.failure);
|
|
3964
|
+
if (signal?.aborted) return Promise.reject(new Error("Worker call cancelled"));
|
|
3965
|
+
const id = ++this.nextId;
|
|
3966
|
+
return new Promise((resolve4, reject) => {
|
|
3967
|
+
const abort = () => {
|
|
3968
|
+
this.pending.delete(id);
|
|
3969
|
+
try {
|
|
3970
|
+
this.send({ kind: "cancel", id });
|
|
3971
|
+
} catch {
|
|
3972
|
+
}
|
|
3973
|
+
reject(new Error("Worker call cancelled"));
|
|
3974
|
+
};
|
|
3975
|
+
const cleanup = () => signal?.removeEventListener("abort", abort);
|
|
3976
|
+
this.pending.set(id, {
|
|
3977
|
+
resolve: (value) => {
|
|
3978
|
+
cleanup();
|
|
3979
|
+
resolve4(value);
|
|
3980
|
+
},
|
|
3981
|
+
reject: (error) => {
|
|
3982
|
+
cleanup();
|
|
3983
|
+
reject(error);
|
|
3984
|
+
}
|
|
3985
|
+
});
|
|
3986
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
3987
|
+
try {
|
|
3988
|
+
this.send({ kind: "call", id, method, args });
|
|
3989
|
+
} catch (error) {
|
|
3990
|
+
this.pending.delete(id);
|
|
3991
|
+
cleanup();
|
|
3992
|
+
reject(error);
|
|
3993
|
+
}
|
|
3994
|
+
});
|
|
3995
|
+
}
|
|
3996
|
+
notify(name, value) {
|
|
3997
|
+
if (!this.failure) this.send({ kind: "notification", name, value });
|
|
3998
|
+
}
|
|
3999
|
+
receive(raw) {
|
|
4000
|
+
if (this.failure || !raw || typeof raw !== "object") return;
|
|
4001
|
+
const message = raw;
|
|
4002
|
+
switch (message.kind) {
|
|
4003
|
+
case "reply": {
|
|
4004
|
+
const pending = this.pending.get(message.id);
|
|
4005
|
+
this.pending.delete(message.id);
|
|
4006
|
+
if (message.error !== void 0) pending?.reject(message.errorCode === "auto_permission_unavailable" ? new AutoPermissionUnavailable(message.error) : new Error(message.error));
|
|
4007
|
+
else pending?.resolve(message.value);
|
|
4008
|
+
break;
|
|
4009
|
+
}
|
|
4010
|
+
case "cancel":
|
|
4011
|
+
this.incoming.get(message.id)?.abort();
|
|
4012
|
+
break;
|
|
4013
|
+
case "notification":
|
|
4014
|
+
this.notification(message.name, message.value);
|
|
4015
|
+
break;
|
|
4016
|
+
case "call": {
|
|
4017
|
+
if (!Number.isSafeInteger(message.id) || typeof message.method !== "string" || !Array.isArray(message.args) || this.incoming.has(message.id)) return;
|
|
4018
|
+
const controller = new AbortController();
|
|
4019
|
+
this.incoming.set(message.id, controller);
|
|
4020
|
+
void Promise.resolve().then(() => this.dispatch(message.method, message.args, controller.signal)).then(
|
|
4021
|
+
(value) => this.reply({ kind: "reply", id: message.id, value }),
|
|
4022
|
+
(error) => this.reply({
|
|
4023
|
+
kind: "reply",
|
|
4024
|
+
id: message.id,
|
|
4025
|
+
error: errorText(error),
|
|
4026
|
+
...error instanceof AutoPermissionUnavailable ? { errorCode: "auto_permission_unavailable" } : {}
|
|
4027
|
+
})
|
|
4028
|
+
).finally(() => this.incoming.delete(message.id));
|
|
4029
|
+
break;
|
|
4030
|
+
}
|
|
4031
|
+
}
|
|
4032
|
+
}
|
|
4033
|
+
reply(message) {
|
|
4034
|
+
if (this.failure) return;
|
|
4035
|
+
try {
|
|
4036
|
+
this.send(message);
|
|
4037
|
+
} catch (error) {
|
|
4038
|
+
this.close(new Error(errorText(error)));
|
|
4039
|
+
}
|
|
4040
|
+
}
|
|
4041
|
+
close(error) {
|
|
4042
|
+
if (this.failure) return;
|
|
4043
|
+
this.failure = error;
|
|
4044
|
+
for (const pending of this.pending.values()) pending.reject(error);
|
|
4045
|
+
this.pending.clear();
|
|
4046
|
+
for (const controller of this.incoming.values()) controller.abort();
|
|
4047
|
+
this.incoming.clear();
|
|
4048
|
+
}
|
|
4049
|
+
};
|
|
4050
|
+
|
|
4051
|
+
// src/backend/worker/protocol.ts
|
|
4052
|
+
function snapshot(session) {
|
|
4053
|
+
return {
|
|
4054
|
+
capabilities: session.capabilities,
|
|
4055
|
+
resume: session.resumeToken(),
|
|
4056
|
+
methods: ["refreshMcp", "startWorkflowSubagent", "compact", "skills", "answerEnquiry", "answerPermission", "setPermissionMode"].filter((method) => typeof session[method] === "function")
|
|
4057
|
+
};
|
|
4058
|
+
}
|
|
4059
|
+
|
|
4060
|
+
// src/backend/worker/launcher.ts
|
|
4061
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
4062
|
+
|
|
4063
|
+
// src/backend/worker/frames.ts
|
|
4064
|
+
import { deserialize, serialize } from "node:v8";
|
|
4065
|
+
function encodeFrame(message) {
|
|
4066
|
+
const body = serialize(message);
|
|
4067
|
+
const frame = Buffer.allocUnsafe(4 + body.length);
|
|
4068
|
+
frame.writeUInt32BE(body.length, 0);
|
|
4069
|
+
body.copy(frame, 4);
|
|
4070
|
+
return frame;
|
|
4071
|
+
}
|
|
4072
|
+
function frameDecoder(onMessage) {
|
|
4073
|
+
let chunks = [];
|
|
4074
|
+
let size = 0;
|
|
4075
|
+
let need = 4;
|
|
4076
|
+
let header = true;
|
|
4077
|
+
return (chunk) => {
|
|
4078
|
+
chunks.push(chunk);
|
|
4079
|
+
size += chunk.length;
|
|
4080
|
+
while (size >= need) {
|
|
4081
|
+
const data = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, size);
|
|
4082
|
+
chunks = [data];
|
|
4083
|
+
if (header) {
|
|
4084
|
+
need = 4 + data.readUInt32BE(0);
|
|
4085
|
+
header = false;
|
|
4086
|
+
continue;
|
|
4087
|
+
}
|
|
4088
|
+
const message = deserialize(data.subarray(4, need));
|
|
4089
|
+
const rest = data.subarray(need);
|
|
4090
|
+
chunks = rest.length ? [rest] : [];
|
|
4091
|
+
size = rest.length;
|
|
4092
|
+
need = 4;
|
|
4093
|
+
header = true;
|
|
4094
|
+
onMessage(message);
|
|
4095
|
+
}
|
|
4096
|
+
};
|
|
4097
|
+
}
|
|
4098
|
+
|
|
4099
|
+
// src/backend/worker/launcher.ts
|
|
4100
|
+
import { isSea } from "node:sea";
|
|
4101
|
+
async function killWorkerTree(child) {
|
|
4102
|
+
if (!child.pid) return;
|
|
4103
|
+
if (process.platform === "win32") {
|
|
4104
|
+
await new Promise((resolve4) => {
|
|
4105
|
+
const killer = spawn4("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
|
4106
|
+
killer.once("error", () => resolve4());
|
|
4107
|
+
killer.once("close", () => resolve4());
|
|
4108
|
+
});
|
|
4109
|
+
} else {
|
|
4110
|
+
try {
|
|
4111
|
+
process.kill(-child.pid, "SIGKILL");
|
|
4112
|
+
} catch (error) {
|
|
4113
|
+
const code = error.code;
|
|
4114
|
+
const exited = child.exitCode !== null || child.signalCode !== null;
|
|
4115
|
+
if (code !== "ESRCH" && !(code === "EPERM" && exited)) throw error;
|
|
4116
|
+
}
|
|
4117
|
+
}
|
|
4118
|
+
}
|
|
4119
|
+
|
|
4120
|
+
// src/backend/worker/entry.ts
|
|
4121
|
+
import { createRequire } from "node:module";
|
|
4122
|
+
import { isSea as isSea3 } from "node:sea";
|
|
4123
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4124
|
+
|
|
4125
|
+
// src/isolation/launcher.ts
|
|
4126
|
+
import { isSea as isSea2 } from "node:sea";
|
|
4127
|
+
var flag = "--flow-isolation-launch";
|
|
4128
|
+
function isFilesystemLauncher() {
|
|
4129
|
+
return process.argv.includes(flag);
|
|
4130
|
+
}
|
|
4131
|
+
async function runFilesystemLauncher() {
|
|
4132
|
+
const { spawn: spawn5 } = await import("node:child_process");
|
|
4133
|
+
const { closeSync: closeSync3, constants: constants3, openSync: openSync3 } = await import("node:fs");
|
|
4134
|
+
const spec = JSON.parse(process.argv.at(-1));
|
|
4135
|
+
if (typeof spec.command !== "string" || !Array.isArray(spec.args) || !spec.args.every((value) => typeof value === "string") || !Array.isArray(spec.sources) || !spec.sources.every((value) => typeof value === "string" && /^\/proc\/\d+\/fd\/\d+$/.test(value))) {
|
|
4136
|
+
throw new Error("Invalid filesystem launch specification");
|
|
4137
|
+
}
|
|
4138
|
+
const fds = [];
|
|
4139
|
+
try {
|
|
4140
|
+
for (const source of spec.sources) fds.push(openSync3(source, constants3.O_RDONLY));
|
|
4141
|
+
await new Promise((resolve4, reject) => {
|
|
4142
|
+
const child = spawn5(spec.command, spec.args, { env: process.env, stdio: [0, 1, 2, ...fds] });
|
|
4143
|
+
child.once("error", reject);
|
|
4144
|
+
child.once("close", (code) => {
|
|
4145
|
+
process.exitCode = code ?? 1;
|
|
4146
|
+
resolve4();
|
|
4147
|
+
});
|
|
4148
|
+
});
|
|
4149
|
+
} finally {
|
|
4150
|
+
for (const fd of fds) closeSync3(fd);
|
|
4151
|
+
}
|
|
4152
|
+
}
|
|
4153
|
+
|
|
4154
|
+
// src/backend/worker/entry.ts
|
|
4155
|
+
function runWorker() {
|
|
4156
|
+
if (isFilesystemLauncher()) {
|
|
4157
|
+
void runFilesystemLauncher().catch((error) => {
|
|
4158
|
+
console.error(errorText(error));
|
|
4159
|
+
process.exitCode = 1;
|
|
4160
|
+
});
|
|
4161
|
+
return;
|
|
4162
|
+
}
|
|
4163
|
+
const writeFrame = process.stdout.write.bind(process.stdout);
|
|
4164
|
+
process.stdout.write = process.stderr.write.bind(process.stderr);
|
|
4165
|
+
let session;
|
|
4166
|
+
let published;
|
|
4167
|
+
const publishSnapshot = () => published = snapshot(session);
|
|
4168
|
+
let creating = false;
|
|
4169
|
+
let closing = false;
|
|
4170
|
+
let shutdown;
|
|
4171
|
+
let tools = [];
|
|
4172
|
+
let localMcp;
|
|
4173
|
+
let localMcpOpening;
|
|
4174
|
+
const workflows = /* @__PURE__ */ new Map();
|
|
4175
|
+
const send = (message) => {
|
|
4176
|
+
if (!process.stdout.writable) throw new Error("Backend worker disconnected");
|
|
4177
|
+
writeFrame(encodeFrame(message), (error) => {
|
|
4178
|
+
if (error) void stop();
|
|
4179
|
+
});
|
|
4180
|
+
};
|
|
4181
|
+
const rpc = new WorkerRpc(send, async (method, args, signal) => {
|
|
4182
|
+
if (method === "create") {
|
|
4183
|
+
const ready = performance.now();
|
|
4184
|
+
if (creating || closing) throw new Error("Backend worker already initialized");
|
|
4185
|
+
creating = true;
|
|
4186
|
+
const { mcpTools, mcpConnectionIds, mcpSandbox, workflowEnabled, workflowBuilderInstructions, backendModule, backend: backendName = "pi", ...options } = args[0];
|
|
4187
|
+
const workflowBuilder = workflowBuilderInstructions === void 0 ? void 0 : {
|
|
4188
|
+
instructions: workflowBuilderInstructions,
|
|
4189
|
+
read: (path) => rpc.call("workflowBuilder.read", [path]),
|
|
4190
|
+
list: (path) => rpc.call("workflowBuilder.list", [path]),
|
|
4191
|
+
write: (content) => rpc.call("workflowBuilder.write", [content])
|
|
4192
|
+
};
|
|
4193
|
+
updateTools(mcpTools ?? []);
|
|
4194
|
+
if (mcpSandbox) localMcp = new McpSession(
|
|
4195
|
+
mcpSandbox,
|
|
4196
|
+
options.scope,
|
|
4197
|
+
void 0,
|
|
4198
|
+
false,
|
|
4199
|
+
void 0,
|
|
4200
|
+
void 0,
|
|
4201
|
+
void 0,
|
|
4202
|
+
"none",
|
|
4203
|
+
void 0,
|
|
4204
|
+
(connectionId, refresh) => rpc.call("mcp.token", [connectionId, refresh])
|
|
4205
|
+
);
|
|
4206
|
+
if (localMcp) {
|
|
4207
|
+
localMcp.connectTimeoutMs = 12e4;
|
|
4208
|
+
localMcpOpening = localMcp.open();
|
|
4209
|
+
localMcpOpening.catch(() => {
|
|
4210
|
+
});
|
|
4211
|
+
}
|
|
4212
|
+
const workflow = {
|
|
4213
|
+
inspect: (input) => rpc.call("workflow.inspect", [input]),
|
|
4214
|
+
recover: (input, signal2) => rpc.call("workflow.recover", [input], signal2),
|
|
4215
|
+
relayEnquiry: (input, signal2) => rpc.call("workflow.relayEnquiry", [input], signal2),
|
|
4216
|
+
relayPermission: (input, signal2) => rpc.call("workflow.relayPermission", [input], signal2)
|
|
4217
|
+
};
|
|
4218
|
+
let backend;
|
|
4219
|
+
const importing = performance.now();
|
|
4220
|
+
try {
|
|
4221
|
+
backend = backendModule ? isSea3() ? createRequire(pathToFileURL(process.execPath))(fileURLToPath(backendModule)).default : (await import(backendModule)).default : backendName === "claude" ? new (await import("./backend-worker-chunks/claude-GTW5KHY5.mjs")).ClaudeBackend() : new (await import("./backend-worker-chunks/pi-M4OA2FGL.mjs")).PiBackend();
|
|
4222
|
+
} catch (error) {
|
|
4223
|
+
throw new Error(`Backend "${backendName}" is not available in this build: ${errorText(error)}`);
|
|
4224
|
+
}
|
|
4225
|
+
const imported = performance.now();
|
|
4226
|
+
session = await backend.create({
|
|
4227
|
+
...options,
|
|
4228
|
+
...workflowBuilder ? { workflowBuilder } : {
|
|
4229
|
+
...localMcp ? { mcp: localMcp } : mcpTools ? { mcp: { connections: (mcpConnectionIds ?? []).map((id) => ({ id })), tools: () => tools } } : {},
|
|
4230
|
+
...workflowEnabled ? { workflow } : {}
|
|
4231
|
+
},
|
|
4232
|
+
emit: (event) => {
|
|
4233
|
+
const changed = session && (session.capabilities !== published?.capabilities || session.resumeToken() !== published?.resume);
|
|
4234
|
+
rpc.notify("event", { event, ...changed ? { snapshot: publishSnapshot() } : {} });
|
|
4235
|
+
}
|
|
4236
|
+
});
|
|
4237
|
+
if (closing) {
|
|
4238
|
+
await session.dispose();
|
|
4239
|
+
throw new Error("Backend worker stopped during initialization");
|
|
4240
|
+
}
|
|
4241
|
+
return { ...publishSnapshot(), startup: { ready, import: imported - importing, create: performance.now() - imported } };
|
|
4242
|
+
}
|
|
4243
|
+
if (method === "dispose") {
|
|
4244
|
+
await disposeSession();
|
|
4245
|
+
setImmediate(() => process.stdout.end(() => process.exit(0)));
|
|
4246
|
+
return;
|
|
4247
|
+
}
|
|
4248
|
+
if (!session || closing) throw new Error("Backend worker is not running");
|
|
4249
|
+
let result;
|
|
4250
|
+
switch (method) {
|
|
4251
|
+
case "prompt":
|
|
4252
|
+
result = await session.prompt(args[0], args[1]);
|
|
4253
|
+
break;
|
|
4254
|
+
case "abort":
|
|
4255
|
+
result = await session.abort();
|
|
4256
|
+
break;
|
|
4257
|
+
case "setModel":
|
|
4258
|
+
result = await session.setModel(args[0]);
|
|
4259
|
+
break;
|
|
4260
|
+
case "setEffort":
|
|
4261
|
+
result = await session.setEffort(args[0]);
|
|
4262
|
+
break;
|
|
4263
|
+
case "setPermissionMode": {
|
|
4264
|
+
const mode = args[0];
|
|
4265
|
+
if (mode !== "ask" && mode !== "auto" && mode !== "always") throw new Error("Invalid permission mode");
|
|
4266
|
+
if (!session.setPermissionMode) throw new Error("Permission mode changes are not supported");
|
|
4267
|
+
result = await session.setPermissionMode(mode);
|
|
4268
|
+
break;
|
|
4269
|
+
}
|
|
4270
|
+
case "compact":
|
|
4271
|
+
result = await session.compact?.(args[0]);
|
|
4272
|
+
break;
|
|
4273
|
+
case "skills":
|
|
4274
|
+
result = await session.skills?.();
|
|
4275
|
+
break;
|
|
4276
|
+
case "answerEnquiry":
|
|
4277
|
+
result = await session.answerEnquiry?.(args[0], args[1]) ?? false;
|
|
4278
|
+
break;
|
|
4279
|
+
case "answerPermission":
|
|
4280
|
+
result = await session.answerPermission?.(args[0], args[1]) ?? false;
|
|
4281
|
+
break;
|
|
4282
|
+
case "refreshMcp":
|
|
4283
|
+
if (!localMcp) updateTools(args[0]);
|
|
4284
|
+
result = await session.refreshMcp?.();
|
|
4285
|
+
break;
|
|
4286
|
+
case "mcp.open": {
|
|
4287
|
+
if (!localMcp) throw new Error("No sandbox MCP clients");
|
|
4288
|
+
const opening = localMcpOpening ?? localMcp.open();
|
|
4289
|
+
localMcpOpening = void 0;
|
|
4290
|
+
await opening;
|
|
4291
|
+
result = localMcp.status();
|
|
4292
|
+
break;
|
|
4293
|
+
}
|
|
4294
|
+
case "mcp.retry":
|
|
4295
|
+
if (!localMcp) throw new Error("No sandbox MCP clients");
|
|
4296
|
+
await localMcp.retry(args[0]);
|
|
4297
|
+
result = localMcp.status();
|
|
4298
|
+
break;
|
|
4299
|
+
case "mcp.direct": {
|
|
4300
|
+
if (!localMcp) throw new Error("No sandbox MCP clients");
|
|
4301
|
+
const id = args[0];
|
|
4302
|
+
if (localMcp.status().find((state) => state.id === id)?.state !== "connected") await localMcp.retry(id).catch(() => {
|
|
4303
|
+
});
|
|
4304
|
+
result = {
|
|
4305
|
+
status: localMcp.status().find((state) => state.id === id) ?? { id, state: "failed", tools: 0 },
|
|
4306
|
+
tools: localMcp.tools().filter((tool) => tool.connectionId === id).map(({ call: _, ...tool }) => tool)
|
|
4307
|
+
};
|
|
4308
|
+
break;
|
|
4309
|
+
}
|
|
4310
|
+
case "mcp.callTool": {
|
|
4311
|
+
const tool = localMcp?.tools().find((entry) => entry.name === args[0]);
|
|
4312
|
+
if (!tool) throw new Error("Unknown MCP tool");
|
|
4313
|
+
result = await tool.call(args[1], signal, args[2]);
|
|
4314
|
+
break;
|
|
4315
|
+
}
|
|
4316
|
+
case "workflow.start": {
|
|
4317
|
+
if (!session.startWorkflowSubagent) throw new Error("Workflow Subagents are not supported");
|
|
4318
|
+
const id = args[0];
|
|
4319
|
+
if (workflows.has(id)) throw new Error("Duplicate workflow handle");
|
|
4320
|
+
const handle = session.startWorkflowSubagent({ ...args[1], emit: (activity) => rpc.notify("workflow.event", { id, activity }) });
|
|
4321
|
+
workflows.set(id, handle);
|
|
4322
|
+
void handle.done.then(
|
|
4323
|
+
(value) => rpc.notify("workflow.done", { id, value }),
|
|
4324
|
+
(error) => rpc.notify("workflow.done", { id, error: errorText(error) })
|
|
4325
|
+
).finally(() => workflows.delete(id)).catch(() => {
|
|
4326
|
+
});
|
|
4327
|
+
break;
|
|
4328
|
+
}
|
|
4329
|
+
case "workflow.answerEnquiry":
|
|
4330
|
+
result = await workflows.get(args[0])?.answerEnquiry(args[1], args[2]) ?? false;
|
|
4331
|
+
break;
|
|
4332
|
+
case "workflow.answerPermission":
|
|
4333
|
+
result = await workflows.get(args[0])?.answerPermission(args[1], args[2]) ?? false;
|
|
4334
|
+
break;
|
|
4335
|
+
case "workflow.cancel":
|
|
4336
|
+
result = await workflows.get(args[0])?.cancel();
|
|
4337
|
+
break;
|
|
4338
|
+
default:
|
|
4339
|
+
throw new Error(`Unknown worker method: ${method}`);
|
|
4340
|
+
}
|
|
4341
|
+
rpc.notify("snapshot", publishSnapshot());
|
|
4342
|
+
return result;
|
|
4343
|
+
}, () => {
|
|
4344
|
+
});
|
|
4345
|
+
function updateTools(metadata) {
|
|
4346
|
+
tools = metadata.map((tool) => ({ ...tool, call: (input, signal, timeoutMs) => rpc.call("mcp.call", [tool.name, input, timeoutMs], signal) }));
|
|
4347
|
+
}
|
|
4348
|
+
async function disposeSession() {
|
|
4349
|
+
closing = true;
|
|
4350
|
+
await Promise.allSettled([...workflows.values()].map((handle) => handle.cancel()));
|
|
4351
|
+
await session?.dispose();
|
|
4352
|
+
await localMcp?.dispose({ waitForExit: true });
|
|
4353
|
+
}
|
|
4354
|
+
function stop() {
|
|
4355
|
+
return shutdown ??= (async () => {
|
|
4356
|
+
rpc.close(new Error("Backend worker disconnected"));
|
|
4357
|
+
const timer = setTimeout(() => {
|
|
4358
|
+
void killWorkerTree({ pid: process.pid }).finally(() => process.exit(1));
|
|
4359
|
+
}, 5e3);
|
|
4360
|
+
try {
|
|
4361
|
+
await disposeSession();
|
|
4362
|
+
} finally {
|
|
4363
|
+
clearTimeout(timer);
|
|
4364
|
+
process.exit(0);
|
|
4365
|
+
}
|
|
4366
|
+
})();
|
|
4367
|
+
}
|
|
4368
|
+
const decode = frameDecoder((message) => rpc.receive(message));
|
|
4369
|
+
process.stdin.on("data", (chunk) => {
|
|
4370
|
+
try {
|
|
4371
|
+
decode(chunk);
|
|
4372
|
+
} catch {
|
|
4373
|
+
void stop();
|
|
4374
|
+
}
|
|
4375
|
+
});
|
|
4376
|
+
process.stdin.once("end", () => {
|
|
4377
|
+
void stop();
|
|
4378
|
+
});
|
|
4379
|
+
process.stdout.on("error", () => {
|
|
4380
|
+
void stop();
|
|
4381
|
+
});
|
|
4382
|
+
process.once("SIGTERM", () => {
|
|
4383
|
+
void stop();
|
|
4384
|
+
});
|
|
4385
|
+
process.once("SIGINT", () => {
|
|
4386
|
+
void stop();
|
|
4387
|
+
});
|
|
4388
|
+
}
|
|
4389
|
+
if (process.env.FLOW_BACKEND_WORKER === "1" || isFilesystemLauncher()) runWorker();
|
|
4390
|
+
export {
|
|
4391
|
+
runWorker
|
|
4392
|
+
};
|
|
4393
|
+
/*! Bundled license information:
|
|
4394
|
+
|
|
4395
|
+
content-type/index.js:
|
|
4396
|
+
(*!
|
|
4397
|
+
* content-type
|
|
4398
|
+
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
4399
|
+
* MIT Licensed
|
|
4400
|
+
*)
|
|
4401
|
+
*/
|