@trans-ai/trans-code 0.3.0 → 0.4.0
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 +13 -3
- package/package.json +1 -1
- package/src/agent/loop.test.ts +92 -1
- package/src/agent/loop.ts +74 -0
- package/src/agent/tools/bash.test.ts +42 -1
- package/src/agent/tools/bash.ts +202 -15
- package/src/agent/tools/dispatch.test.ts +42 -0
- package/src/agent/tools/dispatch.ts +11 -1
- package/src/agent/tools/index.ts +2 -0
- package/src/agent/tools/powershell.test.ts +61 -0
- package/src/agent/tools/read-only.ts +16 -0
- package/src/agent/tools/session.ts +12 -0
- package/src/agent/tools/shell-paths.test.ts +65 -0
- package/src/agent/tools/shell-paths.ts +19 -0
- package/src/agent/tools/types.ts +2 -0
- package/src/cli.ts +2 -0
- package/src/commands.ts +18 -0
- package/src/provider/model-list.test.ts +65 -0
- package/src/provider/provider.ts +34 -0
- package/src/screens/REPL.tsx +256 -27
- package/src/sessions/store.test.ts +91 -0
- package/src/sessions/store.ts +149 -0
- package/src/version.ts +1 -1
package/src/screens/REPL.tsx
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
registerApiKey,
|
|
10
10
|
lookupApiKey,
|
|
11
11
|
setCustomModel,
|
|
12
|
+
listEndpointModels,
|
|
12
13
|
vendorModelSpec,
|
|
13
14
|
vendorModels,
|
|
14
15
|
verifyModel,
|
|
@@ -18,6 +19,13 @@ import { loadConfig } from '../config.js';
|
|
|
18
19
|
import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
|
|
19
20
|
import { createToolSession } from '../agent/tools/index.js';
|
|
20
21
|
import { getPermissionMode } from '../agent/permission.js';
|
|
22
|
+
import {
|
|
23
|
+
generateTitle,
|
|
24
|
+
getSession,
|
|
25
|
+
listSessions,
|
|
26
|
+
saveSession,
|
|
27
|
+
searchSessions,
|
|
28
|
+
} from '../sessions/store.js';
|
|
21
29
|
import { walkFiles } from '../agent/tools/fs-utils.js';
|
|
22
30
|
import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
|
|
23
31
|
import { renderDiff } from './diff-render.js';
|
|
@@ -68,14 +76,23 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
68
76
|
fail: number;
|
|
69
77
|
} | null>(null);
|
|
70
78
|
const [pendingModel, setPendingModel] = useState<ModelId | null>(null);
|
|
79
|
+
const pendingModelRef = useRef<ModelId | null>(null);
|
|
80
|
+
const setVendor = (id: ModelId | null) => {
|
|
81
|
+
pendingModelRef.current = id;
|
|
82
|
+
setPendingModel(id);
|
|
83
|
+
};
|
|
71
84
|
const [modelCursor, setModelCursor] = useState(0);
|
|
72
85
|
// Model selection flow: vendor → model → key (reused if saved) → check.
|
|
73
86
|
const [pickOptions, setPickOptions] = useState<string[]>([]);
|
|
74
87
|
const [pickCursor, setPickCursor] = useState(0);
|
|
88
|
+
const [pickLive, setPickLive] = useState(false);
|
|
89
|
+
const [pickLoading, setPickLoading] = useState(false);
|
|
90
|
+
const vendorModelCache = useRef(new Map<string, string[]>());
|
|
75
91
|
const [pendingSpec, setPendingSpec] = useState<string | null>(null);
|
|
76
92
|
const [pendingDisplayName, setPendingDisplayName] = useState('');
|
|
77
93
|
const [keyHint, setKeyHint] = useState<string | null>(null);
|
|
78
94
|
const [customBaseDraft, setCustomBaseDraft] = useState('');
|
|
95
|
+
const [customKeyDraft, setCustomKeyDraft] = useState('');
|
|
79
96
|
|
|
80
97
|
const models = getAvailableModels();
|
|
81
98
|
// Bun's scheduler can drop the render flush for updates issued from the
|
|
@@ -98,6 +115,10 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
98
115
|
// One tool session per process: bash cwd and read-file state persist
|
|
99
116
|
// across prompts, like the ACP session.
|
|
100
117
|
const toolSessionRef = useRef(createToolSession(process.cwd()));
|
|
118
|
+
// Conversation persistence: lazily created record + model-generated title.
|
|
119
|
+
const conversationRef = useRef<{ id: string; createdAt: number; titled: boolean } | null>(null);
|
|
120
|
+
const conversationTitleRef = useRef('');
|
|
121
|
+
const lastSessionsRef = useRef<string[]>([]);
|
|
101
122
|
|
|
102
123
|
// @-mention file completion: lazy file list, active query, dismissed flag.
|
|
103
124
|
const [fileList, setFileList] = useState<string[] | null>(null);
|
|
@@ -176,11 +197,14 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
176
197
|
);
|
|
177
198
|
|
|
178
199
|
const runChat = useCallback(
|
|
179
|
-
async (text: string, display?: string) => {
|
|
200
|
+
async (text: string, display?: string, options?: { planMode?: boolean }) => {
|
|
180
201
|
setBusyBoth(true);
|
|
181
202
|
const controller = new AbortController();
|
|
182
203
|
abortRef.current = controller;
|
|
183
204
|
addHistory({ input: display ?? text, output: '' });
|
|
205
|
+
if (options?.planMode) {
|
|
206
|
+
appendChatOutput('[plan 模式:只读探索,产出方案,PLAN READY 后可让我执行]\n');
|
|
207
|
+
}
|
|
184
208
|
|
|
185
209
|
try {
|
|
186
210
|
const provider =
|
|
@@ -201,6 +225,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
201
225
|
messagesRef.current.push(new HumanMessage(text));
|
|
202
226
|
|
|
203
227
|
let lastWasTool = false;
|
|
228
|
+
let turnAssistantText = '';
|
|
204
229
|
const stats = createTurnStats();
|
|
205
230
|
const titlesById = new Map<string, string>();
|
|
206
231
|
const bufferedLines: string[] = [];
|
|
@@ -209,12 +234,16 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
209
234
|
model: provider?.model,
|
|
210
235
|
cwd: process.cwd(),
|
|
211
236
|
messages: messagesRef.current,
|
|
212
|
-
systemPrompt
|
|
237
|
+
systemPrompt: options?.planMode
|
|
238
|
+
? `${systemPrompt}\n\nPLAN MODE: explore read-only, then output a numbered implementation plan with exact files and changes. End with the line PLAN READY. Do not modify anything.`
|
|
239
|
+
: systemPrompt,
|
|
240
|
+
planMode: options?.planMode === true,
|
|
213
241
|
signal: controller.signal,
|
|
214
242
|
toolSession: toolSessionRef.current,
|
|
215
243
|
onEvent: event => {
|
|
216
244
|
if (event.type === 'text') {
|
|
217
245
|
appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
|
|
246
|
+
turnAssistantText += event.text;
|
|
218
247
|
lastWasTool = false;
|
|
219
248
|
} else if (event.type === 'max_turns_reached') {
|
|
220
249
|
appendChatOutput(
|
|
@@ -257,6 +286,44 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
257
286
|
}
|
|
258
287
|
|
|
259
288
|
messagesRef.current = result.messages;
|
|
289
|
+
|
|
290
|
+
// Persist the conversation for /sessions and /resume.
|
|
291
|
+
if (!conversationRef.current) {
|
|
292
|
+
conversationRef.current = {
|
|
293
|
+
id: `ses_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`,
|
|
294
|
+
createdAt: Date.now(),
|
|
295
|
+
titled: false,
|
|
296
|
+
};
|
|
297
|
+
conversationTitleRef.current = text.replace(/\s+/g, ' ').trim().slice(0, 24) || '新对话';
|
|
298
|
+
}
|
|
299
|
+
const conversation = conversationRef.current;
|
|
300
|
+
const persist = () =>
|
|
301
|
+
saveSession({
|
|
302
|
+
id: conversation.id,
|
|
303
|
+
title: conversationTitleRef.current,
|
|
304
|
+
createdAt: conversation.createdAt,
|
|
305
|
+
updatedAt: Date.now(),
|
|
306
|
+
cwd: process.cwd(),
|
|
307
|
+
model: ctx.modelId,
|
|
308
|
+
messages: messagesRef.current,
|
|
309
|
+
});
|
|
310
|
+
persist();
|
|
311
|
+
if (!conversation.titled && provider) {
|
|
312
|
+
conversation.titled = true;
|
|
313
|
+
const firstUserText = text;
|
|
314
|
+
void (async () => {
|
|
315
|
+
try {
|
|
316
|
+
conversationTitleRef.current = await generateTitle(
|
|
317
|
+
provider.model,
|
|
318
|
+
firstUserText,
|
|
319
|
+
turnAssistantText,
|
|
320
|
+
);
|
|
321
|
+
} catch {
|
|
322
|
+
// keep the derived fallback title
|
|
323
|
+
}
|
|
324
|
+
persist();
|
|
325
|
+
})();
|
|
326
|
+
}
|
|
260
327
|
if (controller.signal.aborted) appendChatOutput('\n(cancelled)');
|
|
261
328
|
} catch (error) {
|
|
262
329
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -309,33 +376,26 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
309
376
|
setPendingSpec(null);
|
|
310
377
|
setPendingDisplayName('');
|
|
311
378
|
setKeyHint(null);
|
|
312
|
-
|
|
379
|
+
setCustomBaseDraft('');
|
|
380
|
+
setCustomKeyDraft('');
|
|
381
|
+
setVendor(null);
|
|
313
382
|
setPhase('idle');
|
|
314
383
|
dragFlush();
|
|
315
384
|
},
|
|
316
385
|
[ctx, addHistory, dragFlush],
|
|
317
386
|
);
|
|
318
387
|
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
const savedKey = lookupApiKey(spec);
|
|
323
|
-
const apiKey = value.trim() || savedKey;
|
|
324
|
-
|
|
325
|
-
if (!apiKey) {
|
|
326
|
-
addHistory({ input: '••••••••', output: 'API key 不能为空。' });
|
|
327
|
-
return; // stay on the key prompt
|
|
328
|
-
}
|
|
329
|
-
|
|
388
|
+
/** Verify a selection and apply it, or surface the error and re-prompt. */
|
|
389
|
+
const finalizeSelection = useCallback(
|
|
390
|
+
async (spec: string, displayName: string, apiKey: string) => {
|
|
330
391
|
if (process.env.TRANSCODE_SKIP_MODEL_CHECK === '1') {
|
|
331
|
-
applyModelSwitch(spec,
|
|
392
|
+
applyModelSwitch(spec, displayName, apiKey, '已跳过连通性测试');
|
|
332
393
|
return;
|
|
333
394
|
}
|
|
334
|
-
|
|
335
395
|
setPhase('model_check');
|
|
336
396
|
const result = await verifyModel(spec, apiKey);
|
|
337
397
|
if (result.ok) {
|
|
338
|
-
applyModelSwitch(spec,
|
|
398
|
+
applyModelSwitch(spec, displayName, apiKey, `✓ ${result.message}`);
|
|
339
399
|
return;
|
|
340
400
|
}
|
|
341
401
|
addHistory({
|
|
@@ -346,7 +406,55 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
346
406
|
commitInput('');
|
|
347
407
|
dragFlush();
|
|
348
408
|
},
|
|
349
|
-
[
|
|
409
|
+
[applyModelSwitch, addHistory, commitInput, dragFlush],
|
|
410
|
+
);
|
|
411
|
+
|
|
412
|
+
const handleApiKey = useCallback(
|
|
413
|
+
async (value: string) => {
|
|
414
|
+
// Custom-gateway setup: collect the key, then pick the model from the
|
|
415
|
+
// gateway's live list instead of asking for a blind model name.
|
|
416
|
+
if (pendingSpec === null && pendingModel === null && customBaseDraft) {
|
|
417
|
+
const apiKey = value.trim() || lookupApiKey('custom');
|
|
418
|
+
if (!apiKey) {
|
|
419
|
+
addHistory({ input: '••••••••', output: 'API key 不能为空。' });
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
setCustomKeyDraft(apiKey);
|
|
423
|
+
setPickOptions([]);
|
|
424
|
+
setPickCursor(0);
|
|
425
|
+
setPickLive(false);
|
|
426
|
+
setPhase('model_pick');
|
|
427
|
+
commitInput('');
|
|
428
|
+
setPickLoading(true);
|
|
429
|
+
const live = await listEndpointModels('', { baseUrl: customBaseDraft, apiKey });
|
|
430
|
+
setPickOptions(live);
|
|
431
|
+
setPickLive(live.length > 0);
|
|
432
|
+
setPickLoading(false);
|
|
433
|
+
dragFlush();
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const spec = pendingSpec!;
|
|
438
|
+
const savedKey = lookupApiKey(spec);
|
|
439
|
+
const apiKey = value.trim() || savedKey;
|
|
440
|
+
|
|
441
|
+
if (!apiKey) {
|
|
442
|
+
addHistory({ input: '••••••••', output: 'API key 不能为空。' });
|
|
443
|
+
return; // stay on the key prompt
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
await finalizeSelection(spec, pendingDisplayName, apiKey);
|
|
447
|
+
},
|
|
448
|
+
[
|
|
449
|
+
pendingSpec,
|
|
450
|
+
pendingModel,
|
|
451
|
+
pendingDisplayName,
|
|
452
|
+
customBaseDraft,
|
|
453
|
+
addHistory,
|
|
454
|
+
finalizeSelection,
|
|
455
|
+
commitInput,
|
|
456
|
+
dragFlush,
|
|
457
|
+
],
|
|
350
458
|
);
|
|
351
459
|
|
|
352
460
|
const handleSubmit = useCallback(async (raw: string) => {
|
|
@@ -365,7 +473,9 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
365
473
|
return;
|
|
366
474
|
}
|
|
367
475
|
setCustomBaseDraft(trimmed);
|
|
368
|
-
|
|
476
|
+
setKeyHint(lookupApiKey('custom') ? maskKey(lookupApiKey('custom')!) : null);
|
|
477
|
+
setPendingSpec(null);
|
|
478
|
+
setPhase('model_apikey');
|
|
369
479
|
commitInput('');
|
|
370
480
|
return;
|
|
371
481
|
}
|
|
@@ -373,9 +483,9 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
373
483
|
if (phase === 'model_name') {
|
|
374
484
|
if (!trimmed) return;
|
|
375
485
|
if (pendingModel === null) {
|
|
376
|
-
// Custom gateway
|
|
486
|
+
// Custom gateway, free-text model name (live list was empty/unreachable).
|
|
377
487
|
setCustomModel({ baseUrl: customBaseDraft, model: trimmed });
|
|
378
|
-
|
|
488
|
+
await finalizeSelection('custom', `custom/${trimmed}`, customKeyDraft);
|
|
379
489
|
} else {
|
|
380
490
|
beginKeyStep(vendorModelSpec(pendingModel, trimmed), `${pendingModel}/${trimmed}`);
|
|
381
491
|
}
|
|
@@ -396,6 +506,91 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
396
506
|
return;
|
|
397
507
|
}
|
|
398
508
|
|
|
509
|
+
if (cmdName === 'new') {
|
|
510
|
+
conversationRef.current = null;
|
|
511
|
+
conversationTitleRef.current = '';
|
|
512
|
+
messagesRef.current = [];
|
|
513
|
+
toolSessionRef.current = createToolSession(process.cwd());
|
|
514
|
+
addHistory({ input: trimmed, output: '已开始新对话。' });
|
|
515
|
+
commitInput('');
|
|
516
|
+
setHistoryIndex(-1);
|
|
517
|
+
setSavedInput('');
|
|
518
|
+
dragFlush();
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
if (cmdName === 'sessions') {
|
|
523
|
+
const keyword = args.join(' ');
|
|
524
|
+
const found = keyword.trim() ? searchSessions(keyword) : listSessions();
|
|
525
|
+
lastSessionsRef.current = found.map((session) => session.id);
|
|
526
|
+
const lines = found
|
|
527
|
+
.slice(0, 20)
|
|
528
|
+
.map(
|
|
529
|
+
(session, index) =>
|
|
530
|
+
`${index + 1}. ${session.title} · ${new Date(session.updatedAt).toLocaleString()} · ` +
|
|
531
|
+
`${session.model} · ${session.messages.length} 条`,
|
|
532
|
+
);
|
|
533
|
+
addHistory({
|
|
534
|
+
input: trimmed,
|
|
535
|
+
output: found.length
|
|
536
|
+
? `${keyword.trim() ? `匹配“${keyword}”` : ''}${found.length} 个对话:\n${lines.join('\n')}\n/resume <序号|id|标题片段> 恢复`
|
|
537
|
+
: keyword.trim()
|
|
538
|
+
? `没有匹配“${keyword}”的对话。`
|
|
539
|
+
: '暂无历史对话。',
|
|
540
|
+
});
|
|
541
|
+
commitInput('');
|
|
542
|
+
setHistoryIndex(-1);
|
|
543
|
+
setSavedInput('');
|
|
544
|
+
dragFlush();
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
if (cmdName === 'resume') {
|
|
549
|
+
const target = args.join(' ').trim();
|
|
550
|
+
const list = listSessions();
|
|
551
|
+
let record = undefined as ReturnType<typeof getSession>;
|
|
552
|
+
if (/^\d+$/.test(target)) {
|
|
553
|
+
const indexed = lastSessionsRef.current[Number(target) - 1];
|
|
554
|
+
record = (indexed ? getSession(indexed) : undefined) ?? list[Number(target) - 1];
|
|
555
|
+
} else if (target) {
|
|
556
|
+
record = getSession(target) ?? list.find(
|
|
557
|
+
(session) => session.id.includes(target) || session.title.includes(target),
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
if (!record) {
|
|
561
|
+
addHistory({ input: trimmed, output: `未找到对话“${target || '(空)'}”。先 /sessions 查看列表。` });
|
|
562
|
+
} else {
|
|
563
|
+
conversationRef.current = { id: record.id, createdAt: record.createdAt, titled: true };
|
|
564
|
+
conversationTitleRef.current = record.title;
|
|
565
|
+
messagesRef.current = record.messages;
|
|
566
|
+
toolSessionRef.current = createToolSession(process.cwd());
|
|
567
|
+
addHistory({
|
|
568
|
+
input: trimmed,
|
|
569
|
+
output: `已恢复「${record.title}」(${record.messages.length} 条消息,${record.model}),继续对话。`,
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
commitInput('');
|
|
573
|
+
setHistoryIndex(-1);
|
|
574
|
+
setSavedInput('');
|
|
575
|
+
dragFlush();
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
if (cmdName === 'plan') {
|
|
580
|
+
const task = stripped.startsWith('/plan') ? stripped.slice(5).trim() : stripped;
|
|
581
|
+
if (!task) {
|
|
582
|
+
addHistory({ input: trimmed, output: '用法:/plan <任务描述> — 只读探索并产出实施方案(PLAN READY),确认后再执行' });
|
|
583
|
+
dragFlush();
|
|
584
|
+
commitInput('');
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
commitInput('');
|
|
588
|
+
setHistoryIndex(-1);
|
|
589
|
+
setSavedInput('');
|
|
590
|
+
await runChat(task, trimmed, { planMode: true });
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
|
|
399
594
|
if (cmdName === 'init') {
|
|
400
595
|
commitInput('');
|
|
401
596
|
setHistoryIndex(-1);
|
|
@@ -456,7 +651,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
456
651
|
}
|
|
457
652
|
if (phase !== 'idle') {
|
|
458
653
|
setPhase('idle');
|
|
459
|
-
|
|
654
|
+
setVendor(null);
|
|
460
655
|
commitInput('');
|
|
461
656
|
addHistory({ input: '', output: 'Cancelled.' });
|
|
462
657
|
return;
|
|
@@ -482,7 +677,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
482
677
|
const selected = models[modelCursor];
|
|
483
678
|
if (selected.id === 'custom') {
|
|
484
679
|
const saved = loadConfig().custom;
|
|
485
|
-
|
|
680
|
+
setVendor(null);
|
|
486
681
|
if (saved?.baseUrl && saved.model) {
|
|
487
682
|
beginKeyStep('custom', `custom/${saved.model}`);
|
|
488
683
|
} else {
|
|
@@ -491,12 +686,35 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
491
686
|
}
|
|
492
687
|
return;
|
|
493
688
|
}
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
setPickOptions(options);
|
|
689
|
+
setVendor(selected.id);
|
|
690
|
+
setPickOptions(vendorModels(selected.id));
|
|
497
691
|
setPickCursor(0);
|
|
692
|
+
setPickLive(false);
|
|
498
693
|
setPhase('model_pick');
|
|
499
694
|
commitInput('');
|
|
695
|
+
|
|
696
|
+
// Prefer the endpoint's live model list (what it actually serves)
|
|
697
|
+
// over the curated fallback; cache per vendor for this process.
|
|
698
|
+
const vendor = selected.id;
|
|
699
|
+
const cached = vendorModelCache.current.get(vendor);
|
|
700
|
+
if (cached) {
|
|
701
|
+
if (cached.length > 0) {
|
|
702
|
+
setPickOptions(cached);
|
|
703
|
+
setPickLive(true);
|
|
704
|
+
}
|
|
705
|
+
} else {
|
|
706
|
+
setPickLoading(true);
|
|
707
|
+
void listEndpointModels(vendor)
|
|
708
|
+
.then((live) => {
|
|
709
|
+
vendorModelCache.current.set(vendor, live);
|
|
710
|
+
if (live.length > 0 && pendingModelRef.current === vendor) {
|
|
711
|
+
setPickOptions(live);
|
|
712
|
+
setPickCursor(0);
|
|
713
|
+
setPickLive(true);
|
|
714
|
+
}
|
|
715
|
+
})
|
|
716
|
+
.finally(() => setPickLoading(false));
|
|
717
|
+
}
|
|
500
718
|
return;
|
|
501
719
|
}
|
|
502
720
|
if (key.upArrow) {
|
|
@@ -519,7 +737,13 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
519
737
|
return;
|
|
520
738
|
}
|
|
521
739
|
const modelName = pickOptions[pickCursor]!;
|
|
522
|
-
|
|
740
|
+
if (pendingModel === null && customBaseDraft) {
|
|
741
|
+
// Custom gateway: model chosen from the live list.
|
|
742
|
+
setCustomModel({ baseUrl: customBaseDraft, model: modelName });
|
|
743
|
+
void finalizeSelection('custom', `custom/${modelName}`, customKeyDraft);
|
|
744
|
+
} else {
|
|
745
|
+
beginKeyStep(vendorModelSpec(pendingModel!, modelName), `${pendingModel}/${modelName}`);
|
|
746
|
+
}
|
|
523
747
|
commitInput('');
|
|
524
748
|
return;
|
|
525
749
|
}
|
|
@@ -681,6 +905,9 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
681
905
|
|
|
682
906
|
{phase === 'model_pick' && (
|
|
683
907
|
<Box flexDirection="column" marginLeft={2}>
|
|
908
|
+
{pendingModel === null && customBaseDraft && (
|
|
909
|
+
<Text color="gray" dimColor>自定义网关 {customBaseDraft} 的模型:</Text>
|
|
910
|
+
)}
|
|
684
911
|
{pickOptions.map((name, i) => (
|
|
685
912
|
<Box key={name}>
|
|
686
913
|
<Text color={i === pickCursor ? 'cyan' : undefined}>
|
|
@@ -695,6 +922,8 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
695
922
|
自定义模型名…
|
|
696
923
|
</Text>
|
|
697
924
|
</Box>
|
|
925
|
+
{pickLoading && <Text color="gray" dimColor>… 正在从网关获取实时模型列表</Text>}
|
|
926
|
+
{!pickLoading && pickLive && <Text color="gray" dimColor>(网关实时列表)</Text>}
|
|
698
927
|
<Text color="gray" dimColor>↑↓ 选择模型 · Enter 确认</Text>
|
|
699
928
|
</Box>
|
|
700
929
|
)}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { AIMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
|
|
6
|
+
import {
|
|
7
|
+
getSession,
|
|
8
|
+
listSessions,
|
|
9
|
+
saveSession,
|
|
10
|
+
searchSessions,
|
|
11
|
+
type SessionRecord,
|
|
12
|
+
} from './store.js';
|
|
13
|
+
|
|
14
|
+
let dir: string;
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
dir = mkdtempSync(path.join(tmpdir(), 'transcode-sessions-test-'));
|
|
17
|
+
process.env.TRANSCODE_SESSIONS_DIR = dir;
|
|
18
|
+
});
|
|
19
|
+
afterEach(() => {
|
|
20
|
+
delete process.env.TRANSCODE_SESSIONS_DIR;
|
|
21
|
+
rmSync(dir, { recursive: true, force: true });
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
function sample(title: string, body: string): SessionRecord {
|
|
25
|
+
return {
|
|
26
|
+
id: 'ses_test1',
|
|
27
|
+
title,
|
|
28
|
+
createdAt: Date.now(),
|
|
29
|
+
updatedAt: Date.now(),
|
|
30
|
+
cwd: '/tmp',
|
|
31
|
+
model: 'deepseek',
|
|
32
|
+
messages: [
|
|
33
|
+
new SystemMessage('system prompt'),
|
|
34
|
+
new HumanMessage(body),
|
|
35
|
+
new AIMessage({
|
|
36
|
+
content: '好的',
|
|
37
|
+
tool_calls: [{ id: 'call_1', name: 'bash', args: { command: 'ls' } }],
|
|
38
|
+
}),
|
|
39
|
+
new ToolMessage({ content: 'file-a file-b', tool_call_id: 'call_1', name: 'bash' }),
|
|
40
|
+
new AIMessage('完成'),
|
|
41
|
+
],
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
describe('session store', () => {
|
|
46
|
+
test('save + list roundtrips with metadata', () => {
|
|
47
|
+
saveSession(sample('更新 README', '帮我更新这个仓库的 README'));
|
|
48
|
+
|
|
49
|
+
const listed = listSessions();
|
|
50
|
+
expect(listed.length).toBe(1);
|
|
51
|
+
expect(listed[0]!.title).toBe('更新 README');
|
|
52
|
+
expect(listed[0]!.model).toBe('deepseek');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('messages survive serialization with tool calls intact', () => {
|
|
56
|
+
saveSession(sample('更新 README', '帮我更新 README'));
|
|
57
|
+
|
|
58
|
+
const loaded = getSession('ses_test1');
|
|
59
|
+
expect(loaded).toBeDefined();
|
|
60
|
+
const messages = loaded!.messages;
|
|
61
|
+
expect(messages[0]!.getType()).toBe('system');
|
|
62
|
+
expect(messages[1]!.content).toBe('帮我更新 README');
|
|
63
|
+
const ai = messages[2] as AIMessage;
|
|
64
|
+
expect(ai.tool_calls?.[0]?.name).toBe('bash');
|
|
65
|
+
const tool = messages[3] as ToolMessage;
|
|
66
|
+
expect(tool.tool_call_id).toBe('call_1');
|
|
67
|
+
expect(tool.content).toBe('file-a file-b');
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('search matches titles and message content, case-insensitive', () => {
|
|
71
|
+
saveSession(sample('部署脚本调整', '帮我看看部署'));
|
|
72
|
+
saveSession({ ...sample('无关对话', '今天天气如何'), id: 'ses_test2' });
|
|
73
|
+
|
|
74
|
+
const byTitle = searchSessions('部署');
|
|
75
|
+
expect(byTitle.map((s) => s.id)).toEqual(['ses_test1']);
|
|
76
|
+
|
|
77
|
+
const byBody = searchSessions('天气');
|
|
78
|
+
expect(byBody.map((s) => s.id)).toEqual(['ses_test2']);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test('list is ordered newest first', () => {
|
|
82
|
+
const older = sample('旧对话', 'a');
|
|
83
|
+
older.createdAt = Date.now() - 10_000;
|
|
84
|
+
older.updatedAt = Date.now() - 10_000;
|
|
85
|
+
older.id = 'ses_old';
|
|
86
|
+
saveSession(older);
|
|
87
|
+
saveSession(sample('新对话', 'b'));
|
|
88
|
+
|
|
89
|
+
expect(listSessions()[0]!.id).toBe('ses_test1');
|
|
90
|
+
});
|
|
91
|
+
});
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {
|
|
5
|
+
AIMessage,
|
|
6
|
+
HumanMessage,
|
|
7
|
+
SystemMessage,
|
|
8
|
+
ToolMessage,
|
|
9
|
+
type BaseMessage,
|
|
10
|
+
type MessageContent,
|
|
11
|
+
} from '@langchain/core/messages';
|
|
12
|
+
|
|
13
|
+
/** A persisted conversation (one JSON file under ~/.transcode/sessions). */
|
|
14
|
+
export interface SessionRecord {
|
|
15
|
+
id: string;
|
|
16
|
+
title: string;
|
|
17
|
+
createdAt: number;
|
|
18
|
+
updatedAt: number;
|
|
19
|
+
cwd: string;
|
|
20
|
+
model: string;
|
|
21
|
+
messages: BaseMessage[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface StoredMessage {
|
|
25
|
+
type: string;
|
|
26
|
+
content: MessageContent;
|
|
27
|
+
tool_calls?: AIMessage['tool_calls'];
|
|
28
|
+
tool_call_id?: string;
|
|
29
|
+
name?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Test isolation mirrors TRANSCODE_CONFIG_PATH.
|
|
33
|
+
const sessionsDir = (): string =>
|
|
34
|
+
process.env.TRANSCODE_SESSIONS_DIR ?? path.join(homedir(), '.transcode', 'sessions');
|
|
35
|
+
|
|
36
|
+
function serialize(messages: BaseMessage[]): StoredMessage[] {
|
|
37
|
+
return messages.map((message) => {
|
|
38
|
+
const stored: StoredMessage = { type: message.getType(), content: message.content };
|
|
39
|
+
const ai = message as AIMessage;
|
|
40
|
+
if (ai.tool_calls?.length) stored.tool_calls = ai.tool_calls;
|
|
41
|
+
const tool = message as ToolMessage;
|
|
42
|
+
if (tool.tool_call_id) {
|
|
43
|
+
stored.tool_call_id = tool.tool_call_id;
|
|
44
|
+
stored.name = tool.name;
|
|
45
|
+
}
|
|
46
|
+
return stored;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function deserialize(stored: StoredMessage[]): BaseMessage[] {
|
|
51
|
+
return stored.map((item) => {
|
|
52
|
+
const content = item.content as MessageContent;
|
|
53
|
+
switch (item.type) {
|
|
54
|
+
case 'system':
|
|
55
|
+
return new SystemMessage({ content: content as string });
|
|
56
|
+
case 'ai':
|
|
57
|
+
return new AIMessage({
|
|
58
|
+
content,
|
|
59
|
+
...(item.tool_calls ? { tool_calls: item.tool_calls } : {}),
|
|
60
|
+
});
|
|
61
|
+
case 'tool':
|
|
62
|
+
return new ToolMessage({
|
|
63
|
+
content: content as string,
|
|
64
|
+
tool_call_id: item.tool_call_id ?? '',
|
|
65
|
+
name: item.name ?? 'tool',
|
|
66
|
+
});
|
|
67
|
+
default:
|
|
68
|
+
return new HumanMessage({ content });
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function readRecord(file: string): SessionRecord | null {
|
|
74
|
+
try {
|
|
75
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8')) as Omit<SessionRecord, 'messages'> & {
|
|
76
|
+
messages: StoredMessage[];
|
|
77
|
+
};
|
|
78
|
+
return { ...parsed, messages: deserialize(parsed.messages ?? []) };
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function saveSession(record: SessionRecord): void {
|
|
85
|
+
const dir = sessionsDir();
|
|
86
|
+
mkdirSync(dir, { recursive: true });
|
|
87
|
+
writeFileSync(
|
|
88
|
+
path.join(dir, `${record.id}.json`),
|
|
89
|
+
JSON.stringify({ ...record, messages: serialize(record.messages) }, null, 2),
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** All conversations, newest first. */
|
|
94
|
+
export function listSessions(): SessionRecord[] {
|
|
95
|
+
const dir = sessionsDir();
|
|
96
|
+
if (!existsSync(dir)) return [];
|
|
97
|
+
return readdirSync(dir)
|
|
98
|
+
.filter((file) => file.endsWith('.json'))
|
|
99
|
+
.map((file) => readRecord(path.join(dir, file)))
|
|
100
|
+
.filter((record): record is SessionRecord => record !== null)
|
|
101
|
+
.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function getSession(id: string): SessionRecord | undefined {
|
|
105
|
+
const record = readRecord(path.join(sessionsDir(), `${id}.json`));
|
|
106
|
+
return record ?? undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Keyword search over titles AND message content (case-insensitive). */
|
|
110
|
+
export function searchSessions(keyword: string): SessionRecord[] {
|
|
111
|
+
const query = keyword.trim().toLowerCase();
|
|
112
|
+
if (!query) return listSessions();
|
|
113
|
+
return listSessions().filter(
|
|
114
|
+
(record) =>
|
|
115
|
+
record.title.toLowerCase().includes(query) ||
|
|
116
|
+
record.messages.some((message) =>
|
|
117
|
+
typeof message.content === 'string'
|
|
118
|
+
? message.content.toLowerCase().includes(query)
|
|
119
|
+
: JSON.stringify(message.content).toLowerCase().includes(query),
|
|
120
|
+
),
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Model-generated conversation title (≤12 chars). Returns the derived
|
|
126
|
+
* fallback when the model call fails.
|
|
127
|
+
*/
|
|
128
|
+
export async function generateTitle(
|
|
129
|
+
model: { invoke: (input: string) => Promise<{ content: unknown }> },
|
|
130
|
+
firstUserText: string,
|
|
131
|
+
firstAssistantText: string,
|
|
132
|
+
): Promise<string> {
|
|
133
|
+
const fallback = firstUserText.replace(/\s+/g, ' ').trim().slice(0, 24) || '新对话';
|
|
134
|
+
try {
|
|
135
|
+
const response = await model.invoke(
|
|
136
|
+
'为下面这段对话生成一个不超过 12 个字的中文标题,只输出标题本身,不要标点。\n' +
|
|
137
|
+
`用户:${firstUserText.slice(0, 500)}\n助手:${firstAssistantText.slice(0, 500)}`,
|
|
138
|
+
);
|
|
139
|
+
const text = (typeof response.content === 'string'
|
|
140
|
+
? response.content
|
|
141
|
+
: JSON.stringify(response.content)
|
|
142
|
+
)
|
|
143
|
+
.replace(/["“”'‘’\s]/g, '')
|
|
144
|
+
.slice(0, 16);
|
|
145
|
+
return text.length >= 2 ? text : fallback;
|
|
146
|
+
} catch {
|
|
147
|
+
return fallback;
|
|
148
|
+
}
|
|
149
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Auto-generated from package.json by scripts/sync-version.ts (npm version hook)
|
|
2
|
-
export const VERSION = '0.
|
|
2
|
+
export const VERSION = '0.4.0';
|