nolo-cli 0.1.26 → 0.1.29
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.
- package/agent-runtime/dialogStatus.ts +139 -0
- package/agent-runtime/index.ts +8 -0
- package/agentAliases.ts +11 -14
- package/agentCommandSupport.ts +2 -2
- package/agentCreateCustomCommands.ts +273 -0
- package/agentDialogsCommands.ts +226 -0
- package/agentDoctorCommands.ts +203 -0
- package/agentInternalCommandEntries.ts +11 -2
- package/agentListCommands.ts +27 -18
- package/agentMachineCommands.ts +97 -23
- package/agentPullCommand.ts +9 -9
- package/agentRecordHelpers.ts +61 -4
- package/agentRunCommand.ts +35 -410
- package/agentRunLocalWorkspace.ts +182 -0
- package/agentRunParsing.ts +279 -0
- package/agentSuperviseCommands.ts +8 -0
- package/agentUnpublishCommands.ts +112 -0
- package/ai/agent/_executeModel.ts +14 -14
- package/ai/agent/agentSlice.ts +8 -8
- package/ai/agent/appWorkingMemory.ts +2 -2
- package/ai/agent/avatarUtils.ts +1 -1
- package/ai/agent/buildEditingContext.ts +3 -3
- package/ai/agent/buildSystemPrompt.ts +16 -7
- package/ai/agent/cleanAgentMessages.ts +1 -1
- package/ai/agent/cliChatClient.ts +3 -3
- package/ai/agent/cliExecutor.ts +4 -2
- package/ai/agent/createAgentSchema.ts +1 -1
- package/ai/agent/executeToolCall.ts +2 -2
- package/ai/agent/fetchAgentContexts.ts +3 -3
- package/ai/agent/getFullChatContextKeys.ts +4 -4
- package/ai/agent/guidedCreation/draft.ts +1 -1
- package/ai/agent/guidedCreation/types.ts +1 -1
- package/ai/agent/hooks/fetchPublicAgents.ts +6 -6
- package/ai/agent/hooks/useAgentConfig.ts +49 -21
- package/ai/agent/hooks/useAgentDialog.ts +1 -1
- package/ai/agent/hooks/useAgentFormValidation.ts +9 -9
- package/ai/agent/hooks/usePublicAgents.ts +9 -9
- package/ai/agent/persistMessageWithFixedId.ts +4 -4
- package/ai/agent/planSlice.ts +1 -1
- package/ai/agent/referenceUtils.ts +4 -4
- package/ai/agent/runAgentBackground.ts +3 -3
- package/ai/agent/runAgentClientLoop.ts +12 -12
- package/ai/agent/runtimeGuidance.ts +1 -1
- package/ai/agent/server/fetchPublicAgents.ts +6 -6
- package/ai/agent/startParallelAgentStreams.ts +12 -12
- package/ai/agent/streamAgentChatTurn.ts +21 -21
- package/ai/agent/streamAgentChatTurnUtils.ts +22 -22
- package/ai/agent/utils/imageOutput.ts +2 -2
- package/ai/agent/utils/publicImageAgentMode.ts +1 -1
- package/ai/agent/utils/sortUtils.ts +1 -1
- package/ai/agent/web/useGuidedAgentCreation.ts +29 -8
- package/ai/chat/fetchUtils.native.ts +2 -2
- package/ai/chat/fetchUtils.ts +2 -2
- package/ai/chat/sendOpenAICompletionsRequest.native.ts +11 -11
- package/ai/chat/sendOpenAICompletionsRequest.ts +12 -12
- package/ai/chat/sendOpenAIResponseRequest.ts +14 -14
- package/ai/chat/shouldUseServerProxy.ts +1 -1
- package/ai/chat/updateTotalUsage.ts +1 -1
- package/ai/context/buildReferenceContext.ts +14 -14
- package/ai/context/calculateContextUsage.ts +1 -1
- package/ai/llm/generateRequestBody.ts +3 -3
- package/ai/llm/getPricing.ts +4 -4
- package/ai/llm/hooks/useModelPricing.ts +2 -2
- package/ai/llm/imagePricing.ts +1 -1
- package/ai/llm/models.ts +3 -3
- package/ai/llm/providers.ts +8 -8
- package/ai/memory/capture.ts +1 -1
- package/ai/memory/consolidate.ts +1 -1
- package/ai/memory/delete.ts +2 -2
- package/ai/memory/query.ts +1 -1
- package/ai/memory/queryShared.ts +1 -1
- package/ai/memory/recentRelationshipRecap.ts +2 -2
- package/ai/memory/remember.ts +1 -1
- package/ai/memory/store.ts +1 -1
- package/ai/memory/storeShared.ts +2 -2
- package/ai/memory/understanding.ts +1 -1
- package/ai/messages/type.ts +1 -1
- package/ai/policy/personalizationDialog.ts +6 -6
- package/ai/policy/runtimePolicy.ts +1 -1
- package/ai/skills/referenceRuntime.ts +1 -1
- package/ai/skills/skillDiagnostics.ts +1 -1
- package/ai/skills/skillDocBuilder.ts +1 -1
- package/ai/skills/skillReferenceSummary.ts +1 -1
- package/ai/skills/skillSummaryMarker.ts +1 -1
- package/ai/token/calculatePrice.ts +5 -5
- package/ai/token/db.ts +3 -3
- package/ai/token/externalToolCost.ts +4 -4
- package/ai/token/hooks/useRecords.ts +3 -3
- package/ai/token/modelUsageQuery.ts +2 -2
- package/ai/token/openaiImageGenerationUsage.ts +2 -2
- package/ai/token/prepareTokenUsageData.ts +1 -1
- package/ai/token/query.ts +1 -1
- package/ai/token/queryUserTokens.ts +1 -1
- package/ai/token/resolveBillingTarget.ts +1 -1
- package/ai/token/saveTokenRecord.ts +5 -5
- package/ai/token/serverDialogProjection.ts +4 -4
- package/ai/token/serverTokenWriter.ts +3 -3
- package/ai/token/tokenThunks.ts +1 -1
- package/ai/tools/agent/agentUpdateShared.ts +4 -4
- package/ai/tools/agent/callAgentTool.ts +3 -3
- package/ai/tools/agent/createAgentTool.ts +12 -12
- package/ai/tools/agent/createDialogTool.ts +3 -3
- package/ai/tools/agent/parallelBudget.ts +2 -2
- package/ai/tools/agent/prepareAgentDraftTool.ts +18 -4
- package/ai/tools/agent/presets/appBuilderPreset.ts +1 -1
- package/ai/tools/agent/runLlmTool.ts +1 -1
- package/ai/tools/agent/skillAgentPreset.ts +6 -6
- package/ai/tools/agent/updateAgentTool.ts +4 -4
- package/ai/tools/agent/updateSelfTool.ts +8 -8
- package/ai/tools/appTools.ts +3 -3
- package/ai/tools/category/createCategoryTool.ts +2 -2
- package/ai/tools/category/queryContentsByCategoryTool.ts +2 -2
- package/ai/tools/category/updateContentCategoryTool.ts +2 -2
- package/ai/tools/createDocTool.ts +3 -3
- package/ai/tools/createPlanTool.ts +9 -9
- package/ai/tools/createSkillDocTool.ts +4 -4
- package/ai/tools/createWorkflowTool.ts +2 -2
- package/ai/tools/deleteSpacesTool.ts +5 -5
- package/ai/tools/deleteSpacesToolModel.ts +1 -1
- package/ai/tools/doctorSkillTool.ts +3 -3
- package/ai/tools/evalSkillTool.ts +3 -3
- package/ai/tools/execShellTool.ts +1 -1
- package/ai/tools/executeSqlTool.ts +1 -1
- package/ai/tools/geminiImagePreviewTool.ts +9 -9
- package/ai/tools/importDataTool.ts +2 -2
- package/ai/tools/importSkillTool.ts +4 -4
- package/ai/tools/index.ts +37 -0
- package/ai/tools/listUserSpacesTool.ts +2 -2
- package/ai/tools/localFilesTool.ts +85 -9
- package/ai/tools/openaiImageTool.ts +9 -9
- package/ai/tools/readDocTool.ts +3 -3
- package/ai/tools/readTool.ts +9 -9
- package/ai/tools/rememberMemoryTool.ts +3 -3
- package/ai/tools/remotionVideoTool.ts +7 -7
- package/ai/tools/searchDialogMessagesTool.ts +2 -2
- package/ai/tools/searchWorkspaceTool.ts +4 -4
- package/ai/tools/table/addTableRowTool.ts +2 -2
- package/ai/tools/table/createTableTool.ts +2 -2
- package/ai/tools/table/rowTools.ts +2 -2
- package/ai/tools/table/schemaTools.ts +3 -3
- package/ai/tools/table/shareTableTool.ts +5 -5
- package/ai/tools/table/toolShared.ts +6 -6
- package/ai/tools/toolApiClient.ts +15 -6
- package/ai/tools/toolRunSlice.ts +2 -2
- package/ai/tools/updateContentTitleTool.ts +2 -2
- package/ai/tools/updateDocTool.ts +7 -7
- package/ai/tools/updateUserPreferenceProfileTool.ts +3 -3
- package/ai/workflow/workflowExecutor.ts +3 -3
- package/ai/workflow/workflowSlice.ts +1 -1
- package/app/actions/syncAppRecord.ts +73 -0
- package/app/admin/adminPages.ts +13 -0
- package/app/colors.ts +1 -0
- package/app/constants/animationSets.ts +21 -0
- package/app/constants/appEditor.ts +99 -0
- package/app/constants/clientDownloads.ts +54 -0
- package/app/constants/desktopReleaseManifest.ts +68 -0
- package/app/constants/homeTabs.ts +15 -0
- package/app/constants/routePaths.ts +15 -0
- package/app/email/emailApiRoutes.ts +14 -0
- package/app/favorite/favoriteSlice.ts +690 -0
- package/app/favorite/type.ts +43 -0
- package/app/favorite/useAgentFavorite.ts +43 -0
- package/app/favorite/useContentFavorite.ts +41 -0
- package/app/fetchOwnedApps.ts +269 -0
- package/app/guide/quickStartGuide.ts +128 -0
- package/app/hooks/deleteDbKey.ts +233 -0
- package/app/hooks/index.ts +4 -0
- package/app/hooks/useAppDetail.ts +208 -0
- package/app/hooks/useAppVersions.ts +52 -0
- package/app/hooks/useAutoResizeTextarea.ts +29 -0
- package/app/hooks/useChatPageTitle.ts +85 -0
- package/app/hooks/useClipboardFiles.ts +20 -0
- package/app/hooks/useDesktopLocalConnectorAutostart.ts +38 -0
- package/app/hooks/useDragResize.ts +91 -0
- package/app/hooks/useElementSizeVar.ts +24 -0
- package/app/hooks/useFileDropZone.ts +52 -0
- package/app/hooks/useHasMounted.ts +11 -0
- package/app/hooks/useImageLoadFallback.ts +19 -0
- package/app/hooks/useIsMobile.ts +46 -0
- package/app/hooks/useMyApps.ts +375 -0
- package/app/hooks/useMyContentItems.ts +91 -0
- package/app/hooks/useNewMessageNotification.ts +81 -0
- package/app/hooks/usePageMeta.ts +107 -0
- package/app/hooks/useRecentlyOpened.ts +84 -0
- package/app/hooks/useUnifiedStore.ts +11 -0
- package/app/hooks/useUserNotifications.ts +197 -0
- package/app/hooks.ts +55 -0
- package/app/i18n/clientResources.ts +65 -0
- package/app/i18n/i18n.base.ts +14 -0
- package/app/i18n/i18n.config.ts +62 -0
- package/app/i18n/i18n.server.ts +13 -0
- package/app/i18n/index.ts +15 -0
- package/app/i18n/mapLanguage.ts +11 -0
- package/app/i18n/translations/appBuilder.locale.ts +453 -0
- package/app/i18n/translations/error.locale.ts +246 -0
- package/app/i18n/translations/interface.locale.ts +2174 -0
- package/app/i18n/translations/seo.locale.ts +129 -0
- package/app/i18n/types.ts +6 -0
- package/app/notifications/formatNotification.ts +134 -0
- package/app/notifications/model.ts +77 -0
- package/app/notifications/notificationSlice.ts +141 -0
- package/app/notifications/useNotificationActions.ts +67 -0
- package/app/pages/homeTabState.ts +57 -0
- package/app/pages/quickChatFlow.ts +109 -0
- package/app/pages/rechargeCheckout.ts +23 -0
- package/app/pages/usePageArt.ts +91 -0
- package/app/realtime/sharedSse.ts +182 -0
- package/app/reducer.ts +36 -0
- package/app/seo/pageMeta.ts +123 -0
- package/app/settings/config.ts +54 -0
- package/app/settings/dbActionThunks.ts +34 -0
- package/app/settings/defaultSpacePreference.ts +87 -0
- package/app/settings/navItems.ts +73 -0
- package/app/settings/prepareUserSetting.ts +11 -0
- package/app/settings/settingsRecord.ts +8 -0
- package/app/settings/web/chat-config/useAutoSaveGlobalPrompt.ts +59 -0
- package/app/settings/web/machineStatus.ts +23 -0
- package/app/settings/web/useSettingsStylesheet.ts +28 -0
- package/app/settings/web/userSecurityUtils.ts +21 -0
- package/app/stateViews/runtime.ts +86 -0
- package/app/store.ts +53 -0
- package/app/theme/colors.ts +280 -0
- package/app/theme/fontPreference.ts +77 -0
- package/app/theme/index.ts +7 -0
- package/app/theme/theme.config.ts +120 -0
- package/app/theme/themeModeBootstrap.ts +123 -0
- package/app/theme/useSystemTheme.ts +33 -0
- package/app/types/appSummary.ts +114 -0
- package/app/types.ts +358 -0
- package/app/utils/appDeploySource.ts +50 -0
- package/app/utils/appKeys.ts +55 -0
- package/app/utils/appRuntimeUrl.ts +51 -0
- package/app/utils/async.ts +28 -0
- package/app/utils/asyncMapStatus.ts +31 -0
- package/app/utils/clipboard.ts +86 -0
- package/app/utils/credits.ts +12 -0
- package/app/utils/desktopAgentRuntimeStatusClient.ts +42 -0
- package/app/utils/desktopAgentRuntimeTurnClient.ts +70 -0
- package/app/utils/desktopLocalConnectorClient.ts +83 -0
- package/app/utils/env.ts +12 -0
- package/app/utils/excelToSlate.ts +430 -0
- package/app/utils/fileReaders.ts +12 -0
- package/app/utils/fileUtils.ts +229 -0
- package/app/utils/imageUtils.native.ts +96 -0
- package/app/utils/imageUtils.ts +244 -0
- package/app/utils/ime.ts +43 -0
- package/app/utils/myContentItems.ts +290 -0
- package/app/utils/processDateRange.ts +30 -0
- package/app/utils/retryFetch.ts +61 -0
- package/app/utils/slateToExcel.ts +58 -0
- package/app/utils/toast.native.ts +42 -0
- package/app/utils/toast.ts +3 -0
- package/app/web/spaceInitGuard.ts +28 -0
- package/auth/action/signOutAction.ts +0 -0
- package/auth/action/signUpAction.ts +227 -0
- package/auth/actor.ts +16 -0
- package/auth/authSlice.ts +517 -0
- package/auth/billing.ts +130 -0
- package/auth/client/deleteUserRequest.ts +86 -0
- package/auth/client/loginRequest.ts +14 -0
- package/auth/hooks/useAuth.ts +9 -0
- package/auth/hooks/useDeleteOwnAccount.ts +50 -0
- package/auth/hooks/useDeleteOwnAccountFlow.ts +66 -0
- package/auth/hooks/useDeleteUser.ts +45 -0
- package/auth/hooks/useEnableUser.ts +50 -0
- package/auth/hooks/useFetchUsers.ts +77 -0
- package/auth/hooks/useRechargeUser.ts +82 -0
- package/auth/index.ts +1 -0
- package/auth/invite.ts +19 -0
- package/auth/locale.ts +84 -0
- package/auth/resetAuthScopedClientState.ts +27 -0
- package/auth/rn/tokenManager.ts +72 -0
- package/auth/routes.ts +127 -0
- package/auth/server/accessActivity.ts +143 -0
- package/auth/server/billingFullChainSimulator.ts +325 -0
- package/auth/server/billingUsageReport.ts +192 -0
- package/auth/server/cliLogin.ts +198 -0
- package/auth/server/creatorEarningCreditConversion.ts +515 -0
- package/auth/server/creatorEarningsLedger.ts +165 -0
- package/auth/server/creatorEarningsReport.ts +299 -0
- package/auth/server/creatorSettlementLedger.ts +386 -0
- package/auth/server/creatorSettlementReport.ts +442 -0
- package/auth/server/creatorSplitConfig.ts +191 -0
- package/auth/server/deduct.ts +270 -0
- package/auth/server/delete.ts +887 -0
- package/auth/server/disable.ts +61 -0
- package/auth/server/emailAutomation.ts +358 -0
- package/auth/server/emailAutomationConfig.ts +88 -0
- package/auth/server/emailAutomationRules.ts +94 -0
- package/auth/server/emailAutomationTemplates.ts +131 -0
- package/auth/server/emailAutomationTypes.ts +38 -0
- package/auth/server/emailDbConfig.ts +147 -0
- package/auth/server/emailDelivery.ts +960 -0
- package/auth/server/emailDeliveryGuards.ts +282 -0
- package/auth/server/emailPolicy.ts +43 -0
- package/auth/server/emailPreferences.ts +117 -0
- package/auth/server/emailProvider.ts +277 -0
- package/auth/server/emailReport.ts +439 -0
- package/auth/server/emailRuntimeConfig.ts +86 -0
- package/auth/server/emailScenarioNotifications.ts +340 -0
- package/auth/server/enable.ts +61 -0
- package/auth/server/getRechargeHistory.ts +110 -0
- package/auth/server/getUser.ts +71 -0
- package/auth/server/inviteReward.ts +295 -0
- package/auth/server/inviteRewardEmail.ts +1 -0
- package/auth/server/ledger.ts +422 -0
- package/auth/server/ledgerAudit.ts +424 -0
- package/auth/server/ledgerWitness.ts +472 -0
- package/auth/server/listusers.ts +154 -0
- package/auth/server/locks.ts +32 -0
- package/auth/server/login.ts +184 -0
- package/auth/server/productBillingSplits.ts +166 -0
- package/auth/server/productEntitlements.ts +139 -0
- package/auth/server/productPurchase.ts +382 -0
- package/auth/server/recharge.ts +284 -0
- package/auth/server/revenueShareLedger.ts +389 -0
- package/auth/server/revenueShareReport.ts +258 -0
- package/auth/server/revenueSplitPolicy.ts +119 -0
- package/auth/server/revokeSessions.ts +59 -0
- package/auth/server/route.ts +195 -0
- package/auth/server/sendEmail.ts +176 -0
- package/auth/server/shared.ts +51 -0
- package/auth/server/signup.ts +423 -0
- package/auth/server/signupIpQuota.ts +44 -0
- package/auth/server/token.ts +109 -0
- package/auth/server/tokenUsageBilling.ts +312 -0
- package/auth/server/transfer.ts +40 -0
- package/auth/server/utils.ts +200 -0
- package/auth/sessionTokenVersion.ts +38 -0
- package/auth/token.ts +63 -0
- package/auth/tokenCookie.ts +1 -0
- package/auth/types.ts +28 -0
- package/auth/utils.ts +108 -0
- package/auth/web/bootstrapAuthState.ts +60 -0
- package/auth/web/tokenManager.ts +61 -0
- package/auth/web/useRegister.ts +70 -0
- package/build.ts +16 -0
- package/buildPublish.ts +133 -0
- package/buildPublishArtifactAssembly.ts +346 -0
- package/buildPublishImportAnalysis.ts +237 -0
- package/chat/chat.locale.ts +804 -0
- package/chat/dialog/actions/addCybotAction.ts +52 -0
- package/chat/dialog/actions/addReferenceKeysAction.ts +62 -0
- package/chat/dialog/actions/builtinDialogLlm.ts +35 -0
- package/chat/dialog/actions/cleanupCliSession.ts +40 -0
- package/chat/dialog/actions/compactDialogAndForkAction.ts +47 -0
- package/chat/dialog/actions/createDialogAction.ts +372 -0
- package/chat/dialog/actions/createScheduledTaskAction.ts +78 -0
- package/chat/dialog/actions/handleSendMessageAction.ts +197 -0
- package/chat/dialog/actions/handleSendMessageResolver.ts +29 -0
- package/chat/dialog/actions/removeCybotAction.ts +6 -0
- package/chat/dialog/actions/removeDialogAgentAction.ts +44 -0
- package/chat/dialog/actions/replacePrimaryCybotAction.ts +6 -0
- package/chat/dialog/actions/setPrimaryDialogAgentAction.ts +52 -0
- package/chat/dialog/actions/updateDialogSummaryAction.ts +405 -0
- package/chat/dialog/actions/updateDialogTitleAction.ts +151 -0
- package/chat/dialog/actions/updateDialogTitlePolicy.ts +30 -0
- package/chat/dialog/actions/updateTokensAction.ts +233 -0
- package/chat/dialog/dialogAgents.ts +54 -0
- package/chat/dialog/dialogPageRenderMode.ts +182 -0
- package/chat/dialog/dialogSlice.ts +872 -0
- package/chat/dialog/dialogTitle.ts +81 -0
- package/chat/dialog/dialogTokenStats.ts +12 -0
- package/chat/dialog/dialogUrl.ts +6 -0
- package/chat/dialog/ensureDialogSpaceAction.ts +208 -0
- package/chat/dialog/goal.ts +108 -0
- package/chat/dialog/hooks/useStreamingSymbol.ts +63 -0
- package/chat/dialog/objectAssistantRegistry.ts +286 -0
- package/chat/dialog/schedule.ts +17 -0
- package/chat/dialog/useCreateDialog.ts +52 -0
- package/chat/hooks/sendPermissionResolver.ts +128 -0
- package/chat/hooks/useChatInput.ts +99 -0
- package/chat/hooks/useChatInputSeed.ts +31 -0
- package/chat/hooks/useMessageInteraction.ts +412 -0
- package/chat/hooks/useSendPermission.ts +92 -0
- package/chat/hooks/useThinkingVisibility.ts +27 -0
- package/chat/messages/browserImageUrl.ts +48 -0
- package/chat/messages/deleteMessages.ts +47 -0
- package/chat/messages/fetchAndCacheMessages.ts +119 -0
- package/chat/messages/fetchConvMsgs.ts +51 -0
- package/chat/messages/fetchMessages.ts +84 -0
- package/chat/messages/fileUrl.ts +13 -0
- package/chat/messages/generateMessageKey.ts +21 -0
- package/chat/messages/hooks/useBase64Migration.ts +115 -0
- package/chat/messages/messageAgent.ts +8 -0
- package/chat/messages/messageContent.ts +199 -0
- package/chat/messages/messageContract.ts +88 -0
- package/chat/messages/messageSlice.ts +1191 -0
- package/chat/messages/pendingAttachmentParts.ts +117 -0
- package/chat/messages/sendFirstMessage.ts +193 -0
- package/chat/messages/toolPresentation.ts +212 -0
- package/chat/messages/toolThunks.ts +625 -0
- package/chat/messages/types.ts +176 -0
- package/chat/messages/web/ChatDisplayContext.ts +14 -0
- package/chat/messages/web/ToolMessageTypes.ts +23 -0
- package/chat/messages/web/diffViewerModel.ts +61 -0
- package/chat/messages/web/groupToolEntries.ts +44 -0
- package/chat/messages/web/groupToolMessages.ts +35 -0
- package/chat/messages/web/inlineReactArtifactParser.ts +63 -0
- package/chat/messages/web/toolDisplayName.ts +22 -0
- package/chat/messages/web/useLoopStopReason.ts +43 -0
- package/chat/messages/ziweiChartDoc.ts +94 -0
- package/chat/web/docxToSlate.ts +597 -0
- package/chat/web/fileProcessor.ts +442 -0
- package/chat/web/hooks/useProgressiveDisplayCount.ts +102 -0
- package/chat/web/messageInputAgentUi.ts +189 -0
- package/chat/web/messageInputKeyBehavior.ts +53 -0
- package/chat/web/messageInputMention.ts +102 -0
- package/chat/web/messageInputSendResolver.ts +51 -0
- package/chat/web/messageSlashCommands.ts +10 -0
- package/chat/web/pdfOcrProcessor.ts +131 -0
- package/chat/web/sidebar/allViewSearch.ts +87 -0
- package/chat/web/sidebar/types.ts +12 -0
- package/chat/web/sidebar/useChatSidebarFilteredData.ts +141 -0
- package/chat/web/sidebar/useSidebarDragAndDrop.ts +56 -0
- package/cliCommandFactories.ts +32 -0
- package/cliEnvHelpers.ts +96 -10
- package/cliIoTypes.ts +3 -0
- package/client/agentRun.ts +26 -229
- package/client/agentRunLocalExecution.test.ts +123 -0
- package/client/agentRunLocalExecution.ts +124 -0
- package/client/agentRunRuntimeSelection.test.ts +158 -0
- package/client/agentRunRuntimeSelection.ts +155 -0
- package/client/profileConfig.test.ts +66 -0
- package/client/profileConfig.ts +41 -0
- package/client/streamingOutput.ts +1 -3
- package/client/taskRunPrompt.ts +7 -24
- package/commandRegistry.ts +2 -2
- package/connector-experimental/daemonLauncher.ts +189 -0
- package/core/builtinAgents.ts +58 -0
- package/core/coin.ts +42 -0
- package/core/config.ts +15 -0
- package/core/crypto.ts +51 -0
- package/core/events/types.ts +145 -0
- package/core/generateKeyPairFromSeedV1.ts +15 -0
- package/core/generateMainKey.ts +22 -0
- package/core/init.ts +41 -0
- package/core/localOrigins.ts +8 -0
- package/core/password.ts +13 -0
- package/core/prefix.ts +23 -0
- package/create/editor/blockCommands.ts +118 -0
- package/create/editor/highlightExample.ts +66 -0
- package/create/editor/imageUpload.ts +66 -0
- package/create/editor/mark.ts +15 -0
- package/create/editor/plugins/normalizeChineseTypography.ts +85 -0
- package/create/editor/plugins/withBlockStructure.ts +53 -0
- package/create/editor/plugins/withChineseTypography.ts +61 -0
- package/create/editor/plugins/withLayout.ts +30 -0
- package/create/editor/plugins/withLinks.ts +13 -0
- package/create/editor/plugins/withMentions.ts +15 -0
- package/create/editor/plugins/withTables.ts +52 -0
- package/create/editor/tableCommands.ts +270 -0
- package/create/editor/theme/prism/default.ts +145 -0
- package/create/editor/theme/prism/githubDark.ts +139 -0
- package/create/editor/theme/prism/githubLight.ts +139 -0
- package/create/editor/theme/prism/index.ts +23 -0
- package/create/editor/theme/prism/okaidia.ts +197 -0
- package/create/editor/toolMentionOptions.ts +19 -0
- package/create/editor/transforms/fromMarkdown/index.ts +260 -0
- package/create/editor/transforms/fromMarkdown/inline.ts +285 -0
- package/create/editor/transforms/fromMarkdown/table.ts +130 -0
- package/create/editor/transforms/markdownToSlate.ts +24 -0
- package/create/editor/transforms/slateToRenderMarkdown.ts +218 -0
- package/create/editor/transforms/slateToSimplifiedMarkdown.ts +224 -0
- package/create/editor/transforms/slateToText.ts +33 -0
- package/create/editor/types.ts +120 -0
- package/create/editor/utils/editorFactory.ts +54 -0
- package/create/editor/utils/hasPlainCodeBlock.ts +39 -0
- package/create/editor/utils/linkCommands.ts +63 -0
- package/create/editor/utils/pdfToSlate.ts +706 -0
- package/create/editor/utils/slateUtils.ts +233 -0
- package/create/editor/utils/txtToSlate.ts +40 -0
- package/create/hooks/category.ts +82 -0
- package/create/routePaths.ts +5 -0
- package/create/space/addSpaceAction.ts +193 -0
- package/create/space/category/categoryActions.ts +427 -0
- package/create/space/changeSpaceAction.ts +36 -0
- package/create/space/constants.ts +8 -0
- package/create/space/content/addContentAction.ts +116 -0
- package/create/space/content/contentThunks.ts +90 -0
- package/create/space/content/deleteContentFromSpaceAction.ts +187 -0
- package/create/space/content/deleteMultipleContentAction.ts +112 -0
- package/create/space/content/moveContentAction.ts +285 -0
- package/create/space/content/updateContentCategoryAction.ts +154 -0
- package/create/space/content/updateContentTitleAction.ts +106 -0
- package/create/space/content/uploadAndAddFileToSpaceAction.ts +98 -0
- package/create/space/contentKeyUtils.ts +117 -0
- package/create/space/contentLabels.ts +56 -0
- package/create/space/contentTypeMeta.ts +169 -0
- package/create/space/deleteSpaceAction.ts +276 -0
- package/create/space/fetchSpaceAction.ts +70 -0
- package/create/space/fetchSpaceSidebarStateAction.ts +26 -0
- package/create/space/hooks/agentFetchRetry.ts +19 -0
- package/create/space/hooks/useAgentFetcher.ts +149 -0
- package/create/space/hooks/useGroupedContent.ts +118 -0
- package/create/space/hooks/useSpaceEvents.ts +43 -0
- package/create/space/initialSpace.ts +78 -0
- package/create/space/loadDefaultSpaceAction.ts +57 -0
- package/create/space/member/addMemberAction.ts +79 -0
- package/create/space/member/fetchUserSpaceMembershipsAction.ts +386 -0
- package/create/space/member/memberThunks.ts +47 -0
- package/create/space/member/removeMemberAction.ts +67 -0
- package/create/space/publicCatalogSpace.ts +39 -0
- package/create/space/resolvePreferredSpaceId.ts +113 -0
- package/create/space/sidebarVisibleTypes.ts +214 -0
- package/create/space/space.locale.ts +981 -0
- package/create/space/spaceAccess.ts +182 -0
- package/create/space/spaceCollapsedState.ts +54 -0
- package/create/space/spaceKeys.ts +65 -0
- package/create/space/spaceSlice.ts +328 -0
- package/create/space/spaceThunks.ts +410 -0
- package/create/space/types.ts +27 -0
- package/create/space/updateSpaceAction.ts +107 -0
- package/create/space/utils/permissions.ts +47 -0
- package/create/space/validateSpacePermission.ts +38 -0
- package/create/types.ts +21 -0
- package/create/version/appVersionReplication.ts +160 -0
- package/create/version/versionApi.ts +142 -0
- package/customCodingAgentFlow.ts +208 -0
- package/customCodingAgentRecord.ts +179 -0
- package/database/actions/agentReadResolution.ts +33 -0
- package/database/actions/cacheMergedUserData.ts +1 -1
- package/database/actions/common.ts +44 -8
- package/database/actions/fetchUserData.ts +1 -1
- package/database/actions/fileContent.ts +3 -3
- package/database/actions/patch.ts +3 -3
- package/database/actions/read.ts +115 -76
- package/database/actions/readAndWait.ts +54 -86
- package/database/actions/readOutcome.ts +45 -0
- package/database/actions/readResolution.ts +102 -0
- package/database/actions/remove.ts +2 -2
- package/database/actions/upload.ts +4 -4
- package/database/actions/upsert.ts +2 -2
- package/database/actions/write.ts +4 -4
- package/database/client/handleError.ts +1 -1
- package/database/client/queryRequest.ts +1 -1
- package/database/dbSlice.ts +2 -2
- package/database/email.ts +1 -1
- package/database/hooks/useUserData.ts +4 -4
- package/database/keys.ts +2 -2
- package/database/runtimeServerContext.ts +3 -3
- package/database/server/actorAccess.ts +1 -1
- package/database/server/cybotReadonly.ts +1 -1
- package/database/server/dataHandlers.ts +1 -1
- package/database/server/delete.ts +8 -8
- package/database/server/emailRepository.ts +7 -7
- package/database/server/fileService.ts +1 -1
- package/database/server/handleTransaction.ts +2 -2
- package/database/server/patch.ts +3 -3
- package/database/server/read.ts +5 -5
- package/database/server/resourceAccess.ts +2 -2
- package/database/server/routes.ts +3 -3
- package/database/server/write.ts +5 -5
- package/database/table/deleteTable.ts +1 -1
- package/database/userPreferenceRegister.ts +2 -2
- package/dialogDataAccess.ts +186 -0
- package/dialogInternalCommandEntries.ts +11 -0
- package/dialogReadCommands.ts +179 -0
- package/dialogReadHelpers.ts +226 -0
- package/dialogStatusCommands.ts +122 -0
- package/docInternalCommandEntries.ts +20 -0
- package/hybridReadHelpers.ts +109 -0
- package/index.ts +2 -6
- package/integrations/anthropic/anthropicModels.ts +47 -0
- package/integrations/anthropic/type.ts +41 -0
- package/integrations/deepseek/models.ts +67 -0
- package/integrations/google/models.ts +298 -0
- package/integrations/openai/chatCompletionStreamMode.ts +10 -0
- package/integrations/openai/filterAndCleanMessages.ts +284 -0
- package/integrations/openai/flexTier.ts +102 -0
- package/integrations/openai/generateOpenAIRequestBody.ts +274 -0
- package/integrations/openai/generateResponseRequestBody.ts +77 -0
- package/integrations/openai/models.ts +271 -0
- package/integrations/openai/providerBodyCompatibility.ts +23 -0
- package/integrations/openai/responsesHelpers.ts +297 -0
- package/integrations/postmark/index.ts +57 -0
- package/integrations/resend/index.ts +353 -0
- package/integrations/weather/getWeather.ts +24 -0
- package/integrations/weather/index.ts +6 -0
- package/integrations/weather/routes.ts +31 -0
- package/integrations/weather/weatherApi.ts +27 -0
- package/integrations/weather/weatherConstants.ts +2 -0
- package/integrations/weather/weatherI18n.ts +50 -0
- package/integrations/weather/weatherService.ts +50 -0
- package/integrations/weather/weatherTypes.ts +140 -0
- package/integrations/weather/weatherUtils.ts +46 -0
- package/integrations/x-reader/backends/localBrowser.ts +215 -0
- package/integrations/x-reader/backends/publicFallback.ts +31 -0
- package/integrations/x-reader/backends/rawCdp.ts +218 -0
- package/integrations/x-reader/bridge/chromeBridgeManager.ts +235 -0
- package/integrations/x-reader/bridge/readXPostWithBridge.ts +73 -0
- package/integrations/x-reader/fixtureParser.ts +101 -0
- package/integrations/x-reader/index.ts +9 -0
- package/integrations/x-reader/redaction.ts +27 -0
- package/integrations/x-reader/types.ts +109 -0
- package/integrations/x-reader/visibleTextParser.ts +108 -0
- package/integrations/xai/models.ts +13 -0
- package/internalCommandEntries.ts +8 -0
- package/machineCommandPrompts.ts +77 -0
- package/machineCommandResolution.ts +43 -0
- package/machineCommands.ts +89 -1107
- package/machineDaemonCommands.ts +29 -0
- package/machineHeartbeatCommands.ts +29 -0
- package/machineStatusCommands.ts +95 -0
- package/machineWatchCommands.ts +41 -0
- package/machineWsPromptMaterialization.ts +89 -0
- package/machineWsRunDispatch.ts +570 -0
- package/machineWsSession.ts +148 -0
- package/package.json +109 -5
- package/pageCreateCommands.ts +219 -0
- package/pageDeleteCommands.ts +167 -0
- package/pageReadCommands.ts +151 -0
- package/pageUpdateCommands.ts +249 -0
- package/pageWriteHelpers.ts +209 -0
- package/publishPackage.ts +36 -0
- package/render/canvas/canvasEditContext.ts +1 -1
- package/render/layout/mainLayoutViewMode.ts +1 -1
- package/render/page/createPageAction.ts +12 -12
- package/render/page/docSlice.ts +8 -8
- package/render/page/server/createPage.ts +7 -7
- package/render/page/server/handleCreatePage.ts +2 -2
- package/render/page/types.ts +2 -2
- package/render/surf/utils/groupedWeatherData.ts +1 -1
- package/render/table/createTableAction.ts +7 -7
- package/render/table/deleteTableAction.ts +4 -4
- package/render/table/fetchAndCacheTableRows.ts +2 -2
- package/render/table/tableSlice.ts +6 -6
- package/render/table/types.ts +1 -1
- package/render/table/useCreateTable.ts +2 -2
- package/render/table/useTable.ts +2 -2
- package/render/table/utils/tableSerialization.ts +1 -1
- package/runtimeInternalCommandEntries.ts +15 -0
- package/runtimePassthroughCommands.ts +22 -0
- package/scriptCommandEntries.ts +5 -45
- package/scriptPassthroughHelpers.ts +28 -0
- package/secretScanHelpers.ts +31 -0
- package/server/agentEmailRegistrationRoutes.ts +29 -0
- package/server/agentRunRouteContract.ts +9 -0
- package/server/agentRunRoutes.ts +10 -0
- package/server/api/methods.ts +333 -0
- package/server/api/tableHandlers.ts +55 -0
- package/server/api/types.ts +27 -0
- package/server/apiContract.ts +88 -0
- package/server/apiRouteAdapter.ts +218 -0
- package/server/appBundler.ts +90 -0
- package/server/appRoutes.ts +92 -0
- package/server/artifactIconsRoute.ts +89 -0
- package/server/artifactRuntimeRoute.ts +136 -0
- package/server/authenticateToken.ts +73 -0
- package/server/billingLedgerRoutes.ts +48 -0
- package/server/cliChatRoutes.ts +5 -0
- package/server/cloudflareRoutes.ts +35 -0
- package/server/coreHeaders.ts +29 -0
- package/server/coreReadiness.ts +39 -0
- package/server/coreRoutes.ts +65 -0
- package/server/coreRuntime.ts +93 -0
- package/server/createResponse.ts +68 -0
- package/server/cryptoPaymentRoutes.ts +8 -0
- package/server/databaseRoutes.ts +225 -0
- package/server/desktopRuntimeRoutes.ts +120 -0
- package/server/devBuildInfo.ts +51 -0
- package/server/devReload.ts +161 -0
- package/server/devToolPathPolicy.ts +59 -0
- package/server/devToolRoutes.ts +274 -0
- package/server/email/cloudflareEmailProvider.ts +119 -0
- package/server/email/cloudflareInboundBridge.ts +121 -0
- package/server/email/cloudflareInboundWorker.ts +28 -0
- package/server/email/provider.ts +149 -0
- package/server/email/providerRegistry.ts +22 -0
- package/server/emailInboundRoutes.ts +17 -0
- package/server/entry.ts +211 -0
- package/server/handleRPCRequest.ts +117 -0
- package/server/handlers/activityStatsHandler.ts +74 -0
- package/server/handlers/agentEmailRegistrationE2EHandler.ts +406 -0
- package/server/handlers/agentEmailRegistrationE2ERoutes.ts +6 -0
- package/server/handlers/agentRun/agentLookup.ts +77 -0
- package/server/handlers/agentRun/autonomousRuntime.ts +355 -0
- package/server/handlers/agentRun/backgroundRunDialog.ts +31 -0
- package/server/handlers/agentRun/builtinAgents.ts +347 -0
- package/server/handlers/agentRun/continueDialogContext.ts +90 -0
- package/server/handlers/agentRun/debugContext.ts +58 -0
- package/server/handlers/agentRun/dialogLookup.ts +67 -0
- package/server/handlers/agentRun/foregroundStreamDialog.ts +13 -0
- package/server/handlers/agentRun/index.ts +1630 -0
- package/server/handlers/agentRun/inheritedDialogPrompt.ts +111 -0
- package/server/handlers/agentRun/localRuntimeBootstrap.ts +69 -0
- package/server/handlers/agentRun/loop.ts +2210 -0
- package/server/handlers/agentRun/machineConnector.ts +235 -0
- package/server/handlers/agentRun/machineRunAudit.ts +49 -0
- package/server/handlers/agentRun/modelUsageToolHandlers.ts +368 -0
- package/server/handlers/agentRun/referenceRuntime.ts +50 -0
- package/server/handlers/agentRun/requestContext.ts +86 -0
- package/server/handlers/agentRun/response.ts +27 -0
- package/server/handlers/agentRun/runBilling.ts +108 -0
- package/server/handlers/agentRun/runDialogPreparation.ts +55 -0
- package/server/handlers/agentRun/runtimeBinding.ts +61 -0
- package/server/handlers/agentRun/runtimeContext.ts +143 -0
- package/server/handlers/agentRun/runtimeExecutionContext.ts +153 -0
- package/server/handlers/agentRun/runtimePreparation.ts +193 -0
- package/server/handlers/agentRun/runtimeRouting.ts +88 -0
- package/server/handlers/agentRun/runtimeSystemMessages.ts +165 -0
- package/server/handlers/agentRun/saveDialog.ts +1373 -0
- package/server/handlers/agentRun/syncRunDialog.ts +90 -0
- package/server/handlers/agentRun/tableActivityProjection.ts +132 -0
- package/server/handlers/agentRun/taskRunControlPrompt.ts +122 -0
- package/server/handlers/agentRun/taskRunToolHandler.ts +579 -0
- package/server/handlers/agentRun/toolExecutor.ts +2909 -0
- package/server/handlers/agentRun/toolPolicyGuards.ts +295 -0
- package/server/handlers/agentRun/types.ts +94 -0
- package/server/handlers/agentRun/workspaceLease.ts +58 -0
- package/server/handlers/alphaTestRouteGuard.ts +30 -0
- package/server/handlers/apifyActorHandler.ts +170 -0
- package/server/handlers/appDeployFlow.ts +876 -0
- package/server/handlers/appDeployHandler.ts +4 -0
- package/server/handlers/appDeployMutationHandlers.ts +133 -0
- package/server/handlers/appDeployReadHandlers.ts +321 -0
- package/server/handlers/appDeployShared.ts +230 -0
- package/server/handlers/appDeployStatusStore.ts +178 -0
- package/server/handlers/appDomainHandler.ts +476 -0
- package/server/handlers/appLegacyInfraCleanup.ts +7 -0
- package/server/handlers/appSandboxHandler.ts +1055 -0
- package/server/handlers/appSourceReadiness.ts +75 -0
- package/server/handlers/appSpaceAccess.ts +179 -0
- package/server/handlers/applyEditHandler.ts +544 -0
- package/server/handlers/applyLineEditsHandler.ts +1058 -0
- package/server/handlers/billingLedgerAuditHandler.ts +82 -0
- package/server/handlers/billingLedgerWitnessHandler.ts +161 -0
- package/server/handlers/billingUsageReportHandler.ts +90 -0
- package/server/handlers/browserToolHandler.ts +450 -0
- package/server/handlers/cfTextToSpeechHandler.ts +137 -0
- package/server/handlers/cfWhisperHandler.ts +206 -0
- package/server/handlers/chatBillingSse.ts +79 -0
- package/server/handlers/chatHandler.ts +797 -0
- package/server/handlers/chatProxyRouting.ts +404 -0
- package/server/handlers/chatUpstreamRetry.ts +162 -0
- package/server/handlers/checkEnvHandler.ts +250 -0
- package/server/handlers/cliChatHandler.ts +266 -0
- package/server/handlers/cloudflareBrowserHandler.ts +275 -0
- package/server/handlers/cloudflareCrawlHandler.ts +260 -0
- package/server/handlers/codeSearchHandler.ts +484 -0
- package/server/handlers/connector/connectorConnectionRegistry.ts +192 -0
- package/server/handlers/connector/connectorWebSocket.ts +117 -0
- package/server/handlers/creatorEarningsReportHandler.ts +97 -0
- package/server/handlers/creatorSettlementReportHandler.ts +98 -0
- package/server/handlers/deepseekOcrHandler.ts +114 -0
- package/server/handlers/deleteMemoryHandler.ts +115 -0
- package/server/handlers/desktopAgentRuntimeAdapter.ts +307 -0
- package/server/handlers/desktopAgentRuntimeHostFacts.ts +40 -0
- package/server/handlers/desktopAgentRuntimeStatusHandler.ts +54 -0
- package/server/handlers/desktopAgentRuntimeTurnHandler.ts +165 -0
- package/server/handlers/desktopAgentRuntimeTurnService.ts +352 -0
- package/server/handlers/desktopClipboardHandler.ts +104 -0
- package/server/handlers/desktopFiles/handler.ts +159 -0
- package/server/handlers/desktopFiles/operations.ts +202 -0
- package/server/handlers/desktopFiles/sandbox.ts +62 -0
- package/server/handlers/desktopFiles/store.ts +81 -0
- package/server/handlers/desktopLlamaRuntimeHandler.ts +360 -0
- package/server/handlers/desktopLocalConnectorHandler.ts +101 -0
- package/server/handlers/desktopUpdaterHandler.ts +132 -0
- package/server/handlers/dialogEvents.ts +10 -0
- package/server/handlers/emailInboundHandler.ts +65 -0
- package/server/handlers/eventBus.ts +160 -0
- package/server/handlers/exaSearchHandler.ts +73 -0
- package/server/handlers/execShellHandler.ts +661 -0
- package/server/handlers/favoriteHandlers.ts +417 -0
- package/server/handlers/fetchWebpageHandler.ts +117 -0
- package/server/handlers/fileOutlineHandler.ts +107 -0
- package/server/handlers/geminiImagePreviewHandler.ts +612 -0
- package/server/handlers/getDialogBillingHandler.ts +151 -0
- package/server/handlers/getTransactionsHandler.ts +107 -0
- package/server/handlers/googleNativeChat.ts +572 -0
- package/server/handlers/listFilesHandler.ts +139 -0
- package/server/handlers/machines/machineAuth.ts +149 -0
- package/server/handlers/machines/machineBinding.ts +59 -0
- package/server/handlers/machines/machineHandlers.ts +279 -0
- package/server/handlers/machines/machineInstallAssets.ts +563 -0
- package/server/handlers/machines/machineRegistry.ts +89 -0
- package/server/handlers/notificationEmitter.ts +189 -0
- package/server/handlers/notificationsHandler.ts +91 -0
- package/server/handlers/olmOcrHandler.ts +115 -0
- package/server/handlers/openaiImageHandler.ts +500 -0
- package/server/handlers/providerHealthHandler.ts +36 -0
- package/server/handlers/publicHandler.ts +209 -0
- package/server/handlers/readFileHandler.ts +300 -0
- package/server/handlers/readXPostHandler.ts +180 -0
- package/server/handlers/rememberMemoryHandler.ts +69 -0
- package/server/handlers/remotionRenderHandler.ts +236 -0
- package/server/handlers/renderMarkdownHandler.ts +66 -0
- package/server/handlers/revenueShareReportHandler.ts +96 -0
- package/server/handlers/searchRepoHandler.ts +159 -0
- package/server/handlers/tableAccess.ts +34 -0
- package/server/handlers/tableToolHandlers.ts +741 -0
- package/server/handlers/typecheckWorker.ts +54 -0
- package/server/handlers/userEvents.ts +6 -0
- package/server/handlers/userSecretsHandler.ts +210 -0
- package/server/handlers/versionHandler.ts +281 -0
- package/server/handlers/versionStore.ts +176 -0
- package/server/handlers/wereadGatewayHandler.ts +48 -0
- package/server/handlers/whisperHandler.ts +158 -0
- package/server/handlers/writeFileHandler.ts +168 -0
- package/server/html/desktopReleaseManifest.server.ts +17 -0
- package/server/html/generateErrorResponse.ts +22 -0
- package/server/html/serializeState.ts +9 -0
- package/server/html/ssrPreload.ts +247 -0
- package/server/html/template.ts +275 -0
- package/server/httpCompression.ts +102 -0
- package/server/index.ts +0 -0
- package/server/liveReloadScript.ts +105 -0
- package/server/luIconNames.ts +14 -0
- package/server/machineRoutes.ts +44 -0
- package/server/mediaRoutes.ts +25 -0
- package/server/memoryRoutes.ts +14 -0
- package/server/normalizedStatusRoutes.ts +23 -0
- package/server/payments/crypto/cryptoUsdcBaseAddressPool.ts +49 -0
- package/server/payments/crypto/cryptoUsdcBaseConfig.ts +120 -0
- package/server/payments/crypto/cryptoUsdcBasePaymentProvider.ts +134 -0
- package/server/payments/crypto/cryptoUsdcBaseScanner.ts +267 -0
- package/server/payments/crypto/cryptoUsdcBaseWatcher.ts +40 -0
- package/server/payments/crypto/cryptoUsdtTronAddressPool.ts +49 -0
- package/server/payments/crypto/cryptoUsdtTronConfig.ts +120 -0
- package/server/payments/crypto/cryptoUsdtTronPaymentProvider.ts +132 -0
- package/server/payments/crypto/cryptoUsdtTronScanner.ts +313 -0
- package/server/payments/crypto/cryptoUsdtTronWatcher.ts +40 -0
- package/server/payments/paymentProvider.ts +6 -0
- package/server/payments/paymentRoutes.ts +27 -0
- package/server/payments/rechargeCredits.ts +69 -0
- package/server/payments/waffo/waffoPaymentProvider.ts +341 -0
- package/server/preview/previewCapability.ts +90 -0
- package/server/preview/previewConfig.ts +54 -0
- package/server/preview/previewGateway.ts +71 -0
- package/server/preview/previewRealtime.ts +33 -0
- package/server/providerHealthProbe.ts +198 -0
- package/server/providerHealthRoutes.ts +19 -0
- package/server/publicPaths.ts +12 -0
- package/server/publicRequestHandler.ts +15 -0
- package/server/reactAppBuilder.ts +416 -0
- package/server/realtimeRoutes.ts +69 -0
- package/server/renderStream.ts +20 -0
- package/server/routeFactory.ts +45 -0
- package/server/routes.ts +125 -0
- package/server/safeTempFile.ts +48 -0
- package/server/scheduler/scheduledTaskRuntime.ts +228 -0
- package/server/scheduler/schedulerService.ts +290 -0
- package/server/serverDrain.ts +129 -0
- package/server/services/browserSessionManager.ts +354 -0
- package/server/shareRoutes.ts +86 -0
- package/server/sqliteRoutes.ts +141 -0
- package/server/taskRunBridgeRoutes.ts +95 -0
- package/server/tasks.ts +113 -0
- package/server/waffoPaymentRoutes.ts +5 -0
- package/server/webUtilityRoutes.ts +50 -0
- package/server/workerValidator.ts +224 -0
- package/share/action.ts +225 -0
- package/share/clientTableReplication.ts +160 -0
- package/share/helpers.ts +302 -0
- package/share/keys.ts +243 -0
- package/share/link.ts +40 -0
- package/share/loadOwnerShares.ts +154 -0
- package/share/paidAccess.ts +32 -0
- package/share/publicSharePolicy.ts +27 -0
- package/share/server/fetchCommunityShares.ts +45 -0
- package/share/server/helpers.ts +202 -0
- package/share/server/importShare.ts +148 -0
- package/share/server/listCommunityShares.ts +167 -0
- package/share/server/purchaseDoc.ts +224 -0
- package/share/server/readCommunityShareCover.ts +73 -0
- package/share/server/readSharedTable.ts +139 -0
- package/share/server/tableReplication.ts +351 -0
- package/share/shareSlice.ts +53 -0
- package/share/tableShareState.ts +74 -0
- package/share/types.ts +100 -0
- package/spaceCategoryCommands.ts +263 -0
- package/spaceCommands.ts +295 -0
- package/spaceDeleteCommands.ts +312 -0
- package/spaceInternalCommandEntries.ts +19 -0
- package/spaceMutationHelpers.ts +135 -0
- package/spaceReadCommands.ts +323 -0
- package/systemInternalCommandEntries.ts +16 -22
- package/tableCommands.ts +33 -133
- package/tableDataOutput.ts +41 -0
- package/tableDataSafety.ts +26 -0
- package/tableMetaCommands.ts +307 -0
- package/tableMutationCommands.ts +266 -0
- package/tableQueryParsing.ts +90 -0
- package/tableQueryRequest.ts +53 -0
- package/taskRunActions.ts +122 -0
- package/taskRunCommand.ts +8 -214
- package/taskRunParsing.ts +86 -0
- package/taskRunPromptShared.ts +55 -0
- package/tui/session.ts +43 -372
- package/tui/tuiCatalog.ts +22 -0
- package/tui/tuiCommandInterpreter.test.ts +169 -0
- package/tui/tuiCommandInterpreter.ts +253 -0
- package/tui/tuiPresentation.test.ts +154 -0
- package/tui/tuiPresentation.ts +146 -0
- package/workflowInternalCommandEntries.ts +20 -0
- package/offlineMarxistsAgentCommand.ts +0 -314
|
@@ -0,0 +1,960 @@
|
|
|
1
|
+
import { ulid } from "ulid";
|
|
2
|
+
import serverDb from "../../database/server/db";
|
|
3
|
+
import { DB_PREFIX } from "../../database/keys";
|
|
4
|
+
import {
|
|
5
|
+
emailProviderSupportsMarketingBroadcast,
|
|
6
|
+
sendProviderBatchEmails,
|
|
7
|
+
sendProviderEmail,
|
|
8
|
+
sendProviderMarketingBroadcast,
|
|
9
|
+
} from "./emailProvider";
|
|
10
|
+
import { balanceLockManager } from "./locks";
|
|
11
|
+
import { logger } from "./shared";
|
|
12
|
+
import {
|
|
13
|
+
getReengagementDeliveryMode,
|
|
14
|
+
shouldRunSchedulerOnThisInstance,
|
|
15
|
+
} from "./emailAutomationConfig";
|
|
16
|
+
import {
|
|
17
|
+
confirmIdempotencySent,
|
|
18
|
+
normalizeEmailTag,
|
|
19
|
+
releaseIdempotency,
|
|
20
|
+
reserveIdempotency,
|
|
21
|
+
shouldSuppressOnNonLeader,
|
|
22
|
+
type EmailIdempotencyReservation,
|
|
23
|
+
} from "./emailDeliveryGuards";
|
|
24
|
+
|
|
25
|
+
const EMAIL_RECORD_PREFIX = "email:delivery:record:";
|
|
26
|
+
const EMAIL_STATS_PREFIX = "email:delivery:stats:";
|
|
27
|
+
const EMAIL_RETRY_PREFIX = "email:delivery:retry:";
|
|
28
|
+
const EMAIL_MARKETING_SEGMENT_MEMBERS_PREFIX = "email:delivery:marketing:segment-members:";
|
|
29
|
+
|
|
30
|
+
const parseNumber = (value: string | undefined, fallback: number, min = 1) => {
|
|
31
|
+
const parsed = Number(value);
|
|
32
|
+
if (!Number.isFinite(parsed)) return fallback;
|
|
33
|
+
return Math.max(min, Math.floor(parsed));
|
|
34
|
+
};
|
|
35
|
+
const parseBoolean = (value: string | undefined, fallback: boolean) => {
|
|
36
|
+
if (value == null || value === "") return fallback;
|
|
37
|
+
return !["0", "false", "off", "no"].includes(String(value).toLowerCase());
|
|
38
|
+
};
|
|
39
|
+
const normalizeHost = (value: string | undefined) => {
|
|
40
|
+
const raw = String(value || "").trim().toLowerCase();
|
|
41
|
+
if (!raw) return "";
|
|
42
|
+
if (raw.startsWith("[") && raw.includes("]")) {
|
|
43
|
+
return raw.slice(1, raw.indexOf("]"));
|
|
44
|
+
}
|
|
45
|
+
return raw.split("/")[0].split(":")[0];
|
|
46
|
+
};
|
|
47
|
+
const resolveHostFromUrl = (value: string | undefined) => {
|
|
48
|
+
const raw = String(value || "").trim();
|
|
49
|
+
if (!raw) return "";
|
|
50
|
+
try {
|
|
51
|
+
return normalizeHost(new URL(raw).hostname);
|
|
52
|
+
} catch {
|
|
53
|
+
return "";
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
const getCurrentEmailHost = () =>
|
|
57
|
+
normalizeHost(process.env.EMAIL_APP_HOST || process.env.APP_HOST || process.env.HOST) ||
|
|
58
|
+
resolveHostFromUrl(process.env.EMAIL_APP_URL || process.env.APP_URL);
|
|
59
|
+
const getAllowedSignupHost = () =>
|
|
60
|
+
normalizeHost(process.env.EMAIL_SIGNUP_ALLOWED_HOST || "nolo.chat") || "nolo.chat";
|
|
61
|
+
const isFreezeModeEnabled = () =>
|
|
62
|
+
// 临时策略:仅放行 nolo.chat 的 signup-welcome;其余邮件类型统一冻结。
|
|
63
|
+
parseBoolean(process.env.EMAIL_ONLY_SIGNUP_WELCOME_ENABLED, false);
|
|
64
|
+
const getEmailFreezeDecision = (tag: string) => {
|
|
65
|
+
if (!isFreezeModeEnabled()) {
|
|
66
|
+
return {
|
|
67
|
+
allowed: true as const,
|
|
68
|
+
reason: "",
|
|
69
|
+
currentHost: "",
|
|
70
|
+
allowedHost: "",
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const normalizedTag = String(tag || "").trim().toLowerCase();
|
|
74
|
+
const currentHost = getCurrentEmailHost();
|
|
75
|
+
const allowedHost = getAllowedSignupHost();
|
|
76
|
+
const allowed = normalizedTag === "signup-welcome" && currentHost === allowedHost;
|
|
77
|
+
return {
|
|
78
|
+
allowed,
|
|
79
|
+
reason: allowed
|
|
80
|
+
? "allowed"
|
|
81
|
+
: normalizedTag !== "signup-welcome"
|
|
82
|
+
? "frozen_non_signup_welcome"
|
|
83
|
+
: "frozen_non_allowed_host",
|
|
84
|
+
currentHost,
|
|
85
|
+
allowedHost,
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
const getRetryConfig = () => ({
|
|
89
|
+
maxRetryAttempts: parseNumber(process.env.EMAIL_RETRY_MAX_ATTEMPTS, 3, 1),
|
|
90
|
+
retryDelayMs: parseNumber(process.env.EMAIL_RETRY_DELAY_MS, 5 * 60 * 1000, 1_000),
|
|
91
|
+
retryBatchSize: parseNumber(process.env.EMAIL_RETRY_BATCH_SIZE, 100, 1),
|
|
92
|
+
retryIntervalMinutes: parseNumber(process.env.EMAIL_RETRY_INTERVAL_MINUTES, 10, 1),
|
|
93
|
+
retryEnabled: !["0", "false", "off", "no"].includes(
|
|
94
|
+
String(process.env.EMAIL_RETRY_ENABLED ?? "1").toLowerCase()
|
|
95
|
+
),
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const normalizeEmailAddress = (value: string) => String(value || "").trim().toLowerCase();
|
|
99
|
+
|
|
100
|
+
const getReengagementMarketingSegmentId = () =>
|
|
101
|
+
String(process.env.EMAIL_REENGAGEMENT_MARKETING_SEGMENT_ID || "").trim();
|
|
102
|
+
|
|
103
|
+
const getMarketingSegmentMembersKey = (segmentId: string) =>
|
|
104
|
+
`${EMAIL_MARKETING_SEGMENT_MEMBERS_PREFIX}${segmentId}:reengagement`;
|
|
105
|
+
|
|
106
|
+
const isMarketingReengagementBatch = (payloads: ManagedEmailPayload[]) =>
|
|
107
|
+
payloads.length > 0 &&
|
|
108
|
+
getReengagementDeliveryMode() === "marketing" &&
|
|
109
|
+
payloads.every((payload) => normalizeEmailTag(payload.tag) === "reengagement");
|
|
110
|
+
|
|
111
|
+
const hasUniformBatchContent = (payloads: ManagedEmailPayload[]) => {
|
|
112
|
+
if (payloads.length <= 1) return true;
|
|
113
|
+
const first = payloads[0];
|
|
114
|
+
return payloads.every(
|
|
115
|
+
(payload) =>
|
|
116
|
+
payload.subject === first.subject &&
|
|
117
|
+
payload.textBody === first.textBody &&
|
|
118
|
+
payload.htmlBody === first.htmlBody
|
|
119
|
+
);
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const readMarketingSegmentMembers = async (segmentId: string) => {
|
|
123
|
+
const raw = (await serverDb.get(getMarketingSegmentMembersKey(segmentId)).catch(() => null)) as
|
|
124
|
+
| { emails?: unknown }
|
|
125
|
+
| null;
|
|
126
|
+
if (!raw || !Array.isArray(raw.emails)) return [];
|
|
127
|
+
return Array.from(
|
|
128
|
+
new Set(
|
|
129
|
+
raw.emails
|
|
130
|
+
.map((item) => normalizeEmailAddress(String(item || "")))
|
|
131
|
+
.filter(Boolean)
|
|
132
|
+
)
|
|
133
|
+
);
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const writeMarketingSegmentMembers = async (segmentId: string, emails: string[]) => {
|
|
137
|
+
const normalizedEmails = Array.from(
|
|
138
|
+
new Set(emails.map((email) => normalizeEmailAddress(email)).filter(Boolean))
|
|
139
|
+
);
|
|
140
|
+
await serverDb.put(getMarketingSegmentMembersKey(segmentId), {
|
|
141
|
+
emails: normalizedEmails,
|
|
142
|
+
updatedAt: Date.now(),
|
|
143
|
+
});
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const getDayKey = (time: number = Date.now()) =>
|
|
147
|
+
new Date(time).toISOString().slice(0, 10).replace(/-/g, "");
|
|
148
|
+
|
|
149
|
+
const padTimestamp = (time: number) => String(Math.max(0, Math.floor(time))).padStart(13, "0");
|
|
150
|
+
|
|
151
|
+
const getStatsKey = (dayKey: string, tag: string) =>
|
|
152
|
+
`${EMAIL_STATS_PREFIX}${dayKey}:${tag || "untagged"}`;
|
|
153
|
+
|
|
154
|
+
const getRetryKey = (nextRetryAt: number, retryId: string) =>
|
|
155
|
+
`${EMAIL_RETRY_PREFIX}${padTimestamp(nextRetryAt)}:${retryId}`;
|
|
156
|
+
|
|
157
|
+
type DeliveryStatus = "sent" | "failed";
|
|
158
|
+
|
|
159
|
+
export interface ManagedEmailPayload {
|
|
160
|
+
userId?: string;
|
|
161
|
+
to: string;
|
|
162
|
+
subject: string;
|
|
163
|
+
textBody?: string;
|
|
164
|
+
htmlBody?: string;
|
|
165
|
+
tag: string;
|
|
166
|
+
metadata?: Record<string, any>;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
interface RetryJob {
|
|
170
|
+
retryId: string;
|
|
171
|
+
payload: ManagedEmailPayload;
|
|
172
|
+
attempt: number;
|
|
173
|
+
maxAttempts: number;
|
|
174
|
+
nextRetryAt: number;
|
|
175
|
+
lastError?: string;
|
|
176
|
+
createdAt: number;
|
|
177
|
+
updatedAt: number;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
interface SendManagedEmailOptions {
|
|
181
|
+
enqueueOnFail?: boolean;
|
|
182
|
+
attempt?: number;
|
|
183
|
+
maxAttempts?: number;
|
|
184
|
+
retryDelayMs?: number;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export interface SendManagedEmailResult {
|
|
188
|
+
success: boolean;
|
|
189
|
+
queued: boolean;
|
|
190
|
+
error?: string;
|
|
191
|
+
suppressed?: boolean;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export interface SendManagedEmailBatchItemResult extends SendManagedEmailResult {
|
|
195
|
+
userId?: string;
|
|
196
|
+
to: string;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
interface RecordStatsDelta {
|
|
200
|
+
sent?: number;
|
|
201
|
+
failed?: number;
|
|
202
|
+
retried?: number;
|
|
203
|
+
queued?: number;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
interface EmailDeliveryRecord {
|
|
207
|
+
id: string;
|
|
208
|
+
timestamp: number;
|
|
209
|
+
status: DeliveryStatus;
|
|
210
|
+
userId?: string;
|
|
211
|
+
to: string;
|
|
212
|
+
subject: string;
|
|
213
|
+
tag: string;
|
|
214
|
+
attempt: number;
|
|
215
|
+
error?: string;
|
|
216
|
+
metadata?: Record<string, any>;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
let retryTimer: ReturnType<typeof setInterval> | null = null;
|
|
220
|
+
let retryRunning = false;
|
|
221
|
+
|
|
222
|
+
const incrementStats = async (
|
|
223
|
+
dayKey: string,
|
|
224
|
+
tag: string,
|
|
225
|
+
delta: RecordStatsDelta
|
|
226
|
+
) => {
|
|
227
|
+
const statsKey = getStatsKey(dayKey, tag);
|
|
228
|
+
const statsLock = balanceLockManager.getLock(`email-stats:${statsKey}`);
|
|
229
|
+
await statsLock.runExclusive(async () => {
|
|
230
|
+
const currentRaw = await serverDb.get(statsKey).catch(() => null);
|
|
231
|
+
const current =
|
|
232
|
+
currentRaw && typeof currentRaw === "object" && !Array.isArray(currentRaw)
|
|
233
|
+
? (currentRaw as Record<string, any>)
|
|
234
|
+
: {};
|
|
235
|
+
await serverDb.put(statsKey, {
|
|
236
|
+
...current,
|
|
237
|
+
dayKey,
|
|
238
|
+
tag,
|
|
239
|
+
sent: Number(current.sent || 0) + Number(delta.sent || 0),
|
|
240
|
+
failed: Number(current.failed || 0) + Number(delta.failed || 0),
|
|
241
|
+
retried: Number(current.retried || 0) + Number(delta.retried || 0),
|
|
242
|
+
queued: Number(current.queued || 0) + Number(delta.queued || 0),
|
|
243
|
+
updatedAt: Date.now(),
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const writeDeliveryRecord = async (record: EmailDeliveryRecord) => {
|
|
249
|
+
await serverDb.put(`${EMAIL_RECORD_PREFIX}${record.id}`, record);
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const enqueueRetryJob = async (job: RetryJob) => {
|
|
253
|
+
await serverDb.put(getRetryKey(job.nextRetryAt, job.retryId), job);
|
|
254
|
+
await incrementStats(getDayKey(job.updatedAt), job.payload.tag, { queued: 1 });
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const markWelcomeEmailSent = async (userId: string, sentAt: number) => {
|
|
258
|
+
const lock = balanceLockManager.getLock(userId);
|
|
259
|
+
await lock.runExclusive(async () => {
|
|
260
|
+
const key = `${DB_PREFIX.USER}${userId}`;
|
|
261
|
+
const current = await serverDb.get(key).catch(() => null);
|
|
262
|
+
if (!current || typeof current !== "object") return;
|
|
263
|
+
await serverDb.put(key, {
|
|
264
|
+
...current,
|
|
265
|
+
welcomeEmailSentAt: sentAt,
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
interface FinalizeManagedEmailAttemptArgs {
|
|
271
|
+
payload: ManagedEmailPayload;
|
|
272
|
+
status: DeliveryStatus;
|
|
273
|
+
errorMessage?: string;
|
|
274
|
+
attempt: number;
|
|
275
|
+
maxAttempts: number;
|
|
276
|
+
retryDelayMs: number;
|
|
277
|
+
enqueueOnFail: boolean;
|
|
278
|
+
suppressed?: boolean;
|
|
279
|
+
metadata?: Record<string, any>;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const finalizeManagedEmailAttempt = async ({
|
|
283
|
+
payload,
|
|
284
|
+
status,
|
|
285
|
+
errorMessage,
|
|
286
|
+
attempt,
|
|
287
|
+
maxAttempts,
|
|
288
|
+
retryDelayMs,
|
|
289
|
+
enqueueOnFail,
|
|
290
|
+
suppressed = false,
|
|
291
|
+
metadata,
|
|
292
|
+
}: FinalizeManagedEmailAttemptArgs): Promise<SendManagedEmailResult> => {
|
|
293
|
+
const now = Date.now();
|
|
294
|
+
const tag = payload.tag || "untagged";
|
|
295
|
+
|
|
296
|
+
await writeDeliveryRecord({
|
|
297
|
+
id: ulid(now),
|
|
298
|
+
timestamp: now,
|
|
299
|
+
status,
|
|
300
|
+
userId: payload.userId,
|
|
301
|
+
to: payload.to,
|
|
302
|
+
subject: payload.subject,
|
|
303
|
+
tag,
|
|
304
|
+
attempt,
|
|
305
|
+
error: errorMessage,
|
|
306
|
+
metadata: metadata ?? payload.metadata,
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
await incrementStats(getDayKey(now), tag, {
|
|
310
|
+
sent: status === "sent" ? 1 : 0,
|
|
311
|
+
failed: status === "failed" ? 1 : 0,
|
|
312
|
+
retried: attempt > 1 && status === "sent" ? 1 : 0,
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
if (status === "sent") {
|
|
316
|
+
return { success: true as const, queued: false };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (suppressed) {
|
|
320
|
+
return {
|
|
321
|
+
success: false as const,
|
|
322
|
+
queued: false,
|
|
323
|
+
suppressed: true,
|
|
324
|
+
error: errorMessage,
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (!enqueueOnFail || attempt >= maxAttempts) {
|
|
329
|
+
return { success: false as const, queued: false, error: errorMessage };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const retryId = ulid(now);
|
|
333
|
+
const nextRetryAt = now + retryDelayMs * attempt;
|
|
334
|
+
await enqueueRetryJob({
|
|
335
|
+
retryId,
|
|
336
|
+
payload,
|
|
337
|
+
attempt,
|
|
338
|
+
maxAttempts,
|
|
339
|
+
nextRetryAt,
|
|
340
|
+
lastError: errorMessage,
|
|
341
|
+
createdAt: now,
|
|
342
|
+
updatedAt: now,
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
return { success: false as const, queued: true, error: errorMessage };
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
export async function sendManagedEmail(
|
|
349
|
+
payload: ManagedEmailPayload,
|
|
350
|
+
options: SendManagedEmailOptions = {}
|
|
351
|
+
): Promise<SendManagedEmailResult> {
|
|
352
|
+
const retryConfig = getRetryConfig();
|
|
353
|
+
const attempt = options.attempt ?? 1;
|
|
354
|
+
const maxAttempts = options.maxAttempts ?? retryConfig.maxRetryAttempts;
|
|
355
|
+
const retryDelayMs = options.retryDelayMs ?? retryConfig.retryDelayMs;
|
|
356
|
+
const enqueueOnFail = options.enqueueOnFail ?? true;
|
|
357
|
+
const tag = normalizeEmailTag(payload.tag);
|
|
358
|
+
const normalizedPayload: ManagedEmailPayload = { ...payload, tag };
|
|
359
|
+
|
|
360
|
+
if (tag === "reengagement" && getReengagementDeliveryMode() === "marketing") {
|
|
361
|
+
const [result] = await sendManagedEmailBatch([normalizedPayload], options);
|
|
362
|
+
return {
|
|
363
|
+
success: Boolean(result?.success),
|
|
364
|
+
queued: Boolean(result?.queued),
|
|
365
|
+
error: result?.error,
|
|
366
|
+
suppressed: result?.suppressed,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (shouldSuppressOnNonLeader(tag)) {
|
|
371
|
+
const errorMessage = "Email suppressed by leader-only policy (non_leader_instance)";
|
|
372
|
+
logger.warn(
|
|
373
|
+
{
|
|
374
|
+
tag,
|
|
375
|
+
userId: normalizedPayload.userId,
|
|
376
|
+
to: normalizedPayload.to,
|
|
377
|
+
reason: "non_leader_instance",
|
|
378
|
+
},
|
|
379
|
+
"Email suppressed by leader-only policy"
|
|
380
|
+
);
|
|
381
|
+
return finalizeManagedEmailAttempt({
|
|
382
|
+
payload: normalizedPayload,
|
|
383
|
+
status: "failed",
|
|
384
|
+
errorMessage,
|
|
385
|
+
attempt,
|
|
386
|
+
maxAttempts,
|
|
387
|
+
retryDelayMs,
|
|
388
|
+
enqueueOnFail,
|
|
389
|
+
suppressed: true,
|
|
390
|
+
metadata: {
|
|
391
|
+
...(normalizedPayload.metadata || {}),
|
|
392
|
+
suppressedByLeaderOnly: true,
|
|
393
|
+
suppressionReason: "non_leader_instance",
|
|
394
|
+
},
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const freezeDecision = getEmailFreezeDecision(tag);
|
|
399
|
+
|
|
400
|
+
if (!freezeDecision.allowed) {
|
|
401
|
+
const errorMessage = `Email suppressed by freeze policy (${freezeDecision.reason})`;
|
|
402
|
+
logger.warn(
|
|
403
|
+
{
|
|
404
|
+
tag,
|
|
405
|
+
userId: normalizedPayload.userId,
|
|
406
|
+
to: normalizedPayload.to,
|
|
407
|
+
reason: freezeDecision.reason,
|
|
408
|
+
currentHost: freezeDecision.currentHost,
|
|
409
|
+
allowedHost: freezeDecision.allowedHost,
|
|
410
|
+
},
|
|
411
|
+
"Email suppressed by freeze policy"
|
|
412
|
+
);
|
|
413
|
+
return finalizeManagedEmailAttempt({
|
|
414
|
+
payload: normalizedPayload,
|
|
415
|
+
status: "failed",
|
|
416
|
+
errorMessage,
|
|
417
|
+
attempt,
|
|
418
|
+
maxAttempts,
|
|
419
|
+
retryDelayMs,
|
|
420
|
+
enqueueOnFail,
|
|
421
|
+
suppressed: true,
|
|
422
|
+
metadata: {
|
|
423
|
+
...(normalizedPayload.metadata || {}),
|
|
424
|
+
suppressedByFreeze: true,
|
|
425
|
+
suppressionReason: freezeDecision.reason,
|
|
426
|
+
currentHost: freezeDecision.currentHost,
|
|
427
|
+
allowedHost: freezeDecision.allowedHost,
|
|
428
|
+
},
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const idempotencyDecision = await reserveIdempotency(normalizedPayload, tag);
|
|
433
|
+
if (!idempotencyDecision.allowed) {
|
|
434
|
+
const errorMessage = `Email suppressed by idempotency policy (${idempotencyDecision.reason})`;
|
|
435
|
+
logger.warn(
|
|
436
|
+
{
|
|
437
|
+
tag,
|
|
438
|
+
userId: normalizedPayload.userId,
|
|
439
|
+
to: normalizedPayload.to,
|
|
440
|
+
reason: idempotencyDecision.reason,
|
|
441
|
+
},
|
|
442
|
+
"Email suppressed by idempotency policy"
|
|
443
|
+
);
|
|
444
|
+
return finalizeManagedEmailAttempt({
|
|
445
|
+
payload: normalizedPayload,
|
|
446
|
+
status: "failed",
|
|
447
|
+
errorMessage,
|
|
448
|
+
attempt,
|
|
449
|
+
maxAttempts,
|
|
450
|
+
retryDelayMs,
|
|
451
|
+
enqueueOnFail,
|
|
452
|
+
suppressed: true,
|
|
453
|
+
metadata: {
|
|
454
|
+
...(normalizedPayload.metadata || {}),
|
|
455
|
+
suppressedByIdempotency: true,
|
|
456
|
+
suppressionReason: idempotencyDecision.reason,
|
|
457
|
+
},
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const reservation = idempotencyDecision.reservation;
|
|
462
|
+
|
|
463
|
+
let status: DeliveryStatus = "sent";
|
|
464
|
+
let errorMessage: string | undefined;
|
|
465
|
+
try {
|
|
466
|
+
await sendProviderEmail({
|
|
467
|
+
to: normalizedPayload.to,
|
|
468
|
+
subject: normalizedPayload.subject,
|
|
469
|
+
textBody: normalizedPayload.textBody,
|
|
470
|
+
htmlBody: normalizedPayload.htmlBody,
|
|
471
|
+
tag,
|
|
472
|
+
});
|
|
473
|
+
} catch (error: any) {
|
|
474
|
+
status = "failed";
|
|
475
|
+
errorMessage = error?.message || String(error);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
if (status === "sent") {
|
|
479
|
+
await confirmIdempotencySent(reservation);
|
|
480
|
+
} else {
|
|
481
|
+
await releaseIdempotency(reservation);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
return finalizeManagedEmailAttempt({
|
|
485
|
+
payload: normalizedPayload,
|
|
486
|
+
status,
|
|
487
|
+
errorMessage,
|
|
488
|
+
attempt,
|
|
489
|
+
maxAttempts,
|
|
490
|
+
retryDelayMs,
|
|
491
|
+
enqueueOnFail,
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export async function sendManagedEmailBatch(
|
|
496
|
+
payloads: ManagedEmailPayload[],
|
|
497
|
+
options: SendManagedEmailOptions = {}
|
|
498
|
+
): Promise<SendManagedEmailBatchItemResult[]> {
|
|
499
|
+
if (!Array.isArray(payloads) || payloads.length === 0) return [];
|
|
500
|
+
|
|
501
|
+
const retryConfig = getRetryConfig();
|
|
502
|
+
const attempt = options.attempt ?? 1;
|
|
503
|
+
const maxAttempts = options.maxAttempts ?? retryConfig.maxRetryAttempts;
|
|
504
|
+
const retryDelayMs = options.retryDelayMs ?? retryConfig.retryDelayMs;
|
|
505
|
+
const enqueueOnFail = options.enqueueOnFail ?? true;
|
|
506
|
+
|
|
507
|
+
const results: Array<SendManagedEmailBatchItemResult | undefined> = new Array(
|
|
508
|
+
payloads.length
|
|
509
|
+
);
|
|
510
|
+
const batchPayloads: ManagedEmailPayload[] = [];
|
|
511
|
+
const batchIndexes: number[] = [];
|
|
512
|
+
const batchReservations: Array<EmailIdempotencyReservation | null> = [];
|
|
513
|
+
|
|
514
|
+
for (let index = 0; index < payloads.length; index += 1) {
|
|
515
|
+
const payload = payloads[index];
|
|
516
|
+
const tag = normalizeEmailTag(payload.tag);
|
|
517
|
+
const normalizedPayload: ManagedEmailPayload = { ...payload, tag };
|
|
518
|
+
|
|
519
|
+
if (shouldSuppressOnNonLeader(tag)) {
|
|
520
|
+
const errorMessage = "Email suppressed by leader-only policy (non_leader_instance)";
|
|
521
|
+
logger.warn(
|
|
522
|
+
{
|
|
523
|
+
tag,
|
|
524
|
+
userId: normalizedPayload.userId,
|
|
525
|
+
to: normalizedPayload.to,
|
|
526
|
+
reason: "non_leader_instance",
|
|
527
|
+
},
|
|
528
|
+
"Email suppressed by leader-only policy"
|
|
529
|
+
);
|
|
530
|
+
const result = await finalizeManagedEmailAttempt({
|
|
531
|
+
payload: normalizedPayload,
|
|
532
|
+
status: "failed",
|
|
533
|
+
errorMessage,
|
|
534
|
+
attempt,
|
|
535
|
+
maxAttempts,
|
|
536
|
+
retryDelayMs,
|
|
537
|
+
enqueueOnFail,
|
|
538
|
+
suppressed: true,
|
|
539
|
+
metadata: {
|
|
540
|
+
...(normalizedPayload.metadata || {}),
|
|
541
|
+
suppressedByLeaderOnly: true,
|
|
542
|
+
suppressionReason: "non_leader_instance",
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
results[index] = {
|
|
546
|
+
...result,
|
|
547
|
+
userId: normalizedPayload.userId,
|
|
548
|
+
to: normalizedPayload.to,
|
|
549
|
+
};
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
const freezeDecision = getEmailFreezeDecision(tag);
|
|
554
|
+
|
|
555
|
+
if (!freezeDecision.allowed) {
|
|
556
|
+
const errorMessage = `Email suppressed by freeze policy (${freezeDecision.reason})`;
|
|
557
|
+
logger.warn(
|
|
558
|
+
{
|
|
559
|
+
tag,
|
|
560
|
+
userId: normalizedPayload.userId,
|
|
561
|
+
to: normalizedPayload.to,
|
|
562
|
+
reason: freezeDecision.reason,
|
|
563
|
+
currentHost: freezeDecision.currentHost,
|
|
564
|
+
allowedHost: freezeDecision.allowedHost,
|
|
565
|
+
},
|
|
566
|
+
"Email suppressed by freeze policy"
|
|
567
|
+
);
|
|
568
|
+
const result = await finalizeManagedEmailAttempt({
|
|
569
|
+
payload: normalizedPayload,
|
|
570
|
+
status: "failed",
|
|
571
|
+
errorMessage,
|
|
572
|
+
attempt,
|
|
573
|
+
maxAttempts,
|
|
574
|
+
retryDelayMs,
|
|
575
|
+
enqueueOnFail,
|
|
576
|
+
suppressed: true,
|
|
577
|
+
metadata: {
|
|
578
|
+
...(normalizedPayload.metadata || {}),
|
|
579
|
+
suppressedByFreeze: true,
|
|
580
|
+
suppressionReason: freezeDecision.reason,
|
|
581
|
+
currentHost: freezeDecision.currentHost,
|
|
582
|
+
allowedHost: freezeDecision.allowedHost,
|
|
583
|
+
},
|
|
584
|
+
});
|
|
585
|
+
results[index] = {
|
|
586
|
+
...result,
|
|
587
|
+
userId: payload.userId,
|
|
588
|
+
to: payload.to,
|
|
589
|
+
};
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const idempotencyDecision = await reserveIdempotency(normalizedPayload, tag);
|
|
594
|
+
if (!idempotencyDecision.allowed) {
|
|
595
|
+
const errorMessage = `Email suppressed by idempotency policy (${idempotencyDecision.reason})`;
|
|
596
|
+
logger.warn(
|
|
597
|
+
{
|
|
598
|
+
tag,
|
|
599
|
+
userId: normalizedPayload.userId,
|
|
600
|
+
to: normalizedPayload.to,
|
|
601
|
+
reason: idempotencyDecision.reason,
|
|
602
|
+
},
|
|
603
|
+
"Email suppressed by idempotency policy"
|
|
604
|
+
);
|
|
605
|
+
const result = await finalizeManagedEmailAttempt({
|
|
606
|
+
payload: normalizedPayload,
|
|
607
|
+
status: "failed",
|
|
608
|
+
errorMessage,
|
|
609
|
+
attempt,
|
|
610
|
+
maxAttempts,
|
|
611
|
+
retryDelayMs,
|
|
612
|
+
enqueueOnFail,
|
|
613
|
+
suppressed: true,
|
|
614
|
+
metadata: {
|
|
615
|
+
...(normalizedPayload.metadata || {}),
|
|
616
|
+
suppressedByIdempotency: true,
|
|
617
|
+
suppressionReason: idempotencyDecision.reason,
|
|
618
|
+
},
|
|
619
|
+
});
|
|
620
|
+
results[index] = {
|
|
621
|
+
...result,
|
|
622
|
+
userId: normalizedPayload.userId,
|
|
623
|
+
to: normalizedPayload.to,
|
|
624
|
+
};
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
batchPayloads.push(normalizedPayload);
|
|
629
|
+
batchIndexes.push(index);
|
|
630
|
+
batchReservations.push(idempotencyDecision.reservation);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
if (batchPayloads.length > 0) {
|
|
634
|
+
const perItemErrors = new Map<number, string>();
|
|
635
|
+
let batchError: string | undefined;
|
|
636
|
+
let suppressFailedResults = false;
|
|
637
|
+
const useMarketingBatch =
|
|
638
|
+
isMarketingReengagementBatch(batchPayloads) && hasUniformBatchContent(batchPayloads);
|
|
639
|
+
|
|
640
|
+
if (useMarketingBatch && emailProviderSupportsMarketingBroadcast()) {
|
|
641
|
+
const segmentId = getReengagementMarketingSegmentId();
|
|
642
|
+
if (!segmentId) {
|
|
643
|
+
batchError = "EMAIL_REENGAGEMENT_MARKETING_SEGMENT_ID is not defined";
|
|
644
|
+
suppressFailedResults = true;
|
|
645
|
+
} else {
|
|
646
|
+
const firstPayload = batchPayloads[0];
|
|
647
|
+
if (!firstPayload) {
|
|
648
|
+
batchError = "Batch payload missing";
|
|
649
|
+
suppressFailedResults = true;
|
|
650
|
+
} else {
|
|
651
|
+
try {
|
|
652
|
+
const previousRecipientEmails = await readMarketingSegmentMembers(segmentId);
|
|
653
|
+
await sendProviderMarketingBroadcast({
|
|
654
|
+
segmentId,
|
|
655
|
+
recipients: batchPayloads.map((payload) => ({ email: payload.to })),
|
|
656
|
+
previousRecipientEmails,
|
|
657
|
+
subject: firstPayload.subject,
|
|
658
|
+
textBody: firstPayload.textBody,
|
|
659
|
+
htmlBody: firstPayload.htmlBody,
|
|
660
|
+
tag: firstPayload.tag || "reengagement",
|
|
661
|
+
});
|
|
662
|
+
await writeMarketingSegmentMembers(
|
|
663
|
+
segmentId,
|
|
664
|
+
batchPayloads.map((payload) => payload.to)
|
|
665
|
+
);
|
|
666
|
+
} catch (error: any) {
|
|
667
|
+
batchError = error?.message || String(error);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
} else {
|
|
672
|
+
try {
|
|
673
|
+
const batchResponse = await sendProviderBatchEmails(
|
|
674
|
+
batchPayloads.map((payload) => ({
|
|
675
|
+
to: payload.to,
|
|
676
|
+
subject: payload.subject,
|
|
677
|
+
textBody: payload.textBody,
|
|
678
|
+
htmlBody: payload.htmlBody,
|
|
679
|
+
tag: payload.tag || "untagged",
|
|
680
|
+
}))
|
|
681
|
+
);
|
|
682
|
+
|
|
683
|
+
if (Array.isArray((batchResponse as any)?.errors)) {
|
|
684
|
+
for (const entry of (batchResponse as any).errors) {
|
|
685
|
+
if (!Number.isInteger(entry?.index)) continue;
|
|
686
|
+
perItemErrors.set(
|
|
687
|
+
Number(entry.index),
|
|
688
|
+
String(entry?.message || "Batch delivery failed")
|
|
689
|
+
);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
} catch (error: any) {
|
|
693
|
+
batchError = error?.message || String(error);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
for (let localIndex = 0; localIndex < batchPayloads.length; localIndex += 1) {
|
|
698
|
+
const payload = batchPayloads[localIndex];
|
|
699
|
+
const targetIndex = batchIndexes[localIndex];
|
|
700
|
+
const reservation = batchReservations[localIndex] || null;
|
|
701
|
+
const itemError = perItemErrors.get(localIndex);
|
|
702
|
+
const status: DeliveryStatus = batchError || itemError ? "failed" : "sent";
|
|
703
|
+
if (status === "sent") {
|
|
704
|
+
await confirmIdempotencySent(reservation);
|
|
705
|
+
} else {
|
|
706
|
+
await releaseIdempotency(reservation);
|
|
707
|
+
}
|
|
708
|
+
const result = await finalizeManagedEmailAttempt({
|
|
709
|
+
payload,
|
|
710
|
+
status,
|
|
711
|
+
errorMessage: batchError || itemError,
|
|
712
|
+
attempt,
|
|
713
|
+
maxAttempts,
|
|
714
|
+
retryDelayMs,
|
|
715
|
+
enqueueOnFail,
|
|
716
|
+
suppressed: status === "failed" && suppressFailedResults,
|
|
717
|
+
});
|
|
718
|
+
results[targetIndex] = {
|
|
719
|
+
...result,
|
|
720
|
+
userId: payload.userId,
|
|
721
|
+
to: payload.to,
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
return results.map((item, index) => {
|
|
727
|
+
if (item) return item;
|
|
728
|
+
return {
|
|
729
|
+
userId: payloads[index]?.userId,
|
|
730
|
+
to: payloads[index]?.to || "",
|
|
731
|
+
success: false,
|
|
732
|
+
queued: false,
|
|
733
|
+
error: "Batch delivery result missing",
|
|
734
|
+
};
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
export async function processEmailRetryQueue() {
|
|
739
|
+
if (retryRunning) {
|
|
740
|
+
return { processed: 0, retried: 0, queued: 0, failed: 0, skipped: true };
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
retryRunning = true;
|
|
744
|
+
try {
|
|
745
|
+
const retryConfig = getRetryConfig();
|
|
746
|
+
const now = Date.now();
|
|
747
|
+
const jobs: Array<{ key: string; job: RetryJob }> = [];
|
|
748
|
+
|
|
749
|
+
const iter = serverDb.iterator({
|
|
750
|
+
gt: EMAIL_RETRY_PREFIX,
|
|
751
|
+
lt: `${EMAIL_RETRY_PREFIX}\xFF`,
|
|
752
|
+
});
|
|
753
|
+
|
|
754
|
+
try {
|
|
755
|
+
for await (const [key, value] of iter) {
|
|
756
|
+
const job = value as RetryJob;
|
|
757
|
+
if (!job?.nextRetryAt) continue;
|
|
758
|
+
if (job.nextRetryAt > now) break;
|
|
759
|
+
jobs.push({ key, job });
|
|
760
|
+
if (jobs.length >= retryConfig.retryBatchSize) break;
|
|
761
|
+
}
|
|
762
|
+
} finally {
|
|
763
|
+
await iter.close();
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
let retried = 0;
|
|
767
|
+
let queued = 0;
|
|
768
|
+
let failed = 0;
|
|
769
|
+
|
|
770
|
+
for (const item of jobs) {
|
|
771
|
+
await serverDb.del(item.key).catch(() => undefined);
|
|
772
|
+
const result = await sendManagedEmail(item.job.payload, {
|
|
773
|
+
attempt: item.job.attempt + 1,
|
|
774
|
+
maxAttempts: item.job.maxAttempts,
|
|
775
|
+
enqueueOnFail: true,
|
|
776
|
+
});
|
|
777
|
+
if (result.success) {
|
|
778
|
+
retried += 1;
|
|
779
|
+
if (
|
|
780
|
+
item.job.payload.tag === "signup-welcome" &&
|
|
781
|
+
typeof item.job.payload.userId === "string" &&
|
|
782
|
+
item.job.payload.userId
|
|
783
|
+
) {
|
|
784
|
+
try {
|
|
785
|
+
await markWelcomeEmailSent(item.job.payload.userId, Date.now());
|
|
786
|
+
} catch (error) {
|
|
787
|
+
logger.warn(
|
|
788
|
+
{ userId: item.job.payload.userId, error },
|
|
789
|
+
"Failed to mark welcome email as sent after retry"
|
|
790
|
+
);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
} else if (result.queued) {
|
|
794
|
+
queued += 1;
|
|
795
|
+
} else {
|
|
796
|
+
failed += 1;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
return { processed: jobs.length, retried, queued, failed, skipped: false };
|
|
801
|
+
} finally {
|
|
802
|
+
retryRunning = false;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
export function startEmailRetryScheduler() {
|
|
807
|
+
const retryConfig = getRetryConfig();
|
|
808
|
+
if (!retryConfig.retryEnabled) {
|
|
809
|
+
logger.info("Email retry scheduler disabled by env");
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
if (!shouldRunSchedulerOnThisInstance()) {
|
|
813
|
+
logger.info(
|
|
814
|
+
{
|
|
815
|
+
nodeAppInstance: process.env.NODE_APP_INSTANCE ?? null,
|
|
816
|
+
},
|
|
817
|
+
"Email retry scheduler skipped on non-leader instance"
|
|
818
|
+
);
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
if (retryTimer) return;
|
|
822
|
+
|
|
823
|
+
const intervalMs = retryConfig.retryIntervalMinutes * 60 * 1000;
|
|
824
|
+
retryTimer = setInterval(() => {
|
|
825
|
+
void processEmailRetryQueue();
|
|
826
|
+
}, intervalMs);
|
|
827
|
+
void processEmailRetryQueue();
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
export function stopEmailRetryScheduler() {
|
|
831
|
+
if (!retryTimer) return;
|
|
832
|
+
clearInterval(retryTimer);
|
|
833
|
+
retryTimer = null;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
const listPendingRetryCount = async () => {
|
|
837
|
+
let count = 0;
|
|
838
|
+
const iter = serverDb.iterator({
|
|
839
|
+
gt: EMAIL_RETRY_PREFIX,
|
|
840
|
+
lt: `${EMAIL_RETRY_PREFIX}\xFF`,
|
|
841
|
+
});
|
|
842
|
+
try {
|
|
843
|
+
for await (const _entry of iter) {
|
|
844
|
+
count += 1;
|
|
845
|
+
}
|
|
846
|
+
} finally {
|
|
847
|
+
await iter.close();
|
|
848
|
+
}
|
|
849
|
+
return count;
|
|
850
|
+
};
|
|
851
|
+
|
|
852
|
+
export async function getEmailDeliveryReport(days: number = 7, recentLimit: number = 50) {
|
|
853
|
+
const safeDays = Math.max(1, Math.min(90, Math.floor(days)));
|
|
854
|
+
const normalizedRecentLimit = Number.isFinite(Number(recentLimit))
|
|
855
|
+
? Math.floor(Number(recentLimit))
|
|
856
|
+
: 50;
|
|
857
|
+
const includeAllRecent = normalizedRecentLimit <= 0;
|
|
858
|
+
const safeRecentLimit = includeAllRecent
|
|
859
|
+
? 0
|
|
860
|
+
: Math.max(1, Math.min(5_000, normalizedRecentLimit));
|
|
861
|
+
const now = Date.now();
|
|
862
|
+
const earliestTimestamp = now - (safeDays - 1) * 24 * 60 * 60 * 1000;
|
|
863
|
+
const earliestDay = getDayKey(now - (safeDays - 1) * 24 * 60 * 60 * 1000);
|
|
864
|
+
|
|
865
|
+
const stats: Array<{
|
|
866
|
+
dayKey: string;
|
|
867
|
+
tag: string;
|
|
868
|
+
sent: number;
|
|
869
|
+
failed: number;
|
|
870
|
+
retried: number;
|
|
871
|
+
queued: number;
|
|
872
|
+
}> = [];
|
|
873
|
+
|
|
874
|
+
const statsIter = serverDb.iterator({
|
|
875
|
+
gt: EMAIL_STATS_PREFIX,
|
|
876
|
+
lt: `${EMAIL_STATS_PREFIX}\xFF`,
|
|
877
|
+
});
|
|
878
|
+
try {
|
|
879
|
+
for await (const [key, value] of statsIter) {
|
|
880
|
+
const suffix = key.slice(EMAIL_STATS_PREFIX.length);
|
|
881
|
+
const [dayKey, ...tagParts] = suffix.split(":");
|
|
882
|
+
if (!dayKey || dayKey < earliestDay) continue;
|
|
883
|
+
const tag = tagParts.join(":") || "untagged";
|
|
884
|
+
stats.push({
|
|
885
|
+
dayKey,
|
|
886
|
+
tag,
|
|
887
|
+
sent: Number(value?.sent || 0),
|
|
888
|
+
failed: Number(value?.failed || 0),
|
|
889
|
+
retried: Number(value?.retried || 0),
|
|
890
|
+
queued: Number(value?.queued || 0),
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
} finally {
|
|
894
|
+
await statsIter.close();
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
stats.sort((a, b) =>
|
|
898
|
+
a.dayKey === b.dayKey ? a.tag.localeCompare(b.tag) : a.dayKey.localeCompare(b.dayKey)
|
|
899
|
+
);
|
|
900
|
+
|
|
901
|
+
const totals = stats.reduce(
|
|
902
|
+
(acc, item) => {
|
|
903
|
+
acc.sent += item.sent;
|
|
904
|
+
acc.failed += item.failed;
|
|
905
|
+
acc.retried += item.retried;
|
|
906
|
+
acc.queued += item.queued;
|
|
907
|
+
return acc;
|
|
908
|
+
},
|
|
909
|
+
{ sent: 0, failed: 0, retried: 0, queued: 0 }
|
|
910
|
+
);
|
|
911
|
+
|
|
912
|
+
const recent: EmailDeliveryRecord[] = [];
|
|
913
|
+
const recentFailures: EmailDeliveryRecord[] = [];
|
|
914
|
+
const recordIter = serverDb.iterator({
|
|
915
|
+
gt: EMAIL_RECORD_PREFIX,
|
|
916
|
+
lt: `${EMAIL_RECORD_PREFIX}\xFF`,
|
|
917
|
+
reverse: true,
|
|
918
|
+
});
|
|
919
|
+
try {
|
|
920
|
+
for await (const [_key, value] of recordIter) {
|
|
921
|
+
const record = value as EmailDeliveryRecord;
|
|
922
|
+
const recordTimestamp = Number(record?.timestamp || 0);
|
|
923
|
+
if (recordTimestamp > 0 && recordTimestamp < earliestTimestamp) {
|
|
924
|
+
break;
|
|
925
|
+
}
|
|
926
|
+
if (includeAllRecent || recent.length < safeRecentLimit) {
|
|
927
|
+
recent.push(record);
|
|
928
|
+
}
|
|
929
|
+
if (
|
|
930
|
+
record.status === "failed" &&
|
|
931
|
+
(includeAllRecent || recentFailures.length < safeRecentLimit)
|
|
932
|
+
) {
|
|
933
|
+
recentFailures.push(record);
|
|
934
|
+
}
|
|
935
|
+
if (
|
|
936
|
+
!includeAllRecent &&
|
|
937
|
+
recent.length >= safeRecentLimit &&
|
|
938
|
+
recentFailures.length >= safeRecentLimit
|
|
939
|
+
) {
|
|
940
|
+
break;
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
} finally {
|
|
944
|
+
await recordIter.close();
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
const pendingRetryCount = await listPendingRetryCount();
|
|
948
|
+
|
|
949
|
+
return {
|
|
950
|
+
generatedAt: now,
|
|
951
|
+
days: safeDays,
|
|
952
|
+
totals: {
|
|
953
|
+
...totals,
|
|
954
|
+
pendingRetryCount,
|
|
955
|
+
},
|
|
956
|
+
stats,
|
|
957
|
+
recent,
|
|
958
|
+
recentFailures,
|
|
959
|
+
};
|
|
960
|
+
}
|