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