@trans-ai/trans-code 0.10.0 → 0.10.2

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.10.0",
3
+ "version": "0.10.2",
4
4
  "description": "AI-powered multi-model coding CLI",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -690,3 +690,81 @@ describe('runAgentLoop', () => {
690
690
  expect(wrapUp).toBeUndefined();
691
691
  });
692
692
  });
693
+
694
+ describe('context estimator sees tool-call args', () => {
695
+ test('estimateMessagesChars 计入 tool_calls 参数(巨型参数不再隐形)', async () => {
696
+ const { AIMessage } = await import('@langchain/core/messages');
697
+ const { estimateMessagesChars } = await import('./loop.js');
698
+ const messages = [
699
+ new AIMessage({
700
+ content: '写文件',
701
+ tool_calls: [
702
+ { id: 'c1', name: 'write_file', args: { content: 'x'.repeat(250_000) } },
703
+ ],
704
+ }),
705
+ ];
706
+ expect(estimateMessagesChars(messages)).toBeGreaterThan(200_000);
707
+ });
708
+ });
709
+
710
+ describe('malformed tool-call breaker', () => {
711
+ test('isMalformedToolArgs:仅 _raw 键为真,正常/空参数为假', async () => {
712
+ const { isMalformedToolArgs } = await import('./loop.js');
713
+ expect(isMalformedToolArgs({ _raw: '{"broken": tru' })).toBe(true);
714
+ expect(isMalformedToolArgs({ path: 'a.ts' })).toBe(false);
715
+ expect(isMalformedToolArgs({})).toBe(false);
716
+ });
717
+
718
+ test('连续 3 次全格式错误 → 第 3 次拒绝执行并停轮(stalled),给出指引', async () => {
719
+ let executions = 0;
720
+ const countingTool: AgentTool = {
721
+ ...fakeTool,
722
+ name: 'fake',
723
+ async execute() {
724
+ executions++;
725
+ return 'ok';
726
+ },
727
+ };
728
+ const events: Array<{ type: string; text?: string }> = [];
729
+ const result = await runAgentLoop({
730
+ model: scriptedModel([
731
+ { tool: 'fake', args: '{"path": "a.ts", "content": "xxx' },
732
+ { tool: 'fake', args: '{"path": "b.ts", "content": "yyy' },
733
+ { tool: 'fake', args: '{"path": "c.ts", "content": "zzz' },
734
+ { tool: 'fake', args: '{"path": "d.ts", "content": "www' },
735
+ ]),
736
+ cwd: '/tmp',
737
+ messages: [],
738
+ systemPrompt: 'test',
739
+ tools: [countingTool],
740
+ onEvent: (event) => events.push(event as never),
741
+ });
742
+
743
+ expect(result.stopReason).toBe('stalled');
744
+ expect(executions).toBeLessThanOrEqual(2);
745
+ const guidance = events.find(
746
+ (event) => event.type === 'text' && JSON.stringify(event).includes('malformed'),
747
+ );
748
+ expect(guidance).toBeDefined();
749
+ });
750
+
751
+ test('格式错误后自愈(第 2 次正常)→ 计数归零不熔断', async () => {
752
+ const events: Array<{ type: string }> = [];
753
+ const result = await runAgentLoop({
754
+ model: scriptedModel([
755
+ { tool: 'fake', args: '{"broken": tru' },
756
+ { tool: 'fake', args: '{"a":1}' },
757
+ { tool: 'fake', args: '{"a":2}' },
758
+ { tool: 'fake', args: '{"a":3}' },
759
+ { tool: 'fake', args: '{"a":4}' },
760
+ { tool: 'text' as never, text: 'done' } as never,
761
+ ]),
762
+ cwd: '/tmp',
763
+ messages: [],
764
+ systemPrompt: 'test',
765
+ tools: [fakeTool],
766
+ onEvent: (event) => events.push(event as never),
767
+ });
768
+ expect(result.stopReason).toBe('end_turn');
769
+ });
770
+ });
package/src/agent/loop.ts CHANGED
@@ -249,13 +249,36 @@ async function runMockTurn(
249
249
 
250
250
  const COMPACT_DEFAULT_CHARS = 200_000;
251
251
 
252
- function estimateMessagesChars(messages: BaseMessage[]): number {
253
- return messages.reduce(
254
- (sum, message) => sum + JSON.stringify(message.content ?? '').length + 200,
255
- 0,
256
- );
252
+ /**
253
+ * Char estimate for the in-turn compaction gate. MUST include tool-call
254
+ * arguments: a turn that repeatedly emits huge (possibly malformed) tool
255
+ * payloads grows history invisibly if only message content is counted —
256
+ * that blind spot once ballooned a session past the model's context window.
257
+ */
258
+ export function estimateMessagesChars(messages: BaseMessage[]): number {
259
+ return messages.reduce((sum, message) => {
260
+ const toolCalls = (message as AIMessage).tool_calls ?? [];
261
+ const argsChars = toolCalls.reduce(
262
+ (n, call) => n + JSON.stringify(call.args ?? '').length,
263
+ 0,
264
+ );
265
+ return sum + JSON.stringify(message.content ?? '').length + argsChars + 200;
266
+ }, 0);
267
+ }
268
+
269
+ /** True when parseToolCalls fell back to {_raw}: the args were not valid JSON. */
270
+ export function isMalformedToolArgs(args: Record<string, unknown>): boolean {
271
+ return Object.keys(args).length === 1 && '_raw' in args;
257
272
  }
258
273
 
274
+ /** Consecutive all-malformed turns tolerated before the breaker stops the loop. */
275
+ const MALFORMED_TOOL_CALL_BREAKER = 3;
276
+
277
+ const MALFORMED_GUIDANCE =
278
+ 'Your last tool calls had malformed JSON arguments and were never executed. ' +
279
+ 'Do NOT retry the same payload. Write the file in smaller sections, or use a ' +
280
+ 'bash heredoc for large content, or reply describing what you are stuck on.';
281
+
259
282
  /**
260
283
  * Auto-compaction (Claude Code's autoCompact, ported): when the estimated
261
284
  * conversation size exceeds the char budget, summarize the history with the
@@ -350,6 +373,7 @@ export async function runAgentLoop(
350
373
  let stallNudged = false;
351
374
  let callsAtStallNudge = 0;
352
375
  let wrapUpNudged = false;
376
+ let malformedStrikes = 0;
353
377
 
354
378
  for (let turn = 0; turn < maxTurns; turn++) {
355
379
  if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
@@ -399,6 +423,17 @@ export async function runAgentLoop(
399
423
  return { stopReason: 'end_turn', messages };
400
424
  }
401
425
 
426
+ // Malformed-args breaker: every call this turn unparsable → strike;
427
+ // a clean turn resets. The 3rd consecutive strike is refused (never
428
+ // executed) and stops the loop — retrying the same giant broken
429
+ // payload only balloons the context.
430
+ const allMalformed = toolCalls.every((call) => isMalformedToolArgs(call.args));
431
+ malformedStrikes = allMalformed ? malformedStrikes + 1 : 0;
432
+ if (malformedStrikes >= MALFORMED_TOOL_CALL_BREAKER) {
433
+ await options.onEvent({ type: 'text', text: `\n⚠ ${MALFORMED_GUIDANCE}\n` });
434
+ return { stopReason: 'stalled', messages };
435
+ }
436
+
402
437
  for (const call of toolCalls) {
403
438
  if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
404
439
 
@@ -48,3 +48,12 @@ describe('permission mode', () => {
48
48
  expect(PERMISSION_MODES).toEqual(['ask', 'auto', 'readonly']);
49
49
  });
50
50
  });
51
+
52
+ describe('nextPermissionMode', () => {
53
+ test('shift+tab 循环:ask → auto → readonly → ask', async () => {
54
+ const { nextPermissionMode } = await import('./permission.js');
55
+ expect(nextPermissionMode('ask')).toBe('auto');
56
+ expect(nextPermissionMode('auto')).toBe('readonly');
57
+ expect(nextPermissionMode('readonly')).toBe('ask');
58
+ });
59
+ });
@@ -21,6 +21,12 @@ export function getPermissionMode(): PermissionMode {
21
21
  return currentMode;
22
22
  }
23
23
 
24
+ /** Shift+Tab cycling order: ask → auto → readonly → ask. */
25
+ export function nextPermissionMode(current: PermissionMode): PermissionMode {
26
+ const index = PERMISSION_MODES.indexOf(current);
27
+ return PERMISSION_MODES[(index + 1) % PERMISSION_MODES.length]!;
28
+ }
29
+
24
30
  export function setPermissionMode(mode: PermissionMode): void {
25
31
  if (!PERMISSION_MODES.includes(mode)) {
26
32
  throw new Error(`Unknown permission mode: ${mode}. Valid: ${PERMISSION_MODES.join(', ')}`);
@@ -173,3 +173,37 @@ describe('omitted-only user memory', () => {
173
173
  expect(prompt).toContain('(omitted: huge)');
174
174
  });
175
175
  });
176
+
177
+ describe('web tool guidance', () => {
178
+ test('webSearch 已配置 → How to work 含 web_search 优先于记忆的引导', async () => {
179
+ const configDir = await fs.mkdtemp(path.join(tmpdir(), 'transcode-prompt-web-'));
180
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
181
+ try {
182
+ writeFileSync(
183
+ path.join(configDir, 'config.json'),
184
+ JSON.stringify({ webSearch: { provider: 'tavily', apiKey: 'tvly-x' } }),
185
+ );
186
+ const prompt = buildSystemPrompt({ cwd: '/tmp', projectFiles: [] });
187
+ expect(prompt).toContain('web_search');
188
+ expect(prompt).toContain('web_fetch');
189
+ expect(prompt.toLowerCase()).toContain('outside this workspace');
190
+ } finally {
191
+ delete process.env.TRANSCODE_CONFIG_PATH;
192
+ await fs.rm(configDir, { recursive: true, force: true });
193
+ }
194
+ });
195
+
196
+ test('未配置 → 不提 web_search(与工具隐藏一致),仍提 web_fetch', () => {
197
+ const configDir = mkdtempSync(path.join(tmpdir(), 'transcode-prompt-noweb-'));
198
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'empty.json');
199
+ try {
200
+ writeFileSync(path.join(configDir, 'empty.json'), '{}');
201
+ const prompt = buildSystemPrompt({ cwd: '/tmp', projectFiles: [] });
202
+ expect(prompt).not.toContain('web_search');
203
+ expect(prompt).toContain('web_fetch');
204
+ } finally {
205
+ delete process.env.TRANSCODE_CONFIG_PATH;
206
+ rmSync(configDir, { recursive: true, force: true });
207
+ }
208
+ });
209
+ });
@@ -2,6 +2,8 @@ import { promises as fs } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { getRouting } from '../provider/provider.js';
4
4
  import { loadUserMemory, renderMemoryIndex, type UserMemory } from './memory.js';
5
+ import { loadConfig } from '../config.js';
6
+ import { normalizeWebSearchConfig } from '../provider/web-search.js';
5
7
 
6
8
  const CONTEXT_FILES = ['TRANS.md', 'AGENTS.md', 'CLAUDE.md', 'TRANSCODE.md', '.transcode/AGENTS.md'];
7
9
  const MAX_CONTEXT_CHARS = 40_000;
@@ -36,6 +38,26 @@ async function readOptional(file: string): Promise<string | null> {
36
38
  }
37
39
  }
38
40
 
41
+ /**
42
+ * Web tool guidance, gated like the tools themselves: web_search is only
43
+ * advertised when configured (the tool is hidden from the table otherwise);
44
+ * web_fetch is always available.
45
+ */
46
+ function webToolLines(): string[] {
47
+ const searchConfigured = normalizeWebSearchConfig(loadConfig().webSearch) !== null;
48
+ return [
49
+ ...(searchConfigured
50
+ ? [
51
+ '- Questions about anything outside this workspace — unfamiliar terms, latest ' +
52
+ 'releases, current documentation — search the web with web_search BEFORE answering ' +
53
+ 'from memory; read a promising result with web_fetch.',
54
+ ]
55
+ : []),
56
+ '- Use web_fetch to read a specific URL (docs, API responses, raw files) when the user ' +
57
+ 'points at one.',
58
+ ];
59
+ }
60
+
39
61
  /** Advertises configured role routing so the model knows it can delegate. */
40
62
  function roleRoutingLines(): string[] {
41
63
  const entries = Object.entries(getRouting()).filter(([role]) => role !== 'default');
@@ -116,6 +138,7 @@ export function buildSystemPrompt(
116
138
  'then state a short plan and write the result. Exploration is not the deliverable.',
117
139
  '- Multi-step tasks (3+ steps): create the list with todo_write first, keep exactly one ' +
118
140
  'step in_progress, and mark steps completed as you finish them.',
141
+ ...webToolLines(),
119
142
  ...roleRoutingLines(),
120
143
  '- Reporting counts (tests, checks, matches): grep -c counts matching LINES, including ' +
121
144
  'definitions like `def check(` — read the actual item list instead of trusting a raw count.',
@@ -27,7 +27,7 @@ import {
27
27
  } from '../provider/web-search.js';
28
28
  import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
29
29
  import { createToolSession } from '../agent/tools/index.js';
30
- import { getPermissionMode } from '../agent/permission.js';
30
+ import { getPermissionMode, nextPermissionMode, setPermissionMode } from '../agent/permission.js';
31
31
  import {
32
32
  buildSessionRecord,
33
33
  generateTitle,
@@ -50,13 +50,15 @@ import { resolveSubmitInput } from './submit.js';
50
50
  import { submitSearchApiKey } from './search-setup.js';
51
51
  import { historyRule } from './history-rule.js';
52
52
  import { renderDiff } from './diff-render.js';
53
- import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
53
+ import { createTurnStats, recordCall, renderTurnLog, shouldCollapse, summaryLine } from './turn-summary.js';
54
54
  import { buildSystemPrompt, INIT_PROMPT, loadProjectContext } from '../agent/system-prompt.js';
55
55
  import { HumanMessage, SystemMessage, type BaseMessage } from '@langchain/core/messages';
56
56
 
57
57
  interface HistoryEntry {
58
58
  input: string;
59
59
  output: string;
60
+ /** Tool-log detail hidden behind the collapse summary (ctrl+o reveals). */
61
+ hiddenLines?: string[];
60
62
  }
61
63
 
62
64
  type PromptPhase =
@@ -149,6 +151,22 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
149
151
  setHistory(prev => [...prev, entry]);
150
152
  }, []);
151
153
 
154
+ /** ctrl+o verbose view: collapsed turns show their hidden tool-log detail. */
155
+ const [verboseTools, setVerboseTools] = useState(false);
156
+
157
+ const attachHiddenLines = useCallback((lines: string[]) => {
158
+ setHistory(prev => {
159
+ if (prev.length === 0 || lines.length === 0) return prev;
160
+ const next = [...prev];
161
+ const last = next[next.length - 1];
162
+ next[next.length - 1] = {
163
+ ...last,
164
+ hiddenLines: [...(last.hiddenLines ?? []), ...lines],
165
+ };
166
+ return next;
167
+ });
168
+ }, []);
169
+
152
170
  // ---- chat state ----
153
171
  const [busy, setBusy] = useState(false);
154
172
  const busyRef = useRef(false);
@@ -513,9 +531,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
513
531
  });
514
532
 
515
533
  // Collapse long turns into one summary line; short turns stay expanded.
534
+ // Collapsed detail is kept (hiddenLines) so ctrl+o can reveal it.
516
535
  if (shouldCollapse(stats)) {
517
536
  const line = summaryLine(stats);
518
537
  if (line) appendChatOutput(`\n${line}`);
538
+ attachHiddenLines(bufferedLines);
519
539
  } else {
520
540
  for (const line of bufferedLines) appendChatOutput(line);
521
541
  }
@@ -1013,6 +1033,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1013
1033
  // eslint-disable-next-line no-console
1014
1034
  console.error(`CB ${JSON.stringify(ch)} ret=${key.return} esc=${key.escape}`);
1015
1035
  }
1036
+ // ctrl+o: toggle verbose tool logs (expand/collapse every turn).
1037
+ if (key.ctrl && (ch === 'o' || ch === 'O')) {
1038
+ setVerboseTools(v => !v);
1039
+ return;
1040
+ }
1016
1041
  // @-mention popup: Esc dismisses it instead of exiting the app.
1017
1042
  if (key.escape && mentionActive && mentionCandidates.length > 0) {
1018
1043
  setMentionDismissed(true);
@@ -1203,6 +1228,16 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1203
1228
  return;
1204
1229
  }
1205
1230
 
1231
+ // Shift+Tab cycles permission modes (ask → auto → readonly). Runs FIRST:
1232
+ // ink reports shift+tab as a bare {tab} key (raw input '[Z'), so every
1233
+ // later tab branch (popup completion, slash completion) would misfire.
1234
+ if (key.tab && (ch === '[Z' || key.shift) && phase === 'idle') {
1235
+ const next = nextPermissionMode(getPermissionMode());
1236
+ setPermissionMode(next);
1237
+ addHistory({ input: '', output: `权限模式 → ${next}` });
1238
+ return;
1239
+ }
1240
+
1206
1241
  // @-mention popup navigation and completion (takes precedence over
1207
1242
  // history navigation, tab completion and submission).
1208
1243
  if (phase === 'idle' && mentionActive && mentionCandidates.length > 0) {
@@ -1329,7 +1364,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1329
1364
  )}
1330
1365
  {entry.output && (
1331
1366
  <Box marginLeft={2}>
1332
- <Text>{entry.output}</Text>
1367
+ <Text>
1368
+ {entry.hiddenLines?.length
1369
+ ? renderTurnLog(entry.output, entry.hiddenLines, verboseTools)
1370
+ : entry.output}
1371
+ </Text>
1333
1372
  </Box>
1334
1373
  )}
1335
1374
  </Box>
@@ -39,3 +39,26 @@ describe('turn summary', () => {
39
39
  expect(shouldCollapse(long)).toBe(true);
40
40
  });
41
41
  });
42
+
43
+ describe('renderTurnLog', () => {
44
+ test('折叠:summary + "… +N lines (ctrl+o to expand)",N 数实际行数', async () => {
45
+ const { renderTurnLog } = await import('./turn-summary.js');
46
+ const hidden = ['\n⚙ read_file a.ts ✓', '\n⚙ bash npm test ✓\nextra line', '\n⚙ grep foo ✓'];
47
+ expect(renderTurnLog('⚙ 3 tool calls · …', hidden, false)).toBe(
48
+ '⚙ 3 tool calls · …\n… +4 lines (ctrl+o to expand)',
49
+ );
50
+ });
51
+
52
+ test('展开:明细可见 + "(ctrl+o to collapse)" 提示', async () => {
53
+ const { renderTurnLog } = await import('./turn-summary.js');
54
+ const out = renderTurnLog('S', ['\n⚙ read_file a.ts ✓', '\n⚙ bash npm test ✓'], true);
55
+ expect(out).toContain('read_file a.ts');
56
+ expect(out).toContain('bash npm test');
57
+ expect(out).toContain('(ctrl+o to collapse)');
58
+ });
59
+
60
+ test('无明细时原样返回 summary', async () => {
61
+ const { renderTurnLog } = await import('./turn-summary.js');
62
+ expect(renderTurnLog('S', [], false)).toBe('S');
63
+ });
64
+ });
@@ -32,3 +32,19 @@ export function summaryLine(stats: TurnStats): string {
32
32
  const markers = `${stats.ok}✓${stats.fail > 0 ? ` ${stats.fail}✗` : ''}`;
33
33
  return `⚙ ${stats.calls} tool calls · ${parts.join(' ')} · ${markers}`;
34
34
  }
35
+
36
+ /**
37
+ * Render a collapsed turn's tool log. Non-verbose: the summary line plus a
38
+ * "… +N lines (ctrl+o to expand)" affordance; verbose (ctrl+o): the hidden
39
+ * detail lines become visible so nothing is permanently unreachable.
40
+ */
41
+ export function renderTurnLog(summary: string, hiddenLines: string[], verbose: boolean): string {
42
+ if (hiddenLines.length === 0) return summary;
43
+ if (verbose) {
44
+ return `${summary}\n(ctrl+o to collapse)${hiddenLines.join('')}`;
45
+ }
46
+ const count = hiddenLines
47
+ .flatMap((line) => line.split('\n'))
48
+ .filter((line) => line.trim().length > 0).length;
49
+ return `${summary}\n… +${count} lines (ctrl+o to expand)`;
50
+ }
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.10.0';
2
+ export const VERSION = '0.10.2';