zcode-app-cli 3.11.2-19 → 3.11.2-20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/zcode.js +69 -3
- package/package.json +1 -1
- package/vendor/extraction.json +6 -1
- package/vendor/node_modules/@zcode/tui/dist/index.js +117 -6
- package/vendor/zcode.cjs +1 -1
package/bin/zcode.js
CHANGED
|
@@ -5,7 +5,7 @@ import { constants, homedir, tmpdir } from "node:os";
|
|
|
5
5
|
import { basename, dirname, join, posix, resolve, sep, win32 } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
8
|
-
import { chmod, link, mkdir, mkdtemp, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
8
|
+
import { access, chmod, link, mkdir, mkdtemp, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
9
9
|
import { createInterface } from "node:readline/promises";
|
|
10
10
|
import { parseArgs } from "node:util";
|
|
11
11
|
//#region config.example.json
|
|
@@ -1288,6 +1288,50 @@ async function runPluginCommand(args, options) {
|
|
|
1288
1288
|
}
|
|
1289
1289
|
}
|
|
1290
1290
|
//#endregion
|
|
1291
|
+
//#region src/prompt-preflight.ts
|
|
1292
|
+
function record(value) {
|
|
1293
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
1294
|
+
}
|
|
1295
|
+
async function exists(path) {
|
|
1296
|
+
try {
|
|
1297
|
+
await access(path);
|
|
1298
|
+
return true;
|
|
1299
|
+
} catch (error) {
|
|
1300
|
+
return error.code !== "ENOENT";
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
/** Diagnose only unambiguous keyless Coding Plan configs, not general model access. */
|
|
1304
|
+
async function missingCodingPlanKey(options = {}) {
|
|
1305
|
+
const env = options.env ?? process.env;
|
|
1306
|
+
if (Object.entries(env).some(([key, value]) => value?.trim() && key !== "ZCODE_BASE_URL" && !key.startsWith("ZCODE_MODEL_RETRY_") && key !== "ZCODE_MODEL_TELEMETRY_ENABLED" && /^(?:ZCODE|ZAI|BIGMODEL|ZHIPU|ANTHROPIC)_.*(?:KEY|TOKEN|MODEL|CONFIG|PROVIDER|BASE_URL)/u.test(key))) return;
|
|
1307
|
+
let directory = resolve(options.workingDirectory ?? process.cwd());
|
|
1308
|
+
while (true) {
|
|
1309
|
+
if ((await Promise.all([
|
|
1310
|
+
join(directory, "zcode.json"),
|
|
1311
|
+
join(directory, ".zcode", "config.json"),
|
|
1312
|
+
join(directory, ".env")
|
|
1313
|
+
].map(exists))).some(Boolean)) return void 0;
|
|
1314
|
+
const parent = dirname(directory);
|
|
1315
|
+
if (parent === directory) break;
|
|
1316
|
+
directory = parent;
|
|
1317
|
+
}
|
|
1318
|
+
let config;
|
|
1319
|
+
try {
|
|
1320
|
+
config = record(JSON.parse(await readFile(userConfigPath(env), "utf8")));
|
|
1321
|
+
} catch {
|
|
1322
|
+
return;
|
|
1323
|
+
}
|
|
1324
|
+
const model = options.model ?? record(config?.model)?.main;
|
|
1325
|
+
if (typeof model !== "string") return void 0;
|
|
1326
|
+
const providerId = model.split("/", 1)[0];
|
|
1327
|
+
if (providerId !== "zai" && providerId !== "bigmodel") return void 0;
|
|
1328
|
+
const provider = record(record(config?.provider)?.[providerId]);
|
|
1329
|
+
const settings = record(provider?.options);
|
|
1330
|
+
const expectedUrl = providerId === "zai" ? "https://api.z.ai/api/anthropic" : "https://open.bigmodel.cn/api/anthropic";
|
|
1331
|
+
if (provider?.kind !== "anthropic" || settings?.baseURL !== expectedUrl || settings?.apiKeyRequired !== true || typeof settings.apiKey === "string" && settings.apiKey.trim() || settings.apiKey !== void 0 && typeof settings.apiKey !== "string" || Object.keys(record(provider.headers) ?? {}).length > 0) return void 0;
|
|
1332
|
+
return `Model access is not configured for ${providerId}. Run /login or /setup in zcode, or configure its API key before sending a prompt. No model request was sent.`;
|
|
1333
|
+
}
|
|
1334
|
+
//#endregion
|
|
1291
1335
|
//#region src/runtime-capabilities.ts
|
|
1292
1336
|
function isRecord(value) {
|
|
1293
1337
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -1421,6 +1465,8 @@ function inspectRuntimeInvocation(args, runtimeOptionTypes) {
|
|
|
1421
1465
|
let invalid = false;
|
|
1422
1466
|
let passthrough = false;
|
|
1423
1467
|
let presentationSurface = false;
|
|
1468
|
+
let workingDirectory;
|
|
1469
|
+
let resume = false;
|
|
1424
1470
|
for (let index = 0; index < args.length; index += 1) {
|
|
1425
1471
|
const argument = args[index];
|
|
1426
1472
|
if (argument === "--") {
|
|
@@ -1430,6 +1476,8 @@ function inspectRuntimeInvocation(args, runtimeOptionTypes) {
|
|
|
1430
1476
|
if (argument.startsWith("--")) {
|
|
1431
1477
|
const option = longOptionName(argument);
|
|
1432
1478
|
const inlineValue = option.length !== argument.length;
|
|
1479
|
+
if (option === "--cwd") workingDirectory = inlineValue ? argument.slice(option.length + 1) : args[index + 1];
|
|
1480
|
+
if (option === "--resume" || option === "--continue") resume = true;
|
|
1433
1481
|
if (option === "--browser-use") {
|
|
1434
1482
|
explicitBrowserUse = true;
|
|
1435
1483
|
if (!inlineValue) if (index + 1 >= args.length || args[index + 1].startsWith("-")) invalid = true;
|
|
@@ -1481,7 +1529,10 @@ function inspectRuntimeInvocation(args, runtimeOptionTypes) {
|
|
|
1481
1529
|
else index += 1;
|
|
1482
1530
|
continue;
|
|
1483
1531
|
}
|
|
1484
|
-
if (argument === "-c" || argument === "-f")
|
|
1532
|
+
if (argument === "-c" || argument === "-f") {
|
|
1533
|
+
if (argument === "-c") resume = true;
|
|
1534
|
+
continue;
|
|
1535
|
+
}
|
|
1485
1536
|
invalid = true;
|
|
1486
1537
|
continue;
|
|
1487
1538
|
}
|
|
@@ -1493,9 +1544,19 @@ function inspectRuntimeInvocation(args, runtimeOptionTypes) {
|
|
|
1493
1544
|
command,
|
|
1494
1545
|
explicitBrowserUse,
|
|
1495
1546
|
invalid,
|
|
1496
|
-
passthrough
|
|
1547
|
+
passthrough,
|
|
1548
|
+
workingDirectory,
|
|
1549
|
+
resume
|
|
1497
1550
|
};
|
|
1498
1551
|
}
|
|
1552
|
+
async function promptPreflight(args, env = process.env) {
|
|
1553
|
+
const invocation = inspectRuntimeInvocation(args, readRuntimeCliOptionTypes());
|
|
1554
|
+
if (!invocation.agentInvocation || invocation.invalid || invocation.passthrough || invocation.resume) return;
|
|
1555
|
+
return missingCodingPlanKey({
|
|
1556
|
+
env,
|
|
1557
|
+
workingDirectory: invocation.workingDirectory
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1499
1560
|
function withDefaultBrowserUse(args, runtimeOptionTypes = readRuntimeCliOptionTypes()) {
|
|
1500
1561
|
const invocation = inspectRuntimeInvocation(args, runtimeOptionTypes);
|
|
1501
1562
|
if (invocation.explicitBrowserUse || invocation.passthrough || invocation.invalid || !invocation.agentInvocation && invocation.command !== void 0 && invocation.command !== "tui") return args;
|
|
@@ -1722,6 +1783,11 @@ async function main(args) {
|
|
|
1722
1783
|
}
|
|
1723
1784
|
}
|
|
1724
1785
|
try {
|
|
1786
|
+
const diagnostic = await promptPreflight(login.args);
|
|
1787
|
+
if (diagnostic) {
|
|
1788
|
+
console.error(diagnostic);
|
|
1789
|
+
return 1;
|
|
1790
|
+
}
|
|
1725
1791
|
const runtimeArgs = withDefaultBrowserUse(login.args);
|
|
1726
1792
|
return await runRuntime(node, runtimeArgs, firstRunSetupEnv(setupPending, runtimeArgs));
|
|
1727
1793
|
} catch (error) {
|
package/package.json
CHANGED
package/vendor/extraction.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"appVersion": "3.11.2",
|
|
3
3
|
"cliVersion": "0.16.5",
|
|
4
|
-
"extractedAt": "2026-09-
|
|
4
|
+
"extractedAt": "2026-09-05T15:48:54.303Z",
|
|
5
5
|
"sha512": "4UAMZSP9ZWBrnb8wGaP39rb5dB5ikPx4aYPXKXGea1Vmd6L6vGma3rXwRxKbhBxgsCIE9jv6tmrdSL60RrzGcA==",
|
|
6
6
|
"source": "https://cdn-zcode.z.ai/zcode/electron/releases/3.11.2/linux-x64/ZCode-3.11.2-linux-x64.deb",
|
|
7
7
|
"runtimeCapabilities": {
|
|
@@ -79,6 +79,11 @@
|
|
|
79
79
|
}
|
|
80
80
|
},
|
|
81
81
|
"runtimePatches": [
|
|
82
|
+
{
|
|
83
|
+
"id": "official-mcp-availability",
|
|
84
|
+
"requirement": "optional",
|
|
85
|
+
"status": "applied"
|
|
86
|
+
},
|
|
82
87
|
{
|
|
83
88
|
"id": "tui-bridge",
|
|
84
89
|
"requirement": "required",
|
|
@@ -3,8 +3,8 @@ import { spawn } from "node:child_process";
|
|
|
3
3
|
import { accessSync, appendFileSync, closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
|
|
4
4
|
import { constants as constants$1, homedir } from "node:os";
|
|
5
5
|
import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep, win32 } from "node:path";
|
|
6
|
+
import { access, copyFile, link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
6
7
|
import { randomUUID } from "node:crypto";
|
|
7
|
-
import { copyFile, link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
8
8
|
import { Box, CombinedAutocompleteProvider, Container, Editor, Image, Input, Markdown, ProcessTerminal, ScrollView, SelectList, Spacer, Text, TuiAltScreen, TuiMainScreen, VStack, decodeKittyPrintable, getKeybindings, isKeyRelease, isViewportTUI, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
9
9
|
import { isDeepStrictEqual } from "node:util";
|
|
10
10
|
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
|
|
@@ -273,6 +273,65 @@ async function clearSetupPending(env = process.env) {
|
|
|
273
273
|
await rm(setupPendingPath(env), { force: true }).catch(() => {});
|
|
274
274
|
}
|
|
275
275
|
//#endregion
|
|
276
|
+
//#region src/prompt-preflight.ts
|
|
277
|
+
function record$4(value) {
|
|
278
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
279
|
+
}
|
|
280
|
+
async function exists(path) {
|
|
281
|
+
try {
|
|
282
|
+
await access(path);
|
|
283
|
+
return true;
|
|
284
|
+
} catch (error) {
|
|
285
|
+
return error.code !== "ENOENT";
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
/** Diagnose only unambiguous keyless Coding Plan configs, not general model access. */
|
|
289
|
+
async function missingCodingPlanKey(options = {}) {
|
|
290
|
+
const env = options.env ?? process.env;
|
|
291
|
+
if (Object.entries(env).some(([key, value]) => value?.trim() && key !== "ZCODE_BASE_URL" && !key.startsWith("ZCODE_MODEL_RETRY_") && key !== "ZCODE_MODEL_TELEMETRY_ENABLED" && /^(?:ZCODE|ZAI|BIGMODEL|ZHIPU|ANTHROPIC)_.*(?:KEY|TOKEN|MODEL|CONFIG|PROVIDER|BASE_URL)/u.test(key))) return;
|
|
292
|
+
let directory = resolve(options.workingDirectory ?? process.cwd());
|
|
293
|
+
while (true) {
|
|
294
|
+
if ((await Promise.all([
|
|
295
|
+
join(directory, "zcode.json"),
|
|
296
|
+
join(directory, ".zcode", "config.json"),
|
|
297
|
+
join(directory, ".env")
|
|
298
|
+
].map(exists))).some(Boolean)) return void 0;
|
|
299
|
+
const parent = dirname(directory);
|
|
300
|
+
if (parent === directory) break;
|
|
301
|
+
directory = parent;
|
|
302
|
+
}
|
|
303
|
+
let config;
|
|
304
|
+
try {
|
|
305
|
+
config = record$4(JSON.parse(await readFile(userConfigPath(env), "utf8")));
|
|
306
|
+
} catch {
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const model = options.model ?? record$4(config?.model)?.main;
|
|
310
|
+
if (typeof model !== "string") return void 0;
|
|
311
|
+
const providerId = model.split("/", 1)[0];
|
|
312
|
+
if (providerId !== "zai" && providerId !== "bigmodel") return void 0;
|
|
313
|
+
const provider = record$4(record$4(config?.provider)?.[providerId]);
|
|
314
|
+
const settings = record$4(provider?.options);
|
|
315
|
+
const expectedUrl = providerId === "zai" ? "https://api.z.ai/api/anthropic" : "https://open.bigmodel.cn/api/anthropic";
|
|
316
|
+
if (provider?.kind !== "anthropic" || settings?.baseURL !== expectedUrl || settings?.apiKeyRequired !== true || typeof settings.apiKey === "string" && settings.apiKey.trim() || settings.apiKey !== void 0 && typeof settings.apiKey !== "string" || Object.keys(record$4(provider.headers) ?? {}).length > 0) return void 0;
|
|
317
|
+
return `Model access is not configured for ${providerId}. Run /login or /setup in zcode, or configure its API key before sending a prompt. No model request was sent.`;
|
|
318
|
+
}
|
|
319
|
+
//#endregion
|
|
320
|
+
//#region packages/zcode-tui/src/prompt-preflight.ts
|
|
321
|
+
/** Preserve rejected input without replacing a draft typed during validation. */
|
|
322
|
+
async function preflightSubmission(options) {
|
|
323
|
+
const diagnostic = await options.validate();
|
|
324
|
+
if (options.isStopped()) return false;
|
|
325
|
+
if (!diagnostic) return true;
|
|
326
|
+
if (options.queued || options.editor.getText() !== "") options.inputQueue.restoreFollowUp(options.submission);
|
|
327
|
+
else {
|
|
328
|
+
options.editor.setText(options.submission.input);
|
|
329
|
+
options.inputQueue.autoSend = false;
|
|
330
|
+
}
|
|
331
|
+
options.warn(diagnostic);
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
//#endregion
|
|
276
335
|
//#region src/desktop-migration.ts
|
|
277
336
|
const desktopConfigDirectory = "v2";
|
|
278
337
|
const knownFamilies = ["zai", "bigmodel"];
|
|
@@ -162162,6 +162221,7 @@ var TurnNotifier = class {
|
|
|
162162
162221
|
settings;
|
|
162163
162222
|
active = false;
|
|
162164
162223
|
focusReporting = false;
|
|
162224
|
+
focusReportingRequired;
|
|
162165
162225
|
terminalFocus = "unknown";
|
|
162166
162226
|
terminalUnavailable = false;
|
|
162167
162227
|
constructor(options) {
|
|
@@ -162170,6 +162230,7 @@ var TurnNotifier = class {
|
|
|
162170
162230
|
this.platform = options.platform ?? process.platform;
|
|
162171
162231
|
this.nativeNotify = options.nativeNotify ?? ((platform, title, body) => sendNativeNotification(platform, title, body, this.env));
|
|
162172
162232
|
this.settings = options.settings ?? notificationSettings(this.env);
|
|
162233
|
+
this.focusReportingRequired = options.focusReportingRequired === true;
|
|
162173
162234
|
}
|
|
162174
162235
|
start() {
|
|
162175
162236
|
this.active = true;
|
|
@@ -162196,6 +162257,11 @@ var TurnNotifier = class {
|
|
|
162196
162257
|
this.settings = { ...settings };
|
|
162197
162258
|
this.syncFocusReporting();
|
|
162198
162259
|
}
|
|
162260
|
+
setFocusReportingRequired(required) {
|
|
162261
|
+
if (this.focusReportingRequired === required) return;
|
|
162262
|
+
this.focusReportingRequired = required;
|
|
162263
|
+
this.syncFocusReporting();
|
|
162264
|
+
}
|
|
162199
162265
|
handleInput(data) {
|
|
162200
162266
|
if (data === focusIn) {
|
|
162201
162267
|
this.terminalFocus = "focused";
|
|
@@ -162249,7 +162315,7 @@ var TurnNotifier = class {
|
|
|
162249
162315
|
}
|
|
162250
162316
|
}
|
|
162251
162317
|
syncFocusReporting() {
|
|
162252
|
-
if (!this.active || this.settings.method === "off" || this.settings.condition !== "unfocused") {
|
|
162318
|
+
if (!this.active || !this.focusReportingRequired && (this.settings.method === "off" || this.settings.condition !== "unfocused")) {
|
|
162253
162319
|
this.disableFocusReporting();
|
|
162254
162320
|
return;
|
|
162255
162321
|
}
|
|
@@ -162678,6 +162744,11 @@ var InputQueue = class {
|
|
|
162678
162744
|
if (submission) this.syncView();
|
|
162679
162745
|
return submission;
|
|
162680
162746
|
}
|
|
162747
|
+
restoreFollowUp(submission) {
|
|
162748
|
+
this.queuedFollowUps.unshift(submission);
|
|
162749
|
+
this.autoSendEnabled = false;
|
|
162750
|
+
this.syncView();
|
|
162751
|
+
}
|
|
162681
162752
|
editLatestFollowUp() {
|
|
162682
162753
|
const submission = this.queuedFollowUps.pop();
|
|
162683
162754
|
if (submission) this.syncView();
|
|
@@ -165779,6 +165850,7 @@ const runtimeCommandSummaries = /* @__PURE__ */ new Map([
|
|
|
165779
165850
|
const terminalThemeQueryTimeoutMs = 100;
|
|
165780
165851
|
const exitUsageQueryTimeoutMs = 250;
|
|
165781
165852
|
const fullscreenWelcomeTransitionMs = 180;
|
|
165853
|
+
const terminalFocusIn = "\x1B[I";
|
|
165782
165854
|
const updateAvailableBlockId = "update_available";
|
|
165783
165855
|
const modelRetryBlockIdPrefix = "model_retry_status";
|
|
165784
165856
|
const questionBackValue = "__back__";
|
|
@@ -165944,6 +166016,14 @@ var ZCodeAltScreen = class extends TuiAltScreen {
|
|
|
165944
166016
|
setCurrentInput(data) {
|
|
165945
166017
|
this.currentInput = data;
|
|
165946
166018
|
}
|
|
166019
|
+
/**
|
|
166020
|
+
* The terminal can lose visible rows while this process is unfocused even
|
|
166021
|
+
* though pi-tui's logical frame remains unchanged. Invalidate its
|
|
166022
|
+
* differential cache so the next frame repaints every row.
|
|
166023
|
+
*/
|
|
166024
|
+
forceFullRedraw() {
|
|
166025
|
+
process.nextTick(() => this.requestRender(true));
|
|
166026
|
+
}
|
|
165947
166027
|
isOverlayFocused() {
|
|
165948
166028
|
if (super.isOverlayFocused()) return true;
|
|
165949
166029
|
return this.viewportInputDeferral?.(this.currentInput ?? "") === true;
|
|
@@ -165953,10 +166033,14 @@ var ZCodeAltScreen = class extends TuiAltScreen {
|
|
|
165953
166033
|
var NotifyingProcessTerminal = class extends ProcessTerminal {
|
|
165954
166034
|
beforeInput;
|
|
165955
166035
|
afterInput;
|
|
165956
|
-
|
|
166036
|
+
onFocusIn;
|
|
166037
|
+
onTerminalResize;
|
|
166038
|
+
constructor(beforeInput, afterInput, onFocusIn, onTerminalResize) {
|
|
165957
166039
|
super();
|
|
165958
166040
|
this.beforeInput = beforeInput;
|
|
165959
166041
|
this.afterInput = afterInput;
|
|
166042
|
+
this.onFocusIn = onFocusIn;
|
|
166043
|
+
this.onTerminalResize = onTerminalResize;
|
|
165960
166044
|
}
|
|
165961
166045
|
start(onInput, onResize) {
|
|
165962
166046
|
super.start((data) => {
|
|
@@ -165965,8 +166049,12 @@ var NotifyingProcessTerminal = class extends ProcessTerminal {
|
|
|
165965
166049
|
onInput(data);
|
|
165966
166050
|
} finally {
|
|
165967
166051
|
this.afterInput?.();
|
|
166052
|
+
if (data === terminalFocusIn) this.onFocusIn?.();
|
|
165968
166053
|
}
|
|
165969
|
-
},
|
|
166054
|
+
}, () => {
|
|
166055
|
+
onResize();
|
|
166056
|
+
this.onTerminalResize?.();
|
|
166057
|
+
});
|
|
165970
166058
|
}
|
|
165971
166059
|
};
|
|
165972
166060
|
function signalExitCode(signal) {
|
|
@@ -166119,7 +166207,10 @@ var ZCodeTui = class {
|
|
|
166119
166207
|
this.skillCatalog = new SkillCatalog(options.listSkills);
|
|
166120
166208
|
this.tuiMode = resolveTuiMode(process.env, { ui: { tuiMode: options.initialTuiMode } });
|
|
166121
166209
|
this.ui = this.createTui(this.tuiMode);
|
|
166122
|
-
this.notifications = new TurnNotifier({
|
|
166210
|
+
this.notifications = new TurnNotifier({
|
|
166211
|
+
writeTerminal: (data) => this.ui.terminal.write(data),
|
|
166212
|
+
focusReportingRequired: this.tuiMode === "fullscreen"
|
|
166213
|
+
});
|
|
166123
166214
|
this.status = new StatusLine();
|
|
166124
166215
|
this.turnStatus = new FooterBar();
|
|
166125
166216
|
this.queuedInputView = new QueuedInputView(this.theme);
|
|
@@ -166173,6 +166264,7 @@ var ZCodeTui = class {
|
|
|
166173
166264
|
if (effective !== this.tuiMode) {
|
|
166174
166265
|
this.ui = this.createTui(effective);
|
|
166175
166266
|
this.tuiMode = effective;
|
|
166267
|
+
this.notifications.setFocusReportingRequired(effective === "fullscreen");
|
|
166176
166268
|
this.editor = this.createEditor(this.ui);
|
|
166177
166269
|
}
|
|
166178
166270
|
} catch {}
|
|
@@ -166283,7 +166375,7 @@ var ZCodeTui = class {
|
|
|
166283
166375
|
const terminal = new NotifyingProcessTerminal((data) => {
|
|
166284
166376
|
fullscreenTui?.setCurrentInput(data);
|
|
166285
166377
|
this.notifications?.handleInput(data);
|
|
166286
|
-
}, () => fullscreenTui?.setCurrentInput(void 0));
|
|
166378
|
+
}, () => fullscreenTui?.setCurrentInput(void 0), () => fullscreenTui?.forceFullRedraw(), () => fullscreenTui?.forceFullRedraw());
|
|
166287
166379
|
if (mode !== "fullscreen") return new TuiMainScreen(terminal, true);
|
|
166288
166380
|
const tui = new ZCodeAltScreen(terminal, true, void 0, {
|
|
166289
166381
|
copySelection: async (text) => {
|
|
@@ -166471,6 +166563,7 @@ var ZCodeTui = class {
|
|
|
166471
166563
|
this.ui.stop({ preserveScreen: true });
|
|
166472
166564
|
this.ui = this.createTui(next);
|
|
166473
166565
|
this.tuiMode = next;
|
|
166566
|
+
this.notifications.setFocusReportingRequired(next === "fullscreen");
|
|
166474
166567
|
this.sessionHasContent = hadSessionContent;
|
|
166475
166568
|
this.fullscreenWelcomeVisible = !hadSessionContent;
|
|
166476
166569
|
this.fullscreenHeader.setPhase(hadSessionContent ? "rail" : "welcome");
|
|
@@ -166496,6 +166589,7 @@ var ZCodeTui = class {
|
|
|
166496
166589
|
} catch {}
|
|
166497
166590
|
this.ui = previousUi;
|
|
166498
166591
|
this.tuiMode = previousMode;
|
|
166592
|
+
this.notifications.setFocusReportingRequired(previousMode === "fullscreen");
|
|
166499
166593
|
this.sessionHasContent = hadSessionContent;
|
|
166500
166594
|
this.fullscreenWelcomeVisible = previousMode === "fullscreen" ? !hadSessionContent : true;
|
|
166501
166595
|
this.fullscreenHeader.setPhase(hadSessionContent ? "rail" : "welcome");
|
|
@@ -166824,6 +166918,23 @@ var ZCodeTui = class {
|
|
|
166824
166918
|
const input = (queuedSubmission?.input ?? rawInput).trim();
|
|
166825
166919
|
if (!input || this.stopped) return false;
|
|
166826
166920
|
const submission = queuedSubmission ?? protectSubmission(input);
|
|
166921
|
+
if (!input.startsWith("/") && !this.primaryTurnActive) {
|
|
166922
|
+
if (!await preflightSubmission({
|
|
166923
|
+
validate: () => missingCodingPlanKey({
|
|
166924
|
+
model: this.model,
|
|
166925
|
+
workingDirectory: this.options.workspaceDirectory
|
|
166926
|
+
}),
|
|
166927
|
+
isStopped: () => this.stopped,
|
|
166928
|
+
submission,
|
|
166929
|
+
queued: queuedSubmission !== void 0,
|
|
166930
|
+
editor: {
|
|
166931
|
+
getText: () => this.editor.getText(),
|
|
166932
|
+
setText: (text) => this.editor.setText(text)
|
|
166933
|
+
},
|
|
166934
|
+
inputQueue: this.inputQueue,
|
|
166935
|
+
warn: (message) => this.addNotice(message, "warning")
|
|
166936
|
+
})) return false;
|
|
166937
|
+
}
|
|
166827
166938
|
if (submission.recordHistory) {
|
|
166828
166939
|
this.rememberEditorHistory(input);
|
|
166829
166940
|
this.editor.addToHistory(input);
|
package/vendor/zcode.cjs
CHANGED
|
@@ -1809,7 +1809,7 @@ ${n}`}function RDo(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))retu
|
|
|
1809
1809
|
missingProperty: ${p},
|
|
1810
1810
|
depsCount: ${c},
|
|
1811
1811
|
deps: ${d}}`,"params")};let o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){let[c,d]=i(l);s(l,c),u(l,d)}};function i({schema:l}){let c={},d={};for(let p in l){if(p==="__proto__")continue;let m=Array.isArray(l[p])?c:d;m[p]=l[p]}return[c,d]}a(i,"splitDependencies");function s(l,c=l.schema){let{gen:d,data:p,it:m}=l;if(Object.keys(c).length===0)return;let h=d.let("missing");for(let _ in c){let y=c[_];if(y.length===0)continue;let v=(0,n.propertyInData)(d,p,_,m.opts.ownProperties);l.setParams({property:_,depsCount:y.length,deps:y.join(", ")}),m.allErrors?d.if(v,()=>{for(let x of y)(0,n.checkReportMissingProp)(l,x)}):(d.if((0,t._)`${v} && (${(0,n.checkMissingProp)(l,y,h)})`),(0,n.reportMissingProp)(l,h),d.else())}}a(s,"validatePropertyDeps"),e.validatePropertyDeps=s;function u(l,c=l.schema){let{gen:d,data:p,keyword:m,it:h}=l,_=d.name("valid");for(let y in c)(0,r.alwaysValidSchema)(h,c[y])||(d.if((0,n.propertyInData)(d,p,y,h.opts.ownProperties),()=>{let v=l.subschema({keyword:m,schemaProp:y},_);l.mergeValidEvaluated(v,_)},()=>d.var(_,!0)),l.ok(_))}a(u,"validateSchemaDeps"),e.validateSchemaDeps=u,e.default=o})),QLo=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ko(),r=Ra(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:a(({params:o})=>(0,t._)`{propertyName: ${o.propertyName}}`,"params")},code(o){let{gen:i,schema:s,data:u,it:l}=o;if((0,r.alwaysValidSchema)(l,s))return;let c=i.name("valid");i.forIn("key",u,d=>{o.setParams({propertyName:d}),o.subschema({keyword:"propertyNames",data:d,dataTypes:["string"],propertyName:d,compositeRule:!0},c),i.if((0,t.not)(c),()=>{o.error(!0),l.allErrors||i.break()})}),o.ok(c)}};e.default=n})),C1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=e2(),r=Ko(),n=Xv(),o=Ra(),i={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:a(({params:s})=>(0,r._)`{additionalProperty: ${s.additionalProperty}}`,"params")},code(s){let{gen:u,schema:l,parentSchema:c,data:d,errsCount:p,it:m}=s;if(!p)throw new Error("ajv implementation error");let{allErrors:h,opts:_}=m;if(m.props=!0,_.removeAdditional!=="all"&&(0,o.alwaysValidSchema)(m,l))return;let y=(0,t.allSchemaProperties)(c.properties),v=(0,t.allSchemaProperties)(c.patternProperties);x(),s.ok((0,r._)`${p} === ${n.default.errors}`);function x(){u.forIn("key",d,I=>{!y.length&&!v.length?k(I):u.if(w(I),()=>k(I))})}a(x,"checkAdditionalProperties");function w(I){let C;if(y.length>8){let R=(0,o.schemaRefOrVal)(m,c.properties,"properties");C=(0,t.isOwnProperty)(u,R,I)}else y.length?C=(0,r.or)(...y.map(R=>(0,r._)`${I} === ${R}`)):C=r.nil;return v.length&&(C=(0,r.or)(C,...v.map(R=>(0,r._)`${(0,t.usePattern)(s,R)}.test(${I})`))),(0,r.not)(C)}a(w,"isAdditional");function b(I){u.code((0,r._)`delete ${d}[${I}]`)}a(b,"deleteAdditional");function k(I){if(_.removeAdditional==="all"||_.removeAdditional&&l===!1){b(I);return}if(l===!1){s.setParams({additionalProperty:I}),s.error(),h||u.break();return}if(typeof l=="object"&&!(0,o.alwaysValidSchema)(m,l)){let C=u.name("valid");_.removeAdditional==="failing"?(S(I,C,!1),u.if((0,r.not)(C),()=>{s.reset(),b(I)})):(S(I,C),h||u.if((0,r.not)(C),()=>u.break()))}}a(k,"additionalPropertyCode");function S(I,C,R){let A={keyword:"additionalProperties",dataProp:I,dataPropType:o.Type.Str};R===!1&&Object.assign(A,{compositeRule:!0,createErrors:!1,allErrors:!1}),s.subschema(A,C)}a(S,"applyAdditionalSchema")}};e.default=i})),XLo=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=xq(),r=e2(),n=Ra(),o=C1r(),i={keyword:"properties",type:"object",schemaType:"object",code(s){let{gen:u,schema:l,parentSchema:c,data:d,it:p}=s;p.opts.removeAdditional==="all"&&c.additionalProperties===void 0&&o.default.code(new t.KeywordCxt(p,o.default,"additionalProperties"));let m=(0,r.allSchemaProperties)(l);for(let x of m)p.definedProperties.add(x);p.opts.unevaluated&&m.length&&p.props!==!0&&(p.props=n.mergeEvaluated.props(u,(0,n.toHash)(m),p.props));let h=m.filter(x=>!(0,n.alwaysValidSchema)(p,l[x]));if(h.length===0)return;let _=u.name("valid");for(let x of h)y(x)?v(x):(u.if((0,r.propertyInData)(u,d,x,p.opts.ownProperties)),v(x),p.allErrors||u.else().var(_,!0),u.endIf()),s.it.definedProperties.add(x),s.ok(_);function y(x){return p.opts.useDefaults&&!p.compositeRule&&l[x].default!==void 0}a(y,"hasDefault");function v(x){s.subschema({keyword:"properties",schemaProp:x,dataProp:x},_)}a(v,"applyPropertySchema")}};e.default=i})),e8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=e2(),r=Ko(),n=Ra(),o=Ra(),i={keyword:"patternProperties",type:"object",schemaType:"object",code(s){let{gen:u,schema:l,data:c,parentSchema:d,it:p}=s,{opts:m}=p,h=(0,t.allSchemaProperties)(l),_=h.filter(S=>(0,n.alwaysValidSchema)(p,l[S]));if(h.length===0||_.length===h.length&&(!p.opts.unevaluated||p.props===!0))return;let y=m.strictSchema&&!m.allowMatchingProperties&&d.properties,v=u.name("valid");p.props!==!0&&!(p.props instanceof r.Name)&&(p.props=(0,o.evaluatedPropsToName)(u,p.props));let{props:x}=p;w();function w(){for(let S of h)y&&b(S),p.allErrors?k(S):(u.var(v,!0),k(S),u.if(v))}a(w,"validatePatternProperties");function b(S){for(let I in y)new RegExp(S).test(I)&&(0,n.checkStrictMode)(p,`property ${I} matches pattern ${S} (use allowMatchingProperties)`)}a(b,"checkMatchingProperties");function k(S){u.forIn("key",c,I=>{u.if((0,r._)`${(0,t.usePattern)(s,S)}.test(${I})`,()=>{let C=_.includes(S);C||s.subschema({keyword:"patternProperties",schemaProp:S,dataProp:I,dataPropType:o.Type.Str},v),p.opts.unevaluated&&x!==!0?u.assign((0,r._)`${x}[${I}]`,!0):!C&&!p.allErrors&&u.if((0,r.not)(v),()=>u.break())})})}a(k,"validateProperties")}};e.default=i})),t8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ra(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){let{gen:o,schema:i,it:s}=n;if((0,t.alwaysValidSchema)(s,i)){n.fail();return}let u=o.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},u),n.failResult(u,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};e.default=r})),r8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:e2().validateUnion,error:{message:"must match a schema in anyOf"}};e.default=t})),n8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ko(),r=Ra(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:a(({params:o})=>(0,t._)`{passingSchemas: ${o.passing}}`,"params")},code(o){let{gen:i,schema:s,parentSchema:u,it:l}=o;if(!Array.isArray(s))throw new Error("ajv implementation error");if(l.opts.discriminator&&u.discriminator)return;let c=s,d=i.let("valid",!1),p=i.let("passing",null),m=i.name("_valid");o.setParams({passing:p}),i.block(h),o.result(d,()=>o.reset(),()=>o.error(!0));function h(){c.forEach((_,y)=>{let v;(0,r.alwaysValidSchema)(l,_)?i.var(m,!0):v=o.subschema({keyword:"oneOf",schemaProp:y,compositeRule:!0},m),y>0&&i.if((0,t._)`${m} && ${d}`).assign(d,!1).assign(p,(0,t._)`[${p}, ${y}]`).else(),i.if(m,()=>{i.assign(d,!0),i.assign(p,y),v&&o.mergeEvaluated(v,t.Name)})})}a(h,"validateOneOf")}};e.default=n})),o8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ra(),r={keyword:"allOf",schemaType:"array",code(n){let{gen:o,schema:i,it:s}=n;if(!Array.isArray(i))throw new Error("ajv implementation error");let u=o.name("valid");i.forEach((l,c)=>{if((0,t.alwaysValidSchema)(s,l))return;let d=n.subschema({keyword:"allOf",schemaProp:c},u);n.ok(u),n.mergeEvaluated(d)})}};e.default=r})),i8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ko(),r=Ra(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:a(({params:i})=>(0,t.str)`must match "${i.ifClause}" schema`,"message"),params:a(({params:i})=>(0,t._)`{failingKeyword: ${i.ifClause}}`,"params")},code(i){let{gen:s,parentSchema:u,it:l}=i;u.then===void 0&&u.else===void 0&&(0,r.checkStrictMode)(l,'"if" without "then" and "else" is ignored');let c=o(l,"then"),d=o(l,"else");if(!c&&!d)return;let p=s.let("valid",!0),m=s.name("_valid");if(h(),i.reset(),c&&d){let y=s.let("ifClause");i.setParams({ifClause:y}),s.if(m,_("then",y),_("else",y))}else c?s.if(m,_("then")):s.if((0,t.not)(m),_("else"));i.pass(p,()=>i.error(!0));function h(){let y=i.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},m);i.mergeEvaluated(y)}a(h,"validateIf");function _(y,v){return()=>{let x=i.subschema({keyword:y},m);s.assign(p,m),i.mergeValidEvaluated(x,p),v?s.assign(v,(0,t._)`${y}`):i.setParams({ifClause:y})}}a(_,"validateClause")}};function o(i,s){let u=i.schema[s];return u!==void 0&&!(0,r.alwaysValidSchema)(i,u)}a(o,"hasSchema"),e.default=n})),a8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ra(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:o,it:i}){o.if===void 0&&(0,t.checkStrictMode)(i,`"${n}" without "if" is ignored`)}};e.default=r})),E1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=I1r(),r=KLo(),n=T1r(),o=JLo(),i=YLo(),s=Zst(),u=QLo(),l=C1r(),c=XLo(),d=e8o(),p=t8o(),m=r8o(),h=n8o(),_=o8o(),y=i8o(),v=a8o();function x(w=!1){let b=[p.default,m.default,h.default,_.default,y.default,v.default,u.default,l.default,s.default,c.default,d.default];return w?b.push(r.default,o.default):b.push(t.default,n.default),b.push(i.default),b}a(x,"getApplicator"),e.default=x})),s8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ko(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:a(({schemaCode:n})=>(0,t.str)`must match format "${n}"`,"message"),params:a(({schemaCode:n})=>(0,t._)`{format: ${n}}`,"params")},code(n,o){let{gen:i,data:s,$data:u,schema:l,schemaCode:c,it:d}=n,{opts:p,errSchemaPath:m,schemaEnv:h,self:_}=d;if(!p.validateFormats)return;u?y():v();function y(){let x=i.scopeValue("formats",{ref:_.formats,code:p.code.formats}),w=i.const("fDef",(0,t._)`${x}[${c}]`),b=i.let("fType"),k=i.let("format");i.if((0,t._)`typeof ${w} == "object" && !(${w} instanceof RegExp)`,()=>i.assign(b,(0,t._)`${w}.type || "string"`).assign(k,(0,t._)`${w}.validate`),()=>i.assign(b,(0,t._)`"string"`).assign(k,w)),n.fail$data((0,t.or)(S(),I()));function S(){return p.strictSchema===!1?t.nil:(0,t._)`${c} && !${k}`}a(S,"unknownFmt");function I(){let C=h.$async?(0,t._)`(${w}.async ? await ${k}(${s}) : ${k}(${s}))`:(0,t._)`${k}(${s})`,R=(0,t._)`(typeof ${k} == "function" ? ${C} : ${k}.test(${s}))`;return(0,t._)`${k} && ${k} !== true && ${b} === ${o} && !${R}`}a(I,"invalidFmt")}a(y,"validate$DataFormat");function v(){let x=_.formats[l];if(!x){S();return}if(x===!0)return;let[w,b,k]=I(x);w===o&&n.pass(C());function S(){if(p.strictSchema===!1){_.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${l}" ignored in schema at path "${m}"`}}a(S,"unknownFormat");function I(R){let A=R instanceof RegExp?(0,t.regexpCode)(R):p.code.formats?(0,t._)`${p.code.formats}${(0,t.getProperty)(l)}`:void 0,O=i.scopeValue("formats",{key:l,ref:R,code:A});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,t._)`${O}.validate`]:["string",R,O]}a(I,"getFormat");function C(){if(typeof x=="object"&&!(x instanceof RegExp)&&x.async){if(!h.$async)throw new Error("async format in sync schema");return(0,t._)`await ${k}(${s})`}return typeof b=="function"?(0,t._)`${k}(${s})`:(0,t._)`${k}.test(${s})`}a(C,"validCondition")}a(v,"validateFormat")}};e.default=r})),A1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=[s8o().default];e.default=t})),R1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],e.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]})),P1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=k1r(),r=S1r(),n=E1r(),o=A1r(),i=R1r(),s=[t.default,r.default,(0,n.default)(),o.default,i.metadataVocabulary,i.contentVocabulary];e.default=s})),u8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(r){r.Tag="tag",r.Mapping="mapping"})(t||(e.DiscrError=t={}))})),Kst=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ko(),r=u8o(),n=D1e(),o=bq(),i=Ra(),s={keyword:"discriminator",type:"object",schemaType:"object",error:{message:a(({params:{discrError:u,tagName:l}})=>u===r.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,"message"),params:a(({params:{discrError:u,tag:l,tagName:c}})=>(0,t._)`{error: ${u}, tag: ${c}, tagValue: ${l}}`,"params")},code(u){let{gen:l,data:c,schema:d,parentSchema:p,it:m}=u,{oneOf:h}=p;if(!m.opts.discriminator)throw new Error("discriminator: requires discriminator option");let _=d.propertyName;if(typeof _!="string")throw new Error("discriminator: requires propertyName");if(d.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");let y=l.let("valid",!1),v=l.const("tag",(0,t._)`${c}${(0,t.getProperty)(_)}`);l.if((0,t._)`typeof ${v} == "string"`,()=>x(),()=>u.error(!1,{discrError:r.DiscrError.Tag,tag:v,tagName:_})),u.ok(y);function x(){let k=b();l.if(!1);for(let S in k)l.elseIf((0,t._)`${v} === ${S}`),l.assign(y,w(k[S]));l.else(),u.error(!1,{discrError:r.DiscrError.Mapping,tag:v,tagName:_}),l.endIf()}a(x,"validateMapping");function w(k){let S=l.name("valid"),I=u.subschema({keyword:"oneOf",schemaProp:k},S);return u.mergeEvaluated(I,t.Name),S}a(w,"applyTagSchema");function b(){var k;let S={},I=R(p),C=!0;for(let P=0;P<h.length;P++){let D=h[P];if(D?.$ref&&!(0,i.schemaHasRulesButRef)(D,m.self.RULES)){let L=D.$ref;if(D=n.resolveRef.call(m.self,m.schemaEnv.root,m.baseId,L),D instanceof n.SchemaEnv&&(D=D.schema),D===void 0)throw new o.default(m.opts.uriResolver,m.baseId,L)}let U=(k=D?.properties)===null||k===void 0?void 0:k[_];if(typeof U!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${_}"`);C=C&&(I||R(D)),A(U,P)}if(!C)throw new Error(`discriminator: "${_}" must be required`);return S;function R({required:P}){return Array.isArray(P)&&P.includes(_)}function A(P,D){if(P.const)O(P.const,D);else if(P.enum)for(let U of P.enum)O(U,D);else throw new Error(`discriminator: "properties/${_}" must have "const" or "enum"`)}function O(P,D){if(typeof P!="string"||P in S)throw new Error(`discriminator: "${_}" values must be unique strings`);S[P]=D}}a(b,"getMapping")}};e.default=s})),l8o=st(((e,t)=>{t.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}})),M1r=st(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let r=Gst(),n=P1r(),o=Kst(),i=l8o(),s=["/properties"],u="http://json-schema.org/draft-07/schema";var l=class extends r.default{static{a(this,"Ajv")}_addVocabularies(){super._addVocabularies(),n.default.forEach(h=>this.addVocabulary(h)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let h=this.opts.$data?this.$dataMetaSchema(i,s):i;this.addMetaSchema(h,u,!1),this.refs["http://json-schema.org/schema"]=u}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(u)?u:void 0)}};e.Ajv=l,t.exports=e=l,t.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=xq();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:a(function(){return c.KeywordCxt},"get")});var d=Ko();Object.defineProperty(e,"_",{enumerable:!0,get:a(function(){return d._},"get")}),Object.defineProperty(e,"str",{enumerable:!0,get:a(function(){return d.str},"get")}),Object.defineProperty(e,"stringify",{enumerable:!0,get:a(function(){return d.stringify},"get")}),Object.defineProperty(e,"nil",{enumerable:!0,get:a(function(){return d.nil},"get")}),Object.defineProperty(e,"Name",{enumerable:!0,get:a(function(){return d.Name},"get")}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:a(function(){return d.CodeGen},"get")});var p=cre();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:a(function(){return p.default},"get")});var m=bq();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:a(function(){return m.default},"get")})})),O1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=Ko(),r=Xv(),n=D1e(),o=Wst(),i={keyword:"$dynamicAnchor",schemaType:"string",code:a(l=>s(l,l.schema),"code")};function s(l,c){let{gen:d,it:p}=l;p.schemaEnv.root.dynamicAnchors[c]=!0;let m=(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(c)}`,h=p.errSchemaPath==="#"?p.validateName:u(l);d.if((0,t._)`!${m}`,()=>d.assign(m,h))}a(s,"dynamicAnchor"),e.dynamicAnchor=s;function u(l){let{schemaEnv:c,schema:d,self:p}=l.it,{root:m,baseId:h,localRefs:_,meta:y}=c.root,{schemaId:v}=p.opts,x=new n.SchemaEnv({schema:d,schemaId:v,root:m,baseId:h,localRefs:_,meta:y});return n.compileSchema.call(p,x),(0,o.getValidate)(l,x)}a(u,"_getValidate"),e.default=i})),D1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=Ko(),r=Xv(),n=Wst(),o={keyword:"$dynamicRef",schemaType:"string",code:a(s=>i(s,s.schema),"code")};function i(s,u){let{gen:l,keyword:c,it:d}=s;if(u[0]!=="#")throw new Error(`"${c}" only supports hash fragment reference`);let p=u.slice(1);if(d.allErrors)m();else{let _=l.let("valid",!1);m(_),s.ok(_)}function m(_){if(d.schemaEnv.root.dynamicAnchors[p]){let y=l.let("_v",(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(p)}`);l.if(y,h(y,_),h(d.validateName,_))}else h(d.validateName,_)()}a(m,"_dynamicRef");function h(_,y){return y?()=>l.block(()=>{(0,n.callRef)(s,_),l.let(y,!0)}):()=>(0,n.callRef)(s,_)}a(h,"_callRef")}a(i,"dynamicRef"),e.dynamicRef=i,e.default=o})),c8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=O1r(),r=Ra(),n={keyword:"$recursiveAnchor",schemaType:"boolean",code(o){o.schema?(0,t.dynamicAnchor)(o,""):(0,r.checkStrictMode)(o.it,"$recursiveAnchor: false is ignored")}};e.default=n})),d8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=D1r(),r={keyword:"$recursiveRef",schemaType:"string",code:a(n=>(0,t.dynamicRef)(n,n.schema),"code")};e.default=r})),N1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=O1r(),r=D1r(),n=c8o(),o=d8o(),i=[t.default,r.default,n.default,o.default];e.default=i})),p8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zst(),r={keyword:"dependentRequired",type:"object",schemaType:"object",error:t.error,code:a(n=>(0,t.validatePropertyDeps)(n),"code")};e.default=r})),m8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zst(),r={keyword:"dependentSchemas",type:"object",schemaType:"object",code:a(n=>(0,t.validateSchemaDeps)(n),"code")};e.default=r})),f8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ra(),r={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:o,it:i}){o.contains===void 0&&(0,t.checkStrictMode)(i,`"${n}" without "contains" is ignored`)}};e.default=r})),L1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=p8o(),r=m8o(),n=f8o(),o=[t.default,r.default,n.default];e.default=o})),h8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ko(),r=Ra(),n=Xv(),o={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:a(({params:i})=>(0,t._)`{unevaluatedProperty: ${i.unevaluatedProperty}}`,"params")},code(i){let{gen:s,schema:u,data:l,errsCount:c,it:d}=i;if(!c)throw new Error("ajv implementation error");let{allErrors:p,props:m}=d;m instanceof t.Name?s.if((0,t._)`${m} !== true`,()=>s.forIn("key",l,v=>s.if(_(m,v),()=>h(v)))):m!==!0&&s.forIn("key",l,v=>m===void 0?h(v):s.if(y(m,v),()=>h(v))),d.props=!0,i.ok((0,t._)`${c} === ${n.default.errors}`);function h(v){if(u===!1){i.setParams({unevaluatedProperty:v}),i.error(),p||s.break();return}if(!(0,r.alwaysValidSchema)(d,u)){let x=s.name("valid");i.subschema({keyword:"unevaluatedProperties",dataProp:v,dataPropType:r.Type.Str},x),p||s.if((0,t.not)(x),()=>s.break())}}a(h,"unevaluatedPropCode");function _(v,x){return(0,t._)`!${v} || !${v}[${x}]`}a(_,"unevaluatedDynamic");function y(v,x){let w=[];for(let b in v)v[b]===!0&&w.push((0,t._)`${x} !== ${b}`);return(0,t.and)(...w)}a(y,"unevaluatedStatic")}};e.default=o})),g8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ko(),r=Ra(),n={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:a(({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,"message"),params:a(({params:{len:o}})=>(0,t._)`{limit: ${o}}`,"params")},code(o){let{gen:i,schema:s,data:u,it:l}=o,c=l.items||0;if(c===!0)return;let d=i.const("len",(0,t._)`${u}.length`);if(s===!1)o.setParams({len:c}),o.fail((0,t._)`${d} > ${c}`);else if(typeof s=="object"&&!(0,r.alwaysValidSchema)(l,s)){let m=i.var("valid",(0,t._)`${d} <= ${c}`);i.if((0,t.not)(m),()=>p(m,c)),o.ok(m)}l.items=!0;function p(m,h){i.forRange("i",h,d,_=>{o.subschema({keyword:"unevaluatedItems",dataProp:_,dataPropType:r.Type.Num},m),l.allErrors||i.if((0,t.not)(m),()=>i.break())})}a(p,"validateItems")}};e.default=n})),B1r=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=h8o(),r=g8o(),n=[t.default,r.default];e.default=n})),_8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/schema",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format"},{$ref:"meta/content"}],type:["object","boolean"],properties:{definitions:{$comment:"While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},dependencies:{$comment:'"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"',type:"object",additionalProperties:{anyOf:[{$recursiveRef:"#"},{$ref:"meta/validation#/$defs/stringArray"}]}}}}})),y8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{additionalItems:{$recursiveRef:"#"},unevaluatedItems:{$recursiveRef:"#"},items:{anyOf:[{$recursiveRef:"#"},{$ref:"#/$defs/schemaArray"}]},contains:{$recursiveRef:"#"},additionalProperties:{$recursiveRef:"#"},unevaluatedProperties:{$recursiveRef:"#"},properties:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$recursiveRef:"#"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$recursiveRef:"#"}},propertyNames:{$recursiveRef:"#"},if:{$recursiveRef:"#"},then:{$recursiveRef:"#"},else:{$recursiveRef:"#"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$recursiveRef:"#"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$recursiveRef:"#"}}}}})),v8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/content",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentMediaType:{type:"string"},contentEncoding:{type:"string"},contentSchema:{$recursiveRef:"#"}}}})),x8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/core",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{type:"string",format:"uri"},$anchor:{type:"string",pattern:"^[A-Za-z][-A-Za-z0-9.:_]*$"},$ref:{type:"string",format:"uri-reference"},$recursiveRef:{type:"string",format:"uri-reference"},$recursiveAnchor:{type:"boolean",default:!1},$vocabulary:{type:"object",propertyNames:{type:"string",format:"uri"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}}}}})),b8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/format",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:"Format vocabulary meta-schema",type:["object","boolean"],properties:{format:{type:"string"}}}})),w8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),k8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/validation",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},const:!0,enum:{type:"array",items:!0},type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),S8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=_8o(),r=y8o(),n=v8o(),o=x8o(),i=b8o(),s=w8o(),u=k8o(),l=["/properties"];function c(d){return[t,r,n,o,p(this,i),s,p(this,u)].forEach(m=>this.addMetaSchema(m,void 0,!1)),this;function p(m,h){return d?m.$dataMetaSchema(h,l):h}a(p,"with$data")}a(c,"addMetaSchema2019"),e.default=c})),I8o=st(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2019=void 0;let r=Gst(),n=P1r(),o=N1r(),i=L1r(),s=B1r(),u=Kst(),l=S8o(),c="https://json-schema.org/draft/2019-09/schema";var d=class extends r.default{static{a(this,"Ajv2019")}constructor(y={}){super({...y,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(o.default),n.default.forEach(y=>this.addVocabulary(y)),this.addVocabulary(i.default),this.addVocabulary(s.default),this.opts.discriminator&&this.addKeyword(u.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:y,meta:v}=this.opts;v&&(l.default.call(this,y),this.refs["http://json-schema.org/schema"]=c)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}};e.Ajv2019=d,t.exports=e=d,t.exports.Ajv2019=d,Object.defineProperty(e,"__esModule",{value:!0}),e.default=d;var p=xq();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:a(function(){return p.KeywordCxt},"get")});var m=Ko();Object.defineProperty(e,"_",{enumerable:!0,get:a(function(){return m._},"get")}),Object.defineProperty(e,"str",{enumerable:!0,get:a(function(){return m.str},"get")}),Object.defineProperty(e,"stringify",{enumerable:!0,get:a(function(){return m.stringify},"get")}),Object.defineProperty(e,"nil",{enumerable:!0,get:a(function(){return m.nil},"get")}),Object.defineProperty(e,"Name",{enumerable:!0,get:a(function(){return m.Name},"get")}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:a(function(){return m.CodeGen},"get")});var h=cre();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:a(function(){return h.default},"get")});var _=bq();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:a(function(){return _.default},"get")})})),T8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=k1r(),r=S1r(),n=E1r(),o=N1r(),i=L1r(),s=B1r(),u=A1r(),l=R1r(),c=[o.default,t.default,r.default,(0,n.default)(!0),u.default,l.metadataVocabulary,l.contentVocabulary,i.default,s.default];e.default=c})),C8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}})),E8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}})),A8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}})),R8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}})),P8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}})),M8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}})),O8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),D8o=st(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),N8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=C8o(),r=E8o(),n=A8o(),o=R8o(),i=P8o(),s=M8o(),u=O8o(),l=D8o(),c=["/properties"];function d(p){return[t,r,n,o,i,m(this,s),u,m(this,l)].forEach(h=>this.addMetaSchema(h,void 0,!1)),this;function m(h,_){return p?h.$dataMetaSchema(_,c):_}a(m,"with$data")}a(d,"addMetaSchema2020"),e.default=d})),L8o=st(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2020=void 0;let r=Gst(),n=T8o(),o=Kst(),i=N8o(),s="https://json-schema.org/draft/2020-12/schema";var u=class extends r.default{static{a(this,"Ajv2020")}constructor(m={}){super({...m,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),n.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:m,meta:h}=this.opts;h&&(i.default.call(this,m),this.refs["http://json-schema.org/schema"]=s)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv2020=u,t.exports=e=u,t.exports.Ajv2020=u,Object.defineProperty(e,"__esModule",{value:!0}),e.default=u;var l=xq();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:a(function(){return l.KeywordCxt},"get")});var c=Ko();Object.defineProperty(e,"_",{enumerable:!0,get:a(function(){return c._},"get")}),Object.defineProperty(e,"str",{enumerable:!0,get:a(function(){return c.str},"get")}),Object.defineProperty(e,"stringify",{enumerable:!0,get:a(function(){return c.stringify},"get")}),Object.defineProperty(e,"nil",{enumerable:!0,get:a(function(){return c.nil},"get")}),Object.defineProperty(e,"Name",{enumerable:!0,get:a(function(){return c.Name},"get")}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:a(function(){return c.CodeGen},"get")});var d=cre();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:a(function(){return d.default},"get")});var p=bq();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:a(function(){return p.default},"get")})})),B8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(P,D){return{validate:P,compare:D}}a(t,"fmtDef"),e.fullFormats={date:t(i,s),time:t(l(!0),c),"date-time":t(m(!0),h),"iso-time":t(l(),d),"iso-date-time":t(m(),_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:x,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:O,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:b,int32:{type:"number",validate:I},int64:{type:"number",validate:C},float:{type:"number",validate:R},double:{type:"number",validate:R},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,s),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,d),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,_),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(P){return P%4===0&&(P%100!==0||P%400===0)}a(r,"isLeapYear");let n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(P){let D=n.exec(P);if(!D)return!1;let U=+D[1],L=+D[2],G=+D[3];return L>=1&&L<=12&&G>=1&&G<=(L===2&&r(U)?29:o[L])}a(i,"date");function s(P,D){if(P&&D)return P>D?1:P<D?-1:0}a(s,"compareDate");let u=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(P){return a(function(U){let L=u.exec(U);if(!L)return!1;let G=+L[1],K=+L[2],Y=+L[3],Q=L[4],X=L[5]==="-"?-1:1,q=+(L[6]||0),j=+(L[7]||0);if(q>23||j>59||P&&!Q)return!1;if(G<=23&&K<=59&&Y<60)return!0;let ee=K-j*X,F=G-q*X-(ee<0?1:0);return(F===23||F===-1)&&(ee===59||ee===-1)&&Y<61},"time")}a(l,"getTime");function c(P,D){if(!(P&&D))return;let U=new Date("2020-01-01T"+P).valueOf(),L=new Date("2020-01-01T"+D).valueOf();if(U&&L)return U-L}a(c,"compareTime");function d(P,D){if(!(P&&D))return;let U=u.exec(P),L=u.exec(D);if(U&&L)return P=U[1]+U[2]+U[3],D=L[1]+L[2]+L[3],P>D?1:P<D?-1:0}a(d,"compareIsoTime");let p=/t|\s/i;function m(P){let D=l(P);return a(function(L){let G=L.split(p);return G.length===2&&i(G[0])&&D(G[1])},"date_time")}a(m,"getDateTime");function h(P,D){if(!(P&&D))return;let U=new Date(P).valueOf(),L=new Date(D).valueOf();if(U&&L)return U-L}a(h,"compareDateTime");function _(P,D){if(!(P&&D))return;let[U,L]=P.split(p),[G,K]=D.split(p),Y=s(U,G);if(Y!==void 0)return Y||c(L,K)}a(_,"compareIsoDateTime");let y=/\/|:/,v=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function x(P){return y.test(P)&&v.test(P)}a(x,"uri");let w=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function b(P){return w.lastIndex=0,w.test(P)}a(b,"byte");let k=-(2**31),S=2**31-1;function I(P){return Number.isInteger(P)&&P<=S&&P>=k}a(I,"validateInt32");function C(P){return Number.isInteger(P)}a(C,"validateInt64");function R(){return!0}a(R,"validateNumber");let A=/[^\\]\\Z/;function O(P){if(A.test(P))return!1;try{return new RegExp(P),!0}catch{return!1}}a(O,"regex")})),j8o=st((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=M1r(),r=Ko(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},i={message:a(({keyword:u,schemaCode:l})=>(0,r.str)`should be ${o[u].okStr} ${l}`,"message"),params:a(({keyword:u,schemaCode:l})=>(0,r._)`{comparison: ${o[u].okStr}, limit: ${l}}`,"params")};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:i,code(u){let{gen:l,data:c,schemaCode:d,keyword:p,it:m}=u,{opts:h,self:_}=m;if(!h.validateFormats)return;let y=new t.KeywordCxt(m,_.RULES.all.format.definition,"format");y.$data?v():x();function v(){let b=l.scopeValue("formats",{ref:_.formats,code:h.code.formats}),k=l.const("fmt",(0,r._)`${b}[${y.schemaCode}]`);u.fail$data((0,r.or)((0,r._)`typeof ${k} != "object"`,(0,r._)`${k} instanceof RegExp`,(0,r._)`typeof ${k}.compare != "function"`,w(k)))}a(v,"validate$DataFormat");function x(){let b=y.schema,k=_.formats[b];if(!k||k===!0)return;if(typeof k!="object"||k instanceof RegExp||typeof k.compare!="function")throw new Error(`"${p}": format "${b}" does not define "compare" function`);let S=l.scopeValue("formats",{key:b,ref:k,code:h.code.formats?(0,r._)`${h.code.formats}${(0,r.getProperty)(b)}`:void 0});u.fail$data(w(S))}a(x,"validateFormat");function w(b){return(0,r._)`${b}.compare(${c}, ${d}) ${o[p].fail} 0`}a(w,"compareCode")},dependencies:["format"]};let s=a(u=>(u.addKeyword(e.formatLimitDefinition),u),"formatLimitPlugin");e.default=s})),F8o=st(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let r=B8o(),n=j8o(),o=Ko(),i=new o.Name("fullFormats"),s=new o.Name("fastFormats"),u=a((c,d={keywords:!0})=>{if(Array.isArray(d))return l(c,d,r.fullFormats,i),c;let[p,m]=d.mode==="fast"?[r.fastFormats,s]:[r.fullFormats,i];return l(c,d.formats||r.formatNames,p,m),d.keywords&&(0,n.default)(c),c},"formatsPlugin");u.get=(c,d="full")=>{let p=(d==="fast"?r.fastFormats:r.fullFormats)[c];if(!p)throw new Error(`Unknown format "${c}"`);return p};function l(c,d,p,m){var h,_;(h=(_=c.opts.code).formats)!==null&&h!==void 0||(_.formats=(0,o._)`require("ajv-formats/dist/formats").${m}`);for(let y of d)c.addFormat(y,p[y])}a(l,"addFormats"),t.exports=e=u,Object.defineProperty(e,"__esModule",{value:!0}),e.default=u})),j1r=M1r(),z8o=I8o(),U8o=L8o(),$8o=Dbe(F8o(),1),q8o=$8o.default;a(Vst,"createDefaultAjvInstance");Jst=class{static{a(this,"AjvJsonSchemaValidator")}_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(e){this._userAjv=e!==void 0,this._ajv=e}get ajv(){return this._ajv??=Vst(U8o.Ajv2020)}_engineFor(e){if(this._userAjv)return this.ajv;let t=uwr(e,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");return t==="2020-12"?this.ajv:t==="2019-09"?this._ajv2019??=Vst(z8o.Ajv2019):this._ajvDraft7??=Vst(j1r.Ajv)}getValidator(e){let t=this._engineFor(e),r="$id"in e&&typeof e.$id=="string"?t.getSchema(e.$id)??t.compile(e):t.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:t.errorsText(r.errors)}}},_as=j1r.Ajv});var z1r,U1r=T(()=>{F1r();z1r=!1});async function V8o(e){return(await Yst).getRandomValues(new Uint8Array(e))}async function G8o(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let o=await V8o(e-n.length);for(let i of o)i<r&&(n+=t[i%t.length])}return n}async function W8o(e){return await G8o(e)}async function H8o(e){let t=await(await Yst).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Qst(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await W8o(e),r=await H8o(t);return{code_verifier:t,code_challenge:r}}var Yst,$1r=T(()=>{Yst=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto);a(V8o,"getRandomValues");a(G8o,"random");a(W8o,"generateVerifier");a(H8o,"generateChallenge");a(Qst,"pkceChallenge")});function Z8o(e){let t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Xst(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Xst).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Xst(e.cause)}`:e.message:`${e}`}function q1r(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}function K8o(){let e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}var L1e,G1r,sut,Pa,ac,Su,wI,pf,XN,wq,N1e,B1e,mre,Iq,fre,XA,kq,Tq,Sq,dre,t2,eut,tut,rut,V1r,nut,out,pre,iut,aut,eL,W1r=T(()=>{Xet();L1e=class extends Event{static{a(this,"ErrorEvent")}constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(q1r(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(q1r(this),r)}};a(Z8o,"syntaxError");a(Xst,"flattenError");a(q1r,"inspectableError");G1r=a(e=>{throw TypeError(e)},"__typeError"),sut=a((e,t,r)=>t.has(e)||G1r("Cannot "+r),"__accessCheck"),Pa=a((e,t,r)=>(sut(e,t,"read from private field"),r?r.call(e):t.get(e)),"__privateGet"),ac=a((e,t,r)=>t.has(e)?G1r("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),"__privateAdd"),Su=a((e,t,r,n)=>(sut(e,t,"write to private field"),t.set(e,r),r),"__privateSet"),wI=a((e,t,r)=>(sut(e,t,"access private method"),r),"__privateMethod"),eL=class extends EventTarget{static{a(this,"EventSource")}constructor(t,r){var n,o;super(),ac(this,t2),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ac(this,pf),ac(this,XN),ac(this,wq),ac(this,N1e),ac(this,B1e),ac(this,mre),ac(this,Iq),ac(this,fre,null),ac(this,XA),ac(this,kq),ac(this,Tq,null),ac(this,Sq,null),ac(this,dre,null),ac(this,tut,async i=>{var s;Pa(this,kq).reset();let{body:u,redirected:l,status:c,headers:d}=i;if(c===204){wI(this,t2,pre).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Su(this,wq,new URL(i.url)):Su(this,wq,void 0),c!==200){wI(this,t2,pre).call(this,`Non-200 status code (${c})`,c);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){wI(this,t2,pre).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Pa(this,pf)===this.CLOSED)return;Su(this,pf,this.OPEN);let p=new Event("open");if((s=Pa(this,dre))==null||s.call(this,p),this.dispatchEvent(p),typeof u!="object"||!u||!("getReader"in u)){wI(this,t2,pre).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,h=u.getReader(),_=!0;do{let{done:y,value:v}=await h.read();v&&Pa(this,kq).feed(m.decode(v,{stream:!y})),y&&(_=!1,Pa(this,kq).reset(),wI(this,t2,iut).call(this))}while(_)}),ac(this,rut,i=>{Su(this,XA,void 0),!(i.name==="AbortError"||i.type==="aborted")&&wI(this,t2,iut).call(this,Xst(i))}),ac(this,nut,i=>{typeof i.id=="string"&&Su(this,fre,i.id);let s=new MessageEvent(i.event||"message",{data:i.data,origin:Pa(this,wq)?Pa(this,wq).origin:Pa(this,XN).origin,lastEventId:i.id||""});Pa(this,Sq)&&(!i.event||i.event==="message")&&Pa(this,Sq).call(this,s),this.dispatchEvent(s)}),ac(this,out,i=>{Su(this,mre,i)}),ac(this,aut,()=>{Su(this,Iq,void 0),Pa(this,pf)===this.CONNECTING&&wI(this,t2,eut).call(this)});try{if(t instanceof URL)Su(this,XN,t);else if(typeof t=="string")Su(this,XN,new URL(t,K8o()));else throw new Error("Invalid URL")}catch{throw Z8o("An invalid or illegal string was specified")}Su(this,kq,nve({onEvent:Pa(this,nut),onRetry:Pa(this,out)})),Su(this,pf,this.CONNECTING),Su(this,mre,3e3),Su(this,B1e,(n=r?.fetch)!=null?n:globalThis.fetch),Su(this,N1e,(o=r?.withCredentials)!=null?o:!1),wI(this,t2,eut).call(this)}get readyState(){return Pa(this,pf)}get url(){return Pa(this,XN).href}get withCredentials(){return Pa(this,N1e)}get onerror(){return Pa(this,Tq)}set onerror(t){Su(this,Tq,t)}get onmessage(){return Pa(this,Sq)}set onmessage(t){Su(this,Sq,t)}get onopen(){return Pa(this,dre)}set onopen(t){Su(this,dre,t)}addEventListener(t,r,n){let o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){let o=r;super.removeEventListener(t,o,n)}close(){Pa(this,Iq)&&clearTimeout(Pa(this,Iq)),Pa(this,pf)!==this.CLOSED&&(Pa(this,XA)&&Pa(this,XA).abort(),Su(this,pf,this.CLOSED),Su(this,XA,void 0))}};pf=new WeakMap,XN=new WeakMap,wq=new WeakMap,N1e=new WeakMap,B1e=new WeakMap,mre=new WeakMap,Iq=new WeakMap,fre=new WeakMap,XA=new WeakMap,kq=new WeakMap,Tq=new WeakMap,Sq=new WeakMap,dre=new WeakMap,t2=new WeakSet,eut=a(function(){Su(this,pf,this.CONNECTING),Su(this,XA,new AbortController),Pa(this,B1e)(Pa(this,XN),wI(this,t2,V1r).call(this)).then(Pa(this,tut)).catch(Pa(this,rut))},"connect_fn"),tut=new WeakMap,rut=new WeakMap,V1r=a(function(){var e;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Pa(this,fre)?{"Last-Event-ID":Pa(this,fre)}:void 0},cache:"no-store",signal:(e=Pa(this,XA))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},"getRequestOptions_fn"),nut=new WeakMap,out=new WeakMap,pre=a(function(e,t){var r;Pa(this,pf)!==this.CLOSED&&Su(this,pf,this.CLOSED);let n=new L1e("error",{code:t,message:e});(r=Pa(this,Tq))==null||r.call(this,n),this.dispatchEvent(n)},"failConnection_fn"),iut=a(function(e,t){var r;if(Pa(this,pf)===this.CLOSED)return;Su(this,pf,this.CONNECTING);let n=new L1e("error",{code:t,message:e});(r=Pa(this,Tq))==null||r.call(this,n),this.dispatchEvent(n),Su(this,Iq,setTimeout(Pa(this,aut),Pa(this,mre)))},"scheduleReconnect_fn"),aut=new WeakMap,eL.CONNECTING=0,eL.OPEN=1,eL.CLOSED=2;a(K8o,"getBaseURL")});function H1r(e,t,r){if(e!==void 0)return e.issuer===void 0?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e):ikr(e.issuer,t)?e:void 0}function ikr(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function akr(e){if(e==null)return!1;let t=e;return typeof t.tokens=="function"&&typeof t.clientInformation=="function"}async function Y8o(e,t,r){let{resourceMetadataUrl:n,scope:o}=tL(t.response);if(await rL(e,{serverUrl:t.serverUrl,resourceMetadataUrl:n,scope:o,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new Mp}function skr(e,t){return{token:a(async()=>(await e.tokens())?.access_token,"token"),onUnauthorized:a(async r=>Y8o(e,r,t),"onUnauthorized")}}function gut(e){return e?.authorization_response_iss_parameter_supported===!0}function _ut({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new fut("authorization_response",t,void 0);return}if(e!==t)throw new fut("authorization_response",t,e)}}function hre(...e){let t=new Set;for(let r of e)if(r)for(let n of r.split(/\s+/))n&&t.add(n);return t.size>0?[...t].join(" "):void 0}function Q8o(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let n of e.split(/\s+/))if(n&&!r.has(n))return!0;return!1}async function ukr(e,t,r,n,o){if(typeof e=="string")return{authorizationCode:e,iss:t};let i=e.get("iss")??void 0,s=e.get("code");if(s)return{authorizationCode:s,iss:i};let u=(await r.discoveryState?.())?.authorizationServerMetadata;if(!u)try{u=(await $1e(n,o)).authorizationServerMetadata}catch{u=void 0}if(!u)throw new Mp("Authorization callback failed and the issuer could not be verified");_ut({iss:i,expectedIssuer:u.issuer,issParameterSupported:gut(u)});let l=e.get("error");throw l?new xI(l,e.get("error_description")??l,e.get("error_uri")??void 0):new Mp("Authorization callback contained neither `code` nor `error`")}function X8o(e){return["client_secret_basic","client_secret_post","none"].includes(e)}function eBo(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&X8o(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function tBo(e,t,r,n){let{client_id:o,client_secret:i}=t;switch(e){case"client_secret_basic":rBo(o,i,r);return;case"client_secret_post":nBo(o,i,n);return;case"none":oBo(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function rBo(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function nBo(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function oBo(e,t){t.set("client_id",e)}function lkr(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function iBo(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!lkr(t.hostname))throw new okr(t.href);return t}function aBo(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||lkr(r.hostname))return"native"}return"web"}function sBo(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??aBo(t.redirect_uris)}}async function Z1r(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=tre.parse(JSON.parse(r));return xI.fromResponse(n)}catch(n){let o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new xI(Yv.ServerError,o)}}async function rL(e,t){try{return await dut(e,t)}catch(r){if(r instanceof xI){if(r.code===Yv.InvalidClient||r.code===Yv.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await dut(e,t);if(r.code===Yv.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await dut(e,t)}throw r}}function uBo(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:n,clientMetadata:o}=e,i=t||r?.scopes_supported?.join(" ")||o.scope;return i&&n?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&o.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}async function dut(e,{serverUrl:t,authorizationCode:r,iss:n,scope:o,resourceMetadataUrl:i,fetchFn:s,skipIssuerMetadataValidation:u,forceReauthorization:l}){let c=sBo(e),d=await e.discoveryState?.(),p,m,h,_,y=i;if(!y&&d?.resourceMetadataUrl&&(y=new URL(d.resourceMetadataUrl)),d?.authorizationServerUrl){if(m=d.authorizationServerUrl,p=d.resourceMetadata,h=d.authorizationServerMetadata??await pkr(m,{fetchFn:s,skipIssuerValidation:u}),!p)try{p=await ckr(t,{resourceMetadataUrl:y},s)}catch(P){if(P instanceof TypeError)throw P}(h!==d.authorizationServerMetadata||p!==d.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(m),resourceMetadataUrl:y?.toString(),resourceMetadata:p,authorizationServerMetadata:h})}else{let P=await $1e(t,{resourceMetadataUrl:y,fetchFn:s,skipIssuerMetadataValidation:u});m=P.authorizationServerUrl,h=P.authorizationServerMetadata,p=P.resourceMetadata,_={authorizationServerUrl:String(m),resourceMetadataUrl:y?.toString(),resourceMetadata:p,authorizationServerMetadata:h}}let v=h?.issuer??String(m),x={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let P=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(P===void 0){if(e.saveDiscoveryState!==void 0)throw new uut("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",v);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!ikr(P,v))throw new uut(P,v)}_&&await e.saveDiscoveryState?.(_);let w=await yut(t,e,p);w&&await e.saveResourceUrl?.(String(w));let b=uBo({requestedScope:o,resourceMetadata:p,authServerMetadata:h,clientMetadata:e.clientMetadata}),k=await Promise.resolve(e.clientInformation(x)),S=H1r(k,v,{canPersistStamp:e.saveClientInformation!==void 0});if(S===void 0&&k?.issuer&&e.saveClientInformation===void 0)throw new uut(k.issuer,v);if(S&&S.issuer===void 0&&(S={...S,issuer:v},await e.saveClientInformation?.(S,x)),!S){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let P=h?.client_id_metadata_document_supported===!0,D=e.clientMetadataUrl;if(D&&!lBo(D))throw new xI(Yv.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${D}`);if(P&&D)S={client_id:D,issuer:v},await e.saveClientInformation?.(S,x);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");S={...await _Bo(m,{metadata:h,clientMetadata:c,scope:b,fetchFn:s}),issuer:v},await e.saveClientInformation(S,x)}}let I=!e.redirectUrl;if(r!==void 0||I){r!==void 0&&_ut({iss:n,expectedIssuer:h?.issuer,issParameterSupported:gut(h)});let P=await gBo(e,m,{metadata:h,resource:w,authorizationCode:r,iss:n,scope:b,fetchFn:s});return await e.saveTokens({...P,issuer:v},x),"AUTHORIZED"}let C=H1r(await e.tokens(x),v);if(C&&C.issuer===void 0&&(C={...C,issuer:v},await e.saveTokens(C,x)),C?.refresh_token&&!l)try{let P=await vut(m,{metadata:h,clientInformation:S,refreshToken:C.refresh_token,resource:w,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens({...P,issuer:v},x),"AUTHORIZED"}catch(P){if(P instanceof okr||!(!(P instanceof xI)||P.code===Yv.ServerError))throw P}let R=e.state?await e.state():void 0,{authorizationUrl:A,codeVerifier:O}=await fBo(m,{metadata:h,clientInformation:S,state:R,redirectUrl:e.redirectUrl,scope:b,resource:w});return await e.saveCodeVerifier(O),await e.redirectToAuthorization(A),"REDIRECT"}function lBo(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function yut(e,t,r){let n=Pwr(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Mwr({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function tL(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!n)return{};let o=j1e(e,"resource_metadata")||void 0,i;if(o)try{i=new URL(o)}catch{}let s=j1e(e,"scope")||void 0,u=j1e(e,"error")||void 0,l=j1e(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:s,error:u,errorDescription:l}}function j1e(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),o=r.match(n);if(o){let i=o[1]||o[2];if(i)return i}return null}async function ckr(e,t,r=fetch){let n=await pBo(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.text?.().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Qte.parse(await n.json())}async function dkr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!z1r)throw n;if(t)try{return await r(e,{})}catch(o){if(!(o instanceof TypeError))throw o;return}return}}function cBo(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function K1r(e,t,r=fetch){return await dkr(e,{"MCP-Protocol-Version":t},r)}function dBo(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}async function pBo(e,t,r,n){let o=new URL(e),i=n?.protocolVersion??tq,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let l=cBo(t,o.pathname);s=new URL(l,n?.metadataServerUrl??o),s.search=o.search}let u=await K1r(s,i,r);return!n?.metadataUrl&&dBo(u,o.pathname)&&(u=await K1r(new URL(`/.well-known/${t}`,o),i,r)),u}function mBo(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"},{url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function pkr(e,{fetchFn:t=fetch,protocolVersion:r=tq,skipIssuerValidation:n=!1}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=mBo(e);for(let{url:s,type:u}of i){let l=await dkr(s,o,t);if(!l)continue;if(!l.ok){if(await l.text?.().catch(()=>{}),l.status>=400&&l.status<500||l.status===502)continue;throw new Error(`HTTP ${l.status} trying to load ${u==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}let c=u==="oauth"?hq.parse(await l.json()):Xte.parse(await l.json());if(!n){let d=typeof e=="string"?e:e.href;if(!(c.issuer===d||d.endsWith("/")&&c.issuer===d.slice(0,-1)))throw new fut("metadata",d,c.issuer)}return c}}async function $1e(e,t){let r,n;try{r=await ckr(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}n||(n=String(new URL("/",e)));let o=await pkr(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function fBo(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:s}){let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(lut))throw new Error(`Incompatible auth server: does not support response type ${lut}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(cut))throw new Error(`Incompatible auth server: does not support code challenge method ${cut}`)}else u=new URL("/authorize",e);let l=await Qst(),c=l.code_verifier,d=l.code_challenge;return u.searchParams.set("response_type",lut),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",d),u.searchParams.set("code_challenge_method",cut),u.searchParams.set("redirect_uri",String(n)),i&&u.searchParams.set("state",i),o&&u.searchParams.set("scope",o),o?.split(" ").includes("offline_access")&&u.searchParams.append("prompt","consent"),s&&u.searchParams.set("resource",s.href),{authorizationUrl:u,codeVerifier:c}}function hBo(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function mkr(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:s}){let u=iBo(t?.token_endpoint??new URL("/token",e)),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",i.href),o?await o(l,r,u,t):n&&tBo(eBo(n,t?.token_endpoint_auth_methods_supported??[]),n,l,r);let c=await(s??fetch)(u,{method:"POST",headers:l,body:r});if(!c.ok)throw await Z1r(c);let d=await c.json();try{return ere.parse(d)}catch(p){throw typeof d=="object"&&d!==null&&"error"in d?await Z1r(JSON.stringify(d)):p}}async function vut(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:s}){return{refresh_token:n,...await mkr(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:s})}}async function gBo(e,t,{metadata:r,resource:n,authorizationCode:o,iss:i,scope:s,fetchFn:u}={}){o!==void 0&&_ut({iss:i,expectedIssuer:r?.issuer,issParameterSupported:gut(r)});let l=s??e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(l)),!c){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");c=hBo(o,await e.codeVerifier(),e.redirectUrl)}let d=await e.clientInformation({issuer:r?.issuer??String(t)});return mkr(t,{metadata:r,tokenRequestParams:c,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:u})}async function _Bo(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s={...r,...n===void 0?{}:{scope:n}},u=await(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!u.ok)throw new J8o({status:u.status,body:await u.text(),submittedMetadata:s});return rre.parse(await u.json())}function put(e){return`${e.method}\0${JSON.stringify([e.partition??"",e.params??""])}`}function mut(e,t){return t===void 0?e:`${e}\0${t}`}function bBo(e){let t;try{t=JSON.stringify(e)}catch(r){throw new TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!="string")throw new TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}function Pp(e){if(typeof e=="object"&&e!==null||typeof e=="function")try{Object.defineProperty(e,hkr,{value:!0,configurable:!0})}catch{}return e}function wBo(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&e[hkr]===!0}function IBo(e,t){switch(e.kind){case"result":return TBo(e.result,t);case"rpc-error":return gkr(e,t);case"http-error":return CBo(e,t);case"network-error":return J1r(e.error,t);case"auth-required":return{kind:"error",error:e.error};case"closed":return t.transportKind==="stdio"?{kind:"legacy"}:J1r(new Error("Connection closed during the version negotiation probe"),t);case"timeout":return t.transportKind==="stdio"?{kind:"legacy"}:{kind:"error",error:new Xr(Ar.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function TBo(e,t){let r=vI(T1e).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let n=r.value.supportedVersions,o=t.clientModernVersions.find(i=>n.includes(i));return o!==void 0?{kind:"modern",version:o,discover:r.value}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:new yq({supported:[...n],requested:t.requestedVersion})}}function gkr(e,t){let{code:r,message:n,data:o}=e;if(r===kBo){let i=RBo(o);if(i===void 0)return{kind:"legacy"};let s=new yq({supported:i,requested:PBo(o)??t.requestedVersion},n),u=lre(i),l=t.clientModernVersions.find(c=>u.includes(c));return l!==void 0?{kind:"corrective",version:l,error:s}:u.length>0?{kind:"error",error:s}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:s}}return SBo.has(r)?{kind:"legacy"}:{kind:"legacy"}}function CBo(e,t){if(e.status===401||e.status===403){let n=e.status===403;return{kind:"error",error:new Qv(n?Ar.ClientHttpForbidden:Ar.ClientHttpAuthentication,`Version negotiation failed: ${n?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new Qv(Ar.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=MBo(e.body);return r!==void 0?gkr(r,t):{kind:"legacy"}}function J1r(e,t){return t.environment==="browser"&&EBo(e)?{kind:"legacy"}:{kind:"error",error:new Xr(Ar.EraNegotiationFailed,`Version negotiation probe failed: ${ABo(e)}`,{cause:e})}}function EBo(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function ABo(e){return e instanceof Error?e.message:String(e)}function RBo(e){if(typeof e!="object"||e===null)return;let t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(r=>typeof r=="string")))return t}function PBo(e){if(typeof e!="object"||e===null)return;let t=e.requested;return typeof t=="string"?t:void 0}function MBo(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let r=t.error;if(typeof r!="object"||r===null)return;let{code:n,message:o,data:i}=r;if(typeof n=="number")return{code:n,message:typeof o=="string"?o:"",data:i}}function DBo(e,t){let r=e?.mode??OBo;if(r==="legacy")return{kind:"legacy"};let n=e?.probe??{};if(typeof r=="object"){if(!bI(r.pin))throw new TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision \u2014 pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:n}}let o=t?lre(t):[];return{kind:"auto",modernVersions:o.length>0?o:[...Est],fallbackAvailable:t?Ast(t).length>0:!0,probe:n}}function Y1r(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Q1r(e){return"stderr"in e&&"pid"in e?"stdio":"http"}function X1r(e){let t=hut.get(e);hut.delete(e),t?.()}function LBo(e,t,r,n){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:vI(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:n})}}}function BBo(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(wBo(r)||r instanceof Mp||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof Qv){let n=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof n=="string"?n:void 0,statusText:r.data.statusText}}return{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function ykr(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,n=Math.max(0,e.probe.maxRetries??0),o=e.kind==="pin"?[e.version]:e.modernVersions,i=e.kind==="auto"&&e.fallbackAvailable,s=await NBo.open(t.transport),u=a(async()=>{let c=o[0],d=!1,p=n;for(;;){let m=await s.exchange(y=>LBo(y,c,t.clientInfo,t.capabilities),r);if(m.kind==="timeout"&&p>0){p--;continue}let h=BBo(m,r),_=IBo(h,{clientModernVersions:o,requestedVersion:c,fallbackAvailable:i,environment:t.environment,transportKind:t.transportKind});switch(_.kind){case"modern":return{era:"modern",version:_.version,discover:_.discover};case"corrective":if(d)throw _.error;d=!0,c=_.version;continue;case"legacy":{let y=h.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new Xr(Ar.EraNegotiationFailed,y===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${y} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new Xr(Ar.EraNegotiationFailed,y===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${y} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(y!==void 0&&t.disposableProbe!==!0)throw new Xr(Ar.EraNegotiationFailed,`Version negotiation failed: ${y} (this transport probed in place \u2014 the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw _.error}}},"probe"),l;try{l=await u()}catch(c){throw s.detach(),c}return s.release(),l}function jBo(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r=="object"&&r!==null&&typeof r.command=="string"?r:void 0}async function FBo(e,t,r,n){let o=t.constructor,i=new o({...r,stderr:"ignore"}),s=t.close,u=!1,l,c=new Promise((p,m)=>{l=a(()=>m(ekr()),"signalClosed")});t.close=async function(){return u=!0,l?.(),s.call(t)};let d;try{let p=ykr(e,{...n,transport:i,transportKind:"stdio",disposableProbe:!0});p.catch(()=>{}),d=await Promise.race([p,c])}finally{await zBo(i),t.close=s}if(u)throw ekr();return d}function ekr(){return new Xr(Ar.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function zBo(e){try{let t=e._dispose;await(typeof t=="function"?t.call(e):e.close())}catch{}}function tkr(e){let t=e._meta?.[_I];return d1r.Implementation(t)?t:void 0}function z1e(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let o of Object.keys(n)){let i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&z1e(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&z1e(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&z1e(r,t)}}function UBo(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function $Bo(e){if(typeof e=="object"&&e!==null&&(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e)||e.kind==="modern"&&KN.safeParse(e.discover).success))return e;throw new Xr(Ar.EraNegotiationFailed,"connect({ prior }): unrecognized prior \u2014 expected { kind: 'modern', discover } or { kind: 'legacy' }")}function nkr(e,t){if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let n=a(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",i)},"cleanup");function o(){n(),r.abort(e.reason)}a(o,"onA");function i(){n(),r.abort(t.reason)}return a(i,"onB"),e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",i,{once:!0}),r.signal}var gre,fut,J8o,okr,uut,U1e,Mp,lut,cut,fkr,F1e,yBo,vBo,xBo,hkr,kBo,SBo,OBo,NBo,hut,rkr,qBo,vkr,VBo,xkr,GBo,WBo,HBo,bkr,_re=T(()=>{qst();U1r();$1r();W1r();ove();gre=class extends Error{static{a(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Ah(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ah(this,e)}constructor(e){super(e),this.name=new.target.name,YN(this,new.target)}},fut=class extends gre{static{a(this,"IssuerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},J8o=class extends gre{static{a(this,"RegistrationRejectedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},okr=class extends gre{static{a(this,"InsecureTokenEndpointError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},uut=class extends gre{static{a(this,"AuthorizationServerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(e)}, callback resolved ${JSON.stringify(t)}); refusing to send authorization_code/code_verifier to a different token endpoint`),this.recordedIssuer=e,this.currentIssuer=t}},U1e=class extends gre{static{a(this,"InsufficientScopeError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};a(H1r,"discardIfIssuerMismatch");a(ikr,"issuersMatch");a(akr,"isOAuthClientProvider");a(Y8o,"handleOAuthUnauthorized");a(skr,"adaptOAuthProvider");Mp=class extends Error{static{a(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Ah(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ah(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",YN(this,new.target)}};a(gut,"isIssParameterSupported");a(_ut,"validateAuthorizationResponseIssuer");a(hre,"computeScopeUnion");a(Q8o,"isStrictScopeSuperset");a(ukr,"resolveAuthorizationCallbackParams");a(X8o,"isClientAuthMethod");lut="code",cut="S256";a(eBo,"selectClientAuthMethod");a(tBo,"applyClientAuthentication");a(rBo,"applyBasicAuth");a(nBo,"applyPostAuth");a(oBo,"applyPublicAuth");a(lkr,"isLoopbackHost");a(iBo,"assertSecureTokenEndpoint");a(aBo,"deriveApplicationType");a(sBo,"resolveClientMetadata");a(Z1r,"parseErrorResponse");a(rL,"auth");a(uBo,"determineScope");a(dut,"authInternal");a(lBo,"isHttpsUrl");a(yut,"selectResourceURL");a(tL,"extractWWWAuthenticateParams");a(j1e,"extractFieldFromWwwAuth");a(ckr,"discoverOAuthProtectedResourceMetadata");a(dkr,"fetchWithCorsRetry");a(cBo,"buildWellKnownPath");a(K1r,"tryMetadataDiscovery");a(dBo,"shouldAttemptFallback");a(pBo,"discoverMetadataWithFallback");a(mBo,"buildDiscoveryUrls");a(pkr,"discoverAuthorizationServerMetadata");a($1e,"discoverOAuthServerInfo");a(fBo,"startAuthorization");a(hBo,"prepareAuthorizationCodeRequest");a(mkr,"executeTokenRequest");a(vut,"refreshAuthorization");a(gBo,"fetchToken");a(_Bo,"registerClient");fkr=class{static{a(this,"ClientCredentialsProvider")}_tokens;_clientInfo;_clientMetadata;constructor(e){this._clientInfo={client_id:e.clientId,client_secret:e.clientSecret,issuer:e.expectedIssuer},this._clientMetadata={client_name:e.clientName??"client-credentials-client",redirect_uris:[],grant_types:["client_credentials"],token_endpoint_auth_method:"client_secret_basic",scope:e.scope}}get redirectUrl(){}get clientMetadata(){return this._clientMetadata}clientInformation(){return this._clientInfo}tokens(){return this._tokens}saveTokens(e){this._tokens=e}redirectToAuthorization(){throw new Error("redirectToAuthorization is not used for client_credentials flow")}saveCodeVerifier(){}codeVerifier(){throw new Error("codeVerifier is not used for client_credentials flow")}prepareTokenRequest(e){let t=new URLSearchParams({grant_type:"client_credentials"});return e&&t.set("scope",e),t}},F1e=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),yBo=class{static{a(this,"InMemoryResponseCacheStore")}_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(put(e))}set(e,t){let r=put(e),n=F1e.has(e.method),o=!this._entries.has(r);if(!n&&o&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let s of this._entries.keys())if(!F1e.has(s.slice(0,s.indexOf("\0")))){this._entries.delete(s),this._cappedSize--;break}}let i=++this._stamp;return this._entries.set(r,{...t,stamp:i}),o&&!n&&this._cappedSize++,i}delete(e){this._entries.delete(put(e))&&!F1e.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,r=F1e.has(e);for(let n of this._entries.keys())n.startsWith(t)&&(this._entries.delete(n),r||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};a(put,"keyOf");a(mut,"genKey");vBo=864e5,xBo=class{static{a(this,"ClientResponseCache")}_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},n="",o=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=n,this._now=o}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},n=this._partitionFor("private"),o=await this._store.get({...r,partition:n});if(o!==void 0)return o;let i=this._partitionFor("public");if(i===n)return;let s=await this._store.get({...r,partition:i});return s?.scope==="public"?s:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),n=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(o){this._reportError(o)}if(n!==r)try{await this._store.delete({method:e,params:t,partition:n})}catch(o){this._reportError(o)}}async evictKey(e,t){let r=mut(e,t),n=this._evictionGeneration.get(r);n!==void 0&&this._evictionGeneration.set(r,n+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let r=mut(e,t),n=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,n),n}async write(e,t,r,n){if((this._evictionGeneration.get(mut(e,n?.params))??0)!==r)return;let o=n?.params??"",i=this._partitionFor("private"),s=this._partitionFor("public"),u=(n?.scope??"private")==="public"?s:i;try{await this._store.set({method:e,params:o,partition:u},{value:bBo(t),expiresAt:n?.expiresAt,scope:n?.scope})}catch(l){this._reportError(l)}if(s!==i)try{await this._store.delete({method:e,params:o,partition:u===i?s:i})}catch(l){this._reportError(l)}}async read(e,t){let r=await this._probe(e,t);if(!(r?.expiresAt===void 0||!(r.expiresAt>this.now())))try{let n=JSON.parse(r.value);if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("cached document is not an object");return{value:n}}catch(n){this._reportError(n),await this._deleteBoth(e,t??"");return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),n=new Map;if(r!==void 0)for(let o of r.tools)n.set(o.name,o);this._toolIndex={stamp:t.stamp,byName:n}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let n=this._decodeListTools(r)??{tools:[]},o=new Map;for(let i of n.tools){let s=t(i);s!==void 0&&o.set(i.name,s)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:o}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(r=>r!==null&&typeof r=="object"))throw new TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};a(bBo,"encodeCacheValue");hkr=Symbol.for("mcp.authSeamEscape");a(Pp,"markAuthSeamEscape");a(wBo,"isAuthSeamEscape");kBo=-32022,SBo=new Set([-32001,-32020,-32021]);a(IBo,"classifyProbeOutcome");a(TBo,"classifyResult");a(gkr,"classifyRpcError");a(CBo,"classifyHttpError");a(J1r,"classifyNetworkError");a(EBo,"isOpaqueFetchTypeError");a(ABo,"describeError");a(RBo,"parseSupportedList");a(PBo,"parseRequested");a(MBo,"parseJsonRpcErrorBody");OBo="legacy";a(DBo,"resolveVersionNegotiation");a(Y1r,"detectProbeEnvironment");a(Q1r,"detectProbeTransportKind");NBo=class _kr{static{a(this,"ProbeWindow")}_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new _kr(t);t.onmessage=n=>{let o=r._pending;if(o!==void 0&&(_q(n)||vq(n))&&n.id===o.id){r._pending=void 0,_q(n)?o.resolve({kind:"response",result:n.result}):o.resolve({kind:"response",error:n.error});return}},t.onerror=n=>{r._savedOnError?.(n)},t.onclose=()=>{let n=r._pending;n!==void 0&&(r._pending=void 0,n.resolve({kind:"closed"})),r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(n){throw r.detach(),n}return r}async exchange(t,r){let n=`server-discover-probe-${++this._probeCounter}`;return new Promise(o=>{let i=!1,s=a(l=>{i||(i=!0,clearTimeout(u),this._pending?.id===n&&(this._pending=void 0),o(l))},"settle"),u=setTimeout(()=>s({kind:"timeout"}),r);this._pending={id:n,resolve:s},this._transport.send(t(n)).catch(l=>s({kind:"send-error",error:l}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,n=!1,o=a(()=>{if(!n){n=!0;return}t()},"wrapper");r.onclose=o,hut.set(r,()=>{r.onclose===o&&(r.onclose=t)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,n=!0;t.start=async function(){if(n){n=!1,t.start=r;return}return r.call(t)}}},hut=new WeakMap;a(X1r,"disarmSpentCloseGuard");a(LBo,"buildProbeRequest");a(BBo,"normalizeReply");a(ykr,"negotiateEra");a(jBo,"readStdioServerParams");a(FBo,"negotiateStdioViaSibling");a(ekr,"callerCloseAbortError");a(zBo,"disposeSibling");a(tkr,"serverInfoFromDiscover");a(z1e,"applyElicitationDefaults");a(UBo,"getSupportedElicitationModes");a($Bo,"validatePrior");rkr={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},qBo=64,vkr=class extends p1r{static{a(this,"Client")}_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new Xr(Ar.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Jst,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=s1r(t?.inputRequired),this._cache=new xBo(t?.responseCacheStore??new yBo,t?.responseCacheStore!==void 0,r=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??qBo,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&bI(this._negotiatedProtocolVersion)&&QN(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?f1r({getRequestHandler:a(r=>this._getRequestHandler(r),"getRequestHandler"),buildContext:a(r=>this.buildContext(r,void 0),"buildContext"),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new Xr(Ar.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance \u2014 pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=m1r(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw new Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){return e==="elicitation/create"?async(r,n)=>{let o=vI(this._negotiatedProtocolVersion),i=o.validateRequest("elicitation/create",r);if(!i.ok&&i.reason==="not-in-era"&&(i=o.validateInputRequest("elicitation/create",r)),!i.ok)throw new os(i.reason==="not-in-era"?Kn.InternalError:Kn.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);let{params:s}=i.value;s.mode=s.mode??"form";let{supportsFormMode:u,supportsUrlMode:l}=UBo(this._capabilities.elicitation);if(s.mode==="form"&&!u)throw new os(Kn.InvalidParams,"Client does not support form-mode elicitation requests");if(s.mode==="url"&&!l)throw new os(Kn.InvalidParams,"Client does not support URL-mode elicitation requests");let c=await t(r,n),d=o.validateResult("elicitation/create",c);if(!d.ok&&d.reason==="not-in-era"&&(d=o.validateInputResponse("elicitation/create",c)),!d.ok)throw new os(d.reason==="not-in-era"?Kn.InternalError:Kn.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let p=d.value,m=s.mode==="form"?s.requestedSchema:void 0;if(s.mode==="form"&&p.action==="accept"&&p.content&&m&&this._capabilities.elicitation?.form?.applyDefaults)try{z1e(m,p.content)}catch{}return p}:e==="sampling/createMessage"?async(r,n)=>{let o=vI(this._negotiatedProtocolVersion),i=o.validateRequest("sampling/createMessage",r);if(!i.ok&&i.reason==="not-in-era"&&(i=o.validateInputRequest("sampling/createMessage",r)),!i.ok)throw new os(i.reason==="not-in-era"?Kn.InternalError:Kn.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);let{params:s}=i.value,u=await t(r,n),l=!!(s.tools||s.toolChoice),c=o.samplingResultVariant(l,u);if(!c.ok&&c.reason==="not-in-era"&&(c=o.validateInputResponse("sampling/createMessage",u)),!c.ok)throw new os(c.reason==="not-in-era"?Kn.InternalError:Kn.InvalidParams,c.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${c.message}`);return c.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Xr(Ar.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,$Bo(t.prior),t);let r=DBo(this._versionNegotiation,this._supportedProtocolVersionsOption);return r.kind!=="legacy"?this._connectNegotiated(e,r,t):this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;r!==void 0&&e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=Ast(this._supportedProtocolVersions);try{let n=r[0];if(n===void 0)throw new Xr(Ar.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let o=await this.request({method:"initialize",params:{protocolVersion:n,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!r.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=o.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(n){throw this.close(),n}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let o=this._negotiatedProtocolVersion;o!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(o);return}this._resetConnectionState();let n;try{let o=Q1r(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Y1r(),defaultTimeoutMs:r?.timeout??E1e},s=o==="stdio"?jBo(e):void 0;n=s===void 0?await ykr(t,{...i,transport:e,transportKind:o}):await FBo(t,e,s,i)}catch(o){throw await e.close().catch(()=>{}),X1r(e),o}if(X1r(e),await super.connect(e),n.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=n.discover.capabilities,this._serverVersion=tkr(n.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=n.discover.instructions,this._discoverResult=n.discover,this._negotiatedProtocolVersion=n.version,e.setProtocolVersion&&e.setProtocolVersion(n.version),this._listChangedConfig){let o=this._listChangedConfig,i=this._serverCapabilities,s={...o.tools&&i?.tools?.listChanged&&{tools:o.tools},...o.prompts&&i?.prompts?.listChanged&&{prompts:o.prompts},...o.resources&&i?.resources?.listChanged&&{resources:o.resources}},u=!0;try{this._setupListChangedHandlers(s)}catch(c){u=!1,this.onerror?.(c instanceof Error?c:new Error(String(c)))}let l=u?{...s.tools&&{toolsListChanged:!0},...s.prompts&&{promptsListChanged:!0},...s.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(l).length>0){let c=new AbortController,d=a(()=>c.abort(r?.signal?.reason),"onConnectAbort");r?.signal?.aborted&&d(),r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(l,{timeout:r?.timeout,signal:c.signal})}catch(p){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),p;this.onerror?.(p instanceof Error?p:new Error(String(p)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let n=t.discover;this._resetConnectionState();let o=this._supportedProtocolVersionsOption,i=(o&&lre(o).length>0?lre(o):Est).find(s=>n.supportedVersions.includes(s));if(i===void 0)throw new Xr(Ar.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=n,this._serverCapabilities=n.capabilities,this._serverVersion=tkr(n),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=n.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(s){this.onerror?.(s instanceof Error?s:new Error(String(s)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t!==void 0?`${t.name}@${t.version}`:e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return bI(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Xr(Ar.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Xr(Ar.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Xr(Ar.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Xr(Ar.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Xr(Ar.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Xr(Ar.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Xr(Ar.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Xr(Ar.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Xr(Ar.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Xr(Ar.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},KN,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);return r!==void 0?r:this._listAllPages("prompts/list",e,t,(n,o)=>n.prompts.push(...o.prompts))}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/list",e,t,(n,o)=>n.resources.push(...o.resources))}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/templates/list",e,t,(n,o)=>n.resourceTemplates.push(...o.resourceTemplates))}async _listAllPages(e,t,r,n,o){let i=r?.cacheMode==="bypass",s=this._cache.captureGeneration(e),u=await this.request({method:e,...t&&{params:{...t}}},r),l=u.nextCursor,c=new Set,d=1;for(;l!==void 0&&!c.has(l);){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new Xr(Ar.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});c.add(l);let p=await this.request({method:e,params:{...t,cursor:l}},r);n(u,p),l=p.nextCursor,d++}return delete u.nextCursor,o?.(u),i||await this._cache.write(e,u,s,this._freshness(u)),u}_freshness(e,t){let r=e,n=typeof r.ttlMs=="number"?r.ttlMs:this._defaultCacheTtlMs,o=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,n),vBo),scope:o,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let n=await this._cache.read(e,t).catch(o=>void this._reportStoreError(o));if(n!==void 0){if(r?.signal?.aborted){let o=r.signal.reason;throw o instanceof Xr?o:new Xr(Ar.RequestTimeout,String(o))}return n.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:Lst(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let n=this._cache.captureGeneration("resources/read",e.uri),o=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let i=this._freshness(o,e.uri);i.expiresAt>this._cache.now()?await this._cache.write("resources/read",o,n,i):t?.cacheMode==="refresh"&&await this._cache.evictKey("resources/read",e.uri)}return o}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new Xr(Ar.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!bI(r))throw new Xr(Ar.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let w=t.signal.reason;throw w instanceof Xr?w:new Xr(Ar.RequestTimeout,String(w))}let n=new AbortController,o=`listen:${this._nextListenId++}`,i="opening",s,u,l,c,d=new Promise((w,b)=>{l=w,c=b}),p,m=new Promise(w=>{p=w}),h=a(w=>{if(i==="closed")return;let b=i==="opening";if(s!==void 0&&(clearTimeout(s),s=void 0),"ack"in w){i="open",l(w.ack);return}i="closed",u!==void 0&&t?.signal?.removeEventListener("abort",u),this._listenState.delete(o),n.abort(),p(w.cause),b&&c(w.error??new Xr(Ar.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},"settle"),_=a(async()=>{n.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:o}}).catch(()=>{})},"wireTeardown"),y=a(async()=>{i!=="closed"&&(h({cause:"local"}),await _())},"close");this._listenState.set(o,{settle:h});let v=t?.timeout??E1e;if(s=setTimeout(()=>{h({cause:"remote",error:new Xr(Ar.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),_().catch(()=>{})},v),t?.signal){let w=t.signal;u=a(()=>{if(i==="closed")return;let b=w.reason;h({cause:"local",error:b instanceof Error?b:new Error(String(b??"Aborted"))}),_().catch(()=>{})},"onCallerAbort"),w.addEventListener("abort",u,{once:!0})}let x={jsonrpc:"2.0",id:o,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}};try{await this.transport.send(x,{requestSignal:n.signal,onRequestStreamEnd:a(()=>h({cause:"remote",error:new Error("subscriptions/listen: stream ended")}),"onRequestStreamEnd")})}catch(w){h({cause:"remote",error:w instanceof Error?w:new Error(String(w))})}return{honoredFilter:await d,close:y,closed:m}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(rkr,e.method)?rkr[e.method]:void 0;if(e.method==="notifications/resources/updated"){let n=e.params?.uri;typeof n=="string"&&this._cache.evictKey("resources/read",n)}else if(r!==void 0)for(let n of r)this._cache.evict(n);if(e.method==="notifications/subscriptions/acknowledged"){let n=e.params?._meta?.[wte],o=typeof n=="string"?this._listenState.get(n):void 0;if(o!==void 0){let i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);o.settle({ack:i.ok?i.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let n=e.params?.requestId,o=typeof n=="string"?this._listenState.get(n):void 0;if(o!==void 0){o.settle({cause:"remote",error:new Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t=="string"?this._listenState.get(t):void 0;if(r!==void 0){vq(e)?r.settle({cause:"remote",error:os.fromError(e.error.code,e.error.message,e.error.data)}):r.settle({cause:"graceful",error:new Xr(Ar.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new Xr(Ar.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&Y1r()!=="browser",n=a(async()=>{if(!r)return t;let l;try{l=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!l?.valid||l.declarations.length===0)return t;let c=i1r(l.declarations,e.arguments);return Object.keys(c).length===0?t:{...t,headers:{...t?.headers,...c}}},"buildSendOptions"),o=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,l=>this._compileOutputValidator(l)).catch(l=>void this._reportStoreError(l)):this._compileOutputValidator(t.toolDefinition),i=a(()=>{if(o===void 0||o.ok)return;let l=o.compileError,c=(l instanceof Error?l.message:String(l)).slice(0,200);throw new os(Kn.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${c}`)},"assertCompiled");i();let s;try{s=await this.request({method:"tools/call",params:e},await n())}catch(l){let c=l instanceof os&&l.code===gq;if(!r||!c||t?.toolDefinition!==void 0)throw l;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch(p=>this._reportStoreError(p)),o=await this._cache.outputValidator(e.name,p=>this._compileOutputValidator(p)).catch(p=>void this._reportStoreError(p)),i(),s=await this.request({method:"tools/call",params:e},await n())}let u=o!==void 0&&o.ok?o.validator:void 0;if(u){if(s.structuredContent===void 0&&!s.isError)throw new os(Kn.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent!==void 0&&!s.isError)try{let l=u(s.structuredContent);if(!l.valid)throw new os(Kn.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){throw l instanceof os?l:new os(Kn.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return s}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let n=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(n),n}let r=await this._serveFromCache("tools/list",void 0,t);return r!==void 0?r:this._listAllPages("tools/list",e,t,(n,o)=>n.tools.push(...o.tools),n=>this._excludeInvalidXMcpHeaderTools(n))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||Q1r(this.transport)==="stdio")return;let t=e.tools.filter(r=>{let n=Lst(r.inputSchema);return n.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration \u2014 ${n.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,r,n){let o=C1e(qte,r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:s}=o.data,{onChanged:u}=r,l=a(async()=>{if(!i){u(null,null);return}try{u(null,await n())}catch(d){u(d instanceof Error?d:new Error(String(d)),null)}},"refresh"),c=a(()=>{if(s){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let p=setTimeout(l,s);this._listChangedDebounceTimers.set(e,p)}else l()},"handler");this.setNotificationHandler(t,c)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}},VBo=class extends Error{static{a(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Ah(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ah(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,YN(this,new.target)}},xkr=class{static{a(this,"SSEClientTransport")}_eventSource;_endpoint;_abortController;_url;_resourceMetadataUrl;_scope;_eventSourceInit;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_protocolVersion;onclose;onerror;onmessage;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,akr(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=skr(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=$st(t?.fetch,t?.requestInit)}_last401Response;async _commonHeaders(){let e={},t;try{t=await this._authProvider?.token()}catch(n){throw Pp(n)}t&&(e.Authorization=`Bearer ${t}`),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=ure(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,r)=>{this._eventSource=new eL(this._url.href,{...this._eventSourceInit,fetch:a(async(n,o)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let s=await e(n,{...o,headers:i});if(s.status===401&&(this._last401Response=s,s.headers.has("www-authenticate"))){let{resourceMetadataUrl:u,scope:l}=tL(s);this._resourceMetadataUrl=u,this._scope=l}return s},"fetch")}),this._abortController=new AbortController,this._eventSource.onerror=n=>{if(n.code===401&&this._authProvider){if(this._authProvider.onUnauthorized&&this._last401Response){let s=this._last401Response;this._last401Response=void 0,this._eventSource?.close(),this._authProvider.onUnauthorized({response:s,serverUrl:this._url,fetchFn:this._fetchWithInit}).then(()=>this._startOrAuth().then(t,r),u=>{Pp(u),this.onerror?.(u),r(u)});return}let i=Pp(new Mp);r(i),this.onerror?.(i);return}let o=new VBo(n.code,n.message,n);r(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{let o=n;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){r(i),this.onerror?.(i),this.close();return}t()}),this._eventSource.onmessage=n=>{let o=n,i;try{i=uw.parse(JSON.parse(o.data))}catch(s){this.onerror?.(s);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e,t){if(!this._oauthProvider)throw new Mp("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:n}=await ukr(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await rL(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:n,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new Mp("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){return this._send(e,!1)}async _send(e,t){if(!this._endpoint)throw new Xr(Ar.NotConnected,"Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){if(o.status===401&&this._authProvider){if(o.headers.has("www-authenticate")){let{resourceMetadataUrl:s,scope:u}=tL(o);this._resourceMetadataUrl=s,this._scope=u}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:o,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(s){throw Pp(s)}return await o.text?.().catch(()=>{}),this._send(e,!0)}throw await o.text?.().catch(()=>{}),Pp(t?new Qv(Ar.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:o.statusText}):new Mp)}let i=await o.text?.().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${i}`)}await o.text?.().catch(()=>{})}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}},GBo=1,WBo={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},HBo=new Set(["authorization","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);a(nkr,"anySignal");bkr=class{static{a(this,"StreamableHTTPClientTransport")}_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,akr(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=skr(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=$st(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??WBo,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??GBo)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw Pp(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new U1e({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new U1e({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new Qv(Ar.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let r=await this._oauthProvider.tokens(),n=hre(this._scope,r?.scope,e.scope);this._scope=n;let o=Q8o(n,r?.scope);return rL(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:n,forceReauthorization:o,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}async _commonHeaders(){let e={},t;try{t=await this._authProvider?.token()}catch(n){throw Pp(n)}t&&(e.Authorization=`Bearer ${t}`),this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=ure(this._requestInit?.headers);return new Headers({...e,...r})}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!QN(t))return;let r=t.params?._meta?.[gI];if(typeof r!="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let n=t.params,o=t.method==="resources/read"?typeof n?.uri=="string"?n.uri:void 0:typeof n?.name=="string"?n.name:void 0;o!==void 0&&e.set("mcp-name",Bst(o))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!QN(e))return!1;let t=e.params?._meta?.[gI];return typeof t=="string"&&bI(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:n,requestSignal:o}=e,i=a(()=>this._abortController?.signal.aborted===!0||o?.aborted===!0,"isIntentionalAbort");try{let s=await this._commonHeaders(),u=[...s.get("accept")?.split(",").map(p=>p.trim().toLowerCase())??[],"text/event-stream"];s.set("accept",[...new Set(u)].join(", ")),n&&s.set("last-event-id",n);let l=this._abortController?.signal,c=o!==void 0&&l!==void 0?nkr(l,o):o??l,d=await(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:s,signal:c});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:p,scope:m}=tL(d);this._resourceMetadataUrl=p,this._scope=hre(this._scope,m)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(p){throw Pp(p)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}throw await d.text?.().catch(()=>{}),Pp(t?new Qv(Ar.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}):new Mp)}if(d.status===403){let{resourceMetadataUrl:p,scope:m,error:h,errorDescription:_}=tL(d);if(h==="insufficient_scope"){let y=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:m,resourceMetadataUrl:p,errorDescription:_,statusText:d.statusText,text:y},r)!=="AUTHORIZED")throw Pp(new Mp);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}throw new Qv(Ar.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${d.statusText}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(s){throw i()||this.onerror?.(s),s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let n=this._getNextReconnectionDelay(t),o=a(()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(i=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(s){this.onerror?.(s instanceof Error?s:new Error(String(s)))}}})},"reconnect");if(this._reconnectionScheduler){let i=this._reconnectionScheduler(o,n,t);this._cancelReconnection=typeof i=="function"?i:void 0}else{let i=setTimeout(o,n);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:n,replayMessageId:o,requestSignal:i,onRequestStreamEnd:s}=t,u=a(()=>this._abortController?.signal.aborted===!0||i?.aborted===!0,"isIntentionalAbort"),l,c=!1,d=!1;a(async()=>{try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new hA({onRetry:a(h=>{this._serverRetryMs=h},"onRetry")})).getReader();for(;;){let{value:h,done:_}=await m.read();if(_)break;if(h.id&&(l=h.id,c=!0,n?.(h.id)),!!h.data&&(!h.event||h.event==="message"))try{let y=uw.parse(JSON.parse(h.data));(_q(y)||vq(y))&&(d=!0,o!==void 0&&(y.id=o)),this.onmessage?.(y)}catch(y){this.onerror?.(y)}}(r||c)&&!d&&this._abortController&&!u()?this._scheduleReconnection({resumptionToken:l,onresumptiontoken:n,replayMessageId:o,requestSignal:i,onRequestStreamEnd:s},0):u()||s?.()}catch(m){if(u())return;if(this.onerror?.(new Error(`SSE stream disconnected: ${m}`)),(r||c)&&!d&&this._abortController&&!u())try{this._scheduleReconnection({resumptionToken:l,onresumptiontoken:n,replayMessageId:o,requestSignal:i,onRequestStreamEnd:s},0)}catch(h){this.onerror?.(new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`)),s?.()}else s?.()}},"processStream")()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new Mp("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:n}=await ukr(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await rL(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:n,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new Mp("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,n=0){try{let{resumptionToken:o,onresumptiontoken:i}=t||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:QN(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(v=>this.onerror?.(v));return}let s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);let u=Array.isArray(e)?e.some(v=>Nst(v)):Nst(e);if(u&&s.delete("mcp-session-id"),t?.headers!==void 0)for(let[v,x]of Object.entries(t.headers))HBo.has(v.toLowerCase())||s.set(v,x);s.set("content-type","application/json");let l=[...s.get("accept")?.split(",").map(v=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(l)].join(", "));let c=this._abortController?.signal,d=t?.requestSignal!==void 0&&c!==void 0?nkr(c,t.requestSignal):t?.requestSignal??c,p={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:d},m=await(this._fetch??fetch)(this._url,p);if(u&&m.ok&&(this._sessionId=m.headers.get("mcp-session-id")||void 0),!m.ok){if(m.status===401&&this._authProvider){if(m.headers.has("www-authenticate")){let{resourceMetadataUrl:x,scope:w}=tL(m);this._resourceMetadataUrl=x,this._scope=hre(this._scope,w)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:m,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(x){throw Pp(x)}return await m.text?.().catch(()=>{}),this._send(e,t,!0,n)}throw await m.text?.().catch(()=>{}),Pp(r?new Qv(Ar.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:m.statusText}):new Mp)}let v=await m.text?.().catch(()=>null);if(m.status===403){let{resourceMetadataUrl:x,scope:w,error:b,errorDescription:k}=tL(m);if(b==="insufficient_scope"){if(await this._stepUpAuthorize({scope:w,resourceMetadataUrl:x,errorDescription:k,statusText:m.statusText,text:v},n)!=="AUTHORIZED")throw Pp(new Mp);return this._send(e,t,r,n+1)}}if(m.status===400&&typeof v=="string"&&this._isModernEnvelopedRequest(e))try{let x=uw.parse(JSON.parse(v)),w=(Array.isArray(e)?e:[e]).filter(b=>QN(b));if(vq(x)&&w.some(b=>b.id===x.id)){this.onmessage?.(x);return}}catch{}throw new Qv(Ar.ClientHttpNotImplemented,`Error POSTing to endpoint: ${v}`,{status:m.status,statusText:m.statusText,text:v})}if(m.status===202){await m.text?.().catch(()=>{}),r1r(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(v=>this.onerror?.(v));return}let h=(Array.isArray(e)?e:[e]).some(v=>"method"in v&&"id"in v&&v.id!==void 0),_=m.headers.get("content-type"),y=h1r(_);if(h)if(y==="text/event-stream")this._handleSseStream(m.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await m.json(),x=Array.isArray(v)?v.map(w=>uw.parse(w)):[uw.parse(v)];for(let w of x)this.onmessage?.(w)}else throw await m.text?.().catch(()=>{}),new Xr(Ar.ClientHttpUnexpectedContent,`Unexpected content type: ${_}`,{contentType:_});else await m.text?.().catch(()=>{})}catch(o){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new Qv(Ar.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}});var Tkr=W((Gss,Ikr)=>{Ikr.exports=Skr;Skr.sync=KBo;var wkr=require("fs");function ZBo(e,t){var r=t.pathExt!==void 0?t.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}a(ZBo,"checkPathExt");function kkr(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:ZBo(t,r)}a(kkr,"checkStat");function Skr(e,t,r){wkr.stat(e,function(n,o){r(n,n?!1:kkr(o,e,t))})}a(Skr,"isexe");function KBo(e,t){return kkr(wkr.statSync(e),e,t)}a(KBo,"sync")});var Pkr=W((Hss,Rkr)=>{Rkr.exports=Ekr;Ekr.sync=JBo;var Ckr=require("fs");function Ekr(e,t,r){Ckr.stat(e,function(n,o){r(n,n?!1:Akr(o,t))})}a(Ekr,"isexe");function JBo(e,t){return Akr(Ckr.statSync(e),t)}a(JBo,"sync");function Akr(e,t){return e.isFile()&&YBo(e,t)}a(Akr,"checkStat");function YBo(e,t){var r=e.mode,n=e.uid,o=e.gid,i=t.uid!==void 0?t.uid:process.getuid&&process.getuid(),s=t.gid!==void 0?t.gid:process.getgid&&process.getgid(),u=parseInt("100",8),l=parseInt("010",8),c=parseInt("001",8),d=u|l,p=r&c||r&l&&o===s||r&u&&n===i||r&d&&i===0;return p}a(YBo,"checkMode")});var Okr=W((Jss,Mkr)=>{var Kss=require("fs"),q1e;process.platform==="win32"||global.TESTING_WINDOWS?q1e=Tkr():q1e=Pkr();Mkr.exports=xut;xut.sync=QBo;function xut(e,t,r){if(typeof t=="function"&&(r=t,t={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){xut(e,t||{},function(i,s){i?o(i):n(s)})})}q1e(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}a(xut,"isexe");function QBo(e,t){try{return q1e.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}a(QBo,"sync")});var zkr=W((Qss,Fkr)=>{var Cq=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Dkr=require("path"),XBo=Cq?";":":",Nkr=Okr(),Lkr=a(e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),"getNotFoundError"),Bkr=a((e,t)=>{let r=t.colon||XBo,n=e.match(/\//)||Cq&&e.match(/\\/)?[""]:[...Cq?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=Cq?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=Cq?o.split(r):[""];return Cq&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},"getPathInfo"),jkr=a((e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=Bkr(e,t),s=[],u=a(c=>new Promise((d,p)=>{if(c===n.length)return t.all&&s.length?d(s):p(Lkr(e));let m=n[c],h=/^".*"$/.test(m)?m.slice(1,-1):m,_=Dkr.join(h,e),y=!h&&/^\.[\\\/]/.test(e)?e.slice(0,2)+_:_;d(l(y,c,0))}),"step"),l=a((c,d,p)=>new Promise((m,h)=>{if(p===o.length)return m(u(d+1));let _=o[p];Nkr(c+_,{pathExt:i},(y,v)=>{if(!y&&v)if(t.all)s.push(c+_);else return m(c+_);return m(l(c,d,p+1))})}),"subStep");return r?u(0).then(c=>r(null,c),r):u(0)},"which"),ejo=a((e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=Bkr(e,t),i=[];for(let s=0;s<r.length;s++){let u=r[s],l=/^".*"$/.test(u)?u.slice(1,-1):u,c=Dkr.join(l,e),d=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+c:c;for(let p=0;p<n.length;p++){let m=d+n[p];try{if(Nkr.sync(m,{pathExt:o}))if(t.all)i.push(m);else return m}catch{}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw Lkr(e)},"whichSync");Fkr.exports=jkr;jkr.sync=ejo});var $kr=W((eus,but)=>{"use strict";var Ukr=a((e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"},"pathKey");but.exports=Ukr;but.exports.default=Ukr});var Wkr=W((rus,Gkr)=>{"use strict";var qkr=require("path"),tjo=zkr(),rjo=$kr();function Vkr(e,t){let r=e.options.env||process.env,n=process.cwd(),o=e.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(e.options.cwd)}catch{}let s;try{s=tjo.sync(e.command,{path:r[rjo({env:r})],pathExt:t?qkr.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=qkr.resolve(o?e.options.cwd:"",s)),s}a(Vkr,"resolveCommandAttempt");function njo(e){return Vkr(e)||Vkr(e,!0)}a(njo,"resolveCommand");Gkr.exports=njo});var Hkr=W((ous,kut)=>{"use strict";var wut=/([()\][%!^"`<>&|;, *?])/g;function ojo(e){return e=e.replace(wut,"^$1"),e}a(ojo,"escapeCommand");function ijo(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(wut,"^$1"),t&&(e=e.replace(wut,"^$1")),e}a(ijo,"escapeArgument");kut.exports.command=ojo;kut.exports.argument=ijo});var Kkr=W((aus,Zkr)=>{"use strict";Zkr.exports=/^#!(.*)/});var Ykr=W((sus,Jkr)=>{"use strict";var ajo=Kkr();Jkr.exports=(e="")=>{let t=e.match(ajo);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var Xkr=W((uus,Qkr)=>{"use strict";var Sut=require("fs"),sjo=Ykr();function ujo(e){let r=Buffer.alloc(150),n;try{n=Sut.openSync(e,"r"),Sut.readSync(n,r,0,150,0),Sut.closeSync(n)}catch{}return sjo(r.toString())}a(ujo,"readShebang");Qkr.exports=ujo});var nSr=W((cus,rSr)=>{"use strict";var ljo=require("path"),eSr=Wkr(),tSr=Hkr(),cjo=Xkr(),djo=process.platform==="win32",pjo=/\.(?:com|exe)$/i,mjo=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function fjo(e){e.file=eSr(e);let t=e.file&&cjo(e.file);return t?(e.args.unshift(e.file),e.command=t,eSr(e)):e.file}a(fjo,"detectShebang");function hjo(e){if(!djo)return e;let t=fjo(e),r=!pjo.test(t);if(e.options.forceShell||r){let n=mjo.test(t);e.command=ljo.normalize(e.command),e.command=tSr.command(e.command),e.args=e.args.map(i=>tSr.argument(i,n));let o=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${o}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}a(hjo,"parseNonShell");function gjo(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null),t=t?t.slice(0):[],r=Object.assign({},r);let n={command:e,args:t,options:r,file:void 0,original:{command:e,args:t}};return r.shell?n:hjo(n)}a(gjo,"parse");rSr.exports=gjo});var aSr=W((pus,iSr)=>{"use strict";var Iut=process.platform==="win32";function Tut(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}a(Tut,"notFoundError");function _jo(e,t){if(!Iut)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=oSr(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}a(_jo,"hookChildProcess");function oSr(e,t){return Iut&&e===1&&!t.file?Tut(t.original,"spawn"):null}a(oSr,"verifyENOENT");function yjo(e,t){return Iut&&e===1&&!t.file?Tut(t.original,"spawnSync"):null}a(yjo,"verifyENOENTSync");iSr.exports={hookChildProcess:_jo,verifyENOENT:oSr,verifyENOENTSync:yjo,notFoundError:Tut}});var lSr=W((fus,Eq)=>{"use strict";var sSr=require("child_process"),Cut=nSr(),Eut=aSr();function uSr(e,t,r){let n=Cut(e,t,r),o=sSr.spawn(n.command,n.args,n.options);return Eut.hookChildProcess(o,n),o}a(uSr,"spawn");function vjo(e,t,r){let n=Cut(e,t,r),o=sSr.spawnSync(n.command,n.args,n.options);return o.error=o.error||Eut.verifyENOENTSync(o.status,n),o}a(vjo,"spawnSync");Eq.exports=uSr;Eq.exports.spawn=uSr;Eq.exports.sync=vjo;Eq.exports._parse=Cut;Eq.exports._enoent=Eut});function bjo(){let e={};for(let t of xjo){let r=V1e.default.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var V1e,cSr,dSr,xjo,yre,Aut=T(()=>{qst();V1e=ct(require("node:process"),1),cSr=require("node:stream"),dSr=ct(lSr(),1),xjo=V1e.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];a(bjo,"getDefaultEnvironment");yre=class{static{a(this,"StdioClientTransport")}_process;_readBuffer;_serverParams;_stderrStream=null;onclose;onerror;onmessage;constructor(e){this._serverParams=e,this._readBuffer=new zst({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new cSr.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._process=(0,dSr.default)(this._serverParams.command,this._serverParams.args??[],{env:{...bjo(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:V1e.default.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",r=>{t(r),this.onerror?.(r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",r=>{this.onerror?.(r)}),this._process.stdout?.on("data",r=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(n){this.onerror?.(n),this.close().catch(()=>{})}}),this._process.stdout?.on("error",r=>{this.onerror?.(r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async _dispose(){let e=this._process;if(this._process=void 0,e&&e.exitCode===null&&e.signalCode===null){let t=new Promise(r=>e.once("exit",()=>r()));try{e.stdin?.end()}catch{}try{e.kill("SIGTERM")}catch{}if(await Promise.race([t,new Promise(r=>setTimeout(r,1e3).unref())]),e.exitCode===null&&e.signalCode===null)try{e.kill("SIGKILL")}catch{}await t}try{e?.stdout?.destroy()}catch{}try{e?.stdin?.destroy()}catch{}try{e?.stderr?.destroy()}catch{}this._readBuffer.clear()}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(r=>{e.once("close",()=>{r()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new Xr(Ar.NotConnected,"Not connected");let r=Ust(e);this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}}});function mSr(e,t,r,n){let o=vre(t)?t:{},i=typeof o.name=="string"?o.name:"unknown";return{serverName:e,toolName:i,name:`mcp__${pSr(e)}__${pSr(i)}`,description:typeof o.description=="string"?o.description:void 0,timeoutMs:r,inputSchema:wjo(o.inputSchema),outputSchema:vre(o.outputSchema)?o.outputSchema:void 0,annotations:kjo(o.annotations),...n?{official:!0}:{}}}function wjo(e){return vre(e)?{...e,type:"object",properties:vre(e.properties)?e.properties:{}}:{type:"object",properties:{},additionalProperties:!0}}function kjo(e){if(vre(e))return{readOnlyHint:typeof e.readOnlyHint=="boolean"?e.readOnlyHint:void 0,destructiveHint:typeof e.destructiveHint=="boolean"?e.destructiveHint:void 0,idempotentHint:typeof e.idempotentHint=="boolean"?e.idempotentHint:void 0,openWorldHint:typeof e.openWorldHint=="boolean"?e.openWorldHint:void 0}}function pSr(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_");return t.length>0?t:"unknown"}function vre(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var fSr=T(()=>{"use strict";a(mSr,"normalizeMcpToolDescriptor");a(wjo,"normalizeInputSchema");a(kjo,"normalizeAnnotations");a(pSr,"sanitizeMcpName");a(vre,"isRecord")});function ySr(e){let t=hSr(e.url),r=a((o,i)=>(e.onAuthFailure?.(o),new Aq(o,i)),"failWith");return a(async(o,i)=>{let s=Ajo(o),u=hSr(s);if(!u||!t||u!==t)throw r("official_mcp_origin_untrusted",`official MCP request origin does not match the configured endpoint: ${e.serverName}`);let l=await e.trustedOrigins.isTrusted({mcpKey:e.official.mcpKey,origin:u,pluginId:e.official.pluginId});if(!l.trusted)throw r("official_mcp_origin_untrusted",`official MCP origin is not trusted (${l.detail??"unknown"}): ${e.serverName} origin=${u} pluginId=${e.official.pluginId}`);let c=Ojo(i?.body),d={event:"mcp.official_auth.request",mcpKey:e.official.mcpKey,mcpServerName:e.serverName,module:"adapters.mcp.official_auth",requestBodyBytes:Mjo(i?.body),urlPath:Pjo(s),...c.method?{rpcMethod:c.method}:{},...c.id!==void 0?{rpcId:c.id}:{},...c.toolName?{rpcToolName:c.toolName}:{},...c.traceId?{mcpTraceId:c.traceId}:{}},p=a(async _=>{let y={},v;if(e.authHeadersPort){let k=Date.now(),S=await e.authHeadersPort.resolveHeaders({mcpKey:e.official.mcpKey,pluginId:e.official.pluginId,targetOrigin:u,...e.workspaceIdentity?{workspaceIdentity:e.workspaceIdentity}:{},...e.workspacePath?{workspacePath:e.workspacePath}:{},...i?.signal?{signal:i.signal}:{}});v=Date.now()-k,S.ok?y=S.headers:e.logger?.warn("Official MCP auth headers unavailable for request",{...d,attempt:_,event:"mcp.official_auth.resolve",fallback:"anonymous",reason:S.reason,resolveDurationMs:v,status:"failed"})}else e.logger?.warn("Official MCP auth port unavailable for request",{...d,attempt:_,event:"mcp.official_auth.resolve",fallback:"anonymous",reason:"official_auth_unavailable",status:"failed"});let x=FCt(y),w=Ejo(i?.headers,y);w.delete(_Sr),w.delete(Sjo),e.logger?.debug("Official MCP request sending",{...d,attempt:_,resolveDurationMs:v,status:"started",timeoutHint:Djo(i?.signal),...x});let b=Date.now();try{let k=await e.baseFetch(o,{...i,headers:w,redirect:"manual"}),S=vSr(k),I=c.method==="tools/call"?void 0:await Tjo(k);(S||I)&&e.onServerResponse?.({httpStatus:k.status,...I?{failureKind:I}:{},...S?{serverRequestId:S}:{},...c.method?{rpcMethod:c.method}:{},...c.toolName?{rpcToolName:c.toolName}:{},...c.spanId?{spanId:c.spanId}:{},...c.traceId?{traceId:c.traceId}:{}});let C={...d,attempt:_,httpStatus:k.status,responseBodyBytes:xSr(k.headers.get("content-length")),sendDurationMs:Date.now()-b,...S?{serverRequestId:S}:{}};return k.ok?e.logger?.debug("Official MCP response received",{...C,status:"completed"}):e.logger?.warn("Official MCP response failed",{...C,status:"failed"}),{authApplied:Object.keys(y).length>0,response:k}}catch(k){let S=Date.now()-b;throw e.logger?.warn("Official MCP request did not complete",{...d,aborted:Njo(k),attempt:_,error:k instanceof Error?k.message:String(k),errorName:k instanceof Error?k.name:"unknown",sendDurationMs:S,status:"failed"}),k}},"send"),m=await p(1),h=m.response;if(h.status===401&&m.authApplied&&(e.logger?.info("Official MCP retrying once after 401",{...d,attempt:2,status:"started"}),await G1e(h),m=await p(2),h=m.response),h.status===401){let _="official MCP rejected the current credential",y=c.method==="tools/call"?Rut(_,h):_;throw await G1e(h),r("official_auth_rejected",y)}if(h.status===403){let _="official MCP denied access for the current plan",y=c.method==="tools/call"?Rut(_,h):_;throw await G1e(h),r("official_auth_forbidden",y)}if(Rjo(h.status)){let _=`official MCP responded with a blocked redirect (${h.status})`,y=c.method==="tools/call"?Rut(_,h):_;throw await G1e(h),r("official_auth_redirect_blocked",y)}return h},"authFetch")}async function Tjo(e){if(e.status===429)return"rate_limited";if(e.status>=500)return"server_internal_error";if(!(e.headers.get("content-type")?.toLowerCase()??"").includes("json"))return e.ok?void 0:"connection_failed";let r=await Cjo(e,Ijo);if(!r)return e.ok?void 0:"connection_failed";try{let n=JSON.parse(r);if(!n||typeof n!="object"||Array.isArray(n))return e.ok?void 0:"connection_failed";let o=n;if(o.code===3001)return"server_not_found";if(o.code===1e3)return"server_unavailable";if(o.jsonrpc==="2.0"&&o.error!==void 0){let i=o.error;if(i&&typeof i=="object"&&!Array.isArray(i)){let s=i.code;if(s===1006)return"not_authenticated";if(s===3101)return"coding_plan_required"}return"protocol_error"}}catch{return e.ok?void 0:"connection_failed"}return e.ok?void 0:"connection_failed"}async function Cjo(e,t){let r=xSr(e.headers.get("content-length"));if(r!==void 0&&r>t)return;let n=e.clone().body;if(!n)return;let o=n.getReader(),i=new TextDecoder,s=0,u="";try{for(;;){let l=await o.read();if(l.done)break;if(s+=l.value.byteLength,s>t){await o.cancel();return}u+=i.decode(l.value,{stream:!0})}return u+=i.decode(),u}finally{o.releaseLock()}}function Ejo(e,t){let r=new Headers,n=new Set(Object.keys(t).map(o=>o.toLowerCase()));new Headers(e??{}).forEach((o,i)=>{let s=i.toLowerCase();n.has(s)||NCt(s)&&s!=="mcp-session-id"&&s!=="mcp-protocol-version"||r.set(i,o)});for(let[o,i]of Object.entries(t))r.set(o,i);return r}function Ajo(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function hSr(e){try{let t=new URL(e);return t.username!==""||t.password!==""?void 0:t.origin}catch{return}}function Rjo(e){return e>=300&&e<400}function vSr(e){let t=e.headers.get(_Sr)?.trim();return t||void 0}function Rut(e,t){let r=vSr(t);return r?`${e} - ${r}`:e}function Pjo(e){try{return new URL(e).pathname}catch{return"(unparsable)"}}function Mjo(e){if(typeof e=="string")return Buffer.byteLength(e,"utf8");if(e instanceof Uint8Array)return e.byteLength}function xSr(e){if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Ojo(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};let r=t,n=typeof r.method=="string"?r.method:void 0,o=typeof r.id=="number"||typeof r.id=="string"?r.id:void 0,i=gSr(r.params)?r.params:void 0,s=i&&typeof i.name=="string"?i.name:void 0,u=i&&gSr(i._meta)?i._meta:void 0,l=u&&typeof u.trace_id=="string"?u.trace_id:void 0,c=u&&typeof u.span_id=="string"?u.span_id:void 0;return{...o!==void 0?{id:o}:{},...n?{method:n}:{},...c?{spanId:c}:{},...s?{toolName:s}:{},...l?{traceId:l}:{}}}catch{return{}}}function gSr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Djo(e){return e?e.aborted?"already-aborted":"armed":"none"}function Njo(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="TimeoutError")}async function G1e(e){try{await e.body?.cancel()}catch{}}var Aq,_Sr,Sjo,Ijo,bSr=T(()=>{"use strict";gt();Aq=class extends Error{static{a(this,"OfficialMcpAuthError")}kind;constructor(t,r){super(r),this.kind=t,this.name="OfficialMcpAuthError"}},_Sr="x-request-id",Sjo="x-trace-id";a(ySr,"createOfficialMcpAuthFetch");Ijo=64*1024;a(Tjo,"classifyOfficialMcpResponse");a(Cjo,"readBoundedResponseText");a(Ejo,"mergeOfficialAuthHeaders");a(Ajo,"resolveRequestUrl");a(hSr,"safeOrigin");a(Rjo,"isRedirect");a(vSr,"readServerRequestId");a(Rut,"withServerRequestId");a(Pjo,"safePath");a(Mjo,"byteLength");a(xSr,"numericHeader");a(Ojo,"describeJsonRpc");a(gSr,"isPlainRecord");a(Djo,"describeAbortSignal");a(Njo,"isAbortError");a(G1e,"discardBody")});function wSr(e){let t=e.env??process.env;return jjo(hF(pj(Ljo(t)),{network:e.network,sourceEnv:t}))}function xre(e){return bve({caCertFile:e.network?.caCertFile,env:e.env??process.env,httpProxy:e.network?.httpProxy,noProxy:e.network?.noProxy})}function Ljo(e){let t={};for(let[r,n]of Object.entries(e))typeof n=="string"&&(t[r]=n);return t}function jjo(e,t=Bjo){let r=t.platform==="win32"?eR.win32:eR.posix,n=t.platform==="win32"?";":eR.delimiter,o=r.basename(t.execPath).toLowerCase();if(o!=="node"&&o!=="node.exe")return e;let i=Object.keys(e).find(d=>d.toLowerCase()==="path")??"PATH",s=e[i]??"",u=r.dirname(t.execPath),l=s.split(n).filter(Boolean);if(l.some(d=>Fjo(d,u,t.platform)))return e;let c=t.platform==="win32"?"node.exe":"node";return l.some(d=>t.isExecutable(r.join(d,c)))?e:{...e,[i]:s?`${u}${n}${s}`:u}}function Fjo(e,t,r){let n=r==="win32"?eR.win32:eR.posix,o=a(i=>{let s=n.normalize(i);return r==="win32"?s.toLowerCase():s},"normalize");return o(e)===o(t)}function zjo(e){try{return(0,W1e.accessSync)(e,W1e.constants.X_OK),!0}catch{return!1}}var W1e,eR,Bjo,kSr=T(()=>{"use strict";W1e=require("node:fs"),eR=require("node:path");gt();art();Vpe();a(wSr,"buildMcpStdioEnv");a(xre,"createMcpTransportFetch");a(Ljo,"filterStringEnv");Bjo={execPath:process.execPath,isExecutable:zjo,platform:process.platform};a(jjo,"prependRunningNodeDirectory");a(Fjo,"arePathEntriesEqual");a(zjo,"isExecutableFile")});function Mut(e){let t=new Map,r=e.idleGraceMs??Ujo,n=e.logger?.child({module:"adapters.mcp.pool"}),o=!1,i=0,s=a(async d=>{let p=Date.now();d.closeTimer&&clearTimeout(d.closeTimer),d.closeTimer=void 0,t.get(d.key)===d&&t.delete(d.key);try{await d.adapter.close(),n?.info("MCP pooled connection closed",{...d.connectionContext,durationMs:Date.now()-p,event:"mcp.pool.connection.closed",mcpServerName:d.serverName,status:"completed"})}catch(m){n?.warn("MCP pooled connection close failed",{...d.connectionContext,error:m instanceof Error?m.message:String(m),event:"mcp.pool.connection.close.failed",mcpServerName:d.serverName})}finally{e.telemetry?.unregisterConnection({connectionId:d.connectionContext.mcpConnectionId})}},"closeEntry"),u=a(d=>{if(!d.closeTimer){if(r<=0){s(d);return}d.closeTimer=setTimeout(()=>{d.closeTimer=void 0,d.refs.size===0&&s(d)},r),d.closeTimer.unref?.()}},"scheduleClose"),l=a(async(d,p,m)=>{if(d.revalidating){await d.revalidating;return}let h=(async()=>{let y=await d.connecting.then(()=>!0,()=>!1)?(await d.adapter.status())[d.serverName]?.status:void 0;if(!(y==="connecting"||y==="disabled"||y==="untrusted")){if(y==="connected"&&(await d.adapter.pingServer?.(d.serverName)??!0)){n?.debug("MCP pooled connection revalidated",{...d.connectionContext,event:"mcp.pool.connection.revalidated",mcpServerName:d.serverName,status:"completed"});return}n?.warn("MCP pooled connection is stale; reconnecting",{...d.connectionContext,event:"mcp.pool.connection.stale",mcpConnectionState:y??"unknown",mcpServerName:d.serverName,status:"started"}),d.connecting=d.adapter.connectServer(d.serverName,p,m),await d.connecting.catch(()=>{})}})();d.revalidating=h.finally(()=>{d.revalidating=void 0}),await d.revalidating},"revalidateEntry");return{acquireLease:a((d={})=>{if(o)throw new Error("MCP connection pool is closed");let p=`${++i}:${d.leaseId??"lease"}`,m=d.sessionId?.trim()||void 0,h=new Map,_=new Map,y=!1,v=!1,x=a(S=>{let I=h.get(S),C=I?t.get(I):void 0;if(!C)throw new Error(`MCP server is not leased by this session: ${S}`);return C},"requireEntry"),w=a(S=>{let I=h.get(S);if(!I)return;h.delete(S);let C=t.get(I);C&&C.refs.delete(p)&&(e.telemetry?.releaseOwner({connectionId:C.connectionContext.mcpConnectionId,ownerId:p}),n?.info("MCP connection lease released",{...C.connectionContext,event:"mcp.pool.lease.released",mcpLeaseId:p,mcpServerName:S,refCount:C.refs.size,...m?{sessionId:m}:{}}),C.refs.size===0&&u(C))},"release"),b=a(async(S,I,C={})=>{let R=qjo({config:I,connectOptions:C,leaseId:p,serverName:S}),A=h.get(S),O=t.get(R),P=!1;if(O){O.closeTimer&&clearTimeout(O.closeTimer),O.closeTimer=void 0;let D=O.refs.size;O.refs.add(p),P=O.refs.size!==D,C.revalidate&&await l(O,I,C)}else{let D=$jo({config:I,connectOptions:C,sessionId:m});e.telemetry?.registerConnection({connectionId:D.mcpConnectionId,isolation:D.mcpIsolation,serverName:S,...I.source?{source:I.source.kind}:{}});let U=e.createAdapter({connectionContext:D,config:I,serverName:S,workingDirectory:C.workingDirectory});O={adapter:U,connectionContext:D,connecting:U.connectServer(S,I,C),key:R,refs:new Set([p]),serverName:S},t.set(R,O),P=!0,n?.info("MCP pooled connection created",{...D,event:"mcp.pool.connection.created",mcpServerName:S,transport:I.type})}if(A&&A!==R){let D=t.get(A);D&&D.refs.delete(p)&&(e.telemetry?.releaseOwner({connectionId:D.connectionContext.mcpConnectionId,ownerId:p}),n?.info("MCP connection lease released",{...D.connectionContext,event:"mcp.pool.lease.released",mcpLeaseId:p,mcpServerName:S,refCount:D.refs.size,...m?{sessionId:m}:{}}),D.refs.size===0&&u(D))}return h.set(S,R),P&&e.telemetry?.acquireOwner({connectionId:O.connectionContext.mcpConnectionId,ownerId:p,...m?{sessionId:m}:{}}),A!==R&&n?.info("MCP connection lease acquired",{...O.connectionContext,event:"mcp.pool.lease.acquired",mcpLeaseId:p,mcpServerName:S,refCount:O.refs.size,...m?{sessionId:m}:{}}),await O.connecting},"acquire"),k=a(async()=>{let S={},I=[];for(let[C,R]of h){let A=t.get(R);if(!A)continue;let O=(await A.adapter.status())[C];O&&(S[C]=O),I.push(...await A.adapter.listTools())}if(m&&!v){v=!0;let C=[..._].filter(([,A])=>A.enabled!==!1),R=C.filter(([A])=>S[A]?.status==="connected").length;e.telemetry?.recordSessionStartup({configuredCount:C.length,connectedCount:R,failedCount:C.length-R,processCount:C.filter(([A,O])=>O.type==="stdio"&&S[A]?.status==="connected").length,sessionId:m})}return{statuses:S,tools:I}},"snapshot");return{async callTool(S,I){return await x(S.serverName).adapter.callTool(S,I)},async close(){if(!y){y=!0;for(let S of[...h.keys()])w(S)}},async connectConfiguredServers(S,I={}){_.clear();for(let[R,A]of Object.entries(S))_.set(R,A);let C=new Set(Object.keys(S));for(let R of[...h.keys()])C.has(R)||w(R);return await Promise.all(Object.entries(S).map(([R,A])=>b(R,A,I))),await k()},async connectServer(S,I,C={}){return await b(S,I,C)},async disconnectServer(S){let I=h.get(S),C=I?t.get(I):void 0,R=C?(await C.adapter.status())[S]:void 0;return w(S),R?{...R,status:"disconnected",toolCount:0,updatedAt:new Date().toISOString()}:void 0},async listTools(){return(await k()).tools},async pingServer(S,I){let C=h.get(S),R=C?t.get(C):void 0;return R?await R.adapter.pingServer?.(S,I)??!0:!1},async status(){return(await k()).statuses}}},"acquireLease"),async close(){o=!0;let d=[...t.values()];t.clear(),await Promise.all(d.map(s))},stats(){return{activeConnections:t.size,pendingCloseConnections:[...t.values()].filter(d=>d.refs.size===0).length}}}}function $jo(e){let t=e.config.isolation==="workspace"?"workspace":"session",r=ISr(e.connectOptions);return{mcpConnectionId:(0,SSr.randomUUID)(),mcpIsolation:t,...r?{workspaceKey:r}:{},...t==="session"&&e.sessionId?{sessionId:e.sessionId}:{}}}function ISr(e){return e.workspaceIdentity?.trim()||e.workingDirectory?.trim()||void 0}function qjo(e){let t=e.config.isolation==="workspace"?ISr(e.connectOptions)??"":e.leaseId;return[e.serverName,t,Put(e.config)].join("\0")}function Put(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(Put).join(",")}]`;let t=e;return`{${Object.keys(t).toSorted().filter(r=>t[r]!==void 0).map(r=>`${JSON.stringify(r)}:${Put(t[r])}`).join(",")}}`}var SSr,Ujo,Out=T(()=>{"use strict";SSr=require("node:crypto"),Ujo=3e4;a(Mut,"createMcpConnectionPool");a($jo,"createConnectionContext");a(ISr,"resolveWorkspaceKey");a(qjo,"connectionKey");a(Put,"stableStringify")});function Ad(e,t){return`${e}:${t}`}function Vjo(){return(0,Z1e.randomBytes)(16).toString("hex")}function ESr(e,t){return typeof e.generation=="string"&&e.generation.length>0?e.generation:`legacy-${(0,Z1e.createHash)("sha256").update(t).digest("hex").slice(0,32)}`}function But(e){return!kI(e)||typeof e.version!="number"||!CSr.has(e.version)||typeof e.published_by!="string"||e.published_by.length===0||!kI(e.client_information)||!kI(e.tokens)?!1:typeof e.client_information.client_id=="string"&&typeof e.tokens.access_token=="string"&&typeof e.tokens.token_type=="string"}async function wre(e,t){let r=Ad(t,bre),n=await e.load(r);if(!n)return;let o;try{o=JSON.parse(n)}catch{return}if(But(o))return{clientInformation:o.client_information,...o.expires_at===void 0?{}:{expiresAt:o.expires_at},generation:ESr(o,n),...o.issuer===void 0?{}:{issuer:o.issuer},...o.obtained_at===void 0?{}:{obtainedAt:o.obtained_at},raw:n,tokens:o.tokens}}async function kre(e,t,r){let n=r.obtainedAt??Date.now(),o=typeof r.tokens.expires_in=="number"&&Number.isFinite(r.tokens.expires_in)?n+r.tokens.expires_in*1e3:void 0,i=Vjo(),s={client_information:r.clientInformation,...o===void 0?{}:{expires_at:o},generation:i,...r.issuer===void 0?{}:{issuer:r.issuer},obtained_at:n,published_by:r.publishedBy,tokens:r.tokens,version:TSr},u=JSON.stringify(s),l=JSON.stringify(r.clientInformation),c=JSON.stringify(r.tokens);return await e.saveMany({[Ad(t,bre)]:u,[Ad(t,Nut)]:l,[Ad(t,Lut)]:c}),{canonical:s,generation:i,legacyClientRaw:l,legacyTokensRaw:c,raw:u}}function kI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ASr(e,t=Date.now(),r=Gjo){return e.expiresAt===void 0?!0:t>=e.expiresAt-r}async function jut(e,t,r,n){let o=Ad(t,bre),i=[o,Ad(t,Lut)];return n==="all"&&i.push(Ad(t,Nut)),await e.deleteManyIfValue(o,r,i)}async function SI(e,t){let r=Ad(t,bre),n=Ad(t,Nut),o=Ad(t,Lut),i=await e.loadMany([r,n,o]);return RSr({canonicalRaw:i[r]??void 0,legacyClientRaw:i[n]??void 0,legacyTokensRaw:i[o]??void 0})}function RSr(e){let t=Dut(e.canonicalRaw),r=t!==void 0&&But(t)?t:void 0,n=Dut(e.legacyClientRaw),o=Dut(e.legacyTokensRaw);if(r&&e.canonicalRaw){let i={clientInformation:r.client_information,...r.expires_at===void 0?{}:{expiresAt:r.expires_at},generation:ESr(r,e.canonicalRaw),...r.issuer===void 0?{}:{issuer:r.issuer},...r.obtained_at===void 0?{}:{obtainedAt:r.obtained_at},raw:e.canonicalRaw,source:"canonical",tokens:r.tokens};return r.version===1?o!==void 0&&(!n||(0,H1e.isDeepStrictEqual)(n,r.client_information))?{clientInformation:n??r.client_information,source:"legacy",tokens:o}:i:o?(0,H1e.isDeepStrictEqual)(o,r.tokens)?n?i:{source:"legacy",tokens:o}:n&&(0,H1e.isDeepStrictEqual)(n,r.client_information)?{clientInformation:n,source:"legacy",tokens:o}:{clientInformation:n,source:"legacy"}:{clientInformation:n,source:"legacy"}}if(!(!n&&!o))return{clientInformation:n,source:"legacy",...o?{tokens:o}:{}}}function Dut(e){if(e)try{return JSON.parse(e)}catch{return}}var Z1e,H1e,bre,Nut,Lut,TSr,CSr,Gjo,tR=T(()=>{"use strict";Z1e=require("node:crypto"),H1e=require("node:util"),bre="authorization_credentials",Nut="client_information",Lut="tokens",TSr=2,CSr=new Set([1,TSr]);a(Ad,"mcpOAuthCredentialKey");a(Vjo,"createCredentialGeneration");a(ESr,"resolveCredentialGeneration");a(But,"isCanonicalCredentials");a(wre,"loadCanonicalCredentials");a(kre,"publishCanonicalCredentials");a(kI,"isRecord");Gjo=3e4;a(ASr,"isCanonicalTokenNearExpiry");a(jut,"invalidateCanonicalCredentials");a(SI,"loadCredentialPair");a(RSr,"deriveCredentialPair");a(Dut,"parseJson")});function rR(e){let t=new Error(`MCP server ${e.serverName} requires interactive OAuth authorization (${e.reason})`,e.cause===void 0?void 0:{cause:e.cause});return Object.defineProperty(t,PSr,{configurable:!0,value:!0}),t.code=Wjo,t.reason=e.reason,e.requiredScope&&(t.requiredScope=e.requiredScope),e.resourceMetadataUrl&&(t.resourceMetadataUrl=e.resourceMetadataUrl),t}function Fut(e){let t=new Error(`MCP server ${e.serverName} OAuth token refresh failed temporarily`,e.cause===void 0?void 0:{cause:e.cause});return Object.defineProperty(t,MSr,{configurable:!0,value:!0}),t.code=Hjo,t}function Zjo(e){return OSr(e,PSr)}function Kjo(e){return OSr(e,MSr)}function K1e(e){if(Kjo(e))return;if(Zjo(e))return{reason:e.reason,...e.requiredScope?{requiredScope:e.requiredScope}:{},...e.resourceMetadataUrl?{resourceMetadataUrl:e.resourceMetadataUrl}:{}};if(e instanceof U1e)return{reason:"insufficient_scope",...e.requiredScope?{requiredScope:e.requiredScope}:{},...e.resourceMetadataUrl?{resourceMetadataUrl:String(e.resourceMetadataUrl)}:{}};if(e instanceof Mp)return{reason:"unauthorized"};if(Jjo(e))return{reason:"unauthorized"};let t=e?.cause;if(t!==void 0&&t!==e)return K1e(t)}function Jjo(e){return typeof e!="object"||e===null?!1:e.code===Ar.ClientHttpAuthentication}function OSr(e,t){return typeof e=="object"&&e!==null||typeof e=="function"?e[t]===!0:!1}var PSr,MSr,Wjo,Hjo,Sre=T(()=>{"use strict";_re();PSr=Symbol.for("zcode.mcp.oauth.interactiveAuthorizationRequired"),MSr=Symbol.for("zcode.mcp.oauth.temporaryRefreshFailure"),Wjo="MCP_OAUTH_INTERACTIVE_REQUIRED",Hjo="MCP_OAUTH_TEMPORARY_REFRESH_FAILURE";a(rR,"createInteractiveAuthorizationRequiredError");a(Fut,"createTemporaryRefreshFailureError");a(Zjo,"isInteractiveAuthorizationRequiredError");a(Kjo,"isTemporaryRefreshFailureError");a(K1e,"classifyInteractiveAuthorizationTrigger");a(Jjo,"isSdkAuthenticationHttpError");a(OSr,"hasBrand")});async function Ire(e,t,r,n=Date.now()){await e.saveMany({[Ad(t,NSr)]:JSON.stringify(r),[Ad(t,LSr)]:String(n)})}async function Tre(e,t,r={}){let n=r.now??Date.now(),o=r.ttlMs??Yjo,i=Ad(t,NSr),s=Ad(t,LSr),u=await e.loadMany([i,s]),l=u[i];if(!l)return;let c=Number(u[s]);if(!Number.isFinite(c)||n-c>=o)return;let d;try{d=JSON.parse(l)}catch{return}if(!kI(d)||typeof d.authorizationServerUrl!="string")return;let p=d;if(!(r.expectedIssuer&&!Qjo(p,r.expectedIssuer)))return p}function Qjo(e,t){let r=e.authorizationServerMetadata?.issuer??e.authorizationServerUrl;return r?DSr(r)===DSr(t):!1}function DSr(e){return e.endsWith("/")?e.slice(0,-1):e}var NSr,LSr,Yjo,J1e=T(()=>{"use strict";tR();NSr="discovery_state",LSr="discovery_state_fetched_at",Yjo=1440*60*1e3;a(Ire,"saveDiscoveryRecord");a(Tre,"loadDiscoveryRecord");a(Qjo,"issuersMatch");a(DSr,"normalizeIssuer")});function Uut(e,t,r){return`mcp:oauth:${(0,zut.createHash)("sha256").update([e,t,r.clientId??"",r.scope??"",r.redirectPath??""].join(`
|
|
1812
|
-
`)).digest("hex").slice(0,24)}`}var zut,Gus,BSr=T(()=>{"use strict";zut=require("node:crypto");Sbe();Ebe();tR();Sre();J1e();Gus=300*1e3;a(Uut,"createCredentialKeyPrefix")});function nFo(e,t){return(0,Y1e.join)((0,Y1e.dirname)(e),`${$ut(t)}.authz`)}function $ut(e){return e.replaceAll(/[^a-zA-Z0-9-]/g,"-")}async function FSr(e){let t=nFo(e.credentialsFilePath,e.keyPrefix);try{let r=await _te(t,tFo,rFo,eFo);return{attemptId:(0,jSr.randomBytes)(16).toString("hex"),release:r}}catch(r){if(oFo(r)===cH)return;throw r}}async function zSr(e,t,r){let n={attempt_id:r.attemptId,authorization_url:r.authorizationUrl,...r.baselineGeneration===void 0?{}:{baseline_generation:r.baselineGeneration},expires_at:r.expiresAt,state:r.state};await e.save(qut(t),JSON.stringify(n))}async function USr(e,t,r=Date.now()){let n=await e.load(qut(t));if(!n)return;let o;try{o=JSON.parse(n)}catch{return}if(!(!kI(o)||typeof o.attempt_id!="string"||typeof o.authorization_url!="string"||typeof o.state!="string"||typeof o.expires_at!="number")&&!(o.expires_at<=r))return{attemptId:o.attempt_id,authorizationUrl:o.authorization_url,...typeof o.baseline_generation=="string"?{baselineGeneration:o.baseline_generation}:{},expiresAt:o.expires_at,state:o.state}}async function $Sr(e,t,r){let n=qut(t),o=await e.load(n);if(!o)return!1;let i;try{i=JSON.parse(o)}catch{return await e.deleteIfValue(n,o)}return!kI(i)||i.attempt_id!==r?!1:await e.deleteIfValue(n,o)}function qut(e){return Ad(e,Xjo)}function oFo(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}var jSr,Y1e,Xjo,eFo,tFo,rFo,Vut=T(()=>{"use strict";jSr=require("node:crypto"),Y1e=require("node:path");Tbe();gt();tR();Xjo="pending_authorization",eFo=250,tFo=[25],rFo=100;a(nFo,"resolveAuthorizationLeasePath");a($ut,"sanitizeKeyPrefix");a(FSr,"tryAcquireAuthorizationLease");a(zSr,"publishPendingAuthorization");a(USr,"loadPendingAuthorization");a($Sr,"deletePendingAuthorizationIfOwned");a(qut,"pendingKey");a(oFo,"getErrorCode")});function qSr(e){let t=Math.max(0,Math.floor(e));return{expiresAt:Date.now()+t,timeoutMs:t}}function Cre(e,t){let r=e.expiresAt-Date.now();if(r<=0)throw new Rq(t);return r}function Ere(e,t,r,n){return Pq(e,Cre(t,r),r,n)}function Pq(e,t,r,n){return new Promise((o,i)=>{if(n?.aborted){i(n.reason instanceof Error?n.reason:new Error("Operation aborted"));return}let s=!1,u=setTimeout(()=>{s||(s=!0,l(),i(new Rq(r)))},t),l=a(()=>{clearTimeout(u),n?.removeEventListener("abort",c)},"cleanup"),c=a(()=>{s||(s=!0,l(),i(n?.reason instanceof Error?n.reason:new Error("Operation aborted")))},"abortHandler");n?.addEventListener("abort",c),e.then(d=>{s||(s=!0,l(),o(d))},d=>{s||(s=!0,l(),i(d))})})}var Rq,Gut=T(()=>{"use strict";Rq=class extends Error{static{a(this,"McpTimeoutError")}constructor(t){super(t),this.name="McpTimeoutError"}};a(qSr,"createMcpDeadline");a(Cre,"remainingMcpDeadlineMs");a(Ere,"waitWithinMcpDeadline");a(Pq,"withTimeout")});async function VSr(e){let t=e.transactionTtlMs??Hut,n=(await wre(e.credentialStore,e.keyPrefix))?.generation,o=await FSr({credentialsFilePath:e.credentialStore.filePath,keyPrefix:e.keyPrefix});if(!o)return await sFo(e,n,t);try{let i=await wre(e.credentialStore,e.keyPrefix);return Zut(i,n)?{status:"already-authorized"}:await aFo(e,{attemptId:o.attemptId,baselineGeneration:n,transactionTtlMs:t})}finally{await $Sr(e.credentialStore,e.keyPrefix,o.attemptId).catch(()=>{}),await o.release()}}async function aFo(e,t){let r=(0,Mq.randomBytes)(24).toString("base64url"),n=uFo(e.config.redirectPath,e.serverName),o;try{o=await hte({callbackPath:n,state:r})}catch(s){return e.logger?.warn("MCP OAuth callback listener failed",{event:"mcp.oauth.callback_listener.failed",...Q1e(e,r),error:s instanceof Error?s.message:String(s),status:"failed"}),{status:"failed",error:s}}let i=new Wut({attemptId:t.attemptId,baselineGeneration:t.baselineGeneration,callbackServer:o,config:e.config,credentialStore:e.credentialStore,keyPrefix:e.keyPrefix,logger:e.logger,onAuthorizationRequired:e.onAuthorizationRequired,openAuthorizationUrl:e.openAuthorizationUrl,requestedScope:e.requestedScope,serverName:e.serverName,state:r,transactionTtlMs:t.transactionTtlMs});try{if(await rL(i,{serverUrl:e.serverUrl,...e.requestedScope?{scope:e.requestedScope}:{},...e.resourceMetadataUrl?{resourceMetadataUrl:e.resourceMetadataUrl}:{},...e.fetchFn?{fetchFn:e.fetchFn}:{},...e.forceReauthorization?{forceReauthorization:!0}:{}})==="AUTHORIZED")return{status:"authorized"};let u=await Pq(o.waitForCallback(),t.transactionTtlMs,`MCP server ${e.serverName} OAuth authorization timed out`,e.signal),l=new URL(u.url).searchParams,c=l.get("code")??u.code,d=l.get("iss");return await rL(i,{serverUrl:e.serverUrl,authorizationCode:c,...d?{iss:d}:{},...e.requestedScope?{scope:e.requestedScope}:{},...e.resourceMetadataUrl?{resourceMetadataUrl:e.resourceMetadataUrl}:{},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),e.logger?.info("MCP OAuth authorization completed",{event:"mcp.oauth.authorization.completed",...Q1e(e,r),status:"completed"}),{status:"authorized"}}catch(s){let u=await wre(e.credentialStore,e.keyPrefix);return Zut(u,t.baselineGeneration)?{status:"already-authorized"}:(e.logger?.warn("MCP OAuth authorization failed",{event:"mcp.oauth.authorization.failed",...Q1e(e,r),error:s instanceof Error?s.message:String(s),status:"failed"}),{status:"failed",error:s})}finally{await o.close().catch(()=>{})}}async function sFo(e,t,r){let n=Date.now()+r,o;for(e.logger?.info("MCP OAuth authorization is already in progress elsewhere",{event:"mcp.oauth.authorization.following",...Q1e(e),status:"waiting"});Date.now()<n&&!e.signal?.aborted;){let i=await wre(e.credentialStore,e.keyPrefix);if(Zut(i,t))return{status:"already-authorized"};let s=await USr(e.credentialStore,e.keyPrefix);s&&s.authorizationUrl!==o&&(o=s.authorizationUrl,await e.onAuthorizationRequired?.({authorizationUrl:s.authorizationUrl,redirectUrl:"",serverName:e.serverName})),await cFo(iFo,e.signal)}return{status:"pending",...o?{authorizationUrl:o}:{}}}function Zut(e,t){return!!(e?.tokens&&e.generation!==t)}function uFo(e,t){let r=`/oauth/callback/mcp/${encodeURIComponent(t)}`;return e?e.startsWith("/")?e:`/${e}`:r}function Q1e(e,t){return{adapterInstanceId:e.adapterInstanceId,credentialKeyPrefix:e.keyPrefix,mcpServerName:e.serverName,...t?{oauthStateId:(0,Mq.createHash)("sha256").update(t).digest("hex").slice(0,16)}:{},processId:process.pid}}function lFo(e){if(e)return(0,Mq.createHash)("sha256").update(e).digest("hex").slice(0,12)}function cFo(e,t){return new Promise(r=>{let n=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e),o=a(()=>{clearTimeout(n),r()},"onAbort");t?.addEventListener("abort",o,{once:!0})})}var Mq,Hut,iFo,Wut,GSr=T(()=>{"use strict";Mq=require("node:crypto");_re();Sbe();tR();Vut();J1e();Gut();Hut=300*1e3,iFo=500;a(VSr,"runMcpInteractiveAuthorization");a(aFo,"leadAuthorization");a(sFo,"followAuthorization");Wut=class{static{a(this,"InteractiveAuthorizationProvider")}attemptId;baselineGeneration;callbackServer;config;credentialStore;keyPrefix;logger;onAuthorizationRequired;openAuthorizationUrl;requestedScope;serverName;stateValue;transactionId;transactionTtlMs;issuer;memoryCodeVerifier;memoryDiscoveryState;transactionClientInformation;constructor(t){this.attemptId=t.attemptId,this.baselineGeneration=t.baselineGeneration,this.callbackServer=t.callbackServer,this.config=t.config,this.credentialStore=t.credentialStore,this.keyPrefix=t.keyPrefix,this.logger=t.logger,this.onAuthorizationRequired=t.onAuthorizationRequired,this.openAuthorizationUrl=t.openAuthorizationUrl,this.requestedScope=t.requestedScope,this.serverName=t.serverName,this.stateValue=t.state,this.transactionId=(0,Mq.createHash)("sha256").update(t.state).digest("hex"),this.transactionTtlMs=t.transactionTtlMs}get redirectUrl(){return this.callbackServer.callbackUrl}get clientMetadata(){return{client_name:this.config.clientName??`ZCode ${this.serverName}`,grant_types:["authorization_code","refresh_token"],redirect_uris:[this.redirectUrl],response_types:["code"],...this.config.clientSecret?{token_endpoint_auth_method:"client_secret_basic"}:{},...this.requestedScope??this.config.scope?{scope:this.requestedScope??this.config.scope}:{}}}state(){return this.stateValue}clientInformation(){return this.config.clientId?{client_id:this.config.clientId,...this.config.clientSecret?{client_secret:this.config.clientSecret}:{}}:this.transactionClientInformation}saveClientInformation(t){this.transactionClientInformation=t}tokens(){}async saveTokens(t){let r=this.clientInformation();if(!r)throw new Error(`Missing MCP OAuth client information for ${this.serverName}`);let n=await kre(this.credentialStore,this.keyPrefix,{clientInformation:r,...this.issuer?{issuer:this.issuer}:{},publishedBy:this.transactionId,tokens:t});this.logger?.info("MCP OAuth credentials published",{event:"mcp.oauth.credentials.published",...this.logContext(),clientIdHash:lFo(r.client_id),grantKind:"authorization_code",hasRefreshToken:!!t.refresh_token,publishedGeneration:n.generation.slice(0,12),status:"completed",tokenExpiresInSeconds:t.expires_in})}async redirectToAuthorization(t){let r={authorizationUrl:t.toString(),redirectUrl:this.redirectUrl,serverName:this.serverName};await zSr(this.credentialStore,this.keyPrefix,{attemptId:this.attemptId,authorizationUrl:r.authorizationUrl,...this.baselineGeneration?{baselineGeneration:this.baselineGeneration}:{},expiresAt:Date.now()+this.transactionTtlMs,state:this.stateValue}),this.logger?.info("MCP OAuth authorization required",{event:"mcp.oauth.authorization.required",...this.logContext(),callbackPort:Number(new URL(this.redirectUrl).port),status:"waiting"}),await this.onAuthorizationRequired?.(r),await this.openAuthorizationUrl?.(r)}saveCodeVerifier(t){this.memoryCodeVerifier=t}codeVerifier(){if(!this.memoryCodeVerifier)throw new Error(`Missing MCP OAuth PKCE verifier for ${this.serverName}`);return this.memoryCodeVerifier}saveAuthorizationServerUrl(t){this.issuer=t}authorizationServerUrl(){return this.issuer}async saveDiscoveryState(t){this.memoryDiscoveryState=t,await Ire(this.credentialStore,this.keyPrefix,t)}async discoveryState(){return this.memoryDiscoveryState?this.memoryDiscoveryState:await Tre(this.credentialStore,this.keyPrefix)}logContext(){return{credentialKeyPrefix:this.keyPrefix,mcpServerName:this.serverName,oauthAttemptId:this.attemptId.slice(0,12),oauthStateId:this.transactionId.slice(0,16),processId:process.pid}}};a(Zut,"hasNewerCredentials");a(uFo,"normalizeCallbackPath");a(Q1e,"logContext");a(lFo,"hashIdentifier");a(cFo,"sleep")});async function Kut(e){let t=(await SI(e.credentialStore,e.keyPrefix))?.generation,r=hFo(e.credentialStore.filePath,e.keyPrefix);try{return await yte(r,async()=>await pFo(e,t),{lockMaxWaitMs:dFo})}catch(n){if(!Vkt(n))throw n;let o=await SI(e.credentialStore,e.keyPrefix);if(o?.tokens&&o.generation!==t)return o.tokens.access_token;throw Fut({cause:n,serverName:e.serverName})}}async function pFo(e,t){let r=await SI(e.credentialStore,e.keyPrefix);if(r?.tokens&&r.generation!==t)return r.tokens.access_token;if(!r?.tokens)throw rR({reason:"no_credentials",serverName:e.serverName});let n=r.tokens.refresh_token,o=r.clientInformation;if(!n||!o)throw rR({reason:"no_refresh_token",serverName:e.serverName});let i;try{i=await fFo(e,r)}catch(s){return WSr(e,r,s)}try{let s=await vut(i.authorizationServerUrl,{clientInformation:o,refreshToken:n,...i.metadata?{metadata:i.metadata}:{},...i.resource?{resource:i.resource}:{},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),u=await kre(e.credentialStore,e.keyPrefix,{clientInformation:o,...r.issuer?{issuer:r.issuer}:{},publishedBy:`refresh:${e.keyPrefix}`,tokens:s});return e.logger?.info("MCP OAuth access token refreshed",{event:"mcp.oauth.refresh.completed",credentialKeyPrefix:e.keyPrefix,mcpServerName:e.serverName,processId:process.pid,publishedGeneration:u.generation.slice(0,12),reactive:e.reactive,refreshTokenRotated:s.refresh_token!==n,status:"completed"}),s.access_token}catch(s){return await mFo(e,r,s)}}async function mFo(e,t,r){let n=r instanceof xI?r.code:void 0;if(e.logger?.warn("MCP OAuth access token refresh failed",{event:"mcp.oauth.refresh.failed",credentialKeyPrefix:e.keyPrefix,credentialSource:t.source,mcpServerName:e.serverName,oauthErrorCode:n,processId:process.pid,reactive:e.reactive,status:"failed"}),n===Yv.InvalidGrant)throw t.raw&&await jut(e.credentialStore,e.keyPrefix,t.raw,"tokens"),rR({cause:r,reason:"invalid_grant",serverName:e.serverName});if(n===Yv.InvalidClient||n===Yv.UnauthorizedClient)throw e.staticClientId?new Error(`MCP server ${e.serverName} OAuth client was rejected by the authorization server (invalid_client). The configured clientId is not usable; fix the MCP oauth configuration.`,{cause:r}):(t.raw&&await jut(e.credentialStore,e.keyPrefix,t.raw,"all"),rR({cause:r,reason:"invalid_client",serverName:e.serverName}));return WSr(e,t,r)}function WSr(e,t,r){if(e.reactive||!t.tokens)throw Fut({cause:r,serverName:e.serverName});return t.tokens.access_token}async function fFo(e,t){let r=await Tre(e.credentialStore,e.keyPrefix,{...t.issuer?{expectedIssuer:t.issuer}:{}}),n=r??await $1e(e.serverUrl,{...e.fetchFn?{fetchFn:e.fetchFn}:{}});r||await Ire(e.credentialStore,e.keyPrefix,n);let o=await yut(e.serverUrl,{},n.resourceMetadata);return{authorizationServerUrl:n.authorizationServerUrl,...n.authorizationServerMetadata?{metadata:n.authorizationServerMetadata}:{},...o?{resource:o}:{}}}function hFo(e,t){return(0,X1e.join)((0,X1e.dirname)(e),`${$ut(t)}.refresh`)}var X1e,dFo,HSr=T(()=>{"use strict";X1e=require("node:path");_re();gt();Tbe();tR();Sre();Vut();J1e();dFo=45e3;a(Kut,"refreshMcpOAuthTokensUnderLock");a(pFo,"refreshLocked");a(mFo,"handleRefreshFailure");a(WSr,"failSoft");a(fFo,"resolveAsMetadata");a(hFo,"resolveRefreshLockPath")});function ZSr(e){let t={credentialStore:e.credentialStore,...e.fetchFn?{fetchFn:e.fetchFn}:{},keyPrefix:e.keyPrefix,...e.logger?{logger:e.logger}:{},serverName:e.serverName,serverUrl:e.serverUrl,...e.config.clientId?{staticClientId:e.config.clientId}:{}};return{async token(){let r=await SI(e.credentialStore,e.keyPrefix);if(r?.tokens)return!ASr(r)||!r.tokens.refresh_token?r.tokens.access_token:await Kut({...t,reactive:!1})},async onUnauthorized(){let r=await SI(e.credentialStore,e.keyPrefix);if(!r?.tokens?.refresh_token)throw rR({reason:r?.tokens?"no_refresh_token":"no_credentials",serverName:e.serverName});await Kut({...t,reactive:!0})}}}var KSr=T(()=>{"use strict";tR();Sre();HSr();a(ZSr,"createMcpOAuthTokenProvider")});async function tke(e,t={}){if(QSr(t)==="win32"){await CFo(e,t);return}await EFo(e,t)}function nR(e,t){let r=t.kill??process.kill;try{return r(e,0),!0}catch(n){return bFo(n)}}function bFo(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EPERM"}function QSr(e){return e.platform??process.platform}function wFo(e){return new Promise(t=>setTimeout(t,e))}function kFo(e){return e.split(/\s+/).map(t=>Number(t)).filter(t=>Number.isInteger(t)&&t>0)}function SFo(e){return e==="darwin"?["-axo","pid=,ppid="]:["-eo","pid=,ppid="]}function IFo(e,t){let r=[];for(let n of e.split(/\r?\n/)){let[o,i]=n.trim().split(/\s+/),s=Number(o),u=Number(i);Number.isInteger(s)&&s>0&&u===t&&r.push(s)}return r}async function TFo(e,t){let r=await elt("pgrep",["-P",String(e)],{encoding:"utf8",timeout:JSr},t);if(!r.error&&r.status===0&&r.stdout)return kFo(String(r.stdout));let n=await elt("ps",SFo(QSr(t)),{encoding:"utf8",timeout:JSr},t);return n.error||n.status!==0||!n.stdout?[]:IFo(String(n.stdout),e)}async function Xut(e,t,r=new Set){if(r.has(e))return[];r.add(e);let n=[];for(let o of await TFo(e,t))n.push(o,...await Xut(o,t,r));return n}function eke(e){return[...new Set(e.filter(t=>t>0))]}function Jut(e,t,r){let n=r.kill??process.kill;try{n(e,t)}catch{}}function Yut(e,t,r){let n=r.kill??process.kill;try{n(-e,t)}catch{}}async function CFo(e,t){if(!nR(e,t))return;let r=await elt("taskkill",["/PID",String(e),"/T","/F"],{encoding:"utf8",timeout:xFo,windowsHide:!0},t);if(PFo(r)&&nR(e,t))throw new Error(`taskkill failed for MCP stdio process tree pid=${e} status=${r.status??"unknown"}`)}async function EFo(e,t){if(!nR(e,t))return;let r=eke(await Xut(e,t)).reverse(),n=eke([...r,e]);Yut(e,"SIGINT",t);for(let u of n)Jut(u,"SIGINT",t);if(await Qut(n,gFo,t),!n.some(u=>nR(u,t)))return;Yut(e,"SIGTERM",t);for(let u of n)Jut(u,"SIGTERM",t);if(await Qut(n,_Fo,t),!n.some(u=>nR(u,t)))return;let o=eke(await Xut(e,t)).reverse(),i=eke([...o,...n]);for(let u of i)nR(u,t)&&Jut(u,"SIGKILL",t);Yut(e,"SIGKILL",t),await Qut(i,yFo,t);let s=i.filter(u=>nR(u,t));if(s.length>0)throw new Error(`SIGKILL failed for MCP stdio process tree pid=${e} remaining=${s.join(",")}`)}async function Qut(e,t,r){let n=r.sleep??wFo,o=r.now??Date.now,i=o();for(;o()-i<t;){if(!e.some(s=>nR(s,r)))return;await n(vFo)}}function elt(e,t,r,n){return(n.execFile??AFo)(e,t,r)}function AFo(e,t,r){return new Promise(n=>{(0,YSr.execFile)(e,[...t],r,(o,i,s)=>{n({error:o,status:RFo(o),stderr:s,stdout:i})})})}function RFo(e){if(!e||typeof e!="object"||!("code"in e))return 0;let t=e.code;return typeof t=="number"?t:null}function PFo(e){return!!e.error||e.status!==null&&e.status!==0}var YSr,JSr,gFo,_Fo,yFo,vFo,xFo,tlt=T(()=>{"use strict";YSr=require("node:child_process"),JSr=1e3,gFo=250,_Fo=750,yFo=250,vFo=25,xFo=2e3;a(tke,"terminateMcpStdioProcessTree");a(nR,"isProcessAlive");a(bFo,"isPermissionDenied");a(QSr,"getPlatform");a(wFo,"defaultSleep");a(kFo,"parsePidList");a(SFo,"getPosixProcessListArgs");a(IFo,"parseChildPidsFromProcessList");a(TFo,"collectChildPids");a(Xut,"collectDescendantPids");a(eke,"uniquePids");a(Jut,"killPid");a(Yut,"killProcessGroup");a(CFo,"terminateWindowsProcessTree");a(EFo,"terminatePosixProcessTree");a(Qut,"waitUntilAllExited");a(elt,"runCommand");a(AFo,"defaultExecFile");a(RFo,"getExitStatus");a(PFo,"didTerminationFail")});async function eIr(e,t={}){if((t.platform??process.platform)!=="win32"||!Number.isInteger(e)||e<=0)return;let r=t.api??await MFo();if(!r)return;let n;try{if(n=r.create(),!n||!r.assign(n,e)){n&&r.close(n);return}}catch{if(n)try{r.close(n)}catch{}return}let o=!1;return{terminate(){o||r.terminate(n)},close(){o||(o=!0,r.close(n))}}}async function MFo(){return XSr??=OFo(),XSr}async function OFo(){try{let e=await import("koffi"),t="default"in e?e.default:e,r=t.load("kernel32.dll"),n=t.pointer("HANDLE",t.opaque()),o=t.struct("JOBOBJECT_BASIC_LIMIT_INFORMATION",{PerProcessUserTimeLimit:"int64",PerJobUserTimeLimit:"int64",LimitFlags:"uint32",MinimumWorkingSetSize:"size_t",MaximumWorkingSetSize:"size_t",ActiveProcessLimit:"uint32",Affinity:"uintptr_t",PriorityClass:"uint32",SchedulingClass:"uint32"}),i=t.struct("IO_COUNTERS",{ReadOperationCount:"uint64",WriteOperationCount:"uint64",OtherOperationCount:"uint64",ReadTransferCount:"uint64",WriteTransferCount:"uint64",OtherTransferCount:"uint64"}),s=t.struct("JOBOBJECT_EXTENDED_LIMIT_INFORMATION",{BasicLimitInformation:o,IoInfo:i,ProcessMemoryLimit:"size_t",JobMemoryLimit:"size_t",PeakProcessMemoryUsed:"size_t",PeakJobMemoryUsed:"size_t"}),u=r.func("__stdcall","CreateJobObjectW",n,["void *","str16"]),l=r.func("__stdcall","SetInformationJobObject","bool",[n,"uint32",t.pointer(s),"uint32"]),c=r.func("__stdcall","OpenProcess",n,["uint32","bool","uint32"]),d=r.func("__stdcall","AssignProcessToJobObject","bool",[n,n]),p=r.func("__stdcall","TerminateJobObject","bool",[n,"uint32"]),m=r.func("__stdcall","CloseHandle","bool",[n]);return{create(){let h=u(null,null);if(!h)return;if(!l(h,9,{BasicLimitInformation:{PerProcessUserTimeLimit:0,PerJobUserTimeLimit:0,LimitFlags:8192,MinimumWorkingSetSize:0,MaximumWorkingSetSize:0,ActiveProcessLimit:0,Affinity:0,PriorityClass:0,SchedulingClass:0},IoInfo:{ReadOperationCount:0,WriteOperationCount:0,OtherOperationCount:0,ReadTransferCount:0,WriteTransferCount:0,OtherTransferCount:0},ProcessMemoryLimit:0,JobMemoryLimit:0,PeakProcessMemoryUsed:0,PeakJobMemoryUsed:0},t.sizeof(s))){m(h);return}return h},assign(h,_){let y=c(257,!1,_);if(!y)return!1;try{return!!d(h,y)}finally{m(y)}},terminate(h){p(h,1)},close(h){m(h)}}}catch{return}}var XSr,tIr=T(()=>{"use strict";a(eIr,"attachProcessToWindowsJobObject");a(MFo,"loadWindowsJobObjectApi");a(OFo,"createWindowsJobObjectApi")});function DFo(e,t){if(!("method"in e)||!t||Object.keys(t).length===0)return e;let r=nIr(e.params)?e.params:{},n=nIr(r._meta)?r._meta:{};return{...e,params:{...r,_meta:{...n,...t}}}}function nIr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var rIr,oR,oIr=T(()=>{"use strict";Aut();tlt();tIr();rIr=Object.getOwnPropertyDescriptor(yre.prototype,"_dispose")?.value,oR=class extends yre{static{a(this,"ProcessTreeStdioClientTransport")}childProcess;lastProcessExit;requestMetaProvider;windowsJobObjectFactory;windowsJobObject;constructor(t,r={}){super(t),this.requestMetaProvider=t.requestMetaProvider,this.windowsJobObjectFactory=r.windowsJobObjectFactory??eIr}async terminateWindowsJobObject(){let t=this.windowsJobObject;if(this.windowsJobObject=void 0,!!t)try{t.terminate()}catch{}finally{try{t.close()}catch{}}}async send(t){let r=await this.requestMetaProvider?.();await super.send(DFo(t,r))}async start(){let t=Date.now();await super.start();let r=this._process;if(!r)return;this.childProcess=r;let n=a((o,i)=>{this.lastProcessExit??={exitCode:o,exitedAt:Date.now(),signal:i,startedAt:t}},"recordExit");if(r.exitCode!==null||r.signalCode!==null){n(r.exitCode,r.signalCode);return}if(r.once("exit",n),!(process.platform!=="win32"||this.pid==null))try{this.windowsJobObject=await this.windowsJobObjectFactory(this.pid)}catch{this.windowsJobObject=void 0}}get processExit(){return this.lastProcessExit}get processAlive(){return!!(this.childProcess&&this.childProcess.exitCode===null&&this.childProcess.signalCode===null)}};a(DFo,"mergeRequestMeta");a(nIr,"isRecord");Object.defineProperty(oR.prototype,"_dispose",{configurable:!0,async value(){let e=this.pid;if(await this.terminateWindowsJobObject(),typeof e=="number"&&Number.isInteger(e)&&e>0)try{await tke(e)}catch{}if(rIr){await rIr.call(this);return}await this.close()}})});async function sIr(e,t={}){let r=[...new Set(e.filter(n=>Number.isInteger(n)&&n>0))];return r.length===0?new Map:(t.platform??process.platform)==="win32"?await jFo(r,t.execFile??iIr):await BFo(r,t.execFile??iIr)}async function BFo(e,t){let r=await t("ps",["-eo","pid=,ppid=,rss="],uIr());if(r.error||r.status!==0)return;let n=FFo(r.stdout),o=new Map(n.map(s=>[s.pid,s])),i=new Map;for(let s of n){let u=i.get(s.parentPid)??[];u.push(s.pid),i.set(s.parentPid,u)}return new Map(e.flatMap(s=>{if(!o.has(s))return[];let u=new Set,l=0,c=a(d=>{if(!u.has(d)){u.add(d),l+=o.get(d)?.memoryKb??0;for(let p of i.get(d)??[])c(p)}},"visit");return c(s),[[s,{memoryKb:l,memoryScope:"process_tree"}]]}))}async function jFo(e,t){let r=await t("tasklist",["/FO","CSV","/NH"],{...uIr(),windowsHide:!0});if(r.error||r.status!==0)return;let n=new Set(e),o=new Map;for(let i of r.stdout.split(/\r?\n/)){let s=zFo(i),u=Number(s[1]);if(!n.has(u))continue;let l=(s[4]??"").replace(/\D/g,"");if(!l)continue;let c=Number(l);!Number.isFinite(c)||c<0||o.set(u,{memoryKb:c,memoryScope:"direct_process"})}return o}function FFo(e){let t=[];for(let r of e.split(/\r?\n/)){let[n,o,i]=r.trim().split(/\s+/),s=Number(n),u=Number(o),l=Number(i);!Number.isInteger(s)||s<=0||!Number.isInteger(u)||u<0||!Number.isFinite(l)||l<0||t.push({memoryKb:l,parentPid:u,pid:s})}return t}function zFo(e){let t=[];for(let r of e.matchAll(/"((?:[^"]|"")*)"/g))t.push((r[1]??"").replace(/""/g,'"'));return t}function uIr(){return{encoding:"utf8",maxBuffer:LFo,timeout:NFo}}function iIr(e,t,r){return new Promise(n=>{(0,aIr.execFile)(e,[...t],r,(o,i,s)=>{n({...o?{error:o}:{},status:UFo(o),stderr:s,stdout:i})})})}function UFo(e){if(!e||typeof e!="object"||!("code"in e))return 0;let t=e.code;return typeof t=="number"?t:null}var aIr,NFo,LFo,lIr=T(()=>{"use strict";aIr=require("node:child_process"),NFo=5e3,LFo=8*1024*1024;a(sIr,"readMcpProcessMemorySamples");a(BFo,"readPosixProcessTreeMemory");a(jFo,"readWindowsDirectProcessMemory");a(FFo,"parsePosixRows");a(zFo,"parseCsvFields");a(uIr,"commandOptions");a(iIr,"defaultExecFile");a(UFo,"resolveExitStatus")});function nlt(e){let t=e.arch??process.arch,r=e.now??Date.now,n=e.platform??process.platform,o=e.randomId??rke.randomUUID,i=e.readMemorySamples??sIr,s=e.timer??GFo,u=new Map,l,c=a(p=>{try{e.onEvent(p)}catch{}},"emit"),d=a(async()=>{let p=[...u.values()].filter(_=>_.process!==void 0);if(p.length===0)return;let m=await i(p.flatMap(_=>_.process?[_.process.pid]:[]));if(!m)return;let h=r();for(let _ of p){let y=_.process;if(!y)continue;let v=m.get(y.pid);if(!v){_.owners.size===0&&(_.process=void 0,u.delete(_.connectionId));continue}let x=new Set([..._.owners.values()].filter(b=>b!==void 0)),w=_.owners.size===0&&_.unownedAt!==void 0?Math.max(0,h-_.unownedAt):0;c({arch:t,kind:"memory",mcpId:_.mcpId,mcpInstanceId:y.instanceId,mcpIsolation:_.isolation,mcpSource:_.mcpSource,memoryKb:v.memoryKb,memoryScope:v.memoryScope,occurredAt:h,orphanSuspected:_.owners.size===0&&w>6e4,ownerSessionCount:x.size,platform:n,unownedSeconds:w/1e3})}},"sampleNow");return{acquireOwner(p){let m=u.get(p.connectionId);m&&(m.owners.set(p.ownerId,p.sessionId),m.unownedAt=void 0)},recordProcessCrashed(p){let m=u.get(p.connectionId),h=m?.process;if(!m||!h)return;m.process=void 0;let _=r(),y=new Set([...m.owners.values()].filter(v=>v!==void 0));c({affectedSessionCount:y.size,arch:t,exitCode:p.exitCode,kind:"process_crash",mcpId:m.mcpId,mcpInstanceId:h.instanceId,mcpIsolation:m.isolation,mcpSource:m.mcpSource,occurredAt:_,platform:n,signal:p.signal,uptimeMs:Math.max(0,_-h.startedAt)})},recordProcessClosed(p){let m=u.get(p.connectionId);m&&(m.process=void 0,m.owners.size===0&&u.delete(p.connectionId))},recordProcessStarted(p){let m=u.get(p.connectionId);if(!m||!Number.isInteger(p.pid)||p.pid<=0)return;let h=o(),_=r();return m.process={instanceId:h,pid:p.pid,startedAt:_},m.owners.size===0&&(m.unownedAt??=_),c({arch:t,kind:"process_start",mcpId:m.mcpId,mcpInstanceId:h,mcpIsolation:m.isolation,mcpSource:m.mcpSource,occurredAt:_,platform:n}),{mcpId:m.mcpId,mcpInstanceId:h}},recordSessionStartup(p){c({arch:t,configuredCount:p.configuredCount,connectedCount:p.connectedCount,failedCount:p.failedCount,kind:"session_startup",occurredAt:r(),platform:n,processCount:p.processCount,sessionId:p.sessionId})},releaseOwner(p){let m=u.get(p.connectionId);!m||!m.owners.delete(p.ownerId)||m.owners.size===0&&(m.unownedAt=r())},registerConnection(p){let m=p.source??WFo(p.serverName);u.set(p.connectionId,{connectionId:p.connectionId,isolation:p.isolation,mcpId:HFo(p.serverName,m,e.idSalt),mcpSource:m,owners:new Map})},unregisterConnection(p){let m=u.get(p.connectionId);m&&(m.owners.clear(),m.unownedAt??=r(),m.process||u.delete(p.connectionId))},sampleNow:d,start(){if(!l)try{l=s.setInterval(()=>{d().catch(()=>{})},dIr),l.unref?.()}catch{l=void 0}},stop(){if(!l)return;let p=l;l=void 0;try{s.clearInterval(p)}catch{}}}}function WFo(e){return e===qFo?"builtin":e.startsWith(rlt)?"plugin":"custom"}function HFo(e,t,r){if(t==="builtin"){let o=e.startsWith(rlt)?e.slice(rlt.length):e;return`${$Fo}${o.split(":").map(ZFo).join(":")}`}let n=(0,rke.createHmac)("sha256",r).update(e).digest("hex").slice(0,12);return`${t}:${n}`}function ZFo(e){let t="";for(let r of cIr.Buffer.from(e,"utf8")){let n=String.fromCharCode(r);t+=VFo.test(n)?n:`%${r.toString(16).toUpperCase().padStart(2,"0")}`}return t}var cIr,rke,dIr,$Fo,qFo,VFo,rlt,GFo,pIr=T(()=>{"use strict";cIr=require("node:buffer"),rke=require("node:crypto");lIr();dIr=5*6e4,$Fo="builtin:",qFo="node_repl",VFo=/^[A-Za-z0-9._~-]$/,rlt="plugin:",GFo={clearInterval(e){clearInterval(e)},setInterval(e,t){return setInterval(e,t)}};a(nlt,"createMcpTelemetryTracker");a(WFo,"resolveMcpSource");a(HFo,"resolveMcpId");a(ZFo,"encodeMcpIdSegment")});function ult(e={}){return new slt(e)}function gIr(e={}){return Mut({logger:e.logger,telemetry:e.telemetry,createAdapter:a(({connectionContext:t,workingDirectory:r})=>ult({...e,connectionContext:t,workingDirectory:r??e.workingDirectory}),"createAdapter")})}function QFo(e,t){let r={...e?{trace_id:e.traceId}:{},...e?.spanId?{span_id:e.spanId}:{},...e?.parentSpanId?{parent_span_id:e.parentSpanId}:{},...e?.sessionId?{session_id:e.sessionId}:{},...e?.turnId?{turn_id:e.turnId}:{},...t?{runtime_scope:t}:{}};return{...r,"com.zcode/request-context":r}}function _Ir(e){return e.protocolVersion==="2026-07-28"?{pin:"2026-07-28"}:e.type==="sse"||e.protocolVersion==="legacy"?"legacy":"auto"}function yIr(e){if(Xr.isInstance(e)&&e.code===Ar.EraNegotiationFailed||yq.isInstance(e))return!0;let t=e?.cause;return t!==void 0&&t!==e?yIr(t):!1}function XFo(e){let t=_Ir(e);return typeof t=="object"?t.pin:t}function ezo(e,t){let r=_Ir(e);if(r==="legacy")return{mode:r};let n=typeof r=="object"?Math.max(1,Math.floor(t)):Math.min(JFo,Math.max(1,Math.floor(t/2)));return{mode:r,probe:{timeoutMs:n}}}function tzo(e){return{type:"oauth_authorization_code",authorizationUrl:e.authorizationUrl,startedAt:new Date().toISOString()}}function ilt(e){if(e.type!=="stdio"&&!Are(e)){if(e.oauth?.type==="authorization_code")return e.oauth;if(e.oauth?.type!=="client_credentials"&&!rzo(e.headers))return{type:"authorization_code"}}}function Are(e){return(e.type==="http"||e.type==="stdio")&&e.auth?.type==="zcode_official"&&e.auth.provider==="jwt_token"&&e.official!==void 0}function rzo(e){return e?Object.keys(e).some(t=>t.toLowerCase()==="authorization"):!1}function nzo(e){let t="";return{append(r){r&&(t=`${t}${r}`,t.length>e&&(t=t.slice(-e)))},read(){return t}}}function mIr(e){let t=String.raw`(?:api[_-]?key|access[_-]?key|secret(?:[_-]?key)?|private[_-]?key|token|password|passwd|pass|mysql_pass|mysql_password)`,r=e.replace(/(bearer\s+)[^\s"']+/gi,"$1[Redacted]");return r=r.replace(/(\bauthorization\b\s*[:=]\s*)(bearer\s+)?[^\r\n]+/gi,(n,o,i)=>`${o}${i?"Bearer ":""}[Redacted]`),r=r.replace(new RegExp(`([?&]${t}=)[^&\\s]+`,"gi"),"$1[Redacted]"),r=r.replace(new RegExp(`(["']${t}["']\\s*:\\s*)(["'])(?:(?!\\2).)*\\2`,"gi"),"$1$2[Redacted]$2"),r=r.replace(new RegExp(`(\\b${t}\\b\\s*[:=]\\s*)(["']?)[^\\s"',;)}]+`,"gi"),"$1$2[Redacted]"),r.replace(/([a-z][a-z0-9+.-]*:\/\/)[^:\s/@]+:[^@\s/]+@/gi,"$1[Redacted]@")}function oke(e){if(!(e instanceof yre))return;let t=e.pid;return typeof t=="number"&&Number.isInteger(t)&&t>0?t:void 0}function ozo(e){return e instanceof oR?e.processExit:void 0}function izo(e){return e instanceof oR&&e.processAlive}function vIr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function azo(e){return e instanceof os?!0:vIr(e)&&typeof e.code=="number"}var fIr,hIr,alt,nke,KFo,JFo,olt,YFo,slt,ike=T(()=>{"use strict";fIr=require("node:crypto"),hIr=require("node:path"),alt=require("node:util");_re();Aut();ke();fSr();bSr();gt();kSr();Out();BSr();Sre();GSr();Ebe();tR();KSr();tlt();oIr();Gut();Out();pIr();nke=3e4,KFo=5e3,JFo=5e3,olt=4e3,YFo=64;a(ult,"createMcpAdapter");a(gIr,"createMcpAdapterConnectionPool");slt=class{static{a(this,"NodeMcpAdapter")}adapterInstanceId=(0,fIr.randomUUID)();clientName;clientVersion;connectionContext;env;logger;mcpOAuth;network;officialMcpAuth;telemetry;connectionGenerations=new Map;credentialStore;lastOfficialAuthKind=new Map;serverRequestIdBySpan=new Map;connectionDiagnosticByServer=new Map;records=new Map;workingDirectory;constructor(t){this.clientName=t.clientName??"zcode",this.clientVersion=t.clientVersion??"0.0.0",this.connectionContext=t.connectionContext,this.env=t.env,this.logger=t.logger?.child({...this.connectionContext,module:"adapters.mcp"}),this.mcpOAuth=t.mcpOAuth,this.network=t.network,this.officialMcpAuth=t.officialMcpAuth,this.telemetry=t.telemetry,this.workingDirectory=t.workingDirectory}async connectConfiguredServers(t,r={}){let n=Date.now(),o=Object.keys(t);this.logger?.info("MCP configured servers connection started",{event:"mcp.configured_servers.connect.started",serverCount:o.length,serverNames:o,status:"started"});let i=new Set(Object.keys(t));await Promise.all(Array.from(this.records.keys()).filter(c=>!i.has(c)).map(c=>this.disconnectServer(c))),await Promise.all(Object.entries(t).map(([c,d])=>{let p=this.records.get(c);return p?.connecting&&p.status.status==="connecting"&&p.status.authorization&&(0,alt.isDeepStrictEqual)(p.config,d)?this.waitForSharedConnection(c,p,r):this.connectServer(c,d,r)}));let s=await this.status(),u=await this.listTools(),l=Object.values(s).reduce((c,d)=>(c[d.status]=(c[d.status]??0)+1,c),{});return this.logger?.info("MCP configured servers connection completed",{durationMs:Date.now()-n,event:"mcp.configured_servers.connect.completed",serverCount:o.length,status:"completed",statusCounts:l,toolCount:u.length}),{statuses:s,tools:u}}async connectServer(t,r,n={}){let o=Date.now(),i=r.timeoutMs??nke,s=this.nextConnectionGeneration(t);if(this.lastOfficialAuthKind.delete(t),this.connectionDiagnosticByServer.delete(t),this.logger?.info("MCP server connection started",{event:"mcp.server.connect.started",mcpServerName:t,status:"started",timeoutMs:i,transport:r.type}),await this.closeRecord(t),r.enabled===!1){let m=this.createStatus(r,"disabled");return this.records.set(t,{config:r,status:m,tools:[]}),this.logger?.info("MCP server connection skipped",{durationMs:Date.now()-o,event:"mcp.server.connect.skipped",mcpServerName:t,status:"completed",transport:r.type}),m}let u=new AbortController,l=a(()=>{u.abort(n.signal?.reason instanceof Error?n.signal.reason:void 0)},"abortExternal");n.signal?.aborted?l():n.signal?.addEventListener("abort",l,{once:!0});let c=this.createStatus(r,"connecting"),d={abortController:u,config:r,status:c,tools:[]};this.records.set(t,d);let p=this.openServerConnection({config:r,generation:s,name:t,oauthAuthorizationTimeoutMs:n.oauthAuthorizationTimeoutMs,signal:u.signal,timeoutMs:i,workingDirectory:n.workingDirectory}).finally(()=>{n.signal?.removeEventListener("abort",l)});return d.connecting=p,await this.waitForSharedConnection(t,d,n)}async disconnectServer(t){let r=this.records.get(t);if(!r)return;this.nextConnectionGeneration(t),await this.closeRecord(t);let n=this.createStatus(r.config,"disconnected");return this.records.set(t,{config:r.config,status:n,tools:[]}),n}async status(){return Object.fromEntries(Array.from(this.records.entries()).map(([t,r])=>[t,r.status]))}async pingServer(t,r={}){let n=this.records.get(t);if(!n?.client||n.status.status!=="connected")return!1;let o=Math.min(r.timeoutMs??KFo,n.config.timeoutMs??nke),i=this.connectionGenerations.get(t)??0;try{return await n.client.ping({timeout:o}),!0}catch(s){if(azo(s))return!0;if(!this.isCurrentConnection(t,i))return!1;let u=this.records.get(t);return u&&u.client===n.client&&(u.status=this.createStatus(u.config,"disconnected",{error:"MCP server did not answer ping",failureKind:"unexpected_disconnect"})),this.logger?.warn("MCP server ping failed",{...this.connectionContext,error:s instanceof Error?s.message:String(s),event:"mcp.server.ping.failed",mcpServerName:t,status:"failed",transport:n.config.type}),!1}}async listTools(){return Array.from(this.records.values()).flatMap(t=>t.tools)}async callTool(t,r={}){let n=this.records.get(t.serverName),o=r.timeoutMs??n?.config.timeoutMs??nke,i=qSr(o),s=`MCP tool ${t.serverName}/${t.toolName} timed out after ${o}ms`,u=n?.connecting;u&&await Ere(u,i,s,r.signal);let l=this.records.get(t.serverName);l&&l.status.status==="disconnected"&&await Ere(this.reconnectForCall(t.serverName,l.config),i,s,r.signal);let c=this.records.get(t.serverName);if(!c?.client||c.status.status!=="connected")throw new Error(`MCP server is not connected: ${t.serverName}`);try{return await this.callToolOnClient(c.client,t,Cre(i,s),r.signal)}catch(d){let p=K1e(d);if(p&&c.config.type!=="stdio")return await this.recoverToolCallAuthorization({error:d,record:c,request:t,deadline:i,timeoutMessage:s,trigger:p,...r.signal?{signal:r.signal}:{}});if(!(d instanceof Error)||d.message!=="Not connected")throw d;try{await Ere(this.reconnectForCall(t.serverName,c.config),i,s,r.signal)}catch(h){throw this.logger?.warn("MCP server reconnect failed",{error:h instanceof Error?h.message:String(h),event:"mcp.server.reconnect.failed",mcpServerName:t.serverName,status:"failed"}),d}let m=this.records.get(t.serverName);if(!m?.client||m.status.status!=="connected")throw d;return await this.callToolOnClient(m.client,t,Cre(i,s),r.signal)}}rememberServerResponse(t,r){if(!r.spanId&&r.rpcMethod!=="tools/call"&&this.records.get(t)?.status.status==="connecting"){r.failureKind&&this.connectionDiagnosticByServer.set(t,{failureKind:r.failureKind,...r.serverRequestId?{serverRequestId:r.serverRequestId}:{}});return}if(r.spanId&&r.serverRequestId)for(this.serverRequestIdBySpan.set(r.spanId,r.serverRequestId);this.serverRequestIdBySpan.size>YFo;){let n=this.serverRequestIdBySpan.keys().next();if(n.done)break;this.serverRequestIdBySpan.delete(n.value)}}takeServerRequestId(t){if(!t)return;let r=this.serverRequestIdBySpan.get(t);return r!==void 0&&this.serverRequestIdBySpan.delete(t),r}async resolveOfficialStdioAuthMeta(t,r,n){if(r.type!=="stdio"||!Are(r)||!r.official)return;let o=r.official,i=this.officialMcpAuth?.authHeadersPort,s=this.officialMcpAuth?.trustedOrigins,u=this.officialMcpAuth?.resolveZCodeApiOrigin,l={event:"mcp.official_auth.stdio_meta",mcpKey:o.mcpKey,mcpServerName:t,module:"adapters.mcp"},c=a(h=>(this.logger?.warn("Official MCP stdio auth headers unavailable",{...l,reason:h,status:"failed"}),{ok:!1,reason:h}),"fail");if(!i||!s||!u)return c("official_auth_unavailable");let d,p;try{d=u(),p=await s.isTrusted({mcpKey:o.mcpKey,origin:d,pluginId:o.pluginId})}catch(h){return this.logger?.warn("Official MCP stdio origin resolution failed",{...l,error:h instanceof Error?h.message:String(h),errorName:h instanceof Error?h.name:"unknown",pluginId:o.pluginId}),c("official_auth_unavailable")}if(!p.trusted)return this.logger?.warn("Official MCP stdio origin is not trusted",{...l,detail:p.detail??"unknown",pluginId:o.pluginId,targetOrigin:d}),c("official_mcp_origin_untrusted");let m=await i.resolveHeaders({mcpKey:o.mcpKey,pluginId:o.pluginId,targetOrigin:d,...this.officialMcpAuth?.workspaceIdentity?{workspaceIdentity:this.officialMcpAuth.workspaceIdentity}:{},...this.workingDirectory?{workspacePath:this.workingDirectory}:{},...n?{signal:n}:{}});return m.ok?(this.logger?.debug("Official MCP stdio auth headers attached",{...l,identityHeaderNames:Object.keys(m.headers).map(h=>h.toLowerCase()).sort(),...m.headers["Bigmodel-Target-Type"]?{identityTargetType:m.headers["Bigmodel-Target-Type"]}:{},status:"completed"}),{ok:!0,headers:m.headers}):c(m.reason)}async callToolOnClient(t,r,n,o){let i={event:"mcp.tool.call",mcpServerName:r.serverName,mcpToolName:r.toolName,module:"adapters.mcp",timeoutMs:n},s=Object.keys(r.arguments??{}).sort();this.logger?.debug("MCP tool call started",{...i,argumentKeys:s,status:"started"});let u=Date.now();try{let l=await t.callTool({name:r.toolName,arguments:r.arguments??{},...r.trace||r.runtimeScope?{_meta:QFo(r.trace,r.runtimeScope)}:{}},{signal:o,timeout:n,resetTimeoutOnProgress:!0}),c=Date.now()-u,d=typeof l.isError=="boolean"?l.isError:!1,p=this.takeServerRequestId(r.trace?.spanId),m={...i,contentBlocks:Array.isArray(l.content)?l.content.length:0,durationMs:c,hasStructuredContent:l.structuredContent!==void 0,isError:d,...p?{serverRequestId:p}:{}};d?this.logger?.warn("MCP tool returned an error",{...m,status:"failed"}):this.logger?.debug("MCP tool call completed",{...m,status:"completed"});let h=vIr(l._meta)?l._meta:void 0;return{content:Array.isArray(l.content)?l.content:[{type:"text",text:""}],structuredContent:l.structuredContent,isError:typeof l.isError=="boolean"?l.isError:void 0,_meta:d&&p?{...h,[N4t]:p}:h}}catch(l){let c=Date.now()-u,d=l instanceof Error?l.message:String(l),p=/timed?\s*out|timeout/i.test(d)||l instanceof Error&&l.name==="AbortError",m=this.takeServerRequestId(r.trace?.spanId);throw this.logger?.warn("MCP tool call failed",{...i,argumentKeys:s,durationMs:c,error:d,...m?{serverRequestId:m}:{},errorName:l instanceof Error?l.name:"unknown",status:"failed",timedOut:p,...p?{budgetExhausted:c>=n*.9}:{}}),l}}async reconnectForCall(t,r){this.logger?.warn("MCP server reconnecting after lost connection",{event:"mcp.server.reconnect.started",mcpServerName:t,status:"started",transport:r.type}),await this.connectServer(t,r)}async recoverToolCallAuthorization(t){let{record:r,request:n}=t,o=r.config;if(o.type==="stdio")throw t.error;let i=ilt(o);if(!i)throw t.error;this.logger?.warn("MCP tool call requires OAuth authorization",{event:"mcp.oauth.tool_call.authorization_required",mcpServerName:n.serverName,oauthTriggerReason:t.trigger.reason,status:"started",toolName:n.toolName});let s=this.ensureToolCallAuthorizationRecovery({config:o,name:n.serverName,oauthConfig:i,record:r,trigger:t.trigger});if((await Ere(s,t.deadline,t.timeoutMessage,t.signal)).status!=="connected")throw t.error;let l=this.records.get(n.serverName);if(!l?.client||l.status.status!=="connected")throw t.error;return await this.callToolOnClient(l.client,n,Cre(t.deadline,t.timeoutMessage),t.signal)}ensureToolCallAuthorizationRecovery(t){let r=this.records.get(t.name);if(r?.connecting&&r.status.status==="connecting"&&(0,alt.isDeepStrictEqual)(r.config,t.config))return r.connecting;let n=this.nextConnectionGeneration(t.name),o=new AbortController,i={abortController:o,config:t.config,status:this.createStatus(t.config,"connecting",{toolCount:t.record.tools.length}),tools:t.record.tools};this.records.set(t.name,i);let s=this.runToolCallAuthorizationRecovery({abortController:o,config:t.config,generation:n,name:t.name,oauthConfig:t.oauthConfig,previousClient:t.record.client,previousTransport:t.record.transport,trigger:t.trigger});return i.connecting=s,s}async runToolCallAuthorizationRecovery(t){let r=Date.now();try{await this.closeClientAndTransport(t.name,t.previousClient,t.previousTransport);let n=await this.runInteractiveOAuthAuthorization({config:t.config,generation:t.generation,name:t.name,oauthConfig:t.oauthConfig,serverUrl:t.config.url,signal:t.abortController.signal,trigger:t.trigger});return n.status==="authorized"||n.status==="already-authorized"?await this.openServerConnection({config:t.config,generation:t.generation,name:t.name,oauthAuthorizationAttempted:!0,signal:t.abortController.signal,timeoutMs:t.config.timeoutMs??nke}):await this.failConnection({config:t.config,error:n.status==="pending"?new Error(`MCP server ${t.name} OAuth authorization is still in progress; complete it in the browser and reconnect`):n.error,failureKind:"oauth_authorization_failed",generation:t.generation,name:t.name,startedAt:r})}catch(n){return await this.failConnection({config:t.config,error:n,failureKind:"oauth_authorization_failed",generation:t.generation,name:t.name,startedAt:r})}}async close(){let t=Date.now(),r=this.records.size;for(let n of this.records.keys())this.nextConnectionGeneration(n);await Promise.all(Array.from(this.records.keys()).map(n=>this.closeRecord(n))),this.records.clear(),this.connectionDiagnosticByServer.clear(),this.logger?.info("MCP adapter closed",{durationMs:Date.now()-t,event:"mcp.adapter.closed",serverCount:r,status:"completed"})}waitForSharedConnection(t,r,n){let o=r.connecting;if(!o)return Promise.resolve(r.status);if(n.oauthAuthorizationTimeoutMs===void 0&&!n.signal)return o;let i,s,u=a(()=>this.records.get(t)?.status??r.status,"currentStatus"),l=[o],c=n.oauthAuthorizationTimeoutMs;return c!==void 0&&l.push(new Promise(d=>{s=setTimeout(()=>d(u()),c)})),n.signal&&l.push(new Promise(d=>{if(n.signal?.aborted){d(u());return}i=a(()=>d(u()),"abortHandler"),n.signal?.addEventListener("abort",i,{once:!0})})),Promise.race(l).finally(()=>{s!==void 0&&clearTimeout(s),i&&n.signal?.removeEventListener("abort",i)})}async openServerConnection(t){let{config:r,generation:n,name:o,oauthAuthorizationAttempted:i=!1,oauthAuthorizationTimeoutMs:s,signal:u,timeoutMs:l,workingDirectory:c}=t,d=Date.now(),p,m,h,_,y,v=r.type==="stdio"?"process_start_failed":"network_unreachable";try{y=(await this.createTransport(r,o,n,s,c,u)).transport,h=this.attachStdioLogging(o,y),p=new vkr({name:this.clientName,version:this.clientVersion},{versionNegotiation:ezo(r,l)}),this.updateCurrentRecord(o,n,{client:p,transport:y});let w=Date.now();await Pq(p.connect(y),l,`MCP server ${o} connection timed out after ${l}ms`,u),m=Date.now()-w,v="tool_list_failed";let b=Date.now(),k=await Pq(p.listTools(),l,`MCP server ${o} tool listing timed out after ${l}ms`,u);_=Date.now()-b;let S=k.tools.map(P=>mSr(o,P,r.timeoutMs,r.type==="http"&&r.auth?.type===MCt)),I=p.getProtocolEra(),C=p.getNegotiatedProtocolVersion(),R=this.createStatus(r,"connected",{protocolEra:I,toolCount:S.length});if(!this.isCurrentConnection(o,n))return await this.closeClientAndTransport(o,p,y),this.records.get(o)?.status??R;this.connectionDiagnosticByServer.delete(o),this.records.set(o,{client:p,config:r,status:R,tools:S,transport:y});let A=oke(y),O=A!=null&&this.connectionContext?this.telemetry?.recordProcessStarted({connectionId:this.connectionContext.mcpConnectionId,pid:A}):void 0;return p.onclose=()=>{if(!this.isCurrentConnection(o,n))return;let P=this.records.get(o);if(!P||P.client!==p)return;let D=h?.(),U=ozo(y);P.status=this.createStatus(P.config,"disconnected",{error:"MCP server connection closed unexpectedly",failureKind:"unexpected_disconnect"}),this.logger?.warn("MCP server connection lost",{...this.connectionContext,event:"mcp.server.connection_lost",mcpServerName:o,...A!=null?{mcpTransportPid:A}:{},...O??{},...U?{exitCode:U.exitCode,signal:U.signal??void 0}:{},status:"failed",transport:P.config.type,...D?{stderr:D}:{}}),P.config.type==="stdio"&&this.connectionContext&&(U||!izo(y))&&this.telemetry?.recordProcessCrashed({connectionId:this.connectionContext.mcpConnectionId,exitCode:U?.exitCode??null,signal:U?.signal??null})},this.logger?.info("MCP server connected",{...this.connectionContext,connectDurationMs:m,durationMs:Date.now()-d,event:"mcp.server.connected",listToolsDurationMs:_,mcpClientName:this.clientName,mcpClientVersion:this.clientVersion,mcpProtocolEra:I??"unknown",mcpProtocolVersion:C??"unknown",mcpServerName:o,...O??{},...A!=null?{mcpTransportPid:A}:{},mcpVersionNegotiationMode:XFo(r),status:"completed",toolCount:S.length,transport:r.type}),R}catch(x){let w=i?void 0:K1e(x),b=w&&r.type!=="stdio"?ilt(r):void 0;if(w&&b&&r.type!=="stdio"){await this.closeClientAndTransport(o,p,y);let S=await this.runInteractiveOAuthAuthorization({config:r,generation:n,name:o,oauthConfig:b,serverUrl:r.url,signal:u,trigger:w});return S.status==="authorized"||S.status==="already-authorized"?await this.openServerConnection({...t,oauthAuthorizationAttempted:!0}):this.failConnection({config:r,connectDurationMs:m,error:S.status==="pending"?new Error(`MCP server ${o} OAuth authorization is still in progress; complete it in the browser and reconnect`):S.error,failureKind:"oauth_authorization_failed",generation:n,getRecentStderr:h,listToolsDurationMs:_,name:o,startedAt:d})}let k=yIr(x)?"protocol_negotiation_failed":void 0;return this.failConnection({client:p,config:r,connectDurationMs:m,error:x,generation:n,getRecentStderr:h,listToolsDurationMs:_,name:o,startedAt:d,transport:y,failureKind:k??v})}}async runInteractiveOAuthAuthorization(t){try{let r=this.createAuthorizationCodeOAuthOptions(t.config,t.name,t.generation),n=r?.credentialStore??$N(),o=Uut(t.name,t.serverUrl,t.oauthConfig),i=t.oauthConfig.scope;if(t.trigger.requiredScope){let s=await SI(n,o);i=hre(t.oauthConfig.scope,s?.tokens?.scope,t.trigger.requiredScope)}return await VSr({adapterInstanceId:this.adapterInstanceId,config:t.oauthConfig,credentialStore:n,fetchFn:xre({env:this.env,network:this.network}),...t.trigger.reason==="insufficient_scope"?{forceReauthorization:!0}:{},keyPrefix:o,logger:this.logger,...r?.onAuthorizationRequired?{onAuthorizationRequired:r.onAuthorizationRequired}:{},...r?.openAuthorizationUrl?{openAuthorizationUrl:r.openAuthorizationUrl}:{},...i?{requestedScope:i}:{},...t.trigger.resourceMetadataUrl?{resourceMetadataUrl:new URL(t.trigger.resourceMetadataUrl)}:{},serverName:t.name,serverUrl:t.serverUrl,signal:t.signal,transactionTtlMs:Hut})}catch(r){return this.logger?.warn("MCP OAuth authorization orchestration failed",{error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"unknown",event:"mcp.oauth.authorization.orchestration_failed",mcpServerName:t.name,status:"failed"}),{status:"failed",error:r}}}async failConnection(t){let{client:r,config:n,connectDurationMs:o,error:i,failureKind:s,generation:u,getRecentStderr:l,listToolsDurationMs:c,name:d,startedAt:p,transport:m}=t,h=i instanceof Error?i.message:String(i),_=(i instanceof Aq?i.kind:void 0)??this.lastOfficialAuthKind.get(d);this.lastOfficialAuthKind.delete(d);let y=this.connectionDiagnosticByServer.get(d);this.connectionDiagnosticByServer.delete(d);let v=(_==="official_mcp_origin_untrusted"?"official_origin_untrusted":void 0)??y?.failureKind??(i instanceof Rq&&s!=="tool_list_failed"?"connection_timeout":void 0)??s??"connection_failed",x=y?.serverRequestId?`${h} - ${y.serverRequestId}`:h,w=this.createStatus(n,"failed",{error:x,failureKind:v,...y?.serverRequestId?{serverRequestId:y.serverRequestId}:{}}),b=l?.(),k=oke(m);return await this.closeClientAndTransport(d,r,m),this.isCurrentConnection(d,u)?(this.records.set(d,{config:n,status:w,tools:[]}),this.logger?.warn("MCP server connection failed",{...this.connectionContext,connectDurationMs:o,durationMs:Date.now()-p,error:x,event:"mcp.server.failed",listToolsDurationMs:c,mcpServerName:d,..._?{officialAuthKind:_}:{},...k!=null?{mcpTransportPid:k}:{},status:"failed",...b?{stderr:b}:{},transport:n.type}),w):this.records.get(d)?.status??w}async createTransport(t,r,n,o,i,s){if(t.type==="stdio")return{transport:new oR({command:t.command,args:t.args??[],cwd:t.cwd?(0,hIr.resolve)(i??this.workingDirectory??process.cwd(),t.cwd):i??this.workingDirectory,env:{...wSr({env:this.env,network:this.network}),...t.env},stderr:"pipe",...Are(t)&&t.official?{requestMetaProvider:a(async()=>{let l=await this.resolveOfficialStdioAuthMeta(r,t,s);return l?{[OCt]:l}:void 0},"requestMetaProvider")}:{}})};let u=xre({env:this.env,network:this.network});if(t.type==="http"){let l=this.createOfficialAuthFetch(t,r,n);return{transport:new bkr(new URL(t.url),{authProvider:this.createOAuthClientProvider(r,t),fetch:l??u,requestInit:t.headers?{headers:t.headers}:void 0})}}return{transport:new xkr(new URL(t.url),{authProvider:this.createOAuthClientProvider(r,t),fetch:u,requestInit:t.headers?{headers:t.headers}:void 0})}}createOfficialAuthFetch(t,r,n){if(!Are(t)||t.type!=="http"||!t.official)return;let o=t.official,i=this.officialMcpAuth?.authHeadersPort,s=this.officialMcpAuth?.trustedOrigins;return s?ySr({baseFetch:xre({env:this.env,network:this.network}),official:o,onAuthFailure:a(u=>this.lastOfficialAuthKind.set(r,u),"onAuthFailure"),onServerResponse:a(u=>{this.isCurrentConnection(r,n)&&this.rememberServerResponse(r,u)},"onServerResponse"),serverName:r,trustedOrigins:s,url:t.url,...i?{authHeadersPort:i}:{},...this.logger?{logger:this.logger}:{},...this.officialMcpAuth?.workspaceIdentity?{workspaceIdentity:this.officialMcpAuth.workspaceIdentity}:{},...this.workingDirectory?{workspacePath:this.workingDirectory}:{}}):(()=>{throw new Aq("official_auth_unavailable",`official MCP trusted origin registry is not available in this runtime: ${r}`)})}createOAuthClientProvider(t,r){if(r.type==="stdio"||Are(r))return;let n=ilt(r);if(n)return ZSr({config:n,credentialStore:this.resolveCredentialStore(),fetchFn:xre({env:this.env,network:this.network}),keyPrefix:Uut(t,r.url,n),...this.logger?{logger:this.logger}:{},serverName:t,serverUrl:r.url});if(r.oauth?.type==="client_credentials")return new fkr({clientId:r.oauth.clientId,clientName:r.oauth.clientName??`${this.clientName}-${t}`,clientSecret:r.oauth.clientSecret,scope:r.oauth.scope})}resolveCredentialStore(){return this.credentialStore??=this.mcpOAuth?.credentialStore??$N(),this.credentialStore}createAuthorizationCodeOAuthOptions(t,r,n,o){return t.type==="stdio"?this.mcpOAuth:{...this.mcpOAuth,authorizationTimeoutMs:o??this.mcpOAuth?.authorizationTimeoutMs,onAuthorizationRequired:a(async i=>{this.updateCurrentRecordStatus(r,n,{authorization:tzo(i),status:"connecting"}),await this.mcpOAuth?.onAuthorizationRequired?.(i)},"onAuthorizationRequired")}}attachStdioLogging(t,r){let n=nzo(olt);return r.stderr?.on("data",i=>{let s=i.toString("utf8");n.append(s),this.logger?.debug("MCP stdio stderr",{event:"mcp.stdio.stderr",mcpServerName:t,stderr:mIr(s).slice(0,olt)})}),()=>{let i=n.read();if(i)return mIr(i).slice(-olt)}}async closeRecord(t){let r=this.records.get(t);r&&(r.abortController?.abort(new Error(`MCP server ${t} connection closed`)),!(!r.client&&!r.transport)&&await this.closeClientAndTransport(t,r.client,r.transport))}async closeClientAndTransport(t,r,n){let o=Date.now(),i=oke(n);r&&(r.onclose=void 0),await this.terminateStdioProcessTree(t,n);try{await r?.close()}catch(s){this.logger?.debug("MCP client close failed",{error:s instanceof Error?s.message:String(s),event:"mcp.client.close.failed",mcpServerName:t})}try{await n?.close()}catch(s){this.logger?.debug("MCP transport close failed",{error:s instanceof Error?s.message:String(s),event:"mcp.transport.close.failed",mcpServerName:t})}this.connectionContext&&n instanceof oR&&!n.processAlive&&this.telemetry?.recordProcessClosed({connectionId:this.connectionContext.mcpConnectionId}),this.logger?.info("MCP server closed",{...this.connectionContext,durationMs:Date.now()-o,event:"mcp.server.closed",mcpServerName:t,...i!=null?{mcpTransportPid:i}:{},status:"completed"})}async terminateStdioProcessTree(t,r){let n=oke(r);if(n!=null)try{await tke(n)}catch(o){this.logger?.warn("MCP stdio process tree cleanup failed",{...this.connectionContext,error:o instanceof Error?o.message:String(o),event:"mcp.stdio.process_tree_cleanup.failed",mcpServerName:t,mcpTransportPid:n,pid:n,status:"failed"})}}nextConnectionGeneration(t){let r=(this.connectionGenerations.get(t)??0)+1;return this.connectionGenerations.set(t,r),r}isCurrentConnection(t,r){return this.connectionGenerations.get(t)===r}updateCurrentRecord(t,r,n){if(!this.isCurrentConnection(t,r))return;let o=this.records.get(t);o&&Object.assign(o,n)}updateCurrentRecordStatus(t,r,n){if(!this.isCurrentConnection(t,r))return;let o=this.records.get(t);o&&(o.status={...o.status,...n,updatedAt:new Date().toISOString()})}createStatus(t,r,n={}){return{status:r,transport:t.type,toolCount:n.toolCount??0,updatedAt:new Date().toISOString(),authorization:n.authorization,error:n.error,failureKind:n.failureKind,protocolEra:n.protocolEra,serverRequestId:n.serverRequestId}}};a(QFo,"mcpRequestMeta");a(_Ir,"resolveVersionNegotiationMode");a(yIr,"isProtocolNegotiationFailure");a(XFo,"formatVersionNegotiationMode");a(ezo,"resolveVersionNegotiation");a(tzo,"createOAuthAuthorizationStatus");a(ilt,"resolveAuthorizationCodeOAuthConfig");a(Are,"isOfficialAuthConfig");a(rzo,"hasAuthorizationHeader");a(nzo,"createBoundedTextBuffer");a(mIr,"sanitizeMcpStdioStderr");a(oke,"getStdioTransportPid");a(ozo,"getStdioTransportExitInfo");a(izo,"isStdioTransportProcessAlive");a(vIr,"isRecord");a(azo,"isPeerAnsweredError")});function TIr(e={}){return new llt(e)}function CIr(e={}){return new clt(e)}async function bIr(e,t,r){Rh(r,"Workflow JSONL append cancelled"),await(0,mf.mkdir)((0,il.dirname)(e),{recursive:!0}),await(0,mf.appendFile)(e,`${JSON.stringify(t)}
|
|
1812
|
+
`)).digest("hex").slice(0,24)}`}var zut,Gus,BSr=T(()=>{"use strict";zut=require("node:crypto");Sbe();Ebe();tR();Sre();J1e();Gus=300*1e3;a(Uut,"createCredentialKeyPrefix")});function nFo(e,t){return(0,Y1e.join)((0,Y1e.dirname)(e),`${$ut(t)}.authz`)}function $ut(e){return e.replaceAll(/[^a-zA-Z0-9-]/g,"-")}async function FSr(e){let t=nFo(e.credentialsFilePath,e.keyPrefix);try{let r=await _te(t,tFo,rFo,eFo);return{attemptId:(0,jSr.randomBytes)(16).toString("hex"),release:r}}catch(r){if(oFo(r)===cH)return;throw r}}async function zSr(e,t,r){let n={attempt_id:r.attemptId,authorization_url:r.authorizationUrl,...r.baselineGeneration===void 0?{}:{baseline_generation:r.baselineGeneration},expires_at:r.expiresAt,state:r.state};await e.save(qut(t),JSON.stringify(n))}async function USr(e,t,r=Date.now()){let n=await e.load(qut(t));if(!n)return;let o;try{o=JSON.parse(n)}catch{return}if(!(!kI(o)||typeof o.attempt_id!="string"||typeof o.authorization_url!="string"||typeof o.state!="string"||typeof o.expires_at!="number")&&!(o.expires_at<=r))return{attemptId:o.attempt_id,authorizationUrl:o.authorization_url,...typeof o.baseline_generation=="string"?{baselineGeneration:o.baseline_generation}:{},expiresAt:o.expires_at,state:o.state}}async function $Sr(e,t,r){let n=qut(t),o=await e.load(n);if(!o)return!1;let i;try{i=JSON.parse(o)}catch{return await e.deleteIfValue(n,o)}return!kI(i)||i.attempt_id!==r?!1:await e.deleteIfValue(n,o)}function qut(e){return Ad(e,Xjo)}function oFo(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}var jSr,Y1e,Xjo,eFo,tFo,rFo,Vut=T(()=>{"use strict";jSr=require("node:crypto"),Y1e=require("node:path");Tbe();gt();tR();Xjo="pending_authorization",eFo=250,tFo=[25],rFo=100;a(nFo,"resolveAuthorizationLeasePath");a($ut,"sanitizeKeyPrefix");a(FSr,"tryAcquireAuthorizationLease");a(zSr,"publishPendingAuthorization");a(USr,"loadPendingAuthorization");a($Sr,"deletePendingAuthorizationIfOwned");a(qut,"pendingKey");a(oFo,"getErrorCode")});function qSr(e){let t=Math.max(0,Math.floor(e));return{expiresAt:Date.now()+t,timeoutMs:t}}function Cre(e,t){let r=e.expiresAt-Date.now();if(r<=0)throw new Rq(t);return r}function Ere(e,t,r,n){return Pq(e,Cre(t,r),r,n)}function Pq(e,t,r,n){return new Promise((o,i)=>{if(n?.aborted){i(n.reason instanceof Error?n.reason:new Error("Operation aborted"));return}let s=!1,u=setTimeout(()=>{s||(s=!0,l(),i(new Rq(r)))},t),l=a(()=>{clearTimeout(u),n?.removeEventListener("abort",c)},"cleanup"),c=a(()=>{s||(s=!0,l(),i(n?.reason instanceof Error?n.reason:new Error("Operation aborted")))},"abortHandler");n?.addEventListener("abort",c),e.then(d=>{s||(s=!0,l(),o(d))},d=>{s||(s=!0,l(),i(d))})})}var Rq,Gut=T(()=>{"use strict";Rq=class extends Error{static{a(this,"McpTimeoutError")}constructor(t){super(t),this.name="McpTimeoutError"}};a(qSr,"createMcpDeadline");a(Cre,"remainingMcpDeadlineMs");a(Ere,"waitWithinMcpDeadline");a(Pq,"withTimeout")});async function VSr(e){let t=e.transactionTtlMs??Hut,n=(await wre(e.credentialStore,e.keyPrefix))?.generation,o=await FSr({credentialsFilePath:e.credentialStore.filePath,keyPrefix:e.keyPrefix});if(!o)return await sFo(e,n,t);try{let i=await wre(e.credentialStore,e.keyPrefix);return Zut(i,n)?{status:"already-authorized"}:await aFo(e,{attemptId:o.attemptId,baselineGeneration:n,transactionTtlMs:t})}finally{await $Sr(e.credentialStore,e.keyPrefix,o.attemptId).catch(()=>{}),await o.release()}}async function aFo(e,t){let r=(0,Mq.randomBytes)(24).toString("base64url"),n=uFo(e.config.redirectPath,e.serverName),o;try{o=await hte({callbackPath:n,state:r})}catch(s){return e.logger?.warn("MCP OAuth callback listener failed",{event:"mcp.oauth.callback_listener.failed",...Q1e(e,r),error:s instanceof Error?s.message:String(s),status:"failed"}),{status:"failed",error:s}}let i=new Wut({attemptId:t.attemptId,baselineGeneration:t.baselineGeneration,callbackServer:o,config:e.config,credentialStore:e.credentialStore,keyPrefix:e.keyPrefix,logger:e.logger,onAuthorizationRequired:e.onAuthorizationRequired,openAuthorizationUrl:e.openAuthorizationUrl,requestedScope:e.requestedScope,serverName:e.serverName,state:r,transactionTtlMs:t.transactionTtlMs});try{if(await rL(i,{serverUrl:e.serverUrl,...e.requestedScope?{scope:e.requestedScope}:{},...e.resourceMetadataUrl?{resourceMetadataUrl:e.resourceMetadataUrl}:{},...e.fetchFn?{fetchFn:e.fetchFn}:{},...e.forceReauthorization?{forceReauthorization:!0}:{}})==="AUTHORIZED")return{status:"authorized"};let u=await Pq(o.waitForCallback(),t.transactionTtlMs,`MCP server ${e.serverName} OAuth authorization timed out`,e.signal),l=new URL(u.url).searchParams,c=l.get("code")??u.code,d=l.get("iss");return await rL(i,{serverUrl:e.serverUrl,authorizationCode:c,...d?{iss:d}:{},...e.requestedScope?{scope:e.requestedScope}:{},...e.resourceMetadataUrl?{resourceMetadataUrl:e.resourceMetadataUrl}:{},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),e.logger?.info("MCP OAuth authorization completed",{event:"mcp.oauth.authorization.completed",...Q1e(e,r),status:"completed"}),{status:"authorized"}}catch(s){let u=await wre(e.credentialStore,e.keyPrefix);return Zut(u,t.baselineGeneration)?{status:"already-authorized"}:(e.logger?.warn("MCP OAuth authorization failed",{event:"mcp.oauth.authorization.failed",...Q1e(e,r),error:s instanceof Error?s.message:String(s),status:"failed"}),{status:"failed",error:s})}finally{await o.close().catch(()=>{})}}async function sFo(e,t,r){let n=Date.now()+r,o;for(e.logger?.info("MCP OAuth authorization is already in progress elsewhere",{event:"mcp.oauth.authorization.following",...Q1e(e),status:"waiting"});Date.now()<n&&!e.signal?.aborted;){let i=await wre(e.credentialStore,e.keyPrefix);if(Zut(i,t))return{status:"already-authorized"};let s=await USr(e.credentialStore,e.keyPrefix);s&&s.authorizationUrl!==o&&(o=s.authorizationUrl,await e.onAuthorizationRequired?.({authorizationUrl:s.authorizationUrl,redirectUrl:"",serverName:e.serverName})),await cFo(iFo,e.signal)}return{status:"pending",...o?{authorizationUrl:o}:{}}}function Zut(e,t){return!!(e?.tokens&&e.generation!==t)}function uFo(e,t){let r=`/oauth/callback/mcp/${encodeURIComponent(t)}`;return e?e.startsWith("/")?e:`/${e}`:r}function Q1e(e,t){return{adapterInstanceId:e.adapterInstanceId,credentialKeyPrefix:e.keyPrefix,mcpServerName:e.serverName,...t?{oauthStateId:(0,Mq.createHash)("sha256").update(t).digest("hex").slice(0,16)}:{},processId:process.pid}}function lFo(e){if(e)return(0,Mq.createHash)("sha256").update(e).digest("hex").slice(0,12)}function cFo(e,t){return new Promise(r=>{let n=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e),o=a(()=>{clearTimeout(n),r()},"onAbort");t?.addEventListener("abort",o,{once:!0})})}var Mq,Hut,iFo,Wut,GSr=T(()=>{"use strict";Mq=require("node:crypto");_re();Sbe();tR();Vut();J1e();Gut();Hut=300*1e3,iFo=500;a(VSr,"runMcpInteractiveAuthorization");a(aFo,"leadAuthorization");a(sFo,"followAuthorization");Wut=class{static{a(this,"InteractiveAuthorizationProvider")}attemptId;baselineGeneration;callbackServer;config;credentialStore;keyPrefix;logger;onAuthorizationRequired;openAuthorizationUrl;requestedScope;serverName;stateValue;transactionId;transactionTtlMs;issuer;memoryCodeVerifier;memoryDiscoveryState;transactionClientInformation;constructor(t){this.attemptId=t.attemptId,this.baselineGeneration=t.baselineGeneration,this.callbackServer=t.callbackServer,this.config=t.config,this.credentialStore=t.credentialStore,this.keyPrefix=t.keyPrefix,this.logger=t.logger,this.onAuthorizationRequired=t.onAuthorizationRequired,this.openAuthorizationUrl=t.openAuthorizationUrl,this.requestedScope=t.requestedScope,this.serverName=t.serverName,this.stateValue=t.state,this.transactionId=(0,Mq.createHash)("sha256").update(t.state).digest("hex"),this.transactionTtlMs=t.transactionTtlMs}get redirectUrl(){return this.callbackServer.callbackUrl}get clientMetadata(){return{client_name:this.config.clientName??`ZCode ${this.serverName}`,grant_types:["authorization_code","refresh_token"],redirect_uris:[this.redirectUrl],response_types:["code"],...this.config.clientSecret?{token_endpoint_auth_method:"client_secret_basic"}:{},...this.requestedScope??this.config.scope?{scope:this.requestedScope??this.config.scope}:{}}}state(){return this.stateValue}clientInformation(){return this.config.clientId?{client_id:this.config.clientId,...this.config.clientSecret?{client_secret:this.config.clientSecret}:{}}:this.transactionClientInformation}saveClientInformation(t){this.transactionClientInformation=t}tokens(){}async saveTokens(t){let r=this.clientInformation();if(!r)throw new Error(`Missing MCP OAuth client information for ${this.serverName}`);let n=await kre(this.credentialStore,this.keyPrefix,{clientInformation:r,...this.issuer?{issuer:this.issuer}:{},publishedBy:this.transactionId,tokens:t});this.logger?.info("MCP OAuth credentials published",{event:"mcp.oauth.credentials.published",...this.logContext(),clientIdHash:lFo(r.client_id),grantKind:"authorization_code",hasRefreshToken:!!t.refresh_token,publishedGeneration:n.generation.slice(0,12),status:"completed",tokenExpiresInSeconds:t.expires_in})}async redirectToAuthorization(t){let r={authorizationUrl:t.toString(),redirectUrl:this.redirectUrl,serverName:this.serverName};await zSr(this.credentialStore,this.keyPrefix,{attemptId:this.attemptId,authorizationUrl:r.authorizationUrl,...this.baselineGeneration?{baselineGeneration:this.baselineGeneration}:{},expiresAt:Date.now()+this.transactionTtlMs,state:this.stateValue}),this.logger?.info("MCP OAuth authorization required",{event:"mcp.oauth.authorization.required",...this.logContext(),callbackPort:Number(new URL(this.redirectUrl).port),status:"waiting"}),await this.onAuthorizationRequired?.(r),await this.openAuthorizationUrl?.(r)}saveCodeVerifier(t){this.memoryCodeVerifier=t}codeVerifier(){if(!this.memoryCodeVerifier)throw new Error(`Missing MCP OAuth PKCE verifier for ${this.serverName}`);return this.memoryCodeVerifier}saveAuthorizationServerUrl(t){this.issuer=t}authorizationServerUrl(){return this.issuer}async saveDiscoveryState(t){this.memoryDiscoveryState=t,await Ire(this.credentialStore,this.keyPrefix,t)}async discoveryState(){return this.memoryDiscoveryState?this.memoryDiscoveryState:await Tre(this.credentialStore,this.keyPrefix)}logContext(){return{credentialKeyPrefix:this.keyPrefix,mcpServerName:this.serverName,oauthAttemptId:this.attemptId.slice(0,12),oauthStateId:this.transactionId.slice(0,16),processId:process.pid}}};a(Zut,"hasNewerCredentials");a(uFo,"normalizeCallbackPath");a(Q1e,"logContext");a(lFo,"hashIdentifier");a(cFo,"sleep")});async function Kut(e){let t=(await SI(e.credentialStore,e.keyPrefix))?.generation,r=hFo(e.credentialStore.filePath,e.keyPrefix);try{return await yte(r,async()=>await pFo(e,t),{lockMaxWaitMs:dFo})}catch(n){if(!Vkt(n))throw n;let o=await SI(e.credentialStore,e.keyPrefix);if(o?.tokens&&o.generation!==t)return o.tokens.access_token;throw Fut({cause:n,serverName:e.serverName})}}async function pFo(e,t){let r=await SI(e.credentialStore,e.keyPrefix);if(r?.tokens&&r.generation!==t)return r.tokens.access_token;if(!r?.tokens)throw rR({reason:"no_credentials",serverName:e.serverName});let n=r.tokens.refresh_token,o=r.clientInformation;if(!n||!o)throw rR({reason:"no_refresh_token",serverName:e.serverName});let i;try{i=await fFo(e,r)}catch(s){return WSr(e,r,s)}try{let s=await vut(i.authorizationServerUrl,{clientInformation:o,refreshToken:n,...i.metadata?{metadata:i.metadata}:{},...i.resource?{resource:i.resource}:{},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),u=await kre(e.credentialStore,e.keyPrefix,{clientInformation:o,...r.issuer?{issuer:r.issuer}:{},publishedBy:`refresh:${e.keyPrefix}`,tokens:s});return e.logger?.info("MCP OAuth access token refreshed",{event:"mcp.oauth.refresh.completed",credentialKeyPrefix:e.keyPrefix,mcpServerName:e.serverName,processId:process.pid,publishedGeneration:u.generation.slice(0,12),reactive:e.reactive,refreshTokenRotated:s.refresh_token!==n,status:"completed"}),s.access_token}catch(s){return await mFo(e,r,s)}}async function mFo(e,t,r){let n=r instanceof xI?r.code:void 0;if(e.logger?.warn("MCP OAuth access token refresh failed",{event:"mcp.oauth.refresh.failed",credentialKeyPrefix:e.keyPrefix,credentialSource:t.source,mcpServerName:e.serverName,oauthErrorCode:n,processId:process.pid,reactive:e.reactive,status:"failed"}),n===Yv.InvalidGrant)throw t.raw&&await jut(e.credentialStore,e.keyPrefix,t.raw,"tokens"),rR({cause:r,reason:"invalid_grant",serverName:e.serverName});if(n===Yv.InvalidClient||n===Yv.UnauthorizedClient)throw e.staticClientId?new Error(`MCP server ${e.serverName} OAuth client was rejected by the authorization server (invalid_client). The configured clientId is not usable; fix the MCP oauth configuration.`,{cause:r}):(t.raw&&await jut(e.credentialStore,e.keyPrefix,t.raw,"all"),rR({cause:r,reason:"invalid_client",serverName:e.serverName}));return WSr(e,t,r)}function WSr(e,t,r){if(e.reactive||!t.tokens)throw Fut({cause:r,serverName:e.serverName});return t.tokens.access_token}async function fFo(e,t){let r=await Tre(e.credentialStore,e.keyPrefix,{...t.issuer?{expectedIssuer:t.issuer}:{}}),n=r??await $1e(e.serverUrl,{...e.fetchFn?{fetchFn:e.fetchFn}:{}});r||await Ire(e.credentialStore,e.keyPrefix,n);let o=await yut(e.serverUrl,{},n.resourceMetadata);return{authorizationServerUrl:n.authorizationServerUrl,...n.authorizationServerMetadata?{metadata:n.authorizationServerMetadata}:{},...o?{resource:o}:{}}}function hFo(e,t){return(0,X1e.join)((0,X1e.dirname)(e),`${$ut(t)}.refresh`)}var X1e,dFo,HSr=T(()=>{"use strict";X1e=require("node:path");_re();gt();Tbe();tR();Sre();Vut();J1e();dFo=45e3;a(Kut,"refreshMcpOAuthTokensUnderLock");a(pFo,"refreshLocked");a(mFo,"handleRefreshFailure");a(WSr,"failSoft");a(fFo,"resolveAsMetadata");a(hFo,"resolveRefreshLockPath")});function ZSr(e){let t={credentialStore:e.credentialStore,...e.fetchFn?{fetchFn:e.fetchFn}:{},keyPrefix:e.keyPrefix,...e.logger?{logger:e.logger}:{},serverName:e.serverName,serverUrl:e.serverUrl,...e.config.clientId?{staticClientId:e.config.clientId}:{}};return{async token(){let r=await SI(e.credentialStore,e.keyPrefix);if(r?.tokens)return!ASr(r)||!r.tokens.refresh_token?r.tokens.access_token:await Kut({...t,reactive:!1})},async onUnauthorized(){let r=await SI(e.credentialStore,e.keyPrefix);if(!r?.tokens?.refresh_token)throw rR({reason:r?.tokens?"no_refresh_token":"no_credentials",serverName:e.serverName});await Kut({...t,reactive:!0})}}}var KSr=T(()=>{"use strict";tR();Sre();HSr();a(ZSr,"createMcpOAuthTokenProvider")});async function tke(e,t={}){if(QSr(t)==="win32"){await CFo(e,t);return}await EFo(e,t)}function nR(e,t){let r=t.kill??process.kill;try{return r(e,0),!0}catch(n){return bFo(n)}}function bFo(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EPERM"}function QSr(e){return e.platform??process.platform}function wFo(e){return new Promise(t=>setTimeout(t,e))}function kFo(e){return e.split(/\s+/).map(t=>Number(t)).filter(t=>Number.isInteger(t)&&t>0)}function SFo(e){return e==="darwin"?["-axo","pid=,ppid="]:["-eo","pid=,ppid="]}function IFo(e,t){let r=[];for(let n of e.split(/\r?\n/)){let[o,i]=n.trim().split(/\s+/),s=Number(o),u=Number(i);Number.isInteger(s)&&s>0&&u===t&&r.push(s)}return r}async function TFo(e,t){let r=await elt("pgrep",["-P",String(e)],{encoding:"utf8",timeout:JSr},t);if(!r.error&&r.status===0&&r.stdout)return kFo(String(r.stdout));let n=await elt("ps",SFo(QSr(t)),{encoding:"utf8",timeout:JSr},t);return n.error||n.status!==0||!n.stdout?[]:IFo(String(n.stdout),e)}async function Xut(e,t,r=new Set){if(r.has(e))return[];r.add(e);let n=[];for(let o of await TFo(e,t))n.push(o,...await Xut(o,t,r));return n}function eke(e){return[...new Set(e.filter(t=>t>0))]}function Jut(e,t,r){let n=r.kill??process.kill;try{n(e,t)}catch{}}function Yut(e,t,r){let n=r.kill??process.kill;try{n(-e,t)}catch{}}async function CFo(e,t){if(!nR(e,t))return;let r=await elt("taskkill",["/PID",String(e),"/T","/F"],{encoding:"utf8",timeout:xFo,windowsHide:!0},t);if(PFo(r)&&nR(e,t))throw new Error(`taskkill failed for MCP stdio process tree pid=${e} status=${r.status??"unknown"}`)}async function EFo(e,t){if(!nR(e,t))return;let r=eke(await Xut(e,t)).reverse(),n=eke([...r,e]);Yut(e,"SIGINT",t);for(let u of n)Jut(u,"SIGINT",t);if(await Qut(n,gFo,t),!n.some(u=>nR(u,t)))return;Yut(e,"SIGTERM",t);for(let u of n)Jut(u,"SIGTERM",t);if(await Qut(n,_Fo,t),!n.some(u=>nR(u,t)))return;let o=eke(await Xut(e,t)).reverse(),i=eke([...o,...n]);for(let u of i)nR(u,t)&&Jut(u,"SIGKILL",t);Yut(e,"SIGKILL",t),await Qut(i,yFo,t);let s=i.filter(u=>nR(u,t));if(s.length>0)throw new Error(`SIGKILL failed for MCP stdio process tree pid=${e} remaining=${s.join(",")}`)}async function Qut(e,t,r){let n=r.sleep??wFo,o=r.now??Date.now,i=o();for(;o()-i<t;){if(!e.some(s=>nR(s,r)))return;await n(vFo)}}function elt(e,t,r,n){return(n.execFile??AFo)(e,t,r)}function AFo(e,t,r){return new Promise(n=>{(0,YSr.execFile)(e,[...t],r,(o,i,s)=>{n({error:o,status:RFo(o),stderr:s,stdout:i})})})}function RFo(e){if(!e||typeof e!="object"||!("code"in e))return 0;let t=e.code;return typeof t=="number"?t:null}function PFo(e){return!!e.error||e.status!==null&&e.status!==0}var YSr,JSr,gFo,_Fo,yFo,vFo,xFo,tlt=T(()=>{"use strict";YSr=require("node:child_process"),JSr=1e3,gFo=250,_Fo=750,yFo=250,vFo=25,xFo=2e3;a(tke,"terminateMcpStdioProcessTree");a(nR,"isProcessAlive");a(bFo,"isPermissionDenied");a(QSr,"getPlatform");a(wFo,"defaultSleep");a(kFo,"parsePidList");a(SFo,"getPosixProcessListArgs");a(IFo,"parseChildPidsFromProcessList");a(TFo,"collectChildPids");a(Xut,"collectDescendantPids");a(eke,"uniquePids");a(Jut,"killPid");a(Yut,"killProcessGroup");a(CFo,"terminateWindowsProcessTree");a(EFo,"terminatePosixProcessTree");a(Qut,"waitUntilAllExited");a(elt,"runCommand");a(AFo,"defaultExecFile");a(RFo,"getExitStatus");a(PFo,"didTerminationFail")});async function eIr(e,t={}){if((t.platform??process.platform)!=="win32"||!Number.isInteger(e)||e<=0)return;let r=t.api??await MFo();if(!r)return;let n;try{if(n=r.create(),!n||!r.assign(n,e)){n&&r.close(n);return}}catch{if(n)try{r.close(n)}catch{}return}let o=!1;return{terminate(){o||r.terminate(n)},close(){o||(o=!0,r.close(n))}}}async function MFo(){return XSr??=OFo(),XSr}async function OFo(){try{let e=await import("koffi"),t="default"in e?e.default:e,r=t.load("kernel32.dll"),n=t.pointer("HANDLE",t.opaque()),o=t.struct("JOBOBJECT_BASIC_LIMIT_INFORMATION",{PerProcessUserTimeLimit:"int64",PerJobUserTimeLimit:"int64",LimitFlags:"uint32",MinimumWorkingSetSize:"size_t",MaximumWorkingSetSize:"size_t",ActiveProcessLimit:"uint32",Affinity:"uintptr_t",PriorityClass:"uint32",SchedulingClass:"uint32"}),i=t.struct("IO_COUNTERS",{ReadOperationCount:"uint64",WriteOperationCount:"uint64",OtherOperationCount:"uint64",ReadTransferCount:"uint64",WriteTransferCount:"uint64",OtherTransferCount:"uint64"}),s=t.struct("JOBOBJECT_EXTENDED_LIMIT_INFORMATION",{BasicLimitInformation:o,IoInfo:i,ProcessMemoryLimit:"size_t",JobMemoryLimit:"size_t",PeakProcessMemoryUsed:"size_t",PeakJobMemoryUsed:"size_t"}),u=r.func("__stdcall","CreateJobObjectW",n,["void *","str16"]),l=r.func("__stdcall","SetInformationJobObject","bool",[n,"uint32",t.pointer(s),"uint32"]),c=r.func("__stdcall","OpenProcess",n,["uint32","bool","uint32"]),d=r.func("__stdcall","AssignProcessToJobObject","bool",[n,n]),p=r.func("__stdcall","TerminateJobObject","bool",[n,"uint32"]),m=r.func("__stdcall","CloseHandle","bool",[n]);return{create(){let h=u(null,null);if(!h)return;if(!l(h,9,{BasicLimitInformation:{PerProcessUserTimeLimit:0,PerJobUserTimeLimit:0,LimitFlags:8192,MinimumWorkingSetSize:0,MaximumWorkingSetSize:0,ActiveProcessLimit:0,Affinity:0,PriorityClass:0,SchedulingClass:0},IoInfo:{ReadOperationCount:0,WriteOperationCount:0,OtherOperationCount:0,ReadTransferCount:0,WriteTransferCount:0,OtherTransferCount:0},ProcessMemoryLimit:0,JobMemoryLimit:0,PeakProcessMemoryUsed:0,PeakJobMemoryUsed:0},t.sizeof(s))){m(h);return}return h},assign(h,_){let y=c(257,!1,_);if(!y)return!1;try{return!!d(h,y)}finally{m(y)}},terminate(h){p(h,1)},close(h){m(h)}}}catch{return}}var XSr,tIr=T(()=>{"use strict";a(eIr,"attachProcessToWindowsJobObject");a(MFo,"loadWindowsJobObjectApi");a(OFo,"createWindowsJobObjectApi")});function DFo(e,t){if(!("method"in e)||!t||Object.keys(t).length===0)return e;let r=nIr(e.params)?e.params:{},n=nIr(r._meta)?r._meta:{};return{...e,params:{...r,_meta:{...n,...t}}}}function nIr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var rIr,oR,oIr=T(()=>{"use strict";Aut();tlt();tIr();rIr=Object.getOwnPropertyDescriptor(yre.prototype,"_dispose")?.value,oR=class extends yre{static{a(this,"ProcessTreeStdioClientTransport")}childProcess;lastProcessExit;requestMetaProvider;windowsJobObjectFactory;windowsJobObject;constructor(t,r={}){super(t),this.requestMetaProvider=t.requestMetaProvider,this.windowsJobObjectFactory=r.windowsJobObjectFactory??eIr}async terminateWindowsJobObject(){let t=this.windowsJobObject;if(this.windowsJobObject=void 0,!!t)try{t.terminate()}catch{}finally{try{t.close()}catch{}}}async send(t){let r=await this.requestMetaProvider?.();await super.send(DFo(t,r))}async start(){let t=Date.now();await super.start();let r=this._process;if(!r)return;this.childProcess=r;let n=a((o,i)=>{this.lastProcessExit??={exitCode:o,exitedAt:Date.now(),signal:i,startedAt:t}},"recordExit");if(r.exitCode!==null||r.signalCode!==null){n(r.exitCode,r.signalCode);return}if(r.once("exit",n),!(process.platform!=="win32"||this.pid==null))try{this.windowsJobObject=await this.windowsJobObjectFactory(this.pid)}catch{this.windowsJobObject=void 0}}get processExit(){return this.lastProcessExit}get processAlive(){return!!(this.childProcess&&this.childProcess.exitCode===null&&this.childProcess.signalCode===null)}};a(DFo,"mergeRequestMeta");a(nIr,"isRecord");Object.defineProperty(oR.prototype,"_dispose",{configurable:!0,async value(){let e=this.pid;if(await this.terminateWindowsJobObject(),typeof e=="number"&&Number.isInteger(e)&&e>0)try{await tke(e)}catch{}if(rIr){await rIr.call(this);return}await this.close()}})});async function sIr(e,t={}){let r=[...new Set(e.filter(n=>Number.isInteger(n)&&n>0))];return r.length===0?new Map:(t.platform??process.platform)==="win32"?await jFo(r,t.execFile??iIr):await BFo(r,t.execFile??iIr)}async function BFo(e,t){let r=await t("ps",["-eo","pid=,ppid=,rss="],uIr());if(r.error||r.status!==0)return;let n=FFo(r.stdout),o=new Map(n.map(s=>[s.pid,s])),i=new Map;for(let s of n){let u=i.get(s.parentPid)??[];u.push(s.pid),i.set(s.parentPid,u)}return new Map(e.flatMap(s=>{if(!o.has(s))return[];let u=new Set,l=0,c=a(d=>{if(!u.has(d)){u.add(d),l+=o.get(d)?.memoryKb??0;for(let p of i.get(d)??[])c(p)}},"visit");return c(s),[[s,{memoryKb:l,memoryScope:"process_tree"}]]}))}async function jFo(e,t){let r=await t("tasklist",["/FO","CSV","/NH"],{...uIr(),windowsHide:!0});if(r.error||r.status!==0)return;let n=new Set(e),o=new Map;for(let i of r.stdout.split(/\r?\n/)){let s=zFo(i),u=Number(s[1]);if(!n.has(u))continue;let l=(s[4]??"").replace(/\D/g,"");if(!l)continue;let c=Number(l);!Number.isFinite(c)||c<0||o.set(u,{memoryKb:c,memoryScope:"direct_process"})}return o}function FFo(e){let t=[];for(let r of e.split(/\r?\n/)){let[n,o,i]=r.trim().split(/\s+/),s=Number(n),u=Number(o),l=Number(i);!Number.isInteger(s)||s<=0||!Number.isInteger(u)||u<0||!Number.isFinite(l)||l<0||t.push({memoryKb:l,parentPid:u,pid:s})}return t}function zFo(e){let t=[];for(let r of e.matchAll(/"((?:[^"]|"")*)"/g))t.push((r[1]??"").replace(/""/g,'"'));return t}function uIr(){return{encoding:"utf8",maxBuffer:LFo,timeout:NFo}}function iIr(e,t,r){return new Promise(n=>{(0,aIr.execFile)(e,[...t],r,(o,i,s)=>{n({...o?{error:o}:{},status:UFo(o),stderr:s,stdout:i})})})}function UFo(e){if(!e||typeof e!="object"||!("code"in e))return 0;let t=e.code;return typeof t=="number"?t:null}var aIr,NFo,LFo,lIr=T(()=>{"use strict";aIr=require("node:child_process"),NFo=5e3,LFo=8*1024*1024;a(sIr,"readMcpProcessMemorySamples");a(BFo,"readPosixProcessTreeMemory");a(jFo,"readWindowsDirectProcessMemory");a(FFo,"parsePosixRows");a(zFo,"parseCsvFields");a(uIr,"commandOptions");a(iIr,"defaultExecFile");a(UFo,"resolveExitStatus")});function nlt(e){let t=e.arch??process.arch,r=e.now??Date.now,n=e.platform??process.platform,o=e.randomId??rke.randomUUID,i=e.readMemorySamples??sIr,s=e.timer??GFo,u=new Map,l,c=a(p=>{try{e.onEvent(p)}catch{}},"emit"),d=a(async()=>{let p=[...u.values()].filter(_=>_.process!==void 0);if(p.length===0)return;let m=await i(p.flatMap(_=>_.process?[_.process.pid]:[]));if(!m)return;let h=r();for(let _ of p){let y=_.process;if(!y)continue;let v=m.get(y.pid);if(!v){_.owners.size===0&&(_.process=void 0,u.delete(_.connectionId));continue}let x=new Set([..._.owners.values()].filter(b=>b!==void 0)),w=_.owners.size===0&&_.unownedAt!==void 0?Math.max(0,h-_.unownedAt):0;c({arch:t,kind:"memory",mcpId:_.mcpId,mcpInstanceId:y.instanceId,mcpIsolation:_.isolation,mcpSource:_.mcpSource,memoryKb:v.memoryKb,memoryScope:v.memoryScope,occurredAt:h,orphanSuspected:_.owners.size===0&&w>6e4,ownerSessionCount:x.size,platform:n,unownedSeconds:w/1e3})}},"sampleNow");return{acquireOwner(p){let m=u.get(p.connectionId);m&&(m.owners.set(p.ownerId,p.sessionId),m.unownedAt=void 0)},recordProcessCrashed(p){let m=u.get(p.connectionId),h=m?.process;if(!m||!h)return;m.process=void 0;let _=r(),y=new Set([...m.owners.values()].filter(v=>v!==void 0));c({affectedSessionCount:y.size,arch:t,exitCode:p.exitCode,kind:"process_crash",mcpId:m.mcpId,mcpInstanceId:h.instanceId,mcpIsolation:m.isolation,mcpSource:m.mcpSource,occurredAt:_,platform:n,signal:p.signal,uptimeMs:Math.max(0,_-h.startedAt)})},recordProcessClosed(p){let m=u.get(p.connectionId);m&&(m.process=void 0,m.owners.size===0&&u.delete(p.connectionId))},recordProcessStarted(p){let m=u.get(p.connectionId);if(!m||!Number.isInteger(p.pid)||p.pid<=0)return;let h=o(),_=r();return m.process={instanceId:h,pid:p.pid,startedAt:_},m.owners.size===0&&(m.unownedAt??=_),c({arch:t,kind:"process_start",mcpId:m.mcpId,mcpInstanceId:h,mcpIsolation:m.isolation,mcpSource:m.mcpSource,occurredAt:_,platform:n}),{mcpId:m.mcpId,mcpInstanceId:h}},recordSessionStartup(p){c({arch:t,configuredCount:p.configuredCount,connectedCount:p.connectedCount,failedCount:p.failedCount,kind:"session_startup",occurredAt:r(),platform:n,processCount:p.processCount,sessionId:p.sessionId})},releaseOwner(p){let m=u.get(p.connectionId);!m||!m.owners.delete(p.ownerId)||m.owners.size===0&&(m.unownedAt=r())},registerConnection(p){let m=p.source??WFo(p.serverName);u.set(p.connectionId,{connectionId:p.connectionId,isolation:p.isolation,mcpId:HFo(p.serverName,m,e.idSalt),mcpSource:m,owners:new Map})},unregisterConnection(p){let m=u.get(p.connectionId);m&&(m.owners.clear(),m.unownedAt??=r(),m.process||u.delete(p.connectionId))},sampleNow:d,start(){if(!l)try{l=s.setInterval(()=>{d().catch(()=>{})},dIr),l.unref?.()}catch{l=void 0}},stop(){if(!l)return;let p=l;l=void 0;try{s.clearInterval(p)}catch{}}}}function WFo(e){return e===qFo?"builtin":e.startsWith(rlt)?"plugin":"custom"}function HFo(e,t,r){if(t==="builtin"){let o=e.startsWith(rlt)?e.slice(rlt.length):e;return`${$Fo}${o.split(":").map(ZFo).join(":")}`}let n=(0,rke.createHmac)("sha256",r).update(e).digest("hex").slice(0,12);return`${t}:${n}`}function ZFo(e){let t="";for(let r of cIr.Buffer.from(e,"utf8")){let n=String.fromCharCode(r);t+=VFo.test(n)?n:`%${r.toString(16).toUpperCase().padStart(2,"0")}`}return t}var cIr,rke,dIr,$Fo,qFo,VFo,rlt,GFo,pIr=T(()=>{"use strict";cIr=require("node:buffer"),rke=require("node:crypto");lIr();dIr=5*6e4,$Fo="builtin:",qFo="node_repl",VFo=/^[A-Za-z0-9._~-]$/,rlt="plugin:",GFo={clearInterval(e){clearInterval(e)},setInterval(e,t){return setInterval(e,t)}};a(nlt,"createMcpTelemetryTracker");a(WFo,"resolveMcpSource");a(HFo,"resolveMcpId");a(ZFo,"encodeMcpIdSegment")});function ult(e={}){return new slt(e)}function gIr(e={}){return Mut({logger:e.logger,telemetry:e.telemetry,createAdapter:a(({connectionContext:t,workingDirectory:r})=>ult({...e,connectionContext:t,workingDirectory:r??e.workingDirectory}),"createAdapter")})}function QFo(e,t){let r={...e?{trace_id:e.traceId}:{},...e?.spanId?{span_id:e.spanId}:{},...e?.parentSpanId?{parent_span_id:e.parentSpanId}:{},...e?.sessionId?{session_id:e.sessionId}:{},...e?.turnId?{turn_id:e.turnId}:{},...t?{runtime_scope:t}:{}};return{...r,"com.zcode/request-context":r}}function _Ir(e){return e.protocolVersion==="2026-07-28"?{pin:"2026-07-28"}:e.type==="sse"||e.protocolVersion==="legacy"?"legacy":"auto"}function yIr(e){if(Xr.isInstance(e)&&e.code===Ar.EraNegotiationFailed||yq.isInstance(e))return!0;let t=e?.cause;return t!==void 0&&t!==e?yIr(t):!1}function XFo(e){let t=_Ir(e);return typeof t=="object"?t.pin:t}function ezo(e,t){let r=_Ir(e);if(r==="legacy")return{mode:r};let n=typeof r=="object"?Math.max(1,Math.floor(t)):Math.min(JFo,Math.max(1,Math.floor(t/2)));return{mode:r,probe:{timeoutMs:n}}}function tzo(e){return{type:"oauth_authorization_code",authorizationUrl:e.authorizationUrl,startedAt:new Date().toISOString()}}function ilt(e){if(e.type!=="stdio"&&!Are(e)){if(e.oauth?.type==="authorization_code")return e.oauth;if(e.oauth?.type!=="client_credentials"&&!rzo(e.headers))return{type:"authorization_code"}}}function Are(e){return(e.type==="http"||e.type==="stdio")&&e.auth?.type==="zcode_official"&&e.auth.provider==="jwt_token"&&e.official!==void 0}function rzo(e){return e?Object.keys(e).some(t=>t.toLowerCase()==="authorization"):!1}function nzo(e){let t="";return{append(r){r&&(t=`${t}${r}`,t.length>e&&(t=t.slice(-e)))},read(){return t}}}function mIr(e){let t=String.raw`(?:api[_-]?key|access[_-]?key|secret(?:[_-]?key)?|private[_-]?key|token|password|passwd|pass|mysql_pass|mysql_password)`,r=e.replace(/(bearer\s+)[^\s"']+/gi,"$1[Redacted]");return r=r.replace(/(\bauthorization\b\s*[:=]\s*)(bearer\s+)?[^\r\n]+/gi,(n,o,i)=>`${o}${i?"Bearer ":""}[Redacted]`),r=r.replace(new RegExp(`([?&]${t}=)[^&\\s]+`,"gi"),"$1[Redacted]"),r=r.replace(new RegExp(`(["']${t}["']\\s*:\\s*)(["'])(?:(?!\\2).)*\\2`,"gi"),"$1$2[Redacted]$2"),r=r.replace(new RegExp(`(\\b${t}\\b\\s*[:=]\\s*)(["']?)[^\\s"',;)}]+`,"gi"),"$1$2[Redacted]"),r.replace(/([a-z][a-z0-9+.-]*:\/\/)[^:\s/@]+:[^@\s/]+@/gi,"$1[Redacted]@")}function oke(e){if(!(e instanceof yre))return;let t=e.pid;return typeof t=="number"&&Number.isInteger(t)&&t>0?t:void 0}function ozo(e){return e instanceof oR?e.processExit:void 0}function izo(e){return e instanceof oR&&e.processAlive}function vIr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function azo(e){return e instanceof os?!0:vIr(e)&&typeof e.code=="number"}var fIr,hIr,alt,nke,KFo,JFo,olt,YFo,slt,ike=T(()=>{"use strict";fIr=require("node:crypto"),hIr=require("node:path"),alt=require("node:util");_re();Aut();ke();fSr();bSr();gt();kSr();Out();BSr();Sre();GSr();Ebe();tR();KSr();tlt();oIr();Gut();Out();pIr();nke=3e4,KFo=5e3,JFo=5e3,olt=4e3,YFo=64;a(ult,"createMcpAdapter");a(gIr,"createMcpAdapterConnectionPool");slt=class{static{a(this,"NodeMcpAdapter")}adapterInstanceId=(0,fIr.randomUUID)();clientName;clientVersion;connectionContext;env;logger;mcpOAuth;network;officialMcpAuth;telemetry;connectionGenerations=new Map;credentialStore;lastOfficialAuthKind=new Map;serverRequestIdBySpan=new Map;connectionDiagnosticByServer=new Map;records=new Map;workingDirectory;constructor(t){this.clientName=t.clientName??"zcode",this.clientVersion=t.clientVersion??"0.0.0",this.connectionContext=t.connectionContext,this.env=t.env,this.logger=t.logger?.child({...this.connectionContext,module:"adapters.mcp"}),this.mcpOAuth=t.mcpOAuth,this.network=t.network,this.officialMcpAuth=t.officialMcpAuth,this.telemetry=t.telemetry,this.workingDirectory=t.workingDirectory}async connectConfiguredServers(t,r={}){let n=Date.now(),o=Object.keys(t);this.logger?.info("MCP configured servers connection started",{event:"mcp.configured_servers.connect.started",serverCount:o.length,serverNames:o,status:"started"});let i=new Set(Object.keys(t));await Promise.all(Array.from(this.records.keys()).filter(c=>!i.has(c)).map(c=>this.disconnectServer(c))),await Promise.all(Object.entries(t).map(([c,d])=>{let p=this.records.get(c);return p?.connecting&&p.status.status==="connecting"&&p.status.authorization&&(0,alt.isDeepStrictEqual)(p.config,d)?this.waitForSharedConnection(c,p,r):this.connectServer(c,d,r)}));let s=await this.status(),u=await this.listTools(),l=Object.values(s).reduce((c,d)=>(c[d.status]=(c[d.status]??0)+1,c),{});return this.logger?.info("MCP configured servers connection completed",{durationMs:Date.now()-n,event:"mcp.configured_servers.connect.completed",serverCount:o.length,status:"completed",statusCounts:l,toolCount:u.length}),{statuses:s,tools:u}}async connectServer(t,r,n={}){let o=Date.now(),i=r.timeoutMs??nke,s=this.nextConnectionGeneration(t);if(this.lastOfficialAuthKind.delete(t),this.connectionDiagnosticByServer.delete(t),this.logger?.info("MCP server connection started",{event:"mcp.server.connect.started",mcpServerName:t,status:"started",timeoutMs:i,transport:r.type}),await this.closeRecord(t),r.enabled===!1||(r.type==="http"&&r.auth?.type==="zcode_official"&&r.auth.provider==="jwt_token"&&r.official!==void 0&&!this.officialMcpAuth?.trustedOrigins)){let m=this.createStatus(r,"disabled",r.enabled===!1?void 0:{error:"Official MCP authentication is unavailable in this runtime (zcode_cli_official_mcp_unavailable).",failureKind:"official_auth_unavailable"});return this.records.set(t,{config:r,status:m,tools:[]}),this.logger?.info("MCP server connection skipped",{durationMs:Date.now()-o,event:"mcp.server.connect.skipped",mcpServerName:t,status:"completed",transport:r.type}),m}let u=new AbortController,l=a(()=>{u.abort(n.signal?.reason instanceof Error?n.signal.reason:void 0)},"abortExternal");n.signal?.aborted?l():n.signal?.addEventListener("abort",l,{once:!0});let c=this.createStatus(r,"connecting"),d={abortController:u,config:r,status:c,tools:[]};this.records.set(t,d);let p=this.openServerConnection({config:r,generation:s,name:t,oauthAuthorizationTimeoutMs:n.oauthAuthorizationTimeoutMs,signal:u.signal,timeoutMs:i,workingDirectory:n.workingDirectory}).finally(()=>{n.signal?.removeEventListener("abort",l)});return d.connecting=p,await this.waitForSharedConnection(t,d,n)}async disconnectServer(t){let r=this.records.get(t);if(!r)return;this.nextConnectionGeneration(t),await this.closeRecord(t);let n=this.createStatus(r.config,"disconnected");return this.records.set(t,{config:r.config,status:n,tools:[]}),n}async status(){return Object.fromEntries(Array.from(this.records.entries()).map(([t,r])=>[t,r.status]))}async pingServer(t,r={}){let n=this.records.get(t);if(!n?.client||n.status.status!=="connected")return!1;let o=Math.min(r.timeoutMs??KFo,n.config.timeoutMs??nke),i=this.connectionGenerations.get(t)??0;try{return await n.client.ping({timeout:o}),!0}catch(s){if(azo(s))return!0;if(!this.isCurrentConnection(t,i))return!1;let u=this.records.get(t);return u&&u.client===n.client&&(u.status=this.createStatus(u.config,"disconnected",{error:"MCP server did not answer ping",failureKind:"unexpected_disconnect"})),this.logger?.warn("MCP server ping failed",{...this.connectionContext,error:s instanceof Error?s.message:String(s),event:"mcp.server.ping.failed",mcpServerName:t,status:"failed",transport:n.config.type}),!1}}async listTools(){return Array.from(this.records.values()).flatMap(t=>t.tools)}async callTool(t,r={}){let n=this.records.get(t.serverName),o=r.timeoutMs??n?.config.timeoutMs??nke,i=qSr(o),s=`MCP tool ${t.serverName}/${t.toolName} timed out after ${o}ms`,u=n?.connecting;u&&await Ere(u,i,s,r.signal);let l=this.records.get(t.serverName);l&&l.status.status==="disconnected"&&await Ere(this.reconnectForCall(t.serverName,l.config),i,s,r.signal);let c=this.records.get(t.serverName);if(!c?.client||c.status.status!=="connected")throw new Error(`MCP server is not connected: ${t.serverName}`);try{return await this.callToolOnClient(c.client,t,Cre(i,s),r.signal)}catch(d){let p=K1e(d);if(p&&c.config.type!=="stdio")return await this.recoverToolCallAuthorization({error:d,record:c,request:t,deadline:i,timeoutMessage:s,trigger:p,...r.signal?{signal:r.signal}:{}});if(!(d instanceof Error)||d.message!=="Not connected")throw d;try{await Ere(this.reconnectForCall(t.serverName,c.config),i,s,r.signal)}catch(h){throw this.logger?.warn("MCP server reconnect failed",{error:h instanceof Error?h.message:String(h),event:"mcp.server.reconnect.failed",mcpServerName:t.serverName,status:"failed"}),d}let m=this.records.get(t.serverName);if(!m?.client||m.status.status!=="connected")throw d;return await this.callToolOnClient(m.client,t,Cre(i,s),r.signal)}}rememberServerResponse(t,r){if(!r.spanId&&r.rpcMethod!=="tools/call"&&this.records.get(t)?.status.status==="connecting"){r.failureKind&&this.connectionDiagnosticByServer.set(t,{failureKind:r.failureKind,...r.serverRequestId?{serverRequestId:r.serverRequestId}:{}});return}if(r.spanId&&r.serverRequestId)for(this.serverRequestIdBySpan.set(r.spanId,r.serverRequestId);this.serverRequestIdBySpan.size>YFo;){let n=this.serverRequestIdBySpan.keys().next();if(n.done)break;this.serverRequestIdBySpan.delete(n.value)}}takeServerRequestId(t){if(!t)return;let r=this.serverRequestIdBySpan.get(t);return r!==void 0&&this.serverRequestIdBySpan.delete(t),r}async resolveOfficialStdioAuthMeta(t,r,n){if(r.type!=="stdio"||!Are(r)||!r.official)return;let o=r.official,i=this.officialMcpAuth?.authHeadersPort,s=this.officialMcpAuth?.trustedOrigins,u=this.officialMcpAuth?.resolveZCodeApiOrigin,l={event:"mcp.official_auth.stdio_meta",mcpKey:o.mcpKey,mcpServerName:t,module:"adapters.mcp"},c=a(h=>(this.logger?.warn("Official MCP stdio auth headers unavailable",{...l,reason:h,status:"failed"}),{ok:!1,reason:h}),"fail");if(!i||!s||!u)return c("official_auth_unavailable");let d,p;try{d=u(),p=await s.isTrusted({mcpKey:o.mcpKey,origin:d,pluginId:o.pluginId})}catch(h){return this.logger?.warn("Official MCP stdio origin resolution failed",{...l,error:h instanceof Error?h.message:String(h),errorName:h instanceof Error?h.name:"unknown",pluginId:o.pluginId}),c("official_auth_unavailable")}if(!p.trusted)return this.logger?.warn("Official MCP stdio origin is not trusted",{...l,detail:p.detail??"unknown",pluginId:o.pluginId,targetOrigin:d}),c("official_mcp_origin_untrusted");let m=await i.resolveHeaders({mcpKey:o.mcpKey,pluginId:o.pluginId,targetOrigin:d,...this.officialMcpAuth?.workspaceIdentity?{workspaceIdentity:this.officialMcpAuth.workspaceIdentity}:{},...this.workingDirectory?{workspacePath:this.workingDirectory}:{},...n?{signal:n}:{}});return m.ok?(this.logger?.debug("Official MCP stdio auth headers attached",{...l,identityHeaderNames:Object.keys(m.headers).map(h=>h.toLowerCase()).sort(),...m.headers["Bigmodel-Target-Type"]?{identityTargetType:m.headers["Bigmodel-Target-Type"]}:{},status:"completed"}),{ok:!0,headers:m.headers}):c(m.reason)}async callToolOnClient(t,r,n,o){let i={event:"mcp.tool.call",mcpServerName:r.serverName,mcpToolName:r.toolName,module:"adapters.mcp",timeoutMs:n},s=Object.keys(r.arguments??{}).sort();this.logger?.debug("MCP tool call started",{...i,argumentKeys:s,status:"started"});let u=Date.now();try{let l=await t.callTool({name:r.toolName,arguments:r.arguments??{},...r.trace||r.runtimeScope?{_meta:QFo(r.trace,r.runtimeScope)}:{}},{signal:o,timeout:n,resetTimeoutOnProgress:!0}),c=Date.now()-u,d=typeof l.isError=="boolean"?l.isError:!1,p=this.takeServerRequestId(r.trace?.spanId),m={...i,contentBlocks:Array.isArray(l.content)?l.content.length:0,durationMs:c,hasStructuredContent:l.structuredContent!==void 0,isError:d,...p?{serverRequestId:p}:{}};d?this.logger?.warn("MCP tool returned an error",{...m,status:"failed"}):this.logger?.debug("MCP tool call completed",{...m,status:"completed"});let h=vIr(l._meta)?l._meta:void 0;return{content:Array.isArray(l.content)?l.content:[{type:"text",text:""}],structuredContent:l.structuredContent,isError:typeof l.isError=="boolean"?l.isError:void 0,_meta:d&&p?{...h,[N4t]:p}:h}}catch(l){let c=Date.now()-u,d=l instanceof Error?l.message:String(l),p=/timed?\s*out|timeout/i.test(d)||l instanceof Error&&l.name==="AbortError",m=this.takeServerRequestId(r.trace?.spanId);throw this.logger?.warn("MCP tool call failed",{...i,argumentKeys:s,durationMs:c,error:d,...m?{serverRequestId:m}:{},errorName:l instanceof Error?l.name:"unknown",status:"failed",timedOut:p,...p?{budgetExhausted:c>=n*.9}:{}}),l}}async reconnectForCall(t,r){this.logger?.warn("MCP server reconnecting after lost connection",{event:"mcp.server.reconnect.started",mcpServerName:t,status:"started",transport:r.type}),await this.connectServer(t,r)}async recoverToolCallAuthorization(t){let{record:r,request:n}=t,o=r.config;if(o.type==="stdio")throw t.error;let i=ilt(o);if(!i)throw t.error;this.logger?.warn("MCP tool call requires OAuth authorization",{event:"mcp.oauth.tool_call.authorization_required",mcpServerName:n.serverName,oauthTriggerReason:t.trigger.reason,status:"started",toolName:n.toolName});let s=this.ensureToolCallAuthorizationRecovery({config:o,name:n.serverName,oauthConfig:i,record:r,trigger:t.trigger});if((await Ere(s,t.deadline,t.timeoutMessage,t.signal)).status!=="connected")throw t.error;let l=this.records.get(n.serverName);if(!l?.client||l.status.status!=="connected")throw t.error;return await this.callToolOnClient(l.client,n,Cre(t.deadline,t.timeoutMessage),t.signal)}ensureToolCallAuthorizationRecovery(t){let r=this.records.get(t.name);if(r?.connecting&&r.status.status==="connecting"&&(0,alt.isDeepStrictEqual)(r.config,t.config))return r.connecting;let n=this.nextConnectionGeneration(t.name),o=new AbortController,i={abortController:o,config:t.config,status:this.createStatus(t.config,"connecting",{toolCount:t.record.tools.length}),tools:t.record.tools};this.records.set(t.name,i);let s=this.runToolCallAuthorizationRecovery({abortController:o,config:t.config,generation:n,name:t.name,oauthConfig:t.oauthConfig,previousClient:t.record.client,previousTransport:t.record.transport,trigger:t.trigger});return i.connecting=s,s}async runToolCallAuthorizationRecovery(t){let r=Date.now();try{await this.closeClientAndTransport(t.name,t.previousClient,t.previousTransport);let n=await this.runInteractiveOAuthAuthorization({config:t.config,generation:t.generation,name:t.name,oauthConfig:t.oauthConfig,serverUrl:t.config.url,signal:t.abortController.signal,trigger:t.trigger});return n.status==="authorized"||n.status==="already-authorized"?await this.openServerConnection({config:t.config,generation:t.generation,name:t.name,oauthAuthorizationAttempted:!0,signal:t.abortController.signal,timeoutMs:t.config.timeoutMs??nke}):await this.failConnection({config:t.config,error:n.status==="pending"?new Error(`MCP server ${t.name} OAuth authorization is still in progress; complete it in the browser and reconnect`):n.error,failureKind:"oauth_authorization_failed",generation:t.generation,name:t.name,startedAt:r})}catch(n){return await this.failConnection({config:t.config,error:n,failureKind:"oauth_authorization_failed",generation:t.generation,name:t.name,startedAt:r})}}async close(){let t=Date.now(),r=this.records.size;for(let n of this.records.keys())this.nextConnectionGeneration(n);await Promise.all(Array.from(this.records.keys()).map(n=>this.closeRecord(n))),this.records.clear(),this.connectionDiagnosticByServer.clear(),this.logger?.info("MCP adapter closed",{durationMs:Date.now()-t,event:"mcp.adapter.closed",serverCount:r,status:"completed"})}waitForSharedConnection(t,r,n){let o=r.connecting;if(!o)return Promise.resolve(r.status);if(n.oauthAuthorizationTimeoutMs===void 0&&!n.signal)return o;let i,s,u=a(()=>this.records.get(t)?.status??r.status,"currentStatus"),l=[o],c=n.oauthAuthorizationTimeoutMs;return c!==void 0&&l.push(new Promise(d=>{s=setTimeout(()=>d(u()),c)})),n.signal&&l.push(new Promise(d=>{if(n.signal?.aborted){d(u());return}i=a(()=>d(u()),"abortHandler"),n.signal?.addEventListener("abort",i,{once:!0})})),Promise.race(l).finally(()=>{s!==void 0&&clearTimeout(s),i&&n.signal?.removeEventListener("abort",i)})}async openServerConnection(t){let{config:r,generation:n,name:o,oauthAuthorizationAttempted:i=!1,oauthAuthorizationTimeoutMs:s,signal:u,timeoutMs:l,workingDirectory:c}=t,d=Date.now(),p,m,h,_,y,v=r.type==="stdio"?"process_start_failed":"network_unreachable";try{y=(await this.createTransport(r,o,n,s,c,u)).transport,h=this.attachStdioLogging(o,y),p=new vkr({name:this.clientName,version:this.clientVersion},{versionNegotiation:ezo(r,l)}),this.updateCurrentRecord(o,n,{client:p,transport:y});let w=Date.now();await Pq(p.connect(y),l,`MCP server ${o} connection timed out after ${l}ms`,u),m=Date.now()-w,v="tool_list_failed";let b=Date.now(),k=await Pq(p.listTools(),l,`MCP server ${o} tool listing timed out after ${l}ms`,u);_=Date.now()-b;let S=k.tools.map(P=>mSr(o,P,r.timeoutMs,r.type==="http"&&r.auth?.type===MCt)),I=p.getProtocolEra(),C=p.getNegotiatedProtocolVersion(),R=this.createStatus(r,"connected",{protocolEra:I,toolCount:S.length});if(!this.isCurrentConnection(o,n))return await this.closeClientAndTransport(o,p,y),this.records.get(o)?.status??R;this.connectionDiagnosticByServer.delete(o),this.records.set(o,{client:p,config:r,status:R,tools:S,transport:y});let A=oke(y),O=A!=null&&this.connectionContext?this.telemetry?.recordProcessStarted({connectionId:this.connectionContext.mcpConnectionId,pid:A}):void 0;return p.onclose=()=>{if(!this.isCurrentConnection(o,n))return;let P=this.records.get(o);if(!P||P.client!==p)return;let D=h?.(),U=ozo(y);P.status=this.createStatus(P.config,"disconnected",{error:"MCP server connection closed unexpectedly",failureKind:"unexpected_disconnect"}),this.logger?.warn("MCP server connection lost",{...this.connectionContext,event:"mcp.server.connection_lost",mcpServerName:o,...A!=null?{mcpTransportPid:A}:{},...O??{},...U?{exitCode:U.exitCode,signal:U.signal??void 0}:{},status:"failed",transport:P.config.type,...D?{stderr:D}:{}}),P.config.type==="stdio"&&this.connectionContext&&(U||!izo(y))&&this.telemetry?.recordProcessCrashed({connectionId:this.connectionContext.mcpConnectionId,exitCode:U?.exitCode??null,signal:U?.signal??null})},this.logger?.info("MCP server connected",{...this.connectionContext,connectDurationMs:m,durationMs:Date.now()-d,event:"mcp.server.connected",listToolsDurationMs:_,mcpClientName:this.clientName,mcpClientVersion:this.clientVersion,mcpProtocolEra:I??"unknown",mcpProtocolVersion:C??"unknown",mcpServerName:o,...O??{},...A!=null?{mcpTransportPid:A}:{},mcpVersionNegotiationMode:XFo(r),status:"completed",toolCount:S.length,transport:r.type}),R}catch(x){let w=i?void 0:K1e(x),b=w&&r.type!=="stdio"?ilt(r):void 0;if(w&&b&&r.type!=="stdio"){await this.closeClientAndTransport(o,p,y);let S=await this.runInteractiveOAuthAuthorization({config:r,generation:n,name:o,oauthConfig:b,serverUrl:r.url,signal:u,trigger:w});return S.status==="authorized"||S.status==="already-authorized"?await this.openServerConnection({...t,oauthAuthorizationAttempted:!0}):this.failConnection({config:r,connectDurationMs:m,error:S.status==="pending"?new Error(`MCP server ${o} OAuth authorization is still in progress; complete it in the browser and reconnect`):S.error,failureKind:"oauth_authorization_failed",generation:n,getRecentStderr:h,listToolsDurationMs:_,name:o,startedAt:d})}let k=yIr(x)?"protocol_negotiation_failed":void 0;return this.failConnection({client:p,config:r,connectDurationMs:m,error:x,generation:n,getRecentStderr:h,listToolsDurationMs:_,name:o,startedAt:d,transport:y,failureKind:k??v})}}async runInteractiveOAuthAuthorization(t){try{let r=this.createAuthorizationCodeOAuthOptions(t.config,t.name,t.generation),n=r?.credentialStore??$N(),o=Uut(t.name,t.serverUrl,t.oauthConfig),i=t.oauthConfig.scope;if(t.trigger.requiredScope){let s=await SI(n,o);i=hre(t.oauthConfig.scope,s?.tokens?.scope,t.trigger.requiredScope)}return await VSr({adapterInstanceId:this.adapterInstanceId,config:t.oauthConfig,credentialStore:n,fetchFn:xre({env:this.env,network:this.network}),...t.trigger.reason==="insufficient_scope"?{forceReauthorization:!0}:{},keyPrefix:o,logger:this.logger,...r?.onAuthorizationRequired?{onAuthorizationRequired:r.onAuthorizationRequired}:{},...r?.openAuthorizationUrl?{openAuthorizationUrl:r.openAuthorizationUrl}:{},...i?{requestedScope:i}:{},...t.trigger.resourceMetadataUrl?{resourceMetadataUrl:new URL(t.trigger.resourceMetadataUrl)}:{},serverName:t.name,serverUrl:t.serverUrl,signal:t.signal,transactionTtlMs:Hut})}catch(r){return this.logger?.warn("MCP OAuth authorization orchestration failed",{error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"unknown",event:"mcp.oauth.authorization.orchestration_failed",mcpServerName:t.name,status:"failed"}),{status:"failed",error:r}}}async failConnection(t){let{client:r,config:n,connectDurationMs:o,error:i,failureKind:s,generation:u,getRecentStderr:l,listToolsDurationMs:c,name:d,startedAt:p,transport:m}=t,h=i instanceof Error?i.message:String(i),_=(i instanceof Aq?i.kind:void 0)??this.lastOfficialAuthKind.get(d);this.lastOfficialAuthKind.delete(d);let y=this.connectionDiagnosticByServer.get(d);this.connectionDiagnosticByServer.delete(d);let v=(_==="official_mcp_origin_untrusted"?"official_origin_untrusted":void 0)??y?.failureKind??(i instanceof Rq&&s!=="tool_list_failed"?"connection_timeout":void 0)??s??"connection_failed",x=y?.serverRequestId?`${h} - ${y.serverRequestId}`:h,w=this.createStatus(n,"failed",{error:x,failureKind:v,...y?.serverRequestId?{serverRequestId:y.serverRequestId}:{}}),b=l?.(),k=oke(m);return await this.closeClientAndTransport(d,r,m),this.isCurrentConnection(d,u)?(this.records.set(d,{config:n,status:w,tools:[]}),this.logger?.warn("MCP server connection failed",{...this.connectionContext,connectDurationMs:o,durationMs:Date.now()-p,error:x,event:"mcp.server.failed",listToolsDurationMs:c,mcpServerName:d,..._?{officialAuthKind:_}:{},...k!=null?{mcpTransportPid:k}:{},status:"failed",...b?{stderr:b}:{},transport:n.type}),w):this.records.get(d)?.status??w}async createTransport(t,r,n,o,i,s){if(t.type==="stdio")return{transport:new oR({command:t.command,args:t.args??[],cwd:t.cwd?(0,hIr.resolve)(i??this.workingDirectory??process.cwd(),t.cwd):i??this.workingDirectory,env:{...wSr({env:this.env,network:this.network}),...t.env},stderr:"pipe",...Are(t)&&t.official?{requestMetaProvider:a(async()=>{let l=await this.resolveOfficialStdioAuthMeta(r,t,s);return l?{[OCt]:l}:void 0},"requestMetaProvider")}:{}})};let u=xre({env:this.env,network:this.network});if(t.type==="http"){let l=this.createOfficialAuthFetch(t,r,n);return{transport:new bkr(new URL(t.url),{authProvider:this.createOAuthClientProvider(r,t),fetch:l??u,requestInit:t.headers?{headers:t.headers}:void 0})}}return{transport:new xkr(new URL(t.url),{authProvider:this.createOAuthClientProvider(r,t),fetch:u,requestInit:t.headers?{headers:t.headers}:void 0})}}createOfficialAuthFetch(t,r,n){if(!Are(t)||t.type!=="http"||!t.official)return;let o=t.official,i=this.officialMcpAuth?.authHeadersPort,s=this.officialMcpAuth?.trustedOrigins;return s?ySr({baseFetch:xre({env:this.env,network:this.network}),official:o,onAuthFailure:a(u=>this.lastOfficialAuthKind.set(r,u),"onAuthFailure"),onServerResponse:a(u=>{this.isCurrentConnection(r,n)&&this.rememberServerResponse(r,u)},"onServerResponse"),serverName:r,trustedOrigins:s,url:t.url,...i?{authHeadersPort:i}:{},...this.logger?{logger:this.logger}:{},...this.officialMcpAuth?.workspaceIdentity?{workspaceIdentity:this.officialMcpAuth.workspaceIdentity}:{},...this.workingDirectory?{workspacePath:this.workingDirectory}:{}}):(()=>{throw new Aq("official_auth_unavailable",`official MCP trusted origin registry is not available in this runtime: ${r}`)})}createOAuthClientProvider(t,r){if(r.type==="stdio"||Are(r))return;let n=ilt(r);if(n)return ZSr({config:n,credentialStore:this.resolveCredentialStore(),fetchFn:xre({env:this.env,network:this.network}),keyPrefix:Uut(t,r.url,n),...this.logger?{logger:this.logger}:{},serverName:t,serverUrl:r.url});if(r.oauth?.type==="client_credentials")return new fkr({clientId:r.oauth.clientId,clientName:r.oauth.clientName??`${this.clientName}-${t}`,clientSecret:r.oauth.clientSecret,scope:r.oauth.scope})}resolveCredentialStore(){return this.credentialStore??=this.mcpOAuth?.credentialStore??$N(),this.credentialStore}createAuthorizationCodeOAuthOptions(t,r,n,o){return t.type==="stdio"?this.mcpOAuth:{...this.mcpOAuth,authorizationTimeoutMs:o??this.mcpOAuth?.authorizationTimeoutMs,onAuthorizationRequired:a(async i=>{this.updateCurrentRecordStatus(r,n,{authorization:tzo(i),status:"connecting"}),await this.mcpOAuth?.onAuthorizationRequired?.(i)},"onAuthorizationRequired")}}attachStdioLogging(t,r){let n=nzo(olt);return r.stderr?.on("data",i=>{let s=i.toString("utf8");n.append(s),this.logger?.debug("MCP stdio stderr",{event:"mcp.stdio.stderr",mcpServerName:t,stderr:mIr(s).slice(0,olt)})}),()=>{let i=n.read();if(i)return mIr(i).slice(-olt)}}async closeRecord(t){let r=this.records.get(t);r&&(r.abortController?.abort(new Error(`MCP server ${t} connection closed`)),!(!r.client&&!r.transport)&&await this.closeClientAndTransport(t,r.client,r.transport))}async closeClientAndTransport(t,r,n){let o=Date.now(),i=oke(n);r&&(r.onclose=void 0),await this.terminateStdioProcessTree(t,n);try{await r?.close()}catch(s){this.logger?.debug("MCP client close failed",{error:s instanceof Error?s.message:String(s),event:"mcp.client.close.failed",mcpServerName:t})}try{await n?.close()}catch(s){this.logger?.debug("MCP transport close failed",{error:s instanceof Error?s.message:String(s),event:"mcp.transport.close.failed",mcpServerName:t})}this.connectionContext&&n instanceof oR&&!n.processAlive&&this.telemetry?.recordProcessClosed({connectionId:this.connectionContext.mcpConnectionId}),this.logger?.info("MCP server closed",{...this.connectionContext,durationMs:Date.now()-o,event:"mcp.server.closed",mcpServerName:t,...i!=null?{mcpTransportPid:i}:{},status:"completed"})}async terminateStdioProcessTree(t,r){let n=oke(r);if(n!=null)try{await tke(n)}catch(o){this.logger?.warn("MCP stdio process tree cleanup failed",{...this.connectionContext,error:o instanceof Error?o.message:String(o),event:"mcp.stdio.process_tree_cleanup.failed",mcpServerName:t,mcpTransportPid:n,pid:n,status:"failed"})}}nextConnectionGeneration(t){let r=(this.connectionGenerations.get(t)??0)+1;return this.connectionGenerations.set(t,r),r}isCurrentConnection(t,r){return this.connectionGenerations.get(t)===r}updateCurrentRecord(t,r,n){if(!this.isCurrentConnection(t,r))return;let o=this.records.get(t);o&&Object.assign(o,n)}updateCurrentRecordStatus(t,r,n){if(!this.isCurrentConnection(t,r))return;let o=this.records.get(t);o&&(o.status={...o.status,...n,updatedAt:new Date().toISOString()})}createStatus(t,r,n={}){return{status:r,transport:t.type,toolCount:n.toolCount??0,updatedAt:new Date().toISOString(),authorization:n.authorization,error:n.error,failureKind:n.failureKind,protocolEra:n.protocolEra,serverRequestId:n.serverRequestId}}};a(QFo,"mcpRequestMeta");a(_Ir,"resolveVersionNegotiationMode");a(yIr,"isProtocolNegotiationFailure");a(XFo,"formatVersionNegotiationMode");a(ezo,"resolveVersionNegotiation");a(tzo,"createOAuthAuthorizationStatus");a(ilt,"resolveAuthorizationCodeOAuthConfig");a(Are,"isOfficialAuthConfig");a(rzo,"hasAuthorizationHeader");a(nzo,"createBoundedTextBuffer");a(mIr,"sanitizeMcpStdioStderr");a(oke,"getStdioTransportPid");a(ozo,"getStdioTransportExitInfo");a(izo,"isStdioTransportProcessAlive");a(vIr,"isRecord");a(azo,"isPeerAnsweredError")});function TIr(e={}){return new llt(e)}function CIr(e={}){return new clt(e)}async function bIr(e,t,r){Rh(r,"Workflow JSONL append cancelled"),await(0,mf.mkdir)((0,il.dirname)(e),{recursive:!0}),await(0,mf.appendFile)(e,`${JSON.stringify(t)}
|
|
1813
1813
|
`,"utf8")}async function dlt(e,t){Rh(t,"Workflow JSON read cancelled");try{return JSON.parse(await(0,mf.readFile)(e,"utf8"))}catch(r){if(plt(r)&&r.code==="ENOENT")return null;throw r}}async function szo(e,t){Rh(t,"Workflow JSONL read cancelled");try{return(await(0,mf.readFile)(e,"utf8")).split(/\r?\n/).filter(n=>n.trim().length>0).map(n=>JSON.parse(n))}catch(r){if(plt(r)&&r.code==="ENOENT")return[];throw r}}async function wIr(e,t,r){await EIr(e,`${JSON.stringify(t,null,2)}
|
|
1814
1814
|
`,r)}async function EIr(e,t,r){Rh(r,"Workflow file write cancelled"),await(0,mf.mkdir)((0,il.dirname)(e),{recursive:!0});let n=`${e}.${(0,kIr.randomUUID)()}.tmp`;await(0,mf.writeFile)(n,t,"utf8"),await(0,mf.rename)(n,e)}function uzo(e){let t=(0,il.normalize)(e);if((0,il.isAbsolute)(t)||t===".."||t.startsWith("..\\")||t.startsWith("../"))throw new Error(`Workflow artifact path must stay inside the run directory: ${e}`);return t}function lzo(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120)||"unknown"}function czo(e){if(e.length===0||e==="."||e===".."||e.includes("/")||e.includes("\\")||(0,il.normalize)(e)!==e||!/^[a-zA-Z0-9._-]+$/.test(e))throw new Error(`Workflow definition id must be a file-safe name: ${e}`)}function Rh(e,t){if(e?.aborted)throw e.reason instanceof Error?e.reason:new Error(t)}function plt(e){return e instanceof Error&&"code"in e}var kIr,mf,SIr,il,IIr,xIr,llt,clt,mlt=T(()=>{"use strict";kIr=require("node:crypto"),mf=require("node:fs/promises"),SIr=require("node:os"),il=require("node:path");ke();IIr=(0,il.join)((0,SIr.homedir)(),".zcode","cli","workflows"),xIr=".json",llt=class{static{a(this,"NodeWorkflowStore")}rootDir;constructor(t={}){this.rootDir=t.rootDir??IIr}async appendEvent(t,r){Rh(r?.signal,"Workflow event append cancelled"),l9e.parse(t),await bIr(this.eventsPath(t.runId),t,r?.signal)}async appendGraphRecord(t,r,n){Rh(n?.signal,"Workflow graph append cancelled"),B3t.parse(r),await bIr(this.graphPath(t),r,n?.signal)}async listRuns(t={},r){Rh(r?.signal,"Workflow run list cancelled");let i=(await this.readIndex(r?.signal)).runs.filter(s=>(t.cwd===void 0||s.cwd===t.cwd)&&(t.kind===void 0||s.kind===t.kind)).sort((s,u)=>u.updatedAt.localeCompare(s.updatedAt));return t.limit===void 0?i:i.slice(0,t.limit)}async readEvents(t,r){return Rh(r?.signal,"Workflow event read cancelled"),(await szo(this.eventsPath(t),r?.signal)).map(o=>l9e.parse(o))}async readLatestRun(t={},r){let[n]=await this.listRuns({...t,limit:1},r);return n?await this.readRun(n.runId,r):null}async readRun(t,r){Rh(r?.signal,"Workflow snapshot read cancelled");let n=await dlt(this.snapshotPath(t),r?.signal);return n===null?null:u9e.parse(n)}async writeArtifact(t,r,n,o){Rh(o?.signal,"Workflow artifact write cancelled");let i=uzo(r),s=(0,il.join)(this.runRoot(t),i);return await EIr(s,n,o?.signal),{path:s,relativePath:i}}async writeReport(t,r,n){return await this.writeArtifact(t,"report.md",r,n)}async writeSnapshot(t,r){Rh(r?.signal,"Workflow snapshot write cancelled"),u9e.parse(t),await wIr(this.snapshotPath(t.runId),t,r?.signal),await this.upsertIndex(t,r?.signal)}async upsertIndex(t,r){let n=await this.readIndex(r),i=[{completedAt:t.completedAt,createdAt:t.createdAt,cwd:t.cwd,kind:t.kind,runId:t.runId,status:t.status,task:t.task,updatedAt:t.updatedAt},...n.runs.filter(s=>s.runId!==t.runId)].sort((s,u)=>u.updatedAt.localeCompare(s.updatedAt));await wIr(this.indexPath(),{runs:i},r)}async readIndex(t){let r=await dlt(this.indexPath(),t);return r===null?{runs:[]}:{runs:Array.isArray(r.runs)?r.runs:[]}}eventsPath(t){return(0,il.join)(this.runRoot(t),"events.jsonl")}graphPath(t){return(0,il.join)(this.runRoot(t),"graph.jsonl")}indexPath(){return(0,il.join)(this.rootDir,"index.json")}runRoot(t){return(0,il.join)(this.rootDir,"runs",lzo(t))}snapshotPath(t){return(0,il.join)(this.runRoot(t),"run.json")}};a(TIr,"createNodeWorkflowStore");clt=class{static{a(this,"NodeWorkflowDefinitionStore")}definitionsDir;constructor(t={}){this.definitionsDir=t.definitionsDir??(0,il.join)(t.rootDir??IIr,"definitions")}async listDefinitions(t){Rh(t?.signal,"Workflow definition list cancelled");let r;try{r=await(0,mf.readdir)(this.definitionsDir)}catch(i){if(plt(i)&&i.code==="ENOENT")return[];throw i}let n=r.filter(i=>(0,il.extname)(i)===xIr).map(i=>(0,il.parse)(i).name).sort((i,s)=>i.localeCompare(s)),o=[];for(let i of n){let s=await this.readDefinition(i,t);s&&o.push(s)}return o}async readDefinition(t,r){Rh(r?.signal,"Workflow definition read cancelled"),czo(t);let n=await dlt(this.definitionPath(t),r?.signal);if(n===null)return null;let o=Gj.parse(n);if(o.definitionId!==t)throw new Error(`Workflow definition id mismatch: requested ${t}, file declares ${o.definitionId}`);return o}definitionPath(t){return(0,il.join)(this.definitionsDir,`${t}${xIr}`)}};a(CIr,"createNodeWorkflowDefinitionStore");a(bIr,"appendJsonLine");a(dlt,"readJson");a(szo,"readJsonLines");a(wIr,"writeJsonFile");a(EIr,"writeTextFile");a(uzo,"normalizeRelativePath");a(lzo,"sanitizePathSegment");a(czo,"validateDefinitionId");a(Rh,"throwIfAborted");a(plt,"isNodeError")});var AIr=T(()=>{"use strict"});var ake=T(()=>{"use strict";qy();dF();BK();yF();ak();NZe();jZe();err();eI();B7();wl();$7();tit();dte();Fbr();Wat();ike();mlt();AIr()});function RIr(e,t,r,n,o,i){return{id:e,sessionId:t,turnNumber:r,phase:On.Idle,traceId:n,input:o,attachments:i,streamingContent:"",toolCalls:[],toolResults:[],scheduledTools:{items:[],parallelGroups:[],executionOrder:[]},pendingInputs:[],acceptsPendingInput:!0,pendingPermissions:[],resolvedPermissions:[],resultType:"success",startedAt:new Date}}function PIr(e){return e===On.Completing||e===On.Error}function MIr(e,t){return{[On.Idle]:[On.ProcessingInput],[On.ProcessingInput]:[On.AwaitingModelResponse,On.Completing],[On.AwaitingModelResponse]:[On.Streaming,On.Completing,On.Error],[On.Streaming]:[On.SchedulingTools,On.AggregatingResults,On.Completing,On.Error],[On.SchedulingTools]:[On.ExecutingTools,On.AwaitingPermission,On.Error],[On.ExecutingTools]:[On.AggregatingResults,On.AwaitingPermission,On.Error],[On.AggregatingResults]:[On.AwaitingModelResponse,On.SchedulingTools,On.Completing,On.Error],[On.AwaitingPermission]:[On.ExecutingTools,On.Error],[On.Completing]:[On.Idle],[On.Error]:[On.Idle]}[e]?.includes(t)??!1}var On,flt=T(()=>{"use strict";On={Idle:"idle",ProcessingInput:"processing_input",AwaitingModelResponse:"awaiting_model_response",Streaming:"streaming",SchedulingTools:"scheduling_tools",ExecutingTools:"executing_tools",AggregatingResults:"aggregating_results",AwaitingPermission:"awaiting_permission",Completing:"completing",Error:"error"};a(RIr,"createTurnState");a(PIr,"isTerminalPhase");a(MIr,"canTransitionTo")});var $a,hlt=T(()=>{"use strict";flt();ke();$a=class e{static{a(this,"TurnMachineImpl")}state;constructor(t){this.state=t}static create(t,r,n,o,i){let s=RIr(i??u0(),t,r,o??crypto.randomUUID(),n);return new e(s)}transition(t){if(!MIr(this.state.phase,t))throw Ie(ge.InvalidTurnPhase,`Cannot transition from ${this.state.phase} to ${t}`,{context:{current:this.state.phase,target:t},recoverable:!0});return{...this.state,phase:t}}start(){return this.transition(On.ProcessingInput)}startModelRequest(t,r){if(this.state.phase!==On.ProcessingInput&&this.state.phase!==On.AggregatingResults)throw Ie(ge.InvalidTurnPhase,"Must be in ProcessingInput or AggregatingResults phase",{context:{current:this.state.phase},recoverable:!0});return{...this.transition(On.AwaitingModelResponse),modelRequest:{model:t,messages:r}}}receiveModelResponse(t){let r=this.transition(On.Streaming);return{...r,streamingContent:r.streamingContent+t}}addStreamingContent(t){let r=this.transition(On.Streaming);return{...r,streamingContent:r.streamingContent+t}}scheduleTools(t,r){return{...this.transition(On.SchedulingTools),toolCalls:t.map(o=>({id:o.id,name:o.name,input:o.input,status:"scheduled",scheduledAt:new Date})),scheduledTools:r}}startToolExecution(){let r=this.state.toolCalls.some(o=>o.status==="waiting_permission")?On.AwaitingPermission:On.ExecutingTools,n=this.transition(r);return{...n,toolCalls:n.toolCalls.map(o=>({...o,status:o.status==="waiting_permission"?o.status:"running",startedAt:o.status!=="waiting_permission"?new Date:o.startedAt}))}}completeTool(t,r){let n=r.success?void 0:Yn(r.content),o=this.state.toolCalls.map(i=>i.id===t?{...i,status:r.success?"completed":"failed",completedAt:new Date,result:{success:r.success,content:r.content}}:i);return{...this.state,toolCalls:o,toolResults:[...this.state.toolResults,{success:r.success,content:r.content,error:r.success?void 0:{type:"tool_error",message:n??"",recoverable:!0}}]}}queuePendingInput(t){return{...this.state,pendingInputs:[...this.state.pendingInputs,t]}}drainPendingInputs(){return{inputs:this.state.pendingInputs,state:{...this.state,pendingInputs:[]}}}requestPermission(t){let r=this.transition(On.AwaitingPermission);return{...r,toolCalls:r.toolCalls.map(n=>n.id===t.toolCallId?{...n,status:"waiting_permission"}:n),pendingPermissions:[...r.pendingPermissions,t]}}resolvePermission(t,r,n){let o=this.state.toolCalls.map(i=>i.id===t?{...i,status:r==="deny"?"permission_denied":i.status,input:n??i.input}:i);return{...this.state,toolCalls:o,pendingPermissions:this.state.pendingPermissions.filter(i=>i.toolCallId!==t),resolvedPermissions:[...this.state.resolvedPermissions,{toolCallId:t,decision:r,modifiedInput:n,resolvedAt:new Date}]}}aggregateResults(){return this.transition(On.AggregatingResults)}complete(t,r="success"){return{...this.transition(On.Completing),finalResponse:t,resultType:r,completedAt:new Date}}fail(t){return{...this.state,phase:On.Error,error:t,completedAt:new Date}}getNextPhase(){let{phase:t,toolCalls:r,streamingContent:n}=this.state;return t===On.Streaming&&r.length>0?On.SchedulingTools:t===On.Streaming&&r.length===0&&n?On.Completing:t===On.ExecutingTools&&r.filter(i=>i.status==="running"||i.status==="waiting_permission").length===0?On.AggregatingResults:t===On.AggregatingResults?r.filter(i=>i.status==="failed"||i.status==="permission_denied").length>0?On.Completing:On.AwaitingModelResponse:t}isComplete(){return PIr(this.state.phase)}}});function Oq(e){let t=vzo[e];return{source:e,...t}}function _lt(e){return xzo.has(e)}function II(e,t){if(Oq(e).providerVisibility!=="provider_visible")throw new Error(`System reminder source ${e} is not provider-visible`);let n=ylt(Dq(t));return _zo.has(e)?`${n}
|
|
1815
1815
|
`:n}function ylt(e){let t=typeof e=="string"?e:e.join(`
|