linkque-cli-v2 1.6.5 → 1.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dev/worker.js +16 -3
  2. package/linkquejs.js +1015 -631
  3. package/package.json +1 -1
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/anthropic-messages-GSYNBLMR.js +17 -0
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{azure-openai-responses-HVAVRLTK.js → azure-openai-responses-NPKMM3LF.js} +7 -9
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-IATVK6CO.js → chunk-FC6S43DG.js} +1 -1
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-UTJ7DVT7.js → chunk-FH2M6YD6.js} +407 -59
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-YZLXAZFT.js → chunk-ICPH34ZQ.js} +36 -11
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-Q2Y6LMNC.js → chunk-J4JCPZDI.js} +5 -7
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-4XAZNSEQ.js → chunk-JMBJJF7P.js} +18 -5
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{anthropic-messages-5DOLTIGP.js → chunk-KDHBKVSL.js} +14 -15
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-Y3G4J3TB.js → chunk-XOLFZ4XS.js} +316 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{dist-ZPLSQEAM.js → dist-TGBYXSBU.js} +27 -42
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-generative-ai-OLT56CSV.js → google-generative-ai-KD7MXONK.js} +8 -10
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-vertex-4DBBJ7SR.js → google-vertex-TREYA472.js} +9 -11
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-OEBGEDLQ.js → mistral-conversations-OEOTQWE5.js} +7 -9
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-codex-responses-3KOC6KHN.js → openai-codex-responses-GEFKSNVN.js} +10 -12
  18. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-completions-HG6OJRL5.js → openai-completions-TAACO6T5.js} +13 -15
  19. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-responses-F6V2PG3Y.js → openai-responses-4DDTXIGI.js} +12 -14
  20. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +197 -71
  21. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +2 -2
  22. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +2 -2
  23. package/worker.js +357 -94
  24. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-RYONFGPP.js +0 -317
  25. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{pi-messages-DC4DVRAJ.js → pi-messages-7JN3W3BC.js} +4 -4
@@ -5420,8 +5420,8 @@ var require_multipleOf = __commonJS({
5420
5420
  const { gen, data, schemaCode, it } = cxt;
5421
5421
  const prec = it.opts.multipleOfPrecision;
5422
5422
  const res = gen.let("res");
5423
- const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
5424
- cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
5423
+ const invalid2 = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
5424
+ cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid2}))`);
5425
5425
  }
5426
5426
  };
5427
5427
  exports.default = def;
@@ -29313,7 +29313,9 @@ var REDACTED_HEADER_NAMES = /* @__PURE__ */ new Set([
29313
29313
  "x-signature-content",
29314
29314
  "x-alipay-sdk-version",
29315
29315
  "x-alipay-authcode",
29316
- "anthropic-api-key"
29316
+ "anthropic-api-key",
29317
+ "x-linkque-runtime-mac",
29318
+ "x-linkque-run-proof"
29317
29319
  ]);
29318
29320
  var REDACTED_VALUE = "ak***";
29319
29321
  var RESPONSE_CORRELATION_HEADER_NAMES = [
@@ -29768,20 +29770,20 @@ function toWebSearchFailure(error) {
29768
29770
  return { code: safe.code, message: safe.message, retryable: safe.retryable };
29769
29771
  }
29770
29772
  function parseWebSearchArgs(args) {
29771
- const invalid = () => new WebSearchError("WEB_SEARCH_INVALID_ARGS");
29773
+ const invalid2 = () => new WebSearchError("WEB_SEARCH_INVALID_ARGS");
29772
29774
  if (!args || typeof args !== "object" || Array.isArray(args))
29773
- throw invalid();
29775
+ throw invalid2();
29774
29776
  const value = args;
29775
29777
  if (Object.keys(value).some((key) => key !== "query" && key !== "topK"))
29776
- throw invalid();
29778
+ throw invalid2();
29777
29779
  if (typeof value.query !== "string")
29778
- throw invalid();
29780
+ throw invalid2();
29779
29781
  const query = value.query.trim();
29780
29782
  if (!query || [...query].length > WEB_SEARCH_QUERY_MAX_LENGTH)
29781
- throw invalid();
29783
+ throw invalid2();
29782
29784
  const topK = value.topK;
29783
29785
  if (topK !== void 0 && (typeof topK !== "number" || !Number.isInteger(topK) || topK < 1 || topK > WEB_SEARCH_TOP_K_MAX))
29784
- throw invalid();
29786
+ throw invalid2();
29785
29787
  return { query, ...topK !== void 0 ? { topK } : {} };
29786
29788
  }
29787
29789
  function throwIfWebSearchAborted(signal) {
@@ -31244,6 +31246,192 @@ function encodeConversationSseEvent(event) {
31244
31246
  `;
31245
31247
  }
31246
31248
 
31249
+ // ../linkque-agent-runtime/dist/esm/impl/scenario/gatewayRunAuthorization.js
31250
+ import { hkdfSync, randomBytes } from "node:crypto";
31251
+
31252
+ // ../linkque-agent-runtime/dist/esm/impl/scenario/runtimeMac.js
31253
+ import { createHash as createHash3, createHmac, timingSafeEqual } from "node:crypto";
31254
+ function invalid() {
31255
+ throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
31256
+ }
31257
+ function canonicalJson(value, depth = 0) {
31258
+ if (depth > 64)
31259
+ invalid();
31260
+ if (value === null || typeof value === "string" || typeof value === "boolean")
31261
+ return JSON.stringify(value);
31262
+ if (typeof value === "number" && Number.isFinite(value))
31263
+ return JSON.stringify(value);
31264
+ if (Array.isArray(value))
31265
+ return `[${value.map((v) => canonicalJson(v, depth + 1)).join(",")}]`;
31266
+ if (value && typeof value === "object" && Object.prototype.toString.call(value) === "[object Object]") {
31267
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k], depth + 1)}`).join(",")}}`;
31268
+ }
31269
+ return invalid();
31270
+ }
31271
+ function signRuntimeRequest(input, key) {
31272
+ if (!input || key?.length !== 32 || !Number.isSafeInteger(input.timestamp) || input.timestamp <= 0 || !/^[A-Za-z0-9_-]{1,64}$/u.test(input.caller) || !/^[A-Za-z0-9_-]{1,64}$/u.test(input.keyId) || !/^[a-f0-9]{32}$/u.test(input.nonce) || !/^[A-Z]{3,8}$/u.test(input.method) || typeof input.path !== "string" || !input.path.startsWith("/") || input.path.length > 2048 || typeof input.runId !== "string" || !/^[\x21-\x7e]{1,64}$/u.test(input.runId) || typeof input.appbaseUserId !== "string" || !/^[\x21-\x7e]{1,128}$/u.test(input.appbaseUserId) || typeof input.token !== "string" || !input.token || input.token.length > 8192 || typeof input.proof !== "string" || input.proof.length > 4200)
31273
+ invalid();
31274
+ const sha256 = (value) => createHash3("sha256").update(value).digest("hex");
31275
+ const body = canonicalJson(input.body);
31276
+ if (Buffer.byteLength(body) > 4 * 1024 * 1024)
31277
+ invalid();
31278
+ const payload = JSON.stringify([
31279
+ "linkque-runtime-request-v1",
31280
+ input.caller,
31281
+ input.keyId,
31282
+ input.timestamp,
31283
+ input.nonce,
31284
+ input.method,
31285
+ input.path,
31286
+ sha256(body),
31287
+ sha256(input.token),
31288
+ sha256(input.proof),
31289
+ input.runId,
31290
+ input.appbaseUserId
31291
+ ]);
31292
+ return createHmac("sha256", key).update(payload).digest("base64url");
31293
+ }
31294
+
31295
+ // ../linkque-agent-runtime/dist/esm/impl/scenario/gatewayRunAuthorization.js
31296
+ var SCENARIO_RUNTIME_CALLER = "appbase-agent-function";
31297
+ var SCENARIO_RUNTIME_KEY_ID = "agent-aak-v1";
31298
+ function deriveScenarioRuntimeMacKey(accessKey) {
31299
+ const normalized = accessKey.trim();
31300
+ if (!normalized)
31301
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
31302
+ return Buffer.from(hkdfSync("sha256", Buffer.from(normalized, "utf8"), "linkque-scenario-agent-aak-v1", "linkque:scenario:runtime-mac:v1", 32));
31303
+ }
31304
+ function createGatewayRunAuthorization(options) {
31305
+ if (options.authorizationHeader !== `Scenario ${options.token}` || !/^lqs_[A-Za-z0-9_-]{43}$/u.test(options.token)) {
31306
+ throw new Error("scenario authorization credential mismatch");
31307
+ }
31308
+ const base = new URL(options.baseUrl);
31309
+ const key = deriveScenarioRuntimeMacKey(options.accessKey);
31310
+ if (base.protocol !== "https:" || base.username || base.password || base.search || base.hash) {
31311
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
31312
+ }
31313
+ const modelPath = `${base.pathname.replace(/\/$/u, "")}/v1/messages`;
31314
+ const baseFetch = options.fetch ?? globalThis.fetch;
31315
+ return {
31316
+ async authorizeRun(identity) {
31317
+ const signedHeaders = (url2, body, proof) => {
31318
+ const timestamp = Date.now();
31319
+ const nonce = randomBytes(16).toString("hex");
31320
+ const mac = signRuntimeRequest({
31321
+ ...identity,
31322
+ caller: SCENARIO_RUNTIME_CALLER,
31323
+ keyId: SCENARIO_RUNTIME_KEY_ID,
31324
+ timestamp,
31325
+ nonce,
31326
+ method: "POST",
31327
+ path: url2.pathname + url2.search,
31328
+ token: options.token,
31329
+ proof,
31330
+ body
31331
+ }, key);
31332
+ return {
31333
+ "x-linkque-runtime-caller": SCENARIO_RUNTIME_CALLER,
31334
+ "x-linkque-runtime-key-id": SCENARIO_RUNTIME_KEY_ID,
31335
+ "x-linkque-runtime-timestamp": String(timestamp),
31336
+ "x-linkque-runtime-nonce": nonce,
31337
+ "x-linkque-runtime-user-id": identity.appbaseUserId,
31338
+ "x-linkque-runtime-mac": mac
31339
+ };
31340
+ };
31341
+ const invoke = async (path2, previousProof) => {
31342
+ const url2 = new URL(path2, base.origin);
31343
+ const body = {
31344
+ agentId: identity.agentId,
31345
+ runId: identity.runId,
31346
+ ...previousProof ? { proof: previousProof } : {}
31347
+ };
31348
+ let response;
31349
+ try {
31350
+ response = await baseFetch(url2, {
31351
+ method: "POST",
31352
+ redirect: "error",
31353
+ signal: AbortSignal.timeout(5e3),
31354
+ headers: {
31355
+ authorization: options.authorizationHeader,
31356
+ "content-type": "application/json",
31357
+ ...signedHeaders(url2, body, previousProof ?? "")
31358
+ },
31359
+ body: JSON.stringify(body)
31360
+ });
31361
+ } catch {
31362
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
31363
+ }
31364
+ if (!response.ok)
31365
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
31366
+ const raw = await response.text();
31367
+ if (raw.length > 16384)
31368
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
31369
+ let result;
31370
+ try {
31371
+ result = JSON.parse(raw);
31372
+ } catch {
31373
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
31374
+ }
31375
+ if (result?.success !== true) {
31376
+ throw new Error([
31377
+ "SCENARIO_TURN_LIMIT",
31378
+ "SCENARIO_RUNTIME_AUTH_INVALID",
31379
+ "SCENARIO_RUNTIME_REPLAY"
31380
+ ].includes(result?.errorCode) ? result.errorCode : "SCENARIO_RUN_UNAVAILABLE");
31381
+ }
31382
+ const data = result.data;
31383
+ if (data?.quotaMode === "NORMAL" && !previousProof)
31384
+ return { quotaMode: "NORMAL" };
31385
+ if (!["LIMITED", "AUTH_ONLY"].includes(data?.quotaMode) || typeof data.proof !== "string" || !data.proof || data.proof.length > 4200 || !Number.isSafeInteger(data.expiresAt) || data.expiresAt <= Date.now())
31386
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
31387
+ return data;
31388
+ };
31389
+ let grant = await invoke("/api/scenario/authorize-run");
31390
+ if (grant.quotaMode === "NORMAL")
31391
+ return { quotaMode: "NORMAL" };
31392
+ const quotaMode = grant.quotaMode;
31393
+ let renewing;
31394
+ const requireProof = async () => {
31395
+ if (grant.expiresAt - Date.now() > 15e3)
31396
+ return;
31397
+ renewing ??= invoke("/api/scenario/renew-run", grant.proof).then((next) => {
31398
+ if (next.quotaMode !== quotaMode)
31399
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
31400
+ grant = next;
31401
+ }).finally(() => {
31402
+ renewing = void 0;
31403
+ });
31404
+ await renewing;
31405
+ };
31406
+ const modelFetch = async (input, init) => {
31407
+ const request = new Request(input, init);
31408
+ const url2 = new URL(request.url);
31409
+ if (request.method !== "POST" || url2.origin !== base.origin || url2.pathname !== modelPath || url2.search || url2.hash || request.headers.get("x-api-key") !== options.token)
31410
+ throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
31411
+ const raw = await request.text();
31412
+ if (Buffer.byteLength(raw) > 4 * 1024 * 1024)
31413
+ throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
31414
+ const body = JSON.parse(raw);
31415
+ await requireProof();
31416
+ const headers = new Headers(request.headers);
31417
+ headers.set("x-linkque-run-proof", grant.proof);
31418
+ headers.set("x-run-id", identity.runId);
31419
+ headers.set("x-agent-id", identity.agentId);
31420
+ for (const [headerName, value] of Object.entries(signedHeaders(url2, body, grant.proof)))
31421
+ headers.set(headerName, value);
31422
+ return baseFetch(request.url, {
31423
+ method: "POST",
31424
+ headers,
31425
+ body: raw,
31426
+ signal: request.signal,
31427
+ redirect: "error"
31428
+ });
31429
+ };
31430
+ return { quotaMode, modelFetch };
31431
+ }
31432
+ };
31433
+ }
31434
+
31247
31435
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
31248
31436
  function isZ4Schema(s) {
31249
31437
  const schema = s;
@@ -32893,6 +33081,9 @@ var Protocol = class {
32893
33081
  this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
32894
33082
  const handleTaskResult = async () => {
32895
33083
  const taskId = request.params.taskId;
33084
+ if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
33085
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
33086
+ }
32896
33087
  if (this._taskMessageQueue) {
32897
33088
  let queuedMessage;
32898
33089
  while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
@@ -32923,12 +33114,12 @@ var Protocol = class {
32923
33114
  throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
32924
33115
  }
32925
33116
  if (!isTerminal(task.status)) {
32926
- await this._waitForTaskUpdate(taskId, extra.signal);
33117
+ await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
32927
33118
  return await handleTaskResult();
32928
33119
  }
32929
33120
  if (isTerminal(task.status)) {
32930
33121
  const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
32931
- this._clearTaskQueue(taskId);
33122
+ this._clearTaskQueue(taskId, extra.sessionId);
32932
33123
  return {
32933
33124
  ...result,
32934
33125
  _meta: {
@@ -32965,7 +33156,7 @@ var Protocol = class {
32965
33156
  throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
32966
33157
  }
32967
33158
  await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
32968
- this._clearTaskQueue(request.params.taskId);
33159
+ this._clearTaskQueue(request.params.taskId, extra.sessionId);
32969
33160
  const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
32970
33161
  if (!cancelledTask) {
32971
33162
  throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
@@ -33093,6 +33284,19 @@ var Protocol = class {
33093
33284
  const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
33094
33285
  const capturedTransport = this._transport;
33095
33286
  const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
33287
+ const sessionId = capturedTransport?.sessionId;
33288
+ const store = this._taskStore;
33289
+ let relatedTaskFound = true;
33290
+ let relatedTaskLookup;
33291
+ if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) {
33292
+ relatedTaskFound = false;
33293
+ relatedTaskLookup = (async () => {
33294
+ if (!await store.getTask(relatedTaskId, sessionId)) {
33295
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
33296
+ }
33297
+ relatedTaskFound = true;
33298
+ })();
33299
+ }
33096
33300
  if (handler === void 0) {
33097
33301
  const errorResponse = {
33098
33302
  jsonrpc: "2.0",
@@ -33102,7 +33306,10 @@ var Protocol = class {
33102
33306
  message: "Method not found"
33103
33307
  }
33104
33308
  };
33105
- if (relatedTaskId && this._taskMessageQueue) {
33309
+ if (relatedTaskId && relatedTaskLookup) {
33310
+ const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
33311
+ relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
33312
+ } else if (relatedTaskId && this._taskMessageQueue) {
33106
33313
  this._enqueueTaskMessage(relatedTaskId, {
33107
33314
  type: "error",
33108
33315
  message: errorResponse,
@@ -33153,7 +33360,10 @@ var Protocol = class {
33153
33360
  closeSSEStream: extra?.closeSSEStream,
33154
33361
  closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
33155
33362
  };
33156
- Promise.resolve().then(() => {
33363
+ (relatedTaskLookup ?? Promise.resolve()).then(() => {
33364
+ if (relatedTaskLookup && abortController.signal.aborted) {
33365
+ throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
33366
+ }
33157
33367
  if (taskCreationParams) {
33158
33368
  this.assertTaskHandlerCapability(request.method);
33159
33369
  }
@@ -33188,7 +33398,7 @@ var Protocol = class {
33188
33398
  ...error["data"] !== void 0 && { data: error["data"] }
33189
33399
  }
33190
33400
  };
33191
- if (relatedTaskId && this._taskMessageQueue) {
33401
+ if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
33192
33402
  await this._enqueueTaskMessage(relatedTaskId, {
33193
33403
  type: "error",
33194
33404
  message: errorResponse,
@@ -33668,7 +33878,7 @@ var Protocol = class {
33668
33878
  throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
33669
33879
  }
33670
33880
  const maxQueueSize = this._options?.maxTaskQueueSize;
33671
- await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
33881
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
33672
33882
  }
33673
33883
  /**
33674
33884
  * Clears the message queue for a task and rejects any pending request resolvers.
@@ -33697,12 +33907,13 @@ var Protocol = class {
33697
33907
  * Uses polling to check for updates at the task's configured poll interval.
33698
33908
  * @param taskId The task ID to wait for
33699
33909
  * @param signal Abort signal to cancel the wait
33910
+ * @param sessionId Session of the request that waits, passed to the task store
33700
33911
  * @returns Promise that resolves when an update occurs or rejects if aborted
33701
33912
  */
33702
- async _waitForTaskUpdate(taskId, signal) {
33913
+ async _waitForTaskUpdate(taskId, signal, sessionId) {
33703
33914
  let interval = this._options?.defaultTaskPollInterval ?? 1e3;
33704
33915
  try {
33705
- const task = await this._taskStore?.getTask(taskId);
33916
+ const task = await this._taskStore?.getTask(taskId, sessionId);
33706
33917
  if (task?.pollInterval) {
33707
33918
  interval = task.pollInterval;
33708
33919
  }
@@ -35337,6 +35548,68 @@ function createFetchWithInit(baseFetch = fetch, baseInit) {
35337
35548
  return baseFetch(url2, mergedInit);
35338
35549
  };
35339
35550
  }
35551
+ var MAX_REDIRECTS = 5;
35552
+ var REDIRECT_STATUSES = [301, 302, 303, 307, 308];
35553
+ function isWithinOrigin(from, to) {
35554
+ if (from.protocol === to.protocol && from.hostname === to.hostname && from.port === to.port) {
35555
+ return true;
35556
+ }
35557
+ return from.hostname === to.hostname && from.protocol === "http:" && from.port === "" && to.protocol === "https:" && to.port === "";
35558
+ }
35559
+ function redirectTarget(response, requestUrl) {
35560
+ const location = REDIRECT_STATUSES.includes(response.status) ? response.headers.get("location") : null;
35561
+ try {
35562
+ return location ? new URL(location, requestUrl) : void 0;
35563
+ } catch {
35564
+ return void 0;
35565
+ }
35566
+ }
35567
+ function followWithinOrigin(baseFetch, url2, init, response, followed = 0) {
35568
+ const target = redirectTarget(response, url2);
35569
+ const keepsMethod = response.status === 307 || response.status === 308 || (init?.method ?? "GET").toUpperCase() === "GET";
35570
+ if (!target || followed === MAX_REDIRECTS || !keepsMethod) {
35571
+ return void 0;
35572
+ }
35573
+ const from = new URL(url2);
35574
+ const addsUserinfo = (target.username || target.password) && (target.username !== from.username || target.password !== from.password);
35575
+ if (addsUserinfo || !isWithinOrigin(from, target)) {
35576
+ return void 0;
35577
+ }
35578
+ return Promise.resolve(response.body?.cancel()).then(() => baseFetch(target, { ...init, redirect: "manual" })).then((next) => followWithinOrigin(baseFetch, target, init, next, followed + 1) ?? next);
35579
+ }
35580
+ var followingFetches = /* @__PURE__ */ new WeakSet();
35581
+ function fetchLeavingRedirects(baseFetch) {
35582
+ const following = (url2, init) => (baseFetch ?? fetch)(url2, init);
35583
+ followingFetches.add(following);
35584
+ return following;
35585
+ }
35586
+ function fetchWithinOrigin(baseFetch = fetch) {
35587
+ if (followingFetches.has(baseFetch)) {
35588
+ return baseFetch;
35589
+ }
35590
+ return (url2, init) => {
35591
+ if (init?.redirect === "error" || init?.redirect === "manual") {
35592
+ return baseFetch(url2, init);
35593
+ }
35594
+ return Promise.resolve(baseFetch(url2, { ...init, redirect: "manual" })).then((response) => followWithinOrigin(baseFetch, url2, init, response) ?? response);
35595
+ };
35596
+ }
35597
+ function unfollowedRedirect(response, requestUrl) {
35598
+ if (response.type === "opaqueredirect") {
35599
+ return "Redirect not followed: this runtime does not expose the redirect target";
35600
+ }
35601
+ const from = response.url || requestUrl;
35602
+ const target = redirectTarget(response, from);
35603
+ if (!target) {
35604
+ return void 0;
35605
+ }
35606
+ target.username = target.password = target.search = target.hash = "";
35607
+ if (target.protocol === "http:" && new URL(from).protocol === "https:") {
35608
+ target.protocol = "https:";
35609
+ return `Redirect to plain http not followed; try ${target.href} instead`;
35610
+ }
35611
+ return `Redirect to ${target.href} not followed`;
35612
+ }
35340
35613
 
35341
35614
  // ../../node_modules/pkce-challenge/dist/index.node.js
35342
35615
  var crypto;
@@ -35351,8 +35624,8 @@ async function random(size) {
35351
35624
  const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
35352
35625
  let result = "";
35353
35626
  while (result.length < size) {
35354
- const randomBytes = await getRandomValues(size - result.length);
35355
- for (const randomByte of randomBytes) {
35627
+ const randomBytes2 = await getRandomValues(size - result.length);
35628
+ for (const randomByte of randomBytes2) {
35356
35629
  if (randomByte < evenDistCutoff) {
35357
35630
  result += mask[randomByte % mask.length];
35358
35631
  }
@@ -35483,7 +35756,12 @@ var OAuthTokensSchema = object({
35483
35756
  token_type: string(),
35484
35757
  expires_in: coerce_exports.number().optional(),
35485
35758
  scope: string().optional(),
35486
- refresh_token: string().optional()
35759
+ refresh_token: string().optional(),
35760
+ /**
35761
+ * Not part of the wire format: the authorization server this value was obtained from, added by
35762
+ * the client's `auth()` before it is stored and compared when it is read back.
35763
+ */
35764
+ issuer: string().optional().catch(void 0)
35487
35765
  }).strip();
35488
35766
  var OAuthErrorResponseSchema = object({
35489
35767
  error: string(),
@@ -35513,7 +35791,12 @@ var OAuthClientInformationSchema = object({
35513
35791
  client_id: string(),
35514
35792
  client_secret: string().optional(),
35515
35793
  client_id_issued_at: number().optional(),
35516
- client_secret_expires_at: number().optional()
35794
+ client_secret_expires_at: number().optional(),
35795
+ /**
35796
+ * Not part of the wire format: the authorization server this value was obtained from, added by
35797
+ * the client's `auth()` before it is stored and compared when it is read back.
35798
+ */
35799
+ issuer: string().optional().catch(void 0)
35517
35800
  }).strip();
35518
35801
  var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
35519
35802
  var OAuthClientRegistrationErrorSchema = object({
@@ -35711,10 +35994,31 @@ async function parseErrorResponse(input) {
35711
35994
  const errorClass = OAUTH_ERRORS[error] || ServerError;
35712
35995
  return new errorClass(error_description || "", error_uri);
35713
35996
  } catch (error) {
35714
- const errorMessage2 = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
35997
+ const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
35998
+ const errorMessage2 = `${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error}. Raw body: ${body}`}`;
35715
35999
  return new ServerError(errorMessage2);
35716
36000
  }
35717
36001
  }
36002
+ function issuersMatch(a, b) {
36003
+ let [x, y] = [a, b];
36004
+ try {
36005
+ [x, y] = [new URL(a).href, new URL(b).href];
36006
+ } catch {
36007
+ }
36008
+ return x === y || x.endsWith("/") && x.slice(0, -1) === y || y.endsWith("/") && y.slice(0, -1) === x;
36009
+ }
36010
+ function discardIfIssuerMismatch(stored, issuer) {
36011
+ if (!stored)
36012
+ return void 0;
36013
+ if (typeof stored.issuer !== "string")
36014
+ return stored.issuer == null ? stored : { ...stored, issuer: void 0 };
36015
+ return issuersMatch(stored.issuer, issuer) ? stored : void 0;
36016
+ }
36017
+ var TokenResponseSchema = OAuthTokensSchema.omit({ issuer: true });
36018
+ var RegistrationResponseSchema = OAuthClientInformationFullSchema.omit({ issuer: true });
36019
+ function boundElsewhereError(stored, issuer) {
36020
+ return new Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`);
36021
+ }
35718
36022
  async function auth(provider, options) {
35719
36023
  try {
35720
36024
  return await authInternal(provider, options);
@@ -35768,9 +36072,24 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
35768
36072
  authorizationServerMetadata: metadata
35769
36073
  });
35770
36074
  }
35771
- const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
36075
+ const issuer = String(authorizationServerUrl);
36076
+ const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);
36077
+ const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;
35772
36078
  const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
35773
- let clientInformation = await Promise.resolve(provider.clientInformation());
36079
+ const storedClientInformation = await Promise.resolve(provider.clientInformation());
36080
+ let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer);
36081
+ const canRegisterAgain = provider.saveClientInformation !== void 0 && !!provider.redirectUrl;
36082
+ if (storedClientInformation && !clientInformation && !canRegisterAgain) {
36083
+ throw boundElsewhereError(storedClientInformation, issuer);
36084
+ }
36085
+ const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : void 0;
36086
+ const bindClientInformation = async () => {
36087
+ try {
36088
+ if (unstampedClientInformation)
36089
+ await provider.saveClientInformation?.({ ...unstampedClientInformation, issuer });
36090
+ } catch {
36091
+ }
36092
+ };
35774
36093
  if (!clientInformation) {
35775
36094
  if (authorizationCode !== void 0) {
35776
36095
  throw new Error("Existing OAuth client information is required when exchanging an authorization code");
@@ -35782,9 +36101,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
35782
36101
  }
35783
36102
  const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
35784
36103
  if (shouldUseUrlBasedClientId) {
35785
- clientInformation = {
35786
- client_id: clientMetadataUrl
35787
- };
36104
+ clientInformation = { client_id: clientMetadataUrl, issuer };
35788
36105
  await provider.saveClientInformation?.(clientInformation);
35789
36106
  } else {
35790
36107
  if (!provider.saveClientInformation) {
@@ -35796,8 +36113,8 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
35796
36113
  scope: resolvedScope,
35797
36114
  fetchFn
35798
36115
  });
35799
- await provider.saveClientInformation(fullInformation);
35800
- clientInformation = fullInformation;
36116
+ clientInformation = { ...fullInformation, issuer };
36117
+ await provider.saveClientInformation(clientInformation);
35801
36118
  }
35802
36119
  }
35803
36120
  const nonInteractiveFlow = !provider.redirectUrl;
@@ -35808,10 +36125,14 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
35808
36125
  authorizationCode,
35809
36126
  fetchFn
35810
36127
  });
35811
- await provider.saveTokens(tokens2);
36128
+ await bindClientInformation();
36129
+ await provider.saveTokens({ ...tokens2, issuer });
35812
36130
  return "AUTHORIZED";
35813
36131
  }
35814
- const tokens = await provider.tokens();
36132
+ const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);
36133
+ if (tokens?.refresh_token && tokens.issuer == null) {
36134
+ console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.");
36135
+ }
35815
36136
  if (tokens?.refresh_token) {
35816
36137
  try {
35817
36138
  const newTokens = await refreshAuthorization(authorizationServerUrl, {
@@ -35822,7 +36143,8 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
35822
36143
  addClientAuthentication: provider.addClientAuthentication,
35823
36144
  fetchFn
35824
36145
  });
35825
- await provider.saveTokens(newTokens);
36146
+ await bindClientInformation();
36147
+ await provider.saveTokens({ ...newTokens, issuer });
35826
36148
  return "AUTHORIZED";
35827
36149
  } catch (error) {
35828
36150
  if (!(error instanceof OAuthError) || error instanceof ServerError) {
@@ -35921,7 +36243,7 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
35921
36243
  }
35922
36244
  async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
35923
36245
  try {
35924
- return await fetchFn(url2, { headers });
36246
+ return await fetchWithinOrigin(fetchFn)(url2, { headers });
35925
36247
  } catch (error) {
35926
36248
  if (error instanceof TypeError) {
35927
36249
  if (headers) {
@@ -35946,7 +36268,7 @@ async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
35946
36268
  return await fetchWithCorsRetry(url2, headers, fetchFn);
35947
36269
  }
35948
36270
  function shouldAttemptFallback(response, pathname) {
35949
- return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
36271
+ return !response || !response.ok && response.status < 500 && pathname !== "/";
35950
36272
  }
35951
36273
  async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
35952
36274
  const issuer = new URL(serverUrl);
@@ -36012,7 +36334,7 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fet
36012
36334
  }
36013
36335
  if (!response.ok) {
36014
36336
  await response.body?.cancel();
36015
- if (response.status >= 400 && response.status < 500) {
36337
+ if (response.status < 500) {
36016
36338
  continue;
36017
36339
  }
36018
36340
  throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
@@ -36045,6 +36367,9 @@ async function discoverOAuthServerInfo(serverUrl, opts) {
36045
36367
  resourceMetadata
36046
36368
  };
36047
36369
  }
36370
+ function resourceIndicatorToString(resource) {
36371
+ return typeof resource === "string" ? resource : resource.href;
36372
+ }
36048
36373
  async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
36049
36374
  let authorizationUrl;
36050
36375
  if (metadata) {
@@ -36076,7 +36401,7 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
36076
36401
  authorizationUrl.searchParams.append("prompt", "consent");
36077
36402
  }
36078
36403
  if (resource) {
36079
- authorizationUrl.searchParams.set("resource", resource.href);
36404
+ authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource));
36080
36405
  }
36081
36406
  return { authorizationUrl, codeVerifier };
36082
36407
  }
@@ -36095,7 +36420,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
36095
36420
  Accept: "application/json"
36096
36421
  });
36097
36422
  if (resource) {
36098
- tokenRequestParams.set("resource", resource.href);
36423
+ tokenRequestParams.set("resource", resourceIndicatorToString(resource));
36099
36424
  }
36100
36425
  if (addClientAuthentication) {
36101
36426
  await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
@@ -36104,7 +36429,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
36104
36429
  const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
36105
36430
  applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
36106
36431
  }
36107
- const response = await (fetchFn ?? fetch)(tokenUrl, {
36432
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {
36108
36433
  method: "POST",
36109
36434
  headers,
36110
36435
  body: tokenRequestParams
@@ -36112,7 +36437,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
36112
36437
  if (!response.ok) {
36113
36438
  throw await parseErrorResponse(response);
36114
36439
  }
36115
- return OAuthTokensSchema.parse(await response.json());
36440
+ return TokenResponseSchema.parse(await response.json());
36116
36441
  }
36117
36442
  async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
36118
36443
  const tokenRequestParams = new URLSearchParams({
@@ -36130,6 +36455,15 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
36130
36455
  return { refresh_token: refreshToken, ...tokens };
36131
36456
  }
36132
36457
  async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
36458
+ const readClientInformation = async () => {
36459
+ const storedClientInformation = await provider.clientInformation();
36460
+ const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));
36461
+ if (storedClientInformation && !checked) {
36462
+ throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));
36463
+ }
36464
+ return checked;
36465
+ };
36466
+ let clientInformation = await readClientInformation();
36133
36467
  const scope = provider.clientMetadata.scope;
36134
36468
  let tokenRequestParams;
36135
36469
  if (provider.prepareTokenRequest) {
@@ -36145,11 +36479,11 @@ async function fetchToken(provider, authorizationServerUrl, { metadata, resource
36145
36479
  const codeVerifier = await provider.codeVerifier();
36146
36480
  tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
36147
36481
  }
36148
- const clientInformation = await provider.clientInformation();
36482
+ clientInformation ?? (clientInformation = await readClientInformation());
36149
36483
  return executeTokenRequest(authorizationServerUrl, {
36150
36484
  metadata,
36151
36485
  tokenRequestParams,
36152
- clientInformation: clientInformation ?? void 0,
36486
+ clientInformation,
36153
36487
  addClientAuthentication: provider.addClientAuthentication,
36154
36488
  resource,
36155
36489
  fetchFn
@@ -36165,7 +36499,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
36165
36499
  } else {
36166
36500
  registrationUrl = new URL("/register", authorizationServerUrl);
36167
36501
  }
36168
- const response = await (fetchFn ?? fetch)(registrationUrl, {
36502
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {
36169
36503
  method: "POST",
36170
36504
  headers: {
36171
36505
  "Content-Type": "application/json"
@@ -36178,7 +36512,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
36178
36512
  if (!response.ok) {
36179
36513
  throw await parseErrorResponse(response);
36180
36514
  }
36181
- return OAuthClientInformationFullSchema.parse(await response.json());
36515
+ return RegistrationResponseSchema.parse(await response.json());
36182
36516
  }
36183
36517
 
36184
36518
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
@@ -36199,6 +36533,16 @@ var SSEClientTransport = class {
36199
36533
  this._authProvider = opts?.authProvider;
36200
36534
  this._fetch = opts?.fetch;
36201
36535
  this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
36536
+ this._followRedirects = opts?.redirectPolicy === "follow";
36537
+ if (this._followRedirects) {
36538
+ this._fetch = fetchLeavingRedirects(this._fetch);
36539
+ this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
36540
+ }
36541
+ }
36542
+ /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
36543
+ _unfollowedRedirect(response, url2) {
36544
+ const text = unfollowedRedirect(response, url2);
36545
+ return text && !this._followRedirects ? `${text} (redirectPolicy: 'same-origin')` : text;
36202
36546
  }
36203
36547
  async _authThenStart() {
36204
36548
  if (!this._authProvider) {
@@ -36239,7 +36583,9 @@ var SSEClientTransport = class {
36239
36583
  });
36240
36584
  }
36241
36585
  _startOrAuth() {
36242
- const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
36586
+ const baseFetch = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
36587
+ const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);
36588
+ let redirect;
36243
36589
  return new Promise((resolve, reject) => {
36244
36590
  this._eventSource = new EventSource(this._url.href, {
36245
36591
  ...this._eventSourceInit,
@@ -36250,6 +36596,7 @@ var SSEClientTransport = class {
36250
36596
  ...init,
36251
36597
  headers
36252
36598
  });
36599
+ redirect = this._unfollowedRedirect(response, url2);
36253
36600
  if (response.status === 401 && response.headers.has("www-authenticate")) {
36254
36601
  const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
36255
36602
  this._resourceMetadataUrl = resourceMetadataUrl;
@@ -36264,7 +36611,7 @@ var SSEClientTransport = class {
36264
36611
  this._authThenStart().then(resolve, reject);
36265
36612
  return;
36266
36613
  }
36267
- const error = new SseError(event.code, event.message, event);
36614
+ const error = new SseError(event.code, redirect ?? event.message, event);
36268
36615
  reject(error);
36269
36616
  this.onerror?.(error);
36270
36617
  };
@@ -36341,7 +36688,7 @@ var SSEClientTransport = class {
36341
36688
  body: JSON.stringify(message),
36342
36689
  signal: this._abortController?.signal
36343
36690
  };
36344
- const response = await (this._fetch ?? fetch)(this._endpoint, init);
36691
+ const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);
36345
36692
  if (!response.ok) {
36346
36693
  const text = await response.text().catch(() => null);
36347
36694
  if (response.status === 401 && this._authProvider) {
@@ -36359,7 +36706,7 @@ var SSEClientTransport = class {
36359
36706
  }
36360
36707
  return this.send(message);
36361
36708
  }
36362
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
36709
+ throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text}`);
36363
36710
  }
36364
36711
  await response.body?.cancel();
36365
36712
  } catch (error) {
@@ -37151,9 +37498,9 @@ function isText(value, max2) {
37151
37498
  return typeof value === "string" && !!value.trim() && [...value].length <= max2;
37152
37499
  }
37153
37500
  function parseResponse(body, query, topK) {
37154
- const invalid = () => new WebSearchError("WEB_SEARCH_INVALID_RESPONSE");
37501
+ const invalid2 = () => new WebSearchError("WEB_SEARCH_INVALID_RESPONSE");
37155
37502
  if (!isObject2(body))
37156
- throw invalid();
37503
+ throw invalid2();
37157
37504
  if (body.success === false) {
37158
37505
  const code = body.errorCode;
37159
37506
  if (code === "UNAUTHORIZED")
@@ -37171,7 +37518,7 @@ function parseResponse(body, query, topK) {
37171
37518
  throw new WebSearchError(supported.includes(code) ? code : "WEB_SEARCH_UPSTREAM_ERROR");
37172
37519
  }
37173
37520
  if (body.success !== true || !isObject2(body.data) || body.data.query !== query || !Array.isArray(body.data.items) || body.data.items.length > topK)
37174
- throw invalid();
37521
+ throw invalid2();
37175
37522
  const ids = /* @__PURE__ */ new Set();
37176
37523
  let contentLength = 0;
37177
37524
  const items = body.data.items.map((item) => {
@@ -37182,28 +37529,28 @@ function parseResponse(body, query, topK) {
37182
37529
  "snippet",
37183
37530
  "doc"
37184
37531
  ].includes(item.contentSource))
37185
- throw invalid();
37532
+ throw invalid2();
37186
37533
  if (ids.has(item.id))
37187
- throw invalid();
37534
+ throw invalid2();
37188
37535
  ids.add(item.id);
37189
37536
  contentLength += [...item.content].length;
37190
37537
  if (contentLength > 2e4)
37191
- throw invalid();
37538
+ throw invalid2();
37192
37539
  if (item.url !== void 0) {
37193
37540
  if (typeof item.url !== "string" || item.url.length > 4096)
37194
- throw invalid();
37541
+ throw invalid2();
37195
37542
  try {
37196
37543
  if (!["http:", "https:"].includes(new URL(item.url).protocol))
37197
- throw invalid();
37544
+ throw invalid2();
37198
37545
  } catch {
37199
- throw invalid();
37546
+ throw invalid2();
37200
37547
  }
37201
37548
  }
37202
37549
  if (item.channel !== void 0 && !isText(item.channel, 64))
37203
- throw invalid();
37550
+ throw invalid2();
37204
37551
  if (item.publishedAt !== void 0) {
37205
37552
  if (typeof item.publishedAt !== "string" || !Number.isFinite(Date.parse(item.publishedAt)) || new Date(item.publishedAt).toISOString() !== item.publishedAt)
37206
- throw invalid();
37553
+ throw invalid2();
37207
37554
  }
37208
37555
  return {
37209
37556
  id: item.id,
@@ -39381,6 +39728,7 @@ export {
39381
39728
  createKnowledgeTools,
39382
39729
  NoopWebSearchPort,
39383
39730
  EventObservationRegistry,
39731
+ createGatewayRunAuthorization,
39384
39732
  abortableDelay,
39385
39733
  RemoteGatewayMcpServerProvider,
39386
39734
  LinkqueKnowledgeSearchPort,