@trans-ai/trans-code 0.7.1 → 0.8.1

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.
@@ -0,0 +1,131 @@
1
+ # 会话压缩(恢复时自动 + /compact 主动)Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** 恢复超过 10 轮的会话时自动把旧轮提炼为「前情提要」并写回;`/compact` 随时主动压缩当前会话;恢复后以对话形式展示提要 + 最近 10 轮。
6
+
7
+ **Architecture:** 纯逻辑(切轮、提炼编排、窗口渲染)落 `src/sessions/compact.ts` 走 TDD;REPL 三入口(选择器 Enter、带参 resume、/compact)共用 `compressSession`;模型上下文通过「副本注入 + 结果剔除」携带提要,持久化文件不含注入消息。
8
+
9
+ **Tech Stack:** TypeScript、Ink、LangChain BaseMessage、bun:test。
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-21-resume-compact-design.md`
12
+
13
+ ## Global Constraints
14
+
15
+ - `KEEP_TURNS = 10`(导出常量);轮 = 一条 HumanMessage 到下一条 HumanMessage 前,开头的 SystemMessage 属 leading 不算轮
16
+ - 提炼 prompt 要求 ≤约 500 字,保留:决定与结论、关键事实(文件/代码/命令)、未完成事项
17
+ - 失败(模型抛错/空返回)→ 全量恢复原会话 + 提示,不阻塞、不写坏文件
18
+ - ≤10 轮零行为变化;旧会话无 `summary` 字段必须照常工作
19
+ - 持久化文件不得包含注入的【前情提要】消息;`runAgentLoop` 会原位 unshift,注入必须传副本
20
+ - 测试一律 `TRANSCODE_SESSIONS_DIR` 指向 mkdtemp 临时目录
21
+
22
+ ## Review Focus
23
+
24
+ - ≤10 轮恢复:不触发压缩、全量渲染(不误触发/不渲染空提要块)
25
+ - 压缩失败路径:原 record 原样返回、文件未被改写、UI 提示而非静默
26
+ - 注入消息泄漏:保存文件与 `messagesRef` 中都不出现【前情提要】SystemMessage(跨多轮也不累积)
27
+ - 已压缩会话再次恢复(summary 有值、轮数 ≤10):不重复压缩、提要块照常渲染
28
+ - 滚动合并:第二次压缩的 prompt 包含旧摘要文本
29
+ - 超大旧会话(旧 200KB 级):transcript 有截断保护,不超模型上下文
30
+ - picker Enter 异步压缩期间的键盘:busy 门控,不可再提交
31
+
32
+ ---
33
+
34
+ ### Task 1: 压缩核心(splitTurns / compressSession / renderTranscript)
35
+
36
+ **Files:**
37
+ - Create: `src/sessions/compact.ts`
38
+ - Test: `src/sessions/compact.test.ts`
39
+
40
+ **Interfaces:**
41
+ - Consumes: `SessionRecord`、`BaseMessage`(store.js/@langchain/core)
42
+ - Produces(Task 3 依赖):
43
+ - `export const KEEP_TURNS = 10`
44
+ - `splitTurns(messages: BaseMessage[]): { leading: BaseMessage[]; turns: BaseMessage[][] }`
45
+ - `compressSession(record, model: { invoke(input: string): Promise<{ content: unknown }> }): Promise<{ compressed: boolean; record: SessionRecord; error?: string }>`
46
+ - `renderTranscript(summary: string | null, messages: BaseMessage[]): string`
47
+
48
+ - [ ] **Step 1: 写失败测试**
49
+
50
+ ```ts
51
+ describe('splitTurns', () => {
52
+ // 构造:[System, Human(a), AI, Tool, AI, Human(b), AI]
53
+ test('leading system messages are not a turn; tool/AI messages attach to their human turn', () => {
54
+ const { leading, turns } = splitTurns(msgs);
55
+ expect(leading.map(m => m.getType())).toEqual(['system']);
56
+ expect(turns.length).toBe(2);
57
+ expect(turns[0]!.map(m => m.getType())).toEqual(['human', 'ai', 'tool', 'ai']);
58
+ });
59
+ });
60
+
61
+ describe('compressSession', () => {
62
+ test('more than KEEP_TURNS: trims to window, sets summary, keeps leading, bumps updatedAt', async () => {
63
+ // 12 轮 + leading System;mock model 返回 '提要内容'
64
+ const { compressed, record } = await compressSession(rec12, mockModel('提要内容'));
65
+ expect(compressed).toBe(true);
66
+ expect(record.summary).toBe('提要内容');
67
+ expect(splitTurns(record.messages).turns.length).toBe(10);
68
+ expect(record.messages[0]!.getType()).toBe('system');
69
+ });
70
+ test('at or below KEEP_TURNS is a no-op returning the original record', async () => {
71
+ const { compressed, record } = await compressSession(rec10, mockModel('x'));
72
+ expect(compressed).toBe(false);
73
+ expect(record).toBe(rec10);
74
+ });
75
+ test('model failure returns original record with error', async () => {
76
+ const { compressed, record, error } = await compressSession(rec12, failingModel);
77
+ expect(compressed).toBe(false); expect(error).toBeDefined(); expect(record).toBe(rec12);
78
+ });
79
+ test('rolling merge: previous summary appears in the prompt', async () => {
80
+ // rec12.summary = '旧提要';捕获 invoke 入参
81
+ expect(capturedPrompt).toContain('旧提要');
82
+ });
83
+ test('huge old transcript is truncated before invoking the model', async () => {
84
+ // 单轮巨文本;断言 invoke 入参长度 < 上限常量
85
+ });
86
+ });
87
+
88
+ describe('renderTranscript', () => {
89
+ test('renders summary block plus human/ai pairs, skipping tool/system', () => {
90
+ const out = renderTranscript('提要', windowMsgs);
91
+ expect(out).toContain('前情提要'); expect(out).toContain('你:'); expect(out).toContain('AI:');
92
+ expect(out).not.toContain('工具');
93
+ });
94
+ test('null summary renders turns only', () => { /* 无提要块 */ });
95
+ });
96
+ ```
97
+
98
+ - [ ] **Step 2: 跑测试确认失败** — `bun test src/sessions/compact.test.ts` → FAIL(模块不存在)
99
+ - [ ] **Step 3: 实现 `src/sessions/compact.ts`**
100
+ - `splitTurns`:首个 HumanMessage 前的都进 leading;此后每个 HumanMessage 开新轮
101
+ - `compressSession`:≤KEEP → `{ compressed: false, record }`;否则渲染旧轮文本(用户:/助手:/工具结果:,单条超长截断),总长超 `TRANSCRIPT_LIMIT = 40_000` 字符时留尾部并前缀「(更早内容已截断)」;prompt = 提炼指令 + (record.summary ? `已有前情提要:\n…\n` : '') + transcript;调 `model.invoke`,返回文本清洗后为空 → error;成功 → 新 record(`summary`=文本,`messages`=[...leading, ...末 10 轮展开],`updatedAt`=Date.now())
102
+ - `renderTranscript`:summary 非空 → `📝 前情提要(旧 N 轮)\n${summary}\n`;窗口内 Human→`你: ${text}`、AI→`AI: ${text}`(各截 120 字/行),Tool/System 跳过
103
+ - [ ] **Step 4: 跑测试确认通过** — 同命令 → PASS
104
+ - [ ] **Step 5: Commit** — `git add src/sessions/compact.ts src/sessions/compact.test.ts && git commit -m "feat: session compaction core (split turns, distill, transcript render)"`
105
+
106
+ ### Task 2: store 增加 summary 字段
107
+
108
+ **Files:**
109
+ - Modify: `src/sessions/store.ts:14-22`(SessionRecord)、`src/sessions/store.test.ts`
110
+ **Interfaces:**
111
+ - Produces: `SessionRecord.summary?: string`(Task 3 读写;saveSession 已展开 record,字段自动持久化,读回经 readRecord 展开)
112
+
113
+ - [ ] **Step 1: 失败测试** — store.test.ts 增:`saveSession({...sample(), summary: '旧提要'})` → `getSession('ses_test1')?.summary === '旧提要'`;不带 summary 的旧记录 → `?.summary` 为 undefined
114
+ - [ ] **Step 2: 确认失败** — 类型缺字段导致编译错(FAIL 正当)
115
+ - [ ] **Step 3: 实现** — SessionRecord 加 `/** Distilled digest of turns older than the kept window. */ summary?: string;`
116
+ - [ ] **Step 4: 确认通过**(跑 store 测试)
117
+ - [ ] **Step 5: Commit** — `feat: persist optional session summary field`
118
+
119
+ ### Task 3: REPL 三入口接线 + 上下文注入
120
+
121
+ **Files:**
122
+ - Modify: `src/screens/REPL.tsx`(applyResume 区、handleSubmit turn 调用区 :300、resume 分支、新增 compact 分支)、`src/commands.ts`(/compact 注册)
123
+ **Interfaces:**
124
+ - Consumes: Task 1 全部导出、`SessionRecord.summary`、`createModel`(provider.js)
125
+ - Produces: 无
126
+
127
+ - [ ] **Step 1: summaryRef 与注入/剔除** — `const summaryRef = useRef<string | null>(null);`;提交 turn 时:若 `summaryRef.current` 非空,构造副本数组,在 leading system 消息后插入 `new SystemMessage('【前情提要】\n' + summary)` 传给 `runAgentLoop` 的 `messages`;`messagesRef.current = result.messages` 改为先剔除(过滤 system 且 content 以「【前情提要】」开头的消息);`applyResume` 同步 `summaryRef.current = record.summary ?? null`;/new 清空
128
+ - [ ] **Step 2: 恢复路径压缩** — picker Enter 与带参 resume 共用异步流程:加载 record 后,`splitTurns(record.messages).turns.length > KEEP_TURNS` 时置 busy + 「正在提炼前情…」→ `compressSession(record, createModel(ctx.modelId))`;compressed → `saveSession(新 record)` 再 `applyResume`;error → `applyResume(原 record)` + 追加「压缩失败,已恢复完整对话」;最后 `addHistory(renderTranscript(summaryRef.current, messagesRef.current))` 渲染窗口(≤10 轮也渲染,无提要块)
129
+ - [ ] **Step 3: /compact 命令** — commands.ts 注册占位条目(name `compact`,描述「压缩当前会话:旧轮提炼为前情提要,保留最近 10 轮」,注明 Intercepted by the REPL);REPL handleSubmit 内联:无会话 →「当前没有进行中的会话」;≤10 轮 →「无需压缩(当前 N 轮)」;否则同 Step 2 流程,成功后 `messagesRef/summaryRef` 就地更新 + `saveSession` + 渲染提要块
130
+ - [ ] **Step 4: 全量验证** — `bun test` 全绿 + `npm run typecheck` 无输出 + `npm run build:repl` 成功
131
+ - [ ] **Step 5: Commit** — `feat: auto-compact on resume and /compact command with digest context injection`
@@ -0,0 +1,35 @@
1
+ # 恢复会话压缩(前情提要 + 最近 10 轮)— 设计
2
+
3
+ ## 意图
4
+
5
+ 长会话恢复时不再把全量历史塞进模型上下文:超过 10 轮的会话,恢复时自动把旧轮提炼成「前情提要」,会话文件重写为「摘要 + 最近 10 轮」,旧原文丢弃;恢复后聊天区以原有对话样式展示提要与最近 10 轮,继续对话。
6
+
7
+ ## 目标
8
+
9
+ - 恢复时轮数 > 10:旧轮(含其中工具消息)由当前模型提炼为摘要,文件原子写回为摘要 + 最近 10 轮
10
+ - **`/compact` 命令**:随时主动压缩当前进行中的会话 —— 超过 10 轮时旧轮立即提炼,`messagesRef`/`summaryRef` 就地更新并写回文件;≤10 轮提示「无需压缩」;完成后聊天区显示前情提要块
11
+ - 恢复后展示:顶部灰色「📝 前情提要(旧 N 轮)」块 + 最近 10 轮按现有问答样式渲染
12
+ - 模型上下文 = 系统提示 + 前情提要(注入为系统提示后的一条 SystemMessage,仅调用时拼接,不入库)+ 最近 10 轮
13
+ - 再次超限后的下一次恢复:新摘要 = 旧摘要 + 新裁掉的轮 合并提炼(滚动)
14
+ - ≤10 轮行为完全不变;压缩失败(模型调用出错/返回空)→ 回退全量恢复并提示,不阻塞
15
+
16
+ ## 非目标
17
+
18
+ - 不做轮数配置(常量 `KEEP_TURNS = 10`)
19
+ - 不做 token 级窗口、会话进行中压缩、摘要的手动编辑
20
+ - `/sessions` 列表不显示摘要
21
+
22
+ ## 设计
23
+
24
+ - **轮的定义**:一条 `HumanMessage` 到下一条 `HumanMessage` 之前的全部(AI/Tool 消息归属该轮);开头的 SystemMessage 不算轮,原样保留在 messages 头部。
25
+ - **数据模型**:`SessionRecord` 增加 `summary?: string`;压缩后 `messages = [开头 SystemMessage] + 最近 10 轮`,`summary = 提炼文本(≤约 500 字)`。
26
+ - **提炼 prompt**:输入旧摘要(若有)+ 被裁掉的轮,要求保留:决定与结论、代码/文件等关键事实、未完成事项;只输出提要本身。
27
+ - **调用点**:新模块 `src/sessions/compact.ts` —— `splitTurns`(纯)、`compressSession(record, model)`(编排,内部调模型,失败返回原 record + 错误标记);三个入口共用:**恢复路径两条**(选择器 Enter / 带参)+ **`/compact` 命令**(从 conversationRef/messagesRef 现场组装 record 调用,成功后回写内存态与文件)。
28
+ - **运行时注入**:turn 提交时若 `summaryRef` 非空,在消息数组头部系统提示后插入提要 SystemMessage 的副本传入 agent loop;持久化不含注入消息。
29
+ - **展示**:恢复完成后 `addHistory` 输出提要块 + 最近 10 轮的问答渲染(问题/回复沿用现有 rule-framed 高亮样式,工具活动不重放)。
30
+
31
+ ## 备选(已否)
32
+
33
+ - 仅内存压缩、文件保留全量:原始数据不丢,但每次恢复重复付 LLM 成本、文件继续膨胀 — 用户已选写回。
34
+ - 保存时滚动压缩:文件永远轻,但每轮多一次模型调用,且压缩发生在会话进行中而非恢复时 — 与需求描述不符。
35
+ - 摘要作为 messages 内嵌消息持久化:渲染与再压缩都要靠消息类型嗅探 — 改用显式字段。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trans-ai/trans-code",
3
- "version": "0.7.1",
3
+ "version": "0.8.1",
4
4
  "description": "AI-powered multi-model coding CLI",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/src/commands.ts CHANGED
@@ -88,6 +88,12 @@ const commands: Command[] = [
88
88
  // Intercepted by the REPL.
89
89
  execute: () => ({ output: 'Resuming…' }),
90
90
  },
91
+ {
92
+ name: 'compact',
93
+ description: '压缩当前会话:旧轮提炼为前情提要,保留最近 10 轮',
94
+ // Intercepted by the REPL.
95
+ execute: () => ({ output: 'Compacting…' }),
96
+ },
91
97
  {
92
98
  name: 'route',
93
99
  description: 'Show or set role→model routing (analysis/design/vision/…)',
@@ -21,6 +21,7 @@ import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
21
21
  import { createToolSession } from '../agent/tools/index.js';
22
22
  import { getPermissionMode } from '../agent/permission.js';
23
23
  import {
24
+ buildSessionRecord,
24
25
  generateTitle,
25
26
  listSessions,
26
27
  newSessionId,
@@ -29,6 +30,7 @@ import {
29
30
  type SessionRecord,
30
31
  } from '../sessions/store.js';
31
32
  import { listProjectSessions, resolveResumeTarget } from '../sessions/resume.js';
33
+ import { KEEP_TURNS, compressSession, transcriptEntries, splitTurns } from '../sessions/compact.js';
32
34
  import { walkFiles } from '../agent/tools/fs-utils.js';
33
35
  import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
34
36
  import {
@@ -137,6 +139,8 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
137
139
  // Conversation persistence: lazily created record + model-generated title.
138
140
  const conversationRef = useRef<{ id: string; createdAt: number; titled: boolean } | null>(null);
139
141
  const conversationTitleRef = useRef('');
142
+ // Compaction digest of turns older than the kept window (from resume//compact).
143
+ const summaryRef = useRef<string | null>(null);
140
144
  const lastSessionsRef = useRef<string[]>([]);
141
145
  // Snapshot for the /resume arrow-key picker (set together with the phase).
142
146
  const sessionPickerRef = useRef<SessionRecord[]>([]);
@@ -145,6 +149,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
145
149
  (record: SessionRecord, inputLine: string) => {
146
150
  conversationRef.current = { id: record.id, createdAt: record.createdAt, titled: true };
147
151
  conversationTitleRef.current = record.title;
152
+ summaryRef.current = record.summary ?? null;
148
153
  messagesRef.current = record.messages;
149
154
  toolSessionRef.current = createToolSession(process.cwd());
150
155
  addHistory({
@@ -232,6 +237,39 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
232
237
  setBusy(v);
233
238
  }, []);
234
239
 
240
+ /** Shared resume flow: auto-compact over-long sessions, then load + render. */
241
+ const resumeWith = async (record: SessionRecord, inputLine: string) => {
242
+ const { turns } = splitTurns(record.messages);
243
+ let finalRecord = record;
244
+ let oldTurns = 0;
245
+ if (turns.length > KEEP_TURNS) {
246
+ setBusyBoth(true);
247
+ try {
248
+ if (process.env.TRANSCODE_MOCK !== '1') {
249
+ const outcome = await compressSession(record, createModel(ctx.modelId).model);
250
+ if (outcome.compressed) {
251
+ finalRecord = outcome.record;
252
+ oldTurns = turns.length - KEEP_TURNS;
253
+ saveSession(finalRecord);
254
+ } else {
255
+ addHistory({ input: '', output: `⚠ 提炼失败(${outcome.error ?? '未知'}),已恢复完整对话。` });
256
+ }
257
+ }
258
+ } catch {
259
+ addHistory({ input: '', output: '⚠ 提炼失败,已恢复完整对话。' });
260
+ } finally {
261
+ setBusyBoth(false);
262
+ }
263
+ }
264
+ applyResume(finalRecord, inputLine);
265
+ // Restore in the original conversation form: each message becomes a
266
+ // history entry (rule-framed questions, full-length replies).
267
+ for (const entry of transcriptEntries(summaryRef.current, messagesRef.current, oldTurns || undefined)) {
268
+ addHistory(entry);
269
+ }
270
+ dragFlush();
271
+ };
272
+
235
273
  const appendChatOutput = useCallback((chunk: string) => {
236
274
  setHistory(prev => {
237
275
  if (prev.length === 0) return prev;
@@ -297,10 +335,21 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
297
335
  const titlesById = new Map<string, string>();
298
336
  const bufferedLines: string[] = [];
299
337
  let pendingCalls = 0;
338
+ // The digest rides in as a transient system message after the leading
339
+ // system prompt — passed as a copy and stripped from the result so it
340
+ // never lands in messagesRef or the persisted session.
341
+ let loopMessages = messagesRef.current;
342
+ if (summaryRef.current) {
343
+ const copy = [...messagesRef.current];
344
+ let insertAt = 0;
345
+ while (insertAt < copy.length && copy[insertAt]!.getType() === 'system') insertAt++;
346
+ copy.splice(insertAt, 0, new SystemMessage(`【前情提要】\n${summaryRef.current}`));
347
+ loopMessages = copy;
348
+ }
300
349
  const result = await runAgentLoop({
301
350
  model: provider?.model,
302
351
  cwd: process.cwd(),
303
- messages: messagesRef.current,
352
+ messages: loopMessages,
304
353
  systemPrompt: options?.planMode
305
354
  ? `${systemPrompt}\n\nPLAN MODE: explore read-only, then output a numbered implementation plan with exact files and changes. End with the line PLAN READY. Do not modify anything.`
306
355
  : systemPrompt,
@@ -352,7 +401,14 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
352
401
  for (const line of bufferedLines) appendChatOutput(line);
353
402
  }
354
403
 
355
- messagesRef.current = result.messages;
404
+ messagesRef.current = result.messages.filter(
405
+ (message) =>
406
+ !(
407
+ message.getType() === 'system' &&
408
+ typeof message.content === 'string' &&
409
+ message.content.startsWith('【前情提要】')
410
+ ),
411
+ );
356
412
 
357
413
  // Persist the conversation for /sessions and /resume.
358
414
  if (!conversationRef.current) {
@@ -365,15 +421,17 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
365
421
  }
366
422
  const conversation = conversationRef.current;
367
423
  const persist = () =>
368
- saveSession({
369
- id: conversation.id,
370
- title: conversationTitleRef.current,
371
- createdAt: conversation.createdAt,
372
- updatedAt: Date.now(),
373
- cwd: process.cwd(),
374
- model: ctx.modelId,
375
- messages: messagesRef.current,
376
- });
424
+ saveSession(
425
+ buildSessionRecord({
426
+ id: conversation.id,
427
+ title: conversationTitleRef.current,
428
+ createdAt: conversation.createdAt,
429
+ cwd: process.cwd(),
430
+ model: ctx.modelId,
431
+ messages: messagesRef.current,
432
+ summary: summaryRef.current,
433
+ }),
434
+ );
377
435
  persist();
378
436
  if (!conversation.titled && provider) {
379
437
  conversation.titled = true;
@@ -610,6 +668,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
610
668
  if (cmdName === 'new') {
611
669
  conversationRef.current = null;
612
670
  conversationTitleRef.current = '';
671
+ summaryRef.current = null;
613
672
  messagesRef.current = [];
614
673
  toolSessionRef.current = createToolSession(process.cwd());
615
674
  addHistory({ input: trimmed, output: '已开始新对话。' });
@@ -664,7 +723,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
664
723
  if (!record) {
665
724
  addHistory({ input: trimmed, output: `未找到对话“${target}”。先 /sessions 查看列表。` });
666
725
  } else {
667
- applyResume(record, trimmed);
726
+ await resumeWith(record, trimmed);
668
727
  }
669
728
  }
670
729
  commitInput('');
@@ -674,6 +733,61 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
674
733
  return;
675
734
  }
676
735
 
736
+ if (cmdName === 'compact') {
737
+ const finishCompact = () => {
738
+ commitInput('');
739
+ setHistoryIndex(-1);
740
+ setSavedInput('');
741
+ dragFlush();
742
+ };
743
+ if (!conversationRef.current) {
744
+ addHistory({ input: trimmed, output: '当前没有进行中的会话,先聊几句或 /resume 恢复一个。' });
745
+ finishCompact();
746
+ return;
747
+ }
748
+ const { turns } = splitTurns(messagesRef.current);
749
+ if (turns.length <= KEEP_TURNS) {
750
+ addHistory({ input: trimmed, output: `无需压缩:当前 ${turns.length} 轮 ≤ ${KEEP_TURNS}。` });
751
+ finishCompact();
752
+ return;
753
+ }
754
+ setBusyBoth(true);
755
+ try {
756
+ const record: SessionRecord = buildSessionRecord({
757
+ id: conversationRef.current.id,
758
+ title: conversationTitleRef.current,
759
+ createdAt: conversationRef.current.createdAt,
760
+ cwd: process.cwd(),
761
+ model: ctx.modelId,
762
+ messages: messagesRef.current,
763
+ summary: summaryRef.current,
764
+ });
765
+ const outcome = process.env.TRANSCODE_MOCK === '1'
766
+ ? { compressed: false as const, record, error: 'mock 模式无模型' }
767
+ : await compressSession(record, createModel(ctx.modelId).model);
768
+ if (outcome.compressed) {
769
+ summaryRef.current = outcome.record.summary ?? null;
770
+ messagesRef.current = outcome.record.messages;
771
+ saveSession(outcome.record);
772
+ addHistory({
773
+ input: trimmed,
774
+ output: `已压缩:旧 ${turns.length - KEEP_TURNS} 轮提炼为前情提要,保留最近 ${KEEP_TURNS} 轮。`,
775
+ });
776
+ for (const entry of transcriptEntries(summaryRef.current, messagesRef.current)) {
777
+ addHistory(entry);
778
+ }
779
+ } else {
780
+ addHistory({ input: trimmed, output: `⚠ 压缩失败(${outcome.error ?? '未知'}),会话保持原样。` });
781
+ }
782
+ } catch {
783
+ addHistory({ input: trimmed, output: '⚠ 压缩失败,会话保持原样。' });
784
+ } finally {
785
+ setBusyBoth(false);
786
+ }
787
+ finishCompact();
788
+ return;
789
+ }
790
+
677
791
  if (cmdName === 'plan') {
678
792
  const task = stripped.startsWith('/plan') ? stripped.slice(5).trim() : stripped;
679
793
  if (!task) {
@@ -748,8 +862,10 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
748
862
  }
749
863
  if (key.escape) {
750
864
  // While generating, Esc cancels instead of exiting.
751
- if (busyRef.current && abortRef.current) {
752
- abortRef.current.abort();
865
+ if (busyRef.current) {
866
+ // Busy covers both a live agent turn (abort it) and async
867
+ // compaction (no controller yet — Esc must not quit the app).
868
+ abortRef.current?.abort();
753
869
  return;
754
870
  }
755
871
  if (phase !== 'idle') {
@@ -846,9 +962,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
846
962
  const record = picker[sessionCursor];
847
963
  if (record) {
848
964
  setPhase('idle');
849
- applyResume(record, '/resume');
850
- // Stdin-path terminal action: nudge the render flush (Bun quirk).
851
- dragFlush();
965
+ void resumeWith(record, '/resume');
852
966
  }
853
967
  return;
854
968
  }
@@ -0,0 +1,132 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { AIMessage, HumanMessage, SystemMessage, ToolMessage, type BaseMessage } from '@langchain/core/messages';
3
+ import type { SessionRecord } from './store.js';
4
+ import { KEEP_TURNS, TRANSCRIPT_LIMIT, compressSession, transcriptEntries, splitTurns } from './compact.js';
5
+
6
+ function turn(n: number, text = 'x'): BaseMessage[] {
7
+ return [new HumanMessage(`问题${n}:${text}`), new AIMessage(`回答${n}:${text}`)];
8
+ }
9
+
10
+ function recordWith(turns: number, opts: { summary?: string; longTurn?: boolean } = {}): SessionRecord {
11
+ const messages: BaseMessage[] = [new SystemMessage('system prompt')];
12
+ for (let i = 1; i <= turns; i++) {
13
+ messages.push(...turn(i, opts.longTurn ? '长'.repeat(20_000) : '正文'));
14
+ }
15
+ return {
16
+ id: 'ses_c1',
17
+ title: '压缩测试',
18
+ createdAt: 1,
19
+ updatedAt: 1,
20
+ cwd: '/tmp/proj',
21
+ model: 'deepseek',
22
+ messages,
23
+ ...(opts.summary ? { summary: opts.summary } : {}),
24
+ };
25
+ }
26
+
27
+ function mockModel(text: string): { invoke: (input: string) => Promise<{ content: string }>; prompts: string[] } {
28
+ const prompts: string[] = [];
29
+ return {
30
+ prompts,
31
+ invoke: async (input: string) => {
32
+ prompts.push(input);
33
+ return { content: text };
34
+ },
35
+ };
36
+ }
37
+
38
+ describe('splitTurns', () => {
39
+ test('leading system messages are not a turn; tool/AI messages attach to their human turn', () => {
40
+ const msgs: BaseMessage[] = [
41
+ new SystemMessage('sys'),
42
+ new HumanMessage('a'),
43
+ new AIMessage({ content: '思考', tool_calls: [{ id: 't1', name: 'bash', args: { command: 'ls' } }] }),
44
+ new ToolMessage({ content: 'out', tool_call_id: 't1', name: 'bash' }),
45
+ new AIMessage('答a'),
46
+ new HumanMessage('b'),
47
+ new AIMessage('答b'),
48
+ ];
49
+ const { leading, turns } = splitTurns(msgs);
50
+ expect(leading.map((m) => m.getType())).toEqual(['system']);
51
+ expect(turns.length).toBe(2);
52
+ expect(turns[0]!.map((m) => m.getType())).toEqual(['human', 'ai', 'tool', 'ai']);
53
+ expect(turns[1]!.map((m) => m.getType())).toEqual(['human', 'ai']);
54
+ });
55
+ });
56
+
57
+ describe('compressSession', () => {
58
+ test('more than KEEP_TURNS: trims to window, sets summary, keeps leading, bumps updatedAt', async () => {
59
+ const { compressed, record } = await compressSession(recordWith(12), mockModel('提要内容'));
60
+ expect(compressed).toBe(true);
61
+ expect(record.summary).toBe('提要内容');
62
+ expect(splitTurns(record.messages).turns.length).toBe(KEEP_TURNS);
63
+ expect(record.messages[0]!.getType()).toBe('system');
64
+ expect(record.updatedAt).toBeGreaterThan(1);
65
+ });
66
+
67
+ test('at or below KEEP_TURNS is a no-op returning the original record', async () => {
68
+ const rec = recordWith(KEEP_TURNS);
69
+ const { compressed, record } = await compressSession(rec, mockModel('x'));
70
+ expect(compressed).toBe(false);
71
+ expect(record).toBe(rec);
72
+ });
73
+
74
+ test('model failure returns original record with error', async () => {
75
+ const rec = recordWith(12);
76
+ const failing = {
77
+ invoke: async () => {
78
+ throw new Error('API down');
79
+ },
80
+ };
81
+ const { compressed, record, error } = await compressSession(rec, failing);
82
+ expect(compressed).toBe(false);
83
+ expect(error).toBeDefined();
84
+ expect(record).toBe(rec);
85
+ });
86
+
87
+ test('empty model reply is treated as failure', async () => {
88
+ const { compressed, error } = await compressSession(recordWith(12), mockModel(' '));
89
+ expect(compressed).toBe(false);
90
+ expect(error).toBeDefined();
91
+ });
92
+
93
+ test('rolling merge: previous summary appears in the prompt', async () => {
94
+ const model = mockModel('新提要');
95
+ await compressSession(recordWith(12, { summary: '旧提要内容' }), model);
96
+ expect(model.prompts[0]).toContain('旧提要内容');
97
+ });
98
+
99
+ test('huge old transcript is truncated before invoking the model', async () => {
100
+ const model = mockModel('提要');
101
+ await compressSession(recordWith(12, { longTurn: true }), model);
102
+ expect(model.prompts[0]!.length).toBeLessThan(TRANSCRIPT_LIMIT + 2_000);
103
+ expect(model.prompts[0]).toContain('更早内容已截断');
104
+ });
105
+ });
106
+
107
+ describe('transcriptEntries', () => {
108
+ test('digest first, then per-message entries: human→input, ai→output, full content, tool/system skipped', () => {
109
+ const messages: BaseMessage[] = [
110
+ new SystemMessage('sys'),
111
+ new HumanMessage('问题甲'),
112
+ new AIMessage({ content: '', tool_calls: [{ id: 't1', name: 'bash', args: {} }] }),
113
+ new ToolMessage({ content: 'out', tool_call_id: 't1', name: 'bash' }),
114
+ new AIMessage('回答'.repeat(200)),
115
+ ];
116
+ const entries = transcriptEntries('前情文本', messages, 3);
117
+ // digest entry
118
+ expect(entries[0]).toEqual({ input: '', output: '📝 前情提要(旧 3 轮)\n前情文本' });
119
+ const rest = entries.slice(1);
120
+ expect(rest).toHaveLength(2);
121
+ expect(rest[0]).toEqual({ input: '问题甲', output: '' });
122
+ expect(rest[1]).toEqual({ input: '', output: '回答'.repeat(200) });
123
+ });
124
+
125
+ test('null summary yields turn entries only, no digest', () => {
126
+ const entries = transcriptEntries(null, turn(1, '正文'));
127
+ expect(entries).toEqual([
128
+ { input: '问题1:正文', output: '' },
129
+ { input: '', output: '回答1:正文' },
130
+ ]);
131
+ });
132
+ });
@@ -0,0 +1,135 @@
1
+ import { AIMessage, type BaseMessage, type MessageContent } from '@langchain/core/messages';
2
+ import type { SessionRecord } from './store.js';
3
+
4
+ /** Verbatim window kept on compaction; older turns get distilled. */
5
+ export const KEEP_TURNS = 10;
6
+
7
+ /** Cap on the transcript fed to the distilling model (protects its context). */
8
+ export const TRANSCRIPT_LIMIT = 40_000;
9
+
10
+ /** Minimal model surface needed for distillation (mock-friendly). */
11
+ export interface CompactModel {
12
+ invoke(input: string): Promise<{ content: unknown }>;
13
+ }
14
+
15
+ /**
16
+ * Split a message list into leading (pre-first-human) messages and turns.
17
+ * A turn starts at each HumanMessage and owns every AI/Tool message until
18
+ * the next HumanMessage.
19
+ */
20
+ export function splitTurns(messages: BaseMessage[]): {
21
+ leading: BaseMessage[];
22
+ turns: BaseMessage[][];
23
+ } {
24
+ const leading: BaseMessage[] = [];
25
+ const turns: BaseMessage[][] = [];
26
+ for (const message of messages) {
27
+ if (turns.length === 0 && message.getType() !== 'human') {
28
+ leading.push(message);
29
+ continue;
30
+ }
31
+ if (message.getType() === 'human') turns.push([message]);
32
+ else turns[turns.length - 1]!.push(message);
33
+ }
34
+ return { leading, turns };
35
+ }
36
+
37
+ const contentText = (content: MessageContent): string =>
38
+ typeof content === 'string' ? content : JSON.stringify(content);
39
+
40
+ function messageLine(message: BaseMessage): string {
41
+ const kind = message.getType();
42
+ const text = contentText(message.content);
43
+ if (kind === 'human') return `用户: ${text}`;
44
+ if (kind === 'tool') return `工具结果: ${text}`;
45
+ if (kind === 'ai') {
46
+ const calls = (message as AIMessage).tool_calls?.map((c) => c.name).join(', ');
47
+ return `助手: ${text}${calls ? ` [调用 ${calls}]` : ''}`;
48
+ }
49
+ return `系统: ${text}`;
50
+ }
51
+
52
+ function renderTranscriptText(turns: BaseMessage[][]): string {
53
+ const body = turns
54
+ .map((msgs, i) => `— 第${i + 1}轮 —\n${msgs.map(messageLine).join('\n')}`)
55
+ .join('\n\n');
56
+ if (body.length <= TRANSCRIPT_LIMIT) return body;
57
+ return `(更早内容已截断)\n${body.slice(-TRANSCRIPT_LIMIT)}`;
58
+ }
59
+
60
+ function buildPrompt(previousSummary: string | undefined, oldTurns: BaseMessage[][]): string {
61
+ const head =
62
+ '把下面的对话历史提炼成一份"前情提要",供后续对话延续上下文使用。' +
63
+ '必须保留:已做的决定与结论、关键事实(涉及的文件、代码、命令、错误)、尚未完成的事项。' +
64
+ '直接输出提要正文,不要标题和客套,不超过 500 字。';
65
+ const prior = previousSummary
66
+ ? `\n已有前情提要(在此基础上合并更新):\n${previousSummary}\n`
67
+ : '';
68
+ return `${head}${prior}\n对话历史:\n${renderTranscriptText(oldTurns)}`;
69
+ }
70
+
71
+ function replyText(content: unknown): string {
72
+ return (typeof content === 'string' ? content : JSON.stringify(content)).trim();
73
+ }
74
+
75
+ /**
76
+ * Distill turns older than the kept window into `summary`, returning a new
77
+ * record trimmed to [leading, last KEEP_TURNS turns]. ≤KEEP_TURNS or a failed
78
+ * model call returns the original record unchanged (with `error` set on
79
+ * failure) — callers fall back to a full restore.
80
+ */
81
+ export async function compressSession(
82
+ record: SessionRecord,
83
+ model: CompactModel,
84
+ ): Promise<{ compressed: boolean; record: SessionRecord; error?: string }> {
85
+ const { leading, turns } = splitTurns(record.messages);
86
+ if (turns.length <= KEEP_TURNS) return { compressed: false, record };
87
+ const keep = turns.slice(-KEEP_TURNS);
88
+ const old = turns.slice(0, turns.length - KEEP_TURNS);
89
+ let summary: string;
90
+ try {
91
+ const response = await model.invoke(buildPrompt(record.summary, old));
92
+ summary = replyText(response.content);
93
+ } catch (error) {
94
+ return { compressed: false, record, error: error instanceof Error ? error.message : String(error) };
95
+ }
96
+ if (!summary) return { compressed: false, record, error: '模型返回了空前情提要' };
97
+ return {
98
+ compressed: true,
99
+ record: {
100
+ ...record,
101
+ summary,
102
+ messages: [...leading, ...keep.flat()],
103
+ updatedAt: Date.now(),
104
+ },
105
+ };
106
+ }
107
+
108
+ /**
109
+ * History entries for the restored view: optional digest first, then one
110
+ * entry per message — human turns as `input` (rule-framed highlight), AI
111
+ * replies as full-length `output`. Tool activity and system messages are
112
+ * not replayed. Rendering is the existing per-entry chat form.
113
+ */
114
+ export function transcriptEntries(
115
+ summary: string | null,
116
+ messages: BaseMessage[],
117
+ oldTurnsCount?: number,
118
+ ): { input: string; output: string }[] {
119
+ const entries: { input: string; output: string }[] = [];
120
+ if (summary) {
121
+ entries.push({
122
+ input: '',
123
+ output: `📝 前情提要${oldTurnsCount ? `(旧 ${oldTurnsCount} 轮)` : ''}\n${summary}`,
124
+ });
125
+ }
126
+ for (const message of messages) {
127
+ const kind = message.getType();
128
+ if (kind === 'human') entries.push({ input: contentText(message.content), output: '' });
129
+ else if (kind === 'ai') {
130
+ const text = contentText(message.content);
131
+ if (text) entries.push({ input: '', output: text });
132
+ }
133
+ }
134
+ return entries;
135
+ }
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { AIMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
7
7
  import {
8
+ buildSessionRecord,
8
9
  getSession,
9
10
  listSessions,
10
11
  newSessionId,
@@ -136,6 +137,32 @@ describe('session store', () => {
136
137
  expect(getSession('ses_test1')?.title).toBe('旧内容');
137
138
  });
138
139
 
140
+ test('summary field roundtrips when present, stays absent otherwise', () => {
141
+ saveSession({ ...sample('带提要', 'x'), summary: '旧提要内容' });
142
+ expect(getSession('ses_test1')?.summary).toBe('旧提要内容');
143
+
144
+ saveSession({ ...sample('无提要', 'y'), id: 'ses_test2' });
145
+ expect(getSession('ses_test2')?.summary).toBeUndefined();
146
+ });
147
+
148
+ test('buildSessionRecord keeps the compaction digest in the persisted record', () => {
149
+ const base = {
150
+ id: 'ses_b1',
151
+ title: '带提要',
152
+ createdAt: 1,
153
+ cwd: '/tmp',
154
+ model: 'deepseek',
155
+ messages: sample('x', 'y').messages,
156
+ };
157
+ const withDigest = buildSessionRecord({ ...base, summary: '前情提要文本' });
158
+ expect(withDigest.summary).toBe('前情提要文本');
159
+ expect(withDigest.updatedAt).toBeGreaterThan(1);
160
+
161
+ // Null/undefined digest must not materialize an empty summary field.
162
+ expect(buildSessionRecord({ ...base, summary: null }).summary).toBeUndefined();
163
+ expect(buildSessionRecord(base).summary).toBeUndefined();
164
+ });
165
+
139
166
  test('list is ordered newest first', () => {
140
167
  const older = sample('旧对话', 'a');
141
168
  older.createdAt = Date.now() - 10_000;
@@ -20,6 +20,8 @@ export interface SessionRecord {
20
20
  cwd: string;
21
21
  model: string;
22
22
  messages: BaseMessage[];
23
+ /** Distilled digest of turns older than the kept compaction window. */
24
+ summary?: string;
23
25
  }
24
26
 
25
27
  interface StoredMessage {
@@ -42,6 +44,32 @@ export function newSessionId(): string {
42
44
  return randomUUID();
43
45
  }
44
46
 
47
+ /** Inputs for assembling a persistable record (digest is optional). */
48
+ export interface SessionRecordInput {
49
+ id: string;
50
+ title: string;
51
+ createdAt: number;
52
+ cwd: string;
53
+ model: string;
54
+ messages: BaseMessage[];
55
+ /** Compaction digest; null/undefined records carry no summary field. */
56
+ summary?: string | null;
57
+ }
58
+
59
+ /**
60
+ * Assemble the record persist() and /compact both write. The summary MUST
61
+ * ride along here — a turn after a compaction otherwise erases the digest
62
+ * from disk while the old turns are already discarded.
63
+ */
64
+ export function buildSessionRecord(input: SessionRecordInput): SessionRecord {
65
+ const { summary, ...rest } = input;
66
+ return {
67
+ ...rest,
68
+ updatedAt: Date.now(),
69
+ ...(summary ? { summary } : {}),
70
+ };
71
+ }
72
+
45
73
  function serialize(messages: BaseMessage[]): StoredMessage[] {
46
74
  return messages.map((message) => {
47
75
  const stored: StoredMessage = { type: message.getType(), content: message.content };
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.7.1';
2
+ export const VERSION = '0.8.1';