@trans-ai/trans-code 0.2.2 → 0.2.4
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 +11 -0
- package/src/agent/loop.test.ts +243 -0
- package/src/agent/loop.ts +63 -1
- package/src/agent/system-prompt.ts +7 -3
- package/src/agent/tools/bash.test.ts +9 -2
- package/src/agent/tools/bash.ts +13 -4
- package/src/cli.ts +1 -0
- package/src/main.tsx +2 -4
- package/src/screens/REPL.tsx +48 -4
- package/src/screens/banner.test.ts +21 -0
- package/src/screens/banner.ts +9 -0
- 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/acp/session.ts
CHANGED
|
@@ -195,6 +195,17 @@ export class AcpSession {
|
|
|
195
195
|
return;
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
+
if (event.type === 'max_turns_reached') {
|
|
199
|
+
this.host.sendUpdate(this.id, {
|
|
200
|
+
sessionUpdate: 'agent_message_chunk',
|
|
201
|
+
content: {
|
|
202
|
+
type: 'text',
|
|
203
|
+
text: `\n⚠ Reached maximum number of turns (${event.maxTurns}). The task is incomplete — say "continue" or raise TRANSCODE_MAX_TURNS.\n`,
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
|
|
198
209
|
if (event.type === 'tool_call') {
|
|
199
210
|
this.host.sendUpdate(this.id, {
|
|
200
211
|
sessionUpdate: 'tool_call',
|
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,222 @@ 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
|
+
// Windowed rule: the trailing call is the third {"a":1} within the last
|
|
200
|
+
// 6 calls, so it is blocked even though the calls were not consecutive.
|
|
201
|
+
expect(executions).toBe(3);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
test('alternating A-B-A-B loops are blocked by the windowed counter', async () => {
|
|
205
|
+
let aRuns = 0;
|
|
206
|
+
let bRuns = 0;
|
|
207
|
+
const tools: AgentTool[] = [
|
|
208
|
+
{
|
|
209
|
+
...fakeTool,
|
|
210
|
+
name: 'A',
|
|
211
|
+
async execute() {
|
|
212
|
+
aRuns++;
|
|
213
|
+
return 'ok';
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
...fakeTool,
|
|
218
|
+
name: 'B',
|
|
219
|
+
async execute() {
|
|
220
|
+
bRuns++;
|
|
221
|
+
return 'ok';
|
|
222
|
+
},
|
|
223
|
+
},
|
|
224
|
+
];
|
|
225
|
+
|
|
226
|
+
await runAgentLoop({
|
|
227
|
+
model: scriptedModel([
|
|
228
|
+
{ tool: 'A' },
|
|
229
|
+
{ tool: 'B' },
|
|
230
|
+
{ tool: 'A' },
|
|
231
|
+
{ tool: 'B' },
|
|
232
|
+
{ tool: 'A' },
|
|
233
|
+
]),
|
|
234
|
+
cwd: '/tmp',
|
|
235
|
+
messages: [],
|
|
236
|
+
systemPrompt: 'test',
|
|
237
|
+
tools,
|
|
238
|
+
onEvent: () => {},
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
// A appears 3 times within the window → blocked on its third call.
|
|
242
|
+
expect(aRuns).toBe(2);
|
|
243
|
+
expect(bRuns).toBe(2);
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
test('hitting the turn cap is loud: event, notice message, stop reason', async () => {
|
|
247
|
+
const events: AgentEvent[] = [];
|
|
248
|
+
const infiniteTools = scriptedModel(
|
|
249
|
+
Array.from({ length: 20 }, () => ({ tool: 'fake' as const, args: '{"a":1}' })),
|
|
250
|
+
);
|
|
251
|
+
|
|
252
|
+
const result = await runAgentLoop({
|
|
253
|
+
model: infiniteTools,
|
|
254
|
+
cwd: '/tmp',
|
|
255
|
+
messages: [],
|
|
256
|
+
systemPrompt: 'test',
|
|
257
|
+
tools: [fakeTool],
|
|
258
|
+
maxTurns: 2,
|
|
259
|
+
onEvent: (event) => events.push(event),
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
expect(result.stopReason).toBe('max_turn_requests');
|
|
263
|
+
expect(events.some((event) => event.type === 'max_turns_reached')).toBe(true);
|
|
264
|
+
const notice = result.messages.find(
|
|
265
|
+
(message) => message.getType() === 'ai' && message.content.toString().includes('maximum number of turns'),
|
|
266
|
+
);
|
|
267
|
+
expect(notice).toBeDefined();
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
test('TRANSCODE_MAX_TURNS overrides the default cap', async () => {
|
|
271
|
+
process.env.TRANSCODE_MAX_TURNS = '3';
|
|
272
|
+
try {
|
|
273
|
+
const events: AgentEvent[] = [];
|
|
274
|
+
const infiniteTools = scriptedModel(
|
|
275
|
+
Array.from({ length: 20 }, () => ({ tool: 'fake' as const, args: '{"a":1}' })),
|
|
276
|
+
);
|
|
277
|
+
|
|
278
|
+
const result = await runAgentLoop({
|
|
279
|
+
model: infiniteTools,
|
|
280
|
+
cwd: '/tmp',
|
|
281
|
+
messages: [],
|
|
282
|
+
systemPrompt: 'test',
|
|
283
|
+
tools: [fakeTool],
|
|
284
|
+
onEvent: (event) => events.push(event),
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
expect(result.stopReason).toBe('max_turn_requests');
|
|
288
|
+
// Circuit breaker blocks execution from the 3rd identical call, but
|
|
289
|
+
// every turn still emits a tool_result event.
|
|
290
|
+
expect(events.filter((event) => event.type === 'tool_result').length).toBe(3);
|
|
291
|
+
} finally {
|
|
292
|
+
delete process.env.TRANSCODE_MAX_TURNS;
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
test('nudges the model after prolonged exploration without any mutation', async () => {
|
|
297
|
+
// read-only tool (isMutating false): pure exploration, never "acts".
|
|
298
|
+
const exploreTool: AgentTool = {
|
|
299
|
+
...fakeTool,
|
|
300
|
+
isMutating: false,
|
|
301
|
+
async execute() {
|
|
302
|
+
return 'ok';
|
|
303
|
+
},
|
|
304
|
+
};
|
|
305
|
+
// Vary args each call so the circuit breaker does not fire.
|
|
306
|
+
const steps = Array.from({ length: 40 }, (_, i) => ({
|
|
307
|
+
tool: 'fake' as const,
|
|
308
|
+
args: JSON.stringify({ n: i }),
|
|
309
|
+
}));
|
|
310
|
+
|
|
311
|
+
const result = await runAgentLoop({
|
|
312
|
+
model: scriptedModel(steps),
|
|
313
|
+
cwd: '/tmp',
|
|
314
|
+
messages: [],
|
|
315
|
+
systemPrompt: 'test',
|
|
316
|
+
tools: [exploreTool],
|
|
317
|
+
onEvent: () => {},
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
const nudge = result.messages.find(
|
|
321
|
+
(message) =>
|
|
322
|
+
message.getType() === 'ai' && message.content.toString().includes('Stop exploring'),
|
|
323
|
+
);
|
|
324
|
+
expect(nudge).toBeDefined();
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
test('no exploration nudge when the model acted early', async () => {
|
|
328
|
+
const writer: AgentTool = {
|
|
329
|
+
...fakeTool,
|
|
330
|
+
isMutating: true,
|
|
331
|
+
async execute() {
|
|
332
|
+
return 'ok';
|
|
333
|
+
},
|
|
334
|
+
};
|
|
335
|
+
// Mutate on call 1, keep exploring afterwards.
|
|
336
|
+
const steps = Array.from({ length: 40 }, (_, i) => ({
|
|
337
|
+
tool: 'fake' as const,
|
|
338
|
+
args: JSON.stringify({ n: i }),
|
|
339
|
+
}));
|
|
340
|
+
|
|
341
|
+
const result = await runAgentLoop({
|
|
342
|
+
model: scriptedModel(steps),
|
|
343
|
+
cwd: '/tmp',
|
|
344
|
+
messages: [],
|
|
345
|
+
systemPrompt: 'test',
|
|
346
|
+
tools: [writer],
|
|
347
|
+
onEvent: () => {},
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
const nudge = result.messages.find(
|
|
351
|
+
(message) =>
|
|
352
|
+
message.getType() === 'ai' && message.content.toString().includes('Stop exploring'),
|
|
353
|
+
);
|
|
354
|
+
expect(nudge).toBeUndefined();
|
|
355
|
+
});
|
|
113
356
|
});
|
package/src/agent/loop.ts
CHANGED
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
export type AgentEvent =
|
|
22
22
|
| { type: 'text'; text: string }
|
|
23
23
|
| { type: 'thought'; text: string }
|
|
24
|
+
| { type: 'max_turns_reached'; maxTurns: number }
|
|
24
25
|
| {
|
|
25
26
|
type: 'tool_call';
|
|
26
27
|
toolCallId: string;
|
|
@@ -143,6 +144,19 @@ function parseToolCalls(
|
|
|
143
144
|
return calls;
|
|
144
145
|
}
|
|
145
146
|
|
|
147
|
+
const REPEAT_GUIDANCE =
|
|
148
|
+
'This exact command was already executed twice in a row with the same arguments; repeating it ' +
|
|
149
|
+
'will not produce new information. Change your approach: use read_file to view file contents, ' +
|
|
150
|
+
'narrow the search pattern, or answer from the results you already have.';
|
|
151
|
+
|
|
152
|
+
function stableKey(value: unknown): string {
|
|
153
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
154
|
+
const record = value as Record<string, unknown>;
|
|
155
|
+
return JSON.stringify(Object.keys(record).sort().map((key) => [key, record[key]]));
|
|
156
|
+
}
|
|
157
|
+
return JSON.stringify(value) ?? '';
|
|
158
|
+
}
|
|
159
|
+
|
|
146
160
|
function lastHumanText(messages: BaseMessage[]): string {
|
|
147
161
|
for (let index = messages.length - 1; index >= 0; index--) {
|
|
148
162
|
if (messages[index].getType() === 'human') {
|
|
@@ -242,7 +256,10 @@ export async function runAgentLoop(
|
|
|
242
256
|
}
|
|
243
257
|
|
|
244
258
|
const tools = options.tools ?? AGENT_TOOLS;
|
|
245
|
-
|
|
259
|
+
// Claude Code style: generous default cap (their subagents use 200),
|
|
260
|
+
// overridable via TRANSCODE_MAX_TURNS. Hitting it is loud, never silent.
|
|
261
|
+
const envTurns = Number(process.env.TRANSCODE_MAX_TURNS);
|
|
262
|
+
const maxTurns = options.maxTurns ?? (Number.isFinite(envTurns) && envTurns > 0 ? envTurns : 200);
|
|
246
263
|
const toolSession = options.toolSession ?? createToolSession(options.cwd);
|
|
247
264
|
if (!options.model) throw new Error('No model configured for the agent loop');
|
|
248
265
|
|
|
@@ -251,6 +268,19 @@ export async function runAgentLoop(
|
|
|
251
268
|
? options.model.bindTools(bindableTools(tools))
|
|
252
269
|
: options.model;
|
|
253
270
|
|
|
271
|
+
// Windowed repetition tracking: the same call (name + args) occurring
|
|
272
|
+
// >= 3 times within the last 6 calls is refused, which catches both
|
|
273
|
+
// straight repeats (A,A,A) and alternating loops (A,B,A,B,A).
|
|
274
|
+
const recentKeys: string[] = [];
|
|
275
|
+
|
|
276
|
+
// Exploration stall detection: too many calls with zero mutations means
|
|
277
|
+
// the model is drilling instead of delivering (observed with DeepSeek:
|
|
278
|
+
// 272 read-only calls to "update a README"). Nudge it once mid-run.
|
|
279
|
+
const EXPLORE_STALL_THRESHOLD = 30;
|
|
280
|
+
let totalToolCalls = 0;
|
|
281
|
+
let hasActed = false;
|
|
282
|
+
let stallNudged = false;
|
|
283
|
+
|
|
254
284
|
for (let turn = 0; turn < maxTurns; turn++) {
|
|
255
285
|
if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
|
|
256
286
|
|
|
@@ -305,8 +335,17 @@ export async function runAgentLoop(
|
|
|
305
335
|
|
|
306
336
|
let result: { ok: boolean; output: string; diff?: string };
|
|
307
337
|
let skippedPermission = false;
|
|
338
|
+
|
|
339
|
+
// Circuit breaker (windowed): see recentKeys declaration.
|
|
340
|
+
const key = `${call.name}:${stableKey(input)}`;
|
|
341
|
+
const occurrences = recentKeys.filter((recent) => recent === key).length + 1;
|
|
342
|
+
recentKeys.push(key);
|
|
343
|
+
if (recentKeys.length > 6) recentKeys.shift();
|
|
344
|
+
|
|
308
345
|
if (!tool) {
|
|
309
346
|
result = { ok: false, output: `Unknown tool: ${call.name}` };
|
|
347
|
+
} else if (occurrences >= 3) {
|
|
348
|
+
result = { ok: false, output: `Error: ${REPEAT_GUIDANCE}` };
|
|
310
349
|
} else {
|
|
311
350
|
const readOnly = tool.isReadOnly?.(input) === true;
|
|
312
351
|
const needsPermission = tool.isMutating && !readOnly;
|
|
@@ -329,7 +368,12 @@ export async function runAgentLoop(
|
|
|
329
368
|
session: toolSession,
|
|
330
369
|
})
|
|
331
370
|
: { ok: false, output: 'Permission denied by the client.' };
|
|
371
|
+
|
|
372
|
+
if (allowed && tool.isMutating && tool.isReadOnly?.(input) !== true) {
|
|
373
|
+
hasActed = true;
|
|
374
|
+
}
|
|
332
375
|
}
|
|
376
|
+
totalToolCalls++;
|
|
333
377
|
|
|
334
378
|
await options.onEvent({
|
|
335
379
|
type: 'tool_result',
|
|
@@ -349,7 +393,25 @@ export async function runAgentLoop(
|
|
|
349
393
|
}),
|
|
350
394
|
);
|
|
351
395
|
}
|
|
396
|
+
|
|
397
|
+
if (!hasActed && !stallNudged && totalToolCalls >= EXPLORE_STALL_THRESHOLD) {
|
|
398
|
+
stallNudged = true;
|
|
399
|
+
const nudge =
|
|
400
|
+
`You have made ${totalToolCalls} tool calls without producing any edits or output. ` +
|
|
401
|
+
'Stop exploring: synthesize what you already have and complete the task now ' +
|
|
402
|
+
'(edit or write the deliverable, or answer directly). If you need file contents, ' +
|
|
403
|
+
'read_file returns up to 2000 lines in one call — do not paginate with grep/sed windows.';
|
|
404
|
+
messages.push(new AIMessage({ content: nudge }));
|
|
405
|
+
await options.onEvent({ type: 'text', text: `\n⚠ ${nudge}\n` });
|
|
406
|
+
}
|
|
352
407
|
}
|
|
353
408
|
|
|
409
|
+
// Record the cap in the conversation (like Claude Code's max_turns_reached
|
|
410
|
+
// attachment) and surface it as an event so no surface stays silent.
|
|
411
|
+
const notice = new AIMessage({
|
|
412
|
+
content: `Reached maximum number of turns (${maxTurns}). The task is incomplete — ask the user to say "continue" or raise TRANSCODE_MAX_TURNS.`,
|
|
413
|
+
});
|
|
414
|
+
messages.push(notice);
|
|
415
|
+
await options.onEvent({ type: 'max_turns_reached', maxTurns });
|
|
354
416
|
return { stopReason: 'max_turn_requests', messages };
|
|
355
417
|
}
|
|
@@ -89,10 +89,14 @@ 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
|
-
|
|
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.',
|
|
94
|
+
'- read_file returns up to 2000 lines in ONE call. Never paginate a file through repeated ' +
|
|
95
|
+
'grep/sed window commands — that wastes dozens of turns; read the file once instead.',
|
|
96
|
+
'- For synthesis tasks (update docs/README): explore briefly (aim for ~15 tool calls), ' +
|
|
97
|
+
'then state a short plan and write the result. Exploration is not the deliverable.',
|
|
95
98
|
'- The bash working directory persists across calls; you do not need to cd again each time.',
|
|
99
|
+
'- Never repeat an identical tool call; refine it or switch tools.',
|
|
96
100
|
'- Use edit_file for targeted changes and write_file for new files.',
|
|
97
101
|
'- Keep changes focused on the task. Do not undo unrelated user work.',
|
|
98
102
|
'- 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/cli.ts
CHANGED
|
@@ -14,6 +14,7 @@ Environment:
|
|
|
14
14
|
TRANSCODE_DEFAULT_PROVIDER Provider for bare model names (default: openai)
|
|
15
15
|
TRANSCODE_PERMISSION_MODE ask | auto | readonly (default: ask in ACP mode;
|
|
16
16
|
switch at runtime in the REPL with /mode)
|
|
17
|
+
TRANSCODE_MAX_TURNS Agent tool-call turn cap (default: 200)
|
|
17
18
|
ANTHROPIC_API_KEY / OPENAI_API_KEY / DEEPSEEK_API_KEY / ... provider keys
|
|
18
19
|
|
|
19
20
|
Examples:
|
package/src/main.tsx
CHANGED
|
@@ -3,6 +3,7 @@ import { useState } from 'react';
|
|
|
3
3
|
import { envModelLabel, getAvailableModels, preferredModelId, type ModelId } from './provider/provider.js';
|
|
4
4
|
import { type CommandContext } from './commands.js';
|
|
5
5
|
import REPL from './screens/REPL.js';
|
|
6
|
+
import { bannerLines } from './screens/banner.js';
|
|
6
7
|
import { createKeyedStdin } from './tui/keyed-stdin.js';
|
|
7
8
|
import { VERSION } from './version.js';
|
|
8
9
|
const DEFAULT_MODEL: ModelId = preferredModelId() ?? 'opus';
|
|
@@ -11,10 +12,7 @@ function Banner({ modelId, cwd, envLabel }: { modelId: ModelId; cwd: string; env
|
|
|
11
12
|
const models = getAvailableModels();
|
|
12
13
|
const current = models.find(m => m.id === modelId);
|
|
13
14
|
|
|
14
|
-
const logo =
|
|
15
|
-
┌──────────────────────────────────────────────┐
|
|
16
|
-
│ T R A N S C O D E · Multi-model Agent │
|
|
17
|
-
└──────────────────────────────────────────────┘`
|
|
15
|
+
const logo = bannerLines('T R A N S C O D E · Multi-model Agent');
|
|
18
16
|
|
|
19
17
|
return (
|
|
20
18
|
<Box flexDirection="column" marginBottom={1}>
|
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(),
|
|
@@ -177,19 +189,43 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
177
189
|
if (event.type === 'text') {
|
|
178
190
|
appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
|
|
179
191
|
lastWasTool = false;
|
|
192
|
+
} else if (event.type === 'max_turns_reached') {
|
|
193
|
+
appendChatOutput(
|
|
194
|
+
`\n⚠ 已达轮次上限(${event.maxTurns}),任务未完成。输入"继续"接着做,或调大 TRANSCODE_MAX_TURNS。`,
|
|
195
|
+
);
|
|
196
|
+
lastWasTool = true;
|
|
180
197
|
} else if (event.type === 'tool_call') {
|
|
181
|
-
|
|
198
|
+
titlesById.set(event.toolCallId, event.title);
|
|
199
|
+
pendingCalls++;
|
|
200
|
+
setLiveTool({ title: event.title, index: pendingCalls, ok: stats.ok, fail: stats.fail });
|
|
182
201
|
lastWasTool = true;
|
|
183
202
|
} else if (event.type === 'tool_result') {
|
|
203
|
+
const title = titlesById.get(event.toolCallId) ?? event.name;
|
|
184
204
|
const marker = event.skippedPermission ? ' ✓ (read-only)' : event.ok ? ' ✓' : ' ✗';
|
|
185
|
-
|
|
186
|
-
|
|
205
|
+
recordCall(stats, event.name, event.ok);
|
|
206
|
+
setLiveTool(prev =>
|
|
207
|
+
prev ? { ...prev, ok: stats.ok, fail: stats.fail } : prev,
|
|
208
|
+
);
|
|
209
|
+
if (event.diff) {
|
|
210
|
+
// Edits and writes stay visible immediately — rare and important.
|
|
211
|
+
appendChatOutput(`\n⚙ ${title} ${marker}\n${renderDiff(event.diff)}`);
|
|
212
|
+
} else {
|
|
213
|
+
bufferedLines.push(`\n⚙ ${title} ${marker}`);
|
|
214
|
+
}
|
|
187
215
|
lastWasTool = true;
|
|
188
216
|
}
|
|
189
217
|
},
|
|
190
218
|
requestPermission: request => askInTerminal(request, controller.signal),
|
|
191
219
|
});
|
|
192
220
|
|
|
221
|
+
// Collapse long turns into one summary line; short turns stay expanded.
|
|
222
|
+
if (shouldCollapse(stats)) {
|
|
223
|
+
const line = summaryLine(stats);
|
|
224
|
+
if (line) appendChatOutput(`\n${line}`);
|
|
225
|
+
} else {
|
|
226
|
+
for (const line of bufferedLines) appendChatOutput(line);
|
|
227
|
+
}
|
|
228
|
+
|
|
193
229
|
messagesRef.current = result.messages;
|
|
194
230
|
if (controller.signal.aborted) appendChatOutput('\n(cancelled)');
|
|
195
231
|
} catch (error) {
|
|
@@ -201,6 +237,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
201
237
|
} finally {
|
|
202
238
|
setBusyBoth(false);
|
|
203
239
|
abortRef.current = undefined;
|
|
240
|
+
setLiveTool(null);
|
|
204
241
|
// The agent may have created/removed files; rebuild @-completion list.
|
|
205
242
|
setFileList(null);
|
|
206
243
|
dragFlush();
|
|
@@ -472,8 +509,15 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
472
509
|
)}
|
|
473
510
|
|
|
474
511
|
{busy && phase === 'idle' && (
|
|
475
|
-
<Box marginLeft={2}>
|
|
512
|
+
<Box marginLeft={2} flexDirection="column">
|
|
476
513
|
<Text dimColor>… generating (Esc to cancel)</Text>
|
|
514
|
+
{liveTool && (
|
|
515
|
+
<Text dimColor>
|
|
516
|
+
⚙{' '}
|
|
517
|
+
{liveTool.title.length > 64 ? `${liveTool.title.slice(0, 64)}…` : liveTool.title}
|
|
518
|
+
{' '}· call {liveTool.index} · {liveTool.ok}✓ {liveTool.fail}✗
|
|
519
|
+
</Text>
|
|
520
|
+
)}
|
|
477
521
|
</Box>
|
|
478
522
|
)}
|
|
479
523
|
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { bannerLines } from './banner.js';
|
|
3
|
+
|
|
4
|
+
describe('bannerLines', () => {
|
|
5
|
+
test('renders a closed rectangle with aligned sides', () => {
|
|
6
|
+
const lines = bannerLines('T R A N S C O D E · Multi-model Agent').split('\n');
|
|
7
|
+
expect(lines.length).toBe(3);
|
|
8
|
+
expect(lines[0]!.startsWith('┌')).toBe(true);
|
|
9
|
+
expect(lines[0]!.endsWith('┐')).toBe(true);
|
|
10
|
+
expect(lines[1]!.startsWith('│')).toBe(true);
|
|
11
|
+
expect(lines[1]!.endsWith('│')).toBe(true);
|
|
12
|
+
expect(lines[2]!.startsWith('└')).toBe(true);
|
|
13
|
+
expect(lines[2]!.endsWith('┘')).toBe(true);
|
|
14
|
+
|
|
15
|
+
// Every line must have the same display width for the box to close.
|
|
16
|
+
const width = (line: string) => [...line].length;
|
|
17
|
+
expect(width(lines[1]!)).toBe(width(lines[0]!));
|
|
18
|
+
expect(width(lines[2]!)).toBe(width(lines[0]!));
|
|
19
|
+
expect(lines[1]!).toContain('T R A N S C O D E');
|
|
20
|
+
});
|
|
21
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Closed ASCII banner: the border width is derived from the title so the
|
|
3
|
+
* rectangle always lines up, whatever the title text.
|
|
4
|
+
*/
|
|
5
|
+
export function bannerLines(title: string, padding = 2): string {
|
|
6
|
+
const inner = ' '.repeat(padding) + title + ' '.repeat(padding);
|
|
7
|
+
const border = '─'.repeat([...inner].length);
|
|
8
|
+
return `┌${border}┐\n│${inner}│\n└${border}┘`;
|
|
9
|
+
}
|
|
@@ -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.4';
|