linkque-cli-v2 1.6.9 → 1.6.10

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 (17) hide show
  1. package/linkquejs.js +110 -3
  2. package/package.json +1 -1
  3. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-BJXGRRWL.js → chunk-P7NPWFEB.js} +1 -1
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-DNTEEBEH.js → chunk-SICWMO5Y.js} +1 -0
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-NJKO34ZC.js → chunk-UPH5CD2J.js} +632 -558
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-HGKCCOSQ.js → chunk-YODH5M5T.js} +26 -1
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-bsd-JGCLGHFY.js → getMachineId-bsd-NYGVHXGN.js} +1 -1
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-darwin-COHLFNXH.js → getMachineId-darwin-OPTJOAYC.js} +1 -1
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-linux-XV3Z5FQG.js → getMachineId-linux-5SQRYTUJ.js} +1 -1
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-unsupported-FCRKLIZL.js → getMachineId-unsupported-OJE7WPEH.js} +1 -1
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-win-A4WRNVV6.js → getMachineId-win-SLTTCNXU.js} +1 -1
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-OEOTQWE5.js → mistral-conversations-C43A6QIS.js} +1 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{otel-WGS5CC2J.js → otel-RUUFBBFE.js} +1 -1
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +26 -13
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +3 -3
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +3 -3
  17. package/worker.js +739 -666
package/worker.js CHANGED
@@ -33781,6 +33781,110 @@ var init_abortableDelay = __esm({
33781
33781
  }
33782
33782
  });
33783
33783
 
33784
+ // ../../node_modules/content-type/index.js
33785
+ var require_content_type = __commonJS({
33786
+ "../../node_modules/content-type/index.js"(exports2) {
33787
+ "use strict";
33788
+ var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
33789
+ var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/;
33790
+ var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
33791
+ var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
33792
+ var QUOTE_REGEXP = /([\\"])/g;
33793
+ var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
33794
+ exports2.format = format;
33795
+ exports2.parse = parse5;
33796
+ function format(obj) {
33797
+ if (!obj || typeof obj !== "object") {
33798
+ throw new TypeError("argument obj is required");
33799
+ }
33800
+ var parameters = obj.parameters;
33801
+ var type = obj.type;
33802
+ if (!type || !TYPE_REGEXP.test(type)) {
33803
+ throw new TypeError("invalid type");
33804
+ }
33805
+ var string4 = type;
33806
+ if (parameters && typeof parameters === "object") {
33807
+ var param;
33808
+ var params = Object.keys(parameters).sort();
33809
+ for (var i2 = 0; i2 < params.length; i2++) {
33810
+ param = params[i2];
33811
+ if (!TOKEN_REGEXP.test(param)) {
33812
+ throw new TypeError("invalid parameter name");
33813
+ }
33814
+ string4 += "; " + param + "=" + qstring(parameters[param]);
33815
+ }
33816
+ }
33817
+ return string4;
33818
+ }
33819
+ function parse5(string4) {
33820
+ if (!string4) {
33821
+ throw new TypeError("argument string is required");
33822
+ }
33823
+ var header = typeof string4 === "object" ? getcontenttype(string4) : string4;
33824
+ if (typeof header !== "string") {
33825
+ throw new TypeError("argument string is required to be a string");
33826
+ }
33827
+ var index2 = header.indexOf(";");
33828
+ var type = index2 !== -1 ? header.slice(0, index2).trim() : header.trim();
33829
+ if (!TYPE_REGEXP.test(type)) {
33830
+ throw new TypeError("invalid media type");
33831
+ }
33832
+ var obj = new ContentType(type.toLowerCase());
33833
+ if (index2 !== -1) {
33834
+ var key;
33835
+ var match2;
33836
+ var value;
33837
+ PARAM_REGEXP.lastIndex = index2;
33838
+ while (match2 = PARAM_REGEXP.exec(header)) {
33839
+ if (match2.index !== index2) {
33840
+ throw new TypeError("invalid parameter format");
33841
+ }
33842
+ index2 += match2[0].length;
33843
+ key = match2[1].toLowerCase();
33844
+ value = match2[2];
33845
+ if (value.charCodeAt(0) === 34) {
33846
+ value = value.slice(1, -1);
33847
+ if (value.indexOf("\\") !== -1) {
33848
+ value = value.replace(QESC_REGEXP, "$1");
33849
+ }
33850
+ }
33851
+ obj.parameters[key] = value;
33852
+ }
33853
+ if (index2 !== header.length) {
33854
+ throw new TypeError("invalid parameter format");
33855
+ }
33856
+ }
33857
+ return obj;
33858
+ }
33859
+ function getcontenttype(obj) {
33860
+ var header;
33861
+ if (typeof obj.getHeader === "function") {
33862
+ header = obj.getHeader("content-type");
33863
+ } else if (typeof obj.headers === "object") {
33864
+ header = obj.headers && obj.headers["content-type"];
33865
+ }
33866
+ if (typeof header !== "string") {
33867
+ throw new TypeError("content-type header is missing from object");
33868
+ }
33869
+ return header;
33870
+ }
33871
+ function qstring(val) {
33872
+ var str2 = String(val);
33873
+ if (TOKEN_REGEXP.test(str2)) {
33874
+ return str2;
33875
+ }
33876
+ if (str2.length > 0 && !TEXT_REGEXP.test(str2)) {
33877
+ throw new TypeError("invalid parameter value");
33878
+ }
33879
+ return '"' + str2.replace(QUOTE_REGEXP, "\\$1") + '"';
33880
+ }
33881
+ function ContentType(type) {
33882
+ this.parameters = /* @__PURE__ */ Object.create(null);
33883
+ this.type = type;
33884
+ }
33885
+ }
33886
+ });
33887
+
33784
33888
  // ../../node_modules/zod/index.js
33785
33889
  var init_zod = __esm({
33786
33890
  "../../node_modules/zod/index.js"() {
@@ -42091,7 +42195,7 @@ var require_RandomIdGenerator = __commonJS({
42091
42195
  exports2.RandomIdGenerator = void 0;
42092
42196
  var SPAN_ID_BYTES = 8;
42093
42197
  var TRACE_ID_BYTES = 16;
42094
- var RandomIdGenerator = class {
42198
+ var RandomIdGenerator2 = class {
42095
42199
  /**
42096
42200
  * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
42097
42201
  * characters corresponding to 128 bits.
@@ -42103,7 +42207,7 @@ var require_RandomIdGenerator = __commonJS({
42103
42207
  */
42104
42208
  generateSpanId = getIdGenerator(SPAN_ID_BYTES);
42105
42209
  };
42106
- exports2.RandomIdGenerator = RandomIdGenerator;
42210
+ exports2.RandomIdGenerator = RandomIdGenerator2;
42107
42211
  var SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
42108
42212
  function getIdGenerator(bytes2) {
42109
42213
  return function generateId() {
@@ -52012,8 +52116,8 @@ async function defaultParseResponse(client, props) {
52012
52116
  if (props.options.__binaryResponse) {
52013
52117
  return response;
52014
52118
  }
52015
- const contentType = response.headers.get("content-type");
52016
- const mediaType = contentType?.split(";")[0]?.trim();
52119
+ const contentType2 = response.headers.get("content-type");
52120
+ const mediaType = contentType2?.split(";")[0]?.trim();
52017
52121
  const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
52018
52122
  if (isJSON) {
52019
52123
  const contentLength = response.headers.get("content-length");
@@ -52318,9 +52422,9 @@ var init_uploads = __esm({
52318
52422
  form.append(key, String(value));
52319
52423
  } else if (value instanceof Response) {
52320
52424
  let options = {};
52321
- const contentType = value.headers.get("Content-Type");
52322
- if (contentType) {
52323
- options = { type: contentType };
52425
+ const contentType2 = value.headers.get("Content-Type");
52426
+ if (contentType2) {
52427
+ options = { type: contentType2 };
52324
52428
  }
52325
52429
  form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options));
52326
52430
  } else if (isAsyncIterable(value)) {
@@ -61449,8 +61553,8 @@ async function defaultParseResponse2(client, props) {
61449
61553
  if (props.options.__binaryResponse) {
61450
61554
  return response;
61451
61555
  }
61452
- const contentType = response.headers.get("content-type");
61453
- const mediaType = contentType?.split(";")[0]?.trim();
61556
+ const contentType2 = response.headers.get("content-type");
61557
+ const mediaType = contentType2?.split(";")[0]?.trim();
61454
61558
  const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
61455
61559
  if (isJSON) {
61456
61560
  const contentLength = response.headers.get("content-length");
@@ -74904,7 +75008,7 @@ var require_ponyfill_es2018 = __commonJS({
74904
75008
  assertFunction(fn, context2);
74905
75009
  return (reason) => promiseCall(fn, original, [reason]);
74906
75010
  }
74907
- class TransformStream {
75011
+ class TransformStream2 {
74908
75012
  constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
74909
75013
  if (rawTransformer === void 0) {
74910
75014
  rawTransformer = null;
@@ -74953,12 +75057,12 @@ var require_ponyfill_es2018 = __commonJS({
74953
75057
  return this._writable;
74954
75058
  }
74955
75059
  }
74956
- Object.defineProperties(TransformStream.prototype, {
75060
+ Object.defineProperties(TransformStream2.prototype, {
74957
75061
  readable: { enumerable: true },
74958
75062
  writable: { enumerable: true }
74959
75063
  });
74960
75064
  if (typeof Symbol.toStringTag === "symbol") {
74961
- Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {
75065
+ Object.defineProperty(TransformStream2.prototype, Symbol.toStringTag, {
74962
75066
  value: "TransformStream",
74963
75067
  configurable: true
74964
75068
  });
@@ -74997,7 +75101,7 @@ var require_ponyfill_es2018 = __commonJS({
74997
75101
  if (!Object.prototype.hasOwnProperty.call(x2, "_transformStreamController")) {
74998
75102
  return false;
74999
75103
  }
75000
- return x2 instanceof TransformStream;
75104
+ return x2 instanceof TransformStream2;
75001
75105
  }
75002
75106
  function TransformStreamError(stream11, e2) {
75003
75107
  ReadableStreamDefaultControllerError(stream11._readable._readableStreamController, e2);
@@ -75298,7 +75402,7 @@ var require_ponyfill_es2018 = __commonJS({
75298
75402
  exports3.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
75299
75403
  exports3.ReadableStreamDefaultController = ReadableStreamDefaultController;
75300
75404
  exports3.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
75301
- exports3.TransformStream = TransformStream;
75405
+ exports3.TransformStream = TransformStream2;
75302
75406
  exports3.TransformStreamDefaultController = TransformStreamDefaultController;
75303
75407
  exports3.WritableStream = WritableStream;
75304
75408
  exports3.WritableStreamDefaultController = WritableStreamDefaultController;
@@ -75877,7 +75981,7 @@ async function toFormData(Body2, ct) {
75877
75981
  let headerValue;
75878
75982
  let entryValue;
75879
75983
  let entryName;
75880
- let contentType;
75984
+ let contentType2;
75881
75985
  let filename;
75882
75986
  const entryChunks = [];
75883
75987
  const formData = new FormData2();
@@ -75888,7 +75992,7 @@ async function toFormData(Body2, ct) {
75888
75992
  entryChunks.push(ui8a);
75889
75993
  };
75890
75994
  const appendFileToFormData = () => {
75891
- const file2 = new file_default(entryChunks, filename, { type: contentType });
75995
+ const file2 = new file_default(entryChunks, filename, { type: contentType2 });
75892
75996
  formData.append(entryName, file2);
75893
75997
  };
75894
75998
  const appendEntryToFormData = () => {
@@ -75903,7 +76007,7 @@ async function toFormData(Body2, ct) {
75903
76007
  headerValue = "";
75904
76008
  entryValue = "";
75905
76009
  entryName = "";
75906
- contentType = "";
76010
+ contentType2 = "";
75907
76011
  filename = null;
75908
76012
  entryChunks.length = 0;
75909
76013
  };
@@ -75927,7 +76031,7 @@ async function toFormData(Body2, ct) {
75927
76031
  parser.onPartEnd = appendFileToFormData;
75928
76032
  }
75929
76033
  } else if (headerField === "content-type") {
75930
- contentType = headerValue;
76034
+ contentType2 = headerValue;
75931
76035
  }
75932
76036
  headerValue = "";
75933
76037
  headerField = "";
@@ -76679,9 +76783,9 @@ var init_response = __esm({
76679
76783
  const status = options.status != null ? options.status : 200;
76680
76784
  const headers = new Headers2(options.headers);
76681
76785
  if (body !== null && !headers.has("Content-Type")) {
76682
- const contentType = extractContentType(body, this);
76683
- if (contentType) {
76684
- headers.append("Content-Type", contentType);
76786
+ const contentType2 = extractContentType(body, this);
76787
+ if (contentType2) {
76788
+ headers.append("Content-Type", contentType2);
76685
76789
  }
76686
76790
  }
76687
76791
  this[INTERNALS2] = {
@@ -77000,9 +77104,9 @@ var init_request = __esm({
77000
77104
  });
77001
77105
  const headers = new Headers2(init.headers || input.headers || {});
77002
77106
  if (inputBody !== null && !headers.has("Content-Type")) {
77003
- const contentType = extractContentType(inputBody, this);
77004
- if (contentType) {
77005
- headers.set("Content-Type", contentType);
77107
+ const contentType2 = extractContentType(inputBody, this);
77108
+ if (contentType2) {
77109
+ headers.set("Content-Type", contentType2);
77006
77110
  }
77007
77111
  }
77008
77112
  let signal = isRequest(input) ? input.signal : null;
@@ -77842,19 +77946,19 @@ var require_gaxios = __commonJS({
77842
77946
  * @returns a promise that resolves to the response data.
77843
77947
  */
77844
77948
  async getResponseDataFromContentType(response) {
77845
- let contentType = response.headers.get("Content-Type");
77846
- if (contentType === null) {
77949
+ let contentType2 = response.headers.get("Content-Type");
77950
+ if (contentType2 === null) {
77847
77951
  return response.text();
77848
77952
  }
77849
- contentType = contentType.toLowerCase();
77850
- if (contentType.includes("application/json")) {
77953
+ contentType2 = contentType2.toLowerCase();
77954
+ if (contentType2.includes("application/json")) {
77851
77955
  let data = await response.text();
77852
77956
  try {
77853
77957
  data = JSON.parse(data);
77854
77958
  } catch {
77855
77959
  }
77856
77960
  return data;
77857
- } else if (contentType.match(/^text\//)) {
77961
+ } else if (contentType2.match(/^text\//)) {
77858
77962
  return response.text();
77859
77963
  } else {
77860
77964
  return response.blob();
@@ -84162,20 +84266,20 @@ var require_oauth2common = __commonJS({
84162
84266
  throw new Error(`${method} HTTP method does not support ${this.#clientAuthentication.confidentialClientType} client authentication`);
84163
84267
  }
84164
84268
  const headers = new Headers(opts.headers);
84165
- const contentType = headers.get("content-type");
84166
- if (contentType?.startsWith("application/x-www-form-urlencoded") || opts.data instanceof URLSearchParams) {
84269
+ const contentType2 = headers.get("content-type");
84270
+ if (contentType2?.startsWith("application/x-www-form-urlencoded") || opts.data instanceof URLSearchParams) {
84167
84271
  const data = new URLSearchParams(opts.data ?? "");
84168
84272
  data.append("client_id", this.#clientAuthentication.clientId);
84169
84273
  data.append("client_secret", this.#clientAuthentication.clientSecret || "");
84170
84274
  opts.data = data;
84171
- } else if (contentType?.startsWith("application/json")) {
84275
+ } else if (contentType2?.startsWith("application/json")) {
84172
84276
  opts.data = opts.data || {};
84173
84277
  Object.assign(opts.data, {
84174
84278
  client_id: this.#clientAuthentication.clientId,
84175
84279
  client_secret: this.#clientAuthentication.clientSecret || ""
84176
84280
  });
84177
84281
  } else {
84178
- throw new Error(`${contentType} content-types are not supported with ${this.#clientAuthentication.confidentialClientType} client authentication`);
84282
+ throw new Error(`${contentType2} content-types are not supported with ${this.#clientAuthentication.confidentialClientType} client authentication`);
84179
84283
  }
84180
84284
  }
84181
84285
  }
@@ -89524,7 +89628,7 @@ var require_event_target = __commonJS({
89524
89628
  var kTarget = Symbol("kTarget");
89525
89629
  var kType = Symbol("kType");
89526
89630
  var kWasClean = Symbol("kWasClean");
89527
- var Event3 = class {
89631
+ var Event2 = class {
89528
89632
  /**
89529
89633
  * Create a new `Event`.
89530
89634
  *
@@ -89548,9 +89652,9 @@ var require_event_target = __commonJS({
89548
89652
  return this[kType];
89549
89653
  }
89550
89654
  };
89551
- Object.defineProperty(Event3.prototype, "target", { enumerable: true });
89552
- Object.defineProperty(Event3.prototype, "type", { enumerable: true });
89553
- var CloseEvent = class extends Event3 {
89655
+ Object.defineProperty(Event2.prototype, "target", { enumerable: true });
89656
+ Object.defineProperty(Event2.prototype, "type", { enumerable: true });
89657
+ var CloseEvent = class extends Event2 {
89554
89658
  /**
89555
89659
  * Create a new `CloseEvent`.
89556
89660
  *
@@ -89592,7 +89696,7 @@ var require_event_target = __commonJS({
89592
89696
  Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
89593
89697
  Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
89594
89698
  Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
89595
- var ErrorEvent2 = class extends Event3 {
89699
+ var ErrorEvent = class extends Event2 {
89596
89700
  /**
89597
89701
  * Create a new `ErrorEvent`.
89598
89702
  *
@@ -89620,9 +89724,9 @@ var require_event_target = __commonJS({
89620
89724
  return this[kMessage];
89621
89725
  }
89622
89726
  };
89623
- Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: true });
89624
- Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: true });
89625
- var MessageEvent2 = class extends Event3 {
89727
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
89728
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
89729
+ var MessageEvent = class extends Event2 {
89626
89730
  /**
89627
89731
  * Create a new `MessageEvent`.
89628
89732
  *
@@ -89642,8 +89746,8 @@ var require_event_target = __commonJS({
89642
89746
  return this[kData];
89643
89747
  }
89644
89748
  };
89645
- Object.defineProperty(MessageEvent2.prototype, "data", { enumerable: true });
89646
- var EventTarget2 = {
89749
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
89750
+ var EventTarget = {
89647
89751
  /**
89648
89752
  * Register an event listener.
89649
89753
  *
@@ -89665,7 +89769,7 @@ var require_event_target = __commonJS({
89665
89769
  let wrapper;
89666
89770
  if (type === "message") {
89667
89771
  wrapper = function onMessage(data, isBinary) {
89668
- const event = new MessageEvent2("message", {
89772
+ const event = new MessageEvent("message", {
89669
89773
  data: isBinary ? data : data.toString()
89670
89774
  });
89671
89775
  event[kTarget] = this;
@@ -89683,7 +89787,7 @@ var require_event_target = __commonJS({
89683
89787
  };
89684
89788
  } else if (type === "error") {
89685
89789
  wrapper = function onError(error40) {
89686
- const event = new ErrorEvent2("error", {
89790
+ const event = new ErrorEvent("error", {
89687
89791
  error: error40,
89688
89792
  message: error40.message
89689
89793
  });
@@ -89692,7 +89796,7 @@ var require_event_target = __commonJS({
89692
89796
  };
89693
89797
  } else if (type === "open") {
89694
89798
  wrapper = function onOpen() {
89695
- const event = new Event3("open");
89799
+ const event = new Event2("open");
89696
89800
  event[kTarget] = this;
89697
89801
  callListener(handler, this, event);
89698
89802
  };
@@ -89725,10 +89829,10 @@ var require_event_target = __commonJS({
89725
89829
  };
89726
89830
  module2.exports = {
89727
89831
  CloseEvent,
89728
- ErrorEvent: ErrorEvent2,
89729
- Event: Event3,
89730
- EventTarget: EventTarget2,
89731
- MessageEvent: MessageEvent2
89832
+ ErrorEvent,
89833
+ Event: Event2,
89834
+ EventTarget,
89835
+ MessageEvent
89732
89836
  };
89733
89837
  function callListener(listener, thisArg, event) {
89734
89838
  if (typeof listener === "object" && listener.handleEvent) {
@@ -91347,10 +91451,10 @@ var require_websocket_server = __commonJS({
91347
91451
  });
91348
91452
 
91349
91453
  // ../../node_modules/ws/wrapper.mjs
91350
- var import_stream, import_extension, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket, import_websocket_server;
91454
+ var import_stream2, import_extension, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket, import_websocket_server;
91351
91455
  var init_wrapper = __esm({
91352
91456
  "../../node_modules/ws/wrapper.mjs"() {
91353
- import_stream = __toESM(require_stream(), 1);
91457
+ import_stream2 = __toESM(require_stream(), 1);
91354
91458
  import_extension = __toESM(require_extension(), 1);
91355
91459
  import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
91356
91460
  import_receiver = __toESM(require_receiver(), 1);
@@ -101032,8 +101136,8 @@ async function defaultParseResponse3(client, props) {
101032
101136
  if (props.options.__binaryResponse) {
101033
101137
  return response;
101034
101138
  }
101035
- const contentType = response.headers.get("content-type");
101036
- const mediaType = (_a6 = contentType === null || contentType === void 0 ? void 0 : contentType.split(";")[0]) === null || _a6 === void 0 ? void 0 : _a6.trim();
101139
+ const contentType2 = response.headers.get("content-type");
101140
+ const mediaType = (_a6 = contentType2 === null || contentType2 === void 0 ? void 0 : contentType2.split(";")[0]) === null || _a6 === void 0 ? void 0 : _a6.trim();
101037
101141
  const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes("application/json")) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith("+json"));
101038
101142
  if (isJSON) {
101039
101143
  const contentLength = response.headers.get("content-length");
@@ -110529,11 +110633,11 @@ function getContentTypeFromFileName(fileName) {
110529
110633
  };
110530
110634
  return mimeTypes[ext] || null;
110531
110635
  }
110532
- function bytesToBlob(content, contentType) {
110636
+ function bytesToBlob(content, contentType2) {
110533
110637
  if (content instanceof Uint8Array) {
110534
- return new Blob([new Uint8Array(content)], { type: contentType });
110638
+ return new Blob([new Uint8Array(content)], { type: contentType2 });
110535
110639
  }
110536
- return new Blob([content], { type: contentType });
110640
+ return new Blob([content], { type: contentType2 });
110537
110641
  }
110538
110642
  var init_files5 = __esm({
110539
110643
  "../../node_modules/@mistralai/mistralai/esm/lib/files.js"() {
@@ -110545,14 +110649,14 @@ function matchContentType(response, pattern) {
110545
110649
  if (pattern === "*") {
110546
110650
  return true;
110547
110651
  }
110548
- let contentType = response.headers.get("content-type")?.trim() || "application/octet-stream";
110549
- contentType = contentType.toLowerCase();
110652
+ let contentType2 = response.headers.get("content-type")?.trim() || "application/octet-stream";
110653
+ contentType2 = contentType2.toLowerCase();
110550
110654
  const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator);
110551
110655
  const [wantType = "", ...wantParams] = wantParts;
110552
110656
  if (wantType.split("/").length !== 2) {
110553
110657
  return false;
110554
110658
  }
110555
- const gotParts = contentType.split(mediaParamSeparator);
110659
+ const gotParts = contentType2.split(mediaParamSeparator);
110556
110660
  const [gotType = "", ...gotParams] = gotParts;
110557
110661
  const [type = "", subtype = ""] = gotType.split("/");
110558
110662
  if (!type || !subtype) {
@@ -116571,8 +116675,8 @@ function inferGenAiOperationName(operationId) {
116571
116675
  function isKnownGenAiOperation(operationId) {
116572
116676
  return inferGenAiOperationName(operationId) !== null;
116573
116677
  }
116574
- function isJsonContentType(contentType) {
116575
- const mediaType = contentType?.split(";")[0]?.trim().toLowerCase();
116678
+ function isJsonContentType(contentType2) {
116679
+ const mediaType = contentType2?.split(";")[0]?.trim().toLowerCase();
116576
116680
  return mediaType === "application/json" || mediaType === "text/json" || mediaType?.endsWith("+json") === true;
116577
116681
  }
116578
116682
  function buildGenaiSpanName(genAiOp, body) {
@@ -117771,8 +117875,8 @@ async function logRequest(logger, req) {
117771
117875
  if (!logger) {
117772
117876
  return;
117773
117877
  }
117774
- const contentType = req.headers.get("content-type");
117775
- const ct = contentType?.split(";")[0] || "";
117878
+ const contentType2 = req.headers.get("content-type");
117879
+ const ct = contentType2?.split(";")[0] || "";
117776
117880
  logger.group(`> Request: ${req.method} ${req.url}`);
117777
117881
  logger.group("Headers:");
117778
117882
  for (const [k, v] of req.headers.entries()) {
@@ -117796,7 +117900,7 @@ async function logRequest(logger, req) {
117796
117900
  break;
117797
117901
  }
117798
117902
  default:
117799
- logger.log(`<${contentType}>`);
117903
+ logger.log(`<${contentType2}>`);
117800
117904
  break;
117801
117905
  }
117802
117906
  logger.groupEnd();
@@ -117806,8 +117910,8 @@ async function logResponse(logger, res, req) {
117806
117910
  if (!logger) {
117807
117911
  return;
117808
117912
  }
117809
- const contentType = res.headers.get("content-type");
117810
- const ct = contentType?.split(";")[0] || "";
117913
+ const contentType2 = res.headers.get("content-type");
117914
+ const ct = contentType2?.split(";")[0] || "";
117811
117915
  logger.group(`< Response: ${req.method} ${req.url}`);
117812
117916
  logger.log("Status Code:", res.status, res.statusText);
117813
117917
  logger.group("Headers:");
@@ -117822,7 +117926,7 @@ async function logResponse(logger, res, req) {
117822
117926
  break;
117823
117927
  case (matchContentType(res, "application/jsonl") || jsonlLikeContentTypeRE.test(ct)):
117824
117928
  case matchContentType(res, "text/event-stream"):
117825
- logger.log(`<${contentType}>`);
117929
+ logger.log(`<${contentType2}>`);
117826
117930
  break;
117827
117931
  case matchContentType(res, "text/*"):
117828
117932
  logger.log(await res.clone().text());
@@ -117836,7 +117940,7 @@ async function logResponse(logger, res, req) {
117836
117940
  break;
117837
117941
  }
117838
117942
  default:
117839
- logger.log(`<${contentType}>`);
117943
+ logger.log(`<${contentType2}>`);
117840
117944
  break;
117841
117945
  }
117842
117946
  logger.groupEnd();
@@ -118091,9 +118195,9 @@ var init_sdkerror = __esm({
118091
118195
  message += `: `;
118092
118196
  }
118093
118197
  message += `Status ${httpMeta.response.status}`;
118094
- const contentType = httpMeta.response.headers.get("content-type") || `""`;
118095
- if (contentType !== "application/json") {
118096
- message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`;
118198
+ const contentType2 = httpMeta.response.headers.get("content-type") || `""`;
118199
+ if (contentType2 !== "application/json") {
118200
+ message += ` Content-Type ${contentType2.includes(" ") ? `"${contentType2}"` : contentType2}`;
118097
118201
  }
118098
118202
  const body = httpMeta.body || `""`;
118099
118203
  message += body.length > 100 ? "\n" : ". ";
@@ -126019,16 +126123,16 @@ var init_eventprogressstatus = __esm({
126019
126123
  });
126020
126124
 
126021
126125
  // ../../node_modules/@mistralai/mistralai/esm/models/components/eventsource.js
126022
- var EventSource2, EventSource$outboundSchema;
126126
+ var EventSource, EventSource$outboundSchema;
126023
126127
  var init_eventsource = __esm({
126024
126128
  "../../node_modules/@mistralai/mistralai/esm/models/components/eventsource.js"() {
126025
126129
  init_v4();
126026
- EventSource2 = {
126130
+ EventSource = {
126027
126131
  Database: "DATABASE",
126028
126132
  Live: "LIVE",
126029
126133
  Hybrid: "HYBRID"
126030
126134
  };
126031
- EventSource$outboundSchema = _enum2(EventSource2);
126135
+ EventSource$outboundSchema = _enum2(EventSource);
126032
126136
  }
126033
126137
  });
126034
126138
 
@@ -135834,7 +135938,7 @@ var init_streamv1workflowsexecutionsexecutionidstreamget = __esm({
135834
135938
  });
135835
135939
 
135836
135940
  // ../../node_modules/@mistralai/mistralai/esm/models/operations/streamworkflowexecutionlogs.js
135837
- var Event2, StreamWorkflowExecutionLogsRequest$outboundSchema, Event$inboundSchema2, StreamWorkflowExecutionLogsData$inboundSchema, StreamWorkflowExecutionLogsResponseBody$inboundSchema;
135941
+ var Event, StreamWorkflowExecutionLogsRequest$outboundSchema, Event$inboundSchema2, StreamWorkflowExecutionLogsData$inboundSchema, StreamWorkflowExecutionLogsResponseBody$inboundSchema;
135838
135942
  var init_streamworkflowexecutionlogs = __esm({
135839
135943
  "../../node_modules/@mistralai/mistralai/esm/models/operations/streamworkflowexecutionlogs.js"() {
135840
135944
  init_v4();
@@ -135842,7 +135946,7 @@ var init_streamworkflowexecutionlogs = __esm({
135842
135946
  init_enums();
135843
135947
  init_smartUnion();
135844
135948
  init_components();
135845
- Event2 = {
135949
+ Event = {
135846
135950
  Log: "log",
135847
135951
  Error: "error"
135848
135952
  };
@@ -135860,7 +135964,7 @@ var init_streamworkflowexecutionlogs = __esm({
135860
135964
  lastEventId: "last_event_id"
135861
135965
  });
135862
135966
  });
135863
- Event$inboundSchema2 = inboundSchema(Event2);
135967
+ Event$inboundSchema2 = inboundSchema(Event);
135864
135968
  StreamWorkflowExecutionLogsData$inboundSchema = smartUnion([
135865
135969
  ExecutionLogRecord$inboundSchema,
135866
135970
  StreamError$inboundSchema
@@ -136443,11 +136547,11 @@ async function $do4(client, request, options) {
136443
136547
  appendForm(body, "file", blob, name);
136444
136548
  } else if (isReadableStream(payload.file.content)) {
136445
136549
  const buffer = await readableStreamToArrayBuffer(payload.file.content);
136446
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
136447
- appendForm(body, "file", bytesToBlob(buffer, contentType), payload.file.fileName);
136550
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
136551
+ appendForm(body, "file", bytesToBlob(buffer, contentType2), payload.file.fileName);
136448
136552
  } else {
136449
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
136450
- appendForm(body, "file", bytesToBlob(payload.file.content, contentType), payload.file.fileName);
136553
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
136554
+ appendForm(body, "file", bytesToBlob(payload.file.content, contentType2), payload.file.fileName);
136451
136555
  }
136452
136556
  }
136453
136557
  if (payload.file_id !== void 0) {
@@ -136558,11 +136662,11 @@ async function $do5(client, request, options) {
136558
136662
  appendForm(body, "file", blob, name);
136559
136663
  } else if (isReadableStream(payload.file.content)) {
136560
136664
  const buffer = await readableStreamToArrayBuffer(payload.file.content);
136561
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
136562
- appendForm(body, "file", bytesToBlob(buffer, contentType), payload.file.fileName);
136665
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
136666
+ appendForm(body, "file", bytesToBlob(buffer, contentType2), payload.file.fileName);
136563
136667
  } else {
136564
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
136565
- appendForm(body, "file", bytesToBlob(payload.file.content, contentType), payload.file.fileName);
136668
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
136669
+ appendForm(body, "file", bytesToBlob(payload.file.content, contentType2), payload.file.fileName);
136566
136670
  }
136567
136671
  }
136568
136672
  if (payload.file_id !== void 0) {
@@ -143830,11 +143934,11 @@ async function $do82(client, request, options) {
143830
143934
  appendForm(body, "file", blob, name);
143831
143935
  } else if (isReadableStream(payload.RequestBody.file.content)) {
143832
143936
  const buffer = await readableStreamToArrayBuffer(payload.RequestBody.file.content);
143833
- const contentType = getContentTypeFromFileName(payload.RequestBody.file.fileName) || "application/octet-stream";
143834
- appendForm(body, "file", bytesToBlob(buffer, contentType), payload.RequestBody.file.fileName);
143937
+ const contentType2 = getContentTypeFromFileName(payload.RequestBody.file.fileName) || "application/octet-stream";
143938
+ appendForm(body, "file", bytesToBlob(buffer, contentType2), payload.RequestBody.file.fileName);
143835
143939
  } else {
143836
- const contentType = getContentTypeFromFileName(payload.RequestBody.file.fileName) || "application/octet-stream";
143837
- appendForm(body, "file", bytesToBlob(payload.RequestBody.file.content, contentType), payload.RequestBody.file.fileName);
143940
+ const contentType2 = getContentTypeFromFileName(payload.RequestBody.file.fileName) || "application/octet-stream";
143941
+ appendForm(body, "file", bytesToBlob(payload.RequestBody.file.content, contentType2), payload.RequestBody.file.fileName);
143838
143942
  }
143839
143943
  const pathParams = {
143840
143944
  library_id: encodeSimple("library_id", payload.library_id, {
@@ -151311,11 +151415,11 @@ async function $do159(client, request, options) {
151311
151415
  appendForm(body, "file", blob, name);
151312
151416
  } else if (isReadableStream(payload.file.content)) {
151313
151417
  const buffer = await readableStreamToArrayBuffer(payload.file.content);
151314
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
151315
- appendForm(body, "file", bytesToBlob(buffer, contentType), payload.file.fileName);
151418
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
151419
+ appendForm(body, "file", bytesToBlob(buffer, contentType2), payload.file.fileName);
151316
151420
  } else {
151317
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
151318
- appendForm(body, "file", bytesToBlob(payload.file.content, contentType), payload.file.fileName);
151421
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
151422
+ appendForm(body, "file", bytesToBlob(payload.file.content, contentType2), payload.file.fileName);
151319
151423
  }
151320
151424
  if (payload.expiry !== void 0) {
151321
151425
  appendForm(body, "expiry", payload.expiry);
@@ -200960,7 +201064,7 @@ var require_int = __commonJS({
200960
201064
  tag: "tag:yaml.org,2002:int",
200961
201065
  format: "OCT",
200962
201066
  test: /^0o[0-7]+$/,
200963
- resolve: (str2, _onError2, opt) => intResolve(str2, 2, 8, opt),
201067
+ resolve: (str2, _onError, opt) => intResolve(str2, 2, 8, opt),
200964
201068
  stringify: (node) => intStringify(node, 8, "0o")
200965
201069
  };
200966
201070
  var int2 = {
@@ -200968,7 +201072,7 @@ var require_int = __commonJS({
200968
201072
  default: true,
200969
201073
  tag: "tag:yaml.org,2002:int",
200970
201074
  test: /^[-+]?[0-9]+$/,
200971
- resolve: (str2, _onError2, opt) => intResolve(str2, 0, 10, opt),
201075
+ resolve: (str2, _onError, opt) => intResolve(str2, 0, 10, opt),
200972
201076
  stringify: stringifyNumber.stringifyNumber
200973
201077
  };
200974
201078
  var intHex = {
@@ -200977,7 +201081,7 @@ var require_int = __commonJS({
200977
201081
  tag: "tag:yaml.org,2002:int",
200978
201082
  format: "HEX",
200979
201083
  test: /^0x[0-9a-fA-F]+$/,
200980
- resolve: (str2, _onError2, opt) => intResolve(str2, 2, 16, opt),
201084
+ resolve: (str2, _onError, opt) => intResolve(str2, 2, 16, opt),
200981
201085
  stringify: (node) => intStringify(node, 16, "0x")
200982
201086
  };
200983
201087
  exports2.int = int2;
@@ -201055,7 +201159,7 @@ var require_schema2 = __commonJS({
201055
201159
  default: true,
201056
201160
  tag: "tag:yaml.org,2002:int",
201057
201161
  test: /^-?(?:0|[1-9][0-9]*)$/,
201058
- resolve: (str2, _onError2, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10),
201162
+ resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10),
201059
201163
  stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
201060
201164
  },
201061
201165
  {
@@ -201427,7 +201531,7 @@ var require_int2 = __commonJS({
201427
201531
  tag: "tag:yaml.org,2002:int",
201428
201532
  format: "BIN",
201429
201533
  test: /^[-+]?0b[0-1_]+$/,
201430
- resolve: (str2, _onError2, opt) => intResolve(str2, 2, 2, opt),
201534
+ resolve: (str2, _onError, opt) => intResolve(str2, 2, 2, opt),
201431
201535
  stringify: (node) => intStringify(node, 2, "0b")
201432
201536
  };
201433
201537
  var intOct = {
@@ -201436,7 +201540,7 @@ var require_int2 = __commonJS({
201436
201540
  tag: "tag:yaml.org,2002:int",
201437
201541
  format: "OCT",
201438
201542
  test: /^[-+]?0[0-7_]+$/,
201439
- resolve: (str2, _onError2, opt) => intResolve(str2, 1, 8, opt),
201543
+ resolve: (str2, _onError, opt) => intResolve(str2, 1, 8, opt),
201440
201544
  stringify: (node) => intStringify(node, 8, "0")
201441
201545
  };
201442
201546
  var int2 = {
@@ -201444,7 +201548,7 @@ var require_int2 = __commonJS({
201444
201548
  default: true,
201445
201549
  tag: "tag:yaml.org,2002:int",
201446
201550
  test: /^[-+]?[0-9][0-9_]*$/,
201447
- resolve: (str2, _onError2, opt) => intResolve(str2, 0, 10, opt),
201551
+ resolve: (str2, _onError, opt) => intResolve(str2, 0, 10, opt),
201448
201552
  stringify: stringifyNumber.stringifyNumber
201449
201553
  };
201450
201554
  var intHex = {
@@ -201453,7 +201557,7 @@ var require_int2 = __commonJS({
201453
201557
  tag: "tag:yaml.org,2002:int",
201454
201558
  format: "HEX",
201455
201559
  test: /^[-+]?0x[0-9a-fA-F_]+$/,
201456
- resolve: (str2, _onError2, opt) => intResolve(str2, 2, 16, opt),
201560
+ resolve: (str2, _onError, opt) => intResolve(str2, 2, 16, opt),
201457
201561
  stringify: (node) => intStringify(node, 16, "0x")
201458
201562
  };
201459
201563
  exports2.int = int2;
@@ -201596,7 +201700,7 @@ var require_timestamp = __commonJS({
201596
201700
  tag: "tag:yaml.org,2002:int",
201597
201701
  format: "TIME",
201598
201702
  test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
201599
- resolve: (str2, _onError2, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt),
201703
+ resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt),
201600
201704
  stringify: stringifySexagesimal
201601
201705
  };
201602
201706
  var floatTime = {
@@ -203125,19 +203229,19 @@ var require_resolve_flow_scalar = __commonJS({
203125
203229
  const { offset, type, source, end } = scalar2;
203126
203230
  let _type;
203127
203231
  let value;
203128
- const _onError2 = (rel, code, msg) => onError(offset + rel, code, msg);
203232
+ const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
203129
203233
  switch (type) {
203130
203234
  case "scalar":
203131
203235
  _type = Scalar.Scalar.PLAIN;
203132
- value = plainValue(source, _onError2);
203236
+ value = plainValue(source, _onError);
203133
203237
  break;
203134
203238
  case "single-quoted-scalar":
203135
203239
  _type = Scalar.Scalar.QUOTE_SINGLE;
203136
- value = singleQuotedValue(source, _onError2);
203240
+ value = singleQuotedValue(source, _onError);
203137
203241
  break;
203138
203242
  case "double-quoted-scalar":
203139
203243
  _type = Scalar.Scalar.QUOTE_DOUBLE;
203140
- value = doubleQuotedValue(source, _onError2);
203244
+ value = doubleQuotedValue(source, _onError);
203141
203245
  break;
203142
203246
  default:
203143
203247
  onError(scalar2, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
@@ -203811,7 +203915,7 @@ var require_cst_scalar = __commonJS({
203811
203915
  var stringifyString = require_stringifyString();
203812
203916
  function resolveAsScalar(token, strict = true, onError) {
203813
203917
  if (token) {
203814
- const _onError2 = (pos, code, message) => {
203918
+ const _onError = (pos, code, message) => {
203815
203919
  const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
203816
203920
  if (onError)
203817
203921
  onError(offset, code, message);
@@ -203822,9 +203926,9 @@ var require_cst_scalar = __commonJS({
203822
203926
  case "scalar":
203823
203927
  case "single-quoted-scalar":
203824
203928
  case "double-quoted-scalar":
203825
- return resolveFlowScalar.resolveFlowScalar(token, strict, _onError2);
203929
+ return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
203826
203930
  case "block-scalar":
203827
- return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError2);
203931
+ return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
203828
203932
  }
203829
203933
  }
203830
203934
  return null;
@@ -207720,8 +207824,8 @@ async function resolvePromptImage(attachment, fetchImpl) {
207720
207824
  if (!response.ok) {
207721
207825
  throw new Error(`\u8BFB\u53D6\u56FE\u7247\u9644\u4EF6 ${attachment.name} \u5931\u8D25\uFF08${response.status}\uFF09\u3002`);
207722
207826
  }
207723
- const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
207724
- const mimeType = contentType?.startsWith("image/") ? contentType : attachment.mimeType;
207827
+ const contentType2 = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
207828
+ const mimeType = contentType2?.startsWith("image/") ? contentType2 : attachment.mimeType;
207725
207829
  return {
207726
207830
  type: "image",
207727
207831
  data: import_node_buffer3.Buffer.from(await response.arrayBuffer()).toString("base64"),
@@ -211940,6 +212044,7 @@ var InitializedNotificationSchema = NotificationSchema.extend({
211940
212044
  method: literal("notifications/initialized"),
211941
212045
  params: NotificationsParamsSchema.optional()
211942
212046
  });
212047
+ var isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;
211943
212048
  var PingRequestSchema = RequestSchema.extend({
211944
212049
  method: literal("ping"),
211945
212050
  params: BaseRequestParamsSchema.optional()
@@ -215096,480 +215201,24 @@ async function safeText(resp) {
215096
215201
  }
215097
215202
  }
215098
215203
 
215099
- // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/sseTransportFactory.js
215204
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/streamableHttpTransportFactory.js
215100
215205
  init_cancellationScope();
215101
215206
 
215102
- // ../../node_modules/eventsource-parser/dist/index.js
215103
- var ParseError = class extends Error {
215104
- constructor(message, options) {
215105
- super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
215106
- }
215107
- };
215108
- var LF = 10;
215109
- var CR = 13;
215110
- var SPACE = 32;
215111
- function noop(_arg) {
215112
- }
215113
- function createParser(config2) {
215114
- if (typeof config2 == "function")
215115
- throw new TypeError(
215116
- "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
215117
- );
215118
- const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config2, pendingFragments = [];
215119
- let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
215120
- function feed(chunk) {
215121
- if (terminated)
215122
- throw new Error(
215123
- "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
215124
- );
215125
- if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
215126
- const trailing2 = processLines(chunk);
215127
- trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
215128
- return;
215129
- }
215130
- if (chunk.indexOf(`
215131
- `) === -1 && chunk.indexOf("\r") === -1) {
215132
- pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
215133
- return;
215134
- }
215135
- pendingFragments.push(chunk);
215136
- const input = pendingFragments.join("");
215137
- pendingFragments.length = 0, pendingFragmentsLength = 0;
215138
- const trailing = processLines(input);
215139
- trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
215140
- }
215141
- function checkBufferSize() {
215142
- maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
215143
- new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
215144
- type: "max-buffer-size-exceeded"
215145
- })
215146
- )));
215147
- }
215148
- function processLines(chunk) {
215149
- let searchIndex = 0;
215150
- if (chunk.indexOf("\r") === -1) {
215151
- let lfIndex = chunk.indexOf(`
215152
- `, searchIndex);
215153
- for (; lfIndex !== -1; ) {
215154
- if (searchIndex === lfIndex) {
215155
- dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
215156
- `, searchIndex);
215157
- continue;
215158
- }
215159
- const firstCharCode = chunk.charCodeAt(searchIndex);
215160
- if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
215161
- const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
215162
- if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
215163
- onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
215164
- `, searchIndex);
215165
- continue;
215166
- }
215167
- data = dataLines === 0 ? value : `${data}
215168
- ${value}`, dataLines++;
215169
- } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
215170
- chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
215171
- lfIndex
215172
- ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
215173
- searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
215174
- `, searchIndex);
215175
- }
215176
- return chunk.slice(searchIndex);
215177
- }
215178
- for (; searchIndex < chunk.length; ) {
215179
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
215180
- `, searchIndex);
215181
- let lineEnd = -1;
215182
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
215183
- break;
215184
- parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
215185
- }
215186
- return chunk.slice(searchIndex);
215187
- }
215188
- function parseLine(chunk, start, end) {
215189
- if (start === end) {
215190
- dispatchEvent();
215191
- return;
215192
- }
215193
- const firstCharCode = chunk.charCodeAt(start);
215194
- if (isDataPrefix(chunk, start, firstCharCode)) {
215195
- const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
215196
- data = dataLines === 0 ? value2 : `${data}
215197
- ${value2}`, dataLines++;
215198
- return;
215199
- }
215200
- if (isEventPrefix(chunk, start, firstCharCode)) {
215201
- eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
215202
- return;
215203
- }
215204
- if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
215205
- const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
215206
- value2.includes("\0") || (id = value2);
215207
- return;
215208
- }
215209
- if (firstCharCode === 58) {
215210
- if (onComment) {
215211
- const line2 = chunk.slice(start, end);
215212
- onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
215213
- }
215214
- return;
215215
- }
215216
- const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
215217
- if (fieldSeparatorIndex === -1) {
215218
- processField(line, "", line);
215219
- return;
215220
- }
215221
- const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
215222
- processField(field, value, line);
215223
- }
215224
- function processField(field, value, line) {
215225
- switch (field) {
215226
- case "event":
215227
- eventType = value || void 0;
215228
- break;
215229
- case "data":
215230
- data = dataLines === 0 ? value : `${data}
215231
- ${value}`, dataLines++;
215232
- break;
215233
- case "id":
215234
- value.includes("\0") || (id = value);
215235
- break;
215236
- case "retry":
215237
- /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
215238
- new ParseError(`Invalid \`retry\` value: "${value}"`, {
215239
- type: "invalid-retry",
215240
- value,
215241
- line
215242
- })
215243
- );
215244
- break;
215245
- default:
215246
- onError(
215247
- new ParseError(
215248
- `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
215249
- { type: "unknown-field", field, value, line }
215250
- )
215251
- );
215252
- break;
215253
- }
215254
- }
215255
- function dispatchEvent() {
215256
- dataLines > 0 && onEvent({
215257
- id,
215258
- event: eventType,
215259
- data
215260
- }), id = void 0, data = "", dataLines = 0, eventType = void 0;
215261
- }
215262
- function reset(options = {}) {
215263
- if (options.consume && pendingFragments.length > 0) {
215264
- const incompleteLine = pendingFragments.join("");
215265
- parseLine(incompleteLine, 0, incompleteLine.length);
215266
- }
215267
- isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
215268
- }
215269
- return { feed, reset };
215270
- }
215271
- function isDataPrefix(chunk, i2, firstCharCode) {
215272
- return firstCharCode === 100 && chunk.charCodeAt(i2 + 1) === 97 && chunk.charCodeAt(i2 + 2) === 116 && chunk.charCodeAt(i2 + 3) === 97 && chunk.charCodeAt(i2 + 4) === 58;
215273
- }
215274
- function isEventPrefix(chunk, i2, firstCharCode) {
215275
- return firstCharCode === 101 && chunk.charCodeAt(i2 + 1) === 118 && chunk.charCodeAt(i2 + 2) === 101 && chunk.charCodeAt(i2 + 3) === 110 && chunk.charCodeAt(i2 + 4) === 116 && chunk.charCodeAt(i2 + 5) === 58;
215276
- }
215277
-
215278
- // ../../node_modules/eventsource/dist/index.js
215279
- var ErrorEvent = class extends Event {
215280
- /**
215281
- * Constructs a new `ErrorEvent` instance. This is typically not called directly,
215282
- * but rather emitted by the `EventSource` object when an error occurs.
215283
- *
215284
- * @param type - The type of the event (should be "error")
215285
- * @param errorEventInitDict - Optional properties to include in the error event
215286
- */
215287
- constructor(type, errorEventInitDict) {
215288
- var _a6, _b2;
215289
- super(type), this.code = (_a6 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a6 : void 0, this.message = (_b2 = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b2 : void 0;
215290
- }
215291
- /**
215292
- * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
215293
- * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
215294
- * we explicitly include the properties in the `inspect` method.
215295
- *
215296
- * This is automatically called by Node.js when you `console.log` an instance of this class.
215297
- *
215298
- * @param _depth - The current depth
215299
- * @param options - The options passed to `util.inspect`
215300
- * @param inspect - The inspect function to use (prevents having to import it from `util`)
215301
- * @returns A string representation of the error
215302
- */
215303
- [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
215304
- return inspect(inspectableError(this), options);
215305
- }
215306
- /**
215307
- * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
215308
- * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
215309
- * we explicitly include the properties in the `inspect` method.
215310
- *
215311
- * This is automatically called by Deno when you `console.log` an instance of this class.
215312
- *
215313
- * @param inspect - The inspect function to use (prevents having to import it from `util`)
215314
- * @param options - The options passed to `Deno.inspect`
215315
- * @returns A string representation of the error
215316
- */
215317
- [Symbol.for("Deno.customInspect")](inspect, options) {
215318
- return inspect(inspectableError(this), options);
215207
+ // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
215208
+ var import_content_type = __toESM(require_content_type(), 1);
215209
+ function mediaTypeEssence(header) {
215210
+ if (!header) {
215211
+ return void 0;
215319
215212
  }
215320
- };
215321
- function syntaxError(message) {
215322
- const DomException = globalThis.DOMException;
215323
- return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
215324
- }
215325
- function flattenError2(err3) {
215326
- return err3 instanceof Error ? "errors" in err3 && Array.isArray(err3.errors) ? err3.errors.map(flattenError2).join(", ") : "cause" in err3 && err3.cause instanceof Error ? `${err3}: ${flattenError2(err3.cause)}` : err3.message : `${err3}`;
215327
- }
215328
- function inspectableError(err3) {
215329
- return {
215330
- type: err3.type,
215331
- message: err3.message,
215332
- code: err3.code,
215333
- defaultPrevented: err3.defaultPrevented,
215334
- cancelable: err3.cancelable,
215335
- timeStamp: err3.timeStamp
215336
- };
215337
- }
215338
- var __typeError = (msg) => {
215339
- throw TypeError(msg);
215340
- };
215341
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
215342
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
215343
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
215344
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
215345
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
215346
- var _readyState;
215347
- var _url2;
215348
- var _redirectUrl;
215349
- var _withCredentials;
215350
- var _fetch;
215351
- var _reconnectInterval;
215352
- var _reconnectTimer;
215353
- var _lastEventId;
215354
- var _controller;
215355
- var _parser;
215356
- var _onError;
215357
- var _onMessage;
215358
- var _onOpen;
215359
- var _EventSource_instances;
215360
- var connect_fn;
215361
- var _onFetchResponse;
215362
- var _onFetchError;
215363
- var getRequestOptions_fn;
215364
- var _onEvent;
215365
- var _onRetryChange;
215366
- var failConnection_fn;
215367
- var scheduleReconnect_fn;
215368
- var _reconnect;
215369
- var EventSource = class extends EventTarget {
215370
- constructor(url2, eventSourceInitDict) {
215371
- var _a6, _b2;
215372
- super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url2), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
215373
- var _a22;
215374
- __privateGet(this, _parser).reset();
215375
- const { body, redirected, status, headers } = response;
215376
- if (status === 204) {
215377
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
215378
- return;
215379
- }
215380
- if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
215381
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
215382
- return;
215383
- }
215384
- if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
215385
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
215386
- return;
215387
- }
215388
- if (__privateGet(this, _readyState) === this.CLOSED)
215389
- return;
215390
- __privateSet(this, _readyState, this.OPEN);
215391
- const openEvent = new Event("open");
215392
- if ((_a22 = __privateGet(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
215393
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
215394
- return;
215395
- }
215396
- const decoder = new TextDecoder(), reader = body.getReader();
215397
- let open4 = true;
215398
- do {
215399
- const { done, value } = await reader.read();
215400
- value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open4 = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
215401
- } while (open4);
215402
- }), __privateAdd(this, _onFetchError, (err3) => {
215403
- __privateSet(this, _controller, void 0), !(err3.name === "AbortError" || err3.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(err3));
215404
- }), __privateAdd(this, _onEvent, (event) => {
215405
- typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
215406
- const messageEvent = new MessageEvent(event.event || "message", {
215407
- data: event.data,
215408
- origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url2).origin,
215409
- lastEventId: event.id || ""
215410
- });
215411
- __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
215412
- }), __privateAdd(this, _onRetryChange, (value) => {
215413
- __privateSet(this, _reconnectInterval, value);
215414
- }), __privateAdd(this, _reconnect, () => {
215415
- __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
215416
- });
215417
- try {
215418
- if (url2 instanceof URL)
215419
- __privateSet(this, _url2, url2);
215420
- else if (typeof url2 == "string")
215421
- __privateSet(this, _url2, new URL(url2, getBaseURL()));
215422
- else
215423
- throw new Error("Invalid URL");
215424
- } catch {
215425
- throw syntaxError("An invalid or illegal string was specified");
215213
+ try {
215214
+ return import_content_type.default.parse(header).type;
215215
+ } catch {
215216
+ const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase();
215217
+ if (essence === "" || header.slice(essence.length).includes(",")) {
215218
+ return void 0;
215426
215219
  }
215427
- __privateSet(this, _parser, createParser({
215428
- onEvent: __privateGet(this, _onEvent),
215429
- onRetry: __privateGet(this, _onRetryChange)
215430
- })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a6 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a6 : globalThis.fetch), __privateSet(this, _withCredentials, (_b2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b2 : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
215220
+ return essence;
215431
215221
  }
215432
- /**
215433
- * Returns the state of this EventSource object's connection. It can have the values described below.
215434
- *
215435
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
215436
- *
215437
- * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
215438
- * defined in the TypeScript `dom` library.
215439
- *
215440
- * @public
215441
- */
215442
- get readyState() {
215443
- return __privateGet(this, _readyState);
215444
- }
215445
- /**
215446
- * Returns the URL providing the event stream.
215447
- *
215448
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
215449
- *
215450
- * @public
215451
- */
215452
- get url() {
215453
- return __privateGet(this, _url2).href;
215454
- }
215455
- /**
215456
- * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
215457
- *
215458
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
215459
- */
215460
- get withCredentials() {
215461
- return __privateGet(this, _withCredentials);
215462
- }
215463
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
215464
- get onerror() {
215465
- return __privateGet(this, _onError);
215466
- }
215467
- set onerror(value) {
215468
- __privateSet(this, _onError, value);
215469
- }
215470
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
215471
- get onmessage() {
215472
- return __privateGet(this, _onMessage);
215473
- }
215474
- set onmessage(value) {
215475
- __privateSet(this, _onMessage, value);
215476
- }
215477
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
215478
- get onopen() {
215479
- return __privateGet(this, _onOpen);
215480
- }
215481
- set onopen(value) {
215482
- __privateSet(this, _onOpen, value);
215483
- }
215484
- addEventListener(type, listener, options) {
215485
- const listen = listener;
215486
- super.addEventListener(type, listen, options);
215487
- }
215488
- removeEventListener(type, listener, options) {
215489
- const listen = listener;
215490
- super.removeEventListener(type, listen, options);
215491
- }
215492
- /**
215493
- * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
215494
- *
215495
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
215496
- *
215497
- * @public
215498
- */
215499
- close() {
215500
- __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
215501
- }
215502
- };
215503
- _readyState = /* @__PURE__ */ new WeakMap(), _url2 = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**
215504
- * Connect to the given URL and start receiving events
215505
- *
215506
- * @internal
215507
- */
215508
- connect_fn = function() {
215509
- __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url2), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
215510
- }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
215511
- * Get request options for the `fetch()` request
215512
- *
215513
- * @returns The request options
215514
- * @internal
215515
- */
215516
- getRequestOptions_fn = function() {
215517
- var _a6;
215518
- const init = {
215519
- // [spec] Let `corsAttributeState` be `Anonymous`…
215520
- // [spec] …will have their mode set to "cors"…
215521
- mode: "cors",
215522
- redirect: "follow",
215523
- headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
215524
- cache: "no-store",
215525
- signal: (_a6 = __privateGet(this, _controller)) == null ? void 0 : _a6.signal
215526
- };
215527
- return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
215528
- }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
215529
- * Handles the process referred to in the EventSource specification as "failing a connection".
215530
- *
215531
- * @param error - The error causing the connection to fail
215532
- * @param code - The HTTP status code, if available
215533
- * @internal
215534
- */
215535
- failConnection_fn = function(message, code) {
215536
- var _a6;
215537
- __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
215538
- const errorEvent = new ErrorEvent("error", { code, message });
215539
- (_a6 = __privateGet(this, _onError)) == null || _a6.call(this, errorEvent), this.dispatchEvent(errorEvent);
215540
- }, /**
215541
- * Schedules a reconnection attempt against the EventSource endpoint.
215542
- *
215543
- * @param message - The error causing the connection to fail
215544
- * @param code - The HTTP status code, if available
215545
- * @internal
215546
- */
215547
- scheduleReconnect_fn = function(message, code) {
215548
- var _a6;
215549
- if (__privateGet(this, _readyState) === this.CLOSED)
215550
- return;
215551
- __privateSet(this, _readyState, this.CONNECTING);
215552
- const errorEvent = new ErrorEvent("error", { code, message });
215553
- (_a6 = __privateGet(this, _onError)) == null || _a6.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
215554
- }, _reconnect = /* @__PURE__ */ new WeakMap(), /**
215555
- * ReadyState representing an EventSource currently trying to connect
215556
- *
215557
- * @public
215558
- */
215559
- EventSource.CONNECTING = 0, /**
215560
- * ReadyState representing an EventSource connection that is open (eg connected)
215561
- *
215562
- * @public
215563
- */
215564
- EventSource.OPEN = 1, /**
215565
- * ReadyState representing an EventSource connection that is closed (eg disconnected)
215566
- *
215567
- * @public
215568
- */
215569
- EventSource.CLOSED = 2;
215570
- function getBaseURL() {
215571
- const doc = "document" in globalThis ? globalThis.document : void 0;
215572
- return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
215573
215222
  }
215574
215223
 
215575
215224
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
@@ -216566,20 +216215,226 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
216566
216215
  return RegistrationResponseSchema.parse(await response.json());
216567
216216
  }
216568
216217
 
216569
- // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
216570
- var SseError = class extends Error {
216571
- constructor(code, message, event) {
216572
- super(`SSE error: ${message}`);
216218
+ // ../../node_modules/eventsource-parser/dist/index.js
216219
+ var ParseError = class extends Error {
216220
+ constructor(message, options) {
216221
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
216222
+ }
216223
+ };
216224
+ var LF = 10;
216225
+ var CR = 13;
216226
+ var SPACE = 32;
216227
+ function noop(_arg) {
216228
+ }
216229
+ function createParser(config2) {
216230
+ if (typeof config2 == "function")
216231
+ throw new TypeError(
216232
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
216233
+ );
216234
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config2, pendingFragments = [];
216235
+ let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
216236
+ function feed(chunk) {
216237
+ if (terminated)
216238
+ throw new Error(
216239
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
216240
+ );
216241
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
216242
+ const trailing2 = processLines(chunk);
216243
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
216244
+ return;
216245
+ }
216246
+ if (chunk.indexOf(`
216247
+ `) === -1 && chunk.indexOf("\r") === -1) {
216248
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
216249
+ return;
216250
+ }
216251
+ pendingFragments.push(chunk);
216252
+ const input = pendingFragments.join("");
216253
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
216254
+ const trailing = processLines(input);
216255
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
216256
+ }
216257
+ function checkBufferSize() {
216258
+ maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
216259
+ new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
216260
+ type: "max-buffer-size-exceeded"
216261
+ })
216262
+ )));
216263
+ }
216264
+ function processLines(chunk) {
216265
+ let searchIndex = 0;
216266
+ if (chunk.indexOf("\r") === -1) {
216267
+ let lfIndex = chunk.indexOf(`
216268
+ `, searchIndex);
216269
+ for (; lfIndex !== -1; ) {
216270
+ if (searchIndex === lfIndex) {
216271
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
216272
+ `, searchIndex);
216273
+ continue;
216274
+ }
216275
+ const firstCharCode = chunk.charCodeAt(searchIndex);
216276
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
216277
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
216278
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
216279
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
216280
+ `, searchIndex);
216281
+ continue;
216282
+ }
216283
+ data = dataLines === 0 ? value : `${data}
216284
+ ${value}`, dataLines++;
216285
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
216286
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
216287
+ lfIndex
216288
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
216289
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
216290
+ `, searchIndex);
216291
+ }
216292
+ return chunk.slice(searchIndex);
216293
+ }
216294
+ for (; searchIndex < chunk.length; ) {
216295
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
216296
+ `, searchIndex);
216297
+ let lineEnd = -1;
216298
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
216299
+ break;
216300
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
216301
+ }
216302
+ return chunk.slice(searchIndex);
216303
+ }
216304
+ function parseLine(chunk, start, end) {
216305
+ if (start === end) {
216306
+ dispatchEvent();
216307
+ return;
216308
+ }
216309
+ const firstCharCode = chunk.charCodeAt(start);
216310
+ if (isDataPrefix(chunk, start, firstCharCode)) {
216311
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
216312
+ data = dataLines === 0 ? value2 : `${data}
216313
+ ${value2}`, dataLines++;
216314
+ return;
216315
+ }
216316
+ if (isEventPrefix(chunk, start, firstCharCode)) {
216317
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
216318
+ return;
216319
+ }
216320
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
216321
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
216322
+ value2.includes("\0") || (id = value2);
216323
+ return;
216324
+ }
216325
+ if (firstCharCode === 58) {
216326
+ if (onComment) {
216327
+ const line2 = chunk.slice(start, end);
216328
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
216329
+ }
216330
+ return;
216331
+ }
216332
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
216333
+ if (fieldSeparatorIndex === -1) {
216334
+ processField(line, "", line);
216335
+ return;
216336
+ }
216337
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
216338
+ processField(field, value, line);
216339
+ }
216340
+ function processField(field, value, line) {
216341
+ switch (field) {
216342
+ case "event":
216343
+ eventType = value || void 0;
216344
+ break;
216345
+ case "data":
216346
+ data = dataLines === 0 ? value : `${data}
216347
+ ${value}`, dataLines++;
216348
+ break;
216349
+ case "id":
216350
+ value.includes("\0") || (id = value);
216351
+ break;
216352
+ case "retry":
216353
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
216354
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
216355
+ type: "invalid-retry",
216356
+ value,
216357
+ line
216358
+ })
216359
+ );
216360
+ break;
216361
+ default:
216362
+ onError(
216363
+ new ParseError(
216364
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
216365
+ { type: "unknown-field", field, value, line }
216366
+ )
216367
+ );
216368
+ break;
216369
+ }
216370
+ }
216371
+ function dispatchEvent() {
216372
+ dataLines > 0 && onEvent({
216373
+ id,
216374
+ event: eventType,
216375
+ data
216376
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
216377
+ }
216378
+ function reset(options = {}) {
216379
+ if (options.consume && pendingFragments.length > 0) {
216380
+ const incompleteLine = pendingFragments.join("");
216381
+ parseLine(incompleteLine, 0, incompleteLine.length);
216382
+ }
216383
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
216384
+ }
216385
+ return { feed, reset };
216386
+ }
216387
+ function isDataPrefix(chunk, i2, firstCharCode) {
216388
+ return firstCharCode === 100 && chunk.charCodeAt(i2 + 1) === 97 && chunk.charCodeAt(i2 + 2) === 116 && chunk.charCodeAt(i2 + 3) === 97 && chunk.charCodeAt(i2 + 4) === 58;
216389
+ }
216390
+ function isEventPrefix(chunk, i2, firstCharCode) {
216391
+ return firstCharCode === 101 && chunk.charCodeAt(i2 + 1) === 118 && chunk.charCodeAt(i2 + 2) === 101 && chunk.charCodeAt(i2 + 3) === 110 && chunk.charCodeAt(i2 + 4) === 116 && chunk.charCodeAt(i2 + 5) === 58;
216392
+ }
216393
+
216394
+ // ../../node_modules/eventsource-parser/dist/stream.js
216395
+ var EventSourceParserStream = class extends TransformStream {
216396
+ constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
216397
+ let parser;
216398
+ super({
216399
+ start(controller) {
216400
+ parser = createParser({
216401
+ onEvent: (event) => {
216402
+ controller.enqueue(event);
216403
+ },
216404
+ onError(error40) {
216405
+ typeof onError == "function" && onError(error40), (onError === "terminate" || error40.type === "max-buffer-size-exceeded") && controller.error(error40);
216406
+ },
216407
+ onRetry,
216408
+ onComment,
216409
+ maxBufferSize
216410
+ });
216411
+ },
216412
+ transform(chunk) {
216413
+ parser.feed(chunk);
216414
+ }
216415
+ });
216416
+ }
216417
+ };
216418
+
216419
+ // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
216420
+ var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
216421
+ initialReconnectionDelay: 1e3,
216422
+ maxReconnectionDelay: 3e4,
216423
+ reconnectionDelayGrowFactor: 1.5,
216424
+ maxRetries: 2
216425
+ };
216426
+ var StreamableHTTPError = class extends Error {
216427
+ constructor(code, message) {
216428
+ super(`Streamable HTTP error: ${message}`);
216573
216429
  this.code = code;
216574
- this.event = event;
216575
216430
  }
216576
216431
  };
216577
- var SSEClientTransport = class {
216432
+ var StreamableHTTPClientTransport = class {
216578
216433
  constructor(url2, opts) {
216434
+ this._hasCompletedAuthFlow = false;
216579
216435
  this._url = url2;
216580
216436
  this._resourceMetadataUrl = void 0;
216581
216437
  this._scope = void 0;
216582
- this._eventSourceInit = opts?.eventSourceInit;
216583
216438
  this._requestInit = opts?.requestInit;
216584
216439
  this._authProvider = opts?.authProvider;
216585
216440
  this._fetch = opts?.fetch;
@@ -216589,6 +216444,8 @@ var SSEClientTransport = class {
216589
216444
  this._fetch = fetchLeavingRedirects(this._fetch);
216590
216445
  this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
216591
216446
  }
216447
+ this._sessionId = opts?.sessionId;
216448
+ this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
216592
216449
  }
216593
216450
  /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
216594
216451
  _unfollowedRedirect(response, url2) {
@@ -216614,7 +216471,7 @@ var SSEClientTransport = class {
216614
216471
  if (result !== "AUTHORIZED") {
216615
216472
  throw new UnauthorizedError();
216616
216473
  }
216617
- return await this._startOrAuth();
216474
+ return await this._startOrAuthSse({ resumptionToken: void 0 });
216618
216475
  }
216619
216476
  async _commonHeaders() {
216620
216477
  const headers = {};
@@ -216624,6 +216481,9 @@ var SSEClientTransport = class {
216624
216481
  headers["Authorization"] = `Bearer ${tokens.access_token}`;
216625
216482
  }
216626
216483
  }
216484
+ if (this._sessionId) {
216485
+ headers["mcp-session-id"] = this._sessionId;
216486
+ }
216627
216487
  if (this._protocolVersion) {
216628
216488
  headers["mcp-protocol-version"] = this._protocolVersion;
216629
216489
  }
@@ -216633,74 +216493,148 @@ var SSEClientTransport = class {
216633
216493
  ...extraHeaders
216634
216494
  });
216635
216495
  }
216636
- _startOrAuth() {
216637
- const baseFetch = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
216638
- const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);
216639
- let redirect;
216640
- return new Promise((resolve, reject) => {
216641
- this._eventSource = new EventSource(this._url.href, {
216642
- ...this._eventSourceInit,
216643
- fetch: async (url2, init) => {
216644
- const headers = await this._commonHeaders();
216645
- headers.set("Accept", "text/event-stream");
216646
- const response = await fetchImpl(url2, {
216647
- ...init,
216648
- headers
216649
- });
216650
- redirect = this._unfollowedRedirect(response, url2);
216651
- if (response.status === 401 && response.headers.has("www-authenticate")) {
216652
- const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
216653
- this._resourceMetadataUrl = resourceMetadataUrl;
216654
- this._scope = scope;
216655
- }
216656
- return response;
216496
+ async _startOrAuthSse(options) {
216497
+ const { resumptionToken } = options;
216498
+ try {
216499
+ const headers = await this._commonHeaders();
216500
+ headers.set("Accept", "text/event-stream");
216501
+ if (resumptionToken) {
216502
+ headers.set("last-event-id", resumptionToken);
216503
+ }
216504
+ const fetchFn = this._fetch ?? fetch;
216505
+ const init = { method: "GET", headers, signal: this._abortController?.signal };
216506
+ let response = await fetchFn(this._url, this._followRedirects ? init : { ...init, redirect: "manual" });
216507
+ const followed = this._followRedirects ? void 0 : followWithinOrigin(fetchFn, this._url, init, response);
216508
+ if (followed) {
216509
+ response = await followed;
216510
+ }
216511
+ if (!response.ok) {
216512
+ await response.body?.cancel();
216513
+ if (response.status === 401 && this._authProvider) {
216514
+ return await this._authThenStart();
216657
216515
  }
216658
- });
216659
- this._abortController = new AbortController();
216660
- this._eventSource.onerror = (event) => {
216661
- if (event.code === 401 && this._authProvider) {
216662
- this._authThenStart().then(resolve, reject);
216516
+ if (response.status === 405) {
216663
216517
  return;
216664
216518
  }
216665
- const error40 = new SseError(event.code, redirect ?? event.message, event);
216666
- reject(error40);
216667
- this.onerror?.(error40);
216668
- };
216669
- this._eventSource.onopen = () => {
216670
- };
216671
- this._eventSource.addEventListener("endpoint", (event) => {
216672
- const messageEvent = event;
216673
- try {
216674
- this._endpoint = new URL(messageEvent.data, this._url);
216675
- if (this._endpoint.origin !== this._url.origin) {
216676
- throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
216519
+ throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
216520
+ }
216521
+ this._handleSseStream(response.body, options, true);
216522
+ } catch (error40) {
216523
+ this.onerror?.(error40);
216524
+ throw error40;
216525
+ }
216526
+ }
216527
+ /**
216528
+ * Calculates the next reconnection delay using backoff algorithm
216529
+ *
216530
+ * @param attempt Current reconnection attempt count for the specific stream
216531
+ * @returns Time to wait in milliseconds before next reconnection attempt
216532
+ */
216533
+ _getNextReconnectionDelay(attempt) {
216534
+ if (this._serverRetryMs !== void 0) {
216535
+ return this._serverRetryMs;
216536
+ }
216537
+ const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
216538
+ const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
216539
+ const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
216540
+ return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
216541
+ }
216542
+ /**
216543
+ * Schedule a reconnection attempt using server-provided retry interval or backoff
216544
+ *
216545
+ * @param lastEventId The ID of the last received event for resumability
216546
+ * @param attemptCount Current reconnection attempt count for this specific stream
216547
+ */
216548
+ _scheduleReconnection(options, attemptCount = 0) {
216549
+ const maxRetries = this._reconnectionOptions.maxRetries;
216550
+ if (attemptCount >= maxRetries) {
216551
+ this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
216552
+ return;
216553
+ }
216554
+ const delay3 = this._getNextReconnectionDelay(attemptCount);
216555
+ this._reconnectionTimeout = setTimeout(() => {
216556
+ this._startOrAuthSse(options).catch((error40) => {
216557
+ this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error40 instanceof Error ? error40.message : String(error40)}`));
216558
+ this._scheduleReconnection(options, attemptCount + 1);
216559
+ });
216560
+ }, delay3);
216561
+ }
216562
+ _handleSseStream(stream11, options, isReconnectable) {
216563
+ if (!stream11) {
216564
+ return;
216565
+ }
216566
+ const { onresumptiontoken, replayMessageId } = options;
216567
+ let lastEventId;
216568
+ let hasPrimingEvent = false;
216569
+ let receivedResponse = false;
216570
+ const processStream2 = async () => {
216571
+ try {
216572
+ const reader = stream11.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
216573
+ onRetry: (retryMs) => {
216574
+ this._serverRetryMs = retryMs;
216575
+ }
216576
+ })).getReader();
216577
+ while (true) {
216578
+ const { value: event, done } = await reader.read();
216579
+ if (done) {
216580
+ break;
216581
+ }
216582
+ if (event.id) {
216583
+ lastEventId = event.id;
216584
+ hasPrimingEvent = true;
216585
+ onresumptiontoken?.(event.id);
216586
+ }
216587
+ if (!event.data) {
216588
+ continue;
216589
+ }
216590
+ if (!event.event || event.event === "message") {
216591
+ try {
216592
+ const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
216593
+ if (isJSONRPCResultResponse(message)) {
216594
+ receivedResponse = true;
216595
+ if (replayMessageId !== void 0) {
216596
+ message.id = replayMessageId;
216597
+ }
216598
+ }
216599
+ this.onmessage?.(message);
216600
+ } catch (error40) {
216601
+ this.onerror?.(error40);
216602
+ }
216677
216603
  }
216678
- } catch (error40) {
216679
- reject(error40);
216680
- this.onerror?.(error40);
216681
- void this.close();
216682
- return;
216683
216604
  }
216684
- resolve();
216685
- });
216686
- this._eventSource.onmessage = (event) => {
216687
- const messageEvent = event;
216688
- let message;
216689
- try {
216690
- message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
216691
- } catch (error40) {
216692
- this.onerror?.(error40);
216693
- return;
216605
+ const canResume = isReconnectable || hasPrimingEvent;
216606
+ const needsReconnect = canResume && !receivedResponse;
216607
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
216608
+ this._scheduleReconnection({
216609
+ resumptionToken: lastEventId,
216610
+ onresumptiontoken,
216611
+ replayMessageId
216612
+ }, 0);
216694
216613
  }
216695
- this.onmessage?.(message);
216696
- };
216697
- });
216614
+ } catch (error40) {
216615
+ this.onerror?.(new Error(`SSE stream disconnected: ${error40}`));
216616
+ const canResume = isReconnectable || hasPrimingEvent;
216617
+ const needsReconnect = canResume && !receivedResponse;
216618
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
216619
+ try {
216620
+ this._scheduleReconnection({
216621
+ resumptionToken: lastEventId,
216622
+ onresumptiontoken,
216623
+ replayMessageId
216624
+ }, 0);
216625
+ } catch (error41) {
216626
+ this.onerror?.(new Error(`Failed to reconnect: ${error41 instanceof Error ? error41.message : String(error41)}`));
216627
+ }
216628
+ }
216629
+ }
216630
+ };
216631
+ processStream2();
216698
216632
  }
216699
216633
  async start() {
216700
- if (this._eventSource) {
216701
- throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
216634
+ if (this._abortController) {
216635
+ throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
216702
216636
  }
216703
- return await this._startOrAuth();
216637
+ this._abortController = new AbortController();
216704
216638
  }
216705
216639
  /**
216706
216640
  * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
@@ -216721,17 +216655,23 @@ var SSEClientTransport = class {
216721
216655
  }
216722
216656
  }
216723
216657
  async close() {
216658
+ if (this._reconnectionTimeout) {
216659
+ clearTimeout(this._reconnectionTimeout);
216660
+ this._reconnectionTimeout = void 0;
216661
+ }
216724
216662
  this._abortController?.abort();
216725
- this._eventSource?.close();
216726
216663
  this.onclose?.();
216727
216664
  }
216728
- async send(message) {
216729
- if (!this._endpoint) {
216730
- throw new Error("Not connected");
216731
- }
216665
+ async send(message, options) {
216732
216666
  try {
216667
+ const { resumptionToken, onresumptiontoken } = options || {};
216668
+ if (resumptionToken) {
216669
+ this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err3) => this.onerror?.(err3));
216670
+ return;
216671
+ }
216733
216672
  const headers = await this._commonHeaders();
216734
216673
  headers.set("content-type", "application/json");
216674
+ headers.set("accept", "application/json, text/event-stream");
216735
216675
  const init = {
216736
216676
  ...this._requestInit,
216737
216677
  method: "POST",
@@ -216739,10 +216679,17 @@ var SSEClientTransport = class {
216739
216679
  body: JSON.stringify(message),
216740
216680
  signal: this._abortController?.signal
216741
216681
  };
216742
- const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);
216682
+ const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
216683
+ const sessionId = response.headers.get("mcp-session-id");
216684
+ if (sessionId) {
216685
+ this._sessionId = sessionId;
216686
+ }
216743
216687
  if (!response.ok) {
216744
216688
  const text2 = await response.text().catch(() => null);
216745
216689
  if (response.status === 401 && this._authProvider) {
216690
+ if (this._hasCompletedAuthFlow) {
216691
+ throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
216692
+ }
216746
216693
  const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
216747
216694
  this._resourceMetadataUrl = resourceMetadataUrl;
216748
216695
  this._scope = scope;
@@ -216755,11 +216702,103 @@ var SSEClientTransport = class {
216755
216702
  if (result !== "AUTHORIZED") {
216756
216703
  throw new UnauthorizedError();
216757
216704
  }
216705
+ this._hasCompletedAuthFlow = true;
216758
216706
  return this.send(message);
216759
216707
  }
216760
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text2}`);
216708
+ if (response.status === 403 && this._authProvider) {
216709
+ const { resourceMetadataUrl, scope, error: error40 } = extractWWWAuthenticateParams(response);
216710
+ if (error40 === "insufficient_scope") {
216711
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
216712
+ if (this._lastUpscopingHeader === wwwAuthHeader) {
216713
+ throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
216714
+ }
216715
+ if (scope) {
216716
+ this._scope = scope;
216717
+ }
216718
+ if (resourceMetadataUrl) {
216719
+ this._resourceMetadataUrl = resourceMetadataUrl;
216720
+ }
216721
+ this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
216722
+ const result = await auth(this._authProvider, {
216723
+ serverUrl: this._url,
216724
+ resourceMetadataUrl: this._resourceMetadataUrl,
216725
+ scope: this._scope,
216726
+ fetchFn: this._fetch
216727
+ });
216728
+ if (result !== "AUTHORIZED") {
216729
+ throw new UnauthorizedError();
216730
+ }
216731
+ return this.send(message);
216732
+ }
216733
+ }
216734
+ throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${this._unfollowedRedirect(response, this._url) ?? text2}`);
216761
216735
  }
216736
+ this._hasCompletedAuthFlow = false;
216737
+ this._lastUpscopingHeader = void 0;
216738
+ if (response.status === 202) {
216739
+ await response.body?.cancel();
216740
+ if (isInitializedNotification(message)) {
216741
+ this._startOrAuthSse({ resumptionToken: void 0 }).catch((err3) => this.onerror?.(err3));
216742
+ }
216743
+ return;
216744
+ }
216745
+ const messages = Array.isArray(message) ? message : [message];
216746
+ const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
216747
+ const contentType2 = response.headers.get("content-type");
216748
+ const responseMediaType = mediaTypeEssence(contentType2);
216749
+ if (hasRequests) {
216750
+ if (responseMediaType === "text/event-stream") {
216751
+ this._handleSseStream(response.body, { onresumptiontoken }, false);
216752
+ } else if (responseMediaType === "application/json") {
216753
+ const data = await response.json();
216754
+ const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
216755
+ for (const msg of responseMessages) {
216756
+ this.onmessage?.(msg);
216757
+ }
216758
+ } else {
216759
+ await response.body?.cancel();
216760
+ throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType2}`);
216761
+ }
216762
+ } else {
216763
+ await response.body?.cancel();
216764
+ }
216765
+ } catch (error40) {
216766
+ this.onerror?.(error40);
216767
+ throw error40;
216768
+ }
216769
+ }
216770
+ get sessionId() {
216771
+ return this._sessionId;
216772
+ }
216773
+ /**
216774
+ * Terminates the current session by sending a DELETE request to the server.
216775
+ *
216776
+ * Clients that no longer need a particular session
216777
+ * (e.g., because the user is leaving the client application) SHOULD send an
216778
+ * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
216779
+ * terminate the session.
216780
+ *
216781
+ * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
216782
+ * the server does not allow clients to terminate sessions.
216783
+ */
216784
+ async terminateSession() {
216785
+ if (!this._sessionId) {
216786
+ return;
216787
+ }
216788
+ try {
216789
+ const headers = await this._commonHeaders();
216790
+ const init = {
216791
+ ...this._requestInit,
216792
+ method: "DELETE",
216793
+ headers,
216794
+ signal: this._abortController?.signal
216795
+ };
216796
+ const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
216762
216797
  await response.body?.cancel();
216798
+ if (!response.ok && response.status !== 405) {
216799
+ throw new StreamableHTTPError(response.status, `Failed to terminate session: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
216800
+ }
216801
+ this._sessionId = void 0;
216763
216802
  } catch (error40) {
216764
216803
  this.onerror?.(error40);
216765
216804
  throw error40;
@@ -216768,6 +216807,22 @@ var SSEClientTransport = class {
216768
216807
  setProtocolVersion(version2) {
216769
216808
  this._protocolVersion = version2;
216770
216809
  }
216810
+ get protocolVersion() {
216811
+ return this._protocolVersion;
216812
+ }
216813
+ /**
216814
+ * Resume an SSE stream from a previous event ID.
216815
+ * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
216816
+ *
216817
+ * @param lastEventId The event ID to resume from
216818
+ * @param options Optional callback to receive new resumption tokens
216819
+ */
216820
+ async resumeStream(lastEventId, options) {
216821
+ await this._startOrAuthSse({
216822
+ resumptionToken: lastEventId,
216823
+ onresumptiontoken: options?.onresumptiontoken
216824
+ });
216825
+ }
216771
216826
  };
216772
216827
 
216773
216828
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/signingFetch.js
@@ -216891,7 +216946,7 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
216891
216946
  };
216892
216947
  }
216893
216948
 
216894
- // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/sseTransportFactory.js
216949
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/streamableHttpTransportFactory.js
216895
216950
  function withTimeout(fetch3, timeoutMs) {
216896
216951
  return async (url2, init) => {
216897
216952
  if (init?.signal) {
@@ -216905,14 +216960,12 @@ function withTimeout(fetch3, timeoutMs) {
216905
216960
  }
216906
216961
  };
216907
216962
  }
216908
- function createSseTransport(config2, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
216963
+ function createStreamableHttpTransport(config2, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
216909
216964
  const url2 = new URL(config2.sseEndpoint, config2.remoteBaseUrl);
216910
216965
  const timeoutMs = config2.requestTimeoutMs ?? 18e4;
216911
216966
  const signingFetch = withTimeout(createSigningFetch(signer, void 0, onTraceId, debugLog, getCallHeaders, invocationContext), timeoutMs);
216912
- return new SSEClientTransport(url2, {
216913
- // SSE 建连(EventSource)的 GET fetch:SDK 先包默认头再调这里。
216914
- eventSourceInit: { fetch: signingFetch },
216915
- // MCP 发消息用的 POST fetch。
216967
+ return new StreamableHTTPClientTransport(url2, {
216968
+ // SDK 的所有 HTTP 请求统一经签名器,保留会话与协议协商请求头。
216916
216969
  fetch: signingFetch
216917
216970
  });
216918
216971
  }
@@ -217177,7 +217230,7 @@ var RemoteGatewayMcpServerProvider = class {
217177
217230
  const verifier = this.doCreateTokenVerifier(config2);
217178
217231
  const callHeaders = new import_node_async_hooks2.AsyncLocalStorage();
217179
217232
  const { client } = await connectMcpClientWithRetry(config2, {
217180
- createTransport: () => createSseTransport(config2, this.doCreateSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
217233
+ createTransport: () => createStreamableHttpTransport(config2, this.doCreateSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
217181
217234
  createClient: () => this.doCrateClient(),
217182
217235
  runConnect: (operation, attempt) => this.invocationContext.run(timeoutMs, connectSignal, operation, {
217183
217236
  observation,
@@ -219198,6 +219251,24 @@ function sanitizeAttributeValue(value) {
219198
219251
  }
219199
219252
 
219200
219253
  // ../linkque-agent-runtime/dist/esm/impl/telemetry/otelRuntimeTelemetry.js
219254
+ var InitialRootTraceIdGenerator = class {
219255
+ initialRootTraceId;
219256
+ fallback = new import_sdk_trace_base.RandomIdGenerator();
219257
+ constructor(initialRootTraceId) {
219258
+ this.initialRootTraceId = initialRootTraceId;
219259
+ }
219260
+ generateTraceId() {
219261
+ if (this.initialRootTraceId) {
219262
+ const traceId = this.initialRootTraceId;
219263
+ this.initialRootTraceId = void 0;
219264
+ return traceId;
219265
+ }
219266
+ return this.fallback.generateTraceId();
219267
+ }
219268
+ generateSpanId() {
219269
+ return this.fallback.generateSpanId();
219270
+ }
219271
+ };
219201
219272
  var OtelRuntimeTelemetry = class {
219202
219273
  options;
219203
219274
  queue;
@@ -219217,9 +219288,10 @@ var OtelRuntimeTelemetry = class {
219217
219288
  this.options = options;
219218
219289
  this.queue = new IdentityQueue(options);
219219
219290
  const ratio = options.sampleRatio ?? 1;
219291
+ const initialRootTraceId = options.initialRootTraceId?.toLowerCase();
219220
219292
  this.maxActive = options.maxActiveOperations ?? 4096;
219221
219293
  this.maxAge = options.operationMaxAgeMs ?? 24 * 60 * 60 * 1e3;
219222
- if (!options.serviceName || !options.serviceVersion || !options.environment || !Number.isFinite(ratio) || ratio < 0 || ratio > 1 || !Number.isSafeInteger(this.maxActive) || this.maxActive < 1 || !Number.isSafeInteger(this.maxAge) || this.maxAge < 1)
219294
+ if (!options.serviceName || !options.serviceVersion || !options.environment || !Number.isFinite(ratio) || ratio < 0 || ratio > 1 || !Number.isSafeInteger(this.maxActive) || this.maxActive < 1 || !Number.isSafeInteger(this.maxAge) || this.maxAge < 1 || initialRootTraceId !== void 0 && !isValidTraceId(initialRootTraceId))
219223
219295
  throw new Error("\u975E\u6CD5\u9065\u6D4B\u5B9E\u4F8B\u914D\u7F6E");
219224
219296
  const resource = (0, import_resources.resourceFromAttributes)({
219225
219297
  [ETelemetryAttribute.SERVICE_NAME]: options.serviceName,
@@ -219230,6 +219302,7 @@ var OtelRuntimeTelemetry = class {
219230
219302
  });
219231
219303
  this.tracerProvider = new import_sdk_trace_base.BasicTracerProvider({
219232
219304
  resource,
219305
+ idGenerator: new InitialRootTraceIdGenerator(initialRootTraceId),
219233
219306
  sampler: new import_sdk_trace_base.ParentBasedSampler({
219234
219307
  root: new import_sdk_trace_base.TraceIdRatioBasedSampler(ratio)
219235
219308
  }),
@@ -219925,7 +219998,7 @@ var import_http219 = require("http");
219925
219998
  var import_promises7 = require("fs/promises");
219926
219999
  var import_os = require("os");
219927
220000
  var import_path59 = __toESM(require("path"));
219928
- var import_stream2 = require("stream");
220001
+ var import_stream3 = require("stream");
219929
220002
 
219930
220003
  // src/commands/agentdev/sandboxIntegrate/protocolReader.ts
219931
220004
  var import_promises4 = require("fs/promises");
@@ -220174,7 +220247,7 @@ function createMcpConfigResolver(options) {
220174
220247
  remoteBaseUrl,
220175
220248
  // 兼容存量配置误用 mcpName(协议字段为 serverName);两者都没有时落到 undefined,
220176
220249
  // 上游 sseEndpoint 会显式带 undefined 便于诊断。
220177
- sseEndpoint: `api/v1/open/mcps/${resolveServerName(resource.config)}/sse`,
220250
+ sseEndpoint: `api/v1/open/mcps/${resolveServerName(resource.config)}/mcp`,
220178
220251
  agentId: options.agentId,
220179
220252
  ...options.signEndpoint ? { signEndpoint: options.signEndpoint } : {},
220180
220253
  ...options.verifyTokenEndpoint ? { verifyTokenEndpoint: options.verifyTokenEndpoint } : {},
@@ -220194,7 +220267,7 @@ var LOG_MAX_BYTES = 1024 * 1024;
220194
220267
  var LOG_ROTATIONS = 3;
220195
220268
  var SHUTDOWN_GRACE_MS = 2500;
220196
220269
  var HOME_DATA_TRUSTED_CONTEXT_FIELD = "_trustedContext_";
220197
- var RotatingLogWriter = class extends import_stream2.Writable {
220270
+ var RotatingLogWriter = class extends import_stream3.Writable {
220198
220271
  constructor(logPath) {
220199
220272
  super();
220200
220273
  this.logPath = logPath;