@trans-ai/trans-code 0.2.4 → 0.3.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.
@@ -2,7 +2,19 @@ import { Box, Text, useInput, useApp } from 'ink';
2
2
  import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
3
3
  import path from 'node:path';
4
4
  import { findCommand, getCommands, type CommandContext } from '../commands.js';
5
- import { getAvailableModels, createProviderWithKey, createProvider, setPreferredModel, type ModelId } from '../provider/provider.js';
5
+ import {
6
+ getAvailableModels,
7
+ createProvider,
8
+ setPreferredModel,
9
+ registerApiKey,
10
+ lookupApiKey,
11
+ setCustomModel,
12
+ vendorModelSpec,
13
+ vendorModels,
14
+ verifyModel,
15
+ type ModelId,
16
+ } from '../provider/provider.js';
17
+ import { loadConfig } from '../config.js';
6
18
  import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
7
19
  import { createToolSession } from '../agent/tools/index.js';
8
20
  import { getPermissionMode } from '../agent/permission.js';
@@ -18,7 +30,15 @@ interface HistoryEntry {
18
30
  output: string;
19
31
  }
20
32
 
21
- type PromptPhase = 'idle' | 'model_select' | 'model_apikey' | 'permission';
33
+ type PromptPhase =
34
+ | 'idle'
35
+ | 'model_select'
36
+ | 'model_pick'
37
+ | 'model_name'
38
+ | 'custom_baseurl'
39
+ | 'model_apikey'
40
+ | 'model_check'
41
+ | 'permission';
22
42
 
23
43
  interface REPLProps {
24
44
  ctx: CommandContext;
@@ -49,6 +69,13 @@ export default function REPL({ ctx }: REPLProps) {
49
69
  } | null>(null);
50
70
  const [pendingModel, setPendingModel] = useState<ModelId | null>(null);
51
71
  const [modelCursor, setModelCursor] = useState(0);
72
+ // Model selection flow: vendor → model → key (reused if saved) → check.
73
+ const [pickOptions, setPickOptions] = useState<string[]>([]);
74
+ const [pickCursor, setPickCursor] = useState(0);
75
+ const [pendingSpec, setPendingSpec] = useState<string | null>(null);
76
+ const [pendingDisplayName, setPendingDisplayName] = useState('');
77
+ const [keyHint, setKeyHint] = useState<string | null>(null);
78
+ const [customBaseDraft, setCustomBaseDraft] = useState('');
52
79
 
53
80
  const models = getAvailableModels();
54
81
  // Bun's scheduler can drop the render flush for updates issued from the
@@ -209,6 +236,9 @@ export default function REPL({ ctx }: REPLProps) {
209
236
  if (event.diff) {
210
237
  // Edits and writes stay visible immediately — rare and important.
211
238
  appendChatOutput(`\n⚙ ${title} ${marker}\n${renderDiff(event.diff)}`);
239
+ } else if (event.name === 'todo_write' || event.name === 'dispatch_agent') {
240
+ // Progress state and sub-agent reports: show immediately.
241
+ appendChatOutput(`\n${event.output}`);
212
242
  } else {
213
243
  bufferedLines.push(`\n⚙ ${title} ${marker}`);
214
244
  }
@@ -252,36 +282,103 @@ export default function REPL({ ctx }: REPLProps) {
252
282
  setPhase('model_select');
253
283
  }, [ctx.modelId, models]);
254
284
 
255
- const handleApiKey = useCallback((value: string) => {
256
- const apiKey = value.trim();
257
- const modelId = pendingModel!;
285
+ const maskKey = (key: string): string =>
286
+ key.length <= 8 ? '…****' : `${key.slice(0, 3)}…${key.slice(-4)}`;
258
287
 
259
- if (!apiKey) {
260
- addHistory({ input: '••••••••', output: 'API key cannot be empty.' });
261
- enterModelSelect();
262
- return;
263
- }
288
+ const beginKeyStep = useCallback(
289
+ (spec: string, displayName: string) => {
290
+ const saved = lookupApiKey(spec);
291
+ setPendingSpec(spec);
292
+ setPendingDisplayName(displayName);
293
+ setKeyHint(saved ? maskKey(saved) : null);
294
+ setPhase('model_apikey');
295
+ commitInput('');
296
+ },
297
+ [commitInput],
298
+ );
264
299
 
265
- try {
266
- createProviderWithKey(modelId, apiKey);
267
- ctx.setModelId(modelId);
268
- setPreferredModel(modelId);
269
- const found = models.find(m => m.id === modelId);
270
- addHistory({ input: '••••••••', output: `Switched to ${found?.name ?? modelId}` });
271
- } catch {
272
- addHistory({ input: '••••••••', output: 'Failed to switch model. Invalid API key.' });
273
- }
300
+ const applyModelSwitch = useCallback(
301
+ (spec: string, displayName: string, apiKey: string, checkMessage: string) => {
302
+ registerApiKey(spec.split(':')[0]!, apiKey);
303
+ ctx.setModelId(spec);
304
+ setPreferredModel(spec);
305
+ addHistory({
306
+ input: '••••••••',
307
+ output: `${checkMessage} — 已切换到 ${displayName}`,
308
+ });
309
+ setPendingSpec(null);
310
+ setPendingDisplayName('');
311
+ setKeyHint(null);
312
+ setPendingModel(null);
313
+ setPhase('idle');
314
+ dragFlush();
315
+ },
316
+ [ctx, addHistory, dragFlush],
317
+ );
318
+
319
+ const handleApiKey = useCallback(
320
+ async (value: string) => {
321
+ const spec = pendingSpec!;
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
+
330
+ if (process.env.TRANSCODE_SKIP_MODEL_CHECK === '1') {
331
+ applyModelSwitch(spec, pendingDisplayName, apiKey, '已跳过连通性测试');
332
+ return;
333
+ }
274
334
 
275
- setPendingModel(null);
276
- setPhase('idle');
277
- }, [pendingModel, ctx, addHistory, enterModelSelect, models]);
335
+ setPhase('model_check');
336
+ const result = await verifyModel(spec, apiKey);
337
+ if (result.ok) {
338
+ applyModelSwitch(spec, pendingDisplayName, apiKey, `✓ ${result.message}`);
339
+ return;
340
+ }
341
+ addHistory({
342
+ input: '••••••••',
343
+ output: `✗ 连通失败:${result.message}\n请重新输入 key(Esc 返回模型列表)`,
344
+ });
345
+ setPhase('model_apikey');
346
+ commitInput('');
347
+ dragFlush();
348
+ },
349
+ [pendingSpec, pendingDisplayName, addHistory, applyModelSwitch, commitInput, dragFlush],
350
+ );
278
351
 
279
352
  const handleSubmit = useCallback(async (raw: string) => {
280
353
  const trimmed = raw.trim();
281
354
  if (!trimmed) return;
282
355
 
283
- if (phase === 'model_apikey') {
284
- handleApiKey(trimmed);
356
+ if (phase === 'model_apikey' || phase === 'model_check') {
357
+ await handleApiKey(trimmed);
358
+ commitInput('');
359
+ return;
360
+ }
361
+
362
+ if (phase === 'custom_baseurl') {
363
+ if (!/^https?:\/\//.test(trimmed)) {
364
+ addHistory({ input: trimmed, output: '地址需以 http:// 或 https:// 开头。' });
365
+ return;
366
+ }
367
+ setCustomBaseDraft(trimmed);
368
+ setPhase('model_name');
369
+ commitInput('');
370
+ return;
371
+ }
372
+
373
+ if (phase === 'model_name') {
374
+ if (!trimmed) return;
375
+ if (pendingModel === null) {
376
+ // Custom gateway: base URL collected, now the model name.
377
+ setCustomModel({ baseUrl: customBaseDraft, model: trimmed });
378
+ beginKeyStep('custom', `custom/${trimmed}`);
379
+ } else {
380
+ beginKeyStep(vendorModelSpec(pendingModel, trimmed), `${pendingModel}/${trimmed}`);
381
+ }
285
382
  commitInput('');
286
383
  return;
287
384
  }
@@ -383,8 +480,22 @@ export default function REPL({ ctx }: REPLProps) {
383
480
  if (phase === 'model_select') {
384
481
  if (key.return) {
385
482
  const selected = models[modelCursor];
483
+ if (selected.id === 'custom') {
484
+ const saved = loadConfig().custom;
485
+ setPendingModel(null);
486
+ if (saved?.baseUrl && saved.model) {
487
+ beginKeyStep('custom', `custom/${saved.model}`);
488
+ } else {
489
+ setPhase('custom_baseurl');
490
+ commitInput('');
491
+ }
492
+ return;
493
+ }
386
494
  setPendingModel(selected.id);
387
- setPhase('model_apikey');
495
+ const options = vendorModels(selected.id);
496
+ setPickOptions(options);
497
+ setPickCursor(0);
498
+ setPhase('model_pick');
388
499
  commitInput('');
389
500
  return;
390
501
  }
@@ -399,6 +510,30 @@ export default function REPL({ ctx }: REPLProps) {
399
510
  return;
400
511
  }
401
512
 
513
+ if (phase === 'model_pick') {
514
+ const total = pickOptions.length + 1; // + "自定义模型名…"
515
+ if (key.return) {
516
+ if (pickCursor >= pickOptions.length) {
517
+ setPhase('model_name');
518
+ commitInput('');
519
+ return;
520
+ }
521
+ const modelName = pickOptions[pickCursor]!;
522
+ beginKeyStep(vendorModelSpec(pendingModel!, modelName), `${pendingModel}/${modelName}`);
523
+ commitInput('');
524
+ return;
525
+ }
526
+ if (key.upArrow) {
527
+ setPickCursor(prev => (prev - 1 + total) % total);
528
+ return;
529
+ }
530
+ if (key.downArrow) {
531
+ setPickCursor(prev => (prev + 1) % total);
532
+ return;
533
+ }
534
+ return;
535
+ }
536
+
402
537
  // @-mention popup navigation and completion (takes precedence over
403
538
  // history navigation, tab completion and submission).
404
539
  if (phase === 'idle' && mentionActive && mentionCandidates.length > 0) {
@@ -475,12 +610,18 @@ export default function REPL({ ctx }: REPLProps) {
475
610
  });
476
611
 
477
612
  const promptLabel = phase === 'model_select'
478
- ? 'model> '
479
- : phase === 'model_apikey'
480
- ? 'apikey> '
481
- : phase === 'permission'
482
- ? 'allow?> '
483
- : '> ';
613
+ ? 'vendor> '
614
+ : phase === 'model_pick'
615
+ ? 'model> '
616
+ : phase === 'model_name'
617
+ ? pendingModel === null ? '自定义模型名> ' : '自定义模型名> '
618
+ : phase === 'custom_baseurl'
619
+ ? 'baseurl> '
620
+ : phase === 'model_apikey'
621
+ ? keyHint ? `apikey (回车沿用 ${keyHint})> ` : 'apikey> '
622
+ : phase === 'permission'
623
+ ? 'allow?> '
624
+ : '> ';
484
625
 
485
626
  return (
486
627
  <Box flexDirection="column" paddingX={1}>
@@ -534,6 +675,33 @@ export default function REPL({ ctx }: REPLProps) {
534
675
  )}
535
676
  </Box>
536
677
  ))}
678
+ <Text color="gray" dimColor>↑↓ 选择厂商 · Enter 进入模型列表</Text>
679
+ </Box>
680
+ )}
681
+
682
+ {phase === 'model_pick' && (
683
+ <Box flexDirection="column" marginLeft={2}>
684
+ {pickOptions.map((name, i) => (
685
+ <Box key={name}>
686
+ <Text color={i === pickCursor ? 'cyan' : undefined}>
687
+ {i === pickCursor ? '❯ ' : ' '}
688
+ {name}
689
+ </Text>
690
+ </Box>
691
+ ))}
692
+ <Box>
693
+ <Text color={pickCursor === pickOptions.length ? 'cyan' : 'gray'}>
694
+ {pickCursor === pickOptions.length ? '❯ ' : ' '}
695
+ 自定义模型名…
696
+ </Text>
697
+ </Box>
698
+ <Text color="gray" dimColor>↑↓ 选择模型 · Enter 确认</Text>
699
+ </Box>
700
+ )}
701
+
702
+ {phase === 'model_check' && (
703
+ <Box marginLeft={2}>
704
+ <Text dimColor>… 测试连通性({pendingDisplayName})</Text>
537
705
  </Box>
538
706
  )}
539
707
 
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.4';
2
+ export const VERSION = '0.3.0';