@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.
- package/README.md +58 -17
- package/package.json +1 -1
- package/src/acp/session.ts +4 -1
- package/src/agent/loop.test.ts +245 -0
- package/src/agent/loop.ts +92 -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/dispatch.test.ts +115 -0
- package/src/agent/tools/dispatch.ts +141 -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 +27 -2
- package/src/agent/tools/search.test.ts +55 -1
- package/src/agent/tools/search.ts +56 -8
- package/src/agent/tools/session.ts +9 -0
- package/src/agent/tools/todo.test.ts +54 -0
- package/src/agent/tools/todo.ts +47 -0
- package/src/agent/tools/types.ts +13 -1
- package/src/commands.ts +37 -2
- package/src/config.ts +21 -3
- package/src/main.tsx +4 -4
- package/src/provider/provider.test.ts +117 -0
- package/src/provider/provider.ts +278 -34
- package/src/provider/routing.test.ts +109 -0
- package/src/screens/REPL.tsx +199 -31
- package/src/version.ts +1 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
1
2
|
import { promises as fs } from 'node:fs';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
|
|
@@ -78,6 +79,45 @@ function escapeRegex(value: string): string {
|
|
|
78
79
|
return value.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
79
80
|
}
|
|
80
81
|
|
|
82
|
+
function runGit(args: string[], cwd: string): Promise<string> {
|
|
83
|
+
return new Promise((resolve, reject) => {
|
|
84
|
+
execFile('git', args, { cwd, timeout: 5000 }, (error, stdout) => {
|
|
85
|
+
if (error) reject(error);
|
|
86
|
+
else resolve(String(stdout));
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Files under root, honoring .gitignore when inside a git repository:
|
|
93
|
+
* `git ls-files --cached --others --exclude-standard` gives exact git
|
|
94
|
+
* semantics for free. Falls back to the directory walk outside repos.
|
|
95
|
+
*/
|
|
96
|
+
export async function workspaceFiles(root: string, signal?: AbortSignal): Promise<string[]> {
|
|
97
|
+
try {
|
|
98
|
+
const topLevel = (await runGit(['rev-parse', '--show-toplevel'], root)).trim();
|
|
99
|
+
const listing = await runGit(
|
|
100
|
+
['ls-files', '--cached', '--others', '--exclude-standard', '--full-name'],
|
|
101
|
+
root,
|
|
102
|
+
);
|
|
103
|
+
if (!topLevel || signal?.aborted) throw new Error('fallback');
|
|
104
|
+
// git reports physical paths (/private/var/... on macOS) while callers
|
|
105
|
+
// may hold symlinked ones (/var/...); normalize before filtering.
|
|
106
|
+
const physicalRoot = await fs.realpath(root);
|
|
107
|
+
const prefix = topLevel.endsWith(path.sep) ? topLevel : `${topLevel}${path.sep}`;
|
|
108
|
+
const files = listing
|
|
109
|
+
.split('\n')
|
|
110
|
+
.map((line) => line.trim())
|
|
111
|
+
.filter(Boolean)
|
|
112
|
+
.map((line) => `${prefix}${line}`)
|
|
113
|
+
.filter((file) => file.startsWith(`${physicalRoot}${path.sep}`));
|
|
114
|
+
if (files.length === 0) throw new Error('fallback');
|
|
115
|
+
return files;
|
|
116
|
+
} catch {
|
|
117
|
+
return walkFiles(root, signal);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
81
121
|
export function globToRegExp(pattern: string): RegExp {
|
|
82
122
|
let p = pattern.replace(/\\/g, '/').replace(/^\.\//, '');
|
|
83
123
|
p = escapeRegex(p);
|
package/src/agent/tools/index.ts
CHANGED
|
@@ -4,15 +4,35 @@ import type { AgentTool, InvokeResult, ToolContext } from './types.js';
|
|
|
4
4
|
import { bashTool } from './bash.js';
|
|
5
5
|
import { editFileTool, readFileTool, writeFileTool } from './files.js';
|
|
6
6
|
import { globTool, grepTool } from './search.js';
|
|
7
|
+
import { todoWriteTool } from './todo.js';
|
|
8
|
+
import { createAskModelTool } from './ask-model.js';
|
|
9
|
+
import { createDispatchAgentTool } from './dispatch.js';
|
|
10
|
+
import { readImageBlocks } from './files.js';
|
|
11
|
+
import { askRole as providerAskRole } from '../../provider/provider.js';
|
|
7
12
|
|
|
8
|
-
|
|
13
|
+
const askModelTool = createAskModelTool(async (role, prompt, images, ctx) => {
|
|
14
|
+
const blocks = images?.length && ctx ? await readImageBlocks(images, ctx) : undefined;
|
|
15
|
+
return providerAskRole(role, prompt, blocks);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
// The dispatch pool deliberately excludes dispatch_agent itself (no recursion).
|
|
19
|
+
const dispatchPool = [
|
|
9
20
|
readFileTool,
|
|
10
21
|
writeFileTool,
|
|
11
22
|
editFileTool,
|
|
12
23
|
globTool,
|
|
13
24
|
grepTool,
|
|
14
25
|
bashTool,
|
|
26
|
+
todoWriteTool,
|
|
27
|
+
askModelTool,
|
|
15
28
|
];
|
|
29
|
+
const dispatchAgentTool = createDispatchAgentTool({
|
|
30
|
+
runLoop: (options) =>
|
|
31
|
+
import('../loop.js').then(({ runAgentLoop }) => runAgentLoop(options)),
|
|
32
|
+
tools: dispatchPool,
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
export const AGENT_TOOLS: AgentTool[] = [...dispatchPool, dispatchAgentTool];
|
|
16
36
|
|
|
17
37
|
export function findAgentTool(name: string): AgentTool | undefined {
|
|
18
38
|
return AGENT_TOOLS.find((item) => item.name === name);
|
|
@@ -49,7 +69,12 @@ export async function invokeTool(
|
|
|
49
69
|
if (typeof result === 'string') {
|
|
50
70
|
return { ok: true, output: result || '(no output)' };
|
|
51
71
|
}
|
|
52
|
-
return {
|
|
72
|
+
return {
|
|
73
|
+
ok: true,
|
|
74
|
+
output: result.output || '(no output)',
|
|
75
|
+
diff: result.diff,
|
|
76
|
+
images: result.images,
|
|
77
|
+
};
|
|
53
78
|
} catch (error) {
|
|
54
79
|
return { ok: false, output: `Error: ${(error as Error).message}` };
|
|
55
80
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
|
-
import {
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
4
|
import { tmpdir } from 'node:os';
|
|
4
5
|
import path from 'node:path';
|
|
5
6
|
import { globTool, grepTool } from './search.js';
|
|
@@ -52,4 +53,57 @@ describe('grep', () => {
|
|
|
52
53
|
const output = await grepTool.execute({ pattern: 'nope-xyz' }, ctx(session));
|
|
53
54
|
expect(output).toContain('No matches');
|
|
54
55
|
});
|
|
56
|
+
|
|
57
|
+
test('context lines appear with - markers and -- group separators', async () => {
|
|
58
|
+
const dir = workspace();
|
|
59
|
+
const lines = Array.from({ length: 12 }, (_, i) => `line ${i + 1}`);
|
|
60
|
+
writeFileSync(path.join(dir, 'ctx.txt'), `${lines.join('\n')}\n`);
|
|
61
|
+
|
|
62
|
+
const session = createToolSession(dir);
|
|
63
|
+
const output = await grepTool.execute(
|
|
64
|
+
{ pattern: 'line 2$|line 10', context: 1 },
|
|
65
|
+
ctx(session),
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
expect(output).toContain('ctx.txt:2: line 2');
|
|
69
|
+
expect(output).toContain('ctx.txt-3- line 3');
|
|
70
|
+
expect(output).toContain('ctx.txt:10: line 10');
|
|
71
|
+
expect(output).toContain('--');
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('multiline patterns match across lines only with multiline: true', async () => {
|
|
75
|
+
const dir = workspace();
|
|
76
|
+
writeFileSync(path.join(dir, 'fn.ts'), 'function foo(\n x: number\n) {\n return x;\n}\n');
|
|
77
|
+
|
|
78
|
+
const session = createToolSession(dir);
|
|
79
|
+
const single = await grepTool.execute({ pattern: 'foo\\([\\s\\S]*?return' }, ctx(session));
|
|
80
|
+
expect(single).toContain('No matches');
|
|
81
|
+
|
|
82
|
+
const multi = await grepTool.execute(
|
|
83
|
+
{ pattern: 'foo\\([\\s\\S]*?return', multiline: true },
|
|
84
|
+
ctx(session),
|
|
85
|
+
);
|
|
86
|
+
expect(multi).toContain('fn.ts:1-4:');
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test('respects .gitignore inside a git repository', async () => {
|
|
90
|
+
const dir = workspace();
|
|
91
|
+
execFileSync('git', ['init', '-q'], { cwd: dir });
|
|
92
|
+
writeFileSync(path.join(dir, '.gitignore'), 'ignored-dir/\n*.tmp\n');
|
|
93
|
+
writeFileSync(path.join(dir, 'src.txt'), 'target found here\n');
|
|
94
|
+
mkdirSync(path.join(dir, 'ignored-dir'));
|
|
95
|
+
writeFileSync(path.join(dir, 'ignored-dir', 'hidden.txt'), 'target also here\n');
|
|
96
|
+
writeFileSync(path.join(dir, 'noise.tmp'), 'target noise\n');
|
|
97
|
+
|
|
98
|
+
const session = createToolSession(dir);
|
|
99
|
+
const output = await grepTool.execute({ pattern: 'target' }, ctx(session));
|
|
100
|
+
expect(output).toContain('src.txt');
|
|
101
|
+
expect(output).not.toContain('hidden.txt');
|
|
102
|
+
expect(output).not.toContain('noise.tmp');
|
|
103
|
+
|
|
104
|
+
const files = await globTool.execute({ pattern: '**/*' }, ctx(session));
|
|
105
|
+
expect(files).toContain('src.txt');
|
|
106
|
+
expect(files).not.toContain('hidden.txt');
|
|
107
|
+
expect(files).not.toContain('noise.tmp');
|
|
108
|
+
});
|
|
55
109
|
});
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
matchesGlob,
|
|
10
10
|
readTextIfTextFile,
|
|
11
11
|
resolveInsideWorkspace,
|
|
12
|
-
|
|
12
|
+
workspaceFiles,
|
|
13
13
|
} from './fs-utils.js';
|
|
14
14
|
|
|
15
15
|
export const globTool: AgentTool = {
|
|
@@ -27,7 +27,7 @@ export const globTool: AgentTool = {
|
|
|
27
27
|
async execute(input, ctx) {
|
|
28
28
|
const root = resolveInsideWorkspace(ctx.cwd, String(input.path ?? '.'));
|
|
29
29
|
const pattern = String(input.pattern);
|
|
30
|
-
const files = await
|
|
30
|
+
const files = await workspaceFiles(root, ctx.signal);
|
|
31
31
|
const matches: string[] = [];
|
|
32
32
|
|
|
33
33
|
for (const file of files) {
|
|
@@ -59,21 +59,27 @@ export const grepTool: AgentTool = {
|
|
|
59
59
|
path: z.string().nullable().optional().describe('Directory or file to search (default: workspace root)'),
|
|
60
60
|
include: z.string().nullable().optional().describe('Glob that file paths must match'),
|
|
61
61
|
ignore_case: z.boolean().nullable().optional().describe('Case-insensitive search'),
|
|
62
|
+
multiline: z.boolean().nullable().optional().describe('Let the pattern match across line breaks'),
|
|
63
|
+
context: z.number().int().min(0).max(10).nullable().optional().describe('Show N context lines around each match'),
|
|
62
64
|
}),
|
|
63
65
|
title: (input) => `search: ${String(input.pattern ?? '')}`,
|
|
64
66
|
async execute(input, ctx) {
|
|
65
67
|
let regex: RegExp;
|
|
66
68
|
try {
|
|
67
|
-
regex = new RegExp(
|
|
69
|
+
regex = new RegExp(
|
|
70
|
+
String(input.pattern),
|
|
71
|
+
`${input.ignore_case ? 'i' : ''}m${input.multiline ? 's' : ''}`,
|
|
72
|
+
);
|
|
68
73
|
} catch (error) {
|
|
69
74
|
throw new Error(`Invalid regular expression: ${(error as Error).message}`);
|
|
70
75
|
}
|
|
71
76
|
|
|
72
77
|
const target = resolveInsideWorkspace(ctx.cwd, String(input.path ?? '.'));
|
|
73
78
|
const stat = await fs.stat(target);
|
|
74
|
-
const files = stat.isFile() ? [target] : await
|
|
79
|
+
const files = stat.isFile() ? [target] : await workspaceFiles(target, ctx.signal);
|
|
75
80
|
const include = input.include ? String(input.include) : undefined;
|
|
76
81
|
const results: string[] = [];
|
|
82
|
+
const context = Number(input.context ?? 0);
|
|
77
83
|
|
|
78
84
|
for (const file of files) {
|
|
79
85
|
if (ctx.signal?.aborted) throw new Error('Aborted');
|
|
@@ -89,12 +95,54 @@ export const grepTool: AgentTool = {
|
|
|
89
95
|
if (content === null) continue;
|
|
90
96
|
|
|
91
97
|
const lines = content.split('\n');
|
|
92
|
-
|
|
98
|
+
|
|
99
|
+
if (input.multiline === true) {
|
|
93
100
|
regex.lastIndex = 0;
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
101
|
+
let match: RegExpExecArray | null;
|
|
102
|
+
while ((match = regex.exec(content)) !== null) {
|
|
103
|
+
if (match[0] === '') break; // zero-length match guard
|
|
104
|
+
const startLine = content.slice(0, match.index).split('\n').length;
|
|
105
|
+
const endLine = startLine - 1 + match[0].split('\n').length;
|
|
106
|
+
const text = match[0].length > 400 ? `${match[0].slice(0, 400)}...` : match[0];
|
|
107
|
+
results.push(`${relative}:${startLine}-${endLine}: ${text.replace(/\n/g, '\\n')}`);
|
|
108
|
+
if (results.length >= MAX_GREP_MATCHES) break;
|
|
109
|
+
}
|
|
97
110
|
if (results.length >= MAX_GREP_MATCHES) break;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const hits: number[] = [];
|
|
115
|
+
for (let index = 0; index < lines.length; index++) {
|
|
116
|
+
regex.lastIndex = 0;
|
|
117
|
+
if (regex.test(lines[index])) hits.push(index);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (context > 0) {
|
|
121
|
+
// rg-style: hits as rel:N:, context as rel-N-, groups split by --.
|
|
122
|
+
const isHit = new Set(hits);
|
|
123
|
+
const shown = new Set<number>();
|
|
124
|
+
for (const hit of hits) {
|
|
125
|
+
for (let n = hit - context; n <= hit + context; n++) {
|
|
126
|
+
if (n >= 0 && n < lines.length) shown.add(n);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
let previous = -2;
|
|
130
|
+
for (const index of [...shown].sort((a, b) => a - b)) {
|
|
131
|
+
if (previous >= 0 && index - previous > 1) results.push('--');
|
|
132
|
+
previous = index;
|
|
133
|
+
const raw = lines[index];
|
|
134
|
+
const text = raw.length > 500 ? `${raw.slice(0, 500)}...` : raw;
|
|
135
|
+
results.push(
|
|
136
|
+
isHit.has(index) ? `${relative}:${index + 1}: ${text}` : `${relative}-${index + 1}- ${text}`,
|
|
137
|
+
);
|
|
138
|
+
if (results.length >= MAX_GREP_MATCHES) break;
|
|
139
|
+
}
|
|
140
|
+
} else {
|
|
141
|
+
for (const hit of hits) {
|
|
142
|
+
const raw = lines[hit];
|
|
143
|
+
const text = raw.length > 500 ? `${raw.slice(0, 500)}...` : raw;
|
|
144
|
+
results.push(`${relative}:${hit + 1}: ${text}`);
|
|
145
|
+
}
|
|
98
146
|
}
|
|
99
147
|
if (results.length >= MAX_GREP_MATCHES) break;
|
|
100
148
|
}
|
|
@@ -1,5 +1,11 @@
|
|
|
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
|
+
|
|
3
9
|
/**
|
|
4
10
|
* State that persists across tool calls within one conversation/session:
|
|
5
11
|
* the shell's current working directory (so `cd` survives between bash
|
|
@@ -15,6 +21,8 @@ export interface ToolSession {
|
|
|
15
21
|
shellSnapshot?: Promise<string | undefined>;
|
|
16
22
|
/** Absolute paths of files the model has read (or written) this session. */
|
|
17
23
|
readFileState: Set<string>;
|
|
24
|
+
/** Current task list, owned by the todo_write tool. */
|
|
25
|
+
todos: TodoItem[];
|
|
18
26
|
}
|
|
19
27
|
|
|
20
28
|
export function createToolSession(rootCwd: string): ToolSession {
|
|
@@ -23,6 +31,7 @@ export function createToolSession(rootCwd: string): ToolSession {
|
|
|
23
31
|
cwd: absolute,
|
|
24
32
|
rootCwd: absolute,
|
|
25
33
|
readFileState: new Set<string>(),
|
|
34
|
+
todos: [],
|
|
26
35
|
};
|
|
27
36
|
}
|
|
28
37
|
|
|
@@ -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,23 @@ 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>;
|
|
21
29
|
}
|
|
22
30
|
|
|
23
|
-
/** Rich execute result: model-facing output plus
|
|
31
|
+
/** Rich execute result: model-facing output plus optional extras. */
|
|
24
32
|
export interface ToolOutput {
|
|
25
33
|
output: string;
|
|
26
34
|
/** Unified diff text for TUI rendering; never sent to the model. */
|
|
27
35
|
diff?: string;
|
|
36
|
+
/** Base64 images sent to the model as multimodal content blocks. */
|
|
37
|
+
images?: Array<{ data: string; mediaType: string }>;
|
|
28
38
|
}
|
|
29
39
|
|
|
30
40
|
export interface AgentTool {
|
|
@@ -44,4 +54,6 @@ export interface InvokeResult {
|
|
|
44
54
|
output: string;
|
|
45
55
|
/** Unified diff text for UI rendering, when the tool produced one. */
|
|
46
56
|
diff?: string;
|
|
57
|
+
/** Base64 images for multimodal-capable models. */
|
|
58
|
+
images?: Array<{ data: string; mediaType: string }>;
|
|
47
59
|
}
|
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,39 @@ const commands: Command[] = [
|
|
|
68
70
|
return { output: `Permission mode switched to ${target}` };
|
|
69
71
|
},
|
|
70
72
|
},
|
|
73
|
+
{
|
|
74
|
+
name: 'route',
|
|
75
|
+
description: 'Show or set role→model routing (analysis/design/vision/…)',
|
|
76
|
+
execute: (args) => {
|
|
77
|
+
if (args.length === 0) {
|
|
78
|
+
const routing = getRouting();
|
|
79
|
+
const lines = Object.entries(routing).map(([role, profile]) => {
|
|
80
|
+
const resolved = resolveRole(role);
|
|
81
|
+
return ` ${role.padEnd(10)} → ${profile}${resolved ? ` (${resolved.model})` : ' ⚠ 未解析'}`;
|
|
82
|
+
});
|
|
83
|
+
return {
|
|
84
|
+
output:
|
|
85
|
+
`Role routing:\n${lines.length ? lines.join('\n') : ' (none)'}\n` +
|
|
86
|
+
'Usage: /route <role> <profile|-> — e.g. /route analysis glmc ; "-" removes the role',
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
const [role, profile] = args;
|
|
90
|
+
if (!role || !profile) {
|
|
91
|
+
return { output: 'Usage: /route <role> <profile|->' };
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
setRouting(role, profile);
|
|
95
|
+
return {
|
|
96
|
+
output:
|
|
97
|
+
profile === '-'
|
|
98
|
+
? `Role "${role}" removed.`
|
|
99
|
+
: `Role "${role}" → ${profile}`,
|
|
100
|
+
};
|
|
101
|
+
} catch (error) {
|
|
102
|
+
return { output: (error as Error).message };
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
},
|
|
71
106
|
{
|
|
72
107
|
name: 'clear',
|
|
73
108
|
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 = {
|