linkque-cli-v2 1.4.6 → 1.5.0

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.
@@ -22683,6 +22683,7 @@ var EHookExecutorName;
22683
22683
  EHookExecutorName2["LinkquegwEventHookExecutor"] = "LinkquegwEventHookExecutor";
22684
22684
  EHookExecutorName2["SecurityAnswerHookExecutor"] = "SecurityAnswerHookExecutor";
22685
22685
  EHookExecutorName2["ImageUnderstandingHookExecutor"] = "ImageUnderstandingHookExecutor";
22686
+ EHookExecutorName2["McpDiscoveryHookExecutor"] = "McpDiscoveryHookExecutor";
22686
22687
  })(EHookExecutorName || (EHookExecutorName = {}));
22687
22688
 
22688
22689
  // ../linkque-agent-runtime/dist/esm/core/followUpQuestions.js
@@ -26163,6 +26164,7 @@ var ETelemetryEventPrefix;
26163
26164
  ETelemetryEventPrefix2["ADVANCE"] = "harness.advance";
26164
26165
  ETelemetryEventPrefix2["MODEL_INVOKE"] = "harness.model.invoke";
26165
26166
  ETelemetryEventPrefix2["MODEL_ATTEMPT"] = "harness.model.attempt";
26167
+ ETelemetryEventPrefix2["MODEL_REASONING"] = "harness.model.reasoning";
26166
26168
  ETelemetryEventPrefix2["TOOL_INVOKE"] = "harness.tool.invoke";
26167
26169
  ETelemetryEventPrefix2["TOOL_ATTEMPT"] = "harness.tool.attempt";
26168
26170
  ETelemetryEventPrefix2["HOOK_CHAIN"] = "harness.hook.chain";
@@ -26204,6 +26206,8 @@ var ETelemetryEventName;
26204
26206
  ETelemetryEventName2["MODEL_INVOKE_FINISHED"] = "harness.model.invoke.finished";
26205
26207
  ETelemetryEventName2["MODEL_ATTEMPT_STARTED"] = "harness.model.attempt.started";
26206
26208
  ETelemetryEventName2["MODEL_ATTEMPT_FINISHED"] = "harness.model.attempt.finished";
26209
+ ETelemetryEventName2["MODEL_REASONING_STARTED"] = "harness.model.reasoning.started";
26210
+ ETelemetryEventName2["MODEL_REASONING_FINISHED"] = "harness.model.reasoning.finished";
26207
26211
  ETelemetryEventName2["TOOL_INVOKE_STARTED"] = "harness.tool.invoke.started";
26208
26212
  ETelemetryEventName2["TOOL_INVOKE_FINISHED"] = "harness.tool.invoke.finished";
26209
26213
  ETelemetryEventName2["TOOL_ATTEMPT_STARTED"] = "harness.tool.attempt.started";
@@ -26226,7 +26230,12 @@ var ETelemetryEventName;
26226
26230
  var ETelemetryContentSection;
26227
26231
  (function(ETelemetryContentSection2) {
26228
26232
  ETelemetryContentSection2["QUERY_INPUT"] = "query.input";
26233
+ ETelemetryContentSection2["MODEL_INPUT_DIGEST"] = "model.input.digest";
26234
+ ETelemetryContentSection2["MODEL_OUT_RAW"] = "model.out.raw";
26229
26235
  ETelemetryContentSection2["MODEL_OUTPUT"] = "model.output";
26236
+ ETelemetryContentSection2["MODEL_REASONING"] = "model.reasoning";
26237
+ ETelemetryContentSection2["FOLLOW_UP_QUESTION_INPUT"] = "follow_up_question.input";
26238
+ ETelemetryContentSection2["FOLLOW_UP_QUESTION_OUTPUT"] = "follow_up_question.output";
26230
26239
  ETelemetryContentSection2["MCP_ACTION_OUTPUT"] = "mcp_action.output";
26231
26240
  ETelemetryContentSection2["TOOL_INPUT"] = "tool.input";
26232
26241
  ETelemetryContentSection2["TOOL_OUTPUT"] = "tool.output";
@@ -26245,6 +26254,7 @@ var ETelemetryOperationName;
26245
26254
  ETelemetryOperationName2["ADVANCE"] = "harness.advance";
26246
26255
  ETelemetryOperationName2["MODEL_INVOKE"] = "harness.model.invoke";
26247
26256
  ETelemetryOperationName2["MODEL_ATTEMPT"] = "harness.model.attempt";
26257
+ ETelemetryOperationName2["MODEL_REASONING"] = "harness.model.reasoning";
26248
26258
  ETelemetryOperationName2["TOOL_ATTEMPT"] = "harness.tool.attempt";
26249
26259
  ETelemetryOperationName2["HOOK_CHAIN"] = "harness.hook.chain";
26250
26260
  ETelemetryOperationName2["MIDDLEWARE"] = "harness.middleware";
@@ -26380,6 +26390,7 @@ var ETelemetryTerminalSource;
26380
26390
  var ETelemetryModelPurpose;
26381
26391
  (function(ETelemetryModelPurpose2) {
26382
26392
  ETelemetryModelPurpose2["AGENT_LOOP"] = "agent_loop";
26393
+ ETelemetryModelPurpose2["FOLLOW_UP_QUESTION"] = "follow_up_question";
26383
26394
  })(ETelemetryModelPurpose || (ETelemetryModelPurpose = {}));
26384
26395
  var ETelemetryErrorType;
26385
26396
  (function(ETelemetryErrorType2) {
@@ -26436,11 +26447,143 @@ function recordMcpContentSection(observation, section, value, schema) {
26436
26447
  });
26437
26448
  }
26438
26449
 
26450
+ // ../linkque-agent-runtime/dist/esm/core/abort.js
26451
+ function waitWithSignal(operation, signal) {
26452
+ if (typeof operation === "function") {
26453
+ if (signal?.aborted)
26454
+ return Promise.reject(signal.reason);
26455
+ try {
26456
+ return waitForPromise(operation(signal), signal);
26457
+ } catch (error) {
26458
+ return Promise.reject(error);
26459
+ }
26460
+ }
26461
+ return waitForPromise(operation, signal);
26462
+ }
26463
+ function waitForPromise(operation, signal) {
26464
+ if (!signal)
26465
+ return operation;
26466
+ return new Promise((resolve, reject) => {
26467
+ const abort = () => {
26468
+ signal.removeEventListener("abort", abort);
26469
+ reject(signal.reason);
26470
+ };
26471
+ signal.addEventListener("abort", abort, { once: true });
26472
+ operation.then((value) => {
26473
+ signal.removeEventListener("abort", abort);
26474
+ resolve(value);
26475
+ }, (error) => {
26476
+ signal.removeEventListener("abort", abort);
26477
+ reject(error);
26478
+ });
26479
+ if (signal.aborted)
26480
+ abort();
26481
+ });
26482
+ }
26483
+
26484
+ // ../linkque-agent-runtime/dist/esm/core/cancellationScope.js
26485
+ var MAX_TIMER_DELAY_MS = 2147483647;
26486
+ var CancellationScope = class {
26487
+ controller = new AbortController();
26488
+ listeners = [];
26489
+ timeoutReason;
26490
+ parent;
26491
+ ref;
26492
+ timer;
26493
+ disposed = false;
26494
+ context;
26495
+ constructor(options = {}) {
26496
+ const { parent, signals = [], timeoutMs } = options;
26497
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0))
26498
+ throw new Error("\u53D6\u6D88\u4F5C\u7528\u57DF timeoutMs \u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
26499
+ this.parent = parent;
26500
+ this.ref = options.ref ?? true;
26501
+ this.timeoutReason = options.timeoutReason ?? new DOMException("\u64CD\u4F5C\u8D85\u65F6", "TimeoutError");
26502
+ const ownDeadline = timeoutMs === void 0 ? void 0 : performance.now() + timeoutMs;
26503
+ const deadline = ownDeadline === void 0 ? parent?.deadline : parent?.deadline === void 0 ? ownDeadline : Math.min(ownDeadline, parent.deadline);
26504
+ this.context = {
26505
+ signal: this.controller.signal,
26506
+ deadline,
26507
+ remainingMs: () => deadline === void 0 ? Infinity : Math.max(0, deadline - performance.now()),
26508
+ throwIfAborted: () => {
26509
+ this.controller.signal.throwIfAborted();
26510
+ if (deadline !== void 0 && performance.now() >= deadline) {
26511
+ try {
26512
+ parent?.throwIfAborted();
26513
+ } catch {
26514
+ }
26515
+ if (parent?.signal.aborted)
26516
+ this.cancel(parent.signal.reason);
26517
+ else
26518
+ this.cancel(this.timeoutReason);
26519
+ }
26520
+ this.controller.signal.throwIfAborted();
26521
+ }
26522
+ };
26523
+ for (const source of [parent?.signal, ...signals]) {
26524
+ if (!source)
26525
+ continue;
26526
+ if (source.aborted) {
26527
+ this.cancel(source.reason);
26528
+ break;
26529
+ }
26530
+ const forward = () => this.cancel(source.reason);
26531
+ source.addEventListener("abort", forward, { once: true });
26532
+ this.listeners.push(() => source.removeEventListener("abort", forward));
26533
+ }
26534
+ if (!this.controller.signal.aborted && deadline !== void 0)
26535
+ this.armTimer(deadline);
26536
+ }
26537
+ cancel(reason = new DOMException("\u64CD\u4F5C\u5DF2\u53D6\u6D88", "AbortError")) {
26538
+ if (this.disposed || this.controller.signal.aborted)
26539
+ return;
26540
+ this.controller.abort(reason);
26541
+ this.release();
26542
+ }
26543
+ dispose() {
26544
+ if (this.disposed)
26545
+ return;
26546
+ this.disposed = true;
26547
+ this.release();
26548
+ }
26549
+ armTimer(deadline) {
26550
+ if (this.timer !== void 0)
26551
+ clearTimeout(this.timer);
26552
+ const remaining = deadline - performance.now();
26553
+ if (remaining <= 0) {
26554
+ try {
26555
+ this.parent?.throwIfAborted();
26556
+ } catch {
26557
+ }
26558
+ if (this.parent?.signal.aborted)
26559
+ this.cancel(this.parent.signal.reason);
26560
+ else
26561
+ this.cancel(this.timeoutReason);
26562
+ return;
26563
+ }
26564
+ this.timer = setTimeout(() => {
26565
+ this.timer = void 0;
26566
+ this.armTimer(deadline);
26567
+ }, Math.min(remaining, MAX_TIMER_DELAY_MS));
26568
+ if (!this.ref)
26569
+ this.timer.unref?.();
26570
+ }
26571
+ release() {
26572
+ if (this.timer !== void 0)
26573
+ clearTimeout(this.timer);
26574
+ this.timer = void 0;
26575
+ for (const remove of this.listeners.splice(0))
26576
+ remove();
26577
+ }
26578
+ };
26579
+
26439
26580
  // ../linkque-agent-runtime/dist/esm/core/mcpProxyTool.js
26440
26581
  var MCP_PROXY_TOOL_NAME = "mcp";
26441
26582
  var McpProxyTool = class {
26442
26583
  provider;
26443
26584
  /** serverName → 缓存条目(同 serverName 多 resourceId 聚合为一个连接)。 */
26585
+ lifetime;
26586
+ closing = /* @__PURE__ */ new WeakMap();
26444
26587
  entries = /* @__PURE__ */ new Map();
26445
26588
  /** 进行中的连接(去重并发 ensureEntry)。 */
26446
26589
  inFlight = /* @__PURE__ */ new Map();
@@ -26452,6 +26595,9 @@ var McpProxyTool = class {
26452
26595
  authorizeCall;
26453
26596
  constructor(provider, specs, options = {}) {
26454
26597
  this.provider = provider;
26598
+ this.lifetime = new CancellationScope({
26599
+ signals: options.signal ? [options.signal] : []
26600
+ });
26455
26601
  this.specs = specs;
26456
26602
  this.specByServerName = new Map(specs.map((spec) => [spec.serverName, spec]));
26457
26603
  this.specByResourceId = new Map(specs.flatMap((spec) => spec.resourceIds.map((id) => [id, spec])));
@@ -26505,40 +26651,121 @@ var McpProxyTool = class {
26505
26651
  }
26506
26652
  };
26507
26653
  }
26508
- /** 关闭所有已连 server(忽略单 server 关闭错误)。 */
26509
- async closeAll() {
26510
- await Promise.all([...this.entries.values()].map(async (entry) => {
26511
- if (!entry.server)
26512
- return;
26654
+ /** 并发发现所有 server;每个 server 独立限时,失败结果不阻断其他目录。 */
26655
+ async discover(signal) {
26656
+ signal?.throwIfAborted();
26657
+ const results = await Promise.all(this.specs.map(async (spec) => {
26658
+ const scope = new CancellationScope({
26659
+ parent: this.lifetime.context,
26660
+ signals: signal ? [signal] : [],
26661
+ timeoutMs: 5e3,
26662
+ timeoutReason: new DOMException("MCP \u76EE\u5F55\u9884\u52A0\u8F7D\u8D85\u65F6", "TimeoutError")
26663
+ });
26513
26664
  try {
26514
- await entry.server.close?.();
26665
+ const entry = await this.ensureEntry(spec.serverName, scope.context.signal);
26666
+ return {
26667
+ serverName: spec.serverName,
26668
+ status: entry ? "connected" : "failed",
26669
+ tools: (entry?.tools ?? []).map(({ name, description }) => {
26670
+ const metadata = { name };
26671
+ if (description !== void 0)
26672
+ metadata.description = description;
26673
+ return metadata;
26674
+ })
26675
+ };
26515
26676
  } catch (error) {
26516
- try {
26517
- this.debugLog(`[mcp] server ${entry.server.serverName} close failed: ${error instanceof Error ? error.message : "unknown error"}`, EDebugLogScope.MCP);
26518
- } catch {
26677
+ if (signal?.aborted || this.lifetime.context.signal.aborted)
26678
+ throw error;
26679
+ if (scope.context.signal.aborted) {
26680
+ return {
26681
+ serverName: spec.serverName,
26682
+ status: "failed",
26683
+ tools: []
26684
+ };
26519
26685
  }
26686
+ throw error;
26687
+ } finally {
26688
+ scope.dispose();
26520
26689
  }
26521
26690
  }));
26691
+ signal?.throwIfAborted();
26692
+ this.lifetime.context.throwIfAborted();
26693
+ return results;
26694
+ }
26695
+ /** 关闭缓存连接并取消在途连接;忽略取消的 provider 返回后也会立即清理。 */
26696
+ async closeAll() {
26697
+ this.lifetime.cancel(new DOMException("MCP Run \u5DF2\u7ED3\u675F", "AbortError"));
26698
+ for (const attempt of this.inFlight.values()) {
26699
+ attempt.abandoned = true;
26700
+ attempt.scope.cancel(this.lifetime.context.signal.reason);
26701
+ }
26702
+ this.inFlight.clear();
26703
+ await Promise.all([...this.entries.values()].map((entry) => entry.server ? this.closeServer(entry.server) : Promise.resolve()));
26704
+ this.entries.clear();
26705
+ this.lifetime.dispose();
26706
+ }
26707
+ /** 单个连接只关闭一次,诊断失败不得影响资源清理。 */
26708
+ closeServer(server) {
26709
+ const existing = this.closing.get(server);
26710
+ if (existing)
26711
+ return existing;
26712
+ const closing = Promise.resolve().then(() => server.close?.()).then(() => void 0).catch((error) => {
26713
+ this.log(`[mcp] server ${server.serverName} close failed: ${String(error)}`);
26714
+ });
26715
+ this.closing.set(server, closing);
26716
+ return closing;
26717
+ }
26718
+ log(message) {
26719
+ try {
26720
+ this.debugLog(message, EDebugLogScope.MCP);
26721
+ } catch {
26722
+ }
26522
26723
  }
26523
26724
  // —— 内部:连接与缓存 ——
26524
26725
  /** 确保某 server 已连;返回 connected 条目,依失败返回 null(不抛错)。 */
26525
26726
  async ensureEntry(serverName, signal) {
26727
+ this.lifetime.context.throwIfAborted();
26728
+ signal?.throwIfAborted();
26526
26729
  const existing = this.entries.get(serverName);
26527
26730
  if (existing) {
26528
26731
  return existing.status === "connected" ? existing : null;
26529
26732
  }
26530
- let promise = this.inFlight.get(serverName);
26531
- if (!promise) {
26532
- promise = this.connect(serverName, signal).finally(() => {
26533
- this.inFlight.delete(serverName);
26733
+ let attempt = this.inFlight.get(serverName);
26734
+ if (!attempt) {
26735
+ const scope = new CancellationScope({ parent: this.lifetime.context });
26736
+ attempt = {
26737
+ promise: Promise.resolve({}),
26738
+ scope,
26739
+ waiters: 0,
26740
+ settled: false,
26741
+ abandoned: false
26742
+ };
26743
+ const current = attempt;
26744
+ this.inFlight.set(serverName, current);
26745
+ current.promise = this.connect(serverName, scope.context.signal, current).finally(() => {
26746
+ current.settled = true;
26747
+ if (this.inFlight.get(serverName) === current)
26748
+ this.inFlight.delete(serverName);
26749
+ scope.dispose();
26534
26750
  });
26535
- this.inFlight.set(serverName, promise);
26536
26751
  }
26537
- const entry = await promise;
26538
- return entry.status === "connected" ? entry : null;
26752
+ attempt.waiters += 1;
26753
+ try {
26754
+ const entry = await waitWithSignal(attempt.promise, signal);
26755
+ return entry.status === "connected" ? entry : null;
26756
+ } finally {
26757
+ attempt.waiters -= 1;
26758
+ if (attempt.waiters === 0 && !attempt.settled) {
26759
+ attempt.abandoned = true;
26760
+ if (this.inFlight.get(serverName) === attempt)
26761
+ this.inFlight.delete(serverName);
26762
+ attempt.scope.cancel(new DOMException("MCP \u5EFA\u8FDE\u5DF2\u65E0\u7B49\u5F85\u8005", "AbortError"));
26763
+ }
26764
+ }
26539
26765
  }
26540
26766
  /** 连单个 server 并 listTools;按 spec.allowedTools 过滤后缓存;失败记为 failed。 */
26541
- async connect(serverName, _signal) {
26767
+ async connect(serverName, signal, attempt) {
26768
+ const isCurrent = () => !attempt.abandoned && this.inFlight.get(serverName) === attempt && !this.lifetime.context.signal.aborted;
26542
26769
  const spec = this.specByServerName.get(serverName);
26543
26770
  if (!spec) {
26544
26771
  const entry = {
@@ -26547,11 +26774,19 @@ var McpProxyTool = class {
26547
26774
  status: "failed",
26548
26775
  error: `unknown serverName: ${serverName}`
26549
26776
  };
26550
- this.entries.set(serverName, entry);
26777
+ if (isCurrent())
26778
+ this.entries.set(serverName, entry);
26551
26779
  this.debugLog(`[mcp] server ${serverName} unknown serverName`, EDebugLogScope.MCP);
26552
26780
  return entry;
26553
26781
  }
26782
+ let server;
26783
+ const onAbort = () => {
26784
+ if (server)
26785
+ void this.closeServer(server);
26786
+ };
26787
+ signal.addEventListener("abort", onAbort, { once: true });
26554
26788
  try {
26789
+ signal.throwIfAborted();
26555
26790
  const synthetic = {
26556
26791
  resourceId: spec.serverName,
26557
26792
  resourceType: EResourceType.MCP,
@@ -26563,18 +26798,35 @@ var McpProxyTool = class {
26563
26798
  argsMappingRules: spec.argsMappingRules
26564
26799
  }
26565
26800
  };
26566
- const servers = await this.provider.servers([synthetic]);
26567
- const server = servers[0];
26801
+ const pending = this.provider.servers([synthetic], signal).then((servers2) => {
26802
+ server = servers2[0];
26803
+ if (signal.aborted) {
26804
+ for (const item of servers2)
26805
+ void this.closeServer(item);
26806
+ signal.throwIfAborted();
26807
+ }
26808
+ return servers2;
26809
+ });
26810
+ const servers = await waitWithSignal(pending, signal);
26811
+ server = servers[0];
26568
26812
  if (!server) {
26569
26813
  throw new Error(`provider returned no server for ${spec.serverName}`);
26570
26814
  }
26571
- const all = await server.listTools();
26815
+ const all = await waitWithSignal(server.listTools(signal), signal);
26816
+ signal.throwIfAborted();
26572
26817
  const tools = spec.allowedTools ? all.filter((tool) => spec.allowedTools.has(tool.name)) : all;
26573
26818
  const entry = { server, tools, status: "connected" };
26819
+ if (!isCurrent()) {
26820
+ void this.closeServer(server);
26821
+ signal.throwIfAborted();
26822
+ return { server: null, tools: [], status: "failed" };
26823
+ }
26574
26824
  this.entries.set(serverName, entry);
26575
- this.debugLog(`[mcp] server ${spec.serverName} connected (${tools.length}/${all.length} tools)`, EDebugLogScope.MCP);
26825
+ this.log(`[mcp] server ${spec.serverName} connected (${tools.length}/${all.length} tools)`);
26576
26826
  return entry;
26577
26827
  } catch (error) {
26828
+ if (server)
26829
+ void this.closeServer(server);
26578
26830
  const message = error instanceof Error ? error.message : String(error);
26579
26831
  const entry = {
26580
26832
  server: null,
@@ -26582,9 +26834,12 @@ var McpProxyTool = class {
26582
26834
  status: "failed",
26583
26835
  error: message
26584
26836
  };
26585
- this.entries.set(serverName, entry);
26586
- this.debugLog(`[mcp] server ${spec.serverName} connect failed: ${message}`, EDebugLogScope.MCP);
26837
+ if (isCurrent())
26838
+ this.entries.set(serverName, entry);
26839
+ this.log(`[mcp] server ${spec.serverName} connect failed: ${message}`);
26587
26840
  return entry;
26841
+ } finally {
26842
+ signal.removeEventListener("abort", onAbort);
26588
26843
  }
26589
26844
  }
26590
26845
  // —— 派发 ——
@@ -26657,7 +26912,12 @@ ${lines.join("\n")}${hint}`.trim();
26657
26912
  this.recordAction(context2, "connect", "not_found", { server });
26658
26913
  return `Server "${server}" not found. Use mcp({}) to see available servers.`;
26659
26914
  }
26660
- this.entries.delete(spec.serverName);
26915
+ if (!this.inFlight.has(spec.serverName)) {
26916
+ const previous = this.entries.get(spec.serverName);
26917
+ this.entries.delete(spec.serverName);
26918
+ if (previous?.server)
26919
+ await this.closeServer(previous.server);
26920
+ }
26661
26921
  const entry = await this.ensureEntry(spec.serverName, signal);
26662
26922
  if (!entry) {
26663
26923
  this.recordAction(context2, "connect", "failed", {
@@ -27649,7 +27909,7 @@ function buildHookContextBase(resource, stage, commonParams, eventId, timestamp)
27649
27909
  // ../linkque-agent-runtime/dist/esm/core/hook/hookRegistry.js
27650
27910
  var DEFAULT_HOOK_ORDER = 100;
27651
27911
  var DEFAULT_HOOK_TIMEOUT_MS = 1e3;
27652
- var MAX_HOOK_TIMEOUT_MS = 5e3;
27912
+ var MAX_HOOK_TIMEOUT_MS = 6e3;
27653
27913
  function normalizeHookResources(resources) {
27654
27914
  return resources.filter((resource) => resource.config.enabled !== false).map((resource) => {
27655
27915
  const config = Object.assign({}, resource.config, {
@@ -28043,13 +28303,17 @@ var HookDispatcher = class {
28043
28303
  writeHookLog(this.deps.debugLog, { ...baseRecord, event: "started" });
28044
28304
  let result;
28045
28305
  try {
28046
- const controller = new AbortController();
28047
28306
  const timeoutMs = resource.config.timeoutMs ?? 1e3;
28048
- const executorSignal = runtimeInput?.signal ? AbortSignal.any([controller.signal, runtimeInput.signal]) : controller.signal;
28049
- let timeout;
28307
+ const timeoutReason = new Error(`\u72B6\u6001\u578B Hook ${resource.config.name} \u6267\u884C\u8D85\u65F6(${timeoutMs}ms)`);
28308
+ const scope = new CancellationScope({
28309
+ signals: runtimeInput?.signal ? [runtimeInput.signal] : [],
28310
+ timeoutMs,
28311
+ timeoutReason
28312
+ });
28313
+ const executorSignal = scope.context.signal;
28050
28314
  let onAbort;
28051
28315
  try {
28052
- executorSignal.throwIfAborted();
28316
+ scope.context.throwIfAborted();
28053
28317
  observation = parent?.startOperation({
28054
28318
  name: ETelemetryOperationName.MIDDLEWARE,
28055
28319
  eventPrefix: ETelemetryEventPrefix.MIDDLEWARE,
@@ -28064,57 +28328,46 @@ var HookDispatcher = class {
28064
28328
  detached: false,
28065
28329
  links: []
28066
28330
  });
28067
- const aborted = new Promise((_, reject) => {
28068
- onAbort = () => {
28069
- cancelled = true;
28070
- observation?.record(ETelemetryEventName.HOOK_CANCEL_REQUESTED, {});
28071
- reject(executorSignal.reason instanceof Error ? executorSignal.reason : new Error("\u72B6\u6001\u578B Hook \u6267\u884C\u5DF2\u53D6\u6D88"));
28072
- };
28073
- executorSignal.addEventListener("abort", onAbort, { once: true });
28074
- });
28075
- timeout = setTimeout(() => {
28076
- timedOut = true;
28077
- observation?.record(ETelemetryEventName.HOOK_TIMEOUT_REQUESTED, {});
28078
- controller.abort(new Error(`\u72B6\u6001\u578B Hook ${resource.config.name} \u6267\u884C\u8D85\u65F6(${timeoutMs}ms)`));
28079
- }, timeoutMs);
28080
- result = await Promise.race([
28081
- this.deps.hookExecutor.execute(resource, context2, {
28082
- signal: executorSignal,
28083
- ...runtimeInput === void 0 ? {} : { runtimeInput }
28084
- }).then((value) => {
28085
- settled = true;
28086
- observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
28331
+ onAbort = () => {
28332
+ timedOut = executorSignal.reason === timeoutReason;
28333
+ cancelled = !timedOut;
28334
+ observation?.record(timedOut ? ETelemetryEventName.HOOK_TIMEOUT_REQUESTED : ETelemetryEventName.HOOK_CANCEL_REQUESTED, {});
28335
+ };
28336
+ executorSignal.addEventListener("abort", onAbort, { once: true });
28337
+ result = await waitWithSignal(this.deps.hookExecutor.execute(resource, context2, {
28338
+ signal: executorSignal,
28339
+ ...runtimeInput === void 0 ? {} : { runtimeInput }
28340
+ }).then((value) => {
28341
+ settled = true;
28342
+ observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
28343
+ [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28344
+ [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: value.skipped ? ETelemetryHookResult.SKIPPED : value.ok ? ETelemetryHookResult.SUCCESS : ETelemetryHookResult.ERROR
28345
+ });
28346
+ if (timedOut || cancelled)
28347
+ observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
28348
+ [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
28087
28349
  [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28088
28350
  [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: value.skipped ? ETelemetryHookResult.SKIPPED : value.ok ? ETelemetryHookResult.SUCCESS : ETelemetryHookResult.ERROR
28089
28351
  });
28090
- if (timedOut || cancelled)
28091
- observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
28092
- [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
28093
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28094
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: value.skipped ? ETelemetryHookResult.SKIPPED : value.ok ? ETelemetryHookResult.SUCCESS : ETelemetryHookResult.ERROR
28095
- });
28096
- return value;
28097
- }, (error) => {
28098
- settled = true;
28099
- observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
28352
+ return value;
28353
+ }, (error) => {
28354
+ settled = true;
28355
+ observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
28356
+ [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28357
+ [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: ETelemetryHookResult.ERROR
28358
+ });
28359
+ if (timedOut || cancelled)
28360
+ observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
28361
+ [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
28100
28362
  [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28101
28363
  [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: ETelemetryHookResult.ERROR
28102
28364
  });
28103
- if (timedOut || cancelled)
28104
- observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
28105
- [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
28106
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28107
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: ETelemetryHookResult.ERROR
28108
- });
28109
- throw error;
28110
- }),
28111
- aborted
28112
- ]);
28365
+ throw error;
28366
+ }), executorSignal);
28113
28367
  } finally {
28114
- if (timeout !== void 0)
28115
- clearTimeout(timeout);
28116
28368
  if (onAbort !== void 0)
28117
28369
  executorSignal.removeEventListener("abort", onAbort);
28370
+ scope.dispose();
28118
28371
  }
28119
28372
  } catch (error) {
28120
28373
  if (!settled && (timedOut || cancelled)) {
@@ -28220,16 +28473,21 @@ var SideEffectRunner = class {
28220
28473
  return this.pending.size;
28221
28474
  }
28222
28475
  schedule(task) {
28223
- const controller = new AbortController();
28224
28476
  let timedOut = false;
28225
- const timer = setTimeout(() => {
28226
- timedOut = true;
28227
- controller.abort();
28228
- }, task.timeoutMs);
28229
- timer.unref?.();
28230
- const promise = this.runTask(task, controller.signal, () => timedOut).catch(() => {
28477
+ const timeoutReason = new DOMException("\u65C1\u8DEF Hook \u6267\u884C\u8D85\u65F6", "TimeoutError");
28478
+ const scope = new CancellationScope({
28479
+ timeoutMs: task.timeoutMs,
28480
+ timeoutReason,
28481
+ ref: false
28482
+ });
28483
+ const onAbort = () => {
28484
+ timedOut = scope.context.signal.reason === timeoutReason;
28485
+ };
28486
+ scope.context.signal.addEventListener("abort", onAbort, { once: true });
28487
+ const promise = this.runTask(task, scope.context.signal, () => timedOut).catch(() => {
28231
28488
  }).finally(() => {
28232
- clearTimeout(timer);
28489
+ scope.context.signal.removeEventListener("abort", onAbort);
28490
+ scope.dispose();
28233
28491
  this.pending.delete(promise);
28234
28492
  });
28235
28493
  this.pending.add(promise);
@@ -28253,15 +28511,22 @@ var SideEffectRunner = class {
28253
28511
  traceId: this.attribution.traceId
28254
28512
  }
28255
28513
  });
28256
- let timer;
28257
- const timeout = new Promise((resolve) => {
28258
- timer = setTimeout(() => resolve("timeout"), options.timeoutMs);
28259
- timer.unref?.();
28260
- });
28261
28514
  const settled = Promise.allSettled(this.pending).then(() => "completed");
28262
- const outcome = await Promise.race([settled, timeout]);
28263
- if (timer !== void 0)
28264
- clearTimeout(timer);
28515
+ let outcome = "timeout";
28516
+ if (options.timeoutMs > 0) {
28517
+ const scope = new CancellationScope({
28518
+ timeoutMs: options.timeoutMs,
28519
+ ref: false
28520
+ });
28521
+ try {
28522
+ outcome = await waitWithSignal(settled, scope.context.signal);
28523
+ } catch (error) {
28524
+ if (!scope.context.signal.aborted)
28525
+ throw error;
28526
+ } finally {
28527
+ scope.dispose();
28528
+ }
28529
+ }
28265
28530
  const costMs = this.now() - startedAt;
28266
28531
  const completed = outcome === "completed";
28267
28532
  writeHookLog(this.debugLog, {
@@ -29041,26 +29306,7 @@ function throwIfWebSearchAborted(signal) {
29041
29306
  throw new DOMException("\u5168\u7F51\u641C\u7D22\u5DF2\u53D6\u6D88", "AbortError");
29042
29307
  }
29043
29308
  async function awaitWebSearchOperation(operation, signal) {
29044
- signal?.throwIfAborted();
29045
- if (!signal)
29046
- return operation();
29047
- let onAbort = () => {
29048
- };
29049
- const cancelled = new Promise((_, reject) => {
29050
- onAbort = () => reject(signal.reason);
29051
- signal.addEventListener("abort", onAbort, { once: true });
29052
- });
29053
- try {
29054
- return await Promise.race([
29055
- Promise.resolve().then(() => {
29056
- signal.throwIfAborted();
29057
- return operation();
29058
- }),
29059
- cancelled
29060
- ]);
29061
- } finally {
29062
- signal.removeEventListener("abort", onAbort);
29063
- }
29309
+ return waitWithSignal(operation, signal);
29064
29310
  }
29065
29311
 
29066
29312
  // ../linkque-agent-runtime/dist/esm/core/webSearchResource.js
@@ -33925,26 +34171,52 @@ var Client = class extends Protocol {
33925
34171
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
33926
34172
  var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
33927
34173
 
34174
+ // ../linkque-agent-runtime/dist/esm/impl/abortableDelay.js
34175
+ import { setTimeout as delay } from "node:timers/promises";
34176
+ async function abortableDelay(delayMs, signal, ref = true) {
34177
+ signal?.throwIfAborted();
34178
+ try {
34179
+ await delay(delayMs, void 0, { signal, ref });
34180
+ } catch (error) {
34181
+ signal?.throwIfAborted();
34182
+ throw error;
34183
+ }
34184
+ }
34185
+
33928
34186
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/connectRetry.js
33929
34187
  var DEFAULT_MAX_CONNECT_ATTEMPTS = 3;
33930
34188
  var DEFAULT_RECONNECT_BACKOFF_MS = 1e3;
33931
34189
  var MAX_RECONNECT_BACKOFF_MS = 8e3;
33932
- async function connectMcpClientWithRetry(config, factories) {
34190
+ async function connectMcpClientWithRetry(config, factories, signal) {
33933
34191
  const maxAttempts = Math.max(1, config.maxConnectAttempts ?? DEFAULT_MAX_CONNECT_ATTEMPTS);
33934
34192
  const backoffBase = config.reconnectBackoffMs ?? DEFAULT_RECONNECT_BACKOFF_MS;
33935
34193
  let lastError;
33936
34194
  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
34195
+ signal?.throwIfAborted();
33937
34196
  const transport = factories.createTransport();
33938
34197
  const client = factories.createClient();
34198
+ let closing;
34199
+ const close = () => closing ??= safeClose(transport, client);
33939
34200
  try {
33940
- await client.connect(transport);
34201
+ const connecting = client.connect(transport).then(() => {
34202
+ if (signal?.aborted) {
34203
+ void close();
34204
+ signal.throwIfAborted();
34205
+ }
34206
+ });
34207
+ await waitWithSignal(connecting, signal);
34208
+ signal?.throwIfAborted();
33941
34209
  return { transport, client };
33942
34210
  } catch (error) {
33943
34211
  lastError = error;
33944
- await safeClose(transport, client);
34212
+ if (signal?.aborted) {
34213
+ void close();
34214
+ signal.throwIfAborted();
34215
+ }
34216
+ await waitWithSignal(close(), signal);
33945
34217
  if (attempt < maxAttempts) {
33946
- const delay = Math.min(backoffBase * 2 ** (attempt - 1), MAX_RECONNECT_BACKOFF_MS);
33947
- await sleep(delay);
34218
+ const delay2 = Math.min(backoffBase * 2 ** (attempt - 1), MAX_RECONNECT_BACKOFF_MS);
34219
+ await abortableDelay(delay2, signal, false);
33948
34220
  }
33949
34221
  }
33950
34222
  }
@@ -33963,33 +34235,11 @@ async function safeClose(transport, client) {
33963
34235
  } catch {
33964
34236
  }
33965
34237
  }
33966
- function sleep(ms) {
33967
- return new Promise((resolve) => {
33968
- const timer = setTimeout(resolve, ms);
33969
- timer.unref?.();
33970
- });
33971
- }
33972
34238
 
33973
34239
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/mcpInvocationContext.js
33974
34240
  import { AsyncLocalStorage } from "node:async_hooks";
33975
34241
  async function waitForMcpOperation(operation, signal) {
33976
- signal.throwIfAborted();
33977
- let onAbort = () => {
33978
- };
33979
- try {
33980
- return await Promise.race([
33981
- new Promise((_, reject) => {
33982
- onAbort = () => reject(signal.reason);
33983
- signal.addEventListener("abort", onAbort, { once: true });
33984
- }),
33985
- Promise.resolve().then(() => {
33986
- signal.throwIfAborted();
33987
- return operation();
33988
- })
33989
- ]);
33990
- } finally {
33991
- signal.removeEventListener("abort", onAbort);
33992
- }
34242
+ return waitWithSignal(operation, signal);
33993
34243
  }
33994
34244
  var McpInvocationContext = class {
33995
34245
  storage = new AsyncLocalStorage();
@@ -34000,19 +34250,22 @@ var McpInvocationContext = class {
34000
34250
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
34001
34251
  throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
34002
34252
  signal?.throwIfAborted();
34003
- const controller = new AbortController();
34253
+ const scope = new CancellationScope({
34254
+ signals: signal ? [signal] : [],
34255
+ timeoutMs,
34256
+ timeoutReason: new DOMException("MCP \u8C03\u7528\u603B\u9884\u7B97\u5DF2\u8017\u5C3D", "TimeoutError")
34257
+ });
34004
34258
  const context2 = {
34005
- signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
34006
- deadline: performance.now() + timeoutMs
34259
+ signal: scope.context.signal,
34260
+ deadline: scope.context.deadline
34007
34261
  };
34008
- const timer = setTimeout(() => controller.abort(new DOMException("MCP \u8C03\u7528\u603B\u9884\u7B97\u5DF2\u8017\u5C3D", "TimeoutError")), Math.min(timeoutMs, 2147483647));
34009
34262
  try {
34010
- return await this.storage.run(context2, () => waitForMcpOperation(() => operation(context2), context2.signal));
34263
+ return await this.storage.run(context2, () => waitWithSignal(() => operation(context2), context2.signal));
34011
34264
  } catch (error) {
34012
- context2.signal.throwIfAborted();
34265
+ scope.context.throwIfAborted();
34013
34266
  throw error;
34014
34267
  } finally {
34015
- clearTimeout(timer);
34268
+ scope.dispose();
34016
34269
  }
34017
34270
  }
34018
34271
  };
@@ -35725,8 +35978,12 @@ function withTimeout(fetch2, timeoutMs) {
35725
35978
  if (init?.signal) {
35726
35979
  return fetch2(url2, init);
35727
35980
  }
35728
- const signal = AbortSignal.timeout(timeoutMs);
35729
- return fetch2(url2, { ...init, signal });
35981
+ const scope = new CancellationScope({ timeoutMs });
35982
+ try {
35983
+ return await fetch2(url2, { ...init, signal: scope.context.signal });
35984
+ } finally {
35985
+ scope.dispose();
35986
+ }
35730
35987
  };
35731
35988
  }
35732
35989
  function createSseTransport(config, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
@@ -35955,12 +36212,13 @@ var RemoteGatewayMcpServerProvider = class {
35955
36212
  this.onTraceId = options.onTraceId;
35956
36213
  this.debugLog = options.debugLog;
35957
36214
  }
35958
- async servers(resources) {
35959
- return Promise.all(resources.map((r) => this.connectOne(r)));
36215
+ async servers(resources, signal) {
36216
+ return Promise.all(resources.map((r) => this.connectOne(r, signal)));
35960
36217
  }
35961
36218
  /** 连单个远端 server 并包装成 IMcpServer。建连失败有限重试 + 失败清理由 helper 负责。 */
35962
- async connectOne(resource) {
36219
+ async connectOne(resource, connectSignal) {
35963
36220
  const config = await this.resolveConfig(resource);
36221
+ connectSignal?.throwIfAborted();
35964
36222
  const timeoutMs = config.requestTimeoutMs ?? 18e4;
35965
36223
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
35966
36224
  throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
@@ -35969,7 +36227,7 @@ var RemoteGatewayMcpServerProvider = class {
35969
36227
  const { client } = await connectMcpClientWithRetry(config, {
35970
36228
  createTransport: () => createSseTransport(config, this.createSigner(config, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
35971
36229
  createClient: () => this.createClient()
35972
- });
36230
+ }, connectSignal);
35973
36231
  const serverName = resource.config.serverName ?? resource.resourceId;
35974
36232
  const argsMappingRules = resource.config.argsMappingRules ?? [];
35975
36233
  let requestSequence = 0;
@@ -36002,7 +36260,7 @@ var RemoteGatewayMcpServerProvider = class {
36002
36260
  }
36003
36261
  };
36004
36262
  const loggedClient = {
36005
- listTools: () => request("tools/list", {}, () => client.listTools()),
36263
+ listTools: (params, options) => request("tools/list", params ?? {}, () => client.listTools(params, options)),
36006
36264
  callTool: (params, resultSchema, requestOptions) => request("tools/call", params, () => client.callTool(params, resultSchema, requestOptions))
36007
36265
  };
36008
36266
  const callTool = (name, args, signal, options) => callHeaders.run(options?.headers ?? {}, () => this.invocationContext.run(timeoutMs, signal, async (invocation) => {
@@ -36052,7 +36310,7 @@ var RemoteGatewayMcpServerProvider = class {
36052
36310
  return {
36053
36311
  resourceId: resource.resourceId,
36054
36312
  serverName,
36055
- listTools: () => listToolsFromClient(loggedClient, resource.resourceId, callTool),
36313
+ listTools: (signal) => listToolsFromClient(loggedClient, resource.resourceId, callTool, signal),
36056
36314
  callTool,
36057
36315
  close: async () => {
36058
36316
  try {
@@ -36063,8 +36321,9 @@ var RemoteGatewayMcpServerProvider = class {
36063
36321
  };
36064
36322
  }
36065
36323
  };
36066
- async function listToolsFromClient(client, resourceId, callTool) {
36067
- const result = await client.listTools();
36324
+ async function listToolsFromClient(client, resourceId, callTool, listSignal) {
36325
+ listSignal?.throwIfAborted();
36326
+ const result = await client.listTools(void 0, listSignal ? { signal: listSignal } : void 0);
36068
36327
  const tools = result.tools ?? [];
36069
36328
  return tools.map((tool) => {
36070
36329
  const descriptor = {
@@ -36133,28 +36392,20 @@ var LinkqueKnowledgeSearchPort = class {
36133
36392
  "content-type": "application/json",
36134
36393
  ...await this.getAuthHeaders()
36135
36394
  };
36136
- const controller = new AbortController();
36137
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
36138
- const onAbort = () => controller.abort();
36139
- if (signal) {
36140
- if (signal.aborted) {
36141
- controller.abort();
36142
- } else {
36143
- signal.addEventListener("abort", onAbort, { once: true });
36144
- }
36145
- }
36395
+ const scope = new CancellationScope({
36396
+ signals: signal ? [signal] : [],
36397
+ timeoutMs: this.timeoutMs
36398
+ });
36146
36399
  let resp;
36147
36400
  try {
36148
36401
  resp = await this.fetchImpl(url2, {
36149
36402
  method: "POST",
36150
36403
  headers,
36151
36404
  body,
36152
- signal: controller.signal
36405
+ signal: scope.context.signal
36153
36406
  });
36154
36407
  } finally {
36155
- clearTimeout(timer);
36156
- if (signal)
36157
- signal.removeEventListener("abort", onAbort);
36408
+ scope.dispose();
36158
36409
  }
36159
36410
  if (!resp.ok) {
36160
36411
  const text = await safeText2(resp);
@@ -36228,13 +36479,12 @@ var LinkqueWebSearchPort = class {
36228
36479
  }
36229
36480
  async search(input, signal) {
36230
36481
  const startedAt = Date.now();
36231
- const controller = new AbortController();
36232
- const onAbort = () => controller.abort(new DOMException("\u5168\u7F51\u641C\u7D22\u5DF2\u53D6\u6D88", "AbortError"));
36233
- signal?.addEventListener("abort", onAbort, { once: true });
36234
- if (signal?.aborted)
36235
- onAbort();
36236
- const timer = setTimeout(() => controller.abort(new WebSearchError("WEB_SEARCH_TIMEOUT")), this.timeoutMs);
36237
- const requestSignal = controller.signal;
36482
+ const scope = new CancellationScope({
36483
+ signals: signal ? [signal] : [],
36484
+ timeoutMs: this.timeoutMs,
36485
+ timeoutReason: new WebSearchError("WEB_SEARCH_TIMEOUT")
36486
+ });
36487
+ const requestSignal = scope.context.signal;
36238
36488
  let outcome = "success";
36239
36489
  let status;
36240
36490
  let count = 0;
@@ -36279,8 +36529,7 @@ var LinkqueWebSearchPort = class {
36279
36529
  outcome = failure5.code;
36280
36530
  throw new WebSearchError(failure5.code);
36281
36531
  } finally {
36282
- clearTimeout(timer);
36283
- signal?.removeEventListener("abort", onAbort);
36532
+ scope.dispose();
36284
36533
  try {
36285
36534
  this.options.debugLog?.(JSON.stringify({
36286
36535
  tag: "web-search-http",
@@ -37392,9 +37641,9 @@ var import_otlp_transformer = __toESM(require_src7(), 1);
37392
37641
  import { randomUUID as randomUUID5 } from "node:crypto";
37393
37642
 
37394
37643
  // ../linkque-agent-runtime/dist/esm/impl/telemetry/identityQueue.js
37644
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
37395
37645
  init_esm();
37396
37646
  var import_core5 = __toESM(require_src(), 1);
37397
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
37398
37647
  function authorizationKey(auth2) {
37399
37648
  return JSON.stringify([
37400
37649
  auth2.subject,
@@ -37432,7 +37681,7 @@ var IdentityQueue = class {
37432
37681
  maxBytes: options.maxBytes ?? 16 * 1024 * 1024,
37433
37682
  maxPartitions: options.maxPartitions ?? 32,
37434
37683
  batchMaxRecords: options.batchMaxRecords ?? 100,
37435
- batchMaxBytes: options.batchMaxBytes ?? 256 * 1024,
37684
+ batchMaxBytes: options.batchMaxBytes ?? 1024 * 1024,
37436
37685
  intervalMs: options.intervalMs ?? 1e3,
37437
37686
  sendTimeoutMs: options.sendTimeoutMs ?? 2e3,
37438
37687
  maxAgeMs: options.maxAgeMs ?? 6e4,
@@ -37520,7 +37769,7 @@ var IdentityQueue = class {
37520
37769
  const resource = body[signal === ETelemetrySignal.LOGS ? "resourceLogs" : "resourceSpans"][0];
37521
37770
  const bytes2 = Buffer.byteLength(JSON.stringify(resource)) + 1;
37522
37771
  const ratio = critical ? 1 : 1 - this.limits.terminalReserveRatio;
37523
- if (bytes2 + 32 > this.limits.batchMaxBytes || bytes2 > 16 * 1024 || part.records.length + 1 > Math.floor(this.limits.partitionMaxRecords * ratio) || part.bytes + bytes2 > this.limits.partitionMaxBytes * ratio || this.bytes + bytes2 > this.limits.maxBytes * ratio) {
37772
+ if (bytes2 + 32 > this.limits.batchMaxBytes || part.records.length + 1 > Math.floor(this.limits.partitionMaxRecords * ratio) || part.bytes + bytes2 > this.limits.partitionMaxBytes * ratio || this.bytes + bytes2 > this.limits.maxBytes * ratio) {
37524
37773
  this.drop(ETelemetryDiagnosticCode.QUEUE_LIMIT, 1, part);
37525
37774
  return;
37526
37775
  }
@@ -37582,97 +37831,90 @@ var IdentityQueue = class {
37582
37831
  batch.push(record2);
37583
37832
  bytes2 += record2.bytes;
37584
37833
  }
37585
- const controller = new AbortController();
37586
- this.controllers.add(controller);
37587
- let timer;
37588
- const timeout = new Promise((_, reject) => {
37589
- controller.signal.addEventListener("abort", () => reject(new Error("\u9065\u6D4B\u53D1\u9001\u7EC8\u6B62")), { once: true });
37590
- timer = setTimeout(() => controller.abort(), this.limits.sendTimeoutMs);
37591
- timer.unref?.();
37834
+ const scope = new CancellationScope({
37835
+ timeoutMs: this.limits.sendTimeoutMs,
37836
+ timeoutReason: new Error("\u9065\u6D4B\u53D1\u9001\u7EC8\u6B62"),
37837
+ ref: false
37592
37838
  });
37839
+ this.controllers.add(scope);
37593
37840
  try {
37594
- await Promise.race([
37595
- this.exportContext.run(true, () => context.with((0, import_core5.suppressTracing)(context.active()), async () => {
37596
- const headers = await part.authorization.getHeaders();
37597
- if (controller.signal.aborted || this.closed)
37598
- return;
37599
- const response = await (this.options.fetch ?? fetch)(signal === ETelemetrySignal.LOGS ? this.options.logsEndpoint : this.options.tracesEndpoint, {
37600
- method: "POST",
37601
- redirect: "error",
37602
- signal: controller.signal,
37603
- headers: { ...headers, "content-type": "application/json" },
37604
- body: JSON.stringify({
37605
- [signal === ETelemetrySignal.LOGS ? "resourceLogs" : "resourceSpans"]: batch.map((record2) => record2.resource)
37606
- })
37607
- });
37608
- if (controller.signal.aborted || this.closed)
37609
- return;
37610
- if (response.status === 200) {
37611
- const reader = response.body?.getReader();
37612
- const chunks = [];
37613
- let size = 0;
37614
- if (reader) {
37615
- try {
37616
- for (; ; ) {
37617
- const next = await reader.read();
37618
- if (next.done)
37619
- break;
37620
- size += next.value.length;
37621
- if (size > 64 * 1024)
37622
- throw new Error("\u9065\u6D4B\u54CD\u5E94\u8D85\u9650");
37623
- chunks.push(next.value);
37624
- }
37625
- } finally {
37626
- await reader.cancel().catch(() => void 0);
37841
+ await waitWithSignal(() => this.exportContext.run(true, () => context.with((0, import_core5.suppressTracing)(context.active()), async () => {
37842
+ const headers = await part.authorization.getHeaders();
37843
+ if (scope.context.signal.aborted || this.closed)
37844
+ return;
37845
+ const response = await (this.options.fetch ?? fetch)(signal === ETelemetrySignal.LOGS ? this.options.logsEndpoint : this.options.tracesEndpoint, {
37846
+ method: "POST",
37847
+ redirect: "error",
37848
+ signal: scope.context.signal,
37849
+ headers: { ...headers, "content-type": "application/json" },
37850
+ body: JSON.stringify({
37851
+ [signal === ETelemetrySignal.LOGS ? "resourceLogs" : "resourceSpans"]: batch.map((record2) => record2.resource)
37852
+ })
37853
+ });
37854
+ if (scope.context.signal.aborted || this.closed)
37855
+ return;
37856
+ if (response.status === 200) {
37857
+ const reader = response.body?.getReader();
37858
+ const chunks = [];
37859
+ let size = 0;
37860
+ if (reader) {
37861
+ try {
37862
+ for (; ; ) {
37863
+ const next = await reader.read();
37864
+ if (next.done)
37865
+ break;
37866
+ size += next.value.length;
37867
+ if (size > 64 * 1024)
37868
+ throw new Error("\u9065\u6D4B\u54CD\u5E94\u8D85\u9650");
37869
+ chunks.push(next.value);
37627
37870
  }
37871
+ } finally {
37872
+ await reader.cancel().catch(() => void 0);
37628
37873
  }
37629
- const raw = Buffer.concat(chunks).toString("utf8");
37630
- const result = raw ? JSON.parse(raw) : {};
37631
- if (!result || typeof result !== "object" || Array.isArray(result))
37632
- throw new Error("\u9065\u6D4B\u54CD\u5E94\u975E\u6CD5");
37633
- const rejected = Number(result.partialSuccess?.[signal === ETelemetrySignal.LOGS ? "rejectedLogRecords" : "rejectedSpans"] ?? 0);
37634
- if (!Number.isSafeInteger(rejected) || rejected < 0 || rejected > batch.length)
37635
- throw new Error("\u9065\u6D4B\u62D2\u6536\u8BA1\u6570\u975E\u6CD5");
37636
- if (controller.signal.aborted || this.closed)
37637
- return;
37638
- this.remove(part, batch);
37639
- this.sent += batch.length - rejected;
37640
- part.sent += batch.length - rejected;
37641
- if (rejected)
37642
- this.drop(ETelemetryDiagnosticCode.PARTIAL_SUCCESS, rejected, part);
37643
- part.retry = 0;
37644
- part.nextAt = 0;
37874
+ }
37875
+ const raw = Buffer.concat(chunks).toString("utf8");
37876
+ const result = raw ? JSON.parse(raw) : {};
37877
+ if (!result || typeof result !== "object" || Array.isArray(result))
37878
+ throw new Error("\u9065\u6D4B\u54CD\u5E94\u975E\u6CD5");
37879
+ const rejected = Number(result.partialSuccess?.[signal === ETelemetrySignal.LOGS ? "rejectedLogRecords" : "rejectedSpans"] ?? 0);
37880
+ if (!Number.isSafeInteger(rejected) || rejected < 0 || rejected > batch.length)
37881
+ throw new Error("\u9065\u6D4B\u62D2\u6536\u8BA1\u6570\u975E\u6CD5");
37882
+ if (scope.context.signal.aborted || this.closed)
37883
+ return;
37884
+ this.remove(part, batch);
37885
+ this.sent += batch.length - rejected;
37886
+ part.sent += batch.length - rejected;
37887
+ if (rejected)
37888
+ this.drop(ETelemetryDiagnosticCode.PARTIAL_SUCCESS, rejected, part);
37889
+ part.retry = 0;
37890
+ part.nextAt = 0;
37891
+ } else {
37892
+ await response.body?.cancel().catch(() => void 0);
37893
+ if (scope.context.signal.aborted || this.closed)
37894
+ return;
37895
+ if ([429, 502, 503, 504].includes(response.status)) {
37896
+ const value = response.headers.get("retry-after");
37897
+ const delay2 = value === null ? 0 : /^\d+$/.test(value) ? Number(value) * 1e3 : Math.max(0, Date.parse(value) - Date.now());
37898
+ this.retry(part, Number.isFinite(delay2) ? delay2 : 0);
37645
37899
  } else {
37646
- await response.body?.cancel().catch(() => void 0);
37647
- if (controller.signal.aborted || this.closed)
37648
- return;
37649
- if ([429, 502, 503, 504].includes(response.status)) {
37650
- const value = response.headers.get("retry-after");
37651
- const delay = value === null ? 0 : /^\d+$/.test(value) ? Number(value) * 1e3 : Math.max(0, Date.parse(value) - Date.now());
37652
- this.retry(part, Number.isFinite(delay) ? delay : 0);
37900
+ if ([401, 403].includes(response.status)) {
37901
+ part.blocked = true;
37902
+ const records = [...part.records];
37903
+ this.remove(part, records);
37904
+ this.drop(ETelemetryDiagnosticCode.AUTHORIZATION_REJECTED, records.length, part);
37653
37905
  } else {
37654
- if ([401, 403].includes(response.status)) {
37655
- part.blocked = true;
37656
- const records = [...part.records];
37657
- this.remove(part, records);
37658
- this.drop(ETelemetryDiagnosticCode.AUTHORIZATION_REJECTED, records.length, part);
37659
- } else {
37660
- this.remove(part, batch);
37661
- this.drop(ETelemetryDiagnosticCode.PERMANENT_REJECTION, batch.length, part);
37662
- }
37906
+ this.remove(part, batch);
37907
+ this.drop(ETelemetryDiagnosticCode.PERMANENT_REJECTION, batch.length, part);
37663
37908
  }
37664
37909
  }
37665
- })),
37666
- timeout
37667
- ]);
37910
+ }
37911
+ })), scope.context.signal);
37668
37912
  } catch {
37669
37913
  if (!this.closed)
37670
37914
  this.retry(part);
37671
37915
  } finally {
37672
- if (timer)
37673
- clearTimeout(timer);
37674
- controller.abort();
37675
- this.controllers.delete(controller);
37916
+ scope.dispose();
37917
+ this.controllers.delete(scope);
37676
37918
  }
37677
37919
  }
37678
37920
  retry(part, minimum = 0) {
@@ -37708,8 +37950,8 @@ var IdentityQueue = class {
37708
37950
  this.closed = true;
37709
37951
  if (this.timer)
37710
37952
  clearInterval(this.timer);
37711
- for (const controller of this.controllers)
37712
- controller.abort();
37953
+ for (const scope of this.controllers)
37954
+ scope.cancel(new Error("\u9065\u6D4B\u53D1\u9001\u7EC8\u6B62"));
37713
37955
  const count = this.pending();
37714
37956
  if (count)
37715
37957
  this.drop(ETelemetryDiagnosticCode.SHUTDOWN_DROP, count);
@@ -37944,7 +38186,7 @@ var OtelRuntimeTelemetry = class {
37944
38186
  {
37945
38187
  onEmit: (record2, ctx) => {
37946
38188
  const route = ctx?.getValue(this.routeKey);
37947
- this.output(ETelemetrySignal.LOGS, import_otlp_transformer.JsonLogsSerializer.serializeRequest([record2]), route?.route, route?.critical ?? false, route?.localOnly ?? false);
38189
+ this.output(ETelemetrySignal.LOGS, import_otlp_transformer.JsonLogsSerializer.serializeRequest([record2]), route?.route, route?.critical ?? false);
37948
38190
  },
37949
38191
  forceFlush: async () => void 0,
37950
38192
  shutdown: async () => void 0
@@ -37952,13 +38194,12 @@ var OtelRuntimeTelemetry = class {
37952
38194
  ]
37953
38195
  });
37954
38196
  }
37955
- output(signal, encoded, route, critical, localOnly = false) {
38197
+ output(signal, encoded, route, critical) {
37956
38198
  if (!encoded || this.outputActive || this.disposed)
37957
38199
  return;
37958
38200
  this.outputActive = true;
37959
38201
  try {
37960
- if (!localOnly)
37961
- this.queue.enqueue(route, signal, encoded, critical);
38202
+ this.queue.enqueue(route, signal, encoded, critical);
37962
38203
  if (this.options.localSink) {
37963
38204
  try {
37964
38205
  const payload = JSON.parse(new TextDecoder().decode(encoded));
@@ -38114,28 +38355,28 @@ var OtelRuntimeTelemetry = class {
38114
38355
  Math.floor(now / 1e3),
38115
38356
  now % 1e3 * 1e6
38116
38357
  ];
38117
- const localOnly = name === ETelemetryEventName.CONTENT_RECORDED;
38118
- if (localOnly && body && typeof body === "object" && "value" in body) {
38358
+ const contentRecord = name === ETelemetryEventName.CONTENT_RECORDED;
38359
+ if (contentRecord && body && typeof body === "object" && "value" in body) {
38119
38360
  const { value, ...metadata } = body;
38120
38361
  try {
38121
38362
  const valueJson = JSON.stringify(value);
38122
- body = valueJson !== void 0 && Buffer.byteLength(JSON.stringify(valueJson), "utf8") <= 512 * 1024 ? { ...metadata, valueJson } : { ...metadata, availability: "unavailable", reason: "content_limit" };
38363
+ body = valueJson !== void 0 && Buffer.byteLength(JSON.stringify(valueJson), "utf8") <= 512 * 1024 ? { ...metadata, valueJson } : {
38364
+ ...metadata,
38365
+ availability: "unavailable",
38366
+ reason: "content_limit"
38367
+ };
38123
38368
  } catch {
38124
38369
  body = { ...metadata, availability: "unavailable" };
38125
38370
  }
38126
38371
  }
38127
- if (!localOnly && operation.span.isRecording())
38372
+ if (!contentRecord && operation.span.isRecording())
38128
38373
  operation.span.addEvent(
38129
38374
  name,
38130
38375
  // 复用已投影的属性;Span 已持有上下文,事件只保留本次事实及去重字段。
38131
38376
  Object.fromEntries(Object.entries(record2).filter(([key]) => Object.hasOwn(attributes, key) || key === ETelemetryAttribute.HARNESS_RECORD_ID || key === ETelemetryAttribute.HARNESS_EVENT_SEQUENCE)),
38132
38377
  time
38133
38378
  );
38134
- const ctx = trace.setSpan(ROOT_CONTEXT, operation.span).setValue(this.routeKey, {
38135
- route: operation.state.route,
38136
- critical,
38137
- localOnly
38138
- });
38379
+ const ctx = trace.setSpan(ROOT_CONTEXT, operation.span).setValue(this.routeKey, { route: operation.state.route, critical });
38139
38380
  this.loggerProvider.getLogger(ETelemetryMetadata.SCOPE_NAME, ETelemetryVersion.V1_0).emit({
38140
38381
  eventName: name,
38141
38382
  timestamp: time,
@@ -38317,6 +38558,8 @@ export {
38317
38558
  ETelemetryErrorType,
38318
38559
  ETelemetryGenAiOperation,
38319
38560
  recordContentSection,
38561
+ waitWithSignal,
38562
+ CancellationScope,
38320
38563
  McpProxyTool,
38321
38564
  executeHomeData,
38322
38565
  CardActionDiagnostics,
@@ -38354,6 +38597,7 @@ export {
38354
38597
  NoopWebSearchPort,
38355
38598
  NoopRuntimeTelemetry,
38356
38599
  startRuntimeObservation,
38600
+ abortableDelay,
38357
38601
  RemoteGatewayMcpServerProvider,
38358
38602
  LinkqueKnowledgeSearchPort,
38359
38603
  LinkqueWebSearchPort,