nolo-cli 0.1.31 → 0.1.32
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 +6 -0
- package/agentAliases.ts +72 -0
- package/agentCommandSupport.ts +4 -1
- package/agentInternalCommandEntries.ts +2 -0
- package/agentMachineCommands.ts +238 -16
- package/agentPullCommand.ts +46 -18
- package/agentRecordHelpers.ts +96 -5
- package/agentRunCommand.ts +72 -24
- package/agentRunParsing.ts +6 -0
- package/ai/agent/agentSlice.ts +1 -589
- package/ai/index.ts +1 -1
- package/buildPublish.ts +4 -1
- package/buildPublishArtifactAssembly.ts +479 -162
- package/cli/agentAliases.ts +132 -0
- package/cli/agentCommandSupport.ts +80 -0
- package/cli/agentCreateCustomCommands.ts +278 -0
- package/cli/agentDialogsCommands.ts +227 -0
- package/cli/agentDoctorCommands.ts +203 -0
- package/cli/agentInternalCommandEntries.ts +45 -0
- package/cli/agentListCommands.ts +132 -0
- package/cli/agentListHelpers.ts +187 -0
- package/cli/agentMachineCommands.ts +698 -0
- package/cli/agentPullCommand.ts +167 -0
- package/cli/agentRecordCommands.ts +143 -0
- package/cli/agentRecordHelpers.ts +562 -0
- package/cli/agentRunCommand.ts +190 -0
- package/cli/agentRunLocalWorkspace.ts +182 -0
- package/cli/agentRunParsing.ts +298 -0
- package/cli/agentRuntimeLocal.ts +55 -0
- package/cli/agentSuperviseCommands.ts +8 -0
- package/cli/agentUnpublishCommands.ts +113 -0
- package/cli/authCommands.ts +264 -0
- package/cli/buildPublish.ts +138 -0
- package/cli/buildPublishArtifactAssembly.ts +724 -0
- package/cli/buildPublishImportAnalysis.ts +242 -0
- package/cli/cliCommandAdapters.ts +28 -0
- package/cli/cliCommandDispatch.ts +66 -0
- package/cli/cliCommandFactories.ts +66 -0
- package/cli/cliCommandTypes.ts +49 -0
- package/cli/cliEnvHelpers.ts +185 -0
- package/cli/cliIoTypes.ts +3 -0
- package/cli/cliRuntimeDoctorReport.ts +193 -0
- package/cli/client/agentConfigResolver.ts +1 -0
- package/cli/client/agentRun.ts +188 -0
- package/cli/client/agentRunInput.ts +10 -0
- package/cli/client/agentRunLocalExecution.ts +124 -0
- package/cli/client/agentRunLocalExecutor.ts +179 -0
- package/cli/client/agentRunRuntimeSelection.ts +145 -0
- package/cli/client/agentRunServerTransport.ts +397 -0
- package/cli/client/agentRunTaskRunRecorder.ts +176 -0
- package/cli/client/compactDialog.ts +222 -0
- package/cli/client/hybridRecordStore.ts +52 -0
- package/cli/client/localAgentRecords.ts +7 -0
- package/cli/client/localDialogRecords.ts +30 -0
- package/cli/client/localProviderResolver.ts +1 -0
- package/cli/client/localRuntimeAdapter.ts +676 -0
- package/cli/client/localToolPolicy.ts +8 -0
- package/cli/client/profileConfig.ts +101 -0
- package/cli/client/streamingOutput.ts +36 -0
- package/cli/client/taskRunPrompt.ts +10 -0
- package/cli/client/taskWorktree.ts +8 -0
- package/cli/client/workspaceSession.ts +11 -0
- package/cli/commandRegistry.ts +96 -0
- package/cli/connectorRunArtifact.ts +145 -0
- package/cli/connectorWebSocketTarget.ts +109 -0
- package/cli/customCodingAgentFlow.ts +208 -0
- package/cli/customCodingAgentRecord.ts +179 -0
- package/cli/defaultServer.ts +1 -0
- package/cli/dialogDataAccess.ts +186 -0
- package/cli/dialogInternalCommandEntries.ts +11 -0
- package/cli/dialogReadCommands.ts +180 -0
- package/cli/dialogReadHelpers.ts +226 -0
- package/cli/dialogStatusCommands.ts +123 -0
- package/cli/docInternalCommandEntries.ts +20 -0
- package/cli/hybridReadHelpers.ts +109 -0
- package/cli/internalCommandEntries.ts +20 -0
- package/cli/localRuntimeDb.ts +65 -0
- package/cli/machineCommandPrompts.ts +79 -0
- package/cli/machineCommandResolution.ts +43 -0
- package/cli/machineCommands.ts +324 -0
- package/cli/machineDaemonCommands.ts +29 -0
- package/cli/machineHeartbeatCommands.ts +29 -0
- package/cli/machineStatusCommands.ts +87 -0
- package/cli/machineWatchCommands.ts +41 -0
- package/cli/machineWsPromptMaterialization.ts +89 -0
- package/cli/machineWsRunDispatch.ts +635 -0
- package/cli/machineWsSession.ts +213 -0
- package/cli/noloReadBridgePrompt.ts +16 -0
- package/cli/pageCreateCommands.ts +219 -0
- package/cli/pageDeleteCommands.ts +167 -0
- package/cli/pageReadCommands.ts +151 -0
- package/cli/pageUpdateCommands.ts +249 -0
- package/cli/pageWriteHelpers.ts +209 -0
- package/cli/publishPackage.ts +36 -0
- package/cli/runtimeDoctorCommands.ts +67 -0
- package/cli/runtimeInternalCommandEntries.ts +15 -0
- package/cli/runtimeModeArgs.ts +33 -0
- package/cli/runtimePassthroughCommands.ts +22 -0
- package/cli/scriptCommandEntries.ts +31 -0
- package/cli/scriptPassthroughHelpers.ts +28 -0
- package/cli/secretScanHelpers.ts +31 -0
- package/cli/spaceAttachCommands.ts +134 -0
- package/cli/spaceCategoryCommands.ts +263 -0
- package/cli/spaceCommands.ts +295 -0
- package/cli/spaceDeleteCommands.ts +312 -0
- package/cli/spaceInternalCommandEntries.ts +21 -0
- package/cli/spaceMutationHelpers.ts +135 -0
- package/cli/spaceReadCommands.ts +323 -0
- package/cli/systemInternalCommandEntries.ts +65 -0
- package/cli/tableCommands.ts +118 -0
- package/cli/tableDataOutput.ts +41 -0
- package/cli/tableDataSafety.ts +26 -0
- package/cli/tableMetaCommands.ts +307 -0
- package/cli/tableMutationCommands.ts +266 -0
- package/cli/tableQueryParsing.ts +90 -0
- package/cli/tableQueryRequest.ts +53 -0
- package/cli/taskRunActions.ts +122 -0
- package/cli/taskRunCommand.ts +70 -0
- package/cli/taskRunParsing.ts +86 -0
- package/cli/taskRunPromptShared.ts +55 -0
- package/cli/tui/readlineWorkspace.ts +141 -0
- package/cli/tui/session.ts +50 -0
- package/cli/tui/tuiCatalog.ts +22 -0
- package/cli/tui/tuiCommandInterpreter.ts +253 -0
- package/cli/tui/tuiPresentation.ts +146 -0
- package/cli/updateCommands.ts +134 -0
- package/cli/workflowInternalCommandEntries.ts +31 -0
- package/client/agentRun.test.ts +37 -2
- package/client/agentRunRuntimeSelection.test.ts +1 -0
- package/client/agentRunRuntimeSelection.ts +2 -12
- package/client/agentRunServerTransport.ts +7 -4
- package/commandRegistry.ts +1 -0
- package/connectorWebSocketTarget.ts +61 -6
- package/machineCommands.ts +9 -3
- package/machineWsRunDispatch.ts +1 -1
- package/machineWsSession.ts +28 -7
- package/package.json +170 -103
- package/spaceAttachCommands.ts +2 -3
- package/agent-runtime/hostRuntimeCapabilities.ts +0 -7
- package/agent-runtime/shellCommandPolicy.ts +0 -117
- package/agent-runtime/toolGate.ts +0 -38
- package/ai/agent/_executeModel.ts +0 -144
- package/ai/agent/appWorkingMemory.ts +0 -126
- package/ai/agent/avatarUtils.ts +0 -24
- package/ai/agent/buildEditingContext.ts +0 -378
- package/ai/agent/buildSystemPrompt.ts +0 -580
- package/ai/agent/canvasEditingContext.ts +0 -49
- package/ai/agent/cleanAgentMessages.ts +0 -140
- package/ai/agent/cliChatClient.ts +0 -153
- package/ai/agent/contextCompiler.ts +0 -107
- package/ai/agent/contextLayerContract.ts +0 -44
- package/ai/agent/createAgentSchema.ts +0 -258
- package/ai/agent/executeToolCall.ts +0 -59
- package/ai/agent/fetchAgentContexts.ts +0 -42
- package/ai/agent/generatePrompt.ts +0 -3
- package/ai/agent/getFullChatContextKeys.ts +0 -168
- package/ai/agent/guidedCreation/assistant.ts +0 -82
- package/ai/agent/guidedCreation/capabilities.ts +0 -84
- package/ai/agent/guidedCreation/draft.ts +0 -62
- package/ai/agent/guidedCreation/types.ts +0 -38
- package/ai/agent/hooks/fetchPublicAgents.ts +0 -108
- package/ai/agent/hooks/useAgentConfig.ts +0 -89
- package/ai/agent/hooks/useAgentDialog.ts +0 -35
- package/ai/agent/hooks/useAgentFormValidation.ts +0 -202
- package/ai/agent/hooks/usePublicAgents.ts +0 -377
- package/ai/agent/pageBuilderHandoffRules.ts +0 -75
- package/ai/agent/persistMessageWithFixedId.ts +0 -37
- package/ai/agent/planSlice.ts +0 -259
- package/ai/agent/publicAgentCatalog.ts +0 -359
- package/ai/agent/publicAgentIdentity.ts +0 -76
- package/ai/agent/referenceUtils.ts +0 -229
- package/ai/agent/runAgentBackground.ts +0 -238
- package/ai/agent/runAgentClientLoop.ts +0 -141
- package/ai/agent/runtimeGuidance.ts +0 -116
- package/ai/agent/server/fetchPublicAgents.ts +0 -158
- package/ai/agent/serverOrigin.ts +0 -7
- package/ai/agent/startParallelAgentStreams.ts +0 -424
- package/ai/agent/startupProtocol.ts +0 -53
- package/ai/agent/streamAgentChatTurn.ts +0 -1876
- package/ai/agent/streamAgentChatTurnUtils.ts +0 -1068
- package/ai/agent/types.ts +0 -73
- package/ai/agent/utils/imageOutput.ts +0 -39
- package/ai/agent/utils/publicImageAgentMode.ts +0 -26
- package/ai/agent/utils/sortUtils.ts +0 -250
- package/ai/agent/web/agentDisplayUtils.ts +0 -171
- package/ai/agent/web/referencePickerUtils.ts +0 -146
- package/ai/agent/web/useAgentModelAvatarComponent.ts +0 -32
- package/ai/agent/web/useGuidedAgentCreation.ts +0 -238
- package/ai/ai.locale.ts +0 -1103
- package/ai/chat/accumulateToolCallChunks.ts +0 -126
- package/ai/chat/fetchUtils.native.ts +0 -278
- package/ai/chat/fetchUtils.ts +0 -155
- package/ai/chat/inlineImageUrlsForCustomProvider.ts +0 -117
- package/ai/chat/parseApiError.ts +0 -67
- package/ai/chat/parseMultilineSSE.ts +0 -95
- package/ai/chat/sendOpenAICompletionsRequest.native.ts +0 -710
- package/ai/chat/sendOpenAICompletionsRequest.ts +0 -897
- package/ai/chat/sendOpenAIResponseRequest.ts +0 -654
- package/ai/chat/shouldUseServerProxy.ts +0 -18
- package/ai/chat/sseClient.native.ts +0 -91
- package/ai/chat/sseClient.ts +0 -67
- package/ai/chat/streamReader.native.ts +0 -31
- package/ai/chat/streamReader.ts +0 -62
- package/ai/chat/updateTotalUsage.ts +0 -96
- package/ai/context/buildReferenceContext.ts +0 -437
- package/ai/context/calculateContextUsage.ts +0 -133
- package/ai/context/retention.ts +0 -165
- package/ai/context/tokenUtils.ts +0 -78
- package/ai/llm/agentCapabilities.ts +0 -74
- package/ai/llm/calculateGeminiImageTokens.ts +0 -57
- package/ai/llm/deepinfra.ts +0 -94
- package/ai/llm/fireworks.ts +0 -68
- package/ai/llm/generateRequestBody.ts +0 -165
- package/ai/llm/getModelContextWindow.ts +0 -84
- package/ai/llm/getNoloKey.ts +0 -37
- package/ai/llm/getPricing.ts +0 -252
- package/ai/llm/hooks/useModelPricing.ts +0 -75
- package/ai/llm/imagePricing.ts +0 -66
- package/ai/llm/isResponseAPIModel.ts +0 -13
- package/ai/llm/kimi.ts +0 -23
- package/ai/llm/mimo.ts +0 -71
- package/ai/llm/mistral.ts +0 -21
- package/ai/llm/modelAvatar.ts +0 -428
- package/ai/llm/models.ts +0 -45
- package/ai/llm/openrouterModels.ts +0 -6
- package/ai/llm/providers.ts +0 -313
- package/ai/llm/reasoningModels.ts +0 -29
- package/ai/llm/types.ts +0 -82
- package/ai/llm/usageRequestOptions.ts +0 -59
- package/ai/memory/capture.ts +0 -148
- package/ai/memory/consolidate.ts +0 -104
- package/ai/memory/delete.ts +0 -148
- package/ai/memory/overlay.ts +0 -84
- package/ai/memory/query.ts +0 -38
- package/ai/memory/queryShared.ts +0 -160
- package/ai/memory/rank.ts +0 -105
- package/ai/memory/recentRelationshipRecap.ts +0 -247
- package/ai/memory/remember.ts +0 -167
- package/ai/memory/runtime.ts +0 -76
- package/ai/memory/store.ts +0 -20
- package/ai/memory/storeShared.ts +0 -77
- package/ai/memory/types.ts +0 -46
- package/ai/memory/understanding.ts +0 -349
- package/ai/memory/understandingGreeting.ts +0 -264
- package/ai/messages/type.ts +0 -20
- package/ai/policy/commercialMultiplier.ts +0 -16
- package/ai/policy/personalizationDialog.ts +0 -333
- package/ai/policy/runtimePolicy.ts +0 -440
- package/ai/policy/selfUpdateFields.ts +0 -48
- package/ai/skills/referenceRuntime.ts +0 -274
- package/ai/skills/skillDiagnostics.ts +0 -251
- package/ai/skills/skillDocBuilder.ts +0 -139
- package/ai/skills/skillReferenceSummary.ts +0 -63
- package/ai/taskRun/taskRunProtocol.ts +0 -897
- package/ai/token/billingAdminAuditEvent.ts +0 -68
- package/ai/token/billingAdminAuditEventWriter.ts +0 -41
- package/ai/token/billingAnomaly.ts +0 -90
- package/ai/token/billingAnomalyLifecycle.ts +0 -54
- package/ai/token/billingAnomalyLifecycleWriter.ts +0 -44
- package/ai/token/billingAnomalyWriter.ts +0 -41
- package/ai/token/calculatePrice.ts +0 -577
- package/ai/token/db.ts +0 -98
- package/ai/token/deepinfraReconciliation.ts +0 -153
- package/ai/token/deepinfraRequestIdQuery.ts +0 -92
- package/ai/token/externalToolCost.ts +0 -354
- package/ai/token/hooks/useRecords.ts +0 -65
- package/ai/token/missingUsageEstimate.ts +0 -51
- package/ai/token/modelUsageQuery.ts +0 -269
- package/ai/token/normalizeUsage.ts +0 -124
- package/ai/token/openaiImageGenerationUsage.ts +0 -56
- package/ai/token/openaiReconciliation.ts +0 -188
- package/ai/token/prepareTokenUsageData.ts +0 -93
- package/ai/token/providerBillableEvent.ts +0 -84
- package/ai/token/providerBillableEventWriter.ts +0 -36
- package/ai/token/providerBillingAnomalyDrilldown.ts +0 -308
- package/ai/token/providerBillingDrilldown.ts +0 -361
- package/ai/token/providerBillingHealthReport.ts +0 -366
- package/ai/token/providerCall.ts +0 -144
- package/ai/token/providerCallSweeper.ts +0 -168
- package/ai/token/providerCallWriter.ts +0 -33
- package/ai/token/providerCredential.ts +0 -89
- package/ai/token/providerCredentialAnomaly.ts +0 -154
- package/ai/token/providerCredentialLifecycle.ts +0 -59
- package/ai/token/providerCredentialLifecycleWriter.ts +0 -44
- package/ai/token/providerCredentialRegistry.ts +0 -83
- package/ai/token/providerCredentialRegistryCommand.ts +0 -97
- package/ai/token/providerCredentialRegistryList.ts +0 -124
- package/ai/token/providerCredentialRegistryResolver.ts +0 -150
- package/ai/token/providerCredentialRegistryWriter.ts +0 -41
- package/ai/token/providerCredentialRotationCommand.ts +0 -102
- package/ai/token/providerCredentialRuntime.ts +0 -56
- package/ai/token/providerDispatchIntent.ts +0 -67
- package/ai/token/providerDispatchIntentWriter.ts +0 -36
- package/ai/token/providerGateway.ts +0 -260
- package/ai/token/providerReconciliation.ts +0 -148
- package/ai/token/providerReconciliationLocal.ts +0 -97
- package/ai/token/providerReconciliationRunner.ts +0 -165
- package/ai/token/providerReconciliationWriter.ts +0 -41
- package/ai/token/query.ts +0 -88
- package/ai/token/queryUserTokens.ts +0 -59
- package/ai/token/ratingResult.ts +0 -202
- package/ai/token/ratingResultWriter.ts +0 -33
- package/ai/token/resolveBillingTarget.ts +0 -52
- package/ai/token/saveTokenRecord.ts +0 -53
- package/ai/token/serverDialogProjection.ts +0 -80
- package/ai/token/serverTokenWriter.ts +0 -153
- package/ai/token/stats.ts +0 -21
- package/ai/token/tokenThunks.ts +0 -24
- package/ai/token/types.ts +0 -103
- package/ai/tools/agent/agentTools.ts +0 -235
- package/ai/tools/agent/agentUpdateShared.ts +0 -311
- package/ai/tools/agent/callAgentTool.ts +0 -138
- package/ai/tools/agent/createAgentTool.ts +0 -512
- package/ai/tools/agent/createDialogTool.ts +0 -69
- package/ai/tools/agent/createSkillAgentTool.ts +0 -62
- package/ai/tools/agent/parallelBudget.ts +0 -221
- package/ai/tools/agent/prepareAgentDraftTool.ts +0 -173
- package/ai/tools/agent/presets/appBuilderPreset.ts +0 -152
- package/ai/tools/agent/runLlmTool.ts +0 -96
- package/ai/tools/agent/runStreamingAgentTool.ts +0 -72
- package/ai/tools/agent/skillAgentArgs.ts +0 -106
- package/ai/tools/agent/skillAgentPreset.ts +0 -89
- package/ai/tools/agent/startAgentDialogTool.ts +0 -53
- package/ai/tools/agent/streamParallelAgentsTool.ts +0 -122
- package/ai/tools/agent/updateAgentTool.ts +0 -96
- package/ai/tools/agent/updateSelfTool.ts +0 -113
- package/ai/tools/amazonProductScraperTool.ts +0 -86
- package/ai/tools/apifyActorClient.ts +0 -45
- package/ai/tools/appEditGuard.ts +0 -372
- package/ai/tools/appReadSnapshot.ts +0 -153
- package/ai/tools/appTools.ts +0 -1549
- package/ai/tools/applyEditTool.ts +0 -259
- package/ai/tools/applyLineEditsTool.ts +0 -315
- package/ai/tools/browserTools/click.ts +0 -33
- package/ai/tools/browserTools/closeSession.ts +0 -29
- package/ai/tools/browserTools/common.ts +0 -27
- package/ai/tools/browserTools/openSession.ts +0 -48
- package/ai/tools/browserTools/readContent.ts +0 -38
- package/ai/tools/browserTools/selectOption.ts +0 -46
- package/ai/tools/browserTools/typeText.ts +0 -42
- package/ai/tools/category/createCategoryTool.ts +0 -66
- package/ai/tools/category/queryContentsByCategoryTool.ts +0 -69
- package/ai/tools/category/updateContentCategoryTool.ts +0 -75
- package/ai/tools/cfBrowserTools.ts +0 -319
- package/ai/tools/cfSpeechToTextTool.ts +0 -49
- package/ai/tools/checkEnvTool.ts +0 -102
- package/ai/tools/cloudflareCrawlTool.ts +0 -289
- package/ai/tools/codeSearchTool.ts +0 -123
- package/ai/tools/codeTools.ts +0 -101
- package/ai/tools/convertMarxistsBookTool.ts +0 -103
- package/ai/tools/createDocTool.ts +0 -132
- package/ai/tools/createPlanTool.ts +0 -999
- package/ai/tools/createSkillDocTool.ts +0 -155
- package/ai/tools/createWorkflowTool.ts +0 -154
- package/ai/tools/deepseekOcrTool.ts +0 -34
- package/ai/tools/delayTool.ts +0 -31
- package/ai/tools/deleteSpacesTool.ts +0 -325
- package/ai/tools/deleteSpacesToolModel.ts +0 -159
- package/ai/tools/devReloadUtils.ts +0 -29
- package/ai/tools/dialogMessageSearch.ts +0 -137
- package/ai/tools/doctorSkillTool.ts +0 -72
- package/ai/tools/ecommerceScraperTool.ts +0 -86
- package/ai/tools/emailTools.ts +0 -549
- package/ai/tools/evalSkillTool.ts +0 -92
- package/ai/tools/exaSearchTool.ts +0 -64
- package/ai/tools/execShellTool.ts +0 -266
- package/ai/tools/executeSqlTool.ts +0 -192
- package/ai/tools/fetchWebpageSupport.ts +0 -333
- package/ai/tools/fetchWebpageTool.ts +0 -97
- package/ai/tools/geminiImagePreviewTool.ts +0 -361
- package/ai/tools/generateDocxTool.ts +0 -215
- package/ai/tools/googleSearchScraperTool.ts +0 -106
- package/ai/tools/importDataTool.ts +0 -133
- package/ai/tools/importSkillTool.ts +0 -162
- package/ai/tools/index.ts +0 -2132
- package/ai/tools/jdProductScraperTool.ts +0 -821
- package/ai/tools/listFilesTool.ts +0 -85
- package/ai/tools/listUserSpacesTool.ts +0 -113
- package/ai/tools/localFilesTool.ts +0 -276
- package/ai/tools/marxistsOfflineBook.ts +0 -253
- package/ai/tools/modelUsageTools.ts +0 -206
- package/ai/tools/olmOcrTool.ts +0 -34
- package/ai/tools/openaiImageTool.ts +0 -267
- package/ai/tools/prepareTools.ts +0 -23
- package/ai/tools/readDocTool.ts +0 -84
- package/ai/tools/readFileTool.ts +0 -214
- package/ai/tools/readTool.ts +0 -194
- package/ai/tools/readXPostTool.ts +0 -229
- package/ai/tools/rememberMemoryTool.ts +0 -84
- package/ai/tools/remotionVideoTool.ts +0 -151
- package/ai/tools/searchDialogMessagesTool.ts +0 -222
- package/ai/tools/searchRepoTool.ts +0 -118
- package/ai/tools/searchWorkspaceTool.ts +0 -259
- package/ai/tools/skillFollowup.ts +0 -86
- package/ai/tools/surfWeatherTool.ts +0 -169
- package/ai/tools/table/addTableRowTool.ts +0 -217
- package/ai/tools/table/createTableTool.ts +0 -315
- package/ai/tools/table/rowTools.ts +0 -371
- package/ai/tools/table/schemaTools.ts +0 -244
- package/ai/tools/table/shareTableTool.ts +0 -148
- package/ai/tools/table/toolShared.ts +0 -129
- package/ai/tools/taobaoTmallProductScraperTool.ts +0 -49
- package/ai/tools/toolApiClient.ts +0 -255
- package/ai/tools/toolNameAliases.ts +0 -70
- package/ai/tools/toolResultError.ts +0 -42
- package/ai/tools/toolRunSlice.ts +0 -303
- package/ai/tools/toolSchemaCompatibility.ts +0 -53
- package/ai/tools/toolVisibility.ts +0 -4
- package/ai/tools/types.ts +0 -20
- package/ai/tools/uiAskChoiceTool.ts +0 -104
- package/ai/tools/updateContentTitleTool.ts +0 -84
- package/ai/tools/updateDocTool.ts +0 -105
- package/ai/tools/updateUserPreferenceProfileTool.ts +0 -145
- package/ai/tools/wereadGatewayTool.ts +0 -152
- package/ai/tools/whisperTool.ts +0 -77
- package/ai/tools/writeFileTool.ts +0 -213
- package/ai/tools/youtubeScraperTool.ts +0 -116
- package/ai/tools/ziweiChartTool.ts +0 -678
- package/ai/types.ts +0 -55
- package/ai/workflow/workflowExecutor.ts +0 -323
- package/ai/workflow/workflowSlice.ts +0 -73
- package/ai/workflow/workflowTypes.ts +0 -106
- package/app/actions/syncAppRecord.ts +0 -73
- package/app/admin/adminPages.ts +0 -22
- package/app/colors.ts +0 -1
- package/app/constants/animationSets.ts +0 -21
- package/app/constants/appEditor.ts +0 -99
- package/app/constants/clientDownloads.ts +0 -54
- package/app/constants/desktopReleaseManifest.ts +0 -68
- package/app/constants/homeTabs.ts +0 -15
- package/app/constants/routePaths.ts +0 -15
- package/app/email/emailApiRoutes.ts +0 -14
- package/app/favorite/favoriteSlice.ts +0 -690
- package/app/favorite/type.ts +0 -43
- package/app/favorite/useAgentFavorite.ts +0 -43
- package/app/favorite/useContentFavorite.ts +0 -41
- package/app/fetchOwnedApps.ts +0 -269
- package/app/guide/quickStartGuide.ts +0 -128
- package/app/hooks/deleteDbKey.ts +0 -233
- package/app/hooks/index.ts +0 -4
- package/app/hooks/useAppDetail.ts +0 -208
- package/app/hooks/useAppVersions.ts +0 -52
- package/app/hooks/useAutoResizeTextarea.ts +0 -29
- package/app/hooks/useChatPageTitle.ts +0 -85
- package/app/hooks/useClipboardFiles.ts +0 -20
- package/app/hooks/useDesktopLocalConnectorAutostart.ts +0 -38
- package/app/hooks/useDragResize.ts +0 -91
- package/app/hooks/useElementSizeVar.ts +0 -24
- package/app/hooks/useFileDropZone.ts +0 -52
- package/app/hooks/useHasMounted.ts +0 -11
- package/app/hooks/useImageLoadFallback.ts +0 -19
- package/app/hooks/useIsMobile.ts +0 -46
- package/app/hooks/useMyApps.ts +0 -375
- package/app/hooks/useMyContentItems.ts +0 -91
- package/app/hooks/useNewMessageNotification.ts +0 -81
- package/app/hooks/usePageMeta.ts +0 -107
- package/app/hooks/useRecentlyOpened.ts +0 -84
- package/app/hooks/useUnifiedStore.ts +0 -11
- package/app/hooks/useUserNotifications.ts +0 -197
- package/app/hooks.ts +0 -55
- package/app/i18n/clientResources.ts +0 -65
- package/app/i18n/i18n.base.ts +0 -14
- package/app/i18n/i18n.config.ts +0 -67
- package/app/i18n/i18n.server.ts +0 -13
- package/app/i18n/index.ts +0 -15
- package/app/i18n/mapLanguage.ts +0 -11
- package/app/i18n/translations/appBuilder.locale.ts +0 -453
- package/app/i18n/translations/error.locale.ts +0 -246
- package/app/i18n/translations/interface.locale.ts +0 -2174
- package/app/i18n/translations/pricing.locale.ts +0 -397
- package/app/i18n/translations/seo.locale.ts +0 -129
- package/app/i18n/types.ts +0 -6
- package/app/notifications/formatNotification.ts +0 -134
- package/app/notifications/model.ts +0 -77
- package/app/notifications/notificationSlice.ts +0 -141
- package/app/notifications/useNotificationActions.ts +0 -67
- package/app/pages/homeTabState.ts +0 -57
- package/app/pages/quickChatFlow.ts +0 -109
- package/app/pages/rechargeCheckout.ts +0 -23
- package/app/pages/usePageArt.ts +0 -91
- package/app/realtime/sharedSse.ts +0 -182
- package/app/reducer.ts +0 -36
- package/app/seo/pageMeta.ts +0 -123
- package/app/settings/config.ts +0 -54
- package/app/settings/dbActionThunks.ts +0 -34
- package/app/settings/defaultSpacePreference.ts +0 -87
- package/app/settings/navItems.ts +0 -73
- package/app/settings/prepareUserSetting.ts +0 -11
- package/app/settings/settingsRecord.ts +0 -8
- package/app/settings/web/chat-config/useAutoSaveGlobalPrompt.ts +0 -59
- package/app/settings/web/machineStatus.ts +0 -23
- package/app/settings/web/useSettingsStylesheet.ts +0 -28
- package/app/settings/web/userSecurityUtils.ts +0 -21
- package/app/stateViews/runtime.ts +0 -86
- package/app/store.ts +0 -53
- package/app/theme/colors.ts +0 -280
- package/app/theme/fontPreference.ts +0 -77
- package/app/theme/index.ts +0 -7
- package/app/theme/theme.config.ts +0 -120
- package/app/theme/themeModeBootstrap.ts +0 -123
- package/app/theme/useSystemTheme.ts +0 -33
- package/app/types/appSummary.ts +0 -114
- package/app/utils/appDeploySource.ts +0 -50
- package/app/utils/appKeys.ts +0 -55
- package/app/utils/appRuntimeUrl.ts +0 -51
- package/app/utils/async.ts +0 -28
- package/app/utils/asyncMapStatus.ts +0 -31
- package/app/utils/clipboard.ts +0 -86
- package/app/utils/credits.ts +0 -12
- package/app/utils/desktopAgentRuntimeStatusClient.ts +0 -43
- package/app/utils/desktopAgentRuntimeTurnClient.ts +0 -73
- package/app/utils/desktopLocalConnectorClient.ts +0 -83
- package/app/utils/env.ts +0 -12
- package/app/utils/excelToSlate.ts +0 -430
- package/app/utils/fileReaders.ts +0 -12
- package/app/utils/fileUtils.ts +0 -229
- package/app/utils/imageUtils.native.ts +0 -96
- package/app/utils/imageUtils.ts +0 -274
- package/app/utils/ime.ts +0 -43
- package/app/utils/myContentItems.ts +0 -290
- package/app/utils/processDateRange.ts +0 -30
- package/app/utils/retryFetch.ts +0 -61
- package/app/utils/slateToExcel.ts +0 -58
- package/app/utils/toast.native.ts +0 -42
- package/app/utils/toast.ts +0 -3
- package/app/web/spaceInitGuard.ts +0 -28
- package/auth/action/signOutAction.ts +0 -0
- package/auth/action/signUpAction.ts +0 -227
- package/auth/actor.ts +0 -16
- package/auth/adminPermissions.ts +0 -18
- package/auth/authSlice.ts +0 -531
- package/auth/billing.ts +0 -130
- package/auth/client/deleteUserRequest.ts +0 -86
- package/auth/client/loginRequest.ts +0 -14
- package/auth/hooks/useAuth.ts +0 -9
- package/auth/hooks/useDeleteOwnAccount.ts +0 -50
- package/auth/hooks/useDeleteOwnAccountFlow.ts +0 -66
- package/auth/hooks/useDeleteUser.ts +0 -45
- package/auth/hooks/useEnableUser.ts +0 -50
- package/auth/hooks/useFetchUsers.ts +0 -80
- package/auth/hooks/useRechargeUser.ts +0 -82
- package/auth/index.ts +0 -1
- package/auth/invite.ts +0 -19
- package/auth/locale.ts +0 -84
- package/auth/resetAuthScopedClientState.ts +0 -27
- package/auth/rn/tokenManager.ts +0 -72
- package/auth/routes.ts +0 -173
- package/auth/server/accessActivity.ts +0 -144
- package/auth/server/adminPermissions.ts +0 -43
- package/auth/server/adminUsageReport.ts +0 -375
- package/auth/server/billingAnomalies.ts +0 -235
- package/auth/server/billingFullChainSimulator.ts +0 -325
- package/auth/server/billingUsageReport.ts +0 -231
- package/auth/server/cliLogin.ts +0 -198
- package/auth/server/creatorEarningCreditConversion.ts +0 -523
- package/auth/server/creatorEarningsLedger.ts +0 -165
- package/auth/server/creatorEarningsReport.ts +0 -299
- package/auth/server/creatorSettlementLedger.ts +0 -386
- package/auth/server/creatorSettlementReport.ts +0 -442
- package/auth/server/creatorSplitConfig.ts +0 -191
- package/auth/server/deduct.ts +0 -277
- package/auth/server/delete.ts +0 -895
- package/auth/server/disable.ts +0 -62
- package/auth/server/emailAutomation.ts +0 -360
- package/auth/server/emailAutomationConfig.ts +0 -88
- package/auth/server/emailAutomationRules.ts +0 -94
- package/auth/server/emailAutomationTemplates.ts +0 -131
- package/auth/server/emailAutomationTypes.ts +0 -38
- package/auth/server/emailDbConfig.ts +0 -149
- package/auth/server/emailDelivery.ts +0 -964
- package/auth/server/emailDeliveryGuards.ts +0 -285
- package/auth/server/emailPolicy.ts +0 -43
- package/auth/server/emailPreferences.ts +0 -119
- package/auth/server/emailProvider.ts +0 -277
- package/auth/server/emailReport.ts +0 -441
- package/auth/server/emailRuntimeConfig.ts +0 -86
- package/auth/server/emailScenarioNotifications.ts +0 -341
- package/auth/server/enable.ts +0 -62
- package/auth/server/getRechargeHistory.ts +0 -111
- package/auth/server/getUser.ts +0 -72
- package/auth/server/gptProAccess.ts +0 -44
- package/auth/server/inviteReward.ts +0 -298
- package/auth/server/inviteRewardEmail.ts +0 -1
- package/auth/server/ledger.ts +0 -422
- package/auth/server/ledgerAudit.ts +0 -424
- package/auth/server/ledgerWitness.ts +0 -472
- package/auth/server/listusers.ts +0 -156
- package/auth/server/locks.ts +0 -32
- package/auth/server/login.ts +0 -184
- package/auth/server/productBillingSplits.ts +0 -166
- package/auth/server/productEntitlements.ts +0 -142
- package/auth/server/productPurchase.ts +0 -390
- package/auth/server/providerBillingDrilldown.ts +0 -47
- package/auth/server/providerBillingHealth.ts +0 -71
- package/auth/server/providerCredentials.ts +0 -136
- package/auth/server/recharge.ts +0 -290
- package/auth/server/revenueShareLedger.ts +0 -389
- package/auth/server/revenueShareReport.ts +0 -258
- package/auth/server/revenueSplitPolicy.ts +0 -119
- package/auth/server/revokeSessions.ts +0 -60
- package/auth/server/route.ts +0 -272
- package/auth/server/sendEmail.ts +0 -177
- package/auth/server/shared.ts +0 -51
- package/auth/server/signup.ts +0 -430
- package/auth/server/signupIpQuota.ts +0 -44
- package/auth/server/token.ts +0 -107
- package/auth/server/tokenUsageBilling.ts +0 -323
- package/auth/server/transfer.ts +0 -40
- package/auth/server/usageManagementAccess.ts +0 -43
- package/auth/server/usageReport.ts +0 -59
- package/auth/server/utils.ts +0 -200
- package/auth/sessionTokenVersion.ts +0 -38
- package/auth/token.ts +0 -63
- package/auth/tokenCookie.ts +0 -1
- package/auth/types.ts +0 -40
- package/auth/utils.ts +0 -110
- package/auth/web/bootstrapAuthState.ts +0 -60
- package/auth/web/tokenManager.ts +0 -61
- package/auth/web/useRegister.ts +0 -70
- package/chat/chat.locale.ts +0 -804
- package/chat/dialog/actions/addCybotAction.ts +0 -52
- package/chat/dialog/actions/addReferenceKeysAction.ts +0 -62
- package/chat/dialog/actions/builtinDialogLlm.ts +0 -35
- package/chat/dialog/actions/cleanupCliSession.ts +0 -40
- package/chat/dialog/actions/compactDialogAndForkAction.ts +0 -47
- package/chat/dialog/actions/createDialogAction.ts +0 -372
- package/chat/dialog/actions/createScheduledTaskAction.ts +0 -78
- package/chat/dialog/actions/handleSendMessageAction.ts +0 -197
- package/chat/dialog/actions/handleSendMessageResolver.ts +0 -29
- package/chat/dialog/actions/removeCybotAction.ts +0 -6
- package/chat/dialog/actions/removeDialogAgentAction.ts +0 -44
- package/chat/dialog/actions/replacePrimaryCybotAction.ts +0 -6
- package/chat/dialog/actions/setPrimaryDialogAgentAction.ts +0 -52
- package/chat/dialog/actions/updateDialogSummaryAction.ts +0 -405
- package/chat/dialog/actions/updateDialogTitleAction.ts +0 -151
- package/chat/dialog/actions/updateDialogTitlePolicy.ts +0 -30
- package/chat/dialog/actions/updateTokensAction.ts +0 -233
- package/chat/dialog/dialogAgents.ts +0 -54
- package/chat/dialog/dialogLaunchScope.ts +0 -32
- package/chat/dialog/dialogPageRenderMode.ts +0 -182
- package/chat/dialog/dialogSlice.ts +0 -872
- package/chat/dialog/dialogTitle.ts +0 -81
- package/chat/dialog/dialogTokenStats.ts +0 -12
- package/chat/dialog/dialogUrl.ts +0 -6
- package/chat/dialog/ensureDialogSpaceAction.ts +0 -208
- package/chat/dialog/goal.ts +0 -108
- package/chat/dialog/hooks/useStreamingSymbol.ts +0 -63
- package/chat/dialog/objectAssistantRegistry.ts +0 -286
- package/chat/dialog/schedule.ts +0 -17
- package/chat/dialog/useCreateDialog.ts +0 -52
- package/chat/hooks/sendPermissionResolver.ts +0 -128
- package/chat/hooks/useChatInput.ts +0 -130
- package/chat/hooks/useChatInputSeed.ts +0 -31
- package/chat/hooks/useMessageInteraction.ts +0 -412
- package/chat/hooks/useSendPermission.ts +0 -92
- package/chat/hooks/useThinkingVisibility.ts +0 -27
- package/chat/messages/browserImageUrl.ts +0 -48
- package/chat/messages/deleteMessages.ts +0 -47
- package/chat/messages/fetchAndCacheMessages.ts +0 -119
- package/chat/messages/fetchConvMsgs.ts +0 -51
- package/chat/messages/fileUrl.ts +0 -13
- package/chat/messages/generateMessageKey.ts +0 -21
- package/chat/messages/hooks/useBase64Migration.ts +0 -115
- package/chat/messages/messageAgent.ts +0 -8
- package/chat/messages/messageContent.ts +0 -199
- package/chat/messages/messageContract.ts +0 -88
- package/chat/messages/messageSlice.ts +0 -1195
- package/chat/messages/pendingAttachmentParts.ts +0 -143
- package/chat/messages/sendFirstMessage.ts +0 -190
- package/chat/messages/toolPresentation.ts +0 -212
- package/chat/messages/toolThunks.ts +0 -625
- package/chat/messages/web/ChatDisplayContext.ts +0 -14
- package/chat/messages/web/ToolMessageTypes.ts +0 -23
- package/chat/messages/web/diffViewerModel.ts +0 -61
- package/chat/messages/web/groupToolEntries.ts +0 -44
- package/chat/messages/web/groupToolMessages.ts +0 -35
- package/chat/messages/web/inlineReactArtifactParser.ts +0 -63
- package/chat/messages/web/streamingMarkdownModel.ts +0 -41
- package/chat/messages/web/toolDisplayName.ts +0 -22
- package/chat/messages/web/useLoopStopReason.ts +0 -43
- package/chat/messages/web/useStreamingReveal.ts +0 -91
- package/chat/messages/ziweiChartDoc.ts +0 -94
- package/chat/web/docxToSlate.ts +0 -597
- package/chat/web/fileProcessor.ts +0 -442
- package/chat/web/hooks/useProgressiveDisplayCount.ts +0 -102
- package/chat/web/messageInputAgentUi.ts +0 -277
- package/chat/web/messageInputKeyBehavior.ts +0 -53
- package/chat/web/messageInputMention.ts +0 -102
- package/chat/web/messageInputSendResolver.ts +0 -51
- package/chat/web/messageSlashCommands.ts +0 -10
- package/chat/web/pdfOcrProcessor.ts +0 -131
- package/chat/web/sidebar/allViewSearch.ts +0 -87
- package/chat/web/sidebar/types.ts +0 -12
- package/chat/web/sidebar/useChatSidebarFilteredData.ts +0 -141
- package/chat/web/sidebar/useSidebarDragAndDrop.ts +0 -56
- package/connector-experimental/index.ts +0 -5
- package/core/builtinAgents.ts +0 -202
- package/core/coin.ts +0 -42
- package/core/config.ts +0 -15
- package/core/crypto.ts +0 -51
- package/core/events/types.ts +0 -145
- package/core/generateKeyPairFromSeedV1.ts +0 -15
- package/core/generateMainKey.ts +0 -22
- package/core/init.ts +0 -41
- package/core/localOrigins.ts +0 -8
- package/core/password.ts +0 -13
- package/core/prefix.ts +0 -23
- package/create/editor/blockCommands.ts +0 -118
- package/create/editor/highlightExample.ts +0 -66
- package/create/editor/imageUpload.ts +0 -66
- package/create/editor/mark.ts +0 -15
- package/create/editor/plugins/normalizeChineseTypography.ts +0 -85
- package/create/editor/plugins/withBlockStructure.ts +0 -53
- package/create/editor/plugins/withChineseTypography.ts +0 -61
- package/create/editor/plugins/withLayout.ts +0 -30
- package/create/editor/plugins/withLinks.ts +0 -13
- package/create/editor/plugins/withMentions.ts +0 -15
- package/create/editor/plugins/withTables.ts +0 -52
- package/create/editor/tableCommands.ts +0 -270
- package/create/editor/theme/prism/default.ts +0 -145
- package/create/editor/theme/prism/githubDark.ts +0 -139
- package/create/editor/theme/prism/githubLight.ts +0 -139
- package/create/editor/theme/prism/index.ts +0 -23
- package/create/editor/theme/prism/okaidia.ts +0 -197
- package/create/editor/toolMentionOptions.ts +0 -19
- package/create/editor/transforms/fromMarkdown/index.ts +0 -260
- package/create/editor/transforms/fromMarkdown/inline.ts +0 -285
- package/create/editor/transforms/fromMarkdown/table.ts +0 -130
- package/create/editor/transforms/markdownToSlate.ts +0 -24
- package/create/editor/transforms/slateToRenderMarkdown.ts +0 -218
- package/create/editor/transforms/slateToSimplifiedMarkdown.ts +0 -224
- package/create/editor/transforms/slateToText.ts +0 -33
- package/create/editor/types.ts +0 -120
- package/create/editor/utils/editorFactory.ts +0 -54
- package/create/editor/utils/hasPlainCodeBlock.ts +0 -39
- package/create/editor/utils/linkCommands.ts +0 -63
- package/create/editor/utils/pdfToSlate.ts +0 -706
- package/create/editor/utils/slateUtils.ts +0 -233
- package/create/editor/utils/txtToSlate.ts +0 -40
- package/create/hooks/category.ts +0 -82
- package/create/routePaths.ts +0 -5
- package/create/space/addSpaceAction.ts +0 -193
- package/create/space/category/categoryActions.ts +0 -427
- package/create/space/changeSpaceAction.ts +0 -36
- package/create/space/constants.ts +0 -8
- package/create/space/content/addContentAction.ts +0 -116
- package/create/space/content/contentThunks.ts +0 -90
- package/create/space/content/deleteContentFromSpaceAction.ts +0 -187
- package/create/space/content/deleteMultipleContentAction.ts +0 -112
- package/create/space/content/moveContentAction.ts +0 -285
- package/create/space/content/updateContentCategoryAction.ts +0 -154
- package/create/space/content/updateContentTitleAction.ts +0 -106
- package/create/space/content/uploadAndAddFileToSpaceAction.ts +0 -98
- package/create/space/contentKeyUtils.ts +0 -117
- package/create/space/contentLabels.ts +0 -56
- package/create/space/contentTypeMeta.ts +0 -170
- package/create/space/deleteSpaceAction.ts +0 -276
- package/create/space/fetchSpaceAction.ts +0 -70
- package/create/space/fetchSpaceSidebarStateAction.ts +0 -26
- package/create/space/hooks/agentFetchRetry.ts +0 -19
- package/create/space/hooks/useAgentFetcher.ts +0 -149
- package/create/space/hooks/useGroupedContent.ts +0 -118
- package/create/space/hooks/useSpaceEvents.ts +0 -43
- package/create/space/initialSpace.ts +0 -78
- package/create/space/loadDefaultSpaceAction.ts +0 -57
- package/create/space/member/addMemberAction.ts +0 -79
- package/create/space/member/fetchUserSpaceMembershipsAction.ts +0 -386
- package/create/space/member/memberThunks.ts +0 -47
- package/create/space/member/removeMemberAction.ts +0 -67
- package/create/space/publicCatalogSpace.ts +0 -39
- package/create/space/resolvePreferredSpaceId.ts +0 -113
- package/create/space/sidebarVisibleTypes.ts +0 -241
- package/create/space/space.locale.ts +0 -1053
- package/create/space/spaceAccess.ts +0 -182
- package/create/space/spaceCollapsedState.ts +0 -54
- package/create/space/spaceSlice.ts +0 -328
- package/create/space/spaceThunks.ts +0 -410
- package/create/space/types.ts +0 -27
- package/create/space/updateSpaceAction.ts +0 -107
- package/create/space/utils/permissions.ts +0 -47
- package/create/space/validateSpacePermission.ts +0 -38
- package/create/version/appVersionReplication.ts +0 -160
- package/create/version/versionApi.ts +0 -142
- package/database/actions/agentReadResolution.ts +0 -27
- package/database/actions/cacheMergedUserData.ts +0 -64
- package/database/actions/common.ts +0 -279
- package/database/actions/deleteFile.ts +0 -40
- package/database/actions/fetchUserData.ts +0 -16
- package/database/actions/fileContent.ts +0 -125
- package/database/actions/patch.ts +0 -155
- package/database/actions/read.ts +0 -378
- package/database/actions/readAndWait.ts +0 -197
- package/database/actions/readOutcome.ts +0 -45
- package/database/actions/readRequestManager.ts +0 -120
- package/database/actions/readResolution.ts +0 -102
- package/database/actions/remove.ts +0 -94
- package/database/actions/replication.ts +0 -366
- package/database/actions/upload.ts +0 -174
- package/database/actions/upsert.ts +0 -56
- package/database/actions/write.ts +0 -140
- package/database/client/db.native.ts +0 -73
- package/database/client/db.ts +0 -51
- package/database/client/fetchUserData.ts +0 -61
- package/database/client/handleError.ts +0 -19
- package/database/client/queryRequest.ts +0 -21
- package/database/dbActionThunks.ts +0 -1
- package/database/dbSlice.ts +0 -149
- package/database/email.ts +0 -42
- package/database/fileRing.ts +0 -51
- package/database/fileSharding.ts +0 -70
- package/database/fileStorage.native.ts +0 -92
- package/database/fileStorage.ts +0 -232
- package/database/fileUrl.ts +0 -34
- package/database/hooks/useUserData.ts +0 -495
- package/database/index.ts +0 -1
- package/database/queryPrefixes.ts +0 -14
- package/database/requests.ts +0 -443
- package/database/runtimeServerContext.ts +0 -35
- package/database/server/MemoryDB.ts +0 -76
- package/database/server/actorAccess.ts +0 -76
- package/database/server/agentDelegation.ts +0 -125
- package/database/server/authorityStoreConformance.ts +0 -209
- package/database/server/coreDataOwnership.ts +0 -13
- package/database/server/coreDataProxy.ts +0 -93
- package/database/server/cybotReadonly.ts +0 -18
- package/database/server/dataHandlers.ts +0 -117
- package/database/server/delete.ts +0 -516
- package/database/server/emailRepository.ts +0 -1482
- package/database/server/fileRead.ts +0 -337
- package/database/server/fileService.ts +0 -437
- package/database/server/handleTransaction.ts +0 -86
- package/database/server/patch.ts +0 -291
- package/database/server/query.ts +0 -178
- package/database/server/read.ts +0 -314
- package/database/server/recordIdentity.ts +0 -100
- package/database/server/resourceAccess.ts +0 -213
- package/database/server/routes.ts +0 -110
- package/database/server/spaceMemberAuthority.ts +0 -68
- package/database/server/storeBatchCompat.ts +0 -37
- package/database/server/testAuthorityStore.ts +0 -76
- package/database/server/upload.ts +0 -159
- package/database/server/write.ts +0 -492
- package/database/server/writeAuthority.ts +0 -133
- package/database/sqliteDb.ts +0 -46
- package/database/table/deleteTable.ts +0 -120
- package/database/tenantPlacement.ts +0 -57
- package/database/userDataLoadDecision.ts +0 -17
- package/database/userDataMerge.ts +0 -95
- package/database/userPreferenceRegister.ts +0 -108
- package/database/utils/dbPath.ts +0 -47
- package/database/utils/ulid.native.ts +0 -6
- package/integrations/anthropic/anthropicModels.ts +0 -47
- package/integrations/anthropic/type.ts +0 -41
- package/integrations/deepseek/models.ts +0 -67
- package/integrations/google/models.ts +0 -356
- package/integrations/openai/chatCompletionStreamMode.ts +0 -10
- package/integrations/openai/filterAndCleanMessages.ts +0 -284
- package/integrations/openai/flexTier.ts +0 -102
- package/integrations/openai/generateOpenAIRequestBody.ts +0 -274
- package/integrations/openai/generateResponseRequestBody.ts +0 -77
- package/integrations/openai/models.ts +0 -271
- package/integrations/openai/providerBodyCompatibility.ts +0 -23
- package/integrations/openai/responsesHelpers.ts +0 -297
- package/integrations/postmark/index.ts +0 -57
- package/integrations/resend/index.ts +0 -353
- package/integrations/weather/getWeather.ts +0 -24
- package/integrations/weather/index.ts +0 -6
- package/integrations/weather/routes.ts +0 -31
- package/integrations/weather/weatherApi.ts +0 -27
- package/integrations/weather/weatherConstants.ts +0 -2
- package/integrations/weather/weatherI18n.ts +0 -50
- package/integrations/weather/weatherService.ts +0 -50
- package/integrations/weather/weatherTypes.ts +0 -140
- package/integrations/weather/weatherUtils.ts +0 -46
- package/integrations/x-reader/backends/localBrowser.ts +0 -215
- package/integrations/x-reader/backends/publicFallback.ts +0 -31
- package/integrations/x-reader/backends/rawCdp.ts +0 -218
- package/integrations/x-reader/bridge/chromeBridgeManager.ts +0 -235
- package/integrations/x-reader/bridge/readXPostWithBridge.ts +0 -73
- package/integrations/x-reader/fixtureParser.ts +0 -101
- package/integrations/x-reader/index.ts +0 -9
- package/integrations/x-reader/redaction.ts +0 -27
- package/integrations/x-reader/types.ts +0 -109
- package/integrations/x-reader/visibleTextParser.ts +0 -108
- package/integrations/xai/models.ts +0 -13
- package/render/canvas/canvasEditContext.ts +0 -127
- package/render/canvas/canvasRuntime.ts +0 -57
- package/render/canvas/canvasSnapshotParser.ts +0 -76
- package/render/canvas/canvasTree.ts +0 -308
- package/render/canvas/types.ts +0 -46
- package/render/layout/deleteBehavior.ts +0 -52
- package/render/layout/mainLayoutSidebar.ts +0 -17
- package/render/layout/mainLayoutViewMode.ts +0 -81
- package/render/layout/topbarUtils.ts +0 -87
- package/render/layout/useDevReloadPending.ts +0 -30
- package/render/page/createPageAction.ts +0 -183
- package/render/page/docSlice.ts +0 -468
- package/render/page/server/createPage.ts +0 -176
- package/render/page/server/handleCreatePage.ts +0 -82
- package/render/page/server/index.ts +0 -4
- package/render/page/types.ts +0 -17
- package/render/page/useKeyboardSave.ts +0 -48
- package/render/styles/zIndex.ts +0 -12
- package/render/surf/WeatherIconStyles.ts +0 -17
- package/render/surf/color.ts +0 -9
- package/render/surf/config.ts +0 -46
- package/render/surf/screens/style.ts +0 -1
- package/render/surf/styles/ToggleButtonStyles.ts +0 -8
- package/render/surf/utils/groupedWeatherData.ts +0 -32
- package/render/surf/weatherUtils.ts +0 -50
- package/render/table/createTableAction.ts +0 -270
- package/render/table/deleteTableAction.ts +0 -129
- package/render/table/fetchAndCacheTableRows.ts +0 -174
- package/render/table/tableSlice.ts +0 -1106
- package/render/table/tableView.ts +0 -289
- package/render/table/toolValueUtils.ts +0 -363
- package/render/table/types.ts +0 -252
- package/render/table/useCreateTable.ts +0 -72
- package/render/table/useTable.ts +0 -61
- package/render/table/utils/tableSerialization.ts +0 -50
- package/render/web/elements/artifactPreviewCode.ts +0 -43
- package/render/web/elements/artifactRuntimePreload.ts +0 -52
- package/render/web/elements/codeBlockAutoPreview.ts +0 -10
- package/render/web/elements/mermaidPreview.ts +0 -21
- package/render/web/ui/useInlineEdit.ts +0 -135
- package/server/agentEmailRegistrationRoutes.ts +0 -29
- package/server/agentRunRouteContract.ts +0 -9
- package/server/agentRunRoutes.ts +0 -10
- package/server/api/methods.ts +0 -355
- package/server/api/tableHandlers.ts +0 -58
- package/server/api/types.ts +0 -27
- package/server/apiContract.ts +0 -88
- package/server/apiRouteAdapter.ts +0 -218
- package/server/appBundler.ts +0 -90
- package/server/appRoutes.ts +0 -92
- package/server/artifactIconsRoute.ts +0 -89
- package/server/artifactRuntimeRoute.ts +0 -136
- package/server/authenticateToken.ts +0 -118
- package/server/billingLedgerRoutes.ts +0 -63
- package/server/buildManifest.ts +0 -54
- package/server/cliChatRoutes.ts +0 -5
- package/server/cloudflareRoutes.ts +0 -35
- package/server/coreHeaders.ts +0 -29
- package/server/coreReadiness.ts +0 -48
- package/server/coreRoutes.ts +0 -65
- package/server/coreRuntime.ts +0 -98
- package/server/createResponse.ts +0 -68
- package/server/cryptoPaymentRoutes.ts +0 -8
- package/server/databaseRoutes.ts +0 -225
- package/server/desktopRuntimeRoutes.ts +0 -120
- package/server/devBuildInfo.ts +0 -51
- package/server/devReload.ts +0 -161
- package/server/devToolPathPolicy.ts +0 -59
- package/server/devToolRoutes.ts +0 -274
- package/server/email/cloudflareEmailProvider.ts +0 -119
- package/server/email/cloudflareInboundBridge.ts +0 -121
- package/server/email/cloudflareInboundWorker.ts +0 -28
- package/server/email/provider.ts +0 -149
- package/server/email/providerRegistry.ts +0 -22
- package/server/emailInboundRoutes.ts +0 -17
- package/server/entry.ts +0 -211
- package/server/handleRPCRequest.ts +0 -117
- package/server/handlers/activityStatsHandler.ts +0 -77
- package/server/handlers/agentEmailRegistrationE2EHandler.ts +0 -408
- package/server/handlers/agentEmailRegistrationE2ERoutes.ts +0 -6
- package/server/handlers/agentRun/agentLookup.ts +0 -71
- package/server/handlers/agentRun/autonomousRuntime.ts +0 -356
- package/server/handlers/agentRun/backgroundRunDialog.ts +0 -31
- package/server/handlers/agentRun/builtinAgents.ts +0 -271
- package/server/handlers/agentRun/continueDialogContext.ts +0 -102
- package/server/handlers/agentRun/conversationReference.ts +0 -111
- package/server/handlers/agentRun/debugContext.ts +0 -58
- package/server/handlers/agentRun/dialogLookup.ts +0 -68
- package/server/handlers/agentRun/foregroundStreamDialog.ts +0 -13
- package/server/handlers/agentRun/index.ts +0 -2090
- package/server/handlers/agentRun/localRuntimeBootstrap.ts +0 -85
- package/server/handlers/agentRun/loop.ts +0 -2622
- package/server/handlers/agentRun/machineConnector.ts +0 -283
- package/server/handlers/agentRun/machineRunAudit.ts +0 -50
- package/server/handlers/agentRun/modelUsageToolHandlers.ts +0 -371
- package/server/handlers/agentRun/referenceRuntime.ts +0 -50
- package/server/handlers/agentRun/requestContext.ts +0 -90
- package/server/handlers/agentRun/response.ts +0 -27
- package/server/handlers/agentRun/runBilling.ts +0 -108
- package/server/handlers/agentRun/runDialogPreparation.ts +0 -55
- package/server/handlers/agentRun/runtimeBinding.ts +0 -61
- package/server/handlers/agentRun/runtimeContext.ts +0 -143
- package/server/handlers/agentRun/runtimeExecutionContext.ts +0 -165
- package/server/handlers/agentRun/runtimePreparation.ts +0 -195
- package/server/handlers/agentRun/runtimeRouting.ts +0 -73
- package/server/handlers/agentRun/runtimeSystemMessages.ts +0 -230
- package/server/handlers/agentRun/saveDialog.ts +0 -1383
- package/server/handlers/agentRun/syncRunDialog.ts +0 -90
- package/server/handlers/agentRun/tableActivityProjection.ts +0 -132
- package/server/handlers/agentRun/taskRunControlPrompt.ts +0 -122
- package/server/handlers/agentRun/taskRunToolHandler.ts +0 -581
- package/server/handlers/agentRun/toolExecutor.ts +0 -2873
- package/server/handlers/agentRun/toolPolicyGuards.ts +0 -295
- package/server/handlers/agentRun/types.ts +0 -95
- package/server/handlers/agentRun/workspaceLease.ts +0 -58
- package/server/handlers/alphaTestRouteGuard.ts +0 -30
- package/server/handlers/apifyActorHandler.ts +0 -170
- package/server/handlers/appDeployFlow.ts +0 -876
- package/server/handlers/appDeployHandler.ts +0 -4
- package/server/handlers/appDeployMutationHandlers.ts +0 -133
- package/server/handlers/appDeployReadHandlers.ts +0 -321
- package/server/handlers/appDeployShared.ts +0 -230
- package/server/handlers/appDeployStatusStore.ts +0 -185
- package/server/handlers/appDomainHandler.ts +0 -482
- package/server/handlers/appLegacyInfraCleanup.ts +0 -10
- package/server/handlers/appSandboxHandler.ts +0 -1076
- package/server/handlers/appSourceReadiness.ts +0 -75
- package/server/handlers/appSpaceAccess.ts +0 -186
- package/server/handlers/applyEditHandler.ts +0 -544
- package/server/handlers/applyLineEditsHandler.ts +0 -1058
- package/server/handlers/billingLedgerAuditHandler.ts +0 -82
- package/server/handlers/billingLedgerWitnessHandler.ts +0 -161
- package/server/handlers/billingUsageReportHandler.ts +0 -90
- package/server/handlers/browserToolHandler.ts +0 -450
- package/server/handlers/cfTextToSpeechHandler.ts +0 -137
- package/server/handlers/cfWhisperHandler.ts +0 -206
- package/server/handlers/chatBillingSse.ts +0 -79
- package/server/handlers/chatHandler.ts +0 -817
- package/server/handlers/chatProxyRouting.ts +0 -404
- package/server/handlers/chatUpstreamRetry.ts +0 -385
- package/server/handlers/checkEnvHandler.ts +0 -250
- package/server/handlers/cliChatHandler.ts +0 -266
- package/server/handlers/cloudflareBrowserHandler.ts +0 -275
- package/server/handlers/cloudflareCrawlHandler.ts +0 -260
- package/server/handlers/codeSearchHandler.ts +0 -484
- package/server/handlers/connector/connectorConnectionRegistry.ts +0 -240
- package/server/handlers/connector/connectorWebSocket.ts +0 -121
- package/server/handlers/creatorEarningsReportHandler.ts +0 -97
- package/server/handlers/creatorSettlementReportHandler.ts +0 -98
- package/server/handlers/deepseekOcrHandler.ts +0 -114
- package/server/handlers/deleteMemoryHandler.ts +0 -115
- package/server/handlers/desktopAgentRuntimeAdapter.ts +0 -307
- package/server/handlers/desktopAgentRuntimeHostCapabilities.ts +0 -25
- package/server/handlers/desktopAgentRuntimeReadiness.ts +0 -62
- package/server/handlers/desktopAgentRuntimeStatusHandler.ts +0 -62
- package/server/handlers/desktopAgentRuntimeTurnHandler.ts +0 -169
- package/server/handlers/desktopAgentRuntimeTurnService.ts +0 -346
- package/server/handlers/desktopClipboardHandler.ts +0 -104
- package/server/handlers/desktopFiles/handler.ts +0 -159
- package/server/handlers/desktopFiles/operations.ts +0 -202
- package/server/handlers/desktopFiles/sandbox.ts +0 -62
- package/server/handlers/desktopFiles/store.ts +0 -81
- package/server/handlers/desktopLlamaRuntimeHandler.ts +0 -394
- package/server/handlers/desktopLocalConnectorHandler.ts +0 -101
- package/server/handlers/desktopUpdaterHandler.ts +0 -240
- package/server/handlers/dialogEvents.ts +0 -10
- package/server/handlers/emailInboundHandler.ts +0 -65
- package/server/handlers/eventBus.ts +0 -160
- package/server/handlers/exaSearchHandler.ts +0 -73
- package/server/handlers/execShellHandler.ts +0 -661
- package/server/handlers/favoriteHandlers.ts +0 -423
- package/server/handlers/fetchWebpageHandler.ts +0 -117
- package/server/handlers/fileOutlineHandler.ts +0 -107
- package/server/handlers/geminiImagePreviewHandler.ts +0 -612
- package/server/handlers/getDialogBillingHandler.ts +0 -152
- package/server/handlers/getTransactionsHandler.ts +0 -110
- package/server/handlers/googleNativeChat.ts +0 -572
- package/server/handlers/listFilesHandler.ts +0 -139
- package/server/handlers/machines/machineAuth.ts +0 -149
- package/server/handlers/machines/machineBinding.ts +0 -60
- package/server/handlers/machines/machineHandlers.ts +0 -265
- package/server/handlers/machines/machineInstallAssets.ts +0 -565
- package/server/handlers/machines/machineRegistry.ts +0 -89
- package/server/handlers/notificationEmitter.ts +0 -191
- package/server/handlers/notificationsHandler.ts +0 -94
- package/server/handlers/olmOcrHandler.ts +0 -115
- package/server/handlers/openaiImageHandler.ts +0 -500
- package/server/handlers/providerCallsRecentHandler.ts +0 -234
- package/server/handlers/providerHealthHandler.ts +0 -36
- package/server/handlers/providerReconciliationRunHandler.ts +0 -180
- package/server/handlers/providerRequestIdsHandler.ts +0 -105
- package/server/handlers/publicHandler.ts +0 -209
- package/server/handlers/readFileHandler.ts +0 -300
- package/server/handlers/readXPostHandler.ts +0 -180
- package/server/handlers/rememberMemoryHandler.ts +0 -69
- package/server/handlers/remotionRenderHandler.ts +0 -236
- package/server/handlers/renderMarkdownHandler.ts +0 -66
- package/server/handlers/revenueShareReportHandler.ts +0 -96
- package/server/handlers/searchRepoHandler.ts +0 -159
- package/server/handlers/tableAccess.ts +0 -38
- package/server/handlers/tableToolHandlers.ts +0 -755
- package/server/handlers/typecheckWorker.ts +0 -54
- package/server/handlers/userEvents.ts +0 -6
- package/server/handlers/userSecretsHandler.ts +0 -221
- package/server/handlers/versionHandler.ts +0 -286
- package/server/handlers/versionStore.ts +0 -184
- package/server/handlers/wereadGatewayHandler.ts +0 -48
- package/server/handlers/whisperHandler.ts +0 -158
- package/server/handlers/writeFileHandler.ts +0 -168
- package/server/html/desktopReleaseManifest.server.ts +0 -17
- package/server/html/generateErrorResponse.ts +0 -22
- package/server/html/serializeState.ts +0 -9
- package/server/html/ssrPreload.ts +0 -249
- package/server/html/template.ts +0 -275
- package/server/httpCompression.ts +0 -102
- package/server/index.ts +0 -0
- package/server/liveReloadScript.ts +0 -105
- package/server/luIconNames.ts +0 -14
- package/server/machineRoutes.ts +0 -44
- package/server/mediaRoutes.ts +0 -25
- package/server/memoryRoutes.ts +0 -14
- package/server/normalizedStatusRoutes.ts +0 -23
- package/server/payments/crypto/cryptoUsdcBaseAddressPool.ts +0 -49
- package/server/payments/crypto/cryptoUsdcBaseConfig.ts +0 -120
- package/server/payments/crypto/cryptoUsdcBasePaymentProvider.ts +0 -137
- package/server/payments/crypto/cryptoUsdcBaseScanner.ts +0 -272
- package/server/payments/crypto/cryptoUsdcBaseWatcher.ts +0 -40
- package/server/payments/crypto/cryptoUsdtTronAddressPool.ts +0 -49
- package/server/payments/crypto/cryptoUsdtTronConfig.ts +0 -120
- package/server/payments/crypto/cryptoUsdtTronPaymentProvider.ts +0 -135
- package/server/payments/crypto/cryptoUsdtTronScanner.ts +0 -315
- package/server/payments/crypto/cryptoUsdtTronWatcher.ts +0 -40
- package/server/payments/paymentProvider.ts +0 -6
- package/server/payments/paymentRoutes.ts +0 -27
- package/server/payments/rechargeCredits.ts +0 -69
- package/server/payments/waffo/waffoPaymentProvider.ts +0 -344
- package/server/preview/previewCapability.ts +0 -90
- package/server/preview/previewConfig.ts +0 -54
- package/server/preview/previewGateway.ts +0 -71
- package/server/preview/previewRealtime.ts +0 -33
- package/server/providerHealthProbe.ts +0 -198
- package/server/providerHealthRoutes.ts +0 -19
- package/server/publicPaths.ts +0 -12
- package/server/publicRequestHandler.ts +0 -15
- package/server/reactAppBuilder.ts +0 -416
- package/server/realtimeRoutes.ts +0 -69
- package/server/renderStream.ts +0 -20
- package/server/routeFactory.ts +0 -45
- package/server/routes.ts +0 -125
- package/server/runtimeRole.ts +0 -15
- package/server/safeTempFile.ts +0 -48
- package/server/scheduler/scheduledTaskRuntime.ts +0 -230
- package/server/scheduler/schedulerService.ts +0 -290
- package/server/serverDrain.ts +0 -129
- package/server/services/browserSessionManager.ts +0 -354
- package/server/shareRoutes.ts +0 -86
- package/server/sqliteRoutes.ts +0 -141
- package/server/taskRunBridgeRoutes.ts +0 -98
- package/server/tasks.ts +0 -113
- package/server/waffoPaymentRoutes.ts +0 -5
- package/server/webUtilityRoutes.ts +0 -50
- package/server/workerValidator.ts +0 -224
- package/share/action.ts +0 -225
- package/share/clientTableReplication.ts +0 -160
- package/share/link.ts +0 -40
- package/share/loadOwnerShares.ts +0 -154
- package/share/paidAccess.ts +0 -32
- package/share/publicSharePolicy.ts +0 -27
- package/share/server/fetchCommunityShares.ts +0 -45
- package/share/server/helpers.ts +0 -204
- package/share/server/importShare.ts +0 -144
- package/share/server/listCommunityShares.ts +0 -167
- package/share/server/purchaseDoc.ts +0 -216
- package/share/server/readCommunityShareCover.ts +0 -74
- package/share/server/readSharedTable.ts +0 -140
- package/share/server/tableReplication.ts +0 -354
- package/share/shareSlice.ts +0 -53
- package/share/tableShareState.ts +0 -74
|
@@ -1,2622 +0,0 @@
|
|
|
1
|
-
// packages/server/handlers/agentRun/loop.ts
|
|
2
|
-
//
|
|
3
|
-
// 纯函数 Agent Loop(无 Redux,无持久化)。
|
|
4
|
-
// - platform/custom: 直接调用 LLM API,支持本地 tool_calls 循环
|
|
5
|
-
// - cli: 复用 prompt / model / 最近文本历史,但不走本地 tool_calls 协议
|
|
6
|
-
// - 调用方负责传入 messages 历史并保存返回结果
|
|
7
|
-
|
|
8
|
-
import { buildCliPrompt, executeCli, executeCliStreaming, type CliProvider } from "../../../ai/agent/cliExecutor";
|
|
9
|
-
import { findModelConfig, getApiEndpoint } from "../../../ai/llm/providers";
|
|
10
|
-
import {
|
|
11
|
-
DEEPINFRA_KIMI_FALLBACK_MODEL,
|
|
12
|
-
FIREWORKS_KIMI_CURRENT_MODEL,
|
|
13
|
-
KIMI_PLATFORM_FALLBACK_STATUSES,
|
|
14
|
-
OPENROUTER_KIMI_FALLBACK_MODEL,
|
|
15
|
-
isDeepInfraKimiModel,
|
|
16
|
-
isFireworksKimiModel,
|
|
17
|
-
} from "../../../ai/llm/kimi";
|
|
18
|
-
import { getModelInfo } from "../../../ai/llm/getModelContextWindow";
|
|
19
|
-
import { isResponseAPIModel } from "../../../ai/llm/isResponseAPIModel";
|
|
20
|
-
import { getNoloKey } from "../../../ai/llm/getNoloKey";
|
|
21
|
-
import { prepareTools } from "../../../ai/tools/prepareTools";
|
|
22
|
-
import { canonicalizeToolName } from "../../../ai/tools/toolNameAliases";
|
|
23
|
-
import { generateRequestBody } from "../../../ai/llm/generateRequestBody";
|
|
24
|
-
import {
|
|
25
|
-
fetchGoogleNativeImageCompletion,
|
|
26
|
-
fetchGoogleNativeImageChat,
|
|
27
|
-
isGoogleNativeImageModel,
|
|
28
|
-
} from "../googleNativeChat";
|
|
29
|
-
import {
|
|
30
|
-
extractImagePartsFromResponseOutput,
|
|
31
|
-
extractTextFromResponseOutput,
|
|
32
|
-
extractToolCallsFromResponseOutput,
|
|
33
|
-
toResponsesTools,
|
|
34
|
-
} from "../../../integrations/openai/responsesHelpers";
|
|
35
|
-
import { normalizeChatCompletionsBodyForProvider } from "../../../integrations/openai/providerBodyCompatibility";
|
|
36
|
-
import { fetchUpstreamWithGentleRetry } from "../chatUpstreamRetry";
|
|
37
|
-
import type { ProviderCallStore } from "../../../ai/token/providerCallWriter";
|
|
38
|
-
import type { ProviderApiKeySource } from "../../../ai/token/providerCredential";
|
|
39
|
-
import { resolveRuntimeProviderCredential } from "../../../ai/token/providerCredentialRuntime";
|
|
40
|
-
import { executeToolOnServer } from "./toolExecutor";
|
|
41
|
-
import type {
|
|
42
|
-
AgentRunRuntimeContext,
|
|
43
|
-
ChatMessage,
|
|
44
|
-
AssistantToolCall,
|
|
45
|
-
LoopResult,
|
|
46
|
-
ToolPolicyRuntimeState,
|
|
47
|
-
} from "./types";
|
|
48
|
-
import type { ResolvedRuntimePolicy } from "../../../ai/policy/runtimePolicy";
|
|
49
|
-
import { isLocalEndpoint } from "./localRuntimeBootstrap";
|
|
50
|
-
|
|
51
|
-
const MAX_TIME_MS = 10 * 60_000; // 10 min
|
|
52
|
-
const DEFAULT_LLM_REQUEST_TIMEOUT_MS = 300_000;
|
|
53
|
-
const DEFAULT_LOCAL_LLM_REQUEST_TIMEOUT_MS = MAX_TIME_MS;
|
|
54
|
-
const OPENROUTER_CHAT_COMPLETIONS_URL =
|
|
55
|
-
"https://openrouter.ai/api/v1/chat/completions";
|
|
56
|
-
const GOOGLE_FALLBACK_STATUSES = [404, 429, 500, 502, 503, 504];
|
|
57
|
-
const FIREWORKS_OPENROUTER_FALLBACK_STATUSES = KIMI_PLATFORM_FALLBACK_STATUSES;
|
|
58
|
-
const BUILTIN_NOLO_AGENT_KEY = "agent-pub-01NOLOAPPBLD000000019KCKT0";
|
|
59
|
-
|
|
60
|
-
const toOpenRouterGoogleModelName = (modelName: string) => `google/${modelName}`;
|
|
61
|
-
|
|
62
|
-
const parseTimeoutOverride = (rawValue: string | undefined): number | null => {
|
|
63
|
-
const parsed = Number(rawValue);
|
|
64
|
-
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
export const resolveLlmRequestTimeoutMs = (
|
|
68
|
-
agentConfig: any,
|
|
69
|
-
endpoint: string,
|
|
70
|
-
): number => {
|
|
71
|
-
const globalOverride = parseTimeoutOverride(process.env.AGENT_LOOP_LLM_TIMEOUT_MS);
|
|
72
|
-
const localOverride = parseTimeoutOverride(process.env.AGENT_LOOP_LOCAL_LLM_TIMEOUT_MS);
|
|
73
|
-
const isLocalCustomProvider =
|
|
74
|
-
!!agentConfig?.customProviderUrl && isLocalEndpoint(endpoint);
|
|
75
|
-
|
|
76
|
-
if (isLocalCustomProvider && localOverride) {
|
|
77
|
-
return localOverride;
|
|
78
|
-
}
|
|
79
|
-
if (globalOverride) {
|
|
80
|
-
return globalOverride;
|
|
81
|
-
}
|
|
82
|
-
return isLocalCustomProvider
|
|
83
|
-
? DEFAULT_LOCAL_LLM_REQUEST_TIMEOUT_MS
|
|
84
|
-
: DEFAULT_LLM_REQUEST_TIMEOUT_MS;
|
|
85
|
-
};
|
|
86
|
-
|
|
87
|
-
function buildUpstreamHeaders(
|
|
88
|
-
requestUrl: string,
|
|
89
|
-
apiKey?: string | null,
|
|
90
|
-
apiKeyHeader?: string | null,
|
|
91
|
-
) {
|
|
92
|
-
const headers: Record<string, string> = {
|
|
93
|
-
"Content-Type": "application/json",
|
|
94
|
-
};
|
|
95
|
-
const normalizedApiKeyHeader =
|
|
96
|
-
apiKeyHeader?.trim() ||
|
|
97
|
-
(/xiaomimimo\.com/i.test(requestUrl) ? "api-key" : "");
|
|
98
|
-
if (apiKey) {
|
|
99
|
-
if (normalizedApiKeyHeader) {
|
|
100
|
-
headers[normalizedApiKeyHeader] = apiKey;
|
|
101
|
-
} else {
|
|
102
|
-
headers.Authorization = `Bearer ${apiKey}`;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
if (requestUrl.includes("openrouter.ai")) {
|
|
107
|
-
headers["HTTP-Referer"] = "https://nolo.chat";
|
|
108
|
-
headers["X-Title"] = "nolo";
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
return headers;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
async function readAgentApiKeyReference(args: {
|
|
115
|
-
agentKey: string;
|
|
116
|
-
serverBase: string;
|
|
117
|
-
authToken: string;
|
|
118
|
-
}): Promise<string | undefined> {
|
|
119
|
-
const trimmedAgentKey = args.agentKey.trim();
|
|
120
|
-
if (!trimmedAgentKey) return undefined;
|
|
121
|
-
|
|
122
|
-
const url = `${args.serverBase.replace(/\/+$/, "")}/api/v1/db/read/${encodeURIComponent(trimmedAgentKey)}`;
|
|
123
|
-
const headers: Record<string, string> = {};
|
|
124
|
-
if (args.authToken) {
|
|
125
|
-
headers.Authorization = `Bearer ${args.authToken}`;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
const response = await fetch(url, {
|
|
129
|
-
method: "GET",
|
|
130
|
-
headers,
|
|
131
|
-
signal: AbortSignal.timeout(30_000),
|
|
132
|
-
});
|
|
133
|
-
if (!response.ok) {
|
|
134
|
-
throw new Error(`Failed to read apiKeyFromAgentKey agent (${response.status}).`);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
const payload = await response.json() as any;
|
|
138
|
-
const record = payload?.data ?? payload;
|
|
139
|
-
const key = typeof record?.apiKey === "string" ? record.apiKey.trim() : "";
|
|
140
|
-
return key || undefined;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
async function hydrateApiKeyReferenceIfNeeded(
|
|
144
|
-
agentConfig: any,
|
|
145
|
-
serverBase: string,
|
|
146
|
-
authToken: string,
|
|
147
|
-
) {
|
|
148
|
-
if (agentConfig?.apiKey?.trim()) return agentConfig;
|
|
149
|
-
const sourceAgentKey =
|
|
150
|
-
typeof agentConfig?.apiKeyFromAgentKey === "string"
|
|
151
|
-
? agentConfig.apiKeyFromAgentKey.trim()
|
|
152
|
-
: "";
|
|
153
|
-
if (!sourceAgentKey) return agentConfig;
|
|
154
|
-
|
|
155
|
-
const apiKey = await readAgentApiKeyReference({
|
|
156
|
-
agentKey: sourceAgentKey,
|
|
157
|
-
serverBase,
|
|
158
|
-
authToken,
|
|
159
|
-
});
|
|
160
|
-
if (!apiKey) {
|
|
161
|
-
throw new Error(`apiKeyFromAgentKey did not resolve an API key for ${sourceAgentKey}.`);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
return {
|
|
165
|
-
...agentConfig,
|
|
166
|
-
apiKey,
|
|
167
|
-
apiKeySource: "agent_reference",
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
function resolveApiKeySource(agentConfig: any): ProviderApiKeySource {
|
|
172
|
-
if (agentConfig?.apiKeySource === "agent_reference") return "agent_reference";
|
|
173
|
-
if (agentConfig?.apiKey?.trim()) return "agent_secret";
|
|
174
|
-
return "platform_env";
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
async function fetchLoopUpstream(
|
|
178
|
-
endpoint: string,
|
|
179
|
-
agentConfig: any,
|
|
180
|
-
body: Record<string, any>,
|
|
181
|
-
providerCallContext?: {
|
|
182
|
-
userId?: string | null;
|
|
183
|
-
dialogId?: string | null;
|
|
184
|
-
agentId?: string | null;
|
|
185
|
-
},
|
|
186
|
-
providerCallStore?: ProviderCallStore,
|
|
187
|
-
): Promise<{
|
|
188
|
-
response: Response;
|
|
189
|
-
provider?: string;
|
|
190
|
-
model?: string;
|
|
191
|
-
inputPrice?: number;
|
|
192
|
-
outputPrice?: number;
|
|
193
|
-
providerCallIds?: string[];
|
|
194
|
-
}> {
|
|
195
|
-
const apiKey = getApiKey(agentConfig);
|
|
196
|
-
const credential = await resolveRuntimeProviderCredential({
|
|
197
|
-
provider: String(agentConfig?.provider || "unknown"),
|
|
198
|
-
apiKey,
|
|
199
|
-
apiKeySource: resolveApiKeySource(agentConfig),
|
|
200
|
-
registryStore: providerCallStore,
|
|
201
|
-
});
|
|
202
|
-
const llmRequestTimeoutMs = resolveLlmRequestTimeoutMs(agentConfig, endpoint);
|
|
203
|
-
const init: RequestInit = {
|
|
204
|
-
method: "POST",
|
|
205
|
-
headers: {
|
|
206
|
-
...buildUpstreamHeaders(endpoint, apiKey, agentConfig?.apiKeyHeader),
|
|
207
|
-
},
|
|
208
|
-
body: JSON.stringify(body),
|
|
209
|
-
signal: AbortSignal.timeout(llmRequestTimeoutMs),
|
|
210
|
-
};
|
|
211
|
-
|
|
212
|
-
const shouldUseGoogleOpenRouterFallback =
|
|
213
|
-
String(agentConfig?.provider || "").toLowerCase() === "google" &&
|
|
214
|
-
typeof agentConfig?.model === "string" &&
|
|
215
|
-
!!agentConfig.model &&
|
|
216
|
-
!agentConfig?.customProviderUrl;
|
|
217
|
-
const openRouterApiKey = shouldUseGoogleOpenRouterFallback
|
|
218
|
-
? getNoloKey("openrouter")
|
|
219
|
-
: null;
|
|
220
|
-
const shouldUseConfiguredFallback =
|
|
221
|
-
String(agentConfig?.provider || "").toLowerCase() === "fireworks" &&
|
|
222
|
-
typeof agentConfig?.fallbackProvider === "string" &&
|
|
223
|
-
agentConfig.fallbackProvider.trim().toLowerCase() === "openrouter" &&
|
|
224
|
-
typeof agentConfig?.fallbackModel === "string" &&
|
|
225
|
-
!!agentConfig.fallbackModel.trim() &&
|
|
226
|
-
!agentConfig?.customProviderUrl;
|
|
227
|
-
const normalizedAgentProvider = String(agentConfig?.provider || "").toLowerCase();
|
|
228
|
-
const shouldUseKimiPlatformFallback =
|
|
229
|
-
((normalizedAgentProvider === "deepinfra" &&
|
|
230
|
-
isDeepInfraKimiModel(agentConfig?.model)) ||
|
|
231
|
-
(normalizedAgentProvider === "fireworks" &&
|
|
232
|
-
isFireworksKimiModel(agentConfig?.model))) &&
|
|
233
|
-
!agentConfig?.customProviderUrl;
|
|
234
|
-
const fireworksKimiFallbackApiKey =
|
|
235
|
-
shouldUseKimiPlatformFallback && normalizedAgentProvider !== "fireworks"
|
|
236
|
-
? getNoloKey("fireworks")
|
|
237
|
-
: null;
|
|
238
|
-
const deepInfraKimiFallbackApiKey =
|
|
239
|
-
shouldUseKimiPlatformFallback && normalizedAgentProvider !== "deepinfra"
|
|
240
|
-
? getNoloKey("deepinfra")
|
|
241
|
-
: null;
|
|
242
|
-
const openRouterKimiFallbackApiKey = shouldUseKimiPlatformFallback
|
|
243
|
-
? getNoloKey("openrouter")
|
|
244
|
-
: null;
|
|
245
|
-
const configuredFallbackApiKey = shouldUseConfiguredFallback
|
|
246
|
-
? getNoloKey("openrouter")
|
|
247
|
-
: null;
|
|
248
|
-
const deepInfraKimiFallbackUrl = getApiEndpoint({
|
|
249
|
-
provider: "deepinfra",
|
|
250
|
-
model: DEEPINFRA_KIMI_FALLBACK_MODEL,
|
|
251
|
-
} as any);
|
|
252
|
-
const fireworksKimiFallbackUrl = getApiEndpoint({
|
|
253
|
-
provider: "fireworks",
|
|
254
|
-
model: FIREWORKS_KIMI_CURRENT_MODEL,
|
|
255
|
-
} as any);
|
|
256
|
-
const buildProviderCompatibleBody = (
|
|
257
|
-
sourceBody: Record<string, any>,
|
|
258
|
-
providerName: string,
|
|
259
|
-
modelName: string,
|
|
260
|
-
) =>
|
|
261
|
-
normalizeChatCompletionsBodyForProvider({
|
|
262
|
-
body: sourceBody,
|
|
263
|
-
provider: providerName,
|
|
264
|
-
model: modelName,
|
|
265
|
-
});
|
|
266
|
-
const googleFallbackRequest =
|
|
267
|
-
shouldUseGoogleOpenRouterFallback && openRouterApiKey
|
|
268
|
-
? {
|
|
269
|
-
url: OPENROUTER_CHAT_COMPLETIONS_URL,
|
|
270
|
-
provider: "openrouter",
|
|
271
|
-
model: toOpenRouterGoogleModelName(agentConfig.model),
|
|
272
|
-
credential: await resolveRuntimeProviderCredential({
|
|
273
|
-
provider: "openrouter",
|
|
274
|
-
apiKey: openRouterApiKey,
|
|
275
|
-
apiKeySource: "platform_env",
|
|
276
|
-
registryStore: providerCallStore,
|
|
277
|
-
}),
|
|
278
|
-
init: {
|
|
279
|
-
method: "POST",
|
|
280
|
-
headers: buildUpstreamHeaders(
|
|
281
|
-
OPENROUTER_CHAT_COMPLETIONS_URL,
|
|
282
|
-
openRouterApiKey,
|
|
283
|
-
),
|
|
284
|
-
body: JSON.stringify(
|
|
285
|
-
buildProviderCompatibleBody(
|
|
286
|
-
body,
|
|
287
|
-
"openrouter",
|
|
288
|
-
toOpenRouterGoogleModelName(agentConfig.model),
|
|
289
|
-
),
|
|
290
|
-
),
|
|
291
|
-
signal: init.signal,
|
|
292
|
-
} satisfies RequestInit,
|
|
293
|
-
}
|
|
294
|
-
: undefined;
|
|
295
|
-
const kimiPlatformFallbackRequests = shouldUseKimiPlatformFallback
|
|
296
|
-
? [
|
|
297
|
-
fireworksKimiFallbackApiKey
|
|
298
|
-
? {
|
|
299
|
-
url: fireworksKimiFallbackUrl,
|
|
300
|
-
provider: "fireworks",
|
|
301
|
-
model: FIREWORKS_KIMI_CURRENT_MODEL,
|
|
302
|
-
credential: await resolveRuntimeProviderCredential({
|
|
303
|
-
provider: "fireworks",
|
|
304
|
-
apiKey: fireworksKimiFallbackApiKey,
|
|
305
|
-
apiKeySource: "platform_env",
|
|
306
|
-
registryStore: providerCallStore,
|
|
307
|
-
}),
|
|
308
|
-
init: {
|
|
309
|
-
method: "POST",
|
|
310
|
-
headers: buildUpstreamHeaders(
|
|
311
|
-
fireworksKimiFallbackUrl,
|
|
312
|
-
fireworksKimiFallbackApiKey,
|
|
313
|
-
),
|
|
314
|
-
body: JSON.stringify(
|
|
315
|
-
buildProviderCompatibleBody(
|
|
316
|
-
body,
|
|
317
|
-
"fireworks",
|
|
318
|
-
FIREWORKS_KIMI_CURRENT_MODEL,
|
|
319
|
-
),
|
|
320
|
-
),
|
|
321
|
-
signal: init.signal,
|
|
322
|
-
} satisfies RequestInit,
|
|
323
|
-
}
|
|
324
|
-
: undefined,
|
|
325
|
-
deepInfraKimiFallbackApiKey
|
|
326
|
-
? {
|
|
327
|
-
url: deepInfraKimiFallbackUrl,
|
|
328
|
-
provider: "deepinfra",
|
|
329
|
-
model: DEEPINFRA_KIMI_FALLBACK_MODEL,
|
|
330
|
-
credential: await resolveRuntimeProviderCredential({
|
|
331
|
-
provider: "deepinfra",
|
|
332
|
-
apiKey: deepInfraKimiFallbackApiKey,
|
|
333
|
-
apiKeySource: "platform_env",
|
|
334
|
-
registryStore: providerCallStore,
|
|
335
|
-
}),
|
|
336
|
-
init: {
|
|
337
|
-
method: "POST",
|
|
338
|
-
headers: buildUpstreamHeaders(
|
|
339
|
-
deepInfraKimiFallbackUrl,
|
|
340
|
-
deepInfraKimiFallbackApiKey,
|
|
341
|
-
),
|
|
342
|
-
body: JSON.stringify(
|
|
343
|
-
buildProviderCompatibleBody(
|
|
344
|
-
body,
|
|
345
|
-
"deepinfra",
|
|
346
|
-
DEEPINFRA_KIMI_FALLBACK_MODEL,
|
|
347
|
-
),
|
|
348
|
-
),
|
|
349
|
-
signal: init.signal,
|
|
350
|
-
} satisfies RequestInit,
|
|
351
|
-
}
|
|
352
|
-
: undefined,
|
|
353
|
-
openRouterKimiFallbackApiKey
|
|
354
|
-
? {
|
|
355
|
-
url: OPENROUTER_CHAT_COMPLETIONS_URL,
|
|
356
|
-
provider: "openrouter",
|
|
357
|
-
model: OPENROUTER_KIMI_FALLBACK_MODEL,
|
|
358
|
-
credential: await resolveRuntimeProviderCredential({
|
|
359
|
-
provider: "openrouter",
|
|
360
|
-
apiKey: openRouterKimiFallbackApiKey,
|
|
361
|
-
apiKeySource: "platform_env",
|
|
362
|
-
registryStore: providerCallStore,
|
|
363
|
-
}),
|
|
364
|
-
init: {
|
|
365
|
-
method: "POST",
|
|
366
|
-
headers: buildUpstreamHeaders(
|
|
367
|
-
OPENROUTER_CHAT_COMPLETIONS_URL,
|
|
368
|
-
openRouterKimiFallbackApiKey,
|
|
369
|
-
),
|
|
370
|
-
body: JSON.stringify(
|
|
371
|
-
buildProviderCompatibleBody(
|
|
372
|
-
body,
|
|
373
|
-
"openrouter",
|
|
374
|
-
OPENROUTER_KIMI_FALLBACK_MODEL,
|
|
375
|
-
),
|
|
376
|
-
),
|
|
377
|
-
signal: init.signal,
|
|
378
|
-
} satisfies RequestInit,
|
|
379
|
-
}
|
|
380
|
-
: undefined,
|
|
381
|
-
].filter((request): request is NonNullable<typeof request> => !!request)
|
|
382
|
-
: [];
|
|
383
|
-
const configuredFallbackRequest =
|
|
384
|
-
shouldUseConfiguredFallback && configuredFallbackApiKey
|
|
385
|
-
? {
|
|
386
|
-
url: OPENROUTER_CHAT_COMPLETIONS_URL,
|
|
387
|
-
provider: "openrouter",
|
|
388
|
-
model: agentConfig.fallbackModel,
|
|
389
|
-
credential: await resolveRuntimeProviderCredential({
|
|
390
|
-
provider: "openrouter",
|
|
391
|
-
apiKey: configuredFallbackApiKey,
|
|
392
|
-
apiKeySource: "platform_env",
|
|
393
|
-
registryStore: providerCallStore,
|
|
394
|
-
}),
|
|
395
|
-
init: {
|
|
396
|
-
method: "POST",
|
|
397
|
-
headers: buildUpstreamHeaders(
|
|
398
|
-
OPENROUTER_CHAT_COMPLETIONS_URL,
|
|
399
|
-
configuredFallbackApiKey,
|
|
400
|
-
),
|
|
401
|
-
body: JSON.stringify(
|
|
402
|
-
buildProviderCompatibleBody(
|
|
403
|
-
body,
|
|
404
|
-
"openrouter",
|
|
405
|
-
agentConfig.fallbackModel,
|
|
406
|
-
),
|
|
407
|
-
),
|
|
408
|
-
signal: init.signal,
|
|
409
|
-
} satisfies RequestInit,
|
|
410
|
-
}
|
|
411
|
-
: undefined;
|
|
412
|
-
|
|
413
|
-
if (
|
|
414
|
-
String(agentConfig?.provider || "").toLowerCase() === "google" &&
|
|
415
|
-
isGoogleNativeImageModel(agentConfig?.model)
|
|
416
|
-
) {
|
|
417
|
-
try {
|
|
418
|
-
if (body.stream) {
|
|
419
|
-
return {
|
|
420
|
-
response: await fetchGoogleNativeImageChat({
|
|
421
|
-
model: agentConfig.model,
|
|
422
|
-
body,
|
|
423
|
-
apiKey,
|
|
424
|
-
signal: init.signal,
|
|
425
|
-
streamHeaders: {
|
|
426
|
-
"Content-Type": "text/event-stream",
|
|
427
|
-
},
|
|
428
|
-
}),
|
|
429
|
-
provider: agentConfig.provider,
|
|
430
|
-
model: agentConfig.model,
|
|
431
|
-
inputPrice: agentConfig.inputPrice,
|
|
432
|
-
outputPrice: agentConfig.outputPrice,
|
|
433
|
-
};
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
return {
|
|
437
|
-
response: await fetchGoogleNativeImageCompletion({
|
|
438
|
-
model: agentConfig.model,
|
|
439
|
-
body,
|
|
440
|
-
apiKey,
|
|
441
|
-
signal: init.signal,
|
|
442
|
-
}),
|
|
443
|
-
provider: agentConfig.provider,
|
|
444
|
-
model: agentConfig.model,
|
|
445
|
-
inputPrice: agentConfig.inputPrice,
|
|
446
|
-
outputPrice: agentConfig.outputPrice,
|
|
447
|
-
};
|
|
448
|
-
} catch (error: any) {
|
|
449
|
-
const shouldFallbackToOpenRouter =
|
|
450
|
-
!!googleFallbackRequest &&
|
|
451
|
-
(!("status" in (error ?? {})) ||
|
|
452
|
-
GOOGLE_FALLBACK_STATUSES.includes(Number(error?.status)));
|
|
453
|
-
if (!shouldFallbackToOpenRouter) {
|
|
454
|
-
throw error;
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
try {
|
|
460
|
-
const requestArgs = googleFallbackRequest
|
|
461
|
-
? {
|
|
462
|
-
url: endpoint,
|
|
463
|
-
init,
|
|
464
|
-
provider: agentConfig.provider,
|
|
465
|
-
model: agentConfig.model,
|
|
466
|
-
credential,
|
|
467
|
-
log: console,
|
|
468
|
-
fallbackRequest: googleFallbackRequest,
|
|
469
|
-
fallbackOnStatuses:
|
|
470
|
-
String(agentConfig?.provider || "").toLowerCase() === "google"
|
|
471
|
-
? GOOGLE_FALLBACK_STATUSES
|
|
472
|
-
: undefined,
|
|
473
|
-
}
|
|
474
|
-
: kimiPlatformFallbackRequests.length > 0
|
|
475
|
-
? {
|
|
476
|
-
url: endpoint,
|
|
477
|
-
init,
|
|
478
|
-
provider: agentConfig.provider,
|
|
479
|
-
model: agentConfig.model,
|
|
480
|
-
credential,
|
|
481
|
-
log: console,
|
|
482
|
-
fallbackRequests: kimiPlatformFallbackRequests,
|
|
483
|
-
fallbackOnStatuses: KIMI_PLATFORM_FALLBACK_STATUSES,
|
|
484
|
-
}
|
|
485
|
-
: configuredFallbackRequest
|
|
486
|
-
? {
|
|
487
|
-
url: endpoint,
|
|
488
|
-
init,
|
|
489
|
-
provider: agentConfig.provider,
|
|
490
|
-
model: agentConfig.model,
|
|
491
|
-
credential,
|
|
492
|
-
log: console,
|
|
493
|
-
fallbackRequest: configuredFallbackRequest,
|
|
494
|
-
fallbackOnStatuses: FIREWORKS_OPENROUTER_FALLBACK_STATUSES,
|
|
495
|
-
}
|
|
496
|
-
: {
|
|
497
|
-
url: endpoint,
|
|
498
|
-
init,
|
|
499
|
-
provider: agentConfig.provider,
|
|
500
|
-
model: agentConfig.model,
|
|
501
|
-
credential,
|
|
502
|
-
log: console,
|
|
503
|
-
};
|
|
504
|
-
const upstreamResponse = await fetchUpstreamWithGentleRetry({
|
|
505
|
-
...requestArgs,
|
|
506
|
-
...(providerCallStore && providerCallContext?.userId
|
|
507
|
-
? {
|
|
508
|
-
providerCallStore,
|
|
509
|
-
providerCallContext: {
|
|
510
|
-
userId: providerCallContext.userId,
|
|
511
|
-
dialogId: providerCallContext.dialogId ?? undefined,
|
|
512
|
-
agentId: providerCallContext.agentId ?? undefined,
|
|
513
|
-
endpoint: "agentRun",
|
|
514
|
-
},
|
|
515
|
-
}
|
|
516
|
-
: {}),
|
|
517
|
-
});
|
|
518
|
-
const actualProvider = upstreamResponse.provider;
|
|
519
|
-
const actualModel = upstreamResponse.model;
|
|
520
|
-
const actualModelConfig =
|
|
521
|
-
actualProvider && actualModel
|
|
522
|
-
? findModelConfig(String(actualProvider), String(actualModel))
|
|
523
|
-
: null;
|
|
524
|
-
return {
|
|
525
|
-
response: upstreamResponse.response,
|
|
526
|
-
provider: actualProvider,
|
|
527
|
-
model: actualModel,
|
|
528
|
-
inputPrice: actualModelConfig?.price.input ?? agentConfig.inputPrice,
|
|
529
|
-
outputPrice: actualModelConfig?.price.output ?? agentConfig.outputPrice,
|
|
530
|
-
providerCallIds: upstreamResponse.providerCallIds,
|
|
531
|
-
};
|
|
532
|
-
} catch (error: any) {
|
|
533
|
-
if (error?.name === "TimeoutError" || error?.name === "AbortError") {
|
|
534
|
-
throw new Error(`LLM API timeout after ${llmRequestTimeoutMs}ms: ${endpoint}`);
|
|
535
|
-
}
|
|
536
|
-
throw error;
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
function extractAssistantText(message: ChatMessage | null | undefined): string {
|
|
541
|
-
if (!message) return "";
|
|
542
|
-
return typeof message.content === "string"
|
|
543
|
-
? message.content
|
|
544
|
-
: (message.content as any[] | null)
|
|
545
|
-
?.filter((p: any) => p.type === "text")
|
|
546
|
-
.map((p: any) => p.text ?? "")
|
|
547
|
-
.join("") ?? "";
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
const FINAL_PARALLEL_SUMMARY_REPAIR_PROMPT =
|
|
551
|
-
"你刚刚没有给出最终文本回答。请基于上面的并行分支内容,直接输出最终结论,不要再调用任何工具,也不要留空。至少明确给出:共识、保留分歧、下一步。";
|
|
552
|
-
|
|
553
|
-
const EMPTY_ASSISTANT_REPAIR_PROMPT =
|
|
554
|
-
"你刚刚返回了空消息。请继续完成当前任务:如果需要工具就调用工具,否则直接输出可执行的简短结果;不要留空。";
|
|
555
|
-
|
|
556
|
-
function hasParallelBranchMessages(messages: ChatMessage[]): boolean {
|
|
557
|
-
return messages.some(
|
|
558
|
-
(message) =>
|
|
559
|
-
message.role === "assistant" &&
|
|
560
|
-
typeof message.parallelSessionId === "string" &&
|
|
561
|
-
!!message.parallelSessionId.trim(),
|
|
562
|
-
);
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
function extractMessageText(message: ChatMessage | null | undefined): string {
|
|
566
|
-
if (!message) return "";
|
|
567
|
-
return typeof message.content === "string"
|
|
568
|
-
? message.content
|
|
569
|
-
: (message.content as any[] | null)
|
|
570
|
-
?.filter((part: any) => part?.type === "text")
|
|
571
|
-
.map((part: any) => part.text ?? "")
|
|
572
|
-
.join("") ?? "";
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
function buildCliTaskPrompt(
|
|
576
|
-
initialMessages: ChatMessage[],
|
|
577
|
-
userInput?: string | null,
|
|
578
|
-
): string {
|
|
579
|
-
// CLI agent 只接文本上下文,不把本地 tool 轨迹伪装成可重放的远端工具调用。
|
|
580
|
-
const history = initialMessages
|
|
581
|
-
.filter((message) => message.role === "user" || message.role === "assistant")
|
|
582
|
-
.map((message) => {
|
|
583
|
-
const text = extractMessageText(message).trim();
|
|
584
|
-
if (!text) return null;
|
|
585
|
-
const roleLabel =
|
|
586
|
-
message.role === "user"
|
|
587
|
-
? "用户"
|
|
588
|
-
: "助手";
|
|
589
|
-
return `[${roleLabel}]\n${text}`;
|
|
590
|
-
})
|
|
591
|
-
.filter((message): message is string => !!message)
|
|
592
|
-
.slice(-6);
|
|
593
|
-
|
|
594
|
-
const explicitUserInput = userInput?.trim() ?? "";
|
|
595
|
-
if (explicitUserInput) {
|
|
596
|
-
const explicitUserEntry = `[用户]\n${explicitUserInput}`;
|
|
597
|
-
if (history.at(-1) !== explicitUserEntry) {
|
|
598
|
-
history.push(explicitUserEntry);
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
if (history.length === 0) return explicitUserInput;
|
|
603
|
-
if (history.length === 1 && history[0].startsWith("[用户]\n")) {
|
|
604
|
-
return history[0].slice("[用户]\n".length);
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
return `请基于以下最近对话继续完成当前任务。\n\n${history.join("\n\n")}`;
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
function appendTextPart(
|
|
611
|
-
content: NonNullable<Exclude<ChatMessage["content"], string>>,
|
|
612
|
-
text: string,
|
|
613
|
-
) {
|
|
614
|
-
if (!text) return;
|
|
615
|
-
const lastPart = content.at(-1);
|
|
616
|
-
if (lastPart?.type === "text") {
|
|
617
|
-
lastPart.text += text;
|
|
618
|
-
return;
|
|
619
|
-
}
|
|
620
|
-
content.push({ type: "text", text });
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
function finalizeAssistantContent(
|
|
624
|
-
content: NonNullable<Exclude<ChatMessage["content"], string>>,
|
|
625
|
-
): ChatMessage["content"] {
|
|
626
|
-
if (content.length === 0) return null;
|
|
627
|
-
if (content.every((part) => part.type === "text")) {
|
|
628
|
-
return content.map((part) => part.text).join("");
|
|
629
|
-
}
|
|
630
|
-
return content;
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
function parseToolResult(content: string | null | undefined): any {
|
|
634
|
-
if (typeof content !== "string" || !content.trim()) return null;
|
|
635
|
-
try {
|
|
636
|
-
return JSON.parse(content);
|
|
637
|
-
} catch {
|
|
638
|
-
return null;
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
function pickString(value: unknown): string | null {
|
|
643
|
-
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
function getToolError(parsed: any): string | null {
|
|
647
|
-
if (!parsed || typeof parsed !== "object") return null;
|
|
648
|
-
const error = pickString(parsed.error);
|
|
649
|
-
if (error) return error;
|
|
650
|
-
if (parsed.ok === false) return "tool returned ok=false";
|
|
651
|
-
if (parsed.success === false) return "tool returned success=false";
|
|
652
|
-
return null;
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
const TASK_RUN_DIRECT_TOOL_NAMES = new Set([
|
|
656
|
-
"taskRun",
|
|
657
|
-
"readTaskContext",
|
|
658
|
-
"queryReadyWorkItems",
|
|
659
|
-
"upsertWorkItem",
|
|
660
|
-
"claimWorkItem",
|
|
661
|
-
"openDialog",
|
|
662
|
-
"recordArtifact",
|
|
663
|
-
"setBlocker",
|
|
664
|
-
"clearBlocker",
|
|
665
|
-
"requestReview",
|
|
666
|
-
"recordReview",
|
|
667
|
-
"submitOutcome",
|
|
668
|
-
"closeWorkItem",
|
|
669
|
-
]);
|
|
670
|
-
|
|
671
|
-
function normalizeDirectCompletionToolName(toolName: string | undefined): string {
|
|
672
|
-
return canonicalizeToolName((toolName ?? "").replace(/^functions\./, "").trim());
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
function buildStartAgentDialogDirectCompletion(parsed: any): string | null {
|
|
676
|
-
if (!parsed || typeof parsed !== "object") return null;
|
|
677
|
-
const error = getToolError(parsed);
|
|
678
|
-
if (error) {
|
|
679
|
-
const detail = pickString(parsed.detail);
|
|
680
|
-
return [
|
|
681
|
-
"startAgentDialog failed.",
|
|
682
|
-
`error: ${error}`,
|
|
683
|
-
detail ? `detail: ${detail}` : "",
|
|
684
|
-
].filter(Boolean).join("\n");
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
if (parsed.success !== true) return null;
|
|
688
|
-
const childDialogId = pickString(parsed.childDialogId);
|
|
689
|
-
if (!childDialogId) {
|
|
690
|
-
return [
|
|
691
|
-
"startAgentDialog returned success=true but did not return childDialogId.",
|
|
692
|
-
"Treat this handoff as unverified; do not claim the child agent started or completed.",
|
|
693
|
-
].join("\n");
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
const lines = [
|
|
697
|
-
"startAgentDialog accepted the handoff. This means the child dialog was started or queued, not completed.",
|
|
698
|
-
`childDialogId: ${childDialogId}`,
|
|
699
|
-
pickString(parsed.status) ? `status: ${pickString(parsed.status)}` : "",
|
|
700
|
-
pickString(parsed.targetAgentKey) ? `targetAgentKey: ${pickString(parsed.targetAgentKey)}` : "",
|
|
701
|
-
pickString(parsed.parentDialogId) ? `parentDialogId: ${pickString(parsed.parentDialogId)}` : "",
|
|
702
|
-
].filter(Boolean);
|
|
703
|
-
|
|
704
|
-
return lines.join("\n");
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
function buildTaskRunDirectCompletion(parsed: any): string | null {
|
|
708
|
-
if (!parsed || typeof parsed !== "object") return null;
|
|
709
|
-
const error = getToolError(parsed);
|
|
710
|
-
if (error) {
|
|
711
|
-
return [
|
|
712
|
-
"taskRun failed.",
|
|
713
|
-
`error: ${error}`,
|
|
714
|
-
"No task status or outcome was written by this tool call.",
|
|
715
|
-
].join("\n");
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
return null;
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
function buildUpdateTableRowDirectCompletion(parsed: any): string | null {
|
|
722
|
-
if (!parsed || typeof parsed !== "object") return null;
|
|
723
|
-
const error = getToolError(parsed);
|
|
724
|
-
if (error) {
|
|
725
|
-
return [
|
|
726
|
-
"updateTableRow failed.",
|
|
727
|
-
`error: ${error}`,
|
|
728
|
-
"No table row update was confirmed by this tool call.",
|
|
729
|
-
].join("\n");
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
return null;
|
|
733
|
-
}
|
|
734
|
-
|
|
735
|
-
function buildDirectCompletionFromToolResult(toolName: string | undefined, content: string): string | null {
|
|
736
|
-
const normalizedToolName = normalizeDirectCompletionToolName(toolName);
|
|
737
|
-
const parsed = parseToolResult(content);
|
|
738
|
-
if (!parsed || typeof parsed !== "object") return null;
|
|
739
|
-
|
|
740
|
-
if (normalizedToolName === "startAgentDialog") {
|
|
741
|
-
return buildStartAgentDialogDirectCompletion(parsed);
|
|
742
|
-
}
|
|
743
|
-
if (TASK_RUN_DIRECT_TOOL_NAMES.has(normalizedToolName)) {
|
|
744
|
-
return buildTaskRunDirectCompletion(parsed);
|
|
745
|
-
}
|
|
746
|
-
if (normalizedToolName === "updateTableRow") {
|
|
747
|
-
return buildUpdateTableRowDirectCompletion(parsed);
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
if (normalizedToolName !== "remotionRenderVideo") return null;
|
|
751
|
-
if (parsed.ok === false || parsed.error) return null;
|
|
752
|
-
if (typeof parsed.fileId !== "string" || !parsed.fileId.trim()) return null;
|
|
753
|
-
|
|
754
|
-
const lines = [
|
|
755
|
-
parsed.text || "Remotion 视频已生成。",
|
|
756
|
-
`fileId: ${parsed.fileId.trim()}`,
|
|
757
|
-
typeof parsed.fileDbKey === "string" && parsed.fileDbKey.trim()
|
|
758
|
-
? `fileDbKey: ${parsed.fileDbKey.trim()}`
|
|
759
|
-
: "",
|
|
760
|
-
typeof parsed.url === "string" && parsed.url.trim()
|
|
761
|
-
? `url: ${parsed.url.trim()}`
|
|
762
|
-
: "",
|
|
763
|
-
typeof parsed.template === "string" && parsed.template.trim()
|
|
764
|
-
? `template: ${parsed.template.trim()}`
|
|
765
|
-
: "",
|
|
766
|
-
].filter(Boolean);
|
|
767
|
-
|
|
768
|
-
return lines.join("\n");
|
|
769
|
-
}
|
|
770
|
-
|
|
771
|
-
function appendParallelBranchMessages(messages: ChatMessage[], parsed: any) {
|
|
772
|
-
if (!Array.isArray(parsed?.results)) return;
|
|
773
|
-
for (const [index, item] of parsed.results.entries()) {
|
|
774
|
-
if (!item?.ok || typeof item?.content !== "string" || !item.content.trim()) {
|
|
775
|
-
continue;
|
|
776
|
-
}
|
|
777
|
-
messages.push({
|
|
778
|
-
role: "assistant",
|
|
779
|
-
content: item.content,
|
|
780
|
-
cybotKey: item.agentKey,
|
|
781
|
-
agentKey: item.agentKey,
|
|
782
|
-
agentName:
|
|
783
|
-
typeof item.agentName === "string" && item.agentName.trim()
|
|
784
|
-
? item.agentName.trim()
|
|
785
|
-
: typeof item.label === "string" && item.label.trim()
|
|
786
|
-
? item.label.trim()
|
|
787
|
-
: undefined,
|
|
788
|
-
parallelSessionId:
|
|
789
|
-
typeof parsed.parallelSessionId === "string"
|
|
790
|
-
? parsed.parallelSessionId
|
|
791
|
-
: undefined,
|
|
792
|
-
parallelBranchId:
|
|
793
|
-
typeof item.branchId === "string" ? item.branchId : undefined,
|
|
794
|
-
parallelLabel:
|
|
795
|
-
typeof item.label === "string" ? item.label : undefined,
|
|
796
|
-
parallelIndex:
|
|
797
|
-
typeof item.parallelIndex === "number" ? item.parallelIndex : index,
|
|
798
|
-
});
|
|
799
|
-
}
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
function normalizeLoopMessageContent(
|
|
803
|
-
content: ChatMessage["content"] | Record<string, unknown> | undefined,
|
|
804
|
-
): ChatMessage["content"] {
|
|
805
|
-
if (typeof content === "string" || Array.isArray(content) || content === null) {
|
|
806
|
-
return content;
|
|
807
|
-
}
|
|
808
|
-
if (content == null) return null;
|
|
809
|
-
return JSON.stringify(content);
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
const MAX_EXEC_SHELL_COMMAND_CHARS = 500;
|
|
813
|
-
const MAX_EXEC_SHELL_STDOUT_CHARS = 4000;
|
|
814
|
-
const MAX_EXEC_SHELL_STDERR_CHARS = 2000;
|
|
815
|
-
const MAX_READ_FILE_CONTENT_CHARS = 6000;
|
|
816
|
-
const MAX_READ_DOC_CONTENT_CHARS = 6000;
|
|
817
|
-
const MAX_FETCH_WEBPAGE_CONTENT_CHARS = 6000;
|
|
818
|
-
const MAX_SEARCH_RESULT_ITEMS = 8;
|
|
819
|
-
const MAX_SEARCH_PATH_CHARS = 240;
|
|
820
|
-
const MAX_SEARCH_PREVIEW_CHARS = 220;
|
|
821
|
-
const MAX_IMAGE_TOOL_TEXT_CHARS = 1200;
|
|
822
|
-
|
|
823
|
-
function compactTextForUpstream(value: string, maxChars: number): string {
|
|
824
|
-
if (value.length <= maxChars) return value;
|
|
825
|
-
const hiddenChars = value.length - maxChars;
|
|
826
|
-
return `${value.slice(0, maxChars)}\n...[truncated ${hiddenChars} chars]`;
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
function compactSearchPathForUpstream(value: unknown): string | undefined {
|
|
830
|
-
if (typeof value !== "string" || !value) return undefined;
|
|
831
|
-
return compactTextForUpstream(value, MAX_SEARCH_PATH_CHARS);
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
function compactCodeSearchHitsForUpstream(hits: unknown): Array<Record<string, unknown>> | undefined {
|
|
835
|
-
if (!Array.isArray(hits) || hits.length === 0) return undefined;
|
|
836
|
-
return hits.slice(0, MAX_SEARCH_RESULT_ITEMS).flatMap((entry) => {
|
|
837
|
-
if (!entry || typeof entry !== "object") return [];
|
|
838
|
-
const item: Record<string, unknown> = {};
|
|
839
|
-
const path = compactSearchPathForUpstream((entry as any).path);
|
|
840
|
-
if (path) item.path = path;
|
|
841
|
-
if (typeof (entry as any).line === "number") item.line = (entry as any).line;
|
|
842
|
-
if (typeof (entry as any).preview === "string" && (entry as any).preview) {
|
|
843
|
-
item.preview = compactTextForUpstream(
|
|
844
|
-
(entry as any).preview,
|
|
845
|
-
MAX_SEARCH_PREVIEW_CHARS,
|
|
846
|
-
);
|
|
847
|
-
}
|
|
848
|
-
return Object.keys(item).length > 0 ? [item] : [];
|
|
849
|
-
});
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
function compactCodeSearchFilesForUpstream(files: unknown): Array<Record<string, unknown>> | undefined {
|
|
853
|
-
if (!Array.isArray(files) || files.length === 0) return undefined;
|
|
854
|
-
return files.slice(0, MAX_SEARCH_RESULT_ITEMS).flatMap((entry) => {
|
|
855
|
-
if (!entry || typeof entry !== "object") return [];
|
|
856
|
-
const path = compactSearchPathForUpstream((entry as any).path);
|
|
857
|
-
return path ? [{ path }] : [];
|
|
858
|
-
});
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
function compactToolContentForUpstream(
|
|
862
|
-
toolName: string | undefined,
|
|
863
|
-
content: ChatMessage["content"],
|
|
864
|
-
): ChatMessage["content"] {
|
|
865
|
-
if (typeof content !== "string") {
|
|
866
|
-
return normalizeLoopMessageContent(content);
|
|
867
|
-
}
|
|
868
|
-
const normalizedToolName = canonicalizeToolName(toolName ?? "");
|
|
869
|
-
const parsed = parseToolResult(content);
|
|
870
|
-
if (!parsed || typeof parsed !== "object") {
|
|
871
|
-
return content;
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
if (normalizedToolName === "execShell") {
|
|
875
|
-
return JSON.stringify({
|
|
876
|
-
...(typeof parsed.ok === "boolean" ? { ok: parsed.ok } : {}),
|
|
877
|
-
...(typeof parsed.command === "string"
|
|
878
|
-
? {
|
|
879
|
-
command: compactTextForUpstream(
|
|
880
|
-
parsed.command,
|
|
881
|
-
MAX_EXEC_SHELL_COMMAND_CHARS,
|
|
882
|
-
),
|
|
883
|
-
}
|
|
884
|
-
: {}),
|
|
885
|
-
...(typeof parsed.exitCode === "number" ? { exitCode: parsed.exitCode } : {}),
|
|
886
|
-
...(typeof parsed.stdout === "string" && parsed.stdout
|
|
887
|
-
? {
|
|
888
|
-
stdout: compactTextForUpstream(
|
|
889
|
-
parsed.stdout,
|
|
890
|
-
MAX_EXEC_SHELL_STDOUT_CHARS,
|
|
891
|
-
),
|
|
892
|
-
}
|
|
893
|
-
: {}),
|
|
894
|
-
...(typeof parsed.stderr === "string" && parsed.stderr
|
|
895
|
-
? {
|
|
896
|
-
stderr: compactTextForUpstream(
|
|
897
|
-
parsed.stderr,
|
|
898
|
-
MAX_EXEC_SHELL_STDERR_CHARS,
|
|
899
|
-
),
|
|
900
|
-
}
|
|
901
|
-
: {}),
|
|
902
|
-
...(typeof parsed.error === "string" && parsed.error
|
|
903
|
-
? { error: compactTextForUpstream(parsed.error, MAX_EXEC_SHELL_STDERR_CHARS) }
|
|
904
|
-
: {}),
|
|
905
|
-
});
|
|
906
|
-
}
|
|
907
|
-
|
|
908
|
-
if (normalizedToolName === "readFile") {
|
|
909
|
-
return JSON.stringify({
|
|
910
|
-
...(typeof parsed.ok === "boolean" ? { ok: parsed.ok } : {}),
|
|
911
|
-
...(typeof parsed.filePath === "string" ? { filePath: parsed.filePath } : {}),
|
|
912
|
-
...(typeof parsed.lineCount === "number" ? { lineCount: parsed.lineCount } : {}),
|
|
913
|
-
...(typeof parsed.totalLineCount === "number"
|
|
914
|
-
? { totalLineCount: parsed.totalLineCount }
|
|
915
|
-
: {}),
|
|
916
|
-
...(typeof parsed.lineOffset === "number" ? { lineOffset: parsed.lineOffset } : {}),
|
|
917
|
-
...(typeof parsed.rangeStart === "number" ? { rangeStart: parsed.rangeStart } : {}),
|
|
918
|
-
...(typeof parsed.rangeEnd === "number" ? { rangeEnd: parsed.rangeEnd } : {}),
|
|
919
|
-
...(typeof parsed.adjustedEndLine === "number"
|
|
920
|
-
? { adjustedEndLine: parsed.adjustedEndLine }
|
|
921
|
-
: {}),
|
|
922
|
-
...(parsed.nextSymbol && typeof parsed.nextSymbol === "object"
|
|
923
|
-
? { nextSymbol: parsed.nextSymbol }
|
|
924
|
-
: {}),
|
|
925
|
-
...(typeof parsed.content === "string"
|
|
926
|
-
? {
|
|
927
|
-
content: compactTextForUpstream(
|
|
928
|
-
parsed.content,
|
|
929
|
-
MAX_READ_FILE_CONTENT_CHARS,
|
|
930
|
-
),
|
|
931
|
-
}
|
|
932
|
-
: {}),
|
|
933
|
-
...(typeof parsed.error === "string" && parsed.error
|
|
934
|
-
? { error: compactTextForUpstream(parsed.error, MAX_EXEC_SHELL_STDERR_CHARS) }
|
|
935
|
-
: {}),
|
|
936
|
-
});
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
if (normalizedToolName === "readDoc" || normalizedToolName === "readPage") {
|
|
940
|
-
return JSON.stringify({
|
|
941
|
-
...(typeof parsed.success === "boolean" ? { success: parsed.success } : {}),
|
|
942
|
-
...(typeof parsed.id === "string" ? { id: parsed.id } : {}),
|
|
943
|
-
...(typeof parsed.title === "string" ? { title: parsed.title } : {}),
|
|
944
|
-
...(typeof parsed.content === "string"
|
|
945
|
-
? {
|
|
946
|
-
content: compactTextForUpstream(
|
|
947
|
-
parsed.content,
|
|
948
|
-
MAX_READ_DOC_CONTENT_CHARS,
|
|
949
|
-
),
|
|
950
|
-
}
|
|
951
|
-
: {}),
|
|
952
|
-
...(parsed.metadata && typeof parsed.metadata === "object"
|
|
953
|
-
? { metadata: parsed.metadata }
|
|
954
|
-
: {}),
|
|
955
|
-
...(typeof parsed.error === "string" && parsed.error
|
|
956
|
-
? { error: compactTextForUpstream(parsed.error, MAX_EXEC_SHELL_STDERR_CHARS) }
|
|
957
|
-
: {}),
|
|
958
|
-
});
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
if (normalizedToolName === "fetchWebpage") {
|
|
962
|
-
return JSON.stringify({
|
|
963
|
-
...(typeof parsed.preview === "string"
|
|
964
|
-
? {
|
|
965
|
-
preview: compactTextForUpstream(
|
|
966
|
-
parsed.preview,
|
|
967
|
-
MAX_SEARCH_PREVIEW_CHARS,
|
|
968
|
-
),
|
|
969
|
-
}
|
|
970
|
-
: {}),
|
|
971
|
-
...(typeof parsed.fullContent === "string"
|
|
972
|
-
? {
|
|
973
|
-
fullContent: compactTextForUpstream(
|
|
974
|
-
parsed.fullContent,
|
|
975
|
-
MAX_FETCH_WEBPAGE_CONTENT_CHARS,
|
|
976
|
-
),
|
|
977
|
-
}
|
|
978
|
-
: {}),
|
|
979
|
-
...(typeof parsed.rawData === "string"
|
|
980
|
-
? {
|
|
981
|
-
rawData: compactTextForUpstream(
|
|
982
|
-
parsed.rawData,
|
|
983
|
-
MAX_FETCH_WEBPAGE_CONTENT_CHARS,
|
|
984
|
-
),
|
|
985
|
-
}
|
|
986
|
-
: {}),
|
|
987
|
-
...(typeof parsed.displayData === "string"
|
|
988
|
-
? {
|
|
989
|
-
displayData: compactTextForUpstream(
|
|
990
|
-
parsed.displayData,
|
|
991
|
-
MAX_FETCH_WEBPAGE_CONTENT_CHARS,
|
|
992
|
-
),
|
|
993
|
-
}
|
|
994
|
-
: {}),
|
|
995
|
-
...(typeof parsed.contentType === "string" ? { contentType: parsed.contentType } : {}),
|
|
996
|
-
...(typeof parsed.markdownTokens === "string" || typeof parsed.markdownTokens === "number"
|
|
997
|
-
? { markdownTokens: parsed.markdownTokens }
|
|
998
|
-
: {}),
|
|
999
|
-
...(typeof parsed.error === "string" && parsed.error
|
|
1000
|
-
? { error: compactTextForUpstream(parsed.error, MAX_EXEC_SHELL_STDERR_CHARS) }
|
|
1001
|
-
: {}),
|
|
1002
|
-
});
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
if (normalizedToolName === "openAIGptImage") {
|
|
1006
|
-
const files = Array.isArray(parsed.files)
|
|
1007
|
-
? parsed.files.flatMap((entry) => {
|
|
1008
|
-
if (!entry || typeof entry !== "object") return [];
|
|
1009
|
-
return [{
|
|
1010
|
-
...(
|
|
1011
|
-
typeof (entry as any).fileId === "string"
|
|
1012
|
-
? { fileId: (entry as any).fileId }
|
|
1013
|
-
: {}
|
|
1014
|
-
),
|
|
1015
|
-
...(
|
|
1016
|
-
(entry as any).metadata && typeof (entry as any).metadata === "object"
|
|
1017
|
-
? { metadata: (entry as any).metadata }
|
|
1018
|
-
: {}
|
|
1019
|
-
),
|
|
1020
|
-
}];
|
|
1021
|
-
})
|
|
1022
|
-
: undefined;
|
|
1023
|
-
|
|
1024
|
-
return JSON.stringify({
|
|
1025
|
-
...(typeof parsed.text === "string"
|
|
1026
|
-
? { text: compactTextForUpstream(parsed.text, MAX_IMAGE_TOOL_TEXT_CHARS) }
|
|
1027
|
-
: {}),
|
|
1028
|
-
...(typeof parsed.imageCount === "number" ? { imageCount: parsed.imageCount } : {}),
|
|
1029
|
-
...(Array.isArray(parsed.revisedPrompts)
|
|
1030
|
-
? {
|
|
1031
|
-
revisedPrompts: parsed.revisedPrompts
|
|
1032
|
-
.filter((item: unknown): item is string => typeof item === "string" && !!item)
|
|
1033
|
-
.map((item: string) => compactTextForUpstream(item, MAX_IMAGE_TOOL_TEXT_CHARS)),
|
|
1034
|
-
}
|
|
1035
|
-
: {}),
|
|
1036
|
-
...(files ? { files } : {}),
|
|
1037
|
-
...(typeof parsed.error === "string" && parsed.error
|
|
1038
|
-
? { error: compactTextForUpstream(parsed.error, MAX_EXEC_SHELL_STDERR_CHARS) }
|
|
1039
|
-
: {}),
|
|
1040
|
-
});
|
|
1041
|
-
}
|
|
1042
|
-
|
|
1043
|
-
if (normalizedToolName === "codeSearch") {
|
|
1044
|
-
return JSON.stringify({
|
|
1045
|
-
...(typeof parsed.ok === "boolean" ? { ok: parsed.ok } : {}),
|
|
1046
|
-
...(typeof parsed.mode === "string" ? { mode: parsed.mode } : {}),
|
|
1047
|
-
...(typeof parsed.query === "string" ? { query: parsed.query } : {}),
|
|
1048
|
-
...(typeof parsed.path === "string" ? { path: parsed.path } : {}),
|
|
1049
|
-
...(typeof parsed.glob === "string" || parsed.glob === null
|
|
1050
|
-
? { glob: parsed.glob }
|
|
1051
|
-
: {}),
|
|
1052
|
-
...(typeof parsed.truncated === "boolean" ? { truncated: parsed.truncated } : {}),
|
|
1053
|
-
...(typeof parsed.totalHits === "number" ? { totalHits: parsed.totalHits } : {}),
|
|
1054
|
-
...(typeof parsed.totalFiles === "number" ? { totalFiles: parsed.totalFiles } : {}),
|
|
1055
|
-
...(compactCodeSearchHitsForUpstream(parsed.hits)
|
|
1056
|
-
? { hits: compactCodeSearchHitsForUpstream(parsed.hits) }
|
|
1057
|
-
: {}),
|
|
1058
|
-
...(compactCodeSearchFilesForUpstream(parsed.files)
|
|
1059
|
-
? { files: compactCodeSearchFilesForUpstream(parsed.files) }
|
|
1060
|
-
: {}),
|
|
1061
|
-
...(typeof parsed.error === "string" && parsed.error
|
|
1062
|
-
? { error: compactTextForUpstream(parsed.error, MAX_EXEC_SHELL_STDERR_CHARS) }
|
|
1063
|
-
: {}),
|
|
1064
|
-
});
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
return content;
|
|
1068
|
-
}
|
|
1069
|
-
|
|
1070
|
-
function shouldCompactImmediateToolReplay(toolName: string | undefined): boolean {
|
|
1071
|
-
const normalizedToolName = canonicalizeToolName(toolName ?? "");
|
|
1072
|
-
return (
|
|
1073
|
-
normalizedToolName === "execShell" ||
|
|
1074
|
-
normalizedToolName === "openAIGptImage"
|
|
1075
|
-
);
|
|
1076
|
-
}
|
|
1077
|
-
|
|
1078
|
-
function sanitizeLoopMessageForUpstream(message: ChatMessage): ChatMessage {
|
|
1079
|
-
const sanitized: ChatMessage = {
|
|
1080
|
-
role: message.role,
|
|
1081
|
-
content: normalizeLoopMessageContent(message.content),
|
|
1082
|
-
};
|
|
1083
|
-
|
|
1084
|
-
if (
|
|
1085
|
-
message.role === "assistant" &&
|
|
1086
|
-
typeof message.reasoning_content === "string" &&
|
|
1087
|
-
message.reasoning_content
|
|
1088
|
-
) {
|
|
1089
|
-
sanitized.reasoning_content = message.reasoning_content;
|
|
1090
|
-
}
|
|
1091
|
-
|
|
1092
|
-
if (
|
|
1093
|
-
message.role === "assistant" &&
|
|
1094
|
-
Array.isArray(message.tool_calls) &&
|
|
1095
|
-
message.tool_calls.length > 0
|
|
1096
|
-
) {
|
|
1097
|
-
sanitized.tool_calls = message.tool_calls;
|
|
1098
|
-
}
|
|
1099
|
-
|
|
1100
|
-
if (
|
|
1101
|
-
message.role === "tool" &&
|
|
1102
|
-
typeof message.tool_call_id === "string" &&
|
|
1103
|
-
message.tool_call_id.trim()
|
|
1104
|
-
) {
|
|
1105
|
-
sanitized.tool_call_id = message.tool_call_id.trim();
|
|
1106
|
-
}
|
|
1107
|
-
|
|
1108
|
-
return sanitized;
|
|
1109
|
-
}
|
|
1110
|
-
|
|
1111
|
-
function sanitizeLoopMessagesForUpstream(messages: ChatMessage[]): ChatMessage[] {
|
|
1112
|
-
const toolNameByCallId = new Map<string, string>();
|
|
1113
|
-
let firstTrailingToolIndex = messages.length;
|
|
1114
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1115
|
-
if (messages[index]?.role !== "tool") {
|
|
1116
|
-
break;
|
|
1117
|
-
}
|
|
1118
|
-
firstTrailingToolIndex = index;
|
|
1119
|
-
}
|
|
1120
|
-
return messages.map((message, index) => {
|
|
1121
|
-
const sanitized = sanitizeLoopMessageForUpstream(message);
|
|
1122
|
-
|
|
1123
|
-
if (
|
|
1124
|
-
message.role === "assistant" &&
|
|
1125
|
-
Array.isArray(message.tool_calls) &&
|
|
1126
|
-
message.tool_calls.length > 0
|
|
1127
|
-
) {
|
|
1128
|
-
for (const toolCall of message.tool_calls) {
|
|
1129
|
-
if (
|
|
1130
|
-
typeof toolCall?.id === "string" &&
|
|
1131
|
-
toolCall.id.trim() &&
|
|
1132
|
-
typeof toolCall?.function?.name === "string"
|
|
1133
|
-
) {
|
|
1134
|
-
toolNameByCallId.set(toolCall.id.trim(), toolCall.function.name);
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
1137
|
-
sanitized.content = null;
|
|
1138
|
-
return sanitized;
|
|
1139
|
-
}
|
|
1140
|
-
|
|
1141
|
-
if (
|
|
1142
|
-
message.role === "tool" &&
|
|
1143
|
-
typeof sanitized.tool_call_id === "string" &&
|
|
1144
|
-
sanitized.tool_call_id
|
|
1145
|
-
) {
|
|
1146
|
-
const toolName = toolNameByCallId.get(sanitized.tool_call_id);
|
|
1147
|
-
const shouldCompactImmediately = shouldCompactImmediateToolReplay(toolName);
|
|
1148
|
-
const isTrailingToolMessage = index >= firstTrailingToolIndex;
|
|
1149
|
-
sanitized.content =
|
|
1150
|
-
isTrailingToolMessage && !shouldCompactImmediately
|
|
1151
|
-
? normalizeLoopMessageContent(message.content)
|
|
1152
|
-
: compactToolContentForUpstream(toolName, sanitized.content);
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
return sanitized;
|
|
1156
|
-
});
|
|
1157
|
-
}
|
|
1158
|
-
|
|
1159
|
-
function collectLatestImageUrls(messages: ChatMessage[]): string[] {
|
|
1160
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1161
|
-
const content = messages[index]?.content;
|
|
1162
|
-
if (!Array.isArray(content)) continue;
|
|
1163
|
-
|
|
1164
|
-
const urls = content
|
|
1165
|
-
.map((part) =>
|
|
1166
|
-
part?.type === "image_url" && typeof part.image_url?.url === "string"
|
|
1167
|
-
? part.image_url.url.trim()
|
|
1168
|
-
: ""
|
|
1169
|
-
)
|
|
1170
|
-
.filter((url): url is string => !!url);
|
|
1171
|
-
|
|
1172
|
-
if (urls.length > 0) {
|
|
1173
|
-
return [...new Set(urls)];
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
return [];
|
|
1178
|
-
}
|
|
1179
|
-
|
|
1180
|
-
function getApiKey(agentConfig: any): string | undefined {
|
|
1181
|
-
// apiSource="custom" 的 agent 使用自己的 apiKey,不走平台 key。
|
|
1182
|
-
// 使用自己的 apiKey,不走平台 key,不要修改这个逻辑
|
|
1183
|
-
const key = agentConfig.apiKey?.trim() || getNoloKey(agentConfig.provider);
|
|
1184
|
-
// 自定义 provider URL 场景(如本地 Ollama)不强制要求 key
|
|
1185
|
-
const hasCustomUrl = !!(agentConfig.customProviderUrl?.trim());
|
|
1186
|
-
if (!key && !hasCustomUrl) {
|
|
1187
|
-
throw new Error(`No API key configured for provider "${agentConfig.provider}".`);
|
|
1188
|
-
}
|
|
1189
|
-
return key || undefined;
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
function buildTools(agentConfig: any): any[] | undefined {
|
|
1193
|
-
if (!agentConfig.tools?.length) return undefined;
|
|
1194
|
-
const tools = prepareTools(agentConfig.tools, {
|
|
1195
|
-
provider: agentConfig.provider,
|
|
1196
|
-
disabledToolNames: process.env.EXA_API_KEY ? [] : ["exa_search"],
|
|
1197
|
-
});
|
|
1198
|
-
return tools.length > 0 ? tools : undefined;
|
|
1199
|
-
}
|
|
1200
|
-
|
|
1201
|
-
function getPreparedToolNames(tools: any[] | undefined): string[] {
|
|
1202
|
-
if (!tools?.length) return [];
|
|
1203
|
-
return tools
|
|
1204
|
-
.map((tool) => tool?.function?.name ?? tool?.name)
|
|
1205
|
-
.filter((name): name is string => typeof name === "string" && !!name.trim());
|
|
1206
|
-
}
|
|
1207
|
-
|
|
1208
|
-
function extractMessageContentText(content: ChatMessage["content"] | undefined | null): string {
|
|
1209
|
-
if (typeof content === "string") return content;
|
|
1210
|
-
if (!Array.isArray(content)) return "";
|
|
1211
|
-
return content
|
|
1212
|
-
.filter((part: any) => part?.type === "text" && typeof part.text === "string")
|
|
1213
|
-
.map((part: any) => part.text)
|
|
1214
|
-
.join("\n");
|
|
1215
|
-
}
|
|
1216
|
-
|
|
1217
|
-
function extractUserInputText(
|
|
1218
|
-
userInput: string | null | undefined,
|
|
1219
|
-
messages: ChatMessage[],
|
|
1220
|
-
): string {
|
|
1221
|
-
if (typeof userInput === "string" && userInput.trim()) return userInput;
|
|
1222
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1223
|
-
const message = messages[index];
|
|
1224
|
-
if (message?.role !== "user") continue;
|
|
1225
|
-
const text = extractMessageContentText(message.content);
|
|
1226
|
-
if (text.trim()) return text;
|
|
1227
|
-
}
|
|
1228
|
-
return "";
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
function shouldRunWereadGatewayPreflight(
|
|
1232
|
-
agentConfig: any,
|
|
1233
|
-
tools: any[] | undefined,
|
|
1234
|
-
userInput: string | null | undefined,
|
|
1235
|
-
messages: ChatMessage[],
|
|
1236
|
-
): boolean {
|
|
1237
|
-
const hasWereadTool =
|
|
1238
|
-
Array.isArray(agentConfig?.tools) &&
|
|
1239
|
-
agentConfig.tools.some((toolName: unknown) => canonicalizeToolName(String(toolName)) === "wereadGateway") &&
|
|
1240
|
-
getPreparedToolNames(tools).some((toolName) => canonicalizeToolName(toolName) === "wereadGateway");
|
|
1241
|
-
if (!hasWereadTool) return false;
|
|
1242
|
-
|
|
1243
|
-
const text = extractUserInputText(userInput, messages).trim();
|
|
1244
|
-
if (!text) return false;
|
|
1245
|
-
return /微信读书|weread|WEREAD|书架|阅读|读书|笔记|划线|想法|书评|报告|统计|进度|搜索|推荐|key|Key|KEY|密钥|授权|连接|连通|链接|配置|保存|添加|测试|检查|验证/.test(text);
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
async function runWereadGatewayPreflightIfNeeded(args: {
|
|
1249
|
-
agentConfig: any;
|
|
1250
|
-
tools: any[] | undefined;
|
|
1251
|
-
messages: ChatMessage[];
|
|
1252
|
-
serverBase: string;
|
|
1253
|
-
authToken: string;
|
|
1254
|
-
runtimePolicy?: ResolvedRuntimePolicy;
|
|
1255
|
-
runtimeState: ToolPolicyRuntimeState;
|
|
1256
|
-
userId?: string | null;
|
|
1257
|
-
dialogId?: string | null;
|
|
1258
|
-
currentSpaceId?: string | null;
|
|
1259
|
-
userInput?: string | null;
|
|
1260
|
-
runtimeContext?: AgentRunRuntimeContext | null;
|
|
1261
|
-
send?: Send;
|
|
1262
|
-
}): Promise<{ ran: boolean; elapsedMs: number; completedAt?: number }> {
|
|
1263
|
-
if (
|
|
1264
|
-
!shouldRunWereadGatewayPreflight(
|
|
1265
|
-
args.agentConfig,
|
|
1266
|
-
args.tools,
|
|
1267
|
-
args.userInput,
|
|
1268
|
-
args.messages,
|
|
1269
|
-
)
|
|
1270
|
-
) {
|
|
1271
|
-
return { ran: false, elapsedMs: 0 };
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
const toolCall: AssistantToolCall = {
|
|
1275
|
-
id: `call_weread_preflight_${Date.now()}`,
|
|
1276
|
-
type: "function",
|
|
1277
|
-
function: {
|
|
1278
|
-
name: "wereadGateway",
|
|
1279
|
-
arguments: JSON.stringify({ api_name: "/shelf/sync", params: {} }),
|
|
1280
|
-
},
|
|
1281
|
-
};
|
|
1282
|
-
args.messages.push({
|
|
1283
|
-
role: "assistant",
|
|
1284
|
-
content: null,
|
|
1285
|
-
tool_calls: [toolCall],
|
|
1286
|
-
});
|
|
1287
|
-
args.send?.({
|
|
1288
|
-
type: "assistant_tool_calls",
|
|
1289
|
-
content: null,
|
|
1290
|
-
tool_calls: [toolCall],
|
|
1291
|
-
});
|
|
1292
|
-
args.send?.({ type: "tool_start", calls: ["wereadGateway"] });
|
|
1293
|
-
|
|
1294
|
-
const startedAt = Date.now();
|
|
1295
|
-
const toolResult = await executeToolOnServer(
|
|
1296
|
-
toolCall,
|
|
1297
|
-
args.serverBase,
|
|
1298
|
-
args.authToken,
|
|
1299
|
-
buildLoopToolExecutionOptions({
|
|
1300
|
-
agentConfig: args.agentConfig,
|
|
1301
|
-
messages: args.messages,
|
|
1302
|
-
runtimePolicy: args.runtimePolicy,
|
|
1303
|
-
runtimeState: args.runtimeState,
|
|
1304
|
-
userId: args.userId,
|
|
1305
|
-
dialogId: args.dialogId,
|
|
1306
|
-
currentSpaceId: args.currentSpaceId,
|
|
1307
|
-
userInput: args.userInput,
|
|
1308
|
-
runtimeContext: args.runtimeContext,
|
|
1309
|
-
}),
|
|
1310
|
-
);
|
|
1311
|
-
const completedAt = Date.now();
|
|
1312
|
-
args.messages.push({
|
|
1313
|
-
role: "tool",
|
|
1314
|
-
tool_call_id: toolCall.id,
|
|
1315
|
-
content: toolResult,
|
|
1316
|
-
});
|
|
1317
|
-
args.messages.push({
|
|
1318
|
-
role: "system",
|
|
1319
|
-
content:
|
|
1320
|
-
"上面的 wereadGateway 是本轮服务端预检得到的真实结果。请基于该结果回答用户;不要声称 wereadGateway 未挂载、不可用或无法调用。若结果包含 MISSING_WEREAD_API_KEY 或缺少 WEREAD_API_KEY,请提示用户去密钥管理保存 WEREAD_API_KEY。",
|
|
1321
|
-
});
|
|
1322
|
-
args.send?.({
|
|
1323
|
-
type: "tool_result",
|
|
1324
|
-
toolCallId: toolCall.id,
|
|
1325
|
-
toolName: "wereadGateway",
|
|
1326
|
-
content: toolResult,
|
|
1327
|
-
});
|
|
1328
|
-
args.send?.({ type: "tool_end" });
|
|
1329
|
-
|
|
1330
|
-
return {
|
|
1331
|
-
ran: true,
|
|
1332
|
-
elapsedMs: Math.max(0, completedAt - startedAt),
|
|
1333
|
-
completedAt,
|
|
1334
|
-
};
|
|
1335
|
-
}
|
|
1336
|
-
|
|
1337
|
-
function buildLoopRequestBody(
|
|
1338
|
-
agentConfig: any,
|
|
1339
|
-
messages: ChatMessage[],
|
|
1340
|
-
tools: any[] | undefined,
|
|
1341
|
-
stream: boolean,
|
|
1342
|
-
): Record<string, any> {
|
|
1343
|
-
const upstreamMessages = sanitizeLoopMessagesForUpstream(messages);
|
|
1344
|
-
// Keep agent-run aligned with the foreground chat path so image-output agents
|
|
1345
|
-
// inherit the same modalities/image_config contract instead of silently
|
|
1346
|
-
// degrading to plain text.
|
|
1347
|
-
const body: Record<string, any> = generateRequestBody({
|
|
1348
|
-
agentConfig,
|
|
1349
|
-
messages: upstreamMessages as any,
|
|
1350
|
-
prependSystemPrompt: !agentConfig?.runtimePromptAlreadyInMessages,
|
|
1351
|
-
});
|
|
1352
|
-
applyLoopStreamMode(body, stream);
|
|
1353
|
-
if (isResponseAPIModel(agentConfig)) {
|
|
1354
|
-
const responseTools = [
|
|
1355
|
-
...(toResponsesTools(tools) ?? []),
|
|
1356
|
-
...(
|
|
1357
|
-
String(agentConfig?.provider || "").toLowerCase() === "openai" &&
|
|
1358
|
-
!getModelInfo(String(agentConfig?.model || ""))?.hasImageOutput &&
|
|
1359
|
-
!!agentConfig?.imageConfig?.enabled
|
|
1360
|
-
? [{ type: "image_generation" as const }]
|
|
1361
|
-
: []
|
|
1362
|
-
),
|
|
1363
|
-
];
|
|
1364
|
-
if (responseTools.length) {
|
|
1365
|
-
body.tools = responseTools;
|
|
1366
|
-
body.tool_choice = "auto";
|
|
1367
|
-
}
|
|
1368
|
-
return body;
|
|
1369
|
-
}
|
|
1370
|
-
if (tools) {
|
|
1371
|
-
body.tools = tools;
|
|
1372
|
-
body.tool_choice = "auto";
|
|
1373
|
-
}
|
|
1374
|
-
if (agentConfig.enableThinking) {
|
|
1375
|
-
const provider = (agentConfig.provider || "").toLowerCase();
|
|
1376
|
-
if (provider === "anthropic") {
|
|
1377
|
-
body.thinking = { type: "enabled", budget_tokens: agentConfig.thinkingBudget ?? 8000 };
|
|
1378
|
-
}
|
|
1379
|
-
} else if (
|
|
1380
|
-
/xiaomimimo\.com/i.test(agentConfig.customProviderUrl ?? "") ||
|
|
1381
|
-
String(agentConfig?.provider || "").toLowerCase() === "mimo"
|
|
1382
|
-
) {
|
|
1383
|
-
body.thinking = { type: "disabled" };
|
|
1384
|
-
}
|
|
1385
|
-
return body;
|
|
1386
|
-
}
|
|
1387
|
-
|
|
1388
|
-
export function applyLoopStreamMode(body: Record<string, any>, stream: boolean) {
|
|
1389
|
-
body.stream = stream;
|
|
1390
|
-
if (!stream) {
|
|
1391
|
-
delete body.stream_options;
|
|
1392
|
-
}
|
|
1393
|
-
return body;
|
|
1394
|
-
}
|
|
1395
|
-
|
|
1396
|
-
function addNumericUsageField(
|
|
1397
|
-
target: Record<string, any>,
|
|
1398
|
-
field: string,
|
|
1399
|
-
next: Record<string, any>,
|
|
1400
|
-
) {
|
|
1401
|
-
if (typeof next[field] !== "number" || !Number.isFinite(next[field])) return;
|
|
1402
|
-
target[field] = (typeof target[field] === "number" && Number.isFinite(target[field]) ? target[field] : 0) + next[field];
|
|
1403
|
-
}
|
|
1404
|
-
|
|
1405
|
-
function uniqueStringList(...values: unknown[]): string[] {
|
|
1406
|
-
return Array.from(
|
|
1407
|
-
new Set(
|
|
1408
|
-
values
|
|
1409
|
-
.flatMap((value) => Array.isArray(value) ? value : [value])
|
|
1410
|
-
.filter((item): item is string => typeof item === "string")
|
|
1411
|
-
.map((item) => item.trim())
|
|
1412
|
-
.filter(Boolean)
|
|
1413
|
-
)
|
|
1414
|
-
);
|
|
1415
|
-
}
|
|
1416
|
-
|
|
1417
|
-
function addStringListUsageField(
|
|
1418
|
-
target: Record<string, any>,
|
|
1419
|
-
field: string,
|
|
1420
|
-
next: Record<string, any>,
|
|
1421
|
-
) {
|
|
1422
|
-
const merged = uniqueStringList(target[field], next[field]);
|
|
1423
|
-
if (merged.length > 0) target[field] = merged;
|
|
1424
|
-
}
|
|
1425
|
-
|
|
1426
|
-
function buildProviderAuditUsageMetadata(
|
|
1427
|
-
response?: Response | null,
|
|
1428
|
-
payload?: any,
|
|
1429
|
-
): Record<string, any> | undefined {
|
|
1430
|
-
const providerRequestIds = uniqueStringList(
|
|
1431
|
-
response?.headers.get("x-request-id"),
|
|
1432
|
-
response?.headers.get("x-openai-request-id"),
|
|
1433
|
-
response?.headers.get("openai-request-id"),
|
|
1434
|
-
response?.headers.get("cf-ray"),
|
|
1435
|
-
);
|
|
1436
|
-
const providerResponseIds = uniqueStringList(
|
|
1437
|
-
typeof payload?.id === "string" ? payload.id : undefined,
|
|
1438
|
-
typeof payload?.response?.id === "string" ? payload.response.id : undefined,
|
|
1439
|
-
);
|
|
1440
|
-
if (providerRequestIds.length === 0 && providerResponseIds.length === 0) {
|
|
1441
|
-
return undefined;
|
|
1442
|
-
}
|
|
1443
|
-
return {
|
|
1444
|
-
...(providerRequestIds.length > 0 ? { provider_request_ids: providerRequestIds } : {}),
|
|
1445
|
-
...(providerResponseIds.length > 0 ? { provider_response_ids: providerResponseIds } : {}),
|
|
1446
|
-
};
|
|
1447
|
-
}
|
|
1448
|
-
|
|
1449
|
-
function addUsageTotal(
|
|
1450
|
-
current: Record<string, any> | undefined | null,
|
|
1451
|
-
next: Record<string, any> | undefined | null,
|
|
1452
|
-
): Record<string, any> | undefined {
|
|
1453
|
-
if (!next || typeof next !== "object") return current ?? undefined;
|
|
1454
|
-
if (!current || typeof current !== "object") return { ...next };
|
|
1455
|
-
|
|
1456
|
-
const merged: Record<string, any> = { ...current };
|
|
1457
|
-
for (const field of [
|
|
1458
|
-
"prompt_tokens",
|
|
1459
|
-
"completion_tokens",
|
|
1460
|
-
"total_tokens",
|
|
1461
|
-
"input_tokens",
|
|
1462
|
-
"output_tokens",
|
|
1463
|
-
"cache_creation_input_tokens",
|
|
1464
|
-
"cache_read_input_tokens",
|
|
1465
|
-
"prompt_cache_hit_tokens",
|
|
1466
|
-
"prompt_cache_miss_tokens",
|
|
1467
|
-
"cost",
|
|
1468
|
-
]) {
|
|
1469
|
-
addNumericUsageField(merged, field, next);
|
|
1470
|
-
}
|
|
1471
|
-
for (const field of ["provider_response_ids", "provider_request_ids"]) {
|
|
1472
|
-
addStringListUsageField(merged, field, next);
|
|
1473
|
-
}
|
|
1474
|
-
|
|
1475
|
-
for (const [key, value] of Object.entries(next)) {
|
|
1476
|
-
if (
|
|
1477
|
-
!(key in merged) &&
|
|
1478
|
-
typeof value !== "number" &&
|
|
1479
|
-
!["provider_response_ids", "provider_request_ids"].includes(key)
|
|
1480
|
-
) {
|
|
1481
|
-
merged[key] = value;
|
|
1482
|
-
}
|
|
1483
|
-
}
|
|
1484
|
-
return merged;
|
|
1485
|
-
}
|
|
1486
|
-
|
|
1487
|
-
function mergeUsageSnapshot(
|
|
1488
|
-
current: Record<string, any> | undefined | null,
|
|
1489
|
-
next: Record<string, any> | undefined | null,
|
|
1490
|
-
): Record<string, any> | undefined {
|
|
1491
|
-
if (!next || typeof next !== "object") return current ?? undefined;
|
|
1492
|
-
const merged: Record<string, any> =
|
|
1493
|
-
current && typeof current === "object" ? { ...current, ...next } : { ...next };
|
|
1494
|
-
for (const field of ["provider_response_ids", "provider_request_ids"]) {
|
|
1495
|
-
const values = uniqueStringList(
|
|
1496
|
-
current && typeof current === "object" ? current[field] : undefined,
|
|
1497
|
-
next[field],
|
|
1498
|
-
);
|
|
1499
|
-
if (values.length > 0) merged[field] = values;
|
|
1500
|
-
}
|
|
1501
|
-
return merged;
|
|
1502
|
-
}
|
|
1503
|
-
|
|
1504
|
-
function buildAssistantMessageFromResponse(data: any): ChatMessage | null {
|
|
1505
|
-
const toolCalls = extractToolCallsFromResponseOutput(data);
|
|
1506
|
-
const contentText = extractTextFromResponseOutput(data);
|
|
1507
|
-
const contentImages = extractImagePartsFromResponseOutput(data);
|
|
1508
|
-
const content =
|
|
1509
|
-
contentImages.length > 0
|
|
1510
|
-
? [
|
|
1511
|
-
...(contentText ? [{ type: "text", text: contentText }] : []),
|
|
1512
|
-
...contentImages,
|
|
1513
|
-
]
|
|
1514
|
-
: contentText;
|
|
1515
|
-
if (!content && toolCalls.length === 0) return null;
|
|
1516
|
-
|
|
1517
|
-
return {
|
|
1518
|
-
role: "assistant",
|
|
1519
|
-
content: content || null,
|
|
1520
|
-
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
1521
|
-
};
|
|
1522
|
-
}
|
|
1523
|
-
|
|
1524
|
-
function extractTextFromResponseOutputItem(item: any): string {
|
|
1525
|
-
if (item?.type !== "message" || !Array.isArray(item.content)) return "";
|
|
1526
|
-
return item.content
|
|
1527
|
-
.filter((content: any) => content?.type === "output_text" && typeof content.text === "string")
|
|
1528
|
-
.map((content: any) => content.text)
|
|
1529
|
-
.join("");
|
|
1530
|
-
}
|
|
1531
|
-
|
|
1532
|
-
function buildLatencyProfile(args: {
|
|
1533
|
-
startedAt: number;
|
|
1534
|
-
llmRequestCount: number;
|
|
1535
|
-
llmWaitMs: number;
|
|
1536
|
-
llmJsonParseMs: number;
|
|
1537
|
-
toolExecutionMs: number;
|
|
1538
|
-
firstAssistantAt?: number;
|
|
1539
|
-
firstToolResultAt?: number;
|
|
1540
|
-
}) {
|
|
1541
|
-
const endedAt = Date.now();
|
|
1542
|
-
return {
|
|
1543
|
-
totalMs: Math.max(0, endedAt - args.startedAt),
|
|
1544
|
-
llmRequestCount: args.llmRequestCount,
|
|
1545
|
-
llmWaitMs: args.llmWaitMs,
|
|
1546
|
-
llmJsonParseMs: args.llmJsonParseMs,
|
|
1547
|
-
toolExecutionMs: args.toolExecutionMs,
|
|
1548
|
-
...(typeof args.firstAssistantAt === "number"
|
|
1549
|
-
? { timeToFirstAssistantMs: Math.max(0, args.firstAssistantAt - args.startedAt) }
|
|
1550
|
-
: {}),
|
|
1551
|
-
...(typeof args.firstToolResultAt === "number"
|
|
1552
|
-
? { timeToFirstToolResultMs: Math.max(0, args.firstToolResultAt - args.startedAt) }
|
|
1553
|
-
: {}),
|
|
1554
|
-
endedAt,
|
|
1555
|
-
};
|
|
1556
|
-
}
|
|
1557
|
-
|
|
1558
|
-
function buildLoopCompletion(args: {
|
|
1559
|
-
content: string;
|
|
1560
|
-
model: string;
|
|
1561
|
-
provider?: string;
|
|
1562
|
-
inputPrice?: number;
|
|
1563
|
-
outputPrice?: number;
|
|
1564
|
-
usage?: Record<string, any>;
|
|
1565
|
-
trace: ChatMessage[];
|
|
1566
|
-
runtimeToolNames: string[];
|
|
1567
|
-
toolCallCount: number;
|
|
1568
|
-
runtimePolicy?: ResolvedRuntimePolicy;
|
|
1569
|
-
runtimeState: ToolPolicyRuntimeState;
|
|
1570
|
-
startedAt: number;
|
|
1571
|
-
llmRequestCount: number;
|
|
1572
|
-
llmWaitMs: number;
|
|
1573
|
-
llmJsonParseMs: number;
|
|
1574
|
-
toolExecutionMs: number;
|
|
1575
|
-
firstAssistantAt?: number;
|
|
1576
|
-
firstToolResultAt?: number;
|
|
1577
|
-
providerCallIds?: string[];
|
|
1578
|
-
}): LoopResult {
|
|
1579
|
-
return {
|
|
1580
|
-
content: args.content,
|
|
1581
|
-
model: args.model,
|
|
1582
|
-
provider: args.provider,
|
|
1583
|
-
inputPrice: args.inputPrice,
|
|
1584
|
-
outputPrice: args.outputPrice,
|
|
1585
|
-
usage: args.usage,
|
|
1586
|
-
...(args.providerCallIds && args.providerCallIds.length > 0
|
|
1587
|
-
? { providerCallIds: [...args.providerCallIds] }
|
|
1588
|
-
: {}),
|
|
1589
|
-
trace: args.trace,
|
|
1590
|
-
runtimeToolNames: args.runtimeToolNames,
|
|
1591
|
-
toolCallCount: args.toolCallCount,
|
|
1592
|
-
policyState: {
|
|
1593
|
-
autoKnowledgeCaptureCount:
|
|
1594
|
-
(args.runtimePolicy?.knowledgeCapture.currentAutoCreates ?? 0) +
|
|
1595
|
-
args.runtimeState.autoKnowledgeCaptureCountThisRun,
|
|
1596
|
-
autoSpaceReadCount:
|
|
1597
|
-
(args.runtimePolicy?.spaceContext.currentAutoReads ?? 0) +
|
|
1598
|
-
args.runtimeState.autoSpaceReadCountThisRun,
|
|
1599
|
-
updatedAt: Date.now(),
|
|
1600
|
-
},
|
|
1601
|
-
latencyProfile: buildLatencyProfile({
|
|
1602
|
-
startedAt: args.startedAt,
|
|
1603
|
-
llmRequestCount: args.llmRequestCount,
|
|
1604
|
-
llmWaitMs: args.llmWaitMs,
|
|
1605
|
-
llmJsonParseMs: args.llmJsonParseMs,
|
|
1606
|
-
toolExecutionMs: args.toolExecutionMs,
|
|
1607
|
-
firstAssistantAt: args.firstAssistantAt,
|
|
1608
|
-
firstToolResultAt: args.firstToolResultAt,
|
|
1609
|
-
}),
|
|
1610
|
-
};
|
|
1611
|
-
}
|
|
1612
|
-
|
|
1613
|
-
function buildStreamDoneEvent(args: {
|
|
1614
|
-
usage?: Record<string, any>;
|
|
1615
|
-
provider?: string;
|
|
1616
|
-
model?: string;
|
|
1617
|
-
inputPrice?: number;
|
|
1618
|
-
outputPrice?: number;
|
|
1619
|
-
elapsed?: number;
|
|
1620
|
-
providerCallIds?: string[];
|
|
1621
|
-
}) {
|
|
1622
|
-
return {
|
|
1623
|
-
type: "done" as const,
|
|
1624
|
-
...(args.usage ? { usage: args.usage } : {}),
|
|
1625
|
-
...(args.provider ? { provider: args.provider } : {}),
|
|
1626
|
-
...(args.model ? { model: args.model } : {}),
|
|
1627
|
-
...(typeof args.inputPrice === "number" ? { inputPrice: args.inputPrice } : {}),
|
|
1628
|
-
...(typeof args.outputPrice === "number" ? { outputPrice: args.outputPrice } : {}),
|
|
1629
|
-
...(typeof args.elapsed === "number" ? { elapsed: args.elapsed } : {}),
|
|
1630
|
-
...(args.providerCallIds?.length ? { providerCallIds: [...args.providerCallIds] } : {}),
|
|
1631
|
-
};
|
|
1632
|
-
}
|
|
1633
|
-
|
|
1634
|
-
function buildRepairRequestMessages(args: {
|
|
1635
|
-
messages: ChatMessage[];
|
|
1636
|
-
finalParallelSummaryRepairPending: boolean;
|
|
1637
|
-
emptyAssistantRepairPending: boolean;
|
|
1638
|
-
}): ChatMessage[] {
|
|
1639
|
-
if (args.finalParallelSummaryRepairPending) {
|
|
1640
|
-
return [
|
|
1641
|
-
...args.messages,
|
|
1642
|
-
{ role: "system", content: FINAL_PARALLEL_SUMMARY_REPAIR_PROMPT } satisfies ChatMessage,
|
|
1643
|
-
];
|
|
1644
|
-
}
|
|
1645
|
-
if (args.emptyAssistantRepairPending) {
|
|
1646
|
-
return [
|
|
1647
|
-
...args.messages,
|
|
1648
|
-
{ role: "system", content: EMPTY_ASSISTANT_REPAIR_PROMPT } satisfies ChatMessage,
|
|
1649
|
-
];
|
|
1650
|
-
}
|
|
1651
|
-
return args.messages;
|
|
1652
|
-
}
|
|
1653
|
-
|
|
1654
|
-
function resolveAssistantRepairDecision(args: {
|
|
1655
|
-
messages: ChatMessage[];
|
|
1656
|
-
assistantMsg: ChatMessage;
|
|
1657
|
-
finalParallelSummaryRepairUsed: boolean;
|
|
1658
|
-
emptyAssistantRepairUsed: boolean;
|
|
1659
|
-
}): "parallel-summary" | "empty-assistant" | null {
|
|
1660
|
-
const assistantText = extractAssistantText(args.assistantMsg).trim();
|
|
1661
|
-
if (
|
|
1662
|
-
!args.assistantMsg.tool_calls?.length &&
|
|
1663
|
-
!assistantText &&
|
|
1664
|
-
!args.finalParallelSummaryRepairUsed &&
|
|
1665
|
-
hasParallelBranchMessages(args.messages)
|
|
1666
|
-
) {
|
|
1667
|
-
return "parallel-summary";
|
|
1668
|
-
}
|
|
1669
|
-
if (
|
|
1670
|
-
!args.assistantMsg.tool_calls?.length &&
|
|
1671
|
-
!assistantText &&
|
|
1672
|
-
!args.emptyAssistantRepairUsed
|
|
1673
|
-
) {
|
|
1674
|
-
return "empty-assistant";
|
|
1675
|
-
}
|
|
1676
|
-
return null;
|
|
1677
|
-
}
|
|
1678
|
-
|
|
1679
|
-
async function requestLoopUpstreamTurn(args: {
|
|
1680
|
-
endpoint: string;
|
|
1681
|
-
agentConfig: any;
|
|
1682
|
-
messages: ChatMessage[];
|
|
1683
|
-
tools: ReturnType<typeof buildTools>;
|
|
1684
|
-
stream: boolean;
|
|
1685
|
-
finalParallelSummaryRepairPending: boolean;
|
|
1686
|
-
emptyAssistantRepairPending: boolean;
|
|
1687
|
-
resolvedProvider?: string;
|
|
1688
|
-
resolvedModel: string;
|
|
1689
|
-
resolvedInputPrice?: number;
|
|
1690
|
-
resolvedOutputPrice?: number;
|
|
1691
|
-
providerCallContext?: {
|
|
1692
|
-
userId?: string | null;
|
|
1693
|
-
dialogId?: string | null;
|
|
1694
|
-
agentId?: string | null;
|
|
1695
|
-
};
|
|
1696
|
-
providerCallStore?: ProviderCallStore;
|
|
1697
|
-
}): Promise<{
|
|
1698
|
-
response: Response;
|
|
1699
|
-
provider?: string;
|
|
1700
|
-
model: string;
|
|
1701
|
-
inputPrice?: number;
|
|
1702
|
-
outputPrice?: number;
|
|
1703
|
-
providerCallIds?: string[];
|
|
1704
|
-
}> {
|
|
1705
|
-
const requestMessages = buildRepairRequestMessages({
|
|
1706
|
-
messages: args.messages,
|
|
1707
|
-
finalParallelSummaryRepairPending: args.finalParallelSummaryRepairPending,
|
|
1708
|
-
emptyAssistantRepairPending: args.emptyAssistantRepairPending,
|
|
1709
|
-
});
|
|
1710
|
-
const body = buildLoopRequestBody(args.agentConfig, requestMessages, args.tools, args.stream);
|
|
1711
|
-
const upstreamResult = await fetchLoopUpstream(
|
|
1712
|
-
args.endpoint,
|
|
1713
|
-
args.agentConfig,
|
|
1714
|
-
body,
|
|
1715
|
-
args.providerCallContext,
|
|
1716
|
-
args.providerCallStore,
|
|
1717
|
-
);
|
|
1718
|
-
return {
|
|
1719
|
-
response: upstreamResult.response,
|
|
1720
|
-
provider: upstreamResult.provider ?? args.resolvedProvider,
|
|
1721
|
-
model: upstreamResult.model ?? args.resolvedModel,
|
|
1722
|
-
inputPrice: upstreamResult.inputPrice ?? args.resolvedInputPrice,
|
|
1723
|
-
outputPrice: upstreamResult.outputPrice ?? args.resolvedOutputPrice,
|
|
1724
|
-
providerCallIds: upstreamResult.providerCallIds,
|
|
1725
|
-
};
|
|
1726
|
-
}
|
|
1727
|
-
|
|
1728
|
-
function buildLoopToolExecutionOptions(args: {
|
|
1729
|
-
agentConfig: any;
|
|
1730
|
-
messages: ChatMessage[];
|
|
1731
|
-
runtimePolicy?: ResolvedRuntimePolicy;
|
|
1732
|
-
runtimeState: ToolPolicyRuntimeState;
|
|
1733
|
-
userId?: string | null;
|
|
1734
|
-
dialogId?: string | null;
|
|
1735
|
-
currentSpaceId?: string | null;
|
|
1736
|
-
userInput?: string | null;
|
|
1737
|
-
runtimeContext?: AgentRunRuntimeContext | null;
|
|
1738
|
-
}) {
|
|
1739
|
-
return {
|
|
1740
|
-
policy: args.runtimePolicy,
|
|
1741
|
-
runtimeState: args.runtimeState,
|
|
1742
|
-
userId: args.userId,
|
|
1743
|
-
agentKey:
|
|
1744
|
-
typeof args.agentConfig?.dbKey === "string" && args.agentConfig.dbKey.trim()
|
|
1745
|
-
? args.agentConfig.dbKey.trim()
|
|
1746
|
-
: typeof args.agentConfig?.id === "string" && args.agentConfig.id.trim()
|
|
1747
|
-
? args.agentConfig.id.trim()
|
|
1748
|
-
: null,
|
|
1749
|
-
dialogId: args.dialogId,
|
|
1750
|
-
currentSpaceId: args.currentSpaceId,
|
|
1751
|
-
userInput: args.userInput,
|
|
1752
|
-
runtimeContext: args.runtimeContext,
|
|
1753
|
-
imageUrls: collectLatestImageUrls(args.messages),
|
|
1754
|
-
};
|
|
1755
|
-
}
|
|
1756
|
-
|
|
1757
|
-
// ── 非流式 ────────────────────────────────────────────────────────────────────
|
|
1758
|
-
|
|
1759
|
-
export async function runAgentLoop(
|
|
1760
|
-
agentConfig: any,
|
|
1761
|
-
initialMessages: ChatMessage[],
|
|
1762
|
-
_maxRounds: number,
|
|
1763
|
-
serverBase: string,
|
|
1764
|
-
authToken: string,
|
|
1765
|
-
runtimePolicy?: ResolvedRuntimePolicy,
|
|
1766
|
-
userId?: string | null,
|
|
1767
|
-
dialogId?: string | null,
|
|
1768
|
-
currentSpaceId?: string | null,
|
|
1769
|
-
userInput?: string | null,
|
|
1770
|
-
runtimeContext?: AgentRunRuntimeContext | null,
|
|
1771
|
-
providerCallStore?: ProviderCallStore,
|
|
1772
|
-
): Promise<LoopResult> {
|
|
1773
|
-
const startTime = Date.now();
|
|
1774
|
-
agentConfig = await hydrateApiKeyReferenceIfNeeded(agentConfig, serverBase, authToken);
|
|
1775
|
-
const dispatchCliLoop = async () => {
|
|
1776
|
-
// CLI 与普通 model 共享 prompt/model/最近历史,但这里有意保持“单次文本委托”的边界。
|
|
1777
|
-
const provider: CliProvider = (agentConfig.cliProvider ?? "copilot") as CliProvider;
|
|
1778
|
-
const taskPrompt = buildCliTaskPrompt(initialMessages, userInput);
|
|
1779
|
-
const fullPrompt = buildCliPrompt(agentConfig.prompt, taskPrompt);
|
|
1780
|
-
const result = await executeCli(provider, fullPrompt, {
|
|
1781
|
-
model: agentConfig.model || undefined,
|
|
1782
|
-
yolo: true,
|
|
1783
|
-
});
|
|
1784
|
-
|
|
1785
|
-
return buildLoopCompletion({
|
|
1786
|
-
content: result.text,
|
|
1787
|
-
model: agentConfig.model ?? "unknown",
|
|
1788
|
-
provider: agentConfig.provider ?? undefined,
|
|
1789
|
-
inputPrice: agentConfig.inputPrice,
|
|
1790
|
-
outputPrice: agentConfig.outputPrice,
|
|
1791
|
-
usage: undefined,
|
|
1792
|
-
trace: [
|
|
1793
|
-
{
|
|
1794
|
-
role: "assistant",
|
|
1795
|
-
content: result.text,
|
|
1796
|
-
},
|
|
1797
|
-
],
|
|
1798
|
-
runtimeToolNames: [],
|
|
1799
|
-
toolCallCount: 0,
|
|
1800
|
-
runtimePolicy,
|
|
1801
|
-
runtimeState: {
|
|
1802
|
-
autoKnowledgeCaptureCountThisRun: 0,
|
|
1803
|
-
autoSpaceReadCountThisRun: 0,
|
|
1804
|
-
},
|
|
1805
|
-
startedAt: startTime,
|
|
1806
|
-
llmRequestCount: 0,
|
|
1807
|
-
llmWaitMs: 0,
|
|
1808
|
-
llmJsonParseMs: 0,
|
|
1809
|
-
toolExecutionMs: 0,
|
|
1810
|
-
firstAssistantAt: startTime + Math.max(0, result.elapsed ?? 0),
|
|
1811
|
-
});
|
|
1812
|
-
};
|
|
1813
|
-
if (agentConfig.apiSource === "cli") {
|
|
1814
|
-
return await dispatchCliLoop();
|
|
1815
|
-
}
|
|
1816
|
-
const dispatchModelLoop = async () => {
|
|
1817
|
-
|
|
1818
|
-
const endpoint = getApiEndpoint(agentConfig);
|
|
1819
|
-
const tools = buildTools(agentConfig);
|
|
1820
|
-
const runtimeToolNames = getPreparedToolNames(tools);
|
|
1821
|
-
// maxRounds 仅为兼容旧请求字段保留;工具轮次不再做硬限制。
|
|
1822
|
-
// 后续如需控制,应改为基于成本/预算的策略,而不是轮次数量。
|
|
1823
|
-
void _maxRounds;
|
|
1824
|
-
|
|
1825
|
-
const messages: ChatMessage[] = [...initialMessages];
|
|
1826
|
-
const traceStartIndex = messages.length;
|
|
1827
|
-
let finalContent = "";
|
|
1828
|
-
let lastUsage: Record<string, any> | undefined;
|
|
1829
|
-
let lastResolvedProvider = agentConfig.provider ?? undefined;
|
|
1830
|
-
let lastResolvedModel = agentConfig.model ?? "unknown";
|
|
1831
|
-
let lastResolvedInputPrice = agentConfig.inputPrice;
|
|
1832
|
-
let lastResolvedOutputPrice = agentConfig.outputPrice;
|
|
1833
|
-
const providerCallIds: string[] = [];
|
|
1834
|
-
let toolCallCount = 0;
|
|
1835
|
-
let llmRequestCount = 0;
|
|
1836
|
-
let llmWaitMs = 0;
|
|
1837
|
-
let llmJsonParseMs = 0;
|
|
1838
|
-
let toolExecutionMs = 0;
|
|
1839
|
-
let firstAssistantAt: number | undefined;
|
|
1840
|
-
let firstToolResultAt: number | undefined;
|
|
1841
|
-
const runtimeState: ToolPolicyRuntimeState = {
|
|
1842
|
-
autoKnowledgeCaptureCountThisRun: 0,
|
|
1843
|
-
autoSpaceReadCountThisRun: 0,
|
|
1844
|
-
};
|
|
1845
|
-
let finalParallelSummaryRepairPending = false;
|
|
1846
|
-
let finalParallelSummaryRepairUsed = false;
|
|
1847
|
-
let emptyAssistantRepairPending = false;
|
|
1848
|
-
let emptyAssistantRepairUsed = false;
|
|
1849
|
-
|
|
1850
|
-
const wereadPreflight = await runWereadGatewayPreflightIfNeeded({
|
|
1851
|
-
agentConfig,
|
|
1852
|
-
tools,
|
|
1853
|
-
messages,
|
|
1854
|
-
serverBase,
|
|
1855
|
-
authToken,
|
|
1856
|
-
runtimePolicy,
|
|
1857
|
-
runtimeState,
|
|
1858
|
-
userId,
|
|
1859
|
-
dialogId,
|
|
1860
|
-
currentSpaceId,
|
|
1861
|
-
userInput,
|
|
1862
|
-
runtimeContext,
|
|
1863
|
-
});
|
|
1864
|
-
if (wereadPreflight.ran) {
|
|
1865
|
-
toolCallCount += 1;
|
|
1866
|
-
toolExecutionMs += wereadPreflight.elapsedMs;
|
|
1867
|
-
firstToolResultAt = wereadPreflight.completedAt;
|
|
1868
|
-
}
|
|
1869
|
-
|
|
1870
|
-
for (;;) {
|
|
1871
|
-
if (Date.now() - startTime > MAX_TIME_MS) break;
|
|
1872
|
-
|
|
1873
|
-
const repairPendingState = {
|
|
1874
|
-
finalParallelSummaryRepairPending,
|
|
1875
|
-
emptyAssistantRepairPending,
|
|
1876
|
-
};
|
|
1877
|
-
const upstreamStartedAt = Date.now();
|
|
1878
|
-
const upstreamTurn = await requestLoopUpstreamTurn({
|
|
1879
|
-
endpoint,
|
|
1880
|
-
agentConfig,
|
|
1881
|
-
messages,
|
|
1882
|
-
tools,
|
|
1883
|
-
stream: false,
|
|
1884
|
-
finalParallelSummaryRepairPending: repairPendingState.finalParallelSummaryRepairPending,
|
|
1885
|
-
emptyAssistantRepairPending: repairPendingState.emptyAssistantRepairPending,
|
|
1886
|
-
resolvedProvider: lastResolvedProvider,
|
|
1887
|
-
resolvedModel: lastResolvedModel,
|
|
1888
|
-
resolvedInputPrice: lastResolvedInputPrice,
|
|
1889
|
-
resolvedOutputPrice: lastResolvedOutputPrice,
|
|
1890
|
-
providerCallContext: {
|
|
1891
|
-
userId,
|
|
1892
|
-
dialogId,
|
|
1893
|
-
agentId: agentConfig.dbKey ?? agentConfig.id ?? null,
|
|
1894
|
-
},
|
|
1895
|
-
providerCallStore,
|
|
1896
|
-
});
|
|
1897
|
-
finalParallelSummaryRepairPending = false;
|
|
1898
|
-
emptyAssistantRepairPending = false;
|
|
1899
|
-
const res = upstreamTurn.response;
|
|
1900
|
-
llmRequestCount += 1;
|
|
1901
|
-
llmWaitMs += Math.max(0, Date.now() - upstreamStartedAt);
|
|
1902
|
-
lastResolvedProvider = upstreamTurn.provider;
|
|
1903
|
-
lastResolvedModel = upstreamTurn.model;
|
|
1904
|
-
lastResolvedInputPrice = upstreamTurn.inputPrice;
|
|
1905
|
-
lastResolvedOutputPrice = upstreamTurn.outputPrice;
|
|
1906
|
-
if (upstreamTurn.providerCallIds?.length) {
|
|
1907
|
-
providerCallIds.push(...upstreamTurn.providerCallIds);
|
|
1908
|
-
}
|
|
1909
|
-
|
|
1910
|
-
if (!res.ok) throw new Error(`LLM API error (${res.status}): ${await res.text()}`);
|
|
1911
|
-
|
|
1912
|
-
const parseStartedAt = Date.now();
|
|
1913
|
-
const data = await res.json() as any;
|
|
1914
|
-
llmJsonParseMs += Math.max(0, Date.now() - parseStartedAt);
|
|
1915
|
-
const choice = data.choices?.[0];
|
|
1916
|
-
const assistantMsg: ChatMessage | null = isResponseAPIModel(agentConfig)
|
|
1917
|
-
? buildAssistantMessageFromResponse(data)
|
|
1918
|
-
: choice?.message;
|
|
1919
|
-
if (!assistantMsg) break;
|
|
1920
|
-
if (firstAssistantAt === undefined) {
|
|
1921
|
-
firstAssistantAt = Date.now();
|
|
1922
|
-
}
|
|
1923
|
-
|
|
1924
|
-
lastUsage = addUsageTotal(
|
|
1925
|
-
lastUsage,
|
|
1926
|
-
addUsageTotal(data.usage ?? data.response?.usage, buildProviderAuditUsageMetadata(res, data)),
|
|
1927
|
-
);
|
|
1928
|
-
const assistantText = extractAssistantText(assistantMsg).trim();
|
|
1929
|
-
const repairDecision = resolveAssistantRepairDecision({
|
|
1930
|
-
messages,
|
|
1931
|
-
assistantMsg,
|
|
1932
|
-
finalParallelSummaryRepairUsed,
|
|
1933
|
-
emptyAssistantRepairUsed,
|
|
1934
|
-
});
|
|
1935
|
-
if (repairDecision === "parallel-summary") {
|
|
1936
|
-
finalParallelSummaryRepairPending = true;
|
|
1937
|
-
finalParallelSummaryRepairUsed = true;
|
|
1938
|
-
continue;
|
|
1939
|
-
}
|
|
1940
|
-
if (repairDecision === "empty-assistant") {
|
|
1941
|
-
emptyAssistantRepairPending = true;
|
|
1942
|
-
emptyAssistantRepairUsed = true;
|
|
1943
|
-
continue;
|
|
1944
|
-
}
|
|
1945
|
-
messages.push(assistantMsg);
|
|
1946
|
-
|
|
1947
|
-
if (!assistantMsg.tool_calls?.length || (!isResponseAPIModel(agentConfig) && choice.finish_reason === "stop")) {
|
|
1948
|
-
finalContent = assistantText;
|
|
1949
|
-
break;
|
|
1950
|
-
}
|
|
1951
|
-
|
|
1952
|
-
for (const tc of assistantMsg.tool_calls!) {
|
|
1953
|
-
toolCallCount++;
|
|
1954
|
-
const toolStartedAt = Date.now();
|
|
1955
|
-
const toolResult = await executeToolOnServer(
|
|
1956
|
-
tc,
|
|
1957
|
-
serverBase,
|
|
1958
|
-
authToken,
|
|
1959
|
-
buildLoopToolExecutionOptions({
|
|
1960
|
-
agentConfig,
|
|
1961
|
-
messages,
|
|
1962
|
-
runtimePolicy,
|
|
1963
|
-
runtimeState,
|
|
1964
|
-
userId,
|
|
1965
|
-
dialogId,
|
|
1966
|
-
currentSpaceId,
|
|
1967
|
-
userInput,
|
|
1968
|
-
runtimeContext,
|
|
1969
|
-
}),
|
|
1970
|
-
);
|
|
1971
|
-
toolExecutionMs += Math.max(0, Date.now() - toolStartedAt);
|
|
1972
|
-
if (firstToolResultAt === undefined) {
|
|
1973
|
-
firstToolResultAt = Date.now();
|
|
1974
|
-
}
|
|
1975
|
-
messages.push({
|
|
1976
|
-
role: "tool",
|
|
1977
|
-
tool_call_id: tc.id,
|
|
1978
|
-
content: toolResult,
|
|
1979
|
-
});
|
|
1980
|
-
const directCompletion = buildDirectCompletionFromToolResult(tc.function.name, toolResult);
|
|
1981
|
-
if (directCompletion) {
|
|
1982
|
-
finalContent = directCompletion;
|
|
1983
|
-
messages.push({
|
|
1984
|
-
role: "assistant",
|
|
1985
|
-
content: directCompletion,
|
|
1986
|
-
});
|
|
1987
|
-
return buildLoopCompletion({
|
|
1988
|
-
content: finalContent,
|
|
1989
|
-
model: lastResolvedModel,
|
|
1990
|
-
provider: lastResolvedProvider,
|
|
1991
|
-
inputPrice: lastResolvedInputPrice,
|
|
1992
|
-
outputPrice: lastResolvedOutputPrice,
|
|
1993
|
-
usage: lastUsage,
|
|
1994
|
-
trace: messages.slice(traceStartIndex),
|
|
1995
|
-
runtimeToolNames,
|
|
1996
|
-
toolCallCount,
|
|
1997
|
-
runtimePolicy,
|
|
1998
|
-
runtimeState,
|
|
1999
|
-
startedAt: startTime,
|
|
2000
|
-
llmRequestCount,
|
|
2001
|
-
llmWaitMs,
|
|
2002
|
-
llmJsonParseMs,
|
|
2003
|
-
toolExecutionMs,
|
|
2004
|
-
firstAssistantAt,
|
|
2005
|
-
firstToolResultAt,
|
|
2006
|
-
providerCallIds,
|
|
2007
|
-
});
|
|
2008
|
-
}
|
|
2009
|
-
if (["runStreamingAgent", "streamParallelAgents"].includes(canonicalizeToolName(tc.function.name))) {
|
|
2010
|
-
const parsed = parseToolResult(toolResult);
|
|
2011
|
-
if (canonicalizeToolName(tc.function.name) === "streamParallelAgents") {
|
|
2012
|
-
appendParallelBranchMessages(messages, parsed);
|
|
2013
|
-
}
|
|
2014
|
-
if (parsed?.handoff && typeof parsed.content === "string" && parsed.content.trim()) {
|
|
2015
|
-
finalContent = parsed.content;
|
|
2016
|
-
if (canonicalizeToolName(tc.function.name) !== "streamParallelAgents") {
|
|
2017
|
-
messages.push({
|
|
2018
|
-
role: "assistant",
|
|
2019
|
-
content: parsed.content,
|
|
2020
|
-
});
|
|
2021
|
-
}
|
|
2022
|
-
return buildLoopCompletion({
|
|
2023
|
-
content: finalContent,
|
|
2024
|
-
model: parsed.model || lastResolvedModel,
|
|
2025
|
-
provider: parsed.provider || lastResolvedProvider,
|
|
2026
|
-
inputPrice:
|
|
2027
|
-
typeof parsed.inputPrice === "number"
|
|
2028
|
-
? parsed.inputPrice
|
|
2029
|
-
: lastResolvedInputPrice,
|
|
2030
|
-
outputPrice:
|
|
2031
|
-
typeof parsed.outputPrice === "number"
|
|
2032
|
-
? parsed.outputPrice
|
|
2033
|
-
: lastResolvedOutputPrice,
|
|
2034
|
-
usage: parsed.usage ?? lastUsage,
|
|
2035
|
-
trace: messages.slice(traceStartIndex),
|
|
2036
|
-
runtimeToolNames,
|
|
2037
|
-
toolCallCount,
|
|
2038
|
-
runtimePolicy,
|
|
2039
|
-
runtimeState,
|
|
2040
|
-
startedAt: startTime,
|
|
2041
|
-
llmRequestCount,
|
|
2042
|
-
llmWaitMs,
|
|
2043
|
-
llmJsonParseMs,
|
|
2044
|
-
toolExecutionMs,
|
|
2045
|
-
firstAssistantAt,
|
|
2046
|
-
firstToolResultAt,
|
|
2047
|
-
providerCallIds,
|
|
2048
|
-
});
|
|
2049
|
-
}
|
|
2050
|
-
}
|
|
2051
|
-
}
|
|
2052
|
-
}
|
|
2053
|
-
|
|
2054
|
-
return buildLoopCompletion({
|
|
2055
|
-
content: finalContent,
|
|
2056
|
-
model: lastResolvedModel,
|
|
2057
|
-
provider: lastResolvedProvider,
|
|
2058
|
-
inputPrice: lastResolvedInputPrice,
|
|
2059
|
-
outputPrice: lastResolvedOutputPrice,
|
|
2060
|
-
usage: lastUsage,
|
|
2061
|
-
trace: messages.slice(traceStartIndex),
|
|
2062
|
-
runtimeToolNames,
|
|
2063
|
-
toolCallCount,
|
|
2064
|
-
runtimePolicy,
|
|
2065
|
-
runtimeState,
|
|
2066
|
-
startedAt: startTime,
|
|
2067
|
-
llmRequestCount,
|
|
2068
|
-
llmWaitMs,
|
|
2069
|
-
llmJsonParseMs,
|
|
2070
|
-
toolExecutionMs,
|
|
2071
|
-
firstAssistantAt,
|
|
2072
|
-
firstToolResultAt,
|
|
2073
|
-
providerCallIds,
|
|
2074
|
-
});
|
|
2075
|
-
};
|
|
2076
|
-
return await dispatchModelLoop();
|
|
2077
|
-
}
|
|
2078
|
-
|
|
2079
|
-
// ── 流式(SSE)────────────────────────────────────────────────────────────────
|
|
2080
|
-
|
|
2081
|
-
type Send = (data: object) => void;
|
|
2082
|
-
|
|
2083
|
-
export function buildSseStream(
|
|
2084
|
-
agentConfig: any,
|
|
2085
|
-
initialMessages: ChatMessage[],
|
|
2086
|
-
_maxRounds: number,
|
|
2087
|
-
serverBase: string,
|
|
2088
|
-
authToken: string,
|
|
2089
|
-
runtimePolicy?: ResolvedRuntimePolicy,
|
|
2090
|
-
userId?: string | null,
|
|
2091
|
-
dialogId?: string | null,
|
|
2092
|
-
currentSpaceId?: string | null,
|
|
2093
|
-
userInput?: string | null,
|
|
2094
|
-
runtimeContext?: AgentRunRuntimeContext | null,
|
|
2095
|
-
providerCallStore?: ProviderCallStore,
|
|
2096
|
-
): ReadableStream {
|
|
2097
|
-
const encoder = new TextEncoder();
|
|
2098
|
-
|
|
2099
|
-
return new ReadableStream({
|
|
2100
|
-
async start(controller) {
|
|
2101
|
-
const send: Send = (data) =>
|
|
2102
|
-
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
|
|
2103
|
-
|
|
2104
|
-
try {
|
|
2105
|
-
const dispatchCliStreamingLoop = async () => {
|
|
2106
|
-
// CLI 流式输出仅依赖 provider 自己的 stdout 语义,不合成本地 tool 事件。
|
|
2107
|
-
const provider: CliProvider = (agentConfig.cliProvider ?? "copilot") as CliProvider;
|
|
2108
|
-
const taskPrompt = buildCliTaskPrompt(initialMessages, userInput);
|
|
2109
|
-
const fullPrompt = buildCliPrompt(agentConfig.prompt, taskPrompt);
|
|
2110
|
-
|
|
2111
|
-
const result = await executeCliStreaming(provider, fullPrompt, {
|
|
2112
|
-
model: agentConfig.model || undefined,
|
|
2113
|
-
yolo: true,
|
|
2114
|
-
onChunk: (chunk: string) => {
|
|
2115
|
-
if (!chunk) return;
|
|
2116
|
-
send({ type: "text", content: chunk });
|
|
2117
|
-
},
|
|
2118
|
-
});
|
|
2119
|
-
|
|
2120
|
-
send(buildStreamDoneEvent({ elapsed: result.elapsed }));
|
|
2121
|
-
controller.close();
|
|
2122
|
-
};
|
|
2123
|
-
if (agentConfig.apiSource === "cli") {
|
|
2124
|
-
return await dispatchCliStreamingLoop();
|
|
2125
|
-
}
|
|
2126
|
-
const dispatchModelStreamingLoop = async () => {
|
|
2127
|
-
|
|
2128
|
-
const endpoint = getApiEndpoint(agentConfig);
|
|
2129
|
-
const tools = buildTools(agentConfig);
|
|
2130
|
-
// maxRounds 仅为兼容旧请求字段保留;工具轮次不再做硬限制。
|
|
2131
|
-
// 后续如需控制,应改为基于成本/预算的策略,而不是轮次数量。
|
|
2132
|
-
void _maxRounds;
|
|
2133
|
-
const messages: ChatMessage[] = [...initialMessages];
|
|
2134
|
-
const runtimeState: ToolPolicyRuntimeState = {
|
|
2135
|
-
autoKnowledgeCaptureCountThisRun: 0,
|
|
2136
|
-
autoSpaceReadCountThisRun: 0,
|
|
2137
|
-
};
|
|
2138
|
-
const startTime = Date.now();
|
|
2139
|
-
let lastUsage: Record<string, any> | undefined;
|
|
2140
|
-
let lastResolvedProvider = agentConfig.provider ?? undefined;
|
|
2141
|
-
let lastResolvedModel = agentConfig.model ?? "unknown";
|
|
2142
|
-
let lastResolvedInputPrice = agentConfig.inputPrice;
|
|
2143
|
-
let lastResolvedOutputPrice = agentConfig.outputPrice;
|
|
2144
|
-
const providerCallIds: string[] = [];
|
|
2145
|
-
let finalParallelSummaryRepairPending = false;
|
|
2146
|
-
let finalParallelSummaryRepairUsed = false;
|
|
2147
|
-
let emptyAssistantRepairPending = false;
|
|
2148
|
-
let emptyAssistantRepairUsed = false;
|
|
2149
|
-
|
|
2150
|
-
await runWereadGatewayPreflightIfNeeded({
|
|
2151
|
-
agentConfig,
|
|
2152
|
-
tools,
|
|
2153
|
-
messages,
|
|
2154
|
-
serverBase,
|
|
2155
|
-
authToken,
|
|
2156
|
-
runtimePolicy,
|
|
2157
|
-
runtimeState,
|
|
2158
|
-
userId,
|
|
2159
|
-
dialogId,
|
|
2160
|
-
currentSpaceId,
|
|
2161
|
-
userInput,
|
|
2162
|
-
runtimeContext,
|
|
2163
|
-
send,
|
|
2164
|
-
});
|
|
2165
|
-
|
|
2166
|
-
for (;;) {
|
|
2167
|
-
if (Date.now() - startTime > MAX_TIME_MS) {
|
|
2168
|
-
send({ type: "error", message: "Max execution time exceeded" });
|
|
2169
|
-
break;
|
|
2170
|
-
}
|
|
2171
|
-
const repairPendingState = {
|
|
2172
|
-
finalParallelSummaryRepairPending,
|
|
2173
|
-
emptyAssistantRepairPending,
|
|
2174
|
-
};
|
|
2175
|
-
finalParallelSummaryRepairPending = false;
|
|
2176
|
-
emptyAssistantRepairPending = false;
|
|
2177
|
-
|
|
2178
|
-
let res: Response;
|
|
2179
|
-
try {
|
|
2180
|
-
const upstreamTurn = await requestLoopUpstreamTurn({
|
|
2181
|
-
endpoint,
|
|
2182
|
-
agentConfig,
|
|
2183
|
-
messages,
|
|
2184
|
-
tools,
|
|
2185
|
-
stream: true,
|
|
2186
|
-
finalParallelSummaryRepairPending: repairPendingState.finalParallelSummaryRepairPending,
|
|
2187
|
-
emptyAssistantRepairPending: repairPendingState.emptyAssistantRepairPending,
|
|
2188
|
-
resolvedProvider: lastResolvedProvider,
|
|
2189
|
-
resolvedModel: lastResolvedModel,
|
|
2190
|
-
resolvedInputPrice: lastResolvedInputPrice,
|
|
2191
|
-
resolvedOutputPrice: lastResolvedOutputPrice,
|
|
2192
|
-
providerCallContext: {
|
|
2193
|
-
userId,
|
|
2194
|
-
dialogId,
|
|
2195
|
-
agentId: agentConfig.dbKey ?? agentConfig.id ?? null,
|
|
2196
|
-
},
|
|
2197
|
-
providerCallStore,
|
|
2198
|
-
});
|
|
2199
|
-
res = upstreamTurn.response;
|
|
2200
|
-
lastResolvedProvider = upstreamTurn.provider;
|
|
2201
|
-
lastResolvedModel = upstreamTurn.model;
|
|
2202
|
-
lastResolvedInputPrice = upstreamTurn.inputPrice;
|
|
2203
|
-
lastResolvedOutputPrice = upstreamTurn.outputPrice;
|
|
2204
|
-
if (upstreamTurn.providerCallIds?.length) {
|
|
2205
|
-
providerCallIds.push(...upstreamTurn.providerCallIds);
|
|
2206
|
-
}
|
|
2207
|
-
} catch (error: any) {
|
|
2208
|
-
send({ type: "error", message: error?.message ?? "Unexpected error" });
|
|
2209
|
-
break;
|
|
2210
|
-
}
|
|
2211
|
-
if (!res.ok || !res.body) {
|
|
2212
|
-
send({ type: "error", message: `LLM API error (${res.status}): ${await res.text()}` });
|
|
2213
|
-
break;
|
|
2214
|
-
}
|
|
2215
|
-
|
|
2216
|
-
const streamResult = isResponseAPIModel(agentConfig)
|
|
2217
|
-
? await consumeResponsesSseStream(res.body, send)
|
|
2218
|
-
: await consumeSseStream(res.body, send, {
|
|
2219
|
-
suppressPreToolText: shouldSuppressPreToolText(agentConfig),
|
|
2220
|
-
});
|
|
2221
|
-
const {
|
|
2222
|
-
toolCalls,
|
|
2223
|
-
hasToolCalls,
|
|
2224
|
-
assistantContent,
|
|
2225
|
-
reasoningContent,
|
|
2226
|
-
} = streamResult;
|
|
2227
|
-
lastUsage = addUsageTotal(
|
|
2228
|
-
lastUsage,
|
|
2229
|
-
addUsageTotal(streamResult.lastUsage, buildProviderAuditUsageMetadata(res)),
|
|
2230
|
-
);
|
|
2231
|
-
|
|
2232
|
-
const assistantMsg: ChatMessage = {
|
|
2233
|
-
role: "assistant",
|
|
2234
|
-
content: assistantContent || null,
|
|
2235
|
-
...(reasoningContent ? { reasoning_content: reasoningContent } : {}),
|
|
2236
|
-
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
2237
|
-
};
|
|
2238
|
-
const repairDecision = resolveAssistantRepairDecision({
|
|
2239
|
-
messages,
|
|
2240
|
-
assistantMsg,
|
|
2241
|
-
finalParallelSummaryRepairUsed,
|
|
2242
|
-
emptyAssistantRepairUsed,
|
|
2243
|
-
});
|
|
2244
|
-
if (repairDecision === "parallel-summary") {
|
|
2245
|
-
finalParallelSummaryRepairPending = true;
|
|
2246
|
-
finalParallelSummaryRepairUsed = true;
|
|
2247
|
-
continue;
|
|
2248
|
-
}
|
|
2249
|
-
if (repairDecision === "empty-assistant") {
|
|
2250
|
-
emptyAssistantRepairPending = true;
|
|
2251
|
-
emptyAssistantRepairUsed = true;
|
|
2252
|
-
continue;
|
|
2253
|
-
}
|
|
2254
|
-
messages.push(assistantMsg);
|
|
2255
|
-
|
|
2256
|
-
if (!hasToolCalls) {
|
|
2257
|
-
send(buildStreamDoneEvent({
|
|
2258
|
-
usage: lastUsage,
|
|
2259
|
-
provider: lastResolvedProvider,
|
|
2260
|
-
model: lastResolvedModel,
|
|
2261
|
-
inputPrice: lastResolvedInputPrice,
|
|
2262
|
-
outputPrice: lastResolvedOutputPrice,
|
|
2263
|
-
providerCallIds,
|
|
2264
|
-
}));
|
|
2265
|
-
break;
|
|
2266
|
-
}
|
|
2267
|
-
|
|
2268
|
-
send({
|
|
2269
|
-
type: "assistant_tool_calls",
|
|
2270
|
-
content: assistantMsg.content ?? null,
|
|
2271
|
-
tool_calls: toolCalls,
|
|
2272
|
-
});
|
|
2273
|
-
send({ type: "tool_start", calls: toolCalls.map((t) => t.function.name) });
|
|
2274
|
-
for (const tc of toolCalls) {
|
|
2275
|
-
const toolResult = await executeToolOnServer(
|
|
2276
|
-
tc,
|
|
2277
|
-
serverBase,
|
|
2278
|
-
authToken,
|
|
2279
|
-
buildLoopToolExecutionOptions({
|
|
2280
|
-
agentConfig,
|
|
2281
|
-
messages,
|
|
2282
|
-
runtimePolicy,
|
|
2283
|
-
runtimeState,
|
|
2284
|
-
userId,
|
|
2285
|
-
dialogId,
|
|
2286
|
-
currentSpaceId,
|
|
2287
|
-
userInput,
|
|
2288
|
-
runtimeContext,
|
|
2289
|
-
}),
|
|
2290
|
-
);
|
|
2291
|
-
messages.push({
|
|
2292
|
-
role: "tool",
|
|
2293
|
-
tool_call_id: tc.id,
|
|
2294
|
-
content: toolResult,
|
|
2295
|
-
});
|
|
2296
|
-
send({
|
|
2297
|
-
type: "tool_result",
|
|
2298
|
-
toolCallId: tc.id,
|
|
2299
|
-
toolName: canonicalizeToolName(tc.function.name),
|
|
2300
|
-
content: toolResult,
|
|
2301
|
-
});
|
|
2302
|
-
const directCompletion = buildDirectCompletionFromToolResult(tc.function.name, toolResult);
|
|
2303
|
-
if (directCompletion) {
|
|
2304
|
-
messages.push({
|
|
2305
|
-
role: "assistant",
|
|
2306
|
-
content: directCompletion,
|
|
2307
|
-
});
|
|
2308
|
-
send({ type: "text", content: directCompletion });
|
|
2309
|
-
send(buildStreamDoneEvent({
|
|
2310
|
-
usage: lastUsage,
|
|
2311
|
-
provider: lastResolvedProvider,
|
|
2312
|
-
model: lastResolvedModel,
|
|
2313
|
-
inputPrice: lastResolvedInputPrice,
|
|
2314
|
-
outputPrice: lastResolvedOutputPrice,
|
|
2315
|
-
providerCallIds,
|
|
2316
|
-
}));
|
|
2317
|
-
controller.close();
|
|
2318
|
-
return;
|
|
2319
|
-
}
|
|
2320
|
-
if (["runStreamingAgent", "streamParallelAgents"].includes(canonicalizeToolName(tc.function.name))) {
|
|
2321
|
-
const parsed = parseToolResult(toolResult);
|
|
2322
|
-
if (canonicalizeToolName(tc.function.name) === "streamParallelAgents") {
|
|
2323
|
-
appendParallelBranchMessages(messages, parsed);
|
|
2324
|
-
}
|
|
2325
|
-
if (parsed?.handoff && typeof parsed.content === "string" && parsed.content.trim()) {
|
|
2326
|
-
send({ type: "text", content: parsed.content });
|
|
2327
|
-
send(buildStreamDoneEvent({
|
|
2328
|
-
usage: parsed.usage ?? lastUsage,
|
|
2329
|
-
provider: parsed.provider || lastResolvedProvider,
|
|
2330
|
-
model: parsed.model || lastResolvedModel,
|
|
2331
|
-
inputPrice:
|
|
2332
|
-
typeof parsed.inputPrice === "number"
|
|
2333
|
-
? parsed.inputPrice
|
|
2334
|
-
: lastResolvedInputPrice,
|
|
2335
|
-
outputPrice:
|
|
2336
|
-
typeof parsed.outputPrice === "number"
|
|
2337
|
-
? parsed.outputPrice
|
|
2338
|
-
: lastResolvedOutputPrice,
|
|
2339
|
-
providerCallIds,
|
|
2340
|
-
}));
|
|
2341
|
-
controller.close();
|
|
2342
|
-
return;
|
|
2343
|
-
}
|
|
2344
|
-
}
|
|
2345
|
-
// 如果是创建文档类工具,解析结果并推送 doc_created 事件让前端感知
|
|
2346
|
-
if (["createDoc", "createSkillDoc", "importSkill"].includes(canonicalizeToolName(tc.function.name))) {
|
|
2347
|
-
try {
|
|
2348
|
-
const parsed = JSON.parse(toolResult);
|
|
2349
|
-
if (parsed?.dbKey) {
|
|
2350
|
-
send({ type: "doc_created", dbKey: parsed.dbKey, title: parsed.title, spaceId: parsed.spaceId });
|
|
2351
|
-
}
|
|
2352
|
-
} catch { /* 忽略解析失败 */ }
|
|
2353
|
-
}
|
|
2354
|
-
}
|
|
2355
|
-
send({ type: "tool_end" });
|
|
2356
|
-
}
|
|
2357
|
-
controller.close();
|
|
2358
|
-
};
|
|
2359
|
-
return await dispatchModelStreamingLoop();
|
|
2360
|
-
} catch (e: any) {
|
|
2361
|
-
controller.enqueue(
|
|
2362
|
-
encoder.encode(`data: ${JSON.stringify({ type: "error", message: e.message ?? "Unexpected error" })}\n\n`)
|
|
2363
|
-
);
|
|
2364
|
-
}
|
|
2365
|
-
controller.close();
|
|
2366
|
-
},
|
|
2367
|
-
});
|
|
2368
|
-
}
|
|
2369
|
-
|
|
2370
|
-
interface SseConsumeResult {
|
|
2371
|
-
toolCalls: AssistantToolCall[];
|
|
2372
|
-
hasToolCalls: boolean;
|
|
2373
|
-
assistantContent: ChatMessage["content"];
|
|
2374
|
-
reasoningContent: string;
|
|
2375
|
-
lastUsage: any;
|
|
2376
|
-
}
|
|
2377
|
-
|
|
2378
|
-
function shouldSuppressPreToolText(agentConfig: any): boolean {
|
|
2379
|
-
return (
|
|
2380
|
-
agentConfig?.dbKey === BUILTIN_NOLO_AGENT_KEY ||
|
|
2381
|
-
agentConfig?.agentKey === BUILTIN_NOLO_AGENT_KEY ||
|
|
2382
|
-
agentConfig?.id === BUILTIN_NOLO_AGENT_KEY ||
|
|
2383
|
-
agentConfig?.id === "01NOLOAPPBLD000000019KCKT0"
|
|
2384
|
-
);
|
|
2385
|
-
}
|
|
2386
|
-
|
|
2387
|
-
async function consumeSseStream(
|
|
2388
|
-
body: ReadableStream<Uint8Array>,
|
|
2389
|
-
send: Send,
|
|
2390
|
-
options?: { suppressPreToolText?: boolean },
|
|
2391
|
-
): Promise<SseConsumeResult> {
|
|
2392
|
-
const reader = body.getReader();
|
|
2393
|
-
const decoder = new TextDecoder();
|
|
2394
|
-
let buf = "";
|
|
2395
|
-
const acc: Record<number, AssistantToolCall> = {};
|
|
2396
|
-
let hasToolCalls = false;
|
|
2397
|
-
const assistantContentParts: Array<
|
|
2398
|
-
{ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }
|
|
2399
|
-
> = [];
|
|
2400
|
-
let reasoningContent = "";
|
|
2401
|
-
let lastUsage: any = null;
|
|
2402
|
-
let suppressedText = "";
|
|
2403
|
-
|
|
2404
|
-
outer: while (true) {
|
|
2405
|
-
const { done, value } = await reader.read();
|
|
2406
|
-
if (done) break;
|
|
2407
|
-
buf += decoder.decode(value, { stream: true });
|
|
2408
|
-
const lines = buf.split("\n");
|
|
2409
|
-
buf = lines.pop() ?? "";
|
|
2410
|
-
|
|
2411
|
-
for (const line of lines) {
|
|
2412
|
-
if (!line.startsWith("data: ")) continue;
|
|
2413
|
-
const raw = line.slice(6).trim();
|
|
2414
|
-
if (raw === "[DONE]") break outer;
|
|
2415
|
-
|
|
2416
|
-
let chunk: any;
|
|
2417
|
-
try { chunk = JSON.parse(raw); } catch { continue; }
|
|
2418
|
-
|
|
2419
|
-
const delta = chunk.choices?.[0]?.delta;
|
|
2420
|
-
const chunkAuditUsage = buildProviderAuditUsageMetadata(null, chunk);
|
|
2421
|
-
if (!delta) {
|
|
2422
|
-
lastUsage = mergeUsageSnapshot(
|
|
2423
|
-
lastUsage,
|
|
2424
|
-
mergeUsageSnapshot(chunk.usage, chunkAuditUsage),
|
|
2425
|
-
) ?? null;
|
|
2426
|
-
continue;
|
|
2427
|
-
}
|
|
2428
|
-
|
|
2429
|
-
if (typeof delta.content === "string" && delta.content) {
|
|
2430
|
-
appendTextPart(assistantContentParts, delta.content);
|
|
2431
|
-
if (options?.suppressPreToolText) {
|
|
2432
|
-
suppressedText += delta.content;
|
|
2433
|
-
} else {
|
|
2434
|
-
send({ type: "text", content: delta.content });
|
|
2435
|
-
}
|
|
2436
|
-
}
|
|
2437
|
-
|
|
2438
|
-
if (Array.isArray(delta.images) && delta.images.length > 0) {
|
|
2439
|
-
assistantContentParts.push(...delta.images);
|
|
2440
|
-
}
|
|
2441
|
-
|
|
2442
|
-
// 思考内容:Ollama/Qwen3 用 delta.reasoning,DeepSeek 用 delta.reasoning_content
|
|
2443
|
-
const thinkChunk: string = delta.reasoning ?? delta.reasoning_content ?? "";
|
|
2444
|
-
if (thinkChunk) {
|
|
2445
|
-
reasoningContent += thinkChunk;
|
|
2446
|
-
send({ type: "thinking", content: thinkChunk });
|
|
2447
|
-
}
|
|
2448
|
-
|
|
2449
|
-
if (Array.isArray(delta.tool_calls)) {
|
|
2450
|
-
hasToolCalls = true;
|
|
2451
|
-
for (const tc of delta.tool_calls) {
|
|
2452
|
-
const idx: number = tc.index ?? 0;
|
|
2453
|
-
if (!acc[idx]) {
|
|
2454
|
-
acc[idx] = { id: tc.id ?? "", type: "function", function: { name: tc.function?.name ?? "", arguments: "" } };
|
|
2455
|
-
}
|
|
2456
|
-
acc[idx].function.arguments += tc.function?.arguments ?? "";
|
|
2457
|
-
if (tc.id) acc[idx].id = tc.id;
|
|
2458
|
-
if (tc.function?.name) acc[idx].function.name = tc.function.name;
|
|
2459
|
-
}
|
|
2460
|
-
}
|
|
2461
|
-
|
|
2462
|
-
lastUsage = mergeUsageSnapshot(
|
|
2463
|
-
lastUsage,
|
|
2464
|
-
mergeUsageSnapshot(chunk.usage, chunkAuditUsage),
|
|
2465
|
-
) ?? null;
|
|
2466
|
-
}
|
|
2467
|
-
}
|
|
2468
|
-
|
|
2469
|
-
const assistantContent = finalizeAssistantContent(assistantContentParts);
|
|
2470
|
-
if (options?.suppressPreToolText && !hasToolCalls && suppressedText) {
|
|
2471
|
-
send({ type: "text", content: suppressedText });
|
|
2472
|
-
}
|
|
2473
|
-
|
|
2474
|
-
return {
|
|
2475
|
-
toolCalls: Object.values(acc),
|
|
2476
|
-
hasToolCalls,
|
|
2477
|
-
assistantContent,
|
|
2478
|
-
reasoningContent,
|
|
2479
|
-
lastUsage,
|
|
2480
|
-
};
|
|
2481
|
-
}
|
|
2482
|
-
|
|
2483
|
-
async function consumeResponsesSseStream(
|
|
2484
|
-
body: ReadableStream<Uint8Array>,
|
|
2485
|
-
send: Send
|
|
2486
|
-
): Promise<SseConsumeResult> {
|
|
2487
|
-
const reader = body.getReader();
|
|
2488
|
-
const decoder = new TextDecoder();
|
|
2489
|
-
let buf = "";
|
|
2490
|
-
const acc = new Map<string, AssistantToolCall>();
|
|
2491
|
-
let hasToolCalls = false;
|
|
2492
|
-
let assistantContent = "";
|
|
2493
|
-
let reasoningContent = "";
|
|
2494
|
-
let lastUsage: any = null;
|
|
2495
|
-
let completedResponse: any = null;
|
|
2496
|
-
|
|
2497
|
-
outer: while (true) {
|
|
2498
|
-
const { done, value } = await reader.read();
|
|
2499
|
-
if (done) break;
|
|
2500
|
-
buf += decoder.decode(value, { stream: true });
|
|
2501
|
-
const lines = buf.split("\n");
|
|
2502
|
-
buf = lines.pop() ?? "";
|
|
2503
|
-
|
|
2504
|
-
for (const line of lines) {
|
|
2505
|
-
if (!line.startsWith("data: ")) continue;
|
|
2506
|
-
const raw = line.slice(6).trim();
|
|
2507
|
-
if (raw === "[DONE]") break outer;
|
|
2508
|
-
|
|
2509
|
-
let event: any;
|
|
2510
|
-
try {
|
|
2511
|
-
event = JSON.parse(raw);
|
|
2512
|
-
} catch {
|
|
2513
|
-
continue;
|
|
2514
|
-
}
|
|
2515
|
-
|
|
2516
|
-
const eventAuditUsage = buildProviderAuditUsageMetadata(null, event);
|
|
2517
|
-
const eventUsage =
|
|
2518
|
-
event?.type === "response.completed" && event.response?.usage
|
|
2519
|
-
? undefined
|
|
2520
|
-
: event?.usage;
|
|
2521
|
-
lastUsage = mergeUsageSnapshot(
|
|
2522
|
-
lastUsage,
|
|
2523
|
-
mergeUsageSnapshot(eventUsage, eventAuditUsage),
|
|
2524
|
-
) ?? null;
|
|
2525
|
-
|
|
2526
|
-
switch (event?.type) {
|
|
2527
|
-
case "response.output_text.delta":
|
|
2528
|
-
if (event.delta) {
|
|
2529
|
-
assistantContent += event.delta;
|
|
2530
|
-
send({ type: "text", content: event.delta });
|
|
2531
|
-
}
|
|
2532
|
-
break;
|
|
2533
|
-
case "response.reasoning.delta":
|
|
2534
|
-
if (event.delta?.text) {
|
|
2535
|
-
reasoningContent += event.delta.text;
|
|
2536
|
-
send({ type: "thinking", content: event.delta.text });
|
|
2537
|
-
}
|
|
2538
|
-
break;
|
|
2539
|
-
case "response.output_item.added":
|
|
2540
|
-
case "response.output_item.done": {
|
|
2541
|
-
const item = event.item;
|
|
2542
|
-
if (!assistantContent) {
|
|
2543
|
-
const itemText = extractTextFromResponseOutputItem(item);
|
|
2544
|
-
if (itemText) {
|
|
2545
|
-
assistantContent = itemText;
|
|
2546
|
-
send({ type: "text", content: itemText });
|
|
2547
|
-
}
|
|
2548
|
-
}
|
|
2549
|
-
if (item?.type !== "function_call") break;
|
|
2550
|
-
hasToolCalls = true;
|
|
2551
|
-
const key = item.call_id || item.id;
|
|
2552
|
-
if (!key) break;
|
|
2553
|
-
acc.set(key, {
|
|
2554
|
-
id: item.call_id || item.id,
|
|
2555
|
-
type: "function",
|
|
2556
|
-
function: {
|
|
2557
|
-
name: item.name ?? "",
|
|
2558
|
-
arguments:
|
|
2559
|
-
typeof item.arguments === "string" ? item.arguments : "",
|
|
2560
|
-
},
|
|
2561
|
-
});
|
|
2562
|
-
break;
|
|
2563
|
-
}
|
|
2564
|
-
case "response.function_call_arguments.delta": {
|
|
2565
|
-
hasToolCalls = true;
|
|
2566
|
-
const key = event.call_id || event.item_id || `${event.output_index ?? 0}`;
|
|
2567
|
-
const current = acc.get(key) ?? {
|
|
2568
|
-
id: event.call_id || key,
|
|
2569
|
-
type: "function" as const,
|
|
2570
|
-
function: { name: event.name ?? "", arguments: "" },
|
|
2571
|
-
};
|
|
2572
|
-
current.function.arguments += event.delta ?? "";
|
|
2573
|
-
if (event.name) current.function.name = event.name;
|
|
2574
|
-
acc.set(key, current);
|
|
2575
|
-
break;
|
|
2576
|
-
}
|
|
2577
|
-
case "response.function_call_arguments.done": {
|
|
2578
|
-
hasToolCalls = true;
|
|
2579
|
-
const key = event.call_id || event.item_id || `${event.output_index ?? 0}`;
|
|
2580
|
-
const current = acc.get(key) ?? {
|
|
2581
|
-
id: event.call_id || key,
|
|
2582
|
-
type: "function" as const,
|
|
2583
|
-
function: { name: event.name ?? "", arguments: "" },
|
|
2584
|
-
};
|
|
2585
|
-
if (event.name) current.function.name = event.name;
|
|
2586
|
-
if (typeof event.arguments === "string") {
|
|
2587
|
-
current.function.arguments = event.arguments;
|
|
2588
|
-
}
|
|
2589
|
-
acc.set(key, current);
|
|
2590
|
-
break;
|
|
2591
|
-
}
|
|
2592
|
-
case "response.completed":
|
|
2593
|
-
completedResponse = event.response ?? null;
|
|
2594
|
-
lastUsage = mergeUsageSnapshot(
|
|
2595
|
-
lastUsage,
|
|
2596
|
-
mergeUsageSnapshot(
|
|
2597
|
-
event.response?.usage,
|
|
2598
|
-
buildProviderAuditUsageMetadata(null, event.response),
|
|
2599
|
-
),
|
|
2600
|
-
) ?? null;
|
|
2601
|
-
break;
|
|
2602
|
-
default:
|
|
2603
|
-
break;
|
|
2604
|
-
}
|
|
2605
|
-
}
|
|
2606
|
-
}
|
|
2607
|
-
|
|
2608
|
-
if (!assistantContent && completedResponse) {
|
|
2609
|
-
assistantContent = extractTextFromResponseOutput(completedResponse);
|
|
2610
|
-
if (assistantContent) {
|
|
2611
|
-
send({ type: "text", content: assistantContent });
|
|
2612
|
-
}
|
|
2613
|
-
}
|
|
2614
|
-
|
|
2615
|
-
return {
|
|
2616
|
-
toolCalls: Array.from(acc.values()),
|
|
2617
|
-
hasToolCalls,
|
|
2618
|
-
assistantContent,
|
|
2619
|
-
reasoningContent,
|
|
2620
|
-
lastUsage,
|
|
2621
|
-
};
|
|
2622
|
-
}
|