nolo-cli 0.1.38 → 0.1.40
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.
- package/README.md +4 -4
- package/agent-runtime/agentRecordConfig.ts +0 -14
- package/agent-runtime/dialogWritePlan.ts +39 -0
- package/agent-runtime/hostAdapter.ts +4 -1
- package/agent-runtime/hybridRecordStore.ts +1 -1
- package/agent-runtime/index.ts +39 -18
- package/agent-runtime/localDialogRead.ts +23 -0
- package/agent-runtime/localLoop.ts +87 -7
- package/agent-runtime/localToolPolicy.ts +1 -17
- package/agent-runtime/localWorkspaceTools.ts +51 -110
- package/agent-runtime/noloWorkspaceTools.ts +371 -0
- package/agent-runtime/runtimeToolPolicy.ts +3 -14
- package/agent-runtime/runtimeToolSurface.ts +198 -0
- package/agent-runtime/types.ts +2 -1
- package/agentAliases.ts +8 -1
- package/agentRunCommand.ts +65 -95
- package/agentRuntimeLocal.ts +1 -7
- package/ai/agent/cliExecutor.ts +249 -34
- package/chat/messages/fetchMessages.ts +84 -0
- package/chat/messages/types.ts +185 -0
- package/cli/agentAliases.ts +8 -1
- package/cli/agentRunCommand.ts +65 -95
- package/cli/agentRuntimeLocal.ts +1 -7
- package/cli/cliEnvHelpers.ts +11 -7
- package/cli/client/agentRun.ts +94 -93
- package/cli/client/localRuntimeAdapter.ts +250 -69
- package/cli/commandRegistry.ts +2 -2
- package/cli/connectorRunArtifact.ts +0 -1
- package/cli/dialogCommands.ts +572 -0
- package/cli/dialogInternalCommandEntries.ts +4 -0
- package/cli/machineWsRunDispatch.ts +76 -39
- package/cli/offlineMarxistsAgentCommand.ts +6 -4
- package/cli/scriptCommandEntries.ts +0 -2
- package/cli/tui/readlineWorkspace.ts +69 -0
- package/cli/tui/session.ts +176 -1
- package/cliEnvHelpers.ts +11 -7
- package/client/agentConfigResolver.test.ts +4 -5
- package/client/agentRun.test.ts +307 -57
- package/client/agentRun.ts +94 -93
- package/client/localRuntimeAdapter.test.ts +332 -53
- package/client/localRuntimeAdapter.ts +250 -69
- package/client/localRuntimeDryRun.test.ts +23 -9
- package/client/localToolPolicy.test.ts +4 -4
- package/commandRegistry.ts +2 -2
- package/connectorRunArtifact.ts +0 -1
- package/database/server/db.ts +99 -0
- package/database/server/ensureDbOpen.ts +12 -0
- package/database/server/levelAuthorityStore.ts +20 -1
- package/database/server/memoryAuthorityStore.ts +133 -0
- package/database/server/serverStoreFactory.ts +118 -0
- package/dialogCommands.ts +572 -0
- package/dialogInternalCommandEntries.ts +4 -0
- package/machineWsRunDispatch.ts +76 -39
- package/offlineMarxistsAgentCommand.ts +6 -4
- package/package.json +11 -9
- package/scriptCommandEntries.ts +0 -2
- package/tui/readlineWorkspace.ts +69 -0
- package/tui/session.ts +176 -1
- package/agent-runtime/taskWorkspace.ts +0 -193
- package/agent-runtime/workspaceSession.ts +0 -76
- package/cli/client/taskWorktree.ts +0 -8
- package/cli/client/workspaceSession.ts +0 -11
- package/client/taskWorktree.ts +0 -8
- package/client/workspaceSession.test.ts +0 -57
- package/client/workspaceSession.ts +0 -11
package/ai/agent/cliExecutor.ts
CHANGED
|
@@ -15,8 +15,8 @@
|
|
|
15
15
|
|
|
16
16
|
import { exec, execSync, spawn } from "child_process";
|
|
17
17
|
import { randomUUID } from "node:crypto";
|
|
18
|
-
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
19
|
-
import { join } from "node:path";
|
|
18
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
19
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
20
20
|
import { tmpdir } from "node:os";
|
|
21
21
|
import { resolveLaunchableCodexCommand } from "../../connector-experimental/codexBinary";
|
|
22
22
|
import { buildCliPrompt } from "./cliPrompt";
|
|
@@ -26,6 +26,19 @@ import { buildCliPrompt } from "./cliPrompt";
|
|
|
26
26
|
/** 已支持的 CLI 工具。新增时在此联合类型追加,并在 EXECUTORS 里注册实现 */
|
|
27
27
|
export type CliProvider = "copilot" | "gemini" | "codex" | "claude" | "agy";
|
|
28
28
|
|
|
29
|
+
/**
|
|
30
|
+
* CLI provider 图片输入。
|
|
31
|
+
*
|
|
32
|
+
* - `source` 是原始输入(本地路径 / data URL / http URL / file URL)
|
|
33
|
+
* - `materializedPath` 是 materialize 后写入磁盘的绝对路径
|
|
34
|
+
* (本地路径保持不变,data URL 写入临时文件,file URL 转换为本地路径)
|
|
35
|
+
* - HTTP/HTTPS URL 目前无法原生传给 CLI,只作为 prompt 引用保留
|
|
36
|
+
*/
|
|
37
|
+
export interface CliImageInput {
|
|
38
|
+
source: string;
|
|
39
|
+
materializedPath?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
29
42
|
export interface CliExecuteOptions {
|
|
30
43
|
model?: string;
|
|
31
44
|
timeout?: number; // ms,默认 120_000
|
|
@@ -41,6 +54,8 @@ export interface CliExecuteOptions {
|
|
|
41
54
|
maxTokens?: number;
|
|
42
55
|
enableThinking?: boolean;
|
|
43
56
|
thinkingBudget?: number;
|
|
57
|
+
/** 图片输入(本地路径 / data URL / file URL)。materialize 由内部处理。 */
|
|
58
|
+
imageInputs?: CliImageInput[];
|
|
44
59
|
}
|
|
45
60
|
|
|
46
61
|
export interface CliExecuteResult {
|
|
@@ -184,6 +199,138 @@ function shouldPassClaudeModel(options: CliExecuteOptions): boolean {
|
|
|
184
199
|
return (options.env?.NOLO_CLAUDE_CLI_ALLOW_MODEL ?? process.env.NOLO_CLAUDE_CLI_ALLOW_MODEL) === "1";
|
|
185
200
|
}
|
|
186
201
|
|
|
202
|
+
// ── CLI 图片 materialize ─────────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
const DATA_URL_RE = /^data:image\/([\w.+-]+);base64,([A-Za-z0-9+/=]+)$/;
|
|
205
|
+
|
|
206
|
+
/** data URL extension (without prefix) → 完整扩展名 */
|
|
207
|
+
const MIME_EXT: Record<string, string> = {
|
|
208
|
+
"png": ".png",
|
|
209
|
+
"jpeg": ".jpg",
|
|
210
|
+
"jpg": ".jpg",
|
|
211
|
+
"gif": ".gif",
|
|
212
|
+
"webp": ".webp",
|
|
213
|
+
"svg+xml": ".svg",
|
|
214
|
+
"bmp": ".bmp",
|
|
215
|
+
"tiff": ".tiff",
|
|
216
|
+
"avif": ".avif",
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
function inferExtFromMime(extPart: string): string {
|
|
220
|
+
return MIME_EXT[extPart.toLowerCase().trim()] ?? ".bin";
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const FILE_URL_RE = /^file:\/\/(.+)$/;
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* 将单个 data URL 图片写入临时文件,返回绝对路径。
|
|
227
|
+
* caller 负责在执行完后清理 tempDir。
|
|
228
|
+
*/
|
|
229
|
+
function writeDataUrlToTempImage(dataUrl: string, tempDir: string, index: number): string {
|
|
230
|
+
const match = dataUrl.match(DATA_URL_RE);
|
|
231
|
+
if (!match) {
|
|
232
|
+
throw new Error(`Invalid data URL format for image #${index + 1}; expected data:image/<type>;base64,<data>`);
|
|
233
|
+
}
|
|
234
|
+
const [, mimeExt, b64] = match;
|
|
235
|
+
const ext = inferExtFromMime(mimeExt);
|
|
236
|
+
const filePath = join(tempDir, `image-${index + 1}${ext}`);
|
|
237
|
+
writeFileSync(filePath, Buffer.from(b64, "base64"));
|
|
238
|
+
return filePath;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Materialize image input sources into on-disk paths where possible.
|
|
243
|
+
*
|
|
244
|
+
* - 本地 path / file URL → 解析为绝对路径,无需写临时文件
|
|
245
|
+
* - data:image/...;base64,... → 写入 tempDir 内临时文件
|
|
246
|
+
* - http(s) URL → 不做下载,保留 source 引用;materializedPath 为空
|
|
247
|
+
*
|
|
248
|
+
* 返回 `{ materialized, tempDir }`,caller 需在执行完成后 `rmSync(tempDir, { recursive: true, force: true })`。
|
|
249
|
+
* 当没有任何 data URL 时 tempDir 不会被创建,返回 null。
|
|
250
|
+
*/
|
|
251
|
+
export function materializeCliImageInputs(
|
|
252
|
+
imageInputs: CliImageInput[],
|
|
253
|
+
cwd: string,
|
|
254
|
+
): { materialized: CliImageInput[]; tempDir: string | null } {
|
|
255
|
+
let tempDir: string | null = null;
|
|
256
|
+
const materialized = imageInputs.map((input, index) => {
|
|
257
|
+
const src = input.source.trim();
|
|
258
|
+
|
|
259
|
+
if (src.startsWith("http://") || src.startsWith("https://")) {
|
|
260
|
+
return { ...input, materializedPath: undefined };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const fileUrlMatch = src.match(FILE_URL_RE);
|
|
264
|
+
if (fileUrlMatch) {
|
|
265
|
+
const localPath = fileUrlMatch[1];
|
|
266
|
+
return {
|
|
267
|
+
...input,
|
|
268
|
+
materializedPath: isAbsolute(localPath) ? localPath : resolve(cwd, localPath),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (src.startsWith("data:")) {
|
|
273
|
+
if (!tempDir) {
|
|
274
|
+
tempDir = mkdtempSync(join(tmpdir(), "nolo-cli-assets-"));
|
|
275
|
+
}
|
|
276
|
+
const filePath = writeDataUrlToTempImage(src, tempDir, index);
|
|
277
|
+
return { ...input, materializedPath: filePath };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// 本地路径
|
|
281
|
+
return {
|
|
282
|
+
...input,
|
|
283
|
+
materializedPath: isAbsolute(src) ? src : resolve(cwd, src),
|
|
284
|
+
};
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
return { materialized, tempDir };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* 根据 provider 构建图片降级 prompt 块。
|
|
292
|
+
* Codex 使用原生 `-i` 标志,无需注入 prompt。
|
|
293
|
+
* 其他 provider 使用此函数将图片路径列表注入到 prompt 前面。
|
|
294
|
+
*/
|
|
295
|
+
function buildImageReferencePromptBlock(
|
|
296
|
+
provider: CliProvider,
|
|
297
|
+
materialized: CliImageInput[],
|
|
298
|
+
): { promptSuffix: string; warning: string | null } {
|
|
299
|
+
const label = getCliProviderLabel(provider);
|
|
300
|
+
const localPaths = materialized
|
|
301
|
+
.filter((img) => img.materializedPath)
|
|
302
|
+
.map((img) => img.materializedPath!);
|
|
303
|
+
const httpUrls = materialized
|
|
304
|
+
.filter((img) => !img.materializedPath)
|
|
305
|
+
.map((img) => img.source);
|
|
306
|
+
|
|
307
|
+
const lines: string[] = [];
|
|
308
|
+
if (localPaths.length > 0) {
|
|
309
|
+
lines.push(
|
|
310
|
+
`[User attached image(s) - local file references (accessible at these paths):]`,
|
|
311
|
+
...localPaths.map((p) => ` - ${p}`),
|
|
312
|
+
`Please read and analyze these image files as part of the user's request.`,
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
if (httpUrls.length > 0) {
|
|
316
|
+
lines.push(
|
|
317
|
+
`[User attached image(s) - remote URLs (content not available locally):]`,
|
|
318
|
+
...httpUrls.map((u) => ` - ${u}`),
|
|
319
|
+
`These remote URLs could not be downloaded automatically. If you cannot access them, describe what you can infer from context.`,
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const warning =
|
|
324
|
+
materialized.length > 0
|
|
325
|
+
? `${label} image input is passed as local file references; native image flags are not available in this wrapper.`
|
|
326
|
+
: null;
|
|
327
|
+
|
|
328
|
+
return {
|
|
329
|
+
promptSuffix: lines.length > 0 ? lines.join("\n") + "\n\n" : "",
|
|
330
|
+
warning,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
187
334
|
function collectCliCapabilityWarnings(
|
|
188
335
|
provider: CliProvider,
|
|
189
336
|
options: CliExecuteOptions
|
|
@@ -226,18 +373,51 @@ function resolveCliExecution(
|
|
|
226
373
|
provider: CliProvider,
|
|
227
374
|
prompt: string,
|
|
228
375
|
options: CliExecuteOptions
|
|
229
|
-
): { prompt: string; options: CliExecuteOptions; warnings: string[] } {
|
|
376
|
+
): { prompt: string; options: CliExecuteOptions; warnings: string[]; imageTempDir?: string } {
|
|
230
377
|
const warnings = collectCliCapabilityWarnings(provider, options);
|
|
378
|
+
|
|
379
|
+
// Handle image inputs
|
|
380
|
+
const imageInputs = options.imageInputs ?? [];
|
|
381
|
+
let resolvedPrompt = prompt;
|
|
382
|
+
let resolvedOptions = options;
|
|
383
|
+
let imageTempDir: string | undefined;
|
|
384
|
+
|
|
385
|
+
if (imageInputs.length > 0) {
|
|
386
|
+
const { materialized, tempDir } = materializeCliImageInputs(
|
|
387
|
+
imageInputs,
|
|
388
|
+
options.cwd ?? process.cwd(),
|
|
389
|
+
);
|
|
390
|
+
imageTempDir = tempDir ?? undefined;
|
|
391
|
+
|
|
392
|
+
if (provider === "codex") {
|
|
393
|
+
// Codex uses native -i flags; update options with materialized imageInputs
|
|
394
|
+
resolvedOptions = {
|
|
395
|
+
...resolvedOptions,
|
|
396
|
+
imageInputs: materialized,
|
|
397
|
+
};
|
|
398
|
+
} else {
|
|
399
|
+
// Non-codex providers: inject image references into prompt
|
|
400
|
+
const block = buildImageReferencePromptBlock(provider, materialized);
|
|
401
|
+
if (block.promptSuffix) {
|
|
402
|
+
resolvedPrompt = block.promptSuffix + resolvedPrompt;
|
|
403
|
+
}
|
|
404
|
+
if (block.warning) {
|
|
405
|
+
warnings.push(block.warning);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
231
410
|
if (supportsNativeSystemPrompt(provider) || !options.systemPrompt?.trim()) {
|
|
232
|
-
return { prompt, options, warnings };
|
|
411
|
+
return { prompt: resolvedPrompt, options: resolvedOptions, warnings, imageTempDir };
|
|
233
412
|
}
|
|
234
413
|
return {
|
|
235
|
-
prompt: buildCliPrompt(options.systemPrompt,
|
|
414
|
+
prompt: buildCliPrompt(options.systemPrompt, resolvedPrompt),
|
|
236
415
|
options: {
|
|
237
|
-
...
|
|
416
|
+
...resolvedOptions,
|
|
238
417
|
systemPrompt: undefined,
|
|
239
418
|
},
|
|
240
419
|
warnings,
|
|
420
|
+
imageTempDir,
|
|
241
421
|
};
|
|
242
422
|
}
|
|
243
423
|
|
|
@@ -410,6 +590,11 @@ function executeCodex(
|
|
|
410
590
|
yolo = true,
|
|
411
591
|
} = options;
|
|
412
592
|
|
|
593
|
+
// Collect materialized image paths from imageInputs
|
|
594
|
+
const imagePaths = (options.imageInputs ?? [])
|
|
595
|
+
.map((img) => img.materializedPath)
|
|
596
|
+
.filter((p): p is string => Boolean(p));
|
|
597
|
+
|
|
413
598
|
return new Promise((resolve, reject) => {
|
|
414
599
|
const tempDir = mkdtempSync(join(tmpdir(), "codex-exec-"));
|
|
415
600
|
const outputFile = join(tempDir, "last-message.txt");
|
|
@@ -429,6 +614,10 @@ function executeCodex(
|
|
|
429
614
|
args.push("--sandbox");
|
|
430
615
|
args.push("danger-full-access");
|
|
431
616
|
}
|
|
617
|
+
// Add image flags for Codex CLI native image support
|
|
618
|
+
for (const imgPath of imagePaths) {
|
|
619
|
+
args.push("-i", imgPath);
|
|
620
|
+
}
|
|
432
621
|
const start = Date.now();
|
|
433
622
|
const proc = spawn(executable, [...args, prompt], {
|
|
434
623
|
cwd,
|
|
@@ -699,11 +888,17 @@ export async function executeCli(
|
|
|
699
888
|
throw new Error(`Unknown CLI provider: "${provider}". Supported: ${Object.keys(EXECUTORS).join(", ")}`);
|
|
700
889
|
}
|
|
701
890
|
const resolved = resolveCliExecution(provider, prompt, options);
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
891
|
+
try {
|
|
892
|
+
const result = await executor(resolved.prompt, resolved.options);
|
|
893
|
+
return {
|
|
894
|
+
...result,
|
|
895
|
+
warnings: [...resolved.warnings, ...(result.warnings ?? [])],
|
|
896
|
+
};
|
|
897
|
+
} finally {
|
|
898
|
+
if (resolved.imageTempDir) {
|
|
899
|
+
rmSync(resolved.imageTempDir, { recursive: true, force: true });
|
|
900
|
+
}
|
|
901
|
+
}
|
|
707
902
|
}
|
|
708
903
|
|
|
709
904
|
export { buildCliPrompt };
|
|
@@ -831,36 +1026,56 @@ export function executeCliStreaming(
|
|
|
831
1026
|
): Promise<CliExecuteResult> {
|
|
832
1027
|
const resolved = resolveCliExecution(provider, prompt, options);
|
|
833
1028
|
const executor = EXECUTORS[provider];
|
|
1029
|
+
|
|
1030
|
+
const cleanupImageTempDir = () => {
|
|
1031
|
+
if (resolved.imageTempDir) {
|
|
1032
|
+
rmSync(resolved.imageTempDir, { recursive: true, force: true });
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
|
|
1036
|
+
const withCleanup = <T>(promise: Promise<T>): Promise<T> =>
|
|
1037
|
+
promise.finally(cleanupImageTempDir);
|
|
1038
|
+
|
|
834
1039
|
if (provider === "gemini") {
|
|
835
|
-
return
|
|
836
|
-
.
|
|
1040
|
+
return withCleanup(
|
|
1041
|
+
executeGeminiStreaming(resolved.prompt, resolved.options as CliExecuteOptions & { onChunk: (chunk: string) => void })
|
|
1042
|
+
.then((result) => ({ ...result, warnings: [...resolved.warnings, ...(result.warnings ?? [])] }))
|
|
1043
|
+
);
|
|
837
1044
|
}
|
|
838
1045
|
if (provider === "codex") {
|
|
839
|
-
return
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
1046
|
+
return withCleanup(
|
|
1047
|
+
executor(resolved.prompt, resolved.options).then((result) => {
|
|
1048
|
+
const merged = { ...result, warnings: [...resolved.warnings, ...(result.warnings ?? [])] };
|
|
1049
|
+
if (merged.text) options.onChunk(merged.text);
|
|
1050
|
+
return merged;
|
|
1051
|
+
})
|
|
1052
|
+
);
|
|
844
1053
|
}
|
|
845
1054
|
if (provider === "claude") {
|
|
846
|
-
return
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
1055
|
+
return withCleanup(
|
|
1056
|
+
executor(resolved.prompt, resolved.options).then((result) => {
|
|
1057
|
+
const merged = { ...result, warnings: [...resolved.warnings, ...(result.warnings ?? [])] };
|
|
1058
|
+
if (merged.text) options.onChunk(merged.text);
|
|
1059
|
+
return merged;
|
|
1060
|
+
})
|
|
1061
|
+
);
|
|
851
1062
|
}
|
|
852
1063
|
if (provider === "agy") {
|
|
853
|
-
return
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
1064
|
+
return withCleanup(
|
|
1065
|
+
executor(resolved.prompt, resolved.options).then((result) => {
|
|
1066
|
+
const merged = { ...result, warnings: [...resolved.warnings, ...(result.warnings ?? [])] };
|
|
1067
|
+
if (merged.text) options.onChunk(merged.text);
|
|
1068
|
+
return merged;
|
|
1069
|
+
})
|
|
1070
|
+
);
|
|
858
1071
|
}
|
|
859
1072
|
if (provider !== "copilot") {
|
|
860
|
-
return
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
1073
|
+
return withCleanup(
|
|
1074
|
+
executor(resolved.prompt, resolved.options).then((result) => ({
|
|
1075
|
+
...result,
|
|
1076
|
+
warnings: [...resolved.warnings, ...(result.warnings ?? [])],
|
|
1077
|
+
}))
|
|
1078
|
+
);
|
|
864
1079
|
}
|
|
865
1080
|
|
|
866
1081
|
const {
|
|
@@ -871,7 +1086,7 @@ export function executeCliStreaming(
|
|
|
871
1086
|
onChunk,
|
|
872
1087
|
} = resolved.options as CliExecuteOptions & { onChunk: (chunk: string) => void };
|
|
873
1088
|
|
|
874
|
-
return new Promise((resolve, reject) => {
|
|
1089
|
+
return withCleanup(new Promise<CliExecuteResult>((resolve, reject) => {
|
|
875
1090
|
const args = [
|
|
876
1091
|
"copilot", "--",
|
|
877
1092
|
"-p", resolved.prompt,
|
|
@@ -931,7 +1146,7 @@ export function executeCliStreaming(
|
|
|
931
1146
|
if (timer) clearTimeout(timer);
|
|
932
1147
|
reject(err);
|
|
933
1148
|
});
|
|
934
|
-
});
|
|
1149
|
+
}));
|
|
935
1150
|
}
|
|
936
1151
|
|
|
937
1152
|
function executeGeminiStreaming(
|
|
@@ -0,0 +1,84 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,185 @@
|
|
|
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
|
+
}
|
package/cli/agentAliases.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
export const PLATFORM_DEMO_USER_ID = "b2e06f801f";
|
|
2
|
+
export const CURRENT_OPERATOR_USER_ID = "0e95801d90";
|
|
3
|
+
export const NOLO_DEFAULT_AGENT_ID = "01NOLOAPPBLD000000019KCKT0";
|
|
4
|
+
export const NOLO_DEFAULT_AGENT_KEY = `agent-pub-${NOLO_DEFAULT_AGENT_ID}`;
|
|
2
5
|
export const NOLO_PROJECT_MANAGER_AGENT_ID = "01NOLOPROJMGR00000000MSVGG";
|
|
3
6
|
export const NOLO_PROJECT_MANAGER_AGENT_KEY =
|
|
4
7
|
`agent-${PLATFORM_DEMO_USER_ID}-${NOLO_PROJECT_MANAGER_AGENT_ID}`;
|
|
@@ -7,7 +10,7 @@ export const NOLO_SENIOR_FULLSTACK_AGENT_KEY =
|
|
|
7
10
|
`agent-${PLATFORM_DEMO_USER_ID}-${NOLO_SENIOR_FULLSTACK_AGENT_ID}`;
|
|
8
11
|
export const NOLO_FRONTEND_AGENT_ID = "01FRONTENDAG0000000115N4E1";
|
|
9
12
|
export const NOLO_FRONTEND_AGENT_KEY =
|
|
10
|
-
`agent-${
|
|
13
|
+
`agent-${CURRENT_OPERATOR_USER_ID}-${NOLO_FRONTEND_AGENT_ID}`;
|
|
11
14
|
export const WIN_CODEX_AGENT_ID = "WINCODEX00000000FQ0LK0";
|
|
12
15
|
export const WIN_CODEX_AGENT_KEY =
|
|
13
16
|
`agent-0e95801d90-${WIN_CODEX_AGENT_ID}`;
|
|
@@ -19,6 +22,10 @@ export const MIMO_MONTH_AGENT_KEY =
|
|
|
19
22
|
`agent-0e95801d90-${MIMO_MONTH_AGENT_ID}`;
|
|
20
23
|
|
|
21
24
|
const AGENT_ALIAS_TO_KEY: Record<string, string> = {
|
|
25
|
+
nolo: NOLO_DEFAULT_AGENT_KEY,
|
|
26
|
+
default: NOLO_DEFAULT_AGENT_KEY,
|
|
27
|
+
"default-nolo": NOLO_DEFAULT_AGENT_KEY,
|
|
28
|
+
|
|
22
29
|
// Win Codex (高智力终审与架构把关)
|
|
23
30
|
"win-codex": WIN_CODEX_AGENT_KEY,
|
|
24
31
|
"wincodex": WIN_CODEX_AGENT_KEY,
|