@trans-ai/trans-code 0.2.3 → 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 +156 -1
- package/src/agent/loop.ts +45 -11
- package/src/agent/system-prompt.ts +4 -0
- package/src/cli.ts +1 -0
- package/src/main.tsx +2 -4
- package/src/screens/REPL.tsx +5 -0
- package/src/screens/banner.test.ts +21 -0
- package/src/screens/banner.ts +9 -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
|
@@ -196,6 +196,161 @@ describe('runAgentLoop', () => {
|
|
|
196
196
|
onEvent: () => {},
|
|
197
197
|
});
|
|
198
198
|
|
|
199
|
-
|
|
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();
|
|
200
355
|
});
|
|
201
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;
|
|
@@ -255,7 +256,10 @@ export async function runAgentLoop(
|
|
|
255
256
|
}
|
|
256
257
|
|
|
257
258
|
const tools = options.tools ?? AGENT_TOOLS;
|
|
258
|
-
|
|
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);
|
|
259
263
|
const toolSession = options.toolSession ?? createToolSession(options.cwd);
|
|
260
264
|
if (!options.model) throw new Error('No model configured for the agent loop');
|
|
261
265
|
|
|
@@ -264,8 +268,18 @@ export async function runAgentLoop(
|
|
|
264
268
|
? options.model.bindTools(bindableTools(tools))
|
|
265
269
|
: options.model;
|
|
266
270
|
|
|
267
|
-
|
|
268
|
-
|
|
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;
|
|
269
283
|
|
|
270
284
|
for (let turn = 0; turn < maxTurns; turn++) {
|
|
271
285
|
if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
|
|
@@ -322,18 +336,15 @@ export async function runAgentLoop(
|
|
|
322
336
|
let result: { ok: boolean; output: string; diff?: string };
|
|
323
337
|
let skippedPermission = false;
|
|
324
338
|
|
|
325
|
-
// Circuit breaker:
|
|
326
|
-
// instead of executed, with guidance to change approach.
|
|
339
|
+
// Circuit breaker (windowed): see recentKeys declaration.
|
|
327
340
|
const key = `${call.name}:${stableKey(input)}`;
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
repeatCount = 1;
|
|
332
|
-
}
|
|
341
|
+
const occurrences = recentKeys.filter((recent) => recent === key).length + 1;
|
|
342
|
+
recentKeys.push(key);
|
|
343
|
+
if (recentKeys.length > 6) recentKeys.shift();
|
|
333
344
|
|
|
334
345
|
if (!tool) {
|
|
335
346
|
result = { ok: false, output: `Unknown tool: ${call.name}` };
|
|
336
|
-
} else if (
|
|
347
|
+
} else if (occurrences >= 3) {
|
|
337
348
|
result = { ok: false, output: `Error: ${REPEAT_GUIDANCE}` };
|
|
338
349
|
} else {
|
|
339
350
|
const readOnly = tool.isReadOnly?.(input) === true;
|
|
@@ -357,7 +368,12 @@ export async function runAgentLoop(
|
|
|
357
368
|
session: toolSession,
|
|
358
369
|
})
|
|
359
370
|
: { ok: false, output: 'Permission denied by the client.' };
|
|
371
|
+
|
|
372
|
+
if (allowed && tool.isMutating && tool.isReadOnly?.(input) !== true) {
|
|
373
|
+
hasActed = true;
|
|
374
|
+
}
|
|
360
375
|
}
|
|
376
|
+
totalToolCalls++;
|
|
361
377
|
|
|
362
378
|
await options.onEvent({
|
|
363
379
|
type: 'tool_result',
|
|
@@ -377,7 +393,25 @@ export async function runAgentLoop(
|
|
|
377
393
|
}),
|
|
378
394
|
);
|
|
379
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
|
+
}
|
|
380
407
|
}
|
|
381
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 });
|
|
382
416
|
return { stopReason: 'max_turn_requests', messages };
|
|
383
417
|
}
|
|
@@ -91,6 +91,10 @@ export function buildSystemPrompt(
|
|
|
91
91
|
'- Prefer read_file, glob and grep for exploration; use bash for builds, tests and git.',
|
|
92
92
|
'- View file contents with read_file (NOT cat/head/tail/sed); check unknown file sizes with ' +
|
|
93
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.',
|
|
94
98
|
'- The bash working directory persists across calls; you do not need to cd again each time.',
|
|
95
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.',
|
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
|
@@ -189,6 +189,11 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
189
189
|
if (event.type === 'text') {
|
|
190
190
|
appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
|
|
191
191
|
lastWasTool = false;
|
|
192
|
+
} else if (event.type === 'max_turns_reached') {
|
|
193
|
+
appendChatOutput(
|
|
194
|
+
`\n⚠ 已达轮次上限(${event.maxTurns}),任务未完成。输入"继续"接着做,或调大 TRANSCODE_MAX_TURNS。`,
|
|
195
|
+
);
|
|
196
|
+
lastWasTool = true;
|
|
192
197
|
} else if (event.type === 'tool_call') {
|
|
193
198
|
titlesById.set(event.toolCallId, event.title);
|
|
194
199
|
pendingCalls++;
|
|
@@ -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
|
+
}
|
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';
|