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.
@@ -40,18 +40,19 @@ import {
40
40
  resolveRunStorage,
41
41
  toAgentRunMessages,
42
42
  withIsoTimestamp
43
- } from "../../chunk-STGFILDE.js";
43
+ } from "../../chunk-UIU24A4Z.js";
44
44
  import "../../chunk-IWOFD643.js";
45
45
  import "../../chunk-PXCGFBV5.js";
46
46
  import "../../chunk-ETG6PNHQ.js";
47
47
  import {
48
48
  getBakedProtocol
49
- } from "../../chunk-JD3IL3IC.js";
49
+ } from "../../chunk-CBGTFDSE.js";
50
50
  import {
51
51
  ACTIVATE_SKILL_TOOL_NAME,
52
52
  CANCEL_CONVERSATION_RUN_OPERATION,
53
53
  CONTENT_VALUE_MAX_LENGTH,
54
54
  CONVERSATION_HISTORY_VERSION,
55
+ CancellationScope,
55
56
  CardActionDiagnostics,
56
57
  CardMappingError,
57
58
  ConversationControlValidationError,
@@ -115,6 +116,7 @@ import {
115
116
  RemoteGatewayMcpServerProvider,
116
117
  SideEffectRunner,
117
118
  WebSkillLoader,
119
+ abortableDelay,
118
120
  aggregateMcpServers,
119
121
  buildHookCommonParams,
120
122
  buildSkillCatalog,
@@ -161,9 +163,10 @@ import {
161
163
  startRuntimeObservation,
162
164
  streamToConversationEvents,
163
165
  summarizeBody,
166
+ waitWithSignal,
164
167
  warnLogFailure,
165
168
  wrapToolWithHooks
166
- } from "../../chunk-PM2UO433.js";
169
+ } from "../../chunk-EWGNYBVV.js";
167
170
  import "../../chunk-EAODRPW4.js";
168
171
  import "../../chunk-XUFLSZM4.js";
169
172
  import "../../chunk-GAYNLDWK.js";
@@ -7946,7 +7949,7 @@ var require_ignore = __commonJS({
7946
7949
  });
7947
7950
 
7948
7951
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js
7949
- import { randomUUID as randomUUID7 } from "node:crypto";
7952
+ import { randomUUID as randomUUID8 } from "node:crypto";
7950
7953
 
7951
7954
  // ../linkque-agent-runtime/dist/esm/core/telemetry/toolObservation.js
7952
7955
  import { randomUUID } from "node:crypto";
@@ -8167,7 +8170,7 @@ var PiTelemetry = class {
8167
8170
  });
8168
8171
  }
8169
8172
  };
8170
- async function* observeProviderStream(source, observation, signal) {
8173
+ async function* observeProviderStream(source, observation, signal, logical) {
8171
8174
  const started = performance.now();
8172
8175
  let chunks = 0;
8173
8176
  let textChars = 0;
@@ -8198,6 +8201,7 @@ async function* observeProviderStream(source, observation, signal) {
8198
8201
  if (!ended && (event.type === "done" || event.type === "error")) {
8199
8202
  ended = true;
8200
8203
  const message = event.type === "done" ? event.message : event.error;
8204
+ recordContentSection(logical, ETelemetryContentSection.MODEL_OUT_RAW, message.content, event.type === "done" ? "available" : "partial");
8201
8205
  observation.record(ETelemetryEventName.MODEL_USAGE_RECORDED, projectProviderUsage(message.usage));
8202
8206
  observation.finish(event.type === "done" ? ETelemetryOutcome.SUCCESS : signal?.aborted ? ETelemetryOutcome.CANCELLED : ETelemetryOutcome.ERROR, {
8203
8207
  [ETelemetryAttribute.GEN_AI_RESPONSE_MODEL]: message.model,
@@ -8231,6 +8235,31 @@ async function* observeProviderStream(source, observation, signal) {
8231
8235
  });
8232
8236
  }
8233
8237
  }
8238
+ var previewModelInputText = (value) => ({
8239
+ length: value.length,
8240
+ text: value.slice(0, 256),
8241
+ truncated: value.length > 256
8242
+ });
8243
+ function summarizeModelInput(context) {
8244
+ return {
8245
+ systemPrompt: context.systemPrompt ? previewModelInputText(context.systemPrompt) : void 0,
8246
+ messageCount: context.messages.length,
8247
+ messages: context.messages.slice(-20).map((message) => ({
8248
+ role: message.role,
8249
+ content: typeof message.content === "string" ? previewModelInputText(message.content) : message.content.slice(0, 20).map((part) => {
8250
+ if (part.type === "text")
8251
+ return { type: part.type, ...previewModelInputText(part.text) };
8252
+ if (part.type === "toolCall")
8253
+ return { type: part.type, name: part.name };
8254
+ return { type: part.type };
8255
+ }),
8256
+ omittedContentCount: typeof message.content === "string" ? 0 : Math.max(0, message.content.length - 20)
8257
+ })),
8258
+ omittedMessageCount: Math.max(0, context.messages.length - 20),
8259
+ toolNames: context.tools?.slice(0, 50).map((tool) => tool.name) ?? [],
8260
+ omittedToolCount: Math.max(0, (context.tools?.length ?? 0) - 50)
8261
+ };
8262
+ }
8234
8263
  function projectProviderUsage(usage) {
8235
8264
  const source = usage && typeof usage === "object" ? usage : {};
8236
8265
  const result = {
@@ -39614,7 +39643,7 @@ var LlmRequestThrottle = class {
39614
39643
  const configured = options.minIntervalMs ?? DEFAULT_LLM_REQUEST_MIN_INTERVAL_MS;
39615
39644
  this.minIntervalMs = Number.isFinite(configured) && configured > 0 ? Math.floor(configured) : 0;
39616
39645
  this.now = options.now ?? Date.now;
39617
- this.delay = options.delay ?? delayWithSignal;
39646
+ this.delay = options.delay ?? abortableDelay;
39618
39647
  this.onDelay = options.onDelay ?? (() => {
39619
39648
  });
39620
39649
  }
@@ -39634,23 +39663,6 @@ var LlmRequestThrottle = class {
39634
39663
  return scheduled;
39635
39664
  }
39636
39665
  };
39637
- function delayWithSignal(delayMs, signal) {
39638
- return new Promise((resolve, reject) => {
39639
- if (signal?.aborted) {
39640
- reject(signal.reason);
39641
- return;
39642
- }
39643
- const timer = setTimeout(() => {
39644
- signal?.removeEventListener("abort", onAbort);
39645
- resolve();
39646
- }, delayMs);
39647
- const onAbort = () => {
39648
- clearTimeout(timer);
39649
- reject(signal?.reason);
39650
- };
39651
- signal?.addEventListener("abort", onAbort, { once: true });
39652
- });
39653
- }
39654
39666
 
39655
39667
  // ../linkque-agent-runtime/dist/esm/impl/agent/pi/createAgentSession.js
39656
39668
  function buildModelResponseHookError(model, lastMessage, error) {
@@ -39834,6 +39846,7 @@ async function createAgentSession(options) {
39834
39846
  throw error;
39835
39847
  }
39836
39848
  invocation = logical ? options.telemetry?.startProvider(model, logical) : void 0;
39849
+ recordContentSection(logical, ETelemetryContentSection.MODEL_INPUT_DIGEST, summarizeModelInput(context));
39837
39850
  const spanContext = invocation?.spanContext;
39838
39851
  const tracedModel = spanContext ? {
39839
39852
  ...model,
@@ -39852,7 +39865,7 @@ async function createAgentSession(options) {
39852
39865
  });
39853
39866
  throw error;
39854
39867
  }
39855
- const source = invocation ? observeProviderStream(rawSource, invocation, opts.signal) : rawSource;
39868
+ const source = invocation ? observeProviderStream(rawSource, invocation, opts.signal, logical) : rawSource;
39856
39869
  const observedSource = logSink ? observeModelStream(source, requestId, streamCreatedAt, logSink) : source;
39857
39870
  return options.hookRuntime ? gateModelResponseStream(observedSource, model, options.hookRuntime, () => gateState, logical) : observedSource;
39858
39871
  });
@@ -40594,6 +40607,7 @@ var StreamBridge = class {
40594
40607
  };
40595
40608
 
40596
40609
  // ../linkque-agent-runtime/dist/esm/impl/agent/pi/followUpQuestionGenerator.js
40610
+ import { randomUUID as randomUUID3 } from "node:crypto";
40597
40611
  var FOLLOW_UP_QUESTION_MODEL_ID = "Qwen3-30B-A3B-Instruct-2507";
40598
40612
  var FOLLOW_UP_QUESTION_TOOL_NAME = "submit_follow_up_questions";
40599
40613
  var FOLLOW_UP_QUESTION_TIMEOUT_MS = 4500;
@@ -40648,30 +40662,66 @@ var PiFollowUpQuestionGenerator = class {
40648
40662
  }
40649
40663
  ]
40650
40664
  };
40651
- const controller = new AbortController();
40652
- const timeout = setTimeout(() => controller.abort(), FOLLOW_UP_QUESTION_TIMEOUT_MS);
40665
+ const scope = new CancellationScope({
40666
+ timeoutMs: FOLLOW_UP_QUESTION_TIMEOUT_MS
40667
+ });
40668
+ const logical = input.observation?.startOperation({
40669
+ name: ETelemetryOperationName.MODEL_INVOKE,
40670
+ eventPrefix: ETelemetryEventPrefix.MODEL_INVOKE,
40671
+ attributes: {
40672
+ [ETelemetryAttribute.HARNESS_CALL_ID]: randomUUID3(),
40673
+ [ETelemetryAttribute.GEN_AI_REQUEST_MODEL]: FOLLOW_UP_QUESTION_MODEL_ID,
40674
+ [ETelemetryAttribute.GEN_AI_PROVIDER_NAME]: LINKQUE_PROVIDER_ID,
40675
+ [ETelemetryAttribute.HARNESS_MODEL_PURPOSE]: ETelemetryModelPurpose.FOLLOW_UP_QUESTION
40676
+ },
40677
+ detached: false,
40678
+ links: []
40679
+ });
40680
+ const attempt = logical?.startOperation({
40681
+ name: ETelemetryOperationName.MODEL_ATTEMPT,
40682
+ eventPrefix: ETelemetryEventPrefix.MODEL_ATTEMPT,
40683
+ attributes: {
40684
+ [ETelemetryAttribute.GEN_AI_OPERATION_NAME]: ETelemetryGenAiOperation.CHAT,
40685
+ [ETelemetryAttribute.GEN_AI_REQUEST_MODEL]: FOLLOW_UP_QUESTION_MODEL_ID,
40686
+ [ETelemetryAttribute.GEN_AI_PROVIDER_NAME]: LINKQUE_PROVIDER_ID,
40687
+ [ETelemetryAttribute.HARNESS_INVOCATION_ID]: randomUUID3(),
40688
+ [ETelemetryAttribute.HARNESS_ATTEMPT_ID]: randomUUID3(),
40689
+ [ETelemetryAttribute.HARNESS_ATTEMPT_VISIBILITY]: ETelemetryAttemptVisibility.PROVIDER_INVOCATION,
40690
+ [ETelemetryAttribute.HARNESS_TELEMETRY_SOURCE]: ETelemetrySource.PROVIDER
40691
+ },
40692
+ detached: false,
40693
+ links: []
40694
+ });
40695
+ recordContentSection(logical, ETelemetryContentSection.MODEL_INPUT_DIGEST, summarizeModelInput(context));
40653
40696
  try {
40654
40697
  input.debugLog?.(`[follow-up] request model=${FOLLOW_UP_QUESTION_MODEL_ID} messages=${input.context.messages.length}`, EDebugLogScope.LLM);
40655
40698
  const message = await models.complete(model, context, {
40656
40699
  apiKey: input.auth.apiKey,
40657
40700
  maxRetries: 0,
40658
40701
  maxTokens: 96,
40659
- signal: controller.signal,
40702
+ signal: scope.context.signal,
40660
40703
  temperature: 0.3,
40661
40704
  thinkingEnabled: false,
40662
40705
  timeoutMs: FOLLOW_UP_QUESTION_TIMEOUT_MS,
40663
40706
  toolChoice: { type: "tool", name: FOLLOW_UP_QUESTION_TOOL_NAME }
40664
40707
  });
40708
+ recordContentSection(logical, ETelemetryContentSection.MODEL_OUT_RAW, message.content);
40665
40709
  const toolCall = message.content.find((content) => content.type === "toolCall" && content.name === FOLLOW_UP_QUESTION_TOOL_NAME);
40666
40710
  const questions = normalizeFollowUpQuestionStrings(toolCall?.type === "toolCall" ? toolCall.arguments.questions : void 0);
40667
40711
  input.debugLog?.(`[follow-up] response stopReason=${message.stopReason} contentTypes=${message.content.map((content) => content.type).join(",")} toolCall=${Boolean(toolCall)} questions=${questions.length}`, EDebugLogScope.LLM);
40712
+ recordContentSection(logical, ETelemetryContentSection.FOLLOW_UP_QUESTION_INPUT, context.messages[0]?.content ?? "");
40713
+ recordContentSection(logical, ETelemetryContentSection.FOLLOW_UP_QUESTION_OUTPUT, questions);
40714
+ attempt?.finish(ETelemetryOutcome.SUCCESS, {});
40715
+ logical?.finish(ETelemetryOutcome.SUCCESS, {});
40668
40716
  return questions;
40669
40717
  } catch (error) {
40718
+ attempt?.finish(ETelemetryOutcome.ERROR, {});
40719
+ logical?.finish(ETelemetryOutcome.ERROR, {});
40670
40720
  const detail = error instanceof Error ? `${error.name}: ${error.message}` : typeof error;
40671
40721
  input.debugLog?.(`[follow-up] failed ${detail}`, EDebugLogScope.LLM);
40672
40722
  return [];
40673
40723
  } finally {
40674
- clearTimeout(timeout);
40724
+ scope.dispose();
40675
40725
  }
40676
40726
  }
40677
40727
  };
@@ -40813,36 +40863,230 @@ function safeStringify(value) {
40813
40863
  }
40814
40864
  }
40815
40865
 
40816
- // ../linkque-agent-runtime/dist/esm/core/telemetry/publicOutputObservation.js
40817
- var PublicOutputObservation = class {
40818
- root;
40819
- sources = /* @__PURE__ */ new WeakMap();
40820
- completedSources = /* @__PURE__ */ new WeakMap();
40821
- source;
40866
+ // ../linkque-agent-runtime/dist/esm/impl/plugin/mcpDiscoveryPlugin.js
40867
+ var MCP_DISCOVERY_PLUGIN_NAME = "mcp-discovery";
40868
+ var McpDiscoveryPlugin = class {
40869
+ name = MCP_DISCOVERY_PLUGIN_NAME;
40870
+ hookExecutorList = [
40871
+ {
40872
+ name: EHookExecutorName.McpDiscoveryHookExecutor,
40873
+ matches: (_resource, stage) => stage === EHookStage.PREPARE_AGENT_LOOP,
40874
+ execute: async (_resource, context, options) => {
40875
+ if (context.stage !== EHookStage.PREPARE_AGENT_LOOP)
40876
+ return { ok: true, skipped: true };
40877
+ const input = options?.runtimeInput;
40878
+ if (!input?.discoverMcpTools)
40879
+ return { ok: false, code: "MCP_DISCOVERY_RUNTIME_INPUT_MISSING" };
40880
+ const signal = AbortSignal.any([
40881
+ ...input.signal ? [input.signal] : [],
40882
+ ...options?.signal ? [options.signal] : []
40883
+ ]);
40884
+ const entries = await input.discoverMcpTools(signal);
40885
+ signal.throwIfAborted();
40886
+ return {
40887
+ ok: true,
40888
+ patch: {
40889
+ stage: EHookStage.PREPARE_AGENT_LOOP,
40890
+ systemPromptSuffixes: entries.length ? [formatCatalog(entries)] : []
40891
+ }
40892
+ };
40893
+ }
40894
+ }
40895
+ ];
40896
+ modifyAgentConfig = (config) => {
40897
+ if (!config.agent.resources.some((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL))
40898
+ return;
40899
+ const existing = config.agent.resources.filter((resource) => resource.resourceType === EResourceType.HOOK && resource.config.executorName === EHookExecutorName.McpDiscoveryHookExecutor);
40900
+ if (existing.length) {
40901
+ const hook = existing[0].config;
40902
+ 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)
40903
+ 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");
40904
+ hook.timeoutMs = 6e3;
40905
+ return;
40906
+ }
40907
+ config.agent.resources.push({
40908
+ resourceId: "mcp-discovery-prepare-agent-loop",
40909
+ resourceType: EResourceType.HOOK,
40910
+ providerType: EResourceProviderType.LINK_QUE,
40911
+ config: {
40912
+ name: "MCP \u5DE5\u5177\u76EE\u5F55\u9884\u52A0\u8F7D",
40913
+ executorName: EHookExecutorName.McpDiscoveryHookExecutor,
40914
+ stage: EHookStage.PREPARE_AGENT_LOOP,
40915
+ hasSideEffects: true,
40916
+ timeoutMs: 6e3
40917
+ }
40918
+ });
40919
+ };
40920
+ };
40921
+ function formatCatalog(entries) {
40922
+ return [
40923
+ "\u672C\u8F6E MCP \u5DE5\u5177\u76EE\u5F55\uFF08\u5DF2\u6309\u53EF\u89C1\u6743\u9650\u8FC7\u6EE4\uFF09\uFF1A",
40924
+ '\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',
40925
+ '\u4E0D\u53EF\u7528\u7684 server \u53EF\u901A\u8FC7 mcp({connect:"serverName"}) \u91CD\u8BD5\uFF1B\u672C\u76EE\u5F55\u4E0D\u5305\u542B\u53C2\u6570 schema\u3002',
40926
+ ...entries.map((entry) => JSON.stringify(entry))
40927
+ ].join("\n");
40928
+ }
40929
+
40930
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/publicContentAccumulator.js
40931
+ var PUBLIC_CONTENT_MAX_BYTES = 512 * 1024;
40932
+ var PublicContentAccumulator = class {
40933
+ observation;
40934
+ section;
40822
40935
  text = "";
40823
40936
  bytes = 0;
40824
40937
  index = 0;
40825
40938
  truncated = false;
40939
+ finished = false;
40940
+ pendingHighSurrogate = "";
40941
+ /** 创建正文累积器,将分块记录写入 observation,并以 section 标识内容类型。 */
40942
+ constructor(observation, section) {
40943
+ this.observation = observation;
40944
+ this.section = section;
40945
+ }
40946
+ /**
40947
+ * 接收一段正文,与上次暂存的高代理项拼接后,逐个码点交给 append() 累积。
40948
+ * 末尾尚未配对的高代理项暂存到下一次调用。
40949
+ */
40950
+ accept(content) {
40951
+ if (this.finished || this.truncated || !content)
40952
+ return;
40953
+ const text2 = this.pendingHighSurrogate + content;
40954
+ this.pendingHighSurrogate = "";
40955
+ const last = text2.charCodeAt(text2.length - 1);
40956
+ const endsWithHighSurrogate = last >= 55296 && last <= 56319;
40957
+ const ready = endsWithHighSurrogate ? text2.slice(0, -1) : text2;
40958
+ for (const character of ready) {
40959
+ this.append(character);
40960
+ if (this.truncated)
40961
+ return;
40962
+ }
40963
+ if (endsWithHighSurrogate)
40964
+ this.pendingHighSurrogate = text2.slice(-1);
40965
+ }
40966
+ /** 追加暂存的高代理项,写出带完整性标记的最终分块,并结束正文累积。 */
40967
+ finish(complete) {
40968
+ if (this.finished)
40969
+ return;
40970
+ this.finished = true;
40971
+ if (this.pendingHighSurrogate) {
40972
+ this.append(this.pendingHighSurrogate);
40973
+ this.pendingHighSurrogate = "";
40974
+ }
40975
+ if (this.bytes)
40976
+ this.flush(true, complete);
40977
+ }
40978
+ /** 将一个码点追加到缓冲并累计字节数;缓冲满时写出分块,总字节数超限时停止追加。 */
40979
+ append(character) {
40980
+ const size = Buffer.byteLength(character, "utf8");
40981
+ if (this.bytes + size > PUBLIC_CONTENT_MAX_BYTES) {
40982
+ this.truncated = true;
40983
+ return;
40984
+ }
40985
+ if (this.text.length + character.length > CONTENT_VALUE_MAX_LENGTH)
40986
+ this.flush(false, false);
40987
+ this.bytes += size;
40988
+ this.text += character;
40989
+ if (this.text.length === CONTENT_VALUE_MAX_LENGTH)
40990
+ this.flush(false, false);
40991
+ }
40992
+ /** 将当前缓冲写成一条正文记录,设置分块序号、最终标记和完整性,然后清空缓冲。 */
40993
+ flush(final, complete) {
40994
+ this.observation.record(ETelemetryEventName.CONTENT_RECORDED, {}, {
40995
+ section: this.section,
40996
+ value: this.text,
40997
+ chunkIndex: this.index++,
40998
+ final,
40999
+ availability: final && complete && !this.truncated ? "available" : "partial"
41000
+ });
41001
+ this.text = "";
41002
+ }
41003
+ };
41004
+
41005
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/publicReasoningObservation.js
41006
+ var PublicReasoningObservation = class {
41007
+ active;
41008
+ /** 返回当前思考段的来源 observation;没有正在采集的思考段时返回 undefined。 */
41009
+ get currentSource() {
41010
+ return this.active?.source;
41011
+ }
41012
+ /** 按来源创建或复用思考段,并追加思考文本;来源变化时先结束旧段。 */
41013
+ accept(content, source) {
41014
+ if (!content)
41015
+ return;
41016
+ if (source !== this.currentSource)
41017
+ this.finish(true);
41018
+ if (!source)
41019
+ return;
41020
+ if (!this.active) {
41021
+ const observation = source.startOperation({
41022
+ name: ETelemetryOperationName.MODEL_REASONING,
41023
+ eventPrefix: ETelemetryEventPrefix.MODEL_REASONING,
41024
+ attributes: {},
41025
+ detached: false,
41026
+ links: []
41027
+ });
41028
+ this.active = {
41029
+ source,
41030
+ observation,
41031
+ content: new PublicContentAccumulator(observation, ETelemetryContentSection.MODEL_REASONING)
41032
+ };
41033
+ }
41034
+ this.active.content.accept(content);
41035
+ }
41036
+ /** 写出当前思考段的剩余正文,按 complete 将其观察结束为成功或取消,并清除当前段。 */
41037
+ finish(complete) {
41038
+ const segment = this.active;
41039
+ if (!segment)
41040
+ return;
41041
+ this.active = void 0;
41042
+ segment.content.finish(complete);
41043
+ segment.observation.finish(complete ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.CANCELLED, {});
41044
+ }
41045
+ };
41046
+
41047
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/publicOutputObservation.js
41048
+ var PublicOutputObservation = class {
41049
+ root;
41050
+ eventSources = /* @__PURE__ */ new WeakMap();
41051
+ sources = /* @__PURE__ */ new Map();
41052
+ reasoning = new PublicReasoningObservation();
40826
41053
  firstText = false;
41054
+ finished = false;
40827
41055
  startedAt = performance.now();
41056
+ /** 创建本轮公开输出观察器,使用 root 记录首个公开回答片段的延迟。 */
40828
41057
  constructor(root) {
40829
41058
  this.root = root;
40830
41059
  }
41060
+ /** 保存事件与来源 observation 的对应关系,供 accept() 将正文归入该来源。 */
40831
41061
  associate(event, source) {
40832
- if (source)
40833
- this.sources.set(event, source);
41062
+ if (this.finished || !source)
41063
+ return;
41064
+ this.eventSources.set(event, source);
40834
41065
  }
40835
- /** 来源终态可能早于队列中的正文到达,不能在此提前刷空缓冲。 */
41066
+ /** 保存指定来源是否正常完成,供本轮结束时判断其正文的完整性。 */
40836
41067
  completeSource(source, complete) {
40837
- if (source)
40838
- this.completedSources.set(source, complete);
41068
+ if (this.finished || !source)
41069
+ return;
41070
+ this.source(source).completed = complete;
40839
41071
  }
41072
+ /**
41073
+ * 处理一个已放行的公开事件:累积回答或思考正文,记录首个回答片段的延迟,
41074
+ * 并在收到终态事件时结束本轮采集。
41075
+ */
40840
41076
  accept(event) {
41077
+ if (this.finished)
41078
+ return;
41079
+ const source = this.eventSources.get(event);
41080
+ this.eventSources.delete(event);
40841
41081
  if (event.type === "done" || event.type === "error") {
40842
- const completed = this.source ? this.completedSources.get(this.source) : void 0;
40843
- this.finish(completed ?? event.type === "done");
41082
+ this.close(event.type);
41083
+ return;
41084
+ }
41085
+ if (event.type === "thinking") {
41086
+ this.reasoning.accept(event.content, source);
40844
41087
  return;
40845
41088
  }
41089
+ this.reasoning.finish(true);
40846
41090
  if (event.type !== "delta" || !event.content)
40847
41091
  return;
40848
41092
  if (!this.firstText) {
@@ -40851,44 +41095,43 @@ var PublicOutputObservation = class {
40851
41095
  [ETelemetryAttribute.LINKQUE_LOOP_FIRST_PUBLIC_TEXT_MS]: performance.now() - this.startedAt
40852
41096
  });
40853
41097
  }
40854
- const source = this.sources.get(event);
40855
- if (!source)
40856
- return;
40857
- if (source !== this.source) {
40858
- this.finish(true);
40859
- this.source = source;
40860
- }
40861
- if (this.truncated)
40862
- return;
40863
- for (const character of event.content) {
40864
- const size = Buffer.byteLength(character, "utf8");
40865
- if (this.bytes + size > 512 * 1024) {
40866
- this.truncated = true;
40867
- break;
40868
- }
40869
- this.bytes += size;
40870
- this.text += character;
40871
- if (this.text.length >= 16 * 1024)
40872
- this.flush(false, false);
40873
- }
41098
+ if (source)
41099
+ this.source(source).output.accept(event.content);
40874
41100
  }
41101
+ /**
41102
+ * 结束本轮公开输出采集。
41103
+ * complete 为 true 表示事件流自然耗尽,为 false 表示消费者提前退出。
41104
+ */
40875
41105
  finish(complete) {
40876
- if (this.bytes)
40877
- this.flush(true, complete && (this.source ? this.completedSources.get(this.source) ?? true : true));
40878
- this.source = void 0;
40879
- this.bytes = 0;
40880
- this.index = 0;
40881
- this.truncated = false;
41106
+ this.close(complete ? "exhausted" : "interrupted");
40882
41107
  }
40883
- flush(final, complete) {
40884
- this.source?.record(ETelemetryEventName.CONTENT_RECORDED, {}, {
40885
- section: ETelemetryContentSection.MODEL_OUTPUT,
40886
- value: this.text,
40887
- chunkIndex: this.index++,
40888
- final,
40889
- availability: final && complete && !this.truncated ? "available" : "partial"
40890
- });
40891
- this.text = "";
41108
+ /**
41109
+ * 根据本轮结束原因和各来源的完成状态,写出剩余正文、结束思考观察,
41110
+ * 并清理来源状态和事件关联。
41111
+ */
41112
+ close(reason) {
41113
+ if (this.finished)
41114
+ return;
41115
+ this.finished = true;
41116
+ const complete = (source) => reason !== "interrupted" && (this.sources.get(source)?.completed ?? reason !== "error");
41117
+ const reasoningSource = this.reasoning.currentSource;
41118
+ if (reasoningSource)
41119
+ this.reasoning.finish(complete(reasoningSource));
41120
+ for (const [source, state2] of this.sources)
41121
+ state2.output.finish(complete(source));
41122
+ this.sources.clear();
41123
+ this.eventSources = /* @__PURE__ */ new WeakMap();
41124
+ }
41125
+ /** 获取指定 observation 的来源状态;首次访问时创建正文累积器并缓存。 */
41126
+ source(observation) {
41127
+ let source = this.sources.get(observation);
41128
+ if (!source) {
41129
+ source = {
41130
+ output: new PublicContentAccumulator(observation, ETelemetryContentSection.MODEL_OUTPUT)
41131
+ };
41132
+ this.sources.set(observation, source);
41133
+ }
41134
+ return source;
40892
41135
  }
40893
41136
  };
40894
41137
 
@@ -41021,7 +41264,7 @@ var resolveAgentRuntimeHookExecutor = (plugins = [], portHookExecutorList = [],
41021
41264
  };
41022
41265
 
41023
41266
  // ../linkque-agent-runtime/dist/esm/core/cardSourceResult.js
41024
- import { randomUUID as randomUUID3 } from "node:crypto";
41267
+ import { randomUUID as randomUUID4 } from "node:crypto";
41025
41268
  var MAX_RECEIPT_BYTES = 1e5;
41026
41269
  var MAX_PREVIEW_ITEMS = 10;
41027
41270
  var MAX_PREVIEW_TEXT = 160;
@@ -41031,7 +41274,7 @@ var DEFAULT_TEXT_PAGE = 1600;
41031
41274
  var MAX_TEXT_PAGE = 4e3;
41032
41275
  var MAX_OMISSIONS = 32;
41033
41276
  async function createCardSourceReceipt(input) {
41034
- const resultRef = `card-source-result-${randomUUID3()}`;
41277
+ const resultRef = `card-source-result-${randomUUID4()}`;
41035
41278
  try {
41036
41279
  const result = await buildCardSourceReceipt(input, resultRef);
41037
41280
  if (byteLength(result.receipt) > MAX_RECEIPT_BYTES)
@@ -41901,8 +42144,8 @@ var CardRenderMcpServerProvider = class {
41901
42144
  constructor(inner) {
41902
42145
  this.inner = inner;
41903
42146
  }
41904
- async servers(resources) {
41905
- return this.inner.servers(resources);
42147
+ async servers(resources, signal) {
42148
+ return this.inner.servers(resources, signal);
41906
42149
  }
41907
42150
  };
41908
42151
 
@@ -42012,7 +42255,15 @@ var AgentRuntime = class _AgentRuntime {
42012
42255
  */
42013
42256
  static create(protocol, ports) {
42014
42257
  const portsArg = ports ?? {};
42015
- const agentConfig = applyAgentRuntimePluginConfig(protocol, portsArg.plugins);
42258
+ const plugins = [...portsArg.plugins ?? []];
42259
+ let agentConfig = applyAgentRuntimePluginConfig(protocol, plugins);
42260
+ if (!plugins.some((plugin) => plugin.name === MCP_DISCOVERY_PLUGIN_NAME) && agentConfig.agent.resources.some((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL)) {
42261
+ const discoveryPlugin = new McpDiscoveryPlugin();
42262
+ plugins.push(discoveryPlugin);
42263
+ agentConfig = applyAgentRuntimePluginConfig(agentConfig, [
42264
+ discoveryPlugin
42265
+ ]);
42266
+ }
42016
42267
  const webSearchResource = resolveWebSearchResource(agentConfig.agent.resources);
42017
42268
  const model = agentConfig.agent.model;
42018
42269
  const skillResources = agentConfig.agent.resources.filter((r) => r.resourceType === EResourceType.SKILL);
@@ -42025,6 +42276,7 @@ var AgentRuntime = class _AgentRuntime {
42025
42276
  const innerProvider = portsArg.mcpServerProvider ?? new NoopMcpServerProvider();
42026
42277
  const rt = new _AgentRuntime({
42027
42278
  ...portsArg,
42279
+ plugins,
42028
42280
  mcpServerProvider: new CardRenderMcpServerProvider(innerProvider)
42029
42281
  });
42030
42282
  rt.defaultSystemPrompt = agentConfig.agent.systemPrompt.content;
@@ -42053,14 +42305,37 @@ var AgentRuntime = class _AgentRuntime {
42053
42305
  return prepareFollowUpQuestionContext(await this.sessionManager.load(sessionId), history);
42054
42306
  }
42055
42307
  async generateFollowUpQuestions(context, auth, input) {
42056
- return this.followUpQuestionGenerator.generate({
42057
- auth,
42058
- context,
42308
+ const observation = startRuntimeObservation(this.telemetry, {
42059
42309
  runId: input.runId,
42060
- runtimeContext: input.runtimeContext,
42061
- requestSource: input.requestSource,
42062
- debugLog: this.portsDebugLog
42310
+ agentId: input.runtimeContext?.agentId ?? this.agentId,
42311
+ sessionId: "",
42312
+ conversationId: input.runtimeContext?.threadId ?? "",
42313
+ context: input.telemetryContext ?? {
42314
+ parent: null,
42315
+ authorization: null,
42316
+ requestId: "",
42317
+ turnId: "",
42318
+ accountId: "",
42319
+ channel: "",
42320
+ userKey: ""
42321
+ }
42063
42322
  });
42323
+ try {
42324
+ const questions = await this.followUpQuestionGenerator.generate({
42325
+ auth,
42326
+ context,
42327
+ runId: input.runId,
42328
+ observation,
42329
+ runtimeContext: input.runtimeContext,
42330
+ requestSource: input.requestSource,
42331
+ debugLog: this.portsDebugLog
42332
+ });
42333
+ observation.finish(ETelemetryOutcome.SUCCESS, {});
42334
+ return questions;
42335
+ } catch (error) {
42336
+ observation.finish(ETelemetryOutcome.ERROR, {});
42337
+ throw error;
42338
+ }
42064
42339
  }
42065
42340
  /** 产出 AgentStreamEvent 流;内核编排「解析上行资源 → 组请求 → agent loop」。 */
42066
42341
  async *runAgentLoop(request, auth, options = {}) {
@@ -42112,13 +42387,17 @@ var AgentRuntime = class _AgentRuntime {
42112
42387
  [ETelemetryAttribute.HARNESS_TELEMETRY_COMPLETENESS]: this.agentLoop instanceof PiAgentLoop ? ETelemetryCompleteness.COMPLETE : ETelemetryCompleteness.PARTIAL
42113
42388
  });
42114
42389
  this.recordCurrentQuery(observation, request);
42390
+ const runScope = new CancellationScope({
42391
+ signals: options.signal ? [options.signal] : []
42392
+ });
42393
+ const runOptions = { ...options, signal: runScope.context.signal };
42115
42394
  const cleanup = [];
42116
42395
  let termination = ETelemetryStreamTermination.CANCEL;
42117
42396
  let failed = false;
42118
42397
  let primaryFailure = false;
42119
42398
  let cleanupOutcome = ETelemetryOutcome.SUCCESS;
42120
42399
  try {
42121
- for await (const event of this.runObserved(request, auth, options, observation, cleanup)) {
42400
+ for await (const event of this.runObserved(request, auth, runOptions, observation, cleanup)) {
42122
42401
  if (event.type === "error") {
42123
42402
  failed = true;
42124
42403
  termination = ETelemetryStreamTermination.ERROR;
@@ -42136,6 +42415,7 @@ var AgentRuntime = class _AgentRuntime {
42136
42415
  termination = cancelled && !failed ? ETelemetryStreamTermination.CANCEL : ETelemetryStreamTermination.ERROR;
42137
42416
  throw error;
42138
42417
  } finally {
42418
+ runScope.cancel(new DOMException("Run \u5DF2\u7ED3\u675F", "AbortError"));
42139
42419
  const cleaning = observation.startOperation({
42140
42420
  name: ETelemetryOperationName.CLEANUP,
42141
42421
  eventPrefix: ETelemetryEventPrefix.OPERATION,
@@ -42149,6 +42429,7 @@ var AgentRuntime = class _AgentRuntime {
42149
42429
  failed = true;
42150
42430
  });
42151
42431
  } finally {
42432
+ runScope.dispose();
42152
42433
  cleaning.finish(cleanupOutcome, {});
42153
42434
  observation.closePending();
42154
42435
  observation.finish(failed ? ETelemetryOutcome.ERROR : termination === ETelemetryStreamTermination.CANCEL ? ETelemetryOutcome.CANCELLED : termination === ETelemetryStreamTermination.COMPLETE ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.UNKNOWN, {
@@ -42258,6 +42539,16 @@ var AgentRuntime = class _AgentRuntime {
42258
42539
  return false;
42259
42540
  }
42260
42541
  });
42542
+ const mcpServerSpecs = this.mcpServerSpecs;
42543
+ if (mcpServerSpecs.length === 0) {
42544
+ debugLog?.("[mcp] no mcp servers configured (no MCP tools will be available)", EDebugLogScope.MCP);
42545
+ }
42546
+ const mcpProxy = new McpProxyTool(this.mcpServerProvider, mcpServerSpecs, {
42547
+ debugLog,
42548
+ signal: options.signal,
42549
+ ...options.mcpCallAuthorizer ? { authorizeCall: options.mcpCallAuthorizer } : {}
42550
+ });
42551
+ cleanup.push(() => mcpProxy.closeAll());
42261
42552
  const hasPrepareHook = hookDispatcher.hasMatchingResource(EHookStage.PREPARE_AGENT_LOOP);
42262
42553
  if (hasPrepareHook && !this.effectiveAgentConfig) {
42263
42554
  throw new Error("Hook Runtime \u7F3A\u5C11\u6700\u7EC8 Agent Config");
@@ -42265,6 +42556,7 @@ var AgentRuntime = class _AgentRuntime {
42265
42556
  const model = options.model ?? this.defaultModel;
42266
42557
  const prepareResult = hasPrepareHook ? await hookDispatcher.dispatch(EHookStage.PREPARE_AGENT_LOOP, hookCommonParams, {}, {
42267
42558
  stage: EHookStage.PREPARE_AGENT_LOOP,
42559
+ discoverMcpTools: (signal) => mcpProxy.discover(signal),
42268
42560
  auth: { ...auth },
42269
42561
  historyTurns: structuredClone(history),
42270
42562
  currentTurns: structuredClone(newTurns),
@@ -42281,15 +42573,6 @@ var AgentRuntime = class _AgentRuntime {
42281
42573
  const skillRecords = this.skillResources.length ? await this.skillLoader.load(this.skillResources) : [];
42282
42574
  const skillCatalog = buildSkillCatalog(skillRecords);
42283
42575
  const activateSkillTool = createActivateSkillTool(skillRecords);
42284
- const mcpServerSpecs = this.mcpServerSpecs;
42285
- if (mcpServerSpecs.length === 0) {
42286
- debugLog?.("[mcp] no mcp servers configured (no MCP tools will be available)", EDebugLogScope.MCP);
42287
- }
42288
- const mcpProxy = new McpProxyTool(this.mcpServerProvider, mcpServerSpecs, {
42289
- debugLog,
42290
- ...options.mcpCallAuthorizer ? { authorizeCall: options.mcpCallAuthorizer } : {}
42291
- });
42292
- cleanup.push(() => mcpProxy.closeAll());
42293
42576
  const cardServer = new CardRenderMcpServer(this.cardResources, mcpProxy, { ...options.runtimeContext, threadId: request.threadId }, debugLog);
42294
42577
  cleanup.push(() => cardServer.close().catch(() => false));
42295
42578
  const cardTools = await cardServer.listTools();
@@ -42358,6 +42641,7 @@ var AgentRuntime = class _AgentRuntime {
42358
42641
  commonParams: hookCommonParams
42359
42642
  };
42360
42643
  }
42644
+ options.signal?.throwIfAborted();
42361
42645
  const runStartedAt = Date.now();
42362
42646
  if (!hookDispatcher.isEmpty) {
42363
42647
  await hookDispatcher.dispatch(EHookStage.RUN_STARTED, hookCommonParams);
@@ -42678,17 +42962,12 @@ function parseImageEnvelope(envelope, imageId, mode) {
42678
42962
  async function waitForObservation(promise, signal) {
42679
42963
  if (signal.aborted)
42680
42964
  imageError("IMAGE_CANCELLED");
42681
- let cancel;
42682
42965
  try {
42683
- return await Promise.race([
42684
- promise,
42685
- new Promise((_resolve, reject) => {
42686
- cancel = () => reject(new Error("IMAGE_CANCELLED"));
42687
- signal.addEventListener("abort", cancel, { once: true });
42688
- })
42689
- ]);
42690
- } finally {
42691
- signal.removeEventListener("abort", cancel);
42966
+ return await waitWithSignal(promise, signal);
42967
+ } catch (error) {
42968
+ if (signal.aborted)
42969
+ imageError("IMAGE_CANCELLED");
42970
+ throw error;
42692
42971
  }
42693
42972
  }
42694
42973
  function createImageTool(image, input, options, rules) {
@@ -42715,90 +42994,95 @@ function createImageTool(image, input, options, rules) {
42715
42994
  if (++calls > 3)
42716
42995
  imageError("IMAGE_CALL_LIMIT");
42717
42996
  const parsed = parseArgs(args, image.id);
42718
- const signal = AbortSignal.any([
42719
- AbortSignal.timeout(3e4),
42720
- ...[input.signal, executeSignal].filter((s) => !!s)
42721
- ]);
42722
- if (signal.aborted)
42723
- imageError("IMAGE_CANCELLED");
42724
- const key = auth.apiKey?.trim();
42725
- if (auth.provider !== EModelProvider.LINKQUE || !key || /\s|^Bearer\b/i.test(key) || key.includes("${") && !(options.allowSandboxAccessKeyPlaceholder === true && key === "${LINKQUE_AGENT_ACCESS_KEY}"))
42726
- imageError("IMAGE_AUTH_REQUIRED");
42727
- const cacheKey = JSON.stringify(parsed);
42728
- const existing = cache.get(cacheKey);
42729
- if (existing)
42730
- return structuredClone(await waitForObservation(existing, signal));
42731
- const pending = (async () => {
42732
- try {
42733
- const resolved = await resolveImage(image, fetchImpl, rules, signal);
42734
- const response = await fetchImpl(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
42735
- method: "POST",
42736
- signal,
42737
- redirect: "error",
42738
- headers: {
42739
- "content-type": "application/json",
42740
- "x-api-key": key,
42741
- "x-agent-id": input.agentId,
42742
- "x-run-id": input.runId,
42743
- "x-chat-id": input.threadId,
42744
- "x-step-id": context?.toolCallId ?? `inspect-image-${calls}`
42745
- },
42746
- body: JSON.stringify({
42747
- model: "linkque-image-understanding",
42748
- stream: false,
42749
- max_tokens: 1600,
42750
- system: IMAGE_PROMPT,
42751
- messages: [
42752
- {
42753
- role: "user",
42754
- content: [
42755
- {
42756
- type: "text",
42757
- text: JSON.stringify({
42758
- version: "image-request-v1",
42759
- imageId: image.id,
42760
- mode: parsed.mode,
42761
- userQuery: parsed.query
42762
- })
42763
- },
42764
- {
42765
- type: "image",
42766
- source: {
42767
- type: "base64",
42768
- media_type: resolved.mediaType,
42769
- data: resolved.data
42770
- }
42771
- }
42772
- ]
42773
- }
42774
- ]
42775
- })
42776
- });
42777
- if (!response.ok) {
42778
- await response.body?.cancel();
42779
- imageError("IMAGE_GATEWAY_REJECTED");
42780
- }
42781
- let envelope;
42997
+ const scope = new CancellationScope({
42998
+ timeoutMs: 3e4,
42999
+ signals: [input.signal, executeSignal].filter((s) => !!s)
43000
+ });
43001
+ const signal = scope.context.signal;
43002
+ try {
43003
+ if (signal.aborted)
43004
+ imageError("IMAGE_CANCELLED");
43005
+ const key = auth.apiKey?.trim();
43006
+ if (auth.provider !== EModelProvider.LINKQUE || !key || /\s|^Bearer\b/i.test(key) || key.includes("${") && !(options.allowSandboxAccessKeyPlaceholder === true && key === "${LINKQUE_AGENT_ACCESS_KEY}"))
43007
+ imageError("IMAGE_AUTH_REQUIRED");
43008
+ const cacheKey = JSON.stringify(parsed);
43009
+ const existing = cache.get(cacheKey);
43010
+ if (existing)
43011
+ return structuredClone(await waitForObservation(existing, signal));
43012
+ const pending = (async () => {
42782
43013
  try {
42783
- envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await boundedBody(response, 128 * 1024)));
42784
- } catch {
42785
- imageError("IMAGE_OUTPUT_INVALID_ENVELOPE_JSON");
43014
+ const resolved = await resolveImage(image, fetchImpl, rules, signal);
43015
+ const response = await fetchImpl(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
43016
+ method: "POST",
43017
+ signal,
43018
+ redirect: "error",
43019
+ headers: {
43020
+ "content-type": "application/json",
43021
+ "x-api-key": key,
43022
+ "x-agent-id": input.agentId,
43023
+ "x-run-id": input.runId,
43024
+ "x-chat-id": input.threadId,
43025
+ "x-step-id": context?.toolCallId ?? `inspect-image-${calls}`
43026
+ },
43027
+ body: JSON.stringify({
43028
+ model: "linkque-image-understanding",
43029
+ stream: false,
43030
+ max_tokens: 1600,
43031
+ system: IMAGE_PROMPT,
43032
+ messages: [
43033
+ {
43034
+ role: "user",
43035
+ content: [
43036
+ {
43037
+ type: "text",
43038
+ text: JSON.stringify({
43039
+ version: "image-request-v1",
43040
+ imageId: image.id,
43041
+ mode: parsed.mode,
43042
+ userQuery: parsed.query
43043
+ })
43044
+ },
43045
+ {
43046
+ type: "image",
43047
+ source: {
43048
+ type: "base64",
43049
+ media_type: resolved.mediaType,
43050
+ data: resolved.data
43051
+ }
43052
+ }
43053
+ ]
43054
+ }
43055
+ ]
43056
+ })
43057
+ });
43058
+ if (!response.ok) {
43059
+ await response.body?.cancel();
43060
+ imageError("IMAGE_GATEWAY_REJECTED");
43061
+ }
43062
+ let envelope;
43063
+ try {
43064
+ envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await boundedBody(response, 128 * 1024)));
43065
+ } catch {
43066
+ imageError("IMAGE_OUTPUT_INVALID_ENVELOPE_JSON");
43067
+ }
43068
+ return parseImageEnvelope(envelope, image.id, parsed.mode);
43069
+ } catch (error) {
43070
+ if (signal.aborted)
43071
+ imageError("IMAGE_CANCELLED");
43072
+ if (error instanceof Error && /^IMAGE_[A-Z_]+$/.test(error.message))
43073
+ throw error;
43074
+ imageError("IMAGE_REQUEST_FAILED");
42786
43075
  }
42787
- return parseImageEnvelope(envelope, image.id, parsed.mode);
43076
+ })();
43077
+ cache.set(cacheKey, pending);
43078
+ try {
43079
+ return structuredClone(await pending);
42788
43080
  } catch (error) {
42789
- if (signal.aborted)
42790
- imageError("IMAGE_CANCELLED");
42791
- if (error instanceof Error && /^IMAGE_[A-Z_]+$/.test(error.message))
42792
- throw error;
42793
- imageError("IMAGE_REQUEST_FAILED");
43081
+ cache.delete(cacheKey);
43082
+ throw error;
42794
43083
  }
42795
- })();
42796
- cache.set(cacheKey, pending);
42797
- try {
42798
- return structuredClone(await pending);
42799
- } catch (error) {
42800
- cache.delete(cacheKey);
42801
- throw error;
43084
+ } finally {
43085
+ scope.dispose();
42802
43086
  }
42803
43087
  }
42804
43088
  };
@@ -42915,12 +43199,12 @@ var ImageUnderstandingPlugin = class {
42915
43199
  message: "\u4E3B\u6A21\u578B\u672A\u786E\u8BA4\u539F\u751F\u56FE\u7247\u6216 Tool Use \u80FD\u529B"
42916
43200
  };
42917
43201
  if (capability.nativeImages && currentImage) {
43202
+ const scope = new CancellationScope({
43203
+ timeoutMs: 4e3,
43204
+ signals: [input.signal, execution?.signal].filter((s) => !!s)
43205
+ });
42918
43206
  try {
42919
- const signal = AbortSignal.any([
42920
- AbortSignal.timeout(4e3),
42921
- ...[input.signal, execution?.signal].filter((s) => !!s)
42922
- ]);
42923
- const resolved = await resolveImage(image, this.options.fetchImpl ?? globalThis.fetch, this.options.imageUrlRules, signal);
43207
+ const resolved = await resolveImage(image, this.options.fetchImpl ?? globalThis.fetch, this.options.imageUrlRules, scope.context.signal);
42924
43208
  modelTurns[selected.index].attachments = [
42925
43209
  {
42926
43210
  id: image.id,
@@ -42945,6 +43229,8 @@ var ImageUnderstandingPlugin = class {
42945
43229
  code: "IMAGE_FETCH_FAILED",
42946
43230
  message: "\u56FE\u7247\u4E0D\u53EF\u7528\uFF0C\u8BF7\u91CD\u65B0\u4E0A\u4F20"
42947
43231
  };
43232
+ } finally {
43233
+ scope.dispose();
42948
43234
  }
42949
43235
  }
42950
43236
  return {
@@ -43431,7 +43717,7 @@ function guardChatRequest(method, bodyJSON, logCtx) {
43431
43717
 
43432
43718
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationHistoryStore.js
43433
43719
  import { emitWarning } from "node:process";
43434
- import { randomUUID as randomUUID4 } from "node:crypto";
43720
+ import { randomUUID as randomUUID5 } from "node:crypto";
43435
43721
 
43436
43722
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationSearchStore.js
43437
43723
  import { createHash } from "node:crypto";
@@ -44229,7 +44515,7 @@ function createStoredHistoryRequest(request) {
44229
44515
  };
44230
44516
  }
44231
44517
  function createConversationThreadId() {
44232
- return `thread-${Date.now()}-${randomUUID4().replaceAll("-", "").slice(0, 12)}`;
44518
+ return `thread-${Date.now()}-${randomUUID5().replaceAll("-", "").slice(0, 12)}`;
44233
44519
  }
44234
44520
  function readRunStatus(value) {
44235
44521
  return value === "done" || value === "error" || value === "cancelling" || value === "cancelled" ? value : "running";
@@ -45651,7 +45937,7 @@ async function* debugLogAgentStream(stream, debugLog) {
45651
45937
  }
45652
45938
 
45653
45939
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/clientCapabilityTool.js
45654
- import { randomUUID as randomUUID5 } from "node:crypto";
45940
+ import { randomUUID as randomUUID6 } from "node:crypto";
45655
45941
  var POLL_INTERVAL_MS = 500;
45656
45942
  var LOCATION_WAIT_MS = 2e4;
45657
45943
  var ROW_TTL_MS = 3 * 6e4;
@@ -45689,7 +45975,7 @@ function createClientCapabilityTool(input) {
45689
45975
  if (pending)
45690
45976
  return failure("CLIENT_CAPABILITY_BUSY", "\u5DF2\u6709\u5B9A\u4F4D\u8C03\u7528\u6B63\u5728\u7B49\u5F85");
45691
45977
  pending = true;
45692
- const invocationId = randomUUID5();
45978
+ const invocationId = randomUUID6();
45693
45979
  const now = Date.now();
45694
45980
  const acceptUntil = new Date(now + LOCATION_WAIT_MS).toISOString();
45695
45981
  const event = {
@@ -45767,7 +46053,7 @@ function wait(ms, signal) {
45767
46053
  }
45768
46054
 
45769
46055
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/mcpPhoneAuthorization.js
45770
- import { randomUUID as randomUUID6 } from "node:crypto";
46056
+ import { randomUUID as randomUUID7 } from "node:crypto";
45771
46057
  var POLL_INTERVAL_MS2 = 500;
45772
46058
  var AUTH_WAIT_MS = 95e3;
45773
46059
  var ROW_TTL_MS2 = 3 * 6e4;
@@ -45787,7 +46073,7 @@ function createMcpPhoneAuthorizer(input) {
45787
46073
  throw authError("AUTH_UNAVAILABLE", "\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u83B7\u53D6\u624B\u673A\u53F7\u6388\u6743");
45788
46074
  return void 0;
45789
46075
  }
45790
- const invocationId = randomUUID6();
46076
+ const invocationId = randomUUID7();
45791
46077
  const now = Date.now();
45792
46078
  const acceptUntil = new Date(now + AUTH_WAIT_MS).toISOString();
45793
46079
  const capabilityInput = { scopes: ["auth_user"] };
@@ -46141,7 +46427,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
46141
46427
  const cfg = resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth, temporaryFrontendAppId);
46142
46428
  if ("status" in cfg)
46143
46429
  return cfg;
46144
- const leaseOwnerId = randomUUID7();
46430
+ const leaseOwnerId = randomUUID8();
46145
46431
  let leaseAcquired = false;
46146
46432
  let leaseReleased = false;
46147
46433
  const releaseLease = async () => {
@@ -46354,6 +46640,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
46354
46640
  const questions = await cfg.runtime.generateFollowUpQuestions(preparedFollowUpContext, cfg.auth, {
46355
46641
  runId: request.runId,
46356
46642
  requestSource: EModelRequestSource.APPBASE_FUNCTION,
46643
+ telemetryContext: cfg.telemetry?.createContext(request.runId),
46357
46644
  runtimeContext: {
46358
46645
  agentId: cfg.protocol.agentId,
46359
46646
  threadId: request.threadId,