linkque-cli-v2 1.6.5 → 1.6.7

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