@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
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Pragmatic read-only bash command analyzer. A command is considered
3
+ * read-only when every segment (split on ; | && || & and newlines, outside
4
+ * quotes) starts with a whitelisted command AND carries no risky flags, and
5
+ * the raw command contains no unquoted redirection/substitution/heredoc.
6
+ *
7
+ * Conservative by design: anything unparsed or unusual fails closed (asks
8
+ * for permission). Inspired by Claude Code's readOnlyValidation.
9
+ */
10
+
11
+ const SAFE_COMMANDS = new Set([
12
+ 'ls', 'cat', 'head', 'tail', 'pwd', 'echo', 'printf', 'wc', 'file', 'which',
13
+ 'whoami', 'date', 'uname', 'hostname', 'basename', 'dirname', 'realpath',
14
+ 'stat', 'du', 'df', 'tree', 'grep', 'rg', 'fgrep', 'egrep', 'awk', 'sort',
15
+ 'uniq', 'cut', 'tr', 'diff', 'cmp', 'jq', 'printenv', 'type', 'command',
16
+ 'help', 'man', 'true', 'false', 'cd', 'md5sum', 'shasum', 'sha256sum',
17
+ ]);
18
+
19
+ const GIT_READONLY = new Set([
20
+ 'status', 'log', 'diff', 'show', 'rev-parse', 'ls-files', 'blame',
21
+ 'describe', 'shortlog', 'reflog', 'grep', 'whatchanged',
22
+ ]);
23
+
24
+ const FIND_UNSAFE_FLAGS = new Set([
25
+ '-delete', '-exec', '-execdir', '-ok', '-okdir', '-fls', '-fprintf',
26
+ '-fprint', '-fprint0',
27
+ ]);
28
+
29
+ interface Segment {
30
+ tokens: string[];
31
+ }
32
+
33
+ /**
34
+ * Splits a command line into segments on unquoted separators, tracking
35
+ * whether any unquoted disqualifying metacharacter appears. Backslash
36
+ * escapes and single/double quotes are respected.
37
+ */
38
+ function parseSegments(command: string): { segments: Segment[]; unsafe: boolean } {
39
+ const segments: Segment[] = [];
40
+ let current: Segment = { tokens: [] };
41
+ let token = '';
42
+ let hasToken = false;
43
+ let unsafe = false;
44
+
45
+ const endToken = () => {
46
+ if (hasToken) {
47
+ current.tokens.push(token);
48
+ token = '';
49
+ hasToken = false;
50
+ }
51
+ };
52
+ const endSegment = () => {
53
+ endToken();
54
+ if (current.tokens.length > 0) segments.push(current);
55
+ current = { tokens: [] };
56
+ };
57
+
58
+ for (let i = 0; i < command.length; i++) {
59
+ const char = command[i]!;
60
+
61
+ if (char === "'") {
62
+ // Single quotes: everything literal until the closing quote.
63
+ const close = command.indexOf("'", i + 1);
64
+ if (close === -1) return { segments, unsafe: true }; // unterminated quote
65
+ token += command.slice(i + 1, close);
66
+ hasToken = true;
67
+ i = close;
68
+ continue;
69
+ }
70
+
71
+ if (char === '"') {
72
+ const close = command.indexOf('"', i + 1);
73
+ if (close === -1) return { segments, unsafe: true };
74
+ for (let j = i + 1; j < close; j++) {
75
+ if (command[j] === '\\' && j + 1 < close) {
76
+ token += command[j + 1]!;
77
+ j++;
78
+ } else {
79
+ token += command[j]!;
80
+ }
81
+ }
82
+ hasToken = true;
83
+ i = close;
84
+ continue;
85
+ }
86
+
87
+ if (char === '\\') {
88
+ if (i + 1 >= command.length) return { segments, unsafe: true };
89
+ token += command[i + 1]!;
90
+ hasToken = true;
91
+ i++;
92
+ continue;
93
+ }
94
+
95
+ if (char === ';' || char === '\n') {
96
+ endSegment();
97
+ continue;
98
+ }
99
+
100
+ if (char === '|' || char === '&') {
101
+ if (command[i + 1] === char) i++; // || or &&
102
+ endSegment();
103
+ continue;
104
+ }
105
+
106
+ if (char === '>' || char === '<' || char === '`') {
107
+ unsafe = true; // redirection, heredoc, backtick substitution
108
+ continue;
109
+ }
110
+
111
+ if (char === '$' && command[i + 1] === '(') {
112
+ unsafe = true; // command substitution
113
+ continue;
114
+ }
115
+
116
+ if (char === '#' && !hasToken) {
117
+ // Comment: ignore the rest of the line.
118
+ const nl = command.indexOf('\n', i);
119
+ if (nl === -1) break;
120
+ i = nl - 1;
121
+ continue;
122
+ }
123
+
124
+ if (/\s/.test(char)) {
125
+ endToken();
126
+ continue;
127
+ }
128
+
129
+ token += char;
130
+ hasToken = true;
131
+ }
132
+ endSegment();
133
+
134
+ return { segments, unsafe };
135
+ }
136
+
137
+ function segmentIsReadOnly(tokens: string[]): boolean {
138
+ // Strip leading VAR=value assignments (FOO=1 ls …).
139
+ let start = 0;
140
+ while (start < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[start]!)) {
141
+ start++;
142
+ }
143
+ const rest = tokens.slice(start);
144
+ if (rest.length === 0) return true; // pure assignments are side-effect free
145
+ const base = rest[0]!;
146
+
147
+ if (base === 'git') {
148
+ const sub = rest[1];
149
+ if (!sub) return false;
150
+ if (sub === 'branch') {
151
+ // `git branch -vv` lists; `git branch name` creates. Safe only when
152
+ // every argument is a flag.
153
+ return rest.slice(2).every((arg) => arg.startsWith('-'));
154
+ }
155
+ return GIT_READONLY.has(sub);
156
+ }
157
+
158
+ if (base === 'find') {
159
+ return !rest.some((arg) => FIND_UNSAFE_FLAGS.has(arg));
160
+ }
161
+
162
+ if (base === 'sed') {
163
+ // Unsafe when any short-flag cluster contains `i` (in-place) or a long
164
+ // --in-place style flag is present.
165
+ return !rest.some((arg) => {
166
+ if (arg.startsWith('--')) return arg === '--in-place' || arg.startsWith('--in-place=');
167
+ if (arg.startsWith('-') && arg.length > 1) return arg.includes('i');
168
+ return false;
169
+ });
170
+ }
171
+
172
+ return SAFE_COMMANDS.has(base);
173
+ }
174
+
175
+ /** True when the command can run without a permission prompt. */
176
+ export function isReadOnlyCommand(command: string): boolean {
177
+ const { segments, unsafe } = parseSegments(command);
178
+ if (unsafe) return false;
179
+ if (segments.length === 0) return false;
180
+ return segments.every((segment) => segmentIsReadOnly(segment.tokens));
181
+ }
@@ -0,0 +1,55 @@
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 { globTool, grepTool } from './search.js';
6
+ import { createToolSession, type ToolSession } from './session.js';
7
+ import type { ToolContext } from './types.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-search-'));
16
+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
17
+ return dir;
18
+ }
19
+
20
+ function ctx(session: ToolSession): ToolContext {
21
+ return { cwd: session.cwd, session };
22
+ }
23
+
24
+ describe('glob', () => {
25
+ test('finds files by pattern with workspace-relative paths', async () => {
26
+ const dir = workspace();
27
+ writeFileSync(path.join(dir, 'a.ts'), 'x');
28
+ writeFileSync(path.join(dir, 'b.txt'), 'x');
29
+
30
+ const session = createToolSession(dir);
31
+ const output = await globTool.execute({ pattern: '**/*.ts' }, ctx(session));
32
+ expect(output).toContain('a.ts');
33
+ expect(output).not.toContain('b.txt');
34
+ });
35
+ });
36
+
37
+ describe('grep', () => {
38
+ test('returns path:line matches', async () => {
39
+ const dir = workspace();
40
+ writeFileSync(path.join(dir, 'code.ts'), 'const alpha = 1;\nconst beta = 2;\n');
41
+
42
+ const session = createToolSession(dir);
43
+ const output = await grepTool.execute({ pattern: 'beta' }, ctx(session));
44
+ expect(output).toContain('code.ts:2: const beta = 2;');
45
+ });
46
+
47
+ test('reports when nothing matches', async () => {
48
+ const dir = workspace();
49
+ writeFileSync(path.join(dir, 'code.ts'), 'const alpha = 1;\n');
50
+
51
+ const session = createToolSession(dir);
52
+ const output = await grepTool.execute({ pattern: 'nope-xyz' }, ctx(session));
53
+ expect(output).toContain('No matches');
54
+ });
55
+ });
@@ -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,47 @@
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
+ /** When true for a given input, a mutating tool may skip the permission prompt. */
37
+ isReadOnly?(input: Record<string, unknown>): boolean;
38
+ title(input: Record<string, unknown>): string;
39
+ execute(input: Record<string, unknown>, ctx: ToolContext): Promise<string | ToolOutput>;
40
+ }
41
+
42
+ export interface InvokeResult {
43
+ ok: boolean;
44
+ output: string;
45
+ /** Unified diff text for UI rendering, when the tool produced one. */
46
+ diff?: string;
47
+ }
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
@@ -12,7 +12,8 @@ Usage:
12
12
  Environment:
13
13
  TRANSCODE_MODEL Default model (registry id or provider:model)
14
14
  TRANSCODE_DEFAULT_PROVIDER Provider for bare model names (default: openai)
15
- TRANSCODE_PERMISSION_MODE ask | auto | readonly (default: ask in ACP mode)
15
+ TRANSCODE_PERMISSION_MODE ask | auto | readonly (default: ask in ACP mode;
16
+ switch at runtime in the REPL with /mode)
16
17
  ANTHROPIC_API_KEY / OPENAI_API_KEY / DEEPSEEK_API_KEY / ... provider keys
17
18
 
18
19
  Examples:
@@ -0,0 +1,56 @@
1
+ import { afterEach, describe, expect, test } from 'bun:test';
2
+ import { findCommand, getCommands } from './commands.js';
3
+ import { getPermissionMode, resetPermissionMode, setPermissionMode } from './agent/permission.js';
4
+
5
+ afterEach(() => {
6
+ setPermissionMode('ask');
7
+ resetPermissionMode();
8
+ });
9
+
10
+ describe('init command registration', () => {
11
+ test('is registered so /help lists it', () => {
12
+ const init = findCommand('init');
13
+ expect(init).toBeDefined();
14
+ expect(init?.description.length).toBeGreaterThan(0);
15
+ });
16
+
17
+ test('getCommands exposes it alongside the others', () => {
18
+ const names = getCommands().map((command) => command.name);
19
+ expect(names).toContain('init');
20
+ expect(names).toContain('help');
21
+ expect(names).toContain('exit');
22
+ });
23
+ });
24
+
25
+ describe('mode command', () => {
26
+ test('is registered', () => {
27
+ const mode = findCommand('mode');
28
+ expect(mode).toBeDefined();
29
+ });
30
+
31
+ test('bare /mode shows the current mode and usage', async () => {
32
+ const mode = findCommand('mode')!;
33
+ const result = await mode.execute([], { modelId: 'deepseek', setModelId: () => {}, clearHistory: () => {} });
34
+ expect(result.output).toContain('ask');
35
+ expect(result.output).toContain('auto');
36
+ expect(result.output).toContain('readonly');
37
+ });
38
+
39
+ test('/mode auto switches the runtime mode', async () => {
40
+ const mode = findCommand('mode')!;
41
+ const ctx = { modelId: 'deepseek', setModelId: () => {}, clearHistory: () => {} };
42
+ await mode.execute(['auto'], ctx);
43
+ expect(getPermissionMode()).toBe('auto');
44
+
45
+ const result = await mode.execute(['readonly'], ctx);
46
+ expect(getPermissionMode()).toBe('readonly');
47
+ expect(result.output).toContain('readonly');
48
+ });
49
+
50
+ test('/mode bogus reports the valid modes without switching', async () => {
51
+ const mode = findCommand('mode')!;
52
+ const result = await mode.execute(['bogus'], { modelId: 'deepseek', setModelId: () => {}, clearHistory: () => {} });
53
+ expect(result.output).toContain('Unknown mode');
54
+ expect(getPermissionMode()).toBe('ask');
55
+ });
56
+ });
package/src/commands.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ModelId } from './provider/provider.js';
2
2
  import { getAvailableModels } from './provider/provider.js';
3
+ import { getPermissionMode, PERMISSION_MODES, setPermissionMode } from './agent/permission.js';
3
4
 
4
5
  export interface CommandContext {
5
6
  modelId: ModelId;
@@ -37,6 +38,36 @@ const commands: Command[] = [
37
38
  };
38
39
  },
39
40
  },
41
+ {
42
+ name: 'init',
43
+ description: 'Analyze the project and write TRANS.md',
44
+ // Intercepted by the REPL before command dispatch (like /models) so the
45
+ // analysis runs through the full agent loop with tools and permissions.
46
+ execute: () => ({
47
+ output: 'Analyzing the project and writing TRANS.md…',
48
+ }),
49
+ },
50
+ {
51
+ name: 'mode',
52
+ description: 'Show or switch permission mode (ask | auto | readonly)',
53
+ execute: (args) => {
54
+ const target = args[0]?.toLowerCase();
55
+ if (!target) {
56
+ return {
57
+ output:
58
+ `Current permission mode: ${getPermissionMode()}\n` +
59
+ `Usage: /mode <${PERMISSION_MODES.join('|')}> — ` +
60
+ 'ask prompts for mutating tools (read-only commands pass), ' +
61
+ 'auto allows everything, readonly denies mutating tools.',
62
+ };
63
+ }
64
+ if (!PERMISSION_MODES.includes(target as never)) {
65
+ return { output: `Unknown mode: ${target}. Valid modes: ${PERMISSION_MODES.join(', ')}` };
66
+ }
67
+ setPermissionMode(target as never);
68
+ return { output: `Permission mode switched to ${target}` };
69
+ },
70
+ },
40
71
  {
41
72
  name: 'clear',
42
73
  description: 'Clear screen',
@@ -244,8 +244,8 @@ export function resolveModel(spec?: string): ResolvedModel {
244
244
  }
245
245
 
246
246
  // Bare unknown model name: route through a provider guessed from the name,
247
- // then fall back to TRANSCODE_DEFAULT_PROVIDER. This lets multica users type
248
- // 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.
249
249
  const lower = raw.toLowerCase();
250
250
  let fallback = PROVIDER_DEFAULTS[defaultProvider()] ?? PROVIDER_DEFAULTS.openai;
251
251
  if (lower.startsWith('claude')) fallback = PROVIDER_DEFAULTS.anthropic;