@trans-ai/trans-code 0.1.3 → 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 +10 -3
- 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 +26 -3
- 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 +8 -2
- package/src/screens/REPL.tsx +114 -10
- 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,108 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import type { AgentTool } from './types.js';
|
|
5
|
+
import {
|
|
6
|
+
MAX_GLOB_FILES,
|
|
7
|
+
MAX_GREP_MATCHES,
|
|
8
|
+
displayPath,
|
|
9
|
+
matchesGlob,
|
|
10
|
+
readTextIfTextFile,
|
|
11
|
+
resolveInsideWorkspace,
|
|
12
|
+
walkFiles,
|
|
13
|
+
} from './fs-utils.js';
|
|
14
|
+
|
|
15
|
+
export const globTool: AgentTool = {
|
|
16
|
+
name: 'glob',
|
|
17
|
+
description:
|
|
18
|
+
'Find files by glob pattern (for example "**/*.ts" or "src/**/test*.js"). ' +
|
|
19
|
+
'Returns workspace-relative paths.',
|
|
20
|
+
kind: 'search',
|
|
21
|
+
isMutating: false,
|
|
22
|
+
schema: z.object({
|
|
23
|
+
pattern: z.string().describe('Glob pattern, matched against workspace-relative paths'),
|
|
24
|
+
path: z.string().nullable().optional().describe('Directory to search in (default: workspace root)'),
|
|
25
|
+
}),
|
|
26
|
+
title: (input) => `search: ${String(input.pattern ?? '')}`,
|
|
27
|
+
async execute(input, ctx) {
|
|
28
|
+
const root = resolveInsideWorkspace(ctx.cwd, String(input.path ?? '.'));
|
|
29
|
+
const pattern = String(input.pattern);
|
|
30
|
+
const files = await walkFiles(root, ctx.signal);
|
|
31
|
+
const matches: string[] = [];
|
|
32
|
+
|
|
33
|
+
for (const file of files) {
|
|
34
|
+
const relative = path.relative(root, file).replace(/\\/g, '/');
|
|
35
|
+
if (matchesGlob(pattern, relative)) {
|
|
36
|
+
matches.push(displayPath(ctx.cwd, file));
|
|
37
|
+
if (matches.length >= MAX_GLOB_FILES) break;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
matches.sort();
|
|
42
|
+
if (matches.length === 0) return `No files matched ${pattern}`;
|
|
43
|
+
return (
|
|
44
|
+
matches.join('\n') +
|
|
45
|
+
(matches.length >= MAX_GLOB_FILES ? `\n... (limited to ${MAX_GLOB_FILES} files)` : '')
|
|
46
|
+
);
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export const grepTool: AgentTool = {
|
|
51
|
+
name: 'grep',
|
|
52
|
+
description:
|
|
53
|
+
'Search file contents with a regular expression. Returns path:line: text matches. ' +
|
|
54
|
+
'Use include to restrict files by glob (for example "**/*.ts").',
|
|
55
|
+
kind: 'search',
|
|
56
|
+
isMutating: false,
|
|
57
|
+
schema: z.object({
|
|
58
|
+
pattern: z.string().describe('JavaScript regular expression to search for'),
|
|
59
|
+
path: z.string().nullable().optional().describe('Directory or file to search (default: workspace root)'),
|
|
60
|
+
include: z.string().nullable().optional().describe('Glob that file paths must match'),
|
|
61
|
+
ignore_case: z.boolean().nullable().optional().describe('Case-insensitive search'),
|
|
62
|
+
}),
|
|
63
|
+
title: (input) => `search: ${String(input.pattern ?? '')}`,
|
|
64
|
+
async execute(input, ctx) {
|
|
65
|
+
let regex: RegExp;
|
|
66
|
+
try {
|
|
67
|
+
regex = new RegExp(String(input.pattern), input.ignore_case ? 'i' : '');
|
|
68
|
+
} catch (error) {
|
|
69
|
+
throw new Error(`Invalid regular expression: ${(error as Error).message}`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const target = resolveInsideWorkspace(ctx.cwd, String(input.path ?? '.'));
|
|
73
|
+
const stat = await fs.stat(target);
|
|
74
|
+
const files = stat.isFile() ? [target] : await walkFiles(target, ctx.signal);
|
|
75
|
+
const include = input.include ? String(input.include) : undefined;
|
|
76
|
+
const results: string[] = [];
|
|
77
|
+
|
|
78
|
+
for (const file of files) {
|
|
79
|
+
if (ctx.signal?.aborted) throw new Error('Aborted');
|
|
80
|
+
const relative = displayPath(ctx.cwd, file);
|
|
81
|
+
if (include && !matchesGlob(include, relative)) continue;
|
|
82
|
+
|
|
83
|
+
let content: string | null;
|
|
84
|
+
try {
|
|
85
|
+
content = await readTextIfTextFile(file);
|
|
86
|
+
} catch {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (content === null) continue;
|
|
90
|
+
|
|
91
|
+
const lines = content.split('\n');
|
|
92
|
+
for (let index = 0; index < lines.length; index++) {
|
|
93
|
+
regex.lastIndex = 0;
|
|
94
|
+
if (!regex.test(lines[index])) continue;
|
|
95
|
+
const text = lines[index].length > 500 ? `${lines[index].slice(0, 500)}...` : lines[index];
|
|
96
|
+
results.push(`${relative}:${index + 1}: ${text}`);
|
|
97
|
+
if (results.length >= MAX_GREP_MATCHES) break;
|
|
98
|
+
}
|
|
99
|
+
if (results.length >= MAX_GREP_MATCHES) break;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (results.length === 0) return `No matches for ${input.pattern}`;
|
|
103
|
+
return (
|
|
104
|
+
results.join('\n') +
|
|
105
|
+
(results.length >= MAX_GREP_MATCHES ? `\n... (limited to ${MAX_GREP_MATCHES} matches)` : '')
|
|
106
|
+
);
|
|
107
|
+
},
|
|
108
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { afterEach, 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 { createToolSession, hasFileBeenRead, markFileRead } from './session.js';
|
|
6
|
+
|
|
7
|
+
const cleanups: Array<() => void> = [];
|
|
8
|
+
afterEach(() => {
|
|
9
|
+
while (cleanups.length) cleanups.pop()!();
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
describe('createToolSession', () => {
|
|
13
|
+
test('initializes cwd and rootCwd from the workspace root', () => {
|
|
14
|
+
const dir = mkdtempSync(path.join(tmpdir(), 'transcode-session-'));
|
|
15
|
+
cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
|
|
16
|
+
|
|
17
|
+
const session = createToolSession(dir);
|
|
18
|
+
expect(session.cwd).toBe(dir);
|
|
19
|
+
expect(session.rootCwd).toBe(dir);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('starts with an empty read-file state', () => {
|
|
23
|
+
const session = createToolSession('/tmp');
|
|
24
|
+
expect(session.readFileState.size).toBe(0);
|
|
25
|
+
expect(hasFileBeenRead(session, '/tmp/whatever.txt')).toBe(false);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('markFileRead records absolute paths and hasFileBeenRead finds them', () => {
|
|
29
|
+
const session = createToolSession('/tmp');
|
|
30
|
+
markFileRead(session, '/tmp/a.txt');
|
|
31
|
+
expect(hasFileBeenRead(session, '/tmp/a.txt')).toBe(true);
|
|
32
|
+
expect(hasFileBeenRead(session, '/tmp/b.txt')).toBe(false);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* State that persists across tool calls within one conversation/session:
|
|
5
|
+
* the shell's current working directory (so `cd` survives between bash
|
|
6
|
+
* calls), the lazily-created login-shell environment snapshot, and the set
|
|
7
|
+
* of files the model has read this session (read-before-edit/write guard).
|
|
8
|
+
*/
|
|
9
|
+
export interface ToolSession {
|
|
10
|
+
/** Live working directory; updated by the bash tool after every command. */
|
|
11
|
+
cwd: string;
|
|
12
|
+
/** Workspace root the session started in; cwd-recovery fallback. */
|
|
13
|
+
rootCwd: string;
|
|
14
|
+
/** Lazily-created shell environment snapshot file path (bash/zsh script). */
|
|
15
|
+
shellSnapshot?: Promise<string | undefined>;
|
|
16
|
+
/** Absolute paths of files the model has read (or written) this session. */
|
|
17
|
+
readFileState: Set<string>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createToolSession(rootCwd: string): ToolSession {
|
|
21
|
+
const absolute = path.resolve(rootCwd);
|
|
22
|
+
return {
|
|
23
|
+
cwd: absolute,
|
|
24
|
+
rootCwd: absolute,
|
|
25
|
+
readFileState: new Set<string>(),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function markFileRead(session: ToolSession, absolutePath: string): void {
|
|
30
|
+
session.readFileState.add(path.resolve(absolutePath));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function hasFileBeenRead(session: ToolSession, absolutePath: string): boolean {
|
|
34
|
+
return session.readFileState.has(path.resolve(absolutePath));
|
|
35
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import type { ToolSession } from './session.js';
|
|
3
|
+
|
|
4
|
+
export type ToolKind =
|
|
5
|
+
| 'read'
|
|
6
|
+
| 'edit'
|
|
7
|
+
| 'delete'
|
|
8
|
+
| 'move'
|
|
9
|
+
| 'search'
|
|
10
|
+
| 'execute'
|
|
11
|
+
| 'think'
|
|
12
|
+
| 'fetch'
|
|
13
|
+
| 'switch_mode'
|
|
14
|
+
| 'other';
|
|
15
|
+
|
|
16
|
+
export interface ToolContext {
|
|
17
|
+
cwd: string;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
/** Session-scoped state shared across tool calls (shell cwd, read files). */
|
|
20
|
+
session: ToolSession;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Rich execute result: model-facing output plus an optional UI-facing diff. */
|
|
24
|
+
export interface ToolOutput {
|
|
25
|
+
output: string;
|
|
26
|
+
/** Unified diff text for TUI rendering; never sent to the model. */
|
|
27
|
+
diff?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface AgentTool {
|
|
31
|
+
name: string;
|
|
32
|
+
description: string;
|
|
33
|
+
schema: z.ZodObject<z.ZodRawShape>;
|
|
34
|
+
kind: ToolKind;
|
|
35
|
+
isMutating: boolean;
|
|
36
|
+
title(input: Record<string, unknown>): string;
|
|
37
|
+
execute(input: Record<string, unknown>, ctx: ToolContext): Promise<string | ToolOutput>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface InvokeResult {
|
|
41
|
+
ok: boolean;
|
|
42
|
+
output: string;
|
|
43
|
+
/** Unified diff text for UI rendering, when the tool produced one. */
|
|
44
|
+
diff?: string;
|
|
45
|
+
}
|
package/src/cli.ts
CHANGED
|
@@ -4,7 +4,7 @@ const USAGE = `transcode v${VERSION}
|
|
|
4
4
|
|
|
5
5
|
Usage:
|
|
6
6
|
transcode Start the interactive REPL
|
|
7
|
-
transcode acp Start the ACP stdio server (for multica and other ACP clients)
|
|
7
|
+
transcode acp Start the ACP stdio server (for transonce, multica and other ACP clients)
|
|
8
8
|
transcode upgrade Upgrade the npm global install to the latest version
|
|
9
9
|
transcode --version Print the version
|
|
10
10
|
transcode --help Show this help
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { findCommand, getCommands } from './commands.js';
|
|
3
|
+
|
|
4
|
+
describe('init command registration', () => {
|
|
5
|
+
test('is registered so /help lists it', () => {
|
|
6
|
+
const init = findCommand('init');
|
|
7
|
+
expect(init).toBeDefined();
|
|
8
|
+
expect(init?.description.length).toBeGreaterThan(0);
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
test('getCommands exposes it alongside the others', () => {
|
|
12
|
+
const names = getCommands().map((command) => command.name);
|
|
13
|
+
expect(names).toContain('init');
|
|
14
|
+
expect(names).toContain('help');
|
|
15
|
+
expect(names).toContain('exit');
|
|
16
|
+
});
|
|
17
|
+
});
|
package/src/commands.ts
CHANGED
|
@@ -37,6 +37,15 @@ const commands: Command[] = [
|
|
|
37
37
|
};
|
|
38
38
|
},
|
|
39
39
|
},
|
|
40
|
+
{
|
|
41
|
+
name: 'init',
|
|
42
|
+
description: 'Analyze the project and write TRANS.md',
|
|
43
|
+
// Intercepted by the REPL before command dispatch (like /models) so the
|
|
44
|
+
// analysis runs through the full agent loop with tools and permissions.
|
|
45
|
+
execute: () => ({
|
|
46
|
+
output: 'Analyzing the project and writing TRANS.md…',
|
|
47
|
+
}),
|
|
48
|
+
},
|
|
40
49
|
{
|
|
41
50
|
name: 'clear',
|
|
42
51
|
description: 'Clear screen',
|
package/src/provider/provider.ts
CHANGED
|
@@ -149,6 +149,12 @@ function defaultModelSpec(): string {
|
|
|
149
149
|
const explicit = process.env.TRANSCODE_MODEL?.trim();
|
|
150
150
|
if (explicit) return explicit;
|
|
151
151
|
|
|
152
|
+
// A model saved from the REPL `models` flow (~/.transcode.json) applies
|
|
153
|
+
// everywhere — REPL, ACP (`transcode acp`), and model checks — so an
|
|
154
|
+
// integration host without an explicit model gets the user's choice.
|
|
155
|
+
const preferred = preferredModelId();
|
|
156
|
+
if (preferred) return preferred;
|
|
157
|
+
|
|
152
158
|
if (anthropicAuthToken() || anthropicGatewayUrl()) {
|
|
153
159
|
const fable = fableModelName();
|
|
154
160
|
if (fable) return `anthropic:${fable}`;
|
|
@@ -238,8 +244,8 @@ export function resolveModel(spec?: string): ResolvedModel {
|
|
|
238
244
|
}
|
|
239
245
|
|
|
240
246
|
// Bare unknown model name: route through a provider guessed from the name,
|
|
241
|
-
// then fall back to TRANSCODE_DEFAULT_PROVIDER. This lets multica
|
|
242
|
-
// a model id without remembering the provider:model syntax.
|
|
247
|
+
// then fall back to TRANSCODE_DEFAULT_PROVIDER. This lets transonce/multica
|
|
248
|
+
// users type a model id without remembering the provider:model syntax.
|
|
243
249
|
const lower = raw.toLowerCase();
|
|
244
250
|
let fallback = PROVIDER_DEFAULTS[defaultProvider()] ?? PROVIDER_DEFAULTS.openai;
|
|
245
251
|
if (lower.startsWith('claude')) fallback = PROVIDER_DEFAULTS.anthropic;
|
package/src/screens/REPL.tsx
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import { Box, Text, useInput, useApp } from 'ink';
|
|
2
|
-
import { useState, useCallback, useRef } from 'react';
|
|
2
|
+
import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
|
|
3
|
+
import path from 'node:path';
|
|
3
4
|
import { findCommand, getCommands, type CommandContext } from '../commands.js';
|
|
4
5
|
import { getAvailableModels, createProviderWithKey, createProvider, setPreferredModel, type ModelId } from '../provider/provider.js';
|
|
5
6
|
import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
|
|
6
|
-
import {
|
|
7
|
+
import { createToolSession } from '../agent/tools/index.js';
|
|
8
|
+
import { walkFiles } from '../agent/tools/fs-utils.js';
|
|
9
|
+
import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
|
|
10
|
+
import { renderDiff } from './diff-render.js';
|
|
11
|
+
import { buildSystemPrompt, INIT_PROMPT, loadProjectContext } from '../agent/system-prompt.js';
|
|
7
12
|
import { HumanMessage, SystemMessage, type BaseMessage } from '@langchain/core/messages';
|
|
8
13
|
|
|
9
14
|
interface HistoryEntry {
|
|
@@ -54,6 +59,45 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
54
59
|
const busyRef = useRef(false);
|
|
55
60
|
const abortRef = useRef<AbortController | undefined>(undefined);
|
|
56
61
|
const messagesRef = useRef<BaseMessage[]>([]);
|
|
62
|
+
// One tool session per process: bash cwd and read-file state persist
|
|
63
|
+
// across prompts, like the ACP session.
|
|
64
|
+
const toolSessionRef = useRef(createToolSession(process.cwd()));
|
|
65
|
+
|
|
66
|
+
// @-mention file completion: lazy file list, active query, dismissed flag.
|
|
67
|
+
const [fileList, setFileList] = useState<string[] | null>(null);
|
|
68
|
+
const [mentionCursor, setMentionCursor] = useState(0);
|
|
69
|
+
const [mentionDismissed, setMentionDismissed] = useState(false);
|
|
70
|
+
const mention = phase === 'idle' && !busy ? mentionQuery(input) : null;
|
|
71
|
+
const mentionActive = mention !== null && !mentionDismissed;
|
|
72
|
+
|
|
73
|
+
useEffect(() => {
|
|
74
|
+
if (mention === null) setMentionDismissed(false);
|
|
75
|
+
}, [mention]);
|
|
76
|
+
useEffect(() => {
|
|
77
|
+
setMentionCursor(0);
|
|
78
|
+
}, [mention]);
|
|
79
|
+
// Load the workspace file list on first use; refresh on next open after a
|
|
80
|
+
// prompt so files the agent created/removed show up.
|
|
81
|
+
useEffect(() => {
|
|
82
|
+
if (!mentionActive || fileList) return;
|
|
83
|
+
let cancelled = false;
|
|
84
|
+
walkFiles(process.cwd())
|
|
85
|
+
.then((files) => {
|
|
86
|
+
if (cancelled) return;
|
|
87
|
+
setFileList(
|
|
88
|
+
files.map((file) => path.relative(process.cwd(), file).replace(/\\/g, '/')).sort(),
|
|
89
|
+
);
|
|
90
|
+
})
|
|
91
|
+
.catch(() => setFileList([]));
|
|
92
|
+
return () => {
|
|
93
|
+
cancelled = true;
|
|
94
|
+
};
|
|
95
|
+
}, [mentionActive, fileList]);
|
|
96
|
+
|
|
97
|
+
const mentionCandidates = useMemo(
|
|
98
|
+
() => (mentionActive && fileList ? filterFiles(fileList, mention ?? '', 8) : []),
|
|
99
|
+
[mentionActive, fileList, mention],
|
|
100
|
+
);
|
|
57
101
|
const pendingPermissionRef = useRef<{
|
|
58
102
|
request: PermissionRequest;
|
|
59
103
|
resolve: (allow: boolean) => void;
|
|
@@ -96,14 +140,23 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
96
140
|
);
|
|
97
141
|
|
|
98
142
|
const runChat = useCallback(
|
|
99
|
-
async (text: string) => {
|
|
143
|
+
async (text: string, display?: string) => {
|
|
100
144
|
setBusyBoth(true);
|
|
101
145
|
const controller = new AbortController();
|
|
102
146
|
abortRef.current = controller;
|
|
103
|
-
addHistory({ input: text, output: '' });
|
|
147
|
+
addHistory({ input: display ?? text, output: '' });
|
|
104
148
|
|
|
105
149
|
try {
|
|
106
|
-
const
|
|
150
|
+
const provider =
|
|
151
|
+
process.env.TRANSCODE_MOCK === '1'
|
|
152
|
+
? undefined
|
|
153
|
+
: createProvider(ctx.modelId);
|
|
154
|
+
|
|
155
|
+
const projectContext = await loadProjectContext(process.cwd());
|
|
156
|
+
const systemPrompt = buildSystemPrompt(
|
|
157
|
+
projectContext,
|
|
158
|
+
provider ? { modelName: provider.config.name } : undefined,
|
|
159
|
+
);
|
|
107
160
|
if (messagesRef.current[0]?.getType() === 'system') {
|
|
108
161
|
messagesRef.current[0] = new SystemMessage(systemPrompt);
|
|
109
162
|
} else {
|
|
@@ -111,11 +164,6 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
111
164
|
}
|
|
112
165
|
messagesRef.current.push(new HumanMessage(text));
|
|
113
166
|
|
|
114
|
-
const provider =
|
|
115
|
-
process.env.TRANSCODE_MOCK === '1'
|
|
116
|
-
? undefined
|
|
117
|
-
: createProvider(ctx.modelId);
|
|
118
|
-
|
|
119
167
|
let lastWasTool = false;
|
|
120
168
|
const result = await runAgentLoop({
|
|
121
169
|
model: provider?.model,
|
|
@@ -123,6 +171,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
123
171
|
messages: messagesRef.current,
|
|
124
172
|
systemPrompt,
|
|
125
173
|
signal: controller.signal,
|
|
174
|
+
toolSession: toolSessionRef.current,
|
|
126
175
|
onEvent: event => {
|
|
127
176
|
if (event.type === 'text') {
|
|
128
177
|
appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
|
|
@@ -132,6 +181,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
132
181
|
lastWasTool = true;
|
|
133
182
|
} else if (event.type === 'tool_result') {
|
|
134
183
|
appendChatOutput(event.ok ? ' ✓' : ' ✗');
|
|
184
|
+
if (event.diff) appendChatOutput(`\n${renderDiff(event.diff)}`);
|
|
135
185
|
lastWasTool = true;
|
|
136
186
|
}
|
|
137
187
|
},
|
|
@@ -149,6 +199,8 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
149
199
|
} finally {
|
|
150
200
|
setBusyBoth(false);
|
|
151
201
|
abortRef.current = undefined;
|
|
202
|
+
// The agent may have created/removed files; rebuild @-completion list.
|
|
203
|
+
setFileList(null);
|
|
152
204
|
dragFlush();
|
|
153
205
|
}
|
|
154
206
|
},
|
|
@@ -208,6 +260,14 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
208
260
|
return;
|
|
209
261
|
}
|
|
210
262
|
|
|
263
|
+
if (cmdName === 'init') {
|
|
264
|
+
commitInput('');
|
|
265
|
+
setHistoryIndex(-1);
|
|
266
|
+
setSavedInput('');
|
|
267
|
+
await runChat(INIT_PROMPT, trimmed);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
211
271
|
const cmd = findCommand(cmdName);
|
|
212
272
|
|
|
213
273
|
if (cmd) {
|
|
@@ -247,6 +307,11 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
247
307
|
// eslint-disable-next-line no-console
|
|
248
308
|
console.error(`CB ${JSON.stringify(ch)} ret=${key.return} esc=${key.escape}`);
|
|
249
309
|
}
|
|
310
|
+
// @-mention popup: Esc dismisses it instead of exiting the app.
|
|
311
|
+
if (key.escape && mentionActive && mentionCandidates.length > 0) {
|
|
312
|
+
setMentionDismissed(true);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
250
315
|
if (key.escape) {
|
|
251
316
|
// While generating, Esc cancels instead of exiting.
|
|
252
317
|
if (busyRef.current && abortRef.current) {
|
|
@@ -295,6 +360,23 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
295
360
|
return;
|
|
296
361
|
}
|
|
297
362
|
|
|
363
|
+
// @-mention popup navigation and completion (takes precedence over
|
|
364
|
+
// history navigation, tab completion and submission).
|
|
365
|
+
if (phase === 'idle' && mentionActive && mentionCandidates.length > 0) {
|
|
366
|
+
if (key.upArrow) {
|
|
367
|
+
setMentionCursor(prev => (prev - 1 + mentionCandidates.length) % mentionCandidates.length);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
if (key.downArrow) {
|
|
371
|
+
setMentionCursor(prev => (prev + 1) % mentionCandidates.length);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
if (key.tab || key.return) {
|
|
375
|
+
commitInput(applyCompletion(inputRef.current, mentionCandidates[mentionCursor]));
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
298
380
|
if (key.return) {
|
|
299
381
|
if (busyRef.current) return; // still generating; Esc cancels
|
|
300
382
|
handleSubmit(inputRef.current);
|
|
@@ -429,6 +511,28 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
429
511
|
</Box>
|
|
430
512
|
);
|
|
431
513
|
})()}
|
|
514
|
+
|
|
515
|
+
{phase === 'idle' && !busy && mentionActive && (
|
|
516
|
+
<Box flexDirection="column" marginLeft={2}>
|
|
517
|
+
{fileList === null ? (
|
|
518
|
+
<Text color="gray" dimColor>… loading files</Text>
|
|
519
|
+
) : mentionCandidates.length === 0 ? (
|
|
520
|
+
<Text color="gray" dimColor>no files match “{mention}”</Text>
|
|
521
|
+
) : (
|
|
522
|
+
<>
|
|
523
|
+
{mentionCandidates.map((file, i) => (
|
|
524
|
+
<Box key={file}>
|
|
525
|
+
<Text color={i === mentionCursor ? 'cyan' : 'gray'}>
|
|
526
|
+
{i === mentionCursor ? '❯ ' : ' '}
|
|
527
|
+
{file}
|
|
528
|
+
</Text>
|
|
529
|
+
</Box>
|
|
530
|
+
))}
|
|
531
|
+
<Text color="gray" dimColor>↑↓ navigate · tab/enter insert · esc close</Text>
|
|
532
|
+
</>
|
|
533
|
+
)}
|
|
534
|
+
</Box>
|
|
535
|
+
)}
|
|
432
536
|
</Box>
|
|
433
537
|
);
|
|
434
538
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { renderDiff } from './diff-render.js';
|
|
3
|
+
|
|
4
|
+
const GREEN = '\x1b[32m';
|
|
5
|
+
const RED = '\x1b[31m';
|
|
6
|
+
const CYAN = '\x1b[36m';
|
|
7
|
+
const RESET = '\x1b[0m';
|
|
8
|
+
|
|
9
|
+
describe('renderDiff', () => {
|
|
10
|
+
test('colors added, removed and hunk-header lines', () => {
|
|
11
|
+
const diff = '@@ -1,2 +1,2 @@\n context\n-old\n+new';
|
|
12
|
+
const out = renderDiff(diff);
|
|
13
|
+
const lines = out.split('\n');
|
|
14
|
+
expect(lines[0]).toBe(`${CYAN}@@ -1,2 +1,2 @@${RESET}`);
|
|
15
|
+
expect(lines[1]).toBe(' context');
|
|
16
|
+
expect(lines[2]).toBe(`${RED}-old${RESET}`);
|
|
17
|
+
expect(lines[3]).toBe(`${GREEN}+new${RESET}`);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('caps output and reports omitted lines', () => {
|
|
21
|
+
const diff = Array.from({ length: 6 }, (_, i) => `+line${i}`).join('\n');
|
|
22
|
+
const out = renderDiff(diff, 3);
|
|
23
|
+
expect(out.split('\n').length).toBe(4);
|
|
24
|
+
expect(out).toContain('... (3 more lines)');
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('empty diff renders empty', () => {
|
|
28
|
+
expect(renderDiff('')).toBe('');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('neutral lines like truncation markers stay uncolored', () => {
|
|
32
|
+
const out = renderDiff('+a\n... (+12 more lines)');
|
|
33
|
+
const lines = out.split('\n');
|
|
34
|
+
expect(lines[1]).toBe('... (+12 more lines)');
|
|
35
|
+
});
|
|
36
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renders a unified diff as an ANSI-colored string for the ink REPL.
|
|
3
|
+
* Added lines are green, removed red, hunk headers cyan; everything else
|
|
4
|
+
* (context, truncation markers) stays uncolored. Output is capped.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const GREEN = '\x1b[32m';
|
|
8
|
+
const RED = '\x1b[31m';
|
|
9
|
+
const CYAN = '\x1b[36m';
|
|
10
|
+
const RESET = '\x1b[0m';
|
|
11
|
+
|
|
12
|
+
export function renderDiff(diff: string, maxLines = 40): string {
|
|
13
|
+
if (!diff) return '';
|
|
14
|
+
const lines = diff.split('\n');
|
|
15
|
+
const shown = lines.slice(0, maxLines);
|
|
16
|
+
const colored = shown.map((line) => {
|
|
17
|
+
if (line.startsWith('+')) return `${GREEN}${line}${RESET}`;
|
|
18
|
+
if (line.startsWith('-')) return `${RED}${line}${RESET}`;
|
|
19
|
+
if (line.startsWith('@@')) return `${CYAN}${line}${RESET}`;
|
|
20
|
+
return line;
|
|
21
|
+
});
|
|
22
|
+
if (lines.length > maxLines) {
|
|
23
|
+
colored.push(`... (${lines.length - maxLines} more lines)`);
|
|
24
|
+
}
|
|
25
|
+
return colored.join('\n');
|
|
26
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
|
|
3
|
+
|
|
4
|
+
describe('mentionQuery', () => {
|
|
5
|
+
test('detects a trailing @token', () => {
|
|
6
|
+
expect(mentionQuery('fix @src')).toBe('src');
|
|
7
|
+
expect(mentionQuery('fix @src/a.ts')).toBe('src/a.ts');
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test('empty query right after @', () => {
|
|
11
|
+
expect(mentionQuery('hello @')).toBe('');
|
|
12
|
+
expect(mentionQuery('@')).toBe('');
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test('@ at the very start of the input', () => {
|
|
16
|
+
expect(mentionQuery('@readme')).toBe('readme');
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('null when @ is glued to a word (like an email)', () => {
|
|
20
|
+
expect(mentionQuery('mail me a@b.com')).toBeNull();
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('null when the @token is not the trailing segment', () => {
|
|
24
|
+
expect(mentionQuery('see @foo and more')).toBeNull();
|
|
25
|
+
expect(mentionQuery('no mention here')).toBeNull();
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
describe('filterFiles', () => {
|
|
30
|
+
const files = ['src/app.ts', 'src/main.tsx', 'README.md', 'src/util/string.ts', 'a/b/c.ts'];
|
|
31
|
+
|
|
32
|
+
test('empty query returns the first files up to the limit', () => {
|
|
33
|
+
expect(filterFiles(files, '', 3)).toEqual(files.slice(0, 3));
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test('substring match, case-insensitive', () => {
|
|
37
|
+
expect(filterFiles(files, 'readme', 8)).toEqual(['README.md']);
|
|
38
|
+
expect(filterFiles(files, 'main', 8)).toEqual(['src/main.tsx']);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('substring matches rank before subsequence matches', () => {
|
|
42
|
+
const ranked = filterFiles(['axb.ts', 'ab.ts'], 'ab', 8);
|
|
43
|
+
expect(ranked).toEqual(['ab.ts', 'axb.ts']);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test('subsequence fallback matches characters in order', () => {
|
|
47
|
+
expect(filterFiles(files, 'abc', 8)).toEqual(['a/b/c.ts']);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('no matches yields an empty array', () => {
|
|
51
|
+
expect(filterFiles(files, 'zzzz', 8)).toEqual([]);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe('applyCompletion', () => {
|
|
56
|
+
test('replaces the trailing token with the selected path', () => {
|
|
57
|
+
expect(applyCompletion('fix @src', 'src/app.ts')).toBe('fix @src/app.ts ');
|
|
58
|
+
expect(applyCompletion('@re', 'README.md')).toBe('@README.md ');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('leaves the input untouched when no token is active', () => {
|
|
62
|
+
expect(applyCompletion('no token here', 'README.md')).toBe('no token here');
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers for the REPL @-mention file completion. Rendering/keys live in
|
|
3
|
+
* REPL.tsx; these are the testable parts.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Returns the active @query at the end of the input, or null when inactive. */
|
|
7
|
+
export function mentionQuery(input: string): string | null {
|
|
8
|
+
const match = /(?:^|\s)@([^\s@]*)$/.exec(input);
|
|
9
|
+
return match === null ? null : match[1];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function isSubsequence(query: string, target: string): boolean {
|
|
13
|
+
let pos = -1;
|
|
14
|
+
for (const char of query) {
|
|
15
|
+
pos = target.indexOf(char, pos + 1);
|
|
16
|
+
if (pos === -1) return false;
|
|
17
|
+
}
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Filters file paths by query: case-insensitive substring matches first
|
|
23
|
+
* (path order), then subsequence matches. Empty query returns the first
|
|
24
|
+
* `limit` paths unchanged.
|
|
25
|
+
*/
|
|
26
|
+
export function filterFiles(files: string[], query: string, limit: number): string[] {
|
|
27
|
+
if (query === '') return files.slice(0, limit);
|
|
28
|
+
const lower = query.toLowerCase();
|
|
29
|
+
const substring: string[] = [];
|
|
30
|
+
const subsequence: string[] = [];
|
|
31
|
+
for (const file of files) {
|
|
32
|
+
const fileLower = file.toLowerCase();
|
|
33
|
+
if (fileLower.includes(lower)) {
|
|
34
|
+
substring.push(file);
|
|
35
|
+
} else if (isSubsequence(lower, fileLower)) {
|
|
36
|
+
subsequence.push(file);
|
|
37
|
+
}
|
|
38
|
+
if (substring.length >= limit) break;
|
|
39
|
+
}
|
|
40
|
+
return [...substring, ...subsequence].slice(0, limit);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Replaces the trailing @token with the selected path (plus a space). */
|
|
44
|
+
export function applyCompletion(input: string, selectedPath: string): string {
|
|
45
|
+
const match = /(?:^|\s)@([^\s@]*)$/.exec(input);
|
|
46
|
+
if (match === null) return input;
|
|
47
|
+
const atStart = match.index + (match[0].startsWith('@') ? 0 : 1);
|
|
48
|
+
return `${input.slice(0, atStart)}@${selectedPath} `;
|
|
49
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Auto-generated from package.json by scripts/sync-version.ts (npm version hook)
|
|
2
|
-
export const VERSION = '0.
|
|
2
|
+
export const VERSION = '0.2.0';
|