nolo-cli 0.1.30 → 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/agent-runtime/agentRecordConfig.ts +0 -2
- package/agent-runtime/hostAdapter.ts +0 -1
- package/agent-runtime/hostRuntimeConfig.ts +86 -0
- package/agent-runtime/index.ts +13 -0
- package/agent-runtime/localToolPolicy.ts +13 -6
- package/agent-runtime/localWorkspaceTools.ts +333 -30
- package/agent-runtime/platformChatProvider.ts +4 -1
- package/agent-runtime/runtimeToolPolicy.ts +32 -47
- 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/agentRecordCommands.ts +1 -1
- package/agentRecordHelpers.ts +122 -16
- package/agentRunCommand.ts +72 -24
- package/agentRunParsing.ts +24 -5
- package/agentRuntimeLocal.ts +10 -0
- package/ai/agent/agentRunDialogLineage.ts +56 -0
- package/ai/agent/agentSlice.ts +1 -554
- package/ai/agent/cliExecutor.ts +330 -19
- package/ai/index.ts +1 -1
- package/authCommands.ts +36 -2
- package/buildPublish.ts +7 -2
- package/buildPublishArtifactAssembly.ts +514 -136
- package/buildPublishImportAnalysis.ts +21 -16
- package/chat/messages/types.ts +9 -0
- 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/cliEnvHelpers.ts +8 -0
- package/cliRuntimeDoctorReport.ts +193 -0
- package/client/agentConfigResolver.test.ts +0 -2
- package/client/agentRun.test.ts +208 -12
- package/client/agentRun.ts +44 -637
- package/client/agentRunInput.ts +10 -0
- package/client/agentRunLocalExecutor.ts +179 -0
- package/client/agentRunRuntimeSelection.test.ts +1 -0
- package/client/agentRunRuntimeSelection.ts +2 -12
- package/client/agentRunServerTransport.ts +397 -0
- package/client/agentRunTaskRunRecorder.ts +176 -0
- package/client/localRuntimeAdapter.test.ts +236 -9
- package/client/localRuntimeAdapter.ts +221 -23
- package/client/localToolPolicy.test.ts +28 -4
- package/commandRegistry.ts +1 -0
- package/connector-experimental/daemonLauncher.ts +38 -4
- package/connectorRunArtifact.ts +34 -10
- package/connectorWebSocketTarget.ts +70 -11
- package/database/server/authorityStoreTypes.ts +31 -0
- package/database/server/db.ts +15 -34
- package/database/server/legacyServerDb.ts +58 -0
- package/database/server/levelAuthorityStore.ts +75 -0
- package/database/server/memoryAuthorityStore.ts +133 -0
- package/database/server/serverStoreFactory.ts +124 -0
- package/localRuntimeDb.ts +39 -2
- package/machineCommandPrompts.ts +2 -0
- package/machineCommands.ts +199 -63
- package/machineWsRunDispatch.ts +81 -16
- package/machineWsSession.ts +65 -7
- package/noloReadBridgePrompt.ts +16 -0
- package/package.json +222 -62
- package/runtimeDoctorCommands.ts +15 -66
- package/spaceAttachCommands.ts +134 -0
- package/spaceInternalCommandEntries.ts +2 -0
- 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 -581
- 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 -236
- 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 -133
- 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 -479
- package/ai/agent/pageBuilderHandoffRules.ts +0 -75
- package/ai/agent/persistMessageWithFixedId.ts +0 -37
- package/ai/agent/planSlice.ts +0 -259
- 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/runtimeServerBase.ts +0 -37
- package/ai/agent/server/fetchPublicAgents.ts +0 -183
- package/ai/agent/startParallelAgentStreams.ts +0 -424
- package/ai/agent/startupProtocol.ts +0 -53
- package/ai/agent/streamAgentChatTurn.ts +0 -1874
- package/ai/agent/streamAgentChatTurnUtils.ts +0 -782
- package/ai/agent/types.ts +0 -71
- 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/referencePickerUtils.ts +0 -146
- package/ai/agent/web/useGuidedAgentCreation.ts +0 -238
- package/ai/ai.locale.ts +0 -1095
- 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 -695
- package/ai/chat/sendOpenAICompletionsRequest.ts +0 -805
- package/ai/chat/sendOpenAIResponseRequest.ts +0 -577
- 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 -89
- 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 -79
- 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 -22
- 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 -311
- package/ai/llm/reasoningModels.ts +0 -29
- package/ai/llm/types.ts +0 -67
- 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 -147
- 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 -76
- 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/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/calculatePrice.ts +0 -576
- package/ai/token/db.ts +0 -98
- package/ai/token/externalToolCost.ts +0 -341
- package/ai/token/hooks/useRecords.ts +0 -65
- package/ai/token/missingUsageEstimate.ts +0 -42
- package/ai/token/modelUsageQuery.ts +0 -269
- package/ai/token/normalizeUsage.ts +0 -84
- package/ai/token/openaiImageGenerationUsage.ts +0 -56
- package/ai/token/prepareTokenUsageData.ts +0 -93
- package/ai/token/query.ts +0 -88
- package/ai/token/queryUserTokens.ts +0 -59
- package/ai/token/resolveBillingTarget.ts +0 -52
- package/ai/token/saveTokenRecord.ts +0 -53
- package/ai/token/serverDialogProjection.ts +0 -78
- package/ai/token/serverTokenWriter.ts +0 -145
- package/ai/token/stats.ts +0 -21
- package/ai/token/tokenThunks.ts +0 -24
- package/ai/token/types.ts +0 -93
- package/ai/tools/agent/agentTools.ts +0 -235
- package/ai/tools/agent/agentUpdateShared.ts +0 -311
- package/ai/tools/agent/callAgentTool.ts +0 -139
- 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 -154
- package/ai/tools/agent/runLlmTool.ts +0 -96
- package/ai/tools/agent/runStreamingAgentTool.ts +0 -73
- 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 -123
- 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 -233
- 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 -13
- 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 -62
- 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/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 -42
- package/app/utils/desktopAgentRuntimeTurnClient.ts +0 -70
- 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 -244
- 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/authSlice.ts +0 -517
- 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 -77
- 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 -127
- package/auth/server/accessActivity.ts +0 -143
- package/auth/server/billingFullChainSimulator.ts +0 -325
- package/auth/server/billingUsageReport.ts +0 -192
- package/auth/server/cliLogin.ts +0 -198
- package/auth/server/creatorEarningCreditConversion.ts +0 -515
- 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 -270
- package/auth/server/delete.ts +0 -887
- package/auth/server/disable.ts +0 -61
- package/auth/server/emailAutomation.ts +0 -358
- 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 -147
- package/auth/server/emailDelivery.ts +0 -960
- package/auth/server/emailDeliveryGuards.ts +0 -282
- package/auth/server/emailPolicy.ts +0 -43
- package/auth/server/emailPreferences.ts +0 -117
- package/auth/server/emailProvider.ts +0 -277
- package/auth/server/emailReport.ts +0 -439
- package/auth/server/emailRuntimeConfig.ts +0 -86
- package/auth/server/emailScenarioNotifications.ts +0 -340
- package/auth/server/enable.ts +0 -61
- package/auth/server/getRechargeHistory.ts +0 -110
- package/auth/server/getUser.ts +0 -71
- package/auth/server/inviteReward.ts +0 -295
- 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 -154
- 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 -139
- package/auth/server/productPurchase.ts +0 -382
- package/auth/server/recharge.ts +0 -284
- 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 -59
- package/auth/server/route.ts +0 -195
- package/auth/server/sendEmail.ts +0 -176
- package/auth/server/shared.ts +0 -51
- package/auth/server/signup.ts +0 -423
- package/auth/server/signupIpQuota.ts +0 -44
- package/auth/server/token.ts +0 -109
- package/auth/server/tokenUsageBilling.ts +0 -312
- package/auth/server/transfer.ts +0 -40
- 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 -28
- package/auth/utils.ts +0 -108
- 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/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 -99
- 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 -1191
- package/chat/messages/pendingAttachmentParts.ts +0 -117
- package/chat/messages/sendFirstMessage.ts +0 -193
- 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/toolDisplayName.ts +0 -22
- package/chat/messages/web/useLoopStopReason.ts +0 -43
- 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 -189
- 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 -58
- 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 -169
- 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 -214
- package/create/space/space.locale.ts +0 -981
- 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 -33
- 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 -376
- package/database/actions/readAndWait.ts +0 -192
- 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 -124
- 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 -109
- package/database/server/delete.ts +0 -499
- package/database/server/emailRepository.ts +0 -1480
- package/database/server/fileRead.ts +0 -337
- package/database/server/fileService.ts +0 -436
- package/database/server/handleTransaction.ts +0 -86
- package/database/server/patch.ts +0 -290
- package/database/server/query.ts +0 -177
- package/database/server/read.ts +0 -311
- package/database/server/recordIdentity.ts +0 -100
- package/database/server/resourceAccess.ts +0 -211
- package/database/server/routes.ts +0 -110
- package/database/server/spaceMemberAuthority.ts +0 -67
- package/database/server/upload.ts +0 -159
- package/database/server/write.ts +0 -490
- 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 -298
- 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 -56
- 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 -174
- package/render/page/server/handleCreatePage.ts +0 -91
- 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 -333
- package/server/api/tableHandlers.ts +0 -55
- 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 -73
- package/server/billingLedgerRoutes.ts +0 -48
- package/server/cliChatRoutes.ts +0 -5
- package/server/cloudflareRoutes.ts +0 -35
- package/server/coreHeaders.ts +0 -29
- package/server/coreReadiness.ts +0 -39
- package/server/coreRoutes.ts +0 -65
- package/server/coreRuntime.ts +0 -93
- 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 -74
- package/server/handlers/agentEmailRegistrationE2EHandler.ts +0 -406
- package/server/handlers/agentEmailRegistrationE2ERoutes.ts +0 -6
- package/server/handlers/agentRun/agentLookup.ts +0 -77
- package/server/handlers/agentRun/autonomousRuntime.ts +0 -355
- package/server/handlers/agentRun/backgroundRunDialog.ts +0 -31
- package/server/handlers/agentRun/builtinAgents.ts +0 -347
- package/server/handlers/agentRun/continueDialogContext.ts +0 -90
- package/server/handlers/agentRun/debugContext.ts +0 -58
- package/server/handlers/agentRun/dialogLookup.ts +0 -67
- package/server/handlers/agentRun/foregroundStreamDialog.ts +0 -13
- package/server/handlers/agentRun/index.ts +0 -1630
- package/server/handlers/agentRun/inheritedDialogPrompt.ts +0 -111
- package/server/handlers/agentRun/localRuntimeBootstrap.ts +0 -69
- package/server/handlers/agentRun/loop.ts +0 -2210
- package/server/handlers/agentRun/machineConnector.ts +0 -235
- package/server/handlers/agentRun/machineRunAudit.ts +0 -49
- package/server/handlers/agentRun/modelUsageToolHandlers.ts +0 -368
- package/server/handlers/agentRun/referenceRuntime.ts +0 -50
- package/server/handlers/agentRun/requestContext.ts +0 -86
- 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 -153
- package/server/handlers/agentRun/runtimePreparation.ts +0 -193
- package/server/handlers/agentRun/runtimeRouting.ts +0 -88
- package/server/handlers/agentRun/runtimeSystemMessages.ts +0 -165
- package/server/handlers/agentRun/saveDialog.ts +0 -1373
- 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 -579
- package/server/handlers/agentRun/toolExecutor.ts +0 -2909
- package/server/handlers/agentRun/toolPolicyGuards.ts +0 -295
- package/server/handlers/agentRun/types.ts +0 -94
- 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 -178
- package/server/handlers/appDomainHandler.ts +0 -476
- package/server/handlers/appLegacyInfraCleanup.ts +0 -7
- package/server/handlers/appSandboxHandler.ts +0 -1055
- package/server/handlers/appSourceReadiness.ts +0 -75
- package/server/handlers/appSpaceAccess.ts +0 -179
- 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 -797
- package/server/handlers/chatProxyRouting.ts +0 -404
- package/server/handlers/chatUpstreamRetry.ts +0 -162
- 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 -192
- package/server/handlers/connector/connectorWebSocket.ts +0 -117
- 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/desktopAgentRuntimeHostFacts.ts +0 -40
- package/server/handlers/desktopAgentRuntimeStatusHandler.ts +0 -54
- package/server/handlers/desktopAgentRuntimeTurnHandler.ts +0 -165
- package/server/handlers/desktopAgentRuntimeTurnService.ts +0 -352
- 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 -360
- package/server/handlers/desktopLocalConnectorHandler.ts +0 -101
- package/server/handlers/desktopUpdaterHandler.ts +0 -132
- 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 -417
- 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 -151
- package/server/handlers/getTransactionsHandler.ts +0 -107
- 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 -59
- package/server/handlers/machines/machineHandlers.ts +0 -279
- package/server/handlers/machines/machineInstallAssets.ts +0 -563
- package/server/handlers/machines/machineRegistry.ts +0 -89
- package/server/handlers/notificationEmitter.ts +0 -189
- package/server/handlers/notificationsHandler.ts +0 -91
- package/server/handlers/olmOcrHandler.ts +0 -115
- package/server/handlers/openaiImageHandler.ts +0 -500
- package/server/handlers/providerHealthHandler.ts +0 -36
- 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 -34
- package/server/handlers/tableToolHandlers.ts +0 -741
- package/server/handlers/typecheckWorker.ts +0 -54
- package/server/handlers/userEvents.ts +0 -6
- package/server/handlers/userSecretsHandler.ts +0 -210
- package/server/handlers/versionHandler.ts +0 -281
- package/server/handlers/versionStore.ts +0 -176
- 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 -247
- 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 -134
- package/server/payments/crypto/cryptoUsdcBaseScanner.ts +0 -267
- 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 -132
- package/server/payments/crypto/cryptoUsdtTronScanner.ts +0 -313
- 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 -341
- 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/safeTempFile.ts +0 -48
- package/server/scheduler/scheduledTaskRuntime.ts +0 -228
- 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 -95
- 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 -202
- package/share/server/importShare.ts +0 -148
- package/share/server/listCommunityShares.ts +0 -167
- package/share/server/purchaseDoc.ts +0 -224
- package/share/server/readCommunityShareCover.ts +0 -73
- package/share/server/readSharedTable.ts +0 -139
- package/share/server/tableReplication.ts +0 -351
- package/share/shareSlice.ts +0 -53
- package/share/tableShareState.ts +0 -74
|
@@ -1,2909 +0,0 @@
|
|
|
1
|
-
// packages/server/handlers/agentRun/toolExecutor.ts
|
|
2
|
-
//
|
|
3
|
-
// 服务端 tool 执行器。
|
|
4
|
-
// 直接调用本机 API(无需 Redux),结果以字符串返回给 LLM。
|
|
5
|
-
// 不持久化任何内容。
|
|
6
|
-
|
|
7
|
-
import { markdownToSlate } from "../../../create/editor/transforms/markdownToSlate";
|
|
8
|
-
import { slateToRenderMarkdown } from "../../../create/editor/transforms/slateToRenderMarkdown";
|
|
9
|
-
import { extractMentionsFromSlate } from "../../../create/editor/utils/slateUtils";
|
|
10
|
-
import { WEB_AUTH_TOKEN_COOKIE } from "../../../auth/tokenCookie";
|
|
11
|
-
import { DataType } from "../../../create/types";
|
|
12
|
-
import { NOLO_CLUSTER_SERVERS } from "../../../database/config";
|
|
13
|
-
import { createAgentKey, createKey, createUserKey } from "../../../database/keys";
|
|
14
|
-
import { ulid } from "../../../database/utils/ulid";
|
|
15
|
-
import { saveBufferAsFile } from "../../../database/server/fileService";
|
|
16
|
-
import { shareKey } from "../../../share/keys";
|
|
17
|
-
import { DEFAULT_MODEL, getApiEndpoint } from "../../../ai/llm/providers";
|
|
18
|
-
import type { AssistantToolCall, ToolExecutionContext } from "./types";
|
|
19
|
-
import {
|
|
20
|
-
buildSkillDocMarkdown,
|
|
21
|
-
resolvePageSkillMetadata,
|
|
22
|
-
parseSkillDocProtocol,
|
|
23
|
-
parseExternalSkillMarkdown,
|
|
24
|
-
type SkillDocConfig,
|
|
25
|
-
} from "../../../ai/skills/skillDocProtocol";
|
|
26
|
-
import {
|
|
27
|
-
buildSkillDocFromArgs,
|
|
28
|
-
type CreateSkillDocArgs,
|
|
29
|
-
} from "../../../ai/skills/skillDocBuilder";
|
|
30
|
-
import {
|
|
31
|
-
diagnoseSkillDocument,
|
|
32
|
-
evaluateSkillDocument,
|
|
33
|
-
} from "../../../ai/skills/skillDiagnostics";
|
|
34
|
-
import {
|
|
35
|
-
buildSkillAgentRecord,
|
|
36
|
-
type CreateSkillAgentToolArgs,
|
|
37
|
-
} from "../../../ai/tools/agent/skillAgentPreset";
|
|
38
|
-
import {
|
|
39
|
-
prepareAgentDraftToolFunc,
|
|
40
|
-
type PrepareAgentDraftToolArgs,
|
|
41
|
-
} from "../../../ai/tools/agent/prepareAgentDraftTool";
|
|
42
|
-
import type { CreateAgentToolArgs } from "../../../ai/tools/agent/createAgentTool";
|
|
43
|
-
import {
|
|
44
|
-
guardDestructiveAction,
|
|
45
|
-
guardPublicTableShare,
|
|
46
|
-
guardKnowledgeCapture,
|
|
47
|
-
isDestructiveShellCommand,
|
|
48
|
-
guardWorkspaceRead,
|
|
49
|
-
recordKnowledgeCapture,
|
|
50
|
-
recordWorkspaceRead,
|
|
51
|
-
} from "./toolPolicyGuards";
|
|
52
|
-
import { buildReadDocResult } from "../../../ai/tools/readDocTool";
|
|
53
|
-
import { buildSkillFollowupResult } from "../../../ai/tools/skillFollowup";
|
|
54
|
-
import { runZiweiChart } from "../../../ai/tools/ziweiChartTool";
|
|
55
|
-
import { evaluateSmallVisualEditGuard } from "../../../ai/tools/appEditGuard";
|
|
56
|
-
import {
|
|
57
|
-
analyzeAppStyleSystem,
|
|
58
|
-
buildAppStyleSystemHint,
|
|
59
|
-
} from "../../../ai/tools/appReadSnapshot";
|
|
60
|
-
import {
|
|
61
|
-
calculateParallelBranchPricing,
|
|
62
|
-
normalizeBudgetCredits,
|
|
63
|
-
summarizeParallelBudget,
|
|
64
|
-
summarizeParallelCosts,
|
|
65
|
-
} from "../../../ai/tools/agent/parallelBudget";
|
|
66
|
-
import {
|
|
67
|
-
extractAgentRuntimeServerBase,
|
|
68
|
-
normalizeServerOrigin,
|
|
69
|
-
} from "../../../ai/agent/runtimeServerBase";
|
|
70
|
-
import { extractEmailVerificationArtifacts } from "../../../ai/tools/emailTools";
|
|
71
|
-
import { convertMarxistsBookToOfflineHtml } from "../../../ai/tools/marxistsOfflineBook";
|
|
72
|
-
import { formatMarxistsOfflineBookDisplayData } from "../../../ai/tools/convertMarxistsBookTool";
|
|
73
|
-
import {
|
|
74
|
-
formatJdProductDisplayData,
|
|
75
|
-
getKnownJdProductFallback,
|
|
76
|
-
hasSparseJdSpecifications,
|
|
77
|
-
isIncompleteProductData,
|
|
78
|
-
jdProductScraperFunc,
|
|
79
|
-
mergeJdProductData,
|
|
80
|
-
parseJdBrowserExtractedData,
|
|
81
|
-
} from "../../../ai/tools/jdProductScraperTool";
|
|
82
|
-
import {
|
|
83
|
-
buildDialogMessageSearchResults,
|
|
84
|
-
clampDialogSearchNumber,
|
|
85
|
-
normalizeDialogSearchText,
|
|
86
|
-
} from "../../../ai/tools/dialogMessageSearch";
|
|
87
|
-
import serverDb from "../../../database/server/db";
|
|
88
|
-
import { createSpaceKey } from "../../../create/space/spaceKeys";
|
|
89
|
-
import {
|
|
90
|
-
buildDeleteSpacesPreview,
|
|
91
|
-
filterSpaceDeletionCandidates,
|
|
92
|
-
resolveConfirmedSpaceDeletionTargets,
|
|
93
|
-
type SpaceMembershipLike,
|
|
94
|
-
type SpaceRecordLike,
|
|
95
|
-
} from "../../../ai/tools/deleteSpacesToolModel";
|
|
96
|
-
import { canonicalizeToolName } from "../../../ai/tools/toolNameAliases";
|
|
97
|
-
import {
|
|
98
|
-
runCompleteDialogGoalTool,
|
|
99
|
-
runCreateDialogGoalTool,
|
|
100
|
-
runCreateScheduledTaskTool,
|
|
101
|
-
runGetDialogGoalTool,
|
|
102
|
-
runNotifyUserTool,
|
|
103
|
-
runQueryModelUsageTool,
|
|
104
|
-
} from "./modelUsageToolHandlers";
|
|
105
|
-
import { runTaskRunTool } from "./taskRunToolHandler";
|
|
106
|
-
import { projectDialogActivityToSubjectRows } from "./tableActivityProjection";
|
|
107
|
-
import { resolveExistingDialogRef } from "./dialogLookup";
|
|
108
|
-
|
|
109
|
-
const APP_DEPLOY_POLL_INTERVAL_MS = 250;
|
|
110
|
-
const APP_DEPLOY_POLL_TIMEOUT_MS = 60_000;
|
|
111
|
-
const DEFAULT_PARALLEL_AGENT_BRANCH_TIMEOUT_MS = 10 * 60 * 1000;
|
|
112
|
-
const configuredParallelAgentBranchTimeoutMs = Number(
|
|
113
|
-
process.env.PARALLEL_AGENT_BRANCH_TIMEOUT_MS,
|
|
114
|
-
);
|
|
115
|
-
const PARALLEL_AGENT_BRANCH_TIMEOUT_MS =
|
|
116
|
-
Number.isFinite(configuredParallelAgentBranchTimeoutMs) &&
|
|
117
|
-
configuredParallelAgentBranchTimeoutMs > 0
|
|
118
|
-
? configuredParallelAgentBranchTimeoutMs
|
|
119
|
-
: DEFAULT_PARALLEL_AGENT_BRANCH_TIMEOUT_MS;
|
|
120
|
-
const IMAGE_GENERATION_TOOL_NAMES = new Set([
|
|
121
|
-
"geminiFlashImage",
|
|
122
|
-
"geminiProImagePreview",
|
|
123
|
-
"openAIGptImageGenerate",
|
|
124
|
-
"openAIGptImageEdit",
|
|
125
|
-
"openAIGptImage",
|
|
126
|
-
]);
|
|
127
|
-
const FEEDBACK_AGENT_ID = "01NOLOFEEDBACKA000000000R1";
|
|
128
|
-
|
|
129
|
-
const trimString = (value: unknown): string =>
|
|
130
|
-
typeof value === "string" ? value.trim() : "";
|
|
131
|
-
|
|
132
|
-
const normalizeStringArray = (value: unknown): string[] => {
|
|
133
|
-
if (Array.isArray(value)) {
|
|
134
|
-
return value.map(trimString).filter(Boolean);
|
|
135
|
-
}
|
|
136
|
-
if (typeof value === "string") {
|
|
137
|
-
return value.split(",").map((item) => item.trim()).filter(Boolean);
|
|
138
|
-
}
|
|
139
|
-
return [];
|
|
140
|
-
};
|
|
141
|
-
|
|
142
|
-
const normalizeAgentReferencesForServerCreate = (value: unknown) =>
|
|
143
|
-
Array.isArray(value)
|
|
144
|
-
? value
|
|
145
|
-
.filter((item): item is Record<string, unknown> =>
|
|
146
|
-
!!item && typeof item === "object" && !Array.isArray(item)
|
|
147
|
-
)
|
|
148
|
-
.map((item) => ({
|
|
149
|
-
dbKey: trimString(item.dbKey),
|
|
150
|
-
title: trimString(item.title),
|
|
151
|
-
type: trimString(item.type) || "knowledge",
|
|
152
|
-
}))
|
|
153
|
-
.filter((item) => item.dbKey)
|
|
154
|
-
: [];
|
|
155
|
-
|
|
156
|
-
const normalizeRunnableAgentModel = (provider: string, model: string) => {
|
|
157
|
-
try {
|
|
158
|
-
getApiEndpoint({ provider, model } as any);
|
|
159
|
-
return { provider, model };
|
|
160
|
-
} catch (error) {
|
|
161
|
-
if (
|
|
162
|
-
error instanceof Error &&
|
|
163
|
-
(error.message.includes("Unsupported provider") ||
|
|
164
|
-
error.message.includes("Custom provider URL is required"))
|
|
165
|
-
) {
|
|
166
|
-
return {
|
|
167
|
-
provider: DEFAULT_MODEL.provider,
|
|
168
|
-
model: DEFAULT_MODEL.name,
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
throw error;
|
|
172
|
-
}
|
|
173
|
-
};
|
|
174
|
-
|
|
175
|
-
const buildServerCreatedAgentRecord = (
|
|
176
|
-
userId: string,
|
|
177
|
-
args: CreateAgentToolArgs,
|
|
178
|
-
currentSpaceId?: string | null,
|
|
179
|
-
) => {
|
|
180
|
-
const name = trimString(args.name);
|
|
181
|
-
const model = trimString(args.model);
|
|
182
|
-
const provider = trimString(args.provider);
|
|
183
|
-
if (!name) throw new Error("createAgent: name is required");
|
|
184
|
-
if (!model) throw new Error("createAgent: model is required");
|
|
185
|
-
if (!provider) throw new Error("createAgent: provider is required");
|
|
186
|
-
const runnableModel = normalizeRunnableAgentModel(provider, model);
|
|
187
|
-
|
|
188
|
-
const now = Date.now();
|
|
189
|
-
const id = ulid();
|
|
190
|
-
const greeting =
|
|
191
|
-
typeof args.greeting === "string"
|
|
192
|
-
? args.greeting.trim()
|
|
193
|
-
: args.greeting && typeof args.greeting === "object"
|
|
194
|
-
? args.greeting
|
|
195
|
-
: undefined;
|
|
196
|
-
return {
|
|
197
|
-
id,
|
|
198
|
-
type: DataType.AGENT,
|
|
199
|
-
userId,
|
|
200
|
-
createdAt: now,
|
|
201
|
-
updatedAt: now,
|
|
202
|
-
dialogCount: 0,
|
|
203
|
-
messageCount: 0,
|
|
204
|
-
tokenCount: 0,
|
|
205
|
-
spaceId: currentSpaceId || undefined,
|
|
206
|
-
name,
|
|
207
|
-
model: runnableModel.model,
|
|
208
|
-
provider: runnableModel.provider,
|
|
209
|
-
prompt: trimString(args.prompt),
|
|
210
|
-
introduction: trimString(args.introduction),
|
|
211
|
-
...(greeting ? { greeting } : {}),
|
|
212
|
-
isPublic: args.isPublic === true,
|
|
213
|
-
tags: normalizeStringArray(args.tags),
|
|
214
|
-
tools: normalizeStringArray(args.tools),
|
|
215
|
-
references: normalizeAgentReferencesForServerCreate(args.references),
|
|
216
|
-
linkedSpaces: normalizeStringArray(args.linkedSpaces),
|
|
217
|
-
...(typeof args.temperature === "number" ? { temperature: args.temperature } : {}),
|
|
218
|
-
...(typeof args.top_p === "number" ? { top_p: args.top_p } : {}),
|
|
219
|
-
...(typeof args.frequency_penalty === "number"
|
|
220
|
-
? { frequency_penalty: args.frequency_penalty }
|
|
221
|
-
: {}),
|
|
222
|
-
...(typeof args.presence_penalty === "number"
|
|
223
|
-
? { presence_penalty: args.presence_penalty }
|
|
224
|
-
: {}),
|
|
225
|
-
...(typeof args.max_tokens === "number" ? { max_tokens: args.max_tokens } : {}),
|
|
226
|
-
...(args.reasoning_effort ? { reasoning_effort: args.reasoning_effort } : {}),
|
|
227
|
-
whitelist: args.isPublic === true ? [] : [],
|
|
228
|
-
};
|
|
229
|
-
};
|
|
230
|
-
const FEEDBACK_TABLE_ID = "01NOLOFEEDBACKT000000000R1";
|
|
231
|
-
const TASK_BOARD_TABLE_ID = "NOLOTASKBOARD";
|
|
232
|
-
const TASK_RUN_PRIMITIVE_TOOL_NAMES = new Set([
|
|
233
|
-
"readTaskContext",
|
|
234
|
-
"queryReadyWorkItems",
|
|
235
|
-
"upsertWorkItem",
|
|
236
|
-
"claimWorkItem",
|
|
237
|
-
"openDialog",
|
|
238
|
-
"recordArtifact",
|
|
239
|
-
"setBlocker",
|
|
240
|
-
"clearBlocker",
|
|
241
|
-
"requestReview",
|
|
242
|
-
"recordReview",
|
|
243
|
-
"submitOutcome",
|
|
244
|
-
"closeWorkItem",
|
|
245
|
-
]);
|
|
246
|
-
const SEARCH_DIALOG_MESSAGES_SCAN_LIMIT = 500;
|
|
247
|
-
const SEARCH_DIALOG_MESSAGES_RESULT_LIMIT = 10;
|
|
248
|
-
const SEARCH_DIALOG_MESSAGES_CONTEXT_LIMIT = 3;
|
|
249
|
-
const SEARCH_DIALOG_MESSAGES_CLIP_CHARS = 1800;
|
|
250
|
-
const SEARCH_DIALOG_MESSAGES_CONTEXT_CLIP_CHARS = 600;
|
|
251
|
-
|
|
252
|
-
const sanitizeGeneratedHtmlFileName = (value: unknown, fallback: string): string => {
|
|
253
|
-
const raw = typeof value === "string" && value.trim() ? value.trim() : fallback;
|
|
254
|
-
const sanitized =
|
|
255
|
-
raw
|
|
256
|
-
.replace(/[\\/:*?"<>|]+/g, "-")
|
|
257
|
-
.replace(/\s+/g, "-")
|
|
258
|
-
.replace(/-+/g, "-")
|
|
259
|
-
.replace(/^-|-$/g, "")
|
|
260
|
-
.slice(0, 100) || fallback;
|
|
261
|
-
return /\.html?$/i.test(sanitized) ? sanitized : `${sanitized}.html`;
|
|
262
|
-
};
|
|
263
|
-
|
|
264
|
-
const buildFileContentUrl = (base: string, fileDbKey: string): string =>
|
|
265
|
-
`${base}/api/v1/db/file/content/${encodeURIComponent(fileDbKey)}`;
|
|
266
|
-
|
|
267
|
-
const normalizeBase = (base: string): string => base.replace(/\/+$/, "");
|
|
268
|
-
|
|
269
|
-
const normalizeSubjectRefs = (value: unknown): Array<{ kind: string; id: string; role?: string }> => {
|
|
270
|
-
if (!Array.isArray(value)) return [];
|
|
271
|
-
return value
|
|
272
|
-
.map((item) => {
|
|
273
|
-
if (!item || typeof item !== "object") return null;
|
|
274
|
-
const raw = item as Record<string, unknown>;
|
|
275
|
-
const kind = typeof raw.kind === "string" ? raw.kind.trim() : "";
|
|
276
|
-
const id = typeof raw.id === "string" ? raw.id.trim() : "";
|
|
277
|
-
if (!kind || !id) return null;
|
|
278
|
-
const role = typeof raw.role === "string" && raw.role.trim() ? raw.role.trim() : undefined;
|
|
279
|
-
return { kind, id, ...(role ? { role } : {}) };
|
|
280
|
-
})
|
|
281
|
-
.filter((item): item is { kind: string; id: string; role?: string } => Boolean(item));
|
|
282
|
-
};
|
|
283
|
-
|
|
284
|
-
function mergeSubjectRefs(
|
|
285
|
-
...refGroups: unknown[]
|
|
286
|
-
): Array<{ kind: string; id: string; role?: string }> {
|
|
287
|
-
const merged: Array<{ kind: string; id: string; role?: string }> = [];
|
|
288
|
-
const seen = new Set<string>();
|
|
289
|
-
for (const ref of refGroups.flatMap((group) => normalizeSubjectRefs(group))) {
|
|
290
|
-
const key = `${ref.kind}\u0000${ref.id}\u0000${ref.role ?? ""}`;
|
|
291
|
-
if (seen.has(key)) continue;
|
|
292
|
-
seen.add(key);
|
|
293
|
-
merged.push(ref);
|
|
294
|
-
}
|
|
295
|
-
return merged;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
const resolveSameOriginChildRunBase = (targetBase: string, mainBase: string) => {
|
|
299
|
-
if (normalizeServerOrigin(targetBase) !== normalizeServerOrigin(mainBase)) {
|
|
300
|
-
return targetBase;
|
|
301
|
-
}
|
|
302
|
-
const port = process.env.HTTP_PORT;
|
|
303
|
-
if (!port) return targetBase;
|
|
304
|
-
const host = process.env.PLATFORM_SERVER_HOST || "127.0.0.1";
|
|
305
|
-
const loopbackHost =
|
|
306
|
-
host === "0.0.0.0" || host === "::" || host === "[::]" ? "127.0.0.1" : host;
|
|
307
|
-
return `http://${loopbackHost}:${port}`;
|
|
308
|
-
};
|
|
309
|
-
|
|
310
|
-
const generateShareToken = (): string => {
|
|
311
|
-
const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
312
|
-
const charsLen = chars.length;
|
|
313
|
-
const maxValid = 252;
|
|
314
|
-
let token = "";
|
|
315
|
-
while (token.length < 10) {
|
|
316
|
-
const bytes = new Uint8Array(16);
|
|
317
|
-
crypto.getRandomValues(bytes);
|
|
318
|
-
for (let i = 0; i < bytes.length && token.length < 10; i += 1) {
|
|
319
|
-
if (bytes[i] < maxValid) {
|
|
320
|
-
token += chars.charAt(bytes[i] % charsLen);
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
return token;
|
|
325
|
-
};
|
|
326
|
-
const normalizeTaskRunPrimitiveArgs = (
|
|
327
|
-
toolName: string,
|
|
328
|
-
args: Record<string, any>,
|
|
329
|
-
): Record<string, any> | null => {
|
|
330
|
-
if (!TASK_RUN_PRIMITIVE_TOOL_NAMES.has(toolName)) return null;
|
|
331
|
-
const dbKey = args.dbKey ?? args.rowDbKey;
|
|
332
|
-
const baseArgs = {
|
|
333
|
-
action: toolName,
|
|
334
|
-
...(typeof dbKey === "string" && dbKey.trim() ? { dbKey: dbKey.trim() } : {}),
|
|
335
|
-
...(typeof args.tenantId === "string" && args.tenantId.trim() ? { tenantId: args.tenantId.trim() } : {}),
|
|
336
|
-
...(typeof args.tableId === "string" && args.tableId.trim() ? { tableId: args.tableId.trim() } : {}),
|
|
337
|
-
...(typeof args.rowId === "string" && args.rowId.trim() ? { rowId: args.rowId.trim() } : {}),
|
|
338
|
-
};
|
|
339
|
-
|
|
340
|
-
if (toolName !== "upsertWorkItem" || Array.isArray(args.workItems)) {
|
|
341
|
-
return {
|
|
342
|
-
...baseArgs,
|
|
343
|
-
...args,
|
|
344
|
-
action: toolName,
|
|
345
|
-
...(typeof dbKey === "string" && dbKey.trim() ? { dbKey: dbKey.trim() } : {}),
|
|
346
|
-
rowDbKey: undefined,
|
|
347
|
-
};
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
const id = args.workItemId ?? args.itemId ?? args.id;
|
|
351
|
-
const title = args.title ?? args.summary ?? args.description;
|
|
352
|
-
return {
|
|
353
|
-
...baseArgs,
|
|
354
|
-
workItems: [
|
|
355
|
-
{
|
|
356
|
-
...(typeof id === "string" && id.trim() ? { id: id.trim() } : {}),
|
|
357
|
-
...(typeof args.kind === "string" && args.kind.trim()
|
|
358
|
-
? { kind: args.kind.trim() }
|
|
359
|
-
: typeof args.type === "string" && args.type.trim()
|
|
360
|
-
? { kind: args.type.trim() }
|
|
361
|
-
: {}),
|
|
362
|
-
...(typeof args.ownerAgent === "string" && args.ownerAgent.trim()
|
|
363
|
-
? { ownerAgent: args.ownerAgent.trim() }
|
|
364
|
-
: typeof args.owner === "string" && args.owner.trim()
|
|
365
|
-
? { ownerAgent: args.owner.trim() }
|
|
366
|
-
: typeof args.agentKey === "string" && args.agentKey.trim()
|
|
367
|
-
? { ownerAgent: args.agentKey.trim() }
|
|
368
|
-
: {}),
|
|
369
|
-
...(typeof title === "string" && title.trim() ? { title: title.trim() } : {}),
|
|
370
|
-
...(typeof args.status === "string" && args.status.trim()
|
|
371
|
-
? { status: args.status.trim() }
|
|
372
|
-
: {}),
|
|
373
|
-
...(Array.isArray(args.dependsOn) ? { dependsOn: args.dependsOn } : {}),
|
|
374
|
-
...(Array.isArray(args.writeScope) ? { writeScope: args.writeScope } : {}),
|
|
375
|
-
...(typeof args.reviewPolicy === "string" && args.reviewPolicy.trim()
|
|
376
|
-
? { reviewPolicy: args.reviewPolicy.trim() }
|
|
377
|
-
: {}),
|
|
378
|
-
},
|
|
379
|
-
],
|
|
380
|
-
};
|
|
381
|
-
};
|
|
382
|
-
const getAllowedRemoteServerBases = (): string[] =>
|
|
383
|
-
(process.env.AGENT_TOOL_ALLOWED_SERVER_BASES ?? "")
|
|
384
|
-
.split(",")
|
|
385
|
-
.map((base) => normalizeServerOrigin(base.trim()))
|
|
386
|
-
.filter((base): base is string => !!base);
|
|
387
|
-
|
|
388
|
-
const buildFanoutServerList = (
|
|
389
|
-
originServer: string,
|
|
390
|
-
syncServers: unknown,
|
|
391
|
-
): string[] => {
|
|
392
|
-
const normalizedOrigin = normalizeServerOrigin(originServer);
|
|
393
|
-
const candidates = Array.isArray(syncServers) ? syncServers : [];
|
|
394
|
-
const shouldIncludeNoloCluster =
|
|
395
|
-
!!normalizedOrigin &&
|
|
396
|
-
(/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/i.test(normalizedOrigin) ||
|
|
397
|
-
NOLO_CLUSTER_SERVERS.some(
|
|
398
|
-
(server) => normalizeServerOrigin(server) === normalizedOrigin,
|
|
399
|
-
));
|
|
400
|
-
return Array.from(
|
|
401
|
-
new Set(
|
|
402
|
-
[
|
|
403
|
-
normalizedOrigin,
|
|
404
|
-
...candidates,
|
|
405
|
-
...(shouldIncludeNoloCluster ? NOLO_CLUSTER_SERVERS : []),
|
|
406
|
-
]
|
|
407
|
-
.map((value) =>
|
|
408
|
-
typeof value === "string" ? normalizeServerOrigin(value) : null,
|
|
409
|
-
)
|
|
410
|
-
.filter((value): value is string => !!value),
|
|
411
|
-
),
|
|
412
|
-
);
|
|
413
|
-
};
|
|
414
|
-
|
|
415
|
-
export const resolveDelegatedServerBase = (
|
|
416
|
-
requestedBase: unknown,
|
|
417
|
-
mainBase: string,
|
|
418
|
-
): { ok: true; base: string } | { ok: false; error: string } => {
|
|
419
|
-
if (typeof requestedBase !== "string" || !requestedBase.trim()) {
|
|
420
|
-
return { ok: true, base: mainBase };
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
const requestedOrigin = normalizeServerOrigin(requestedBase.trim());
|
|
424
|
-
if (!requestedOrigin) {
|
|
425
|
-
return {
|
|
426
|
-
ok: false,
|
|
427
|
-
error: `Invalid serverBase: ${String(requestedBase)}`,
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
const mainOrigin = normalizeServerOrigin(mainBase);
|
|
432
|
-
const isLocalMain =
|
|
433
|
-
!!mainOrigin &&
|
|
434
|
-
/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/i.test(mainOrigin);
|
|
435
|
-
const isNoloClusterTarget = NOLO_CLUSTER_SERVERS.some(
|
|
436
|
-
(server) => normalizeServerOrigin(server) === requestedOrigin,
|
|
437
|
-
);
|
|
438
|
-
if (
|
|
439
|
-
requestedOrigin === mainOrigin ||
|
|
440
|
-
getAllowedRemoteServerBases().includes(requestedOrigin) ||
|
|
441
|
-
(isLocalMain && isNoloClusterTarget)
|
|
442
|
-
) {
|
|
443
|
-
return { ok: true, base: requestedOrigin };
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
return {
|
|
447
|
-
ok: false,
|
|
448
|
-
error:
|
|
449
|
-
`serverBase "${requestedOrigin}" is not allowed. ` +
|
|
450
|
-
"Add it to AGENT_TOOL_ALLOWED_SERVER_BASES before delegating current auth to a remote nolo server.",
|
|
451
|
-
};
|
|
452
|
-
};
|
|
453
|
-
|
|
454
|
-
export { extractAgentRuntimeServerBase, normalizeServerOrigin };
|
|
455
|
-
|
|
456
|
-
const buildDelegatedAgentInput = (task: string, input: unknown): string => {
|
|
457
|
-
if (input === undefined || input === null) return task;
|
|
458
|
-
if (typeof input === "string") {
|
|
459
|
-
return `${task}\n\n--- INPUT (text) ---\n${input}`;
|
|
460
|
-
}
|
|
461
|
-
return `${task}\n\n--- INPUT (json) ---\n${JSON.stringify(input, null, 2)}`;
|
|
462
|
-
};
|
|
463
|
-
|
|
464
|
-
const isHttpImageData = (value: unknown): boolean =>
|
|
465
|
-
typeof value === "string" && /^https?:\/\//i.test(value.trim());
|
|
466
|
-
|
|
467
|
-
const collectLatestImageUrlsFromMessages = (messages: unknown): string[] => {
|
|
468
|
-
if (!Array.isArray(messages)) return [];
|
|
469
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
470
|
-
const content = (messages[index] as any)?.content;
|
|
471
|
-
if (!Array.isArray(content)) continue;
|
|
472
|
-
const urls = content
|
|
473
|
-
.map((part) =>
|
|
474
|
-
part?.type === "image_url" && typeof part.image_url?.url === "string"
|
|
475
|
-
? part.image_url.url.trim()
|
|
476
|
-
: "",
|
|
477
|
-
)
|
|
478
|
-
.filter((url): url is string => isHttpImageData(url));
|
|
479
|
-
if (urls.length > 0) return [...new Set(urls)];
|
|
480
|
-
}
|
|
481
|
-
return [];
|
|
482
|
-
};
|
|
483
|
-
|
|
484
|
-
const fetchPersistedDialogImageUrls = async (
|
|
485
|
-
mainBase: string,
|
|
486
|
-
authToken: string,
|
|
487
|
-
dialogId?: string | null,
|
|
488
|
-
): Promise<string[]> => {
|
|
489
|
-
if (!dialogId) return [];
|
|
490
|
-
try {
|
|
491
|
-
const res = await fetch(`${mainBase}/rpc/getConvMsgs`, {
|
|
492
|
-
method: "POST",
|
|
493
|
-
headers: {
|
|
494
|
-
"Content-Type": "application/json",
|
|
495
|
-
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
|
|
496
|
-
},
|
|
497
|
-
body: JSON.stringify({ dialogId, limit: 80 }),
|
|
498
|
-
});
|
|
499
|
-
if (!res.ok) return [];
|
|
500
|
-
const messages = await res.json().catch(() => []);
|
|
501
|
-
return collectLatestImageUrlsFromMessages(messages);
|
|
502
|
-
} catch {
|
|
503
|
-
return [];
|
|
504
|
-
}
|
|
505
|
-
};
|
|
506
|
-
|
|
507
|
-
const resolveImageToolArgs = async (
|
|
508
|
-
toolName: string,
|
|
509
|
-
args: Record<string, any>,
|
|
510
|
-
mainBase: string,
|
|
511
|
-
authToken: string,
|
|
512
|
-
context?: ToolExecutionContext,
|
|
513
|
-
): Promise<Record<string, any>> => {
|
|
514
|
-
if (!IMAGE_GENERATION_TOOL_NAMES.has(toolName)) return args;
|
|
515
|
-
|
|
516
|
-
const images = Array.isArray(args.images) ? args.images : [];
|
|
517
|
-
if (images.some((image: any) => isHttpImageData(image?.data))) {
|
|
518
|
-
return args;
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
let fallbackUrls = Array.isArray(context?.imageUrls)
|
|
522
|
-
? context.imageUrls.filter((url) => isHttpImageData(url))
|
|
523
|
-
: [];
|
|
524
|
-
if (fallbackUrls.length === 0) {
|
|
525
|
-
fallbackUrls = await fetchPersistedDialogImageUrls(
|
|
526
|
-
mainBase,
|
|
527
|
-
authToken,
|
|
528
|
-
context?.dialogId,
|
|
529
|
-
);
|
|
530
|
-
}
|
|
531
|
-
if (fallbackUrls.length === 0) return args;
|
|
532
|
-
|
|
533
|
-
return {
|
|
534
|
-
...args,
|
|
535
|
-
images: fallbackUrls.slice(0, Math.max(1, images.length)).map((url) => ({
|
|
536
|
-
data: url,
|
|
537
|
-
})),
|
|
538
|
-
};
|
|
539
|
-
};
|
|
540
|
-
|
|
541
|
-
const normalizeSkillImportUrl = (rawUrl: string): string => {
|
|
542
|
-
const trimmed = rawUrl.trim();
|
|
543
|
-
const githubBlobMatch = trimmed.match(
|
|
544
|
-
/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/blob\/([^/]+)\/(.+)$/,
|
|
545
|
-
);
|
|
546
|
-
if (githubBlobMatch) {
|
|
547
|
-
const [, owner, repo, ref, path] = githubBlobMatch;
|
|
548
|
-
return `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${path}`;
|
|
549
|
-
}
|
|
550
|
-
return trimmed;
|
|
551
|
-
};
|
|
552
|
-
|
|
553
|
-
const withTaskRunContext = (
|
|
554
|
-
args: Record<string, any>,
|
|
555
|
-
context?: ToolExecutionContext,
|
|
556
|
-
): Record<string, any> => {
|
|
557
|
-
const hasExplicitRowTarget =
|
|
558
|
-
(typeof args.dbKey === "string" && args.dbKey.trim()) ||
|
|
559
|
-
(typeof args.tenantId === "string" && args.tenantId.trim() &&
|
|
560
|
-
typeof args.tableId === "string" && args.tableId.trim() &&
|
|
561
|
-
typeof args.rowId === "string" && args.rowId.trim());
|
|
562
|
-
if (hasExplicitRowTarget) return args;
|
|
563
|
-
const rowDbKey =
|
|
564
|
-
typeof context?.runtimeContext?.taskRun?.rowDbKey === "string" &&
|
|
565
|
-
context.runtimeContext.taskRun.rowDbKey.trim()
|
|
566
|
-
? context.runtimeContext.taskRun.rowDbKey.trim()
|
|
567
|
-
: "";
|
|
568
|
-
return rowDbKey ? { ...args, dbKey: rowDbKey } : args;
|
|
569
|
-
};
|
|
570
|
-
|
|
571
|
-
function buildAgentHandoffUserInput(args: {
|
|
572
|
-
message: string;
|
|
573
|
-
parentDialogId?: string;
|
|
574
|
-
subjectRefs?: Array<{ kind: string; id: string; role?: string }>;
|
|
575
|
-
subjectEvidenceLines?: string[];
|
|
576
|
-
runtimeContext?: Record<string, any>;
|
|
577
|
-
}): string {
|
|
578
|
-
const taskRun = args.runtimeContext?.taskRun;
|
|
579
|
-
const rowDbKey =
|
|
580
|
-
typeof taskRun?.rowDbKey === "string" && taskRun.rowDbKey.trim()
|
|
581
|
-
? taskRun.rowDbKey.trim()
|
|
582
|
-
: "";
|
|
583
|
-
const workItemId =
|
|
584
|
-
typeof taskRun?.workItemId === "string" && taskRun.workItemId.trim()
|
|
585
|
-
? taskRun.workItemId.trim()
|
|
586
|
-
: "";
|
|
587
|
-
const artifactIds = Array.isArray(taskRun?.artifactIds)
|
|
588
|
-
? taskRun.artifactIds.filter((item: unknown): item is string => typeof item === "string" && Boolean(item.trim()))
|
|
589
|
-
: [];
|
|
590
|
-
const subjectRefs = args.subjectRefs?.filter((ref) => ref?.kind && ref?.id) ?? [];
|
|
591
|
-
const subjectEvidenceLines = args.subjectEvidenceLines?.filter(Boolean) ?? [];
|
|
592
|
-
if (!args.parentDialogId && !rowDbKey && !workItemId && artifactIds.length === 0 && subjectRefs.length === 0 && subjectEvidenceLines.length === 0) {
|
|
593
|
-
return args.message;
|
|
594
|
-
}
|
|
595
|
-
return [
|
|
596
|
-
"--- Nolo agent handoff context ---",
|
|
597
|
-
"This block is orientation for the receiving agent. It is not a workflow decision, review result, or replacement for inspecting durable records.",
|
|
598
|
-
...(args.parentDialogId ? [`- parentDialogId: ${args.parentDialogId}`] : []),
|
|
599
|
-
...(rowDbKey ? [`- task row: ${rowDbKey}`] : []),
|
|
600
|
-
...(workItemId ? [`- workItemId: ${workItemId}`] : []),
|
|
601
|
-
...(artifactIds.length ? [`- artifactIds: ${artifactIds.join(",")}`] : []),
|
|
602
|
-
...(subjectRefs.length
|
|
603
|
-
? [
|
|
604
|
-
"- subjectRefs:",
|
|
605
|
-
...subjectRefs.map((ref) => ` - ${ref.kind}:${ref.id}${ref.role ? ` (${ref.role})` : ""}`),
|
|
606
|
-
]
|
|
607
|
-
: []),
|
|
608
|
-
...(subjectEvidenceLines.length
|
|
609
|
-
? [
|
|
610
|
-
"- referenced evidence snapshot (server-read durable facts at handoff time):",
|
|
611
|
-
...subjectEvidenceLines.map((line) => ` - ${line}`),
|
|
612
|
-
]
|
|
613
|
-
: []),
|
|
614
|
-
"- Start by reading the durable task context when task-run is available.",
|
|
615
|
-
"- To find the work evidence, inspect the task row fields that already exist: workItems.dialogIds, workItems.outcome, review.dialogId, activityRefs, agentRuns.dialogId/resultSummary, and artifactRefs.",
|
|
616
|
-
"- Use dialog read/search tools for exact wording or tool traces; do not infer completion or review status from this handoff text alone.",
|
|
617
|
-
"- Durable result channels include taskRun primitives such as submitOutcome, setBlocker, requestReview, recordReview, or closeWorkItem when they are available.",
|
|
618
|
-
"--- Handoff task ---",
|
|
619
|
-
args.message,
|
|
620
|
-
].join("\n");
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
const asPlainRecord = (value: unknown): Record<string, any> =>
|
|
624
|
-
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, any> : {};
|
|
625
|
-
|
|
626
|
-
const summarizeStringArray = (value: unknown, max = 6): string[] => {
|
|
627
|
-
if (!Array.isArray(value)) return [];
|
|
628
|
-
const items = value
|
|
629
|
-
.filter((item): item is string => typeof item === "string" && Boolean(item.trim()))
|
|
630
|
-
.map((item) => item.trim());
|
|
631
|
-
return items.length > max ? [...items.slice(0, max), `+${items.length - max} more`] : items;
|
|
632
|
-
};
|
|
633
|
-
|
|
634
|
-
const clipEvidenceText = (value: unknown, max = 220): string => {
|
|
635
|
-
if (typeof value !== "string") return "";
|
|
636
|
-
const compact = value.replace(/\s+/g, " ").trim();
|
|
637
|
-
return compact.length > max ? `${compact.slice(0, max - 3)}...` : compact;
|
|
638
|
-
};
|
|
639
|
-
|
|
640
|
-
async function buildReferencedDialogEvidenceLines(args: {
|
|
641
|
-
subjectRefs: Array<{ kind: string; id: string; role?: string }>;
|
|
642
|
-
userId?: string | null;
|
|
643
|
-
}): Promise<string[]> {
|
|
644
|
-
const lines: string[] = [];
|
|
645
|
-
const seenDialogIds = new Set<string>();
|
|
646
|
-
for (const ref of args.subjectRefs) {
|
|
647
|
-
if (ref.kind !== "dialog" || !ref.id.trim()) continue;
|
|
648
|
-
const dialogId = ref.id.trim();
|
|
649
|
-
if (seenDialogIds.has(dialogId)) continue;
|
|
650
|
-
seenDialogIds.add(dialogId);
|
|
651
|
-
try {
|
|
652
|
-
const resolved = await resolveExistingDialogRef({
|
|
653
|
-
dialogId,
|
|
654
|
-
preferredUserId: args.userId,
|
|
655
|
-
});
|
|
656
|
-
if (!resolved?.dialogRecord) {
|
|
657
|
-
lines.push(`dialog:${dialogId}${ref.role ? ` (${ref.role})` : ""} not found`);
|
|
658
|
-
continue;
|
|
659
|
-
}
|
|
660
|
-
const dialog = asPlainRecord(resolved.dialogRecord);
|
|
661
|
-
const runtimeCheckpoint = asPlainRecord(dialog.runtimeCheckpoint);
|
|
662
|
-
const artifacts = asPlainRecord(dialog.artifacts);
|
|
663
|
-
const workspaceProgress = asPlainRecord(runtimeCheckpoint.workspaceProgress);
|
|
664
|
-
const workspaceLease = asPlainRecord(dialog.workspaceLease ?? runtimeCheckpoint.workspaceLease);
|
|
665
|
-
const messageCount = await countDialogMessages(dialogId);
|
|
666
|
-
const changedFiles = summarizeStringArray(
|
|
667
|
-
artifacts.changedFiles ?? workspaceProgress.changedFiles ?? workspaceLease.changedFiles,
|
|
668
|
-
);
|
|
669
|
-
const workspaceRoot = typeof workspaceLease.workspaceRoot === "string" && workspaceLease.workspaceRoot.trim()
|
|
670
|
-
? workspaceLease.workspaceRoot.trim()
|
|
671
|
-
: typeof workspaceProgress.workspaceRoot === "string" && workspaceProgress.workspaceRoot.trim()
|
|
672
|
-
? workspaceProgress.workspaceRoot.trim()
|
|
673
|
-
: "";
|
|
674
|
-
const status = typeof dialog.status === "string" && dialog.status.trim()
|
|
675
|
-
? dialog.status.trim()
|
|
676
|
-
: "unknown";
|
|
677
|
-
const runtimeStatus = typeof runtimeCheckpoint.status === "string" && runtimeCheckpoint.status.trim()
|
|
678
|
-
? runtimeCheckpoint.status.trim()
|
|
679
|
-
: "none";
|
|
680
|
-
const summary = clipEvidenceText(
|
|
681
|
-
dialog.resultSummary ?? runtimeCheckpoint.lastAssistantText ?? dialog.title,
|
|
682
|
-
);
|
|
683
|
-
lines.push(
|
|
684
|
-
[
|
|
685
|
-
`dialog:${dialogId}${ref.role ? ` (${ref.role})` : ""}`,
|
|
686
|
-
`status=${status}`,
|
|
687
|
-
`runtimeStatus=${runtimeStatus}`,
|
|
688
|
-
`messagesCount=${messageCount.count}${messageCount.truncated ? "+" : ""}`,
|
|
689
|
-
`artifacts=${Object.keys(artifacts).length ? "present" : "none"}`,
|
|
690
|
-
...(workspaceRoot ? [`workspace=${workspaceRoot}`] : []),
|
|
691
|
-
`changedFiles=${changedFiles.length ? changedFiles.join(",") : "none"}`,
|
|
692
|
-
...(summary ? [`summary="${summary}"`] : []),
|
|
693
|
-
].join(" "),
|
|
694
|
-
);
|
|
695
|
-
} catch (error) {
|
|
696
|
-
const detail = error instanceof Error && error.message ? error.message : "read failed";
|
|
697
|
-
lines.push(`dialog:${dialogId}${ref.role ? ` (${ref.role})` : ""} unavailable: ${detail}`);
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
return lines;
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
async function countDialogMessages(dialogId: string, max = 200): Promise<{ count: number; truncated: boolean }> {
|
|
704
|
-
let count = 0;
|
|
705
|
-
const gte = createKey(DataType.DIALOG, dialogId, "msg", "");
|
|
706
|
-
const lte = createKey(DataType.DIALOG, dialogId, "msg", "\uffff");
|
|
707
|
-
for await (const _ of serverDb.iterator({ gte, lte })) {
|
|
708
|
-
count += 1;
|
|
709
|
-
if (count > max) return { count: max, truncated: true };
|
|
710
|
-
}
|
|
711
|
-
return { count, truncated: false };
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
const looksLikeLocalFilePath = (value: unknown): value is string => {
|
|
715
|
-
if (typeof value !== "string") return false;
|
|
716
|
-
const trimmed = value.trim();
|
|
717
|
-
if (!trimmed) return false;
|
|
718
|
-
return (
|
|
719
|
-
trimmed.startsWith("/") ||
|
|
720
|
-
trimmed.startsWith("./") ||
|
|
721
|
-
trimmed.startsWith("../") ||
|
|
722
|
-
trimmed.includes("/") ||
|
|
723
|
-
/\.[A-Za-z0-9_-]{1,12}$/.test(trimmed)
|
|
724
|
-
);
|
|
725
|
-
};
|
|
726
|
-
|
|
727
|
-
const normalizeToolExecutionArgs = (
|
|
728
|
-
toolName: string,
|
|
729
|
-
args: Record<string, any>,
|
|
730
|
-
): Record<string, any> => {
|
|
731
|
-
if (toolName === "execShell") {
|
|
732
|
-
const command =
|
|
733
|
-
args.command ??
|
|
734
|
-
args.runCommand ??
|
|
735
|
-
args.run_command ??
|
|
736
|
-
args.terminalCommand ??
|
|
737
|
-
args.terminal_command ??
|
|
738
|
-
args.runInBash ??
|
|
739
|
-
args.run_in_bash ??
|
|
740
|
-
args.executeCommand ??
|
|
741
|
-
args.execute_command ??
|
|
742
|
-
args.execShell ??
|
|
743
|
-
args.bash ??
|
|
744
|
-
args.cmd;
|
|
745
|
-
return command == null ? args : { ...args, command };
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
if (toolName === "readFile") {
|
|
749
|
-
const filePath = args.filePath ?? args.path ?? args.filename ?? args.file;
|
|
750
|
-
return filePath == null ? args : { ...args, filePath };
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
if (toolName === "read") {
|
|
754
|
-
const filePath = args.filePath ?? args.path ?? args.filename ?? args.file;
|
|
755
|
-
if (filePath != null) return { ...args, filePath };
|
|
756
|
-
if (process.env.NOLO_DESKTOP === "1" && looksLikeLocalFilePath(args.dbKey)) {
|
|
757
|
-
return { ...args, filePath: args.dbKey };
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
return args;
|
|
762
|
-
};
|
|
763
|
-
|
|
764
|
-
export async function executeToolOnServer(
|
|
765
|
-
toolCall: AssistantToolCall,
|
|
766
|
-
serverBase: string,
|
|
767
|
-
authToken: string,
|
|
768
|
-
context?: ToolExecutionContext,
|
|
769
|
-
): Promise<string> {
|
|
770
|
-
const mainBase = normalizeBase(serverBase);
|
|
771
|
-
const rawToolName = (toolCall.function.name || "").replace(/^functions\./, "").trim();
|
|
772
|
-
const toolName = canonicalizeToolName(rawToolName);
|
|
773
|
-
let args: Record<string, any> = {};
|
|
774
|
-
try {
|
|
775
|
-
args = JSON.parse(toolCall.function.arguments || "{}");
|
|
776
|
-
} catch {
|
|
777
|
-
return JSON.stringify({ error: "Invalid tool arguments JSON" });
|
|
778
|
-
}
|
|
779
|
-
args = normalizeToolExecutionArgs(toolName, args);
|
|
780
|
-
args = await resolveImageToolArgs(toolName, args, mainBase, authToken, context);
|
|
781
|
-
|
|
782
|
-
const currentAgentKey =
|
|
783
|
-
typeof context?.agentKey === "string" && context.agentKey.trim()
|
|
784
|
-
? context.agentKey.trim()
|
|
785
|
-
: "";
|
|
786
|
-
const buildAuthHeaders = (): Record<string, string> => {
|
|
787
|
-
const headers: Record<string, string> = {};
|
|
788
|
-
if (authToken) {
|
|
789
|
-
headers.Authorization = `Bearer ${authToken}`;
|
|
790
|
-
headers.Cookie = `${WEB_AUTH_TOKEN_COOKIE}=${encodeURIComponent(authToken)}`;
|
|
791
|
-
}
|
|
792
|
-
if (currentAgentKey) {
|
|
793
|
-
headers["X-Nolo-Agent-Key"] = currentAgentKey;
|
|
794
|
-
}
|
|
795
|
-
return headers;
|
|
796
|
-
};
|
|
797
|
-
|
|
798
|
-
const post = async (
|
|
799
|
-
base: string,
|
|
800
|
-
path: string,
|
|
801
|
-
body: object
|
|
802
|
-
): Promise<string> => {
|
|
803
|
-
const headers: Record<string, string> = {
|
|
804
|
-
"Content-Type": "application/json",
|
|
805
|
-
...buildAuthHeaders(),
|
|
806
|
-
};
|
|
807
|
-
|
|
808
|
-
const res = await fetch(`${base}${path}`, {
|
|
809
|
-
method: "POST",
|
|
810
|
-
headers,
|
|
811
|
-
body: JSON.stringify(body),
|
|
812
|
-
});
|
|
813
|
-
if (!res.ok) {
|
|
814
|
-
return JSON.stringify({ error: `HTTP ${res.status}`, detail: await res.text() });
|
|
815
|
-
}
|
|
816
|
-
return res.text();
|
|
817
|
-
};
|
|
818
|
-
|
|
819
|
-
const postJson = async (
|
|
820
|
-
base: string,
|
|
821
|
-
path: string,
|
|
822
|
-
body: object,
|
|
823
|
-
): Promise<{
|
|
824
|
-
ok: boolean;
|
|
825
|
-
status: number;
|
|
826
|
-
text: string;
|
|
827
|
-
data: any;
|
|
828
|
-
}> => {
|
|
829
|
-
const headers: Record<string, string> = {
|
|
830
|
-
"Content-Type": "application/json",
|
|
831
|
-
...buildAuthHeaders(),
|
|
832
|
-
};
|
|
833
|
-
|
|
834
|
-
const res = await fetch(`${base}${path}`, {
|
|
835
|
-
method: "POST",
|
|
836
|
-
headers,
|
|
837
|
-
body: JSON.stringify(body),
|
|
838
|
-
});
|
|
839
|
-
const text = await res.text();
|
|
840
|
-
let data: any = null;
|
|
841
|
-
try {
|
|
842
|
-
data = text ? JSON.parse(text) : null;
|
|
843
|
-
} catch {
|
|
844
|
-
data = null;
|
|
845
|
-
}
|
|
846
|
-
return {
|
|
847
|
-
ok: res.ok,
|
|
848
|
-
status: res.status,
|
|
849
|
-
text,
|
|
850
|
-
data,
|
|
851
|
-
};
|
|
852
|
-
};
|
|
853
|
-
|
|
854
|
-
const postMain = async (path: string, body: object): Promise<string> =>
|
|
855
|
-
post(resolveSameOriginChildRunBase(mainBase, mainBase), path, body);
|
|
856
|
-
|
|
857
|
-
const sleep = (ms: number) =>
|
|
858
|
-
new Promise((resolve) => setTimeout(resolve, ms));
|
|
859
|
-
|
|
860
|
-
const withDialogId = (body: Record<string, any>): Record<string, any> => {
|
|
861
|
-
if (!context?.dialogId || "dialogId" in body) return body;
|
|
862
|
-
return {
|
|
863
|
-
...body,
|
|
864
|
-
dialogId: context.dialogId,
|
|
865
|
-
};
|
|
866
|
-
};
|
|
867
|
-
|
|
868
|
-
const withFeedbackSubmitterUserId = (args: Record<string, any>): Record<string, any> => {
|
|
869
|
-
const agentKey = typeof context?.agentKey === "string" ? context.agentKey.trim() : "";
|
|
870
|
-
const userId = typeof context?.userId === "string" ? context.userId.trim() : "";
|
|
871
|
-
if (
|
|
872
|
-
!userId ||
|
|
873
|
-
!(
|
|
874
|
-
agentKey === `agent-pub-${FEEDBACK_AGENT_ID}` ||
|
|
875
|
-
agentKey.endsWith(`-${FEEDBACK_AGENT_ID}`)
|
|
876
|
-
)
|
|
877
|
-
) {
|
|
878
|
-
return args;
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
const tableId = typeof args.tableId === "string" ? args.tableId.trim() : "";
|
|
882
|
-
const values =
|
|
883
|
-
args.values && typeof args.values === "object" && !Array.isArray(args.values)
|
|
884
|
-
? args.values
|
|
885
|
-
: {};
|
|
886
|
-
if (tableId === FEEDBACK_TABLE_ID) {
|
|
887
|
-
return {
|
|
888
|
-
...args,
|
|
889
|
-
values: {
|
|
890
|
-
...values,
|
|
891
|
-
submitterUserId: values.submitterUserId || userId,
|
|
892
|
-
},
|
|
893
|
-
};
|
|
894
|
-
}
|
|
895
|
-
if (tableId === TASK_BOARD_TABLE_ID) {
|
|
896
|
-
return {
|
|
897
|
-
...args,
|
|
898
|
-
values: {
|
|
899
|
-
...values,
|
|
900
|
-
feedbackSubmitterUserId: values.feedbackSubmitterUserId || userId,
|
|
901
|
-
},
|
|
902
|
-
};
|
|
903
|
-
}
|
|
904
|
-
return args;
|
|
905
|
-
};
|
|
906
|
-
|
|
907
|
-
const deleteDbKey = async (dbKey: string): Promise<{ ok: boolean; status: number; text: string }> => {
|
|
908
|
-
const res = await fetch(`${mainBase}/api/v1/db/delete/${encodeURIComponent(dbKey)}`, {
|
|
909
|
-
method: "DELETE",
|
|
910
|
-
headers: buildAuthHeaders(),
|
|
911
|
-
});
|
|
912
|
-
return {
|
|
913
|
-
ok: res.ok,
|
|
914
|
-
status: res.status,
|
|
915
|
-
text: await res.text(),
|
|
916
|
-
};
|
|
917
|
-
};
|
|
918
|
-
|
|
919
|
-
const spaceMemberKeysForDelete = (spaceId: string, record: SpaceRecordLike): string[] => {
|
|
920
|
-
const memberIds = new Set<string>();
|
|
921
|
-
if (context?.userId) memberIds.add(context.userId);
|
|
922
|
-
if (Array.isArray(record.members)) {
|
|
923
|
-
for (const memberId of record.members) {
|
|
924
|
-
if (typeof memberId === "string" && memberId.trim()) {
|
|
925
|
-
memberIds.add(memberId.trim());
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
} else if (record.members && typeof record.members === "object") {
|
|
929
|
-
for (const memberId of Object.keys(record.members)) {
|
|
930
|
-
if (memberId.trim()) memberIds.add(memberId.trim());
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
return Array.from(memberIds).map((memberId) => createSpaceKey.member(memberId, spaceId));
|
|
934
|
-
};
|
|
935
|
-
const requireCurrentAgentKey = () => {
|
|
936
|
-
if (!currentAgentKey) {
|
|
937
|
-
return JSON.stringify({
|
|
938
|
-
error: "Current agent key is unavailable in server-side agent mode.",
|
|
939
|
-
});
|
|
940
|
-
}
|
|
941
|
-
return null;
|
|
942
|
-
};
|
|
943
|
-
const includesCaseInsensitive = (haystack: unknown, needle: unknown): boolean => {
|
|
944
|
-
const normalizedNeedle =
|
|
945
|
-
typeof needle === "string" && needle.trim() ? needle.trim().toLowerCase() : "";
|
|
946
|
-
if (!normalizedNeedle) return true;
|
|
947
|
-
const normalizedHaystack =
|
|
948
|
-
typeof haystack === "string" ? haystack.toLowerCase() : String(haystack || "").toLowerCase();
|
|
949
|
-
return normalizedHaystack.includes(normalizedNeedle);
|
|
950
|
-
};
|
|
951
|
-
const participantText = (participants: any): string =>
|
|
952
|
-
Array.isArray(participants)
|
|
953
|
-
? participants
|
|
954
|
-
.map((participant) =>
|
|
955
|
-
[participant?.name, participant?.email]
|
|
956
|
-
.filter((value) => typeof value === "string" && value.trim())
|
|
957
|
-
.join(" "),
|
|
958
|
-
)
|
|
959
|
-
.join("\n")
|
|
960
|
-
: "";
|
|
961
|
-
const EMAIL_WAIT_GRACE_MS = 10_000;
|
|
962
|
-
const parseEmailTimestamp = (value: unknown): number | null => {
|
|
963
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
964
|
-
return value;
|
|
965
|
-
}
|
|
966
|
-
if (typeof value === "string" && value.trim()) {
|
|
967
|
-
const parsed = Date.parse(value);
|
|
968
|
-
return Number.isFinite(parsed) ? parsed : null;
|
|
969
|
-
}
|
|
970
|
-
return null;
|
|
971
|
-
};
|
|
972
|
-
const emailReceivedAtMs = (email: any): number | null =>
|
|
973
|
-
parseEmailTimestamp(email?.meta?.provider?.receivedAt) ??
|
|
974
|
-
parseEmailTimestamp(email?.receivedAt) ??
|
|
975
|
-
parseEmailTimestamp(email?.createdAt) ??
|
|
976
|
-
parseEmailTimestamp(email?.updatedAt);
|
|
977
|
-
const emailMatchesWaitFilters = (email: any, waitArgs: Record<string, any>): boolean =>
|
|
978
|
-
includesCaseInsensitive(email?.subject, waitArgs.subjectContains) &&
|
|
979
|
-
includesCaseInsensitive(email?.from?.email, waitArgs.fromContains) &&
|
|
980
|
-
includesCaseInsensitive(participantText(email?.to), waitArgs.toContains) &&
|
|
981
|
-
includesCaseInsensitive(
|
|
982
|
-
[email?.subject, email?.text, email?.html].filter(Boolean).join("\n"),
|
|
983
|
-
waitArgs.bodyContains,
|
|
984
|
-
);
|
|
985
|
-
const emailIsFreshForWait = (email: any, waitStartedAtMs: number): boolean => {
|
|
986
|
-
const receivedAtMs = emailReceivedAtMs(email);
|
|
987
|
-
if (receivedAtMs == null) return true;
|
|
988
|
-
return receivedAtMs >= waitStartedAtMs - EMAIL_WAIT_GRACE_MS;
|
|
989
|
-
};
|
|
990
|
-
|
|
991
|
-
const runChildAgent = async (
|
|
992
|
-
agentKey: string,
|
|
993
|
-
userInput: string,
|
|
994
|
-
requestedServerBase?: unknown,
|
|
995
|
-
requestedTimeoutMs?: unknown,
|
|
996
|
-
options?: {
|
|
997
|
-
background?: boolean;
|
|
998
|
-
parentDialogId?: string;
|
|
999
|
-
subjectRefs?: Array<{ kind: string; id: string; role?: string }>;
|
|
1000
|
-
idempotencyKey?: string;
|
|
1001
|
-
},
|
|
1002
|
-
) => {
|
|
1003
|
-
let effectiveRequestedServerBase = requestedServerBase;
|
|
1004
|
-
let autoRouted = false;
|
|
1005
|
-
const allowedRemoteServerBases = getAllowedRemoteServerBases();
|
|
1006
|
-
if (
|
|
1007
|
-
allowedRemoteServerBases.length > 0 &&
|
|
1008
|
-
(typeof requestedServerBase !== "string" || !requestedServerBase.trim())
|
|
1009
|
-
) {
|
|
1010
|
-
try {
|
|
1011
|
-
const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(agentKey)}`, {
|
|
1012
|
-
headers: buildAuthHeaders(),
|
|
1013
|
-
});
|
|
1014
|
-
if (res.ok) {
|
|
1015
|
-
const raw = await res.json();
|
|
1016
|
-
const agentRecord = raw?.data ?? raw;
|
|
1017
|
-
const runtimeServerBase = extractAgentRuntimeServerBase(agentRecord);
|
|
1018
|
-
const runtimeOrigin = runtimeServerBase
|
|
1019
|
-
? normalizeServerOrigin(runtimeServerBase)
|
|
1020
|
-
: null;
|
|
1021
|
-
const mainOrigin = normalizeServerOrigin(mainBase);
|
|
1022
|
-
if (runtimeOrigin && runtimeOrigin !== mainOrigin) {
|
|
1023
|
-
effectiveRequestedServerBase = runtimeOrigin;
|
|
1024
|
-
autoRouted = true;
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
} catch {
|
|
1028
|
-
// Best effort only. If metadata cannot be read, run on the current server.
|
|
1029
|
-
}
|
|
1030
|
-
}
|
|
1031
|
-
|
|
1032
|
-
const target = resolveDelegatedServerBase(effectiveRequestedServerBase, mainBase);
|
|
1033
|
-
if (!target.ok) {
|
|
1034
|
-
return {
|
|
1035
|
-
ok: false as const,
|
|
1036
|
-
status: 400,
|
|
1037
|
-
error: autoRouted
|
|
1038
|
-
? `${target.error} Target agent declares this runtime serverBase in its delegation metadata.`
|
|
1039
|
-
: target.error,
|
|
1040
|
-
};
|
|
1041
|
-
}
|
|
1042
|
-
|
|
1043
|
-
const childRunBase = resolveSameOriginChildRunBase(target.base, mainBase);
|
|
1044
|
-
const childSubjectRefs = mergeSubjectRefs(
|
|
1045
|
-
context?.runtimeContext?.subjectRefs,
|
|
1046
|
-
options?.subjectRefs,
|
|
1047
|
-
);
|
|
1048
|
-
const childRuntimeContext = options?.background || childSubjectRefs.length || options?.idempotencyKey
|
|
1049
|
-
? {
|
|
1050
|
-
...(context?.runtimeContext ?? {}),
|
|
1051
|
-
surface: context?.runtimeContext?.surface ?? "server-script",
|
|
1052
|
-
entrypoint:
|
|
1053
|
-
options?.background
|
|
1054
|
-
? "agent-tool:startAgentDialog"
|
|
1055
|
-
: context?.runtimeContext?.entrypoint ?? "agent-tool:callAgent",
|
|
1056
|
-
...(childSubjectRefs.length ? { subjectRefs: childSubjectRefs } : {}),
|
|
1057
|
-
...(options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),
|
|
1058
|
-
}
|
|
1059
|
-
: context?.runtimeContext;
|
|
1060
|
-
const res = await fetch(`${childRunBase}/api/agent/run`, {
|
|
1061
|
-
method: "POST",
|
|
1062
|
-
headers: { "Content-Type": "application/json", ...buildAuthHeaders() },
|
|
1063
|
-
body: JSON.stringify({
|
|
1064
|
-
agentKey,
|
|
1065
|
-
userInput,
|
|
1066
|
-
stream: false,
|
|
1067
|
-
...(options?.background ? { background: true } : {}),
|
|
1068
|
-
spaceId: context?.currentSpaceId ?? undefined,
|
|
1069
|
-
...(options?.parentDialogId ? { parentDialogId: options.parentDialogId } : {}),
|
|
1070
|
-
...(childRuntimeContext ? { runtimeContext: childRuntimeContext } : {}),
|
|
1071
|
-
...(typeof requestedTimeoutMs === "number" &&
|
|
1072
|
-
Number.isFinite(requestedTimeoutMs) &&
|
|
1073
|
-
requestedTimeoutMs > 0
|
|
1074
|
-
? { timeoutMs: requestedTimeoutMs }
|
|
1075
|
-
: {}),
|
|
1076
|
-
}),
|
|
1077
|
-
});
|
|
1078
|
-
if (!res.ok) {
|
|
1079
|
-
return {
|
|
1080
|
-
ok: false as const,
|
|
1081
|
-
status: res.status,
|
|
1082
|
-
error: await res.text(),
|
|
1083
|
-
};
|
|
1084
|
-
}
|
|
1085
|
-
const payload = await res.json();
|
|
1086
|
-
return {
|
|
1087
|
-
ok: true as const,
|
|
1088
|
-
payload,
|
|
1089
|
-
...(typeof effectiveRequestedServerBase === "string" && effectiveRequestedServerBase.trim()
|
|
1090
|
-
? { serverBase: target.base }
|
|
1091
|
-
: {}),
|
|
1092
|
-
...(autoRouted ? { autoRouted: true } : {}),
|
|
1093
|
-
};
|
|
1094
|
-
};
|
|
1095
|
-
|
|
1096
|
-
const waitForAppDeployResult = async (jobId: string) => {
|
|
1097
|
-
const deadline = Date.now() + APP_DEPLOY_POLL_TIMEOUT_MS;
|
|
1098
|
-
let latestPayload: any = null;
|
|
1099
|
-
|
|
1100
|
-
while (Date.now() < deadline) {
|
|
1101
|
-
const statusResult = await postJson(
|
|
1102
|
-
mainBase,
|
|
1103
|
-
"/api/app/deploy/status",
|
|
1104
|
-
{ jobId },
|
|
1105
|
-
);
|
|
1106
|
-
|
|
1107
|
-
if (!statusResult.ok) {
|
|
1108
|
-
return JSON.stringify(
|
|
1109
|
-
statusResult.data ?? {
|
|
1110
|
-
error: `appDeploy status: HTTP ${statusResult.status}`,
|
|
1111
|
-
detail: statusResult.text,
|
|
1112
|
-
},
|
|
1113
|
-
);
|
|
1114
|
-
}
|
|
1115
|
-
|
|
1116
|
-
latestPayload = statusResult.data;
|
|
1117
|
-
if (
|
|
1118
|
-
latestPayload?.status === "succeeded" ||
|
|
1119
|
-
latestPayload?.status === "failed"
|
|
1120
|
-
) {
|
|
1121
|
-
if (latestPayload.status === "succeeded" && latestPayload.result) {
|
|
1122
|
-
const result = latestPayload.result;
|
|
1123
|
-
return JSON.stringify({
|
|
1124
|
-
...result,
|
|
1125
|
-
jobId: latestPayload.jobId,
|
|
1126
|
-
status: latestPayload.status,
|
|
1127
|
-
summary: latestPayload.summary,
|
|
1128
|
-
steps: latestPayload.steps,
|
|
1129
|
-
appUrl: result.customUrl ?? result.url,
|
|
1130
|
-
});
|
|
1131
|
-
}
|
|
1132
|
-
return JSON.stringify(latestPayload);
|
|
1133
|
-
}
|
|
1134
|
-
|
|
1135
|
-
await sleep(APP_DEPLOY_POLL_INTERVAL_MS);
|
|
1136
|
-
}
|
|
1137
|
-
|
|
1138
|
-
return JSON.stringify({
|
|
1139
|
-
...(latestPayload && typeof latestPayload === "object"
|
|
1140
|
-
? latestPayload
|
|
1141
|
-
: {
|
|
1142
|
-
success: true,
|
|
1143
|
-
jobId,
|
|
1144
|
-
status: "pending",
|
|
1145
|
-
summary: "部署任务仍在进行中",
|
|
1146
|
-
}),
|
|
1147
|
-
timeout: true,
|
|
1148
|
-
nextAction:
|
|
1149
|
-
"部署任务还未完成。请稍后再次查询该 jobId,或等待服务端完成后再继续向用户确认最终访问链接。",
|
|
1150
|
-
});
|
|
1151
|
-
};
|
|
1152
|
-
|
|
1153
|
-
const normalizeAppFiles = () => {
|
|
1154
|
-
if (Array.isArray(args.files) && args.files.length > 0) return args.files;
|
|
1155
|
-
if (Array.isArray(args.pages) && args.pages.length > 0) return args.pages;
|
|
1156
|
-
return undefined;
|
|
1157
|
-
};
|
|
1158
|
-
const serverToolName = toolName;
|
|
1159
|
-
const taskRunPrimitiveArgs = normalizeTaskRunPrimitiveArgs(serverToolName, args);
|
|
1160
|
-
if (taskRunPrimitiveArgs) {
|
|
1161
|
-
return runTaskRunTool(withTaskRunContext(taskRunPrimitiveArgs, context), authToken);
|
|
1162
|
-
}
|
|
1163
|
-
|
|
1164
|
-
switch (serverToolName) {
|
|
1165
|
-
// ── 网络/外部 API(同构,前后端都能调,这里走服务端代理)──
|
|
1166
|
-
case "fetchWebpage":
|
|
1167
|
-
return postMain("/api/fetch-webpage", withDialogId({ url: args.url }));
|
|
1168
|
-
case "convertMarxistsBookToOfflineHtml": {
|
|
1169
|
-
const result = await convertMarxistsBookToOfflineHtml({
|
|
1170
|
-
startUrl: args.startUrl,
|
|
1171
|
-
encoding: args.encoding,
|
|
1172
|
-
maxPages: args.maxPages,
|
|
1173
|
-
fetchImpl: fetch,
|
|
1174
|
-
});
|
|
1175
|
-
const fileName = sanitizeGeneratedHtmlFileName(
|
|
1176
|
-
args.singleFileName,
|
|
1177
|
-
`${result.title || "marxists-offline-book"}.html`,
|
|
1178
|
-
);
|
|
1179
|
-
const rawData: Record<string, unknown> = {
|
|
1180
|
-
title: result.title,
|
|
1181
|
-
startUrl: result.startUrl,
|
|
1182
|
-
indexUrl: result.indexUrl,
|
|
1183
|
-
stylesheetUrl: result.stylesheetUrl,
|
|
1184
|
-
pages: result.pages,
|
|
1185
|
-
validation: result.validation,
|
|
1186
|
-
fileName,
|
|
1187
|
-
};
|
|
1188
|
-
if (args.saveAsFile !== false) {
|
|
1189
|
-
if (!context?.userId) {
|
|
1190
|
-
rawData.saveWarning =
|
|
1191
|
-
"saveAsFile was requested, but the server tool execution context has no userId.";
|
|
1192
|
-
} else {
|
|
1193
|
-
const { fileId, metadata } = await saveBufferAsFile(
|
|
1194
|
-
Buffer.from(result.html, "utf8"),
|
|
1195
|
-
{
|
|
1196
|
-
tenantId: context.userId,
|
|
1197
|
-
originalName: fileName,
|
|
1198
|
-
mimeType: "text/html; charset=utf-8",
|
|
1199
|
-
ownerType: "user",
|
|
1200
|
-
ownerId: context.userId,
|
|
1201
|
-
uploadedBy: context.userId,
|
|
1202
|
-
source: "ai-generated",
|
|
1203
|
-
model: "convertMarxistsBookToOfflineHtml",
|
|
1204
|
-
prompt: result.startUrl,
|
|
1205
|
-
tags: ["offline-book", "marxists-org", "html"],
|
|
1206
|
-
clientMetadata: {
|
|
1207
|
-
fileCategory: "document",
|
|
1208
|
-
sourceUrl: result.startUrl,
|
|
1209
|
-
indexUrl: result.indexUrl,
|
|
1210
|
-
stylesheetUrl: result.stylesheetUrl,
|
|
1211
|
-
pageCount: result.validation.pageCount,
|
|
1212
|
-
},
|
|
1213
|
-
},
|
|
1214
|
-
);
|
|
1215
|
-
const fileDbKey =
|
|
1216
|
-
typeof (metadata as any).dbKey === "string"
|
|
1217
|
-
? (metadata as any).dbKey
|
|
1218
|
-
: `file-${context.userId}-${fileId}`;
|
|
1219
|
-
rawData.fileId = fileId;
|
|
1220
|
-
rawData.fileDbKey = fileDbKey;
|
|
1221
|
-
rawData.fileUrl = buildFileContentUrl(mainBase, fileDbKey);
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
|
-
if (args.outputMode === "html") {
|
|
1225
|
-
rawData.html = result.html;
|
|
1226
|
-
}
|
|
1227
|
-
return JSON.stringify({
|
|
1228
|
-
rawData,
|
|
1229
|
-
displayData: formatMarxistsOfflineBookDisplayData({
|
|
1230
|
-
...rawData,
|
|
1231
|
-
htmlIncluded: args.outputMode === "html",
|
|
1232
|
-
}),
|
|
1233
|
-
});
|
|
1234
|
-
}
|
|
1235
|
-
case "read_x_post":
|
|
1236
|
-
return postMain(
|
|
1237
|
-
"/api/read-x-post",
|
|
1238
|
-
withDialogId({
|
|
1239
|
-
url: args.url,
|
|
1240
|
-
keepOpen: args.keepOpen,
|
|
1241
|
-
profileDir: args.profileDir,
|
|
1242
|
-
headless: args.headless,
|
|
1243
|
-
}),
|
|
1244
|
-
);
|
|
1245
|
-
case "wereadGateway":
|
|
1246
|
-
return postMain(
|
|
1247
|
-
"/api/weread/gateway",
|
|
1248
|
-
withDialogId(args),
|
|
1249
|
-
);
|
|
1250
|
-
case "exa_search":
|
|
1251
|
-
return postMain(
|
|
1252
|
-
"/api/exa-search",
|
|
1253
|
-
withDialogId({
|
|
1254
|
-
query: args.query,
|
|
1255
|
-
numResults: args.numResults ?? 5,
|
|
1256
|
-
contents: args.contents,
|
|
1257
|
-
}),
|
|
1258
|
-
);
|
|
1259
|
-
case "youtubeScraper":
|
|
1260
|
-
case "ecommerceScraper":
|
|
1261
|
-
case "amazonProductScraper":
|
|
1262
|
-
return postMain(
|
|
1263
|
-
"/api/apify-actor",
|
|
1264
|
-
withDialogId({ actorId: args.actorId ?? serverToolName, input: args }),
|
|
1265
|
-
);
|
|
1266
|
-
case "taobaoTmallProductScraper":
|
|
1267
|
-
return postMain(
|
|
1268
|
-
"/api/apify-actor",
|
|
1269
|
-
withDialogId({
|
|
1270
|
-
actorId: "sian.agency~taobao-tmall-product-scraper",
|
|
1271
|
-
input: {
|
|
1272
|
-
operation: "productDetail",
|
|
1273
|
-
itemId: args.itemId,
|
|
1274
|
-
detailDepth: args.detailDepth ?? "full",
|
|
1275
|
-
},
|
|
1276
|
-
resultType: "datasetItems",
|
|
1277
|
-
}),
|
|
1278
|
-
);
|
|
1279
|
-
case "jdProductScraper": {
|
|
1280
|
-
const result = await jdProductScraperFunc({
|
|
1281
|
-
skuId: args.skuId,
|
|
1282
|
-
url: args.url,
|
|
1283
|
-
});
|
|
1284
|
-
const skuId = typeof result.rawData?.skuId === "string" ? result.rawData.skuId : "";
|
|
1285
|
-
if (
|
|
1286
|
-
skuId &&
|
|
1287
|
-
(isIncompleteProductData(result.rawData) ||
|
|
1288
|
-
hasSparseJdSpecifications(result.rawData))
|
|
1289
|
-
) {
|
|
1290
|
-
const mobileUrl = `https://item.m.jd.com/product/${skuId}.html`;
|
|
1291
|
-
const apifyText = await postMain(
|
|
1292
|
-
"/api/apify-actor",
|
|
1293
|
-
withDialogId({
|
|
1294
|
-
actorId: "apify~web-scraper",
|
|
1295
|
-
input: {
|
|
1296
|
-
startUrls: [{ url: mobileUrl }],
|
|
1297
|
-
maxPagesPerCrawl: 1,
|
|
1298
|
-
maxRequestRetries: 1,
|
|
1299
|
-
maxConcurrency: 1,
|
|
1300
|
-
proxyConfiguration: { useApifyProxy: true },
|
|
1301
|
-
pageFunction: `async function pageFunction(context) {
|
|
1302
|
-
await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
1303
|
-
return {
|
|
1304
|
-
url: context.request.url,
|
|
1305
|
-
itemOnly: window._itemOnly || null,
|
|
1306
|
-
itemInfo: window._itemInfo || null,
|
|
1307
|
-
priceInfo: window.__price || window._price || null,
|
|
1308
|
-
title: document.title,
|
|
1309
|
-
html: document.documentElement ? document.documentElement.innerHTML : ""
|
|
1310
|
-
};
|
|
1311
|
-
}`,
|
|
1312
|
-
},
|
|
1313
|
-
resultType: "datasetItems",
|
|
1314
|
-
}),
|
|
1315
|
-
);
|
|
1316
|
-
let apifyData: any = null;
|
|
1317
|
-
try {
|
|
1318
|
-
apifyData = JSON.parse(apifyText || "null");
|
|
1319
|
-
} catch {
|
|
1320
|
-
apifyData = null;
|
|
1321
|
-
}
|
|
1322
|
-
const browserItem = Array.isArray(apifyData) ? apifyData[0] : null;
|
|
1323
|
-
if (browserItem && typeof browserItem === "object" && !("error" in browserItem)) {
|
|
1324
|
-
const browserFallback = parseJdBrowserExtractedData(browserItem, {
|
|
1325
|
-
skuId,
|
|
1326
|
-
url: mobileUrl,
|
|
1327
|
-
});
|
|
1328
|
-
result.rawData = mergeJdProductData(result.rawData, browserFallback);
|
|
1329
|
-
}
|
|
1330
|
-
}
|
|
1331
|
-
if (skuId && isIncompleteProductData(result.rawData)) {
|
|
1332
|
-
const knownFallback = getKnownJdProductFallback(skuId);
|
|
1333
|
-
if (knownFallback) {
|
|
1334
|
-
result.rawData = mergeJdProductData(result.rawData, knownFallback);
|
|
1335
|
-
}
|
|
1336
|
-
}
|
|
1337
|
-
result.displayData = formatJdProductDisplayData(result.rawData);
|
|
1338
|
-
return JSON.stringify(result);
|
|
1339
|
-
}
|
|
1340
|
-
case "geminiFlashImage":
|
|
1341
|
-
case "geminiProImagePreview":
|
|
1342
|
-
return postMain("/api/gemini-image-preview", withDialogId(args));
|
|
1343
|
-
case "openAIGptImageGenerate":
|
|
1344
|
-
return postMain(
|
|
1345
|
-
"/api/openai-image",
|
|
1346
|
-
withDialogId({
|
|
1347
|
-
...args,
|
|
1348
|
-
operation: "generate",
|
|
1349
|
-
model: "gpt-image-2",
|
|
1350
|
-
})
|
|
1351
|
-
);
|
|
1352
|
-
case "openAIGptImageEdit":
|
|
1353
|
-
return postMain(
|
|
1354
|
-
"/api/openai-image",
|
|
1355
|
-
withDialogId({
|
|
1356
|
-
...args,
|
|
1357
|
-
operation: "edit",
|
|
1358
|
-
model: "gpt-image-2",
|
|
1359
|
-
})
|
|
1360
|
-
);
|
|
1361
|
-
case "openAIGptImage":
|
|
1362
|
-
return postMain("/api/openai-image", withDialogId(args));
|
|
1363
|
-
case "remotionRenderVideo":
|
|
1364
|
-
return postMain("/api/remotion/render", withDialogId(args));
|
|
1365
|
-
case "ui_ask_choice": {
|
|
1366
|
-
const question =
|
|
1367
|
-
typeof args.question === "string" ? args.question.trim() : "";
|
|
1368
|
-
const choices = Array.isArray(args.choices) ? args.choices : [];
|
|
1369
|
-
const blocking = args.blocking !== false;
|
|
1370
|
-
if (!question || choices.length === 0) {
|
|
1371
|
-
return JSON.stringify({
|
|
1372
|
-
error: "ui_ask_choice",
|
|
1373
|
-
detail: "ui_ask_choice 需要 question 和至少一个 choice。",
|
|
1374
|
-
});
|
|
1375
|
-
}
|
|
1376
|
-
return JSON.stringify({
|
|
1377
|
-
type: "ui_ask_choice",
|
|
1378
|
-
question,
|
|
1379
|
-
choices,
|
|
1380
|
-
blocking,
|
|
1381
|
-
});
|
|
1382
|
-
}
|
|
1383
|
-
case "queryModelUsage": {
|
|
1384
|
-
try {
|
|
1385
|
-
return JSON.stringify(await runQueryModelUsageTool(args, context));
|
|
1386
|
-
} catch (err: any) {
|
|
1387
|
-
return JSON.stringify({
|
|
1388
|
-
error: "queryModelUsage",
|
|
1389
|
-
detail: err?.message ?? String(err),
|
|
1390
|
-
});
|
|
1391
|
-
}
|
|
1392
|
-
}
|
|
1393
|
-
case "createScheduledTask": {
|
|
1394
|
-
try {
|
|
1395
|
-
return JSON.stringify(await runCreateScheduledTaskTool(args, context));
|
|
1396
|
-
} catch (err: any) {
|
|
1397
|
-
return JSON.stringify({
|
|
1398
|
-
error: "createScheduledTask",
|
|
1399
|
-
detail: err?.message ?? String(err),
|
|
1400
|
-
});
|
|
1401
|
-
}
|
|
1402
|
-
}
|
|
1403
|
-
case "createDialogGoal": {
|
|
1404
|
-
try {
|
|
1405
|
-
return JSON.stringify(await runCreateDialogGoalTool(args, context));
|
|
1406
|
-
} catch (err: any) {
|
|
1407
|
-
return JSON.stringify({
|
|
1408
|
-
error: "createDialogGoal",
|
|
1409
|
-
detail: err?.message ?? String(err),
|
|
1410
|
-
});
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
case "getDialogGoal": {
|
|
1414
|
-
try {
|
|
1415
|
-
return JSON.stringify(await runGetDialogGoalTool(args, context));
|
|
1416
|
-
} catch (err: any) {
|
|
1417
|
-
return JSON.stringify({
|
|
1418
|
-
error: "getDialogGoal",
|
|
1419
|
-
detail: err?.message ?? String(err),
|
|
1420
|
-
});
|
|
1421
|
-
}
|
|
1422
|
-
}
|
|
1423
|
-
case "completeDialogGoal": {
|
|
1424
|
-
try {
|
|
1425
|
-
return JSON.stringify(await runCompleteDialogGoalTool(args, context));
|
|
1426
|
-
} catch (err: any) {
|
|
1427
|
-
return JSON.stringify({
|
|
1428
|
-
error: "completeDialogGoal",
|
|
1429
|
-
detail: err?.message ?? String(err),
|
|
1430
|
-
});
|
|
1431
|
-
}
|
|
1432
|
-
}
|
|
1433
|
-
case "taskRun":
|
|
1434
|
-
return runTaskRunTool(withTaskRunContext(args, context), authToken);
|
|
1435
|
-
case "notifyUser": {
|
|
1436
|
-
try {
|
|
1437
|
-
return JSON.stringify(await runNotifyUserTool(args, context));
|
|
1438
|
-
} catch (err: any) {
|
|
1439
|
-
return JSON.stringify({
|
|
1440
|
-
error: "notifyUser",
|
|
1441
|
-
detail: err?.message ?? String(err),
|
|
1442
|
-
});
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
case "rememberMemory":
|
|
1446
|
-
return postMain("/api/memory/remember", withDialogId({
|
|
1447
|
-
content: args.content,
|
|
1448
|
-
scope: args.scope,
|
|
1449
|
-
spaceId: context?.currentSpaceId ?? undefined,
|
|
1450
|
-
}));
|
|
1451
|
-
case "callAgent": {
|
|
1452
|
-
const agentKey = typeof args.agentKey === "string" ? args.agentKey.trim() : "";
|
|
1453
|
-
const task = typeof args.task === "string" ? args.task.trim() : "";
|
|
1454
|
-
if (!agentKey) {
|
|
1455
|
-
return JSON.stringify({ error: "callAgent: agentKey is required" });
|
|
1456
|
-
}
|
|
1457
|
-
if (!task) {
|
|
1458
|
-
return JSON.stringify({ error: "callAgent: task is required" });
|
|
1459
|
-
}
|
|
1460
|
-
const childRun = await runChildAgent(
|
|
1461
|
-
agentKey,
|
|
1462
|
-
buildDelegatedAgentInput(task, args.input),
|
|
1463
|
-
args.serverBase,
|
|
1464
|
-
);
|
|
1465
|
-
if (!childRun.ok) {
|
|
1466
|
-
return JSON.stringify({
|
|
1467
|
-
error: `callAgent: HTTP ${childRun.status}`,
|
|
1468
|
-
detail: childRun.error,
|
|
1469
|
-
});
|
|
1470
|
-
}
|
|
1471
|
-
const payload = childRun.payload;
|
|
1472
|
-
return JSON.stringify({
|
|
1473
|
-
success: true,
|
|
1474
|
-
agentKey,
|
|
1475
|
-
...(childRun.serverBase ? { serverBase: childRun.serverBase } : {}),
|
|
1476
|
-
...(childRun.autoRouted ? { autoRouted: true } : {}),
|
|
1477
|
-
dialogId: payload?.dialogId ?? null,
|
|
1478
|
-
model: payload?.model ?? null,
|
|
1479
|
-
provider: payload?.provider ?? null,
|
|
1480
|
-
content: typeof payload?.content === "string" ? payload.content : "",
|
|
1481
|
-
usage: payload?.usage ?? null,
|
|
1482
|
-
artifacts: payload?.artifacts ?? null,
|
|
1483
|
-
});
|
|
1484
|
-
}
|
|
1485
|
-
case "runStreamingAgent": {
|
|
1486
|
-
const agentKey = typeof args.agentKey === "string" ? args.agentKey.trim() : "";
|
|
1487
|
-
const userInput = typeof args.userInput === "string" ? args.userInput.trim() : "";
|
|
1488
|
-
if (!agentKey) {
|
|
1489
|
-
return JSON.stringify({ error: "runStreamingAgent: agentKey is required" });
|
|
1490
|
-
}
|
|
1491
|
-
if (!userInput) {
|
|
1492
|
-
return JSON.stringify({ error: "runStreamingAgent: userInput is required" });
|
|
1493
|
-
}
|
|
1494
|
-
const childRun = await runChildAgent(agentKey, userInput, args.serverBase);
|
|
1495
|
-
if (!childRun.ok) {
|
|
1496
|
-
return JSON.stringify({
|
|
1497
|
-
error: `runStreamingAgent: HTTP ${childRun.status}`,
|
|
1498
|
-
detail: childRun.error,
|
|
1499
|
-
});
|
|
1500
|
-
}
|
|
1501
|
-
const payload = childRun.payload;
|
|
1502
|
-
return JSON.stringify({
|
|
1503
|
-
success: true,
|
|
1504
|
-
handoff: true,
|
|
1505
|
-
agentKey,
|
|
1506
|
-
...(childRun.serverBase ? { serverBase: childRun.serverBase } : {}),
|
|
1507
|
-
...(childRun.autoRouted ? { autoRouted: true } : {}),
|
|
1508
|
-
dialogId: payload?.dialogId ?? null,
|
|
1509
|
-
...(payload?.dialogKey ? { dialogKey: payload.dialogKey } : {}),
|
|
1510
|
-
model: payload?.model ?? null,
|
|
1511
|
-
content: typeof payload?.content === "string" ? payload.content : "",
|
|
1512
|
-
usage: payload?.usage ?? null,
|
|
1513
|
-
artifacts: payload?.artifacts ?? null,
|
|
1514
|
-
});
|
|
1515
|
-
}
|
|
1516
|
-
case "startAgentDialog": {
|
|
1517
|
-
const targetAgentKey =
|
|
1518
|
-
typeof args.targetAgentKey === "string"
|
|
1519
|
-
? args.targetAgentKey.trim()
|
|
1520
|
-
: typeof args.agentKey === "string"
|
|
1521
|
-
? args.agentKey.trim()
|
|
1522
|
-
: "";
|
|
1523
|
-
const message =
|
|
1524
|
-
typeof args.message === "string"
|
|
1525
|
-
? args.message.trim()
|
|
1526
|
-
: typeof args.userInput === "string"
|
|
1527
|
-
? args.userInput.trim()
|
|
1528
|
-
: "";
|
|
1529
|
-
if (!targetAgentKey) {
|
|
1530
|
-
return JSON.stringify({ error: "startAgentDialog: targetAgentKey is required" });
|
|
1531
|
-
}
|
|
1532
|
-
if (!message) {
|
|
1533
|
-
return JSON.stringify({ error: "startAgentDialog: message is required" });
|
|
1534
|
-
}
|
|
1535
|
-
const parentDialogId =
|
|
1536
|
-
typeof args.parentDialogId === "string" && args.parentDialogId.trim()
|
|
1537
|
-
? args.parentDialogId.trim()
|
|
1538
|
-
: typeof context?.dialogId === "string" && context.dialogId.trim()
|
|
1539
|
-
? context.dialogId.trim()
|
|
1540
|
-
: undefined;
|
|
1541
|
-
const timeoutMs =
|
|
1542
|
-
typeof args.timeoutMs === "number" && Number.isFinite(args.timeoutMs) && args.timeoutMs > 0
|
|
1543
|
-
? args.timeoutMs
|
|
1544
|
-
: undefined;
|
|
1545
|
-
const subjectRefs = normalizeSubjectRefs(args.subjectRefs);
|
|
1546
|
-
const childSubjectRefs = mergeSubjectRefs(
|
|
1547
|
-
context?.runtimeContext?.subjectRefs,
|
|
1548
|
-
subjectRefs,
|
|
1549
|
-
);
|
|
1550
|
-
const subjectEvidenceLines = await buildReferencedDialogEvidenceLines({
|
|
1551
|
-
subjectRefs: childSubjectRefs,
|
|
1552
|
-
userId: context?.userId,
|
|
1553
|
-
});
|
|
1554
|
-
const childMessage = buildAgentHandoffUserInput({
|
|
1555
|
-
message,
|
|
1556
|
-
parentDialogId,
|
|
1557
|
-
subjectRefs: childSubjectRefs,
|
|
1558
|
-
subjectEvidenceLines,
|
|
1559
|
-
runtimeContext: context?.runtimeContext,
|
|
1560
|
-
});
|
|
1561
|
-
const childRun = await runChildAgent(
|
|
1562
|
-
targetAgentKey,
|
|
1563
|
-
childMessage,
|
|
1564
|
-
args.serverBase,
|
|
1565
|
-
timeoutMs,
|
|
1566
|
-
{
|
|
1567
|
-
background: true,
|
|
1568
|
-
parentDialogId,
|
|
1569
|
-
subjectRefs: childSubjectRefs,
|
|
1570
|
-
...(typeof args.idempotencyKey === "string" && args.idempotencyKey.trim()
|
|
1571
|
-
? { idempotencyKey: args.idempotencyKey.trim() }
|
|
1572
|
-
: {}),
|
|
1573
|
-
},
|
|
1574
|
-
);
|
|
1575
|
-
if (!childRun.ok) {
|
|
1576
|
-
return JSON.stringify({
|
|
1577
|
-
error: `startAgentDialog: HTTP ${childRun.status}`,
|
|
1578
|
-
detail: childRun.error,
|
|
1579
|
-
});
|
|
1580
|
-
}
|
|
1581
|
-
const payload = childRun.payload;
|
|
1582
|
-
const childDialogId = typeof payload?.dialogId === "string" && payload.dialogId.trim()
|
|
1583
|
-
? payload.dialogId.trim()
|
|
1584
|
-
: "";
|
|
1585
|
-
const childDialogKey = typeof payload?.dialogKey === "string" && payload.dialogKey.trim()
|
|
1586
|
-
? payload.dialogKey.trim()
|
|
1587
|
-
: undefined;
|
|
1588
|
-
const activityProjection = childDialogId
|
|
1589
|
-
? await projectDialogActivityToSubjectRows({
|
|
1590
|
-
db: serverDb,
|
|
1591
|
-
subjectRefs: childSubjectRefs,
|
|
1592
|
-
activityRef: {
|
|
1593
|
-
type: "dialog",
|
|
1594
|
-
dialogId: childDialogId,
|
|
1595
|
-
...(childDialogKey ? { dialogKey: childDialogKey } : {}),
|
|
1596
|
-
role: "child-dialog",
|
|
1597
|
-
agentKey: targetAgentKey,
|
|
1598
|
-
...(parentDialogId ? { parentDialogId } : {}),
|
|
1599
|
-
status: typeof payload?.status === "string" && payload.status.trim()
|
|
1600
|
-
? payload.status.trim()
|
|
1601
|
-
: "pending",
|
|
1602
|
-
updatedAt: new Date().toISOString(),
|
|
1603
|
-
},
|
|
1604
|
-
})
|
|
1605
|
-
: undefined;
|
|
1606
|
-
return JSON.stringify({
|
|
1607
|
-
success: true,
|
|
1608
|
-
status: payload?.status ?? "pending",
|
|
1609
|
-
targetAgentKey,
|
|
1610
|
-
childDialogId: childDialogId || null,
|
|
1611
|
-
childDialogKey: childDialogKey ?? null,
|
|
1612
|
-
...(parentDialogId ? { parentDialogId } : {}),
|
|
1613
|
-
...(childRun.serverBase ? { serverBase: childRun.serverBase } : {}),
|
|
1614
|
-
...(childRun.autoRouted ? { autoRouted: true } : {}),
|
|
1615
|
-
...(activityProjection && activityProjection.updatedRowDbKeys.length
|
|
1616
|
-
? {
|
|
1617
|
-
activityProjection: {
|
|
1618
|
-
updatedRowDbKeys: activityProjection.updatedRowDbKeys,
|
|
1619
|
-
},
|
|
1620
|
-
}
|
|
1621
|
-
: {}),
|
|
1622
|
-
});
|
|
1623
|
-
}
|
|
1624
|
-
case "streamParallelAgents": {
|
|
1625
|
-
const task = typeof args.task === "string" ? args.task.trim() : "";
|
|
1626
|
-
const agents = Array.isArray(args.agents) ? args.agents : [];
|
|
1627
|
-
const returnMode = args.returnMode === "continue" ? "continue" : "handoff";
|
|
1628
|
-
const displayMode = "inline";
|
|
1629
|
-
const defaultServerBase = args.serverBase;
|
|
1630
|
-
const parallelSessionId = `parallel-${Date.now()}-${Math.random()
|
|
1631
|
-
.toString(36)
|
|
1632
|
-
.slice(2, 10)}`;
|
|
1633
|
-
const timeoutMs =
|
|
1634
|
-
typeof args.timeoutMs === "number" && Number.isFinite(args.timeoutMs) && args.timeoutMs > 0
|
|
1635
|
-
? args.timeoutMs
|
|
1636
|
-
: PARALLEL_AGENT_BRANCH_TIMEOUT_MS;
|
|
1637
|
-
const budgetCredits = normalizeBudgetCredits(args.budgetCredits);
|
|
1638
|
-
if (!task) {
|
|
1639
|
-
return JSON.stringify({ error: "streamParallelAgents: task is required" });
|
|
1640
|
-
}
|
|
1641
|
-
if (agents.length === 0) {
|
|
1642
|
-
return JSON.stringify({ error: "streamParallelAgents: agents is required" });
|
|
1643
|
-
}
|
|
1644
|
-
|
|
1645
|
-
const results = await Promise.all(
|
|
1646
|
-
agents.map(async (agent: Record<string, any>, index: number) => {
|
|
1647
|
-
const agentKey =
|
|
1648
|
-
typeof agent?.agentKey === "string" ? agent.agentKey.trim() : "";
|
|
1649
|
-
const label =
|
|
1650
|
-
typeof agent?.label === "string" && agent.label.trim()
|
|
1651
|
-
? agent.label.trim()
|
|
1652
|
-
: `Agent ${index + 1}`;
|
|
1653
|
-
const branchId =
|
|
1654
|
-
typeof agent?.branchId === "string" && agent.branchId.trim()
|
|
1655
|
-
? agent.branchId.trim()
|
|
1656
|
-
: `branch-${index + 1}`;
|
|
1657
|
-
if (!agentKey) {
|
|
1658
|
-
return {
|
|
1659
|
-
ok: false,
|
|
1660
|
-
label,
|
|
1661
|
-
branchId,
|
|
1662
|
-
agentKey,
|
|
1663
|
-
error: "missing agentKey",
|
|
1664
|
-
spentCredits: null,
|
|
1665
|
-
};
|
|
1666
|
-
}
|
|
1667
|
-
|
|
1668
|
-
const childRun = await Promise.race([
|
|
1669
|
-
runChildAgent(agentKey, task, agent?.serverBase ?? defaultServerBase, timeoutMs),
|
|
1670
|
-
sleep(timeoutMs).then(() => ({
|
|
1671
|
-
ok: false as const,
|
|
1672
|
-
status: 408,
|
|
1673
|
-
error: `branch timeout after ${timeoutMs}ms`,
|
|
1674
|
-
})),
|
|
1675
|
-
]);
|
|
1676
|
-
if (!childRun.ok) {
|
|
1677
|
-
return {
|
|
1678
|
-
ok: false,
|
|
1679
|
-
label,
|
|
1680
|
-
branchId,
|
|
1681
|
-
agentKey,
|
|
1682
|
-
error: childRun.error,
|
|
1683
|
-
status: childRun.status,
|
|
1684
|
-
authForwarded: Boolean(authToken),
|
|
1685
|
-
spentCredits: null,
|
|
1686
|
-
};
|
|
1687
|
-
}
|
|
1688
|
-
|
|
1689
|
-
const payload = childRun.payload;
|
|
1690
|
-
const pricing = calculateParallelBranchPricing({
|
|
1691
|
-
usage: payload?.usage,
|
|
1692
|
-
agentKey,
|
|
1693
|
-
dialogId: payload?.dialogId ?? null,
|
|
1694
|
-
agentConfig: {
|
|
1695
|
-
id: agentKey,
|
|
1696
|
-
model:
|
|
1697
|
-
typeof payload?.model === "string" ? payload.model : null,
|
|
1698
|
-
provider:
|
|
1699
|
-
typeof payload?.provider === "string"
|
|
1700
|
-
? payload.provider
|
|
1701
|
-
: null,
|
|
1702
|
-
inputPrice:
|
|
1703
|
-
typeof payload?.inputPrice === "number"
|
|
1704
|
-
? payload.inputPrice
|
|
1705
|
-
: null,
|
|
1706
|
-
outputPrice:
|
|
1707
|
-
typeof payload?.outputPrice === "number"
|
|
1708
|
-
? payload.outputPrice
|
|
1709
|
-
: null,
|
|
1710
|
-
},
|
|
1711
|
-
});
|
|
1712
|
-
return {
|
|
1713
|
-
ok: true,
|
|
1714
|
-
label,
|
|
1715
|
-
branchId,
|
|
1716
|
-
parallelSessionId,
|
|
1717
|
-
parallelIndex: index,
|
|
1718
|
-
agentKey,
|
|
1719
|
-
agentName: label,
|
|
1720
|
-
...(childRun.serverBase ? { serverBase: childRun.serverBase } : {}),
|
|
1721
|
-
...(childRun.autoRouted ? { autoRouted: true } : {}),
|
|
1722
|
-
dialogId: payload?.dialogId ?? null,
|
|
1723
|
-
model: payload?.model ?? null,
|
|
1724
|
-
provider: payload?.provider ?? null,
|
|
1725
|
-
content:
|
|
1726
|
-
typeof payload?.content === "string" ? payload.content.trim() : "",
|
|
1727
|
-
usage: payload?.usage ?? null,
|
|
1728
|
-
artifacts: payload?.artifacts ?? null,
|
|
1729
|
-
spentCredits: pricing.spentCredits,
|
|
1730
|
-
billedModel: pricing.billedModel,
|
|
1731
|
-
billedProvider: pricing.billedProvider,
|
|
1732
|
-
billingServiceTier: pricing.billingServiceTier,
|
|
1733
|
-
pricingError: pricing.pricingError,
|
|
1734
|
-
};
|
|
1735
|
-
}),
|
|
1736
|
-
);
|
|
1737
|
-
|
|
1738
|
-
const successful = results.filter((item) => item.ok);
|
|
1739
|
-
const costSummary = summarizeParallelCosts(results);
|
|
1740
|
-
const budget = summarizeParallelBudget({
|
|
1741
|
-
budgetCredits,
|
|
1742
|
-
results,
|
|
1743
|
-
});
|
|
1744
|
-
const stats = {
|
|
1745
|
-
total: results.length,
|
|
1746
|
-
succeeded: successful.length,
|
|
1747
|
-
failed: results.length - successful.length,
|
|
1748
|
-
};
|
|
1749
|
-
const mergedContent = successful
|
|
1750
|
-
.map((item) => `## ${item.label}\n\n${item.content || "(无内容)"}`)
|
|
1751
|
-
.join("\n\n");
|
|
1752
|
-
|
|
1753
|
-
return JSON.stringify({
|
|
1754
|
-
success: true,
|
|
1755
|
-
handoff: returnMode === "handoff",
|
|
1756
|
-
returnMode,
|
|
1757
|
-
displayMode,
|
|
1758
|
-
toolName: "streamParallelAgents",
|
|
1759
|
-
content: mergedContent,
|
|
1760
|
-
summary: `并行调用 ${stats.total} 个 Agent · ${stats.succeeded} 成功 · ${stats.failed} 失败`,
|
|
1761
|
-
stats,
|
|
1762
|
-
costSummary,
|
|
1763
|
-
...(budget ? { budget } : {}),
|
|
1764
|
-
parallelSessionId,
|
|
1765
|
-
results,
|
|
1766
|
-
timeoutMs,
|
|
1767
|
-
usage: successful.map((item) => item.usage).filter(Boolean),
|
|
1768
|
-
});
|
|
1769
|
-
}
|
|
1770
|
-
case "ziweiChart":
|
|
1771
|
-
return JSON.stringify(runZiweiChart(args));
|
|
1772
|
-
|
|
1773
|
-
// ── LevelDB 读写(同构,前后端均可用)──
|
|
1774
|
-
case "read": {
|
|
1775
|
-
if (looksLikeLocalFilePath(args.filePath)) {
|
|
1776
|
-
return postMain("/api/read-file", {
|
|
1777
|
-
filePath: args.filePath,
|
|
1778
|
-
startLine: args.startLine,
|
|
1779
|
-
endLine: args.endLine,
|
|
1780
|
-
});
|
|
1781
|
-
}
|
|
1782
|
-
const dbKey = args.dbKey;
|
|
1783
|
-
if (!dbKey) return JSON.stringify({ error: "read: dbKey is required" });
|
|
1784
|
-
const blockedReadResult = guardWorkspaceRead(dbKey, context);
|
|
1785
|
-
if (blockedReadResult) return blockedReadResult;
|
|
1786
|
-
const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(dbKey)}`, {
|
|
1787
|
-
headers: { Authorization: `Bearer ${authToken}` },
|
|
1788
|
-
});
|
|
1789
|
-
if (!res.ok) return JSON.stringify({ error: `read: HTTP ${res.status}`, detail: await res.text() });
|
|
1790
|
-
recordWorkspaceRead(dbKey, context);
|
|
1791
|
-
return res.text();
|
|
1792
|
-
}
|
|
1793
|
-
case "searchDialogMessages": {
|
|
1794
|
-
const dialogKey = normalizeDialogSearchText(args.dialogKey);
|
|
1795
|
-
const query = normalizeDialogSearchText(args.query);
|
|
1796
|
-
if (!dialogKey.startsWith("dialog-")) {
|
|
1797
|
-
return JSON.stringify({ error: "searchDialogMessages: dialogKey must be a dialog-* dbKey" });
|
|
1798
|
-
}
|
|
1799
|
-
if (!query) {
|
|
1800
|
-
return JSON.stringify({ error: "searchDialogMessages: query is required" });
|
|
1801
|
-
}
|
|
1802
|
-
const blockedReadResult = guardWorkspaceRead(dialogKey, context);
|
|
1803
|
-
if (blockedReadResult) return blockedReadResult;
|
|
1804
|
-
const dialogId = dialogKey.split("-").at(-1) || dialogKey;
|
|
1805
|
-
const scanLimit = clampDialogSearchNumber(
|
|
1806
|
-
args.scanLimit,
|
|
1807
|
-
SEARCH_DIALOG_MESSAGES_SCAN_LIMIT,
|
|
1808
|
-
1,
|
|
1809
|
-
SEARCH_DIALOG_MESSAGES_SCAN_LIMIT,
|
|
1810
|
-
);
|
|
1811
|
-
const resultLimit = clampDialogSearchNumber(args.limit, 5, 1, SEARCH_DIALOG_MESSAGES_RESULT_LIMIT);
|
|
1812
|
-
const contextMessages = clampDialogSearchNumber(
|
|
1813
|
-
args.contextMessages,
|
|
1814
|
-
1,
|
|
1815
|
-
0,
|
|
1816
|
-
SEARCH_DIALOG_MESSAGES_CONTEXT_LIMIT,
|
|
1817
|
-
);
|
|
1818
|
-
const res = await fetch(`${mainBase}/rpc/getConvMsgs`, {
|
|
1819
|
-
method: "POST",
|
|
1820
|
-
headers: {
|
|
1821
|
-
Authorization: `Bearer ${authToken}`,
|
|
1822
|
-
"Content-Type": "application/json",
|
|
1823
|
-
},
|
|
1824
|
-
body: JSON.stringify({ dialogId, limit: scanLimit }),
|
|
1825
|
-
});
|
|
1826
|
-
if (!res.ok) {
|
|
1827
|
-
return JSON.stringify({ error: `searchDialogMessages: HTTP ${res.status}`, detail: await res.text() });
|
|
1828
|
-
}
|
|
1829
|
-
const newestFirst = await res.json();
|
|
1830
|
-
const messages = Array.isArray(newestFirst) ? [...newestFirst].reverse() : [];
|
|
1831
|
-
const matches = buildDialogMessageSearchResults({
|
|
1832
|
-
messages,
|
|
1833
|
-
query,
|
|
1834
|
-
limit: resultLimit,
|
|
1835
|
-
contextMessages,
|
|
1836
|
-
role: typeof args.role === "string" ? args.role : undefined,
|
|
1837
|
-
includeTools: args.includeTools,
|
|
1838
|
-
contentClipChars: SEARCH_DIALOG_MESSAGES_CLIP_CHARS,
|
|
1839
|
-
contextClipChars: SEARCH_DIALOG_MESSAGES_CONTEXT_CLIP_CHARS,
|
|
1840
|
-
});
|
|
1841
|
-
recordWorkspaceRead(dialogKey, context);
|
|
1842
|
-
return JSON.stringify({
|
|
1843
|
-
success: true,
|
|
1844
|
-
dialogKey,
|
|
1845
|
-
query,
|
|
1846
|
-
scannedMessages: messages.length,
|
|
1847
|
-
matches,
|
|
1848
|
-
});
|
|
1849
|
-
}
|
|
1850
|
-
case "readDoc":
|
|
1851
|
-
case "readPage": {
|
|
1852
|
-
const id = typeof args.id === "string" ? args.id.trim() : "";
|
|
1853
|
-
if (!id) return JSON.stringify({ error: `${serverToolName}: id is required` });
|
|
1854
|
-
const blockedReadResult = guardWorkspaceRead(id, context);
|
|
1855
|
-
if (blockedReadResult) return blockedReadResult;
|
|
1856
|
-
const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(id)}`, {
|
|
1857
|
-
headers: { Authorization: `Bearer ${authToken}` },
|
|
1858
|
-
});
|
|
1859
|
-
if (!res.ok) {
|
|
1860
|
-
return JSON.stringify({
|
|
1861
|
-
error: `${serverToolName}: HTTP ${res.status}`,
|
|
1862
|
-
detail: await res.text(),
|
|
1863
|
-
});
|
|
1864
|
-
}
|
|
1865
|
-
const page = await res.json();
|
|
1866
|
-
recordWorkspaceRead(id, context);
|
|
1867
|
-
return JSON.stringify(buildReadDocResult(page).rawData);
|
|
1868
|
-
}
|
|
1869
|
-
case "deleteSpaces": {
|
|
1870
|
-
if (!context?.userId) {
|
|
1871
|
-
return JSON.stringify({ error: "deleteSpaces: userId is required" });
|
|
1872
|
-
}
|
|
1873
|
-
|
|
1874
|
-
const query = typeof args.query === "string" ? args.query.trim() : "";
|
|
1875
|
-
if (!query) {
|
|
1876
|
-
return JSON.stringify({ error: "deleteSpaces: query is required" });
|
|
1877
|
-
}
|
|
1878
|
-
|
|
1879
|
-
const membershipsRes = await postJson(mainBase, "/rpc/getUserSpaceMemberships", {
|
|
1880
|
-
userId: context.userId,
|
|
1881
|
-
});
|
|
1882
|
-
if (!membershipsRes.ok || !Array.isArray(membershipsRes.data)) {
|
|
1883
|
-
return JSON.stringify({
|
|
1884
|
-
error: `deleteSpaces: membership HTTP ${membershipsRes.status}`,
|
|
1885
|
-
detail: membershipsRes.text,
|
|
1886
|
-
});
|
|
1887
|
-
}
|
|
1888
|
-
|
|
1889
|
-
const candidates = filterSpaceDeletionCandidates(
|
|
1890
|
-
membershipsRes.data as SpaceMembershipLike[],
|
|
1891
|
-
{
|
|
1892
|
-
query,
|
|
1893
|
-
matchMode: args.matchMode,
|
|
1894
|
-
}
|
|
1895
|
-
);
|
|
1896
|
-
const spaceRecordsById: Record<string, SpaceRecordLike | null> = {};
|
|
1897
|
-
for (const candidate of candidates) {
|
|
1898
|
-
const spaceId = String(candidate.spaceId ?? "").replace(/^space-/, "");
|
|
1899
|
-
if (!spaceId) continue;
|
|
1900
|
-
const readRes = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(createSpaceKey.space(spaceId))}`, {
|
|
1901
|
-
headers: buildAuthHeaders(),
|
|
1902
|
-
});
|
|
1903
|
-
if (!readRes.ok) {
|
|
1904
|
-
spaceRecordsById[spaceId] = null;
|
|
1905
|
-
continue;
|
|
1906
|
-
}
|
|
1907
|
-
try {
|
|
1908
|
-
spaceRecordsById[spaceId] = await readRes.json();
|
|
1909
|
-
} catch {
|
|
1910
|
-
spaceRecordsById[spaceId] = null;
|
|
1911
|
-
}
|
|
1912
|
-
}
|
|
1913
|
-
|
|
1914
|
-
const preview = buildDeleteSpacesPreview({
|
|
1915
|
-
currentUserId: context.userId,
|
|
1916
|
-
candidates,
|
|
1917
|
-
spaceRecordsById,
|
|
1918
|
-
});
|
|
1919
|
-
|
|
1920
|
-
const confirmedSpaceIds = Array.isArray(args.confirmedSpaceIds)
|
|
1921
|
-
? args.confirmedSpaceIds.filter((id: unknown): id is string => typeof id === "string" && id.trim())
|
|
1922
|
-
: [];
|
|
1923
|
-
if (confirmedSpaceIds.length === 0) {
|
|
1924
|
-
return JSON.stringify({
|
|
1925
|
-
requiresConfirmation: true,
|
|
1926
|
-
message:
|
|
1927
|
-
"请让用户确认后,再带 confirmedSpaceIds 调用 deleteSpaces。只会删除 Space 壳和成员关系,不删除挂载内容。",
|
|
1928
|
-
...preview,
|
|
1929
|
-
});
|
|
1930
|
-
}
|
|
1931
|
-
|
|
1932
|
-
const { targets, missingConfirmedSpaceIds } =
|
|
1933
|
-
resolveConfirmedSpaceDeletionTargets(preview, confirmedSpaceIds);
|
|
1934
|
-
const deletedSpaceIds: string[] = [];
|
|
1935
|
-
const deletedKeys: string[] = [];
|
|
1936
|
-
const failures: Array<{ dbKey: string; status: number; detail: string }> = [];
|
|
1937
|
-
|
|
1938
|
-
for (const target of targets) {
|
|
1939
|
-
const record = spaceRecordsById[target.spaceId];
|
|
1940
|
-
if (!record) continue;
|
|
1941
|
-
const keys = [
|
|
1942
|
-
...spaceMemberKeysForDelete(target.spaceId, record),
|
|
1943
|
-
createSpaceKey.space(target.spaceId),
|
|
1944
|
-
];
|
|
1945
|
-
let targetFailed = false;
|
|
1946
|
-
for (const key of keys) {
|
|
1947
|
-
const result = await deleteDbKey(key);
|
|
1948
|
-
if (!result.ok) {
|
|
1949
|
-
targetFailed = true;
|
|
1950
|
-
failures.push({ dbKey: key, status: result.status, detail: result.text });
|
|
1951
|
-
} else {
|
|
1952
|
-
deletedKeys.push(key);
|
|
1953
|
-
}
|
|
1954
|
-
}
|
|
1955
|
-
if (!targetFailed) deletedSpaceIds.push(target.spaceId);
|
|
1956
|
-
}
|
|
1957
|
-
|
|
1958
|
-
return JSON.stringify({
|
|
1959
|
-
deletedSpaceIds,
|
|
1960
|
-
deletedKeys,
|
|
1961
|
-
missingConfirmedSpaceIds,
|
|
1962
|
-
skipped: preview.skipped,
|
|
1963
|
-
failures,
|
|
1964
|
-
});
|
|
1965
|
-
}
|
|
1966
|
-
case "createDoc":
|
|
1967
|
-
case "createPage": {
|
|
1968
|
-
const blockedKnowledgeResult = guardKnowledgeCapture({
|
|
1969
|
-
context,
|
|
1970
|
-
target: "doc",
|
|
1971
|
-
});
|
|
1972
|
-
if (blockedKnowledgeResult) return blockedKnowledgeResult;
|
|
1973
|
-
const res = await fetch(`${mainBase}/api/page/create`, {
|
|
1974
|
-
method: "POST",
|
|
1975
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
|
|
1976
|
-
body: JSON.stringify({
|
|
1977
|
-
title: args.title ?? "新文档",
|
|
1978
|
-
content: args.content ?? "",
|
|
1979
|
-
spaceId: args.spaceId,
|
|
1980
|
-
categoryId: args.categoryId,
|
|
1981
|
-
}),
|
|
1982
|
-
});
|
|
1983
|
-
if (!res.ok) return JSON.stringify({ error: `createDoc: HTTP ${res.status}`, detail: await res.text() });
|
|
1984
|
-
recordKnowledgeCapture(context);
|
|
1985
|
-
return res.text();
|
|
1986
|
-
}
|
|
1987
|
-
case "createSkillDoc": {
|
|
1988
|
-
let title = "New Skill";
|
|
1989
|
-
let content = "";
|
|
1990
|
-
try {
|
|
1991
|
-
const built = buildSkillDocFromArgs(args as CreateSkillDocArgs);
|
|
1992
|
-
title = built.title;
|
|
1993
|
-
content = built.content;
|
|
1994
|
-
} catch (error: any) {
|
|
1995
|
-
return JSON.stringify({
|
|
1996
|
-
error: "createSkillDoc",
|
|
1997
|
-
detail: typeof error?.message === "string" ? error.message : String(error),
|
|
1998
|
-
});
|
|
1999
|
-
}
|
|
2000
|
-
|
|
2001
|
-
const blockedKnowledgeResult = guardKnowledgeCapture({
|
|
2002
|
-
context,
|
|
2003
|
-
target: "doc",
|
|
2004
|
-
});
|
|
2005
|
-
if (blockedKnowledgeResult) return blockedKnowledgeResult;
|
|
2006
|
-
|
|
2007
|
-
const res = await fetch(`${mainBase}/api/page/create`, {
|
|
2008
|
-
method: "POST",
|
|
2009
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
|
|
2010
|
-
body: JSON.stringify({
|
|
2011
|
-
title,
|
|
2012
|
-
content,
|
|
2013
|
-
spaceId: args.spaceId,
|
|
2014
|
-
categoryId: args.categoryId,
|
|
2015
|
-
}),
|
|
2016
|
-
});
|
|
2017
|
-
if (!res.ok) {
|
|
2018
|
-
return JSON.stringify({ error: `createSkillDoc: HTTP ${res.status}`, detail: await res.text() });
|
|
2019
|
-
}
|
|
2020
|
-
recordKnowledgeCapture(context);
|
|
2021
|
-
const created = await res.json();
|
|
2022
|
-
return JSON.stringify(
|
|
2023
|
-
buildSkillFollowupResult({
|
|
2024
|
-
dbKey: created?.dbKey ?? created?.id ?? "",
|
|
2025
|
-
title: created?.title ?? title,
|
|
2026
|
-
skillId: (args as CreateSkillDocArgs).name || undefined,
|
|
2027
|
-
spaceId: created?.spaceId ?? args.spaceId ?? null,
|
|
2028
|
-
toolNames: Array.isArray((args as CreateSkillDocArgs).toolNames)
|
|
2029
|
-
? (args as CreateSkillDocArgs).toolNames
|
|
2030
|
-
: [],
|
|
2031
|
-
hasEvalConfig: Array.isArray((args as CreateSkillDocArgs).evalCases)
|
|
2032
|
-
&& (args as CreateSkillDocArgs).evalCases!.length > 0,
|
|
2033
|
-
}).rawData
|
|
2034
|
-
);
|
|
2035
|
-
}
|
|
2036
|
-
case "doctorSkill": {
|
|
2037
|
-
let page: any = null;
|
|
2038
|
-
if (typeof args.id === "string" && args.id.trim()) {
|
|
2039
|
-
const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(args.id.trim())}`, {
|
|
2040
|
-
headers: { Authorization: `Bearer ${authToken}` },
|
|
2041
|
-
});
|
|
2042
|
-
if (!res.ok) {
|
|
2043
|
-
return JSON.stringify({ error: `doctorSkill: HTTP ${res.status}`, detail: await res.text() });
|
|
2044
|
-
}
|
|
2045
|
-
page = await res.json();
|
|
2046
|
-
}
|
|
2047
|
-
const result = await diagnoseSkillDocument(
|
|
2048
|
-
{
|
|
2049
|
-
id: page?.dbKey ?? args.id,
|
|
2050
|
-
title: page?.title,
|
|
2051
|
-
content: typeof args.content === "string" ? args.content : page?.content ?? "",
|
|
2052
|
-
meta: resolvePageSkillMetadata(page),
|
|
2053
|
-
tools: page?.tools,
|
|
2054
|
-
},
|
|
2055
|
-
);
|
|
2056
|
-
return JSON.stringify(result);
|
|
2057
|
-
}
|
|
2058
|
-
case "evalSkill": {
|
|
2059
|
-
let page: any = null;
|
|
2060
|
-
const loadPage = async (dbKey: string) => {
|
|
2061
|
-
const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(dbKey)}`, {
|
|
2062
|
-
headers: { Authorization: `Bearer ${authToken}` },
|
|
2063
|
-
});
|
|
2064
|
-
if (!res.ok) return undefined;
|
|
2065
|
-
return res.json();
|
|
2066
|
-
};
|
|
2067
|
-
if (typeof args.id === "string" && args.id.trim()) {
|
|
2068
|
-
page = await loadPage(args.id.trim());
|
|
2069
|
-
if (!page) {
|
|
2070
|
-
return JSON.stringify({ error: `evalSkill: 未找到 ${args.id}` });
|
|
2071
|
-
}
|
|
2072
|
-
}
|
|
2073
|
-
const result = await evaluateSkillDocument(
|
|
2074
|
-
{
|
|
2075
|
-
id: page?.dbKey ?? args.id,
|
|
2076
|
-
title: page?.title,
|
|
2077
|
-
content: typeof args.content === "string" ? args.content : page?.content ?? "",
|
|
2078
|
-
meta: resolvePageSkillMetadata(page),
|
|
2079
|
-
tools: page?.tools,
|
|
2080
|
-
},
|
|
2081
|
-
{
|
|
2082
|
-
loadPage,
|
|
2083
|
-
},
|
|
2084
|
-
);
|
|
2085
|
-
return JSON.stringify(result);
|
|
2086
|
-
}
|
|
2087
|
-
case "createSkillAgent": {
|
|
2088
|
-
if (!context?.userId) {
|
|
2089
|
-
return JSON.stringify({ error: "createSkillAgent: missing userId in execution context" });
|
|
2090
|
-
}
|
|
2091
|
-
|
|
2092
|
-
const agent = buildSkillAgentRecord({
|
|
2093
|
-
userId: context.userId,
|
|
2094
|
-
currentSpaceId: context.currentSpaceId ?? undefined,
|
|
2095
|
-
args: args as CreateSkillAgentToolArgs,
|
|
2096
|
-
});
|
|
2097
|
-
|
|
2098
|
-
const res = await fetch(`${mainBase}/api/v1/db/write/`, {
|
|
2099
|
-
method: "POST",
|
|
2100
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
|
|
2101
|
-
body: JSON.stringify({
|
|
2102
|
-
userId: context.userId,
|
|
2103
|
-
customKey: agent.dbKey,
|
|
2104
|
-
data: agent,
|
|
2105
|
-
}),
|
|
2106
|
-
});
|
|
2107
|
-
if (!res.ok) {
|
|
2108
|
-
return JSON.stringify({ error: `createSkillAgent: HTTP ${res.status}`, detail: await res.text() });
|
|
2109
|
-
}
|
|
2110
|
-
if (agent.isPublic) {
|
|
2111
|
-
const publicRes = await fetch(`${mainBase}/api/v1/db/write/`, {
|
|
2112
|
-
method: "POST",
|
|
2113
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
|
|
2114
|
-
body: JSON.stringify({
|
|
2115
|
-
userId: context.userId,
|
|
2116
|
-
customKey: agent.publicDbKey,
|
|
2117
|
-
data: agent,
|
|
2118
|
-
}),
|
|
2119
|
-
});
|
|
2120
|
-
if (!publicRes.ok) {
|
|
2121
|
-
return JSON.stringify({
|
|
2122
|
-
error: `createSkillAgent(public): HTTP ${publicRes.status}`,
|
|
2123
|
-
detail: await publicRes.text(),
|
|
2124
|
-
});
|
|
2125
|
-
}
|
|
2126
|
-
}
|
|
2127
|
-
return res.text();
|
|
2128
|
-
}
|
|
2129
|
-
case "prepareAgentDraft": {
|
|
2130
|
-
const result = await prepareAgentDraftToolFunc(args as PrepareAgentDraftToolArgs);
|
|
2131
|
-
return JSON.stringify(result);
|
|
2132
|
-
}
|
|
2133
|
-
case "createAgent": {
|
|
2134
|
-
if (!context?.userId) {
|
|
2135
|
-
return JSON.stringify({ error: "createAgent: missing userId in execution context" });
|
|
2136
|
-
}
|
|
2137
|
-
let agent: ReturnType<typeof buildServerCreatedAgentRecord>;
|
|
2138
|
-
try {
|
|
2139
|
-
agent = buildServerCreatedAgentRecord(
|
|
2140
|
-
context.userId,
|
|
2141
|
-
args as CreateAgentToolArgs,
|
|
2142
|
-
context.currentSpaceId,
|
|
2143
|
-
);
|
|
2144
|
-
} catch (error) {
|
|
2145
|
-
return JSON.stringify({
|
|
2146
|
-
error: error instanceof Error ? error.message : String(error),
|
|
2147
|
-
});
|
|
2148
|
-
}
|
|
2149
|
-
const privateKey = createAgentKey.private(context.userId, agent.id);
|
|
2150
|
-
const publicKey = createAgentKey.public(agent.id);
|
|
2151
|
-
const writeAgent = async (customKey: string) =>
|
|
2152
|
-
fetch(`${mainBase}/api/v1/db/write/`, {
|
|
2153
|
-
method: "POST",
|
|
2154
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
|
|
2155
|
-
body: JSON.stringify({
|
|
2156
|
-
userId: context.userId,
|
|
2157
|
-
customKey,
|
|
2158
|
-
data: agent,
|
|
2159
|
-
}),
|
|
2160
|
-
});
|
|
2161
|
-
|
|
2162
|
-
const privateRes = await writeAgent(privateKey);
|
|
2163
|
-
if (!privateRes.ok) {
|
|
2164
|
-
return JSON.stringify({
|
|
2165
|
-
error: `createAgent(private): HTTP ${privateRes.status}`,
|
|
2166
|
-
detail: await privateRes.text(),
|
|
2167
|
-
});
|
|
2168
|
-
}
|
|
2169
|
-
if (agent.isPublic) {
|
|
2170
|
-
const publicRes = await writeAgent(publicKey);
|
|
2171
|
-
if (!publicRes.ok) {
|
|
2172
|
-
return JSON.stringify({
|
|
2173
|
-
error: `createAgent(public): HTTP ${publicRes.status}`,
|
|
2174
|
-
detail: await publicRes.text(),
|
|
2175
|
-
});
|
|
2176
|
-
}
|
|
2177
|
-
}
|
|
2178
|
-
return JSON.stringify({
|
|
2179
|
-
rawData: {
|
|
2180
|
-
...agent,
|
|
2181
|
-
dbKey: privateKey,
|
|
2182
|
-
publicDbKey: agent.isPublic ? publicKey : undefined,
|
|
2183
|
-
},
|
|
2184
|
-
displayData: [
|
|
2185
|
-
`已创建 Agent: ${agent.name}`,
|
|
2186
|
-
`- ID: ${agent.id}`,
|
|
2187
|
-
`- 模型: ${agent.model}`,
|
|
2188
|
-
`- Provider: ${agent.provider}`,
|
|
2189
|
-
`- 是否公开: ${agent.isPublic ? "是" : "否"}`,
|
|
2190
|
-
agent.isPublic ? `- Public Key: ${publicKey}` : "",
|
|
2191
|
-
].filter(Boolean).join("\n"),
|
|
2192
|
-
});
|
|
2193
|
-
}
|
|
2194
|
-
case "importSkill": {
|
|
2195
|
-
const sourceUrl = typeof args.url === "string" ? normalizeSkillImportUrl(args.url) : "";
|
|
2196
|
-
let rawMarkdown =
|
|
2197
|
-
typeof args.content === "string" ? args.content.trim() : "";
|
|
2198
|
-
if (!rawMarkdown && !sourceUrl) {
|
|
2199
|
-
return JSON.stringify({ error: "importSkill: url 或 content 至少需要一个" });
|
|
2200
|
-
}
|
|
2201
|
-
if (!rawMarkdown) {
|
|
2202
|
-
const sourceRes = await fetch(sourceUrl);
|
|
2203
|
-
if (!sourceRes.ok) {
|
|
2204
|
-
return JSON.stringify({
|
|
2205
|
-
error: `importSkill(fetch): HTTP ${sourceRes.status}`,
|
|
2206
|
-
detail: await sourceRes.text(),
|
|
2207
|
-
});
|
|
2208
|
-
}
|
|
2209
|
-
rawMarkdown = (await sourceRes.text()).trim();
|
|
2210
|
-
}
|
|
2211
|
-
|
|
2212
|
-
const parsed = parseExternalSkillMarkdown(rawMarkdown);
|
|
2213
|
-
const title = typeof args.title === "string" && args.title.trim()
|
|
2214
|
-
? args.title.trim()
|
|
2215
|
-
: parsed.name || "Imported Skill";
|
|
2216
|
-
const skillConfig: SkillDocConfig = {
|
|
2217
|
-
version: "0.1",
|
|
2218
|
-
kind: "skill",
|
|
2219
|
-
id:
|
|
2220
|
-
(parsed.name || title)
|
|
2221
|
-
.trim()
|
|
2222
|
-
.toLowerCase()
|
|
2223
|
-
.replace(/[^a-z0-9]+/g, "-")
|
|
2224
|
-
.replace(/^-+|-+$/g, "") || "imported-skill",
|
|
2225
|
-
name: parsed.name || title,
|
|
2226
|
-
description: parsed.description || "Imported external skill.",
|
|
2227
|
-
triggerMode: "explicit",
|
|
2228
|
-
toolNames: parsed.allowedTools,
|
|
2229
|
-
budgetTier: "medium",
|
|
2230
|
-
dispatchPreferred: false,
|
|
2231
|
-
modalities: ["text"],
|
|
2232
|
-
};
|
|
2233
|
-
const content = buildSkillDocMarkdown({
|
|
2234
|
-
body: [
|
|
2235
|
-
parsed.body,
|
|
2236
|
-
parsed.compatibility ? `## Compatibility\n${parsed.compatibility}` : "",
|
|
2237
|
-
sourceUrl ? `Imported from: ${sourceUrl}` : "",
|
|
2238
|
-
]
|
|
2239
|
-
.filter(Boolean)
|
|
2240
|
-
.join("\n\n"),
|
|
2241
|
-
skillConfig,
|
|
2242
|
-
});
|
|
2243
|
-
|
|
2244
|
-
const blockedKnowledgeResult = guardKnowledgeCapture({
|
|
2245
|
-
context,
|
|
2246
|
-
target: "doc",
|
|
2247
|
-
});
|
|
2248
|
-
if (blockedKnowledgeResult) return blockedKnowledgeResult;
|
|
2249
|
-
|
|
2250
|
-
const res = await fetch(`${mainBase}/api/page/create`, {
|
|
2251
|
-
method: "POST",
|
|
2252
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
|
|
2253
|
-
body: JSON.stringify({
|
|
2254
|
-
title,
|
|
2255
|
-
content,
|
|
2256
|
-
spaceId: args.spaceId,
|
|
2257
|
-
categoryId: args.categoryId,
|
|
2258
|
-
}),
|
|
2259
|
-
});
|
|
2260
|
-
if (!res.ok) {
|
|
2261
|
-
return JSON.stringify({ error: `importSkill: HTTP ${res.status}`, detail: await res.text() });
|
|
2262
|
-
}
|
|
2263
|
-
recordKnowledgeCapture(context);
|
|
2264
|
-
const created = await res.json();
|
|
2265
|
-
return JSON.stringify(
|
|
2266
|
-
buildSkillFollowupResult({
|
|
2267
|
-
dbKey: created?.dbKey ?? created?.id ?? "",
|
|
2268
|
-
title: created?.title ?? title,
|
|
2269
|
-
skillId: skillConfig.id,
|
|
2270
|
-
spaceId: created?.spaceId ?? args.spaceId ?? null,
|
|
2271
|
-
toolNames: skillConfig.toolNames ?? [],
|
|
2272
|
-
importedFrom: sourceUrl || null,
|
|
2273
|
-
hasEvalConfig: false,
|
|
2274
|
-
}).rawData
|
|
2275
|
-
);
|
|
2276
|
-
}
|
|
2277
|
-
case "shareTable": {
|
|
2278
|
-
const blockedShareResult = guardPublicTableShare(context);
|
|
2279
|
-
if (blockedShareResult) return blockedShareResult;
|
|
2280
|
-
if (!context?.userId) {
|
|
2281
|
-
return JSON.stringify({ error: "shareTable requires an authenticated user." });
|
|
2282
|
-
}
|
|
2283
|
-
|
|
2284
|
-
const tableDbKey =
|
|
2285
|
-
typeof args.dbKey === "string" && args.dbKey.trim()
|
|
2286
|
-
? args.dbKey.trim()
|
|
2287
|
-
: typeof args.tenantId === "string" &&
|
|
2288
|
-
args.tenantId.trim() &&
|
|
2289
|
-
typeof args.tableId === "string" &&
|
|
2290
|
-
args.tableId.trim()
|
|
2291
|
-
? `meta-${args.tenantId.trim()}-${args.tableId.trim()}`
|
|
2292
|
-
: "";
|
|
2293
|
-
if (!tableDbKey) {
|
|
2294
|
-
return JSON.stringify({
|
|
2295
|
-
error: "shareTable requires dbKey, or both tenantId and tableId.",
|
|
2296
|
-
});
|
|
2297
|
-
}
|
|
2298
|
-
|
|
2299
|
-
const tableReadRes = await fetch(
|
|
2300
|
-
`${mainBase}/api/v1/db/read/${encodeURIComponent(tableDbKey)}`,
|
|
2301
|
-
{ headers: buildAuthHeaders() },
|
|
2302
|
-
);
|
|
2303
|
-
if (!tableReadRes.ok) {
|
|
2304
|
-
return JSON.stringify({
|
|
2305
|
-
error: `shareTable: failed to read table meta (${tableReadRes.status})`,
|
|
2306
|
-
detail: await tableReadRes.text(),
|
|
2307
|
-
});
|
|
2308
|
-
}
|
|
2309
|
-
const tableReadPayload = await tableReadRes.json();
|
|
2310
|
-
const tableMeta = tableReadPayload?.data ?? tableReadPayload;
|
|
2311
|
-
const tableOwnerId =
|
|
2312
|
-
(typeof args.tenantId === "string" && args.tenantId.trim()) ||
|
|
2313
|
-
(typeof tableMeta?.tenantId === "string" && tableMeta.tenantId.trim()) ||
|
|
2314
|
-
context.userId;
|
|
2315
|
-
const tableId =
|
|
2316
|
-
(typeof args.tableId === "string" && args.tableId.trim()) ||
|
|
2317
|
-
(typeof tableMeta?.tableId === "string" && tableMeta.tableId.trim()) ||
|
|
2318
|
-
tableDbKey;
|
|
2319
|
-
|
|
2320
|
-
let settings: any = null;
|
|
2321
|
-
try {
|
|
2322
|
-
const settingsRes = await fetch(
|
|
2323
|
-
`${mainBase}/api/v1/db/read/${encodeURIComponent(createUserKey.settings(context.userId))}`,
|
|
2324
|
-
{ headers: buildAuthHeaders() },
|
|
2325
|
-
);
|
|
2326
|
-
if (settingsRes.ok) {
|
|
2327
|
-
const settingsPayload = await settingsRes.json();
|
|
2328
|
-
settings = settingsPayload?.data ?? settingsPayload;
|
|
2329
|
-
}
|
|
2330
|
-
} catch {
|
|
2331
|
-
settings = null;
|
|
2332
|
-
}
|
|
2333
|
-
|
|
2334
|
-
const originServer =
|
|
2335
|
-
normalizeServerOrigin(settings?.currentServer) ??
|
|
2336
|
-
normalizeServerOrigin(mainBase) ??
|
|
2337
|
-
normalizeBase(mainBase);
|
|
2338
|
-
const fanoutServers = buildFanoutServerList(originServer, settings?.syncServers);
|
|
2339
|
-
const token = generateShareToken();
|
|
2340
|
-
const dbKey = shareKey.create(token);
|
|
2341
|
-
const createdAt = Date.now();
|
|
2342
|
-
const title =
|
|
2343
|
-
(typeof args.title === "string" && args.title.trim()) ||
|
|
2344
|
-
(typeof tableMeta?.displayName === "string" && tableMeta.displayName.trim()) ||
|
|
2345
|
-
tableId;
|
|
2346
|
-
const description =
|
|
2347
|
-
typeof args.description === "string" && args.description.trim()
|
|
2348
|
-
? args.description.trim()
|
|
2349
|
-
: undefined;
|
|
2350
|
-
const visibility = args.visibility === "private" ? "private" : "community";
|
|
2351
|
-
|
|
2352
|
-
const sharedObject = {
|
|
2353
|
-
type: DataType.TABLE,
|
|
2354
|
-
version: 1,
|
|
2355
|
-
data: {
|
|
2356
|
-
mode: "live",
|
|
2357
|
-
tableDbKey,
|
|
2358
|
-
tableOwnerId,
|
|
2359
|
-
originServer,
|
|
2360
|
-
},
|
|
2361
|
-
meta: {
|
|
2362
|
-
authorId: context.userId,
|
|
2363
|
-
createdAt,
|
|
2364
|
-
visibility,
|
|
2365
|
-
title,
|
|
2366
|
-
description,
|
|
2367
|
-
originalId: tableDbKey,
|
|
2368
|
-
mode: "live",
|
|
2369
|
-
tableDbKey,
|
|
2370
|
-
tableOwnerId,
|
|
2371
|
-
originServer,
|
|
2372
|
-
},
|
|
2373
|
-
};
|
|
2374
|
-
const indexKeys = shareKey.allIndexKeysFromShare(dbKey, sharedObject);
|
|
2375
|
-
const writeBody = {
|
|
2376
|
-
data: sharedObject,
|
|
2377
|
-
customKey: dbKey,
|
|
2378
|
-
userId: context.userId,
|
|
2379
|
-
indexKeys,
|
|
2380
|
-
};
|
|
2381
|
-
const originResult = {
|
|
2382
|
-
server: originServer,
|
|
2383
|
-
...(await postJson(originServer, "/api/v1/db/write/", writeBody)),
|
|
2384
|
-
};
|
|
2385
|
-
if (!originResult.ok) {
|
|
2386
|
-
return JSON.stringify({
|
|
2387
|
-
error: "shareTable: failed to publish on origin server",
|
|
2388
|
-
originServer,
|
|
2389
|
-
detail: originResult.text ?? "",
|
|
2390
|
-
});
|
|
2391
|
-
}
|
|
2392
|
-
const replicaServers = fanoutServers.filter(
|
|
2393
|
-
(server) => normalizeServerOrigin(server) !== originServer,
|
|
2394
|
-
);
|
|
2395
|
-
const replicaResults = await Promise.all(
|
|
2396
|
-
replicaServers.map(async (server) => ({
|
|
2397
|
-
server,
|
|
2398
|
-
...(await postJson(server, "/api/v1/db/write/", writeBody)),
|
|
2399
|
-
})),
|
|
2400
|
-
);
|
|
2401
|
-
const writeResults = [originResult, ...replicaResults];
|
|
2402
|
-
|
|
2403
|
-
const replicaFailures = writeResults
|
|
2404
|
-
.filter(
|
|
2405
|
-
(result) =>
|
|
2406
|
-
normalizeServerOrigin(result.server) !== originServer && !result.ok,
|
|
2407
|
-
)
|
|
2408
|
-
.map((result) => ({
|
|
2409
|
-
server: result.server,
|
|
2410
|
-
status: result.status,
|
|
2411
|
-
detail: result.text,
|
|
2412
|
-
}));
|
|
2413
|
-
|
|
2414
|
-
return JSON.stringify({
|
|
2415
|
-
token,
|
|
2416
|
-
key: dbKey,
|
|
2417
|
-
url: `/share/${token}`,
|
|
2418
|
-
originServer,
|
|
2419
|
-
replicatedServers: fanoutServers,
|
|
2420
|
-
...(replicaFailures.length > 0 ? { replicaFailures } : {}),
|
|
2421
|
-
});
|
|
2422
|
-
}
|
|
2423
|
-
case "createTable":
|
|
2424
|
-
{
|
|
2425
|
-
const blockedKnowledgeResult = guardKnowledgeCapture({
|
|
2426
|
-
context,
|
|
2427
|
-
target: "table",
|
|
2428
|
-
});
|
|
2429
|
-
if (blockedKnowledgeResult) return blockedKnowledgeResult;
|
|
2430
|
-
}
|
|
2431
|
-
{
|
|
2432
|
-
const result = await postMain("/api/table/create", {
|
|
2433
|
-
spaceId: args.spaceId,
|
|
2434
|
-
title: args.title,
|
|
2435
|
-
description: args.description,
|
|
2436
|
-
tags: args.tags,
|
|
2437
|
-
categoryId: args.categoryId,
|
|
2438
|
-
columns: args.columns,
|
|
2439
|
-
withDefaultRows: args.withDefaultRows,
|
|
2440
|
-
});
|
|
2441
|
-
recordKnowledgeCapture(context);
|
|
2442
|
-
return result;
|
|
2443
|
-
}
|
|
2444
|
-
case "addTableRow":
|
|
2445
|
-
return postMain(
|
|
2446
|
-
"/api/table/add-row",
|
|
2447
|
-
withFeedbackSubmitterUserId({
|
|
2448
|
-
tenantId: args.tenantId,
|
|
2449
|
-
tableId: args.tableId,
|
|
2450
|
-
values: args.values,
|
|
2451
|
-
}),
|
|
2452
|
-
);
|
|
2453
|
-
case "queryTableRows":
|
|
2454
|
-
return postMain("/api/table/query-rows", {
|
|
2455
|
-
tenantId: args.tenantId,
|
|
2456
|
-
tableId: args.tableId,
|
|
2457
|
-
filters: args.filters,
|
|
2458
|
-
columns: args.columns,
|
|
2459
|
-
limit: args.limit,
|
|
2460
|
-
offset: args.offset,
|
|
2461
|
-
includeBaseFields: args.includeBaseFields,
|
|
2462
|
-
sortBy: args.sortBy,
|
|
2463
|
-
sortOrder: args.sortOrder,
|
|
2464
|
-
});
|
|
2465
|
-
case "updateTableRow":
|
|
2466
|
-
return postMain("/api/table/update-row", {
|
|
2467
|
-
tenantId: args.tenantId,
|
|
2468
|
-
tableId: args.tableId,
|
|
2469
|
-
rowId: args.rowId,
|
|
2470
|
-
dbKey: args.dbKey,
|
|
2471
|
-
changes: args.changes,
|
|
2472
|
-
});
|
|
2473
|
-
case "deleteTableRow":
|
|
2474
|
-
{
|
|
2475
|
-
const blockedDeleteResult = guardDestructiveAction({
|
|
2476
|
-
context,
|
|
2477
|
-
target: "table_row_delete",
|
|
2478
|
-
detail: "deleteTableRow",
|
|
2479
|
-
});
|
|
2480
|
-
if (blockedDeleteResult) return blockedDeleteResult;
|
|
2481
|
-
}
|
|
2482
|
-
return postMain("/api/table/delete-row", {
|
|
2483
|
-
tenantId: args.tenantId,
|
|
2484
|
-
tableId: args.tableId,
|
|
2485
|
-
rowId: args.rowId,
|
|
2486
|
-
dbKey: args.dbKey,
|
|
2487
|
-
});
|
|
2488
|
-
case "addTableRows":
|
|
2489
|
-
return postMain("/api/table/add-rows", {
|
|
2490
|
-
tenantId: args.tenantId,
|
|
2491
|
-
tableId: args.tableId,
|
|
2492
|
-
rows: args.rows,
|
|
2493
|
-
});
|
|
2494
|
-
case "updateTableRows":
|
|
2495
|
-
return postMain("/api/table/update-rows", {
|
|
2496
|
-
tenantId: args.tenantId,
|
|
2497
|
-
tableId: args.tableId,
|
|
2498
|
-
updates: args.updates,
|
|
2499
|
-
});
|
|
2500
|
-
case "deleteTableRows":
|
|
2501
|
-
{
|
|
2502
|
-
const blockedDeleteResult = guardDestructiveAction({
|
|
2503
|
-
context,
|
|
2504
|
-
target: "table_row_delete",
|
|
2505
|
-
detail: "deleteTableRows",
|
|
2506
|
-
});
|
|
2507
|
-
if (blockedDeleteResult) return blockedDeleteResult;
|
|
2508
|
-
}
|
|
2509
|
-
return postMain("/api/table/delete-rows", {
|
|
2510
|
-
tenantId: args.tenantId,
|
|
2511
|
-
tableId: args.tableId,
|
|
2512
|
-
rowIds: args.rowIds,
|
|
2513
|
-
dbKeys: args.dbKeys,
|
|
2514
|
-
});
|
|
2515
|
-
case "addTableColumn":
|
|
2516
|
-
return postMain("/api/table/add-column", {
|
|
2517
|
-
tenantId: args.tenantId,
|
|
2518
|
-
tableId: args.tableId,
|
|
2519
|
-
name: args.name,
|
|
2520
|
-
label: args.label,
|
|
2521
|
-
type: args.type,
|
|
2522
|
-
description: args.description,
|
|
2523
|
-
required: args.required,
|
|
2524
|
-
options: args.options,
|
|
2525
|
-
});
|
|
2526
|
-
case "deleteTableColumn":
|
|
2527
|
-
{
|
|
2528
|
-
const blockedDeleteResult = guardDestructiveAction({
|
|
2529
|
-
context,
|
|
2530
|
-
target: "table_column_delete",
|
|
2531
|
-
detail: "deleteTableColumn",
|
|
2532
|
-
});
|
|
2533
|
-
if (blockedDeleteResult) return blockedDeleteResult;
|
|
2534
|
-
}
|
|
2535
|
-
return postMain("/api/table/delete-column", {
|
|
2536
|
-
tenantId: args.tenantId,
|
|
2537
|
-
tableId: args.tableId,
|
|
2538
|
-
columnName: args.columnName,
|
|
2539
|
-
});
|
|
2540
|
-
case "renameTableColumn":
|
|
2541
|
-
return postMain("/api/table/rename-column", {
|
|
2542
|
-
tenantId: args.tenantId,
|
|
2543
|
-
tableId: args.tableId,
|
|
2544
|
-
oldName: args.oldName,
|
|
2545
|
-
newName: args.newName,
|
|
2546
|
-
});
|
|
2547
|
-
case "renameTableColumnLabel":
|
|
2548
|
-
return postMain("/api/table/rename-column-label", {
|
|
2549
|
-
tenantId: args.tenantId,
|
|
2550
|
-
tableId: args.tableId,
|
|
2551
|
-
columnName: args.columnName,
|
|
2552
|
-
newLabel: args.newLabel,
|
|
2553
|
-
});
|
|
2554
|
-
case "renameTable":
|
|
2555
|
-
return postMain("/api/table/rename", {
|
|
2556
|
-
tenantId: args.tenantId,
|
|
2557
|
-
tableId: args.tableId,
|
|
2558
|
-
newName: args.newName,
|
|
2559
|
-
});
|
|
2560
|
-
|
|
2561
|
-
case "updateDoc":
|
|
2562
|
-
case "update_page": {
|
|
2563
|
-
const { id, title, content, mode = "replace" } = args;
|
|
2564
|
-
if (!id) return JSON.stringify({ error: "updateDoc: id (dbKey) is required" });
|
|
2565
|
-
if (typeof content !== "string") {
|
|
2566
|
-
return JSON.stringify({ error: "updateDoc: content is required" });
|
|
2567
|
-
}
|
|
2568
|
-
|
|
2569
|
-
const existingRes = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(id)}`, {
|
|
2570
|
-
headers: { Authorization: `Bearer ${authToken}` },
|
|
2571
|
-
});
|
|
2572
|
-
if (!existingRes.ok) {
|
|
2573
|
-
return JSON.stringify({ error: `updateDoc(read): HTTP ${existingRes.status}`, detail: await existingRes.text() });
|
|
2574
|
-
}
|
|
2575
|
-
|
|
2576
|
-
const existing = await existingRes.json();
|
|
2577
|
-
const currentMarkdown =
|
|
2578
|
-
typeof existing?.content === "string" && existing.content.trim()
|
|
2579
|
-
? existing.content
|
|
2580
|
-
: slateToRenderMarkdown(
|
|
2581
|
-
Array.isArray(existing?.slateData) ? existing.slateData : [],
|
|
2582
|
-
);
|
|
2583
|
-
const mergedMarkdown = mode === "append"
|
|
2584
|
-
? [currentMarkdown, content].filter(Boolean).join("\n\n")
|
|
2585
|
-
: content;
|
|
2586
|
-
const parsedProtocol = parseSkillDocProtocol(
|
|
2587
|
-
mergedMarkdown,
|
|
2588
|
-
existing?.meta,
|
|
2589
|
-
existing?.tools,
|
|
2590
|
-
);
|
|
2591
|
-
const slateData = markdownToSlate(parsedProtocol.content) as any[];
|
|
2592
|
-
const tools = extractMentionsFromSlate(slateData as any);
|
|
2593
|
-
|
|
2594
|
-
const changes: Record<string, any> = {
|
|
2595
|
-
slateData,
|
|
2596
|
-
content: parsedProtocol.content,
|
|
2597
|
-
tools,
|
|
2598
|
-
...(parsedProtocol.meta ? { meta: parsedProtocol.meta } : {}),
|
|
2599
|
-
updated_at: new Date().toISOString(),
|
|
2600
|
-
};
|
|
2601
|
-
if (typeof title === "string" && title.trim()) {
|
|
2602
|
-
changes.title = title.trim();
|
|
2603
|
-
}
|
|
2604
|
-
|
|
2605
|
-
const res = await fetch(`${mainBase}/api/v1/db/patch/${encodeURIComponent(id)}`, {
|
|
2606
|
-
method: "PATCH",
|
|
2607
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
|
|
2608
|
-
body: JSON.stringify(changes),
|
|
2609
|
-
});
|
|
2610
|
-
if (!res.ok) return JSON.stringify({ error: `updateDoc: HTTP ${res.status}`, detail: await res.text() });
|
|
2611
|
-
return JSON.stringify({ success: true, id, title: changes.title ?? existing?.title });
|
|
2612
|
-
}
|
|
2613
|
-
|
|
2614
|
-
// ── 数据库(服务端专属)──
|
|
2615
|
-
case "executeSql":
|
|
2616
|
-
return postMain("/api/v1/sqlite/execute_sql", { sql: args.sql, params: args.params });
|
|
2617
|
-
|
|
2618
|
-
// ── 文件系统 / shell(由目标 server 直接提供)──
|
|
2619
|
-
case "readFile":
|
|
2620
|
-
return postMain("/api/read-file", { filePath: args.filePath, startLine: args.startLine, endLine: args.endLine });
|
|
2621
|
-
case "writeFile":
|
|
2622
|
-
return postMain("/api/write-file", { filePath: args.filePath, content: args.content, overwrite: args.overwrite });
|
|
2623
|
-
case "applyEdit":
|
|
2624
|
-
return postMain("/api/apply-edit", { filePath: args.filePath, edits: args.edits });
|
|
2625
|
-
case "execShell":
|
|
2626
|
-
if (isDestructiveShellCommand({ command: args.command, input: args.input })) {
|
|
2627
|
-
const blockedDeleteResult = guardDestructiveAction({
|
|
2628
|
-
context,
|
|
2629
|
-
target: "shell_command",
|
|
2630
|
-
detail: "execShell destructive command",
|
|
2631
|
-
});
|
|
2632
|
-
if (blockedDeleteResult) return blockedDeleteResult;
|
|
2633
|
-
}
|
|
2634
|
-
return postMain("/api/exec-shell", {
|
|
2635
|
-
command: args.command,
|
|
2636
|
-
cwd: args.cwd,
|
|
2637
|
-
shell: args.shell,
|
|
2638
|
-
interactive: args.interactive,
|
|
2639
|
-
pty: args.pty,
|
|
2640
|
-
sessionId: args.sessionId,
|
|
2641
|
-
input: args.input,
|
|
2642
|
-
close: args.close,
|
|
2643
|
-
});
|
|
2644
|
-
case "codeSearch":
|
|
2645
|
-
return postMain("/api/code-search", {
|
|
2646
|
-
query: args.query,
|
|
2647
|
-
path: args.path ?? args.pathScope ?? args.dirPath,
|
|
2648
|
-
glob: args.glob,
|
|
2649
|
-
mode: args.mode ?? "content",
|
|
2650
|
-
maxResults: args.maxResults ?? args.maxFiles,
|
|
2651
|
-
caseSensitive: args.caseSensitive,
|
|
2652
|
-
});
|
|
2653
|
-
case "search_workspace":
|
|
2654
|
-
return postMain("/api/search-repo", {
|
|
2655
|
-
query: args.query,
|
|
2656
|
-
pathScope: args.pathScope,
|
|
2657
|
-
maxResults: args.maxResults,
|
|
2658
|
-
contextLines: args.contextLines,
|
|
2659
|
-
});
|
|
2660
|
-
case "applyLineEdits":
|
|
2661
|
-
return postMain("/api/apply-line-edits", { filePath: args.filePath, edits: args.edits });
|
|
2662
|
-
case "checkEnv":
|
|
2663
|
-
case "check_env":
|
|
2664
|
-
return postMain("/api/check-env", { check: args.check ?? "build" });
|
|
2665
|
-
|
|
2666
|
-
// ── 浏览器自动化(服务端 Puppeteer)──
|
|
2667
|
-
case "browser_openSession":
|
|
2668
|
-
case "browser_closeSession":
|
|
2669
|
-
case "browser_selectOption":
|
|
2670
|
-
case "browser_click":
|
|
2671
|
-
case "browser_typeText":
|
|
2672
|
-
case "browser_readContent":
|
|
2673
|
-
case "browser_probePage":
|
|
2674
|
-
return postMain("/api/browser-tool", {
|
|
2675
|
-
toolName: serverToolName,
|
|
2676
|
-
params: args,
|
|
2677
|
-
});
|
|
2678
|
-
|
|
2679
|
-
case "email_provision_identity": {
|
|
2680
|
-
const missingAgentKey = requireCurrentAgentKey();
|
|
2681
|
-
if (missingAgentKey) return missingAgentKey;
|
|
2682
|
-
const result = await postJson(mainBase, "/rpc/provisionAgentEmailIdentity", {
|
|
2683
|
-
...args,
|
|
2684
|
-
agentId: currentAgentKey,
|
|
2685
|
-
});
|
|
2686
|
-
if (!result.ok) {
|
|
2687
|
-
return JSON.stringify(
|
|
2688
|
-
result.data ?? {
|
|
2689
|
-
error: `email_provision_identity: HTTP ${result.status}`,
|
|
2690
|
-
detail: result.text,
|
|
2691
|
-
},
|
|
2692
|
-
);
|
|
2693
|
-
}
|
|
2694
|
-
return JSON.stringify(result.data ?? {});
|
|
2695
|
-
}
|
|
2696
|
-
case "email_wait_for": {
|
|
2697
|
-
const missingAgentKey = requireCurrentAgentKey();
|
|
2698
|
-
if (missingAgentKey) return missingAgentKey;
|
|
2699
|
-
|
|
2700
|
-
const timeoutSecondsRaw =
|
|
2701
|
-
typeof args.timeoutSeconds === "number"
|
|
2702
|
-
? args.timeoutSeconds
|
|
2703
|
-
: Number(args.timeoutSeconds ?? 60);
|
|
2704
|
-
const timeoutMs = Math.min(Math.max(timeoutSecondsRaw, 1), 180) * 1000;
|
|
2705
|
-
const pollIntervalRaw =
|
|
2706
|
-
typeof args.pollIntervalMs === "number"
|
|
2707
|
-
? args.pollIntervalMs
|
|
2708
|
-
: Number(args.pollIntervalMs ?? 3000);
|
|
2709
|
-
const pollIntervalMs = Math.min(Math.max(pollIntervalRaw, 500), 10_000);
|
|
2710
|
-
const limitRaw =
|
|
2711
|
-
typeof args.limit === "number" ? args.limit : Number(args.limit ?? 20);
|
|
2712
|
-
const limit = Math.min(Math.max(limitRaw, 1), 200);
|
|
2713
|
-
const startedAt = Date.now();
|
|
2714
|
-
let attempts = 0;
|
|
2715
|
-
|
|
2716
|
-
while (Date.now() - startedAt <= timeoutMs) {
|
|
2717
|
-
attempts += 1;
|
|
2718
|
-
const result = await postJson(mainBase, "/rpc/listEmails", {
|
|
2719
|
-
ownerId: currentAgentKey,
|
|
2720
|
-
mailbox: typeof args.mailbox === "string" ? args.mailbox : "inbox",
|
|
2721
|
-
status: args.status,
|
|
2722
|
-
tag: args.tag,
|
|
2723
|
-
limit,
|
|
2724
|
-
});
|
|
2725
|
-
if (!result.ok) {
|
|
2726
|
-
return JSON.stringify(
|
|
2727
|
-
result.data ?? {
|
|
2728
|
-
error: `email_wait_for: HTTP ${result.status}`,
|
|
2729
|
-
detail: result.text,
|
|
2730
|
-
},
|
|
2731
|
-
);
|
|
2732
|
-
}
|
|
2733
|
-
const items = Array.isArray(result.data) ? result.data : [];
|
|
2734
|
-
const match = items.find(
|
|
2735
|
-
(email) => emailIsFreshForWait(email, startedAt) && emailMatchesWaitFilters(email, args),
|
|
2736
|
-
);
|
|
2737
|
-
if (match) {
|
|
2738
|
-
return JSON.stringify({
|
|
2739
|
-
email: match,
|
|
2740
|
-
attempts,
|
|
2741
|
-
waitedMs: Date.now() - startedAt,
|
|
2742
|
-
});
|
|
2743
|
-
}
|
|
2744
|
-
await sleep(pollIntervalMs);
|
|
2745
|
-
}
|
|
2746
|
-
|
|
2747
|
-
return JSON.stringify({
|
|
2748
|
-
error: `等待邮件超时:${Math.ceil(timeoutMs / 1000)} 秒内没有匹配邮件`,
|
|
2749
|
-
});
|
|
2750
|
-
}
|
|
2751
|
-
case "email_extract_verification": {
|
|
2752
|
-
let email: any = null;
|
|
2753
|
-
let text = typeof args.text === "string" ? args.text : undefined;
|
|
2754
|
-
let html = typeof args.html === "string" ? args.html : undefined;
|
|
2755
|
-
if (typeof args.dbKey === "string" && args.dbKey.trim()) {
|
|
2756
|
-
const result = await postJson(mainBase, "/rpc/getEmail", {
|
|
2757
|
-
dbKey: args.dbKey.trim(),
|
|
2758
|
-
});
|
|
2759
|
-
if (!result.ok) {
|
|
2760
|
-
return JSON.stringify(
|
|
2761
|
-
result.data ?? {
|
|
2762
|
-
error: `email_extract_verification: HTTP ${result.status}`,
|
|
2763
|
-
detail: result.text,
|
|
2764
|
-
},
|
|
2765
|
-
);
|
|
2766
|
-
}
|
|
2767
|
-
email = result.data;
|
|
2768
|
-
text = typeof email?.text === "string" ? email.text : text;
|
|
2769
|
-
html = typeof email?.html === "string" ? email.html : html;
|
|
2770
|
-
}
|
|
2771
|
-
if (!text && !html) {
|
|
2772
|
-
return JSON.stringify({
|
|
2773
|
-
error: "必须提供 dbKey、text 或 html 中至少一个",
|
|
2774
|
-
});
|
|
2775
|
-
}
|
|
2776
|
-
return JSON.stringify({
|
|
2777
|
-
email,
|
|
2778
|
-
...extractEmailVerificationArtifacts({ text, html }),
|
|
2779
|
-
});
|
|
2780
|
-
}
|
|
2781
|
-
|
|
2782
|
-
// ── 应用部署管理 ──
|
|
2783
|
-
case "appPreflight":
|
|
2784
|
-
return postMain("/api/app/preflight", {
|
|
2785
|
-
name: args.name,
|
|
2786
|
-
code: args.code,
|
|
2787
|
-
files: normalizeAppFiles(),
|
|
2788
|
-
appId: args.appId,
|
|
2789
|
-
framework: args.framework,
|
|
2790
|
-
spaceId: args.spaceId,
|
|
2791
|
-
});
|
|
2792
|
-
case "appDeploy": {
|
|
2793
|
-
const nextFiles = normalizeAppFiles();
|
|
2794
|
-
const guardUserInput =
|
|
2795
|
-
typeof context?.userInput === "string" ? context.userInput.trim() : "";
|
|
2796
|
-
if (args.appId && guardUserInput && (typeof args.code === "string" || (Array.isArray(nextFiles) && nextFiles.length > 0))) {
|
|
2797
|
-
const previousRead = await postJson(mainBase, "/api/app/prepare-edit", {
|
|
2798
|
-
appId: args.appId,
|
|
2799
|
-
});
|
|
2800
|
-
if (previousRead.ok) {
|
|
2801
|
-
const guardResult = evaluateSmallVisualEditGuard({
|
|
2802
|
-
userInput: guardUserInput,
|
|
2803
|
-
previousSource: previousRead.data ?? {},
|
|
2804
|
-
nextSource: {
|
|
2805
|
-
code: typeof args.code === "string" ? args.code : undefined,
|
|
2806
|
-
files: nextFiles,
|
|
2807
|
-
},
|
|
2808
|
-
});
|
|
2809
|
-
if (!guardResult.ok) {
|
|
2810
|
-
return JSON.stringify(guardResult.rawData);
|
|
2811
|
-
}
|
|
2812
|
-
}
|
|
2813
|
-
}
|
|
2814
|
-
|
|
2815
|
-
const deployStart = await postJson(mainBase, "/api/app/deploy", {
|
|
2816
|
-
name: args.name,
|
|
2817
|
-
code: args.code,
|
|
2818
|
-
files: nextFiles,
|
|
2819
|
-
appId: args.appId,
|
|
2820
|
-
framework: args.framework,
|
|
2821
|
-
spaceId: args.spaceId,
|
|
2822
|
-
});
|
|
2823
|
-
if (!deployStart.ok) {
|
|
2824
|
-
return JSON.stringify(
|
|
2825
|
-
deployStart.data ?? {
|
|
2826
|
-
error: `appDeploy: HTTP ${deployStart.status}`,
|
|
2827
|
-
detail: deployStart.text,
|
|
2828
|
-
},
|
|
2829
|
-
);
|
|
2830
|
-
}
|
|
2831
|
-
|
|
2832
|
-
const jobId =
|
|
2833
|
-
typeof deployStart.data?.jobId === "string"
|
|
2834
|
-
? deployStart.data.jobId
|
|
2835
|
-
: "";
|
|
2836
|
-
if (!jobId) {
|
|
2837
|
-
return deployStart.text;
|
|
2838
|
-
}
|
|
2839
|
-
return waitForAppDeployResult(jobId);
|
|
2840
|
-
}
|
|
2841
|
-
case "appList":
|
|
2842
|
-
return postMain("/api/app/list", args.spaceId ? { spaceId: args.spaceId } : {});
|
|
2843
|
-
case "appDelete": {
|
|
2844
|
-
if (!args.appId) {
|
|
2845
|
-
return JSON.stringify({ error: "appDelete: appId is required; call appList first" });
|
|
2846
|
-
}
|
|
2847
|
-
{
|
|
2848
|
-
const blockedDeleteResult = guardDestructiveAction({
|
|
2849
|
-
context,
|
|
2850
|
-
target: "app_delete",
|
|
2851
|
-
detail: "appDelete",
|
|
2852
|
-
});
|
|
2853
|
-
if (blockedDeleteResult) return blockedDeleteResult;
|
|
2854
|
-
}
|
|
2855
|
-
const lookupRes = await fetch(`${mainBase}/api/app/get`, {
|
|
2856
|
-
method: "POST",
|
|
2857
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
|
|
2858
|
-
body: JSON.stringify({ appId: args.appId }),
|
|
2859
|
-
});
|
|
2860
|
-
if (!lookupRes.ok) {
|
|
2861
|
-
return JSON.stringify({ error: `appDelete lookup: HTTP ${lookupRes.status}`, detail: await lookupRes.text() });
|
|
2862
|
-
}
|
|
2863
|
-
const lookupJson = await lookupRes.json().catch(() => null) as { appKey?: string } | null;
|
|
2864
|
-
if (!lookupJson?.appKey) {
|
|
2865
|
-
return JSON.stringify({ error: "appDelete: appKey not found" });
|
|
2866
|
-
}
|
|
2867
|
-
const deleteRes = await fetch(`${mainBase}/api/v1/db/delete/${encodeURIComponent(lookupJson.appKey)}`, {
|
|
2868
|
-
method: "DELETE",
|
|
2869
|
-
headers: { Authorization: `Bearer ${authToken}` },
|
|
2870
|
-
});
|
|
2871
|
-
if (!deleteRes.ok) {
|
|
2872
|
-
return JSON.stringify({ error: `appDelete: HTTP ${deleteRes.status}`, detail: await deleteRes.text() });
|
|
2873
|
-
}
|
|
2874
|
-
return deleteRes.text();
|
|
2875
|
-
}
|
|
2876
|
-
case "appRead":
|
|
2877
|
-
if (!args.appId) {
|
|
2878
|
-
return JSON.stringify({ error: "appRead: appId is required; call appList first" });
|
|
2879
|
-
}
|
|
2880
|
-
{
|
|
2881
|
-
const readResult = await postJson(mainBase, "/api/app/prepare-edit", {
|
|
2882
|
-
appId: args.appId,
|
|
2883
|
-
});
|
|
2884
|
-
if (!readResult.ok) {
|
|
2885
|
-
return JSON.stringify(
|
|
2886
|
-
readResult.data ?? {
|
|
2887
|
-
error: `appRead: HTTP ${readResult.status}`,
|
|
2888
|
-
detail: readResult.text,
|
|
2889
|
-
},
|
|
2890
|
-
);
|
|
2891
|
-
}
|
|
2892
|
-
const styleSystemAnalysis = analyzeAppStyleSystem(readResult.data ?? {});
|
|
2893
|
-
const styleSystemHint = buildAppStyleSystemHint(styleSystemAnalysis);
|
|
2894
|
-
return JSON.stringify({
|
|
2895
|
-
...(readResult.data ?? {}),
|
|
2896
|
-
styleSystemStatus: styleSystemAnalysis.status,
|
|
2897
|
-
legacyMigrationRecommended:
|
|
2898
|
-
styleSystemAnalysis.legacyMigrationRecommended,
|
|
2899
|
-
styleSystemEvidence: styleSystemAnalysis.evidence,
|
|
2900
|
-
...(styleSystemHint ? { styleSystemHint } : {}),
|
|
2901
|
-
});
|
|
2902
|
-
}
|
|
2903
|
-
|
|
2904
|
-
default:
|
|
2905
|
-
return JSON.stringify({
|
|
2906
|
-
error: `Tool "${toolCall.function.name}" is not available in server-side agent mode.`,
|
|
2907
|
-
});
|
|
2908
|
-
}
|
|
2909
|
-
}
|