@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.
- package/README.md +3 -3
- package/docs/ACP.md +2 -2
- package/package.json +2 -1
- package/src/acp/session.ts +7 -3
- package/src/agent/loop.test.ts +113 -0
- package/src/agent/loop.ts +27 -6
- package/src/agent/permission.test.ts +50 -0
- package/src/agent/permission.ts +34 -0
- 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 +315 -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/read-only.test.ts +78 -0
- package/src/agent/tools/read-only.ts +181 -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 +47 -0
- package/src/cli.ts +3 -2
- package/src/commands.test.ts +56 -0
- package/src/commands.ts +31 -0
- package/src/provider/provider.ts +2 -2
- package/src/screens/REPL.tsx +108 -6
- 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
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# transcode
|
|
2
2
|
|
|
3
|
-
多模型 AI 编码 Agent CLI。当前 MVP 的目标是:**作为本地 Agent 被 multica
|
|
3
|
+
多模型 AI 编码 Agent CLI。当前 MVP 的目标是:**作为本地 Agent 被 transonce、multica 等客户端通过 ACP 调用**。
|
|
4
4
|
|
|
5
5
|
- 终端侧:Ink REPL(保留原有命令:`help` / `models` / `clear` / `exit`)
|
|
6
|
-
- Agent 侧:`transcode acp` 启动 ACP v1 stdio 服务,供 multica
|
|
6
|
+
- Agent 侧:`transcode acp` 启动 ACP v1 stdio 服务,供 transonce、multica 等客户端调用
|
|
7
7
|
- 模型侧:Anthropic / OpenAI 及任意 OpenAI 兼容网关(DeepSeek、GLM、MiniMax、Kimi、自建网关等)
|
|
8
8
|
- 工具侧:`read_file` / `write_file` / `edit_file` / `glob` / `grep` / `bash`
|
|
9
9
|
|
|
@@ -84,7 +84,7 @@ bun run test:acp:real # 完整 ACP + 工具调用(会创建临时 works
|
|
|
84
84
|
## 本地运行
|
|
85
85
|
|
|
86
86
|
```bash
|
|
87
|
-
# ACP 服务(给 multica
|
|
87
|
+
# ACP 服务(给 transonce / multica 等 ACP 客户端用)
|
|
88
88
|
bun bin/transcode.ts acp
|
|
89
89
|
|
|
90
90
|
# 交互式 REPL
|
package/docs/ACP.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# transcode ACP 协议说明
|
|
2
2
|
|
|
3
|
-
transcode 实现了 [Agent Client Protocol (ACP) v1](https://agentclientprotocol.com/) 的最小子集,通过 stdin/stdout 上的换行分隔 JSON-RPC 2.0 通信。multica
|
|
3
|
+
transcode 实现了 [Agent Client Protocol (ACP) v1](https://agentclientprotocol.com/) 的最小子集,通过 stdin/stdout 上的换行分隔 JSON-RPC 2.0 通信。transonce、multica 等客户端可以把 transcode 当作一个本地 ACP runtime 启动。
|
|
4
4
|
|
|
5
5
|
## 启动
|
|
6
6
|
|
|
@@ -119,7 +119,7 @@ bun bin/transcode.ts acp
|
|
|
119
119
|
| `tool_call` | 工具开始:`toolCallId`、`name`、`title`、`kind`、`status: "pending"`、`rawInput` |
|
|
120
120
|
| `tool_call_update` | 工具结束:`toolCallId`、`status: "completed" \| "failed"`、`content` |
|
|
121
121
|
|
|
122
|
-
工具标题使用 ACP 常见前缀,便于 multica
|
|
122
|
+
工具标题使用 ACP 常见前缀,便于 transonce / multica 等客户端映射:
|
|
123
123
|
|
|
124
124
|
- `terminal: <command>`
|
|
125
125
|
- `read: <path>`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trans-ai/trans-code",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "AI-powered multi-model coding CLI",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
"dev": "bun run build:repl && node dist/main.js",
|
|
24
24
|
"acp": "bun bin/transcode.ts acp",
|
|
25
25
|
"typecheck": "tsc --noEmit",
|
|
26
|
+
"test": "bun test",
|
|
26
27
|
"test:acp": "bun scripts/acp-smoke.ts",
|
|
27
28
|
"test:acp:openai": "bun scripts/acp-openai-smoke.ts",
|
|
28
29
|
"test:acp:real": "bun scripts/acp-real-smoke.ts",
|
package/src/acp/session.ts
CHANGED
|
@@ -8,6 +8,8 @@ import {
|
|
|
8
8
|
} from '@langchain/core/messages';
|
|
9
9
|
import { createModel, getAvailableModels, resolveModel } from '../provider/provider.js';
|
|
10
10
|
import { runAgentLoop, type AgentEvent, type PermissionRequest } from '../agent/loop.js';
|
|
11
|
+
import { createToolSession, type ToolSession } from '../agent/tools/index.js';
|
|
12
|
+
import { getPermissionMode } from '../agent/permission.js';
|
|
11
13
|
import { buildSystemPrompt, loadProjectContext } from '../agent/system-prompt.js';
|
|
12
14
|
import {
|
|
13
15
|
RPC_ERRORS,
|
|
@@ -65,9 +67,7 @@ function promptText(prompt: AcpPromptBlock[]): string {
|
|
|
65
67
|
}
|
|
66
68
|
|
|
67
69
|
function permissionMode(): 'ask' | 'auto' | 'readonly' {
|
|
68
|
-
|
|
69
|
-
if (value === 'auto' || value === 'readonly') return value;
|
|
70
|
-
return 'ask';
|
|
70
|
+
return getPermissionMode();
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
export class AcpSession {
|
|
@@ -76,6 +76,8 @@ export class AcpSession {
|
|
|
76
76
|
private busy = false;
|
|
77
77
|
private abortController?: AbortController;
|
|
78
78
|
private modelSpec: string;
|
|
79
|
+
/** Shared across prompts: shell cwd persistence and read-file tracking. */
|
|
80
|
+
private readonly toolSession: ToolSession;
|
|
79
81
|
|
|
80
82
|
constructor(
|
|
81
83
|
private readonly host: AcpSessionHost,
|
|
@@ -83,6 +85,7 @@ export class AcpSession {
|
|
|
83
85
|
modelSpec?: string,
|
|
84
86
|
) {
|
|
85
87
|
this.modelSpec = modelSpec?.trim() || process.env.TRANSCODE_MODEL || '';
|
|
88
|
+
this.toolSession = createToolSession(cwd);
|
|
86
89
|
}
|
|
87
90
|
|
|
88
91
|
get modelState(): AcpSessionModelState {
|
|
@@ -136,6 +139,7 @@ export class AcpSession {
|
|
|
136
139
|
messages: this.messages,
|
|
137
140
|
systemPrompt,
|
|
138
141
|
signal,
|
|
142
|
+
toolSession: this.toolSession,
|
|
139
143
|
onEvent: (event) => this.forwardEvent(event),
|
|
140
144
|
requestPermission: (request) => this.askPermission(request, signal),
|
|
141
145
|
});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { AIMessageChunk } from '@langchain/core/messages';
|
|
3
|
+
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
|
4
|
+
import type { AgentEvent } from './loop.js';
|
|
5
|
+
import { runAgentLoop } from './loop.js';
|
|
6
|
+
import type { AgentTool } from './tools/index.js';
|
|
7
|
+
|
|
8
|
+
/** Streams one tool call on the first turn, plain text afterwards. */
|
|
9
|
+
function stubModel(): BaseChatModel {
|
|
10
|
+
let calls = 0;
|
|
11
|
+
const runnable = {
|
|
12
|
+
async stream(): Promise<AsyncIterable<{ content: unknown; tool_call_chunks?: unknown[] }>> {
|
|
13
|
+
calls++;
|
|
14
|
+
const chunks =
|
|
15
|
+
calls === 1
|
|
16
|
+
? [
|
|
17
|
+
new AIMessageChunk({
|
|
18
|
+
content: '',
|
|
19
|
+
tool_call_chunks: [{ id: 'call_1', name: 'fake', args: '{}', index: 0 }],
|
|
20
|
+
}),
|
|
21
|
+
]
|
|
22
|
+
: [new AIMessageChunk({ content: 'done' })];
|
|
23
|
+
return (async function* () {
|
|
24
|
+
yield* chunks;
|
|
25
|
+
})();
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
return { bindTools: () => runnable } as unknown as BaseChatModel;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const fakeTool: AgentTool = {
|
|
32
|
+
name: 'fake',
|
|
33
|
+
description: 'test double',
|
|
34
|
+
schema: (await import('zod')).z.object({}),
|
|
35
|
+
kind: 'other',
|
|
36
|
+
isMutating: true,
|
|
37
|
+
title: () => 'fake',
|
|
38
|
+
async execute() {
|
|
39
|
+
return { output: 'ok', diff: '+added-line' };
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
describe('runAgentLoop', () => {
|
|
44
|
+
test('tool_result events carry the diff produced by the tool', async () => {
|
|
45
|
+
const events: AgentEvent[] = [];
|
|
46
|
+
const result = await runAgentLoop({
|
|
47
|
+
model: stubModel(),
|
|
48
|
+
cwd: '/tmp',
|
|
49
|
+
messages: [],
|
|
50
|
+
systemPrompt: 'test',
|
|
51
|
+
tools: [fakeTool],
|
|
52
|
+
onEvent: (event) => {
|
|
53
|
+
events.push(event);
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
expect(result.stopReason).toBe('end_turn');
|
|
58
|
+
const toolResult = events.find((event) => event.type === 'tool_result');
|
|
59
|
+
expect(toolResult).toBeDefined();
|
|
60
|
+
expect(toolResult && toolResult.type === 'tool_result' ? toolResult.diff : undefined).toBe(
|
|
61
|
+
'+added-line',
|
|
62
|
+
);
|
|
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
|
+
});
|
|
113
|
+
});
|
package/src/agent/loop.ts
CHANGED
|
@@ -12,9 +12,11 @@ import {
|
|
|
12
12
|
bindableTools,
|
|
13
13
|
findAgentTool,
|
|
14
14
|
invokeTool,
|
|
15
|
+
createToolSession,
|
|
15
16
|
type AgentTool,
|
|
16
17
|
type ToolKind,
|
|
17
|
-
|
|
18
|
+
type ToolSession,
|
|
19
|
+
} from './tools/index.js';
|
|
18
20
|
|
|
19
21
|
export type AgentEvent =
|
|
20
22
|
| { type: 'text'; text: string }
|
|
@@ -33,6 +35,10 @@ export type AgentEvent =
|
|
|
33
35
|
name: string;
|
|
34
36
|
output: string;
|
|
35
37
|
ok: boolean;
|
|
38
|
+
/** Unified diff for UI rendering; not sent to the model. */
|
|
39
|
+
diff?: string;
|
|
40
|
+
/** True when a mutating tool ran without prompting (read-only input). */
|
|
41
|
+
skippedPermission?: boolean;
|
|
36
42
|
};
|
|
37
43
|
|
|
38
44
|
export interface PermissionRequest {
|
|
@@ -61,6 +67,8 @@ export interface AgentLoopOptions {
|
|
|
61
67
|
signal?: AbortSignal;
|
|
62
68
|
onEvent: (event: AgentEvent) => void | Promise<void>;
|
|
63
69
|
requestPermission?: RequestPermission;
|
|
70
|
+
/** Session state shared across tool calls (shell cwd, read files). Created when absent. */
|
|
71
|
+
toolSession?: ToolSession;
|
|
64
72
|
}
|
|
65
73
|
|
|
66
74
|
export interface AgentLoopResult {
|
|
@@ -148,6 +156,7 @@ async function runMockTurn(
|
|
|
148
156
|
options: AgentLoopOptions,
|
|
149
157
|
prompt: string,
|
|
150
158
|
): Promise<StopReason> {
|
|
159
|
+
const toolSession = options.toolSession ?? createToolSession(options.cwd);
|
|
151
160
|
if (prompt.includes('MOCK_TOOL_BASH')) {
|
|
152
161
|
const tool = findAgentTool('bash');
|
|
153
162
|
const input = { command: 'echo mock-tool-ok' };
|
|
@@ -178,7 +187,11 @@ async function runMockTurn(
|
|
|
178
187
|
: true;
|
|
179
188
|
|
|
180
189
|
const result = allowed
|
|
181
|
-
? await invokeTool(tool, input, {
|
|
190
|
+
? await invokeTool(tool, input, {
|
|
191
|
+
cwd: toolSession.cwd,
|
|
192
|
+
signal: options.signal,
|
|
193
|
+
session: toolSession,
|
|
194
|
+
})
|
|
182
195
|
: { ok: false, output: 'Permission denied.' };
|
|
183
196
|
|
|
184
197
|
await options.onEvent({
|
|
@@ -187,6 +200,7 @@ async function runMockTurn(
|
|
|
187
200
|
name: tool.name,
|
|
188
201
|
output: result.output,
|
|
189
202
|
ok: result.ok,
|
|
203
|
+
diff: result.diff,
|
|
190
204
|
});
|
|
191
205
|
|
|
192
206
|
options.messages.push(
|
|
@@ -229,6 +243,7 @@ export async function runAgentLoop(
|
|
|
229
243
|
|
|
230
244
|
const tools = options.tools ?? AGENT_TOOLS;
|
|
231
245
|
const maxTurns = options.maxTurns ?? 50;
|
|
246
|
+
const toolSession = options.toolSession ?? createToolSession(options.cwd);
|
|
232
247
|
if (!options.model) throw new Error('No model configured for the agent loop');
|
|
233
248
|
|
|
234
249
|
const runnable =
|
|
@@ -275,7 +290,7 @@ export async function runAgentLoop(
|
|
|
275
290
|
if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
|
|
276
291
|
|
|
277
292
|
const input = (call.args ?? {}) as Record<string, unknown>;
|
|
278
|
-
const tool = findAgentTool(call.name);
|
|
293
|
+
const tool = tools.find((item) => item.name === call.name) ?? findAgentTool(call.name);
|
|
279
294
|
const toolCallId = call.id ?? `call_${turn}_${call.name}`;
|
|
280
295
|
const title = tool ? tool.title(input) : call.name;
|
|
281
296
|
|
|
@@ -288,11 +303,14 @@ export async function runAgentLoop(
|
|
|
288
303
|
input,
|
|
289
304
|
});
|
|
290
305
|
|
|
291
|
-
let result: { ok: boolean; output: string };
|
|
306
|
+
let result: { ok: boolean; output: string; diff?: string };
|
|
307
|
+
let skippedPermission = false;
|
|
292
308
|
if (!tool) {
|
|
293
309
|
result = { ok: false, output: `Unknown tool: ${call.name}` };
|
|
294
310
|
} else {
|
|
295
|
-
const
|
|
311
|
+
const readOnly = tool.isReadOnly?.(input) === true;
|
|
312
|
+
const needsPermission = tool.isMutating && !readOnly;
|
|
313
|
+
skippedPermission = tool.isMutating && readOnly;
|
|
296
314
|
const allowed =
|
|
297
315
|
!needsPermission || !options.requestPermission
|
|
298
316
|
? true
|
|
@@ -306,8 +324,9 @@ export async function runAgentLoop(
|
|
|
306
324
|
|
|
307
325
|
result = allowed
|
|
308
326
|
? await invokeTool(tool, input, {
|
|
309
|
-
cwd:
|
|
327
|
+
cwd: toolSession.cwd,
|
|
310
328
|
signal: options.signal,
|
|
329
|
+
session: toolSession,
|
|
311
330
|
})
|
|
312
331
|
: { ok: false, output: 'Permission denied by the client.' };
|
|
313
332
|
}
|
|
@@ -318,6 +337,8 @@ export async function runAgentLoop(
|
|
|
318
337
|
name: call.name,
|
|
319
338
|
output: result.output,
|
|
320
339
|
ok: result.ok,
|
|
340
|
+
diff: result.diff,
|
|
341
|
+
skippedPermission,
|
|
321
342
|
});
|
|
322
343
|
|
|
323
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
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
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 { INIT_PROMPT, loadProjectContext } from './system-prompt.js';
|
|
6
|
+
|
|
7
|
+
const cleanups: Array<() => void> = [];
|
|
8
|
+
afterEach(() => {
|
|
9
|
+
while (cleanups.length) cleanups.pop()!();
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
function workspace(): string {
|
|
13
|
+
const dir = mkdtempSync(path.join(tmpdir(), 'transcode-init-'));
|
|
14
|
+
cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
|
|
15
|
+
return dir;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
describe('loadProjectContext', () => {
|
|
19
|
+
test('reads TRANS.md as a project context file', async () => {
|
|
20
|
+
const dir = workspace();
|
|
21
|
+
writeFileSync(path.join(dir, 'TRANS.md'), '# Project\nSome rules.\n');
|
|
22
|
+
|
|
23
|
+
const context = await loadProjectContext(dir);
|
|
24
|
+
const entry = context.projectFiles.find((file) => file.path === 'TRANS.md');
|
|
25
|
+
expect(entry).toBeDefined();
|
|
26
|
+
expect(entry?.content).toContain('Some rules.');
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('reads CLAUDE.md and AGENTS.md too, with TRANS.md taking priority', async () => {
|
|
30
|
+
const dir = workspace();
|
|
31
|
+
writeFileSync(path.join(dir, 'TRANS.md'), 'trans rules\n');
|
|
32
|
+
writeFileSync(path.join(dir, 'CLAUDE.md'), 'claude rules\n');
|
|
33
|
+
writeFileSync(path.join(dir, 'AGENTS.md'), 'agents rules\n');
|
|
34
|
+
|
|
35
|
+
const context = await loadProjectContext(dir);
|
|
36
|
+
expect(context.projectFiles.map((file) => file.path)).toEqual([
|
|
37
|
+
'TRANS.md',
|
|
38
|
+
'AGENTS.md',
|
|
39
|
+
'CLAUDE.md',
|
|
40
|
+
]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('returns no project files when none exist', async () => {
|
|
44
|
+
const context = await loadProjectContext(workspace());
|
|
45
|
+
expect(context.projectFiles.length).toBe(0);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('INIT_PROMPT', () => {
|
|
50
|
+
test('instructs the agent to analyze the project and write TRANS.md only', () => {
|
|
51
|
+
expect(INIT_PROMPT).toContain('TRANS.md');
|
|
52
|
+
expect(INIT_PROMPT.toLowerCase()).toContain('analyze');
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -1,9 +1,22 @@
|
|
|
1
1
|
import { promises as fs } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
|
|
4
|
-
const CONTEXT_FILES = ['AGENTS.md', 'CLAUDE.md', 'TRANSCODE.md', '.transcode/AGENTS.md'];
|
|
4
|
+
const CONTEXT_FILES = ['TRANS.md', 'AGENTS.md', 'CLAUDE.md', 'TRANSCODE.md', '.transcode/AGENTS.md'];
|
|
5
5
|
const MAX_CONTEXT_CHARS = 40_000;
|
|
6
6
|
|
|
7
|
+
/** Prompt behind /init: agent analyzes the project and writes TRANS.md. */
|
|
8
|
+
export const INIT_PROMPT = `Analyze this project and create a TRANS.md file at the workspace root that records the project background and working rules, like CLAUDE.md does for Claude Code.
|
|
9
|
+
|
|
10
|
+
Explore first with glob, grep and read_file: README, package.json (or other manifest) scripts, the directory layout, entry points, build/test/lint tooling, and any existing contributor docs. Do not guess what you can read.
|
|
11
|
+
|
|
12
|
+
Then write TRANS.md with these sections (keep the whole file under 60 lines):
|
|
13
|
+
- Project overview: what this project is, in 2-3 sentences
|
|
14
|
+
- Commands: how to install, build, test, lint/typecheck — exact commands
|
|
15
|
+
- Architecture: key directories/modules and how they fit together
|
|
16
|
+
- Conventions: naming, code style, commit message style if discoverable
|
|
17
|
+
|
|
18
|
+
Write TRANS.md only; do not modify any other file. Reply with a one-paragraph summary when done.`;
|
|
19
|
+
|
|
7
20
|
export interface ProjectContext {
|
|
8
21
|
cwd: string;
|
|
9
22
|
gitBranch?: string;
|
|
@@ -76,6 +89,7 @@ export function buildSystemPrompt(
|
|
|
76
89
|
'## How to work',
|
|
77
90
|
'- Inspect the repository before changing it. Read the relevant files first.',
|
|
78
91
|
'- Prefer read_file, glob and grep for exploration; use bash for builds, tests and git.',
|
|
92
|
+
'- The bash working directory persists across calls; you do not need to cd again each time.',
|
|
79
93
|
'- Use edit_file for targeted changes and write_file for new files.',
|
|
80
94
|
'- Keep changes focused on the task. Do not undo unrelated user work.',
|
|
81
95
|
'- After changing code, run the cheapest relevant check (typecheck, targeted test) when available.',
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { bashTool } from './bash.js';
|
|
6
|
+
import { createToolSession, type ToolSession } from './session.js';
|
|
7
|
+
import type { ToolContext } from './types.js';
|
|
8
|
+
|
|
9
|
+
const cleanups: Array<() => void> = [];
|
|
10
|
+
const savedEnv: Record<string, string | undefined> = {};
|
|
11
|
+
function setEnv(key: string, value: string | undefined): void {
|
|
12
|
+
if (!(key in savedEnv)) savedEnv[key] = process.env[key];
|
|
13
|
+
if (value === undefined) delete process.env[key];
|
|
14
|
+
else process.env[key] = value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
afterEach(() => {
|
|
18
|
+
while (cleanups.length) cleanups.pop()!();
|
|
19
|
+
for (const [key, value] of Object.entries(savedEnv)) {
|
|
20
|
+
if (value === undefined) delete process.env[key];
|
|
21
|
+
else process.env[key] = value;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
function workspace(): string {
|
|
26
|
+
const dir = mkdtempSync(path.join(tmpdir(), 'transcode-bash-'));
|
|
27
|
+
cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
|
|
28
|
+
return dir;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function ctx(session: ToolSession): ToolContext {
|
|
32
|
+
return { cwd: session.cwd, session };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function run(session: ToolSession, command: string, input: Record<string, unknown> = {}) {
|
|
36
|
+
const result = await bashTool.execute({ command, ...input }, ctx(session));
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
describe('bash tool', () => {
|
|
41
|
+
test('runs a simple command and returns its output', async () => {
|
|
42
|
+
const session = createToolSession(workspace());
|
|
43
|
+
const output = await run(session, 'echo hello-tools');
|
|
44
|
+
expect(output).toContain('hello-tools');
|
|
45
|
+
expect(output).toContain('[exit] code=0');
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test('cd persists across bash calls', async () => {
|
|
49
|
+
const dir = workspace();
|
|
50
|
+
mkdirSync(path.join(dir, 'sub'));
|
|
51
|
+
const session = createToolSession(dir);
|
|
52
|
+
|
|
53
|
+
await run(session, 'cd sub');
|
|
54
|
+
// pwd -P captures the physical path (/private/var/... on macOS).
|
|
55
|
+
expect(session.cwd).toBe(path.join(realpathSync(dir), 'sub'));
|
|
56
|
+
|
|
57
|
+
const output = await run(session, 'basename "$(pwd)"');
|
|
58
|
+
expect(output).toContain('sub');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('failed command still updates the session cwd', async () => {
|
|
62
|
+
const dir = workspace();
|
|
63
|
+
mkdirSync(path.join(dir, 'sub'));
|
|
64
|
+
const session = createToolSession(dir);
|
|
65
|
+
|
|
66
|
+
// A failing (non-zero) command must still update cwd; note that a literal
|
|
67
|
+
// `exit N` cannot — it terminates the shell before the pwd trailer runs.
|
|
68
|
+
const output = await run(session, 'cd sub && cat /nonexistent-file');
|
|
69
|
+
expect(output).toContain('code=1');
|
|
70
|
+
expect(session.cwd).toBe(path.join(realpathSync(dir), 'sub'));
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('injects GIT_EDITOR and TRANSCODE environment markers', async () => {
|
|
74
|
+
const session = createToolSession(workspace());
|
|
75
|
+
const output = await run(session, 'echo "$GIT_EDITOR/$TRANSCODE"');
|
|
76
|
+
expect(output).toContain('true/1');
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('aliases from the user shell config survive via the snapshot', async () => {
|
|
80
|
+
const home = mkdtempSync(path.join(tmpdir(), 'transcode-home-'));
|
|
81
|
+
cleanups.push(() => rmSync(home, { recursive: true, force: true }));
|
|
82
|
+
writeFileSync(path.join(home, '.bashrc'), "alias tsmoke='echo alias-ok'\\n");
|
|
83
|
+
setEnv('HOME', home);
|
|
84
|
+
setEnv('SHELL', '/bin/bash');
|
|
85
|
+
|
|
86
|
+
const session = createToolSession(workspace());
|
|
87
|
+
const output = await run(session, 'tsmoke');
|
|
88
|
+
expect(output).toContain('alias-ok');
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test('times out long-running commands and reports it', async () => {
|
|
92
|
+
const session = createToolSession(workspace());
|
|
93
|
+
const output = await run(session, 'sleep 5', { timeout_ms: 1000 });
|
|
94
|
+
expect(output).toMatch(/timed out after 1000ms/);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('truncates oversized output keeping head and tail', async () => {
|
|
98
|
+
const session = createToolSession(workspace());
|
|
99
|
+
const output = await run(session, "head -c 60000 /dev/zero | tr '\\0' x");
|
|
100
|
+
expect(output).toContain('[35000 bytes truncated]');
|
|
101
|
+
expect(output.startsWith('xxxx')).toBe(true);
|
|
102
|
+
expect(output.includes('x'.repeat(10000))).toBe(true);
|
|
103
|
+
expect(output.length).toBeLessThan(30000);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('recovers to the workspace root when the cwd was deleted', async () => {
|
|
107
|
+
const dir = workspace();
|
|
108
|
+
const session = createToolSession(dir);
|
|
109
|
+
session.cwd = path.join(dir, 'gone');
|
|
110
|
+
|
|
111
|
+
const output = await run(session, 'basename "$(pwd)"');
|
|
112
|
+
expect(output).toContain(path.basename(dir));
|
|
113
|
+
expect(session.cwd).toBe(realpathSync(dir));
|
|
114
|
+
});
|
|
115
|
+
});
|