linkque-cli-v2 1.3.6 → 1.3.7

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 (18) hide show
  1. package/linkquejs.js +21 -7
  2. package/package.json +1 -1
  3. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-NHRW2KQW.js → chunk-AACYYAZ6.js} +1 -1
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-HM7KNEG3.js → chunk-DNTEEBEH.js} +5 -0
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-EAODRPW4.js +518 -0
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-7SF3H2GM.js → chunk-RHMVQTA7.js} +6 -1
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-RHFHCJYP.js → chunk-ZNU4GVF3.js} +15155 -379
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-bsd-H2ZLZRGB.js → getMachineId-bsd-JGCLGHFY.js} +1 -1
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-darwin-HUKYR46U.js → getMachineId-darwin-COHLFNXH.js} +1 -1
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-linux-M5ZADHBA.js → getMachineId-linux-XV3Z5FQG.js} +1 -1
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-unsupported-BM5RZZVM.js → getMachineId-unsupported-FCRKLIZL.js} +1 -1
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-win-BQPUF5TW.js → getMachineId-win-A4WRNVV6.js} +1 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-TQA2MPJJ.js → mistral-conversations-5RZTVEO2.js} +1 -1
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{otel-RXJWJ2TU.js → otel-WGS5CC2J.js} +250 -267
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +97 -18
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +4 -3
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +4 -3
  18. package/worker.js +270 -47
package/worker.js CHANGED
@@ -80,6 +80,7 @@ var init_agentProtocol = __esm({
80
80
  (function(EArgsMappingValueType2) {
81
81
  EArgsMappingValueType2["DEFAULT"] = "DEFAULT";
82
82
  EArgsMappingValueType2["CONST"] = "CONST";
83
+ EArgsMappingValueType2["SYSTEM_VARIABLE"] = "SYSTEM_VARIABLE";
83
84
  })(EArgsMappingValueType || (EArgsMappingValueType = {}));
84
85
  (function(EHookStage2) {
85
86
  EHookStage2["PREPARE_AGENT_LOOP"] = "PREPARE_AGENT_LOOP";
@@ -4360,13 +4361,14 @@ var require_fast_uri = __commonJS({
4360
4361
  if (!malformedIPLiteral) {
4361
4362
  malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP2);
4362
4363
  }
4363
- if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
4364
- if (uri.indexOf("%") !== -1) {
4365
- if (parsed.host !== void 0 && !malformedIPLiteral) {
4366
- const host = isIP2 ? parsed.host : normalizePercentEncoding(parsed.host, true);
4367
- parsed.host = reescapeHostDelimiters(host, isIP2);
4368
- }
4364
+ if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) {
4365
+ let host = isIP2 ? parsed.host : normalizePercentEncoding(parsed.host, true);
4366
+ if (!isIP2) {
4367
+ host = normalizePercentEncoding(host.toLowerCase());
4369
4368
  }
4369
+ parsed.host = reescapeHostDelimiters(host, isIP2);
4370
+ }
4371
+ if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
4370
4372
  if (parsed.path) {
4371
4373
  parsed.path = normalizePathEncoding(parsed.path);
4372
4374
  }
@@ -13868,7 +13870,8 @@ var init_runtimeConfigProvider = __esm({
13868
13870
  LINKQUEGW_KNOWLEDGE_BASE_URL: LINKQUE_ENDPOINT_PROD,
13869
13871
  LINKQUEGW_WEB_SEARCH_BASE_URL: LINKQUE_ENDPOINT_PROD,
13870
13872
  LINKQUEGW_EVENT_BASE_URL: LINKQUE_ENDPOINT_PROD,
13871
- LINKQUEGW_MCP_SIGN_ENDPOINT: `${LINKQUE_ENDPOINT_PROD}/api/mcp/signature`
13873
+ LINKQUEGW_MCP_SIGN_ENDPOINT: `${LINKQUE_ENDPOINT_PROD}/api/mcp/signature`,
13874
+ LINKQUEGW_TOKEN_VERIFY_ENDPOINT: `${LINKQUE_ENDPOINT_PROD}/api/auth/verify`
13872
13875
  });
13873
13876
  RuntimeConfigProvider = class {
13874
13877
  defaults;
@@ -212491,6 +212494,53 @@ function sleep(ms) {
212491
212494
  });
212492
212495
  }
212493
212496
 
212497
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/mcpInvocationContext.js
212498
+ var import_node_async_hooks = require("node:async_hooks");
212499
+ async function waitForMcpOperation(operation, signal) {
212500
+ signal.throwIfAborted();
212501
+ let onAbort = () => {
212502
+ };
212503
+ try {
212504
+ return await Promise.race([
212505
+ new Promise((_, reject) => {
212506
+ onAbort = () => reject(signal.reason);
212507
+ signal.addEventListener("abort", onAbort, { once: true });
212508
+ }),
212509
+ Promise.resolve().then(() => {
212510
+ signal.throwIfAborted();
212511
+ return operation();
212512
+ })
212513
+ ]);
212514
+ } finally {
212515
+ signal.removeEventListener("abort", onAbort);
212516
+ }
212517
+ }
212518
+ var McpInvocationContext = class {
212519
+ storage = new import_node_async_hooks.AsyncLocalStorage();
212520
+ current() {
212521
+ return this.storage.getStore();
212522
+ }
212523
+ async run(timeoutMs, signal, operation) {
212524
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
212525
+ throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
212526
+ signal?.throwIfAborted();
212527
+ const controller = new AbortController();
212528
+ const context2 = {
212529
+ signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
212530
+ deadline: performance.now() + timeoutMs
212531
+ };
212532
+ const timer = setTimeout(() => controller.abort(new DOMException("MCP \u8C03\u7528\u603B\u9884\u7B97\u5DF2\u8017\u5C3D", "TimeoutError")), Math.min(timeoutMs, 2147483647));
212533
+ try {
212534
+ return await this.storage.run(context2, () => waitForMcpOperation(() => operation(context2), context2.signal));
212535
+ } catch (error40) {
212536
+ context2.signal.throwIfAborted();
212537
+ throw error40;
212538
+ } finally {
212539
+ clearTimeout(timer);
212540
+ }
212541
+ }
212542
+ };
212543
+
212494
212544
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/remoteSignatureSigner.js
212495
212545
  init_config();
212496
212546
  init_httpLoggingFetch();
@@ -212499,11 +212549,13 @@ var RemoteSignatureSigner = class {
212499
212549
  agentId;
212500
212550
  signEndpoint;
212501
212551
  fetchImpl;
212552
+ rawFetch;
212502
212553
  getAuthorizationHeader;
212503
212554
  constructor(options) {
212504
212555
  this.agentId = options.agentId;
212505
212556
  this.signEndpoint = options.signEndpoint ?? DEFAULT_SIGN_ENDPOINT;
212506
212557
  const baseFetch = options.fetchImpl ?? globalThis.fetch;
212558
+ this.rawFetch = baseFetch;
212507
212559
  this.fetchImpl = options.debugLog ? createHttpLoggingFetch(options.debugLog, "mcp-sign", baseFetch) : baseFetch;
212508
212560
  this.getAuthorizationHeader = options.getAuthorizationHeader;
212509
212561
  }
@@ -212514,7 +212566,8 @@ var RemoteSignatureSigner = class {
212514
212566
  * @returns `{authorization, signatureContent, userId?}`
212515
212567
  * @throws 签名服务非 2xx / 鉴权头获取失败 / 响应缺字段时抛错(由 signingFetch 转 transport-error)。
212516
212568
  */
212517
- async sign(req) {
212569
+ async sign(req, options = {}) {
212570
+ options.signal?.throwIfAborted();
212518
212571
  const body = JSON.stringify({
212519
212572
  agentId: this.agentId,
212520
212573
  httpMethod: req.httpMethod,
@@ -212525,16 +212578,16 @@ var RemoteSignatureSigner = class {
212525
212578
  "content-type": "application/json",
212526
212579
  "x-linkque-agent-id": this.agentId
212527
212580
  };
212528
- if (this.getAuthorizationHeader) {
212529
- headers.authorization = await this.getAuthorizationHeader();
212581
+ if (options.authorizationHeader !== void 0) {
212582
+ headers.authorization = options.authorizationHeader;
212583
+ } else if (this.getAuthorizationHeader) {
212584
+ headers.authorization = options.signal ? await waitForMcpOperation(() => this.getAuthorizationHeader(), options.signal) : await this.getAuthorizationHeader();
212530
212585
  }
212531
- const resp = await this.fetchImpl(this.signEndpoint, {
212532
- method: "POST",
212533
- headers,
212534
- body
212535
- });
212586
+ options.signal?.throwIfAborted();
212587
+ const resp = await (options.sensitive ? this.rawFetch : this.fetchImpl)(this.signEndpoint, { method: "POST", headers, body, signal: options.signal });
212588
+ options.signal?.throwIfAborted();
212536
212589
  if (!resp.ok) {
212537
- const text2 = await safeText(resp);
212590
+ const text2 = options.sensitive ? "" : await safeText(resp);
212538
212591
  throw new Error(`linkquegw \u7B7E\u540D\u670D\u52A1\u5931\u8D25: status=${resp.status}${text2 ? ` body=${text2}` : ""}`);
212539
212592
  }
212540
212593
  const parsed = await resp.json().catch(() => ({}));
@@ -212575,7 +212628,7 @@ function extractFromWrapped(wrapped) {
212575
212628
  };
212576
212629
  }
212577
212630
  function optionalUserId(value) {
212578
- return typeof value === "string" && value.trim() ? { userId: value.trim() } : {};
212631
+ return typeof value === "string" && value.trim() ? { userId: value } : {};
212579
212632
  }
212580
212633
  async function safeText(resp) {
212581
212634
  try {
@@ -214120,20 +214173,42 @@ var SSEClientTransport = class {
214120
214173
  }
214121
214174
  };
214122
214175
 
214176
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/mcpInvocationError.js
214177
+ var McpInvocationError = class extends Error {
214178
+ code;
214179
+ constructor(code, message) {
214180
+ super(`${code}: ${message}`);
214181
+ this.code = code;
214182
+ this.name = "McpInvocationError";
214183
+ }
214184
+ };
214185
+
214123
214186
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/signingFetch.js
214124
214187
  init_httpLoggingFetch();
214125
214188
  var ALIPAY_SDK_VERSION = "@alipay/open-mcp-server-2.0.4";
214126
214189
  var OAGW_ALIPAY_UID_HEADER = "x-oagw-alipay-uid";
214127
- function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, debugLog, getCallHeaders) {
214190
+ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, debugLog, getCallHeaders, invocationContext) {
214128
214191
  const loggedFetch = debugLog ? createHttpLoggingFetch(debugLog, "mcp-call", baseFetch) : baseFetch;
214129
214192
  return async (url2, init) => {
214193
+ const invocation = invocationContext?.current();
214194
+ const signals = [init?.signal, invocation?.signal].filter((signal2) => !!signal2);
214195
+ const signal = signals.length ? AbortSignal.any(signals) : void 0;
214196
+ signal?.throwIfAborted();
214130
214197
  const targetUrl = url2 instanceof URL ? url2 : new URL(typeof url2 === "string" ? url2 : url2.url);
214131
214198
  const req = {
214132
214199
  httpMethod: init?.method ?? "GET",
214133
214200
  httpRequestUrl: targetUrl.pathname + targetUrl.search,
214134
214201
  httpRequestBody: typeof init?.body === "string" ? init.body : ""
214135
214202
  };
214136
- const { authorization, signatureContent, userId } = await signer.sign(req);
214203
+ const { authorization, signatureContent, userId } = await signer.sign(req, {
214204
+ authorizationHeader: invocation?.auth?.authorization,
214205
+ signal,
214206
+ sensitive: !!invocation?.auth
214207
+ });
214208
+ signal?.throwIfAborted();
214209
+ if (invocation?.auth && userId !== invocation.auth.userId) {
214210
+ throw new McpInvocationError("MCP_IDENTITY_MISMATCH", "\u7B7E\u540D\u8EAB\u4EFD\u4E0E\u6821\u9A8C\u8EAB\u4EFD\u4E0D\u4E00\u81F4");
214211
+ }
214137
214212
  const headers = new Headers(init?.headers);
214138
214213
  headers.set("Authorization", authorization);
214139
214214
  headers.set("X-Signature-Content", Buffer.from(signatureContent).toString("base64"));
@@ -214150,7 +214225,11 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
214150
214225
  else
214151
214226
  headers.delete("x-alipay-authcode");
214152
214227
  }
214153
- const resp = await loggedFetch(url2, { ...init, headers });
214228
+ const resp = await (invocation?.auth ? baseFetch : loggedFetch)(url2, {
214229
+ ...init,
214230
+ headers,
214231
+ ...signal ? { signal } : {}
214232
+ });
214154
214233
  if (onTraceId) {
214155
214234
  try {
214156
214235
  const traceId = resp.headers.get("alipay-trace-id");
@@ -214178,10 +214257,10 @@ function withTimeout(fetch3, timeoutMs) {
214178
214257
  return fetch3(url2, { ...init, signal });
214179
214258
  };
214180
214259
  }
214181
- function createSseTransport(config2, signer, onTraceId, debugLog, getCallHeaders) {
214260
+ function createSseTransport(config2, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
214182
214261
  const url2 = new URL(config2.sseEndpoint, config2.remoteBaseUrl);
214183
214262
  const timeoutMs = config2.requestTimeoutMs ?? 18e4;
214184
- const signingFetch = withTimeout(createSigningFetch(signer, void 0, onTraceId, debugLog, getCallHeaders), timeoutMs);
214263
+ const signingFetch = withTimeout(createSigningFetch(signer, void 0, onTraceId, debugLog, getCallHeaders, invocationContext), timeoutMs);
214185
214264
  return new SSEClientTransport(url2, {
214186
214265
  // SSE 建连(EventSource)的 GET fetch:SDK 先包默认头再调这里。
214187
214266
  eventSourceInit: { fetch: signingFetch },
@@ -214192,6 +214271,17 @@ function createSseTransport(config2, signer, onTraceId, debugLog, getCallHeaders
214192
214271
 
214193
214272
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/argsMapper.js
214194
214273
  init_esm();
214274
+ var USER_ID = Symbol("\u7CFB\u7EDF\u53D8\u91CF\u7528\u6237\u6807\u8BC6");
214275
+ function assertSafePath(segments) {
214276
+ if (segments.some((s2) => ["__proto__", "constructor", "prototype"].includes(String(s2)))) {
214277
+ throw new McpInvocationError("MCP_SYSTEM_VARIABLE_INVALID", "\u6620\u5C04\u8DEF\u5F84\u7981\u6B62\u8BBF\u95EE\u539F\u578B");
214278
+ }
214279
+ }
214280
+ function assertContainer(value) {
214281
+ if (value === null || typeof value !== "object") {
214282
+ throw new McpInvocationError("MCP_SYSTEM_VARIABLE_INVALID", "\u6620\u5C04\u8DEF\u5F84\u4E0D\u53EF\u5199");
214283
+ }
214284
+ }
214195
214285
  function parsePath(path9) {
214196
214286
  if (path9 === "")
214197
214287
  return [];
@@ -214216,50 +214306,60 @@ function parsePath(path9) {
214216
214306
  return segments;
214217
214307
  }
214218
214308
  function getByPath(obj, segments) {
214309
+ assertSafePath(segments);
214219
214310
  let cur = obj;
214220
214311
  for (const seg of segments) {
214221
214312
  if (cur === null || cur === void 0)
214222
214313
  return void 0;
214223
- cur = cur[seg];
214314
+ cur = Object.hasOwn(Object(cur), seg) ? cur[seg] : void 0;
214224
214315
  }
214225
214316
  return cur;
214226
214317
  }
214227
214318
  function setByPath(obj, segments, value) {
214319
+ assertSafePath(segments);
214228
214320
  if (segments.length === 0)
214229
214321
  return;
214230
214322
  let cur = obj;
214231
214323
  for (let i2 = 0; i2 < segments.length - 1; i2 += 1) {
214232
214324
  const seg = segments[i2];
214233
214325
  const next = segments[i2 + 1];
214234
- const existing = cur[seg];
214326
+ assertContainer(cur);
214327
+ const existing = Object.hasOwn(cur, seg) ? cur[seg] : void 0;
214235
214328
  if (existing === null || existing === void 0) {
214236
214329
  cur[seg] = typeof next === "number" ? [] : {};
214237
214330
  }
214238
214331
  cur = cur[seg];
214239
214332
  }
214240
214333
  const last = segments[segments.length - 1];
214241
- cur[last] = value;
214334
+ assertContainer(cur);
214335
+ Object.defineProperty(cur, last, {
214336
+ value,
214337
+ enumerable: true,
214338
+ writable: true,
214339
+ configurable: true
214340
+ });
214242
214341
  }
214243
214342
  function unsetByPath(obj, segments) {
214343
+ assertSafePath(segments);
214244
214344
  if (segments.length === 0)
214245
214345
  return;
214246
214346
  let cur = obj;
214247
214347
  for (let i2 = 0; i2 < segments.length - 1; i2 += 1) {
214248
214348
  const seg = segments[i2];
214249
- cur = cur[seg];
214349
+ assertContainer(cur);
214350
+ cur = Object.hasOwn(cur, seg) ? cur[seg] : void 0;
214250
214351
  if (cur === null || cur === void 0)
214251
214352
  return;
214252
214353
  }
214253
214354
  const last = segments[segments.length - 1];
214254
214355
  if (cur !== void 0) {
214356
+ assertContainer(cur);
214255
214357
  delete cur[last];
214256
214358
  }
214257
214359
  }
214258
- function applyArgsMappingRules(toolName, args, rules) {
214360
+ function createArgsMappingPlan(toolName, args, rules) {
214259
214361
  const out = args ? JSON.parse(JSON.stringify(args)) : {};
214260
- if (!rules || rules.length === 0)
214261
- return out;
214262
- for (const rule of rules) {
214362
+ for (const rule of rules ?? []) {
214263
214363
  if (rule.mcpToolName !== toolName)
214264
214364
  continue;
214265
214365
  const segments = parsePath(rule.argJsonPath);
@@ -214267,6 +214367,13 @@ function applyArgsMappingRules(toolName, args, rules) {
214267
214367
  unsetByPath(out, segments);
214268
214368
  continue;
214269
214369
  }
214370
+ if (rule.valueType === EArgsMappingValueType.SYSTEM_VARIABLE) {
214371
+ if (rule.value !== "${userId}" || segments.length === 0) {
214372
+ throw new McpInvocationError("MCP_SYSTEM_VARIABLE_INVALID", "\u7CFB\u7EDF\u53D8\u91CF\u914D\u7F6E\u65E0\u6548");
214373
+ }
214374
+ setByPath(out, segments, USER_ID);
214375
+ continue;
214376
+ }
214270
214377
  if (rule.valueType === EArgsMappingValueType.CONST) {
214271
214378
  setByPath(out, segments, rule.value);
214272
214379
  continue;
@@ -214278,14 +214385,83 @@ function applyArgsMappingRules(toolName, args, rules) {
214278
214385
  continue;
214279
214386
  }
214280
214387
  }
214281
- return out;
214388
+ const contains = (value) => value === USER_ID || value !== null && typeof value === "object" && Object.values(value).some(contains);
214389
+ const requiresUserId = contains(out);
214390
+ return {
214391
+ requiresUserId,
214392
+ resolve(identity) {
214393
+ if (requiresUserId && !identity?.userId?.trim()) {
214394
+ throw new McpInvocationError("MCP_USER_AUTH_REQUIRED", "\u7CFB\u7EDF\u53D8\u91CF\u9700\u8981\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD");
214395
+ }
214396
+ const visit = (value) => {
214397
+ if (value === USER_ID)
214398
+ return identity.userId;
214399
+ if (Array.isArray(value))
214400
+ return value.map(visit);
214401
+ if (value !== null && typeof value === "object") {
214402
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
214403
+ }
214404
+ return value;
214405
+ };
214406
+ return visit(out);
214407
+ }
214408
+ };
214409
+ }
214410
+ function resolveArgsMappingPlan(plan, identity) {
214411
+ return plan.resolve(identity);
214282
214412
  }
214283
214413
 
214284
214414
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/index.js
214285
214415
  init_esm();
214286
214416
 
214287
214417
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/remoteGatewayMcpServer.js
214288
- var import_node_async_hooks = require("node:async_hooks");
214418
+ var import_node_async_hooks2 = require("node:async_hooks");
214419
+
214420
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/linkquegwTokenVerifier.js
214421
+ init_config();
214422
+ function assertMcpUserAuthorization(authorization) {
214423
+ if (!/^Bearer\s+\S+$/i.test(authorization.trim())) {
214424
+ throw new McpInvocationError("MCP_USER_AUTH_REQUIRED", "\u7CFB\u7EDF\u53D8\u91CF\u9700\u8981\u7528\u6237 Bearer \u51ED\u636E");
214425
+ }
214426
+ }
214427
+ var LinkquegwTokenVerifier = class {
214428
+ options;
214429
+ constructor(options = {}) {
214430
+ this.options = options;
214431
+ }
214432
+ async verify(input) {
214433
+ input.signal?.throwIfAborted();
214434
+ assertMcpUserAuthorization(input.authorization);
214435
+ try {
214436
+ const response = await (this.options.fetchImpl ?? globalThis.fetch)(this.options.endpoint ?? RUNTIME_CONFIG_DEFAULTS.LINKQUEGW_TOKEN_VERIFY_ENDPOINT, {
214437
+ method: "POST",
214438
+ headers: {
214439
+ authorization: input.authorization,
214440
+ "content-type": "application/json"
214441
+ },
214442
+ body: JSON.stringify({ agentId: input.agentId }),
214443
+ signal: input.signal
214444
+ });
214445
+ if (!response.ok)
214446
+ throw new Error("\u6821\u9A8C\u8BF7\u6C42\u5931\u8D25");
214447
+ const result = await response.json();
214448
+ input.signal?.throwIfAborted();
214449
+ if (result?.success !== true || typeof result.data?.userId !== "string" || !result.data.userId.trim() || typeof result.data.agentId !== "string" || !result.data.agentId.trim()) {
214450
+ throw new Error("\u8EAB\u4EFD\u54CD\u5E94\u65E0\u6548");
214451
+ }
214452
+ if (result.data.agentId !== input.agentId)
214453
+ throw new McpInvocationError("MCP_IDENTITY_MISMATCH", "\u7528\u6237\u51ED\u636E\u4E0D\u5C5E\u4E8E\u76EE\u6807 Agent");
214454
+ return { userId: result.data.userId, agentId: result.data.agentId };
214455
+ } catch (error40) {
214456
+ input.signal?.throwIfAborted();
214457
+ if (error40 instanceof McpInvocationError)
214458
+ throw error40;
214459
+ throw new McpInvocationError("MCP_TOKEN_VERIFY_FAILED", "\u7528\u6237\u51ED\u636E\u6821\u9A8C\u5931\u8D25");
214460
+ }
214461
+ }
214462
+ };
214463
+
214464
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/remoteGatewayMcpServer.js
214289
214465
  init_types();
214290
214466
  init_logFailure();
214291
214467
  var defaultCreateSigner = (config2, getAuthorizationHeader, debugLog) => new RemoteSignatureSigner({
@@ -214297,6 +214473,8 @@ var defaultCreateSigner = (config2, getAuthorizationHeader, debugLog) => new Rem
214297
214473
  });
214298
214474
  var defaultCreateClient = () => new Client({ name: "linkque-agent-runtime-mcp-client", version: "1.0.0" });
214299
214475
  var RemoteGatewayMcpServerProvider = class {
214476
+ invocationContext = new McpInvocationContext();
214477
+ createTokenVerifier;
214300
214478
  resolveConfig;
214301
214479
  getAuthorizationHeader;
214302
214480
  createSigner;
@@ -214305,6 +214483,7 @@ var RemoteGatewayMcpServerProvider = class {
214305
214483
  debugLog;
214306
214484
  constructor(options) {
214307
214485
  this.resolveConfig = options.resolveConfig;
214486
+ this.createTokenVerifier = options.createTokenVerifier ?? ((config2) => new LinkquegwTokenVerifier({ endpoint: config2.verifyTokenEndpoint }));
214308
214487
  this.getAuthorizationHeader = options.getAuthorizationHeader;
214309
214488
  this.createSigner = options.createSigner ?? ((config2, getAuthorizationHeader) => defaultCreateSigner(config2, getAuthorizationHeader, this.debugLog));
214310
214489
  this.createClient = options.createClient ?? defaultCreateClient;
@@ -214317,9 +214496,13 @@ var RemoteGatewayMcpServerProvider = class {
214317
214496
  /** 连单个远端 server 并包装成 IMcpServer。建连失败有限重试 + 失败清理由 helper 负责。 */
214318
214497
  async connectOne(resource) {
214319
214498
  const config2 = await this.resolveConfig(resource);
214320
- const callHeaders = new import_node_async_hooks.AsyncLocalStorage();
214499
+ const timeoutMs = config2.requestTimeoutMs ?? 18e4;
214500
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
214501
+ throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
214502
+ const verifier = this.createTokenVerifier(config2);
214503
+ const callHeaders = new import_node_async_hooks2.AsyncLocalStorage();
214321
214504
  const { client } = await connectMcpClientWithRetry(config2, {
214322
- createTransport: () => createSseTransport(config2, this.createSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore()),
214505
+ createTransport: () => createSseTransport(config2, this.createSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
214323
214506
  createClient: () => this.createClient()
214324
214507
  });
214325
214508
  const serverName = resource.config.serverName ?? resource.resourceId;
@@ -214331,7 +214514,7 @@ var RemoteGatewayMcpServerProvider = class {
214331
214514
  if (!this.debugLog)
214332
214515
  return;
214333
214516
  try {
214334
- this.debugLog(`[mcp-client] ${JSON.stringify({ serverName, resourceId: resource.resourceId, requestId, method, phase, payload })}`, EDebugLogScope.MCP);
214517
+ this.debugLog(`[mcp-client] ${JSON.stringify({ serverName, resourceId: resource.resourceId, requestId, method, phase, payload: this.invocationContext.current()?.auth ? { redacted: true } : payload })}`, EDebugLogScope.MCP);
214335
214518
  } catch (error40) {
214336
214519
  warnLogFailure("remoteGatewayMcpServer.log", error40);
214337
214520
  }
@@ -214348,16 +214531,52 @@ var RemoteGatewayMcpServerProvider = class {
214348
214531
  };
214349
214532
  const loggedClient = {
214350
214533
  listTools: () => request("tools/list", {}, () => client.listTools()),
214351
- callTool: (params) => request("tools/call", params, () => client.callTool(params))
214352
- };
214534
+ callTool: (params, resultSchema, requestOptions) => request("tools/call", params, () => client.callTool(params, resultSchema, requestOptions))
214535
+ };
214536
+ const callTool = (name, args, signal, options) => callHeaders.run(options?.headers ?? {}, () => this.invocationContext.run(timeoutMs, signal, async (invocation) => {
214537
+ const plan = createArgsMappingPlan(name, args, argsMappingRules);
214538
+ if (plan.requiresUserId) {
214539
+ if (config2.signEndpoint !== void 0 && config2.signEndpoint !== DEFAULT_SIGN_ENDPOINT && !config2.verifyTokenEndpoint?.trim())
214540
+ throw new McpInvocationError("MCP_CONFIG_INVALID", "\u81EA\u5B9A\u4E49\u7B7E\u540D\u7AEF\u70B9\u5FC5\u987B\u540C\u65F6\u914D\u7F6E\u7528\u6237\u51ED\u636E\u6821\u9A8C\u7AEF\u70B9");
214541
+ if (!this.getAuthorizationHeader)
214542
+ throw new McpInvocationError("MCP_USER_AUTH_REQUIRED", "\u7CFB\u7EDF\u53D8\u91CF\u9700\u8981\u7528\u6237\u51ED\u636E");
214543
+ const authorization = await waitForMcpOperation(() => this.getAuthorizationHeader(), invocation.signal);
214544
+ assertMcpUserAuthorization(authorization);
214545
+ const identity = await waitForMcpOperation(() => verifier.verify({
214546
+ authorization,
214547
+ agentId: config2.agentId,
214548
+ signal: invocation.signal
214549
+ }), invocation.signal);
214550
+ if (!identity.userId?.trim() || identity.agentId !== config2.agentId)
214551
+ throw new McpInvocationError("MCP_IDENTITY_MISMATCH", "\u6821\u9A8C\u8EAB\u4EFD\u65E0\u6548");
214552
+ invocation.auth = {
214553
+ authorization,
214554
+ userId: identity.userId,
214555
+ agentId: identity.agentId
214556
+ };
214557
+ }
214558
+ const mapped = resolveArgsMappingPlan(plan, invocation.auth);
214559
+ invocation.signal.throwIfAborted();
214560
+ const remaining = Math.max(1, invocation.deadline - performance.now());
214561
+ try {
214562
+ return await loggedClient.callTool({ name, arguments: mapped }, void 0, {
214563
+ signal: invocation.signal,
214564
+ timeout: remaining,
214565
+ maxTotalTimeout: remaining,
214566
+ resetTimeoutOnProgress: false
214567
+ });
214568
+ } catch (error40) {
214569
+ invocation.signal.throwIfAborted();
214570
+ if (invocation.auth && !(error40 instanceof McpInvocationError))
214571
+ throw new Error("MCP \u7528\u6237\u5DE5\u5177\u8C03\u7528\u5931\u8D25");
214572
+ throw error40;
214573
+ }
214574
+ }));
214353
214575
  return {
214354
214576
  resourceId: resource.resourceId,
214355
214577
  serverName,
214356
- listTools: () => listToolsFromClient(loggedClient, resource.resourceId),
214357
- callTool: (name, args, _signal, options) => {
214358
- const mapped = applyArgsMappingRules(name, args, argsMappingRules);
214359
- return callHeaders.run(options?.headers ?? {}, () => loggedClient.callTool({ name, arguments: mapped ?? {} }));
214360
- },
214578
+ listTools: () => listToolsFromClient(loggedClient, resource.resourceId, callTool),
214579
+ callTool,
214361
214580
  close: async () => {
214362
214581
  try {
214363
214582
  await client.close();
@@ -214367,14 +214586,14 @@ var RemoteGatewayMcpServerProvider = class {
214367
214586
  };
214368
214587
  }
214369
214588
  };
214370
- async function listToolsFromClient(client, resourceId) {
214589
+ async function listToolsFromClient(client, resourceId, callTool) {
214371
214590
  const result = await client.listTools();
214372
214591
  const tools = result.tools ?? [];
214373
214592
  return tools.map((tool) => {
214374
214593
  const descriptor = {
214375
214594
  name: tool.name,
214376
214595
  resourceId,
214377
- execute: (args) => client.callTool({ name: tool.name, arguments: args })
214596
+ execute: (args, signal) => callTool(tool.name, args, signal)
214378
214597
  };
214379
214598
  if (tool.description !== void 0)
214380
214599
  descriptor.description = tool.description;
@@ -215610,7 +215829,7 @@ init_noopRuntimeTelemetry();
215610
215829
  // ../linkque-agent-runtime/dist/esm/impl/telemetry/identityQueue.js
215611
215830
  init_telemetry();
215612
215831
  init_telemetryEnums2();
215613
- var import_node_async_hooks2 = require("node:async_hooks");
215832
+ var import_node_async_hooks3 = require("node:async_hooks");
215614
215833
  init_esm6();
215615
215834
  var import_core11 = __toESM(require_src(), 1);
215616
215835
  function authorizationKey(auth2) {
@@ -215624,7 +215843,7 @@ function authorizationKey(auth2) {
215624
215843
  }
215625
215844
  var IdentityQueue = class {
215626
215845
  options;
215627
- exportContext = new import_node_async_hooks2.AsyncLocalStorage();
215846
+ exportContext = new import_node_async_hooks3.AsyncLocalStorage();
215628
215847
  get isExporting() {
215629
215848
  return this.exportContext.getStore() === true;
215630
215849
  }
@@ -217001,6 +217220,7 @@ function createMcpConfigResolver(options) {
217001
217220
  sseEndpoint: `api/v1/open/mcps/${resolveServerName(resource.config)}/sse`,
217002
217221
  agentId: options.agentId,
217003
217222
  ...options.signEndpoint ? { signEndpoint: options.signEndpoint } : {},
217223
+ ...options.verifyTokenEndpoint ? { verifyTokenEndpoint: options.verifyTokenEndpoint } : {},
217004
217224
  ...options.requestTimeoutMs ? { requestTimeoutMs: options.requestTimeoutMs } : {}
217005
217225
  });
217006
217226
  }
@@ -217096,6 +217316,7 @@ var AGENT_ENV_SNAPSHOT = [
217096
217316
  ["LINKQUE_BASE_URL", false],
217097
217317
  ["LINKQUE_OPEN_MCP_BASE_URL", false],
217098
217318
  ["LINKQUE_MCP_SIGN_ENDPOINT", false],
217319
+ ["LINKQUEGW_TOKEN_VERIFY_ENDPOINT", false],
217099
217320
  ["LINKQUE_AGENT_MCP_FIXTURE_URL", false]
217100
217321
  ];
217101
217322
  var formatEnvSnapshot = (env2) => {
@@ -217405,7 +217626,9 @@ var main = async () => {
217405
217626
  const resolveConfig = createMcpConfigResolver({
217406
217627
  agentId: protocol.agentId,
217407
217628
  remoteBaseUrl: config2.get("LINKQUE_OPEN_MCP_BASE_URL"),
217408
- signEndpoint: config2.get("LINKQUE_MCP_SIGN_ENDPOINT")
217629
+ signEndpoint: config2.get("LINKQUE_MCP_SIGN_ENDPOINT"),
217630
+ // 保留未显式配置的状态,由运行时检查自定义环境配置是否完整。
217631
+ verifyTokenEndpoint: config2.getRaw("LINKQUEGW_TOKEN_VERIFY_ENDPOINT")?.trim() || void 0
217409
217632
  });
217410
217633
  return new RemoteGatewayMcpServerProvider({
217411
217634
  resolveConfig,