linkque-cli-v2 1.6.4 → 1.6.5

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 +3 -16
  2. package/linkquejs.js +631 -1015
  3. package/package.json +1 -1
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-KDHBKVSL.js → anthropic-messages-5DOLTIGP.js} +15 -14
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{azure-openai-responses-NPKMM3LF.js → azure-openai-responses-HVAVRLTK.js} +9 -7
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-JMBJJF7P.js → chunk-4XAZNSEQ.js} +5 -18
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-UZS5YLV2.js → chunk-IATVK6CO.js} +1 -1
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-J4JCPZDI.js → chunk-Q2Y6LMNC.js} +7 -5
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-RYONFGPP.js +317 -0
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-VBERH5QM.js → chunk-UTJ7DVT7.js} +133 -423
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-XOLFZ4XS.js → chunk-Y3G4J3TB.js} +1 -316
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-CO4I3RJE.js → chunk-YZLXAZFT.js} +2 -15
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{dist-TGBYXSBU.js → dist-ZPLSQEAM.js} +42 -27
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-generative-ai-KD7MXONK.js → google-generative-ai-OLT56CSV.js} +10 -8
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-vertex-TREYA472.js → google-vertex-4DBBJ7SR.js} +11 -9
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-OEOTQWE5.js → mistral-conversations-OEBGEDLQ.js} +9 -7
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-codex-responses-GEFKSNVN.js → openai-codex-responses-3KOC6KHN.js} +12 -10
  18. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-completions-TAACO6T5.js → openai-completions-HG6OJRL5.js} +15 -13
  19. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-responses-4DDTXIGI.js → openai-responses-F6V2PG3Y.js} +14 -12
  20. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +60 -181
  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 +183 -381
  24. package/vendor/linkque-agent-appwrite-integrate/dist/esm/anthropic-messages-GSYNBLMR.js +0 -17
  25. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{pi-messages-7JN3W3BC.js → pi-messages-DC4DVRAJ.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 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}))`);
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}))`);
5425
5425
  }
5426
5426
  };
5427
5427
  exports.default = def;
@@ -29313,9 +29313,7 @@ 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",
29317
- "x-linkque-runtime-mac",
29318
- "x-linkque-run-proof"
29316
+ "anthropic-api-key"
29319
29317
  ]);
29320
29318
  var REDACTED_VALUE = "ak***";
29321
29319
  var RESPONSE_CORRELATION_HEADER_NAMES = [
@@ -29770,20 +29768,20 @@ function toWebSearchFailure(error) {
29770
29768
  return { code: safe.code, message: safe.message, retryable: safe.retryable };
29771
29769
  }
29772
29770
  function parseWebSearchArgs(args) {
29773
- const invalid2 = () => new WebSearchError("WEB_SEARCH_INVALID_ARGS");
29771
+ const invalid = () => new WebSearchError("WEB_SEARCH_INVALID_ARGS");
29774
29772
  if (!args || typeof args !== "object" || Array.isArray(args))
29775
- throw invalid2();
29773
+ throw invalid();
29776
29774
  const value = args;
29777
29775
  if (Object.keys(value).some((key) => key !== "query" && key !== "topK"))
29778
- throw invalid2();
29776
+ throw invalid();
29779
29777
  if (typeof value.query !== "string")
29780
- throw invalid2();
29778
+ throw invalid();
29781
29779
  const query = value.query.trim();
29782
29780
  if (!query || [...query].length > WEB_SEARCH_QUERY_MAX_LENGTH)
29783
- throw invalid2();
29781
+ throw invalid();
29784
29782
  const topK = value.topK;
29785
29783
  if (topK !== void 0 && (typeof topK !== "number" || !Number.isInteger(topK) || topK < 1 || topK > WEB_SEARCH_TOP_K_MAX))
29786
- throw invalid2();
29784
+ throw invalid();
29787
29785
  return { query, ...topK !== void 0 ? { topK } : {} };
29788
29786
  }
29789
29787
  function throwIfWebSearchAborted(signal) {
@@ -29810,6 +29808,41 @@ function resolveWebSearchResource(resources) {
29810
29808
  };
29811
29809
  }
29812
29810
 
29811
+ // ../linkque-agent-runtime/dist/esm/core/webSearchPresentation.js
29812
+ function projectWebSearchSources(result) {
29813
+ if (!isRecord2(result))
29814
+ return void 0;
29815
+ const value = result;
29816
+ if (value.error || typeof value.query !== "string" || !Array.isArray(value.items))
29817
+ return void 0;
29818
+ const items = value.items.slice(0, 10).flatMap((item) => {
29819
+ if (!isRecord2(item) || typeof item.id !== "string" || !item.id.trim() || typeof item.title !== "string" || !item.title.trim() || typeof item.content !== "string")
29820
+ return [];
29821
+ let url2;
29822
+ if (typeof item.url === "string") {
29823
+ try {
29824
+ const parsed = new URL(item.url);
29825
+ if (["http:", "https:"].includes(parsed.protocol) && !parsed.username && !parsed.password)
29826
+ url2 = parsed.href;
29827
+ } catch {
29828
+ }
29829
+ }
29830
+ return [
29831
+ {
29832
+ id: item.id.slice(0, 256),
29833
+ title: item.title.slice(0, 256),
29834
+ content: item.content.slice(0, 4e3),
29835
+ ...url2 ? { url: url2 } : {},
29836
+ ...typeof item.channel === "string" ? { channel: item.channel.slice(0, 64) } : {}
29837
+ }
29838
+ ];
29839
+ });
29840
+ return items.length ? { query: value.query.slice(0, 2048), items } : void 0;
29841
+ }
29842
+ function isRecord2(value) {
29843
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
29844
+ }
29845
+
29813
29846
  // ../linkque-agent-runtime/dist/esm/core/createWebSearchTool.js
29814
29847
  function createWebSearchTool(resource, searchPort, agentId, debugLog) {
29815
29848
  return {
@@ -29846,6 +29879,15 @@ function createWebSearchTool(resource, searchPort, agentId, debugLog) {
29846
29879
  const result = await waitWithSignal(() => searchPort.search({ agentId, ...parsed }, signal, context2?.observation), signal);
29847
29880
  throwIfWebSearchAborted(signal);
29848
29881
  count = result.items.length;
29882
+ const presentation = context2 ? projectWebSearchSources(result) : void 0;
29883
+ if (context2 && presentation) {
29884
+ context2.emit({
29885
+ type: "tool_result",
29886
+ toolCallId: context2.toolCallId,
29887
+ messageId: `${context2.toolCallId}:web-search-result`,
29888
+ content: JSON.stringify(presentation)
29889
+ });
29890
+ }
29849
29891
  return result;
29850
29892
  } catch (error) {
29851
29893
  if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
@@ -30077,7 +30119,7 @@ var ConversationControlValidationError = class extends Error {
30077
30119
  };
30078
30120
  function parseCancelConversationRunRequest(value) {
30079
30121
  const issues = [];
30080
- if (!isRecord2(value)) {
30122
+ if (!isRecord3(value)) {
30081
30123
  throw new ConversationControlValidationError([
30082
30124
  "control request must be an object"
30083
30125
  ]);
@@ -30097,7 +30139,7 @@ function parseCancelConversationRunRequest(value) {
30097
30139
  }
30098
30140
  function parseMarkConversationRunsReadRequest(value) {
30099
30141
  const issues = [];
30100
- if (!isRecord2(value)) {
30142
+ if (!isRecord3(value)) {
30101
30143
  throw new ConversationControlValidationError([
30102
30144
  "control request must be an object"
30103
30145
  ]);
@@ -30131,7 +30173,7 @@ function parseMarkConversationRunsReadRequest(value) {
30131
30173
  function isNonEmptyString(value) {
30132
30174
  return typeof value === "string" && Boolean(value.trim());
30133
30175
  }
30134
- function isRecord2(value) {
30176
+ function isRecord3(value) {
30135
30177
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
30136
30178
  }
30137
30179
 
@@ -30767,12 +30809,12 @@ var CONVERSATION_CUSTOM_EVENT_NAMES = Object.freeze({
30767
30809
  var MAX_CONVERSATION_FOLLOW_UP_QUESTIONS = 3;
30768
30810
  var MAX_CONVERSATION_FOLLOW_UP_QUESTION_LENGTH = 20;
30769
30811
  function parseConversationFollowUpQuestions(value) {
30770
- if (!isRecord3(value) || !Array.isArray(value.questions))
30812
+ if (!isRecord4(value) || !Array.isArray(value.questions))
30771
30813
  return void 0;
30772
30814
  const seen = /* @__PURE__ */ new Set();
30773
30815
  const questions = [];
30774
30816
  for (const candidate of value.questions) {
30775
- if (!isRecord3(candidate))
30817
+ if (!isRecord4(candidate))
30776
30818
  continue;
30777
30819
  const label = normalizeFollowUpText(candidate.label);
30778
30820
  const prompt = normalizeFollowUpText(candidate.prompt);
@@ -30797,7 +30839,7 @@ function normalizeFollowUpText(value) {
30797
30839
  const normalized = value.replace(/\s+/gu, " ").trim();
30798
30840
  return normalized || void 0;
30799
30841
  }
30800
- function isRecord3(value) {
30842
+ function isRecord4(value) {
30801
30843
  return typeof value === "object" && value !== null && !Array.isArray(value);
30802
30844
  }
30803
30845
  function createConversationCustomEvent(name, value, fields = {}) {
@@ -30826,7 +30868,7 @@ function parseConversationRunRequest(value) {
30826
30868
  return value;
30827
30869
  }
30828
30870
  function getConversationRunRequestIssues(value) {
30829
- if (!isRecord4(value))
30871
+ if (!isRecord5(value))
30830
30872
  return ["request must be an object"];
30831
30873
  const issues = [];
30832
30874
  if (!isSupportedConversationProtocolVersion(value.protocolVersion)) {
@@ -30849,7 +30891,7 @@ function getConversationRunRequestIssues(value) {
30849
30891
  } else {
30850
30892
  value.attachments.forEach((attachment, index) => validateAttachment(attachment, index, issues));
30851
30893
  }
30852
- if (!isRecord4(value.metadata))
30894
+ if (!isRecord5(value.metadata))
30853
30895
  issues.push("metadata must be an object");
30854
30896
  if (value.clientCapabilities !== void 0) {
30855
30897
  if (!Array.isArray(value.clientCapabilities)) {
@@ -30867,7 +30909,7 @@ function getConversationRunRequestIssues(value) {
30867
30909
  return issues;
30868
30910
  }
30869
30911
  function validateMessage(value, index, issues) {
30870
- if (!isRecord4(value)) {
30912
+ if (!isRecord5(value)) {
30871
30913
  issues.push(`messages[${index}] must be an object`);
30872
30914
  return;
30873
30915
  }
@@ -30878,7 +30920,7 @@ function validateMessage(value, index, issues) {
30878
30920
  }
30879
30921
  if (value.content !== void 0) {
30880
30922
  if (typeof value.content === "string") {
30881
- } else if (isRecord4(value.content) && value.content.type === "a2ui.event") {
30923
+ } else if (isRecord5(value.content) && value.content.type === "a2ui.event") {
30882
30924
  if (value.role !== "user") {
30883
30925
  issues.push(`messages[${index}].content a2ui.event requires the user role`);
30884
30926
  }
@@ -30902,21 +30944,21 @@ function validateA2UIEventContent(value, path2, issues) {
30902
30944
  validateA2UIEventSource(value.source, `${path2}.source`, issues);
30903
30945
  }
30904
30946
  function validateA2UIEvent(value, path2, issues) {
30905
- if (!isRecord4(value)) {
30947
+ if (!isRecord5(value)) {
30906
30948
  issues.push(`${path2} must be an object`);
30907
30949
  return;
30908
30950
  }
30909
30951
  if (!isSafeEventName(value.name)) {
30910
30952
  issues.push(`${path2}.name must be a safe event name up to 96 characters`);
30911
30953
  }
30912
- if (!isRecord4(value.payload)) {
30954
+ if (!isRecord5(value.payload)) {
30913
30955
  issues.push(`${path2}.payload must be an object`);
30914
30956
  return;
30915
30957
  }
30916
30958
  validateJsonValue(value.payload, `${path2}.payload`, issues);
30917
30959
  }
30918
30960
  function validateA2UIEventSource(value, path2, issues) {
30919
- if (!isRecord4(value)) {
30961
+ if (!isRecord5(value)) {
30920
30962
  issues.push(`${path2} must be an object`);
30921
30963
  return;
30922
30964
  }
@@ -30957,7 +30999,7 @@ function validateJsonValue(value, path2, issues) {
30957
30999
  value.forEach((entry, index) => validateJsonValue(entry, `${path2}[${index}]`, issues));
30958
31000
  return;
30959
31001
  }
30960
- if (!isRecord4(value)) {
31002
+ if (!isRecord5(value)) {
30961
31003
  issues.push(`${path2} must be JSON-safe`);
30962
31004
  return;
30963
31005
  }
@@ -30970,7 +31012,7 @@ function validateJsonValue(value, path2, issues) {
30970
31012
  }
30971
31013
  }
30972
31014
  function validateAttachment(value, index, issues) {
30973
- if (!isRecord4(value)) {
31015
+ if (!isRecord5(value)) {
30974
31016
  issues.push(`attachments[${index}] must be an object`);
30975
31017
  return;
30976
31018
  }
@@ -30988,11 +31030,11 @@ function validateAttachment(value, index, issues) {
30988
31030
  if (value.size !== void 0 && (!Number.isSafeInteger(value.size) || Number(value.size) < 0)) {
30989
31031
  issues.push(`attachments[${index}].size must be a non-negative safe integer when provided`);
30990
31032
  }
30991
- if (value.metadata !== void 0 && !isRecord4(value.metadata)) {
31033
+ if (value.metadata !== void 0 && !isRecord5(value.metadata)) {
30992
31034
  issues.push(`attachments[${index}].metadata must be an object when provided`);
30993
31035
  }
30994
31036
  }
30995
- function isRecord4(value) {
31037
+ function isRecord5(value) {
30996
31038
  return typeof value === "object" && value !== null && !Array.isArray(value);
30997
31039
  }
30998
31040
  function isNonEmptyString2(value) {
@@ -31034,7 +31076,7 @@ function parseConversationHistoryRequest(value) {
31034
31076
  return value;
31035
31077
  }
31036
31078
  function getConversationHistoryRequestIssues(value) {
31037
- if (!isRecord5(value))
31079
+ if (!isRecord6(value))
31038
31080
  return ["history request must be an object"];
31039
31081
  const issues = [];
31040
31082
  if (!isSupportedConversationProtocolVersion(value.protocolVersion)) {
@@ -31132,7 +31174,7 @@ var HISTORY_OPERATIONS = /* @__PURE__ */ new Set([
31132
31174
  function isNonEmptyString3(value) {
31133
31175
  return typeof value === "string" && Boolean(value.trim());
31134
31176
  }
31135
- function isRecord5(value) {
31177
+ function isRecord6(value) {
31136
31178
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
31137
31179
  }
31138
31180
 
@@ -31202,189 +31244,6 @@ function encodeConversationSseEvent(event) {
31202
31244
  `;
31203
31245
  }
31204
31246
 
31205
- // ../linkque-agent-runtime/dist/esm/impl/scenario/gatewayRunAuthorization.js
31206
- import { hkdfSync, randomBytes } from "node:crypto";
31207
-
31208
- // ../linkque-agent-runtime/dist/esm/impl/scenario/runtimeMac.js
31209
- import { createHash as createHash3, createHmac, timingSafeEqual } from "node:crypto";
31210
- function invalid() {
31211
- throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
31212
- }
31213
- function canonicalJson(value, depth = 0) {
31214
- if (depth > 64)
31215
- invalid();
31216
- if (value === null || typeof value === "string" || typeof value === "boolean")
31217
- return JSON.stringify(value);
31218
- if (typeof value === "number" && Number.isFinite(value))
31219
- return JSON.stringify(value);
31220
- if (Array.isArray(value))
31221
- return `[${value.map((v) => canonicalJson(v, depth + 1)).join(",")}]`;
31222
- if (value && typeof value === "object" && Object.prototype.toString.call(value) === "[object Object]") {
31223
- return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k], depth + 1)}`).join(",")}}`;
31224
- }
31225
- return invalid();
31226
- }
31227
- function signRuntimeRequest(input, key) {
31228
- 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)
31229
- invalid();
31230
- const sha256 = (value) => createHash3("sha256").update(value).digest("hex");
31231
- const body = canonicalJson(input.body);
31232
- if (Buffer.byteLength(body) > 4 * 1024 * 1024)
31233
- invalid();
31234
- const payload = JSON.stringify([
31235
- "linkque-runtime-request-v1",
31236
- input.caller,
31237
- input.keyId,
31238
- input.timestamp,
31239
- input.nonce,
31240
- input.method,
31241
- input.path,
31242
- sha256(body),
31243
- sha256(input.token),
31244
- sha256(input.proof),
31245
- input.runId,
31246
- input.appbaseUserId
31247
- ]);
31248
- return createHmac("sha256", key).update(payload).digest("base64url");
31249
- }
31250
-
31251
- // ../linkque-agent-runtime/dist/esm/impl/scenario/gatewayRunAuthorization.js
31252
- var SCENARIO_RUNTIME_CALLER = "appbase-agent-function";
31253
- var SCENARIO_RUNTIME_KEY_ID = "agent-aak-v1";
31254
- function deriveScenarioRuntimeMacKey(accessKey) {
31255
- const normalized = accessKey.trim();
31256
- if (!normalized)
31257
- throw new Error("SCENARIO_RUN_UNAVAILABLE");
31258
- return Buffer.from(hkdfSync("sha256", Buffer.from(normalized, "utf8"), "linkque-scenario-agent-aak-v1", "linkque:scenario:runtime-mac:v1", 32));
31259
- }
31260
- function createGatewayRunAuthorization(options) {
31261
- const base = new URL(options.baseUrl);
31262
- const key = deriveScenarioRuntimeMacKey(options.accessKey);
31263
- if (base.protocol !== "https:" || base.username || base.password || base.search || base.hash) {
31264
- throw new Error("SCENARIO_RUN_UNAVAILABLE");
31265
- }
31266
- const modelPath = `${base.pathname.replace(/\/$/u, "")}/v1/messages`;
31267
- const baseFetch = options.fetch ?? globalThis.fetch;
31268
- return {
31269
- async authorizeRun(identity) {
31270
- const signedHeaders = (url2, body, proof) => {
31271
- const timestamp = Date.now();
31272
- const nonce = randomBytes(16).toString("hex");
31273
- const mac = signRuntimeRequest({
31274
- ...identity,
31275
- caller: SCENARIO_RUNTIME_CALLER,
31276
- keyId: SCENARIO_RUNTIME_KEY_ID,
31277
- timestamp,
31278
- nonce,
31279
- method: "POST",
31280
- path: url2.pathname + url2.search,
31281
- token: options.token,
31282
- proof,
31283
- body
31284
- }, key);
31285
- return {
31286
- "x-linkque-runtime-caller": SCENARIO_RUNTIME_CALLER,
31287
- "x-linkque-runtime-key-id": SCENARIO_RUNTIME_KEY_ID,
31288
- "x-linkque-runtime-timestamp": String(timestamp),
31289
- "x-linkque-runtime-nonce": nonce,
31290
- "x-linkque-runtime-user-id": identity.appbaseUserId,
31291
- "x-linkque-runtime-mac": mac
31292
- };
31293
- };
31294
- const invoke = async (path2, previousProof) => {
31295
- const url2 = new URL(path2, base.origin);
31296
- const body = {
31297
- agentId: identity.agentId,
31298
- runId: identity.runId,
31299
- ...previousProof ? { proof: previousProof } : {}
31300
- };
31301
- let response;
31302
- try {
31303
- response = await baseFetch(url2, {
31304
- method: "POST",
31305
- redirect: "error",
31306
- signal: AbortSignal.timeout(5e3),
31307
- headers: {
31308
- authorization: `Bearer ${options.token}`,
31309
- "content-type": "application/json",
31310
- ...signedHeaders(url2, body, previousProof ?? "")
31311
- },
31312
- body: JSON.stringify(body)
31313
- });
31314
- } catch {
31315
- throw new Error("SCENARIO_RUN_UNAVAILABLE");
31316
- }
31317
- if (!response.ok)
31318
- throw new Error("SCENARIO_RUN_UNAVAILABLE");
31319
- const raw = await response.text();
31320
- if (raw.length > 16384)
31321
- throw new Error("SCENARIO_RUN_UNAVAILABLE");
31322
- let result;
31323
- try {
31324
- result = JSON.parse(raw);
31325
- } catch {
31326
- throw new Error("SCENARIO_RUN_UNAVAILABLE");
31327
- }
31328
- if (result?.success !== true) {
31329
- throw new Error([
31330
- "SCENARIO_TURN_LIMIT",
31331
- "SCENARIO_RUNTIME_AUTH_INVALID",
31332
- "SCENARIO_RUNTIME_REPLAY"
31333
- ].includes(result?.errorCode) ? result.errorCode : "SCENARIO_RUN_UNAVAILABLE");
31334
- }
31335
- const data = result.data;
31336
- if (data?.quotaMode === "NORMAL" && !previousProof)
31337
- return { quotaMode: "NORMAL" };
31338
- 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())
31339
- throw new Error("SCENARIO_RUN_UNAVAILABLE");
31340
- return data;
31341
- };
31342
- let grant = await invoke("/api/scenario/authorize-run");
31343
- if (grant.quotaMode === "NORMAL")
31344
- return { quotaMode: "NORMAL" };
31345
- const quotaMode = grant.quotaMode;
31346
- let renewing;
31347
- const requireProof = async () => {
31348
- if (grant.expiresAt - Date.now() > 15e3)
31349
- return;
31350
- renewing ??= invoke("/api/scenario/renew-run", grant.proof).then((next) => {
31351
- if (next.quotaMode !== quotaMode)
31352
- throw new Error("SCENARIO_RUN_UNAVAILABLE");
31353
- grant = next;
31354
- }).finally(() => {
31355
- renewing = void 0;
31356
- });
31357
- await renewing;
31358
- };
31359
- const modelFetch = async (input, init) => {
31360
- const request = new Request(input, init);
31361
- const url2 = new URL(request.url);
31362
- if (request.method !== "POST" || url2.origin !== base.origin || url2.pathname !== modelPath || url2.search || url2.hash || request.headers.get("x-api-key") !== options.token)
31363
- throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
31364
- const raw = await request.text();
31365
- if (Buffer.byteLength(raw) > 4 * 1024 * 1024)
31366
- throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
31367
- const body = JSON.parse(raw);
31368
- await requireProof();
31369
- const headers = new Headers(request.headers);
31370
- headers.set("x-linkque-run-proof", grant.proof);
31371
- headers.set("x-run-id", identity.runId);
31372
- headers.set("x-agent-id", identity.agentId);
31373
- for (const [headerName, value] of Object.entries(signedHeaders(url2, body, grant.proof)))
31374
- headers.set(headerName, value);
31375
- return baseFetch(request.url, {
31376
- method: "POST",
31377
- headers,
31378
- body: raw,
31379
- signal: request.signal,
31380
- redirect: "error"
31381
- });
31382
- };
31383
- return { quotaMode, modelFetch };
31384
- }
31385
- };
31386
- }
31387
-
31388
31247
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
31389
31248
  function isZ4Schema(s) {
31390
31249
  const schema = s;
@@ -33034,9 +32893,6 @@ var Protocol = class {
33034
32893
  this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
33035
32894
  const handleTaskResult = async () => {
33036
32895
  const taskId = request.params.taskId;
33037
- if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
33038
- throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
33039
- }
33040
32896
  if (this._taskMessageQueue) {
33041
32897
  let queuedMessage;
33042
32898
  while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
@@ -33067,12 +32923,12 @@ var Protocol = class {
33067
32923
  throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
33068
32924
  }
33069
32925
  if (!isTerminal(task.status)) {
33070
- await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
32926
+ await this._waitForTaskUpdate(taskId, extra.signal);
33071
32927
  return await handleTaskResult();
33072
32928
  }
33073
32929
  if (isTerminal(task.status)) {
33074
32930
  const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
33075
- this._clearTaskQueue(taskId, extra.sessionId);
32931
+ this._clearTaskQueue(taskId);
33076
32932
  return {
33077
32933
  ...result,
33078
32934
  _meta: {
@@ -33109,7 +32965,7 @@ var Protocol = class {
33109
32965
  throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
33110
32966
  }
33111
32967
  await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
33112
- this._clearTaskQueue(request.params.taskId, extra.sessionId);
32968
+ this._clearTaskQueue(request.params.taskId);
33113
32969
  const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
33114
32970
  if (!cancelledTask) {
33115
32971
  throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
@@ -33237,19 +33093,6 @@ var Protocol = class {
33237
33093
  const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
33238
33094
  const capturedTransport = this._transport;
33239
33095
  const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
33240
- const sessionId = capturedTransport?.sessionId;
33241
- const store = this._taskStore;
33242
- let relatedTaskFound = true;
33243
- let relatedTaskLookup;
33244
- if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) {
33245
- relatedTaskFound = false;
33246
- relatedTaskLookup = (async () => {
33247
- if (!await store.getTask(relatedTaskId, sessionId)) {
33248
- throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
33249
- }
33250
- relatedTaskFound = true;
33251
- })();
33252
- }
33253
33096
  if (handler === void 0) {
33254
33097
  const errorResponse = {
33255
33098
  jsonrpc: "2.0",
@@ -33259,10 +33102,7 @@ var Protocol = class {
33259
33102
  message: "Method not found"
33260
33103
  }
33261
33104
  };
33262
- if (relatedTaskId && relatedTaskLookup) {
33263
- const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
33264
- relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
33265
- } else if (relatedTaskId && this._taskMessageQueue) {
33105
+ if (relatedTaskId && this._taskMessageQueue) {
33266
33106
  this._enqueueTaskMessage(relatedTaskId, {
33267
33107
  type: "error",
33268
33108
  message: errorResponse,
@@ -33313,10 +33153,7 @@ var Protocol = class {
33313
33153
  closeSSEStream: extra?.closeSSEStream,
33314
33154
  closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
33315
33155
  };
33316
- (relatedTaskLookup ?? Promise.resolve()).then(() => {
33317
- if (relatedTaskLookup && abortController.signal.aborted) {
33318
- throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
33319
- }
33156
+ Promise.resolve().then(() => {
33320
33157
  if (taskCreationParams) {
33321
33158
  this.assertTaskHandlerCapability(request.method);
33322
33159
  }
@@ -33351,7 +33188,7 @@ var Protocol = class {
33351
33188
  ...error["data"] !== void 0 && { data: error["data"] }
33352
33189
  }
33353
33190
  };
33354
- if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
33191
+ if (relatedTaskId && this._taskMessageQueue) {
33355
33192
  await this._enqueueTaskMessage(relatedTaskId, {
33356
33193
  type: "error",
33357
33194
  message: errorResponse,
@@ -33831,7 +33668,7 @@ var Protocol = class {
33831
33668
  throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
33832
33669
  }
33833
33670
  const maxQueueSize = this._options?.maxTaskQueueSize;
33834
- await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
33671
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
33835
33672
  }
33836
33673
  /**
33837
33674
  * Clears the message queue for a task and rejects any pending request resolvers.
@@ -33860,13 +33697,12 @@ var Protocol = class {
33860
33697
  * Uses polling to check for updates at the task's configured poll interval.
33861
33698
  * @param taskId The task ID to wait for
33862
33699
  * @param signal Abort signal to cancel the wait
33863
- * @param sessionId Session of the request that waits, passed to the task store
33864
33700
  * @returns Promise that resolves when an update occurs or rejects if aborted
33865
33701
  */
33866
- async _waitForTaskUpdate(taskId, signal, sessionId) {
33702
+ async _waitForTaskUpdate(taskId, signal) {
33867
33703
  let interval = this._options?.defaultTaskPollInterval ?? 1e3;
33868
33704
  try {
33869
- const task = await this._taskStore?.getTask(taskId, sessionId);
33705
+ const task = await this._taskStore?.getTask(taskId);
33870
33706
  if (task?.pollInterval) {
33871
33707
  interval = task.pollInterval;
33872
33708
  }
@@ -35501,68 +35337,6 @@ function createFetchWithInit(baseFetch = fetch, baseInit) {
35501
35337
  return baseFetch(url2, mergedInit);
35502
35338
  };
35503
35339
  }
35504
- var MAX_REDIRECTS = 5;
35505
- var REDIRECT_STATUSES = [301, 302, 303, 307, 308];
35506
- function isWithinOrigin(from, to) {
35507
- if (from.protocol === to.protocol && from.hostname === to.hostname && from.port === to.port) {
35508
- return true;
35509
- }
35510
- return from.hostname === to.hostname && from.protocol === "http:" && from.port === "" && to.protocol === "https:" && to.port === "";
35511
- }
35512
- function redirectTarget(response, requestUrl) {
35513
- const location = REDIRECT_STATUSES.includes(response.status) ? response.headers.get("location") : null;
35514
- try {
35515
- return location ? new URL(location, requestUrl) : void 0;
35516
- } catch {
35517
- return void 0;
35518
- }
35519
- }
35520
- function followWithinOrigin(baseFetch, url2, init, response, followed = 0) {
35521
- const target = redirectTarget(response, url2);
35522
- const keepsMethod = response.status === 307 || response.status === 308 || (init?.method ?? "GET").toUpperCase() === "GET";
35523
- if (!target || followed === MAX_REDIRECTS || !keepsMethod) {
35524
- return void 0;
35525
- }
35526
- const from = new URL(url2);
35527
- const addsUserinfo = (target.username || target.password) && (target.username !== from.username || target.password !== from.password);
35528
- if (addsUserinfo || !isWithinOrigin(from, target)) {
35529
- return void 0;
35530
- }
35531
- return Promise.resolve(response.body?.cancel()).then(() => baseFetch(target, { ...init, redirect: "manual" })).then((next) => followWithinOrigin(baseFetch, target, init, next, followed + 1) ?? next);
35532
- }
35533
- var followingFetches = /* @__PURE__ */ new WeakSet();
35534
- function fetchLeavingRedirects(baseFetch) {
35535
- const following = (url2, init) => (baseFetch ?? fetch)(url2, init);
35536
- followingFetches.add(following);
35537
- return following;
35538
- }
35539
- function fetchWithinOrigin(baseFetch = fetch) {
35540
- if (followingFetches.has(baseFetch)) {
35541
- return baseFetch;
35542
- }
35543
- return (url2, init) => {
35544
- if (init?.redirect === "error" || init?.redirect === "manual") {
35545
- return baseFetch(url2, init);
35546
- }
35547
- return Promise.resolve(baseFetch(url2, { ...init, redirect: "manual" })).then((response) => followWithinOrigin(baseFetch, url2, init, response) ?? response);
35548
- };
35549
- }
35550
- function unfollowedRedirect(response, requestUrl) {
35551
- if (response.type === "opaqueredirect") {
35552
- return "Redirect not followed: this runtime does not expose the redirect target";
35553
- }
35554
- const from = response.url || requestUrl;
35555
- const target = redirectTarget(response, from);
35556
- if (!target) {
35557
- return void 0;
35558
- }
35559
- target.username = target.password = target.search = target.hash = "";
35560
- if (target.protocol === "http:" && new URL(from).protocol === "https:") {
35561
- target.protocol = "https:";
35562
- return `Redirect to plain http not followed; try ${target.href} instead`;
35563
- }
35564
- return `Redirect to ${target.href} not followed`;
35565
- }
35566
35340
 
35567
35341
  // ../../node_modules/pkce-challenge/dist/index.node.js
35568
35342
  var crypto;
@@ -35577,8 +35351,8 @@ async function random(size) {
35577
35351
  const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
35578
35352
  let result = "";
35579
35353
  while (result.length < size) {
35580
- const randomBytes2 = await getRandomValues(size - result.length);
35581
- for (const randomByte of randomBytes2) {
35354
+ const randomBytes = await getRandomValues(size - result.length);
35355
+ for (const randomByte of randomBytes) {
35582
35356
  if (randomByte < evenDistCutoff) {
35583
35357
  result += mask[randomByte % mask.length];
35584
35358
  }
@@ -35709,12 +35483,7 @@ var OAuthTokensSchema = object({
35709
35483
  token_type: string(),
35710
35484
  expires_in: coerce_exports.number().optional(),
35711
35485
  scope: string().optional(),
35712
- refresh_token: string().optional(),
35713
- /**
35714
- * Not part of the wire format: the authorization server this value was obtained from, added by
35715
- * the client's `auth()` before it is stored and compared when it is read back.
35716
- */
35717
- issuer: string().optional().catch(void 0)
35486
+ refresh_token: string().optional()
35718
35487
  }).strip();
35719
35488
  var OAuthErrorResponseSchema = object({
35720
35489
  error: string(),
@@ -35744,12 +35513,7 @@ var OAuthClientInformationSchema = object({
35744
35513
  client_id: string(),
35745
35514
  client_secret: string().optional(),
35746
35515
  client_id_issued_at: number().optional(),
35747
- client_secret_expires_at: number().optional(),
35748
- /**
35749
- * Not part of the wire format: the authorization server this value was obtained from, added by
35750
- * the client's `auth()` before it is stored and compared when it is read back.
35751
- */
35752
- issuer: string().optional().catch(void 0)
35516
+ client_secret_expires_at: number().optional()
35753
35517
  }).strip();
35754
35518
  var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
35755
35519
  var OAuthClientRegistrationErrorSchema = object({
@@ -35947,31 +35711,10 @@ async function parseErrorResponse(input) {
35947
35711
  const errorClass = OAUTH_ERRORS[error] || ServerError;
35948
35712
  return new errorClass(error_description || "", error_uri);
35949
35713
  } catch (error) {
35950
- const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
35951
- const errorMessage2 = `${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error}. Raw body: ${body}`}`;
35714
+ const errorMessage2 = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
35952
35715
  return new ServerError(errorMessage2);
35953
35716
  }
35954
35717
  }
35955
- function issuersMatch(a, b) {
35956
- let [x, y] = [a, b];
35957
- try {
35958
- [x, y] = [new URL(a).href, new URL(b).href];
35959
- } catch {
35960
- }
35961
- return x === y || x.endsWith("/") && x.slice(0, -1) === y || y.endsWith("/") && y.slice(0, -1) === x;
35962
- }
35963
- function discardIfIssuerMismatch(stored, issuer) {
35964
- if (!stored)
35965
- return void 0;
35966
- if (typeof stored.issuer !== "string")
35967
- return stored.issuer == null ? stored : { ...stored, issuer: void 0 };
35968
- return issuersMatch(stored.issuer, issuer) ? stored : void 0;
35969
- }
35970
- var TokenResponseSchema = OAuthTokensSchema.omit({ issuer: true });
35971
- var RegistrationResponseSchema = OAuthClientInformationFullSchema.omit({ issuer: true });
35972
- function boundElsewhereError(stored, issuer) {
35973
- 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.`);
35974
- }
35975
35718
  async function auth(provider, options) {
35976
35719
  try {
35977
35720
  return await authInternal(provider, options);
@@ -36025,24 +35768,9 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
36025
35768
  authorizationServerMetadata: metadata
36026
35769
  });
36027
35770
  }
36028
- const issuer = String(authorizationServerUrl);
36029
- const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);
36030
- const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;
35771
+ const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
36031
35772
  const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
36032
- const storedClientInformation = await Promise.resolve(provider.clientInformation());
36033
- let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer);
36034
- const canRegisterAgain = provider.saveClientInformation !== void 0 && !!provider.redirectUrl;
36035
- if (storedClientInformation && !clientInformation && !canRegisterAgain) {
36036
- throw boundElsewhereError(storedClientInformation, issuer);
36037
- }
36038
- const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : void 0;
36039
- const bindClientInformation = async () => {
36040
- try {
36041
- if (unstampedClientInformation)
36042
- await provider.saveClientInformation?.({ ...unstampedClientInformation, issuer });
36043
- } catch {
36044
- }
36045
- };
35773
+ let clientInformation = await Promise.resolve(provider.clientInformation());
36046
35774
  if (!clientInformation) {
36047
35775
  if (authorizationCode !== void 0) {
36048
35776
  throw new Error("Existing OAuth client information is required when exchanging an authorization code");
@@ -36054,7 +35782,9 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
36054
35782
  }
36055
35783
  const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
36056
35784
  if (shouldUseUrlBasedClientId) {
36057
- clientInformation = { client_id: clientMetadataUrl, issuer };
35785
+ clientInformation = {
35786
+ client_id: clientMetadataUrl
35787
+ };
36058
35788
  await provider.saveClientInformation?.(clientInformation);
36059
35789
  } else {
36060
35790
  if (!provider.saveClientInformation) {
@@ -36066,8 +35796,8 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
36066
35796
  scope: resolvedScope,
36067
35797
  fetchFn
36068
35798
  });
36069
- clientInformation = { ...fullInformation, issuer };
36070
- await provider.saveClientInformation(clientInformation);
35799
+ await provider.saveClientInformation(fullInformation);
35800
+ clientInformation = fullInformation;
36071
35801
  }
36072
35802
  }
36073
35803
  const nonInteractiveFlow = !provider.redirectUrl;
@@ -36078,14 +35808,10 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
36078
35808
  authorizationCode,
36079
35809
  fetchFn
36080
35810
  });
36081
- await bindClientInformation();
36082
- await provider.saveTokens({ ...tokens2, issuer });
35811
+ await provider.saveTokens(tokens2);
36083
35812
  return "AUTHORIZED";
36084
35813
  }
36085
- const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);
36086
- if (tokens?.refresh_token && tokens.issuer == null) {
36087
- 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.");
36088
- }
35814
+ const tokens = await provider.tokens();
36089
35815
  if (tokens?.refresh_token) {
36090
35816
  try {
36091
35817
  const newTokens = await refreshAuthorization(authorizationServerUrl, {
@@ -36096,8 +35822,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
36096
35822
  addClientAuthentication: provider.addClientAuthentication,
36097
35823
  fetchFn
36098
35824
  });
36099
- await bindClientInformation();
36100
- await provider.saveTokens({ ...newTokens, issuer });
35825
+ await provider.saveTokens(newTokens);
36101
35826
  return "AUTHORIZED";
36102
35827
  } catch (error) {
36103
35828
  if (!(error instanceof OAuthError) || error instanceof ServerError) {
@@ -36196,7 +35921,7 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
36196
35921
  }
36197
35922
  async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
36198
35923
  try {
36199
- return await fetchWithinOrigin(fetchFn)(url2, { headers });
35924
+ return await fetchFn(url2, { headers });
36200
35925
  } catch (error) {
36201
35926
  if (error instanceof TypeError) {
36202
35927
  if (headers) {
@@ -36221,7 +35946,7 @@ async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
36221
35946
  return await fetchWithCorsRetry(url2, headers, fetchFn);
36222
35947
  }
36223
35948
  function shouldAttemptFallback(response, pathname) {
36224
- return !response || !response.ok && response.status < 500 && pathname !== "/";
35949
+ return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
36225
35950
  }
36226
35951
  async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
36227
35952
  const issuer = new URL(serverUrl);
@@ -36287,7 +36012,7 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fet
36287
36012
  }
36288
36013
  if (!response.ok) {
36289
36014
  await response.body?.cancel();
36290
- if (response.status < 500) {
36015
+ if (response.status >= 400 && response.status < 500) {
36291
36016
  continue;
36292
36017
  }
36293
36018
  throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
@@ -36320,9 +36045,6 @@ async function discoverOAuthServerInfo(serverUrl, opts) {
36320
36045
  resourceMetadata
36321
36046
  };
36322
36047
  }
36323
- function resourceIndicatorToString(resource) {
36324
- return typeof resource === "string" ? resource : resource.href;
36325
- }
36326
36048
  async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
36327
36049
  let authorizationUrl;
36328
36050
  if (metadata) {
@@ -36354,7 +36076,7 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
36354
36076
  authorizationUrl.searchParams.append("prompt", "consent");
36355
36077
  }
36356
36078
  if (resource) {
36357
- authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource));
36079
+ authorizationUrl.searchParams.set("resource", resource.href);
36358
36080
  }
36359
36081
  return { authorizationUrl, codeVerifier };
36360
36082
  }
@@ -36373,7 +36095,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
36373
36095
  Accept: "application/json"
36374
36096
  });
36375
36097
  if (resource) {
36376
- tokenRequestParams.set("resource", resourceIndicatorToString(resource));
36098
+ tokenRequestParams.set("resource", resource.href);
36377
36099
  }
36378
36100
  if (addClientAuthentication) {
36379
36101
  await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
@@ -36382,7 +36104,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
36382
36104
  const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
36383
36105
  applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
36384
36106
  }
36385
- const response = await fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {
36107
+ const response = await (fetchFn ?? fetch)(tokenUrl, {
36386
36108
  method: "POST",
36387
36109
  headers,
36388
36110
  body: tokenRequestParams
@@ -36390,7 +36112,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
36390
36112
  if (!response.ok) {
36391
36113
  throw await parseErrorResponse(response);
36392
36114
  }
36393
- return TokenResponseSchema.parse(await response.json());
36115
+ return OAuthTokensSchema.parse(await response.json());
36394
36116
  }
36395
36117
  async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
36396
36118
  const tokenRequestParams = new URLSearchParams({
@@ -36408,15 +36130,6 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
36408
36130
  return { refresh_token: refreshToken, ...tokens };
36409
36131
  }
36410
36132
  async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
36411
- const readClientInformation = async () => {
36412
- const storedClientInformation = await provider.clientInformation();
36413
- const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));
36414
- if (storedClientInformation && !checked) {
36415
- throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));
36416
- }
36417
- return checked;
36418
- };
36419
- let clientInformation = await readClientInformation();
36420
36133
  const scope = provider.clientMetadata.scope;
36421
36134
  let tokenRequestParams;
36422
36135
  if (provider.prepareTokenRequest) {
@@ -36432,11 +36145,11 @@ async function fetchToken(provider, authorizationServerUrl, { metadata, resource
36432
36145
  const codeVerifier = await provider.codeVerifier();
36433
36146
  tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
36434
36147
  }
36435
- clientInformation ?? (clientInformation = await readClientInformation());
36148
+ const clientInformation = await provider.clientInformation();
36436
36149
  return executeTokenRequest(authorizationServerUrl, {
36437
36150
  metadata,
36438
36151
  tokenRequestParams,
36439
- clientInformation,
36152
+ clientInformation: clientInformation ?? void 0,
36440
36153
  addClientAuthentication: provider.addClientAuthentication,
36441
36154
  resource,
36442
36155
  fetchFn
@@ -36452,7 +36165,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
36452
36165
  } else {
36453
36166
  registrationUrl = new URL("/register", authorizationServerUrl);
36454
36167
  }
36455
- const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {
36168
+ const response = await (fetchFn ?? fetch)(registrationUrl, {
36456
36169
  method: "POST",
36457
36170
  headers: {
36458
36171
  "Content-Type": "application/json"
@@ -36465,7 +36178,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
36465
36178
  if (!response.ok) {
36466
36179
  throw await parseErrorResponse(response);
36467
36180
  }
36468
- return RegistrationResponseSchema.parse(await response.json());
36181
+ return OAuthClientInformationFullSchema.parse(await response.json());
36469
36182
  }
36470
36183
 
36471
36184
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
@@ -36486,16 +36199,6 @@ var SSEClientTransport = class {
36486
36199
  this._authProvider = opts?.authProvider;
36487
36200
  this._fetch = opts?.fetch;
36488
36201
  this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
36489
- this._followRedirects = opts?.redirectPolicy === "follow";
36490
- if (this._followRedirects) {
36491
- this._fetch = fetchLeavingRedirects(this._fetch);
36492
- this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
36493
- }
36494
- }
36495
- /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
36496
- _unfollowedRedirect(response, url2) {
36497
- const text = unfollowedRedirect(response, url2);
36498
- return text && !this._followRedirects ? `${text} (redirectPolicy: 'same-origin')` : text;
36499
36202
  }
36500
36203
  async _authThenStart() {
36501
36204
  if (!this._authProvider) {
@@ -36536,9 +36239,7 @@ var SSEClientTransport = class {
36536
36239
  });
36537
36240
  }
36538
36241
  _startOrAuth() {
36539
- const baseFetch = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
36540
- const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);
36541
- let redirect;
36242
+ const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
36542
36243
  return new Promise((resolve, reject) => {
36543
36244
  this._eventSource = new EventSource(this._url.href, {
36544
36245
  ...this._eventSourceInit,
@@ -36549,7 +36250,6 @@ var SSEClientTransport = class {
36549
36250
  ...init,
36550
36251
  headers
36551
36252
  });
36552
- redirect = this._unfollowedRedirect(response, url2);
36553
36253
  if (response.status === 401 && response.headers.has("www-authenticate")) {
36554
36254
  const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
36555
36255
  this._resourceMetadataUrl = resourceMetadataUrl;
@@ -36564,7 +36264,7 @@ var SSEClientTransport = class {
36564
36264
  this._authThenStart().then(resolve, reject);
36565
36265
  return;
36566
36266
  }
36567
- const error = new SseError(event.code, redirect ?? event.message, event);
36267
+ const error = new SseError(event.code, event.message, event);
36568
36268
  reject(error);
36569
36269
  this.onerror?.(error);
36570
36270
  };
@@ -36641,7 +36341,7 @@ var SSEClientTransport = class {
36641
36341
  body: JSON.stringify(message),
36642
36342
  signal: this._abortController?.signal
36643
36343
  };
36644
- const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);
36344
+ const response = await (this._fetch ?? fetch)(this._endpoint, init);
36645
36345
  if (!response.ok) {
36646
36346
  const text = await response.text().catch(() => null);
36647
36347
  if (response.status === 401 && this._authProvider) {
@@ -36659,7 +36359,7 @@ var SSEClientTransport = class {
36659
36359
  }
36660
36360
  return this.send(message);
36661
36361
  }
36662
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text}`);
36362
+ throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
36663
36363
  }
36664
36364
  await response.body?.cancel();
36665
36365
  } catch (error) {
@@ -37451,9 +37151,9 @@ function isText(value, max2) {
37451
37151
  return typeof value === "string" && !!value.trim() && [...value].length <= max2;
37452
37152
  }
37453
37153
  function parseResponse(body, query, topK) {
37454
- const invalid2 = () => new WebSearchError("WEB_SEARCH_INVALID_RESPONSE");
37154
+ const invalid = () => new WebSearchError("WEB_SEARCH_INVALID_RESPONSE");
37455
37155
  if (!isObject2(body))
37456
- throw invalid2();
37156
+ throw invalid();
37457
37157
  if (body.success === false) {
37458
37158
  const code = body.errorCode;
37459
37159
  if (code === "UNAUTHORIZED")
@@ -37471,7 +37171,7 @@ function parseResponse(body, query, topK) {
37471
37171
  throw new WebSearchError(supported.includes(code) ? code : "WEB_SEARCH_UPSTREAM_ERROR");
37472
37172
  }
37473
37173
  if (body.success !== true || !isObject2(body.data) || body.data.query !== query || !Array.isArray(body.data.items) || body.data.items.length > topK)
37474
- throw invalid2();
37174
+ throw invalid();
37475
37175
  const ids = /* @__PURE__ */ new Set();
37476
37176
  let contentLength = 0;
37477
37177
  const items = body.data.items.map((item) => {
@@ -37482,28 +37182,28 @@ function parseResponse(body, query, topK) {
37482
37182
  "snippet",
37483
37183
  "doc"
37484
37184
  ].includes(item.contentSource))
37485
- throw invalid2();
37185
+ throw invalid();
37486
37186
  if (ids.has(item.id))
37487
- throw invalid2();
37187
+ throw invalid();
37488
37188
  ids.add(item.id);
37489
37189
  contentLength += [...item.content].length;
37490
37190
  if (contentLength > 2e4)
37491
- throw invalid2();
37191
+ throw invalid();
37492
37192
  if (item.url !== void 0) {
37493
37193
  if (typeof item.url !== "string" || item.url.length > 4096)
37494
- throw invalid2();
37194
+ throw invalid();
37495
37195
  try {
37496
37196
  if (!["http:", "https:"].includes(new URL(item.url).protocol))
37497
- throw invalid2();
37197
+ throw invalid();
37498
37198
  } catch {
37499
- throw invalid2();
37199
+ throw invalid();
37500
37200
  }
37501
37201
  }
37502
37202
  if (item.channel !== void 0 && !isText(item.channel, 64))
37503
- throw invalid2();
37203
+ throw invalid();
37504
37204
  if (item.publishedAt !== void 0) {
37505
37205
  if (typeof item.publishedAt !== "string" || !Number.isFinite(Date.parse(item.publishedAt)) || new Date(item.publishedAt).toISOString() !== item.publishedAt)
37506
- throw invalid2();
37206
+ throw invalid();
37507
37207
  }
37508
37208
  return {
37509
37209
  id: item.id,
@@ -38474,6 +38174,17 @@ function mapAgentEventToBaseEvents(event, messageId, thinkingId) {
38474
38174
  }
38475
38175
  return events;
38476
38176
  }
38177
+ case "tool_result": {
38178
+ return [
38179
+ {
38180
+ type: EventType.TOOL_CALL_RESULT,
38181
+ toolCallId: event.toolCallId,
38182
+ messageId: event.messageId,
38183
+ role: "tool",
38184
+ content: event.content
38185
+ }
38186
+ ];
38187
+ }
38477
38188
  case "tool_end": {
38478
38189
  return [{ type: EventType.TOOL_CALL_END, toolCallId: event.toolCallId }];
38479
38190
  }
@@ -39670,7 +39381,6 @@ export {
39670
39381
  createKnowledgeTools,
39671
39382
  NoopWebSearchPort,
39672
39383
  EventObservationRegistry,
39673
- createGatewayRunAuthorization,
39674
39384
  abortableDelay,
39675
39385
  RemoteGatewayMcpServerProvider,
39676
39386
  LinkqueKnowledgeSearchPort,