nolo-cli 0.1.29 → 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 (329) 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/agentCreateCustomCommands.ts +9 -4
  13. package/agentDialogsCommands.ts +4 -3
  14. package/agentDoctorCommands.ts +3 -3
  15. package/agentListCommands.ts +3 -3
  16. package/agentMachineCommands.ts +6 -6
  17. package/agentPullCommand.ts +4 -12
  18. package/agentRecordCommands.ts +5 -3
  19. package/agentRecordHelpers.ts +42 -23
  20. package/agentRunCommand.ts +2 -6
  21. package/agentRunParsing.ts +18 -5
  22. package/agentRuntimeLocal.ts +10 -0
  23. package/agentUnpublishCommands.ts +3 -2
  24. package/ai/agent/agentRunDialogLineage.ts +56 -0
  25. package/ai/agent/agentSlice.ts +45 -10
  26. package/ai/agent/avatarUtils.ts +1 -1
  27. package/ai/agent/buildSystemPrompt.ts +1 -2
  28. package/ai/agent/cliExecutor.ts +330 -19
  29. package/ai/agent/createAgentSchema.ts +22 -0
  30. package/ai/agent/hooks/fetchPublicAgents.ts +14 -39
  31. package/ai/agent/hooks/usePublicAgents.ts +90 -192
  32. package/ai/agent/publicAgentCatalog.ts +359 -0
  33. package/ai/agent/publicAgentIdentity.ts +76 -0
  34. package/ai/agent/server/fetchPublicAgents.ts +21 -46
  35. package/ai/agent/serverOrigin.ts +7 -0
  36. package/ai/agent/streamAgentChatTurn.ts +23 -21
  37. package/ai/agent/streamAgentChatTurnUtils.ts +292 -6
  38. package/ai/agent/types.ts +2 -0
  39. package/ai/agent/web/agentDisplayUtils.ts +171 -0
  40. package/ai/agent/web/useAgentModelAvatarComponent.ts +32 -0
  41. package/ai/ai.locale.ts +8 -0
  42. package/ai/chat/sendOpenAICompletionsRequest.native.ts +15 -0
  43. package/ai/chat/sendOpenAICompletionsRequest.ts +93 -1
  44. package/ai/chat/sendOpenAIResponseRequest.ts +86 -9
  45. package/ai/chat/updateTotalUsage.ts +7 -0
  46. package/ai/llm/deepinfra.ts +30 -15
  47. package/ai/llm/mistral.ts +3 -4
  48. package/ai/llm/providers.ts +2 -0
  49. package/ai/llm/types.ts +15 -0
  50. package/ai/memory/capture.ts +3 -3
  51. package/ai/memory/consolidate.ts +2 -2
  52. package/ai/memory/delete.ts +4 -3
  53. package/ai/memory/query.ts +3 -3
  54. package/ai/memory/remember.ts +2 -2
  55. package/ai/memory/store.ts +3 -3
  56. package/ai/memory/storeShared.ts +3 -2
  57. package/ai/policy/commercialMultiplier.ts +16 -0
  58. package/ai/token/billingAdminAuditEvent.ts +68 -0
  59. package/ai/token/billingAdminAuditEventWriter.ts +41 -0
  60. package/ai/token/billingAnomaly.ts +90 -0
  61. package/ai/token/billingAnomalyLifecycle.ts +54 -0
  62. package/ai/token/billingAnomalyLifecycleWriter.ts +44 -0
  63. package/ai/token/billingAnomalyWriter.ts +41 -0
  64. package/ai/token/calculatePrice.ts +3 -2
  65. package/ai/token/deepinfraReconciliation.ts +153 -0
  66. package/ai/token/deepinfraRequestIdQuery.ts +92 -0
  67. package/ai/token/externalToolCost.ts +54 -41
  68. package/ai/token/missingUsageEstimate.ts +12 -3
  69. package/ai/token/normalizeUsage.ts +45 -5
  70. package/ai/token/openaiReconciliation.ts +188 -0
  71. package/ai/token/providerBillableEvent.ts +84 -0
  72. package/ai/token/providerBillableEventWriter.ts +36 -0
  73. package/ai/token/providerBillingAnomalyDrilldown.ts +308 -0
  74. package/ai/token/providerBillingDrilldown.ts +361 -0
  75. package/ai/token/providerBillingHealthReport.ts +366 -0
  76. package/ai/token/providerCall.ts +144 -0
  77. package/ai/token/providerCallSweeper.ts +168 -0
  78. package/ai/token/providerCallWriter.ts +33 -0
  79. package/ai/token/providerCredential.ts +89 -0
  80. package/ai/token/providerCredentialAnomaly.ts +154 -0
  81. package/ai/token/providerCredentialLifecycle.ts +59 -0
  82. package/ai/token/providerCredentialLifecycleWriter.ts +44 -0
  83. package/ai/token/providerCredentialRegistry.ts +83 -0
  84. package/ai/token/providerCredentialRegistryCommand.ts +97 -0
  85. package/ai/token/providerCredentialRegistryList.ts +124 -0
  86. package/ai/token/providerCredentialRegistryResolver.ts +150 -0
  87. package/ai/token/providerCredentialRegistryWriter.ts +41 -0
  88. package/ai/token/providerCredentialRotationCommand.ts +102 -0
  89. package/ai/token/providerCredentialRuntime.ts +56 -0
  90. package/ai/token/providerDispatchIntent.ts +67 -0
  91. package/ai/token/providerDispatchIntentWriter.ts +36 -0
  92. package/ai/token/providerGateway.ts +260 -0
  93. package/ai/token/providerReconciliation.ts +148 -0
  94. package/ai/token/providerReconciliationLocal.ts +97 -0
  95. package/ai/token/providerReconciliationRunner.ts +165 -0
  96. package/ai/token/providerReconciliationWriter.ts +41 -0
  97. package/ai/token/ratingResult.ts +202 -0
  98. package/ai/token/ratingResultWriter.ts +33 -0
  99. package/ai/token/serverDialogProjection.ts +5 -3
  100. package/ai/token/serverTokenWriter.ts +11 -3
  101. package/ai/token/types.ts +10 -0
  102. package/ai/tools/agent/callAgentTool.ts +3 -4
  103. package/ai/tools/agent/presets/appBuilderPreset.ts +5 -7
  104. package/ai/tools/agent/runStreamingAgentTool.ts +1 -2
  105. package/ai/tools/agent/streamParallelAgentsTool.ts +2 -3
  106. package/ai/tools/readXPostTool.ts +1 -5
  107. package/app/admin/adminPages.ts +9 -0
  108. package/app/i18n/i18n.config.ts +5 -0
  109. package/app/i18n/translations/pricing.locale.ts +397 -0
  110. package/app/utils/desktopAgentRuntimeStatusClient.ts +5 -4
  111. package/app/utils/desktopAgentRuntimeTurnClient.ts +4 -1
  112. package/app/utils/imageUtils.ts +64 -34
  113. package/auth/adminPermissions.ts +18 -0
  114. package/auth/authSlice.ts +26 -12
  115. package/auth/hooks/useFetchUsers.ts +3 -0
  116. package/auth/routes.ts +46 -0
  117. package/auth/server/accessActivity.ts +4 -3
  118. package/auth/server/adminPermissions.ts +43 -0
  119. package/auth/server/adminUsageReport.ts +375 -0
  120. package/auth/server/billingAnomalies.ts +235 -0
  121. package/auth/server/billingUsageReport.ts +41 -2
  122. package/auth/server/creatorEarningCreditConversion.ts +10 -2
  123. package/auth/server/deduct.ts +14 -7
  124. package/auth/server/delete.ts +10 -2
  125. package/auth/server/disable.ts +4 -3
  126. package/auth/server/emailAutomation.ts +7 -5
  127. package/auth/server/emailDbConfig.ts +4 -2
  128. package/auth/server/emailDelivery.ts +24 -20
  129. package/auth/server/emailDeliveryGuards.ts +10 -7
  130. package/auth/server/emailPreferences.ts +6 -4
  131. package/auth/server/emailReport.ts +6 -4
  132. package/auth/server/emailRuntimeConfig.ts +3 -3
  133. package/auth/server/emailScenarioNotifications.ts +9 -8
  134. package/auth/server/enable.ts +4 -3
  135. package/auth/server/getRechargeHistory.ts +3 -2
  136. package/auth/server/getUser.ts +3 -2
  137. package/auth/server/gptProAccess.ts +44 -0
  138. package/auth/server/inviteReward.ts +10 -7
  139. package/auth/server/listusers.ts +6 -4
  140. package/auth/server/login.ts +2 -2
  141. package/auth/server/productEntitlements.ts +7 -4
  142. package/auth/server/productPurchase.ts +10 -2
  143. package/auth/server/providerBillingDrilldown.ts +47 -0
  144. package/auth/server/providerBillingHealth.ts +71 -0
  145. package/auth/server/providerCredentials.ts +136 -0
  146. package/auth/server/recharge.ts +14 -8
  147. package/auth/server/revokeSessions.ts +4 -3
  148. package/auth/server/route.ts +77 -0
  149. package/auth/server/sendEmail.ts +5 -4
  150. package/auth/server/signup.ts +10 -3
  151. package/auth/server/token.ts +53 -55
  152. package/auth/server/tokenUsageBilling.ts +18 -7
  153. package/auth/server/usageManagementAccess.ts +43 -0
  154. package/auth/server/usageReport.ts +59 -0
  155. package/auth/types.ts +12 -0
  156. package/auth/utils.ts +24 -22
  157. package/authCommands.ts +36 -2
  158. package/buildPublish.ts +3 -1
  159. package/buildPublishArtifactAssembly.ts +62 -1
  160. package/buildPublishImportAnalysis.ts +21 -16
  161. package/chat/dialog/dialogLaunchScope.ts +32 -0
  162. package/chat/dialog/objectAssistantRegistry.ts +2 -2
  163. package/chat/dialog/useCreateDialog.ts +1 -1
  164. package/chat/hooks/useChatInput.ts +41 -10
  165. package/chat/messages/messageSlice.ts +5 -1
  166. package/chat/messages/pendingAttachmentParts.ts +28 -2
  167. package/chat/messages/sendFirstMessage.ts +76 -79
  168. package/chat/messages/types.ts +9 -0
  169. package/chat/messages/web/streamingMarkdownModel.ts +41 -0
  170. package/chat/messages/web/useStreamingReveal.ts +91 -0
  171. package/chat/web/messageInputAgentUi.ts +94 -6
  172. package/cliEnvHelpers.ts +68 -13
  173. package/cliRuntimeDoctorReport.ts +193 -0
  174. package/client/agentConfigResolver.test.ts +0 -2
  175. package/client/agentRun.test.ts +171 -10
  176. package/client/agentRun.ts +44 -637
  177. package/client/agentRunInput.ts +10 -0
  178. package/client/agentRunLocalExecutor.ts +179 -0
  179. package/client/agentRunServerTransport.ts +394 -0
  180. package/client/agentRunTaskRunRecorder.ts +176 -0
  181. package/client/localRuntimeAdapter.test.ts +236 -9
  182. package/client/localRuntimeAdapter.ts +221 -23
  183. package/client/localToolPolicy.test.ts +28 -4
  184. package/connector-experimental/daemonLauncher.ts +38 -4
  185. package/connectorRunArtifact.ts +34 -10
  186. package/connectorWebSocketTarget.ts +40 -15
  187. package/core/builtinAgents.ts +155 -11
  188. package/create/space/contentLabels.ts +1 -1
  189. package/create/space/contentTypeMeta.ts +3 -2
  190. package/create/space/sidebarVisibleTypes.ts +27 -0
  191. package/create/space/space.locale.ts +76 -4
  192. package/database/actions/agentReadResolution.ts +2 -8
  193. package/database/actions/read.ts +11 -9
  194. package/database/actions/readAndWait.ts +10 -5
  195. package/database/server/agentDelegation.ts +3 -2
  196. package/database/server/authorityStoreConformance.ts +209 -0
  197. package/database/server/authorityStoreTypes.ts +31 -0
  198. package/database/server/coreDataProxy.ts +1 -1
  199. package/database/server/dataHandlers.ts +13 -5
  200. package/database/server/db.ts +15 -34
  201. package/database/server/delete.ts +88 -71
  202. package/database/server/emailRepository.ts +11 -9
  203. package/database/server/fileService.ts +2 -1
  204. package/database/server/legacyServerDb.ts +58 -0
  205. package/database/server/levelAuthorityStore.ts +75 -0
  206. package/database/server/memoryAuthorityStore.ts +133 -0
  207. package/database/server/patch.ts +13 -12
  208. package/database/server/query.ts +3 -2
  209. package/database/server/read.ts +33 -30
  210. package/database/server/resourceAccess.ts +7 -5
  211. package/database/server/serverStoreFactory.ts +124 -0
  212. package/database/server/spaceMemberAuthority.ts +3 -2
  213. package/database/server/storeBatchCompat.ts +37 -0
  214. package/database/server/testAuthorityStore.ts +76 -0
  215. package/database/server/write.ts +29 -27
  216. package/dialogReadCommands.ts +2 -1
  217. package/dialogStatusCommands.ts +2 -1
  218. package/integrations/anthropic/anthropicModels.ts +12 -12
  219. package/integrations/deepseek/models.ts +67 -67
  220. package/integrations/google/models.ts +111 -53
  221. package/integrations/openai/models.ts +22 -22
  222. package/integrations/xai/models.ts +1 -1
  223. package/localRuntimeDb.ts +39 -2
  224. package/machineCommandPrompts.ts +2 -0
  225. package/machineCommands.ts +193 -62
  226. package/machineStatusCommands.ts +4 -12
  227. package/machineWsRunDispatch.ts +80 -15
  228. package/machineWsSession.ts +46 -2
  229. package/noloReadBridgePrompt.ts +16 -0
  230. package/package.json +114 -21
  231. package/pageCreateCommands.ts +2 -2
  232. package/pageDeleteCommands.ts +3 -3
  233. package/pageReadCommands.ts +3 -3
  234. package/pageUpdateCommands.ts +3 -3
  235. package/render/layout/mainLayoutViewMode.ts +25 -0
  236. package/render/page/server/createPage.ts +3 -1
  237. package/render/page/server/handleCreatePage.ts +2 -11
  238. package/runtimeDoctorCommands.ts +18 -69
  239. package/server/api/methods.ts +34 -12
  240. package/server/api/tableHandlers.ts +6 -3
  241. package/server/authenticateToken.ts +47 -2
  242. package/server/billingLedgerRoutes.ts +15 -0
  243. package/server/buildManifest.ts +54 -0
  244. package/server/coreReadiness.ts +34 -25
  245. package/server/coreRuntime.ts +15 -10
  246. package/server/handlers/activityStatsHandler.ts +5 -2
  247. package/server/handlers/agentEmailRegistrationE2EHandler.ts +25 -23
  248. package/server/handlers/agentRun/agentLookup.ts +1 -7
  249. package/server/handlers/agentRun/autonomousRuntime.ts +11 -10
  250. package/server/handlers/agentRun/builtinAgents.ts +12 -88
  251. package/server/handlers/agentRun/continueDialogContext.ts +15 -3
  252. package/server/handlers/agentRun/{inheritedDialogPrompt.ts → conversationReference.ts} +3 -3
  253. package/server/handlers/agentRun/dialogLookup.ts +4 -3
  254. package/server/handlers/agentRun/index.ts +864 -404
  255. package/server/handlers/agentRun/localRuntimeBootstrap.ts +17 -1
  256. package/server/handlers/agentRun/loop.ts +920 -508
  257. package/server/handlers/agentRun/machineConnector.ts +56 -8
  258. package/server/handlers/agentRun/machineRunAudit.ts +3 -2
  259. package/server/handlers/agentRun/modelUsageToolHandlers.ts +13 -10
  260. package/server/handlers/agentRun/requestContext.ts +12 -8
  261. package/server/handlers/agentRun/runtimeExecutionContext.ts +15 -3
  262. package/server/handlers/agentRun/runtimePreparation.ts +26 -24
  263. package/server/handlers/agentRun/runtimeRouting.ts +25 -40
  264. package/server/handlers/agentRun/runtimeSystemMessages.ts +65 -0
  265. package/server/handlers/agentRun/saveDialog.ts +97 -87
  266. package/server/handlers/agentRun/taskRunToolHandler.ts +9 -7
  267. package/server/handlers/agentRun/toolExecutor.ts +42 -78
  268. package/server/handlers/agentRun/types.ts +2 -1
  269. package/server/handlers/appDeployStatusStore.ts +17 -10
  270. package/server/handlers/appDomainHandler.ts +21 -15
  271. package/server/handlers/appLegacyInfraCleanup.ts +5 -2
  272. package/server/handlers/appSandboxHandler.ts +29 -8
  273. package/server/handlers/appSpaceAccess.ts +15 -8
  274. package/server/handlers/chatHandler.ts +22 -2
  275. package/server/handlers/chatUpstreamRetry.ts +225 -2
  276. package/server/handlers/connector/connectorConnectionRegistry.ts +55 -7
  277. package/server/handlers/connector/connectorWebSocket.ts +14 -10
  278. package/server/handlers/desktopAgentRuntimeAdapter.ts +4 -4
  279. package/server/handlers/desktopAgentRuntimeHostCapabilities.ts +25 -0
  280. package/server/handlers/desktopAgentRuntimeReadiness.ts +62 -0
  281. package/server/handlers/desktopAgentRuntimeStatusHandler.ts +38 -30
  282. package/server/handlers/desktopAgentRuntimeTurnHandler.ts +7 -3
  283. package/server/handlers/desktopAgentRuntimeTurnService.ts +39 -45
  284. package/server/handlers/desktopLlamaRuntimeHandler.ts +85 -51
  285. package/server/handlers/desktopUpdaterHandler.ts +132 -24
  286. package/server/handlers/favoriteHandlers.ts +8 -2
  287. package/server/handlers/getDialogBillingHandler.ts +4 -3
  288. package/server/handlers/getTransactionsHandler.ts +5 -2
  289. package/server/handlers/machines/machineBinding.ts +1 -0
  290. package/server/handlers/machines/machineHandlers.ts +0 -14
  291. package/server/handlers/machines/machineInstallAssets.ts +4 -2
  292. package/server/handlers/notificationEmitter.ts +5 -3
  293. package/server/handlers/notificationsHandler.ts +5 -2
  294. package/server/handlers/providerCallsRecentHandler.ts +234 -0
  295. package/server/handlers/providerReconciliationRunHandler.ts +180 -0
  296. package/server/handlers/providerRequestIdsHandler.ts +105 -0
  297. package/server/handlers/tableAccess.ts +6 -2
  298. package/server/handlers/tableToolHandlers.ts +28 -14
  299. package/server/handlers/userSecretsHandler.ts +17 -6
  300. package/server/handlers/versionHandler.ts +9 -4
  301. package/server/handlers/versionStore.ts +18 -10
  302. package/server/html/ssrPreload.ts +5 -3
  303. package/server/payments/crypto/cryptoUsdcBasePaymentProvider.ts +11 -8
  304. package/server/payments/crypto/cryptoUsdcBaseScanner.ts +12 -7
  305. package/server/payments/crypto/cryptoUsdtTronPaymentProvider.ts +11 -8
  306. package/server/payments/crypto/cryptoUsdtTronScanner.ts +9 -7
  307. package/server/payments/waffo/waffoPaymentProvider.ts +12 -9
  308. package/server/runtimeRole.ts +15 -0
  309. package/server/scheduler/scheduledTaskRuntime.ts +4 -2
  310. package/server/scheduler/schedulerService.ts +2 -2
  311. package/server/taskRunBridgeRoutes.ts +8 -5
  312. package/share/server/fetchCommunityShares.ts +1 -1
  313. package/share/server/helpers.ts +19 -17
  314. package/share/server/importShare.ts +9 -13
  315. package/share/server/listCommunityShares.ts +4 -4
  316. package/share/server/purchaseDoc.ts +8 -16
  317. package/share/server/readCommunityShareCover.ts +3 -2
  318. package/share/server/readSharedTable.ts +14 -13
  319. package/share/server/tableReplication.ts +42 -39
  320. package/spaceAttachCommands.ts +135 -0
  321. package/spaceCategoryCommands.ts +6 -6
  322. package/spaceCommands.ts +3 -3
  323. package/spaceDeleteCommands.ts +2 -2
  324. package/spaceInternalCommandEntries.ts +2 -0
  325. package/spaceReadCommands.ts +3 -3
  326. package/tableMetaCommands.ts +2 -2
  327. package/taskRunCommand.ts +11 -0
  328. package/ai/agent/runtimeServerBase.ts +0 -37
  329. package/server/handlers/desktopAgentRuntimeHostFacts.ts +0 -40
@@ -12,6 +12,7 @@ import {
12
12
  import { handleToolCalls } from "../../chat/messages/toolThunks";
13
13
  import {
14
14
  MessageContentPart,
15
+ ImageGenerationState,
15
16
  Message,
16
17
  OpenAITextContent,
17
18
  } from "../../chat/messages/types";
@@ -34,6 +35,7 @@ import {
34
35
  } from "./inlineImageUrlsForCustomProvider";
35
36
 
36
37
  import { getModelInfo } from "../llm/getModelContextWindow";
38
+ import { supportsImageGeneration } from "../agent/utils/imageOutput";
37
39
 
38
40
  import type { RootState } from "../../app/store";
39
41
 
@@ -69,6 +71,13 @@ type AssistantToolCall = {
69
71
  function: { name: string; arguments: string };
70
72
  };
71
73
 
74
+ const EXPLICIT_IMAGE_TOOL_NAMES = new Set([
75
+ "openAIGptImage",
76
+ "openAIGptImageGenerate",
77
+ "openAIGptImageEdit",
78
+ "geminiProImagePreview",
79
+ ]);
80
+
72
81
  function getStreamErrorMessage(data: any): string {
73
82
  const message =
74
83
  typeof data?.error?.message === "string" && data.error.message.trim()
@@ -150,6 +159,33 @@ type StreamCompletionContext = {
150
159
  agentConfig: any;
151
160
  };
152
161
 
162
+ const withImageGenerationStage = (
163
+ messageMetadata: Partial<Message> | undefined,
164
+ stage: ImageGenerationState["stage"]
165
+ ): Partial<Message> | undefined => {
166
+ const previousState = messageMetadata?.imageGenerationState;
167
+ if (previousState?.kind !== "image_generation") {
168
+ return messageMetadata;
169
+ }
170
+
171
+ return {
172
+ ...(messageMetadata ?? {}),
173
+ imageGenerationState: {
174
+ ...previousState,
175
+ stage,
176
+ },
177
+ };
178
+ };
179
+
180
+ const shouldShowImageSavingState = (contentBuffer: MessageContentPart[]) =>
181
+ contentBuffer.some((part) => part?.type === "image_url") &&
182
+ !contentBuffer.some(
183
+ (part) =>
184
+ part?.type === "text" &&
185
+ typeof part.text === "string" &&
186
+ part.text.trim().length > 0
187
+ );
188
+
153
189
  /** 单轮调用后返回给 Agent Loop 的元信息 */
154
190
  export type CompletionMeta = {
155
191
  hasToolCalls: boolean;
@@ -212,6 +248,13 @@ function buildRequestBodyWithTools(
212
248
 
213
249
  const rawTools = agentConfig.tools;
214
250
  if (!Array.isArray(rawTools) || rawTools.length === 0) return bodyData;
251
+ const hasExplicitImageTool = rawTools.some(
252
+ (toolName: unknown) =>
253
+ typeof toolName === "string" && EXPLICIT_IMAGE_TOOL_NAMES.has(toolName)
254
+ );
255
+ if (supportsImageGeneration(agentConfig) && !hasExplicitImageTool) {
256
+ return bodyData;
257
+ }
215
258
 
216
259
  const tools = prepareTools(rawTools, { provider: agentConfig.provider });
217
260
  if (!tools.length) return bodyData;
@@ -232,6 +275,30 @@ async function finalizeStream(
232
275
  ): Promise<StreamState> {
233
276
  if (state.hasHandedOff || state.alreadyFinalized) return state;
234
277
 
278
+ const savingMetadata = withImageGenerationStage(
279
+ ctx.messageMetadata,
280
+ "saving"
281
+ );
282
+ if (savingMetadata && shouldShowImageSavingState(state.contentBuffer)) {
283
+ ctx.dispatch(
284
+ messageStreaming({
285
+ id: ctx.messageId,
286
+ dialogId: ctx.dialogId,
287
+ dbKey: ctx.msgKey,
288
+ content: "",
289
+ thinkContent: state.reasoningBuffer,
290
+ role: "assistant",
291
+ agentKey: ctx.agentConfig.dbKey,
292
+ cybotKey: ctx.agentConfig.dbKey,
293
+ ...(typeof ctx.agentConfig?.name === "string" && ctx.agentConfig.name.trim()
294
+ ? { agentName: ctx.agentConfig.name.trim() }
295
+ : {}),
296
+ ...(savingMetadata ?? {}),
297
+ })
298
+ );
299
+ ctx.messageMetadata = savingMetadata;
300
+ }
301
+
235
302
  await ctx.dispatch(
236
303
  messageStreamEnd({
237
304
  finalContentBuffer: state.contentBuffer,
@@ -556,6 +623,7 @@ export const sendOpenAICompletionsRequest = async ({
556
623
  let hasHandedOffOverall = false;
557
624
  let hasPendingInteractionOverall = false;
558
625
  let lastFinishReason: string | null = null;
626
+ let activeMessageMetadata = messageMetadata;
559
627
 
560
628
  const buildMeta = (): CompletionMeta => ({
561
629
  hasToolCalls:
@@ -582,7 +650,7 @@ export const sendOpenAICompletionsRequest = async ({
582
650
  ...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
583
651
  ? { agentName: agentConfig.name.trim() }
584
652
  : {}),
585
- ...(messageMetadata ?? {}),
653
+ ...(activeMessageMetadata ?? {}),
586
654
  isStreaming: true,
587
655
  })
588
656
  );
@@ -607,6 +675,29 @@ export const sendOpenAICompletionsRequest = async ({
607
675
  status: response.status,
608
676
  dialogKey,
609
677
  });
678
+ activeMessageMetadata = withImageGenerationStage(
679
+ activeMessageMetadata,
680
+ "generating"
681
+ );
682
+ finalizeCtx.messageMetadata = activeMessageMetadata;
683
+ if (!parentMessageId && activeMessageMetadata?.imageGenerationState) {
684
+ dispatch(
685
+ messageStreaming({
686
+ id: messageId,
687
+ dialogId,
688
+ dbKey: msgKey,
689
+ content: "",
690
+ role: "assistant",
691
+ agentKey: agentConfig.dbKey,
692
+ cybotKey: agentConfig.dbKey,
693
+ ...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
694
+ ? { agentName: agentConfig.name.trim() }
695
+ : {}),
696
+ ...(activeMessageMetadata ?? {}),
697
+ isStreaming: true,
698
+ })
699
+ );
700
+ }
610
701
 
611
702
  if (!response.ok) {
612
703
  const errorMessage = await parseApiError(response);
@@ -726,6 +817,7 @@ export const sendOpenAICompletionsRequest = async ({
726
817
  messageId,
727
818
  msgKey,
728
819
  dialogId,
820
+ messageMetadata: activeMessageMetadata,
729
821
  });
730
822
 
731
823
  const finishReason = choice.finish_reason;
@@ -8,7 +8,7 @@ import {
8
8
  messageStreamEnd,
9
9
  } from "../../chat/messages/messageSlice";
10
10
  import { handleToolCalls } from "../../chat/messages/toolThunks";
11
- import type { Message } from "../../chat/messages/types";
11
+ import type { ImageGenerationState, Message } from "../../chat/messages/types";
12
12
  import { selectRuntimeCurrentServer } from "../../app/stateViews/runtime";
13
13
  import { selectCurrentSpaceId } from "../../create/space/spaceSlice";
14
14
  import { getApiEndpoint } from "../llm/providers";
@@ -42,6 +42,34 @@ const shouldEnableBuiltInImageGeneration = (agentConfig: any): boolean =>
42
42
  !getModelInfo(String(agentConfig?.model || ""))?.hasImageOutput &&
43
43
  !!agentConfig?.imageConfig?.enabled;
44
44
 
45
+ const withImageGenerationStage = (
46
+ messageMetadata: Partial<Message> | undefined,
47
+ stage: ImageGenerationState["stage"]
48
+ ): Partial<Message> | undefined => {
49
+ const previousState = messageMetadata?.imageGenerationState;
50
+ if (previousState?.kind !== "image_generation") {
51
+ return messageMetadata;
52
+ }
53
+
54
+ return {
55
+ ...(messageMetadata ?? {}),
56
+ imageGenerationState: {
57
+ ...previousState,
58
+ stage,
59
+ },
60
+ };
61
+ };
62
+
63
+ const shouldShowImageSavingState = (
64
+ contentBuffer: Array<
65
+ { type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }
66
+ >
67
+ ) =>
68
+ contentBuffer.some((part) => part?.type === "image_url") &&
69
+ !contentBuffer.some(
70
+ (part) => part?.type === "text" && typeof part.text === "string" && part.text.trim()
71
+ );
72
+
45
73
  const logQuickChatPerfStage = (
46
74
  startedAt: number | undefined,
47
75
  stage: string,
@@ -193,6 +221,7 @@ export const sendOpenAIResponseRequest = async ({
193
221
  assistantToolCalls: [],
194
222
  completedResponse: null,
195
223
  };
224
+ let activeMessageMetadata = messageMetadata;
196
225
 
197
226
  const buildMeta = (
198
227
  hasPendingInteraction = false,
@@ -221,7 +250,7 @@ export const sendOpenAIResponseRequest = async ({
221
250
  ...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
222
251
  ? { agentName: agentConfig.name.trim() }
223
252
  : {}),
224
- ...(messageMetadata ?? {}),
253
+ ...(activeMessageMetadata ?? {}),
225
254
  })
226
255
  );
227
256
 
@@ -250,7 +279,33 @@ export const sendOpenAIResponseRequest = async ({
250
279
  state.contentBuffer = seg(state.content);
251
280
  }
252
281
 
253
- flush();
282
+ activeMessageMetadata = withImageGenerationStage(
283
+ activeMessageMetadata,
284
+ "saving"
285
+ );
286
+ if (
287
+ activeMessageMetadata?.imageGenerationState &&
288
+ shouldShowImageSavingState(state.contentBuffer)
289
+ ) {
290
+ dispatch(
291
+ messageStreaming({
292
+ id: messageId,
293
+ dialogId,
294
+ dbKey: msgKey,
295
+ content: "",
296
+ thinkContent: state.reasoning,
297
+ role: "assistant",
298
+ agentKey: agentConfig.dbKey,
299
+ cybotKey: agentConfig.dbKey,
300
+ ...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
301
+ ? { agentName: agentConfig.name.trim() }
302
+ : {}),
303
+ ...(activeMessageMetadata ?? {}),
304
+ })
305
+ );
306
+ } else {
307
+ flush();
308
+ }
254
309
  await dispatch(
255
310
  messageStreamEnd({
256
311
  finalContentBuffer: state.contentBuffer,
@@ -261,7 +316,7 @@ export const sendOpenAIResponseRequest = async ({
261
316
  dialogKey,
262
317
  messageId,
263
318
  reasoningBuffer: state.reasoning,
264
- messageMetadata,
319
+ messageMetadata: activeMessageMetadata,
265
320
  toolCalls: state.assistantToolCalls,
266
321
  spaceId: streamSpaceId,
267
322
  })
@@ -294,10 +349,10 @@ export const sendOpenAIResponseRequest = async ({
294
349
  messageId,
295
350
  dialogId,
296
351
  dialogKey,
297
- parallelSessionId: messageMetadata?.parallelSessionId,
298
- parallelBranchId: messageMetadata?.parallelBranchId,
299
- parallelLabel: messageMetadata?.parallelLabel,
300
- parallelIndex: messageMetadata?.parallelIndex,
352
+ parallelSessionId: activeMessageMetadata?.parallelSessionId,
353
+ parallelBranchId: activeMessageMetadata?.parallelBranchId,
354
+ parallelLabel: activeMessageMetadata?.parallelLabel,
355
+ parallelIndex: activeMessageMetadata?.parallelIndex,
301
356
  })
302
357
  ).unwrap();
303
358
 
@@ -331,7 +386,7 @@ export const sendOpenAIResponseRequest = async ({
331
386
  ...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
332
387
  ? { agentName: agentConfig.name.trim() }
333
388
  : {}),
334
- ...(messageMetadata ?? {}),
389
+ ...(activeMessageMetadata ?? {}),
335
390
  isStreaming: true,
336
391
  })
337
392
  );
@@ -388,6 +443,28 @@ export const sendOpenAIResponseRequest = async ({
388
443
  status: response.status,
389
444
  dialogKey,
390
445
  });
446
+ activeMessageMetadata = withImageGenerationStage(
447
+ activeMessageMetadata,
448
+ "generating"
449
+ );
450
+ if (!parentMessageId && activeMessageMetadata?.imageGenerationState) {
451
+ dispatch(
452
+ messageStreaming({
453
+ id: messageId,
454
+ dialogId,
455
+ dbKey: msgKey,
456
+ content: "",
457
+ role: "assistant",
458
+ agentKey: agentConfig.dbKey,
459
+ cybotKey: agentConfig.dbKey,
460
+ ...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
461
+ ? { agentName: agentConfig.name.trim() }
462
+ : {}),
463
+ ...(activeMessageMetadata ?? {}),
464
+ isStreaming: true,
465
+ })
466
+ );
467
+ }
391
468
 
392
469
  if (!response.ok) {
393
470
  const errorMessage = await parseApiError(response);
@@ -85,5 +85,12 @@ export function updateTotalUsage(
85
85
  updatedUsage.billing_model = newUsageChunk.billing_model.trim();
86
86
  }
87
87
 
88
+ if (
89
+ typeof newUsageChunk.billing_service_tier === "string" &&
90
+ newUsageChunk.billing_service_tier.trim()
91
+ ) {
92
+ updatedUsage.billing_service_tier = newUsageChunk.billing_service_tier.trim();
93
+ }
94
+
88
95
  return updatedUsage;
89
96
  }
@@ -1,15 +1,30 @@
1
1
  // ai/llm/deepinfra.ts
2
+ import { scaleProviderPrice } from "../policy/commercialMultiplier";
2
3
  import { DEEPINFRA_KIMI_FALLBACK_MODEL } from "./kimi";
3
4
 
5
+ const price = (rawProviderPrice: number, model: string) =>
6
+ scaleProviderPrice(rawProviderPrice, "deepinfra", model);
7
+
4
8
  export const deepinfraModels = [
9
+ {
10
+ name: "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
11
+ displayName: "Meta Llama 3.1 8B Turbo (DeepInfra)",
12
+ hasVision: false,
13
+ price: {
14
+ input: price(0.02, "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"),
15
+ output: price(0.03, "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"),
16
+ },
17
+ contextWindow: 131072,
18
+ supportsTool: true,
19
+ },
5
20
  {
6
21
  name: DEEPINFRA_KIMI_FALLBACK_MODEL,
7
22
  displayName: "MoonshotAI: Kimi K2.6 (DeepInfra)",
8
23
  hasVision: true,
9
24
  price: {
10
- input: 0.6 * 8,
11
- output: 2.5 * 8,
12
- inputCacheHit: 0.06 * 8,
25
+ input: price(0.6, DEEPINFRA_KIMI_FALLBACK_MODEL),
26
+ output: price(2.5, DEEPINFRA_KIMI_FALLBACK_MODEL),
27
+ inputCacheHit: price(0.06, DEEPINFRA_KIMI_FALLBACK_MODEL),
13
28
  },
14
29
  maxOutputTokens: 262144,
15
30
  contextWindow: 262144,
@@ -20,9 +35,9 @@ export const deepinfraModels = [
20
35
  displayName: "MoonshotAI: Kimi K2.5 (DeepInfra)",
21
36
  hasVision: true,
22
37
  price: {
23
- input: 0.45 * 8,
24
- output: 2.25 * 8,
25
- inputCacheHit: 0.07 * 8,
38
+ input: price(0.45, "moonshotai/Kimi-K2.5"),
39
+ output: price(2.25, "moonshotai/Kimi-K2.5"),
40
+ inputCacheHit: price(0.07, "moonshotai/Kimi-K2.5"),
26
41
  },
27
42
  maxOutputTokens: 262144,
28
43
  contextWindow: 262144,
@@ -33,9 +48,9 @@ export const deepinfraModels = [
33
48
  displayName: "Z.AI: GLM 5.1 (DeepInfra)",
34
49
  hasVision: false,
35
50
  price: {
36
- input: 1.26 * 8,
37
- output: 3.96 * 8,
38
- inputCacheHit: 0.26 * 8,
51
+ input: price(1.26, "zai-org/GLM-5.1"),
52
+ output: price(3.96, "zai-org/GLM-5.1"),
53
+ inputCacheHit: price(0.26, "zai-org/GLM-5.1"),
39
54
  },
40
55
  contextWindow: 202752,
41
56
  supportsTool: true,
@@ -45,8 +60,8 @@ export const deepinfraModels = [
45
60
  displayName: "Anthropic: Claude Haiku 4.5 (DeepInfra)",
46
61
  hasVision: true,
47
62
  price: {
48
- input: 1 * 9,
49
- output: 5 * 9,
63
+ input: price(1, "anthropic/claude-haiku-4-5"),
64
+ output: price(5, "anthropic/claude-haiku-4-5"),
50
65
  },
51
66
  contextWindow: 195000,
52
67
  maxOutputTokens: 4092,
@@ -57,8 +72,8 @@ export const deepinfraModels = [
57
72
  displayName: "Anthropic: Claude Sonnet 4.6 (DeepInfra)",
58
73
  hasVision: true,
59
74
  price: {
60
- input: 3 * 9,
61
- output: 15 * 9,
75
+ input: price(3, "anthropic/claude-sonnet-4-6"),
76
+ output: price(15, "anthropic/claude-sonnet-4-6"),
62
77
  },
63
78
  contextWindow: 976000,
64
79
  maxOutputTokens: 4092,
@@ -69,8 +84,8 @@ export const deepinfraModels = [
69
84
  displayName: "Anthropic: Claude Opus 4.7 (DeepInfra)",
70
85
  hasVision: true,
71
86
  price: {
72
- input: 5 * 9,
73
- output: 25 * 9,
87
+ input: price(5, "anthropic/claude-opus-4-7"),
88
+ output: price(25, "anthropic/claude-opus-4-7"),
74
89
  },
75
90
  contextWindow: 976000,
76
91
  maxOutputTokens: 4092,
package/ai/llm/mistral.ts CHANGED
@@ -9,9 +9,8 @@ export const mistralModels: Model[] = [
9
9
  displayName: "Mistral: Devstral 2",
10
10
  hasVision: false,
11
11
  price: {
12
- // 单位:$/M tokens,按你给的文档:input 0.4,output 2
13
- input: 0.1,
14
- output: 0.1,
12
+ input: 0.1 * 8,
13
+ output: 0.1 * 8,
15
14
  },
16
15
  maxOutputTokens: 262144,
17
16
  contextWindow: 262144, // 256k ≈ 256 * 1024
@@ -19,4 +18,4 @@ export const mistralModels: Model[] = [
19
18
  // 如果后面确认支持 reasoning effort,可以加上:
20
19
  // supportsReasoningEffort: true,
21
20
  },
22
- ];
21
+ ];
@@ -119,6 +119,8 @@ const toModel = (candidate: ModelLookupCandidate): Model => ({
119
119
  imagePricingNote: candidate.imagePricingNote,
120
120
  imageTokenPricePerMillion: candidate.imageTokenPricePerMillion,
121
121
  imageOutputTokenEstimateBySize: candidate.imageOutputTokenEstimateBySize,
122
+ imageGenerationWaitTimeSeconds: candidate.imageGenerationWaitTimeSeconds,
123
+ imageGenerationProfiles: candidate.imageGenerationProfiles,
122
124
  supportsReasoningEffort:
123
125
  typeof candidate.supportsReasoningEffort === "boolean"
124
126
  ? candidate.supportsReasoningEffort
package/ai/llm/types.ts CHANGED
@@ -25,6 +25,19 @@ export interface ServiceTierPriceMultiplier {
25
25
  cache?: number;
26
26
  }
27
27
 
28
+ export interface ImageGenerationWaitTimeSeconds {
29
+ min: number;
30
+ max: number;
31
+ }
32
+
33
+ export interface ImageGenerationProfile {
34
+ key: "speed" | "quality";
35
+ label: string;
36
+ imageModel: string;
37
+ description?: string;
38
+ waitTimeSeconds?: ImageGenerationWaitTimeSeconds;
39
+ }
40
+
28
41
  export interface Model {
29
42
  name: string;
30
43
  displayName?: string; // 可选的 displayName 字段
@@ -61,6 +74,8 @@ export interface Model {
61
74
  imagePricingNote?: string;
62
75
  imageTokenPricePerMillion?: number;
63
76
  imageOutputTokenEstimateBySize?: Partial<Record<"1K" | "2K" | "4K", number>>;
77
+ imageGenerationWaitTimeSeconds?: ImageGenerationWaitTimeSeconds;
78
+ imageGenerationProfiles?: ImageGenerationProfile[];
64
79
 
65
80
  supportsReasoningEffort?: boolean; // 是否支持推理功能
66
81
  endpointKey?: string;
@@ -1,4 +1,4 @@
1
- import serverDb from "../../database/server/db";
1
+ import { getServerAuthorityStore } from "../../database/server/db";
2
2
  import { maybeConsolidateExplicitRemember } from "./consolidate";
3
3
  import { createMemoryItem, writeMemoryItemWithIndexesToDb } from "./store";
4
4
  import type { MemoryOwnerType, MemorySubjectType, MemoryVisibility } from "./types";
@@ -81,7 +81,7 @@ export const captureExplicitMemoryEpisode = async (input: {
81
81
  userInput: string;
82
82
  }): Promise<void> => {
83
83
  if (!shouldCaptureExplicitMemory(input.userInput)) return;
84
- const db = input.db ?? serverDb;
84
+ const db = input.db ?? getServerAuthorityStore();
85
85
  const targets = buildExplicitMemoryTargets(input);
86
86
 
87
87
  for (const target of targets) {
@@ -112,7 +112,7 @@ export const consolidateExplicitMemoryAfterDialog = async (input: {
112
112
  userInput: string;
113
113
  }): Promise<void> => {
114
114
  if (!shouldCaptureExplicitMemory(input.userInput)) return;
115
- const db = input.db ?? serverDb;
115
+ const db = input.db ?? getServerAuthorityStore();
116
116
  const targets = buildExplicitMemoryTargets(input);
117
117
 
118
118
  for (const target of targets) {
@@ -1,4 +1,4 @@
1
- import serverDb from "../../database/server/db";
1
+ import { getServerAuthorityStore } from "../../database/server/db";
2
2
  import { loadMemoryCandidatesFromDb } from "./query";
3
3
  import { createMemoryItem, writeMemoryItemWithIndexesToDb } from "./store";
4
4
  import type { MemoryItem, MemoryOwnerRef, MemorySubjectType } from "./types";
@@ -56,7 +56,7 @@ export const maybeConsolidateExplicitRemember = async (input: {
56
56
  const normalizedContent = normalizeExplicitRememberContent(input.content);
57
57
  if (!shouldKeepAsSemanticCandidate(normalizedContent)) return;
58
58
 
59
- const db = input.db ?? serverDb;
59
+ const db = input.db ?? getServerAuthorityStore();
60
60
  const items = await loadMemoryCandidatesFromDb(db, {
61
61
  owners: [input.owner],
62
62
  subjects: [{ subjectType: input.subjectType, subjectId: input.subjectId }],
@@ -1,4 +1,5 @@
1
- import serverDb from "../../database/server/db";
1
+ import { getServerAuthorityStore } from "../../database/server/db";
2
+ import { createStoreBatch } from "../../database/server/storeBatchCompat";
2
3
  import {
3
4
  createMemoryKey,
4
5
  createMemoryOwnerIndexKey,
@@ -127,7 +128,7 @@ export const deleteMemoriesForOwnerFromDb = async (
127
128
  return { deletedCount: 0, deletedIds: [], matchedItems: [] };
128
129
  }
129
130
 
130
- const batch = db.batch();
131
+ const batch = createStoreBatch(db);
131
132
  for (const item of matchedItems) {
132
133
  deleteMemoryItemWithIndexesInBatch(batch, item);
133
134
  }
@@ -144,4 +145,4 @@ export const deleteMemoriesForOwner = async (
144
145
  owner: MemoryOwnerRef,
145
146
  filters: DeleteMemoryFilters = {}
146
147
  ): Promise<DeleteMemoryResult> =>
147
- deleteMemoriesForOwnerFromDb(serverDb, owner, filters);
148
+ deleteMemoriesForOwnerFromDb(getServerAuthorityStore(), owner, filters);
@@ -1,4 +1,4 @@
1
- import serverDb from "../../database/server/db";
1
+ import { getServerAuthorityStore } from "../../database/server/db";
2
2
  import type {
3
3
  MemoryItem,
4
4
  MemoryKind,
@@ -25,7 +25,7 @@ export const loadOwnerItems = async (
25
25
  owner: MemoryOwnerRef,
26
26
  limit: number
27
27
  ): Promise<MemoryItem[]> => {
28
- return loadOwnerItemsFromDb(serverDb, owner, limit);
28
+ return loadOwnerItemsFromDb(getServerAuthorityStore(), owner, limit);
29
29
  };
30
30
 
31
31
  export const loadMemoryCandidates = async (input: {
@@ -34,5 +34,5 @@ export const loadMemoryCandidates = async (input: {
34
34
  kinds?: MemoryKind[];
35
35
  ownerLimit?: number;
36
36
  }): Promise<MemoryItem[]> => {
37
- return loadMemoryCandidatesFromDb(serverDb, input);
37
+ return loadMemoryCandidatesFromDb(getServerAuthorityStore(), input);
38
38
  };
@@ -1,4 +1,4 @@
1
- import serverDb from "../../database/server/db";
1
+ import { getServerAuthorityStore } from "../../database/server/db";
2
2
  import { createMemoryItem, writeMemoryItemWithIndexesToDb } from "./store";
3
3
  import type { MemoryKind, MemoryOwnerType, MemorySubjectType, MemoryVisibility } from "./types";
4
4
 
@@ -126,7 +126,7 @@ export const rememberMemory = async (
126
126
  throw new Error("rememberMemory: no valid owner scope found");
127
127
  }
128
128
 
129
- const db = input.db ?? serverDb;
129
+ const db = input.db ?? getServerAuthorityStore();
130
130
  const kind = input.kind ?? "episodic";
131
131
  if (!MEMORY_KINDS.has(kind)) {
132
132
  throw new Error("rememberMemory: kind must be episodic, semantic, or procedural");
@@ -1,4 +1,4 @@
1
- import serverDb from "../../database/server/db";
1
+ import { getServerAuthorityStore } from "../../database/server/db";
2
2
  import type { MemoryItem } from "./types";
3
3
  import {
4
4
  createMemoryItem,
@@ -9,12 +9,12 @@ import {
9
9
  export { createMemoryItem, writeMemoryItemWithIndexesToDb, touchMemoryItemsInDb };
10
10
 
11
11
  export const writeMemoryItemWithIndexes = async (item: MemoryItem): Promise<void> => {
12
- return writeMemoryItemWithIndexesToDb(serverDb, item);
12
+ return writeMemoryItemWithIndexesToDb(getServerAuthorityStore(), item);
13
13
  };
14
14
 
15
15
  export const touchMemoryItems = async (
16
16
  items: MemoryItem[],
17
17
  now = new Date().toISOString()
18
18
  ): Promise<void> => {
19
- return touchMemoryItemsInDb(serverDb, items, now);
19
+ return touchMemoryItemsInDb(getServerAuthorityStore(), items, now);
20
20
  };
@@ -4,6 +4,7 @@ import {
4
4
  createMemoryOwnerIndexKey,
5
5
  createMemorySubjectKindIndexKey,
6
6
  } from "../../database/keys";
7
+ import { createStoreBatch } from "../../database/server/storeBatchCompat";
7
8
  import type { MemoryItem } from "./types";
8
9
 
9
10
  export const createMemoryItem = (
@@ -23,7 +24,7 @@ export const writeMemoryItemWithIndexesToDb = async (
23
24
  db: any,
24
25
  item: MemoryItem
25
26
  ): Promise<void> => {
26
- const batch = db.batch();
27
+ const batch = createStoreBatch(db);
27
28
  batch.put(createMemoryKey(item.ownerType, item.ownerId, item.id), item);
28
29
  batch.put(
29
30
  createMemoryOwnerIndexKey(
@@ -64,7 +65,7 @@ export const touchMemoryItemsInDb = async (
64
65
  now = new Date().toISOString()
65
66
  ): Promise<void> => {
66
67
  if (items.length === 0) return;
67
- const batch = db.batch();
68
+ const batch = createStoreBatch(db);
68
69
  for (const item of items) {
69
70
  batch.put(createMemoryKey(item.ownerType, item.ownerId, item.id), {
70
71
  ...item,
@@ -0,0 +1,16 @@
1
+ export const DEFAULT_COMMERCIAL_MULTIPLIER = 8;
2
+ export const DEEPINFRA_CLAUDE_COMMERCIAL_MULTIPLIER = 9;
3
+
4
+ export const isDeepInfraHostedClaude = (provider: string, model: string) =>
5
+ provider === "deepinfra" && model.startsWith("anthropic/");
6
+
7
+ export const resolveCommercialMultiplier = (provider: string, model: string) =>
8
+ isDeepInfraHostedClaude(provider, model)
9
+ ? DEEPINFRA_CLAUDE_COMMERCIAL_MULTIPLIER
10
+ : DEFAULT_COMMERCIAL_MULTIPLIER;
11
+
12
+ export const scaleProviderPrice = (
13
+ rawProviderPrice: number,
14
+ provider: string,
15
+ model: string
16
+ ) => rawProviderPrice * resolveCommercialMultiplier(provider, model);