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.
package/worker.js CHANGED
@@ -99,6 +99,7 @@ var init_agentProtocol = __esm({
99
99
  EHookExecutorName2["LinkquegwEventHookExecutor"] = "LinkquegwEventHookExecutor";
100
100
  EHookExecutorName2["SecurityAnswerHookExecutor"] = "SecurityAnswerHookExecutor";
101
101
  EHookExecutorName2["ImageUnderstandingHookExecutor"] = "ImageUnderstandingHookExecutor";
102
+ EHookExecutorName2["McpDiscoveryHookExecutor"] = "McpDiscoveryHookExecutor";
102
103
  })(EHookExecutorName || (EHookExecutorName = {}));
103
104
  }
104
105
  });
@@ -12003,6 +12004,7 @@ var init_telemetryEnums = __esm({
12003
12004
  ETelemetryEventPrefix2["ADVANCE"] = "harness.advance";
12004
12005
  ETelemetryEventPrefix2["MODEL_INVOKE"] = "harness.model.invoke";
12005
12006
  ETelemetryEventPrefix2["MODEL_ATTEMPT"] = "harness.model.attempt";
12007
+ ETelemetryEventPrefix2["MODEL_REASONING"] = "harness.model.reasoning";
12006
12008
  ETelemetryEventPrefix2["TOOL_INVOKE"] = "harness.tool.invoke";
12007
12009
  ETelemetryEventPrefix2["TOOL_ATTEMPT"] = "harness.tool.attempt";
12008
12010
  ETelemetryEventPrefix2["HOOK_CHAIN"] = "harness.hook.chain";
@@ -12042,6 +12044,8 @@ var init_telemetryEnums = __esm({
12042
12044
  ETelemetryEventName2["MODEL_INVOKE_FINISHED"] = "harness.model.invoke.finished";
12043
12045
  ETelemetryEventName2["MODEL_ATTEMPT_STARTED"] = "harness.model.attempt.started";
12044
12046
  ETelemetryEventName2["MODEL_ATTEMPT_FINISHED"] = "harness.model.attempt.finished";
12047
+ ETelemetryEventName2["MODEL_REASONING_STARTED"] = "harness.model.reasoning.started";
12048
+ ETelemetryEventName2["MODEL_REASONING_FINISHED"] = "harness.model.reasoning.finished";
12045
12049
  ETelemetryEventName2["TOOL_INVOKE_STARTED"] = "harness.tool.invoke.started";
12046
12050
  ETelemetryEventName2["TOOL_INVOKE_FINISHED"] = "harness.tool.invoke.finished";
12047
12051
  ETelemetryEventName2["TOOL_ATTEMPT_STARTED"] = "harness.tool.attempt.started";
@@ -12063,7 +12067,12 @@ var init_telemetryEnums = __esm({
12063
12067
  })(ETelemetryEventName || (ETelemetryEventName = {}));
12064
12068
  (function(ETelemetryContentSection2) {
12065
12069
  ETelemetryContentSection2["QUERY_INPUT"] = "query.input";
12070
+ ETelemetryContentSection2["MODEL_INPUT_DIGEST"] = "model.input.digest";
12071
+ ETelemetryContentSection2["MODEL_OUT_RAW"] = "model.out.raw";
12066
12072
  ETelemetryContentSection2["MODEL_OUTPUT"] = "model.output";
12073
+ ETelemetryContentSection2["MODEL_REASONING"] = "model.reasoning";
12074
+ ETelemetryContentSection2["FOLLOW_UP_QUESTION_INPUT"] = "follow_up_question.input";
12075
+ ETelemetryContentSection2["FOLLOW_UP_QUESTION_OUTPUT"] = "follow_up_question.output";
12067
12076
  ETelemetryContentSection2["MCP_ACTION_OUTPUT"] = "mcp_action.output";
12068
12077
  ETelemetryContentSection2["TOOL_INPUT"] = "tool.input";
12069
12078
  ETelemetryContentSection2["TOOL_OUTPUT"] = "tool.output";
@@ -12081,6 +12090,7 @@ var init_telemetryEnums = __esm({
12081
12090
  ETelemetryOperationName2["ADVANCE"] = "harness.advance";
12082
12091
  ETelemetryOperationName2["MODEL_INVOKE"] = "harness.model.invoke";
12083
12092
  ETelemetryOperationName2["MODEL_ATTEMPT"] = "harness.model.attempt";
12093
+ ETelemetryOperationName2["MODEL_REASONING"] = "harness.model.reasoning";
12084
12094
  ETelemetryOperationName2["TOOL_ATTEMPT"] = "harness.tool.attempt";
12085
12095
  ETelemetryOperationName2["HOOK_CHAIN"] = "harness.hook.chain";
12086
12096
  ETelemetryOperationName2["MIDDLEWARE"] = "harness.middleware";
@@ -12194,6 +12204,7 @@ var init_telemetryEnums = __esm({
12194
12204
  })(ETelemetryTerminalSource || (ETelemetryTerminalSource = {}));
12195
12205
  (function(ETelemetryModelPurpose2) {
12196
12206
  ETelemetryModelPurpose2["AGENT_LOOP"] = "agent_loop";
12207
+ ETelemetryModelPurpose2["FOLLOW_UP_QUESTION"] = "follow_up_question";
12197
12208
  })(ETelemetryModelPurpose || (ETelemetryModelPurpose = {}));
12198
12209
  (function(ETelemetryErrorType2) {
12199
12210
  ETelemetryErrorType2["PROVIDER_STREAM_ERROR"] = "ProviderStreamError";
@@ -12262,6 +12273,147 @@ var init_contentRecording = __esm({
12262
12273
  }
12263
12274
  });
12264
12275
 
12276
+ // ../linkque-agent-runtime/dist/esm/core/abort.js
12277
+ function waitWithSignal(operation, signal) {
12278
+ if (typeof operation === "function") {
12279
+ if (signal?.aborted)
12280
+ return Promise.reject(signal.reason);
12281
+ try {
12282
+ return waitForPromise(operation(signal), signal);
12283
+ } catch (error40) {
12284
+ return Promise.reject(error40);
12285
+ }
12286
+ }
12287
+ return waitForPromise(operation, signal);
12288
+ }
12289
+ function waitForPromise(operation, signal) {
12290
+ if (!signal)
12291
+ return operation;
12292
+ return new Promise((resolve, reject) => {
12293
+ const abort = () => {
12294
+ signal.removeEventListener("abort", abort);
12295
+ reject(signal.reason);
12296
+ };
12297
+ signal.addEventListener("abort", abort, { once: true });
12298
+ operation.then((value) => {
12299
+ signal.removeEventListener("abort", abort);
12300
+ resolve(value);
12301
+ }, (error40) => {
12302
+ signal.removeEventListener("abort", abort);
12303
+ reject(error40);
12304
+ });
12305
+ if (signal.aborted)
12306
+ abort();
12307
+ });
12308
+ }
12309
+ var init_abort = __esm({
12310
+ "../linkque-agent-runtime/dist/esm/core/abort.js"() {
12311
+ "use strict";
12312
+ }
12313
+ });
12314
+
12315
+ // ../linkque-agent-runtime/dist/esm/core/cancellationScope.js
12316
+ var MAX_TIMER_DELAY_MS, CancellationScope;
12317
+ var init_cancellationScope = __esm({
12318
+ "../linkque-agent-runtime/dist/esm/core/cancellationScope.js"() {
12319
+ "use strict";
12320
+ MAX_TIMER_DELAY_MS = 2147483647;
12321
+ CancellationScope = class {
12322
+ controller = new AbortController();
12323
+ listeners = [];
12324
+ timeoutReason;
12325
+ parent;
12326
+ ref;
12327
+ timer;
12328
+ disposed = false;
12329
+ context;
12330
+ constructor(options = {}) {
12331
+ const { parent, signals = [], timeoutMs } = options;
12332
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0))
12333
+ throw new Error("\u53D6\u6D88\u4F5C\u7528\u57DF timeoutMs \u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
12334
+ this.parent = parent;
12335
+ this.ref = options.ref ?? true;
12336
+ this.timeoutReason = options.timeoutReason ?? new DOMException("\u64CD\u4F5C\u8D85\u65F6", "TimeoutError");
12337
+ const ownDeadline = timeoutMs === void 0 ? void 0 : performance.now() + timeoutMs;
12338
+ const deadline = ownDeadline === void 0 ? parent?.deadline : parent?.deadline === void 0 ? ownDeadline : Math.min(ownDeadline, parent.deadline);
12339
+ this.context = {
12340
+ signal: this.controller.signal,
12341
+ deadline,
12342
+ remainingMs: () => deadline === void 0 ? Infinity : Math.max(0, deadline - performance.now()),
12343
+ throwIfAborted: () => {
12344
+ this.controller.signal.throwIfAborted();
12345
+ if (deadline !== void 0 && performance.now() >= deadline) {
12346
+ try {
12347
+ parent?.throwIfAborted();
12348
+ } catch {
12349
+ }
12350
+ if (parent?.signal.aborted)
12351
+ this.cancel(parent.signal.reason);
12352
+ else
12353
+ this.cancel(this.timeoutReason);
12354
+ }
12355
+ this.controller.signal.throwIfAborted();
12356
+ }
12357
+ };
12358
+ for (const source of [parent?.signal, ...signals]) {
12359
+ if (!source)
12360
+ continue;
12361
+ if (source.aborted) {
12362
+ this.cancel(source.reason);
12363
+ break;
12364
+ }
12365
+ const forward = () => this.cancel(source.reason);
12366
+ source.addEventListener("abort", forward, { once: true });
12367
+ this.listeners.push(() => source.removeEventListener("abort", forward));
12368
+ }
12369
+ if (!this.controller.signal.aborted && deadline !== void 0)
12370
+ this.armTimer(deadline);
12371
+ }
12372
+ cancel(reason = new DOMException("\u64CD\u4F5C\u5DF2\u53D6\u6D88", "AbortError")) {
12373
+ if (this.disposed || this.controller.signal.aborted)
12374
+ return;
12375
+ this.controller.abort(reason);
12376
+ this.release();
12377
+ }
12378
+ dispose() {
12379
+ if (this.disposed)
12380
+ return;
12381
+ this.disposed = true;
12382
+ this.release();
12383
+ }
12384
+ armTimer(deadline) {
12385
+ if (this.timer !== void 0)
12386
+ clearTimeout(this.timer);
12387
+ const remaining = deadline - performance.now();
12388
+ if (remaining <= 0) {
12389
+ try {
12390
+ this.parent?.throwIfAborted();
12391
+ } catch {
12392
+ }
12393
+ if (this.parent?.signal.aborted)
12394
+ this.cancel(this.parent.signal.reason);
12395
+ else
12396
+ this.cancel(this.timeoutReason);
12397
+ return;
12398
+ }
12399
+ this.timer = setTimeout(() => {
12400
+ this.timer = void 0;
12401
+ this.armTimer(deadline);
12402
+ }, Math.min(remaining, MAX_TIMER_DELAY_MS));
12403
+ if (!this.ref)
12404
+ this.timer.unref?.();
12405
+ }
12406
+ release() {
12407
+ if (this.timer !== void 0)
12408
+ clearTimeout(this.timer);
12409
+ this.timer = void 0;
12410
+ for (const remove of this.listeners.splice(0))
12411
+ remove();
12412
+ }
12413
+ };
12414
+ }
12415
+ });
12416
+
12265
12417
  // ../linkque-agent-runtime/dist/esm/core/mcpProxyTool.js
12266
12418
  function resourceIdsForTool(spec, toolName) {
12267
12419
  if (!spec.allToolResourceIds && !spec.resourceIdsByTool)
@@ -12334,11 +12486,15 @@ var init_mcpProxyTool = __esm({
12334
12486
  init_telemetry();
12335
12487
  init_contentRecording();
12336
12488
  init_esm();
12489
+ init_abort();
12490
+ init_cancellationScope();
12337
12491
  init_types();
12338
12492
  MCP_PROXY_TOOL_NAME = "mcp";
12339
12493
  McpProxyTool = class {
12340
12494
  provider;
12341
12495
  /** serverName → 缓存条目(同 serverName 多 resourceId 聚合为一个连接)。 */
12496
+ lifetime;
12497
+ closing = /* @__PURE__ */ new WeakMap();
12342
12498
  entries = /* @__PURE__ */ new Map();
12343
12499
  /** 进行中的连接(去重并发 ensureEntry)。 */
12344
12500
  inFlight = /* @__PURE__ */ new Map();
@@ -12350,6 +12506,9 @@ var init_mcpProxyTool = __esm({
12350
12506
  authorizeCall;
12351
12507
  constructor(provider, specs, options = {}) {
12352
12508
  this.provider = provider;
12509
+ this.lifetime = new CancellationScope({
12510
+ signals: options.signal ? [options.signal] : []
12511
+ });
12353
12512
  this.specs = specs;
12354
12513
  this.specByServerName = new Map(specs.map((spec) => [spec.serverName, spec]));
12355
12514
  this.specByResourceId = new Map(specs.flatMap((spec) => spec.resourceIds.map((id) => [id, spec])));
@@ -12403,40 +12562,121 @@ var init_mcpProxyTool = __esm({
12403
12562
  }
12404
12563
  };
12405
12564
  }
12406
- /** 关闭所有已连 server(忽略单 server 关闭错误)。 */
12407
- async closeAll() {
12408
- await Promise.all([...this.entries.values()].map(async (entry) => {
12409
- if (!entry.server)
12410
- return;
12565
+ /** 并发发现所有 server;每个 server 独立限时,失败结果不阻断其他目录。 */
12566
+ async discover(signal) {
12567
+ signal?.throwIfAborted();
12568
+ const results = await Promise.all(this.specs.map(async (spec) => {
12569
+ const scope = new CancellationScope({
12570
+ parent: this.lifetime.context,
12571
+ signals: signal ? [signal] : [],
12572
+ timeoutMs: 5e3,
12573
+ timeoutReason: new DOMException("MCP \u76EE\u5F55\u9884\u52A0\u8F7D\u8D85\u65F6", "TimeoutError")
12574
+ });
12411
12575
  try {
12412
- await entry.server.close?.();
12576
+ const entry = await this.ensureEntry(spec.serverName, scope.context.signal);
12577
+ return {
12578
+ serverName: spec.serverName,
12579
+ status: entry ? "connected" : "failed",
12580
+ tools: (entry?.tools ?? []).map(({ name, description }) => {
12581
+ const metadata = { name };
12582
+ if (description !== void 0)
12583
+ metadata.description = description;
12584
+ return metadata;
12585
+ })
12586
+ };
12413
12587
  } catch (error40) {
12414
- try {
12415
- this.debugLog(`[mcp] server ${entry.server.serverName} close failed: ${error40 instanceof Error ? error40.message : "unknown error"}`, EDebugLogScope.MCP);
12416
- } catch {
12588
+ if (signal?.aborted || this.lifetime.context.signal.aborted)
12589
+ throw error40;
12590
+ if (scope.context.signal.aborted) {
12591
+ return {
12592
+ serverName: spec.serverName,
12593
+ status: "failed",
12594
+ tools: []
12595
+ };
12417
12596
  }
12597
+ throw error40;
12598
+ } finally {
12599
+ scope.dispose();
12418
12600
  }
12419
12601
  }));
12602
+ signal?.throwIfAborted();
12603
+ this.lifetime.context.throwIfAborted();
12604
+ return results;
12605
+ }
12606
+ /** 关闭缓存连接并取消在途连接;忽略取消的 provider 返回后也会立即清理。 */
12607
+ async closeAll() {
12608
+ this.lifetime.cancel(new DOMException("MCP Run \u5DF2\u7ED3\u675F", "AbortError"));
12609
+ for (const attempt of this.inFlight.values()) {
12610
+ attempt.abandoned = true;
12611
+ attempt.scope.cancel(this.lifetime.context.signal.reason);
12612
+ }
12613
+ this.inFlight.clear();
12614
+ await Promise.all([...this.entries.values()].map((entry) => entry.server ? this.closeServer(entry.server) : Promise.resolve()));
12615
+ this.entries.clear();
12616
+ this.lifetime.dispose();
12617
+ }
12618
+ /** 单个连接只关闭一次,诊断失败不得影响资源清理。 */
12619
+ closeServer(server) {
12620
+ const existing = this.closing.get(server);
12621
+ if (existing)
12622
+ return existing;
12623
+ const closing = Promise.resolve().then(() => server.close?.()).then(() => void 0).catch((error40) => {
12624
+ this.log(`[mcp] server ${server.serverName} close failed: ${String(error40)}`);
12625
+ });
12626
+ this.closing.set(server, closing);
12627
+ return closing;
12628
+ }
12629
+ log(message) {
12630
+ try {
12631
+ this.debugLog(message, EDebugLogScope.MCP);
12632
+ } catch {
12633
+ }
12420
12634
  }
12421
12635
  // —— 内部:连接与缓存 ——
12422
12636
  /** 确保某 server 已连;返回 connected 条目,依失败返回 null(不抛错)。 */
12423
12637
  async ensureEntry(serverName, signal) {
12638
+ this.lifetime.context.throwIfAborted();
12639
+ signal?.throwIfAborted();
12424
12640
  const existing = this.entries.get(serverName);
12425
12641
  if (existing) {
12426
12642
  return existing.status === "connected" ? existing : null;
12427
12643
  }
12428
- let promise2 = this.inFlight.get(serverName);
12429
- if (!promise2) {
12430
- promise2 = this.connect(serverName, signal).finally(() => {
12431
- this.inFlight.delete(serverName);
12644
+ let attempt = this.inFlight.get(serverName);
12645
+ if (!attempt) {
12646
+ const scope = new CancellationScope({ parent: this.lifetime.context });
12647
+ attempt = {
12648
+ promise: Promise.resolve({}),
12649
+ scope,
12650
+ waiters: 0,
12651
+ settled: false,
12652
+ abandoned: false
12653
+ };
12654
+ const current = attempt;
12655
+ this.inFlight.set(serverName, current);
12656
+ current.promise = this.connect(serverName, scope.context.signal, current).finally(() => {
12657
+ current.settled = true;
12658
+ if (this.inFlight.get(serverName) === current)
12659
+ this.inFlight.delete(serverName);
12660
+ scope.dispose();
12432
12661
  });
12433
- this.inFlight.set(serverName, promise2);
12434
12662
  }
12435
- const entry = await promise2;
12436
- return entry.status === "connected" ? entry : null;
12663
+ attempt.waiters += 1;
12664
+ try {
12665
+ const entry = await waitWithSignal(attempt.promise, signal);
12666
+ return entry.status === "connected" ? entry : null;
12667
+ } finally {
12668
+ attempt.waiters -= 1;
12669
+ if (attempt.waiters === 0 && !attempt.settled) {
12670
+ attempt.abandoned = true;
12671
+ if (this.inFlight.get(serverName) === attempt)
12672
+ this.inFlight.delete(serverName);
12673
+ attempt.scope.cancel(new DOMException("MCP \u5EFA\u8FDE\u5DF2\u65E0\u7B49\u5F85\u8005", "AbortError"));
12674
+ }
12675
+ }
12437
12676
  }
12438
12677
  /** 连单个 server 并 listTools;按 spec.allowedTools 过滤后缓存;失败记为 failed。 */
12439
- async connect(serverName, _signal) {
12678
+ async connect(serverName, signal, attempt) {
12679
+ const isCurrent = () => !attempt.abandoned && this.inFlight.get(serverName) === attempt && !this.lifetime.context.signal.aborted;
12440
12680
  const spec = this.specByServerName.get(serverName);
12441
12681
  if (!spec) {
12442
12682
  const entry = {
@@ -12445,11 +12685,19 @@ var init_mcpProxyTool = __esm({
12445
12685
  status: "failed",
12446
12686
  error: `unknown serverName: ${serverName}`
12447
12687
  };
12448
- this.entries.set(serverName, entry);
12688
+ if (isCurrent())
12689
+ this.entries.set(serverName, entry);
12449
12690
  this.debugLog(`[mcp] server ${serverName} unknown serverName`, EDebugLogScope.MCP);
12450
12691
  return entry;
12451
12692
  }
12693
+ let server;
12694
+ const onAbort = () => {
12695
+ if (server)
12696
+ void this.closeServer(server);
12697
+ };
12698
+ signal.addEventListener("abort", onAbort, { once: true });
12452
12699
  try {
12700
+ signal.throwIfAborted();
12453
12701
  const synthetic = {
12454
12702
  resourceId: spec.serverName,
12455
12703
  resourceType: EResourceType.MCP,
@@ -12461,18 +12709,35 @@ var init_mcpProxyTool = __esm({
12461
12709
  argsMappingRules: spec.argsMappingRules
12462
12710
  }
12463
12711
  };
12464
- const servers = await this.provider.servers([synthetic]);
12465
- const server = servers[0];
12712
+ const pending = this.provider.servers([synthetic], signal).then((servers2) => {
12713
+ server = servers2[0];
12714
+ if (signal.aborted) {
12715
+ for (const item of servers2)
12716
+ void this.closeServer(item);
12717
+ signal.throwIfAborted();
12718
+ }
12719
+ return servers2;
12720
+ });
12721
+ const servers = await waitWithSignal(pending, signal);
12722
+ server = servers[0];
12466
12723
  if (!server) {
12467
12724
  throw new Error(`provider returned no server for ${spec.serverName}`);
12468
12725
  }
12469
- const all = await server.listTools();
12726
+ const all = await waitWithSignal(server.listTools(signal), signal);
12727
+ signal.throwIfAborted();
12470
12728
  const tools = spec.allowedTools ? all.filter((tool) => spec.allowedTools.has(tool.name)) : all;
12471
12729
  const entry = { server, tools, status: "connected" };
12730
+ if (!isCurrent()) {
12731
+ void this.closeServer(server);
12732
+ signal.throwIfAborted();
12733
+ return { server: null, tools: [], status: "failed" };
12734
+ }
12472
12735
  this.entries.set(serverName, entry);
12473
- this.debugLog(`[mcp] server ${spec.serverName} connected (${tools.length}/${all.length} tools)`, EDebugLogScope.MCP);
12736
+ this.log(`[mcp] server ${spec.serverName} connected (${tools.length}/${all.length} tools)`);
12474
12737
  return entry;
12475
12738
  } catch (error40) {
12739
+ if (server)
12740
+ void this.closeServer(server);
12476
12741
  const message = error40 instanceof Error ? error40.message : String(error40);
12477
12742
  const entry = {
12478
12743
  server: null,
@@ -12480,9 +12745,12 @@ var init_mcpProxyTool = __esm({
12480
12745
  status: "failed",
12481
12746
  error: message
12482
12747
  };
12483
- this.entries.set(serverName, entry);
12484
- this.debugLog(`[mcp] server ${spec.serverName} connect failed: ${message}`, EDebugLogScope.MCP);
12748
+ if (isCurrent())
12749
+ this.entries.set(serverName, entry);
12750
+ this.log(`[mcp] server ${spec.serverName} connect failed: ${message}`);
12485
12751
  return entry;
12752
+ } finally {
12753
+ signal.removeEventListener("abort", onAbort);
12486
12754
  }
12487
12755
  }
12488
12756
  // —— 派发 ——
@@ -12555,7 +12823,12 @@ ${lines.join("\n")}${hint}`.trim();
12555
12823
  this.recordAction(context2, "connect", "not_found", { server });
12556
12824
  return `Server "${server}" not found. Use mcp({}) to see available servers.`;
12557
12825
  }
12558
- this.entries.delete(spec.serverName);
12826
+ if (!this.inFlight.has(spec.serverName)) {
12827
+ const previous = this.entries.get(spec.serverName);
12828
+ this.entries.delete(spec.serverName);
12829
+ if (previous?.server)
12830
+ await this.closeServer(previous.server);
12831
+ }
12559
12832
  const entry = await this.ensureEntry(spec.serverName, signal);
12560
12833
  if (!entry) {
12561
12834
  this.recordAction(context2, "connect", "failed", {
@@ -13063,7 +13336,7 @@ var init_hookRegistry = __esm({
13063
13336
  "use strict";
13064
13337
  DEFAULT_HOOK_ORDER = 100;
13065
13338
  DEFAULT_HOOK_TIMEOUT_MS = 1e3;
13066
- MAX_HOOK_TIMEOUT_MS = 5e3;
13339
+ MAX_HOOK_TIMEOUT_MS = 6e3;
13067
13340
  }
13068
13341
  });
13069
13342
 
@@ -13221,6 +13494,8 @@ var init_hookDispatcher = __esm({
13221
13494
  "use strict";
13222
13495
  init_telemetry();
13223
13496
  import_node_crypto3 = require("node:crypto");
13497
+ init_abort();
13498
+ init_cancellationScope();
13224
13499
  init_esm();
13225
13500
  init_hookContext();
13226
13501
  init_hookLog();
@@ -13477,13 +13752,17 @@ var init_hookDispatcher = __esm({
13477
13752
  writeHookLog(this.deps.debugLog, { ...baseRecord, event: "started" });
13478
13753
  let result;
13479
13754
  try {
13480
- const controller = new AbortController();
13481
13755
  const timeoutMs = resource.config.timeoutMs ?? 1e3;
13482
- const executorSignal = runtimeInput?.signal ? AbortSignal.any([controller.signal, runtimeInput.signal]) : controller.signal;
13483
- let timeout;
13756
+ const timeoutReason = new Error(`\u72B6\u6001\u578B Hook ${resource.config.name} \u6267\u884C\u8D85\u65F6(${timeoutMs}ms)`);
13757
+ const scope = new CancellationScope({
13758
+ signals: runtimeInput?.signal ? [runtimeInput.signal] : [],
13759
+ timeoutMs,
13760
+ timeoutReason
13761
+ });
13762
+ const executorSignal = scope.context.signal;
13484
13763
  let onAbort;
13485
13764
  try {
13486
- executorSignal.throwIfAborted();
13765
+ scope.context.throwIfAborted();
13487
13766
  observation = parent?.startOperation({
13488
13767
  name: ETelemetryOperationName.MIDDLEWARE,
13489
13768
  eventPrefix: ETelemetryEventPrefix.MIDDLEWARE,
@@ -13498,57 +13777,46 @@ var init_hookDispatcher = __esm({
13498
13777
  detached: false,
13499
13778
  links: []
13500
13779
  });
13501
- const aborted2 = new Promise((_, reject) => {
13502
- onAbort = () => {
13503
- cancelled = true;
13504
- observation?.record(ETelemetryEventName.HOOK_CANCEL_REQUESTED, {});
13505
- reject(executorSignal.reason instanceof Error ? executorSignal.reason : new Error("\u72B6\u6001\u578B Hook \u6267\u884C\u5DF2\u53D6\u6D88"));
13506
- };
13507
- executorSignal.addEventListener("abort", onAbort, { once: true });
13508
- });
13509
- timeout = setTimeout(() => {
13510
- timedOut = true;
13511
- observation?.record(ETelemetryEventName.HOOK_TIMEOUT_REQUESTED, {});
13512
- controller.abort(new Error(`\u72B6\u6001\u578B Hook ${resource.config.name} \u6267\u884C\u8D85\u65F6(${timeoutMs}ms)`));
13513
- }, timeoutMs);
13514
- result = await Promise.race([
13515
- this.deps.hookExecutor.execute(resource, context2, {
13516
- signal: executorSignal,
13517
- ...runtimeInput === void 0 ? {} : { runtimeInput }
13518
- }).then((value) => {
13519
- settled = true;
13520
- observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
13780
+ onAbort = () => {
13781
+ timedOut = executorSignal.reason === timeoutReason;
13782
+ cancelled = !timedOut;
13783
+ observation?.record(timedOut ? ETelemetryEventName.HOOK_TIMEOUT_REQUESTED : ETelemetryEventName.HOOK_CANCEL_REQUESTED, {});
13784
+ };
13785
+ executorSignal.addEventListener("abort", onAbort, { once: true });
13786
+ result = await waitWithSignal(this.deps.hookExecutor.execute(resource, context2, {
13787
+ signal: executorSignal,
13788
+ ...runtimeInput === void 0 ? {} : { runtimeInput }
13789
+ }).then((value) => {
13790
+ settled = true;
13791
+ observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
13792
+ [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
13793
+ [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: value.skipped ? ETelemetryHookResult.SKIPPED : value.ok ? ETelemetryHookResult.SUCCESS : ETelemetryHookResult.ERROR
13794
+ });
13795
+ if (timedOut || cancelled)
13796
+ observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
13797
+ [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
13521
13798
  [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
13522
13799
  [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: value.skipped ? ETelemetryHookResult.SKIPPED : value.ok ? ETelemetryHookResult.SUCCESS : ETelemetryHookResult.ERROR
13523
13800
  });
13524
- if (timedOut || cancelled)
13525
- observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
13526
- [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
13527
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
13528
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: value.skipped ? ETelemetryHookResult.SKIPPED : value.ok ? ETelemetryHookResult.SUCCESS : ETelemetryHookResult.ERROR
13529
- });
13530
- return value;
13531
- }, (error40) => {
13532
- settled = true;
13533
- observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
13801
+ return value;
13802
+ }, (error40) => {
13803
+ settled = true;
13804
+ observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
13805
+ [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
13806
+ [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: ETelemetryHookResult.ERROR
13807
+ });
13808
+ if (timedOut || cancelled)
13809
+ observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
13810
+ [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
13534
13811
  [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
13535
13812
  [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: ETelemetryHookResult.ERROR
13536
13813
  });
13537
- if (timedOut || cancelled)
13538
- observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
13539
- [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
13540
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
13541
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: ETelemetryHookResult.ERROR
13542
- });
13543
- throw error40;
13544
- }),
13545
- aborted2
13546
- ]);
13814
+ throw error40;
13815
+ }), executorSignal);
13547
13816
  } finally {
13548
- if (timeout !== void 0)
13549
- clearTimeout(timeout);
13550
13817
  if (onAbort !== void 0)
13551
13818
  executorSignal.removeEventListener("abort", onAbort);
13819
+ scope.dispose();
13552
13820
  }
13553
13821
  } catch (error40) {
13554
13822
  if (!settled && (timedOut || cancelled)) {
@@ -13643,6 +13911,8 @@ var init_sideEffectRunner = __esm({
13643
13911
  "use strict";
13644
13912
  init_telemetry();
13645
13913
  import_node_crypto4 = require("node:crypto");
13914
+ init_abort();
13915
+ init_cancellationScope();
13646
13916
  init_hookLog();
13647
13917
  init_hookMetrics();
13648
13918
  DEFAULT_HOOK_DRAIN_BUDGET_MS = 100;
@@ -13663,16 +13933,21 @@ var init_sideEffectRunner = __esm({
13663
13933
  return this.pending.size;
13664
13934
  }
13665
13935
  schedule(task) {
13666
- const controller = new AbortController();
13667
13936
  let timedOut = false;
13668
- const timer = setTimeout(() => {
13669
- timedOut = true;
13670
- controller.abort();
13671
- }, task.timeoutMs);
13672
- timer.unref?.();
13673
- const promise2 = this.runTask(task, controller.signal, () => timedOut).catch(() => {
13937
+ const timeoutReason = new DOMException("\u65C1\u8DEF Hook \u6267\u884C\u8D85\u65F6", "TimeoutError");
13938
+ const scope = new CancellationScope({
13939
+ timeoutMs: task.timeoutMs,
13940
+ timeoutReason,
13941
+ ref: false
13942
+ });
13943
+ const onAbort = () => {
13944
+ timedOut = scope.context.signal.reason === timeoutReason;
13945
+ };
13946
+ scope.context.signal.addEventListener("abort", onAbort, { once: true });
13947
+ const promise2 = this.runTask(task, scope.context.signal, () => timedOut).catch(() => {
13674
13948
  }).finally(() => {
13675
- clearTimeout(timer);
13949
+ scope.context.signal.removeEventListener("abort", onAbort);
13950
+ scope.dispose();
13676
13951
  this.pending.delete(promise2);
13677
13952
  });
13678
13953
  this.pending.add(promise2);
@@ -13696,15 +13971,22 @@ var init_sideEffectRunner = __esm({
13696
13971
  traceId: this.attribution.traceId
13697
13972
  }
13698
13973
  });
13699
- let timer;
13700
- const timeout = new Promise((resolve) => {
13701
- timer = setTimeout(() => resolve("timeout"), options.timeoutMs);
13702
- timer.unref?.();
13703
- });
13704
13974
  const settled = Promise.allSettled(this.pending).then(() => "completed");
13705
- const outcome = await Promise.race([settled, timeout]);
13706
- if (timer !== void 0)
13707
- clearTimeout(timer);
13975
+ let outcome = "timeout";
13976
+ if (options.timeoutMs > 0) {
13977
+ const scope = new CancellationScope({
13978
+ timeoutMs: options.timeoutMs,
13979
+ ref: false
13980
+ });
13981
+ try {
13982
+ outcome = await waitWithSignal(settled, scope.context.signal);
13983
+ } catch (error40) {
13984
+ if (!scope.context.signal.aborted)
13985
+ throw error40;
13986
+ } finally {
13987
+ scope.dispose();
13988
+ }
13989
+ }
13708
13990
  const costMs = this.now() - startedAt;
13709
13991
  const completed = outcome === "completed";
13710
13992
  writeHookLog(this.debugLog, {
@@ -14514,31 +14796,13 @@ function throwIfWebSearchAborted(signal) {
14514
14796
  throw new DOMException("\u5168\u7F51\u641C\u7D22\u5DF2\u53D6\u6D88", "AbortError");
14515
14797
  }
14516
14798
  async function awaitWebSearchOperation(operation, signal) {
14517
- signal?.throwIfAborted();
14518
- if (!signal)
14519
- return operation();
14520
- let onAbort = () => {
14521
- };
14522
- const cancelled = new Promise((_, reject) => {
14523
- onAbort = () => reject(signal.reason);
14524
- signal.addEventListener("abort", onAbort, { once: true });
14525
- });
14526
- try {
14527
- return await Promise.race([
14528
- Promise.resolve().then(() => {
14529
- signal.throwIfAborted();
14530
- return operation();
14531
- }),
14532
- cancelled
14533
- ]);
14534
- } finally {
14535
- signal.removeEventListener("abort", onAbort);
14536
- }
14799
+ return waitWithSignal(operation, signal);
14537
14800
  }
14538
14801
  var WEB_SEARCH_TOOL_NAME, WEB_SEARCH_QUERY_MAX_LENGTH, WEB_SEARCH_TOP_K_DEFAULT, WEB_SEARCH_TOP_K_MAX, WEB_SEARCH_ERRORS, WebSearchError;
14539
14802
  var init_webSearchTools = __esm({
14540
14803
  "../linkque-agent-runtime/dist/esm/core/webSearchTools.js"() {
14541
14804
  "use strict";
14805
+ init_abort();
14542
14806
  WEB_SEARCH_TOOL_NAME = "web_search";
14543
14807
  WEB_SEARCH_QUERY_MAX_LENGTH = 2048;
14544
14808
  WEB_SEARCH_TOP_K_DEFAULT = 5;
@@ -32592,6 +32856,24 @@ var require_dist = __commonJS({
32592
32856
  }
32593
32857
  });
32594
32858
 
32859
+ // ../linkque-agent-runtime/dist/esm/impl/abortableDelay.js
32860
+ async function abortableDelay(delayMs, signal, ref = true) {
32861
+ signal?.throwIfAborted();
32862
+ try {
32863
+ await (0, import_promises.setTimeout)(delayMs, void 0, { signal, ref });
32864
+ } catch (error40) {
32865
+ signal?.throwIfAborted();
32866
+ throw error40;
32867
+ }
32868
+ }
32869
+ var import_promises;
32870
+ var init_abortableDelay = __esm({
32871
+ "../linkque-agent-runtime/dist/esm/impl/abortableDelay.js"() {
32872
+ "use strict";
32873
+ import_promises = require("node:timers/promises");
32874
+ }
32875
+ });
32876
+
32595
32877
  // ../../node_modules/zod/index.js
32596
32878
  var init_zod = __esm({
32597
32879
  "../../node_modules/zod/index.js"() {
@@ -49321,7 +49603,7 @@ var init_toolObservation = __esm({
49321
49603
  });
49322
49604
 
49323
49605
  // ../linkque-agent-runtime/dist/esm/impl/agent/pi/piTelemetry.js
49324
- async function* observeProviderStream(source, observation, signal) {
49606
+ async function* observeProviderStream(source, observation, signal, logical) {
49325
49607
  const started = performance.now();
49326
49608
  let chunks = 0;
49327
49609
  let textChars = 0;
@@ -49352,6 +49634,7 @@ async function* observeProviderStream(source, observation, signal) {
49352
49634
  if (!ended && (event.type === "done" || event.type === "error")) {
49353
49635
  ended = true;
49354
49636
  const message = event.type === "done" ? event.message : event.error;
49637
+ recordContentSection(logical, ETelemetryContentSection.MODEL_OUT_RAW, message.content, event.type === "done" ? "available" : "partial");
49355
49638
  observation.record(ETelemetryEventName.MODEL_USAGE_RECORDED, projectProviderUsage(message.usage));
49356
49639
  observation.finish(event.type === "done" ? ETelemetryOutcome.SUCCESS : signal?.aborted ? ETelemetryOutcome.CANCELLED : ETelemetryOutcome.ERROR, {
49357
49640
  [ETelemetryAttribute.GEN_AI_RESPONSE_MODEL]: message.model,
@@ -49385,6 +49668,26 @@ async function* observeProviderStream(source, observation, signal) {
49385
49668
  });
49386
49669
  }
49387
49670
  }
49671
+ function summarizeModelInput(context2) {
49672
+ return {
49673
+ systemPrompt: context2.systemPrompt ? previewModelInputText(context2.systemPrompt) : void 0,
49674
+ messageCount: context2.messages.length,
49675
+ messages: context2.messages.slice(-20).map((message) => ({
49676
+ role: message.role,
49677
+ content: typeof message.content === "string" ? previewModelInputText(message.content) : message.content.slice(0, 20).map((part) => {
49678
+ if (part.type === "text")
49679
+ return { type: part.type, ...previewModelInputText(part.text) };
49680
+ if (part.type === "toolCall")
49681
+ return { type: part.type, name: part.name };
49682
+ return { type: part.type };
49683
+ }),
49684
+ omittedContentCount: typeof message.content === "string" ? 0 : Math.max(0, message.content.length - 20)
49685
+ })),
49686
+ omittedMessageCount: Math.max(0, context2.messages.length - 20),
49687
+ toolNames: context2.tools?.slice(0, 50).map((tool) => tool.name) ?? [],
49688
+ omittedToolCount: Math.max(0, (context2.tools?.length ?? 0) - 50)
49689
+ };
49690
+ }
49388
49691
  function projectProviderUsage(usage) {
49389
49692
  const source = usage && typeof usage === "object" ? usage : {};
49390
49693
  const result = {
@@ -49410,12 +49713,13 @@ function projectProviderUsage(usage) {
49410
49713
  }
49411
49714
  return result;
49412
49715
  }
49413
- var import_node_crypto7, PiTelemetry;
49716
+ var import_node_crypto7, PiTelemetry, previewModelInputText;
49414
49717
  var init_piTelemetry = __esm({
49415
49718
  "../linkque-agent-runtime/dist/esm/impl/agent/pi/piTelemetry.js"() {
49416
49719
  "use strict";
49417
49720
  init_telemetry();
49418
49721
  init_telemetryEnums2();
49722
+ init_contentRecording();
49419
49723
  init_toolObservation();
49420
49724
  import_node_crypto7 = require("node:crypto");
49421
49725
  PiTelemetry = class {
@@ -49567,6 +49871,11 @@ var init_piTelemetry = __esm({
49567
49871
  });
49568
49872
  }
49569
49873
  };
49874
+ previewModelInputText = (value) => ({
49875
+ length: value.length,
49876
+ text: value.slice(0, 256),
49877
+ truncated: value.length > 256
49878
+ });
49570
49879
  }
49571
49880
  });
49572
49881
 
@@ -49920,10 +50229,10 @@ var init_values = __esm({
49920
50229
  });
49921
50230
 
49922
50231
  // ../../node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs
49923
- var sleep2;
50232
+ var sleep;
49924
50233
  var init_sleep = __esm({
49925
50234
  "../../node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"() {
49926
- sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
50235
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
49927
50236
  }
49928
50237
  });
49929
50238
 
@@ -56276,7 +56585,7 @@ var init_client = __esm({
56276
56585
  const maxRetries = options.maxRetries ?? this.maxRetries;
56277
56586
  timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
56278
56587
  }
56279
- await sleep2(timeoutMillis);
56588
+ await sleep(timeoutMillis);
56280
56589
  return this.makeRequest(options, retriesRemaining - 1, requestLogID);
56281
56590
  }
56282
56591
  calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
@@ -58974,10 +59283,10 @@ var init_values2 = __esm({
58974
59283
  });
58975
59284
 
58976
59285
  // ../../node_modules/openai/internal/utils/sleep.mjs
58977
- var sleep3;
59286
+ var sleep2;
58978
59287
  var init_sleep2 = __esm({
58979
59288
  "../../node_modules/openai/internal/utils/sleep.mjs"() {
58980
- sleep3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
59289
+ sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
58981
59290
  }
58982
59291
  });
58983
59292
 
@@ -63431,7 +63740,7 @@ var init_runs = __esm({
63431
63740
  }
63432
63741
  }
63433
63742
  }
63434
- await sleep3(sleepInterval);
63743
+ await sleep2(sleepInterval);
63435
63744
  break;
63436
63745
  case "requires_action":
63437
63746
  case "incomplete":
@@ -64088,7 +64397,7 @@ var init_files3 = __esm({
64088
64397
  const start = Date.now();
64089
64398
  let file2 = await this.retrieve(id);
64090
64399
  while (!file2.status || !TERMINAL_STATES.has(file2.status)) {
64091
- await sleep3(pollInterval);
64400
+ await sleep2(pollInterval);
64092
64401
  file2 = await this.retrieve(id);
64093
64402
  if (Date.now() - start > maxWait) {
64094
64403
  throw new APIConnectionTimeoutError2({
@@ -65609,7 +65918,7 @@ var init_file_batches = __esm({
65609
65918
  }
65610
65919
  }
65611
65920
  }
65612
- await sleep3(sleepInterval);
65921
+ await sleep2(sleepInterval);
65613
65922
  break;
65614
65923
  case "failed":
65615
65924
  case "cancelled":
@@ -65754,7 +66063,7 @@ var init_files4 = __esm({
65754
66063
  }
65755
66064
  }
65756
66065
  }
65757
- await sleep3(sleepInterval);
66066
+ await sleep2(sleepInterval);
65758
66067
  break;
65759
66068
  case "failed":
65760
66069
  case "completed":
@@ -66455,7 +66764,7 @@ var init_client2 = __esm({
66455
66764
  const maxRetries = options.maxRetries ?? this.maxRetries;
66456
66765
  timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
66457
66766
  }
66458
- await sleep3(timeoutMillis);
66767
+ await sleep2(timeoutMillis);
66459
66768
  return this.makeRequest(options, retriesRemaining - 1, requestLogID);
66460
66769
  }
66461
66770
  calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
@@ -68339,10 +68648,10 @@ var require_retry3 = __commonJS({
68339
68648
  if (!await shouldRetryFn(err3)) {
68340
68649
  return { shouldRetry: false, config: err3.config };
68341
68650
  }
68342
- const delay2 = getNextRetryDelay(config2);
68651
+ const delay3 = getNextRetryDelay(config2);
68343
68652
  err3.config.retryConfig.currentRetryAttempt += 1;
68344
- const backoff = config2.retryBackoff ? config2.retryBackoff(err3, delay2) : new Promise((resolve) => {
68345
- setTimeout(resolve, delay2);
68653
+ const backoff = config2.retryBackoff ? config2.retryBackoff(err3, delay3) : new Promise((resolve) => {
68654
+ setTimeout(resolve, delay3);
68346
68655
  });
68347
68656
  if (config2.onRetryAttempt) {
68348
68657
  await config2.onRetryAttempt(err3);
@@ -76130,7 +76439,7 @@ var require_gaxios = __commonJS({
76130
76439
  var retry_js_1 = require_retry3();
76131
76440
  var stream_1 = require("stream");
76132
76441
  var interceptor_js_1 = require_interceptor();
76133
- var randomUUID9 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
76442
+ var randomUUID10 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
76134
76443
  var HTTP_STATUS_NO_CONTENT = 204;
76135
76444
  var Gaxios = class {
76136
76445
  agentCache = /* @__PURE__ */ new Map();
@@ -76403,7 +76712,7 @@ var require_gaxios = __commonJS({
76403
76712
  */
76404
76713
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
76405
76714
  if (opts.multipart?.length) {
76406
- const boundary = await randomUUID9();
76715
+ const boundary = await randomUUID10();
76407
76716
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
76408
76717
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
76409
76718
  } else if (shouldDirectlyPassData) {
@@ -100648,7 +100957,7 @@ async function uploadBlobInternal(file2, uploadUrl, apiClient, httpOptions) {
100648
100957
  break;
100649
100958
  }
100650
100959
  retryCount++;
100651
- await sleep4(currentDelayMs);
100960
+ await sleep3(currentDelayMs);
100652
100961
  currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
100653
100962
  }
100654
100963
  offset += chunkSize;
@@ -100665,7 +100974,7 @@ async function getBlobStat(file2) {
100665
100974
  const fileStat = { size: file2.size, type: file2.type };
100666
100975
  return fileStat;
100667
100976
  }
100668
- function sleep4(ms) {
100977
+ function sleep3(ms) {
100669
100978
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
100670
100979
  }
100671
100980
  function resolveCloudFlag(options) {
@@ -100709,16 +101018,16 @@ function getApiKeyFromEnv() {
100709
101018
  }
100710
101019
  return envGoogleApiKey || envGeminiApiKey || void 0;
100711
101020
  }
100712
- var import_p_retry, import_google_auth_library, import_fs2, fs2, import_promises4, import_node_stream3, import_promises5, path$1, _defaultBaseGeminiUrl, _defaultBaseVertexUrl, BaseModule, Language, Outcome, FunctionResponseScheduling, Type, Environment, AuthType, HttpElementLocation, ApiSpec, PhishBlockThreshold, Behavior, DynamicRetrievalConfigMode, FunctionCallingConfigMode, ThinkingLevel, PersonGeneration, ProminentPeople, HarmCategory, HarmBlockMethod, HarmBlockThreshold, FinishReason, HarmProbability, HarmSeverity, UrlRetrievalStatus, BlockedReason, TrafficType, Modality, ModelStage, MediaResolution, TuningMode, AdapterSize, JobState, TuningJobState, AggregationMetric, PairwiseChoice, TuningTask, DocumentState, PartMediaResolutionLevel, ToolType, ResourceScope, ServiceTier, FeatureSelectionPreference, EmbeddingApiType, SafetyFilterLevel, ImagePromptLanguage, MaskReferenceMode, ControlReferenceType, SubjectReferenceType, EditMode, SegmentMode, VideoGenerationReferenceType, VideoGenerationMaskMode, VideoCompressionQuality, ImageResizeMode, TuningMethod, FileState, FileSource, TurnCompleteReason, MediaModality, VadSignalType, VoiceActivityType, StartSensitivity, EndSensitivity, ActivityHandling, TurnCoverage, Scale, MusicGenerationMode, LiveMusicPlaybackControl, HttpResponse, GenerateContentResponse, EmbedContentResponse, GenerateImagesResponse, EditImageResponse, UpscaleImageResponse, RecontextImageResponse, SegmentImageResponse, ListModelsResponse, DeleteModelResponse, CountTokensResponse, ComputeTokensResponse, GenerateVideosOperation, ListTuningJobsResponse, CancelTuningJobResponse, DeleteCachedContentResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, UploadToFileSearchStoreResumableResponse, ImportFileOperation, ListFilesResponse, CreateFileResponse, DeleteFileResponse, RegisterFilesResponse, ListBatchJobsResponse, LiveServerMessage, LiveMusicServerMessage, UploadToFileSearchStoreOperation, PagedItem, Pager, Batches4, Caches, Chats, Chat2, ApiError, Files5, CONTENT_TYPE_HEADER, SERVER_TIMEOUT_HEADER, USER_AGENT_HEADER, GOOGLE_API_CLIENT_HEADER, SDK_VERSION, LIBRARY_LABEL, VERTEX_AI_API_DEFAULT_VERSION, GOOGLE_AI_API_DEFAULT_VERSION, MULTI_REGIONAL_LOCATIONS, DEFAULT_RETRY_ATTEMPTS, DEFAULT_RETRY_HTTP_STATUS_CODES, ApiClient, MCP_LABEL, hasMcpToolUsageFromMcpToTool, McpCallableTool, LiveMusic, LiveMusicSession, FUNCTION_RESPONSE_REQUIRES_ID, Live, defaultLiveSendClientContentParamerters, Session, DEFAULT_MAX_REMOTE_CALLS, Models4, Operations, Tokens, Documents, FileSearchStores, uuid4Internal, uuid44, castToError3, GeminiNextGenAPIClientError, APIError3, APIUserAbortError3, APIConnectionError3, APIConnectionTimeoutError3, BadRequestError3, AuthenticationError3, PermissionDeniedError3, NotFoundError3, ConflictError3, UnprocessableEntityError3, RateLimitError3, InternalServerError3, startsWithSchemeRegexp3, isAbsoluteURL3, isArrayInternal, isArray3, isReadonlyArrayInternal, isReadonlyArray3, validatePositiveInteger3, safeJSON3, sleep$1, FallbackEncoder3, VERSION4, checkFileSupport3, isAsyncIterable3, isBlobLike3, isFileLike3, isResponseLike3, APIResource3, EMPTY3, createPathTagFunction3, path7, BaseInteractions, Interactions, BaseWebhooks, Webhooks2, encodeUTF8_3, decodeUTF8_3, LineDecoder3, levelNumbers3, parseLogLevel3, noopLogger3, cachedLoggers3, formatRequestDetails3, Stream5, SSEDecoder3, APIPromise3, brand_privateNullableHeaders3, buildHeaders3, readEnv3, _a5, BaseGeminiNextGenAPIClient, GeminiNextGenAPIClient, GOOGLE_API_KEY_HEADER, REQUIRED_VERTEX_AI_SCOPE, NodeAuth, NodeDownloader, NodeWebSocketFactory, NodeWebSocket, Tunings, MAX_CHUNK_SIZE, MAX_RETRY_COUNT, INITIAL_RETRY_DELAY_MS, DELAY_MULTIPLIER, X_GOOG_UPLOAD_STATUS_HEADER_FIELD, NodeUploader, NodeFiles, LANGUAGE_LABEL_PREFIX, GoogleGenAI;
101021
+ var import_p_retry, import_google_auth_library, import_fs2, fs2, import_promises5, import_node_stream3, import_promises6, path$1, _defaultBaseGeminiUrl, _defaultBaseVertexUrl, BaseModule, Language, Outcome, FunctionResponseScheduling, Type, Environment, AuthType, HttpElementLocation, ApiSpec, PhishBlockThreshold, Behavior, DynamicRetrievalConfigMode, FunctionCallingConfigMode, ThinkingLevel, PersonGeneration, ProminentPeople, HarmCategory, HarmBlockMethod, HarmBlockThreshold, FinishReason, HarmProbability, HarmSeverity, UrlRetrievalStatus, BlockedReason, TrafficType, Modality, ModelStage, MediaResolution, TuningMode, AdapterSize, JobState, TuningJobState, AggregationMetric, PairwiseChoice, TuningTask, DocumentState, PartMediaResolutionLevel, ToolType, ResourceScope, ServiceTier, FeatureSelectionPreference, EmbeddingApiType, SafetyFilterLevel, ImagePromptLanguage, MaskReferenceMode, ControlReferenceType, SubjectReferenceType, EditMode, SegmentMode, VideoGenerationReferenceType, VideoGenerationMaskMode, VideoCompressionQuality, ImageResizeMode, TuningMethod, FileState, FileSource, TurnCompleteReason, MediaModality, VadSignalType, VoiceActivityType, StartSensitivity, EndSensitivity, ActivityHandling, TurnCoverage, Scale, MusicGenerationMode, LiveMusicPlaybackControl, HttpResponse, GenerateContentResponse, EmbedContentResponse, GenerateImagesResponse, EditImageResponse, UpscaleImageResponse, RecontextImageResponse, SegmentImageResponse, ListModelsResponse, DeleteModelResponse, CountTokensResponse, ComputeTokensResponse, GenerateVideosOperation, ListTuningJobsResponse, CancelTuningJobResponse, DeleteCachedContentResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, UploadToFileSearchStoreResumableResponse, ImportFileOperation, ListFilesResponse, CreateFileResponse, DeleteFileResponse, RegisterFilesResponse, ListBatchJobsResponse, LiveServerMessage, LiveMusicServerMessage, UploadToFileSearchStoreOperation, PagedItem, Pager, Batches4, Caches, Chats, Chat2, ApiError, Files5, CONTENT_TYPE_HEADER, SERVER_TIMEOUT_HEADER, USER_AGENT_HEADER, GOOGLE_API_CLIENT_HEADER, SDK_VERSION, LIBRARY_LABEL, VERTEX_AI_API_DEFAULT_VERSION, GOOGLE_AI_API_DEFAULT_VERSION, MULTI_REGIONAL_LOCATIONS, DEFAULT_RETRY_ATTEMPTS, DEFAULT_RETRY_HTTP_STATUS_CODES, ApiClient, MCP_LABEL, hasMcpToolUsageFromMcpToTool, McpCallableTool, LiveMusic, LiveMusicSession, FUNCTION_RESPONSE_REQUIRES_ID, Live, defaultLiveSendClientContentParamerters, Session, DEFAULT_MAX_REMOTE_CALLS, Models4, Operations, Tokens, Documents, FileSearchStores, uuid4Internal, uuid44, castToError3, GeminiNextGenAPIClientError, APIError3, APIUserAbortError3, APIConnectionError3, APIConnectionTimeoutError3, BadRequestError3, AuthenticationError3, PermissionDeniedError3, NotFoundError3, ConflictError3, UnprocessableEntityError3, RateLimitError3, InternalServerError3, startsWithSchemeRegexp3, isAbsoluteURL3, isArrayInternal, isArray3, isReadonlyArrayInternal, isReadonlyArray3, validatePositiveInteger3, safeJSON3, sleep$1, FallbackEncoder3, VERSION4, checkFileSupport3, isAsyncIterable3, isBlobLike3, isFileLike3, isResponseLike3, APIResource3, EMPTY3, createPathTagFunction3, path7, BaseInteractions, Interactions, BaseWebhooks, Webhooks2, encodeUTF8_3, decodeUTF8_3, LineDecoder3, levelNumbers3, parseLogLevel3, noopLogger3, cachedLoggers3, formatRequestDetails3, Stream5, SSEDecoder3, APIPromise3, brand_privateNullableHeaders3, buildHeaders3, readEnv3, _a5, BaseGeminiNextGenAPIClient, GeminiNextGenAPIClient, GOOGLE_API_KEY_HEADER, REQUIRED_VERTEX_AI_SCOPE, NodeAuth, NodeDownloader, NodeWebSocketFactory, NodeWebSocket, Tunings, MAX_CHUNK_SIZE, MAX_RETRY_COUNT, INITIAL_RETRY_DELAY_MS, DELAY_MULTIPLIER, X_GOOG_UPLOAD_STATUS_HEADER_FIELD, NodeUploader, NodeFiles, LANGUAGE_LABEL_PREFIX, GoogleGenAI;
100713
101022
  var init_node2 = __esm({
100714
101023
  "../../node_modules/@google/genai/dist/node/index.mjs"() {
100715
101024
  import_p_retry = __toESM(require_p_retry(), 1);
100716
101025
  import_google_auth_library = __toESM(require_src12(), 1);
100717
101026
  import_fs2 = require("fs");
100718
101027
  fs2 = __toESM(require("fs/promises"), 1);
100719
- import_promises4 = require("fs/promises");
101028
+ import_promises5 = require("fs/promises");
100720
101029
  import_node_stream3 = require("node:stream");
100721
- import_promises5 = require("node:stream/promises");
101030
+ import_promises6 = require("node:stream/promises");
100722
101031
  init_wrapper();
100723
101032
  path$1 = __toESM(require("path"), 1);
100724
101033
  _defaultBaseGeminiUrl = void 0;
@@ -107272,10 +107581,10 @@ ${underline}`);
107272
107581
  const writer = (0, import_fs2.createWriteStream)(params.downloadPath);
107273
107582
  const body = import_node_stream3.Readable.fromWeb(response.responseInternal.body);
107274
107583
  body.pipe(writer);
107275
- await (0, import_promises5.finished)(writer);
107584
+ await (0, import_promises6.finished)(writer);
107276
107585
  } else {
107277
107586
  try {
107278
- await (0, import_promises4.writeFile)(params.downloadPath, response, {
107587
+ await (0, import_promises5.writeFile)(params.downloadPath, response, {
107279
107588
  encoding: "base64"
107280
107589
  });
107281
107590
  } catch (error40) {
@@ -107788,7 +108097,7 @@ ${underline}`);
107788
108097
  break;
107789
108098
  }
107790
108099
  retryCount++;
107791
- await sleep4(currentDelayMs);
108100
+ await sleep3(currentDelayMs);
107792
108101
  currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
107793
108102
  }
107794
108103
  offset += bytesRead;
@@ -116332,7 +116641,7 @@ async function retryBackoff(fn, strategy) {
116332
116641
  retryInterval = initialInterval * Math.pow(x2, exponent) + Math.random() * 1e3;
116333
116642
  }
116334
116643
  const d = Math.min(retryInterval, maxInterval);
116335
- await delay(d);
116644
+ await delay2(d);
116336
116645
  x2++;
116337
116646
  }
116338
116647
  }
@@ -116353,8 +116662,8 @@ function retryIntervalFromResponse(res) {
116353
116662
  }
116354
116663
  return 0;
116355
116664
  }
116356
- async function delay(delay2) {
116357
- return new Promise((resolve) => setTimeout(resolve, delay2));
116665
+ async function delay2(delay3) {
116666
+ return new Promise((resolve) => setTimeout(resolve, delay3));
116358
116667
  }
116359
116668
  var defaultBackoff, PermanentError, TemporaryError, codeRangeRE2;
116360
116669
  var init_retries = __esm({
@@ -156361,7 +156670,7 @@ function capRetryDelayMs(delayMs, options) {
156361
156670
  const maxRetryDelayMs = options?.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;
156362
156671
  return maxRetryDelayMs > 0 ? Math.min(delayMs, maxRetryDelayMs) : delayMs;
156363
156672
  }
156364
- function sleep5(ms, signal) {
156673
+ function sleep4(ms, signal) {
156365
156674
  return new Promise((resolve, reject) => {
156366
156675
  if (signal?.aborted) {
156367
156676
  reject(new Error("Request was aborted"));
@@ -157364,7 +157673,7 @@ var init_openai_codex_responses = __esm({
157364
157673
  if (attempt < maxRetries && isRetryableError(response.status, errorText)) {
157365
157674
  const retryAfterDelayMs = getRetryAfterDelayMs(response.headers);
157366
157675
  const delayMs = retryAfterDelayMs === void 0 ? BASE_DELAY_MS * 2 ** attempt : response.status === 429 ? capRetryDelayMs(retryAfterDelayMs, options) : retryAfterDelayMs;
157367
- await sleep5(delayMs, options?.signal);
157676
+ await sleep4(delayMs, options?.signal);
157368
157677
  continue;
157369
157678
  }
157370
157679
  const fakeResponse = new Response(errorText, {
@@ -157382,7 +157691,7 @@ var init_openai_codex_responses = __esm({
157382
157691
  lastError = error40 instanceof Error ? error40 : new Error(String(error40));
157383
157692
  if (attempt < maxRetries && !lastError.message.includes("usage limit")) {
157384
157693
  const delayMs = BASE_DELAY_MS * 2 ** attempt;
157385
- await sleep5(delayMs, options?.signal);
157694
+ await sleep4(delayMs, options?.signal);
157386
157695
  continue;
157387
157696
  }
157388
157697
  throw lastError;
@@ -205076,27 +205385,11 @@ var init_dist4 = __esm({
205076
205385
  });
205077
205386
 
205078
205387
  // ../linkque-agent-runtime/dist/esm/impl/agent/pi/llmRequestThrottle.js
205079
- function delayWithSignal(delayMs, signal) {
205080
- return new Promise((resolve, reject) => {
205081
- if (signal?.aborted) {
205082
- reject(signal.reason);
205083
- return;
205084
- }
205085
- const timer = setTimeout(() => {
205086
- signal?.removeEventListener("abort", onAbort);
205087
- resolve();
205088
- }, delayMs);
205089
- const onAbort = () => {
205090
- clearTimeout(timer);
205091
- reject(signal?.reason);
205092
- };
205093
- signal?.addEventListener("abort", onAbort, { once: true });
205094
- });
205095
- }
205096
205388
  var DEFAULT_LLM_REQUEST_MIN_INTERVAL_MS, LlmRequestThrottle;
205097
205389
  var init_llmRequestThrottle = __esm({
205098
205390
  "../linkque-agent-runtime/dist/esm/impl/agent/pi/llmRequestThrottle.js"() {
205099
205391
  "use strict";
205392
+ init_abortableDelay();
205100
205393
  DEFAULT_LLM_REQUEST_MIN_INTERVAL_MS = 1e3;
205101
205394
  LlmRequestThrottle = class {
205102
205395
  minIntervalMs;
@@ -205109,7 +205402,7 @@ var init_llmRequestThrottle = __esm({
205109
205402
  const configured = options.minIntervalMs ?? DEFAULT_LLM_REQUEST_MIN_INTERVAL_MS;
205110
205403
  this.minIntervalMs = Number.isFinite(configured) && configured > 0 ? Math.floor(configured) : 0;
205111
205404
  this.now = options.now ?? Date.now;
205112
- this.delay = options.delay ?? delayWithSignal;
205405
+ this.delay = options.delay ?? abortableDelay;
205113
205406
  this.onDelay = options.onDelay ?? (() => {
205114
205407
  });
205115
205408
  }
@@ -205314,6 +205607,7 @@ async function createAgentSession(options) {
205314
205607
  throw error40;
205315
205608
  }
205316
205609
  invocation = logical ? options.telemetry?.startProvider(model, logical) : void 0;
205610
+ recordContentSection(logical, ETelemetryContentSection.MODEL_INPUT_DIGEST, summarizeModelInput(context2));
205317
205611
  const spanContext = invocation?.spanContext;
205318
205612
  const tracedModel = spanContext ? {
205319
205613
  ...model,
@@ -205332,7 +205626,7 @@ async function createAgentSession(options) {
205332
205626
  });
205333
205627
  throw error40;
205334
205628
  }
205335
- const source = invocation ? observeProviderStream(rawSource, invocation, opts.signal) : rawSource;
205629
+ const source = invocation ? observeProviderStream(rawSource, invocation, opts.signal, logical) : rawSource;
205336
205630
  const observedSource = logSink ? observeModelStream(source, requestId, streamCreatedAt, logSink) : source;
205337
205631
  return options.hookRuntime ? gateModelResponseStream(observedSource, model, options.hookRuntime, () => gateState, logical) : observedSource;
205338
205632
  });
@@ -205501,6 +205795,7 @@ var init_createAgentSession = __esm({
205501
205795
  "use strict";
205502
205796
  init_telemetry();
205503
205797
  init_piTelemetry();
205798
+ init_contentRecording();
205504
205799
  init_logFailure();
205505
205800
  init_dist4();
205506
205801
  init_dist3();
@@ -206141,12 +206436,17 @@ ${history}
206141
206436
  ` : ""}\u5F53\u524D\u8F6E\uFF1A
206142
206437
  ${currentTurn}`;
206143
206438
  }
206144
- var FOLLOW_UP_QUESTION_MODEL_ID, FOLLOW_UP_QUESTION_TOOL_NAME, FOLLOW_UP_QUESTION_TIMEOUT_MS, SYSTEM_PROMPT, PiFollowUpQuestionGenerator;
206439
+ var import_node_crypto8, FOLLOW_UP_QUESTION_MODEL_ID, FOLLOW_UP_QUESTION_TOOL_NAME, FOLLOW_UP_QUESTION_TIMEOUT_MS, SYSTEM_PROMPT, PiFollowUpQuestionGenerator;
206145
206440
  var init_followUpQuestionGenerator = __esm({
206146
206441
  "../linkque-agent-runtime/dist/esm/impl/agent/pi/followUpQuestionGenerator.js"() {
206147
206442
  "use strict";
206148
206443
  init_compat2();
206444
+ init_telemetry();
206445
+ import_node_crypto8 = require("node:crypto");
206446
+ init_cancellationScope();
206149
206447
  init_followUpQuestions();
206448
+ init_contentRecording();
206449
+ init_piTelemetry();
206150
206450
  init_types();
206151
206451
  init_linkqueProvider();
206152
206452
  FOLLOW_UP_QUESTION_MODEL_ID = "Qwen3-30B-A3B-Instruct-2507";
@@ -206203,30 +206503,66 @@ var init_followUpQuestionGenerator = __esm({
206203
206503
  }
206204
206504
  ]
206205
206505
  };
206206
- const controller = new AbortController();
206207
- const timeout = setTimeout(() => controller.abort(), FOLLOW_UP_QUESTION_TIMEOUT_MS);
206506
+ const scope = new CancellationScope({
206507
+ timeoutMs: FOLLOW_UP_QUESTION_TIMEOUT_MS
206508
+ });
206509
+ const logical = input.observation?.startOperation({
206510
+ name: ETelemetryOperationName.MODEL_INVOKE,
206511
+ eventPrefix: ETelemetryEventPrefix.MODEL_INVOKE,
206512
+ attributes: {
206513
+ [ETelemetryAttribute.HARNESS_CALL_ID]: (0, import_node_crypto8.randomUUID)(),
206514
+ [ETelemetryAttribute.GEN_AI_REQUEST_MODEL]: FOLLOW_UP_QUESTION_MODEL_ID,
206515
+ [ETelemetryAttribute.GEN_AI_PROVIDER_NAME]: LINKQUE_PROVIDER_ID,
206516
+ [ETelemetryAttribute.HARNESS_MODEL_PURPOSE]: ETelemetryModelPurpose.FOLLOW_UP_QUESTION
206517
+ },
206518
+ detached: false,
206519
+ links: []
206520
+ });
206521
+ const attempt = logical?.startOperation({
206522
+ name: ETelemetryOperationName.MODEL_ATTEMPT,
206523
+ eventPrefix: ETelemetryEventPrefix.MODEL_ATTEMPT,
206524
+ attributes: {
206525
+ [ETelemetryAttribute.GEN_AI_OPERATION_NAME]: ETelemetryGenAiOperation.CHAT,
206526
+ [ETelemetryAttribute.GEN_AI_REQUEST_MODEL]: FOLLOW_UP_QUESTION_MODEL_ID,
206527
+ [ETelemetryAttribute.GEN_AI_PROVIDER_NAME]: LINKQUE_PROVIDER_ID,
206528
+ [ETelemetryAttribute.HARNESS_INVOCATION_ID]: (0, import_node_crypto8.randomUUID)(),
206529
+ [ETelemetryAttribute.HARNESS_ATTEMPT_ID]: (0, import_node_crypto8.randomUUID)(),
206530
+ [ETelemetryAttribute.HARNESS_ATTEMPT_VISIBILITY]: ETelemetryAttemptVisibility.PROVIDER_INVOCATION,
206531
+ [ETelemetryAttribute.HARNESS_TELEMETRY_SOURCE]: ETelemetrySource.PROVIDER
206532
+ },
206533
+ detached: false,
206534
+ links: []
206535
+ });
206536
+ recordContentSection(logical, ETelemetryContentSection.MODEL_INPUT_DIGEST, summarizeModelInput(context2));
206208
206537
  try {
206209
206538
  input.debugLog?.(`[follow-up] request model=${FOLLOW_UP_QUESTION_MODEL_ID} messages=${input.context.messages.length}`, EDebugLogScope.LLM);
206210
206539
  const message = await models.complete(model, context2, {
206211
206540
  apiKey: input.auth.apiKey,
206212
206541
  maxRetries: 0,
206213
206542
  maxTokens: 96,
206214
- signal: controller.signal,
206543
+ signal: scope.context.signal,
206215
206544
  temperature: 0.3,
206216
206545
  thinkingEnabled: false,
206217
206546
  timeoutMs: FOLLOW_UP_QUESTION_TIMEOUT_MS,
206218
206547
  toolChoice: { type: "tool", name: FOLLOW_UP_QUESTION_TOOL_NAME }
206219
206548
  });
206549
+ recordContentSection(logical, ETelemetryContentSection.MODEL_OUT_RAW, message.content);
206220
206550
  const toolCall = message.content.find((content) => content.type === "toolCall" && content.name === FOLLOW_UP_QUESTION_TOOL_NAME);
206221
206551
  const questions = normalizeFollowUpQuestionStrings(toolCall?.type === "toolCall" ? toolCall.arguments.questions : void 0);
206222
206552
  input.debugLog?.(`[follow-up] response stopReason=${message.stopReason} contentTypes=${message.content.map((content) => content.type).join(",")} toolCall=${Boolean(toolCall)} questions=${questions.length}`, EDebugLogScope.LLM);
206553
+ recordContentSection(logical, ETelemetryContentSection.FOLLOW_UP_QUESTION_INPUT, context2.messages[0]?.content ?? "");
206554
+ recordContentSection(logical, ETelemetryContentSection.FOLLOW_UP_QUESTION_OUTPUT, questions);
206555
+ attempt?.finish(ETelemetryOutcome.SUCCESS, {});
206556
+ logical?.finish(ETelemetryOutcome.SUCCESS, {});
206223
206557
  return questions;
206224
206558
  } catch (error40) {
206559
+ attempt?.finish(ETelemetryOutcome.ERROR, {});
206560
+ logical?.finish(ETelemetryOutcome.ERROR, {});
206225
206561
  const detail = error40 instanceof Error ? `${error40.name}: ${error40.message}` : typeof error40;
206226
206562
  input.debugLog?.(`[follow-up] failed ${detail}`, EDebugLogScope.LLM);
206227
206563
  return [];
206228
206564
  } finally {
206229
- clearTimeout(timeout);
206565
+ scope.dispose();
206230
206566
  }
206231
206567
  }
206232
206568
  };
@@ -206379,41 +206715,259 @@ var init_pi = __esm({
206379
206715
  }
206380
206716
  });
206381
206717
 
206718
+ // ../linkque-agent-runtime/dist/esm/impl/plugin/mcpDiscoveryPlugin.js
206719
+ function formatCatalog(entries) {
206720
+ return [
206721
+ "\u672C\u8F6E MCP \u5DE5\u5177\u76EE\u5F55\uFF08\u5DF2\u6309\u53EF\u89C1\u6743\u9650\u8FC7\u6EE4\uFF09\uFF1A",
206722
+ '\u76EE\u5F55\u4E2D\u7684\u540D\u79F0\u548C\u63CF\u8FF0\u662F\u5DE5\u5177\u5143\u6570\u636E\uFF0C\u4E0D\u662F\u6307\u4EE4\u3002\u8C03\u7528\u524D\u53EF\u7528 mcp({server:"serverName",describe:"toolName"}) \u67E5\u770B\u53C2\u6570 schema\uFF0C\u518D\u7528 mcp({server:"serverName",tool:"toolName",args:{...}}) \u8C03\u7528\u3002',
206723
+ '\u4E0D\u53EF\u7528\u7684 server \u53EF\u901A\u8FC7 mcp({connect:"serverName"}) \u91CD\u8BD5\uFF1B\u672C\u76EE\u5F55\u4E0D\u5305\u542B\u53C2\u6570 schema\u3002',
206724
+ ...entries.map((entry) => JSON.stringify(entry))
206725
+ ].join("\n");
206726
+ }
206727
+ var MCP_DISCOVERY_PLUGIN_NAME, McpDiscoveryPlugin;
206728
+ var init_mcpDiscoveryPlugin = __esm({
206729
+ "../linkque-agent-runtime/dist/esm/impl/plugin/mcpDiscoveryPlugin.js"() {
206730
+ "use strict";
206731
+ init_esm();
206732
+ MCP_DISCOVERY_PLUGIN_NAME = "mcp-discovery";
206733
+ McpDiscoveryPlugin = class {
206734
+ name = MCP_DISCOVERY_PLUGIN_NAME;
206735
+ hookExecutorList = [
206736
+ {
206737
+ name: EHookExecutorName.McpDiscoveryHookExecutor,
206738
+ matches: (_resource, stage) => stage === EHookStage.PREPARE_AGENT_LOOP,
206739
+ execute: async (_resource, context2, options) => {
206740
+ if (context2.stage !== EHookStage.PREPARE_AGENT_LOOP)
206741
+ return { ok: true, skipped: true };
206742
+ const input = options?.runtimeInput;
206743
+ if (!input?.discoverMcpTools)
206744
+ return { ok: false, code: "MCP_DISCOVERY_RUNTIME_INPUT_MISSING" };
206745
+ const signal = AbortSignal.any([
206746
+ ...input.signal ? [input.signal] : [],
206747
+ ...options?.signal ? [options.signal] : []
206748
+ ]);
206749
+ const entries = await input.discoverMcpTools(signal);
206750
+ signal.throwIfAborted();
206751
+ return {
206752
+ ok: true,
206753
+ patch: {
206754
+ stage: EHookStage.PREPARE_AGENT_LOOP,
206755
+ systemPromptSuffixes: entries.length ? [formatCatalog(entries)] : []
206756
+ }
206757
+ };
206758
+ }
206759
+ }
206760
+ ];
206761
+ modifyAgentConfig = (config2) => {
206762
+ if (!config2.agent.resources.some((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL))
206763
+ return;
206764
+ const existing = config2.agent.resources.filter((resource) => resource.resourceType === EResourceType.HOOK && resource.config.executorName === EHookExecutorName.McpDiscoveryHookExecutor);
206765
+ if (existing.length) {
206766
+ const hook = existing[0].config;
206767
+ if (existing.length !== 1 || hook.stage !== EHookStage.PREPARE_AGENT_LOOP || hook.hasSideEffects !== true || hook.enabled === false || hook.matcher !== void 0 || hook.timeoutMs !== void 0 && hook.timeoutMs !== 6e3)
206768
+ throw new Error("MCP \u53D1\u73B0 Hook \u5FC5\u987B\u542F\u7528 PREPARE_AGENT_LOOP \u72B6\u6001\u578B\u6267\u884C\u30016000ms \u8D85\u65F6\u4E14\u4E0D\u914D\u7F6E matcher");
206769
+ hook.timeoutMs = 6e3;
206770
+ return;
206771
+ }
206772
+ config2.agent.resources.push({
206773
+ resourceId: "mcp-discovery-prepare-agent-loop",
206774
+ resourceType: EResourceType.HOOK,
206775
+ providerType: EResourceProviderType.LINK_QUE,
206776
+ config: {
206777
+ name: "MCP \u5DE5\u5177\u76EE\u5F55\u9884\u52A0\u8F7D",
206778
+ executorName: EHookExecutorName.McpDiscoveryHookExecutor,
206779
+ stage: EHookStage.PREPARE_AGENT_LOOP,
206780
+ hasSideEffects: true,
206781
+ timeoutMs: 6e3
206782
+ }
206783
+ });
206784
+ };
206785
+ };
206786
+ }
206787
+ });
206788
+
206789
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/publicContentAccumulator.js
206790
+ var PUBLIC_CONTENT_MAX_BYTES, PublicContentAccumulator;
206791
+ var init_publicContentAccumulator = __esm({
206792
+ "../linkque-agent-runtime/dist/esm/core/telemetry/publicContentAccumulator.js"() {
206793
+ "use strict";
206794
+ init_telemetry();
206795
+ PUBLIC_CONTENT_MAX_BYTES = 512 * 1024;
206796
+ PublicContentAccumulator = class {
206797
+ observation;
206798
+ section;
206799
+ text = "";
206800
+ bytes = 0;
206801
+ index = 0;
206802
+ truncated = false;
206803
+ finished = false;
206804
+ pendingHighSurrogate = "";
206805
+ /** 创建正文累积器,将分块记录写入 observation,并以 section 标识内容类型。 */
206806
+ constructor(observation, section) {
206807
+ this.observation = observation;
206808
+ this.section = section;
206809
+ }
206810
+ /**
206811
+ * 接收一段正文,与上次暂存的高代理项拼接后,逐个码点交给 append() 累积。
206812
+ * 末尾尚未配对的高代理项暂存到下一次调用。
206813
+ */
206814
+ accept(content) {
206815
+ if (this.finished || this.truncated || !content)
206816
+ return;
206817
+ const text2 = this.pendingHighSurrogate + content;
206818
+ this.pendingHighSurrogate = "";
206819
+ const last = text2.charCodeAt(text2.length - 1);
206820
+ const endsWithHighSurrogate = last >= 55296 && last <= 56319;
206821
+ const ready = endsWithHighSurrogate ? text2.slice(0, -1) : text2;
206822
+ for (const character of ready) {
206823
+ this.append(character);
206824
+ if (this.truncated)
206825
+ return;
206826
+ }
206827
+ if (endsWithHighSurrogate)
206828
+ this.pendingHighSurrogate = text2.slice(-1);
206829
+ }
206830
+ /** 追加暂存的高代理项,写出带完整性标记的最终分块,并结束正文累积。 */
206831
+ finish(complete) {
206832
+ if (this.finished)
206833
+ return;
206834
+ this.finished = true;
206835
+ if (this.pendingHighSurrogate) {
206836
+ this.append(this.pendingHighSurrogate);
206837
+ this.pendingHighSurrogate = "";
206838
+ }
206839
+ if (this.bytes)
206840
+ this.flush(true, complete);
206841
+ }
206842
+ /** 将一个码点追加到缓冲并累计字节数;缓冲满时写出分块,总字节数超限时停止追加。 */
206843
+ append(character) {
206844
+ const size = Buffer.byteLength(character, "utf8");
206845
+ if (this.bytes + size > PUBLIC_CONTENT_MAX_BYTES) {
206846
+ this.truncated = true;
206847
+ return;
206848
+ }
206849
+ if (this.text.length + character.length > CONTENT_VALUE_MAX_LENGTH)
206850
+ this.flush(false, false);
206851
+ this.bytes += size;
206852
+ this.text += character;
206853
+ if (this.text.length === CONTENT_VALUE_MAX_LENGTH)
206854
+ this.flush(false, false);
206855
+ }
206856
+ /** 将当前缓冲写成一条正文记录,设置分块序号、最终标记和完整性,然后清空缓冲。 */
206857
+ flush(final, complete) {
206858
+ this.observation.record(ETelemetryEventName.CONTENT_RECORDED, {}, {
206859
+ section: this.section,
206860
+ value: this.text,
206861
+ chunkIndex: this.index++,
206862
+ final,
206863
+ availability: final && complete && !this.truncated ? "available" : "partial"
206864
+ });
206865
+ this.text = "";
206866
+ }
206867
+ };
206868
+ }
206869
+ });
206870
+
206871
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/publicReasoningObservation.js
206872
+ var PublicReasoningObservation;
206873
+ var init_publicReasoningObservation = __esm({
206874
+ "../linkque-agent-runtime/dist/esm/core/telemetry/publicReasoningObservation.js"() {
206875
+ "use strict";
206876
+ init_telemetry();
206877
+ init_publicContentAccumulator();
206878
+ PublicReasoningObservation = class {
206879
+ active;
206880
+ /** 返回当前思考段的来源 observation;没有正在采集的思考段时返回 undefined。 */
206881
+ get currentSource() {
206882
+ return this.active?.source;
206883
+ }
206884
+ /** 按来源创建或复用思考段,并追加思考文本;来源变化时先结束旧段。 */
206885
+ accept(content, source) {
206886
+ if (!content)
206887
+ return;
206888
+ if (source !== this.currentSource)
206889
+ this.finish(true);
206890
+ if (!source)
206891
+ return;
206892
+ if (!this.active) {
206893
+ const observation = source.startOperation({
206894
+ name: ETelemetryOperationName.MODEL_REASONING,
206895
+ eventPrefix: ETelemetryEventPrefix.MODEL_REASONING,
206896
+ attributes: {},
206897
+ detached: false,
206898
+ links: []
206899
+ });
206900
+ this.active = {
206901
+ source,
206902
+ observation,
206903
+ content: new PublicContentAccumulator(observation, ETelemetryContentSection.MODEL_REASONING)
206904
+ };
206905
+ }
206906
+ this.active.content.accept(content);
206907
+ }
206908
+ /** 写出当前思考段的剩余正文,按 complete 将其观察结束为成功或取消,并清除当前段。 */
206909
+ finish(complete) {
206910
+ const segment = this.active;
206911
+ if (!segment)
206912
+ return;
206913
+ this.active = void 0;
206914
+ segment.content.finish(complete);
206915
+ segment.observation.finish(complete ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.CANCELLED, {});
206916
+ }
206917
+ };
206918
+ }
206919
+ });
206920
+
206382
206921
  // ../linkque-agent-runtime/dist/esm/core/telemetry/publicOutputObservation.js
206383
206922
  var PublicOutputObservation;
206384
206923
  var init_publicOutputObservation = __esm({
206385
206924
  "../linkque-agent-runtime/dist/esm/core/telemetry/publicOutputObservation.js"() {
206386
206925
  "use strict";
206387
206926
  init_telemetry();
206927
+ init_publicContentAccumulator();
206928
+ init_publicReasoningObservation();
206388
206929
  PublicOutputObservation = class {
206389
206930
  root;
206390
- sources = /* @__PURE__ */ new WeakMap();
206391
- completedSources = /* @__PURE__ */ new WeakMap();
206392
- source;
206393
- text = "";
206394
- bytes = 0;
206395
- index = 0;
206396
- truncated = false;
206931
+ eventSources = /* @__PURE__ */ new WeakMap();
206932
+ sources = /* @__PURE__ */ new Map();
206933
+ reasoning = new PublicReasoningObservation();
206397
206934
  firstText = false;
206935
+ finished = false;
206398
206936
  startedAt = performance.now();
206937
+ /** 创建本轮公开输出观察器,使用 root 记录首个公开回答片段的延迟。 */
206399
206938
  constructor(root) {
206400
206939
  this.root = root;
206401
206940
  }
206941
+ /** 保存事件与来源 observation 的对应关系,供 accept() 将正文归入该来源。 */
206402
206942
  associate(event, source) {
206403
- if (source)
206404
- this.sources.set(event, source);
206943
+ if (this.finished || !source)
206944
+ return;
206945
+ this.eventSources.set(event, source);
206405
206946
  }
206406
- /** 来源终态可能早于队列中的正文到达,不能在此提前刷空缓冲。 */
206947
+ /** 保存指定来源是否正常完成,供本轮结束时判断其正文的完整性。 */
206407
206948
  completeSource(source, complete) {
206408
- if (source)
206409
- this.completedSources.set(source, complete);
206949
+ if (this.finished || !source)
206950
+ return;
206951
+ this.source(source).completed = complete;
206410
206952
  }
206953
+ /**
206954
+ * 处理一个已放行的公开事件:累积回答或思考正文,记录首个回答片段的延迟,
206955
+ * 并在收到终态事件时结束本轮采集。
206956
+ */
206411
206957
  accept(event) {
206958
+ if (this.finished)
206959
+ return;
206960
+ const source = this.eventSources.get(event);
206961
+ this.eventSources.delete(event);
206412
206962
  if (event.type === "done" || event.type === "error") {
206413
- const completed = this.source ? this.completedSources.get(this.source) : void 0;
206414
- this.finish(completed ?? event.type === "done");
206963
+ this.close(event.type);
206964
+ return;
206965
+ }
206966
+ if (event.type === "thinking") {
206967
+ this.reasoning.accept(event.content, source);
206415
206968
  return;
206416
206969
  }
206970
+ this.reasoning.finish(true);
206417
206971
  if (event.type !== "delta" || !event.content)
206418
206972
  return;
206419
206973
  if (!this.firstText) {
@@ -206422,44 +206976,43 @@ var init_publicOutputObservation = __esm({
206422
206976
  [ETelemetryAttribute.LINKQUE_LOOP_FIRST_PUBLIC_TEXT_MS]: performance.now() - this.startedAt
206423
206977
  });
206424
206978
  }
206425
- const source = this.sources.get(event);
206426
- if (!source)
206427
- return;
206428
- if (source !== this.source) {
206429
- this.finish(true);
206430
- this.source = source;
206431
- }
206432
- if (this.truncated)
206433
- return;
206434
- for (const character of event.content) {
206435
- const size = Buffer.byteLength(character, "utf8");
206436
- if (this.bytes + size > 512 * 1024) {
206437
- this.truncated = true;
206438
- break;
206439
- }
206440
- this.bytes += size;
206441
- this.text += character;
206442
- if (this.text.length >= 16 * 1024)
206443
- this.flush(false, false);
206444
- }
206979
+ if (source)
206980
+ this.source(source).output.accept(event.content);
206445
206981
  }
206982
+ /**
206983
+ * 结束本轮公开输出采集。
206984
+ * complete 为 true 表示事件流自然耗尽,为 false 表示消费者提前退出。
206985
+ */
206446
206986
  finish(complete) {
206447
- if (this.bytes)
206448
- this.flush(true, complete && (this.source ? this.completedSources.get(this.source) ?? true : true));
206449
- this.source = void 0;
206450
- this.bytes = 0;
206451
- this.index = 0;
206452
- this.truncated = false;
206987
+ this.close(complete ? "exhausted" : "interrupted");
206453
206988
  }
206454
- flush(final, complete) {
206455
- this.source?.record(ETelemetryEventName.CONTENT_RECORDED, {}, {
206456
- section: ETelemetryContentSection.MODEL_OUTPUT,
206457
- value: this.text,
206458
- chunkIndex: this.index++,
206459
- final,
206460
- availability: final && complete && !this.truncated ? "available" : "partial"
206461
- });
206462
- this.text = "";
206989
+ /**
206990
+ * 根据本轮结束原因和各来源的完成状态,写出剩余正文、结束思考观察,
206991
+ * 并清理来源状态和事件关联。
206992
+ */
206993
+ close(reason) {
206994
+ if (this.finished)
206995
+ return;
206996
+ this.finished = true;
206997
+ const complete = (source) => reason !== "interrupted" && (this.sources.get(source)?.completed ?? reason !== "error");
206998
+ const reasoningSource = this.reasoning.currentSource;
206999
+ if (reasoningSource)
207000
+ this.reasoning.finish(complete(reasoningSource));
207001
+ for (const [source, state2] of this.sources)
207002
+ state2.output.finish(complete(source));
207003
+ this.sources.clear();
207004
+ this.eventSources = /* @__PURE__ */ new WeakMap();
207005
+ }
207006
+ /** 获取指定 observation 的来源状态;首次访问时创建正文累积器并缓存。 */
207007
+ source(observation) {
207008
+ let source = this.sources.get(observation);
207009
+ if (!source) {
207010
+ source = {
207011
+ output: new PublicContentAccumulator(observation, ETelemetryContentSection.MODEL_OUTPUT)
207012
+ };
207013
+ this.sources.set(observation, source);
207014
+ }
207015
+ return source;
206463
207016
  }
206464
207017
  };
206465
207018
  }
@@ -206610,7 +207163,7 @@ var init_agentRuntimePlugin = __esm({
206610
207163
 
206611
207164
  // ../linkque-agent-runtime/dist/esm/core/cardSourceResult.js
206612
207165
  async function createCardSourceReceipt(input) {
206613
- const resultRef = `card-source-result-${(0, import_node_crypto8.randomUUID)()}`;
207166
+ const resultRef = `card-source-result-${(0, import_node_crypto9.randomUUID)()}`;
206614
207167
  try {
206615
207168
  const result = await buildCardSourceReceipt(input, resultRef);
206616
207169
  if (byteLength(result.receipt) > MAX_RECEIPT_BYTES)
@@ -207018,11 +207571,11 @@ function collectionSize(value) {
207018
207571
  function shortText(value, maxLength) {
207019
207572
  return value.length <= maxLength ? value : `${value.slice(0, maxLength - 1)}\u2026`;
207020
207573
  }
207021
- var import_node_crypto8, MAX_RECEIPT_BYTES, MAX_PREVIEW_ITEMS, MAX_PREVIEW_TEXT, DEFAULT_PAGE_ITEMS, MAX_PAGE_ITEMS, DEFAULT_TEXT_PAGE, MAX_TEXT_PAGE, MAX_OMISSIONS;
207574
+ var import_node_crypto9, MAX_RECEIPT_BYTES, MAX_PREVIEW_ITEMS, MAX_PREVIEW_TEXT, DEFAULT_PAGE_ITEMS, MAX_PAGE_ITEMS, DEFAULT_TEXT_PAGE, MAX_TEXT_PAGE, MAX_OMISSIONS;
207022
207575
  var init_cardSourceResult = __esm({
207023
207576
  "../linkque-agent-runtime/dist/esm/core/cardSourceResult.js"() {
207024
207577
  "use strict";
207025
- import_node_crypto8 = require("node:crypto");
207578
+ import_node_crypto9 = require("node:crypto");
207026
207579
  init_esm3();
207027
207580
  MAX_RECEIPT_BYTES = 1e5;
207028
207581
  MAX_PREVIEW_ITEMS = 10;
@@ -207511,8 +208064,8 @@ var init_cardRenderMcpServerProvider = __esm({
207511
208064
  constructor(inner) {
207512
208065
  this.inner = inner;
207513
208066
  }
207514
- async servers(resources) {
207515
- return this.inner.servers(resources);
208067
+ async servers(resources, signal) {
208068
+ return this.inner.servers(resources, signal);
207516
208069
  }
207517
208070
  };
207518
208071
  }
@@ -207568,9 +208121,12 @@ var DEFAULT_HARNESS_PROMPT, AgentRuntime;
207568
208121
  var init_agentRuntime = __esm({
207569
208122
  "../linkque-agent-runtime/dist/esm/core/agentRuntime.js"() {
207570
208123
  "use strict";
208124
+ init_mcpDiscoveryPlugin();
208125
+ init_cancellationScope();
207571
208126
  init_telemetry();
207572
208127
  init_noopRuntimeTelemetry();
207573
208128
  init_publicOutputObservation();
208129
+ init_runtimeObservation();
207574
208130
  init_runtimeErrorBoundary();
207575
208131
  init_toolObservation();
207576
208132
  init_esm();
@@ -207694,7 +208250,15 @@ var init_agentRuntime = __esm({
207694
208250
  */
207695
208251
  static create(protocol, ports) {
207696
208252
  const portsArg = ports ?? {};
207697
- const agentConfig = applyAgentRuntimePluginConfig(protocol, portsArg.plugins);
208253
+ const plugins = [...portsArg.plugins ?? []];
208254
+ let agentConfig = applyAgentRuntimePluginConfig(protocol, plugins);
208255
+ if (!plugins.some((plugin) => plugin.name === MCP_DISCOVERY_PLUGIN_NAME) && agentConfig.agent.resources.some((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL)) {
208256
+ const discoveryPlugin = new McpDiscoveryPlugin();
208257
+ plugins.push(discoveryPlugin);
208258
+ agentConfig = applyAgentRuntimePluginConfig(agentConfig, [
208259
+ discoveryPlugin
208260
+ ]);
208261
+ }
207698
208262
  const webSearchResource = resolveWebSearchResource(agentConfig.agent.resources);
207699
208263
  const model = agentConfig.agent.model;
207700
208264
  const skillResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.SKILL);
@@ -207707,6 +208271,7 @@ var init_agentRuntime = __esm({
207707
208271
  const innerProvider = portsArg.mcpServerProvider ?? new NoopMcpServerProvider();
207708
208272
  const rt = new _AgentRuntime({
207709
208273
  ...portsArg,
208274
+ plugins,
207710
208275
  mcpServerProvider: new CardRenderMcpServerProvider(innerProvider)
207711
208276
  });
207712
208277
  rt.defaultSystemPrompt = agentConfig.agent.systemPrompt.content;
@@ -207735,14 +208300,37 @@ var init_agentRuntime = __esm({
207735
208300
  return prepareFollowUpQuestionContext(await this.sessionManager.load(sessionId), history);
207736
208301
  }
207737
208302
  async generateFollowUpQuestions(context2, auth2, input) {
207738
- return this.followUpQuestionGenerator.generate({
207739
- auth: auth2,
207740
- context: context2,
208303
+ const observation = startRuntimeObservation(this.telemetry, {
207741
208304
  runId: input.runId,
207742
- runtimeContext: input.runtimeContext,
207743
- requestSource: input.requestSource,
207744
- debugLog: this.portsDebugLog
208305
+ agentId: input.runtimeContext?.agentId ?? this.agentId,
208306
+ sessionId: "",
208307
+ conversationId: input.runtimeContext?.threadId ?? "",
208308
+ context: input.telemetryContext ?? {
208309
+ parent: null,
208310
+ authorization: null,
208311
+ requestId: "",
208312
+ turnId: "",
208313
+ accountId: "",
208314
+ channel: "",
208315
+ userKey: ""
208316
+ }
207745
208317
  });
208318
+ try {
208319
+ const questions = await this.followUpQuestionGenerator.generate({
208320
+ auth: auth2,
208321
+ context: context2,
208322
+ runId: input.runId,
208323
+ observation,
208324
+ runtimeContext: input.runtimeContext,
208325
+ requestSource: input.requestSource,
208326
+ debugLog: this.portsDebugLog
208327
+ });
208328
+ observation.finish(ETelemetryOutcome.SUCCESS, {});
208329
+ return questions;
208330
+ } catch (error40) {
208331
+ observation.finish(ETelemetryOutcome.ERROR, {});
208332
+ throw error40;
208333
+ }
207746
208334
  }
207747
208335
  /** 产出 AgentStreamEvent 流;内核编排「解析上行资源 → 组请求 → agent loop」。 */
207748
208336
  async *runAgentLoop(request, auth2, options = {}) {
@@ -207794,13 +208382,17 @@ var init_agentRuntime = __esm({
207794
208382
  [ETelemetryAttribute.HARNESS_TELEMETRY_COMPLETENESS]: this.agentLoop instanceof PiAgentLoop ? ETelemetryCompleteness.COMPLETE : ETelemetryCompleteness.PARTIAL
207795
208383
  });
207796
208384
  this.recordCurrentQuery(observation, request);
208385
+ const runScope = new CancellationScope({
208386
+ signals: options.signal ? [options.signal] : []
208387
+ });
208388
+ const runOptions = { ...options, signal: runScope.context.signal };
207797
208389
  const cleanup = [];
207798
208390
  let termination = ETelemetryStreamTermination.CANCEL;
207799
208391
  let failed = false;
207800
208392
  let primaryFailure = false;
207801
208393
  let cleanupOutcome = ETelemetryOutcome.SUCCESS;
207802
208394
  try {
207803
- for await (const event of this.runObserved(request, auth2, options, observation, cleanup)) {
208395
+ for await (const event of this.runObserved(request, auth2, runOptions, observation, cleanup)) {
207804
208396
  if (event.type === "error") {
207805
208397
  failed = true;
207806
208398
  termination = ETelemetryStreamTermination.ERROR;
@@ -207818,6 +208410,7 @@ var init_agentRuntime = __esm({
207818
208410
  termination = cancelled && !failed ? ETelemetryStreamTermination.CANCEL : ETelemetryStreamTermination.ERROR;
207819
208411
  throw error40;
207820
208412
  } finally {
208413
+ runScope.cancel(new DOMException("Run \u5DF2\u7ED3\u675F", "AbortError"));
207821
208414
  const cleaning = observation.startOperation({
207822
208415
  name: ETelemetryOperationName.CLEANUP,
207823
208416
  eventPrefix: ETelemetryEventPrefix.OPERATION,
@@ -207831,6 +208424,7 @@ var init_agentRuntime = __esm({
207831
208424
  failed = true;
207832
208425
  });
207833
208426
  } finally {
208427
+ runScope.dispose();
207834
208428
  cleaning.finish(cleanupOutcome, {});
207835
208429
  observation.closePending();
207836
208430
  observation.finish(failed ? ETelemetryOutcome.ERROR : termination === ETelemetryStreamTermination.CANCEL ? ETelemetryOutcome.CANCELLED : termination === ETelemetryStreamTermination.COMPLETE ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.UNKNOWN, {
@@ -207940,6 +208534,16 @@ var init_agentRuntime = __esm({
207940
208534
  return false;
207941
208535
  }
207942
208536
  });
208537
+ const mcpServerSpecs = this.mcpServerSpecs;
208538
+ if (mcpServerSpecs.length === 0) {
208539
+ debugLog?.("[mcp] no mcp servers configured (no MCP tools will be available)", EDebugLogScope.MCP);
208540
+ }
208541
+ const mcpProxy = new McpProxyTool(this.mcpServerProvider, mcpServerSpecs, {
208542
+ debugLog,
208543
+ signal: options.signal,
208544
+ ...options.mcpCallAuthorizer ? { authorizeCall: options.mcpCallAuthorizer } : {}
208545
+ });
208546
+ cleanup.push(() => mcpProxy.closeAll());
207943
208547
  const hasPrepareHook = hookDispatcher.hasMatchingResource(EHookStage.PREPARE_AGENT_LOOP);
207944
208548
  if (hasPrepareHook && !this.effectiveAgentConfig) {
207945
208549
  throw new Error("Hook Runtime \u7F3A\u5C11\u6700\u7EC8 Agent Config");
@@ -207947,6 +208551,7 @@ var init_agentRuntime = __esm({
207947
208551
  const model = options.model ?? this.defaultModel;
207948
208552
  const prepareResult = hasPrepareHook ? await hookDispatcher.dispatch(EHookStage.PREPARE_AGENT_LOOP, hookCommonParams, {}, {
207949
208553
  stage: EHookStage.PREPARE_AGENT_LOOP,
208554
+ discoverMcpTools: (signal) => mcpProxy.discover(signal),
207950
208555
  auth: { ...auth2 },
207951
208556
  historyTurns: structuredClone(history),
207952
208557
  currentTurns: structuredClone(newTurns),
@@ -207963,15 +208568,6 @@ var init_agentRuntime = __esm({
207963
208568
  const skillRecords = this.skillResources.length ? await this.skillLoader.load(this.skillResources) : [];
207964
208569
  const skillCatalog = buildSkillCatalog(skillRecords);
207965
208570
  const activateSkillTool = createActivateSkillTool(skillRecords);
207966
- const mcpServerSpecs = this.mcpServerSpecs;
207967
- if (mcpServerSpecs.length === 0) {
207968
- debugLog?.("[mcp] no mcp servers configured (no MCP tools will be available)", EDebugLogScope.MCP);
207969
- }
207970
- const mcpProxy = new McpProxyTool(this.mcpServerProvider, mcpServerSpecs, {
207971
- debugLog,
207972
- ...options.mcpCallAuthorizer ? { authorizeCall: options.mcpCallAuthorizer } : {}
207973
- });
207974
- cleanup.push(() => mcpProxy.closeAll());
207975
208571
  const cardServer = new CardRenderMcpServer(this.cardResources, mcpProxy, { ...options.runtimeContext, threadId: request.threadId }, debugLog);
207976
208572
  cleanup.push(() => cardServer.close().catch(() => false));
207977
208573
  const cardTools = await cardServer.listTools();
@@ -208040,6 +208636,7 @@ var init_agentRuntime = __esm({
208040
208636
  commonParams: hookCommonParams
208041
208637
  };
208042
208638
  }
208639
+ options.signal?.throwIfAborted();
208043
208640
  const runStartedAt = Date.now();
208044
208641
  if (!hookDispatcher.isEmpty) {
208045
208642
  await hookDispatcher.dispatch(EHookStage.RUN_STARTED, hookCommonParams);
@@ -208481,17 +209078,12 @@ All keys required, no additional keys. Preserve imageId and mode exactly. Sum of
208481
209078
  async function waitForObservation(promise2, signal) {
208482
209079
  if (signal.aborted)
208483
209080
  imageError("IMAGE_CANCELLED");
208484
- let cancel;
208485
209081
  try {
208486
- return await Promise.race([
208487
- promise2,
208488
- new Promise((_resolve, reject) => {
208489
- cancel = () => reject(new Error("IMAGE_CANCELLED"));
208490
- signal.addEventListener("abort", cancel, { once: true });
208491
- })
208492
- ]);
208493
- } finally {
208494
- signal.removeEventListener("abort", cancel);
209082
+ return await waitWithSignal(promise2, signal);
209083
+ } catch (error40) {
209084
+ if (signal.aborted)
209085
+ imageError("IMAGE_CANCELLED");
209086
+ throw error40;
208495
209087
  }
208496
209088
  }
208497
209089
  function createImageTool(image, input, options, rules) {
@@ -208518,90 +209110,95 @@ function createImageTool(image, input, options, rules) {
208518
209110
  if (++calls > 3)
208519
209111
  imageError("IMAGE_CALL_LIMIT");
208520
209112
  const parsed = parseArgs(args, image.id);
208521
- const signal = AbortSignal.any([
208522
- AbortSignal.timeout(3e4),
208523
- ...[input.signal, executeSignal].filter((s2) => !!s2)
208524
- ]);
208525
- if (signal.aborted)
208526
- imageError("IMAGE_CANCELLED");
208527
- const key = auth2.apiKey?.trim();
208528
- if (auth2.provider !== EModelProvider.LINKQUE || !key || /\s|^Bearer\b/i.test(key) || key.includes("${") && !(options.allowSandboxAccessKeyPlaceholder === true && key === "${LINKQUE_AGENT_ACCESS_KEY}"))
208529
- imageError("IMAGE_AUTH_REQUIRED");
208530
- const cacheKey = JSON.stringify(parsed);
208531
- const existing = cache.get(cacheKey);
208532
- if (existing)
208533
- return structuredClone(await waitForObservation(existing, signal));
208534
- const pending = (async () => {
208535
- try {
208536
- const resolved = await resolveImage(image, fetchImpl, rules, signal);
208537
- const response = await fetchImpl(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
208538
- method: "POST",
208539
- signal,
208540
- redirect: "error",
208541
- headers: {
208542
- "content-type": "application/json",
208543
- "x-api-key": key,
208544
- "x-agent-id": input.agentId,
208545
- "x-run-id": input.runId,
208546
- "x-chat-id": input.threadId,
208547
- "x-step-id": context2?.toolCallId ?? `inspect-image-${calls}`
208548
- },
208549
- body: JSON.stringify({
208550
- model: "linkque-image-understanding",
208551
- stream: false,
208552
- max_tokens: 1600,
208553
- system: IMAGE_PROMPT,
208554
- messages: [
208555
- {
208556
- role: "user",
208557
- content: [
208558
- {
208559
- type: "text",
208560
- text: JSON.stringify({
208561
- version: "image-request-v1",
208562
- imageId: image.id,
208563
- mode: parsed.mode,
208564
- userQuery: parsed.query
208565
- })
208566
- },
208567
- {
208568
- type: "image",
208569
- source: {
208570
- type: "base64",
208571
- media_type: resolved.mediaType,
208572
- data: resolved.data
208573
- }
208574
- }
208575
- ]
208576
- }
208577
- ]
208578
- })
208579
- });
208580
- if (!response.ok) {
208581
- await response.body?.cancel();
208582
- imageError("IMAGE_GATEWAY_REJECTED");
208583
- }
208584
- let envelope;
209113
+ const scope = new CancellationScope({
209114
+ timeoutMs: 3e4,
209115
+ signals: [input.signal, executeSignal].filter((s2) => !!s2)
209116
+ });
209117
+ const signal = scope.context.signal;
209118
+ try {
209119
+ if (signal.aborted)
209120
+ imageError("IMAGE_CANCELLED");
209121
+ const key = auth2.apiKey?.trim();
209122
+ if (auth2.provider !== EModelProvider.LINKQUE || !key || /\s|^Bearer\b/i.test(key) || key.includes("${") && !(options.allowSandboxAccessKeyPlaceholder === true && key === "${LINKQUE_AGENT_ACCESS_KEY}"))
209123
+ imageError("IMAGE_AUTH_REQUIRED");
209124
+ const cacheKey = JSON.stringify(parsed);
209125
+ const existing = cache.get(cacheKey);
209126
+ if (existing)
209127
+ return structuredClone(await waitForObservation(existing, signal));
209128
+ const pending = (async () => {
208585
209129
  try {
208586
- envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await boundedBody(response, 128 * 1024)));
208587
- } catch {
208588
- imageError("IMAGE_OUTPUT_INVALID_ENVELOPE_JSON");
209130
+ const resolved = await resolveImage(image, fetchImpl, rules, signal);
209131
+ const response = await fetchImpl(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
209132
+ method: "POST",
209133
+ signal,
209134
+ redirect: "error",
209135
+ headers: {
209136
+ "content-type": "application/json",
209137
+ "x-api-key": key,
209138
+ "x-agent-id": input.agentId,
209139
+ "x-run-id": input.runId,
209140
+ "x-chat-id": input.threadId,
209141
+ "x-step-id": context2?.toolCallId ?? `inspect-image-${calls}`
209142
+ },
209143
+ body: JSON.stringify({
209144
+ model: "linkque-image-understanding",
209145
+ stream: false,
209146
+ max_tokens: 1600,
209147
+ system: IMAGE_PROMPT,
209148
+ messages: [
209149
+ {
209150
+ role: "user",
209151
+ content: [
209152
+ {
209153
+ type: "text",
209154
+ text: JSON.stringify({
209155
+ version: "image-request-v1",
209156
+ imageId: image.id,
209157
+ mode: parsed.mode,
209158
+ userQuery: parsed.query
209159
+ })
209160
+ },
209161
+ {
209162
+ type: "image",
209163
+ source: {
209164
+ type: "base64",
209165
+ media_type: resolved.mediaType,
209166
+ data: resolved.data
209167
+ }
209168
+ }
209169
+ ]
209170
+ }
209171
+ ]
209172
+ })
209173
+ });
209174
+ if (!response.ok) {
209175
+ await response.body?.cancel();
209176
+ imageError("IMAGE_GATEWAY_REJECTED");
209177
+ }
209178
+ let envelope;
209179
+ try {
209180
+ envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await boundedBody(response, 128 * 1024)));
209181
+ } catch {
209182
+ imageError("IMAGE_OUTPUT_INVALID_ENVELOPE_JSON");
209183
+ }
209184
+ return parseImageEnvelope(envelope, image.id, parsed.mode);
209185
+ } catch (error40) {
209186
+ if (signal.aborted)
209187
+ imageError("IMAGE_CANCELLED");
209188
+ if (error40 instanceof Error && /^IMAGE_[A-Z_]+$/.test(error40.message))
209189
+ throw error40;
209190
+ imageError("IMAGE_REQUEST_FAILED");
208589
209191
  }
208590
- return parseImageEnvelope(envelope, image.id, parsed.mode);
209192
+ })();
209193
+ cache.set(cacheKey, pending);
209194
+ try {
209195
+ return structuredClone(await pending);
208591
209196
  } catch (error40) {
208592
- if (signal.aborted)
208593
- imageError("IMAGE_CANCELLED");
208594
- if (error40 instanceof Error && /^IMAGE_[A-Z_]+$/.test(error40.message))
208595
- throw error40;
208596
- imageError("IMAGE_REQUEST_FAILED");
209197
+ cache.delete(cacheKey);
209198
+ throw error40;
208597
209199
  }
208598
- })();
208599
- cache.set(cacheKey, pending);
208600
- try {
208601
- return structuredClone(await pending);
208602
- } catch (error40) {
208603
- cache.delete(cacheKey);
208604
- throw error40;
209200
+ } finally {
209201
+ scope.dispose();
208605
209202
  }
208606
209203
  }
208607
209204
  };
@@ -208610,6 +209207,8 @@ var init_tool2 = __esm({
208610
209207
  "../linkque-agent-runtime/dist/esm/impl/plugin/imageUnderstanding/tool.js"() {
208611
209208
  "use strict";
208612
209209
  init_esm();
209210
+ init_abort();
209211
+ init_cancellationScope();
208613
209212
  init_runtimeConfigProvider();
208614
209213
  init_contract();
208615
209214
  init_io();
@@ -208622,6 +209221,7 @@ var init_imageUnderstandingPlugin = __esm({
208622
209221
  "../linkque-agent-runtime/dist/esm/impl/plugin/imageUnderstandingPlugin.js"() {
208623
209222
  "use strict";
208624
209223
  init_esm();
209224
+ init_cancellationScope();
208625
209225
  init_io();
208626
209226
  init_tool2();
208627
209227
  IMAGE_UNDERSTANDING_PLUGIN_NAME = "image-understanding";
@@ -208734,12 +209334,12 @@ var init_imageUnderstandingPlugin = __esm({
208734
209334
  message: "\u4E3B\u6A21\u578B\u672A\u786E\u8BA4\u539F\u751F\u56FE\u7247\u6216 Tool Use \u80FD\u529B"
208735
209335
  };
208736
209336
  if (capability.nativeImages && currentImage) {
209337
+ const scope = new CancellationScope({
209338
+ timeoutMs: 4e3,
209339
+ signals: [input.signal, execution?.signal].filter((s2) => !!s2)
209340
+ });
208737
209341
  try {
208738
- const signal = AbortSignal.any([
208739
- AbortSignal.timeout(4e3),
208740
- ...[input.signal, execution?.signal].filter((s2) => !!s2)
208741
- ]);
208742
- const resolved = await resolveImage(image, this.options.fetchImpl ?? globalThis.fetch, this.options.imageUrlRules, signal);
209342
+ const resolved = await resolveImage(image, this.options.fetchImpl ?? globalThis.fetch, this.options.imageUrlRules, scope.context.signal);
208743
209343
  modelTurns[selected.index].attachments = [
208744
209344
  {
208745
209345
  id: image.id,
@@ -208764,6 +209364,8 @@ var init_imageUnderstandingPlugin = __esm({
208764
209364
  code: "IMAGE_FETCH_FAILED",
208765
209365
  message: "\u56FE\u7247\u4E0D\u53EF\u7528\uFF0C\u8BF7\u91CD\u65B0\u4E0A\u4F20"
208766
209366
  };
209367
+ } finally {
209368
+ scope.dispose();
208767
209369
  }
208768
209370
  }
208769
209371
  return {
@@ -208884,7 +209486,9 @@ __export(plugin_exports, {
208884
209486
  LINKQUEGW_RUN_COMPLETED_HOOK_RESOURCE_ID: () => LINKQUEGW_RUN_COMPLETED_HOOK_RESOURCE_ID,
208885
209487
  LINKQUEGW_RUN_FAILED_HOOK_RESOURCE_ID: () => LINKQUEGW_RUN_FAILED_HOOK_RESOURCE_ID,
208886
209488
  LINKQUEGW_RUN_READ_HOOK_RESOURCE_ID: () => LINKQUEGW_RUN_READ_HOOK_RESOURCE_ID,
208887
- LinkquegwEventPlugin: () => LinkquegwEventPlugin
209489
+ LinkquegwEventPlugin: () => LinkquegwEventPlugin,
209490
+ MCP_DISCOVERY_PLUGIN_NAME: () => MCP_DISCOVERY_PLUGIN_NAME,
209491
+ McpDiscoveryPlugin: () => McpDiscoveryPlugin
208888
209492
  });
208889
209493
  var init_plugin = __esm({
208890
209494
  "../linkque-agent-runtime/dist/esm/impl/plugin/index.js"() {
@@ -208892,6 +209496,7 @@ var init_plugin = __esm({
208892
209496
  init_examplePlugin();
208893
209497
  init_imageUnderstandingPlugin();
208894
209498
  init_linkquegwEventPlugin();
209499
+ init_mcpDiscoveryPlugin();
208895
209500
  }
208896
209501
  });
208897
209502
 
@@ -212948,25 +213553,41 @@ var Client = class extends Protocol {
212948
213553
  var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
212949
213554
 
212950
213555
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/connectRetry.js
213556
+ init_abort();
213557
+ init_abortableDelay();
212951
213558
  var DEFAULT_MAX_CONNECT_ATTEMPTS = 3;
212952
213559
  var DEFAULT_RECONNECT_BACKOFF_MS = 1e3;
212953
213560
  var MAX_RECONNECT_BACKOFF_MS = 8e3;
212954
- async function connectMcpClientWithRetry(config2, factories) {
213561
+ async function connectMcpClientWithRetry(config2, factories, signal) {
212955
213562
  const maxAttempts = Math.max(1, config2.maxConnectAttempts ?? DEFAULT_MAX_CONNECT_ATTEMPTS);
212956
213563
  const backoffBase = config2.reconnectBackoffMs ?? DEFAULT_RECONNECT_BACKOFF_MS;
212957
213564
  let lastError;
212958
213565
  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
213566
+ signal?.throwIfAborted();
212959
213567
  const transport = factories.createTransport();
212960
213568
  const client = factories.createClient();
213569
+ let closing;
213570
+ const close = () => closing ??= safeClose(transport, client);
212961
213571
  try {
212962
- await client.connect(transport);
213572
+ const connecting = client.connect(transport).then(() => {
213573
+ if (signal?.aborted) {
213574
+ void close();
213575
+ signal.throwIfAborted();
213576
+ }
213577
+ });
213578
+ await waitWithSignal(connecting, signal);
213579
+ signal?.throwIfAborted();
212963
213580
  return { transport, client };
212964
213581
  } catch (error40) {
212965
213582
  lastError = error40;
212966
- await safeClose(transport, client);
213583
+ if (signal?.aborted) {
213584
+ void close();
213585
+ signal.throwIfAborted();
213586
+ }
213587
+ await waitWithSignal(close(), signal);
212967
213588
  if (attempt < maxAttempts) {
212968
- const delay2 = Math.min(backoffBase * 2 ** (attempt - 1), MAX_RECONNECT_BACKOFF_MS);
212969
- await sleep(delay2);
213589
+ const delay3 = Math.min(backoffBase * 2 ** (attempt - 1), MAX_RECONNECT_BACKOFF_MS);
213590
+ await abortableDelay(delay3, signal, false);
212970
213591
  }
212971
213592
  }
212972
213593
  }
@@ -212985,33 +213606,13 @@ async function safeClose(transport, client) {
212985
213606
  } catch {
212986
213607
  }
212987
213608
  }
212988
- function sleep(ms) {
212989
- return new Promise((resolve) => {
212990
- const timer = setTimeout(resolve, ms);
212991
- timer.unref?.();
212992
- });
212993
- }
212994
213609
 
212995
213610
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/mcpInvocationContext.js
212996
213611
  var import_node_async_hooks = require("node:async_hooks");
213612
+ init_abort();
213613
+ init_cancellationScope();
212997
213614
  async function waitForMcpOperation(operation, signal) {
212998
- signal.throwIfAborted();
212999
- let onAbort = () => {
213000
- };
213001
- try {
213002
- return await Promise.race([
213003
- new Promise((_, reject) => {
213004
- onAbort = () => reject(signal.reason);
213005
- signal.addEventListener("abort", onAbort, { once: true });
213006
- }),
213007
- Promise.resolve().then(() => {
213008
- signal.throwIfAborted();
213009
- return operation();
213010
- })
213011
- ]);
213012
- } finally {
213013
- signal.removeEventListener("abort", onAbort);
213014
- }
213615
+ return waitWithSignal(operation, signal);
213015
213616
  }
213016
213617
  var McpInvocationContext = class {
213017
213618
  storage = new import_node_async_hooks.AsyncLocalStorage();
@@ -213022,19 +213623,22 @@ var McpInvocationContext = class {
213022
213623
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
213023
213624
  throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
213024
213625
  signal?.throwIfAborted();
213025
- const controller = new AbortController();
213626
+ const scope = new CancellationScope({
213627
+ signals: signal ? [signal] : [],
213628
+ timeoutMs,
213629
+ timeoutReason: new DOMException("MCP \u8C03\u7528\u603B\u9884\u7B97\u5DF2\u8017\u5C3D", "TimeoutError")
213630
+ });
213026
213631
  const context2 = {
213027
- signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
213028
- deadline: performance.now() + timeoutMs
213632
+ signal: scope.context.signal,
213633
+ deadline: scope.context.deadline
213029
213634
  };
213030
- const timer = setTimeout(() => controller.abort(new DOMException("MCP \u8C03\u7528\u603B\u9884\u7B97\u5DF2\u8017\u5C3D", "TimeoutError")), Math.min(timeoutMs, 2147483647));
213031
213635
  try {
213032
- return await this.storage.run(context2, () => waitForMcpOperation(() => operation(context2), context2.signal));
213636
+ return await this.storage.run(context2, () => waitWithSignal(() => operation(context2), context2.signal));
213033
213637
  } catch (error40) {
213034
- context2.signal.throwIfAborted();
213638
+ scope.context.throwIfAborted();
213035
213639
  throw error40;
213036
213640
  } finally {
213037
- clearTimeout(timer);
213641
+ scope.dispose();
213038
213642
  }
213039
213643
  }
213040
213644
  };
@@ -213136,6 +213740,9 @@ async function safeText(resp) {
213136
213740
  }
213137
213741
  }
213138
213742
 
213743
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/sseTransportFactory.js
213744
+ init_cancellationScope();
213745
+
213139
213746
  // ../../node_modules/eventsource-parser/dist/index.js
213140
213747
  var ParseError = class extends Error {
213141
213748
  constructor(message, options) {
@@ -214751,8 +215358,12 @@ function withTimeout(fetch3, timeoutMs) {
214751
215358
  if (init?.signal) {
214752
215359
  return fetch3(url2, init);
214753
215360
  }
214754
- const signal = AbortSignal.timeout(timeoutMs);
214755
- return fetch3(url2, { ...init, signal });
215361
+ const scope = new CancellationScope({ timeoutMs });
215362
+ try {
215363
+ return await fetch3(url2, { ...init, signal: scope.context.signal });
215364
+ } finally {
215365
+ scope.dispose();
215366
+ }
214756
215367
  };
214757
215368
  }
214758
215369
  function createSseTransport(config2, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
@@ -214990,12 +215601,13 @@ var RemoteGatewayMcpServerProvider = class {
214990
215601
  this.onTraceId = options.onTraceId;
214991
215602
  this.debugLog = options.debugLog;
214992
215603
  }
214993
- async servers(resources) {
214994
- return Promise.all(resources.map((r2) => this.connectOne(r2)));
215604
+ async servers(resources, signal) {
215605
+ return Promise.all(resources.map((r2) => this.connectOne(r2, signal)));
214995
215606
  }
214996
215607
  /** 连单个远端 server 并包装成 IMcpServer。建连失败有限重试 + 失败清理由 helper 负责。 */
214997
- async connectOne(resource) {
215608
+ async connectOne(resource, connectSignal) {
214998
215609
  const config2 = await this.resolveConfig(resource);
215610
+ connectSignal?.throwIfAborted();
214999
215611
  const timeoutMs = config2.requestTimeoutMs ?? 18e4;
215000
215612
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
215001
215613
  throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
@@ -215004,7 +215616,7 @@ var RemoteGatewayMcpServerProvider = class {
215004
215616
  const { client } = await connectMcpClientWithRetry(config2, {
215005
215617
  createTransport: () => createSseTransport(config2, this.createSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
215006
215618
  createClient: () => this.createClient()
215007
- });
215619
+ }, connectSignal);
215008
215620
  const serverName = resource.config.serverName ?? resource.resourceId;
215009
215621
  const argsMappingRules = resource.config.argsMappingRules ?? [];
215010
215622
  let requestSequence = 0;
@@ -215037,7 +215649,7 @@ var RemoteGatewayMcpServerProvider = class {
215037
215649
  }
215038
215650
  };
215039
215651
  const loggedClient = {
215040
- listTools: () => request("tools/list", {}, () => client.listTools()),
215652
+ listTools: (params, options) => request("tools/list", params ?? {}, () => client.listTools(params, options)),
215041
215653
  callTool: (params, resultSchema, requestOptions) => request("tools/call", params, () => client.callTool(params, resultSchema, requestOptions))
215042
215654
  };
215043
215655
  const callTool = (name, args, signal, options) => callHeaders.run(options?.headers ?? {}, () => this.invocationContext.run(timeoutMs, signal, async (invocation) => {
@@ -215087,7 +215699,7 @@ var RemoteGatewayMcpServerProvider = class {
215087
215699
  return {
215088
215700
  resourceId: resource.resourceId,
215089
215701
  serverName,
215090
- listTools: () => listToolsFromClient(loggedClient, resource.resourceId, callTool),
215702
+ listTools: (signal) => listToolsFromClient(loggedClient, resource.resourceId, callTool, signal),
215091
215703
  callTool,
215092
215704
  close: async () => {
215093
215705
  try {
@@ -215098,8 +215710,9 @@ var RemoteGatewayMcpServerProvider = class {
215098
215710
  };
215099
215711
  }
215100
215712
  };
215101
- async function listToolsFromClient(client, resourceId, callTool) {
215102
- const result = await client.listTools();
215713
+ async function listToolsFromClient(client, resourceId, callTool, listSignal) {
215714
+ listSignal?.throwIfAborted();
215715
+ const result = await client.listTools(void 0, listSignal ? { signal: listSignal } : void 0);
215103
215716
  const tools = result.tools ?? [];
215104
215717
  return tools.map((tool) => {
215105
215718
  const descriptor = {
@@ -215127,6 +215740,7 @@ async function listToolsFromClient(client, resourceId, callTool) {
215127
215740
 
215128
215741
  // ../linkque-agent-runtime/dist/esm/impl/knowledge/linkqueKnowledgeSearchPort.js
215129
215742
  init_config();
215743
+ init_cancellationScope();
215130
215744
  init_httpLoggingFetch();
215131
215745
  var DEFAULT_LINKQUEGW_KNOWLEDGE_BASE_URL = RUNTIME_CONFIG_DEFAULTS.LINKQUEGW_KNOWLEDGE_BASE_URL;
215132
215746
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
@@ -215170,28 +215784,20 @@ var LinkqueKnowledgeSearchPort = class {
215170
215784
  "content-type": "application/json",
215171
215785
  ...await this.getAuthHeaders()
215172
215786
  };
215173
- const controller = new AbortController();
215174
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
215175
- const onAbort = () => controller.abort();
215176
- if (signal) {
215177
- if (signal.aborted) {
215178
- controller.abort();
215179
- } else {
215180
- signal.addEventListener("abort", onAbort, { once: true });
215181
- }
215182
- }
215787
+ const scope = new CancellationScope({
215788
+ signals: signal ? [signal] : [],
215789
+ timeoutMs: this.timeoutMs
215790
+ });
215183
215791
  let resp;
215184
215792
  try {
215185
215793
  resp = await this.fetchImpl(url2, {
215186
215794
  method: "POST",
215187
215795
  headers,
215188
215796
  body,
215189
- signal: controller.signal
215797
+ signal: scope.context.signal
215190
215798
  });
215191
215799
  } finally {
215192
- clearTimeout(timer);
215193
- if (signal)
215194
- signal.removeEventListener("abort", onAbort);
215800
+ scope.dispose();
215195
215801
  }
215196
215802
  if (!resp.ok) {
215197
215803
  const text2 = await safeText2(resp);
@@ -215243,6 +215849,7 @@ async function safeText2(resp) {
215243
215849
 
215244
215850
  // ../linkque-agent-runtime/dist/esm/impl/webSearch/linkqueWebSearchPort.js
215245
215851
  init_config();
215852
+ init_cancellationScope();
215246
215853
  init_types();
215247
215854
  init_webSearchTools();
215248
215855
  var DEFAULT_LINKQUEGW_WEB_SEARCH_BASE_URL = RUNTIME_CONFIG_DEFAULTS.LINKQUEGW_WEB_SEARCH_BASE_URL;
@@ -215268,13 +215875,12 @@ var LinkqueWebSearchPort = class {
215268
215875
  }
215269
215876
  async search(input, signal) {
215270
215877
  const startedAt = Date.now();
215271
- const controller = new AbortController();
215272
- const onAbort = () => controller.abort(new DOMException("\u5168\u7F51\u641C\u7D22\u5DF2\u53D6\u6D88", "AbortError"));
215273
- signal?.addEventListener("abort", onAbort, { once: true });
215274
- if (signal?.aborted)
215275
- onAbort();
215276
- const timer = setTimeout(() => controller.abort(new WebSearchError("WEB_SEARCH_TIMEOUT")), this.timeoutMs);
215277
- const requestSignal = controller.signal;
215878
+ const scope = new CancellationScope({
215879
+ signals: signal ? [signal] : [],
215880
+ timeoutMs: this.timeoutMs,
215881
+ timeoutReason: new WebSearchError("WEB_SEARCH_TIMEOUT")
215882
+ });
215883
+ const requestSignal = scope.context.signal;
215278
215884
  let outcome = "success";
215279
215885
  let status;
215280
215886
  let count = 0;
@@ -215319,8 +215925,7 @@ var LinkqueWebSearchPort = class {
215319
215925
  outcome = failure6.code;
215320
215926
  throw new WebSearchError(failure6.code);
215321
215927
  } finally {
215322
- clearTimeout(timer);
215323
- signal?.removeEventListener("abort", onAbort);
215928
+ scope.dispose();
215324
215929
  try {
215325
215930
  this.options.debugLog?.(JSON.stringify({
215326
215931
  tag: "web-search-http",
@@ -215476,7 +216081,8 @@ var LocalHttpMcpServerProvider = class {
215476
216081
  const baseFetch = options.fetch ?? fetch;
215477
216082
  this.fetchImpl = options.debugLog ? createHttpLoggingFetch(options.debugLog, "local-mcp", baseFetch) : baseFetch;
215478
216083
  }
215479
- async servers(resources) {
216084
+ async servers(resources, signal) {
216085
+ signal?.throwIfAborted();
215480
216086
  return resources.map((resource) => this.createServer(resource));
215481
216087
  }
215482
216088
  createServer(resource) {
@@ -215484,8 +216090,8 @@ var LocalHttpMcpServerProvider = class {
215484
216090
  return {
215485
216091
  resourceId: resource.resourceId,
215486
216092
  serverName: resource.config.serverName ?? resource.resourceId,
215487
- listTools: async () => {
215488
- const response = await this.fetchImpl(toolsUrl);
216093
+ listTools: async (signal) => {
216094
+ const response = await this.fetchImpl(toolsUrl, { signal });
215489
216095
  const body = await readJsonResponse(response);
215490
216096
  if (!isRecord2(body) || !Array.isArray(body.tools)) {
215491
216097
  throw new Error(`Invalid local MCP tool catalog for ${resource.resourceId}`);
@@ -215553,7 +216159,7 @@ function isRecord2(value) {
215553
216159
  }
215554
216160
 
215555
216161
  // ../linkque-agent-runtime/dist/esm/impl/webSkillLoader.js
215556
- var import_promises = require("node:fs/promises");
216162
+ var import_promises2 = require("node:fs/promises");
215557
216163
  var import_node_path = __toESM(require("node:path"), 1);
215558
216164
  var import_node_url = require("node:url");
215559
216165
 
@@ -216278,12 +216884,12 @@ var WebSkillLoader = class {
216278
216884
  if (candidate !== this.root && !candidate.startsWith(`${this.root}${import_node_path.default.sep}`)) {
216279
216885
  throw new Error(`WebSkillLoader file:// \u8DEF\u5F84\u9003\u9038 root: ${url2} \u2192 ${candidate} (root=${this.root}, resourceId=${resourceId})`);
216280
216886
  }
216281
- const info = await (0, import_promises.stat)(candidate);
216887
+ const info = await (0, import_promises2.stat)(candidate);
216282
216888
  if (info.isDirectory()) {
216283
- return (0, import_promises.readFile)(import_node_path.default.join(candidate, "SKILL.md"), "utf8");
216889
+ return (0, import_promises2.readFile)(import_node_path.default.join(candidate, "SKILL.md"), "utf8");
216284
216890
  }
216285
216891
  if (isZipPath(candidate)) {
216286
- const bytes2 = new Uint8Array(await (0, import_promises.readFile)(candidate));
216892
+ const bytes2 = new Uint8Array(await (0, import_promises2.readFile)(candidate));
216287
216893
  const files = await unzipBytes(bytes2, resourceId);
216288
216894
  const body = extractSkillMarkdown(files);
216289
216895
  if (body === void 0) {
@@ -216291,7 +216897,7 @@ var WebSkillLoader = class {
216291
216897
  }
216292
216898
  return body;
216293
216899
  }
216294
- return (0, import_promises.readFile)(candidate, "utf8");
216900
+ return (0, import_promises2.readFile)(candidate, "utf8");
216295
216901
  }
216296
216902
  /** fetch zip 字节;非 2xx 或网络失败抛错。 */
216297
216903
  async fetchZip(url2, resourceId) {
@@ -216362,6 +216968,8 @@ init_noopRuntimeTelemetry();
216362
216968
  init_telemetry();
216363
216969
  init_telemetryEnums2();
216364
216970
  var import_node_async_hooks3 = require("node:async_hooks");
216971
+ init_abort();
216972
+ init_cancellationScope();
216365
216973
  init_esm6();
216366
216974
  var import_core11 = __toESM(require_src(), 1);
216367
216975
  function authorizationKey(auth2) {
@@ -216401,7 +217009,7 @@ var IdentityQueue = class {
216401
217009
  maxBytes: options.maxBytes ?? 16 * 1024 * 1024,
216402
217010
  maxPartitions: options.maxPartitions ?? 32,
216403
217011
  batchMaxRecords: options.batchMaxRecords ?? 100,
216404
- batchMaxBytes: options.batchMaxBytes ?? 256 * 1024,
217012
+ batchMaxBytes: options.batchMaxBytes ?? 1024 * 1024,
216405
217013
  intervalMs: options.intervalMs ?? 1e3,
216406
217014
  sendTimeoutMs: options.sendTimeoutMs ?? 2e3,
216407
217015
  maxAgeMs: options.maxAgeMs ?? 6e4,
@@ -216489,7 +217097,7 @@ var IdentityQueue = class {
216489
217097
  const resource = body[signal === ETelemetrySignal.LOGS ? "resourceLogs" : "resourceSpans"][0];
216490
217098
  const bytes2 = Buffer.byteLength(JSON.stringify(resource)) + 1;
216491
217099
  const ratio = critical ? 1 : 1 - this.limits.terminalReserveRatio;
216492
- 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) {
217100
+ 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) {
216493
217101
  this.drop(ETelemetryDiagnosticCode.QUEUE_LIMIT, 1, part);
216494
217102
  return;
216495
217103
  }
@@ -216551,97 +217159,90 @@ var IdentityQueue = class {
216551
217159
  batch.push(record4);
216552
217160
  bytes2 += record4.bytes;
216553
217161
  }
216554
- const controller = new AbortController();
216555
- this.controllers.add(controller);
216556
- let timer;
216557
- const timeout = new Promise((_, reject) => {
216558
- controller.signal.addEventListener("abort", () => reject(new Error("\u9065\u6D4B\u53D1\u9001\u7EC8\u6B62")), { once: true });
216559
- timer = setTimeout(() => controller.abort(), this.limits.sendTimeoutMs);
216560
- timer.unref?.();
217162
+ const scope = new CancellationScope({
217163
+ timeoutMs: this.limits.sendTimeoutMs,
217164
+ timeoutReason: new Error("\u9065\u6D4B\u53D1\u9001\u7EC8\u6B62"),
217165
+ ref: false
216561
217166
  });
217167
+ this.controllers.add(scope);
216562
217168
  try {
216563
- await Promise.race([
216564
- this.exportContext.run(true, () => context.with((0, import_core11.suppressTracing)(context.active()), async () => {
216565
- const headers = await part.authorization.getHeaders();
216566
- if (controller.signal.aborted || this.closed)
216567
- return;
216568
- const response = await (this.options.fetch ?? fetch)(signal === ETelemetrySignal.LOGS ? this.options.logsEndpoint : this.options.tracesEndpoint, {
216569
- method: "POST",
216570
- redirect: "error",
216571
- signal: controller.signal,
216572
- headers: { ...headers, "content-type": "application/json" },
216573
- body: JSON.stringify({
216574
- [signal === ETelemetrySignal.LOGS ? "resourceLogs" : "resourceSpans"]: batch.map((record4) => record4.resource)
216575
- })
216576
- });
216577
- if (controller.signal.aborted || this.closed)
216578
- return;
216579
- if (response.status === 200) {
216580
- const reader = response.body?.getReader();
216581
- const chunks = [];
216582
- let size = 0;
216583
- if (reader) {
216584
- try {
216585
- for (; ; ) {
216586
- const next = await reader.read();
216587
- if (next.done)
216588
- break;
216589
- size += next.value.length;
216590
- if (size > 64 * 1024)
216591
- throw new Error("\u9065\u6D4B\u54CD\u5E94\u8D85\u9650");
216592
- chunks.push(next.value);
216593
- }
216594
- } finally {
216595
- await reader.cancel().catch(() => void 0);
217169
+ await waitWithSignal(() => this.exportContext.run(true, () => context.with((0, import_core11.suppressTracing)(context.active()), async () => {
217170
+ const headers = await part.authorization.getHeaders();
217171
+ if (scope.context.signal.aborted || this.closed)
217172
+ return;
217173
+ const response = await (this.options.fetch ?? fetch)(signal === ETelemetrySignal.LOGS ? this.options.logsEndpoint : this.options.tracesEndpoint, {
217174
+ method: "POST",
217175
+ redirect: "error",
217176
+ signal: scope.context.signal,
217177
+ headers: { ...headers, "content-type": "application/json" },
217178
+ body: JSON.stringify({
217179
+ [signal === ETelemetrySignal.LOGS ? "resourceLogs" : "resourceSpans"]: batch.map((record4) => record4.resource)
217180
+ })
217181
+ });
217182
+ if (scope.context.signal.aborted || this.closed)
217183
+ return;
217184
+ if (response.status === 200) {
217185
+ const reader = response.body?.getReader();
217186
+ const chunks = [];
217187
+ let size = 0;
217188
+ if (reader) {
217189
+ try {
217190
+ for (; ; ) {
217191
+ const next = await reader.read();
217192
+ if (next.done)
217193
+ break;
217194
+ size += next.value.length;
217195
+ if (size > 64 * 1024)
217196
+ throw new Error("\u9065\u6D4B\u54CD\u5E94\u8D85\u9650");
217197
+ chunks.push(next.value);
216596
217198
  }
217199
+ } finally {
217200
+ await reader.cancel().catch(() => void 0);
216597
217201
  }
216598
- const raw = Buffer.concat(chunks).toString("utf8");
216599
- const result = raw ? JSON.parse(raw) : {};
216600
- if (!result || typeof result !== "object" || Array.isArray(result))
216601
- throw new Error("\u9065\u6D4B\u54CD\u5E94\u975E\u6CD5");
216602
- const rejected = Number(result.partialSuccess?.[signal === ETelemetrySignal.LOGS ? "rejectedLogRecords" : "rejectedSpans"] ?? 0);
216603
- if (!Number.isSafeInteger(rejected) || rejected < 0 || rejected > batch.length)
216604
- throw new Error("\u9065\u6D4B\u62D2\u6536\u8BA1\u6570\u975E\u6CD5");
216605
- if (controller.signal.aborted || this.closed)
216606
- return;
216607
- this.remove(part, batch);
216608
- this.sent += batch.length - rejected;
216609
- part.sent += batch.length - rejected;
216610
- if (rejected)
216611
- this.drop(ETelemetryDiagnosticCode.PARTIAL_SUCCESS, rejected, part);
216612
- part.retry = 0;
216613
- part.nextAt = 0;
217202
+ }
217203
+ const raw = Buffer.concat(chunks).toString("utf8");
217204
+ const result = raw ? JSON.parse(raw) : {};
217205
+ if (!result || typeof result !== "object" || Array.isArray(result))
217206
+ throw new Error("\u9065\u6D4B\u54CD\u5E94\u975E\u6CD5");
217207
+ const rejected = Number(result.partialSuccess?.[signal === ETelemetrySignal.LOGS ? "rejectedLogRecords" : "rejectedSpans"] ?? 0);
217208
+ if (!Number.isSafeInteger(rejected) || rejected < 0 || rejected > batch.length)
217209
+ throw new Error("\u9065\u6D4B\u62D2\u6536\u8BA1\u6570\u975E\u6CD5");
217210
+ if (scope.context.signal.aborted || this.closed)
217211
+ return;
217212
+ this.remove(part, batch);
217213
+ this.sent += batch.length - rejected;
217214
+ part.sent += batch.length - rejected;
217215
+ if (rejected)
217216
+ this.drop(ETelemetryDiagnosticCode.PARTIAL_SUCCESS, rejected, part);
217217
+ part.retry = 0;
217218
+ part.nextAt = 0;
217219
+ } else {
217220
+ await response.body?.cancel().catch(() => void 0);
217221
+ if (scope.context.signal.aborted || this.closed)
217222
+ return;
217223
+ if ([429, 502, 503, 504].includes(response.status)) {
217224
+ const value = response.headers.get("retry-after");
217225
+ const delay3 = value === null ? 0 : /^\d+$/.test(value) ? Number(value) * 1e3 : Math.max(0, Date.parse(value) - Date.now());
217226
+ this.retry(part, Number.isFinite(delay3) ? delay3 : 0);
216614
217227
  } else {
216615
- await response.body?.cancel().catch(() => void 0);
216616
- if (controller.signal.aborted || this.closed)
216617
- return;
216618
- if ([429, 502, 503, 504].includes(response.status)) {
216619
- const value = response.headers.get("retry-after");
216620
- const delay2 = value === null ? 0 : /^\d+$/.test(value) ? Number(value) * 1e3 : Math.max(0, Date.parse(value) - Date.now());
216621
- this.retry(part, Number.isFinite(delay2) ? delay2 : 0);
217228
+ if ([401, 403].includes(response.status)) {
217229
+ part.blocked = true;
217230
+ const records = [...part.records];
217231
+ this.remove(part, records);
217232
+ this.drop(ETelemetryDiagnosticCode.AUTHORIZATION_REJECTED, records.length, part);
216622
217233
  } else {
216623
- if ([401, 403].includes(response.status)) {
216624
- part.blocked = true;
216625
- const records = [...part.records];
216626
- this.remove(part, records);
216627
- this.drop(ETelemetryDiagnosticCode.AUTHORIZATION_REJECTED, records.length, part);
216628
- } else {
216629
- this.remove(part, batch);
216630
- this.drop(ETelemetryDiagnosticCode.PERMANENT_REJECTION, batch.length, part);
216631
- }
217234
+ this.remove(part, batch);
217235
+ this.drop(ETelemetryDiagnosticCode.PERMANENT_REJECTION, batch.length, part);
216632
217236
  }
216633
217237
  }
216634
- })),
216635
- timeout
216636
- ]);
217238
+ }
217239
+ })), scope.context.signal);
216637
217240
  } catch {
216638
217241
  if (!this.closed)
216639
217242
  this.retry(part);
216640
217243
  } finally {
216641
- if (timer)
216642
- clearTimeout(timer);
216643
- controller.abort();
216644
- this.controllers.delete(controller);
217244
+ scope.dispose();
217245
+ this.controllers.delete(scope);
216645
217246
  }
216646
217247
  }
216647
217248
  retry(part, minimum = 0) {
@@ -216677,8 +217278,8 @@ var IdentityQueue = class {
216677
217278
  this.closed = true;
216678
217279
  if (this.timer)
216679
217280
  clearInterval(this.timer);
216680
- for (const controller of this.controllers)
216681
- controller.abort();
217281
+ for (const scope of this.controllers)
217282
+ scope.cancel(new Error("\u9065\u6D4B\u53D1\u9001\u7EC8\u6B62"));
216682
217283
  const count = this.pending();
216683
217284
  if (count)
216684
217285
  this.drop(ETelemetryDiagnosticCode.SHUTDOWN_DROP, count);
@@ -216914,7 +217515,7 @@ var OtelRuntimeTelemetry = class {
216914
217515
  {
216915
217516
  onEmit: (record4, ctx) => {
216916
217517
  const route = ctx?.getValue(this.routeKey);
216917
- this.output(ETelemetrySignal.LOGS, import_otlp_transformer.JsonLogsSerializer.serializeRequest([record4]), route?.route, route?.critical ?? false, route?.localOnly ?? false);
217518
+ this.output(ETelemetrySignal.LOGS, import_otlp_transformer.JsonLogsSerializer.serializeRequest([record4]), route?.route, route?.critical ?? false);
216918
217519
  },
216919
217520
  forceFlush: async () => void 0,
216920
217521
  shutdown: async () => void 0
@@ -216922,13 +217523,12 @@ var OtelRuntimeTelemetry = class {
216922
217523
  ]
216923
217524
  });
216924
217525
  }
216925
- output(signal, encoded, route, critical, localOnly = false) {
217526
+ output(signal, encoded, route, critical) {
216926
217527
  if (!encoded || this.outputActive || this.disposed)
216927
217528
  return;
216928
217529
  this.outputActive = true;
216929
217530
  try {
216930
- if (!localOnly)
216931
- this.queue.enqueue(route, signal, encoded, critical);
217531
+ this.queue.enqueue(route, signal, encoded, critical);
216932
217532
  if (this.options.localSink) {
216933
217533
  try {
216934
217534
  const payload = JSON.parse(new TextDecoder().decode(encoded));
@@ -217084,28 +217684,28 @@ var OtelRuntimeTelemetry = class {
217084
217684
  Math.floor(now / 1e3),
217085
217685
  now % 1e3 * 1e6
217086
217686
  ];
217087
- const localOnly = name === ETelemetryEventName.CONTENT_RECORDED;
217088
- if (localOnly && body && typeof body === "object" && "value" in body) {
217687
+ const contentRecord = name === ETelemetryEventName.CONTENT_RECORDED;
217688
+ if (contentRecord && body && typeof body === "object" && "value" in body) {
217089
217689
  const { value, ...metadata } = body;
217090
217690
  try {
217091
217691
  const valueJson = JSON.stringify(value);
217092
- body = valueJson !== void 0 && Buffer.byteLength(JSON.stringify(valueJson), "utf8") <= 512 * 1024 ? { ...metadata, valueJson } : { ...metadata, availability: "unavailable", reason: "content_limit" };
217692
+ body = valueJson !== void 0 && Buffer.byteLength(JSON.stringify(valueJson), "utf8") <= 512 * 1024 ? { ...metadata, valueJson } : {
217693
+ ...metadata,
217694
+ availability: "unavailable",
217695
+ reason: "content_limit"
217696
+ };
217093
217697
  } catch {
217094
217698
  body = { ...metadata, availability: "unavailable" };
217095
217699
  }
217096
217700
  }
217097
- if (!localOnly && operation.span.isRecording())
217701
+ if (!contentRecord && operation.span.isRecording())
217098
217702
  operation.span.addEvent(
217099
217703
  name,
217100
217704
  // 复用已投影的属性;Span 已持有上下文,事件只保留本次事实及去重字段。
217101
217705
  Object.fromEntries(Object.entries(record4).filter(([key]) => Object.hasOwn(attributes, key) || key === ETelemetryAttribute.HARNESS_RECORD_ID || key === ETelemetryAttribute.HARNESS_EVENT_SEQUENCE)),
217102
217706
  time3
217103
217707
  );
217104
- const ctx = trace.setSpan(ROOT_CONTEXT, operation.span).setValue(this.routeKey, {
217105
- route: operation.state.route,
217106
- critical,
217107
- localOnly
217108
- });
217708
+ const ctx = trace.setSpan(ROOT_CONTEXT, operation.span).setValue(this.routeKey, { route: operation.state.route, critical });
217109
217709
  this.loggerProvider.getLogger(ETelemetryMetadata.SCOPE_NAME, ETelemetryVersion.V1_0).emit({
217110
217710
  eventName: name,
217111
217711
  timestamp: time3,
@@ -217325,7 +217925,7 @@ var readCliVersion = () => {
217325
217925
  var CLI_VERSION = readCliVersion();
217326
217926
 
217327
217927
  // src/commands/agentdev/otlpFileSink.ts
217328
- var import_promises2 = require("fs/promises");
217928
+ var import_promises3 = require("fs/promises");
217329
217929
  var import_path2 = __toESM(require("path"));
217330
217930
 
217331
217931
  // src/utils/files.ts
@@ -217347,12 +217947,12 @@ var OtlpFileSink = class {
217347
217947
  failed = false;
217348
217948
  async initialize() {
217349
217949
  try {
217350
- await (0, import_promises2.mkdir)(import_path2.default.dirname(this.filePath), { recursive: true });
217351
- this.size = await (0, import_promises2.stat)(this.filePath).then((info) => info.size).catch((error40) => {
217950
+ await (0, import_promises3.mkdir)(import_path2.default.dirname(this.filePath), { recursive: true });
217951
+ this.size = await (0, import_promises3.stat)(this.filePath).then((info) => info.size).catch((error40) => {
217352
217952
  if (isNodeError(error40, "ENOENT")) return 0;
217353
217953
  throw error40;
217354
217954
  });
217355
- this.handle = await (0, import_promises2.open)(this.filePath, "a", 384);
217955
+ this.handle = await (0, import_promises3.open)(this.filePath, "a", 384);
217356
217956
  } catch {
217357
217957
  this.failed = true;
217358
217958
  this.report("otlp_file_open_failed");
@@ -217402,16 +218002,16 @@ var OtlpFileSink = class {
217402
218002
  async rotate() {
217403
218003
  await this.handle?.close();
217404
218004
  this.handle = void 0;
217405
- await (0, import_promises2.rm)(`${this.filePath}.3`, { force: true });
218005
+ await (0, import_promises3.rm)(`${this.filePath}.3`, { force: true });
217406
218006
  for (let index2 = 2; index2 >= 0; index2--) {
217407
- await (0, import_promises2.rename)(
218007
+ await (0, import_promises3.rename)(
217408
218008
  index2 ? `${this.filePath}.${index2}` : this.filePath,
217409
218009
  `${this.filePath}.${index2 + 1}`
217410
218010
  ).catch((error40) => {
217411
218011
  if (!isNodeError(error40, "ENOENT")) throw error40;
217412
218012
  });
217413
218013
  }
217414
- this.handle = await (0, import_promises2.open)(this.filePath, "a", 384);
218014
+ this.handle = await (0, import_promises3.open)(this.filePath, "a", 384);
217415
218015
  this.size = 0;
217416
218016
  }
217417
218017
  report(code) {
@@ -217541,13 +218141,13 @@ async function createAgentDevTelemetry(agentId, agentLogPath, diagnostic, env2 =
217541
218141
 
217542
218142
  // src/commands/agentdev/worker.ts
217543
218143
  var import_http219 = require("http");
217544
- var import_promises6 = require("fs/promises");
218144
+ var import_promises7 = require("fs/promises");
217545
218145
  var import_os = require("os");
217546
218146
  var import_path59 = __toESM(require("path"));
217547
218147
  var import_stream2 = require("stream");
217548
218148
 
217549
218149
  // src/commands/agentdev/sandboxIntegrate/protocolReader.ts
217550
- var import_promises3 = require("fs/promises");
218150
+ var import_promises4 = require("fs/promises");
217551
218151
  var ProtocolConfigError = class extends Error {
217552
218152
  constructor(message, configPath) {
217553
218153
  super(message);
@@ -217558,7 +218158,7 @@ var ProtocolConfigError = class extends Error {
217558
218158
  var readProtocolFromConfig = async (configPath) => {
217559
218159
  let text2;
217560
218160
  try {
217561
- text2 = await (0, import_promises3.readFile)(configPath, "utf8");
218161
+ text2 = await (0, import_promises4.readFile)(configPath, "utf8");
217562
218162
  } catch (cause) {
217563
218163
  throw new ProtocolConfigError(
217564
218164
  `failed to read agent config at ${configPath}: ${cause instanceof Error ? cause.message : String(cause)}`,
@@ -217823,7 +218423,7 @@ var RotatingLogWriter = class extends import_stream2.Writable {
217823
218423
  size = 0;
217824
218424
  async initialize() {
217825
218425
  this.size = await fileSize(this.logPath);
217826
- this.handle = await (0, import_promises6.open)(this.logPath, "a");
218426
+ this.handle = await (0, import_promises7.open)(this.logPath, "a");
217827
218427
  }
217828
218428
  _write(chunk, _encoding, callback) {
217829
218429
  void this.append(chunk).then(
@@ -217852,20 +218452,20 @@ var RotatingLogWriter = class extends import_stream2.Writable {
217852
218452
  }
217853
218453
  async rotate() {
217854
218454
  await this.close();
217855
- await (0, import_promises6.rm)(`${this.logPath}.${LOG_ROTATIONS}`, { force: true });
218455
+ await (0, import_promises7.rm)(`${this.logPath}.${LOG_ROTATIONS}`, { force: true });
217856
218456
  for (let generation = LOG_ROTATIONS - 1; generation >= 1; generation--) {
217857
- await (0, import_promises6.rename)(
218457
+ await (0, import_promises7.rename)(
217858
218458
  `${this.logPath}.${generation}`,
217859
218459
  `${this.logPath}.${generation + 1}`
217860
218460
  ).catch((error40) => {
217861
218461
  if (!isNodeError(error40, "ENOENT")) throw error40;
217862
218462
  });
217863
218463
  }
217864
- await (0, import_promises6.rename)(this.logPath, `${this.logPath}.1`).catch((error40) => {
218464
+ await (0, import_promises7.rename)(this.logPath, `${this.logPath}.1`).catch((error40) => {
217865
218465
  if (!isNodeError(error40, "ENOENT")) throw error40;
217866
218466
  });
217867
218467
  this.size = 0;
217868
- this.handle = await (0, import_promises6.open)(this.logPath, "a");
218468
+ this.handle = await (0, import_promises7.open)(this.logPath, "a");
217869
218469
  }
217870
218470
  async close() {
217871
218471
  const handle = this.handle;
@@ -217875,7 +218475,7 @@ var RotatingLogWriter = class extends import_stream2.Writable {
217875
218475
  };
217876
218476
  var fileSize = async (filePath) => {
217877
218477
  try {
217878
- return (await (0, import_promises6.stat)(filePath)).size;
218478
+ return (await (0, import_promises7.stat)(filePath)).size;
217879
218479
  } catch (error40) {
217880
218480
  if (isNodeError(error40, "ENOENT")) return 0;
217881
218481
  throw error40;
@@ -217909,8 +218509,8 @@ var decodeInput = () => JSON.parse(
217909
218509
  );
217910
218510
  var removeOwnedState = async (statePath) => {
217911
218511
  try {
217912
- const state2 = JSON.parse(await (0, import_promises6.readFile)(statePath, "utf8"));
217913
- if (state2.pid === process.pid) await (0, import_promises6.rm)(statePath, { force: true });
218512
+ const state2 = JSON.parse(await (0, import_promises7.readFile)(statePath, "utf8"));
218513
+ if (state2.pid === process.pid) await (0, import_promises7.rm)(statePath, { force: true });
217914
218514
  } catch {
217915
218515
  return;
217916
218516
  }
@@ -218113,7 +218713,7 @@ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array
218113
218713
  var errorMessage4 = (error40) => error40 instanceof Error ? error40.message : "unknown agent error";
218114
218714
  var main = async () => {
218115
218715
  const input = decodeInput();
218116
- await (0, import_promises6.mkdir)(import_path59.default.dirname(input.logPath), { recursive: true });
218716
+ await (0, import_promises7.mkdir)(import_path59.default.dirname(input.logPath), { recursive: true });
218117
218717
  const log = new RotatingLogWriter(input.logPath);
218118
218718
  await log.initialize();
218119
218719
  log.write(