nolo-cli 0.1.39 → 0.1.41
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/README.md +4 -4
- package/agent-runtime/dialogWritePlan.ts +39 -0
- package/agent-runtime/hostAdapter.ts +4 -0
- package/agent-runtime/hybridRecordStore.ts +5 -3
- package/agent-runtime/index.ts +15 -0
- package/agent-runtime/localLoop.ts +87 -7
- package/agent-runtime/localToolPolicy.ts +2 -13
- package/agent-runtime/localWorkspaceTools.ts +42 -110
- package/agent-runtime/runtimeToolPolicy.ts +2 -11
- package/agent-runtime/runtimeToolSurface.ts +198 -0
- package/agent-runtime/types.ts +1 -0
- package/agentAliases.ts +2 -1
- package/agentRunCommand.ts +10 -32
- package/agentRuntimeLocal.ts +1 -0
- package/ai/agent/_executeModel.ts +146 -0
- package/ai/agent/agentSlice.ts +556 -1
- package/ai/agent/appWorkingMemory.ts +126 -0
- package/ai/agent/buildEditingContext.ts +378 -0
- package/ai/agent/buildSystemPrompt.ts +585 -0
- package/ai/agent/canvasEditingContext.ts +49 -0
- package/ai/agent/cleanAgentMessages.ts +140 -0
- package/ai/agent/cliChatClient.ts +153 -0
- package/ai/agent/cliExecutor.ts +314 -40
- package/ai/agent/contextCompiler.ts +107 -0
- package/ai/agent/contextLayerContract.ts +44 -0
- package/ai/agent/createAgentSchema.ts +272 -0
- package/ai/agent/currentTimeContext.ts +65 -0
- package/ai/agent/executeToolCall.ts +58 -0
- package/ai/agent/fetchAgentContexts.ts +42 -0
- package/ai/agent/generatePrompt.ts +3 -0
- package/ai/agent/getFullChatContextKeys.ts +168 -0
- package/ai/agent/guidedCreation/capabilities.ts +84 -0
- package/ai/agent/guidedCreation/types.ts +38 -0
- package/ai/agent/isLiveAudioOnlyAgent.ts +26 -0
- package/ai/agent/liveAudioModel.ts +2 -0
- package/ai/agent/pageBuilderHandoffRules.ts +75 -0
- package/ai/agent/persistMessageWithFixedId.ts +37 -0
- package/ai/agent/planSlice.ts +259 -0
- package/ai/agent/referenceUtils.ts +229 -0
- package/ai/agent/runAgentBackground.ts +310 -0
- package/ai/agent/runAgentClientLoop.ts +164 -0
- package/ai/agent/runtimeGuidance.ts +116 -0
- package/ai/agent/serverOrigin.ts +7 -0
- package/ai/agent/startParallelAgentStreams.ts +424 -0
- package/ai/agent/startupProtocol.ts +53 -0
- package/ai/agent/streamAgentChatTurn.ts +2001 -0
- package/ai/agent/streamAgentChatTurnUtils.ts +860 -0
- package/ai/agent/toolFailureGuard.ts +99 -0
- package/ai/agent/types.ts +73 -0
- package/ai/agent/utils/imageOutput.ts +37 -0
- package/ai/agent/utils/publicImageAgentMode.ts +26 -0
- package/ai/ai.locale.ts +1095 -0
- package/ai/chat/accumulateToolCallChunks.ts +126 -0
- package/ai/chat/fetchUtils.ts +143 -0
- package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
- package/ai/chat/parseApiError.ts +67 -0
- package/ai/chat/parseMultilineSSE.ts +95 -0
- package/ai/chat/sendOpenAICompletionsRequest.ts +897 -0
- package/ai/chat/sendOpenAIResponseRequest.ts +720 -0
- package/ai/chat/serverProxyRetry.ts +102 -0
- package/ai/chat/shouldUseServerProxy.ts +18 -0
- package/ai/chat/streamRetry.ts +46 -0
- package/ai/chat/updateTotalUsage.ts +89 -0
- package/ai/context/buildReferenceContext.ts +437 -0
- package/ai/context/retention.ts +165 -0
- package/ai/context/tokenUtils.ts +78 -0
- package/ai/llm/agentCapabilities.ts +74 -0
- package/ai/llm/deepinfra.ts +79 -0
- package/ai/llm/fireworks.ts +68 -0
- package/ai/llm/generateRequestBody.ts +165 -0
- package/ai/llm/getModelContextWindow.ts +93 -0
- package/ai/llm/getPricing.ts +252 -0
- package/ai/llm/imagePricing.ts +66 -0
- package/ai/llm/isResponseAPIModel.ts +13 -0
- package/ai/llm/kimi.ts +23 -0
- package/ai/llm/mimo.ts +99 -0
- package/ai/llm/mistral.ts +21 -0
- package/ai/llm/models.ts +45 -0
- package/ai/llm/openrouterModels.ts +6 -0
- package/ai/llm/providers.ts +313 -0
- package/ai/llm/reasoningModels.ts +27 -0
- package/ai/llm/types.ts +82 -0
- package/ai/llm/usageRequestOptions.ts +59 -0
- package/ai/memory/queryShared.ts +161 -0
- package/ai/memory/recentRelationshipRecap.ts +247 -0
- package/ai/memory/remember.ts +167 -0
- package/ai/memory/store.ts +20 -0
- package/ai/memory/storeShared.ts +76 -0
- package/ai/memory/types.ts +46 -0
- package/ai/memory/understanding.ts +349 -0
- package/ai/memory/understandingGreeting.ts +264 -0
- package/ai/policy/personalizationDialog.ts +333 -0
- package/ai/policy/runtimePolicy.ts +454 -0
- package/ai/policy/selfUpdateFields.ts +48 -0
- package/ai/policy/types.ts +64 -0
- package/ai/skills/referenceRuntime.ts +274 -0
- package/ai/skills/skillDiagnostics.ts +251 -0
- package/ai/skills/skillDocBuilder.ts +139 -0
- package/ai/skills/skillSummaryMarker.ts +26 -0
- package/ai/token/calculatePrice.ts +576 -0
- package/ai/token/missingUsageEstimate.ts +42 -0
- package/ai/token/normalizeUsage.ts +124 -0
- package/ai/token/openaiImageGenerationUsage.ts +56 -0
- package/ai/token/prepareTokenUsageData.ts +93 -0
- package/ai/token/resolveBillingTarget.ts +52 -0
- package/ai/token/saveTokenRecord.ts +53 -0
- package/ai/token/types.ts +103 -0
- package/ai/tools/agent/agentTools.ts +235 -0
- package/ai/tools/agent/agentUpdateShared.ts +311 -0
- package/ai/tools/agent/callAgentTool.ts +139 -0
- package/ai/tools/agent/createAgentTool.ts +512 -0
- package/ai/tools/agent/createDialogTool.ts +69 -0
- package/ai/tools/agent/createSkillAgentTool.ts +62 -0
- package/ai/tools/agent/parallelBudget.ts +221 -0
- package/ai/tools/agent/prepareAgentDraftTool.ts +159 -0
- package/ai/tools/agent/presets/appBuilderPreset.ts +154 -0
- package/ai/tools/agent/runLlmTool.ts +96 -0
- package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
- package/ai/tools/agent/skillAgentArgs.ts +106 -0
- package/ai/tools/agent/startAgentDialogTool.ts +53 -0
- package/ai/tools/agent/streamParallelAgentsTool.ts +123 -0
- package/ai/tools/agent/updateAgentTool.ts +96 -0
- package/ai/tools/agent/updateSelfTool.ts +113 -0
- package/ai/tools/amazonProductScraperTool.ts +86 -0
- package/ai/tools/apifyActorClient.ts +45 -0
- package/ai/tools/appEditGuard.ts +372 -0
- package/ai/tools/appReadSnapshot.ts +153 -0
- package/ai/tools/appTools.ts +1549 -0
- package/ai/tools/applyEditTool.ts +259 -0
- package/ai/tools/applyLineEditsTool.ts +315 -0
- package/ai/tools/browserTools/click.ts +33 -0
- package/ai/tools/browserTools/closeSession.ts +29 -0
- package/ai/tools/browserTools/common.ts +27 -0
- package/ai/tools/browserTools/openSession.ts +48 -0
- package/ai/tools/browserTools/readContent.ts +38 -0
- package/ai/tools/browserTools/selectOption.ts +46 -0
- package/ai/tools/browserTools/typeText.ts +42 -0
- package/ai/tools/category/createCategoryTool.ts +66 -0
- package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
- package/ai/tools/category/updateContentCategoryTool.ts +75 -0
- package/ai/tools/cfBrowserTools.ts +319 -0
- package/ai/tools/cfSpeechToTextTool.ts +49 -0
- package/ai/tools/checkEnvTool.ts +102 -0
- package/ai/tools/cloudflareCrawlTool.ts +289 -0
- package/ai/tools/codeSearchTool.ts +123 -0
- package/ai/tools/codeTools.ts +101 -0
- package/ai/tools/convertMarxistsBookTool.ts +103 -0
- package/ai/tools/createDocTool.ts +132 -0
- package/ai/tools/createSkillDocTool.ts +155 -0
- package/ai/tools/createWorkflowTool.ts +154 -0
- package/ai/tools/delayTool.ts +31 -0
- package/ai/tools/deleteSpacesTool.ts +325 -0
- package/ai/tools/deleteSpacesToolModel.ts +159 -0
- package/ai/tools/devReloadUtils.ts +29 -0
- package/ai/tools/dialogMessageSearch.ts +137 -0
- package/ai/tools/doctorSkillTool.ts +72 -0
- package/ai/tools/ecommerceScraperTool.ts +86 -0
- package/ai/tools/emailTools.ts +549 -0
- package/ai/tools/evalSkillTool.ts +92 -0
- package/ai/tools/exaSearchTool.ts +63 -0
- package/ai/tools/execShellTool.ts +266 -0
- package/ai/tools/executeSqlTool.ts +192 -0
- package/ai/tools/fetchWebpageSupport.ts +333 -0
- package/ai/tools/fetchWebpageTool.ts +97 -0
- package/ai/tools/geminiImagePreviewTool.ts +386 -0
- package/ai/tools/generateDocxTool.ts +215 -0
- package/ai/tools/googleSearchScraperTool.ts +106 -0
- package/ai/tools/importDataTool.ts +133 -0
- package/ai/tools/importSkillTool.ts +162 -0
- package/ai/tools/index.ts +2308 -0
- package/ai/tools/jdProductScraperTool.ts +821 -0
- package/ai/tools/listUserSpacesTool.ts +113 -0
- package/ai/tools/localFilesTool.ts +276 -0
- package/ai/tools/marxistsOfflineBook.ts +253 -0
- package/ai/tools/modelUsageTools.ts +206 -0
- package/ai/tools/noloWorkspaceReadTools.ts +467 -0
- package/ai/tools/olmOcrTool.ts +33 -0
- package/ai/tools/openaiImageTool.ts +267 -0
- package/ai/tools/prepareTools.ts +23 -0
- package/ai/tools/readDocTool.ts +88 -0
- package/ai/tools/readFileTool.ts +214 -0
- package/ai/tools/readTool.ts +194 -0
- package/ai/tools/readXPostTool.ts +229 -0
- package/ai/tools/readXhsProfileTool.ts +627 -0
- package/ai/tools/rememberMemoryTool.ts +84 -0
- package/ai/tools/remotionVideoTool.ts +151 -0
- package/ai/tools/searchDialogMessagesTool.ts +222 -0
- package/ai/tools/searchWorkspaceTool.ts +259 -0
- package/ai/tools/skillFollowup.ts +86 -0
- package/ai/tools/surfWeatherTool.ts +169 -0
- package/ai/tools/table/addTableRowTool.ts +217 -0
- package/ai/tools/table/createTableTool.ts +315 -0
- package/ai/tools/table/rowTools.ts +386 -0
- package/ai/tools/table/schemaTools.ts +244 -0
- package/ai/tools/table/shareTableTool.ts +148 -0
- package/ai/tools/table/toolShared.ts +129 -0
- package/ai/tools/taobaoTmallProductScraperTool.ts +49 -0
- package/ai/tools/toolApiClient.ts +279 -0
- package/ai/tools/toolResultError.ts +42 -0
- package/ai/tools/toolRunSlice.ts +303 -0
- package/ai/tools/toolSchemaCompatibility.ts +53 -0
- package/ai/tools/uiAskChoiceTool.ts +104 -0
- package/ai/tools/updateContentTitleTool.ts +84 -0
- package/ai/tools/updateDocTool.ts +105 -0
- package/ai/tools/updateUserPreferenceProfileTool.ts +153 -0
- package/ai/tools/wereadGatewayTool.ts +152 -0
- package/ai/tools/whisperTool.ts +76 -0
- package/ai/tools/writeFileTool.ts +213 -0
- package/ai/tools/youtubeScraperTool.ts +116 -0
- package/ai/tools/ziweiChartTool.ts +678 -0
- package/ai/types.ts +55 -0
- package/ai/workflow/workflowExecutor.ts +323 -0
- package/ai/workflow/workflowSlice.ts +73 -0
- package/ai/workflow/workflowTypes.ts +106 -0
- package/app/actions/syncAppRecord.ts +73 -0
- package/app/constants/animationSets.ts +21 -0
- package/app/constants/appEditor.ts +99 -0
- package/app/favorite/favoriteSlice.ts +690 -0
- package/app/favorite/type.ts +43 -0
- package/app/hooks/deleteDbKey.ts +233 -0
- package/app/i18n/client.ts +13 -0
- package/app/i18n/i18n.base.ts +14 -0
- package/app/i18n/i18n.config.ts +77 -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/pricing.locale.ts +397 -0
- package/app/i18n/translations/privacy.locale.ts +168 -0
- package/app/i18n/translations/seo.locale.ts +129 -0
- package/app/i18n/translations/terms.locale.ts +124 -0
- package/app/i18n/types.ts +6 -0
- package/app/notifications/model.ts +77 -0
- package/app/notifications/notificationSlice.ts +141 -0
- package/app/reducer.ts +36 -0
- package/app/settings/dbActionThunks.ts +34 -0
- package/app/settings/defaultSpacePreference.ts +87 -0
- package/app/settings/settingSlice.tsx +1212 -0
- package/app/settings/settingsRecord.ts +8 -0
- package/app/stateViews/runtime.ts +90 -0
- package/app/store.ts +55 -0
- package/app/theme/colors.ts +280 -0
- package/app/theme/fontPreference.ts +77 -0
- package/app/theme/theme.config.ts +120 -0
- package/app/theme/themeModeBootstrap.ts +123 -0
- package/app/types/appSummary.ts +114 -0
- package/app/types.ts +358 -0
- package/app/utils/appKeys.ts +55 -0
- package/app/utils/async.ts +28 -0
- package/app/utils/desktopAgentRuntimeTurnClient.ts +73 -0
- package/app/utils/env.ts +17 -0
- package/app/utils/fileUtils.ts +229 -0
- package/app/utils/imageUtils.ts +274 -0
- package/app/utils/myContentItems.ts +289 -0
- package/app/utils/retryAfter.ts +36 -0
- package/app/utils/retryFetch.ts +61 -0
- package/app/utils/toast.ts +3 -0
- package/auth/action/signUpAction.ts +227 -0
- package/auth/adminPermissions.ts +18 -0
- package/auth/authSlice.ts +531 -0
- package/auth/client/loginRequest.ts +14 -0
- package/auth/resetAuthScopedClientState.ts +27 -0
- package/auth/routes.ts +178 -0
- package/auth/token.ts +63 -0
- package/auth/types.ts +40 -0
- package/chat/chat.locale.ts +813 -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/createDialogAction.ts +379 -0
- package/chat/dialog/actions/createScheduledTaskAction.ts +78 -0
- package/chat/dialog/actions/handleSendMessageAction.ts +197 -0
- package/chat/dialog/actions/handleSendMessageResolver.ts +27 -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 +430 -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 +72 -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/goal.ts +108 -0
- package/chat/dialog/objectAssistantRegistry.ts +286 -0
- package/chat/dialog/schedule.ts +17 -0
- package/chat/messages/fetchAndCacheMessages.ts +119 -0
- package/chat/messages/fetchConvMsgs.ts +51 -0
- package/chat/messages/fileUrl.ts +13 -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 +1367 -0
- package/chat/messages/toolThunks.ts +625 -0
- package/cli/agentAliases.ts +2 -1
- package/cli/agentRunCommand.ts +10 -32
- package/cli/agentRuntimeLocal.ts +1 -0
- package/cli/client/agentRun.ts +67 -95
- package/cli/client/localRuntimeAdapter.ts +323 -54
- package/cli/commandRegistry.ts +2 -2
- package/cli/machineWsRunDispatch.ts +51 -6
- package/cli/offlineMarxistsAgentCommand.ts +6 -4
- package/client/agentConfigResolver.test.ts +2 -2
- package/client/agentRun.test.ts +175 -57
- package/client/agentRun.ts +67 -95
- package/client/localRuntimeAdapter.test.ts +682 -37
- package/client/localRuntimeAdapter.ts +323 -54
- package/client/localRuntimeDryRun.test.ts +23 -9
- package/client/localToolPolicy.test.ts +4 -4
- package/commandRegistry.ts +2 -2
- package/core/builtinAgents.ts +209 -0
- package/core/config.ts +15 -0
- package/core/crypto.ts +51 -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/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/utils/slateUtils.ts +233 -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 +151 -0
- package/create/space/content/uploadAndAddFileToSpaceAction.ts +98 -0
- package/create/space/contentKeyUtils.ts +117 -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/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/resolvePreferredSpaceId.ts +113 -0
- package/create/space/sidebarVisibleTypes.ts +241 -0
- package/create/space/space.locale.ts +1087 -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/types.ts +21 -0
- package/database/actions/agentReadResolution.ts +33 -0
- package/database/actions/common.ts +243 -0
- package/database/actions/deleteFile.ts +40 -0
- package/database/actions/fileContent.ts +125 -0
- package/database/actions/patch.ts +155 -0
- package/database/actions/read.ts +358 -0
- package/database/actions/readAndWait.ts +260 -0
- package/database/actions/readRequestManager.ts +120 -0
- package/database/actions/readResolution.ts +125 -0
- package/database/actions/remove.ts +94 -0
- package/database/actions/replication.ts +477 -0
- package/database/actions/upload.ts +186 -0
- package/database/actions/upsert.ts +56 -0
- package/database/actions/write.ts +146 -0
- package/database/authority/ownerKey.ts +80 -0
- package/database/authority/recordAuthority.ts +67 -0
- package/database/authority/userAuthorityRegistry.ts +54 -0
- package/database/client/fetchUserData.ts +61 -0
- package/database/dbActionThunks.ts +1 -0
- package/database/dbSlice.ts +149 -0
- package/database/fileRing.ts +51 -0
- package/database/fileStorage.ts +232 -0
- package/database/fileUrl.ts +34 -0
- package/database/keys.ts +767 -0
- package/database/queryPrefixes.ts +14 -0
- package/database/requests.ts +443 -0
- package/database/runtimeServerContext.ts +54 -0
- package/database/server/levelAuthorityStore.ts +20 -1
- package/database/tenantPlacement.ts +57 -0
- package/database/userPreferenceRegister.ts +131 -0
- package/database/utils/ulid.ts +1 -0
- package/integrations/anthropic/anthropicModels.ts +47 -0
- package/integrations/deepseek/models.ts +37 -0
- package/integrations/google/models.ts +341 -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/x-reader/types.ts +109 -0
- package/integrations/xai/models.ts +13 -0
- package/integrations/xhs-reader/analyze/profileAnalyzer.ts +205 -0
- package/integrations/xhs-reader/backends/playwrightProfileCollector.ts +624 -0
- package/integrations/xhs-reader/bridge/readXhsProfileWithBridge.ts +227 -0
- package/integrations/xhs-reader/client/xhsWebApiClient.ts +229 -0
- package/integrations/xhs-reader/normalize.ts +390 -0
- package/integrations/xhs-reader/orchestrator.ts +178 -0
- package/integrations/xhs-reader/redaction.ts +68 -0
- package/integrations/xhs-reader/types.ts +244 -0
- package/integrations/xhs-reader/url.ts +57 -0
- package/machineWsRunDispatch.ts +51 -6
- package/offlineMarxistsAgentCommand.ts +6 -4
- package/package.json +430 -3
- package/render/page/createPageAction.ts +183 -0
- package/render/page/docSlice.ts +468 -0
- package/render/page/types.ts +17 -0
- package/render/table/createTableAction.ts +270 -0
- package/render/table/deleteTableAction.ts +193 -0
- package/render/table/fetchAndCacheTableRows.ts +174 -0
- package/render/table/tableSlice.ts +1106 -0
- package/render/table/toolValueUtils.ts +363 -0
- package/render/table/types.ts +252 -0
- package/render/table/utils/tableSerialization.ts +50 -0
- package/server/handlers/agentRun/types.ts +104 -0
- package/share/action.ts +225 -0
- package/share/helpers.ts +302 -0
- package/share/keys.ts +243 -0
- package/share/publicSharePolicy.ts +27 -0
- package/share/shareSlice.ts +53 -0
- package/share/types.ts +100 -0
|
@@ -0,0 +1,860 @@
|
|
|
1
|
+
// 文件路径: packages/ai/agent/streamAgentChatTurnUtils.ts
|
|
2
|
+
|
|
3
|
+
import type { RootState } from "../../app/store";
|
|
4
|
+
import { read, selectById } from "../../database/dbSlice";
|
|
5
|
+
import { fetchReferenceContents } from "../context/buildReferenceContext";
|
|
6
|
+
import {
|
|
7
|
+
selectPendingFiles,
|
|
8
|
+
type PendingFile,
|
|
9
|
+
} from "../../chat/dialog/dialogSlice";
|
|
10
|
+
import { selectAllMsgs } from "../../chat/messages/messageSlice";
|
|
11
|
+
import { selectCurrentSpace, selectViewMode } from "../../create/space/spaceSlice";
|
|
12
|
+
import { createSpaceKey } from "../../create/space/spaceKeys";
|
|
13
|
+
import {
|
|
14
|
+
selectAiRecentContentLimit,
|
|
15
|
+
selectGlobalPrompt,
|
|
16
|
+
selectKnowledgeCaptureLevel,
|
|
17
|
+
selectSpaceContextLevel,
|
|
18
|
+
selectUserTonePreset,
|
|
19
|
+
} from "../../app/settings/settingSlice";
|
|
20
|
+
import {
|
|
21
|
+
getFullChatContextKeys,
|
|
22
|
+
deduplicateContextKeys,
|
|
23
|
+
} from "../agent/getFullChatContextKeys";
|
|
24
|
+
import type { Agent, Category, SpaceContent, DialogConfig } from "../../app/types";
|
|
25
|
+
import type { Contexts } from "../types";
|
|
26
|
+
import { getModelContextWindow } from "../llm/getModelContextWindow";
|
|
27
|
+
import {
|
|
28
|
+
selectCurrentUserBalance,
|
|
29
|
+
selectUserId,
|
|
30
|
+
} from "../../auth/authSlice";
|
|
31
|
+
import {
|
|
32
|
+
getModelPricing,
|
|
33
|
+
getPrices,
|
|
34
|
+
getFinalPrice,
|
|
35
|
+
hasExplicitAgentPricing,
|
|
36
|
+
} from "../llm/getPricing";
|
|
37
|
+
import {
|
|
38
|
+
buildStaticUserPolicyContext,
|
|
39
|
+
resolveSpaceContextPreloadPlan,
|
|
40
|
+
} from "../policy/runtimePolicy";
|
|
41
|
+
import {
|
|
42
|
+
PERSONALIZATION_DIALOG_CATEGORY,
|
|
43
|
+
buildPersonalizationDialogPolicyContext,
|
|
44
|
+
} from "../policy/personalizationDialog";
|
|
45
|
+
import { buildEditingContextSummary } from "./buildEditingContext";
|
|
46
|
+
import { estimateTokenCount } from "../context/tokenUtils";
|
|
47
|
+
import type { OpenAIMessage } from "../../integrations/openai/filterAndCleanMessages";
|
|
48
|
+
import {
|
|
49
|
+
ConversationLoad,
|
|
50
|
+
planContextUsage,
|
|
51
|
+
} from "../context/retention";
|
|
52
|
+
import { TOOL_PACKS } from "../tools";
|
|
53
|
+
import { canonicalizeToolNames, prioritizeToolNames } from "../tools/toolNameAliases";
|
|
54
|
+
import {
|
|
55
|
+
selectAllToolRuns,
|
|
56
|
+
} from "../tools/toolRunSlice";
|
|
57
|
+
import { buildRecentAppToolMemory } from "./appWorkingMemory";
|
|
58
|
+
import type { AgentRuntimeOptions } from "./types";
|
|
59
|
+
import { getModelConfig, getProviderByModelName, type Provider } from "../llm/providers";
|
|
60
|
+
import type { ImageGenerationState } from "../../chat/messages/types";
|
|
61
|
+
|
|
62
|
+
const BROWSER_UNAVAILABLE_CORE_TOOLS = new Set([
|
|
63
|
+
"queryModelUsage",
|
|
64
|
+
"createDialogGoal",
|
|
65
|
+
"getDialogGoal",
|
|
66
|
+
"completeDialogGoal",
|
|
67
|
+
"createScheduledTask",
|
|
68
|
+
"notifyUser",
|
|
69
|
+
]);
|
|
70
|
+
|
|
71
|
+
const getRuntimeCoreTools = (): string[] => {
|
|
72
|
+
if (typeof window === "undefined") {
|
|
73
|
+
return TOOL_PACKS.CORE;
|
|
74
|
+
}
|
|
75
|
+
return TOOL_PACKS.CORE.filter(
|
|
76
|
+
(toolName) => !BROWSER_UNAVAILABLE_CORE_TOOLS.has(toolName),
|
|
77
|
+
);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const isInlineVisualArtifactAgent = (agentConfig: Agent): boolean => {
|
|
81
|
+
const tags = Array.isArray((agentConfig as any).tags)
|
|
82
|
+
? ((agentConfig as any).tags as unknown[])
|
|
83
|
+
: [];
|
|
84
|
+
return tags.some(
|
|
85
|
+
(tag) =>
|
|
86
|
+
typeof tag === "string" &&
|
|
87
|
+
["inline-artifact", "streaming-ui"].includes(tag)
|
|
88
|
+
);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 估算单条 OpenAI 消息的 token 数(包括 tool_calls)。
|
|
93
|
+
*/
|
|
94
|
+
export const estimateTokensOfMessage = (msg: OpenAIMessage): number => {
|
|
95
|
+
let content = "";
|
|
96
|
+
|
|
97
|
+
if (typeof msg.content === "string") {
|
|
98
|
+
content = msg.content;
|
|
99
|
+
} else if (Array.isArray(msg.content)) {
|
|
100
|
+
content = msg.content
|
|
101
|
+
.map((p: any) => {
|
|
102
|
+
if (p.type === "text") return p.text || "";
|
|
103
|
+
if (p.type === "image_url") return "[image]";
|
|
104
|
+
return "[non-text]";
|
|
105
|
+
})
|
|
106
|
+
.join("");
|
|
107
|
+
} else if (msg.content && typeof msg.content === "object") {
|
|
108
|
+
content = JSON.stringify(msg.content);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
let extraTokens = 0;
|
|
112
|
+
if (Array.isArray((msg as any).tool_calls)) {
|
|
113
|
+
const toolsStr = JSON.stringify((msg as any).tool_calls);
|
|
114
|
+
extraTokens = estimateTokenCount(toolsStr);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return estimateTokenCount(content) + extraTokens;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 基于最近 N 条消息的 token 分布,粗略评估会话负载等级。
|
|
122
|
+
*/
|
|
123
|
+
export const classifyConversationLoad = (
|
|
124
|
+
messages: OpenAIMessage[],
|
|
125
|
+
): ConversationLoad => {
|
|
126
|
+
const N = 20;
|
|
127
|
+
if (!Array.isArray(messages) || messages.length === 0) return "light";
|
|
128
|
+
|
|
129
|
+
const tail = messages.slice(-N);
|
|
130
|
+
const tokenSamples = tail.map(estimateTokensOfMessage);
|
|
131
|
+
if (tokenSamples.length === 0) return "light";
|
|
132
|
+
|
|
133
|
+
const sum = tokenSamples.reduce((acc, v) => acc + v, 0);
|
|
134
|
+
const avg = sum / tokenSamples.length;
|
|
135
|
+
const sorted = [...tokenSamples].sort((a, b) => a - b);
|
|
136
|
+
const p95 = sorted[Math.floor((sorted.length - 1) * 0.95)];
|
|
137
|
+
|
|
138
|
+
if (p95 < 200 && avg < 120) {
|
|
139
|
+
return "light";
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (p95 > 2000 || avg > 1200) {
|
|
143
|
+
return "heavy";
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return "medium";
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 根据上下文窗口和对话摘要,对消息历史做截断。
|
|
151
|
+
*/
|
|
152
|
+
/**
|
|
153
|
+
* 压缩历史 tool_result 内容,防止大体积工具返回值撑爆上下文。
|
|
154
|
+
*
|
|
155
|
+
* 策略:
|
|
156
|
+
* - 最近一个 tool 轮次(最后一条 assistant tool_calls + 对应 tool 结果):完整保留
|
|
157
|
+
* - 更早的 tool 消息:内容截断到 MAX_CHARS,并追加截断标记
|
|
158
|
+
*
|
|
159
|
+
* 在 filterAndCleanMessages 之后、trimMessagesWithSummary 之前调用。
|
|
160
|
+
*/
|
|
161
|
+
export const compressOldToolResults = (
|
|
162
|
+
messages: OpenAIMessage[],
|
|
163
|
+
maxChars = 800,
|
|
164
|
+
): OpenAIMessage[] => {
|
|
165
|
+
// 找到最后一条 assistant 消息(含 tool_calls)的索引
|
|
166
|
+
let lastToolCallAssistantIdx = -1;
|
|
167
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
168
|
+
if (
|
|
169
|
+
messages[i].role === "assistant" &&
|
|
170
|
+
Array.isArray((messages[i] as any).tool_calls) &&
|
|
171
|
+
(messages[i] as any).tool_calls.length > 0
|
|
172
|
+
) {
|
|
173
|
+
lastToolCallAssistantIdx = i;
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return messages.map((msg, idx) => {
|
|
179
|
+
// 只处理 tool 消息,且不是最近轮次的
|
|
180
|
+
if (msg.role !== "tool") return msg;
|
|
181
|
+
if (idx > lastToolCallAssistantIdx) return msg; // 最近轮次,保留完整
|
|
182
|
+
|
|
183
|
+
const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
|
|
184
|
+
if (content.length <= maxChars) return msg;
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
...msg,
|
|
188
|
+
content: content.slice(0, maxChars) + `\n…[截断,原始长度 ${content.length} 字符]`,
|
|
189
|
+
};
|
|
190
|
+
});
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
export const trimMessagesWithSummary = (
|
|
195
|
+
messages: OpenAIMessage[],
|
|
196
|
+
contextWindow: number,
|
|
197
|
+
summaryTokenCount: number,
|
|
198
|
+
retention: number = 50,
|
|
199
|
+
): OpenAIMessage[] => {
|
|
200
|
+
const recentLoad = classifyConversationLoad(messages);
|
|
201
|
+
|
|
202
|
+
const { rawMessageBudget, minTailTokens } = planContextUsage({
|
|
203
|
+
contextWindow,
|
|
204
|
+
retentionSlider: retention,
|
|
205
|
+
summaryTokens: summaryTokenCount,
|
|
206
|
+
recentLoad,
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
if (!Array.isArray(messages) || messages.length === 0) return messages;
|
|
210
|
+
|
|
211
|
+
let totalTokens = 0;
|
|
212
|
+
let keepCount = 0;
|
|
213
|
+
|
|
214
|
+
// 从后往前保留,直到填满 rawMessageBudget
|
|
215
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
216
|
+
const t = estimateTokensOfMessage(messages[i]);
|
|
217
|
+
if (totalTokens + t > rawMessageBudget) break;
|
|
218
|
+
totalTokens += t;
|
|
219
|
+
keepCount++;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (keepCount >= messages.length) {
|
|
223
|
+
return messages;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// 二次兜底:如果保留下来的 token 太少,尝试多保留几条,
|
|
227
|
+
// 直到达到 minTailTokens,允许轻微超过 rawMessageBudget(最多 20%)。
|
|
228
|
+
if (totalTokens < minTailTokens) {
|
|
229
|
+
const maxBudgetWithSlack = rawMessageBudget * 1.2;
|
|
230
|
+
for (let i = messages.length - 1 - keepCount; i >= 0; i--) {
|
|
231
|
+
const t = estimateTokensOfMessage(messages[i]);
|
|
232
|
+
if (totalTokens + t > maxBudgetWithSlack) break;
|
|
233
|
+
totalTokens += t;
|
|
234
|
+
keepCount++;
|
|
235
|
+
if (totalTokens >= minTailTokens) break;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// 再兜一层底:至少保留 2 条消息(如果存在)
|
|
240
|
+
if (keepCount === 0 && messages.length > 0) {
|
|
241
|
+
keepCount = Math.min(2, messages.length);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
let cutIndex = messages.length - keepCount;
|
|
245
|
+
if (cutIndex < 0) cutIndex = 0;
|
|
246
|
+
|
|
247
|
+
// 避免从 tool 消息中间开始,丢失其调用方 assistant
|
|
248
|
+
while (cutIndex < messages.length && messages[cutIndex].role === "tool") {
|
|
249
|
+
cutIndex++;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return messages.slice(cutIndex);
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* 安全读取数据库记录,失败时返回 null。
|
|
257
|
+
*/
|
|
258
|
+
export const readSafe = async <T>(
|
|
259
|
+
dispatch: any,
|
|
260
|
+
dbKey: string,
|
|
261
|
+
): Promise<T | null> => {
|
|
262
|
+
try {
|
|
263
|
+
return (await dispatch(read({
|
|
264
|
+
dbKey: dbKey
|
|
265
|
+
})).unwrap()) as T;
|
|
266
|
+
} catch {
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
/** 将 Map 的所有 value 拼接为一个字符串 */
|
|
272
|
+
export const joinMapValues = (map: Map<string, string>): string =>
|
|
273
|
+
Array.from(map.values()).join("");
|
|
274
|
+
|
|
275
|
+
/** 检查 OpenAI 消息数组中是否包含 image_url 片段 */
|
|
276
|
+
export const hasImageInMessages = (messages: any[]): boolean => {
|
|
277
|
+
if (!Array.isArray(messages)) return false;
|
|
278
|
+
|
|
279
|
+
return messages.some((msg) => {
|
|
280
|
+
const content = (msg as any).content;
|
|
281
|
+
if (!Array.isArray(content)) return false;
|
|
282
|
+
|
|
283
|
+
return content.some(
|
|
284
|
+
(part: any) =>
|
|
285
|
+
part &&
|
|
286
|
+
typeof part === "object" &&
|
|
287
|
+
part.type === "image_url" &&
|
|
288
|
+
part.image_url &&
|
|
289
|
+
typeof part.image_url.url === "string" &&
|
|
290
|
+
part.image_url.url.trim() !== "",
|
|
291
|
+
);
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
/** 根据 pendingFiles 和 currentInputMap 构造“当前输入上下文”字符串 */
|
|
296
|
+
export const formatCurrentInputContext = (
|
|
297
|
+
pendingFiles: PendingFile[],
|
|
298
|
+
currentInputMap: Map<string, string>,
|
|
299
|
+
): string => {
|
|
300
|
+
if (pendingFiles.length === 0 || currentInputMap.size === 0) {
|
|
301
|
+
return joinMapValues(currentInputMap);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const relevantPendingFiles = pendingFiles.filter((file) => {
|
|
305
|
+
const key = file.sourceDialogKey || file.dialogKey || file.pageKey;
|
|
306
|
+
return key && currentInputMap.has(key);
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
if (relevantPendingFiles.length === 0) {
|
|
310
|
+
return joinMapValues(currentInputMap);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const filesByGroup = new Map<string, PendingFile[]>();
|
|
314
|
+
for (const file of relevantPendingFiles) {
|
|
315
|
+
const groupKey = file.groupId || file.id;
|
|
316
|
+
const group = filesByGroup.get(groupKey);
|
|
317
|
+
if (group) {
|
|
318
|
+
group.push(file);
|
|
319
|
+
} else {
|
|
320
|
+
filesByGroup.set(groupKey, [file]);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
let sourceCounter = 1;
|
|
325
|
+
let output = "";
|
|
326
|
+
|
|
327
|
+
filesByGroup.forEach((filesInGroup) => {
|
|
328
|
+
const isGroup = filesInGroup.length > 1;
|
|
329
|
+
const sourceName = isGroup
|
|
330
|
+
? filesInGroup[0].name.split(" (")[0]
|
|
331
|
+
: filesInGroup[0].name;
|
|
332
|
+
|
|
333
|
+
output += `--- Source ${sourceCounter}: "${sourceName}" ---\n`;
|
|
334
|
+
|
|
335
|
+
filesInGroup.forEach((file) => {
|
|
336
|
+
const key = file.sourceDialogKey || file.dialogKey || file.pageKey;
|
|
337
|
+
if (!key) return; // Skip if no key
|
|
338
|
+
const content = currentInputMap.get(key);
|
|
339
|
+
if (!content) return;
|
|
340
|
+
|
|
341
|
+
if (isGroup) {
|
|
342
|
+
output += `### Document: "${file.name}"\n${content}\n`;
|
|
343
|
+
} else {
|
|
344
|
+
output += `${content}\n`;
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
output += `--- End of Source ${sourceCounter} ---\n\n`;
|
|
349
|
+
sourceCounter++;
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
return output;
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
/** 校验当前用户是否有权限使用该 Agent,并且余额是否充足(每轮调用) */
|
|
356
|
+
export const validateAccessAndBalance = (
|
|
357
|
+
agentConfig: Agent,
|
|
358
|
+
state: RootState,
|
|
359
|
+
): string | null => {
|
|
360
|
+
const userBalance = selectCurrentUserBalance(state);
|
|
361
|
+
const currentUserId = selectUserId(state);
|
|
362
|
+
|
|
363
|
+
if (typeof userBalance !== "number") {
|
|
364
|
+
return "正在获取用户余额,请稍候...";
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const isOwner = Boolean(currentUserId) && agentConfig.userId === currentUserId;
|
|
368
|
+
|
|
369
|
+
if (!isOwner) {
|
|
370
|
+
const hasWhitelist =
|
|
371
|
+
Array.isArray(agentConfig.whitelist) &&
|
|
372
|
+
agentConfig.whitelist.length > 0;
|
|
373
|
+
|
|
374
|
+
if (hasWhitelist) {
|
|
375
|
+
const isUserInWhitelist =
|
|
376
|
+
!!currentUserId && agentConfig.whitelist?.includes(currentUserId);
|
|
377
|
+
|
|
378
|
+
if (!isUserInWhitelist) {
|
|
379
|
+
return "您不在该应用的白名单中,无法使用。";
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const isCustomApi = agentConfig.apiSource === "custom";
|
|
385
|
+
const isCliApi = agentConfig.apiSource === "cli";
|
|
386
|
+
if (isCustomApi || isCliApi) {
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const serverPrices = getModelPricing(agentConfig.provider || "", agentConfig.model);
|
|
391
|
+
|
|
392
|
+
if (!serverPrices && !hasExplicitAgentPricing(agentConfig)) {
|
|
393
|
+
return "无法获取模型定价信息,请稍后重试。";
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const prices = getPrices(agentConfig, serverPrices ?? null);
|
|
397
|
+
const maxPrice = getFinalPrice(prices);
|
|
398
|
+
|
|
399
|
+
if (userBalance < maxPrice) {
|
|
400
|
+
return "余额不足,请充值后再试。";
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
return null;
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
/** 静态上下文:Loop 期间稳定不变的部分 */
|
|
407
|
+
export interface StaticContexts {
|
|
408
|
+
botInstructionsContext: string;
|
|
409
|
+
botKnowledgeContext: string;
|
|
410
|
+
spaceContext: string | null;
|
|
411
|
+
userGlobalPrompt: string | null;
|
|
412
|
+
userPolicyContext: string | null;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** 动态上下文:每轮 Loop 需要更新的部分 */
|
|
416
|
+
export interface DynamicContexts {
|
|
417
|
+
currentInputContext: string | null;
|
|
418
|
+
historyContext: string;
|
|
419
|
+
editingContext: string | null;
|
|
420
|
+
appWorkingMemory: string | null;
|
|
421
|
+
dialogSummary: string | null;
|
|
422
|
+
proactiveSummary: string | null;
|
|
423
|
+
referenceKeys: string[];
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* 构建静态上下文(Loop 外调用一次)
|
|
429
|
+
* 包含:botInstructions、botKnowledge、spaceContext、userGlobalPrompt
|
|
430
|
+
* 这些内容在 Agent Loop 期间是稳定的,不需要每轮重新构建
|
|
431
|
+
*/
|
|
432
|
+
export const buildStaticContexts = async (
|
|
433
|
+
state: RootState,
|
|
434
|
+
dispatch: any,
|
|
435
|
+
agentConfig: Agent,
|
|
436
|
+
dialogConfig?: DialogConfig,
|
|
437
|
+
referenceContentCache?: Map<string, any>,
|
|
438
|
+
): Promise<StaticContexts> => {
|
|
439
|
+
// 获取上下文 keys
|
|
440
|
+
const keySets = await getFullChatContextKeys(
|
|
441
|
+
state,
|
|
442
|
+
dispatch,
|
|
443
|
+
agentConfig,
|
|
444
|
+
"", // 静态上下文不需要 userInput
|
|
445
|
+
undefined, // 静态上下文不需要 dialogConfig
|
|
446
|
+
);
|
|
447
|
+
const finalKeys = deduplicateContextKeys(keySets);
|
|
448
|
+
|
|
449
|
+
const fetchReferences = (keys: string[]) =>
|
|
450
|
+
fetchReferenceContents(keys, dispatch, {
|
|
451
|
+
format: "simplified_markdown",
|
|
452
|
+
inlineMentionMeta: true,
|
|
453
|
+
preloaded: referenceContentCache,
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
// 并行获取静态引用内容
|
|
457
|
+
const [botInstructionsMap, botKnowledgeMap] = await Promise.all([
|
|
458
|
+
fetchReferences(finalKeys.botInstructionsContext),
|
|
459
|
+
fetchReferences(finalKeys.botKnowledgeContext),
|
|
460
|
+
]);
|
|
461
|
+
|
|
462
|
+
// 构建 spaceContext
|
|
463
|
+
const globalPrompt = selectGlobalPrompt(state);
|
|
464
|
+
const userTonePreset = selectUserTonePreset(state);
|
|
465
|
+
const knowledgeCaptureLevel = selectKnowledgeCaptureLevel(state);
|
|
466
|
+
const spaceContextLevel = selectSpaceContextLevel(state);
|
|
467
|
+
const currentSpace = selectCurrentSpace(state);
|
|
468
|
+
const userRecentLimit = selectAiRecentContentLimit(state);
|
|
469
|
+
const contextWindow = getModelContextWindow(agentConfig.model) || 128000;
|
|
470
|
+
const preloadPlan = resolveSpaceContextPreloadPlan(spaceContextLevel);
|
|
471
|
+
const dynamicLimit = Math.floor((contextWindow * preloadPlan.preloadBudgetRatio) / 150);
|
|
472
|
+
const recentLimit = preloadPlan.includeRecentContent
|
|
473
|
+
? Math.max(3, Math.min(userRecentLimit, Math.max(3, dynamicLimit)))
|
|
474
|
+
: 0;
|
|
475
|
+
|
|
476
|
+
let spaceContext: string | null = null;
|
|
477
|
+
|
|
478
|
+
if (currentSpace && spaceContextLevel > 1) {
|
|
479
|
+
const { categories, contents } = currentSpace;
|
|
480
|
+
const catEntries = Object.entries(categories || {}) as Array<
|
|
481
|
+
[string, Category | null]
|
|
482
|
+
>;
|
|
483
|
+
const validCatList = catEntries
|
|
484
|
+
.filter((entry) => entry[1] !== null)
|
|
485
|
+
.map((entry) => [entry[0], entry[1] as Category] as const)
|
|
486
|
+
.sort((a, b) => (a[1].order || 0) - (b[1].order || 0));
|
|
487
|
+
|
|
488
|
+
const catMap = new Map<string, string>();
|
|
489
|
+
let struct = "Directory Structure (Categories):\n";
|
|
490
|
+
if (validCatList.length === 0) struct += "(No categories defined)\n";
|
|
491
|
+
|
|
492
|
+
validCatList.forEach(([id, cat]) => {
|
|
493
|
+
catMap.set(id, cat.name);
|
|
494
|
+
struct += `- ${cat.name} (ID: ${id})\n`;
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
const contentEntries = Object.entries(contents || {}) as Array<
|
|
498
|
+
[string, SpaceContent | null]
|
|
499
|
+
>;
|
|
500
|
+
const contentList = recentLimit > 0
|
|
501
|
+
? contentEntries
|
|
502
|
+
.filter((entry) => entry[1] !== null)
|
|
503
|
+
.map((entry) => entry[1] as SpaceContent)
|
|
504
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
505
|
+
.slice(0, recentLimit)
|
|
506
|
+
: [];
|
|
507
|
+
|
|
508
|
+
if (contentList.length > 0) {
|
|
509
|
+
struct += `\nRecent Contents (Top ${recentLimit}):\n`;
|
|
510
|
+
contentList.forEach((c) => {
|
|
511
|
+
const item = c as SpaceContent;
|
|
512
|
+
const catName = item.categoryId
|
|
513
|
+
? catMap.get(item.categoryId) || "Unknown"
|
|
514
|
+
: "Uncategorized";
|
|
515
|
+
struct += `- [${item.type}] ${item.title} (Category: ${catName}, dbKey: ${item.contentKey})\n`;
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
spaceContext = `Space Title: ${currentSpace.name}\nSpace ID: ${currentSpace.id}\nDescription: ${currentSpace.description || "N/A"}\n\n${struct}`;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// 处理 linkedSpaces
|
|
523
|
+
const linkedSpaceIds = agentConfig.linkedSpaces || [];
|
|
524
|
+
if (linkedSpaceIds.length > 0 && spaceContextLevel > 1) {
|
|
525
|
+
const linkedSpacesInfo: string[] = [];
|
|
526
|
+
|
|
527
|
+
for (const spaceId of linkedSpaceIds) {
|
|
528
|
+
const spaceKey = createSpaceKey.space(spaceId);
|
|
529
|
+
const spaceData = await readSafe<any>(dispatch, spaceKey);
|
|
530
|
+
if (spaceData) {
|
|
531
|
+
const name = spaceData.name || spaceId;
|
|
532
|
+
const desc = spaceData.description || "";
|
|
533
|
+
linkedSpacesInfo.push(
|
|
534
|
+
`- ${name} (ID: ${spaceId})${desc ? `: ${desc}` : ""}`,
|
|
535
|
+
);
|
|
536
|
+
} else {
|
|
537
|
+
linkedSpacesInfo.push(`- [无法访问] ${spaceId}`);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
if (linkedSpacesInfo.length > 0) {
|
|
542
|
+
const linkedSection =
|
|
543
|
+
`\n\n--- 关联空间 (Linked Spaces) ---\n` +
|
|
544
|
+
`以下是 Agent 可访问的其他工作空间(粗略上下文):\n` +
|
|
545
|
+
linkedSpacesInfo.join("\n") +
|
|
546
|
+
`\n\n提示:如需查询这些空间的详细内容,可使用 read 工具配合对应的 dbKey。`;
|
|
547
|
+
|
|
548
|
+
spaceContext = (spaceContext || "") + linkedSection;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// 当前仓库里只有 personalization 这一类“特殊流程对话”需要在普通 agent 之外
|
|
553
|
+
// 额外追加工具/策略约束,因此先按 dialog category 做最小分流。
|
|
554
|
+
// 如果未来出现多个稳定存在的流程型入口(例如 onboarding / agent-authoring / skill-authoring),
|
|
555
|
+
// 再考虑把这层升级成统一的 dialog mode 抽象。
|
|
556
|
+
const dialogPolicyContext =
|
|
557
|
+
dialogConfig?.category === PERSONALIZATION_DIALOG_CATEGORY
|
|
558
|
+
? buildPersonalizationDialogPolicyContext()
|
|
559
|
+
: null;
|
|
560
|
+
|
|
561
|
+
return {
|
|
562
|
+
botInstructionsContext: joinMapValues(botInstructionsMap),
|
|
563
|
+
botKnowledgeContext: joinMapValues(botKnowledgeMap),
|
|
564
|
+
spaceContext,
|
|
565
|
+
userGlobalPrompt: globalPrompt,
|
|
566
|
+
userPolicyContext: [
|
|
567
|
+
buildStaticUserPolicyContext({
|
|
568
|
+
agentConfig,
|
|
569
|
+
settingsRecord: {
|
|
570
|
+
userTonePreset,
|
|
571
|
+
knowledgeCaptureLevel,
|
|
572
|
+
spaceContextLevel,
|
|
573
|
+
enableReadCurrentSpace: spaceContextLevel > 1,
|
|
574
|
+
},
|
|
575
|
+
}),
|
|
576
|
+
dialogPolicyContext,
|
|
577
|
+
]
|
|
578
|
+
.filter(Boolean)
|
|
579
|
+
.join("\n"),
|
|
580
|
+
};
|
|
581
|
+
};
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* 构建动态上下文(每轮 Loop 调用)
|
|
585
|
+
* 包含:currentInput、history、editingContext、dialogSummary
|
|
586
|
+
* 这些内容可能每轮变化,需要实时更新
|
|
587
|
+
*/
|
|
588
|
+
export const buildDynamicContexts = async (
|
|
589
|
+
state: RootState,
|
|
590
|
+
dispatch: any,
|
|
591
|
+
agentConfig: Agent,
|
|
592
|
+
userInput: string | any[],
|
|
593
|
+
runtimeOptions?: AgentRuntimeOptions,
|
|
594
|
+
referenceContentCache?: Map<string, any>,
|
|
595
|
+
dialogKey?: string,
|
|
596
|
+
): Promise<DynamicContexts> => {
|
|
597
|
+
// 读取 dialog summary 和 config
|
|
598
|
+
let dialogSummary: string | null = null;
|
|
599
|
+
let dialogConfig: DialogConfig | undefined;
|
|
600
|
+
if (dialogKey) {
|
|
601
|
+
dialogConfig = selectById(state, dialogKey) as DialogConfig | undefined;
|
|
602
|
+
if (dialogConfig?.summary) {
|
|
603
|
+
dialogSummary = dialogConfig.summary;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const keySets = await getFullChatContextKeys(
|
|
608
|
+
state,
|
|
609
|
+
dispatch,
|
|
610
|
+
agentConfig,
|
|
611
|
+
userInput,
|
|
612
|
+
dialogConfig,
|
|
613
|
+
);
|
|
614
|
+
const finalKeys = deduplicateContextKeys(keySets);
|
|
615
|
+
|
|
616
|
+
const fetchReferences = (keys: string[]) =>
|
|
617
|
+
fetchReferenceContents(keys, dispatch, {
|
|
618
|
+
format: "simplified_markdown",
|
|
619
|
+
inlineMentionMeta: true,
|
|
620
|
+
preloaded: referenceContentCache,
|
|
621
|
+
});
|
|
622
|
+
|
|
623
|
+
// 只获取动态引用内容
|
|
624
|
+
const [currentInputMap, historyMap] = await Promise.all([
|
|
625
|
+
fetchReferences(finalKeys.currentInputContext),
|
|
626
|
+
fetchReferences(finalKeys.historyContext),
|
|
627
|
+
]);
|
|
628
|
+
|
|
629
|
+
const pendingFiles = selectPendingFiles(state);
|
|
630
|
+
const formattedCurrentInputContext = formatCurrentInputContext(
|
|
631
|
+
pendingFiles,
|
|
632
|
+
currentInputMap,
|
|
633
|
+
);
|
|
634
|
+
|
|
635
|
+
const dialogId = dialogConfig?.id ?? null;
|
|
636
|
+
const currentDialogMessages = selectAllMsgs(state, dialogId);
|
|
637
|
+
const currentDialogMessageIds = new Set(currentDialogMessages.map((msg) => msg.id));
|
|
638
|
+
const currentDialogToolRuns = selectAllToolRuns(state).filter((run) =>
|
|
639
|
+
currentDialogMessageIds.has(run.messageId)
|
|
640
|
+
);
|
|
641
|
+
|
|
642
|
+
const editingContext = buildEditingContextSummary(state, runtimeOptions);
|
|
643
|
+
const appWorkingMemory = buildRecentAppToolMemory(
|
|
644
|
+
currentDialogMessages,
|
|
645
|
+
currentDialogToolRuns,
|
|
646
|
+
);
|
|
647
|
+
|
|
648
|
+
return {
|
|
649
|
+
currentInputContext: formattedCurrentInputContext.trim() || null,
|
|
650
|
+
historyContext: joinMapValues(historyMap),
|
|
651
|
+
editingContext,
|
|
652
|
+
appWorkingMemory,
|
|
653
|
+
dialogSummary,
|
|
654
|
+
proactiveSummary: dialogConfig?.proactiveSummary || null,
|
|
655
|
+
referenceKeys: dialogConfig?.referenceKeys || [],
|
|
656
|
+
};
|
|
657
|
+
};
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* 合并静态和动态上下文为完整的 Contexts 对象
|
|
661
|
+
*/
|
|
662
|
+
export const mergeContexts = (
|
|
663
|
+
staticCtx: StaticContexts,
|
|
664
|
+
dynamicCtx: DynamicContexts,
|
|
665
|
+
): Contexts => ({
|
|
666
|
+
botInstructionsContext: staticCtx.botInstructionsContext || undefined,
|
|
667
|
+
botKnowledgeContext: staticCtx.botKnowledgeContext || undefined,
|
|
668
|
+
spaceContext: staticCtx.spaceContext || undefined,
|
|
669
|
+
userGlobalPrompt: staticCtx.userGlobalPrompt || undefined,
|
|
670
|
+
userPolicyContext: staticCtx.userPolicyContext || undefined,
|
|
671
|
+
currentInputContext: dynamicCtx.currentInputContext,
|
|
672
|
+
historyContext: dynamicCtx.historyContext || undefined,
|
|
673
|
+
editingContext: dynamicCtx.editingContext,
|
|
674
|
+
appWorkingMemory: dynamicCtx.appWorkingMemory,
|
|
675
|
+
dialogSummary: dynamicCtx.dialogSummary,
|
|
676
|
+
proactiveSummary: dynamicCtx.proactiveSummary,
|
|
677
|
+
referenceKeys: dynamicCtx.referenceKeys,
|
|
678
|
+
});
|
|
679
|
+
|
|
680
|
+
/** 合并 Agent.tools + Context Page Tools + Mentioned Tools + runtimeOptions.extraTools */
|
|
681
|
+
export const mergeAgentToolsWithRuntime = (
|
|
682
|
+
agentConfig: Agent,
|
|
683
|
+
referencedTools: string[],
|
|
684
|
+
mentionedTools: string[],
|
|
685
|
+
runtimeOptions?: AgentRuntimeOptions,
|
|
686
|
+
state?: RootState,
|
|
687
|
+
): Agent => {
|
|
688
|
+
const rawBaseTools = Array.isArray((agentConfig as any).tools)
|
|
689
|
+
? ((agentConfig as any).tools as string[])
|
|
690
|
+
: [];
|
|
691
|
+
const baseTools = canonicalizeToolNames(rawBaseTools);
|
|
692
|
+
const requiredSkillTools = canonicalizeToolNames(
|
|
693
|
+
(agentConfig as any).referencedTools ?? []
|
|
694
|
+
);
|
|
695
|
+
const recommendedSkillTools = canonicalizeToolNames(
|
|
696
|
+
(agentConfig as any).recommendedSkillTools ?? []
|
|
697
|
+
);
|
|
698
|
+
const recommendedSkillHints = Array.from(
|
|
699
|
+
new Set(
|
|
700
|
+
((agentConfig as any).recommendedSkillHints ?? []).filter(
|
|
701
|
+
(item: unknown): item is string =>
|
|
702
|
+
typeof item === "string" && item.trim().length > 0,
|
|
703
|
+
),
|
|
704
|
+
),
|
|
705
|
+
);
|
|
706
|
+
const skillPromptPatches = Array.from(
|
|
707
|
+
new Set(
|
|
708
|
+
((agentConfig as any).skillPromptPatches ?? []).filter(
|
|
709
|
+
(item: unknown): item is string =>
|
|
710
|
+
typeof item === "string" && item.trim().length > 0,
|
|
711
|
+
),
|
|
712
|
+
),
|
|
713
|
+
);
|
|
714
|
+
const enhancedTools = new Set<string>([
|
|
715
|
+
...baseTools,
|
|
716
|
+
...(isInlineVisualArtifactAgent(agentConfig) ? [] : getRuntimeCoreTools()),
|
|
717
|
+
...(baseTools.length > 0 && !isInlineVisualArtifactAgent(agentConfig)
|
|
718
|
+
? TOOL_PACKS.LIGHT_WEB
|
|
719
|
+
: []),
|
|
720
|
+
...(isInlineVisualArtifactAgent(agentConfig) ? [] : requiredSkillTools),
|
|
721
|
+
...(isInlineVisualArtifactAgent(agentConfig)
|
|
722
|
+
? []
|
|
723
|
+
: canonicalizeToolNames(referencedTools)),
|
|
724
|
+
...(isInlineVisualArtifactAgent(agentConfig)
|
|
725
|
+
? []
|
|
726
|
+
: canonicalizeToolNames(mentionedTools)),
|
|
727
|
+
]);
|
|
728
|
+
|
|
729
|
+
// Intelligence: If user explicitly added ANY browser tool, auto-inject the FULL browser pack
|
|
730
|
+
const hasAnyBrowserTool = baseTools.some((t) => t.startsWith("browser_"));
|
|
731
|
+
if (hasAnyBrowserTool) {
|
|
732
|
+
TOOL_PACKS.FULL_BROWSER.forEach((t) => enhancedTools.add(t));
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
const extraTools = isInlineVisualArtifactAgent(agentConfig)
|
|
736
|
+
? []
|
|
737
|
+
: canonicalizeToolNames(runtimeOptions?.extraTools ?? []);
|
|
738
|
+
for (const t of extraTools) {
|
|
739
|
+
enhancedTools.add(t);
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
if (!isInlineVisualArtifactAgent(agentConfig)) {
|
|
743
|
+
const viewMode = state ? selectViewMode(state) : "categories";
|
|
744
|
+
if (viewMode === "all") {
|
|
745
|
+
enhancedTools.delete("search_workspace");
|
|
746
|
+
enhancedTools.add("search_all_spaces");
|
|
747
|
+
} else {
|
|
748
|
+
enhancedTools.delete("search_all_spaces");
|
|
749
|
+
enhancedTools.add("search_workspace");
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
return {
|
|
754
|
+
...agentConfig,
|
|
755
|
+
tools: prioritizeToolNames(
|
|
756
|
+
Array.from(enhancedTools),
|
|
757
|
+
recommendedSkillTools,
|
|
758
|
+
),
|
|
759
|
+
recommendedSkillTools,
|
|
760
|
+
recommendedSkillHints,
|
|
761
|
+
skillPromptPatches,
|
|
762
|
+
};
|
|
763
|
+
};
|
|
764
|
+
|
|
765
|
+
/** 应用本轮图片配置 override */
|
|
766
|
+
export const applyImageConfigRuntimeOverride = (
|
|
767
|
+
agentConfig: Agent,
|
|
768
|
+
runtimeOptions?: AgentRuntimeOptions,
|
|
769
|
+
): Agent => {
|
|
770
|
+
const override = runtimeOptions?.imageConfigOverride;
|
|
771
|
+
if (!override) {
|
|
772
|
+
return agentConfig;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
const baseImageConfig = (agentConfig as any).imageConfig ?? {};
|
|
776
|
+
|
|
777
|
+
return {
|
|
778
|
+
...agentConfig,
|
|
779
|
+
...(override.imageModelOverride
|
|
780
|
+
? { model: override.imageModelOverride }
|
|
781
|
+
: {}),
|
|
782
|
+
imageConfig: {
|
|
783
|
+
...baseImageConfig,
|
|
784
|
+
...override,
|
|
785
|
+
},
|
|
786
|
+
};
|
|
787
|
+
};
|
|
788
|
+
|
|
789
|
+
const formatImageWaitHint = (
|
|
790
|
+
range?: {
|
|
791
|
+
min: number;
|
|
792
|
+
max: number;
|
|
793
|
+
},
|
|
794
|
+
) => {
|
|
795
|
+
if (!range || typeof range.min !== "number" || typeof range.max !== "number") {
|
|
796
|
+
return undefined;
|
|
797
|
+
}
|
|
798
|
+
return `通常需要 ${range.min}-${range.max} 秒`;
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
const resolveAgentImageModelIdentity = (agentConfig: Partial<Agent>) => {
|
|
802
|
+
let providerKey = (agentConfig.provider || "").toLowerCase();
|
|
803
|
+
let modelName = agentConfig.model ?? "";
|
|
804
|
+
|
|
805
|
+
if (modelName.includes("/")) {
|
|
806
|
+
const slash = modelName.indexOf("/");
|
|
807
|
+
if (!providerKey) providerKey = modelName.slice(0, slash);
|
|
808
|
+
modelName = modelName.slice(slash + 1);
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
try {
|
|
812
|
+
return {
|
|
813
|
+
providerKey,
|
|
814
|
+
modelConfig: getModelConfig(providerKey as Provider, modelName),
|
|
815
|
+
};
|
|
816
|
+
} catch {
|
|
817
|
+
try {
|
|
818
|
+
const detected = getProviderByModelName(modelName);
|
|
819
|
+
if (!detected) {
|
|
820
|
+
return { providerKey, modelConfig: null };
|
|
821
|
+
}
|
|
822
|
+
return {
|
|
823
|
+
providerKey: detected,
|
|
824
|
+
modelConfig: getModelConfig(detected, modelName),
|
|
825
|
+
};
|
|
826
|
+
} catch {
|
|
827
|
+
return { providerKey, modelConfig: null };
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
|
|
832
|
+
export const resolveImageGenerationStreamingState = (
|
|
833
|
+
agentConfig: Agent,
|
|
834
|
+
args?: {
|
|
835
|
+
stage?: ImageGenerationState["stage"];
|
|
836
|
+
previous?: ImageGenerationState | null;
|
|
837
|
+
},
|
|
838
|
+
): ImageGenerationState | undefined => {
|
|
839
|
+
const { modelConfig } = resolveAgentImageModelIdentity(agentConfig);
|
|
840
|
+
const hasImageOutput =
|
|
841
|
+
!!(modelConfig?.hasImageOutput ?? (modelConfig as any)?.supportsImageOutput) ||
|
|
842
|
+
agentConfig.imageConfig?.enabled === true;
|
|
843
|
+
if (!hasImageOutput) {
|
|
844
|
+
return undefined;
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
const currentProfile = modelConfig?.imageGenerationProfiles?.find(
|
|
848
|
+
(profile) => profile.imageModel === modelConfig.name,
|
|
849
|
+
);
|
|
850
|
+
|
|
851
|
+
return {
|
|
852
|
+
kind: "image_generation",
|
|
853
|
+
stage: args?.stage ?? args?.previous?.stage ?? "submitted",
|
|
854
|
+
startedAt: args?.previous?.startedAt ?? Date.now(),
|
|
855
|
+
waitHint:
|
|
856
|
+
formatImageWaitHint(modelConfig?.imageGenerationWaitTimeSeconds) ??
|
|
857
|
+
"通常需要几十秒",
|
|
858
|
+
profileLabel: currentProfile?.label,
|
|
859
|
+
};
|
|
860
|
+
};
|