@fugood/buttress-server 2.26.0-beta.18 → 2.26.0-beta.19

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.
@@ -1,11 +1,102 @@
1
1
  #!/usr/bin/env node
2
- const e=256*1024,t=1024*1024,n=`image expects a non-empty image URL string, an object with image_url, or a raw MCP image block`,r=`(function (bridge, toolsJson, globalsJson, storeJson) {
2
+ const e=256*1024,t=1024*1024,n=16*1024*1024,r=1e5,i=`image expects a non-empty image URL string, an object with image_url, or a raw MCP image block`,a=`(function (bridge, toolsJson, globalsJson, storeJson) {
3
3
  "use strict";
4
+
5
+ // Freeze every object reachable from the built-in globals, plus the intrinsics that are only
6
+ // reachable from instances (iterator and generator prototypes, %TypedArray%).
7
+ //
8
+ // Freezing alone breaks ordinary code through the "override mistake": a data property that is
9
+ // read-only on a prototype cannot be assigned on an instance either, so
10
+ // this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
11
+ // become accessors whose setter defines an own property on the instance instead.
12
+ (function lockdown() {
13
+ const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
14
+ const seen = new Set([globalThis]);
15
+ const queue = [];
16
+ const add = (value) => {
17
+ if ((typeof value === "object" && value !== null) || typeof value === "function") {
18
+ if (!seen.has(value)) {
19
+ seen.add(value);
20
+ queue.push(value);
21
+ }
22
+ }
23
+ };
24
+
25
+ // Accessors from an object literal have no own prototype object, unlike function expressions,
26
+ // whose prototype.constructor would be converted again without end.
27
+ function allowOverride(object, key, value, enumerable) {
28
+ const { get, set } = Object.getOwnPropertyDescriptor(
29
+ {
30
+ get accessor() {
31
+ return value;
32
+ },
33
+ set accessor(next) {
34
+ if (this === object) {
35
+ throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
36
+ }
37
+ if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
38
+ Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
39
+ },
40
+ },
41
+ "accessor",
42
+ );
43
+ Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
44
+ add(get);
45
+ add(set);
46
+ }
47
+
48
+ for (const key of Reflect.ownKeys(globalThis)) {
49
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
50
+ add(descriptor.value);
51
+ add(descriptor.get);
52
+ add(descriptor.set);
53
+ if ("value" in descriptor && descriptor.configurable) {
54
+ Object.defineProperty(globalThis, key, { writable: false, configurable: false });
55
+ }
56
+ }
57
+ add(Object.getPrototypeOf(function* () {}));
58
+ add(Object.getPrototypeOf(async function () {}));
59
+ add(Object.getPrototypeOf(async function* () {}));
60
+ add(Object.getPrototypeOf(Int8Array));
61
+ add(Object.getPrototypeOf([][Symbol.iterator]()));
62
+ add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
63
+ add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
64
+ add(Object.getPrototypeOf(""[Symbol.iterator]()));
65
+ add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
66
+ if (typeof Iterator === "function") {
67
+ if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
68
+ if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
69
+ }
70
+
71
+ while (queue.length > 0) {
72
+ const object = queue.pop();
73
+ add(Object.getPrototypeOf(object));
74
+ const descriptors = Object.getOwnPropertyDescriptors(object);
75
+ for (const key of Reflect.ownKeys(descriptors)) {
76
+ const descriptor = descriptors[key];
77
+ if ("value" in descriptor) {
78
+ add(descriptor.value);
79
+ if (
80
+ descriptor.writable &&
81
+ descriptor.configurable &&
82
+ (object === Object.prototype || OVERRIDABLE.has(key))
83
+ ) {
84
+ allowOverride(object, key, descriptor.value, descriptor.enumerable);
85
+ }
86
+ } else {
87
+ add(descriptor.get);
88
+ add(descriptor.set);
89
+ }
90
+ }
91
+ Object.freeze(object);
92
+ }
93
+ })();
4
94
  const stringify = JSON.stringify;
5
95
  const parse = JSON.parse;
6
96
  const promiseThen = Promise.prototype.then;
7
97
  const ErrorCtor = Error;
8
98
  const TypeErrorCtor = TypeError;
99
+ const RangeErrorCtor = RangeError;
9
100
  const pending = new Map();
10
101
  let nextId = 1;
11
102
  let finished = false;
@@ -44,11 +135,17 @@ const e=256*1024,t=1024*1024,n=`image expects a non-empty image URL string, an o
44
135
  }
45
136
  }
46
137
 
138
+ // The host requires string fields. A script can set an error's name or message to anything, so
139
+ // they are coerced, and a value whose coercion throws gets a placeholder.
47
140
  function describeError(error) {
48
- if (error instanceof ErrorCtor) {
49
- return stringify({ name: error.name, message: error.message, stack: errorText(error) });
141
+ try {
142
+ if (error instanceof ErrorCtor) {
143
+ return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
144
+ }
145
+ return stringify({ message: String(format(error)) });
146
+ } catch {
147
+ return stringify({ message: "The script threw a value that cannot be described" });
50
148
  }
51
- return stringify({ message: format(error) });
52
149
  }
53
150
 
54
151
  function caller(kind, name, spread) {
@@ -191,6 +288,26 @@ const e=256*1024,t=1024*1024,n=`image expects a non-empty image URL string, an o
191
288
  Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
192
289
  Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
193
290
 
291
+ let outputChars = 0;
292
+ let outputItems = 0;
293
+
294
+ // Past the output limits the script fails: done() reports the error, so catching it does not
295
+ // resume output, and the host ends the script.
296
+ function output(kind, data, mimeType) {
297
+ if (finished) return;
298
+ outputChars += data.length;
299
+ outputItems++;
300
+ if (outputChars > ${n} || outputItems > ${r}) {
301
+ const error = new RangeErrorCtor(
302
+ "script output exceeded the limit of ${n} characters or ${r} text(), image(), and console calls. " +
303
+ "Print a summary instead, or write large data to a file with a tool.",
304
+ );
305
+ done(false, describeError(error));
306
+ throw error;
307
+ }
308
+ bridge("output", kind, data, mimeType);
309
+ }
310
+
194
311
  // Primitives become their string form, everything else JSON.
195
312
  function outputText(value) {
196
313
  if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
@@ -207,19 +324,19 @@ const e=256*1024,t=1024*1024,n=`image expects a non-empty image URL string, an o
207
324
  } catch (error) {
208
325
  throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
209
326
  }
210
- if (!finished) bridge("output", "text", rendered);
327
+ output("text", rendered);
211
328
  }
212
329
 
213
330
  function imageUrl(value) {
214
331
  if (typeof value === "string") return value;
215
332
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
216
- throw new TypeErrorCtor(${JSON.stringify(n)});
333
+ throw new TypeErrorCtor(${JSON.stringify(i)});
217
334
  }
218
335
  if (value.image_url !== undefined) {
219
- if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(n)});
336
+ if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(i)});
220
337
  return value.image_url;
221
338
  }
222
- if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(n)});
339
+ if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(i)});
223
340
  if (value.type !== "image") {
224
341
  throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
225
342
  }
@@ -239,7 +356,7 @@ const e=256*1024,t=1024*1024,n=`image expects a non-empty image URL string, an o
239
356
 
240
357
  function image(value) {
241
358
  const url = imageUrl(value);
242
- if (url === "") throw new TypeErrorCtor(${JSON.stringify(n)});
359
+ if (url === "") throw new TypeErrorCtor(${JSON.stringify(i)});
243
360
  const colon = url.indexOf(":");
244
361
  const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
245
362
  if (scheme === "http" || scheme === "https") {
@@ -262,7 +379,7 @@ const e=256*1024,t=1024*1024,n=`image expects a non-empty image URL string, an o
262
379
  if (!signature) {
263
380
  throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
264
381
  }
265
- if (!finished) bridge("output", "image", data, signature[0]);
382
+ output("image", data, signature[0]);
266
383
  }
267
384
 
268
385
  function exit() {
@@ -280,7 +397,7 @@ const e=256*1024,t=1024*1024,n=`image expects a non-empty image URL string, an o
280
397
  const console = {};
281
398
  for (const level of ["log", "info", "warn", "error", "debug"]) {
282
399
  console[level] = (...args) => {
283
- if (!finished) bridge("output", "text", args.map(format).join(" "));
400
+ output("console", args.map(format).join(" "));
284
401
  };
285
402
  }
286
403
  Object.freeze(console);
@@ -348,4 +465,4 @@ const e=256*1024,t=1024*1024,n=`image expects a non-empty image URL string, an o
348
465
  return true;
349
466
  },
350
467
  };
351
- })`;function i(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`call`||t===`output`||t===`done`||t===`crash`}function a(e){return typeof e==`object`&&!!e&&e.type===`result`}export{i as n,r,a as t};
468
+ })`;function o(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`call`||t===`output`||t===`done`||t===`crash`}function s(e){return typeof e==`object`&&!!e&&e.type===`result`}export{o as n,a as r,s as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fugood/buttress-server",
3
- "version": "2.26.0-beta.18",
3
+ "version": "2.26.0-beta.19",
4
4
  "main": "lib/index.mjs",
5
5
  "types": "lib/index.d.ts",
6
6
  "type": "module",
@@ -37,13 +37,13 @@
37
37
  ],
38
38
  "license": "MIT",
39
39
  "dependencies": {
40
- "@earendil-works/pi-agent-core": "^1.0.0",
41
- "@earendil-works/pi-ai": "1.0.0",
42
- "@earendil-works/pi-tui": "^1.0.0",
40
+ "@earendil-works/pi-agent-core": "^1.1.0",
41
+ "@earendil-works/pi-ai": "1.1.0",
42
+ "@earendil-works/pi-tui": "^1.1.0",
43
43
  "@elysiajs/cors": "^1.1.1",
44
44
  "@elysiajs/node": "^1.4.2",
45
45
  "@fugood/llama.node": "^1.8.0-rc.9",
46
- "@fugood/whisper.node": "^1.2.0-rc.0",
46
+ "@fugood/whisper.node": "^1.2.0-rc.1",
47
47
  "@huggingface/gguf": "^0.3.2",
48
48
  "@iarna/toml": "^3.0.0",
49
49
  "@modelcontextprotocol/sdk": "^1.30.0",
@@ -69,11 +69,11 @@
69
69
  "zod": "^3.25.76"
70
70
  },
71
71
  "devDependencies": {
72
- "@fugood/agent-tool-runtime": "^2.26.0-beta.18",
73
- "@fugood/bricks-cli": "^2.26.0-beta.18",
72
+ "@fugood/agent-tool-runtime": "^2.26.0-beta.19",
73
+ "@fugood/bricks-cli": "^2.26.0-beta.19",
74
74
  "@fugood/bricks-devtools-core": "^2.26.0-beta.18",
75
75
  "tsdown": "^0.22.4",
76
76
  "typescript": "^7.0.2"
77
77
  },
78
- "gitHead": "56a905825a9905fbcf48a3ee7dcc689759b7f1f4"
78
+ "gitHead": "59c100eee13c4152667a221954959f741ef0194f"
79
79
  }
@@ -1,112 +0,0 @@
1
- #!/usr/bin/env node
2
- import{n as e}from"./protocol-RJSV46H1.mjs";import{createRequire as t}from"node:module";import{readFile as n}from"node:fs/promises";import{runToolCall as r}from"@earendil-works/pi-agent-core";import{Worker as i}from"node:worker_threads";function a(e){let t=``;for(let n of e){let e=t===``?/^[A-Za-z_$]$/.test(n):/^[A-Za-z0-9_$]$/.test(n);t+=e?n:`_`}return t===``?`_`:t}const o=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function s(e,t={}){let n=e.inputSchema===void 0?`unknown`:m(e.inputSchema,{maxChars:t.inputMaxChars??16e3});return`${a(e.name)}(args: ${n}): Promise<${u(e.outputSchema)}>;`}function c(e,t={}){let n=`declare const tools: { ${s(e,t)} };`;return`${e.description?.trim()??``}\n\ncodemode tool declaration:\n\`\`\`ts\n${n}\n\`\`\``}function l(e){if(!f(e)||!f(e.properties))return;let{content:t,isError:n,_meta:r,structuredContent:i}=e.properties;if(!(!f(t)||t.type!==`array`||!f(t.items)||t.items.type!==`object`)&&!(!f(n)||n.type!==`boolean`||!f(r)||r.type!==`object`))return f(i)||typeof i==`boolean`?i:!0}function u(e){let t=l(e);if(t!==void 0){let e=m(t);return e===`unknown`?`CallToolResult`:`CallToolResult<${e}>`}return e===void 0?`unknown`:m(e)}function d(e){return o.test(e)?e:JSON.stringify(e)}function f(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function p(e){let t=[...new Set(e)];return t.includes(`unknown`)?`unknown`:t.length===0?`never`:t.join(` | `)}function m(e,t={}){let n=g(e,{root:e,resolving:new Set,expansions:0});return t.maxChars!==void 0&&n.length>t.maxChars?`unknown`:n}function h(e,t){if(e!==`#`&&!e.startsWith(`#/`))return;let n=t;for(let t of e.slice(2).split(`/`).filter(Boolean)){let e=decodeURIComponent(t).replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(!f(n)||!(e in n))return;n=n[e]}return typeof n==`boolean`||f(n)?n:void 0}function g(e,t){if(e===!0)return`unknown`;if(e===!1)return`never`;if(!f(e))return`unknown`;if(typeof e.$ref==`string`){let n=e.$ref;if(t.resolving.has(n)||t.expansions>=32)return`unknown`;let r=h(n,t.root);if(r===void 0)return`unknown`;t.expansions++,t.resolving.add(n);try{return g(r,t)}finally{t.resolving.delete(n)}}if(`const`in e)return JSON.stringify(e.const)??`unknown`;if(Array.isArray(e.enum))return p(e.enum.map(e=>JSON.stringify(e)??`unknown`));let n=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(n)return p(n.map(e=>g(e,t)));if(Array.isArray(e.allOf)){let n=e.allOf.map(e=>g(e,t)).filter(e=>e!==`unknown`);return n.length===0?`unknown`:n.map(e=>e.includes(` | `)?`(${e})`:e).join(` & `)}let r=e.type;if(Array.isArray(r))return p(r.map(n=>g({...e,type:n},t)));switch(r){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:return _(e,t);case`object`:return y(e,t);case void 0:return`properties`in e||`additionalProperties`in e||`required`in e?y(e,t):`items`in e||`prefixItems`in e?_(e,t):`unknown`;default:return`unknown`}}function _(e,t){if(e.items!==void 0&&!Array.isArray(e.items))return`Array<${g(e.items,t)}>`;let n=Array.isArray(e.prefixItems)?e.prefixItems:Array.isArray(e.items)?e.items:[];return n.length>0?`[${n.map(e=>g(e,t)).join(`, `)}]`:`unknown[]`}function v(e){return f(e)&&typeof e.description==`string`?e.description.trim():``}function y(e,t){let n=f(e.properties)?e.properties:{},r=new Set(Array.isArray(e.required)?e.required:[]),i=Object.keys(n).sort(),a=i.map(e=>{let i=r.has(e)?``:`?`;return`${d(e)}${i}: ${g(n[e],t)};`}),o=e.additionalProperties;if(o!==void 0&&o!==!1){let e=o===!0?`unknown`:g(o,t);a.push(`[key: string]: ${e};`)}else o===void 0&&i.length===0&&a.push(`[key: string]: unknown;`);if(a.length===0)return`{}`;if(!i.some(e=>v(n[e])))return`{ ${a.join(` `)} }`;let s=[`{`];i.forEach((e,t)=>{for(let t of v(n[e]).split(/\r?\n/))t.trim()&&s.push(` // ${t.trim()}`);s.push(` ${a[t].replaceAll(`
3
- `,`
4
- `)}`)});for(let e of a.slice(i.length))s.push(` ${e}`);return s.push(`}`),s.join(`
5
- `)}const b=3e3,x={type:`string`};function S(e){return[`Globals:`,"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script.","- `store(key, value)` and `load(key)` keep small JSON values across codemode calls.","- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find tools you were not given directly, such as MCP tools, and read their declarations.",...e?['- `models`: non-chat models with your credentials. `await models.getAvailableOfType("image" | "classifier")` lists them; `models.generateImages(model, { input: [{ type: "text", text }, ...{ type: "image", data, mimeType }] })` resolves to `{ output, stopReason, errorMessage? }` (show its image blocks with `image(block)`; can take minutes, so do not set a short timeout_ms); `models.classify(model, { state: {...}, questions: { id: { type: "choice" | "score" | "bool", instructions, criteria } } })` resolves to `{ answers, stopReason, errorMessage? }`. They do not throw on provider errors: check `stopReason`.']:[]].join(`
6
- `)}function ee(e){return{name:e.name,description:e.description,inputSchema:e.parameters,outputSchema:e.outputSchema??x}}function C(e){let t=a(e.name);return`${t===e.name?`### \`${t}\``:`### \`${t}\` (\`${e.name}\`)`}\n${c(e).trim()}`}function te(e,t){let n=e.map(e=>[...e.entries].sort((e,t)=>e.cost-t.cost)),r=new Set,i=t,a=n.filter(e=>e.length>0);for(;a.length>0;)a=a.filter(e=>{let t=e[0];return t.cost>i?!1:(i-=t.cost,r.add(t.name),e.shift(),e.length>0)});return r}function w({tools:e,declaredNames:t=new Set,isDeferred:n=()=>!1,getNamespace:r=()=>void 0,models:i=!1,inlineBudget:a=b}){let o=['Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file system, network, or timers.\n- `await tools.<name>({ ...args })` calls a tool by its name (characters outside [A-Za-z0-9_] become `_`), including most tools you can call directly (`ALL_TOOLS` is the exact list). It resolves to the tool\'s text output; MCP tools (`mcp__*`) resolve to their `CallToolResult` (`{ content, structuredContent?, isError? }`). A failed or blocked call rejects with an Error. Calls still running when the script ends are cancelled.\n- Use it to batch independent calls (`Promise.allSettled`), chain calls, or filter large output; only what the script outputs reaches you.\n- Optional first line: `// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}`',S(i)],s=new Map;for(let i of e){if(t.has(i.name))continue;let e=r(i);if(!e||!n(i))continue;let a=s.get(e.name)??{...e,count:0};a.count+=1,s.set(e.name,a)}if(s.size>0){let e=[...s.values()].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>{let t=e.description?.trim().split(`
7
- `)[0];return`- \`${e.name}\` (${e.count} tool${e.count===1?``:`s`})${t?`: ${t}`:``}`});o.push(`Tool namespaces (find their tools with \`searchTools(query, { namespace })\` or \`describeNamespace(name)\`):\n${e.join(`
8
- `)}`)}let c=e.filter(e=>!t.has(e.name)&&!n(e)).map(ee);if(c.length===0)return o.join(`
9
-
10
- `);let u=new Map([[``,{namespace:void 0,entries:[]}]]);for(let t of c){let n=r(e.find(e=>e.name===t.name)),i=n?`ns:${n.name}`:``,a=u.get(i)??{namespace:n,entries:[]};u.set(i,a);let o=C(t);a.entries.push({name:t.name,section:o,cost:Math.ceil(o.length/4)})}let d=[...u.values()].sort((e,t)=>e.namespace===void 0?-1:t.namespace===void 0?1:e.namespace.name.localeCompare(t.namespace.name)),f=te(d,a);c.some(e=>f.has(e.name)&&l(e.outputSchema)!==void 0)&&o.push(`Shared MCP Types:
11
- \`\`\`ts
12
- type Role = "user" | "assistant";
13
- type MetaObject = Record<string, unknown>;
14
- type Annotations = {
15
- audience?: Role[];
16
- priority?: number;
17
- lastModified?: string;
18
- };
19
- type Icon = {
20
- src: string;
21
- mimeType?: string;
22
- sizes?: string[];
23
- theme?: "light" | "dark";
24
- };
25
- type TextResourceContents = {
26
- uri: string;
27
- mimeType?: string;
28
- _meta?: MetaObject;
29
- text: string;
30
- };
31
- type BlobResourceContents = {
32
- uri: string;
33
- mimeType?: string;
34
- _meta?: MetaObject;
35
- blob: string;
36
- };
37
- type TextContent = {
38
- type: "text";
39
- text: string;
40
- annotations?: Annotations;
41
- _meta?: MetaObject;
42
- };
43
- type ImageContent = {
44
- type: "image";
45
- data: string;
46
- mimeType: string;
47
- annotations?: Annotations;
48
- _meta?: MetaObject;
49
- };
50
- type AudioContent = {
51
- type: "audio";
52
- data: string;
53
- mimeType: string;
54
- annotations?: Annotations;
55
- _meta?: MetaObject;
56
- };
57
- type ResourceLink = {
58
- icons?: Icon[];
59
- name: string;
60
- title?: string;
61
- uri: string;
62
- description?: string;
63
- mimeType?: string;
64
- annotations?: Annotations;
65
- size?: number;
66
- _meta?: MetaObject;
67
- type: "resource_link";
68
- };
69
- type EmbeddedResource = {
70
- type: "resource";
71
- resource: TextResourceContents | BlobResourceContents;
72
- annotations?: Annotations;
73
- _meta?: MetaObject;
74
- };
75
- type ContentBlock =
76
- | TextContent
77
- | ImageContent
78
- | AudioContent
79
- | ResourceLink
80
- | EmbeddedResource;
81
- type CallToolResult<TStructured = { [key: string]: unknown }> = {
82
- _meta?: MetaObject;
83
- content: ContentBlock[];
84
- isError?: boolean;
85
- structuredContent?: TStructured;
86
- [key: string]: unknown;
87
- };
88
- \`\`\``);let p=[`Script-only tools:`];for(let{namespace:e,entries:t}of d){let n=t.filter(e=>f.has(e.name));if(e){let r=n.length===t.length?``:n.length===0?` (tools not listed)`:` (some tools not listed)`;p.push(`## ${e.name}${r}`)}for(let e of n)p.push(e.section)}return o.push(p.join(`
89
-
90
- `)),o.join(`
91
-
92
- `)}const T=new Map;function ne(e){let r=e??t(import.meta.url).resolve(`quickjs-wasi/quickjs.wasm`),i=T.get(r);if(!i){let{WebAssembly:e}=globalThis;i=n(r).then(t=>e.compile(t)).catch(e=>{throw T.delete(r),e}),T.set(r,i)}return i}const re=/^[A-Za-z_$][A-Za-z0-9_$]*$/,E=new Set([`tools`,`ALL_TOOLS`,`console`,`text`,`image`,`exit`,`globalThis`,`store`,`load`]);function D(e){return e instanceof Error?e.message:String(e)}function O(e){let t=Object.create(null);for(let[n,r]of Object.entries(e??{})){let e=JSON.stringify(r);e!==void 0&&(t[n]=e)}return t}function ie(e){let t={set:Object.create(null),delete:[]};for(let[n,r]of JSON.parse(e))r===void 0?t.delete.push(n):t.set[n]=JSON.parse(r);return t}function k(){return new URL(import.meta.url.endsWith(`.ts`)?`./worker.ts`:`./worker.js`,import.meta.url)}var A=class{promise;resolveResult;worker;interrupt=new SharedArrayBuffer(4);tools;globals;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(e){this.promise=new Promise(e=>{this.resolveResult=e}),this.tools=e.tools,this.globals=e.globals,this.signal=e.signal,Number.isFinite(e.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:`timeout`,message:`Execution timed out after ${e.timeoutMs} ms`})},e.timeoutMs)),e.signal&&(e.signal.aborted?this.onAbort():e.signal.addEventListener(`abort`,this.onAbort,{once:!0})),e.wasm.then(t=>this.start(e,t),e=>{this.finish({kind:`sandbox`,message:`Failed to load QuickJS: ${D(e)}`})})}abort(e){return this.finish({kind:`aborted`,message:e}),this.promise}start(e,t){if(this.finished)return;let n={code:e.code,tools:[...e.tools.values()].map(e=>({name:e.name,jsName:a(e.name),description:e.description??``})),globals:[...e.globals.values()].map(e=>({name:e.name,spread:e.spread===!0})),wasm:t,memoryLimitBytes:e.memoryLimitBytes,store:e.store,interrupt:this.interrupt},r;try{r=new i(e.workerUrl,{workerData:n})}catch(e){this.finish({kind:`sandbox`,message:`Failed to start worker: ${D(e)}`});return}this.worker=r,r.on(`message`,e=>this.handleMessage(e)),r.on(`error`,e=>{this.finish({kind:`sandbox`,name:e instanceof Error?e.name:void 0,message:D(e)})}),r.on(`exit`,e=>{this.finish({kind:`sandbox`,message:`Worker exited with code ${e} before the script settled`})})}onAbort=()=>{let e=this.signal?.reason;this.finish({kind:`aborted`,message:e instanceof Error?e.message:`Execution aborted`})};post(e){this.worker?.postMessage(e)}handleMessage(t){if(!(this.finished||!e(t)))switch(t.type){case`output`:this.output.push(t.item);break;case`call`:this.handleCall(t);break;case`done`:this.handleDone(t);break;case`crash`:this.finish({kind:`sandbox`,message:t.message});break}}handleDone(e){if(!e.ok){let t=JSON.parse(e.error);this.finish({kind:`script`,...t});return}this.finish(void 0,e.value===void 0?void 0:JSON.parse(e.value),e.writes)}async handleCall(e){let{id:t,name:n}=e,r=e.target===`tool`,i=r?{name:n,status:`cancelled`,durationMs:0}:void 0;i&&this.calls.push(i);let a={record:i,startedAt:performance.now(),controller:new AbortController};this.pending.set(t,a);let o,s;try{let i=(r?this.tools:this.globals).get(n);if(!i)throw Error(`Unknown ${r?`tool`:`global`} "${n}"`);let c=e.args===void 0?void 0:JSON.parse(e.args),l=await i.execute(c,{signal:a.controller.signal});s={type:`result`,id:t,ok:!0,payload:l===void 0?void 0:JSON.stringify(l)},o=`ok`}catch(e){s={type:`result`,id:t,ok:!1,payload:D(e)},o=`error`}this.pending.delete(t)&&(i&&(i.status=o,i.durationMs=performance.now()-a.startedAt),this.post(s))}finish(e,t,n){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener(`abort`,this.onAbort);let r=performance.now();for(let e of this.pending.values())e.record&&(e.record.durationMs=r-e.startedAt),e.controller.abort();this.pending.clear();let i=e?{ok:!1,error:e,output:this.output,calls:this.calls}:{ok:!0,value:t,output:this.output,calls:this.calls,storeWrites:n===void 0?{set:{},delete:[]}:ie(n)};if(!this.worker){this.resolveResult(i);return}Atomics.store(new Int32Array(this.interrupt),0,1),this.worker.terminate().catch(()=>void 0).then(()=>this.resolveResult(i))}},ae=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;wasm;workerUrl;running=new Set;closed=!1;constructor(e={}){this.timeoutMs=e.timeoutMs??3e5,this.memoryLimitBytes=e.memoryLimitBytes,this.wasm=e.wasm,this.workerUrl=e.workerUrl??k();for(let t of e.tools??[])this.registerTool(t);let t=new Set;for(let n of e.globals??[]){let e=n.name.split(`.`);if(e.length>2||!e.every(e=>re.test(e))||E.has(e[0]))throw Error(`Invalid global name "${n.name}"`);if(this.globalsByName.has(n.name))throw Error(`Global "${n.name}" is already registered`);e.length===2&&t.add(e[0]),this.globalsByName.set(n.name,n)}for(let e of t)if(this.globalsByName.has(e))throw Error(`Global "${e}" conflicts with the namespace "${e}"`)}registerTool(e){if(this.toolsByName.has(e.name))throw Error(`Tool "${e.name}" is already registered`);this.toolsByName.set(e.name,e)}unregisterTool(e){return this.toolsByName.delete(e)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(e,t={}){if(this.closed)return Promise.reject(Error(`Sandbox is closed`));let n=new A({code:e,tools:new Map(this.toolsByName),globals:this.globalsByName,timeoutMs:t.timeoutMs??this.timeoutMs,signal:t.signal,memoryLimitBytes:this.memoryLimitBytes,store:O(t.store),wasm:this.wasm===void 0?ne():Promise.resolve(this.wasm),workerUrl:this.workerUrl});return this.running.add(n),n.promise.finally(()=>this.running.delete(n))}async close(){this.closed=!0,await Promise.all([...this.running].map(e=>e.abort(`Sandbox closed`)))}};const j=[`max_output_tokens`,`timeout_ms`],M="`max_output_tokens` and `timeout_ms`",oe=2147483647;String.raw`
93
- start: options_source | plain_source
94
- options_source: OPTIONS_LINE NEWLINE SOURCE
95
- plain_source: SOURCE
96
-
97
- OPTIONS_LINE: /[ \t]*\/\/ @options:[^\r\n]*/
98
- NEWLINE: /\r?\n/
99
- SOURCE: /[\s\S]+/
100
- `;var N=class extends Error{constructor(e){super(e),this.name=`CodemodeSourceError`}};function se(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function ce(e){if(e===``)throw new N(`@options must be a JSON object with supported fields ${M}`);let t;try{t=JSON.parse(e)}catch(e){throw new N(`@options must be valid JSON with supported fields ${M}: ${e instanceof Error?e.message:String(e)}`)}if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`@options must be a JSON object with supported fields ${M}`);let n=t;for(let e of Object.keys(n))if(!j.includes(e))throw new N(`@options only supports ${M}; got \`${e}\``);let r={},{max_output_tokens:i,timeout_ms:a}=n;if(i!==void 0){if(!se(i))throw new N("@options field `max_output_tokens` must be a non-negative safe integer");r.maxOutputTokens=i}if(a!==void 0){if(!se(a)||a===0||a>oe)throw new N(`@options field \`timeout_ms\` must be a positive integer up to ${oe}`);r.timeoutMs=a}return r}function le(e){if(e.trim()===``)throw new N('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {"max_output_tokens": 1000}`.');let t=e.indexOf(`
101
- `),n=(t===-1?e:e.slice(0,t)).replace(/\r$/,``).trimStart();if(!n.startsWith(`// @options:`))return{code:e,options:{}};let r=t===-1?``:e.slice(t);if(r.trim()===``)throw new N(`The @options line must be followed by JavaScript source on subsequent lines`);return{code:r,options:ce(n.slice(12).trim())}}function P(e){return String(e||``).toLowerCase().match(/[\p{L}\p{N}]+/gu)||[]}function ue(e){try{return JSON.stringify(e||{}).toLowerCase()}catch{return``}}function de(e,t,n){let r=e.name.toLowerCase(),i=String(e.label||``).toLowerCase(),a=n?.(e),o=String(e._mcpServer||a?.name||``).toLowerCase(),s=String([e.description,a?.description].filter(Boolean).join(` `)).toLowerCase(),c=P(`${r} ${i}`);return{tool:e,index:t,name:r,label:i,server:o,namespace:a?.name,description:s,schema:ue(e.parameters),namePhrase:c.join(` `),nameTerms:new Set(c),serverTerms:new Set(P(o))}}function fe(e,t,n,r){let i=0;(e.name===t||e.label===t)&&(i+=100),n&&e.namePhrase.includes(n)&&(i+=24);for(let t of r)e.nameTerms.has(t)?i+=14:(e.name.includes(t)||e.label.includes(t))&&(i+=9),e.serverTerms.has(t)?i+=7:e.server.includes(t)&&(i+=4),e.description.includes(t)&&(i+=3),e.schema.includes(t)&&(i+=1);return i}function pe(e,{getNamespace:t}={}){return e.map((e,n)=>de(e,n,t))}function me(e,{max:t=10}={}){return Number.isInteger(e)?Math.max(1,Math.min(e,t)):5}function he(e,t,n,{namespace:r,maxLimit:i}={}){let a=String(t||``).trim().toLowerCase(),o=P(a);if(o.length===0)return[];let s=o.join(` `);return e.filter(e=>!r||e.namespace===r).map(e=>({entry:e,score:fe(e,a,s,o)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score||e.entry.index-t.entry.index).slice(0,me(n,{max:i})).map(({entry:e})=>e.tool)}const ge=new Set([`chat`,`image`,`classifier`]),F=e=>typeof e==`object`&&!!e&&!Array.isArray(e),_e=(e,t)=>e.length>t?`${e.slice(0,t-3)}...`:e,I=e=>`${/^[aeiou]/.test(e)?`an`:`a`} ${e}`;function ve(e){return{read:async t=>{let n=await e(t);return n?{type:`api_key`,key:n}:void 0},list:async()=>[],modify:async()=>void 0,delete:async()=>{}}}function ye({getApiKey:e}){let t;return async()=>{if(!t){let{builtinModels:n}=await import(`@earendil-works/pi-ai/providers/all`);t=n({credentials:ve(e)})}return t}}function be({classifiers:e,images:t}={}){let n=async(n,r)=>{let i=n===`classifier`?e?(await e()).getModelsOfType(`classifier`):[]:n===`image`?t?.list()??[]:[];return r?i.filter(e=>e.provider===r):i};return{getModelsOfType:n,getAvailableOfType:async(t,r,i)=>t===`classifier`&&e?(await e()).getAvailableOfType(`classifier`,r,i):n(t,r),getModelOfType:async(e,t,r)=>(await n(e,t)).find(e=>e.id===r),classify:async(t,n,r)=>(await e()).classify(t,n,r),generateImages:(e,n,r)=>t.generateImages(e,n,r)}}function L(e){if(typeof e==`string`&&ge.has(e))return e;throw Error(`Unknown model type ${JSON.stringify(e)}. Use "chat", "image", or "classifier".`)}function xe(e){if(e!=null){if(typeof e!=`string`)throw Error(`provider must be a string`);return e}}function R(e){let{headers:t,...n}=e;return n}function z(e){if(e==null)return String(e);if(Array.isArray(e))return e.length===0?`an empty array`:`an array`;if(typeof e==`object`){let t=Object.keys(e);return t.length===0?`{}`:`{ ${t.slice(0,6).join(`, `)}${t.length>6?`, ...`:``} }`}return typeof e==`string`?`a string`:`a ${typeof e}`}function Se(e){let t=e=>Error(`models.classify() ${e}. Expected context: { state: { ... }, questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }.`);if(!F(e))throw t(`expects a context object as its second argument, got ${z(e)}`);if(!F(e.state))throw t(`context.state must be an object, got ${z(e.state)}`);let{questions:n}=e;if(!F(n)||Object.keys(n).length===0)throw t(`context.questions must map question IDs to questions, got ${z(n)}`);let r=e=>e.length>0&&e.every(e=>typeof e==`string`);for(let[e,i]of Object.entries(n)){let n=`context.questions.${e}`;if(!F(i))throw t(`${n} must be a question object, got ${z(i)}`);if(typeof i.instructions!=`string`)throw t(`${n}.instructions must be a string`);let{criteria:a}=i;if(i.type===`choice`){if(!F(a)||!r(Object.values(a)))throw t(`${n} is a "choice" question, so criteria must map each label to its meaning`)}else if(i.type===`score`){if(!Array.isArray(a)||!r(a))throw t(`${n} is a "score" question, so criteria must list the levels as strings, lowest first`)}else if(i.type===`bool`){if(!F(a)||typeof a.true!=`string`||typeof a.false!=`string`)throw t(`${n} is a "bool" question, so criteria must be { true: string, false: string }`)}else throw t(`${n}.type must be "choice", "score", or "bool", got ${JSON.stringify(i.type)}`)}return e}function Ce(e){let t=e=>Error(`models.generateImages() ${e}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }.`);if(!F(e))throw t(`expects a context object as its second argument, got ${z(e)}`);let{input:n}=e;if(!Array.isArray(n)||n.length===0)throw t(`context.input must be a non-empty array of blocks, got ${z(n)}`);return n.forEach((e,n)=>{if(!(F(e)&&e.type===`text`&&typeof e.text==`string`)&&!(F(e)&&e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`))throw t(`context.input[${n}] must be a text or image block, got ${z(e)}`)}),e}function we(e){let t=0,n=[];return async r=>{t>=e?await new Promise(e=>n.push(e)):t+=1;try{return await r()}finally{let e=n.shift();e?e():--t}}}function Te(e,{toolCallId:t,track:n,publish:r,addUsage:i,addGeneratedImages:a}){let o=we(4),s=0,c=async(a,c,[l,u],d,f)=>{let p=`List the ${c} models you can use with models.getAvailableOfType("${c}").`;if(!F(l)||typeof l.provider!=`string`||typeof l.id!=`string`){let e=l==null?` models.getModelOfType() returns undefined for an unknown provider or id.`:``;throw Error(`${a}() expects ${I(c)} model as its first argument, got ${z(l)}.${e} ${p}`)}let{provider:m,id:h}=l,g=await e.getModelOfType(c,m,h);if(!g){let t;for(let n of ge)n!==c&&await e.getModelOfType(n,m,h)&&(t=n);throw Error(t?`"${m}/${h}" is ${I(t)} model, not ${I(c)} model. ${p}`:`Unknown ${c} model "${m}/${h}". ${p}`)}let _=d(u),v=n({id:`${t}/${a}/${++s}`,name:a,args:`${g.provider}/${g.id}`,status:`running`});r();let y=performance.now(),b=await o(()=>f(g,_));return v.durationMs=performance.now()-y,v.status=b.stopReason===`stop`?`ok`:b.stopReason===`aborted`?`cancelled`:`error`,b.errorMessage&&(v.error=_e(b.errorMessage,500)),b.usage&&(v.cost=b.usage.cost?.total,i(b.usage)),r(),b};return Object.entries({"models.getModelsOfType":async([t,n])=>(await e.getModelsOfType(L(t),xe(n))).map(R),"models.getAvailableOfType":async([t,n],{signal:r})=>(await e.getAvailableOfType(L(t),xe(n),{signal:r})).map(R),"models.getModelOfType":async t=>{let[n,r,i]=t;if(typeof r!=`string`||typeof i!=`string`)throw Error(`models.getModelOfType(type, provider, id) expects three strings, got (${t.map(z).join(`, `)}). The provider and the id are separate arguments.`);let a=await e.getModelOfType(L(n),r,i);return a===void 0?void 0:R(a)},"models.classify":(t,{signal:n})=>c(`models.classify`,`classifier`,t,Se,(t,r)=>e.classify(t,r,{signal:n})),"models.generateImages":(t,{signal:n})=>c(`models.generateImages`,`image`,t,Ce,async(t,r)=>{let i=await e.generateImages(t,r,{signal:n});return a(i.output.filter(e=>e.type===`image`).length),i})}).map(([e,t])=>({name:e,spread:!0,execute:t}))}const Ee=256*1024*1024,De=5*6e4,Oe=30*6e4,B=(e,t)=>e.length>t?`${e.slice(0,t-3)}...`:e;function ke(e){if(e===void 0)return``;try{return B(JSON.stringify(e)??``,200)}catch{return``}}const V=e=>(e?.content??[]).filter(e=>e.type===`text`).map(e=>e.text).join(`
102
- `),Ae=e=>typeof e==`string`?e:JSON.stringify(e)??String(e);function je(e,t){if(!e)return structuredClone(t);for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`,`totalTokens`])e[n]=(e[n]??0)+(t[n]??0);if(t.cost){e.cost??={};for(let[n,r]of Object.entries(t.cost))e.cost[n]=(e.cost[n]??0)+(r??0)}return e}function Me(e){return e.length===0?`No tool calls were made.`:`Tool calls made before the failure (they are not undone): ${e.map(e=>`${e.name} (${e.status})`).join(`, `)}`}function Ne(e,t){return`${e.kind===`script`?e.stack??`${e.name??`Error`}: ${e.message}`:e.kind===`timeout`?`Script timed out: ${e.message}`:e.kind===`aborted`?`Script aborted: ${e.message}`:`Script sandbox failed: ${e.message}`}\n\n${Me(t)}`}function H(e,t){let n=Math.floor(t/2),r=t-n,i=e.length-n-r;return`${e.slice(0,n)}…${Math.ceil(i/4)} tokens truncated…${r>0?e.slice(-r):``}`}function Pe(e,t){let n=Array.from({length:e.length}),r=e.map((e,t)=>({length:e,index:t})).sort((e,t)=>e.length-t.length),i=t;return r.forEach(({length:e,index:t},a)=>{n[t]=Math.min(e,Math.floor(i/(r.length-a))),i-=n[t]}),n}async function Fe(e,t,n){let r=e.filter(e=>e.type===`text`).map(e=>e.text),i=r.join(`
103
- `),a=t*4;if(r.length===0||i.length<=a)return{items:e};let o=Pe(r.map(e=>e.length),a),s=r.every((e,t)=>e.length<=o[t]||o[t]>=400)?r.map((e,t)=>e.length>o[t]?H(e,o[t]):e).join(`
104
- `):H(i,a),c=`Warning: truncated output (original token count: ${Math.ceil(i.length/4)})\nTotal output lines: ${i.split(`
105
- `).length}\n\n${s}`,l;if(n)try{l=await n(i),l&&(c+=`\n\n[Full output: ${l} (read with offset/limit)]`)}catch(e){c+=`\n\n[Could not save the full output: ${e?.message||e}]`}return{items:[{type:`text`,text:c},...e.filter(e=>e.type===`image`)],...l?{fullOutputPath:l}:{}}}function Ie(e,t){let{result:n}=t;if(e.outputSchema&&n.structuredContent!==void 0)return n.structuredContent;let r=V(n);if(t.isError)throw Error(r||`Tool "${e.name}" failed`);return r}function Le(e,t){let n=a(e),r=a(t),i=e=>e.includes(`__`)?e.slice(e.lastIndexOf(`__`)+2):void 0;return e===t||n===r||i(e)===t||i(n)===r}function Re(e,t,n){let r=pe(e,{getNamespace:n}),i=e=>({name:a(e.name),description:t.get(e.name)??``}),o=t=>e.map(n).find(e=>e&&Le(e.name,t));return[{name:`searchTools`,spread:!0,execute:([e,t])=>{if(typeof e!=`string`)throw Error(`searchTools() expects a query string`);let n=t?.limit??8;if(typeof n!=`number`||!Number.isInteger(n)||n<=0)throw Error(`searchTools() limit must be a positive integer`);let a=t?.namespace;if(a!=null&&typeof a!=`string`)throw Error(`searchTools() namespace must be a string`);let s=a?o(a):void 0;return a&&!s?[]:he(r,e,n,{namespace:s?.name,maxLimit:Math.max(n,8)}).map(i)}},{name:`describeTool`,spread:!0,execute:([n])=>{if(typeof n!=`string`)throw Error(`describeTool() expects a tool name`);let r=e.find(e=>e.name===n||a(e.name)===n);return r?t.get(r.name):void 0}},{name:`describeNamespace`,spread:!0,execute:([t])=>{if(typeof t!=`string`)throw Error(`describeNamespace() expects a namespace name`);let r=o(t);if(r)return{name:r.name,...r.description?{description:r.description}:{},...r.instructions?{instructions:r.instructions}:{},tools:e.filter(e=>n(e)?.name===r.name).map(e=>a(e.name))}}}]}async function U({toolCallId:e,code:t,signal:n,onUpdate:r,tools:i,executeTool:a,store:o={},models:s,getNamespace:l=()=>void 0,sandbox:u={},spillOutput:d}){let f=performance.now(),p;try{p=le(t)}catch(e){if(!(e instanceof N))throw e;return{content:[{type:`text`,text:`Script failed\nScript error:\n${e.message}`}],details:{calls:[]},isError:!0}}let{code:m,options:h}=p,g=[],_=0,v,y=0,b=()=>g.slice(-200).map(e=>({...e})),x=()=>r?.({content:[],details:{calls:b()}}),S=e=>(g.push(e),e),C=new Map(i.map(e=>[e.name,c(ee(e))])),te=i.map(t=>({name:t.name,description:C.get(t.name),execute:async(n,{signal:r})=>{let i=S({id:`${e}/${++_}`,name:t.name,args:ke(n),status:`running`});x();let o=performance.now(),s=await a(t,n,{id:i.id,parentToolCallId:e,signal:r});return i.durationMs=performance.now()-o,s.isError?(i.status=r.aborted?`cancelled`:`error`,i.error=B(V(s.result)||`Tool "${t.name}" failed`,500)):i.status=`ok`,x(),Ie(t,s)}})),w=Math.min(h.timeoutMs??u.defaultTimeoutMs??1/0,u.maxTimeoutMs??1/0),T=new ae({tools:te,globals:[...Re(i,C,l),...s?Te(s,{toolCallId:e,track:S,publish:x,addUsage:e=>{v=je(v,e)},addGeneratedImages:e=>{y+=e}}):[]],timeoutMs:w,memoryLimitBytes:u.memoryLimitBytes??268435456,...u.wasmPath?{wasm:ne(u.wasmPath)}:{},...u.workerUrl?{workerUrl:u.workerUrl}:{}}),re=u.limit??(e=>e()),E;try{E=await re(()=>T.execute(m,{signal:n,store:o}))}finally{await T.close()}for(let e of g)e.status===`running`&&(e.status=`cancelled`);let D=E.output.map(e=>e.type===`text`?{type:`text`,text:e.text}:e);E.ok?E.value!==void 0&&D.push({type:`text`,text:Ae(E.value)}):D.push({type:`text`,text:`Script error:\n${Ne(E.error,g)}`}),y>0&&!D.some(e=>e.type===`image`)&&D.push({type:`text`,text:`Note: models.generateImages() returned ${y} image${y===1?``:`s`} that the script did not show. Show each image block of result.output with image(block).`});let O=await Fe(D,h.maxOutputTokens??1e4,d),ie=((performance.now()-f)/1e3).toFixed(1),k=`${E.ok?`Script completed`:`Script failed`}\nWall time ${ie} seconds\nOutput:\n`,A=E.ok?E.storeWrites:null,j=A&&(Object.keys(A.set).length>0||A.delete.length>0);return{content:[{type:`text`,text:k},...O.items],details:{calls:b(),...g.length>200?{omittedCalls:g.length-200}:{},...j?{storeWrites:A}:{},...O.fullOutputPath?{fullOutputPath:O.fullOutputPath}:{}},...v?{usage:v}:{},...E.ok?{}:{isError:!0}}}const W=`codemode`,G=`codemodeStore`,K=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function ze(e,t){if(!(!K(t)||!K(t.set)||!Array.isArray(t.delete))){for(let n of t.delete)delete e[n];Object.assign(e,t.set)}}function Be(e){let t=Object.create(null);for(let n of Array.isArray(e)?e:[]){if(K(n?.codemodeStore)){for(let e of Object.keys(t))delete t[e];Object.assign(t,n[G])}n?.role===`toolResult`&&n.toolName===`codemode`&&ze(t,n.details?.storeWrites)}return t}function Ve(e,t){let n=Be(t);Object.keys(n).length>0&&(e[G]=n)}var He=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function q(e){}function Ue(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=q,onError:n=q,onRetry:r=q,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=We(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
106
- `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new He(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new He(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
107
- `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function We(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
108
- `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
109
- `&&r++}}return[t,n]}const J=`ctor-images`,Y=2e3;async function X(e,t,n){let r=await e(t,n),i=await r.text();if(!r.ok)throw Error(`HTTP ${r.status}: ${i.slice(0,Y)}`);try{return JSON.parse(i)}catch{throw Error(`Provider returned invalid JSON: ${i.slice(0,Y)}`)}}function Z(e){return{prompt:e.filter(e=>e.type===`text`).map(e=>e.text).join(`
110
- `),images:e.filter(e=>e.type===`image`)}}const Q=(e,t,n)=>{let r=e[t];if(!r)throw Error(n);return r};function Ge(e){let{prompt:t,images:n}=Z(e);return{contents:[{role:`user`,parts:[{text:t},...n.map(e=>({inlineData:{mimeType:e.mimeType,data:e.data}}))]}],generationConfig:{responseModalities:[`TEXT`,`IMAGE`]}}}function Ke(e){let t=e?.candidates?.[0]?.content?.parts||e?.parts||[],n=[];for(let e of t){e?.text&&n.push({type:`text`,text:e.text});let t=e?.inlineData||e?.inline_data;t?.data&&n.push({type:`image`,data:t.data,mimeType:t.mimeType||t.mime_type||`image/png`})}return n}function qe(e,t,n){let r=encodeURIComponent(t);if(e===`bricks`){let e=Q(n,`BRICKS_AI_GATEWAY_URL`,`BRICKS image generation needs a signed-in BRICKS account.`),t;try{t=JSON.parse(n.BRICKS_AI_GATEWAY_HEADERS||`{}`)}catch{throw Error(`BRICKS_AI_GATEWAY_HEADERS must be a JSON object of request headers.`)}return{url:`${e.replace(/\/+$/,``)}/v1/gemini/models/${r}:generateContent`,headers:t}}if(e===`google`){let e=n.GEMINI_API_KEY||n.GOOGLE_API_KEY;if(!e)throw Error(`Google image generation needs a Gemini API key.`);return{url:`https://generativelanguage.googleapis.com/v1beta/models/${r}:generateContent?key=${encodeURIComponent(e)}`,headers:{}}}let i=Q(n,`GOOGLE_CLOUD_PROJECT`,`Vertex AI image generation needs a Google Cloud project.`),a=n.GOOGLE_CLOUD_LOCATION||`global`,o=a===`global`?`aiplatform.googleapis.com`:`${a}-aiplatform.googleapis.com`,s=n.GOOGLE_VERTEX_API_KEY?{"x-goog-api-key":n.GOOGLE_VERTEX_API_KEY}:n.GOOGLE_VERTEX_ACCESS_TOKEN?{Authorization:`Bearer ${n.GOOGLE_VERTEX_ACCESS_TOKEN}`}:null;if(!s)throw Error(`Vertex AI image generation needs an API key or an access token.`);return{url:`https://${o}/v1/projects/${encodeURIComponent(i)}/locations/${encodeURIComponent(a)}/publishers/google/models/${r}:generateContent`,headers:s}}async function $(e,t,n,r,{fetch:i,signal:a}){let{url:o,headers:s}=qe(e,t,r);return Ke(await X(i,o,{method:`POST`,headers:{...s,"Content-Type":`application/json`},body:JSON.stringify(Ge(n)),signal:a}))}async function Je(e,t,n){let r=[];for(let i of Array.isArray(t?.data)?t.data:[])if(i?.b64_json)r.push({type:`image`,data:i.b64_json,mimeType:`image/png`});else if(i?.url){let t=await e(i.url,{signal:n});if(!t.ok)throw Error(`Failed to download image URL: HTTP ${t.status}`);let a=t.headers.get(`content-type`)||`image/png`;r.push({type:`image`,data:Buffer.from(await t.arrayBuffer()).toString(`base64`),mimeType:a})}return r}async function Ye(e,t,n,{fetch:r,signal:i}){let a=Q(n,`OPENAI_API_KEY`,`OpenAI image generation needs an API key.`),o=(n.OPENAI_BASE_URL||`https://api.openai.com/v1`).replace(/\/$/,``),{prompt:s,images:c}=Z(t),l={model:e,prompt:s,n:1,size:`auto`,quality:`medium`,output_format:`png`};if(c.length===0)return Je(r,await X(r,`${o}/images/generations`,{method:`POST`,headers:{Authorization:`Bearer ${a}`,"Content-Type":`application/json`},body:JSON.stringify(l),signal:i}),i);let u=new FormData;for(let[e,t]of Object.entries(l))u.append(e,String(t));return c.forEach((e,t)=>{let n=e.mimeType.split(`/`)[1]||`png`;u.append(c.length>1?`image[]`:`image`,new Blob([Buffer.from(e.data,`base64`)],{type:e.mimeType}),`reference-${t+1}.${n}`)}),Je(r,await X(r,`${o}/images/edits`,{method:`POST`,headers:{Authorization:`Bearer ${a}`},body:u,signal:i}),i)}function Xe(e){let t=(e.OPENAI_CODEX_BASE_URL||`https://chatgpt.com/backend-api`).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function Ze(e){try{let t=JSON.parse(Buffer.from(e.split(`.`)[1]||``,`base64url`).toString(`utf8`))?.[`https://api.openai.com/auth`]?.chatgpt_account_id;if(typeof t==`string`&&t)return t}catch{}throw Error(`The OpenAI Codex token does not include a ChatGPT account ID.`)}async function*Qe(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r=[],i=Ue({onEvent:({data:e})=>r.push(e)}),a=!1;try{for(;;){let{done:e,value:o}=await t.read(),s=n.decode(o,{stream:!e});i.feed(s),s&&(a=s.endsWith(`\r`)),e&&a&&i.feed(`
111
- `);for(let e of r)if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch{}if(r.length=0,e)break}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}async function $e(e,t,n,{fetch:r,signal:i}){let a=Q(n,`OPENAI_CODEX_ACCESS_TOKEN`,`OpenAI Codex image generation needs a ChatGPT sign-in.`),{prompt:o,images:s}=Z(t),c=await r(Xe(n),{method:`POST`,headers:{Authorization:`Bearer ${a}`,"chatgpt-account-id":Ze(a),originator:`pi`,"OpenAI-Beta":`responses=experimental`,Accept:`text/event-stream`,"Content-Type":`application/json`},body:JSON.stringify({model:e,store:!1,stream:!0,instructions:[`You are an image generation agent.`,`Use the image_generation tool for the user request.`,`Do not finish with text only when an image can be generated.`,s.length>0?`Use the attached image(s) as visual input and create one edited image.`:`Create one image.`].join(` `),input:[{role:`user`,content:[{type:`input_text`,text:o},...s.map(e=>({type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`}))]}],tools:[{type:`image_generation`,output_format:`png`}],tool_choice:`auto`,parallel_tool_calls:!1,text:{verbosity:`low`}}),signal:i});if(!c.ok)throw Error(`HTTP ${c.status}: ${(await c.text()).slice(0,Y)}`);let l=[];for await(let e of Qe(c)){if(e?.type===`error`)throw Error(e.message||e.code||`Codex error`);if(e?.type===`response.failed`)throw Error(e.response?.error?.message||`OpenAI Codex response failed.`);let t=e?.item;if(t?.type===`message`)for(let e of Array.isArray(t.content)?t.content:[]){let t=e?.text||e?.content?.[0]?.text;typeof t==`string`&&t.trim()&&l.push({type:`text`,text:t})}t?.type===`image_generation_call`&&t.result&&l.push({type:`image`,data:t.result,mimeType:`image/png`})}return l}const et={bricks:(e,t,n,r)=>$(`bricks`,e,t,n,r),google:(e,t,n,r)=>$(`google`,e,t,n,r),"google-vertex":(e,t,n,r)=>$(`google-vertex`,e,t,n,r),openai:Ye,"openai-codex":$e};function tt({listProviders:e,resolveEnv:t,fetch:n=globalThis.fetch}){return{list:()=>e().filter(({provider:e})=>et[e]).map(({provider:e,defaultModel:t})=>({type:`image`,provider:e,id:t,name:t,api:J,input:[`text`,`image`],output:[`text`,`image`]})),generateImages:async(e,r,{signal:i}={})=>{let a={api:J,provider:e.provider,model:e.id};try{let o=await t(e.provider),s=await et[e.provider](e.id,r.input,o,{fetch:n,signal:i}),c=s.some(e=>e.type===`image`);return{...a,output:s,stopReason:c?`stop`:`error`,...c?{}:{errorMessage:`The model returned no image.`},timestamp:Date.now()}}catch(e){return{...a,output:[],stopReason:i?.aborted?`aborted`:`error`,errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}}}}const nt={type:`object`,properties:{code:{type:`string`,description:`Raw JavaScript source.`}},required:[`code`],additionalProperties:!1};function rt(e){if(!e?._mcpNamespace)return;let t=e._mcpServerInstructions?.trim();return{name:e._mcpNamespace,description:e._mcpServerDescription??t?.split(`
112
- `)[0],...t?{instructions:t}:{}}}const it=e=>!!e?._mcpServer&&e._mcpExposure!==`direct`;function at(e,t,{id:n,parentToolCallId:i,signal:a,hooks:o,state:s}){let c={type:`toolCall`,id:n,name:e.name,arguments:t,parentToolCallId:i},l=s?.messages??[],u=[...l].reverse().find(e=>e.role===`assistant`);return r(c,{tools:[e],assistantMessage:u??{role:`assistant`,content:[c]},context:{systemPrompt:s?.systemPrompt??``,messages:l,tools:s?.tools??[e]},beforeToolCall:o?.beforeToolCall,afterToolCall:o?.afterToolCall,signal:a})}function ot(e){return{...e,execute:(t,n,r,i)=>e.execute(t,n,r,i&&(e=>i(e.details)))}}function st({getTools:e,declaredNames:t,isDeferred:n=it,getNamespace:r=rt,executeTool:i,getStore:a=()=>({}),models:o,sandbox:s,spillOutput:c,inlineBudget:l}){let u=()=>e().filter(e=>e.name!==W);return{name:W,label:`Codemode`,description:w({tools:u(),declaredNames:t,isDeferred:n,getNamespace:r,models:!!o,inlineBudget:l}),parameters:nt,execute:(e,t,n,l)=>U({toolCallId:e,code:t?.code??``,signal:n,onUpdate:l,tools:u(),executeTool:i,store:a(),models:o,getNamespace:r,sandbox:s,spillOutput:c})}}export{nt as CODEMODE_PARAMETERS,G as CODEMODE_STORE_SNAPSHOT_KEY,W as CODEMODE_TOOL_NAME,J as CTOR_IMAGE_API,b as DEFAULT_CODEMODE_INLINE_BUDGET,Ee as DEFAULT_CODEMODE_MEMORY_LIMIT_BYTES,De as DEFAULT_CODEMODE_TIMEOUT_MS,Oe as MAX_CODEMODE_TIMEOUT_MS,Ve as annotateCodemodeStore,Be as collectCodemodeStore,ye as createClassifierModels,w as createCodemodeDescription,be as createCodemodeModels,st as createCodemodeTool,tt as createImageModels,we as createLimiter,U as executeCodemode,it as isSearchOnlyMcpTool,rt as mcpToolNamespace,at as runNestedToolCall,ot as withDetailsUpdates};
@@ -1,5 +0,0 @@
1
- #!/usr/bin/env node
2
- import{i as e,r as t,t as n}from"./rolldown-runtime-dTnj95Mm.mjs";import{createHash as r}from"node:crypto";import i from"node:path";import{spawn as a}from"node:child_process";import o from"node:process";import{createServer as s}from"node:http";const c=[`codemode`,`deferred`,`direct`,`hidden`],l={"codemode-deferred":`codemode`},u=[`localhost`,`127.0.0.1`,`[::1]`],d=e=>typeof e==`object`&&!!e&&!Array.isArray(e),f=e=>d(e)&&Object.values(e).every(e=>typeof e==`string`),p=e=>typeof e==`string`?l[e]??e:e,m=e=>c.includes(e);function h(e){return`mcp__${String(e).replace(/[^A-Za-z0-9_]/g,`_`)}`}const ee=e=>RegExp(`^${e.split(`*`).map(e=>e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`)).join(`.*`)}$`);function g(e,t,n=`deferred`){let r=d(e?.toolExposure)?e.toolExposure:{},i=Object.hasOwn(r,t)?r[t]:void 0;if(i!==void 0)return i;for(let[e,n]of Object.entries(r))if(e.includes(`*`)&&ee(e).test(t))return n;return e?.exposure??n}const te=e=>{if(!URL.canParse(e))return!1;let t=new URL(e);return t.protocol===`http:`&&u.includes(t.hostname)&&t.search===``&&t.hash===``};function ne(e){if(e===void 0)return;if(!d(e))return`oauth must be an object`;for(let t of[`clientId`,`clientSecret`,`scope`])if(e[t]!==void 0&&typeof e[t]!=`string`)return`oauth.${t} must be a string`;let t=e.callbackPort;if(t!==void 0&&(typeof t!=`number`||!Number.isInteger(t)||t<1||t>65535))return`oauth.callbackPort must be a port number`;if(e.callbackUrl!==void 0){if(typeof e.callbackUrl!=`string`||!te(e.callbackUrl))return`oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment`;let n=new URL(e.callbackUrl).port;if(n&&t!==void 0&&Number(n)!==t)return`oauth.callbackUrl and oauth.callbackPort name different ports`}if(e.clientName!==void 0&&(typeof e.clientName!=`string`||!e.clientName.trim()))return`oauth.clientName must be a non-empty string`;let n=e.authServerMetadataUrl;if(n!==void 0){let e=typeof n==`string`&&URL.canParse(n)?new URL(n):null;if(!(e&&(e.protocol===`https:`||e.protocol===`http:`&&u.includes(e.hostname))))return`oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]`}}function re(e,t){if(typeof e!=`string`||!e)return`server names must be non-empty strings`;if(!d(t))return`server "${e}" must be an object`;let n={...t};n.exposure!==void 0&&(n.exposure=p(n.exposure)),d(n.toolExposure)&&(n.toolExposure=Object.fromEntries(Object.entries(n.toolExposure).map(([e,t])=>[e,p(t)])));let r=c.map(e=>`"${e}"`).join(`, `);if(n.exposure!==void 0&&!m(n.exposure))return`server "${e}": exposure must be one of ${r}`;if(n.toolExposure!==void 0){if(!d(n.toolExposure))return`server "${e}": toolExposure must map tool names to exposures`;for(let[t,i]of Object.entries(n.toolExposure))if(!m(i))return`server "${e}": toolExposure "${t}" must be one of ${r}`}if(n.enabled!==void 0&&typeof n.enabled!=`boolean`)return`server "${e}": enabled must be a boolean`;if(n.description!==void 0&&typeof n.description!=`string`)return`server "${e}": description must be a string`;if(n.timeout!==void 0&&(typeof n.timeout!=`number`||!(n.timeout>0)))return`server "${e}": timeout must be a positive number of seconds`;let{type:i}=n;if(i===`sse`)return`server "${e}": the legacy SSE transport is not supported; use the streamable HTTP URL`;if(typeof n.url==`string`&&(i===void 0||i===`http`||i===`streamable-http`)){if(!URL.canParse(n.url)||!/^https?:$/.test(new URL(n.url).protocol))return`server "${e}": url must be an http or https URL`;if(n.headers!==void 0&&!f(n.headers))return`server "${e}": headers must map names to strings`;let t=ne(n.oauth);return t?`server "${e}": ${t}`:n}return typeof n.command==`string`&&(i===void 0||i===`stdio`)?n.args!==void 0&&!(Array.isArray(n.args)&&n.args.every(e=>typeof e==`string`))?`server "${e}": args must be an array of strings`:n.env!==void 0&&!f(n.env)?`server "${e}": env must map names to strings`:n.cwd!==void 0&&typeof n.cwd!=`string`?`server "${e}": cwd must be a string`:n:`server "${e}" needs either "command" (stdio) or "url" (streamable HTTP)`}const _={parseError:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internalError:-32603};var v=class extends Error{code;data;constructor(e,t,n){super(t),this.name=`McpError`,this.code=e,this.data=n}},y=class extends Error{constructor(e=`MCP connection closed`){super(e),this.name=`McpConnectionClosedError`}},ie=class extends Error{timeoutMs;constructor(e){super(`MCP request timed out after ${e}ms`),this.name=`McpTimeoutError`,this.timeoutMs=e}},ae=class extends Error{constructor(e=`MCP request aborted`){super(e),this.name=`AbortError`}};function b(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x(e){return e instanceof Error?e:Error(String(e))}function S(e){return typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function C(e){return b(e)&&e.jsonrpc===`2.0`&&S(e.id)&&typeof e.method==`string`}function w(e){return b(e)&&e.jsonrpc===`2.0`&&!(`id`in e)&&typeof e.method==`string`}function T(e){return!b(e)||e.jsonrpc!==`2.0`||!S(e.id)?!1:`result`in e?!(`error`in e):!(`error`in e)||!b(e.error)?!1:typeof e.error.code==`number`&&typeof e.error.message==`string`}function E(e){if(C(e)||w(e)||T(e))return e;throw new v(_.invalidRequest,`Invalid JSON-RPC message`)}const oe=`2025-11-25`,se=[oe,`2025-06-18`,`2025-03-26`,`2024-11-05`],ce=1e3;function le(e){if(!b(e)||typeof e.protocolVersion!=`string`||!b(e.capabilities)||!b(e.serverInfo)||typeof e.serverInfo.name!=`string`||typeof e.serverInfo.version!=`string`||e.instructions!==void 0&&typeof e.instructions!=`string`)throw new v(_.invalidRequest,`Invalid MCP initialize result`);return e}function D(e){return new v(_.invalidRequest,e)}function ue(e,t,n,r){let i=b(n)?n[t]:void 0;if(!b(n)||!Array.isArray(i))throw D(`Invalid MCP ${e} result`);for(let t of i)if(!b(t)||!r(t))throw D(`Invalid entry in MCP ${e} result`);let a=n.nextCursor===null||n.nextCursor===``?void 0:n.nextCursor;if(a!==void 0&&typeof a!=`string`)throw D(`Invalid MCP ${e} cursor`);return{items:i,...a===void 0?{}:{nextCursor:a}}}const de=e=>typeof e.name==`string`&&b(e.inputSchema),fe=e=>typeof e.uri==`string`&&(e.name===void 0||typeof e.name==`string`),pe=e=>typeof e.uriTemplate==`string`&&(e.name===void 0||typeof e.name==`string`);function me(e){return{...e,name:e.name??e.uri}}function he(e){return{...e,name:e.name??e.uriTemplate}}function ge(e){return e.nextCursor===void 0?{}:{nextCursor:e.nextCursor}}function _e(e){if(!b(e)||!Array.isArray(e.contents))throw D(`Invalid MCP resources/read result`);for(let t of e.contents)if(!b(t)||typeof t.uri!=`string`||typeof t.text!=`string`&&typeof t.blob!=`string`)throw D(`Invalid contents in MCP resources/read result`);return e}function ve(e){if(!b(e)||e.content!==void 0&&!Array.isArray(e.content))throw new v(_.invalidRequest,`Invalid MCP tools/call result`);if(e.structuredContent!==void 0&&!b(e.structuredContent))throw new v(_.invalidRequest,`Invalid MCP tools/call structured content`);return e.content===void 0?{...e,content:[]}:e}var ye=class{options;state=`idle`;transport;nextRequestId=1;serverInfoValue;serverCapabilitiesValue;instructionsValue;protocolVersionValue;pending=new Map;progressRequests=new Map;incoming=new Map;requestHandlers=new Map;notificationListeners=new Map;errorListeners=new Set;closeListeners=new Set;disposers=[];constructor(e){this.options=Object.freeze({...e}),this.requestHandlers.set(`ping`,()=>({}));let t=e.roots;t&&this.requestHandlers.set(`roots/list`,async()=>({roots:[...typeof t==`function`?await t():t]}))}get connectionState(){return this.state}get serverInfo(){return this.serverInfoValue}get serverCapabilities(){return this.serverCapabilitiesValue}get instructions(){return this.instructionsValue}get protocolVersion(){return this.protocolVersionValue}async connect(e){if(this.state!==`idle`)throw Error(`Cannot connect MCP client in ${this.state} state`);this.state=`connecting`,this.transport=e,this.disposers=[e.onMessage(e=>this.handleMessage(e)),e.onError(e=>this.emitError(e)),e.onClose(()=>this.handleTransportClose())];try{await e.start();let t={...this.options.capabilities};this.options.roots&&t.roots===void 0&&(t.roots={});let n=le(await this.requestInternal(`initialize`,{protocolVersion:this.options.protocolVersion??`2025-11-25`,capabilities:t,clientInfo:{name:this.options.name,version:this.options.version,...this.options.title===void 0?{}:{title:this.options.title}}},{},!0));if(!se.includes(n.protocolVersion))throw Error(`MCP server selected unsupported protocol version ${n.protocolVersion}`);return this.protocolVersionValue=n.protocolVersion,this.serverInfoValue=n.serverInfo,this.serverCapabilitiesValue=n.capabilities,this.instructionsValue=n.instructions,e.setProtocolVersion?.(n.protocolVersion),await this.notifyInternal(`notifications/initialized`,void 0,!0),this.state=`connected`,n}catch(e){throw await this.close().catch(()=>{}),e}}request(e,t,n={}){return this.requestInternal(e,t,n,!1)}notify(e,t){return this.notifyInternal(e,t,!1)}setRequestHandler(e,t){return this.requestHandlers.set(e,t),()=>{this.requestHandlers.get(e)===t&&this.requestHandlers.delete(e)}}onNotification(e,t){let n=this.notificationListeners.get(e)??new Set;return this.notificationListeners.set(e,n),n.add(t),()=>{n.delete(t),n.size===0&&this.notificationListeners.delete(e)}}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}async ping(e={}){await this.request(`ping`,void 0,e)}async listTools(e={}){return await this.listAll(`tools/list`,`tools`,de,e)}async listResources(e={}){return(await this.listAll(`resources/list`,`resources`,fe,e)).map(me)}async listResourcesPage(e,t={}){let n=await this.listPage(`resources/list`,`resources`,fe,e,t);return{resources:n.items.map(me),...ge(n)}}async listResourceTemplates(e={}){return(await this.listAll(`resources/templates/list`,`resourceTemplates`,pe,e)).map(he)}async listResourceTemplatesPage(e,t={}){let n=await this.listPage(`resources/templates/list`,`resourceTemplates`,pe,e,t);return{resourceTemplates:n.items.map(he),...ge(n)}}async readResource(e,t={}){return _e(await this.request(`resources/read`,{uri:e},t))}async listPage(e,t,n,r,i){return ue(e,t,await this.request(e,r===void 0?void 0:{cursor:r},i),n)}async listAll(e,t,n,r){let i=[],a=new Set,o;for(let s=0;s<ce;s++){let s=await this.listPage(e,t,n,o,r);if(i.push(...s.items),s.nextCursor===void 0)return i;if(a.has(s.nextCursor))throw Error(`MCP ${e} returned duplicate cursor: ${s.nextCursor}`);a.add(s.nextCursor),o=s.nextCursor}throw Error(`MCP ${e} exceeded ${ce} pages`)}async callTool(e,t,n={}){return ve(await this.request(`tools/call`,{name:e,...t===void 0?{}:{arguments:t}},n))}async close(){let e=this.transport;this.transport=void 0,this.disposeTransportListeners(),this.markClosed(new y),await e?.close()}async requestInternal(e,t,n,r){let i=this.requireTransport(r);if(n.signal?.aborted)throw new ae;let a=this.nextRequestId++,o=n.onProgress?a:void 0,s=o===void 0?t:{...t,_meta:{...b(t?._meta)?t._meta:{},progressToken:o}},c={jsonrpc:`2.0`,id:a,method:e,...s===void 0?{}:{params:s}};return new Promise((t,r)=>{let s={resolve:t,reject:r,timeoutMs:n.timeoutMs??this.options.requestTimeoutMs??3e4,timer:void 0,signal:n.signal,onAbort:()=>this.cancelPending(a,new ae,e!==`initialize`,String(n.signal?.reason??`Aborted`)),cancellable:e!==`initialize`,onProgress:n.onProgress,progressToken:o};this.pending.set(a,s),o!==void 0&&this.progressRequests.set(o,a),n.signal?.addEventListener(`abort`,s.onAbort,{once:!0}),this.armTimeout(a,s),i.send(c).catch(e=>this.cancelPending(a,e,!1))})}async notifyInternal(e,t,n){await this.requireTransport(n).send({jsonrpc:`2.0`,method:e,...t===void 0?{}:{params:t}})}requireTransport(e){if(this.transport&&(this.state===`connected`||e&&this.state===`connecting`))return this.transport;throw new y(`MCP client is ${this.state}`)}handleMessage(e){if(T(e)){this.handleResponse(e);return}if(C(e)){this.handleRequest(e);return}if(w(e)){this.handleNotification(e.method,e.params);return}this.emitError(new v(_.invalidRequest,`Received invalid JSON-RPC message`))}handleResponse(e){let t=this.pending.get(e.id);if(!t){this.emitError(Error(`Received response for unknown MCP request ${String(e.id)}`));return}this.removePending(e.id,t),`error`in e?t.reject(new v(e.error.code,e.error.message,e.error.data)):t.resolve(e.result)}async handleRequest(e){let t=this.transport;if(!t)return;let n=this.requestHandlers.get(e.method);if(!n){await t.send({jsonrpc:`2.0`,id:e.id,error:{code:_.methodNotFound,message:`Method not found: ${e.method}`}}).catch(e=>this.emitError(e));return}let r=new AbortController;this.incoming.set(e.id,r);try{let i=await n(e.params,{signal:r.signal});await t.send({jsonrpc:`2.0`,id:e.id,result:i??{}})}catch(n){let r=n instanceof v?{code:n.code,message:n.message,data:n.data}:{code:_.internalError,message:x(n).message};await t.send({jsonrpc:`2.0`,id:e.id,error:r}).catch(e=>this.emitError(e))}finally{this.incoming.delete(e.id)}}handleNotification(e,t){e===`notifications/progress`?this.handleProgress(t):e===`notifications/cancelled`&&this.handleCancelled(t);for(let n of this.notificationListeners.get(e)??[])try{n(t)}catch(e){this.emitError(e)}}handleProgress(e){if(!b(e)||!S(e.progressToken)||typeof e.progress!=`number`)return;let t=this.progressRequests.get(e.progressToken),n=t===void 0?void 0:this.pending.get(t);if(!(t===void 0||!n)){this.armTimeout(t,n);try{n.onProgress?.(e)}catch(e){this.emitError(e)}}}handleCancelled(e){b(e)&&S(e.requestId)&&this.incoming.get(e.requestId)?.abort(e.reason)}armTimeout(e,t){t.timer&&clearTimeout(t.timer),!(!Number.isFinite(t.timeoutMs)||t.timeoutMs<=0)&&(t.timer=setTimeout(()=>{this.cancelPending(e,new ie(t.timeoutMs),t.cancellable,`Request timed out`)},t.timeoutMs))}cancelPending(e,t,n,r){let i=this.pending.get(e);i&&(this.removePending(e,i),i.reject(t),n&&this.transport&&this.transport.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:e,...r?{reason:r}:{}}}).catch(e=>this.emitError(e)))}removePending(e,t){this.pending.delete(e),t.timer&&clearTimeout(t.timer),t.progressToken!==void 0&&this.progressRequests.delete(t.progressToken),t.signal?.removeEventListener(`abort`,t.onAbort)}rejectPending(e){for(let[t,n]of this.pending)this.removePending(t,n),n.reject(e)}handleTransportClose(){this.markClosed(new y)}markClosed(e){let t=this.state===`closed`;this.state=`closed`,this.rejectPending(e);for(let t of this.incoming.values())t.abort(e);if(this.incoming.clear(),!t)for(let e of[...this.closeListeners])try{e()}catch(e){this.emitError(e)}}emitError(e){let t=x(e);for(let e of this.errorListeners)e(t)}disposeTransportListeners(){for(let e of this.disposers.splice(0))e()}};function be(e){switch(e.type){case`text`:return{type:`text`,text:e.text};case`image`:return{type:`image`,data:e.data,mimeType:e.mimeType};case`audio`:return{type:`text`,text:`[audio ${e.mimeType} omitted]`};case`resource_link`:return{type:`text`,text:`${e.name}: ${e.uri}`};case`resource`:{let t=e.resource;return`text`in t?{type:`text`,text:t.text}:t.mimeType?.startsWith(`image/`)?{type:`image`,data:t.blob,mimeType:t.mimeType}:{type:`text`,text:`[binary resource ${t.uri} (${t.mimeType??`unknown type`}) omitted]`}}default:return{type:`text`,text:`[unsupported MCP content ${e.type}]`}}}function xe(e){let t=(e.content??[]).map(be);return t.length===0&&e.structuredContent!==void 0&&t.push({type:`text`,text:JSON.stringify(e.structuredContent,null,2)}),t}var Se=n(((e,n)=>{n.exports=o,o.sync=s;var r=t(`fs`);function i(e,t){var n=t.pathExt===void 0?process.env.PATHEXT:t.pathExt;if(!n||(n=n.split(`;`),n.indexOf(``)!==-1))return!0;for(var r=0;r<n.length;r++){var i=n[r].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}function a(e,t,n){return!e.isSymbolicLink()&&!e.isFile()?!1:i(t,n)}function o(e,t,n){r.stat(e,function(r,i){n(r,!r&&a(i,e,t))})}function s(e,t){return a(r.statSync(e),e,t)}})),Ce=n(((e,n)=>{n.exports=i,i.sync=a;var r=t(`fs`);function i(e,t,n){r.stat(e,function(e,r){n(e,!e&&o(r,t))})}function a(e,t){return o(r.statSync(e),t)}function o(e,t){return e.isFile()&&s(e,t)}function s(e,t){var n=e.mode,r=e.uid,i=e.gid,a=t.uid===void 0?process.getuid&&process.getuid():t.uid,o=t.gid===void 0?process.getgid&&process.getgid():t.gid,s=64,c=8,l=1,u=s|c;return n&l||n&c&&i===o||n&s&&r===a||n&u&&a===0}})),we=n(((e,n)=>{t(`fs`);var r=process.platform===`win32`||global.TESTING_WINDOWS?Se():Ce();n.exports=i,i.sync=a;function i(e,t,n){if(typeof t==`function`&&(n=t,t={}),!n){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(n,r){i(e,t||{},function(e,t){e?r(e):n(t)})})}r(e,t||{},function(e,r){e&&(e.code===`EACCES`||t&&t.ignoreErrors)&&(e=null,r=!1),n(e,r)})}function a(e,t){try{return r.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code===`EACCES`)return!1;throw e}}})),Te=n(((e,n)=>{let r=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,i=t(`path`),a=r?`;`:`:`,o=we(),s=e=>Object.assign(Error(`not found: ${e}`),{code:`ENOENT`}),c=(e,t)=>{let n=t.colon||a,i=e.match(/\//)||r&&e.match(/\\/)?[``]:[...r?[process.cwd()]:[],...(t.path||process.env.PATH||``).split(n)],o=r?t.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`:``,s=r?o.split(n):[``];return r&&e.indexOf(`.`)!==-1&&s[0]!==``&&s.unshift(``),{pathEnv:i,pathExt:s,pathExtExe:o}},l=(e,t,n)=>{typeof t==`function`&&(n=t,t={}),t||={};let{pathEnv:r,pathExt:a,pathExtExe:l}=c(e,t),u=[],d=n=>new Promise((a,o)=>{if(n===r.length)return t.all&&u.length?a(u):o(s(e));let c=r[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=i.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;a(f(p,n,0))}),f=(e,n,r)=>new Promise((i,s)=>{if(r===a.length)return i(d(n+1));let c=a[r];o(e+c,{pathExt:l},(a,o)=>{if(!a&&o)if(t.all)u.push(e+c);else return i(e+c);return i(f(e,n,r+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};n.exports=l,l.sync=(e,t)=>{t||={};let{pathEnv:n,pathExt:r,pathExtExe:a}=c(e,t),l=[];for(let s=0;s<n.length;s++){let c=n[s],u=/^".*"$/.test(c)?c.slice(1,-1):c,d=i.join(u,e),f=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<r.length;e++){let n=f+r[e];try{if(o.sync(n,{pathExt:a}))if(t.all)l.push(n);else return n}catch{}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw s(e)}})),Ee=n(((e,t)=>{let n=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)===`win32`?Object.keys(t).reverse().find(e=>e.toUpperCase()===`PATH`)||`Path`:`PATH`};t.exports=n,t.exports.default=n})),De=n(((e,n)=>{let r=t(`path`),i=Te(),a=Ee();function o(e,t){let n=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,c=s&&process.chdir!==void 0&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch{}let l;try{l=i.sync(e.command,{path:n[a({env:n})],pathExt:t?r.delimiter:void 0})}catch{}finally{c&&process.chdir(o)}return l&&=r.resolve(s?e.options.cwd:``,l),l}function s(e){return o(e)||o(e,!0)}n.exports=s})),Oe=n(((e,t)=>{let n=/([()\][%!^"`<>&|;, *?])/g;function r(e){return e=e.replace(n,`^$1`),e}function i(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`),e=e.replace(/(?=(\\+?)?)\1$/,`$1$1`),e=`"${e}"`,e=e.replace(n,`^$1`),t&&(e=e.replace(n,`^$1`)),e}t.exports.command=r,t.exports.argument=i})),ke=n(((e,t)=>{t.exports=/^#!(.*)/})),Ae=n(((e,t)=>{let n=ke();t.exports=(e=``)=>{let t=e.match(n);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,``).split(` `),a=r.split(`/`).pop();return a===`env`?i:i?`${a} ${i}`:a}})),je=n(((e,n)=>{let r=t(`fs`),i=Ae();function a(e){let t=Buffer.alloc(150),n;try{n=r.openSync(e,`r`),r.readSync(n,t,0,150,0),r.closeSync(n)}catch{}return i(t.toString())}n.exports=a})),Me=n(((e,n)=>{let r=t(`path`),i=De(),a=Oe(),o=je(),s=process.platform===`win32`,c=/\.(?:com|exe)$/i,l=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(e){e.file=i(e);let t=e.file&&o(e.file);return t?(e.args.unshift(e.file),e.command=t,i(e)):e.file}function d(e){if(!s)return e;let t=u(e),n=!c.test(t);if(e.options.forceShell||n){let n=l.test(t);e.command=r.normalize(e.command),e.command=a.command(e.command),e.args=e.args.map(e=>a.argument(e,n)),e.args=[`/d`,`/s`,`/c`,`"${[e.command].concat(e.args).join(` `)}"`],e.command=process.env.comspec||`cmd.exe`,e.options.windowsVerbatimArguments=!0}return e}function f(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);let r={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?r:d(r)}n.exports=f})),Ne=n(((e,t)=>{let n=process.platform===`win32`;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:`ENOENT`,errno:`ENOENT`,syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function i(e,t){if(!n)return;let r=e.emit;e.emit=function(n,i){if(n===`exit`){let n=a(i,t);if(n)return r.call(e,`error`,n)}return r.apply(e,arguments)}}function a(e,t){return n&&e===1&&!t.file?r(t.original,`spawn`):null}function o(e,t){return n&&e===1&&!t.file?r(t.original,`spawnSync`):null}t.exports={hookChildProcess:i,verifyENOENT:a,verifyENOENTSync:o,notFoundError:r}})),Pe=n(((e,n)=>{let r=t(`child_process`),i=Me(),a=Ne();function o(e,t,n){let o=i(e,t,n),s=r.spawn(o.command,o.args,o.options);return a.hookChildProcess(s,o),s}function s(e,t,n){let o=i(e,t,n),s=r.spawnSync(o.command,o.args,o.options);return s.error=s.error||a.verifyENOENTSync(s.status,o),s}n.exports=o,n.exports.spawn=o,n.exports.sync=s,n.exports._parse=i,n.exports._enoent=a})),Fe=class{messageListeners=new Set;errorListeners=new Set;closeListeners=new Set;closeEmitted=!1;onMessage(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}emitMessage(e){for(let t of this.messageListeners)t(e)}emitError(e){let t=x(e);for(let e of this.errorListeners)e(t)}emitClose(){if(!this.closeEmitted){this.closeEmitted=!0;for(let e of this.closeListeners)e()}}},Ie=e(Pe(),1);const O=o.platform!==`win32`,k=new Set;let Le=!1;function A(e,t){let n=e.pid;if(o.platform===`win32`&&n!==void 0){if(e.exitCode!==null)return;a(`taskkill`,[`/pid`,String(n),`/T`,`/F`],{stdio:`ignore`,windowsHide:!0}).on(`error`,()=>{});return}if(O&&n!==void 0)try{o.kill(-n,t);return}catch{}try{e.kill(t)}catch{}}function Re(){Le||(Le=!0,o.once(`exit`,()=>{for(let e of k)try{o.kill(-e,`SIGTERM`)}catch{}}))}var ze=class extends Fe{options;child;stdoutBuffer=Buffer.alloc(0);stderrBuffer=Buffer.alloc(0);started=!1;closed=!1;constructor(e){super(),this.options=Object.freeze({...e,args:e.args?[...e.args]:void 0})}get pid(){return this.child?.pid}get stderr(){return this.stderrBuffer.toString(`utf8`)}async start(){if(this.started)throw Error(`MCP stdio transport already started`);if(this.closed)throw new y;this.started=!0;let e=this.options.inheritEnv===!1?{...this.options.env}:{...o.env,...this.options.env},t=(0,Ie.default)(this.options.command,this.options.args??[],{cwd:this.options.cwd,env:e,stdio:[`pipe`,`pipe`,this.options.stderr===`inherit`?`inherit`:`pipe`],windowsHide:!0,detached:O});this.child=t;let n=t.pid;O&&n!==void 0&&(Re(),k.add(n),t.once(`exit`,()=>k.delete(n))),t.stdout?.on(`data`,e=>this.handleStdout(e)),t.stdout?.on(`error`,e=>this.emitError(e)),t.stdin?.on(`error`,e=>{this.closed||this.emitError(e)}),t.stderr?.on(`data`,e=>this.handleStderr(e)),t.stderr?.on(`error`,e=>this.emitError(e)),t.on(`close`,()=>{this.child=void 0,this.stdoutBuffer.toString(`utf8`).trim()&&this.emitError(Error(`MCP stdio server closed with an incomplete JSON-RPC message`)),this.stdoutBuffer=Buffer.alloc(0),this.emitClose()}),await new Promise((e,n)=>{let r=()=>{t.off(`error`,i),e()},i=e=>{t.off(`spawn`,r),n(e)};t.once(`spawn`,r),t.once(`error`,i)}),t.on(`error`,e=>{this.closed||this.emitError(e)})}async send(e){let t=this.child?.stdin;if(!this.started||this.closed||!t?.writable)throw new y;let n=`${JSON.stringify(e)}\n`;await new Promise((e,r)=>{t.write(n,t=>t?r(t):e())})}async close(){if(this.closed)return;this.closed=!0;let e=this.child;if(!e){this.emitClose();return}if(e.exitCode!==null||e.signalCode!==null){e.stdin?.end();return}let t=this.options.closeTimeoutMs??2e3;await new Promise(n=>{let r=[];e.once(`close`,()=>{for(let e of r)clearTimeout(e);A(e,`SIGTERM`),n()});let i=Math.min(500,t);r.push(setTimeout(()=>A(e,`SIGTERM`),i)),r.push(setTimeout(()=>A(e,`SIGKILL`),i+t)),e.stdin?.end()})}handleStdout(e){this.stdoutBuffer=Buffer.concat([this.stdoutBuffer,Buffer.isBuffer(e)?e:Buffer.from(e)]);let t=this.options.maxMessageBytes??16777216;for(;;){let e=this.stdoutBuffer.indexOf(10);if(e<0){this.stdoutBuffer.length>t&&(this.stdoutBuffer=Buffer.alloc(0),this.emitError(Error(`MCP stdio message exceeds ${t} bytes`)));return}let n=this.stdoutBuffer.subarray(0,e);if(this.stdoutBuffer=this.stdoutBuffer.subarray(e+1),n.length>t){this.emitError(Error(`MCP stdio message exceeds ${t} bytes`));continue}let r=n.toString(`utf8`).replace(/\r$/,``);if(r.trim())try{this.emitMessage(E(JSON.parse(r)))}catch(e){this.emitError(e)}}}handleStderr(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e),n=this.options.maxStderrBytes??65536;this.stderrBuffer=Buffer.concat([this.stderrBuffer,t]),this.stderrBuffer.length>n&&(this.stderrBuffer=this.stderrBuffer.subarray(-n)),this.options.onStderr?.(t.toString(`utf8`))}};async function Be(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a,o,s=[],c=0,l=t.maxEventBytes??16777216,u=()=>{if(s.length===0){a=void 0,o=void 0;return}let e=s.join(`
3
- `);t.onEvent({...a?{event:a}:{},data:e,...o?{id:o}:{}}),a=void 0,o=void 0,s=[],c=0},d=e=>{let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n===``){u();return}if(n.startsWith(`:`))return;let r=n.indexOf(`:`),i=r<0?n:n.slice(0,r),d=r<0?``:n.slice(r+1);if(d.startsWith(` `)&&(d=d.slice(1)),i===`data`){if(c+=Buffer.byteLength(d)+ +(s.length>0),c>l)throw Error(`MCP SSE event exceeds ${l} bytes`);s.push(d)}else i===`event`?a=d:i===`id`&&!d.includes(`\0`)?(o=d,t.onId?.(d)):i===`retry`&&/^\d+$/.test(d)&&t.onRetry?.(Number(d))};try{for(;;){let{done:e,value:t}=await n.read();if(e)break;i+=r.decode(t,{stream:!0});let a=i.indexOf(`
4
- `);for(;a>=0;)d(i.slice(0,a)),i=i.slice(a+1),a=i.indexOf(`
5
- `);if(Buffer.byteLength(i)>l)throw Error(`MCP SSE event exceeds ${l} bytes`)}i+=r.decode(),i&&d(i),u()}finally{n.releaseLock()}}var j=class extends Error{status;body;constructor(e,t,n=``){super(t),this.name=`McpHttpError`,this.status=e,this.body=n}},Ve=class extends j{wwwAuthenticate;constructor(e,t=``){super(401,`MCP server requires authentication`,t),this.name=`McpAuthRequiredError`,this.wwwAuthenticate=e.headers.get(`www-authenticate`)}},He=class extends j{constructor(e=``){super(404,`MCP session expired`,e),this.name=`McpSessionExpiredError`}};function Ue(e){return e.headers.get(`content-type`)?.split(`;`,1)[0]?.trim().toLowerCase()}function We(e){return e.status===401||e.status===403&&/(?:^|[\s,])error="?insufficient_scope"?/i.test(e.headers.get(`www-authenticate`)??``)}function Ge(e){return e===408||e===429||e>=500}function M(e){return e.body?.cancel().catch(()=>{})??Promise.resolve()}function Ke(e,t){let n=t.trim(),r=n.length>500?`${n.slice(0,497)}...`:n;return`MCP HTTP request failed with status ${e}${r?`: ${r}`:``}`}var qe=class extends Fe{url;options;fetch;controller=new AbortController;started=!1;closed=!1;sessionIdValue;protocolVersion;getStreamStarted=!1;constructor(e){super(),this.options=Object.freeze({...e,headers:e.headers?{...e.headers}:void 0}),this.url=new URL(e.url);let t=e.fetch??globalThis.fetch;this.fetch=(e,n)=>t(e,n)}get sessionId(){return this.sessionIdValue}async start(){if(this.started)throw Error(`MCP Streamable HTTP transport already started`);if(this.closed)throw new y;this.started=!0}setProtocolVersion(e){this.protocolVersion=e}async send(e){if(!this.started||this.closed)throw new y;let t=await this.authorizedFetch(`POST`,{headers:{accept:`application/json, text/event-stream`,"content-type":`application/json`},body:JSON.stringify(e)});if(await this.checkResponse(t),this.captureSession(t),!C(e)){await M(t),`method`in e&&e.method===`notifications/initialized`&&this.startGetStream();return}if(t.status===202||t.status===204)throw new j(t.status,`MCP server accepted request ${e.method} without a response`);let n=Ue(t);if(n===`application/json`){let e=await t.json();for(let t of Array.isArray(e)?e:[e])this.emitMessage(E(t));return}if(n===`text/event-stream`&&t.body){this.consumeResponseStream(t.body,e.id);return}throw await M(t),new j(t.status,`Unsupported MCP response content type: ${n??`missing`}`)}async close(){if(!this.closed){if(this.closed=!0,this.controller.abort(),this.started&&this.sessionIdValue){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let{headers:t}=await this.headers();await this.fetch(this.url,{method:`DELETE`,headers:t,signal:e.signal}).then(M).catch(()=>void 0)}catch{}finally{clearTimeout(t)}}this.emitClose()}}async authorizedFetch(e,t){let n=this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);for(let r=0;;r++){let{headers:i,token:a}=await this.headers(t.headers),o=await this.fetch(this.url,{method:e,headers:i,body:t.body,signal:this.controller.signal});if(r>0||!n||!We(o))return o;try{await n({response:o,serverUrl:this.url,fetch:this.fetch,token:a})}finally{await M(o)}}}async headers(e={}){let t=new Headers(this.options.headers);for(let[n,r]of Object.entries(e))t.set(n,r);this.sessionIdValue&&t.set(`Mcp-Session-Id`,this.sessionIdValue),this.protocolVersion&&t.set(`MCP-Protocol-Version`,this.protocolVersion);let n=await this.options.authProvider?.token();return n&&t.set(`Authorization`,`Bearer ${n}`),{headers:t,...n?{token:n}:{}}}captureSession(e){let t=e.headers.get(`mcp-session-id`);t&&(this.sessionIdValue=t)}async checkResponse(e){if(e.ok)return;let t=(await e.text().catch(()=>``)).slice(0,8192);throw e.status===401?new Ve(e,t):e.status===404&&this.sessionIdValue?new He(t):new j(e.status,Ke(e.status,t),t)}async consumeSse(e,t,n){await Be(e,{maxEventBytes:this.options.maxMessageBytes??16777216,onId:e=>{t.lastEventId=e},onRetry:e=>{t.retryMs=e},onEvent:e=>{if(t.received=!0,!e.data.trim()||e.event!==void 0&&e.event!==`message`)return;let r;try{r=E(JSON.parse(e.data))}catch(e){this.emitError(e);return}n?.(r),this.emitMessage(r)}})}async consumeResponseStream(e,t){let n={lastEventId:void 0,retryMs:void 0,received:!1},r=!1,i=e=>{T(e)&&e.id===t&&(r=!0)},a=e,o;for(let e=0;;){if(a)try{await this.consumeSse(a,n,i),o=void 0}catch(e){o=e}if(r||this.closed)return;if(o!==void 0&&!this.isRetryable(o)||n.lastEventId===void 0||e>=this.maxRetries())break;if(n.received&&(e=0),n.received=!1,!await this.sleep(this.reconnectDelay(e++,n.retryMs)))return;try{a=await this.openSseStream(n.lastEventId)}catch(e){if(o=e,!this.isRetryable(e))break;a=void 0}}if(this.closed)return;let s=o===void 0?`stream ended without a response`:x(o).message;this.emitMessage({jsonrpc:`2.0`,id:t,error:{code:_.internalError,message:`MCP response stream failed: ${s}`}})}startGetStream(){this.options.openGetStream===!1||this.getStreamStarted||this.closed||(this.getStreamStarted=!0,this.runGetStream())}async runGetStream(){let e={lastEventId:void 0,retryMs:void 0,received:!1};for(let t=0;!this.closed;){try{let n=await this.openSseStream(e.lastEventId);if(!n)return;let r=Date.now();await this.consumeSse(n,e),(e.received||Date.now()-r>this.maxDelay())&&(t=0)}catch(e){if(this.closed)return;if(!this.isRetryable(e)){this.emitError(e);return}}if(e.received=!1,t>=this.maxRetries()){this.emitError(Error(`MCP server-to-client stream dropped and could not be reopened`));return}if(!await this.sleep(this.reconnectDelay(t++,e.retryMs)))return}}async openSseStream(e){let t=await this.authorizedFetch(`GET`,{headers:{accept:`text/event-stream`,...e===void 0?{}:{"last-event-id":e}}});if(t.status===405){await M(t);return}await this.checkResponse(t),this.captureSession(t);let n=Ue(t);if(n!==`text/event-stream`||!t.body)throw await M(t),new j(t.status,`Unsupported MCP GET response content type: ${n??`missing`}`);return t.body}isRetryable(e){if(e instanceof j)return Ge(e.status);if(e instanceof TypeError)return!0;let t=e?.code;return typeof t==`string`&&(t.startsWith(`E`)||t.startsWith(`UND_ERR`))}reconnectDelay(e,t){if(t!==void 0)return t;let n=this.options.reconnect?.initialDelayMs??1e3;return Math.min(n*2**e,this.maxDelay())}maxDelay(){return this.options.reconnect?.maxDelayMs??3e4}maxRetries(){return this.options.reconnect?.maxRetries??5}sleep(e){let t=this.controller.signal;return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t.removeEventListener(`abort`,r),n(!0)},e);i.unref?.(),t.addEventListener(`abort`,r,{once:!0})})}};const Je=6e4;function N(e){return typeof e?.timeout==`number`&&e.timeout>0?e.timeout*1e3:Je}function Ye(e,{cwd:t,env:n,authProvider:r,fetch:a}){return typeof e.url==`string`&&e.type!==`stdio`?new qe({url:e.url,...e.headers?{headers:e.headers}:{},...r?{authProvider:r}:{},...a?{fetch:a}:{}}):new ze({command:e.command,args:e.args??[],cwd:e.cwd?i.resolve(t??process.cwd(),e.cwd):t,...n?{env:n,inheritEnv:!1}:{env:e.env??{}}})}async function Xe({name:e,config:t,cwd:n,env:r,clientName:i,clientVersion:a=`1.0.0`,authProvider:o,fetch:s}){let c=Ye(t,{cwd:n,env:r,authProvider:o,fetch:s}),l=new ye({name:i,version:a,requestTimeoutMs:N(t)});try{return await l.connect(c),{name:e,config:t,client:l,tools:await l.listTools(),instructions:l.instructions,close:()=>l.close()}}catch(e){await l.close().catch(()=>{});let t=c instanceof ze?c.stderr.trim():``;throw t&&e instanceof Error&&(e.message=`${e.message}\n${t.slice(-2e3)}`),e}}function Ze(e,t){return`mcp__${e}__${t}`.replace(/[^A-Za-z0-9_]/g,`_`)}function Qe(e,t,n){let i=r(`sha256`).update(`${t}\0${n}`).digest(`hex`).slice(0,8);return`${e.slice(0,64-i.length-1)}_${i}`}function $e(e,{reserved:t=new Set}={}){let n=e.map(({server:e,tool:t})=>Ze(e,t)),r=new Map;for(let[t,i]of n.entries()){let{server:n,tool:a}=e[t],o=`${n}\0${a}`;r.has(i)||r.set(i,new Set),r.get(i).add(o)}return n.map((n,i)=>{let{server:a,tool:o}=e[i],s=r.get(n).size>1;return n.length<=64&&!s&&!t.has(n)?n:Qe(n,a,o)})}function et(e){return`mcp_${e}`}const tt=48*1024;function P(e){if(e.length<=65536)return e;let t=e.length-tt-16384;return`${e.slice(0,tt)}\n[... ${t} characters truncated ...]\n${e.slice(-16384)}`}const nt=e=>e.some(e=>e.type===`text`&&e.text.trim()!==``);function rt(e,t,n,{limitText:r=P}={}){let i=xe(n).map(e=>e.type===`text`?{type:`text`,text:r(e.text)}:e);n.isError&&!nt(i)&&i.push({type:`text`,text:`MCP tool ${e}/${t} returned an error`});let{_meta:a,...o}=n;return{content:i,details:{server:e,tool:t},structuredContent:o,...n.isError?{isError:!0}:{}}}function it(e,t,n,{limitText:r=P}={}){return{content:[{type:`text`,text:`MCP tool error: ${r(n instanceof Error?n.message:String(n))}`}],details:{server:e,tool:t},isError:!0}}function at(e){return e.ok?`Authorization complete. You may close this window.`:e.details?`${e.message}\n\n${e.details}`:e.message}var F=class e{redirectUrl;server;path;timeoutMs;renderPage;pending=new Map;constructor(e,t,n,r,i){this.server=e,this.redirectUrl=t,this.path=n,this.timeoutMs=r,this.renderPage=i}static async listen(t={}){let n=t.host??`127.0.0.1`,r=t.redirectHost??n,i=t.path??`/callback`,a,o=s((e,t)=>a?.handle(e.url??`/`,t));await new Promise((e,r)=>{o.once(`error`,r),o.listen(t.port??0,n,()=>{o.off(`error`,r),e()})});let c=o.address();if(!c||typeof c==`string`)throw Error(`OAuth callback server did not bind to TCP`);return a=new e(o,`http://${r.includes(`:`)?`[${r}]`:r}:${c.port}${i}`,i,t.timeoutMs??5*6e4,t.renderPage),a}waitForCallback(e){if(this.pending.has(e))throw Error(`OAuth state is already pending`);return new Promise((t,n)=>{let r=setTimeout(()=>{this.pending.delete(e),n(Error(`OAuth callback timed out`))},this.timeoutMs);this.pending.set(e,{resolve:t,reject:n,timer:r})})}async close(){for(let e of this.pending.values())clearTimeout(e.timer),e.reject(Error(`OAuth callback server closed`));this.pending.clear(),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())})}reply(e,t,n){this.renderPage?(e.writeHead(t,{"content-type":`text/html; charset=utf-8`,"cache-control":`no-store`}),e.end(this.renderPage(n))):e.writeHead(t,{"content-type":`text/plain; charset=utf-8`}).end(at(n))}handle(e,t){let n=new URL(e,this.redirectUrl);if(n.pathname!==this.path){this.reply(t,404,{ok:!1,message:`Not found`});return}let r=n.searchParams.get(`state`),i=r?this.pending.get(r):void 0;if(!r||!i){this.reply(t,400,{ok:!1,message:`Invalid or expired OAuth state`});return}clearTimeout(i.timer),this.pending.delete(r);let a=n.searchParams.get(`error`);if(a){let e=n.searchParams.get(`error_description`)??a;i.reject(Error(e)),this.reply(t,200,{ok:!1,message:`Authorization failed. You may close this window.`,details:e});return}let o=n.searchParams.get(`code`);if(!o){i.reject(Error(`OAuth callback did not include an authorization code`)),this.reply(t,400,{ok:!1,message:`Missing authorization code`});return}let s=n.searchParams.get(`iss`);i.resolve({code:o,state:r,...s?{iss:s}:{}}),this.reply(t,200,{ok:!0})}},I=class extends Error{code;errorUri;constructor(e,t,n){super(t||e),this.name=`OAuthError`,this.code=e,this.errorUri=n}},ot=class extends Error{expected;received;constructor(e,t){super(`OAuth issuer mismatch: expected ${JSON.stringify(e)}, received ${t===void 0?`none`:JSON.stringify(t)}`),this.name=`OAuthIssuerMismatchError`,this.expected=e,this.received=t}},st=class extends Error{endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name=`OAuthInsecureEndpointError`,this.endpoint=e}},ct=class extends Error{status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name=`OAuthRegistrationError`,this.status=e,this.body=t}},L=class extends Error{constructor(){super(`MCP OAuth authorization requires user interaction`),this.name=`McpOAuthAuthorizationRequiredError`}};function R(e,t){if(!b(e))throw Error(`Invalid ${t}`);return e}function z(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function B(e,t){if(typeof e!=`string`||e.length===0)throw Error(`Invalid ${t}`);return e}function V(e){return e==null||e===``}function H(e,t){if(!V(e))return B(e,t)}function U(e,t){if(e!=null){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`Invalid ${t}`);return[...e]}}function W(e,t){let n=B(e,t);if(!URL.canParse(n))throw Error(`Invalid ${t}`);let r=new URL(n);if([`javascript:`,`data:`,`vbscript:`].includes(r.protocol))throw Error(`Invalid ${t}`);return n}function lt(e,t){return V(e)?void 0:W(e,t)}function ut(e){let t=R(e,`OAuth protected resource metadata`);return z({...t,resource:W(t.resource,`OAuth protected resource metadata resource`),authorization_servers:U(t.authorization_servers,`authorization_servers`)?.map(e=>W(e,`authorization server URL`)),scopes_supported:U(t.scopes_supported,`scopes_supported`)})}function dt(e){let t=R(e,`authorization server metadata`),n=U(t.response_types_supported,`response_types_supported`);if(!n)throw Error(`Invalid response_types_supported`);return z({...t,issuer:W(t.issuer,`authorization server issuer`),authorization_endpoint:W(t.authorization_endpoint,`authorization endpoint`),token_endpoint:W(t.token_endpoint,`token endpoint`),registration_endpoint:lt(t.registration_endpoint,`registration endpoint`),scopes_supported:U(t.scopes_supported,`scopes_supported`),response_types_supported:n,grant_types_supported:U(t.grant_types_supported,`grant_types_supported`),token_endpoint_auth_methods_supported:U(t.token_endpoint_auth_methods_supported,`token_endpoint_auth_methods_supported`),code_challenge_methods_supported:U(t.code_challenge_methods_supported,`code_challenge_methods_supported`),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported==`boolean`?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported==`boolean`?t.authorization_response_iss_parameter_supported:void 0})}function ft(e){let t=R(e,`OAuth token response`),n=V(t.expires_in)?void 0:Number(t.expires_in);if(n!==void 0&&!Number.isFinite(n))throw Error(`Invalid expires_in`);return z({access_token:B(t.access_token,`access_token`),token_type:B(t.token_type,`token_type`),expires_in:n,scope:H(t.scope,`scope`),refresh_token:H(t.refresh_token,`refresh_token`),id_token:H(t.id_token,`id_token`)})}function pt(e){let t=R(e,`OAuth client registration response`);return z({...t,client_id:B(t.client_id,`client_id`),client_secret:H(t.client_secret,`client_secret`),client_id_issued_at:typeof t.client_id_issued_at==`number`?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at==`number`?t.client_secret_expires_at:void 0,redirect_uris:U(t.redirect_uris,`redirect_uris`)??[]})}function G(e){e?.body?.cancel().catch(()=>{})}function K(e){return e>=400&&e<500||e===502}function mt(e){return e.endsWith(`/`)?e.slice(0,-1):e}function q(e,t){let n=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,`i`));return n?.[1]||n?.[2]||void 0}function ht(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!==`bearer`&&t!==`dpop`)return{};let n=q(e,`resource_metadata`),r;if(n)try{r=new URL(n)}catch{}return{resourceMetadataUrl:r,scope:q(e,`scope`),error:q(e,`error`),errorDescription:q(e,`error_description`)}}async function J(e,t,n){return t(e,{headers:{Accept:`application/json`,"MCP-Protocol-Version":n}})}async function gt(e,t={}){let n=new URL(e),r=t.fetch??globalThis.fetch,i=t.protocolVersion??`2025-11-25`,a=await J(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${mt(n.pathname)}`,n.origin),r,i);if(!t.resourceMetadataUrl&&n.pathname!==`/`&&K(a.status)&&(G(a),a=await J(new URL(`/.well-known/oauth-protected-resource`,n.origin),r,i)),!a.ok)throw G(a),Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return ut(await a.json())}function _t(e){let t=new URL(e),n=mt(t.pathname),r=[{url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:`oidc`}];return n&&r.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function vt(e,t={}){let n=t.fetch??globalThis.fetch;for(let{url:r}of _t(e)){let i=await J(r,n,t.protocolVersion??`2025-11-25`);if(!i.ok){if(G(i),K(i.status))continue;throw Error(`HTTP ${i.status} loading authorization server metadata from ${r}`)}let a=dt(await i.json());if(!t.skipIssuerValidation){let t=String(e),n=e=>e.endsWith(`/`)?e.slice(0,-1):e;if(n(a.issuer)!==n(t))throw new ot(t,a.issuer)}return a}}async function yt(e,t={}){let n;try{n=await gt(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch})}catch(e){if(e instanceof TypeError)throw e}if(t.authorizationServerMetadataUrl){let e=t.authorizationServerMetadataUrl,r=await J(e,t.fetch??globalThis.fetch,oe);if(!r.ok)throw G(r),Error(`HTTP ${r.status} loading authorization server metadata from ${e}`);let i=dt(await r.json());return{authorizationServerUrl:i.issuer,authorizationServerMetadata:i,resourceMetadata:n}}let r=n?.authorization_servers?.[0]??String(new URL(`/`,e));return{authorizationServerUrl:r,authorizationServerMetadata:await vt(r,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation}),resourceMetadata:n}}function bt(e){let t=new URL(e);return t.hash=``,t}function xt(e,t){if(!t)return;let n=bt(e),r=new URL(t.resource);if(n.origin!==r.origin)throw Error(`Protected resource ${t.resource} does not match MCP server ${n}`);let i=n.pathname.endsWith(`/`)?n.pathname:`${n.pathname}/`,a=r.pathname.endsWith(`/`)?r.pathname:`${r.pathname}/`;if(!i.startsWith(a))throw Error(`Protected resource ${t.resource} does not match MCP server ${n}`);return t.resource}function St(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}function Ct(e){let t=new URL(e);if(t.protocol!==`https:`&&!St(t.hostname))throw new st(t.href);return t}function wt(e,t){let n=`token_endpoint_auth_method`in e?e.token_endpoint_auth_method:void 0;return n&&[`client_secret_basic`,`client_secret_post`,`none`].includes(n)&&(t.length===0||t.includes(n))?n:t.length===0?e.client_secret?`client_secret_basic`:`none`:e.client_secret&&t.includes(`client_secret_basic`)?`client_secret_basic`:e.client_secret&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:e.client_secret?`client_secret_post`:`none`}function Tt(e,t,n,r){if(e===`client_secret_basic`){if(!t.client_secret)throw Error(`client_secret_basic requires a client secret`);n.set(`Authorization`,`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString(`base64`)}`)}else r.set(`client_id`,t.client_id),e===`client_secret_post`&&t.client_secret&&r.set(`client_secret`,t.client_secret)}async function Et(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString(`base64url`),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(n).toString(`base64url`)}}async function Dt(e,t){let n=t.metadata;if(n&&!n.response_types_supported.includes(`code`))throw Error(`Authorization server does not support authorization codes`);if(n?.code_challenge_methods_supported&&!n.code_challenge_methods_supported.includes(`S256`))throw Error(`Authorization server does not support PKCE S256`);let r=new URL(n?.authorization_endpoint??new URL(`/authorize`,e)),{verifier:i,challenge:a}=await Et();return r.searchParams.set(`response_type`,`code`),r.searchParams.set(`client_id`,t.clientInformation.client_id),r.searchParams.set(`code_challenge`,a),r.searchParams.set(`code_challenge_method`,`S256`),r.searchParams.set(`redirect_uri`,String(t.redirectUrl)),t.state&&r.searchParams.set(`state`,t.state),t.scope&&r.searchParams.set(`scope`,t.scope),t.scope?.split(/\s+/).includes(`offline_access`)&&r.searchParams.set(`prompt`,`consent`),t.resource&&r.searchParams.set(`resource`,t.resource),{authorizationUrl:r,codeVerifier:i}}async function Ot(e,t,n){let r=Ct(t.metadata?.token_endpoint??new URL(`/token`,e)),i=new Headers({Accept:`application/json`,"content-type":`application/x-www-form-urlencoded`});t.resource&&n.set(`resource`,t.resource),t.addClientAuthentication?await t.addClientAuthentication(i,n,r,t.metadata):Tt(wt(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,i,n);let a=await(t.fetch??globalThis.fetch)(r,{method:`POST`,headers:i,body:n}),o=await a.text(),s;try{s=JSON.parse(o)}catch{}if(b(s)&&typeof s.error==`string`)throw new I(s.error,typeof s.error_description==`string`?s.error_description:s.error,typeof s.error_uri==`string`?s.error_uri:void 0);if(!a.ok)throw new I(`server_error`,`HTTP ${a.status}: ${o}`);return ft(s)}async function kt(e,t){let n=t.metadata?.registration_endpoint;if(t.metadata&&!n)throw Error(`Authorization server does not support dynamic client registration`);let r=await(t.fetch??globalThis.fetch)(new URL(n??new URL(`/register`,e)),{method:`POST`,headers:{Accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({...t.clientMetadata,...t.scope?{scope:t.scope}:{}})});if(!r.ok)throw new ct(r.status,await r.text());return pt(await r.json())}async function At(e,t){return Ot(e,t,new URLSearchParams({grant_type:`authorization_code`,code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}async function jt(e,t){let n=await Ot(e,t,new URLSearchParams({grant_type:`refresh_token`,refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...n}}function Mt(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}function Nt(e,t){if(!t)return;let n=[e,t].flatMap(e=>e?.split(/\s+/).filter(Boolean)??[]);return[...new Set(n)].join(` `)}async function Y(e,t){let n=t.authorizationServerMetadataUrl&&Ct(t.authorizationServerMetadataUrl),r=n?void 0:await e.discoveryState?.(),i=r?.authorizationServerUrl?{authorizationServerUrl:r.authorizationServerUrl,authorizationServerMetadata:r.authorizationServerMetadata??await vt(r.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation}),resourceMetadata:r.resourceMetadata}:await yt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:n,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation});n||await e.saveDiscoveryState?.({...i,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let a=i.authorizationServerMetadata,o=xt(t.serverUrl,i.resourceMetadata),s=t.scope||i.resourceMetadata?.scopes_supported?.join(` `)||e.clientMetadata.scope,c=await e.clientInformation();if(!c){if(t.authorizationCode)throw Error(`OAuth client information is missing during code exchange`);if(a?.client_id_metadata_document_supported&&e.clientMetadataUrl){let t=new URL(e.clientMetadataUrl);if(t.protocol!==`https:`||t.pathname===`/`)throw Error(`Invalid OAuth client metadata URL`);c={client_id:e.clientMetadataUrl},await e.saveClientInformation?.(c)}else{if(!e.saveClientInformation)throw Error(`OAuth client information cannot be persisted`);c=await kt(i.authorizationServerUrl,{metadata:a,clientMetadata:e.clientMetadata,scope:s,fetch:t.fetch}),await e.saveClientInformation(c)}}let l={metadata:a,clientInformation:c,resource:o,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch};if(t.authorizationCode){let n=t.iss;if(a&&(n!==void 0||a.authorization_response_iss_parameter_supported)&&n!==a.issuer)throw new ot(a.issuer,n);let r=await At(i.authorizationServerUrl,{...l,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:e.redirectUrl});return await e.saveTokens(Mt(r,s)),`AUTHORIZED`}let u=t.skipRefresh?void 0:await e.tokens();if(u?.refresh_token)try{let t=await jt(i.authorizationServerUrl,{...l,refreshToken:u.refresh_token});return await e.saveTokens(Mt(t,u.scope)),`AUTHORIZED`}catch(e){if(e instanceof st||e instanceof I&&e.code!==`server_error`)throw e}let d=await e.state?.(),f=await Dt(i.authorizationServerUrl,{metadata:a,clientInformation:c,redirectUrl:e.redirectUrl,scope:s,state:d,resource:o});return await e.saveCodeVerifier(f.codeVerifier),await e.redirectToAuthorization(f.authorizationUrl),`REDIRECT`}async function X(e,t){try{return await Y(e,t)}catch(n){if(n instanceof I&&[`invalid_client`,`unauthorized_client`].includes(n.code))return await e.invalidateCredentials?.(`all`),Y(e,t);if(n instanceof I&&n.code===`invalid_grant`)return await e.invalidateCredentials?.(`tokens`),Y(e,t);throw n}}var Pt=class{value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},Ft=class{redirectUrl;clientMetadata;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??[`authorization_code`,`refresh_token`],response_types:e.clientMetadata.response_types??[`code`],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?`client_secret_post`:`none`)},this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new Pt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString(`hex`);return await this.update(e=>({...e,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(n=>{let r={...n,tokens:e};return t===void 0?delete r.tokensExpireAt:r.tokensExpireAt=t,r})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw Error(`No OAuth PKCE code verifier is stored`);return e}async invalidateCredentials(e){await this.update(t=>{let n={...t};return(e===`all`||e===`client`)&&delete n.clientInformation,(e===`all`||e===`tokens`)&&(delete n.tokens,delete n.tokensExpireAt),(e===`all`||e===`verifier`)&&delete n.codeVerifier,(e===`all`||e===`discovery`)&&delete n.discovery,e===`all`&&delete n.oauthState,n})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};const Z=`127.0.0.1`,It=`/callback`,Lt=`http://${Z}${It}`;function Rt(e){return typeof e?.url!=`string`||e.type===`stdio`?!1:!Object.keys(e.headers??{}).some(e=>e.toLowerCase()===`authorization`)}function zt(e,t){return`${e}|${String(new URL(t))}`}function Bt(e){let t=new URL(e.callbackUrl??`http://${Z}${It}`),n=t.hostname.replace(/^\[|\]$/g,``),r=t.port?Number(t.port):e.callbackPort,i;return t.port?i=e.callbackUrl:r!==void 0&&(t.port=String(r),i=t.href),{host:n===`localhost`?Z:n,redirectHost:n,port:r,path:t.pathname,fixedRedirectUrl:i}}function Vt(...e){let t=[...new Set(e.flatMap(e=>e?.split(/\s+/).filter(Boolean)??[]))];return t.length>0?t.join(` `):void 0}const Q=e=>e&&`redirect_uris`in e?e.redirect_uris:[];function Ht(e,t,n,r,i,a){return new Ft({serverUrl:e,redirectUrl:i,clientMetadata:{client_name:n.clientName??r},clientId:n.clientId,clientSecret:n.clientSecret,store:t,onRedirect:a})}const $=new Map;function Ut({serverUrl:e,storeKey:t,store:n,settings:r={},clientName:i,onChallenge:a}){let o=(a,o=globalThis.fetch,s)=>{let c=$.get(t);return c||(c=(async()=>{let t=await n.load();if(t?.tokens?.access_token===a&&(!t?.tokens?.refresh_token||await X(Ht(e,n,r,i,Bt(r).fixedRedirectUrl??Q(t.clientInformation)[0]??Lt,()=>{}),{serverUrl:e,resourceMetadataUrl:s?.resourceMetadataUrl,authorizationServerMetadataUrl:r.authServerMetadataUrl,scope:s?.scope,fetch:(e,t)=>o(e,{...t,signal:AbortSignal.timeout(15e3)})})===`REDIRECT`))throw new L})().finally(()=>$.delete(t)),$.set(t,c)),c};return{token:async()=>{await $.get(t)?.catch(()=>void 0);let e=await n.load(),r=e?.tokens?.access_token;return!(e?.tokensExpireAt!==void 0&&e.tokensExpireAt-3e4<=Date.now())||!e?.tokens?.refresh_token?r:(await o(r).catch(()=>void 0),(await n.load())?.tokens?.access_token)},onUnauthorized:async e=>{let t=ht(e.response.headers.get(`www-authenticate`));if(a?.(t),t.error===`insufficient_scope`)throw new L;await o(e.token,e.fetch,t)}}}async function Wt(e,t,n,r){let i={host:e.host,redirectHost:e.redirectHost,path:e.path,...r?{renderPage:r}:{}};try{return await F.listen({...i,port:t??0})}catch(e){if(n||t===void 0)throw e;return F.listen(i)}}async function Gt(e,t){if(!t)return e;let n,r=new Promise((e,r)=>{n=()=>r(t.reason??Error(`Sign-in cancelled`)),t.aborted?n():t.addEventListener(`abort`,n,{once:!0})});try{let n=await Promise.race([e,r]);return t.throwIfAborted(),n}finally{t.removeEventListener(`abort`,n)}}async function Kt({serverUrl:e,store:t,settings:n={},clientName:r,challenge:i,openUrl:a,signal:o,renderPage:s}){o?.throwIfAborted();let c=await t.load();o?.throwIfAborted();let l={load:()=>t.load(),save:e=>(o?.throwIfAborted(),t.save(e))},u=i?.error===`insufficient_scope`,d=Bt(n),f=Q(c?.clientInformation)[0],p=await Wt(d,d.port??(f&&Number(new URL(f).port)||void 0),d.port!==void 0,s),m=d.fixedRedirectUrl??p.redirectUrl;try{if(o?.throwIfAborted(),c){let e={...c};delete e.oauthState,!n.clientId&&!Q(c.clientInformation).includes(m)&&(delete e.clientInformation,delete e.tokens,delete e.tokensExpireAt),await l.save(e)}let t,s=Ht(e,l,n,r,m,e=>{t=e}),d={serverUrl:e,resourceMetadataUrl:i?.resourceMetadataUrl,authorizationServerMetadataUrl:n.authServerMetadataUrl,scope:Vt(n.scope,u?Nt(c?.tokens?.scope,i?.scope):i?.scope),fetch:(e,t)=>(o?.throwIfAborted(),fetch(e,{...t,signal:o&&t?.signal?AbortSignal.any([o,t.signal]):o??t?.signal}))},f=await X(s,{...d,skipRefresh:u});if(o?.throwIfAborted(),f===`AUTHORIZED`)return;if(!t)throw Error(`OAuth flow did not produce an authorization URL`);let h=p.waitForCallback(await s.state());h.catch(()=>void 0),o?.throwIfAborted(),await Gt(a(t),o);let{code:ee,iss:g}=await Gt(h,o);await X(s,{...d,authorizationCode:ee,iss:g}),o?.throwIfAborted()}finally{await p.close()}}const qt=[`readOnlyHint`,`destructiveHint`,`idempotentHint`,`openWorldHint`];function Jt(e){let t=e&&typeof e==`object`?e:{};return{...t,type:t.type??`object`,...t.properties===void 0?{properties:{}}:{}}}function Yt(e){return{type:`object`,properties:{content:{type:`array`,items:{type:`object`}},...e?{structuredContent:e}:{},isError:{type:`boolean`},_meta:{type:`object`}},required:[`content`]}}function Xt(e){let t={};for(let n of qt){let r=e.annotations?.[n];typeof r==`boolean`&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function Zt({server:e,client:t,tool:n,name:r,exposure:i,config:a,instructions:o,limitText:s}){let c=n.title??n.annotations?.title,l=Xt(n),u=N(a);return{name:r,label:`${e}/${n.name}`,description:n.description?.trim()||c||`MCP tool ${n.name} from server ${e}`,parameters:Jt(n.inputSchema),outputSchema:Yt(n.outputSchema),execute:async(r,i,a,o)=>{try{let r=await t.callTool(n.name,i??{},{signal:a,timeoutMs:u,onProgress:t=>{let r=t.total===void 0?``:`/${t.total}`;o?.({content:[{type:`text`,text:t.message??`Progress ${t.progress}${r}`}],details:{server:e,tool:n.name}})}});return rt(e,n.name,r,{limitText:s})}catch(t){if(a?.aborted)throw t;return it(e,n.name,t,{limitText:s})}},_mcpServer:e,_mcpToolName:n.name,_mcpExposure:i,_mcpNamespace:h(e),...typeof a.description==`string`&&a.description.trim()?{_mcpServerDescription:a.description.trim()}:{},...o?{_mcpServerInstructions:o}:{},...l?{_mcpAnnotations:l}:{},_client:t}}function Qt(e,{defaultExposure:t=`deferred`,reservedNames:n,limitText:r=P}={}){let i=e.flatMap(e=>e.tools.map(n=>({connection:e,tool:n,exposure:g(e.config,n.name,t)}))),a=$e(i.map(({connection:e,tool:t})=>({server:e.name,tool:t.name})),{reserved:n});return i.flatMap(({connection:e,tool:t,exposure:n},i)=>n===`hidden`?[]:[Zt({server:e.name,client:e.client,tool:t,name:a[i],exposure:n,config:e.config,instructions:e.instructions?.trim(),limitText:r})])}export{Je as DEFAULT_MCP_TIMEOUT_MS,c as MCP_EXPOSURES,L as McpOAuthAuthorizationRequiredError,$e as assignMcpToolNames,Xe as connectMcpServer,rt as convertMcpResult,Qt as createMcpAgentTools,Ut as createMcpAuthProvider,g as getMcpToolExposure,et as legacyMcpToolName,P as limitMcpTextDefault,it as mcpCallErrorResult,h as mcpNamespace,zt as mcpOAuthStoreKey,N as mcpRequestTimeoutMs,Ze as mcpToolBaseName,Kt as signInMcpServer,Rt as usesMcpOAuth,re as validateMcpServerConfig};