@trans-ai/trans-code 0.1.4 → 0.2.1

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.
Files changed (37) hide show
  1. package/README.md +3 -3
  2. package/docs/ACP.md +2 -2
  3. package/package.json +2 -1
  4. package/src/acp/session.ts +7 -3
  5. package/src/agent/loop.test.ts +113 -0
  6. package/src/agent/loop.ts +27 -6
  7. package/src/agent/permission.test.ts +50 -0
  8. package/src/agent/permission.ts +34 -0
  9. package/src/agent/system-prompt.test.ts +54 -0
  10. package/src/agent/system-prompt.ts +15 -1
  11. package/src/agent/tools/bash.test.ts +115 -0
  12. package/src/agent/tools/bash.ts +315 -0
  13. package/src/agent/tools/diff-plumbing.test.ts +81 -0
  14. package/src/agent/tools/diff.test.ts +82 -0
  15. package/src/agent/tools/diff.ts +146 -0
  16. package/src/agent/tools/files.test.ts +133 -0
  17. package/src/agent/tools/files.ts +240 -0
  18. package/src/agent/tools/fs-utils.ts +117 -0
  19. package/src/agent/tools/index.ts +59 -0
  20. package/src/agent/tools/read-only.test.ts +78 -0
  21. package/src/agent/tools/read-only.ts +181 -0
  22. package/src/agent/tools/search.test.ts +55 -0
  23. package/src/agent/tools/search.ts +108 -0
  24. package/src/agent/tools/session.test.ts +34 -0
  25. package/src/agent/tools/session.ts +35 -0
  26. package/src/agent/tools/types.ts +47 -0
  27. package/src/cli.ts +3 -2
  28. package/src/commands.test.ts +56 -0
  29. package/src/commands.ts +31 -0
  30. package/src/provider/provider.ts +2 -2
  31. package/src/screens/REPL.tsx +108 -6
  32. package/src/screens/diff-render.test.ts +36 -0
  33. package/src/screens/diff-render.ts +26 -0
  34. package/src/screens/file-completion.test.ts +64 -0
  35. package/src/screens/file-completion.ts +49 -0
  36. package/src/version.ts +1 -1
  37. package/src/agent/tools.ts +0 -483
@@ -1,483 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { promises as fs } from 'node:fs';
3
- import path from 'node:path';
4
- import { z } from 'zod';
5
- import { tool as langChainTool } from '@langchain/core/tools';
6
- import type { StructuredToolInterface } from '@langchain/core/tools';
7
-
8
- export type ToolKind =
9
- | 'read'
10
- | 'edit'
11
- | 'delete'
12
- | 'move'
13
- | 'search'
14
- | 'execute'
15
- | 'think'
16
- | 'fetch'
17
- | 'switch_mode'
18
- | 'other';
19
-
20
- export interface ToolContext {
21
- cwd: string;
22
- signal?: AbortSignal;
23
- }
24
-
25
- export interface AgentTool {
26
- name: string;
27
- description: string;
28
- schema: z.ZodObject<z.ZodRawShape>;
29
- kind: ToolKind;
30
- isMutating: boolean;
31
- title(input: Record<string, unknown>): string;
32
- execute(input: Record<string, unknown>, ctx: ToolContext): Promise<string>;
33
- }
34
-
35
- export interface InvokeResult {
36
- ok: boolean;
37
- output: string;
38
- }
39
-
40
- const MAX_READ_BYTES = 100_000;
41
- const MAX_BASH_OUTPUT = 30_000;
42
- const MAX_GREP_MATCHES = 200;
43
- const MAX_GLOB_FILES = 200;
44
-
45
- const SKIP_DIRS = new Set([
46
- '.git',
47
- 'node_modules',
48
- '.turbo',
49
- 'dist',
50
- 'build',
51
- '.next',
52
- 'target',
53
- '__pycache__',
54
- '.venv',
55
- 'venv',
56
- '.cache',
57
- ]);
58
-
59
- function truncate(text: string, max: number): string {
60
- if (text.length <= max) return text;
61
- return `${text.slice(0, max)}\n... (truncated, ${text.length - max} chars omitted)`;
62
- }
63
-
64
- function resolveInsideWorkspace(cwd: string, inputPath: string): string {
65
- const absolute = path.resolve(cwd, inputPath || '.');
66
- if (process.env.TRANSCODE_ALLOW_OUTSIDE_CWD === '1') return absolute;
67
-
68
- const relative = path.relative(cwd, absolute);
69
- const inside =
70
- relative === '' ||
71
- (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative));
72
- if (!inside) {
73
- throw new Error(
74
- `Path escapes the workspace: ${inputPath}. ` +
75
- `Set TRANSCODE_ALLOW_OUTSIDE_CWD=1 to allow it.`,
76
- );
77
- }
78
- return absolute;
79
- }
80
-
81
- function displayPath(cwd: string, absolute: string): string {
82
- const relative = path.relative(cwd, absolute);
83
- return relative && !relative.startsWith('..') ? relative : absolute;
84
- }
85
-
86
- async function walkFiles(root: string, signal?: AbortSignal): Promise<string[]> {
87
- const files: string[] = [];
88
- const stack: string[] = [root];
89
-
90
- while (stack.length > 0) {
91
- if (signal?.aborted) throw new Error('Aborted');
92
- const dir = stack.pop()!;
93
- let entries;
94
- try {
95
- entries = await fs.readdir(dir, { withFileTypes: true });
96
- } catch {
97
- continue;
98
- }
99
- for (const entry of entries) {
100
- const full = path.join(dir, entry.name);
101
- if (entry.isDirectory()) {
102
- if (SKIP_DIRS.has(entry.name)) continue;
103
- stack.push(full);
104
- } else if (entry.isFile()) {
105
- files.push(full);
106
- }
107
- }
108
- }
109
-
110
- return files;
111
- }
112
-
113
- function escapeRegex(value: string): string {
114
- return value.replace(/[.+^${}()|[\]\\]/g, '\\$&');
115
- }
116
-
117
- function globToRegExp(pattern: string): RegExp {
118
- let p = pattern.replace(/\\/g, '/').replace(/^\.\//, '');
119
- p = escapeRegex(p);
120
- // `**/` should also match zero directories.
121
- p = p.replace(/\*\*\//g, '\u0001');
122
- p = p.replace(/\*\*/g, '\u0002');
123
- p = p.replace(/\*/g, '[^/]*');
124
- p = p.replace(/\?/g, '[^/]');
125
- p = p.replace(/\u0001/g, '(?:.*/)?');
126
- p = p.replace(/\u0002/g, '.*');
127
- return new RegExp(`^${p}$`);
128
- }
129
-
130
- function matchesGlob(pattern: string, relativePath: string): boolean {
131
- const normalized = relativePath.replace(/\\/g, '/');
132
- const re = globToRegExp(pattern);
133
- if (!pattern.includes('/')) {
134
- return re.test(path.posix.basename(normalized));
135
- }
136
- return re.test(normalized);
137
- }
138
-
139
- async function readTextIfTextFile(file: string): Promise<string | null> {
140
- const stat = await fs.stat(file);
141
- if (stat.size > 2_000_000) return null;
142
-
143
- const handle = await fs.open(file, 'r');
144
- try {
145
- const buffer = Buffer.alloc(8192);
146
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
147
- const sample = buffer.subarray(0, bytesRead);
148
- if (sample.includes(0)) return null;
149
- return await fs.readFile(file, 'utf8');
150
- } finally {
151
- await handle.close();
152
- }
153
- }
154
-
155
- const readFileTool: AgentTool = {
156
- name: 'read_file',
157
- description:
158
- 'Read a UTF-8 text file from the workspace. Returns line-numbered content. ' +
159
- 'Use offset (1-based line) and limit to read large files in chunks.',
160
- kind: 'read',
161
- isMutating: false,
162
- schema: z.object({
163
- path: z.string().describe('File path, relative to the workspace root'),
164
- offset: z.number().int().min(1).nullable().optional().describe('First line to read (1-based)'),
165
- limit: z.number().int().min(1).max(5000).nullable().optional().describe('Maximum number of lines'),
166
- }),
167
- title: (input) => `read: ${String(input.path ?? '')}`,
168
- async execute(input, ctx) {
169
- const absolute = resolveInsideWorkspace(ctx.cwd, String(input.path));
170
- const stat = await fs.stat(absolute);
171
- if (!stat.isFile()) throw new Error(`Not a file: ${input.path}`);
172
- if (stat.size > 5_000_000) {
173
- throw new Error(
174
- `File is ${stat.size} bytes, which exceeds the 5 MB read limit. ` +
175
- 'Use grep or bash (head/tail) to inspect it.',
176
- );
177
- }
178
- if (stat.size > MAX_READ_BYTES && !input.offset && !input.limit) {
179
- throw new Error(
180
- `File is ${stat.size} bytes. Pass offset/limit to read it in chunks.`,
181
- );
182
- }
183
-
184
- const content = await fs.readFile(absolute, 'utf8');
185
- const lines = content.split('\n');
186
- const offset = Math.max(1, Number(input.offset ?? 1));
187
- const limit = Math.min(Number(input.limit ?? 2000), 5000);
188
- const selected = lines.slice(offset - 1, offset - 1 + limit);
189
- const numbered = selected
190
- .map((line, index) => `${String(offset + index).padStart(6)}\t${line}`)
191
- .join('\n');
192
-
193
- const more = offset - 1 + selected.length < lines.length;
194
- return truncate(
195
- numbered + (more ? `\n... (${lines.length} lines total)` : ''),
196
- MAX_READ_BYTES,
197
- );
198
- },
199
- };
200
-
201
- const writeFileTool: AgentTool = {
202
- name: 'write_file',
203
- description:
204
- 'Create or overwrite a file in the workspace with the given content. ' +
205
- 'Prefer edit_file for existing files so unrelated content is preserved.',
206
- kind: 'edit',
207
- isMutating: true,
208
- schema: z.object({
209
- path: z.string().describe('File path, relative to the workspace root'),
210
- content: z.string().describe('Full file content to write'),
211
- }),
212
- title: (input) => `write: ${String(input.path ?? '')}`,
213
- async execute(input, ctx) {
214
- const absolute = resolveInsideWorkspace(ctx.cwd, String(input.path));
215
- await fs.mkdir(path.dirname(absolute), { recursive: true });
216
- await fs.writeFile(absolute, String(input.content), 'utf8');
217
- return `Wrote ${Buffer.byteLength(String(input.content), 'utf8')} bytes to ${displayPath(
218
- ctx.cwd,
219
- absolute,
220
- )}`;
221
- },
222
- };
223
-
224
- const editFileTool: AgentTool = {
225
- name: 'edit_file',
226
- description:
227
- 'Replace an exact string in an existing file. The old_string must appear exactly once ' +
228
- 'unless replace_all is true. Read the file first to get exact text.',
229
- kind: 'edit',
230
- isMutating: true,
231
- schema: z.object({
232
- path: z.string().describe('File path, relative to the workspace root'),
233
- old_string: z.string().describe('Exact text to replace'),
234
- new_string: z.string().describe('Replacement text'),
235
- replace_all: z.boolean().nullable().optional().describe('Replace every occurrence'),
236
- }),
237
- title: (input) => `patch: ${String(input.path ?? '')}`,
238
- async execute(input, ctx) {
239
- const absolute = resolveInsideWorkspace(ctx.cwd, String(input.path));
240
- const oldString = String(input.old_string);
241
- const newString = String(input.new_string);
242
- if (oldString === newString) throw new Error('old_string and new_string are identical');
243
-
244
- const original = await fs.readFile(absolute, 'utf8');
245
- const occurrences = oldString === '' ? 0 : original.split(oldString).length - 1;
246
- if (occurrences === 0) {
247
- throw new Error('old_string was not found in the file. Read it again and use exact text.');
248
- }
249
- if (occurrences > 1 && input.replace_all !== true) {
250
- throw new Error(
251
- `old_string appears ${occurrences} times. Pass replace_all=true or include more context.`,
252
- );
253
- }
254
-
255
- const updated =
256
- input.replace_all === true
257
- ? original.split(oldString).join(newString)
258
- : original.replace(oldString, () => newString);
259
- await fs.writeFile(absolute, updated, 'utf8');
260
-
261
- return `Replaced ${input.replace_all === true ? occurrences : 1} occurrence(s) in ${displayPath(
262
- ctx.cwd,
263
- absolute,
264
- )}`;
265
- },
266
- };
267
-
268
- const globTool: AgentTool = {
269
- name: 'glob',
270
- description:
271
- 'Find files by glob pattern (for example "**/*.ts" or "src/**/test*.js"). ' +
272
- 'Returns workspace-relative paths.',
273
- kind: 'search',
274
- isMutating: false,
275
- schema: z.object({
276
- pattern: z.string().describe('Glob pattern, matched against workspace-relative paths'),
277
- path: z.string().nullable().optional().describe('Directory to search in (default: workspace root)'),
278
- }),
279
- title: (input) => `search: ${String(input.pattern ?? '')}`,
280
- async execute(input, ctx) {
281
- const root = resolveInsideWorkspace(ctx.cwd, String(input.path ?? '.'));
282
- const pattern = String(input.pattern);
283
- const files = await walkFiles(root, ctx.signal);
284
- const matches: string[] = [];
285
-
286
- for (const file of files) {
287
- const relative = path.relative(root, file).replace(/\\/g, '/');
288
- if (matchesGlob(pattern, relative)) {
289
- matches.push(displayPath(ctx.cwd, file));
290
- if (matches.length >= MAX_GLOB_FILES) break;
291
- }
292
- }
293
-
294
- matches.sort();
295
- if (matches.length === 0) return `No files matched ${pattern}`;
296
- return (
297
- matches.join('\n') +
298
- (matches.length >= MAX_GLOB_FILES ? `\n... (limited to ${MAX_GLOB_FILES} files)` : '')
299
- );
300
- },
301
- };
302
-
303
- const grepTool: AgentTool = {
304
- name: 'grep',
305
- description:
306
- 'Search file contents with a regular expression. Returns path:line: text matches. ' +
307
- 'Use include to restrict files by glob (for example "**/*.ts").',
308
- kind: 'search',
309
- isMutating: false,
310
- schema: z.object({
311
- pattern: z.string().describe('JavaScript regular expression to search for'),
312
- path: z.string().nullable().optional().describe('Directory or file to search (default: workspace root)'),
313
- include: z.string().nullable().optional().describe('Glob that file paths must match'),
314
- ignore_case: z.boolean().nullable().optional().describe('Case-insensitive search'),
315
- }),
316
- title: (input) => `search: ${String(input.pattern ?? '')}`,
317
- async execute(input, ctx) {
318
- let regex: RegExp;
319
- try {
320
- regex = new RegExp(String(input.pattern), input.ignore_case ? 'i' : '');
321
- } catch (error) {
322
- throw new Error(`Invalid regular expression: ${(error as Error).message}`);
323
- }
324
-
325
- const target = resolveInsideWorkspace(ctx.cwd, String(input.path ?? '.'));
326
- const stat = await fs.stat(target);
327
- const files = stat.isFile() ? [target] : await walkFiles(target, ctx.signal);
328
- const include = input.include ? String(input.include) : undefined;
329
- const results: string[] = [];
330
-
331
- for (const file of files) {
332
- if (ctx.signal?.aborted) throw new Error('Aborted');
333
- const relative = displayPath(ctx.cwd, file);
334
- if (include && !matchesGlob(include, relative)) continue;
335
-
336
- let content: string | null;
337
- try {
338
- content = await readTextIfTextFile(file);
339
- } catch {
340
- continue;
341
- }
342
- if (content === null) continue;
343
-
344
- const lines = content.split('\n');
345
- for (let index = 0; index < lines.length; index++) {
346
- regex.lastIndex = 0;
347
- if (!regex.test(lines[index])) continue;
348
- const text = lines[index].length > 500 ? `${lines[index].slice(0, 500)}...` : lines[index];
349
- results.push(`${relative}:${index + 1}: ${text}`);
350
- if (results.length >= MAX_GREP_MATCHES) break;
351
- }
352
- if (results.length >= MAX_GREP_MATCHES) break;
353
- }
354
-
355
- if (results.length === 0) return `No matches for ${input.pattern}`;
356
- return (
357
- results.join('\n') +
358
- (results.length >= MAX_GREP_MATCHES ? `\n... (limited to ${MAX_GREP_MATCHES} matches)` : '')
359
- );
360
- },
361
- };
362
-
363
- const bashTool: AgentTool = {
364
- name: 'bash',
365
- description:
366
- 'Run a shell command in the workspace using bash. Returns stdout, stderr and the exit code. ' +
367
- 'Prefer dedicated read/write/edit/glob/grep tools for file operations.',
368
- kind: 'execute',
369
- isMutating: true,
370
- schema: z.object({
371
- command: z.string().describe('Shell command to run'),
372
- timeout_ms: z.number().int().min(1000).max(600_000).nullable().optional().describe('Timeout in ms'),
373
- description: z.string().nullable().optional().describe('Short description of what the command does'),
374
- }),
375
- title: (input) => {
376
- const command = String(input.command ?? '');
377
- return `terminal: ${command.length > 80 ? `${command.slice(0, 80)}...` : command}`;
378
- },
379
- async execute(input, ctx) {
380
- const command = String(input.command);
381
- const timeoutMs = Number(input.timeout_ms ?? 120_000);
382
- if (ctx.signal?.aborted) return 'Command cancelled before it started.';
383
-
384
- return await new Promise<string>((resolve) => {
385
- const child = spawn('bash', ['-lc', command], {
386
- cwd: ctx.cwd,
387
- env: process.env,
388
- stdio: ['ignore', 'pipe', 'pipe'],
389
- });
390
-
391
- let stdout = '';
392
- let stderr = '';
393
- let killedForTimeout = false;
394
-
395
- const killTimer = setTimeout(() => {
396
- killedForTimeout = true;
397
- child.kill('SIGTERM');
398
- setTimeout(() => child.kill('SIGKILL'), 2000).unref();
399
- }, timeoutMs);
400
-
401
- const onAbort = () => {
402
- child.kill('SIGTERM');
403
- setTimeout(() => child.kill('SIGKILL'), 2000).unref();
404
- };
405
- ctx.signal?.addEventListener('abort', onAbort, { once: true });
406
-
407
- child.stdout.on('data', (chunk: Buffer) => {
408
- if (stdout.length < MAX_BASH_OUTPUT * 2) stdout += chunk.toString('utf8');
409
- });
410
- child.stderr.on('data', (chunk: Buffer) => {
411
- if (stderr.length < MAX_BASH_OUTPUT * 2) stderr += chunk.toString('utf8');
412
- });
413
-
414
- child.on('error', (error) => {
415
- clearTimeout(killTimer);
416
- ctx.signal?.removeEventListener('abort', onAbort);
417
- resolve(`Failed to start command: ${error.message}`);
418
- });
419
-
420
- child.on('close', (code, signal) => {
421
- clearTimeout(killTimer);
422
- ctx.signal?.removeEventListener('abort', onAbort);
423
-
424
- const parts: string[] = [];
425
- if (stdout.trim()) parts.push(truncate(stdout.trimEnd(), MAX_BASH_OUTPUT));
426
- if (stderr.trim()) parts.push(`[stderr]\n${truncate(stderr.trimEnd(), MAX_BASH_OUTPUT)}`);
427
- parts.push(
428
- killedForTimeout
429
- ? `[exit] timed out after ${timeoutMs}ms`
430
- : `[exit] code=${code ?? 'null'}${signal ? ` signal=${signal}` : ''}`,
431
- );
432
- resolve(parts.join('\n\n'));
433
- });
434
- });
435
- },
436
- };
437
-
438
- export const AGENT_TOOLS: AgentTool[] = [
439
- readFileTool,
440
- writeFileTool,
441
- editFileTool,
442
- globTool,
443
- grepTool,
444
- bashTool,
445
- ];
446
-
447
- export function findAgentTool(name: string): AgentTool | undefined {
448
- return AGENT_TOOLS.find((item) => item.name === name);
449
- }
450
-
451
- /** Tool definitions bound to the model. Execution happens locally via invokeTool. */
452
- export function bindableTools(tools: AgentTool[] = AGENT_TOOLS): StructuredToolInterface[] {
453
- return tools.map((item) =>
454
- langChainTool(async () => '', {
455
- name: item.name,
456
- description: item.description,
457
- schema: item.schema,
458
- }),
459
- );
460
- }
461
-
462
- export async function invokeTool(
463
- item: AgentTool,
464
- input: Record<string, unknown>,
465
- ctx: ToolContext,
466
- ): Promise<InvokeResult> {
467
- const parsed = item.schema.safeParse(input);
468
- if (!parsed.success) {
469
- return {
470
- ok: false,
471
- output: `Invalid input for ${item.name}: ${parsed.error.issues
472
- .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)
473
- .join('; ')}`,
474
- };
475
- }
476
-
477
- try {
478
- const output = await item.execute(parsed.data as Record<string, unknown>, ctx);
479
- return { ok: true, output: output || '(no output)' };
480
- } catch (error) {
481
- return { ok: false, output: `Error: ${(error as Error).message}` };
482
- }
483
- }