linkque-cli-v2 1.6.9 → 1.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (17) hide show
  1. package/linkquejs.js +110 -3
  2. package/package.json +1 -1
  3. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-BJXGRRWL.js → chunk-P7NPWFEB.js} +1 -1
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-DNTEEBEH.js → chunk-SICWMO5Y.js} +1 -0
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-NJKO34ZC.js → chunk-UPH5CD2J.js} +632 -558
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-HGKCCOSQ.js → chunk-YODH5M5T.js} +26 -1
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-bsd-JGCLGHFY.js → getMachineId-bsd-NYGVHXGN.js} +1 -1
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-darwin-COHLFNXH.js → getMachineId-darwin-OPTJOAYC.js} +1 -1
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-linux-XV3Z5FQG.js → getMachineId-linux-5SQRYTUJ.js} +1 -1
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-unsupported-FCRKLIZL.js → getMachineId-unsupported-OJE7WPEH.js} +1 -1
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-win-A4WRNVV6.js → getMachineId-win-SLTTCNXU.js} +1 -1
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-OEOTQWE5.js → mistral-conversations-C43A6QIS.js} +1 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{otel-WGS5CC2J.js → otel-RUUFBBFE.js} +1 -1
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +26 -13
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +3 -3
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +3 -3
  17. package/worker.js +739 -666
@@ -388,8 +388,9 @@ import {
388
388
  esm_exports,
389
389
  init_esm,
390
390
  isSpanContextValid,
391
+ isValidTraceId,
391
392
  trace
392
- } from "./chunk-DNTEEBEH.js";
393
+ } from "./chunk-SICWMO5Y.js";
393
394
  import {
394
395
  __commonJS,
395
396
  __esm,
@@ -9130,6 +9131,110 @@ var require_dist = __commonJS({
9130
9131
  }
9131
9132
  });
9132
9133
 
9134
+ // ../../node_modules/content-type/index.js
9135
+ var require_content_type = __commonJS({
9136
+ "../../node_modules/content-type/index.js"(exports) {
9137
+ "use strict";
9138
+ var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
9139
+ var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/;
9140
+ var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
9141
+ var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
9142
+ var QUOTE_REGEXP = /([\\"])/g;
9143
+ var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
9144
+ exports.format = format;
9145
+ exports.parse = parse2;
9146
+ function format(obj) {
9147
+ if (!obj || typeof obj !== "object") {
9148
+ throw new TypeError("argument obj is required");
9149
+ }
9150
+ var parameters = obj.parameters;
9151
+ var type = obj.type;
9152
+ if (!type || !TYPE_REGEXP.test(type)) {
9153
+ throw new TypeError("invalid type");
9154
+ }
9155
+ var string2 = type;
9156
+ if (parameters && typeof parameters === "object") {
9157
+ var param;
9158
+ var params = Object.keys(parameters).sort();
9159
+ for (var i = 0; i < params.length; i++) {
9160
+ param = params[i];
9161
+ if (!TOKEN_REGEXP.test(param)) {
9162
+ throw new TypeError("invalid parameter name");
9163
+ }
9164
+ string2 += "; " + param + "=" + qstring(parameters[param]);
9165
+ }
9166
+ }
9167
+ return string2;
9168
+ }
9169
+ function parse2(string2) {
9170
+ if (!string2) {
9171
+ throw new TypeError("argument string is required");
9172
+ }
9173
+ var header = typeof string2 === "object" ? getcontenttype(string2) : string2;
9174
+ if (typeof header !== "string") {
9175
+ throw new TypeError("argument string is required to be a string");
9176
+ }
9177
+ var index = header.indexOf(";");
9178
+ var type = index !== -1 ? header.slice(0, index).trim() : header.trim();
9179
+ if (!TYPE_REGEXP.test(type)) {
9180
+ throw new TypeError("invalid media type");
9181
+ }
9182
+ var obj = new ContentType(type.toLowerCase());
9183
+ if (index !== -1) {
9184
+ var key;
9185
+ var match;
9186
+ var value;
9187
+ PARAM_REGEXP.lastIndex = index;
9188
+ while (match = PARAM_REGEXP.exec(header)) {
9189
+ if (match.index !== index) {
9190
+ throw new TypeError("invalid parameter format");
9191
+ }
9192
+ index += match[0].length;
9193
+ key = match[1].toLowerCase();
9194
+ value = match[2];
9195
+ if (value.charCodeAt(0) === 34) {
9196
+ value = value.slice(1, -1);
9197
+ if (value.indexOf("\\") !== -1) {
9198
+ value = value.replace(QESC_REGEXP, "$1");
9199
+ }
9200
+ }
9201
+ obj.parameters[key] = value;
9202
+ }
9203
+ if (index !== header.length) {
9204
+ throw new TypeError("invalid parameter format");
9205
+ }
9206
+ }
9207
+ return obj;
9208
+ }
9209
+ function getcontenttype(obj) {
9210
+ var header;
9211
+ if (typeof obj.getHeader === "function") {
9212
+ header = obj.getHeader("content-type");
9213
+ } else if (typeof obj.headers === "object") {
9214
+ header = obj.headers && obj.headers["content-type"];
9215
+ }
9216
+ if (typeof header !== "string") {
9217
+ throw new TypeError("content-type header is missing from object");
9218
+ }
9219
+ return header;
9220
+ }
9221
+ function qstring(val) {
9222
+ var str = String(val);
9223
+ if (TOKEN_REGEXP.test(str)) {
9224
+ return str;
9225
+ }
9226
+ if (str.length > 0 && !TEXT_REGEXP.test(str)) {
9227
+ throw new TypeError("invalid parameter value");
9228
+ }
9229
+ return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"';
9230
+ }
9231
+ function ContentType(type) {
9232
+ this.parameters = /* @__PURE__ */ Object.create(null);
9233
+ this.type = type;
9234
+ }
9235
+ }
9236
+ });
9237
+
9133
9238
  // ../../node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js
9134
9239
  var require_suppress_tracing = __commonJS({
9135
9240
  "../../node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js"(exports) {
@@ -12914,19 +13019,19 @@ var require_getMachineId = __commonJS({
12914
13019
  if (!getMachineIdImpl) {
12915
13020
  switch (process2.platform) {
12916
13021
  case "darwin":
12917
- getMachineIdImpl = (await import("./getMachineId-darwin-COHLFNXH.js")).getMachineId;
13022
+ getMachineIdImpl = (await import("./getMachineId-darwin-OPTJOAYC.js")).getMachineId;
12918
13023
  break;
12919
13024
  case "linux":
12920
- getMachineIdImpl = (await import("./getMachineId-linux-XV3Z5FQG.js")).getMachineId;
13025
+ getMachineIdImpl = (await import("./getMachineId-linux-5SQRYTUJ.js")).getMachineId;
12921
13026
  break;
12922
13027
  case "freebsd":
12923
- getMachineIdImpl = (await import("./getMachineId-bsd-JGCLGHFY.js")).getMachineId;
13028
+ getMachineIdImpl = (await import("./getMachineId-bsd-NYGVHXGN.js")).getMachineId;
12924
13029
  break;
12925
13030
  case "win32":
12926
- getMachineIdImpl = (await import("./getMachineId-win-A4WRNVV6.js")).getMachineId;
13031
+ getMachineIdImpl = (await import("./getMachineId-win-SLTTCNXU.js")).getMachineId;
12927
13032
  break;
12928
13033
  default:
12929
- getMachineIdImpl = (await import("./getMachineId-unsupported-FCRKLIZL.js")).getMachineId;
13034
+ getMachineIdImpl = (await import("./getMachineId-unsupported-OJE7WPEH.js")).getMachineId;
12930
13035
  break;
12931
13036
  }
12932
13037
  }
@@ -14318,7 +14423,7 @@ var require_RandomIdGenerator = __commonJS({
14318
14423
  exports.RandomIdGenerator = void 0;
14319
14424
  var SPAN_ID_BYTES = 8;
14320
14425
  var TRACE_ID_BYTES = 16;
14321
- var RandomIdGenerator = class {
14426
+ var RandomIdGenerator2 = class {
14322
14427
  /**
14323
14428
  * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
14324
14429
  * characters corresponding to 128 bits.
@@ -14330,7 +14435,7 @@ var require_RandomIdGenerator = __commonJS({
14330
14435
  */
14331
14436
  generateSpanId = getIdGenerator(SPAN_ID_BYTES);
14332
14437
  };
14333
- exports.RandomIdGenerator = RandomIdGenerator;
14438
+ exports.RandomIdGenerator = RandomIdGenerator2;
14334
14439
  var SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
14335
14440
  function getIdGenerator(bytes2) {
14336
14441
  return function generateId() {
@@ -31996,6 +32101,7 @@ var InitializedNotificationSchema = NotificationSchema.extend({
31996
32101
  method: literal("notifications/initialized"),
31997
32102
  params: NotificationsParamsSchema.optional()
31998
32103
  });
32104
+ var isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;
31999
32105
  var PingRequestSchema = RequestSchema.extend({
32000
32106
  method: literal("ping"),
32001
32107
  params: BaseRequestParamsSchema.optional()
@@ -35149,477 +35255,21 @@ async function safeText(resp) {
35149
35255
  }
35150
35256
  }
35151
35257
 
35152
- // ../../node_modules/eventsource-parser/dist/index.js
35153
- var ParseError = class extends Error {
35154
- constructor(message, options) {
35155
- super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
35156
- }
35157
- };
35158
- var LF = 10;
35159
- var CR = 13;
35160
- var SPACE = 32;
35161
- function noop(_arg) {
35162
- }
35163
- function createParser(config) {
35164
- if (typeof config == "function")
35165
- throw new TypeError(
35166
- "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
35167
- );
35168
- const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];
35169
- let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
35170
- function feed(chunk) {
35171
- if (terminated)
35172
- throw new Error(
35173
- "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
35174
- );
35175
- if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
35176
- const trailing2 = processLines(chunk);
35177
- trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
35178
- return;
35179
- }
35180
- if (chunk.indexOf(`
35181
- `) === -1 && chunk.indexOf("\r") === -1) {
35182
- pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
35183
- return;
35184
- }
35185
- pendingFragments.push(chunk);
35186
- const input = pendingFragments.join("");
35187
- pendingFragments.length = 0, pendingFragmentsLength = 0;
35188
- const trailing = processLines(input);
35189
- trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
35190
- }
35191
- function checkBufferSize() {
35192
- maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
35193
- new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
35194
- type: "max-buffer-size-exceeded"
35195
- })
35196
- )));
35197
- }
35198
- function processLines(chunk) {
35199
- let searchIndex = 0;
35200
- if (chunk.indexOf("\r") === -1) {
35201
- let lfIndex = chunk.indexOf(`
35202
- `, searchIndex);
35203
- for (; lfIndex !== -1; ) {
35204
- if (searchIndex === lfIndex) {
35205
- dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
35206
- `, searchIndex);
35207
- continue;
35208
- }
35209
- const firstCharCode = chunk.charCodeAt(searchIndex);
35210
- if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
35211
- const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
35212
- if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
35213
- onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
35214
- `, searchIndex);
35215
- continue;
35216
- }
35217
- data = dataLines === 0 ? value : `${data}
35218
- ${value}`, dataLines++;
35219
- } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
35220
- chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
35221
- lfIndex
35222
- ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
35223
- searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
35224
- `, searchIndex);
35225
- }
35226
- return chunk.slice(searchIndex);
35227
- }
35228
- for (; searchIndex < chunk.length; ) {
35229
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
35230
- `, searchIndex);
35231
- let lineEnd = -1;
35232
- 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)
35233
- break;
35234
- parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
35235
- }
35236
- return chunk.slice(searchIndex);
35237
- }
35238
- function parseLine(chunk, start, end) {
35239
- if (start === end) {
35240
- dispatchEvent();
35241
- return;
35242
- }
35243
- const firstCharCode = chunk.charCodeAt(start);
35244
- if (isDataPrefix(chunk, start, firstCharCode)) {
35245
- const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
35246
- data = dataLines === 0 ? value2 : `${data}
35247
- ${value2}`, dataLines++;
35248
- return;
35249
- }
35250
- if (isEventPrefix(chunk, start, firstCharCode)) {
35251
- eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
35252
- return;
35253
- }
35254
- if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
35255
- const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
35256
- value2.includes("\0") || (id = value2);
35257
- return;
35258
- }
35259
- if (firstCharCode === 58) {
35260
- if (onComment) {
35261
- const line2 = chunk.slice(start, end);
35262
- onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
35263
- }
35264
- return;
35265
- }
35266
- const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
35267
- if (fieldSeparatorIndex === -1) {
35268
- processField(line, "", line);
35269
- return;
35270
- }
35271
- const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
35272
- processField(field, value, line);
35273
- }
35274
- function processField(field, value, line) {
35275
- switch (field) {
35276
- case "event":
35277
- eventType = value || void 0;
35278
- break;
35279
- case "data":
35280
- data = dataLines === 0 ? value : `${data}
35281
- ${value}`, dataLines++;
35282
- break;
35283
- case "id":
35284
- value.includes("\0") || (id = value);
35285
- break;
35286
- case "retry":
35287
- /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
35288
- new ParseError(`Invalid \`retry\` value: "${value}"`, {
35289
- type: "invalid-retry",
35290
- value,
35291
- line
35292
- })
35293
- );
35294
- break;
35295
- default:
35296
- onError(
35297
- new ParseError(
35298
- `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
35299
- { type: "unknown-field", field, value, line }
35300
- )
35301
- );
35302
- break;
35303
- }
35304
- }
35305
- function dispatchEvent() {
35306
- dataLines > 0 && onEvent({
35307
- id,
35308
- event: eventType,
35309
- data
35310
- }), id = void 0, data = "", dataLines = 0, eventType = void 0;
35311
- }
35312
- function reset(options = {}) {
35313
- if (options.consume && pendingFragments.length > 0) {
35314
- const incompleteLine = pendingFragments.join("");
35315
- parseLine(incompleteLine, 0, incompleteLine.length);
35316
- }
35317
- isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
35318
- }
35319
- return { feed, reset };
35320
- }
35321
- function isDataPrefix(chunk, i, firstCharCode) {
35322
- return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
35323
- }
35324
- function isEventPrefix(chunk, i, firstCharCode) {
35325
- return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
35326
- }
35327
-
35328
- // ../../node_modules/eventsource/dist/index.js
35329
- var ErrorEvent = class extends Event {
35330
- /**
35331
- * Constructs a new `ErrorEvent` instance. This is typically not called directly,
35332
- * but rather emitted by the `EventSource` object when an error occurs.
35333
- *
35334
- * @param type - The type of the event (should be "error")
35335
- * @param errorEventInitDict - Optional properties to include in the error event
35336
- */
35337
- constructor(type, errorEventInitDict) {
35338
- var _a2, _b2;
35339
- super(type), this.code = (_a2 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a2 : void 0, this.message = (_b2 = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b2 : void 0;
35340
- }
35341
- /**
35342
- * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
35343
- * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
35344
- * we explicitly include the properties in the `inspect` method.
35345
- *
35346
- * This is automatically called by Node.js when you `console.log` an instance of this class.
35347
- *
35348
- * @param _depth - The current depth
35349
- * @param options - The options passed to `util.inspect`
35350
- * @param inspect - The inspect function to use (prevents having to import it from `util`)
35351
- * @returns A string representation of the error
35352
- */
35353
- [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
35354
- return inspect(inspectableError(this), options);
35355
- }
35356
- /**
35357
- * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
35358
- * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
35359
- * we explicitly include the properties in the `inspect` method.
35360
- *
35361
- * This is automatically called by Deno when you `console.log` an instance of this class.
35362
- *
35363
- * @param inspect - The inspect function to use (prevents having to import it from `util`)
35364
- * @param options - The options passed to `Deno.inspect`
35365
- * @returns A string representation of the error
35366
- */
35367
- [Symbol.for("Deno.customInspect")](inspect, options) {
35368
- return inspect(inspectableError(this), options);
35258
+ // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
35259
+ var import_content_type = __toESM(require_content_type(), 1);
35260
+ function mediaTypeEssence(header) {
35261
+ if (!header) {
35262
+ return void 0;
35369
35263
  }
35370
- };
35371
- function syntaxError(message) {
35372
- const DomException = globalThis.DOMException;
35373
- return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
35374
- }
35375
- function flattenError(err2) {
35376
- return err2 instanceof Error ? "errors" in err2 && Array.isArray(err2.errors) ? err2.errors.map(flattenError).join(", ") : "cause" in err2 && err2.cause instanceof Error ? `${err2}: ${flattenError(err2.cause)}` : err2.message : `${err2}`;
35377
- }
35378
- function inspectableError(err2) {
35379
- return {
35380
- type: err2.type,
35381
- message: err2.message,
35382
- code: err2.code,
35383
- defaultPrevented: err2.defaultPrevented,
35384
- cancelable: err2.cancelable,
35385
- timeStamp: err2.timeStamp
35386
- };
35387
- }
35388
- var __typeError = (msg) => {
35389
- throw TypeError(msg);
35390
- };
35391
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
35392
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
35393
- 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);
35394
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
35395
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
35396
- var _readyState;
35397
- var _url;
35398
- var _redirectUrl;
35399
- var _withCredentials;
35400
- var _fetch;
35401
- var _reconnectInterval;
35402
- var _reconnectTimer;
35403
- var _lastEventId;
35404
- var _controller;
35405
- var _parser;
35406
- var _onError;
35407
- var _onMessage;
35408
- var _onOpen;
35409
- var _EventSource_instances;
35410
- var connect_fn;
35411
- var _onFetchResponse;
35412
- var _onFetchError;
35413
- var getRequestOptions_fn;
35414
- var _onEvent;
35415
- var _onRetryChange;
35416
- var failConnection_fn;
35417
- var scheduleReconnect_fn;
35418
- var _reconnect;
35419
- var EventSource = class extends EventTarget {
35420
- constructor(url2, eventSourceInitDict) {
35421
- var _a2, _b2;
35422
- super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __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) => {
35423
- var _a22;
35424
- __privateGet(this, _parser).reset();
35425
- const { body, redirected, status, headers } = response;
35426
- if (status === 204) {
35427
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
35428
- return;
35429
- }
35430
- if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
35431
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
35432
- return;
35433
- }
35434
- if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
35435
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
35436
- return;
35437
- }
35438
- if (__privateGet(this, _readyState) === this.CLOSED)
35439
- return;
35440
- __privateSet(this, _readyState, this.OPEN);
35441
- const openEvent = new Event("open");
35442
- if ((_a22 = __privateGet(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
35443
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
35444
- return;
35445
- }
35446
- const decoder = new TextDecoder(), reader = body.getReader();
35447
- let open = true;
35448
- do {
35449
- const { done, value } = await reader.read();
35450
- value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
35451
- } while (open);
35452
- }), __privateAdd(this, _onFetchError, (err2) => {
35453
- __privateSet(this, _controller, void 0), !(err2.name === "AbortError" || err2.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err2));
35454
- }), __privateAdd(this, _onEvent, (event) => {
35455
- typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
35456
- const messageEvent = new MessageEvent(event.event || "message", {
35457
- data: event.data,
35458
- origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
35459
- lastEventId: event.id || ""
35460
- });
35461
- __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
35462
- }), __privateAdd(this, _onRetryChange, (value) => {
35463
- __privateSet(this, _reconnectInterval, value);
35464
- }), __privateAdd(this, _reconnect, () => {
35465
- __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
35466
- });
35467
- try {
35468
- if (url2 instanceof URL)
35469
- __privateSet(this, _url, url2);
35470
- else if (typeof url2 == "string")
35471
- __privateSet(this, _url, new URL(url2, getBaseURL()));
35472
- else
35473
- throw new Error("Invalid URL");
35474
- } catch {
35475
- throw syntaxError("An invalid or illegal string was specified");
35264
+ try {
35265
+ return import_content_type.default.parse(header).type;
35266
+ } catch {
35267
+ const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase();
35268
+ if (essence === "" || header.slice(essence.length).includes(",")) {
35269
+ return void 0;
35476
35270
  }
35477
- __privateSet(this, _parser, createParser({
35478
- onEvent: __privateGet(this, _onEvent),
35479
- onRetry: __privateGet(this, _onRetryChange)
35480
- })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a2 : globalThis.fetch), __privateSet(this, _withCredentials, (_b2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b2 : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
35271
+ return essence;
35481
35272
  }
35482
- /**
35483
- * Returns the state of this EventSource object's connection. It can have the values described below.
35484
- *
35485
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
35486
- *
35487
- * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
35488
- * defined in the TypeScript `dom` library.
35489
- *
35490
- * @public
35491
- */
35492
- get readyState() {
35493
- return __privateGet(this, _readyState);
35494
- }
35495
- /**
35496
- * Returns the URL providing the event stream.
35497
- *
35498
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
35499
- *
35500
- * @public
35501
- */
35502
- get url() {
35503
- return __privateGet(this, _url).href;
35504
- }
35505
- /**
35506
- * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
35507
- *
35508
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
35509
- */
35510
- get withCredentials() {
35511
- return __privateGet(this, _withCredentials);
35512
- }
35513
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
35514
- get onerror() {
35515
- return __privateGet(this, _onError);
35516
- }
35517
- set onerror(value) {
35518
- __privateSet(this, _onError, value);
35519
- }
35520
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
35521
- get onmessage() {
35522
- return __privateGet(this, _onMessage);
35523
- }
35524
- set onmessage(value) {
35525
- __privateSet(this, _onMessage, value);
35526
- }
35527
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
35528
- get onopen() {
35529
- return __privateGet(this, _onOpen);
35530
- }
35531
- set onopen(value) {
35532
- __privateSet(this, _onOpen, value);
35533
- }
35534
- addEventListener(type, listener, options) {
35535
- const listen = listener;
35536
- super.addEventListener(type, listen, options);
35537
- }
35538
- removeEventListener(type, listener, options) {
35539
- const listen = listener;
35540
- super.removeEventListener(type, listen, options);
35541
- }
35542
- /**
35543
- * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
35544
- *
35545
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
35546
- *
35547
- * @public
35548
- */
35549
- close() {
35550
- __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));
35551
- }
35552
- };
35553
- _readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__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(), /**
35554
- * Connect to the given URL and start receiving events
35555
- *
35556
- * @internal
35557
- */
35558
- connect_fn = function() {
35559
- __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
35560
- }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
35561
- * Get request options for the `fetch()` request
35562
- *
35563
- * @returns The request options
35564
- * @internal
35565
- */
35566
- getRequestOptions_fn = function() {
35567
- var _a2;
35568
- const init = {
35569
- // [spec] Let `corsAttributeState` be `Anonymous`…
35570
- // [spec] …will have their mode set to "cors"…
35571
- mode: "cors",
35572
- redirect: "follow",
35573
- headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
35574
- cache: "no-store",
35575
- signal: (_a2 = __privateGet(this, _controller)) == null ? void 0 : _a2.signal
35576
- };
35577
- return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
35578
- }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
35579
- * Handles the process referred to in the EventSource specification as "failing a connection".
35580
- *
35581
- * @param error - The error causing the connection to fail
35582
- * @param code - The HTTP status code, if available
35583
- * @internal
35584
- */
35585
- failConnection_fn = function(message, code) {
35586
- var _a2;
35587
- __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
35588
- const errorEvent = new ErrorEvent("error", { code, message });
35589
- (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent);
35590
- }, /**
35591
- * Schedules a reconnection attempt against the EventSource endpoint.
35592
- *
35593
- * @param message - The error causing the connection to fail
35594
- * @param code - The HTTP status code, if available
35595
- * @internal
35596
- */
35597
- scheduleReconnect_fn = function(message, code) {
35598
- var _a2;
35599
- if (__privateGet(this, _readyState) === this.CLOSED)
35600
- return;
35601
- __privateSet(this, _readyState, this.CONNECTING);
35602
- const errorEvent = new ErrorEvent("error", { code, message });
35603
- (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
35604
- }, _reconnect = /* @__PURE__ */ new WeakMap(), /**
35605
- * ReadyState representing an EventSource currently trying to connect
35606
- *
35607
- * @public
35608
- */
35609
- EventSource.CONNECTING = 0, /**
35610
- * ReadyState representing an EventSource connection that is open (eg connected)
35611
- *
35612
- * @public
35613
- */
35614
- EventSource.OPEN = 1, /**
35615
- * ReadyState representing an EventSource connection that is closed (eg disconnected)
35616
- *
35617
- * @public
35618
- */
35619
- EventSource.CLOSED = 2;
35620
- function getBaseURL() {
35621
- const doc = "document" in globalThis ? globalThis.document : void 0;
35622
- return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
35623
35273
  }
35624
35274
 
35625
35275
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
@@ -36615,20 +36265,226 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
36615
36265
  return RegistrationResponseSchema.parse(await response.json());
36616
36266
  }
36617
36267
 
36618
- // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
36619
- var SseError = class extends Error {
36620
- constructor(code, message, event) {
36621
- super(`SSE error: ${message}`);
36268
+ // ../../node_modules/eventsource-parser/dist/index.js
36269
+ var ParseError = class extends Error {
36270
+ constructor(message, options) {
36271
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
36272
+ }
36273
+ };
36274
+ var LF = 10;
36275
+ var CR = 13;
36276
+ var SPACE = 32;
36277
+ function noop(_arg) {
36278
+ }
36279
+ function createParser(config) {
36280
+ if (typeof config == "function")
36281
+ throw new TypeError(
36282
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
36283
+ );
36284
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];
36285
+ let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
36286
+ function feed(chunk) {
36287
+ if (terminated)
36288
+ throw new Error(
36289
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
36290
+ );
36291
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
36292
+ const trailing2 = processLines(chunk);
36293
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
36294
+ return;
36295
+ }
36296
+ if (chunk.indexOf(`
36297
+ `) === -1 && chunk.indexOf("\r") === -1) {
36298
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
36299
+ return;
36300
+ }
36301
+ pendingFragments.push(chunk);
36302
+ const input = pendingFragments.join("");
36303
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
36304
+ const trailing = processLines(input);
36305
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
36306
+ }
36307
+ function checkBufferSize() {
36308
+ maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
36309
+ new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
36310
+ type: "max-buffer-size-exceeded"
36311
+ })
36312
+ )));
36313
+ }
36314
+ function processLines(chunk) {
36315
+ let searchIndex = 0;
36316
+ if (chunk.indexOf("\r") === -1) {
36317
+ let lfIndex = chunk.indexOf(`
36318
+ `, searchIndex);
36319
+ for (; lfIndex !== -1; ) {
36320
+ if (searchIndex === lfIndex) {
36321
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
36322
+ `, searchIndex);
36323
+ continue;
36324
+ }
36325
+ const firstCharCode = chunk.charCodeAt(searchIndex);
36326
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
36327
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
36328
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
36329
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
36330
+ `, searchIndex);
36331
+ continue;
36332
+ }
36333
+ data = dataLines === 0 ? value : `${data}
36334
+ ${value}`, dataLines++;
36335
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
36336
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
36337
+ lfIndex
36338
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
36339
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
36340
+ `, searchIndex);
36341
+ }
36342
+ return chunk.slice(searchIndex);
36343
+ }
36344
+ for (; searchIndex < chunk.length; ) {
36345
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
36346
+ `, searchIndex);
36347
+ let lineEnd = -1;
36348
+ 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)
36349
+ break;
36350
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
36351
+ }
36352
+ return chunk.slice(searchIndex);
36353
+ }
36354
+ function parseLine(chunk, start, end) {
36355
+ if (start === end) {
36356
+ dispatchEvent();
36357
+ return;
36358
+ }
36359
+ const firstCharCode = chunk.charCodeAt(start);
36360
+ if (isDataPrefix(chunk, start, firstCharCode)) {
36361
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
36362
+ data = dataLines === 0 ? value2 : `${data}
36363
+ ${value2}`, dataLines++;
36364
+ return;
36365
+ }
36366
+ if (isEventPrefix(chunk, start, firstCharCode)) {
36367
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
36368
+ return;
36369
+ }
36370
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
36371
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
36372
+ value2.includes("\0") || (id = value2);
36373
+ return;
36374
+ }
36375
+ if (firstCharCode === 58) {
36376
+ if (onComment) {
36377
+ const line2 = chunk.slice(start, end);
36378
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
36379
+ }
36380
+ return;
36381
+ }
36382
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
36383
+ if (fieldSeparatorIndex === -1) {
36384
+ processField(line, "", line);
36385
+ return;
36386
+ }
36387
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
36388
+ processField(field, value, line);
36389
+ }
36390
+ function processField(field, value, line) {
36391
+ switch (field) {
36392
+ case "event":
36393
+ eventType = value || void 0;
36394
+ break;
36395
+ case "data":
36396
+ data = dataLines === 0 ? value : `${data}
36397
+ ${value}`, dataLines++;
36398
+ break;
36399
+ case "id":
36400
+ value.includes("\0") || (id = value);
36401
+ break;
36402
+ case "retry":
36403
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
36404
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
36405
+ type: "invalid-retry",
36406
+ value,
36407
+ line
36408
+ })
36409
+ );
36410
+ break;
36411
+ default:
36412
+ onError(
36413
+ new ParseError(
36414
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
36415
+ { type: "unknown-field", field, value, line }
36416
+ )
36417
+ );
36418
+ break;
36419
+ }
36420
+ }
36421
+ function dispatchEvent() {
36422
+ dataLines > 0 && onEvent({
36423
+ id,
36424
+ event: eventType,
36425
+ data
36426
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
36427
+ }
36428
+ function reset(options = {}) {
36429
+ if (options.consume && pendingFragments.length > 0) {
36430
+ const incompleteLine = pendingFragments.join("");
36431
+ parseLine(incompleteLine, 0, incompleteLine.length);
36432
+ }
36433
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
36434
+ }
36435
+ return { feed, reset };
36436
+ }
36437
+ function isDataPrefix(chunk, i, firstCharCode) {
36438
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
36439
+ }
36440
+ function isEventPrefix(chunk, i, firstCharCode) {
36441
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
36442
+ }
36443
+
36444
+ // ../../node_modules/eventsource-parser/dist/stream.js
36445
+ var EventSourceParserStream = class extends TransformStream {
36446
+ constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
36447
+ let parser;
36448
+ super({
36449
+ start(controller) {
36450
+ parser = createParser({
36451
+ onEvent: (event) => {
36452
+ controller.enqueue(event);
36453
+ },
36454
+ onError(error) {
36455
+ typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
36456
+ },
36457
+ onRetry,
36458
+ onComment,
36459
+ maxBufferSize
36460
+ });
36461
+ },
36462
+ transform(chunk) {
36463
+ parser.feed(chunk);
36464
+ }
36465
+ });
36466
+ }
36467
+ };
36468
+
36469
+ // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
36470
+ var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
36471
+ initialReconnectionDelay: 1e3,
36472
+ maxReconnectionDelay: 3e4,
36473
+ reconnectionDelayGrowFactor: 1.5,
36474
+ maxRetries: 2
36475
+ };
36476
+ var StreamableHTTPError = class extends Error {
36477
+ constructor(code, message) {
36478
+ super(`Streamable HTTP error: ${message}`);
36622
36479
  this.code = code;
36623
- this.event = event;
36624
36480
  }
36625
36481
  };
36626
- var SSEClientTransport = class {
36482
+ var StreamableHTTPClientTransport = class {
36627
36483
  constructor(url2, opts) {
36484
+ this._hasCompletedAuthFlow = false;
36628
36485
  this._url = url2;
36629
36486
  this._resourceMetadataUrl = void 0;
36630
36487
  this._scope = void 0;
36631
- this._eventSourceInit = opts?.eventSourceInit;
36632
36488
  this._requestInit = opts?.requestInit;
36633
36489
  this._authProvider = opts?.authProvider;
36634
36490
  this._fetch = opts?.fetch;
@@ -36638,6 +36494,8 @@ var SSEClientTransport = class {
36638
36494
  this._fetch = fetchLeavingRedirects(this._fetch);
36639
36495
  this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
36640
36496
  }
36497
+ this._sessionId = opts?.sessionId;
36498
+ this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
36641
36499
  }
36642
36500
  /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
36643
36501
  _unfollowedRedirect(response, url2) {
@@ -36663,7 +36521,7 @@ var SSEClientTransport = class {
36663
36521
  if (result !== "AUTHORIZED") {
36664
36522
  throw new UnauthorizedError();
36665
36523
  }
36666
- return await this._startOrAuth();
36524
+ return await this._startOrAuthSse({ resumptionToken: void 0 });
36667
36525
  }
36668
36526
  async _commonHeaders() {
36669
36527
  const headers = {};
@@ -36673,6 +36531,9 @@ var SSEClientTransport = class {
36673
36531
  headers["Authorization"] = `Bearer ${tokens.access_token}`;
36674
36532
  }
36675
36533
  }
36534
+ if (this._sessionId) {
36535
+ headers["mcp-session-id"] = this._sessionId;
36536
+ }
36676
36537
  if (this._protocolVersion) {
36677
36538
  headers["mcp-protocol-version"] = this._protocolVersion;
36678
36539
  }
@@ -36682,74 +36543,148 @@ var SSEClientTransport = class {
36682
36543
  ...extraHeaders
36683
36544
  });
36684
36545
  }
36685
- _startOrAuth() {
36686
- const baseFetch = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
36687
- const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);
36688
- let redirect;
36689
- return new Promise((resolve, reject) => {
36690
- this._eventSource = new EventSource(this._url.href, {
36691
- ...this._eventSourceInit,
36692
- fetch: async (url2, init) => {
36693
- const headers = await this._commonHeaders();
36694
- headers.set("Accept", "text/event-stream");
36695
- const response = await fetchImpl(url2, {
36696
- ...init,
36697
- headers
36698
- });
36699
- redirect = this._unfollowedRedirect(response, url2);
36700
- if (response.status === 401 && response.headers.has("www-authenticate")) {
36701
- const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
36702
- this._resourceMetadataUrl = resourceMetadataUrl;
36703
- this._scope = scope;
36704
- }
36705
- return response;
36546
+ async _startOrAuthSse(options) {
36547
+ const { resumptionToken } = options;
36548
+ try {
36549
+ const headers = await this._commonHeaders();
36550
+ headers.set("Accept", "text/event-stream");
36551
+ if (resumptionToken) {
36552
+ headers.set("last-event-id", resumptionToken);
36553
+ }
36554
+ const fetchFn = this._fetch ?? fetch;
36555
+ const init = { method: "GET", headers, signal: this._abortController?.signal };
36556
+ let response = await fetchFn(this._url, this._followRedirects ? init : { ...init, redirect: "manual" });
36557
+ const followed = this._followRedirects ? void 0 : followWithinOrigin(fetchFn, this._url, init, response);
36558
+ if (followed) {
36559
+ response = await followed;
36560
+ }
36561
+ if (!response.ok) {
36562
+ await response.body?.cancel();
36563
+ if (response.status === 401 && this._authProvider) {
36564
+ return await this._authThenStart();
36706
36565
  }
36707
- });
36708
- this._abortController = new AbortController();
36709
- this._eventSource.onerror = (event) => {
36710
- if (event.code === 401 && this._authProvider) {
36711
- this._authThenStart().then(resolve, reject);
36566
+ if (response.status === 405) {
36712
36567
  return;
36713
36568
  }
36714
- const error = new SseError(event.code, redirect ?? event.message, event);
36715
- reject(error);
36716
- this.onerror?.(error);
36717
- };
36718
- this._eventSource.onopen = () => {
36719
- };
36720
- this._eventSource.addEventListener("endpoint", (event) => {
36721
- const messageEvent = event;
36722
- try {
36723
- this._endpoint = new URL(messageEvent.data, this._url);
36724
- if (this._endpoint.origin !== this._url.origin) {
36725
- throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
36569
+ throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
36570
+ }
36571
+ this._handleSseStream(response.body, options, true);
36572
+ } catch (error) {
36573
+ this.onerror?.(error);
36574
+ throw error;
36575
+ }
36576
+ }
36577
+ /**
36578
+ * Calculates the next reconnection delay using backoff algorithm
36579
+ *
36580
+ * @param attempt Current reconnection attempt count for the specific stream
36581
+ * @returns Time to wait in milliseconds before next reconnection attempt
36582
+ */
36583
+ _getNextReconnectionDelay(attempt) {
36584
+ if (this._serverRetryMs !== void 0) {
36585
+ return this._serverRetryMs;
36586
+ }
36587
+ const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
36588
+ const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
36589
+ const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
36590
+ return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
36591
+ }
36592
+ /**
36593
+ * Schedule a reconnection attempt using server-provided retry interval or backoff
36594
+ *
36595
+ * @param lastEventId The ID of the last received event for resumability
36596
+ * @param attemptCount Current reconnection attempt count for this specific stream
36597
+ */
36598
+ _scheduleReconnection(options, attemptCount = 0) {
36599
+ const maxRetries = this._reconnectionOptions.maxRetries;
36600
+ if (attemptCount >= maxRetries) {
36601
+ this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
36602
+ return;
36603
+ }
36604
+ const delay2 = this._getNextReconnectionDelay(attemptCount);
36605
+ this._reconnectionTimeout = setTimeout(() => {
36606
+ this._startOrAuthSse(options).catch((error) => {
36607
+ this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
36608
+ this._scheduleReconnection(options, attemptCount + 1);
36609
+ });
36610
+ }, delay2);
36611
+ }
36612
+ _handleSseStream(stream, options, isReconnectable) {
36613
+ if (!stream) {
36614
+ return;
36615
+ }
36616
+ const { onresumptiontoken, replayMessageId } = options;
36617
+ let lastEventId;
36618
+ let hasPrimingEvent = false;
36619
+ let receivedResponse = false;
36620
+ const processStream = async () => {
36621
+ try {
36622
+ const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
36623
+ onRetry: (retryMs) => {
36624
+ this._serverRetryMs = retryMs;
36625
+ }
36626
+ })).getReader();
36627
+ while (true) {
36628
+ const { value: event, done } = await reader.read();
36629
+ if (done) {
36630
+ break;
36631
+ }
36632
+ if (event.id) {
36633
+ lastEventId = event.id;
36634
+ hasPrimingEvent = true;
36635
+ onresumptiontoken?.(event.id);
36636
+ }
36637
+ if (!event.data) {
36638
+ continue;
36639
+ }
36640
+ if (!event.event || event.event === "message") {
36641
+ try {
36642
+ const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
36643
+ if (isJSONRPCResultResponse(message)) {
36644
+ receivedResponse = true;
36645
+ if (replayMessageId !== void 0) {
36646
+ message.id = replayMessageId;
36647
+ }
36648
+ }
36649
+ this.onmessage?.(message);
36650
+ } catch (error) {
36651
+ this.onerror?.(error);
36652
+ }
36726
36653
  }
36727
- } catch (error) {
36728
- reject(error);
36729
- this.onerror?.(error);
36730
- void this.close();
36731
- return;
36732
36654
  }
36733
- resolve();
36734
- });
36735
- this._eventSource.onmessage = (event) => {
36736
- const messageEvent = event;
36737
- let message;
36738
- try {
36739
- message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
36740
- } catch (error) {
36741
- this.onerror?.(error);
36742
- return;
36655
+ const canResume = isReconnectable || hasPrimingEvent;
36656
+ const needsReconnect = canResume && !receivedResponse;
36657
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
36658
+ this._scheduleReconnection({
36659
+ resumptionToken: lastEventId,
36660
+ onresumptiontoken,
36661
+ replayMessageId
36662
+ }, 0);
36743
36663
  }
36744
- this.onmessage?.(message);
36745
- };
36746
- });
36664
+ } catch (error) {
36665
+ this.onerror?.(new Error(`SSE stream disconnected: ${error}`));
36666
+ const canResume = isReconnectable || hasPrimingEvent;
36667
+ const needsReconnect = canResume && !receivedResponse;
36668
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
36669
+ try {
36670
+ this._scheduleReconnection({
36671
+ resumptionToken: lastEventId,
36672
+ onresumptiontoken,
36673
+ replayMessageId
36674
+ }, 0);
36675
+ } catch (error2) {
36676
+ this.onerror?.(new Error(`Failed to reconnect: ${error2 instanceof Error ? error2.message : String(error2)}`));
36677
+ }
36678
+ }
36679
+ }
36680
+ };
36681
+ processStream();
36747
36682
  }
36748
36683
  async start() {
36749
- if (this._eventSource) {
36750
- throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
36684
+ if (this._abortController) {
36685
+ throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
36751
36686
  }
36752
- return await this._startOrAuth();
36687
+ this._abortController = new AbortController();
36753
36688
  }
36754
36689
  /**
36755
36690
  * 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.
@@ -36770,17 +36705,23 @@ var SSEClientTransport = class {
36770
36705
  }
36771
36706
  }
36772
36707
  async close() {
36708
+ if (this._reconnectionTimeout) {
36709
+ clearTimeout(this._reconnectionTimeout);
36710
+ this._reconnectionTimeout = void 0;
36711
+ }
36773
36712
  this._abortController?.abort();
36774
- this._eventSource?.close();
36775
36713
  this.onclose?.();
36776
36714
  }
36777
- async send(message) {
36778
- if (!this._endpoint) {
36779
- throw new Error("Not connected");
36780
- }
36715
+ async send(message, options) {
36781
36716
  try {
36717
+ const { resumptionToken, onresumptiontoken } = options || {};
36718
+ if (resumptionToken) {
36719
+ this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err2) => this.onerror?.(err2));
36720
+ return;
36721
+ }
36782
36722
  const headers = await this._commonHeaders();
36783
36723
  headers.set("content-type", "application/json");
36724
+ headers.set("accept", "application/json, text/event-stream");
36784
36725
  const init = {
36785
36726
  ...this._requestInit,
36786
36727
  method: "POST",
@@ -36788,10 +36729,17 @@ var SSEClientTransport = class {
36788
36729
  body: JSON.stringify(message),
36789
36730
  signal: this._abortController?.signal
36790
36731
  };
36791
- const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);
36732
+ const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
36733
+ const sessionId = response.headers.get("mcp-session-id");
36734
+ if (sessionId) {
36735
+ this._sessionId = sessionId;
36736
+ }
36792
36737
  if (!response.ok) {
36793
36738
  const text = await response.text().catch(() => null);
36794
36739
  if (response.status === 401 && this._authProvider) {
36740
+ if (this._hasCompletedAuthFlow) {
36741
+ throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
36742
+ }
36795
36743
  const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
36796
36744
  this._resourceMetadataUrl = resourceMetadataUrl;
36797
36745
  this._scope = scope;
@@ -36804,11 +36752,103 @@ var SSEClientTransport = class {
36804
36752
  if (result !== "AUTHORIZED") {
36805
36753
  throw new UnauthorizedError();
36806
36754
  }
36755
+ this._hasCompletedAuthFlow = true;
36807
36756
  return this.send(message);
36808
36757
  }
36809
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text}`);
36758
+ if (response.status === 403 && this._authProvider) {
36759
+ const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
36760
+ if (error === "insufficient_scope") {
36761
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
36762
+ if (this._lastUpscopingHeader === wwwAuthHeader) {
36763
+ throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
36764
+ }
36765
+ if (scope) {
36766
+ this._scope = scope;
36767
+ }
36768
+ if (resourceMetadataUrl) {
36769
+ this._resourceMetadataUrl = resourceMetadataUrl;
36770
+ }
36771
+ this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
36772
+ const result = await auth(this._authProvider, {
36773
+ serverUrl: this._url,
36774
+ resourceMetadataUrl: this._resourceMetadataUrl,
36775
+ scope: this._scope,
36776
+ fetchFn: this._fetch
36777
+ });
36778
+ if (result !== "AUTHORIZED") {
36779
+ throw new UnauthorizedError();
36780
+ }
36781
+ return this.send(message);
36782
+ }
36783
+ }
36784
+ throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${this._unfollowedRedirect(response, this._url) ?? text}`);
36810
36785
  }
36786
+ this._hasCompletedAuthFlow = false;
36787
+ this._lastUpscopingHeader = void 0;
36788
+ if (response.status === 202) {
36789
+ await response.body?.cancel();
36790
+ if (isInitializedNotification(message)) {
36791
+ this._startOrAuthSse({ resumptionToken: void 0 }).catch((err2) => this.onerror?.(err2));
36792
+ }
36793
+ return;
36794
+ }
36795
+ const messages = Array.isArray(message) ? message : [message];
36796
+ const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
36797
+ const contentType2 = response.headers.get("content-type");
36798
+ const responseMediaType = mediaTypeEssence(contentType2);
36799
+ if (hasRequests) {
36800
+ if (responseMediaType === "text/event-stream") {
36801
+ this._handleSseStream(response.body, { onresumptiontoken }, false);
36802
+ } else if (responseMediaType === "application/json") {
36803
+ const data = await response.json();
36804
+ const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
36805
+ for (const msg of responseMessages) {
36806
+ this.onmessage?.(msg);
36807
+ }
36808
+ } else {
36809
+ await response.body?.cancel();
36810
+ throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType2}`);
36811
+ }
36812
+ } else {
36813
+ await response.body?.cancel();
36814
+ }
36815
+ } catch (error) {
36816
+ this.onerror?.(error);
36817
+ throw error;
36818
+ }
36819
+ }
36820
+ get sessionId() {
36821
+ return this._sessionId;
36822
+ }
36823
+ /**
36824
+ * Terminates the current session by sending a DELETE request to the server.
36825
+ *
36826
+ * Clients that no longer need a particular session
36827
+ * (e.g., because the user is leaving the client application) SHOULD send an
36828
+ * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
36829
+ * terminate the session.
36830
+ *
36831
+ * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
36832
+ * the server does not allow clients to terminate sessions.
36833
+ */
36834
+ async terminateSession() {
36835
+ if (!this._sessionId) {
36836
+ return;
36837
+ }
36838
+ try {
36839
+ const headers = await this._commonHeaders();
36840
+ const init = {
36841
+ ...this._requestInit,
36842
+ method: "DELETE",
36843
+ headers,
36844
+ signal: this._abortController?.signal
36845
+ };
36846
+ const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
36811
36847
  await response.body?.cancel();
36848
+ if (!response.ok && response.status !== 405) {
36849
+ throw new StreamableHTTPError(response.status, `Failed to terminate session: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
36850
+ }
36851
+ this._sessionId = void 0;
36812
36852
  } catch (error) {
36813
36853
  this.onerror?.(error);
36814
36854
  throw error;
@@ -36817,6 +36857,22 @@ var SSEClientTransport = class {
36817
36857
  setProtocolVersion(version) {
36818
36858
  this._protocolVersion = version;
36819
36859
  }
36860
+ get protocolVersion() {
36861
+ return this._protocolVersion;
36862
+ }
36863
+ /**
36864
+ * Resume an SSE stream from a previous event ID.
36865
+ * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
36866
+ *
36867
+ * @param lastEventId The event ID to resume from
36868
+ * @param options Optional callback to receive new resumption tokens
36869
+ */
36870
+ async resumeStream(lastEventId, options) {
36871
+ await this._startOrAuthSse({
36872
+ resumptionToken: lastEventId,
36873
+ onresumptiontoken: options?.onresumptiontoken
36874
+ });
36875
+ }
36820
36876
  };
36821
36877
 
36822
36878
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/mcpInvocationError.js
@@ -36935,7 +36991,7 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
36935
36991
  };
36936
36992
  }
36937
36993
 
36938
- // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/sseTransportFactory.js
36994
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/streamableHttpTransportFactory.js
36939
36995
  function withTimeout(fetch2, timeoutMs) {
36940
36996
  return async (url2, init) => {
36941
36997
  if (init?.signal) {
@@ -36949,14 +37005,12 @@ function withTimeout(fetch2, timeoutMs) {
36949
37005
  }
36950
37006
  };
36951
37007
  }
36952
- function createSseTransport(config, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
37008
+ function createStreamableHttpTransport(config, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
36953
37009
  const url2 = new URL(config.sseEndpoint, config.remoteBaseUrl);
36954
37010
  const timeoutMs = config.requestTimeoutMs ?? 18e4;
36955
37011
  const signingFetch = withTimeout(createSigningFetch(signer, void 0, onTraceId, debugLog, getCallHeaders, invocationContext), timeoutMs);
36956
- return new SSEClientTransport(url2, {
36957
- // SSE 建连(EventSource)的 GET fetch:SDK 先包默认头再调这里。
36958
- eventSourceInit: { fetch: signingFetch },
36959
- // MCP 发消息用的 POST fetch。
37012
+ return new StreamableHTTPClientTransport(url2, {
37013
+ // SDK 的所有 HTTP 请求统一经签名器,保留会话与协议协商请求头。
36960
37014
  fetch: signingFetch
36961
37015
  });
36962
37016
  }
@@ -37210,7 +37264,7 @@ var RemoteGatewayMcpServerProvider = class {
37210
37264
  const verifier = this.doCreateTokenVerifier(config);
37211
37265
  const callHeaders = new AsyncLocalStorage2();
37212
37266
  const { client } = await connectMcpClientWithRetry(config, {
37213
- createTransport: () => createSseTransport(config, this.doCreateSigner(config, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
37267
+ createTransport: () => createStreamableHttpTransport(config, this.doCreateSigner(config, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
37214
37268
  createClient: () => this.doCrateClient(),
37215
37269
  runConnect: (operation, attempt) => this.invocationContext.run(timeoutMs, connectSignal, operation, {
37216
37270
  observation,
@@ -39304,6 +39358,24 @@ function sanitizeAttributeValue(value) {
39304
39358
  }
39305
39359
 
39306
39360
  // ../linkque-agent-runtime/dist/esm/impl/telemetry/otelRuntimeTelemetry.js
39361
+ var InitialRootTraceIdGenerator = class {
39362
+ initialRootTraceId;
39363
+ fallback = new import_sdk_trace_base.RandomIdGenerator();
39364
+ constructor(initialRootTraceId) {
39365
+ this.initialRootTraceId = initialRootTraceId;
39366
+ }
39367
+ generateTraceId() {
39368
+ if (this.initialRootTraceId) {
39369
+ const traceId = this.initialRootTraceId;
39370
+ this.initialRootTraceId = void 0;
39371
+ return traceId;
39372
+ }
39373
+ return this.fallback.generateTraceId();
39374
+ }
39375
+ generateSpanId() {
39376
+ return this.fallback.generateSpanId();
39377
+ }
39378
+ };
39307
39379
  var OtelRuntimeTelemetry = class {
39308
39380
  options;
39309
39381
  queue;
@@ -39323,9 +39395,10 @@ var OtelRuntimeTelemetry = class {
39323
39395
  this.options = options;
39324
39396
  this.queue = new IdentityQueue(options);
39325
39397
  const ratio = options.sampleRatio ?? 1;
39398
+ const initialRootTraceId = options.initialRootTraceId?.toLowerCase();
39326
39399
  this.maxActive = options.maxActiveOperations ?? 4096;
39327
39400
  this.maxAge = options.operationMaxAgeMs ?? 24 * 60 * 60 * 1e3;
39328
- 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)
39401
+ 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))
39329
39402
  throw new Error("\u975E\u6CD5\u9065\u6D4B\u5B9E\u4F8B\u914D\u7F6E");
39330
39403
  const resource = (0, import_resources.resourceFromAttributes)({
39331
39404
  [ETelemetryAttribute.SERVICE_NAME]: options.serviceName,
@@ -39336,6 +39409,7 @@ var OtelRuntimeTelemetry = class {
39336
39409
  });
39337
39410
  this.tracerProvider = new import_sdk_trace_base.BasicTracerProvider({
39338
39411
  resource,
39412
+ idGenerator: new InitialRootTraceIdGenerator(initialRootTraceId),
39339
39413
  sampler: new import_sdk_trace_base.ParentBasedSampler({
39340
39414
  root: new import_sdk_trace_base.TraceIdRatioBasedSampler(ratio)
39341
39415
  }),