@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,6 +1,6 @@
1
1
  import { Icons } from '../../../core/icons.js';
2
2
  import { t } from '../../../core/i18n.js';
3
- import { setChannelModelOverride, setChannelThinkingOverride, getActiveProfile, setActiveProfile, clearChannelProfile, getDefaultAgent, setDefaultAgent, switchChannelProfile } from '../../../domain/agents/index.js';
3
+ import { setChannelModelOverride, setChannelThinkingOverride, getActiveProfile, setActiveProfile, clearChannelProfile, getChannelAgents, getDefaultAgent, setDefaultAgent, switchChannelAgent, clearChannelAgentSelection, switchChannelProfile } from '../../../domain/agents/index.js';
4
4
  import { getDefaultProfileForBackend, getDefaultProfileName, isValidThinkingLevel, listProfiles, resolveProfile, THINKING_LEVELS_BY_BACKEND } from '../../../domain/agents/profile-manager.js';
5
5
  import { resolveRunConfig } from '../../../domain/runs/config-resolver.js';
6
6
  import { getDisplaySkillGroups } from '../../../domain/memory/skill-scanner.js';
@@ -305,71 +305,108 @@ export async function handleSkillsCmd(channel, adapter) {
305
305
  await adapter.postMessage(dest, { text: lines.join('\n') });
306
306
  }
307
307
  const MAX_AGENT_BUTTONS = 10;
308
- function buildAgentText() {
309
- const current = getDefaultAgent();
310
- const agents = listAgents();
311
- if (current) {
312
- const agentDef = getAgent(current);
313
- const profile = agentDef?.profile || '?';
314
- const claudeAgentStr = agentDef?.claudeAgent ? ` · agent:${agentDef.claudeAgent}` : '';
315
- return t('cmd.agent.current', { name: current, detail: `${profile}${claudeAgentStr}` });
316
- }
317
- return t('cmd.agent.none', { agents: agents.map(a => `\`${a.name}\``).join(', ') });
308
+ /** `profile · agent:<claude agent>` — what an agent runs under, in one line. */
309
+ function agentDetail(name) {
310
+ const agentDef = getAgent(name);
311
+ const claudeAgentStr = agentDef?.claudeAgent ? ` · agent:${agentDef.claudeAgent}` : '';
312
+ return `${agentDef?.profile || '?'}${claudeAgentStr}`;
318
313
  }
319
- function buildAgentButtons() {
314
+ /**
315
+ * What `!agent` reports: this conversation's agent, the global default it would fall back to, and
316
+ * the list to pick from. The two layers are always both named — "this channel runs creative" and
317
+ * "everything else runs main" are different facts, and a reader who sees only one cannot tell which
318
+ * of them a later `!agent reset` would leave behind.
319
+ */
320
+ function buildAgentText(channel) {
321
+ const channelAgent = getChannelAgents()[channel] ?? null;
322
+ const globalAgent = getDefaultAgent();
323
+ const header = channelAgent
324
+ ? t('cmd.agent.channelHeader', { name: channelAgent, detail: agentDetail(channelAgent) })
325
+ : globalAgent
326
+ ? t('cmd.agent.followingGlobal', { name: globalAgent })
327
+ : t('cmd.agent.followingGlobalNone');
328
+ const globalLine = globalAgent
329
+ ? t('cmd.agent.globalLine', { name: globalAgent })
330
+ : t('cmd.agent.globalNone');
331
+ const available = t('cmd.agent.available', {
332
+ agents: listAgents().map(a => `\`${a.name}\``).join(', '),
333
+ });
334
+ return `${header}\n${globalLine}\n${available}`;
335
+ }
336
+ /** The buttons set the CHANNEL's agent (the common move); the last one hands the channel back to
337
+ * the global default. Changing the global is a typed command (`!agent global <name>`) — a button
338
+ * that silently re-points every other conversation is not a button anyone wants to mis-tap. */
339
+ function buildAgentButtons(channel) {
320
340
  const agents = listAgents();
321
341
  const buttons = agents.slice(0, MAX_AGENT_BUTTONS - 1).map((a, i) => ({
322
342
  type: 'button',
323
343
  text: a.name,
324
344
  actionId: `cmd:agent:set-${i}`,
325
- value: a.name,
345
+ value: JSON.stringify({ name: a.name, channel }),
326
346
  }));
327
347
  buttons.push({
328
348
  type: 'button',
329
- text: t('cmd.agent.disableButton'),
330
- actionId: 'cmd:agent:disable',
331
- value: 'off',
332
- style: 'danger',
349
+ text: t('cmd.agent.followGlobalButton'),
350
+ actionId: 'cmd:agent:reset',
351
+ value: JSON.stringify({ channel }),
333
352
  });
334
353
  return buttons;
335
354
  }
355
+ /** Apply the shared per-channel agent-switch rule and build the reply text. Used by both
356
+ * `!agent <name>` and the interactive buttons, so Slack + Feishu share ONE code path — the same
357
+ * `switchChannelAgent` the Web UI's `sessions.setAgent` calls. */
358
+ async function switchChannelAgentReply(channel, name) {
359
+ const res = await switchChannelAgent({ channel, name });
360
+ // `res.ok === false` rather than `!res.ok`: this project compiles non-strict, where a boolean
361
+ // discriminant narrows only through an explicit comparison.
362
+ if (res.ok === false) {
363
+ if (res.reason === 'cross-backend-live-session') {
364
+ return `${Icons.error} ${t('cmd.agent.crossBackendBlocked', {
365
+ name, target: res.targetBackend ?? '?', current: res.currentBackend ?? '?',
366
+ })}`;
367
+ }
368
+ const available = listAgents().map(a => `\`${a.name}\``).join(', ');
369
+ return `${Icons.error} ${t('cmd.agent.unknown', { name, available })}`;
370
+ }
371
+ return `${Icons.ok} ${t('cmd.agent.channelSet', { name, detail: agentDetail(name) })}`;
372
+ }
373
+ /** Hand this conversation back to the global default. */
374
+ async function resetChannelAgentReply(channel) {
375
+ await clearChannelAgentSelection(channel);
376
+ const globalAgent = getDefaultAgent();
377
+ return `${Icons.ok} ${globalAgent
378
+ ? t('cmd.agent.cleared', { name: globalAgent })
379
+ : t('cmd.agent.clearedNoGlobal')}`;
380
+ }
381
+ /** `!agent reset` and its aliases: every bare form of the command is channel-scoped now, so "off"
382
+ * means "this conversation stops overriding", not "nobody has a default agent". The global is
383
+ * reached through `!agent global off`. */
384
+ const AGENT_RESET_WORDS = new Set(['reset', 'clear', 'off', 'none', 'disable']);
336
385
  export function createAgentHandler(router) {
337
386
  if (router) {
338
- const setHandler = async (ctx) => {
387
+ const rerender = async (ctx, channel, text) => {
339
388
  const adapter = router.getAdapter();
340
- if (!adapter)
389
+ if (!adapter || !ctx.messageRef)
341
390
  return;
342
- const name = ctx.value;
343
- const agentDef = getAgent(name);
344
- if (!agentDef)
391
+ await adapter.updateMessage(ctx.messageRef, {
392
+ text,
393
+ richBlocks: [
394
+ { type: 'section', text },
395
+ { type: 'actions', elements: buildAgentButtons(channel) },
396
+ ],
397
+ }).catch(() => { });
398
+ };
399
+ const setHandler = async (ctx) => {
400
+ if (!router.getAdapter())
345
401
  return;
346
- setDefaultAgent(name);
347
- const claudeAgentStr = agentDef.claudeAgent ? ` · agent:${agentDef.claudeAgent}` : '';
348
- const text = `${Icons.ok} ${t('cmd.agent.defaultSet', { name, detail: `${agentDef.profile}${claudeAgentStr}` })}`;
349
- if (ctx.messageRef) {
350
- await adapter.updateMessage(ctx.messageRef, {
351
- text,
352
- richBlocks: [
353
- { type: 'section', text },
354
- { type: 'actions', elements: buildAgentButtons() },
355
- ],
356
- }).catch(() => { });
357
- }
402
+ const { name, channel } = JSON.parse(ctx.value);
403
+ await rerender(ctx, channel, await switchChannelAgentReply(channel, name));
358
404
  };
359
- const disableHandler = async (ctx) => {
360
- const adapter = router.getAdapter();
361
- if (!adapter)
405
+ const resetHandler = async (ctx) => {
406
+ if (!router.getAdapter())
362
407
  return;
363
- setDefaultAgent(null);
364
- if (ctx.messageRef) {
365
- await adapter.updateMessage(ctx.messageRef, {
366
- text: `${Icons.ok} ${t('cmd.agent.disabled')}`,
367
- richBlocks: [
368
- { type: 'section', text: `${Icons.ok} ${t('cmd.agent.disabled')}` },
369
- { type: 'actions', elements: buildAgentButtons() },
370
- ],
371
- }).catch(() => { });
372
- }
408
+ const { channel } = JSON.parse(ctx.value);
409
+ await rerender(ctx, channel, await resetChannelAgentReply(channel));
373
410
  };
374
411
  router.registerCommand('agent', {
375
412
  actions: [
@@ -377,32 +414,46 @@ export function createAgentHandler(router) {
377
414
  actionId: `set-${i}`,
378
415
  handler: setHandler,
379
416
  })),
380
- { actionId: 'disable', handler: disableHandler },
417
+ { actionId: 'reset', handler: resetHandler },
381
418
  ],
382
419
  });
383
420
  }
384
421
  return async function handleAgentCmdInteractive(channel, adapter, trimmedMessage) {
385
- const args = trimmedMessage.replace(/^!agent\s*/, '').trim();
422
+ const args = trimmedMessage.replace(/^!agent\s*/, '').trim().split(/\s+/).filter(Boolean);
386
423
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
387
- if (args) {
388
- const name = args.split(/\s+/)[0];
389
- if (name === 'off' || name === 'none' || name === 'disable') {
390
- setDefaultAgent(null);
391
- await adapter.postMessage(dest, { text: `${Icons.ok} ${t('cmd.agent.disabled')}` });
424
+ if (args.length > 0) {
425
+ if (AGENT_RESET_WORDS.has(args[0])) {
426
+ await adapter.postMessage(dest, { text: await resetChannelAgentReply(channel) });
392
427
  return;
393
428
  }
394
- const agentDef = getAgent(name);
395
- if (!agentDef) {
396
- const available = listAgents().map(a => `\`${a.name}\``).join(', ');
397
- await adapter.postMessage(dest, { text: `${Icons.error} ${t('cmd.agent.unknown', { name, available })}` });
429
+ // The old daemon-wide semantics, kept under an explicit prefix: an agent set here is what
430
+ // every conversation WITHOUT one of its own runs.
431
+ if (args[0] === 'global') {
432
+ const name = args[1];
433
+ if (!name) {
434
+ await adapter.postMessage(dest, { text: `${Icons.error} ${t('cmd.agent.globalUsage')}` });
435
+ return;
436
+ }
437
+ if (name === 'off' || name === 'none' || name === 'disable') {
438
+ setDefaultAgent(null);
439
+ await adapter.postMessage(dest, { text: `${Icons.ok} ${t('cmd.agent.disabled')}` });
440
+ return;
441
+ }
442
+ if (!getAgent(name)) {
443
+ const available = listAgents().map(a => `\`${a.name}\``).join(', ');
444
+ await adapter.postMessage(dest, { text: `${Icons.error} ${t('cmd.agent.unknown', { name, available })}` });
445
+ return;
446
+ }
447
+ setDefaultAgent(name);
448
+ await adapter.postMessage(dest, {
449
+ text: `${Icons.ok} ${t('cmd.agent.defaultSet', { name, detail: agentDetail(name) })}`,
450
+ });
398
451
  return;
399
452
  }
400
- setDefaultAgent(name);
401
- const claudeAgentStr = agentDef.claudeAgent ? ` · agent:${agentDef.claudeAgent}` : '';
402
- await adapter.postMessage(dest, { text: `${Icons.ok} ${t('cmd.agent.defaultSet', { name, detail: `${agentDef.profile}${claudeAgentStr}` })}` });
453
+ await adapter.postMessage(dest, { text: await switchChannelAgentReply(channel, args[0]) });
403
454
  return;
404
455
  }
405
- const text = buildAgentText();
456
+ const text = buildAgentText(channel);
406
457
  if (!router) {
407
458
  await adapter.postMessage(dest, { text });
408
459
  return;
@@ -410,7 +461,7 @@ export function createAgentHandler(router) {
410
461
  return {
411
462
  text,
412
463
  richBlocks: [{ type: 'section', text }],
413
- actions: buildAgentButtons(),
464
+ actions: buildAgentButtons(channel),
414
465
  };
415
466
  };
416
467
  }
@@ -6,6 +6,9 @@ import { getActiveHandle } from '../domain/threads/runner.js';
6
6
  import { openThreadRun } from './thread-run/index.js';
7
7
  import { threadStore } from '../store/thread-repo.js';
8
8
  import { downloadFiles, bufferUserMessage } from './thread-input.js';
9
+ import { isRebuildHeld, refuseTurnForRebuild } from '../domain/system/rebuild-hold.js';
10
+ import { createLogger } from '../core/log.js';
11
+ const log = createLogger('thread-executor');
9
12
  export class ThreadExecutor {
10
13
  _enqueue;
11
14
  _track;
@@ -18,6 +21,16 @@ export class ThreadExecutor {
18
21
  }
19
22
  async route(ctx) {
20
23
  const { message, channel, adapter } = ctx;
24
+ // Same admission rule as the direct path (agent-runner): while the supervisor is rebuilding or
25
+ // replacing this process, starting a thread step only produces a step that the SIGTERM marks
26
+ // `failed` a moment later. Refuse it where the person can see why.
27
+ if (isRebuildHeld()) {
28
+ log.info(`Refusing thread routing on ${channel}: supervisor rebuild in progress`);
29
+ await refuseTurnForRebuild({
30
+ adapter, channel, text: ctx.agentMessage || '', interactive: true,
31
+ });
32
+ return;
33
+ }
21
34
  // Phase 6: buffer user messages when the thread is running a step,
22
35
  // so they're included in the next step's prompt instead of being lost.
23
36
  // DR-0014: also buffer for a parent suspended on child threads — routing such a
@@ -586,6 +586,7 @@ export function buildInjectDeps(sessionName, channel, adapter) {
586
586
  getLiveExecutions: (channel) => runRegistry.getByChannel(channel).map((entry) => ({
587
587
  backend: entry.backend,
588
588
  run: entry.run,
589
+ trackSessionId: entry.trackSessionId ?? null,
589
590
  })),
590
591
  getStreamingCallback: (channel) => activeTurns.streamingCallback(channel),
591
592
  appendAssistant: (sessionId, o) => recordHistory(conversationHistory.appendAssistant(sessionId, o)),
@@ -16,12 +16,20 @@ export interface CompactConversationHistory {
16
16
  events: CompactConversationEvent[];
17
17
  committedSourceIds: string[];
18
18
  subagentSummaries: CompactSubagentSummary[];
19
+ /** Server-internal, positionally aligned with `events`: the source row's revision. Present only
20
+ * when the caller supplied revisions; it is what lets a transcript read answer "since X". */
21
+ eventRevs?: number[];
19
22
  }
20
23
  export interface SubagentConversationHistory {
21
24
  sessionId: string;
22
25
  subagentId: string;
23
26
  events: CompactConversationEvent[];
24
27
  }
25
- export declare function projectCompactHistory(history: SessionHistory): CompactConversationHistory;
28
+ /**
29
+ * Fold a parsed history into the compact read model. `sourceRevs` is positional against
30
+ * `history.events`; supply it and the result carries the revision of each surviving row, which is
31
+ * what a delta read compares against a client cursor.
32
+ */
33
+ export declare function projectCompactHistory(history: SessionHistory, sourceRevs?: readonly number[]): CompactConversationHistory;
26
34
  export declare function estimateCompactHistoryBytes(history: CompactConversationHistory | null): number;
27
35
  export declare function projectSubagentHistory(history: SessionHistory | null, subagentId: string): SubagentConversationHistory;
@@ -26,6 +26,7 @@ function copyEvent(event, elapsed) {
26
26
  function createCompactState() {
27
27
  return {
28
28
  events: [],
29
+ eventRevs: [],
29
30
  summaries: new Map(),
30
31
  summaryOrder: [],
31
32
  previousMs: null,
@@ -121,10 +122,11 @@ function consumeChildEvent(state, event) {
121
122
  }
122
123
  markDetail(summary, event);
123
124
  }
124
- function pushCompactEvent(state, event, elapsed) {
125
+ function pushCompactEvent(state, event, elapsed, rev) {
125
126
  state.events.push(copyEvent(event, elapsed));
127
+ state.eventRevs.push(rev);
126
128
  }
127
- function consumeCompactEvent(state, event) {
129
+ function consumeCompactEvent(state, event, rev = 0) {
128
130
  const elapsed = elapsedMs(state.previousMs, event.ts);
129
131
  state.previousMs = nextPreviousMs(event.ts);
130
132
  if (event.type === 'user')
@@ -133,7 +135,7 @@ function consumeCompactEvent(state, event) {
133
135
  if (event.subagentId && !isStructuralSpawnTool(event))
134
136
  consumeChildEvent(state, event);
135
137
  if (keepCompactEvent(state, event))
136
- pushCompactEvent(state, event, elapsed);
138
+ pushCompactEvent(state, event, elapsed, rev);
137
139
  }
138
140
  function summarize(state) {
139
141
  return state.summaryOrder.map((id) => {
@@ -157,16 +159,21 @@ function sealReportedEnds(state, history) {
157
159
  summary.structurallyOpen = false;
158
160
  }
159
161
  }
160
- export function projectCompactHistory(history) {
162
+ /**
163
+ * Fold a parsed history into the compact read model. `sourceRevs` is positional against
164
+ * `history.events`; supply it and the result carries the revision of each surviving row, which is
165
+ * what a delta read compares against a client cursor.
166
+ */
167
+ export function projectCompactHistory(history, sourceRevs) {
161
168
  const state = createCompactState();
162
- for (const event of history.events)
163
- consumeCompactEvent(state, event);
169
+ history.events.forEach((event, index) => consumeCompactEvent(state, event, sourceRevs?.[index] ?? 0));
164
170
  sealReportedEnds(state, history);
165
171
  return {
166
172
  sessionId: history.sessionId,
167
173
  events: state.events,
168
174
  committedSourceIds: history.committedSourceIds ?? [],
169
175
  subagentSummaries: summarize(state),
176
+ ...(sourceRevs ? { eventRevs: state.eventRevs } : {}),
170
177
  };
171
178
  }
172
179
  export function estimateCompactHistoryBytes(history) {
@@ -2,11 +2,30 @@ import type { HistoryReadOptions, RawEvent, SessionHistory } from './conversatio
2
2
  export declare class ConversationHistoryAccumulator {
3
3
  private readonly sessionId;
4
4
  private readonly state;
5
+ /** Byte offset of the first byte of the file NOT yet folded in. */
6
+ private cursor;
5
7
  constructor(sessionId: string, options?: HistoryReadOptions);
8
+ /** Bytes of the source file already folded in — where a resumed read starts. */
9
+ get bytesConsumed(): number;
10
+ /** Monotonic revision of the folded model. Unchanged between two reads means nothing to redo. */
11
+ get revision(): number;
12
+ /** Rows folded so far. Zero means the file held nothing a transcript can show. */
13
+ get eventCount(): number;
14
+ /** @internal Advanced by the file fold; never rewound. */
15
+ advanceCursor(bytes: number): void;
6
16
  consumeLine(line: string): void;
7
17
  consumeRawEvent(ev: RawEvent, serializedLine?: string): void;
8
18
  snapshot(): SessionHistory | null;
19
+ /** Per-row revisions, positionally aligned with `snapshot().events`. Live array — read only. */
20
+ eventRevisions(): readonly number[];
9
21
  }
10
22
  export declare function parseHistoryText(sessionId: string, raw: string, options?: HistoryReadOptions): Promise<SessionHistory | null>;
11
23
  export declare function readHistoryAccumulator(sessionId: string, filePath: string, options?: HistoryReadOptions): Promise<ConversationHistoryAccumulator>;
24
+ /**
25
+ * Fold whatever the file has gained since this accumulator last read it. The file is append-only
26
+ * between rewrites, so a partially-read fold is a valid PREFIX state, not a spoiled one — resuming
27
+ * from the cursor is what turns a refresh from "re-parse the session" into "parse the new bytes".
28
+ * A rewrite (rewind / clear) is not resumable and is handled by the caller dropping the model.
29
+ */
30
+ export declare function resumeHistoryAccumulator(accumulator: ConversationHistoryAccumulator, filePath: string): Promise<ConversationHistoryAccumulator>;
12
31
  export declare function readHistoryStream(sessionId: string, filePath: string, options?: HistoryReadOptions): Promise<SessionHistory | null>;