@trans-ai/trans-code 0.2.0 → 0.2.2
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/package.json +1 -1
- package/src/acp/session.ts +2 -3
- package/src/agent/loop.test.ts +50 -1
- package/src/agent/loop.ts +7 -1
- package/src/agent/permission.test.ts +50 -0
- package/src/agent/permission.ts +34 -0
- package/src/agent/system-prompt.test.ts +13 -1
- package/src/agent/system-prompt.ts +3 -0
- package/src/agent/tools/bash.test.ts +11 -0
- package/src/agent/tools/bash.ts +4 -1
- package/src/agent/tools/read-only.test.ts +97 -0
- package/src/agent/tools/read-only.ts +212 -0
- package/src/agent/tools/types.ts +2 -0
- package/src/cli.ts +2 -1
- package/src/commands.test.ts +40 -1
- package/src/commands.ts +22 -0
- package/src/screens/REPL.tsx +4 -2
- package/src/version.ts +1 -1
package/package.json
CHANGED
package/src/acp/session.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
import { createModel, getAvailableModels, resolveModel } from '../provider/provider.js';
|
|
10
10
|
import { runAgentLoop, type AgentEvent, type PermissionRequest } from '../agent/loop.js';
|
|
11
11
|
import { createToolSession, type ToolSession } from '../agent/tools/index.js';
|
|
12
|
+
import { getPermissionMode } from '../agent/permission.js';
|
|
12
13
|
import { buildSystemPrompt, loadProjectContext } from '../agent/system-prompt.js';
|
|
13
14
|
import {
|
|
14
15
|
RPC_ERRORS,
|
|
@@ -66,9 +67,7 @@ function promptText(prompt: AcpPromptBlock[]): string {
|
|
|
66
67
|
}
|
|
67
68
|
|
|
68
69
|
function permissionMode(): 'ask' | 'auto' | 'readonly' {
|
|
69
|
-
|
|
70
|
-
if (value === 'auto' || value === 'readonly') return value;
|
|
71
|
-
return 'ask';
|
|
70
|
+
return getPermissionMode();
|
|
72
71
|
}
|
|
73
72
|
|
|
74
73
|
export class AcpSession {
|
package/src/agent/loop.test.ts
CHANGED
|
@@ -33,7 +33,7 @@ const fakeTool: AgentTool = {
|
|
|
33
33
|
description: 'test double',
|
|
34
34
|
schema: (await import('zod')).z.object({}),
|
|
35
35
|
kind: 'other',
|
|
36
|
-
isMutating:
|
|
36
|
+
isMutating: true,
|
|
37
37
|
title: () => 'fake',
|
|
38
38
|
async execute() {
|
|
39
39
|
return { output: 'ok', diff: '+added-line' };
|
|
@@ -61,4 +61,53 @@ describe('runAgentLoop', () => {
|
|
|
61
61
|
'+added-line',
|
|
62
62
|
);
|
|
63
63
|
});
|
|
64
|
+
|
|
65
|
+
test('read-only mutating tools skip the permission request', async () => {
|
|
66
|
+
const events: AgentEvent[] = [];
|
|
67
|
+
let permissionAsked = 0;
|
|
68
|
+
const readOnlyTool: AgentTool = {
|
|
69
|
+
...fakeTool,
|
|
70
|
+
name: 'fake',
|
|
71
|
+
isMutating: true,
|
|
72
|
+
isReadOnly: () => true,
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const result = await runAgentLoop({
|
|
76
|
+
model: stubModel(),
|
|
77
|
+
cwd: '/tmp',
|
|
78
|
+
messages: [],
|
|
79
|
+
systemPrompt: 'test',
|
|
80
|
+
tools: [readOnlyTool],
|
|
81
|
+
onEvent: (event) => {
|
|
82
|
+
events.push(event);
|
|
83
|
+
},
|
|
84
|
+
requestPermission: async () => {
|
|
85
|
+
permissionAsked++;
|
|
86
|
+
return true;
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
expect(result.stopReason).toBe('end_turn');
|
|
91
|
+
expect(permissionAsked).toBe(0);
|
|
92
|
+
const toolResult = events.find((event) => event.type === 'tool_result');
|
|
93
|
+
expect(toolResult && toolResult.type === 'tool_result' ? toolResult.skippedPermission : false)
|
|
94
|
+
.toBe(true);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('mutating tools without isReadOnly still request permission', async () => {
|
|
98
|
+
let permissionAsked = 0;
|
|
99
|
+
await runAgentLoop({
|
|
100
|
+
model: stubModel(),
|
|
101
|
+
cwd: '/tmp',
|
|
102
|
+
messages: [],
|
|
103
|
+
systemPrompt: 'test',
|
|
104
|
+
tools: [fakeTool],
|
|
105
|
+
onEvent: () => {},
|
|
106
|
+
requestPermission: async () => {
|
|
107
|
+
permissionAsked++;
|
|
108
|
+
return true;
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
expect(permissionAsked).toBe(1);
|
|
112
|
+
});
|
|
64
113
|
});
|
package/src/agent/loop.ts
CHANGED
|
@@ -37,6 +37,8 @@ export type AgentEvent =
|
|
|
37
37
|
ok: boolean;
|
|
38
38
|
/** Unified diff for UI rendering; not sent to the model. */
|
|
39
39
|
diff?: string;
|
|
40
|
+
/** True when a mutating tool ran without prompting (read-only input). */
|
|
41
|
+
skippedPermission?: boolean;
|
|
40
42
|
};
|
|
41
43
|
|
|
42
44
|
export interface PermissionRequest {
|
|
@@ -302,10 +304,13 @@ export async function runAgentLoop(
|
|
|
302
304
|
});
|
|
303
305
|
|
|
304
306
|
let result: { ok: boolean; output: string; diff?: string };
|
|
307
|
+
let skippedPermission = false;
|
|
305
308
|
if (!tool) {
|
|
306
309
|
result = { ok: false, output: `Unknown tool: ${call.name}` };
|
|
307
310
|
} else {
|
|
308
|
-
const
|
|
311
|
+
const readOnly = tool.isReadOnly?.(input) === true;
|
|
312
|
+
const needsPermission = tool.isMutating && !readOnly;
|
|
313
|
+
skippedPermission = tool.isMutating && readOnly;
|
|
309
314
|
const allowed =
|
|
310
315
|
!needsPermission || !options.requestPermission
|
|
311
316
|
? true
|
|
@@ -333,6 +338,7 @@ export async function runAgentLoop(
|
|
|
333
338
|
output: result.output,
|
|
334
339
|
ok: result.ok,
|
|
335
340
|
diff: result.diff,
|
|
341
|
+
skippedPermission,
|
|
336
342
|
});
|
|
337
343
|
|
|
338
344
|
messages.push(
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import {
|
|
3
|
+
getPermissionMode,
|
|
4
|
+
PERMISSION_MODES,
|
|
5
|
+
resetPermissionMode,
|
|
6
|
+
setPermissionMode,
|
|
7
|
+
} from './permission.js';
|
|
8
|
+
|
|
9
|
+
const savedEnv: string | undefined = process.env.TRANSCODE_PERMISSION_MODE;
|
|
10
|
+
afterEach(() => {
|
|
11
|
+
if (savedEnv === undefined) delete process.env.TRANSCODE_PERMISSION_MODE;
|
|
12
|
+
else process.env.TRANSCODE_PERMISSION_MODE = savedEnv;
|
|
13
|
+
resetPermissionMode();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe('permission mode', () => {
|
|
17
|
+
test('defaults to ask', () => {
|
|
18
|
+
delete process.env.TRANSCODE_PERMISSION_MODE;
|
|
19
|
+
resetPermissionMode();
|
|
20
|
+
expect(getPermissionMode()).toBe('ask');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('initializes from the environment variable', () => {
|
|
24
|
+
process.env.TRANSCODE_PERMISSION_MODE = 'AUTO';
|
|
25
|
+
resetPermissionMode();
|
|
26
|
+
expect(getPermissionMode()).toBe('auto');
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('invalid environment value falls back to ask', () => {
|
|
30
|
+
process.env.TRANSCODE_PERMISSION_MODE = 'yolo';
|
|
31
|
+
resetPermissionMode();
|
|
32
|
+
expect(getPermissionMode()).toBe('ask');
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('switches at runtime', () => {
|
|
36
|
+
setPermissionMode('auto');
|
|
37
|
+
expect(getPermissionMode()).toBe('auto');
|
|
38
|
+
setPermissionMode('readonly');
|
|
39
|
+
expect(getPermissionMode()).toBe('readonly');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('rejects unknown modes', () => {
|
|
43
|
+
expect(() => setPermissionMode('yolo' as never)).toThrow();
|
|
44
|
+
expect(getPermissionMode()).toBe('ask');
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('documents the mode list', () => {
|
|
48
|
+
expect(PERMISSION_MODES).toEqual(['ask', 'auto', 'readonly']);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime-switchable permission mode, shared by the REPL and the ACP server.
|
|
3
|
+
* Initialized from TRANSCODE_PERMISSION_MODE; switchable at runtime via /mode.
|
|
4
|
+
*
|
|
5
|
+
* - ask: mutating tools prompt (read-only bash commands pass silently)
|
|
6
|
+
* - auto: everything is allowed without prompting
|
|
7
|
+
* - readonly: mutating tools are denied; read-only commands still run
|
|
8
|
+
*/
|
|
9
|
+
export type PermissionMode = 'ask' | 'auto' | 'readonly';
|
|
10
|
+
|
|
11
|
+
export const PERMISSION_MODES: readonly PermissionMode[] = ['ask', 'auto', 'readonly'];
|
|
12
|
+
|
|
13
|
+
function parseMode(value: string | undefined): PermissionMode {
|
|
14
|
+
const lower = value?.toLowerCase();
|
|
15
|
+
return PERMISSION_MODES.includes(lower as PermissionMode) ? (lower as PermissionMode) : 'ask';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
let currentMode: PermissionMode = parseMode(process.env.TRANSCODE_PERMISSION_MODE);
|
|
19
|
+
|
|
20
|
+
export function getPermissionMode(): PermissionMode {
|
|
21
|
+
return currentMode;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function setPermissionMode(mode: PermissionMode): void {
|
|
25
|
+
if (!PERMISSION_MODES.includes(mode)) {
|
|
26
|
+
throw new Error(`Unknown permission mode: ${mode}. Valid: ${PERMISSION_MODES.join(', ')}`);
|
|
27
|
+
}
|
|
28
|
+
currentMode = mode;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Re-reads the environment variable (used at startup and in tests). */
|
|
32
|
+
export function resetPermissionMode(): void {
|
|
33
|
+
currentMode = parseMode(process.env.TRANSCODE_PERMISSION_MODE);
|
|
34
|
+
}
|
|
@@ -2,7 +2,19 @@ import { afterEach, describe, expect, test } from 'bun:test';
|
|
|
2
2
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
-
import { INIT_PROMPT, loadProjectContext } from './system-prompt.js';
|
|
5
|
+
import { INIT_PROMPT, buildSystemPrompt, loadProjectContext } from './system-prompt.js';
|
|
6
|
+
|
|
7
|
+
describe('buildSystemPrompt', () => {
|
|
8
|
+
test('steers file inspection away from whole-file cat/sed dumps', () => {
|
|
9
|
+
const prompt = buildSystemPrompt(
|
|
10
|
+
{ cwd: '/tmp', projectFiles: [] },
|
|
11
|
+
{ modelName: 'test-model' },
|
|
12
|
+
);
|
|
13
|
+
expect(prompt).toContain('wc -l');
|
|
14
|
+
expect(prompt).toContain('offset');
|
|
15
|
+
expect(prompt.toLowerCase()).toContain('do not cat');
|
|
16
|
+
});
|
|
17
|
+
});
|
|
6
18
|
|
|
7
19
|
const cleanups: Array<() => void> = [];
|
|
8
20
|
afterEach(() => {
|
|
@@ -89,6 +89,9 @@ export function buildSystemPrompt(
|
|
|
89
89
|
'## How to work',
|
|
90
90
|
'- Inspect the repository before changing it. Read the relevant files first.',
|
|
91
91
|
'- Prefer read_file, glob and grep for exploration; use bash for builds, tests and git.',
|
|
92
|
+
'- Inspect file contents with read_file, not cat/sed: it caps lines and paginates. ' +
|
|
93
|
+
'Check unknown file sizes with wc -l first and read large files in offset/limit chunks. ' +
|
|
94
|
+
'Do not cat entire files into the conversation.',
|
|
92
95
|
'- The bash working directory persists across calls; you do not need to cd again each time.',
|
|
93
96
|
'- Use edit_file for targeted changes and write_file for new files.',
|
|
94
97
|
'- Keep changes focused on the task. Do not undo unrelated user work.',
|
|
@@ -6,6 +6,17 @@ import { bashTool } from './bash.js';
|
|
|
6
6
|
import { createToolSession, type ToolSession } from './session.js';
|
|
7
7
|
import type { ToolContext } from './types.js';
|
|
8
8
|
|
|
9
|
+
describe('bash tool wiring', () => {
|
|
10
|
+
test('description steers file viewing to read_file', () => {
|
|
11
|
+
expect(bashTool.description).toContain('read_file');
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test('isReadOnly is wired to the analyzer', () => {
|
|
15
|
+
expect(bashTool.isReadOnly?.({ command: 'cat config.py 2>/dev/null' })).toBe(true);
|
|
16
|
+
expect(bashTool.isReadOnly?.({ command: 'npm install' })).toBe(false);
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
9
20
|
const cleanups: Array<() => void> = [];
|
|
10
21
|
const savedEnv: Record<string, string | undefined> = {};
|
|
11
22
|
function setEnv(key: string, value: string | undefined): void {
|
package/src/agent/tools/bash.ts
CHANGED
|
@@ -6,6 +6,7 @@ import path from 'node:path';
|
|
|
6
6
|
import { z } from 'zod';
|
|
7
7
|
import type { AgentTool } from './types.js';
|
|
8
8
|
import type { ToolSession } from './session.js';
|
|
9
|
+
import { isReadOnlyCommand } from './read-only.js';
|
|
9
10
|
|
|
10
11
|
const MAX_BASH_OUTPUT = 30_000;
|
|
11
12
|
const TRUNCATE_HEAD = 15_000;
|
|
@@ -217,9 +218,11 @@ export const bashTool: AgentTool = {
|
|
|
217
218
|
description:
|
|
218
219
|
'Run a shell command in the workspace using the user shell. Working directory changes (cd) ' +
|
|
219
220
|
'persist across calls. Returns stdout, stderr and the exit code. ' +
|
|
220
|
-
'
|
|
221
|
+
'For viewing file contents use read_file (line-capped, paginates with offset/limit) — ' +
|
|
222
|
+
'cat/sed dumps of entire files waste context.',
|
|
221
223
|
kind: 'execute',
|
|
222
224
|
isMutating: true,
|
|
225
|
+
isReadOnly: (input) => isReadOnlyCommand(String(input.command ?? '')),
|
|
223
226
|
schema: z.object({
|
|
224
227
|
command: z.string().describe('Shell command to run'),
|
|
225
228
|
timeout_ms: z.number().int().min(1000).max(600_000).nullable().optional().describe('Timeout in ms'),
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { isReadOnlyCommand } from './read-only.js';
|
|
3
|
+
|
|
4
|
+
describe('isReadOnlyCommand', () => {
|
|
5
|
+
test('simple read-only commands pass', () => {
|
|
6
|
+
expect(isReadOnlyCommand('ls')).toBe(true);
|
|
7
|
+
expect(isReadOnlyCommand('ls -la /tmp')).toBe(true);
|
|
8
|
+
expect(isReadOnlyCommand('git status')).toBe(true);
|
|
9
|
+
expect(isReadOnlyCommand('git log --oneline -3')).toBe(true);
|
|
10
|
+
expect(isReadOnlyCommand('grep -n foo bar.txt')).toBe(true);
|
|
11
|
+
expect(isReadOnlyCommand('sed -n "348,420p" tests/smoke.py')).toBe(true);
|
|
12
|
+
expect(isReadOnlyCommand('pwd')).toBe(true);
|
|
13
|
+
expect(isReadOnlyCommand('cd trans-once && pwd')).toBe(true);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
test('pipelines and chains pass when every segment is read-only', () => {
|
|
17
|
+
expect(isReadOnlyCommand('cat x | grep y')).toBe(true);
|
|
18
|
+
expect(isReadOnlyCommand('git log --oneline -3; echo "---"; git diff --stat')).toBe(true);
|
|
19
|
+
expect(isReadOnlyCommand('ls && echo done || echo failed')).toBe(true);
|
|
20
|
+
expect(isReadOnlyCommand('git branch -vv && git log --oneline -15')).toBe(true);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('mutating commands fail', () => {
|
|
24
|
+
expect(isReadOnlyCommand('npm install')).toBe(false);
|
|
25
|
+
expect(isReadOnlyCommand('git push origin main')).toBe(false);
|
|
26
|
+
expect(isReadOnlyCommand('git commit -m x')).toBe(false);
|
|
27
|
+
expect(isReadOnlyCommand('node check.ts')).toBe(false);
|
|
28
|
+
expect(isReadOnlyCommand('rm -rf /tmp/x')).toBe(false);
|
|
29
|
+
expect(isReadOnlyCommand('curl https://example.com')).toBe(false);
|
|
30
|
+
expect(isReadOnlyCommand('mkdir newdir')).toBe(false);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('mixed chains fail when any segment mutates', () => {
|
|
34
|
+
expect(isReadOnlyCommand('ls && npm install')).toBe(false);
|
|
35
|
+
expect(isReadOnlyCommand('git status; git push')).toBe(false);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('output redirection disqualifies', () => {
|
|
39
|
+
expect(isReadOnlyCommand('grep foo bar > out.txt')).toBe(false);
|
|
40
|
+
expect(isReadOnlyCommand('echo hi >> log.txt')).toBe(false);
|
|
41
|
+
expect(isReadOnlyCommand('ls >out')).toBe(false);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('command substitution and heredocs disqualify', () => {
|
|
45
|
+
expect(isReadOnlyCommand('echo $(rm -rf x)')).toBe(false);
|
|
46
|
+
expect(isReadOnlyCommand('echo `rm -rf x`')).toBe(false);
|
|
47
|
+
expect(isReadOnlyCommand('cat <<EOF\nhi\nEOF')).toBe(false);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('risky flags disqualify find and sed', () => {
|
|
51
|
+
expect(isReadOnlyCommand('find . -name "*.tmp" -delete')).toBe(false);
|
|
52
|
+
expect(isReadOnlyCommand('find . -exec rm {} \\;')).toBe(false);
|
|
53
|
+
expect(isReadOnlyCommand('sed -i s/a/b file.txt')).toBe(false);
|
|
54
|
+
expect(isReadOnlyCommand('sed -in s/a/b file.txt')).toBe(false);
|
|
55
|
+
expect(isReadOnlyCommand('sed --in-place s/a/b file.txt')).toBe(false);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('git subcommands outside the read-only set fail', () => {
|
|
59
|
+
expect(isReadOnlyCommand('git branch feature')).toBe(false);
|
|
60
|
+
expect(isReadOnlyCommand('git config user.name x')).toBe(false);
|
|
61
|
+
expect(isReadOnlyCommand('git checkout main')).toBe(false);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test('quoted separators and metacharacters are not treated as operators', () => {
|
|
65
|
+
expect(isReadOnlyCommand('echo "a;b | c && d"')).toBe(true);
|
|
66
|
+
expect(isReadOnlyCommand('grep "a > b" file.txt')).toBe(true);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('env assignment prefixes are tolerated', () => {
|
|
70
|
+
expect(isReadOnlyCommand('LC_ALL=C sort big.txt')).toBe(true);
|
|
71
|
+
expect(isReadOnlyCommand('FOO=1 ls')).toBe(true);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('empty or whitespace command is not read-only', () => {
|
|
75
|
+
expect(isReadOnlyCommand('')).toBe(false);
|
|
76
|
+
expect(isReadOnlyCommand(' ')).toBe(false);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('redirects to /dev/null and fd duplication are harmless', () => {
|
|
80
|
+
expect(isReadOnlyCommand('cat config.py 2>/dev/null')).toBe(true);
|
|
81
|
+
expect(isReadOnlyCommand('ls missing 2>/dev/null; echo done')).toBe(true);
|
|
82
|
+
expect(isReadOnlyCommand('grep foo bar >/dev/null')).toBe(true);
|
|
83
|
+
expect(isReadOnlyCommand('echo hi 2>>/dev/null')).toBe(true);
|
|
84
|
+
expect(isReadOnlyCommand('grep foo bar 2>&1 | wc -l')).toBe(true);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('redirects to real files still disqualify', () => {
|
|
88
|
+
expect(isReadOnlyCommand('grep foo bar > out.txt')).toBe(false);
|
|
89
|
+
expect(isReadOnlyCommand('grep foo bar >> out.txt')).toBe(false);
|
|
90
|
+
expect(isReadOnlyCommand('grep foo bar 2> err.txt')).toBe(false);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('input redirection is read-only, process substitution is not', () => {
|
|
94
|
+
expect(isReadOnlyCommand('sort < input.txt')).toBe(true);
|
|
95
|
+
expect(isReadOnlyCommand('cat <(ls)')).toBe(false);
|
|
96
|
+
});
|
|
97
|
+
});
|
|
@@ -0,0 +1,212 @@
|
|
|
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 === '>') {
|
|
107
|
+
// Output redirection: harmless when the target is /dev/null or an fd
|
|
108
|
+
// duplication (2>&1); anything else writes a file and disqualifies.
|
|
109
|
+
let j = i + 1;
|
|
110
|
+
if (command[j] === '>') j++; // >>
|
|
111
|
+
let k = j;
|
|
112
|
+
while (k < command.length && /\s/.test(command[k]!)) k++;
|
|
113
|
+
if (command[k] === '&' && /[0-9]/.test(command[k + 1] ?? '')) {
|
|
114
|
+
i = k + 1; // >&N — safe, consumed
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
let t = k;
|
|
118
|
+
if (command[t] === '"' || command[t] === "'") t++;
|
|
119
|
+
if (command.startsWith('/dev/null', t)) {
|
|
120
|
+
i = t + 8; // >/dev/null — safe, consumed
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
unsafe = true;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (char === '<') {
|
|
128
|
+
// Heredocs (<<) and process substitution (<() are disqualifying;
|
|
129
|
+
// a plain input redirect (< file) only reads.
|
|
130
|
+
if (command[i + 1] === '<' || command[i + 1] === '(' || command[i + 1] === '>') {
|
|
131
|
+
unsafe = true;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
continue; // target tokenizes as a regular word
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (char === '`') {
|
|
138
|
+
unsafe = true; // backtick substitution
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (char === '$' && command[i + 1] === '(') {
|
|
143
|
+
unsafe = true; // command substitution
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (char === '#' && !hasToken) {
|
|
148
|
+
// Comment: ignore the rest of the line.
|
|
149
|
+
const nl = command.indexOf('\n', i);
|
|
150
|
+
if (nl === -1) break;
|
|
151
|
+
i = nl - 1;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (/\s/.test(char)) {
|
|
156
|
+
endToken();
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
token += char;
|
|
161
|
+
hasToken = true;
|
|
162
|
+
}
|
|
163
|
+
endSegment();
|
|
164
|
+
|
|
165
|
+
return { segments, unsafe };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function segmentIsReadOnly(tokens: string[]): boolean {
|
|
169
|
+
// Strip leading VAR=value assignments (FOO=1 ls …).
|
|
170
|
+
let start = 0;
|
|
171
|
+
while (start < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[start]!)) {
|
|
172
|
+
start++;
|
|
173
|
+
}
|
|
174
|
+
const rest = tokens.slice(start);
|
|
175
|
+
if (rest.length === 0) return true; // pure assignments are side-effect free
|
|
176
|
+
const base = rest[0]!;
|
|
177
|
+
|
|
178
|
+
if (base === 'git') {
|
|
179
|
+
const sub = rest[1];
|
|
180
|
+
if (!sub) return false;
|
|
181
|
+
if (sub === 'branch') {
|
|
182
|
+
// `git branch -vv` lists; `git branch name` creates. Safe only when
|
|
183
|
+
// every argument is a flag.
|
|
184
|
+
return rest.slice(2).every((arg) => arg.startsWith('-'));
|
|
185
|
+
}
|
|
186
|
+
return GIT_READONLY.has(sub);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (base === 'find') {
|
|
190
|
+
return !rest.some((arg) => FIND_UNSAFE_FLAGS.has(arg));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (base === 'sed') {
|
|
194
|
+
// Unsafe when any short-flag cluster contains `i` (in-place) or a long
|
|
195
|
+
// --in-place style flag is present.
|
|
196
|
+
return !rest.some((arg) => {
|
|
197
|
+
if (arg.startsWith('--')) return arg === '--in-place' || arg.startsWith('--in-place=');
|
|
198
|
+
if (arg.startsWith('-') && arg.length > 1) return arg.includes('i');
|
|
199
|
+
return false;
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return SAFE_COMMANDS.has(base);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** True when the command can run without a permission prompt. */
|
|
207
|
+
export function isReadOnlyCommand(command: string): boolean {
|
|
208
|
+
const { segments, unsafe } = parseSegments(command);
|
|
209
|
+
if (unsafe) return false;
|
|
210
|
+
if (segments.length === 0) return false;
|
|
211
|
+
return segments.every((segment) => segmentIsReadOnly(segment.tokens));
|
|
212
|
+
}
|
package/src/agent/tools/types.ts
CHANGED
|
@@ -33,6 +33,8 @@ export interface AgentTool {
|
|
|
33
33
|
schema: z.ZodObject<z.ZodRawShape>;
|
|
34
34
|
kind: ToolKind;
|
|
35
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;
|
|
36
38
|
title(input: Record<string, unknown>): string;
|
|
37
39
|
execute(input: Record<string, unknown>, ctx: ToolContext): Promise<string | ToolOutput>;
|
|
38
40
|
}
|
package/src/cli.ts
CHANGED
|
@@ -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:
|
package/src/commands.test.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
|
-
import { describe, expect, test } from 'bun:test';
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
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
|
+
});
|
|
3
9
|
|
|
4
10
|
describe('init command registration', () => {
|
|
5
11
|
test('is registered so /help lists it', () => {
|
|
@@ -15,3 +21,36 @@ describe('init command registration', () => {
|
|
|
15
21
|
expect(names).toContain('exit');
|
|
16
22
|
});
|
|
17
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;
|
|
@@ -46,6 +47,27 @@ const commands: Command[] = [
|
|
|
46
47
|
output: 'Analyzing the project and writing TRANS.md…',
|
|
47
48
|
}),
|
|
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
|
+
},
|
|
49
71
|
{
|
|
50
72
|
name: 'clear',
|
|
51
73
|
description: 'Clear screen',
|
package/src/screens/REPL.tsx
CHANGED
|
@@ -5,6 +5,7 @@ import { findCommand, getCommands, type CommandContext } from '../commands.js';
|
|
|
5
5
|
import { getAvailableModels, createProviderWithKey, createProvider, setPreferredModel, type ModelId } from '../provider/provider.js';
|
|
6
6
|
import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
|
|
7
7
|
import { createToolSession } from '../agent/tools/index.js';
|
|
8
|
+
import { getPermissionMode } from '../agent/permission.js';
|
|
8
9
|
import { walkFiles } from '../agent/tools/fs-utils.js';
|
|
9
10
|
import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
|
|
10
11
|
import { renderDiff } from './diff-render.js';
|
|
@@ -120,7 +121,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
120
121
|
|
|
121
122
|
const askInTerminal = useCallback(
|
|
122
123
|
(request: PermissionRequest, signal: AbortSignal): Promise<boolean> => {
|
|
123
|
-
const mode =
|
|
124
|
+
const mode = getPermissionMode();
|
|
124
125
|
if (mode === 'auto') return Promise.resolve(true);
|
|
125
126
|
if (mode === 'readonly') return Promise.resolve(false);
|
|
126
127
|
return new Promise<boolean>(resolve => {
|
|
@@ -180,7 +181,8 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
180
181
|
appendChatOutput(`\n⚙ ${event.title}`);
|
|
181
182
|
lastWasTool = true;
|
|
182
183
|
} else if (event.type === 'tool_result') {
|
|
183
|
-
|
|
184
|
+
const marker = event.skippedPermission ? ' ✓ (read-only)' : event.ok ? ' ✓' : ' ✗';
|
|
185
|
+
appendChatOutput(marker);
|
|
184
186
|
if (event.diff) appendChatOutput(`\n${renderDiff(event.diff)}`);
|
|
185
187
|
lastWasTool = true;
|
|
186
188
|
}
|
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.
|
|
2
|
+
export const VERSION = '0.2.2';
|