nolo-cli 0.1.13 → 0.1.15

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 (321) 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/agentRunCommand.ts +104 -0
  8. package/agentRuntimeCommands.ts +139 -22
  9. package/agentRuntimeLocal.ts +7 -0
  10. package/ai/agent/_executeModel.ts +118 -0
  11. package/ai/agent/agentSlice.ts +544 -1
  12. package/ai/agent/appWorkingMemory.ts +126 -0
  13. package/ai/agent/avatarUtils.ts +24 -0
  14. package/ai/agent/buildEditingContext.ts +373 -0
  15. package/ai/agent/buildSystemPrompt.ts +532 -0
  16. package/ai/agent/cleanAgentMessages.ts +140 -0
  17. package/ai/agent/cliChatClient.ts +119 -0
  18. package/ai/agent/contextCompiler.ts +107 -0
  19. package/ai/agent/contextLayerContract.ts +44 -0
  20. package/ai/agent/createAgentSchema.ts +234 -0
  21. package/ai/agent/executeToolCall.ts +58 -0
  22. package/ai/agent/fetchAgentContexts.ts +42 -0
  23. package/ai/agent/generatePrompt.ts +3 -0
  24. package/ai/agent/getFullChatContextKeys.ts +168 -0
  25. package/ai/agent/hooks/fetchPublicAgents.ts +133 -0
  26. package/ai/agent/hooks/useAgentConfig.ts +61 -0
  27. package/ai/agent/hooks/useAgentDialog.ts +35 -0
  28. package/ai/agent/hooks/useAgentFormValidation.ts +202 -0
  29. package/ai/agent/hooks/usePublicAgents.ts +473 -0
  30. package/ai/agent/persistMessageWithFixedId.ts +37 -0
  31. package/ai/agent/planSlice.ts +259 -0
  32. package/ai/agent/referenceUtils.ts +229 -0
  33. package/ai/agent/runAgentBackground.ts +238 -0
  34. package/ai/agent/runAgentClientLoop.ts +138 -0
  35. package/ai/agent/runtimeGuidance.ts +97 -0
  36. package/ai/agent/runtimeServerBase.ts +37 -0
  37. package/ai/agent/server/fetchPublicAgents.ts +128 -0
  38. package/ai/agent/startParallelAgentStreams.ts +424 -0
  39. package/ai/agent/startupProtocol.ts +53 -0
  40. package/ai/agent/streamAgentChatTurn.ts +1299 -0
  41. package/ai/agent/streamAgentChatTurnUtils.ts +738 -0
  42. package/ai/agent/types.ts +71 -0
  43. package/ai/agent/utils/imageOutput.ts +39 -0
  44. package/ai/agent/utils/publicImageAgentMode.ts +26 -0
  45. package/ai/agent/utils/sortUtils.ts +250 -0
  46. package/ai/agent/web/referencePickerUtils.ts +146 -0
  47. package/ai/ai.locale.ts +1083 -0
  48. package/ai/chat/accumulateToolCallChunks.ts +95 -0
  49. package/ai/chat/fetchUtils.native.ts +276 -0
  50. package/ai/chat/fetchUtils.ts +153 -0
  51. package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
  52. package/ai/chat/parseApiError.ts +64 -0
  53. package/ai/chat/parseMultilineSSE.ts +95 -0
  54. package/ai/chat/sendOpenAICompletionsRequest.native.ts +682 -0
  55. package/ai/chat/sendOpenAICompletionsRequest.ts +712 -0
  56. package/ai/chat/sendOpenAIResponseRequest.ts +512 -0
  57. package/ai/chat/shouldUseServerProxy.ts +18 -0
  58. package/ai/chat/sseClient.native.ts +91 -0
  59. package/ai/chat/sseClient.ts +67 -0
  60. package/ai/chat/streamReader.native.ts +31 -0
  61. package/ai/chat/streamReader.ts +62 -0
  62. package/ai/chat/updateTotalUsage.ts +72 -0
  63. package/ai/context/buildReferenceContext.ts +437 -0
  64. package/ai/context/calculateContextUsage.ts +133 -0
  65. package/ai/context/retention.ts +165 -0
  66. package/ai/context/tokenUtils.ts +78 -0
  67. package/ai/index.ts +1 -1
  68. package/ai/llm/agentCapabilities.ts +74 -0
  69. package/ai/llm/calculateGeminiImageTokens.ts +57 -0
  70. package/ai/llm/deepinfra.ts +28 -0
  71. package/ai/llm/fireworks.ts +68 -0
  72. package/ai/llm/generateRequestBody.ts +165 -0
  73. package/ai/llm/getModelContextWindow.ts +84 -0
  74. package/ai/llm/getNoloKey.ts +37 -0
  75. package/ai/llm/getPricing.ts +232 -0
  76. package/ai/llm/hooks/useModelPricing.ts +75 -0
  77. package/ai/llm/imagePricing.ts +66 -0
  78. package/ai/llm/isResponseAPIModel.ts +13 -0
  79. package/ai/llm/kimi.ts +18 -0
  80. package/ai/llm/mimo.ts +71 -0
  81. package/ai/llm/mistral.ts +22 -0
  82. package/ai/llm/modelAvatar.ts +427 -0
  83. package/ai/llm/models.ts +45 -0
  84. package/ai/llm/openrouterModels.ts +141 -0
  85. package/ai/llm/providers.ts +307 -0
  86. package/ai/llm/reasoningModels.ts +28 -0
  87. package/ai/llm/types.ts +59 -0
  88. package/ai/llm/usageRequestOptions.ts +59 -0
  89. package/ai/memory/capture.ts +148 -0
  90. package/ai/memory/consolidate.ts +104 -0
  91. package/ai/memory/delete.ts +147 -0
  92. package/ai/memory/overlay.ts +84 -0
  93. package/ai/memory/query.ts +38 -0
  94. package/ai/memory/queryShared.ts +160 -0
  95. package/ai/memory/rank.ts +105 -0
  96. package/ai/memory/recentRelationshipRecap.ts +247 -0
  97. package/ai/memory/remember.ts +167 -0
  98. package/ai/memory/runtime.ts +76 -0
  99. package/ai/memory/store.ts +20 -0
  100. package/ai/memory/storeShared.ts +76 -0
  101. package/ai/memory/types.ts +46 -0
  102. package/ai/memory/understanding.ts +349 -0
  103. package/ai/memory/understandingGreeting.ts +264 -0
  104. package/ai/messages/type.ts +20 -0
  105. package/ai/policy/personalizationDialog.ts +333 -0
  106. package/ai/policy/runtimePolicy.ts +440 -0
  107. package/ai/policy/selfUpdateFields.ts +48 -0
  108. package/ai/policy/types.ts +64 -0
  109. package/ai/skills/referenceRuntime.ts +274 -0
  110. package/ai/skills/skillDiagnostics.ts +251 -0
  111. package/ai/skills/skillDocBuilder.ts +139 -0
  112. package/ai/skills/skillDocProtocol.ts +434 -0
  113. package/ai/skills/skillReferenceSummary.ts +63 -0
  114. package/ai/skills/skillSummaryMarker.ts +26 -0
  115. package/ai/token/calculatePrice.ts +546 -0
  116. package/ai/token/db.ts +98 -0
  117. package/ai/token/externalToolCost.ts +321 -0
  118. package/ai/token/hooks/useRecords.ts +65 -0
  119. package/ai/token/missingUsageEstimate.ts +42 -0
  120. package/ai/token/modelUsageQuery.ts +252 -0
  121. package/ai/token/normalizeUsage.ts +84 -0
  122. package/ai/token/openaiImageGenerationUsage.ts +56 -0
  123. package/ai/token/prepareTokenUsageData.ts +88 -0
  124. package/ai/token/query.ts +88 -0
  125. package/ai/token/queryUserTokens.ts +59 -0
  126. package/ai/token/resolveBillingTarget.ts +52 -0
  127. package/ai/token/saveTokenRecord.ts +53 -0
  128. package/ai/token/serverDialogProjection.ts +78 -0
  129. package/ai/token/serverTokenWriter.ts +143 -0
  130. package/ai/token/stats.ts +21 -0
  131. package/ai/token/tokenThunks.ts +24 -0
  132. package/ai/token/types.ts +93 -0
  133. package/ai/tools/agent/agentTools.ts +176 -0
  134. package/ai/tools/agent/agentUpdateShared.ts +311 -0
  135. package/ai/tools/agent/callAgentTool.ts +139 -0
  136. package/ai/tools/agent/createAgentTool.ts +512 -0
  137. package/ai/tools/agent/createDialogTool.ts +69 -0
  138. package/ai/tools/agent/createSkillAgentTool.ts +62 -0
  139. package/ai/tools/agent/parallelBudget.ts +221 -0
  140. package/ai/tools/agent/presets/appBuilderPreset.ts +147 -0
  141. package/ai/tools/agent/runLlmTool.ts +96 -0
  142. package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
  143. package/ai/tools/agent/skillAgentArgs.ts +106 -0
  144. package/ai/tools/agent/skillAgentPreset.ts +89 -0
  145. package/ai/tools/agent/streamParallelAgentsTool.ts +122 -0
  146. package/ai/tools/agent/updateAgentTool.ts +96 -0
  147. package/ai/tools/agent/updateSelfTool.ts +113 -0
  148. package/ai/tools/amazonProductScraperTool.ts +86 -0
  149. package/ai/tools/apifyActorClient.ts +45 -0
  150. package/ai/tools/appEditGuard.ts +372 -0
  151. package/ai/tools/appReadSnapshot.ts +153 -0
  152. package/ai/tools/appTools.ts +1549 -0
  153. package/ai/tools/applyEditTool.ts +256 -0
  154. package/ai/tools/applyLineEditsTool.ts +312 -0
  155. package/ai/tools/browserTools/click.ts +33 -0
  156. package/ai/tools/browserTools/closeSession.ts +29 -0
  157. package/ai/tools/browserTools/common.ts +27 -0
  158. package/ai/tools/browserTools/openSession.ts +48 -0
  159. package/ai/tools/browserTools/readContent.ts +38 -0
  160. package/ai/tools/browserTools/selectOption.ts +46 -0
  161. package/ai/tools/browserTools/typeText.ts +42 -0
  162. package/ai/tools/category/createCategoryTool.ts +66 -0
  163. package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
  164. package/ai/tools/category/updateContentCategoryTool.ts +75 -0
  165. package/ai/tools/cfBrowserTools.ts +319 -0
  166. package/ai/tools/cfSpeechToTextTool.ts +49 -0
  167. package/ai/tools/checkEnvTool.ts +65 -0
  168. package/ai/tools/cloudflareCrawlTool.ts +289 -0
  169. package/ai/tools/codeSearchTool.ts +111 -0
  170. package/ai/tools/codeTools.ts +101 -0
  171. package/ai/tools/createDocTool.ts +132 -0
  172. package/ai/tools/createPlanTool.ts +999 -0
  173. package/ai/tools/createSkillDocTool.ts +155 -0
  174. package/ai/tools/createWorkflowTool.ts +154 -0
  175. package/ai/tools/deepseekOcrTool.ts +34 -0
  176. package/ai/tools/delayTool.ts +31 -0
  177. package/ai/tools/deleteSpacesTool.ts +325 -0
  178. package/ai/tools/deleteSpacesToolModel.ts +159 -0
  179. package/ai/tools/devReloadUtils.ts +29 -0
  180. package/ai/tools/dialogMessageSearch.ts +137 -0
  181. package/ai/tools/doctorSkillTool.ts +72 -0
  182. package/ai/tools/ecommerceScraperTool.ts +86 -0
  183. package/ai/tools/emailTools.ts +549 -0
  184. package/ai/tools/evalSkillTool.ts +92 -0
  185. package/ai/tools/exaSearchTool.ts +64 -0
  186. package/ai/tools/execBashTool.ts +379 -0
  187. package/ai/tools/executeSqlTool.ts +192 -0
  188. package/ai/tools/fetchWebpageSupport.ts +309 -0
  189. package/ai/tools/fetchWebpageTool.ts +84 -0
  190. package/ai/tools/geminiImagePreviewTool.ts +361 -0
  191. package/ai/tools/generateDocxTool.ts +215 -0
  192. package/ai/tools/googleSearchScraperTool.ts +106 -0
  193. package/ai/tools/importDataTool.ts +133 -0
  194. package/ai/tools/importSkillTool.ts +162 -0
  195. package/ai/tools/index.ts +1927 -0
  196. package/ai/tools/listFilesTool.ts +82 -0
  197. package/ai/tools/listUserSpacesTool.ts +113 -0
  198. package/ai/tools/modelUsageTools.ts +199 -0
  199. package/ai/tools/olmOcrTool.ts +34 -0
  200. package/ai/tools/openaiImageTool.ts +267 -0
  201. package/ai/tools/prepareTools.ts +23 -0
  202. package/ai/tools/readDocTool.ts +84 -0
  203. package/ai/tools/readFileTool.ts +211 -0
  204. package/ai/tools/readTool.ts +163 -0
  205. package/ai/tools/readXPostTool.ts +233 -0
  206. package/ai/tools/rememberMemoryTool.ts +84 -0
  207. package/ai/tools/remotionVideoTool.ts +151 -0
  208. package/ai/tools/searchDialogMessagesTool.ts +222 -0
  209. package/ai/tools/searchRepoTool.ts +115 -0
  210. package/ai/tools/searchWorkspaceTool.ts +259 -0
  211. package/ai/tools/skillFollowup.ts +86 -0
  212. package/ai/tools/surfWeatherTool.ts +169 -0
  213. package/ai/tools/table/addTableRowTool.ts +217 -0
  214. package/ai/tools/table/createTableTool.ts +315 -0
  215. package/ai/tools/table/rowTools.ts +366 -0
  216. package/ai/tools/table/schemaTools.ts +244 -0
  217. package/ai/tools/table/shareTableTool.ts +148 -0
  218. package/ai/tools/table/toolShared.ts +129 -0
  219. package/ai/tools/toolApiClient.ts +198 -0
  220. package/ai/tools/toolNameAliases.ts +57 -0
  221. package/ai/tools/toolResultError.ts +42 -0
  222. package/ai/tools/toolRunSlice.ts +303 -0
  223. package/ai/tools/toolSchemaCompatibility.ts +53 -0
  224. package/ai/tools/toolVisibility.ts +4 -0
  225. package/ai/tools/types.ts +20 -0
  226. package/ai/tools/uiAskChoiceTool.ts +104 -0
  227. package/ai/tools/updateContentTitleTool.ts +84 -0
  228. package/ai/tools/updateDocTool.ts +105 -0
  229. package/ai/tools/updateUserPreferenceProfileTool.ts +145 -0
  230. package/ai/tools/whisperTool.ts +77 -0
  231. package/ai/tools/writeFileTool.ts +210 -0
  232. package/ai/tools/youtubeScraperTool.ts +116 -0
  233. package/ai/tools/ziweiChartTool.ts +678 -0
  234. package/ai/types.ts +55 -0
  235. package/ai/workflow/workflowExecutor.ts +323 -0
  236. package/ai/workflow/workflowSlice.ts +73 -0
  237. package/ai/workflow/workflowTypes.ts +106 -0
  238. package/client/agentRun.test.ts +240 -0
  239. package/client/agentRun.ts +182 -19
  240. package/client/compactDialog.test.ts +238 -0
  241. package/client/localRuntimeAdapter.test.ts +135 -0
  242. package/client/localRuntimeAdapter.ts +244 -0
  243. package/client/profileConfig.test.ts +40 -0
  244. package/client/streamingOutput.test.ts +22 -0
  245. package/client/streamingOutput.ts +38 -0
  246. package/commandRegistry.ts +11 -2
  247. package/connector-experimental/index.ts +5 -0
  248. package/database/actions/cacheMergedUserData.ts +64 -0
  249. package/database/actions/common.ts +242 -0
  250. package/database/actions/deleteFile.ts +40 -0
  251. package/database/actions/fetchUserData.ts +16 -0
  252. package/database/actions/fileContent.ts +125 -0
  253. package/database/actions/patch.ts +155 -0
  254. package/database/actions/read.ts +337 -0
  255. package/database/actions/readAndWait.ts +224 -0
  256. package/database/actions/readRequestManager.ts +120 -0
  257. package/database/actions/remove.ts +94 -0
  258. package/database/actions/replication.ts +366 -0
  259. package/database/actions/upload.ts +174 -0
  260. package/database/actions/upsert.ts +56 -0
  261. package/database/actions/write.ts +126 -0
  262. package/database/client/db.native.ts +73 -0
  263. package/database/client/db.ts +51 -0
  264. package/database/client/fetchUserData.ts +61 -0
  265. package/database/client/handleError.ts +19 -0
  266. package/database/client/queryRequest.ts +21 -0
  267. package/database/config.ts +21 -0
  268. package/database/dbActionThunks.ts +1 -0
  269. package/database/dbSlice.ts +149 -0
  270. package/database/email.ts +42 -0
  271. package/database/fileRing.ts +51 -0
  272. package/database/fileSharding.ts +70 -0
  273. package/database/fileStorage.native.ts +92 -0
  274. package/database/fileStorage.ts +232 -0
  275. package/database/fileUrl.ts +34 -0
  276. package/database/hooks/useUserData.ts +489 -0
  277. package/database/index.ts +1 -0
  278. package/database/keys.ts +765 -0
  279. package/database/queryPrefixes.ts +14 -0
  280. package/database/requests.ts +443 -0
  281. package/database/runtimeServerContext.ts +35 -0
  282. package/database/server/MemoryDB.ts +76 -0
  283. package/database/server/actorAccess.ts +76 -0
  284. package/database/server/agentDelegation.ts +124 -0
  285. package/database/server/coreDataOwnership.ts +13 -0
  286. package/database/server/coreDataProxy.ts +76 -0
  287. package/database/server/cybotReadonly.ts +18 -0
  288. package/database/server/dataHandlers.ts +111 -0
  289. package/database/server/db.ts +118 -0
  290. package/database/server/dbPath.ts +20 -0
  291. package/database/server/delete.ts +499 -0
  292. package/database/server/emailRepository.ts +1480 -0
  293. package/database/server/ensureDbOpen.ts +12 -0
  294. package/database/server/fileRead.ts +337 -0
  295. package/database/server/fileService.ts +436 -0
  296. package/database/server/handleTransaction.ts +86 -0
  297. package/database/server/patch.ts +282 -0
  298. package/database/server/query.ts +138 -0
  299. package/database/server/read.ts +325 -0
  300. package/database/server/resourceAccess.ts +211 -0
  301. package/database/server/routes.ts +110 -0
  302. package/database/server/spaceMemberAuthority.ts +67 -0
  303. package/database/server/upload.ts +159 -0
  304. package/database/server/write.ts +494 -0
  305. package/database/server/writeAuthority.ts +133 -0
  306. package/database/sqliteDb.ts +46 -0
  307. package/database/table/deleteTable.ts +120 -0
  308. package/database/tenantPlacement.ts +57 -0
  309. package/database/tombstones.ts +52 -0
  310. package/database/userDataLoadDecision.ts +17 -0
  311. package/database/userDataMerge.ts +95 -0
  312. package/database/userPreferenceRegister.ts +108 -0
  313. package/database/utils/dbPath.ts +47 -0
  314. package/database/utils/ulid.native.ts +6 -0
  315. package/database/utils/ulid.ts +1 -0
  316. package/index.ts +37 -19
  317. package/localRuntimeDb.ts +28 -0
  318. package/package.json +17 -4
  319. package/runtimeModeArgs.ts +33 -0
  320. package/tui/readlineWorkspace.ts +1 -0
  321. package/tui/session.ts +22 -0
@@ -0,0 +1,95 @@
1
+ /**
2
+ * 处理流式工具调用数据块,将其累积到数组中。
3
+ * 关键点:
4
+ * - 支持按 index 拼接,也支持同一 id、无 index 的分片追加(OpenAI 风格常见)
5
+ * - 字符串分片追加;对象分片直接覆盖(最后一段为准)
6
+ * - 不再过滤特殊标记,保持原样透传
7
+ */
8
+
9
+ export interface ToolCallChunk {
10
+ index?: number;
11
+ id?: string;
12
+ type?: "function";
13
+ function?: {
14
+ name?: string;
15
+ arguments?: string;
16
+ };
17
+ }
18
+
19
+ export interface AccumulatedToolCall {
20
+ index?: number;
21
+ id: string;
22
+ type: "function";
23
+ function: {
24
+ name: string;
25
+ arguments: string;
26
+ };
27
+ }
28
+
29
+ export function accumulateToolCallChunks(
30
+ currentAccumulatedCalls: AccumulatedToolCall[],
31
+ toolCallChunks: ToolCallChunk[]
32
+ ): AccumulatedToolCall[] {
33
+ const out = [...currentAccumulatedCalls];
34
+
35
+ for (const chunk of toolCallChunks) {
36
+ const { index, id, type, function: fn } = chunk;
37
+
38
+ // 分块流(带 index)
39
+ if (index !== undefined) {
40
+ // 确保数组长度足够覆盖 index
41
+ while (out.length <= index) {
42
+ // 先占位,后续必须填充 id/type/function 才能成为有效的 AccumulatedToolCall
43
+ // 这里暂时断言为空对象,等待后续逻辑填充完整
44
+ out.push({} as AccumulatedToolCall);
45
+ }
46
+
47
+ const cur = out[index];
48
+
49
+ // 初始化或更新基础字段
50
+ if (id && !cur.id) cur.id = id;
51
+ if (type && !cur.type) cur.type = type;
52
+ if (!cur.function) cur.function = { name: "", arguments: "" };
53
+
54
+ if (fn) {
55
+ if (fn.name) cur.function.name += fn.name;
56
+ if (fn.arguments) cur.function.arguments += fn.arguments;
57
+ }
58
+ continue;
59
+ }
60
+
61
+ // 无 index,但有 fn 的分片(同 id 的后续片段会被追加)
62
+ // 这种模式下通常 id 在第一个 chunk 给定,后续 chunk 可能没有 id
63
+ if (fn?.name || fn?.arguments) {
64
+ let targetIndex = -1;
65
+
66
+ // 尝试通过 ID 查找现有调用
67
+ if (id) {
68
+ targetIndex = out.findIndex((c) => c.id === id);
69
+ } else if (out.length > 0) {
70
+ // 如果没有 ID,默认追加到最后一个(假设顺序性)
71
+ // 注意:这是兜底逻辑,OpenAI 规范通常会带 index 或 id
72
+ targetIndex = out.length - 1;
73
+ }
74
+
75
+ if (targetIndex >= 0) {
76
+ const target = out[targetIndex];
77
+ if (fn.name) target.function.name += fn.name; // 追加
78
+ if (fn.arguments) target.function.arguments += fn.arguments; // 追加
79
+ } else if (id) {
80
+ // 是新的调用
81
+ const newCall: AccumulatedToolCall = {
82
+ id,
83
+ type: type || "function",
84
+ function: {
85
+ name: fn.name || "",
86
+ arguments: fn.arguments || ""
87
+ },
88
+ };
89
+ out.push(newCall);
90
+ }
91
+ }
92
+ }
93
+
94
+ return out;
95
+ }
@@ -0,0 +1,276 @@
1
+ // 文件路径: ai/chat/fetchUtils.native.ts
2
+ // React Native 版 fetch 工具 - 使用 react-native-sse 支持流式传输
3
+
4
+ import { Agent } from "app/types";
5
+ import { API_ENDPOINTS } from "database/config";
6
+ import EventSource from 'react-native-sse';
7
+ import { shouldUseServerProxy } from "./shouldUseServerProxy";
8
+
9
+ interface BodyData {
10
+ model: string;
11
+ messages: any[];
12
+ stream: boolean;
13
+ tools?: any[];
14
+ provider?: string;
15
+ }
16
+
17
+ interface FetchParams {
18
+ agentConfig: Agent;
19
+ api: string;
20
+ bodyData: BodyData;
21
+ currentServer: string;
22
+ token: string;
23
+ signal?: AbortSignal;
24
+ }
25
+
26
+ const buildProxyPayload = (
27
+ bodyData: BodyData,
28
+ api: string,
29
+ agentConfig: Agent
30
+ ) => {
31
+ const apiSource =
32
+ agentConfig.apiSource === "custom" || agentConfig.apiSource === "cli"
33
+ ? agentConfig.apiSource
34
+ : undefined;
35
+ const provider =
36
+ bodyData.provider ||
37
+ agentConfig.provider ||
38
+ (apiSource === "custom" ? "custom" : undefined);
39
+ const apiKey = agentConfig.apiKey?.trim() || undefined;
40
+
41
+ return {
42
+ ...bodyData,
43
+ url: api,
44
+ provider,
45
+ ...(apiSource ? { apiSource } : {}),
46
+ KEY: apiKey,
47
+ };
48
+ };
49
+
50
+ interface SSEFetchParams extends FetchParams {
51
+ onChunk: (chunk: string) => void;
52
+ onError: (error: Error) => void;
53
+ onComplete: () => void;
54
+ }
55
+
56
+ /**
57
+ * React Native 版流式 SSE 请求
58
+ * 使用 react-native-sse 库
59
+ */
60
+ export const performSSEFetchRequest = (params: SSEFetchParams): (() => void) => {
61
+ const {
62
+ agentConfig,
63
+ api,
64
+ bodyData,
65
+ currentServer,
66
+ token,
67
+ signal,
68
+ onChunk,
69
+ onError,
70
+ onComplete,
71
+ } = params;
72
+
73
+ // 确定请求 URL 和 headers
74
+ const useProxy = shouldUseServerProxy(agentConfig, bodyData.provider);
75
+ const url = useProxy ? `${currentServer}${API_ENDPOINTS.CHAT}` : api;
76
+
77
+ const headers: Record<string, string> = {
78
+ 'Content-Type': 'application/json',
79
+ 'Accept': 'text/event-stream',
80
+ 'Cache-Control': 'no-cache',
81
+ };
82
+
83
+ if (api.includes("openrouter.ai")) {
84
+ headers["HTTP-Referer"] = "https://nolo.chat";
85
+ headers["X-Title"] = "nolo";
86
+ }
87
+
88
+ let requestBody: any;
89
+
90
+ if (useProxy) {
91
+ headers['Authorization'] = `Bearer ${token}`;
92
+ requestBody = buildProxyPayload(bodyData, api, agentConfig);
93
+ } else {
94
+ const directApiKey = agentConfig.apiKey?.trim();
95
+ if (directApiKey) {
96
+ headers['Authorization'] = `Bearer ${directApiKey}`;
97
+ }
98
+ requestBody = bodyData;
99
+ }
100
+
101
+ console.log('[SSE Native] Creating EventSource for:', url);
102
+
103
+ const es = new EventSource(url, {
104
+ method: 'POST',
105
+ headers,
106
+ body: JSON.stringify(requestBody),
107
+ pollingInterval: 0,
108
+ });
109
+
110
+ let isCompleted = false;
111
+
112
+ const cleanup = () => {
113
+ if (!isCompleted) {
114
+ isCompleted = true;
115
+ es.close();
116
+ }
117
+ };
118
+
119
+ // 处理消息事件
120
+ es.addEventListener('message', (event: any) => {
121
+ // console.log('[SSE Native] Message event received:', event);
122
+ if (event.data) {
123
+ // console.log('[SSE Native] Chunk data:', event.data.substring(0, 100));
124
+ // 包装成 SSE 格式
125
+ onChunk(`data: ${event.data}\n\n`);
126
+ }
127
+ });
128
+
129
+ // 处理打开事件
130
+ es.addEventListener('open', () => {
131
+ console.log('[SSE Native] Connection opened');
132
+ });
133
+
134
+ // 处理错误
135
+ es.addEventListener('error', (event: any) => {
136
+ console.error('SSE Error event:', event);
137
+
138
+ // react-native-sse 有时会把结束信号当做 error 发送 (xhrStatus 200, but type error)
139
+ // 或者简单的网络错误
140
+
141
+ // 如果是正常结束(有些实现会把 close 当 error 发)
142
+ if (event.type === 'error' && !event.message && !event.xhrStatus) {
143
+ // 可能是连接关闭
144
+ console.log('[SSE Native] Empty error event, treating as close/complete');
145
+ if (!isCompleted) {
146
+ onComplete();
147
+ cleanup();
148
+ }
149
+ return;
150
+ }
151
+
152
+ if (!isCompleted) {
153
+ // 检查是否包含 [DONE] 或者 status 200 但解析失败
154
+ if (event.message?.includes('[DONE]')) {
155
+ onComplete();
156
+ } else {
157
+ onError(new Error(event.message || 'SSE connection error'));
158
+ }
159
+ cleanup();
160
+ }
161
+ });
162
+
163
+ // 处理关闭
164
+ es.addEventListener('close', () => {
165
+ console.log('[SSE Native] Connection closed');
166
+ if (!isCompleted) {
167
+ onComplete();
168
+ cleanup();
169
+ }
170
+ });
171
+
172
+ // 处理 abort signal
173
+ if (signal) {
174
+ signal.addEventListener('abort', () => {
175
+ // console.log('[SSE Native] Aborted by signal');
176
+ cleanup();
177
+ onComplete();
178
+ });
179
+ }
180
+
181
+ // 返回 cleanup 函数
182
+ return cleanup;
183
+ };
184
+
185
+ /**
186
+ * React Native 版普通 fetch 请求 (非流式)
187
+ * 保持与 web 版相同的接口
188
+ */
189
+ const fetchDirectly = async ({
190
+ api,
191
+ agentConfig,
192
+ bodyData,
193
+ signal,
194
+ }: Omit<FetchParams, "currentServer" | "token">): Promise<Response> => {
195
+ try {
196
+ const apiKey = agentConfig.apiKey?.trim();
197
+ return await fetch(api, {
198
+ method: "POST",
199
+ headers: {
200
+ "Content-Type": "application/json",
201
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
202
+ ...(api.includes("openrouter.ai") ? {
203
+ "HTTP-Referer": "https://nolo.chat",
204
+ "X-Title": "nolo"
205
+ } : {})
206
+ },
207
+ body: JSON.stringify(bodyData),
208
+ signal,
209
+ });
210
+ } catch (error: any) {
211
+ console.error("[fetchDirectly] 网络请求失败:", error);
212
+ throw error;
213
+ }
214
+ };
215
+
216
+ const fetchWithServerProxy = async ({
217
+ currentServer,
218
+ api,
219
+ bodyData,
220
+ agentConfig,
221
+ token,
222
+ signal,
223
+ }: FetchParams): Promise<Response> => {
224
+ try {
225
+ const payload = buildProxyPayload(bodyData, api, agentConfig);
226
+
227
+ let response = await fetch(`${currentServer}${API_ENDPOINTS.CHAT}`, {
228
+ method: "POST",
229
+ headers: {
230
+ "Content-Type": "application/json",
231
+ Authorization: `Bearer ${token}`,
232
+ },
233
+ body: JSON.stringify(payload),
234
+ signal,
235
+ });
236
+
237
+ if (response.status === 503) {
238
+ console.warn("[fetchWithServerProxy] 检测到503状态,重试一次...");
239
+ response = await fetch(`${currentServer}${API_ENDPOINTS.CHAT}`, {
240
+ method: "POST",
241
+ headers: {
242
+ "Content-Type": "application/json",
243
+ Authorization: `Bearer ${token}`,
244
+ },
245
+ body: JSON.stringify(payload),
246
+ signal,
247
+ });
248
+ }
249
+
250
+ return response;
251
+ } catch (error: any) {
252
+ console.error("[fetchWithServerProxy] 网络请求失败:", error);
253
+ throw error;
254
+ }
255
+ };
256
+
257
+ export const performFetchRequest = async (
258
+ params: FetchParams
259
+ ): Promise<Response> => {
260
+ try {
261
+ return shouldUseServerProxy(
262
+ params.agentConfig,
263
+ params.bodyData.provider,
264
+ )
265
+ ? await fetchWithServerProxy(params)
266
+ : await fetchDirectly(params);
267
+ } catch (error: any) {
268
+ console.error("[performFetchRequest] 请求过程中发生错误:", error);
269
+ throw new Error(`网络请求失败: ${error.message || String(error)}`);
270
+ }
271
+ };
272
+
273
+ /**
274
+ * 标识当前是 React Native 环境
275
+ */
276
+ export const isNativeSSE = true;
@@ -0,0 +1,153 @@
1
+ // 文件路径: ai/chat/fetchUtils.ts
2
+ import { Agent } from "app/types";
3
+
4
+ import { API_ENDPOINTS } from "database/config";
5
+ import { shouldUseServerProxy } from "./shouldUseServerProxy";
6
+
7
+ interface BodyData {
8
+ model: string;
9
+ messages: any[];
10
+ stream: boolean;
11
+ tools?: any[];
12
+ provider?: string;
13
+ }
14
+
15
+ interface FetchParams {
16
+ agentConfig: Agent;
17
+ api: string;
18
+ bodyData: BodyData;
19
+ currentServer: string;
20
+ token: string;
21
+ signal?: AbortSignal; // signal 是可选的
22
+ }
23
+
24
+ const buildProxyPayload = (
25
+ bodyData: BodyData,
26
+ api: string,
27
+ agentConfig: Agent
28
+ ) => {
29
+ const apiSource =
30
+ agentConfig.apiSource === "custom" || agentConfig.apiSource === "cli"
31
+ ? agentConfig.apiSource
32
+ : undefined;
33
+ const provider =
34
+ bodyData.provider ||
35
+ agentConfig.provider ||
36
+ (apiSource === "custom" ? "custom" : undefined);
37
+ const apiKey = agentConfig.apiKey?.trim() || undefined;
38
+
39
+ return {
40
+ ...bodyData,
41
+ url: api,
42
+ provider,
43
+ ...(apiSource ? { apiSource } : {}),
44
+ KEY: apiKey,
45
+ };
46
+ };
47
+
48
+ const fetchDirectly = async ({
49
+ api,
50
+ agentConfig,
51
+ bodyData,
52
+ signal,
53
+ }: Omit<FetchParams, "currentServer" | "token">): Promise<Response> => {
54
+ try {
55
+ const apiKey = agentConfig.apiKey?.trim();
56
+ return await fetch(api, {
57
+ method: "POST",
58
+ headers: {
59
+ "Content-Type": "application/json",
60
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
61
+ ...(api.includes("openrouter.ai") ? {
62
+ "HTTP-Referer": "https://nolo.chat",
63
+ "X-Title": "nolo"
64
+ } : {})
65
+ },
66
+ body: JSON.stringify(bodyData),
67
+ signal, // 可选参数,直接传递
68
+ });
69
+ } catch (error: any) {
70
+ console.error("[fetchDirectly] 网络请求失败:", error);
71
+ throw error; // 抛出错误,交给上层处理
72
+ }
73
+ };
74
+
75
+ const fetchWithServerProxy = async ({
76
+ currentServer,
77
+ api,
78
+ bodyData,
79
+ agentConfig,
80
+ token,
81
+ signal,
82
+ }: FetchParams): Promise<Response> => {
83
+ try {
84
+ const payload = buildProxyPayload(bodyData, api, agentConfig);
85
+
86
+ let response = await fetch(`${currentServer}${API_ENDPOINTS.CHAT}`, {
87
+ method: "POST",
88
+ headers: {
89
+ "Content-Type": "application/json",
90
+ Authorization: `Bearer ${token}`, // 使用 Authorization 头传递 token
91
+ },
92
+ body: JSON.stringify(payload),
93
+ signal, // 可选参数,直接传递
94
+ });
95
+
96
+ // 如果状态码是503,重试一次
97
+ if (response.status === 503) {
98
+ console.warn("[fetchWithServerProxy] 检测到503状态,重试一次...");
99
+ response = await fetch(`${currentServer}${API_ENDPOINTS.CHAT}`, {
100
+ method: "POST",
101
+ headers: {
102
+ "Content-Type": "application/json",
103
+ Authorization: `Bearer ${token}`,
104
+ },
105
+ body: JSON.stringify(payload),
106
+ signal,
107
+ });
108
+ }
109
+
110
+ return response;
111
+ } catch (error: any) {
112
+ console.error("[fetchWithServerProxy] 网络请求失败:", error);
113
+ throw error; // 抛出错误,交给上层处理
114
+ }
115
+ };
116
+ export const performFetchRequest = async (
117
+ params: FetchParams
118
+ ): Promise<Response> => {
119
+ try {
120
+ return shouldUseServerProxy(
121
+ params.agentConfig,
122
+ params.bodyData.provider
123
+ )
124
+ ? await fetchWithServerProxy(params)
125
+ : await fetchDirectly(params);
126
+ } catch (error: any) {
127
+ console.error("[performFetchRequest] 请求过程中发生错误:", error);
128
+ // 如果是网络错误,抛出自定义错误对象,以便上层捕获
129
+ throw new Error(`网络请求失败: ${error.message || String(error)}`);
130
+ }
131
+ };
132
+
133
+ // SSE 流式请求参数(与 native 版本保持一致的接口)
134
+ interface SSEFetchParams extends FetchParams {
135
+ onChunk: (chunk: string) => void;
136
+ onError: (error: Error) => void;
137
+ onComplete: () => void;
138
+ }
139
+
140
+ /**
141
+ * Web 版流式 SSE 请求 - 占位函数
142
+ * Web 版不使用此函数,而是使用 performFetchRequest + ReadableStream
143
+ * 此函数仅为类型兼容而存在
144
+ */
145
+ export const performSSEFetchRequest = (_params: SSEFetchParams): (() => void) => {
146
+ throw new Error('performSSEFetchRequest should not be called on web platform');
147
+ };
148
+
149
+ /**
150
+ * 标识当前是否为 React Native 环境
151
+ * Web 版返回 false
152
+ */
153
+ export const isNativeSSE = false;
@@ -0,0 +1,117 @@
1
+ type ImageFetchResult = {
2
+ ok: boolean;
3
+ mimeType?: string;
4
+ bytes?: Uint8Array;
5
+ error?: string;
6
+ };
7
+
8
+ type InlineOptions = {
9
+ shouldInline: boolean;
10
+ fetchImage?: (url: string) => Promise<ImageFetchResult>;
11
+ };
12
+
13
+ const FILE_CONTENT_PATH = "/api/v1/db/file/content/";
14
+
15
+ export const shouldInlineImageUrlsForAgent = (
16
+ agentConfig: { apiSource?: string | null; provider?: string | null } | null | undefined,
17
+ ) => {
18
+ const apiSource = agentConfig?.apiSource?.toLowerCase();
19
+ const provider = agentConfig?.provider?.toLowerCase();
20
+ return apiSource === "custom" || provider === "custom";
21
+ };
22
+
23
+ const isInlineCandidate = (url: string) =>
24
+ /^https?:\/\//i.test(url) && url.includes(FILE_CONTENT_PATH);
25
+
26
+ const bytesToBase64 = (bytes: Uint8Array) => {
27
+ let binary = "";
28
+ for (const byte of bytes) {
29
+ binary += String.fromCharCode(byte);
30
+ }
31
+ return btoa(binary);
32
+ };
33
+
34
+ const defaultFetchImage = async (url: string): Promise<ImageFetchResult> => {
35
+ const response = await fetch(url);
36
+ if (!response.ok) {
37
+ return {
38
+ ok: false,
39
+ error: `HTTP ${response.status}`,
40
+ };
41
+ }
42
+
43
+ const bytes = new Uint8Array(await response.arrayBuffer());
44
+ return {
45
+ ok: true,
46
+ mimeType: response.headers.get("content-type") ?? "application/octet-stream",
47
+ bytes,
48
+ };
49
+ };
50
+
51
+ const cloneImagePartWithDataUrl = async (
52
+ part: any,
53
+ fetchImage: (url: string) => Promise<ImageFetchResult>,
54
+ ) => {
55
+ const url = part?.image_url?.url;
56
+ if (typeof url !== "string" || !isInlineCandidate(url)) return part;
57
+
58
+ const result = await fetchImage(url);
59
+ if (!result.ok || !result.bytes) {
60
+ throw new Error(
61
+ `Failed to inline custom provider image URL ${url}: ${result.error ?? "unknown error"}`,
62
+ );
63
+ }
64
+
65
+ const mimeType = result.mimeType || "application/octet-stream";
66
+ return {
67
+ ...part,
68
+ image_url: {
69
+ ...part.image_url,
70
+ url: `data:${mimeType};base64,${bytesToBase64(result.bytes)}`,
71
+ },
72
+ };
73
+ };
74
+
75
+ export const inlineImageUrlsForCustomProvider = async <T>(
76
+ bodyData: T,
77
+ options: InlineOptions,
78
+ ): Promise<T> => {
79
+ if (!options.shouldInline) return bodyData;
80
+
81
+ const body: any = bodyData;
82
+ if (!Array.isArray(body?.messages)) return bodyData;
83
+
84
+ const fetchImage = options.fetchImage ?? defaultFetchImage;
85
+ let changed = false;
86
+ const messages = [];
87
+
88
+ for (const message of body.messages) {
89
+ if (!Array.isArray(message?.content)) {
90
+ messages.push(message);
91
+ continue;
92
+ }
93
+
94
+ const content = [];
95
+ let messageChanged = false;
96
+ for (const part of message.content) {
97
+ if (part?.type !== "image_url") {
98
+ content.push(part);
99
+ continue;
100
+ }
101
+ const nextPart = await cloneImagePartWithDataUrl(part, fetchImage);
102
+ if (nextPart !== part) {
103
+ changed = true;
104
+ messageChanged = true;
105
+ }
106
+ content.push(nextPart);
107
+ }
108
+
109
+ messages.push(messageChanged ? { ...message, content } : message);
110
+ }
111
+
112
+ if (!changed) return bodyData;
113
+ return {
114
+ ...body,
115
+ messages,
116
+ };
117
+ };
@@ -0,0 +1,64 @@
1
+ // 处理失败的API响应
2
+ export async function parseApiError(response: Response): Promise<string> {
3
+ const errorBody = await response.text();
4
+ const truncateErrorMessage = (message: string, maxChars = 320): string =>
5
+ message.length <= maxChars ? message : `${message.slice(0, maxChars)}…`;
6
+ const isContextOverflow = (message: string): boolean =>
7
+ /maximum context length|context length|context_length_exceeded|requested about .*tokens|too many tokens/i.test(message);
8
+ let defaultMessage = `状态码 ${response.status} ${response.statusText}`;
9
+ let errorMessage = defaultMessage;
10
+ let errorCode: string | null = `E${response.status}`;
11
+
12
+ try {
13
+ const errorJson = JSON.parse(errorBody);
14
+ errorMessage = errorJson?.error?.message
15
+ || errorJson?.message
16
+ || errorJson?.msg
17
+ || errorBody
18
+ || defaultMessage;
19
+ errorCode = errorJson?.error?.code || errorJson?.code || errorCode;
20
+ } catch (_e) {
21
+ if (errorBody) {
22
+ errorMessage = errorBody;
23
+ }
24
+ }
25
+
26
+ switch (response.status) {
27
+ case 400:
28
+ if (isContextOverflow(errorMessage) || isContextOverflow(errorBody) || errorCode === "UPSTREAM_400") {
29
+ return "上下文过长:本轮消息或工具结果太大。请缩小范围,或先读取更小片段后再继续。";
30
+ }
31
+ if (errorMessage && errorMessage !== defaultMessage) {
32
+ return `请求参数错误: ${truncateErrorMessage(errorMessage)}`;
33
+ }
34
+ return "请求参数错误,请检查输入";
35
+ case 413:
36
+ return "请求内容过大:请减少一次发送的消息、文件或工具结果。";
37
+ case 401:
38
+ switch (errorCode) {
39
+ case "AUTH_TOKEN_EXPIRED":
40
+ return "登录状态已过期,请先登出后重新登录";
41
+ case "AUTH_ACCOUNT_INVALID":
42
+ return "账户无效或已被停用,请联系管理员";
43
+ case "AUTH_NO_TOKEN":
44
+ return "未检测到登录状态,请先登录";
45
+ case "AUTH_INVALID_TOKEN":
46
+ return "登录凭证无效,请先登出后重新登录";
47
+ case "AUTH_TOKEN_NOT_ACTIVE":
48
+ return "令牌尚未生效,请稍后再试";
49
+ default:
50
+ // 避免把第三方 API 的 401(如 OpenRouter key 缺失)误显示为"请先登出重登"
51
+ return errorMessage && errorMessage !== `状态码 401 Unauthorized`
52
+ ? `认证错误: ${truncateErrorMessage(errorMessage)}`
53
+ : "身份验证失败,请先登出后重新登录";
54
+ }
55
+ case 503:
56
+ return errorMessage && errorMessage !== `状态码 503 Service Unavailable`
57
+ ? truncateErrorMessage(errorMessage)
58
+ : "服务暂时不可用,请稍后再试";
59
+ case 504:
60
+ return "请求超时,请稍后再试";
61
+ default:
62
+ return `API请求失败: ${truncateErrorMessage(errorMessage)}`;
63
+ }
64
+ }