@waq666/pneuma 0.8.0 → 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.
Files changed (84) hide show
  1. package/README.md +10 -5
  2. package/lib/adapter/transcript.js +12 -1
  3. package/lib/app/Composer.js +14 -2
  4. package/lib/contract/plugin.d.ts +8 -0
  5. package/lib/contract/session.d.ts +8 -0
  6. package/lib/contract/snapshot.d.ts +5 -0
  7. package/lib/core/agent-roles.js +3 -2
  8. package/lib/core/commands-completion.d.ts +17 -0
  9. package/lib/core/commands-completion.js +56 -3
  10. package/lib/core/compact.d.ts +36 -6
  11. package/lib/core/compact.js +89 -17
  12. package/lib/core/events.d.ts +5 -0
  13. package/lib/core/git-info.d.ts +127 -15
  14. package/lib/core/git-info.js +307 -32
  15. package/lib/core/host-methods.d.ts +1 -1
  16. package/lib/core/host-methods.js +1 -0
  17. package/lib/core/llm.d.ts +9 -0
  18. package/lib/core/llm.js +1 -0
  19. package/lib/core/loop.js +8 -2
  20. package/lib/core/permission-scope.d.ts +12 -1
  21. package/lib/core/permission-scope.js +26 -1
  22. package/lib/core/presets.js +30 -2
  23. package/lib/core/session.d.ts +48 -7
  24. package/lib/core/session.js +263 -9
  25. package/lib/core/ui-methods.d.ts +1 -1
  26. package/lib/core/ui-methods.js +6 -0
  27. package/lib/plugins/agent.js +47 -6
  28. package/lib/plugins/commands.js +118 -14
  29. package/lib/plugins/compact.d.ts +2 -2
  30. package/lib/plugins/compact.js +150 -22
  31. package/lib/plugins/git.js +15 -1
  32. package/lib/plugins/goal.js +8 -4
  33. package/lib/plugins/host-stdio.js +11 -1
  34. package/lib/plugins/microcompact.d.ts +3 -0
  35. package/lib/plugins/microcompact.js +26 -0
  36. package/lib/plugins/remote.js +7 -1
  37. package/lib/plugins/runtime.js +5 -0
  38. package/lib/plugins/session.js +81 -7
  39. package/lib/plugins/skills.js +16 -0
  40. package/lib/plugins/subagent.js +47 -11
  41. package/lib/services/types.d.ts +66 -8
  42. package/lib/ui/assets/{app-MhfBFsp-.js → app-B-Jx5dnh.js} +60 -59
  43. package/lib/ui/assets/{chunk-Cq7xGE-D.js → chunk-Bfdlo8Me.js} +1 -1
  44. package/lib/ui/assets/{chunk-CA5f1pGf.js → chunk-DGX-i4eb.js} +1 -1
  45. package/lib/ui/assets/index.html +2 -2
  46. package/lib/ui/assets/style-WzxwEPaE.css +1 -0
  47. package/lib/ui/plugins/actions/bundle.json +2 -2
  48. package/lib/ui/plugins/ask/bundle.json +2 -2
  49. package/lib/ui/plugins/browser/bundle.json +2 -2
  50. package/lib/ui/plugins/composer/bundle.json +2 -2
  51. package/lib/ui/plugins/composer/client.js +57 -4
  52. package/lib/ui/plugins/files/bundle.json +2 -2
  53. package/lib/ui/plugins/manifest.json +1 -1
  54. package/lib/ui/plugins/palette/bundle.json +2 -2
  55. package/lib/ui/plugins/plugins/bundle.json +2 -2
  56. package/lib/ui/plugins/preview/bundle.json +2 -2
  57. package/lib/ui/plugins/prompt/bundle.json +2 -2
  58. package/lib/ui/plugins/sessions/bundle.json +2 -2
  59. package/lib/ui/plugins/sessions/client.js +41 -13
  60. package/lib/ui/plugins/settings/bundle.json +2 -2
  61. package/lib/ui/plugins/skills/bundle.json +2 -2
  62. package/lib/ui/plugins/status/bundle.json +2 -2
  63. package/lib/ui/plugins/status/client.js +162 -9
  64. package/lib/ui/plugins/statusbar/bundle.json +2 -2
  65. package/lib/ui/plugins/tasks/bundle.json +2 -2
  66. package/lib/ui/plugins/team/bundle.json +2 -2
  67. package/lib/ui/plugins/terminal/bundle.json +2 -2
  68. package/lib/ui/plugins/trace/bundle.json +2 -2
  69. package/lib/ui/plugins/transcript/bundle.json +2 -2
  70. package/lib/ui/plugins/transcript/client.js +156 -96
  71. package/lib/ui/sdk/@dsc/ui/package.json +1 -1
  72. package/lib/ui/sdk/@dsc/ui-core/package.json +1 -1
  73. package/lib/ui/sdk/@dsc/ui-dockkit/package.json +1 -1
  74. package/lib/ui/sdk/@dsc/ui-layout/package.json +1 -1
  75. package/lib/ui/sdk/@dsc/ui-primitives/icons.d.ts +13 -2
  76. package/lib/ui/sdk/@dsc/ui-primitives/image-lightbox.d.ts +21 -0
  77. package/lib/ui/sdk/@dsc/ui-primitives/index.d.ts +3 -0
  78. package/lib/ui/sdk/@dsc/ui-primitives/package.json +1 -1
  79. package/lib/ui/sdk/@dsc/ui-primitives/review-findings-card.d.ts +25 -0
  80. package/lib/ui/sdk/@dsc/ui-primitives/review-findings.d.ts +64 -0
  81. package/lib/ui/sdk/@dsc/ui-renderer/package.json +1 -1
  82. package/lib/ui/sdk/@dsc/ui-slots/package.json +1 -1
  83. package/package.json +1 -1
  84. package/lib/ui/assets/style-CIJVQKkj.css +0 -1
@@ -20,6 +20,7 @@ export const UI_METHODS = [
20
20
  'setSessionPinned',
21
21
  'listUserMessages',
22
22
  'forkSession',
23
+ 'rewindSession',
23
24
  'listArchivedSessions',
24
25
  'usageStats',
25
26
  // 旁问(只读一次性问答):不建会话、不落盘、不带工具,见 core/side-ask.ts。
@@ -178,6 +179,11 @@ export const UI_ARG_SPECS = {
178
179
  setSessionPinned: [{ shape: { kind: 'string', max: MAX_PATH } }, { shape: { kind: 'boolean' } }],
179
180
  listUserMessages: [{ shape: { kind: 'string', max: MAX_PATH } }],
180
181
  forkSession: [{ shape: { kind: 'string', max: MAX_PATH } }, { shape: { kind: 'number' } }],
182
+ rewindSession: [
183
+ { shape: { kind: 'string', max: MAX_PATH } },
184
+ { shape: { kind: 'number' } },
185
+ { shape: { kind: 'string', max: MAX_NAME }, optional: true },
186
+ ],
181
187
  listArchivedSessions: [],
182
188
  usageStats: [],
183
189
  // 旁问:问题 + 可选引用 + 取消票据。上限与 core/side-ask.ts 的常量对齐(那边截断引用、
@@ -38,6 +38,11 @@ function noteSystemPrompt(session, text) {
38
38
  return;
39
39
  session.appendState('system-prompt', { hash, text });
40
40
  }
41
+ /**
42
+ * 切走之后最多留几个空闲会话(见 {@link rememberIdle})。
43
+ * 3 够覆盖「在最近三条之间来回跳」,再多只是白占内存。
44
+ */
45
+ const IDLE_KEEP = 3;
41
46
  export const agentPlugin = {
42
47
  name: 'agent',
43
48
  inject: ['session', 'transcript', 'tools', 'llm', 'compact', 'prompt', 'guards'],
@@ -45,6 +50,8 @@ export const agentPlugin = {
45
50
  apply(ctx) {
46
51
  /** 常驻注册表:会话 id(meta.id)→ agent。含当前查看的那个。 */
47
52
  const agents = new Map();
53
+ /** 切走但还留着的空闲会话(按「最近切走的」排在后面),上限见 {@link IDLE_KEEP}。 */
54
+ const idleOrder = [];
48
55
  /** 收摊 agent 的墓碑:id → jsonl 路径。非常驻投递(followup 带 id)靠它找文件。 */
49
56
  const tombstones = new Map();
50
57
  /** 当前查看的 agent。不变量:它的会话就是 ctx.session.current() 那个对象。 */
@@ -159,27 +166,55 @@ export const agentPlugin = {
159
166
  stream: (api, request, handlers) => ctx.llm.stream(api, request, handlers),
160
167
  // 完全闲下来又不是当前查看的:就地收摊(释放写租约与内存)。正被查看的
161
168
  // 留着——用户下一句话还得靠它。
169
+ //
170
+ // 收摊统一走 disposeAgent(2026-11-03):它同时清「空闲保留」名册(idleOrder),
171
+ // 这里要是自己删一遍,名册里就会留下已经收摊的 id。
162
172
  onIdle: () => {
163
173
  if (active !== null && active.sessionId === session.meta.id)
164
174
  return;
165
175
  const agent = agents.get(session.meta.id);
166
176
  if (agent === undefined)
167
177
  return;
168
- agents.delete(session.meta.id);
169
- tombstones.set(session.meta.id, session.filePath);
170
- // 「先读过才许改」的台账跟着会话走,收摊时一起清,防长窗口无界增长
171
- clearReadLedger(session.meta.id);
172
- agent.dispose();
178
+ disposeAgent(agent);
173
179
  },
174
180
  }, session);
175
181
  };
176
182
  const disposeAgent = (agent) => {
177
183
  agents.delete(agent.sessionId);
184
+ const idleAt = idleOrder.indexOf(agent.sessionId);
185
+ if (idleAt >= 0)
186
+ idleOrder.splice(idleAt, 1);
178
187
  tombstones.set(agent.sessionId, agent.session.filePath);
179
188
  // 「先读过才许改」的台账跟着会话走,收摊时一起清,防长窗口无界增长
180
189
  clearReadLedger(agent.sessionId);
181
190
  agent.dispose();
182
191
  };
192
+ /**
193
+ * 切走之后**先不收摊**,把空闲 agent 留下几个(0.6.48 常驻多 agent 的延伸,2026-11-03)。
194
+ *
195
+ * 为什么:切会话的耗时里最大的一块是重新把整份 jsonl 读回来解析(实测 6.8MB 的会话
196
+ * 45–65ms,同步跑在宿主主线程上)。而人在几条会话之间来回跳是常态——刚切走又切回来,
197
+ * 那时磁盘上的文件一个字都没变,重读纯属白烧。留下最近几个,切回去直接命中
198
+ * `sessionFor`(`plugins/session.ts` 的 open 里那条短路),一次读盘都不用。
199
+ *
200
+ * 为什么是 3:配合 `IDLE_KEEP` 的数量,内存里最多三份已解析的历史(每份几 MB),
201
+ * 换来「来回跳」全部零加载;再多就只是白占内存。
202
+ *
203
+ * 与「常驻」不冲突:这里留下的都是**空闲**的(跑着的走上面 busy 那条分支,本来就不收摊),
204
+ * 也就是说不会有一轮在跑、却因为被人切走而被打断或错位。
205
+ */
206
+ const rememberIdle = (sessionId) => {
207
+ const at = idleOrder.indexOf(sessionId);
208
+ if (at >= 0)
209
+ idleOrder.splice(at, 1);
210
+ idleOrder.push(sessionId);
211
+ while (idleOrder.length > IDLE_KEEP) {
212
+ const oldest = idleOrder.shift();
213
+ const agent = oldest === undefined ? undefined : agents.get(oldest);
214
+ if (agent !== undefined)
215
+ disposeAgent(agent);
216
+ }
217
+ };
183
218
  // ---- 初始 agent:内核启动恢复/新建的那个会话 ----
184
219
  active = makeAgent(ctx.session.current());
185
220
  agents.set(active.sessionId, active);
@@ -190,6 +225,12 @@ export const agentPlugin = {
190
225
  next = makeAgent(session);
191
226
  agents.set(session.meta.id, next);
192
227
  }
228
+ else {
229
+ // 又切回来了一条还留着的会话:把它从「空闲待收摊」里摘出来(它就是现在这条)。
230
+ const idleAt = idleOrder.indexOf(session.meta.id);
231
+ if (idleAt >= 0)
232
+ idleOrder.splice(idleAt, 1);
233
+ }
193
234
  active = next;
194
235
  if (prev !== null && prev !== next) {
195
236
  if (prev.busy) {
@@ -206,7 +247,7 @@ export const agentPlugin = {
206
247
  });
207
248
  }
208
249
  else {
209
- disposeAgent(prev);
250
+ rememberIdle(prev.sessionId);
210
251
  }
211
252
  }
212
253
  });
@@ -11,7 +11,7 @@
11
11
  import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
12
12
  import { spawn } from 'node:child_process';
13
13
  import { dirname, join } from 'node:path';
14
- import { collectWorkingTree, reviewMessage } from '../core/git-info.js';
14
+ import { collectReviewScope, listReviewBranches, listReviewCommits, reviewStatusText, reviewTaskText, } from '../core/git-info.js';
15
15
  import { estimateTokens } from '../core/compact.js';
16
16
  import { exportSessionMarkdown } from '../core/session-export.js';
17
17
  import { checkForUpdate } from '../core/update-check.js';
@@ -154,38 +154,142 @@ export const commandsPlugin = {
154
154
  }
155
155
  ui.notice(`已导出 ${session.messages.length} 条消息 → ${target}`);
156
156
  });
157
+ // ── /review:先选范围,再派只读审查队友(T45)────────────────────────────
158
+ //
159
+ // 范围分四档,与 codex /review 同口径:不传参数就先问「审什么」——diff 从哪来
160
+ // 决定了这次审查在看什么,默认只审未提交改动会让「分支相对 main 改了什么」
161
+ // 这种最常见的诉求每次都得自己先跑 git diff 再贴过来。
162
+ // 传了参数(`/review 只看安全`)就按未提交改动审,那句话是关注点。
163
+ /** 范围卡的四个选项(顺序即展示顺序)。 */
164
+ const REVIEW_SCOPE_OPTIONS = [
165
+ { label: '对比基准分支', description: '从共同祖先审查当前分支的更改' },
166
+ { label: '审查未提交的更改', description: '暂存、未暂存与未跟踪的净改动' },
167
+ { label: '审查某次提交', description: '挑一个提交看它改了什么' },
168
+ { label: '自定义审查要求', description: '写一段要求,按它审当前改动' },
169
+ ];
170
+ /** 界面在用户点「跳过」时交回的原文(`answerOf` 的口径);与空串一样算没答。 */
171
+ const SKIPPED_ANSWER = '(用户跳过了这一题)';
172
+ /**
173
+ * 弹一张卡问一句,返回答案原文(空串 = 没答 / 跳过 / 没有提问通道)。
174
+ *
175
+ * 为什么这里的信号是自己 new 的:斜杠命令这条路口**没有回合取消信号**(它不是模型
176
+ * 发起的那一轮工具调用),所以卡只能由用户自己答完或跳过。这个控制器因此不会主动
177
+ * abort,只是为了满足 ask 的契约参数。
178
+ */
179
+ const askInCard = async (ask, question, signal) => {
180
+ const answer = await ask.ask({
181
+ question: question.question,
182
+ header: '代码审查',
183
+ options: question.options,
184
+ multiSelect: false,
185
+ allowFreeText: true,
186
+ }, signal);
187
+ const text = answer.trim();
188
+ return text === SKIPPED_ANSWER ? '' : text;
189
+ };
190
+ /**
191
+ * 问出这次要审的范围;用户取消或空答返回 null(调用方收口成「审查已取消」)。
192
+ *
193
+ * 在范围卡上直接写自由文本时按「自定义审查要求」理解:用户写了话就是有要求,
194
+ * 再追问一遍「你要什么要求」是废话。
195
+ */
196
+ const pickReviewTarget = async (cwd, ask, signal) => {
197
+ const choice = await askInCard(ask, { question: '选择审查范围', options: REVIEW_SCOPE_OPTIONS }, signal);
198
+ if (choice === '')
199
+ return null;
200
+ if (choice === '审查未提交的更改')
201
+ return { kind: 'worktree' };
202
+ if (choice === '自定义审查要求') {
203
+ const instructions = await askInCard(ask, { question: '写一段审查要求,按它审当前的未提交改动', options: [] }, signal);
204
+ return instructions === '' ? null : { kind: 'custom', instructions };
205
+ }
206
+ if (choice === '对比基准分支') {
207
+ const branches = await listReviewBranches(cwd);
208
+ const ref = await askInCard(ask, { question: '选择基准分支,也可以直接填写分支名或引用', options: branches.map((branch) => ({ label: branch })) }, signal);
209
+ return ref === '' ? null : { kind: 'base', ref };
210
+ }
211
+ if (choice === '审查某次提交') {
212
+ const commits = await listReviewCommits(cwd);
213
+ const labels = commits.map((commit) => `${commit.sha.slice(0, 10)} ${commit.subject}`.trim());
214
+ const answer = await askInCard(ask, { question: '选择提交,也可以直接填写提交 SHA', options: labels.map((label) => ({ label })) }, signal);
215
+ if (answer === '')
216
+ return null;
217
+ const at = labels.indexOf(answer);
218
+ const picked = at < 0 ? undefined : commits[at];
219
+ // 手填的 SHA 认不出来也照样交给 git:它自己会报「找不到这个引用」
220
+ return picked === undefined
221
+ ? { kind: 'commit', ref: answer }
222
+ : { kind: 'commit', ref: picked.sha, ...(picked.subject === '' ? {} : { title: picked.subject }) };
223
+ }
224
+ // 认不出的答案就是用户在卡上直接写的要求
225
+ return { kind: 'custom', instructions: choice };
226
+ };
157
227
  service.register(builtinSpec('review'), ({ args, runtime, ui }) => {
158
- const cwd = ctx.session.current().meta.cwd;
228
+ const session = ctx.session.current();
229
+ const cwd = session.meta.cwd;
159
230
  const focus = args.join(' ').trim();
160
- void collectWorkingTree(cwd)
161
- .then((collected) => {
162
- if (collected === null) {
231
+ // 本命令自己的信号(见 askInCard 的说明):命令这条路口没有回合取消信号。
232
+ const signal = new AbortController().signal;
233
+ void (async () => {
234
+ const ask = ctx.get('ask');
235
+ let target;
236
+ if (focus !== '') {
237
+ // 有参数 = 审未提交改动,那句话是关注点(不再弹卡,按回车就开跑)
238
+ target = { kind: 'worktree' };
239
+ }
240
+ else if (ask === undefined) {
241
+ // 没有提问通道(ask 插件关着):退回默认口径,别让命令整个不可用
242
+ ui.notice('这个会话没有提问卡通道,/review 按未提交改动审。');
243
+ target = { kind: 'worktree' };
244
+ }
245
+ else {
246
+ target = await pickReviewTarget(cwd, ask, signal);
247
+ }
248
+ if (target === null) {
249
+ ui.notice('审查已取消。');
250
+ return;
251
+ }
252
+ const scope = await collectReviewScope(cwd, target, session.meta.id);
253
+ if (scope === null) {
163
254
  ui.notice('这里不是 git 仓库,/review 没有可审查的改动。');
164
255
  return;
165
256
  }
166
- if (collected.diff === '' && collected.untracked.length === 0) {
167
- ui.notice('工作区没有未提交的改动。');
257
+ if (scope.diffBytes === 0 && scope.untracked.length === 0) {
258
+ ui.notice(`这个范围里没有可审查的改动(${scope.label})。`);
168
259
  return;
169
260
  }
261
+ // 自定义要求已经写进 scope.target,不再算一次「关注点」(否则任务书里会出现两遍)
262
+ const effectiveFocus = target.kind === 'custom' ? '' : focus;
170
263
  // T18:subagent 插件开着就走只读审查队友——后台审,findings 直接出卡片,
171
- // 不占用当前会话的模型轮;插件没开(或额度满)回落 v1 的主会话审查轮。
264
+ // 不占用当前会话的模型轮;插件没开(或额度满)回落主会话审查轮。
172
265
  const review = ctx.get('review');
173
266
  if (review !== undefined) {
174
- const spawned = review.spawn({ ...collected, focus });
267
+ const spawned = review.spawn({ scope, focus: effectiveFocus });
175
268
  if (spawned.ok) {
176
- ui.notice(`已派出只读审查队友 ${spawned.name},结论出来后直接出现在会话里`);
269
+ ui.notice(`已派出只读审查队友 ${spawned.name}(范围:${scope.label}),结论出来后直接出现在会话里;/review-status 看状态,/review-cancel 取消`);
177
270
  return;
178
271
  }
179
272
  ui.notice(`/review 没派出审查队友(${spawned.reason}),改在本会话里审`);
180
273
  }
181
274
  // 组装一条审查请求走正常对话轮(runtime.submit → agent.followup):
182
275
  // 回复就是审查意见,与用户自己贴着 diff 问「帮我看看」同一条链路。
183
- runtime.submit(reviewMessage(collected, focus));
184
- })
185
- .catch((cause) => {
186
- ui.notice(`/review 失败:${cause instanceof Error ? cause.message : String(cause)}`);
276
+ runtime.submit(reviewTaskText(scope, effectiveFocus));
277
+ })().catch((cause) => {
278
+ ui.notice(`/review 失败:${errText(cause)}`);
187
279
  });
188
280
  });
281
+ service.register(builtinSpec('review-status'), ({ ui }) => {
282
+ // 审查通道不存在(subagent 插件关着)时就是「没有记录」,与没跑过审查同一种回答
283
+ ui.notice(reviewStatusText(ctx.get('review')?.status() ?? null));
284
+ });
285
+ service.register(builtinSpec('review-cancel'), ({ ui }) => {
286
+ const review = ctx.get('review');
287
+ if (review === undefined) {
288
+ ui.notice('审查通道没开着(subagent 插件关着),当前没有在跑的审查。');
289
+ return;
290
+ }
291
+ ui.notice(review.cancel() ? '已取消这次审查。' : '当前没有在跑的审查。');
292
+ });
189
293
  service.register(builtinSpec('diff'), ({ args, runtime, ui }) => {
190
294
  const file = args[0];
191
295
  void runtime
@@ -11,8 +11,8 @@
11
11
  * 摘要调用复用主对话前缀(2026-10-03):系统提示词取自 prompt 服务、工具目录取自 tools 服务,
12
12
  * 摘要请求因此是上一次真实请求的前缀扩展,命中服务端 KV 缓存(见 core/compact.ts 的 context 参数)。
13
13
  *
14
- * 六个可调值(保留条数、自动压缩触发线、锚点索引字符预算、用户原话字符预算、
15
- * read-state 文件数、read-state 字符预算)读自己的插件配置,
14
+ * 九个可调值(保留条数、保留尾部的窗口占比、自动压缩触发线、安全余量、压一次不够时最多再压几次、
15
+ * 锚点索引字符预算、用户原话字符预算、read-state 文件数、read-state 字符预算)读自己的插件配置,
16
16
  * 并以设置分区的面目交给界面;保存后本插件立刻重读,下一次压缩就用新值。
17
17
  *
18
18
  * @module dsc/plugins/compact
@@ -10,6 +10,9 @@ const CONFIG_KEY = 'compact';
10
10
  const DEFAULTS = {
11
11
  keepRecent: DEFAULT_KEEP_RECENT,
12
12
  autoCompactPercent: 80,
13
+ headroomTokens: 0,
14
+ compactionRetries: 1,
15
+ retainPercent: 16,
13
16
  anchorBudgetChars: DEFAULT_ANCHOR_BUDGET_CHARS,
14
17
  userQuoteBudgetChars: DEFAULT_USER_QUOTE_BUDGET_CHARS,
15
18
  readStateFiles: DEFAULT_READ_STATE_FILES,
@@ -22,6 +25,19 @@ const USER_QUOTE_BUDGET_RANGE = { min: 1000, max: 40000 };
22
25
  const READ_STATE_FILES_RANGE = { min: 0, max: 20 };
23
26
  /** read-state 字符预算的区间(默认 1500,压得很紧)。 */
24
27
  const READ_STATE_BUDGET_RANGE = { min: 200, max: 10000 };
28
+ /**
29
+ * 安全余量的区间:0 = 自动(窗口的 6.4%,封顶 65536)。
30
+ * 上限给到 131072:再大的窗口配再大的余量也够用了,填得比窗口还大等于永远触发压缩。
31
+ */
32
+ const HEADROOM_RANGE = { min: 0, max: 131072 };
33
+ /** 补压次数的区间:0 = 只压一次(手动 `/compact` 就是这条口径),最多补 3 次。 */
34
+ const COMPACTION_RETRIES_RANGE = { min: 0, max: 3 };
35
+ /**
36
+ * 尾部保留占比的区间(百分比)。
37
+ * 低于 5% 等于几乎不留给下一个自己;高于 40% 时压完留下的比折掉的还多,压缩没意义。
38
+ * 缺省 16%:dsh 的 retainRatio 就是这个数(按它那边 1M 窗口留约 16 万 token)。
39
+ */
40
+ const RETAIN_PERCENT_RANGE = { min: 5, max: 40 };
25
41
  /**
26
42
  * 从插件配置取这些可调值,并把区间外的值夹回来。
27
43
  * @param passed - 装配时传进来的配置(内核挂载时的第二参数);没给就读磁盘。
@@ -33,6 +49,9 @@ function readConfig(passed) {
33
49
  keepRecent: clamp(raw.keepRecent, 5, 200, DEFAULTS.keepRecent),
34
50
  // 低于 50% 会在干活时频繁打断,高于 95% 等于等模型报错才压。
35
51
  autoCompactPercent: clamp(raw.autoCompactPercent, 50, 95, DEFAULTS.autoCompactPercent),
52
+ headroomTokens: clamp(raw.headroomTokens, HEADROOM_RANGE.min, HEADROOM_RANGE.max, DEFAULTS.headroomTokens),
53
+ compactionRetries: clamp(raw.compactionRetries, COMPACTION_RETRIES_RANGE.min, COMPACTION_RETRIES_RANGE.max, DEFAULTS.compactionRetries),
54
+ retainPercent: clamp(raw.retainPercent, RETAIN_PERCENT_RANGE.min, RETAIN_PERCENT_RANGE.max, DEFAULTS.retainPercent),
36
55
  anchorBudgetChars: clamp(raw.anchorBudgetChars, ANCHOR_BUDGET_RANGE.min, ANCHOR_BUDGET_RANGE.max, DEFAULTS.anchorBudgetChars),
37
56
  userQuoteBudgetChars: clamp(raw.userQuoteBudgetChars, USER_QUOTE_BUDGET_RANGE.min, USER_QUOTE_BUDGET_RANGE.max, DEFAULTS.userQuoteBudgetChars),
38
57
  readStateFiles: clamp(raw.readStateFiles, READ_STATE_FILES_RANGE.min, READ_STATE_FILES_RANGE.max, DEFAULTS.readStateFiles),
@@ -52,14 +71,30 @@ export const compactPlugin = {
52
71
  writePluginConfig(CONFIG_KEY, patch);
53
72
  config = readConfig();
54
73
  };
55
- /** 当前配置里的压缩上限,现读 config,保存后下一压就用新值。 */
56
- const limits = () => ({
57
- keepRecent: config.keepRecent,
58
- anchorChars: config.anchorBudgetChars,
59
- userQuoteChars: config.userQuoteBudgetChars,
60
- readStateFiles: config.readStateFiles,
61
- readStateChars: config.readStateChars,
62
- });
74
+ /**
75
+ * 当前配置里的压缩上限,现读 config,保存后下一压就用新值。
76
+ *
77
+ * 需要目标会话:尾部 token 预算按**这条会话**的模型窗口折算(后台会话按它自己的路由,
78
+ * 不看用户正在看的那条)。窗口拿不到时退回纯条数口径,不猜一个数。
79
+ *
80
+ * @param target - 要压的会话
81
+ * @param retain - 是否按窗口占比留尾巴。自动阈值压缩留(省下的空间还得放得下这一轮),
82
+ * 手动 `/compact` 与爆窗强压**不留**:这两条路的目的是尽快腾出空间,只保留条数下限。
83
+ * 不留这一档不是省事:100 万窗口的模型上,16% 的尾巴就是 16 万 token,短历史手动压
84
+ * 会因为「尾巴装得下整段」直接判成没得压——用户看到的是一句「历史不长,无需压缩」。
85
+ */
86
+ const limits = (target, retain = true) => {
87
+ const window = ctx.llm.contextWindowOf(target);
88
+ const retainTokens = retain ? Math.floor(window * (config.retainPercent / 100)) : 0;
89
+ return {
90
+ keepRecent: config.keepRecent,
91
+ ...(retainTokens > 0 ? { retainTokens } : {}),
92
+ anchorChars: config.anchorBudgetChars,
93
+ userQuoteChars: config.userQuoteBudgetChars,
94
+ readStateFiles: config.readStateFiles,
95
+ readStateChars: config.readStateChars,
96
+ };
97
+ };
63
98
  /** T19 前置裁剪口径:spill 配置复用 spill 插件的那份(目录与上限一致,模型可照常 read)。 */
64
99
  const prune = () => ({
65
100
  ...DEFAULT_PRUNE_OPTIONS,
@@ -137,6 +172,28 @@ export const compactPlugin = {
137
172
  else
138
173
  runningTurnsBySid.set(sid, count - 1);
139
174
  });
175
+ /**
176
+ * 自动压缩的触发阈值(token)。
177
+ *
178
+ * 口径对齐 dsh:阈值 = min(窗口 × 触发比例, 窗口 − 输出预留 − 安全余量)。
179
+ * 为什么要减输出预留与安全余量:一次请求最多吐 maxTokens,这部分窗口不能拿去装历史;
180
+ * 余量留给「系统提示词 + 工具目录 + 本轮新增消息」的浮动空间,压到贴边的话
181
+ * 下一轮请求立刻又超。
182
+ * 余量为什么按窗口 6.4% 算并封顶 65536:dsh 那里是写死的 65536(按 1M 窗口设计),
183
+ * 照搬到 128k 窗口的模型上,阈值会掉到窗口的一半以下(131072 − 8192 输出 − 65536
184
+ * 只剩 57344,约 44%),活干到一半就被压一次。按窗口缩放才跟着窗口走。
185
+ *
186
+ * @param target - 要判定的会话(阈值跟这个会话的模型路由走,不看「当前查看的会话」)。
187
+ */
188
+ const thresholdOf = (target) => {
189
+ const window = ctx.llm.contextWindowOf(target);
190
+ const reserve = ctx.llm.routeForSession(target).maxTokens ?? 0;
191
+ const headroom = config.headroomTokens > 0 ? config.headroomTokens : Math.min(65_536, Math.floor(window * 0.064));
192
+ const byRatio = Math.floor(window * (config.autoCompactPercent / 100));
193
+ // 下限 1024:窗口配得很小、或 maxTokens 接近窗口时,阈值不能变成 0 甚至负数,
194
+ // 否则每次请求都判成「超了」,压缩会连着空转(每次都是 noop)。
195
+ return Math.max(1024, Math.min(byRatio, window - reserve - headroom));
196
+ };
140
197
  const service = {
141
198
  registerCarry(contribute) {
142
199
  carries.push(contribute);
@@ -146,28 +203,63 @@ export const compactPlugin = {
146
203
  carries.splice(at, 1);
147
204
  };
148
205
  },
149
- /** 当前模型路由 + 配置里的自动压缩触发线(缺省 contextWindow 的 80%)。 */
206
+ /** 当前模型路由 + 配置里的自动压缩触发线(缺省 min(窗口的 80%, 窗口 − 输出预留 − 余量))。 */
150
207
  async check(signal, target) {
151
208
  const session = target ?? ctx.session.current();
152
- const threshold = ctx.llm.contextWindowOf(session) * (config.autoCompactPercent / 100);
153
- if (estimateTokens(session.messages) <= threshold)
209
+ const threshold = thresholdOf(session);
210
+ let used = estimateTokens(session.messages);
211
+ if (used <= threshold)
154
212
  return;
155
- const outcome = await whileCompacting(session, () => compactSession(session, ctx.llm.routeForSession(session), stream, signal ?? new AbortController().signal, carry(), limits(), undefined, prune(), requestContext(session)));
156
- const compacted = outcome === 'compacted';
213
+ // 压完复量、还超就再压(对齐 dsh 的 compactionRetries):一次压缩的收缩率
214
+ // 跟摘要模型当时的输出质量有关,偶尔一次压不到线以下;补压一两次比直接放弃好。
215
+ // 手动 /compact 与 forceCompact 不循环——手动只压一次,爆窗重试也只看这一次的成败。
216
+ //
217
+ // 补压这一刀必须绕开「历史太短」守卫(force):第一次压完只剩摘要 + 条数下限那几条,
218
+ // 正常判定会认为没得压、直接 noop,可恰恰是「尾巴本身就超预算」才需要再压。
219
+ // 带 force 之后能折进上一份摘要本身,尾部按 token 预算重新收紧——这才是补压的意义。
220
+ let attempts = 0;
221
+ for (let attempt = 0; attempt <= config.compactionRetries; attempt += 1) {
222
+ const result = await whileCompacting(session, () => compactSession(session, ctx.llm.routeForSession(session), stream, signal ?? new AbortController().signal, carry(), limits(session), attempt > 0 ? true : undefined, prune(), requestContext(session)));
223
+ // 一轮都没压成(历史太短 / 整段都是工具结果)就别再试:再压还是同一个结果
224
+ if (result.outcome !== 'compacted')
225
+ break;
226
+ attempts += 1;
227
+ // 复量按新历史算:摘要 + 尾巴的实际估算(dsh 在同一处也用 token 计量器重量)
228
+ used = estimateTokens(session.messages);
229
+ if (used <= threshold)
230
+ break;
231
+ }
232
+ const compacted = attempts > 0;
157
233
  // 只有真压出结果才打压缩标记:noop 时这条提示照旧发(文案不动),
158
234
  // 但轨迹页不该凭空多出一段「压缩历史」
159
235
  // 带会话归属(0.6.68):后台会话自动压缩时,这句提示不该冒到用户正在看的视图里。
160
- ctx.emit('dsc/notice', '上下文接近模型上限,已自动压缩历史', compacted ? 'compaction' : undefined, session.filePath);
161
- if (compacted) {
162
- ctx.emit('dsc/compacted');
163
- reportContextUsed(session);
236
+ if (!compacted) {
237
+ ctx.emit('dsc/notice', '上下文接近模型上限,已自动压缩历史', undefined, session.filePath);
238
+ return;
239
+ }
240
+ if (used <= threshold) {
241
+ ctx.emit('dsc/notice', '上下文接近模型上限,已自动压缩历史', 'compaction', session.filePath);
242
+ }
243
+ else {
244
+ // 补压用完仍在阈值之上:说清「还超多少、压了几次」,用户才知道该不该手动收紧口径
245
+ ctx.emit('dsc/notice', `上下文仍接近模型上限(估算 ${used} tokens ≥ 阈值 ${threshold}),已连续压缩 ${attempts} 次`, 'compaction', session.filePath);
164
246
  }
247
+ ctx.emit('dsc/compacted');
248
+ reportContextUsed(session);
165
249
  },
166
250
  /** 请求已经因爆窗失败,强制压一次(2026-09-29):压出空间返回 true,循环方重试请求。 */
167
251
  async forceCompact(signal, target) {
168
252
  const session = target ?? ctx.session.current();
169
- const outcome = await whileCompacting(session, () => compactSession(session, ctx.llm.routeForSession(session), stream, signal ?? new AbortController().signal, carry(), limits(), true, prune(), requestContext(session)));
170
- if (outcome === 'compacted') {
253
+ // 先看微压缩(2026-11-02):旧工具结果换成占位符是**投影**,不落历史,
254
+ // 此时真正发出去的请求本来就是清理过的。若清理后已经装进窗口,就没必要
255
+ // 牺牲历史去压摘要——白白丢掉原文,还可能把工具配对切坏。直接让调用方重试。
256
+ const micro = ctx.get('microcompact');
257
+ if (micro !== undefined && micro.projectedTokens(session.messages) < ctx.llm.contextWindowOf(session)) {
258
+ ctx.emit('dsc/notice', '上下文超出模型窗口,但旧工具结果清理后已在窗口内,直接重试', undefined, session.filePath);
259
+ return false;
260
+ }
261
+ const result = await whileCompacting(session, () => compactSession(session, ctx.llm.routeForSession(session), stream, signal ?? new AbortController().signal, carry(), limits(session, false), true, prune(), requestContext(session)));
262
+ if (result.outcome === 'compacted') {
171
263
  // 打上 'compaction' 类别:transcript 据此把这条通知标成压缩落点(轨迹页切区段)
172
264
  ctx.emit('dsc/notice', '上下文超出模型窗口:已自动压缩历史并重试', 'compaction', session.filePath);
173
265
  ctx.emit('dsc/compacted');
@@ -191,8 +283,8 @@ export const compactPlugin = {
191
283
  }
192
284
  try {
193
285
  const target = ctx.session.current();
194
- const outcome = await whileCompacting(target, () => compactSession(target, ctx.llm.routeForSession(target), stream, new AbortController().signal, carry(), limits(), undefined, prune(), requestContext(target)));
195
- const compacted = outcome === 'compacted';
286
+ const result = await whileCompacting(target, () => compactSession(target, ctx.llm.routeForSession(target), stream, new AbortController().signal, carry(), limits(target, false), undefined, prune(), requestContext(target)));
287
+ const compacted = result.outcome === 'compacted';
196
288
  ctx.emit('dsc/notice', compacted ? '上下文已压缩(任务清单与目标原样保留)' : '历史不长,无需压缩', compacted ? 'compaction' : undefined);
197
289
  // 压完等于换了半本历史:加载时冻结的东西该重算了(记忆栏就是这么挂上去的)
198
290
  if (compacted) {
@@ -232,7 +324,34 @@ export const compactPlugin = {
232
324
  min: 50,
233
325
  max: 95,
234
326
  step: 5,
235
- help: '估算用量超过这个比例就自动压缩;/compact 手动压缩不受这条线限制。',
327
+ help: '估算用量超过这个比例就自动压缩;/compact 手动压缩不受这条线限制。阈值还会被「窗口减去输出预留与安全余量」压低,取两者中较小的那个。',
328
+ },
329
+ {
330
+ type: 'number',
331
+ key: 'headroomTokens',
332
+ label: '安全余量(token,0 = 按窗口自动)',
333
+ min: HEADROOM_RANGE.min,
334
+ max: HEADROOM_RANGE.max,
335
+ step: 1024,
336
+ help: '压到多早才开始动手:阈值会给输出预留(模型的 maxTokens 上限)再加这么多 token 的安全余量。0 = 自动(窗口的 6.4%,最多 65536)。调大 = 更早压缩、留给这一轮的空间更多;调小 = 压得更晚、更省历史。',
337
+ },
338
+ {
339
+ type: 'number',
340
+ key: 'compactionRetries',
341
+ label: '压一次还不够时最多再压几次',
342
+ min: COMPACTION_RETRIES_RANGE.min,
343
+ max: COMPACTION_RETRIES_RANGE.max,
344
+ step: 1,
345
+ help: '自动压缩后若估算用量仍在阈值之上,会再压一次,最多补这么多次。代价:每多压一次就多一次摘要模型调用(要等它写完才发真实请求),并且每次都把更早的原文折成摘要,细节会再丢一层。0 = 只压一次。',
346
+ },
347
+ {
348
+ type: 'number',
349
+ key: 'retainPercent',
350
+ label: '保留尾部(占模型窗口的百分比)',
351
+ min: RETAIN_PERCENT_RANGE.min,
352
+ max: RETAIN_PERCENT_RANGE.max,
353
+ step: 1,
354
+ help: '压缩后原样保留最近这些对话,按模型窗口折算成 token 预算,再退到「工具调用与结果不拆开」的安全边界;「压缩后保留最近多少条」仍是条数下限。为什么按 token 算:一条工具结果就可能几十万字符,只按条数留会在这种会话里压不动。调大 = 原文留得更多、省出的空间更少。',
236
355
  },
237
356
  {
238
357
  type: 'number',
@@ -283,6 +402,9 @@ export const compactPlugin = {
283
402
  return {
284
403
  keepRecent: config.keepRecent,
285
404
  autoCompactPercent: config.autoCompactPercent,
405
+ headroomTokens: config.headroomTokens,
406
+ compactionRetries: config.compactionRetries,
407
+ retainPercent: config.retainPercent,
286
408
  anchorBudgetChars: config.anchorBudgetChars,
287
409
  userQuoteBudgetChars: config.userQuoteBudgetChars,
288
410
  readStateFiles: config.readStateFiles,
@@ -298,6 +420,12 @@ export const compactPlugin = {
298
420
  applyConfig({ keepRecent: num });
299
421
  else if (key === 'autoCompactPercent')
300
422
  applyConfig({ autoCompactPercent: num });
423
+ else if (key === 'headroomTokens')
424
+ applyConfig({ headroomTokens: num });
425
+ else if (key === 'compactionRetries')
426
+ applyConfig({ compactionRetries: num });
427
+ else if (key === 'retainPercent')
428
+ applyConfig({ retainPercent: num });
301
429
  else if (key === 'anchorBudgetChars')
302
430
  applyConfig({ anchorBudgetChars: num });
303
431
  else if (key === 'userQuoteBudgetChars')
@@ -29,6 +29,14 @@ export const gitPlugin = {
29
29
  let dueAt = 0;
30
30
  /** 一拍还在跑时不再起第二拍(git 慢的时候)。 */
31
31
  let busy = false;
32
+ /**
33
+ * 手上这份 {@link cache} 属于哪个工作目录(null = 还没读过)。
34
+ *
35
+ * 用来回答「这次换会话要不要重拍」:读数只有一份、跟着当前会话的目录走,
36
+ * 同一个工作区里换会话读到的还是同一份,重拍纯属白拉三个 git 子进程
37
+ * (2026-11-03 量到每次切会话约 30–50ms 的进程创建开销)。
38
+ */
39
+ let cacheCwd = null;
32
40
  const schedule = (ms) => {
33
41
  const at = Date.now() + ms;
34
42
  if (timer !== null && at >= dueAt)
@@ -44,6 +52,7 @@ export const gitPlugin = {
44
52
  /** 读一拍:分支名 + 改动条数。读不动(不是仓库 / git 不在 / 目录没了)按空读数记。 */
45
53
  const read = async () => {
46
54
  const cwd = ctx.session.current().meta.cwd;
55
+ cacheCwd = cwd;
47
56
  let next;
48
57
  try {
49
58
  // 先问一句「这儿是不是仓库」:不然「不是仓库」与「空仓库(还没提交过)」
@@ -121,6 +130,11 @@ export const gitPlugin = {
121
130
  // 三处催拍:回合收工(这一轮可能落了文件/切了分支)、换会话(换了工作区)、
122
131
  // 以及写类 git op 自己调 refresh()(那条在 desktop-dock 里)。
123
132
  ctx.on('dsc/turn-end', refresh);
124
- ctx.on('dsc/session-open', refresh);
133
+ // 换会话只在**工作目录真的变了**时才重拍:同一个工作区里的会话共用一个仓库读数,
134
+ // 每切一次就拉三个 git 子进程是纯浪费(读数本身由巡检按 12s/30s 的节奏保鲜)。
135
+ ctx.on('dsc/session-open', ({ session }) => {
136
+ if (session.meta.cwd !== cacheCwd)
137
+ refresh();
138
+ });
125
139
  },
126
140
  };
@@ -33,11 +33,15 @@ export const goalPlugin = {
33
33
  if (restored !== undefined)
34
34
  goals.restore(restored);
35
35
  const touch = () => ctx.emit('dsc/changed');
36
- /** 把当前目标快照写进会话日志(恢复会话时靠它)并让快照失效。 */
36
+ /**
37
+ * 把当前目标快照写进会话日志(恢复会话时靠它)并让快照失效。
38
+ *
39
+ * **空目标也要写**:用户点 ✕ 清空之后快照是 null,得追加一条 `goal = null` 盖掉
40
+ * 日志里上一条真目标;不写的话日志最后一条仍是清空前那份,重启重放又把它读回来
41
+ * (2026-11-02 报障「目标关闭后重启又会出现」)。
42
+ */
37
43
  const persist = () => {
38
- const snapshot = goals.snapshot;
39
- if (snapshot !== null)
40
- ctx.session.current().appendState('goal', snapshot);
44
+ ctx.session.current().appendState('goal', goals.snapshot);
41
45
  touch();
42
46
  };
43
47
  const service = {
@@ -104,19 +104,29 @@ export const hostStdioPlugin = {
104
104
  // 审批插件据此决定是弹卡还是立刻按拒,不再白等一次审批超时。
105
105
  const offInteractive = ctx.provide('interactive', { kind: 'host', reachable: () => transport.reachable() });
106
106
  // ---- 快照节流推送 ----
107
+ //
108
+ // 节流的口径是「一帧最密的间隔」,不是「每次变化都先等一个窗口」(2026-11-03):
109
+ // 旧写法第一处变化就 setTimeout(throttleMs),于是「点一下会话」这类**用户刚做完的
110
+ // 动作**永远要多等 60–80ms 才出现在界面上——量到的正是这段(宿主 30ms 就干完了,
111
+ // 界面 95ms 才看到)。现在退化成标准的 leading-edge:距上一帧已经超过窗口就立刻推,
112
+ // 窗口内的连续变化仍旧合并成一帧,密度上限不变。
107
113
  let pendingSnapshot = false;
108
114
  let timer = null;
115
+ /** 上一帧推出去的时刻(0 = 还没推过)。 */
116
+ let lastSentAt = 0;
109
117
  const scheduleSnapshot = () => {
110
118
  pendingSnapshot = true;
111
119
  if (timer !== null)
112
120
  return;
121
+ const wait = Math.max(0, throttleMs - (Date.now() - lastSentAt));
113
122
  timer = setTimeout(() => {
114
123
  timer = null;
115
124
  if (!pendingSnapshot)
116
125
  return;
117
126
  pendingSnapshot = false;
127
+ lastSentAt = Date.now();
118
128
  transport.send({ type: 'snapshot', snapshot: runtime.getSnapshot() });
119
- }, throttleMs);
129
+ }, wait);
120
130
  };
121
131
  const unsubscribe = runtime.subscribe(scheduleSnapshot);
122
132
  // ---- 请求处理 ----