nolo-cli 0.1.31 → 0.1.32

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