linkque-cli-v2 1.6.11-alpha.0 → 1.6.11

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 +116 -9
  2. package/package.json +1 -1
  3. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-NE7CUP5E.js → chunk-3J4AB676.js} +1 -1
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-H7TMASQH.js → chunk-DPHKD4SK.js} +633 -558
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-FA5CNADA.js → chunk-EHNI5TX3.js} +25 -1
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-DNTEEBEH.js → chunk-SICWMO5Y.js} +1 -0
  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-ZYAKAOUL.js → mistral-conversations-XUDTCRDY.js} +1 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{otel-BHGIWGIT.js → otel-3OUODIOB.js} +1 -1
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +25 -18
  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 +740 -666
package/worker.js CHANGED
@@ -9679,11 +9679,11 @@ function validateClientAction(body, path9, issues) {
9679
9679
  issues.push(issue2(`${path9}.context`, "INVALID_CLIENT_ACTION_CONTEXT", "ui.surface.open requires context.surfaceId"));
9680
9680
  return;
9681
9681
  }
9682
- if (body.name === "ui.page.open") {
9682
+ if (body.name === "ui.page.open" || body.name === "ui.miniprogram.embed") {
9683
9683
  if (!isPlainRecord(body.context) || Object.keys(body.context).length !== 1 || typeof body.context.url !== "string" && !isStrictBinding(body.context.url))
9684
- issues.push(issue2(`${path9}.context`, "INVALID_CLIENT_ACTION_CONTEXT", "ui.page.open requires one literal or bound URL"));
9684
+ issues.push(issue2(`${path9}.context`, "INVALID_CLIENT_ACTION_CONTEXT", `${body.name} requires one literal or bound URL`));
9685
9685
  else if (typeof body.context.url === "string" && !isSafePageUrl(body.context.url))
9686
- issues.push(issue2(`${path9}.context.url`, "INVALID_PAGE_URL", "ui.page.open URL must use https or the approved Alipay scheme"));
9686
+ issues.push(issue2(`${path9}.context.url`, "INVALID_PAGE_URL", `${body.name} URL must use https or the approved Alipay scheme`));
9687
9687
  return;
9688
9688
  }
9689
9689
  issues.push(issue2(`${path9}.name`, "UNSUPPORTED_CLIENT_ACTION", `unsupported client action ${String(body.name)}`));
@@ -36748,6 +36748,110 @@ var init_abortableDelay = __esm({
36748
36748
  }
36749
36749
  });
36750
36750
 
36751
+ // ../../node_modules/content-type/index.js
36752
+ var require_content_type = __commonJS({
36753
+ "../../node_modules/content-type/index.js"(exports2) {
36754
+ "use strict";
36755
+ var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
36756
+ var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/;
36757
+ var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
36758
+ var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
36759
+ var QUOTE_REGEXP = /([\\"])/g;
36760
+ var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
36761
+ exports2.format = format;
36762
+ exports2.parse = parse5;
36763
+ function format(obj) {
36764
+ if (!obj || typeof obj !== "object") {
36765
+ throw new TypeError("argument obj is required");
36766
+ }
36767
+ var parameters = obj.parameters;
36768
+ var type = obj.type;
36769
+ if (!type || !TYPE_REGEXP.test(type)) {
36770
+ throw new TypeError("invalid type");
36771
+ }
36772
+ var string4 = type;
36773
+ if (parameters && typeof parameters === "object") {
36774
+ var param;
36775
+ var params = Object.keys(parameters).sort();
36776
+ for (var i2 = 0; i2 < params.length; i2++) {
36777
+ param = params[i2];
36778
+ if (!TOKEN_REGEXP.test(param)) {
36779
+ throw new TypeError("invalid parameter name");
36780
+ }
36781
+ string4 += "; " + param + "=" + qstring(parameters[param]);
36782
+ }
36783
+ }
36784
+ return string4;
36785
+ }
36786
+ function parse5(string4) {
36787
+ if (!string4) {
36788
+ throw new TypeError("argument string is required");
36789
+ }
36790
+ var header = typeof string4 === "object" ? getcontenttype(string4) : string4;
36791
+ if (typeof header !== "string") {
36792
+ throw new TypeError("argument string is required to be a string");
36793
+ }
36794
+ var index2 = header.indexOf(";");
36795
+ var type = index2 !== -1 ? header.slice(0, index2).trim() : header.trim();
36796
+ if (!TYPE_REGEXP.test(type)) {
36797
+ throw new TypeError("invalid media type");
36798
+ }
36799
+ var obj = new ContentType(type.toLowerCase());
36800
+ if (index2 !== -1) {
36801
+ var key;
36802
+ var match2;
36803
+ var value;
36804
+ PARAM_REGEXP.lastIndex = index2;
36805
+ while (match2 = PARAM_REGEXP.exec(header)) {
36806
+ if (match2.index !== index2) {
36807
+ throw new TypeError("invalid parameter format");
36808
+ }
36809
+ index2 += match2[0].length;
36810
+ key = match2[1].toLowerCase();
36811
+ value = match2[2];
36812
+ if (value.charCodeAt(0) === 34) {
36813
+ value = value.slice(1, -1);
36814
+ if (value.indexOf("\\") !== -1) {
36815
+ value = value.replace(QESC_REGEXP, "$1");
36816
+ }
36817
+ }
36818
+ obj.parameters[key] = value;
36819
+ }
36820
+ if (index2 !== header.length) {
36821
+ throw new TypeError("invalid parameter format");
36822
+ }
36823
+ }
36824
+ return obj;
36825
+ }
36826
+ function getcontenttype(obj) {
36827
+ var header;
36828
+ if (typeof obj.getHeader === "function") {
36829
+ header = obj.getHeader("content-type");
36830
+ } else if (typeof obj.headers === "object") {
36831
+ header = obj.headers && obj.headers["content-type"];
36832
+ }
36833
+ if (typeof header !== "string") {
36834
+ throw new TypeError("content-type header is missing from object");
36835
+ }
36836
+ return header;
36837
+ }
36838
+ function qstring(val) {
36839
+ var str2 = String(val);
36840
+ if (TOKEN_REGEXP.test(str2)) {
36841
+ return str2;
36842
+ }
36843
+ if (str2.length > 0 && !TEXT_REGEXP.test(str2)) {
36844
+ throw new TypeError("invalid parameter value");
36845
+ }
36846
+ return '"' + str2.replace(QUOTE_REGEXP, "\\$1") + '"';
36847
+ }
36848
+ function ContentType(type) {
36849
+ this.parameters = /* @__PURE__ */ Object.create(null);
36850
+ this.type = type;
36851
+ }
36852
+ }
36853
+ });
36854
+
36751
36855
  // ../../node_modules/@ag-ui/core/node_modules/zod/v3/helpers/util.js
36752
36856
  var util2, objectUtil2, ZodParsedType2, getParsedType3;
36753
36857
  var init_util3 = __esm({
@@ -49156,7 +49260,7 @@ var require_RandomIdGenerator = __commonJS({
49156
49260
  exports2.RandomIdGenerator = void 0;
49157
49261
  var SPAN_ID_BYTES = 8;
49158
49262
  var TRACE_ID_BYTES = 16;
49159
- var RandomIdGenerator = class {
49263
+ var RandomIdGenerator2 = class {
49160
49264
  /**
49161
49265
  * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
49162
49266
  * characters corresponding to 128 bits.
@@ -49168,7 +49272,7 @@ var require_RandomIdGenerator = __commonJS({
49168
49272
  */
49169
49273
  generateSpanId = getIdGenerator(SPAN_ID_BYTES);
49170
49274
  };
49171
- exports2.RandomIdGenerator = RandomIdGenerator;
49275
+ exports2.RandomIdGenerator = RandomIdGenerator2;
49172
49276
  var SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
49173
49277
  function getIdGenerator(bytes2) {
49174
49278
  return function generateId() {
@@ -59077,8 +59181,8 @@ async function defaultParseResponse(client, props) {
59077
59181
  if (props.options.__binaryResponse) {
59078
59182
  return response;
59079
59183
  }
59080
- const contentType = response.headers.get("content-type");
59081
- const mediaType = contentType?.split(";")[0]?.trim();
59184
+ const contentType2 = response.headers.get("content-type");
59185
+ const mediaType = contentType2?.split(";")[0]?.trim();
59082
59186
  const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
59083
59187
  if (isJSON) {
59084
59188
  const contentLength = response.headers.get("content-length");
@@ -59383,9 +59487,9 @@ var init_uploads = __esm({
59383
59487
  form.append(key, String(value));
59384
59488
  } else if (value instanceof Response) {
59385
59489
  let options = {};
59386
- const contentType = value.headers.get("Content-Type");
59387
- if (contentType) {
59388
- options = { type: contentType };
59490
+ const contentType2 = value.headers.get("Content-Type");
59491
+ if (contentType2) {
59492
+ options = { type: contentType2 };
59389
59493
  }
59390
59494
  form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options));
59391
59495
  } else if (isAsyncIterable(value)) {
@@ -68514,8 +68618,8 @@ async function defaultParseResponse2(client, props) {
68514
68618
  if (props.options.__binaryResponse) {
68515
68619
  return response;
68516
68620
  }
68517
- const contentType = response.headers.get("content-type");
68518
- const mediaType = contentType?.split(";")[0]?.trim();
68621
+ const contentType2 = response.headers.get("content-type");
68622
+ const mediaType = contentType2?.split(";")[0]?.trim();
68519
68623
  const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
68520
68624
  if (isJSON) {
68521
68625
  const contentLength = response.headers.get("content-length");
@@ -81969,7 +82073,7 @@ var require_ponyfill_es2018 = __commonJS({
81969
82073
  assertFunction(fn, context2);
81970
82074
  return (reason) => promiseCall(fn, original, [reason]);
81971
82075
  }
81972
- class TransformStream {
82076
+ class TransformStream2 {
81973
82077
  constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
81974
82078
  if (rawTransformer === void 0) {
81975
82079
  rawTransformer = null;
@@ -82018,12 +82122,12 @@ var require_ponyfill_es2018 = __commonJS({
82018
82122
  return this._writable;
82019
82123
  }
82020
82124
  }
82021
- Object.defineProperties(TransformStream.prototype, {
82125
+ Object.defineProperties(TransformStream2.prototype, {
82022
82126
  readable: { enumerable: true },
82023
82127
  writable: { enumerable: true }
82024
82128
  });
82025
82129
  if (typeof Symbol.toStringTag === "symbol") {
82026
- Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {
82130
+ Object.defineProperty(TransformStream2.prototype, Symbol.toStringTag, {
82027
82131
  value: "TransformStream",
82028
82132
  configurable: true
82029
82133
  });
@@ -82062,7 +82166,7 @@ var require_ponyfill_es2018 = __commonJS({
82062
82166
  if (!Object.prototype.hasOwnProperty.call(x2, "_transformStreamController")) {
82063
82167
  return false;
82064
82168
  }
82065
- return x2 instanceof TransformStream;
82169
+ return x2 instanceof TransformStream2;
82066
82170
  }
82067
82171
  function TransformStreamError(stream11, e2) {
82068
82172
  ReadableStreamDefaultControllerError(stream11._readable._readableStreamController, e2);
@@ -82363,7 +82467,7 @@ var require_ponyfill_es2018 = __commonJS({
82363
82467
  exports3.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
82364
82468
  exports3.ReadableStreamDefaultController = ReadableStreamDefaultController;
82365
82469
  exports3.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
82366
- exports3.TransformStream = TransformStream;
82470
+ exports3.TransformStream = TransformStream2;
82367
82471
  exports3.TransformStreamDefaultController = TransformStreamDefaultController;
82368
82472
  exports3.WritableStream = WritableStream;
82369
82473
  exports3.WritableStreamDefaultController = WritableStreamDefaultController;
@@ -82942,7 +83046,7 @@ async function toFormData(Body2, ct) {
82942
83046
  let headerValue;
82943
83047
  let entryValue;
82944
83048
  let entryName;
82945
- let contentType;
83049
+ let contentType2;
82946
83050
  let filename;
82947
83051
  const entryChunks = [];
82948
83052
  const formData = new FormData2();
@@ -82953,7 +83057,7 @@ async function toFormData(Body2, ct) {
82953
83057
  entryChunks.push(ui8a);
82954
83058
  };
82955
83059
  const appendFileToFormData = () => {
82956
- const file2 = new file_default(entryChunks, filename, { type: contentType });
83060
+ const file2 = new file_default(entryChunks, filename, { type: contentType2 });
82957
83061
  formData.append(entryName, file2);
82958
83062
  };
82959
83063
  const appendEntryToFormData = () => {
@@ -82968,7 +83072,7 @@ async function toFormData(Body2, ct) {
82968
83072
  headerValue = "";
82969
83073
  entryValue = "";
82970
83074
  entryName = "";
82971
- contentType = "";
83075
+ contentType2 = "";
82972
83076
  filename = null;
82973
83077
  entryChunks.length = 0;
82974
83078
  };
@@ -82992,7 +83096,7 @@ async function toFormData(Body2, ct) {
82992
83096
  parser.onPartEnd = appendFileToFormData;
82993
83097
  }
82994
83098
  } else if (headerField === "content-type") {
82995
- contentType = headerValue;
83099
+ contentType2 = headerValue;
82996
83100
  }
82997
83101
  headerValue = "";
82998
83102
  headerField = "";
@@ -83744,9 +83848,9 @@ var init_response = __esm({
83744
83848
  const status = options.status != null ? options.status : 200;
83745
83849
  const headers = new Headers2(options.headers);
83746
83850
  if (body !== null && !headers.has("Content-Type")) {
83747
- const contentType = extractContentType(body, this);
83748
- if (contentType) {
83749
- headers.append("Content-Type", contentType);
83851
+ const contentType2 = extractContentType(body, this);
83852
+ if (contentType2) {
83853
+ headers.append("Content-Type", contentType2);
83750
83854
  }
83751
83855
  }
83752
83856
  this[INTERNALS2] = {
@@ -84065,9 +84169,9 @@ var init_request = __esm({
84065
84169
  });
84066
84170
  const headers = new Headers2(init.headers || input.headers || {});
84067
84171
  if (inputBody !== null && !headers.has("Content-Type")) {
84068
- const contentType = extractContentType(inputBody, this);
84069
- if (contentType) {
84070
- headers.set("Content-Type", contentType);
84172
+ const contentType2 = extractContentType(inputBody, this);
84173
+ if (contentType2) {
84174
+ headers.set("Content-Type", contentType2);
84071
84175
  }
84072
84176
  }
84073
84177
  let signal = isRequest(input) ? input.signal : null;
@@ -84907,19 +85011,19 @@ var require_gaxios = __commonJS({
84907
85011
  * @returns a promise that resolves to the response data.
84908
85012
  */
84909
85013
  async getResponseDataFromContentType(response) {
84910
- let contentType = response.headers.get("Content-Type");
84911
- if (contentType === null) {
85014
+ let contentType2 = response.headers.get("Content-Type");
85015
+ if (contentType2 === null) {
84912
85016
  return response.text();
84913
85017
  }
84914
- contentType = contentType.toLowerCase();
84915
- if (contentType.includes("application/json")) {
85018
+ contentType2 = contentType2.toLowerCase();
85019
+ if (contentType2.includes("application/json")) {
84916
85020
  let data = await response.text();
84917
85021
  try {
84918
85022
  data = JSON.parse(data);
84919
85023
  } catch {
84920
85024
  }
84921
85025
  return data;
84922
- } else if (contentType.match(/^text\//)) {
85026
+ } else if (contentType2.match(/^text\//)) {
84923
85027
  return response.text();
84924
85028
  } else {
84925
85029
  return response.blob();
@@ -91227,20 +91331,20 @@ var require_oauth2common = __commonJS({
91227
91331
  throw new Error(`${method} HTTP method does not support ${this.#clientAuthentication.confidentialClientType} client authentication`);
91228
91332
  }
91229
91333
  const headers = new Headers(opts.headers);
91230
- const contentType = headers.get("content-type");
91231
- if (contentType?.startsWith("application/x-www-form-urlencoded") || opts.data instanceof URLSearchParams) {
91334
+ const contentType2 = headers.get("content-type");
91335
+ if (contentType2?.startsWith("application/x-www-form-urlencoded") || opts.data instanceof URLSearchParams) {
91232
91336
  const data = new URLSearchParams(opts.data ?? "");
91233
91337
  data.append("client_id", this.#clientAuthentication.clientId);
91234
91338
  data.append("client_secret", this.#clientAuthentication.clientSecret || "");
91235
91339
  opts.data = data;
91236
- } else if (contentType?.startsWith("application/json")) {
91340
+ } else if (contentType2?.startsWith("application/json")) {
91237
91341
  opts.data = opts.data || {};
91238
91342
  Object.assign(opts.data, {
91239
91343
  client_id: this.#clientAuthentication.clientId,
91240
91344
  client_secret: this.#clientAuthentication.clientSecret || ""
91241
91345
  });
91242
91346
  } else {
91243
- throw new Error(`${contentType} content-types are not supported with ${this.#clientAuthentication.confidentialClientType} client authentication`);
91347
+ throw new Error(`${contentType2} content-types are not supported with ${this.#clientAuthentication.confidentialClientType} client authentication`);
91244
91348
  }
91245
91349
  }
91246
91350
  }
@@ -96589,7 +96693,7 @@ var require_event_target = __commonJS({
96589
96693
  var kTarget = Symbol("kTarget");
96590
96694
  var kType = Symbol("kType");
96591
96695
  var kWasClean = Symbol("kWasClean");
96592
- var Event3 = class {
96696
+ var Event2 = class {
96593
96697
  /**
96594
96698
  * Create a new `Event`.
96595
96699
  *
@@ -96613,9 +96717,9 @@ var require_event_target = __commonJS({
96613
96717
  return this[kType];
96614
96718
  }
96615
96719
  };
96616
- Object.defineProperty(Event3.prototype, "target", { enumerable: true });
96617
- Object.defineProperty(Event3.prototype, "type", { enumerable: true });
96618
- var CloseEvent = class extends Event3 {
96720
+ Object.defineProperty(Event2.prototype, "target", { enumerable: true });
96721
+ Object.defineProperty(Event2.prototype, "type", { enumerable: true });
96722
+ var CloseEvent = class extends Event2 {
96619
96723
  /**
96620
96724
  * Create a new `CloseEvent`.
96621
96725
  *
@@ -96657,7 +96761,7 @@ var require_event_target = __commonJS({
96657
96761
  Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
96658
96762
  Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
96659
96763
  Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
96660
- var ErrorEvent2 = class extends Event3 {
96764
+ var ErrorEvent = class extends Event2 {
96661
96765
  /**
96662
96766
  * Create a new `ErrorEvent`.
96663
96767
  *
@@ -96685,9 +96789,9 @@ var require_event_target = __commonJS({
96685
96789
  return this[kMessage];
96686
96790
  }
96687
96791
  };
96688
- Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: true });
96689
- Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: true });
96690
- var MessageEvent2 = class extends Event3 {
96792
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
96793
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
96794
+ var MessageEvent = class extends Event2 {
96691
96795
  /**
96692
96796
  * Create a new `MessageEvent`.
96693
96797
  *
@@ -96707,8 +96811,8 @@ var require_event_target = __commonJS({
96707
96811
  return this[kData];
96708
96812
  }
96709
96813
  };
96710
- Object.defineProperty(MessageEvent2.prototype, "data", { enumerable: true });
96711
- var EventTarget2 = {
96814
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
96815
+ var EventTarget = {
96712
96816
  /**
96713
96817
  * Register an event listener.
96714
96818
  *
@@ -96730,7 +96834,7 @@ var require_event_target = __commonJS({
96730
96834
  let wrapper;
96731
96835
  if (type === "message") {
96732
96836
  wrapper = function onMessage(data, isBinary) {
96733
- const event = new MessageEvent2("message", {
96837
+ const event = new MessageEvent("message", {
96734
96838
  data: isBinary ? data : data.toString()
96735
96839
  });
96736
96840
  event[kTarget] = this;
@@ -96748,7 +96852,7 @@ var require_event_target = __commonJS({
96748
96852
  };
96749
96853
  } else if (type === "error") {
96750
96854
  wrapper = function onError(error51) {
96751
- const event = new ErrorEvent2("error", {
96855
+ const event = new ErrorEvent("error", {
96752
96856
  error: error51,
96753
96857
  message: error51.message
96754
96858
  });
@@ -96757,7 +96861,7 @@ var require_event_target = __commonJS({
96757
96861
  };
96758
96862
  } else if (type === "open") {
96759
96863
  wrapper = function onOpen() {
96760
- const event = new Event3("open");
96864
+ const event = new Event2("open");
96761
96865
  event[kTarget] = this;
96762
96866
  callListener(handler, this, event);
96763
96867
  };
@@ -96790,10 +96894,10 @@ var require_event_target = __commonJS({
96790
96894
  };
96791
96895
  module2.exports = {
96792
96896
  CloseEvent,
96793
- ErrorEvent: ErrorEvent2,
96794
- Event: Event3,
96795
- EventTarget: EventTarget2,
96796
- MessageEvent: MessageEvent2
96897
+ ErrorEvent,
96898
+ Event: Event2,
96899
+ EventTarget,
96900
+ MessageEvent
96797
96901
  };
96798
96902
  function callListener(listener, thisArg, event) {
96799
96903
  if (typeof listener === "object" && listener.handleEvent) {
@@ -98399,10 +98503,10 @@ var require_websocket_server = __commonJS({
98399
98503
  });
98400
98504
 
98401
98505
  // ../../node_modules/ws/wrapper.mjs
98402
- var import_stream, import_extension, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket, import_websocket_server;
98506
+ var import_stream2, import_extension, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket, import_websocket_server;
98403
98507
  var init_wrapper = __esm({
98404
98508
  "../../node_modules/ws/wrapper.mjs"() {
98405
- import_stream = __toESM(require_stream(), 1);
98509
+ import_stream2 = __toESM(require_stream(), 1);
98406
98510
  import_extension = __toESM(require_extension(), 1);
98407
98511
  import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
98408
98512
  import_receiver = __toESM(require_receiver(), 1);
@@ -108084,8 +108188,8 @@ async function defaultParseResponse3(client, props) {
108084
108188
  if (props.options.__binaryResponse) {
108085
108189
  return response;
108086
108190
  }
108087
- const contentType = response.headers.get("content-type");
108088
- const mediaType = (_a8 = contentType === null || contentType === void 0 ? void 0 : contentType.split(";")[0]) === null || _a8 === void 0 ? void 0 : _a8.trim();
108191
+ const contentType2 = response.headers.get("content-type");
108192
+ const mediaType = (_a8 = contentType2 === null || contentType2 === void 0 ? void 0 : contentType2.split(";")[0]) === null || _a8 === void 0 ? void 0 : _a8.trim();
108089
108193
  const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes("application/json")) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith("+json"));
108090
108194
  if (isJSON) {
108091
108195
  const contentLength = response.headers.get("content-length");
@@ -117581,11 +117685,11 @@ function getContentTypeFromFileName(fileName) {
117581
117685
  };
117582
117686
  return mimeTypes[ext] || null;
117583
117687
  }
117584
- function bytesToBlob(content, contentType) {
117688
+ function bytesToBlob(content, contentType2) {
117585
117689
  if (content instanceof Uint8Array) {
117586
- return new Blob([new Uint8Array(content)], { type: contentType });
117690
+ return new Blob([new Uint8Array(content)], { type: contentType2 });
117587
117691
  }
117588
- return new Blob([content], { type: contentType });
117692
+ return new Blob([content], { type: contentType2 });
117589
117693
  }
117590
117694
  var init_files5 = __esm({
117591
117695
  "../../node_modules/@mistralai/mistralai/esm/lib/files.js"() {
@@ -117597,14 +117701,14 @@ function matchContentType(response, pattern) {
117597
117701
  if (pattern === "*") {
117598
117702
  return true;
117599
117703
  }
117600
- let contentType = response.headers.get("content-type")?.trim() || "application/octet-stream";
117601
- contentType = contentType.toLowerCase();
117704
+ let contentType2 = response.headers.get("content-type")?.trim() || "application/octet-stream";
117705
+ contentType2 = contentType2.toLowerCase();
117602
117706
  const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator);
117603
117707
  const [wantType = "", ...wantParams] = wantParts;
117604
117708
  if (wantType.split("/").length !== 2) {
117605
117709
  return false;
117606
117710
  }
117607
- const gotParts = contentType.split(mediaParamSeparator);
117711
+ const gotParts = contentType2.split(mediaParamSeparator);
117608
117712
  const [gotType = "", ...gotParams] = gotParts;
117609
117713
  const [type = "", subtype = ""] = gotType.split("/");
117610
117714
  if (!type || !subtype) {
@@ -123623,8 +123727,8 @@ function inferGenAiOperationName(operationId) {
123623
123727
  function isKnownGenAiOperation(operationId) {
123624
123728
  return inferGenAiOperationName(operationId) !== null;
123625
123729
  }
123626
- function isJsonContentType(contentType) {
123627
- const mediaType = contentType?.split(";")[0]?.trim().toLowerCase();
123730
+ function isJsonContentType(contentType2) {
123731
+ const mediaType = contentType2?.split(";")[0]?.trim().toLowerCase();
123628
123732
  return mediaType === "application/json" || mediaType === "text/json" || mediaType?.endsWith("+json") === true;
123629
123733
  }
123630
123734
  function buildGenaiSpanName(genAiOp, body) {
@@ -124823,8 +124927,8 @@ async function logRequest(logger, req) {
124823
124927
  if (!logger) {
124824
124928
  return;
124825
124929
  }
124826
- const contentType = req.headers.get("content-type");
124827
- const ct = contentType?.split(";")[0] || "";
124930
+ const contentType2 = req.headers.get("content-type");
124931
+ const ct = contentType2?.split(";")[0] || "";
124828
124932
  logger.group(`> Request: ${req.method} ${req.url}`);
124829
124933
  logger.group("Headers:");
124830
124934
  for (const [k, v] of req.headers.entries()) {
@@ -124848,7 +124952,7 @@ async function logRequest(logger, req) {
124848
124952
  break;
124849
124953
  }
124850
124954
  default:
124851
- logger.log(`<${contentType}>`);
124955
+ logger.log(`<${contentType2}>`);
124852
124956
  break;
124853
124957
  }
124854
124958
  logger.groupEnd();
@@ -124858,8 +124962,8 @@ async function logResponse(logger, res, req) {
124858
124962
  if (!logger) {
124859
124963
  return;
124860
124964
  }
124861
- const contentType = res.headers.get("content-type");
124862
- const ct = contentType?.split(";")[0] || "";
124965
+ const contentType2 = res.headers.get("content-type");
124966
+ const ct = contentType2?.split(";")[0] || "";
124863
124967
  logger.group(`< Response: ${req.method} ${req.url}`);
124864
124968
  logger.log("Status Code:", res.status, res.statusText);
124865
124969
  logger.group("Headers:");
@@ -124874,7 +124978,7 @@ async function logResponse(logger, res, req) {
124874
124978
  break;
124875
124979
  case (matchContentType(res, "application/jsonl") || jsonlLikeContentTypeRE.test(ct)):
124876
124980
  case matchContentType(res, "text/event-stream"):
124877
- logger.log(`<${contentType}>`);
124981
+ logger.log(`<${contentType2}>`);
124878
124982
  break;
124879
124983
  case matchContentType(res, "text/*"):
124880
124984
  logger.log(await res.clone().text());
@@ -124888,7 +124992,7 @@ async function logResponse(logger, res, req) {
124888
124992
  break;
124889
124993
  }
124890
124994
  default:
124891
- logger.log(`<${contentType}>`);
124995
+ logger.log(`<${contentType2}>`);
124892
124996
  break;
124893
124997
  }
124894
124998
  logger.groupEnd();
@@ -125143,9 +125247,9 @@ var init_sdkerror = __esm({
125143
125247
  message += `: `;
125144
125248
  }
125145
125249
  message += `Status ${httpMeta.response.status}`;
125146
- const contentType = httpMeta.response.headers.get("content-type") || `""`;
125147
- if (contentType !== "application/json") {
125148
- message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`;
125250
+ const contentType2 = httpMeta.response.headers.get("content-type") || `""`;
125251
+ if (contentType2 !== "application/json") {
125252
+ message += ` Content-Type ${contentType2.includes(" ") ? `"${contentType2}"` : contentType2}`;
125149
125253
  }
125150
125254
  const body = httpMeta.body || `""`;
125151
125255
  message += body.length > 100 ? "\n" : ". ";
@@ -133071,16 +133175,16 @@ var init_eventprogressstatus = __esm({
133071
133175
  });
133072
133176
 
133073
133177
  // ../../node_modules/@mistralai/mistralai/esm/models/components/eventsource.js
133074
- var EventSource2, EventSource$outboundSchema;
133178
+ var EventSource, EventSource$outboundSchema;
133075
133179
  var init_eventsource = __esm({
133076
133180
  "../../node_modules/@mistralai/mistralai/esm/models/components/eventsource.js"() {
133077
133181
  init_v4();
133078
- EventSource2 = {
133182
+ EventSource = {
133079
133183
  Database: "DATABASE",
133080
133184
  Live: "LIVE",
133081
133185
  Hybrid: "HYBRID"
133082
133186
  };
133083
- EventSource$outboundSchema = _enum2(EventSource2);
133187
+ EventSource$outboundSchema = _enum2(EventSource);
133084
133188
  }
133085
133189
  });
133086
133190
 
@@ -142886,7 +142990,7 @@ var init_streamv1workflowsexecutionsexecutionidstreamget = __esm({
142886
142990
  });
142887
142991
 
142888
142992
  // ../../node_modules/@mistralai/mistralai/esm/models/operations/streamworkflowexecutionlogs.js
142889
- var Event2, StreamWorkflowExecutionLogsRequest$outboundSchema, Event$inboundSchema2, StreamWorkflowExecutionLogsData$inboundSchema, StreamWorkflowExecutionLogsResponseBody$inboundSchema;
142993
+ var Event, StreamWorkflowExecutionLogsRequest$outboundSchema, Event$inboundSchema2, StreamWorkflowExecutionLogsData$inboundSchema, StreamWorkflowExecutionLogsResponseBody$inboundSchema;
142890
142994
  var init_streamworkflowexecutionlogs = __esm({
142891
142995
  "../../node_modules/@mistralai/mistralai/esm/models/operations/streamworkflowexecutionlogs.js"() {
142892
142996
  init_v4();
@@ -142894,7 +142998,7 @@ var init_streamworkflowexecutionlogs = __esm({
142894
142998
  init_enums();
142895
142999
  init_smartUnion();
142896
143000
  init_components();
142897
- Event2 = {
143001
+ Event = {
142898
143002
  Log: "log",
142899
143003
  Error: "error"
142900
143004
  };
@@ -142912,7 +143016,7 @@ var init_streamworkflowexecutionlogs = __esm({
142912
143016
  lastEventId: "last_event_id"
142913
143017
  });
142914
143018
  });
142915
- Event$inboundSchema2 = inboundSchema(Event2);
143019
+ Event$inboundSchema2 = inboundSchema(Event);
142916
143020
  StreamWorkflowExecutionLogsData$inboundSchema = smartUnion([
142917
143021
  ExecutionLogRecord$inboundSchema,
142918
143022
  StreamError$inboundSchema
@@ -143495,11 +143599,11 @@ async function $do4(client, request, options) {
143495
143599
  appendForm(body, "file", blob, name);
143496
143600
  } else if (isReadableStream(payload.file.content)) {
143497
143601
  const buffer = await readableStreamToArrayBuffer(payload.file.content);
143498
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
143499
- appendForm(body, "file", bytesToBlob(buffer, contentType), payload.file.fileName);
143602
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
143603
+ appendForm(body, "file", bytesToBlob(buffer, contentType2), payload.file.fileName);
143500
143604
  } else {
143501
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
143502
- appendForm(body, "file", bytesToBlob(payload.file.content, contentType), payload.file.fileName);
143605
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
143606
+ appendForm(body, "file", bytesToBlob(payload.file.content, contentType2), payload.file.fileName);
143503
143607
  }
143504
143608
  }
143505
143609
  if (payload.file_id !== void 0) {
@@ -143610,11 +143714,11 @@ async function $do5(client, request, options) {
143610
143714
  appendForm(body, "file", blob, name);
143611
143715
  } else if (isReadableStream(payload.file.content)) {
143612
143716
  const buffer = await readableStreamToArrayBuffer(payload.file.content);
143613
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
143614
- appendForm(body, "file", bytesToBlob(buffer, contentType), payload.file.fileName);
143717
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
143718
+ appendForm(body, "file", bytesToBlob(buffer, contentType2), payload.file.fileName);
143615
143719
  } else {
143616
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
143617
- appendForm(body, "file", bytesToBlob(payload.file.content, contentType), payload.file.fileName);
143720
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
143721
+ appendForm(body, "file", bytesToBlob(payload.file.content, contentType2), payload.file.fileName);
143618
143722
  }
143619
143723
  }
143620
143724
  if (payload.file_id !== void 0) {
@@ -150882,11 +150986,11 @@ async function $do82(client, request, options) {
150882
150986
  appendForm(body, "file", blob, name);
150883
150987
  } else if (isReadableStream(payload.RequestBody.file.content)) {
150884
150988
  const buffer = await readableStreamToArrayBuffer(payload.RequestBody.file.content);
150885
- const contentType = getContentTypeFromFileName(payload.RequestBody.file.fileName) || "application/octet-stream";
150886
- appendForm(body, "file", bytesToBlob(buffer, contentType), payload.RequestBody.file.fileName);
150989
+ const contentType2 = getContentTypeFromFileName(payload.RequestBody.file.fileName) || "application/octet-stream";
150990
+ appendForm(body, "file", bytesToBlob(buffer, contentType2), payload.RequestBody.file.fileName);
150887
150991
  } else {
150888
- const contentType = getContentTypeFromFileName(payload.RequestBody.file.fileName) || "application/octet-stream";
150889
- appendForm(body, "file", bytesToBlob(payload.RequestBody.file.content, contentType), payload.RequestBody.file.fileName);
150992
+ const contentType2 = getContentTypeFromFileName(payload.RequestBody.file.fileName) || "application/octet-stream";
150993
+ appendForm(body, "file", bytesToBlob(payload.RequestBody.file.content, contentType2), payload.RequestBody.file.fileName);
150890
150994
  }
150891
150995
  const pathParams = {
150892
150996
  library_id: encodeSimple("library_id", payload.library_id, {
@@ -158363,11 +158467,11 @@ async function $do159(client, request, options) {
158363
158467
  appendForm(body, "file", blob, name);
158364
158468
  } else if (isReadableStream(payload.file.content)) {
158365
158469
  const buffer = await readableStreamToArrayBuffer(payload.file.content);
158366
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
158367
- appendForm(body, "file", bytesToBlob(buffer, contentType), payload.file.fileName);
158470
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
158471
+ appendForm(body, "file", bytesToBlob(buffer, contentType2), payload.file.fileName);
158368
158472
  } else {
158369
- const contentType = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
158370
- appendForm(body, "file", bytesToBlob(payload.file.content, contentType), payload.file.fileName);
158473
+ const contentType2 = getContentTypeFromFileName(payload.file.fileName) || "application/octet-stream";
158474
+ appendForm(body, "file", bytesToBlob(payload.file.content, contentType2), payload.file.fileName);
158371
158475
  }
158372
158476
  if (payload.expiry !== void 0) {
158373
158477
  appendForm(body, "expiry", payload.expiry);
@@ -208012,7 +208116,7 @@ var require_int = __commonJS({
208012
208116
  tag: "tag:yaml.org,2002:int",
208013
208117
  format: "OCT",
208014
208118
  test: /^0o[0-7]+$/,
208015
- resolve: (str2, _onError2, opt) => intResolve(str2, 2, 8, opt),
208119
+ resolve: (str2, _onError, opt) => intResolve(str2, 2, 8, opt),
208016
208120
  stringify: (node) => intStringify(node, 8, "0o")
208017
208121
  };
208018
208122
  var int2 = {
@@ -208020,7 +208124,7 @@ var require_int = __commonJS({
208020
208124
  default: true,
208021
208125
  tag: "tag:yaml.org,2002:int",
208022
208126
  test: /^[-+]?[0-9]+$/,
208023
- resolve: (str2, _onError2, opt) => intResolve(str2, 0, 10, opt),
208127
+ resolve: (str2, _onError, opt) => intResolve(str2, 0, 10, opt),
208024
208128
  stringify: stringifyNumber.stringifyNumber
208025
208129
  };
208026
208130
  var intHex = {
@@ -208029,7 +208133,7 @@ var require_int = __commonJS({
208029
208133
  tag: "tag:yaml.org,2002:int",
208030
208134
  format: "HEX",
208031
208135
  test: /^0x[0-9a-fA-F]+$/,
208032
- resolve: (str2, _onError2, opt) => intResolve(str2, 2, 16, opt),
208136
+ resolve: (str2, _onError, opt) => intResolve(str2, 2, 16, opt),
208033
208137
  stringify: (node) => intStringify(node, 16, "0x")
208034
208138
  };
208035
208139
  exports2.int = int2;
@@ -208107,7 +208211,7 @@ var require_schema2 = __commonJS({
208107
208211
  default: true,
208108
208212
  tag: "tag:yaml.org,2002:int",
208109
208213
  test: /^-?(?:0|[1-9][0-9]*)$/,
208110
- resolve: (str2, _onError2, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10),
208214
+ resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10),
208111
208215
  stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
208112
208216
  },
208113
208217
  {
@@ -208479,7 +208583,7 @@ var require_int2 = __commonJS({
208479
208583
  tag: "tag:yaml.org,2002:int",
208480
208584
  format: "BIN",
208481
208585
  test: /^[-+]?0b[0-1_]+$/,
208482
- resolve: (str2, _onError2, opt) => intResolve(str2, 2, 2, opt),
208586
+ resolve: (str2, _onError, opt) => intResolve(str2, 2, 2, opt),
208483
208587
  stringify: (node) => intStringify(node, 2, "0b")
208484
208588
  };
208485
208589
  var intOct = {
@@ -208488,7 +208592,7 @@ var require_int2 = __commonJS({
208488
208592
  tag: "tag:yaml.org,2002:int",
208489
208593
  format: "OCT",
208490
208594
  test: /^[-+]?0[0-7_]+$/,
208491
- resolve: (str2, _onError2, opt) => intResolve(str2, 1, 8, opt),
208595
+ resolve: (str2, _onError, opt) => intResolve(str2, 1, 8, opt),
208492
208596
  stringify: (node) => intStringify(node, 8, "0")
208493
208597
  };
208494
208598
  var int2 = {
@@ -208496,7 +208600,7 @@ var require_int2 = __commonJS({
208496
208600
  default: true,
208497
208601
  tag: "tag:yaml.org,2002:int",
208498
208602
  test: /^[-+]?[0-9][0-9_]*$/,
208499
- resolve: (str2, _onError2, opt) => intResolve(str2, 0, 10, opt),
208603
+ resolve: (str2, _onError, opt) => intResolve(str2, 0, 10, opt),
208500
208604
  stringify: stringifyNumber.stringifyNumber
208501
208605
  };
208502
208606
  var intHex = {
@@ -208505,7 +208609,7 @@ var require_int2 = __commonJS({
208505
208609
  tag: "tag:yaml.org,2002:int",
208506
208610
  format: "HEX",
208507
208611
  test: /^[-+]?0x[0-9a-fA-F_]+$/,
208508
- resolve: (str2, _onError2, opt) => intResolve(str2, 2, 16, opt),
208612
+ resolve: (str2, _onError, opt) => intResolve(str2, 2, 16, opt),
208509
208613
  stringify: (node) => intStringify(node, 16, "0x")
208510
208614
  };
208511
208615
  exports2.int = int2;
@@ -208648,7 +208752,7 @@ var require_timestamp = __commonJS({
208648
208752
  tag: "tag:yaml.org,2002:int",
208649
208753
  format: "TIME",
208650
208754
  test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
208651
- resolve: (str2, _onError2, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt),
208755
+ resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt),
208652
208756
  stringify: stringifySexagesimal
208653
208757
  };
208654
208758
  var floatTime = {
@@ -210177,19 +210281,19 @@ var require_resolve_flow_scalar = __commonJS({
210177
210281
  const { offset, type, source, end } = scalar2;
210178
210282
  let _type;
210179
210283
  let value;
210180
- const _onError2 = (rel, code, msg) => onError(offset + rel, code, msg);
210284
+ const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
210181
210285
  switch (type) {
210182
210286
  case "scalar":
210183
210287
  _type = Scalar.Scalar.PLAIN;
210184
- value = plainValue(source, _onError2);
210288
+ value = plainValue(source, _onError);
210185
210289
  break;
210186
210290
  case "single-quoted-scalar":
210187
210291
  _type = Scalar.Scalar.QUOTE_SINGLE;
210188
- value = singleQuotedValue(source, _onError2);
210292
+ value = singleQuotedValue(source, _onError);
210189
210293
  break;
210190
210294
  case "double-quoted-scalar":
210191
210295
  _type = Scalar.Scalar.QUOTE_DOUBLE;
210192
- value = doubleQuotedValue(source, _onError2);
210296
+ value = doubleQuotedValue(source, _onError);
210193
210297
  break;
210194
210298
  default:
210195
210299
  onError(scalar2, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
@@ -210863,7 +210967,7 @@ var require_cst_scalar = __commonJS({
210863
210967
  var stringifyString = require_stringifyString();
210864
210968
  function resolveAsScalar(token, strict = true, onError) {
210865
210969
  if (token) {
210866
- const _onError2 = (pos, code, message) => {
210970
+ const _onError = (pos, code, message) => {
210867
210971
  const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
210868
210972
  if (onError)
210869
210973
  onError(offset, code, message);
@@ -210874,9 +210978,9 @@ var require_cst_scalar = __commonJS({
210874
210978
  case "scalar":
210875
210979
  case "single-quoted-scalar":
210876
210980
  case "double-quoted-scalar":
210877
- return resolveFlowScalar.resolveFlowScalar(token, strict, _onError2);
210981
+ return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
210878
210982
  case "block-scalar":
210879
- return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError2);
210983
+ return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
210880
210984
  }
210881
210985
  }
210882
210986
  return null;
@@ -214772,8 +214876,8 @@ async function resolvePromptImage(attachment, fetchImpl) {
214772
214876
  if (!response.ok) {
214773
214877
  throw new Error(`\u8BFB\u53D6\u56FE\u7247\u9644\u4EF6 ${attachment.name} \u5931\u8D25\uFF08${response.status}\uFF09\u3002`);
214774
214878
  }
214775
- const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
214776
- const mimeType = contentType?.startsWith("image/") ? contentType : attachment.mimeType;
214879
+ const contentType2 = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
214880
+ const mimeType = contentType2?.startsWith("image/") ? contentType2 : attachment.mimeType;
214777
214881
  return {
214778
214882
  type: "image",
214779
214883
  data: import_node_buffer3.Buffer.from(await response.arrayBuffer()).toString("base64"),
@@ -218992,6 +219096,7 @@ var InitializedNotificationSchema = NotificationSchema.extend({
218992
219096
  method: literal("notifications/initialized"),
218993
219097
  params: NotificationsParamsSchema.optional()
218994
219098
  });
219099
+ var isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;
218995
219100
  var PingRequestSchema = RequestSchema.extend({
218996
219101
  method: literal("ping"),
218997
219102
  params: BaseRequestParamsSchema.optional()
@@ -222125,480 +222230,24 @@ async function safeText(resp) {
222125
222230
  }
222126
222231
  }
222127
222232
 
222128
- // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/sseTransportFactory.js
222233
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/streamableHttpTransportFactory.js
222129
222234
  init_cancellationScope();
222130
222235
 
222131
- // ../../node_modules/eventsource-parser/dist/index.js
222132
- var ParseError = class extends Error {
222133
- constructor(message, options) {
222134
- super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
222135
- }
222136
- };
222137
- var LF = 10;
222138
- var CR = 13;
222139
- var SPACE = 32;
222140
- function noop(_arg) {
222141
- }
222142
- function createParser(config2) {
222143
- if (typeof config2 == "function")
222144
- throw new TypeError(
222145
- "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
222146
- );
222147
- const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config2, pendingFragments = [];
222148
- let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
222149
- function feed(chunk) {
222150
- if (terminated)
222151
- throw new Error(
222152
- "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
222153
- );
222154
- if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
222155
- const trailing2 = processLines(chunk);
222156
- trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
222157
- return;
222158
- }
222159
- if (chunk.indexOf(`
222160
- `) === -1 && chunk.indexOf("\r") === -1) {
222161
- pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
222162
- return;
222163
- }
222164
- pendingFragments.push(chunk);
222165
- const input = pendingFragments.join("");
222166
- pendingFragments.length = 0, pendingFragmentsLength = 0;
222167
- const trailing = processLines(input);
222168
- trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
222169
- }
222170
- function checkBufferSize() {
222171
- maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
222172
- new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
222173
- type: "max-buffer-size-exceeded"
222174
- })
222175
- )));
222176
- }
222177
- function processLines(chunk) {
222178
- let searchIndex = 0;
222179
- if (chunk.indexOf("\r") === -1) {
222180
- let lfIndex = chunk.indexOf(`
222181
- `, searchIndex);
222182
- for (; lfIndex !== -1; ) {
222183
- if (searchIndex === lfIndex) {
222184
- dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
222185
- `, searchIndex);
222186
- continue;
222187
- }
222188
- const firstCharCode = chunk.charCodeAt(searchIndex);
222189
- if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
222190
- const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
222191
- if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
222192
- onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
222193
- `, searchIndex);
222194
- continue;
222195
- }
222196
- data = dataLines === 0 ? value : `${data}
222197
- ${value}`, dataLines++;
222198
- } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
222199
- chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
222200
- lfIndex
222201
- ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
222202
- searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
222203
- `, searchIndex);
222204
- }
222205
- return chunk.slice(searchIndex);
222206
- }
222207
- for (; searchIndex < chunk.length; ) {
222208
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
222209
- `, searchIndex);
222210
- let lineEnd = -1;
222211
- 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)
222212
- break;
222213
- parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
222214
- }
222215
- return chunk.slice(searchIndex);
222216
- }
222217
- function parseLine(chunk, start, end) {
222218
- if (start === end) {
222219
- dispatchEvent();
222220
- return;
222221
- }
222222
- const firstCharCode = chunk.charCodeAt(start);
222223
- if (isDataPrefix(chunk, start, firstCharCode)) {
222224
- const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
222225
- data = dataLines === 0 ? value2 : `${data}
222226
- ${value2}`, dataLines++;
222227
- return;
222228
- }
222229
- if (isEventPrefix(chunk, start, firstCharCode)) {
222230
- eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
222231
- return;
222232
- }
222233
- if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
222234
- const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
222235
- id = value2.includes("\0") ? void 0 : value2;
222236
- return;
222237
- }
222238
- if (firstCharCode === 58) {
222239
- if (onComment) {
222240
- const line2 = chunk.slice(start, end);
222241
- onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
222242
- }
222243
- return;
222244
- }
222245
- const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
222246
- if (fieldSeparatorIndex === -1) {
222247
- processField(line, "", line);
222248
- return;
222249
- }
222250
- const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
222251
- processField(field, value, line);
222252
- }
222253
- function processField(field, value, line) {
222254
- switch (field) {
222255
- case "event":
222256
- eventType = value || void 0;
222257
- break;
222258
- case "data":
222259
- data = dataLines === 0 ? value : `${data}
222260
- ${value}`, dataLines++;
222261
- break;
222262
- case "id":
222263
- id = value.includes("\0") ? void 0 : value;
222264
- break;
222265
- case "retry":
222266
- /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
222267
- new ParseError(`Invalid \`retry\` value: "${value}"`, {
222268
- type: "invalid-retry",
222269
- value,
222270
- line
222271
- })
222272
- );
222273
- break;
222274
- default:
222275
- onError(
222276
- new ParseError(
222277
- `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
222278
- { type: "unknown-field", field, value, line }
222279
- )
222280
- );
222281
- break;
222282
- }
222283
- }
222284
- function dispatchEvent() {
222285
- dataLines > 0 && onEvent({
222286
- id,
222287
- event: eventType,
222288
- data
222289
- }), id = void 0, data = "", dataLines = 0, eventType = void 0;
222290
- }
222291
- function reset(options = {}) {
222292
- if (options.consume && pendingFragments.length > 0) {
222293
- const incompleteLine = pendingFragments.join("");
222294
- parseLine(incompleteLine, 0, incompleteLine.length);
222295
- }
222296
- isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
222297
- }
222298
- return { feed, reset };
222299
- }
222300
- function isDataPrefix(chunk, i2, firstCharCode) {
222301
- return firstCharCode === 100 && chunk.charCodeAt(i2 + 1) === 97 && chunk.charCodeAt(i2 + 2) === 116 && chunk.charCodeAt(i2 + 3) === 97 && chunk.charCodeAt(i2 + 4) === 58;
222302
- }
222303
- function isEventPrefix(chunk, i2, firstCharCode) {
222304
- 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;
222305
- }
222306
-
222307
- // ../../node_modules/eventsource/dist/index.js
222308
- var ErrorEvent = class extends Event {
222309
- /**
222310
- * Constructs a new `ErrorEvent` instance. This is typically not called directly,
222311
- * but rather emitted by the `EventSource` object when an error occurs.
222312
- *
222313
- * @param type - The type of the event (should be "error")
222314
- * @param errorEventInitDict - Optional properties to include in the error event
222315
- */
222316
- constructor(type, errorEventInitDict) {
222317
- var _a8, _b2;
222318
- super(type), this.code = (_a8 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a8 : void 0, this.message = (_b2 = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b2 : void 0;
222319
- }
222320
- /**
222321
- * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
222322
- * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
222323
- * we explicitly include the properties in the `inspect` method.
222324
- *
222325
- * This is automatically called by Node.js when you `console.log` an instance of this class.
222326
- *
222327
- * @param _depth - The current depth
222328
- * @param options - The options passed to `util.inspect`
222329
- * @param inspect - The inspect function to use (prevents having to import it from `util`)
222330
- * @returns A string representation of the error
222331
- */
222332
- [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
222333
- return inspect(inspectableError(this), options);
222334
- }
222335
- /**
222336
- * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
222337
- * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
222338
- * we explicitly include the properties in the `inspect` method.
222339
- *
222340
- * This is automatically called by Deno when you `console.log` an instance of this class.
222341
- *
222342
- * @param inspect - The inspect function to use (prevents having to import it from `util`)
222343
- * @param options - The options passed to `Deno.inspect`
222344
- * @returns A string representation of the error
222345
- */
222346
- [Symbol.for("Deno.customInspect")](inspect, options) {
222347
- return inspect(inspectableError(this), options);
222236
+ // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
222237
+ var import_content_type = __toESM(require_content_type(), 1);
222238
+ function mediaTypeEssence(header) {
222239
+ if (!header) {
222240
+ return void 0;
222348
222241
  }
222349
- };
222350
- function syntaxError(message) {
222351
- const DomException = globalThis.DOMException;
222352
- return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
222353
- }
222354
- function flattenError2(err3) {
222355
- 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}`;
222356
- }
222357
- function inspectableError(err3) {
222358
- return {
222359
- type: err3.type,
222360
- message: err3.message,
222361
- code: err3.code,
222362
- defaultPrevented: err3.defaultPrevented,
222363
- cancelable: err3.cancelable,
222364
- timeStamp: err3.timeStamp
222365
- };
222366
- }
222367
- var __typeError = (msg) => {
222368
- throw TypeError(msg);
222369
- };
222370
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
222371
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
222372
- 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);
222373
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
222374
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
222375
- var _readyState;
222376
- var _url2;
222377
- var _redirectUrl;
222378
- var _withCredentials;
222379
- var _fetch;
222380
- var _reconnectInterval;
222381
- var _reconnectTimer;
222382
- var _lastEventId;
222383
- var _controller;
222384
- var _parser;
222385
- var _onError;
222386
- var _onMessage;
222387
- var _onOpen;
222388
- var _EventSource_instances;
222389
- var connect_fn;
222390
- var _onFetchResponse;
222391
- var _onFetchError;
222392
- var getRequestOptions_fn;
222393
- var _onEvent;
222394
- var _onRetryChange;
222395
- var failConnection_fn;
222396
- var scheduleReconnect_fn;
222397
- var _reconnect;
222398
- var EventSource = class extends EventTarget {
222399
- constructor(url2, eventSourceInitDict) {
222400
- var _a8, _b2;
222401
- 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) => {
222402
- var _a22;
222403
- __privateGet(this, _parser).reset();
222404
- const { body, redirected, status, headers } = response;
222405
- if (status === 204) {
222406
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
222407
- return;
222408
- }
222409
- if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
222410
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
222411
- return;
222412
- }
222413
- if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
222414
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
222415
- return;
222416
- }
222417
- if (__privateGet(this, _readyState) === this.CLOSED)
222418
- return;
222419
- __privateSet(this, _readyState, this.OPEN);
222420
- const openEvent = new Event("open");
222421
- if ((_a22 = __privateGet(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
222422
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
222423
- return;
222424
- }
222425
- const decoder = new TextDecoder(), reader = body.getReader();
222426
- let open4 = true;
222427
- do {
222428
- const { done, value } = await reader.read();
222429
- 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));
222430
- } while (open4);
222431
- }), __privateAdd(this, _onFetchError, (err3) => {
222432
- __privateSet(this, _controller, void 0), !(err3.name === "AbortError" || err3.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(err3));
222433
- }), __privateAdd(this, _onEvent, (event) => {
222434
- typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
222435
- const messageEvent = new MessageEvent(event.event || "message", {
222436
- data: event.data,
222437
- origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url2).origin,
222438
- lastEventId: event.id || ""
222439
- });
222440
- __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
222441
- }), __privateAdd(this, _onRetryChange, (value) => {
222442
- __privateSet(this, _reconnectInterval, value);
222443
- }), __privateAdd(this, _reconnect, () => {
222444
- __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
222445
- });
222446
- try {
222447
- if (url2 instanceof URL)
222448
- __privateSet(this, _url2, url2);
222449
- else if (typeof url2 == "string")
222450
- __privateSet(this, _url2, new URL(url2, getBaseURL()));
222451
- else
222452
- throw new Error("Invalid URL");
222453
- } catch {
222454
- throw syntaxError("An invalid or illegal string was specified");
222242
+ try {
222243
+ return import_content_type.default.parse(header).type;
222244
+ } catch {
222245
+ const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase();
222246
+ if (essence === "" || header.slice(essence.length).includes(",")) {
222247
+ return void 0;
222455
222248
  }
222456
- __privateSet(this, _parser, createParser({
222457
- onEvent: __privateGet(this, _onEvent),
222458
- onRetry: __privateGet(this, _onRetryChange)
222459
- })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a8 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a8 : globalThis.fetch), __privateSet(this, _withCredentials, (_b2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b2 : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
222460
- }
222461
- /**
222462
- * Returns the state of this EventSource object's connection. It can have the values described below.
222463
- *
222464
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
222465
- *
222466
- * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
222467
- * defined in the TypeScript `dom` library.
222468
- *
222469
- * @public
222470
- */
222471
- get readyState() {
222472
- return __privateGet(this, _readyState);
222473
- }
222474
- /**
222475
- * Returns the URL providing the event stream.
222476
- *
222477
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
222478
- *
222479
- * @public
222480
- */
222481
- get url() {
222482
- return __privateGet(this, _url2).href;
222483
- }
222484
- /**
222485
- * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
222486
- *
222487
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
222488
- */
222489
- get withCredentials() {
222490
- return __privateGet(this, _withCredentials);
222491
- }
222492
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
222493
- get onerror() {
222494
- return __privateGet(this, _onError);
222495
- }
222496
- set onerror(value) {
222497
- __privateSet(this, _onError, value);
222249
+ return essence;
222498
222250
  }
222499
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
222500
- get onmessage() {
222501
- return __privateGet(this, _onMessage);
222502
- }
222503
- set onmessage(value) {
222504
- __privateSet(this, _onMessage, value);
222505
- }
222506
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
222507
- get onopen() {
222508
- return __privateGet(this, _onOpen);
222509
- }
222510
- set onopen(value) {
222511
- __privateSet(this, _onOpen, value);
222512
- }
222513
- addEventListener(type, listener, options) {
222514
- const listen = listener;
222515
- super.addEventListener(type, listen, options);
222516
- }
222517
- removeEventListener(type, listener, options) {
222518
- const listen = listener;
222519
- super.removeEventListener(type, listen, options);
222520
- }
222521
- /**
222522
- * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
222523
- *
222524
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
222525
- *
222526
- * @public
222527
- */
222528
- close() {
222529
- __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));
222530
- }
222531
- };
222532
- _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(), /**
222533
- * Connect to the given URL and start receiving events
222534
- *
222535
- * @internal
222536
- */
222537
- connect_fn = function() {
222538
- __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));
222539
- }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
222540
- * Get request options for the `fetch()` request
222541
- *
222542
- * @returns The request options
222543
- * @internal
222544
- */
222545
- getRequestOptions_fn = function() {
222546
- var _a8;
222547
- const init = {
222548
- // [spec] Let `corsAttributeState` be `Anonymous`…
222549
- // [spec] …will have their mode set to "cors"…
222550
- mode: "cors",
222551
- redirect: "follow",
222552
- headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
222553
- cache: "no-store",
222554
- signal: (_a8 = __privateGet(this, _controller)) == null ? void 0 : _a8.signal
222555
- };
222556
- return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
222557
- }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
222558
- * Handles the process referred to in the EventSource specification as "failing a connection".
222559
- *
222560
- * @param error - The error causing the connection to fail
222561
- * @param code - The HTTP status code, if available
222562
- * @internal
222563
- */
222564
- failConnection_fn = function(message, code) {
222565
- var _a8;
222566
- __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
222567
- const errorEvent = new ErrorEvent("error", { code, message });
222568
- (_a8 = __privateGet(this, _onError)) == null || _a8.call(this, errorEvent), this.dispatchEvent(errorEvent);
222569
- }, /**
222570
- * Schedules a reconnection attempt against the EventSource endpoint.
222571
- *
222572
- * @param message - The error causing the connection to fail
222573
- * @param code - The HTTP status code, if available
222574
- * @internal
222575
- */
222576
- scheduleReconnect_fn = function(message, code) {
222577
- var _a8;
222578
- if (__privateGet(this, _readyState) === this.CLOSED)
222579
- return;
222580
- __privateSet(this, _readyState, this.CONNECTING);
222581
- const errorEvent = new ErrorEvent("error", { code, message });
222582
- (_a8 = __privateGet(this, _onError)) == null || _a8.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
222583
- }, _reconnect = /* @__PURE__ */ new WeakMap(), /**
222584
- * ReadyState representing an EventSource currently trying to connect
222585
- *
222586
- * @public
222587
- */
222588
- EventSource.CONNECTING = 0, /**
222589
- * ReadyState representing an EventSource connection that is open (eg connected)
222590
- *
222591
- * @public
222592
- */
222593
- EventSource.OPEN = 1, /**
222594
- * ReadyState representing an EventSource connection that is closed (eg disconnected)
222595
- *
222596
- * @public
222597
- */
222598
- EventSource.CLOSED = 2;
222599
- function getBaseURL() {
222600
- const doc = "document" in globalThis ? globalThis.document : void 0;
222601
- return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
222602
222251
  }
222603
222252
 
222604
222253
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
@@ -223472,24 +223121,232 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
223472
223121
  return OAuthClientInformationFullSchema.parse(await response.json());
223473
223122
  }
223474
223123
 
223475
- // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
223476
- var SseError = class extends Error {
223477
- constructor(code, message, event) {
223478
- super(`SSE error: ${message}`);
223124
+ // ../../node_modules/eventsource-parser/dist/index.js
223125
+ var ParseError = class extends Error {
223126
+ constructor(message, options) {
223127
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
223128
+ }
223129
+ };
223130
+ var LF = 10;
223131
+ var CR = 13;
223132
+ var SPACE = 32;
223133
+ function noop(_arg) {
223134
+ }
223135
+ function createParser(config2) {
223136
+ if (typeof config2 == "function")
223137
+ throw new TypeError(
223138
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
223139
+ );
223140
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config2, pendingFragments = [];
223141
+ let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
223142
+ function feed(chunk) {
223143
+ if (terminated)
223144
+ throw new Error(
223145
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
223146
+ );
223147
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
223148
+ const trailing2 = processLines(chunk);
223149
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
223150
+ return;
223151
+ }
223152
+ if (chunk.indexOf(`
223153
+ `) === -1 && chunk.indexOf("\r") === -1) {
223154
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
223155
+ return;
223156
+ }
223157
+ pendingFragments.push(chunk);
223158
+ const input = pendingFragments.join("");
223159
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
223160
+ const trailing = processLines(input);
223161
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
223162
+ }
223163
+ function checkBufferSize() {
223164
+ maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
223165
+ new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
223166
+ type: "max-buffer-size-exceeded"
223167
+ })
223168
+ )));
223169
+ }
223170
+ function processLines(chunk) {
223171
+ let searchIndex = 0;
223172
+ if (chunk.indexOf("\r") === -1) {
223173
+ let lfIndex = chunk.indexOf(`
223174
+ `, searchIndex);
223175
+ for (; lfIndex !== -1; ) {
223176
+ if (searchIndex === lfIndex) {
223177
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
223178
+ `, searchIndex);
223179
+ continue;
223180
+ }
223181
+ const firstCharCode = chunk.charCodeAt(searchIndex);
223182
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
223183
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
223184
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
223185
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
223186
+ `, searchIndex);
223187
+ continue;
223188
+ }
223189
+ data = dataLines === 0 ? value : `${data}
223190
+ ${value}`, dataLines++;
223191
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
223192
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
223193
+ lfIndex
223194
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
223195
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
223196
+ `, searchIndex);
223197
+ }
223198
+ return chunk.slice(searchIndex);
223199
+ }
223200
+ for (; searchIndex < chunk.length; ) {
223201
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
223202
+ `, searchIndex);
223203
+ let lineEnd = -1;
223204
+ 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)
223205
+ break;
223206
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
223207
+ }
223208
+ return chunk.slice(searchIndex);
223209
+ }
223210
+ function parseLine(chunk, start, end) {
223211
+ if (start === end) {
223212
+ dispatchEvent();
223213
+ return;
223214
+ }
223215
+ const firstCharCode = chunk.charCodeAt(start);
223216
+ if (isDataPrefix(chunk, start, firstCharCode)) {
223217
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
223218
+ data = dataLines === 0 ? value2 : `${data}
223219
+ ${value2}`, dataLines++;
223220
+ return;
223221
+ }
223222
+ if (isEventPrefix(chunk, start, firstCharCode)) {
223223
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
223224
+ return;
223225
+ }
223226
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
223227
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
223228
+ id = value2.includes("\0") ? void 0 : value2;
223229
+ return;
223230
+ }
223231
+ if (firstCharCode === 58) {
223232
+ if (onComment) {
223233
+ const line2 = chunk.slice(start, end);
223234
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
223235
+ }
223236
+ return;
223237
+ }
223238
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
223239
+ if (fieldSeparatorIndex === -1) {
223240
+ processField(line, "", line);
223241
+ return;
223242
+ }
223243
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
223244
+ processField(field, value, line);
223245
+ }
223246
+ function processField(field, value, line) {
223247
+ switch (field) {
223248
+ case "event":
223249
+ eventType = value || void 0;
223250
+ break;
223251
+ case "data":
223252
+ data = dataLines === 0 ? value : `${data}
223253
+ ${value}`, dataLines++;
223254
+ break;
223255
+ case "id":
223256
+ id = value.includes("\0") ? void 0 : value;
223257
+ break;
223258
+ case "retry":
223259
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
223260
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
223261
+ type: "invalid-retry",
223262
+ value,
223263
+ line
223264
+ })
223265
+ );
223266
+ break;
223267
+ default:
223268
+ onError(
223269
+ new ParseError(
223270
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
223271
+ { type: "unknown-field", field, value, line }
223272
+ )
223273
+ );
223274
+ break;
223275
+ }
223276
+ }
223277
+ function dispatchEvent() {
223278
+ dataLines > 0 && onEvent({
223279
+ id,
223280
+ event: eventType,
223281
+ data
223282
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
223283
+ }
223284
+ function reset(options = {}) {
223285
+ if (options.consume && pendingFragments.length > 0) {
223286
+ const incompleteLine = pendingFragments.join("");
223287
+ parseLine(incompleteLine, 0, incompleteLine.length);
223288
+ }
223289
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
223290
+ }
223291
+ return { feed, reset };
223292
+ }
223293
+ function isDataPrefix(chunk, i2, firstCharCode) {
223294
+ return firstCharCode === 100 && chunk.charCodeAt(i2 + 1) === 97 && chunk.charCodeAt(i2 + 2) === 116 && chunk.charCodeAt(i2 + 3) === 97 && chunk.charCodeAt(i2 + 4) === 58;
223295
+ }
223296
+ function isEventPrefix(chunk, i2, firstCharCode) {
223297
+ 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;
223298
+ }
223299
+
223300
+ // ../../node_modules/eventsource-parser/dist/stream.js
223301
+ var EventSourceParserStream = class extends TransformStream {
223302
+ constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
223303
+ let parser;
223304
+ super({
223305
+ start(controller) {
223306
+ parser = createParser({
223307
+ onEvent: (event) => {
223308
+ controller.enqueue(event);
223309
+ },
223310
+ onError(error51) {
223311
+ typeof onError == "function" && onError(error51), (onError === "terminate" || error51.type === "max-buffer-size-exceeded") && controller.error(error51);
223312
+ },
223313
+ onRetry,
223314
+ onComment,
223315
+ maxBufferSize
223316
+ });
223317
+ },
223318
+ transform(chunk) {
223319
+ parser.feed(chunk);
223320
+ }
223321
+ });
223322
+ }
223323
+ };
223324
+
223325
+ // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
223326
+ var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
223327
+ initialReconnectionDelay: 1e3,
223328
+ maxReconnectionDelay: 3e4,
223329
+ reconnectionDelayGrowFactor: 1.5,
223330
+ maxRetries: 2
223331
+ };
223332
+ var StreamableHTTPError = class extends Error {
223333
+ constructor(code, message) {
223334
+ super(`Streamable HTTP error: ${message}`);
223479
223335
  this.code = code;
223480
- this.event = event;
223481
223336
  }
223482
223337
  };
223483
- var SSEClientTransport = class {
223338
+ var StreamableHTTPClientTransport = class {
223484
223339
  constructor(url2, opts) {
223340
+ this._hasCompletedAuthFlow = false;
223485
223341
  this._url = url2;
223486
223342
  this._resourceMetadataUrl = void 0;
223487
223343
  this._scope = void 0;
223488
- this._eventSourceInit = opts?.eventSourceInit;
223489
223344
  this._requestInit = opts?.requestInit;
223490
223345
  this._authProvider = opts?.authProvider;
223491
223346
  this._fetch = opts?.fetch;
223492
223347
  this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
223348
+ this._sessionId = opts?.sessionId;
223349
+ this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
223493
223350
  }
223494
223351
  async _authThenStart() {
223495
223352
  if (!this._authProvider) {
@@ -223510,7 +223367,7 @@ var SSEClientTransport = class {
223510
223367
  if (result !== "AUTHORIZED") {
223511
223368
  throw new UnauthorizedError();
223512
223369
  }
223513
- return await this._startOrAuth();
223370
+ return await this._startOrAuthSse({ resumptionToken: void 0 });
223514
223371
  }
223515
223372
  async _commonHeaders() {
223516
223373
  const headers = {};
@@ -223520,6 +223377,9 @@ var SSEClientTransport = class {
223520
223377
  headers["Authorization"] = `Bearer ${tokens.access_token}`;
223521
223378
  }
223522
223379
  }
223380
+ if (this._sessionId) {
223381
+ headers["mcp-session-id"] = this._sessionId;
223382
+ }
223523
223383
  if (this._protocolVersion) {
223524
223384
  headers["mcp-protocol-version"] = this._protocolVersion;
223525
223385
  }
@@ -223529,71 +223389,146 @@ var SSEClientTransport = class {
223529
223389
  ...extraHeaders
223530
223390
  });
223531
223391
  }
223532
- _startOrAuth() {
223533
- const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
223534
- return new Promise((resolve, reject) => {
223535
- this._eventSource = new EventSource(this._url.href, {
223536
- ...this._eventSourceInit,
223537
- fetch: async (url2, init) => {
223538
- const headers = await this._commonHeaders();
223539
- headers.set("Accept", "text/event-stream");
223540
- const response = await fetchImpl(url2, {
223541
- ...init,
223542
- headers
223543
- });
223544
- if (response.status === 401 && response.headers.has("www-authenticate")) {
223545
- const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
223546
- this._resourceMetadataUrl = resourceMetadataUrl;
223547
- this._scope = scope;
223548
- }
223549
- return response;
223550
- }
223392
+ async _startOrAuthSse(options) {
223393
+ const { resumptionToken } = options;
223394
+ try {
223395
+ const headers = await this._commonHeaders();
223396
+ headers.set("Accept", "text/event-stream");
223397
+ if (resumptionToken) {
223398
+ headers.set("last-event-id", resumptionToken);
223399
+ }
223400
+ const response = await (this._fetch ?? fetch)(this._url, {
223401
+ method: "GET",
223402
+ headers,
223403
+ signal: this._abortController?.signal
223551
223404
  });
223552
- this._abortController = new AbortController();
223553
- this._eventSource.onerror = (event) => {
223554
- if (event.code === 401 && this._authProvider) {
223555
- this._authThenStart().then(resolve, reject);
223556
- return;
223405
+ if (!response.ok) {
223406
+ await response.body?.cancel();
223407
+ if (response.status === 401 && this._authProvider) {
223408
+ return await this._authThenStart();
223557
223409
  }
223558
- const error51 = new SseError(event.code, event.message, event);
223559
- reject(error51);
223560
- this.onerror?.(error51);
223561
- };
223562
- this._eventSource.onopen = () => {
223563
- };
223564
- this._eventSource.addEventListener("endpoint", (event) => {
223565
- const messageEvent = event;
223566
- try {
223567
- this._endpoint = new URL(messageEvent.data, this._url);
223568
- if (this._endpoint.origin !== this._url.origin) {
223569
- throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
223570
- }
223571
- } catch (error51) {
223572
- reject(error51);
223573
- this.onerror?.(error51);
223574
- void this.close();
223410
+ if (response.status === 405) {
223575
223411
  return;
223576
223412
  }
223577
- resolve();
223413
+ throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
223414
+ }
223415
+ this._handleSseStream(response.body, options, true);
223416
+ } catch (error51) {
223417
+ this.onerror?.(error51);
223418
+ throw error51;
223419
+ }
223420
+ }
223421
+ /**
223422
+ * Calculates the next reconnection delay using backoff algorithm
223423
+ *
223424
+ * @param attempt Current reconnection attempt count for the specific stream
223425
+ * @returns Time to wait in milliseconds before next reconnection attempt
223426
+ */
223427
+ _getNextReconnectionDelay(attempt) {
223428
+ if (this._serverRetryMs !== void 0) {
223429
+ return this._serverRetryMs;
223430
+ }
223431
+ const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
223432
+ const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
223433
+ const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
223434
+ return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
223435
+ }
223436
+ /**
223437
+ * Schedule a reconnection attempt using server-provided retry interval or backoff
223438
+ *
223439
+ * @param lastEventId The ID of the last received event for resumability
223440
+ * @param attemptCount Current reconnection attempt count for this specific stream
223441
+ */
223442
+ _scheduleReconnection(options, attemptCount = 0) {
223443
+ const maxRetries = this._reconnectionOptions.maxRetries;
223444
+ if (attemptCount >= maxRetries) {
223445
+ this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
223446
+ return;
223447
+ }
223448
+ const delay3 = this._getNextReconnectionDelay(attemptCount);
223449
+ this._reconnectionTimeout = setTimeout(() => {
223450
+ this._startOrAuthSse(options).catch((error51) => {
223451
+ this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error51 instanceof Error ? error51.message : String(error51)}`));
223452
+ this._scheduleReconnection(options, attemptCount + 1);
223578
223453
  });
223579
- this._eventSource.onmessage = (event) => {
223580
- const messageEvent = event;
223581
- let message;
223582
- try {
223583
- message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
223584
- } catch (error51) {
223585
- this.onerror?.(error51);
223586
- return;
223454
+ }, delay3);
223455
+ }
223456
+ _handleSseStream(stream11, options, isReconnectable) {
223457
+ if (!stream11) {
223458
+ return;
223459
+ }
223460
+ const { onresumptiontoken, replayMessageId } = options;
223461
+ let lastEventId;
223462
+ let hasPrimingEvent = false;
223463
+ let receivedResponse = false;
223464
+ const processStream2 = async () => {
223465
+ try {
223466
+ const reader = stream11.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
223467
+ onRetry: (retryMs) => {
223468
+ this._serverRetryMs = retryMs;
223469
+ }
223470
+ })).getReader();
223471
+ while (true) {
223472
+ const { value: event, done } = await reader.read();
223473
+ if (done) {
223474
+ break;
223475
+ }
223476
+ if (event.id) {
223477
+ lastEventId = event.id;
223478
+ hasPrimingEvent = true;
223479
+ onresumptiontoken?.(event.id);
223480
+ }
223481
+ if (!event.data) {
223482
+ continue;
223483
+ }
223484
+ if (!event.event || event.event === "message") {
223485
+ try {
223486
+ const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
223487
+ if (isJSONRPCResultResponse(message)) {
223488
+ receivedResponse = true;
223489
+ if (replayMessageId !== void 0) {
223490
+ message.id = replayMessageId;
223491
+ }
223492
+ }
223493
+ this.onmessage?.(message);
223494
+ } catch (error51) {
223495
+ this.onerror?.(error51);
223496
+ }
223497
+ }
223587
223498
  }
223588
- this.onmessage?.(message);
223589
- };
223590
- });
223499
+ const canResume = isReconnectable || hasPrimingEvent;
223500
+ const needsReconnect = canResume && !receivedResponse;
223501
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
223502
+ this._scheduleReconnection({
223503
+ resumptionToken: lastEventId,
223504
+ onresumptiontoken,
223505
+ replayMessageId
223506
+ }, 0);
223507
+ }
223508
+ } catch (error51) {
223509
+ this.onerror?.(new Error(`SSE stream disconnected: ${error51}`));
223510
+ const canResume = isReconnectable || hasPrimingEvent;
223511
+ const needsReconnect = canResume && !receivedResponse;
223512
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
223513
+ try {
223514
+ this._scheduleReconnection({
223515
+ resumptionToken: lastEventId,
223516
+ onresumptiontoken,
223517
+ replayMessageId
223518
+ }, 0);
223519
+ } catch (error52) {
223520
+ this.onerror?.(new Error(`Failed to reconnect: ${error52 instanceof Error ? error52.message : String(error52)}`));
223521
+ }
223522
+ }
223523
+ }
223524
+ };
223525
+ processStream2();
223591
223526
  }
223592
223527
  async start() {
223593
- if (this._eventSource) {
223594
- throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
223528
+ if (this._abortController) {
223529
+ throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
223595
223530
  }
223596
- return await this._startOrAuth();
223531
+ this._abortController = new AbortController();
223597
223532
  }
223598
223533
  /**
223599
223534
  * 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.
@@ -223614,17 +223549,23 @@ var SSEClientTransport = class {
223614
223549
  }
223615
223550
  }
223616
223551
  async close() {
223552
+ if (this._reconnectionTimeout) {
223553
+ clearTimeout(this._reconnectionTimeout);
223554
+ this._reconnectionTimeout = void 0;
223555
+ }
223617
223556
  this._abortController?.abort();
223618
- this._eventSource?.close();
223619
223557
  this.onclose?.();
223620
223558
  }
223621
- async send(message) {
223622
- if (!this._endpoint) {
223623
- throw new Error("Not connected");
223624
- }
223559
+ async send(message, options) {
223625
223560
  try {
223561
+ const { resumptionToken, onresumptiontoken } = options || {};
223562
+ if (resumptionToken) {
223563
+ this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err3) => this.onerror?.(err3));
223564
+ return;
223565
+ }
223626
223566
  const headers = await this._commonHeaders();
223627
223567
  headers.set("content-type", "application/json");
223568
+ headers.set("accept", "application/json, text/event-stream");
223628
223569
  const init = {
223629
223570
  ...this._requestInit,
223630
223571
  method: "POST",
@@ -223632,10 +223573,17 @@ var SSEClientTransport = class {
223632
223573
  body: JSON.stringify(message),
223633
223574
  signal: this._abortController?.signal
223634
223575
  };
223635
- const response = await (this._fetch ?? fetch)(this._endpoint, init);
223576
+ const response = await (this._fetch ?? fetch)(this._url, init);
223577
+ const sessionId = response.headers.get("mcp-session-id");
223578
+ if (sessionId) {
223579
+ this._sessionId = sessionId;
223580
+ }
223636
223581
  if (!response.ok) {
223637
223582
  const text2 = await response.text().catch(() => null);
223638
223583
  if (response.status === 401 && this._authProvider) {
223584
+ if (this._hasCompletedAuthFlow) {
223585
+ throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
223586
+ }
223639
223587
  const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
223640
223588
  this._resourceMetadataUrl = resourceMetadataUrl;
223641
223589
  this._scope = scope;
@@ -223648,11 +223596,103 @@ var SSEClientTransport = class {
223648
223596
  if (result !== "AUTHORIZED") {
223649
223597
  throw new UnauthorizedError();
223650
223598
  }
223599
+ this._hasCompletedAuthFlow = true;
223651
223600
  return this.send(message);
223652
223601
  }
223653
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text2}`);
223602
+ if (response.status === 403 && this._authProvider) {
223603
+ const { resourceMetadataUrl, scope, error: error51 } = extractWWWAuthenticateParams(response);
223604
+ if (error51 === "insufficient_scope") {
223605
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
223606
+ if (this._lastUpscopingHeader === wwwAuthHeader) {
223607
+ throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
223608
+ }
223609
+ if (scope) {
223610
+ this._scope = scope;
223611
+ }
223612
+ if (resourceMetadataUrl) {
223613
+ this._resourceMetadataUrl = resourceMetadataUrl;
223614
+ }
223615
+ this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
223616
+ const result = await auth(this._authProvider, {
223617
+ serverUrl: this._url,
223618
+ resourceMetadataUrl: this._resourceMetadataUrl,
223619
+ scope: this._scope,
223620
+ fetchFn: this._fetch
223621
+ });
223622
+ if (result !== "AUTHORIZED") {
223623
+ throw new UnauthorizedError();
223624
+ }
223625
+ return this.send(message);
223626
+ }
223627
+ }
223628
+ throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text2}`);
223629
+ }
223630
+ this._hasCompletedAuthFlow = false;
223631
+ this._lastUpscopingHeader = void 0;
223632
+ if (response.status === 202) {
223633
+ await response.body?.cancel();
223634
+ if (isInitializedNotification(message)) {
223635
+ this._startOrAuthSse({ resumptionToken: void 0 }).catch((err3) => this.onerror?.(err3));
223636
+ }
223637
+ return;
223638
+ }
223639
+ const messages = Array.isArray(message) ? message : [message];
223640
+ const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
223641
+ const contentType2 = response.headers.get("content-type");
223642
+ const responseMediaType = mediaTypeEssence(contentType2);
223643
+ if (hasRequests) {
223644
+ if (responseMediaType === "text/event-stream") {
223645
+ this._handleSseStream(response.body, { onresumptiontoken }, false);
223646
+ } else if (responseMediaType === "application/json") {
223647
+ const data = await response.json();
223648
+ const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
223649
+ for (const msg of responseMessages) {
223650
+ this.onmessage?.(msg);
223651
+ }
223652
+ } else {
223653
+ await response.body?.cancel();
223654
+ throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType2}`);
223655
+ }
223656
+ } else {
223657
+ await response.body?.cancel();
223654
223658
  }
223659
+ } catch (error51) {
223660
+ this.onerror?.(error51);
223661
+ throw error51;
223662
+ }
223663
+ }
223664
+ get sessionId() {
223665
+ return this._sessionId;
223666
+ }
223667
+ /**
223668
+ * Terminates the current session by sending a DELETE request to the server.
223669
+ *
223670
+ * Clients that no longer need a particular session
223671
+ * (e.g., because the user is leaving the client application) SHOULD send an
223672
+ * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
223673
+ * terminate the session.
223674
+ *
223675
+ * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
223676
+ * the server does not allow clients to terminate sessions.
223677
+ */
223678
+ async terminateSession() {
223679
+ if (!this._sessionId) {
223680
+ return;
223681
+ }
223682
+ try {
223683
+ const headers = await this._commonHeaders();
223684
+ const init = {
223685
+ ...this._requestInit,
223686
+ method: "DELETE",
223687
+ headers,
223688
+ signal: this._abortController?.signal
223689
+ };
223690
+ const response = await (this._fetch ?? fetch)(this._url, init);
223655
223691
  await response.body?.cancel();
223692
+ if (!response.ok && response.status !== 405) {
223693
+ throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
223694
+ }
223695
+ this._sessionId = void 0;
223656
223696
  } catch (error51) {
223657
223697
  this.onerror?.(error51);
223658
223698
  throw error51;
@@ -223661,6 +223701,22 @@ var SSEClientTransport = class {
223661
223701
  setProtocolVersion(version2) {
223662
223702
  this._protocolVersion = version2;
223663
223703
  }
223704
+ get protocolVersion() {
223705
+ return this._protocolVersion;
223706
+ }
223707
+ /**
223708
+ * Resume an SSE stream from a previous event ID.
223709
+ * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
223710
+ *
223711
+ * @param lastEventId The event ID to resume from
223712
+ * @param options Optional callback to receive new resumption tokens
223713
+ */
223714
+ async resumeStream(lastEventId, options) {
223715
+ await this._startOrAuthSse({
223716
+ resumptionToken: lastEventId,
223717
+ onresumptiontoken: options?.onresumptiontoken
223718
+ });
223719
+ }
223664
223720
  };
223665
223721
 
223666
223722
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/signingFetch.js
@@ -223784,7 +223840,7 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
223784
223840
  };
223785
223841
  }
223786
223842
 
223787
- // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/sseTransportFactory.js
223843
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/streamableHttpTransportFactory.js
223788
223844
  function withTimeout(fetch3, timeoutMs) {
223789
223845
  return async (url2, init) => {
223790
223846
  if (init?.signal) {
@@ -223798,14 +223854,12 @@ function withTimeout(fetch3, timeoutMs) {
223798
223854
  }
223799
223855
  };
223800
223856
  }
223801
- function createSseTransport(config2, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
223857
+ function createStreamableHttpTransport(config2, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
223802
223858
  const url2 = new URL(config2.sseEndpoint, config2.remoteBaseUrl);
223803
223859
  const timeoutMs = config2.requestTimeoutMs ?? 18e4;
223804
223860
  const signingFetch = withTimeout(createSigningFetch(signer, void 0, onTraceId, debugLog, getCallHeaders, invocationContext), timeoutMs);
223805
- return new SSEClientTransport(url2, {
223806
- // SSE 建连(EventSource)的 GET fetch:SDK 先包默认头再调这里。
223807
- eventSourceInit: { fetch: signingFetch },
223808
- // MCP 发消息用的 POST fetch。
223861
+ return new StreamableHTTPClientTransport(url2, {
223862
+ // SDK 的所有 HTTP 请求统一经签名器,保留会话与协议协商请求头。
223809
223863
  fetch: signingFetch
223810
223864
  });
223811
223865
  }
@@ -224070,7 +224124,7 @@ var RemoteGatewayMcpServerProvider = class {
224070
224124
  const verifier = this.doCreateTokenVerifier(config2);
224071
224125
  const callHeaders = new import_node_async_hooks2.AsyncLocalStorage();
224072
224126
  const { client } = await connectMcpClientWithRetry(config2, {
224073
- createTransport: () => createSseTransport(config2, this.doCreateSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
224127
+ createTransport: () => createStreamableHttpTransport(config2, this.doCreateSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
224074
224128
  createClient: () => this.doCrateClient(),
224075
224129
  runConnect: (operation, attempt) => this.invocationContext.run(timeoutMs, connectSignal, operation, {
224076
224130
  observation,
@@ -226091,6 +226145,24 @@ function sanitizeAttributeValue(value) {
226091
226145
  }
226092
226146
 
226093
226147
  // ../linkque-agent-runtime/dist/esm/impl/telemetry/otelRuntimeTelemetry.js
226148
+ var InitialRootTraceIdGenerator = class {
226149
+ initialRootTraceId;
226150
+ fallback = new import_sdk_trace_base.RandomIdGenerator();
226151
+ constructor(initialRootTraceId) {
226152
+ this.initialRootTraceId = initialRootTraceId;
226153
+ }
226154
+ generateTraceId() {
226155
+ if (this.initialRootTraceId) {
226156
+ const traceId = this.initialRootTraceId;
226157
+ this.initialRootTraceId = void 0;
226158
+ return traceId;
226159
+ }
226160
+ return this.fallback.generateTraceId();
226161
+ }
226162
+ generateSpanId() {
226163
+ return this.fallback.generateSpanId();
226164
+ }
226165
+ };
226094
226166
  var OtelRuntimeTelemetry = class {
226095
226167
  options;
226096
226168
  queue;
@@ -226110,9 +226182,10 @@ var OtelRuntimeTelemetry = class {
226110
226182
  this.options = options;
226111
226183
  this.queue = new IdentityQueue(options);
226112
226184
  const ratio = options.sampleRatio ?? 1;
226185
+ const initialRootTraceId = options.initialRootTraceId?.toLowerCase();
226113
226186
  this.maxActive = options.maxActiveOperations ?? 4096;
226114
226187
  this.maxAge = options.operationMaxAgeMs ?? 24 * 60 * 60 * 1e3;
226115
- 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)
226188
+ 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))
226116
226189
  throw new Error("\u975E\u6CD5\u9065\u6D4B\u5B9E\u4F8B\u914D\u7F6E");
226117
226190
  const resource = (0, import_resources.resourceFromAttributes)({
226118
226191
  [ETelemetryAttribute.SERVICE_NAME]: options.serviceName,
@@ -226123,6 +226196,7 @@ var OtelRuntimeTelemetry = class {
226123
226196
  });
226124
226197
  this.tracerProvider = new import_sdk_trace_base.BasicTracerProvider({
226125
226198
  resource,
226199
+ idGenerator: new InitialRootTraceIdGenerator(initialRootTraceId),
226126
226200
  sampler: new import_sdk_trace_base.ParentBasedSampler({
226127
226201
  root: new import_sdk_trace_base.TraceIdRatioBasedSampler(ratio)
226128
226202
  }),
@@ -226818,7 +226892,7 @@ var import_http219 = require("http");
226818
226892
  var import_promises7 = require("fs/promises");
226819
226893
  var import_os = require("os");
226820
226894
  var import_path59 = __toESM(require("path"));
226821
- var import_stream2 = require("stream");
226895
+ var import_stream3 = require("stream");
226822
226896
 
226823
226897
  // src/commands/agentdev/sandboxIntegrate/protocolReader.ts
226824
226898
  var import_promises4 = require("fs/promises");
@@ -227067,7 +227141,7 @@ function createMcpConfigResolver(options) {
227067
227141
  remoteBaseUrl,
227068
227142
  // 兼容存量配置误用 mcpName(协议字段为 serverName);两者都没有时落到 undefined,
227069
227143
  // 上游 sseEndpoint 会显式带 undefined 便于诊断。
227070
- sseEndpoint: `api/v1/open/mcps/${resolveServerName(resource.config)}/sse`,
227144
+ sseEndpoint: `api/v1/open/mcps/${resolveServerName(resource.config)}/mcp`,
227071
227145
  agentId: options.agentId,
227072
227146
  ...options.signEndpoint ? { signEndpoint: options.signEndpoint } : {},
227073
227147
  ...options.verifyTokenEndpoint ? { verifyTokenEndpoint: options.verifyTokenEndpoint } : {},
@@ -227087,7 +227161,7 @@ var LOG_MAX_BYTES = 1024 * 1024;
227087
227161
  var LOG_ROTATIONS = 3;
227088
227162
  var SHUTDOWN_GRACE_MS = 2500;
227089
227163
  var HOME_DATA_TRUSTED_CONTEXT_FIELD = "_trustedContext_";
227090
- var RotatingLogWriter = class extends import_stream2.Writable {
227164
+ var RotatingLogWriter = class extends import_stream3.Writable {
227091
227165
  constructor(logPath) {
227092
227166
  super();
227093
227167
  this.logPath = logPath;