@trans-ai/trans-code 0.8.2 → 0.10.0

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.
Files changed (38) hide show
  1. package/README.md +20 -2
  2. package/docs/superpowers/plans/2026-11-21-auto-compact.md +84 -0
  3. package/docs/superpowers/plans/2026-11-21-compact-speed.md +85 -0
  4. package/docs/superpowers/plans/2026-11-22-user-memory.md +243 -0
  5. package/docs/superpowers/plans/2026-11-22-web-tools.md +192 -0
  6. package/docs/superpowers/specs/2026-11-21-auto-compact-design.md +25 -0
  7. package/docs/superpowers/specs/2026-11-21-compact-speed-design.md +21 -0
  8. package/docs/superpowers/specs/2026-11-22-user-memory-design.md +48 -0
  9. package/docs/superpowers/specs/2026-11-22-web-tools-design.md +48 -0
  10. package/package.json +1 -1
  11. package/src/acp/server.ts +6 -0
  12. package/src/agent/loop.ts +5 -1
  13. package/src/agent/memory.test.ts +169 -0
  14. package/src/agent/memory.ts +207 -0
  15. package/src/agent/system-prompt.test.ts +87 -1
  16. package/src/agent/system-prompt.ts +23 -1
  17. package/src/agent/tools/index.ts +7 -0
  18. package/src/agent/tools/memory.test.ts +88 -0
  19. package/src/agent/tools/memory.ts +61 -0
  20. package/src/agent/tools/types.ts +2 -0
  21. package/src/agent/tools/web-fetch.test.ts +186 -0
  22. package/src/agent/tools/web-fetch.ts +137 -0
  23. package/src/agent/tools/web-search.test.ts +100 -0
  24. package/src/agent/tools/web-search.ts +41 -0
  25. package/src/commands.test.ts +104 -1
  26. package/src/commands.ts +101 -0
  27. package/src/config.test.ts +25 -0
  28. package/src/config.ts +52 -0
  29. package/src/provider/web-search.test.ts +195 -0
  30. package/src/provider/web-search.ts +143 -0
  31. package/src/screens/REPL.tsx +222 -24
  32. package/src/screens/search-setup.test.ts +89 -0
  33. package/src/screens/search-setup.ts +57 -0
  34. package/src/screens/submit.test.ts +8 -0
  35. package/src/screens/submit.ts +1 -1
  36. package/src/sessions/compact.test.ts +90 -25
  37. package/src/sessions/compact.ts +41 -9
  38. package/src/version.ts +1 -1
@@ -0,0 +1,57 @@
1
+ import type { WebSearchCheck, WebSearchConfig } from '../provider/web-search.js';
2
+
3
+ /**
4
+ * /search key-step orchestration, extracted so the flow is testable without
5
+ * the REPL: reuse a saved key on empty input, run a live check, persist only
6
+ * on success, and abandon the outcome entirely when the run went stale
7
+ * (the user pressed Esc while the check was in flight).
8
+ */
9
+
10
+ export interface SearchSetupDeps {
11
+ /** Current persisted config (for the "Enter keeps the saved key" path). */
12
+ savedConfig: () => WebSearchConfig | null;
13
+ /** Live connectivity check (never throws). */
14
+ check: (cfg: WebSearchConfig) => Promise<WebSearchCheck>;
15
+ /** Persist provider+key. */
16
+ save: (provider: WebSearchConfig['provider'], apiKey: string) => void;
17
+ /** Append a message to the chat history. */
18
+ notify: (output: string) => void;
19
+ /** Phase transition after the outcome: idle on success, key prompt on failure. */
20
+ onOutcome: (phase: 'idle' | 'search_apikey') => void;
21
+ /** True when this run was cancelled (Esc) before the check returned. */
22
+ isStale: () => boolean;
23
+ }
24
+
25
+ export async function submitSearchApiKey(
26
+ value: string,
27
+ provider: WebSearchConfig['provider'],
28
+ deps: SearchSetupDeps,
29
+ ): Promise<void> {
30
+ const saved = deps.savedConfig();
31
+ const apiKey = value.trim() || (saved?.provider === provider ? saved.apiKey : '');
32
+ if (!apiKey) {
33
+ deps.notify('API key 不能为空。(Esc 取消)');
34
+ return;
35
+ }
36
+
37
+ deps.notify(`正在测试 ${provider} key…`);
38
+ const result = await deps.check({ provider, apiKey });
39
+ // Esc during the check: write nothing, touch no phase, show no late result.
40
+ if (deps.isStale()) return;
41
+
42
+ if (result.ok) {
43
+ try {
44
+ deps.save(provider, apiKey);
45
+ } catch (error) {
46
+ deps.notify(`✗ 配置写入失败:${error instanceof Error ? error.message : String(error)}\n请重试或手改 ~/.transcode.json`);
47
+ deps.onOutcome('search_apikey');
48
+ return;
49
+ }
50
+ deps.notify(`✓ ${provider} 连通正常(首条结果:${result.firstTitle})。web_search 已启用。`);
51
+ deps.onOutcome('idle');
52
+ return;
53
+ }
54
+
55
+ deps.notify(`✗ 测试失败:${result.error}\n请重新输入 key(Esc 取消)`);
56
+ deps.onOutcome('search_apikey');
57
+ }
@@ -21,3 +21,11 @@ describe('resolveSubmitInput', () => {
21
21
  expect(resolveSubmitInput('idle', 'hello')).toBe('hello');
22
22
  });
23
23
  });
24
+
25
+ describe('search_apikey empty submit', () => {
26
+ test('empty Enter at the search_apikey prompt submits (reuses the saved key)', () => {
27
+ // The /search prompt advertises "(Enter 沿用已存 key)" — a bare Enter
28
+ // must reach the search key handler, which falls back to the saved key.
29
+ expect(resolveSubmitInput('search_apikey', '')).toBe('');
30
+ });
31
+ });
@@ -3,7 +3,7 @@
3
3
  * prompt the hint reads "apikey (回车沿用 sk-…xxxx)> " — a bare Enter means
4
4
  * "reuse the saved key", and handleApiKey falls back to it for empty input.
5
5
  */
6
- const EMPTY_SUBMIT_PHASES = new Set(['model_apikey']);
6
+ const EMPTY_SUBMIT_PHASES = new Set(['model_apikey', 'search_apikey']);
7
7
 
8
8
  /**
9
9
  * Decide whether a submitted line should be dispatched. Returns the trimmed
@@ -2,10 +2,13 @@ import { describe, expect, test } from 'bun:test';
2
2
  import { AIMessage, HumanMessage, SystemMessage, ToolMessage, type BaseMessage } from '@langchain/core/messages';
3
3
  import type { SessionRecord } from './store.js';
4
4
  import {
5
+ COMPACT_MAX_SUMMARY_CHARS,
5
6
  DEFAULT_KEEP_TURNS,
6
7
  TRANSCRIPT_LIMIT,
7
8
  compressSession,
9
+ estimateTokens,
8
10
  parseKeepCount,
11
+ shouldAutoCompact,
9
12
  transcriptEntries,
10
13
  splitTurns,
11
14
  } from './compact.js';
@@ -31,13 +34,21 @@ function recordWith(turns: number, opts: { summary?: string; longTurn?: boolean
31
34
  };
32
35
  }
33
36
 
34
- function mockModel(text: string): { invoke: (input: string) => Promise<{ content: string }>; prompts: string[] } {
37
+ /** Streaming mock: yields chunks; can throw at chunk N and track pulls. */
38
+ function streamModel(
39
+ chunks: string[],
40
+ opts: { throwAt?: number; trackPulled?: string[] } = {},
41
+ ): { stream: (input: string) => AsyncGenerator<{ content: string }>; prompts: string[] } {
35
42
  const prompts: string[] = [];
36
43
  return {
37
44
  prompts,
38
- invoke: async (input: string) => {
45
+ stream: async function* (input: string) {
39
46
  prompts.push(input);
40
- return { content: text };
47
+ for (let i = 0; i < chunks.length; i++) {
48
+ opts.trackPulled?.push(chunks[i]!);
49
+ if (opts.throwAt === i + 1) throw new Error('stream blew up');
50
+ yield { content: chunks[i]! };
51
+ }
41
52
  },
42
53
  };
43
54
  }
@@ -62,66 +73,120 @@ describe('splitTurns', () => {
62
73
  });
63
74
 
64
75
  describe('compressSession', () => {
76
+ test('streams chunks into the summary and forwards each delta', async () => {
77
+ const deltas: string[] = [];
78
+ const { compressed, record } = await compressSession(
79
+ recordWith(3),
80
+ streamModel(['前情', '提要']),
81
+ 1,
82
+ (d) => deltas.push(d),
83
+ );
84
+ expect(compressed).toBe(true);
85
+ expect(record.summary).toBe('前情提要');
86
+ expect(deltas).toEqual(['前情', '提要']);
87
+ });
88
+
89
+ test('caps summary at COMPACT_MAX_SUMMARY_CHARS and stops consuming early', async () => {
90
+ const pulled: string[] = [];
91
+ const model = streamModel(['x'.repeat(1000), 'y'.repeat(1000), 'z'.repeat(1000)], { trackPulled: pulled });
92
+ const { record } = await compressSession(recordWith(3), model, 1);
93
+ expect(record.summary!.length).toBeLessThanOrEqual(COMPACT_MAX_SUMMARY_CHARS);
94
+ expect(pulled.length).toBe(2); // 第三块未消费
95
+ });
96
+
97
+ test('mid-stream error falls back with error set', async () => {
98
+ const rec = recordWith(3);
99
+ const { compressed, record, error } = await compressSession(rec, streamModel(['前情', '提要'], { throwAt: 2 }), 1);
100
+ expect(compressed).toBe(false);
101
+ expect(error).toBeDefined();
102
+ expect(record).toBe(rec);
103
+ });
104
+
105
+ test('non-string chunk content is skipped', async () => {
106
+ const model = {
107
+ stream: async function* () {
108
+ yield { content: '前情' };
109
+ yield { content: [{ text: 'x' }] };
110
+ yield { content: '提要' };
111
+ },
112
+ };
113
+ const { record } = await compressSession(recordWith(3), model as never, 1);
114
+ expect(record.summary).toBe('前情提要');
115
+ });
116
+
65
117
  test('default keeps only 1 turn', async () => {
66
- const { compressed, record } = await compressSession(recordWith(3), mockModel('提要内容'));
118
+ const { compressed, record } = await compressSession(recordWith(3), streamModel(['提要内容']));
67
119
  expect(compressed).toBe(true);
68
120
  expect(record.summary).toBe('提要内容');
69
- expect(splitTurns(record.messages).turns.length).toBe(DEFAULT_KEEP_TURNS);
70
121
  expect(splitTurns(record.messages).turns.length).toBe(1);
71
122
  expect(record.messages[0]!.getType()).toBe('system');
72
123
  expect(record.updatedAt).toBeGreaterThan(1);
73
124
  });
74
125
 
75
126
  test('explicit keepTurns=10 keeps 10', async () => {
76
- const { record } = await compressSession(recordWith(12), mockModel('提要'), 10);
127
+ const { record } = await compressSession(recordWith(12), streamModel(['提要']), 10);
77
128
  expect(splitTurns(record.messages).turns.length).toBe(10);
78
129
  });
79
130
 
80
131
  test('keepTurns below 1 clamps to 1', async () => {
81
- const { record } = await compressSession(recordWith(3), mockModel('提要'), 0);
132
+ const { record } = await compressSession(recordWith(3), streamModel(['提要']), 0);
82
133
  expect(splitTurns(record.messages).turns.length).toBe(1);
83
134
  });
84
135
 
85
136
  test('at or below keepTurns is a no-op returning the original record', async () => {
86
137
  const rec = recordWith(10);
87
- const { compressed, record } = await compressSession(rec, mockModel('x'), 10);
138
+ const { compressed, record } = await compressSession(rec, streamModel(['x']), 10);
88
139
  expect(compressed).toBe(false);
89
140
  expect(record).toBe(rec);
90
141
  });
91
142
 
92
- test('model failure returns original record with error', async () => {
93
- const rec = recordWith(12);
94
- const failing = {
95
- invoke: async () => {
96
- throw new Error('API down');
97
- },
98
- };
99
- const { compressed, record, error } = await compressSession(rec, failing, 10);
100
- expect(compressed).toBe(false);
101
- expect(error).toBeDefined();
102
- expect(record).toBe(rec);
103
- });
104
-
105
- test('empty model reply is treated as failure', async () => {
106
- const { compressed, error } = await compressSession(recordWith(12), mockModel(' '), 10);
143
+ test('empty summary is treated as failure', async () => {
144
+ const { compressed, error } = await compressSession(recordWith(12), streamModel([' ']), 10);
107
145
  expect(compressed).toBe(false);
108
146
  expect(error).toBeDefined();
109
147
  });
110
148
 
111
149
  test('rolling merge: previous summary appears in the prompt', async () => {
112
- const model = mockModel('新提要');
150
+ const model = streamModel(['新提要']);
113
151
  await compressSession(recordWith(12, { summary: '旧提要内容' }), model, 10);
114
152
  expect(model.prompts[0]).toContain('旧提要内容');
115
153
  });
116
154
 
117
155
  test('huge old transcript is truncated before invoking the model', async () => {
118
- const model = mockModel('提要');
156
+ const model = streamModel(['提要']);
119
157
  await compressSession(recordWith(12, { longTurn: true }), model, 10);
120
158
  expect(model.prompts[0]!.length).toBeLessThan(TRANSCRIPT_LIMIT + 2_000);
121
159
  expect(model.prompts[0]).toContain('更早内容已截断');
122
160
  });
123
161
  });
124
162
 
163
+ describe('estimateTokens', () => {
164
+ test('sums content chars / 4, floors; empty → 0', () => {
165
+ expect(estimateTokens([])).toBe(0);
166
+ expect(estimateTokens([new HumanMessage('a'.repeat(40))])).toBe(10);
167
+ expect(
168
+ estimateTokens([new HumanMessage('x'.repeat(10)), new AIMessage('y'.repeat(30))]),
169
+ ).toBe(10);
170
+ expect(estimateTokens([new HumanMessage('abcd')])).toBe(1);
171
+ });
172
+
173
+ test('counts tool_calls args payloads (often the largest text)', () => {
174
+ const ai = new AIMessage({
175
+ content: '',
176
+ tool_calls: [{ id: 'c1', name: 'write_file', args: { content: 'x'.repeat(200) } }],
177
+ });
178
+ expect(estimateTokens([ai])).toBeGreaterThanOrEqual(50);
179
+ });
180
+ });
181
+
182
+ describe('shouldAutoCompact', () => {
183
+ test('compares in CHARS: at threshold triggers, just below does not', () => {
184
+ const cfg = { thresholdChars: 200 };
185
+ expect(shouldAutoCompact([new HumanMessage('a'.repeat(200))], cfg)).toBe(true);
186
+ expect(shouldAutoCompact([new HumanMessage('a'.repeat(196))], cfg)).toBe(false);
187
+ });
188
+ });
189
+
125
190
  describe('parseKeepCount', () => {
126
191
  test('undefined → default; "5" → 5; "0"/"abc" → error, no keep', () => {
127
192
  expect(parseKeepCount(undefined)).toEqual({});
@@ -7,9 +7,38 @@ export const DEFAULT_KEEP_TURNS = 1;
7
7
  /** Cap on the transcript fed to the distilling model (protects its context). */
8
8
  export const TRANSCRIPT_LIMIT = 40_000;
9
9
 
10
- /** Minimal model surface needed for distillation (mock-friendly). */
10
+ /** Cap on the distilled summary: stop consuming the stream past this. */
11
+ export const COMPACT_MAX_SUMMARY_CHARS = 1200;
12
+
13
+ /** Minimal streaming model surface needed for distillation (mock-friendly).
14
+ * LangChain's model.stream() returns Promise<IterableReadableStream>, plain
15
+ * async generators return the iterable directly — both are accepted. */
11
16
  export interface CompactModel {
12
- invoke(input: string): Promise<{ content: unknown }>;
17
+ stream(
18
+ input: string,
19
+ ): AsyncIterable<{ content: unknown }> | Promise<AsyncIterable<{ content: unknown }>>;
20
+ }
21
+
22
+ /** Rough token estimate for auto-compact: total content chars / 4.
23
+ * Tool-call args are included — in a coding session they are often the
24
+ * largest text (write_file/edit payloads). */
25
+ export function estimateTokens(messages: BaseMessage[]): number {
26
+ let chars = 0;
27
+ for (const message of messages) {
28
+ chars += contentText(message.content).length;
29
+ const calls = (message as AIMessage).tool_calls;
30
+ if (calls?.length) chars += JSON.stringify(calls).length;
31
+ }
32
+ return Math.floor(chars / 4);
33
+ }
34
+
35
+ /** Auto-compact decision. thresholdChars is in CHARS; estimateTokens is in
36
+ * tokens (chars/4) — convert back so units match. */
37
+ export function shouldAutoCompact(
38
+ messages: BaseMessage[],
39
+ cfg: { thresholdChars: number },
40
+ ): boolean {
41
+ return estimateTokens(messages) * 4 >= cfg.thresholdChars;
13
42
  }
14
43
 
15
44
  /**
@@ -68,10 +97,6 @@ function buildPrompt(previousSummary: string | undefined, oldTurns: BaseMessage[
68
97
  return `${head}${prior}\n对话历史:\n${renderTranscriptText(oldTurns)}`;
69
98
  }
70
99
 
71
- function replyText(content: unknown): string {
72
- return (typeof content === 'string' ? content : JSON.stringify(content)).trim();
73
- }
74
-
75
100
  /**
76
101
  * Validate a raw keep-turns argument: undefined → default (no opinion),
77
102
  * pure digits ≥1 → {keep}, anything else → {error} so callers can show a
@@ -93,19 +118,26 @@ export async function compressSession(
93
118
  record: SessionRecord,
94
119
  model: CompactModel,
95
120
  keepTurns = DEFAULT_KEEP_TURNS,
121
+ onDelta?: (delta: string) => void,
96
122
  ): Promise<{ compressed: boolean; record: SessionRecord; error?: string }> {
97
123
  const window = Math.max(1, keepTurns);
98
124
  const { leading, turns } = splitTurns(record.messages);
99
125
  if (turns.length <= window) return { compressed: false, record };
100
126
  const keep = turns.slice(-window);
101
127
  const old = turns.slice(0, turns.length - window);
102
- let summary: string;
128
+ let raw = '';
103
129
  try {
104
- const response = await model.invoke(buildPrompt(record.summary, old));
105
- summary = replyText(response.content);
130
+ const stream = await model.stream(buildPrompt(record.summary, old));
131
+ for await (const chunk of stream) {
132
+ const text = typeof chunk.content === 'string' ? chunk.content : '';
133
+ if (text) onDelta?.(text);
134
+ raw += text;
135
+ if (raw.length >= COMPACT_MAX_SUMMARY_CHARS) break;
136
+ }
106
137
  } catch (error) {
107
138
  return { compressed: false, record, error: error instanceof Error ? error.message : String(error) };
108
139
  }
140
+ const summary = raw.slice(0, COMPACT_MAX_SUMMARY_CHARS).trim();
109
141
  if (!summary) return { compressed: false, record, error: '模型返回了空前情提要' };
110
142
  return {
111
143
  compressed: true,
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.8.2';
2
+ export const VERSION = '0.10.0';