linkque-cli-v2 1.2.5 → 1.2.7

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.
@@ -24,13 +24,13 @@ import {
24
24
  resolveLinkqueGatewayAuth,
25
25
  resolveRunStorage,
26
26
  toAgentRunMessages
27
- } from "../../chunk-E5KGGPEP.js";
27
+ } from "../../chunk-B5QEJGC6.js";
28
28
  import "../../chunk-MKS245OU.js";
29
29
  import "../../chunk-YDKZZ6EH.js";
30
30
  import "../../chunk-2NGJGNYB.js";
31
31
  import {
32
32
  getBakedProtocol
33
- } from "../../chunk-7OQJF6OX.js";
33
+ } from "../../chunk-5SPKWM3O.js";
34
34
  import {
35
35
  A2UI_PAYMENT_RESULT_EVENT_NAME,
36
36
  CANCEL_CONVERSATION_RUN_OPERATION,
@@ -92,14 +92,16 @@ import {
92
92
  parseMarkConversationRunsReadRequest,
93
93
  parseSkillFile,
94
94
  prepareFollowUpQuestionContext,
95
+ projectPresentationReceiptForModel,
95
96
  readStructuredContent,
96
97
  redactHeaders,
97
98
  stableToolName,
98
99
  streamToConversationEvents,
99
100
  summarizeBody,
100
101
  verifyPaymentResult,
102
+ warnLogFailure,
101
103
  wrapToolWithHooks
102
- } from "../../chunk-YYBDYBTX.js";
104
+ } from "../../chunk-MLVSBCIT.js";
103
105
  import "../../chunk-XUFLSZM4.js";
104
106
  import "../../chunk-I64V3ICJ.js";
105
107
  import {
@@ -39376,7 +39378,8 @@ async function createAgentSession(options) {
39376
39378
  onDelay: (delayMs) => {
39377
39379
  try {
39378
39380
  options.debugLog?.(`[llm-throttle] wait ${delayMs}ms before next request`, EDebugLogScope.LLM);
39379
- } catch {
39381
+ } catch (error) {
39382
+ warnLogFailure("createAgentSession.throttleLog", error);
39380
39383
  }
39381
39384
  }
39382
39385
  });
@@ -39409,7 +39412,8 @@ async function createAgentSession(options) {
39409
39412
  await prevOnPayload?.(payload, m);
39410
39413
  try {
39411
39414
  logSink(formatHttpLogLine("llm", "req", `POST ${baseUrl} model=${m.id} payload=${summarizeBody(safeStringifyPayload(payload))}`), EDebugLogScope.LLM);
39412
- } catch {
39415
+ } catch (error) {
39416
+ warnLogFailure("createAgentSession.requestLog", error);
39413
39417
  }
39414
39418
  };
39415
39419
  }
@@ -39426,6 +39430,7 @@ async function createAgentSession(options) {
39426
39430
  responseHeaders: response.headers
39427
39431
  }
39428
39432
  };
39433
+ await options.hookRuntime.dispatcher.dispatch(EHookStage.MODEL_RESPONSE_RECEIVED, options.hookRuntime.commonParams, subject);
39429
39434
  if (options.hookRuntime.dispatcher.hasMatchingResource(EHookStage.AFTER_MODEL_CALL, subject)) {
39430
39435
  gateState = { subject };
39431
39436
  }
@@ -39434,7 +39439,8 @@ async function createAgentSession(options) {
39434
39439
  try {
39435
39440
  const baseUrl = model.baseUrl ?? "<unknown>";
39436
39441
  logSink(formatHttpLogLine("llm", "resp", `POST ${baseUrl} model=${m.id} ${response.status} headers=${redactHeaders(response.headers)}`), EDebugLogScope.LLM);
39437
- } catch {
39442
+ } catch (error) {
39443
+ warnLogFailure("createAgentSession.responseLog", error);
39438
39444
  }
39439
39445
  }
39440
39446
  };
@@ -39461,7 +39467,8 @@ async function createAgentSession(options) {
39461
39467
  try {
39462
39468
  agent.abort();
39463
39469
  agent.reset();
39464
- } catch {
39470
+ } catch (error) {
39471
+ warnLogFailure("createAgentSession.dispose", error);
39465
39472
  }
39466
39473
  }
39467
39474
  }
@@ -39514,7 +39521,8 @@ function serializeToolResult(value) {
39514
39521
  try {
39515
39522
  const serialized = JSON.stringify(value);
39516
39523
  return serialized === void 0 ? "\u5DE5\u5177\u6267\u884C\u5B8C\u6210\u3002" : serialized;
39517
- } catch {
39524
+ } catch (error) {
39525
+ warnLogFailure("createAgentSession.toolResultSerialization", error);
39518
39526
  return "\u5DE5\u5177\u6267\u884C\u5B8C\u6210\u3002";
39519
39527
  }
39520
39528
  }
@@ -39525,7 +39533,8 @@ function safeStringifyPayload(payload) {
39525
39533
  return payload;
39526
39534
  try {
39527
39535
  return JSON.stringify(payload) ?? "";
39528
- } catch {
39536
+ } catch (error) {
39537
+ warnLogFailure("createAgentSession.payloadSerialization", error);
39529
39538
  return "<unserializable>";
39530
39539
  }
39531
39540
  }
@@ -40270,6 +40279,9 @@ function safeStringify(value) {
40270
40279
  }
40271
40280
 
40272
40281
  // ../linkque-agent-runtime/dist/esm/core/cardRenderMcpServer.js
40282
+ var CARD_SEQUENCE = "\u540C\u4E00\u65F6\u95F4\u53EA\u80FD\u5236\u4F5C\u4E00\u5F20\u5361\u7247\uFF1A\u5148\u5B8C\u6210\u5F53\u524D\u5361\u7247\u7684\u9009\u62E9 \u2192 \u6570\u636E\u6E90\u8C03\u7528 \u2192 \u5C55\u793A\uFF0C\u518D\u9009\u62E9\u4E0B\u4E00\u5F20\u5361\u7247\u3002\u4E0D\u8981\u4EA4\u53C9\u8C03\u7528\u4E0D\u540C\u672A\u5B8C\u6210\u5361\u7247\u7684\u5DE5\u5177\u3002";
40283
+ var AFTER_CARD_DESCRIPTION = "\u968F\u5361\u7247\u4E00\u8D77\u5C55\u793A\u7684\u6587\u5B57\u3002card_only \u5FC5\u987B\u4E3A\u7A7A\u5B57\u7B26\u4E32\u3002supplement \u53EA\u5B8C\u6210\u5269\u4F59\u95EE\u9898\uFF0C\u76F4\u63A5\u7ED9\u7ED3\u8BBA\uFF0C\u4E0D\u5148\u6982\u8FF0\u5404\u4E2A\u5019\u9009\uFF1A\u4EF7\u683C\u603B\u7ED3\u5E94\u8BF4\u8303\u56F4/\u96C6\u4E2D\u533A\u95F4/\u53D6\u820D\uFF0C\u4E0D\u6309\u9152\u5E97\u5206\u522B\u5199\u8BC4\u4EF7\uFF1B\u8FFD\u95EE\u53EA\u95EE\u6240\u9700\u6761\u4EF6\uFF0C\u4E0D\u5148\u4ECB\u7ECD\u5168\u90E8\u9152\u5E97\uFF1B\u9009\u4E00\u5BB6\u53EA\u7ED9\u8BE5\u9879\u53CA\u7406\u7531\u3002\u5141\u8BB8\u5FC5\u8981\u5F15\u7528\u4E2A\u522B\u540D\u79F0\u6570\u503C\u3002\u4E0D\u8981\u4ECE\u8BC4\u5206\u63A8\u65AD\u536B\u751F\u3001\u4ECE\u8FD1\u5730\u94C1\u63A8\u65AD\u7279\u5B9A\u666F\u70B9\u4FBF\u5229\u6027\uFF0C\u672A\u77E5\u4FDD\u6301\u672A\u77E5\u3002user_requested_text \u53EF\u63D0\u4F9B\u7528\u6237\u660E\u786E\u8981\u6C42\u7684\u5B8C\u6574\u6587\u5B57/\u8868\u683C\u3002\u591A\u5361\u7247\u65F6\u586B\u5199\u7D27\u63A5\u5F53\u524D\u5361\u7247\u7684\u8BF4\u660E\uFF0C\u7136\u540E\u7EE7\u7EED\u8C03\u7528\u4E0B\u4E00\u5F20\u5361\u7247\u5DE5\u5177\u3002\u6B64\u5904\u6587\u5B57\u4F1A\u76F4\u63A5\u5C55\u793A\uFF0Cfinish \u6210\u529F\u540E\u4E0D\u8981\u53E6\u5199\u4E00\u904D\uFF1B\u5361\u7247\u5931\u8D25\u65F6\u4ECD\u53EF\u6B63\u5E38\u6587\u5B57\u56DE\u7B54\u3002";
40284
+ var RESPONSE_MODE_DESCRIPTION = "\u6309\u7528\u6237\u4EFB\u52A1\u9009\u62E9\uFF1Acard_only=\u67E5\u8BE2/\u5C55\u793A\u7ED3\u679C/\u6CDB\u6CDB\u63A8\u8350\u5019\u9009\uFF0C\u5361\u7247\u5DF2\u7ECF\u5B8C\u6210\u4EFB\u52A1\uFF0C\u4E0D\u4E3B\u52A8\u65B0\u589E\u89E3\u91CA\u6216\u8FFD\u95EE\uFF1Bsupplement=\u7528\u6237\u8FD8\u8981\u6C42\u9009\u4E00\u5BB6\u53CA\u7406\u7531\u3001\u603B\u7ED3\u53D6\u820D\u3001\u8865\u5145\u653F\u7B56\u3001\u9884\u8BA2\u6240\u9700\u4FE1\u606F\uFF0C\u6216\u67E5\u8BE2\u4E3A\u7A7A\u9700\u8BF4\u660E\uFF1Buser_requested_text=\u7528\u6237\u660E\u786E\u8981\u6C42\u53E6\u7ED9\u6587\u5B57/\u53EF\u590D\u5236\u8868\u683C\u3002\u793A\u4F8B\uFF1A\u201C\u63A8\u8350\u676D\u5DDE\u9152\u5E97\u201D\u2192card_only\uFF1B\u201C\u63A8\u8350\u676D\u5DDE\u9152\u5E97\uFF0C\u9009\u4E00\u5BB6\u9002\u5408\u5E26\u5B69\u5B50\u7684\u201D\u2192supplement\uFF1B\u201C\u65E2\u8981\u5361\u7247\u4E5F\u8981\u5B8C\u6574\u8868\u683C\u201D\u2192user_requested_text\u3002";
40273
40285
  var CardRenderMcpServer = class {
40274
40286
  resources;
40275
40287
  registry;
@@ -40291,6 +40303,8 @@ var CardRenderMcpServer = class {
40291
40303
  toolByName = /* @__PURE__ */ new Map();
40292
40304
  activeCardId;
40293
40305
  invalidCards = [];
40306
+ /** 只信任本实例实际执行成功的结果,普通 MCP JSON 无权控制文字输出。 */
40307
+ companions = /* @__PURE__ */ new WeakMap();
40294
40308
  /** 本轮被隔离的坏卡,仅供宿主诊断,不影响其它卡片注册。 */
40295
40309
  getInvalidCards() {
40296
40310
  return this.invalidCards;
@@ -40331,7 +40345,7 @@ var CardRenderMcpServer = class {
40331
40345
  resourceId: resource.resourceId,
40332
40346
  label: config.displayName,
40333
40347
  description: `${createPresentationDescription(config)}
40334
- Select this card first, then call its card_source tools and card_finish tool.`,
40348
+ \u5148\u9009\u62E9\u6B64\u5361\u7247\uFF0C\u518D\u4F9D\u6B21\u8C03\u7528\u5B83\u7684 card_source \u6570\u636E\u6E90\u5DE5\u5177\u548C card_finish \u5C55\u793A\u5DE5\u5177\u3002${CARD_SEQUENCE}`,
40335
40349
  inputSchema: {
40336
40350
  type: "object",
40337
40351
  properties: {},
@@ -40370,18 +40384,18 @@ Select this card first, then call its card_source tools and card_finish tool.`,
40370
40384
  modelName: sourceToolName,
40371
40385
  resourceId: resource.resourceId,
40372
40386
  label: source.purpose,
40373
- description: `Use after selecting ${name}. ${source.purpose}. Choose all MCP arguments from the conversation and prior source results.`,
40387
+ description: `\u9009\u62E9 ${name} \u540E\u4F7F\u7528\u3002${source.purpose}\u3002\u6839\u636E\u5BF9\u8BDD\u548C\u5DF2\u6709\u6570\u636E\u6E90\u7ED3\u679C\u786E\u5B9A\u6240\u6709 MCP \u53C2\u6570\u3002${CARD_SEQUENCE}`,
40374
40388
  inputSchema: normalizeMcpInputSchema(discoveredHandle?.inputSchema),
40375
40389
  outputSchema: discoveredHandle?.outputSchema ?? source.outputSchema,
40376
40390
  execute: async (args, signal) => {
40377
40391
  if (!state2.selected || this.activeCardId !== resource.resourceId)
40378
- throw new Error(`Select card ${name} before calling its data sources`);
40392
+ throw new Error(`\u8C03\u7528\u6570\u636E\u6E90\u524D\uFF0C\u8BF7\u5148\u9009\u62E9\u5361\u7247 ${name}`);
40379
40393
  const missingDependencies = (source.dependsOn ?? []).filter((dependency) => !state2.results.has(dependency));
40380
40394
  if (missingDependencies.length)
40381
- throw new Error(`Data source ${source.sourceId} is waiting for: ${missingDependencies.join(", ")}`);
40395
+ throw new Error(`\u6570\u636E\u6E90 ${source.sourceId} \u9700\u8981\u5148\u5B8C\u6210\u4EE5\u4E0B\u4F9D\u8D56\uFF1A${missingDependencies.join(", ")}`);
40382
40396
  const handle = discoveredHandle ?? await this.registry.resolve(source.mcpResourceId, source.toolName, signal);
40383
40397
  if (!handle)
40384
- throw new Error(`MCP tool ${source.mcpResourceId}/${source.toolName} is unavailable`);
40398
+ throw new Error(`MCP \u5DE5\u5177 ${source.mcpResourceId}/${source.toolName} \u5F53\u524D\u4E0D\u53EF\u7528`);
40385
40399
  const result = await handle.execute(args, signal);
40386
40400
  const structured = readStructuredContent(result);
40387
40401
  if (structured === void 0) {
@@ -40408,16 +40422,36 @@ Select this card first, then call its card_source tools and card_finish tool.`,
40408
40422
  modelName: finishName,
40409
40423
  resourceId: resource.resourceId,
40410
40424
  label: `\u5C55\u793A${config.displayName}`,
40411
- description: `Finish and render ${config.displayName} after all required card_source tools succeed.`,
40425
+ description: `\u6240\u6709\u5FC5\u9700\u7684 card_source \u6570\u636E\u6E90\u5DE5\u5177\u6210\u529F\u540E\uFF0C\u5B8C\u6210\u5E76\u5C55\u793A${config.displayName}\u3002${CARD_SEQUENCE}
40426
+ ${AFTER_CARD_DESCRIPTION}`,
40412
40427
  inputSchema: {
40413
40428
  type: "object",
40414
- properties: {},
40429
+ required: ["responseMode", "afterCard"],
40430
+ properties: {
40431
+ responseMode: {
40432
+ type: "string",
40433
+ enum: ["card_only", "supplement", "user_requested_text"],
40434
+ description: RESPONSE_MODE_DESCRIPTION
40435
+ },
40436
+ afterCard: {
40437
+ type: "string",
40438
+ maxLength: 16e3,
40439
+ description: AFTER_CARD_DESCRIPTION
40440
+ }
40441
+ },
40415
40442
  additionalProperties: false
40416
40443
  },
40417
- execute: async (_args, signal) => {
40444
+ execute: async (args, signal) => {
40418
40445
  if (!state2.selected || this.activeCardId !== resource.resourceId)
40419
- throw new Error(`Select card ${name} before finishing it`);
40446
+ throw new Error(`\u5B8C\u6210\u5C55\u793A\u524D\uFF0C\u8BF7\u5148\u9009\u62E9\u5361\u7247 ${name}`);
40447
+ const afterCard = readAfterCard(args);
40420
40448
  const result = await executeCardPresentationFromSources(resource, this.runtimeContext, state2.results, signal);
40449
+ if (afterCard !== void 0) {
40450
+ this.companions.set(result, afterCard);
40451
+ result.modelText += `
40452
+ <a2ui-companion-delivery>${JSON.stringify({ afterCard })}</a2ui-companion-delivery>
40453
+ \u5361\u7247\u548C\u4E0A\u8FF0\u4F34\u968F\u6587\u5B57\u5DF2\u4F5C\u4E3A\u56DE\u7B54\u53D1\u51FA\u3002\u65E0\u9700\u518D\u6B21\u8F93\u51FA\u6587\u5B57\uFF1B\u82E5\u8FD8\u6709\u5176\u4ED6\u4EFB\u52A1\uFF0C\u7EE7\u7EED\u8C03\u7528\u5DE5\u5177\u3002`;
40454
+ }
40421
40455
  state2.selected = false;
40422
40456
  this.activeCardId = void 0;
40423
40457
  return result;
@@ -40448,8 +40482,52 @@ Select this card first, then call its card_source tools and card_finish tool.`,
40448
40482
  this.activeCardId = void 0;
40449
40483
  this.states.clear();
40450
40484
  this.toolByName.clear();
40485
+ this.companions = /* @__PURE__ */ new WeakMap();
40486
+ }
40487
+ /** 卡片与伴随文字的共享输出边界,不参与模型循环或工具调度。 */
40488
+ async *projectConversation(events) {
40489
+ const pending = /* @__PURE__ */ new WeakMap();
40490
+ let cardOwnsText = false;
40491
+ for await (const event of events) {
40492
+ if (event.type === "tool_start" || event.type === "error" || event.type === "done")
40493
+ cardOwnsText = false;
40494
+ if (event.type === "tool_end" && !event.isError) {
40495
+ const details = event.result && typeof event.result === "object" && "details" in event.result ? event.result.details : void 0;
40496
+ if (details && this.companions.has(details)) {
40497
+ pending.set(details.card, this.companions.get(details));
40498
+ }
40499
+ }
40500
+ if (event.type === "delta" && cardOwnsText)
40501
+ continue;
40502
+ yield event;
40503
+ if (event.type === "a2ui_card" && pending.has(event)) {
40504
+ const text2 = pending.get(event);
40505
+ pending.delete(event);
40506
+ cardOwnsText = true;
40507
+ if (text2)
40508
+ yield { type: "delta", content: text2 };
40509
+ }
40510
+ }
40451
40511
  }
40452
40512
  };
40513
+ function readAfterCard(args) {
40514
+ if (!args || typeof args !== "object")
40515
+ return void 0;
40516
+ const mode = args.responseMode;
40517
+ if (Object.hasOwn(args, "responseMode") && !["card_only", "supplement", "user_requested_text"].includes(mode))
40518
+ throw new Error("responseMode \u65E0\u6548\uFF0C\u8BF7\u9009\u62E9\u5DF2\u58F0\u660E\u7684\u6A21\u5F0F");
40519
+ if (!Object.hasOwn(args, "afterCard")) {
40520
+ if (mode !== void 0)
40521
+ throw new Error("\u6307\u5B9A responseMode \u65F6\u5FC5\u987B\u63D0\u4F9B afterCard");
40522
+ return void 0;
40523
+ }
40524
+ const value = args.afterCard;
40525
+ if (typeof value !== "string" || value.length > 16e3)
40526
+ throw new Error("afterCard \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\uFF0C\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 16000");
40527
+ if (mode === "card_only" && value.trim() !== "")
40528
+ throw new Error("card_only \u6A21\u5F0F\u4E0B afterCard \u5FC5\u987B\u4E3A\u7A7A\u5B57\u7B26\u4E32\uFF1B\u5361\u7247\u5DF2\u7ECF\u56DE\u7B54\u4E86\u67E5\u8BE2");
40529
+ return value.trim();
40530
+ }
40453
40531
  function createCardSourceToolName(resourceId, sourceId) {
40454
40532
  return stableToolName("card_source", `${resourceId}_${sourceId}`);
40455
40533
  }
@@ -41026,7 +41104,7 @@ var AgentRuntime = class _AgentRuntime {
41026
41104
  });
41027
41105
  };
41028
41106
  try {
41029
- for await (const ev of this.agentLoop.run(agentReq)) {
41107
+ for await (const ev of cardServer.projectConversation(this.agentLoop.run(agentReq))) {
41030
41108
  if (ev.type === "delta")
41031
41109
  assistantText += ev.content;
41032
41110
  if (ev.type === "tool_end" && !ev.isError) {
@@ -41046,7 +41124,10 @@ var AgentRuntime = class _AgentRuntime {
41046
41124
  ...presentationReceipts.map((receipt) => ({
41047
41125
  role: "tool",
41048
41126
  name: "a2ui_presentation_receipt",
41049
- content: { type: "a2ui.presentation-receipt", receipt }
41127
+ content: {
41128
+ type: "a2ui.presentation-receipt",
41129
+ receipt: projectPresentationReceiptForModel(receipt)
41130
+ }
41050
41131
  })),
41051
41132
  { role: "assistant", content: assistantText }
41052
41133
  ];
@@ -41449,12 +41530,6 @@ var ImageUnderstandingPlugin = class {
41449
41530
  ]
41450
41531
  }
41451
41532
  });
41452
- if (!input.agentConfig.agent.multimodel.enabled)
41453
- return currentImage ? {
41454
- ok: false,
41455
- code: "IMAGE_DISABLED",
41456
- message: "\u5F53\u524D Agent \u672A\u5F00\u542F\u591A\u6A21\u6001\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u6216\u5F00\u542F\u540E\u91CD\u8BD5"
41457
- } : unavailable();
41458
41533
  const images = selected.turn.attachments;
41459
41534
  if (images.length !== 1)
41460
41535
  return currentImage ? {
@@ -41982,6 +42057,7 @@ function guardChatRequest(method, bodyJSON, logCtx) {
41982
42057
  }
41983
42058
 
41984
42059
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationHistoryStore.js
42060
+ import { emitWarning } from "node:process";
41985
42061
  import { randomUUID } from "node:crypto";
41986
42062
 
41987
42063
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationSearchStore.js
@@ -42256,18 +42332,27 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
42256
42332
  },
42257
42333
  async completeRun(completion) {
42258
42334
  const completedAt = completion.completedAt ?? Date.now();
42259
- const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, completion.runId);
42260
- if (!run || run.ownerId !== ownerId || run.threadId !== completion.threadId) {
42261
- throw new ConversationHistoryNotFoundError("Run \u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237");
42335
+ const transaction = await databases.createTransaction();
42336
+ const transactionId = transaction.$id;
42337
+ let status;
42338
+ try {
42339
+ const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, completion.runId, transactionId);
42340
+ if (!run || run.ownerId !== ownerId || run.threadId !== completion.threadId) {
42341
+ throw new ConversationHistoryNotFoundError("Run \u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237");
42342
+ }
42343
+ const persistedStatus = readRunStatus(run.status);
42344
+ status = persistedStatus === "cancelling" || persistedStatus === "cancelled" ? "cancelled" : completion.status;
42345
+ await databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, completion.runId, {
42346
+ status,
42347
+ completedAt,
42348
+ totalChunks: completion.totalChunks,
42349
+ ...status === "cancelled" ? { cancelledAt: completedAt } : {}
42350
+ }, void 0, transactionId);
42351
+ await databases.updateTransaction(transactionId, true, false);
42352
+ } catch (error) {
42353
+ await rollbackTransactionQuietly(databases, transactionId);
42354
+ throw error;
42262
42355
  }
42263
- const persistedStatus = readRunStatus(run.status);
42264
- const status = persistedStatus === "cancelling" || persistedStatus === "cancelled" ? "cancelled" : completion.status;
42265
- await databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, completion.runId, {
42266
- status,
42267
- completedAt,
42268
- totalChunks: completion.totalChunks,
42269
- ...status === "cancelled" ? { cancelledAt: completedAt } : {}
42270
- });
42271
42356
  const session = await readDocument(databases, config.sessionDatabaseId, config.sessionTableId, completion.threadId);
42272
42357
  if (session?.ownerId === ownerId && session.lastRunId === completion.runId) {
42273
42358
  await databases.updateDocument(config.sessionDatabaseId, config.sessionTableId, completion.threadId, { lastRunStatus: status });
@@ -42277,11 +42362,23 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
42277
42362
  const normalized = parseConversationFollowUpQuestions(value);
42278
42363
  if (!normalized?.questions.length)
42279
42364
  return;
42280
- const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, runId);
42281
- if (!run || run.ownerId !== ownerId || run.threadId !== threadId || readRunStatus(run.status) !== "done") {
42282
- throw new ConversationHistoryNotFoundError("Run \u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237\u6216\u5C1A\u672A\u6210\u529F\u7ED3\u675F");
42365
+ const transaction = await databases.createTransaction();
42366
+ const transactionId = transaction.$id;
42367
+ try {
42368
+ const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, runId, transactionId);
42369
+ if (!run || run.ownerId !== ownerId || run.threadId !== threadId || readRunStatus(run.status) !== "done") {
42370
+ throw new ConversationHistoryNotFoundError("Run \u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237\u6216\u5C1A\u672A\u6210\u529F\u7ED3\u675F");
42371
+ }
42372
+ if (run.blockedAnswer === true) {
42373
+ await databases.updateTransaction(transactionId, true, false);
42374
+ return;
42375
+ }
42376
+ await databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, runId, { followUpQuestionsJson: JSON.stringify(normalized) }, void 0, transactionId);
42377
+ await databases.updateTransaction(transactionId, true, false);
42378
+ } catch (error) {
42379
+ await rollbackTransactionQuietly(databases, transactionId);
42380
+ throw error;
42283
42381
  }
42284
- await databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, runId, { followUpQuestionsJson: JSON.stringify(normalized) });
42285
42382
  },
42286
42383
  async getRecentFollowUpQuestionContext(agentId, threadId, currentRunId, limit) {
42287
42384
  const boundedLimit = Math.max(0, Math.min(limit, 2));
@@ -42375,6 +42472,42 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
42375
42472
  throw error;
42376
42473
  }
42377
42474
  },
42475
+ async isRunAnswerBlocked(agentId, runId) {
42476
+ const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, runId);
42477
+ if (!run || run.ownerId !== ownerId || run.agentId !== agentId) {
42478
+ throw new ConversationHistoryNotFoundError();
42479
+ }
42480
+ return run.blockedAnswer === true;
42481
+ },
42482
+ async replaceAnswer(input) {
42483
+ const transaction = await databases.createTransaction();
42484
+ const transactionId = transaction.$id;
42485
+ try {
42486
+ const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, input.runId, transactionId);
42487
+ if (!run) {
42488
+ throw new ConversationHistoryNotFoundError("Run \u4E0D\u5B58\u5728");
42489
+ }
42490
+ if (run.blockedAnswer === true) {
42491
+ await databases.updateTransaction(transactionId, true, false);
42492
+ return "duplicate";
42493
+ }
42494
+ const active = !["done", "error", "cancelled"].includes(String(run.status));
42495
+ const now = Date.now();
42496
+ await databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, input.runId, {
42497
+ blockedAnswer: true,
42498
+ answerReplacement: input.replacementText,
42499
+ blockedAt: now,
42500
+ blockedBy: input.eventId,
42501
+ followUpQuestionsJson: null,
42502
+ ...active ? { status: "cancelling", cancelRequestedAt: now } : {}
42503
+ }, void 0, transactionId);
42504
+ await databases.updateTransaction(transactionId, true, false);
42505
+ return "applied";
42506
+ } catch (error) {
42507
+ await rollbackTransactionQuietly(databases, transactionId);
42508
+ throw error;
42509
+ }
42510
+ },
42378
42511
  async setRunBlocked(params) {
42379
42512
  const existing = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, params.runId);
42380
42513
  if (!existing) {
@@ -42549,7 +42682,8 @@ function readStoredFollowUpQuestions(value) {
42549
42682
  try {
42550
42683
  const parsed = parseConversationFollowUpQuestions(JSON.parse(value));
42551
42684
  return parsed?.questions.length ? parsed : void 0;
42552
- } catch {
42685
+ } catch (error) {
42686
+ emitWarning("[conversationHistoryStore.readStoredFollowUpQuestions] invalid stored JSON errorType=" + (error instanceof Error ? error.name : typeof error), { code: "LINKQUE_HISTORY_PARSE_FAILED" });
42553
42687
  return void 0;
42554
42688
  }
42555
42689
  }
@@ -42565,7 +42699,8 @@ function readStoredRunUserMessage(value) {
42565
42699
  return typeof message.content === "string" ? readNonEmptyString(message.content.replace(/\s+/gu, " ")) : void 0;
42566
42700
  }
42567
42701
  return void 0;
42568
- } catch {
42702
+ } catch (error) {
42703
+ emitWarning("[conversationHistoryStore.readStoredRunUserMessage] invalid stored JSON errorType=" + (error instanceof Error ? error.name : typeof error), { code: "LINKQUE_HISTORY_PARSE_FAILED" });
42569
42704
  return void 0;
42570
42705
  }
42571
42706
  }
@@ -42639,7 +42774,8 @@ async function readDocument(databases, databaseId, tableId, documentId, transact
42639
42774
  async function rollbackTransactionQuietly(databases, transactionId) {
42640
42775
  try {
42641
42776
  await databases.updateTransaction(transactionId, false, true);
42642
- } catch {
42777
+ } catch (error) {
42778
+ emitWarning(`[conversationHistoryStore.rollbackTransaction] transactionId=${transactionId} errorType=${error instanceof Error ? error.name : typeof error}`, { code: "LINKQUE_HISTORY_ROLLBACK_FAILED" });
42643
42779
  }
42644
42780
  }
42645
42781
  function deriveConversationCopy(request) {
@@ -42762,6 +42898,53 @@ function controlError(status, code, message) {
42762
42898
  return { status, body: { error: { code, message, status } } };
42763
42899
  }
42764
42900
 
42901
+ // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/replaceAnswer.js
42902
+ var REPLACE_ANSWER_OPERATION = "replaceAnswer";
42903
+ async function runReplaceAnswer(method, body, env, deps, logCtx, appwriteApiKey) {
42904
+ if (method !== "POST")
42905
+ return jsonError(405, "method_not_allowed", "\u4EC5\u652F\u6301 POST");
42906
+ const request = body;
42907
+ if (!request || request.operation !== REPLACE_ANSWER_OPERATION || request.version !== 1 || ![
42908
+ "eventId",
42909
+ "agentId",
42910
+ "threadId",
42911
+ "runId",
42912
+ "replacementText",
42913
+ "originalTraceId"
42914
+ ].every((key) => typeof body[key] === "string" && Boolean(body[key])) || !["ANSWER_STREAM", "QUESTION_FEEDBACK", "ANSWER_FEEDBACK"].includes(request.source)) {
42915
+ return jsonError(400, "invalid_replacement", "\u5B89\u5168\u66FF\u6362\u8BF7\u6C42\u65E0\u6548");
42916
+ }
42917
+ try {
42918
+ const store = deps?.store ?? createConversationHistoryStore(createAppBaseClient(env, logCtx, appwriteApiKey).databases, resolveConversationHistoryStorage(env));
42919
+ if (!store.replaceAnswer)
42920
+ return jsonError(503, "replacement_unsupported", "\u5B89\u5168\u66FF\u6362\u672A\u914D\u7F6E");
42921
+ const outcome = await store.replaceAnswer(request);
42922
+ logCtx?.log?.("[replaceAnswer] result", {
42923
+ eventId: request.eventId,
42924
+ agentId: request.agentId,
42925
+ threadId: request.threadId,
42926
+ runId: request.runId,
42927
+ originalTraceId: request.originalTraceId,
42928
+ source: request.source,
42929
+ outcome
42930
+ });
42931
+ return {
42932
+ status: 200,
42933
+ body: {
42934
+ operation: REPLACE_ANSWER_OPERATION,
42935
+ eventId: request.eventId,
42936
+ outcome
42937
+ }
42938
+ };
42939
+ } catch (error) {
42940
+ logCtx?.error?.("[replaceAnswer] failed", {
42941
+ eventId: request.eventId,
42942
+ runId: request.runId
42943
+ });
42944
+ return error instanceof ConversationHistoryNotFoundError ? jsonError(404, "run_not_found", "Run \u4E0D\u5B58\u5728") : jsonError(500, "replacement_failed", "\u5B89\u5168\u66FF\u6362\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
42945
+ }
42946
+ }
42947
+
42765
42948
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/appbaseStore.js
42766
42949
  function createAppBaseStore(databases, databaseId, tableId, ownerId) {
42767
42950
  const permissions = rowPermissions(ownerId);
@@ -43619,18 +43802,34 @@ var hasSecurityAnswerHeader = (headers) => Object.entries(headers ?? {}).some(([
43619
43802
  var SecurityAnswerHookExecutor = class {
43620
43803
  historyStore;
43621
43804
  handledRunIds;
43805
+ log;
43622
43806
  name = EHookExecutorName.SecurityAnswerHookExecutor;
43623
- constructor(historyStore, handledRunIds) {
43807
+ constructor(historyStore, handledRunIds, log) {
43624
43808
  this.historyStore = historyStore;
43625
43809
  this.handledRunIds = handledRunIds;
43810
+ this.log = log;
43626
43811
  }
43627
43812
  matches(resource, stage, subject) {
43628
- return resource.providerType === EResourceProviderType.LINK_QUE && resource.config.executorName === EHookExecutorName.SecurityAnswerHookExecutor && stage === EHookStage.AFTER_MODEL_CALL && hasSecurityAnswerHeader(subject.model?.responseHeaders);
43813
+ return resource.providerType === EResourceProviderType.LINK_QUE && resource.config.executorName === EHookExecutorName.SecurityAnswerHookExecutor && (stage === EHookStage.MODEL_RESPONSE_RECEIVED || stage === EHookStage.AFTER_MODEL_CALL && hasSecurityAnswerHeader(subject.model?.responseHeaders));
43629
43814
  }
43630
43815
  async execute(resource, context, _options) {
43631
- if (resource.providerType !== EResourceProviderType.LINK_QUE || resource.config.executorName !== EHookExecutorName.SecurityAnswerHookExecutor || context.stage !== EHookStage.AFTER_MODEL_CALL) {
43816
+ if (resource.providerType !== EResourceProviderType.LINK_QUE || resource.config.executorName !== EHookExecutorName.SecurityAnswerHookExecutor || context.stage !== EHookStage.AFTER_MODEL_CALL && context.stage !== EHookStage.MODEL_RESPONSE_RECEIVED) {
43632
43817
  return { ok: true, skipped: true, code: "EXECUTOR_MISMATCH" };
43633
43818
  }
43819
+ if (context.stage === EHookStage.MODEL_RESPONSE_RECEIVED) {
43820
+ const action = Object.entries(context.model.responseHeaders).find(([key]) => key.toLowerCase() === SECURITY_ANSWER_HEADER)?.[1];
43821
+ if (action)
43822
+ this.log?.("[guardrails] interception", {
43823
+ actionCode: action,
43824
+ case: action === SECURITY_ANSWER_ACTION ? 3 : 1,
43825
+ agentId: context.commonParams.agentId,
43826
+ threadId: context.commonParams.threadId,
43827
+ runId: context.commonParams.runId,
43828
+ traceId: context.commonParams.traceId,
43829
+ responseStatus: context.model.responseStatus
43830
+ });
43831
+ return { ok: true };
43832
+ }
43634
43833
  if (!hasSecurityAnswerHeader(context.model.responseHeaders)) {
43635
43834
  return { ok: true };
43636
43835
  }
@@ -43661,13 +43860,27 @@ var SecurityAnswerHookExecutor = class {
43661
43860
  }
43662
43861
  };
43663
43862
  var isSecurityAnswerHook = (resource) => resource.resourceType === EResourceType.HOOK && resource.providerType === EResourceProviderType.LINK_QUE && resource.config.executorName === EHookExecutorName.SecurityAnswerHookExecutor && resource.config.stage === EHookStage.AFTER_MODEL_CALL;
43664
- function createSecurityAnswerPlugin(historyStore) {
43863
+ function createSecurityAnswerPlugin(historyStore, log) {
43665
43864
  const handledRunIds = /* @__PURE__ */ new Set();
43666
- const executor = new SecurityAnswerHookExecutor(historyStore, handledRunIds);
43865
+ const executor = new SecurityAnswerHookExecutor(historyStore, handledRunIds, log);
43667
43866
  return {
43668
43867
  name: SECURITY_ANSWER_PLUGIN_NAME,
43669
43868
  hookExecutorList: [executor],
43670
43869
  modifyAgentConfig(agentConfig) {
43870
+ if (log && !agentConfig.agent.resources.some((resource) => resource.resourceId === "chat-gateway-guardrails-response-log")) {
43871
+ agentConfig.agent.resources.push({
43872
+ resourceId: "chat-gateway-guardrails-response-log",
43873
+ resourceType: EResourceType.HOOK,
43874
+ providerType: EResourceProviderType.LINK_QUE,
43875
+ config: {
43876
+ name: "\u5B89\u5168\u62E6\u622A\u54CD\u5E94\u65E5\u5FD7",
43877
+ executorName: EHookExecutorName.SecurityAnswerHookExecutor,
43878
+ stage: EHookStage.MODEL_RESPONSE_RECEIVED,
43879
+ hasSideEffects: false,
43880
+ timeoutMs: 5e3
43881
+ }
43882
+ });
43883
+ }
43671
43884
  if (agentConfig.agent.resources.some(isSecurityAnswerHook))
43672
43885
  return;
43673
43886
  const hookResource = {
@@ -43756,7 +43969,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
43756
43969
  resolveConfig: mcpConfigResolver,
43757
43970
  getAuthorizationHeader: mcpAuthorizationHeaderProvider
43758
43971
  });
43759
- const securityAnswerPlugin = deps?.securityAnswerPlugin ?? createSecurityAnswerPlugin(historyStore);
43972
+ const securityAnswerPlugin = deps?.securityAnswerPlugin ?? createSecurityAnswerPlugin(historyStore, logCtx?.log);
43760
43973
  const runtime = deps?.runtime ?? createAppBaseRuntime(protocol, env, {
43761
43974
  ...appwriteApiKey ? { appBaseApiKey: appwriteApiKey } : {},
43762
43975
  mcpConfigResolver,
@@ -44230,6 +44443,21 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
44230
44443
  }
44231
44444
  }
44232
44445
  }
44446
+ const isAnswerBlocked = async () => {
44447
+ if (execution.securityAnswer)
44448
+ return true;
44449
+ if (!cfg.historyStore?.isRunAnswerBlocked || isPresentationRun)
44450
+ return false;
44451
+ try {
44452
+ return await cfg.historyStore.isRunAnswerBlocked(cfg.protocol.agentId, request.runId);
44453
+ } catch (error) {
44454
+ logError("\u5B89\u5168\u72B6\u6001\u67E5\u8BE2\u5931\u8D25\uFF0C\u8DF3\u8FC7\u8FFD\u95EE", {
44455
+ runId: request.runId,
44456
+ errorMsg: error instanceof Error ? error.message : String(error)
44457
+ });
44458
+ return true;
44459
+ }
44460
+ };
44233
44461
  let preparedFollowUpContext;
44234
44462
  log("\u8FFD\u95EE\u89E6\u53D1\u68C0\u67E5:", {
44235
44463
  runStatus: execution.runStatus,
@@ -44239,7 +44467,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
44239
44467
  hasContextPreparer: Boolean(cfg.runtime.prepareFollowUpQuestionContext),
44240
44468
  hasGenerator: Boolean(cfg.runtime.generateFollowUpQuestions)
44241
44469
  });
44242
- if (!isPresentationRun && !execution.securityAnswer && execution.runStatus === "done" && execution.searchMessages.length > 0 && cfg.historyStore?.saveFollowUpQuestions && cfg.runtime.prepareFollowUpQuestionContext && cfg.runtime.generateFollowUpQuestions) {
44470
+ if (!isPresentationRun && !execution.securityAnswer && !await isAnswerBlocked() && execution.runStatus === "done" && execution.searchMessages.length > 0 && cfg.historyStore?.saveFollowUpQuestions && cfg.runtime.prepareFollowUpQuestionContext && cfg.runtime.generateFollowUpQuestions) {
44243
44471
  let followUpHistory = [];
44244
44472
  if (cfg.historyStore.getRecentFollowUpQuestionContext) {
44245
44473
  try {
@@ -44260,7 +44488,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
44260
44488
  }
44261
44489
  }
44262
44490
  const released = await releaseLease();
44263
- if (released && preparedFollowUpContext && cfg.historyStore?.saveFollowUpQuestions && cfg.runtime.generateFollowUpQuestions) {
44491
+ if (released && preparedFollowUpContext && !await isAnswerBlocked() && cfg.historyStore?.saveFollowUpQuestions && cfg.runtime.generateFollowUpQuestions) {
44264
44492
  try {
44265
44493
  const questions = await cfg.runtime.generateFollowUpQuestions(preparedFollowUpContext, cfg.auth, {
44266
44494
  runId: request.runId,
@@ -44504,6 +44732,10 @@ async function chat(ctx) {
44504
44732
  const bodyJSON = resolveBodyJSON(ctx.req);
44505
44733
  const historyOwnerId = readAuthenticatedUserId(ctx.req.headers);
44506
44734
  const appwriteApiKey = readAppwriteApiKey(ctx.req.headers);
44735
+ if (readOperation(bodyJSON) === REPLACE_ANSWER_OPERATION) {
44736
+ const control = await runReplaceAnswer(ctx.req.method, bodyJSON, process.env, void 0, { log: ctx.log, error: ctx.error }, appwriteApiKey);
44737
+ return ctx.res.json?.(control.body, control.status);
44738
+ }
44507
44739
  const envSelector = readEnvSelector(ctx.req.headers);
44508
44740
  const traceId = readTraceId(ctx.req.headers);
44509
44741
  const temporaryFrontendAppId = readTemporaryFrontendAppId(ctx.req.headers);
@@ -3,11 +3,11 @@ import {
3
3
  runClientCapability,
4
4
  runClientCapabilityCleanup,
5
5
  runClientCapabilityResult
6
- } from "../../chunk-E5KGGPEP.js";
6
+ } from "../../chunk-B5QEJGC6.js";
7
7
  import "../../chunk-MKS245OU.js";
8
8
  import "../../chunk-YDKZZ6EH.js";
9
9
  import "../../chunk-2NGJGNYB.js";
10
- import "../../chunk-YYBDYBTX.js";
10
+ import "../../chunk-MLVSBCIT.js";
11
11
  import "../../chunk-XUFLSZM4.js";
12
12
  import "../../chunk-I64V3ICJ.js";
13
13
  import "../../chunk-VS2QQHAK.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  getBakedProtocol,
3
3
  setBakedProtocol
4
- } from "../chunk-7OQJF6OX.js";
5
- import "../chunk-YYBDYBTX.js";
4
+ } from "../chunk-5SPKWM3O.js";
5
+ import "../chunk-MLVSBCIT.js";
6
6
  import "../chunk-XUFLSZM4.js";
7
7
  import "../chunk-I64V3ICJ.js";
8
8
  import "../chunk-VS2QQHAK.js";