linkque-cli-v2 1.5.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (18) hide show
  1. package/dataTransformWorker.js +1880 -0
  2. package/emscripten-module.wasm +0 -0
  3. package/linkquejs.js +1277 -583
  4. package/package.json +1 -1
  5. package/vendor/linkque-agent-appwrite-integrate/data-transform/dataTransformWorker.js +1880 -0
  6. package/vendor/linkque-agent-appwrite-integrate/data-transform/emscripten-module.wasm +0 -0
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-EWGNYBVV.js → chunk-2ZKZKYDK.js} +1935 -1205
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-GQ4TD3EQ.js → chunk-4XAZNSEQ.js} +1 -1
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-CBGTFDSE.js → chunk-CV22XO3R.js} +1 -2
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-UIU24A4Z.js → chunk-HINGKYT5.js} +2 -19
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{dist-TGBYXSBU.js → dist-ZPLSQEAM.js} +42 -27
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-generative-ai-ENBYCHYT.js → google-generative-ai-OLT56CSV.js} +1 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-vertex-RIGAEYLC.js → google-vertex-4DBBJ7SR.js} +1 -1
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +1251 -624
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +2 -2
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +2 -2
  17. package/vendor/linkque-agent-appwrite-integrate/package.json +1 -1
  18. package/worker.js +3166 -1872
@@ -7260,7 +7260,7 @@ var require_jmespath = __commonJS({
7260
7260
  return false;
7261
7261
  }
7262
7262
  }
7263
- function isObject3(obj) {
7263
+ function isObject4(obj) {
7264
7264
  if (obj !== null) {
7265
7265
  return Object.prototype.toString.call(obj) === "[object Object]";
7266
7266
  } else {
@@ -7286,7 +7286,7 @@ var require_jmespath = __commonJS({
7286
7286
  }
7287
7287
  return true;
7288
7288
  }
7289
- if (isObject3(first) === true) {
7289
+ if (isObject4(first) === true) {
7290
7290
  var keysSeen = {};
7291
7291
  for (var key in first) {
7292
7292
  if (hasOwnProperty.call(first, key)) {
@@ -7312,7 +7312,7 @@ var require_jmespath = __commonJS({
7312
7312
  return true;
7313
7313
  } else if (isArray(obj) && obj.length === 0) {
7314
7314
  return true;
7315
- } else if (isObject3(obj)) {
7315
+ } else if (isObject4(obj)) {
7316
7316
  for (var key in obj) {
7317
7317
  if (obj.hasOwnProperty(key)) {
7318
7318
  return false;
@@ -8029,7 +8029,7 @@ var require_jmespath = __commonJS({
8029
8029
  var matched, current, result, first, second, field, left, right, collected, i;
8030
8030
  switch (node.type) {
8031
8031
  case "Field":
8032
- if (value !== null && isObject3(value)) {
8032
+ if (value !== null && isObject4(value)) {
8033
8033
  field = value[node.name];
8034
8034
  if (field === void 0) {
8035
8035
  return null;
@@ -8099,7 +8099,7 @@ var require_jmespath = __commonJS({
8099
8099
  return collected;
8100
8100
  case "ValueProjection":
8101
8101
  base = this.visit(node.children[0], value);
8102
- if (!isObject3(base)) {
8102
+ if (!isObject4(base)) {
8103
8103
  return null;
8104
8104
  }
8105
8105
  collected = [];
@@ -8496,7 +8496,7 @@ var require_jmespath = __commonJS({
8496
8496
  return Math.floor(resolvedArgs[0]);
8497
8497
  },
8498
8498
  _functionLength: function(resolvedArgs) {
8499
- if (!isObject3(resolvedArgs[0])) {
8499
+ if (!isObject4(resolvedArgs[0])) {
8500
8500
  return resolvedArgs[0].length;
8501
8501
  } else {
8502
8502
  return Object.keys(resolvedArgs[0]).length;
@@ -12052,7 +12052,7 @@ var require_merge = __commonJS({
12052
12052
  for (let i = 0, j = two.length; i < j; i++) {
12053
12053
  result.push(takeValue(two[i]));
12054
12054
  }
12055
- } else if (isObject3(two)) {
12055
+ } else if (isObject4(two)) {
12056
12056
  const keys = Object.keys(two);
12057
12057
  for (let i = 0, j = keys.length; i < j; i++) {
12058
12058
  const key = keys[i];
@@ -12062,8 +12062,8 @@ var require_merge = __commonJS({
12062
12062
  result[key] = takeValue(two[key]);
12063
12063
  }
12064
12064
  }
12065
- } else if (isObject3(one)) {
12066
- if (isObject3(two)) {
12065
+ } else if (isObject4(one)) {
12066
+ if (isObject4(two)) {
12067
12067
  if (!shouldMerge(one, two)) {
12068
12068
  return two;
12069
12069
  }
@@ -12087,7 +12087,7 @@ var require_merge = __commonJS({
12087
12087
  if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) {
12088
12088
  delete result[key];
12089
12089
  } else {
12090
- if (isObject3(obj1) && isObject3(obj2)) {
12090
+ if (isObject4(obj1) && isObject4(obj2)) {
12091
12091
  const arr1 = objects.get(obj1) || [];
12092
12092
  const arr2 = objects.get(obj2) || [];
12093
12093
  arr1.push({ obj: one, key });
@@ -12121,7 +12121,7 @@ var require_merge = __commonJS({
12121
12121
  function isFunction(value) {
12122
12122
  return typeof value === "function";
12123
12123
  }
12124
- function isObject3(value) {
12124
+ function isObject4(value) {
12125
12125
  return !isPrimitive2(value) && !isArray(value) && !isFunction(value) && typeof value === "object";
12126
12126
  }
12127
12127
  function isPrimitive2(value) {
@@ -22684,6 +22684,7 @@ var EHookExecutorName;
22684
22684
  EHookExecutorName2["SecurityAnswerHookExecutor"] = "SecurityAnswerHookExecutor";
22685
22685
  EHookExecutorName2["ImageUnderstandingHookExecutor"] = "ImageUnderstandingHookExecutor";
22686
22686
  EHookExecutorName2["McpDiscoveryHookExecutor"] = "McpDiscoveryHookExecutor";
22687
+ EHookExecutorName2["CurrentTimeHookExecutor"] = "CurrentTimeHookExecutor";
22687
22688
  })(EHookExecutorName || (EHookExecutorName = {}));
22688
22689
 
22689
22690
  // ../linkque-agent-runtime/dist/esm/core/followUpQuestions.js
@@ -22819,6 +22820,288 @@ function truncateToEstimatedTokens(text, budget) {
22819
22820
  return text.slice(0, low).trim();
22820
22821
  }
22821
22822
 
22823
+ // ../linkque-agent-runtime/dist/esm/core/dataTransformExecutor.js
22824
+ import { createHash } from "node:crypto";
22825
+ import { dirname, join } from "node:path";
22826
+ import { createRequire } from "node:module";
22827
+ import { pathToFileURL } from "node:url";
22828
+ import { Worker } from "node:worker_threads";
22829
+ var DATA_TRANSFORM_LIMITS = Object.freeze({
22830
+ sourceBytes: 32 * 1024,
22831
+ inputBytes: 2 * 1024 * 1024,
22832
+ outputBytes: 1024 * 1024,
22833
+ maxDepth: 64,
22834
+ memoryBytes: 32 * 1024 * 1024,
22835
+ stackBytes: 512 * 1024,
22836
+ executionMs: 100,
22837
+ watchdogMs: 500,
22838
+ initializationMs: 5e3,
22839
+ maxConcurrent: 4,
22840
+ maxQueued: 32
22841
+ });
22842
+ var DataTransformError = class extends Error {
22843
+ code;
22844
+ sourceHash;
22845
+ constructor(code, message, sourceHash) {
22846
+ super(message);
22847
+ this.code = code;
22848
+ this.sourceHash = sourceHash;
22849
+ this.name = "DataTransformError";
22850
+ }
22851
+ };
22852
+ var DataTransformExecutor = class {
22853
+ workerUrl;
22854
+ queue = [];
22855
+ slots = [];
22856
+ nextRequestId = 1;
22857
+ disposed = false;
22858
+ constructor(workerUrl = defaultWorkerUrl()) {
22859
+ this.workerUrl = workerUrl;
22860
+ }
22861
+ execute(source, input, signal) {
22862
+ const sourceBytes = Buffer.byteLength(source, "utf8");
22863
+ const sourceHash = createHash("sha256").update(source).digest("hex");
22864
+ if (!source.trim() || sourceBytes > DATA_TRANSFORM_LIMITS.sourceBytes) {
22865
+ return Promise.reject(new DataTransformError("CARD_TRANSFORM_SOURCE_INVALID", `\u6570\u636E\u8F6C\u6362\u6E90\u7801\u4E3A\u7A7A\u6216\u8D85\u8FC7 ${DATA_TRANSFORM_LIMITS.sourceBytes} \u5B57\u8282`, sourceHash));
22866
+ }
22867
+ if (signal?.aborted) {
22868
+ return Promise.reject(signal.reason ?? new Error("\u64CD\u4F5C\u5DF2\u53D6\u6D88"));
22869
+ }
22870
+ let inputJson;
22871
+ try {
22872
+ inputJson = JSON.stringify(input);
22873
+ } catch {
22874
+ return Promise.reject(new DataTransformError("CARD_TRANSFORM_INPUT_TOO_LARGE", "\u6570\u636E\u8F6C\u6362\u8F93\u5165\u65E0\u6CD5\u5E8F\u5217\u5316", sourceHash));
22875
+ }
22876
+ const inputBytes = Buffer.byteLength(inputJson, "utf8");
22877
+ if (inputBytes > DATA_TRANSFORM_LIMITS.inputBytes || jsonDepth(input) > DATA_TRANSFORM_LIMITS.maxDepth) {
22878
+ return Promise.reject(new DataTransformError("CARD_TRANSFORM_INPUT_TOO_LARGE", "\u6570\u636E\u8F6C\u6362\u8F93\u5165\u8D85\u8FC7\u5927\u5C0F\u6216\u6DF1\u5EA6\u9650\u5236", sourceHash));
22879
+ }
22880
+ const active = this.slots.filter((slot) => slot.busy).length;
22881
+ if (active >= DATA_TRANSFORM_LIMITS.maxConcurrent && this.queue.length >= DATA_TRANSFORM_LIMITS.maxQueued) {
22882
+ return Promise.reject(new DataTransformError("CARD_TRANSFORM_BUSY", "\u6570\u636E\u8F6C\u6362\u6267\u884C\u961F\u5217\u5DF2\u6EE1", sourceHash));
22883
+ }
22884
+ if (this.disposed) {
22885
+ return Promise.reject(new DataTransformError("CARD_TRANSFORM_FAILED", "\u6570\u636E\u8F6C\u6362\u6267\u884C\u5668\u5DF2\u5173\u95ED", sourceHash));
22886
+ }
22887
+ return new Promise((resolve, reject) => {
22888
+ this.queue.push({
22889
+ mode: "execute",
22890
+ source,
22891
+ sourceHash,
22892
+ inputJson,
22893
+ inputBytes,
22894
+ signal,
22895
+ resolve,
22896
+ reject
22897
+ });
22898
+ this.drain();
22899
+ });
22900
+ }
22901
+ validateSource(source) {
22902
+ const sourceBytes = Buffer.byteLength(source, "utf8");
22903
+ const sourceHash = createHash("sha256").update(source).digest("hex");
22904
+ if (!source.trim() || sourceBytes > DATA_TRANSFORM_LIMITS.sourceBytes) {
22905
+ return Promise.reject(new DataTransformError("CARD_TRANSFORM_SOURCE_INVALID", `\u6570\u636E\u8F6C\u6362\u6E90\u7801\u4E3A\u7A7A\u6216\u8D85\u8FC7 ${DATA_TRANSFORM_LIMITS.sourceBytes} \u5B57\u8282`, sourceHash));
22906
+ }
22907
+ if (this.disposed) {
22908
+ return Promise.reject(new DataTransformError("CARD_TRANSFORM_FAILED", "\u6570\u636E\u8F6C\u6362\u6267\u884C\u5668\u5DF2\u5173\u95ED", sourceHash));
22909
+ }
22910
+ const active = this.slots.filter((slot) => slot.busy).length;
22911
+ if (active >= DATA_TRANSFORM_LIMITS.maxConcurrent && this.queue.length >= DATA_TRANSFORM_LIMITS.maxQueued) {
22912
+ return Promise.reject(new DataTransformError("CARD_TRANSFORM_BUSY", "\u6570\u636E\u8F6C\u6362\u6267\u884C\u961F\u5217\u5DF2\u6EE1", sourceHash));
22913
+ }
22914
+ return new Promise((resolve, reject) => {
22915
+ this.queue.push({
22916
+ mode: "validate",
22917
+ source,
22918
+ sourceHash,
22919
+ inputJson: "[]",
22920
+ inputBytes: 2,
22921
+ resolve: () => resolve(),
22922
+ reject
22923
+ });
22924
+ this.drain();
22925
+ });
22926
+ }
22927
+ async close() {
22928
+ this.disposed = true;
22929
+ for (const queued of this.queue.splice(0)) {
22930
+ queued.reject(new DataTransformError("CARD_TRANSFORM_FAILED", "\u6570\u636E\u8F6C\u6362\u6267\u884C\u5668\u5DF2\u5173\u95ED", queued.sourceHash));
22931
+ }
22932
+ await Promise.all(this.slots.splice(0).map(async (slot) => {
22933
+ slot.disposed = true;
22934
+ await slot.worker.terminate();
22935
+ }));
22936
+ }
22937
+ drain() {
22938
+ if (this.disposed)
22939
+ return;
22940
+ while (this.queue.length > 0) {
22941
+ let slot = this.slots.find((candidate) => !candidate.busy);
22942
+ if (!slot && this.slots.length < DATA_TRANSFORM_LIMITS.maxConcurrent) {
22943
+ slot = this.createSlot();
22944
+ this.slots.push(slot);
22945
+ }
22946
+ if (!slot)
22947
+ return;
22948
+ const queued = this.queue.shift();
22949
+ if (!queued)
22950
+ return;
22951
+ if (queued.signal?.aborted) {
22952
+ queued.reject(queued.signal.reason ?? new Error("\u64CD\u4F5C\u5DF2\u53D6\u6D88"));
22953
+ continue;
22954
+ }
22955
+ slot.busy = true;
22956
+ void this.run(slot, queued).finally(() => {
22957
+ if (!slot.disposed)
22958
+ slot.busy = false;
22959
+ this.drain();
22960
+ });
22961
+ }
22962
+ }
22963
+ createSlot() {
22964
+ const worker = new Worker(this.workerUrl);
22965
+ const slot = {
22966
+ worker,
22967
+ busy: false,
22968
+ disposed: false,
22969
+ ready: Promise.resolve()
22970
+ };
22971
+ slot.ready = new Promise((resolve, reject) => {
22972
+ const timeout = setTimeout(() => {
22973
+ reject(new DataTransformError("CARD_TRANSFORM_TIMEOUT", "\u6570\u636E\u8F6C\u6362\u5F15\u64CE\u521D\u59CB\u5316\u8D85\u65F6"));
22974
+ this.discardSlot(slot);
22975
+ }, DATA_TRANSFORM_LIMITS.initializationMs);
22976
+ worker.once("message", (message) => {
22977
+ if (message?.type !== "ready")
22978
+ return;
22979
+ clearTimeout(timeout);
22980
+ resolve();
22981
+ });
22982
+ worker.once("error", (error) => {
22983
+ clearTimeout(timeout);
22984
+ reject(error);
22985
+ });
22986
+ });
22987
+ return slot;
22988
+ }
22989
+ async run(slot, queued) {
22990
+ try {
22991
+ await slot.ready;
22992
+ } catch (error) {
22993
+ queued.reject(error instanceof DataTransformError ? error : new DataTransformError("CARD_TRANSFORM_FAILED", error instanceof Error ? error.message : "\u6570\u636E\u8F6C\u6362\u5F15\u64CE\u521D\u59CB\u5316\u5931\u8D25", queued.sourceHash));
22994
+ this.discardSlot(slot);
22995
+ return;
22996
+ }
22997
+ if (queued.signal?.aborted) {
22998
+ queued.reject(queued.signal.reason ?? new Error("\u64CD\u4F5C\u5DF2\u53D6\u6D88"));
22999
+ return;
23000
+ }
23001
+ const requestId = this.nextRequestId++;
23002
+ await new Promise((resolve) => {
23003
+ let settled = false;
23004
+ let watchdog;
23005
+ const finish = (callback) => {
23006
+ if (settled)
23007
+ return;
23008
+ settled = true;
23009
+ clearTimeout(watchdog);
23010
+ queued.signal?.removeEventListener("abort", abort);
23011
+ slot.worker.off("message", onMessage);
23012
+ slot.worker.off("error", onError);
23013
+ callback();
23014
+ resolve();
23015
+ };
23016
+ const abort = () => {
23017
+ finish(() => {
23018
+ queued.reject(queued.signal?.reason ?? new Error("\u64CD\u4F5C\u5DF2\u53D6\u6D88"));
23019
+ this.discardSlot(slot);
23020
+ });
23021
+ };
23022
+ const onError = (error) => {
23023
+ finish(() => {
23024
+ queued.reject(new DataTransformError("CARD_TRANSFORM_FAILED", error.message, queued.sourceHash));
23025
+ this.discardSlot(slot);
23026
+ });
23027
+ };
23028
+ const onMessage = (message) => {
23029
+ if (message?.type !== "result" || message.requestId !== requestId)
23030
+ return;
23031
+ finish(() => this.acceptWorkerResult(queued, message));
23032
+ };
23033
+ watchdog = setTimeout(() => {
23034
+ finish(() => {
23035
+ queued.reject(new DataTransformError("CARD_TRANSFORM_TIMEOUT", "\u6570\u636E\u8F6C\u6362\u8D85\u8FC7\u5BBF\u4E3B\u6267\u884C\u671F\u9650", queued.sourceHash));
23036
+ this.discardSlot(slot);
23037
+ });
23038
+ }, DATA_TRANSFORM_LIMITS.watchdogMs);
23039
+ queued.signal?.addEventListener("abort", abort, { once: true });
23040
+ slot.worker.on("message", onMessage);
23041
+ slot.worker.once("error", onError);
23042
+ slot.worker.postMessage({
23043
+ type: "execute",
23044
+ mode: queued.mode,
23045
+ requestId,
23046
+ source: queued.source,
23047
+ inputJson: queued.inputJson,
23048
+ limits: DATA_TRANSFORM_LIMITS
23049
+ });
23050
+ });
23051
+ }
23052
+ acceptWorkerResult(queued, message) {
23053
+ if (!message.ok || typeof message.resultJson !== "string") {
23054
+ queued.reject(new DataTransformError(message.code ?? "CARD_TRANSFORM_FAILED", message.message ?? "\u6570\u636E\u8F6C\u6362\u6267\u884C\u5931\u8D25", queued.sourceHash));
23055
+ return;
23056
+ }
23057
+ const outputBytes = Buffer.byteLength(message.resultJson, "utf8");
23058
+ if (outputBytes > DATA_TRANSFORM_LIMITS.outputBytes) {
23059
+ queued.reject(new DataTransformError("CARD_TRANSFORM_OUTPUT_TOO_LARGE", "\u6570\u636E\u8F6C\u6362\u7ED3\u679C\u8D85\u8FC7\u5927\u5C0F\u9650\u5236", queued.sourceHash));
23060
+ return;
23061
+ }
23062
+ try {
23063
+ const data = JSON.parse(message.resultJson);
23064
+ if (data !== null && (typeof data !== "object" || Array.isArray(data) || jsonDepth(data) > DATA_TRANSFORM_LIMITS.maxDepth)) {
23065
+ throw new DataTransformError("CARD_TRANSFORM_OUTPUT_INVALID", "\u6570\u636E\u8F6C\u6362\u7ED3\u679C\u5FC5\u987B\u662F JSON \u5BF9\u8C61\u6216 null", queued.sourceHash);
23066
+ }
23067
+ queued.resolve({
23068
+ data,
23069
+ durationMs: message.durationMs ?? 0,
23070
+ inputBytes: queued.inputBytes,
23071
+ outputBytes,
23072
+ sourceHash: queued.sourceHash
23073
+ });
23074
+ } catch (error) {
23075
+ queued.reject(error instanceof DataTransformError ? error : new DataTransformError("CARD_TRANSFORM_OUTPUT_INVALID", "\u6570\u636E\u8F6C\u6362\u7ED3\u679C\u4E0D\u662F\u6709\u6548 JSON", queued.sourceHash));
23076
+ }
23077
+ }
23078
+ discardSlot(slot) {
23079
+ if (slot.disposed)
23080
+ return;
23081
+ slot.disposed = true;
23082
+ const index = this.slots.indexOf(slot);
23083
+ if (index >= 0)
23084
+ this.slots.splice(index, 1);
23085
+ void slot.worker.terminate();
23086
+ }
23087
+ };
23088
+ function defaultWorkerUrl() {
23089
+ if (typeof __dirname === "string") {
23090
+ return pathToFileURL(join(__dirname, "dataTransformWorker.js"));
23091
+ }
23092
+ const resolver = createRequire(pathToFileURL(join(process.cwd(), "__linkque_worker_resolver__.js")).href);
23093
+ const packageJson = resolver.resolve("@alipay/linkque-agent-runtime/package.json");
23094
+ return pathToFileURL(join(dirname(packageJson), "dist/esm/core/dataTransformWorker.js"));
23095
+ }
23096
+ function jsonDepth(value, depth = 0) {
23097
+ if (value === null || typeof value !== "object")
23098
+ return depth;
23099
+ if (depth > DATA_TRANSFORM_LIMITS.maxDepth)
23100
+ return depth;
23101
+ const children = Array.isArray(value) ? value : Object.values(value);
23102
+ return children.reduce((maximum, child) => Math.max(maximum, jsonDepth(child, depth + 1)), depth);
23103
+ }
23104
+
22822
23105
  // ../linkque-agent-runtime/dist/esm/core/types.js
22823
23106
  var EDebugLogScope;
22824
23107
  (function(EDebugLogScope2) {
@@ -22857,6 +23140,9 @@ var A2UI_CARD_TRANSFORM_PROFILE = "linkque-structural-v1";
22857
23140
  var A2UI_CARD_EXPRESSION_MAX_LENGTH = 4096;
22858
23141
  var A2UI_CARD_EXPRESSION_MAX_AST_NODES = 512;
22859
23142
  var A2UI_CARD_EXPRESSION_MAX_AST_DEPTH = 32;
23143
+ var A2UI_CARD_DATA_TRANSFORM_LANGUAGE = "javascript";
23144
+ var A2UI_CARD_DATA_TRANSFORM_PROFILE = "linkque-card-data-transform-v1";
23145
+ var A2UI_CARD_DATA_TRANSFORM_MAX_SOURCE_BYTES = 32 * 1024;
22860
23146
 
22861
23147
  // ../linkque-agent-data-binding-contract/dist/esm/json.js
22862
23148
  var BLOCKED_PATH_SEGMENTS = /* @__PURE__ */ new Set([
@@ -23248,8 +23534,8 @@ function analyzeA2UIBindings(protocol) {
23248
23534
  visitValue(component, "", context2);
23249
23535
  const children = component.children;
23250
23536
  if (isPlainRecord(children) && typeof children.path === "string") {
23251
- const canonicalPath = canonicalizeBindingPath(children.path);
23252
- if (!canonicalPath || !isSafeJsonPointer(canonicalPath)) {
23537
+ const canonicalPath = canonicalizeBindingPath(children.path, context2.listRoot);
23538
+ if (!canonicalPath || !isSafeJsonPointer(canonicalPath, true)) {
23253
23539
  issues.push(issue2(`card.surfaces.${surfaceId}.components.${component.id}.children.path`, "INVALID_BINDING_PATH", `Invalid list path ${children.path}`));
23254
23540
  } else {
23255
23541
  occurrences.push({
@@ -23259,6 +23545,7 @@ function analyzeA2UIBindings(protocol) {
23259
23545
  propertyPath: "children.path",
23260
23546
  rawPath: children.path,
23261
23547
  canonicalPath,
23548
+ ...context2.listRoot ? { listRoot: context2.listRoot } : {},
23262
23549
  usage: "list"
23263
23550
  });
23264
23551
  }
@@ -23323,6 +23610,7 @@ function addOccurrence(rawPath, propertyPath, usage, context2) {
23323
23610
  propertyPath,
23324
23611
  rawPath,
23325
23612
  canonicalPath,
23613
+ ...context2.listRoot ? { listRoot: context2.listRoot } : {},
23326
23614
  usage
23327
23615
  });
23328
23616
  }
@@ -23419,6 +23707,60 @@ function validateJsonSchemaValue2(schema, value, path2 = "$") {
23419
23707
  validateValue(schema, value, path2, issues);
23420
23708
  return issues;
23421
23709
  }
23710
+ function normalizeCardDataValue(schema, value, required = true) {
23711
+ if (value === void 0 || value === null)
23712
+ return required ? value : void 0;
23713
+ let normalized = value;
23714
+ if (schema.type === "string" && (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value))) {
23715
+ normalized = String(value);
23716
+ } else if ((schema.type === "number" || schema.type === "integer") && typeof value === "string") {
23717
+ const text = value.trim();
23718
+ if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/u.test(text)) {
23719
+ const number2 = Number(text);
23720
+ if (Number.isFinite(number2) && (schema.type !== "integer" || Number.isSafeInteger(number2))) {
23721
+ normalized = number2;
23722
+ }
23723
+ }
23724
+ } else if (schema.type === "object" && isPlainRecord(value)) {
23725
+ const properties = isPlainRecord(schema.properties) ? schema.properties : {};
23726
+ const requiredKeys = new Set(Array.isArray(schema.required) ? schema.required : []);
23727
+ normalized = Object.fromEntries(Object.entries(value).flatMap(([key, child]) => {
23728
+ const childSchema = properties[key];
23729
+ const next = isPlainRecord(childSchema) ? normalizeCardDataValue(childSchema, child, requiredKeys.has(key)) : child;
23730
+ return next === void 0 ? [] : [[key, next]];
23731
+ }));
23732
+ } else if (schema.type === "array" && Array.isArray(value) && isPlainRecord(schema.items)) {
23733
+ normalized = value.map((child) => normalizeCardDataValue(schema.items, child));
23734
+ }
23735
+ return !required && validateJsonSchemaValue2(schema, normalized).length > 0 ? void 0 : normalized;
23736
+ }
23737
+ function getJsonSchemaAtDataPointer(schema, pointer) {
23738
+ if (!isSafeJsonPointer(pointer, true))
23739
+ return void 0;
23740
+ if (pointer === "/")
23741
+ return schema;
23742
+ return getJsonSchemaAtPath(schema, pointer.slice(1).split("/").map(decodePointerSegment));
23743
+ }
23744
+ function getJsonSchemaAtPath(schema, path2) {
23745
+ let current = schema;
23746
+ for (const segment of path2) {
23747
+ if (!current)
23748
+ return void 0;
23749
+ if (segment === "*" || current.type === "array") {
23750
+ if (!isPlainRecord(current.items))
23751
+ return void 0;
23752
+ current = current.items;
23753
+ if (segment === "*")
23754
+ continue;
23755
+ }
23756
+ if (current.type !== "object" || !isPlainRecord(current.properties)) {
23757
+ return void 0;
23758
+ }
23759
+ const child = current.properties[segment];
23760
+ current = isPlainRecord(child) ? child : void 0;
23761
+ }
23762
+ return current;
23763
+ }
23422
23764
  function validateSchemaNode(value, path2, issues, options) {
23423
23765
  if (!isPlainRecord(value) || !isJsonValue(value)) {
23424
23766
  issues.push(issue2(path2, "INVALID_JSON_SCHEMA", `${path2} must be a JSON object`));
@@ -23749,7 +24091,8 @@ var decoration = {
23749
24091
  "primary",
23750
24092
  "primary-muted",
23751
24093
  "accent",
23752
- "warning"
24094
+ "warning",
24095
+ "transparent"
23753
24096
  ]
23754
24097
  },
23755
24098
  border: {
@@ -23761,6 +24104,7 @@ var decoration = {
23761
24104
  var typography = {
23762
24105
  color: { kind: "string", values: colors },
23763
24106
  fontSize: { kind: "string", values: ["xs", "sm", "md", "lg", "xl", "xxl"] },
24107
+ fontFamily: { kind: "string", values: ["digit", "digit-bold"] },
23764
24108
  fontWeight: { kind: "string", values: ["normal", "semibold", "bold"] }
23765
24109
  };
23766
24110
  var container = {
@@ -23797,6 +24141,7 @@ var A2UI_V4_COMPONENT_CATALOG = Object.freeze({
23797
24141
  ...layoutItem,
23798
24142
  ...containerSize,
23799
24143
  ...decoration,
24144
+ verticalAlign: { kind: "string", values: ["top", "center", "bottom"] },
23800
24145
  child: { kind: "child", required: true },
23801
24146
  action: { kind: "action" },
23802
24147
  disabled: { kind: "boolean" }
@@ -23831,8 +24176,8 @@ var A2UI_V4_COMPONENT_CATALOG = Object.freeze({
23831
24176
  shrink: { kind: "boolean" },
23832
24177
  text: { kind: "binding", required: true },
23833
24178
  maxLines: { kind: "number", values: [0, 1, 2, 3, 4, 5, 6] },
23834
- decoration: { kind: "string", values: ["line-through"] },
23835
- format: { kind: "format" }
24179
+ textAlign: { kind: "string", values: ["left", "center", "right"] },
24180
+ decoration: { kind: "string", values: ["line-through"] }
23836
24181
  }
23837
24182
  },
23838
24183
  Tag: {
@@ -23841,6 +24186,7 @@ var A2UI_V4_COMPONENT_CATALOG = Object.freeze({
23841
24186
  ...layoutItem,
23842
24187
  text: { kind: "binding", required: true },
23843
24188
  icon: { kind: "string", values: iconNames },
24189
+ image: { kind: "binding" },
23844
24190
  tone: {
23845
24191
  kind: "string",
23846
24192
  values: [
@@ -23896,7 +24242,20 @@ var A2UI_V4_COMPONENT_CATALOG = Object.freeze({
23896
24242
  height: { kind: "string", values: ["auto", "fill"] },
23897
24243
  size: {
23898
24244
  kind: "string",
23899
- values: ["xs", "sm", "md", "lg", "xl", "full"]
24245
+ values: [
24246
+ "xs",
24247
+ "sm",
24248
+ "md",
24249
+ "lg",
24250
+ "xl",
24251
+ "full",
24252
+ "text-xs",
24253
+ "text-sm",
24254
+ "text-md",
24255
+ "text-lg",
24256
+ "text-xl",
24257
+ "text-xxl"
24258
+ ]
23900
24259
  }
23901
24260
  }
23902
24261
  },
@@ -23940,7 +24299,6 @@ var A2UI_V4_COMPONENT_CATALOG = Object.freeze({
23940
24299
  "x2-funds"
23941
24300
  ]
23942
24301
  },
23943
- format: { kind: "string", values: ["date"] },
23944
24302
  validationRegexp: { kind: "string" },
23945
24303
  "x2-limit": { kind: "number" }
23946
24304
  }
@@ -24051,14 +24409,6 @@ function validateV4Component(component, componentPath, issues) {
24051
24409
  issues.push(issue2(`${componentPath}.component`, "UNSUPPORTED_COMPONENT", `V4 does not support component ${component.component}`));
24052
24410
  return;
24053
24411
  }
24054
- const allowed = /* @__PURE__ */ new Set([
24055
- "id",
24056
- "component",
24057
- ...Object.keys(schema.properties)
24058
- ]);
24059
- for (const key of Object.keys(component))
24060
- if (!allowed.has(key))
24061
- issues.push(issue2(`${componentPath}.${key}`, "UNSUPPORTED_COMPONENT_PROP", `${component.component} does not support property ${key}`));
24062
24412
  for (const [name, property] of Object.entries(schema.properties)) {
24063
24413
  const value = component[name];
24064
24414
  if (property.required && value === void 0)
@@ -24088,8 +24438,8 @@ function validateV4Component(component, componentPath, issues) {
24088
24438
  }
24089
24439
  if (component.checks !== void 0)
24090
24440
  validateChecks(component.checks, `${componentPath}.checks`, issues);
24091
- if (component.format !== void 0 && component.component === "Text")
24092
- validateNumberFormat(component.format, `${componentPath}.format`, issues);
24441
+ if (component.component === "Tag" && component.icon !== void 0 && component.image !== void 0)
24442
+ issues.push(issue2(componentPath, "INVALID_COMPONENT_PROP_VALUE", "Tag icon and image cannot be used together"));
24093
24443
  if (component.action !== void 0)
24094
24444
  validateAction(component.action, `${componentPath}.action`, issues, 0);
24095
24445
  }
@@ -24114,7 +24464,7 @@ function validateComponents(payload, path2, surfaces, issues) {
24114
24464
  }
24115
24465
  function validateProperty(value, schema, path2, issues, propertyName) {
24116
24466
  if (schema.kind === "binding") {
24117
- const stringOnly = propertyName === "label" || propertyName === "src" || propertyName === "alt";
24467
+ const stringOnly = propertyName === "label" || propertyName === "src" || propertyName === "alt" || propertyName === "image";
24118
24468
  const literalValid = typeof value === "string" || !stringOnly && typeof value === "number" && Number.isFinite(value);
24119
24469
  if (!literalValid && !isDisplayBinding(value, stringOnly))
24120
24470
  issues.push(issue2(path2, "INVALID_DISPLAY_VALUE", `display value must be ${stringOnly ? "a string" : "a string or finite number"}, or a compatible display binding`));
@@ -24137,10 +24487,10 @@ function validateProperty(value, schema, path2, issues, propertyName) {
24137
24487
  return;
24138
24488
  if (schema.kind === "boolean" && typeof value !== "boolean")
24139
24489
  issues.push(issue2(path2, "INVALID_COMPONENT_PROP_TYPE", "value must be boolean"));
24140
- if (schema.kind === "number" && (!Number.isFinite(value) || schema.values && !schema.values.includes(value)))
24141
- issues.push(issue2(path2, "INVALID_COMPONENT_PROP_VALUE", "value is not an allowed finite number"));
24142
- if (schema.kind === "string" && (typeof value !== "string" || schema.values && !schema.values.includes(value)))
24143
- issues.push(issue2(path2, "INVALID_COMPONENT_PROP_VALUE", "value is not an allowed string"));
24490
+ if (schema.kind === "number" && !Number.isFinite(value))
24491
+ issues.push(issue2(path2, "INVALID_COMPONENT_PROP_VALUE", "value must be a finite number"));
24492
+ if (schema.kind === "string" && typeof value !== "string")
24493
+ issues.push(issue2(path2, "INVALID_COMPONENT_PROP_VALUE", "value must be a string"));
24144
24494
  }
24145
24495
  function isDisplayBinding(value, stringOnly = false) {
24146
24496
  if (!isPlainRecord(value) || typeof value.path !== "string" || !isSafePath(value.path))
@@ -24232,51 +24582,8 @@ function validateClientAction(body, path2, issues) {
24232
24582
  issues.push(issue2(`${path2}.context.url`, "INVALID_PAGE_URL", "ui.page.open URL must use https or the approved Alipay scheme"));
24233
24583
  return;
24234
24584
  }
24235
- if (body.name === "payment.trade-pay") {
24236
- validatePaymentActionContext(body.context, `${path2}.context`, issues);
24237
- return;
24238
- }
24239
24585
  issues.push(issue2(`${path2}.name`, "UNSUPPORTED_CLIENT_ACTION", `unsupported client action ${String(body.name)}`));
24240
24586
  }
24241
- function validatePaymentActionContext(value, path2, issues) {
24242
- if (!isPlainRecord(value)) {
24243
- issues.push(issue2(path2, "INVALID_CLIENT_ACTION_CONTEXT", "payment.trade-pay requires createTrade and onSuccess"));
24244
- return;
24245
- }
24246
- rejectUnknownKeys(value, ["createTrade", "onSuccess"], path2, issues);
24247
- const createTrade = isPlainRecord(value.createTrade) ? value.createTrade : void 0;
24248
- if (!createTrade) {
24249
- issues.push(issue2(`${path2}.createTrade`, "INVALID_PAYMENT_CREATE_TRADE", "createTrade must be an object"));
24250
- } else {
24251
- rejectUnknownKeys(createTrade, ["mcpResourceId", "toolName", "input", "tradeNoPath"], `${path2}.createTrade`, issues);
24252
- if (!isSafeIdentifier(createTrade.mcpResourceId))
24253
- issues.push(issue2(`${path2}.createTrade.mcpResourceId`, "INVALID_MCP_RESOURCE_ID", "mcpResourceId is invalid"));
24254
- if (typeof createTrade.toolName !== "string" || !createTrade.toolName.trim())
24255
- issues.push(issue2(`${path2}.createTrade.toolName`, "INVALID_TOOL_NAME", "toolName is required"));
24256
- if (!isPlainRecord(createTrade.input))
24257
- issues.push(issue2(`${path2}.createTrade.input`, "INVALID_PAYMENT_INPUT", "input must be an object"));
24258
- else
24259
- validateActionDynamicValue(createTrade.input, `${path2}.createTrade.input`, issues);
24260
- if (!isSafeJsonPointer(createTrade.tradeNoPath))
24261
- issues.push(issue2(`${path2}.createTrade.tradeNoPath`, "INVALID_TRADE_NO_PATH", "tradeNoPath must be an absolute JSON Pointer"));
24262
- }
24263
- const onSuccess = isPlainRecord(value.onSuccess) ? value.onSuccess : void 0;
24264
- const event = onSuccess && isPlainRecord(onSuccess.event) ? onSuccess.event : void 0;
24265
- if (!onSuccess || !event) {
24266
- issues.push(issue2(`${path2}.onSuccess`, "INVALID_PAYMENT_SUCCESS_EVENT", "onSuccess.event is required"));
24267
- return;
24268
- }
24269
- rejectUnknownKeys(onSuccess, ["event"], `${path2}.onSuccess`, issues);
24270
- rejectUnknownKeys(event, ["name", "context", "x2-user-message"], `${path2}.onSuccess.event`, issues);
24271
- if (typeof event.name !== "string" || !/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(event.name) || event.name.length > 96)
24272
- issues.push(issue2(`${path2}.onSuccess.event.name`, "INVALID_ACTION_NAME", "event name is invalid"));
24273
- if (event.context !== void 0 && !isPlainRecord(event.context))
24274
- issues.push(issue2(`${path2}.onSuccess.event.context`, "INVALID_ACTION_CONTEXT", "event context must be an object"));
24275
- else if (event.context !== void 0)
24276
- validateActionDynamicValue(event.context, `${path2}.onSuccess.event.context`, issues);
24277
- if (typeof event["x2-user-message"] !== "string" || !event["x2-user-message"].trim())
24278
- issues.push(issue2(`${path2}.onSuccess.event.x2-user-message`, "INVALID_ACTION_CONTEXT", "x2-user-message must be a non-empty string"));
24279
- }
24280
24587
  function validateActionDynamicValue(value, path2, issues) {
24281
24588
  if (Array.isArray(value)) {
24282
24589
  value.forEach((entry, index) => validateActionDynamicValue(entry, `${path2}[${index}]`, issues));
@@ -24321,7 +24628,7 @@ function validateTextField(component, path2, issues) {
24321
24628
  issues.push(issue2(`${path2}.validationRegexp`, "INVALID_VALIDATION_REGEXP", "validationRegexp is too long"));
24322
24629
  else
24323
24630
  try {
24324
- new RegExp(component.validationRegexp);
24631
+ RegExp(component.validationRegexp);
24325
24632
  } catch {
24326
24633
  issues.push(issue2(`${path2}.validationRegexp`, "INVALID_VALIDATION_REGEXP", "validationRegexp is invalid"));
24327
24634
  }
@@ -24372,26 +24679,6 @@ function validateOverflow(component, path2, issues) {
24372
24679
  }
24373
24680
  }
24374
24681
  }
24375
- function validateNumberFormat(value, path2, issues) {
24376
- if (!isPlainRecord(value))
24377
- return void issues.push(issue2(path2, "INVALID_NUMBER_FORMAT", "format must be an object"));
24378
- rejectUnknownKeys(value, [
24379
- "type",
24380
- "style",
24381
- "currency",
24382
- "locale",
24383
- "minimumFractionDigits",
24384
- "maximumFractionDigits",
24385
- "useGrouping",
24386
- "prefix",
24387
- "suffix"
24388
- ], path2, issues);
24389
- const style = value.style ?? "decimal";
24390
- const digit = (entry) => entry === void 0 || Number.isInteger(entry) && Number(entry) >= 0 && Number(entry) <= 20;
24391
- if (value.type !== "number" || !["decimal", "currency", "percent"].includes(String(style)) || style === "currency" && (typeof value.currency !== "string" || !/^[A-Z]{3}$/u.test(value.currency)) || value.locale !== void 0 && typeof value.locale !== "string" || !digit(value.minimumFractionDigits) || !digit(value.maximumFractionDigits) || Number.isInteger(value.minimumFractionDigits) && Number.isInteger(value.maximumFractionDigits) && Number(value.minimumFractionDigits) > Number(value.maximumFractionDigits) || value.useGrouping !== void 0 && typeof value.useGrouping !== "boolean" || value.prefix !== void 0 && (typeof value.prefix !== "string" || value.prefix.length > 32) || value.suffix !== void 0 && (typeof value.suffix !== "string" || value.suffix.length > 32)) {
24392
- issues.push(issue2(path2, "INVALID_NUMBER_FORMAT", "number format options are invalid"));
24393
- }
24394
- }
24395
24682
  function rejectUnknownKeys(value, allowed, path2, issues) {
24396
24683
  const allowedKeys = new Set(allowed);
24397
24684
  Object.keys(value).forEach((key) => {
@@ -24480,21 +24767,49 @@ function hasInteractiveDescendant(id, components, visited) {
24480
24767
  return refs.some((ref) => typeof ref === "string" && hasInteractiveDescendant(ref, components, visited));
24481
24768
  }
24482
24769
 
24770
+ // ../agent-a2ui-card-contract/dist/esm/pipeline-input.js
24771
+ function createA2UICardPipelineModelInputSchema(sources) {
24772
+ const properties = {};
24773
+ const required = [];
24774
+ sources.forEach((source, index) => {
24775
+ const name = `input${index}`;
24776
+ properties[name] = {
24777
+ ...scopeLocalReferences(source.inputSchema, `#/properties/${name}`),
24778
+ description: `\u7B2C ${index} \u4E2A\u6570\u636E\u6E90 ${source.toolName} \u7684 MCP \u8C03\u7528\u53C2\u6570\u3002${source.purpose}`
24779
+ };
24780
+ required.push(name);
24781
+ });
24782
+ return { type: "object", properties, required, additionalProperties: false };
24783
+ }
24784
+ function scopeLocalReferences(schema, root) {
24785
+ const visit = (value) => {
24786
+ if (Array.isArray(value))
24787
+ return value.map(visit);
24788
+ if (value === null || typeof value !== "object")
24789
+ return value;
24790
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
24791
+ key,
24792
+ key === "$ref" && typeof entry === "string" && (entry === "#" || entry.startsWith("#/")) ? `${root}${entry.slice(1)}` : visit(entry)
24793
+ ]));
24794
+ };
24795
+ return visit(schema);
24796
+ }
24797
+
24483
24798
  // ../agent-a2ui-card-contract/dist/esm/validation.js
24484
- var FIELD_TYPES = [
24799
+ var FIELD_TYPES = /* @__PURE__ */ new Set([
24485
24800
  "array",
24486
24801
  "boolean",
24487
24802
  "integer",
24488
24803
  "number",
24489
24804
  "object",
24490
24805
  "string"
24491
- ];
24492
- var FIELD_SOURCES = [
24806
+ ]);
24807
+ var FIELD_SOURCES = /* @__PURE__ */ new Set([
24493
24808
  "business",
24494
24809
  "invocation",
24495
24810
  "runtime-context",
24496
24811
  "local"
24497
- ];
24812
+ ]);
24498
24813
  var RUNTIME_CONTEXT_KEYS = /* @__PURE__ */ new Set([
24499
24814
  "agentId",
24500
24815
  "tenantId",
@@ -24539,6 +24854,9 @@ function getA2UICardResourceConfigIssues(value) {
24539
24854
  ];
24540
24855
  }
24541
24856
  const issues = [];
24857
+ if (value.schemaVersion === "4" && value.dataMode === "pipeline") {
24858
+ return getA2UICardResourceConfigV4PipelineIssues(value);
24859
+ }
24542
24860
  if (value.schemaVersion === "3" || value.schemaVersion === "4") {
24543
24861
  return getA2UICardResourceConfigV3Issues(value);
24544
24862
  }
@@ -24573,6 +24891,57 @@ function getA2UICardResourceConfigIssues(value) {
24573
24891
  validateResolverCoverage(fields, resolver, issues, card);
24574
24892
  return issues;
24575
24893
  }
24894
+ function getA2UICardResourceConfigV4PipelineIssues(value) {
24895
+ const issues = [];
24896
+ exactKeys(value, [
24897
+ "schemaVersion",
24898
+ "dataMode",
24899
+ "argumentMode",
24900
+ "revision",
24901
+ "displayName",
24902
+ "description",
24903
+ "whenToUse",
24904
+ "whenNotToUse",
24905
+ "presentationInputSchema",
24906
+ "fields",
24907
+ "dataSources",
24908
+ "dataTransform",
24909
+ "dataModelSchema",
24910
+ "a2uiTemplate"
24911
+ ], "config", issues);
24912
+ if (value.schemaVersion !== "4" || value.dataMode !== "pipeline") {
24913
+ issues.push(issue2("config.dataMode", "INVALID_DATA_MODE", "pipeline cards require schemaVersion 4 and dataMode pipeline"));
24914
+ }
24915
+ if (value.argumentMode !== void 0 && value.argumentMode !== "model") {
24916
+ issues.push(issue2("config.argumentMode", "INVALID_ARGUMENT_MODE", "argumentMode must be model"));
24917
+ }
24918
+ if (!isSafeIdentifier(value.revision)) {
24919
+ issues.push(issue2("config.revision", "INVALID_CARD_REVISION", "revision must be a stable safe identifier"));
24920
+ }
24921
+ requiredString(value.displayName, "config.displayName", issues);
24922
+ requiredString(value.description, "config.description", issues);
24923
+ requiredString(value.whenToUse, "config.whenToUse", issues);
24924
+ optionalString(value.whenNotToUse, "config.whenNotToUse", issues);
24925
+ validateLooseJsonSchema(value.presentationInputSchema, "config.presentationInputSchema", issues);
24926
+ const fields = validateFields(value.fields, "config.fields", issues);
24927
+ const pipelineSources = validatePipelineDataSources(value.dataSources, "config.dataSources", issues);
24928
+ if (value.argumentMode === "model" && pipelineSources) {
24929
+ validateModelPipelineArguments(value, pipelineSources, "config", issues);
24930
+ }
24931
+ validateDataTransform(value.dataTransform, "config.dataTransform", issues);
24932
+ const dataModelSchema = validateLooseJsonSchema(value.dataModelSchema, "config.dataModelSchema", issues);
24933
+ const card = validateTemplate(value.a2uiTemplate, fields, issues);
24934
+ if (card) {
24935
+ issues.push(...getA2UIV4ProtocolIssues(card, "config.a2uiTemplate.content"), ...getPersistedV4ProtocolIssues(card, "config.a2uiTemplate.content"));
24936
+ }
24937
+ if (fields && dataModelSchema) {
24938
+ validatePipelineFieldSchemas(fields, value.dataModelSchema, issues);
24939
+ }
24940
+ if (dataModelSchema && isPlainRecord(value.a2uiTemplate) && stableJsonStringify(value.a2uiTemplate.argsSchema) !== stableJsonStringify(value.dataModelSchema)) {
24941
+ issues.push(issue2("config.a2uiTemplate.argsSchema", "DATA_MODEL_SCHEMA_MISMATCH", "a2uiTemplate.argsSchema must equal dataModelSchema"));
24942
+ }
24943
+ return issues;
24944
+ }
24576
24945
  function getA2UICardResourceConfigV3Issues(value) {
24577
24946
  const issues = [];
24578
24947
  if (value.actionBindings !== void 0) {
@@ -24684,6 +25053,98 @@ function validateDataSources(value, path2, issues, options = {}) {
24684
25053
  }
24685
25054
  return value;
24686
25055
  }
25056
+ function validateModelPipelineArguments(value, sources, path2, issues) {
25057
+ sources.forEach((source, index) => {
25058
+ if (isPlainRecord(source.fixedInput) && Object.keys(source.fixedInput).length || Array.isArray(source.inputBindings) && source.inputBindings.length) {
25059
+ issues.push(issue2(`${path2}.dataSources[${index}]`, "MODEL_ARGUMENTS_CONFLICT", "model arguments cannot be combined with fixedInput or inputBindings"));
25060
+ }
25061
+ });
25062
+ const expected = createA2UICardPipelineModelInputSchema(sources);
25063
+ if (isJsonValue(value.presentationInputSchema) && stableJsonStringify(value.presentationInputSchema) !== stableJsonStringify(expected)) {
25064
+ issues.push(issue2(`${path2}.presentationInputSchema`, "MODEL_ARGUMENT_SCHEMA_MISMATCH", "presentationInputSchema must match the configured MCP input schemas"));
25065
+ }
25066
+ }
25067
+ function validatePipelineDataSources(value, path2, issues) {
25068
+ if (!Array.isArray(value) || value.length === 0) {
25069
+ issues.push(issue2(path2, "INVALID_DATA_SOURCES", "pipeline dataSources must be a non-empty array"));
25070
+ return void 0;
25071
+ }
25072
+ const ids = /* @__PURE__ */ new Set();
25073
+ value.forEach((candidate, index) => {
25074
+ const itemPath = `${path2}[${index}]`;
25075
+ if (!isPlainRecord(candidate)) {
25076
+ issues.push(issue2(itemPath, "INVALID_DATA_SOURCE", "data source must be an object"));
25077
+ return;
25078
+ }
25079
+ exactKeys(candidate, [
25080
+ "sourceId",
25081
+ "mcpResourceId",
25082
+ "toolName",
25083
+ "purpose",
25084
+ "fixedInput",
25085
+ "inputBindings",
25086
+ "inputSchema",
25087
+ "outputSchema"
25088
+ ], itemPath, issues);
25089
+ if (!isSafeIdentifier(candidate.sourceId)) {
25090
+ issues.push(issue2(`${itemPath}.sourceId`, "INVALID_SOURCE_ID", "sourceId is invalid"));
25091
+ } else if (ids.has(candidate.sourceId)) {
25092
+ issues.push(issue2(`${itemPath}.sourceId`, "DUPLICATE_SOURCE_ID", `sourceId ${candidate.sourceId} is duplicated`));
25093
+ } else {
25094
+ ids.add(candidate.sourceId);
25095
+ }
25096
+ if (!isSafeIdentifier(candidate.mcpResourceId)) {
25097
+ issues.push(issue2(`${itemPath}.mcpResourceId`, "INVALID_MCP_RESOURCE_ID", "mcpResourceId is invalid"));
25098
+ }
25099
+ requiredString(candidate.toolName, `${itemPath}.toolName`, issues);
25100
+ requiredString(candidate.purpose, `${itemPath}.purpose`, issues);
25101
+ if (!isPlainRecord(candidate.fixedInput) || !isJsonValue(candidate.fixedInput)) {
25102
+ issues.push(issue2(`${itemPath}.fixedInput`, "INVALID_FIXED_INPUT", "fixedInput must be a JSON object"));
25103
+ }
25104
+ const inputBindings = validateInputBindings(candidate.inputBindings, `${itemPath}.inputBindings`, issues);
25105
+ if (isPlainRecord(candidate.fixedInput) && inputBindings) {
25106
+ for (let bindingIndex = 0; bindingIndex < inputBindings.length; bindingIndex += 1) {
25107
+ const binding = inputBindings[bindingIndex];
25108
+ if (hasOverlappingJsonPointer(candidate.fixedInput, binding.inputPath)) {
25109
+ issues.push(issue2(`${itemPath}.inputBindings[${bindingIndex}].inputPath`, "FIXED_INPUT_OVERRIDE", `dynamic input ${binding.inputPath} overlaps a fixed input and cannot override it`));
25110
+ }
25111
+ }
25112
+ }
25113
+ validateLooseJsonSchema(candidate.inputSchema, `${itemPath}.inputSchema`, issues);
25114
+ validateLooseJsonSchema(candidate.outputSchema, `${itemPath}.outputSchema`, issues);
25115
+ });
25116
+ return value;
25117
+ }
25118
+ function validateDataTransform(value, path2, issues) {
25119
+ if (!isPlainRecord(value)) {
25120
+ issues.push(issue2(path2, "INVALID_DATA_TRANSFORM", "dataTransform must be an object"));
25121
+ return;
25122
+ }
25123
+ exactKeys(value, ["language", "profile", "source"], path2, issues);
25124
+ if (value.language !== A2UI_CARD_DATA_TRANSFORM_LANGUAGE) {
25125
+ issues.push(issue2(`${path2}.language`, "INVALID_DATA_TRANSFORM_LANGUAGE", `language must be ${A2UI_CARD_DATA_TRANSFORM_LANGUAGE}`));
25126
+ }
25127
+ if (value.profile !== A2UI_CARD_DATA_TRANSFORM_PROFILE) {
25128
+ issues.push(issue2(`${path2}.profile`, "INVALID_DATA_TRANSFORM_PROFILE", `profile must be ${A2UI_CARD_DATA_TRANSFORM_PROFILE}`));
25129
+ }
25130
+ if (typeof value.source !== "string" || value.source.trim().length === 0) {
25131
+ issues.push(issue2(`${path2}.source`, "INVALID_DATA_TRANSFORM_SOURCE", "source must be a non-empty string"));
25132
+ } else if (new TextEncoder().encode(value.source).byteLength > A2UI_CARD_DATA_TRANSFORM_MAX_SOURCE_BYTES) {
25133
+ issues.push(issue2(`${path2}.source`, "DATA_TRANSFORM_SOURCE_TOO_LARGE", `source exceeds ${A2UI_CARD_DATA_TRANSFORM_MAX_SOURCE_BYTES} bytes`));
25134
+ } else if (!/^\s*function\s+transform\s*\(\s*input\s*\)\s*\{/u.test(value.source)) {
25135
+ issues.push(issue2(`${path2}.source`, "INVALID_DATA_TRANSFORM_SOURCE", "source must declare function transform(input) { ... }"));
25136
+ }
25137
+ }
25138
+ function validatePipelineFieldSchemas(fields, dataModelSchema, issues) {
25139
+ fields.forEach((field, index) => {
25140
+ if (field.source !== "business")
25141
+ return;
25142
+ const schema = getJsonSchemaAtDataPointer(dataModelSchema, field.path);
25143
+ if (!schema) {
25144
+ issues.push(issue2(`config.fields[${index}].path`, "DATA_MODEL_FIELD_MISSING", `dataModelSchema does not define ${field.path}`));
25145
+ }
25146
+ });
25147
+ }
24687
25148
  function validateV3OutputBindings(value, path2, issues) {
24688
25149
  if (!Array.isArray(value)) {
24689
25150
  issues.push(issue2(path2, "INVALID_OUTPUT_BINDINGS", "bindings must be an array"));
@@ -24734,6 +25195,23 @@ function validateV3Coverage(fields, dataSources, bindings, issues, options = {})
24734
25195
  }
24735
25196
  }
24736
25197
  }
25198
+ function hasOverlappingJsonPointer(fixedInput, inputPath) {
25199
+ const fixedPaths = [];
25200
+ const visit = (value, path2) => {
25201
+ fixedPaths.push(path2);
25202
+ if (!isPlainRecord(value))
25203
+ return;
25204
+ for (const [key, child] of Object.entries(value)) {
25205
+ const escaped = key.replace(/~/gu, "~0").replace(/\//gu, "~1");
25206
+ visit(child, `${path2}/${escaped}`);
25207
+ }
25208
+ };
25209
+ for (const [key, value] of Object.entries(fixedInput)) {
25210
+ const escaped = key.replace(/~/gu, "~0").replace(/\//gu, "~1");
25211
+ visit(value, `/${escaped}`);
25212
+ }
25213
+ return fixedPaths.some((fixedPath) => fixedPath === inputPath || fixedPath.startsWith(`${inputPath}/`) || inputPath.startsWith(`${fixedPath}/`));
25214
+ }
24737
25215
  function validateFields(value, path2, issues) {
24738
25216
  if (!Array.isArray(value)) {
24739
25217
  issues.push(issue2(path2, "INVALID_FIELDS", `${path2} must be an array`));
@@ -24778,13 +25256,13 @@ function validateFields(value, path2, issues) {
24778
25256
  paths.add(canonicalPath);
24779
25257
  }
24780
25258
  requiredString(candidate.label, `${itemPath}.label`, issues);
24781
- if (!FIELD_TYPES.includes(candidate.type)) {
25259
+ if (!FIELD_TYPES.has(candidate.type)) {
24782
25260
  issues.push(issue2(`${itemPath}.type`, "INVALID_FIELD_TYPE", "field type is invalid"));
24783
25261
  }
24784
25262
  if (typeof candidate.required !== "boolean") {
24785
25263
  issues.push(issue2(`${itemPath}.required`, "INVALID_FIELD_REQUIRED", "required must be a boolean"));
24786
25264
  }
24787
- if (!FIELD_SOURCES.includes(candidate.source)) {
25265
+ if (!FIELD_SOURCES.has(candidate.source)) {
24788
25266
  issues.push(issue2(`${itemPath}.source`, "INVALID_FIELD_SOURCE", "field source is invalid"));
24789
25267
  }
24790
25268
  const schemaIssues = getJsonSchemaIssues2(candidate.valueSchema, `${itemPath}.valueSchema`, { requireCompleteStructures: true });
@@ -25232,6 +25710,7 @@ async function executeA2UICardResolver(input) {
25232
25710
  return viewModel;
25233
25711
  }
25234
25712
  function normalizeOptionalNulls(value, schema, required) {
25713
+ value = normalizeCardDataValue(schema, value, required);
25235
25714
  if (value === null || value === void 0) {
25236
25715
  return required ? value : void 0;
25237
25716
  }
@@ -25242,7 +25721,7 @@ function normalizeOptionalNulls(value, schema, required) {
25242
25721
  return [];
25243
25722
  if (!itemSchema)
25244
25723
  return [item];
25245
- const normalized2 = normalizeOptionalNulls(item, itemSchema, false);
25724
+ const normalized2 = normalizeOptionalNulls(item, itemSchema, true);
25246
25725
  return normalized2 === void 0 ? [] : [normalized2];
25247
25726
  });
25248
25727
  }
@@ -25291,80 +25770,12 @@ function valueType2(value) {
25291
25770
  return typeof value === "object" ? "object" : typeof value;
25292
25771
  }
25293
25772
 
25294
- // ../agent-a2ui-card-contract/dist/esm/payment-action.js
25295
- var A2UIActionContractError = class extends Error {
25296
- constructor(issues) {
25297
- super(issues.join("; "));
25298
- Object.defineProperty(this, "issues", {
25299
- enumerable: true,
25300
- configurable: true,
25301
- writable: true,
25302
- value: issues
25303
- });
25304
- Object.defineProperty(this, "code", {
25305
- enumerable: true,
25306
- configurable: true,
25307
- writable: true,
25308
- value: "A2UI_ACTION_CONTRACT_INVALID"
25309
- });
25310
- this.name = "A2UIActionContractError";
25311
- }
25312
- };
25313
- function parseA2UIActionExecuteRequest(value) {
25314
- const issues = getA2UIActionExecuteRequestIssues(value);
25315
- if (issues.length)
25316
- throw new A2UIActionContractError(issues);
25317
- return JSON.parse(JSON.stringify(value));
25318
- }
25319
- function getA2UIActionExecuteRequestIssues(value) {
25320
- if (!isPlainRecord(value))
25321
- return ["request must be an object"];
25322
- const issues = [];
25323
- rejectExtraKeys(value, ["schemaVersion", "agentId", "threadId", "invocationId", "source", "input"], "request", issues);
25324
- if (value.schemaVersion !== "2")
25325
- issues.push("schemaVersion must be 2");
25326
- requiredIdentifier(value.agentId, "agentId", issues);
25327
- requiredIdentifier(value.threadId, "threadId", issues);
25328
- requiredIdentifier(value.invocationId, "invocationId", issues);
25329
- validateSource(value.source, issues);
25330
- if (!cloneJsonObject(value.input))
25331
- issues.push("input must be a JSON object");
25332
- return issues;
25333
- }
25334
- function validateSource(value, issues) {
25335
- if (!isPlainRecord(value)) {
25336
- issues.push("source must be an object");
25337
- return;
25338
- }
25339
- rejectExtraKeys(value, ["cardRef", "cardRevision", "cardInstanceId", "surfaceId", "componentId"], "source", issues);
25340
- requiredIdentifier(value.cardRef, "source.cardRef", issues);
25341
- requiredIdentifier(value.cardRevision, "source.cardRevision", issues);
25342
- requiredText(value.cardInstanceId, "source.cardInstanceId", issues);
25343
- requiredIdentifier(value.surfaceId, "source.surfaceId", issues);
25344
- requiredIdentifier(value.componentId, "source.componentId", issues);
25345
- }
25346
- function rejectExtraKeys(value, allowed, path2, issues) {
25347
- const allowedKeys = new Set(allowed);
25348
- for (const key of Object.keys(value))
25349
- if (!allowedKeys.has(key))
25350
- issues.push(`${path2}.${key} is not allowed`);
25351
- }
25352
- function requiredIdentifier(value, path2, issues) {
25353
- if (!isSafeIdentifier(value))
25354
- issues.push(`${path2} must be a safe identifier`);
25355
- }
25356
- function requiredText(value, path2, issues) {
25357
- if (typeof value !== "string" || !value.trim() || value.length > 256) {
25358
- issues.push(`${path2} must be a non-empty string up to 256 characters`);
25359
- }
25360
- }
25361
-
25362
- // ../agent-a2ui-card-contract/dist/esm/function-action.js
25363
- function parseA2UIFunctionMcpExecuteRequest(value) {
25773
+ // ../agent-a2ui-card-contract/dist/esm/function-action.js
25774
+ function parseA2UIFunctionMcpExecuteRequest(value) {
25364
25775
  const issues = [];
25365
25776
  if (!isPlainRecord(value))
25366
25777
  throw new Error("request must be an object");
25367
- rejectExtraKeys2(value, [
25778
+ rejectExtraKeys(value, [
25368
25779
  "schemaVersion",
25369
25780
  "agentId",
25370
25781
  "threadId",
@@ -25392,15 +25803,15 @@ function parseA2UIFunctionMcpExecuteRequest(value) {
25392
25803
  if (!isPlainRecord(value.action))
25393
25804
  issues.push("action must be an object");
25394
25805
  else {
25395
- rejectExtraKeys2(value.action, ["ref"], "action", issues);
25806
+ rejectExtraKeys(value.action, ["ref"], "action", issues);
25396
25807
  if (!isFunctionRef(value.action.ref))
25397
25808
  issues.push("action.ref is invalid");
25398
25809
  }
25399
- validateSource2(value.source, issues);
25810
+ validateSource(value.source, issues);
25400
25811
  if (!isPlainRecord(value.tool))
25401
25812
  issues.push("tool must be an object");
25402
25813
  else {
25403
- rejectExtraKeys2(value.tool, ["mcpResourceId", "toolName", "input"], "tool", issues);
25814
+ rejectExtraKeys(value.tool, ["mcpResourceId", "toolName", "input"], "tool", issues);
25404
25815
  if (!isSafeIdentifier(value.tool.mcpResourceId))
25405
25816
  issues.push("tool.mcpResourceId is invalid");
25406
25817
  if (!isSafeIdentifier(value.tool.toolName))
@@ -25412,10 +25823,10 @@ function parseA2UIFunctionMcpExecuteRequest(value) {
25412
25823
  throw new Error(issues.join("; "));
25413
25824
  return JSON.parse(JSON.stringify(value));
25414
25825
  }
25415
- function validateSource2(value, issues) {
25826
+ function validateSource(value, issues) {
25416
25827
  if (!isPlainRecord(value))
25417
25828
  return void issues.push("source must be an object");
25418
- rejectExtraKeys2(value, ["cardRef", "cardRevision", "cardInstanceId", "surfaceId", "componentId"], "source", issues);
25829
+ rejectExtraKeys(value, ["cardRef", "cardRevision", "cardInstanceId", "surfaceId", "componentId"], "source", issues);
25419
25830
  for (const key of [
25420
25831
  "cardRef",
25421
25832
  "cardRevision",
@@ -25432,7 +25843,7 @@ function validateSource2(value, issues) {
25432
25843
  function isFunctionRef(value) {
25433
25844
  return typeof value === "string" && value.length <= 128 && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u.test(value);
25434
25845
  }
25435
- function rejectExtraKeys2(value, allowed, path2, issues) {
25846
+ function rejectExtraKeys(value, allowed, path2, issues) {
25436
25847
  const keys = new Set(allowed);
25437
25848
  for (const key of Object.keys(value)) {
25438
25849
  if (!keys.has(key))
@@ -25557,10 +25968,10 @@ function truncateText(value) {
25557
25968
  }
25558
25969
 
25559
25970
  // ../linkque-agent-runtime/dist/esm/core/mcpNaming.js
25560
- import { createHash } from "node:crypto";
25971
+ import { createHash as createHash2 } from "node:crypto";
25561
25972
  function stableToolName(prefix, raw) {
25562
25973
  const readable = raw.replace(/[^A-Za-z0-9_-]+/gu, "_").replace(/^_+|_+$/gu, "").slice(0, 38) || "resource";
25563
- const digest = createHash("sha256").update(raw).digest("hex").slice(0, 10);
25974
+ const digest = createHash2("sha256").update(raw).digest("hex").slice(0, 10);
25564
25975
  return `${prefix}_${readable}_${digest}`;
25565
25976
  }
25566
25977
 
@@ -25699,6 +26110,9 @@ async function executeCardPresentationFromSources(resource, runtimeContext, sour
25699
26110
  if (config.schemaVersion !== "3" && config.schemaVersion !== "4") {
25700
26111
  throw new Error("Source-result rendering is only available for schema v3/v4 cards");
25701
26112
  }
26113
+ if (config.schemaVersion === "4" && config.dataMode === "pipeline") {
26114
+ throw new Error("Pipeline cards must be executed through the aggregate pipeline tool");
26115
+ }
25702
26116
  const missing = config.dataSources.filter((source) => source.required && !sourceResults.has(source.sourceId)).map((source) => source.sourceId);
25703
26117
  if (missing.length) {
25704
26118
  throw new Error(`Required card data sources are incomplete: ${missing.join(", ")}`);
@@ -25820,6 +26234,11 @@ function isAgentPresentationToolResult(value) {
25820
26234
  return false;
25821
26235
  return value.type === "linkque.presentation-tool-result" && typeof value.modelText === "string" && isJsonObject(value.card) && value.card.type === "a2ui_card";
25822
26236
  }
26237
+ function isAgentPresentationSkippedToolResult(value) {
26238
+ if (!isJsonObject(value) || !isJsonObject(value.receipt))
26239
+ return false;
26240
+ return value.type === "linkque.presentation-skipped-tool-result" && typeof value.modelText === "string" && value.receipt.status === "skipped";
26241
+ }
25823
26242
  function injectResolvedViewModel(protocol, viewModel) {
25824
26243
  const analysis = analyzeA2UIBindings(protocol);
25825
26244
  const declaredSurfaceIds = analysis.surfaceIds;
@@ -25941,7 +26360,7 @@ function isJsonObject(value) {
25941
26360
  }
25942
26361
 
25943
26362
  // ../linkque-agent-runtime/dist/esm/core/mcpAggregator.js
25944
- function aggregateMcpServers(resources, protocolAgentId) {
26363
+ function aggregateMcpServers(mcpResources, mcpToolResources, protocolAgentId) {
25945
26364
  const specs = /* @__PURE__ */ new Map();
25946
26365
  const touch = (serverName) => {
25947
26366
  let spec = specs.get(serverName);
@@ -25960,7 +26379,7 @@ function aggregateMcpServers(resources, protocolAgentId) {
25960
26379
  }
25961
26380
  return spec;
25962
26381
  };
25963
- for (const resource of resources) {
26382
+ const collectBase = (resource) => {
25964
26383
  const serverName = resource.config.serverName ?? resource.resourceId;
25965
26384
  const spec = touch(serverName);
25966
26385
  spec.resourceIds.push(resource.resourceId);
@@ -25969,23 +26388,27 @@ function aggregateMcpServers(resources, protocolAgentId) {
25969
26388
  }
25970
26389
  if (!spec.description)
25971
26390
  spec.description = resource.config.description;
25972
- if (resource.resourceType === EResourceType.MCP) {
25973
- for (const rule of resource.config.argsMappingRules ?? []) {
25974
- spec.argsMappingRules.push(rule);
25975
- }
25976
- const allowed = resource.config.allowedTools;
25977
- if (allowed && allowed.length > 0) {
25978
- if (!spec.allowedTools)
25979
- spec.allowedTools = /* @__PURE__ */ new Set();
25980
- for (const toolName of allowed) {
25981
- spec.allowedTools.add(toolName);
25982
- addToolResourceId(spec.resourceIdsByTool, toolName, resource.resourceId);
25983
- }
25984
- } else {
25985
- spec.allToolResourceIds.push(resource.resourceId);
26391
+ return spec;
26392
+ };
26393
+ for (const resource of mcpResources) {
26394
+ const spec = collectBase(resource);
26395
+ for (const rule of resource.config.argsMappingRules ?? []) {
26396
+ spec.argsMappingRules.push(rule);
26397
+ }
26398
+ const allowed = resource.config.allowedTools;
26399
+ if (allowed && allowed.length > 0) {
26400
+ if (!spec.allowedTools)
26401
+ spec.allowedTools = /* @__PURE__ */ new Set();
26402
+ for (const toolName of allowed) {
26403
+ spec.allowedTools.add(toolName);
26404
+ addToolResourceId(spec.resourceIdsByTool, toolName, resource.resourceId);
25986
26405
  }
25987
- continue;
26406
+ } else {
26407
+ spec.allToolResourceIds.push(resource.resourceId);
25988
26408
  }
26409
+ }
26410
+ for (const resource of mcpToolResources) {
26411
+ const spec = collectBase(resource);
25989
26412
  if (!spec.allowedTools)
25990
26413
  spec.allowedTools = /* @__PURE__ */ new Set();
25991
26414
  spec.allowedTools.add(resource.config.toolName);
@@ -26055,6 +26478,22 @@ function resolvePhoneAuthorizationDependency(protocol, resourceIds, toolName) {
26055
26478
  var CONTENT_VALUE_MAX_LENGTH = 16 * 1024;
26056
26479
  var ETelemetryAttribute;
26057
26480
  (function(ETelemetryAttribute2) {
26481
+ ETelemetryAttribute2["LINKQUE_REMOTE_TRACE_ID"] = "linkque.remote.trace_id";
26482
+ ETelemetryAttribute2["LINKQUE_REMOTE_TRACE_ID_HEADER"] = "linkque.remote.trace_id_header";
26483
+ ETelemetryAttribute2["HTTP_REQUEST_METHOD"] = "http.request.method";
26484
+ ETelemetryAttribute2["SERVER_ADDRESS"] = "server.address";
26485
+ ETelemetryAttribute2["URL_PATH"] = "url.path";
26486
+ ETelemetryAttribute2["LINKQUE_MCP_PHASE"] = "linkque.mcp.phase";
26487
+ ETelemetryAttribute2["LINKQUE_MCP_SERVER_NAME"] = "linkque.mcp.server_name";
26488
+ ETelemetryAttribute2["LINKQUE_IO_ATTEMPT"] = "linkque.io.attempt";
26489
+ ETelemetryAttribute2["LINKQUE_SKILL_RESOURCE_ID"] = "linkque.skill.resource_id";
26490
+ ETelemetryAttribute2["LINKQUE_SKILL_REQUESTED_COUNT"] = "linkque.skill.requested_count";
26491
+ ETelemetryAttribute2["LINKQUE_SKILL_RESOLVED_COUNT"] = "linkque.skill.resolved_count";
26492
+ ETelemetryAttribute2["LINKQUE_SKILL_LOADED_COUNT"] = "linkque.skill.loaded_count";
26493
+ ETelemetryAttribute2["LINKQUE_SKILL_SKIPPED_COUNT"] = "linkque.skill.skipped_count";
26494
+ ETelemetryAttribute2["LINKQUE_CHUNK_INDEX"] = "linkque.chunk.index";
26495
+ ETelemetryAttribute2["LINKQUE_CHUNK_STATUS"] = "linkque.chunk.status";
26496
+ ETelemetryAttribute2["LINKQUE_CHUNK_LINE_COUNT"] = "linkque.chunk.line_count";
26058
26497
  ETelemetryAttribute2["HARNESS_TELEMETRY_SCHEMA_VERSION"] = "harness.telemetry.schema.version";
26059
26498
  ETelemetryAttribute2["LINKQUE_TELEMETRY_SCHEMA_VERSION"] = "linkque.telemetry.schema.version";
26060
26499
  ETelemetryAttribute2["LINKQUE_TELEMETRY_ADAPTER_VERSION"] = "linkque.telemetry.adapter.version";
@@ -26087,6 +26526,8 @@ var ETelemetryAttribute;
26087
26526
  ETelemetryAttribute2["HARNESS_RECORD_ID"] = "harness.record.id";
26088
26527
  ETelemetryAttribute2["HARNESS_EVENT_SEQUENCE"] = "harness.event.sequence";
26089
26528
  ETelemetryAttribute2["ERROR_TYPE"] = "error.type";
26529
+ ETelemetryAttribute2["LINKQUE_APPBASE_RUN_FAILURE_STAGE"] = "linkque.appbase.run.failure_stage";
26530
+ ETelemetryAttribute2["LINKQUE_APPBASE_RUN_ERROR_MESSAGE"] = "linkque.appbase.run.error_message";
26090
26531
  ETelemetryAttribute2["LINKQUE_STREAM_TERMINATION"] = "linkque.stream.termination";
26091
26532
  ETelemetryAttribute2["LINKQUE_STREAM_CANCEL_SOURCE"] = "linkque.stream.cancel_source";
26092
26533
  ETelemetryAttribute2["LINKQUE_TERMINAL_EVIDENCE"] = "linkque.terminal.evidence";
@@ -26249,6 +26690,18 @@ var ETelemetryContentSection;
26249
26690
  })(ETelemetryContentSection || (ETelemetryContentSection = {}));
26250
26691
  var ETelemetryOperationName;
26251
26692
  (function(ETelemetryOperationName2) {
26693
+ ETelemetryOperationName2["APPBASE_RUN"] = "linkque.appbase.run";
26694
+ ETelemetryOperationName2["RUNS_WRITE"] = "linkque.appbase.runs.write";
26695
+ ETelemetryOperationName2["MCP_DISCOVER"] = "linkque.mcp.discover";
26696
+ ETelemetryOperationName2["MCP_SIGN"] = "linkque.mcp.sign";
26697
+ ETelemetryOperationName2["MCP_OPENGW"] = "linkque.mcp.opengw";
26698
+ ETelemetryOperationName2["MCP_VERIFY"] = "linkque.mcp.verify";
26699
+ ETelemetryOperationName2["KNOWLEDGE_SEARCH"] = "linkque.knowledge.search";
26700
+ ETelemetryOperationName2["WEB_SEARCH"] = "linkque.web_search.search";
26701
+ ETelemetryOperationName2["SKILL_LOAD"] = "linkque.skill.load";
26702
+ ETelemetryOperationName2["SKILL_QUERY"] = "linkque.skill.query";
26703
+ ETelemetryOperationName2["SKILL_RESOURCE_LOAD"] = "linkque.skill.resource.load";
26704
+ ETelemetryOperationName2["SKILL_DOWNLOAD"] = "linkque.skill.download";
26252
26705
  ETelemetryOperationName2["OPERATION"] = "linkque.operation";
26253
26706
  ETelemetryOperationName2["TOOL_INVOKE"] = "harness.tool.invoke";
26254
26707
  ETelemetryOperationName2["ADVANCE"] = "harness.advance";
@@ -26394,6 +26847,9 @@ var ETelemetryModelPurpose;
26394
26847
  })(ETelemetryModelPurpose || (ETelemetryModelPurpose = {}));
26395
26848
  var ETelemetryErrorType;
26396
26849
  (function(ETelemetryErrorType2) {
26850
+ ETelemetryErrorType2["IO_ERROR"] = "io_error";
26851
+ ETelemetryErrorType2["IO_CANCELLED"] = "io_cancelled";
26852
+ ETelemetryErrorType2["IO_TIMEOUT"] = "io_timeout";
26397
26853
  ETelemetryErrorType2["PROVIDER_STREAM_ERROR"] = "ProviderStreamError";
26398
26854
  ETelemetryErrorType2["TOOL_EXECUTION_ERROR"] = "ToolExecutionError";
26399
26855
  ETelemetryErrorType2["HOOK_DISPATCH_ERROR"] = "HookDispatchError";
@@ -26404,6 +26860,16 @@ var ETelemetrySpanKind;
26404
26860
  ETelemetrySpanKind2["INTERNAL"] = "internal";
26405
26861
  ETelemetrySpanKind2["CLIENT"] = "client";
26406
26862
  })(ETelemetrySpanKind || (ETelemetrySpanKind = {}));
26863
+ var ETelemetryMcpPhase;
26864
+ (function(ETelemetryMcpPhase2) {
26865
+ ETelemetryMcpPhase2["SSE_CONNECT"] = "sse_connect";
26866
+ ETelemetryMcpPhase2["INITIALIZE"] = "initialize";
26867
+ ETelemetryMcpPhase2["TOOLS_LIST"] = "tools/list";
26868
+ ETelemetryMcpPhase2["TOOLS_CALL"] = "tools/call";
26869
+ ETelemetryMcpPhase2["INITIALIZED"] = "notifications/initialized";
26870
+ ETelemetryMcpPhase2["CANCELLED"] = "notifications/cancelled";
26871
+ ETelemetryMcpPhase2["HTTP"] = "http";
26872
+ })(ETelemetryMcpPhase || (ETelemetryMcpPhase = {}));
26407
26873
  var ETelemetryGenAiOperation;
26408
26874
  (function(ETelemetryGenAiOperation2) {
26409
26875
  ETelemetryGenAiOperation2["CHAT"] = "chat";
@@ -26416,6 +26882,306 @@ var ETelemetryVersion;
26416
26882
  ETelemetryVersion2["V1_0"] = "1.0";
26417
26883
  })(ETelemetryVersion || (ETelemetryVersion = {}));
26418
26884
 
26885
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/noopRuntimeTelemetry.js
26886
+ var NoopRuntimeObservation = class {
26887
+ enabled = false;
26888
+ operationId = "";
26889
+ spanContext = null;
26890
+ captureParent() {
26891
+ return {
26892
+ operationId: "",
26893
+ spanContext: null,
26894
+ startOperation: () => this,
26895
+ release: () => {
26896
+ }
26897
+ };
26898
+ }
26899
+ startOperation(_operation) {
26900
+ return this;
26901
+ }
26902
+ record(_name, _attributes, _body) {
26903
+ }
26904
+ finish(_outcome, _attributes) {
26905
+ }
26906
+ abandon(_reason) {
26907
+ }
26908
+ };
26909
+ var NoopRuntimeTelemetry = class {
26910
+ startOperation() {
26911
+ return new NoopRuntimeObservation();
26912
+ }
26913
+ startAdvance(_input) {
26914
+ return new NoopRuntimeObservation();
26915
+ }
26916
+ async forceFlush(_options) {
26917
+ return { completed: true, pendingCount: 0, sentCount: 0, droppedCount: 0 };
26918
+ }
26919
+ shutdown(options) {
26920
+ return this.forceFlush(options);
26921
+ }
26922
+ };
26923
+
26924
+ // ../linkque-agent-runtime/dist/esm/utils/skipError.js
26925
+ function skipError(fn) {
26926
+ try {
26927
+ return fn();
26928
+ } catch (err2) {
26929
+ console.error("[observeIo] skipped", err2);
26930
+ }
26931
+ }
26932
+
26933
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/runtimeObservation.js
26934
+ var RuntimeObservation = class _RuntimeObservation {
26935
+ sink;
26936
+ associations;
26937
+ key;
26938
+ scope;
26939
+ finished = false;
26940
+ abandoned = false;
26941
+ resultAttributes = {};
26942
+ constructor(sink, associations = /* @__PURE__ */ new Map(), key, scope = {
26943
+ active: /* @__PURE__ */ new Set(),
26944
+ abandoned: false
26945
+ }) {
26946
+ this.sink = sink;
26947
+ this.associations = associations;
26948
+ this.key = key;
26949
+ this.scope = scope;
26950
+ }
26951
+ get enabled() {
26952
+ try {
26953
+ return this.sink.enabled;
26954
+ } catch {
26955
+ return false;
26956
+ }
26957
+ }
26958
+ get operationId() {
26959
+ try {
26960
+ return this.sink.operationId;
26961
+ } catch {
26962
+ return "";
26963
+ }
26964
+ }
26965
+ get spanContext() {
26966
+ try {
26967
+ return this.sink.spanContext;
26968
+ } catch {
26969
+ return null;
26970
+ }
26971
+ }
26972
+ captureParent() {
26973
+ let parent;
26974
+ try {
26975
+ parent = this.sink.captureParent?.();
26976
+ if (parent) {
26977
+ const captured = parent;
26978
+ let released = false;
26979
+ return {
26980
+ operationId: parent.operationId,
26981
+ spanContext: parent.spanContext,
26982
+ startOperation: (operation) => {
26983
+ try {
26984
+ return new _RuntimeObservation(released || this.abandoned || this.scope.abandoned ? new NoopRuntimeObservation() : captured.startOperation(operation));
26985
+ } catch {
26986
+ return new _RuntimeObservation(new NoopRuntimeObservation());
26987
+ }
26988
+ },
26989
+ release: () => {
26990
+ if (released)
26991
+ return;
26992
+ released = true;
26993
+ skipError(() => captured.release());
26994
+ }
26995
+ };
26996
+ }
26997
+ } catch {
26998
+ skipError(() => parent?.release());
26999
+ }
27000
+ return new NoopRuntimeObservation().captureParent();
27001
+ }
27002
+ startOperation(operation, key) {
27003
+ if (this.scope.abandoned) {
27004
+ return new _RuntimeObservation(new NoopRuntimeObservation());
27005
+ }
27006
+ if (this.scope.active.size >= 4096) {
27007
+ this.record(ETelemetryEventName.OPERATION_OBSERVATION_LOST, {
27008
+ [ETelemetryAttribute.LINKQUE_TELEMETRY_LOSS_REASON]: ETelemetryLossReason.ACTIVE_LIMIT
27009
+ });
27010
+ return new _RuntimeObservation(new NoopRuntimeObservation());
27011
+ }
27012
+ let sink = new NoopRuntimeObservation();
27013
+ skipError(() => {
27014
+ if (!this.enabled) {
27015
+ return;
27016
+ }
27017
+ sink = this.sink.startOperation(operation);
27018
+ });
27019
+ const child = new _RuntimeObservation(sink, this.associations, key, this.scope);
27020
+ if (child.enabled)
27021
+ this.scope.active.add(child);
27022
+ if (key && child.enabled && this.associations.size < 4096)
27023
+ this.associations.set(key, child);
27024
+ return child;
27025
+ }
27026
+ find(key) {
27027
+ return this.associations.get(key);
27028
+ }
27029
+ record(name, attributes, body) {
27030
+ if (this.abandoned)
27031
+ return;
27032
+ skipError(() => {
27033
+ if (attributes[ETelemetryAttribute.LINKQUE_TOOL_FAILURE_STAGE]) {
27034
+ this.resultAttributes = {
27035
+ [ETelemetryAttribute.LINKQUE_TOOL_FAILURE_STAGE]: attributes[ETelemetryAttribute.LINKQUE_TOOL_FAILURE_STAGE]
27036
+ };
27037
+ }
27038
+ this.sink.record(name, attributes, body);
27039
+ });
27040
+ }
27041
+ finish(outcome, attributes) {
27042
+ if (this.finished)
27043
+ return;
27044
+ this.finished = true;
27045
+ this.scope.active.delete(this);
27046
+ if (this.key && this.associations.get(this.key) === this)
27047
+ this.associations.delete(this.key);
27048
+ let result = this.resultAttributes;
27049
+ skipError(() => {
27050
+ result = Object.assign({}, result, attributes);
27051
+ });
27052
+ skipError(() => {
27053
+ this.sink.finish(outcome, result);
27054
+ });
27055
+ }
27056
+ abandon(reason) {
27057
+ if (this.finished)
27058
+ return;
27059
+ this.finished = true;
27060
+ this.abandoned = true;
27061
+ this.scope.active.delete(this);
27062
+ if (this.key && this.associations.get(this.key) === this) {
27063
+ this.associations.delete(this.key);
27064
+ }
27065
+ skipError(() => {
27066
+ this.sink.abandon(reason);
27067
+ });
27068
+ }
27069
+ /** 包含无关联键及旁路操作,仅回收本次 advance 的观察资源。 */
27070
+ abandonPending(reason) {
27071
+ this.scope.abandoned = true;
27072
+ for (const operation of this.scope.active)
27073
+ operation.abandon(reason);
27074
+ this.associations.clear();
27075
+ }
27076
+ /** 仅结束仍由本地消费方拥有的观察,旁路任务不注册到此表。 */
27077
+ closePending() {
27078
+ for (const operation of this.associations.values()) {
27079
+ operation.finish(ETelemetryOutcome.UNKNOWN, {
27080
+ [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.LOCAL_WAIT,
27081
+ [ETelemetryAttribute.HARNESS_REMOTE_COMPLETION]: ETelemetryRemoteCompletion.UNKNOWN
27082
+ });
27083
+ }
27084
+ this.associations.clear();
27085
+ }
27086
+ };
27087
+ function startRuntimeObservation(telemetry, input) {
27088
+ try {
27089
+ return new RuntimeObservation(telemetry.startAdvance(input));
27090
+ } catch {
27091
+ return new RuntimeObservation(new NoopRuntimeObservation());
27092
+ }
27093
+ }
27094
+
27095
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/ioObservation.js
27096
+ async function observeIo(create, task, classify = () => ETelemetryOutcome.SUCCESS) {
27097
+ let operation;
27098
+ operation = skipError(create);
27099
+ const active = operation ?? {
27100
+ observation: new RuntimeObservation(new NoopRuntimeObservation()),
27101
+ add: () => {
27102
+ }
27103
+ };
27104
+ let outcome = ETelemetryOutcome.SUCCESS;
27105
+ try {
27106
+ const value = await task(active);
27107
+ outcome = skipError(() => classify(value)) ?? ETelemetryOutcome.UNKNOWN;
27108
+ return value;
27109
+ } catch (error) {
27110
+ outcome = ETelemetryOutcome.ERROR;
27111
+ skipError(() => operation?.fail(error));
27112
+ throw error;
27113
+ } finally {
27114
+ skipError(() => operation?.finish(outcome));
27115
+ }
27116
+ }
27117
+ var IoObservation = class {
27118
+ signal;
27119
+ observation;
27120
+ ended = false;
27121
+ attributes = {};
27122
+ onAbort = () => this.fail(this.signal?.reason);
27123
+ constructor(parent, name, attributes = {}, signal, links = []) {
27124
+ this.signal = signal;
27125
+ const sink = skipError(() => parent?.startOperation({
27126
+ name,
27127
+ attributes,
27128
+ eventPrefix: ETelemetryEventPrefix.OPERATION,
27129
+ detached: false,
27130
+ links
27131
+ })) ?? new NoopRuntimeObservation();
27132
+ this.observation = new RuntimeObservation(sink);
27133
+ signal?.addEventListener("abort", this.onAbort, { once: true });
27134
+ if (signal?.aborted) {
27135
+ this.onAbort();
27136
+ }
27137
+ }
27138
+ add(attributes) {
27139
+ if (this.ended) {
27140
+ return;
27141
+ }
27142
+ this.attributes = Object.assign({}, this.attributes, attributes);
27143
+ }
27144
+ finish(outcome = ETelemetryOutcome.SUCCESS) {
27145
+ if (this.ended) {
27146
+ return;
27147
+ }
27148
+ if (outcome === ETelemetryOutcome.ERROR) {
27149
+ const errorType = this.attributes[ETelemetryAttribute.ERROR_TYPE] ?? ETelemetryErrorType.IO_ERROR;
27150
+ this.add({ [ETelemetryAttribute.ERROR_TYPE]: errorType });
27151
+ }
27152
+ this.ended = true;
27153
+ this.signal?.removeEventListener("abort", this.onAbort);
27154
+ this.observation.finish(outcome, this.attributes);
27155
+ }
27156
+ fail(error) {
27157
+ const reason = this.signal?.aborted ? this.signal.reason : error;
27158
+ let timeout = false;
27159
+ let cancelled = this.signal?.aborted ?? false;
27160
+ skipError(() => {
27161
+ const value = reason;
27162
+ timeout = value?.name === "TimeoutError" || typeof value?.code === "string" && value.code.endsWith("_TIMEOUT");
27163
+ cancelled ||= value?.name === "AbortError";
27164
+ });
27165
+ let outcome = ETelemetryOutcome.ERROR;
27166
+ let errorType = ETelemetryErrorType.IO_ERROR;
27167
+ if (timeout) {
27168
+ outcome = ETelemetryOutcome.TIMEOUT;
27169
+ errorType = ETelemetryErrorType.IO_TIMEOUT;
27170
+ } else if (cancelled) {
27171
+ outcome = ETelemetryOutcome.CANCELLED;
27172
+ errorType = ETelemetryErrorType.IO_CANCELLED;
27173
+ }
27174
+ this.add({ [ETelemetryAttribute.ERROR_TYPE]: errorType });
27175
+ if (cancelled || timeout) {
27176
+ this.add({
27177
+ [ETelemetryAttribute.HARNESS_REMOTE_COMPLETION]: ETelemetryRemoteCompletion.UNKNOWN,
27178
+ [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.LOCAL_WAIT
27179
+ });
27180
+ }
27181
+ this.finish(outcome);
27182
+ }
27183
+ };
27184
+
26419
27185
  // ../linkque-agent-runtime/dist/esm/core/telemetry/contentRecording.js
26420
27186
  function recordContentSection(observation, section, value, availability = "available") {
26421
27187
  observation?.record(ETelemetryEventName.CONTENT_RECORDED, {}, { section, value, availability });
@@ -26592,6 +27358,7 @@ var McpProxyTool = class {
26592
27358
  specByResourceId;
26593
27359
  specs;
26594
27360
  debugLog;
27361
+ observation;
26595
27362
  authorizeCall;
26596
27363
  constructor(provider, specs, options = {}) {
26597
27364
  this.provider = provider;
@@ -26604,6 +27371,7 @@ var McpProxyTool = class {
26604
27371
  this.debugLog = options.debugLog ?? (() => {
26605
27372
  });
26606
27373
  this.authorizeCall = options.authorizeCall;
27374
+ this.observation = options.observation;
26607
27375
  }
26608
27376
  /**
26609
27377
  * 产单个 `mcp` 代理工具描述符,注入 `agentReq.tools`。
@@ -26652,7 +27420,7 @@ var McpProxyTool = class {
26652
27420
  };
26653
27421
  }
26654
27422
  /** 并发发现所有 server;每个 server 独立限时,失败结果不阻断其他目录。 */
26655
- async discover(signal) {
27423
+ async discover(signal, observation) {
26656
27424
  signal?.throwIfAborted();
26657
27425
  const results = await Promise.all(this.specs.map(async (spec) => {
26658
27426
  const scope = new CancellationScope({
@@ -26662,17 +27430,21 @@ var McpProxyTool = class {
26662
27430
  timeoutReason: new DOMException("MCP \u76EE\u5F55\u9884\u52A0\u8F7D\u8D85\u65F6", "TimeoutError")
26663
27431
  });
26664
27432
  try {
26665
- const entry = await this.ensureEntry(spec.serverName, scope.context.signal);
26666
- return {
26667
- serverName: spec.serverName,
26668
- status: entry ? "connected" : "failed",
26669
- tools: (entry?.tools ?? []).map(({ name, description }) => {
26670
- const metadata = { name };
26671
- if (description !== void 0)
27433
+ return await observeIo(() => new IoObservation(observation, ETelemetryOperationName.MCP_DISCOVER, {
27434
+ [ETelemetryAttribute.LINKQUE_MCP_SERVER_NAME]: spec.serverName
27435
+ }, scope.context.signal), async (discovery) => {
27436
+ const entry = await this.ensureEntry(spec.serverName, scope.context.signal, discovery.observation);
27437
+ const status = entry ? "connected" : "failed";
27438
+ const tools = entry?.tools?.map(({ name, description }) => {
27439
+ const metadata = {
27440
+ name
27441
+ };
27442
+ if (description)
26672
27443
  metadata.description = description;
26673
27444
  return metadata;
26674
- })
26675
- };
27445
+ }) ?? [];
27446
+ return { serverName: spec.serverName, status, tools };
27447
+ }, (result) => result.status === "connected" ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.ERROR);
26676
27448
  } catch (error) {
26677
27449
  if (signal?.aborted || this.lifetime.context.signal.aborted)
26678
27450
  throw error;
@@ -26723,7 +27495,7 @@ var McpProxyTool = class {
26723
27495
  }
26724
27496
  // —— 内部:连接与缓存 ——
26725
27497
  /** 确保某 server 已连;返回 connected 条目,依失败返回 null(不抛错)。 */
26726
- async ensureEntry(serverName, signal) {
27498
+ async ensureEntry(serverName, signal, observation) {
26727
27499
  this.lifetime.context.throwIfAborted();
26728
27500
  signal?.throwIfAborted();
26729
27501
  const existing = this.entries.get(serverName);
@@ -26733,16 +27505,10 @@ var McpProxyTool = class {
26733
27505
  let attempt = this.inFlight.get(serverName);
26734
27506
  if (!attempt) {
26735
27507
  const scope = new CancellationScope({ parent: this.lifetime.context });
26736
- attempt = {
26737
- promise: Promise.resolve({}),
26738
- scope,
26739
- waiters: 0,
26740
- settled: false,
26741
- abandoned: false
26742
- };
27508
+ attempt = { scope, waiters: 0, settled: false, abandoned: false };
26743
27509
  const current = attempt;
26744
27510
  this.inFlight.set(serverName, current);
26745
- current.promise = this.connect(serverName, scope.context.signal, current).finally(() => {
27511
+ current.promise = this.connect(serverName, scope.context.signal, current, observation ?? this.observation).finally(() => {
26746
27512
  current.settled = true;
26747
27513
  if (this.inFlight.get(serverName) === current)
26748
27514
  this.inFlight.delete(serverName);
@@ -26751,7 +27517,11 @@ var McpProxyTool = class {
26751
27517
  }
26752
27518
  attempt.waiters += 1;
26753
27519
  try {
26754
- const entry = await waitWithSignal(attempt.promise, signal);
27520
+ const promise = attempt.promise;
27521
+ if (!promise) {
27522
+ throw new Error("MCP \u5EFA\u8FDE\u72B6\u6001\u7F3A\u5C11 Promise");
27523
+ }
27524
+ const entry = await waitWithSignal(promise, signal);
26755
27525
  return entry.status === "connected" ? entry : null;
26756
27526
  } finally {
26757
27527
  attempt.waiters -= 1;
@@ -26764,7 +27534,7 @@ var McpProxyTool = class {
26764
27534
  }
26765
27535
  }
26766
27536
  /** 连单个 server 并 listTools;按 spec.allowedTools 过滤后缓存;失败记为 failed。 */
26767
- async connect(serverName, signal, attempt) {
27537
+ async connect(serverName, signal, attempt, observation) {
26768
27538
  const isCurrent = () => !attempt.abandoned && this.inFlight.get(serverName) === attempt && !this.lifetime.context.signal.aborted;
26769
27539
  const spec = this.specByServerName.get(serverName);
26770
27540
  if (!spec) {
@@ -26798,7 +27568,7 @@ var McpProxyTool = class {
26798
27568
  argsMappingRules: spec.argsMappingRules
26799
27569
  }
26800
27570
  };
26801
- const pending = this.provider.servers([synthetic], signal).then((servers2) => {
27571
+ const pending = this.provider.servers([synthetic], signal, observation).then((servers2) => {
26802
27572
  server = servers2[0];
26803
27573
  if (signal.aborted) {
26804
27574
  for (const item of servers2)
@@ -26812,7 +27582,7 @@ var McpProxyTool = class {
26812
27582
  if (!server) {
26813
27583
  throw new Error(`provider returned no server for ${spec.serverName}`);
26814
27584
  }
26815
- const all = await waitWithSignal(server.listTools(signal), signal);
27585
+ const all = await waitWithSignal(server.listTools(signal, observation), signal);
26816
27586
  signal.throwIfAborted();
26817
27587
  const tools = spec.allowedTools ? all.filter((tool) => spec.allowedTools.has(tool.name)) : all;
26818
27588
  const entry = { server, tools, status: "connected" };
@@ -26856,7 +27626,7 @@ var McpProxyTool = class {
26856
27626
  return this.executeBatchSearch(params.searches, params.server, context2);
26857
27627
  }
26858
27628
  if (params.search !== void 0) {
26859
- const result = await this.executeSearch(params.search, params.server);
27629
+ const result = await this.executeSearch(params.search, params.server, context2?.observation);
26860
27630
  this.recordAction(context2, "search", result.tools.length ? "matched" : "no_hits", { query: result.query, tools: result.tools });
26861
27631
  return result.text;
26862
27632
  }
@@ -26918,7 +27688,7 @@ ${lines.join("\n")}${hint}`.trim();
26918
27688
  if (previous?.server)
26919
27689
  await this.closeServer(previous.server);
26920
27690
  }
26921
- const entry = await this.ensureEntry(spec.serverName, signal);
27691
+ const entry = await this.ensureEntry(spec.serverName, signal, context2?.observation);
26922
27692
  if (!entry) {
26923
27693
  this.recordAction(context2, "connect", "failed", {
26924
27694
  server: spec.serverName
@@ -26943,7 +27713,7 @@ ${lines.join("\n")}${hint}`.trim();
26943
27713
  this.recordAction(context2, "list", "not_found", { server });
26944
27714
  return `Server "${server}" not found. Use mcp({}) to see available servers.`;
26945
27715
  }
26946
- const entry = await this.ensureEntry(spec.serverName, signal);
27716
+ const entry = await this.ensureEntry(spec.serverName, signal, context2?.observation);
26947
27717
  if (!entry) {
26948
27718
  this.recordAction(context2, "list", "failed", { server: spec.serverName });
26949
27719
  return `Server "${spec.serverName}" is not connected. Use mcp({ connect: "${spec.serverName}" }) to retry.`;
@@ -26958,13 +27728,13 @@ ${lines.join("\n")}${hint}`.trim();
26958
27728
  return this.formatToolList(spec.serverName, entry.tools);
26959
27729
  }
26960
27730
  /** `mcp({ search: "query" })`:空格分词 OR 子串匹配 name/description(跨所有 server)。 */
26961
- async executeSearch(query, serverHint) {
27731
+ async executeSearch(query, serverHint, observation) {
26962
27732
  const terms = query.trim().split(/\s+/u).filter((t) => t.length > 0);
26963
27733
  if (terms.length === 0)
26964
27734
  return { query, text: "Search query cannot be empty.", tools: [] };
26965
27735
  const pattern = new RegExp(terms.map(escapeRegExp).join("|"), "iu");
26966
27736
  const specs = serverHint ? this.specsMatching(serverHint) : this.specs;
26967
- await Promise.all(specs.map((s) => this.ensureEntry(s.serverName)));
27737
+ await Promise.all(specs.map((s) => this.ensureEntry(s.serverName, void 0, observation)));
26968
27738
  const matches = [];
26969
27739
  for (const spec of specs) {
26970
27740
  const entry = this.entries.get(spec.serverName);
@@ -27010,15 +27780,15 @@ ${formatSchema(tool.inputSchema, " ")}`);
27010
27780
  return "Batch search requires at least one non-empty query.";
27011
27781
  }
27012
27782
  const specs = serverHint ? this.specsMatching(serverHint) : this.specs;
27013
- await Promise.all(specs.map((spec) => this.ensureEntry(spec.serverName)));
27014
- const results = await Promise.all(normalized.map((query) => this.executeSearch(query, serverHint)));
27783
+ await Promise.all(specs.map((spec) => this.ensureEntry(spec.serverName, void 0, context2?.observation)));
27784
+ const results = await Promise.all(normalized.map((query) => this.executeSearch(query, serverHint, context2?.observation)));
27015
27785
  this.recordAction(context2, "search", results.some((result) => result.tools.length) ? "matched" : "no_hits", { results: results.map(({ query, tools }) => ({ query, tools })) });
27016
27786
  return results.map((result, index) => `Query ${index + 1}: "${normalized[index]}"
27017
27787
  ${result.text}`).join("\n\n");
27018
27788
  }
27019
27789
  /** `mcp({ describe: "tool" })`:输出工具所属 server + 参数 schema。 */
27020
27790
  async executeDescribe(toolName, serverHint, signal, context2) {
27021
- const found = await this.findTool(toolName, serverHint, signal);
27791
+ const found = await this.findTool(toolName, serverHint, signal, context2?.observation);
27022
27792
  if (!found) {
27023
27793
  this.recordAction(context2, "describe", "not_found", { name: toolName });
27024
27794
  return `Tool "${toolName}" not found. Use mcp({ search: "..." }) to search.`;
@@ -27045,7 +27815,7 @@ ${formatSchema(tool.inputSchema)}`);
27045
27815
  }
27046
27816
  /** `mcp({ tool: "name", args: {...} })`:调用工具,返回序列化结果。 */
27047
27817
  async executeCall(toolName, args, serverHint, signal, context2) {
27048
- const found = await this.findTool(toolName, serverHint, signal);
27818
+ const found = await this.findTool(toolName, serverHint, signal, context2?.observation);
27049
27819
  if (!found) {
27050
27820
  this.recordAction(context2, "call", "not_found", { name: toolName });
27051
27821
  return `Tool "${toolName}" not found. Use mcp({ search: "..." }) to search.`;
@@ -27076,7 +27846,7 @@ ${formatSchema(tool.inputSchema)}`);
27076
27846
  }
27077
27847
  // —— 辅助 ——
27078
27848
  /** 跨(或按 hint)已连 server 查找工具;未连则触发懒连接。 */
27079
- async findTool(toolName, serverHint, signal) {
27849
+ async findTool(toolName, serverHint, signal, observation) {
27080
27850
  const specs = serverHint ? this.specsMatching(serverHint) : this.specs;
27081
27851
  for (const spec of specs) {
27082
27852
  const entry = this.entries.get(spec.serverName);
@@ -27087,7 +27857,7 @@ ${formatSchema(tool.inputSchema)}`);
27087
27857
  return { entry, server: spec.serverName, tool, spec };
27088
27858
  }
27089
27859
  }
27090
- await Promise.all(specs.map((s) => this.ensureEntry(s.serverName, signal)));
27860
+ await Promise.all(specs.map((s) => this.ensureEntry(s.serverName, signal, observation)));
27091
27861
  for (const spec of specs) {
27092
27862
  const entry = this.entries.get(spec.serverName);
27093
27863
  if (!entry || entry.status !== "connected")
@@ -27244,8 +28014,9 @@ async function executeHomeData(input) {
27244
28014
  if (!input.userId.trim()) {
27245
28015
  return failure("AUTH_REQUIRED", "\u9996\u9875\u6570\u636E\u8BF7\u6C42\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
27246
28016
  }
27247
- const resources = input.protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL);
27248
- const specs = aggregateMcpServers(resources, input.protocol.agentId);
28017
+ const mcpResources = input.protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP);
28018
+ const mcpToolResources = input.protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP_TOOL);
28019
+ const specs = aggregateMcpServers(mcpResources, mcpToolResources, input.protocol.agentId);
27249
28020
  const spec = specs.find((candidate) => candidate.serverName === request.binding.mcpName);
27250
28021
  if (!spec) {
27251
28022
  return failure("MCP_NOT_BOUND", "\u5F53\u524D Agent \u672A\u7ED1\u5B9A\u8BE5 MCP", false);
@@ -27329,443 +28100,43 @@ function failure(code, message, retryable) {
27329
28100
  return { ok: false, error: { code, message, retryable } };
27330
28101
  }
27331
28102
 
27332
- // ../linkque-agent-runtime/dist/esm/core/cardActionDiagnostics.js
27333
- var CardActionDiagnostics = class {
27334
- sink;
27335
- layer;
27336
- operation;
27337
- stage = "validate";
27338
- context;
27339
- debugLog;
27340
- startedAt = performance.now();
27341
- sensitiveValues = /* @__PURE__ */ new Set();
27342
- constructor(sink, context2, layer = "runtime", operation = "a2uiAction.execute") {
27343
- this.sink = sink;
27344
- this.layer = layer;
27345
- this.operation = operation;
27346
- this.context = { ...context2 };
27347
- if (sink) {
27348
- this.debugLog = (line, scope) => {
27349
- this.write("diagnostic", { message: line }, scope);
27350
- };
28103
+ // ../linkque-agent-runtime/dist/esm/core/mcpExecution.js
28104
+ async function executeAuthorizedMcp(input) {
28105
+ if (input.agentId !== input.protocol.agentId)
28106
+ return failure2("AGENT_MISMATCH", "\u8BF7\u6C42\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
28107
+ if (!input.userId.trim())
28108
+ return failure2("AUTH_REQUIRED", "\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
28109
+ const mcpResources = input.protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP);
28110
+ const mcpToolResources = input.protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP_TOOL);
28111
+ const registry = new McpProxyTool(input.mcpServerProvider, aggregateMcpServers(mcpResources, mcpToolResources, input.protocol.agentId), {
28112
+ authorizeCall: createRequestMcpPhoneAuthorizer(input.protocol, input.phoneAuthorization)
28113
+ });
28114
+ try {
28115
+ const tool = await registry.resolve(input.tool.mcpResourceId, input.tool.toolName, input.signal);
28116
+ if (!tool)
28117
+ return failure2("TOOL_NOT_ALLOWED", "MCP Tool \u4E0D\u5B58\u5728\u6216\u672A\u6388\u6743", false);
28118
+ const schema = cloneJsonObject(tool.inputSchema);
28119
+ if (schema && validateJsonSchemaValue(schema, input.tool.input).length > 0) {
28120
+ return failure2("INVALID_INPUT", "MCP \u5165\u53C2\u4E0D\u7B26\u5408 Tool Schema", false);
27351
28121
  }
27352
- }
27353
- /** 根据绑定路径登记敏感值;解析仅为日志服务,失败不影响业务。 */
27354
- protect(readValue) {
27355
- if (!this.sink)
27356
- return;
28122
+ let result;
27357
28123
  try {
27358
- const value = readValue();
27359
- if (typeof value === "string" && value)
27360
- this.sensitiveValues.add(value);
27361
- } catch {
28124
+ result = await tool.execute(input.tool.input, input.signal);
28125
+ } catch (error) {
28126
+ if (isMcpPhoneAuthorizationError(error))
28127
+ throw error;
28128
+ return failure2("EXECUTION_UNCERTAIN", "MCP \u6267\u884C\u7ED3\u679C\u4E0D\u786E\u5B9A\uFF0C\u8BF7\u52FF\u81EA\u52A8\u91CD\u8BD5", false);
27362
28129
  }
27363
- }
27364
- write(event, fields = {}, scope = EDebugLogScope.A2UI_ACTION) {
27365
- if (!this.sink)
27366
- return;
27367
- try {
27368
- const record2 = { ...this.context, ...fields };
27369
- if (record2.message)
27370
- record2.message = sanitizeDiagnosticText(redactKnownValues(record2.message, this.sensitiveValues));
27371
- if (record2.errorName)
27372
- record2.errorName = sanitizeDiagnosticText(redactKnownValues(record2.errorName, this.sensitiveValues));
27373
- if ("input" in record2)
27374
- record2.input = sanitizeLogValue(record2.input, this.sensitiveValues);
27375
- if ("output" in record2)
27376
- record2.output = sanitizeLogValue(record2.output, this.sensitiveValues);
27377
- this.sink(JSON.stringify({
27378
- operation: this.operation,
27379
- level: "info",
27380
- layer: this.layer,
27381
- event,
27382
- stage: this.stage,
27383
- ...record2,
27384
- costMs: Math.max(0, Math.round(performance.now() - this.startedAt))
27385
- }), scope);
27386
- } catch {
27387
- }
27388
- }
27389
- error(event, error) {
27390
- if (!this.sink)
27391
- return;
27392
- try {
27393
- this.write(event, {
27394
- errorName: error instanceof Error ? error.name : typeof error,
27395
- message: error instanceof Error ? error.message : typeof error === "string" ? error : "\u975E\u6807\u51C6\u5F02\u5E38"
27396
- });
27397
- } catch {
27398
- }
27399
- }
27400
- };
27401
- function sanitizeLogValue(value, sensitiveValues) {
27402
- const seen = /* @__PURE__ */ new WeakSet();
27403
- let nodes = 200;
27404
- let characters = 4e3;
27405
- const visit = (item, depth, key = "") => {
27406
- if (/authorization|cookie|token|secret|password|api[_-]?key|access[_-]?key|private[_-]?key|^(?:ak|sk|userId|orderId|tradeNO|phone|mobile|email|idCard)$/iu.test(key)) {
27407
- if (typeof item === "string" && item)
27408
- sensitiveValues.add(item);
27409
- return "<redacted>";
27410
- }
27411
- if (--nodes < 0 || depth > 8 || characters <= 0)
27412
- return "<truncated>";
27413
- if (item === null || typeof item === "number" || typeof item === "boolean")
27414
- return item;
27415
- if (typeof item === "string") {
27416
- if (/^\s*[{[]/u.test(item)) {
27417
- if (item.length > 16e3)
27418
- return "<truncated JSON>";
27419
- try {
27420
- return JSON.stringify(visit(JSON.parse(item), depth + 1));
27421
- } catch {
27422
- return "<invalid JSON>";
27423
- }
27424
- }
27425
- const text2 = sanitizeDiagnosticText(redactKnownValues(item, sensitiveValues));
27426
- const result2 = text2.slice(0, Math.min(512, characters));
27427
- characters -= result2.length;
27428
- return result2.length < item.length ? `${result2}<truncated>` : result2;
27429
- }
27430
- if (typeof item !== "object")
27431
- return `<${typeof item}>`;
27432
- if (seen.has(item))
27433
- return "<circular>";
27434
- seen.add(item);
27435
- try {
27436
- const keys = Object.keys(item);
27437
- const result2 = /* @__PURE__ */ Object.create(null);
27438
- for (const name of keys.slice(0, 20)) {
27439
- const descriptor = Object.getOwnPropertyDescriptor(item, name);
27440
- if (name === "value" && Object.getOwnPropertyDescriptor(item, "kind")?.value === "literal" && typeof descriptor?.value === "string" && descriptor.value)
27441
- sensitiveValues.add(descriptor.value);
27442
- result2[name.slice(0, 100)] = name === "value" && Object.getOwnPropertyDescriptor(item, "kind")?.value === "literal" ? "<redacted>" : descriptor && "value" in descriptor ? visit(descriptor.value, depth + 1, name) : "<accessor>";
27443
- }
27444
- if (Array.isArray(item)) {
27445
- const values = Object.values(result2);
27446
- if (keys.length > 20)
27447
- values.push("<truncated>");
27448
- return values;
27449
- }
27450
- if (keys.length > 20)
27451
- result2["<truncated>"] = true;
27452
- return result2;
27453
- } catch {
27454
- return "<unreadable>";
27455
- } finally {
27456
- seen.delete(item);
27457
- }
27458
- };
27459
- const result = visit(value, 0);
27460
- const text = JSON.stringify(result);
27461
- return text.length > 6e3 ? { truncated: true, preview: text.slice(0, 2e3) } : result;
27462
- }
27463
- function sanitizeDiagnosticText(value) {
27464
- return value.replace(/\b(?:body|arguments|payload|headers)\s*[:=][\s\S]*/giu, "<payload>").replace(/\{[\s\S]*/gu, "<payload>").replace(/https?:\/\/[^\s]+/giu, "<url>").replace(/\b(?:authorization|cookie|set-cookie)\s*[:=][^\r\n]*/giu, "<redacted>").replace(/\bbearer\s+[^\s,;]+/giu, "Bearer <redacted>").replace(/\b((?:api[_-]?key|access[_-]?key|token|secret|password|ak|sk|tradeNO|userId|orderId)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu, "$1<redacted>").replace(/\s+/gu, " ").slice(0, 300);
27465
- }
27466
- function redactKnownValues(text, sensitiveValues) {
27467
- let result = text;
27468
- for (const sensitive of sensitiveValues)
27469
- result = result.replaceAll(sensitive, "<redacted>");
27470
- return result;
27471
- }
27472
-
27473
- // ../linkque-agent-runtime/dist/esm/core/cardActionExecutor.js
27474
- async function executeCardAction(input) {
27475
- const diagnostics = new CardActionDiagnostics(input.debugLog, {
27476
- agentId: input.protocol.agentId,
27477
- threadId: input.runtimeContext.threadId
27478
- });
27479
- diagnostics.protect(() => input.runtimeContext.userId);
27480
- diagnostics.protect(() => input.runtimeContext.tenantId);
27481
- diagnostics.write("started", {
27482
- input: { request: input.request, runtimeContext: input.runtimeContext }
27483
- });
27484
- try {
27485
- const response = await executeCardActionInternal(input, diagnostics);
27486
- diagnostics.write(response.ok ? "completed" : "failed", response.ok ? { output: response } : {
27487
- code: response.error.code,
27488
- retryable: response.error.retryable,
27489
- output: response
27490
- });
27491
- return response;
27492
- } catch (error) {
27493
- diagnostics.error("failed", error);
27494
- throw error;
27495
- }
27496
- }
27497
- async function executeCardActionInternal(input, diagnostics) {
27498
- let request;
27499
- try {
27500
- request = parseA2UIActionExecuteRequest(input.request);
27501
- } catch (error) {
27502
- return failure2("INVALID_INPUT", errorMessage(error, "\u652F\u4ED8\u52A8\u4F5C\u8BF7\u6C42\u65E0\u6548"), false);
27503
- }
27504
- Object.assign(diagnostics.context, {
27505
- invocationId: request.invocationId,
27506
- cardRef: request.source.cardRef,
27507
- cardRevision: request.source.cardRevision
27508
- });
27509
- if (request.agentId !== input.protocol.agentId)
27510
- return failure2("AGENT_MISMATCH", "\u652F\u4ED8\u52A8\u4F5C\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
27511
- if (request.threadId !== input.runtimeContext.threadId)
27512
- return failure2("INVALID_INPUT", "\u652F\u4ED8\u52A8\u4F5C\u4E0E\u5F53\u524D\u4F1A\u8BDD\u4E0D\u5339\u914D", false);
27513
- if (!input.runtimeContext.userId.trim())
27514
- return failure2("AUTH_REQUIRED", "\u652F\u4ED8\u52A8\u4F5C\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
27515
- diagnostics.write("validated", { output: request });
27516
- diagnostics.stage = "binding";
27517
- diagnostics.write("binding_started", { input: { source: request.source } });
27518
- const resolved = resolvePaymentAction(input.protocol, request.source);
27519
- if (!resolved.ok) {
27520
- diagnostics.write("binding_failed", { output: resolved.response });
27521
- return resolved.response;
27522
- }
27523
- const args = materializePaymentInput(resolved.payment.createTrade.input, request.input);
27524
- if (!args)
27525
- return failure2("INVALID_INPUT", "\u65E0\u6CD5\u751F\u6210\u521B\u5EFA\u4EA4\u6613 MCP \u5165\u53C2", false);
27526
- const createTrade = resolved.payment.createTrade;
27527
- Object.assign(diagnostics.context, {
27528
- mcpResourceId: createTrade.mcpResourceId,
27529
- toolName: createTrade.toolName
27530
- });
27531
- diagnostics.write("binding_resolved", { output: createTrade });
27532
- diagnostics.stage = "tool_resolve";
27533
- const registry = createRegistry(input.protocol, input.mcpServerProvider, diagnostics.debugLog, input.phoneAuthorization);
27534
- try {
27535
- diagnostics.write("tool_resolve_started", { input: createTrade });
27536
- const tool = await registry.resolve(createTrade.mcpResourceId, createTrade.toolName, input.signal);
27537
- diagnostics.write("tool_resolved", {
27538
- output: {
27539
- found: Boolean(tool),
27540
- inputSchema: tool?.inputSchema,
27541
- outputSchema: tool?.outputSchema
27542
- }
27543
- });
27544
- if (!tool)
27545
- return failure2("TOOL_NOT_ALLOWED", "\u521B\u5EFA\u4EA4\u6613 MCP Tool \u4E0D\u5B58\u5728\u6216\u672A\u6388\u6743", false);
27546
- diagnostics.stage = "tool_input";
27547
- const inputSchema = cloneJsonObject(tool.inputSchema);
27548
- if (inputSchema && validateJsonSchemaValue(inputSchema, args).length > 0) {
27549
- return failure2("INVALID_INPUT", "\u521B\u5EFA\u4EA4\u6613 MCP \u5165\u53C2\u4E0D\u7B26\u5408 Tool Schema", false);
27550
- }
27551
- diagnostics.write("tool_input_completed", { output: { args } });
27552
- let result;
27553
- diagnostics.stage = "tool_execute";
27554
- diagnostics.write("tool_started", { input: args });
27555
- try {
27556
- result = await tool.execute(args, input.signal);
27557
- diagnostics.protect(() => readJsonPointer(readStructuredContent3(result), createTrade.tradeNoPath));
27558
- diagnostics.write("tool_completed", { output: result });
27559
- } catch (error) {
27560
- diagnostics.error("tool_failed", error);
27561
- if (isMcpPhoneAuthorizationError(error))
27562
- throw error;
27563
- return failure2("EXECUTION_FAILED", "\u521B\u5EFA\u4EA4\u6613\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5", true);
27564
- }
27565
- diagnostics.stage = "tool_output";
27566
28130
  const structured = readStructuredContent3(result);
27567
- const tradeNO = readJsonPointer(structured, createTrade.tradeNoPath);
27568
- diagnostics.write("tool_output_completed", {
27569
- output: {
27570
- structured,
27571
- tradeNO,
27572
- valid: typeof tradeNO === "string" && Boolean(tradeNO.trim()) && tradeNO.length <= 64
27573
- }
27574
- });
27575
- if (typeof tradeNO !== "string" || !tradeNO.trim() || tradeNO.length > 64)
27576
- return failure2("INVALID_OUTPUT", "\u521B\u5EFA\u4EA4\u6613 MCP \u672A\u8FD4\u56DE\u6709\u6548 tradeNO", false);
27577
- return {
27578
- ok: true,
27579
- invocationId: request.invocationId,
27580
- result: { kind: "payment", tradeNO }
27581
- };
27582
- } finally {
27583
- const stage = diagnostics.stage;
27584
- diagnostics.stage = "cleanup";
27585
- diagnostics.write("cleanup_started", {
27586
- input: { mcpResourceId: diagnostics.context.mcpResourceId }
27587
- });
27588
- await registry.closeAll();
27589
- diagnostics.write("cleanup_completed", {
27590
- output: { closeAttempted: true }
27591
- });
27592
- diagnostics.stage = stage;
27593
- }
27594
- }
27595
- function resolvePaymentAction(protocol, source) {
27596
- const card = protocol.agent.resources.find((resource) => resource.resourceType === EResourceType.CARD && resource.resourceId === source.cardRef);
27597
- if (!card)
27598
- return {
27599
- ok: false,
27600
- response: failure2("CARD_NOT_FOUND", "\u652F\u4ED8\u5361\u7247\u4E0D\u5B58\u5728", false)
27601
- };
27602
- if (card.config.revision !== source.cardRevision) {
27603
- return {
27604
- ok: false,
27605
- response: failure2("CARD_REVISION_MISMATCH", "\u652F\u4ED8\u5361\u7247\u7248\u672C\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5", false)
27606
- };
27607
- }
27608
- if (card.config.schemaVersion !== "4")
27609
- return {
27610
- ok: false,
27611
- response: failure2("ACTION_NOT_FOUND", "\u652F\u4ED8\u52A8\u4F5C\u4E0D\u5B58\u5728", false)
27612
- };
27613
- const component = findSavedComponent(card.config.a2uiTemplate.content, source.surfaceId, source.componentId);
27614
- if (!component)
27615
- return {
27616
- ok: false,
27617
- response: failure2("ACTION_NOT_FOUND", "\u652F\u4ED8\u52A8\u4F5C\u4E0D\u5B58\u5728", false)
27618
- };
27619
- const payments = collectPaymentActions(component.action);
27620
- if (payments.length !== 1)
27621
- return {
27622
- ok: false,
27623
- response: failure2("ACTION_KIND_MISMATCH", "\u7EC4\u4EF6\u5FC5\u987B\u5305\u542B\u552F\u4E00\u652F\u4ED8\u52A8\u4F5C", false)
27624
- };
27625
- return { ok: true, payment: payments[0] };
27626
- }
27627
- function findSavedComponent(content, surfaceId, componentId) {
27628
- let parsed;
27629
- try {
27630
- parsed = JSON.parse(content);
27631
- } catch {
27632
- return void 0;
27633
- }
27634
- if (!Array.isArray(parsed))
27635
- return void 0;
27636
- const instructions = parsed.flatMap((entry) => {
27637
- const record2 = cloneJsonObject(entry);
27638
- return record2 && Array.isArray(record2.datas) ? record2.datas : [entry];
27639
- });
27640
- for (const instruction of instructions) {
27641
- const record2 = cloneJsonObject(instruction);
27642
- const update = record2 && cloneJsonObject(record2.updateComponents);
27643
- if (!update || update.surfaceId !== surfaceId || !Array.isArray(update.components))
27644
- continue;
27645
- const component = update.components.find((candidate) => {
27646
- const item = cloneJsonObject(candidate);
27647
- return item?.id === componentId;
27648
- });
27649
- const result = cloneJsonObject(component);
27650
- if (result)
27651
- return result;
27652
- }
27653
- return void 0;
27654
- }
27655
- function collectPaymentActions(value) {
27656
- const action = cloneJsonObject(value);
27657
- if (!action)
27658
- return [];
27659
- const client = cloneJsonObject(action.client);
27660
- if (client?.name === "payment.trade-pay") {
27661
- const context2 = cloneJsonObject(client.context);
27662
- return context2 ? [context2] : [];
27663
- }
27664
- const select = cloneJsonObject(action.select);
27665
- if (!select)
27666
- return [];
27667
- const cases = Array.isArray(select.cases) ? select.cases : [];
27668
- return [
27669
- ...cases.flatMap((entry) => collectPaymentActions(cloneJsonObject(entry)?.action)),
27670
- ...collectPaymentActions(select.default)
27671
- ];
27672
- }
27673
- function materializePaymentInput(definition, supplied) {
27674
- const materialized = materializeValue(definition, supplied);
27675
- return cloneJsonObject(materialized);
27676
- }
27677
- function materializeValue(definition, supplied) {
27678
- if (Array.isArray(definition)) {
27679
- if (!Array.isArray(supplied) || supplied.length !== definition.length)
27680
- return void 0;
27681
- const result = definition.map((entry, index) => materializeValue(entry, supplied[index]));
27682
- return result.some((entry) => entry === void 0) ? void 0 : result;
27683
- }
27684
- if (definition && typeof definition === "object") {
27685
- const keys = Object.keys(definition);
27686
- if (keys.length === 1 && keys[0] === "path" && typeof definition.path === "string")
27687
- return supplied;
27688
- const suppliedObject = cloneJsonObject(supplied);
27689
- if (!suppliedObject)
27690
- return void 0;
27691
- const result = {};
27692
- for (const [key, entry] of Object.entries(definition)) {
27693
- const value = materializeValue(entry, suppliedObject[key]);
27694
- if (value === void 0)
27695
- return void 0;
27696
- result[key] = value;
27697
- }
27698
- return result;
27699
- }
27700
- return definition;
27701
- }
27702
- function createRegistry(protocol, provider, debugLog, phoneAuthorization) {
27703
- const resources = protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL);
27704
- return new McpProxyTool(provider, aggregateMcpServers(resources, protocol.agentId), {
27705
- debugLog,
27706
- authorizeCall: createRequestMcpPhoneAuthorizer(protocol, phoneAuthorization)
27707
- });
27708
- }
27709
- function readStructuredContent3(result) {
27710
- const object3 = cloneJsonObject(result);
27711
- if (!object3)
27712
- return void 0;
27713
- if (cloneJsonObject(object3.structuredContent))
27714
- return object3.structuredContent;
27715
- if (!Array.isArray(object3.content) || object3.content.length !== 1)
27716
- return void 0;
27717
- const content = cloneJsonObject(object3.content[0]);
27718
- if (!content || content.type !== "text" || typeof content.text !== "string")
27719
- return void 0;
27720
- try {
27721
- return JSON.parse(content.text);
27722
- } catch {
27723
- return void 0;
27724
- }
27725
- }
27726
- function failure2(code, message, retryable) {
27727
- return { ok: false, error: { code, message, retryable } };
27728
- }
27729
- function errorMessage(error, fallback) {
27730
- return error instanceof Error && error.message.trim() ? error.message : fallback;
27731
- }
27732
-
27733
- // ../linkque-agent-runtime/dist/esm/core/mcpExecution.js
27734
- async function executeAuthorizedMcp(input) {
27735
- if (input.agentId !== input.protocol.agentId)
27736
- return failure3("AGENT_MISMATCH", "\u8BF7\u6C42\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
27737
- if (!input.userId.trim())
27738
- return failure3("AUTH_REQUIRED", "\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
27739
- const resources = input.protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL);
27740
- const registry = new McpProxyTool(input.mcpServerProvider, aggregateMcpServers(resources, input.protocol.agentId), {
27741
- authorizeCall: createRequestMcpPhoneAuthorizer(input.protocol, input.phoneAuthorization)
27742
- });
27743
- try {
27744
- const tool = await registry.resolve(input.tool.mcpResourceId, input.tool.toolName, input.signal);
27745
- if (!tool)
27746
- return failure3("TOOL_NOT_ALLOWED", "MCP Tool \u4E0D\u5B58\u5728\u6216\u672A\u6388\u6743", false);
27747
- const schema = cloneJsonObject(tool.inputSchema);
27748
- if (schema && validateJsonSchemaValue(schema, input.tool.input).length > 0) {
27749
- return failure3("INVALID_INPUT", "MCP \u5165\u53C2\u4E0D\u7B26\u5408 Tool Schema", false);
27750
- }
27751
- let result;
27752
- try {
27753
- result = await tool.execute(input.tool.input, input.signal);
27754
- } catch (error) {
27755
- if (isMcpPhoneAuthorizationError(error))
27756
- throw error;
27757
- return failure3("EXECUTION_UNCERTAIN", "MCP \u6267\u884C\u7ED3\u679C\u4E0D\u786E\u5B9A\uFF0C\u8BF7\u52FF\u81EA\u52A8\u91CD\u8BD5", false);
27758
- }
27759
- const structured = readStructuredContent4(result);
27760
28131
  if (!isJsonValue2(structured)) {
27761
- return failure3("INVALID_OUTPUT", "MCP \u672A\u8FD4\u56DE\u6709\u6548 JSON \u7ED3\u679C", false);
28132
+ return failure2("INVALID_OUTPUT", "MCP \u672A\u8FD4\u56DE\u6709\u6548 JSON \u7ED3\u679C", false);
27762
28133
  }
27763
28134
  return { ok: true, callId: input.callId, result: structured };
27764
28135
  } finally {
27765
28136
  await registry.closeAll();
27766
28137
  }
27767
28138
  }
27768
- function readStructuredContent4(result) {
28139
+ function readStructuredContent3(result) {
27769
28140
  const object3 = cloneJsonObject(result);
27770
28141
  if (!object3)
27771
28142
  return void 0;
@@ -27792,7 +28163,7 @@ function isJsonValue2(value) {
27792
28163
  const object3 = cloneJsonObject(value);
27793
28164
  return Boolean(object3) && Object.values(object3 ?? {}).every(isJsonValue2);
27794
28165
  }
27795
- function failure3(code, message, retryable) {
28166
+ function failure2(code, message, retryable) {
27796
28167
  return { ok: false, error: { code, message, retryable } };
27797
28168
  }
27798
28169
 
@@ -27802,13 +28173,13 @@ async function executeFunctionActionMcp(input) {
27802
28173
  try {
27803
28174
  request = parseA2UIFunctionMcpExecuteRequest(input.request);
27804
28175
  } catch (error) {
27805
- return failure4("INVALID_INPUT", errorMessage2(error, "\u51FD\u6570 MCP \u8BF7\u6C42\u65E0\u6548"), false);
28176
+ return failure3("INVALID_INPUT", errorMessage(error, "\u51FD\u6570 MCP \u8BF7\u6C42\u65E0\u6548"), false);
27806
28177
  }
27807
28178
  if (request.agentId !== input.protocol.agentId) {
27808
- return failure4("AGENT_MISMATCH", "\u51FD\u6570\u52A8\u4F5C\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
28179
+ return failure3("AGENT_MISMATCH", "\u51FD\u6570\u52A8\u4F5C\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
27809
28180
  }
27810
28181
  if (request.threadId !== input.runtimeContext.threadId || !input.runtimeContext.userId.trim()) {
27811
- return failure4("AUTH_REQUIRED", "\u51FD\u6570\u52A8\u4F5C\u7F3A\u5C11\u53EF\u4FE1\u4F1A\u8BDD\u8EAB\u4EFD", false);
28182
+ return failure3("AUTH_REQUIRED", "\u51FD\u6570\u52A8\u4F5C\u7F3A\u5C11\u53EF\u4FE1\u4F1A\u8BDD\u8EAB\u4EFD", false);
27812
28183
  }
27813
28184
  return executeAuthorizedMcp({
27814
28185
  protocol: input.protocol,
@@ -27821,10 +28192,10 @@ async function executeFunctionActionMcp(input) {
27821
28192
  phoneAuthorization: input.phoneAuthorization
27822
28193
  });
27823
28194
  }
27824
- function failure4(code, message, retryable) {
28195
+ function failure3(code, message, retryable) {
27825
28196
  return { ok: false, error: { code, message, retryable } };
27826
28197
  }
27827
- function errorMessage2(error, fallback) {
28198
+ function errorMessage(error, fallback) {
27828
28199
  return error instanceof Error && error.message.trim() ? error.message : fallback;
27829
28200
  }
27830
28201
 
@@ -27920,6 +28291,82 @@ function normalizeHookResources(resources) {
27920
28291
  }).sort((a, b) => (a.config.order ?? 0) - (b.config.order ?? 0));
27921
28292
  }
27922
28293
 
28294
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/observe.js
28295
+ function createObservation(create) {
28296
+ try {
28297
+ const observation = typeof create === "function" ? create() : create.parent?.startOperation(create.operation);
28298
+ if (observation && "find" in observation && "closePending" in observation)
28299
+ return observation;
28300
+ return new RuntimeObservation(observation ?? new NoopRuntimeObservation());
28301
+ } catch {
28302
+ return new RuntimeObservation(new NoopRuntimeObservation());
28303
+ }
28304
+ }
28305
+ function settle(observation, completion, classify) {
28306
+ let result = {
28307
+ outcome: completion.status === "fulfilled" ? ETelemetryOutcome.SUCCESS : completion.status === "returned" ? ETelemetryOutcome.CANCELLED : ETelemetryOutcome.ERROR
28308
+ };
28309
+ try {
28310
+ if (classify) {
28311
+ const classified = classify(completion);
28312
+ result = {
28313
+ outcome: classified.outcome,
28314
+ attributes: classified.attributes
28315
+ };
28316
+ }
28317
+ } catch {
28318
+ }
28319
+ try {
28320
+ observation.finish(result.outcome, result.attributes ?? {});
28321
+ } catch {
28322
+ }
28323
+ }
28324
+ async function observePromise(create, task, classify) {
28325
+ const observation = createObservation(create);
28326
+ let completion = { status: "returned" };
28327
+ try {
28328
+ const value = await task(observation);
28329
+ completion = { status: "fulfilled", value };
28330
+ return value;
28331
+ } catch (error) {
28332
+ completion = { status: "rejected", error };
28333
+ throw error;
28334
+ } finally {
28335
+ settle(observation, completion, classify);
28336
+ }
28337
+ }
28338
+ async function* observeStream(create, source, classify) {
28339
+ const observation = createObservation(create);
28340
+ let completion = { status: "returned" };
28341
+ try {
28342
+ const value = yield* source(observation);
28343
+ completion = { status: "fulfilled", value };
28344
+ return value;
28345
+ } catch (error) {
28346
+ completion = { status: "rejected", error };
28347
+ throw error;
28348
+ } finally {
28349
+ settle(observation, completion, classify);
28350
+ }
28351
+ }
28352
+ function observeEvent(create, subscribe, classify) {
28353
+ return observePromise(create, async (observation) => {
28354
+ const cleanup = {};
28355
+ try {
28356
+ return await new Promise((resolve, reject) => {
28357
+ const unsubscribe = subscribe(observation, resolve, reject);
28358
+ if (unsubscribe)
28359
+ cleanup.unsubscribe = unsubscribe;
28360
+ });
28361
+ } finally {
28362
+ try {
28363
+ cleanup.unsubscribe?.();
28364
+ } catch {
28365
+ }
28366
+ }
28367
+ }, classify);
28368
+ }
28369
+
27923
28370
  // ../linkque-agent-runtime/dist/esm/core/hook/hookDispatcher.js
27924
28371
  import { randomUUID as randomUUID2 } from "node:crypto";
27925
28372
 
@@ -28077,21 +28524,21 @@ var HookDispatcher = class {
28077
28524
  * 触发一个 stage:命中 hook 后按序调度。状态型 hook 必须成功;旁路 hook 立即返回。
28078
28525
  */
28079
28526
  async dispatch(stage, commonParams, subject = {}, runtimeInput, parent = this.deps.observation) {
28080
- const observation = parent?.startOperation({
28527
+ let matched = 0;
28528
+ let scheduled = 0;
28529
+ return observePromise(() => parent?.startOperation({
28081
28530
  name: ETelemetryOperationName.HOOK_CHAIN,
28082
28531
  eventPrefix: ETelemetryEventPrefix.HOOK_CHAIN,
28083
28532
  attributes: { [ETelemetryAttribute.LINKQUE_HOOK_STAGE]: stage },
28084
28533
  detached: false,
28085
28534
  links: []
28086
- });
28087
- let matched = 0;
28088
- let scheduled = 0;
28089
- try {
28535
+ }), async (observation) => {
28090
28536
  const now = this.deps.now ?? Date.now;
28091
28537
  const patches = [];
28092
28538
  for (const resource of this.resources) {
28093
- if (!matchHookResource(resource, stage, subject))
28539
+ if (!matchHookResource(resource, stage, subject)) {
28094
28540
  continue;
28541
+ }
28095
28542
  if (this.deps.hookExecutor.matches?.(resource, stage, subject) === false) {
28096
28543
  continue;
28097
28544
  }
@@ -28119,19 +28566,34 @@ var HookDispatcher = class {
28119
28566
  this.scheduleDetached(resource, context2, observation);
28120
28567
  }
28121
28568
  }
28122
- observation?.finish(ETelemetryOutcome.SUCCESS, {
28123
- [ETelemetryAttribute.LINKQUE_HOOK_MATCHED_COUNT]: matched,
28124
- [ETelemetryAttribute.LINKQUE_HOOK_SCHEDULED_COUNT]: scheduled
28125
- });
28126
28569
  return { patches };
28127
- } catch (error) {
28128
- observation?.finish(ETelemetryOutcome.ERROR, {
28129
- [ETelemetryAttribute.ERROR_TYPE]: ETelemetryErrorType.HOOK_DISPATCH_ERROR,
28130
- [ETelemetryAttribute.LINKQUE_HOOK_MATCHED_COUNT]: matched,
28131
- [ETelemetryAttribute.LINKQUE_HOOK_SCHEDULED_COUNT]: scheduled
28132
- });
28133
- throw error;
28134
- }
28570
+ }, (completion) => {
28571
+ if (completion.status === "fulfilled") {
28572
+ return {
28573
+ outcome: ETelemetryOutcome.SUCCESS,
28574
+ attributes: {
28575
+ [ETelemetryAttribute.LINKQUE_HOOK_MATCHED_COUNT]: matched,
28576
+ [ETelemetryAttribute.LINKQUE_HOOK_SCHEDULED_COUNT]: scheduled
28577
+ }
28578
+ };
28579
+ } else if (completion.status === "rejected") {
28580
+ return {
28581
+ outcome: ETelemetryOutcome.ERROR,
28582
+ attributes: {
28583
+ [ETelemetryAttribute.LINKQUE_HOOK_MATCHED_COUNT]: matched,
28584
+ [ETelemetryAttribute.LINKQUE_HOOK_SCHEDULED_COUNT]: scheduled,
28585
+ [ETelemetryAttribute.ERROR_TYPE]: ETelemetryErrorType.HOOK_DISPATCH_ERROR
28586
+ }
28587
+ };
28588
+ }
28589
+ return {
28590
+ outcome: ETelemetryOutcome.ERROR,
28591
+ attributes: {
28592
+ [ETelemetryAttribute.LINKQUE_HOOK_MATCHED_COUNT]: matched,
28593
+ [ETelemetryAttribute.LINKQUE_HOOK_SCHEDULED_COUNT]: scheduled
28594
+ }
28595
+ };
28596
+ });
28135
28597
  }
28136
28598
  /** 构造 stage-specific context(discriminated union 分支)。 */
28137
28599
  buildContext(resource, stage, commonParams, subject, now) {
@@ -28305,6 +28767,7 @@ var HookDispatcher = class {
28305
28767
  try {
28306
28768
  const timeoutMs = resource.config.timeoutMs ?? 1e3;
28307
28769
  const timeoutReason = new Error(`\u72B6\u6001\u578B Hook ${resource.config.name} \u6267\u884C\u8D85\u65F6(${timeoutMs}ms)`);
28770
+ timeoutReason.name = "TimeoutError";
28308
28771
  const scope = new CancellationScope({
28309
28772
  signals: runtimeInput?.signal ? [runtimeInput.signal] : [],
28310
28773
  timeoutMs,
@@ -28314,7 +28777,7 @@ var HookDispatcher = class {
28314
28777
  let onAbort;
28315
28778
  try {
28316
28779
  scope.context.throwIfAborted();
28317
- observation = parent?.startOperation({
28780
+ const execution = observePromise(() => parent?.startOperation({
28318
28781
  name: ETelemetryOperationName.MIDDLEWARE,
28319
28782
  eventPrefix: ETelemetryEventPrefix.MIDDLEWARE,
28320
28783
  attributes: {
@@ -28327,43 +28790,55 @@ var HookDispatcher = class {
28327
28790
  },
28328
28791
  detached: false,
28329
28792
  links: []
28330
- });
28331
- onAbort = () => {
28332
- timedOut = executorSignal.reason === timeoutReason;
28333
- cancelled = !timedOut;
28334
- observation?.record(timedOut ? ETelemetryEventName.HOOK_TIMEOUT_REQUESTED : ETelemetryEventName.HOOK_CANCEL_REQUESTED, {});
28335
- };
28336
- executorSignal.addEventListener("abort", onAbort, { once: true });
28337
- result = await waitWithSignal(this.deps.hookExecutor.execute(resource, context2, {
28338
- signal: executorSignal,
28339
- ...runtimeInput === void 0 ? {} : { runtimeInput }
28340
- }).then((value) => {
28341
- settled = true;
28342
- observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
28343
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28344
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: value.skipped ? ETelemetryHookResult.SKIPPED : value.ok ? ETelemetryHookResult.SUCCESS : ETelemetryHookResult.ERROR
28345
- });
28346
- if (timedOut || cancelled)
28347
- observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
28348
- [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
28349
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28350
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: value.skipped ? ETelemetryHookResult.SKIPPED : value.ok ? ETelemetryHookResult.SUCCESS : ETelemetryHookResult.ERROR
28793
+ }), async (current) => {
28794
+ observation = current;
28795
+ onAbort = () => {
28796
+ timedOut = executorSignal.reason === timeoutReason;
28797
+ cancelled = !timedOut;
28798
+ observation?.record(timedOut ? ETelemetryEventName.HOOK_TIMEOUT_REQUESTED : ETelemetryEventName.HOOK_CANCEL_REQUESTED, {});
28799
+ };
28800
+ executorSignal.addEventListener("abort", onAbort, { once: true });
28801
+ try {
28802
+ return await this.deps.hookExecutor.execute(resource, context2, {
28803
+ observation: current,
28804
+ signal: executorSignal,
28805
+ ...runtimeInput === void 0 ? {} : { runtimeInput }
28351
28806
  });
28352
- return value;
28353
- }, (error) => {
28354
- settled = true;
28807
+ } finally {
28808
+ settled = true;
28809
+ }
28810
+ }, (completion) => {
28811
+ const value = completion.status === "fulfilled" ? completion.value : void 0;
28812
+ let hookResult = ETelemetryHookResult.ERROR;
28813
+ if (value?.skipped) {
28814
+ hookResult = ETelemetryHookResult.SKIPPED;
28815
+ } else if (value?.ok) {
28816
+ hookResult = ETelemetryHookResult.SUCCESS;
28817
+ }
28355
28818
  observation?.record(ETelemetryEventName.HOOK_EXECUTOR_SETTLED, {
28356
28819
  [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28357
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: ETelemetryHookResult.ERROR
28820
+ [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: hookResult
28358
28821
  });
28359
- if (timedOut || cancelled)
28360
- observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.CANCELLED, {
28361
- [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
28362
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28363
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: ETelemetryHookResult.ERROR
28364
- });
28365
- throw error;
28366
- }), executorSignal);
28822
+ let outcome = ETelemetryOutcome.ERROR;
28823
+ if (timedOut) {
28824
+ outcome = ETelemetryOutcome.TIMEOUT;
28825
+ } else if (cancelled) {
28826
+ outcome = ETelemetryOutcome.CANCELLED;
28827
+ } else if (value?.skipped) {
28828
+ outcome = ETelemetryOutcome.UNKNOWN;
28829
+ } else if (value?.ok) {
28830
+ outcome = ETelemetryOutcome.SUCCESS;
28831
+ }
28832
+ const innerAttributes = {
28833
+ [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true,
28834
+ [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: hookResult
28835
+ };
28836
+ if (timedOut || cancelled || completion.status === "rejected") {
28837
+ innerAttributes[ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY] = ETelemetryObservationBoundary.EXECUTOR_SETTLED;
28838
+ }
28839
+ return { outcome, attributes: innerAttributes };
28840
+ });
28841
+ result = await waitWithSignal(execution, executorSignal);
28367
28842
  } finally {
28368
28843
  if (onAbort !== void 0)
28369
28844
  executorSignal.removeEventListener("abort", onAbort);
@@ -28375,11 +28850,6 @@ var HookDispatcher = class {
28375
28850
  [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.LOCAL_WAIT,
28376
28851
  [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: false
28377
28852
  });
28378
- } else {
28379
- observation?.finish(timedOut ? ETelemetryOutcome.TIMEOUT : cancelled ? ETelemetryOutcome.CANCELLED : ETelemetryOutcome.ERROR, {
28380
- [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.EXECUTOR_SETTLED,
28381
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true
28382
- });
28383
28853
  }
28384
28854
  writeHookLog(this.deps.debugLog, {
28385
28855
  ...baseRecord,
@@ -28395,10 +28865,6 @@ var HookDispatcher = class {
28395
28865
  }));
28396
28866
  throw error;
28397
28867
  }
28398
- observation?.finish(result.skipped ? ETelemetryOutcome.UNKNOWN : result.ok ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.ERROR, {
28399
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: result.skipped ? ETelemetryHookResult.SKIPPED : result.ok ? ETelemetryHookResult.SUCCESS : ETelemetryHookResult.ERROR,
28400
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true
28401
- });
28402
28868
  const costMs = now() - startedAt;
28403
28869
  if (result.skipped) {
28404
28870
  writeHookLog(this.deps.debugLog, {
@@ -28557,7 +29023,8 @@ var SideEffectRunner = class {
28557
29023
  /** 执行单个旁路任务:超时/吞错/日志/指标全收口,永不 reject 到外部。 */
28558
29024
  async runTask(task, signal, isTimedOut) {
28559
29025
  const { resource, context: context2 } = task;
28560
- const observation = task.observation?.startOperation({
29026
+ let startedAt = this.now();
29027
+ const metricResult = await observePromise(() => task.observation?.startOperation({
28561
29028
  name: ETelemetryOperationName.MIDDLEWARE,
28562
29029
  eventPrefix: ETelemetryEventPrefix.MIDDLEWARE,
28563
29030
  detached: true,
@@ -28575,122 +29042,136 @@ var SideEffectRunner = class {
28575
29042
  [ETelemetryAttribute.LINKQUE_HOOK_MODE]: ETelemetryHookMode.DETACHED,
28576
29043
  [ETelemetryAttribute.LINKQUE_HOOK_TIMEOUT_MS]: task.timeoutMs
28577
29044
  }
28578
- });
28579
- const onAbort = () => observation?.record(ETelemetryEventName.HOOK_TIMEOUT_REQUESTED, {});
28580
- signal.addEventListener("abort", onAbort, { once: true });
28581
- const baseRecord = {
28582
- tag: "hook",
28583
- hookId: resource.resourceId,
28584
- hookName: resource.config.name,
28585
- stage: context2.stage,
28586
- providerType: resource.providerType,
28587
- hasSideEffects: resource.config.hasSideEffects,
28588
- eventId: context2.eventId,
28589
- runId: context2.commonParams.runId,
28590
- conversationId: context2.commonParams.conversationId,
28591
- ...context2.commonParams.runIndex !== void 0 && {
28592
- runIndex: context2.commonParams.runIndex
28593
- },
28594
- agentId: context2.commonParams.agentId,
28595
- ...context2.commonParams.sessionId !== void 0 && {
28596
- sessionId: context2.commonParams.sessionId
28597
- },
28598
- ...context2.commonParams.userId !== void 0 && {
28599
- userId: context2.commonParams.userId
28600
- },
28601
- ...context2.commonParams.traceId !== void 0 && {
28602
- traceId: context2.commonParams.traceId
28603
- }
28604
- };
28605
- writeHookLog(this.debugLog, { ...baseRecord, event: "started" });
28606
- const startedAt = this.now();
28607
- let result = "ok";
28608
- try {
28609
- const executeResult = await task.execute(signal);
28610
- const costMs = this.now() - startedAt;
28611
- if (isTimedOut()) {
28612
- result = "timeout";
28613
- writeHookLog(this.debugLog, {
28614
- ...baseRecord,
28615
- event: "timeout",
28616
- timeoutMs: task.timeoutMs,
28617
- costMs,
28618
- result
28619
- });
28620
- } else if (executeResult.skipped) {
28621
- result = "skipped";
28622
- writeHookLog(this.debugLog, {
28623
- ...baseRecord,
28624
- event: "skipped",
28625
- costMs,
28626
- result,
28627
- ...executeResult.code !== void 0 && { code: executeResult.code },
28628
- ...executeResult.message !== void 0 && {
28629
- message: executeResult.message
28630
- }
28631
- });
28632
- } else if (executeResult.ok) {
28633
- writeHookLog(this.debugLog, {
28634
- ...baseRecord,
28635
- event: "completed",
28636
- costMs,
28637
- result
28638
- });
28639
- } else {
28640
- result = "error";
28641
- writeHookLog(this.debugLog, {
28642
- ...baseRecord,
28643
- event: "failed",
28644
- costMs,
28645
- result,
28646
- ...executeResult.code !== void 0 && { code: executeResult.code },
28647
- ...executeResult.retryable !== void 0 && {
28648
- retryable: executeResult.retryable
29045
+ }), async (observation) => {
29046
+ let result = "ok";
29047
+ const onAbort = () => observation?.record(ETelemetryEventName.HOOK_TIMEOUT_REQUESTED, {});
29048
+ signal.addEventListener("abort", onAbort, { once: true });
29049
+ try {
29050
+ const baseRecord = {
29051
+ tag: "hook",
29052
+ hookId: resource.resourceId,
29053
+ hookName: resource.config.name,
29054
+ stage: context2.stage,
29055
+ providerType: resource.providerType,
29056
+ hasSideEffects: resource.config.hasSideEffects,
29057
+ eventId: context2.eventId,
29058
+ runId: context2.commonParams.runId,
29059
+ conversationId: context2.commonParams.conversationId,
29060
+ ...context2.commonParams.runIndex !== void 0 && {
29061
+ runIndex: context2.commonParams.runIndex
29062
+ },
29063
+ agentId: context2.commonParams.agentId,
29064
+ ...context2.commonParams.sessionId !== void 0 && {
29065
+ sessionId: context2.commonParams.sessionId
29066
+ },
29067
+ ...context2.commonParams.userId !== void 0 && {
29068
+ userId: context2.commonParams.userId
28649
29069
  },
28650
- ...executeResult.message !== void 0 && {
28651
- message: executeResult.message
29070
+ ...context2.commonParams.traceId !== void 0 && {
29071
+ traceId: context2.commonParams.traceId
28652
29072
  }
28653
- });
28654
- }
28655
- } catch (error) {
28656
- const costMs = this.now() - startedAt;
28657
- if (isTimedOut()) {
28658
- result = "timeout";
28659
- writeHookLog(this.debugLog, {
28660
- ...baseRecord,
28661
- event: "timeout",
28662
- timeoutMs: task.timeoutMs,
28663
- costMs,
28664
- result
28665
- });
28666
- } else {
28667
- result = "error";
28668
- writeHookLog(this.debugLog, {
28669
- ...baseRecord,
28670
- event: "failed",
28671
- costMs,
28672
- result,
28673
- code: "EXECUTOR_THROW",
28674
- message: error instanceof Error ? error.message : String(error)
28675
- });
29073
+ };
29074
+ writeHookLog(this.debugLog, { ...baseRecord, event: "started" });
29075
+ startedAt = this.now();
29076
+ try {
29077
+ const executeResult = await task.execute(signal);
29078
+ const costMs = this.now() - startedAt;
29079
+ if (isTimedOut()) {
29080
+ result = "timeout";
29081
+ writeHookLog(this.debugLog, {
29082
+ ...baseRecord,
29083
+ event: "timeout",
29084
+ timeoutMs: task.timeoutMs,
29085
+ costMs,
29086
+ result
29087
+ });
29088
+ } else if (executeResult.skipped) {
29089
+ result = "skipped";
29090
+ writeHookLog(this.debugLog, {
29091
+ ...baseRecord,
29092
+ event: "skipped",
29093
+ costMs,
29094
+ result,
29095
+ ...executeResult.code !== void 0 && {
29096
+ code: executeResult.code
29097
+ },
29098
+ ...executeResult.message !== void 0 && {
29099
+ message: executeResult.message
29100
+ }
29101
+ });
29102
+ } else if (executeResult.ok) {
29103
+ writeHookLog(this.debugLog, {
29104
+ ...baseRecord,
29105
+ event: "completed",
29106
+ costMs,
29107
+ result
29108
+ });
29109
+ } else {
29110
+ result = "error";
29111
+ writeHookLog(this.debugLog, {
29112
+ ...baseRecord,
29113
+ event: "failed",
29114
+ costMs,
29115
+ result,
29116
+ ...executeResult.code !== void 0 && {
29117
+ code: executeResult.code
29118
+ },
29119
+ ...executeResult.retryable !== void 0 && {
29120
+ retryable: executeResult.retryable
29121
+ },
29122
+ ...executeResult.message !== void 0 && {
29123
+ message: executeResult.message
29124
+ }
29125
+ });
29126
+ }
29127
+ } catch (error) {
29128
+ const costMs = this.now() - startedAt;
29129
+ if (isTimedOut()) {
29130
+ result = "timeout";
29131
+ writeHookLog(this.debugLog, {
29132
+ ...baseRecord,
29133
+ event: "timeout",
29134
+ timeoutMs: task.timeoutMs,
29135
+ costMs,
29136
+ result
29137
+ });
29138
+ } else {
29139
+ result = "error";
29140
+ writeHookLog(this.debugLog, {
29141
+ ...baseRecord,
29142
+ event: "failed",
29143
+ costMs,
29144
+ result,
29145
+ code: "EXECUTOR_THROW",
29146
+ message: error instanceof Error ? error.message : String(error)
29147
+ });
29148
+ }
29149
+ }
29150
+ } finally {
29151
+ signal.removeEventListener("abort", onAbort);
28676
29152
  }
28677
- }
28678
- signal.removeEventListener("abort", onAbort);
28679
- observation?.finish(result === ETelemetryHookResult.OK ? ETelemetryOutcome.SUCCESS : result === ETelemetryHookResult.SKIPPED ? ETelemetryOutcome.UNKNOWN : result === ETelemetryHookResult.TIMEOUT ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.ERROR, {
28680
- [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: result,
28681
- [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true
29153
+ return result;
29154
+ }, (completion) => {
29155
+ const result = completion.status === "fulfilled" ? completion.value : "error";
29156
+ return {
29157
+ outcome: completion.status === "rejected" ? ETelemetryOutcome.ERROR : result === ETelemetryHookResult.OK ? ETelemetryOutcome.SUCCESS : result === ETelemetryHookResult.SKIPPED ? ETelemetryOutcome.UNKNOWN : result === ETelemetryHookResult.TIMEOUT ? ETelemetryOutcome.TIMEOUT : ETelemetryOutcome.ERROR,
29158
+ attributes: {
29159
+ [ETelemetryAttribute.LINKQUE_HOOK_RESULT]: result,
29160
+ [ETelemetryAttribute.LINKQUE_HOOK_EXECUTOR_SETTLED]: true
29161
+ }
29162
+ };
28682
29163
  });
28683
29164
  const labels = hookMetricLabels(resource, context2.commonParams);
28684
29165
  this.metricsSink?.increment(HOOK_METRIC.EXECUTE_TOTAL, {
28685
29166
  ...labels,
28686
29167
  sideEffect: 1,
28687
- result
29168
+ result: metricResult
28688
29169
  });
28689
- this.metricsSink?.histogram(HOOK_METRIC.DURATION_MS, this.now() - startedAt, { ...labels, result });
28690
- if (result === "timeout") {
29170
+ this.metricsSink?.histogram(HOOK_METRIC.DURATION_MS, this.now() - startedAt, { ...labels, result: metricResult });
29171
+ if (metricResult === "timeout") {
28691
29172
  this.metricsSink?.increment(HOOK_METRIC.TIMEOUT_TOTAL, labels);
28692
29173
  }
28693
- if (result === "skipped") {
29174
+ if (metricResult === "skipped") {
28694
29175
  this.metricsSink?.increment(HOOK_METRIC.SKIPPED_TOTAL, {
28695
29176
  ...labels,
28696
29177
  reason: "executor_skipped"
@@ -28795,6 +29276,7 @@ var LINKQUE_ENDPOINT_PROD = "https://linkquegw.alipay.com";
28795
29276
  var RUNTIME_CONFIG_DEFAULTS = Object.freeze({
28796
29277
  LINKQUE_BASE_URL: `${LINKQUE_ENDPOINT_PROD}/api/anthropic`,
28797
29278
  LINKQUEGW_KNOWLEDGE_BASE_URL: LINKQUE_ENDPOINT_PROD,
29279
+ LINKQUEGW_SKILL_LOADER_BASE_URL: LINKQUE_ENDPOINT_PROD,
28798
29280
  LINKQUEGW_WEB_SEARCH_BASE_URL: LINKQUE_ENDPOINT_PROD,
28799
29281
  LINKQUEGW_EVENT_BASE_URL: LINKQUE_ENDPOINT_PROD,
28800
29282
  LINKQUEGW_MCP_SIGN_ENDPOINT: `${LINKQUE_ENDPOINT_PROD}/api/mcp/signature`,
@@ -29305,9 +29787,6 @@ function throwIfWebSearchAborted(signal) {
29305
29787
  if (signal?.aborted)
29306
29788
  throw new DOMException("\u5168\u7F51\u641C\u7D22\u5DF2\u53D6\u6D88", "AbortError");
29307
29789
  }
29308
- async function awaitWebSearchOperation(operation, signal) {
29309
- return waitWithSignal(operation, signal);
29310
- }
29311
29790
 
29312
29791
  // ../linkque-agent-runtime/dist/esm/core/webSearchResource.js
29313
29792
  function resolveWebSearchResource(resources) {
@@ -29352,7 +29831,7 @@ function createWebSearchTool(resource, searchPort, agentId, debugLog) {
29352
29831
  annotations: { readOnlyHint: true },
29353
29832
  execute: search3
29354
29833
  };
29355
- async function search3(args, signal) {
29834
+ async function search3(args, signal, context2) {
29356
29835
  const startedAt = Date.now();
29357
29836
  let query = "";
29358
29837
  let outcome = "success";
@@ -29361,7 +29840,7 @@ function createWebSearchTool(resource, searchPort, agentId, debugLog) {
29361
29840
  throwIfWebSearchAborted(signal);
29362
29841
  const parsed = parseWebSearchArgs(args);
29363
29842
  query = parsed.query;
29364
- const result = await awaitWebSearchOperation(() => searchPort.search({ agentId, ...parsed }, signal), signal);
29843
+ const result = await waitWithSignal(() => searchPort.search({ agentId, ...parsed }, signal, context2?.observation), signal);
29365
29844
  throwIfWebSearchAborted(signal);
29366
29845
  count = result.items.length;
29367
29846
  return result;
@@ -29370,19 +29849,18 @@ function createWebSearchTool(resource, searchPort, agentId, debugLog) {
29370
29849
  outcome = "cancelled";
29371
29850
  throw new DOMException("\u5168\u7F51\u641C\u7D22\u5DF2\u53D6\u6D88", "AbortError");
29372
29851
  }
29373
- const failure5 = toWebSearchFailure(error);
29374
- outcome = failure5.code;
29375
- return { query, items: [], error: failure5 };
29852
+ const failure4 = toWebSearchFailure(error);
29853
+ outcome = failure4.code;
29854
+ return { query, items: [], error: failure4 };
29376
29855
  } finally {
29377
- try {
29856
+ skipError(() => {
29378
29857
  debugLog?.(JSON.stringify({
29379
29858
  tag: "web-search-tool",
29380
29859
  outcome,
29381
29860
  count,
29382
29861
  durationMs: Date.now() - startedAt
29383
29862
  }), EDebugLogScope.MCP);
29384
- } catch {
29385
- }
29863
+ });
29386
29864
  }
29387
29865
  }
29388
29866
  }
@@ -29501,7 +29979,7 @@ function createKnowledgeTools(resources, searchPort, agentId) {
29501
29979
  knowledgeBaseId: parsed.knowledgeBaseId,
29502
29980
  agentId,
29503
29981
  topK: parsed.topK
29504
- }, signal);
29982
+ }, signal, obs);
29505
29983
  recordContentSection(obs, ETelemetryContentSection.KNOWLEDGE_OUTPUT, {
29506
29984
  status: result.hits.length ? "matched" : "no_hits",
29507
29985
  hits: result.hits
@@ -29519,174 +29997,61 @@ function createKnowledgeTools(resources, searchPort, agentId) {
29519
29997
  }
29520
29998
  }
29521
29999
  async function getKnowledgeBases() {
29522
- if (!cachedKnowledgeBases) {
29523
- cachedKnowledgeBases = await searchPort.listKnowledgeBases(resources);
29524
- }
29525
- return cachedKnowledgeBases;
29526
- }
29527
- }
29528
-
29529
- // ../linkque-agent-runtime/dist/esm/core/noopWebSearchPort.js
29530
- var NoopWebSearchPort = class {
29531
- async search(_input, signal) {
29532
- throwIfWebSearchAborted(signal);
29533
- throw new WebSearchError("WEB_SEARCH_UNAVAILABLE");
29534
- }
29535
- };
29536
-
29537
- // ../linkque-agent-runtime/dist/esm/core/telemetry/noopRuntimeTelemetry.js
29538
- var NoopRuntimeObservation = class {
29539
- enabled = false;
29540
- operationId = "";
29541
- spanContext = null;
29542
- startOperation(_operation) {
29543
- return this;
29544
- }
29545
- record(_name, _attributes, _body) {
29546
- }
29547
- finish(_outcome, _attributes) {
29548
- }
29549
- abandon(_reason) {
29550
- }
29551
- };
29552
- var NoopRuntimeTelemetry = class {
29553
- startAdvance(_input) {
29554
- return new NoopRuntimeObservation();
29555
- }
29556
- async forceFlush(_options) {
29557
- return { completed: true, pendingCount: 0, sentCount: 0, droppedCount: 0 };
29558
- }
29559
- shutdown(options) {
29560
- return this.forceFlush(options);
29561
- }
29562
- };
29563
-
29564
- // ../linkque-agent-runtime/dist/esm/core/telemetry/runtimeObservation.js
29565
- var RuntimeObservation = class _RuntimeObservation {
29566
- sink;
29567
- associations;
29568
- key;
29569
- scope;
29570
- finished = false;
29571
- abandoned = false;
29572
- resultAttributes = {};
29573
- constructor(sink, associations = /* @__PURE__ */ new Map(), key, scope = {
29574
- active: /* @__PURE__ */ new Set(),
29575
- abandoned: false
29576
- }) {
29577
- this.sink = sink;
29578
- this.associations = associations;
29579
- this.key = key;
29580
- this.scope = scope;
29581
- }
29582
- get enabled() {
29583
- try {
29584
- return this.sink.enabled;
29585
- } catch {
29586
- return false;
29587
- }
29588
- }
29589
- get operationId() {
29590
- try {
29591
- return this.sink.operationId;
29592
- } catch {
29593
- return "";
29594
- }
29595
- }
29596
- get spanContext() {
29597
- try {
29598
- return this.sink.spanContext;
29599
- } catch {
29600
- return null;
29601
- }
29602
- }
29603
- startOperation(operation, key) {
29604
- if (this.scope.abandoned)
29605
- return new _RuntimeObservation(new NoopRuntimeObservation());
29606
- if (this.scope.active.size >= 4096) {
29607
- this.record(ETelemetryEventName.OPERATION_OBSERVATION_LOST, {
29608
- [ETelemetryAttribute.LINKQUE_TELEMETRY_LOSS_REASON]: ETelemetryLossReason.ACTIVE_LIMIT
29609
- });
29610
- return new _RuntimeObservation(new NoopRuntimeObservation());
29611
- }
29612
- let sink = new NoopRuntimeObservation();
29613
- try {
29614
- if (this.enabled)
29615
- sink = this.sink.startOperation(operation);
29616
- } catch {
30000
+ if (!cachedKnowledgeBases) {
30001
+ cachedKnowledgeBases = await searchPort.listKnowledgeBases(resources);
29617
30002
  }
29618
- const child = new _RuntimeObservation(sink, this.associations, key, this.scope);
29619
- if (child.enabled)
29620
- this.scope.active.add(child);
29621
- if (key && child.enabled && this.associations.size < 4096)
29622
- this.associations.set(key, child);
29623
- return child;
30003
+ return cachedKnowledgeBases;
29624
30004
  }
29625
- find(key) {
29626
- return this.associations.get(key);
30005
+ }
30006
+
30007
+ // ../linkque-agent-runtime/dist/esm/core/noopWebSearchPort.js
30008
+ var NoopWebSearchPort = class {
30009
+ async search(_input, signal) {
30010
+ throwIfWebSearchAborted(signal);
30011
+ throw new WebSearchError("WEB_SEARCH_UNAVAILABLE");
29627
30012
  }
29628
- record(name, attributes, body) {
29629
- if (this.abandoned)
30013
+ };
30014
+
30015
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/eventObservationRegistry.js
30016
+ var EventObservationRegistry = class {
30017
+ events = /* @__PURE__ */ new WeakMap();
30018
+ parents = /* @__PURE__ */ new Map();
30019
+ closed = false;
30020
+ associate(event, observation) {
30021
+ if (this.closed || !observation)
29630
30022
  return;
29631
- try {
29632
- if (attributes[ETelemetryAttribute.LINKQUE_TOOL_FAILURE_STAGE])
29633
- this.resultAttributes = {
29634
- [ETelemetryAttribute.LINKQUE_TOOL_FAILURE_STAGE]: attributes[ETelemetryAttribute.LINKQUE_TOOL_FAILURE_STAGE]
29635
- };
29636
- this.sink.record(name, attributes, body);
29637
- } catch {
29638
- }
29639
- }
29640
- finish(outcome, attributes) {
29641
- if (this.finished)
30023
+ const safe = new RuntimeObservation(observation);
30024
+ const key = safe.operationId;
30025
+ if (!key)
29642
30026
  return;
29643
- this.finished = true;
29644
- this.scope.active.delete(this);
29645
- if (this.key && this.associations.get(this.key) === this)
29646
- this.associations.delete(this.key);
29647
- try {
29648
- this.sink.finish(outcome, { ...this.resultAttributes, ...attributes });
29649
- } catch {
30027
+ let parent = this.parents.get(key);
30028
+ if (!parent && this.parents.size < 4096) {
30029
+ parent = safe.captureParent();
30030
+ if (!parent.spanContext) {
30031
+ parent.release();
30032
+ return;
30033
+ }
30034
+ this.parents.set(key, parent);
29650
30035
  }
30036
+ if (parent)
30037
+ this.events.set(event, parent);
29651
30038
  }
29652
- abandon(reason) {
29653
- if (this.finished)
29654
- return;
29655
- this.finished = true;
29656
- this.abandoned = true;
29657
- this.scope.active.delete(this);
29658
- if (this.key && this.associations.get(this.key) === this)
29659
- this.associations.delete(this.key);
29660
- try {
29661
- this.sink.abandon(reason);
29662
- } catch {
29663
- }
30039
+ get(event) {
30040
+ return this.events.get(event);
29664
30041
  }
29665
- /** 包含无关联键及旁路操作,仅回收本次 advance 的观察资源。 */
29666
- abandonPending(reason) {
29667
- this.scope.abandoned = true;
29668
- for (const operation of this.scope.active)
29669
- operation.abandon(reason);
29670
- this.associations.clear();
30042
+ transfer(from, to) {
30043
+ const parent = this.get(from);
30044
+ if (!this.closed && parent)
30045
+ this.events.set(to, parent);
29671
30046
  }
29672
- /** 仅结束仍由本地消费方拥有的观察,旁路任务不注册到此表。 */
29673
- closePending() {
29674
- for (const operation of this.associations.values()) {
29675
- operation.finish(ETelemetryOutcome.UNKNOWN, {
29676
- [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.LOCAL_WAIT,
29677
- [ETelemetryAttribute.HARNESS_REMOTE_COMPLETION]: ETelemetryRemoteCompletion.UNKNOWN
29678
- });
29679
- }
29680
- this.associations.clear();
30047
+ close() {
30048
+ this.closed = true;
30049
+ for (const parent of this.parents.values())
30050
+ parent.release();
30051
+ this.parents.clear();
30052
+ this.events = /* @__PURE__ */ new WeakMap();
29681
30053
  }
29682
30054
  };
29683
- function startRuntimeObservation(telemetry, input) {
29684
- try {
29685
- return new RuntimeObservation(telemetry.startAdvance(input));
29686
- } catch {
29687
- return new RuntimeObservation(new NoopRuntimeObservation());
29688
- }
29689
- }
29690
30055
 
29691
30056
  // ../agent-conversation-contract/dist/esm/version.js
29692
30057
  var CONVERSATION_PROTOCOL_VERSION = "1.0";
@@ -30442,10 +30807,6 @@ function createConversationCustomEvent(name, value, fields = {}) {
30442
30807
  }
30443
30808
 
30444
30809
  // ../agent-conversation-contract/dist/esm/run.js
30445
- var CONVERSATION_CLIENT_CAPABILITIES = [
30446
- "location",
30447
- "userInfo"
30448
- ];
30449
30810
  var ConversationProtocolValidationError = class extends Error {
30450
30811
  issues;
30451
30812
  code = "CONVERSATION_PROTOCOL_INVALID";
@@ -30490,8 +30851,8 @@ function getConversationRunRequestIssues(value) {
30490
30851
  if (value.clientCapabilities !== void 0) {
30491
30852
  if (!Array.isArray(value.clientCapabilities)) {
30492
30853
  issues.push("clientCapabilities must be an array when provided");
30493
- } else if (!value.clientCapabilities.every((capability) => CONVERSATION_CLIENT_CAPABILITIES.includes(capability))) {
30494
- issues.push("clientCapabilities contains an unsupported capability");
30854
+ } else if (!value.clientCapabilities.every(isNonEmptyString2)) {
30855
+ issues.push("clientCapabilities must contain non-empty strings");
30495
30856
  }
30496
30857
  }
30497
30858
  if (value.executionScope !== void 0 && value.executionScope !== "presentation") {
@@ -32499,8 +32860,8 @@ var Protocol = class {
32499
32860
  if (queuedMessage.type === "response") {
32500
32861
  resolver(message);
32501
32862
  } else {
32502
- const errorMessage3 = message;
32503
- const error = new McpError(errorMessage3.error.code, errorMessage3.error.message, errorMessage3.error.data);
32863
+ const errorMessage2 = message;
32864
+ const error = new McpError(errorMessage2.error.code, errorMessage2.error.message, errorMessage2.error.data);
32504
32865
  resolver(error);
32505
32866
  }
32506
32867
  } else {
@@ -33786,8 +34147,8 @@ var Client = class extends Protocol {
33786
34147
  const wrappedHandler = async (request, extra) => {
33787
34148
  const validatedRequest = safeParse2(ElicitRequestSchema, request);
33788
34149
  if (!validatedRequest.success) {
33789
- const errorMessage3 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
33790
- throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage3}`);
34150
+ const errorMessage2 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
34151
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage2}`);
33791
34152
  }
33792
34153
  const { params } = validatedRequest.data;
33793
34154
  params.mode = params.mode ?? "form";
@@ -33802,15 +34163,15 @@ var Client = class extends Protocol {
33802
34163
  if (params.task) {
33803
34164
  const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
33804
34165
  if (!taskValidationResult.success) {
33805
- const errorMessage3 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
33806
- throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage3}`);
34166
+ const errorMessage2 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
34167
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage2}`);
33807
34168
  }
33808
34169
  return taskValidationResult.data;
33809
34170
  }
33810
34171
  const validationResult = safeParse2(ElicitResultSchema, result);
33811
34172
  if (!validationResult.success) {
33812
- const errorMessage3 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
33813
- throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage3}`);
34173
+ const errorMessage2 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
34174
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage2}`);
33814
34175
  }
33815
34176
  const validatedResult = validationResult.data;
33816
34177
  const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
@@ -33830,16 +34191,16 @@ var Client = class extends Protocol {
33830
34191
  const wrappedHandler = async (request, extra) => {
33831
34192
  const validatedRequest = safeParse2(CreateMessageRequestSchema, request);
33832
34193
  if (!validatedRequest.success) {
33833
- const errorMessage3 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
33834
- throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage3}`);
34194
+ const errorMessage2 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
34195
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage2}`);
33835
34196
  }
33836
34197
  const { params } = validatedRequest.data;
33837
34198
  const result = await Promise.resolve(handler(request, extra));
33838
34199
  if (params.task) {
33839
34200
  const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
33840
34201
  if (!taskValidationResult.success) {
33841
- const errorMessage3 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
33842
- throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage3}`);
34202
+ const errorMessage2 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
34203
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage2}`);
33843
34204
  }
33844
34205
  return taskValidationResult.data;
33845
34206
  }
@@ -33847,8 +34208,8 @@ var Client = class extends Protocol {
33847
34208
  const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
33848
34209
  const validationResult = safeParse2(resultSchema, result);
33849
34210
  if (!validationResult.success) {
33850
- const errorMessage3 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
33851
- throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage3}`);
34211
+ const errorMessage2 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
34212
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage2}`);
33852
34213
  }
33853
34214
  return validationResult.data;
33854
34215
  };
@@ -34198,7 +34559,7 @@ async function connectMcpClientWithRetry(config, factories, signal) {
34198
34559
  let closing;
34199
34560
  const close = () => closing ??= safeClose(transport, client);
34200
34561
  try {
34201
- const connecting = client.connect(transport).then(() => {
34562
+ const connecting = (factories.runConnect ? factories.runConnect(() => client.connect(transport), attempt) : client.connect(transport)).then(() => {
34202
34563
  if (signal?.aborted) {
34203
34564
  void close();
34204
34565
  signal.throwIfAborted();
@@ -34236,8 +34597,49 @@ async function safeClose(transport, client) {
34236
34597
  }
34237
34598
  }
34238
34599
 
34600
+ // ../linkque-agent-runtime/dist/esm/impl/httpTelemetry.js
34601
+ function httpTelemetryAttributes(url2, method) {
34602
+ try {
34603
+ const target = new URL(url2);
34604
+ return {
34605
+ [ETelemetryAttribute.HTTP_REQUEST_METHOD]: method.toUpperCase(),
34606
+ [ETelemetryAttribute.SERVER_ADDRESS]: target.hostname,
34607
+ [ETelemetryAttribute.URL_PATH]: target.pathname
34608
+ };
34609
+ } catch {
34610
+ return {};
34611
+ }
34612
+ }
34613
+ function recordHttpResponse(observation, response) {
34614
+ try {
34615
+ const correlation = readResponseCorrelationId(response.headers);
34616
+ observation.add({
34617
+ [ETelemetryAttribute.HTTP_RESPONSE_STATUS_CODE]: response.status,
34618
+ ...correlation ? {
34619
+ [ETelemetryAttribute.LINKQUE_REMOTE_TRACE_ID]: correlation.value,
34620
+ [ETelemetryAttribute.LINKQUE_REMOTE_TRACE_ID_HEADER]: correlation.name
34621
+ } : {}
34622
+ });
34623
+ } catch {
34624
+ }
34625
+ }
34626
+
34239
34627
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/mcpInvocationContext.js
34240
34628
  import { AsyncLocalStorage } from "node:async_hooks";
34629
+ function observeMcpRequest(create) {
34630
+ let operation;
34631
+ let resolve;
34632
+ let reject;
34633
+ const completion = observeIo(create, (current) => {
34634
+ operation = current;
34635
+ return new Promise((accept, fail) => {
34636
+ resolve = accept;
34637
+ reject = fail;
34638
+ });
34639
+ }, (outcome) => outcome);
34640
+ const completed = completion.catch(() => void 0);
34641
+ return { operation, resolve, reject, completed };
34642
+ }
34241
34643
  async function waitForMcpOperation(operation, signal) {
34242
34644
  return waitWithSignal(operation, signal);
34243
34645
  }
@@ -34246,7 +34648,7 @@ var McpInvocationContext = class {
34246
34648
  current() {
34247
34649
  return this.storage.getStore();
34248
34650
  }
34249
- async run(timeoutMs, signal, operation) {
34651
+ async run(timeoutMs, signal, operation, telemetry = {}) {
34250
34652
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
34251
34653
  throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
34252
34654
  signal?.throwIfAborted();
@@ -34256,19 +34658,42 @@ var McpInvocationContext = class {
34256
34658
  timeoutReason: new DOMException("MCP \u8C03\u7528\u603B\u9884\u7B97\u5DF2\u8017\u5C3D", "TimeoutError")
34257
34659
  });
34258
34660
  const context2 = {
34661
+ ...telemetry,
34662
+ active: true,
34663
+ requests: /* @__PURE__ */ new Set(),
34259
34664
  signal: scope.context.signal,
34260
34665
  deadline: scope.context.deadline
34261
34666
  };
34262
34667
  try {
34263
- return await this.storage.run(context2, () => waitWithSignal(() => operation(context2), context2.signal));
34668
+ const result = await this.storage.run(context2, () => waitWithSignal(() => operation(context2), context2.signal));
34669
+ const failed = result && typeof result === "object" && "isError" in result && result.isError === true;
34670
+ for (const request of context2.requests)
34671
+ request.resolve(failed ? ETelemetryOutcome.ERROR : ETelemetryOutcome.SUCCESS);
34672
+ return result;
34264
34673
  } catch (error) {
34674
+ const observationError = classifyMcpObservationError(error);
34675
+ for (const request of context2.requests)
34676
+ request.reject(observationError);
34265
34677
  scope.context.throwIfAborted();
34266
34678
  throw error;
34267
34679
  } finally {
34680
+ context2.active = false;
34681
+ await Promise.all([...context2.requests].map((request) => request.completed));
34682
+ context2.observation = void 0;
34683
+ context2.requests.clear();
34268
34684
  scope.dispose();
34269
34685
  }
34270
34686
  }
34271
34687
  };
34688
+ function classifyMcpObservationError(error) {
34689
+ try {
34690
+ const cause = error instanceof Error ? error.cause : void 0;
34691
+ if ([error, cause].some((value) => value instanceof McpError && value.code === ErrorCode.RequestTimeout))
34692
+ return new DOMException("MCP SDK \u8BF7\u6C42\u7B49\u5F85\u8D85\u65F6", "TimeoutError");
34693
+ } catch {
34694
+ }
34695
+ return error;
34696
+ }
34272
34697
 
34273
34698
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/remoteSignatureSigner.js
34274
34699
  var DEFAULT_SIGN_ENDPOINT = RUNTIME_CONFIG_DEFAULTS.LINKQUEGW_MCP_SIGN_ENDPOINT;
@@ -34311,25 +34736,28 @@ var RemoteSignatureSigner = class {
34311
34736
  headers.authorization = options.signal ? await waitForMcpOperation(() => this.getAuthorizationHeader(), options.signal) : await this.getAuthorizationHeader();
34312
34737
  }
34313
34738
  options.signal?.throwIfAborted();
34314
- const resp = await (options.sensitive ? this.rawFetch : this.fetchImpl)(this.signEndpoint, { method: "POST", headers, body, signal: options.signal });
34315
- options.signal?.throwIfAborted();
34316
- if (!resp.ok) {
34317
- const text = options.sensitive ? "" : await safeText(resp);
34318
- throw new Error(`linkquegw \u7B7E\u540D\u670D\u52A1\u5931\u8D25: status=${resp.status}${text ? ` body=${text}` : ""}`);
34319
- }
34320
- const parsed = await resp.json().catch(() => ({}));
34321
- const payload = isWrappedSignResponse(parsed) ? extractFromWrapped(parsed) : parsed;
34322
- if (typeof payload.authorization !== "string" || !payload.authorization) {
34323
- throw new Error("linkquegw \u7B7E\u540D\u670D\u52A1\u54CD\u5E94\u7F3A\u5C11 authorization");
34324
- }
34325
- if (typeof payload.signatureContent !== "string") {
34326
- throw new Error("linkquegw \u7B7E\u540D\u670D\u52A1\u54CD\u5E94\u7F3A\u5C11 signatureContent");
34327
- }
34328
- return {
34329
- authorization: payload.authorization,
34330
- signatureContent: payload.signatureContent,
34331
- ...optionalUserId(payload.userId)
34332
- };
34739
+ return observeIo(() => new IoObservation(options.observation, ETelemetryOperationName.MCP_SIGN, httpTelemetryAttributes(this.signEndpoint, "POST"), options.signal), async (operation) => {
34740
+ const resp = await (options.sensitive ? this.rawFetch : this.fetchImpl)(this.signEndpoint, { method: "POST", headers, body, signal: options.signal });
34741
+ recordHttpResponse(operation, resp);
34742
+ options.signal?.throwIfAborted();
34743
+ if (!resp.ok) {
34744
+ const text = options.sensitive ? "" : await safeText(resp);
34745
+ throw new Error(`linkquegw \u7B7E\u540D\u670D\u52A1\u5931\u8D25: status=${resp.status}${text ? ` body=${text}` : ""}`);
34746
+ }
34747
+ const parsed = await resp.json().catch(() => ({}));
34748
+ const payload = isWrappedSignResponse(parsed) ? extractFromWrapped(parsed) : parsed;
34749
+ if (typeof payload.authorization !== "string" || !payload.authorization) {
34750
+ throw new Error("linkquegw \u7B7E\u540D\u670D\u52A1\u54CD\u5E94\u7F3A\u5C11 authorization");
34751
+ }
34752
+ if (typeof payload.signatureContent !== "string") {
34753
+ throw new Error("linkquegw \u7B7E\u540D\u670D\u52A1\u54CD\u5E94\u7F3A\u5C11 signatureContent");
34754
+ }
34755
+ return {
34756
+ authorization: payload.authorization,
34757
+ signatureContent: payload.signatureContent,
34758
+ ...optionalUserId(payload.userId)
34759
+ };
34760
+ });
34333
34761
  }
34334
34762
  };
34335
34763
  function isWrappedSignResponse(v) {
@@ -35238,8 +35666,8 @@ async function parseErrorResponse(input) {
35238
35666
  const errorClass = OAUTH_ERRORS[error] || ServerError;
35239
35667
  return new errorClass(error_description || "", error_uri);
35240
35668
  } catch (error) {
35241
- const errorMessage3 = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
35242
- return new ServerError(errorMessage3);
35669
+ const errorMessage2 = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
35670
+ return new ServerError(errorMessage2);
35243
35671
  }
35244
35672
  }
35245
35673
  async function auth(provider, options) {
@@ -35926,6 +36354,7 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
35926
36354
  httpRequestBody: typeof init?.body === "string" ? init.body : ""
35927
36355
  };
35928
36356
  const { authorization, signatureContent, userId } = await signer.sign(req, {
36357
+ observation: invocation?.observation,
35929
36358
  authorizationHeader: invocation?.auth?.authorization,
35930
36359
  signal,
35931
36360
  sensitive: !!invocation?.auth
@@ -35950,25 +36379,67 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
35950
36379
  else
35951
36380
  headers.delete("x-alipay-authcode");
35952
36381
  }
35953
- const resp = await (invocation?.auth ? baseFetch : loggedFetch)(url2, {
35954
- ...init,
35955
- headers,
35956
- ...signal ? { signal } : {}
35957
- });
35958
- if (onTraceId) {
35959
- try {
35960
- const traceId = resp.headers.get("alipay-trace-id");
35961
- if (traceId) {
35962
- onTraceId({
35963
- traceId,
35964
- httpMethod: req.httpMethod,
35965
- requestUrl: req.httpRequestUrl
35966
- });
36382
+ let rpcMethod;
36383
+ try {
36384
+ const parsed = JSON.parse(req.httpRequestBody);
36385
+ if (typeof parsed.method === "string" && [
36386
+ ETelemetryMcpPhase.INITIALIZE,
36387
+ ETelemetryMcpPhase.TOOLS_LIST,
36388
+ ETelemetryMcpPhase.TOOLS_CALL,
36389
+ ETelemetryMcpPhase.INITIALIZED,
36390
+ ETelemetryMcpPhase.CANCELLED
36391
+ ].some((phase) => phase === parsed.method))
36392
+ rpcMethod = parsed.method;
36393
+ } catch {
36394
+ }
36395
+ const requestObservation = observeMcpRequest(() => new IoObservation(invocation?.observation, ETelemetryOperationName.MCP_OPENGW, {
36396
+ ...httpTelemetryAttributes(targetUrl, req.httpMethod),
36397
+ [ETelemetryAttribute.LINKQUE_MCP_PHASE]: rpcMethod ?? (req.httpMethod.toUpperCase() === "GET" ? ETelemetryMcpPhase.SSE_CONNECT : ETelemetryMcpPhase.HTTP),
36398
+ ...invocation?.serverName ? {
36399
+ [ETelemetryAttribute.LINKQUE_MCP_SERVER_NAME]: invocation.serverName
36400
+ } : {},
36401
+ ...invocation?.attempt ? { [ETelemetryAttribute.LINKQUE_IO_ATTEMPT]: invocation.attempt } : {}
36402
+ }, signal));
36403
+ const operation = requestObservation.operation;
36404
+ const waitForResult = !!invocation?.active && !!rpcMethod && [
36405
+ ETelemetryMcpPhase.INITIALIZE,
36406
+ ETelemetryMcpPhase.TOOLS_LIST,
36407
+ ETelemetryMcpPhase.TOOLS_CALL
36408
+ ].includes(rpcMethod);
36409
+ if (waitForResult)
36410
+ invocation.requests.add(requestObservation);
36411
+ try {
36412
+ const resp = await (invocation?.auth ? baseFetch : loggedFetch)(url2, {
36413
+ ...init,
36414
+ headers,
36415
+ ...signal ? { signal } : {}
36416
+ });
36417
+ recordHttpResponse(operation, resp);
36418
+ if (!resp.ok)
36419
+ requestObservation.resolve(ETelemetryOutcome.ERROR);
36420
+ else if (!waitForResult)
36421
+ requestObservation.resolve(ETelemetryOutcome.SUCCESS);
36422
+ if (onTraceId) {
36423
+ try {
36424
+ const traceId = resp.headers.get("alipay-trace-id");
36425
+ if (traceId) {
36426
+ onTraceId({
36427
+ traceId,
36428
+ httpMethod: req.httpMethod,
36429
+ requestUrl: req.httpRequestUrl
36430
+ });
36431
+ }
36432
+ } catch {
35967
36433
  }
35968
- } catch {
35969
36434
  }
36435
+ return resp;
36436
+ } catch (error) {
36437
+ requestObservation.reject(error);
36438
+ throw error;
36439
+ } finally {
36440
+ if (!waitForResult)
36441
+ await requestObservation.completed;
35970
36442
  }
35971
- return resp;
35972
36443
  };
35973
36444
  }
35974
36445
 
@@ -36156,26 +36627,30 @@ var LinkquegwTokenVerifier = class {
36156
36627
  async verify(input) {
36157
36628
  input.signal?.throwIfAborted();
36158
36629
  assertMcpUserAuthorization(input.authorization);
36630
+ const endpoint = this.options.endpoint ?? RUNTIME_CONFIG_DEFAULTS.LINKQUEGW_TOKEN_VERIFY_ENDPOINT;
36159
36631
  try {
36160
- const response = await (this.options.fetchImpl ?? globalThis.fetch)(this.options.endpoint ?? RUNTIME_CONFIG_DEFAULTS.LINKQUEGW_TOKEN_VERIFY_ENDPOINT, {
36161
- method: "POST",
36162
- headers: {
36163
- authorization: input.authorization,
36164
- "content-type": "application/json"
36165
- },
36166
- body: JSON.stringify({ agentId: input.agentId }),
36167
- signal: input.signal
36632
+ return await observeIo(() => new IoObservation(input.observation, ETelemetryOperationName.MCP_VERIFY, httpTelemetryAttributes(endpoint, "POST"), input.signal), async (operation) => {
36633
+ const response = await (this.options.fetchImpl ?? globalThis.fetch)(this.options.endpoint ?? RUNTIME_CONFIG_DEFAULTS.LINKQUEGW_TOKEN_VERIFY_ENDPOINT, {
36634
+ method: "POST",
36635
+ headers: {
36636
+ authorization: input.authorization,
36637
+ "content-type": "application/json"
36638
+ },
36639
+ body: JSON.stringify({ agentId: input.agentId }),
36640
+ signal: input.signal
36641
+ });
36642
+ recordHttpResponse(operation, response);
36643
+ if (!response.ok)
36644
+ throw new Error("\u6821\u9A8C\u8BF7\u6C42\u5931\u8D25");
36645
+ const result = await response.json();
36646
+ input.signal?.throwIfAborted();
36647
+ if (result?.success !== true || typeof result.data?.userId !== "string" || !result.data.userId.trim() || typeof result.data.agentId !== "string" || !result.data.agentId.trim()) {
36648
+ throw new Error("\u8EAB\u4EFD\u54CD\u5E94\u65E0\u6548");
36649
+ }
36650
+ if (result.data.agentId !== input.agentId)
36651
+ throw new McpInvocationError("MCP_IDENTITY_MISMATCH", "\u7528\u6237\u51ED\u636E\u4E0D\u5C5E\u4E8E\u76EE\u6807 Agent");
36652
+ return { userId: result.data.userId, agentId: result.data.agentId };
36168
36653
  });
36169
- if (!response.ok)
36170
- throw new Error("\u6821\u9A8C\u8BF7\u6C42\u5931\u8D25");
36171
- const result = await response.json();
36172
- input.signal?.throwIfAborted();
36173
- if (result?.success !== true || typeof result.data?.userId !== "string" || !result.data.userId.trim() || typeof result.data.agentId !== "string" || !result.data.agentId.trim()) {
36174
- throw new Error("\u8EAB\u4EFD\u54CD\u5E94\u65E0\u6548");
36175
- }
36176
- if (result.data.agentId !== input.agentId)
36177
- throw new McpInvocationError("MCP_IDENTITY_MISMATCH", "\u7528\u6237\u51ED\u636E\u4E0D\u5C5E\u4E8E\u76EE\u6807 Agent");
36178
- return { userId: result.data.userId, agentId: result.data.agentId };
36179
36654
  } catch (error) {
36180
36655
  input.signal?.throwIfAborted();
36181
36656
  if (error instanceof McpInvocationError)
@@ -36190,8 +36665,7 @@ var defaultCreateSigner = (config, getAuthorizationHeader, debugLog) => new Remo
36190
36665
  agentId: config.agentId,
36191
36666
  signEndpoint: config.signEndpoint,
36192
36667
  getAuthorizationHeader,
36193
- // 签名服务出站日志(mcp-sign);注入后 signer 内部把 fetchImpl 包成打日志 fetch。
36194
- ...debugLog ? { debugLog } : {}
36668
+ debugLog
36195
36669
  });
36196
36670
  var defaultCreateClient = () => new Client({ name: "linkque-agent-runtime-mcp-client", version: "1.0.0" });
36197
36671
  var RemoteGatewayMcpServerProvider = class {
@@ -36205,28 +36679,52 @@ var RemoteGatewayMcpServerProvider = class {
36205
36679
  debugLog;
36206
36680
  constructor(options) {
36207
36681
  this.resolveConfig = options.resolveConfig;
36208
- this.createTokenVerifier = options.createTokenVerifier ?? ((config) => new LinkquegwTokenVerifier({ endpoint: config.verifyTokenEndpoint }));
36682
+ this.createTokenVerifier = options.createTokenVerifier;
36209
36683
  this.getAuthorizationHeader = options.getAuthorizationHeader;
36210
- this.createSigner = options.createSigner ?? ((config, getAuthorizationHeader) => defaultCreateSigner(config, getAuthorizationHeader, this.debugLog));
36211
- this.createClient = options.createClient ?? defaultCreateClient;
36684
+ this.createSigner = options.createSigner;
36685
+ this.createClient = options.createClient;
36212
36686
  this.onTraceId = options.onTraceId;
36213
36687
  this.debugLog = options.debugLog;
36214
36688
  }
36215
- async servers(resources, signal) {
36216
- return Promise.all(resources.map((r) => this.connectOne(r, signal)));
36689
+ doCreateTokenVerifier(config) {
36690
+ if (this.createTokenVerifier) {
36691
+ return this.createTokenVerifier(config);
36692
+ }
36693
+ return new LinkquegwTokenVerifier({ endpoint: config.verifyTokenEndpoint });
36694
+ }
36695
+ doCreateSigner(config, getAuthorizationHeader) {
36696
+ if (this.createSigner) {
36697
+ return this.createSigner(config, getAuthorizationHeader);
36698
+ }
36699
+ return defaultCreateSigner(config, getAuthorizationHeader, this.debugLog);
36700
+ }
36701
+ doCrateClient() {
36702
+ if (this.createClient) {
36703
+ return this.createClient();
36704
+ }
36705
+ return defaultCreateClient();
36706
+ }
36707
+ async servers(resources, signal, observation) {
36708
+ return Promise.all(resources.map((r) => this.connectOne(r, signal, observation)));
36217
36709
  }
36218
36710
  /** 连单个远端 server 并包装成 IMcpServer。建连失败有限重试 + 失败清理由 helper 负责。 */
36219
- async connectOne(resource, connectSignal) {
36711
+ async connectOne(resource, connectSignal, observation) {
36220
36712
  const config = await this.resolveConfig(resource);
36221
36713
  connectSignal?.throwIfAborted();
36222
36714
  const timeoutMs = config.requestTimeoutMs ?? 18e4;
36223
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
36715
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
36224
36716
  throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
36225
- const verifier = this.createTokenVerifier(config);
36717
+ }
36718
+ const verifier = this.doCreateTokenVerifier(config);
36226
36719
  const callHeaders = new AsyncLocalStorage2();
36227
36720
  const { client } = await connectMcpClientWithRetry(config, {
36228
- createTransport: () => createSseTransport(config, this.createSigner(config, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
36229
- createClient: () => this.createClient()
36721
+ createTransport: () => createSseTransport(config, this.doCreateSigner(config, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
36722
+ createClient: () => this.doCrateClient(),
36723
+ runConnect: (operation, attempt) => this.invocationContext.run(timeoutMs, connectSignal, operation, {
36724
+ observation,
36725
+ attempt,
36726
+ serverName: resource.config.serverName ?? resource.resourceId
36727
+ })
36230
36728
  }, connectSignal);
36231
36729
  const serverName = resource.config.serverName ?? resource.resourceId;
36232
36730
  const argsMappingRules = resource.config.argsMappingRules ?? [];
@@ -36264,8 +36762,8 @@ var RemoteGatewayMcpServerProvider = class {
36264
36762
  callTool: (params, resultSchema, requestOptions) => request("tools/call", params, () => client.callTool(params, resultSchema, requestOptions))
36265
36763
  };
36266
36764
  const callTool = (name, args, signal, options) => callHeaders.run(options?.headers ?? {}, () => this.invocationContext.run(timeoutMs, signal, async (invocation) => {
36267
- const observation = options?.context?.observation;
36268
- recordMcpContentSection(observation, ETelemetryContentSection.MCP_REQUESTED_INPUT, args, options?.toolSchema?.inputSchema);
36765
+ const innerObservation = options?.context?.observation;
36766
+ recordMcpContentSection(innerObservation, ETelemetryContentSection.MCP_REQUESTED_INPUT, args, options?.toolSchema?.inputSchema);
36269
36767
  const plan = createArgsMappingPlan(name, args, argsMappingRules);
36270
36768
  if (plan.requiresUserId) {
36271
36769
  if (config.signEndpoint !== void 0 && config.signEndpoint !== DEFAULT_SIGN_ENDPOINT && !config.verifyTokenEndpoint?.trim())
@@ -36275,6 +36773,7 @@ var RemoteGatewayMcpServerProvider = class {
36275
36773
  const authorization = await waitForMcpOperation(() => this.getAuthorizationHeader(), invocation.signal);
36276
36774
  assertMcpUserAuthorization(authorization);
36277
36775
  const identity = await waitForMcpOperation(() => verifier.verify({
36776
+ observation: innerObservation,
36278
36777
  authorization,
36279
36778
  agentId: config.agentId,
36280
36779
  signal: invocation.signal
@@ -36288,7 +36787,7 @@ var RemoteGatewayMcpServerProvider = class {
36288
36787
  };
36289
36788
  }
36290
36789
  const mapped = resolveArgsMappingPlan(plan, invocation.auth);
36291
- recordMcpContentSection(observation, ETelemetryContentSection.MCP_INPUT, mapped, options?.toolSchema?.inputSchema);
36790
+ recordMcpContentSection(innerObservation, ETelemetryContentSection.MCP_INPUT, mapped, options?.toolSchema?.inputSchema);
36292
36791
  invocation.signal.throwIfAborted();
36293
36792
  const remaining = Math.max(1, invocation.deadline - performance.now());
36294
36793
  try {
@@ -36298,7 +36797,7 @@ var RemoteGatewayMcpServerProvider = class {
36298
36797
  maxTotalTimeout: remaining,
36299
36798
  resetTimeoutOnProgress: false
36300
36799
  });
36301
- recordMcpContentSection(observation, ETelemetryContentSection.MCP_OUTPUT, result, options?.toolSchema?.outputSchema);
36800
+ recordMcpContentSection(innerObservation, ETelemetryContentSection.MCP_OUTPUT, result, options?.toolSchema?.outputSchema);
36302
36801
  return result;
36303
36802
  } catch (error) {
36304
36803
  invocation.signal.throwIfAborted();
@@ -36306,11 +36805,11 @@ var RemoteGatewayMcpServerProvider = class {
36306
36805
  throw new Error("MCP \u7528\u6237\u5DE5\u5177\u8C03\u7528\u5931\u8D25", { cause: error });
36307
36806
  throw error;
36308
36807
  }
36309
- }));
36808
+ }, { observation: options?.context?.observation, serverName }));
36310
36809
  return {
36311
36810
  resourceId: resource.resourceId,
36312
36811
  serverName,
36313
- listTools: (signal) => listToolsFromClient(loggedClient, resource.resourceId, callTool, signal),
36812
+ listTools: (signal, parent) => this.invocationContext.run(timeoutMs, signal, (invocation) => listToolsFromClient(loggedClient, resource.resourceId, callTool, invocation.signal), { observation: parent, serverName }),
36314
36813
  callTool,
36315
36814
  close: async () => {
36316
36815
  try {
@@ -36379,7 +36878,7 @@ var LinkqueKnowledgeSearchPort = class {
36379
36878
  resourceId: resource.resourceId
36380
36879
  }));
36381
36880
  }
36382
- async search(input, signal) {
36881
+ async search(input, signal, observation) {
36383
36882
  const url2 = `${this.baseUrl}${KNOWLEDGE_SEARCH_PATH}`;
36384
36883
  const body = JSON.stringify({
36385
36884
  query: input.query,
@@ -36396,34 +36895,36 @@ var LinkqueKnowledgeSearchPort = class {
36396
36895
  signals: signal ? [signal] : [],
36397
36896
  timeoutMs: this.timeoutMs
36398
36897
  });
36399
- let resp;
36400
36898
  try {
36401
- resp = await this.fetchImpl(url2, {
36402
- method: "POST",
36403
- headers,
36404
- body,
36405
- signal: scope.context.signal
36899
+ return await observeIo(() => new IoObservation(observation, ETelemetryOperationName.KNOWLEDGE_SEARCH, httpTelemetryAttributes(url2, "POST"), scope.context.signal), async (operation) => {
36900
+ const resp = await this.fetchImpl(url2, {
36901
+ method: "POST",
36902
+ headers,
36903
+ body,
36904
+ signal: scope.context.signal
36905
+ });
36906
+ recordHttpResponse(operation, resp);
36907
+ if (!resp.ok) {
36908
+ const text = await safeText2(resp);
36909
+ throw new Error(`linkquegw \u77E5\u8BC6\u5E93\u68C0\u7D22\u5931\u8D25: status=${resp.status}${text ? ` body=${text}` : ""}`);
36910
+ }
36911
+ const parsed = await resp.json().catch(() => ({}));
36912
+ if (typeof parsed.success === "boolean") {
36913
+ if (!parsed.success) {
36914
+ const code = parsed.errorCode ?? "UNKNOWN";
36915
+ const msg = parsed.errorMessage ?? "linkquegw \u77E5\u8BC6\u5E93\u68C0\u7D22\u8FD4\u56DE\u5931\u8D25";
36916
+ throw new Error(`linkquegw \u77E5\u8BC6\u5E93\u68C0\u7D22\u5931\u8D25: ${code} ${msg}`);
36917
+ }
36918
+ return { hits: normalizeHits(parsed.data?.hits) };
36919
+ }
36920
+ if (parsed.hits !== void 0) {
36921
+ return { hits: normalizeHits(parsed.hits) };
36922
+ }
36923
+ throw new Error("linkquegw \u77E5\u8BC6\u5E93\u68C0\u7D22\u54CD\u5E94\u7F3A\u5C11 success/hits");
36406
36924
  });
36407
36925
  } finally {
36408
36926
  scope.dispose();
36409
36927
  }
36410
- if (!resp.ok) {
36411
- const text = await safeText2(resp);
36412
- throw new Error(`linkquegw \u77E5\u8BC6\u5E93\u68C0\u7D22\u5931\u8D25: status=${resp.status}${text ? ` body=${text}` : ""}`);
36413
- }
36414
- const parsed = await resp.json().catch(() => ({}));
36415
- if (typeof parsed.success === "boolean") {
36416
- if (!parsed.success) {
36417
- const code = parsed.errorCode ?? "UNKNOWN";
36418
- const msg = parsed.errorMessage ?? "linkquegw \u77E5\u8BC6\u5E93\u68C0\u7D22\u8FD4\u56DE\u5931\u8D25";
36419
- throw new Error(`linkquegw \u77E5\u8BC6\u5E93\u68C0\u7D22\u5931\u8D25: ${code} ${msg}`);
36420
- }
36421
- return { hits: normalizeHits(parsed.data?.hits) };
36422
- }
36423
- if (parsed.hits !== void 0) {
36424
- return { hits: normalizeHits(parsed.hits) };
36425
- }
36426
- throw new Error("linkquegw \u77E5\u8BC6\u5E93\u68C0\u7D22\u54CD\u5E94\u7F3A\u5C11 success/hits");
36427
36928
  }
36428
36929
  };
36429
36930
  function normalizeHits(raw) {
@@ -36477,7 +36978,7 @@ var LinkqueWebSearchPort = class {
36477
36978
  if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0)
36478
36979
  throw new Error("\u5168\u7F51\u641C\u7D22 timeoutMs \u5FC5\u987B\u4E3A\u6B63\u6570");
36479
36980
  }
36480
- async search(input, signal) {
36981
+ async search(input, signal, observation) {
36481
36982
  const startedAt = Date.now();
36482
36983
  const scope = new CancellationScope({
36483
36984
  signals: signal ? [signal] : [],
@@ -36496,38 +36997,41 @@ var LinkqueWebSearchPort = class {
36496
36997
  });
36497
36998
  if (typeof input.agentId !== "string" || !input.agentId.trim() || [...input.agentId].length > 128)
36498
36999
  throw new WebSearchError("WEB_SEARCH_INVALID_ARGS");
36499
- const authHeaders = await awaitWebSearchOperation(() => this.options.getAuthHeaders(), requestSignal);
37000
+ const authHeaders = await waitWithSignal(() => this.options.getAuthHeaders(), requestSignal);
36500
37001
  const authorization = readBearerAuthorization(authHeaders);
36501
37002
  const url2 = new URL(this.endpoint);
36502
37003
  url2.searchParams.set("agentId", input.agentId);
36503
37004
  url2.searchParams.set("query", args.query);
36504
37005
  if (args.topK !== void 0)
36505
37006
  url2.searchParams.set("topK", String(args.topK));
36506
- const response = await awaitWebSearchOperation(() => this.fetchImpl(url2, {
36507
- method: "GET",
36508
- headers: { authorization, accept: "application/json" },
36509
- signal: requestSignal,
36510
- redirect: "error"
36511
- }), requestSignal);
36512
- status = response.status;
36513
- if (!response.ok) {
36514
- void response.body?.cancel().catch(() => {
36515
- });
36516
- throw new WebSearchError(status === 401 || status === 403 ? "WEB_SEARCH_USER_ID_UNAVAILABLE" : status === 429 ? "WEB_SEARCH_RATE_LIMITED" : "WEB_SEARCH_UPSTREAM_ERROR");
36517
- }
36518
- const body = await readLimitedJson(response, requestSignal);
36519
- requestSignal.throwIfAborted();
36520
- const result = parseResponse(body, args.query, args.topK ?? WEB_SEARCH_TOP_K_DEFAULT);
36521
- count = result.items.length;
36522
- return result;
37007
+ return await observeIo(() => new IoObservation(observation, ETelemetryOperationName.WEB_SEARCH, httpTelemetryAttributes(url2, "GET"), requestSignal), async (operation) => {
37008
+ const response = await waitWithSignal(() => this.fetchImpl(url2, {
37009
+ method: "GET",
37010
+ headers: { authorization, accept: "application/json" },
37011
+ signal: requestSignal,
37012
+ redirect: "error"
37013
+ }), requestSignal);
37014
+ status = response.status;
37015
+ recordHttpResponse(operation, response);
37016
+ if (!response.ok) {
37017
+ void response.body?.cancel().catch(() => {
37018
+ });
37019
+ throw new WebSearchError(status === 401 || status === 403 ? "WEB_SEARCH_USER_ID_UNAVAILABLE" : status === 429 ? "WEB_SEARCH_RATE_LIMITED" : "WEB_SEARCH_UPSTREAM_ERROR");
37020
+ }
37021
+ const body = await readLimitedJson(response, requestSignal);
37022
+ requestSignal.throwIfAborted();
37023
+ const result = parseResponse(body, args.query, args.topK ?? WEB_SEARCH_TOP_K_DEFAULT);
37024
+ count = result.items.length;
37025
+ return result;
37026
+ });
36523
37027
  } catch (error) {
36524
37028
  if (signal?.aborted) {
36525
37029
  outcome = "cancelled";
36526
37030
  throw new DOMException("\u5168\u7F51\u641C\u7D22\u5DF2\u53D6\u6D88", "AbortError");
36527
37031
  }
36528
- const failure5 = toWebSearchFailure(requestSignal.aborted ? requestSignal.reason : error);
36529
- outcome = failure5.code;
36530
- throw new WebSearchError(failure5.code);
37032
+ const failure4 = toWebSearchFailure(requestSignal.aborted ? requestSignal.reason : error);
37033
+ outcome = failure4.code;
37034
+ throw new WebSearchError(failure4.code);
36531
37035
  } finally {
36532
37036
  scope.dispose();
36533
37037
  try {
@@ -36567,7 +37071,7 @@ async function readLimitedJson(response, signal) {
36567
37071
  let completed = false;
36568
37072
  try {
36569
37073
  while (true) {
36570
- const { done, value } = await awaitWebSearchOperation(() => reader.read(), signal);
37074
+ const { done, value } = await waitWithSignal(() => reader.read(), signal);
36571
37075
  if (done) {
36572
37076
  completed = true;
36573
37077
  break;
@@ -36676,19 +37180,19 @@ import path from "node:path";
36676
37180
  import { fileURLToPath } from "node:url";
36677
37181
 
36678
37182
  // ../../node_modules/fflate/esm/index.mjs
36679
- import { createRequire } from "module";
36680
- var require2 = createRequire("/");
37183
+ import { createRequire as createRequire2 } from "module";
37184
+ var require2 = createRequire2("/");
36681
37185
  var _a;
36682
- var Worker;
37186
+ var Worker2;
36683
37187
  var isMarkedAsUntransferable;
36684
37188
  var workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";
36685
37189
  try {
36686
- _a = require2("worker_threads"), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
37190
+ _a = require2("worker_threads"), Worker2 = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
36687
37191
  } catch (e) {
36688
37192
  }
36689
- var wk = Worker ? function(c, _, msg, transfer, cb) {
37193
+ var wk = Worker2 ? function(c, _, msg, transfer, cb) {
36690
37194
  var done = false;
36691
- var w = new Worker(c + workerAdd, { eval: true }).on("error", function(e) {
37195
+ var w = new Worker2(c + workerAdd, { eval: true }).on("error", function(e) {
36692
37196
  return cb(e, null);
36693
37197
  }).on("message", function(m) {
36694
37198
  return cb(null, m);
@@ -36703,7 +37207,7 @@ var wk = Worker ? function(c, _, msg, transfer, cb) {
36703
37207
  w.postMessage(msg, transfer);
36704
37208
  w.terminate = function() {
36705
37209
  done = true;
36706
- return Worker.prototype.terminate.call(w);
37210
+ return Worker2.prototype.terminate.call(w);
36707
37211
  };
36708
37212
  return w;
36709
37213
  } : function(_, __, ___, ____, cb) {
@@ -37323,6 +37827,117 @@ function unzip(data, opts, cb) {
37323
37827
  return tAll;
37324
37828
  }
37325
37829
 
37830
+ // ../linkque-agent-runtime/dist/esm/impl/linkqueSkillResourceResolver.js
37831
+ function isLocalSkillResource(resource) {
37832
+ return /^file:\/\//i.test(resource.config.skillZipUrl?.trim() ?? "");
37833
+ }
37834
+ var LinkqueSkillResourceResolver = class {
37835
+ options;
37836
+ fetchImpl;
37837
+ constructor(options = {}) {
37838
+ this.options = options;
37839
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
37840
+ this.fetchImpl = options.debugLog ? createHttpLoggingFetch(options.debugLog, "skill-query", fetchImpl) : fetchImpl;
37841
+ }
37842
+ async resolve(resources, observation) {
37843
+ const invalidSkillResourceIds = [];
37844
+ const skillResourceIds = Array.from(new Set(resources.filter((r) => !isLocalSkillResource(r)).map((r) => r.resourceId))).filter((id) => {
37845
+ const valid = typeof id === "string" && id.trim().length > 0 && id.length <= 128;
37846
+ if (!valid)
37847
+ invalidSkillResourceIds.push(id);
37848
+ return valid;
37849
+ });
37850
+ this.warn(invalidSkillResourceIds, "\u65E0\u6548 resourceId");
37851
+ const urls = await this.queryBatch(skillResourceIds, observation);
37852
+ return resources.flatMap((resource) => {
37853
+ const url2 = isLocalSkillResource(resource) ? resource.config.skillZipUrl.trim() : urls.get(resource.resourceId);
37854
+ return url2 ? [{ ...resource, config: { ...resource.config, skillZipUrl: url2 } }] : [];
37855
+ });
37856
+ }
37857
+ async queryBatch(ids, observation) {
37858
+ const urls = /* @__PURE__ */ new Map();
37859
+ if (ids.length === 0)
37860
+ return urls;
37861
+ const scope = new CancellationScope({
37862
+ timeoutMs: this.options.timeoutMs ?? 3e4
37863
+ });
37864
+ const baseUrl = this.options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUEGW_SKILL_LOADER_BASE_URL;
37865
+ const url2 = `${baseUrl.replace(/\/+$/, "")}/api/skill/batchQuery`;
37866
+ try {
37867
+ await observeIo(() => new IoObservation(observation, ETelemetryOperationName.SKILL_QUERY, {
37868
+ ...httpTelemetryAttributes(url2, "POST"),
37869
+ [ETelemetryAttribute.LINKQUE_SKILL_REQUESTED_COUNT]: ids.length
37870
+ }, scope.context.signal), async (operation) => {
37871
+ operation.add({
37872
+ [ETelemetryAttribute.LINKQUE_SKILL_RESOLVED_COUNT]: 0,
37873
+ [ETelemetryAttribute.LINKQUE_SKILL_SKIPPED_COUNT]: ids.length
37874
+ });
37875
+ const headers = new Headers(await this.options.getAuthHeaders?.());
37876
+ if (!headers.get("authorization")?.trim()) {
37877
+ this.warn(ids, "\u7F3A\u5C11\u7F51\u5173\u9274\u6743");
37878
+ return ETelemetryOutcome.ERROR;
37879
+ }
37880
+ headers.set("content-type", "application/json");
37881
+ const response = await this.fetchImpl(url2, {
37882
+ method: "POST",
37883
+ headers,
37884
+ body: JSON.stringify({ abilityCodes: ids }),
37885
+ signal: scope.context.signal
37886
+ });
37887
+ recordHttpResponse(operation, response);
37888
+ if (!response.ok) {
37889
+ throw new Error(`HTTP ${response.status}`);
37890
+ }
37891
+ const body = await response.json();
37892
+ if (!isObject3(body) || body.success !== true || !isObject3(body.data) || !Array.isArray(body.data.skills)) {
37893
+ throw new Error("\u7F51\u5173\u4E1A\u52A1\u5931\u8D25\u6216\u54CD\u5E94\u683C\u5F0F\u65E0\u6548");
37894
+ }
37895
+ for (const item of body.data.skills) {
37896
+ if (!isObject3(item) || typeof item.abilityCode !== "string" || !ids.includes(item.abilityCode)) {
37897
+ continue;
37898
+ }
37899
+ const skillZipUrl = httpUrl(item.skillZipUrl);
37900
+ if (skillZipUrl) {
37901
+ urls.set(item.abilityCode, skillZipUrl);
37902
+ }
37903
+ }
37904
+ const noURLIds = ids.filter((id) => !urls.has(id));
37905
+ if (noURLIds.length > 0) {
37906
+ this.warn(noURLIds, "\u672A\u8FD4\u56DE\u6709\u6548 HTTP(S) skillZipUrl");
37907
+ }
37908
+ operation.add({
37909
+ [ETelemetryAttribute.LINKQUE_SKILL_RESOLVED_COUNT]: urls.size,
37910
+ [ETelemetryAttribute.LINKQUE_SKILL_SKIPPED_COUNT]: noURLIds.length
37911
+ });
37912
+ return noURLIds.length === 0 ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.ERROR;
37913
+ }, (outcome) => outcome);
37914
+ } catch {
37915
+ const reason = scope.context.signal.aborted ? "\u67E5\u8BE2\u8D85\u65F6" : "\u7F51\u5173\u67E5\u8BE2\u5931\u8D25";
37916
+ this.warn(ids, reason);
37917
+ } finally {
37918
+ scope.dispose();
37919
+ }
37920
+ return urls;
37921
+ }
37922
+ warn(resourceIds, reason) {
37923
+ const ids = Array.isArray(resourceIds) ? resourceIds : [resourceIds];
37924
+ this.options.debugLog?.(`[skill] \u8DF3\u8FC7\u8D44\u6E90 ${ids.join(",")}:${reason}`, EDebugLogScope.SKILL);
37925
+ }
37926
+ };
37927
+ function isObject3(value) {
37928
+ return typeof value === "object" && value !== null;
37929
+ }
37930
+ function httpUrl(value) {
37931
+ if (typeof value !== "string" || !/^https?:\/\//i.test(value.trim()))
37932
+ return void 0;
37933
+ try {
37934
+ const url2 = new URL(value.trim());
37935
+ return url2.protocol === "http:" || url2.protocol === "https:" ? value.trim() : void 0;
37936
+ } catch {
37937
+ return void 0;
37938
+ }
37939
+ }
37940
+
37326
37941
  // ../linkque-agent-runtime/dist/esm/impl/webSkillLoader.js
37327
37942
  var ESkillUrlScheme;
37328
37943
  (function(ESkillUrlScheme2) {
@@ -37336,12 +37951,17 @@ var DEFAULT_SCHEMES = [
37336
37951
  ESkillUrlScheme.FILE
37337
37952
  ];
37338
37953
  var WebSkillLoader = class {
37954
+ resourceResolver;
37339
37955
  root;
37340
37956
  allowedSchemes;
37341
37957
  fetchImpl;
37342
37958
  /** 缺 description 等被跳过技能的警告 sink(可选);与下载出站日志同源。 */
37343
37959
  debugLog;
37344
37960
  constructor(options) {
37961
+ this.resourceResolver = new LinkqueSkillResourceResolver({
37962
+ ...options.skillQuery,
37963
+ debugLog: options.debugLog ?? options.skillQuery?.debugLog
37964
+ });
37345
37965
  this.allowedSchemes = options.allowedSchemes ?? DEFAULT_SCHEMES;
37346
37966
  const allowsFile = this.allowedSchemes.includes(ESkillUrlScheme.FILE);
37347
37967
  if (allowsFile && (options.root === void 0 || options.root.trim() === "")) {
@@ -37352,19 +37972,29 @@ var WebSkillLoader = class {
37352
37972
  const baseFetch = options.fetchImpl ?? globalFetch;
37353
37973
  this.fetchImpl = options.debugLog ? (url2) => createHttpLoggingFetch(options.debugLog, "skill", baseFetch)(url2) : baseFetch;
37354
37974
  }
37355
- async load(resources) {
37975
+ async load(resources, observation) {
37356
37976
  if (resources.length === 0)
37357
37977
  return [];
37358
- const records = await Promise.all(resources.map((resource) => this.loadOne(resource)));
37978
+ const resolvedResources = await this.resourceResolver.resolve(resources, observation);
37979
+ const records = await Promise.all(resolvedResources.map((resource) => observeIo(() => new IoObservation(observation, ETelemetryOperationName.SKILL_RESOURCE_LOAD, {
37980
+ [ETelemetryAttribute.LINKQUE_SKILL_RESOURCE_ID]: resource.resourceId
37981
+ }), async (operation) => {
37982
+ const record2 = await this.loadOne(resource, operation.observation);
37983
+ operation.add({
37984
+ [ETelemetryAttribute.LINKQUE_SKILL_LOADED_COUNT]: record2 ? 1 : 0,
37985
+ [ETelemetryAttribute.LINKQUE_SKILL_SKIPPED_COUNT]: record2 ? 0 : 1
37986
+ });
37987
+ return record2;
37988
+ })));
37359
37989
  return records.filter((record2, idx) => {
37360
37990
  if (record2 !== void 0)
37361
37991
  return true;
37362
- this.debugLog?.(`[skill] \u8DF3\u8FC7\u8D44\u6E90 ${resources[idx]?.resourceId ?? "?"}:SKILL.md \u7F3A description(\u524D\u7F6E\u65E0\u6548),\u6309 spec \u4E0D\u52A0\u8F7D`, EDebugLogScope.SKILL);
37992
+ this.debugLog?.(`[skill] \u8DF3\u8FC7\u8D44\u6E90 ${resolvedResources[idx]?.resourceId ?? "?"}:SKILL.md \u7F3A description(\u524D\u7F6E\u65E0\u6548),\u6309 spec \u4E0D\u52A0\u8F7D`, EDebugLogScope.SKILL);
37363
37993
  return false;
37364
37994
  });
37365
37995
  }
37366
37996
  /** 加载单个 skill 资源:按 skillZipUrl 协议分发,先校验协议在 allowedSchemes 白名单内。 */
37367
- async loadOne(resource) {
37997
+ async loadOne(resource, observation) {
37368
37998
  const url2 = resource.config.skillZipUrl.trim();
37369
37999
  const scheme = detectScheme(url2);
37370
38000
  if (scheme === null || !this.allowedSchemes.includes(scheme)) {
@@ -37372,7 +38002,7 @@ var WebSkillLoader = class {
37372
38002
  }
37373
38003
  let raw;
37374
38004
  if (scheme === ESkillUrlScheme.HTTP || scheme === ESkillUrlScheme.HTTPS) {
37375
- const buf = await this.fetchZip(url2, resource.resourceId);
38005
+ const buf = await this.fetchZip(url2, resource.resourceId, observation);
37376
38006
  const files = await unzipBytes(buf, resource.resourceId);
37377
38007
  const md = extractSkillMarkdown(files);
37378
38008
  if (md === void 0) {
@@ -37409,18 +38039,24 @@ var WebSkillLoader = class {
37409
38039
  return readFile(candidate, "utf8");
37410
38040
  }
37411
38041
  /** fetch zip 字节;非 2xx 或网络失败抛错。 */
37412
- async fetchZip(url2, resourceId) {
37413
- let response;
37414
- try {
37415
- response = await this.fetchImpl(url2);
37416
- } catch (cause) {
37417
- throw new Error(`WebSkillLoader fetch \u5931\u8D25: ${url2} (resourceId=${resourceId}): ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
37418
- }
37419
- if (!response.ok) {
37420
- throw new Error(`WebSkillLoader fetch \u975E 2xx: ${response.status} ${url2} (resourceId=${resourceId})`);
37421
- }
37422
- const arrayBuffer = await response.arrayBuffer();
37423
- return new Uint8Array(arrayBuffer);
38042
+ async fetchZip(url2, resourceId, observation) {
38043
+ return observeIo(() => new IoObservation(observation, ETelemetryOperationName.SKILL_DOWNLOAD, {
38044
+ ...httpTelemetryAttributes(url2, "GET"),
38045
+ [ETelemetryAttribute.LINKQUE_SKILL_RESOURCE_ID]: resourceId
38046
+ }), async (operation) => {
38047
+ let response;
38048
+ try {
38049
+ response = await this.fetchImpl(url2);
38050
+ } catch (cause) {
38051
+ throw new Error(`WebSkillLoader fetch \u5931\u8D25: ${url2} (resourceId=${resourceId}): ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
38052
+ }
38053
+ recordHttpResponse(operation, response);
38054
+ if (!response.ok) {
38055
+ throw new Error(`WebSkillLoader fetch \u975E 2xx: ${response.status} ${url2} (resourceId=${resourceId})`);
38056
+ }
38057
+ const arrayBuffer = await response.arrayBuffer();
38058
+ return new Uint8Array(arrayBuffer);
38059
+ });
37424
38060
  }
37425
38061
  };
37426
38062
  var isZipPath = (p) => /\.zip$/i.test(p);
@@ -37531,19 +38167,32 @@ function safeStringifyArgs(args) {
37531
38167
  // ../linkque-agent-runtime/dist/esm/impl/agui/conversationBridge.js
37532
38168
  async function* streamToConversationEvents(events, ctx, options = {}) {
37533
38169
  const generateId = options.generateId ?? defaultGenerateId;
38170
+ let eventSource;
38171
+ let messageSource;
38172
+ let thinkingSource;
38173
+ const emitAgui = (base, id, source = eventSource) => {
38174
+ const output = createConversationAGUIEvent(base, id);
38175
+ try {
38176
+ if (source)
38177
+ options.eventObservations?.transfer(source, output);
38178
+ } catch {
38179
+ }
38180
+ return output;
38181
+ };
37534
38182
  yield createConversationRunAck(ctx.runId, ctx.threadId);
37535
- yield createConversationAGUIEvent({ type: EventType.RUN_STARTED, threadId: ctx.threadId, runId: ctx.runId }, void 0);
38183
+ yield emitAgui({ type: EventType.RUN_STARTED, threadId: ctx.threadId, runId: ctx.runId }, void 0);
37536
38184
  let activeMessageId;
37537
38185
  let activeThinkingId;
37538
38186
  let sawDone = false;
37539
38187
  for await (const ev of events) {
38188
+ eventSource = ev;
37540
38189
  if (ev.type === "error") {
37541
38190
  if (activeMessageId !== void 0) {
37542
- yield createConversationAGUIEvent(emitTextEnd(activeMessageId), void 0);
38191
+ yield emitAgui(emitTextEnd(activeMessageId), void 0, messageSource);
37543
38192
  activeMessageId = void 0;
37544
38193
  }
37545
38194
  if (activeThinkingId !== void 0) {
37546
- yield createConversationAGUIEvent(emitThinkingEnd(activeThinkingId), void 0);
38195
+ yield emitAgui(emitThinkingEnd(activeThinkingId), void 0, thinkingSource);
37547
38196
  activeThinkingId = void 0;
37548
38197
  }
37549
38198
  yield options.signal?.aborted ? createCancelledEvent() : createConversationTransportError({
@@ -37560,7 +38209,7 @@ async function* streamToConversationEvents(events, ctx, options = {}) {
37560
38209
  if (ev.type === "thinking") {
37561
38210
  if (activeThinkingId === void 0) {
37562
38211
  activeThinkingId = generateId();
37563
- yield createConversationAGUIEvent({
38212
+ yield emitAgui({
37564
38213
  type: EventType.THINKING_TEXT_MESSAGE_START,
37565
38214
  messageId: activeThinkingId,
37566
38215
  role: "assistant"
@@ -37568,14 +38217,14 @@ async function* streamToConversationEvents(events, ctx, options = {}) {
37568
38217
  }
37569
38218
  } else {
37570
38219
  if (activeThinkingId !== void 0) {
37571
- yield createConversationAGUIEvent(emitThinkingEnd(activeThinkingId), void 0);
38220
+ yield emitAgui(emitThinkingEnd(activeThinkingId), void 0, thinkingSource);
37572
38221
  activeThinkingId = void 0;
37573
38222
  }
37574
38223
  }
37575
38224
  if (ev.type === "delta") {
37576
38225
  if (activeMessageId === void 0) {
37577
38226
  activeMessageId = generateId();
37578
- yield createConversationAGUIEvent({
38227
+ yield emitAgui({
37579
38228
  type: EventType.TEXT_MESSAGE_START,
37580
38229
  messageId: activeMessageId,
37581
38230
  role: "assistant"
@@ -37583,20 +38232,25 @@ async function* streamToConversationEvents(events, ctx, options = {}) {
37583
38232
  }
37584
38233
  } else if (ev.type !== "thinking") {
37585
38234
  if (activeMessageId !== void 0) {
37586
- yield createConversationAGUIEvent(emitTextEnd(activeMessageId), void 0);
38235
+ yield emitAgui(emitTextEnd(activeMessageId), void 0, messageSource);
37587
38236
  activeMessageId = void 0;
37588
38237
  }
37589
38238
  }
38239
+ if (ev.type === "delta")
38240
+ messageSource = ev;
38241
+ if (ev.type === "thinking")
38242
+ thinkingSource = ev;
37590
38243
  for (const base of mapAgentEventToBaseEvents(ev, activeMessageId, activeThinkingId)) {
37591
- yield createConversationAGUIEvent(base, void 0);
38244
+ yield emitAgui(base, void 0);
37592
38245
  }
37593
38246
  }
38247
+ eventSource = void 0;
37594
38248
  if (activeMessageId !== void 0) {
37595
- yield createConversationAGUIEvent(emitTextEnd(activeMessageId), void 0);
38249
+ yield emitAgui(emitTextEnd(activeMessageId), void 0, messageSource);
37596
38250
  activeMessageId = void 0;
37597
38251
  }
37598
38252
  if (activeThinkingId !== void 0) {
37599
- yield createConversationAGUIEvent(emitThinkingEnd(activeThinkingId), void 0);
38253
+ yield emitAgui(emitThinkingEnd(activeThinkingId), void 0, thinkingSource);
37600
38254
  activeThinkingId = void 0;
37601
38255
  }
37602
38256
  if (!sawDone) {
@@ -37607,7 +38261,7 @@ async function* streamToConversationEvents(events, ctx, options = {}) {
37607
38261
  });
37608
38262
  return;
37609
38263
  }
37610
- yield createConversationAGUIEvent({ type: EventType.RUN_FINISHED, threadId: ctx.threadId, runId: ctx.runId }, void 0);
38264
+ yield emitAgui({ type: EventType.RUN_FINISHED, threadId: ctx.threadId, runId: ctx.runId }, void 0);
37611
38265
  }
37612
38266
  function createCancelledEvent() {
37613
38267
  return createConversationTransportError({
@@ -37965,6 +38619,22 @@ var MAX_ATTRIBUTE_COUNT = 64;
37965
38619
  var MAX_STRING_LENGTH = 256;
37966
38620
  var MAX_ARRAY_LENGTH = 16;
37967
38621
  var allowedAttributeKeys = /* @__PURE__ */ new Set([
38622
+ ETelemetryAttribute.LINKQUE_REMOTE_TRACE_ID,
38623
+ ETelemetryAttribute.LINKQUE_REMOTE_TRACE_ID_HEADER,
38624
+ ETelemetryAttribute.HTTP_REQUEST_METHOD,
38625
+ ETelemetryAttribute.SERVER_ADDRESS,
38626
+ ETelemetryAttribute.URL_PATH,
38627
+ ETelemetryAttribute.LINKQUE_MCP_PHASE,
38628
+ ETelemetryAttribute.LINKQUE_MCP_SERVER_NAME,
38629
+ ETelemetryAttribute.LINKQUE_IO_ATTEMPT,
38630
+ ETelemetryAttribute.LINKQUE_SKILL_RESOURCE_ID,
38631
+ ETelemetryAttribute.LINKQUE_SKILL_REQUESTED_COUNT,
38632
+ ETelemetryAttribute.LINKQUE_SKILL_LOADED_COUNT,
38633
+ ETelemetryAttribute.LINKQUE_SKILL_RESOLVED_COUNT,
38634
+ ETelemetryAttribute.LINKQUE_SKILL_SKIPPED_COUNT,
38635
+ ETelemetryAttribute.LINKQUE_CHUNK_INDEX,
38636
+ ETelemetryAttribute.LINKQUE_CHUNK_STATUS,
38637
+ ETelemetryAttribute.LINKQUE_CHUNK_LINE_COUNT,
37968
38638
  ETelemetryAttribute.HARNESS_TELEMETRY_SCHEMA_VERSION,
37969
38639
  ETelemetryAttribute.LINKQUE_TELEMETRY_SCHEMA_VERSION,
37970
38640
  ETelemetryAttribute.LINKQUE_TELEMETRY_ADAPTER_VERSION,
@@ -37986,6 +38656,8 @@ var allowedAttributeKeys = /* @__PURE__ */ new Set([
37986
38656
  ETelemetryAttribute.HARNESS_INVOCATION_ID,
37987
38657
  ETelemetryAttribute.HARNESS_ATTEMPT_ID,
37988
38658
  ETelemetryAttribute.HARNESS_ATTEMPT_VISIBILITY,
38659
+ ETelemetryAttribute.LINKQUE_APPBASE_RUN_FAILURE_STAGE,
38660
+ ETelemetryAttribute.LINKQUE_APPBASE_RUN_ERROR_MESSAGE,
37989
38661
  ETelemetryAttribute.HARNESS_ADVANCE_OUTCOME,
37990
38662
  ETelemetryAttribute.HARNESS_OPERATION_OUTCOME,
37991
38663
  ETelemetryAttribute.HARNESS_REMOTE_COMPLETION,
@@ -38063,6 +38735,7 @@ var allowedAttributeKeys = /* @__PURE__ */ new Set([
38063
38735
  ETelemetryAttribute.HTTP_RESPONSE_STATUS_CODE
38064
38736
  ]);
38065
38737
  var priorityAttributeKeys = /* @__PURE__ */ new Set([
38738
+ ETelemetryAttribute.ERROR_TYPE,
38066
38739
  ETelemetryAttribute.HARNESS_RECORD_ID,
38067
38740
  ETelemetryAttribute.HARNESS_EVENT_SEQUENCE,
38068
38741
  ETelemetryAttribute.HARNESS_ADVANCE_ID,
@@ -38072,6 +38745,8 @@ var priorityAttributeKeys = /* @__PURE__ */ new Set([
38072
38745
  ETelemetryAttribute.LINKQUE_OPERATION_NAME,
38073
38746
  ETelemetryAttribute.LINKQUE_OPERATION_DURATION_MS,
38074
38747
  ETelemetryAttribute.HARNESS_OPERATION_OUTCOME,
38748
+ ETelemetryAttribute.LINKQUE_APPBASE_RUN_FAILURE_STAGE,
38749
+ ETelemetryAttribute.LINKQUE_APPBASE_RUN_ERROR_MESSAGE,
38075
38750
  ETelemetryAttribute.HARNESS_ADVANCE_OUTCOME,
38076
38751
  ETelemetryAttribute.HARNESS_CALL_ID,
38077
38752
  ETelemetryAttribute.HARNESS_INVOCATION_ID,
@@ -38215,6 +38890,17 @@ var OtelRuntimeTelemetry = class {
38215
38890
  }
38216
38891
  }
38217
38892
  startAdvance(input) {
38893
+ return this.startOperation(input, {
38894
+ name: ETelemetryOperationName.ADVANCE,
38895
+ eventPrefix: ETelemetryEventPrefix.ADVANCE,
38896
+ attributes: {
38897
+ [ETelemetryAttribute.GEN_AI_OPERATION_NAME]: ETelemetryGenAiOperation.INVOKE_AGENT
38898
+ },
38899
+ detached: false,
38900
+ links: []
38901
+ });
38902
+ }
38903
+ startOperation(input, spec) {
38218
38904
  if (this.closed || this.outputActive || this.queue.isExporting)
38219
38905
  return new NoopRuntimeObservation();
38220
38906
  try {
@@ -38246,15 +38932,7 @@ var OtelRuntimeTelemetry = class {
38246
38932
  [ETelemetryAttribute.LINKQUE_USER_KEY]: input.context.userKey
38247
38933
  })
38248
38934
  };
38249
- return this.createOperation(state, {
38250
- name: ETelemetryOperationName.ADVANCE,
38251
- eventPrefix: ETelemetryEventPrefix.ADVANCE,
38252
- attributes: {
38253
- [ETelemetryAttribute.GEN_AI_OPERATION_NAME]: ETelemetryGenAiOperation.INVOKE_AGENT
38254
- },
38255
- detached: false,
38256
- links: []
38257
- }, void 0, input.context.parent);
38935
+ return this.createOperation(state, spec, void 0, input.context.parent);
38258
38936
  } catch {
38259
38937
  this.queue.report(ETelemetryDiagnosticCode.CAPTURE_FAILED);
38260
38938
  return new NoopRuntimeObservation();
@@ -38301,7 +38979,15 @@ var OtelRuntimeTelemetry = class {
38301
38979
  [ETelemetryAttribute.LINKQUE_SPAN_PARENT_ID]: spec.detached ? "" : parentContext?.spanId ?? ""
38302
38980
  });
38303
38981
  const span = this.tracerProvider.getTracer(ETelemetryMetadata.SCOPE_NAME, ETelemetryVersion.V1_0).startSpan(spec.name, {
38304
- kind: spec.name === ETelemetryOperationName.MODEL_ATTEMPT ? SpanKind.CLIENT : SpanKind.INTERNAL,
38982
+ kind: [
38983
+ ETelemetryOperationName.MODEL_ATTEMPT,
38984
+ ETelemetryOperationName.RUNS_WRITE,
38985
+ ETelemetryOperationName.MCP_SIGN,
38986
+ ETelemetryOperationName.MCP_OPENGW,
38987
+ ETelemetryOperationName.MCP_VERIFY,
38988
+ ETelemetryOperationName.KNOWLEDGE_SEARCH,
38989
+ ETelemetryOperationName.WEB_SEARCH
38990
+ ].includes(spec.name) ? SpanKind.CLIENT : SpanKind.INTERNAL,
38305
38991
  attributes,
38306
38992
  links: spec.links.filter((link) => validContext(link.context)).slice(0, 16).map((link) => ({
38307
38993
  context: {
@@ -38393,6 +39079,17 @@ var OtelRuntimeTelemetry = class {
38393
39079
  this.routes.delete(operation.spanContext.spanId);
38394
39080
  this.queue.release(operation.state.route);
38395
39081
  }
39082
+ /** 快照持有发送分区,直到宿主完成延迟写入后释放。 */
39083
+ retainParent(operation) {
39084
+ this.queue.retain(operation.state.route);
39085
+ let released = false;
39086
+ return () => {
39087
+ if (released)
39088
+ return;
39089
+ released = true;
39090
+ this.queue.release(operation.state.route);
39091
+ };
39092
+ }
38396
39093
  forceFlush(options) {
38397
39094
  return this.queue.forceFlush(options);
38398
39095
  }
@@ -38452,6 +39149,19 @@ var OtelObservation = class {
38452
39149
  return new NoopRuntimeObservation();
38453
39150
  return this.owner.createOperation(this.state, spec, this);
38454
39151
  }
39152
+ captureParent() {
39153
+ const releaseRoute = this.owner.retainParent(this);
39154
+ let released = false;
39155
+ return {
39156
+ operationId: this.operationId,
39157
+ spanContext: this.spanContext,
39158
+ startOperation: (spec) => released || this.lost ? new NoopRuntimeObservation() : this.owner.createOperation(this.state, spec, this),
39159
+ release: () => {
39160
+ released = true;
39161
+ releaseRoute();
39162
+ }
39163
+ };
39164
+ }
38455
39165
  record(name, attributes, body) {
38456
39166
  if (this.lost || !/^(harness|linkque)\.[a-z0-9_.]{1,128}$/.test(name))
38457
39167
  return;
@@ -38461,20 +39171,23 @@ var OtelObservation = class {
38461
39171
  finish(outcome, attributes) {
38462
39172
  if (this.ended)
38463
39173
  return;
38464
- const result = sanitizeTelemetryAttributes({
38465
- ...attributes,
38466
- [ETelemetryAttribute.HARNESS_OPERATION_OUTCOME]: outcome,
38467
- [ETelemetryAttribute.LINKQUE_OPERATION_DURATION_MS]: performance.now() - this.started
38468
- });
39174
+ this.ended = true;
38469
39175
  try {
39176
+ const result = sanitizeTelemetryAttributes({
39177
+ ...attributes,
39178
+ [ETelemetryAttribute.HARNESS_OPERATION_OUTCOME]: outcome,
39179
+ [ETelemetryAttribute.LINKQUE_OPERATION_DURATION_MS]: performance.now() - this.started
39180
+ });
38470
39181
  this.span.setAttributes(result);
38471
39182
  if (outcome === ETelemetryOutcome.ERROR || outcome === ETelemetryOutcome.TIMEOUT)
38472
39183
  this.span.setStatus({ code: SpanStatusCode.ERROR });
38473
39184
  this.record(`${this.spec.eventPrefix}.${ETelemetryEventPhase.FINISHED}`, result);
38474
- this.span.end();
38475
39185
  } finally {
38476
- this.ended = true;
38477
- this.owner.release(this);
39186
+ try {
39187
+ this.span.end();
39188
+ } finally {
39189
+ this.owner.release(this);
39190
+ }
38478
39191
  }
38479
39192
  }
38480
39193
  abandon(reason) {
@@ -38501,6 +39214,7 @@ function validContext(value) {
38501
39214
 
38502
39215
  export {
38503
39216
  EModelRequestSource,
39217
+ DataTransformExecutor,
38504
39218
  EDebugLogScope,
38505
39219
  isDebugLoggingEnabled,
38506
39220
  createRuntimeDebugLog,
@@ -38510,18 +39224,25 @@ export {
38510
39224
  EHookStage,
38511
39225
  EHookExecutorName,
38512
39226
  isJsonValue,
39227
+ cloneJsonValue,
39228
+ cloneJsonObject,
38513
39229
  isSafeJsonPointer,
38514
39230
  readJsonPointer,
39231
+ writeJsonPointer,
39232
+ validateJsonSchemaValue2 as validateJsonSchemaValue,
39233
+ normalizeCardDataValue,
39234
+ createA2UICardPipelineModelInputSchema,
38515
39235
  executeA2UICardResolver,
38516
- parseA2UIActionExecuteRequest,
38517
39236
  parseA2UIFunctionMcpExecuteRequest,
38518
39237
  stableToolName,
38519
39238
  createCardPresentationToolName,
38520
39239
  executeCardPresentation,
38521
39240
  executeCardPresentationFromSources,
39241
+ createPresentationResult,
38522
39242
  projectPresentationReceiptForModel,
38523
39243
  parseCardConfig,
38524
39244
  isAgentPresentationToolResult,
39245
+ isAgentPresentationSkippedToolResult,
38525
39246
  createPresentationDescription,
38526
39247
  readStructuredContent,
38527
39248
  normalizeMcpInputSchema,
@@ -38557,13 +39278,18 @@ export {
38557
39278
  ETelemetryModelPurpose,
38558
39279
  ETelemetryErrorType,
38559
39280
  ETelemetryGenAiOperation,
39281
+ NoopRuntimeObservation,
39282
+ NoopRuntimeTelemetry,
39283
+ skipError,
39284
+ RuntimeObservation,
39285
+ startRuntimeObservation,
39286
+ observeIo,
39287
+ IoObservation,
38560
39288
  recordContentSection,
38561
39289
  waitWithSignal,
38562
39290
  CancellationScope,
38563
39291
  McpProxyTool,
38564
39292
  executeHomeData,
38565
- CardActionDiagnostics,
38566
- executeCardAction,
38567
39293
  executeFunctionActionMcp,
38568
39294
  FOLLOW_UP_CONTEXT_MAX_HISTORY_RUNS,
38569
39295
  prepareFollowUpQuestionContext,
@@ -38573,6 +39299,9 @@ export {
38573
39299
  NoopMcpServerProvider,
38574
39300
  buildHookCommonParams,
38575
39301
  normalizeHookResources,
39302
+ observePromise,
39303
+ observeStream,
39304
+ observeEvent,
38576
39305
  warnLogFailure,
38577
39306
  HookDispatcher,
38578
39307
  DEFAULT_HOOK_DRAIN_BUDGET_MS,
@@ -38595,12 +39324,13 @@ export {
38595
39324
  createWebSearchTool,
38596
39325
  createKnowledgeTools,
38597
39326
  NoopWebSearchPort,
38598
- NoopRuntimeTelemetry,
38599
- startRuntimeObservation,
39327
+ EventObservationRegistry,
38600
39328
  abortableDelay,
38601
39329
  RemoteGatewayMcpServerProvider,
38602
39330
  LinkqueKnowledgeSearchPort,
38603
39331
  LinkqueWebSearchPort,
39332
+ isLocalSkillResource,
39333
+ LinkqueSkillResourceResolver,
38604
39334
  ESkillUrlScheme,
38605
39335
  WebSkillLoader,
38606
39336
  EventType,