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,2001 @@
|
|
|
1
|
+
// 文件路径: packages/ai/agent/streamAgentChatTurn.ts
|
|
2
|
+
import { extractCustomId } from "../../core/prefix";
|
|
3
|
+
import { createDialogMessageKeyAndId } from "../../database/keys";
|
|
4
|
+
import { DataType } from "../../create/types";
|
|
5
|
+
import { isLiveAudioOnlyAgent } from "./isLiveAudioOnlyAgent";
|
|
6
|
+
|
|
7
|
+
import type { RootState } from "../../app/store";
|
|
8
|
+
import { patch, read, selectById } from "../../database/dbSlice";
|
|
9
|
+
import { generateRequestBody } from "../llm/generateRequestBody";
|
|
10
|
+
import {
|
|
11
|
+
selectCurrentDialogConfig,
|
|
12
|
+
selectDialogConfigByKey,
|
|
13
|
+
addActiveController,
|
|
14
|
+
removeActiveController,
|
|
15
|
+
selectPendingUserInputQueue,
|
|
16
|
+
dequeueUserInput,
|
|
17
|
+
clearPendingUserInputQueue,
|
|
18
|
+
} from "../../chat/dialog/dialogSlice";
|
|
19
|
+
import { removeTransientMessage, selectAllMsgs } from "../../chat/messages/messageSlice";
|
|
20
|
+
import {
|
|
21
|
+
selectContextRetention,
|
|
22
|
+
selectMaxExecutionTime,
|
|
23
|
+
selectCurrentServer,
|
|
24
|
+
} from "../../app/settings/settingSlice";
|
|
25
|
+
import { filterAndCleanMessages } from "../../integrations/openai/filterAndCleanMessages";
|
|
26
|
+
import {
|
|
27
|
+
getFullChatContextKeys,
|
|
28
|
+
deduplicateContextKeys,
|
|
29
|
+
} from "../agent/getFullChatContextKeys";
|
|
30
|
+
import type { Agent, DialogConfig } from "../../app/types";
|
|
31
|
+
import { isResponseAPIModel } from "../llm/isResponseAPIModel";
|
|
32
|
+
import { getModelContextWindow } from "../llm/getModelContextWindow";
|
|
33
|
+
import { resolveAgentImageInputSupport } from "../llm/agentCapabilities";
|
|
34
|
+
|
|
35
|
+
import {
|
|
36
|
+
sendOpenAICompletionsRequest,
|
|
37
|
+
type CompletionMeta,
|
|
38
|
+
} from "../chat/sendOpenAICompletionsRequest";
|
|
39
|
+
import { sendOpenAIResponseRequest } from "../chat/sendOpenAIResponseRequest";
|
|
40
|
+
|
|
41
|
+
import type { AgentRuntimeOptions } from "./types";
|
|
42
|
+
import { buildAgentViewMessages } from "./cleanAgentMessages";
|
|
43
|
+
import { extractCategorizedMentions, type CategorizedMentions } from "../../create/editor/utils/slateUtils";
|
|
44
|
+
import { resolveReferenceAssets, resolveToolsFromKeys } from "./referenceUtils";
|
|
45
|
+
import { estimateTokenCount } from "../context/tokenUtils";
|
|
46
|
+
import {
|
|
47
|
+
applyImageConfigRuntimeOverride,
|
|
48
|
+
buildStaticContexts,
|
|
49
|
+
compressOldToolResults,
|
|
50
|
+
buildDynamicContexts,
|
|
51
|
+
mergeContexts,
|
|
52
|
+
hasImageInMessages,
|
|
53
|
+
mergeAgentToolsWithRuntime,
|
|
54
|
+
resolveImageGenerationStreamingState,
|
|
55
|
+
trimMessagesWithSummary,
|
|
56
|
+
validateAccessAndBalance,
|
|
57
|
+
} from "./streamAgentChatTurnUtils";
|
|
58
|
+
import { buildCliPrompt } from "./cliPrompt";
|
|
59
|
+
import { createCliChatTurnStream } from "./cliChatClient";
|
|
60
|
+
import { getCliChatSession, startCliChatSession } from "./cliChatClient";
|
|
61
|
+
import {
|
|
62
|
+
messageStreamEnd,
|
|
63
|
+
messageStreaming,
|
|
64
|
+
prepareAndPersistUserMessage,
|
|
65
|
+
} from "../../chat/messages/messageSlice";
|
|
66
|
+
import { selectCurrentToken, selectUserId } from "../../auth/authSlice";
|
|
67
|
+
import { persistMessageWithFixedId } from "./persistMessageWithFixedId";
|
|
68
|
+
import { updateTotalUsage } from "../chat/updateTotalUsage";
|
|
69
|
+
import { createSSEParser } from "../chat/parseMultilineSSE";
|
|
70
|
+
import { performServerProxyFetchWithRetry } from "../chat/serverProxyRetry";
|
|
71
|
+
import { normalizeServerOrigin } from "./serverOrigin";
|
|
72
|
+
import { getIsDesktopApp } from "../../app/utils/env";
|
|
73
|
+
import { runDesktopAgentRuntimeTurn } from "../../app/utils/desktopAgentRuntimeTurnClient";
|
|
74
|
+
import { resolveRuntimeToolSurfaceForAgent } from "../../agent-runtime/runtimeToolSurface";
|
|
75
|
+
|
|
76
|
+
const BUILTIN_NOLO_AGENT_ID = "01NOLOAPPBLD000000019KCKT0";
|
|
77
|
+
const BUILTIN_NOLO_AGENT_KEY = `agent-pub-${BUILTIN_NOLO_AGENT_ID}`;
|
|
78
|
+
|
|
79
|
+
const buildParallelMessageMetadata = (
|
|
80
|
+
agentConfig: Pick<Agent, "dbKey" | "name">,
|
|
81
|
+
runtimeOptions?: AgentRuntimeOptions,
|
|
82
|
+
) => {
|
|
83
|
+
const rawName =
|
|
84
|
+
typeof agentConfig?.name === "string" ? agentConfig.name.trim() : "";
|
|
85
|
+
return {
|
|
86
|
+
agentKey: agentConfig.dbKey,
|
|
87
|
+
cybotKey: agentConfig.dbKey,
|
|
88
|
+
...(rawName ? { agentName: rawName } : {}),
|
|
89
|
+
...(runtimeOptions?.parallelSessionId
|
|
90
|
+
? { parallelSessionId: runtimeOptions.parallelSessionId }
|
|
91
|
+
: {}),
|
|
92
|
+
...(runtimeOptions?.parallelBranchId
|
|
93
|
+
? { parallelBranchId: runtimeOptions.parallelBranchId }
|
|
94
|
+
: {}),
|
|
95
|
+
...(runtimeOptions?.parallelLabel
|
|
96
|
+
? { parallelLabel: runtimeOptions.parallelLabel }
|
|
97
|
+
: {}),
|
|
98
|
+
...(runtimeOptions?.parallelIndex !== undefined
|
|
99
|
+
? { parallelIndex: runtimeOptions.parallelIndex }
|
|
100
|
+
: {}),
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const filterMessagesForParallelBranch = (
|
|
105
|
+
messages: any[],
|
|
106
|
+
runtimeOptions?: AgentRuntimeOptions,
|
|
107
|
+
) => {
|
|
108
|
+
if (!runtimeOptions?.parallelSessionId) return messages;
|
|
109
|
+
|
|
110
|
+
return messages.filter((message: any) => {
|
|
111
|
+
const sessionId = message?.parallelSessionId;
|
|
112
|
+
if (sessionId !== runtimeOptions.parallelSessionId) {
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
return message?.parallelBranchId === runtimeOptions.parallelBranchId;
|
|
116
|
+
});
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const isDesktopBuiltinNoloAgent = (
|
|
120
|
+
requestedAgentKey: string,
|
|
121
|
+
agentConfig: Partial<Agent> | null | undefined,
|
|
122
|
+
) => {
|
|
123
|
+
if (!getIsDesktopApp()) return false;
|
|
124
|
+
const candidates = [
|
|
125
|
+
requestedAgentKey,
|
|
126
|
+
agentConfig?.dbKey,
|
|
127
|
+
agentConfig?.agentKey,
|
|
128
|
+
agentConfig?.id,
|
|
129
|
+
];
|
|
130
|
+
return candidates.some((value) =>
|
|
131
|
+
typeof value === "string" &&
|
|
132
|
+
(value === BUILTIN_NOLO_AGENT_KEY ||
|
|
133
|
+
value === BUILTIN_NOLO_AGENT_ID ||
|
|
134
|
+
value.endsWith(`-${BUILTIN_NOLO_AGENT_ID}`))
|
|
135
|
+
);
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const resolveWebAgentRuntimeToolSurface = (
|
|
139
|
+
agentConfig: Agent,
|
|
140
|
+
state: RootState,
|
|
141
|
+
): Agent => {
|
|
142
|
+
const toolSurface = resolveRuntimeToolSurfaceForAgent({
|
|
143
|
+
explicitToolNames: Array.isArray((agentConfig as any).tools)
|
|
144
|
+
? (agentConfig as any).tools
|
|
145
|
+
: [],
|
|
146
|
+
currentUserId: selectUserId(state),
|
|
147
|
+
agentOwnerId: typeof (agentConfig as any).userId === "string"
|
|
148
|
+
? (agentConfig as any).userId
|
|
149
|
+
: null,
|
|
150
|
+
agentKey: (agentConfig as any).dbKey ?? (agentConfig as any).agentKey,
|
|
151
|
+
isPublic: (agentConfig as any).isPublic === true,
|
|
152
|
+
sharingLevel: typeof (agentConfig as any).sharingLevel === "string"
|
|
153
|
+
? (agentConfig as any).sharingLevel
|
|
154
|
+
: null,
|
|
155
|
+
runtimeHost: "web",
|
|
156
|
+
});
|
|
157
|
+
return {
|
|
158
|
+
...agentConfig,
|
|
159
|
+
tools: toolSurface.finalToolNames,
|
|
160
|
+
runtimeToolSurface: toolSurface,
|
|
161
|
+
} as Agent;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const formatMachineAgentRunError = async (response: Response): Promise<string> => {
|
|
165
|
+
const errorText = await response.text();
|
|
166
|
+
let payload: any = null;
|
|
167
|
+
try {
|
|
168
|
+
payload = errorText ? JSON.parse(errorText) : null;
|
|
169
|
+
} catch {
|
|
170
|
+
payload = null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const reason = typeof payload?.reason === "string" ? payload.reason : "";
|
|
174
|
+
if (response.status === 409) {
|
|
175
|
+
if (reason === "bound_machine_unavailable") {
|
|
176
|
+
return "绑定的电脑不在线。请确认这台电脑已开机并重新运行连接命令。";
|
|
177
|
+
}
|
|
178
|
+
if (reason === "bound_machine_owner_mismatch") {
|
|
179
|
+
return "这台电脑是在线的,但当前账号和 Agent 绑定账号不一致。请重新绑定 Agent,或在绑定账号下重新连接这台电脑。";
|
|
180
|
+
}
|
|
181
|
+
if (reason === "connector_offline") {
|
|
182
|
+
return "电脑在线,但连接器未连接。请在这台电脑上重新运行连接命令后再试。";
|
|
183
|
+
}
|
|
184
|
+
if (reason === "missing_capability") {
|
|
185
|
+
return "这台电脑没有对应的 CLI 能力。请安装对应 CLI,或把 Agent 绑定到另一台电脑。";
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const message =
|
|
190
|
+
typeof payload?.message === "string" && payload.message.trim()
|
|
191
|
+
? payload.message.trim()
|
|
192
|
+
: typeof payload?.error === "string" && payload.error.trim()
|
|
193
|
+
? payload.error.trim()
|
|
194
|
+
: errorText.trim();
|
|
195
|
+
return message || `Machine agent run failed (${response.status})`;
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
const normalizeThreadMetadataPatch = (value: unknown) => {
|
|
199
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
200
|
+
const record = value as Record<string, unknown>;
|
|
201
|
+
const changes: Record<string, string> = {};
|
|
202
|
+
if (typeof record.threadKind === "string" && record.threadKind.trim()) {
|
|
203
|
+
changes.threadKind = record.threadKind.trim();
|
|
204
|
+
}
|
|
205
|
+
if (
|
|
206
|
+
typeof record.presentationIntent === "string" &&
|
|
207
|
+
record.presentationIntent.trim()
|
|
208
|
+
) {
|
|
209
|
+
changes.presentationIntent = record.presentationIntent.trim();
|
|
210
|
+
}
|
|
211
|
+
return Object.keys(changes).length > 0 ? changes : null;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const patchDialogThreadMetadata = async (
|
|
215
|
+
dispatch: any,
|
|
216
|
+
dialogKey: string,
|
|
217
|
+
metadata: unknown,
|
|
218
|
+
) => {
|
|
219
|
+
const changes = normalizeThreadMetadataPatch(metadata);
|
|
220
|
+
if (!changes) return;
|
|
221
|
+
await dispatch(
|
|
222
|
+
patch({
|
|
223
|
+
dbKey: dialogKey,
|
|
224
|
+
changes,
|
|
225
|
+
}),
|
|
226
|
+
).unwrap?.();
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
const patchDialogActiveAgent = async (
|
|
230
|
+
dispatch: any,
|
|
231
|
+
dialogKey: string,
|
|
232
|
+
agentKey: unknown,
|
|
233
|
+
) => {
|
|
234
|
+
if (typeof agentKey !== "string" || !agentKey.trim()) return;
|
|
235
|
+
await dispatch(
|
|
236
|
+
patch({
|
|
237
|
+
dbKey: dialogKey,
|
|
238
|
+
changes: {
|
|
239
|
+
primaryAgentKey: agentKey.trim(),
|
|
240
|
+
},
|
|
241
|
+
}),
|
|
242
|
+
).unwrap?.();
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
/** streamAgentChatTurn 参数(聊天轮次专用) */
|
|
246
|
+
export interface StreamAgentChatTurnArgs {
|
|
247
|
+
agentKey: string;
|
|
248
|
+
userInput: string | any[];
|
|
249
|
+
serverBase?: string;
|
|
250
|
+
dialogKey?: string; // 可选。显式指定目标对话,不传则使用当前活跃对话。
|
|
251
|
+
isStreaming?: boolean;
|
|
252
|
+
parentMessageId?: string;
|
|
253
|
+
runtimeOptions?: AgentRuntimeOptions;
|
|
254
|
+
quickChatPerfStartedAt?: number;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const QUICK_CHAT_AGENT_CONFIG_READ_TIMEOUT_MS = 10_000;
|
|
258
|
+
const QUICK_CHAT_DYNAMIC_CONTEXT_TIMEOUT_MS = 5_000;
|
|
259
|
+
const EMPTY_DYNAMIC_CONTEXTS = {
|
|
260
|
+
currentInputContext: null,
|
|
261
|
+
historyContext: "",
|
|
262
|
+
editingContext: null,
|
|
263
|
+
appWorkingMemory: null,
|
|
264
|
+
dialogSummary: null,
|
|
265
|
+
proactiveSummary: null,
|
|
266
|
+
referenceKeys: [],
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
function appendCliCapabilityWarnings(content: string, warnings: string[]): string {
|
|
270
|
+
if (!warnings.length) return content;
|
|
271
|
+
const warningBlock = `\n\n[CLI 能力提示]\n${warnings.map((warning) => `- ${warning}`).join("\n")}`;
|
|
272
|
+
return `${content}${warningBlock}`;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const logQuickChatPerfStage = (
|
|
276
|
+
startedAt: number | undefined,
|
|
277
|
+
stage: string,
|
|
278
|
+
details: Record<string, unknown> = {}
|
|
279
|
+
) => {
|
|
280
|
+
if (!startedAt) return;
|
|
281
|
+
const now = typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
282
|
+
console.info("[QuickChatPerf]", {
|
|
283
|
+
stage,
|
|
284
|
+
elapsedMs: now - startedAt,
|
|
285
|
+
...(typeof performance !== "undefined" ? { atMs: now } : {}),
|
|
286
|
+
...details,
|
|
287
|
+
});
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
const readAgentConfigForTurn = async (
|
|
291
|
+
dispatch: any,
|
|
292
|
+
agentKey: string,
|
|
293
|
+
quickChatPerfStartedAt?: number,
|
|
294
|
+
): Promise<Agent> => {
|
|
295
|
+
const readPromise = dispatch(read({ dbKey: agentKey })).unwrap() as Promise<Agent>;
|
|
296
|
+
if (!quickChatPerfStartedAt) return readPromise;
|
|
297
|
+
|
|
298
|
+
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
299
|
+
try {
|
|
300
|
+
return await Promise.race([
|
|
301
|
+
readPromise,
|
|
302
|
+
new Promise<Agent>((_, reject) => {
|
|
303
|
+
timeoutId = setTimeout(() => {
|
|
304
|
+
logQuickChatPerfStage(
|
|
305
|
+
quickChatPerfStartedAt,
|
|
306
|
+
"quick-chat-agent-config-read-timeout",
|
|
307
|
+
{
|
|
308
|
+
agentKey,
|
|
309
|
+
timeoutMs: QUICK_CHAT_AGENT_CONFIG_READ_TIMEOUT_MS,
|
|
310
|
+
},
|
|
311
|
+
);
|
|
312
|
+
reject(
|
|
313
|
+
new Error("读取 Agent 配置超时,未能启动模型回复。"),
|
|
314
|
+
);
|
|
315
|
+
}, QUICK_CHAT_AGENT_CONFIG_READ_TIMEOUT_MS);
|
|
316
|
+
}),
|
|
317
|
+
]);
|
|
318
|
+
} finally {
|
|
319
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
const buildDynamicContextsForTurn = async (
|
|
324
|
+
state: RootState,
|
|
325
|
+
dispatch: any,
|
|
326
|
+
agentConfig: Agent,
|
|
327
|
+
userInput: string | any[],
|
|
328
|
+
runtimeOptions: AgentRuntimeOptions | undefined,
|
|
329
|
+
mergedContentCache: Map<string, any>,
|
|
330
|
+
dialogKey: string | undefined,
|
|
331
|
+
quickChatPerfStartedAt?: number,
|
|
332
|
+
) => {
|
|
333
|
+
if (!quickChatPerfStartedAt) {
|
|
334
|
+
return buildDynamicContexts(
|
|
335
|
+
state,
|
|
336
|
+
dispatch,
|
|
337
|
+
agentConfig,
|
|
338
|
+
userInput,
|
|
339
|
+
runtimeOptions,
|
|
340
|
+
mergedContentCache,
|
|
341
|
+
dialogKey,
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
346
|
+
try {
|
|
347
|
+
const timeoutPromise = new Promise<typeof EMPTY_DYNAMIC_CONTEXTS>((resolve) => {
|
|
348
|
+
timeoutId = setTimeout(() => {
|
|
349
|
+
logQuickChatPerfStage(
|
|
350
|
+
quickChatPerfStartedAt,
|
|
351
|
+
"quick-chat-dynamic-context-timeout",
|
|
352
|
+
{
|
|
353
|
+
agentKey: agentConfig.dbKey,
|
|
354
|
+
dialogKey,
|
|
355
|
+
timeoutMs: QUICK_CHAT_DYNAMIC_CONTEXT_TIMEOUT_MS,
|
|
356
|
+
},
|
|
357
|
+
);
|
|
358
|
+
resolve(EMPTY_DYNAMIC_CONTEXTS);
|
|
359
|
+
}, QUICK_CHAT_DYNAMIC_CONTEXT_TIMEOUT_MS);
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
logQuickChatPerfStage(
|
|
363
|
+
quickChatPerfStartedAt,
|
|
364
|
+
"stream-agent-dynamic-context-starting",
|
|
365
|
+
{
|
|
366
|
+
responseApi: isResponseAPIModel(agentConfig),
|
|
367
|
+
},
|
|
368
|
+
);
|
|
369
|
+
const contextPromise = buildDynamicContexts(
|
|
370
|
+
state,
|
|
371
|
+
dispatch,
|
|
372
|
+
agentConfig,
|
|
373
|
+
userInput,
|
|
374
|
+
runtimeOptions,
|
|
375
|
+
mergedContentCache,
|
|
376
|
+
dialogKey,
|
|
377
|
+
);
|
|
378
|
+
|
|
379
|
+
return await Promise.race([
|
|
380
|
+
contextPromise,
|
|
381
|
+
timeoutPromise,
|
|
382
|
+
]);
|
|
383
|
+
} finally {
|
|
384
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
const finalizeQuickChatAgentTurnFailure = async (
|
|
389
|
+
dispatch: any,
|
|
390
|
+
dialogKey: string,
|
|
391
|
+
agentKey: string,
|
|
392
|
+
error: unknown,
|
|
393
|
+
) => {
|
|
394
|
+
const dialogId = extractCustomId(dialogKey);
|
|
395
|
+
const { key: msgKey, messageId } = createDialogMessageKeyAndId(dialogId);
|
|
396
|
+
const reason =
|
|
397
|
+
error instanceof Error && error.message.trim()
|
|
398
|
+
? error.message.trim()
|
|
399
|
+
: "未能启动模型回复,请重试。";
|
|
400
|
+
|
|
401
|
+
await dispatch(
|
|
402
|
+
messageStreamEnd({
|
|
403
|
+
finalContentBuffer: [
|
|
404
|
+
{
|
|
405
|
+
type: "text",
|
|
406
|
+
text: `[错误: ${reason}]`,
|
|
407
|
+
},
|
|
408
|
+
],
|
|
409
|
+
totalUsage: null,
|
|
410
|
+
msgKey,
|
|
411
|
+
agentConfig: {
|
|
412
|
+
dbKey: agentKey,
|
|
413
|
+
},
|
|
414
|
+
dialogId,
|
|
415
|
+
dialogKey,
|
|
416
|
+
messageId,
|
|
417
|
+
reasoningBuffer: "",
|
|
418
|
+
})
|
|
419
|
+
).unwrap?.();
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
const normalizeAgentRunUserInput = (userInput: string | any[]) => {
|
|
423
|
+
if (typeof userInput === "string") {
|
|
424
|
+
return userInput;
|
|
425
|
+
}
|
|
426
|
+
if (!Array.isArray(userInput)) {
|
|
427
|
+
return "";
|
|
428
|
+
}
|
|
429
|
+
return userInput.filter((part) => {
|
|
430
|
+
if (!part || typeof part !== "object") return false;
|
|
431
|
+
if (part.type === "text") return typeof part.text === "string";
|
|
432
|
+
return (
|
|
433
|
+
part.type === "image_url" &&
|
|
434
|
+
typeof part.image_url?.url === "string" &&
|
|
435
|
+
!!part.image_url.url.trim()
|
|
436
|
+
);
|
|
437
|
+
});
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
const isSimpleTextInput = (userInput: string | any[]) => {
|
|
441
|
+
if (typeof userInput === "string") return true;
|
|
442
|
+
if (!Array.isArray(userInput)) return false;
|
|
443
|
+
return userInput.every(
|
|
444
|
+
(part) =>
|
|
445
|
+
part &&
|
|
446
|
+
typeof part === "object" &&
|
|
447
|
+
part.type === "text" &&
|
|
448
|
+
typeof part.text === "string",
|
|
449
|
+
);
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
const canUseQuickChatEmptyDynamicContexts = (
|
|
453
|
+
quickChatPerfStartedAt: number | undefined,
|
|
454
|
+
userInput: string | any[],
|
|
455
|
+
runtimeOptions: AgentRuntimeOptions | undefined,
|
|
456
|
+
dialogConfig: DialogConfig | null,
|
|
457
|
+
) => {
|
|
458
|
+
if (!quickChatPerfStartedAt) return false;
|
|
459
|
+
if (runtimeOptions) return false;
|
|
460
|
+
if (!isSimpleTextInput(userInput)) return false;
|
|
461
|
+
if (dialogConfig?.referenceKeys?.length) return false;
|
|
462
|
+
return true;
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
const QUICK_CHAT_DIRECT_ANSWER_PATTERN =
|
|
466
|
+
/(只回复|只输出|只回答|直接回复|直接回答|不要解释|无需解释|不用解释|简短回答|一句话)/i;
|
|
467
|
+
const QUICK_CHAT_TOOL_INTENT_PATTERN =
|
|
468
|
+
/(调用|转交|agent|助手|应用|网页|页面|图表|图片|生成图|画图|删除|清理|空间|商品|链接|https?:\/\/|www\.|@)/i;
|
|
469
|
+
|
|
470
|
+
const shouldDisableQuickChatToolsForDirectAnswer = (
|
|
471
|
+
quickChatPerfStartedAt: number | undefined,
|
|
472
|
+
userInput: string | any[],
|
|
473
|
+
runtimeOptions: AgentRuntimeOptions | undefined,
|
|
474
|
+
dialogConfig: DialogConfig | null,
|
|
475
|
+
) => {
|
|
476
|
+
if (!canUseQuickChatEmptyDynamicContexts(
|
|
477
|
+
quickChatPerfStartedAt,
|
|
478
|
+
userInput,
|
|
479
|
+
runtimeOptions,
|
|
480
|
+
dialogConfig,
|
|
481
|
+
)) {
|
|
482
|
+
return false;
|
|
483
|
+
}
|
|
484
|
+
const text = extractAgentRunUserText(userInput);
|
|
485
|
+
if (!text || text.length > 500) return false;
|
|
486
|
+
if (!QUICK_CHAT_DIRECT_ANSWER_PATTERN.test(text)) return false;
|
|
487
|
+
return !QUICK_CHAT_TOOL_INTENT_PATTERN.test(text);
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
const classifyQuickChatAccessError = (accessError: string) => {
|
|
491
|
+
if (accessError.includes("获取用户余额")) return "balance-loading";
|
|
492
|
+
if (accessError.includes("余额")) return "balance";
|
|
493
|
+
if (accessError.includes("白名单")) return "whitelist";
|
|
494
|
+
if (accessError.includes("定价")) return "pricing";
|
|
495
|
+
return "unknown";
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
const isUsableAgentConfig = (value: unknown): value is Agent =>
|
|
499
|
+
!!value &&
|
|
500
|
+
typeof value === "object" &&
|
|
501
|
+
(value as any).__ssrPreviewOnly !== true &&
|
|
502
|
+
typeof (value as Agent).dbKey === "string" &&
|
|
503
|
+
!!(value as Agent).dbKey &&
|
|
504
|
+
typeof (value as Agent).model === "string" &&
|
|
505
|
+
!!(value as Agent).model &&
|
|
506
|
+
typeof (value as Agent).provider === "string" &&
|
|
507
|
+
!!(value as Agent).provider;
|
|
508
|
+
|
|
509
|
+
const extractAgentRunUserText = (userInput: string | any[]) => {
|
|
510
|
+
if (typeof userInput === "string") {
|
|
511
|
+
return userInput;
|
|
512
|
+
}
|
|
513
|
+
if (!Array.isArray(userInput)) {
|
|
514
|
+
return "";
|
|
515
|
+
}
|
|
516
|
+
return userInput
|
|
517
|
+
.filter((part) => part?.type === "text" && typeof part.text === "string")
|
|
518
|
+
.map((part) => part.text)
|
|
519
|
+
.join("\n")
|
|
520
|
+
.trim();
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
const hasAgentRunUserInputContent = (userInput: string | any[]) => {
|
|
524
|
+
if (typeof userInput === "string") {
|
|
525
|
+
return userInput.trim().length > 0;
|
|
526
|
+
}
|
|
527
|
+
return Array.isArray(userInput) && userInput.length > 0;
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* 真正用于“聊天轮次”的流式 Agent 调用(带 Agent Loop):
|
|
532
|
+
* - 每轮检查权限 & 余额
|
|
533
|
+
* - 每轮重建上下文 & 消息
|
|
534
|
+
* - 调用 Completions/Response API
|
|
535
|
+
* - 对 Completions 模型,基于 tool_calls / handoff / pending 决定是否继续
|
|
536
|
+
*/
|
|
537
|
+
export const streamAgentChatTurnHandler = async (
|
|
538
|
+
args: StreamAgentChatTurnArgs,
|
|
539
|
+
thunkApi: any,
|
|
540
|
+
) => {
|
|
541
|
+
const {
|
|
542
|
+
agentKey,
|
|
543
|
+
userInput,
|
|
544
|
+
dialogKey: explicitDialogKey,
|
|
545
|
+
parentMessageId,
|
|
546
|
+
runtimeOptions,
|
|
547
|
+
quickChatPerfStartedAt,
|
|
548
|
+
} = args;
|
|
549
|
+
const { getState, dispatch, rejectWithValue } = thunkApi;
|
|
550
|
+
const state = getState() as RootState;
|
|
551
|
+
|
|
552
|
+
// 🚀 额外引入一个 Loop 控制器,用于中止整个 Agent 循环
|
|
553
|
+
const loopController = new AbortController();
|
|
554
|
+
const isAbortError = (error?: { name?: string } | null) =>
|
|
555
|
+
error?.name === "AbortError" || loopController.signal.aborted || thunkApi.signal.aborted;
|
|
556
|
+
const onAbort = () => loopController.abort();
|
|
557
|
+
thunkApi.signal.addEventListener("abort", onAbort);
|
|
558
|
+
let loopKey: string | null = null;
|
|
559
|
+
let runtimeDialogKey: string | null = explicitDialogKey ?? null;
|
|
560
|
+
let remoteTransientMessageId: string | null = null;
|
|
561
|
+
let remoteTransientMessageFinalized = false;
|
|
562
|
+
let modelRequestStarted = false;
|
|
563
|
+
|
|
564
|
+
try {
|
|
565
|
+
let totalTurnUsage: any = null;
|
|
566
|
+
const agentRunUserInput = normalizeAgentRunUserInput(userInput);
|
|
567
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-entered", {
|
|
568
|
+
agentKey,
|
|
569
|
+
dialogKey: explicitDialogKey ?? null,
|
|
570
|
+
});
|
|
571
|
+
// 1. 读取 Agent 配置。Quick Chat 会提前预热默认 agent;命中 Redux DB 缓存时避免重复读。
|
|
572
|
+
const cachedAgentConfig = selectById(getState() as RootState, agentKey);
|
|
573
|
+
const rawAgentConfig = isUsableAgentConfig(cachedAgentConfig)
|
|
574
|
+
? cachedAgentConfig
|
|
575
|
+
: await readAgentConfigForTurn(
|
|
576
|
+
dispatch,
|
|
577
|
+
agentKey,
|
|
578
|
+
quickChatPerfStartedAt,
|
|
579
|
+
);
|
|
580
|
+
if (!rawAgentConfig) {
|
|
581
|
+
return rejectWithValue(`Agent config not found for ID: ${agentKey}`);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ── Live-audio-only guard ────────────────────────────────────────────
|
|
585
|
+
if (isLiveAudioOnlyAgent(rawAgentConfig)) {
|
|
586
|
+
return rejectWithValue(
|
|
587
|
+
"此 Agent 仅支持实时语音模式,请使用语音面板进行对话。",
|
|
588
|
+
);
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const agentConfig = resolveWebAgentRuntimeToolSurface(
|
|
592
|
+
rawAgentConfig,
|
|
593
|
+
getState() as RootState,
|
|
594
|
+
);
|
|
595
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-config-read", {
|
|
596
|
+
agentKey,
|
|
597
|
+
model: agentConfig.model,
|
|
598
|
+
provider: agentConfig.provider,
|
|
599
|
+
apiSource: agentConfig.apiSource,
|
|
600
|
+
source: cachedAgentConfig === rawAgentConfig ? "cache" : "read",
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
const boundMachineId =
|
|
604
|
+
typeof (agentConfig as any).runtimeBinding?.machineId === "string"
|
|
605
|
+
? (agentConfig as any).runtimeBinding.machineId.trim()
|
|
606
|
+
: "";
|
|
607
|
+
|
|
608
|
+
// ── Remote runtime route ─────────────────────────────────────────────
|
|
609
|
+
// runtimeBinding selects the bound machine. Without it, custom provider
|
|
610
|
+
// requests stay on the normal OpenAI-compatible path, where
|
|
611
|
+
// useServerProxy decides server proxy vs current-client direct fetch.
|
|
612
|
+
if (agentConfig.apiSource === "cli" || boundMachineId) {
|
|
613
|
+
const currentState = getState() as RootState;
|
|
614
|
+
const w =
|
|
615
|
+
typeof globalThis !== "undefined" && (globalThis as any).window
|
|
616
|
+
? (globalThis as any).window
|
|
617
|
+
: null;
|
|
618
|
+
if (w) w.__LOOP_STOP_REASON__ = null;
|
|
619
|
+
|
|
620
|
+
const userText = extractAgentRunUserText(userInput);
|
|
621
|
+
|
|
622
|
+
const prompt = buildCliPrompt(agentConfig.prompt, userText);
|
|
623
|
+
|
|
624
|
+
// 生成消息 key
|
|
625
|
+
const dialogConfig =
|
|
626
|
+
selectDialogConfigByKey(currentState, explicitDialogKey) ??
|
|
627
|
+
selectCurrentDialogConfig(currentState);
|
|
628
|
+
if (!dialogConfig) {
|
|
629
|
+
return rejectWithValue("Dialog config not found");
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const dialogKey = explicitDialogKey || dialogConfig.dbKey;
|
|
633
|
+
if (!dialogKey) {
|
|
634
|
+
return rejectWithValue("当前对话不存在,无法发送消息。");
|
|
635
|
+
}
|
|
636
|
+
runtimeDialogKey = dialogKey;
|
|
637
|
+
const dialogId = extractCustomId(dialogKey);
|
|
638
|
+
loopKey = `loop:${dialogId}`;
|
|
639
|
+
dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey }));
|
|
640
|
+
|
|
641
|
+
const { key: msgKey, messageId } = createDialogMessageKeyAndId(dialogId);
|
|
642
|
+
const cliMessageMetadata = buildParallelMessageMetadata(
|
|
643
|
+
agentConfig,
|
|
644
|
+
runtimeOptions,
|
|
645
|
+
);
|
|
646
|
+
if (boundMachineId) {
|
|
647
|
+
const token = selectCurrentToken(currentState);
|
|
648
|
+
const authHeader = token ? `Bearer ${token}` : "";
|
|
649
|
+
const rawMessages = filterMessagesForParallelBranch(
|
|
650
|
+
selectAllMsgs(currentState, dialogId),
|
|
651
|
+
runtimeOptions,
|
|
652
|
+
);
|
|
653
|
+
const visibleMessages = buildAgentViewMessages(
|
|
654
|
+
rawMessages as any,
|
|
655
|
+
agentConfig.dbKey,
|
|
656
|
+
);
|
|
657
|
+
const cleanedMessages = filterAndCleanMessages(visibleMessages);
|
|
658
|
+
const currentServer = selectCurrentServer(currentState);
|
|
659
|
+
remoteTransientMessageId = messageId;
|
|
660
|
+
let accumulated = "";
|
|
661
|
+
let totalTurnUsage: any = undefined;
|
|
662
|
+
const buildMachineAssistantMessage = () => ({
|
|
663
|
+
id: messageId,
|
|
664
|
+
dbKey: msgKey,
|
|
665
|
+
role: "assistant" as const,
|
|
666
|
+
content: accumulated,
|
|
667
|
+
...cliMessageMetadata,
|
|
668
|
+
userId: selectUserId(getState() as RootState),
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
dispatch(messageStreaming({
|
|
672
|
+
id: messageId,
|
|
673
|
+
dialogId,
|
|
674
|
+
dbKey: msgKey,
|
|
675
|
+
content: "",
|
|
676
|
+
role: "assistant",
|
|
677
|
+
...cliMessageMetadata,
|
|
678
|
+
}));
|
|
679
|
+
|
|
680
|
+
const rejectMachineStream = async (message: string) => {
|
|
681
|
+
if (accumulated.length > 0) {
|
|
682
|
+
await persistMessageWithFixedId(dispatch, buildMachineAssistantMessage());
|
|
683
|
+
} else {
|
|
684
|
+
dispatch(removeTransientMessage(messageId));
|
|
685
|
+
}
|
|
686
|
+
remoteTransientMessageFinalized = true;
|
|
687
|
+
return rejectWithValue(message);
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
const machineResponse = await fetch(`${currentServer.replace(/\/+$/, "")}/api/agent/run`, {
|
|
691
|
+
method: "POST",
|
|
692
|
+
headers: {
|
|
693
|
+
"Content-Type": "application/json",
|
|
694
|
+
Accept: "text/event-stream",
|
|
695
|
+
...(authHeader ? { Authorization: authHeader } : {}),
|
|
696
|
+
},
|
|
697
|
+
body: JSON.stringify({
|
|
698
|
+
agentKey,
|
|
699
|
+
userInput: agentRunUserInput,
|
|
700
|
+
messages: cleanedMessages,
|
|
701
|
+
stream: true,
|
|
702
|
+
persistDialog: false,
|
|
703
|
+
clientDialogId: dialogId,
|
|
704
|
+
runtimeContext: {
|
|
705
|
+
surface: "web",
|
|
706
|
+
host: "browser",
|
|
707
|
+
runtime: "react",
|
|
708
|
+
entrypoint: "chat-dialog",
|
|
709
|
+
capabilities: ["streaming", "dialog-ui", "machine-bound-cli"],
|
|
710
|
+
},
|
|
711
|
+
...((dialogConfig as any)?.spaceId ? { spaceId: (dialogConfig as any).spaceId } : {}),
|
|
712
|
+
}),
|
|
713
|
+
signal: loopController.signal,
|
|
714
|
+
});
|
|
715
|
+
|
|
716
|
+
if (!machineResponse.ok) {
|
|
717
|
+
return await rejectMachineStream(
|
|
718
|
+
await formatMachineAgentRunError(machineResponse),
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
const reader = machineResponse.body?.getReader();
|
|
723
|
+
if (!reader) {
|
|
724
|
+
return await rejectMachineStream("无法读取电脑端 Agent 流式响应");
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
const decoder = new TextDecoder();
|
|
728
|
+
const parseSSE = createSSEParser();
|
|
729
|
+
const abortMachineStream = async () => {
|
|
730
|
+
if (w) w.__LOOP_STOP_REASON__ = "aborted";
|
|
731
|
+
if (accumulated.length <= 0) return;
|
|
732
|
+
await persistMessageWithFixedId(dispatch, buildMachineAssistantMessage());
|
|
733
|
+
};
|
|
734
|
+
|
|
735
|
+
try {
|
|
736
|
+
while (true) {
|
|
737
|
+
const { done, value } = await reader.read();
|
|
738
|
+
if (done) break;
|
|
739
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
740
|
+
await abortMachineStream();
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
const payloads = parseSSE(
|
|
745
|
+
decoder.decode(value, { stream: true }),
|
|
746
|
+
);
|
|
747
|
+
for (const payload of payloads) {
|
|
748
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
749
|
+
await abortMachineStream();
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (payload.type === "error") {
|
|
753
|
+
return await rejectMachineStream(
|
|
754
|
+
payload.message || "电脑端 Agent 执行失败",
|
|
755
|
+
);
|
|
756
|
+
}
|
|
757
|
+
if (payload.type === "text" && typeof payload.content === "string") {
|
|
758
|
+
accumulated += payload.content;
|
|
759
|
+
dispatch(messageStreaming({
|
|
760
|
+
id: messageId,
|
|
761
|
+
dialogId,
|
|
762
|
+
dbKey: msgKey,
|
|
763
|
+
content: accumulated,
|
|
764
|
+
role: "assistant",
|
|
765
|
+
...cliMessageMetadata,
|
|
766
|
+
}));
|
|
767
|
+
}
|
|
768
|
+
if (payload.type === "done") {
|
|
769
|
+
totalTurnUsage = payload.usage;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
775
|
+
await abortMachineStream();
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
await persistMessageWithFixedId(dispatch, buildMachineAssistantMessage());
|
|
780
|
+
remoteTransientMessageFinalized = true;
|
|
781
|
+
} finally {
|
|
782
|
+
try {
|
|
783
|
+
await reader.cancel();
|
|
784
|
+
} catch {
|
|
785
|
+
// ignore
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
return {
|
|
790
|
+
usage: totalTurnUsage ?? undefined,
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
let cliSessionId = dialogConfig.cliSessionId ?? null;
|
|
795
|
+
|
|
796
|
+
// 先创建一条空的流式消息(让用户立刻看到 loading 状态)
|
|
797
|
+
dispatch(messageStreaming({
|
|
798
|
+
id: messageId,
|
|
799
|
+
dialogId,
|
|
800
|
+
dbKey: msgKey,
|
|
801
|
+
content: "",
|
|
802
|
+
role: "assistant",
|
|
803
|
+
...cliMessageMetadata,
|
|
804
|
+
}));
|
|
805
|
+
|
|
806
|
+
const ensureCliSession = async () => {
|
|
807
|
+
if (cliSessionId) {
|
|
808
|
+
const existing = await getCliChatSession(
|
|
809
|
+
{ getState },
|
|
810
|
+
{ sessionId: cliSessionId },
|
|
811
|
+
).catch(() => null);
|
|
812
|
+
if (existing?.ok && existing?.session?.sessionId) {
|
|
813
|
+
return cliSessionId;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
const started = await startCliChatSession(
|
|
818
|
+
{ getState },
|
|
819
|
+
{
|
|
820
|
+
cliProvider: agentConfig.cliProvider || "copilot",
|
|
821
|
+
model: agentConfig.model || undefined,
|
|
822
|
+
systemPrompt: agentConfig.prompt || undefined,
|
|
823
|
+
reasoningEffort: agentConfig.reasoning_effort || undefined,
|
|
824
|
+
temperature: agentConfig.temperature,
|
|
825
|
+
topP: agentConfig.top_p,
|
|
826
|
+
frequencyPenalty: agentConfig.frequency_penalty,
|
|
827
|
+
presencePenalty: agentConfig.presence_penalty,
|
|
828
|
+
maxTokens: agentConfig.max_tokens,
|
|
829
|
+
enableThinking: agentConfig.enableThinking,
|
|
830
|
+
thinkingBudget: agentConfig.thinkingBudget,
|
|
831
|
+
},
|
|
832
|
+
);
|
|
833
|
+
|
|
834
|
+
const newSessionId =
|
|
835
|
+
typeof started?.sessionId === "string" ? started.sessionId : null;
|
|
836
|
+
if (!newSessionId) {
|
|
837
|
+
throw new Error("无法创建 CLI session。");
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
cliSessionId = newSessionId;
|
|
841
|
+
const patchResult = dispatch(
|
|
842
|
+
patch({
|
|
843
|
+
dbKey: dialogKey,
|
|
844
|
+
changes: {
|
|
845
|
+
cliSessionId: newSessionId,
|
|
846
|
+
},
|
|
847
|
+
})
|
|
848
|
+
) as any;
|
|
849
|
+
try {
|
|
850
|
+
if (typeof patchResult?.unwrap === "function") {
|
|
851
|
+
await patchResult.unwrap();
|
|
852
|
+
} else {
|
|
853
|
+
await patchResult;
|
|
854
|
+
}
|
|
855
|
+
} catch {
|
|
856
|
+
// Best effort only. Session still exists server-side even if dialog persistence fails.
|
|
857
|
+
}
|
|
858
|
+
return newSessionId;
|
|
859
|
+
};
|
|
860
|
+
|
|
861
|
+
const initialSessionId = await ensureCliSession();
|
|
862
|
+
let resp = await createCliChatTurnStream(
|
|
863
|
+
{
|
|
864
|
+
getState,
|
|
865
|
+
},
|
|
866
|
+
{
|
|
867
|
+
sessionId: initialSessionId,
|
|
868
|
+
prompt,
|
|
869
|
+
model: agentConfig.model || undefined,
|
|
870
|
+
},
|
|
871
|
+
loopController.signal,
|
|
872
|
+
);
|
|
873
|
+
|
|
874
|
+
if (!resp.ok && resp.status === 404) {
|
|
875
|
+
cliSessionId = null;
|
|
876
|
+
const renewedSessionId = await ensureCliSession();
|
|
877
|
+
resp = await createCliChatTurnStream(
|
|
878
|
+
{
|
|
879
|
+
getState,
|
|
880
|
+
},
|
|
881
|
+
{
|
|
882
|
+
sessionId: renewedSessionId,
|
|
883
|
+
prompt,
|
|
884
|
+
model: agentConfig.model || undefined,
|
|
885
|
+
},
|
|
886
|
+
loopController.signal,
|
|
887
|
+
);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
if (!resp.ok) {
|
|
891
|
+
const err = await resp.json().catch(() => ({ error: resp.statusText }));
|
|
892
|
+
return rejectWithValue(err.error || "CLI 执行失败");
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// 读取 SSE 流并逐步更新消息内容
|
|
896
|
+
const reader = resp.body?.getReader();
|
|
897
|
+
if (!reader) {
|
|
898
|
+
return rejectWithValue("无法读取流式响应");
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
let accumulated = "";
|
|
902
|
+
let cliCapabilityWarnings: string[] = [];
|
|
903
|
+
const decoder = new TextDecoder();
|
|
904
|
+
const buildCliAssistantMessage = () => ({
|
|
905
|
+
id: messageId,
|
|
906
|
+
dbKey: msgKey,
|
|
907
|
+
role: "assistant" as const,
|
|
908
|
+
content: accumulated,
|
|
909
|
+
...cliMessageMetadata,
|
|
910
|
+
userId: selectUserId(getState() as RootState),
|
|
911
|
+
});
|
|
912
|
+
const abortCliStream = async () => {
|
|
913
|
+
if (w) w.__LOOP_STOP_REASON__ = "aborted";
|
|
914
|
+
if (accumulated.length <= 0) {
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
await persistMessageWithFixedId(dispatch, buildCliAssistantMessage());
|
|
918
|
+
};
|
|
919
|
+
|
|
920
|
+
try {
|
|
921
|
+
while (true) {
|
|
922
|
+
const { done, value } = await reader.read();
|
|
923
|
+
if (done) break;
|
|
924
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
925
|
+
await abortCliStream();
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
const raw = decoder.decode(value, { stream: true });
|
|
930
|
+
// 解析 SSE 格式 "data: {...}\n\n"
|
|
931
|
+
const lines = raw.split("\n");
|
|
932
|
+
for (const line of lines) {
|
|
933
|
+
if (!line.startsWith("data: ")) continue;
|
|
934
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
935
|
+
await abortCliStream();
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
try {
|
|
939
|
+
const payload = JSON.parse(line.slice(6));
|
|
940
|
+
if (payload.error) {
|
|
941
|
+
return rejectWithValue(payload.error);
|
|
942
|
+
}
|
|
943
|
+
if (payload.chunk) {
|
|
944
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
945
|
+
await abortCliStream();
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
accumulated += payload.chunk;
|
|
949
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
950
|
+
await abortCliStream();
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
dispatch(messageStreaming({
|
|
954
|
+
id: messageId,
|
|
955
|
+
dialogId,
|
|
956
|
+
dbKey: msgKey,
|
|
957
|
+
content: accumulated,
|
|
958
|
+
role: "assistant",
|
|
959
|
+
...cliMessageMetadata,
|
|
960
|
+
}));
|
|
961
|
+
}
|
|
962
|
+
if (payload.done && Array.isArray(payload.warnings)) {
|
|
963
|
+
cliCapabilityWarnings = payload.warnings.filter((warning): warning is string => typeof warning === "string" && warning.trim().length > 0);
|
|
964
|
+
}
|
|
965
|
+
} catch {
|
|
966
|
+
// 忽略解析失败的行
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
972
|
+
await abortCliStream();
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
if (cliCapabilityWarnings.length > 0) {
|
|
977
|
+
accumulated = appendCliCapabilityWarnings(accumulated, cliCapabilityWarnings);
|
|
978
|
+
dispatch(messageStreaming({
|
|
979
|
+
id: messageId,
|
|
980
|
+
dialogId,
|
|
981
|
+
dbKey: msgKey,
|
|
982
|
+
content: accumulated,
|
|
983
|
+
role: "assistant",
|
|
984
|
+
...cliMessageMetadata,
|
|
985
|
+
}));
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// 持久化最终消息:用已有 ID,避免 prepareAndPersistMessage 重新生成 ID 导致重复
|
|
989
|
+
await persistMessageWithFixedId(dispatch, buildCliAssistantMessage());
|
|
990
|
+
} finally {
|
|
991
|
+
try {
|
|
992
|
+
await reader.cancel();
|
|
993
|
+
} catch {
|
|
994
|
+
// ignore
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
1001
|
+
|
|
1002
|
+
const currentDialog =
|
|
1003
|
+
selectDialogConfigByKey(state, explicitDialogKey) ??
|
|
1004
|
+
selectCurrentDialogConfig(state);
|
|
1005
|
+
const activeDialogKey = currentDialog?.dbKey;
|
|
1006
|
+
const dialogKey = explicitDialogKey || activeDialogKey;
|
|
1007
|
+
|
|
1008
|
+
if (!dialogKey) {
|
|
1009
|
+
return rejectWithValue("当前对话不存在,无法发送消息。");
|
|
1010
|
+
}
|
|
1011
|
+
runtimeDialogKey = dialogKey;
|
|
1012
|
+
const dialogId = extractCustomId(dialogKey);
|
|
1013
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-dialog-resolved", {
|
|
1014
|
+
dialogKey,
|
|
1015
|
+
dialogId,
|
|
1016
|
+
});
|
|
1017
|
+
|
|
1018
|
+
if (isDesktopBuiltinNoloAgent(agentKey, agentConfig)) {
|
|
1019
|
+
const { key: msgKey, messageId } = createDialogMessageKeyAndId(dialogId);
|
|
1020
|
+
const desktopMessageMetadata = buildParallelMessageMetadata(
|
|
1021
|
+
agentConfig,
|
|
1022
|
+
runtimeOptions,
|
|
1023
|
+
);
|
|
1024
|
+
remoteTransientMessageId = messageId;
|
|
1025
|
+
loopKey = `loop:${dialogId}`;
|
|
1026
|
+
dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey }));
|
|
1027
|
+
dispatch(messageStreaming({
|
|
1028
|
+
id: messageId,
|
|
1029
|
+
dialogId,
|
|
1030
|
+
dbKey: msgKey,
|
|
1031
|
+
content: "",
|
|
1032
|
+
role: "assistant",
|
|
1033
|
+
...desktopMessageMetadata,
|
|
1034
|
+
}));
|
|
1035
|
+
|
|
1036
|
+
const localResult = await runDesktopAgentRuntimeTurn({
|
|
1037
|
+
agentRef: agentConfig.dbKey || agentKey,
|
|
1038
|
+
input: userInput,
|
|
1039
|
+
continueDialogId: dialogId,
|
|
1040
|
+
});
|
|
1041
|
+
if (!localResult.ok) {
|
|
1042
|
+
dispatch(removeTransientMessage(messageId));
|
|
1043
|
+
remoteTransientMessageFinalized = true;
|
|
1044
|
+
return rejectWithValue(localResult.error);
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
dispatch(messageStreaming({
|
|
1048
|
+
id: messageId,
|
|
1049
|
+
dialogId,
|
|
1050
|
+
dbKey: msgKey,
|
|
1051
|
+
content: localResult.result.content || "",
|
|
1052
|
+
role: "assistant",
|
|
1053
|
+
...desktopMessageMetadata,
|
|
1054
|
+
}));
|
|
1055
|
+
await dispatch(messageStreamEnd({
|
|
1056
|
+
finalContentBuffer: [
|
|
1057
|
+
{
|
|
1058
|
+
type: "text",
|
|
1059
|
+
text: localResult.result.content || "",
|
|
1060
|
+
},
|
|
1061
|
+
],
|
|
1062
|
+
totalUsage: localResult.result.usage ?? undefined,
|
|
1063
|
+
messageId,
|
|
1064
|
+
msgKey,
|
|
1065
|
+
agentConfig,
|
|
1066
|
+
dialogId,
|
|
1067
|
+
dialogKey,
|
|
1068
|
+
reasoningBuffer: "",
|
|
1069
|
+
toolCalls: [],
|
|
1070
|
+
messageMetadata: desktopMessageMetadata,
|
|
1071
|
+
})).unwrap();
|
|
1072
|
+
remoteTransientMessageFinalized = true;
|
|
1073
|
+
return {
|
|
1074
|
+
usage: localResult.result.usage ?? undefined,
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
const userInputText = extractAgentRunUserText(userInput);
|
|
1079
|
+
|
|
1080
|
+
const explicitServerBase =
|
|
1081
|
+
typeof args.serverBase === "string" && args.serverBase.trim()
|
|
1082
|
+
? args.serverBase.trim()
|
|
1083
|
+
: null;
|
|
1084
|
+
const currentServer = selectCurrentServer(state);
|
|
1085
|
+
const normalizedRequestedServerBase =
|
|
1086
|
+
explicitServerBase && normalizeServerOrigin(explicitServerBase);
|
|
1087
|
+
const normalizedCurrentServer = normalizeServerOrigin(
|
|
1088
|
+
currentServer,
|
|
1089
|
+
);
|
|
1090
|
+
const canProxyToExplicitServerBase =
|
|
1091
|
+
!Array.isArray(userInput) &&
|
|
1092
|
+
!runtimeOptions?.extraTools?.length &&
|
|
1093
|
+
!runtimeOptions?.editingTarget &&
|
|
1094
|
+
!runtimeOptions?.imageConfigOverride;
|
|
1095
|
+
if (explicitServerBase && canProxyToExplicitServerBase) {
|
|
1096
|
+
if (
|
|
1097
|
+
normalizedRequestedServerBase &&
|
|
1098
|
+
normalizedCurrentServer &&
|
|
1099
|
+
normalizedRequestedServerBase === normalizedCurrentServer
|
|
1100
|
+
) {
|
|
1101
|
+
// Same server as the current workspace; keep the UI-managed
|
|
1102
|
+
// chat/tool loop and let /api/chat hydrate redacted provider
|
|
1103
|
+
// credentials server-side when needed.
|
|
1104
|
+
} else {
|
|
1105
|
+
const token = selectCurrentToken(state);
|
|
1106
|
+
const authHeader = token ? `Bearer ${token}` : "";
|
|
1107
|
+
const rawMessages = filterMessagesForParallelBranch(
|
|
1108
|
+
selectAllMsgs(state, dialogId),
|
|
1109
|
+
runtimeOptions,
|
|
1110
|
+
);
|
|
1111
|
+
const visibleMessages = buildAgentViewMessages(
|
|
1112
|
+
rawMessages as any,
|
|
1113
|
+
agentConfig.dbKey,
|
|
1114
|
+
);
|
|
1115
|
+
const cleanedMessages = filterAndCleanMessages(visibleMessages);
|
|
1116
|
+
const { key: msgKey, messageId } = createDialogMessageKeyAndId(dialogId);
|
|
1117
|
+
remoteTransientMessageId = messageId;
|
|
1118
|
+
const remoteMessageMetadata = buildParallelMessageMetadata(
|
|
1119
|
+
agentConfig,
|
|
1120
|
+
runtimeOptions,
|
|
1121
|
+
);
|
|
1122
|
+
let accumulated = "";
|
|
1123
|
+
let totalTurnUsage: any = undefined;
|
|
1124
|
+
const buildRemoteAssistantMessage = () => ({
|
|
1125
|
+
id: messageId,
|
|
1126
|
+
dbKey: msgKey,
|
|
1127
|
+
role: "assistant" as const,
|
|
1128
|
+
content: accumulated,
|
|
1129
|
+
...remoteMessageMetadata,
|
|
1130
|
+
userId: selectUserId(getState() as RootState),
|
|
1131
|
+
});
|
|
1132
|
+
|
|
1133
|
+
loopKey = `loop:${dialogId}`;
|
|
1134
|
+
dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey }));
|
|
1135
|
+
dispatch(messageStreaming({
|
|
1136
|
+
id: messageId,
|
|
1137
|
+
dialogId,
|
|
1138
|
+
dbKey: msgKey,
|
|
1139
|
+
content: "",
|
|
1140
|
+
role: "assistant",
|
|
1141
|
+
...remoteMessageMetadata,
|
|
1142
|
+
}));
|
|
1143
|
+
|
|
1144
|
+
const rejectRemoteStream = async (message: string) => {
|
|
1145
|
+
if (accumulated.length > 0) {
|
|
1146
|
+
await persistMessageWithFixedId(dispatch, buildRemoteAssistantMessage());
|
|
1147
|
+
} else {
|
|
1148
|
+
dispatch(removeTransientMessage(messageId));
|
|
1149
|
+
}
|
|
1150
|
+
remoteTransientMessageFinalized = true;
|
|
1151
|
+
return rejectWithValue(message);
|
|
1152
|
+
};
|
|
1153
|
+
|
|
1154
|
+
const remoteRequestBody = JSON.stringify({
|
|
1155
|
+
agentKey,
|
|
1156
|
+
userInput: agentRunUserInput,
|
|
1157
|
+
messages: cleanedMessages,
|
|
1158
|
+
stream: true,
|
|
1159
|
+
persistDialog: false,
|
|
1160
|
+
clientDialogId: dialogId,
|
|
1161
|
+
runtimeContext: {
|
|
1162
|
+
surface: "web",
|
|
1163
|
+
host: "browser",
|
|
1164
|
+
runtime: "react",
|
|
1165
|
+
entrypoint: "chat-dialog",
|
|
1166
|
+
capabilities: ["streaming", "dialog-ui", "tool-cards"],
|
|
1167
|
+
},
|
|
1168
|
+
...(currentDialog?.spaceId ? { spaceId: currentDialog.spaceId } : {}),
|
|
1169
|
+
});
|
|
1170
|
+
const remoteRunUrl = `${explicitServerBase.replace(/\/+$/, "")}/api/agent/run`;
|
|
1171
|
+
const remoteResponse = await performServerProxyFetchWithRetry({
|
|
1172
|
+
execute: () => fetch(remoteRunUrl, {
|
|
1173
|
+
method: "POST",
|
|
1174
|
+
headers: {
|
|
1175
|
+
"Content-Type": "application/json",
|
|
1176
|
+
Accept: "text/event-stream",
|
|
1177
|
+
...(authHeader ? { Authorization: authHeader } : {}),
|
|
1178
|
+
},
|
|
1179
|
+
body: remoteRequestBody,
|
|
1180
|
+
signal: loopController.signal,
|
|
1181
|
+
}),
|
|
1182
|
+
signal: loopController.signal,
|
|
1183
|
+
logPrefix: "[streamAgentChatTurn.remoteRun]",
|
|
1184
|
+
});
|
|
1185
|
+
|
|
1186
|
+
if (!remoteResponse.ok) {
|
|
1187
|
+
const errorText = await remoteResponse.text();
|
|
1188
|
+
return await rejectRemoteStream(
|
|
1189
|
+
errorText || `Remote agent run failed (${remoteResponse.status})`,
|
|
1190
|
+
);
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
const reader = remoteResponse.body?.getReader();
|
|
1194
|
+
if (!reader) {
|
|
1195
|
+
return await rejectRemoteStream("无法读取远端流式响应");
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
const decoder = new TextDecoder();
|
|
1199
|
+
const parseSSE = createSSEParser();
|
|
1200
|
+
const abortRemoteStream = async () => {
|
|
1201
|
+
if (accumulated.length <= 0) return;
|
|
1202
|
+
await persistMessageWithFixedId(dispatch, buildRemoteAssistantMessage());
|
|
1203
|
+
};
|
|
1204
|
+
|
|
1205
|
+
try {
|
|
1206
|
+
while (true) {
|
|
1207
|
+
const { done, value } = await reader.read();
|
|
1208
|
+
if (done) break;
|
|
1209
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
1210
|
+
await abortRemoteStream();
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
const payloads = parseSSE(
|
|
1215
|
+
decoder.decode(value, { stream: true }),
|
|
1216
|
+
);
|
|
1217
|
+
for (const payload of payloads) {
|
|
1218
|
+
if (payload.type === "error") {
|
|
1219
|
+
return await rejectRemoteStream(
|
|
1220
|
+
payload.message || "远端 Agent 执行失败",
|
|
1221
|
+
);
|
|
1222
|
+
}
|
|
1223
|
+
if (payload.type === "agent_handoff") {
|
|
1224
|
+
await patchDialogThreadMetadata(
|
|
1225
|
+
dispatch,
|
|
1226
|
+
dialogKey,
|
|
1227
|
+
payload.threadMetadata,
|
|
1228
|
+
);
|
|
1229
|
+
await patchDialogActiveAgent(
|
|
1230
|
+
dispatch,
|
|
1231
|
+
dialogKey,
|
|
1232
|
+
payload.agentKey,
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
if (payload.type === "text" && typeof payload.content === "string") {
|
|
1236
|
+
accumulated += payload.content;
|
|
1237
|
+
dispatch(messageStreaming({
|
|
1238
|
+
id: messageId,
|
|
1239
|
+
dialogId,
|
|
1240
|
+
dbKey: msgKey,
|
|
1241
|
+
content: accumulated,
|
|
1242
|
+
role: "assistant",
|
|
1243
|
+
...remoteMessageMetadata,
|
|
1244
|
+
}));
|
|
1245
|
+
}
|
|
1246
|
+
if (payload.type === "done") {
|
|
1247
|
+
totalTurnUsage = payload.usage;
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
} finally {
|
|
1252
|
+
try {
|
|
1253
|
+
await reader.cancel();
|
|
1254
|
+
} catch {
|
|
1255
|
+
// ignore
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
await persistMessageWithFixedId(dispatch, buildRemoteAssistantMessage());
|
|
1260
|
+
remoteTransientMessageFinalized = true;
|
|
1261
|
+
return {
|
|
1262
|
+
usage: totalTurnUsage ?? undefined,
|
|
1263
|
+
};
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
// Extract Mentions from userInput if it's potentially Slate content
|
|
1268
|
+
let extractedMentions: CategorizedMentions | undefined;
|
|
1269
|
+
if (Array.isArray(userInput)) {
|
|
1270
|
+
// Basic check if it looks like Slate nodes (has children) or just assume safe to traverse
|
|
1271
|
+
// extractCategorizedMentions handles traversal safely.
|
|
1272
|
+
extractedMentions = extractCategorizedMentions(userInput as any);
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
const mentionedTools = extractedMentions?.tools ?? [];
|
|
1276
|
+
|
|
1277
|
+
// 2. 解析引用:包含 tools 的页面自动升级为 instruction
|
|
1278
|
+
const {
|
|
1279
|
+
references: normalizedReferences,
|
|
1280
|
+
contentByKey: referenceContentCache,
|
|
1281
|
+
referencedTools: referenceTools,
|
|
1282
|
+
recommendedSkillTools: referenceRecommendedSkillTools,
|
|
1283
|
+
recommendedSkillHints: referenceRecommendedSkillHints,
|
|
1284
|
+
skillPromptPatches: referenceSkillPromptPatches,
|
|
1285
|
+
} = await resolveReferenceAssets(agentConfig.references, dispatch);
|
|
1286
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-references-resolved", {
|
|
1287
|
+
referenceCount: normalizedReferences?.length ?? 0,
|
|
1288
|
+
referencedToolCount: referenceTools?.length ?? 0,
|
|
1289
|
+
});
|
|
1290
|
+
|
|
1291
|
+
const agentConfigWithReferences = {
|
|
1292
|
+
...agentConfig,
|
|
1293
|
+
references: normalizedReferences,
|
|
1294
|
+
referencedTools: referenceTools,
|
|
1295
|
+
recommendedSkillTools: referenceRecommendedSkillTools,
|
|
1296
|
+
recommendedSkillHints: referenceRecommendedSkillHints,
|
|
1297
|
+
skillPromptPatches: referenceSkillPromptPatches,
|
|
1298
|
+
};
|
|
1299
|
+
|
|
1300
|
+
// --- [新增] 提取本次 Handler 启动前的稳定历史消息 ID 集合 ---
|
|
1301
|
+
const initialRawMsgs = selectAllMsgs(state, dialogId);
|
|
1302
|
+
const initialHistoryIds = new Set(initialRawMsgs.map((m: any) => m.id));
|
|
1303
|
+
|
|
1304
|
+
const keySets = await getFullChatContextKeys(
|
|
1305
|
+
state,
|
|
1306
|
+
dispatch,
|
|
1307
|
+
agentConfigWithReferences,
|
|
1308
|
+
userInput,
|
|
1309
|
+
currentDialog ?? undefined,
|
|
1310
|
+
);
|
|
1311
|
+
const finalKeys = deduplicateContextKeys(keySets);
|
|
1312
|
+
const allContextKeys = new Set<string>([
|
|
1313
|
+
...finalKeys.botInstructionsContext,
|
|
1314
|
+
...finalKeys.currentInputContext,
|
|
1315
|
+
...finalKeys.historyContext,
|
|
1316
|
+
...finalKeys.botKnowledgeContext,
|
|
1317
|
+
]);
|
|
1318
|
+
|
|
1319
|
+
// 4. 上下文页面里提取 tools 并缓存内容
|
|
1320
|
+
const {
|
|
1321
|
+
tools: contextTools,
|
|
1322
|
+
contentByKey: contextContentCache,
|
|
1323
|
+
recommendedSkillTools: contextRecommendedSkillTools = [],
|
|
1324
|
+
recommendedSkillHints: contextRecommendedSkillHints = [],
|
|
1325
|
+
skillPromptPatches: contextSkillPromptPatches = [],
|
|
1326
|
+
} = await resolveToolsFromKeys(
|
|
1327
|
+
Array.from(allContextKeys),
|
|
1328
|
+
dispatch,
|
|
1329
|
+
referenceContentCache,
|
|
1330
|
+
);
|
|
1331
|
+
|
|
1332
|
+
const mergedContentCache = new Map<string, any>([
|
|
1333
|
+
...referenceContentCache,
|
|
1334
|
+
...contextContentCache,
|
|
1335
|
+
]);
|
|
1336
|
+
|
|
1337
|
+
// 4. 合并工具 (Base + Default + Context + Mentioned + Runtime) + 图片配置
|
|
1338
|
+
const agentConfigWithTools = mergeAgentToolsWithRuntime(
|
|
1339
|
+
{
|
|
1340
|
+
...agentConfigWithReferences,
|
|
1341
|
+
recommendedSkillTools: [
|
|
1342
|
+
...(((agentConfigWithReferences as any).recommendedSkillTools ?? []) as string[]),
|
|
1343
|
+
...contextRecommendedSkillTools,
|
|
1344
|
+
],
|
|
1345
|
+
recommendedSkillHints: [
|
|
1346
|
+
...(((agentConfigWithReferences as any).recommendedSkillHints ?? []) as string[]),
|
|
1347
|
+
...contextRecommendedSkillHints,
|
|
1348
|
+
],
|
|
1349
|
+
skillPromptPatches: [
|
|
1350
|
+
...(((agentConfigWithReferences as any).skillPromptPatches ?? []) as string[]),
|
|
1351
|
+
...contextSkillPromptPatches,
|
|
1352
|
+
],
|
|
1353
|
+
},
|
|
1354
|
+
contextTools,
|
|
1355
|
+
mentionedTools,
|
|
1356
|
+
runtimeOptions,
|
|
1357
|
+
state,
|
|
1358
|
+
);
|
|
1359
|
+
const agentConfigForCall = applyImageConfigRuntimeOverride(
|
|
1360
|
+
agentConfigWithTools,
|
|
1361
|
+
runtimeOptions,
|
|
1362
|
+
);
|
|
1363
|
+
|
|
1364
|
+
// 如果对话设置了 maxTokens,覆盖 agent 的 max_tokens
|
|
1365
|
+
const dialogMaxTokens = currentDialog?.maxTokens;
|
|
1366
|
+
const effectiveAgentConfig = dialogMaxTokens
|
|
1367
|
+
? { ...agentConfigForCall, max_tokens: dialogMaxTokens }
|
|
1368
|
+
: agentConfigForCall;
|
|
1369
|
+
const initialImageGenerationState = resolveImageGenerationStreamingState(
|
|
1370
|
+
effectiveAgentConfig,
|
|
1371
|
+
);
|
|
1372
|
+
const streamingMessageMetadata = {
|
|
1373
|
+
...buildParallelMessageMetadata(
|
|
1374
|
+
agentConfigForCall,
|
|
1375
|
+
runtimeOptions,
|
|
1376
|
+
),
|
|
1377
|
+
...(initialImageGenerationState
|
|
1378
|
+
? { imageGenerationState: initialImageGenerationState }
|
|
1379
|
+
: {}),
|
|
1380
|
+
};
|
|
1381
|
+
|
|
1382
|
+
const isRespModel = isResponseAPIModel(agentConfigForCall);
|
|
1383
|
+
|
|
1384
|
+
// 🔹 Response-style 模型:与 completions 一样走完整 Agent Loop
|
|
1385
|
+
if (isRespModel) {
|
|
1386
|
+
const maxExecutionTime = selectMaxExecutionTime(state);
|
|
1387
|
+
const MAX_TIME_MS = maxExecutionTime > 0 ? maxExecutionTime : 240_000;
|
|
1388
|
+
const startTime = Date.now();
|
|
1389
|
+
|
|
1390
|
+
const staticContexts = await buildStaticContexts(
|
|
1391
|
+
state,
|
|
1392
|
+
dispatch,
|
|
1393
|
+
agentConfigForCall,
|
|
1394
|
+
currentDialog ?? undefined,
|
|
1395
|
+
mergedContentCache,
|
|
1396
|
+
);
|
|
1397
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-static-context-ready", {
|
|
1398
|
+
model: agentConfigForCall.model,
|
|
1399
|
+
responseApi: true,
|
|
1400
|
+
});
|
|
1401
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-post-static-entered", {
|
|
1402
|
+
responseApi: true,
|
|
1403
|
+
});
|
|
1404
|
+
|
|
1405
|
+
let appendTempUserInput = true;
|
|
1406
|
+
let currentParentMessageId = parentMessageId ?? undefined;
|
|
1407
|
+
|
|
1408
|
+
const w = typeof globalThis !== "undefined" && (globalThis as any).window ? (globalThis as any).window : null;
|
|
1409
|
+
if (w) w.__LOOP_STOP_REASON__ = null;
|
|
1410
|
+
|
|
1411
|
+
loopKey = `loop:${dialogId}`;
|
|
1412
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-active-controller-adding", {
|
|
1413
|
+
responseApi: true,
|
|
1414
|
+
});
|
|
1415
|
+
dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey }));
|
|
1416
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-active-controller-added", {
|
|
1417
|
+
responseApi: true,
|
|
1418
|
+
});
|
|
1419
|
+
|
|
1420
|
+
for (;;) {
|
|
1421
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-loop-entered", {
|
|
1422
|
+
responseApi: true,
|
|
1423
|
+
});
|
|
1424
|
+
const requestParentMessageId = currentParentMessageId;
|
|
1425
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
1426
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-loop-aborted-before-context", {
|
|
1427
|
+
loopControllerAborted: loopController.signal.aborted,
|
|
1428
|
+
thunkSignalAborted: thunkApi.signal.aborted,
|
|
1429
|
+
responseApi: true,
|
|
1430
|
+
});
|
|
1431
|
+
if (w) w.__LOOP_STOP_REASON__ = "aborted";
|
|
1432
|
+
break;
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
const loopState = getState() as RootState;
|
|
1436
|
+
const now = Date.now();
|
|
1437
|
+
if (now - startTime > MAX_TIME_MS) {
|
|
1438
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-loop-timeout-before-context", {
|
|
1439
|
+
maxTimeMs: MAX_TIME_MS,
|
|
1440
|
+
elapsedMs: now - startTime,
|
|
1441
|
+
responseApi: true,
|
|
1442
|
+
});
|
|
1443
|
+
if (w) w.__LOOP_STOP_REASON__ = "timeout";
|
|
1444
|
+
break;
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
const accessError = validateAccessAndBalance(
|
|
1448
|
+
agentConfigForCall,
|
|
1449
|
+
loopState,
|
|
1450
|
+
);
|
|
1451
|
+
if (accessError) {
|
|
1452
|
+
const accessErrorReason = classifyQuickChatAccessError(accessError);
|
|
1453
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-access-error-before-context", {
|
|
1454
|
+
hasAccessError: true,
|
|
1455
|
+
reason: accessErrorReason,
|
|
1456
|
+
responseApi: true,
|
|
1457
|
+
});
|
|
1458
|
+
if (quickChatPerfStartedAt && runtimeDialogKey && !modelRequestStarted) {
|
|
1459
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-access-error-finalized", {
|
|
1460
|
+
reason: accessErrorReason,
|
|
1461
|
+
responseApi: true,
|
|
1462
|
+
});
|
|
1463
|
+
await finalizeQuickChatAgentTurnFailure(
|
|
1464
|
+
dispatch,
|
|
1465
|
+
runtimeDialogKey,
|
|
1466
|
+
agentKey,
|
|
1467
|
+
new Error(accessError),
|
|
1468
|
+
);
|
|
1469
|
+
}
|
|
1470
|
+
return rejectWithValue(accessError);
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
const willSkipDynamicContext = canUseQuickChatEmptyDynamicContexts(
|
|
1474
|
+
quickChatPerfStartedAt,
|
|
1475
|
+
userInput,
|
|
1476
|
+
runtimeOptions,
|
|
1477
|
+
currentDialog,
|
|
1478
|
+
);
|
|
1479
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-dynamic-context-decision", {
|
|
1480
|
+
hasRuntimeOptions: !!runtimeOptions,
|
|
1481
|
+
isSimpleTextInput: isSimpleTextInput(userInput),
|
|
1482
|
+
referenceKeyCount: currentDialog?.referenceKeys?.length ?? 0,
|
|
1483
|
+
willSkipDynamicContext,
|
|
1484
|
+
responseApi: true,
|
|
1485
|
+
});
|
|
1486
|
+
|
|
1487
|
+
const dynamicContexts = willSkipDynamicContext
|
|
1488
|
+
? (logQuickChatPerfStage(
|
|
1489
|
+
quickChatPerfStartedAt,
|
|
1490
|
+
"stream-agent-dynamic-context-skipped",
|
|
1491
|
+
{
|
|
1492
|
+
reason: "simple-quick-chat-first-turn",
|
|
1493
|
+
responseApi: true,
|
|
1494
|
+
},
|
|
1495
|
+
), EMPTY_DYNAMIC_CONTEXTS)
|
|
1496
|
+
: await buildDynamicContextsForTurn(
|
|
1497
|
+
loopState,
|
|
1498
|
+
dispatch,
|
|
1499
|
+
agentConfigForCall,
|
|
1500
|
+
userInput,
|
|
1501
|
+
runtimeOptions,
|
|
1502
|
+
mergedContentCache,
|
|
1503
|
+
dialogKey,
|
|
1504
|
+
quickChatPerfStartedAt,
|
|
1505
|
+
);
|
|
1506
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-dynamic-context-ready", {
|
|
1507
|
+
responseApi: true,
|
|
1508
|
+
});
|
|
1509
|
+
const contexts = mergeContexts(staticContexts, dynamicContexts);
|
|
1510
|
+
|
|
1511
|
+
const rawMessages = filterMessagesForParallelBranch(
|
|
1512
|
+
selectAllMsgs(loopState, dialogId),
|
|
1513
|
+
runtimeOptions,
|
|
1514
|
+
);
|
|
1515
|
+
let visibleMessages = buildAgentViewMessages(
|
|
1516
|
+
rawMessages as any,
|
|
1517
|
+
agentConfigForCall.dbKey,
|
|
1518
|
+
);
|
|
1519
|
+
|
|
1520
|
+
if (appendTempUserInput && hasAgentRunUserInputContent(agentRunUserInput)) {
|
|
1521
|
+
visibleMessages = [
|
|
1522
|
+
...visibleMessages,
|
|
1523
|
+
{
|
|
1524
|
+
id: `__tmp_user_${Date.now()}`,
|
|
1525
|
+
dbKey: "",
|
|
1526
|
+
role: "user",
|
|
1527
|
+
content: agentRunUserInput,
|
|
1528
|
+
thinkContent: "",
|
|
1529
|
+
cybotKey: agentConfigForCall.dbKey,
|
|
1530
|
+
isStreaming: false,
|
|
1531
|
+
} as any,
|
|
1532
|
+
];
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
const cleanedMessages = filterAndCleanMessages(visibleMessages);
|
|
1536
|
+
const ctxWindow =
|
|
1537
|
+
getModelContextWindow(agentConfigForCall.model) || 128000;
|
|
1538
|
+
const retention = selectContextRetention(loopState);
|
|
1539
|
+
const summaryTokenCount = contexts.dialogSummary
|
|
1540
|
+
? estimateTokenCount(contexts.dialogSummary)
|
|
1541
|
+
: 0;
|
|
1542
|
+
const processedMessages = trimMessagesWithSummary(
|
|
1543
|
+
compressOldToolResults(cleanedMessages),
|
|
1544
|
+
ctxWindow,
|
|
1545
|
+
summaryTokenCount,
|
|
1546
|
+
retention,
|
|
1547
|
+
);
|
|
1548
|
+
|
|
1549
|
+
let firstDynamicIdx = processedMessages.findIndex(
|
|
1550
|
+
(m) => m.id && !initialHistoryIds.has(m.id),
|
|
1551
|
+
);
|
|
1552
|
+
if (firstDynamicIdx === -1) firstDynamicIdx = processedMessages.length;
|
|
1553
|
+
|
|
1554
|
+
const stableMessages = processedMessages.slice(0, firstDynamicIdx);
|
|
1555
|
+
const dynamicMessages = processedMessages.slice(firstDynamicIdx);
|
|
1556
|
+
|
|
1557
|
+
if (appendTempUserInput) {
|
|
1558
|
+
const agentHasVision = resolveAgentImageInputSupport(
|
|
1559
|
+
agentConfigForCall as any,
|
|
1560
|
+
);
|
|
1561
|
+
|
|
1562
|
+
if (!agentHasVision && hasImageInMessages(processedMessages)) {
|
|
1563
|
+
return rejectWithValue(
|
|
1564
|
+
"当前 Agent 不支持图片输入,请改用文本或文档。",
|
|
1565
|
+
);
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
const bodyData = generateRequestBody({
|
|
1570
|
+
agentConfig: effectiveAgentConfig,
|
|
1571
|
+
messages: dynamicMessages,
|
|
1572
|
+
stableMessages,
|
|
1573
|
+
userInput: userInputText,
|
|
1574
|
+
contexts,
|
|
1575
|
+
});
|
|
1576
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-model-request-starting", {
|
|
1577
|
+
responseApi: true,
|
|
1578
|
+
dynamicMessageCount: dynamicMessages.length,
|
|
1579
|
+
stableMessageCount: stableMessages.length,
|
|
1580
|
+
});
|
|
1581
|
+
modelRequestStarted = true;
|
|
1582
|
+
|
|
1583
|
+
const meta: CompletionMeta = await sendOpenAIResponseRequest({
|
|
1584
|
+
bodyData,
|
|
1585
|
+
agentConfig: agentConfigForCall,
|
|
1586
|
+
thunkApi,
|
|
1587
|
+
dialogKey,
|
|
1588
|
+
parentMessageId: currentParentMessageId,
|
|
1589
|
+
messageMetadata: streamingMessageMetadata,
|
|
1590
|
+
quickChatPerfStartedAt,
|
|
1591
|
+
});
|
|
1592
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-model-request-finished", {
|
|
1593
|
+
responseApi: true,
|
|
1594
|
+
hasToolCalls: meta.hasToolCalls,
|
|
1595
|
+
hasHandedOff: meta.hasHandedOff,
|
|
1596
|
+
hasPendingInteraction: meta.hasPendingInteraction,
|
|
1597
|
+
});
|
|
1598
|
+
|
|
1599
|
+
appendTempUserInput = false;
|
|
1600
|
+
currentParentMessageId = undefined;
|
|
1601
|
+
totalTurnUsage = updateTotalUsage(totalTurnUsage, meta.usage);
|
|
1602
|
+
|
|
1603
|
+
if (meta.hasHandedOff) {
|
|
1604
|
+
if (!requestParentMessageId && meta.messageId) {
|
|
1605
|
+
dispatch(removeTransientMessage(meta.messageId));
|
|
1606
|
+
}
|
|
1607
|
+
if (w) w.__LOOP_STOP_REASON__ = "handoff";
|
|
1608
|
+
break;
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
if (meta.hasPendingInteraction) {
|
|
1612
|
+
if (w) w.__LOOP_STOP_REASON__ = "pending";
|
|
1613
|
+
break;
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
const afterTurnState = getState() as RootState;
|
|
1617
|
+
const queuedMessages = selectPendingUserInputQueue(afterTurnState, dialogKey);
|
|
1618
|
+
if (queuedMessages.length > 0) {
|
|
1619
|
+
const queuedText = queuedMessages[0];
|
|
1620
|
+
|
|
1621
|
+
const currentDialogConfig =
|
|
1622
|
+
selectDialogConfigByKey(afterTurnState, dialogKey) ??
|
|
1623
|
+
selectCurrentDialogConfig(afterTurnState);
|
|
1624
|
+
if (!currentDialogConfig) {
|
|
1625
|
+
dispatch(clearPendingUserInputQueue({ dialogKey }));
|
|
1626
|
+
break;
|
|
1627
|
+
}
|
|
1628
|
+
await dispatch(
|
|
1629
|
+
prepareAndPersistUserMessage({
|
|
1630
|
+
userInput: queuedText,
|
|
1631
|
+
dialogConfig: currentDialogConfig,
|
|
1632
|
+
})
|
|
1633
|
+
).unwrap();
|
|
1634
|
+
dispatch(dequeueUserInput({ dialogKey }));
|
|
1635
|
+
continue;
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
if (!meta.hasToolCalls) {
|
|
1639
|
+
if (w) w.__LOOP_STOP_REASON__ = "done";
|
|
1640
|
+
break;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
return {
|
|
1645
|
+
usage: totalTurnUsage ?? undefined,
|
|
1646
|
+
};
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
// 🔹 Completions-style 模型:Agent Loop
|
|
1650
|
+
const maxExecutionTime = selectMaxExecutionTime(state);
|
|
1651
|
+
|
|
1652
|
+
const MAX_TIME_MS = maxExecutionTime > 0 ? maxExecutionTime : 240_000;
|
|
1653
|
+
const startTime = Date.now();
|
|
1654
|
+
|
|
1655
|
+
// 🚀 优化:在 Loop 外构建静态上下文(只执行一次)
|
|
1656
|
+
// 静态上下文包含:botInstructions、botKnowledge、spaceContext、userGlobalPrompt
|
|
1657
|
+
// 这些内容在 Loop 期间是稳定的,不需要每轮重新构建
|
|
1658
|
+
const staticContexts = await buildStaticContexts(
|
|
1659
|
+
state,
|
|
1660
|
+
dispatch,
|
|
1661
|
+
agentConfigForCall,
|
|
1662
|
+
currentDialog ?? undefined,
|
|
1663
|
+
mergedContentCache,
|
|
1664
|
+
);
|
|
1665
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-static-context-ready", {
|
|
1666
|
+
model: agentConfigForCall.model,
|
|
1667
|
+
responseApi: false,
|
|
1668
|
+
});
|
|
1669
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-post-static-entered", {
|
|
1670
|
+
responseApi: false,
|
|
1671
|
+
});
|
|
1672
|
+
|
|
1673
|
+
let appendTempUserInput = true;
|
|
1674
|
+
let currentParentMessageId = parentMessageId ?? undefined;
|
|
1675
|
+
|
|
1676
|
+
const w = typeof globalThis !== "undefined" && (globalThis as any).window ? (globalThis as any).window : null;
|
|
1677
|
+
if (w) w.__LOOP_STOP_REASON__ = null;
|
|
1678
|
+
|
|
1679
|
+
if (!isRespModel) {
|
|
1680
|
+
loopKey = `loop:${dialogId}`;
|
|
1681
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-active-controller-adding", {
|
|
1682
|
+
responseApi: false,
|
|
1683
|
+
});
|
|
1684
|
+
dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey }));
|
|
1685
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-active-controller-added", {
|
|
1686
|
+
responseApi: false,
|
|
1687
|
+
});
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
for (;;) {
|
|
1691
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-loop-entered", {
|
|
1692
|
+
responseApi: false,
|
|
1693
|
+
});
|
|
1694
|
+
const requestParentMessageId = currentParentMessageId;
|
|
1695
|
+
// 每轮开始前检查是否已中止
|
|
1696
|
+
if (loopController.signal.aborted || thunkApi.signal.aborted) {
|
|
1697
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-loop-aborted-before-context", {
|
|
1698
|
+
loopControllerAborted: loopController.signal.aborted,
|
|
1699
|
+
thunkSignalAborted: thunkApi.signal.aborted,
|
|
1700
|
+
responseApi: false,
|
|
1701
|
+
});
|
|
1702
|
+
if (w) w.__LOOP_STOP_REASON__ = "aborted";
|
|
1703
|
+
break;
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
const loopState = getState() as RootState;
|
|
1707
|
+
const now = Date.now();
|
|
1708
|
+
if (now - startTime > MAX_TIME_MS) {
|
|
1709
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-loop-timeout-before-context", {
|
|
1710
|
+
maxTimeMs: MAX_TIME_MS,
|
|
1711
|
+
elapsedMs: now - startTime,
|
|
1712
|
+
responseApi: false,
|
|
1713
|
+
});
|
|
1714
|
+
if (w) w.__LOOP_STOP_REASON__ = "timeout";
|
|
1715
|
+
break;
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
// 每轮检查权限 & 余额
|
|
1719
|
+
const accessError = validateAccessAndBalance(
|
|
1720
|
+
agentConfigForCall,
|
|
1721
|
+
loopState,
|
|
1722
|
+
);
|
|
1723
|
+
if (accessError) {
|
|
1724
|
+
const accessErrorReason = classifyQuickChatAccessError(accessError);
|
|
1725
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-access-error-before-context", {
|
|
1726
|
+
hasAccessError: true,
|
|
1727
|
+
reason: accessErrorReason,
|
|
1728
|
+
responseApi: false,
|
|
1729
|
+
});
|
|
1730
|
+
if (quickChatPerfStartedAt && runtimeDialogKey && !modelRequestStarted) {
|
|
1731
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-access-error-finalized", {
|
|
1732
|
+
reason: accessErrorReason,
|
|
1733
|
+
responseApi: false,
|
|
1734
|
+
});
|
|
1735
|
+
await finalizeQuickChatAgentTurnFailure(
|
|
1736
|
+
dispatch,
|
|
1737
|
+
runtimeDialogKey,
|
|
1738
|
+
agentKey,
|
|
1739
|
+
new Error(accessError),
|
|
1740
|
+
);
|
|
1741
|
+
}
|
|
1742
|
+
return rejectWithValue(accessError);
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
const willSkipDynamicContext = canUseQuickChatEmptyDynamicContexts(
|
|
1746
|
+
quickChatPerfStartedAt,
|
|
1747
|
+
userInput,
|
|
1748
|
+
runtimeOptions,
|
|
1749
|
+
currentDialog,
|
|
1750
|
+
);
|
|
1751
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-dynamic-context-decision", {
|
|
1752
|
+
hasRuntimeOptions: !!runtimeOptions,
|
|
1753
|
+
isSimpleTextInput: isSimpleTextInput(userInput),
|
|
1754
|
+
referenceKeyCount: currentDialog?.referenceKeys?.length ?? 0,
|
|
1755
|
+
willSkipDynamicContext,
|
|
1756
|
+
responseApi: false,
|
|
1757
|
+
});
|
|
1758
|
+
|
|
1759
|
+
// 🚀 优化:每轮只构建动态上下文(currentInput、history、editingContext、dialogSummary)
|
|
1760
|
+
const dynamicContexts = willSkipDynamicContext
|
|
1761
|
+
? (logQuickChatPerfStage(
|
|
1762
|
+
quickChatPerfStartedAt,
|
|
1763
|
+
"stream-agent-dynamic-context-skipped",
|
|
1764
|
+
{
|
|
1765
|
+
reason: "simple-quick-chat-first-turn",
|
|
1766
|
+
responseApi: false,
|
|
1767
|
+
},
|
|
1768
|
+
), EMPTY_DYNAMIC_CONTEXTS)
|
|
1769
|
+
: await buildDynamicContextsForTurn(
|
|
1770
|
+
loopState,
|
|
1771
|
+
dispatch,
|
|
1772
|
+
agentConfigForCall,
|
|
1773
|
+
userInput,
|
|
1774
|
+
runtimeOptions,
|
|
1775
|
+
mergedContentCache,
|
|
1776
|
+
dialogKey,
|
|
1777
|
+
quickChatPerfStartedAt,
|
|
1778
|
+
);
|
|
1779
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-dynamic-context-ready", {
|
|
1780
|
+
responseApi: false,
|
|
1781
|
+
});
|
|
1782
|
+
|
|
1783
|
+
// 合并静态和动态上下文
|
|
1784
|
+
const contexts = mergeContexts(staticContexts, dynamicContexts);
|
|
1785
|
+
|
|
1786
|
+
const rawMessages = filterMessagesForParallelBranch(
|
|
1787
|
+
selectAllMsgs(loopState, dialogId),
|
|
1788
|
+
runtimeOptions,
|
|
1789
|
+
);
|
|
1790
|
+
let visibleMessages = buildAgentViewMessages(
|
|
1791
|
+
rawMessages as any,
|
|
1792
|
+
agentConfigForCall.dbKey,
|
|
1793
|
+
);
|
|
1794
|
+
|
|
1795
|
+
if (appendTempUserInput && hasAgentRunUserInputContent(agentRunUserInput)) {
|
|
1796
|
+
visibleMessages = [
|
|
1797
|
+
...visibleMessages,
|
|
1798
|
+
{
|
|
1799
|
+
id: `__tmp_user_${Date.now()}`,
|
|
1800
|
+
dbKey: "",
|
|
1801
|
+
role: "user",
|
|
1802
|
+
content: agentRunUserInput,
|
|
1803
|
+
thinkContent: "",
|
|
1804
|
+
cybotKey: agentConfigForCall.dbKey,
|
|
1805
|
+
isStreaming: false,
|
|
1806
|
+
} as any,
|
|
1807
|
+
];
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
const cleanedMessages = filterAndCleanMessages(visibleMessages);
|
|
1811
|
+
const ctxWindow =
|
|
1812
|
+
getModelContextWindow(agentConfigForCall.model) || 128000;
|
|
1813
|
+
const retention = selectContextRetention(loopState);
|
|
1814
|
+
const summaryTokenCount = contexts.dialogSummary
|
|
1815
|
+
? estimateTokenCount(contexts.dialogSummary)
|
|
1816
|
+
: 0;
|
|
1817
|
+
const processedMessages = trimMessagesWithSummary(
|
|
1818
|
+
compressOldToolResults(cleanedMessages),
|
|
1819
|
+
ctxWindow,
|
|
1820
|
+
summaryTokenCount,
|
|
1821
|
+
retention,
|
|
1822
|
+
);
|
|
1823
|
+
|
|
1824
|
+
// --- [优化 P1] 使用 findIndex + slice 确保顺序和无 ID 稳定消息的保留 ---
|
|
1825
|
+
let firstDynamicIdx = processedMessages.findIndex(
|
|
1826
|
+
(m) => m.id && !initialHistoryIds.has(m.id),
|
|
1827
|
+
);
|
|
1828
|
+
if (firstDynamicIdx === -1) firstDynamicIdx = processedMessages.length;
|
|
1829
|
+
|
|
1830
|
+
const stableMessages = processedMessages.slice(0, firstDynamicIdx);
|
|
1831
|
+
const dynamicMessages = processedMessages.slice(firstDynamicIdx);
|
|
1832
|
+
|
|
1833
|
+
if (appendTempUserInput) {
|
|
1834
|
+
const agentHasVision = resolveAgentImageInputSupport(
|
|
1835
|
+
agentConfigForCall as any,
|
|
1836
|
+
);
|
|
1837
|
+
|
|
1838
|
+
if (!agentHasVision && hasImageInMessages(processedMessages)) {
|
|
1839
|
+
return rejectWithValue(
|
|
1840
|
+
"当前 Agent 不支持图片输入,请改用文本或文档。",
|
|
1841
|
+
);
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
const bodyData = generateRequestBody({
|
|
1846
|
+
agentConfig: effectiveAgentConfig,
|
|
1847
|
+
messages: dynamicMessages,
|
|
1848
|
+
stableMessages,
|
|
1849
|
+
userInput: userInputText,
|
|
1850
|
+
contexts,
|
|
1851
|
+
});
|
|
1852
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-model-request-starting", {
|
|
1853
|
+
responseApi: false,
|
|
1854
|
+
dynamicMessageCount: dynamicMessages.length,
|
|
1855
|
+
stableMessageCount: stableMessages.length,
|
|
1856
|
+
});
|
|
1857
|
+
modelRequestStarted = true;
|
|
1858
|
+
|
|
1859
|
+
const disableToolsForThisRequest =
|
|
1860
|
+
shouldDisableQuickChatToolsForDirectAnswer(
|
|
1861
|
+
quickChatPerfStartedAt,
|
|
1862
|
+
userInput,
|
|
1863
|
+
runtimeOptions,
|
|
1864
|
+
currentDialog,
|
|
1865
|
+
);
|
|
1866
|
+
if (disableToolsForThisRequest) {
|
|
1867
|
+
logQuickChatPerfStage(
|
|
1868
|
+
quickChatPerfStartedAt,
|
|
1869
|
+
"stream-agent-tools-disabled-for-direct-answer",
|
|
1870
|
+
{
|
|
1871
|
+
responseApi: false,
|
|
1872
|
+
toolCount: Array.isArray(agentConfigForCall.tools)
|
|
1873
|
+
? agentConfigForCall.tools.length
|
|
1874
|
+
: 0,
|
|
1875
|
+
},
|
|
1876
|
+
);
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
const meta: CompletionMeta = await sendOpenAICompletionsRequest({
|
|
1880
|
+
bodyData,
|
|
1881
|
+
agentConfig: agentConfigForCall,
|
|
1882
|
+
thunkApi,
|
|
1883
|
+
dialogKey,
|
|
1884
|
+
parentMessageId: currentParentMessageId,
|
|
1885
|
+
messageMetadata: streamingMessageMetadata,
|
|
1886
|
+
disableToolsForThisRequest,
|
|
1887
|
+
quickChatPerfStartedAt,
|
|
1888
|
+
});
|
|
1889
|
+
logQuickChatPerfStage(quickChatPerfStartedAt, "stream-agent-model-request-finished", {
|
|
1890
|
+
responseApi: false,
|
|
1891
|
+
hasToolCalls: meta.hasToolCalls,
|
|
1892
|
+
hasHandedOff: meta.hasHandedOff,
|
|
1893
|
+
hasPendingInteraction: meta.hasPendingInteraction,
|
|
1894
|
+
});
|
|
1895
|
+
|
|
1896
|
+
appendTempUserInput = false;
|
|
1897
|
+
currentParentMessageId = undefined;
|
|
1898
|
+
totalTurnUsage = updateTotalUsage(totalTurnUsage, meta.usage);
|
|
1899
|
+
|
|
1900
|
+
// handoff(例如 runStreamingAgent):当前 Agent 停止,后续由子 Agent 自动续跑
|
|
1901
|
+
if (meta.hasHandedOff) {
|
|
1902
|
+
if (!requestParentMessageId && meta.messageId) {
|
|
1903
|
+
dispatch(removeTransientMessage(meta.messageId));
|
|
1904
|
+
}
|
|
1905
|
+
if (w) w.__LOOP_STOP_REASON__ = "handoff";
|
|
1906
|
+
break;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
if (meta.hasPendingInteraction) {
|
|
1910
|
+
if (w) w.__LOOP_STOP_REASON__ = "pending";
|
|
1911
|
+
break;
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
// 检查是否有用户在 loop 期间发送的排队消息
|
|
1915
|
+
const afterTurnState = getState() as RootState;
|
|
1916
|
+
const queuedMessages = selectPendingUserInputQueue(afterTurnState, dialogKey);
|
|
1917
|
+
if (queuedMessages.length > 0) {
|
|
1918
|
+
const queuedText = queuedMessages[0];
|
|
1919
|
+
|
|
1920
|
+
const currentDialogConfig =
|
|
1921
|
+
selectDialogConfigByKey(afterTurnState, dialogKey) ??
|
|
1922
|
+
selectCurrentDialogConfig(afterTurnState);
|
|
1923
|
+
if (!currentDialogConfig) {
|
|
1924
|
+
// 对话已切换/销毁,无法持久化;清空队列并终止 loop,避免死循环重试
|
|
1925
|
+
dispatch(clearPendingUserInputQueue({ dialogKey }));
|
|
1926
|
+
break;
|
|
1927
|
+
}
|
|
1928
|
+
await dispatch(
|
|
1929
|
+
prepareAndPersistUserMessage({
|
|
1930
|
+
userInput: queuedText,
|
|
1931
|
+
dialogConfig: currentDialogConfig,
|
|
1932
|
+
})
|
|
1933
|
+
).unwrap();
|
|
1934
|
+
// 持久化成功后再出队,避免 persist 失败时丢消息
|
|
1935
|
+
dispatch(dequeueUserInput({ dialogKey }));
|
|
1936
|
+
// 用户消息已持久化到 DB,下一轮 selectAllMsgs 会自动包含它
|
|
1937
|
+
// 不设置 appendTempUserInput,直接继续下一轮
|
|
1938
|
+
continue;
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
if (!meta.hasToolCalls) {
|
|
1942
|
+
if (w) w.__LOOP_STOP_REASON__ = "done";
|
|
1943
|
+
break;
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
// 否则:存在 tool_calls 且没有 handoff / pending,基于新的 history 继续下一轮
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
return {
|
|
1950
|
+
usage: totalTurnUsage ?? undefined,
|
|
1951
|
+
};
|
|
1952
|
+
} catch (error: any) {
|
|
1953
|
+
if (isAbortError(error)) {
|
|
1954
|
+
if (remoteTransientMessageId && !remoteTransientMessageFinalized) {
|
|
1955
|
+
dispatch(removeTransientMessage(remoteTransientMessageId));
|
|
1956
|
+
remoteTransientMessageFinalized = true;
|
|
1957
|
+
}
|
|
1958
|
+
const w =
|
|
1959
|
+
typeof globalThis !== "undefined" && (globalThis as any).window
|
|
1960
|
+
? (globalThis as any).window
|
|
1961
|
+
: null;
|
|
1962
|
+
if (w) w.__LOOP_STOP_REASON__ = "aborted";
|
|
1963
|
+
return;
|
|
1964
|
+
}
|
|
1965
|
+
console.error(
|
|
1966
|
+
`Error in streamAgentChatTurn for [${agentKey}]:`,
|
|
1967
|
+
error,
|
|
1968
|
+
);
|
|
1969
|
+
if (remoteTransientMessageId && !remoteTransientMessageFinalized) {
|
|
1970
|
+
dispatch(removeTransientMessage(remoteTransientMessageId));
|
|
1971
|
+
remoteTransientMessageFinalized = true;
|
|
1972
|
+
}
|
|
1973
|
+
if (
|
|
1974
|
+
quickChatPerfStartedAt &&
|
|
1975
|
+
runtimeDialogKey &&
|
|
1976
|
+
!modelRequestStarted &&
|
|
1977
|
+
!remoteTransientMessageId
|
|
1978
|
+
) {
|
|
1979
|
+
await finalizeQuickChatAgentTurnFailure(
|
|
1980
|
+
dispatch,
|
|
1981
|
+
runtimeDialogKey,
|
|
1982
|
+
agentKey,
|
|
1983
|
+
error,
|
|
1984
|
+
);
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
return rejectWithValue(
|
|
1988
|
+
error?.message ||
|
|
1989
|
+
"An unexpected error occurred in streamAgentChatTurn.",
|
|
1990
|
+
);
|
|
1991
|
+
} finally {
|
|
1992
|
+
if (loopKey && runtimeDialogKey) {
|
|
1993
|
+
dispatch(removeActiveController({ messageId: loopKey, dialogKey: runtimeDialogKey }));
|
|
1994
|
+
} else if (loopKey) {
|
|
1995
|
+
dispatch(removeActiveController(loopKey));
|
|
1996
|
+
}
|
|
1997
|
+
// 清空排队的用户消息(loop 结束或异常时,未消费的消息不应继续保留)
|
|
1998
|
+
dispatch(clearPendingUserInputQueue(runtimeDialogKey ? { dialogKey: runtimeDialogKey } : undefined));
|
|
1999
|
+
thunkApi.signal.removeEventListener("abort", onAbort);
|
|
2000
|
+
}
|
|
2001
|
+
};
|