@trans-ai/trans-code 0.3.0 → 0.5.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/src/commands.ts CHANGED
@@ -70,6 +70,24 @@ const commands: Command[] = [
70
70
  return { output: `Permission mode switched to ${target}` };
71
71
  },
72
72
  },
73
+ {
74
+ name: 'new',
75
+ description: 'Start a new conversation',
76
+ // Intercepted by the REPL (needs messagesRef/toolSession state).
77
+ execute: () => ({ output: 'Starting a new conversation…' }),
78
+ },
79
+ {
80
+ name: 'sessions',
81
+ description: 'List/search saved conversations (optionally by keyword)',
82
+ // Intercepted by the REPL.
83
+ execute: () => ({ output: 'Listing conversations…' }),
84
+ },
85
+ {
86
+ name: 'resume',
87
+ description: 'Resume a saved conversation (/resume <序号|id|标题片段>)',
88
+ // Intercepted by the REPL.
89
+ execute: () => ({ output: 'Resuming…' }),
90
+ },
73
91
  {
74
92
  name: 'route',
75
93
  description: 'Show or set role→model routing (analysis/design/vision/…)',
@@ -0,0 +1,49 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { normalizeAutoUpdate } from './config.js';
3
+
4
+ describe('normalizeAutoUpdate', () => {
5
+ test('false disables auto-update, keeping default target and lastCheck', () => {
6
+ expect(normalizeAutoUpdate(false)).toEqual({
7
+ enabled: false,
8
+ target: 'latest',
9
+ lastCheck: 0,
10
+ });
11
+ });
12
+
13
+ test('undefined (no config) defaults to enabled', () => {
14
+ expect(normalizeAutoUpdate(undefined)).toEqual({
15
+ enabled: true,
16
+ target: 'latest',
17
+ lastCheck: 0,
18
+ });
19
+ });
20
+
21
+ test('an empty object keeps defaults (enabled, latest, 0)', () => {
22
+ expect(normalizeAutoUpdate({})).toEqual({
23
+ enabled: true,
24
+ target: 'latest',
25
+ lastCheck: 0,
26
+ });
27
+ });
28
+
29
+ test('an object preserves its fields', () => {
30
+ expect(normalizeAutoUpdate({ enabled: false, target: '0.3.0' })).toEqual({
31
+ enabled: false,
32
+ target: '0.3.0',
33
+ lastCheck: 0,
34
+ });
35
+ expect(
36
+ normalizeAutoUpdate({ enabled: true, target: '0.3.0', lastCheck: 123 }),
37
+ ).toEqual({ enabled: true, target: '0.3.0', lastCheck: 123 });
38
+ });
39
+
40
+ test('invalid values fall back to the enabled default instead of throwing', () => {
41
+ for (const raw of ['yes', 5, null, [true]]) {
42
+ expect(normalizeAutoUpdate(raw)).toEqual({
43
+ enabled: true,
44
+ target: 'latest',
45
+ lastCheck: 0,
46
+ });
47
+ }
48
+ });
49
+ });
package/src/config.ts CHANGED
@@ -21,6 +21,48 @@ export interface TranscodeConfig {
21
21
  profiles?: Record<string, ProfileConfig>;
22
22
  /** Role → profile routing (default / analysis / design / vision / …). */
23
23
  routing?: Record<string, string>;
24
+ /** Auto-update on startup: `false` disables, an object configures it. */
25
+ autoUpdate?: boolean | AutoUpdateConfig;
26
+ }
27
+
28
+ /** Raw (on-disk) shape of the autoUpdate config block. */
29
+ export interface AutoUpdateConfig {
30
+ enabled?: boolean;
31
+ /** Registry version to stay at; defaults to 'latest'. */
32
+ target?: string;
33
+ /** Epoch ms of the last registry check; internal throttle cache. */
34
+ lastCheck?: number;
35
+ }
36
+
37
+ /** Normalized form used by the updater. */
38
+ export interface NormalizedAutoUpdate {
39
+ enabled: boolean;
40
+ target: string;
41
+ lastCheck: number;
42
+ }
43
+
44
+ const DEFAULT_AUTO_UPDATE: NormalizedAutoUpdate = {
45
+ enabled: true,
46
+ target: 'latest',
47
+ lastCheck: 0,
48
+ };
49
+
50
+ /**
51
+ * Normalizes the raw autoUpdate config value. Anything unrecognizable
52
+ * (wrong type, null, arrays) falls back to the enabled default rather
53
+ * than throwing — a bad config must never break startup.
54
+ */
55
+ export function normalizeAutoUpdate(raw: unknown): NormalizedAutoUpdate {
56
+ if (raw === false) return { ...DEFAULT_AUTO_UPDATE, enabled: false };
57
+ if (raw === null || raw === undefined || typeof raw !== 'object' || Array.isArray(raw)) {
58
+ return { ...DEFAULT_AUTO_UPDATE };
59
+ }
60
+ const obj = raw as AutoUpdateConfig;
61
+ return {
62
+ enabled: typeof obj.enabled === 'boolean' ? obj.enabled : true,
63
+ target: typeof obj.target === 'string' && obj.target ? obj.target : 'latest',
64
+ lastCheck: typeof obj.lastCheck === 'number' ? obj.lastCheck : 0,
65
+ };
24
66
  }
25
67
 
26
68
  // Overridable so tests never touch the user's real ~/.transcode.json.
package/src/main.tsx CHANGED
@@ -5,6 +5,7 @@ import { type CommandContext } from './commands.js';
5
5
  import REPL from './screens/REPL.js';
6
6
  import { bannerLines } from './screens/banner.js';
7
7
  import { createKeyedStdin } from './tui/keyed-stdin.js';
8
+ import { autoUpdateNotice } from './upgrade.js';
8
9
  import { VERSION } from './version.js';
9
10
  const DEFAULT_MODEL: string = preferredModelId() ?? 'opus';
10
11
 
@@ -50,7 +51,7 @@ function App() {
50
51
  <Box flexDirection="column">
51
52
  {/* A saved model choice (from the models flow) wins over the env label */}
52
53
  <Banner modelId={modelId} cwd={cwd} envLabel={preferredModelId() ? undefined : envModelLabel()} />
53
- <REPL ctx={ctx} />
54
+ <REPL ctx={ctx} updateNotice={autoUpdateNotice()} />
54
55
  </Box>
55
56
  );
56
57
  }
@@ -0,0 +1,65 @@
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 { clearRegisteredApiKeys, listEndpointModels, registerApiKey } from './provider.js';
6
+
7
+ let configDir: string;
8
+ let server: ReturnType<typeof Bun.serve> | undefined;
9
+
10
+ beforeEach(() => {
11
+ configDir = mkdtempSync(path.join(tmpdir(), 'transcode-modellist-test-'));
12
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
13
+ clearRegisteredApiKeys();
14
+ });
15
+ afterEach(async () => {
16
+ delete process.env.TRANSCODE_CONFIG_PATH;
17
+ rmSync(configDir, { recursive: true, force: true });
18
+ await server?.stop?.();
19
+ server = undefined;
20
+ });
21
+
22
+ function stubModelsEndpoint(ids: string[]): string {
23
+ server = Bun.serve({
24
+ port: 0,
25
+ fetch: () =>
26
+ new Response(JSON.stringify({ object: 'list', data: ids.map((id) => ({ id })) }), {
27
+ headers: { 'content-type': 'application/json' },
28
+ }),
29
+ });
30
+ return `http://localhost:${server.port}/v1`;
31
+ }
32
+
33
+ describe('listEndpointModels', () => {
34
+ test('fetches the live model list from the endpoint', async () => {
35
+ const baseUrl = stubModelsEndpoint(['glm-5.1', 'glm-4.6', 'glm-5.3-flash']);
36
+ const { saveConfig } = await import('../config.js');
37
+ saveConfig({
38
+ apiKeys: { custom: 'k' },
39
+ profiles: { myhub: { baseUrl, model: 'glm-4.6', keyId: 'custom' } },
40
+ });
41
+
42
+ const models = await listEndpointModels('myhub');
43
+ expect(models).toEqual(['glm-4.6', 'glm-5.1', 'glm-5.3-flash']); // sorted
44
+ });
45
+
46
+ test('override form queries an unsaved custom gateway with its key', async () => {
47
+ const baseUrl = stubModelsEndpoint(['m1', 'm2']);
48
+ const models = await listEndpointModels('', { baseUrl, apiKey: 'k' });
49
+ expect(models).toEqual(['m1', 'm2']);
50
+ });
51
+
52
+ test('returns an empty list on failure so callers can fall back', async () => {
53
+ registerApiKey('deepseek', 'k');
54
+ const models = await listEndpointModels('deepseek'); // real URL, no network in test env → fails fast? may hit network…
55
+ // Use an unreachable local port instead for determinism.
56
+ const { saveConfig } = await import('../config.js');
57
+ saveConfig({
58
+ apiKeys: { custom: 'k' },
59
+ profiles: { dead: { baseUrl: 'http://127.0.0.1:1/v1', model: 'x', keyId: 'custom' } },
60
+ });
61
+ const none = await listEndpointModels('dead');
62
+ expect(none).toEqual([]);
63
+ void models;
64
+ });
65
+ });
@@ -68,6 +68,12 @@ describe('vendor model lists', () => {
68
68
  expect(glm).toContain('glm-4.5');
69
69
  });
70
70
 
71
+ test('deepseek lists the current model line', () => {
72
+ const deepseek = vendorModels('deepseek');
73
+ expect(deepseek).toContain('deepseek-v4-pro');
74
+ expect(deepseek).toContain('deepseek-flash');
75
+ });
76
+
71
77
  test('spec mapping routes registry ids to provider prefixes', () => {
72
78
  expect(vendorModelSpec('deepseek', 'deepseek-reasoner')).toBe('deepseek:deepseek-reasoner');
73
79
  expect(vendorModelSpec('opus', 'claude-sonnet-4')).toBe('anthropic:claude-sonnet-4');
@@ -87,7 +87,7 @@ const MODEL_REGISTRY: Record<ModelId, ModelConfig> = {
87
87
  const VENDOR_MODELS: Partial<Record<ModelId, string[]>> = {
88
88
  opus: ['claude-opus-4-20250514', 'claude-sonnet-4-20250514'],
89
89
  gpt: ['gpt-4o', 'gpt-4o-mini'],
90
- deepseek: ['deepseek-chat', 'deepseek-reasoner'],
90
+ deepseek: ['deepseek-v4-pro', 'deepseek-flash'],
91
91
  glm: ['glm-4.6', 'glm-4.5', 'glm-4.5-air', 'glm-4-flash'],
92
92
  glmc: ['glm-4.6', 'glm-4.5'],
93
93
  minimax: ['MiniMax-Text-01'],
@@ -581,6 +581,40 @@ export function getRouting(): Record<string, string> {
581
581
  return { ...(loadConfig().routing ?? {}) };
582
582
  }
583
583
 
584
+ /**
585
+ * Live model list from an endpoint's OpenAI-compatible GET /models, so the
586
+ * /models picker shows what the gateway actually serves (Zhipu's coding
587
+ * endpoint, for one, maps old names to newer generations). Empty list on
588
+ * any failure — callers fall back to the curated list. The override form
589
+ * queries an in-progress custom gateway before it is saved.
590
+ */
591
+ export async function listEndpointModels(
592
+ specOrId: string,
593
+ override?: { baseUrl: string; apiKey?: string },
594
+ ): Promise<string[]> {
595
+ try {
596
+ const baseUrl = (override?.baseUrl ?? baseUrlFor(resolveModel(specOrId)))?.replace(/\/$/, '');
597
+ if (!baseUrl) return [];
598
+ const apiKey = override?.apiKey ?? lookupApiKey(resolveModel(specOrId).id);
599
+ const response = await Promise.race([
600
+ fetch(`${baseUrl}/models`, {
601
+ headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
602
+ }),
603
+ new Promise<Response>((_, reject) =>
604
+ setTimeout(() => reject(new Error('timeout')), 5_000),
605
+ ),
606
+ ]);
607
+ if (!response.ok) return [];
608
+ const body = (await response.json()) as { data?: Array<{ id?: string }> };
609
+ const ids = (body.data ?? [])
610
+ .map((entry) => entry?.id)
611
+ .filter((id): id is string => typeof id === 'string' && id.length > 0);
612
+ return [...new Set(ids)].sort();
613
+ } catch {
614
+ return [];
615
+ }
616
+ }
617
+
584
618
  /** Set (or clear with "-") a role's profile. */
585
619
  export function setRouting(role: string, profile: string): void {
586
620
  if (!role.trim()) throw new Error('Role name cannot be empty.');