linkque-cli-v2 1.6.2 → 1.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dev/worker.js +16 -3
  2. package/linkquejs.js +1030 -644
  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-2HV35GH7.js → chunk-CO4I3RJE.js} +15 -2
  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-SDEXPSW4.js → chunk-UZS5YLV2.js} +1 -1
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-2CFN5G5A.js → chunk-VBERH5QM.js} +419 -73
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-Y3G4J3TB.js → chunk-XOLFZ4XS.js} +316 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{dist-ZPLSQEAM.js → dist-TGBYXSBU.js} +27 -42
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-generative-ai-OLT56CSV.js → google-generative-ai-KD7MXONK.js} +8 -10
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-vertex-4DBBJ7SR.js → google-vertex-TREYA472.js} +9 -11
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-OEBGEDLQ.js → mistral-conversations-OEOTQWE5.js} +7 -9
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-codex-responses-3KOC6KHN.js → openai-codex-responses-GEFKSNVN.js} +10 -12
  18. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-completions-HG6OJRL5.js → openai-completions-TAACO6T5.js} +13 -15
  19. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-responses-F6V2PG3Y.js → openai-responses-4DDTXIGI.js} +12 -14
  20. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +197 -61
  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 +387 -106
  24. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-RYONFGPP.js +0 -317
  25. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{pi-messages-DC4DVRAJ.js → pi-messages-7JN3W3BC.js} +4 -4
package/worker.js CHANGED
@@ -34,15 +34,24 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
34
34
  ));
35
35
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
36
 
37
- // ../linkque-agent-runtime/dist/esm/core/dataTransformExecutor.js
38
- function defaultWorkerUrl() {
37
+ // ../linkque-agent-runtime/dist/esm/core/dataTransformWorkerUrl.js
38
+ function defaultDataTransformWorkerUrl() {
39
39
  if (typeof __dirname === "string") {
40
40
  return (0, import_node_url.pathToFileURL)((0, import_node_path.join)(__dirname, "dataTransformWorker.js"));
41
41
  }
42
- const resolver = (0, import_node_module.createRequire)((0, import_node_url.pathToFileURL)((0, import_node_path.join)(process.cwd(), "__linkque_worker_resolver__.js")).href);
43
- const packageJson = resolver.resolve("@alipay/linkque-agent-runtime/package.json");
44
- return (0, import_node_url.pathToFileURL)((0, import_node_path.join)((0, import_node_path.dirname)(packageJson), "dist/esm/core/dataTransformWorker.js"));
42
+ return new URL("dataTransformWorker.js", import_meta.url);
45
43
  }
44
+ var import_node_path, import_node_url, import_meta;
45
+ var init_dataTransformWorkerUrl = __esm({
46
+ "../linkque-agent-runtime/dist/esm/core/dataTransformWorkerUrl.js"() {
47
+ "use strict";
48
+ import_node_path = require("node:path");
49
+ import_node_url = require("node:url");
50
+ import_meta = {};
51
+ }
52
+ });
53
+
54
+ // ../linkque-agent-runtime/dist/esm/core/dataTransformExecutor.js
46
55
  function jsonDepth(value, depth = 0) {
47
56
  if (value === null || typeof value !== "object")
48
57
  return depth;
@@ -51,15 +60,13 @@ function jsonDepth(value, depth = 0) {
51
60
  const children = Array.isArray(value) ? value : Object.values(value);
52
61
  return children.reduce((maximum, child) => Math.max(maximum, jsonDepth(child, depth + 1)), depth);
53
62
  }
54
- var import_node_crypto, import_node_path, import_node_module, import_node_url, import_node_worker_threads, DATA_TRANSFORM_LIMITS, DataTransformError, DataTransformExecutor;
63
+ var import_node_crypto, import_node_worker_threads, DATA_TRANSFORM_LIMITS, DataTransformError, DataTransformExecutor;
55
64
  var init_dataTransformExecutor = __esm({
56
65
  "../linkque-agent-runtime/dist/esm/core/dataTransformExecutor.js"() {
57
66
  "use strict";
58
67
  import_node_crypto = require("node:crypto");
59
- import_node_path = require("node:path");
60
- import_node_module = require("node:module");
61
- import_node_url = require("node:url");
62
68
  import_node_worker_threads = require("node:worker_threads");
69
+ init_dataTransformWorkerUrl();
63
70
  DATA_TRANSFORM_LIMITS = Object.freeze({
64
71
  sourceBytes: 32 * 1024,
65
72
  inputBytes: 2 * 1024 * 1024,
@@ -89,7 +96,7 @@ var init_dataTransformExecutor = __esm({
89
96
  slots = [];
90
97
  nextRequestId = 1;
91
98
  disposed = false;
92
- constructor(workerUrl = defaultWorkerUrl()) {
99
+ constructor(workerUrl = defaultDataTransformWorkerUrl()) {
93
100
  this.workerUrl = workerUrl;
94
101
  }
95
102
  execute(source, input, signal) {
@@ -15360,7 +15367,9 @@ var init_httpLoggingFetch = __esm({
15360
15367
  "x-signature-content",
15361
15368
  "x-alipay-sdk-version",
15362
15369
  "x-alipay-authcode",
15363
- "anthropic-api-key"
15370
+ "anthropic-api-key",
15371
+ "x-linkque-runtime-mac",
15372
+ "x-linkque-run-proof"
15364
15373
  ]);
15365
15374
  REDACTED_VALUE = "ak***";
15366
15375
  RESPONSE_CORRELATION_HEADER_NAMES = [
@@ -68707,11 +68716,11 @@ var init_azure_openai_responses_lazy = __esm({
68707
68716
  });
68708
68717
 
68709
68718
  // ../../node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.lazy.js
68710
- var import_meta, __rewriteRelativeImportExtension2, importNodeOnlyApi, bedrockModuleOverride, bedrockConverseStreamApi;
68719
+ var import_meta2, __rewriteRelativeImportExtension2, importNodeOnlyApi, bedrockModuleOverride, bedrockConverseStreamApi;
68711
68720
  var init_bedrock_converse_stream_lazy = __esm({
68712
68721
  "../../node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.lazy.js"() {
68713
68722
  init_lazy();
68714
- import_meta = {};
68723
+ import_meta2 = {};
68715
68724
  __rewriteRelativeImportExtension2 = function(path9, preserveJsx) {
68716
68725
  if (typeof path9 === "string" && /^\.\.?\//.test(path9)) {
68717
68726
  return path9.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m2, tsx, d, ext, cm) {
@@ -68721,7 +68730,7 @@ var init_bedrock_converse_stream_lazy = __esm({
68721
68730
  return path9;
68722
68731
  };
68723
68732
  importNodeOnlyApi = (specifier) => {
68724
- const runtimeSpecifier = import_meta.url.endsWith(".js") ? specifier.replace(/\.ts$/, ".js") : specifier;
68733
+ const runtimeSpecifier = import_meta2.url.endsWith(".js") ? specifier.replace(/\.ts$/, ".js") : specifier;
68725
68734
  return import(__rewriteRelativeImportExtension2(runtimeSpecifier));
68726
68735
  };
68727
68736
  bedrockConverseStreamApi = () => lazyApi(async () => bedrockModuleOverride ?? await importNodeOnlyApi("./bedrock-converse-stream.ts"));
@@ -69824,64 +69833,50 @@ var require_common2 = __commonJS({
69824
69833
  createDebug.namespaces = namespaces;
69825
69834
  createDebug.names = [];
69826
69835
  createDebug.skips = [];
69827
- const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
69828
- for (const ns of split) {
69829
- if (ns[0] === "-") {
69830
- createDebug.skips.push(ns.slice(1));
69831
- } else {
69832
- createDebug.names.push(ns);
69836
+ let i2;
69837
+ const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
69838
+ const len = split.length;
69839
+ for (i2 = 0; i2 < len; i2++) {
69840
+ if (!split[i2]) {
69841
+ continue;
69833
69842
  }
69834
- }
69835
- }
69836
- function matchesTemplate(search3, template) {
69837
- let searchIndex = 0;
69838
- let templateIndex = 0;
69839
- let starIndex = -1;
69840
- let matchIndex = 0;
69841
- while (searchIndex < search3.length) {
69842
- if (templateIndex < template.length && (template[templateIndex] === search3[searchIndex] || template[templateIndex] === "*")) {
69843
- if (template[templateIndex] === "*") {
69844
- starIndex = templateIndex;
69845
- matchIndex = searchIndex;
69846
- templateIndex++;
69847
- } else {
69848
- searchIndex++;
69849
- templateIndex++;
69850
- }
69851
- } else if (starIndex !== -1) {
69852
- templateIndex = starIndex + 1;
69853
- matchIndex++;
69854
- searchIndex = matchIndex;
69843
+ namespaces = split[i2].replace(/\*/g, ".*?");
69844
+ if (namespaces[0] === "-") {
69845
+ createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
69855
69846
  } else {
69856
- return false;
69847
+ createDebug.names.push(new RegExp("^" + namespaces + "$"));
69857
69848
  }
69858
69849
  }
69859
- while (templateIndex < template.length && template[templateIndex] === "*") {
69860
- templateIndex++;
69861
- }
69862
- return templateIndex === template.length;
69863
69850
  }
69864
69851
  function disable() {
69865
69852
  const namespaces = [
69866
- ...createDebug.names,
69867
- ...createDebug.skips.map((namespace) => "-" + namespace)
69853
+ ...createDebug.names.map(toNamespace),
69854
+ ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
69868
69855
  ].join(",");
69869
69856
  createDebug.enable("");
69870
69857
  return namespaces;
69871
69858
  }
69872
69859
  function enabled(name) {
69873
- for (const skip of createDebug.skips) {
69874
- if (matchesTemplate(name, skip)) {
69860
+ if (name[name.length - 1] === "*") {
69861
+ return true;
69862
+ }
69863
+ let i2;
69864
+ let len;
69865
+ for (i2 = 0, len = createDebug.skips.length; i2 < len; i2++) {
69866
+ if (createDebug.skips[i2].test(name)) {
69875
69867
  return false;
69876
69868
  }
69877
69869
  }
69878
- for (const ns of createDebug.names) {
69879
- if (matchesTemplate(name, ns)) {
69870
+ for (i2 = 0, len = createDebug.names.length; i2 < len; i2++) {
69871
+ if (createDebug.names[i2].test(name)) {
69880
69872
  return true;
69881
69873
  }
69882
69874
  }
69883
69875
  return false;
69884
69876
  }
69877
+ function toNamespace(regexp) {
69878
+ return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
69879
+ }
69885
69880
  function coerce2(val) {
69886
69881
  if (val instanceof Error) {
69887
69882
  return val.stack || val.message;
@@ -70000,11 +69995,10 @@ var require_browser = __commonJS({
70000
69995
  if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
70001
69996
  return false;
70002
69997
  }
70003
- let m2;
70004
69998
  return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
70005
69999
  typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
70006
70000
  // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
70007
- typeof navigator !== "undefined" && navigator.userAgent && (m2 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m2[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
70001
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
70008
70002
  typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
70009
70003
  }
70010
70004
  function formatArgs(args) {
@@ -70042,7 +70036,7 @@ var require_browser = __commonJS({
70042
70036
  function load() {
70043
70037
  let r2;
70044
70038
  try {
70045
- r2 = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
70039
+ r2 = exports2.storage.getItem("debug");
70046
70040
  } catch (error40) {
70047
70041
  }
70048
70042
  if (!r2 && typeof process !== "undefined" && "env" in process) {
@@ -70325,7 +70319,7 @@ var require_node5 = __commonJS({
70325
70319
  return (/* @__PURE__ */ new Date()).toISOString() + " ";
70326
70320
  }
70327
70321
  function log(...args) {
70328
- return process.stderr.write(util2.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
70322
+ return process.stderr.write(util2.format(...args) + "\n");
70329
70323
  }
70330
70324
  function save(namespaces) {
70331
70325
  if (namespaces) {
@@ -89810,11 +89804,23 @@ var require_websocket = __commonJS({
89810
89804
  this._isServer = false;
89811
89805
  this._redirects = 0;
89812
89806
  if (protocols === void 0) {
89813
- protocols = [];
89807
+ if (!options || options.protocols === void 0) {
89808
+ protocols = [];
89809
+ } else if (Array.isArray(options.protocols)) {
89810
+ protocols = options.protocols;
89811
+ } else {
89812
+ protocols = [options.protocols];
89813
+ }
89814
89814
  } else if (!Array.isArray(protocols)) {
89815
89815
  if (typeof protocols === "object" && protocols !== null) {
89816
89816
  options = protocols;
89817
- protocols = [];
89817
+ if (options.protocols === void 0) {
89818
+ protocols = [];
89819
+ } else if (Array.isArray(options.protocols)) {
89820
+ protocols = options.protocols;
89821
+ } else {
89822
+ protocols = [options.protocols];
89823
+ }
89818
89824
  } else {
89819
89825
  protocols = [protocols];
89820
89826
  }
@@ -90011,7 +90017,6 @@ var require_websocket = __commonJS({
90011
90017
  }
90012
90018
  return;
90013
90019
  }
90014
- this._readyState = _WebSocket.CLOSING;
90015
90020
  this._sender.close(code, data, !this._isServer, (err3) => {
90016
90021
  if (err3) return;
90017
90022
  this._closeFrameSent = true;
@@ -90019,6 +90024,7 @@ var require_websocket = __commonJS({
90019
90024
  this._socket.end();
90020
90025
  }
90021
90026
  });
90027
+ this._readyState = _WebSocket.CLOSING;
90022
90028
  setCloseTimer(this);
90023
90029
  }
90024
90030
  /**
@@ -90243,6 +90249,7 @@ var require_websocket = __commonJS({
90243
90249
  socketPath: void 0,
90244
90250
  hostname: void 0,
90245
90251
  protocol: void 0,
90252
+ protocols: void 0,
90246
90253
  timeout: void 0,
90247
90254
  method: "GET",
90248
90255
  host: void 0,
@@ -196197,10 +196204,10 @@ var init_ant_ling = __esm({
196197
196204
  });
196198
196205
 
196199
196206
  // ../../node_modules/@earendil-works/pi-ai/dist/auth/oauth/load.js
196200
- var import_meta2, __rewriteRelativeImportExtension4, importOAuthModule, bundledLoaders, loadAnthropicOAuth, loadOpenAICodexOAuth, loadGitHubCopilotOAuth, loadXaiOAuth, loadRadiusOAuth;
196207
+ var import_meta3, __rewriteRelativeImportExtension4, importOAuthModule, bundledLoaders, loadAnthropicOAuth, loadOpenAICodexOAuth, loadGitHubCopilotOAuth, loadXaiOAuth, loadRadiusOAuth;
196201
196208
  var init_load = __esm({
196202
196209
  "../../node_modules/@earendil-works/pi-ai/dist/auth/oauth/load.js"() {
196203
- import_meta2 = {};
196210
+ import_meta3 = {};
196204
196211
  __rewriteRelativeImportExtension4 = function(path9, preserveJsx) {
196205
196212
  if (typeof path9 === "string" && /^\.\.?\//.test(path9)) {
196206
196213
  return path9.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m2, tsx, d, ext, cm) {
@@ -196210,7 +196217,7 @@ var init_load = __esm({
196210
196217
  return path9;
196211
196218
  };
196212
196219
  importOAuthModule = (specifier) => {
196213
- const runtimeSpecifier = import_meta2.url.endsWith(".js") ? specifier.replace(/\.ts$/, ".js") : specifier;
196220
+ const runtimeSpecifier = import_meta3.url.endsWith(".js") ? specifier.replace(/\.ts$/, ".js") : specifier;
196214
196221
  return import(__rewriteRelativeImportExtension4(runtimeSpecifier));
196215
196222
  };
196216
196223
  loadAnthropicOAuth = async () => {
@@ -206793,6 +206800,55 @@ var init_testProvider = __esm({
206793
206800
  }
206794
206801
  });
206795
206802
 
206803
+ // ../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/transportAnthropicApi.js
206804
+ function createTransportAnthropicApi(modelFetch) {
206805
+ const call = (model, context2, options = {}) => {
206806
+ const client = new Anthropic({
206807
+ baseURL: model.baseUrl,
206808
+ apiKey: options.apiKey ?? null,
206809
+ authToken: null,
206810
+ defaultHeaders: { ...model.headers, ...options.headers },
206811
+ fetch: modelFetch,
206812
+ maxRetries: 0
206813
+ });
206814
+ return stream(model, context2, {
206815
+ ...options,
206816
+ client,
206817
+ maxRetries: 0
206818
+ });
206819
+ };
206820
+ const simple = (model, context2, options) => {
206821
+ const base = buildBaseOptions(model, context2, options, options?.apiKey);
206822
+ if (!options?.reasoning)
206823
+ return call(model, context2, { ...base, thinkingEnabled: false });
206824
+ if (model.compat?.forceAdaptiveThinking === true) {
206825
+ const mapped = model.thinkingLevelMap?.[options.reasoning];
206826
+ const effort = typeof mapped === "string" ? mapped : options.reasoning === "minimal" || options.reasoning === "low" ? "low" : options.reasoning === "medium" ? "medium" : "high";
206827
+ return call(model, context2, { ...base, thinkingEnabled: true, effort });
206828
+ }
206829
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, options.reasoning, options.thinkingBudgets);
206830
+ const maxTokens = clampMaxTokensToContext(model, context2, adjusted.maxTokens);
206831
+ return call(model, context2, {
206832
+ ...base,
206833
+ thinkingEnabled: true,
206834
+ maxTokens,
206835
+ thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024))
206836
+ });
206837
+ };
206838
+ return {
206839
+ stream: (m2, c, o) => call(m2, c, o),
206840
+ streamSimple: (m2, c, o) => simple(m2, c, o)
206841
+ };
206842
+ }
206843
+ var init_transportAnthropicApi = __esm({
206844
+ "../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/transportAnthropicApi.js"() {
206845
+ "use strict";
206846
+ init_sdk();
206847
+ init_anthropic_messages();
206848
+ init_simple_options();
206849
+ }
206850
+ });
206851
+
206796
206852
  // ../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/anthropicProvider.js
206797
206853
  function createApiKeyAuth(authName, fixedApiKey) {
206798
206854
  return {
@@ -206815,7 +206871,7 @@ function createAnthropicProvider(options) {
206815
206871
  auth: { apiKey: createApiKeyAuth(authName, fixedApiKey) },
206816
206872
  models,
206817
206873
  // 复用 pi-ai 内置的 Anthropic Messages 协议实现(含 stream/SSE 逻辑)
206818
- api: anthropicMessagesApi()
206874
+ api: options.modelFetch ? createTransportAnthropicApi(options.modelFetch) : anthropicMessagesApi()
206819
206875
  });
206820
206876
  }
206821
206877
  function buildAnthropicModel(providerId, baseUrl, descriptor) {
@@ -206839,6 +206895,7 @@ var init_anthropicProvider = __esm({
206839
206895
  "../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/anthropicProvider.js"() {
206840
206896
  "use strict";
206841
206897
  init_compat2();
206898
+ init_transportAnthropicApi();
206842
206899
  }
206843
206900
  });
206844
206901
 
@@ -206849,13 +206906,14 @@ function createLinkqueModel(modelId, baseUrl = LINKQUE_DEFAULT_BASE_URL) {
206849
206906
  id: modelId
206850
206907
  });
206851
206908
  }
206852
- function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL) {
206909
+ function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL, modelFetch) {
206853
206910
  return createAnthropicProvider({
206854
206911
  providerId: LINKQUE_PROVIDER_ID,
206855
206912
  providerName: "Linkque",
206856
206913
  baseUrl,
206857
206914
  models: LINKQUE_MODELS,
206858
- authName: "Linkque API key"
206915
+ authName: "Linkque API key",
206916
+ modelFetch
206859
206917
  });
206860
206918
  }
206861
206919
  var LINKQUE_PROVIDER_ID, LINKQUE_AGENT_ID_HEADER, LINKQUE_RUN_ID_HEADER, LINKQUE_CHAT_ID_HEADER, LINKQUE_USER_ID_HEADER, LINKQUE_REQUEST_SOURCE_HEADER, LINKQUE_DEFAULT_BASE_URL, SANDBOX_AGENT_ACCESS_KEY_PLACEHOLDER, LINKQUE_MODELS, LINKQUE_PASSTHROUGH_DEFAULTS;
@@ -207172,7 +207230,7 @@ var init_agentService = __esm({
207172
207230
  async startSession() {
207173
207231
  const models = createModels();
207174
207232
  const providerId = providerIdFor(this.auth.provider);
207175
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
207233
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, this.auth.modelFetch));
207176
207234
  models.setProvider(createTestProvider().provider);
207177
207235
  let model;
207178
207236
  if (this.options.model !== void 0) {
@@ -207386,7 +207444,7 @@ var init_followUpQuestionGenerator = __esm({
207386
207444
  }
207387
207445
  async generate(input) {
207388
207446
  const models = this.modelsFactory();
207389
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
207447
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, input.auth.modelFetch));
207390
207448
  let model = models.getModel(LINKQUE_PROVIDER_ID, FOLLOW_UP_QUESTION_MODEL_ID);
207391
207449
  model ??= createLinkqueModel(FOLLOW_UP_QUESTION_MODEL_ID, this.linkqueBaseUrl);
207392
207450
  model = {
@@ -207933,6 +207991,29 @@ var init_types12 = __esm({
207933
207991
  }
207934
207992
  });
207935
207993
 
207994
+ // ../linkque-agent-runtime/dist/esm/core/scenarioRunAuthorization.js
207995
+ async function authorizeAgentRun(runId, identity, port) {
207996
+ if (typeof runId !== "string" || !/^[\x21-\x7e]{1,64}$/u.test(runId) || typeof identity?.userId !== "string" || !/^[\x21-\x7e]{1,128}$/u.test(identity.userId) || typeof identity.agentId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/u.test(identity.agentId)) {
207997
+ throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
207998
+ }
207999
+ const result = await port.authorizeRun({
208000
+ runId,
208001
+ agentId: identity.agentId,
208002
+ appbaseUserId: identity.userId
208003
+ });
208004
+ if (result?.quotaMode === "NORMAL")
208005
+ return { quotaMode: "NORMAL" };
208006
+ if (result?.quotaMode !== "LIMITED" && result?.quotaMode !== "AUTH_ONLY" || typeof result.modelFetch !== "function") {
208007
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
208008
+ }
208009
+ return result;
208010
+ }
208011
+ var init_scenarioRunAuthorization = __esm({
208012
+ "../linkque-agent-runtime/dist/esm/core/scenarioRunAuthorization.js"() {
208013
+ "use strict";
208014
+ }
208015
+ });
208016
+
207936
208017
  // ../linkque-agent-runtime/dist/esm/core/agentRuntimePlugin.js
207937
208018
  function assertAgentConfigRoot(value, pluginName) {
207938
208019
  if (typeof value !== "object" || value === null || !("agent" in value)) {
@@ -209202,6 +209283,7 @@ var init_agentRuntime = __esm({
209202
209283
  init_runtimeErrorBoundary();
209203
209284
  init_toolObservation();
209204
209285
  init_types12();
209286
+ init_scenarioRunAuthorization();
209205
209287
  init_esm();
209206
209288
  init_types();
209207
209289
  init_followUpQuestionGenerator();
@@ -209381,6 +209463,28 @@ var init_agentRuntime = __esm({
209381
209463
  }
209382
209464
  /** 产出 AgentStreamEvent 流;内核编排「解析上行资源 → 组请求 → agent loop」。 */
209383
209465
  async *runAgentLoop(request, auth2, options = {}) {
209466
+ if (options.runAuthorization) {
209467
+ try {
209468
+ const grant = await authorizeAgentRun(request.runId, options.runtimeContext, options.runAuthorization);
209469
+ if (grant.quotaMode !== "NORMAL")
209470
+ auth2 = { ...auth2, modelFetch: grant.modelFetch };
209471
+ } catch (error40) {
209472
+ const reason = error40 instanceof Error ? error40.message : "";
209473
+ const code = [
209474
+ "SCENARIO_TURN_LIMIT",
209475
+ "SCENARIO_RUNTIME_AUTH_INVALID",
209476
+ "SCENARIO_RUNTIME_REPLAY"
209477
+ ].includes(reason) ? reason : "SCENARIO_RUN_UNAVAILABLE";
209478
+ yield {
209479
+ type: "error",
209480
+ error: {
209481
+ code,
209482
+ message: code === "SCENARIO_TURN_LIMIT" ? "\u4F53\u9A8C\u5BF9\u8BDD\u6B21\u6570\u5DF2\u7528\u5B8C" : "\u672C\u8F6E\u5BF9\u8BDD\u672A\u83B7\u51C6\u6267\u884C"
209483
+ }
209484
+ };
209485
+ return;
209486
+ }
209487
+ }
209384
209488
  const input = {
209385
209489
  runId: request.runId,
209386
209490
  agentId: options.runtimeContext?.agentId ?? this.agentId,
@@ -209966,6 +210070,8 @@ async function* runConversation(request, auth2, options = {}) {
209966
210070
  const ports = options.agentLoop ? { agentLoop: options.agentLoop } : void 0;
209967
210071
  const runtime = options.runtime ?? (options.protocol ? AgentRuntime.create(options.protocol, ports) : new AgentRuntime(ports));
209968
210072
  const runOptions = {};
210073
+ if (options.runAuthorization)
210074
+ runOptions.runAuthorization = options.runAuthorization;
209969
210075
  if (options.sessionId !== void 0)
209970
210076
  runOptions.sessionId = options.sessionId;
209971
210077
  if (options.cwd !== void 0)
@@ -210280,6 +210386,7 @@ async function waitForObservation(promise2, signal) {
210280
210386
  function createImageTool(image, input, options, rules) {
210281
210387
  const fetchImpl = options.fetchImpl ?? globalThis.fetch;
210282
210388
  const auth2 = { ...input.auth };
210389
+ const modelFetch = auth2.modelFetch ?? fetchImpl;
210283
210390
  const cache = /* @__PURE__ */ new Map();
210284
210391
  let calls = 0;
210285
210392
  return {
@@ -210319,7 +210426,7 @@ function createImageTool(image, input, options, rules) {
210319
210426
  const pending = (async () => {
210320
210427
  try {
210321
210428
  const resolved = await resolveImage(image, fetchImpl, rules, signal);
210322
- const response = await fetchImpl(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
210429
+ const response = await modelFetch(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
210323
210430
  method: "POST",
210324
210431
  signal,
210325
210432
  redirect: "error",
@@ -210744,6 +210851,21 @@ var init_mcpDiscoveryPlugin = __esm({
210744
210851
  });
210745
210852
 
210746
210853
  // ../linkque-agent-runtime/dist/esm/impl/plugin/defaultHarnessPromptPlugin.js
210854
+ function formatLocalDateTime(date5) {
210855
+ const pad = (value, length = 2) => String(value).padStart(length, "0");
210856
+ const offsetMinutes = -date5.getTimezoneOffset();
210857
+ const offsetSign = offsetMinutes >= 0 ? "+" : "-";
210858
+ const absoluteOffset = Math.abs(offsetMinutes);
210859
+ const offset = `${offsetSign}${pad(Math.floor(absoluteOffset / 60))}:${pad(absoluteOffset % 60)}`;
210860
+ return `${date5.getFullYear()}-${pad(date5.getMonth() + 1)}-${pad(date5.getDate())}T${pad(date5.getHours())}:${pad(date5.getMinutes())}:${pad(date5.getSeconds())}.${pad(date5.getMilliseconds(), 3)}${offset}`;
210861
+ }
210862
+ function createDefaultHarnessPrompt() {
210863
+ const timestampMs = Date.now();
210864
+ const now = new Date(timestampMs);
210865
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
210866
+ return `${DEFAULT_HARNESS_PROMPT}
210867
+ - \u5F53\u524D\u65F6\u95F4:\u5F53\u5730\u65F6\u95F4 ${formatLocalDateTime(now)}\uFF0C\u5F53\u5730\u65F6\u533A ${timeZone}\uFF0CUnix \u6BEB\u79D2\u65F6\u95F4\u6233 ${timestampMs}\u3002`;
210868
+ }
210747
210869
  var DEFAULT_HARNESS_PROMPT_PLUGIN_NAME, DEFAULT_HARNESS_PROMPT, DefaultHarnessPromptPlugin;
210748
210870
  var init_defaultHarnessPromptPlugin = __esm({
210749
210871
  "../linkque-agent-runtime/dist/esm/impl/plugin/defaultHarnessPromptPlugin.js"() {
@@ -210762,7 +210884,7 @@ var init_defaultHarnessPromptPlugin = __esm({
210762
210884
  DefaultHarnessPromptPlugin = class {
210763
210885
  name = DEFAULT_HARNESS_PROMPT_PLUGIN_NAME;
210764
210886
  modifyAgentConfig = (config2) => {
210765
- config2.agent.harness ??= { systemPrompt: DEFAULT_HARNESS_PROMPT };
210887
+ config2.agent.harness ??= { systemPrompt: createDefaultHarnessPrompt() };
210766
210888
  };
210767
210889
  };
210768
210890
  }
@@ -212873,6 +212995,9 @@ var Protocol = class {
212873
212995
  this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
212874
212996
  const handleTaskResult = async () => {
212875
212997
  const taskId = request.params.taskId;
212998
+ if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
212999
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
213000
+ }
212876
213001
  if (this._taskMessageQueue) {
212877
213002
  let queuedMessage;
212878
213003
  while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
@@ -212903,12 +213028,12 @@ var Protocol = class {
212903
213028
  throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
212904
213029
  }
212905
213030
  if (!isTerminal(task.status)) {
212906
- await this._waitForTaskUpdate(taskId, extra.signal);
213031
+ await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
212907
213032
  return await handleTaskResult();
212908
213033
  }
212909
213034
  if (isTerminal(task.status)) {
212910
213035
  const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
212911
- this._clearTaskQueue(taskId);
213036
+ this._clearTaskQueue(taskId, extra.sessionId);
212912
213037
  return {
212913
213038
  ...result,
212914
213039
  _meta: {
@@ -212945,7 +213070,7 @@ var Protocol = class {
212945
213070
  throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
212946
213071
  }
212947
213072
  await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
212948
- this._clearTaskQueue(request.params.taskId);
213073
+ this._clearTaskQueue(request.params.taskId, extra.sessionId);
212949
213074
  const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
212950
213075
  if (!cancelledTask) {
212951
213076
  throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
@@ -213073,6 +213198,19 @@ var Protocol = class {
213073
213198
  const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
213074
213199
  const capturedTransport = this._transport;
213075
213200
  const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
213201
+ const sessionId = capturedTransport?.sessionId;
213202
+ const store = this._taskStore;
213203
+ let relatedTaskFound = true;
213204
+ let relatedTaskLookup;
213205
+ if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) {
213206
+ relatedTaskFound = false;
213207
+ relatedTaskLookup = (async () => {
213208
+ if (!await store.getTask(relatedTaskId, sessionId)) {
213209
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
213210
+ }
213211
+ relatedTaskFound = true;
213212
+ })();
213213
+ }
213076
213214
  if (handler === void 0) {
213077
213215
  const errorResponse = {
213078
213216
  jsonrpc: "2.0",
@@ -213082,7 +213220,10 @@ var Protocol = class {
213082
213220
  message: "Method not found"
213083
213221
  }
213084
213222
  };
213085
- if (relatedTaskId && this._taskMessageQueue) {
213223
+ if (relatedTaskId && relatedTaskLookup) {
213224
+ const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
213225
+ relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error40) => this._onerror(new Error(`Failed to send an error response: ${error40}`)));
213226
+ } else if (relatedTaskId && this._taskMessageQueue) {
213086
213227
  this._enqueueTaskMessage(relatedTaskId, {
213087
213228
  type: "error",
213088
213229
  message: errorResponse,
@@ -213133,7 +213274,10 @@ var Protocol = class {
213133
213274
  closeSSEStream: extra?.closeSSEStream,
213134
213275
  closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
213135
213276
  };
213136
- Promise.resolve().then(() => {
213277
+ (relatedTaskLookup ?? Promise.resolve()).then(() => {
213278
+ if (relatedTaskLookup && abortController.signal.aborted) {
213279
+ throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
213280
+ }
213137
213281
  if (taskCreationParams) {
213138
213282
  this.assertTaskHandlerCapability(request.method);
213139
213283
  }
@@ -213168,7 +213312,7 @@ var Protocol = class {
213168
213312
  ...error40["data"] !== void 0 && { data: error40["data"] }
213169
213313
  }
213170
213314
  };
213171
- if (relatedTaskId && this._taskMessageQueue) {
213315
+ if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
213172
213316
  await this._enqueueTaskMessage(relatedTaskId, {
213173
213317
  type: "error",
213174
213318
  message: errorResponse,
@@ -213648,7 +213792,7 @@ var Protocol = class {
213648
213792
  throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
213649
213793
  }
213650
213794
  const maxQueueSize = this._options?.maxTaskQueueSize;
213651
- await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
213795
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
213652
213796
  }
213653
213797
  /**
213654
213798
  * Clears the message queue for a task and rejects any pending request resolvers.
@@ -213677,12 +213821,13 @@ var Protocol = class {
213677
213821
  * Uses polling to check for updates at the task's configured poll interval.
213678
213822
  * @param taskId The task ID to wait for
213679
213823
  * @param signal Abort signal to cancel the wait
213824
+ * @param sessionId Session of the request that waits, passed to the task store
213680
213825
  * @returns Promise that resolves when an update occurs or rejects if aborted
213681
213826
  */
213682
- async _waitForTaskUpdate(taskId, signal) {
213827
+ async _waitForTaskUpdate(taskId, signal, sessionId) {
213683
213828
  let interval = this._options?.defaultTaskPollInterval ?? 1e3;
213684
213829
  try {
213685
- const task = await this._taskStore?.getTask(taskId);
213830
+ const task = await this._taskStore?.getTask(taskId, sessionId);
213686
213831
  if (task?.pollInterval) {
213687
213832
  interval = task.pollInterval;
213688
213833
  }
@@ -215322,6 +215467,68 @@ function createFetchWithInit(baseFetch = fetch, baseInit) {
215322
215467
  return baseFetch(url2, mergedInit);
215323
215468
  };
215324
215469
  }
215470
+ var MAX_REDIRECTS = 5;
215471
+ var REDIRECT_STATUSES = [301, 302, 303, 307, 308];
215472
+ function isWithinOrigin(from, to) {
215473
+ if (from.protocol === to.protocol && from.hostname === to.hostname && from.port === to.port) {
215474
+ return true;
215475
+ }
215476
+ return from.hostname === to.hostname && from.protocol === "http:" && from.port === "" && to.protocol === "https:" && to.port === "";
215477
+ }
215478
+ function redirectTarget(response, requestUrl) {
215479
+ const location = REDIRECT_STATUSES.includes(response.status) ? response.headers.get("location") : null;
215480
+ try {
215481
+ return location ? new URL(location, requestUrl) : void 0;
215482
+ } catch {
215483
+ return void 0;
215484
+ }
215485
+ }
215486
+ function followWithinOrigin(baseFetch, url2, init, response, followed = 0) {
215487
+ const target = redirectTarget(response, url2);
215488
+ const keepsMethod = response.status === 307 || response.status === 308 || (init?.method ?? "GET").toUpperCase() === "GET";
215489
+ if (!target || followed === MAX_REDIRECTS || !keepsMethod) {
215490
+ return void 0;
215491
+ }
215492
+ const from = new URL(url2);
215493
+ const addsUserinfo = (target.username || target.password) && (target.username !== from.username || target.password !== from.password);
215494
+ if (addsUserinfo || !isWithinOrigin(from, target)) {
215495
+ return void 0;
215496
+ }
215497
+ return Promise.resolve(response.body?.cancel()).then(() => baseFetch(target, { ...init, redirect: "manual" })).then((next) => followWithinOrigin(baseFetch, target, init, next, followed + 1) ?? next);
215498
+ }
215499
+ var followingFetches = /* @__PURE__ */ new WeakSet();
215500
+ function fetchLeavingRedirects(baseFetch) {
215501
+ const following = (url2, init) => (baseFetch ?? fetch)(url2, init);
215502
+ followingFetches.add(following);
215503
+ return following;
215504
+ }
215505
+ function fetchWithinOrigin(baseFetch = fetch) {
215506
+ if (followingFetches.has(baseFetch)) {
215507
+ return baseFetch;
215508
+ }
215509
+ return (url2, init) => {
215510
+ if (init?.redirect === "error" || init?.redirect === "manual") {
215511
+ return baseFetch(url2, init);
215512
+ }
215513
+ return Promise.resolve(baseFetch(url2, { ...init, redirect: "manual" })).then((response) => followWithinOrigin(baseFetch, url2, init, response) ?? response);
215514
+ };
215515
+ }
215516
+ function unfollowedRedirect(response, requestUrl) {
215517
+ if (response.type === "opaqueredirect") {
215518
+ return "Redirect not followed: this runtime does not expose the redirect target";
215519
+ }
215520
+ const from = response.url || requestUrl;
215521
+ const target = redirectTarget(response, from);
215522
+ if (!target) {
215523
+ return void 0;
215524
+ }
215525
+ target.username = target.password = target.search = target.hash = "";
215526
+ if (target.protocol === "http:" && new URL(from).protocol === "https:") {
215527
+ target.protocol = "https:";
215528
+ return `Redirect to plain http not followed; try ${target.href} instead`;
215529
+ }
215530
+ return `Redirect to ${target.href} not followed`;
215531
+ }
215325
215532
 
215326
215533
  // ../../node_modules/pkce-challenge/dist/index.node.js
215327
215534
  var crypto2;
@@ -215469,7 +215676,12 @@ var OAuthTokensSchema = object2({
215469
215676
  token_type: string2(),
215470
215677
  expires_in: coerce_exports.number().optional(),
215471
215678
  scope: string2().optional(),
215472
- refresh_token: string2().optional()
215679
+ refresh_token: string2().optional(),
215680
+ /**
215681
+ * Not part of the wire format: the authorization server this value was obtained from, added by
215682
+ * the client's `auth()` before it is stored and compared when it is read back.
215683
+ */
215684
+ issuer: string2().optional().catch(void 0)
215473
215685
  }).strip();
215474
215686
  var OAuthErrorResponseSchema = object2({
215475
215687
  error: string2(),
@@ -215499,7 +215711,12 @@ var OAuthClientInformationSchema = object2({
215499
215711
  client_id: string2(),
215500
215712
  client_secret: string2().optional(),
215501
215713
  client_id_issued_at: number2().optional(),
215502
- client_secret_expires_at: number2().optional()
215714
+ client_secret_expires_at: number2().optional(),
215715
+ /**
215716
+ * Not part of the wire format: the authorization server this value was obtained from, added by
215717
+ * the client's `auth()` before it is stored and compared when it is read back.
215718
+ */
215719
+ issuer: string2().optional().catch(void 0)
215503
215720
  }).strip();
215504
215721
  var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
215505
215722
  var OAuthClientRegistrationErrorSchema = object2({
@@ -215697,10 +215914,31 @@ async function parseErrorResponse(input) {
215697
215914
  const errorClass = OAUTH_ERRORS[error40] || ServerError;
215698
215915
  return new errorClass(error_description || "", error_uri);
215699
215916
  } catch (error40) {
215700
- const errorMessage4 = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error40}. Raw body: ${body}`;
215917
+ const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
215918
+ const errorMessage4 = `${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error40}. Raw body: ${body}`}`;
215701
215919
  return new ServerError(errorMessage4);
215702
215920
  }
215703
215921
  }
215922
+ function issuersMatch(a, b) {
215923
+ let [x2, y] = [a, b];
215924
+ try {
215925
+ [x2, y] = [new URL(a).href, new URL(b).href];
215926
+ } catch {
215927
+ }
215928
+ return x2 === y || x2.endsWith("/") && x2.slice(0, -1) === y || y.endsWith("/") && y.slice(0, -1) === x2;
215929
+ }
215930
+ function discardIfIssuerMismatch(stored, issuer) {
215931
+ if (!stored)
215932
+ return void 0;
215933
+ if (typeof stored.issuer !== "string")
215934
+ return stored.issuer == null ? stored : { ...stored, issuer: void 0 };
215935
+ return issuersMatch(stored.issuer, issuer) ? stored : void 0;
215936
+ }
215937
+ var TokenResponseSchema = OAuthTokensSchema.omit({ issuer: true });
215938
+ var RegistrationResponseSchema = OAuthClientInformationFullSchema.omit({ issuer: true });
215939
+ function boundElsewhereError(stored, issuer) {
215940
+ 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.`);
215941
+ }
215704
215942
  async function auth(provider, options) {
215705
215943
  try {
215706
215944
  return await authInternal(provider, options);
@@ -215754,9 +215992,24 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215754
215992
  authorizationServerMetadata: metadata
215755
215993
  });
215756
215994
  }
215757
- const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
215995
+ const issuer = String(authorizationServerUrl);
215996
+ const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);
215997
+ const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;
215758
215998
  const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
215759
- let clientInformation = await Promise.resolve(provider.clientInformation());
215999
+ const storedClientInformation = await Promise.resolve(provider.clientInformation());
216000
+ let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer);
216001
+ const canRegisterAgain = provider.saveClientInformation !== void 0 && !!provider.redirectUrl;
216002
+ if (storedClientInformation && !clientInformation && !canRegisterAgain) {
216003
+ throw boundElsewhereError(storedClientInformation, issuer);
216004
+ }
216005
+ const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : void 0;
216006
+ const bindClientInformation = async () => {
216007
+ try {
216008
+ if (unstampedClientInformation)
216009
+ await provider.saveClientInformation?.({ ...unstampedClientInformation, issuer });
216010
+ } catch {
216011
+ }
216012
+ };
215760
216013
  if (!clientInformation) {
215761
216014
  if (authorizationCode !== void 0) {
215762
216015
  throw new Error("Existing OAuth client information is required when exchanging an authorization code");
@@ -215768,9 +216021,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215768
216021
  }
215769
216022
  const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
215770
216023
  if (shouldUseUrlBasedClientId) {
215771
- clientInformation = {
215772
- client_id: clientMetadataUrl
215773
- };
216024
+ clientInformation = { client_id: clientMetadataUrl, issuer };
215774
216025
  await provider.saveClientInformation?.(clientInformation);
215775
216026
  } else {
215776
216027
  if (!provider.saveClientInformation) {
@@ -215782,8 +216033,8 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215782
216033
  scope: resolvedScope,
215783
216034
  fetchFn
215784
216035
  });
215785
- await provider.saveClientInformation(fullInformation);
215786
- clientInformation = fullInformation;
216036
+ clientInformation = { ...fullInformation, issuer };
216037
+ await provider.saveClientInformation(clientInformation);
215787
216038
  }
215788
216039
  }
215789
216040
  const nonInteractiveFlow = !provider.redirectUrl;
@@ -215794,10 +216045,14 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215794
216045
  authorizationCode,
215795
216046
  fetchFn
215796
216047
  });
215797
- await provider.saveTokens(tokens2);
216048
+ await bindClientInformation();
216049
+ await provider.saveTokens({ ...tokens2, issuer });
215798
216050
  return "AUTHORIZED";
215799
216051
  }
215800
- const tokens = await provider.tokens();
216052
+ const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);
216053
+ if (tokens?.refresh_token && tokens.issuer == null) {
216054
+ 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.");
216055
+ }
215801
216056
  if (tokens?.refresh_token) {
215802
216057
  try {
215803
216058
  const newTokens = await refreshAuthorization(authorizationServerUrl, {
@@ -215808,7 +216063,8 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215808
216063
  addClientAuthentication: provider.addClientAuthentication,
215809
216064
  fetchFn
215810
216065
  });
215811
- await provider.saveTokens(newTokens);
216066
+ await bindClientInformation();
216067
+ await provider.saveTokens({ ...newTokens, issuer });
215812
216068
  return "AUTHORIZED";
215813
216069
  } catch (error40) {
215814
216070
  if (!(error40 instanceof OAuthError) || error40 instanceof ServerError) {
@@ -215907,7 +216163,7 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
215907
216163
  }
215908
216164
  async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
215909
216165
  try {
215910
- return await fetchFn(url2, { headers });
216166
+ return await fetchWithinOrigin(fetchFn)(url2, { headers });
215911
216167
  } catch (error40) {
215912
216168
  if (error40 instanceof TypeError) {
215913
216169
  if (headers) {
@@ -215932,7 +216188,7 @@ async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
215932
216188
  return await fetchWithCorsRetry(url2, headers, fetchFn);
215933
216189
  }
215934
216190
  function shouldAttemptFallback(response, pathname) {
215935
- return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
216191
+ return !response || !response.ok && response.status < 500 && pathname !== "/";
215936
216192
  }
215937
216193
  async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
215938
216194
  const issuer = new URL(serverUrl);
@@ -215998,7 +216254,7 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fet
215998
216254
  }
215999
216255
  if (!response.ok) {
216000
216256
  await response.body?.cancel();
216001
- if (response.status >= 400 && response.status < 500) {
216257
+ if (response.status < 500) {
216002
216258
  continue;
216003
216259
  }
216004
216260
  throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
@@ -216031,6 +216287,9 @@ async function discoverOAuthServerInfo(serverUrl, opts) {
216031
216287
  resourceMetadata
216032
216288
  };
216033
216289
  }
216290
+ function resourceIndicatorToString(resource) {
216291
+ return typeof resource === "string" ? resource : resource.href;
216292
+ }
216034
216293
  async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state: state2, resource }) {
216035
216294
  let authorizationUrl;
216036
216295
  if (metadata) {
@@ -216062,7 +216321,7 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
216062
216321
  authorizationUrl.searchParams.append("prompt", "consent");
216063
216322
  }
216064
216323
  if (resource) {
216065
- authorizationUrl.searchParams.set("resource", resource.href);
216324
+ authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource));
216066
216325
  }
216067
216326
  return { authorizationUrl, codeVerifier };
216068
216327
  }
@@ -216081,7 +216340,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
216081
216340
  Accept: "application/json"
216082
216341
  });
216083
216342
  if (resource) {
216084
- tokenRequestParams.set("resource", resource.href);
216343
+ tokenRequestParams.set("resource", resourceIndicatorToString(resource));
216085
216344
  }
216086
216345
  if (addClientAuthentication) {
216087
216346
  await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
@@ -216090,7 +216349,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
216090
216349
  const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
216091
216350
  applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
216092
216351
  }
216093
- const response = await (fetchFn ?? fetch)(tokenUrl, {
216352
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {
216094
216353
  method: "POST",
216095
216354
  headers,
216096
216355
  body: tokenRequestParams
@@ -216098,7 +216357,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
216098
216357
  if (!response.ok) {
216099
216358
  throw await parseErrorResponse(response);
216100
216359
  }
216101
- return OAuthTokensSchema.parse(await response.json());
216360
+ return TokenResponseSchema.parse(await response.json());
216102
216361
  }
216103
216362
  async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
216104
216363
  const tokenRequestParams = new URLSearchParams({
@@ -216116,6 +216375,15 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
216116
216375
  return { refresh_token: refreshToken, ...tokens };
216117
216376
  }
216118
216377
  async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
216378
+ const readClientInformation = async () => {
216379
+ const storedClientInformation = await provider.clientInformation();
216380
+ const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));
216381
+ if (storedClientInformation && !checked) {
216382
+ throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));
216383
+ }
216384
+ return checked;
216385
+ };
216386
+ let clientInformation = await readClientInformation();
216119
216387
  const scope = provider.clientMetadata.scope;
216120
216388
  let tokenRequestParams;
216121
216389
  if (provider.prepareTokenRequest) {
@@ -216131,11 +216399,11 @@ async function fetchToken(provider, authorizationServerUrl, { metadata, resource
216131
216399
  const codeVerifier = await provider.codeVerifier();
216132
216400
  tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
216133
216401
  }
216134
- const clientInformation = await provider.clientInformation();
216402
+ clientInformation ?? (clientInformation = await readClientInformation());
216135
216403
  return executeTokenRequest(authorizationServerUrl, {
216136
216404
  metadata,
216137
216405
  tokenRequestParams,
216138
- clientInformation: clientInformation ?? void 0,
216406
+ clientInformation,
216139
216407
  addClientAuthentication: provider.addClientAuthentication,
216140
216408
  resource,
216141
216409
  fetchFn
@@ -216151,7 +216419,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
216151
216419
  } else {
216152
216420
  registrationUrl = new URL("/register", authorizationServerUrl);
216153
216421
  }
216154
- const response = await (fetchFn ?? fetch)(registrationUrl, {
216422
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {
216155
216423
  method: "POST",
216156
216424
  headers: {
216157
216425
  "Content-Type": "application/json"
@@ -216164,7 +216432,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
216164
216432
  if (!response.ok) {
216165
216433
  throw await parseErrorResponse(response);
216166
216434
  }
216167
- return OAuthClientInformationFullSchema.parse(await response.json());
216435
+ return RegistrationResponseSchema.parse(await response.json());
216168
216436
  }
216169
216437
 
216170
216438
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
@@ -216185,6 +216453,16 @@ var SSEClientTransport = class {
216185
216453
  this._authProvider = opts?.authProvider;
216186
216454
  this._fetch = opts?.fetch;
216187
216455
  this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
216456
+ this._followRedirects = opts?.redirectPolicy === "follow";
216457
+ if (this._followRedirects) {
216458
+ this._fetch = fetchLeavingRedirects(this._fetch);
216459
+ this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
216460
+ }
216461
+ }
216462
+ /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
216463
+ _unfollowedRedirect(response, url2) {
216464
+ const text2 = unfollowedRedirect(response, url2);
216465
+ return text2 && !this._followRedirects ? `${text2} (redirectPolicy: 'same-origin')` : text2;
216188
216466
  }
216189
216467
  async _authThenStart() {
216190
216468
  if (!this._authProvider) {
@@ -216225,7 +216503,9 @@ var SSEClientTransport = class {
216225
216503
  });
216226
216504
  }
216227
216505
  _startOrAuth() {
216228
- const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
216506
+ const baseFetch = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
216507
+ const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);
216508
+ let redirect;
216229
216509
  return new Promise((resolve, reject) => {
216230
216510
  this._eventSource = new EventSource(this._url.href, {
216231
216511
  ...this._eventSourceInit,
@@ -216236,6 +216516,7 @@ var SSEClientTransport = class {
216236
216516
  ...init,
216237
216517
  headers
216238
216518
  });
216519
+ redirect = this._unfollowedRedirect(response, url2);
216239
216520
  if (response.status === 401 && response.headers.has("www-authenticate")) {
216240
216521
  const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
216241
216522
  this._resourceMetadataUrl = resourceMetadataUrl;
@@ -216250,7 +216531,7 @@ var SSEClientTransport = class {
216250
216531
  this._authThenStart().then(resolve, reject);
216251
216532
  return;
216252
216533
  }
216253
- const error40 = new SseError(event.code, event.message, event);
216534
+ const error40 = new SseError(event.code, redirect ?? event.message, event);
216254
216535
  reject(error40);
216255
216536
  this.onerror?.(error40);
216256
216537
  };
@@ -216327,7 +216608,7 @@ var SSEClientTransport = class {
216327
216608
  body: JSON.stringify(message),
216328
216609
  signal: this._abortController?.signal
216329
216610
  };
216330
- const response = await (this._fetch ?? fetch)(this._endpoint, init);
216611
+ const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);
216331
216612
  if (!response.ok) {
216332
216613
  const text2 = await response.text().catch(() => null);
216333
216614
  if (response.status === 401 && this._authProvider) {
@@ -216345,7 +216626,7 @@ var SSEClientTransport = class {
216345
216626
  }
216346
216627
  return this.send(message);
216347
216628
  }
216348
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text2}`);
216629
+ throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text2}`);
216349
216630
  }
216350
216631
  await response.body?.cancel();
216351
216632
  } catch (error40) {