dsh-lpipe-focus 0.1.0 → 0.1.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.
package/INDEX.md CHANGED
@@ -7,13 +7,13 @@
7
7
  - [src/rpc.mjs](src/rpc.mjs):`/api/dsh-lpipe-focus` 的 `focus.config` 与 `focus.config.save` 信封处理。
8
8
  - [src/tools.mjs](src/tools.mjs):`focus_conclude` 参数校验、并发工具调用硬拦截与结果渲染。
9
9
  - [src/render.mjs](src/render.mjs):结论层 `<working-conclusions>`、提示层 `<current-objective>` 与轻推提醒 `<system-reminder>` 正文构造。
10
- - [src/surface.mjs](src/surface.mjs):四层表层切分、双段 `replace` 折叠、过线/闲置程序归并裁剪与防刷屏轻推提醒。
10
+ - [src/surface.mjs](src/surface.mjs):识别需要原样保留的用户、宿主与技能节点;折叠已完成工作、承接目标、整理结论并按需提醒。
11
11
  - [src/prompt.mjs](src/prompt.mjs):注入主会话的英文固定系统提示词章节(`order: 712`)。
12
12
  - [client/panel.js](client/panel.js):设置页里的「聚焦管线」块(「所有对话生效」即时开关、四项输入、K/M 简写、恢复默认/撤回/保存、读取失败保护与重试);构建到 [lib/client.js](lib/client.js)。
13
13
  - [scripts/build-client.mjs](scripts/build-client.mjs):把面板打包为宿主的客户端模块壳。
14
14
  - [assets/icon.png](assets/icon.png):组件图标(聚焦四角框 + 堆叠结论条 + 琥珀色当前目标条,512² 透明 PNG)。
15
15
  - [test/config.test.mjs](test/config.test.mjs):四项范围、跨字段关系、损坏文件保护与未知键保留测试。
16
- - [test/surface.test.mjs](test/surface.test.mjs):四层折叠与前缀守恒、提示层承接、并发拦截、过线/闲置整理、提醒与主会话隔离回归。
16
+ - [test/surface.test.mjs](test/surface.test.mjs):普通折叠的原节点保留、目标承接、并发拦截、过线/闲置整理、同会话恢复、提醒与作用域回归。
17
17
  - [test/rpc.test.mjs](test/rpc.test.mjs):RPC 信封、HTTP 状态码与读写错误测试。
18
18
  - [test/client.test.mjs](test/client.test.mjs):客户端构建同步、宿主主题 token、K/M 输入校验、读取失败重试与保存按钮状态测试。
19
19
  - [package.json](package.json)、[cordis.patch.yml](cordis.patch.yml):独立组件声明与挂载行。
package/README.md CHANGED
@@ -1,17 +1,14 @@
1
1
  # 聚焦管线 · dsh-lpipe-focus
2
2
 
3
- 聚焦管线管理 LP 主会话窗口内的短期工作上下文。多步搜索、读文件和改代码结束后,模型可以单独调用 `focus_conclude`,把已经用完的过程折叠成简短结论追加到结论层末尾,不改动前面的常驻前缀与旧结论,从而保留提供方的提示词前缀缓存(KV Cache)。
3
+ 结论用来替代已经完成的一段工作。判断标准是:只看这条结论和当前工作区,模型能不能直接做对下一步?例如,在多个文件里找到实现时,记下相关文件的位置和用途即可。测试文件写好、下一步是运行时,记下测试命令;只有实际运行过,才记通过或失败。
4
4
 
5
- 只有当窗口总字符达到过线整理阈值,或距离上一次模型交互超过闲置整理时长时,宿主才会用纯程序归并同名键、清理标空作废的键,并按上限裁剪结论层,全程不额外调用模型。所有表层替换均通过 DSH 的 `surfaceOp: replace` 完成,只影响发给模型的消息表层,不会删除聊天界面里的历史记录,也不会生成伪造的用户发言气泡。
5
+ ## 什么时候折叠,哪些原文会留下
6
6
 
7
- ## 四层表层与折叠规则
7
+ 模型用完一段搜索、读取或编辑结果后,可以单独调用 `focus_conclude`。下一步仍要逐字引用或修改原文,就先用完再折;已经能回答或需要用户决定,就直接回复。每条结论用稳定的 `key` 标识,同键以后写的为准,`text: ""` 表示作废。可选的 `objective` 说明当前任务和下一步,不要用一句「继续」代替原任务;目标不能覆盖用户后来的要求或授权。
8
8
 
9
- 主会话的模型可见表层按顺序分为四层:
9
+ 普通折叠从最后一个需要保留的节点之后开始,到本次工具结果为止。不搬动用户原话、系统和工作区指令、宿主上下文快照、技能目录或已加载技能的正文。用 `skill` 加载技能时,调用和结果一起留在原位;用 `/技能名` 直接加载的指令同样保留。因此,中途加载技能之前的搜索过程可能暂时仍在。时间提示和聚焦提醒本身不构成保留边界。
10
10
 
11
- 1. **最底层**:首条 `system/message` 及首轮对话前的初始 `runtime-context`、`skill-catalog` 与 `developer/message`,折叠与整理时永不遮蔽。
12
- 2. **结论层**:连续的 `layer: 'conclusion'` 节点。日常每次折叠只在结论层末尾追加一条新节点;同名 `key` 以最新一条为准,传入 `text: ""` 表示该键作废。
13
- 3. **提示层**:紧跟在结论层后面的单条目标节点。模型填写 `objective` 时保存下一步目标;未填写时自动承接被折叠区间内最近一条真实用户、聊天或唤醒消息;区间内没有新触发消息时沿用上一轮提示层。
14
- 4. **未转化层**:提示层之后的活跃对话、思考链、工具调用与结果。未转化层累积到提醒线时,宿主会在下一步附带一条不显示窗口百分比的 `<system-reminder>` 提醒;模型若仍在查看原始细节可推迟折叠,折叠后该提醒一并被遮蔽。
11
+ 恢复同一会话时,DSH 从已保存的会话事件重建发给模型的消息;不需要重开对话,也不会因此重做一次已完成的折叠。聚焦管线只替换发给模型的上下文,不删除聊天历史,不保证提供方的缓存命中。
15
12
 
16
13
  `focus_conclude` 不能与其他工具在同一条回复中并发调用。若同一条 `assistant/message` 含有其他工具调用,本次 `focus_conclude` 会直接返回参数错误,下一步不做任何表层替换。会话存在未闭合的宿主 `compaction/start` 锁时,聚焦管线同样跳过改写。
17
14
 
@@ -28,7 +25,9 @@
28
25
  | `nudgeChars` | 未转化提醒线 | `256K` 字符 | `16K`–`2M` | 未转化层达到此字符数时轻推一次整理提醒;须满足 `<= compactChars` |
29
26
  | `maxConclusionChars` | 结论层上限 | `64K` 字符 | `4K`–`512K` | 程序大整理后结论层保留的最大字符数,超限时淘汰最早条目;须满足 `< compactChars` |
30
27
 
31
- 如果结论层原本只有 1 个节点、无重复键、无标空墓碑且未超过上限,即使达到闲置时长也不会发出无意义的替换。
28
+ 字符数过线时,Focus 只整理结论。即使两组结论之间隔着用户消息,也按键保留最新值、删除已作废的键;中间的用户消息留在原位。
29
+
30
+ 闲置达到设定时长后,或 DSH 成功完成一次原生压缩后,Focus 还会清理已被新版本取代的上下文快照和技能目录。最新快照、用户原话、工作区指令和已加载技能仍然保留。不完整的技能目录不能替代此前的完整目录。没有内容需要整理时,不写入新事件。
32
31
 
33
32
  「恢复默认」只把草稿填回默认值,保存后生效;「撤回」恢复已保存的值;「保存」仅在存在有效未保存改动时启用。
34
33
 
@@ -64,4 +63,4 @@ node components/dsh-lpipe-focus/scripts/build-client.mjs
64
63
  node --test "components/dsh-lpipe-focus/test/*.test.mjs"
65
64
  ```
66
65
 
67
- 客户端源码 `client/panel.js` 构建生成 `lib/client.js`。测试覆盖四层折叠与前缀 `seq` 守恒、提示层承接、并发工具拦截、过线与闲置程序归并、提醒防刷屏与自清理、压缩锁避让、主会话隔离、配置文件损坏保护、RPC 信封及客户端状态机。
66
+ 客户端面板由 `client/panel.js` 构建到 `lib/client.js`。折叠回归检查受保护消息的事件编号(`seq`)和顺序、跨消息归并结论、旧目标的承接,以及同一会话恢复后不会再次折叠同一个检查点。其余测试覆盖并发工具拦截、压缩锁、提醒频率、会话隔离、配置、RPC 和设置面板。
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Lpipe Focus",
4
- "description": "Stack working conclusions in the main session while preserving the prompt prefix cache, compacting deterministically only on threshold or idle timeout."
4
+ "description": "Keep the findings needed for the next step. Ordinary folds preserve user messages, host context and loaded skills."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "聚焦管线(Lpipe Focus)",
4
- "description": "将主会话已消费的搜索与编辑过程折叠为结论层,日常只追加不改前缀;仅在过线或闲置超时后由程序去重裁剪。"
4
+ "description": "用结论替代已完成的工作;普通折叠保留用户原话、宿主上下文和已加载的技能。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lpipe-focus",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "description": "Short-term working context focus and conclusion stacking for the Lpipe main session.",
6
6
  "license": "AGPL-3.0-or-later",
package/src/prompt.mjs CHANGED
@@ -4,12 +4,7 @@ export const FOCUS_PROMPT_ORDER = 712;
4
4
  export const FOCUS_SYSTEM_PROMPT = [
5
5
  '## Context focus (`focus_conclude`)',
6
6
  '',
7
- 'Use `focus_conclude` during multi-step work to fold consumed exploration and file-editing steps into concise conclusions while keeping the prompt prefix cache intact.',
8
- '',
9
- '- **Call alone:** Never call `focus_conclude` in the same response as another tool call. Finish reading any needed tool outputs or images first, then call `focus_conclude` by itself.',
10
- '- **What to record:**',
11
- ' - *Information gathering (search, file reads, debugging, web/video inspection):* Write a self-contained conclusion equivalent to the search — if you have this text later, you do not need to re-run those steps. Keep exact file paths, symbol or config names, decisions with reasons, and exact values. If an attempt hit a dead end, note what failed and why in one short clause so you do not repeat it.',
12
- ' - *File creation or edits:* Since the file now exists on disk, do not copy full source code into conclusions. Record only the file path and what it now does or changed.',
13
- '- **Same-slot updates & retirement:** Reuse the same `key` to supersede an older conclusion on the same subject. When entering a new stage where an earlier `key` is completely unneeded, pass `text: ""` for that `key`.',
14
- '- **Prompt layer (`objective`):** Write conclusions as settled past facts, never as live imperatives. Put the single next action or remaining goal in `objective`; omit `objective` when you are about to answer the active user request directly on the next step.',
7
+ 'Fold a completed stage when its conclusion and the current workspace let you take the next step without replaying that stage. Keep what the work established, not a log of how you got there.',
8
+ 'After a search, keep the useful location and what it is for. After writing a test, keep the command to run it; report a pass or failure only if you ran it. Keep a constraint or failed approach when it changes the next decision.',
9
+ 'If you still need the raw output to edit, quote, or check something, use it before folding. Do not copy user instructions, host context, or skill text into conclusions. When you can already answer or need a decision from the user, respond directly.',
15
10
  ].join('\n');
package/src/render.mjs CHANGED
@@ -15,7 +15,7 @@ export const RETIRED_CONCLUSION_MARKER = '(retired — no longer needed)';
15
15
 
16
16
  export const NUDGE_REMINDER_TEXT = [
17
17
  '<system-reminder>',
18
- 'Efficiency note: Unfolded working context (tool outputs and intermediate steps since the last checkpoint) has grown substantially. If a sub-step or investigation has reached a conclusion, consider calling `focus_conclude` by itself to fold the consumed material and keep context sharp. If you are mid-reasoning on raw details you still need right now, finish the current step first and fold afterward.',
18
+ 'Fold a completed stage with `focus_conclude` only when you no longer need its raw output.',
19
19
  '</system-reminder>',
20
20
  ].join('\n');
21
21
 
@@ -47,14 +47,14 @@ export function renderObjectiveText(rawText, origin) {
47
47
  if (origin === 'model') {
48
48
  return [
49
49
  '<current-objective>',
50
- 'Current objective recorded at the last checkpoint (continue from here; newer user messages below take precedence if they change direction):',
50
+ 'Checkpoint objective. Follow the user’s latest instructions if they change this task:',
51
51
  safe,
52
52
  '</current-objective>',
53
53
  ].join('\n');
54
54
  }
55
55
  return [
56
- '<current-objective origin="user-request">',
57
- 'Active request carried across the last checkpoint:',
56
+ '<current-objective origin="carried">',
57
+ 'Task carried forward from the last checkpoint. Follow the user’s latest instructions if they change it:',
58
58
  safe,
59
59
  '</current-objective>',
60
60
  ].join('\n');
package/src/surface.mjs CHANGED
@@ -13,31 +13,21 @@ import {
13
13
  } from './tools.mjs';
14
14
 
15
15
  export const TRIGGER_SOURCE_KINDS = new Set(['user', 'dsh-lpipe-chat', 'dsh-lpipe-wake']);
16
+ const HOST_KINDS = new Set(['runtime-context', 'skill-catalog', 'agent-instructions', 'skill-invocation', 'compact-checkpoint']);
17
+ const CONTINUE_CLAUSE = /^(?:(?:please\s+)?(?:continue|resume|go on|keep going)(?:\s+(?:please|(?:with\s+)?(?:the\s+)?(?:original\s+|previous\s+|current\s+)?(?:task|work)))?|(?:请)?(?:继续|接着)(?:执行|进行|做)?(?:原本的?|之前的?|原来的?|当前的?)?(?:工作|任务)?(?:就好|即可|吧)?)$/iu;
18
+ const ACK_CLAUSE = /^(?:哦|噢|嗯|好(?:的)?|没事(?:了)?|没关系|(?:我)?(?:明白|知道)(?:原因)?了|ok(?:ay)?|thanks|got it|no worries)$/iu;
16
19
 
17
- const INITIAL_BASE_USER_KINDS = new Set(['runtime-context', 'skill-catalog', 'agent-instructions']);
20
+ function isContinuation(text) {
21
+ const clauses = text.trim().split(/[,.!?,。!?;;…\n]+/u).map(s => s.trim()).filter(Boolean);
22
+ return clauses.some(s => CONTINUE_CLAUSE.test(s)) && clauses.every(s => CONTINUE_CLAUSE.test(s) || ACK_CLAUSE.test(s));
23
+ }
18
24
 
19
25
  function eventAtSeq(session, events, seq) {
20
- if (typeof session?.eventAt === 'function') {
21
- const found = session.eventAt(seq);
22
- if (found) return found;
23
- }
24
- const direct = events[seq];
25
- if (direct && direct.seq === seq) return direct;
26
- return events.find((item) => item?.seq === seq);
26
+ return session?.eventAt?.(seq) ?? (events[seq]?.seq === seq ? events[seq] : events.find(ev => ev?.seq === seq));
27
27
  }
28
28
 
29
- function messageOfSurfaceEvent(event) {
30
- if (!event) return null;
31
- if (event.type === 'user/message') return event.data ?? null;
32
- if (
33
- event.type === 'system/message'
34
- || event.type === 'developer/message'
35
- || event.type === 'assistant/message'
36
- || event.type === 'tool/result'
37
- ) {
38
- return event.data?.message ?? null;
39
- }
40
- return null;
29
+ function messageOfSurfaceEvent(ev) {
30
+ return ev?.type === 'user/message' ? ev.data : ev?.data?.message;
41
31
  }
42
32
 
43
33
  export function charsOfBlocks(content) {
@@ -45,18 +35,14 @@ export function charsOfBlocks(content) {
45
35
  if (!Array.isArray(content)) return 0;
46
36
  let total = 0;
47
37
  for (const block of content) {
48
- if (!block) continue;
49
- if (typeof block === 'string') {
50
- total += block.length;
51
- continue;
52
- }
53
- if (typeof block.text === 'string') total += block.text.length;
54
- if (typeof block.thinking === 'string') total += block.thinking.length;
55
- if (block.type === 'tool-call') {
38
+ if (typeof block === 'string') total += block.length;
39
+ if (typeof block?.text === 'string') total += block.text.length;
40
+ if (typeof block?.thinking === 'string') total += block.thinking.length;
41
+ if (block?.type === 'tool-call') {
56
42
  total += String(block.name ?? '').length;
57
43
  if (typeof block.arguments === 'string') total += block.arguments.length;
58
44
  else if (block.arguments !== undefined) {
59
- try { total += JSON.stringify(block.arguments).length; } catch { /* ignore */ }
45
+ try { total += JSON.stringify(block.arguments).length; } catch { /* ignore non-JSON input */ }
60
46
  }
61
47
  }
62
48
  }
@@ -64,12 +50,7 @@ export function charsOfBlocks(content) {
64
50
  }
65
51
 
66
52
  export function charsOfMessage(message) {
67
- if (!message || typeof message !== 'object') return 0;
68
- if (Array.isArray(message.content) || typeof message.content === 'string') {
69
- return charsOfBlocks(message.content);
70
- }
71
- if (typeof message.text === 'string') return message.text.length;
72
- return 0;
53
+ return charsOfBlocks(message?.content ?? message?.text);
73
54
  }
74
55
 
75
56
  export function charsOfSurfaceEvent(event) {
@@ -77,662 +58,405 @@ export function charsOfSurfaceEvent(event) {
77
58
  }
78
59
 
79
60
  export function textOfUserMessage(message) {
80
- if (!message || typeof message !== 'object') return '';
81
- if (typeof message.text === 'string') return message.text;
82
- if (typeof message.content === 'string') return message.content;
83
- if (!Array.isArray(message.content)) return '';
84
- return message.content
85
- .filter((block) => block?.type === 'text' && typeof block.text === 'string')
86
- .map((block) => block.text)
87
- .join('\n');
61
+ if (typeof message?.text === 'string') return message.text;
62
+ if (typeof message?.content === 'string') return message.content;
63
+ if (!Array.isArray(message?.content)) return '';
64
+ return message.content.filter(b => b?.type === 'text').map(b => b.text).join('\n');
88
65
  }
89
66
 
90
67
  export function hasActiveCompaction(events) {
91
- let latestEndSeedSeq = -1;
92
- let unmatchedStartSeq = null;
93
- let known = false;
94
- for (let index = events.length - 1; index >= 0; index -= 1) {
95
- const event = events[index];
96
- if (!event) continue;
97
- if (latestEndSeedSeq === -1 && event.type === 'session/end-seed') {
98
- latestEndSeedSeq = typeof event.seq === 'number' ? event.seq : index;
99
- }
100
- if (!known) {
101
- if (event.type === 'compaction/start') {
102
- unmatchedStartSeq = typeof event.seq === 'number' ? event.seq : index;
103
- known = true;
104
- } else if (event.type === 'compaction/end') {
105
- known = true;
106
- }
107
- }
108
- if (known && latestEndSeedSeq !== -1) break;
68
+ for (let i = events.length - 1; i >= 0; i--) {
69
+ if (events[i]?.type === 'compaction/start') return true;
70
+ if (events[i]?.type === 'compaction/end' || events[i]?.type === 'session/end-seed') break;
109
71
  }
110
- if (unmatchedStartSeq === null) return false;
111
- return unmatchedStartSeq > latestEndSeedSeq;
72
+ return false;
112
73
  }
113
74
 
114
- function isInitialBaseNode(event, index) {
115
- if (!event) return false;
116
- if (index === 0 && event.type === 'system/message') return true;
117
- if (event.type === 'system/message' || event.type === 'developer/message') return true;
118
- if (event.type === 'user/message') {
119
- const kind = event.data?.source?.kind;
120
- if (INITIAL_BASE_USER_KINDS.has(kind)) return true;
121
- }
122
- return false;
75
+ function sourceOf(ev) {
76
+ return ev?.type === 'user/message' ? ev.data?.source : undefined;
123
77
  }
124
78
 
125
- /**
126
- * Compute four-layer boundaries on `surface.nodes`:
127
- * - `[0, baseEndExclusive)`: Layer 1 (base layer, never shadowed)
128
- * - `[conclusionStartIdx, conclusionEndExclusive)`: Layer 2 (conclusion layer)
129
- * - `objectiveIdx`: Layer 3 (prompt/objective layer, or -1 if absent)
130
- * - `[unconvertedStartIdx, nodes.length)`: Layer 4 (unconverted layer)
131
- */
132
- export function inspectLayers(session, events = readSessionEvents(session)) {
133
- const nodes = Array.isArray(session?.surface?.nodes) ? [...session.surface.nodes] : [];
134
- const surfaceEvents = nodes.map((seq) => eventAtSeq(session, events, seq));
79
+ function layerOf(ev) {
80
+ const source = sourceOf(ev);
81
+ return source?.kind === FOCUS_SOURCE_KIND ? source.layer : undefined;
82
+ }
135
83
 
136
- let baseEndExclusive = 0;
137
- while (baseEndExclusive < surfaceEvents.length && isInitialBaseNode(surfaceEvents[baseEndExclusive], baseEndExclusive)) {
138
- baseEndExclusive += 1;
139
- }
84
+ function isTrigger(source) {
85
+ return TRIGGER_SOURCE_KINDS.has(source?.kind) && !(source.kind === 'dsh-lpipe-wake' && source.form === 'snapshot');
86
+ }
140
87
 
141
- let conclusionStartIdx = baseEndExclusive;
142
- let conclusionEndExclusive = baseEndExclusive;
143
- while (conclusionEndExclusive < surfaceEvents.length) {
144
- const ev = surfaceEvents[conclusionEndExclusive];
145
- if (ev?.type === 'user/message' && ev.data?.source?.kind === FOCUS_SOURCE_KIND && ev.data?.source?.layer === 'conclusion') {
146
- conclusionEndExclusive += 1;
147
- } else {
148
- break;
149
- }
150
- }
88
+ function toolCalls(ev) {
89
+ const blocks = ev?.type === 'assistant/message' ? ev.data?.message?.content : null;
90
+ return Array.isArray(blocks) ? blocks.filter(b => b?.type === 'tool-call') : [];
91
+ }
151
92
 
152
- let objectiveIdx = -1;
153
- if (conclusionEndExclusive > conclusionStartIdx) {
154
- // Folded state: objective layer is an explicit layer === 'objective' node right after conclusions (if present)
155
- const candidate = surfaceEvents[conclusionEndExclusive];
156
- if (candidate?.type === 'user/message' && candidate.data?.source?.kind === FOCUS_SOURCE_KIND && candidate.data?.source?.layer === 'objective') {
157
- objectiveIdx = conclusionEndExclusive;
158
- }
159
- } else {
160
- // Unfolded state: first real trigger user message after base layer acts as initial prompt layer
161
- for (let idx = baseEndExclusive; idx < surfaceEvents.length; idx += 1) {
162
- const ev = surfaceEvents[idx];
163
- if (ev?.type === 'user/message' && TRIGGER_SOURCE_KINDS.has(ev.data?.source?.kind)) {
164
- objectiveIdx = idx;
165
- break;
93
+ function resultId(ev) {
94
+ const msg = ev?.data?.message;
95
+ if (msg?.toolCallId && msg.source?.callId && msg.toolCallId !== msg.source.callId) return null;
96
+ return msg?.toolCallId ?? msg?.source?.callId;
97
+ }
98
+
99
+ // A cut is valid only outside a complete, identified batch. An unfinished suffix
100
+ // doesn't invalidate a completed checkpoint before it. Never infer pairs by count.
101
+ function inspectSurface(surfaceEvents) {
102
+ const cuts = [true];
103
+ const barriers = [];
104
+ const pending = new Map();
105
+ let valid = true;
106
+ let lastConclusionIdx = -1;
107
+ let unconvertedStartIdx = 0;
108
+ for (const [i, ev] of surfaceEvents.entries()) {
109
+ const source = sourceOf(ev);
110
+ const layer = layerOf(ev);
111
+ const calls = toolCalls(ev);
112
+ let barrier = ev?.type === 'system/message' || ev?.type === 'developer/message'
113
+ || isTrigger(source) || HOST_KINDS.has(source?.kind) || layer === 'conclusion';
114
+ if (!ev) valid = false;
115
+ if (ev?.type === 'assistant/message') {
116
+ if (pending.size) valid = false;
117
+ const skill = calls.some(b => b.name === 'skill');
118
+ barrier ||= skill;
119
+ for (const call of calls) {
120
+ if (!call.id || !call.name || pending.has(call.id)) valid = false;
121
+ pending.set(call.id, { ev, skill });
166
122
  }
123
+ } else if (ev?.type === 'tool/result') {
124
+ const id = resultId(ev);
125
+ const pair = pending.get(id);
126
+ if (!pair || pair.ev.data.turn !== ev.data.turn || pair.ev.data.step !== ev.data.step) valid = false;
127
+ barrier ||= pair?.skill === true;
128
+ pending.delete(id);
167
129
  }
130
+ if (barrier) barriers.push(i);
131
+ if (layer === 'conclusion') lastConclusionIdx = i;
132
+ if (barrier || layer === 'objective') unconvertedStartIdx = i + 1;
133
+ cuts.push(valid && pending.size === 0);
168
134
  }
135
+ return { cuts, barriers, lastConclusionIdx, unconvertedStartIdx };
136
+ }
169
137
 
170
- const unconvertedStartIdx = objectiveIdx >= 0
171
- ? objectiveIdx + 1
172
- : conclusionEndExclusive;
173
-
174
- return {
175
- nodes,
176
- surfaceEvents,
177
- baseEndExclusive,
178
- conclusionStartIdx,
179
- conclusionEndExclusive,
180
- objectiveIdx,
181
- unconvertedStartIdx,
182
- };
138
+ export function inspectLayers(session, events = readSessionEvents(session)) {
139
+ const nodes = [...(session?.surface?.nodes ?? [])];
140
+ const surfaceEvents = nodes.map(seq => eventAtSeq(session, events, seq));
141
+ return { nodes, surfaceEvents, ...inspectSurface(surfaceEvents) };
183
142
  }
184
143
 
185
- /**
186
- * Verify that `nodes[startIdx .. endIdx]` is balanced with respect to tool-call / tool/result pairs:
187
- * 1. Prefix `[0 .. startIdx)` has 0 open tool calls;
188
- * 2. Span `[startIdx .. endIdx]` never goes negative and ends with 0 open tool calls.
189
- */
190
144
  export function isSurfaceSpanBalanced(surfaceEvents, startIdx, endIdx) {
191
- if (startIdx <= 0 || startIdx > endIdx || endIdx >= surfaceEvents.length) return false;
192
- let openCalls = 0;
193
- for (let i = 0; i < surfaceEvents.length; i += 1) {
194
- if (i === startIdx && openCalls !== 0) return false;
145
+ if (startIdx < 0 || startIdx > endIdx || endIdx >= surfaceEvents.length) return false;
146
+ const { cuts } = inspectSurface(surfaceEvents);
147
+ return cuts[startIdx] && cuts[endIdx + 1];
148
+ }
149
+
150
+ function parseArgs(rawArgs) {
151
+ try { return validateFocusConcludeArgs(typeof rawArgs === 'string' ? JSON.parse(rawArgs) : rawArgs); }
152
+ catch { return null; }
153
+ }
154
+
155
+ function pendingCheckpoints(layout, events) {
156
+ const { surfaceEvents, cuts, lastConclusionIdx } = layout;
157
+ const matches = [];
158
+ for (let i = lastConclusionIdx + 1; i + 1 < surfaceEvents.length; i++) {
195
159
  const ev = surfaceEvents[i];
196
- if (!ev) return false;
197
- if (ev.type === 'assistant/message') {
198
- const content = ev.data?.message?.content;
199
- const calls = Array.isArray(content) ? content.filter((b) => b?.type === 'tool-call').length : 0;
200
- openCalls += calls;
201
- } else if (ev.type === 'tool/result') {
202
- openCalls -= 1;
203
- if (openCalls < 0) return false;
204
- }
205
- if (i === endIdx && openCalls !== 0) return false;
160
+ const calls = toolCalls(ev);
161
+ if (calls.length !== 1 || calls[0].name !== FOCUS_TOOL_NAME || ev.data.interrupted || !cuts[i]) continue;
162
+ const result = surfaceEvents[i + 1];
163
+ const [call] = calls;
164
+ if (result?.type !== 'tool/result' || !cuts[i + 2] || resultId(result) !== call.id
165
+ || result.data.message?.isError || result.data.error !== undefined) continue;
166
+ // A durable tool/call is trace, not a surface node. Only use a matching
167
+ // execution from this exact step when an old assistant omitted arguments.
168
+ const raw = call.arguments ?? call.input ?? events.find(e => e.type === 'tool/call'
169
+ && e.seq > ev.seq && e.seq < result.seq && e.data?.turn === ev.data.turn && e.data.step === ev.data.step
170
+ && e.data.name === FOCUS_TOOL_NAME && e.data.callId === call.id)?.data.arguments;
171
+ const parsed = parseArgs(raw);
172
+ if (parsed) matches.push({ ...parsed, callIdx: i, resultIdx: i + 1 });
206
173
  }
207
- return true;
174
+ return matches;
208
175
  }
209
176
 
210
- function parseRawToolCallArgs(rawArgs) {
211
- if (rawArgs && typeof rawArgs === 'object' && !Array.isArray(rawArgs)) return rawArgs;
212
- if (typeof rawArgs === 'string') {
213
- try { return JSON.parse(rawArgs); } catch { return null; }
177
+ function storedObjective(ev) {
178
+ const source = sourceOf(ev);
179
+ const value = layerOf(ev) === 'objective' ? source : layerOf(ev) === 'conclusion' ? source.objective : null;
180
+ if (typeof value?.rawText === 'string' && value.rawText.trim()) {
181
+ return { rawText: value.rawText.trim(), origin: value.origin === 'model' ? 'model' : 'carried' };
214
182
  }
215
183
  return null;
216
184
  }
217
185
 
218
- /**
219
- * Scan `surfaceEvents` after `afterIdx` for completed successful `focus_conclude` pairs `[callIdx, resultIdx]`.
220
- * Also falls back to `tool/call` log events for argument lookup when needed.
221
- */
222
- function findPendingFocusConcludeCalls(surfaceEvents, startIdx, events) {
223
- const toolCallArgsById = new Map();
224
- for (const ev of events) {
225
- if (ev?.type === 'tool/call' && ev.data?.name === FOCUS_TOOL_NAME && ev.data?.callId) {
226
- toolCallArgsById.set(ev.data.callId, ev.data.arguments);
227
- }
228
- }
229
-
230
- const assistantCalls = new Map();
231
- const matched = [];
232
-
233
- for (let idx = startIdx; idx < surfaceEvents.length; idx += 1) {
234
- const ev = surfaceEvents[idx];
235
- if (!ev) continue;
236
- if (ev.type === 'assistant/message') {
237
- const blocks = Array.isArray(ev.data?.message?.content)
238
- ? ev.data.message.content.filter((b) => b?.type === 'tool-call')
239
- : [];
240
- // Hard rule: never fold a parallel tool-call assistant message
241
- if (blocks.length === 1 && blocks[0]?.name === FOCUS_TOOL_NAME) {
242
- const block = blocks[0];
243
- const callId = block.id ?? block.callId ?? block.toolCallId;
244
- if (callId) {
245
- assistantCalls.set(callId, {
246
- callIdx: idx,
247
- callSeq: ev.seq,
248
- rawArgs: block.arguments ?? block.input ?? toolCallArgsById.get(callId),
249
- });
250
- }
251
- }
252
- } else if (ev.type === 'tool/result') {
253
- const msg = ev.data?.message;
254
- const callId = msg?.toolCallId ?? msg?.source?.callId;
255
- if (!callId || msg?.isError === true || ev.data?.error !== undefined) continue;
256
- const callInfo = assistantCalls.get(callId);
257
- if (!callInfo) continue;
258
- const parsedObj = parseRawToolCallArgs(callInfo.rawArgs ?? toolCallArgsById.get(callId));
259
- if (!parsedObj) continue;
260
- try {
261
- const validated = validateFocusConcludeArgs(parsedObj);
262
- matched.push({
263
- callIdx: callInfo.callIdx,
264
- callSeq: callInfo.callSeq,
265
- resultIdx: idx,
266
- resultSeq: ev.seq,
267
- entries: validated.entries,
268
- objective: validated.objective,
269
- });
270
- } catch {
271
- // Invalid args cannot fold
272
- }
186
+ function resolveObjective(surfaceEvents, callIdx, explicit) {
187
+ let active = null;
188
+ let redirected = false;
189
+ let seenTask = false;
190
+ for (let i = 0; i < callIdx; i++) {
191
+ const ev = surfaceEvents[i];
192
+ const saved = storedObjective(ev);
193
+ if (saved) {
194
+ active = { ...saved, origin: 'carried' };
195
+ seenTask = true;
196
+ redirected = false;
197
+ } else if (isTrigger(sourceOf(ev))) {
198
+ const text = textOfUserMessage(ev.data).trim();
199
+ const attachment = ev.data?.content?.some?.(b => b?.type === 'image' || b?.type === 'file');
200
+ if (!attachment && (!text || isContinuation(text))) continue;
201
+ active = { rawText: text || 'Refer to the most recent user attachment.', origin: 'carried' };
202
+ redirected = seenTask;
203
+ seenTask = true;
273
204
  }
274
205
  }
206
+ return explicit && !redirected ? { rawText: explicit, origin: 'model' } : active;
207
+ }
275
208
 
276
- return matched;
209
+ function conclusionMessage(entries, now, objective) {
210
+ const msg = buildConclusionMessage(entries, now);
211
+ if (!objective) return msg;
212
+ const obj = buildObjectiveMessage({ ...objective, now });
213
+ return { ...msg, content: [...msg.content, ...obj.content], source: { ...msg.source, objective } };
277
214
  }
278
215
 
279
- function resolveObjectiveForFold(surfaceEvents, startIdx, callIdx, explicitObjective) {
280
- if (typeof explicitObjective === 'string' && explicitObjective.trim().length > 0) {
281
- return { rawText: explicitObjective.trim(), origin: 'model' };
282
- }
283
- // Search backward in [startIdx .. callIdx) for the latest real user/chat/wake trigger message
284
- for (let idx = callIdx - 1; idx >= startIdx; idx -= 1) {
285
- const ev = surfaceEvents[idx];
286
- if (ev?.type !== 'user/message') continue;
287
- const kind = ev.data?.source?.kind;
288
- if (!TRIGGER_SOURCE_KINDS.has(kind)) continue;
289
- const text = textOfUserMessage(ev.data).trim();
290
- if (text) return { rawText: text, origin: 'carried' };
291
- }
292
- // Fallback: carry forward the previous layer === 'objective' node inside [startIdx .. callIdx)
293
- for (let idx = callIdx - 1; idx >= startIdx; idx -= 1) {
294
- const ev = surfaceEvents[idx];
295
- if (ev?.type === 'user/message' && ev.data?.source?.kind === FOCUS_SOURCE_KIND && ev.data?.source?.layer === 'objective') {
296
- const saved = typeof ev.data.source.rawText === 'string' && ev.data.source.rawText.trim()
297
- ? ev.data.source.rawText.trim()
298
- : textOfUserMessage(ev.data).trim();
299
- if (saved) return { rawText: saved, origin: 'carried' };
300
- }
301
- }
302
- return null;
216
+ function replaceInput(nodes, start, end, message) {
217
+ return ['user/message', message, {
218
+ surfaceOp: { op: 'replace', startSeq: nodes[start], endSeq: nodes[end] },
219
+ sourceEventSeqs: nodes.slice(start, end + 1),
220
+ }];
303
221
  }
304
222
 
305
223
  export function foldPendingConclusions(session, { now = Date.now(), turn = 0, step = 0, onDiagnostic = () => {} } = {}) {
306
224
  const events = readSessionEvents(session);
225
+ if (hasActiveCompaction(events)) return null;
307
226
  const layout = inspectLayers(session, events);
308
- const startIdx = layout.conclusionEndExclusive;
309
- if (startIdx <= 0 || startIdx >= layout.surfaceEvents.length) return null;
310
-
311
- const matches = findPendingFocusConcludeCalls(layout.surfaceEvents, startIdx, events);
312
- if (matches.length === 0) return null;
313
-
314
- const latest = matches[matches.length - 1];
315
- const endIdx = latest.resultIdx;
316
- const callIdx = latest.callIdx;
317
-
318
- if (!isSurfaceSpanBalanced(layout.surfaceEvents, startIdx, endIdx)) {
319
- onDiagnostic({
320
- event: 'fold-skipped-unbalanced',
321
- sessionId: session?.id ?? null,
322
- turn,
323
- step,
324
- startSeq: layout.nodes[startIdx],
325
- endSeq: layout.nodes[endIdx],
326
- });
327
- return null;
328
- }
329
-
330
- // Merge entries in order across all matched focus_conclude calls in the span
331
- const mergedMap = new Map();
332
- let chosenObjective = '';
227
+ const { nodes, surfaceEvents, cuts, barriers } = layout;
228
+ const matches = pendingCheckpoints(layout, events);
229
+ const latest = matches.at(-1);
230
+ if (!latest) return null;
231
+ const { callIdx, resultIdx } = latest;
232
+ let start = (barriers.findLast(i => i <= resultIdx) ?? -1) + 1;
233
+ // A user or host message could itself have landed inside an unrelated batch.
234
+ // Keep the entire batch instead of beginning at one of its results.
235
+ while (start < callIdx && !cuts[start]) start++;
236
+ if (start > callIdx || !cuts[start] || !cuts[resultIdx + 1]) return null;
237
+
238
+ const merged = new Map();
239
+ let explicit = '';
333
240
  for (const item of matches) {
241
+ if (item.callIdx < start) continue;
334
242
  for (const entry of item.entries) {
335
- if (mergedMap.has(entry.key)) mergedMap.delete(entry.key);
336
- mergedMap.set(entry.key, entry);
337
- }
338
- if (item.objective) chosenObjective = item.objective;
339
- }
340
- const mergedEntries = [...mergedMap.values()];
341
- const objectiveInfo = resolveObjectiveForFold(layout.surfaceEvents, startIdx, callIdx, chosenObjective);
342
-
343
- const beforeChars = layout.surfaceEvents
344
- .slice(startIdx, endIdx + 1)
345
- .reduce((sum, ev) => sum + charsOfSurfaceEvent(ev), 0);
346
-
347
- const conclusionMsg = buildConclusionMessage(mergedEntries, now);
348
- const startSeq = layout.nodes[startIdx];
349
- const endSeq = layout.nodes[endIdx];
350
- let deferredObjectiveMessage = null;
351
- let afterChars = charsOfMessage(conclusionMsg);
352
-
353
- if (startIdx < callIdx) {
354
- // Normal two-segment replace:
355
- // 1. [startSeq .. preCallSeq] -> conclusionMsg
356
- // 2. [callSeq .. endSeq] -> objectiveMsg (or single replace if no objective exists)
357
- const preCallIdx = callIdx - 1;
358
- const preCallSeq = layout.nodes[preCallIdx];
359
- const callSpanSeqs = layout.nodes.slice(callIdx, endIdx + 1);
360
- const beforeCallSeqs = layout.nodes.slice(startIdx, callIdx);
361
-
362
- if (objectiveInfo && isSurfaceSpanBalanced(layout.surfaceEvents, startIdx, preCallIdx) && isSurfaceSpanBalanced(layout.surfaceEvents, callIdx, endIdx)) {
363
- const objectiveMsg = buildObjectiveMessage({
364
- rawText: objectiveInfo.rawText,
365
- origin: objectiveInfo.origin,
366
- now,
367
- });
368
- afterChars += charsOfMessage(objectiveMsg);
369
- session.append('user/message', conclusionMsg, {
370
- surfaceOp: { op: 'replace', startSeq, endSeq: preCallSeq },
371
- sourceEventSeqs: beforeCallSeqs,
372
- });
373
- session.append('user/message', objectiveMsg, {
374
- surfaceOp: { op: 'replace', startSeq: layout.nodes[callIdx], endSeq },
375
- sourceEventSeqs: callSpanSeqs,
376
- });
377
- } else {
378
- const allShadowed = layout.nodes.slice(startIdx, endIdx + 1);
379
- session.append('user/message', conclusionMsg, {
380
- surfaceOp: { op: 'replace', startSeq, endSeq },
381
- sourceEventSeqs: allShadowed,
382
- });
383
- if (objectiveInfo) {
384
- deferredObjectiveMessage = buildObjectiveMessage({
385
- rawText: objectiveInfo.rawText,
386
- origin: objectiveInfo.origin,
387
- now,
388
- asNotice: true,
389
- });
390
- afterChars += charsOfMessage(deferredObjectiveMessage);
391
- }
392
- }
393
- } else {
394
- // Degenerate path: startIdx === callIdx
395
- const allShadowed = layout.nodes.slice(startIdx, endIdx + 1);
396
- session.append('user/message', conclusionMsg, {
397
- surfaceOp: { op: 'replace', startSeq, endSeq },
398
- sourceEventSeqs: allShadowed,
399
- });
400
- if (objectiveInfo) {
401
- deferredObjectiveMessage = buildObjectiveMessage({
402
- rawText: objectiveInfo.rawText,
403
- origin: objectiveInfo.origin,
404
- now,
405
- asNotice: true,
406
- });
407
- afterChars += charsOfMessage(deferredObjectiveMessage);
243
+ merged.delete(entry.key);
244
+ merged.set(entry.key, entry);
408
245
  }
246
+ if (item.objective && !isContinuation(item.objective)) explicit = item.objective;
409
247
  }
410
-
411
- onDiagnostic({
412
- event: 'folded',
413
- sessionId: session?.id ?? null,
414
- turn,
415
- step,
416
- replacedRange: { startSeq, endSeq },
417
- keys: mergedEntries.map((item) => item.key),
418
- origin: objectiveInfo?.origin ?? 'none',
419
- beforeChars,
420
- afterChars,
421
- });
422
-
423
- return {
424
- deferredObjectiveMessage,
425
- beforeChars,
426
- afterChars,
427
- };
248
+ const entries = [...merged.values()];
249
+ const objective = resolveObjective(surfaceEvents, callIdx, explicit);
250
+ const inputs = start < callIdx && objective ? [
251
+ replaceInput(nodes, start, callIdx - 1, conclusionMessage(entries, now)),
252
+ replaceInput(nodes, callIdx, resultIdx, buildObjectiveMessage({ ...objective, now })),
253
+ ] : [replaceInput(nodes, start, resultIdx, conclusionMessage(entries, now, objective))];
254
+ session.append(inputs);
255
+ const beforeChars = surfaceEvents.slice(start, resultIdx + 1).reduce((n, ev) => n + charsOfSurfaceEvent(ev), 0);
256
+ const afterChars = inputs.reduce((n, [, msg]) => n + charsOfMessage(msg), 0);
257
+ onDiagnostic({ event: 'folded', sessionId: session.id, turn, step,
258
+ replacedRange: { startSeq: nodes[start], endSeq: nodes[resultIdx] }, keys: [...merged.keys()],
259
+ origin: objective?.origin ?? 'none', beforeChars, afterChars });
260
+ return { beforeChars, afterChars };
428
261
  }
429
262
 
430
- /**
431
- * Find the timestamp of the last completed model interaction (`turn/end` or `assistant/message`),
432
- * deliberately ignoring the freshly opened `turn/start` or current incoming user message.
433
- */
434
263
  export function lastModelInteractionTime(events) {
435
- for (let index = events.length - 1; index >= 0; index -= 1) {
436
- const event = events[index];
437
- if (!event) continue;
438
- if (event.type === 'turn/end' || event.type === 'assistant/message') {
439
- if (typeof event.time === 'number' && Number.isFinite(event.time)) {
440
- return event.time;
441
- }
442
- }
264
+ for (let i = events.length - 1; i >= 0; i--) {
265
+ const ev = events[i];
266
+ if ((ev?.type === 'turn/end' || ev?.type === 'assistant/message') && Number.isFinite(ev.time)) return ev.time;
443
267
  }
444
268
  return null;
445
269
  }
446
270
 
447
- /**
448
- * Deterministically merge, purge tombstones, and cap entries to `maxConclusionChars`.
449
- */
450
271
  export function compactConclusionEntries(rawEntriesList, maxConclusionChars) {
451
272
  const ordered = new Map();
452
- const retiredKeys = new Set();
453
-
454
273
  for (const entries of rawEntriesList) {
455
- if (!Array.isArray(entries)) continue;
456
- for (const raw of entries) {
457
- const key = typeof raw?.key === 'string' ? raw.key.trim() : '';
458
- const text = typeof raw?.text === 'string' ? raw.text : '';
459
- if (!key) continue;
460
- if (ordered.has(key)) ordered.delete(key);
461
- ordered.set(key, { key, text });
274
+ for (const entry of entries) {
275
+ ordered.delete(entry.key);
276
+ ordered.set(entry.key, entry);
462
277
  }
463
278
  }
464
-
465
- const active = [];
466
- for (const [key, entry] of ordered.entries()) {
467
- if (entry.text === '') {
468
- retiredKeys.add(key);
469
- } else {
470
- active.push(entry);
279
+ const kept = [];
280
+ const droppedKeys = [];
281
+ const overhead = renderConclusionsText([{ key: 'k', text: 'v' }]).length - renderConclusionLine({ key: 'k', text: 'v' }).length;
282
+ let available = maxConclusionChars - overhead;
283
+ let full = false;
284
+ for (const entry of [...ordered.values()].reverse()) {
285
+ if (!entry.text || full) { droppedKeys.push(entry.key); continue; }
286
+ const cost = renderConclusionLine(entry).length + (kept.length ? 1 : 0);
287
+ if (cost <= available) { kept.push(entry); available -= cost; continue; }
288
+ full = true;
289
+ if (kept.length) { droppedKeys.push(entry.key); continue; }
290
+ // Price the rendered prefix, including multiline indentation and escaped tags.
291
+ let low = 0, high = entry.text.length;
292
+ while (low < high) {
293
+ const mid = Math.ceil((low + high) / 2);
294
+ if (renderConclusionLine({ ...entry, text: entry.text.slice(0, mid) + '…' }).length <= available) low = mid;
295
+ else high = mid - 1;
471
296
  }
297
+ kept.push({ key: entry.key, text: entry.text.slice(0, low) + '…' });
472
298
  }
299
+ return { entries: kept.reverse(), droppedKeys: droppedKeys.reverse() };
300
+ }
473
301
 
474
- if (active.length === 0) {
475
- return { entries: [], droppedKeys: [...retiredKeys] };
476
- }
302
+ function usableConclusion(ev) {
303
+ const entries = sourceOf(ev)?.entries;
304
+ return layerOf(ev) === 'conclusion' && Array.isArray(entries)
305
+ && entries.every(e => typeof e?.key === 'string' && e.key.trim() && typeof e.text === 'string');
306
+ }
477
307
 
478
- const wrapperOverhead = renderConclusionsText([{ key: 'k', text: 'v' }]).length - renderConclusionLine({ key: 'k', text: 'v' }).length;
479
- const keptReversed = [];
480
- const evictedKeys = [];
481
- let usedChars = wrapperOverhead;
482
-
483
- for (let idx = active.length - 1; idx >= 0; idx -= 1) {
484
- const item = active[idx];
485
- const lineLen = renderConclusionLine(item).length + (keptReversed.length > 0 ? 1 : 0);
486
- if (keptReversed.length === 0 && usedChars + lineLen > maxConclusionChars) {
487
- // Single newest entry exceeds cap: truncate its text to fit within maxConclusionChars
488
- const prefixOverhead = wrapperOverhead + `- [${item.key}]: `.length;
489
- const available = Math.max(1, maxConclusionChars - prefixOverhead - 1);
490
- const truncatedText = item.text.length > available ? `${item.text.slice(0, Math.max(1, available - 1))}…` : item.text;
491
- keptReversed.push({ key: item.key, text: truncatedText });
492
- for (let older = idx - 1; older >= 0; older -= 1) {
493
- evictedKeys.push(active[older].key);
494
- }
495
- break;
496
- }
497
- if (usedChars + lineLen <= maxConclusionChars) {
498
- keptReversed.push(item);
499
- usedChars += lineLen;
500
- } else {
501
- for (let older = idx; older >= 0; older -= 1) {
502
- evictedKeys.push(active[older].key);
503
- }
504
- break;
308
+ function latestCompactionEnd(events) {
309
+ let open;
310
+ let end = -1;
311
+ for (const ev of events) {
312
+ if (ev.type === 'compaction/start') open = ev.data?.compactionId;
313
+ if (ev.type === 'session/end-seed') open = undefined;
314
+ if (ev.type === 'compaction/end') {
315
+ if (open && ev.data?.compactionId === open && ev.data.error === undefined) end = ev.seq;
316
+ open = undefined;
505
317
  }
506
318
  }
507
-
508
- keptReversed.reverse();
509
- return {
510
- entries: keptReversed,
511
- droppedKeys: [...new Set([...retiredKeys, ...evictedKeys.reverse()])],
512
- };
319
+ return end;
513
320
  }
514
321
 
515
- function entriesEquivalent(rawNodesEntries, compactedEntries) {
516
- if (rawNodesEntries.length !== 1) return false;
517
- const single = rawNodesEntries[0];
518
- if (!Array.isArray(single) || single.length !== compactedEntries.length) return false;
519
- for (let i = 0; i < single.length; i += 1) {
520
- if (single[i]?.key !== compactedEntries[i]?.key || single[i]?.text !== compactedEntries[i]?.text) {
521
- return false;
522
- }
523
- }
524
- return true;
322
+ function snapshotKind(ev) {
323
+ const s = sourceOf(ev);
324
+ if (s?.kind === 'runtime-context' && s.form === 'snapshot' && Array.isArray(s.sections)
325
+ && s.sections.every(x => typeof x?.name === 'string' && typeof x.text === 'string')) return s.kind;
326
+ if (s?.kind === 'skill-catalog' && s.form === 'catalog' && Array.isArray(s.entries)
327
+ && s.entries.every(x => typeof x?.name === 'string' && typeof x.description === 'string')) return s.kind;
328
+ return null;
525
329
  }
526
330
 
527
- export function compactConclusionsIfNeeded(
528
- session,
529
- config,
530
- { incomingMessages = [], now = Date.now(), onDiagnostic = () => {} } = {},
531
- ) {
331
+ export function compactConclusionsIfNeeded(session, config, { incomingMessages = [], now = Date.now(), onDiagnostic = () => {} } = {}) {
532
332
  const events = readSessionEvents(session);
533
- const layout = inspectLayers(session, events);
534
- const conclusionCount = layout.conclusionEndExclusive - layout.conclusionStartIdx;
535
- if (conclusionCount <= 0) return null;
536
-
537
- const surfaceChars = layout.surfaceEvents.reduce((sum, ev) => sum + charsOfSurfaceEvent(ev), 0);
538
- const incomingChars = (Array.isArray(incomingMessages) ? incomingMessages : [])
539
- .reduce((sum, msg) => sum + charsOfMessage(msg), 0);
540
- const totalChars = surfaceChars + incomingChars;
541
-
542
- const lastInteractionAt = lastModelInteractionTime(events);
543
- const idleElapsedMs = lastInteractionAt !== null ? now - lastInteractionAt : 0;
544
- const idleTriggered = lastInteractionAt !== null && idleElapsedMs >= config.idleMinutes * 60_000;
545
- const thresholdTriggered = totalChars >= config.compactChars;
546
-
547
- if (!idleTriggered && !thresholdTriggered) return null;
548
-
549
- const conclusionEvents = layout.surfaceEvents.slice(layout.conclusionStartIdx, layout.conclusionEndExclusive);
550
- const rawNodesEntries = conclusionEvents.map((ev) => (Array.isArray(ev?.data?.source?.entries) ? ev.data.source.entries : []));
551
- const { entries: compactedEntries, droppedKeys } = compactConclusionEntries(rawNodesEntries, config.maxConclusionChars);
552
-
553
- // Guard: skip no-op replace when already 1 node, no duplicates, no tombstones, and under cap
554
- if (entriesEquivalent(rawNodesEntries, compactedEntries)) {
555
- return null;
333
+ if (hasActiveCompaction(events)) return null;
334
+ const { nodes, surfaceEvents, cuts } = inspectLayers(session, events);
335
+ const lastTime = lastModelInteractionTime(events);
336
+ const idle = lastTime !== null && now - lastTime >= config.idleMinutes * 60_000;
337
+ const threshold = surfaceEvents.reduce((n, ev) => n + charsOfSurfaceEvent(ev), 0)
338
+ + incomingMessages.reduce((n, msg) => n + charsOfMessage(msg), 0) >= config.compactChars;
339
+ const hostEnd = latestCompactionEnd(events);
340
+ if (!idle && !threshold && hostEnd < 0) return null;
341
+
342
+ // One old successful host compaction must never authorize cleanup of future
343
+ // work. Only nodes already present at its end participate in that pass.
344
+ const largeCutoff = idle ? Infinity : hostEnd;
345
+ const conclusionCutoff = threshold ? Infinity : largeCutoff;
346
+ const stale = new Set();
347
+ const staleEmbeddedObjectives = new Set();
348
+ const seenSnapshots = new Set();
349
+ let newerObjective = false;
350
+ for (let i = nodes.length - 1; i >= 0; i--) {
351
+ if (nodes[i] > largeCutoff) continue;
352
+ const ev = surfaceEvents[i];
353
+ const kind = snapshotKind(ev);
354
+ if (kind) {
355
+ if (seenSnapshots.has(kind)) stale.add(i);
356
+ // Incomplete discovery is not affirmative evidence of a complete replacement.
357
+ if (sourceOf(ev).incomplete !== true) seenSnapshots.add(kind);
358
+ }
359
+ if (storedObjective(ev)) {
360
+ if (newerObjective) {
361
+ if (layerOf(ev) === 'objective') stale.add(i);
362
+ else staleEmbeddedObjectives.add(i);
363
+ }
364
+ newerObjective = true;
365
+ }
556
366
  }
557
367
 
558
- const beforeChars = conclusionEvents.reduce((sum, ev) => sum + charsOfSurfaceEvent(ev), 0);
559
- const compactedMsg = buildConclusionMessage(compactedEntries, now);
560
- const afterChars = charsOfMessage(compactedMsg);
561
- const conclusionSeqs = layout.nodes.slice(layout.conclusionStartIdx, layout.conclusionEndExclusive);
562
- const firstConclusionSeq = conclusionSeqs[0];
563
- const lastConclusionSeq = conclusionSeqs[conclusionSeqs.length - 1];
564
-
565
- session.append('user/message', compactedMsg, {
566
- surfaceOp: { op: 'replace', startSeq: firstConclusionSeq, endSeq: lastConclusionSeq },
567
- sourceEventSeqs: conclusionSeqs,
568
- });
569
-
570
- const reason = thresholdTriggered ? 'threshold' : 'idle';
571
- onDiagnostic({
572
- event: 'compacted',
573
- sessionId: session?.id ?? null,
574
- reason,
575
- beforeNodes: conclusionCount,
576
- afterNodes: 1,
577
- beforeChars,
578
- afterChars,
579
- removedKeys: droppedKeys,
580
- });
581
-
582
- return {
583
- reason,
584
- beforeNodes: conclusionCount,
585
- afterNodes: 1,
586
- beforeChars,
587
- afterChars,
588
- removedKeys: droppedKeys,
589
- };
590
- }
368
+ const conclusionIndices = [];
369
+ for (let i = 0; i < nodes.length; i++) {
370
+ if (layerOf(surfaceEvents[i]) !== 'conclusion') continue;
371
+ // Never purge a retirement or evict an older version without seeing all
372
+ // records that participate in last-write-wins, including legacy records.
373
+ if (!usableConclusion(surfaceEvents[i]) || !cuts[i] || !cuts[i + 1]) return null;
374
+ if (nodes[i] > conclusionCutoff) continue;
375
+ conclusionIndices.push(i);
376
+ }
377
+ const raw = conclusionIndices.map(i => sourceOf(surfaceEvents[i]).entries);
378
+ const { entries, droppedKeys } = compactConclusionEntries(raw, config.maxConclusionChars);
379
+ const lastOwner = new Map();
380
+ for (const i of conclusionIndices) for (const e of sourceOf(surfaceEvents[i]).entries) lastOwner.set(e.key, i);
381
+ const retained = new Map();
382
+ for (const entry of entries) {
383
+ const i = lastOwner.get(entry.key);
384
+ if (!retained.has(i)) retained.set(i, []);
385
+ retained.get(i).push(entry);
386
+ }
591
387
 
592
- export function evaluateUnconvertedNudge(
593
- session,
594
- decisionMessages,
595
- config,
596
- { onDiagnostic = () => {} } = {},
597
- ) {
598
- const events = readSessionEvents(session);
599
- const layout = inspectLayers(session, events);
600
- const unconvertedEvents = layout.surfaceEvents.slice(layout.unconvertedStartIdx);
601
-
602
- const surfaceUnconvertedChars = unconvertedEvents.reduce((sum, ev) => sum + charsOfSurfaceEvent(ev), 0);
603
- const incomingChars = (Array.isArray(decisionMessages) ? decisionMessages : [])
604
- .reduce((sum, msg) => sum + charsOfMessage(msg), 0);
605
- const unconvertedChars = surfaceUnconvertedChars + incomingChars;
606
-
607
- // Check if a nudge already exists in the unconverted layer (either on surface or in decisionMessages)
608
- let lastNudgeIdx = -1;
609
- for (let i = unconvertedEvents.length - 1; i >= 0; i -= 1) {
610
- const ev = unconvertedEvents[i];
611
- if (ev?.type === 'user/message' && ev.data?.source?.kind === FOCUS_SOURCE_KIND && ev.data?.source?.layer === 'nudge') {
612
- lastNudgeIdx = i;
613
- break;
388
+ const eligible = new Set([...conclusionIndices, ...stale]);
389
+ const inputs = [];
390
+ let beforeNodes = 0, beforeChars = 0;
391
+ for (let i = 0; i < nodes.length;) {
392
+ if (!eligible.has(i) || !cuts[i] || !cuts[i + 1]) { i++; continue; }
393
+ const start = i;
394
+ const group = [];
395
+ let hasConclusion = false, objective = null;
396
+ do {
397
+ const ev = surfaceEvents[i];
398
+ if (usableConclusion(ev)) {
399
+ hasConclusion = true;
400
+ if (!staleEmbeddedObjectives.has(i)) objective = storedObjective(ev) ?? objective;
401
+ for (const entry of retained.get(i) ?? []) group.push(entry);
402
+ }
403
+ i++;
404
+ } while (i < nodes.length && eligible.has(i) && cuts[i] && cuts[i + 1]);
405
+ if (i === start + 1 && hasConclusion && !staleEmbeddedObjectives.has(start)) {
406
+ const old = sourceOf(surfaceEvents[start]).entries;
407
+ if (old.length === group.length && old.every((e, k) => e.key === group[k].key && e.text === group[k].text)) continue;
614
408
  }
409
+ const message = hasConclusion ? conclusionMessage(group, now, objective) : {
410
+ ...buildConclusionMessage([], now),
411
+ content: [{ type: 'text', text: '[Superseded context omitted.]' }],
412
+ source: { kind: FOCUS_SOURCE_KIND, layer: 'superseded' },
413
+ };
414
+ inputs.push(replaceInput(nodes, start, i - 1, message));
415
+ beforeNodes += i - start;
416
+ for (let j = start; j < i; j++) beforeChars += charsOfSurfaceEvent(surfaceEvents[j]);
615
417
  }
616
- const decisionHasNudge = (Array.isArray(decisionMessages) ? decisionMessages : []).some(
617
- (msg) => msg?.source?.kind === FOCUS_SOURCE_KIND && msg?.source?.layer === 'nudge',
618
- );
619
- if (decisionHasNudge) return null;
620
-
621
- if (lastNudgeIdx === -1) {
622
- if (unconvertedChars < config.nudgeChars) return null;
623
- } else {
624
- const charsSinceLastNudge = unconvertedEvents
625
- .slice(lastNudgeIdx + 1)
626
- .reduce((sum, ev) => sum + charsOfSurfaceEvent(ev), 0) + incomingChars;
627
- const repeatStep = Math.max(8000, Math.floor(config.nudgeChars / 2));
628
- if (charsSinceLastNudge < repeatStep) return null;
629
- }
418
+ if (!inputs.length) return null;
419
+ session.append(inputs);
420
+ const result = { reason: idle ? 'idle' : threshold ? 'threshold' : 'host-compaction', beforeNodes, afterNodes: inputs.length,
421
+ beforeChars, afterChars: inputs.reduce((n, [, msg]) => n + charsOfMessage(msg), 0), removedKeys: droppedKeys };
422
+ onDiagnostic({ event: 'compacted', sessionId: session.id, ...result });
423
+ return result;
424
+ }
630
425
 
631
- const nudgeMessage = buildNudgeMessage();
632
- onDiagnostic({
633
- event: 'nudged',
634
- sessionId: session?.id ?? null,
635
- unconvertedChars,
636
- nudgeChars: config.nudgeChars,
637
- });
638
- return nudgeMessage;
426
+ export function evaluateUnconvertedNudge(session, decisionMessages, config, { onDiagnostic = () => {} } = {}) {
427
+ const { surfaceEvents, unconvertedStartIdx } = inspectLayers(session);
428
+ const work = surfaceEvents.slice(unconvertedStartIdx);
429
+ const incoming = Array.isArray(decisionMessages) ? decisionMessages : [];
430
+ if (incoming.some(msg => msg?.source?.kind === FOCUS_SOURCE_KIND && msg.source.layer === 'nudge')) return null;
431
+ const incomingChars = incoming.reduce((n, msg) => n + charsOfMessage(msg), 0);
432
+ const lastNudge = work.findLastIndex(ev => layerOf(ev) === 'nudge');
433
+ const unconvertedChars = work.reduce((n, ev) => n + charsOfSurfaceEvent(ev), incomingChars);
434
+ if (lastNudge < 0 ? unconvertedChars < config.nudgeChars :
435
+ work.slice(lastNudge + 1).reduce((n, ev) => n + charsOfSurfaceEvent(ev), incomingChars) < Math.max(8000, Math.floor(config.nudgeChars / 2))) return null;
436
+ onDiagnostic({ event: 'nudged', sessionId: session.id, unconvertedChars, nudgeChars: config.nudgeChars });
437
+ return buildNudgeMessage();
639
438
  }
640
439
 
641
- export function createPreStepHandler({
642
- loadConfig,
643
- allowed,
644
- now = () => Date.now(),
645
- onDiagnostic = () => {},
646
- }) {
440
+ export function createPreStepHandler({ loadConfig, allowed, now = () => Date.now(), onDiagnostic = () => {} }) {
647
441
  return async (payload, next) => {
648
442
  const { agent, messages, turn, step, signal } = payload ?? {};
649
- if (!agent?.session || signal?.aborted || !allowed(agent)) {
650
- return next();
651
- }
652
-
653
- const session = agent.session;
654
- const initialEvents = readSessionEvents(session);
655
- if (hasActiveCompaction(initialEvents)) {
656
- return next();
657
- }
658
-
443
+ if (!agent?.session || signal?.aborted || !allowed(agent)) return next();
444
+ const { session } = agent;
445
+ if (hasActiveCompaction(readSessionEvents(session))) return next();
446
+ const report = (event, error) => onDiagnostic({ event, sessionId: session.id, message: String(error?.message ?? error) });
659
447
  let config;
660
- try {
661
- config = loadConfig();
662
- } catch (error) {
663
- onDiagnostic({
664
- event: 'config-error',
665
- sessionId: session.id ?? null,
666
- message: String(error?.message ?? error),
667
- });
668
- return next();
669
- }
670
-
671
- let deferredObjectiveMessage = null;
672
- const currentNow = now();
673
-
674
- // Stage A: Fold completed focus_conclude call(s) before inner pre-step listeners inspect surface
675
- try {
676
- const folded = foldPendingConclusions(session, {
677
- now: currentNow,
678
- turn,
679
- step,
680
- onDiagnostic,
681
- });
682
- if (folded?.deferredObjectiveMessage) {
683
- deferredObjectiveMessage = folded.deferredObjectiveMessage;
684
- }
685
- } catch (error) {
686
- onDiagnostic({
687
- event: 'fold-error',
688
- sessionId: session.id ?? null,
689
- message: String(error?.message ?? error),
690
- });
691
- }
692
-
693
- // Stage B: Deterministic conclusion-layer compaction on threshold or idle timeout
694
- try {
695
- compactConclusionsIfNeeded(session, config, {
696
- incomingMessages: messages,
697
- now: currentNow,
698
- onDiagnostic,
699
- });
700
- } catch (error) {
701
- onDiagnostic({
702
- event: 'compact-error',
703
- sessionId: session.id ?? null,
704
- message: String(error?.message ?? error),
705
- });
706
- }
707
-
448
+ try { config = loadConfig(); } catch (error) { report('config-error', error); return next(); }
449
+ const time = now();
450
+ try { foldPendingConclusions(session, { now: time, turn, step, onDiagnostic }); }
451
+ catch (error) { report('fold-error', error); }
452
+ try { compactConclusionsIfNeeded(session, config, { incomingMessages: messages, now: time, onDiagnostic }); }
453
+ catch (error) { report('compact-error', error); }
708
454
  const decision = await next();
709
- if (!decision || decision.kind === 'reject' || signal?.aborted) {
710
- return decision;
711
- }
712
-
713
- let nextMessages = Array.isArray(decision.messages) ? decision.messages : [];
714
- let mutated = false;
715
-
716
- if (deferredObjectiveMessage) {
717
- nextMessages = [...nextMessages, deferredObjectiveMessage];
718
- mutated = true;
719
- }
720
-
721
- // Stage C: Unconverted layer thickness nudge
455
+ if (!decision || decision.kind === 'reject' || signal?.aborted) return decision;
722
456
  try {
723
- const nudge = evaluateUnconvertedNudge(session, nextMessages, config, { onDiagnostic });
724
- if (nudge) {
725
- nextMessages = [...nextMessages, nudge];
726
- mutated = true;
727
- }
728
- } catch (error) {
729
- onDiagnostic({
730
- event: 'nudge-error',
731
- sessionId: session.id ?? null,
732
- message: String(error?.message ?? error),
733
- });
734
- }
735
-
736
- return mutated ? { ...decision, messages: nextMessages } : decision;
457
+ const nudge = evaluateUnconvertedNudge(session, decision.messages, config, { onDiagnostic });
458
+ if (nudge) return { ...decision, messages: [...decision.messages, nudge] };
459
+ } catch (error) { report('nudge-error', error); }
460
+ return decision;
737
461
  };
738
462
  }
package/src/tools.mjs CHANGED
@@ -114,7 +114,7 @@ export function createFocusConcludeTool({ onDiagnostic = () => {} } = {}) {
114
114
  return {
115
115
  name: FOCUS_TOOL_NAME,
116
116
  description:
117
- 'Stack concise conclusions onto the main-session conclusion layer and fold consumed raw search or file-editing steps before the next request, keeping the prompt prefix cache intact. Must be called alone without any sibling tool calls in the same response.',
117
+ 'Record conclusions that replace a completed span of work. Call this tool alone, after all tool results you need have arrived.',
118
118
  parameters: {
119
119
  type: 'object',
120
120
  additionalProperties: false,
@@ -122,7 +122,7 @@ export function createFocusConcludeTool({ onDiagnostic = () => {} } = {}) {
122
122
  properties: {
123
123
  conclusions: {
124
124
  type: 'array',
125
- description: 'Conclusions to stack onto the conclusion layer (1..32 items). Each item sets or updates a slot key; pass text: "" to retire an obsolete key.',
125
+ description: 'One to 32 entries, each setting or updating a key.',
126
126
  items: {
127
127
  type: 'object',
128
128
  additionalProperties: false,
@@ -130,7 +130,7 @@ export function createFocusConcludeTool({ onDiagnostic = () => {} } = {}) {
130
130
  properties: {
131
131
  key: {
132
132
  type: 'string',
133
- description: "Short slot identifier for same-slot supersession, e.g. 'wake.timer' or 'file.rpc'.",
133
+ description: "Stable name for the finding, e.g. 'file.rpc'. Reuse it to update the finding.",
134
134
  },
135
135
  text: {
136
136
  type: 'string',
@@ -141,7 +141,7 @@ export function createFocusConcludeTool({ onDiagnostic = () => {} } = {}) {
141
141
  },
142
142
  objective: {
143
143
  type: 'string',
144
- description: 'Optional single current objective for the next step. Omit or pass "" to carry forward the active user request.',
144
+ description: 'Optional standalone sentence naming the current task and next action. Omit or pass "" to keep the current task; do not replace it with "continue". User instructions take precedence.',
145
145
  },
146
146
  },
147
147
  },