linkque-cli-v2 1.2.0 → 1.2.2

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.
@@ -13,13 +13,14 @@ import {
13
13
  readAppwriteApiKey,
14
14
  readAuthenticatedUserId,
15
15
  readEnvSelector,
16
+ readTemporaryFrontendAppId,
16
17
  readTraceId,
17
18
  resolveBodyJSON,
18
19
  resolveGatewayAuthContext,
19
20
  resolveLinkqueGatewayAuth,
20
21
  resolveRunStorage,
21
22
  toAgentRunMessages
22
- } from "../../chunk-NRTXRI33.js";
23
+ } from "../../chunk-F3IESVDW.js";
23
24
  import "../../chunk-MKS245OU.js";
24
25
  import "../../chunk-YDKZZ6EH.js";
25
26
  import "../../chunk-2NGJGNYB.js";
@@ -34,6 +35,7 @@ import {
34
35
  DEFAULT_CONVERSATION_LIST_LIMIT,
35
36
  DEFAULT_CONVERSATION_RUN_LIST_LIMIT,
36
37
  DEFAULT_CONVERSATION_SEARCH_LIMIT,
38
+ DEFAULT_HOOK_DRAIN_BUDGET_MS,
37
39
  EHookExecutorName,
38
40
  EHookStage,
39
41
  EResourceProviderType,
@@ -41,24 +43,29 @@ import {
41
43
  ESkillUrlScheme,
42
44
  EventType,
43
45
  FOLLOW_UP_CONTEXT_MAX_HISTORY_RUNS,
46
+ HookDispatcher,
44
47
  LinkqueKnowledgeSearchPort,
45
48
  LinkquegwEventHookExecutor,
49
+ MARK_CONVERSATION_RUNS_READ_OPERATION,
46
50
  RemoteGatewayMcpServerProvider,
51
+ SideEffectRunner,
47
52
  WebSkillLoader,
48
53
  encodeConversationSseEvent,
49
54
  executeCardAction,
50
55
  executeHomeData,
51
56
  getBakedProtocol,
57
+ normalizeHookResources,
52
58
  parseA2UIActionExecuteRequest,
53
59
  parseA2UIPaymentResultEventPayload,
54
60
  parseCancelConversationRunRequest,
55
61
  parseConversationFollowUpQuestions,
56
62
  parseConversationHistoryRequest,
57
63
  parseConversationRunRequest,
64
+ parseMarkConversationRunsReadRequest,
58
65
  parseSkillFile,
59
66
  streamToConversationEvents,
60
67
  verifyPaymentResult
61
- } from "../../chunk-HPOFEAMP.js";
68
+ } from "../../chunk-7YMZ4CJ5.js";
62
69
  import "../../chunk-XUFLSZM4.js";
63
70
  import "../../chunk-I64V3ICJ.js";
64
71
  import "../../chunk-6MHDOBWO.js";
@@ -77,6 +84,7 @@ var LINKQUEGW_EVENT_PLUGIN_NAME = "linkquegw-event-plugin";
77
84
  var LINKQUEGW_EVENT_HOOK_RESOURCE_ID = "linkquegw-event-run-started";
78
85
  var LINKQUEGW_RUN_COMPLETED_HOOK_RESOURCE_ID = "linkquegw-event-run-completed";
79
86
  var LINKQUEGW_RUN_FAILED_HOOK_RESOURCE_ID = "linkquegw-event-run-failed";
87
+ var LINKQUEGW_RUN_READ_HOOK_RESOURCE_ID = "linkquegw-event-run-read";
80
88
  var DEFAULT_LINKQUEGW_EVENT_HOOKS = [
81
89
  {
82
90
  resourceId: LINKQUEGW_EVENT_HOOK_RESOURCE_ID,
@@ -89,6 +97,10 @@ var DEFAULT_LINKQUEGW_EVENT_HOOKS = [
89
97
  {
90
98
  resourceId: LINKQUEGW_RUN_FAILED_HOOK_RESOURCE_ID,
91
99
  stage: EHookStage.RUN_FAILED
100
+ },
101
+ {
102
+ resourceId: LINKQUEGW_RUN_READ_HOOK_RESOURCE_ID,
103
+ stage: EHookStage.RUN_READ
92
104
  }
93
105
  ];
94
106
  var createLinkquegwEventHookResource = (resourceId, stage) => ({
@@ -130,6 +142,9 @@ var LinkquegwEventPlugin = class {
130
142
  ...options.metricsSink !== void 0 && {
131
143
  metricsSink: options.metricsSink
132
144
  },
145
+ ...options.temporaryFrontendAppId !== void 0 && {
146
+ temporaryFrontendAppId: options.temporaryFrontendAppId
147
+ },
133
148
  ...options.now !== void 0 && { now: options.now }
134
149
  };
135
150
  this.hookExecutorList = [new LinkquegwEventHookExecutor(executorOptions)];
@@ -295,6 +310,7 @@ function createAppbaseMcpProvider(options = {}) {
295
310
  return new RemoteGatewayMcpServerProvider({
296
311
  resolveConfig: options.resolveConfig,
297
312
  ...options.getAuthorizationHeader ? { getAuthorizationHeader: options.getAuthorizationHeader } : {},
313
+ ...options.onTraceId ? { onTraceId: options.onTraceId } : {},
298
314
  ...options.debugLog ? { debugLog: options.debugLog } : {}
299
315
  });
300
316
  }
@@ -385,6 +401,9 @@ function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
385
401
  getUserTokenAuthorizationHeader: mcpAuthHeader,
386
402
  ...eventBaseUrl ? { baseUrl: eventBaseUrl } : {},
387
403
  ...ports.gatewayAgentId ? { agentId: ports.gatewayAgentId } : {},
404
+ ...ports.temporaryFrontendAppId !== void 0 && {
405
+ temporaryFrontendAppId: ports.temporaryFrontendAppId
406
+ },
388
407
  ...debugLog ? { debugLog } : {}
389
408
  }));
390
409
  }
@@ -874,6 +893,39 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
874
893
  const status = readRunStatus(run.status);
875
894
  return status === "cancelling" || status === "cancelled" || readNonNegativeInteger2(run.cancelRequestedAt) > 0;
876
895
  },
896
+ async markRunsRead(agentId, runIds) {
897
+ const transaction = await databases.createTransaction();
898
+ const transactionId = transaction.$id;
899
+ try {
900
+ const runs = await Promise.all(runIds.map((runId) => readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, runId, transactionId)));
901
+ const invalidRun = runs.some((run, index) => {
902
+ const expectedRunId = runIds[index];
903
+ return !run || run.$id !== expectedRunId || run.runId !== expectedRunId || run.ownerId !== ownerId || run.agentId !== agentId || run.historyVersion !== CONVERSATION_HISTORY_VERSION;
904
+ });
905
+ if (invalidRun) {
906
+ throw new ConversationHistoryNotFoundError("Run \u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237");
907
+ }
908
+ const batchReadAt = Date.now();
909
+ const states = runs.map((run, index) => ({
910
+ runId: runIds[index],
911
+ isRead: true,
912
+ readAt: readOptionalTimestamp(run?.readAt) ?? batchReadAt,
913
+ threadId: requireRowString(run, "threadId"),
914
+ newlyRead: readOptionalTimestamp(run?.readAt) === void 0
915
+ }));
916
+ await Promise.all(states.map((state, index) => {
917
+ if (readOptionalTimestamp(runs[index]?.readAt) !== void 0) {
918
+ return Promise.resolve();
919
+ }
920
+ return databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, state.runId, { readAt: new Date(state.readAt).toISOString() }, void 0, transactionId);
921
+ }));
922
+ await databases.updateTransaction(transactionId, true, false);
923
+ return states;
924
+ } catch (error) {
925
+ await rollbackTransactionQuietly(databases, transactionId);
926
+ throw error;
927
+ }
928
+ },
877
929
  async setRunBlocked(params) {
878
930
  const existing = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, params.runId);
879
931
  if (!existing) {
@@ -1018,6 +1070,7 @@ async function readConversationRun(databases, config, row) {
1018
1070
  ]);
1019
1071
  const chunkRows = chunks.documents;
1020
1072
  const status = readRunStatus(row.status);
1073
+ const readAt = readOptionalTimestamp(row.readAt);
1021
1074
  const expectedChunks = readNonNegativeInteger2(row.totalChunks);
1022
1075
  if (chunks.total > chunkRows.length || status !== "running" && expectedChunks > chunkRows.length) {
1023
1076
  throw new Error(`run ${runId} \u5206\u7247\u4E0D\u5B8C\u6574\uFF0C\u5DF2\u8BFB\u53D6 ${chunkRows.length} / ${Math.max(chunks.total, expectedChunks)}`);
@@ -1030,6 +1083,8 @@ async function readConversationRun(databases, config, row) {
1030
1083
  status,
1031
1084
  startedAt: readNonNegativeInteger2(row.startedAt),
1032
1085
  completedAt: row.completedAt === null || row.completedAt === void 0 ? void 0 : readNonNegativeInteger2(row.completedAt),
1086
+ isRead: readAt !== void 0,
1087
+ readAt,
1033
1088
  blockedQuestion: row.blockedQuestion === true,
1034
1089
  blockedAnswer: row.blockedAnswer === true,
1035
1090
  questionReplacement: readNonEmptyString(row.questionReplacement),
@@ -1123,15 +1178,21 @@ async function upsertDocument(databases, databaseId, tableId, documentId, data,
1123
1178
  await databases.createDocument(databaseId, tableId, documentId, data, permissions);
1124
1179
  }
1125
1180
  }
1126
- async function readDocument(databases, databaseId, tableId, documentId) {
1181
+ async function readDocument(databases, databaseId, tableId, documentId, transactionId) {
1127
1182
  try {
1128
- return await databases.getDocument(databaseId, tableId, documentId);
1183
+ return await databases.getDocument(databaseId, tableId, documentId, void 0, transactionId);
1129
1184
  } catch (error) {
1130
1185
  if (isNotFound2(error))
1131
1186
  return void 0;
1132
1187
  throw error;
1133
1188
  }
1134
1189
  }
1190
+ async function rollbackTransactionQuietly(databases, transactionId) {
1191
+ try {
1192
+ await databases.updateTransaction(transactionId, false, true);
1193
+ } catch {
1194
+ }
1195
+ }
1135
1196
  function deriveConversationCopy(request) {
1136
1197
  const content = request.messages.at(-1)?.content;
1137
1198
  let visibleText = "";
@@ -1180,6 +1241,18 @@ function readStringArray(value) {
1180
1241
  function readNonNegativeInteger2(value) {
1181
1242
  return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : 0;
1182
1243
  }
1244
+ function readOptionalNonNegativeInteger(value) {
1245
+ return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : void 0;
1246
+ }
1247
+ function readOptionalTimestamp(value) {
1248
+ const integer = readOptionalNonNegativeInteger(value);
1249
+ if (integer !== void 0)
1250
+ return integer;
1251
+ if (typeof value !== "string" || !value.trim())
1252
+ return void 0;
1253
+ const timestamp = Date.parse(value);
1254
+ return Number.isSafeInteger(timestamp) && timestamp >= 0 ? timestamp : void 0;
1255
+ }
1183
1256
  function readNonEmptyString(value) {
1184
1257
  return typeof value === "string" && value.trim() ? value : void 0;
1185
1258
  }
@@ -1678,9 +1751,128 @@ function historyError(status, code, message) {
1678
1751
  return { status, body: { error: { code, message, status } } };
1679
1752
  }
1680
1753
 
1754
+ // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/readStatus.js
1755
+ async function runMarkConversationRunsRead(method, bodyJSON, env, deps, logCtx, ownerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId) {
1756
+ if (method !== "POST") {
1757
+ return readStatusError(405, "method_not_allowed", "\u4EC5\u652F\u6301 POST");
1758
+ }
1759
+ let request;
1760
+ try {
1761
+ request = parseMarkConversationRunsReadRequest(bodyJSON);
1762
+ } catch (error) {
1763
+ const message = error instanceof ConversationControlValidationError ? error.issues.join("; ") : "\u8BF7\u6C42\u4F53\u65E0\u6CD5\u89E3\u6790\u4E3A MarkConversationRunsReadRequest";
1764
+ return readStatusError(400, "control_protocol_invalid", message);
1765
+ }
1766
+ const protocol = deps?.protocol ?? getBakedProtocol();
1767
+ let store = deps?.store;
1768
+ if (!store) {
1769
+ try {
1770
+ const handle = createAppBaseClient(env, logCtx, appwriteApiKey);
1771
+ store = createConversationHistoryStore(handle.databases, resolveConversationHistoryStorage(env), ownerId);
1772
+ } catch (error) {
1773
+ logCtx?.error?.("[readStatus] \u5B58\u50A8\u914D\u7F6E\u5931\u8D25:", error);
1774
+ return readStatusError(500, "read_status_storage_unconfigured", error instanceof Error ? error.message : "\u5DF2\u8BFB\u72B6\u6001\u5B58\u50A8\u672A\u914D\u7F6E");
1775
+ }
1776
+ }
1777
+ try {
1778
+ const runs = await store.markRunsRead(protocol.agentId, request.runIds);
1779
+ try {
1780
+ const newlyReadRuns = runs.filter((run) => run.newlyRead === true);
1781
+ if (deps?.publishReadHooks) {
1782
+ if (newlyReadRuns.length > 0) {
1783
+ await deps.publishReadHooks(newlyReadRuns);
1784
+ }
1785
+ } else {
1786
+ await publishConversationRunReadHooks({
1787
+ protocol,
1788
+ runs: newlyReadRuns,
1789
+ env,
1790
+ ownerId,
1791
+ envSelector,
1792
+ traceId,
1793
+ gatewayAuth,
1794
+ temporaryFrontendAppId,
1795
+ logCtx
1796
+ });
1797
+ }
1798
+ } catch (error) {
1799
+ logCtx?.error?.("[readStatus] RUN_READ Hook \u6295\u9012\u5931\u8D25:", error);
1800
+ }
1801
+ const response = {
1802
+ operation: MARK_CONVERSATION_RUNS_READ_OPERATION,
1803
+ runs: runs.map(({ runId, isRead, readAt }) => ({
1804
+ runId,
1805
+ isRead,
1806
+ readAt
1807
+ }))
1808
+ };
1809
+ return { status: 200, body: response };
1810
+ } catch (error) {
1811
+ logCtx?.error?.("[readStatus] \u8BF7\u6C42\u6267\u884C\u5931\u8D25:", error);
1812
+ if (error instanceof ConversationHistoryNotFoundError) {
1813
+ return readStatusError(404, "conversation_run_not_found", "Run \u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237");
1814
+ }
1815
+ return readStatusError(500, "mark_runs_read_failed", error instanceof Error ? error.message : "\u6279\u91CF\u6807\u8BB0\u5DF2\u8BFB\u5931\u8D25");
1816
+ }
1817
+ }
1818
+ async function publishConversationRunReadHooks(input) {
1819
+ const newlyReadRuns = input.runs.filter((run) => run.newlyRead === true);
1820
+ if (newlyReadRuns.length === 0 || input.gatewayAuth?.mode !== "user-token") {
1821
+ return;
1822
+ }
1823
+ const { eventBaseUrl } = resolveLinkqueEndpoints(input.env, input.envSelector);
1824
+ const debugLog = input.logCtx?.log ? (line) => input.logCtx?.log?.("[readStatus]", line) : void 0;
1825
+ const plugin = new LinkquegwEventPlugin({
1826
+ getUserTokenAuthorizationHeader: async () => input.gatewayAuth?.authorizationHeader ?? "",
1827
+ agentId: input.protocol.agentId,
1828
+ ...input.temporaryFrontendAppId !== void 0 && {
1829
+ temporaryFrontendAppId: input.temporaryFrontendAppId
1830
+ },
1831
+ ...eventBaseUrl ? { baseUrl: eventBaseUrl } : {},
1832
+ ...debugLog ? { debugLog } : {},
1833
+ ...input.fetchImpl ? { fetchImpl: input.fetchImpl } : {}
1834
+ });
1835
+ const effectiveProtocol = structuredClone(input.protocol);
1836
+ plugin.modifyAgentConfig(effectiveProtocol);
1837
+ const resources = normalizeHookResources(effectiveProtocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.HOOK && resource.config.stage === EHookStage.RUN_READ));
1838
+ const hookExecutor = plugin.hookExecutorList[0];
1839
+ if (resources.length === 0 || !hookExecutor)
1840
+ return;
1841
+ await Promise.all(newlyReadRuns.map(async (run) => {
1842
+ const commonParams = {
1843
+ agentId: input.protocol.agentId,
1844
+ runId: run.runId,
1845
+ conversationId: run.threadId,
1846
+ threadId: run.threadId,
1847
+ ...input.ownerId !== void 0 && { userId: input.ownerId },
1848
+ ...input.traceId !== void 0 && { traceId: input.traceId }
1849
+ };
1850
+ const sideEffectRunner = new SideEffectRunner({
1851
+ attribution: {
1852
+ runId: run.runId,
1853
+ agentId: input.protocol.agentId,
1854
+ ...input.traceId !== void 0 && { traceId: input.traceId }
1855
+ },
1856
+ ...debugLog ? { debugLog } : {}
1857
+ });
1858
+ const dispatcher = new HookDispatcher(resources, {
1859
+ hookExecutor,
1860
+ sideEffectRunner,
1861
+ ...debugLog ? { debugLog } : {}
1862
+ });
1863
+ await dispatcher.dispatch(EHookStage.RUN_READ, commonParams, {
1864
+ readAt: run.readAt
1865
+ });
1866
+ await sideEffectRunner.drain({ timeoutMs: DEFAULT_HOOK_DRAIN_BUDGET_MS });
1867
+ }));
1868
+ }
1869
+ function readStatusError(status, code, message) {
1870
+ return { status, body: { error: { code, message, status } } };
1871
+ }
1872
+
1681
1873
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/homeData.js
1682
1874
  var HOME_DATA_REQUEST_OPERATION = "homeData.request";
1683
- async function runHomeData(method, body, userId, deps = {}, env = process.env, envSelector = "PROD", gatewayAuth, logCtx) {
1875
+ async function runHomeData(method, body, userId, deps = {}, env = process.env, envSelector = "PROD", gatewayAuth, logCtx, traceId) {
1684
1876
  if (method.toUpperCase() !== "POST") {
1685
1877
  return jsonError(405, "method_not_allowed", "\u4EC5\u652F\u6301 POST");
1686
1878
  }
@@ -1688,6 +1880,8 @@ async function runHomeData(method, body, userId, deps = {}, env = process.env, e
1688
1880
  return jsonError(401, "authentication_required", "\u7F3A\u5C11 Appwrite \u8BA4\u8BC1\u7528\u6237");
1689
1881
  }
1690
1882
  const protocol = deps.protocol ?? getBakedProtocol();
1883
+ let mcpTraceId;
1884
+ const debugLog = createHomeDataDebugLog(env, logCtx, traceId, () => mcpTraceId);
1691
1885
  let provider = deps.mcpServerProvider;
1692
1886
  if (!provider) {
1693
1887
  let resolvedAuth;
@@ -1702,17 +1896,114 @@ async function runHomeData(method, body, userId, deps = {}, env = process.env, e
1702
1896
  agentId: protocol.agentId,
1703
1897
  ...mcpSignEndpoint ? { signEndpoint: mcpSignEndpoint } : {}
1704
1898
  }),
1705
- getAuthorizationHeader: async () => resolvedAuth.authorizationHeader
1899
+ getAuthorizationHeader: async () => resolvedAuth.authorizationHeader,
1900
+ ...debugLog ? {
1901
+ onTraceId: (info) => {
1902
+ mcpTraceId = info.traceId;
1903
+ debugLog("mcp-trace", {});
1904
+ }
1905
+ } : {}
1706
1906
  });
1707
1907
  }
1908
+ if (debugLog)
1909
+ provider = withHomeDataDiagnostics(provider, debugLog);
1708
1910
  const response = await executeHomeData({
1709
1911
  request: body,
1710
1912
  protocol,
1711
1913
  userId,
1712
1914
  mcpServerProvider: provider
1713
1915
  });
1916
+ debugLog?.("response", response.ok ? { ok: true } : { ok: false, errorCode: response.error.code });
1714
1917
  return { status: 200, body: response };
1715
1918
  }
1919
+ function createHomeDataDebugLog(env, logCtx, traceId, getMcpTraceId) {
1920
+ if (!isDebugLogLevel(env) || !logCtx?.log)
1921
+ return void 0;
1922
+ return (event, fields) => {
1923
+ logCtx.log?.("[home-data][debug]", JSON.stringify({
1924
+ event,
1925
+ traceId: traceId ?? null,
1926
+ mcpTraceId: getMcpTraceId() ?? null,
1927
+ ...fields
1928
+ }));
1929
+ };
1930
+ }
1931
+ function withHomeDataDiagnostics(provider, debugLog) {
1932
+ return {
1933
+ async servers(resources) {
1934
+ const servers = await provider.servers(resources);
1935
+ return servers.map((server) => wrapMcpServer(server, debugLog));
1936
+ }
1937
+ };
1938
+ }
1939
+ function wrapMcpServer(server, debugLog) {
1940
+ return {
1941
+ resourceId: server.resourceId,
1942
+ serverName: server.serverName,
1943
+ listTools: () => server.listTools(),
1944
+ async callTool(name, args, signal) {
1945
+ debugLog("mcp-call-start", {
1946
+ mcpName: server.serverName,
1947
+ toolName: name
1948
+ });
1949
+ try {
1950
+ const result = await server.callTool(name, args, signal);
1951
+ debugLog("mcp-call-result", {
1952
+ mcpName: server.serverName,
1953
+ toolName: name,
1954
+ ...summarizeMcpResult(result)
1955
+ });
1956
+ return result;
1957
+ } catch (error) {
1958
+ debugLog("mcp-call-error", {
1959
+ mcpName: server.serverName,
1960
+ toolName: name,
1961
+ errorName: error instanceof Error ? error.name : valueType(error),
1962
+ errorMessage: sanitizeDiagnosticText(error instanceof Error ? error.message : String(error))
1963
+ });
1964
+ throw error;
1965
+ }
1966
+ },
1967
+ ...server.close ? { close: () => server.close() } : {}
1968
+ };
1969
+ }
1970
+ function summarizeMcpResult(result) {
1971
+ const object = isRecord(result) ? result : void 0;
1972
+ const content = Array.isArray(object?.content) ? object.content : void 0;
1973
+ const summary = {
1974
+ resultType: valueType(result),
1975
+ resultKeys: objectKeys(object),
1976
+ structuredContentType: valueType(object?.structuredContent),
1977
+ structuredContentKeys: objectKeys(isRecord(object?.structuredContent) ? object.structuredContent : void 0),
1978
+ contentCount: content?.length ?? 0,
1979
+ contentTypes: content?.map((item) => isRecord(item) && typeof item.type === "string" ? item.type : valueType(item))
1980
+ };
1981
+ if (typeof object?.isError === "boolean")
1982
+ summary.isError = object.isError;
1983
+ if (object?.isError === true) {
1984
+ const errorText = content?.find((item) => isRecord(item) && item.type === "text" && typeof item.text === "string");
1985
+ if (isRecord(errorText) && typeof errorText.text === "string") {
1986
+ summary.errorMessage = sanitizeDiagnosticText(errorText.text);
1987
+ }
1988
+ }
1989
+ return summary;
1990
+ }
1991
+ function isRecord(value) {
1992
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1993
+ }
1994
+ function objectKeys(value) {
1995
+ return value ? Object.keys(value).slice(0, 20) : [];
1996
+ }
1997
+ function valueType(value) {
1998
+ if (value === null)
1999
+ return "null";
2000
+ if (Array.isArray(value))
2001
+ return "array";
2002
+ return typeof value;
2003
+ }
2004
+ function sanitizeDiagnosticText(value) {
2005
+ return value.replace(/\s+/gu, " ").replace(/(bearer\s+)[^\s,;]+/giu, "$1<redacted>").replace(/((?:authorization|api[_-]?key|token|secret)\s*[=:]\s*)[^\s,;]+/giu, "$1<redacted>").slice(0, 500);
2006
+ }
1716
2007
 
1717
2008
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/a2uiAction.js
1718
2009
  var A2UI_ACTION_EXECUTE_OPERATION = "a2uiAction.execute";
@@ -1743,8 +2034,16 @@ async function runA2UIAction(method, body, userId, deps = {}, env = process.env,
1743
2034
  const begin = await store.begin(createPaymentInvocation(userId, request));
1744
2035
  if (begin.kind === "existing") {
1745
2036
  const current = begin.invocation;
1746
- if (current.tradeNO && ["trade-created", "payment-reported", "verified-paid", "verified-unpaid"].includes(current.status)) {
1747
- return { status: 200, body: success(current.invocationId, current.tradeNO) };
2037
+ if (current.tradeNO && [
2038
+ "trade-created",
2039
+ "payment-reported",
2040
+ "verified-paid",
2041
+ "verified-unpaid"
2042
+ ].includes(current.status)) {
2043
+ return {
2044
+ status: 200,
2045
+ body: success(current.invocationId, current.tradeNO)
2046
+ };
1748
2047
  }
1749
2048
  if (current.status === "executing") {
1750
2049
  return paymentFailure(409, "ACTION_IN_PROGRESS", "\u652F\u4ED8\u52A8\u4F5C\u6B63\u5728\u5904\u7406\u4E2D", true);
@@ -1775,7 +2074,10 @@ async function runA2UIAction(method, body, userId, deps = {}, env = process.env,
1775
2074
  await store.update(invocationId, {
1776
2075
  status: response.error.code === "EXECUTION_FAILED" ? "uncertain" : "failed-before-execute"
1777
2076
  });
1778
- return { status: response.error.code === "EXECUTION_FAILED" ? 502 : 400, body: response };
2077
+ return {
2078
+ status: response.error.code === "EXECUTION_FAILED" ? 502 : 400,
2079
+ body: response
2080
+ };
1779
2081
  }
1780
2082
  function resolveStore(env, appwriteApiKey) {
1781
2083
  if (!env.A2UI_ACTION_DATABASE_ID || !env.A2UI_ACTION_TABLE_ID)
@@ -1810,7 +2112,7 @@ function errorMessage(error, fallback) {
1810
2112
  }
1811
2113
 
1812
2114
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chatConfig.js
1813
- function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth) {
2115
+ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth, temporaryFrontendAppId) {
1814
2116
  const log = (...a) => logCtx?.log?.("[chat]", ...a);
1815
2117
  const logError = (...a) => logCtx?.error?.("[chat]", ...a);
1816
2118
  const protocol = deps?.protocol ?? getBakedProtocol();
@@ -1888,7 +2190,8 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
1888
2190
  gatewayAgentId: protocol.agentId,
1889
2191
  ...linkqueBaseUrl ? { linkqueBaseUrl } : {},
1890
2192
  ...knowledgeBaseUrl ? { knowledgeBaseUrl } : {},
1891
- ...eventBaseUrl ? { eventBaseUrl } : {}
2193
+ ...eventBaseUrl ? { eventBaseUrl } : {},
2194
+ ...temporaryFrontendAppId !== void 0 && { temporaryFrontendAppId }
1892
2195
  }, logCtx);
1893
2196
  return {
1894
2197
  auth: resolved.auth,
@@ -2225,7 +2528,7 @@ function shouldFlushConversationEvent(event) {
2225
2528
  }
2226
2529
 
2227
2530
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js
2228
- async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth) {
2531
+ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId) {
2229
2532
  const log = (...args) => logCtx?.log?.("[chat]", ...args);
2230
2533
  const logError = (...args) => logCtx?.error?.("[chat]", ...args);
2231
2534
  const guarded = guardChatRequest(method, bodyJSON, logCtx);
@@ -2233,7 +2536,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
2233
2536
  return guarded;
2234
2537
  let request = guarded;
2235
2538
  const isPresentationRun = request.executionScope === "presentation";
2236
- const cfg = resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth);
2539
+ const cfg = resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth, temporaryFrontendAppId);
2237
2540
  if ("status" in cfg)
2238
2541
  return cfg;
2239
2542
  const leaseOwnerId = randomUUID3();
@@ -2428,7 +2731,10 @@ async function preparePaymentResultRequest(request, cfg, ownerId, logCtx) {
2428
2731
  const store = cfg.paymentActionStore;
2429
2732
  if (!store) {
2430
2733
  return enrichPaymentRequest(request, payload, {
2431
- verificationError: { code: "PAYMENT_VERIFICATION_UNAVAILABLE", message: "\u652F\u4ED8\u72B6\u6001\u6682\u672A\u786E\u8BA4" }
2734
+ verificationError: {
2735
+ code: "PAYMENT_VERIFICATION_UNAVAILABLE",
2736
+ message: "\u652F\u4ED8\u72B6\u6001\u6682\u672A\u786E\u8BA4"
2737
+ }
2432
2738
  });
2433
2739
  }
2434
2740
  const invocation = await store.get(payload.actionInvocationId);
@@ -2436,11 +2742,16 @@ async function preparePaymentResultRequest(request, cfg, ownerId, logCtx) {
2436
2742
  return jsonError(403, "payment_result_forbidden", "\u652F\u4ED8\u7ED3\u679C\u4E0E\u5DF2\u521B\u5EFA\u7684\u4EA4\u6613\u4E0D\u5339\u914D");
2437
2743
  }
2438
2744
  if (invocation.verification) {
2439
- return enrichPaymentRequest(request, payload, { verification: invocation.verification });
2745
+ return enrichPaymentRequest(request, payload, {
2746
+ verification: invocation.verification
2747
+ });
2440
2748
  }
2441
2749
  if (invocation.status === "payment-reported") {
2442
2750
  return enrichPaymentRequest(request, payload, {
2443
- verificationError: { code: "PAYMENT_VERIFICATION_IN_PROGRESS", message: "\u652F\u4ED8\u72B6\u6001\u6682\u672A\u786E\u8BA4" }
2751
+ verificationError: {
2752
+ code: "PAYMENT_VERIFICATION_IN_PROGRESS",
2753
+ message: "\u652F\u4ED8\u72B6\u6001\u6682\u672A\u786E\u8BA4"
2754
+ }
2444
2755
  });
2445
2756
  }
2446
2757
  try {
@@ -2471,9 +2782,17 @@ async function preparePaymentResultRequest(request, cfg, ownerId, logCtx) {
2471
2782
  });
2472
2783
  return enrichPaymentRequest(request, payload, { verification });
2473
2784
  } catch {
2785
+ try {
2786
+ await store.update(invocation.invocationId, { status: "trade-created" });
2787
+ } catch {
2788
+ logCtx?.error?.("[chat] \u652F\u4ED8\u6838\u9A8C\u5931\u8D25\u540E\u7684 invocation \u72B6\u6001\u6062\u590D\u5931\u8D25");
2789
+ }
2474
2790
  logCtx?.error?.("[chat] \u652F\u4ED8\u7ED3\u679C\u670D\u52A1\u7AEF\u6838\u9A8C\u5931\u8D25", "PAYMENT_VERIFICATION_FAILED");
2475
2791
  return enrichPaymentRequest(request, payload, {
2476
- verificationError: { code: "PAYMENT_VERIFICATION_FAILED", message: "\u652F\u4ED8\u72B6\u6001\u6682\u672A\u786E\u8BA4" }
2792
+ verificationError: {
2793
+ code: "PAYMENT_VERIFICATION_FAILED",
2794
+ message: "\u652F\u4ED8\u72B6\u6001\u6682\u672A\u786E\u8BA4"
2795
+ }
2477
2796
  });
2478
2797
  }
2479
2798
  }
@@ -2553,11 +2872,18 @@ function waitForCancellationPoll(delayMs, signal) {
2553
2872
  }
2554
2873
  });
2555
2874
  }
2556
- async function runGateway(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth) {
2875
+ async function runGateway(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId) {
2557
2876
  const operation = readOperation(bodyJSON);
2558
2877
  if (operation === "cancelConversationRun") {
2559
2878
  return runCancelConversation(method, bodyJSON, env, deps ? { protocol: deps.protocol, store: deps.historyStore } : void 0, logCtx, historyOwnerId, appwriteApiKey);
2560
2879
  }
2880
+ if (operation === MARK_CONVERSATION_RUNS_READ_OPERATION) {
2881
+ return runMarkConversationRunsRead(method, bodyJSON, env, deps ? {
2882
+ protocol: deps.protocol,
2883
+ store: deps.historyStore,
2884
+ publishReadHooks: deps.readStatusHookPublisher
2885
+ } : void 0, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId);
2886
+ }
2561
2887
  if (operation === ASR_CREATE_CREDENTIAL_OPERATION) {
2562
2888
  const agentId = deps?.protocol?.agentId ?? getBakedProtocol().agentId;
2563
2889
  return runAsrCredential(method, env, historyOwnerId, agentId, void 0, envSelector, gatewayAuth, logCtx);
@@ -2571,7 +2897,7 @@ async function runGateway(method, bodyJSON, env, deps, logCtx, historyOwnerId, a
2571
2897
  return runHomeData(method, request, historyOwnerId, {
2572
2898
  ...deps?.protocol ? { protocol: deps.protocol } : {},
2573
2899
  ...deps?.mcpServerProvider ? { mcpServerProvider: deps.mcpServerProvider } : {}
2574
- }, env, envSelector === "PRE" ? "PRE" : "PROD");
2900
+ }, env, envSelector === "PRE" ? "PRE" : "PROD", gatewayAuth, logCtx, traceId);
2575
2901
  }
2576
2902
  if (operation === A2UI_ACTION_EXECUTE_OPERATION) {
2577
2903
  const request = readOperationPayload(bodyJSON);
@@ -2590,7 +2916,7 @@ async function runGateway(method, bodyJSON, env, deps, logCtx, historyOwnerId, a
2590
2916
  if (operation) {
2591
2917
  return jsonError(400, "operation_unsupported", `\u4E0D\u652F\u6301\u7684 operation: ${operation}`);
2592
2918
  }
2593
- return runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth);
2919
+ return runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId);
2594
2920
  }
2595
2921
  async function chat(ctx) {
2596
2922
  let result;
@@ -2600,11 +2926,12 @@ async function chat(ctx) {
2600
2926
  const appwriteApiKey = readAppwriteApiKey(ctx.req.headers);
2601
2927
  const envSelector = readEnvSelector(ctx.req.headers);
2602
2928
  const traceId = readTraceId(ctx.req.headers);
2929
+ const temporaryFrontendAppId = readTemporaryFrontendAppId(ctx.req.headers);
2603
2930
  const gatewayAuth = historyOwnerId ? resolveLinkqueGatewayAuth(ctx.req.headers, process.env, {
2604
2931
  log: ctx.log,
2605
2932
  error: ctx.error
2606
2933
  }) : void 0;
2607
- result = historyOwnerId ? await runGateway(ctx.req.method, bodyJSON, process.env, void 0, { log: ctx.log, error: ctx.error }, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth) : jsonError(401, "authentication_required", "\u7F3A\u5C11 Appwrite \u8BA4\u8BC1\u7528\u6237");
2934
+ result = historyOwnerId ? await runGateway(ctx.req.method, bodyJSON, process.env, void 0, { log: ctx.log, error: ctx.error }, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId) : jsonError(401, "authentication_required", "\u7F3A\u5C11 Appwrite \u8BA4\u8BC1\u7528\u6237");
2608
2935
  } catch (err) {
2609
2936
  ctx.error?.(err);
2610
2937
  result = err instanceof LinkqueGatewayAuthError || err instanceof LinkqueGatewayAuthUnconfiguredError ? jsonError(err.status, err.code, err.message) : {
@@ -3,7 +3,7 @@ import {
3
3
  runClientCapability,
4
4
  runClientCapabilityCleanup,
5
5
  runClientCapabilityResult
6
- } from "../../chunk-NRTXRI33.js";
6
+ } from "../../chunk-F3IESVDW.js";
7
7
  import "../../chunk-MKS245OU.js";
8
8
  import "../../chunk-YDKZZ6EH.js";
9
9
  import "../../chunk-2NGJGNYB.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  getBakedProtocol,
3
3
  setBakedProtocol
4
- } from "../chunk-HPOFEAMP.js";
4
+ } from "../chunk-7YMZ4CJ5.js";
5
5
  import "../chunk-XUFLSZM4.js";
6
6
  import "../chunk-I64V3ICJ.js";
7
7
  import "../chunk-6MHDOBWO.js";