nolo-cli 0.1.13 → 0.1.14

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 (320) hide show
  1. package/README.md +9 -2
  2. package/agent-runtime/hostAdapter.ts +53 -0
  3. package/agent-runtime/index.ts +28 -0
  4. package/agent-runtime/localLoop.ts +62 -0
  5. package/agent-runtime/runtimeDecision.ts +70 -0
  6. package/agent-runtime/types.ts +87 -0
  7. package/agentRuntimeCommands.ts +139 -22
  8. package/agentRuntimeLocal.ts +7 -0
  9. package/ai/agent/_executeModel.ts +118 -0
  10. package/ai/agent/agentSlice.ts +544 -1
  11. package/ai/agent/appWorkingMemory.ts +126 -0
  12. package/ai/agent/avatarUtils.ts +24 -0
  13. package/ai/agent/buildEditingContext.ts +373 -0
  14. package/ai/agent/buildSystemPrompt.ts +532 -0
  15. package/ai/agent/cleanAgentMessages.ts +140 -0
  16. package/ai/agent/cliChatClient.ts +119 -0
  17. package/ai/agent/contextCompiler.ts +107 -0
  18. package/ai/agent/contextLayerContract.ts +44 -0
  19. package/ai/agent/createAgentSchema.ts +234 -0
  20. package/ai/agent/executeToolCall.ts +58 -0
  21. package/ai/agent/fetchAgentContexts.ts +42 -0
  22. package/ai/agent/generatePrompt.ts +3 -0
  23. package/ai/agent/getFullChatContextKeys.ts +168 -0
  24. package/ai/agent/hooks/fetchPublicAgents.ts +133 -0
  25. package/ai/agent/hooks/useAgentConfig.ts +61 -0
  26. package/ai/agent/hooks/useAgentDialog.ts +35 -0
  27. package/ai/agent/hooks/useAgentFormValidation.ts +202 -0
  28. package/ai/agent/hooks/usePublicAgents.ts +473 -0
  29. package/ai/agent/persistMessageWithFixedId.ts +37 -0
  30. package/ai/agent/planSlice.ts +259 -0
  31. package/ai/agent/referenceUtils.ts +229 -0
  32. package/ai/agent/runAgentBackground.ts +238 -0
  33. package/ai/agent/runAgentClientLoop.ts +138 -0
  34. package/ai/agent/runtimeGuidance.ts +97 -0
  35. package/ai/agent/runtimeServerBase.ts +37 -0
  36. package/ai/agent/server/fetchPublicAgents.ts +128 -0
  37. package/ai/agent/startParallelAgentStreams.ts +424 -0
  38. package/ai/agent/startupProtocol.ts +53 -0
  39. package/ai/agent/streamAgentChatTurn.ts +1299 -0
  40. package/ai/agent/streamAgentChatTurnUtils.ts +738 -0
  41. package/ai/agent/types.ts +71 -0
  42. package/ai/agent/utils/imageOutput.ts +39 -0
  43. package/ai/agent/utils/publicImageAgentMode.ts +26 -0
  44. package/ai/agent/utils/sortUtils.ts +250 -0
  45. package/ai/agent/web/referencePickerUtils.ts +146 -0
  46. package/ai/ai.locale.ts +1083 -0
  47. package/ai/chat/accumulateToolCallChunks.ts +95 -0
  48. package/ai/chat/fetchUtils.native.ts +276 -0
  49. package/ai/chat/fetchUtils.ts +153 -0
  50. package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
  51. package/ai/chat/parseApiError.ts +64 -0
  52. package/ai/chat/parseMultilineSSE.ts +95 -0
  53. package/ai/chat/sendOpenAICompletionsRequest.native.ts +682 -0
  54. package/ai/chat/sendOpenAICompletionsRequest.ts +712 -0
  55. package/ai/chat/sendOpenAIResponseRequest.ts +512 -0
  56. package/ai/chat/shouldUseServerProxy.ts +18 -0
  57. package/ai/chat/sseClient.native.ts +91 -0
  58. package/ai/chat/sseClient.ts +67 -0
  59. package/ai/chat/streamReader.native.ts +31 -0
  60. package/ai/chat/streamReader.ts +62 -0
  61. package/ai/chat/updateTotalUsage.ts +72 -0
  62. package/ai/context/buildReferenceContext.ts +437 -0
  63. package/ai/context/calculateContextUsage.ts +133 -0
  64. package/ai/context/retention.ts +165 -0
  65. package/ai/context/tokenUtils.ts +78 -0
  66. package/ai/index.ts +1 -1
  67. package/ai/llm/agentCapabilities.ts +74 -0
  68. package/ai/llm/calculateGeminiImageTokens.ts +57 -0
  69. package/ai/llm/deepinfra.ts +28 -0
  70. package/ai/llm/fireworks.ts +68 -0
  71. package/ai/llm/generateRequestBody.ts +165 -0
  72. package/ai/llm/getModelContextWindow.ts +84 -0
  73. package/ai/llm/getNoloKey.ts +37 -0
  74. package/ai/llm/getPricing.ts +232 -0
  75. package/ai/llm/hooks/useModelPricing.ts +75 -0
  76. package/ai/llm/imagePricing.ts +66 -0
  77. package/ai/llm/isResponseAPIModel.ts +13 -0
  78. package/ai/llm/kimi.ts +18 -0
  79. package/ai/llm/mimo.ts +71 -0
  80. package/ai/llm/mistral.ts +22 -0
  81. package/ai/llm/modelAvatar.ts +427 -0
  82. package/ai/llm/models.ts +45 -0
  83. package/ai/llm/openrouterModels.ts +141 -0
  84. package/ai/llm/providers.ts +307 -0
  85. package/ai/llm/reasoningModels.ts +28 -0
  86. package/ai/llm/types.ts +59 -0
  87. package/ai/llm/usageRequestOptions.ts +59 -0
  88. package/ai/memory/capture.ts +148 -0
  89. package/ai/memory/consolidate.ts +104 -0
  90. package/ai/memory/delete.ts +147 -0
  91. package/ai/memory/overlay.ts +84 -0
  92. package/ai/memory/query.ts +38 -0
  93. package/ai/memory/queryShared.ts +160 -0
  94. package/ai/memory/rank.ts +105 -0
  95. package/ai/memory/recentRelationshipRecap.ts +247 -0
  96. package/ai/memory/remember.ts +167 -0
  97. package/ai/memory/runtime.ts +76 -0
  98. package/ai/memory/store.ts +20 -0
  99. package/ai/memory/storeShared.ts +76 -0
  100. package/ai/memory/types.ts +46 -0
  101. package/ai/memory/understanding.ts +349 -0
  102. package/ai/memory/understandingGreeting.ts +264 -0
  103. package/ai/messages/type.ts +20 -0
  104. package/ai/policy/personalizationDialog.ts +333 -0
  105. package/ai/policy/runtimePolicy.ts +440 -0
  106. package/ai/policy/selfUpdateFields.ts +48 -0
  107. package/ai/policy/types.ts +64 -0
  108. package/ai/skills/referenceRuntime.ts +274 -0
  109. package/ai/skills/skillDiagnostics.ts +251 -0
  110. package/ai/skills/skillDocBuilder.ts +139 -0
  111. package/ai/skills/skillDocProtocol.ts +434 -0
  112. package/ai/skills/skillReferenceSummary.ts +63 -0
  113. package/ai/skills/skillSummaryMarker.ts +26 -0
  114. package/ai/token/calculatePrice.ts +546 -0
  115. package/ai/token/db.ts +98 -0
  116. package/ai/token/externalToolCost.ts +321 -0
  117. package/ai/token/hooks/useRecords.ts +65 -0
  118. package/ai/token/missingUsageEstimate.ts +42 -0
  119. package/ai/token/modelUsageQuery.ts +252 -0
  120. package/ai/token/normalizeUsage.ts +84 -0
  121. package/ai/token/openaiImageGenerationUsage.ts +56 -0
  122. package/ai/token/prepareTokenUsageData.ts +88 -0
  123. package/ai/token/query.ts +88 -0
  124. package/ai/token/queryUserTokens.ts +59 -0
  125. package/ai/token/resolveBillingTarget.ts +52 -0
  126. package/ai/token/saveTokenRecord.ts +53 -0
  127. package/ai/token/serverDialogProjection.ts +78 -0
  128. package/ai/token/serverTokenWriter.ts +143 -0
  129. package/ai/token/stats.ts +21 -0
  130. package/ai/token/tokenThunks.ts +24 -0
  131. package/ai/token/types.ts +93 -0
  132. package/ai/tools/agent/agentTools.ts +176 -0
  133. package/ai/tools/agent/agentUpdateShared.ts +311 -0
  134. package/ai/tools/agent/callAgentTool.ts +139 -0
  135. package/ai/tools/agent/createAgentTool.ts +512 -0
  136. package/ai/tools/agent/createDialogTool.ts +69 -0
  137. package/ai/tools/agent/createSkillAgentTool.ts +62 -0
  138. package/ai/tools/agent/parallelBudget.ts +221 -0
  139. package/ai/tools/agent/presets/appBuilderPreset.ts +147 -0
  140. package/ai/tools/agent/runLlmTool.ts +96 -0
  141. package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
  142. package/ai/tools/agent/skillAgentArgs.ts +106 -0
  143. package/ai/tools/agent/skillAgentPreset.ts +89 -0
  144. package/ai/tools/agent/streamParallelAgentsTool.ts +122 -0
  145. package/ai/tools/agent/updateAgentTool.ts +96 -0
  146. package/ai/tools/agent/updateSelfTool.ts +113 -0
  147. package/ai/tools/amazonProductScraperTool.ts +86 -0
  148. package/ai/tools/apifyActorClient.ts +45 -0
  149. package/ai/tools/appEditGuard.ts +372 -0
  150. package/ai/tools/appReadSnapshot.ts +153 -0
  151. package/ai/tools/appTools.ts +1549 -0
  152. package/ai/tools/applyEditTool.ts +256 -0
  153. package/ai/tools/applyLineEditsTool.ts +312 -0
  154. package/ai/tools/browserTools/click.ts +33 -0
  155. package/ai/tools/browserTools/closeSession.ts +29 -0
  156. package/ai/tools/browserTools/common.ts +27 -0
  157. package/ai/tools/browserTools/openSession.ts +48 -0
  158. package/ai/tools/browserTools/readContent.ts +38 -0
  159. package/ai/tools/browserTools/selectOption.ts +46 -0
  160. package/ai/tools/browserTools/typeText.ts +42 -0
  161. package/ai/tools/category/createCategoryTool.ts +66 -0
  162. package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
  163. package/ai/tools/category/updateContentCategoryTool.ts +75 -0
  164. package/ai/tools/cfBrowserTools.ts +319 -0
  165. package/ai/tools/cfSpeechToTextTool.ts +49 -0
  166. package/ai/tools/checkEnvTool.ts +65 -0
  167. package/ai/tools/cloudflareCrawlTool.ts +289 -0
  168. package/ai/tools/codeSearchTool.ts +111 -0
  169. package/ai/tools/codeTools.ts +101 -0
  170. package/ai/tools/createDocTool.ts +132 -0
  171. package/ai/tools/createPlanTool.ts +999 -0
  172. package/ai/tools/createSkillDocTool.ts +155 -0
  173. package/ai/tools/createWorkflowTool.ts +154 -0
  174. package/ai/tools/deepseekOcrTool.ts +34 -0
  175. package/ai/tools/delayTool.ts +31 -0
  176. package/ai/tools/deleteSpacesTool.ts +325 -0
  177. package/ai/tools/deleteSpacesToolModel.ts +159 -0
  178. package/ai/tools/devReloadUtils.ts +29 -0
  179. package/ai/tools/dialogMessageSearch.ts +137 -0
  180. package/ai/tools/doctorSkillTool.ts +72 -0
  181. package/ai/tools/ecommerceScraperTool.ts +86 -0
  182. package/ai/tools/emailTools.ts +549 -0
  183. package/ai/tools/evalSkillTool.ts +92 -0
  184. package/ai/tools/exaSearchTool.ts +64 -0
  185. package/ai/tools/execBashTool.ts +379 -0
  186. package/ai/tools/executeSqlTool.ts +192 -0
  187. package/ai/tools/fetchWebpageSupport.ts +309 -0
  188. package/ai/tools/fetchWebpageTool.ts +84 -0
  189. package/ai/tools/geminiImagePreviewTool.ts +361 -0
  190. package/ai/tools/generateDocxTool.ts +215 -0
  191. package/ai/tools/googleSearchScraperTool.ts +106 -0
  192. package/ai/tools/importDataTool.ts +133 -0
  193. package/ai/tools/importSkillTool.ts +162 -0
  194. package/ai/tools/index.ts +1927 -0
  195. package/ai/tools/listFilesTool.ts +82 -0
  196. package/ai/tools/listUserSpacesTool.ts +113 -0
  197. package/ai/tools/modelUsageTools.ts +199 -0
  198. package/ai/tools/olmOcrTool.ts +34 -0
  199. package/ai/tools/openaiImageTool.ts +267 -0
  200. package/ai/tools/prepareTools.ts +23 -0
  201. package/ai/tools/readDocTool.ts +84 -0
  202. package/ai/tools/readFileTool.ts +211 -0
  203. package/ai/tools/readTool.ts +163 -0
  204. package/ai/tools/readXPostTool.ts +233 -0
  205. package/ai/tools/rememberMemoryTool.ts +84 -0
  206. package/ai/tools/remotionVideoTool.ts +151 -0
  207. package/ai/tools/searchDialogMessagesTool.ts +222 -0
  208. package/ai/tools/searchRepoTool.ts +115 -0
  209. package/ai/tools/searchWorkspaceTool.ts +259 -0
  210. package/ai/tools/skillFollowup.ts +86 -0
  211. package/ai/tools/surfWeatherTool.ts +169 -0
  212. package/ai/tools/table/addTableRowTool.ts +217 -0
  213. package/ai/tools/table/createTableTool.ts +315 -0
  214. package/ai/tools/table/rowTools.ts +366 -0
  215. package/ai/tools/table/schemaTools.ts +244 -0
  216. package/ai/tools/table/shareTableTool.ts +148 -0
  217. package/ai/tools/table/toolShared.ts +129 -0
  218. package/ai/tools/toolApiClient.ts +198 -0
  219. package/ai/tools/toolNameAliases.ts +57 -0
  220. package/ai/tools/toolResultError.ts +42 -0
  221. package/ai/tools/toolRunSlice.ts +303 -0
  222. package/ai/tools/toolSchemaCompatibility.ts +53 -0
  223. package/ai/tools/toolVisibility.ts +4 -0
  224. package/ai/tools/types.ts +20 -0
  225. package/ai/tools/uiAskChoiceTool.ts +104 -0
  226. package/ai/tools/updateContentTitleTool.ts +84 -0
  227. package/ai/tools/updateDocTool.ts +105 -0
  228. package/ai/tools/updateUserPreferenceProfileTool.ts +145 -0
  229. package/ai/tools/whisperTool.ts +77 -0
  230. package/ai/tools/writeFileTool.ts +210 -0
  231. package/ai/tools/youtubeScraperTool.ts +116 -0
  232. package/ai/tools/ziweiChartTool.ts +678 -0
  233. package/ai/types.ts +55 -0
  234. package/ai/workflow/workflowExecutor.ts +323 -0
  235. package/ai/workflow/workflowSlice.ts +73 -0
  236. package/ai/workflow/workflowTypes.ts +106 -0
  237. package/client/agentRun.test.ts +240 -0
  238. package/client/agentRun.ts +182 -19
  239. package/client/compactDialog.test.ts +238 -0
  240. package/client/localRuntimeAdapter.test.ts +135 -0
  241. package/client/localRuntimeAdapter.ts +244 -0
  242. package/client/profileConfig.test.ts +40 -0
  243. package/client/streamingOutput.test.ts +22 -0
  244. package/client/streamingOutput.ts +38 -0
  245. package/commandRegistry.ts +9 -2
  246. package/connector-experimental/index.ts +5 -0
  247. package/database/actions/cacheMergedUserData.ts +64 -0
  248. package/database/actions/common.ts +242 -0
  249. package/database/actions/deleteFile.ts +40 -0
  250. package/database/actions/fetchUserData.ts +16 -0
  251. package/database/actions/fileContent.ts +125 -0
  252. package/database/actions/patch.ts +155 -0
  253. package/database/actions/read.ts +337 -0
  254. package/database/actions/readAndWait.ts +224 -0
  255. package/database/actions/readRequestManager.ts +120 -0
  256. package/database/actions/remove.ts +94 -0
  257. package/database/actions/replication.ts +366 -0
  258. package/database/actions/upload.ts +174 -0
  259. package/database/actions/upsert.ts +56 -0
  260. package/database/actions/write.ts +126 -0
  261. package/database/client/db.native.ts +73 -0
  262. package/database/client/db.ts +51 -0
  263. package/database/client/fetchUserData.ts +61 -0
  264. package/database/client/handleError.ts +19 -0
  265. package/database/client/queryRequest.ts +21 -0
  266. package/database/config.ts +21 -0
  267. package/database/dbActionThunks.ts +1 -0
  268. package/database/dbSlice.ts +149 -0
  269. package/database/email.ts +42 -0
  270. package/database/fileRing.ts +51 -0
  271. package/database/fileSharding.ts +70 -0
  272. package/database/fileStorage.native.ts +92 -0
  273. package/database/fileStorage.ts +232 -0
  274. package/database/fileUrl.ts +34 -0
  275. package/database/hooks/useUserData.ts +489 -0
  276. package/database/index.ts +1 -0
  277. package/database/keys.ts +765 -0
  278. package/database/queryPrefixes.ts +14 -0
  279. package/database/requests.ts +443 -0
  280. package/database/runtimeServerContext.ts +35 -0
  281. package/database/server/MemoryDB.ts +76 -0
  282. package/database/server/actorAccess.ts +76 -0
  283. package/database/server/agentDelegation.ts +124 -0
  284. package/database/server/coreDataOwnership.ts +13 -0
  285. package/database/server/coreDataProxy.ts +76 -0
  286. package/database/server/cybotReadonly.ts +18 -0
  287. package/database/server/dataHandlers.ts +111 -0
  288. package/database/server/db.ts +118 -0
  289. package/database/server/dbPath.ts +20 -0
  290. package/database/server/delete.ts +499 -0
  291. package/database/server/emailRepository.ts +1480 -0
  292. package/database/server/ensureDbOpen.ts +12 -0
  293. package/database/server/fileRead.ts +337 -0
  294. package/database/server/fileService.ts +436 -0
  295. package/database/server/handleTransaction.ts +86 -0
  296. package/database/server/patch.ts +282 -0
  297. package/database/server/query.ts +138 -0
  298. package/database/server/read.ts +325 -0
  299. package/database/server/resourceAccess.ts +211 -0
  300. package/database/server/routes.ts +110 -0
  301. package/database/server/spaceMemberAuthority.ts +67 -0
  302. package/database/server/upload.ts +159 -0
  303. package/database/server/write.ts +494 -0
  304. package/database/server/writeAuthority.ts +133 -0
  305. package/database/sqliteDb.ts +46 -0
  306. package/database/table/deleteTable.ts +120 -0
  307. package/database/tenantPlacement.ts +57 -0
  308. package/database/tombstones.ts +52 -0
  309. package/database/userDataLoadDecision.ts +17 -0
  310. package/database/userDataMerge.ts +95 -0
  311. package/database/userPreferenceRegister.ts +108 -0
  312. package/database/utils/dbPath.ts +47 -0
  313. package/database/utils/ulid.native.ts +6 -0
  314. package/database/utils/ulid.ts +1 -0
  315. package/index.ts +25 -15
  316. package/localRuntimeDb.ts +28 -0
  317. package/package.json +16 -4
  318. package/runtimeModeArgs.ts +33 -0
  319. package/tui/readlineWorkspace.ts +1 -0
  320. package/tui/session.ts +22 -0
@@ -0,0 +1,682 @@
1
+ // 文件路径: chat/sendOpenAICompletionsRequest.native.ts
2
+ // React Native 版 - 使用 react-native-sse 进行流式传输
3
+
4
+
5
+
6
+ import {
7
+ addActiveController,
8
+ removeActiveController,
9
+ } from "chat/dialog/dialogSlice";
10
+ import {
11
+ messageStreamEnd,
12
+ messageStreaming,
13
+ } from "chat/messages/messageSlice";
14
+ import { handleToolCalls } from "chat/messages/toolThunks";
15
+ import { MessageContentPart, OpenAITextContent } from "chat/messages/types";
16
+ import { selectCurrentServer } from "app/settings/settingSlice";
17
+ import { getApiEndpoint } from "ai/llm/providers";
18
+ import { createDialogMessageKeyAndId } from "database/keys";
19
+ import { selectCurrentToken } from "auth/authSlice";
20
+ import { extractCustomId } from "core/prefix";
21
+
22
+ import { performSSEFetchRequest } from "./fetchUtils";
23
+ import { createSSEParser } from "./parseMultilineSSE";
24
+ import { parseApiError } from "./parseApiError";
25
+ import { updateTotalUsage } from "./updateTotalUsage";
26
+ import { accumulateToolCallChunks, AccumulatedToolCall, ToolCallChunk } from "./accumulateToolCallChunks";
27
+ import { prepareTools } from "../tools/prepareTools";
28
+
29
+ import { getModelInfo } from "ai/llm/getModelContextWindow";
30
+
31
+ import type { RootState } from "app/store";
32
+
33
+ /**
34
+ * 追加文本 chunk 到 contentBuffer(不可变更新)
35
+ */
36
+ function appendTextChunk(
37
+ currentContentBuffer: MessageContentPart[],
38
+ textChunk: string
39
+ ): MessageContentPart[] {
40
+ if (!textChunk) return currentContentBuffer;
41
+
42
+ const updatedContentBuffer = [...currentContentBuffer];
43
+ const lastIndex = updatedContentBuffer.length - 1;
44
+
45
+ if (lastIndex >= 0 && updatedContentBuffer[lastIndex].type === "text") {
46
+ const last = updatedContentBuffer[lastIndex] as OpenAITextContent;
47
+ updatedContentBuffer[lastIndex] = {
48
+ ...last,
49
+ text: (last.text || "") + textChunk,
50
+ };
51
+ } else {
52
+ updatedContentBuffer.push({ type: "text", text: textChunk });
53
+ }
54
+
55
+ return updatedContentBuffer;
56
+ }
57
+
58
+ /** OpenAI 标准 tool_call 结构 */
59
+ type AssistantToolCall = {
60
+ id: string;
61
+ type: "function";
62
+ function: { name: string; arguments: string };
63
+ };
64
+
65
+ /** 单次流式请求过程中的全部中间状态(显式 state) */
66
+ type StreamState = {
67
+ contentBuffer: MessageContentPart[];
68
+ totalUsage: any | null;
69
+ accumulatedToolCalls: AccumulatedToolCall[];
70
+ reasoningBuffer: string;
71
+ assistantToolCalls?: AssistantToolCall[];
72
+ hasHandedOff: boolean;
73
+ hasProcessedToolCalls: boolean;
74
+ alreadyFinalized: boolean;
75
+ finishReason: string | null;
76
+ };
77
+
78
+ type FinalizeContext = {
79
+ dispatch: any;
80
+ msgKey: string;
81
+ dialogId: string;
82
+ dialogKey: string;
83
+ messageId: string;
84
+ agentConfig: any;
85
+ };
86
+
87
+ type ToolCallsContext = {
88
+ dispatch: any;
89
+ agentConfig: any;
90
+ dialogId: string;
91
+ dialogKey: string;
92
+ messageId: string;
93
+ };
94
+
95
+ type StreamCompletionContext = {
96
+ dispatch: any;
97
+ dialogId: string;
98
+ dialogKey: string;
99
+ messageId: string;
100
+ agentConfig: any;
101
+ };
102
+
103
+ /** 单轮调用后返回给 Agent Loop 的元信息 */
104
+ export type CompletionMeta = {
105
+ hasToolCalls: boolean;
106
+ hasPendingInteraction: boolean;
107
+ hasHandedOff: boolean;
108
+ finishReason: string | null;
109
+ usage?: any;
110
+ };
111
+
112
+ /**
113
+ * 初始化流式状态
114
+ */
115
+ function createInitialStreamState(): StreamState {
116
+ return {
117
+ contentBuffer: [],
118
+ totalUsage: null,
119
+ accumulatedToolCalls: [],
120
+ reasoningBuffer: "",
121
+ assistantToolCalls: undefined,
122
+ hasHandedOff: false,
123
+ hasProcessedToolCalls: false,
124
+ alreadyFinalized: false,
125
+ finishReason: null,
126
+ };
127
+ }
128
+
129
+ /**
130
+ * 根据 tools 配置生成本次请求体(不改动外部传入的 bodyData)
131
+ */
132
+ function buildRequestBodyWithTools(
133
+ bodyData: any,
134
+ agentConfig: any,
135
+ disableToolsForThisRequest: boolean
136
+ ): any {
137
+ if (disableToolsForThisRequest) return bodyData;
138
+
139
+ // 如果模型拥有图像输出能力,则不组装任何 tools
140
+ const modelInfo = getModelInfo(agentConfig.model);
141
+ if (modelInfo?.hasImageOutput) {
142
+ return bodyData;
143
+ }
144
+
145
+ const rawTools = agentConfig.tools;
146
+ if (!Array.isArray(rawTools) || rawTools.length === 0) return bodyData;
147
+
148
+ const tools = prepareTools(rawTools, { provider: agentConfig.provider });
149
+ if (!tools.length) return bodyData;
150
+
151
+ return {
152
+ ...bodyData,
153
+ tools,
154
+ tool_choice: bodyData.tool_choice ?? "auto",
155
+ };
156
+ }
157
+
158
+ /**
159
+ * 结束当前流式消息,派发 messageStreamEnd(带幂等保护)
160
+ */
161
+ async function finalizeStream(
162
+ state: StreamState,
163
+ ctx: FinalizeContext
164
+ ): Promise<StreamState> {
165
+ if (state.hasHandedOff || state.alreadyFinalized) return state;
166
+
167
+ await ctx.dispatch(
168
+ messageStreamEnd({
169
+ finalContentBuffer: state.contentBuffer,
170
+ totalUsage: state.totalUsage,
171
+ msgKey: ctx.msgKey,
172
+ agentConfig: ctx.agentConfig,
173
+ dialogId: ctx.dialogId,
174
+ dialogKey: ctx.dialogKey,
175
+ messageId: ctx.messageId,
176
+ reasoningBuffer: state.reasoningBuffer,
177
+ toolCalls: state.assistantToolCalls,
178
+ })
179
+ );
180
+
181
+ return {
182
+ ...state,
183
+ alreadyFinalized: true,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * 累积 usage
189
+ */
190
+ function applyUsage(state: StreamState, data: any): StreamState {
191
+ if (!data.usage) return state;
192
+
193
+ return {
194
+ ...state,
195
+ totalUsage: updateTotalUsage(state.totalUsage, data.usage),
196
+ };
197
+ }
198
+
199
+ /**
200
+ * 处理单个 delta(文本 / 推理 / tool_calls / 图片)
201
+ */
202
+ function applyDelta(
203
+ state: StreamState,
204
+ delta: any
205
+ ): { state: StreamState; hasNewVisibleContent: boolean } {
206
+ let hasNewVisibleContent = false;
207
+ let next: StreamState = { ...state };
208
+
209
+ // reasoning_content 增量
210
+ if (delta.reasoning_content) {
211
+ next.reasoningBuffer =
212
+ (next.reasoningBuffer || "") + delta.reasoning_content;
213
+ }
214
+
215
+ // tool_calls 累积 + 映射为 OpenAI 标准格式
216
+ if (Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0) {
217
+ const accumulated = accumulateToolCallChunks(
218
+ next.accumulatedToolCalls,
219
+ delta.tool_calls
220
+ );
221
+
222
+ next = {
223
+ ...next,
224
+ accumulatedToolCalls: accumulated,
225
+ assistantToolCalls: accumulated.map((call) => ({
226
+ id: call.id,
227
+ type: "function",
228
+ function: {
229
+ name: call.function?.name,
230
+ arguments:
231
+ typeof call.function?.arguments === "string"
232
+ ? call.function.arguments
233
+ : JSON.stringify(call.function?.arguments ?? {}),
234
+ },
235
+ })),
236
+ };
237
+ }
238
+
239
+ // 图片增量
240
+ const deltaAny = delta as any;
241
+ if (Array.isArray(deltaAny.images) && deltaAny.images.length > 0) {
242
+ next = {
243
+ ...next,
244
+ contentBuffer: [...next.contentBuffer, ...deltaAny.images],
245
+ };
246
+ hasNewVisibleContent = true;
247
+ }
248
+
249
+ // 文本增量
250
+ const contentChunk = delta.content || "";
251
+ if (contentChunk) {
252
+ next = {
253
+ ...next,
254
+ contentBuffer: appendTextChunk(next.contentBuffer, contentChunk),
255
+ };
256
+ hasNewVisibleContent = true;
257
+ }
258
+
259
+ return { state: next, hasNewVisibleContent };
260
+ }
261
+
262
+ /**
263
+ * 如果有新可见内容,则派发一次 messageStreaming 更新前端
264
+ */
265
+ function emitStreamingUpdate(
266
+ hasNewVisibleContent: boolean,
267
+ state: StreamState,
268
+ ctx: {
269
+ dispatch: any;
270
+ agentConfig: any;
271
+ messageId: string;
272
+ msgKey: string;
273
+ dialogId: string;
274
+ }
275
+ ) {
276
+ if (!hasNewVisibleContent) return;
277
+
278
+ ctx.dispatch(
279
+ messageStreaming({
280
+ id: ctx.messageId,
281
+ dialogId: ctx.dialogId,
282
+ dbKey: ctx.msgKey,
283
+ content: state.contentBuffer,
284
+ thinkContent: state.reasoningBuffer,
285
+ role: "assistant",
286
+ cybotKey: ctx.agentConfig.dbKey,
287
+ })
288
+ );
289
+ }
290
+
291
+ /**
292
+ * 处理已经累积好的 tool_calls
293
+ */
294
+ async function processAccumulatedToolCalls(
295
+ state: StreamState,
296
+ ctx: ToolCallsContext
297
+ ): Promise<{
298
+ state: StreamState;
299
+ hasHandedOff: boolean;
300
+ hasPendingInteraction: boolean;
301
+ }> {
302
+ if (!state.accumulatedToolCalls.length) {
303
+ return {
304
+ state,
305
+ hasHandedOff: false,
306
+ hasPendingInteraction: false,
307
+ };
308
+ }
309
+
310
+ const result = await ctx
311
+ .dispatch(
312
+ handleToolCalls({
313
+ accumulatedCalls: state.accumulatedToolCalls,
314
+ currentContentBuffer: state.contentBuffer,
315
+ agentConfig: ctx.agentConfig,
316
+ messageId: ctx.messageId,
317
+ dialogId: ctx.dialogId,
318
+ dialogKey: ctx.dialogKey,
319
+ })
320
+ )
321
+ .unwrap();
322
+
323
+ const nextState: StreamState = {
324
+ ...state,
325
+ contentBuffer: result.finalContentBuffer,
326
+ accumulatedToolCalls: [],
327
+ hasProcessedToolCalls: true,
328
+ hasHandedOff: result.hasHandedOff,
329
+ };
330
+
331
+ return {
332
+ state: nextState,
333
+ hasHandedOff: result.hasHandedOff,
334
+ hasPendingInteraction: result.hasPendingInteraction,
335
+ };
336
+ }
337
+
338
+ /**
339
+ * 处理「流结束」场景(done === true)
340
+ */
341
+ async function handleStreamCompletion(
342
+ state: StreamState,
343
+ ctx: StreamCompletionContext,
344
+ finalizeCtx: FinalizeContext
345
+ ): Promise<{
346
+ state: StreamState;
347
+ hasHandedOff: boolean;
348
+ hasPendingInteraction: boolean;
349
+ }> {
350
+ let hasHandedOff = false;
351
+ let hasPendingInteraction = false;
352
+
353
+ if (!state.hasProcessedToolCalls && state.accumulatedToolCalls.length > 0) {
354
+ const toolResult = await processAccumulatedToolCalls(state, {
355
+ dispatch: ctx.dispatch,
356
+ agentConfig: ctx.agentConfig,
357
+ dialogId: ctx.dialogId,
358
+ dialogKey: ctx.dialogKey,
359
+ messageId: ctx.messageId,
360
+ });
361
+
362
+ let next = toolResult.state;
363
+ hasHandedOff ||= toolResult.hasHandedOff;
364
+ hasPendingInteraction ||= toolResult.hasPendingInteraction;
365
+
366
+ next = await finalizeStream(next, finalizeCtx);
367
+ return { state: next, hasHandedOff, hasPendingInteraction };
368
+ }
369
+
370
+ const finalized = await finalizeStream(state, finalizeCtx);
371
+ return { state: finalized, hasHandedOff, hasPendingInteraction };
372
+ }
373
+
374
+ /**
375
+ * React Native 版主流程:使用 react-native-sse 处理流式 SSE
376
+ */
377
+ export const sendOpenAICompletionsRequest = async ({
378
+ bodyData,
379
+ agentConfig,
380
+ thunkApi,
381
+ dialogKey,
382
+ parentMessageId,
383
+ disableToolsForThisRequest = false,
384
+ }: {
385
+ bodyData: any;
386
+ agentConfig: any;
387
+ thunkApi: any;
388
+ dialogKey: string;
389
+ parentMessageId?: string;
390
+ disableToolsForThisRequest?: boolean;
391
+ }): Promise<CompletionMeta> => {
392
+ const getStreamErrorMessage = (data: any): string => {
393
+ const message =
394
+ typeof data?.error?.message === "string" && data.error.message.trim()
395
+ ? data.error.message.trim()
396
+ : typeof data?.error?.msg === "string" && data.error.msg.trim()
397
+ ? data.error.msg.trim()
398
+ : typeof data?.message === "string" && data.message.trim()
399
+ ? data.message.trim()
400
+ : null;
401
+ if (message) return message;
402
+
403
+ const code =
404
+ typeof data?.error?.code === "string" && data.error.code.trim()
405
+ ? data.error.code.trim()
406
+ : typeof data?.code === "string" && data.code.trim()
407
+ ? data.code.trim()
408
+ : null;
409
+ if (code) return code;
410
+
411
+ const type =
412
+ typeof data?.error?.type === "string" && data.error.type.trim()
413
+ ? data.error.type.trim()
414
+ : null;
415
+ if (type) return type;
416
+
417
+ return "Unknown error";
418
+ };
419
+
420
+ const { dispatch, getState, signal: thunkSignal } = thunkApi;
421
+
422
+ const dialogId = extractCustomId(dialogKey);
423
+ const controller = new AbortController();
424
+ thunkSignal.addEventListener("abort", () => controller.abort());
425
+ const signal = controller.signal;
426
+
427
+ let messageId: string;
428
+ let msgKey: string;
429
+
430
+ if (parentMessageId) {
431
+ messageId = parentMessageId;
432
+ msgKey = `msg:${dialogId}:${messageId}`;
433
+ } else {
434
+ const newIds = createDialogMessageKeyAndId(dialogId);
435
+ messageId = newIds.messageId;
436
+ msgKey = newIds.key;
437
+ }
438
+
439
+ dispatch(addActiveController({ messageId, controller, dialogKey }));
440
+
441
+
442
+ const requestBody = buildRequestBodyWithTools(
443
+ bodyData,
444
+ agentConfig,
445
+ disableToolsForThisRequest
446
+ );
447
+
448
+ let streamState: StreamState = createInitialStreamState();
449
+ const parseSSE = createSSEParser();
450
+ let cleanup: (() => void) | undefined;
451
+
452
+ const finalizeCtx: FinalizeContext = {
453
+ dispatch,
454
+ msgKey,
455
+ dialogId,
456
+ dialogKey,
457
+ messageId,
458
+ agentConfig,
459
+ };
460
+
461
+ let hasHandedOffOverall = false;
462
+ let hasPendingInteractionOverall = false;
463
+ let lastFinishReason: string | null = null;
464
+
465
+ const buildMeta = (): CompletionMeta => ({
466
+ hasToolCalls:
467
+ Array.isArray(streamState.assistantToolCalls) &&
468
+ streamState.assistantToolCalls.length > 0,
469
+ hasPendingInteraction: hasPendingInteractionOverall,
470
+ hasHandedOff: hasHandedOffOverall,
471
+ finishReason: lastFinishReason,
472
+ usage: streamState.totalUsage ?? undefined,
473
+ });
474
+
475
+ return new Promise<CompletionMeta>((resolve) => {
476
+ // 防止 finishWithMeta 被多次调用([DONE] + close/error 事件可能重复触发)
477
+ let resolved = false;
478
+
479
+ const finishWithMeta = async () => {
480
+ if (resolved) {
481
+
482
+ return;
483
+ }
484
+ resolved = true;
485
+
486
+ dispatch(removeActiveController({ messageId, dialogKey }));
487
+ cleanup?.();
488
+ resolve(buildMeta());
489
+ };
490
+
491
+ try {
492
+ if (!parentMessageId) {
493
+ dispatch(
494
+ messageStreaming({
495
+ id: messageId,
496
+ dialogId,
497
+ dbKey: msgKey,
498
+ content: "",
499
+ role: "assistant",
500
+ cybotKey: agentConfig.dbKey,
501
+ isStreaming: true,
502
+ })
503
+ );
504
+ }
505
+
506
+ const api = getApiEndpoint(agentConfig);
507
+ const token = selectCurrentToken(getState() as RootState);
508
+
509
+ const handleCompletion = async () => {
510
+ const completion = await handleStreamCompletion(
511
+ streamState,
512
+ {
513
+ dispatch,
514
+ dialogId,
515
+ dialogKey: finalizeCtx.dialogKey,
516
+ messageId,
517
+ agentConfig,
518
+ },
519
+ finalizeCtx
520
+ );
521
+
522
+ streamState = completion.state;
523
+ hasHandedOffOverall ||= completion.hasHandedOff;
524
+ hasPendingInteractionOverall ||= completion.hasPendingInteraction;
525
+
526
+ await finishWithMeta();
527
+ };
528
+
529
+ cleanup = performSSEFetchRequest({
530
+ agentConfig,
531
+ api,
532
+ bodyData: requestBody,
533
+ currentServer: selectCurrentServer(getState() as RootState),
534
+ signal,
535
+ token,
536
+ onChunk: (chunk: string) => {
537
+ const parsedResults = parseSSE(chunk);
538
+
539
+ for (const parsedData of parsedResults) {
540
+ const dataList = Array.isArray(parsedData) ? parsedData : [parsedData];
541
+
542
+ for (const data of dataList) {
543
+ streamState = applyUsage(streamState, data);
544
+
545
+ if (data === "[DONE]") {
546
+
547
+ cleanup?.();
548
+ // 必须显式调用,不能指望 onComplete
549
+ handleCompletion();
550
+ return;
551
+ }
552
+
553
+ if (data.error) {
554
+ const errorMsg = `Error: ${getStreamErrorMessage(data)}`;
555
+ streamState = {
556
+ ...streamState,
557
+ contentBuffer: appendTextChunk(
558
+ streamState.contentBuffer,
559
+ `\n[API Error] ${errorMsg}`
560
+ ),
561
+ };
562
+ // 必须调用 finishWithMeta 来 resolve Promise 并移除 controller
563
+ finalizeStream(streamState, finalizeCtx).then(() => {
564
+ finishWithMeta();
565
+ });
566
+ return;
567
+ }
568
+
569
+ const choice = data.choices?.[0];
570
+ if (!choice) continue;
571
+
572
+ const delta = choice.delta || {};
573
+
574
+ const { state: updatedState, hasNewVisibleContent } = applyDelta(
575
+ streamState,
576
+ delta
577
+ );
578
+ streamState = updatedState;
579
+
580
+ emitStreamingUpdate(hasNewVisibleContent, streamState, {
581
+ dispatch,
582
+ agentConfig,
583
+ messageId,
584
+ msgKey,
585
+ dialogId,
586
+ });
587
+
588
+ const finishReason = choice.finish_reason;
589
+ if (finishReason) {
590
+ lastFinishReason = finishReason;
591
+ streamState.finishReason = finishReason;
592
+
593
+ if (finishReason === "tool_calls") {
594
+ // 处理 tool_calls - 异步执行
595
+ processAccumulatedToolCalls(streamState, {
596
+ dispatch,
597
+ agentConfig,
598
+ dialogId,
599
+ dialogKey,
600
+ messageId,
601
+ }).then((toolResult) => {
602
+ streamState = toolResult.state;
603
+ hasHandedOffOverall ||= toolResult.hasHandedOff;
604
+ hasPendingInteractionOverall ||= toolResult.hasPendingInteraction;
605
+
606
+ finalizeStream(streamState, finalizeCtx).then((finalized) => {
607
+ streamState = finalized;
608
+ });
609
+ });
610
+ } else if (finishReason !== "stop") {
611
+ streamState = {
612
+ ...streamState,
613
+ contentBuffer: appendTextChunk(
614
+ streamState.contentBuffer,
615
+ `\n[流结束原因: ${finishReason}]`
616
+ ),
617
+ };
618
+ }
619
+ }
620
+ }
621
+ }
622
+ },
623
+ onError: async (error: Error) => {
624
+ if (error?.message?.includes('[DONE]')) {
625
+ const completion = await handleStreamCompletion(
626
+ streamState,
627
+ {
628
+ dispatch,
629
+ dialogId,
630
+ dialogKey: finalizeCtx.dialogKey,
631
+ messageId,
632
+ agentConfig,
633
+ },
634
+ finalizeCtx
635
+ );
636
+
637
+ streamState = completion.state;
638
+ hasHandedOffOverall ||= completion.hasHandedOff;
639
+ hasPendingInteractionOverall ||= completion.hasPendingInteraction;
640
+
641
+ await finishWithMeta();
642
+ return;
643
+ }
644
+
645
+ let errorText: string;
646
+ if (error?.name === "AbortError") {
647
+ errorText = "\n[用户中断]";
648
+ } else {
649
+ errorText = `\n[错误: ${error?.message || String(error)}]`;
650
+ }
651
+
652
+ console.error("[SSE Native] sendOpenAICompletionsRequest error:", error);
653
+
654
+ streamState = {
655
+ ...streamState,
656
+ contentBuffer: appendTextChunk(streamState.contentBuffer, errorText),
657
+ };
658
+ streamState = await finalizeStream(streamState, finalizeCtx);
659
+ await finishWithMeta();
660
+ },
661
+ onComplete: handleCompletion,
662
+ });
663
+ } catch (error: any) {
664
+ let errorText: string;
665
+ if (error?.name === "AbortError") {
666
+ errorText = "\n[用户中断]";
667
+ } else {
668
+ errorText = `\n[错误: ${error?.message || String(error)}]`;
669
+ }
670
+
671
+ console.error("[SSE Native] sendOpenAICompletionsRequest error:", error);
672
+
673
+ streamState = {
674
+ ...streamState,
675
+ contentBuffer: appendTextChunk(streamState.contentBuffer, errorText),
676
+ };
677
+ finalizeStream(streamState, finalizeCtx).then(() => {
678
+ finishWithMeta();
679
+ });
680
+ }
681
+ });
682
+ };