@trans-ai/trans-code 0.2.2 → 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 +1 -1
- package/src/agent/loop.test.ts +88 -0
- package/src/agent/loop.ts +28 -0
- package/src/agent/system-prompt.ts +3 -3
- package/src/agent/tools/bash.test.ts +9 -2
- package/src/agent/tools/bash.ts +13 -4
- package/src/screens/REPL.tsx +43 -4
- package/src/screens/turn-summary.test.ts +41 -0
- package/src/screens/turn-summary.ts +34 -0
- package/src/version.ts +1 -1
package/package.json
CHANGED
package/src/agent/loop.test.ts
CHANGED
|
@@ -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;
|
|
@@ -89,10 +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
|
-
'-
|
|
93
|
-
'
|
|
94
|
-
'Do not cat entire files into the conversation.',
|
|
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.',
|
|
95
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.',
|
|
96
96
|
'- Use edit_file for targeted changes and write_file for new files.',
|
|
97
97
|
'- Keep changes focused on the task. Do not undo unrelated user work.',
|
|
98
98
|
'- After changing code, run the cheapest relevant check (typecheck, targeted test) when available.',
|
|
@@ -7,8 +7,15 @@ import { createToolSession, type ToolSession } from './session.js';
|
|
|
7
7
|
import type { ToolContext } from './types.js';
|
|
8
8
|
|
|
9
9
|
describe('bash tool wiring', () => {
|
|
10
|
-
test('description
|
|
11
|
-
|
|
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');
|
|
12
19
|
});
|
|
13
20
|
|
|
14
21
|
test('isReadOnly is wired to the analyzer', () => {
|
package/src/agent/tools/bash.ts
CHANGED
|
@@ -216,10 +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.
|
|
220
|
-
'
|
|
221
|
-
'
|
|
222
|
-
'
|
|
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.',
|
|
223
232
|
kind: 'execute',
|
|
224
233
|
isMutating: true,
|
|
225
234
|
isReadOnly: (input) => isReadOnlyCommand(String(input.command ?? '')),
|
package/src/screens/REPL.tsx
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
186
|
-
|
|
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.
|
|
2
|
+
export const VERSION = '0.2.3';
|