@trans-ai/trans-code 0.1.4 → 0.2.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 +3 -3
- package/docs/ACP.md +2 -2
- package/package.json +2 -1
- package/src/acp/session.ts +5 -0
- package/src/agent/loop.test.ts +64 -0
- package/src/agent/loop.ts +20 -5
- package/src/agent/system-prompt.test.ts +54 -0
- package/src/agent/system-prompt.ts +15 -1
- package/src/agent/tools/bash.test.ts +115 -0
- package/src/agent/tools/bash.ts +313 -0
- package/src/agent/tools/diff-plumbing.test.ts +81 -0
- package/src/agent/tools/diff.test.ts +82 -0
- package/src/agent/tools/diff.ts +146 -0
- package/src/agent/tools/files.test.ts +133 -0
- package/src/agent/tools/files.ts +240 -0
- package/src/agent/tools/fs-utils.ts +117 -0
- package/src/agent/tools/index.ts +59 -0
- package/src/agent/tools/search.test.ts +55 -0
- package/src/agent/tools/search.ts +108 -0
- package/src/agent/tools/session.test.ts +34 -0
- package/src/agent/tools/session.ts +35 -0
- package/src/agent/tools/types.ts +45 -0
- package/src/cli.ts +1 -1
- package/src/commands.test.ts +17 -0
- package/src/commands.ts +9 -0
- package/src/provider/provider.ts +2 -2
- package/src/screens/REPL.tsx +104 -4
- package/src/screens/diff-render.test.ts +36 -0
- package/src/screens/diff-render.ts +26 -0
- package/src/screens/file-completion.test.ts +64 -0
- package/src/screens/file-completion.ts +49 -0
- package/src/version.ts +1 -1
- package/src/agent/tools.ts +0 -483
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import { readFileSync, unlinkSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import type { AgentTool } from './types.js';
|
|
8
|
+
import type { ToolSession } from './session.js';
|
|
9
|
+
|
|
10
|
+
const MAX_BASH_OUTPUT = 30_000;
|
|
11
|
+
const TRUNCATE_HEAD = 15_000;
|
|
12
|
+
const TRUNCATE_TAIL = 10_000;
|
|
13
|
+
const SNAPSHOT_TIMEOUT_MS = 10_000;
|
|
14
|
+
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
15
|
+
|
|
16
|
+
let cwdFileCounter = 0;
|
|
17
|
+
|
|
18
|
+
/** Single-quote a value for safe inclusion in a shell command line. */
|
|
19
|
+
function shellQuote(value: string): string {
|
|
20
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function detectShell(): string {
|
|
24
|
+
const shell = process.env.SHELL ?? '';
|
|
25
|
+
if (shell.includes('bash') || shell.includes('zsh')) return shell;
|
|
26
|
+
return '/bin/bash';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function isZsh(shell: string): boolean {
|
|
30
|
+
return shell.includes('zsh');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function rcFileFor(shell: string): string {
|
|
34
|
+
const home = process.env.HOME ?? tmpdir();
|
|
35
|
+
return isZsh(shell) ? path.join(home, '.zshrc') : path.join(home, '.bashrc');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Builds the script that captures the user's interactive shell state
|
|
40
|
+
* (functions, shell options, aliases) into a re-sourceable snapshot file.
|
|
41
|
+
* Ported from Claude Code's ShellSnapshot.getUserSnapshotContent.
|
|
42
|
+
*/
|
|
43
|
+
function snapshotScript(shell: string, snapshotPath: string, rcFile: string, rcExists: boolean): string {
|
|
44
|
+
const zsh = isZsh(shell);
|
|
45
|
+
const userContent = rcExists
|
|
46
|
+
? zsh
|
|
47
|
+
? `
|
|
48
|
+
echo "# Functions" >> "$SNAPSHOT_FILE"
|
|
49
|
+
typeset -f > /dev/null 2>&1
|
|
50
|
+
typeset +f | grep -vE '^_[^_]' | while read func; do
|
|
51
|
+
typeset -f "$func" >> "$SNAPSHOT_FILE"
|
|
52
|
+
done
|
|
53
|
+
echo "# Shell Options" >> "$SNAPSHOT_FILE"
|
|
54
|
+
setopt | sed 's/^/setopt /' | head -n 1000 >> "$SNAPSHOT_FILE"
|
|
55
|
+
`
|
|
56
|
+
: `
|
|
57
|
+
echo "# Functions" >> "$SNAPSHOT_FILE"
|
|
58
|
+
declare -f > /dev/null 2>&1
|
|
59
|
+
declare -F | cut -d' ' -f3 | grep -vE '^_[^_]' | while read func; do
|
|
60
|
+
declare -f "$func" >> "$SNAPSHOT_FILE"
|
|
61
|
+
done
|
|
62
|
+
echo "# Shell Options" >> "$SNAPSHOT_FILE"
|
|
63
|
+
shopt -p | head -n 1000 >> "$SNAPSHOT_FILE"
|
|
64
|
+
set -o | grep "on" | awk '{print "set -o " $1}' | head -n 1000 >> "$SNAPSHOT_FILE"
|
|
65
|
+
echo "shopt -s expand_aliases" >> "$SNAPSHOT_FILE"
|
|
66
|
+
`
|
|
67
|
+
: zsh
|
|
68
|
+
? ''
|
|
69
|
+
: 'echo "shopt -s expand_aliases" >> "$SNAPSHOT_FILE"';
|
|
70
|
+
|
|
71
|
+
return `SNAPSHOT_FILE=${shellQuote(snapshotPath)}
|
|
72
|
+
${rcExists ? `source ${shellQuote(rcFile)} < /dev/null` : '# No user config file to source'}
|
|
73
|
+
|
|
74
|
+
echo "# Snapshot file" >| "$SNAPSHOT_FILE"
|
|
75
|
+
|
|
76
|
+
# Unset aliases so function definitions do not capture stale ones
|
|
77
|
+
echo "unalias -a 2>/dev/null || true" >> "$SNAPSHOT_FILE"
|
|
78
|
+
|
|
79
|
+
${userContent}
|
|
80
|
+
|
|
81
|
+
echo "# Aliases" >> "$SNAPSHOT_FILE"
|
|
82
|
+
alias | sed 's/^alias //g' | sed 's/^/alias -- /' | head -n 1000 >> "$SNAPSHOT_FILE"
|
|
83
|
+
|
|
84
|
+
if [ ! -f "$SNAPSHOT_FILE" ]; then
|
|
85
|
+
echo "Error: Snapshot file was not created at $SNAPSHOT_FILE" >&2
|
|
86
|
+
exit 1
|
|
87
|
+
fi`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Creates the shell environment snapshot once per session by loading the
|
|
92
|
+
* user's shell configuration. Returns the snapshot path, or undefined when
|
|
93
|
+
* creation fails (callers then fall back to a login shell per command).
|
|
94
|
+
*/
|
|
95
|
+
async function createSnapshot(shell: string): Promise<string | undefined> {
|
|
96
|
+
const snapshotsDir = path.join(tmpdir(), 'transcode-shell-snapshots');
|
|
97
|
+
const snapshotPath = path.join(
|
|
98
|
+
snapshotsDir,
|
|
99
|
+
`snapshot-${process.pid}-${Date.now().toString(36)}.sh`,
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
let rcExists = false;
|
|
103
|
+
const rcFile = rcFileFor(shell);
|
|
104
|
+
try {
|
|
105
|
+
await fs.access(rcFile);
|
|
106
|
+
rcExists = true;
|
|
107
|
+
} catch {
|
|
108
|
+
rcExists = false;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
try {
|
|
112
|
+
await fs.mkdir(snapshotsDir, { recursive: true });
|
|
113
|
+
await new Promise<void>((resolve, reject) => {
|
|
114
|
+
const child = spawn(
|
|
115
|
+
shell,
|
|
116
|
+
['-l', '-c', snapshotScript(shell, snapshotPath, rcFile, rcExists)],
|
|
117
|
+
{
|
|
118
|
+
stdio: 'ignore',
|
|
119
|
+
env: { ...process.env, SHELL: shell, GIT_EDITOR: 'true', TRANSCODE: '1' },
|
|
120
|
+
},
|
|
121
|
+
);
|
|
122
|
+
const timer = setTimeout(() => {
|
|
123
|
+
child.kill('SIGKILL');
|
|
124
|
+
reject(new Error('Snapshot creation timed out'));
|
|
125
|
+
}, SNAPSHOT_TIMEOUT_MS);
|
|
126
|
+
child.on('error', (error) => {
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
reject(error);
|
|
129
|
+
});
|
|
130
|
+
child.on('close', (code) => {
|
|
131
|
+
clearTimeout(timer);
|
|
132
|
+
if (code === 0) resolve();
|
|
133
|
+
else reject(new Error(`Snapshot shell exited with code ${code}`));
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
const stat = await fs.stat(snapshotPath);
|
|
137
|
+
if (stat.size === 0) return undefined;
|
|
138
|
+
return snapshotPath;
|
|
139
|
+
} catch {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function getSnapshot(session: ToolSession, shell: string): Promise<string | undefined> {
|
|
145
|
+
if (!session.shellSnapshot) {
|
|
146
|
+
session.shellSnapshot = createSnapshot(shell).catch(() => undefined);
|
|
147
|
+
}
|
|
148
|
+
return session.shellSnapshot;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Keeps the head and the tail of oversized output so failures stay visible. */
|
|
152
|
+
function truncateMiddle(text: string): string {
|
|
153
|
+
if (text.length <= MAX_BASH_OUTPUT) return text;
|
|
154
|
+
const omitted = text.length - TRUNCATE_HEAD - TRUNCATE_TAIL;
|
|
155
|
+
return `${text.slice(0, TRUNCATE_HEAD)}\n... [${omitted} bytes truncated] ...\n${text.slice(-TRUNCATE_TAIL)}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Resolves the directory to spawn in, recovering to the workspace root when
|
|
160
|
+
* the persisted cwd no longer exists (e.g. deleted by a previous command).
|
|
161
|
+
*/
|
|
162
|
+
async function resolveSpawnCwd(session: ToolSession): Promise<string> {
|
|
163
|
+
try {
|
|
164
|
+
await fs.realpath(session.cwd);
|
|
165
|
+
return session.cwd;
|
|
166
|
+
} catch {
|
|
167
|
+
try {
|
|
168
|
+
await fs.realpath(session.rootCwd);
|
|
169
|
+
session.cwd = session.rootCwd;
|
|
170
|
+
return session.rootCwd;
|
|
171
|
+
} catch {
|
|
172
|
+
throw new Error(
|
|
173
|
+
`Working directory "${session.cwd}" no longer exists. Restart transcode from an existing directory.`,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Wraps the user command so the snapshot is sourced, extended globs are
|
|
181
|
+
* disabled (security), and the physical cwd is captured even when the
|
|
182
|
+
* command fails.
|
|
183
|
+
*/
|
|
184
|
+
function buildWrappedCommand(
|
|
185
|
+
command: string,
|
|
186
|
+
shell: string,
|
|
187
|
+
snapshotPath: string | undefined,
|
|
188
|
+
cwdFilePath: string,
|
|
189
|
+
): string {
|
|
190
|
+
const parts: string[] = [];
|
|
191
|
+
if (snapshotPath) {
|
|
192
|
+
parts.push(`source ${shellQuote(snapshotPath)} 2>/dev/null || true`);
|
|
193
|
+
}
|
|
194
|
+
parts.push(
|
|
195
|
+
isZsh(shell)
|
|
196
|
+
? 'setopt NO_EXTENDED_GLOB 2>/dev/null || true'
|
|
197
|
+
: 'shopt -u extglob 2>/dev/null || true',
|
|
198
|
+
);
|
|
199
|
+
parts.push(`eval ${shellQuote(command)}`);
|
|
200
|
+
parts.push('__transcode_rc=$?');
|
|
201
|
+
parts.push(`pwd -P >| ${shellQuote(cwdFilePath)}`);
|
|
202
|
+
parts.push('exit $__transcode_rc');
|
|
203
|
+
return parts.join('\n');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function killProcessGroup(pid: number | undefined, signal: NodeJS.Signals): void {
|
|
207
|
+
if (pid === undefined) return;
|
|
208
|
+
try {
|
|
209
|
+
process.kill(-pid, signal);
|
|
210
|
+
} catch {
|
|
211
|
+
// Process (group) already gone.
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export const bashTool: AgentTool = {
|
|
216
|
+
name: 'bash',
|
|
217
|
+
description:
|
|
218
|
+
'Run a shell command in the workspace using the user shell. Working directory changes (cd) ' +
|
|
219
|
+
'persist across calls. Returns stdout, stderr and the exit code. ' +
|
|
220
|
+
'Prefer dedicated read/write/edit/glob/grep tools for file operations.',
|
|
221
|
+
kind: 'execute',
|
|
222
|
+
isMutating: true,
|
|
223
|
+
schema: z.object({
|
|
224
|
+
command: z.string().describe('Shell command to run'),
|
|
225
|
+
timeout_ms: z.number().int().min(1000).max(600_000).nullable().optional().describe('Timeout in ms'),
|
|
226
|
+
description: z.string().nullable().optional().describe('Short description of what the command does'),
|
|
227
|
+
}),
|
|
228
|
+
title: (input) => {
|
|
229
|
+
const command = String(input.command ?? '');
|
|
230
|
+
return `terminal: ${command.length > 80 ? `${command.slice(0, 80)}...` : command}`;
|
|
231
|
+
},
|
|
232
|
+
async execute(input, ctx) {
|
|
233
|
+
const command = String(input.command);
|
|
234
|
+
const timeoutMs = Number(input.timeout_ms ?? DEFAULT_TIMEOUT_MS);
|
|
235
|
+
if (ctx.signal?.aborted) return 'Command cancelled before it started.';
|
|
236
|
+
|
|
237
|
+
const session = ctx.session;
|
|
238
|
+
const shell = detectShell();
|
|
239
|
+
const snapshotPath = await getSnapshot(session, shell);
|
|
240
|
+
const cwd = await resolveSpawnCwd(session);
|
|
241
|
+
const cwdFilePath = path.join(
|
|
242
|
+
tmpdir(),
|
|
243
|
+
`transcode-${process.pid}-${cwdFileCounter++}-cwd`,
|
|
244
|
+
);
|
|
245
|
+
const wrapped = buildWrappedCommand(command, shell, snapshotPath, cwdFilePath);
|
|
246
|
+
|
|
247
|
+
return await new Promise<string>((resolve) => {
|
|
248
|
+
const child = spawn(shell, snapshotPath ? ['-c', wrapped] : ['-l', '-c', wrapped], {
|
|
249
|
+
cwd,
|
|
250
|
+
env: { ...process.env, SHELL: shell, GIT_EDITOR: 'true', TRANSCODE: '1' },
|
|
251
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
252
|
+
detached: true,
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
let stdout = '';
|
|
256
|
+
let stderr = '';
|
|
257
|
+
let killedForTimeout = false;
|
|
258
|
+
|
|
259
|
+
const killTimer = setTimeout(() => {
|
|
260
|
+
killedForTimeout = true;
|
|
261
|
+
killProcessGroup(child.pid, 'SIGTERM');
|
|
262
|
+
setTimeout(() => killProcessGroup(child.pid, 'SIGKILL'), 2000).unref();
|
|
263
|
+
}, timeoutMs);
|
|
264
|
+
|
|
265
|
+
const onAbort = () => {
|
|
266
|
+
killProcessGroup(child.pid, 'SIGTERM');
|
|
267
|
+
setTimeout(() => killProcessGroup(child.pid, 'SIGKILL'), 2000).unref();
|
|
268
|
+
};
|
|
269
|
+
ctx.signal?.addEventListener('abort', onAbort, { once: true });
|
|
270
|
+
|
|
271
|
+
child.stdout.on('data', (chunk: Buffer) => {
|
|
272
|
+
if (stdout.length < MAX_BASH_OUTPUT * 3) stdout += chunk.toString('utf8');
|
|
273
|
+
});
|
|
274
|
+
child.stderr.on('data', (chunk: Buffer) => {
|
|
275
|
+
if (stderr.length < MAX_BASH_OUTPUT * 3) stderr += chunk.toString('utf8');
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
child.on('error', (error) => {
|
|
279
|
+
clearTimeout(killTimer);
|
|
280
|
+
ctx.signal?.removeEventListener('abort', onAbort);
|
|
281
|
+
resolve(`Failed to start command: ${error.message}`);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
child.on('close', (code, signal) => {
|
|
285
|
+
clearTimeout(killTimer);
|
|
286
|
+
ctx.signal?.removeEventListener('abort', onAbort);
|
|
287
|
+
|
|
288
|
+
// Sync read so callers awaiting execute() see the updated cwd immediately.
|
|
289
|
+
try {
|
|
290
|
+
const newCwd = readFileSync(cwdFilePath, 'utf8').trim();
|
|
291
|
+
if (newCwd) session.cwd = newCwd;
|
|
292
|
+
} catch {
|
|
293
|
+
// Command exited before pwd ran (e.g. `exit`); keep the previous cwd.
|
|
294
|
+
}
|
|
295
|
+
try {
|
|
296
|
+
unlinkSync(cwdFilePath);
|
|
297
|
+
} catch {
|
|
298
|
+
// Best effort cleanup only.
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const parts: string[] = [];
|
|
302
|
+
if (stdout.trim()) parts.push(truncateMiddle(stdout.trimEnd()));
|
|
303
|
+
if (stderr.trim()) parts.push(`[stderr]\n${truncateMiddle(stderr.trimEnd())}`);
|
|
304
|
+
parts.push(
|
|
305
|
+
killedForTimeout
|
|
306
|
+
? `[exit] timed out after ${timeoutMs}ms`
|
|
307
|
+
: `[exit] code=${code ?? 'null'}${signal ? ` signal=${signal}` : ''}`,
|
|
308
|
+
);
|
|
309
|
+
resolve(parts.join('\n\n'));
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
},
|
|
313
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { editFileTool, readFileTool, writeFileTool } from './files.js';
|
|
6
|
+
import { invokeTool } from './index.js';
|
|
7
|
+
import { createToolSession } from './session.js';
|
|
8
|
+
|
|
9
|
+
const cleanups: Array<() => void> = [];
|
|
10
|
+
afterEach(() => {
|
|
11
|
+
while (cleanups.length) cleanups.pop()!();
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
function workspace(): string {
|
|
15
|
+
const dir = mkdtempSync(path.join(tmpdir(), 'transcode-diff-'));
|
|
16
|
+
cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
|
|
17
|
+
return dir;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
describe('tool diff plumbing', () => {
|
|
21
|
+
test('edit_file returns a unified diff via invokeTool', async () => {
|
|
22
|
+
const dir = workspace();
|
|
23
|
+
writeFileSync(path.join(dir, 'a.txt'), 'one\ntwo\nthree\n');
|
|
24
|
+
const session = createToolSession(dir);
|
|
25
|
+
|
|
26
|
+
await invokeTool(readFileTool, { path: 'a.txt' }, { cwd: dir, session });
|
|
27
|
+
const result = await invokeTool(
|
|
28
|
+
editFileTool,
|
|
29
|
+
{ path: 'a.txt', old_string: 'two', new_string: 'TWO' },
|
|
30
|
+
{ cwd: dir, session },
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
expect(result.ok).toBe(true);
|
|
34
|
+
expect(result.diff).toBeDefined();
|
|
35
|
+
expect(result.diff).toContain('-two');
|
|
36
|
+
expect(result.diff).toContain('+TWO');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('write_file returns an all-additions diff for a new file (capped)', async () => {
|
|
40
|
+
const dir = workspace();
|
|
41
|
+
const session = createToolSession(dir);
|
|
42
|
+
|
|
43
|
+
const result = await invokeTool(
|
|
44
|
+
writeFileTool,
|
|
45
|
+
{ path: 'new.txt', content: 'l1\nl2\nl3\n' },
|
|
46
|
+
{ cwd: dir, session },
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
expect(result.ok).toBe(true);
|
|
50
|
+
expect(result.diff).toBeDefined();
|
|
51
|
+
expect(result.diff).toContain('+l1');
|
|
52
|
+
expect(result.diff).toContain('+l3');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('write_file returns a line diff when overwriting', async () => {
|
|
56
|
+
const dir = workspace();
|
|
57
|
+
writeFileSync(path.join(dir, 'a.txt'), 'keep\nold\n');
|
|
58
|
+
const session = createToolSession(dir);
|
|
59
|
+
|
|
60
|
+
await invokeTool(readFileTool, { path: 'a.txt' }, { cwd: dir, session });
|
|
61
|
+
const result = await invokeTool(
|
|
62
|
+
writeFileTool,
|
|
63
|
+
{ path: 'a.txt', content: 'keep\nnew\n' },
|
|
64
|
+
{ cwd: dir, session },
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
expect(result.ok).toBe(true);
|
|
68
|
+
expect(result.diff).toContain('-old');
|
|
69
|
+
expect(result.diff).toContain('+new');
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('plain string execute results carry no diff', async () => {
|
|
73
|
+
const dir = workspace();
|
|
74
|
+
writeFileSync(path.join(dir, 'a.txt'), 'hello\n');
|
|
75
|
+
const session = createToolSession(dir);
|
|
76
|
+
|
|
77
|
+
const result = await invokeTool(readFileTool, { path: 'a.txt' }, { cwd: dir, session });
|
|
78
|
+
expect(result.ok).toBe(true);
|
|
79
|
+
expect(result.diff).toBeUndefined();
|
|
80
|
+
});
|
|
81
|
+
});
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { lineDiff } from './diff.js';
|
|
3
|
+
|
|
4
|
+
describe('lineDiff', () => {
|
|
5
|
+
test('returns empty string for identical content', () => {
|
|
6
|
+
expect(lineDiff('a\nb\nc\n', 'a\nb\nc\n')).toBe('');
|
|
7
|
+
expect(lineDiff('', '')).toBe('');
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test('shows a middle line change with full context on a small file', () => {
|
|
11
|
+
const diff = lineDiff('a\nb\nc\n', 'a\nX\nc\n');
|
|
12
|
+
expect(diff).toBe('@@ -1,3 +1,3 @@\n a\n-b\n+X\n c');
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test('shows an insertion', () => {
|
|
16
|
+
const diff = lineDiff('a\nb\n', 'a\nX\nb\n');
|
|
17
|
+
expect(diff).toBe('@@ -1,2 +1,3 @@\n a\n+X\n b');
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('shows a deletion', () => {
|
|
21
|
+
const diff = lineDiff('a\nb\nc\n', 'a\nc\n');
|
|
22
|
+
expect(diff).toBe('@@ -1,3 +1,2 @@\n a\n-b\n c');
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test('insertion at the very top shows following context lines', () => {
|
|
26
|
+
const diff = lineDiff('b\nc\n', 'X\nb\nc\n');
|
|
27
|
+
expect(diff).toBe('@@ -1,2 +1,3 @@\n+X\n b\n c');
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('insertion into empty content uses the zero-count old range', () => {
|
|
31
|
+
expect(lineDiff('', 'X\n')).toBe('@@ -0,0 +1,1 @@\n+X');
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('limits context to 3 lines around a change', () => {
|
|
35
|
+
const lines = Array.from({ length: 11 }, (_, i) => `l${i + 1}`);
|
|
36
|
+
const changed = [...lines];
|
|
37
|
+
changed[5] = 'CHANGED'; // l6
|
|
38
|
+
const diff = lineDiff(`${lines.join('\n')}\n`, `${changed.join('\n')}\n`);
|
|
39
|
+
|
|
40
|
+
expect(diff.startsWith('@@ -3,7 +3,7 @@')).toBe(true);
|
|
41
|
+
expect(diff).toContain('-l6');
|
|
42
|
+
expect(diff).toContain('+CHANGED');
|
|
43
|
+
expect(diff).toContain(' l3');
|
|
44
|
+
expect(diff).toContain(' l9');
|
|
45
|
+
expect(diff).not.toContain(' l2');
|
|
46
|
+
expect(diff).not.toContain(' l10');
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('splits distant changes into separate hunks', () => {
|
|
50
|
+
const old = Array.from({ length: 30 }, (_, i) => `l${i + 1}`);
|
|
51
|
+
const next = [...old];
|
|
52
|
+
next[1] = 'A'; // l2
|
|
53
|
+
next[27] = 'B'; // l28 — 25 lines apart, beyond merge distance
|
|
54
|
+
const diff = lineDiff(`${old.join('\n')}\n`, `${next.join('\n')}\n`);
|
|
55
|
+
|
|
56
|
+
const hunks = diff.split('\n').filter((line) => line.startsWith('@@'));
|
|
57
|
+
expect(hunks.length).toBe(2);
|
|
58
|
+
expect(diff).toContain('+A');
|
|
59
|
+
expect(diff).toContain('+B');
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('merges changes within the merge distance into one hunk', () => {
|
|
63
|
+
const old = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
|
|
64
|
+
const next = [...old];
|
|
65
|
+
next[0] = 'A';
|
|
66
|
+
next[8] = 'I'; // gap of 7 context lines < 2*context+2 → merged
|
|
67
|
+
const diff = lineDiff(`${old.join('\n')}\n`, `${next.join('\n')}\n`);
|
|
68
|
+
|
|
69
|
+
const hunks = diff.split('\n').filter((line) => line.startsWith('@@'));
|
|
70
|
+
expect(hunks.length).toBe(1);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('falls back to whole-block replace when the change is huge', () => {
|
|
74
|
+
const old = Array.from({ length: 2500 }, (_, i) => `old${i}`);
|
|
75
|
+
const next = Array.from({ length: 2500 }, (_, i) => `new${i}`);
|
|
76
|
+
const diff = lineDiff(`${old.join('\n')}\n`, `${next.join('\n')}\n`);
|
|
77
|
+
|
|
78
|
+
expect(diff.startsWith('@@ -1,2500 +1,2500 @@')).toBe(true);
|
|
79
|
+
expect(diff.split('\n').filter((l) => l.startsWith('-')).length).toBe(2500);
|
|
80
|
+
expect(diff.split('\n').filter((l) => l.startsWith('+')).length).toBe(2500);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal unified-diff generator for TUI display. No dependencies.
|
|
3
|
+
*
|
|
4
|
+
* Strategy: trim the common prefix/suffix lines (edits are localized), run an
|
|
5
|
+
* LCS DP over the remaining middle, and fall back to a whole-block replace
|
|
6
|
+
* when the middle is huge so pathological rewrites stay fast.
|
|
7
|
+
*
|
|
8
|
+
* Limitation: a trailing-newline-only difference is not detected (the last
|
|
9
|
+
* line compares equal either way). Acceptable for display purposes.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
type Op = { t: 0 | 1 | 2; line: string }; // 0 = context, 1 = delete, 2 = add
|
|
13
|
+
|
|
14
|
+
const FALLBACK_MIDDLE_LIMIT = 4000;
|
|
15
|
+
|
|
16
|
+
function splitLines(text: string): string[] {
|
|
17
|
+
if (text === '') return [];
|
|
18
|
+
const body = text.endsWith('\n') ? text.slice(0, -1) : text;
|
|
19
|
+
return body.split('\n');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function editScript(midA: string[], midB: string[]): Op[] {
|
|
23
|
+
const ops: Op[] = [];
|
|
24
|
+
if (midA.length + midB.length > FALLBACK_MIDDLE_LIMIT) {
|
|
25
|
+
for (const line of midA) ops.push({ t: 1, line });
|
|
26
|
+
for (const line of midB) ops.push({ t: 2, line });
|
|
27
|
+
return ops;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// dp[i * (m + 1) + j] = LCS length of midA[i:] and midB[j:]
|
|
31
|
+
const n = midA.length;
|
|
32
|
+
const m = midB.length;
|
|
33
|
+
const dp = new Int32Array((n + 1) * (m + 1));
|
|
34
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
35
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
36
|
+
dp[i * (m + 1) + j] =
|
|
37
|
+
midA[i] === midB[j]
|
|
38
|
+
? dp[(i + 1) * (m + 1) + j + 1] + 1
|
|
39
|
+
: Math.max(dp[(i + 1) * (m + 1) + j], dp[i * (m + 1) + j + 1]);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let i = 0;
|
|
44
|
+
let j = 0;
|
|
45
|
+
while (i < n && j < m) {
|
|
46
|
+
if (midA[i] === midB[j]) {
|
|
47
|
+
ops.push({ t: 0, line: midA[i] });
|
|
48
|
+
i++;
|
|
49
|
+
j++;
|
|
50
|
+
} else if (dp[(i + 1) * (m + 1) + j] >= dp[i * (m + 1) + j + 1]) {
|
|
51
|
+
ops.push({ t: 1, line: midA[i] });
|
|
52
|
+
i++;
|
|
53
|
+
} else {
|
|
54
|
+
ops.push({ t: 2, line: midB[j] });
|
|
55
|
+
j++;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
while (i < n) ops.push({ t: 1, line: midA[i++] });
|
|
59
|
+
while (j < m) ops.push({ t: 2, line: midB[j++] });
|
|
60
|
+
return ops;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Generates a unified diff (hunks only, no ---/+++ headers). '' when equal. */
|
|
64
|
+
export function lineDiff(a: string, b: string, context = 3): string {
|
|
65
|
+
const linesA = splitLines(a);
|
|
66
|
+
const linesB = splitLines(b);
|
|
67
|
+
|
|
68
|
+
let prefix = 0;
|
|
69
|
+
while (prefix < linesA.length && prefix < linesB.length && linesA[prefix] === linesB[prefix]) {
|
|
70
|
+
prefix++;
|
|
71
|
+
}
|
|
72
|
+
let suffix = 0;
|
|
73
|
+
while (
|
|
74
|
+
suffix < linesA.length - prefix &&
|
|
75
|
+
suffix < linesB.length - prefix &&
|
|
76
|
+
linesA[linesA.length - 1 - suffix] === linesB[linesB.length - 1 - suffix]
|
|
77
|
+
) {
|
|
78
|
+
suffix++;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const midA = linesA.slice(prefix, linesA.length - suffix);
|
|
82
|
+
const midB = linesB.slice(prefix, linesB.length - suffix);
|
|
83
|
+
|
|
84
|
+
const ops: Op[] = [];
|
|
85
|
+
for (let k = 0; k < prefix; k++) ops.push({ t: 0, line: linesA[k] });
|
|
86
|
+
ops.push(...editScript(midA, midB));
|
|
87
|
+
for (let k = linesA.length - suffix; k < linesA.length; k++) ops.push({ t: 0, line: linesA[k] });
|
|
88
|
+
|
|
89
|
+
// Group change ops into hunks; merge when the context gap between changes
|
|
90
|
+
// is small enough that the windows would touch.
|
|
91
|
+
const changeIndices: number[] = [];
|
|
92
|
+
for (let index = 0; index < ops.length; index++) {
|
|
93
|
+
if (ops[index].t !== 0) changeIndices.push(index);
|
|
94
|
+
}
|
|
95
|
+
if (changeIndices.length === 0) return '';
|
|
96
|
+
|
|
97
|
+
// a/b line counters before each op index (ctx consumes both sides).
|
|
98
|
+
const aBefore: number[] = new Array(ops.length + 1);
|
|
99
|
+
const bBefore: number[] = new Array(ops.length + 1);
|
|
100
|
+
aBefore[0] = 0;
|
|
101
|
+
bBefore[0] = 0;
|
|
102
|
+
for (let index = 0; index < ops.length; index++) {
|
|
103
|
+
aBefore[index + 1] = aBefore[index] + (ops[index].t === 2 ? 0 : 1);
|
|
104
|
+
bBefore[index + 1] = bBefore[index] + (ops[index].t === 1 ? 0 : 1);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const mergeDistance = 2 * context + 1;
|
|
108
|
+
const hunks: Array<{ start: number; end: number }> = []; // op window [start, end)
|
|
109
|
+
let groupFirst = changeIndices[0];
|
|
110
|
+
let groupLast = changeIndices[0];
|
|
111
|
+
for (let index = 1; index <= changeIndices.length; index++) {
|
|
112
|
+
const next = changeIndices[index];
|
|
113
|
+
if (next !== undefined && next - groupLast - 1 <= mergeDistance) {
|
|
114
|
+
groupLast = next;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
hunks.push({
|
|
118
|
+
start: Math.max(0, groupFirst - context),
|
|
119
|
+
end: Math.min(ops.length, groupLast + context + 1),
|
|
120
|
+
});
|
|
121
|
+
if (next !== undefined) {
|
|
122
|
+
groupFirst = next;
|
|
123
|
+
groupLast = next;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const parts: string[] = [];
|
|
128
|
+
for (const hunk of hunks) {
|
|
129
|
+
let oldCount = 0;
|
|
130
|
+
let newCount = 0;
|
|
131
|
+
for (let index = hunk.start; index < hunk.end; index++) {
|
|
132
|
+
if (ops[index].t !== 2) oldCount++;
|
|
133
|
+
if (ops[index].t !== 1) newCount++;
|
|
134
|
+
}
|
|
135
|
+
// Zero-count ranges point at the line before the window.
|
|
136
|
+
const oldStart = oldCount === 0 ? aBefore[hunk.start] : aBefore[hunk.start] + 1;
|
|
137
|
+
const newStart = newCount === 0 ? bBefore[hunk.start] : bBefore[hunk.start] + 1;
|
|
138
|
+
parts.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
|
|
139
|
+
for (let index = hunk.start; index < hunk.end; index++) {
|
|
140
|
+
const op = ops[index];
|
|
141
|
+
parts.push(`${op.t === 0 ? ' ' : op.t === 1 ? '-' : '+'}${op.line}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return parts.join('\n');
|
|
146
|
+
}
|