nolo-cli 0.1.10 → 0.1.12

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 (232) hide show
  1. package/README.md +0 -32
  2. package/agentRuntimeCommands.ts +1 -1
  3. package/client/compactDialog.ts +2 -5
  4. package/commandRegistry.ts +2 -2
  5. package/machineCommands.ts +28 -3
  6. package/package.json +5 -25
  7. package/ai/agent/_executeModel.ts +0 -118
  8. package/ai/agent/agentSlice.ts +0 -525
  9. package/ai/agent/appWorkingMemory.ts +0 -126
  10. package/ai/agent/avatarUtils.ts +0 -24
  11. package/ai/agent/buildEditingContext.ts +0 -373
  12. package/ai/agent/buildSystemPrompt.ts +0 -532
  13. package/ai/agent/cleanAgentMessages.ts +0 -140
  14. package/ai/agent/cliChatClient.ts +0 -119
  15. package/ai/agent/contextCompiler.ts +0 -107
  16. package/ai/agent/contextLayerContract.ts +0 -44
  17. package/ai/agent/createAgentSchema.ts +0 -234
  18. package/ai/agent/executeToolCall.ts +0 -58
  19. package/ai/agent/fetchAgentContexts.ts +0 -42
  20. package/ai/agent/generatePrompt.ts +0 -3
  21. package/ai/agent/getFullChatContextKeys.ts +0 -168
  22. package/ai/agent/hooks/fetchPublicAgents.ts +0 -133
  23. package/ai/agent/hooks/useAgentConfig.ts +0 -61
  24. package/ai/agent/hooks/useAgentDialog.ts +0 -35
  25. package/ai/agent/hooks/useAgentFormValidation.ts +0 -202
  26. package/ai/agent/hooks/usePublicAgents.ts +0 -473
  27. package/ai/agent/persistMessageWithFixedId.ts +0 -37
  28. package/ai/agent/planSlice.ts +0 -259
  29. package/ai/agent/referenceUtils.ts +0 -229
  30. package/ai/agent/runAgentBackground.ts +0 -238
  31. package/ai/agent/runAgentClientLoop.ts +0 -138
  32. package/ai/agent/runtimeGuidance.ts +0 -97
  33. package/ai/agent/runtimeServerBase.ts +0 -37
  34. package/ai/agent/server/fetchPublicAgents.ts +0 -128
  35. package/ai/agent/startParallelAgentStreams.ts +0 -424
  36. package/ai/agent/startupProtocol.ts +0 -53
  37. package/ai/agent/streamAgentChatTurn.ts +0 -1278
  38. package/ai/agent/streamAgentChatTurnUtils.ts +0 -738
  39. package/ai/agent/types.ts +0 -71
  40. package/ai/agent/utils/imageOutput.ts +0 -33
  41. package/ai/agent/utils/sortUtils.ts +0 -250
  42. package/ai/agent/web/referencePickerUtils.ts +0 -146
  43. package/ai/ai.locale.ts +0 -1079
  44. package/ai/chat/accumulateToolCallChunks.ts +0 -95
  45. package/ai/chat/fetchUtils.native.ts +0 -276
  46. package/ai/chat/fetchUtils.ts +0 -153
  47. package/ai/chat/parseApiError.ts +0 -64
  48. package/ai/chat/parseMultilineSSE.ts +0 -95
  49. package/ai/chat/sendOpenAICompletionsRequest.native.ts +0 -682
  50. package/ai/chat/sendOpenAICompletionsRequest.ts +0 -703
  51. package/ai/chat/sendOpenAIResponseRequest.ts +0 -491
  52. package/ai/chat/shouldUseServerProxy.ts +0 -18
  53. package/ai/chat/sseClient.native.ts +0 -91
  54. package/ai/chat/sseClient.ts +0 -67
  55. package/ai/chat/streamReader.native.ts +0 -31
  56. package/ai/chat/streamReader.ts +0 -62
  57. package/ai/chat/updateTotalUsage.ts +0 -72
  58. package/ai/context/buildReferenceContext.ts +0 -437
  59. package/ai/context/calculateContextUsage.ts +0 -133
  60. package/ai/context/retention.ts +0 -165
  61. package/ai/context/tokenUtils.ts +0 -78
  62. package/ai/index.ts +0 -1
  63. package/ai/llm/calculateGeminiImageTokens.ts +0 -57
  64. package/ai/llm/deepinfra.ts +0 -28
  65. package/ai/llm/fireworks.ts +0 -50
  66. package/ai/llm/generateRequestBody.ts +0 -165
  67. package/ai/llm/getModelContextWindow.ts +0 -84
  68. package/ai/llm/getNoloKey.ts +0 -31
  69. package/ai/llm/getPricing.ts +0 -199
  70. package/ai/llm/hooks/useModelPricing.ts +0 -75
  71. package/ai/llm/imagePricing.ts +0 -40
  72. package/ai/llm/isResponseAPIModel.ts +0 -13
  73. package/ai/llm/mimo.ts +0 -71
  74. package/ai/llm/mistral.ts +0 -22
  75. package/ai/llm/modelAvatar.ts +0 -427
  76. package/ai/llm/models.ts +0 -45
  77. package/ai/llm/openrouterModels.ts +0 -269
  78. package/ai/llm/providers.ts +0 -306
  79. package/ai/llm/reasoningModels.ts +0 -28
  80. package/ai/llm/types.ts +0 -59
  81. package/ai/llm/usageRequestOptions.ts +0 -59
  82. package/ai/memory/capture.ts +0 -148
  83. package/ai/memory/consolidate.ts +0 -104
  84. package/ai/memory/delete.ts +0 -147
  85. package/ai/memory/overlay.ts +0 -84
  86. package/ai/memory/query.ts +0 -38
  87. package/ai/memory/queryShared.ts +0 -160
  88. package/ai/memory/rank.ts +0 -105
  89. package/ai/memory/recentRelationshipRecap.ts +0 -249
  90. package/ai/memory/remember.ts +0 -167
  91. package/ai/memory/runtime.ts +0 -76
  92. package/ai/memory/store.ts +0 -20
  93. package/ai/memory/storeShared.ts +0 -76
  94. package/ai/memory/types.ts +0 -46
  95. package/ai/memory/understanding.ts +0 -349
  96. package/ai/memory/understandingGreeting.ts +0 -264
  97. package/ai/messages/type.ts +0 -20
  98. package/ai/policy/personalizationDialog.ts +0 -333
  99. package/ai/policy/runtimePolicy.ts +0 -440
  100. package/ai/policy/selfUpdateFields.ts +0 -48
  101. package/ai/policy/types.ts +0 -64
  102. package/ai/skills/referenceRuntime.ts +0 -274
  103. package/ai/skills/skillDiagnostics.ts +0 -251
  104. package/ai/skills/skillDocBuilder.ts +0 -139
  105. package/ai/skills/skillDocProtocol.ts +0 -434
  106. package/ai/skills/skillReferenceSummary.ts +0 -63
  107. package/ai/skills/skillSummaryMarker.ts +0 -26
  108. package/ai/token/calculatePrice.ts +0 -544
  109. package/ai/token/db.ts +0 -98
  110. package/ai/token/externalToolCost.ts +0 -330
  111. package/ai/token/hooks/useRecords.ts +0 -65
  112. package/ai/token/missingUsageEstimate.ts +0 -42
  113. package/ai/token/modelUsageQuery.ts +0 -252
  114. package/ai/token/normalizeUsage.ts +0 -84
  115. package/ai/token/openaiImageGenerationUsage.ts +0 -56
  116. package/ai/token/prepareTokenUsageData.ts +0 -88
  117. package/ai/token/query.ts +0 -88
  118. package/ai/token/queryUserTokens.ts +0 -59
  119. package/ai/token/resolveBillingTarget.ts +0 -52
  120. package/ai/token/saveTokenRecord.ts +0 -53
  121. package/ai/token/serverDialogProjection.ts +0 -78
  122. package/ai/token/serverTokenWriter.ts +0 -143
  123. package/ai/token/stats.ts +0 -21
  124. package/ai/token/tokenThunks.ts +0 -24
  125. package/ai/token/types.ts +0 -93
  126. package/ai/tools/agent/agentTools.ts +0 -176
  127. package/ai/tools/agent/agentUpdateShared.ts +0 -311
  128. package/ai/tools/agent/callAgentTool.ts +0 -139
  129. package/ai/tools/agent/createAgentTool.ts +0 -512
  130. package/ai/tools/agent/createDialogTool.ts +0 -69
  131. package/ai/tools/agent/createSkillAgentTool.ts +0 -62
  132. package/ai/tools/agent/parallelBudget.ts +0 -221
  133. package/ai/tools/agent/presets/appBuilderPreset.ts +0 -145
  134. package/ai/tools/agent/runLlmTool.ts +0 -96
  135. package/ai/tools/agent/runStreamingAgentTool.ts +0 -73
  136. package/ai/tools/agent/skillAgentArgs.ts +0 -106
  137. package/ai/tools/agent/skillAgentPreset.ts +0 -89
  138. package/ai/tools/agent/streamParallelAgentsTool.ts +0 -122
  139. package/ai/tools/agent/updateAgentTool.ts +0 -96
  140. package/ai/tools/agent/updateSelfTool.ts +0 -113
  141. package/ai/tools/amazonProductScraperTool.ts +0 -86
  142. package/ai/tools/apifyActorClient.ts +0 -45
  143. package/ai/tools/appEditGuard.ts +0 -372
  144. package/ai/tools/appReadSnapshot.ts +0 -153
  145. package/ai/tools/appTools.ts +0 -1549
  146. package/ai/tools/applyEditTool.ts +0 -256
  147. package/ai/tools/applyLineEditsTool.ts +0 -312
  148. package/ai/tools/browserTools/click.ts +0 -33
  149. package/ai/tools/browserTools/closeSession.ts +0 -29
  150. package/ai/tools/browserTools/common.ts +0 -27
  151. package/ai/tools/browserTools/openSession.ts +0 -48
  152. package/ai/tools/browserTools/readContent.ts +0 -38
  153. package/ai/tools/browserTools/selectOption.ts +0 -46
  154. package/ai/tools/browserTools/typeText.ts +0 -42
  155. package/ai/tools/category/createCategoryTool.ts +0 -66
  156. package/ai/tools/category/queryContentsByCategoryTool.ts +0 -69
  157. package/ai/tools/category/updateContentCategoryTool.ts +0 -75
  158. package/ai/tools/cfBrowserTools.ts +0 -319
  159. package/ai/tools/cfSpeechToTextTool.ts +0 -49
  160. package/ai/tools/checkEnvTool.ts +0 -65
  161. package/ai/tools/cloudflareCrawlTool.ts +0 -289
  162. package/ai/tools/codeSearchTool.ts +0 -111
  163. package/ai/tools/codeTools.ts +0 -101
  164. package/ai/tools/createDocTool.ts +0 -132
  165. package/ai/tools/createPlanTool.ts +0 -999
  166. package/ai/tools/createSkillDocTool.ts +0 -155
  167. package/ai/tools/createWorkflowTool.ts +0 -154
  168. package/ai/tools/deepseekOcrTool.ts +0 -34
  169. package/ai/tools/delayTool.ts +0 -31
  170. package/ai/tools/deleteSpacesTool.ts +0 -325
  171. package/ai/tools/deleteSpacesToolModel.ts +0 -159
  172. package/ai/tools/devReloadUtils.ts +0 -29
  173. package/ai/tools/dialogMessageSearch.ts +0 -137
  174. package/ai/tools/doctorSkillTool.ts +0 -72
  175. package/ai/tools/ecommerceScraperTool.ts +0 -86
  176. package/ai/tools/emailTools.ts +0 -549
  177. package/ai/tools/evalSkillTool.ts +0 -92
  178. package/ai/tools/exaSearchTool.ts +0 -64
  179. package/ai/tools/execBashTool.ts +0 -379
  180. package/ai/tools/executeSqlTool.ts +0 -192
  181. package/ai/tools/fetchWebpageSupport.ts +0 -309
  182. package/ai/tools/fetchWebpageTool.ts +0 -84
  183. package/ai/tools/geminiImagePreviewTool.ts +0 -361
  184. package/ai/tools/generateDocxTool.ts +0 -215
  185. package/ai/tools/googleSearchScraperTool.ts +0 -106
  186. package/ai/tools/importDataTool.ts +0 -133
  187. package/ai/tools/importSkillTool.ts +0 -162
  188. package/ai/tools/index.ts +0 -1858
  189. package/ai/tools/listFilesTool.ts +0 -82
  190. package/ai/tools/listUserSpacesTool.ts +0 -113
  191. package/ai/tools/modelUsageTools.ts +0 -142
  192. package/ai/tools/olmOcrTool.ts +0 -34
  193. package/ai/tools/openaiImageTool.ts +0 -218
  194. package/ai/tools/paddleOcrTool.ts +0 -34
  195. package/ai/tools/prepareTools.ts +0 -23
  196. package/ai/tools/readDocTool.ts +0 -84
  197. package/ai/tools/readFileTool.ts +0 -211
  198. package/ai/tools/readTool.ts +0 -163
  199. package/ai/tools/readXPostTool.ts +0 -233
  200. package/ai/tools/rememberMemoryTool.ts +0 -84
  201. package/ai/tools/remotionVideoTool.ts +0 -151
  202. package/ai/tools/searchDialogMessagesTool.ts +0 -222
  203. package/ai/tools/searchRepoTool.ts +0 -115
  204. package/ai/tools/searchWorkspaceTool.ts +0 -259
  205. package/ai/tools/skillFollowup.ts +0 -86
  206. package/ai/tools/surfWeatherTool.ts +0 -169
  207. package/ai/tools/table/addTableRowTool.ts +0 -217
  208. package/ai/tools/table/createTableTool.ts +0 -315
  209. package/ai/tools/table/rowTools.ts +0 -366
  210. package/ai/tools/table/schemaTools.ts +0 -244
  211. package/ai/tools/table/shareTableTool.ts +0 -148
  212. package/ai/tools/table/toolShared.ts +0 -129
  213. package/ai/tools/toolApiClient.ts +0 -198
  214. package/ai/tools/toolNameAliases.ts +0 -57
  215. package/ai/tools/toolResultError.ts +0 -42
  216. package/ai/tools/toolRunSlice.ts +0 -303
  217. package/ai/tools/toolSchemaCompatibility.ts +0 -53
  218. package/ai/tools/toolVisibility.ts +0 -4
  219. package/ai/tools/types.ts +0 -20
  220. package/ai/tools/uiAskChoiceTool.ts +0 -104
  221. package/ai/tools/updateContentTitleTool.ts +0 -84
  222. package/ai/tools/updateDocTool.ts +0 -105
  223. package/ai/tools/updateUserPreferenceProfileTool.ts +0 -145
  224. package/ai/tools/whisperTool.ts +0 -77
  225. package/ai/tools/writeFileTool.ts +0 -210
  226. package/ai/tools/youtubeScraperTool.ts +0 -116
  227. package/ai/tools/ziweiChartTool.ts +0 -678
  228. package/ai/types.ts +0 -55
  229. package/ai/workflow/workflowExecutor.ts +0 -323
  230. package/ai/workflow/workflowSlice.ts +0 -73
  231. package/ai/workflow/workflowTypes.ts +0 -106
  232. package/connector-experimental/index.ts +0 -5
@@ -1,95 +0,0 @@
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
- }
@@ -1,276 +0,0 @@
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;
@@ -1,153 +0,0 @@
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;
@@ -1,64 +0,0 @@
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
- }
@@ -1,95 +0,0 @@
1
- // 文件路径: chat/messages/parseMultilineSSE.ts
2
-
3
- /**
4
- * 创建一个 SSE 解析器实例,支持跨 chunk 累积完整事件。
5
- *
6
- * 用法:
7
- * const parseSSE = createSSEParser();
8
- * const objs = parseSSE(chunk); // 每次网络 chunk 调一次
9
- */
10
- export function createSSEParser() {
11
- // buffer 保存「还没形成完整事件」的残余文本(跨 chunk 累积)
12
- let buffer = "";
13
-
14
- return function parseSSE(chunk: string): any[] {
15
- const results: any[] = [];
16
- if (!chunk) return results;
17
-
18
- // 追加到全局 buffer
19
- buffer += chunk;
20
-
21
- // 按 “空行” 分割成若干完整事件:
22
- // 一个 event = 若干行,以空行 (\n\n 或 \r\n\r\n) 结束
23
- const events = buffer.split(/\r?\n\r?\n/);
24
- buffer = events.pop() ?? ""; // 最后一个当作“残余”,留在 buffer
25
-
26
- for (const ev of events) {
27
- if (!ev.trim()) continue;
28
-
29
- const lines = ev.split(/\r?\n/);
30
- let accumulator = "";
31
-
32
- for (const line of lines) {
33
- const t = line.trim();
34
-
35
- // 1. 处理 [DONE]
36
- if (t === "data: [DONE]") {
37
- if (accumulator.trim()) {
38
- // 尝试解析残余
39
- try { results.push(JSON.parse(accumulator)); } catch (e) { }
40
- accumulator = "";
41
- }
42
- results.push("[DONE]");
43
- continue;
44
- }
45
-
46
- let content = "";
47
- let isDataLine = false;
48
-
49
- // 2. 提取内容
50
- if (t.startsWith("data:")) {
51
- content = line.substring(line.indexOf("data:") + 5).trim();
52
- isDataLine = true;
53
- } else if (accumulator && t && !t.startsWith("event:") && !t.startsWith("id:") && !t.startsWith("retry:")) {
54
- // 支持非标多行 JSON(没有 data: 前缀的行,视为上一行的延续)
55
- content = line;
56
- } else {
57
- continue; // 其他行或空行忽略
58
- }
59
-
60
- // 3. 尝试即时解析(针对每行都是独立 JSON 的情况)
61
- if (isDataLine && !accumulator) {
62
- // 只有在 accumulator 为空时才尝试单行解析,避免要把单行插入到多行中间
63
- try {
64
- // 快速检查:如果 content 看起来不完整(比如以 { 结尾),就别试了,直接进 acc
65
- // 但 JSON.parse 会处理。
66
- const obj = JSON.parse(content);
67
- results.push(obj);
68
- continue; // 成功解析,本行处理完毕
69
- } catch (e) {
70
- // 解析失败,说明可能是多行 JSON 的一部分
71
- }
72
- }
73
-
74
- // 4. 累积
75
- accumulator += content;
76
- }
77
-
78
- // 5. 事件结束,尝试解析累积的内容
79
- if (accumulator.trim()) {
80
- try {
81
- const obj = JSON.parse(accumulator);
82
- results.push(obj);
83
- } catch (e) {
84
- // 仍然失败?那就真没办法了,或者尝试容错
85
- // console.warn("Parse failed:", accumulator);
86
- }
87
- }
88
- }
89
-
90
- return results;
91
- };
92
- }
93
-
94
- /** 若仍需旧的函数名导入,可用此单例(但不隔离并发流) */
95
- export const parseMultilineSSE = createSSEParser();