@trans-ai/trans-code 0.2.3 → 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
@@ -189,6 +216,11 @@ export default function REPL({ ctx }: REPLProps) {
189
216
  if (event.type === 'text') {
190
217
  appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
191
218
  lastWasTool = false;
219
+ } else if (event.type === 'max_turns_reached') {
220
+ appendChatOutput(
221
+ `\n⚠ 已达轮次上限(${event.maxTurns}),任务未完成。输入"继续"接着做,或调大 TRANSCODE_MAX_TURNS。`,
222
+ );
223
+ lastWasTool = true;
192
224
  } else if (event.type === 'tool_call') {
193
225
  titlesById.set(event.toolCallId, event.title);
194
226
  pendingCalls++;
@@ -204,6 +236,9 @@ export default function REPL({ ctx }: REPLProps) {
204
236
  if (event.diff) {
205
237
  // Edits and writes stay visible immediately — rare and important.
206
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}`);
207
242
  } else {
208
243
  bufferedLines.push(`\n⚙ ${title} ${marker}`);
209
244
  }
@@ -247,36 +282,103 @@ export default function REPL({ ctx }: REPLProps) {
247
282
  setPhase('model_select');
248
283
  }, [ctx.modelId, models]);
249
284
 
250
- const handleApiKey = useCallback((value: string) => {
251
- const apiKey = value.trim();
252
- const modelId = pendingModel!;
285
+ const maskKey = (key: string): string =>
286
+ key.length <= 8 ? '…****' : `${key.slice(0, 3)}…${key.slice(-4)}`;
253
287
 
254
- if (!apiKey) {
255
- addHistory({ input: '••••••••', output: 'API key cannot be empty.' });
256
- enterModelSelect();
257
- return;
258
- }
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
+ );
259
299
 
260
- try {
261
- createProviderWithKey(modelId, apiKey);
262
- ctx.setModelId(modelId);
263
- setPreferredModel(modelId);
264
- const found = models.find(m => m.id === modelId);
265
- addHistory({ input: '••••••••', output: `Switched to ${found?.name ?? modelId}` });
266
- } catch {
267
- addHistory({ input: '••••••••', output: 'Failed to switch model. Invalid API key.' });
268
- }
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
+ );
269
318
 
270
- setPendingModel(null);
271
- setPhase('idle');
272
- }, [pendingModel, ctx, addHistory, enterModelSelect, models]);
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
+ }
334
+
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
+ );
273
351
 
274
352
  const handleSubmit = useCallback(async (raw: string) => {
275
353
  const trimmed = raw.trim();
276
354
  if (!trimmed) return;
277
355
 
278
- if (phase === 'model_apikey') {
279
- 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
+ }
280
382
  commitInput('');
281
383
  return;
282
384
  }
@@ -378,8 +480,22 @@ export default function REPL({ ctx }: REPLProps) {
378
480
  if (phase === 'model_select') {
379
481
  if (key.return) {
380
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
+ }
381
494
  setPendingModel(selected.id);
382
- setPhase('model_apikey');
495
+ const options = vendorModels(selected.id);
496
+ setPickOptions(options);
497
+ setPickCursor(0);
498
+ setPhase('model_pick');
383
499
  commitInput('');
384
500
  return;
385
501
  }
@@ -394,6 +510,30 @@ export default function REPL({ ctx }: REPLProps) {
394
510
  return;
395
511
  }
396
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
+
397
537
  // @-mention popup navigation and completion (takes precedence over
398
538
  // history navigation, tab completion and submission).
399
539
  if (phase === 'idle' && mentionActive && mentionCandidates.length > 0) {
@@ -470,12 +610,18 @@ export default function REPL({ ctx }: REPLProps) {
470
610
  });
471
611
 
472
612
  const promptLabel = phase === 'model_select'
473
- ? 'model> '
474
- : phase === 'model_apikey'
475
- ? 'apikey> '
476
- : phase === 'permission'
477
- ? 'allow?> '
478
- : '> ';
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
+ : '> ';
479
625
 
480
626
  return (
481
627
  <Box flexDirection="column" paddingX={1}>
@@ -529,6 +675,33 @@ export default function REPL({ ctx }: REPLProps) {
529
675
  )}
530
676
  </Box>
531
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>
532
705
  </Box>
533
706
  )}
534
707
 
@@ -0,0 +1,21 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { bannerLines } from './banner.js';
3
+
4
+ describe('bannerLines', () => {
5
+ test('renders a closed rectangle with aligned sides', () => {
6
+ const lines = bannerLines('T R A N S C O D E · Multi-model Agent').split('\n');
7
+ expect(lines.length).toBe(3);
8
+ expect(lines[0]!.startsWith('┌')).toBe(true);
9
+ expect(lines[0]!.endsWith('┐')).toBe(true);
10
+ expect(lines[1]!.startsWith('│')).toBe(true);
11
+ expect(lines[1]!.endsWith('│')).toBe(true);
12
+ expect(lines[2]!.startsWith('└')).toBe(true);
13
+ expect(lines[2]!.endsWith('┘')).toBe(true);
14
+
15
+ // Every line must have the same display width for the box to close.
16
+ const width = (line: string) => [...line].length;
17
+ expect(width(lines[1]!)).toBe(width(lines[0]!));
18
+ expect(width(lines[2]!)).toBe(width(lines[0]!));
19
+ expect(lines[1]!).toContain('T R A N S C O D E');
20
+ });
21
+ });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Closed ASCII banner: the border width is derived from the title so the
3
+ * rectangle always lines up, whatever the title text.
4
+ */
5
+ export function bannerLines(title: string, padding = 2): string {
6
+ const inner = ' '.repeat(padding) + title + ' '.repeat(padding);
7
+ const border = '─'.repeat([...inner].length);
8
+ return `┌${border}┐\n│${inner}│\n└${border}┘`;
9
+ }
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.3';
2
+ export const VERSION = '0.3.0';