@cortex-agent/server 2026.9.21 → 2026.9.25

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 (139) hide show
  1. package/defaults/config/thread-templates/agents/creative.json +17 -0
  2. package/defaults/prompts/systemPrompts/creative.md +13 -0
  3. package/defaults/prompts/systemPrompts/direct.md +1 -1
  4. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  5. package/dist/agent-adapter/claude/adapter.js +19 -1
  6. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  7. package/dist/agent-adapter/claude/spawn-args.js +10 -0
  8. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  9. package/dist/agent-adapter/pi/child-runner.js +5 -1
  10. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  11. package/dist/agent-adapter/pi/event-parser.js +46 -2
  12. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  13. package/dist/agent-adapter/pi/extensions.js +10 -3
  14. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  15. package/dist/agent-adapter/pi/pi-session.js +5 -0
  16. package/dist/agent-adapter/pi/runtime.js +3 -0
  17. package/dist/agent-adapter/pi/session-options.js +5 -1
  18. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  19. package/dist/agent-adapter/pi/subagent.js +18 -0
  20. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  21. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  22. package/dist/agent-adapter/types.d.ts +5 -0
  23. package/dist/core/agents/subagent/types.d.ts +3 -0
  24. package/dist/core/config-generator.js +17 -2
  25. package/dist/core/debug-mode.d.ts +11 -10
  26. package/dist/core/debug-mode.js +12 -18
  27. package/dist/core/exec-async.d.ts +26 -0
  28. package/dist/core/exec-async.js +47 -0
  29. package/dist/core/locales/en.d.ts +14 -1
  30. package/dist/core/locales/slices/commands.d.ts +12 -1
  31. package/dist/core/locales/slices/commands.js +24 -2
  32. package/dist/core/locales/slices/startup.d.ts +2 -0
  33. package/dist/core/locales/slices/startup.js +4 -0
  34. package/dist/core/rebuild-progress.d.ts +58 -0
  35. package/dist/core/rebuild-progress.js +103 -0
  36. package/dist/core/resilient-watch.js +5 -3
  37. package/dist/core/run-registry.d.ts +7 -0
  38. package/dist/core/run-registry.js +6 -0
  39. package/dist/core/types/thread-types.d.ts +23 -4
  40. package/dist/domain/agents/agent-state.d.ts +7 -0
  41. package/dist/domain/agents/agent-state.js +9 -1
  42. package/dist/domain/agents/agent-switch.d.ts +38 -0
  43. package/dist/domain/agents/agent-switch.js +106 -0
  44. package/dist/domain/agents/config.d.ts +20 -2
  45. package/dist/domain/agents/config.js +58 -4
  46. package/dist/domain/agents/index.d.ts +1 -0
  47. package/dist/domain/agents/index.js +1 -0
  48. package/dist/domain/agents/profile-manager.d.ts +6 -0
  49. package/dist/domain/agents/profile-manager.js +14 -1
  50. package/dist/domain/executions/registry.d.ts +2 -0
  51. package/dist/domain/executions/registry.js +84 -7
  52. package/dist/domain/plugins/runtime.js +1 -1
  53. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  54. package/dist/domain/plugins/skill-projection.js +76 -19
  55. package/dist/domain/remote/client-bootstrap.js +1 -1
  56. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  57. package/dist/domain/remote/client-hot-reload.js +27 -23
  58. package/dist/domain/runs/engine-spec.js +4 -0
  59. package/dist/domain/runs/request.d.ts +6 -0
  60. package/dist/domain/runs/run.js +1 -0
  61. package/dist/domain/runs/spec-loader.d.ts +4 -3
  62. package/dist/domain/runs/spec-loader.js +4 -3
  63. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  64. package/dist/domain/scheduling/scheduler.js +14 -12
  65. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  66. package/dist/domain/sessions/session-lifecycle.js +13 -1
  67. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  68. package/dist/domain/system/rebuild-hold.js +91 -0
  69. package/dist/domain/system/server-update-check.d.ts +2 -1
  70. package/dist/domain/system/server-update-check.js +15 -13
  71. package/dist/domain/tasks/archiver.js +21 -13
  72. package/dist/domain/tasks/mutator.js +60 -59
  73. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  74. package/dist/domain/tasks/system/task-completion.js +69 -6
  75. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  76. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  77. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  78. package/dist/domain/tasks/system/task-lock.js +29 -1
  79. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  80. package/dist/domain/tasks/system/task-mutations.js +25 -2
  81. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  82. package/dist/domain/tasks/system/task-state.js +19 -2
  83. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  84. package/dist/domain/threads/prompt-builder.js +28 -10
  85. package/dist/domain/threads/runner.js +7 -3
  86. package/dist/domain/threads/state-machine.js +15 -11
  87. package/dist/domain/threads/template-loader.js +6 -4
  88. package/dist/domain/threads/template-validate.d.ts +43 -6
  89. package/dist/domain/threads/template-validate.js +12 -0
  90. package/dist/domain/ui-service/app-router.d.ts +10 -0
  91. package/dist/domain/ui-service/app-router.js +2 -1
  92. package/dist/domain/ui-service/input-schemas.d.ts +11 -0
  93. package/dist/domain/ui-service/input-schemas.js +11 -0
  94. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  95. package/dist/domain/ui-service/mutate/sessions.js +40 -0
  96. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  97. package/dist/domain/ui-service/query/config.js +19 -1
  98. package/dist/domain/ui-service/query/memory.js +28 -34
  99. package/dist/domain/ui-service/query/sessions.js +89 -12
  100. package/dist/domain/ui-service/query/system.js +19 -0
  101. package/dist/domain/ui-service/query-input-schemas.d.ts +1 -0
  102. package/dist/domain/ui-service/query-input-schemas.js +2 -0
  103. package/dist/domain/ui-service/types.d.ts +97 -3
  104. package/dist/domain/ui-service/ui-service.js +2 -1
  105. package/dist/entry/app.js +23 -4
  106. package/dist/entry/daemon-notice.d.ts +10 -1
  107. package/dist/entry/daemon-notice.js +16 -1
  108. package/dist/entry/daemon.d.ts +43 -2
  109. package/dist/entry/daemon.js +163 -9
  110. package/dist/orchestration/agent-runner.js +16 -0
  111. package/dist/orchestration/conversation-request.d.ts +33 -0
  112. package/dist/orchestration/conversation-request.js +78 -16
  113. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  114. package/dist/orchestration/mid-turn-inject.js +9 -4
  115. package/dist/orchestration/resume-dispatcher.js +4 -2
  116. package/dist/orchestration/routing/commands/mode.js +114 -63
  117. package/dist/orchestration/thread-executor.js +13 -0
  118. package/dist/orchestration/turn/turn.js +1 -0
  119. package/dist/store/conversation-display-projection.d.ts +9 -1
  120. package/dist/store/conversation-display-projection.js +13 -6
  121. package/dist/store/conversation-history-reader.d.ts +19 -0
  122. package/dist/store/conversation-history-reader.js +163 -44
  123. package/dist/store/conversation-history-repo.d.ts +37 -10
  124. package/dist/store/conversation-history-repo.js +161 -139
  125. package/dist/store/session-registry-journal.d.ts +4 -0
  126. package/dist/store/session-registry-journal.js +4 -0
  127. package/dist/store/session-registry-repo.d.ts +2 -1
  128. package/dist/store/session-registry-repo.js +2 -0
  129. package/dist/store/task-repo.d.ts +6 -3
  130. package/dist/store/task-repo.js +26 -10
  131. package/package.json +2 -1
  132. package/web/dist/AGENTS.md +10 -0
  133. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  134. package/web/dist/assets/{index-DZTuqUO4.js → index-BAeLybF0.js} +1 -1
  135. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  136. package/web/dist/index.html +12 -4
  137. package/web/dist/theme.css +211 -40
  138. package/web/dist/assets/index-CwwQNMpP.css +0 -1
  139. package/web/dist/assets/index-DLSfgq3o.js +0 -444
@@ -1,9 +1,10 @@
1
1
  import { createReadStream } from 'fs';
2
- import { createInterface } from 'node:readline';
3
- import { debugToolWarningChars, isDebugToolOverWarningThreshold } from '../core/debug-mode.js';
2
+ import { isOverDebugToolWarningChars } from '../core/debug-mode.js';
4
3
  function createParseState(options) {
5
4
  return {
6
5
  events: [],
6
+ revs: [],
7
+ revision: 0,
7
8
  committedSourceIds: new Set(),
8
9
  subagentEnds: new Map(),
9
10
  interactionById: new Map(),
@@ -15,6 +16,23 @@ function createParseState(options) {
15
16
  includeToolDebug: options.includeToolDebug !== false,
16
17
  };
17
18
  }
19
+ /** Append a row and stamp it with a fresh revision. Returns the row's index. */
20
+ function pushEvent(state, event) {
21
+ state.events.push(event);
22
+ state.revs.push(++state.revision);
23
+ return state.events.length - 1;
24
+ }
25
+ /** Re-stamp a row that an already-folded line reached back and changed. */
26
+ function touchEvent(state, index) {
27
+ if (index < 0 || index >= state.revs.length)
28
+ return;
29
+ state.revs[index] = ++state.revision;
30
+ }
31
+ /** Record a change that belongs to the model as a whole rather than to one row
32
+ * (subagent ends, committed source ids) — the projection is derived, so it must re-run. */
33
+ function touchModel(state) {
34
+ state.revision += 1;
35
+ }
18
36
  function isPrefixRelated(a, b) {
19
37
  return a.startsWith(b) || b.startsWith(a);
20
38
  }
@@ -54,9 +72,11 @@ function noteLargeToolResult(state, line) {
54
72
  if (state.includeToolDebug || !line.startsWith('{"type":"debug-tool-result"'))
55
73
  return false;
56
74
  const ref = debugResultToolRef(line);
57
- const tool = ref ? state.toolByUseId.get(ref) : undefined;
58
- if (tool && line.length > debugToolWarningChars()) {
75
+ const index = ref ? state.toolByUseId.get(ref) : undefined;
76
+ const tool = index === undefined ? undefined : state.events[index];
77
+ if (tool && isOverDebugToolWarningChars(line.length)) {
59
78
  tool.debug = { ...(tool.debug ?? {}), overCharacterThreshold: true };
79
+ touchEvent(state, index);
60
80
  }
61
81
  return true;
62
82
  }
@@ -71,25 +91,32 @@ function consumeSubagentEnd(state, ev) {
71
91
  if (state.subagentEnds.has(ev.subagentId))
72
92
  return;
73
93
  state.subagentEnds.set(ev.subagentId, ev.subagentEnded);
94
+ touchModel(state);
74
95
  }
75
96
  function consumeDebugPrompt(state, ev) {
76
- if (!state.lastUser || ev.agentMessage === undefined)
97
+ if (state.lastUser === null || ev.agentMessage === undefined)
77
98
  return;
78
- state.lastUser.debug = { ...(state.lastUser.debug ?? {}), agentMessage: ev.agentMessage };
99
+ const user = state.events[state.lastUser];
100
+ user.debug = { ...(user.debug ?? {}), agentMessage: ev.agentMessage };
101
+ touchEvent(state, state.lastUser);
79
102
  }
80
103
  function consumeDebugToolResult(state, ev) {
81
- const tool = ev.toolUseId ? state.toolByUseId.get(ev.toolUseId) : undefined;
82
- if (!tool)
104
+ const index = ev.toolUseId ? state.toolByUseId.get(ev.toolUseId) : undefined;
105
+ if (index === undefined)
83
106
  return;
107
+ const tool = state.events[index];
84
108
  tool.debug = {
85
109
  ...(tool.debug ?? {}),
86
110
  toolResult: { content: ev.text ?? '', isError: ev.isError === true },
87
111
  };
112
+ touchEvent(state, index);
88
113
  }
89
114
  function pushUser(state, ev) {
90
115
  state.turnIndex += 1;
91
- if (ev.sourceId)
116
+ if (ev.sourceId) {
92
117
  state.committedSourceIds.add(ev.sourceId);
118
+ touchModel(state);
119
+ }
93
120
  const user = {
94
121
  type: 'user',
95
122
  text: ev.text ?? '',
@@ -100,12 +127,12 @@ function pushUser(state, ev) {
100
127
  ...(state.pendingEdit ? { edited: state.pendingEdit } : {}),
101
128
  ...(ev.agentMessage !== undefined ? { debug: { agentMessage: ev.agentMessage } } : {}),
102
129
  };
103
- state.events.push(user);
104
- state.lastUser = user;
130
+ state.lastUser = pushEvent(state, user);
105
131
  state.pendingEdit = null;
106
132
  }
107
133
  function canCollapseAssistant(state, ev) {
108
- const last = state.events[state.events.length - 1];
134
+ const index = state.events.length - 1;
135
+ const last = state.events[index];
109
136
  const text = ev.text ?? '';
110
137
  const hasAttachments = ev.attachments !== undefined;
111
138
  const hasDecisions = ev.decisions !== undefined && ev.decisions.length > 0;
@@ -117,22 +144,24 @@ function canCollapseAssistant(state, ev) {
117
144
  return null;
118
145
  if (last.subagentId !== ev.subagentId || typeof last.text !== 'string')
119
146
  return null;
120
- return isPrefixRelated(last.text, text) ? last : null;
147
+ return isPrefixRelated(last.text, text) ? index : null;
121
148
  }
122
149
  function pushAssistant(state, ev) {
123
- const existing = canCollapseAssistant(state, ev);
150
+ const collapseInto = canCollapseAssistant(state, ev);
124
151
  const text = ev.text ?? '';
125
- if (existing) {
152
+ if (collapseInto !== null) {
153
+ const existing = state.events[collapseInto];
126
154
  if (text.length >= existing.text.length) {
127
155
  existing.text = text;
128
156
  existing.ts = ev.ts;
157
+ touchEvent(state, collapseInto);
129
158
  }
130
159
  return;
131
160
  }
132
161
  const decisions = ev.decisions?.length
133
162
  ? ev.decisions.map((decision) => ({ ...decision, actions: [] }))
134
163
  : undefined;
135
- state.events.push({
164
+ const index = pushEvent(state, {
136
165
  type: 'assistant',
137
166
  text,
138
167
  ts: ev.ts,
@@ -145,11 +174,14 @@ function pushAssistant(state, ev) {
145
174
  ...subagentFields(ev),
146
175
  });
147
176
  for (const decision of decisions ?? [])
148
- state.decisionById.set(decision.id, decision);
177
+ state.decisionById.set(decision.id, { index, decision });
149
178
  }
150
- function toolDebug(state, ev) {
151
- const warned = !state.includeToolDebug && ev.fullInput !== undefined
152
- && isDebugToolOverWarningThreshold({ toolInput: ev.fullInput });
179
+ /** `chars` is the length of the JSON line this event was parsed from — see
180
+ * `isOverDebugToolWarningChars`. The verdict is stamped on DEBUG and plain reads alike: the fold
181
+ * is the only place that still holds the row's own bytes, so stamping here is what lets every
182
+ * reader downstream trust the flag instead of re-deriving it from the parsed input. */
183
+ function toolDebug(state, ev, chars) {
184
+ const warned = ev.fullInput !== undefined && isOverDebugToolWarningChars(chars);
153
185
  if (!ev.toolUseId && !warned && (!state.includeToolDebug || ev.fullInput === undefined))
154
186
  return undefined;
155
187
  return {
@@ -158,8 +190,8 @@ function toolDebug(state, ev) {
158
190
  ...(warned ? { overCharacterThreshold: true } : {}),
159
191
  };
160
192
  }
161
- function pushTool(state, ev) {
162
- const debug = toolDebug(state, ev);
193
+ function pushTool(state, ev, chars) {
194
+ const debug = toolDebug(state, ev, chars);
163
195
  const tool = {
164
196
  type: 'tool',
165
197
  toolName: ev.toolName ?? '',
@@ -171,9 +203,9 @@ function pushTool(state, ev) {
171
203
  ...(ev.subagentSpawns?.length ? { subagentSpawns: ev.subagentSpawns } : {}),
172
204
  ...subagentFields(ev),
173
205
  };
174
- state.events.push(tool);
206
+ const index = pushEvent(state, tool);
175
207
  if (ev.toolUseId)
176
- state.toolByUseId.set(ev.toolUseId, tool);
208
+ state.toolByUseId.set(ev.toolUseId, index);
177
209
  }
178
210
  function mergeResolvedInteraction(prior, ev) {
179
211
  prior.status = ev.status;
@@ -187,12 +219,13 @@ function mergeResolvedInteraction(prior, ev) {
187
219
  }
188
220
  function pushInteraction(state, ev) {
189
221
  if (!ev.id) {
190
- state.events.push({ type: 'interaction', subtype: ev.subtype, text: ev.text ?? '', ts: ev.ts, turnIndex: turnFor(state) });
222
+ pushEvent(state, { type: 'interaction', subtype: ev.subtype, text: ev.text ?? '', ts: ev.ts, turnIndex: turnFor(state) });
191
223
  return;
192
224
  }
193
- const prior = state.interactionById.get(ev.id);
194
- if (prior && ev.status && ev.status !== 'pending') {
195
- mergeResolvedInteraction(prior, ev);
225
+ const priorIndex = state.interactionById.get(ev.id);
226
+ if (priorIndex !== undefined && ev.status && ev.status !== 'pending') {
227
+ mergeResolvedInteraction(state.events[priorIndex], ev);
228
+ touchEvent(state, priorIndex);
196
229
  return;
197
230
  }
198
231
  const interaction = {
@@ -207,20 +240,20 @@ function pushInteraction(state, ev) {
207
240
  ts: ev.ts,
208
241
  turnIndex: turnFor(state),
209
242
  };
210
- state.events.push(interaction);
211
- state.interactionById.set(ev.id, interaction);
243
+ state.interactionById.set(ev.id, pushEvent(state, interaction));
212
244
  }
213
245
  function consumeDecisionAction(state, ev) {
214
246
  const target = ev.decisionId ? state.decisionById.get(ev.decisionId) : undefined;
215
247
  if (!target || !ev.action)
216
248
  return;
217
- target.actions.push({
249
+ target.decision.actions.push({
218
250
  action: ev.action,
219
251
  ...(ev.message !== undefined ? { message: ev.message } : {}),
220
252
  ts: ev.ts,
221
253
  });
254
+ touchEvent(state, target.index);
222
255
  }
223
- function consumeParsedEvent(state, ev) {
256
+ function consumeParsedEvent(state, ev, chars) {
224
257
  if (ev.type === 'edit-marker')
225
258
  return consumeEditMarker(state, ev);
226
259
  if (ev.type === 'subagent-end')
@@ -236,7 +269,7 @@ function consumeParsedEvent(state, ev) {
236
269
  if (ev.type === 'assistant')
237
270
  return pushAssistant(state, ev);
238
271
  if (ev.type === 'tool')
239
- return pushTool(state, ev);
272
+ return pushTool(state, ev, chars);
240
273
  pushInteraction(state, ev);
241
274
  }
242
275
  function finishHistory(sessionId, state) {
@@ -254,13 +287,92 @@ async function consumeHistoryIterable(accumulator, lines) {
254
287
  accumulator.consumeLine(line);
255
288
  return accumulator;
256
289
  }
290
+ const NEWLINE = 0x0a;
291
+ const CARRIAGE_RETURN = 0x0d;
292
+ /**
293
+ * Fold a JSONL file into `accumulator`, starting at its byte cursor, and stop at the last COMPLETE
294
+ * line. Deliberately byte-level rather than `readline`:
295
+ *
296
+ * - The cursor has to be exact. It is what makes the next read resume instead of re-parsing the
297
+ * whole file, and `readline` reports lines, not byte offsets.
298
+ * - A concurrent append can be observed half-written (a multi-megabyte tool result is not one
299
+ * atomic write). `readline` would hand that fragment over as if it were a line and the cursor
300
+ * would step past it, losing the row for good. Stopping at the last newline leaves the fragment
301
+ * for the next read, which sees it whole.
302
+ *
303
+ * Splitting on the newline BYTE is safe for UTF-8: 0x0A cannot occur inside a multi-byte sequence.
304
+ */
305
+ async function foldFileInto(accumulator, filePath, start) {
306
+ const stream = createReadStream(filePath, { start });
307
+ /** Pieces of a line whose newline has not arrived yet, kept UNJOINED until it does. Re-joining
308
+ * the tail onto every chunk instead is quadratic in the line's length, and a row here is a whole
309
+ * tool result: the largest in this store is 43MB, which that shape folds in 3.6 minutes against
310
+ * 1.8 seconds for one join at the end. Rows are joined once, when their newline lands. */
311
+ let pending = [];
312
+ let pendingBytes = 0;
313
+ let consumed = start;
314
+ try {
315
+ for await (const chunk of stream) {
316
+ let from = 0;
317
+ for (;;) {
318
+ // Only the new chunk is searched: everything before it has already been scanned.
319
+ const nl = chunk.indexOf(NEWLINE, from);
320
+ if (nl < 0)
321
+ break;
322
+ let line;
323
+ if (pendingBytes > 0) {
324
+ pending.push(chunk.subarray(from, nl));
325
+ line = Buffer.concat(pending, pendingBytes + (nl - from));
326
+ pending = [];
327
+ pendingBytes = 0;
328
+ }
329
+ else {
330
+ line = chunk.subarray(from, nl);
331
+ }
332
+ consumed += line.length + 1;
333
+ const end = line.length > 0 && line[line.length - 1] === CARRIAGE_RETURN
334
+ ? line.length - 1 : line.length; // tolerate CRLF
335
+ accumulator.consumeLine(line.toString('utf8', 0, end));
336
+ from = nl + 1;
337
+ }
338
+ if (from < chunk.length) {
339
+ const tail = chunk.subarray(from);
340
+ pending.push(tail);
341
+ pendingBytes += tail.length;
342
+ }
343
+ }
344
+ }
345
+ finally {
346
+ accumulator.advanceCursor(consumed);
347
+ stream.destroy();
348
+ }
349
+ }
257
350
  export class ConversationHistoryAccumulator {
258
351
  sessionId;
259
352
  state;
353
+ /** Byte offset of the first byte of the file NOT yet folded in. */
354
+ cursor = 0;
260
355
  constructor(sessionId, options = {}) {
261
356
  this.sessionId = sessionId;
262
357
  this.state = createParseState(options);
263
358
  }
359
+ /** Bytes of the source file already folded in — where a resumed read starts. */
360
+ get bytesConsumed() {
361
+ return this.cursor;
362
+ }
363
+ /** Monotonic revision of the folded model. Unchanged between two reads means nothing to redo. */
364
+ get revision() {
365
+ return this.state.revision;
366
+ }
367
+ /** Rows folded so far. Zero means the file held nothing a transcript can show. */
368
+ get eventCount() {
369
+ return this.state.events.length;
370
+ }
371
+ /** @internal Advanced by the file fold; never rewound. */
372
+ advanceCursor(bytes) {
373
+ if (bytes > this.cursor)
374
+ this.cursor = bytes;
375
+ }
264
376
  consumeLine(line) {
265
377
  if (!line.trim())
266
378
  return;
@@ -268,7 +380,7 @@ export class ConversationHistoryAccumulator {
268
380
  return;
269
381
  const ev = parseRawEvent(line);
270
382
  if (ev)
271
- consumeParsedEvent(this.state, ev);
383
+ consumeParsedEvent(this.state, ev, line.length);
272
384
  }
273
385
  consumeRawEvent(ev, serializedLine) {
274
386
  const line = serializedLine === undefined
@@ -276,11 +388,15 @@ export class ConversationHistoryAccumulator {
276
388
  : serializedLine.endsWith('\n') ? serializedLine.slice(0, -1) : serializedLine;
277
389
  if (noteLargeToolResult(this.state, line))
278
390
  return;
279
- consumeParsedEvent(this.state, ev);
391
+ consumeParsedEvent(this.state, ev, line.length);
280
392
  }
281
393
  snapshot() {
282
394
  return finishHistory(this.sessionId, this.state);
283
395
  }
396
+ /** Per-row revisions, positionally aligned with `snapshot().events`. Live array — read only. */
397
+ eventRevisions() {
398
+ return this.state.revs;
399
+ }
284
400
  }
285
401
  export async function parseHistoryText(sessionId, raw, options = {}) {
286
402
  const accumulator = new ConversationHistoryAccumulator(sessionId, options);
@@ -288,16 +404,19 @@ export async function parseHistoryText(sessionId, raw, options = {}) {
288
404
  return accumulator.snapshot();
289
405
  }
290
406
  export async function readHistoryAccumulator(sessionId, filePath, options = {}) {
291
- const stream = createReadStream(filePath, { encoding: 'utf8' });
292
- const lines = createInterface({ input: stream, crlfDelay: Infinity });
293
407
  const accumulator = new ConversationHistoryAccumulator(sessionId, options);
294
- try {
295
- return await consumeHistoryIterable(accumulator, lines);
296
- }
297
- finally {
298
- lines.close();
299
- stream.destroy();
300
- }
408
+ await foldFileInto(accumulator, filePath, 0);
409
+ return accumulator;
410
+ }
411
+ /**
412
+ * Fold whatever the file has gained since this accumulator last read it. The file is append-only
413
+ * between rewrites, so a partially-read fold is a valid PREFIX state, not a spoiled one — resuming
414
+ * from the cursor is what turns a refresh from "re-parse the session" into "parse the new bytes".
415
+ * A rewrite (rewind / clear) is not resumable and is handled by the caller dropping the model.
416
+ */
417
+ export async function resumeHistoryAccumulator(accumulator, filePath) {
418
+ await foldFileInto(accumulator, filePath, accumulator.bytesConsumed);
419
+ return accumulator;
301
420
  }
302
421
  export async function readHistoryStream(sessionId, filePath, options = {}) {
303
422
  const accumulator = await readHistoryAccumulator(sessionId, filePath, options);
@@ -224,7 +224,10 @@ export declare class ConversationHistoryRepo {
224
224
  private readonly historyDir;
225
225
  /** Per-session serial write chain — keeps concurrent appends from interleaving a line. */
226
226
  private writeChains;
227
- private generations;
227
+ /** Bumped only when a session's file is REWRITTEN (rewind / clear) — never by an append. */
228
+ private rewriteEpochs;
229
+ /** In-flight model refresh per session, so concurrent reads share one fold instead of racing. */
230
+ private refreshChains;
228
231
  private compactCache;
229
232
  private compactCacheBytes;
230
233
  private dirReady;
@@ -233,22 +236,37 @@ export declare class ConversationHistoryRepo {
233
236
  private readonly compactHistoryAccumulatorReader;
234
237
  constructor(historyDir?: string, options?: ConversationHistoryRepoOptions);
235
238
  private ensureDir;
236
- private currentGeneration;
237
- private bumpGeneration;
239
+ private currentEpoch;
240
+ private bumpEpoch;
238
241
  private awaitWriteChain;
239
242
  private dropCompactCache;
240
- private readCompactCache;
241
- private markCompactCacheGeneration;
242
243
  private storeCompactCache;
243
244
  private trimCompactCache;
244
- private updateCompactCacheAfterAppend;
245
+ /**
246
+ * Bring the session's resident model level with the file on disk and return it.
247
+ *
248
+ * Cold: fold the whole file once. Warm: fold only the bytes appended since the model's cursor —
249
+ * which is the whole point, because a chat session's transcript is re-read at event rate and
250
+ * re-parsing it end to end is what saturated the event loop.
251
+ *
252
+ * Refreshes are serialized per session rather than shared: a caller that has already awaited an
253
+ * append must not be handed a fold that started before it. Queueing costs nothing once warm —
254
+ * the refresh behind it finds the model current and only stats the file — and it keeps
255
+ * read-your-writes, which a shared in-flight promise would quietly break.
256
+ *
257
+ * A rewrite landing mid-fold is caught by the epoch check and the fold is discarded (one retry,
258
+ * then the caller gets whatever the retry saw).
259
+ */
260
+ private ensureModel;
261
+ private refreshModel;
262
+ /** The compact projection of a current model, recomputed only when the fold actually moved. */
263
+ private compactOf;
264
+ /** Append one line. The resident model is deliberately NOT updated here: the file is the single
265
+ * source of truth and the next read folds the new bytes off it, so an in-memory copy can never
266
+ * drift from — or double-count against — what a concurrent read already folded. */
245
267
  private append;
246
268
  private readHistoryFile;
247
- private readStreamHistory;
248
269
  private rewriteTruncatedSession;
249
- private scanCompactHistory;
250
- private stableCompactHistory;
251
- private serializedCompactHistory;
252
270
  /** Append a user message — starts a new turn (turn boundaries are derived on read).
253
271
  * An optional `ts` override lets the caller share a single timestamp with the
254
272
  * EventBus event so the web UI's content-based de-dup produces identical keys. */
@@ -369,6 +387,15 @@ export declare class ConversationHistoryRepo {
369
387
  */
370
388
  getHistory(sessionId: string, options?: HistoryReadOptions): Promise<SessionHistory | null>;
371
389
  getCompactHistory(sessionId: string): Promise<CompactConversationHistory | null>;
390
+ /**
391
+ * The compact projection plus the cursor a caller needs to ask for the next delta. The cursor is
392
+ * `<epoch>:<revision>`: the epoch changes when the session is rewritten, which is precisely when
393
+ * a held cursor stops meaning anything and the caller must take a full snapshot again.
394
+ */
395
+ getCompactHistoryAt(sessionId: string): Promise<{
396
+ value: CompactConversationHistory | null;
397
+ cursor: string;
398
+ }>;
372
399
  getSubagentHistory(sessionId: string, subagentId: string): Promise<SubagentConversationHistory>;
373
400
  /** Load one tool's lossless DEBUG payload without attaching every result to the transcript. */
374
401
  getToolDebugDetails(sessionId: string, toolRef: string): Promise<HistoryDebugDetails | null>;