@trans-ai/trans-code 0.2.1 → 0.2.3

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trans-ai/trans-code",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "AI-powered multi-model coding CLI",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -28,6 +28,31 @@ function stubModel(): BaseChatModel {
28
28
  return { bindTools: () => runnable } as unknown as BaseChatModel;
29
29
  }
30
30
 
31
+ type ScriptStep = { tool: string; args?: string } | { text: string };
32
+
33
+ /** Replays a scripted sequence: one step per stream call, then ends. */
34
+ function scriptedModel(steps: ScriptStep[]): BaseChatModel {
35
+ let calls = 0;
36
+ const runnable = {
37
+ async stream(): Promise<AsyncIterable<{ content: unknown; tool_call_chunks?: unknown[] }>> {
38
+ const step = steps[calls++] ?? { text: 'done' };
39
+ const chunk =
40
+ 'tool' in step
41
+ ? new AIMessageChunk({
42
+ content: '',
43
+ tool_call_chunks: [
44
+ { id: `call_${calls}`, name: step.tool, args: step.args ?? '{}', index: 0 },
45
+ ],
46
+ })
47
+ : new AIMessageChunk({ content: step.text });
48
+ return (async function* () {
49
+ yield chunk;
50
+ })();
51
+ },
52
+ };
53
+ return { bindTools: () => runnable } as unknown as BaseChatModel;
54
+ }
55
+
31
56
  const fakeTool: AgentTool = {
32
57
  name: 'fake',
33
58
  description: 'test double',
@@ -110,4 +135,67 @@ describe('runAgentLoop', () => {
110
135
  });
111
136
  expect(permissionAsked).toBe(1);
112
137
  });
138
+
139
+ test('blocks the third consecutive identical call and guides the model', async () => {
140
+ let executions = 0;
141
+ const countingTool: AgentTool = {
142
+ ...fakeTool,
143
+ async execute() {
144
+ executions++;
145
+ return 'ok';
146
+ },
147
+ };
148
+ const events: AgentEvent[] = [];
149
+
150
+ const result = await runAgentLoop({
151
+ model: scriptedModel([
152
+ { tool: 'fake', args: '{"a":1}' },
153
+ { tool: 'fake', args: '{"a":1}' },
154
+ { tool: 'fake', args: '{"a":1}' },
155
+ { tool: 'fake', args: '{"a":1}' },
156
+ ]),
157
+ cwd: '/tmp',
158
+ messages: [],
159
+ systemPrompt: 'test',
160
+ tools: [countingTool],
161
+ onEvent: (event) => events.push(event),
162
+ });
163
+
164
+ expect(result.stopReason).toBe('end_turn');
165
+ expect(executions).toBe(2);
166
+ const results = events.filter((event) => event.type === 'tool_result');
167
+ expect(results.length).toBe(4);
168
+ const blocked = results[2];
169
+ expect(blocked && blocked.type === 'tool_result' ? blocked.ok : true).toBe(false);
170
+ expect(blocked && blocked.type === 'tool_result' ? blocked.output : '').toMatch(
171
+ /already executed/i,
172
+ );
173
+ });
174
+
175
+ test('a different call resets the repetition counter', async () => {
176
+ let executions = 0;
177
+ const countingTool: AgentTool = {
178
+ ...fakeTool,
179
+ async execute() {
180
+ executions++;
181
+ return 'ok';
182
+ },
183
+ };
184
+
185
+ await runAgentLoop({
186
+ model: scriptedModel([
187
+ { tool: 'fake', args: '{"a":1}' },
188
+ { tool: 'fake', args: '{"a":1}' },
189
+ { tool: 'fake', args: '{"a":2}' },
190
+ { tool: 'fake', args: '{"a":1}' },
191
+ ]),
192
+ cwd: '/tmp',
193
+ messages: [],
194
+ systemPrompt: 'test',
195
+ tools: [countingTool],
196
+ onEvent: () => {},
197
+ });
198
+
199
+ expect(executions).toBe(4);
200
+ });
113
201
  });
package/src/agent/loop.ts CHANGED
@@ -143,6 +143,19 @@ function parseToolCalls(
143
143
  return calls;
144
144
  }
145
145
 
146
+ const REPEAT_GUIDANCE =
147
+ 'This exact command was already executed twice in a row with the same arguments; repeating it ' +
148
+ 'will not produce new information. Change your approach: use read_file to view file contents, ' +
149
+ 'narrow the search pattern, or answer from the results you already have.';
150
+
151
+ function stableKey(value: unknown): string {
152
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
153
+ const record = value as Record<string, unknown>;
154
+ return JSON.stringify(Object.keys(record).sort().map((key) => [key, record[key]]));
155
+ }
156
+ return JSON.stringify(value) ?? '';
157
+ }
158
+
146
159
  function lastHumanText(messages: BaseMessage[]): string {
147
160
  for (let index = messages.length - 1; index >= 0; index--) {
148
161
  if (messages[index].getType() === 'human') {
@@ -251,6 +264,9 @@ export async function runAgentLoop(
251
264
  ? options.model.bindTools(bindableTools(tools))
252
265
  : options.model;
253
266
 
267
+ let repeatedKey: string | undefined;
268
+ let repeatCount = 0;
269
+
254
270
  for (let turn = 0; turn < maxTurns; turn++) {
255
271
  if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
256
272
 
@@ -305,8 +321,20 @@ export async function runAgentLoop(
305
321
 
306
322
  let result: { ok: boolean; output: string; diff?: string };
307
323
  let skippedPermission = false;
324
+
325
+ // Circuit breaker: the third consecutive identical call is refused
326
+ // instead of executed, with guidance to change approach.
327
+ const key = `${call.name}:${stableKey(input)}`;
328
+ if (key === repeatedKey) repeatCount++;
329
+ else {
330
+ repeatedKey = key;
331
+ repeatCount = 1;
332
+ }
333
+
308
334
  if (!tool) {
309
335
  result = { ok: false, output: `Unknown tool: ${call.name}` };
336
+ } else if (repeatCount >= 3) {
337
+ result = { ok: false, output: `Error: ${REPEAT_GUIDANCE}` };
310
338
  } else {
311
339
  const readOnly = tool.isReadOnly?.(input) === true;
312
340
  const needsPermission = tool.isMutating && !readOnly;
@@ -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,7 +89,10 @@ 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
+ '- View file contents with read_file (NOT cat/head/tail/sed); check unknown file sizes with ' +
93
+ 'wc -l first and read large files in offset/limit chunks. Do not cat entire files into the conversation.',
92
94
  '- The bash working directory persists across calls; you do not need to cd again each time.',
95
+ '- Never repeat an identical tool call; refine it or switch tools.',
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.',
95
98
  '- After changing code, run the cheapest relevant check (typecheck, targeted test) when available.',
@@ -6,6 +6,24 @@ 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 uses claudecode-style hard wording against file dumps', () => {
11
+ const d = bashTool.description;
12
+ expect(d).toContain('IMPORTANT');
13
+ expect(d).toContain('NOT cat');
14
+ expect(d).toContain('NOT sed');
15
+ expect(d).toContain('glob');
16
+ expect(d).toContain('write_file');
17
+ expect(d).toContain('Never repeat');
18
+ expect(d).toContain('absolute paths');
19
+ });
20
+
21
+ test('isReadOnly is wired to the analyzer', () => {
22
+ expect(bashTool.isReadOnly?.({ command: 'cat config.py 2>/dev/null' })).toBe(true);
23
+ expect(bashTool.isReadOnly?.({ command: 'npm install' })).toBe(false);
24
+ });
25
+ });
26
+
9
27
  const cleanups: Array<() => void> = [];
10
28
  const savedEnv: Record<string, string | undefined> = {};
11
29
  function setEnv(key: string, value: string | undefined): void {
@@ -216,9 +216,19 @@ function killProcessGroup(pid: number | undefined, signal: NodeJS.Signals): void
216
216
  export const bashTool: AgentTool = {
217
217
  name: 'bash',
218
218
  description:
219
- 'Run a shell command in the workspace using the user shell. Working directory changes (cd) ' +
220
- 'persist across calls. Returns stdout, stderr and the exit code. ' +
221
- 'Prefer dedicated read/write/edit/glob/grep tools for file operations.',
219
+ 'Run a shell command in the workspace using the user shell. The working directory persists ' +
220
+ 'between calls. Returns stdout, stderr and the exit code.\n' +
221
+ 'IMPORTANT: Avoid using this tool for `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk` or ' +
222
+ '`echo` unless explicitly instructed or you have verified a dedicated tool cannot do it:\n' +
223
+ '- Find files: Use glob (NOT find or ls)\n' +
224
+ '- Search content: Use the grep tool (NOT bash grep/rg)\n' +
225
+ '- Read files: Use read_file (NOT cat/head/tail); it caps lines and paginates with offset/limit\n' +
226
+ '- Edit files: Use edit_file (NOT sed/awk)\n' +
227
+ '- Write files: Use write_file (NOT echo > or cat <<EOF)\n' +
228
+ 'Dedicated tools are capped, paginated and easier to review.\n' +
229
+ '- Never repeat an identical command; if the result was not useful, refine it or switch tools.\n' +
230
+ '- Independent commands: make separate bash calls in one message instead of one long && chain.\n' +
231
+ '- Prefer absolute paths over cd; keep one working directory per task.',
222
232
  kind: 'execute',
223
233
  isMutating: true,
224
234
  isReadOnly: (input) => isReadOnlyCommand(String(input.command ?? '')),
@@ -75,4 +75,23 @@ describe('isReadOnlyCommand', () => {
75
75
  expect(isReadOnlyCommand('')).toBe(false);
76
76
  expect(isReadOnlyCommand(' ')).toBe(false);
77
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
+ });
78
97
  });
@@ -103,8 +103,39 @@ function parseSegments(command: string): { segments: Segment[]; unsafe: boolean
103
103
  continue;
104
104
  }
105
105
 
106
- if (char === '>' || char === '<' || char === '`') {
107
- unsafe = true; // redirection, heredoc, backtick substitution
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
108
139
  continue;
109
140
  }
110
141
 
@@ -9,6 +9,7 @@ import { getPermissionMode } from '../agent/permission.js';
9
9
  import { walkFiles } from '../agent/tools/fs-utils.js';
10
10
  import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
11
11
  import { renderDiff } from './diff-render.js';
12
+ import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
12
13
  import { buildSystemPrompt, INIT_PROMPT, loadProjectContext } from '../agent/system-prompt.js';
13
14
  import { HumanMessage, SystemMessage, type BaseMessage } from '@langchain/core/messages';
14
15
 
@@ -39,6 +40,13 @@ export default function REPL({ ctx }: REPLProps) {
39
40
  const [historyIndex, setHistoryIndex] = useState(-1);
40
41
  const [savedInput, setSavedInput] = useState('');
41
42
  const [phase, setPhase] = useState<PromptPhase>('idle');
43
+ // Live tool activity while generating; collapsed into a summary at turn end.
44
+ const [liveTool, setLiveTool] = useState<{
45
+ title: string;
46
+ index: number;
47
+ ok: number;
48
+ fail: number;
49
+ } | null>(null);
42
50
  const [pendingModel, setPendingModel] = useState<ModelId | null>(null);
43
51
  const [modelCursor, setModelCursor] = useState(0);
44
52
 
@@ -166,6 +174,10 @@ export default function REPL({ ctx }: REPLProps) {
166
174
  messagesRef.current.push(new HumanMessage(text));
167
175
 
168
176
  let lastWasTool = false;
177
+ const stats = createTurnStats();
178
+ const titlesById = new Map<string, string>();
179
+ const bufferedLines: string[] = [];
180
+ let pendingCalls = 0;
169
181
  const result = await runAgentLoop({
170
182
  model: provider?.model,
171
183
  cwd: process.cwd(),
@@ -178,18 +190,37 @@ export default function REPL({ ctx }: REPLProps) {
178
190
  appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
179
191
  lastWasTool = false;
180
192
  } else if (event.type === 'tool_call') {
181
- appendChatOutput(`\n⚙ ${event.title}`);
193
+ titlesById.set(event.toolCallId, event.title);
194
+ pendingCalls++;
195
+ setLiveTool({ title: event.title, index: pendingCalls, ok: stats.ok, fail: stats.fail });
182
196
  lastWasTool = true;
183
197
  } else if (event.type === 'tool_result') {
198
+ const title = titlesById.get(event.toolCallId) ?? event.name;
184
199
  const marker = event.skippedPermission ? ' ✓ (read-only)' : event.ok ? ' ✓' : ' ✗';
185
- appendChatOutput(marker);
186
- if (event.diff) appendChatOutput(`\n${renderDiff(event.diff)}`);
200
+ recordCall(stats, event.name, event.ok);
201
+ setLiveTool(prev =>
202
+ prev ? { ...prev, ok: stats.ok, fail: stats.fail } : prev,
203
+ );
204
+ if (event.diff) {
205
+ // Edits and writes stay visible immediately — rare and important.
206
+ appendChatOutput(`\n⚙ ${title} ${marker}\n${renderDiff(event.diff)}`);
207
+ } else {
208
+ bufferedLines.push(`\n⚙ ${title} ${marker}`);
209
+ }
187
210
  lastWasTool = true;
188
211
  }
189
212
  },
190
213
  requestPermission: request => askInTerminal(request, controller.signal),
191
214
  });
192
215
 
216
+ // Collapse long turns into one summary line; short turns stay expanded.
217
+ if (shouldCollapse(stats)) {
218
+ const line = summaryLine(stats);
219
+ if (line) appendChatOutput(`\n${line}`);
220
+ } else {
221
+ for (const line of bufferedLines) appendChatOutput(line);
222
+ }
223
+
193
224
  messagesRef.current = result.messages;
194
225
  if (controller.signal.aborted) appendChatOutput('\n(cancelled)');
195
226
  } catch (error) {
@@ -201,6 +232,7 @@ export default function REPL({ ctx }: REPLProps) {
201
232
  } finally {
202
233
  setBusyBoth(false);
203
234
  abortRef.current = undefined;
235
+ setLiveTool(null);
204
236
  // The agent may have created/removed files; rebuild @-completion list.
205
237
  setFileList(null);
206
238
  dragFlush();
@@ -472,8 +504,15 @@ export default function REPL({ ctx }: REPLProps) {
472
504
  )}
473
505
 
474
506
  {busy && phase === 'idle' && (
475
- <Box marginLeft={2}>
507
+ <Box marginLeft={2} flexDirection="column">
476
508
  <Text dimColor>… generating (Esc to cancel)</Text>
509
+ {liveTool && (
510
+ <Text dimColor>
511
+ ⚙{' '}
512
+ {liveTool.title.length > 64 ? `${liveTool.title.slice(0, 64)}…` : liveTool.title}
513
+ {' '}· call {liveTool.index} · {liveTool.ok}✓ {liveTool.fail}✗
514
+ </Text>
515
+ )}
477
516
  </Box>
478
517
  )}
479
518
 
@@ -0,0 +1,41 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
3
+
4
+ describe('turn summary', () => {
5
+ test('records calls per tool name with ok/fail counts', () => {
6
+ const stats = createTurnStats();
7
+ recordCall(stats, 'bash', true);
8
+ recordCall(stats, 'bash', true);
9
+ recordCall(stats, 'read_file', true);
10
+ recordCall(stats, 'edit_file', false);
11
+
12
+ expect(stats.calls).toBe(4);
13
+ expect(stats.ok).toBe(3);
14
+ expect(stats.fail).toBe(1);
15
+ });
16
+
17
+ test('summary line lists counts by tool with markers', () => {
18
+ const stats = createTurnStats();
19
+ recordCall(stats, 'bash', true);
20
+ recordCall(stats, 'bash', true);
21
+ recordCall(stats, 'read_file', true);
22
+ recordCall(stats, 'edit_file', false);
23
+
24
+ const line = summaryLine(stats);
25
+ expect(line).toContain('4 tool calls');
26
+ expect(line).toContain('bash×2');
27
+ expect(line).toContain('read_file×1');
28
+ expect(line).toContain('3✓');
29
+ expect(line).toContain('1✗');
30
+ });
31
+
32
+ test('short turns stay expanded, long turns collapse', () => {
33
+ const short = createTurnStats();
34
+ for (let i = 0; i < 3; i++) recordCall(short, 'bash', true);
35
+ expect(shouldCollapse(short)).toBe(false);
36
+
37
+ const long = createTurnStats();
38
+ for (let i = 0; i < 4; i++) recordCall(long, 'bash', true);
39
+ expect(shouldCollapse(long)).toBe(true);
40
+ });
41
+ });
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Per-turn tool call statistics for the REPL: decides whether a turn's tool
3
+ * log collapses into one summary line and formats that line.
4
+ */
5
+
6
+ export interface TurnStats {
7
+ calls: number;
8
+ ok: number;
9
+ fail: number;
10
+ byName: Map<string, number>;
11
+ }
12
+
13
+ export function createTurnStats(): TurnStats {
14
+ return { calls: 0, ok: 0, fail: 0, byName: new Map() };
15
+ }
16
+
17
+ export function recordCall(stats: TurnStats, name: string, ok: boolean): void {
18
+ stats.calls++;
19
+ if (ok) stats.ok++;
20
+ else stats.fail++;
21
+ stats.byName.set(name, (stats.byName.get(name) ?? 0) + 1);
22
+ }
23
+
24
+ /** Turns with more than 3 tool calls collapse into a single summary line. */
25
+ export function shouldCollapse(stats: TurnStats): boolean {
26
+ return stats.calls > 3;
27
+ }
28
+
29
+ export function summaryLine(stats: TurnStats): string {
30
+ if (stats.calls === 0) return '';
31
+ const parts = [...stats.byName.entries()].map(([name, count]) => `${name}×${count}`);
32
+ const markers = `${stats.ok}✓${stats.fail > 0 ? ` ${stats.fail}✗` : ''}`;
33
+ return `⚙ ${stats.calls} tool calls · ${parts.join(' ')} · ${markers}`;
34
+ }
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.1';
2
+ export const VERSION = '0.2.3';