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
package/worker.js CHANGED
@@ -15367,9 +15367,7 @@ var init_httpLoggingFetch = __esm({
15367
15367
  "x-signature-content",
15368
15368
  "x-alipay-sdk-version",
15369
15369
  "x-alipay-authcode",
15370
- "anthropic-api-key",
15371
- "x-linkque-runtime-mac",
15372
- "x-linkque-run-proof"
15370
+ "anthropic-api-key"
15373
15371
  ]);
15374
15372
  REDACTED_VALUE = "ak***";
15375
15373
  RESPONSE_CORRELATION_HEADER_NAMES = [
@@ -15792,6 +15790,46 @@ var init_webSearchResource = __esm({
15792
15790
  }
15793
15791
  });
15794
15792
 
15793
+ // ../linkque-agent-runtime/dist/esm/core/webSearchPresentation.js
15794
+ function projectWebSearchSources(result) {
15795
+ if (!isRecord2(result))
15796
+ return void 0;
15797
+ const value = result;
15798
+ if (value.error || typeof value.query !== "string" || !Array.isArray(value.items))
15799
+ return void 0;
15800
+ const items = value.items.slice(0, 10).flatMap((item) => {
15801
+ if (!isRecord2(item) || typeof item.id !== "string" || !item.id.trim() || typeof item.title !== "string" || !item.title.trim() || typeof item.content !== "string")
15802
+ return [];
15803
+ let url2;
15804
+ if (typeof item.url === "string") {
15805
+ try {
15806
+ const parsed = new URL(item.url);
15807
+ if (["http:", "https:"].includes(parsed.protocol) && !parsed.username && !parsed.password)
15808
+ url2 = parsed.href;
15809
+ } catch {
15810
+ }
15811
+ }
15812
+ return [
15813
+ {
15814
+ id: item.id.slice(0, 256),
15815
+ title: item.title.slice(0, 256),
15816
+ content: item.content.slice(0, 4e3),
15817
+ ...url2 ? { url: url2 } : {},
15818
+ ...typeof item.channel === "string" ? { channel: item.channel.slice(0, 64) } : {}
15819
+ }
15820
+ ];
15821
+ });
15822
+ return items.length ? { query: value.query.slice(0, 2048), items } : void 0;
15823
+ }
15824
+ function isRecord2(value) {
15825
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
15826
+ }
15827
+ var init_webSearchPresentation = __esm({
15828
+ "../linkque-agent-runtime/dist/esm/core/webSearchPresentation.js"() {
15829
+ "use strict";
15830
+ }
15831
+ });
15832
+
15795
15833
  // ../linkque-agent-runtime/dist/esm/core/createWebSearchTool.js
15796
15834
  function createWebSearchTool(resource, searchPort, agentId, debugLog) {
15797
15835
  return {
@@ -15828,6 +15866,15 @@ function createWebSearchTool(resource, searchPort, agentId, debugLog) {
15828
15866
  const result = await waitWithSignal(() => searchPort.search({ agentId, ...parsed }, signal, context2?.observation), signal);
15829
15867
  throwIfWebSearchAborted(signal);
15830
15868
  count = result.items.length;
15869
+ const presentation = context2 ? projectWebSearchSources(result) : void 0;
15870
+ if (context2 && presentation) {
15871
+ context2.emit({
15872
+ type: "tool_result",
15873
+ toolCallId: context2.toolCallId,
15874
+ messageId: `${context2.toolCallId}:web-search-result`,
15875
+ content: JSON.stringify(presentation)
15876
+ });
15877
+ }
15831
15878
  return result;
15832
15879
  } catch (error40) {
15833
15880
  if (signal?.aborted || error40 instanceof Error && error40.name === "AbortError") {
@@ -15852,6 +15899,7 @@ function createWebSearchTool(resource, searchPort, agentId, debugLog) {
15852
15899
  var init_createWebSearchTool = __esm({
15853
15900
  "../linkque-agent-runtime/dist/esm/core/createWebSearchTool.js"() {
15854
15901
  "use strict";
15902
+ init_webSearchPresentation();
15855
15903
  init_types();
15856
15904
  init_webSearchTools();
15857
15905
  init_abort();
@@ -34213,7 +34261,7 @@ function parseConversationRunRequest(value) {
34213
34261
  return value;
34214
34262
  }
34215
34263
  function getConversationRunRequestIssues(value) {
34216
- if (!isRecord3(value))
34264
+ if (!isRecord4(value))
34217
34265
  return ["request must be an object"];
34218
34266
  const issues = [];
34219
34267
  if (!isSupportedConversationProtocolVersion(value.protocolVersion)) {
@@ -34236,7 +34284,7 @@ function getConversationRunRequestIssues(value) {
34236
34284
  } else {
34237
34285
  value.attachments.forEach((attachment, index2) => validateAttachment(attachment, index2, issues));
34238
34286
  }
34239
- if (!isRecord3(value.metadata))
34287
+ if (!isRecord4(value.metadata))
34240
34288
  issues.push("metadata must be an object");
34241
34289
  if (value.clientCapabilities !== void 0) {
34242
34290
  if (!Array.isArray(value.clientCapabilities)) {
@@ -34254,7 +34302,7 @@ function getConversationRunRequestIssues(value) {
34254
34302
  return issues;
34255
34303
  }
34256
34304
  function validateMessage(value, index2, issues) {
34257
- if (!isRecord3(value)) {
34305
+ if (!isRecord4(value)) {
34258
34306
  issues.push(`messages[${index2}] must be an object`);
34259
34307
  return;
34260
34308
  }
@@ -34265,7 +34313,7 @@ function validateMessage(value, index2, issues) {
34265
34313
  }
34266
34314
  if (value.content !== void 0) {
34267
34315
  if (typeof value.content === "string") {
34268
- } else if (isRecord3(value.content) && value.content.type === "a2ui.event") {
34316
+ } else if (isRecord4(value.content) && value.content.type === "a2ui.event") {
34269
34317
  if (value.role !== "user") {
34270
34318
  issues.push(`messages[${index2}].content a2ui.event requires the user role`);
34271
34319
  }
@@ -34289,21 +34337,21 @@ function validateA2UIEventContent(value, path9, issues) {
34289
34337
  validateA2UIEventSource(value.source, `${path9}.source`, issues);
34290
34338
  }
34291
34339
  function validateA2UIEvent(value, path9, issues) {
34292
- if (!isRecord3(value)) {
34340
+ if (!isRecord4(value)) {
34293
34341
  issues.push(`${path9} must be an object`);
34294
34342
  return;
34295
34343
  }
34296
34344
  if (!isSafeEventName(value.name)) {
34297
34345
  issues.push(`${path9}.name must be a safe event name up to 96 characters`);
34298
34346
  }
34299
- if (!isRecord3(value.payload)) {
34347
+ if (!isRecord4(value.payload)) {
34300
34348
  issues.push(`${path9}.payload must be an object`);
34301
34349
  return;
34302
34350
  }
34303
34351
  validateJsonValue(value.payload, `${path9}.payload`, issues);
34304
34352
  }
34305
34353
  function validateA2UIEventSource(value, path9, issues) {
34306
- if (!isRecord3(value)) {
34354
+ if (!isRecord4(value)) {
34307
34355
  issues.push(`${path9} must be an object`);
34308
34356
  return;
34309
34357
  }
@@ -34344,7 +34392,7 @@ function validateJsonValue(value, path9, issues) {
34344
34392
  value.forEach((entry, index2) => validateJsonValue(entry, `${path9}[${index2}]`, issues));
34345
34393
  return;
34346
34394
  }
34347
- if (!isRecord3(value)) {
34395
+ if (!isRecord4(value)) {
34348
34396
  issues.push(`${path9} must be JSON-safe`);
34349
34397
  return;
34350
34398
  }
@@ -34357,7 +34405,7 @@ function validateJsonValue(value, path9, issues) {
34357
34405
  }
34358
34406
  }
34359
34407
  function validateAttachment(value, index2, issues) {
34360
- if (!isRecord3(value)) {
34408
+ if (!isRecord4(value)) {
34361
34409
  issues.push(`attachments[${index2}] must be an object`);
34362
34410
  return;
34363
34411
  }
@@ -34375,11 +34423,11 @@ function validateAttachment(value, index2, issues) {
34375
34423
  if (value.size !== void 0 && (!Number.isSafeInteger(value.size) || Number(value.size) < 0)) {
34376
34424
  issues.push(`attachments[${index2}].size must be a non-negative safe integer when provided`);
34377
34425
  }
34378
- if (value.metadata !== void 0 && !isRecord3(value.metadata)) {
34426
+ if (value.metadata !== void 0 && !isRecord4(value.metadata)) {
34379
34427
  issues.push(`attachments[${index2}].metadata must be an object when provided`);
34380
34428
  }
34381
34429
  }
34382
- function isRecord3(value) {
34430
+ function isRecord4(value) {
34383
34431
  return typeof value === "object" && value !== null && !Array.isArray(value);
34384
34432
  }
34385
34433
  function isNonEmptyString(value) {
@@ -34551,6 +34599,17 @@ function mapAgentEventToBaseEvents(event, messageId, thinkingId) {
34551
34599
  }
34552
34600
  return events;
34553
34601
  }
34602
+ case "tool_result": {
34603
+ return [
34604
+ {
34605
+ type: EventType.TOOL_CALL_RESULT,
34606
+ toolCallId: event.toolCallId,
34607
+ messageId: event.messageId,
34608
+ role: "tool",
34609
+ content: event.content
34610
+ }
34611
+ ];
34612
+ }
34554
34613
  case "tool_end": {
34555
34614
  return [{ type: EventType.TOOL_CALL_END, toolCallId: event.toolCallId }];
34556
34615
  }
@@ -69833,50 +69892,64 @@ var require_common2 = __commonJS({
69833
69892
  createDebug.namespaces = namespaces;
69834
69893
  createDebug.names = [];
69835
69894
  createDebug.skips = [];
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;
69895
+ const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
69896
+ for (const ns of split) {
69897
+ if (ns[0] === "-") {
69898
+ createDebug.skips.push(ns.slice(1));
69899
+ } else {
69900
+ createDebug.names.push(ns);
69842
69901
  }
69843
- namespaces = split[i2].replace(/\*/g, ".*?");
69844
- if (namespaces[0] === "-") {
69845
- createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
69902
+ }
69903
+ }
69904
+ function matchesTemplate(search3, template) {
69905
+ let searchIndex = 0;
69906
+ let templateIndex = 0;
69907
+ let starIndex = -1;
69908
+ let matchIndex = 0;
69909
+ while (searchIndex < search3.length) {
69910
+ if (templateIndex < template.length && (template[templateIndex] === search3[searchIndex] || template[templateIndex] === "*")) {
69911
+ if (template[templateIndex] === "*") {
69912
+ starIndex = templateIndex;
69913
+ matchIndex = searchIndex;
69914
+ templateIndex++;
69915
+ } else {
69916
+ searchIndex++;
69917
+ templateIndex++;
69918
+ }
69919
+ } else if (starIndex !== -1) {
69920
+ templateIndex = starIndex + 1;
69921
+ matchIndex++;
69922
+ searchIndex = matchIndex;
69846
69923
  } else {
69847
- createDebug.names.push(new RegExp("^" + namespaces + "$"));
69924
+ return false;
69848
69925
  }
69849
69926
  }
69927
+ while (templateIndex < template.length && template[templateIndex] === "*") {
69928
+ templateIndex++;
69929
+ }
69930
+ return templateIndex === template.length;
69850
69931
  }
69851
69932
  function disable() {
69852
69933
  const namespaces = [
69853
- ...createDebug.names.map(toNamespace),
69854
- ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
69934
+ ...createDebug.names,
69935
+ ...createDebug.skips.map((namespace) => "-" + namespace)
69855
69936
  ].join(",");
69856
69937
  createDebug.enable("");
69857
69938
  return namespaces;
69858
69939
  }
69859
69940
  function enabled(name) {
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)) {
69941
+ for (const skip of createDebug.skips) {
69942
+ if (matchesTemplate(name, skip)) {
69867
69943
  return false;
69868
69944
  }
69869
69945
  }
69870
- for (i2 = 0, len = createDebug.names.length; i2 < len; i2++) {
69871
- if (createDebug.names[i2].test(name)) {
69946
+ for (const ns of createDebug.names) {
69947
+ if (matchesTemplate(name, ns)) {
69872
69948
  return true;
69873
69949
  }
69874
69950
  }
69875
69951
  return false;
69876
69952
  }
69877
- function toNamespace(regexp) {
69878
- return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
69879
- }
69880
69953
  function coerce2(val) {
69881
69954
  if (val instanceof Error) {
69882
69955
  return val.stack || val.message;
@@ -69995,10 +70068,11 @@ var require_browser = __commonJS({
69995
70068
  if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
69996
70069
  return false;
69997
70070
  }
70071
+ let m2;
69998
70072
  return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
69999
70073
  typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
70000
70074
  // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
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
70075
+ 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
70002
70076
  typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
70003
70077
  }
70004
70078
  function formatArgs(args) {
@@ -70036,7 +70110,7 @@ var require_browser = __commonJS({
70036
70110
  function load() {
70037
70111
  let r2;
70038
70112
  try {
70039
- r2 = exports2.storage.getItem("debug");
70113
+ r2 = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
70040
70114
  } catch (error40) {
70041
70115
  }
70042
70116
  if (!r2 && typeof process !== "undefined" && "env" in process) {
@@ -70319,7 +70393,7 @@ var require_node5 = __commonJS({
70319
70393
  return (/* @__PURE__ */ new Date()).toISOString() + " ";
70320
70394
  }
70321
70395
  function log(...args) {
70322
- return process.stderr.write(util2.format(...args) + "\n");
70396
+ return process.stderr.write(util2.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
70323
70397
  }
70324
70398
  function save(namespaces) {
70325
70399
  if (namespaces) {
@@ -89804,23 +89878,11 @@ var require_websocket = __commonJS({
89804
89878
  this._isServer = false;
89805
89879
  this._redirects = 0;
89806
89880
  if (protocols === void 0) {
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
- }
89881
+ protocols = [];
89814
89882
  } else if (!Array.isArray(protocols)) {
89815
89883
  if (typeof protocols === "object" && protocols !== null) {
89816
89884
  options = 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
- }
89885
+ protocols = [];
89824
89886
  } else {
89825
89887
  protocols = [protocols];
89826
89888
  }
@@ -90017,6 +90079,7 @@ var require_websocket = __commonJS({
90017
90079
  }
90018
90080
  return;
90019
90081
  }
90082
+ this._readyState = _WebSocket.CLOSING;
90020
90083
  this._sender.close(code, data, !this._isServer, (err3) => {
90021
90084
  if (err3) return;
90022
90085
  this._closeFrameSent = true;
@@ -90024,7 +90087,6 @@ var require_websocket = __commonJS({
90024
90087
  this._socket.end();
90025
90088
  }
90026
90089
  });
90027
- this._readyState = _WebSocket.CLOSING;
90028
90090
  setCloseTimer(this);
90029
90091
  }
90030
90092
  /**
@@ -90249,7 +90311,6 @@ var require_websocket = __commonJS({
90249
90311
  socketPath: void 0,
90250
90312
  hostname: void 0,
90251
90313
  protocol: void 0,
90252
- protocols: void 0,
90253
90314
  timeout: void 0,
90254
90315
  method: "GET",
90255
90316
  host: void 0,
@@ -159917,13 +159978,13 @@ __export(pi_messages_exports, {
159917
159978
  stream: () => stream10,
159918
159979
  streamSimple: () => streamSimple9
159919
159980
  });
159920
- function isRecord4(value) {
159981
+ function isRecord5(value) {
159921
159982
  return typeof value === "object" && value !== null && !Array.isArray(value);
159922
159983
  }
159923
159984
  function parsePiMessagesErrorBody(body) {
159924
159985
  try {
159925
159986
  const parsed = JSON.parse(body);
159926
- return isRecord4(parsed) && isRecord4(parsed.error) ? parsed : void 0;
159987
+ return isRecord5(parsed) && isRecord5(parsed.error) ? parsed : void 0;
159927
159988
  } catch {
159928
159989
  return void 0;
159929
159990
  }
@@ -196938,14 +196999,14 @@ var init_openrouter = __esm({
196938
196999
  });
196939
197000
 
196940
197001
  // ../../node_modules/@earendil-works/pi-ai/dist/providers/radius-config.js
196941
- function isRecord5(value) {
197002
+ function isRecord6(value) {
196942
197003
  return typeof value === "object" && value !== null && !Array.isArray(value);
196943
197004
  }
196944
197005
  function isRadiusGatewayModel(value) {
196945
- return isRecord5(value) && typeof value.id === "string" && typeof value.name === "string" && typeof value.reasoning === "boolean" && Array.isArray(value.input) && isRecord5(value.cost) && typeof value.contextWindow === "number" && typeof value.maxTokens === "number";
197006
+ return isRecord6(value) && typeof value.id === "string" && typeof value.name === "string" && typeof value.reasoning === "boolean" && Array.isArray(value.input) && isRecord6(value.cost) && typeof value.contextWindow === "number" && typeof value.maxTokens === "number";
196946
197007
  }
196947
197008
  function sanitizeRadiusGatewayConfig(config2) {
196948
- if (!isRecord5(config2) || typeof config2.baseUrl !== "string" || !Array.isArray(config2.models))
197009
+ if (!isRecord6(config2) || typeof config2.baseUrl !== "string" || !Array.isArray(config2.models))
196949
197010
  return void 0;
196950
197011
  return {
196951
197012
  baseUrl: config2.baseUrl,
@@ -206639,14 +206700,14 @@ function getToolUiStatusEnabledNames(descriptors) {
206639
206700
  }
206640
206701
  function decorateToolParametersWithUiStatus(value) {
206641
206702
  const parameters = normalizeParameters(value);
206642
- if (!isRecord6(parameters) || parameters.type !== "object") {
206703
+ if (!isRecord7(parameters) || parameters.type !== "object") {
206643
206704
  return { parameters, enabled: false };
206644
206705
  }
206645
206706
  if ([...UNSAFE_TOOL_SCHEMA_KEYS].some((key) => key in parameters)) {
206646
206707
  return { parameters, enabled: false };
206647
206708
  }
206648
206709
  const properties = parameters.properties;
206649
- if (properties !== void 0 && !isRecord6(properties)) {
206710
+ if (properties !== void 0 && !isRecord7(properties)) {
206650
206711
  return { parameters, enabled: false };
206651
206712
  }
206652
206713
  const required2 = parameters.required;
@@ -206665,12 +206726,12 @@ function decorateToolParametersWithUiStatus(value) {
206665
206726
  };
206666
206727
  }
206667
206728
  function stripToolUiStatusArgument(value) {
206668
- if (!isRecord6(value) || !(TOOL_UI_STATUS_ARGUMENT in value))
206729
+ if (!isRecord7(value) || !(TOOL_UI_STATUS_ARGUMENT in value))
206669
206730
  return value;
206670
206731
  const { [TOOL_UI_STATUS_ARGUMENT]: _status, ...args } = value;
206671
206732
  return args;
206672
206733
  }
206673
- function isRecord6(value) {
206734
+ function isRecord7(value) {
206674
206735
  return typeof value === "object" && value !== null && !Array.isArray(value);
206675
206736
  }
206676
206737
  function normalizeParameters(value) {
@@ -206800,55 +206861,6 @@ var init_testProvider = __esm({
206800
206861
  }
206801
206862
  });
206802
206863
 
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
-
206852
206864
  // ../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/anthropicProvider.js
206853
206865
  function createApiKeyAuth(authName, fixedApiKey) {
206854
206866
  return {
@@ -206871,7 +206883,7 @@ function createAnthropicProvider(options) {
206871
206883
  auth: { apiKey: createApiKeyAuth(authName, fixedApiKey) },
206872
206884
  models,
206873
206885
  // 复用 pi-ai 内置的 Anthropic Messages 协议实现(含 stream/SSE 逻辑)
206874
- api: options.modelFetch ? createTransportAnthropicApi(options.modelFetch) : anthropicMessagesApi()
206886
+ api: anthropicMessagesApi()
206875
206887
  });
206876
206888
  }
206877
206889
  function buildAnthropicModel(providerId, baseUrl, descriptor) {
@@ -206895,7 +206907,6 @@ var init_anthropicProvider = __esm({
206895
206907
  "../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/anthropicProvider.js"() {
206896
206908
  "use strict";
206897
206909
  init_compat2();
206898
- init_transportAnthropicApi();
206899
206910
  }
206900
206911
  });
206901
206912
 
@@ -206906,14 +206917,13 @@ function createLinkqueModel(modelId, baseUrl = LINKQUE_DEFAULT_BASE_URL) {
206906
206917
  id: modelId
206907
206918
  });
206908
206919
  }
206909
- function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL, modelFetch) {
206920
+ function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL) {
206910
206921
  return createAnthropicProvider({
206911
206922
  providerId: LINKQUE_PROVIDER_ID,
206912
206923
  providerName: "Linkque",
206913
206924
  baseUrl,
206914
206925
  models: LINKQUE_MODELS,
206915
- authName: "Linkque API key",
206916
- modelFetch
206926
+ authName: "Linkque API key"
206917
206927
  });
206918
206928
  }
206919
206929
  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;
@@ -207230,7 +207240,7 @@ var init_agentService = __esm({
207230
207240
  async startSession() {
207231
207241
  const models = createModels();
207232
207242
  const providerId = providerIdFor(this.auth.provider);
207233
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, this.auth.modelFetch));
207243
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
207234
207244
  models.setProvider(createTestProvider().provider);
207235
207245
  let model;
207236
207246
  if (this.options.model !== void 0) {
@@ -207444,7 +207454,7 @@ var init_followUpQuestionGenerator = __esm({
207444
207454
  }
207445
207455
  async generate(input) {
207446
207456
  const models = this.modelsFactory();
207447
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, input.auth.modelFetch));
207457
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
207448
207458
  let model = models.getModel(LINKQUE_PROVIDER_ID, FOLLOW_UP_QUESTION_MODEL_ID);
207449
207459
  model ??= createLinkqueModel(FOLLOW_UP_QUESTION_MODEL_ID, this.linkqueBaseUrl);
207450
207460
  model = {
@@ -207991,29 +208001,6 @@ var init_types12 = __esm({
207991
208001
  }
207992
208002
  });
207993
208003
 
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
-
208017
208004
  // ../linkque-agent-runtime/dist/esm/core/agentRuntimePlugin.js
208018
208005
  function assertAgentConfigRoot(value, pluginName) {
208019
208006
  if (typeof value !== "object" || value === null || !("agent" in value)) {
@@ -209283,7 +209270,6 @@ var init_agentRuntime = __esm({
209283
209270
  init_runtimeErrorBoundary();
209284
209271
  init_toolObservation();
209285
209272
  init_types12();
209286
- init_scenarioRunAuthorization();
209287
209273
  init_esm();
209288
209274
  init_types();
209289
209275
  init_followUpQuestionGenerator();
@@ -209463,28 +209449,6 @@ var init_agentRuntime = __esm({
209463
209449
  }
209464
209450
  /** 产出 AgentStreamEvent 流;内核编排「解析上行资源 → 组请求 → agent loop」。 */
209465
209451
  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
- }
209488
209452
  const input = {
209489
209453
  runId: request.runId,
209490
209454
  agentId: options.runtimeContext?.agentId ?? this.agentId,
@@ -210070,8 +210034,6 @@ async function* runConversation(request, auth2, options = {}) {
210070
210034
  const ports = options.agentLoop ? { agentLoop: options.agentLoop } : void 0;
210071
210035
  const runtime = options.runtime ?? (options.protocol ? AgentRuntime.create(options.protocol, ports) : new AgentRuntime(ports));
210072
210036
  const runOptions = {};
210073
- if (options.runAuthorization)
210074
- runOptions.runAuthorization = options.runAuthorization;
210075
210037
  if (options.sessionId !== void 0)
210076
210038
  runOptions.sessionId = options.sessionId;
210077
210039
  if (options.cwd !== void 0)
@@ -210386,7 +210348,6 @@ async function waitForObservation(promise2, signal) {
210386
210348
  function createImageTool(image, input, options, rules) {
210387
210349
  const fetchImpl = options.fetchImpl ?? globalThis.fetch;
210388
210350
  const auth2 = { ...input.auth };
210389
- const modelFetch = auth2.modelFetch ?? fetchImpl;
210390
210351
  const cache = /* @__PURE__ */ new Map();
210391
210352
  let calls = 0;
210392
210353
  return {
@@ -210426,7 +210387,7 @@ function createImageTool(image, input, options, rules) {
210426
210387
  const pending = (async () => {
210427
210388
  try {
210428
210389
  const resolved = await resolveImage(image, fetchImpl, rules, signal);
210429
- const response = await modelFetch(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
210390
+ const response = await fetchImpl(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
210430
210391
  method: "POST",
210431
210392
  signal,
210432
210393
  redirect: "error",
@@ -212995,9 +212956,6 @@ var Protocol = class {
212995
212956
  this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
212996
212957
  const handleTaskResult = async () => {
212997
212958
  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
- }
213001
212959
  if (this._taskMessageQueue) {
213002
212960
  let queuedMessage;
213003
212961
  while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
@@ -213028,12 +212986,12 @@ var Protocol = class {
213028
212986
  throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
213029
212987
  }
213030
212988
  if (!isTerminal(task.status)) {
213031
- await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
212989
+ await this._waitForTaskUpdate(taskId, extra.signal);
213032
212990
  return await handleTaskResult();
213033
212991
  }
213034
212992
  if (isTerminal(task.status)) {
213035
212993
  const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
213036
- this._clearTaskQueue(taskId, extra.sessionId);
212994
+ this._clearTaskQueue(taskId);
213037
212995
  return {
213038
212996
  ...result,
213039
212997
  _meta: {
@@ -213070,7 +213028,7 @@ var Protocol = class {
213070
213028
  throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
213071
213029
  }
213072
213030
  await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
213073
- this._clearTaskQueue(request.params.taskId, extra.sessionId);
213031
+ this._clearTaskQueue(request.params.taskId);
213074
213032
  const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
213075
213033
  if (!cancelledTask) {
213076
213034
  throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
@@ -213198,19 +213156,6 @@ var Protocol = class {
213198
213156
  const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
213199
213157
  const capturedTransport = this._transport;
213200
213158
  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
- }
213214
213159
  if (handler === void 0) {
213215
213160
  const errorResponse = {
213216
213161
  jsonrpc: "2.0",
@@ -213220,10 +213165,7 @@ var Protocol = class {
213220
213165
  message: "Method not found"
213221
213166
  }
213222
213167
  };
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) {
213168
+ if (relatedTaskId && this._taskMessageQueue) {
213227
213169
  this._enqueueTaskMessage(relatedTaskId, {
213228
213170
  type: "error",
213229
213171
  message: errorResponse,
@@ -213274,10 +213216,7 @@ var Protocol = class {
213274
213216
  closeSSEStream: extra?.closeSSEStream,
213275
213217
  closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
213276
213218
  };
213277
- (relatedTaskLookup ?? Promise.resolve()).then(() => {
213278
- if (relatedTaskLookup && abortController.signal.aborted) {
213279
- throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
213280
- }
213219
+ Promise.resolve().then(() => {
213281
213220
  if (taskCreationParams) {
213282
213221
  this.assertTaskHandlerCapability(request.method);
213283
213222
  }
@@ -213312,7 +213251,7 @@ var Protocol = class {
213312
213251
  ...error40["data"] !== void 0 && { data: error40["data"] }
213313
213252
  }
213314
213253
  };
213315
- if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
213254
+ if (relatedTaskId && this._taskMessageQueue) {
213316
213255
  await this._enqueueTaskMessage(relatedTaskId, {
213317
213256
  type: "error",
213318
213257
  message: errorResponse,
@@ -213792,7 +213731,7 @@ var Protocol = class {
213792
213731
  throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
213793
213732
  }
213794
213733
  const maxQueueSize = this._options?.maxTaskQueueSize;
213795
- await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
213734
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
213796
213735
  }
213797
213736
  /**
213798
213737
  * Clears the message queue for a task and rejects any pending request resolvers.
@@ -213821,13 +213760,12 @@ var Protocol = class {
213821
213760
  * Uses polling to check for updates at the task's configured poll interval.
213822
213761
  * @param taskId The task ID to wait for
213823
213762
  * @param signal Abort signal to cancel the wait
213824
- * @param sessionId Session of the request that waits, passed to the task store
213825
213763
  * @returns Promise that resolves when an update occurs or rejects if aborted
213826
213764
  */
213827
- async _waitForTaskUpdate(taskId, signal, sessionId) {
213765
+ async _waitForTaskUpdate(taskId, signal) {
213828
213766
  let interval = this._options?.defaultTaskPollInterval ?? 1e3;
213829
213767
  try {
213830
- const task = await this._taskStore?.getTask(taskId, sessionId);
213768
+ const task = await this._taskStore?.getTask(taskId);
213831
213769
  if (task?.pollInterval) {
213832
213770
  interval = task.pollInterval;
213833
213771
  }
@@ -215467,68 +215405,6 @@ function createFetchWithInit(baseFetch = fetch, baseInit) {
215467
215405
  return baseFetch(url2, mergedInit);
215468
215406
  };
215469
215407
  }
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
- }
215532
215408
 
215533
215409
  // ../../node_modules/pkce-challenge/dist/index.node.js
215534
215410
  var crypto2;
@@ -215676,12 +215552,7 @@ var OAuthTokensSchema = object2({
215676
215552
  token_type: string2(),
215677
215553
  expires_in: coerce_exports.number().optional(),
215678
215554
  scope: 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)
215555
+ refresh_token: string2().optional()
215685
215556
  }).strip();
215686
215557
  var OAuthErrorResponseSchema = object2({
215687
215558
  error: string2(),
@@ -215711,12 +215582,7 @@ var OAuthClientInformationSchema = object2({
215711
215582
  client_id: string2(),
215712
215583
  client_secret: string2().optional(),
215713
215584
  client_id_issued_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)
215585
+ client_secret_expires_at: number2().optional()
215720
215586
  }).strip();
215721
215587
  var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
215722
215588
  var OAuthClientRegistrationErrorSchema = object2({
@@ -215914,31 +215780,10 @@ async function parseErrorResponse(input) {
215914
215780
  const errorClass = OAUTH_ERRORS[error40] || ServerError;
215915
215781
  return new errorClass(error_description || "", error_uri);
215916
215782
  } catch (error40) {
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}`}`;
215783
+ const errorMessage4 = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error40}. Raw body: ${body}`;
215919
215784
  return new ServerError(errorMessage4);
215920
215785
  }
215921
215786
  }
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
- }
215942
215787
  async function auth(provider, options) {
215943
215788
  try {
215944
215789
  return await authInternal(provider, options);
@@ -215992,24 +215837,9 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215992
215837
  authorizationServerMetadata: metadata
215993
215838
  });
215994
215839
  }
215995
- const issuer = String(authorizationServerUrl);
215996
- const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);
215997
- const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;
215840
+ const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
215998
215841
  const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
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
- };
215842
+ let clientInformation = await Promise.resolve(provider.clientInformation());
216013
215843
  if (!clientInformation) {
216014
215844
  if (authorizationCode !== void 0) {
216015
215845
  throw new Error("Existing OAuth client information is required when exchanging an authorization code");
@@ -216021,7 +215851,9 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
216021
215851
  }
216022
215852
  const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
216023
215853
  if (shouldUseUrlBasedClientId) {
216024
- clientInformation = { client_id: clientMetadataUrl, issuer };
215854
+ clientInformation = {
215855
+ client_id: clientMetadataUrl
215856
+ };
216025
215857
  await provider.saveClientInformation?.(clientInformation);
216026
215858
  } else {
216027
215859
  if (!provider.saveClientInformation) {
@@ -216033,8 +215865,8 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
216033
215865
  scope: resolvedScope,
216034
215866
  fetchFn
216035
215867
  });
216036
- clientInformation = { ...fullInformation, issuer };
216037
- await provider.saveClientInformation(clientInformation);
215868
+ await provider.saveClientInformation(fullInformation);
215869
+ clientInformation = fullInformation;
216038
215870
  }
216039
215871
  }
216040
215872
  const nonInteractiveFlow = !provider.redirectUrl;
@@ -216045,14 +215877,10 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
216045
215877
  authorizationCode,
216046
215878
  fetchFn
216047
215879
  });
216048
- await bindClientInformation();
216049
- await provider.saveTokens({ ...tokens2, issuer });
215880
+ await provider.saveTokens(tokens2);
216050
215881
  return "AUTHORIZED";
216051
215882
  }
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
- }
215883
+ const tokens = await provider.tokens();
216056
215884
  if (tokens?.refresh_token) {
216057
215885
  try {
216058
215886
  const newTokens = await refreshAuthorization(authorizationServerUrl, {
@@ -216063,8 +215891,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
216063
215891
  addClientAuthentication: provider.addClientAuthentication,
216064
215892
  fetchFn
216065
215893
  });
216066
- await bindClientInformation();
216067
- await provider.saveTokens({ ...newTokens, issuer });
215894
+ await provider.saveTokens(newTokens);
216068
215895
  return "AUTHORIZED";
216069
215896
  } catch (error40) {
216070
215897
  if (!(error40 instanceof OAuthError) || error40 instanceof ServerError) {
@@ -216163,7 +215990,7 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
216163
215990
  }
216164
215991
  async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
216165
215992
  try {
216166
- return await fetchWithinOrigin(fetchFn)(url2, { headers });
215993
+ return await fetchFn(url2, { headers });
216167
215994
  } catch (error40) {
216168
215995
  if (error40 instanceof TypeError) {
216169
215996
  if (headers) {
@@ -216188,7 +216015,7 @@ async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
216188
216015
  return await fetchWithCorsRetry(url2, headers, fetchFn);
216189
216016
  }
216190
216017
  function shouldAttemptFallback(response, pathname) {
216191
- return !response || !response.ok && response.status < 500 && pathname !== "/";
216018
+ return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
216192
216019
  }
216193
216020
  async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
216194
216021
  const issuer = new URL(serverUrl);
@@ -216254,7 +216081,7 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fet
216254
216081
  }
216255
216082
  if (!response.ok) {
216256
216083
  await response.body?.cancel();
216257
- if (response.status < 500) {
216084
+ if (response.status >= 400 && response.status < 500) {
216258
216085
  continue;
216259
216086
  }
216260
216087
  throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
@@ -216287,9 +216114,6 @@ async function discoverOAuthServerInfo(serverUrl, opts) {
216287
216114
  resourceMetadata
216288
216115
  };
216289
216116
  }
216290
- function resourceIndicatorToString(resource) {
216291
- return typeof resource === "string" ? resource : resource.href;
216292
- }
216293
216117
  async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state: state2, resource }) {
216294
216118
  let authorizationUrl;
216295
216119
  if (metadata) {
@@ -216321,7 +216145,7 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
216321
216145
  authorizationUrl.searchParams.append("prompt", "consent");
216322
216146
  }
216323
216147
  if (resource) {
216324
- authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource));
216148
+ authorizationUrl.searchParams.set("resource", resource.href);
216325
216149
  }
216326
216150
  return { authorizationUrl, codeVerifier };
216327
216151
  }
@@ -216340,7 +216164,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
216340
216164
  Accept: "application/json"
216341
216165
  });
216342
216166
  if (resource) {
216343
- tokenRequestParams.set("resource", resourceIndicatorToString(resource));
216167
+ tokenRequestParams.set("resource", resource.href);
216344
216168
  }
216345
216169
  if (addClientAuthentication) {
216346
216170
  await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
@@ -216349,7 +216173,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
216349
216173
  const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
216350
216174
  applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
216351
216175
  }
216352
- const response = await fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {
216176
+ const response = await (fetchFn ?? fetch)(tokenUrl, {
216353
216177
  method: "POST",
216354
216178
  headers,
216355
216179
  body: tokenRequestParams
@@ -216357,7 +216181,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
216357
216181
  if (!response.ok) {
216358
216182
  throw await parseErrorResponse(response);
216359
216183
  }
216360
- return TokenResponseSchema.parse(await response.json());
216184
+ return OAuthTokensSchema.parse(await response.json());
216361
216185
  }
216362
216186
  async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
216363
216187
  const tokenRequestParams = new URLSearchParams({
@@ -216375,15 +216199,6 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
216375
216199
  return { refresh_token: refreshToken, ...tokens };
216376
216200
  }
216377
216201
  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();
216387
216202
  const scope = provider.clientMetadata.scope;
216388
216203
  let tokenRequestParams;
216389
216204
  if (provider.prepareTokenRequest) {
@@ -216399,11 +216214,11 @@ async function fetchToken(provider, authorizationServerUrl, { metadata, resource
216399
216214
  const codeVerifier = await provider.codeVerifier();
216400
216215
  tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
216401
216216
  }
216402
- clientInformation ?? (clientInformation = await readClientInformation());
216217
+ const clientInformation = await provider.clientInformation();
216403
216218
  return executeTokenRequest(authorizationServerUrl, {
216404
216219
  metadata,
216405
216220
  tokenRequestParams,
216406
- clientInformation,
216221
+ clientInformation: clientInformation ?? void 0,
216407
216222
  addClientAuthentication: provider.addClientAuthentication,
216408
216223
  resource,
216409
216224
  fetchFn
@@ -216419,7 +216234,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
216419
216234
  } else {
216420
216235
  registrationUrl = new URL("/register", authorizationServerUrl);
216421
216236
  }
216422
- const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {
216237
+ const response = await (fetchFn ?? fetch)(registrationUrl, {
216423
216238
  method: "POST",
216424
216239
  headers: {
216425
216240
  "Content-Type": "application/json"
@@ -216432,7 +216247,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
216432
216247
  if (!response.ok) {
216433
216248
  throw await parseErrorResponse(response);
216434
216249
  }
216435
- return RegistrationResponseSchema.parse(await response.json());
216250
+ return OAuthClientInformationFullSchema.parse(await response.json());
216436
216251
  }
216437
216252
 
216438
216253
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
@@ -216453,16 +216268,6 @@ var SSEClientTransport = class {
216453
216268
  this._authProvider = opts?.authProvider;
216454
216269
  this._fetch = opts?.fetch;
216455
216270
  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;
216466
216271
  }
216467
216272
  async _authThenStart() {
216468
216273
  if (!this._authProvider) {
@@ -216503,9 +216308,7 @@ var SSEClientTransport = class {
216503
216308
  });
216504
216309
  }
216505
216310
  _startOrAuth() {
216506
- const baseFetch = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
216507
- const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);
216508
- let redirect;
216311
+ const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
216509
216312
  return new Promise((resolve, reject) => {
216510
216313
  this._eventSource = new EventSource(this._url.href, {
216511
216314
  ...this._eventSourceInit,
@@ -216516,7 +216319,6 @@ var SSEClientTransport = class {
216516
216319
  ...init,
216517
216320
  headers
216518
216321
  });
216519
- redirect = this._unfollowedRedirect(response, url2);
216520
216322
  if (response.status === 401 && response.headers.has("www-authenticate")) {
216521
216323
  const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
216522
216324
  this._resourceMetadataUrl = resourceMetadataUrl;
@@ -216531,7 +216333,7 @@ var SSEClientTransport = class {
216531
216333
  this._authThenStart().then(resolve, reject);
216532
216334
  return;
216533
216335
  }
216534
- const error40 = new SseError(event.code, redirect ?? event.message, event);
216336
+ const error40 = new SseError(event.code, event.message, event);
216535
216337
  reject(error40);
216536
216338
  this.onerror?.(error40);
216537
216339
  };
@@ -216608,7 +216410,7 @@ var SSEClientTransport = class {
216608
216410
  body: JSON.stringify(message),
216609
216411
  signal: this._abortController?.signal
216610
216412
  };
216611
- const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);
216413
+ const response = await (this._fetch ?? fetch)(this._endpoint, init);
216612
216414
  if (!response.ok) {
216613
216415
  const text2 = await response.text().catch(() => null);
216614
216416
  if (response.status === 401 && this._authProvider) {
@@ -216626,7 +216428,7 @@ var SSEClientTransport = class {
216626
216428
  }
216627
216429
  return this.send(message);
216628
216430
  }
216629
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text2}`);
216431
+ throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text2}`);
216630
216432
  }
216631
216433
  await response.body?.cancel();
216632
216434
  } catch (error40) {
@@ -217541,7 +217343,7 @@ var LocalHttpMcpServerProvider = class {
217541
217343
  listTools: async (signal) => {
217542
217344
  const response = await this.fetchImpl(toolsUrl, { signal });
217543
217345
  const body = await readJsonResponse(response);
217544
- if (!isRecord2(body) || !Array.isArray(body.tools)) {
217346
+ if (!isRecord3(body) || !Array.isArray(body.tools)) {
217545
217347
  throw new Error(`Invalid local MCP tool catalog for ${resource.resourceId}`);
217546
217348
  }
217547
217349
  return body.tools.map((value) => this.createDescriptor(resource.resourceId, value));
@@ -217550,16 +217352,16 @@ var LocalHttpMcpServerProvider = class {
217550
217352
  };
217551
217353
  }
217552
217354
  createDescriptor(resourceId, value) {
217553
- if (!isRecord2(value) || typeof value.name !== "string") {
217355
+ if (!isRecord3(value) || typeof value.name !== "string") {
217554
217356
  throw new Error(`Invalid local MCP tool descriptor for ${resourceId}`);
217555
217357
  }
217556
217358
  return {
217557
217359
  name: value.name,
217558
217360
  resourceId,
217559
217361
  ...typeof value.description === "string" ? { description: value.description } : {},
217560
- ...isRecord2(value.inputSchema) ? { inputSchema: value.inputSchema } : {},
217561
- ...isRecord2(value.outputSchema) ? { outputSchema: value.outputSchema } : {},
217562
- ...isRecord2(value.annotations) ? { annotations: value.annotations } : {},
217362
+ ...isRecord3(value.inputSchema) ? { inputSchema: value.inputSchema } : {},
217363
+ ...isRecord3(value.outputSchema) ? { outputSchema: value.outputSchema } : {},
217364
+ ...isRecord3(value.annotations) ? { annotations: value.annotations } : {},
217563
217365
  execute: (args, signal, context2) => this.callTool(resourceId, value.name, args, signal, {
217564
217366
  context: context2,
217565
217367
  toolSchema: {
@@ -217591,7 +217393,7 @@ async function readJsonResponse(response) {
217591
217393
  const raw = await response.json().catch(() => void 0);
217592
217394
  const value = raw === void 0 ? void 0 : JSON.parse(JSON.stringify(raw));
217593
217395
  if (!response.ok) {
217594
- const message = isRecord2(value) && typeof value.message === "string" ? value.message : `Local MCP fixture request failed with ${response.status}`;
217396
+ const message = isRecord3(value) && typeof value.message === "string" ? value.message : `Local MCP fixture request failed with ${response.status}`;
217595
217397
  throw new Error(message);
217596
217398
  }
217597
217399
  return value;
@@ -217602,7 +217404,7 @@ function ensureTrailingSlash(url2) {
217602
217404
  next.pathname += "/";
217603
217405
  return next;
217604
217406
  }
217605
- function isRecord2(value) {
217407
+ function isRecord3(value) {
217606
217408
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
217607
217409
  }
217608
217410
 
@@ -220285,10 +220087,10 @@ var handleFunctionActionMcp = async (req, res, input) => {
220285
220087
  }
220286
220088
  };
220287
220089
  var parseHomeDataProxyInput = (value) => {
220288
- const trustedContext = isRecord7(value) ? value[HOME_DATA_TRUSTED_CONTEXT_FIELD] : void 0;
220289
- const trustedUserId = isRecord7(trustedContext) ? trustedContext.userId : void 0;
220090
+ const trustedContext = isRecord8(value) ? value[HOME_DATA_TRUSTED_CONTEXT_FIELD] : void 0;
220091
+ const trustedUserId = isRecord8(trustedContext) ? trustedContext.userId : void 0;
220290
220092
  const normalizedUserId = typeof trustedUserId === "string" ? trustedUserId.trim() : "";
220291
- if (!isRecord7(value) || !normalizedUserId) {
220093
+ if (!isRecord8(value) || !normalizedUserId) {
220292
220094
  throw new Error("home-data trusted user is invalid");
220293
220095
  }
220294
220096
  const request = { ...value };
@@ -220296,9 +220098,9 @@ var parseHomeDataProxyInput = (value) => {
220296
220098
  return { request, userId: normalizedUserId };
220297
220099
  };
220298
220100
  var parseFunctionActionMcpProxyInput = (value) => {
220299
- if (!isRecord7(value)) throw new Error("function action request is invalid");
220101
+ if (!isRecord8(value)) throw new Error("function action request is invalid");
220300
220102
  const trustedContext = value._trustedContext_;
220301
- const userId = isRecord7(trustedContext) && typeof trustedContext.userId === "string" ? trustedContext.userId.trim() : "";
220103
+ const userId = isRecord8(trustedContext) && typeof trustedContext.userId === "string" ? trustedContext.userId.trim() : "";
220302
220104
  if (!userId) {
220303
220105
  throw new Error("function action trusted context is invalid");
220304
220106
  }
@@ -220310,7 +220112,7 @@ var writeJson = (res, status, value) => {
220310
220112
  res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
220311
220113
  res.end(JSON.stringify(value));
220312
220114
  };
220313
- var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
220115
+ var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
220314
220116
  var errorMessage3 = (error40) => error40 instanceof Error ? error40.message : "unknown agent error";
220315
220117
  var main = async () => {
220316
220118
  const input = decodeInput();