linkque-cli-v2 1.3.3 → 1.3.5

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 (17) hide show
  1. package/linkquejs.js +188 -317
  2. package/package.json +1 -1
  3. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-BWCMNWG2.js → chunk-LT6VSAY4.js} +54 -41
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-JXQYQ563.js → chunk-NBYB7HSY.js} +1 -1
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-CM4N2PT3.js → chunk-VVEDZWQ5.js} +1850 -1944
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +708 -351
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +2 -2
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +2 -2
  9. package/vendor/linkque-agent-appwrite-integrate/package.json +1 -1
  10. package/worker.js +892 -616
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{anthropic-messages-5DOLTIGP.js → anthropic-messages-EL2IU4YU.js} +3 -3
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{azure-openai-responses-HVAVRLTK.js → azure-openai-responses-A4XURCOX.js} +1 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-UJBDG2KY.js → mistral-conversations-TQA2MPJJ.js} +10 -10
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-codex-responses-3KOC6KHN.js → openai-codex-responses-WLREQPZK.js} +1 -1
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-completions-HG6OJRL5.js → openai-completions-U6LUBY4P.js} +3 -3
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-responses-F6V2PG3Y.js → openai-responses-SFZAU5JA.js} +1 -1
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{pi-messages-DC4DVRAJ.js → pi-messages-QQA6ZGV2.js} +3 -3
@@ -4250,13 +4250,14 @@ var require_fast_uri = __commonJS({
4250
4250
  if (!malformedIPLiteral) {
4251
4251
  malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
4252
4252
  }
4253
- if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
4254
- if (uri.indexOf("%") !== -1) {
4255
- if (parsed.host !== void 0 && !malformedIPLiteral) {
4256
- const host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
4257
- parsed.host = reescapeHostDelimiters(host, isIP);
4258
- }
4253
+ if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) {
4254
+ let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
4255
+ if (!isIP) {
4256
+ host = normalizePercentEncoding(host.toLowerCase());
4259
4257
  }
4258
+ parsed.host = reescapeHostDelimiters(host, isIP);
4259
+ }
4260
+ if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
4260
4261
  if (parsed.path) {
4261
4262
  parsed.path = normalizePathEncoding(parsed.path);
4262
4263
  }
@@ -8866,6 +8867,164 @@ var EHookExecutorName;
8866
8867
  EHookExecutorName2["ImageUnderstandingHookExecutor"] = "ImageUnderstandingHookExecutor";
8867
8868
  })(EHookExecutorName || (EHookExecutorName = {}));
8868
8869
 
8870
+ // ../linkque-agent-runtime/dist/esm/core/followUpQuestions.js
8871
+ var FOLLOW_UP_QUESTION_MAX_COUNT = 3;
8872
+ var FOLLOW_UP_QUESTION_MAX_LENGTH = 20;
8873
+ var FOLLOW_UP_CONTEXT_MAX_HISTORY_RUNS = 2;
8874
+ var FOLLOW_UP_CONTEXT_TOKEN_BUDGET = 2e3;
8875
+ function prepareFollowUpQuestionContext(turns, history = []) {
8876
+ const visible = turns.flatMap((turn) => {
8877
+ if (turn.role !== "user" && turn.role !== "assistant")
8878
+ return [];
8879
+ if (typeof turn.content !== "string")
8880
+ return [];
8881
+ const content = turn.content.replace(/\s+/gu, " ").trim();
8882
+ return content ? [{ role: turn.role, content }] : [];
8883
+ });
8884
+ let assistantIndex = -1;
8885
+ let userIndex = -1;
8886
+ for (let index = visible.length - 1; index >= 0; index -= 1) {
8887
+ if (assistantIndex < 0 && visible[index].role === "assistant") {
8888
+ assistantIndex = index;
8889
+ continue;
8890
+ }
8891
+ if (assistantIndex >= 0 && index < assistantIndex && visible[index].role === "user") {
8892
+ userIndex = index;
8893
+ break;
8894
+ }
8895
+ }
8896
+ if (userIndex < 0 || assistantIndex < 0)
8897
+ return void 0;
8898
+ const lastUserMessage = visible[userIndex].content;
8899
+ const assistantTokens = estimateTokens(visible[assistantIndex].content);
8900
+ const userTokens = estimateTokens(lastUserMessage);
8901
+ const assistantBudget = Math.min(assistantTokens, 1500);
8902
+ const userBudget = Math.min(userTokens, FOLLOW_UP_CONTEXT_TOKEN_BUDGET - assistantBudget);
8903
+ let remaining = FOLLOW_UP_CONTEXT_TOKEN_BUDGET - assistantBudget - userBudget;
8904
+ const messages = [
8905
+ {
8906
+ role: "user",
8907
+ content: truncateToEstimatedTokens(lastUserMessage, userBudget)
8908
+ },
8909
+ {
8910
+ role: "assistant",
8911
+ content: truncateToEstimatedTokens(visible[assistantIndex].content, assistantBudget)
8912
+ }
8913
+ ];
8914
+ const normalizedHistory = history.slice(-FOLLOW_UP_CONTEXT_MAX_HISTORY_RUNS).map(normalizeHistoryEntry).filter((entry) => Boolean(entry));
8915
+ const selectedHistory = [];
8916
+ for (let index = normalizedHistory.length - 1; index >= 0; index -= 1) {
8917
+ if (remaining <= 0)
8918
+ break;
8919
+ const entry = normalizedHistory[index];
8920
+ let entryRemaining = remaining;
8921
+ const followUpQuestions = [];
8922
+ for (const question of entry.followUpQuestions) {
8923
+ const tokens = estimateTokens(question);
8924
+ if (tokens > entryRemaining)
8925
+ break;
8926
+ followUpQuestions.push(question);
8927
+ entryRemaining -= tokens;
8928
+ }
8929
+ const userMessage = truncateToEstimatedTokens(entry.userMessage, entryRemaining);
8930
+ if (!userMessage)
8931
+ continue;
8932
+ entryRemaining -= estimateTokens(userMessage);
8933
+ remaining = entryRemaining;
8934
+ selectedHistory.unshift({ userMessage, followUpQuestions });
8935
+ }
8936
+ return {
8937
+ messages,
8938
+ lastUserMessage,
8939
+ ...selectedHistory.length ? { history: selectedHistory } : {}
8940
+ };
8941
+ }
8942
+ function normalizeHistoryEntry(entry) {
8943
+ const userMessage = entry.userMessage.replace(/\s+/gu, " ").trim();
8944
+ if (!userMessage)
8945
+ return void 0;
8946
+ return {
8947
+ userMessage,
8948
+ followUpQuestions: normalizeFollowUpQuestionStrings(entry.followUpQuestions)
8949
+ };
8950
+ }
8951
+ function normalizeFollowUpQuestionStrings(value) {
8952
+ if (!Array.isArray(value))
8953
+ return [];
8954
+ const seen = /* @__PURE__ */ new Set();
8955
+ const result = [];
8956
+ for (const candidate of value) {
8957
+ if (typeof candidate !== "string")
8958
+ continue;
8959
+ const normalized = candidate.replace(/\s+/gu, " ").trim();
8960
+ if (!normalized || normalized.length > FOLLOW_UP_QUESTION_MAX_LENGTH || seen.has(normalized))
8961
+ continue;
8962
+ seen.add(normalized);
8963
+ result.push(normalized);
8964
+ if (result.length === FOLLOW_UP_QUESTION_MAX_COUNT)
8965
+ break;
8966
+ }
8967
+ return result;
8968
+ }
8969
+ function estimateTokens(text) {
8970
+ let tokens = 0;
8971
+ let asciiRun = 0;
8972
+ const flushAscii = () => {
8973
+ if (asciiRun > 0)
8974
+ tokens += Math.ceil(asciiRun / 4);
8975
+ asciiRun = 0;
8976
+ };
8977
+ for (const character of text) {
8978
+ if (/^[\x20-\x7e]$/u.test(character))
8979
+ asciiRun += 1;
8980
+ else {
8981
+ flushAscii();
8982
+ tokens += 1;
8983
+ }
8984
+ }
8985
+ flushAscii();
8986
+ return Math.max(tokens, 1);
8987
+ }
8988
+ function truncateToEstimatedTokens(text, budget) {
8989
+ if (estimateTokens(text) <= budget)
8990
+ return text;
8991
+ let low = 0;
8992
+ let high = text.length;
8993
+ while (low < high) {
8994
+ const middle = Math.ceil((low + high) / 2);
8995
+ if (estimateTokens(text.slice(0, middle)) <= budget)
8996
+ low = middle;
8997
+ else
8998
+ high = middle - 1;
8999
+ }
9000
+ return text.slice(0, low).trim();
9001
+ }
9002
+
9003
+ // ../linkque-agent-runtime/dist/esm/core/types.js
9004
+ var EDebugLogScope;
9005
+ (function(EDebugLogScope2) {
9006
+ EDebugLogScope2["A2UI_ACTION"] = "A2UI_ACTION";
9007
+ EDebugLogScope2["CONFIG"] = "CONFIG";
9008
+ EDebugLogScope2["LLM"] = "LLM";
9009
+ EDebugLogScope2["PI_EVENT"] = "PI_EVENT";
9010
+ EDebugLogScope2["MCP"] = "MCP";
9011
+ EDebugLogScope2["HTTP"] = "HTTP";
9012
+ EDebugLogScope2["HOOK"] = "HOOK";
9013
+ })(EDebugLogScope || (EDebugLogScope = {}));
9014
+
9015
+ // ../linkque-agent-runtime/dist/esm/core/cardTools.js
9016
+ import { randomUUID } from "node:crypto";
9017
+
9018
+ // ../agent-a2ui-card-contract/dist/esm/protocol.js
9019
+ var LINKQUE_A2UI_V4_CATALOG_ID = "urn:linkque:a2ui:runtime:4";
9020
+
9021
+ // ../agent-a2ui-card-contract/dist/esm/types.js
9022
+ var A2UI_CARD_TRANSFORM_LANGUAGE = "jmespath";
9023
+ var A2UI_CARD_TRANSFORM_PROFILE = "linkque-structural-v1";
9024
+ var A2UI_CARD_EXPRESSION_MAX_LENGTH = 4096;
9025
+ var A2UI_CARD_EXPRESSION_MAX_AST_NODES = 512;
9026
+ var A2UI_CARD_EXPRESSION_MAX_AST_DEPTH = 32;
9027
+
8869
9028
  // ../linkque-agent-data-binding-contract/dist/esm/json.js
8870
9029
  var BLOCKED_PATH_SEGMENTS = /* @__PURE__ */ new Set([
8871
9030
  "__proto__",
@@ -8991,6 +9150,21 @@ function getJsonSchemaIssues(value, path2 = "schema") {
8991
9150
  function isObjectJsonSchema(value) {
8992
9151
  return isPlainRecord(value) && value.type === "object" && getJsonSchemaIssues(value).length === 0;
8993
9152
  }
9153
+ function validateJsonSchemaValue(schema, value, path2 = "$") {
9154
+ let validate;
9155
+ try {
9156
+ validate = ajv.compile(schema);
9157
+ } catch (error) {
9158
+ return [
9159
+ issue(path2, "INVALID_JSON_SCHEMA", error instanceof Error ? error.message : "schema is invalid")
9160
+ ];
9161
+ }
9162
+ return validate(value) ? [] : (validate.errors ?? []).map(errorToIssue.bind(null, path2));
9163
+ }
9164
+ function errorToIssue(root, error) {
9165
+ const suffix = error.instancePath.split("/").filter(Boolean).map((segment) => segment.replace(/~1/gu, "/").replace(/~0/gu, "~")).map((segment) => `[${JSON.stringify(segment)}]`).join("");
9166
+ return issue(`${root}${suffix}`, "JSON_SCHEMA_VALUE_INVALID", error.message ?? "value does not match schema");
9167
+ }
8994
9168
 
8995
9169
  // ../linkque-agent-data-binding-contract/dist/esm/structural.js
8996
9170
  var import_jmespath = __toESM(require_jmespath(), 1);
@@ -9172,343 +9346,28 @@ function issue2(path2, code, message) {
9172
9346
  function exactKeys(value, allowed, path2, issues) {
9173
9347
  }
9174
9348
 
9175
- // ../agent-a2ui-card-contract/dist/esm/payment-action.js
9176
- var A2UI_PAYMENT_ACTION_NAME = "payment.trade-pay";
9177
- var A2UI_PAYMENT_RESULT_EVENT_NAME = "payment.result";
9178
- var A2UI_PAYMENT_CALLBACK_MAX_BYTES = 16 * 1024;
9179
- var A2UIActionContractError = class extends Error {
9180
- constructor(issues) {
9181
- super(issues.join("; "));
9182
- Object.defineProperty(this, "issues", {
9183
- enumerable: true,
9184
- configurable: true,
9185
- writable: true,
9186
- value: issues
9187
- });
9188
- Object.defineProperty(this, "code", {
9189
- enumerable: true,
9190
- configurable: true,
9191
- writable: true,
9192
- value: "A2UI_ACTION_CONTRACT_INVALID"
9193
- });
9194
- this.name = "A2UIActionContractError";
9195
- }
9196
- };
9197
- function parseA2UIActionExecuteRequest(value) {
9198
- const issues = getA2UIActionExecuteRequestIssues(value);
9199
- if (issues.length)
9200
- throw new A2UIActionContractError(issues);
9201
- return JSON.parse(JSON.stringify(value));
9202
- }
9203
- function getA2UIActionExecuteRequestIssues(value) {
9204
- if (!isPlainRecord(value))
9205
- return ["request must be an object"];
9206
- const issues = [];
9207
- rejectExtraKeysAsStrings(value, [
9208
- "schemaVersion",
9209
- "agentId",
9210
- "threadId",
9211
- "invocationId",
9212
- "actionId",
9213
- "source",
9214
- "actionContext"
9215
- ], "request", issues);
9216
- if (value.schemaVersion !== "1")
9217
- issues.push("schemaVersion must be 1");
9218
- requiredIdentifier(value.agentId, "agentId", issues);
9219
- requiredIdentifier(value.threadId, "threadId", issues);
9220
- requiredIdentifier(value.invocationId, "invocationId", issues);
9221
- requiredIdentifier(value.actionId, "actionId", issues);
9222
- validateSource(value.source, issues);
9223
- if (!cloneJsonObject(value.actionContext)) {
9224
- issues.push("actionContext must be a JSON object");
9225
- }
9226
- return issues;
9227
- }
9228
- function parseA2UIPaymentResultEventPayload(value) {
9229
- if (!isPlainRecord(value)) {
9230
- throw new A2UIActionContractError([
9231
- "payment result payload must be an object"
9232
- ]);
9233
- }
9234
- const issues = [];
9235
- rejectExtraKeysAsStrings(value, ["actionId", "actionInvocationId", "tradeNO", "actionContext", "callback"], "payment result payload", issues);
9236
- requiredIdentifier(value.actionId, "actionId", issues);
9237
- requiredIdentifier(value.actionInvocationId, "actionInvocationId", issues);
9238
- if (typeof value.tradeNO !== "string" || !value.tradeNO.trim() || value.tradeNO.length > 64) {
9239
- issues.push("tradeNO must be a non-empty string up to 64 characters");
9240
- }
9241
- if (!cloneJsonObject(value.actionContext)) {
9242
- issues.push("actionContext must be a JSON object");
9243
- }
9244
- const callback = cloneJsonObject(value.callback);
9245
- if (!callback || typeof callback.resultCode !== "string") {
9246
- issues.push("callback.resultCode must be a string");
9247
- } else if (new TextEncoder().encode(JSON.stringify(callback)).byteLength > A2UI_PAYMENT_CALLBACK_MAX_BYTES) {
9248
- issues.push(`callback must not exceed ${A2UI_PAYMENT_CALLBACK_MAX_BYTES} bytes`);
9249
- }
9250
- if (issues.length)
9251
- throw new A2UIActionContractError(issues);
9252
- return JSON.parse(JSON.stringify(value));
9253
- }
9254
- function getA2UICardActionBindingIssues(value, path2 = "actionBindings") {
9255
- if (!Array.isArray(value)) {
9256
- return [
9257
- issue2(path2, "INVALID_ACTION_BINDINGS", "actionBindings must be an array")
9258
- ];
9259
- }
9349
+ // ../agent-a2ui-card-contract/dist/esm/binding-analyzer.js
9350
+ var INPUT_COMPONENTS = /* @__PURE__ */ new Set(["ChoicePicker", "Stepper", "TextField"]);
9351
+ function analyzeA2UIBindings(protocol) {
9260
9352
  const issues = [];
9261
- const actionIds = /* @__PURE__ */ new Set();
9262
- value.forEach((candidate, index) => {
9263
- const itemPath = `${path2}[${index}]`;
9264
- if (!isPlainRecord(candidate)) {
9265
- issues.push(issue2(itemPath, "INVALID_ACTION_BINDING", "action binding must be an object"));
9353
+ const occurrences = [];
9354
+ const surfaces = /* @__PURE__ */ new Set();
9355
+ const componentsBySurface = /* @__PURE__ */ new Map();
9356
+ protocol.forEach((message, messageIndex) => {
9357
+ if (!isPlainRecord(message) || !Array.isArray(message.datas)) {
9358
+ issues.push(issue2(`card[${messageIndex}]`, "INVALID_A2UI_MESSAGE", "A2UI message must contain a datas array"));
9266
9359
  return;
9267
9360
  }
9268
- if (!isSafeIdentifier(candidate.actionId)) {
9269
- issues.push(issue2(`${itemPath}.actionId`, "INVALID_ACTION_ID", "actionId is invalid"));
9270
- } else if (actionIds.has(candidate.actionId)) {
9271
- issues.push(issue2(`${itemPath}.actionId`, "DUPLICATE_ACTION_ID", "actionId must be unique"));
9272
- } else {
9273
- actionIds.add(candidate.actionId);
9274
- }
9275
- if (candidate.kind !== "payment") {
9276
- issues.push(issue2(`${itemPath}.kind`, "INVALID_ACTION_KIND", "kind must be payment"));
9277
- return;
9361
+ if (message.version !== "0.9") {
9362
+ issues.push(issue2(`card[${messageIndex}].version`, "UNSUPPORTED_PROTOCOL_VERSION", "A2UI card resources must use protocol version 0.9"));
9278
9363
  }
9279
- rejectExtraKeys(candidate, ["actionId", "kind", "createTrade", "queryTrade"], itemPath, issues);
9280
- validateToolBinding(candidate.createTrade, `${itemPath}.createTrade`, "create", issues);
9281
- validateToolBinding(candidate.queryTrade, `${itemPath}.queryTrade`, "query", issues);
9282
- });
9283
- return issues;
9284
- }
9285
- function getA2UIPaymentActionReferenceIssues(card, bindings, path2 = "a2uiTemplate.content") {
9286
- const issues = [];
9287
- const bindingIds = new Set(bindings.map((binding) => binding.actionId));
9288
- const referenced = /* @__PURE__ */ new Set();
9289
- card.forEach((message, messageIndex) => {
9290
9364
  message.datas.forEach((instruction, instructionIndex) => {
9291
- const instructionRecord = instruction;
9292
- const update = isPlainRecord(instructionRecord.updateComponents) ? instructionRecord.updateComponents : void 0;
9293
- const components = update && Array.isArray(update.components) ? update.components : [];
9294
- components.forEach((component, componentIndex) => {
9295
- if (!isPlainRecord(component))
9296
- return;
9297
- collectPaymentActionReferences(component.action, `${path2}[${messageIndex}].datas[${instructionIndex}].updateComponents.components[${componentIndex}].action`, referenced, issues);
9298
- });
9299
- });
9300
- });
9301
- for (const actionId of referenced) {
9302
- if (!bindingIds.has(actionId)) {
9303
- issues.push(issue2(path2, "PAYMENT_ACTION_BINDING_MISSING", `payment action ${actionId} has no action binding`));
9304
- }
9305
- }
9306
- for (const actionId of bindingIds) {
9307
- if (!referenced.has(actionId)) {
9308
- issues.push(issue2(path2, "PAYMENT_ACTION_UNUSED", `payment action binding ${actionId} is not referenced`));
9309
- }
9310
- }
9311
- return issues;
9312
- }
9313
- function validateToolBinding(value, path2, phase, issues) {
9314
- if (!isPlainRecord(value)) {
9315
- issues.push(issue2(path2, "INVALID_PAYMENT_TOOL", `${path2} must be an object`));
9316
- return;
9317
- }
9318
- rejectExtraKeys(value, phase === "create" ? ["mcpResourceId", "toolName", "inputBindings", "tradeNoPath"] : [
9319
- "mcpResourceId",
9320
- "toolName",
9321
- "inputBindings",
9322
- "statusPath",
9323
- "paidValues"
9324
- ], path2, issues);
9325
- if (!isSafeIdentifier(value.mcpResourceId)) {
9326
- issues.push(issue2(`${path2}.mcpResourceId`, "INVALID_MCP_RESOURCE_ID", "mcpResourceId is invalid"));
9327
- }
9328
- if (typeof value.toolName !== "string" || !value.toolName.trim()) {
9329
- issues.push(issue2(`${path2}.toolName`, "INVALID_TOOL_NAME", "toolName is required"));
9330
- }
9331
- validateInputBindings(value.inputBindings, `${path2}.inputBindings`, phase, issues);
9332
- if (phase === "create") {
9333
- if (!isSafeJsonPointer(value.tradeNoPath)) {
9334
- issues.push(issue2(`${path2}.tradeNoPath`, "INVALID_TRADE_NO_PATH", "tradeNoPath must be an absolute JSON Pointer"));
9335
- }
9336
- return;
9337
- }
9338
- if (!isSafeJsonPointer(value.statusPath)) {
9339
- issues.push(issue2(`${path2}.statusPath`, "INVALID_PAYMENT_STATUS_PATH", "statusPath must be an absolute JSON Pointer"));
9340
- }
9341
- if (!Array.isArray(value.inputBindings) || !value.inputBindings.some((binding) => isPlainRecord(binding) && isPlainRecord(binding.source) && binding.source.kind === "trade-no")) {
9342
- issues.push(issue2(`${path2}.inputBindings`, "PAYMENT_TRADE_NO_BINDING_MISSING", "queryTrade must map tradeNO"));
9343
- }
9344
- if (!Array.isArray(value.paidValues) || value.paidValues.length === 0 || value.paidValues.some((entry) => !isJsonPrimitive(entry))) {
9345
- issues.push(issue2(`${path2}.paidValues`, "INVALID_PAID_VALUES", "paidValues must contain JSON primitives"));
9346
- }
9347
- }
9348
- function collectPaymentActionReferences(value, path2, referenced, issues) {
9349
- if (!isPlainRecord(value))
9350
- return;
9351
- if (isPlainRecord(value.client) && value.client.name === A2UI_PAYMENT_ACTION_NAME) {
9352
- const context = value.client.context;
9353
- if (!isPlainRecord(context) || !isSafeIdentifier(context.actionId)) {
9354
- issues.push(issue2(path2, "INVALID_PAYMENT_ACTION", "payment action requires a safe actionId"));
9355
- return;
9356
- }
9357
- rejectExtraKeys(context, ["actionId", "actionContext"], `${path2}.client.context`, issues);
9358
- if (!isPlainRecord(context.actionContext)) {
9359
- issues.push(issue2(path2, "INVALID_PAYMENT_ACTION", "payment action requires an object actionContext"));
9360
- }
9361
- referenced.add(context.actionId);
9362
- return;
9363
- }
9364
- if (!isPlainRecord(value.select))
9365
- return;
9366
- if (Array.isArray(value.select.cases)) {
9367
- value.select.cases.forEach((entry, index) => {
9368
- if (isPlainRecord(entry)) {
9369
- collectPaymentActionReferences(entry.action, `${path2}.select.cases[${index}].action`, referenced, issues);
9370
- }
9371
- });
9372
- }
9373
- collectPaymentActionReferences(value.select.default, `${path2}.select.default`, referenced, issues);
9374
- }
9375
- function validateInputBindings(value, path2, phase, issues) {
9376
- if (!Array.isArray(value) || value.length > 128) {
9377
- issues.push(issue2(path2, "INVALID_PAYMENT_INPUT_BINDINGS", "inputBindings must be an array of at most 128 entries"));
9378
- return;
9379
- }
9380
- const targets = /* @__PURE__ */ new Set();
9381
- value.forEach((candidate, index) => {
9382
- const itemPath = `${path2}[${index}]`;
9383
- if (!isPlainRecord(candidate) || !isSafeJsonPointer(candidate.inputPath)) {
9384
- issues.push(issue2(itemPath, "INVALID_PAYMENT_INPUT_BINDING", "inputPath must be an absolute JSON Pointer"));
9385
- return;
9386
- }
9387
- rejectExtraKeys(candidate, ["inputPath", "source"], itemPath, issues);
9388
- if (targets.has(candidate.inputPath)) {
9389
- issues.push(issue2(`${itemPath}.inputPath`, "DUPLICATE_PAYMENT_INPUT_PATH", "inputPath must be unique"));
9390
- }
9391
- targets.add(candidate.inputPath);
9392
- validateInputSource(candidate.source, `${itemPath}.source`, phase, issues);
9393
- });
9394
- }
9395
- function validateInputSource(value, path2, phase, issues) {
9396
- if (!isPlainRecord(value) || typeof value.kind !== "string") {
9397
- issues.push(issue2(path2, "INVALID_PAYMENT_INPUT_SOURCE", "source must be an object"));
9398
- return;
9399
- }
9400
- if (value.kind === "action-context") {
9401
- rejectExtraKeys(value, ["kind", "path"], path2, issues);
9402
- if (!isSafeJsonPointer(value.path, true)) {
9403
- issues.push(issue2(`${path2}.path`, "INVALID_PAYMENT_SOURCE_PATH", "action context path must be a JSON Pointer"));
9404
- }
9405
- return;
9406
- }
9407
- if (value.kind === "runtime-context") {
9408
- rejectExtraKeys(value, ["kind", "key"], path2, issues);
9409
- if (!RUNTIME_CONTEXT_KEYS.has(String(value.key))) {
9410
- issues.push(issue2(`${path2}.key`, "INVALID_RUNTIME_CONTEXT_KEY", "runtime context key is unsupported"));
9411
- }
9412
- return;
9413
- }
9414
- if (value.kind === "literal") {
9415
- rejectExtraKeys(value, ["kind", "value"], path2, issues);
9416
- if (!isJsonValue(value.value)) {
9417
- issues.push(issue2(`${path2}.value`, "INVALID_PAYMENT_LITERAL", "literal must be JSON"));
9418
- }
9419
- return;
9420
- }
9421
- if (phase === "query" && value.kind === "trade-no") {
9422
- rejectExtraKeys(value, ["kind"], path2, issues);
9423
- return;
9424
- }
9425
- if (phase === "query" && value.kind === "callback") {
9426
- rejectExtraKeys(value, ["kind", "path"], path2, issues);
9427
- if (!isSafeJsonPointer(value.path, true)) {
9428
- issues.push(issue2(`${path2}.path`, "INVALID_PAYMENT_CALLBACK_PATH", "callback path must be a JSON Pointer"));
9429
- }
9430
- return;
9431
- }
9432
- issues.push(issue2(path2, "INVALID_PAYMENT_INPUT_SOURCE", `${value.kind} is unavailable for ${phase}`));
9433
- }
9434
- function rejectExtraKeys(value, allowed, path2, issues) {
9435
- const allowedKeys = new Set(allowed);
9436
- for (const key of Object.keys(value)) {
9437
- if (!allowedKeys.has(key)) {
9438
- issues.push(issue2(`${path2}.${key}`, "UNEXPECTED_ACTION_BINDING_FIELD", `${key} is not allowed`));
9439
- }
9440
- }
9441
- }
9442
- function validateSource(value, issues) {
9443
- if (!isPlainRecord(value)) {
9444
- issues.push("source must be an object");
9445
- return;
9446
- }
9447
- rejectExtraKeysAsStrings(value, ["cardRef", "cardRevision", "cardInstanceId", "surfaceId", "componentId"], "source", issues);
9448
- requiredIdentifier(value.cardRef, "source.cardRef", issues);
9449
- requiredIdentifier(value.cardRevision, "source.cardRevision", issues);
9450
- requiredText(value.cardInstanceId, "source.cardInstanceId", issues);
9451
- requiredIdentifier(value.surfaceId, "source.surfaceId", issues);
9452
- requiredIdentifier(value.componentId, "source.componentId", issues);
9453
- }
9454
- function rejectExtraKeysAsStrings(value, allowed, path2, issues) {
9455
- const allowedKeys = new Set(allowed);
9456
- for (const key of Object.keys(value)) {
9457
- if (!allowedKeys.has(key))
9458
- issues.push(`${path2}.${key} is not allowed`);
9459
- }
9460
- }
9461
- function requiredIdentifier(value, path2, issues) {
9462
- if (!isSafeIdentifier(value))
9463
- issues.push(`${path2} must be a safe identifier`);
9464
- }
9465
- function requiredText(value, path2, issues) {
9466
- if (typeof value !== "string" || !value.trim() || value.length > 256) {
9467
- issues.push(`${path2} must be a non-empty string up to 256 characters`);
9468
- }
9469
- }
9470
- function isJsonPrimitive(value) {
9471
- return value === null || ["string", "number", "boolean"].includes(typeof value);
9472
- }
9473
- var RUNTIME_CONTEXT_KEYS = /* @__PURE__ */ new Set([
9474
- "agentId",
9475
- "tenantId",
9476
- "threadId",
9477
- "userId"
9478
- ]);
9479
-
9480
- // ../agent-a2ui-card-contract/dist/esm/protocol.js
9481
- var LINKQUE_A2UI_V4_CATALOG_ID = "urn:linkque:a2ui:runtime:4";
9482
-
9483
- // ../agent-a2ui-card-contract/dist/esm/types.js
9484
- var A2UI_CARD_TRANSFORM_LANGUAGE = "jmespath";
9485
- var A2UI_CARD_TRANSFORM_PROFILE = "linkque-structural-v1";
9486
- var A2UI_CARD_EXPRESSION_MAX_LENGTH = 4096;
9487
- var A2UI_CARD_EXPRESSION_MAX_AST_NODES = 512;
9488
- var A2UI_CARD_EXPRESSION_MAX_AST_DEPTH = 32;
9489
-
9490
- // ../agent-a2ui-card-contract/dist/esm/binding-analyzer.js
9491
- var INPUT_COMPONENTS = /* @__PURE__ */ new Set(["ChoicePicker", "Stepper", "TextField"]);
9492
- function analyzeA2UIBindings(protocol) {
9493
- const issues = [];
9494
- const occurrences = [];
9495
- const surfaces = /* @__PURE__ */ new Set();
9496
- const componentsBySurface = /* @__PURE__ */ new Map();
9497
- protocol.forEach((message, messageIndex) => {
9498
- if (!isPlainRecord(message) || !Array.isArray(message.datas)) {
9499
- issues.push(issue2(`card[${messageIndex}]`, "INVALID_A2UI_MESSAGE", "A2UI message must contain a datas array"));
9500
- return;
9501
- }
9502
- if (message.version !== "0.9") {
9503
- issues.push(issue2(`card[${messageIndex}].version`, "UNSUPPORTED_PROTOCOL_VERSION", "A2UI card resources must use protocol version 0.9"));
9504
- }
9505
- message.datas.forEach((instruction, instructionIndex) => {
9506
- if (!isPlainRecord(instruction)) {
9507
- issues.push(issue2(`card[${messageIndex}].datas[${instructionIndex}]`, "INVALID_A2UI_INSTRUCTION", "instruction must be an object"));
9508
- return;
9509
- }
9510
- if ("createSurface" in instruction) {
9511
- if (!isPlainRecord(instruction.createSurface))
9365
+ if (!isPlainRecord(instruction)) {
9366
+ issues.push(issue2(`card[${messageIndex}].datas[${instructionIndex}]`, "INVALID_A2UI_INSTRUCTION", "instruction must be an object"));
9367
+ return;
9368
+ }
9369
+ if ("createSurface" in instruction) {
9370
+ if (!isPlainRecord(instruction.createSurface))
9512
9371
  return;
9513
9372
  const surfaceId = instruction.createSurface.surfaceId;
9514
9373
  if (!isSafeIdentifier(surfaceId)) {
@@ -10353,6 +10212,54 @@ function getA2UIV4ProtocolIssues(value, path2 = "card") {
10353
10212
  validateReferences(surfaces, path2, issues);
10354
10213
  return issues;
10355
10214
  }
10215
+ function validateV4Component(component, componentPath, issues) {
10216
+ const schema = A2UI_V4_COMPONENT_CATALOG.components[component.component];
10217
+ if (!schema) {
10218
+ issues.push(issue2(`${componentPath}.component`, "UNSUPPORTED_COMPONENT", `V4 does not support component ${component.component}`));
10219
+ return;
10220
+ }
10221
+ const allowed = /* @__PURE__ */ new Set([
10222
+ "id",
10223
+ "component",
10224
+ ...Object.keys(schema.properties)
10225
+ ]);
10226
+ for (const key of Object.keys(component))
10227
+ if (!allowed.has(key))
10228
+ issues.push(issue2(`${componentPath}.${key}`, "UNSUPPORTED_COMPONENT_PROP", `${component.component} does not support property ${key}`));
10229
+ for (const [name, property] of Object.entries(schema.properties)) {
10230
+ const value = component[name];
10231
+ if (property.required && value === void 0)
10232
+ issues.push(issue2(`${componentPath}.${name}`, "REQUIRED_COMPONENT_PROP_MISSING", `${component.component}.${name} is required`));
10233
+ if (value !== void 0)
10234
+ validateProperty(value, property, `${componentPath}.${name}`, issues, name);
10235
+ }
10236
+ if (component["x2-overflow"] !== void 0)
10237
+ validateOverflow(component, componentPath, issues);
10238
+ if (component.component === "TextField")
10239
+ validateTextField(component, componentPath, issues);
10240
+ if (component.component === "ChoicePicker") {
10241
+ if (!isStrictBinding(component.value))
10242
+ issues.push(issue2(`${componentPath}.value`, "INPUT_REQUIRES_BINDING", "ChoicePicker.value must be a strict writable binding"));
10243
+ validateOptions(component.options, `${componentPath}.options`, issues);
10244
+ }
10245
+ if (component.component === "Stepper")
10246
+ validateStepper(component, componentPath, issues);
10247
+ if (["Card", "Row", "Column", "List"].includes(component.component)) {
10248
+ for (const axis of ["width", "height"]) {
10249
+ const value = component[axis];
10250
+ const modes = axis === "width" ? ["fit", "fill"] : ["auto"];
10251
+ if (value !== void 0 && !(typeof value === "string" && (modes.includes(value) || /^\d+(?:\.\d+)?px$/.test(value) && Number.isFinite(parseFloat(value))))) {
10252
+ issues.push(issue2(`${componentPath}.${axis}`, "INVALID_COMPONENT_PROP_VALUE", `size must be ${modes.join(" / ")} or a non-negative px string such as 120px`));
10253
+ }
10254
+ }
10255
+ }
10256
+ if (component.checks !== void 0)
10257
+ validateChecks(component.checks, `${componentPath}.checks`, issues);
10258
+ if (component.format !== void 0 && component.component === "Text")
10259
+ validateNumberFormat(component.format, `${componentPath}.format`, issues);
10260
+ if (component.action !== void 0)
10261
+ validateAction(component.action, `${componentPath}.action`, issues, 0);
10262
+ }
10356
10263
  function validateComponents(payload, path2, surfaces, issues) {
10357
10264
  if (!Array.isArray(payload.components)) {
10358
10265
  issues.push(issue2(`${path2}.updateComponents.components`, "INVALID_A2UI_COMPONENTS", "components must be an array"));
@@ -10369,52 +10276,7 @@ function validateComponents(payload, path2, surfaces, issues) {
10369
10276
  if (surface.has(component.id))
10370
10277
  issues.push(issue2(`${componentPath}.id`, "DUPLICATE_COMPONENT_ID", `component id ${component.id} is duplicated`));
10371
10278
  surface.set(component.id, component);
10372
- const schema = A2UI_V4_COMPONENT_CATALOG.components[component.component];
10373
- if (!schema) {
10374
- issues.push(issue2(`${componentPath}.component`, "UNSUPPORTED_COMPONENT", `V4 does not support component ${component.component}`));
10375
- return;
10376
- }
10377
- const allowed = /* @__PURE__ */ new Set([
10378
- "id",
10379
- "component",
10380
- ...Object.keys(schema.properties)
10381
- ]);
10382
- for (const key of Object.keys(component))
10383
- if (!allowed.has(key))
10384
- issues.push(issue2(`${componentPath}.${key}`, "UNSUPPORTED_COMPONENT_PROP", `${component.component} does not support property ${key}`));
10385
- for (const [name, property] of Object.entries(schema.properties)) {
10386
- const value = component[name];
10387
- if (property.required && value === void 0)
10388
- issues.push(issue2(`${componentPath}.${name}`, "REQUIRED_COMPONENT_PROP_MISSING", `${component.component}.${name} is required`));
10389
- if (value !== void 0)
10390
- validateProperty(value, property, `${componentPath}.${name}`, issues, name);
10391
- }
10392
- if (component["x2-overflow"] !== void 0)
10393
- validateOverflow(component, componentPath, issues);
10394
- if (component.component === "TextField")
10395
- validateTextField(component, componentPath, issues);
10396
- if (component.component === "ChoicePicker") {
10397
- if (!isStrictBinding(component.value))
10398
- issues.push(issue2(`${componentPath}.value`, "INPUT_REQUIRES_BINDING", "ChoicePicker.value must be a strict writable binding"));
10399
- validateOptions(component.options, `${componentPath}.options`, issues);
10400
- }
10401
- if (component.component === "Stepper")
10402
- validateStepper(component, componentPath, issues);
10403
- if (["Card", "Row", "Column", "List"].includes(component.component)) {
10404
- for (const axis of ["width", "height"]) {
10405
- const value = component[axis];
10406
- const modes = axis === "width" ? ["fit", "fill"] : ["auto"];
10407
- if (value !== void 0 && !(typeof value === "string" && (modes.includes(value) || /^\d+(?:\.\d+)?px$/.test(value) && Number.isFinite(parseFloat(value))))) {
10408
- issues.push(issue2(`${componentPath}.${axis}`, "INVALID_COMPONENT_PROP_VALUE", `size must be ${modes.join(" / ")} or a non-negative px string such as 120px`));
10409
- }
10410
- }
10411
- }
10412
- if (component.checks !== void 0)
10413
- validateChecks(component.checks, `${componentPath}.checks`, issues);
10414
- if (component.format !== void 0 && component.component === "Text")
10415
- validateNumberFormat(component.format, `${componentPath}.format`, issues);
10416
- if (component.action !== void 0)
10417
- validateAction(component.action, `${componentPath}.action`, issues, 0);
10279
+ validateV4Component(component, componentPath, issues);
10418
10280
  });
10419
10281
  }
10420
10282
  function validateProperty(value, schema, path2, issues, propertyName) {
@@ -10464,7 +10326,7 @@ function validateAction(value, path2, issues, depth) {
10464
10326
  issues.push(issue2(path2, "INVALID_ACTION", "action must be an object with at most four nested selects"));
10465
10327
  return;
10466
10328
  }
10467
- const branches = ["event", "local", "client", "select"].filter((key) => key in value);
10329
+ const branches = ["event", "function", "local", "client", "select"].filter((key) => key in value);
10468
10330
  if (branches.length !== 1 || Object.keys(value).length !== 1) {
10469
10331
  issues.push(issue2(path2, "INVALID_ACTION", "action must contain exactly one branch"));
10470
10332
  return;
@@ -10485,6 +10347,10 @@ function validateAction(value, path2, issues, depth) {
10485
10347
  issues.push(issue2(`${path2}.event.x2-user-message`, "INVALID_ACTION_CONTEXT", "x2-user-message must be a string or strict binding"));
10486
10348
  if (body.target !== void 0)
10487
10349
  validateOverlayTarget(body.target, `${path2}.event.target`, issues);
10350
+ } else if (branch === "function") {
10351
+ rejectUnknownKeys(body, ["ref"], `${path2}.function`, issues);
10352
+ if (!isFunctionActionRef(body.ref))
10353
+ issues.push(issue2(`${path2}.function.ref`, "INVALID_FUNCTION_ACTION_REF", "function ref must be a dot-separated identifier up to 128 characters"));
10488
10354
  } else if (branch === "local") {
10489
10355
  rejectUnknownKeys(body, ["name", "path", "value"], `${path2}.local`, issues);
10490
10356
  if (body.name !== "data.set" || typeof body.path !== "string" || !isSafePath(body.path) || !Object.prototype.hasOwnProperty.call(body, "value"))
@@ -10511,6 +10377,9 @@ function validateAction(value, path2, issues, depth) {
10511
10377
  validateAction(body.default, `${path2}.select.default`, issues, depth + 1);
10512
10378
  }
10513
10379
  }
10380
+ function isFunctionActionRef(value) {
10381
+ return typeof value === "string" && value.length <= 128 && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u.test(value);
10382
+ }
10514
10383
  function validateClientAction(body, path2, issues) {
10515
10384
  rejectUnknownKeys(body, ["name", "context"], path2, issues);
10516
10385
  if (body.name === "ui.overlay.close") {
@@ -10531,14 +10400,50 @@ function validateClientAction(body, path2, issues) {
10531
10400
  return;
10532
10401
  }
10533
10402
  if (body.name === "payment.trade-pay") {
10534
- if (!isPlainRecord(body.context) || typeof body.context.actionId !== "string" || !isPlainRecord(body.context.actionContext) || Object.keys(body.context).length !== 2)
10535
- issues.push(issue2(`${path2}.context`, "INVALID_CLIENT_ACTION_CONTEXT", "payment.trade-pay requires actionId and actionContext"));
10536
- else
10537
- validateActionDynamicValue(body.context.actionContext, `${path2}.context.actionContext`, issues);
10403
+ validatePaymentActionContext(body.context, `${path2}.context`, issues);
10538
10404
  return;
10539
10405
  }
10540
10406
  issues.push(issue2(`${path2}.name`, "UNSUPPORTED_CLIENT_ACTION", `unsupported client action ${String(body.name)}`));
10541
10407
  }
10408
+ function validatePaymentActionContext(value, path2, issues) {
10409
+ if (!isPlainRecord(value)) {
10410
+ issues.push(issue2(path2, "INVALID_CLIENT_ACTION_CONTEXT", "payment.trade-pay requires createTrade and onSuccess"));
10411
+ return;
10412
+ }
10413
+ rejectUnknownKeys(value, ["createTrade", "onSuccess"], path2, issues);
10414
+ const createTrade = isPlainRecord(value.createTrade) ? value.createTrade : void 0;
10415
+ if (!createTrade) {
10416
+ issues.push(issue2(`${path2}.createTrade`, "INVALID_PAYMENT_CREATE_TRADE", "createTrade must be an object"));
10417
+ } else {
10418
+ rejectUnknownKeys(createTrade, ["mcpResourceId", "toolName", "input", "tradeNoPath"], `${path2}.createTrade`, issues);
10419
+ if (!isSafeIdentifier(createTrade.mcpResourceId))
10420
+ issues.push(issue2(`${path2}.createTrade.mcpResourceId`, "INVALID_MCP_RESOURCE_ID", "mcpResourceId is invalid"));
10421
+ if (typeof createTrade.toolName !== "string" || !createTrade.toolName.trim())
10422
+ issues.push(issue2(`${path2}.createTrade.toolName`, "INVALID_TOOL_NAME", "toolName is required"));
10423
+ if (!isPlainRecord(createTrade.input))
10424
+ issues.push(issue2(`${path2}.createTrade.input`, "INVALID_PAYMENT_INPUT", "input must be an object"));
10425
+ else
10426
+ validateActionDynamicValue(createTrade.input, `${path2}.createTrade.input`, issues);
10427
+ if (!isSafeJsonPointer(createTrade.tradeNoPath))
10428
+ issues.push(issue2(`${path2}.createTrade.tradeNoPath`, "INVALID_TRADE_NO_PATH", "tradeNoPath must be an absolute JSON Pointer"));
10429
+ }
10430
+ const onSuccess = isPlainRecord(value.onSuccess) ? value.onSuccess : void 0;
10431
+ const event = onSuccess && isPlainRecord(onSuccess.event) ? onSuccess.event : void 0;
10432
+ if (!onSuccess || !event) {
10433
+ issues.push(issue2(`${path2}.onSuccess`, "INVALID_PAYMENT_SUCCESS_EVENT", "onSuccess.event is required"));
10434
+ return;
10435
+ }
10436
+ rejectUnknownKeys(onSuccess, ["event"], `${path2}.onSuccess`, issues);
10437
+ rejectUnknownKeys(event, ["name", "context", "x2-user-message"], `${path2}.onSuccess.event`, issues);
10438
+ if (typeof event.name !== "string" || !/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(event.name) || event.name.length > 96)
10439
+ issues.push(issue2(`${path2}.onSuccess.event.name`, "INVALID_ACTION_NAME", "event name is invalid"));
10440
+ if (event.context !== void 0 && !isPlainRecord(event.context))
10441
+ issues.push(issue2(`${path2}.onSuccess.event.context`, "INVALID_ACTION_CONTEXT", "event context must be an object"));
10442
+ else if (event.context !== void 0)
10443
+ validateActionDynamicValue(event.context, `${path2}.onSuccess.event.context`, issues);
10444
+ if (typeof event["x2-user-message"] !== "string" || !event["x2-user-message"].trim())
10445
+ issues.push(issue2(`${path2}.onSuccess.event.x2-user-message`, "INVALID_ACTION_CONTEXT", "x2-user-message must be a non-empty string"));
10446
+ }
10542
10447
  function validateActionDynamicValue(value, path2, issues) {
10543
10448
  if (Array.isArray(value)) {
10544
10449
  value.forEach((entry, index) => validateActionDynamicValue(entry, `${path2}[${index}]`, issues));
@@ -10757,7 +10662,7 @@ var FIELD_SOURCES = [
10757
10662
  "runtime-context",
10758
10663
  "local"
10759
10664
  ];
10760
- var RUNTIME_CONTEXT_KEYS2 = /* @__PURE__ */ new Set([
10665
+ var RUNTIME_CONTEXT_KEYS = /* @__PURE__ */ new Set([
10761
10666
  "agentId",
10762
10667
  "tenantId",
10763
10668
  "threadId",
@@ -10837,6 +10742,9 @@ function getA2UICardResourceConfigIssues(value) {
10837
10742
  }
10838
10743
  function getA2UICardResourceConfigV3Issues(value) {
10839
10744
  const issues = [];
10745
+ if (value.actionBindings !== void 0) {
10746
+ issues.push(issue2("config.actionBindings", "LEGACY_PAYMENT_ACTION_BINDINGS_UNSUPPORTED", "payment actions must be defined inline in card JSON"));
10747
+ }
10840
10748
  exactKeys(value, [
10841
10749
  "schemaVersion",
10842
10750
  "revision",
@@ -10847,7 +10755,6 @@ function getA2UICardResourceConfigV3Issues(value) {
10847
10755
  "fields",
10848
10756
  "dataSources",
10849
10757
  "bindings",
10850
- "actionBindings",
10851
10758
  "a2uiTemplate"
10852
10759
  ], "config", issues);
10853
10760
  if (value.schemaVersion !== "3" && value.schemaVersion !== "4") {
@@ -10871,11 +10778,6 @@ function getA2UICardResourceConfigV3Issues(value) {
10871
10778
  issues.push(...getA2UIV4ProtocolIssues(card, "config.a2uiTemplate.content"));
10872
10779
  issues.push(...getPersistedV4ProtocolIssues(card, "config.a2uiTemplate.content"));
10873
10780
  }
10874
- const actionBindings = value.actionBindings === void 0 ? [] : value.actionBindings;
10875
- issues.push(...getA2UICardActionBindingIssues(actionBindings, "config.actionBindings"));
10876
- if (card && Array.isArray(actionBindings)) {
10877
- issues.push(...getA2UIPaymentActionReferenceIssues(card, actionBindings, "config.a2uiTemplate.content"));
10878
- }
10879
10781
  if (fields && dataSources && bindings) {
10880
10782
  validateV3Coverage(fields, dataSources, bindings, issues, { card });
10881
10783
  }
@@ -11095,7 +10997,7 @@ function validateFieldSource(candidate, itemPath, issues) {
11095
10997
  issues.push(issue2(`${itemPath}.sourcePath`, "UNEXPECTED_FIELD_SOURCE_PATH", "sourcePath is only allowed for invocation fields"));
11096
10998
  }
11097
10999
  if (candidate.source === "runtime-context") {
11098
- if (!RUNTIME_CONTEXT_KEYS2.has(candidate.runtimeContextKey)) {
11000
+ if (!RUNTIME_CONTEXT_KEYS.has(candidate.runtimeContextKey)) {
11099
11001
  issues.push(issue2(`${itemPath}.runtimeContextKey`, "INVALID_RUNTIME_CONTEXT", "runtime-context fields require an allowed runtimeContextKey"));
11100
11002
  }
11101
11003
  } else if (candidate.runtimeContextKey !== void 0) {
@@ -11147,11 +11049,11 @@ function validateResolverCalls(value, path2, issues) {
11147
11049
  issues.push(issue2(`${itemPath}.mcpResourceId`, "INVALID_MCP_RESOURCE_ID", "mcpResourceId is invalid"));
11148
11050
  }
11149
11051
  requiredString(candidate.toolName, `${itemPath}.toolName`, issues);
11150
- validateInputBindings2(candidate.inputBindings, `${itemPath}.inputBindings`, issues);
11052
+ validateInputBindings(candidate.inputBindings, `${itemPath}.inputBindings`, issues);
11151
11053
  });
11152
11054
  return value;
11153
11055
  }
11154
- function validateInputBindings2(value, path2, issues) {
11056
+ function validateInputBindings(value, path2, issues) {
11155
11057
  if (!Array.isArray(value)) {
11156
11058
  issues.push(issue2(path2, "INVALID_INPUT_BINDINGS", "inputBindings must be an array"));
11157
11059
  return void 0;
@@ -11171,11 +11073,11 @@ function validateInputBindings2(value, path2, issues) {
11171
11073
  } else {
11172
11074
  paths.add(candidate.inputPath);
11173
11075
  }
11174
- validateInputSource2(candidate.source, `${itemPath}.source`, issues);
11076
+ validateInputSource(candidate.source, `${itemPath}.source`, issues);
11175
11077
  });
11176
11078
  return value;
11177
11079
  }
11178
- function validateInputSource2(value, path2, issues) {
11080
+ function validateInputSource(value, path2, issues) {
11179
11081
  if (!isPlainRecord(value)) {
11180
11082
  issues.push(issue2(path2, "INVALID_INPUT_SOURCE", "source must be an object"));
11181
11083
  return;
@@ -11189,7 +11091,7 @@ function validateInputSource2(value, path2, issues) {
11189
11091
  }
11190
11092
  if (value.kind === "runtime-context") {
11191
11093
  exactKeys(value, ["kind", "key"], path2, issues);
11192
- if (!RUNTIME_CONTEXT_KEYS2.has(value.key)) {
11094
+ if (!RUNTIME_CONTEXT_KEYS.has(value.key)) {
11193
11095
  issues.push(issue2(`${path2}.key`, "INVALID_RUNTIME_CONTEXT", "runtime context key is invalid"));
11194
11096
  }
11195
11097
  return;
@@ -11556,6 +11458,155 @@ function valueType2(value) {
11556
11458
  return typeof value === "object" ? "object" : typeof value;
11557
11459
  }
11558
11460
 
11461
+ // ../agent-a2ui-card-contract/dist/esm/payment-action.js
11462
+ var A2UIActionContractError = class extends Error {
11463
+ constructor(issues) {
11464
+ super(issues.join("; "));
11465
+ Object.defineProperty(this, "issues", {
11466
+ enumerable: true,
11467
+ configurable: true,
11468
+ writable: true,
11469
+ value: issues
11470
+ });
11471
+ Object.defineProperty(this, "code", {
11472
+ enumerable: true,
11473
+ configurable: true,
11474
+ writable: true,
11475
+ value: "A2UI_ACTION_CONTRACT_INVALID"
11476
+ });
11477
+ this.name = "A2UIActionContractError";
11478
+ }
11479
+ };
11480
+ function parseA2UIActionExecuteRequest(value) {
11481
+ const issues = getA2UIActionExecuteRequestIssues(value);
11482
+ if (issues.length)
11483
+ throw new A2UIActionContractError(issues);
11484
+ return JSON.parse(JSON.stringify(value));
11485
+ }
11486
+ function getA2UIActionExecuteRequestIssues(value) {
11487
+ if (!isPlainRecord(value))
11488
+ return ["request must be an object"];
11489
+ const issues = [];
11490
+ rejectExtraKeys(value, ["schemaVersion", "agentId", "threadId", "invocationId", "source", "input"], "request", issues);
11491
+ if (value.schemaVersion !== "2")
11492
+ issues.push("schemaVersion must be 2");
11493
+ requiredIdentifier(value.agentId, "agentId", issues);
11494
+ requiredIdentifier(value.threadId, "threadId", issues);
11495
+ requiredIdentifier(value.invocationId, "invocationId", issues);
11496
+ validateSource(value.source, issues);
11497
+ if (!cloneJsonObject(value.input))
11498
+ issues.push("input must be a JSON object");
11499
+ return issues;
11500
+ }
11501
+ function validateSource(value, issues) {
11502
+ if (!isPlainRecord(value)) {
11503
+ issues.push("source must be an object");
11504
+ return;
11505
+ }
11506
+ rejectExtraKeys(value, ["cardRef", "cardRevision", "cardInstanceId", "surfaceId", "componentId"], "source", issues);
11507
+ requiredIdentifier(value.cardRef, "source.cardRef", issues);
11508
+ requiredIdentifier(value.cardRevision, "source.cardRevision", issues);
11509
+ requiredText(value.cardInstanceId, "source.cardInstanceId", issues);
11510
+ requiredIdentifier(value.surfaceId, "source.surfaceId", issues);
11511
+ requiredIdentifier(value.componentId, "source.componentId", issues);
11512
+ }
11513
+ function rejectExtraKeys(value, allowed, path2, issues) {
11514
+ const allowedKeys = new Set(allowed);
11515
+ for (const key of Object.keys(value))
11516
+ if (!allowedKeys.has(key))
11517
+ issues.push(`${path2}.${key} is not allowed`);
11518
+ }
11519
+ function requiredIdentifier(value, path2, issues) {
11520
+ if (!isSafeIdentifier(value))
11521
+ issues.push(`${path2} must be a safe identifier`);
11522
+ }
11523
+ function requiredText(value, path2, issues) {
11524
+ if (typeof value !== "string" || !value.trim() || value.length > 256) {
11525
+ issues.push(`${path2} must be a non-empty string up to 256 characters`);
11526
+ }
11527
+ }
11528
+
11529
+ // ../agent-a2ui-card-contract/dist/esm/function-action.js
11530
+ function parseA2UIFunctionMcpExecuteRequest(value) {
11531
+ const issues = [];
11532
+ if (!isPlainRecord(value))
11533
+ throw new Error("request must be an object");
11534
+ rejectExtraKeys2(value, [
11535
+ "schemaVersion",
11536
+ "agentId",
11537
+ "threadId",
11538
+ "invocationId",
11539
+ "callId",
11540
+ "buildId",
11541
+ "action",
11542
+ "source",
11543
+ "tool"
11544
+ ], "request", issues);
11545
+ if (value.schemaVersion !== "1")
11546
+ issues.push("schemaVersion must be 1");
11547
+ for (const key of [
11548
+ "agentId",
11549
+ "threadId",
11550
+ "invocationId",
11551
+ "callId"
11552
+ ]) {
11553
+ if (!isSafeIdentifier(value[key]))
11554
+ issues.push(`${key} must be a safe identifier`);
11555
+ }
11556
+ if (value.buildId !== void 0 && (typeof value.buildId !== "string" || !/^[a-f0-9]{64}$/u.test(value.buildId))) {
11557
+ issues.push("buildId must be a sha256 digest");
11558
+ }
11559
+ if (!isPlainRecord(value.action))
11560
+ issues.push("action must be an object");
11561
+ else {
11562
+ rejectExtraKeys2(value.action, ["ref"], "action", issues);
11563
+ if (!isFunctionRef(value.action.ref))
11564
+ issues.push("action.ref is invalid");
11565
+ }
11566
+ validateSource2(value.source, issues);
11567
+ if (!isPlainRecord(value.tool))
11568
+ issues.push("tool must be an object");
11569
+ else {
11570
+ rejectExtraKeys2(value.tool, ["mcpResourceId", "toolName", "input"], "tool", issues);
11571
+ if (!isSafeIdentifier(value.tool.mcpResourceId))
11572
+ issues.push("tool.mcpResourceId is invalid");
11573
+ if (!isSafeIdentifier(value.tool.toolName))
11574
+ issues.push("tool.toolName is invalid");
11575
+ if (!cloneJsonObject(value.tool.input))
11576
+ issues.push("tool.input must be a JSON object");
11577
+ }
11578
+ if (issues.length)
11579
+ throw new Error(issues.join("; "));
11580
+ return JSON.parse(JSON.stringify(value));
11581
+ }
11582
+ function validateSource2(value, issues) {
11583
+ if (!isPlainRecord(value))
11584
+ return void issues.push("source must be an object");
11585
+ rejectExtraKeys2(value, ["cardRef", "cardRevision", "cardInstanceId", "surfaceId", "componentId"], "source", issues);
11586
+ for (const key of [
11587
+ "cardRef",
11588
+ "cardRevision",
11589
+ "surfaceId",
11590
+ "componentId"
11591
+ ]) {
11592
+ if (!isSafeIdentifier(value[key]))
11593
+ issues.push(`source.${key} is invalid`);
11594
+ }
11595
+ if (typeof value.cardInstanceId !== "string" || !value.cardInstanceId.trim()) {
11596
+ issues.push("source.cardInstanceId is invalid");
11597
+ }
11598
+ }
11599
+ function isFunctionRef(value) {
11600
+ return typeof value === "string" && value.length <= 128 && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u.test(value);
11601
+ }
11602
+ function rejectExtraKeys2(value, allowed, path2, issues) {
11603
+ const keys = new Set(allowed);
11604
+ for (const key of Object.keys(value)) {
11605
+ if (!keys.has(key))
11606
+ issues.push(`${path2}.${key} is not allowed`);
11607
+ }
11608
+ }
11609
+
11559
11610
  // ../agent-a2ui-card-contract/dist/esm/presentation.js
11560
11611
  var MAX_FIELDS = 32;
11561
11612
  var MAX_ENTITIES = 10;
@@ -11672,1620 +11723,1471 @@ function truncateText(value) {
11672
11723
  return { value: `${value.slice(0, MAX_TEXT_LENGTH - 1)}\u2026`, truncated: true };
11673
11724
  }
11674
11725
 
11675
- // ../linkque-agent-runtime/dist/esm/core/mcpAggregator.js
11676
- function aggregateMcpServers(resources, protocolAgentId) {
11677
- const specs = /* @__PURE__ */ new Map();
11678
- const touch = (serverName) => {
11679
- let spec = specs.get(serverName);
11680
- if (!spec) {
11681
- spec = {
11682
- serverName,
11683
- agentId: "",
11684
- argsMappingRules: [],
11685
- allowedTools: void 0,
11686
- resourceIds: [],
11687
- description: ""
11688
- };
11689
- specs.set(serverName, spec);
11690
- }
11691
- return spec;
11726
+ // ../linkque-agent-runtime/dist/esm/core/mcpNaming.js
11727
+ import { createHash } from "node:crypto";
11728
+ function stableToolName(prefix, raw) {
11729
+ const readable = raw.replace(/[^A-Za-z0-9_-]+/gu, "_").replace(/^_+|_+$/gu, "").slice(0, 38) || "resource";
11730
+ const digest = createHash("sha256").update(raw).digest("hex").slice(0, 10);
11731
+ return `${prefix}_${readable}_${digest}`;
11732
+ }
11733
+
11734
+ // ../linkque-agent-runtime/dist/esm/core/cardSemanticSnapshot.js
11735
+ var MAX_BYTES = 6e3;
11736
+ var MAX_LABEL = 160;
11737
+ function createCardSemanticSnapshot(receipt, fields) {
11738
+ const groups = receipt.coverage.map((coverage) => {
11739
+ const field = fields.find((f) => f.fieldId === coverage.fieldId);
11740
+ const entities = receipt.entities.filter((e) => e.fieldId === coverage.fieldId);
11741
+ const echo = field?.presentation?.visibility === "echo";
11742
+ const attributes = echo ? [...new Set(entities.flatMap((e) => Object.keys(e.attributes ?? {})))] : [];
11743
+ const hasValue = echo && entities.some((e) => Object.hasOwn(e, "value"));
11744
+ const hasLabel = echo && entities.some((e) => !Object.hasOwn(e, "value"));
11745
+ const columns = [
11746
+ "\u6761\u76EE\u5F15\u7528",
11747
+ ...hasLabel ? [columnLabel(field, field?.presentation?.labelPath, "\u540D\u79F0")] : [],
11748
+ ...hasValue ? [short(coverage.label)] : [],
11749
+ ...attributes.map((path2) => columnLabel(field, path2, path2))
11750
+ ];
11751
+ const rows = entities.map((e) => [
11752
+ e.ref,
11753
+ ...hasLabel ? [e.label] : [],
11754
+ ...hasValue ? [e.value ?? null] : [],
11755
+ ...attributes.map((path2) => e.attributes?.[path2] ?? null)
11756
+ ]);
11757
+ const total = coverage.itemCount ?? (coverage.present ? 1 : 0);
11758
+ return {
11759
+ field: coverage.fieldId,
11760
+ label: short(coverage.label),
11761
+ present: coverage.present,
11762
+ total,
11763
+ included: rows.length,
11764
+ complete: echo && coverage.present && rows.length === total && !entities.some((e) => e.truncated) && !receipt.omissions.some((o) => o.fieldId === coverage.fieldId),
11765
+ columns,
11766
+ rows
11767
+ };
11768
+ });
11769
+ const snapshot = {
11770
+ version: 1,
11771
+ groups,
11772
+ omissions: receipt.omissions.map((o) => ({ ...o }))
11692
11773
  };
11693
- for (const resource of resources) {
11694
- const serverName = resource.config.serverName ?? resource.resourceId;
11695
- const spec = touch(serverName);
11696
- spec.resourceIds.push(resource.resourceId);
11697
- if (!spec.agentId) {
11698
- spec.agentId = protocolAgentId ?? resource.config.agentId;
11699
- }
11700
- if (!spec.description)
11701
- spec.description = resource.config.description;
11702
- if (resource.resourceType === EResourceType.MCP) {
11703
- for (const rule of resource.config.argsMappingRules ?? []) {
11704
- spec.argsMappingRules.push(rule);
11705
- }
11706
- const allowed = resource.config.allowedTools;
11707
- if (allowed && allowed.length > 0) {
11708
- if (!spec.allowedTools)
11709
- spec.allowedTools = /* @__PURE__ */ new Set();
11710
- for (const toolName of allowed)
11711
- spec.allowedTools.add(toolName);
11774
+ while (bytes(snapshot) > MAX_BYTES) {
11775
+ let group;
11776
+ for (let i = groups.length - 1; i >= 0; i--) {
11777
+ if (groups[i].rows.length > 0) {
11778
+ group = groups[i];
11779
+ break;
11712
11780
  }
11713
- continue;
11714
- }
11715
- if (!spec.allowedTools)
11716
- spec.allowedTools = /* @__PURE__ */ new Set();
11717
- spec.allowedTools.add(resource.config.toolName);
11718
- for (const rule of resource.config.argsMappingRules ?? []) {
11719
- const fullRule = {
11720
- mcpToolName: resource.config.toolName,
11721
- argJsonPath: rule.argJsonPath,
11722
- disabled: rule.disabled,
11723
- valueType: rule.valueType,
11724
- ...rule.value !== void 0 ? { value: rule.value } : {}
11725
- };
11726
- spec.argsMappingRules.push(fullRule);
11727
11781
  }
11782
+ snapshot.truncated = true;
11783
+ if (group) {
11784
+ group.rows.pop();
11785
+ group.included = group.rows.length;
11786
+ group.complete = false;
11787
+ } else if (groups.length) {
11788
+ groups.pop();
11789
+ } else if (snapshot.omissions.length) {
11790
+ snapshot.omissions.pop();
11791
+ } else
11792
+ break;
11728
11793
  }
11729
- return [...specs.values()];
11794
+ return snapshot;
11730
11795
  }
11731
-
11732
- // ../linkque-agent-runtime/dist/esm/core/types.js
11733
- var EDebugLogScope;
11734
- (function(EDebugLogScope2) {
11735
- EDebugLogScope2["A2UI_ACTION"] = "A2UI_ACTION";
11736
- EDebugLogScope2["CONFIG"] = "CONFIG";
11737
- EDebugLogScope2["LLM"] = "LLM";
11738
- EDebugLogScope2["PI_EVENT"] = "PI_EVENT";
11739
- EDebugLogScope2["MCP"] = "MCP";
11740
- EDebugLogScope2["HTTP"] = "HTTP";
11741
- EDebugLogScope2["HOOK"] = "HOOK";
11742
- })(EDebugLogScope || (EDebugLogScope = {}));
11743
-
11744
- // ../linkque-agent-runtime/dist/esm/core/mcpProxyTool.js
11745
- var MCP_PROXY_TOOL_NAME = "mcp";
11746
- var McpProxyTool = class {
11747
- provider;
11748
- /** serverName → 缓存条目(同 serverName 多 resourceId 聚合为一个连接)。 */
11749
- entries = /* @__PURE__ */ new Map();
11750
- /** 进行中的连接(去重并发 ensureEntry)。 */
11751
- inFlight = /* @__PURE__ */ new Map();
11752
- specByServerName;
11753
- /** 原始 resourceId → 所属 spec(resolve(resourceId,...) 反查用)。 */
11754
- specByResourceId;
11755
- specs;
11756
- debugLog;
11757
- constructor(provider, specs, options = {}) {
11758
- this.provider = provider;
11759
- this.specs = specs;
11760
- this.specByServerName = new Map(specs.map((spec) => [spec.serverName, spec]));
11761
- this.specByResourceId = new Map(specs.flatMap((spec) => spec.resourceIds.map((id) => [id, spec])));
11762
- this.debugLog = options.debugLog ?? (() => {
11763
- });
11764
- }
11765
- /**
11766
- * 产单个 `mcp` 代理工具描述符,注入 `agentReq.tools`。
11767
- * `execute` 闭包按入参字段派发到 status/connect/list/search/describe/call。
11768
- */
11769
- asTool() {
11770
- return {
11771
- name: MCP_PROXY_TOOL_NAME,
11772
- modelName: MCP_PROXY_TOOL_NAME,
11773
- label: "MCP",
11774
- description: MCP_PROXY_DESCRIPTION,
11775
- inputSchema: MCP_PROXY_INPUT_SCHEMA,
11776
- execute: (args, signal) => this.dispatch(args, signal)
11777
- };
11796
+ function bytes(value) {
11797
+ return Buffer.byteLength(JSON.stringify(value));
11798
+ }
11799
+ function short(value) {
11800
+ return value.length > MAX_LABEL ? `${value.slice(0, MAX_LABEL - 1)}\u2026` : value;
11801
+ }
11802
+ function columnLabel(field, path2, fallback) {
11803
+ if (!field || !path2)
11804
+ return short(fallback);
11805
+ let schema = field.type === "array" ? field.valueSchema.items : field.valueSchema;
11806
+ for (const token of path2.slice(1).split("/").map((t) => t.replaceAll("~1", "/").replaceAll("~0", "~"))) {
11807
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
11808
+ return short(fallback);
11809
+ const properties = schema.properties;
11810
+ if (!properties || typeof properties !== "object" || Array.isArray(properties) || !Object.hasOwn(properties, token))
11811
+ return short(fallback);
11812
+ schema = properties[token];
11778
11813
  }
11779
- /** {@link IMcpToolRegistry.resolve}:按 (resourceId, toolName) 解析可调用句柄。 */
11780
- async resolve(resourceId, toolName, signal) {
11781
- const spec = this.findSpec(resourceId);
11782
- if (!spec)
11783
- return void 0;
11784
- const entry = await this.ensureEntry(spec.serverName, signal);
11785
- if (!entry || !entry.server)
11786
- return void 0;
11787
- const tool = entry.tools.find((t) => t.name === toolName);
11788
- if (!tool)
11789
- return void 0;
11790
- return {
11791
- inputSchema: tool.inputSchema,
11792
- outputSchema: tool.outputSchema,
11793
- execute: (args, sig) => entry.server.callTool(tool.name, args, sig)
11794
- };
11814
+ const title = schema && typeof schema === "object" && !Array.isArray(schema) ? schema.title : void 0;
11815
+ return short(typeof title === "string" && title ? title : fallback);
11816
+ }
11817
+
11818
+ // ../linkque-agent-runtime/dist/esm/core/cardTools.js
11819
+ var FALLBACK_OBJECT_SCHEMA = {
11820
+ type: "object",
11821
+ additionalProperties: true
11822
+ };
11823
+ function createCardPresentationToolName(resourceId) {
11824
+ return stableToolName("a2ui_card", resourceId);
11825
+ }
11826
+ async function executeCardPresentation(resource, registry, runtimeContext, args, signal) {
11827
+ const config = parseCardConfig(resource);
11828
+ if (config.schemaVersion !== "2") {
11829
+ throw new Error(`Schema v${config.schemaVersion} cards must be executed through the card data-source loop`);
11795
11830
  }
11796
- /** 关闭所有已连 server(忽略单 server 关闭错误)。 */
11797
- async closeAll() {
11798
- await Promise.all([...this.entries.values()].map(async (entry) => {
11799
- if (!entry.server)
11800
- return;
11801
- try {
11802
- await entry.server.close?.();
11803
- } catch (error) {
11804
- try {
11805
- this.debugLog(`[mcp] server ${entry.server.serverName} close failed: ${error instanceof Error ? error.message : "unknown error"}`, EDebugLogScope.MCP);
11806
- } catch {
11807
- }
11831
+ const invocation = cloneJsonObject2(args, "Presentation Tool arguments");
11832
+ const viewModel = await executeA2UICardResolver({
11833
+ resolver: config.resolver,
11834
+ fields: config.fields,
11835
+ presentationInputSchema: config.presentationInputSchema,
11836
+ argsSchema: config.a2uiTemplate.argsSchema,
11837
+ invocation,
11838
+ runtimeContext,
11839
+ tools: await Promise.all(config.resolver.calls.map(async (call) => {
11840
+ const handle = await registry.resolve(call.mcpResourceId, call.toolName, signal);
11841
+ if (!handle) {
11842
+ throw new Error(`MCP tool ${call.mcpResourceId}/${call.toolName} is unavailable`);
11808
11843
  }
11809
- }));
11844
+ const inputSchema = normalizeMcpInputSchema(handle.inputSchema);
11845
+ return {
11846
+ resourceId: call.mcpResourceId,
11847
+ toolName: call.toolName,
11848
+ // 旧 MCP server 可能只在开放平台元数据中声明 Schema,但
11849
+ // tools/list 未返回。运行时不因此拒绝调用:有实时 Schema 时用它
11850
+ // 做额外校验,缺失时依赖 CARD 已固化的字段 Schema 与最终
11851
+ // ViewModel Schema 校验。
11852
+ inputSchema,
11853
+ outputSchema: isJsonObject(handle.outputSchema) ? handle.outputSchema : FALLBACK_OBJECT_SCHEMA,
11854
+ call: async (input, callSignal) => {
11855
+ const result = await handle.execute(supplementMcpInput(input, invocation, config.presentationInputSchema, inputSchema), callSignal);
11856
+ return { structuredContent: readStructuredContent(result) };
11857
+ }
11858
+ };
11859
+ })),
11860
+ signal
11861
+ });
11862
+ return createPresentationResult(resource, config, viewModel);
11863
+ }
11864
+ async function executeCardPresentationFromSources(resource, runtimeContext, sourceResults, signal) {
11865
+ const config = parseCardConfig(resource);
11866
+ if (config.schemaVersion !== "3" && config.schemaVersion !== "4") {
11867
+ throw new Error("Source-result rendering is only available for schema v3/v4 cards");
11810
11868
  }
11811
- // —— 内部:连接与缓存 ——
11812
- /** 确保某 server 已连;返回 connected 条目,依失败返回 null(不抛错)。 */
11813
- async ensureEntry(serverName, signal) {
11814
- const existing = this.entries.get(serverName);
11815
- if (existing) {
11816
- return existing.status === "connected" ? existing : null;
11817
- }
11818
- let promise = this.inFlight.get(serverName);
11819
- if (!promise) {
11820
- promise = this.connect(serverName, signal).finally(() => {
11821
- this.inFlight.delete(serverName);
11822
- });
11823
- this.inFlight.set(serverName, promise);
11824
- }
11825
- const entry = await promise;
11826
- return entry.status === "connected" ? entry : null;
11827
- }
11828
- /** 连单个 server 并 listTools;按 spec.allowedTools 过滤后缓存;失败记为 failed。 */
11829
- async connect(serverName, _signal) {
11830
- const spec = this.specByServerName.get(serverName);
11831
- if (!spec) {
11832
- const entry = {
11833
- server: null,
11834
- tools: [],
11835
- status: "failed",
11836
- error: `unknown serverName: ${serverName}`
11837
- };
11838
- this.entries.set(serverName, entry);
11839
- this.debugLog(`[mcp] server ${serverName} unknown serverName`, EDebugLogScope.MCP);
11840
- return entry;
11841
- }
11842
- try {
11843
- const synthetic = {
11844
- resourceId: spec.serverName,
11845
- resourceType: EResourceType.MCP,
11846
- providerType: EResourceProviderType.ALIPAY_OPEN,
11847
- config: {
11848
- agentId: spec.agentId,
11849
- serverName: spec.serverName,
11850
- description: spec.description,
11851
- argsMappingRules: spec.argsMappingRules
11852
- }
11853
- };
11854
- const servers = await this.provider.servers([synthetic]);
11855
- const server = servers[0];
11856
- if (!server) {
11857
- throw new Error(`provider returned no server for ${spec.serverName}`);
11858
- }
11859
- const all = await server.listTools();
11860
- const tools = spec.allowedTools ? all.filter((tool) => spec.allowedTools.has(tool.name)) : all;
11861
- const entry = { server, tools, status: "connected" };
11862
- this.entries.set(serverName, entry);
11863
- this.debugLog(`[mcp] server ${spec.serverName} connected (${tools.length}/${all.length} tools)`, EDebugLogScope.MCP);
11864
- return entry;
11865
- } catch (error) {
11866
- const message = error instanceof Error ? error.message : String(error);
11867
- const entry = {
11868
- server: null,
11869
- tools: [],
11870
- status: "failed",
11871
- error: message
11872
- };
11873
- this.entries.set(serverName, entry);
11874
- this.debugLog(`[mcp] server ${spec.serverName} connect failed: ${message}`, EDebugLogScope.MCP);
11875
- return entry;
11876
- }
11877
- }
11878
- // —— 派发 ——
11879
- /** 按入参字段派发;返回 LLM 可读文本。 */
11880
- async dispatch(args, signal) {
11881
- const params = parseProxyArgs(args);
11882
- if (params.connect !== void 0) {
11883
- return this.executeConnect(params.connect, signal);
11884
- }
11885
- if (params.describe !== void 0) {
11886
- return this.executeDescribe(params.describe, params.server, signal);
11887
- }
11888
- if (params.searches !== void 0) {
11889
- return this.executeBatchSearch(params.searches, params.server);
11890
- }
11891
- if (params.search !== void 0) {
11892
- return this.executeSearch(params.search, params.server);
11893
- }
11894
- if (params.tool !== void 0) {
11895
- return this.executeCall(params.tool, params.args, params.server, signal);
11896
- }
11897
- if (params.server !== void 0) {
11898
- return this.executeList(params.server, signal);
11899
- }
11900
- return this.executeStatus();
11901
- }
11902
- /** `mcp({})` / `mcp({ status: true })`:列各 server 连接状态 + 工具数。 */
11903
- executeStatus() {
11904
- const lines = [];
11905
- let connected = 0;
11906
- let totalTools = 0;
11907
- for (const spec of this.specs) {
11908
- const label = spec.serverName;
11909
- const entry = this.entries.get(spec.serverName);
11910
- if (!entry) {
11911
- lines.push(`\u25CB ${label} (not connected)`);
11912
- continue;
11913
- }
11914
- if (entry.status === "connected") {
11915
- connected += 1;
11916
- totalTools += entry.tools.length;
11917
- lines.push(`\u2713 ${label} (${entry.tools.length} tools)`);
11918
- } else {
11919
- lines.push(`\u2717 ${label} (failed${entry.error ? ": " + entry.error : ""})`);
11920
- }
11921
- }
11922
- const header = `MCP: ${connected}/${this.specs.length} servers, ${totalTools} tools`;
11923
- const hint = this.specs.length > 0 ? '\nmcp({ server: "name" }) to list tools, mcp({ search: "..." }) to search, mcp({ tool: "...", args: {...} }) to call' : "\n(no MCP resources configured)";
11924
- return `${header}
11925
-
11926
- ${lines.join("\n")}${hint}`.trim();
11927
- }
11928
- /** `mcp({ connect: "server" })`:显式连接并刷元数据,返回该 server 工具列表。 */
11929
- async executeConnect(server, signal) {
11930
- const spec = this.findSpec(server);
11931
- if (!spec)
11932
- return `Server "${server}" not found. Use mcp({}) to see available servers.`;
11933
- this.entries.delete(spec.serverName);
11934
- const entry = await this.ensureEntry(spec.serverName, signal);
11935
- if (!entry) {
11936
- const failed = this.entries.get(spec.serverName);
11937
- const detail = failed?.error ? `: ${failed.error}` : "";
11938
- return `Failed to connect to "${spec.serverName}"${detail}.`;
11939
- }
11940
- return this.formatToolList(spec.serverName, entry.tools);
11941
- }
11942
- /** `mcp({ server: "name" })`:列该 server 工具名 + 截断 description。 */
11943
- async executeList(server, signal) {
11944
- const spec = this.findSpec(server);
11945
- if (!spec)
11946
- return `Server "${server}" not found. Use mcp({}) to see available servers.`;
11947
- const entry = await this.ensureEntry(spec.serverName, signal);
11948
- if (!entry) {
11949
- return `Server "${spec.serverName}" is not connected. Use mcp({ connect: "${spec.serverName}" }) to retry.`;
11950
- }
11951
- return this.formatToolList(spec.serverName, entry.tools);
11952
- }
11953
- /** `mcp({ search: "query" })`:空格分词 OR 子串匹配 name/description(跨所有 server)。 */
11954
- async executeSearch(query, serverHint) {
11955
- const terms = query.trim().split(/\s+/u).filter((t) => t.length > 0);
11956
- if (terms.length === 0)
11957
- return "Search query cannot be empty.";
11958
- const pattern = new RegExp(terms.map(escapeRegExp).join("|"), "iu");
11959
- const specs = serverHint ? this.specsMatching(serverHint) : this.specs;
11960
- await Promise.all(specs.map((s) => this.ensureEntry(s.serverName)));
11961
- const matches = [];
11962
- for (const spec of specs) {
11963
- const entry = this.entries.get(spec.serverName);
11964
- if (!entry || entry.status !== "connected")
11965
- continue;
11966
- for (const tool of entry.tools) {
11967
- if (pattern.test(tool.name) || pattern.test(tool.description ?? "")) {
11968
- matches.push({ server: spec.serverName, tool });
11969
- }
11970
- }
11971
- }
11972
- if (matches.length === 0) {
11973
- return serverHint ? `No tools matching "${query}" in "${serverHint}"` : `No tools matching "${query}"`;
11974
- }
11975
- const lines = [`Found ${matches.length} tool(s) matching "${query}":`, ""];
11976
- for (const { server, tool } of matches) {
11977
- lines.push(`${tool.name} [${server}]`);
11978
- lines.push(` ${tool.description ?? "(no description)"}`);
11979
- if (tool.inputSchema) {
11980
- lines.push(` Parameters:
11981
- ${formatSchema(tool.inputSchema, " ")}`);
11982
- }
11983
- lines.push("");
11984
- }
11985
- return lines.join("\n").trim();
11986
- }
11987
- /** `mcp({ searches: [...] })`:一次连接元数据并按 query 分组执行多组搜索。 */
11988
- async executeBatchSearch(queries, serverHint) {
11989
- const normalized = [
11990
- ...new Set(queries.map((query) => query.trim()).filter(Boolean))
11991
- ].slice(0, MCP_BATCH_SEARCH_MAX_ITEMS);
11992
- if (normalized.length === 0) {
11993
- return "Batch search requires at least one non-empty query.";
11994
- }
11995
- const specs = serverHint ? this.specsMatching(serverHint) : this.specs;
11996
- await Promise.all(specs.map((spec) => this.ensureEntry(spec.serverName)));
11997
- const results = await Promise.all(normalized.map((query) => this.executeSearch(query, serverHint)));
11998
- return results.map((result, index) => `Query ${index + 1}: "${normalized[index]}"
11999
- ${result}`).join("\n\n");
12000
- }
12001
- /** `mcp({ describe: "tool" })`:输出工具所属 server + 参数 schema。 */
12002
- async executeDescribe(toolName, serverHint, signal) {
12003
- const found = await this.findTool(toolName, serverHint, signal);
12004
- if (!found) {
12005
- return `Tool "${toolName}" not found. Use mcp({ search: "..." }) to search.`;
12006
- }
12007
- const { server, tool } = found;
12008
- const lines = [
12009
- `${tool.name}`,
12010
- `Server: ${server}`,
12011
- "",
12012
- tool.description ?? "(no description)"
12013
- ];
12014
- if (tool.inputSchema) {
12015
- lines.push("", `Parameters:
12016
- ${formatSchema(tool.inputSchema)}`);
12017
- } else {
12018
- lines.push("", "No parameters defined.");
12019
- }
12020
- return lines.join("\n").trim();
12021
- }
12022
- /** `mcp({ tool: "name", args: {...} })`:调用工具,返回序列化结果。 */
12023
- async executeCall(toolName, args, serverHint, signal) {
12024
- const found = await this.findTool(toolName, serverHint, signal);
12025
- if (!found) {
12026
- return `Tool "${toolName}" not found. Use mcp({ search: "..." }) to search.`;
12027
- }
12028
- const { entry, tool } = found;
12029
- try {
12030
- const result = await entry.server.callTool(tool.name, args, signal);
12031
- return serializeToolResult(result);
12032
- } catch (error) {
12033
- const message = error instanceof Error ? error.message : String(error);
12034
- return `Tool "${toolName}" call failed: ${message}`;
12035
- }
11869
+ const missing = config.dataSources.filter((source) => source.required && !sourceResults.has(source.sourceId)).map((source) => source.sourceId);
11870
+ if (missing.length) {
11871
+ throw new Error(`Required card data sources are incomplete: ${missing.join(", ")}`);
12036
11872
  }
12037
- // —— 辅助 ——
12038
- /** 跨(或按 hint)已连 server 查找工具;未连则触发懒连接。 */
12039
- async findTool(toolName, serverHint, signal) {
12040
- const specs = serverHint ? this.specsMatching(serverHint) : this.specs;
12041
- for (const spec of specs) {
12042
- const entry = this.entries.get(spec.serverName);
12043
- if (!entry || entry.status !== "connected")
12044
- continue;
12045
- const tool = entry.tools.find((t) => t.name === toolName);
12046
- if (tool) {
12047
- return { entry, server: spec.serverName, tool };
12048
- }
12049
- }
12050
- await Promise.all(specs.map((s) => this.ensureEntry(s.serverName, signal)));
12051
- for (const spec of specs) {
12052
- const entry = this.entries.get(spec.serverName);
12053
- if (!entry || entry.status !== "connected")
12054
- continue;
12055
- const tool = entry.tools.find((t) => t.name === toolName);
12056
- if (tool) {
12057
- return { entry, server: spec.serverName, tool };
12058
- }
11873
+ const resolver = {
11874
+ version: 2,
11875
+ calls: config.dataSources.filter((source) => sourceResults.has(source.sourceId)).map((source) => ({
11876
+ callId: source.sourceId,
11877
+ mcpResourceId: source.mcpResourceId,
11878
+ toolName: source.toolName,
11879
+ inputBindings: []
11880
+ })),
11881
+ outputBindings: config.bindings.filter((binding) => sourceResults.has(binding.sourceId)).map((binding) => ({
11882
+ fieldId: binding.fieldId,
11883
+ callId: binding.sourceId,
11884
+ transform: binding.transform
11885
+ }))
11886
+ };
11887
+ let viewModel;
11888
+ try {
11889
+ viewModel = await executeA2UICardResolver({
11890
+ resolver,
11891
+ fields: config.fields,
11892
+ presentationInputSchema: {
11893
+ type: "object",
11894
+ properties: {},
11895
+ additionalProperties: false
11896
+ },
11897
+ argsSchema: config.a2uiTemplate.argsSchema,
11898
+ invocation: {},
11899
+ runtimeContext,
11900
+ tools: config.dataSources.filter((source) => sourceResults.has(source.sourceId)).map((source) => ({
11901
+ resourceId: source.mcpResourceId,
11902
+ toolName: source.toolName,
11903
+ inputSchema: FALLBACK_OBJECT_SCHEMA,
11904
+ outputSchema: source.outputSchema ?? FALLBACK_OBJECT_SCHEMA,
11905
+ call: async () => ({
11906
+ structuredContent: sourceResults.get(source.sourceId)
11907
+ })
11908
+ })),
11909
+ signal
11910
+ });
11911
+ } catch (error) {
11912
+ if (error instanceof A2UICardResolverError) {
11913
+ const binding = config.bindings.find((candidate) => candidate.fieldId === error.fieldId);
11914
+ const field = config.fields.find((candidate) => candidate.fieldId === error.fieldId);
11915
+ throw new CardMappingError({
11916
+ code: error.code,
11917
+ cardId: resource.resourceId,
11918
+ fieldId: error.fieldId ?? "unknown",
11919
+ sourceId: binding?.sourceId ?? "unknown",
11920
+ expectedType: error.expectedType ?? field?.type ?? "unknown",
11921
+ actualType: error.actualType ?? "unknown",
11922
+ retryable: false
11923
+ });
12059
11924
  }
12060
- return void 0;
12061
- }
12062
- /** 按 serverName 或原始 resourceId 找 spec(server 入参可为二者)。 */
12063
- findSpec(server) {
12064
- return this.specByServerName.get(server) ?? this.specByResourceId.get(server);
12065
- }
12066
- /** serverHint(serverName 或 resourceId)命中的 spec 子集。 */
12067
- specsMatching(serverHint) {
12068
- return this.specs.filter((spec) => spec.serverName === serverHint || spec.resourceIds.includes(serverHint));
11925
+ throw error;
12069
11926
  }
12070
- /** 格式化某 server 的工具列表。 */
12071
- formatToolList(server, tools) {
12072
- if (tools.length === 0)
12073
- return `Server "${server}" has no tools.`;
12074
- const lines = [`${server} (${tools.length} tools):`, ""];
12075
- for (const tool of tools) {
12076
- const desc = truncate(tool.description ?? "", 50);
12077
- lines.push(`- ${tool.name}${desc ? " - " + desc : ""}`);
11927
+ return createPresentationResult(resource, config, viewModel);
11928
+ }
11929
+ function createPresentationResult(resource, config, viewModel) {
11930
+ const protocol = injectResolvedViewModel(JSON.parse(config.a2uiTemplate.content), viewModel);
11931
+ const cardInstanceId = `card-instance-${randomUUID()}`;
11932
+ const receipt = {
11933
+ version: 1,
11934
+ cardRef: resource.resourceId,
11935
+ cardRevision: config.revision,
11936
+ cardInstanceId,
11937
+ status: "emitted",
11938
+ ...createA2UICardPresentationReceiptContent(config.fields, viewModel),
11939
+ responsePolicy: { verbatimEcho: "forbidden", hint: "acknowledge" }
11940
+ };
11941
+ receipt.semanticSnapshot = createCardSemanticSnapshot(receipt, config.fields);
11942
+ return {
11943
+ type: "linkque.presentation-tool-result",
11944
+ modelText: formatPresentationReceiptForModel(receipt),
11945
+ receipt,
11946
+ card: {
11947
+ type: "a2ui_card",
11948
+ itemId: cardInstanceId,
11949
+ payload: { protocol },
11950
+ metadata: {
11951
+ cardRef: resource.resourceId,
11952
+ cardRevision: config.revision,
11953
+ cardInstanceId
11954
+ }
12078
11955
  }
12079
- return lines.join("\n").trim();
12080
- }
12081
- };
12082
- function parseProxyArgs(args) {
12083
- if (!isRecord(args))
12084
- return {};
12085
- const out = {};
12086
- if (typeof args.connect === "string")
12087
- out.connect = args.connect;
12088
- if (typeof args.describe === "string")
12089
- out.describe = args.describe;
12090
- if (typeof args.search === "string")
12091
- out.search = args.search;
12092
- if (Array.isArray(args.searches)) {
12093
- out.searches = args.searches.filter((query) => typeof query === "string").slice(0, MCP_BATCH_SEARCH_MAX_ITEMS);
12094
- }
12095
- if (typeof args.tool === "string")
12096
- out.tool = args.tool;
12097
- if (typeof args.server === "string")
12098
- out.server = args.server;
12099
- if (args.args !== void 0)
12100
- out.args = args.args;
12101
- return out;
11956
+ };
12102
11957
  }
12103
- function formatSchema(schema, indent = " ") {
12104
- if (!isRecord(schema))
12105
- return `${indent}No parameters defined.`;
12106
- const props = schema.properties;
12107
- if (!isRecord(props) || Object.keys(props).length === 0) {
12108
- return `${indent}No parameters defined.`;
12109
- }
12110
- const required = new Set(Array.isArray(schema.required) ? schema.required : []);
12111
- const lines = Object.entries(props).map(([key, value]) => {
12112
- const type = isRecord(value) && typeof value.type === "string" ? value.type : "any";
12113
- const desc = isRecord(value) && typeof value.description === "string" ? value.description : "";
12114
- const req = required.has(key) ? " [required]" : "";
12115
- return `${indent}- ${key} (${type})${req}${desc ? " - " + desc : ""}`;
12116
- });
12117
- return lines.join("\n");
11958
+ function formatPresentationReceiptForModel(receipt) {
11959
+ return [
11960
+ "<a2ui-presentation-receipt>",
11961
+ JSON.stringify(projectPresentationReceiptForModel(receipt)),
11962
+ "</a2ui-presentation-receipt>",
11963
+ "\u5361\u7247\u5DF2\u53D1\u51FA\uFF08\u4E0D\u4EE3\u8868\u5BA2\u6237\u7AEF\u5DF2\u6E32\u67D3\uFF09\u3002\u8BED\u4E49\u5FEB\u7167\u6765\u81EA\u6388\u6743\u7684\u6700\u7EC8\u5361\u7247\u6570\u636E\uFF1Bcolumns \u4E0E rows \u6309\u4F4D\u7F6E\u5BF9\u5E94\uFF0Cnull \u8868\u793A\u7F3A\u5931\u6216\u7A7A\u503C\uFF0Ccomplete=false \u65F6\u4E0D\u5F97\u628A\u91C7\u6837\u5F53\u4F5C\u5168\u96C6\u3002\u4E0D\u8981\u7528 Markdown \u91CD\u590D\u5217\u51FA\u6216\u6539\u5199\u5361\u7247\u4E2D\u7684\u6761\u76EE\uFF1B\u53EA\u8865\u5145\u7528\u6237\u5C1A\u672A\u5F97\u5230\u7684\u6BD4\u8F83\u3001\u89E3\u91CA\u6216\u5FC5\u8981\u8FFD\u95EE\uFF0C\u7528\u6237\u660E\u786E\u8981\u6C42\u6587\u5B57\u8868\u683C\u65F6\u53EF\u4EE5\u63D0\u4F9B\u3002\u5FEB\u7167\u672A\u5305\u542B\u7684\u4FE1\u606F\u4FDD\u6301\u672A\u77E5\uFF0C\u6E90\u5DE5\u5177\u7684\u989D\u5916\u4FE1\u606F\u4E0D\u80FD\u79F0\u4E3A\u5361\u7247\u5DF2\u5C55\u793A\u5185\u5BB9\u3002"
11964
+ ].join("\n");
12118
11965
  }
12119
- function serializeToolResult(value) {
12120
- if (typeof value === "string")
12121
- return value;
12122
- try {
12123
- const serialized = JSON.stringify(value);
12124
- return serialized === void 0 ? "\u5DE5\u5177\u6267\u884C\u5B8C\u6210\u3002" : serialized;
12125
- } catch {
12126
- return "\u5DE5\u5177\u6267\u884C\u5B8C\u6210\u3002";
12127
- }
11966
+ function projectPresentationReceiptForModel(receipt) {
11967
+ if (!receipt.semanticSnapshot)
11968
+ return receipt;
11969
+ return {
11970
+ version: receipt.version,
11971
+ cardRef: receipt.cardRef,
11972
+ cardRevision: receipt.cardRevision,
11973
+ cardInstanceId: receipt.cardInstanceId,
11974
+ status: receipt.status,
11975
+ semanticSnapshot: receipt.semanticSnapshot
11976
+ };
12128
11977
  }
12129
- function escapeRegExp(text) {
12130
- return text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
11978
+ function parseCardConfig(resource) {
11979
+ const parsed = parseA2UICardResourceConfig(resource.config);
11980
+ if (!parsed.success) {
11981
+ throw new Error(`Invalid CARD ${resource.resourceId}: ${parsed.issues.map((entry) => `${entry.path}: ${entry.message}`).join("; ")}`);
11982
+ }
11983
+ return parsed.data;
12131
11984
  }
12132
- function truncate(text, max2) {
12133
- return text.length > max2 ? `${text.slice(0, max2)}\u2026` : text;
11985
+ function isAgentPresentationToolResult(value) {
11986
+ if (!isJsonObject(value))
11987
+ return false;
11988
+ return value.type === "linkque.presentation-tool-result" && typeof value.modelText === "string" && isJsonObject(value.card) && value.card.type === "a2ui_card";
12134
11989
  }
12135
- function isRecord(value) {
12136
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
11990
+ function injectResolvedViewModel(protocol, viewModel) {
11991
+ const analysis = analyzeA2UIBindings(protocol);
11992
+ const declaredSurfaceIds = analysis.surfaceIds;
11993
+ const surfaceIds = Array.isArray(declaredSurfaceIds) && declaredSurfaceIds.every((surfaceId) => typeof surfaceId === "string") ? declaredSurfaceIds : collectA2UISurfaceIdsForLegacyContract(protocol);
11994
+ if (analysis.issues.length || surfaceIds.length === 0) {
11995
+ throw new Error("CARD template does not contain a valid A2UI surface");
11996
+ }
11997
+ return [
11998
+ ...protocol,
11999
+ {
12000
+ version: "0.9",
12001
+ datas: surfaceIds.map((surfaceId) => ({
12002
+ updateDataModel: { surfaceId, path: "/", value: viewModel }
12003
+ }))
12004
+ }
12005
+ ];
12137
12006
  }
12138
- var MCP_BATCH_SEARCH_MAX_ITEMS = 5;
12139
- var MCP_PROXY_DESCRIPTION = [
12140
- "MCP \u7F51\u5173:\u53D1\u73B0\u5E76\u8C03\u7528 MCP server \u63D0\u4F9B\u7684\u5DE5\u5177\u3002\u53EF\u7528\u52A8\u4F5C:",
12141
- "- mcp({}) \u6216 mcp({ status: true }):\u67E5\u770B\u6240\u6709 server \u8FDE\u63A5\u72B6\u6001\u4E0E\u5DE5\u5177\u6570\u3002",
12142
- '- mcp({ connect: "server" }):\u8FDE\u63A5\u5E76\u5237\u65B0\u67D0 server \u7684\u5DE5\u5177\u5217\u8868\u3002',
12143
- '- mcp({ server: "name" }):\u5217\u51FA\u8BE5 server \u7684\u5DE5\u5177\u3002',
12144
- '- mcp({ search: "\u5173\u952E\u8BCD" }):\u6309\u540D\u79F0/\u63CF\u8FF0\u6A21\u7CCA\u641C\u7D22\u5DE5\u5177(\u7A7A\u683C\u5206\u8BCD OR)\u3002',
12145
- '- mcp({ searches: ["\u5173\u952E\u8BCD1", "\u5173\u952E\u8BCD2"] }):\u4E00\u6B21\u6267\u884C\u591A\u7EC4\u641C\u7D22\u5E76\u6309 query \u5206\u7EC4\u8FD4\u56DE(\u6700\u591A 5 \u7EC4)\u3002',
12146
- '- mcp({ describe: "toolName" }):\u67E5\u770B\u67D0\u5DE5\u5177\u7684\u53C2\u6570 schema\u3002',
12147
- '- mcp({ tool: "toolName", args: { ... } }):\u8C03\u7528\u67D0\u5DE5\u5177,args \u4E3A\u5BF9\u8C61\u3002',
12148
- "\u53EF\u7528 server \u540D\u89C1 mcp({}) \u8F93\u51FA\u3002\u4EC5\u5728\u786E\u9700\u8C03\u7528 MCP \u5DE5\u5177\u65F6\u4F7F\u7528\u672C\u5DE5\u5177\u3002",
12149
- "\u4EC5 mcp({}) \u5217\u51FA\u7684\u5DE5\u5177\u53EF\u8C03\u7528(\u672A\u58F0\u660E\u7684\u5DE5\u5177\u4E0D\u4F1A\u51FA\u73B0)\u3002"
12150
- ].join("\n");
12151
- var MCP_PROXY_INPUT_SCHEMA = {
12152
- type: "object",
12153
- additionalProperties: false,
12154
- properties: {
12155
- status: {
12156
- type: "boolean",
12157
- description: "\u67E5\u770B\u6240\u6709 server \u8FDE\u63A5\u72B6\u6001(\u7B49\u4EF7\u4E8E\u7A7A\u5165\u53C2)"
12158
- },
12159
- connect: {
12160
- type: "string",
12161
- description: "\u663E\u5F0F\u8FDE\u63A5\u5E76\u5237\u65B0\u67D0 server(serverName \u6216 resourceId)"
12162
- },
12163
- server: { type: "string", description: "\u6307\u5B9A server:\u5217\u5DE5\u5177\u6216\u6D88\u6B67\u5DE5\u5177\u8C03\u7528" },
12164
- search: {
12165
- type: "string",
12166
- description: "\u6309\u540D\u79F0/\u63CF\u8FF0\u6A21\u7CCA\u641C\u7D22\u5DE5\u5177(\u7A7A\u683C\u5206\u8BCD OR)"
12167
- },
12168
- searches: {
12169
- type: "array",
12170
- description: "\u6279\u91CF\u641C\u7D22\u5173\u952E\u8BCD\uFF1B\u4E00\u6B21\u63D0\u4EA4\u6240\u6709\u5019\u9009 query\uFF0C\u6309 query \u5206\u7EC4\u8FD4\u56DE",
12171
- minItems: 1,
12172
- maxItems: MCP_BATCH_SEARCH_MAX_ITEMS,
12173
- items: { type: "string", minLength: 1 }
12174
- },
12175
- describe: { type: "string", description: "\u67E5\u770B\u67D0\u5DE5\u5177\u7684\u53C2\u6570 schema" },
12176
- tool: { type: "string", description: "\u8981\u8C03\u7528\u7684\u5DE5\u5177\u540D(\u53EF\u914D\u5408 server \u6D88\u6B67)" },
12177
- args: {
12178
- type: "object",
12179
- description: "\u5DE5\u5177\u5165\u53C2\u5BF9\u8C61(\u4EC5\u5728 tool \u6307\u5B9A\u65F6\u6709\u6548)",
12180
- additionalProperties: true
12007
+ function collectA2UISurfaceIdsForLegacyContract(protocol) {
12008
+ const surfaceIds = /* @__PURE__ */ new Set();
12009
+ for (const message of protocol) {
12010
+ if (!isJsonObject(message) || !Array.isArray(message.datas))
12011
+ continue;
12012
+ for (const instruction of message.datas) {
12013
+ if (!isJsonObject(instruction))
12014
+ continue;
12015
+ const operations = [
12016
+ "createSurface" in instruction ? instruction.createSurface : void 0,
12017
+ "updateComponents" in instruction ? instruction.updateComponents : void 0
12018
+ ];
12019
+ for (const operation of operations) {
12020
+ if (isJsonObject(operation) && typeof operation.surfaceId === "string") {
12021
+ surfaceIds.add(operation.surfaceId);
12022
+ }
12023
+ }
12181
12024
  }
12182
12025
  }
12183
- };
12184
-
12185
- // ../linkque-agent-runtime/dist/esm/core/cardActionDiagnostics.js
12186
- var CardActionDiagnostics = class {
12187
- sink;
12188
- layer;
12189
- operation;
12190
- stage = "validate";
12191
- context;
12192
- debugLog;
12193
- startedAt = performance.now();
12194
- sensitiveValues = /* @__PURE__ */ new Set();
12195
- constructor(sink, context, layer = "runtime", operation = "a2uiAction.execute") {
12196
- this.sink = sink;
12197
- this.layer = layer;
12198
- this.operation = operation;
12199
- this.context = { ...context };
12200
- if (sink) {
12201
- this.debugLog = (line, scope) => {
12202
- this.write("diagnostic", { message: line }, scope);
12203
- };
12026
+ return [...surfaceIds];
12027
+ }
12028
+ function createPresentationDescription(config) {
12029
+ return [
12030
+ config.description,
12031
+ `\u9002\u7528\u573A\u666F\uFF1A${config.whenToUse}`,
12032
+ ...config.whenNotToUse ? [`\u4E0D\u9002\u7528\u573A\u666F\uFF1A${config.whenNotToUse}`] : [],
12033
+ "\u53EA\u63D0\u4F9B\u5DF2\u58F0\u660E\u7684\u6807\u8BC6\u6216\u7B5B\u9009\u53C2\u6570\u3002\u6743\u5A01\u4E1A\u52A1\u6570\u636E\u7531\u5E73\u53F0\u89E3\u6790\u83B7\u53D6\u3002"
12034
+ ].join("\n");
12035
+ }
12036
+ function cloneJsonObject2(value, label) {
12037
+ if (!isJsonObject(value))
12038
+ throw new Error(`${label} must be a JSON object`);
12039
+ return JSON.parse(JSON.stringify(value));
12040
+ }
12041
+ function supplementMcpInput(input, invocation, presentationSchema, mcpInputSchema) {
12042
+ const result = cloneJsonObject2(input, "MCP Tool arguments");
12043
+ const presentationProperties = schemaProperties(presentationSchema);
12044
+ const mcpProperties = schemaProperties(mcpInputSchema);
12045
+ if (!presentationProperties || !mcpProperties)
12046
+ return result;
12047
+ for (const [name, mcpProperty] of Object.entries(mcpProperties)) {
12048
+ if (result[name] !== void 0 || invocation[name] === void 0)
12049
+ continue;
12050
+ const presentationProperty = presentationProperties[name];
12051
+ if (isJsonObject(presentationProperty) && isJsonObject(mcpProperty) && compatibleSchemaTypes(presentationProperty.type, mcpProperty.type)) {
12052
+ result[name] = JSON.parse(JSON.stringify(invocation[name]));
12204
12053
  }
12205
12054
  }
12206
- /** 根据绑定路径登记敏感值;解析仅为日志服务,失败不影响业务。 */
12207
- protect(readValue) {
12208
- if (!this.sink)
12209
- return;
12210
- try {
12211
- const value = readValue();
12212
- if (typeof value === "string" && value)
12213
- this.sensitiveValues.add(value);
12214
- } catch {
12215
- }
12055
+ return result;
12056
+ }
12057
+ function schemaProperties(schema) {
12058
+ return schema.type === "object" && isJsonObject(schema.properties) ? schema.properties : void 0;
12059
+ }
12060
+ function compatibleSchemaTypes(source, target) {
12061
+ if (typeof source !== "string" || typeof target !== "string")
12062
+ return false;
12063
+ return source === target || source === "integer" && target === "number";
12064
+ }
12065
+ function readStructuredContent(result) {
12066
+ if (!isJsonObject(result))
12067
+ return void 0;
12068
+ if (Object.hasOwn(result, "structuredContent") && isJsonValue(result.structuredContent)) {
12069
+ return cloneJsonValue(result.structuredContent);
12216
12070
  }
12217
- write(event, fields = {}, scope = EDebugLogScope.A2UI_ACTION) {
12218
- if (!this.sink)
12219
- return;
12220
- try {
12221
- const record2 = { ...this.context, ...fields };
12222
- if (record2.message)
12223
- record2.message = sanitizeDiagnosticText(redactKnownValues(record2.message, this.sensitiveValues));
12224
- if (record2.errorName)
12225
- record2.errorName = sanitizeDiagnosticText(redactKnownValues(record2.errorName, this.sensitiveValues));
12226
- if ("input" in record2)
12227
- record2.input = sanitizeLogValue(record2.input, this.sensitiveValues);
12228
- if ("output" in record2)
12229
- record2.output = sanitizeLogValue(record2.output, this.sensitiveValues);
12230
- this.sink(JSON.stringify({
12231
- operation: this.operation,
12232
- level: "info",
12233
- layer: this.layer,
12234
- event,
12235
- stage: this.stage,
12236
- ...record2,
12237
- costMs: Math.max(0, Math.round(performance.now() - this.startedAt))
12238
- }), scope);
12239
- } catch {
12240
- }
12071
+ if (!Array.isArray(result.content) || result.content.length === 0) {
12072
+ return void 0;
12241
12073
  }
12242
- error(event, error) {
12243
- if (!this.sink)
12244
- return;
12245
- try {
12246
- this.write(event, {
12247
- errorName: error instanceof Error ? error.name : typeof error,
12248
- message: error instanceof Error ? error.message : typeof error === "string" ? error : "\u975E\u6807\u51C6\u5F02\u5E38"
12249
- });
12250
- } catch {
12251
- }
12074
+ const texts = [];
12075
+ for (const content of result.content) {
12076
+ if (!isJsonObject(content) || content.type !== "text" || typeof content.text !== "string")
12077
+ return void 0;
12078
+ texts.push(content.text);
12079
+ }
12080
+ if (texts.length > 1)
12081
+ return texts.join("\n");
12082
+ try {
12083
+ const parsed = JSON.parse(texts[0]);
12084
+ return isJsonValue(parsed) ? cloneJsonValue(parsed) : texts[0];
12085
+ } catch {
12086
+ return texts[0];
12087
+ }
12088
+ }
12089
+ function normalizeMcpInputSchema(value) {
12090
+ if (!isJsonObject(value) || getJsonSchemaIssues2(value).length > 0) {
12091
+ return { ...FALLBACK_OBJECT_SCHEMA };
12092
+ }
12093
+ if (value.type === "object" && (!isJsonObject(value.properties) || Object.keys(value.properties).length === 0))
12094
+ return { ...FALLBACK_OBJECT_SCHEMA };
12095
+ return JSON.parse(JSON.stringify(value));
12096
+ }
12097
+ var CardMappingError = class extends Error {
12098
+ details;
12099
+ retryable = false;
12100
+ constructor(details) {
12101
+ super(JSON.stringify(details));
12102
+ this.name = "CardMappingError";
12103
+ this.details = details;
12252
12104
  }
12253
12105
  };
12254
- function sanitizeLogValue(value, sensitiveValues) {
12255
- const seen = /* @__PURE__ */ new WeakSet();
12256
- let nodes = 200;
12257
- let characters = 4e3;
12258
- const visit = (item, depth, key = "") => {
12259
- if (/authorization|cookie|token|secret|password|api[_-]?key|access[_-]?key|private[_-]?key|^(?:ak|sk|userId|orderId|tradeNO|phone|mobile|email|idCard)$/iu.test(key)) {
12260
- if (typeof item === "string" && item)
12261
- sensitiveValues.add(item);
12262
- return "<redacted>";
12106
+ function isJsonObject(value) {
12107
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
12108
+ }
12109
+
12110
+ // ../linkque-agent-runtime/dist/esm/core/mcpAggregator.js
12111
+ function aggregateMcpServers(resources, protocolAgentId) {
12112
+ const specs = /* @__PURE__ */ new Map();
12113
+ const touch = (serverName) => {
12114
+ let spec = specs.get(serverName);
12115
+ if (!spec) {
12116
+ spec = {
12117
+ serverName,
12118
+ agentId: "",
12119
+ argsMappingRules: [],
12120
+ allowedTools: void 0,
12121
+ resourceIds: [],
12122
+ description: ""
12123
+ };
12124
+ specs.set(serverName, spec);
12263
12125
  }
12264
- if (--nodes < 0 || depth > 8 || characters <= 0)
12265
- return "<truncated>";
12266
- if (item === null || typeof item === "number" || typeof item === "boolean")
12267
- return item;
12268
- if (typeof item === "string") {
12269
- if (/^\s*[{[]/u.test(item)) {
12270
- if (item.length > 16e3)
12271
- return "<truncated JSON>";
12272
- try {
12273
- return JSON.stringify(visit(JSON.parse(item), depth + 1));
12274
- } catch {
12275
- return "<invalid JSON>";
12276
- }
12277
- }
12278
- const text2 = sanitizeDiagnosticText(redactKnownValues(item, sensitiveValues));
12279
- const result2 = text2.slice(0, Math.min(512, characters));
12280
- characters -= result2.length;
12281
- return result2.length < item.length ? `${result2}<truncated>` : result2;
12126
+ return spec;
12127
+ };
12128
+ for (const resource of resources) {
12129
+ const serverName = resource.config.serverName ?? resource.resourceId;
12130
+ const spec = touch(serverName);
12131
+ spec.resourceIds.push(resource.resourceId);
12132
+ if (!spec.agentId) {
12133
+ spec.agentId = protocolAgentId ?? resource.config.agentId;
12282
12134
  }
12283
- if (typeof item !== "object")
12284
- return `<${typeof item}>`;
12285
- if (seen.has(item))
12286
- return "<circular>";
12287
- seen.add(item);
12288
- try {
12289
- const keys = Object.keys(item);
12290
- const result2 = /* @__PURE__ */ Object.create(null);
12291
- for (const name of keys.slice(0, 20)) {
12292
- const descriptor = Object.getOwnPropertyDescriptor(item, name);
12293
- if (name === "value" && Object.getOwnPropertyDescriptor(item, "kind")?.value === "literal" && typeof descriptor?.value === "string" && descriptor.value)
12294
- sensitiveValues.add(descriptor.value);
12295
- 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>";
12135
+ if (!spec.description)
12136
+ spec.description = resource.config.description;
12137
+ if (resource.resourceType === EResourceType.MCP) {
12138
+ for (const rule of resource.config.argsMappingRules ?? []) {
12139
+ spec.argsMappingRules.push(rule);
12296
12140
  }
12297
- if (Array.isArray(item)) {
12298
- const values = Object.values(result2);
12299
- if (keys.length > 20)
12300
- values.push("<truncated>");
12301
- return values;
12141
+ const allowed = resource.config.allowedTools;
12142
+ if (allowed && allowed.length > 0) {
12143
+ if (!spec.allowedTools)
12144
+ spec.allowedTools = /* @__PURE__ */ new Set();
12145
+ for (const toolName of allowed)
12146
+ spec.allowedTools.add(toolName);
12302
12147
  }
12303
- if (keys.length > 20)
12304
- result2["<truncated>"] = true;
12305
- return result2;
12306
- } catch {
12307
- return "<unreadable>";
12308
- } finally {
12309
- seen.delete(item);
12148
+ continue;
12149
+ }
12150
+ if (!spec.allowedTools)
12151
+ spec.allowedTools = /* @__PURE__ */ new Set();
12152
+ spec.allowedTools.add(resource.config.toolName);
12153
+ for (const rule of resource.config.argsMappingRules ?? []) {
12154
+ const fullRule = {
12155
+ mcpToolName: resource.config.toolName,
12156
+ argJsonPath: rule.argJsonPath,
12157
+ disabled: rule.disabled,
12158
+ valueType: rule.valueType,
12159
+ ...rule.value !== void 0 ? { value: rule.value } : {}
12160
+ };
12161
+ spec.argsMappingRules.push(fullRule);
12310
12162
  }
12311
- };
12312
- const result = visit(value, 0);
12313
- const text = JSON.stringify(result);
12314
- return text.length > 6e3 ? { truncated: true, preview: text.slice(0, 2e3) } : result;
12315
- }
12316
- function sanitizeDiagnosticText(value) {
12317
- 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);
12318
- }
12319
- function redactKnownValues(text, sensitiveValues) {
12320
- let result = text;
12321
- for (const sensitive of sensitiveValues)
12322
- result = result.replaceAll(sensitive, "<redacted>");
12323
- return result;
12324
- }
12325
-
12326
- // ../linkque-agent-runtime/dist/esm/core/cardActionExecutor.js
12327
- async function executeCardAction(input) {
12328
- const diagnostics = new CardActionDiagnostics(input.debugLog, {
12329
- agentId: input.protocol.agentId,
12330
- threadId: input.runtimeContext.threadId
12331
- });
12332
- diagnostics.protect(() => input.runtimeContext.userId);
12333
- diagnostics.protect(() => input.runtimeContext.tenantId);
12334
- diagnostics.write("started", {
12335
- input: { request: input.request, runtimeContext: input.runtimeContext }
12336
- });
12337
- try {
12338
- const response = await executeCardActionInternal(input, diagnostics);
12339
- diagnostics.write(response.ok ? "completed" : "failed", response.ok ? { output: response } : {
12340
- code: response.error.code,
12341
- retryable: response.error.retryable,
12342
- output: response
12343
- });
12344
- return response;
12345
- } catch (error) {
12346
- diagnostics.error("failed", error);
12347
- throw error;
12348
12163
  }
12164
+ return [...specs.values()];
12349
12165
  }
12350
- async function executeCardActionInternal(input, diagnostics) {
12351
- let request;
12352
- try {
12353
- request = parseA2UIActionExecuteRequest(input.request);
12354
- } catch (error) {
12355
- return failure("INVALID_INPUT", errorMessage(error, "\u652F\u4ED8\u52A8\u4F5C\u8BF7\u6C42\u65E0\u6548"), false);
12166
+
12167
+ // ../linkque-agent-runtime/dist/esm/core/mcpProxyTool.js
12168
+ var MCP_PROXY_TOOL_NAME = "mcp";
12169
+ var McpProxyTool = class {
12170
+ provider;
12171
+ /** serverName → 缓存条目(同 serverName 多 resourceId 聚合为一个连接)。 */
12172
+ entries = /* @__PURE__ */ new Map();
12173
+ /** 进行中的连接(去重并发 ensureEntry)。 */
12174
+ inFlight = /* @__PURE__ */ new Map();
12175
+ specByServerName;
12176
+ /** 原始 resourceId → 所属 spec(resolve(resourceId,...) 反查用)。 */
12177
+ specByResourceId;
12178
+ specs;
12179
+ debugLog;
12180
+ constructor(provider, specs, options = {}) {
12181
+ this.provider = provider;
12182
+ this.specs = specs;
12183
+ this.specByServerName = new Map(specs.map((spec) => [spec.serverName, spec]));
12184
+ this.specByResourceId = new Map(specs.flatMap((spec) => spec.resourceIds.map((id) => [id, spec])));
12185
+ this.debugLog = options.debugLog ?? (() => {
12186
+ });
12356
12187
  }
12357
- Object.assign(diagnostics.context, {
12358
- invocationId: request.invocationId,
12359
- actionId: request.actionId,
12360
- cardRef: request.source.cardRef,
12361
- cardRevision: request.source.cardRevision
12362
- });
12363
- if (request.agentId !== input.protocol.agentId) {
12364
- return failure("AGENT_MISMATCH", "\u652F\u4ED8\u52A8\u4F5C\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
12188
+ /**
12189
+ * 产单个 `mcp` 代理工具描述符,注入 `agentReq.tools`。
12190
+ * `execute` 闭包按入参字段派发到 status/connect/list/search/describe/call。
12191
+ */
12192
+ asTool() {
12193
+ return {
12194
+ name: MCP_PROXY_TOOL_NAME,
12195
+ modelName: MCP_PROXY_TOOL_NAME,
12196
+ label: "MCP",
12197
+ description: MCP_PROXY_DESCRIPTION,
12198
+ inputSchema: MCP_PROXY_INPUT_SCHEMA,
12199
+ execute: (args, signal) => this.dispatch(args, signal)
12200
+ };
12365
12201
  }
12366
- if (request.threadId !== input.runtimeContext.threadId) {
12367
- return failure("INVALID_INPUT", "\u652F\u4ED8\u52A8\u4F5C\u4E0E\u5F53\u524D\u4F1A\u8BDD\u4E0D\u5339\u914D", false);
12202
+ /** {@link IMcpToolRegistry.resolve}:按 (resourceId, toolName) 解析可调用句柄。 */
12203
+ async resolve(resourceId, toolName, signal) {
12204
+ const spec = this.findSpec(resourceId);
12205
+ if (!spec)
12206
+ return void 0;
12207
+ const entry = await this.ensureEntry(spec.serverName, signal);
12208
+ if (!entry || !entry.server)
12209
+ return void 0;
12210
+ const tool = entry.tools.find((t) => t.name === toolName);
12211
+ if (!tool)
12212
+ return void 0;
12213
+ return {
12214
+ inputSchema: tool.inputSchema,
12215
+ outputSchema: tool.outputSchema,
12216
+ execute: (args, sig) => entry.server.callTool(tool.name, args, sig)
12217
+ };
12368
12218
  }
12369
- if (!input.runtimeContext.userId.trim()) {
12370
- return failure("AUTH_REQUIRED", "\u652F\u4ED8\u52A8\u4F5C\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
12219
+ /** 关闭所有已连 server(忽略单 server 关闭错误)。 */
12220
+ async closeAll() {
12221
+ await Promise.all([...this.entries.values()].map(async (entry) => {
12222
+ if (!entry.server)
12223
+ return;
12224
+ try {
12225
+ await entry.server.close?.();
12226
+ } catch (error) {
12227
+ try {
12228
+ this.debugLog(`[mcp] server ${entry.server.serverName} close failed: ${error instanceof Error ? error.message : "unknown error"}`, EDebugLogScope.MCP);
12229
+ } catch {
12230
+ }
12231
+ }
12232
+ }));
12371
12233
  }
12372
- diagnostics.write("validated", { output: request });
12373
- diagnostics.stage = "binding";
12374
- diagnostics.write("binding_started", {
12375
- input: { source: request.source, actionId: request.actionId }
12376
- });
12377
- const resolved = resolvePaymentBinding(input.protocol, request.source, request.actionId);
12378
- if (!resolved.ok) {
12379
- diagnostics.write("binding_failed", { output: resolved.response });
12380
- return resolved.response;
12234
+ // —— 内部:连接与缓存 ——
12235
+ /** 确保某 server 已连;返回 connected 条目,依失败返回 null(不抛错)。 */
12236
+ async ensureEntry(serverName, signal) {
12237
+ const existing = this.entries.get(serverName);
12238
+ if (existing) {
12239
+ return existing.status === "connected" ? existing : null;
12240
+ }
12241
+ let promise = this.inFlight.get(serverName);
12242
+ if (!promise) {
12243
+ promise = this.connect(serverName, signal).finally(() => {
12244
+ this.inFlight.delete(serverName);
12245
+ });
12246
+ this.inFlight.set(serverName, promise);
12247
+ }
12248
+ const entry = await promise;
12249
+ return entry.status === "connected" ? entry : null;
12381
12250
  }
12382
- Object.assign(diagnostics.context, {
12383
- mcpResourceId: resolved.binding.createTrade.mcpResourceId,
12384
- toolName: resolved.binding.createTrade.toolName
12385
- });
12386
- protectBindingValues(diagnostics, resolved.binding.createTrade.inputBindings);
12387
- diagnostics.write("binding_resolved", { output: resolved.binding });
12388
- diagnostics.stage = "tool_resolve";
12389
- const registry = createRegistry(input.protocol, input.mcpServerProvider, diagnostics.debugLog);
12390
- try {
12391
- diagnostics.write("tool_resolve_started", {
12392
- input: resolved.binding.createTrade
12393
- });
12394
- const tool = await registry.resolve(resolved.binding.createTrade.mcpResourceId, resolved.binding.createTrade.toolName, input.signal);
12395
- diagnostics.write("tool_resolved", {
12396
- output: {
12397
- found: Boolean(tool),
12398
- inputSchema: tool?.inputSchema,
12399
- outputSchema: tool?.outputSchema
12400
- }
12401
- });
12402
- if (!tool) {
12403
- return failure("TOOL_NOT_ALLOWED", "\u521B\u5EFA\u4EA4\u6613 MCP Tool \u4E0D\u5B58\u5728\u6216\u672A\u6388\u6743", false);
12251
+ /** 连单个 server 并 listTools;按 spec.allowedTools 过滤后缓存;失败记为 failed。 */
12252
+ async connect(serverName, _signal) {
12253
+ const spec = this.specByServerName.get(serverName);
12254
+ if (!spec) {
12255
+ const entry = {
12256
+ server: null,
12257
+ tools: [],
12258
+ status: "failed",
12259
+ error: `unknown serverName: ${serverName}`
12260
+ };
12261
+ this.entries.set(serverName, entry);
12262
+ this.debugLog(`[mcp] server ${serverName} unknown serverName`, EDebugLogScope.MCP);
12263
+ return entry;
12404
12264
  }
12405
- diagnostics.stage = "tool_input";
12406
- diagnostics.write("tool_input_started", {
12407
- input: {
12408
- bindings: resolved.binding.createTrade.inputBindings,
12409
- actionContext: request.actionContext,
12410
- runtimeContext: input.runtimeContext
12411
- }
12412
- });
12413
- const args = createToolInput(resolved.binding.createTrade.inputBindings, request.actionContext, input.runtimeContext);
12414
- diagnostics.write("tool_input_completed", {
12415
- output: { mapped: Boolean(args), args }
12416
- });
12417
- if (!args)
12418
- return failure("INVALID_INPUT", "\u65E0\u6CD5\u751F\u6210\u521B\u5EFA\u4EA4\u6613 MCP \u5165\u53C2", false);
12419
- let result;
12420
- diagnostics.stage = "tool_execute";
12421
- diagnostics.write("tool_started", { input: args });
12422
12265
  try {
12423
- result = await tool.execute(args, input.signal);
12424
- diagnostics.protect(() => readJsonPointer(readStructuredContent(result), resolved.binding.createTrade.tradeNoPath));
12425
- diagnostics.write("tool_completed", { output: result });
12266
+ const synthetic = {
12267
+ resourceId: spec.serverName,
12268
+ resourceType: EResourceType.MCP,
12269
+ providerType: EResourceProviderType.ALIPAY_OPEN,
12270
+ config: {
12271
+ agentId: spec.agentId,
12272
+ serverName: spec.serverName,
12273
+ description: spec.description,
12274
+ argsMappingRules: spec.argsMappingRules
12275
+ }
12276
+ };
12277
+ const servers = await this.provider.servers([synthetic]);
12278
+ const server = servers[0];
12279
+ if (!server) {
12280
+ throw new Error(`provider returned no server for ${spec.serverName}`);
12281
+ }
12282
+ const all = await server.listTools();
12283
+ const tools = spec.allowedTools ? all.filter((tool) => spec.allowedTools.has(tool.name)) : all;
12284
+ const entry = { server, tools, status: "connected" };
12285
+ this.entries.set(serverName, entry);
12286
+ this.debugLog(`[mcp] server ${spec.serverName} connected (${tools.length}/${all.length} tools)`, EDebugLogScope.MCP);
12287
+ return entry;
12426
12288
  } catch (error) {
12427
- diagnostics.error("tool_failed", error);
12428
- return failure("EXECUTION_FAILED", "\u521B\u5EFA\u4EA4\u6613\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5", true);
12289
+ const message = error instanceof Error ? error.message : String(error);
12290
+ const entry = {
12291
+ server: null,
12292
+ tools: [],
12293
+ status: "failed",
12294
+ error: message
12295
+ };
12296
+ this.entries.set(serverName, entry);
12297
+ this.debugLog(`[mcp] server ${spec.serverName} connect failed: ${message}`, EDebugLogScope.MCP);
12298
+ return entry;
12429
12299
  }
12430
- diagnostics.stage = "tool_output";
12431
- diagnostics.write("tool_output_started", {
12432
- input: { result, tradeNoPath: resolved.binding.createTrade.tradeNoPath }
12433
- });
12434
- const structured = readStructuredContent(result);
12435
- const tradeNO = readJsonPointer(structured, resolved.binding.createTrade.tradeNoPath);
12436
- diagnostics.write("tool_output_completed", {
12437
- output: {
12438
- structured,
12439
- tradeNO,
12440
- valid: typeof tradeNO === "string" && Boolean(tradeNO.trim()) && tradeNO.length <= 64
12300
+ }
12301
+ // —— 派发 ——
12302
+ /** 按入参字段派发;返回 LLM 可读文本。 */
12303
+ async dispatch(args, signal) {
12304
+ const params = parseProxyArgs(args);
12305
+ if (params.connect !== void 0) {
12306
+ return this.executeConnect(params.connect, signal);
12307
+ }
12308
+ if (params.describe !== void 0) {
12309
+ return this.executeDescribe(params.describe, params.server, signal);
12310
+ }
12311
+ if (params.searches !== void 0) {
12312
+ return this.executeBatchSearch(params.searches, params.server);
12313
+ }
12314
+ if (params.search !== void 0) {
12315
+ return this.executeSearch(params.search, params.server);
12316
+ }
12317
+ if (params.tool !== void 0) {
12318
+ return this.executeCall(params.tool, params.args, params.server, signal);
12319
+ }
12320
+ if (params.server !== void 0) {
12321
+ return this.executeList(params.server, signal);
12322
+ }
12323
+ return this.executeStatus();
12324
+ }
12325
+ /** `mcp({})` / `mcp({ status: true })`:列各 server 连接状态 + 工具数。 */
12326
+ executeStatus() {
12327
+ const lines = [];
12328
+ let connected = 0;
12329
+ let totalTools = 0;
12330
+ for (const spec of this.specs) {
12331
+ const label = spec.serverName;
12332
+ const entry = this.entries.get(spec.serverName);
12333
+ if (!entry) {
12334
+ lines.push(`\u25CB ${label} (not connected)`);
12335
+ continue;
12336
+ }
12337
+ if (entry.status === "connected") {
12338
+ connected += 1;
12339
+ totalTools += entry.tools.length;
12340
+ lines.push(`\u2713 ${label} (${entry.tools.length} tools)`);
12341
+ } else {
12342
+ lines.push(`\u2717 ${label} (failed${entry.error ? ": " + entry.error : ""})`);
12441
12343
  }
12442
- });
12443
- if (typeof tradeNO !== "string" || !tradeNO.trim() || tradeNO.length > 64) {
12444
- return failure("INVALID_OUTPUT", "\u521B\u5EFA\u4EA4\u6613 MCP \u672A\u8FD4\u56DE\u6709\u6548 tradeNO", false);
12445
12344
  }
12446
- return {
12447
- ok: true,
12448
- invocationId: request.invocationId,
12449
- result: { kind: "payment", tradeNO }
12450
- };
12451
- } finally {
12452
- const stage = diagnostics.stage;
12453
- diagnostics.stage = "cleanup";
12454
- diagnostics.write("cleanup_started", {
12455
- input: { mcpResourceId: diagnostics.context.mcpResourceId }
12456
- });
12457
- await registry.closeAll();
12458
- diagnostics.write("cleanup_completed", {
12459
- output: { closeAttempted: true }
12460
- });
12461
- diagnostics.stage = stage;
12345
+ const header = `MCP: ${connected}/${this.specs.length} servers, ${totalTools} tools`;
12346
+ const hint = this.specs.length > 0 ? '\nmcp({ server: "name" }) to list tools, mcp({ search: "..." }) to search, mcp({ tool: "...", args: {...} }) to call' : "\n(no MCP resources configured)";
12347
+ return `${header}
12348
+
12349
+ ${lines.join("\n")}${hint}`.trim();
12462
12350
  }
12463
- }
12464
- async function verifyPaymentResult(input) {
12465
- const diagnostics = new CardActionDiagnostics(input.debugLog, {
12466
- agentId: input.protocol.agentId,
12467
- threadId: input.runtimeContext.threadId
12468
- }, "runtime", "a2uiAction.verifyPaymentResult");
12469
- diagnostics.protect(() => input.runtimeContext.userId);
12470
- diagnostics.protect(() => input.runtimeContext.tenantId);
12471
- diagnostics.write("started", {
12472
- input: {
12473
- payload: input.payload,
12474
- source: input.source,
12475
- runtimeContext: input.runtimeContext
12351
+ /** `mcp({ connect: "server" })`:显式连接并刷元数据,返回该 server 工具列表。 */
12352
+ async executeConnect(server, signal) {
12353
+ const spec = this.findSpec(server);
12354
+ if (!spec)
12355
+ return `Server "${server}" not found. Use mcp({}) to see available servers.`;
12356
+ this.entries.delete(spec.serverName);
12357
+ const entry = await this.ensureEntry(spec.serverName, signal);
12358
+ if (!entry) {
12359
+ const failed = this.entries.get(spec.serverName);
12360
+ const detail = failed?.error ? `: ${failed.error}` : "";
12361
+ return `Failed to connect to "${spec.serverName}"${detail}.`;
12476
12362
  }
12477
- });
12478
- try {
12479
- const result = await verifyPaymentResultInternal(input, diagnostics);
12480
- diagnostics.write("completed", { output: result });
12481
- return result;
12482
- } catch (error) {
12483
- diagnostics.error("failed", error);
12484
- throw error;
12363
+ return this.formatToolList(spec.serverName, entry.tools);
12485
12364
  }
12486
- }
12487
- async function verifyPaymentResultInternal(input, diagnostics) {
12488
- const payload = parseA2UIPaymentResultEventPayload(input.payload);
12489
- Object.assign(diagnostics.context, {
12490
- invocationId: payload.actionInvocationId,
12491
- actionId: payload.actionId,
12492
- cardRef: input.source.cardRef,
12493
- cardRevision: input.source.cardRevision
12494
- });
12495
- diagnostics.write("validated", { output: payload });
12496
- if (payload.callback.resultCode !== "9000") {
12497
- throw new Error("\u53EA\u6709 resultCode=9000 \u7684\u652F\u4ED8\u56DE\u8C03\u53EF\u4EE5\u8FDB\u5165\u670D\u52A1\u7AEF\u6838\u9A8C");
12365
+ /** `mcp({ server: "name" })`:列该 server 工具名 + 截断 description。 */
12366
+ async executeList(server, signal) {
12367
+ const spec = this.findSpec(server);
12368
+ if (!spec)
12369
+ return `Server "${server}" not found. Use mcp({}) to see available servers.`;
12370
+ const entry = await this.ensureEntry(spec.serverName, signal);
12371
+ if (!entry) {
12372
+ return `Server "${spec.serverName}" is not connected. Use mcp({ connect: "${spec.serverName}" }) to retry.`;
12373
+ }
12374
+ return this.formatToolList(spec.serverName, entry.tools);
12498
12375
  }
12499
- diagnostics.stage = "binding";
12500
- diagnostics.write("binding_started", {
12501
- input: { source: input.source, actionId: payload.actionId }
12502
- });
12503
- const resolved = resolvePaymentBinding(input.protocol, input.source, payload.actionId);
12504
- if (resolved.ok)
12505
- protectBindingValues(diagnostics, resolved.binding.queryTrade.inputBindings);
12506
- diagnostics.write("binding_resolved", { output: resolved });
12507
- if (!resolved.ok)
12508
- throw new Error(resolved.response.error.message);
12509
- Object.assign(diagnostics.context, {
12510
- mcpResourceId: resolved.binding.queryTrade.mcpResourceId,
12511
- toolName: resolved.binding.queryTrade.toolName
12512
- });
12513
- diagnostics.stage = "tool_resolve";
12514
- const registry = createRegistry(input.protocol, input.mcpServerProvider, diagnostics.debugLog);
12515
- try {
12516
- diagnostics.write("tool_resolve_started", {
12517
- input: resolved.binding.queryTrade
12518
- });
12519
- const tool = await registry.resolve(resolved.binding.queryTrade.mcpResourceId, resolved.binding.queryTrade.toolName, input.signal);
12520
- diagnostics.write("tool_resolved", {
12521
- output: {
12522
- found: Boolean(tool),
12523
- inputSchema: tool?.inputSchema,
12524
- outputSchema: tool?.outputSchema
12525
- }
12526
- });
12527
- if (!tool)
12528
- throw new Error("\u67E5\u8BE2\u652F\u4ED8\u7ED3\u679C MCP Tool \u4E0D\u5B58\u5728\u6216\u672A\u6388\u6743");
12529
- diagnostics.stage = "tool_input";
12530
- diagnostics.write("tool_input_started", {
12531
- input: {
12532
- bindings: resolved.binding.queryTrade.inputBindings,
12533
- actionContext: payload.actionContext,
12534
- runtimeContext: input.runtimeContext,
12535
- tradeNO: payload.tradeNO,
12536
- callback: payload.callback
12376
+ /** `mcp({ search: "query" })`:空格分词 OR 子串匹配 name/description(跨所有 server)。 */
12377
+ async executeSearch(query, serverHint) {
12378
+ const terms = query.trim().split(/\s+/u).filter((t) => t.length > 0);
12379
+ if (terms.length === 0)
12380
+ return "Search query cannot be empty.";
12381
+ const pattern = new RegExp(terms.map(escapeRegExp).join("|"), "iu");
12382
+ const specs = serverHint ? this.specsMatching(serverHint) : this.specs;
12383
+ await Promise.all(specs.map((s) => this.ensureEntry(s.serverName)));
12384
+ const matches = [];
12385
+ for (const spec of specs) {
12386
+ const entry = this.entries.get(spec.serverName);
12387
+ if (!entry || entry.status !== "connected")
12388
+ continue;
12389
+ for (const tool of entry.tools) {
12390
+ if (pattern.test(tool.name) || pattern.test(tool.description ?? "")) {
12391
+ matches.push({ server: spec.serverName, tool });
12392
+ }
12537
12393
  }
12538
- });
12539
- const args = createToolInput(resolved.binding.queryTrade.inputBindings, payload.actionContext, input.runtimeContext, payload.tradeNO, payload.callback);
12540
- diagnostics.write("tool_input_completed", {
12541
- output: { mapped: Boolean(args), args }
12542
- });
12543
- if (!args)
12544
- throw new Error("\u65E0\u6CD5\u751F\u6210\u67E5\u8BE2\u652F\u4ED8\u7ED3\u679C MCP \u5165\u53C2");
12545
- diagnostics.stage = "tool_execute";
12546
- diagnostics.write("tool_started", { input: args });
12547
- const result = await tool.execute(args, input.signal);
12548
- diagnostics.write("tool_completed", { output: result });
12549
- diagnostics.stage = "tool_output";
12550
- diagnostics.write("tool_output_started", {
12551
- input: {
12552
- result,
12553
- statusPath: resolved.binding.queryTrade.statusPath,
12554
- paidValues: resolved.binding.queryTrade.paidValues
12394
+ }
12395
+ if (matches.length === 0) {
12396
+ return serverHint ? `No tools matching "${query}" in "${serverHint}"` : `No tools matching "${query}"`;
12397
+ }
12398
+ const lines = [`Found ${matches.length} tool(s) matching "${query}":`, ""];
12399
+ for (const { server, tool } of matches) {
12400
+ lines.push(`${tool.name} [${server}]`);
12401
+ lines.push(` ${tool.description ?? "(no description)"}`);
12402
+ if (tool.inputSchema) {
12403
+ lines.push(` Parameters:
12404
+ ${formatSchema(tool.inputSchema, " ")}`);
12555
12405
  }
12556
- });
12557
- const structured = readStructuredContent(result);
12558
- const data = cloneJsonObject(structured);
12559
- if (!data)
12560
- throw new Error("\u67E5\u8BE2\u652F\u4ED8\u7ED3\u679C MCP \u5FC5\u987B\u8FD4\u56DE JSON object");
12561
- const status = readJsonPointer(data, resolved.binding.queryTrade.statusPath);
12562
- diagnostics.write("tool_output_completed", {
12563
- output: { data, status, valid: isJsonPrimitive2(status) }
12564
- });
12565
- if (!isJsonPrimitive2(status))
12566
- throw new Error("\u67E5\u8BE2\u652F\u4ED8\u7ED3\u679C MCP \u72B6\u6001\u5B57\u6BB5\u65E0\u6548");
12567
- return {
12568
- paid: resolved.binding.queryTrade.paidValues.some((value) => Object.is(value, status)),
12569
- status,
12570
- data
12571
- };
12572
- } finally {
12573
- const stage = diagnostics.stage;
12574
- diagnostics.stage = "cleanup";
12575
- diagnostics.write("cleanup_started", {
12576
- input: { mcpResourceId: diagnostics.context.mcpResourceId }
12577
- });
12578
- await registry.closeAll();
12579
- diagnostics.write("cleanup_completed", {
12580
- output: { closeAttempted: true }
12581
- });
12582
- diagnostics.stage = stage;
12583
- }
12584
- }
12585
- function resolvePaymentBinding(protocol, source, actionId) {
12586
- const card = protocol.agent.resources.find((resource) => resource.resourceType === EResourceType.CARD && resource.resourceId === source.cardRef);
12587
- if (!card)
12588
- return {
12589
- ok: false,
12590
- response: failure("CARD_NOT_FOUND", "\u652F\u4ED8\u5361\u7247\u4E0D\u5B58\u5728", false)
12591
- };
12592
- if (card.config.revision !== source.cardRevision) {
12593
- return {
12594
- ok: false,
12595
- response: failure("CARD_REVISION_MISMATCH", "\u652F\u4ED8\u5361\u7247\u7248\u672C\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5", false)
12596
- };
12597
- }
12598
- const binding = card.config.schemaVersion === "3" || card.config.schemaVersion === "4" ? card.config.actionBindings?.find((candidate) => candidate.actionId === actionId) : void 0;
12599
- if (!binding)
12600
- return {
12601
- ok: false,
12602
- response: failure("ACTION_NOT_FOUND", "\u652F\u4ED8\u52A8\u4F5C\u672A\u7ED1\u5B9A", false)
12603
- };
12604
- if (binding.kind !== "payment") {
12605
- return {
12606
- ok: false,
12607
- response: failure("ACTION_KIND_MISMATCH", "\u52A8\u4F5C\u4E0D\u662F\u652F\u4ED8\u7C7B\u578B", false)
12608
- };
12406
+ lines.push("");
12407
+ }
12408
+ return lines.join("\n").trim();
12609
12409
  }
12610
- return { ok: true, binding };
12611
- }
12612
- function protectBindingValues(diagnostics, bindings) {
12613
- for (const binding of bindings) {
12614
- diagnostics.protect(() => binding.source.kind === "literal" ? binding.source.value : void 0);
12410
+ /** `mcp({ searches: [...] })`:一次连接元数据并按 query 分组执行多组搜索。 */
12411
+ async executeBatchSearch(queries, serverHint) {
12412
+ const normalized = [
12413
+ ...new Set(queries.map((query) => query.trim()).filter(Boolean))
12414
+ ].slice(0, MCP_BATCH_SEARCH_MAX_ITEMS);
12415
+ if (normalized.length === 0) {
12416
+ return "Batch search requires at least one non-empty query.";
12417
+ }
12418
+ const specs = serverHint ? this.specsMatching(serverHint) : this.specs;
12419
+ await Promise.all(specs.map((spec) => this.ensureEntry(spec.serverName)));
12420
+ const results = await Promise.all(normalized.map((query) => this.executeSearch(query, serverHint)));
12421
+ return results.map((result, index) => `Query ${index + 1}: "${normalized[index]}"
12422
+ ${result}`).join("\n\n");
12615
12423
  }
12616
- }
12617
- function createRegistry(protocol, provider, debugLog) {
12618
- const resources = protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL);
12619
- return new McpProxyTool(provider, aggregateMcpServers(resources, protocol.agentId), { debugLog });
12620
- }
12621
- function createToolInput(bindings, actionContext, runtimeContext, tradeNO, callback) {
12622
- const result = {};
12623
- for (const binding of bindings) {
12624
- let value;
12625
- switch (binding.source.kind) {
12626
- case "action-context":
12627
- value = readJsonPointer(actionContext, binding.source.path);
12628
- break;
12629
- case "runtime-context":
12630
- value = runtimeContext[binding.source.key];
12631
- break;
12632
- case "literal":
12633
- value = binding.source.value;
12634
- break;
12635
- case "trade-no":
12636
- value = tradeNO;
12637
- break;
12638
- case "callback":
12639
- value = callback ? readJsonPointer(callback, binding.source.path) : void 0;
12640
- break;
12424
+ /** `mcp({ describe: "tool" })`:输出工具所属 server + 参数 schema。 */
12425
+ async executeDescribe(toolName, serverHint, signal) {
12426
+ const found = await this.findTool(toolName, serverHint, signal);
12427
+ if (!found) {
12428
+ return `Tool "${toolName}" not found. Use mcp({ search: "..." }) to search.`;
12641
12429
  }
12642
- if (value === void 0 || !writeJsonPointer(result, binding.inputPath, value)) {
12643
- return void 0;
12430
+ const { server, tool } = found;
12431
+ const lines = [
12432
+ `${tool.name}`,
12433
+ `Server: ${server}`,
12434
+ "",
12435
+ tool.description ?? "(no description)"
12436
+ ];
12437
+ if (tool.inputSchema) {
12438
+ lines.push("", `Parameters:
12439
+ ${formatSchema(tool.inputSchema)}`);
12440
+ } else {
12441
+ lines.push("", "No parameters defined.");
12644
12442
  }
12443
+ return lines.join("\n").trim();
12645
12444
  }
12646
- return result;
12647
- }
12648
- function readStructuredContent(result) {
12649
- const object3 = cloneJsonObject(result);
12650
- if (!object3)
12651
- return void 0;
12652
- if (cloneJsonObject(object3.structuredContent))
12653
- return object3.structuredContent;
12654
- if (!Array.isArray(object3.content) || object3.content.length !== 1)
12655
- return void 0;
12656
- const content = cloneJsonObject(object3.content[0]);
12657
- if (!content || content.type !== "text" || typeof content.text !== "string")
12658
- return void 0;
12659
- try {
12660
- return JSON.parse(content.text);
12661
- } catch {
12662
- return void 0;
12663
- }
12664
- }
12665
- function failure(code, message, retryable) {
12666
- return { ok: false, error: { code, message, retryable } };
12667
- }
12668
- function errorMessage(error, fallback) {
12669
- return error instanceof Error && error.message.trim() ? error.message : fallback;
12670
- }
12671
- function isJsonPrimitive2(value) {
12672
- return value === null || ["string", "number", "boolean"].includes(typeof value);
12673
- }
12674
-
12675
- // ../linkque-agent-runtime/dist/esm/core/followUpQuestions.js
12676
- var FOLLOW_UP_QUESTION_MAX_COUNT = 3;
12677
- var FOLLOW_UP_QUESTION_MAX_LENGTH = 20;
12678
- var FOLLOW_UP_CONTEXT_MAX_HISTORY_RUNS = 2;
12679
- var FOLLOW_UP_CONTEXT_TOKEN_BUDGET = 2e3;
12680
- function prepareFollowUpQuestionContext(turns, history = []) {
12681
- const visible = turns.flatMap((turn) => {
12682
- if (turn.role !== "user" && turn.role !== "assistant")
12683
- return [];
12684
- if (typeof turn.content !== "string")
12685
- return [];
12686
- const content = turn.content.replace(/\s+/gu, " ").trim();
12687
- return content ? [{ role: turn.role, content }] : [];
12688
- });
12689
- let assistantIndex = -1;
12690
- let userIndex = -1;
12691
- for (let index = visible.length - 1; index >= 0; index -= 1) {
12692
- if (assistantIndex < 0 && visible[index].role === "assistant") {
12693
- assistantIndex = index;
12694
- continue;
12445
+ /** `mcp({ tool: "name", args: {...} })`:调用工具,返回序列化结果。 */
12446
+ async executeCall(toolName, args, serverHint, signal) {
12447
+ const found = await this.findTool(toolName, serverHint, signal);
12448
+ if (!found) {
12449
+ return `Tool "${toolName}" not found. Use mcp({ search: "..." }) to search.`;
12695
12450
  }
12696
- if (assistantIndex >= 0 && index < assistantIndex && visible[index].role === "user") {
12697
- userIndex = index;
12698
- break;
12451
+ const { entry, tool } = found;
12452
+ try {
12453
+ const result = await entry.server.callTool(tool.name, args, signal);
12454
+ return serializeToolResult(result);
12455
+ } catch (error) {
12456
+ const message = error instanceof Error ? error.message : String(error);
12457
+ return `Tool "${toolName}" call failed: ${message}`;
12699
12458
  }
12700
12459
  }
12701
- if (userIndex < 0 || assistantIndex < 0)
12702
- return void 0;
12703
- const lastUserMessage = visible[userIndex].content;
12704
- const assistantTokens = estimateTokens(visible[assistantIndex].content);
12705
- const userTokens = estimateTokens(lastUserMessage);
12706
- const assistantBudget = Math.min(assistantTokens, 1500);
12707
- const userBudget = Math.min(userTokens, FOLLOW_UP_CONTEXT_TOKEN_BUDGET - assistantBudget);
12708
- let remaining = FOLLOW_UP_CONTEXT_TOKEN_BUDGET - assistantBudget - userBudget;
12709
- const messages = [
12710
- {
12711
- role: "user",
12712
- content: truncateToEstimatedTokens(lastUserMessage, userBudget)
12713
- },
12714
- {
12715
- role: "assistant",
12716
- content: truncateToEstimatedTokens(visible[assistantIndex].content, assistantBudget)
12460
+ // —— 辅助 ——
12461
+ /** 跨(或按 hint)已连 server 查找工具;未连则触发懒连接。 */
12462
+ async findTool(toolName, serverHint, signal) {
12463
+ const specs = serverHint ? this.specsMatching(serverHint) : this.specs;
12464
+ for (const spec of specs) {
12465
+ const entry = this.entries.get(spec.serverName);
12466
+ if (!entry || entry.status !== "connected")
12467
+ continue;
12468
+ const tool = entry.tools.find((t) => t.name === toolName);
12469
+ if (tool) {
12470
+ return { entry, server: spec.serverName, tool };
12471
+ }
12717
12472
  }
12718
- ];
12719
- const normalizedHistory = history.slice(-FOLLOW_UP_CONTEXT_MAX_HISTORY_RUNS).map(normalizeHistoryEntry).filter((entry) => Boolean(entry));
12720
- const selectedHistory = [];
12721
- for (let index = normalizedHistory.length - 1; index >= 0; index -= 1) {
12722
- if (remaining <= 0)
12723
- break;
12724
- const entry = normalizedHistory[index];
12725
- let entryRemaining = remaining;
12726
- const followUpQuestions = [];
12727
- for (const question of entry.followUpQuestions) {
12728
- const tokens = estimateTokens(question);
12729
- if (tokens > entryRemaining)
12730
- break;
12731
- followUpQuestions.push(question);
12732
- entryRemaining -= tokens;
12473
+ await Promise.all(specs.map((s) => this.ensureEntry(s.serverName, signal)));
12474
+ for (const spec of specs) {
12475
+ const entry = this.entries.get(spec.serverName);
12476
+ if (!entry || entry.status !== "connected")
12477
+ continue;
12478
+ const tool = entry.tools.find((t) => t.name === toolName);
12479
+ if (tool) {
12480
+ return { entry, server: spec.serverName, tool };
12481
+ }
12482
+ }
12483
+ return void 0;
12484
+ }
12485
+ /** 按 serverName 或原始 resourceId 找 spec(server 入参可为二者)。 */
12486
+ findSpec(server) {
12487
+ return this.specByServerName.get(server) ?? this.specByResourceId.get(server);
12488
+ }
12489
+ /** serverHint(serverName 或 resourceId)命中的 spec 子集。 */
12490
+ specsMatching(serverHint) {
12491
+ return this.specs.filter((spec) => spec.serverName === serverHint || spec.resourceIds.includes(serverHint));
12492
+ }
12493
+ /** 格式化某 server 的工具列表。 */
12494
+ formatToolList(server, tools) {
12495
+ if (tools.length === 0)
12496
+ return `Server "${server}" has no tools.`;
12497
+ const lines = [`${server} (${tools.length} tools):`, ""];
12498
+ for (const tool of tools) {
12499
+ const desc = truncate(tool.description ?? "", 50);
12500
+ lines.push(`- ${tool.name}${desc ? " - " + desc : ""}`);
12733
12501
  }
12734
- const userMessage = truncateToEstimatedTokens(entry.userMessage, entryRemaining);
12735
- if (!userMessage)
12736
- continue;
12737
- entryRemaining -= estimateTokens(userMessage);
12738
- remaining = entryRemaining;
12739
- selectedHistory.unshift({ userMessage, followUpQuestions });
12502
+ return lines.join("\n").trim();
12740
12503
  }
12741
- return {
12742
- messages,
12743
- lastUserMessage,
12744
- ...selectedHistory.length ? { history: selectedHistory } : {}
12745
- };
12746
- }
12747
- function normalizeHistoryEntry(entry) {
12748
- const userMessage = entry.userMessage.replace(/\s+/gu, " ").trim();
12749
- if (!userMessage)
12750
- return void 0;
12751
- return {
12752
- userMessage,
12753
- followUpQuestions: normalizeFollowUpQuestionStrings(entry.followUpQuestions)
12754
- };
12755
- }
12756
- function normalizeFollowUpQuestionStrings(value) {
12757
- if (!Array.isArray(value))
12758
- return [];
12759
- const seen = /* @__PURE__ */ new Set();
12760
- const result = [];
12761
- for (const candidate of value) {
12762
- if (typeof candidate !== "string")
12763
- continue;
12764
- const normalized = candidate.replace(/\s+/gu, " ").trim();
12765
- if (!normalized || normalized.length > FOLLOW_UP_QUESTION_MAX_LENGTH || seen.has(normalized))
12766
- continue;
12767
- seen.add(normalized);
12768
- result.push(normalized);
12769
- if (result.length === FOLLOW_UP_QUESTION_MAX_COUNT)
12770
- break;
12504
+ };
12505
+ function parseProxyArgs(args) {
12506
+ if (!isRecord(args))
12507
+ return {};
12508
+ const out = {};
12509
+ if (typeof args.connect === "string")
12510
+ out.connect = args.connect;
12511
+ if (typeof args.describe === "string")
12512
+ out.describe = args.describe;
12513
+ if (typeof args.search === "string")
12514
+ out.search = args.search;
12515
+ if (Array.isArray(args.searches)) {
12516
+ out.searches = args.searches.filter((query) => typeof query === "string").slice(0, MCP_BATCH_SEARCH_MAX_ITEMS);
12771
12517
  }
12772
- return result;
12518
+ if (typeof args.tool === "string")
12519
+ out.tool = args.tool;
12520
+ if (typeof args.server === "string")
12521
+ out.server = args.server;
12522
+ if (args.args !== void 0)
12523
+ out.args = args.args;
12524
+ return out;
12773
12525
  }
12774
- function estimateTokens(text) {
12775
- let tokens = 0;
12776
- let asciiRun = 0;
12777
- const flushAscii = () => {
12778
- if (asciiRun > 0)
12779
- tokens += Math.ceil(asciiRun / 4);
12780
- asciiRun = 0;
12781
- };
12782
- for (const character of text) {
12783
- if (/^[\x20-\x7e]$/u.test(character))
12784
- asciiRun += 1;
12785
- else {
12786
- flushAscii();
12787
- tokens += 1;
12788
- }
12526
+ function formatSchema(schema, indent = " ") {
12527
+ if (!isRecord(schema))
12528
+ return `${indent}No parameters defined.`;
12529
+ const props = schema.properties;
12530
+ if (!isRecord(props) || Object.keys(props).length === 0) {
12531
+ return `${indent}No parameters defined.`;
12789
12532
  }
12790
- flushAscii();
12791
- return Math.max(tokens, 1);
12533
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
12534
+ const lines = Object.entries(props).map(([key, value]) => {
12535
+ const type = isRecord(value) && typeof value.type === "string" ? value.type : "any";
12536
+ const desc = isRecord(value) && typeof value.description === "string" ? value.description : "";
12537
+ const req = required.has(key) ? " [required]" : "";
12538
+ return `${indent}- ${key} (${type})${req}${desc ? " - " + desc : ""}`;
12539
+ });
12540
+ return lines.join("\n");
12792
12541
  }
12793
- function truncateToEstimatedTokens(text, budget) {
12794
- if (estimateTokens(text) <= budget)
12795
- return text;
12796
- let low = 0;
12797
- let high = text.length;
12798
- while (low < high) {
12799
- const middle = Math.ceil((low + high) / 2);
12800
- if (estimateTokens(text.slice(0, middle)) <= budget)
12801
- low = middle;
12802
- else
12803
- high = middle - 1;
12542
+ function serializeToolResult(value) {
12543
+ if (typeof value === "string")
12544
+ return value;
12545
+ try {
12546
+ const serialized = JSON.stringify(value);
12547
+ return serialized === void 0 ? "\u5DE5\u5177\u6267\u884C\u5B8C\u6210\u3002" : serialized;
12548
+ } catch {
12549
+ return "\u5DE5\u5177\u6267\u884C\u5B8C\u6210\u3002";
12804
12550
  }
12805
- return text.slice(0, low).trim();
12806
12551
  }
12807
-
12808
- // ../linkque-agent-runtime/dist/esm/core/cardTools.js
12809
- import { randomUUID } from "node:crypto";
12810
-
12811
- // ../linkque-agent-runtime/dist/esm/core/mcpNaming.js
12812
- import { createHash } from "node:crypto";
12813
- function stableToolName(prefix, raw) {
12814
- const readable = raw.replace(/[^A-Za-z0-9_-]+/gu, "_").replace(/^_+|_+$/gu, "").slice(0, 38) || "resource";
12815
- const digest = createHash("sha256").update(raw).digest("hex").slice(0, 10);
12816
- return `${prefix}_${readable}_${digest}`;
12552
+ function escapeRegExp(text) {
12553
+ return text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
12554
+ }
12555
+ function truncate(text, max2) {
12556
+ return text.length > max2 ? `${text.slice(0, max2)}\u2026` : text;
12557
+ }
12558
+ function isRecord(value) {
12559
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
12817
12560
  }
12561
+ var MCP_BATCH_SEARCH_MAX_ITEMS = 5;
12562
+ var MCP_PROXY_DESCRIPTION = [
12563
+ "MCP \u7F51\u5173:\u53D1\u73B0\u5E76\u8C03\u7528 MCP server \u63D0\u4F9B\u7684\u5DE5\u5177\u3002\u53EF\u7528\u52A8\u4F5C:",
12564
+ "- mcp({}) \u6216 mcp({ status: true }):\u67E5\u770B\u6240\u6709 server \u8FDE\u63A5\u72B6\u6001\u4E0E\u5DE5\u5177\u6570\u3002",
12565
+ '- mcp({ connect: "server" }):\u8FDE\u63A5\u5E76\u5237\u65B0\u67D0 server \u7684\u5DE5\u5177\u5217\u8868\u3002',
12566
+ '- mcp({ server: "name" }):\u5217\u51FA\u8BE5 server \u7684\u5DE5\u5177\u3002',
12567
+ '- mcp({ search: "\u5173\u952E\u8BCD" }):\u6309\u540D\u79F0/\u63CF\u8FF0\u6A21\u7CCA\u641C\u7D22\u5DE5\u5177(\u7A7A\u683C\u5206\u8BCD OR)\u3002',
12568
+ '- mcp({ searches: ["\u5173\u952E\u8BCD1", "\u5173\u952E\u8BCD2"] }):\u4E00\u6B21\u6267\u884C\u591A\u7EC4\u641C\u7D22\u5E76\u6309 query \u5206\u7EC4\u8FD4\u56DE(\u6700\u591A 5 \u7EC4)\u3002',
12569
+ '- mcp({ describe: "toolName" }):\u67E5\u770B\u67D0\u5DE5\u5177\u7684\u53C2\u6570 schema\u3002',
12570
+ '- mcp({ tool: "toolName", args: { ... } }):\u8C03\u7528\u67D0\u5DE5\u5177,args \u4E3A\u5BF9\u8C61\u3002',
12571
+ "\u53EF\u7528 server \u540D\u89C1 mcp({}) \u8F93\u51FA\u3002\u4EC5\u5728\u786E\u9700\u8C03\u7528 MCP \u5DE5\u5177\u65F6\u4F7F\u7528\u672C\u5DE5\u5177\u3002",
12572
+ "\u4EC5 mcp({}) \u5217\u51FA\u7684\u5DE5\u5177\u53EF\u8C03\u7528(\u672A\u58F0\u660E\u7684\u5DE5\u5177\u4E0D\u4F1A\u51FA\u73B0)\u3002"
12573
+ ].join("\n");
12574
+ var MCP_PROXY_INPUT_SCHEMA = {
12575
+ type: "object",
12576
+ additionalProperties: false,
12577
+ properties: {
12578
+ status: {
12579
+ type: "boolean",
12580
+ description: "\u67E5\u770B\u6240\u6709 server \u8FDE\u63A5\u72B6\u6001(\u7B49\u4EF7\u4E8E\u7A7A\u5165\u53C2)"
12581
+ },
12582
+ connect: {
12583
+ type: "string",
12584
+ description: "\u663E\u5F0F\u8FDE\u63A5\u5E76\u5237\u65B0\u67D0 server(serverName \u6216 resourceId)"
12585
+ },
12586
+ server: { type: "string", description: "\u6307\u5B9A server:\u5217\u5DE5\u5177\u6216\u6D88\u6B67\u5DE5\u5177\u8C03\u7528" },
12587
+ search: {
12588
+ type: "string",
12589
+ description: "\u6309\u540D\u79F0/\u63CF\u8FF0\u6A21\u7CCA\u641C\u7D22\u5DE5\u5177(\u7A7A\u683C\u5206\u8BCD OR)"
12590
+ },
12591
+ searches: {
12592
+ type: "array",
12593
+ description: "\u6279\u91CF\u641C\u7D22\u5173\u952E\u8BCD\uFF1B\u4E00\u6B21\u63D0\u4EA4\u6240\u6709\u5019\u9009 query\uFF0C\u6309 query \u5206\u7EC4\u8FD4\u56DE",
12594
+ minItems: 1,
12595
+ maxItems: MCP_BATCH_SEARCH_MAX_ITEMS,
12596
+ items: { type: "string", minLength: 1 }
12597
+ },
12598
+ describe: { type: "string", description: "\u67E5\u770B\u67D0\u5DE5\u5177\u7684\u53C2\u6570 schema" },
12599
+ tool: { type: "string", description: "\u8981\u8C03\u7528\u7684\u5DE5\u5177\u540D(\u53EF\u914D\u5408 server \u6D88\u6B67)" },
12600
+ args: {
12601
+ type: "object",
12602
+ description: "\u5DE5\u5177\u5165\u53C2\u5BF9\u8C61(\u4EC5\u5728 tool \u6307\u5B9A\u65F6\u6709\u6548)",
12603
+ additionalProperties: true
12604
+ }
12605
+ }
12606
+ };
12818
12607
 
12819
- // ../linkque-agent-runtime/dist/esm/core/cardSemanticSnapshot.js
12820
- var MAX_BYTES = 6e3;
12821
- var MAX_LABEL = 160;
12822
- function createCardSemanticSnapshot(receipt, fields) {
12823
- const groups = receipt.coverage.map((coverage) => {
12824
- const field = fields.find((f) => f.fieldId === coverage.fieldId);
12825
- const entities = receipt.entities.filter((e) => e.fieldId === coverage.fieldId);
12826
- const echo = field?.presentation?.visibility === "echo";
12827
- const attributes = echo ? [...new Set(entities.flatMap((e) => Object.keys(e.attributes ?? {})))] : [];
12828
- const hasValue = echo && entities.some((e) => Object.hasOwn(e, "value"));
12829
- const hasLabel = echo && entities.some((e) => !Object.hasOwn(e, "value"));
12830
- const columns = [
12831
- "\u6761\u76EE\u5F15\u7528",
12832
- ...hasLabel ? [columnLabel(field, field?.presentation?.labelPath, "\u540D\u79F0")] : [],
12833
- ...hasValue ? [short(coverage.label)] : [],
12834
- ...attributes.map((path2) => columnLabel(field, path2, path2))
12835
- ];
12836
- const rows = entities.map((e) => [
12837
- e.ref,
12838
- ...hasLabel ? [e.label] : [],
12839
- ...hasValue ? [e.value ?? null] : [],
12840
- ...attributes.map((path2) => e.attributes?.[path2] ?? null)
12841
- ]);
12842
- const total = coverage.itemCount ?? (coverage.present ? 1 : 0);
12843
- return {
12844
- field: coverage.fieldId,
12845
- label: short(coverage.label),
12846
- present: coverage.present,
12847
- total,
12848
- included: rows.length,
12849
- complete: echo && coverage.present && rows.length === total && !entities.some((e) => e.truncated) && !receipt.omissions.some((o) => o.fieldId === coverage.fieldId),
12850
- columns,
12851
- rows
12852
- };
12853
- });
12854
- const snapshot = {
12855
- version: 1,
12856
- groups,
12857
- omissions: receipt.omissions.map((o) => ({ ...o }))
12858
- };
12859
- while (bytes(snapshot) > MAX_BYTES) {
12860
- let group;
12861
- for (let i = groups.length - 1; i >= 0; i--) {
12862
- if (groups[i].rows.length > 0) {
12863
- group = groups[i];
12864
- break;
12608
+ // ../linkque-agent-runtime/dist/esm/core/homeData.js
12609
+ async function executeHomeData(input) {
12610
+ let request;
12611
+ try {
12612
+ request = parseHomeDataRequest(input.request);
12613
+ } catch (error) {
12614
+ return failure("INVALID_INPUT", error instanceof Error ? error.message : "\u9996\u9875\u5361\u7247\u8BF7\u6C42\u65E0\u6548", false);
12615
+ }
12616
+ if (request.agentId !== input.protocol.agentId) {
12617
+ return failure("AGENT_MISMATCH", "\u9996\u9875\u6570\u636E\u8BF7\u6C42\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
12618
+ }
12619
+ if (!input.userId.trim()) {
12620
+ return failure("AUTH_REQUIRED", "\u9996\u9875\u6570\u636E\u8BF7\u6C42\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
12621
+ }
12622
+ const resources = input.protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL);
12623
+ const specs = aggregateMcpServers(resources, input.protocol.agentId);
12624
+ const spec = specs.find((candidate) => candidate.serverName === request.binding.mcpName);
12625
+ if (!spec) {
12626
+ return failure("MCP_NOT_BOUND", "\u5F53\u524D Agent \u672A\u7ED1\u5B9A\u8BE5 MCP", false);
12627
+ }
12628
+ if (spec.allowedTools && !spec.allowedTools.has(request.binding.toolName)) {
12629
+ return failure("TOOL_NOT_ALLOWED", "\u5F53\u524D Agent \u672A\u5141\u8BB8\u8C03\u7528\u8BE5 MCP \u5DE5\u5177", false);
12630
+ }
12631
+ const registry = new McpProxyTool(input.mcpServerProvider, specs);
12632
+ try {
12633
+ const handle = await registry.resolve(spec.resourceIds[0], request.binding.toolName, input.signal);
12634
+ if (!handle) {
12635
+ return failure("TOOL_NOT_ALLOWED", "MCP \u5DE5\u5177\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528", false);
12636
+ }
12637
+ const toolInput = {};
12638
+ for (const mapping of request.binding.input) {
12639
+ let value;
12640
+ switch (mapping.source.kind) {
12641
+ case "parameter":
12642
+ value = readJsonPointer(request.parameters, mapping.source.pointer);
12643
+ break;
12644
+ case "runtime-context":
12645
+ value = mapping.source.key === "agentId" ? input.protocol.agentId : input.userId;
12646
+ break;
12647
+ case "literal":
12648
+ value = mapping.source.value;
12649
+ break;
12650
+ }
12651
+ if (value === void 0 || !writeJsonPointer(toolInput, mapping.target, value)) {
12652
+ return failure("INVALID_INPUT", `\u65E0\u6CD5\u751F\u6210 MCP \u5165\u53C2 ${mapping.target}`, false);
12865
12653
  }
12866
12654
  }
12867
- snapshot.truncated = true;
12868
- if (group) {
12869
- group.rows.pop();
12870
- group.included = group.rows.length;
12871
- group.complete = false;
12872
- } else if (groups.length) {
12873
- groups.pop();
12874
- } else if (snapshot.omissions.length) {
12875
- snapshot.omissions.pop();
12876
- } else
12877
- break;
12655
+ let result;
12656
+ try {
12657
+ result = await handle.execute(toolInput, input.signal);
12658
+ } catch (error) {
12659
+ return failure("EXECUTION_FAILED", error instanceof Error ? error.message : "MCP \u5DE5\u5177\u8C03\u7528\u5931\u8D25", true);
12660
+ }
12661
+ const structured = readStructuredContent2(result);
12662
+ let cardData = structured;
12663
+ if (request.binding.transform) {
12664
+ try {
12665
+ cardData = executeStructuralTransform(request.binding.transform, structured);
12666
+ } catch (error) {
12667
+ return failure("TRANSFORM_FAILED", error instanceof Error ? error.message : "\u9996\u9875\u5361\u7247\u6570\u636E\u8F6C\u6362\u5931\u8D25", false);
12668
+ }
12669
+ }
12670
+ const cardDataObject = cloneJsonObject(cardData);
12671
+ if (!cardDataObject) {
12672
+ return failure("INVALID_CARD_DATA", "\u9996\u9875\u5361\u7247\u6570\u636E\u5FC5\u987B\u662F JSON object", false);
12673
+ }
12674
+ return { ok: true, data: cardDataObject };
12675
+ } finally {
12676
+ await registry.closeAll();
12878
12677
  }
12879
- return snapshot;
12880
- }
12881
- function bytes(value) {
12882
- return Buffer.byteLength(JSON.stringify(value));
12883
- }
12884
- function short(value) {
12885
- return value.length > MAX_LABEL ? `${value.slice(0, MAX_LABEL - 1)}\u2026` : value;
12886
12678
  }
12887
- function columnLabel(field, path2, fallback) {
12888
- if (!field || !path2)
12889
- return short(fallback);
12890
- let schema = field.type === "array" ? field.valueSchema.items : field.valueSchema;
12891
- for (const token of path2.slice(1).split("/").map((t) => t.replaceAll("~1", "/").replaceAll("~0", "~"))) {
12892
- if (!schema || typeof schema !== "object" || Array.isArray(schema))
12893
- return short(fallback);
12894
- const properties = schema.properties;
12895
- if (!properties || typeof properties !== "object" || Array.isArray(properties) || !Object.hasOwn(properties, token))
12896
- return short(fallback);
12897
- schema = properties[token];
12679
+ function readStructuredContent2(result) {
12680
+ const object3 = cloneJsonObject(result);
12681
+ if (!object3)
12682
+ return void 0;
12683
+ if (cloneJsonObject(object3.structuredContent)) {
12684
+ return object3.structuredContent;
12685
+ }
12686
+ if (!Array.isArray(object3.content) || object3.content.length !== 1) {
12687
+ return void 0;
12688
+ }
12689
+ const content = cloneJsonObject(object3.content[0]);
12690
+ if (!content || content.type !== "text" || typeof content.text !== "string") {
12691
+ return void 0;
12692
+ }
12693
+ try {
12694
+ return JSON.parse(content.text);
12695
+ } catch {
12696
+ return void 0;
12898
12697
  }
12899
- const title = schema && typeof schema === "object" && !Array.isArray(schema) ? schema.title : void 0;
12900
- return short(typeof title === "string" && title ? title : fallback);
12901
12698
  }
12902
-
12903
- // ../linkque-agent-runtime/dist/esm/core/cardTools.js
12904
- var FALLBACK_OBJECT_SCHEMA = {
12905
- type: "object",
12906
- additionalProperties: true
12907
- };
12908
- function createCardPresentationToolName(resourceId) {
12909
- return stableToolName("a2ui_card", resourceId);
12699
+ function failure(code, message, retryable) {
12700
+ return { ok: false, error: { code, message, retryable } };
12910
12701
  }
12911
- async function executeCardPresentation(resource, registry, runtimeContext, args, signal) {
12912
- const config = parseCardConfig(resource);
12913
- if (config.schemaVersion !== "2") {
12914
- throw new Error(`Schema v${config.schemaVersion} cards must be executed through the card data-source loop`);
12915
- }
12916
- const invocation = cloneJsonObject2(args, "Presentation Tool arguments");
12917
- const viewModel = await executeA2UICardResolver({
12918
- resolver: config.resolver,
12919
- fields: config.fields,
12920
- presentationInputSchema: config.presentationInputSchema,
12921
- argsSchema: config.a2uiTemplate.argsSchema,
12922
- invocation,
12923
- runtimeContext,
12924
- tools: await Promise.all(config.resolver.calls.map(async (call) => {
12925
- const handle = await registry.resolve(call.mcpResourceId, call.toolName, signal);
12926
- if (!handle) {
12927
- throw new Error(`MCP tool ${call.mcpResourceId}/${call.toolName} is unavailable`);
12928
- }
12929
- const inputSchema = normalizeMcpInputSchema(handle.inputSchema);
12930
- return {
12931
- resourceId: call.mcpResourceId,
12932
- toolName: call.toolName,
12933
- // 旧 MCP server 可能只在开放平台元数据中声明 Schema,但
12934
- // tools/list 未返回。运行时不因此拒绝调用:有实时 Schema 时用它
12935
- // 做额外校验,缺失时依赖 CARD 已固化的字段 Schema 与最终
12936
- // ViewModel Schema 校验。
12937
- inputSchema,
12938
- outputSchema: isJsonObject(handle.outputSchema) ? handle.outputSchema : FALLBACK_OBJECT_SCHEMA,
12939
- call: async (input, callSignal) => {
12940
- const result = await handle.execute(supplementMcpInput(input, invocation, config.presentationInputSchema, inputSchema), callSignal);
12941
- return { structuredContent: readStructuredContent2(result) };
12942
- }
12702
+
12703
+ // ../linkque-agent-runtime/dist/esm/core/cardActionDiagnostics.js
12704
+ var CardActionDiagnostics = class {
12705
+ sink;
12706
+ layer;
12707
+ operation;
12708
+ stage = "validate";
12709
+ context;
12710
+ debugLog;
12711
+ startedAt = performance.now();
12712
+ sensitiveValues = /* @__PURE__ */ new Set();
12713
+ constructor(sink, context, layer = "runtime", operation = "a2uiAction.execute") {
12714
+ this.sink = sink;
12715
+ this.layer = layer;
12716
+ this.operation = operation;
12717
+ this.context = { ...context };
12718
+ if (sink) {
12719
+ this.debugLog = (line, scope) => {
12720
+ this.write("diagnostic", { message: line }, scope);
12943
12721
  };
12944
- })),
12945
- signal
12946
- });
12947
- return createPresentationResult(resource, config, viewModel);
12948
- }
12949
- async function executeCardPresentationFromSources(resource, runtimeContext, sourceResults, signal) {
12950
- const config = parseCardConfig(resource);
12951
- if (config.schemaVersion !== "3" && config.schemaVersion !== "4") {
12952
- throw new Error("Source-result rendering is only available for schema v3/v4 cards");
12722
+ }
12953
12723
  }
12954
- const missing = config.dataSources.filter((source) => source.required && !sourceResults.has(source.sourceId)).map((source) => source.sourceId);
12955
- if (missing.length) {
12956
- throw new Error(`Required card data sources are incomplete: ${missing.join(", ")}`);
12724
+ /** 根据绑定路径登记敏感值;解析仅为日志服务,失败不影响业务。 */
12725
+ protect(readValue) {
12726
+ if (!this.sink)
12727
+ return;
12728
+ try {
12729
+ const value = readValue();
12730
+ if (typeof value === "string" && value)
12731
+ this.sensitiveValues.add(value);
12732
+ } catch {
12733
+ }
12957
12734
  }
12958
- const resolver = {
12959
- version: 2,
12960
- calls: config.dataSources.filter((source) => sourceResults.has(source.sourceId)).map((source) => ({
12961
- callId: source.sourceId,
12962
- mcpResourceId: source.mcpResourceId,
12963
- toolName: source.toolName,
12964
- inputBindings: []
12965
- })),
12966
- outputBindings: config.bindings.filter((binding) => sourceResults.has(binding.sourceId)).map((binding) => ({
12967
- fieldId: binding.fieldId,
12968
- callId: binding.sourceId,
12969
- transform: binding.transform
12970
- }))
12735
+ write(event, fields = {}, scope = EDebugLogScope.A2UI_ACTION) {
12736
+ if (!this.sink)
12737
+ return;
12738
+ try {
12739
+ const record2 = { ...this.context, ...fields };
12740
+ if (record2.message)
12741
+ record2.message = sanitizeDiagnosticText(redactKnownValues(record2.message, this.sensitiveValues));
12742
+ if (record2.errorName)
12743
+ record2.errorName = sanitizeDiagnosticText(redactKnownValues(record2.errorName, this.sensitiveValues));
12744
+ if ("input" in record2)
12745
+ record2.input = sanitizeLogValue(record2.input, this.sensitiveValues);
12746
+ if ("output" in record2)
12747
+ record2.output = sanitizeLogValue(record2.output, this.sensitiveValues);
12748
+ this.sink(JSON.stringify({
12749
+ operation: this.operation,
12750
+ level: "info",
12751
+ layer: this.layer,
12752
+ event,
12753
+ stage: this.stage,
12754
+ ...record2,
12755
+ costMs: Math.max(0, Math.round(performance.now() - this.startedAt))
12756
+ }), scope);
12757
+ } catch {
12758
+ }
12759
+ }
12760
+ error(event, error) {
12761
+ if (!this.sink)
12762
+ return;
12763
+ try {
12764
+ this.write(event, {
12765
+ errorName: error instanceof Error ? error.name : typeof error,
12766
+ message: error instanceof Error ? error.message : typeof error === "string" ? error : "\u975E\u6807\u51C6\u5F02\u5E38"
12767
+ });
12768
+ } catch {
12769
+ }
12770
+ }
12771
+ };
12772
+ function sanitizeLogValue(value, sensitiveValues) {
12773
+ const seen = /* @__PURE__ */ new WeakSet();
12774
+ let nodes = 200;
12775
+ let characters = 4e3;
12776
+ const visit = (item, depth, key = "") => {
12777
+ if (/authorization|cookie|token|secret|password|api[_-]?key|access[_-]?key|private[_-]?key|^(?:ak|sk|userId|orderId|tradeNO|phone|mobile|email|idCard)$/iu.test(key)) {
12778
+ if (typeof item === "string" && item)
12779
+ sensitiveValues.add(item);
12780
+ return "<redacted>";
12781
+ }
12782
+ if (--nodes < 0 || depth > 8 || characters <= 0)
12783
+ return "<truncated>";
12784
+ if (item === null || typeof item === "number" || typeof item === "boolean")
12785
+ return item;
12786
+ if (typeof item === "string") {
12787
+ if (/^\s*[{[]/u.test(item)) {
12788
+ if (item.length > 16e3)
12789
+ return "<truncated JSON>";
12790
+ try {
12791
+ return JSON.stringify(visit(JSON.parse(item), depth + 1));
12792
+ } catch {
12793
+ return "<invalid JSON>";
12794
+ }
12795
+ }
12796
+ const text2 = sanitizeDiagnosticText(redactKnownValues(item, sensitiveValues));
12797
+ const result2 = text2.slice(0, Math.min(512, characters));
12798
+ characters -= result2.length;
12799
+ return result2.length < item.length ? `${result2}<truncated>` : result2;
12800
+ }
12801
+ if (typeof item !== "object")
12802
+ return `<${typeof item}>`;
12803
+ if (seen.has(item))
12804
+ return "<circular>";
12805
+ seen.add(item);
12806
+ try {
12807
+ const keys = Object.keys(item);
12808
+ const result2 = /* @__PURE__ */ Object.create(null);
12809
+ for (const name of keys.slice(0, 20)) {
12810
+ const descriptor = Object.getOwnPropertyDescriptor(item, name);
12811
+ if (name === "value" && Object.getOwnPropertyDescriptor(item, "kind")?.value === "literal" && typeof descriptor?.value === "string" && descriptor.value)
12812
+ sensitiveValues.add(descriptor.value);
12813
+ 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>";
12814
+ }
12815
+ if (Array.isArray(item)) {
12816
+ const values = Object.values(result2);
12817
+ if (keys.length > 20)
12818
+ values.push("<truncated>");
12819
+ return values;
12820
+ }
12821
+ if (keys.length > 20)
12822
+ result2["<truncated>"] = true;
12823
+ return result2;
12824
+ } catch {
12825
+ return "<unreadable>";
12826
+ } finally {
12827
+ seen.delete(item);
12828
+ }
12971
12829
  };
12972
- let viewModel;
12830
+ const result = visit(value, 0);
12831
+ const text = JSON.stringify(result);
12832
+ return text.length > 6e3 ? { truncated: true, preview: text.slice(0, 2e3) } : result;
12833
+ }
12834
+ function sanitizeDiagnosticText(value) {
12835
+ 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);
12836
+ }
12837
+ function redactKnownValues(text, sensitiveValues) {
12838
+ let result = text;
12839
+ for (const sensitive of sensitiveValues)
12840
+ result = result.replaceAll(sensitive, "<redacted>");
12841
+ return result;
12842
+ }
12843
+
12844
+ // ../linkque-agent-runtime/dist/esm/core/cardActionExecutor.js
12845
+ async function executeCardAction(input) {
12846
+ const diagnostics = new CardActionDiagnostics(input.debugLog, {
12847
+ agentId: input.protocol.agentId,
12848
+ threadId: input.runtimeContext.threadId
12849
+ });
12850
+ diagnostics.protect(() => input.runtimeContext.userId);
12851
+ diagnostics.protect(() => input.runtimeContext.tenantId);
12852
+ diagnostics.write("started", {
12853
+ input: { request: input.request, runtimeContext: input.runtimeContext }
12854
+ });
12973
12855
  try {
12974
- viewModel = await executeA2UICardResolver({
12975
- resolver,
12976
- fields: config.fields,
12977
- presentationInputSchema: {
12978
- type: "object",
12979
- properties: {},
12980
- additionalProperties: false
12981
- },
12982
- argsSchema: config.a2uiTemplate.argsSchema,
12983
- invocation: {},
12984
- runtimeContext,
12985
- tools: config.dataSources.filter((source) => sourceResults.has(source.sourceId)).map((source) => ({
12986
- resourceId: source.mcpResourceId,
12987
- toolName: source.toolName,
12988
- inputSchema: FALLBACK_OBJECT_SCHEMA,
12989
- outputSchema: source.outputSchema ?? FALLBACK_OBJECT_SCHEMA,
12990
- call: async () => ({
12991
- structuredContent: sourceResults.get(source.sourceId)
12992
- })
12993
- })),
12994
- signal
12856
+ const response = await executeCardActionInternal(input, diagnostics);
12857
+ diagnostics.write(response.ok ? "completed" : "failed", response.ok ? { output: response } : {
12858
+ code: response.error.code,
12859
+ retryable: response.error.retryable,
12860
+ output: response
12995
12861
  });
12862
+ return response;
12996
12863
  } catch (error) {
12997
- if (error instanceof A2UICardResolverError) {
12998
- const binding = config.bindings.find((candidate) => candidate.fieldId === error.fieldId);
12999
- const field = config.fields.find((candidate) => candidate.fieldId === error.fieldId);
13000
- throw new CardMappingError({
13001
- code: error.code,
13002
- cardId: resource.resourceId,
13003
- fieldId: error.fieldId ?? "unknown",
13004
- sourceId: binding?.sourceId ?? "unknown",
13005
- expectedType: error.expectedType ?? field?.type ?? "unknown",
13006
- actualType: error.actualType ?? "unknown",
13007
- retryable: false
13008
- });
13009
- }
12864
+ diagnostics.error("failed", error);
13010
12865
  throw error;
13011
12866
  }
13012
- return createPresentationResult(resource, config, viewModel);
13013
12867
  }
13014
- function createPresentationResult(resource, config, viewModel) {
13015
- const protocol = injectResolvedViewModel(JSON.parse(config.a2uiTemplate.content), viewModel);
13016
- const cardInstanceId = `card-instance-${randomUUID()}`;
13017
- const receipt = {
13018
- version: 1,
13019
- cardRef: resource.resourceId,
13020
- cardRevision: config.revision,
13021
- cardInstanceId,
13022
- status: "emitted",
13023
- ...createA2UICardPresentationReceiptContent(config.fields, viewModel),
13024
- responsePolicy: { verbatimEcho: "forbidden", hint: "acknowledge" }
13025
- };
13026
- receipt.semanticSnapshot = createCardSemanticSnapshot(receipt, config.fields);
13027
- return {
13028
- type: "linkque.presentation-tool-result",
13029
- modelText: formatPresentationReceiptForModel(receipt),
13030
- receipt,
13031
- card: {
13032
- type: "a2ui_card",
13033
- itemId: cardInstanceId,
13034
- payload: { protocol },
13035
- metadata: {
13036
- cardRef: resource.resourceId,
13037
- cardRevision: config.revision,
13038
- cardInstanceId
12868
+ async function executeCardActionInternal(input, diagnostics) {
12869
+ let request;
12870
+ try {
12871
+ request = parseA2UIActionExecuteRequest(input.request);
12872
+ } catch (error) {
12873
+ return failure2("INVALID_INPUT", errorMessage(error, "\u652F\u4ED8\u52A8\u4F5C\u8BF7\u6C42\u65E0\u6548"), false);
12874
+ }
12875
+ Object.assign(diagnostics.context, {
12876
+ invocationId: request.invocationId,
12877
+ cardRef: request.source.cardRef,
12878
+ cardRevision: request.source.cardRevision
12879
+ });
12880
+ if (request.agentId !== input.protocol.agentId)
12881
+ return failure2("AGENT_MISMATCH", "\u652F\u4ED8\u52A8\u4F5C\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
12882
+ if (request.threadId !== input.runtimeContext.threadId)
12883
+ return failure2("INVALID_INPUT", "\u652F\u4ED8\u52A8\u4F5C\u4E0E\u5F53\u524D\u4F1A\u8BDD\u4E0D\u5339\u914D", false);
12884
+ if (!input.runtimeContext.userId.trim())
12885
+ return failure2("AUTH_REQUIRED", "\u652F\u4ED8\u52A8\u4F5C\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
12886
+ diagnostics.write("validated", { output: request });
12887
+ diagnostics.stage = "binding";
12888
+ diagnostics.write("binding_started", { input: { source: request.source } });
12889
+ const resolved = resolvePaymentAction(input.protocol, request.source);
12890
+ if (!resolved.ok) {
12891
+ diagnostics.write("binding_failed", { output: resolved.response });
12892
+ return resolved.response;
12893
+ }
12894
+ const args = materializePaymentInput(resolved.payment.createTrade.input, request.input);
12895
+ if (!args)
12896
+ return failure2("INVALID_INPUT", "\u65E0\u6CD5\u751F\u6210\u521B\u5EFA\u4EA4\u6613 MCP \u5165\u53C2", false);
12897
+ const createTrade = resolved.payment.createTrade;
12898
+ Object.assign(diagnostics.context, {
12899
+ mcpResourceId: createTrade.mcpResourceId,
12900
+ toolName: createTrade.toolName
12901
+ });
12902
+ diagnostics.write("binding_resolved", { output: createTrade });
12903
+ diagnostics.stage = "tool_resolve";
12904
+ const registry = createRegistry(input.protocol, input.mcpServerProvider, diagnostics.debugLog);
12905
+ try {
12906
+ diagnostics.write("tool_resolve_started", { input: createTrade });
12907
+ const tool = await registry.resolve(createTrade.mcpResourceId, createTrade.toolName, input.signal);
12908
+ diagnostics.write("tool_resolved", {
12909
+ output: {
12910
+ found: Boolean(tool),
12911
+ inputSchema: tool?.inputSchema,
12912
+ outputSchema: tool?.outputSchema
13039
12913
  }
12914
+ });
12915
+ if (!tool)
12916
+ return failure2("TOOL_NOT_ALLOWED", "\u521B\u5EFA\u4EA4\u6613 MCP Tool \u4E0D\u5B58\u5728\u6216\u672A\u6388\u6743", false);
12917
+ diagnostics.stage = "tool_input";
12918
+ const inputSchema = cloneJsonObject(tool.inputSchema);
12919
+ if (inputSchema && validateJsonSchemaValue(inputSchema, args).length > 0) {
12920
+ return failure2("INVALID_INPUT", "\u521B\u5EFA\u4EA4\u6613 MCP \u5165\u53C2\u4E0D\u7B26\u5408 Tool Schema", false);
13040
12921
  }
13041
- };
13042
- }
13043
- function formatPresentationReceiptForModel(receipt) {
13044
- return [
13045
- "<a2ui-presentation-receipt>",
13046
- JSON.stringify(projectPresentationReceiptForModel(receipt)),
13047
- "</a2ui-presentation-receipt>",
13048
- "\u5361\u7247\u5DF2\u53D1\u51FA\uFF08\u4E0D\u4EE3\u8868\u5BA2\u6237\u7AEF\u5DF2\u6E32\u67D3\uFF09\u3002\u8BED\u4E49\u5FEB\u7167\u6765\u81EA\u6388\u6743\u7684\u6700\u7EC8\u5361\u7247\u6570\u636E\uFF1Bcolumns \u4E0E rows \u6309\u4F4D\u7F6E\u5BF9\u5E94\uFF0Cnull \u8868\u793A\u7F3A\u5931\u6216\u7A7A\u503C\uFF0Ccomplete=false \u65F6\u4E0D\u5F97\u628A\u91C7\u6837\u5F53\u4F5C\u5168\u96C6\u3002\u4E0D\u8981\u7528 Markdown \u91CD\u590D\u5217\u51FA\u6216\u6539\u5199\u5361\u7247\u4E2D\u7684\u6761\u76EE\uFF1B\u53EA\u8865\u5145\u7528\u6237\u5C1A\u672A\u5F97\u5230\u7684\u6BD4\u8F83\u3001\u89E3\u91CA\u6216\u5FC5\u8981\u8FFD\u95EE\uFF0C\u7528\u6237\u660E\u786E\u8981\u6C42\u6587\u5B57\u8868\u683C\u65F6\u53EF\u4EE5\u63D0\u4F9B\u3002\u5FEB\u7167\u672A\u5305\u542B\u7684\u4FE1\u606F\u4FDD\u6301\u672A\u77E5\uFF0C\u6E90\u5DE5\u5177\u7684\u989D\u5916\u4FE1\u606F\u4E0D\u80FD\u79F0\u4E3A\u5361\u7247\u5DF2\u5C55\u793A\u5185\u5BB9\u3002"
13049
- ].join("\n");
13050
- }
13051
- function projectPresentationReceiptForModel(receipt) {
13052
- if (!receipt.semanticSnapshot)
13053
- return receipt;
13054
- return {
13055
- version: receipt.version,
13056
- cardRef: receipt.cardRef,
13057
- cardRevision: receipt.cardRevision,
13058
- cardInstanceId: receipt.cardInstanceId,
13059
- status: receipt.status,
13060
- semanticSnapshot: receipt.semanticSnapshot
13061
- };
13062
- }
13063
- function parseCardConfig(resource) {
13064
- const parsed = parseA2UICardResourceConfig(resource.config);
13065
- if (!parsed.success) {
13066
- throw new Error(`Invalid CARD ${resource.resourceId}: ${parsed.issues.map((entry) => `${entry.path}: ${entry.message}`).join("; ")}`);
12922
+ diagnostics.write("tool_input_completed", { output: { args } });
12923
+ let result;
12924
+ diagnostics.stage = "tool_execute";
12925
+ diagnostics.write("tool_started", { input: args });
12926
+ try {
12927
+ result = await tool.execute(args, input.signal);
12928
+ diagnostics.protect(() => readJsonPointer(readStructuredContent3(result), createTrade.tradeNoPath));
12929
+ diagnostics.write("tool_completed", { output: result });
12930
+ } catch (error) {
12931
+ diagnostics.error("tool_failed", error);
12932
+ return failure2("EXECUTION_FAILED", "\u521B\u5EFA\u4EA4\u6613\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5", true);
12933
+ }
12934
+ diagnostics.stage = "tool_output";
12935
+ const structured = readStructuredContent3(result);
12936
+ const tradeNO = readJsonPointer(structured, createTrade.tradeNoPath);
12937
+ diagnostics.write("tool_output_completed", {
12938
+ output: {
12939
+ structured,
12940
+ tradeNO,
12941
+ valid: typeof tradeNO === "string" && Boolean(tradeNO.trim()) && tradeNO.length <= 64
12942
+ }
12943
+ });
12944
+ if (typeof tradeNO !== "string" || !tradeNO.trim() || tradeNO.length > 64)
12945
+ return failure2("INVALID_OUTPUT", "\u521B\u5EFA\u4EA4\u6613 MCP \u672A\u8FD4\u56DE\u6709\u6548 tradeNO", false);
12946
+ return {
12947
+ ok: true,
12948
+ invocationId: request.invocationId,
12949
+ result: { kind: "payment", tradeNO }
12950
+ };
12951
+ } finally {
12952
+ const stage = diagnostics.stage;
12953
+ diagnostics.stage = "cleanup";
12954
+ diagnostics.write("cleanup_started", {
12955
+ input: { mcpResourceId: diagnostics.context.mcpResourceId }
12956
+ });
12957
+ await registry.closeAll();
12958
+ diagnostics.write("cleanup_completed", {
12959
+ output: { closeAttempted: true }
12960
+ });
12961
+ diagnostics.stage = stage;
13067
12962
  }
13068
- return parsed.data;
13069
- }
13070
- function isAgentPresentationToolResult(value) {
13071
- if (!isJsonObject(value))
13072
- return false;
13073
- return value.type === "linkque.presentation-tool-result" && typeof value.modelText === "string" && isJsonObject(value.card) && value.card.type === "a2ui_card";
13074
12963
  }
13075
- function injectResolvedViewModel(protocol, viewModel) {
13076
- const analysis = analyzeA2UIBindings(protocol);
13077
- const declaredSurfaceIds = analysis.surfaceIds;
13078
- const surfaceIds = Array.isArray(declaredSurfaceIds) && declaredSurfaceIds.every((surfaceId) => typeof surfaceId === "string") ? declaredSurfaceIds : collectA2UISurfaceIdsForLegacyContract(protocol);
13079
- if (analysis.issues.length || surfaceIds.length === 0) {
13080
- throw new Error("CARD template does not contain a valid A2UI surface");
12964
+ function resolvePaymentAction(protocol, source) {
12965
+ const card = protocol.agent.resources.find((resource) => resource.resourceType === EResourceType.CARD && resource.resourceId === source.cardRef);
12966
+ if (!card)
12967
+ return {
12968
+ ok: false,
12969
+ response: failure2("CARD_NOT_FOUND", "\u652F\u4ED8\u5361\u7247\u4E0D\u5B58\u5728", false)
12970
+ };
12971
+ if (card.config.revision !== source.cardRevision) {
12972
+ return {
12973
+ ok: false,
12974
+ response: failure2("CARD_REVISION_MISMATCH", "\u652F\u4ED8\u5361\u7247\u7248\u672C\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5", false)
12975
+ };
13081
12976
  }
13082
- return [
13083
- ...protocol,
13084
- {
13085
- version: "0.9",
13086
- datas: surfaceIds.map((surfaceId) => ({
13087
- updateDataModel: { surfaceId, path: "/", value: viewModel }
13088
- }))
13089
- }
13090
- ];
12977
+ if (card.config.schemaVersion !== "4")
12978
+ return {
12979
+ ok: false,
12980
+ response: failure2("ACTION_NOT_FOUND", "\u652F\u4ED8\u52A8\u4F5C\u4E0D\u5B58\u5728", false)
12981
+ };
12982
+ const component = findSavedComponent(card.config.a2uiTemplate.content, source.surfaceId, source.componentId);
12983
+ if (!component)
12984
+ return {
12985
+ ok: false,
12986
+ response: failure2("ACTION_NOT_FOUND", "\u652F\u4ED8\u52A8\u4F5C\u4E0D\u5B58\u5728", false)
12987
+ };
12988
+ const payments = collectPaymentActions(component.action);
12989
+ if (payments.length !== 1)
12990
+ return {
12991
+ ok: false,
12992
+ response: failure2("ACTION_KIND_MISMATCH", "\u7EC4\u4EF6\u5FC5\u987B\u5305\u542B\u552F\u4E00\u652F\u4ED8\u52A8\u4F5C", false)
12993
+ };
12994
+ return { ok: true, payment: payments[0] };
13091
12995
  }
13092
- function collectA2UISurfaceIdsForLegacyContract(protocol) {
13093
- const surfaceIds = /* @__PURE__ */ new Set();
13094
- for (const message of protocol) {
13095
- if (!isJsonObject(message) || !Array.isArray(message.datas))
13096
- continue;
13097
- for (const instruction of message.datas) {
13098
- if (!isJsonObject(instruction))
13099
- continue;
13100
- const operations = [
13101
- "createSurface" in instruction ? instruction.createSurface : void 0,
13102
- "updateComponents" in instruction ? instruction.updateComponents : void 0
13103
- ];
13104
- for (const operation of operations) {
13105
- if (isJsonObject(operation) && typeof operation.surfaceId === "string") {
13106
- surfaceIds.add(operation.surfaceId);
13107
- }
13108
- }
13109
- }
12996
+ function findSavedComponent(content, surfaceId, componentId) {
12997
+ let parsed;
12998
+ try {
12999
+ parsed = JSON.parse(content);
13000
+ } catch {
13001
+ return void 0;
13110
13002
  }
13111
- return [...surfaceIds];
13003
+ if (!Array.isArray(parsed))
13004
+ return void 0;
13005
+ const instructions = parsed.flatMap((entry) => {
13006
+ const record2 = cloneJsonObject(entry);
13007
+ return record2 && Array.isArray(record2.datas) ? record2.datas : [entry];
13008
+ });
13009
+ for (const instruction of instructions) {
13010
+ const record2 = cloneJsonObject(instruction);
13011
+ const update = record2 && cloneJsonObject(record2.updateComponents);
13012
+ if (!update || update.surfaceId !== surfaceId || !Array.isArray(update.components))
13013
+ continue;
13014
+ const component = update.components.find((candidate) => {
13015
+ const item = cloneJsonObject(candidate);
13016
+ return item?.id === componentId;
13017
+ });
13018
+ const result = cloneJsonObject(component);
13019
+ if (result)
13020
+ return result;
13021
+ }
13022
+ return void 0;
13112
13023
  }
13113
- function createPresentationDescription(config) {
13024
+ function collectPaymentActions(value) {
13025
+ const action = cloneJsonObject(value);
13026
+ if (!action)
13027
+ return [];
13028
+ const client = cloneJsonObject(action.client);
13029
+ if (client?.name === "payment.trade-pay") {
13030
+ const context = cloneJsonObject(client.context);
13031
+ return context ? [context] : [];
13032
+ }
13033
+ const select = cloneJsonObject(action.select);
13034
+ if (!select)
13035
+ return [];
13036
+ const cases = Array.isArray(select.cases) ? select.cases : [];
13114
13037
  return [
13115
- config.description,
13116
- `\u9002\u7528\u573A\u666F\uFF1A${config.whenToUse}`,
13117
- ...config.whenNotToUse ? [`\u4E0D\u9002\u7528\u573A\u666F\uFF1A${config.whenNotToUse}`] : [],
13118
- "\u53EA\u63D0\u4F9B\u5DF2\u58F0\u660E\u7684\u6807\u8BC6\u6216\u7B5B\u9009\u53C2\u6570\u3002\u6743\u5A01\u4E1A\u52A1\u6570\u636E\u7531\u5E73\u53F0\u89E3\u6790\u83B7\u53D6\u3002"
13119
- ].join("\n");
13038
+ ...cases.flatMap((entry) => collectPaymentActions(cloneJsonObject(entry)?.action)),
13039
+ ...collectPaymentActions(select.default)
13040
+ ];
13120
13041
  }
13121
- function cloneJsonObject2(value, label) {
13122
- if (!isJsonObject(value))
13123
- throw new Error(`${label} must be a JSON object`);
13124
- return JSON.parse(JSON.stringify(value));
13042
+ function materializePaymentInput(definition, supplied) {
13043
+ const materialized = materializeValue(definition, supplied);
13044
+ return cloneJsonObject(materialized);
13125
13045
  }
13126
- function supplementMcpInput(input, invocation, presentationSchema, mcpInputSchema) {
13127
- const result = cloneJsonObject2(input, "MCP Tool arguments");
13128
- const presentationProperties = schemaProperties(presentationSchema);
13129
- const mcpProperties = schemaProperties(mcpInputSchema);
13130
- if (!presentationProperties || !mcpProperties)
13131
- return result;
13132
- for (const [name, mcpProperty] of Object.entries(mcpProperties)) {
13133
- if (result[name] !== void 0 || invocation[name] === void 0)
13134
- continue;
13135
- const presentationProperty = presentationProperties[name];
13136
- if (isJsonObject(presentationProperty) && isJsonObject(mcpProperty) && compatibleSchemaTypes(presentationProperty.type, mcpProperty.type)) {
13137
- result[name] = JSON.parse(JSON.stringify(invocation[name]));
13046
+ function materializeValue(definition, supplied) {
13047
+ if (Array.isArray(definition)) {
13048
+ if (!Array.isArray(supplied) || supplied.length !== definition.length)
13049
+ return void 0;
13050
+ const result = definition.map((entry, index) => materializeValue(entry, supplied[index]));
13051
+ return result.some((entry) => entry === void 0) ? void 0 : result;
13052
+ }
13053
+ if (definition && typeof definition === "object") {
13054
+ const keys = Object.keys(definition);
13055
+ if (keys.length === 1 && keys[0] === "path" && typeof definition.path === "string")
13056
+ return supplied;
13057
+ const suppliedObject = cloneJsonObject(supplied);
13058
+ if (!suppliedObject)
13059
+ return void 0;
13060
+ const result = {};
13061
+ for (const [key, entry] of Object.entries(definition)) {
13062
+ const value = materializeValue(entry, suppliedObject[key]);
13063
+ if (value === void 0)
13064
+ return void 0;
13065
+ result[key] = value;
13138
13066
  }
13067
+ return result;
13139
13068
  }
13140
- return result;
13069
+ return definition;
13141
13070
  }
13142
- function schemaProperties(schema) {
13143
- return schema.type === "object" && isJsonObject(schema.properties) ? schema.properties : void 0;
13144
- }
13145
- function compatibleSchemaTypes(source, target) {
13146
- if (typeof source !== "string" || typeof target !== "string")
13147
- return false;
13148
- return source === target || source === "integer" && target === "number";
13071
+ function createRegistry(protocol, provider, debugLog) {
13072
+ const resources = protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL);
13073
+ return new McpProxyTool(provider, aggregateMcpServers(resources, protocol.agentId), { debugLog });
13149
13074
  }
13150
- function readStructuredContent2(result) {
13151
- if (!isJsonObject(result))
13075
+ function readStructuredContent3(result) {
13076
+ const object3 = cloneJsonObject(result);
13077
+ if (!object3)
13152
13078
  return void 0;
13153
- if (Object.hasOwn(result, "structuredContent") && isJsonValue(result.structuredContent)) {
13154
- return cloneJsonValue(result.structuredContent);
13155
- }
13156
- if (!Array.isArray(result.content) || result.content.length === 0) {
13079
+ if (cloneJsonObject(object3.structuredContent))
13080
+ return object3.structuredContent;
13081
+ if (!Array.isArray(object3.content) || object3.content.length !== 1)
13082
+ return void 0;
13083
+ const content = cloneJsonObject(object3.content[0]);
13084
+ if (!content || content.type !== "text" || typeof content.text !== "string")
13157
13085
  return void 0;
13158
- }
13159
- const texts = [];
13160
- for (const content of result.content) {
13161
- if (!isJsonObject(content) || content.type !== "text" || typeof content.text !== "string")
13162
- return void 0;
13163
- texts.push(content.text);
13164
- }
13165
- if (texts.length > 1)
13166
- return texts.join("\n");
13167
13086
  try {
13168
- const parsed = JSON.parse(texts[0]);
13169
- return isJsonValue(parsed) ? cloneJsonValue(parsed) : texts[0];
13087
+ return JSON.parse(content.text);
13170
13088
  } catch {
13171
- return texts[0];
13089
+ return void 0;
13172
13090
  }
13173
13091
  }
13174
- function normalizeMcpInputSchema(value) {
13175
- if (!isJsonObject(value) || getJsonSchemaIssues2(value).length > 0) {
13176
- return { ...FALLBACK_OBJECT_SCHEMA };
13177
- }
13178
- if (value.type === "object" && (!isJsonObject(value.properties) || Object.keys(value.properties).length === 0))
13179
- return { ...FALLBACK_OBJECT_SCHEMA };
13180
- return JSON.parse(JSON.stringify(value));
13092
+ function failure2(code, message, retryable) {
13093
+ return { ok: false, error: { code, message, retryable } };
13181
13094
  }
13182
- var CardMappingError = class extends Error {
13183
- details;
13184
- retryable = false;
13185
- constructor(details) {
13186
- super(JSON.stringify(details));
13187
- this.name = "CardMappingError";
13188
- this.details = details;
13189
- }
13190
- };
13191
- function isJsonObject(value) {
13192
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13095
+ function errorMessage(error, fallback) {
13096
+ return error instanceof Error && error.message.trim() ? error.message : fallback;
13193
13097
  }
13194
13098
 
13195
- // ../linkque-agent-runtime/dist/esm/core/homeData.js
13196
- async function executeHomeData(input) {
13197
- let request;
13198
- try {
13199
- request = parseHomeDataRequest(input.request);
13200
- } catch (error) {
13201
- return failure2("INVALID_INPUT", error instanceof Error ? error.message : "\u9996\u9875\u5361\u7247\u8BF7\u6C42\u65E0\u6548", false);
13202
- }
13203
- if (request.agentId !== input.protocol.agentId) {
13204
- return failure2("AGENT_MISMATCH", "\u9996\u9875\u6570\u636E\u8BF7\u6C42\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
13205
- }
13206
- if (!input.userId.trim()) {
13207
- return failure2("AUTH_REQUIRED", "\u9996\u9875\u6570\u636E\u8BF7\u6C42\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
13208
- }
13099
+ // ../linkque-agent-runtime/dist/esm/core/mcpExecution.js
13100
+ async function executeAuthorizedMcp(input) {
13101
+ if (input.agentId !== input.protocol.agentId)
13102
+ return failure3("AGENT_MISMATCH", "\u8BF7\u6C42\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
13103
+ if (!input.userId.trim())
13104
+ return failure3("AUTH_REQUIRED", "\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
13209
13105
  const resources = input.protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL);
13210
- const specs = aggregateMcpServers(resources, input.protocol.agentId);
13211
- const spec = specs.find((candidate) => candidate.serverName === request.binding.mcpName);
13212
- if (!spec) {
13213
- return failure2("MCP_NOT_BOUND", "\u5F53\u524D Agent \u672A\u7ED1\u5B9A\u8BE5 MCP", false);
13214
- }
13215
- if (spec.allowedTools && !spec.allowedTools.has(request.binding.toolName)) {
13216
- return failure2("TOOL_NOT_ALLOWED", "\u5F53\u524D Agent \u672A\u5141\u8BB8\u8C03\u7528\u8BE5 MCP \u5DE5\u5177", false);
13217
- }
13218
- const registry = new McpProxyTool(input.mcpServerProvider, specs);
13106
+ const registry = new McpProxyTool(input.mcpServerProvider, aggregateMcpServers(resources, input.protocol.agentId));
13219
13107
  try {
13220
- const handle = await registry.resolve(spec.resourceIds[0], request.binding.toolName, input.signal);
13221
- if (!handle) {
13222
- return failure2("TOOL_NOT_ALLOWED", "MCP \u5DE5\u5177\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528", false);
13223
- }
13224
- const toolInput = {};
13225
- for (const mapping of request.binding.input) {
13226
- let value;
13227
- switch (mapping.source.kind) {
13228
- case "parameter":
13229
- value = readJsonPointer(request.parameters, mapping.source.pointer);
13230
- break;
13231
- case "runtime-context":
13232
- value = mapping.source.key === "agentId" ? input.protocol.agentId : input.userId;
13233
- break;
13234
- case "literal":
13235
- value = mapping.source.value;
13236
- break;
13237
- }
13238
- if (value === void 0 || !writeJsonPointer(toolInput, mapping.target, value)) {
13239
- return failure2("INVALID_INPUT", `\u65E0\u6CD5\u751F\u6210 MCP \u5165\u53C2 ${mapping.target}`, false);
13240
- }
13108
+ const tool = await registry.resolve(input.tool.mcpResourceId, input.tool.toolName, input.signal);
13109
+ if (!tool)
13110
+ return failure3("TOOL_NOT_ALLOWED", "MCP Tool \u4E0D\u5B58\u5728\u6216\u672A\u6388\u6743", false);
13111
+ const schema = cloneJsonObject(tool.inputSchema);
13112
+ if (schema && validateJsonSchemaValue(schema, input.tool.input).length > 0) {
13113
+ return failure3("INVALID_INPUT", "MCP \u5165\u53C2\u4E0D\u7B26\u5408 Tool Schema", false);
13241
13114
  }
13242
13115
  let result;
13243
13116
  try {
13244
- result = await handle.execute(toolInput, input.signal);
13245
- } catch (error) {
13246
- return failure2("EXECUTION_FAILED", error instanceof Error ? error.message : "MCP \u5DE5\u5177\u8C03\u7528\u5931\u8D25", true);
13247
- }
13248
- const structured = readStructuredContent3(result);
13249
- let cardData = structured;
13250
- if (request.binding.transform) {
13251
- try {
13252
- cardData = executeStructuralTransform(request.binding.transform, structured);
13253
- } catch (error) {
13254
- return failure2("TRANSFORM_FAILED", error instanceof Error ? error.message : "\u9996\u9875\u5361\u7247\u6570\u636E\u8F6C\u6362\u5931\u8D25", false);
13255
- }
13117
+ result = await tool.execute(input.tool.input, input.signal);
13118
+ } catch {
13119
+ return failure3("EXECUTION_UNCERTAIN", "MCP \u6267\u884C\u7ED3\u679C\u4E0D\u786E\u5B9A\uFF0C\u8BF7\u52FF\u81EA\u52A8\u91CD\u8BD5", false);
13256
13120
  }
13257
- const cardDataObject = cloneJsonObject(cardData);
13258
- if (!cardDataObject) {
13259
- return failure2("INVALID_CARD_DATA", "\u9996\u9875\u5361\u7247\u6570\u636E\u5FC5\u987B\u662F JSON object", false);
13121
+ const structured = readStructuredContent4(result);
13122
+ if (!isJsonValue2(structured)) {
13123
+ return failure3("INVALID_OUTPUT", "MCP \u672A\u8FD4\u56DE\u6709\u6548 JSON \u7ED3\u679C", false);
13260
13124
  }
13261
- return { ok: true, data: cardDataObject };
13125
+ return { ok: true, callId: input.callId, result: structured };
13262
13126
  } finally {
13263
13127
  await registry.closeAll();
13264
13128
  }
13265
13129
  }
13266
- function readStructuredContent3(result) {
13130
+ function readStructuredContent4(result) {
13267
13131
  const object3 = cloneJsonObject(result);
13268
13132
  if (!object3)
13269
13133
  return void 0;
13270
- if (cloneJsonObject(object3.structuredContent)) {
13134
+ if (object3.structuredContent !== void 0)
13271
13135
  return object3.structuredContent;
13272
- }
13273
- if (!Array.isArray(object3.content) || object3.content.length !== 1) {
13136
+ if (!Array.isArray(object3.content) || object3.content.length !== 1)
13274
13137
  return void 0;
13275
- }
13276
- const content = cloneJsonObject(object3.content[0]);
13277
- if (!content || content.type !== "text" || typeof content.text !== "string") {
13138
+ const text = cloneJsonObject(object3.content[0]);
13139
+ if (text?.type !== "text" || typeof text.text !== "string")
13278
13140
  return void 0;
13279
- }
13280
13141
  try {
13281
- return JSON.parse(content.text);
13142
+ return JSON.parse(text.text);
13282
13143
  } catch {
13283
13144
  return void 0;
13284
13145
  }
13285
13146
  }
13286
- function failure2(code, message, retryable) {
13147
+ function isJsonValue2(value) {
13148
+ if (value === null || ["string", "boolean"].includes(typeof value))
13149
+ return true;
13150
+ if (typeof value === "number")
13151
+ return Number.isFinite(value);
13152
+ if (Array.isArray(value))
13153
+ return value.every(isJsonValue2);
13154
+ const object3 = cloneJsonObject(value);
13155
+ return Boolean(object3) && Object.values(object3 ?? {}).every(isJsonValue2);
13156
+ }
13157
+ function failure3(code, message, retryable) {
13158
+ return { ok: false, error: { code, message, retryable } };
13159
+ }
13160
+
13161
+ // ../linkque-agent-runtime/dist/esm/core/functionActionExecutor.js
13162
+ async function executeFunctionActionMcp(input) {
13163
+ let request;
13164
+ try {
13165
+ request = parseA2UIFunctionMcpExecuteRequest(input.request);
13166
+ } catch (error) {
13167
+ return failure4("INVALID_INPUT", errorMessage2(error, "\u51FD\u6570 MCP \u8BF7\u6C42\u65E0\u6548"), false);
13168
+ }
13169
+ if (request.agentId !== input.protocol.agentId) {
13170
+ return failure4("AGENT_MISMATCH", "\u51FD\u6570\u52A8\u4F5C\u4E0E\u5F53\u524D Agent \u4E0D\u5339\u914D", false);
13171
+ }
13172
+ if (request.threadId !== input.runtimeContext.threadId || !input.runtimeContext.userId.trim()) {
13173
+ return failure4("AUTH_REQUIRED", "\u51FD\u6570\u52A8\u4F5C\u7F3A\u5C11\u53EF\u4FE1\u4F1A\u8BDD\u8EAB\u4EFD", false);
13174
+ }
13175
+ return executeAuthorizedMcp({
13176
+ protocol: input.protocol,
13177
+ agentId: request.agentId,
13178
+ userId: input.runtimeContext.userId,
13179
+ callId: request.callId,
13180
+ tool: request.tool,
13181
+ mcpServerProvider: input.mcpServerProvider,
13182
+ signal: input.signal
13183
+ });
13184
+ }
13185
+ function failure4(code, message, retryable) {
13287
13186
  return { ok: false, error: { code, message, retryable } };
13288
13187
  }
13188
+ function errorMessage2(error, fallback) {
13189
+ return error instanceof Error && error.message.trim() ? error.message : fallback;
13190
+ }
13289
13191
 
13290
13192
  // ../linkque-agent-runtime/dist/esm/core/inMemorySessionManager.js
13291
13193
  var InMemorySessionManager = class {
@@ -13379,7 +13281,7 @@ function normalizeHookResources(resources) {
13379
13281
  }).sort((a, b) => (a.config.order ?? 0) - (b.config.order ?? 0));
13380
13282
  }
13381
13283
 
13382
- // ../linkque-agent-runtime/dist/esm/core/telemetry/telemetryEnums.js
13284
+ // ../linkque-agent-protocol/dist/esm/telemetry/telemetryEnums.js
13383
13285
  var ETelemetryAttribute;
13384
13286
  (function(ETelemetryAttribute2) {
13385
13287
  ETelemetryAttribute2["HARNESS_TELEMETRY_SCHEMA_VERSION"] = "harness.telemetry.schema.version";
@@ -13571,24 +13473,6 @@ var ETelemetrySignal;
13571
13473
  ETelemetrySignal2["LOGS"] = "logs";
13572
13474
  ETelemetrySignal2["TRACES"] = "traces";
13573
13475
  })(ETelemetrySignal || (ETelemetrySignal = {}));
13574
- var ETelemetryDiagnosticCode;
13575
- (function(ETelemetryDiagnosticCode2) {
13576
- ETelemetryDiagnosticCode2["INVALID_AUTHORIZATION"] = "invalid_authorization";
13577
- ETelemetryDiagnosticCode2["PARTITION_LIMIT"] = "partition_limit";
13578
- ETelemetryDiagnosticCode2["UNAVAILABLE_PARTITION"] = "unavailable_partition";
13579
- ETelemetryDiagnosticCode2["QUEUE_LIMIT"] = "queue_limit";
13580
- ETelemetryDiagnosticCode2["QUEUE_EXPIRED"] = "queue_expired";
13581
- ETelemetryDiagnosticCode2["SENDER_FAILED"] = "sender_failed";
13582
- ETelemetryDiagnosticCode2["PARTIAL_SUCCESS"] = "partial_success";
13583
- ETelemetryDiagnosticCode2["AUTHORIZATION_REJECTED"] = "authorization_rejected";
13584
- ETelemetryDiagnosticCode2["PERMANENT_REJECTION"] = "permanent_rejection";
13585
- ETelemetryDiagnosticCode2["SEND_RETRY"] = "send_retry";
13586
- ETelemetryDiagnosticCode2["SHUTDOWN_DROP"] = "shutdown_drop";
13587
- ETelemetryDiagnosticCode2["LOCAL_SINK_FAILED"] = "local_sink_failed";
13588
- ETelemetryDiagnosticCode2["CAPTURE_FAILED"] = "capture_failed";
13589
- ETelemetryDiagnosticCode2["IDENTITY_MISMATCH"] = "identity_mismatch";
13590
- ETelemetryDiagnosticCode2["ACTIVE_LIMIT"] = "active_limit";
13591
- })(ETelemetryDiagnosticCode || (ETelemetryDiagnosticCode = {}));
13592
13476
  var ETelemetryLossReason;
13593
13477
  (function(ETelemetryLossReason2) {
13594
13478
  ETelemetryLossReason2["UNCAUGHT_ERROR"] = "uncaught_error";
@@ -13719,21 +13603,6 @@ var ETelemetryGenAiOperation;
13719
13603
  ETelemetryGenAiOperation2["EXECUTE_TOOL"] = "execute_tool";
13720
13604
  ETelemetryGenAiOperation2["INVOKE_AGENT"] = "invoke_agent";
13721
13605
  })(ETelemetryGenAiOperation || (ETelemetryGenAiOperation = {}));
13722
- var ETelemetryAssociation;
13723
- (function(ETelemetryAssociation2) {
13724
- ETelemetryAssociation2["LOOP"] = "loop";
13725
- ETelemetryAssociation2["ITERATION"] = "iteration";
13726
- ETelemetryAssociation2["MODEL"] = "model";
13727
- ETelemetryAssociation2["TOOL"] = "tool";
13728
- ETelemetryAssociation2["PROVIDER"] = "provider";
13729
- })(ETelemetryAssociation || (ETelemetryAssociation = {}));
13730
- var ETelemetryMetadata;
13731
- (function(ETelemetryMetadata2) {
13732
- ETelemetryMetadata2["SCOPE_NAME"] = "com.alipay.linkque.runtime.telemetry";
13733
- ETelemetryMetadata2["RUNTIME_KIND"] = "node_toolkit";
13734
- ETelemetryMetadata2["SERVICE_NAMESPACE"] = "linkque";
13735
- ETelemetryMetadata2["ROUTE_CONTEXT_KEY"] = "linkque.telemetry.route";
13736
- })(ETelemetryMetadata || (ETelemetryMetadata = {}));
13737
13606
  var ETelemetryVersion;
13738
13607
  (function(ETelemetryVersion2) {
13739
13608
  ETelemetryVersion2["V0_2"] = "0.2";
@@ -14514,6 +14383,41 @@ var SideEffectRunner = class {
14514
14383
  }
14515
14384
  };
14516
14385
 
14386
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/telemetryEnums.js
14387
+ var ETelemetryDiagnosticCode;
14388
+ (function(ETelemetryDiagnosticCode2) {
14389
+ ETelemetryDiagnosticCode2["INVALID_AUTHORIZATION"] = "invalid_authorization";
14390
+ ETelemetryDiagnosticCode2["PARTITION_LIMIT"] = "partition_limit";
14391
+ ETelemetryDiagnosticCode2["UNAVAILABLE_PARTITION"] = "unavailable_partition";
14392
+ ETelemetryDiagnosticCode2["QUEUE_LIMIT"] = "queue_limit";
14393
+ ETelemetryDiagnosticCode2["QUEUE_EXPIRED"] = "queue_expired";
14394
+ ETelemetryDiagnosticCode2["SENDER_FAILED"] = "sender_failed";
14395
+ ETelemetryDiagnosticCode2["PARTIAL_SUCCESS"] = "partial_success";
14396
+ ETelemetryDiagnosticCode2["AUTHORIZATION_REJECTED"] = "authorization_rejected";
14397
+ ETelemetryDiagnosticCode2["PERMANENT_REJECTION"] = "permanent_rejection";
14398
+ ETelemetryDiagnosticCode2["SEND_RETRY"] = "send_retry";
14399
+ ETelemetryDiagnosticCode2["SHUTDOWN_DROP"] = "shutdown_drop";
14400
+ ETelemetryDiagnosticCode2["LOCAL_SINK_FAILED"] = "local_sink_failed";
14401
+ ETelemetryDiagnosticCode2["CAPTURE_FAILED"] = "capture_failed";
14402
+ ETelemetryDiagnosticCode2["IDENTITY_MISMATCH"] = "identity_mismatch";
14403
+ ETelemetryDiagnosticCode2["ACTIVE_LIMIT"] = "active_limit";
14404
+ })(ETelemetryDiagnosticCode || (ETelemetryDiagnosticCode = {}));
14405
+ var ETelemetryAssociation;
14406
+ (function(ETelemetryAssociation2) {
14407
+ ETelemetryAssociation2["LOOP"] = "loop";
14408
+ ETelemetryAssociation2["ITERATION"] = "iteration";
14409
+ ETelemetryAssociation2["MODEL"] = "model";
14410
+ ETelemetryAssociation2["TOOL"] = "tool";
14411
+ ETelemetryAssociation2["PROVIDER"] = "provider";
14412
+ })(ETelemetryAssociation || (ETelemetryAssociation = {}));
14413
+ var ETelemetryMetadata;
14414
+ (function(ETelemetryMetadata2) {
14415
+ ETelemetryMetadata2["SCOPE_NAME"] = "com.alipay.linkque.runtime.telemetry";
14416
+ ETelemetryMetadata2["RUNTIME_KIND"] = "node_toolkit";
14417
+ ETelemetryMetadata2["SERVICE_NAMESPACE"] = "linkque";
14418
+ ETelemetryMetadata2["ROUTE_CONTEXT_KEY"] = "linkque.telemetry.route";
14419
+ })(ETelemetryMetadata || (ETelemetryMetadata = {}));
14420
+
14517
14421
  // ../linkque-agent-runtime/dist/esm/core/hook/hookToolWrapper.js
14518
14422
  function resolveHookToolName(tool) {
14519
14423
  return tool.modelName ?? tool.name;
@@ -15140,9 +15044,9 @@ function createWebSearchTool(resource, searchPort, agentId, debugLog) {
15140
15044
  outcome = "cancelled";
15141
15045
  throw new DOMException("\u5168\u7F51\u641C\u7D22\u5DF2\u53D6\u6D88", "AbortError");
15142
15046
  }
15143
- const failure3 = toWebSearchFailure(error);
15144
- outcome = failure3.code;
15145
- return { query, items: [], error: failure3 };
15047
+ const failure5 = toWebSearchFailure(error);
15048
+ outcome = failure5.code;
15049
+ return { query, items: [], error: failure5 };
15146
15050
  } finally {
15147
15051
  try {
15148
15052
  debugLog?.(JSON.stringify({
@@ -16178,7 +16082,10 @@ function createConversationCustomEvent(name, value, fields = {}) {
16178
16082
  }
16179
16083
 
16180
16084
  // ../agent-conversation-contract/dist/esm/run.js
16181
- var CONVERSATION_CLIENT_CAPABILITIES = ["location"];
16085
+ var CONVERSATION_CLIENT_CAPABILITIES = [
16086
+ "location",
16087
+ "userInfo"
16088
+ ];
16182
16089
  var ConversationProtocolValidationError = class extends Error {
16183
16090
  issues;
16184
16091
  code = "CONVERSATION_PROTOCOL_INVALID";
@@ -18202,8 +18109,8 @@ var Protocol = class {
18202
18109
  if (queuedMessage.type === "response") {
18203
18110
  resolver(message);
18204
18111
  } else {
18205
- const errorMessage2 = message;
18206
- const error = new McpError(errorMessage2.error.code, errorMessage2.error.message, errorMessage2.error.data);
18112
+ const errorMessage3 = message;
18113
+ const error = new McpError(errorMessage3.error.code, errorMessage3.error.message, errorMessage3.error.data);
18207
18114
  resolver(error);
18208
18115
  }
18209
18116
  } else {
@@ -19489,8 +19396,8 @@ var Client = class extends Protocol {
19489
19396
  const wrappedHandler = async (request, extra) => {
19490
19397
  const validatedRequest = safeParse2(ElicitRequestSchema, request);
19491
19398
  if (!validatedRequest.success) {
19492
- const errorMessage2 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
19493
- throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage2}`);
19399
+ const errorMessage3 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
19400
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage3}`);
19494
19401
  }
19495
19402
  const { params } = validatedRequest.data;
19496
19403
  params.mode = params.mode ?? "form";
@@ -19505,15 +19412,15 @@ var Client = class extends Protocol {
19505
19412
  if (params.task) {
19506
19413
  const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
19507
19414
  if (!taskValidationResult.success) {
19508
- const errorMessage2 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
19509
- throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage2}`);
19415
+ const errorMessage3 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
19416
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage3}`);
19510
19417
  }
19511
19418
  return taskValidationResult.data;
19512
19419
  }
19513
19420
  const validationResult = safeParse2(ElicitResultSchema, result);
19514
19421
  if (!validationResult.success) {
19515
- const errorMessage2 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
19516
- throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage2}`);
19422
+ const errorMessage3 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
19423
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage3}`);
19517
19424
  }
19518
19425
  const validatedResult = validationResult.data;
19519
19426
  const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
@@ -19533,16 +19440,16 @@ var Client = class extends Protocol {
19533
19440
  const wrappedHandler = async (request, extra) => {
19534
19441
  const validatedRequest = safeParse2(CreateMessageRequestSchema, request);
19535
19442
  if (!validatedRequest.success) {
19536
- const errorMessage2 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
19537
- throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage2}`);
19443
+ const errorMessage3 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
19444
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage3}`);
19538
19445
  }
19539
19446
  const { params } = validatedRequest.data;
19540
19447
  const result = await Promise.resolve(handler(request, extra));
19541
19448
  if (params.task) {
19542
19449
  const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
19543
19450
  if (!taskValidationResult.success) {
19544
- const errorMessage2 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
19545
- throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage2}`);
19451
+ const errorMessage3 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
19452
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage3}`);
19546
19453
  }
19547
19454
  return taskValidationResult.data;
19548
19455
  }
@@ -19550,8 +19457,8 @@ var Client = class extends Protocol {
19550
19457
  const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
19551
19458
  const validationResult = safeParse2(resultSchema, result);
19552
19459
  if (!validationResult.success) {
19553
- const errorMessage2 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
19554
- throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage2}`);
19460
+ const errorMessage3 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
19461
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage3}`);
19555
19462
  }
19556
19463
  return validationResult.data;
19557
19464
  };
@@ -20884,8 +20791,8 @@ async function parseErrorResponse(input) {
20884
20791
  const errorClass = OAUTH_ERRORS[error] || ServerError;
20885
20792
  return new errorClass(error_description || "", error_uri);
20886
20793
  } catch (error) {
20887
- const errorMessage2 = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
20888
- return new ServerError(errorMessage2);
20794
+ const errorMessage3 = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
20795
+ return new ServerError(errorMessage3);
20889
20796
  }
20890
20797
  }
20891
20798
  async function auth(provider, options) {
@@ -21985,9 +21892,9 @@ var LinkqueWebSearchPort = class {
21985
21892
  outcome = "cancelled";
21986
21893
  throw new DOMException("\u5168\u7F51\u641C\u7D22\u5DF2\u53D6\u6D88", "AbortError");
21987
21894
  }
21988
- const failure3 = toWebSearchFailure(requestSignal.aborted ? requestSignal.reason : error);
21989
- outcome = failure3.code;
21990
- throw new WebSearchError(failure3.code);
21895
+ const failure5 = toWebSearchFailure(requestSignal.aborted ? requestSignal.reason : error);
21896
+ outcome = failure5.code;
21897
+ throw new WebSearchError(failure5.code);
21991
21898
  } finally {
21992
21899
  clearTimeout(timer);
21993
21900
  signal?.removeEventListener("abort", onAbort);
@@ -23220,10 +23127,9 @@ export {
23220
23127
  isJsonValue,
23221
23128
  isSafeJsonPointer,
23222
23129
  readJsonPointer,
23223
- A2UI_PAYMENT_RESULT_EVENT_NAME,
23224
- parseA2UIActionExecuteRequest,
23225
- parseA2UIPaymentResultEventPayload,
23226
23130
  executeA2UICardResolver,
23131
+ parseA2UIActionExecuteRequest,
23132
+ parseA2UIFunctionMcpExecuteRequest,
23227
23133
  stableToolName,
23228
23134
  createCardPresentationToolName,
23229
23135
  executeCardPresentation,
@@ -23232,7 +23138,7 @@ export {
23232
23138
  parseCardConfig,
23233
23139
  isAgentPresentationToolResult,
23234
23140
  createPresentationDescription,
23235
- readStructuredContent2 as readStructuredContent,
23141
+ readStructuredContent,
23236
23142
  normalizeMcpInputSchema,
23237
23143
  CardMappingError,
23238
23144
  aggregateMcpServers,
@@ -23240,7 +23146,7 @@ export {
23240
23146
  executeHomeData,
23241
23147
  CardActionDiagnostics,
23242
23148
  executeCardAction,
23243
- verifyPaymentResult,
23149
+ executeFunctionActionMcp,
23244
23150
  FOLLOW_UP_CONTEXT_MAX_HISTORY_RUNS,
23245
23151
  prepareFollowUpQuestionContext,
23246
23152
  normalizeFollowUpQuestionStrings,
@@ -23273,11 +23179,11 @@ export {
23273
23179
  ETelemetryModelPurpose,
23274
23180
  ETelemetryErrorType,
23275
23181
  ETelemetryGenAiOperation,
23276
- ETelemetryAssociation,
23277
23182
  warnLogFailure,
23278
23183
  HookDispatcher,
23279
23184
  DEFAULT_HOOK_DRAIN_BUDGET_MS,
23280
23185
  SideEffectRunner,
23186
+ ETelemetryAssociation,
23281
23187
  wrapToolWithHooks,
23282
23188
  NoopHookExecutor,
23283
23189
  RUNTIME_CONFIG_DEFAULTS,