nolo-cli 0.1.9 → 0.1.11

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 (240) hide show
  1. package/README.md +0 -32
  2. package/agentRuntimeCommands.ts +3 -3
  3. package/commandRegistry.ts +2 -2
  4. package/machineCommands.ts +31 -6
  5. package/package.json +6 -8
  6. package/ai/agent/_executeModel.ts +0 -118
  7. package/ai/agent/agentSlice.ts +0 -525
  8. package/ai/agent/appWorkingMemory.ts +0 -126
  9. package/ai/agent/avatarUtils.ts +0 -24
  10. package/ai/agent/buildEditingContext.ts +0 -373
  11. package/ai/agent/buildSystemPrompt.ts +0 -532
  12. package/ai/agent/cleanAgentMessages.ts +0 -140
  13. package/ai/agent/cliChatClient.ts +0 -119
  14. package/ai/agent/cliExecutor.ts +0 -733
  15. package/ai/agent/cliPrompt.ts +0 -10
  16. package/ai/agent/contextCompiler.ts +0 -107
  17. package/ai/agent/contextLayerContract.ts +0 -44
  18. package/ai/agent/createAgentSchema.ts +0 -234
  19. package/ai/agent/executeToolCall.ts +0 -58
  20. package/ai/agent/fetchAgentContexts.ts +0 -42
  21. package/ai/agent/generatePrompt.ts +0 -3
  22. package/ai/agent/getFullChatContextKeys.ts +0 -168
  23. package/ai/agent/hooks/fetchPublicAgents.ts +0 -133
  24. package/ai/agent/hooks/useAgentConfig.ts +0 -61
  25. package/ai/agent/hooks/useAgentDialog.ts +0 -35
  26. package/ai/agent/hooks/useAgentFormValidation.ts +0 -202
  27. package/ai/agent/hooks/usePublicAgents.ts +0 -473
  28. package/ai/agent/machineRunPermissions.ts +0 -95
  29. package/ai/agent/persistMessageWithFixedId.ts +0 -37
  30. package/ai/agent/planSlice.ts +0 -259
  31. package/ai/agent/referenceUtils.ts +0 -229
  32. package/ai/agent/runAgentBackground.ts +0 -238
  33. package/ai/agent/runAgentClientLoop.ts +0 -138
  34. package/ai/agent/runtimeGuidance.ts +0 -97
  35. package/ai/agent/runtimeServerBase.ts +0 -37
  36. package/ai/agent/server/fetchPublicAgents.ts +0 -128
  37. package/ai/agent/startParallelAgentStreams.ts +0 -424
  38. package/ai/agent/startupProtocol.ts +0 -53
  39. package/ai/agent/streamAgentChatTurn.ts +0 -1278
  40. package/ai/agent/streamAgentChatTurnUtils.ts +0 -738
  41. package/ai/agent/types.ts +0 -71
  42. package/ai/agent/utils/imageOutput.ts +0 -33
  43. package/ai/agent/utils/sortUtils.ts +0 -250
  44. package/ai/agent/web/referencePickerUtils.ts +0 -146
  45. package/ai/ai.locale.ts +0 -1075
  46. package/ai/chat/accumulateToolCallChunks.ts +0 -95
  47. package/ai/chat/fetchUtils.native.ts +0 -276
  48. package/ai/chat/fetchUtils.ts +0 -153
  49. package/ai/chat/parseApiError.ts +0 -64
  50. package/ai/chat/parseMultilineSSE.ts +0 -95
  51. package/ai/chat/sendOpenAICompletionsRequest.native.ts +0 -682
  52. package/ai/chat/sendOpenAICompletionsRequest.ts +0 -703
  53. package/ai/chat/sendOpenAIResponseRequest.ts +0 -491
  54. package/ai/chat/shouldUseServerProxy.ts +0 -18
  55. package/ai/chat/sseClient.native.ts +0 -91
  56. package/ai/chat/sseClient.ts +0 -67
  57. package/ai/chat/streamReader.native.ts +0 -31
  58. package/ai/chat/streamReader.ts +0 -62
  59. package/ai/chat/updateTotalUsage.ts +0 -72
  60. package/ai/context/buildReferenceContext.ts +0 -437
  61. package/ai/context/calculateContextUsage.ts +0 -133
  62. package/ai/context/retention.ts +0 -165
  63. package/ai/context/tokenUtils.ts +0 -78
  64. package/ai/index.ts +0 -1
  65. package/ai/llm/calculateGeminiImageTokens.ts +0 -57
  66. package/ai/llm/deepinfra.ts +0 -28
  67. package/ai/llm/fireworks.ts +0 -50
  68. package/ai/llm/generateRequestBody.ts +0 -165
  69. package/ai/llm/getModelContextWindow.ts +0 -84
  70. package/ai/llm/getNoloKey.ts +0 -31
  71. package/ai/llm/getPricing.ts +0 -199
  72. package/ai/llm/hooks/useModelPricing.ts +0 -75
  73. package/ai/llm/imagePricing.ts +0 -40
  74. package/ai/llm/isResponseAPIModel.ts +0 -13
  75. package/ai/llm/mimo.ts +0 -71
  76. package/ai/llm/mistral.ts +0 -22
  77. package/ai/llm/modelAvatar.ts +0 -427
  78. package/ai/llm/models.ts +0 -45
  79. package/ai/llm/openrouterModels.ts +0 -269
  80. package/ai/llm/providers.ts +0 -306
  81. package/ai/llm/reasoningModels.ts +0 -28
  82. package/ai/llm/types.ts +0 -59
  83. package/ai/llm/usageRequestOptions.ts +0 -59
  84. package/ai/memory/capture.ts +0 -148
  85. package/ai/memory/consolidate.ts +0 -104
  86. package/ai/memory/delete.ts +0 -147
  87. package/ai/memory/overlay.ts +0 -84
  88. package/ai/memory/query.ts +0 -38
  89. package/ai/memory/queryShared.ts +0 -160
  90. package/ai/memory/rank.ts +0 -105
  91. package/ai/memory/recentRelationshipRecap.ts +0 -249
  92. package/ai/memory/remember.ts +0 -167
  93. package/ai/memory/runtime.ts +0 -76
  94. package/ai/memory/store.ts +0 -20
  95. package/ai/memory/storeShared.ts +0 -76
  96. package/ai/memory/types.ts +0 -46
  97. package/ai/memory/understanding.ts +0 -349
  98. package/ai/memory/understandingGreeting.ts +0 -264
  99. package/ai/messages/type.ts +0 -20
  100. package/ai/policy/personalizationDialog.ts +0 -333
  101. package/ai/policy/runtimePolicy.ts +0 -440
  102. package/ai/policy/selfUpdateFields.ts +0 -48
  103. package/ai/policy/types.ts +0 -64
  104. package/ai/skills/referenceRuntime.ts +0 -274
  105. package/ai/skills/skillDiagnostics.ts +0 -251
  106. package/ai/skills/skillDocBuilder.ts +0 -139
  107. package/ai/skills/skillDocProtocol.ts +0 -434
  108. package/ai/skills/skillReferenceSummary.ts +0 -63
  109. package/ai/skills/skillSummaryMarker.ts +0 -26
  110. package/ai/token/calculatePrice.ts +0 -544
  111. package/ai/token/db.ts +0 -98
  112. package/ai/token/externalToolCost.ts +0 -330
  113. package/ai/token/hooks/useRecords.ts +0 -65
  114. package/ai/token/missingUsageEstimate.ts +0 -42
  115. package/ai/token/modelUsageQuery.ts +0 -252
  116. package/ai/token/normalizeUsage.ts +0 -84
  117. package/ai/token/openaiImageGenerationUsage.ts +0 -56
  118. package/ai/token/prepareTokenUsageData.ts +0 -88
  119. package/ai/token/query.ts +0 -88
  120. package/ai/token/queryUserTokens.ts +0 -59
  121. package/ai/token/resolveBillingTarget.ts +0 -52
  122. package/ai/token/saveTokenRecord.ts +0 -53
  123. package/ai/token/serverDialogProjection.ts +0 -78
  124. package/ai/token/serverTokenWriter.ts +0 -143
  125. package/ai/token/stats.ts +0 -21
  126. package/ai/token/tokenThunks.ts +0 -24
  127. package/ai/token/types.ts +0 -93
  128. package/ai/tools/agent/agentTools.ts +0 -176
  129. package/ai/tools/agent/agentUpdateShared.ts +0 -311
  130. package/ai/tools/agent/callAgentTool.ts +0 -139
  131. package/ai/tools/agent/createAgentTool.ts +0 -512
  132. package/ai/tools/agent/createDialogTool.ts +0 -69
  133. package/ai/tools/agent/createSkillAgentTool.ts +0 -62
  134. package/ai/tools/agent/parallelBudget.ts +0 -221
  135. package/ai/tools/agent/presets/appBuilderPreset.ts +0 -145
  136. package/ai/tools/agent/runLlmTool.ts +0 -96
  137. package/ai/tools/agent/runStreamingAgentTool.ts +0 -73
  138. package/ai/tools/agent/skillAgentArgs.ts +0 -106
  139. package/ai/tools/agent/skillAgentPreset.ts +0 -89
  140. package/ai/tools/agent/streamParallelAgentsTool.ts +0 -122
  141. package/ai/tools/agent/updateAgentTool.ts +0 -96
  142. package/ai/tools/agent/updateSelfTool.ts +0 -113
  143. package/ai/tools/amazonProductScraperTool.ts +0 -86
  144. package/ai/tools/apifyActorClient.ts +0 -45
  145. package/ai/tools/appEditGuard.ts +0 -372
  146. package/ai/tools/appReadSnapshot.ts +0 -153
  147. package/ai/tools/appTools.ts +0 -1549
  148. package/ai/tools/applyEditTool.ts +0 -256
  149. package/ai/tools/applyLineEditsTool.ts +0 -312
  150. package/ai/tools/browserTools/click.ts +0 -33
  151. package/ai/tools/browserTools/closeSession.ts +0 -29
  152. package/ai/tools/browserTools/common.ts +0 -27
  153. package/ai/tools/browserTools/openSession.ts +0 -48
  154. package/ai/tools/browserTools/readContent.ts +0 -38
  155. package/ai/tools/browserTools/selectOption.ts +0 -46
  156. package/ai/tools/browserTools/typeText.ts +0 -42
  157. package/ai/tools/category/createCategoryTool.ts +0 -66
  158. package/ai/tools/category/queryContentsByCategoryTool.ts +0 -69
  159. package/ai/tools/category/updateContentCategoryTool.ts +0 -75
  160. package/ai/tools/cfBrowserTools.ts +0 -319
  161. package/ai/tools/cfSpeechToTextTool.ts +0 -49
  162. package/ai/tools/checkEnvTool.ts +0 -65
  163. package/ai/tools/cloudflareCrawlTool.ts +0 -289
  164. package/ai/tools/codeSearchTool.ts +0 -111
  165. package/ai/tools/codeTools.ts +0 -101
  166. package/ai/tools/createDocTool.ts +0 -132
  167. package/ai/tools/createPlanTool.ts +0 -999
  168. package/ai/tools/createSkillDocTool.ts +0 -155
  169. package/ai/tools/createWorkflowTool.ts +0 -154
  170. package/ai/tools/deepseekOcrTool.ts +0 -34
  171. package/ai/tools/delayTool.ts +0 -31
  172. package/ai/tools/deleteSpacesTool.ts +0 -325
  173. package/ai/tools/deleteSpacesToolModel.ts +0 -159
  174. package/ai/tools/devReloadUtils.ts +0 -29
  175. package/ai/tools/dialogMessageSearch.ts +0 -137
  176. package/ai/tools/doctorSkillTool.ts +0 -72
  177. package/ai/tools/ecommerceScraperTool.ts +0 -86
  178. package/ai/tools/emailTools.ts +0 -549
  179. package/ai/tools/evalSkillTool.ts +0 -92
  180. package/ai/tools/exaSearchTool.ts +0 -64
  181. package/ai/tools/execBashTool.ts +0 -379
  182. package/ai/tools/executeSqlTool.ts +0 -192
  183. package/ai/tools/fetchWebpageSupport.ts +0 -309
  184. package/ai/tools/fetchWebpageTool.ts +0 -84
  185. package/ai/tools/geminiImagePreviewTool.ts +0 -361
  186. package/ai/tools/generateDocxTool.ts +0 -215
  187. package/ai/tools/googleSearchScraperTool.ts +0 -106
  188. package/ai/tools/importDataTool.ts +0 -133
  189. package/ai/tools/importSkillTool.ts +0 -162
  190. package/ai/tools/index.ts +0 -1858
  191. package/ai/tools/listFilesTool.ts +0 -82
  192. package/ai/tools/listUserSpacesTool.ts +0 -113
  193. package/ai/tools/modelUsageTools.ts +0 -142
  194. package/ai/tools/olmOcrTool.ts +0 -34
  195. package/ai/tools/openaiImageTool.ts +0 -218
  196. package/ai/tools/paddleOcrTool.ts +0 -34
  197. package/ai/tools/prepareTools.ts +0 -23
  198. package/ai/tools/readDocTool.ts +0 -84
  199. package/ai/tools/readFileTool.ts +0 -211
  200. package/ai/tools/readTool.ts +0 -163
  201. package/ai/tools/readXPostTool.ts +0 -233
  202. package/ai/tools/rememberMemoryTool.ts +0 -84
  203. package/ai/tools/remotionVideoTool.ts +0 -151
  204. package/ai/tools/searchDialogMessagesTool.ts +0 -222
  205. package/ai/tools/searchRepoTool.ts +0 -115
  206. package/ai/tools/searchWorkspaceTool.ts +0 -259
  207. package/ai/tools/skillFollowup.ts +0 -86
  208. package/ai/tools/surfWeatherTool.ts +0 -169
  209. package/ai/tools/table/addTableRowTool.ts +0 -217
  210. package/ai/tools/table/createTableTool.ts +0 -315
  211. package/ai/tools/table/rowTools.ts +0 -366
  212. package/ai/tools/table/schemaTools.ts +0 -244
  213. package/ai/tools/table/shareTableTool.ts +0 -148
  214. package/ai/tools/table/toolShared.ts +0 -129
  215. package/ai/tools/toolApiClient.ts +0 -198
  216. package/ai/tools/toolNameAliases.ts +0 -57
  217. package/ai/tools/toolResultError.ts +0 -42
  218. package/ai/tools/toolRunSlice.ts +0 -303
  219. package/ai/tools/toolSchemaCompatibility.ts +0 -53
  220. package/ai/tools/toolVisibility.ts +0 -4
  221. package/ai/tools/types.ts +0 -20
  222. package/ai/tools/uiAskChoiceTool.ts +0 -104
  223. package/ai/tools/updateContentTitleTool.ts +0 -84
  224. package/ai/tools/updateDocTool.ts +0 -105
  225. package/ai/tools/updateUserPreferenceProfileTool.ts +0 -145
  226. package/ai/tools/whisperTool.ts +0 -77
  227. package/ai/tools/writeFileTool.ts +0 -210
  228. package/ai/tools/youtubeScraperTool.ts +0 -116
  229. package/ai/tools/ziweiChartTool.ts +0 -678
  230. package/ai/types.ts +0 -55
  231. package/ai/workflow/workflowExecutor.ts +0 -323
  232. package/ai/workflow/workflowSlice.ts +0 -73
  233. package/ai/workflow/workflowTypes.ts +0 -106
  234. package/client/compactDialog.ts +0 -222
  235. package/connector-experimental/capabilities.ts +0 -73
  236. package/connector-experimental/codexBinary.ts +0 -41
  237. package/connector-experimental/heartbeatLoop.ts +0 -22
  238. package/connector-experimental/index.ts +0 -5
  239. package/connector-experimental/machineInfo.ts +0 -46
  240. package/connector-experimental/protocol.ts +0 -54
@@ -1,148 +0,0 @@
1
- import { DataType } from "create/types";
2
- import { readAndWait } from "database/dbSlice";
3
- import { shareResourceAction } from "share/action";
4
- import { hasExplicitPublicShareRequest } from "share/publicSharePolicy";
5
- import { selectAllMsgs, selectCurrentDialogId } from "chat/messages/messageSlice";
6
-
7
- type ShareTableArgs = {
8
- dbKey?: string;
9
- tenantId?: string;
10
- tableId?: string;
11
- title?: string;
12
- description?: string;
13
- visibility?: "private" | "community";
14
- };
15
-
16
- type ShareTableResult = {
17
- rawData: {
18
- token: string;
19
- key: string;
20
- url: string;
21
- };
22
- displayData: string;
23
- };
24
-
25
- export const shareTableFunctionSchema = {
26
- name: "shareTable",
27
- description:
28
- "把一张表发布为分享链接。默认用于社区分享;只有当用户明确要求公开/社区分享时才应调用。",
29
- parameters: {
30
- type: "object",
31
- properties: {
32
- dbKey: {
33
- type: "string",
34
- description: "表 meta 记录的 dbKey,例如 meta-user123-table123。",
35
- },
36
- tenantId: {
37
- type: "string",
38
- description: "表所属租户 ID。dbKey 缺失时必填。",
39
- },
40
- tableId: {
41
- type: "string",
42
- description: "表 ID。dbKey 缺失时必填。",
43
- },
44
- title: {
45
- type: "string",
46
- description: "分享标题;不传则回退为表 ID。",
47
- },
48
- description: {
49
- type: "string",
50
- description: "可选:分享描述。",
51
- },
52
- visibility: {
53
- type: "string",
54
- enum: ["private", "community"],
55
- description: "默认 community。",
56
- },
57
- },
58
- },
59
- };
60
-
61
- const resolveTableDbKey = (args: ShareTableArgs): string => {
62
- if (typeof args.dbKey === "string" && args.dbKey.trim()) {
63
- return args.dbKey.trim();
64
- }
65
- if (
66
- typeof args.tenantId === "string" &&
67
- args.tenantId.trim() &&
68
- typeof args.tableId === "string" &&
69
- args.tableId.trim()
70
- ) {
71
- return `meta-${args.tenantId.trim()}-${args.tableId.trim()}`;
72
- }
73
- throw new Error("shareTable 需要提供 dbKey,或同时提供 tenantId 和 tableId。");
74
- };
75
-
76
- const asNonEmptyString = (value: unknown): string =>
77
- typeof value === "string" && value.trim() ? value.trim() : "";
78
-
79
- const readSharedTableMeta = async (
80
- thunkApi: any,
81
- tableDbKey: string
82
- ): Promise<Record<string, unknown> | null> => {
83
- if (typeof thunkApi?.dispatch !== "function") return null;
84
- const result = await thunkApi.dispatch(readAndWait(tableDbKey));
85
- if (!readAndWait.fulfilled.match(result) || !result.payload || typeof result.payload !== "object") {
86
- return null;
87
- }
88
- return result.payload as Record<string, unknown>;
89
- };
90
-
91
- export async function shareTableFunc(
92
- args: ShareTableArgs,
93
- thunkApi: any
94
- ): Promise<ShareTableResult> {
95
- const state = thunkApi?.getState?.();
96
- const dialogId = state ? selectCurrentDialogId(state) : undefined;
97
- const latestUserInput = state
98
- ? selectAllMsgs(state, dialogId)
99
- .slice()
100
- .reverse()
101
- .find((message) => message?.role === "user" && typeof message?.content === "string")
102
- ?.content
103
- : undefined;
104
- if (!hasExplicitPublicShareRequest(latestUserInput)) {
105
- throw new Error("当前策略不允许在用户未明确要求公开/社区分享时自动发布表。");
106
- }
107
-
108
- const tableDbKey = resolveTableDbKey(args);
109
- const tableMeta =
110
- !asNonEmptyString(args.tenantId) || !asNonEmptyString(args.tableId) || !asNonEmptyString(args.title)
111
- ? await readSharedTableMeta(thunkApi, tableDbKey)
112
- : null;
113
- const tenantId = asNonEmptyString(args.tenantId) || asNonEmptyString(tableMeta?.tenantId);
114
- const tableId = asNonEmptyString(args.tableId) || asNonEmptyString(tableMeta?.tableId);
115
- const title =
116
- asNonEmptyString(args.title) ||
117
- asNonEmptyString(tableMeta?.displayName) ||
118
- asNonEmptyString(tableMeta?.title) ||
119
- tableId ||
120
- tableDbKey;
121
-
122
- const result = await shareResourceAction(
123
- {
124
- type: DataType.TABLE,
125
- data: {
126
- dbKey: tableDbKey,
127
- ...(tenantId ? { tenantId } : {}),
128
- ...(tableId ? { tableId } : {}),
129
- displayName: title,
130
- },
131
- title,
132
- description:
133
- typeof args.description === "string" && args.description.trim()
134
- ? args.description.trim()
135
- : undefined,
136
- visibility: args.visibility ?? "community",
137
- },
138
- thunkApi
139
- );
140
-
141
- return {
142
- rawData: {
143
- ...result,
144
- url: `/share/${result.token}`,
145
- },
146
- displayData: `表已分享:/share/${result.token}`,
147
- };
148
- }
@@ -1,129 +0,0 @@
1
- import type { RootState } from "app/store";
2
- import { readAndWait, patch, write } from "database/dbSlice";
3
- import { metaKey, rowKey } from "database/keys";
4
- import { DataType } from "create/types";
5
- import { loadTableRows } from "render/table/tableSlice";
6
- import type { TableMeta } from "render/table/types";
7
-
8
- export const resolveTableIdentity = (
9
- args: { tenantId?: string; tableId?: string },
10
- state: RootState
11
- ) => {
12
- const currentTable = state.table.currentTable;
13
- const tenantId = args.tenantId ?? currentTable?.tenantId;
14
- const tableId = args.tableId ?? currentTable?.tableId;
15
- return { tenantId, tableId, currentTable };
16
- };
17
-
18
- export async function loadTableMetaOrThrow(
19
- thunkApi: any,
20
- tenantId: string,
21
- tableId: string
22
- ): Promise<TableMeta> {
23
- const result = await thunkApi.dispatch(readAndWait(metaKey(tenantId, tableId)));
24
- if (!readAndWait.fulfilled.match(result) || !result.payload) {
25
- const message =
26
- (result.payload as any)?.message ||
27
- result.error?.message ||
28
- `找不到表 ${tableId} 的定义。`;
29
- throw new Error(message);
30
- }
31
- return result.payload as TableMeta;
32
- }
33
-
34
- export async function ensureRowsLoaded(
35
- thunkApi: any,
36
- tenantId: string,
37
- tableId: string
38
- ): Promise<any[]> {
39
- const result = await thunkApi.dispatch(loadTableRows({ tenantId, tableId }));
40
- if (!loadTableRows.fulfilled.match(result)) {
41
- const message =
42
- (result.payload as any) ||
43
- result.error?.message ||
44
- "加载表行失败";
45
- throw new Error(message);
46
- }
47
-
48
- const state = thunkApi.getState() as RootState;
49
- return state.table.rows.filter(
50
- (row: any) => row?.tenantId === tenantId && row?.tableId === tableId && !row?.deletedAt
51
- );
52
- }
53
-
54
- export async function resolveRowOrThrow(
55
- thunkApi: any,
56
- args: { tenantId: string; tableId: string; rowId?: string; dbKey?: string }
57
- ) {
58
- const { tenantId, tableId, rowId, dbKey } = args;
59
-
60
- if (!rowId && !dbKey) {
61
- throw new Error("需要提供 rowId 或 dbKey 才能定位表行。");
62
- }
63
-
64
- const finalDbKey = dbKey || rowKey.single(tenantId, tableId, String(rowId));
65
- const readResult = await thunkApi.dispatch(readAndWait(finalDbKey));
66
- if (readAndWait.fulfilled.match(readResult) && readResult.payload && !readResult.payload.deletedAt) {
67
- return readResult.payload;
68
- }
69
-
70
- const rows = await ensureRowsLoaded(thunkApi, tenantId, tableId);
71
- const found = rows.find((row) => row?.dbKey === finalDbKey || row?.rowId === rowId);
72
- if (!found) {
73
- throw new Error(`找不到要操作的行:${rowId || finalDbKey}`);
74
- }
75
- return found;
76
- }
77
-
78
- export async function writeRow(thunkApi: any, row: any) {
79
- const result = await thunkApi.dispatch(
80
- write({
81
- data: row,
82
- customKey: row.dbKey,
83
- })
84
- );
85
- if (!write.fulfilled.match(result)) {
86
- const message =
87
- (result.payload as any)?.message ||
88
- result.error?.message ||
89
- "写入表行失败";
90
- throw new Error(message);
91
- }
92
- return result.payload;
93
- }
94
-
95
- export async function patchRecord(thunkApi: any, dbKey: string, changes: Record<string, any>) {
96
- const result = await thunkApi.dispatch(
97
- patch({
98
- dbKey,
99
- changes,
100
- })
101
- );
102
- if (!patch.fulfilled.match(result)) {
103
- const message =
104
- (result.payload as any)?.message ||
105
- result.error?.message ||
106
- `更新记录失败:${dbKey}`;
107
- throw new Error(message);
108
- }
109
- return result.payload;
110
- }
111
-
112
- export function buildNewRow(
113
- tenantId: string,
114
- tableId: string,
115
- values: Record<string, any>
116
- ) {
117
- const { dbKey, rowId } = rowKey.create(tenantId, tableId);
118
- const now = new Date().toISOString();
119
- return {
120
- dbKey,
121
- tenantId,
122
- tableId,
123
- rowId,
124
- createdAt: now,
125
- updatedAt: now,
126
- type: DataType.TABLE_ROW as const,
127
- ...values,
128
- };
129
- }
@@ -1,198 +0,0 @@
1
- /**
2
- * toolApiClient.ts
3
- *
4
- * 所有 AI tool 调用后端 API 的统一工具模块。
5
- *
6
- * 解决的问题:
7
- * - 相对路径(如 "/api/xxx")在 React Native 中无法解析。
8
- * - 多个 tool 文件中重复定义相同的 getRequestConfig / buildRequestHeaders 等辅助函数。
9
- *
10
- * 使用方式:
11
- * const data = await callToolApi(thunkApi, "/api/exa-search", body);
12
- * const data = await callToolApi(thunkApi, "/api/apify-actor", body, { withAuth: true });
13
- */
14
-
15
- import type { RootState } from "app/store";
16
- import { selectCurrentServer } from "app/settings/settingSlice";
17
- import { selectCurrentToken } from "auth/authSlice";
18
- import { selectCurrentDialogKey } from "chat/dialog/dialogSlice";
19
- import { extractCustomId } from "core/prefix";
20
-
21
- // ─────────────────────────────────────────────
22
- // 基础提取:从 Redux state 中获取服务器配置
23
- // ─────────────────────────────────────────────
24
-
25
- export interface RequestConfig {
26
- currentServer: string;
27
- token: string | null;
28
- }
29
-
30
- export interface ToolRequestContext extends RequestConfig {
31
- baseUrl: string;
32
- }
33
-
34
- export const resolveToolBaseUrl = (currentServer?: string | null): string => {
35
- const _window = (globalThis as any).window;
36
- if (!_window) return (currentServer || "").replace(/\/+$/, "");
37
- const fallbackLocal = _window.location.origin;
38
- if (!currentServer) return fallbackLocal;
39
- return currentServer.replace(/\/+$/, "");
40
- };
41
-
42
- export const getRequestConfig = (thunkApi: any): RequestConfig => {
43
- const state = thunkApi.getState() as RootState;
44
- const currentServer = selectCurrentServer(state);
45
- const token = selectCurrentToken(state);
46
- if (!currentServer) throw new Error("无法获取当前服务器地址。");
47
- return { currentServer, token };
48
- };
49
-
50
- export const getToolBaseUrl = (thunkApi: any): string => {
51
- const { currentServer } = getRequestConfig(thunkApi);
52
- const baseUrl = resolveToolBaseUrl(currentServer);
53
- if (!baseUrl) throw new Error("无法获取工具服务器地址。");
54
- return baseUrl;
55
- };
56
-
57
- export const getToolRequestContext = (thunkApi: any): ToolRequestContext => {
58
- const { currentServer, token } = getRequestConfig(thunkApi);
59
- const baseUrl = resolveToolBaseUrl(currentServer);
60
- if (!baseUrl) throw new Error("无法获取工具服务器地址。");
61
- return {
62
- currentServer,
63
- token,
64
- baseUrl,
65
- };
66
- };
67
-
68
- // ─────────────────────────────────────────────
69
- // 统一 POST 请求入口
70
- // ─────────────────────────────────────────────
71
-
72
- export interface CallToolApiOptions {
73
- /** 是否在请求头中附带 Authorization token,默认 false */
74
- withAuth?: boolean;
75
- }
76
-
77
- const maybeAttachDialogId = (thunkApi: any, body: object): object => {
78
- if (!body || typeof body !== "object" || Array.isArray(body)) return body;
79
- if ("dialogId" in body) return body;
80
-
81
- const state = thunkApi.getState() as RootState;
82
- const currentDialogKey = selectCurrentDialogKey(state);
83
- const dialogId = currentDialogKey ? extractCustomId(currentDialogKey) : null;
84
- if (!dialogId) return body;
85
-
86
- return {
87
- ...body,
88
- dialogId,
89
- };
90
- };
91
-
92
- export class ToolApiError extends Error {
93
- status?: number;
94
- code?: string;
95
- details?: unknown;
96
-
97
- constructor(message: string, options?: { status?: number; code?: string; details?: unknown }) {
98
- super(message);
99
- this.name = "ToolApiError";
100
- this.status = options?.status;
101
- this.code = options?.code;
102
- this.details = options?.details;
103
- }
104
- }
105
-
106
- const buildResponsePreview = (text: string): string =>
107
- text
108
- .replace(/\s+/g, " ")
109
- .trim()
110
- .slice(0, 240);
111
-
112
- const looksLikeHtmlResponse = (text: string, contentType: string | null): boolean => {
113
- if (contentType?.toLowerCase().includes("text/html")) return true;
114
- const trimmed = text.trim().toLowerCase();
115
- return trimmed.startsWith("<!doctype html") || trimmed.startsWith("<html");
116
- };
117
-
118
- /**
119
- * 向本项目后端发起 POST 请求的统一封装。
120
- * - 自动从 Redux state 中读取 currentServer,构建完整 URL(兼容 Web & RN)。
121
- * - 自动处理错误响应,抛出包含状态码和错误信息的 Error。
122
- *
123
- * @param thunkApi Redux Thunk API
124
- * @param path API 路径,如 "/api/exa-search"
125
- * @param body 请求体对象
126
- * @param options 选项:{ withAuth } 是否附带 token
127
- * @returns 解析后的 JSON 数据
128
- */
129
- export async function callToolApi<T = any>(
130
- thunkApi: any,
131
- path: string,
132
- body: object,
133
- options: CallToolApiOptions = {}
134
- ): Promise<T> {
135
- const { withAuth = false } = options;
136
- const { currentServer, token } = getRequestConfig(thunkApi);
137
-
138
- const url = `${currentServer}${path}`;
139
- const headers: Record<string, string> = { "Content-Type": "application/json" };
140
- if (withAuth && token) {
141
- headers["Authorization"] = `Bearer ${token}`;
142
- }
143
-
144
- const response = await fetch(url, {
145
- method: "POST",
146
- headers,
147
- body: JSON.stringify(maybeAttachDialogId(thunkApi, body)),
148
- });
149
-
150
- const contentType = response.headers.get("content-type");
151
- const responseText = await response.text();
152
-
153
- if (!response.ok) {
154
- let errorMessage = `API 请求失败,状态码: ${response.status}`;
155
- let errorCode: string | undefined;
156
- let errorDetails: unknown;
157
- try {
158
- const errorData = JSON.parse(responseText) as Record<string, any>;
159
- const err = errorData?.error;
160
- if (err) {
161
- errorMessage += `: ${err.message ?? JSON.stringify(err)}`;
162
- errorCode = typeof err.code === "string" ? err.code : undefined;
163
- errorDetails = err.details;
164
- }
165
- } catch {
166
- errorCode = looksLikeHtmlResponse(responseText, contentType)
167
- ? "HTML_ERROR_RESPONSE"
168
- : "NON_JSON_ERROR_RESPONSE";
169
- errorDetails = {
170
- contentType,
171
- responsePreview: buildResponsePreview(responseText),
172
- };
173
- if (typeof (errorDetails as any).responsePreview === "string" && (errorDetails as any).responsePreview) {
174
- errorMessage += `: ${(errorDetails as any).responsePreview}`;
175
- }
176
- }
177
- throw new ToolApiError(errorMessage, {
178
- status: response.status,
179
- code: errorCode,
180
- details: errorDetails,
181
- });
182
- }
183
-
184
- try {
185
- return JSON.parse(responseText) as T;
186
- } catch {
187
- throw new ToolApiError("服务端返回了无法解析的非 JSON 响应", {
188
- status: response.status,
189
- code: looksLikeHtmlResponse(responseText, contentType)
190
- ? "HTML_RESPONSE"
191
- : "INVALID_JSON_RESPONSE",
192
- details: {
193
- contentType,
194
- responsePreview: buildResponsePreview(responseText),
195
- },
196
- });
197
- }
198
- }
@@ -1,57 +0,0 @@
1
- const LEGACY_TOOL_NAME_ALIASES: Record<string, string> = {
2
- createPage: "createDoc",
3
- updatePage: "updateDoc",
4
- update_page: "updateDoc",
5
- create_page: "createDoc",
6
- fetchwebpage: "fetchWebpage",
7
- fetch_webpage: "fetchWebpage",
8
- "fetch-page": "fetchWebpage",
9
- exasearch: "exa_search",
10
- "exa-search": "exa_search",
11
- exa_search: "exa_search",
12
- readDoc: "readDoc",
13
- readpage: "readDoc",
14
- read_page: "readDoc",
15
- read_doc: "readDoc",
16
- createdoc: "createDoc",
17
- updateDocTool: "updateDoc",
18
- };
19
-
20
- const normalizeToolName = (name: string): string =>
21
- name.replace(/[-_]/g, "").toLowerCase();
22
-
23
- export const canonicalizeToolName = (rawName: string): string => {
24
- const trimmedName = rawName.trim();
25
- if (!trimmedName) return rawName;
26
-
27
- if (LEGACY_TOOL_NAME_ALIASES[trimmedName]) {
28
- return LEGACY_TOOL_NAME_ALIASES[trimmedName];
29
- }
30
-
31
- const normalizedRawName = normalizeToolName(trimmedName);
32
- const matchedAlias = Object.entries(LEGACY_TOOL_NAME_ALIASES).find(
33
- ([alias]) => normalizeToolName(alias) === normalizedRawName,
34
- );
35
-
36
- return matchedAlias?.[1] ?? trimmedName;
37
- };
38
-
39
- export const canonicalizeToolNames = (toolNames: string[]): string[] =>
40
- Array.from(
41
- new Set(
42
- toolNames
43
- .filter((toolName): toolName is string => typeof toolName === "string")
44
- .map(canonicalizeToolName),
45
- ),
46
- );
47
-
48
- export const prioritizeToolNames = (
49
- toolNames: string[],
50
- preferredToolNames: string[],
51
- ): string[] => {
52
- const canonicalTools = canonicalizeToolNames(toolNames);
53
- const preferred = new Set(canonicalizeToolNames(preferredToolNames));
54
- const prioritized = canonicalTools.filter((toolName) => preferred.has(toolName));
55
- const remaining = canonicalTools.filter((toolName) => !preferred.has(toolName));
56
- return [...prioritized, ...remaining];
57
- };
@@ -1,42 +0,0 @@
1
- export class ToolResultError extends Error {
2
- code?: string;
3
- rawData?: unknown;
4
- displayData?: string;
5
- retryable?: boolean;
6
-
7
- constructor(
8
- message: string,
9
- options?: {
10
- code?: string;
11
- rawData?: unknown;
12
- displayData?: string;
13
- retryable?: boolean;
14
- }
15
- ) {
16
- super(message);
17
- this.name = "ToolResultError";
18
- this.code = options?.code;
19
- this.rawData = options?.rawData;
20
- this.displayData = options?.displayData;
21
- this.retryable = options?.retryable;
22
- }
23
- }
24
-
25
- export const getToolResultErrorData = (error: unknown) => {
26
- if (!error || typeof error !== "object") return null;
27
- const candidate = error as {
28
- rawData?: unknown;
29
- displayData?: string;
30
- code?: string;
31
- retryable?: boolean;
32
- message?: string;
33
- };
34
- return {
35
- rawData: candidate.rawData,
36
- displayData: candidate.displayData,
37
- code: candidate.code,
38
- retryable: candidate.retryable,
39
- message: candidate.message,
40
- };
41
- };
42
-