nolo-cli 0.1.32 → 0.1.33

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 (230) hide show
  1. package/README.md +0 -6
  2. package/agent-runtime/agentRecordConfig.ts +2 -0
  3. package/agent-runtime/hostAdapter.ts +1 -0
  4. package/agent-runtime/index.ts +0 -21
  5. package/agent-runtime/localToolPolicy.ts +6 -13
  6. package/agent-runtime/localWorkspaceTools.ts +30 -333
  7. package/agent-runtime/platformChatProvider.ts +1 -4
  8. package/agent-runtime/runtimeToolPolicy.ts +47 -32
  9. package/agentAliases.ts +14 -83
  10. package/agentCommandSupport.ts +3 -6
  11. package/agentInternalCommandEntries.ts +2 -13
  12. package/agentListCommands.ts +19 -28
  13. package/agentMachineCommands.ts +40 -336
  14. package/agentPullCommand.ts +36 -56
  15. package/agentRecordCommands.ts +3 -5
  16. package/agentRecordHelpers.ts +22 -189
  17. package/agentRunCommand.ts +438 -107
  18. package/agentRuntimeLocal.ts +0 -10
  19. package/ai/agent/cliExecutor.ts +19 -323
  20. package/authCommands.ts +2 -36
  21. package/cli/agentAliases.ts +14 -83
  22. package/cli/agentCommandSupport.ts +3 -6
  23. package/cli/agentInternalCommandEntries.ts +2 -13
  24. package/cli/agentListCommands.ts +19 -28
  25. package/cli/agentMachineCommands.ts +40 -336
  26. package/cli/agentPullCommand.ts +36 -56
  27. package/cli/agentRecordCommands.ts +3 -5
  28. package/cli/agentRecordHelpers.ts +22 -189
  29. package/cli/agentRunCommand.ts +438 -107
  30. package/cli/agentRuntimeLocal.ts +0 -10
  31. package/cli/authCommands.ts +2 -36
  32. package/cli/cliEnvHelpers.ts +21 -162
  33. package/cli/client/agentRun.ts +853 -57
  34. package/cli/client/localRuntimeAdapter.ts +22 -159
  35. package/cli/client/streamingOutput.ts +3 -1
  36. package/cli/client/taskRunPrompt.ts +24 -7
  37. package/cli/commandRegistry.ts +2 -3
  38. package/cli/connectorRunArtifact.ts +10 -34
  39. package/cli/connectorWebSocketTarget.ts +6 -10
  40. package/cli/internalCommandEntries.ts +0 -8
  41. package/cli/localRuntimeDb.ts +2 -39
  42. package/cli/machineCommands.ts +189 -190
  43. package/cli/machineDaemonCommands.ts +165 -9
  44. package/cli/machineHeartbeatCommands.ts +2 -1
  45. package/cli/machineStatusCommands.ts +13 -5
  46. package/cli/machineWatchCommands.ts +1 -1
  47. package/cli/machineWsRunDispatch.ts +14 -48
  48. package/cli/machineWsSession.ts +0 -2
  49. package/cli/offlineMarxistsAgentCommand.ts +314 -0
  50. package/cli/runtimeDoctorCommands.ts +69 -18
  51. package/cli/scriptCommandEntries.ts +45 -5
  52. package/cli/tableCommands.ts +133 -33
  53. package/cli/taskRunCommand.ts +211 -16
  54. package/cli/tui/session.ts +372 -43
  55. package/cli/workflowInternalCommandEntries.ts +0 -20
  56. package/cliEnvHelpers.ts +21 -162
  57. package/client/agentConfigResolver.test.ts +2 -0
  58. package/client/agentRun.test.ts +12 -208
  59. package/client/agentRun.ts +853 -57
  60. package/client/localRuntimeAdapter.test.ts +9 -168
  61. package/client/localRuntimeAdapter.ts +22 -159
  62. package/client/localToolPolicy.test.ts +4 -28
  63. package/client/streamingOutput.ts +3 -1
  64. package/client/taskRunPrompt.ts +24 -7
  65. package/commandRegistry.ts +2 -3
  66. package/connectorRunArtifact.ts +10 -34
  67. package/connectorWebSocketTarget.ts +6 -10
  68. package/database/server/db.ts +34 -15
  69. package/internalCommandEntries.ts +0 -8
  70. package/localRuntimeDb.ts +2 -39
  71. package/machineCommands.ts +189 -190
  72. package/machineDaemonCommands.ts +165 -9
  73. package/machineHeartbeatCommands.ts +2 -1
  74. package/machineStatusCommands.ts +13 -5
  75. package/machineWatchCommands.ts +1 -1
  76. package/machineWsRunDispatch.ts +14 -48
  77. package/machineWsSession.ts +0 -2
  78. package/offlineMarxistsAgentCommand.ts +314 -0
  79. package/package.json +49 -193
  80. package/runtimeDoctorCommands.ts +69 -18
  81. package/scriptCommandEntries.ts +45 -5
  82. package/tableCommands.ts +133 -33
  83. package/taskRunCommand.ts +211 -16
  84. package/tui/session.ts +372 -43
  85. package/workflowInternalCommandEntries.ts +0 -20
  86. package/agent-runtime/dialogStatus.ts +0 -139
  87. package/agent-runtime/hostRuntimeConfig.ts +0 -86
  88. package/agentCreateCustomCommands.ts +0 -278
  89. package/agentDialogsCommands.ts +0 -227
  90. package/agentDoctorCommands.ts +0 -203
  91. package/agentRunLocalWorkspace.ts +0 -182
  92. package/agentRunParsing.ts +0 -298
  93. package/agentSuperviseCommands.ts +0 -8
  94. package/agentUnpublishCommands.ts +0 -113
  95. package/ai/agent/agentRunDialogLineage.ts +0 -56
  96. package/ai/policy/types.ts +0 -64
  97. package/ai/skills/skillSummaryMarker.ts +0 -26
  98. package/app/types.ts +0 -358
  99. package/build.ts +0 -16
  100. package/buildPublish.ts +0 -138
  101. package/buildPublishArtifactAssembly.ts +0 -724
  102. package/buildPublishImportAnalysis.ts +0 -242
  103. package/chat/messages/fetchMessages.ts +0 -84
  104. package/chat/messages/types.ts +0 -185
  105. package/cli/agentCreateCustomCommands.ts +0 -278
  106. package/cli/agentDialogsCommands.ts +0 -227
  107. package/cli/agentDoctorCommands.ts +0 -203
  108. package/cli/agentRunLocalWorkspace.ts +0 -182
  109. package/cli/agentRunParsing.ts +0 -298
  110. package/cli/agentSuperviseCommands.ts +0 -8
  111. package/cli/agentUnpublishCommands.ts +0 -113
  112. package/cli/buildPublish.ts +0 -138
  113. package/cli/buildPublishArtifactAssembly.ts +0 -724
  114. package/cli/buildPublishImportAnalysis.ts +0 -242
  115. package/cli/cliIoTypes.ts +0 -3
  116. package/cli/cliRuntimeDoctorReport.ts +0 -193
  117. package/cli/client/agentRunInput.ts +0 -10
  118. package/cli/client/agentRunLocalExecution.ts +0 -124
  119. package/cli/client/agentRunLocalExecutor.ts +0 -179
  120. package/cli/client/agentRunRuntimeSelection.ts +0 -145
  121. package/cli/client/agentRunServerTransport.ts +0 -397
  122. package/cli/client/agentRunTaskRunRecorder.ts +0 -176
  123. package/cli/customCodingAgentFlow.ts +0 -208
  124. package/cli/customCodingAgentRecord.ts +0 -179
  125. package/cli/dialogDataAccess.ts +0 -186
  126. package/cli/dialogInternalCommandEntries.ts +0 -11
  127. package/cli/dialogReadCommands.ts +0 -180
  128. package/cli/dialogReadHelpers.ts +0 -226
  129. package/cli/dialogStatusCommands.ts +0 -123
  130. package/cli/docInternalCommandEntries.ts +0 -20
  131. package/cli/hybridReadHelpers.ts +0 -109
  132. package/cli/machineCommandPrompts.ts +0 -79
  133. package/cli/machineCommandResolution.ts +0 -43
  134. package/cli/noloReadBridgePrompt.ts +0 -16
  135. package/cli/pageCreateCommands.ts +0 -219
  136. package/cli/pageDeleteCommands.ts +0 -167
  137. package/cli/pageReadCommands.ts +0 -151
  138. package/cli/pageUpdateCommands.ts +0 -249
  139. package/cli/pageWriteHelpers.ts +0 -209
  140. package/cli/publishPackage.ts +0 -36
  141. package/cli/runtimeInternalCommandEntries.ts +0 -15
  142. package/cli/runtimePassthroughCommands.ts +0 -22
  143. package/cli/scriptPassthroughHelpers.ts +0 -28
  144. package/cli/secretScanHelpers.ts +0 -31
  145. package/cli/spaceAttachCommands.ts +0 -134
  146. package/cli/spaceCategoryCommands.ts +0 -263
  147. package/cli/spaceCommands.ts +0 -295
  148. package/cli/spaceDeleteCommands.ts +0 -312
  149. package/cli/spaceInternalCommandEntries.ts +0 -21
  150. package/cli/spaceMutationHelpers.ts +0 -135
  151. package/cli/spaceReadCommands.ts +0 -323
  152. package/cli/tableDataOutput.ts +0 -41
  153. package/cli/tableDataSafety.ts +0 -26
  154. package/cli/tableMetaCommands.ts +0 -307
  155. package/cli/tableMutationCommands.ts +0 -266
  156. package/cli/tableQueryParsing.ts +0 -90
  157. package/cli/tableQueryRequest.ts +0 -53
  158. package/cli/taskRunActions.ts +0 -122
  159. package/cli/taskRunParsing.ts +0 -86
  160. package/cli/taskRunPromptShared.ts +0 -55
  161. package/cli/tui/tuiCatalog.ts +0 -22
  162. package/cli/tui/tuiCommandInterpreter.ts +0 -253
  163. package/cli/tui/tuiPresentation.ts +0 -146
  164. package/cliIoTypes.ts +0 -3
  165. package/cliRuntimeDoctorReport.ts +0 -193
  166. package/client/agentRunInput.ts +0 -10
  167. package/client/agentRunLocalExecution.test.ts +0 -123
  168. package/client/agentRunLocalExecution.ts +0 -124
  169. package/client/agentRunLocalExecutor.ts +0 -179
  170. package/client/agentRunRuntimeSelection.test.ts +0 -159
  171. package/client/agentRunRuntimeSelection.ts +0 -145
  172. package/client/agentRunServerTransport.ts +0 -397
  173. package/client/agentRunTaskRunRecorder.ts +0 -176
  174. package/connector-experimental/daemonLauncher.ts +0 -223
  175. package/create/space/spaceKeys.ts +0 -65
  176. package/create/types.ts +0 -21
  177. package/customCodingAgentFlow.ts +0 -208
  178. package/customCodingAgentRecord.ts +0 -179
  179. package/database/keys.ts +0 -765
  180. package/database/server/authorityStoreTypes.ts +0 -31
  181. package/database/server/legacyServerDb.ts +0 -58
  182. package/database/server/levelAuthorityStore.ts +0 -75
  183. package/database/server/memoryAuthorityStore.ts +0 -133
  184. package/database/server/serverStoreFactory.ts +0 -124
  185. package/database/tombstones.ts +0 -52
  186. package/database/utils/ulid.ts +0 -1
  187. package/dialogDataAccess.ts +0 -186
  188. package/dialogInternalCommandEntries.ts +0 -11
  189. package/dialogReadCommands.ts +0 -180
  190. package/dialogReadHelpers.ts +0 -226
  191. package/dialogStatusCommands.ts +0 -123
  192. package/docInternalCommandEntries.ts +0 -20
  193. package/hybridReadHelpers.ts +0 -109
  194. package/machineCommandPrompts.ts +0 -79
  195. package/machineCommandResolution.ts +0 -43
  196. package/noloReadBridgePrompt.ts +0 -16
  197. package/pageCreateCommands.ts +0 -219
  198. package/pageDeleteCommands.ts +0 -167
  199. package/pageReadCommands.ts +0 -151
  200. package/pageUpdateCommands.ts +0 -249
  201. package/pageWriteHelpers.ts +0 -209
  202. package/publishPackage.ts +0 -36
  203. package/runtimeInternalCommandEntries.ts +0 -15
  204. package/runtimePassthroughCommands.ts +0 -22
  205. package/scriptPassthroughHelpers.ts +0 -28
  206. package/secretScanHelpers.ts +0 -31
  207. package/share/helpers.ts +0 -302
  208. package/share/keys.ts +0 -243
  209. package/share/types.ts +0 -100
  210. package/spaceAttachCommands.ts +0 -134
  211. package/spaceCategoryCommands.ts +0 -263
  212. package/spaceCommands.ts +0 -295
  213. package/spaceDeleteCommands.ts +0 -312
  214. package/spaceInternalCommandEntries.ts +0 -21
  215. package/spaceMutationHelpers.ts +0 -135
  216. package/spaceReadCommands.ts +0 -323
  217. package/tableDataOutput.ts +0 -41
  218. package/tableDataSafety.ts +0 -26
  219. package/tableMetaCommands.ts +0 -307
  220. package/tableMutationCommands.ts +0 -266
  221. package/tableQueryParsing.ts +0 -90
  222. package/tableQueryRequest.ts +0 -53
  223. package/taskRunActions.ts +0 -122
  224. package/taskRunParsing.ts +0 -86
  225. package/taskRunPromptShared.ts +0 -55
  226. package/tui/tuiCatalog.ts +0 -22
  227. package/tui/tuiCommandInterpreter.test.ts +0 -169
  228. package/tui/tuiCommandInterpreter.ts +0 -253
  229. package/tui/tuiPresentation.test.ts +0 -154
  230. 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
- }