nolo-cli 0.1.30 → 0.1.31

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 (308) hide show
  1. package/agent-runtime/agentRecordConfig.ts +0 -2
  2. package/agent-runtime/hostAdapter.ts +0 -1
  3. package/agent-runtime/hostRuntimeCapabilities.ts +7 -0
  4. package/agent-runtime/hostRuntimeConfig.ts +86 -0
  5. package/agent-runtime/index.ts +13 -0
  6. package/agent-runtime/localToolPolicy.ts +13 -6
  7. package/agent-runtime/localWorkspaceTools.ts +333 -30
  8. package/agent-runtime/platformChatProvider.ts +4 -1
  9. package/agent-runtime/runtimeToolPolicy.ts +32 -47
  10. package/agent-runtime/shellCommandPolicy.ts +117 -0
  11. package/agent-runtime/toolGate.ts +38 -0
  12. package/agentRecordCommands.ts +1 -1
  13. package/agentRecordHelpers.ts +35 -20
  14. package/agentRunParsing.ts +18 -5
  15. package/agentRuntimeLocal.ts +10 -0
  16. package/ai/agent/agentRunDialogLineage.ts +56 -0
  17. package/ai/agent/agentSlice.ts +45 -10
  18. package/ai/agent/avatarUtils.ts +1 -1
  19. package/ai/agent/buildSystemPrompt.ts +1 -2
  20. package/ai/agent/cliExecutor.ts +330 -19
  21. package/ai/agent/createAgentSchema.ts +22 -0
  22. package/ai/agent/hooks/fetchPublicAgents.ts +14 -39
  23. package/ai/agent/hooks/usePublicAgents.ts +90 -192
  24. package/ai/agent/publicAgentCatalog.ts +359 -0
  25. package/ai/agent/publicAgentIdentity.ts +76 -0
  26. package/ai/agent/server/fetchPublicAgents.ts +21 -46
  27. package/ai/agent/serverOrigin.ts +7 -0
  28. package/ai/agent/streamAgentChatTurn.ts +23 -21
  29. package/ai/agent/streamAgentChatTurnUtils.ts +292 -6
  30. package/ai/agent/types.ts +2 -0
  31. package/ai/agent/web/agentDisplayUtils.ts +171 -0
  32. package/ai/agent/web/useAgentModelAvatarComponent.ts +32 -0
  33. package/ai/ai.locale.ts +8 -0
  34. package/ai/chat/sendOpenAICompletionsRequest.native.ts +15 -0
  35. package/ai/chat/sendOpenAICompletionsRequest.ts +93 -1
  36. package/ai/chat/sendOpenAIResponseRequest.ts +86 -9
  37. package/ai/chat/updateTotalUsage.ts +7 -0
  38. package/ai/llm/deepinfra.ts +30 -15
  39. package/ai/llm/mistral.ts +3 -4
  40. package/ai/llm/providers.ts +2 -0
  41. package/ai/llm/types.ts +15 -0
  42. package/ai/memory/capture.ts +3 -3
  43. package/ai/memory/consolidate.ts +2 -2
  44. package/ai/memory/delete.ts +4 -3
  45. package/ai/memory/query.ts +3 -3
  46. package/ai/memory/remember.ts +2 -2
  47. package/ai/memory/store.ts +3 -3
  48. package/ai/memory/storeShared.ts +3 -2
  49. package/ai/policy/commercialMultiplier.ts +16 -0
  50. package/ai/token/billingAdminAuditEvent.ts +68 -0
  51. package/ai/token/billingAdminAuditEventWriter.ts +41 -0
  52. package/ai/token/billingAnomaly.ts +90 -0
  53. package/ai/token/billingAnomalyLifecycle.ts +54 -0
  54. package/ai/token/billingAnomalyLifecycleWriter.ts +44 -0
  55. package/ai/token/billingAnomalyWriter.ts +41 -0
  56. package/ai/token/calculatePrice.ts +3 -2
  57. package/ai/token/deepinfraReconciliation.ts +153 -0
  58. package/ai/token/deepinfraRequestIdQuery.ts +92 -0
  59. package/ai/token/externalToolCost.ts +54 -41
  60. package/ai/token/missingUsageEstimate.ts +12 -3
  61. package/ai/token/normalizeUsage.ts +45 -5
  62. package/ai/token/openaiReconciliation.ts +188 -0
  63. package/ai/token/providerBillableEvent.ts +84 -0
  64. package/ai/token/providerBillableEventWriter.ts +36 -0
  65. package/ai/token/providerBillingAnomalyDrilldown.ts +308 -0
  66. package/ai/token/providerBillingDrilldown.ts +361 -0
  67. package/ai/token/providerBillingHealthReport.ts +366 -0
  68. package/ai/token/providerCall.ts +144 -0
  69. package/ai/token/providerCallSweeper.ts +168 -0
  70. package/ai/token/providerCallWriter.ts +33 -0
  71. package/ai/token/providerCredential.ts +89 -0
  72. package/ai/token/providerCredentialAnomaly.ts +154 -0
  73. package/ai/token/providerCredentialLifecycle.ts +59 -0
  74. package/ai/token/providerCredentialLifecycleWriter.ts +44 -0
  75. package/ai/token/providerCredentialRegistry.ts +83 -0
  76. package/ai/token/providerCredentialRegistryCommand.ts +97 -0
  77. package/ai/token/providerCredentialRegistryList.ts +124 -0
  78. package/ai/token/providerCredentialRegistryResolver.ts +150 -0
  79. package/ai/token/providerCredentialRegistryWriter.ts +41 -0
  80. package/ai/token/providerCredentialRotationCommand.ts +102 -0
  81. package/ai/token/providerCredentialRuntime.ts +56 -0
  82. package/ai/token/providerDispatchIntent.ts +67 -0
  83. package/ai/token/providerDispatchIntentWriter.ts +36 -0
  84. package/ai/token/providerGateway.ts +260 -0
  85. package/ai/token/providerReconciliation.ts +148 -0
  86. package/ai/token/providerReconciliationLocal.ts +97 -0
  87. package/ai/token/providerReconciliationRunner.ts +165 -0
  88. package/ai/token/providerReconciliationWriter.ts +41 -0
  89. package/ai/token/ratingResult.ts +202 -0
  90. package/ai/token/ratingResultWriter.ts +33 -0
  91. package/ai/token/serverDialogProjection.ts +5 -3
  92. package/ai/token/serverTokenWriter.ts +11 -3
  93. package/ai/token/types.ts +10 -0
  94. package/ai/tools/agent/callAgentTool.ts +3 -4
  95. package/ai/tools/agent/presets/appBuilderPreset.ts +5 -7
  96. package/ai/tools/agent/runStreamingAgentTool.ts +1 -2
  97. package/ai/tools/agent/streamParallelAgentsTool.ts +2 -3
  98. package/ai/tools/readXPostTool.ts +1 -5
  99. package/app/admin/adminPages.ts +9 -0
  100. package/app/i18n/i18n.config.ts +5 -0
  101. package/app/i18n/translations/pricing.locale.ts +397 -0
  102. package/app/utils/desktopAgentRuntimeStatusClient.ts +5 -4
  103. package/app/utils/desktopAgentRuntimeTurnClient.ts +4 -1
  104. package/app/utils/imageUtils.ts +64 -34
  105. package/auth/adminPermissions.ts +18 -0
  106. package/auth/authSlice.ts +26 -12
  107. package/auth/hooks/useFetchUsers.ts +3 -0
  108. package/auth/routes.ts +46 -0
  109. package/auth/server/accessActivity.ts +4 -3
  110. package/auth/server/adminPermissions.ts +43 -0
  111. package/auth/server/adminUsageReport.ts +375 -0
  112. package/auth/server/billingAnomalies.ts +235 -0
  113. package/auth/server/billingUsageReport.ts +41 -2
  114. package/auth/server/creatorEarningCreditConversion.ts +10 -2
  115. package/auth/server/deduct.ts +14 -7
  116. package/auth/server/delete.ts +10 -2
  117. package/auth/server/disable.ts +4 -3
  118. package/auth/server/emailAutomation.ts +7 -5
  119. package/auth/server/emailDbConfig.ts +4 -2
  120. package/auth/server/emailDelivery.ts +24 -20
  121. package/auth/server/emailDeliveryGuards.ts +10 -7
  122. package/auth/server/emailPreferences.ts +6 -4
  123. package/auth/server/emailReport.ts +6 -4
  124. package/auth/server/emailRuntimeConfig.ts +3 -3
  125. package/auth/server/emailScenarioNotifications.ts +9 -8
  126. package/auth/server/enable.ts +4 -3
  127. package/auth/server/getRechargeHistory.ts +3 -2
  128. package/auth/server/getUser.ts +3 -2
  129. package/auth/server/gptProAccess.ts +44 -0
  130. package/auth/server/inviteReward.ts +10 -7
  131. package/auth/server/listusers.ts +6 -4
  132. package/auth/server/login.ts +2 -2
  133. package/auth/server/productEntitlements.ts +7 -4
  134. package/auth/server/productPurchase.ts +10 -2
  135. package/auth/server/providerBillingDrilldown.ts +47 -0
  136. package/auth/server/providerBillingHealth.ts +71 -0
  137. package/auth/server/providerCredentials.ts +136 -0
  138. package/auth/server/recharge.ts +14 -8
  139. package/auth/server/revokeSessions.ts +4 -3
  140. package/auth/server/route.ts +77 -0
  141. package/auth/server/sendEmail.ts +5 -4
  142. package/auth/server/signup.ts +10 -3
  143. package/auth/server/token.ts +53 -55
  144. package/auth/server/tokenUsageBilling.ts +18 -7
  145. package/auth/server/usageManagementAccess.ts +43 -0
  146. package/auth/server/usageReport.ts +59 -0
  147. package/auth/types.ts +12 -0
  148. package/auth/utils.ts +24 -22
  149. package/authCommands.ts +36 -2
  150. package/buildPublish.ts +3 -1
  151. package/buildPublishArtifactAssembly.ts +62 -1
  152. package/buildPublishImportAnalysis.ts +21 -16
  153. package/chat/dialog/dialogLaunchScope.ts +32 -0
  154. package/chat/dialog/objectAssistantRegistry.ts +2 -2
  155. package/chat/dialog/useCreateDialog.ts +1 -1
  156. package/chat/hooks/useChatInput.ts +41 -10
  157. package/chat/messages/messageSlice.ts +5 -1
  158. package/chat/messages/pendingAttachmentParts.ts +28 -2
  159. package/chat/messages/sendFirstMessage.ts +76 -79
  160. package/chat/messages/types.ts +9 -0
  161. package/chat/messages/web/streamingMarkdownModel.ts +41 -0
  162. package/chat/messages/web/useStreamingReveal.ts +91 -0
  163. package/chat/web/messageInputAgentUi.ts +94 -6
  164. package/cliEnvHelpers.ts +8 -0
  165. package/cliRuntimeDoctorReport.ts +193 -0
  166. package/client/agentConfigResolver.test.ts +0 -2
  167. package/client/agentRun.test.ts +171 -10
  168. package/client/agentRun.ts +44 -637
  169. package/client/agentRunInput.ts +10 -0
  170. package/client/agentRunLocalExecutor.ts +179 -0
  171. package/client/agentRunServerTransport.ts +394 -0
  172. package/client/agentRunTaskRunRecorder.ts +176 -0
  173. package/client/localRuntimeAdapter.test.ts +236 -9
  174. package/client/localRuntimeAdapter.ts +221 -23
  175. package/client/localToolPolicy.test.ts +28 -4
  176. package/connector-experimental/daemonLauncher.ts +38 -4
  177. package/connectorRunArtifact.ts +34 -10
  178. package/connectorWebSocketTarget.ts +9 -5
  179. package/core/builtinAgents.ts +155 -11
  180. package/create/space/contentLabels.ts +1 -1
  181. package/create/space/contentTypeMeta.ts +3 -2
  182. package/create/space/sidebarVisibleTypes.ts +27 -0
  183. package/create/space/space.locale.ts +76 -4
  184. package/database/actions/agentReadResolution.ts +2 -8
  185. package/database/actions/read.ts +11 -9
  186. package/database/actions/readAndWait.ts +10 -5
  187. package/database/server/agentDelegation.ts +3 -2
  188. package/database/server/authorityStoreConformance.ts +209 -0
  189. package/database/server/authorityStoreTypes.ts +31 -0
  190. package/database/server/coreDataProxy.ts +1 -1
  191. package/database/server/dataHandlers.ts +13 -5
  192. package/database/server/db.ts +15 -34
  193. package/database/server/delete.ts +88 -71
  194. package/database/server/emailRepository.ts +11 -9
  195. package/database/server/fileService.ts +2 -1
  196. package/database/server/legacyServerDb.ts +58 -0
  197. package/database/server/levelAuthorityStore.ts +75 -0
  198. package/database/server/memoryAuthorityStore.ts +133 -0
  199. package/database/server/patch.ts +13 -12
  200. package/database/server/query.ts +3 -2
  201. package/database/server/read.ts +33 -30
  202. package/database/server/resourceAccess.ts +7 -5
  203. package/database/server/serverStoreFactory.ts +124 -0
  204. package/database/server/spaceMemberAuthority.ts +3 -2
  205. package/database/server/storeBatchCompat.ts +37 -0
  206. package/database/server/testAuthorityStore.ts +76 -0
  207. package/database/server/write.ts +29 -27
  208. package/integrations/anthropic/anthropicModels.ts +12 -12
  209. package/integrations/deepseek/models.ts +67 -67
  210. package/integrations/google/models.ts +111 -53
  211. package/integrations/openai/models.ts +22 -22
  212. package/integrations/xai/models.ts +1 -1
  213. package/localRuntimeDb.ts +39 -2
  214. package/machineCommandPrompts.ts +2 -0
  215. package/machineCommands.ts +193 -63
  216. package/machineWsRunDispatch.ts +80 -15
  217. package/machineWsSession.ts +39 -2
  218. package/noloReadBridgePrompt.ts +16 -0
  219. package/package.json +99 -6
  220. package/render/layout/mainLayoutViewMode.ts +25 -0
  221. package/render/page/server/createPage.ts +3 -1
  222. package/render/page/server/handleCreatePage.ts +2 -11
  223. package/runtimeDoctorCommands.ts +15 -66
  224. package/server/api/methods.ts +34 -12
  225. package/server/api/tableHandlers.ts +6 -3
  226. package/server/authenticateToken.ts +47 -2
  227. package/server/billingLedgerRoutes.ts +15 -0
  228. package/server/buildManifest.ts +54 -0
  229. package/server/coreReadiness.ts +34 -25
  230. package/server/coreRuntime.ts +15 -10
  231. package/server/handlers/activityStatsHandler.ts +5 -2
  232. package/server/handlers/agentEmailRegistrationE2EHandler.ts +25 -23
  233. package/server/handlers/agentRun/agentLookup.ts +1 -7
  234. package/server/handlers/agentRun/autonomousRuntime.ts +11 -10
  235. package/server/handlers/agentRun/builtinAgents.ts +12 -88
  236. package/server/handlers/agentRun/continueDialogContext.ts +15 -3
  237. package/server/handlers/agentRun/{inheritedDialogPrompt.ts → conversationReference.ts} +3 -3
  238. package/server/handlers/agentRun/dialogLookup.ts +4 -3
  239. package/server/handlers/agentRun/index.ts +864 -404
  240. package/server/handlers/agentRun/localRuntimeBootstrap.ts +17 -1
  241. package/server/handlers/agentRun/loop.ts +920 -508
  242. package/server/handlers/agentRun/machineConnector.ts +56 -8
  243. package/server/handlers/agentRun/machineRunAudit.ts +3 -2
  244. package/server/handlers/agentRun/modelUsageToolHandlers.ts +13 -10
  245. package/server/handlers/agentRun/requestContext.ts +12 -8
  246. package/server/handlers/agentRun/runtimeExecutionContext.ts +15 -3
  247. package/server/handlers/agentRun/runtimePreparation.ts +26 -24
  248. package/server/handlers/agentRun/runtimeRouting.ts +25 -40
  249. package/server/handlers/agentRun/runtimeSystemMessages.ts +65 -0
  250. package/server/handlers/agentRun/saveDialog.ts +97 -87
  251. package/server/handlers/agentRun/taskRunToolHandler.ts +9 -7
  252. package/server/handlers/agentRun/toolExecutor.ts +42 -78
  253. package/server/handlers/agentRun/types.ts +2 -1
  254. package/server/handlers/appDeployStatusStore.ts +17 -10
  255. package/server/handlers/appDomainHandler.ts +21 -15
  256. package/server/handlers/appLegacyInfraCleanup.ts +5 -2
  257. package/server/handlers/appSandboxHandler.ts +29 -8
  258. package/server/handlers/appSpaceAccess.ts +15 -8
  259. package/server/handlers/chatHandler.ts +22 -2
  260. package/server/handlers/chatUpstreamRetry.ts +225 -2
  261. package/server/handlers/connector/connectorConnectionRegistry.ts +55 -7
  262. package/server/handlers/connector/connectorWebSocket.ts +14 -10
  263. package/server/handlers/desktopAgentRuntimeAdapter.ts +4 -4
  264. package/server/handlers/desktopAgentRuntimeHostCapabilities.ts +25 -0
  265. package/server/handlers/desktopAgentRuntimeReadiness.ts +62 -0
  266. package/server/handlers/desktopAgentRuntimeStatusHandler.ts +38 -30
  267. package/server/handlers/desktopAgentRuntimeTurnHandler.ts +7 -3
  268. package/server/handlers/desktopAgentRuntimeTurnService.ts +39 -45
  269. package/server/handlers/desktopLlamaRuntimeHandler.ts +85 -51
  270. package/server/handlers/desktopUpdaterHandler.ts +132 -24
  271. package/server/handlers/favoriteHandlers.ts +8 -2
  272. package/server/handlers/getDialogBillingHandler.ts +4 -3
  273. package/server/handlers/getTransactionsHandler.ts +5 -2
  274. package/server/handlers/machines/machineBinding.ts +1 -0
  275. package/server/handlers/machines/machineHandlers.ts +0 -14
  276. package/server/handlers/machines/machineInstallAssets.ts +4 -2
  277. package/server/handlers/notificationEmitter.ts +5 -3
  278. package/server/handlers/notificationsHandler.ts +5 -2
  279. package/server/handlers/providerCallsRecentHandler.ts +234 -0
  280. package/server/handlers/providerReconciliationRunHandler.ts +180 -0
  281. package/server/handlers/providerRequestIdsHandler.ts +105 -0
  282. package/server/handlers/tableAccess.ts +6 -2
  283. package/server/handlers/tableToolHandlers.ts +28 -14
  284. package/server/handlers/userSecretsHandler.ts +17 -6
  285. package/server/handlers/versionHandler.ts +9 -4
  286. package/server/handlers/versionStore.ts +18 -10
  287. package/server/html/ssrPreload.ts +5 -3
  288. package/server/payments/crypto/cryptoUsdcBasePaymentProvider.ts +11 -8
  289. package/server/payments/crypto/cryptoUsdcBaseScanner.ts +12 -7
  290. package/server/payments/crypto/cryptoUsdtTronPaymentProvider.ts +11 -8
  291. package/server/payments/crypto/cryptoUsdtTronScanner.ts +9 -7
  292. package/server/payments/waffo/waffoPaymentProvider.ts +12 -9
  293. package/server/runtimeRole.ts +15 -0
  294. package/server/scheduler/scheduledTaskRuntime.ts +4 -2
  295. package/server/scheduler/schedulerService.ts +2 -2
  296. package/server/taskRunBridgeRoutes.ts +8 -5
  297. package/share/server/fetchCommunityShares.ts +1 -1
  298. package/share/server/helpers.ts +19 -17
  299. package/share/server/importShare.ts +9 -13
  300. package/share/server/listCommunityShares.ts +4 -4
  301. package/share/server/purchaseDoc.ts +8 -16
  302. package/share/server/readCommunityShareCover.ts +3 -2
  303. package/share/server/readSharedTable.ts +14 -13
  304. package/share/server/tableReplication.ts +42 -39
  305. package/spaceAttachCommands.ts +135 -0
  306. package/spaceInternalCommandEntries.ts +2 -0
  307. package/ai/agent/runtimeServerBase.ts +0 -37
  308. package/server/handlers/desktopAgentRuntimeHostFacts.ts +0 -40
@@ -1,7 +1,8 @@
1
1
  import { assertSessionTokenVersion } from "../auth/sessionTokenVersion";
2
2
  import { parseToken, verifyToken } from "../auth/token";
3
+ import { NOLO_CLUSTER_SERVERS, normalizeKnownServerOrigin } from "../database/config";
3
4
  import { DB_PREFIX } from "../database/keys";
4
- import serverDb from "../database/server/db";
5
+ import { getServerAuthorityStore } from "../database/server/db";
5
6
  import type { ApiError } from "./api/types";
6
7
 
7
8
  const unauthorized = (message: string): ApiError => ({
@@ -31,10 +32,46 @@ const isOutsideTokenWindow = (payload: any): boolean => {
31
32
  return false;
32
33
  };
33
34
 
35
+ const normalizeServerOrigin = (value: string | null | undefined): string | null => {
36
+ if (typeof value !== "string" || !value.trim()) return null;
37
+ return normalizeKnownServerOrigin(value);
38
+ };
39
+
40
+ const resolveAuthFallbackServers = (): string[] => {
41
+ const current = normalizeServerOrigin(process.env.APP_BASE_URL);
42
+ return NOLO_CLUSTER_SERVERS.filter((server) => normalizeServerOrigin(server) !== current);
43
+ };
44
+
45
+ const getAuthTokenStore = () => getServerAuthorityStore();
46
+
47
+ const readUserFromClusterPeer = async (userId: string, token: string): Promise<any | null> => {
48
+ const store = getAuthTokenStore();
49
+ for (const server of resolveAuthFallbackServers()) {
50
+ try {
51
+ const res = await fetch(`${server}/api/v1/users/${encodeURIComponent(userId)}`, {
52
+ method: "GET",
53
+ headers: { Authorization: `Bearer ${token}` },
54
+ });
55
+ if (!res.ok) continue;
56
+ const data = await res.json().catch(() => null);
57
+ if (!data || typeof data !== "object") continue;
58
+ const record = { ...(data as Record<string, unknown>) };
59
+ delete (record as Record<string, unknown>).id;
60
+ if (typeof record.publicKey !== "string" || !record.publicKey) continue;
61
+ await store.put(`${DB_PREFIX.USER}${userId}`, record);
62
+ return record;
63
+ } catch {
64
+ // Try the next peer.
65
+ }
66
+ }
67
+ return null;
68
+ };
69
+
34
70
  export async function authenticateToken(token?: string | null): Promise<{
35
71
  userId: string;
36
72
  payload: any;
37
73
  }> {
74
+ const store = getAuthTokenStore();
38
75
  if (!token) {
39
76
  throw unauthorized("Authentication required");
40
77
  }
@@ -47,8 +84,16 @@ export async function authenticateToken(token?: string | null): Promise<{
47
84
 
48
85
  let user: any;
49
86
  try {
50
- user = await serverDb.get(`${DB_PREFIX.USER}${userId}`);
87
+ user = await store.get(`${DB_PREFIX.USER}${userId}`);
51
88
  } catch {
89
+ user = null;
90
+ }
91
+
92
+ if (!user) {
93
+ user = await readUserFromClusterPeer(userId, token);
94
+ }
95
+
96
+ if (!user) {
52
97
  throw unauthorized("User not found");
53
98
  }
54
99
 
@@ -3,6 +3,9 @@ import { handleBillingLedgerWitness } from "./handlers/billingLedgerWitnessHandl
3
3
  import { handleBillingUsageReport } from "./handlers/billingUsageReportHandler";
4
4
  import { handleCreatorEarningsReport } from "./handlers/creatorEarningsReportHandler";
5
5
  import { handleCreatorSettlementReport } from "./handlers/creatorSettlementReportHandler";
6
+ import { handleProviderCallsRecent } from "./handlers/providerCallsRecentHandler";
7
+ import { handleProviderRequestIds } from "./handlers/providerRequestIdsHandler";
8
+ import { handleProviderReconciliationRun } from "./handlers/providerReconciliationRunHandler";
6
9
  import { handleRevenueShareReport } from "./handlers/revenueShareReportHandler";
7
10
 
8
11
  const CORS_HEADERS: Record<string, string> = {
@@ -33,6 +36,18 @@ export const billingLedgerRoutes: Record<string, any> = {
33
36
  GET: handleBillingUsageReport,
34
37
  OPTIONS: options,
35
38
  },
39
+ "/api/admin/provider-calls/recent": {
40
+ GET: handleProviderCallsRecent,
41
+ OPTIONS: options,
42
+ },
43
+ "/api/admin/provider-request-ids/recent": {
44
+ GET: handleProviderRequestIds,
45
+ OPTIONS: options,
46
+ },
47
+ "/api/admin/provider-reconciliation/run": {
48
+ POST: handleProviderReconciliationRun,
49
+ OPTIONS: options,
50
+ },
36
51
  "/api/admin/revenue-share/report": {
37
52
  GET: handleRevenueShareReport,
38
53
  OPTIONS: options,
@@ -0,0 +1,54 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ import { resolvePublicPath } from "./publicPaths";
4
+
5
+ export type NoloBuildManifest = {
6
+ basePath: string | null;
7
+ timestamp: string | null;
8
+ buildSha: string | null;
9
+ buildTime: string | null;
10
+ };
11
+
12
+ export const EMPTY_BUILD_MANIFEST: NoloBuildManifest = {
13
+ basePath: null,
14
+ timestamp: null,
15
+ buildSha: null,
16
+ buildTime: null,
17
+ };
18
+
19
+ const readOptionalString = (value: unknown): string | null =>
20
+ typeof value === "string" && value.trim().length > 0 ? value : null;
21
+
22
+ export function parseBuildManifestFromJson(rawValue: string): NoloBuildManifest {
23
+ try {
24
+ const parsed = JSON.parse(rawValue);
25
+ return {
26
+ basePath: readOptionalString(parsed?.basePath),
27
+ timestamp: readOptionalString(parsed?.timestamp),
28
+ buildSha: readOptionalString(parsed?.buildSha),
29
+ buildTime: readOptionalString(parsed?.buildTime),
30
+ };
31
+ } catch {
32
+ return EMPTY_BUILD_MANIFEST;
33
+ }
34
+ }
35
+
36
+ export function readBuildManifestSync(): NoloBuildManifest {
37
+ try {
38
+ return parseBuildManifestFromJson(
39
+ readFileSync(resolvePublicPath("latest-assets.json"), "utf8")
40
+ );
41
+ } catch {
42
+ return EMPTY_BUILD_MANIFEST;
43
+ }
44
+ }
45
+
46
+ export async function readBuildManifest(): Promise<NoloBuildManifest> {
47
+ try {
48
+ return parseBuildManifestFromJson(
49
+ await Bun.file(resolvePublicPath("latest-assets.json")).text()
50
+ );
51
+ } catch {
52
+ return EMPTY_BUILD_MANIFEST;
53
+ }
54
+ }
@@ -1,13 +1,18 @@
1
- import { withServiceHeaders } from "./coreHeaders";
2
- import { getCoreRuntimeSnapshot } from "./coreRuntime";
3
-
4
- export function handleCoreReady(_req: Request) {
5
- const snapshot = getCoreRuntimeSnapshot();
6
- const body = {
7
- ok: snapshot.ready,
8
- ready: snapshot.ready,
9
- status: snapshot.status,
10
- };
1
+ import { withServiceHeaders } from "./coreHeaders";
2
+ import { readBuildManifestSync } from "./buildManifest";
3
+ import { getCoreRuntimeSnapshot } from "./coreRuntime";
4
+
5
+ export function handleCoreReady(_req: Request) {
6
+ const snapshot = getCoreRuntimeSnapshot();
7
+ const buildManifest = readBuildManifestSync();
8
+ const body = {
9
+ ok: snapshot.ready,
10
+ ready: snapshot.ready,
11
+ status: snapshot.status,
12
+ role: snapshot.role,
13
+ buildSha: buildManifest.buildSha,
14
+ buildTime: buildManifest.buildTime,
15
+ };
11
16
 
12
17
  return withServiceHeaders(
13
18
  Response.json(body, {
@@ -21,19 +26,23 @@ export function handleCoreReady(_req: Request) {
21
26
  );
22
27
  }
23
28
 
24
- export function handleCoreMeta(_req: Request) {
25
- const snapshot = getCoreRuntimeSnapshot();
26
-
27
- return withServiceHeaders(
28
- Response.json({
29
- service: "core",
30
- status: snapshot.status,
31
- ready: snapshot.ready,
32
- }),
33
- {
34
- service: "core",
35
- owner: "core-route",
36
- routeKind: "core",
37
- }
38
- );
29
+ export function handleCoreMeta(_req: Request) {
30
+ const snapshot = getCoreRuntimeSnapshot();
31
+ const buildManifest = readBuildManifestSync();
32
+
33
+ return withServiceHeaders(
34
+ Response.json({
35
+ service: "core",
36
+ status: snapshot.status,
37
+ ready: snapshot.ready,
38
+ role: snapshot.role,
39
+ buildSha: buildManifest.buildSha,
40
+ buildTime: buildManifest.buildTime,
41
+ }),
42
+ {
43
+ service: "core",
44
+ owner: "core-route",
45
+ routeKind: "core",
46
+ }
47
+ );
39
48
  }
@@ -26,22 +26,27 @@ import {
26
26
  startCryptoUsdtTronWatcher,
27
27
  stopCryptoUsdtTronWatcher,
28
28
  } from "./payments/crypto/cryptoUsdtTronWatcher";
29
-
30
- type CoreRuntimeStatus = "idle" | "starting" | "ready" | "stopping";
29
+ import { resolveRuntimeRole, shouldRunBackgroundWorkers } from "./runtimeRole";
30
+
31
+ type CoreRuntimeStatus = "idle" | "starting" | "ready" | "stopping";
31
32
 
32
33
  let status: CoreRuntimeStatus = "idle";
33
34
  let startPromise: Promise<void> | null = null;
34
35
  let stopPromise: Promise<void> | null = null;
35
36
 
37
+ const getRuntimeRole = () => resolveRuntimeRole(process.env);
38
+
36
39
  const backgroundWorkersDisabled = () =>
37
- process.env.NOLO_DISABLE_BACKGROUND_WORKERS === "1";
38
-
39
- export function getCoreRuntimeSnapshot() {
40
- return {
41
- status,
42
- ready: status === "ready",
43
- };
44
- }
40
+ process.env.NOLO_DISABLE_BACKGROUND_WORKERS === "1" ||
41
+ !shouldRunBackgroundWorkers(getRuntimeRole());
42
+
43
+ export function getCoreRuntimeSnapshot() {
44
+ return {
45
+ status,
46
+ ready: status === "ready",
47
+ role: getRuntimeRole(),
48
+ };
49
+ }
45
50
 
46
51
  export async function startCoreRuntime() {
47
52
  if (startPromise) return startPromise;
@@ -4,13 +4,15 @@
4
4
  //
5
5
  // GET /api/admin/activity-stats?days=30
6
6
 
7
- import serverDb from "../../database/server/db";
7
+ import { getServerAuthorityStore } from "../../database/server/db";
8
8
 
9
9
  const CORS = {
10
10
  "Access-Control-Allow-Origin": "*",
11
11
  "Content-Type": "application/json",
12
12
  };
13
13
 
14
+ const getActivityStatsStore = () => getServerAuthorityStore();
15
+
14
16
  export async function handleActivityStats(req: Request): Promise<Response> {
15
17
  if (req.method === "OPTIONS") return new Response(null, { status: 204, headers: CORS });
16
18
 
@@ -27,8 +29,9 @@ export async function handleActivityStats(req: Request): Promise<Response> {
27
29
  let skipped = 0;
28
30
 
29
31
  try {
32
+ const store = getActivityStatsStore();
30
33
  // 扫描所有以 "token-" 开头但不是 "token-stats-" 的记录
31
- const iter = serverDb.iterator({
34
+ const iter = store.iterator({
32
35
  gte: "token-",
33
36
  lte: "token-\uffff",
34
37
  });
@@ -1,7 +1,7 @@
1
- import { randomInt, randomUUID } from "node:crypto";
2
- import { authenticateRequest } from "../../auth/utils";
3
- import serverDb from "../../database/server/db";
4
- import { getEmailProvider } from "../email/providerRegistry";
1
+ import { randomInt, randomUUID } from "node:crypto";
2
+ import { authenticateRequest } from "../../auth/utils";
3
+ import { getServerAuthorityStore } from "../../database/server/db";
4
+ import { getEmailProvider } from "../email/providerRegistry";
5
5
  import { mirrorEmailToControlledInboxes } from "../../database/server/emailRepository";
6
6
  import {
7
7
  AGENT_EMAIL_REGISTRATION_E2E_PAGE_PATH,
@@ -23,8 +23,10 @@ const HTML_HEADERS = {
23
23
  "Content-Type": "text/html; charset=utf-8",
24
24
  };
25
25
 
26
- const REGISTRATION_TTL_MS = 15 * 60 * 1000;
27
- const KEY_PREFIX = "agent-email-registration-e2e-";
26
+ const REGISTRATION_TTL_MS = 15 * 60 * 1000;
27
+ const KEY_PREFIX = "agent-email-registration-e2e-";
28
+
29
+ const getAgentEmailRegistrationStore = () => getServerAuthorityStore();
28
30
 
29
31
  type RegistrationRecord = {
30
32
  dbKey: string;
@@ -144,12 +146,12 @@ const getAppOrigin = (req: Request) =>
144
146
  new URL(req.url).origin;
145
147
 
146
148
  const loadRegistration = async (registrationId: string): Promise<RegistrationRecord> => {
147
- const id = normalizeText(registrationId);
148
- if (!id) throw new Error("registrationId is required");
149
- try {
150
- const record = await serverDb.get(buildDbKey(id));
151
- if (!record) throw new Error("registration not found");
152
- return record as RegistrationRecord;
149
+ const id = normalizeText(registrationId);
150
+ if (!id) throw new Error("registrationId is required");
151
+ try {
152
+ const record = await getAgentEmailRegistrationStore().get(buildDbKey(id));
153
+ if (!record) throw new Error("registration not found");
154
+ return record as RegistrationRecord;
153
155
  } catch (error: any) {
154
156
  if (isNotFoundError(error)) {
155
157
  throw new Error("registration not found");
@@ -264,10 +266,10 @@ export const handleAgentEmailRegistrationE2EStart = async (req: Request) => {
264
266
  code,
265
267
  status: "pending",
266
268
  createdAt: now.toISOString(),
267
- updatedAt: now.toISOString(),
268
- expiresAt: expiresAt.toISOString(),
269
- };
270
- await serverDb.put(dbKey, record);
269
+ updatedAt: now.toISOString(),
270
+ expiresAt: expiresAt.toISOString(),
271
+ };
272
+ await getAgentEmailRegistrationStore().put(dbKey, record);
271
273
 
272
274
  const origin = getAppOrigin(req);
273
275
  const verifyUrl = `${origin}${AGENT_EMAIL_REGISTRATION_E2E_PAGE_PATH}?registrationId=${encodeURIComponent(registrationId)}`;
@@ -371,13 +373,13 @@ export const handleAgentEmailRegistrationE2EVerify = async (req: Request) => {
371
373
  }
372
374
 
373
375
  const now = new Date().toISOString();
374
- const updated: RegistrationRecord = {
375
- ...record,
376
- status: "verified",
377
- verifiedAt: now,
378
- updatedAt: now,
379
- };
380
- await serverDb.put(record.dbKey, updated);
376
+ const updated: RegistrationRecord = {
377
+ ...record,
378
+ status: "verified",
379
+ verifiedAt: now,
380
+ updatedAt: now,
381
+ };
382
+ await getAgentEmailRegistrationStore().put(record.dbKey, updated);
381
383
 
382
384
  return json({
383
385
  success: true,
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  BUILTIN_ECOMMERCE_AGENT_KEY,
3
3
  BUILTIN_NOLO_AGENT_KEY,
4
- fetchBuiltinPlatformAgentRecord,
5
4
  normalizeBuiltinPlatformAgentModelConfig,
6
5
  resolveBuiltinAgentConfig,
7
6
  } from "./builtinAgents";
@@ -16,7 +15,6 @@ export async function resolveAgentRunAgentConfig(options: {
16
15
  agentKey: string;
17
16
  getAgentRecord: AgentRecordGetter;
18
17
  resolveBuiltinAgentConfig?: typeof resolveBuiltinAgentConfig;
19
- fetchBuiltinPlatformAgentRecord?: typeof fetchBuiltinPlatformAgentRecord;
20
18
  normalizeBuiltinPlatformAgentModelConfig?: typeof normalizeBuiltinPlatformAgentModelConfig;
21
19
  }): Promise<AgentRunAgentLookupResult> {
22
20
  const {
@@ -24,8 +22,6 @@ export async function resolveAgentRunAgentConfig(options: {
24
22
  getAgentRecord,
25
23
  resolveBuiltinAgentConfig: resolveBuiltin =
26
24
  resolveBuiltinAgentConfig,
27
- fetchBuiltinPlatformAgentRecord: fetchBuiltinPlatform =
28
- fetchBuiltinPlatformAgentRecord,
29
25
  normalizeBuiltinPlatformAgentModelConfig: normalizeBuiltinPlatform =
30
26
  normalizeBuiltinPlatformAgentModelConfig,
31
27
  } = options;
@@ -53,9 +49,7 @@ export async function resolveAgentRunAgentConfig(options: {
53
49
  }
54
50
 
55
51
  if (!agentConfig || typeof agentConfig !== "object") {
56
- agentConfig =
57
- resolveBuiltin(agentKey) ??
58
- await fetchBuiltinPlatform(agentKey);
52
+ agentConfig = resolveBuiltin(agentKey);
59
53
  if (!agentConfig || typeof agentConfig !== "object") {
60
54
  return {
61
55
  ok: false,
@@ -1,7 +1,7 @@
1
- import { DataType } from "../../../create/types";
2
- import type { DialogRuntimeProfile } from "../../../app/types";
3
- import { createPageServer } from "../../../render/page/server/createPage";
4
- import serverDb from "../../../database/server/db";
1
+ import { DataType } from "../../../create/types";
2
+ import type { DialogRuntimeProfile } from "../../../app/types";
3
+ import { createPageServer } from "../../../render/page/server/createPage";
4
+ import { getServerAuthorityStore } from "../../../database/server/db";
5
5
 
6
6
  type RuntimeCheckpointLike = {
7
7
  toolCallCount?: number;
@@ -244,12 +244,13 @@ async function ensureAutonomousWorkbenchDocs(args: {
244
244
  userId: string;
245
245
  spaceId: string;
246
246
  agentKey: string;
247
- }): Promise<AutonomousWorkbenchDoc[]> {
248
- const { userId, spaceId, agentKey } = args;
249
- const spaceKey = `space-${spaceId}`;
250
- const spaceRecord = (await serverDb.get(spaceKey).catch(() => null)) as Record<string, any> | null;
251
- const contents = spaceRecord?.contents ?? {};
252
- const specs = buildAutonomousWorkbenchSpecs(agentKey);
247
+ }): Promise<AutonomousWorkbenchDoc[]> {
248
+ const { userId, spaceId, agentKey } = args;
249
+ const spaceKey = `space-${spaceId}`;
250
+ const store = getServerAuthorityStore();
251
+ const spaceRecord = (await store.get(spaceKey).catch(() => null)) as Record<string, any> | null;
252
+ const contents = spaceRecord?.contents ?? {};
253
+ const specs = buildAutonomousWorkbenchSpecs(agentKey);
253
254
  const docs: AutonomousWorkbenchDoc[] = [];
254
255
 
255
256
  for (const spec of specs) {
@@ -1,4 +1,3 @@
1
- import { APP_BUILDER_PRESET } from "../../../ai/tools/agent/presets/appBuilderPreset";
2
1
  import {
3
2
  DEEPINFRA_KIMI_FALLBACK_MODEL,
4
3
  FIREWORKS_KIMI_LATEST_MODEL,
@@ -11,9 +10,14 @@ import {
11
10
  BUILTIN_APP_BUILDER_AGENT_KEY,
12
11
  BUILTIN_ECOMMERCE_AGENT_KEY,
13
12
  BUILTIN_NOLO_AGENT_KEY,
13
+ BUILTIN_NOLO_AGENT_ID,
14
+ BUILTIN_APP_BUILDER_AGENT_ID,
15
+ BUILTIN_ECOMMERCE_AGENT_ID,
16
+ buildBuiltinAppBuilderRecord,
14
17
  buildBuiltinAgentCreatorRecord,
18
+ buildBuiltinEcommerceAgentRecord,
19
+ buildBuiltinNoloRecord,
15
20
  } from "../../../core/builtinAgents";
16
- import { NOLO_CLUSTER_SERVERS } from "../../../database/config";
17
21
 
18
22
  export {
19
23
  BUILTIN_AGENT_CREATOR_AGENT_KEY,
@@ -23,10 +27,6 @@ export {
23
27
  BUILTIN_NOLO_AGENT_KEY,
24
28
  } from "../../../core/builtinAgents";
25
29
 
26
- export const BUILTIN_NOLO_AGENT_ID = "01NOLOAPPBLD000000019KCKT0";
27
- export const BUILTIN_APP_BUILDER_AGENT_ID = "01APPBUILDER00000001YAII3I";
28
- export const BUILTIN_ECOMMERCE_AGENT_ID = "01ECOMMERCEAG00000001PYQ2J";
29
-
30
30
  const DESKTOP_NOLO_LOCAL_FILE_TOOLS = [
31
31
  "codeSearch",
32
32
  "checkEnv",
@@ -115,14 +115,6 @@ function buildBaseAgent(overrides: Record<string, unknown>) {
115
115
  };
116
116
  }
117
117
 
118
- function buildBuiltinAppBuilderAgent() {
119
- return buildBaseAgent({
120
- ...APP_BUILDER_PRESET,
121
- id: BUILTIN_APP_BUILDER_AGENT_ID,
122
- tags: ["应用构建", "App Builder", "无代码"],
123
- });
124
- }
125
-
126
118
  export function resolveBuiltinNoloModelConfig() {
127
119
  if (process.env.FIREWORKS_API_KEY?.trim()) {
128
120
  return {
@@ -148,8 +140,8 @@ export function resolveBuiltinNoloModelConfig() {
148
140
  return {
149
141
  provider: "openai",
150
142
  model: "gpt-5.4-mini",
151
- inputPrice: 0.75,
152
- outputPrice: 4.5,
143
+ inputPrice: 0.75 * 8,
144
+ outputPrice: 4.5 * 8,
153
145
  };
154
146
  }
155
147
  if (process.env.GOOGLE_API_KEY?.trim()) {
@@ -227,12 +219,6 @@ export function normalizeBuiltinPlatformAgentModelConfig(agentConfig: any) {
227
219
  runtimeToolPolicy: DESKTOP_NOLO_LOCAL_DEVELOPER_RUNTIME_POLICY,
228
220
  }
229
221
  : {}),
230
- ...(!hasLocalProviderKey && !shouldRunBuiltinNoloInDesktop
231
- ? {
232
- runtimeServerBase:
233
- agentConfig.runtimeServerBase ?? NOLO_CLUSTER_SERVERS[0],
234
- }
235
- : {}),
236
222
  };
237
223
  }
238
224
 
@@ -251,73 +237,11 @@ function mergeToolNames(existing: string[], additions: string[]) {
251
237
  return merged;
252
238
  }
253
239
 
254
- export async function fetchBuiltinPlatformAgentRecord(agentKey: string) {
255
- const isBuiltinPlatformAgent =
256
- agentKey === BUILTIN_NOLO_AGENT_KEY ||
257
- agentKey === BUILTIN_APP_BUILDER_AGENT_KEY ||
258
- agentKey === BUILTIN_ECOMMERCE_AGENT_KEY;
259
-
260
- if (!isBuiltinPlatformAgent) return null;
261
-
262
- for (const server of NOLO_CLUSTER_SERVERS) {
263
- try {
264
- const response = await fetch(
265
- `${server.replace(/\/+$/, "")}/api/v1/db/read/${encodeURIComponent(agentKey)}`
266
- );
267
- if (!response.ok) continue;
268
- const data = await response.json();
269
- if (data && typeof data === "object" && !Array.isArray(data)) {
270
- return { ...data, dbKey: (data as any).dbKey ?? agentKey };
271
- }
272
- } catch {
273
- // Try the next public server.
274
- }
275
- }
276
-
277
- return null;
278
- }
279
-
280
- function buildBuiltinEcommerceAgent() {
281
- const modelConfig = resolveBuiltinNoloModelConfig();
282
- return buildBaseAgent({
283
- id: BUILTIN_ECOMMERCE_AGENT_ID,
284
- name: "电商商品参数助手",
285
- introduction:
286
- "专门获取淘宝、天猫、京东等电商商品真实参数、SKU、价格、库存和店铺信息,并做结构化对比。",
287
- greeting: "发给我淘宝、天猫或京东商品链接,我会尽量获取真实商品参数。",
288
- provider: modelConfig.provider,
289
- model: modelConfig.model,
290
- fallbackProvider: modelConfig.fallbackProvider,
291
- fallbackModel: modelConfig.fallbackModel,
292
- secondFallbackProvider: modelConfig.secondFallbackProvider,
293
- secondFallbackModel: modelConfig.secondFallbackModel,
294
- useServerProxy: true,
295
- inputPrice: modelConfig.inputPrice,
296
- outputPrice: modelConfig.outputPrice,
297
- hasVision: false,
298
- apiSource: "platform",
299
- tags: ["电商", "商品参数", "数据抓取"],
300
- tools: ["taobaoTmallProductScraper", "jdProductScraper"],
301
- prompt: [
302
- "你是电商商品参数助手,只负责获取和整理电商商品真实数据。",
303
- "当用户给淘宝/天猫链接或商品 ID 时,先提取数字 itemId,再调用 taobaoTmallProductScraper。",
304
- "当用户给京东链接或 SKU 时,先提取数字 skuId,再调用 jdProductScraper。",
305
- "输出要结构化:商品标题、品牌、型号、店铺、价格、SKU/规格、库存、尺寸重量、质保、数据来源和缺失项。",
306
- "用户问参数或详情时,必须展开工具返回的详细参数,不要只摘要基础字段。",
307
- "只输出用户请求的数据结果;不要输出寒暄、确认、过渡句或结尾追问。",
308
- "如果用户给多个商品,逐个调用对应工具后再做对比表。",
309
- "如果工具返回缺失字段,如实说明缺失;不要编造参数,也不要要求用户手抄页面。",
310
- ].join("\n"),
311
- });
312
- }
313
-
314
240
  function buildBuiltinAgentCreatorAgent() {
315
241
  const modelConfig = resolveBuiltinNoloModelConfig();
316
- const hasLocalProviderKey = !!getNoloKey(modelConfig.provider as any)?.trim();
317
242
  const baseRecord = buildBuiltinAgentCreatorRecord();
318
- const { runtimeServerBase: _runtimeServerBase, ...localRecord } = baseRecord;
319
243
  return buildBaseAgent({
320
- ...(hasLocalProviderKey ? localRecord : baseRecord),
244
+ ...baseRecord,
321
245
  provider: modelConfig.provider,
322
246
  model: modelConfig.model,
323
247
  fallbackProvider: modelConfig.fallbackProvider,
@@ -332,13 +256,13 @@ function buildBuiltinAgentCreatorAgent() {
332
256
 
333
257
  export function resolveBuiltinAgentConfig(agentKey: string) {
334
258
  if (agentKey === BUILTIN_NOLO_AGENT_KEY) {
335
- return null;
259
+ return buildBuiltinNoloRecord();
336
260
  }
337
261
  if (agentKey === BUILTIN_APP_BUILDER_AGENT_KEY) {
338
- return buildBuiltinAppBuilderAgent();
262
+ return buildBuiltinAppBuilderRecord();
339
263
  }
340
264
  if (agentKey === BUILTIN_ECOMMERCE_AGENT_KEY) {
341
- return buildBuiltinEcommerceAgent();
265
+ return buildBuiltinEcommerceAgentRecord();
342
266
  }
343
267
  if (agentKey === BUILTIN_AGENT_CREATOR_AGENT_KEY) {
344
268
  return buildBuiltinAgentCreatorAgent();
@@ -3,7 +3,7 @@ import type { ChatMessage } from "./types";
3
3
 
4
4
  type ResolveContinueDialogContextOptions = {
5
5
  continueDialogId?: string | null;
6
- history: ChatMessage[];
6
+ requestHistoryFallback: ChatMessage[];
7
7
  userId: string | null;
8
8
  resolveExistingDialogRef(args: {
9
9
  dialogId: string;
@@ -27,7 +27,7 @@ export async function resolveContinueDialogContext(
27
27
  ): Promise<ContinueDialogContext> {
28
28
  const {
29
29
  continueDialogId,
30
- history,
30
+ requestHistoryFallback,
31
31
  userId,
32
32
  resolveExistingDialogRef,
33
33
  fetchConvMsgs,
@@ -36,7 +36,7 @@ export async function resolveContinueDialogContext(
36
36
  warn = console.warn,
37
37
  } = options;
38
38
 
39
- let contextHistory: ChatMessage[] = history;
39
+ let contextHistory: ChatMessage[] = requestHistoryFallback;
40
40
  let existingDialogRecord: any = null;
41
41
  let existingDialogKey: string | null = null;
42
42
  let continueDialogUserId: string | null = userId;
@@ -61,6 +61,12 @@ export async function resolveContinueDialogContext(
61
61
  } catch (_) { }
62
62
 
63
63
  try {
64
+ if (requestHistoryFallback.length > 0) {
65
+ log("[agentRun] continue-history-overrides-request-history", {
66
+ dialogId: continueDialogId,
67
+ requestHistoryCount: requestHistoryFallback.length,
68
+ });
69
+ }
64
70
  const prevMsgs = await fetchConvMsgs({ dialogId: continueDialogId, limit: 50 });
65
71
  contextHistory = (prevMsgs as any[])
66
72
  .reverse()
@@ -79,6 +85,12 @@ export async function resolveContinueDialogContext(
79
85
  });
80
86
  } catch (error) {
81
87
  warn(`[agentRun] continueDialogId=${continueDialogId} load failed:`, error);
88
+ if (requestHistoryFallback.length > 0) {
89
+ warn("[agentRun] continue-history-falling-back-to-request-history", {
90
+ dialogId: continueDialogId,
91
+ requestHistoryCount: requestHistoryFallback.length,
92
+ });
93
+ }
82
94
  }
83
95
 
84
96
  return {
@@ -10,7 +10,7 @@ type FetchConversationMessages = (args: {
10
10
  limit: number;
11
11
  }) => Promise<unknown[]>;
12
12
 
13
- type BuildInheritedDialogPromptBlockOptions = {
13
+ type BuildConversationReferenceBlockOptions = {
14
14
  dialogKey?: string;
15
15
  parentDialogId?: string;
16
16
  getDialogRecord(dialogKey: string): Promise<DialogRecord | null>;
@@ -46,13 +46,13 @@ const clipDialogReferenceText = (
46
46
  const asRecord = (value: unknown): Record<string, unknown> =>
47
47
  value && typeof value === "object" ? (value as Record<string, unknown>) : {};
48
48
 
49
- export async function buildInheritedDialogPromptBlock({
49
+ export async function buildConversationReferenceBlock({
50
50
  dialogKey: rawDialogKey,
51
51
  parentDialogId,
52
52
  getDialogRecord,
53
53
  fetchConversationMessages,
54
54
  estimateTokenCount = defaultEstimateTokenCount,
55
- }: BuildInheritedDialogPromptBlockOptions): Promise<string | undefined> {
55
+ }: BuildConversationReferenceBlockOptions): Promise<string | undefined> {
56
56
  const dialogKey = rawDialogKey?.trim();
57
57
  if (!dialogKey?.startsWith("dialog-")) return undefined;
58
58