nolo-cli 0.1.44 → 0.1.46

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