@trans-ai/trans-code 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # transcode
2
2
 
3
- 多模型 AI 编码 Agent CLI。当前 MVP 的目标是:**作为本地 Agent 被 multica 通过 ACP 调用**。
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 daemon 等客户端调用
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 daemon 可以把 transcode 当作一个本地 ACP runtime 启动。
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.4",
3
+ "version": "0.2.0",
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",
@@ -8,6 +8,7 @@ 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';
11
12
  import { buildSystemPrompt, loadProjectContext } from '../agent/system-prompt.js';
12
13
  import {
13
14
  RPC_ERRORS,
@@ -76,6 +77,8 @@ export class AcpSession {
76
77
  private busy = false;
77
78
  private abortController?: AbortController;
78
79
  private modelSpec: string;
80
+ /** Shared across prompts: shell cwd persistence and read-file tracking. */
81
+ private readonly toolSession: ToolSession;
79
82
 
80
83
  constructor(
81
84
  private readonly host: AcpSessionHost,
@@ -83,6 +86,7 @@ export class AcpSession {
83
86
  modelSpec?: string,
84
87
  ) {
85
88
  this.modelSpec = modelSpec?.trim() || process.env.TRANSCODE_MODEL || '';
89
+ this.toolSession = createToolSession(cwd);
86
90
  }
87
91
 
88
92
  get modelState(): AcpSessionModelState {
@@ -136,6 +140,7 @@ export class AcpSession {
136
140
  messages: this.messages,
137
141
  systemPrompt,
138
142
  signal,
143
+ toolSession: this.toolSession,
139
144
  onEvent: (event) => this.forwardEvent(event),
140
145
  requestPermission: (request) => this.askPermission(request, signal),
141
146
  });
@@ -0,0 +1,64 @@
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: false,
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
+ });
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
- } from './tools.js';
18
+ type ToolSession,
19
+ } from './tools/index.js';
18
20
 
19
21
  export type AgentEvent =
20
22
  | { type: 'text'; text: string }
@@ -33,6 +35,8 @@ 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;
36
40
  };
37
41
 
38
42
  export interface PermissionRequest {
@@ -61,6 +65,8 @@ export interface AgentLoopOptions {
61
65
  signal?: AbortSignal;
62
66
  onEvent: (event: AgentEvent) => void | Promise<void>;
63
67
  requestPermission?: RequestPermission;
68
+ /** Session state shared across tool calls (shell cwd, read files). Created when absent. */
69
+ toolSession?: ToolSession;
64
70
  }
65
71
 
66
72
  export interface AgentLoopResult {
@@ -148,6 +154,7 @@ async function runMockTurn(
148
154
  options: AgentLoopOptions,
149
155
  prompt: string,
150
156
  ): Promise<StopReason> {
157
+ const toolSession = options.toolSession ?? createToolSession(options.cwd);
151
158
  if (prompt.includes('MOCK_TOOL_BASH')) {
152
159
  const tool = findAgentTool('bash');
153
160
  const input = { command: 'echo mock-tool-ok' };
@@ -178,7 +185,11 @@ async function runMockTurn(
178
185
  : true;
179
186
 
180
187
  const result = allowed
181
- ? await invokeTool(tool, input, { cwd: options.cwd, signal: options.signal })
188
+ ? await invokeTool(tool, input, {
189
+ cwd: toolSession.cwd,
190
+ signal: options.signal,
191
+ session: toolSession,
192
+ })
182
193
  : { ok: false, output: 'Permission denied.' };
183
194
 
184
195
  await options.onEvent({
@@ -187,6 +198,7 @@ async function runMockTurn(
187
198
  name: tool.name,
188
199
  output: result.output,
189
200
  ok: result.ok,
201
+ diff: result.diff,
190
202
  });
191
203
 
192
204
  options.messages.push(
@@ -229,6 +241,7 @@ export async function runAgentLoop(
229
241
 
230
242
  const tools = options.tools ?? AGENT_TOOLS;
231
243
  const maxTurns = options.maxTurns ?? 50;
244
+ const toolSession = options.toolSession ?? createToolSession(options.cwd);
232
245
  if (!options.model) throw new Error('No model configured for the agent loop');
233
246
 
234
247
  const runnable =
@@ -275,7 +288,7 @@ export async function runAgentLoop(
275
288
  if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
276
289
 
277
290
  const input = (call.args ?? {}) as Record<string, unknown>;
278
- const tool = findAgentTool(call.name);
291
+ const tool = tools.find((item) => item.name === call.name) ?? findAgentTool(call.name);
279
292
  const toolCallId = call.id ?? `call_${turn}_${call.name}`;
280
293
  const title = tool ? tool.title(input) : call.name;
281
294
 
@@ -288,7 +301,7 @@ export async function runAgentLoop(
288
301
  input,
289
302
  });
290
303
 
291
- let result: { ok: boolean; output: string };
304
+ let result: { ok: boolean; output: string; diff?: string };
292
305
  if (!tool) {
293
306
  result = { ok: false, output: `Unknown tool: ${call.name}` };
294
307
  } else {
@@ -306,8 +319,9 @@ export async function runAgentLoop(
306
319
 
307
320
  result = allowed
308
321
  ? await invokeTool(tool, input, {
309
- cwd: options.cwd,
322
+ cwd: toolSession.cwd,
310
323
  signal: options.signal,
324
+ session: toolSession,
311
325
  })
312
326
  : { ok: false, output: 'Permission denied by the client.' };
313
327
  }
@@ -318,6 +332,7 @@ export async function runAgentLoop(
318
332
  name: call.name,
319
333
  output: result.output,
320
334
  ok: result.ok,
335
+ diff: result.diff,
321
336
  });
322
337
 
323
338
  messages.push(
@@ -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
+ });