nolo-cli 0.1.32 → 0.1.34

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 (234) hide show
  1. package/README.md +4 -10
  2. package/agent-runtime/agentRecordConfig.ts +10 -0
  3. package/agent-runtime/hostAdapter.ts +10 -1
  4. package/agent-runtime/index.ts +9 -20
  5. package/agent-runtime/localLoop.ts +49 -2
  6. package/agent-runtime/localToolPolicy.ts +76 -34
  7. package/agent-runtime/localWorkspaceTools.ts +30 -333
  8. package/agent-runtime/openAiCompatibleProvider.ts +7 -3
  9. package/agent-runtime/openAiCompatibleProviderConfig.ts +15 -26
  10. package/agent-runtime/platformChatProvider.ts +47 -73
  11. package/agent-runtime/providerResolution.ts +244 -0
  12. package/agent-runtime/runtimeToolPolicy.ts +77 -29
  13. package/agent-runtime/shellCommandPolicy.ts +120 -0
  14. package/agentAliases.ts +14 -83
  15. package/agentCommandSupport.ts +3 -6
  16. package/agentInternalCommandEntries.ts +4 -13
  17. package/agentListCommands.ts +18 -27
  18. package/agentMachineCommands.ts +40 -336
  19. package/agentPullCommand.ts +30 -55
  20. package/agentRecordCommands.ts +84 -1
  21. package/agentRecordHelpers.ts +102 -186
  22. package/agentRunCommand.ts +438 -107
  23. package/agentRuntimeLocal.ts +2 -9
  24. package/ai/agent/cliExecutor.ts +19 -323
  25. package/ai/tools/toolNameAliases.ts +70 -0
  26. package/authCommands.ts +2 -36
  27. package/cli/agentAliases.ts +14 -83
  28. package/cli/agentCommandSupport.ts +3 -6
  29. package/cli/agentInternalCommandEntries.ts +4 -13
  30. package/cli/agentListCommands.ts +18 -27
  31. package/cli/agentMachineCommands.ts +40 -336
  32. package/cli/agentPullCommand.ts +30 -55
  33. package/cli/agentRecordCommands.ts +84 -1
  34. package/cli/agentRecordHelpers.ts +102 -186
  35. package/cli/agentRunCommand.ts +438 -107
  36. package/cli/agentRuntimeLocal.ts +2 -9
  37. package/cli/authCommands.ts +2 -36
  38. package/cli/cliCommandDispatch.ts +2 -2
  39. package/cli/cliEnvHelpers.ts +34 -107
  40. package/cli/client/agentRun.ts +854 -57
  41. package/cli/client/localRuntimeAdapter.ts +59 -159
  42. package/cli/client/streamingOutput.ts +3 -1
  43. package/cli/client/taskRunPrompt.ts +24 -7
  44. package/cli/commandRegistry.ts +4 -5
  45. package/cli/connectorRunArtifact.ts +10 -34
  46. package/cli/connectorWebSocketTarget.ts +6 -10
  47. package/cli/internalCommandEntries.ts +0 -8
  48. package/cli/localRuntimeDb.ts +2 -39
  49. package/cli/machineCommands.ts +189 -190
  50. package/cli/machineDaemonCommands.ts +165 -9
  51. package/cli/machineHeartbeatCommands.ts +2 -1
  52. package/cli/machineStatusCommands.ts +13 -5
  53. package/cli/machineWatchCommands.ts +1 -1
  54. package/cli/machineWsRunDispatch.ts +30 -44
  55. package/cli/machineWsSession.ts +0 -2
  56. package/cli/offlineMarxistsAgentCommand.ts +314 -0
  57. package/cli/runtimeDoctorCommands.ts +72 -15
  58. package/cli/scriptCommandEntries.ts +45 -5
  59. package/cli/tableCommands.ts +133 -33
  60. package/cli/taskRunCommand.ts +211 -16
  61. package/cli/tui/session.ts +372 -43
  62. package/cli/workflowInternalCommandEntries.ts +0 -20
  63. package/cliCommandDispatch.ts +2 -2
  64. package/cliEnvHelpers.ts +34 -107
  65. package/client/agentConfigResolver.test.ts +2 -0
  66. package/client/agentRun.test.ts +12 -208
  67. package/client/agentRun.ts +854 -57
  68. package/client/localProviderResolver.test.ts +26 -2
  69. package/client/localRuntimeAdapter.test.ts +296 -171
  70. package/client/localRuntimeAdapter.ts +59 -159
  71. package/client/localToolPolicy.test.ts +4 -28
  72. package/client/streamingOutput.ts +3 -1
  73. package/client/taskRunPrompt.ts +24 -7
  74. package/commandRegistry.ts +4 -5
  75. package/connectorRunArtifact.ts +10 -34
  76. package/connectorWebSocketTarget.ts +6 -10
  77. package/database/server/serverStoreFactory.ts +2 -8
  78. package/internalCommandEntries.ts +0 -8
  79. package/localRuntimeDb.ts +2 -39
  80. package/machineCommands.ts +189 -190
  81. package/machineDaemonCommands.ts +165 -9
  82. package/machineHeartbeatCommands.ts +2 -1
  83. package/machineStatusCommands.ts +13 -5
  84. package/machineWatchCommands.ts +1 -1
  85. package/machineWsRunDispatch.ts +30 -44
  86. package/machineWsSession.ts +0 -2
  87. package/offlineMarxistsAgentCommand.ts +314 -0
  88. package/package.json +52 -188
  89. package/runtimeDoctorCommands.ts +72 -15
  90. package/scriptCommandEntries.ts +45 -5
  91. package/tableCommands.ts +133 -33
  92. package/taskRunCommand.ts +211 -16
  93. package/tui/session.ts +372 -43
  94. package/workflowInternalCommandEntries.ts +0 -20
  95. package/agent-runtime/dialogStatus.ts +0 -139
  96. package/agent-runtime/hostRuntimeConfig.ts +0 -86
  97. package/agentCreateCustomCommands.ts +0 -278
  98. package/agentDialogsCommands.ts +0 -227
  99. package/agentDoctorCommands.ts +0 -203
  100. package/agentRunLocalWorkspace.ts +0 -182
  101. package/agentRunParsing.ts +0 -298
  102. package/agentSuperviseCommands.ts +0 -8
  103. package/agentUnpublishCommands.ts +0 -113
  104. package/ai/agent/agentRunDialogLineage.ts +0 -56
  105. package/ai/policy/types.ts +0 -64
  106. package/ai/skills/skillSummaryMarker.ts +0 -26
  107. package/app/types.ts +0 -358
  108. package/build.ts +0 -16
  109. package/buildPublish.ts +0 -138
  110. package/buildPublishArtifactAssembly.ts +0 -724
  111. package/buildPublishImportAnalysis.ts +0 -242
  112. package/chat/messages/fetchMessages.ts +0 -84
  113. package/chat/messages/types.ts +0 -185
  114. package/cli/agentCreateCustomCommands.ts +0 -278
  115. package/cli/agentDialogsCommands.ts +0 -227
  116. package/cli/agentDoctorCommands.ts +0 -203
  117. package/cli/agentRunLocalWorkspace.ts +0 -182
  118. package/cli/agentRunParsing.ts +0 -298
  119. package/cli/agentSuperviseCommands.ts +0 -8
  120. package/cli/agentUnpublishCommands.ts +0 -113
  121. package/cli/buildPublish.ts +0 -138
  122. package/cli/buildPublishArtifactAssembly.ts +0 -724
  123. package/cli/buildPublishImportAnalysis.ts +0 -242
  124. package/cli/cliIoTypes.ts +0 -3
  125. package/cli/cliRuntimeDoctorReport.ts +0 -193
  126. package/cli/client/agentRunInput.ts +0 -10
  127. package/cli/client/agentRunLocalExecution.ts +0 -124
  128. package/cli/client/agentRunLocalExecutor.ts +0 -179
  129. package/cli/client/agentRunRuntimeSelection.ts +0 -145
  130. package/cli/client/agentRunServerTransport.ts +0 -397
  131. package/cli/client/agentRunTaskRunRecorder.ts +0 -176
  132. package/cli/customCodingAgentFlow.ts +0 -208
  133. package/cli/customCodingAgentRecord.ts +0 -179
  134. package/cli/dialogDataAccess.ts +0 -186
  135. package/cli/dialogInternalCommandEntries.ts +0 -11
  136. package/cli/dialogReadCommands.ts +0 -180
  137. package/cli/dialogReadHelpers.ts +0 -226
  138. package/cli/dialogStatusCommands.ts +0 -123
  139. package/cli/docInternalCommandEntries.ts +0 -20
  140. package/cli/hybridReadHelpers.ts +0 -109
  141. package/cli/machineCommandPrompts.ts +0 -79
  142. package/cli/machineCommandResolution.ts +0 -43
  143. package/cli/noloReadBridgePrompt.ts +0 -16
  144. package/cli/pageCreateCommands.ts +0 -219
  145. package/cli/pageDeleteCommands.ts +0 -167
  146. package/cli/pageReadCommands.ts +0 -151
  147. package/cli/pageUpdateCommands.ts +0 -249
  148. package/cli/pageWriteHelpers.ts +0 -209
  149. package/cli/publishPackage.ts +0 -36
  150. package/cli/runtimeInternalCommandEntries.ts +0 -15
  151. package/cli/runtimePassthroughCommands.ts +0 -22
  152. package/cli/scriptPassthroughHelpers.ts +0 -28
  153. package/cli/secretScanHelpers.ts +0 -31
  154. package/cli/spaceAttachCommands.ts +0 -134
  155. package/cli/spaceCategoryCommands.ts +0 -263
  156. package/cli/spaceCommands.ts +0 -295
  157. package/cli/spaceDeleteCommands.ts +0 -312
  158. package/cli/spaceInternalCommandEntries.ts +0 -21
  159. package/cli/spaceMutationHelpers.ts +0 -135
  160. package/cli/spaceReadCommands.ts +0 -323
  161. package/cli/tableDataOutput.ts +0 -41
  162. package/cli/tableDataSafety.ts +0 -26
  163. package/cli/tableMetaCommands.ts +0 -307
  164. package/cli/tableMutationCommands.ts +0 -266
  165. package/cli/tableQueryParsing.ts +0 -90
  166. package/cli/tableQueryRequest.ts +0 -53
  167. package/cli/taskRunActions.ts +0 -122
  168. package/cli/taskRunParsing.ts +0 -86
  169. package/cli/taskRunPromptShared.ts +0 -55
  170. package/cli/tui/tuiCatalog.ts +0 -22
  171. package/cli/tui/tuiCommandInterpreter.ts +0 -253
  172. package/cli/tui/tuiPresentation.ts +0 -146
  173. package/cliIoTypes.ts +0 -3
  174. package/cliRuntimeDoctorReport.ts +0 -193
  175. package/client/agentRunInput.ts +0 -10
  176. package/client/agentRunLocalExecution.test.ts +0 -123
  177. package/client/agentRunLocalExecution.ts +0 -124
  178. package/client/agentRunLocalExecutor.ts +0 -179
  179. package/client/agentRunRuntimeSelection.test.ts +0 -159
  180. package/client/agentRunRuntimeSelection.ts +0 -145
  181. package/client/agentRunServerTransport.ts +0 -397
  182. package/client/agentRunTaskRunRecorder.ts +0 -176
  183. package/connector-experimental/daemonLauncher.ts +0 -223
  184. package/create/space/spaceKeys.ts +0 -65
  185. package/create/types.ts +0 -21
  186. package/customCodingAgentFlow.ts +0 -208
  187. package/customCodingAgentRecord.ts +0 -179
  188. package/database/keys.ts +0 -765
  189. package/database/tombstones.ts +0 -52
  190. package/database/utils/ulid.ts +0 -1
  191. package/dialogDataAccess.ts +0 -186
  192. package/dialogInternalCommandEntries.ts +0 -11
  193. package/dialogReadCommands.ts +0 -180
  194. package/dialogReadHelpers.ts +0 -226
  195. package/dialogStatusCommands.ts +0 -123
  196. package/docInternalCommandEntries.ts +0 -20
  197. package/hybridReadHelpers.ts +0 -109
  198. package/machineCommandPrompts.ts +0 -79
  199. package/machineCommandResolution.ts +0 -43
  200. package/noloReadBridgePrompt.ts +0 -16
  201. package/pageCreateCommands.ts +0 -219
  202. package/pageDeleteCommands.ts +0 -167
  203. package/pageReadCommands.ts +0 -151
  204. package/pageUpdateCommands.ts +0 -249
  205. package/pageWriteHelpers.ts +0 -209
  206. package/publishPackage.ts +0 -36
  207. package/runtimeInternalCommandEntries.ts +0 -15
  208. package/runtimePassthroughCommands.ts +0 -22
  209. package/scriptPassthroughHelpers.ts +0 -28
  210. package/secretScanHelpers.ts +0 -31
  211. package/share/helpers.ts +0 -302
  212. package/share/keys.ts +0 -243
  213. package/share/types.ts +0 -100
  214. package/spaceAttachCommands.ts +0 -134
  215. package/spaceCategoryCommands.ts +0 -263
  216. package/spaceCommands.ts +0 -295
  217. package/spaceDeleteCommands.ts +0 -312
  218. package/spaceInternalCommandEntries.ts +0 -21
  219. package/spaceMutationHelpers.ts +0 -135
  220. package/spaceReadCommands.ts +0 -323
  221. package/tableDataOutput.ts +0 -41
  222. package/tableDataSafety.ts +0 -26
  223. package/tableMetaCommands.ts +0 -307
  224. package/tableMutationCommands.ts +0 -266
  225. package/tableQueryParsing.ts +0 -90
  226. package/tableQueryRequest.ts +0 -53
  227. package/taskRunActions.ts +0 -122
  228. package/taskRunParsing.ts +0 -86
  229. package/taskRunPromptShared.ts +0 -55
  230. package/tui/tuiCatalog.ts +0 -22
  231. package/tui/tuiCommandInterpreter.test.ts +0 -169
  232. package/tui/tuiCommandInterpreter.ts +0 -253
  233. package/tui/tuiPresentation.test.ts +0 -154
  234. package/tui/tuiPresentation.ts +0 -146
@@ -1,242 +0,0 @@
1
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
- import { dirname, join, relative } from "node:path";
3
-
4
- function extractPackageNameFromImportPath(importPath: string): string {
5
- if (importPath.startsWith("@")) {
6
- const parts = importPath.split("/");
7
- return parts.slice(0, 2).join("/");
8
- }
9
-
10
- const firstSlash = importPath.indexOf("/");
11
- return firstSlash === -1 ? importPath : importPath.slice(0, firstSlash);
12
- }
13
-
14
- function extractModuleSpecifiers(content: string): string[] {
15
- const specifiers = new Set<string>();
16
- const importOrExportRegex =
17
- /(?:import|export)\s+(?:(?:type\s+)?(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s+from\s+)?['"]([^'"]+)['"]/g;
18
- const dynamicImportRegex = /import\(\s*['"]([^'"]+)['"]\s*\)/g;
19
-
20
- let match: RegExpExecArray | null;
21
- while ((match = importOrExportRegex.exec(content)) !== null) {
22
- specifiers.add(match[1]);
23
- }
24
-
25
- while ((match = dynamicImportRegex.exec(content)) !== null) {
26
- specifiers.add(match[1]);
27
- }
28
-
29
- return Array.from(specifiers);
30
- }
31
-
32
- export function extractExternalImports(content: string): string[] {
33
- const imports = new Set<string>();
34
- for (const importPath of extractModuleSpecifiers(content)) {
35
- if (
36
- importPath.startsWith(".") ||
37
- importPath.startsWith("node:") ||
38
- importPath.startsWith("/")
39
- ) {
40
- continue;
41
- }
42
- imports.add(extractPackageNameFromImportPath(importPath));
43
- }
44
- return Array.from(imports);
45
- }
46
-
47
- export function extractLocalRelativeImports(content: string): string[] {
48
- return extractModuleSpecifiers(content).filter(
49
- (importPath) => importPath.startsWith(".") && !importPath.startsWith("/")
50
- );
51
- }
52
-
53
- export function extractWorkspaceDependencies(
54
- manifest: Record<string, any>
55
- ): string[] {
56
- const deps: string[] = [];
57
- for (const field of ["dependencies", "devDependencies", "peerDependencies"]) {
58
- if (!manifest[field]) {
59
- continue;
60
- }
61
- for (const [name, version] of Object.entries(manifest[field])) {
62
- if (typeof version === "string" && version.startsWith("workspace:")) {
63
- deps.push(name);
64
- }
65
- }
66
- }
67
- return deps;
68
- }
69
-
70
- export function findSiblingWorkspacePackageNames(sourceDir: string): string[] {
71
- const packagesDir = join(sourceDir, "..");
72
- const names: string[] = [];
73
-
74
- for (const entry of readdirSync(packagesDir)) {
75
- const pkgPath = join(packagesDir, entry, "package.json");
76
- if (!existsSync(pkgPath)) {
77
- continue;
78
- }
79
- try {
80
- const manifest = JSON.parse(readFileSync(pkgPath, "utf8"));
81
- if (typeof manifest.name === "string" && manifest.name.length > 0) {
82
- names.push(manifest.name);
83
- }
84
- } catch {
85
- // Ignore malformed sibling manifests while scanning workspace package names.
86
- }
87
- }
88
-
89
- return names;
90
- }
91
-
92
- export function extractWorkspaceImports(
93
- content: string,
94
- workspacePackageNames: Set<string>
95
- ): string[] {
96
- const imports = new Set<string>();
97
-
98
- for (const packageName of extractExternalImports(content)) {
99
- if (workspacePackageNames.has(packageName)) {
100
- imports.add(packageName);
101
- }
102
- }
103
-
104
- const relativeWorkspaceImportRegex =
105
- /(?:from\s+['"]\.\.\/([^./'"][^/'"]*)(?:\/[^'"]*)?['"]|import\(\s*['"]\.\.\/([^./'"][^/'"]*)(?:\/[^'"]*)?['"]\s*\))/g;
106
-
107
- let match: RegExpExecArray | null;
108
- while ((match = relativeWorkspaceImportRegex.exec(content)) !== null) {
109
- const packageName = match[1] || match[2];
110
- if (packageName && workspacePackageNames.has(packageName)) {
111
- imports.add(packageName);
112
- }
113
- }
114
-
115
- return Array.from(imports);
116
- }
117
-
118
- export function collectWorkspaceDependencies(
119
- sourceDir: string,
120
- manifest: Record<string, any>,
121
- filesToCopy: string[]
122
- ): string[] {
123
- const workspaceDeps = new Set(extractWorkspaceDependencies(manifest));
124
- const workspacePackageNames = new Set(findSiblingWorkspacePackageNames(sourceDir));
125
-
126
- for (const filePath of collectTypeScriptSourceFiles(sourceDir, filesToCopy)) {
127
- const content = readFileSync(filePath, "utf8");
128
- for (const dep of extractWorkspaceImports(content, workspacePackageNames)) {
129
- workspaceDeps.add(dep);
130
- }
131
- }
132
-
133
- return Array.from(workspaceDeps);
134
- }
135
-
136
- export function findTypeScriptFiles(dir: string): string[] {
137
- const files: string[] = [];
138
-
139
- for (const entry of readdirSync(dir)) {
140
- const fullPath = join(dir, entry);
141
- const stat = statSync(fullPath);
142
- if (stat.isDirectory()) {
143
- files.push(...findTypeScriptFiles(fullPath));
144
- continue;
145
- }
146
- if (stat.isFile() && fullPath.endsWith(".ts")) {
147
- files.push(fullPath);
148
- }
149
- }
150
-
151
- return files;
152
- }
153
-
154
- export function collectTypeScriptSourceFiles(
155
- sourceDir: string,
156
- filesToCopy: string[]
157
- ): string[] {
158
- const files: string[] = [];
159
-
160
- for (const entry of filesToCopy) {
161
- const sourcePath = join(sourceDir, entry);
162
- if (!existsSync(sourcePath)) {
163
- continue;
164
- }
165
- const stat = statSync(sourcePath);
166
- if (stat.isDirectory()) {
167
- files.push(...findTypeScriptFiles(sourcePath));
168
- continue;
169
- }
170
- if (stat.isFile() && sourcePath.endsWith(".ts")) {
171
- files.push(sourcePath);
172
- }
173
- }
174
-
175
- return files;
176
- }
177
-
178
- function escapeRegex(text: string): string {
179
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
180
- }
181
-
182
- function createWorkspaceSpecifier(relativeFilePath: string, packageName: string, path = ""): string {
183
- const fileDir = dirname(relativeFilePath);
184
- const relativePackagePath = relative(fileDir === "." ? "" : fileDir, packageName).replace(
185
- /\\/g,
186
- "/"
187
- );
188
- const prefix = relativePackagePath.startsWith(".")
189
- ? relativePackagePath
190
- : `./${relativePackagePath}`;
191
- return `${prefix}${path}`;
192
- }
193
-
194
- export function rewriteCrossPackageImports(
195
- content: string,
196
- workspaceDeps: string[],
197
- relativeFilePath = ""
198
- ): string {
199
- if (workspaceDeps.length === 0) {
200
- return content;
201
- }
202
-
203
- const patterns = workspaceDeps.map(escapeRegex);
204
- const relativeDepth =
205
- dirname(relativeFilePath) === "."
206
- ? 1
207
- : dirname(relativeFilePath).split(/[\\/]/).filter(Boolean).length + 1;
208
- const crossPackagePrefixPattern = `(?:\\.\\./){${relativeDepth}}`;
209
-
210
- const relativeImportRegex = new RegExp(
211
- `(from\\s+['"])${crossPackagePrefixPattern}((?!\\.)${patterns.join("|")})(/[^'"]*)?(['"])`,
212
- "g"
213
- );
214
- const bareImportRegex = new RegExp(
215
- `(from\\s+['"])(${patterns.join("|")})(/[^'"]*)?(['"])`,
216
- "g"
217
- );
218
- const dynamicRelativeImportRegex = new RegExp(
219
- `(import\\(\\s*['"])${crossPackagePrefixPattern}((?!\\.)${patterns.join("|")})(/[^'"]*)?(['"]\\s*\\))`,
220
- "g"
221
- );
222
- const dynamicBareImportRegex = new RegExp(
223
- `(import\\(\\s*['"])(${patterns.join("|")})(/[^'"]*)?(['"]\\s*\\))`,
224
- "g"
225
- );
226
-
227
- let result = content;
228
- result = result.replace(relativeImportRegex, (_, prefix, packageName, path, suffix) => {
229
- return `${prefix}${createWorkspaceSpecifier(relativeFilePath, packageName, path)}${suffix}`;
230
- });
231
- result = result.replace(bareImportRegex, (_, prefix, packageName, path, suffix) => {
232
- return `${prefix}${createWorkspaceSpecifier(relativeFilePath, packageName, path)}${suffix}`;
233
- });
234
- result = result.replace(dynamicRelativeImportRegex, (_, prefix, packageName, path, suffix) => {
235
- return `${prefix}${createWorkspaceSpecifier(relativeFilePath, packageName, path)}${suffix}`;
236
- });
237
- result = result.replace(dynamicBareImportRegex, (_, prefix, packageName, path, suffix) => {
238
- return `${prefix}${createWorkspaceSpecifier(relativeFilePath, packageName, path)}${suffix}`;
239
- });
240
-
241
- return result;
242
- }
@@ -1,84 +0,0 @@
1
- // chat/messages/fetchMessages.ts
2
- import type { Message } from "./types"; // 确保引入你的 Message 类型定义
3
- import { isTombstoneRecord } from "../../database/tombstones";
4
-
5
- // 定义返回类型,包含数据库的 key
6
- export type MessageWithKey = Message & { _key: string };
7
-
8
- /**
9
- * 获取指定对话的消息,支持分页加载。
10
- * @param db 数据库实例。
11
- * @param dialogId 对话 ID。
12
- * @param options 配置选项 (limit?, beforeKey?, throwOnError?)。
13
- * @returns Promise<MessageWithKey[]> 消息数组 (带 key, 默认最新在前)。
14
- */
15
- export const fetchMessages = async (
16
- db: any, // TODO: 替换为具体的数据库实例类型
17
- dialogId: string,
18
- options: {
19
- limit?: number;
20
- beforeKey?: string | null;
21
- throwOnError?: boolean;
22
- includeDeleted?: boolean;
23
- } = {}
24
- ): Promise<MessageWithKey[]> => {
25
- const { limit = 30, beforeKey = null, throwOnError = false, includeDeleted = false } = options; // 分页默认 limit 30
26
-
27
- // --- 输入验证 ---
28
- if (!dialogId || typeof dialogId !== "string") {
29
- const errorMsg = "fetchMessages: dialogId 必须是一个非空字符串";
30
- if (throwOnError) throw new Error(errorMsg);
31
- console.error(errorMsg);
32
- return [];
33
- }
34
- // 其他验证 (limit, beforeKey) 可以根据需要添加
35
-
36
- // --- 准备查询 ---
37
- const messages: MessageWithKey[] = [];
38
- const prefix = `dialog-${dialogId}-msg-`;
39
-
40
- const iteratorOptions: any = {
41
- // TODO: 替换为具体的迭代器选项类型
42
- gte: prefix,
43
- reverse: true, // 总是从新到旧获取
44
- limit: limit,
45
- };
46
-
47
- if (beforeKey) {
48
- // 加载更早的消息: Key < beforeKey
49
- iteratorOptions.lt = beforeKey;
50
- } else {
51
- // 加载最新的消息: Key <= prefix + '\uffff'
52
- iteratorOptions.lte = prefix + "\uffff";
53
- }
54
-
55
- // --- 执行查询 ---
56
- try {
57
- let iterator = db.iterator(iteratorOptions);
58
- // 处理 react-native-leveldb 可能返回 Promise 的情况
59
- if (iterator && typeof iterator.then === 'function') {
60
- iterator = await iterator;
61
- }
62
-
63
-
64
- let count = 0;
65
- for await (const [key, value] of iterator) {
66
- count++;
67
- if (!includeDeleted && isTombstoneRecord(value)) {
68
- continue;
69
- }
70
- // 基本数据校验
71
- if (value && typeof value === "object" && value.id && value.createdAt) {
72
- // **关键: 将数据库 key 作为 _key 附加到消息对象上**
73
- messages.push({ ...(value as Message), _key: key });
74
- }
75
- }
76
-
77
-
78
- return messages; // 返回的消息数组是 newest first
79
- } catch (error) {
80
- console.error(`fetchMessages: 获取对话 ${dialogId} 消息失败:`, error);
81
- if (throwOnError) throw error;
82
- return [];
83
- }
84
- };
@@ -1,185 +0,0 @@
1
- // 文件路径: chat/messages/types.ts
2
-
3
- // ========== 角色 ==========
4
- export type MessageRole = "user" | "system" | "assistant" | "tool";
5
-
6
- // ========== OpenAI 风格的 content ==========
7
- export type OpenAIImageUrl =
8
- | `http${string}`
9
- | `https${string}`
10
- | `data:image/${string};base64,${string}`;
11
-
12
- export interface OpenAIImageContent {
13
- type: "image_url";
14
- image_url: {
15
- url: OpenAIImageUrl;
16
- detail?: "low" | "high" | "auto";
17
- };
18
- google_native?: {
19
- inlineData: {
20
- mimeType: string;
21
- data: string;
22
- };
23
- thoughtSignature?: string;
24
- };
25
- }
26
-
27
- export interface OpenAITextContent {
28
- type: "text";
29
- text: string;
30
- }
31
-
32
- export type MessageContentPart = OpenAITextContent | OpenAIImageContent;
33
-
34
- export type CompletionFinishReason = "stop" | "tool_calls" | "length" | "content_filter" | null;
35
-
36
- // ========== Token Usage ==========
37
- export interface CompletionUsage {
38
- completion_tokens: number;
39
- prompt_tokens: number;
40
- total_tokens: number;
41
- cost?: number; // OpenRouter extension
42
- prompt_tokens_details?: Record<string, any>;
43
- completion_tokens_details?: Record<string, any>;
44
- cost_details?: Record<string, any>;
45
- }
46
-
47
- export type Content = string | MessageContentPart[];
48
-
49
- export interface ImageGenerationState {
50
- kind: "image_generation";
51
- stage: "submitted" | "generating" | "saving";
52
- startedAt: number;
53
- waitHint?: string;
54
- profileLabel?: string;
55
- }
56
-
57
- // ========== 消息级 UI 选项(Agent 菜单 / 快速回复 等) ==========
58
-
59
- export type UiOptionSource = "agent_menu" | "llm" | "system" | "tool";
60
-
61
- export interface UiOptionMeta {
62
- /** 选项来源:Agent 配置 / LLM 建议 / 系统内置 / Tool 生成 */
63
- source?: UiOptionSource;
64
- /** 可选描述:用于 tooltip 或 hover 展示的详细说明 */
65
- description?: string;
66
- }
67
-
68
- /**
69
- * 一条消息下方的可点击选项(Agent 菜单 / quick reply / Tool 提示等)
70
- * - 显示给用户的是 label
71
- * - 发给 LLM 的是 userMessage(如果不写则使用 label)
72
- */
73
- export interface UiOption {
74
- /** 选项自身的稳定 ID(和 message.id 不同) */
75
- id: string;
76
- /** 按钮上的文案(用户可见) */
77
- label: string;
78
- /** 点击后要发给 LLM 的“等价人话”,不填则默认用 label */
79
- userMessage?: string;
80
- /** 附加元信息(目前轻量使用,后续可以扩展) */
81
- meta?: UiOptionMeta;
82
- }
83
-
84
- // ========== Tool 调用快照 ==========
85
-
86
- export interface ToolErrorPayload {
87
- type: string;
88
- message: string;
89
- code?: string;
90
- retryable?: boolean;
91
- }
92
-
93
- export interface ToolPayload {
94
- toolName: string;
95
- status: "pending" | "running" | "succeeded" | "failed";
96
- input: any;
97
- rawToolCall?: any;
98
-
99
- /**
100
- * ✅ 工具输出不在 toolPayload 存储(唯一输出来源是 message.content)
101
- * rawResult 不再写入;这里不保留兼容字段,按你的要求直接干掉。
102
- */
103
-
104
- error?: ToolErrorPayload;
105
- toolRunId?: string;
106
- startedAt?: number;
107
- finishedAt?: number;
108
-
109
- /**
110
- * ✅ 持久化摘要:用于 ToolMessageItem header 展示
111
- * 没有的话 UI 会 fallback 默认文案
112
- */
113
- summary?: string;
114
-
115
- /**
116
- * 提供给下一轮 LLM 的结构化上下文补充。
117
- * 典型场景:工具真实产物(如 fileId / 可复用 URL)不能只靠 summary 传达。
118
- * UI 不直接展示它,避免把 header 摘要污染成长文本。
119
- */
120
- llmContext?: string;
121
-
122
- /**
123
- * callAgent 子任务完成后产生的独立 dialog ID
124
- * 供 UI 渲染「查看完整对话 →」跳转链接
125
- */
126
- subDialogId?: string;
127
-
128
- /**
129
- * 可选(未来建议):toolVersion / executorVersion,用于严格复现
130
- * toolVersion?: string;
131
- */
132
- }
133
-
134
- // ========== Message 主类型 ==========
135
-
136
- export interface Message {
137
- role: MessageRole;
138
- content: Content;
139
-
140
- thinkContent?: string;
141
- image?: string;
142
- images?: string[];
143
-
144
- id: string;
145
- dbKey: string;
146
-
147
- cybotId?: string;
148
- cybotKey?: string;
149
- agentKey?: string;
150
- agentName?: string;
151
-
152
- isStreaming?: boolean;
153
- imageGenerationState?: ImageGenerationState;
154
- userId?: string;
155
- usage?: any;
156
-
157
- controller?: AbortController;
158
-
159
- // ========= Tool 扩展字段 =========
160
-
161
- toolName?: string;
162
- toolPayload?: ToolPayload;
163
- parentMessageId?: string;
164
- toolRunId?: string;
165
- parallelSessionId?: string;
166
- parallelBranchId?: string;
167
- parallelLabel?: string;
168
- parallelIndex?: number;
169
-
170
- // tool_call_id:关联 assistant message 的 tool_calls[].id
171
- toolCallId?: string;
172
-
173
- // assistant message 的 tool_calls(OpenAI 标准字段名)
174
- tool_calls?: Array<{
175
- id: string;
176
- type: "function";
177
- function: {
178
- name: string;
179
- arguments: string;
180
- };
181
- }>;
182
-
183
- // ========= 消息级 UI 选项(Agent 菜单 / quick reply) =========
184
- options?: UiOption[];
185
- }