@trans-ai/trans-code 0.8.0 → 0.8.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.
@@ -0,0 +1,74 @@
1
+ # 压缩保留轮数参数化 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:** `/compact [N]` 与 `/resume [target] [N]` 可指定压缩保留的最近轮数,默认 1 轮。
6
+
7
+ **Architecture:** `compressSession` 增加第三参 `keepTurns`(默认 `DEFAULT_KEEP_TURNS = 1`),新增纯函数 `parseKeepCount` 校验参数;REPL 两条恢复路径与 /compact 接线;核心逻辑 TDD。
8
+
9
+ **Tech Stack:** TypeScript、bun:test。
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-21-keep-turns-param-design.md`
12
+
13
+ ## Global Constraints
14
+
15
+ - `DEFAULT_KEEP_TURNS = 1`(替代 `KEEP_TURNS = 10`)
16
+ - `/resume` 首参仍是会话目标(现有解析不变);第二个纯数字参数 ≥1 才生效,非法(0/负数/非数字)提示用法并按默认执行
17
+ - 保留轮数不持久化
18
+ - 其余行为(滚动合并、失败回退、原子写、前情提要注入)不动
19
+
20
+ ## Review Focus
21
+
22
+ - 默认值语义:>1 轮会话默认压缩到只剩 1 轮(Task 测试:default keeps 1)
23
+ - `/resume 3 0`、`/resume 3 abc`:用法提示 + 按默认执行,不崩(parseKeepCount 测试)
24
+ - 显式大窗口仍可用:`compressSession(rec, model, 10)` 保留 10 轮(Task 测试)
25
+ - picker Enter(无参路径)用默认 1(接线,复用现有 DEFAULT 导入)
26
+ - 「无需压缩」提示与「旧 N 轮」计数按生效 N 计算(接线)
27
+
28
+ ---
29
+
30
+ ### Task 1: keepTurns 参数化(核心 + 接线)
31
+
32
+ **Files:**
33
+ - Modify: `src/sessions/compact.ts`、`src/sessions/compact.test.ts`、`src/screens/REPL.tsx`(resume 分支、resumeWith、/compact 分支)
34
+
35
+ **Interfaces:**
36
+ - Produces:
37
+ - `export const DEFAULT_KEEP_TURNS = 1`
38
+ - `compressSession(record, model, keepTurns = DEFAULT_KEEP_TURNS)`(内部窗口判断全用 keepTurns,`Math.max(1, keepTurns)` 防御)
39
+ - `parseKeepCount(raw: string | undefined): { keep?: number; error?: string }` — undefined→`{}`;`/^\d+$/` 且 ≥1→`{keep:N}`;否则→`{error:'保留轮数需为 ≥1 的整数,已按默认 N 轮执行'}`(N 为默认值)
40
+
41
+ - [ ] **Step 1: 失败测试**(compact.test.ts 重写压缩用例并新增)
42
+
43
+ ```ts
44
+ test('default keeps only 1 turn', async () => {
45
+ const { compressed, record } = await compressSession(recordWith(3), mockModel('提要'));
46
+ expect(compressed).toBe(true);
47
+ expect(splitTurns(record.messages).turns.length).toBe(1);
48
+ });
49
+ test('explicit keepTurns=10 keeps 10', async () => {
50
+ const { record } = await compressSession(recordWith(12), mockModel('提要'), 10);
51
+ expect(splitTurns(record.messages).turns.length).toBe(10);
52
+ });
53
+ test('keepTurns below 1 clamps to 1', async () => {
54
+ const { record } = await compressSession(recordWith(3), mockModel('提要'), 0);
55
+ expect(splitTurns(record.messages).turns.length).toBe(1);
56
+ });
57
+ describe('parseKeepCount', () => {
58
+ test('undefined → default; "5" → 5; "0"/"abc" → error, no keep', () => {
59
+ expect(parseKeepCount(undefined)).toEqual({});
60
+ expect(parseKeepCount('5')).toEqual({ keep: 5 });
61
+ expect(parseKeepCount('0').keep).toBeUndefined();
62
+ expect(parseKeepCount('0').error).toBeDefined();
63
+ expect(parseKeepCount('abc').error).toBeDefined();
64
+ });
65
+ });
66
+ ```
67
+ (既有「≤KEEP_TURNS no-op」用例改为显式传 10;rolling merge / truncation / failure 用例传 10 保持原语义)
68
+
69
+ - [ ] **Step 2: 确认失败** — `bun test src/sessions/compact.test.ts` → FAIL(KEEP_TURNS/parseKeepCount 不存在)
70
+ - [ ] **Step 3: 实现** — `DEFAULT_KEEP_TURNS = 1`;`compressSession` 第三参与钳制;`parseKeepCount` 按接口注释
71
+ - [ ] **Step 4: 确认通过** — 同命令 → PASS
72
+ - [ ] **Step 5: REPL 接线** — import 改 `DEFAULT_KEEP_TURNS`;resume 分支:`parseKeepCount(args[1])`,error 则 addHistory 提示,keep 传入 `resumeWith(record, trimmed, keep)`;`resumeWith(record, inputLine, keepTurns = DEFAULT_KEEP_TURNS)` 内部判断与 `oldTurns = turns.length - keepTurns` 全部改用参数;picker Enter 调 `resumeWith(record, '/resume')` 走默认;`/compact` 分支:`parseKeepCount(args[0])` 同规则,「无需压缩(当前 X 轮 ≤ N)」与 oldTurnsCount 用生效 N
73
+ - [ ] **Step 6: 全量验证** — `bun test` 全绿 + `npm run typecheck` + `npm run build:repl`
74
+ - [ ] **Step 7: Commit** — `git add src/sessions/compact.ts src/sessions/compact.test.ts src/screens/REPL.tsx && git commit -m "feat: parameterizable keep-turns for /compact and /resume (default 1)"`
@@ -0,0 +1,26 @@
1
+ # 压缩保留轮数参数化(/compact、/resume)— 设计
2
+
3
+ ## 意图
4
+
5
+ 压缩保留的「最近 N 轮」由固定 10 改为**可传参、默认 1**,两个入口都支持。
6
+
7
+ ## 用法
8
+
9
+ - `/compact` → 保留最近 1 轮;`/compact 5` → 保留最近 5 轮
10
+ - `/resume` → 选择器,Enter 后按默认 1 轮压缩;`/resume 3` → 恢复第 3 个、默认 1 轮;`/resume 3 5` → 恢复第 3 个、保留 5 轮
11
+ - 解析:第二个纯数字参数 = 保留轮数,须 ≥1;不合法(N<1 或非数字)提示用法并忽略
12
+ - 选择器路径(Enter)固定用默认值,不接参数
13
+
14
+ ## 设计
15
+
16
+ - `compact.ts`:`KEEP_TURNS = 10` 改为 `DEFAULT_KEEP_TURNS = 1`;`compressSession(record, model, keepTurns = DEFAULT_KEEP_TURNS)`,内部所有窗口判断用 `keepTurns`
17
+ - REPL:恢复分支解析尾参(首参仍是会话目标,逻辑不变);`resumeWith(record, inputLine, keepTurns)`;`/compact` 分支解析首参数字;「无需压缩」提示与 oldTurnsCount 均按生效 N 计算
18
+ - 保留轮数**不持久化**到会话记录(会话记忆式方案已否)
19
+
20
+ ## 非目标
21
+
22
+ - 不做 picker 内选轮数、不做配置文件项、不改摘要提示词
23
+
24
+ ## 备选(已否)
25
+
26
+ - 会话记忆式(/compact 记住 N,resume 沿用):行为藏在数据里,换会话默认不同 — 用户选尾参式。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trans-ai/trans-code",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "AI-powered multi-model coding CLI",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/src/commands.ts CHANGED
@@ -84,13 +84,13 @@ const commands: Command[] = [
84
84
  },
85
85
  {
86
86
  name: 'resume',
87
- description: 'Resume a saved conversation (/resume <序号|id|标题片段>)',
87
+ description: 'Resume a saved conversation (/resume <序号|id|标题片段> [N])',
88
88
  // Intercepted by the REPL.
89
89
  execute: () => ({ output: 'Resuming…' }),
90
90
  },
91
91
  {
92
92
  name: 'compact',
93
- description: '压缩当前会话:旧轮提炼为前情提要,保留最近 10 轮',
93
+ description: '压缩当前会话:旧轮提炼为前情提要,默认保留最近 1 轮(/compact <N> 自定义)',
94
94
  // Intercepted by the REPL.
95
95
  execute: () => ({ output: 'Compacting…' }),
96
96
  },
@@ -29,8 +29,8 @@ import {
29
29
  searchSessions,
30
30
  type SessionRecord,
31
31
  } from '../sessions/store.js';
32
- import { listProjectSessions, resolveResumeTarget } from '../sessions/resume.js';
33
- import { KEEP_TURNS, compressSession, renderTranscript, splitTurns } from '../sessions/compact.js';
32
+ import { listProjectSessions, resolveResumeTarget, splitResumeArgs } from '../sessions/resume.js';
33
+ import { DEFAULT_KEEP_TURNS, compressSession, parseKeepCount, transcriptEntries, splitTurns } from '../sessions/compact.js';
34
34
  import { walkFiles } from '../agent/tools/fs-utils.js';
35
35
  import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
36
36
  import {
@@ -238,18 +238,18 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
238
238
  }, []);
239
239
 
240
240
  /** Shared resume flow: auto-compact over-long sessions, then load + render. */
241
- const resumeWith = async (record: SessionRecord, inputLine: string) => {
241
+ const resumeWith = async (record: SessionRecord, inputLine: string, keepTurns = DEFAULT_KEEP_TURNS) => {
242
242
  const { turns } = splitTurns(record.messages);
243
243
  let finalRecord = record;
244
244
  let oldTurns = 0;
245
- if (turns.length > KEEP_TURNS) {
245
+ if (turns.length > keepTurns) {
246
246
  setBusyBoth(true);
247
247
  try {
248
248
  if (process.env.TRANSCODE_MOCK !== '1') {
249
- const outcome = await compressSession(record, createModel(ctx.modelId).model);
249
+ const outcome = await compressSession(record, createModel(ctx.modelId).model, keepTurns);
250
250
  if (outcome.compressed) {
251
251
  finalRecord = outcome.record;
252
- oldTurns = turns.length - KEEP_TURNS;
252
+ oldTurns = turns.length - keepTurns;
253
253
  saveSession(finalRecord);
254
254
  } else {
255
255
  addHistory({ input: '', output: `⚠ 提炼失败(${outcome.error ?? '未知'}),已恢复完整对话。` });
@@ -262,10 +262,11 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
262
262
  }
263
263
  }
264
264
  applyResume(finalRecord, inputLine);
265
- addHistory({
266
- input: inputLine,
267
- output: renderTranscript(summaryRef.current, messagesRef.current, oldTurns || undefined),
268
- });
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
+ }
269
270
  dragFlush();
270
271
  };
271
272
 
@@ -705,7 +706,9 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
705
706
  }
706
707
 
707
708
  if (cmdName === 'resume') {
708
- const target = args.join(' ').trim();
709
+ const { target, keepRaw } = splitResumeArgs(args);
710
+ const { keep, error } = parseKeepCount(keepRaw);
711
+ if (error) addHistory({ input: '', output: `⚠ ${error}` });
709
712
  if (!target) {
710
713
  // One-step resume: arrow-key picker over this project's sessions.
711
714
  const projectSessions = listProjectSessions(process.cwd()).slice(0, 20);
@@ -722,7 +725,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
722
725
  if (!record) {
723
726
  addHistory({ input: trimmed, output: `未找到对话“${target}”。先 /sessions 查看列表。` });
724
727
  } else {
725
- await resumeWith(record, trimmed);
728
+ await resumeWith(record, trimmed, keep);
726
729
  }
727
730
  }
728
731
  commitInput('');
@@ -744,9 +747,12 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
744
747
  finishCompact();
745
748
  return;
746
749
  }
750
+ const { keep, error } = parseKeepCount(args[0]);
751
+ const keepN = keep ?? DEFAULT_KEEP_TURNS;
752
+ if (error) addHistory({ input: '', output: `⚠ ${error}` });
747
753
  const { turns } = splitTurns(messagesRef.current);
748
- if (turns.length <= KEEP_TURNS) {
749
- addHistory({ input: trimmed, output: `无需压缩:当前 ${turns.length} 轮 ≤ ${KEEP_TURNS}。` });
754
+ if (turns.length <= keepN) {
755
+ addHistory({ input: trimmed, output: `无需压缩:当前 ${turns.length} 轮 ≤ ${keepN}。` });
750
756
  finishCompact();
751
757
  return;
752
758
  }
@@ -763,17 +769,18 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
763
769
  });
764
770
  const outcome = process.env.TRANSCODE_MOCK === '1'
765
771
  ? { compressed: false as const, record, error: 'mock 模式无模型' }
766
- : await compressSession(record, createModel(ctx.modelId).model);
772
+ : await compressSession(record, createModel(ctx.modelId).model, keepN);
767
773
  if (outcome.compressed) {
768
774
  summaryRef.current = outcome.record.summary ?? null;
769
775
  messagesRef.current = outcome.record.messages;
770
776
  saveSession(outcome.record);
771
777
  addHistory({
772
778
  input: trimmed,
773
- output:
774
- `已压缩:旧 ${turns.length - KEEP_TURNS} 轮提炼为前情提要,保留最近 ${KEEP_TURNS} 轮。\n` +
775
- renderTranscript(summaryRef.current, messagesRef.current),
779
+ output: `已压缩:旧 ${turns.length - keepN} 轮提炼为前情提要,保留最近 ${keepN} 轮。`,
776
780
  });
781
+ for (const entry of transcriptEntries(summaryRef.current, messagesRef.current)) {
782
+ addHistory(entry);
783
+ }
777
784
  } else {
778
785
  addHistory({ input: trimmed, output: `⚠ 压缩失败(${outcome.error ?? '未知'}),会话保持原样。` });
779
786
  }
@@ -1,7 +1,14 @@
1
1
  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
- import { KEEP_TURNS, TRANSCRIPT_LIMIT, compressSession, renderTranscript, splitTurns } from './compact.js';
4
+ import {
5
+ DEFAULT_KEEP_TURNS,
6
+ TRANSCRIPT_LIMIT,
7
+ compressSession,
8
+ parseKeepCount,
9
+ transcriptEntries,
10
+ splitTurns,
11
+ } from './compact.js';
5
12
 
6
13
  function turn(n: number, text = 'x'): BaseMessage[] {
7
14
  return [new HumanMessage(`问题${n}:${text}`), new AIMessage(`回答${n}:${text}`)];
@@ -55,18 +62,29 @@ describe('splitTurns', () => {
55
62
  });
56
63
 
57
64
  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('提要内容'));
65
+ test('default keeps only 1 turn', async () => {
66
+ const { compressed, record } = await compressSession(recordWith(3), mockModel('提要内容'));
60
67
  expect(compressed).toBe(true);
61
68
  expect(record.summary).toBe('提要内容');
62
- expect(splitTurns(record.messages).turns.length).toBe(KEEP_TURNS);
69
+ expect(splitTurns(record.messages).turns.length).toBe(DEFAULT_KEEP_TURNS);
70
+ expect(splitTurns(record.messages).turns.length).toBe(1);
63
71
  expect(record.messages[0]!.getType()).toBe('system');
64
72
  expect(record.updatedAt).toBeGreaterThan(1);
65
73
  });
66
74
 
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'));
75
+ test('explicit keepTurns=10 keeps 10', async () => {
76
+ const { record } = await compressSession(recordWith(12), mockModel('提要'), 10);
77
+ expect(splitTurns(record.messages).turns.length).toBe(10);
78
+ });
79
+
80
+ test('keepTurns below 1 clamps to 1', async () => {
81
+ const { record } = await compressSession(recordWith(3), mockModel('提要'), 0);
82
+ expect(splitTurns(record.messages).turns.length).toBe(1);
83
+ });
84
+
85
+ test('at or below keepTurns is a no-op returning the original record', async () => {
86
+ const rec = recordWith(10);
87
+ const { compressed, record } = await compressSession(rec, mockModel('x'), 10);
70
88
  expect(compressed).toBe(false);
71
89
  expect(record).toBe(rec);
72
90
  });
@@ -78,55 +96,65 @@ describe('compressSession', () => {
78
96
  throw new Error('API down');
79
97
  },
80
98
  };
81
- const { compressed, record, error } = await compressSession(rec, failing);
99
+ const { compressed, record, error } = await compressSession(rec, failing, 10);
82
100
  expect(compressed).toBe(false);
83
101
  expect(error).toBeDefined();
84
102
  expect(record).toBe(rec);
85
103
  });
86
104
 
87
105
  test('empty model reply is treated as failure', async () => {
88
- const { compressed, error } = await compressSession(recordWith(12), mockModel(' '));
106
+ const { compressed, error } = await compressSession(recordWith(12), mockModel(' '), 10);
89
107
  expect(compressed).toBe(false);
90
108
  expect(error).toBeDefined();
91
109
  });
92
110
 
93
111
  test('rolling merge: previous summary appears in the prompt', async () => {
94
112
  const model = mockModel('新提要');
95
- await compressSession(recordWith(12, { summary: '旧提要内容' }), model);
113
+ await compressSession(recordWith(12, { summary: '旧提要内容' }), model, 10);
96
114
  expect(model.prompts[0]).toContain('旧提要内容');
97
115
  });
98
116
 
99
117
  test('huge old transcript is truncated before invoking the model', async () => {
100
118
  const model = mockModel('提要');
101
- await compressSession(recordWith(12, { longTurn: true }), model);
119
+ await compressSession(recordWith(12, { longTurn: true }), model, 10);
102
120
  expect(model.prompts[0]!.length).toBeLessThan(TRANSCRIPT_LIMIT + 2_000);
103
121
  expect(model.prompts[0]).toContain('更早内容已截断');
104
122
  });
105
123
  });
106
124
 
107
- describe('renderTranscript', () => {
108
- test('renders summary block plus human/ai pairs, skipping tool/system, capping line length', () => {
125
+ describe('parseKeepCount', () => {
126
+ test('undefined → default; "5" → 5; "0"/"abc" → error, no keep', () => {
127
+ expect(parseKeepCount(undefined)).toEqual({});
128
+ expect(parseKeepCount('5')).toEqual({ keep: 5 });
129
+ expect(parseKeepCount('0').keep).toBeUndefined();
130
+ expect(parseKeepCount('0').error).toBeDefined();
131
+ expect(parseKeepCount('abc').error).toBeDefined();
132
+ });
133
+ });
134
+
135
+ describe('transcriptEntries', () => {
136
+ test('digest first, then per-message entries: human→input, ai→output, full content, tool/system skipped', () => {
109
137
  const messages: BaseMessage[] = [
110
138
  new SystemMessage('sys'),
111
139
  new HumanMessage('问题甲'),
112
- new AIMessage({ content: '调用', tool_calls: [{ id: 't1', name: 'bash', args: {} }] }),
140
+ new AIMessage({ content: '', tool_calls: [{ id: 't1', name: 'bash', args: {} }] }),
113
141
  new ToolMessage({ content: 'out', tool_call_id: 't1', name: 'bash' }),
114
- new AIMessage('回答'.repeat(100)),
142
+ new AIMessage('回答'.repeat(200)),
115
143
  ];
116
- const out = renderTranscript('前情文本', messages);
117
- expect(out).toContain('前情提要');
118
- expect(out).toContain('前情文本');
119
- expect(out).toContain('你: 问题甲');
120
- expect(out).toContain('AI:');
121
- expect(out).not.toContain('工具');
122
- const longest = Math.max(...out.split('\n').map((l) => l.length));
123
- expect(longest).toBeLessThanOrEqual(140);
144
+ const entries = transcriptEntries('前情文本', messages, 3);
145
+ // digest entry
146
+ expect(entries[0]).toEqual({ input: '', output: '📝 前情提要(旧 3 轮)\n前情文本' });
147
+ const rest = entries.slice(1);
148
+ expect(rest).toHaveLength(2);
149
+ expect(rest[0]).toEqual({ input: '问题甲', output: '' });
150
+ expect(rest[1]).toEqual({ input: '', output: '回答'.repeat(200) });
124
151
  });
125
152
 
126
- test('null summary renders turns only', () => {
127
- const out = renderTranscript(null, turn(1, '正文'));
128
- expect(out).not.toContain('前情提要');
129
- expect(out).toContain('你: 问题1:正文');
130
- expect(out).toContain('AI: 回答1:正文');
153
+ test('null summary yields turn entries only, no digest', () => {
154
+ const entries = transcriptEntries(null, turn(1, '正文'));
155
+ expect(entries).toEqual([
156
+ { input: '问题1:正文', output: '' },
157
+ { input: '', output: '回答1:正文' },
158
+ ]);
131
159
  });
132
160
  });
@@ -1,8 +1,8 @@
1
1
  import { AIMessage, type BaseMessage, type MessageContent } from '@langchain/core/messages';
2
2
  import type { SessionRecord } from './store.js';
3
3
 
4
- /** Verbatim window kept on compaction; older turns get distilled. */
5
- export const KEEP_TURNS = 10;
4
+ /** Default verbatim window kept on compaction; older turns get distilled. */
5
+ export const DEFAULT_KEEP_TURNS = 1;
6
6
 
7
7
  /** Cap on the transcript fed to the distilling model (protects its context). */
8
8
  export const TRANSCRIPT_LIMIT = 40_000;
@@ -72,20 +72,33 @@ function replyText(content: unknown): string {
72
72
  return (typeof content === 'string' ? content : JSON.stringify(content)).trim();
73
73
  }
74
74
 
75
+ /**
76
+ * Validate a raw keep-turns argument: undefined → default (no opinion),
77
+ * pure digits ≥1 → {keep}, anything else → {error} so callers can show a
78
+ * usage hint and proceed with the default.
79
+ */
80
+ export function parseKeepCount(raw: string | undefined): { keep?: number; error?: string } {
81
+ if (raw === undefined) return {};
82
+ if (/^\d+$/.test(raw) && Number(raw) >= 1) return { keep: Number(raw) };
83
+ return { error: `保留轮数需为 ≥1 的整数,已按默认 ${DEFAULT_KEEP_TURNS} 轮执行` };
84
+ }
85
+
75
86
  /**
76
87
  * 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.
88
+ * record trimmed to [leading, last keepTurns turns]. At or below the window,
89
+ * or on a failed model call, returns the original record unchanged (with
90
+ * `error` set on failure) — callers fall back to a full restore.
80
91
  */
81
92
  export async function compressSession(
82
93
  record: SessionRecord,
83
94
  model: CompactModel,
95
+ keepTurns = DEFAULT_KEEP_TURNS,
84
96
  ): Promise<{ compressed: boolean; record: SessionRecord; error?: string }> {
97
+ const window = Math.max(1, keepTurns);
85
98
  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);
99
+ if (turns.length <= window) return { compressed: false, record };
100
+ const keep = turns.slice(-window);
101
+ const old = turns.slice(0, turns.length - window);
89
102
  let summary: string;
90
103
  try {
91
104
  const response = await model.invoke(buildPrompt(record.summary, old));
@@ -106,27 +119,30 @@ export async function compressSession(
106
119
  }
107
120
 
108
121
  /**
109
- * Render the resumed view: optional digest block (with the count of
110
- * compressed turns) plus the kept window as 你:/AI: lines. Tool activity and
111
- * system messages are not replayed.
122
+ * History entries for the restored view: optional digest first, then one
123
+ * entry per message — human turns as `input` (rule-framed highlight), AI
124
+ * replies as full-length `output`. Tool activity and system messages are
125
+ * not replayed. Rendering is the existing per-entry chat form.
112
126
  */
113
- export function renderTranscript(
127
+ export function transcriptEntries(
114
128
  summary: string | null,
115
129
  messages: BaseMessage[],
116
130
  oldTurnsCount?: number,
117
- ): string {
118
- const cap = (text: string): string => (text.length > 120 ? `${text.slice(0, 120)}…` : text);
119
- const lines: string[] = [];
131
+ ): { input: string; output: string }[] {
132
+ const entries: { input: string; output: string }[] = [];
120
133
  if (summary) {
121
- lines.push(`📝 前情提要${oldTurnsCount ? `(旧 ${oldTurnsCount} 轮)` : ''}`, summary, '');
134
+ entries.push({
135
+ input: '',
136
+ output: `📝 前情提要${oldTurnsCount ? `(旧 ${oldTurnsCount} 轮)` : ''}\n${summary}`,
137
+ });
122
138
  }
123
139
  for (const message of messages) {
124
140
  const kind = message.getType();
125
- if (kind === 'human') lines.push(`你: ${cap(contentText(message.content))}`);
141
+ if (kind === 'human') entries.push({ input: contentText(message.content), output: '' });
126
142
  else if (kind === 'ai') {
127
143
  const text = contentText(message.content);
128
- if (text) lines.push(`AI: ${cap(text)}`);
144
+ if (text) entries.push({ input: '', output: text });
129
145
  }
130
146
  }
131
- return lines.join('\n');
147
+ return entries;
132
148
  }
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { HumanMessage } from '@langchain/core/messages';
6
6
  import { saveSession, type SessionRecord } from './store.js';
7
- import { listProjectSessions, resolveResumeTarget } from './resume.js';
7
+ import { listProjectSessions, resolveResumeTarget, splitResumeArgs } from './resume.js';
8
8
 
9
9
  let dir: string;
10
10
  beforeEach(() => {
@@ -90,3 +90,14 @@ describe('resolveResumeTarget', () => {
90
90
  expect(resolveResumeTarget('不存在', [], list)).toBeUndefined();
91
91
  });
92
92
  });
93
+
94
+ describe('splitResumeArgs', () => {
95
+ test('second arg is keep-raw only when it is pure digits', () => {
96
+ expect(splitResumeArgs(['部署', '脚本'])).toEqual({ target: '部署 脚本' });
97
+ expect(splitResumeArgs(['3', '5'])).toEqual({ target: '3', keepRaw: '5' });
98
+ expect(splitResumeArgs(['3', '0'])).toEqual({ target: '3', keepRaw: '0' });
99
+ expect(splitResumeArgs(['3', 'abc'])).toEqual({ target: '3 abc' });
100
+ expect(splitResumeArgs(['3'])).toEqual({ target: '3' });
101
+ expect(splitResumeArgs([])).toEqual({ target: '' });
102
+ });
103
+ });
@@ -5,6 +5,19 @@ export function listProjectSessions(cwd: string): SessionRecord[] {
5
5
  return listSessions().filter((session) => session.cwd === cwd);
6
6
  }
7
7
 
8
+ /**
9
+ * Split /resume args: the second token is a keep-turns attempt ONLY when it
10
+ * is pure digits; otherwise all tokens join into the target (multi-word
11
+ * title fragments keep working).
12
+ */
13
+ export function splitResumeArgs(args: string[]): { target: string; keepRaw?: string } {
14
+ const hasKeepArg = args.length > 1 && /^\d+$/.test(args[1]!);
15
+ return {
16
+ target: (hasKeepArg ? args[0] : args.join(' ')).trim(),
17
+ ...(hasKeepArg ? { keepRaw: args[1] } : {}),
18
+ };
19
+ }
20
+
8
21
  /**
9
22
  * Resolve a /resume argument to a session record.
10
23
  * Blank target → undefined (caller opens the picker). Numeric → the last
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.0';
2
+ export const VERSION = '0.8.2';