@trans-ai/trans-code 0.2.4 → 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 +68 -17
- package/package.json +1 -1
- package/src/acp/session.ts +4 -1
- package/src/agent/loop.test.ts +337 -1
- package/src/agent/loop.ts +166 -2
- package/src/agent/system-prompt.test.ts +24 -1
- package/src/agent/system-prompt.ts +21 -0
- package/src/agent/tools/ask-model.test.ts +54 -0
- package/src/agent/tools/ask-model.ts +44 -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 +157 -0
- package/src/agent/tools/dispatch.ts +151 -0
- package/src/agent/tools/files.test.ts +96 -0
- package/src/agent/tools/files.ts +111 -29
- package/src/agent/tools/fs-utils.ts +40 -0
- package/src/agent/tools/index.ts +29 -2
- package/src/agent/tools/powershell.test.ts +61 -0
- package/src/agent/tools/read-only.ts +16 -0
- package/src/agent/tools/search.test.ts +55 -1
- package/src/agent/tools/search.ts +56 -8
- package/src/agent/tools/session.ts +21 -0
- package/src/agent/tools/shell-paths.test.ts +65 -0
- package/src/agent/tools/shell-paths.ts +19 -0
- package/src/agent/tools/todo.test.ts +54 -0
- package/src/agent/tools/todo.ts +47 -0
- package/src/agent/tools/types.ts +15 -1
- package/src/cli.ts +2 -0
- package/src/commands.ts +55 -2
- package/src/config.ts +21 -3
- package/src/main.tsx +4 -4
- package/src/provider/model-list.test.ts +65 -0
- package/src/provider/provider.test.ts +117 -0
- package/src/provider/provider.ts +312 -34
- package/src/provider/routing.test.ts +109 -0
- package/src/screens/REPL.tsx +432 -35
- package/src/sessions/store.test.ts +91 -0
- package/src/sessions/store.ts +149 -0
- package/src/version.ts +1 -1
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
|
|
3
|
+
/** One step of the model-maintained task list (todo_write tool). */
|
|
4
|
+
export interface TodoItem {
|
|
5
|
+
content: string;
|
|
6
|
+
status: 'pending' | 'in_progress' | 'completed';
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** A background shell task started via bash run_in_background. */
|
|
10
|
+
export interface BackgroundTask {
|
|
11
|
+
id: string;
|
|
12
|
+
pid: number;
|
|
13
|
+
logPath: string;
|
|
14
|
+
command: string;
|
|
15
|
+
startedAt: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
3
18
|
/**
|
|
4
19
|
* State that persists across tool calls within one conversation/session:
|
|
5
20
|
* the shell's current working directory (so `cd` survives between bash
|
|
@@ -15,6 +30,10 @@ export interface ToolSession {
|
|
|
15
30
|
shellSnapshot?: Promise<string | undefined>;
|
|
16
31
|
/** Absolute paths of files the model has read (or written) this session. */
|
|
17
32
|
readFileState: Set<string>;
|
|
33
|
+
/** Current task list, owned by the todo_write tool. */
|
|
34
|
+
todos: TodoItem[];
|
|
35
|
+
/** Background shell tasks (bash run_in_background), keyed by id. */
|
|
36
|
+
bgTasks: Map<string, BackgroundTask>;
|
|
18
37
|
}
|
|
19
38
|
|
|
20
39
|
export function createToolSession(rootCwd: string): ToolSession {
|
|
@@ -23,6 +42,8 @@ export function createToolSession(rootCwd: string): ToolSession {
|
|
|
23
42
|
cwd: absolute,
|
|
24
43
|
rootCwd: absolute,
|
|
25
44
|
readFileState: new Set<string>(),
|
|
45
|
+
todos: [],
|
|
46
|
+
bgTasks: new Map(),
|
|
26
47
|
};
|
|
27
48
|
}
|
|
28
49
|
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { fromPosixPath, toPosixPath } from './shell-paths.js';
|
|
3
|
+
import { detectShellWith, killTreeCommand } from './bash.js';
|
|
4
|
+
|
|
5
|
+
describe('path conversion', () => {
|
|
6
|
+
test('windows → posix drive paths', () => {
|
|
7
|
+
expect(toPosixPath('C:\\Users\\lindaw\\AppData\\Local\\Temp')).toBe(
|
|
8
|
+
'/c/Users/lindaw/AppData/Local/Temp',
|
|
9
|
+
);
|
|
10
|
+
expect(toPosixPath('D:/data/x')).toBe('/d/data/x');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test('posix paths pass through untouched', () => {
|
|
14
|
+
expect(toPosixPath('/var/folders/abc')).toBe('/var/folders/abc');
|
|
15
|
+
expect(toPosixPath('/tmp')).toBe('/tmp');
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('posix → windows drive paths (normalized uppercase)', () => {
|
|
19
|
+
expect(fromPosixPath('/c/Users/lindaw')).toBe('C:\\Users\\lindaw');
|
|
20
|
+
expect(fromPosixPath('/d/data/x')).toBe('D:\\data\\x');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('non-drive posix paths pass through', () => {
|
|
24
|
+
expect(fromPosixPath('/var/folders/abc')).toBe('/var/folders/abc');
|
|
25
|
+
expect(fromPosixPath('/usr/bin/env')).toBe('/usr/bin/env');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('roundtrips', () => {
|
|
29
|
+
const win = 'C:\\repo\\trans-once';
|
|
30
|
+
expect(fromPosixPath(toPosixPath(win))).toBe(win);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
describe('detectShellWith', () => {
|
|
35
|
+
test('TRANSCODE_SHELL override wins everywhere', () => {
|
|
36
|
+
expect(
|
|
37
|
+
detectShellWith('win32', () => false, { TRANSCODE_SHELL: 'C:\\sh\\pwsh.exe' }),
|
|
38
|
+
).toBe('C:\\sh\\pwsh.exe');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('SHELL env is used when it is bash/zsh', () => {
|
|
42
|
+
expect(detectShellWith('linux', () => false, { SHELL: '/usr/bin/zsh' })).toBe('/usr/bin/zsh');
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('win32 probes Git Bash, then PowerShell, before the POSIX fallback', () => {
|
|
46
|
+
expect(detectShellWith('win32', (p) => p === 'C:\\Program Files\\Git\\bin\\bash.exe', {})).toBe(
|
|
47
|
+
'C:\\Program Files\\Git\\bin\\bash.exe',
|
|
48
|
+
);
|
|
49
|
+
// No Git Bash and no pwsh on disk → Windows PowerShell via PATH.
|
|
50
|
+
expect(detectShellWith('win32', () => false, {})).toBe('powershell.exe');
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
describe('killTreeCommand', () => {
|
|
55
|
+
test('win32 uses taskkill /T /F', () => {
|
|
56
|
+
const command = killTreeCommand(4242, 'win32');
|
|
57
|
+
expect(command?.file).toBe('taskkill');
|
|
58
|
+
expect(command?.args).toEqual(['/pid', '4242', '/T', '/F']);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('posix uses the process-group kill path (no command)', () => {
|
|
62
|
+
expect(killTreeCommand(4242, 'darwin')).toBeNull();
|
|
63
|
+
expect(killTreeCommand(4242, 'linux')).toBeNull();
|
|
64
|
+
});
|
|
65
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows ↔ Git-Bash (MSYS) path conversion. Git Bash accepts both forms
|
|
3
|
+
* for arguments, but `pwd -P` outputs POSIX paths while Node APIs need
|
|
4
|
+
* native Windows ones — every boundary converts explicitly.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** C:\a\b or C:/a/b → /c/a/b ; already-POSIX paths pass through. */
|
|
8
|
+
export function toPosixPath(input: string): string {
|
|
9
|
+
const drive = /^([a-zA-Z]):[\\/](.*)$/.exec(input);
|
|
10
|
+
if (!drive) return input;
|
|
11
|
+
return `/${drive[1]!.toLowerCase()}/${drive[2]!.replace(/\\/g, '/')}`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** /c/a/b → C:\a\b (drive letter uppercased) ; non-drive paths pass through. */
|
|
15
|
+
export function fromPosixPath(input: string): string {
|
|
16
|
+
const drive = /^\/([a-zA-Z])\/(.*)$/.exec(input);
|
|
17
|
+
if (!drive) return input;
|
|
18
|
+
return `${drive[1]!.toUpperCase()}:\\${drive[2]!.replace(/\//g, '\\')}`;
|
|
19
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { findAgentTool } from './index.js';
|
|
4
|
+
import { createToolSession } from './session.js';
|
|
5
|
+
import { todoWriteTool, type TodoItem } from './todo.js';
|
|
6
|
+
|
|
7
|
+
describe('todo_write', () => {
|
|
8
|
+
test('is registered in the default tool set', () => {
|
|
9
|
+
expect(findAgentTool('todo_write')).toBeDefined();
|
|
10
|
+
expect(todoWriteTool.isMutating).toBe(false);
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test('replaces the whole list and returns a status checklist', async () => {
|
|
14
|
+
const session = createToolSession('/tmp');
|
|
15
|
+
const todos: TodoItem[] = [
|
|
16
|
+
{ content: '调研仓库结构', status: 'completed' },
|
|
17
|
+
{ content: '起草 README 方案', status: 'in_progress' },
|
|
18
|
+
{ content: '写入 README', status: 'pending' },
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
const output = await todoWriteTool.execute(
|
|
22
|
+
{ todos },
|
|
23
|
+
{ cwd: '/tmp', session },
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
expect(session.todos).toEqual(todos);
|
|
27
|
+
expect(output).toContain('[x]');
|
|
28
|
+
expect(output).toContain('[~]');
|
|
29
|
+
expect(output).toContain('[ ]');
|
|
30
|
+
expect(output).toContain('调研仓库结构');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('reports completion when everything is done', async () => {
|
|
34
|
+
const session = createToolSession('/tmp');
|
|
35
|
+
const output = await todoWriteTool.execute(
|
|
36
|
+
{ todos: [{ content: 'a', status: 'completed' }, { content: 'b', status: 'completed' }] },
|
|
37
|
+
{ cwd: '/tmp', session },
|
|
38
|
+
);
|
|
39
|
+
expect(output).toMatch(/all complete/i);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('rejects unknown status values via the schema', () => {
|
|
43
|
+
const parsed = todoWriteTool.schema.safeParse({
|
|
44
|
+
todos: [{ content: 'a', status: 'bogus' }],
|
|
45
|
+
});
|
|
46
|
+
expect(parsed.success).toBe(false);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('schema matches the OpenAI nullable-optional convention', () => {
|
|
50
|
+
const shape = todoWriteTool.schema.shape;
|
|
51
|
+
void z;
|
|
52
|
+
expect(Object.keys(shape)).toEqual(['todos']);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { AgentTool } from './types.js';
|
|
3
|
+
import type { TodoItem } from './session.js';
|
|
4
|
+
|
|
5
|
+
const STATUS_MARK: Record<TodoItem['status'], string> = {
|
|
6
|
+
pending: '[ ]',
|
|
7
|
+
in_progress: '[~]',
|
|
8
|
+
completed: '[x]',
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export const todoWriteTool: AgentTool = {
|
|
12
|
+
name: 'todo_write',
|
|
13
|
+
description:
|
|
14
|
+
'Create or replace the task todo list. Use it for any task with 3 or more steps: write the ' +
|
|
15
|
+
'list BEFORE you start, keep exactly one step in_progress at a time, mark steps completed ' +
|
|
16
|
+
'immediately after finishing them, and update the list as plans change. ' +
|
|
17
|
+
'This keeps you on the deliverable instead of endless exploration. ' +
|
|
18
|
+
'Each call replaces the entire list. Do not use it for single-step tasks.',
|
|
19
|
+
kind: 'think',
|
|
20
|
+
isMutating: false,
|
|
21
|
+
schema: z.object({
|
|
22
|
+
todos: z
|
|
23
|
+
.array(
|
|
24
|
+
z.object({
|
|
25
|
+
content: z.string().min(1).describe('Short step description'),
|
|
26
|
+
status: z.enum(['pending', 'in_progress', 'completed']).describe('Step status'),
|
|
27
|
+
}),
|
|
28
|
+
)
|
|
29
|
+
.describe('The full todo list (replaces the previous one)'),
|
|
30
|
+
}),
|
|
31
|
+
title: () => 'todos',
|
|
32
|
+
async execute(input, ctx) {
|
|
33
|
+
const todos = (input.todos as TodoItem[]).map((item) => ({
|
|
34
|
+
content: String(item.content),
|
|
35
|
+
status: item.status,
|
|
36
|
+
}));
|
|
37
|
+
ctx.session.todos = todos;
|
|
38
|
+
|
|
39
|
+
if (todos.length === 0) return 'Todo list cleared.';
|
|
40
|
+
|
|
41
|
+
const lines = todos.map(
|
|
42
|
+
(item, index) => `${STATUS_MARK[item.status]} ${index + 1}. ${item.content}`,
|
|
43
|
+
);
|
|
44
|
+
const allDone = todos.every((item) => item.status === 'completed');
|
|
45
|
+
return `${lines.join('\n')}${allDone ? '\n(all complete)' : ''}`;
|
|
46
|
+
},
|
|
47
|
+
};
|
package/src/agent/tools/types.ts
CHANGED
|
@@ -18,13 +18,25 @@ export interface ToolContext {
|
|
|
18
18
|
signal?: AbortSignal;
|
|
19
19
|
/** Session-scoped state shared across tool calls (shell cwd, read files). */
|
|
20
20
|
session: ToolSession;
|
|
21
|
+
/** Forwarded permission asker, so nested agents respect the same gate. */
|
|
22
|
+
requestPermission?: (request: {
|
|
23
|
+
toolCallId: string;
|
|
24
|
+
name: string;
|
|
25
|
+
title: string;
|
|
26
|
+
kind: ToolKind;
|
|
27
|
+
input: Record<string, unknown>;
|
|
28
|
+
}) => Promise<boolean>;
|
|
29
|
+
/** Event sink for nested agent progress (dispatch_agent forwards here). */
|
|
30
|
+
emit?: (event: { type: 'tool_call'; [key: string]: unknown }) => void;
|
|
21
31
|
}
|
|
22
32
|
|
|
23
|
-
/** Rich execute result: model-facing output plus
|
|
33
|
+
/** Rich execute result: model-facing output plus optional extras. */
|
|
24
34
|
export interface ToolOutput {
|
|
25
35
|
output: string;
|
|
26
36
|
/** Unified diff text for TUI rendering; never sent to the model. */
|
|
27
37
|
diff?: string;
|
|
38
|
+
/** Base64 images sent to the model as multimodal content blocks. */
|
|
39
|
+
images?: Array<{ data: string; mediaType: string }>;
|
|
28
40
|
}
|
|
29
41
|
|
|
30
42
|
export interface AgentTool {
|
|
@@ -44,4 +56,6 @@ export interface InvokeResult {
|
|
|
44
56
|
output: string;
|
|
45
57
|
/** Unified diff text for UI rendering, when the tool produced one. */
|
|
46
58
|
diff?: string;
|
|
59
|
+
/** Base64 images for multimodal-capable models. */
|
|
60
|
+
images?: Array<{ data: string; mediaType: string }>;
|
|
47
61
|
}
|
package/src/cli.ts
CHANGED
|
@@ -15,6 +15,8 @@ Environment:
|
|
|
15
15
|
TRANSCODE_PERMISSION_MODE ask | auto | readonly (default: ask in ACP mode;
|
|
16
16
|
switch at runtime in the REPL with /mode)
|
|
17
17
|
TRANSCODE_MAX_TURNS Agent tool-call turn cap (default: 200)
|
|
18
|
+
TRANSCODE_SHELL Override the shell used by the bash tool
|
|
19
|
+
(Windows: Git Bash is auto-detected)
|
|
18
20
|
ANTHROPIC_API_KEY / OPENAI_API_KEY / DEEPSEEK_API_KEY / ... provider keys
|
|
19
21
|
|
|
20
22
|
Examples:
|
package/src/commands.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import type { ModelId } from './provider/provider.js';
|
|
2
2
|
import { getAvailableModels } from './provider/provider.js';
|
|
3
3
|
import { getPermissionMode, PERMISSION_MODES, setPermissionMode } from './agent/permission.js';
|
|
4
|
+
import { getRouting, resolveRole, setRouting } from './provider/provider.js';
|
|
4
5
|
|
|
5
6
|
export interface CommandContext {
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
/** Registry id (deepseek) or provider:model spec (deepseek:deepseek-reasoner). */
|
|
8
|
+
modelId: string;
|
|
9
|
+
setModelId: (id: string) => void;
|
|
8
10
|
clearHistory: () => void;
|
|
9
11
|
}
|
|
10
12
|
|
|
@@ -68,6 +70,57 @@ const commands: Command[] = [
|
|
|
68
70
|
return { output: `Permission mode switched to ${target}` };
|
|
69
71
|
},
|
|
70
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
|
+
},
|
|
91
|
+
{
|
|
92
|
+
name: 'route',
|
|
93
|
+
description: 'Show or set role→model routing (analysis/design/vision/…)',
|
|
94
|
+
execute: (args) => {
|
|
95
|
+
if (args.length === 0) {
|
|
96
|
+
const routing = getRouting();
|
|
97
|
+
const lines = Object.entries(routing).map(([role, profile]) => {
|
|
98
|
+
const resolved = resolveRole(role);
|
|
99
|
+
return ` ${role.padEnd(10)} → ${profile}${resolved ? ` (${resolved.model})` : ' ⚠ 未解析'}`;
|
|
100
|
+
});
|
|
101
|
+
return {
|
|
102
|
+
output:
|
|
103
|
+
`Role routing:\n${lines.length ? lines.join('\n') : ' (none)'}\n` +
|
|
104
|
+
'Usage: /route <role> <profile|-> — e.g. /route analysis glmc ; "-" removes the role',
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const [role, profile] = args;
|
|
108
|
+
if (!role || !profile) {
|
|
109
|
+
return { output: 'Usage: /route <role> <profile|->' };
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
setRouting(role, profile);
|
|
113
|
+
return {
|
|
114
|
+
output:
|
|
115
|
+
profile === '-'
|
|
116
|
+
? `Role "${role}" removed.`
|
|
117
|
+
: `Role "${role}" → ${profile}`,
|
|
118
|
+
};
|
|
119
|
+
} catch (error) {
|
|
120
|
+
return { output: (error as Error).message };
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
},
|
|
71
124
|
{
|
|
72
125
|
name: 'clear',
|
|
73
126
|
description: 'Clear screen',
|
package/src/config.ts
CHANGED
|
@@ -2,16 +2,34 @@ import { readFileSync, writeFileSync } from 'node:fs';
|
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
|
|
5
|
+
/** A named model endpoint: model id → {address, model name, credential}. */
|
|
6
|
+
export interface ProfileConfig {
|
|
7
|
+
baseUrl: string;
|
|
8
|
+
model: string;
|
|
9
|
+
/** Key store id this profile uses (e.g. "glm" for both zhipu endpoints). */
|
|
10
|
+
keyId?: string;
|
|
11
|
+
/** Fallback environment variable for the credential. */
|
|
12
|
+
envKey?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
5
15
|
export interface TranscodeConfig {
|
|
6
16
|
model?: string;
|
|
7
17
|
apiKeys?: Record<string, string>;
|
|
18
|
+
/** Custom OpenAI-compatible gateway chosen in the /models flow. */
|
|
19
|
+
custom?: { baseUrl: string; model: string };
|
|
20
|
+
/** User-defined model profiles; override built-in registry ids by name. */
|
|
21
|
+
profiles?: Record<string, ProfileConfig>;
|
|
22
|
+
/** Role → profile routing (default / analysis / design / vision / …). */
|
|
23
|
+
routing?: Record<string, string>;
|
|
8
24
|
}
|
|
9
25
|
|
|
10
|
-
|
|
26
|
+
// Overridable so tests never touch the user's real ~/.transcode.json.
|
|
27
|
+
const configPath = (): string =>
|
|
28
|
+
process.env.TRANSCODE_CONFIG_PATH ?? join(homedir(), '.transcode.json');
|
|
11
29
|
|
|
12
30
|
export function loadConfig(): TranscodeConfig {
|
|
13
31
|
try {
|
|
14
|
-
const parsed = JSON.parse(readFileSync(
|
|
32
|
+
const parsed = JSON.parse(readFileSync(configPath(), 'utf8'));
|
|
15
33
|
if (parsed && typeof parsed === 'object') return parsed as TranscodeConfig;
|
|
16
34
|
} catch {
|
|
17
35
|
// missing or invalid — treat as empty
|
|
@@ -20,5 +38,5 @@ export function loadConfig(): TranscodeConfig {
|
|
|
20
38
|
}
|
|
21
39
|
|
|
22
40
|
export function saveConfig(config: TranscodeConfig): void {
|
|
23
|
-
writeFileSync(
|
|
41
|
+
writeFileSync(configPath(), JSON.stringify(config, null, 2) + '\n');
|
|
24
42
|
}
|
package/src/main.tsx
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { render, Box, Text } from 'ink';
|
|
2
2
|
import { useState } from 'react';
|
|
3
|
-
import { envModelLabel, getAvailableModels, preferredModelId
|
|
3
|
+
import { envModelLabel, getAvailableModels, preferredModelId } from './provider/provider.js';
|
|
4
4
|
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
8
|
import { VERSION } from './version.js';
|
|
9
|
-
const DEFAULT_MODEL:
|
|
9
|
+
const DEFAULT_MODEL: string = preferredModelId() ?? 'opus';
|
|
10
10
|
|
|
11
|
-
function Banner({ modelId, cwd, envLabel }: { modelId:
|
|
11
|
+
function Banner({ modelId, cwd, envLabel }: { modelId: string; cwd: string; envLabel?: string }) {
|
|
12
12
|
const models = getAvailableModels();
|
|
13
13
|
const current = models.find(m => m.id === modelId);
|
|
14
14
|
|
|
@@ -37,7 +37,7 @@ function Banner({ modelId, cwd, envLabel }: { modelId: ModelId; cwd: string; env
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
function App() {
|
|
40
|
-
const [modelId, setModelId] = useState<
|
|
40
|
+
const [modelId, setModelId] = useState<string>(DEFAULT_MODEL);
|
|
41
41
|
const cwd = process.cwd();
|
|
42
42
|
|
|
43
43
|
const ctx: CommandContext = {
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,117 @@
|
|
|
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 {
|
|
6
|
+
clearRegisteredApiKeys,
|
|
7
|
+
createModel,
|
|
8
|
+
getAvailableModels,
|
|
9
|
+
lookupApiKey,
|
|
10
|
+
registerApiKey,
|
|
11
|
+
resolveModel,
|
|
12
|
+
setCustomModel,
|
|
13
|
+
vendorModelSpec,
|
|
14
|
+
vendorModels,
|
|
15
|
+
verifyModel,
|
|
16
|
+
} from './provider.js';
|
|
17
|
+
|
|
18
|
+
let configDir: string;
|
|
19
|
+
beforeEach(() => {
|
|
20
|
+
configDir = mkdtempSync(path.join(tmpdir(), 'transcode-provider-test-'));
|
|
21
|
+
process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
|
|
22
|
+
clearRegisteredApiKeys();
|
|
23
|
+
});
|
|
24
|
+
afterEach(() => {
|
|
25
|
+
delete process.env.TRANSCODE_CONFIG_PATH;
|
|
26
|
+
delete process.env.TRANSCODE_MODEL;
|
|
27
|
+
rmSync(configDir, { recursive: true, force: true });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
describe('GLM Coding Plan preset', () => {
|
|
31
|
+
test('resolves the glmc registry id to the coding endpoint', () => {
|
|
32
|
+
const resolved = resolveModel('glmc');
|
|
33
|
+
expect(resolved.id).toBe('glmc');
|
|
34
|
+
expect(resolved.baseUrl).toBe('https://open.bigmodel.cn/api/coding/paas/v4');
|
|
35
|
+
expect(resolved.envKey).toBe('GLM_API_KEY');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('the glmc:MODEL spec overrides the model name but keeps the coding endpoint', () => {
|
|
39
|
+
const resolved = resolveModel('glmc:glm-4.5');
|
|
40
|
+
expect(resolved.model).toBe('glm-4.5');
|
|
41
|
+
expect(resolved.baseUrl).toBe('https://open.bigmodel.cn/api/coding/paas/v4');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('createModel wires the coding base URL into the client config', () => {
|
|
45
|
+
registerApiKey('glmc', 'test-key');
|
|
46
|
+
const provider = createModel('glmc');
|
|
47
|
+
expect(provider.config.baseUrl).toContain('/api/coding/');
|
|
48
|
+
expect(provider.config.model).toBe('glm-4.6');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('appears in the model list for /models', () => {
|
|
52
|
+
const entry = getAvailableModels().find((model) => model.id === 'glmc');
|
|
53
|
+
expect(entry?.name).toContain('Coding');
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe('vendor model lists', () => {
|
|
58
|
+
test('every vendor exposes at least one curated model', () => {
|
|
59
|
+
for (const model of getAvailableModels()) {
|
|
60
|
+
if (model.id === 'custom') continue; // empty until the gateway is set up
|
|
61
|
+
expect(vendorModels(model.id).length).toBeGreaterThan(0);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('glm lists the current model line', () => {
|
|
66
|
+
const glm = vendorModels('glm');
|
|
67
|
+
expect(glm).toContain('glm-4.6');
|
|
68
|
+
expect(glm).toContain('glm-4.5');
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('spec mapping routes registry ids to provider prefixes', () => {
|
|
72
|
+
expect(vendorModelSpec('deepseek', 'deepseek-reasoner')).toBe('deepseek:deepseek-reasoner');
|
|
73
|
+
expect(vendorModelSpec('opus', 'claude-sonnet-4')).toBe('anthropic:claude-sonnet-4');
|
|
74
|
+
expect(vendorModelSpec('gpt', 'gpt-4o-mini')).toBe('openai:gpt-4o-mini');
|
|
75
|
+
expect(vendorModelSpec('glmc', 'glm-4.5')).toBe('glmc:glm-4.5');
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
describe('key reuse', () => {
|
|
80
|
+
test('a spec inherits the key registered for its vendor prefix', () => {
|
|
81
|
+
registerApiKey('deepseek', 'vendor-key');
|
|
82
|
+
expect(lookupApiKey('deepseek:deepseek-reasoner')).toBe('vendor-key');
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('glmc reuses the key saved for glm (same credential family)', () => {
|
|
86
|
+
registerApiKey('glm', 'glm-key');
|
|
87
|
+
expect(lookupApiKey('glmc')).toBe('glm-key');
|
|
88
|
+
expect(lookupApiKey('glmc:glm-4.5')).toBe('glm-key');
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
describe('custom gateway', () => {
|
|
93
|
+
test('persists and resolves base URL and model', () => {
|
|
94
|
+
setCustomModel({ baseUrl: 'https://gw.example.com/v1', model: 'my-model' });
|
|
95
|
+
|
|
96
|
+
const resolved = resolveModel('custom');
|
|
97
|
+
expect(resolved.model).toBe('my-model');
|
|
98
|
+
expect(resolved.baseUrl).toBe('https://gw.example.com/v1');
|
|
99
|
+
expect(resolved.provider).toBe('openai');
|
|
100
|
+
|
|
101
|
+
const overridden = resolveModel('custom:other-model');
|
|
102
|
+
expect(overridden.model).toBe('other-model');
|
|
103
|
+
expect(overridden.baseUrl).toBe('https://gw.example.com/v1');
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('appears in the model list', () => {
|
|
107
|
+
expect(getAvailableModels().some((model) => model.id === 'custom')).toBe(true);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
describe('verifyModel', () => {
|
|
112
|
+
test('fails fast with a readable message when no key is available', async () => {
|
|
113
|
+
const result = await verifyModel('deepseek:deepseek-chat', '');
|
|
114
|
+
expect(result.ok).toBe(false);
|
|
115
|
+
expect(result.message).toMatch(/key/i);
|
|
116
|
+
});
|
|
117
|
+
});
|