@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
@@ -2,22 +2,17 @@ import * as path from 'path';
2
2
  import { createReadStream, promises as fs } from 'fs';
3
3
  import { createInterface } from 'node:readline';
4
4
  import { STORE_DIR } from '../core/paths.js';
5
- import { estimateCompactHistoryBytes, projectCompactHistory, projectSubagentHistory, } from './conversation-display-projection.js';
6
- import { readHistoryAccumulator, readHistoryStream, } from './conversation-history-reader.js';
5
+ import { isOverDebugToolWarningChars } from '../core/debug-mode.js';
6
+ import { projectCompactHistory, projectSubagentHistory, } from './conversation-display-projection.js';
7
+ import { readHistoryAccumulator, readHistoryStream, resumeHistoryAccumulator, } from './conversation-history-reader.js';
7
8
  import { parseTodoSnapshot, renderTodoProgress } from '../agent-adapter/normalize/todo.js';
8
9
  const HISTORY_DIR = path.join(STORE_DIR, 'conversation-history');
9
10
  const DEFAULT_COMPACT_CACHE_ENTRIES = 32;
10
- const DEFAULT_COMPACT_CACHE_BYTES = 32 * 1024 * 1024;
11
- function estimateCacheEntryBytes(value, accumulator) {
12
- const retained = accumulator.snapshot();
13
- const retainedBytes = retained ? Buffer.byteLength(JSON.stringify(retained), 'utf8') : 0;
14
- return retainedBytes + estimateCompactHistoryBytes(value);
15
- }
16
- function appendedCacheBytes(serializedLine) {
17
- if (serializedLine.startsWith('{"type":"debug-tool-result"'))
18
- return 0;
19
- return Buffer.byteLength(serializedLine, 'utf8') + 256;
20
- }
11
+ /** Total resident budget for folded transcripts. Sized to hold several long sessions at once:
12
+ * a session whose model is dropped here is re-folded from byte 0 on every read (~1s of
13
+ * synchronous JSON parsing for a 40MB transcript, measured), so the budget is the difference
14
+ * between a warm read (~1ms) and a repeated full scan. */
15
+ const DEFAULT_COMPACT_CACHE_BYTES = 128 * 1024 * 1024;
21
16
  function nowIso() {
22
17
  return new Date().toISOString();
23
18
  }
@@ -112,7 +107,10 @@ export class ConversationHistoryRepo {
112
107
  historyDir;
113
108
  /** Per-session serial write chain — keeps concurrent appends from interleaving a line. */
114
109
  writeChains = new Map();
115
- generations = new Map();
110
+ /** Bumped only when a session's file is REWRITTEN (rewind / clear) — never by an append. */
111
+ rewriteEpochs = new Map();
112
+ /** In-flight model refresh per session, so concurrent reads share one fold instead of racing. */
113
+ refreshChains = new Map();
116
114
  compactCache = new Map();
117
115
  compactCacheBytes = 0;
118
116
  dirReady = false;
@@ -131,12 +129,12 @@ export class ConversationHistoryRepo {
131
129
  await fs.mkdir(this.historyDir, { recursive: true });
132
130
  this.dirReady = true;
133
131
  }
134
- currentGeneration(sessionId) {
135
- return this.generations.get(sessionId) ?? 0;
132
+ currentEpoch(sessionId) {
133
+ return this.rewriteEpochs.get(sessionId) ?? 0;
136
134
  }
137
- bumpGeneration(sessionId) {
138
- const next = this.currentGeneration(sessionId) + 1;
139
- this.generations.set(sessionId, next);
135
+ bumpEpoch(sessionId) {
136
+ const next = this.currentEpoch(sessionId) + 1;
137
+ this.rewriteEpochs.set(sessionId, next);
140
138
  return next;
141
139
  }
142
140
  async awaitWriteChain(sessionId) {
@@ -149,35 +147,17 @@ export class ConversationHistoryRepo {
149
147
  this.compactCacheBytes -= cached.bytes;
150
148
  this.compactCache.delete(sessionId);
151
149
  }
152
- readCompactCache(sessionId) {
153
- const cached = this.compactCache.get(sessionId);
154
- if (!cached)
155
- return undefined;
156
- if (cached.generation !== this.currentGeneration(sessionId)) {
157
- this.dropCompactCache(sessionId);
158
- return undefined;
159
- }
160
- this.compactCache.delete(sessionId);
161
- this.compactCache.set(sessionId, cached);
162
- return cached.value;
163
- }
164
- markCompactCacheGeneration(sessionId, generation) {
165
- const cached = this.compactCache.get(sessionId);
166
- if (!cached)
167
- return;
168
- cached.generation = generation;
169
- this.compactCache.delete(sessionId);
170
- this.compactCache.set(sessionId, cached);
171
- }
172
- storeCompactCache(sessionId, value, generation, accumulator, estimatedBytes) {
173
- if (value === null || !accumulator)
174
- return this.dropCompactCache(sessionId);
175
- const bytes = estimatedBytes ?? estimateCacheEntryBytes(value, accumulator);
150
+ storeCompactCache(sessionId, entry) {
176
151
  this.dropCompactCache(sessionId);
177
- if (bytes > this.compactCacheByteLimit)
152
+ // A transcript that alone exceeds the WHOLE budget is not retained. This is the total-budget
153
+ // invariant, not an independent per-file size cap: without it `trimCompactCache` (which walks
154
+ // insertion order) would evict every other session trying to make room and then evict this
155
+ // entry too, leaving the cache empty — measurably worse than not admitting it. Raising the
156
+ // budget is what makes longer sessions cacheable; this line only bounds a single outlier.
157
+ if (entry.bytes > this.compactCacheByteLimit)
178
158
  return;
179
- this.compactCache.set(sessionId, { generation, bytes, accumulator, value });
180
- this.compactCacheBytes += bytes;
159
+ this.compactCache.set(sessionId, entry);
160
+ this.compactCacheBytes += entry.bytes;
181
161
  this.trimCompactCache();
182
162
  }
183
163
  trimCompactCache() {
@@ -189,34 +169,109 @@ export class ConversationHistoryRepo {
189
169
  this.dropCompactCache(oldest);
190
170
  }
191
171
  }
192
- updateCompactCacheAfterAppend(sessionId, serializedLine, generation) {
193
- const cached = this.compactCache.get(sessionId);
194
- if (!cached)
195
- return;
196
- try {
197
- cached.accumulator.consumeLine(serializedLine.slice(0, -1));
198
- const history = cached.accumulator.snapshot();
199
- const bytes = cached.bytes + appendedCacheBytes(serializedLine);
200
- this.storeCompactCache(sessionId, history ? projectCompactHistory(history) : null, generation, cached.accumulator, bytes);
201
- }
202
- catch {
172
+ /**
173
+ * Bring the session's resident model level with the file on disk and return it.
174
+ *
175
+ * Cold: fold the whole file once. Warm: fold only the bytes appended since the model's cursor —
176
+ * which is the whole point, because a chat session's transcript is re-read at event rate and
177
+ * re-parsing it end to end is what saturated the event loop.
178
+ *
179
+ * Refreshes are serialized per session rather than shared: a caller that has already awaited an
180
+ * append must not be handed a fold that started before it. Queueing costs nothing once warm —
181
+ * the refresh behind it finds the model current and only stats the file — and it keeps
182
+ * read-your-writes, which a shared in-flight promise would quietly break.
183
+ *
184
+ * A rewrite landing mid-fold is caught by the epoch check and the fold is discarded (one retry,
185
+ * then the caller gets whatever the retry saw).
186
+ */
187
+ ensureModel(sessionId) {
188
+ const prev = this.refreshChains.get(sessionId) ?? Promise.resolve(null);
189
+ const run = prev
190
+ .catch(() => null)
191
+ .then(() => this.refreshModel(sessionId))
192
+ .finally(() => {
193
+ if (this.refreshChains.get(sessionId) === run)
194
+ this.refreshChains.delete(sessionId);
195
+ });
196
+ this.refreshChains.set(sessionId, run);
197
+ return run;
198
+ }
199
+ async refreshModel(sessionId) {
200
+ for (let attempt = 0; attempt < 2; attempt++) {
201
+ const epoch = this.currentEpoch(sessionId);
202
+ const filePath = sessionFilePath(this.historyDir, sessionId);
203
+ let size;
204
+ try {
205
+ size = (await fs.stat(filePath)).size;
206
+ }
207
+ catch {
208
+ this.dropCompactCache(sessionId); // absent file — nothing to model
209
+ return null;
210
+ }
211
+ let entry = this.compactCache.get(sessionId);
212
+ // A file that SHRANK was rewritten behind our back: the fold is not a prefix of it any more.
213
+ if (entry && (entry.epoch !== epoch || size < entry.accumulator.bytesConsumed))
214
+ entry = undefined;
215
+ // Take the entry OUT of the budget before touching it. `bytes` grows as the fold advances, so
216
+ // an in-place update would later be subtracted at its new size and leave the total adrift.
203
217
  this.dropCompactCache(sessionId);
218
+ try {
219
+ if (!entry) {
220
+ const accumulator = await this.compactHistoryAccumulatorReader(sessionId, filePath, { includeToolDebug: false });
221
+ // A reader that does not report a cursor cannot be resumed — folding from 0 next time
222
+ // would replay every row into the same model. Serve it, but never keep it.
223
+ if (accumulator.bytesConsumed === 0 && size > 0)
224
+ return { epoch, bytes: size, accumulator, projection: null };
225
+ entry = { epoch, bytes: accumulator.bytesConsumed, accumulator, projection: null };
226
+ }
227
+ else if (size > entry.accumulator.bytesConsumed) {
228
+ await resumeHistoryAccumulator(entry.accumulator, filePath);
229
+ entry.bytes = entry.accumulator.bytesConsumed;
230
+ entry.projection = null;
231
+ }
232
+ }
233
+ catch {
234
+ this.dropCompactCache(sessionId);
235
+ return null;
236
+ }
237
+ if (this.currentEpoch(sessionId) !== epoch) {
238
+ this.dropCompactCache(sessionId);
239
+ continue; // rewritten while we folded — rebuild against the new file
240
+ }
241
+ // An empty session has nothing to keep warm and costs nothing to re-fold; leaving it out
242
+ // keeps the budget for transcripts where resuming actually saves work.
243
+ if (entry.accumulator.eventCount === 0) {
244
+ this.dropCompactCache(sessionId);
245
+ return entry;
246
+ }
247
+ this.storeCompactCache(sessionId, entry); // re-inserting is also what refreshes LRU order
248
+ return entry; // returned even when the budget refused it: correct, just not retained
249
+ }
250
+ return null;
251
+ }
252
+ /** The compact projection of a current model, recomputed only when the fold actually moved. */
253
+ compactOf(entry) {
254
+ const revision = entry.accumulator.revision;
255
+ if (entry.projection && entry.projection.revision === revision)
256
+ return entry.projection.value;
257
+ const history = entry.accumulator.snapshot();
258
+ if (!history) {
259
+ entry.projection = null;
260
+ return null;
204
261
  }
262
+ const value = projectCompactHistory(history, entry.accumulator.eventRevisions());
263
+ entry.projection = { revision, value };
264
+ return value;
205
265
  }
266
+ /** Append one line. The resident model is deliberately NOT updated here: the file is the single
267
+ * source of truth and the next read folds the new bytes off it, so an in-memory copy can never
268
+ * drift from — or double-count against — what a concurrent read already folded. */
206
269
  append(sessionId, ev) {
207
- const generation = this.bumpGeneration(sessionId);
208
270
  const serializedLine = JSON.stringify(ev) + '\n';
209
271
  const prev = this.writeChains.get(sessionId) ?? Promise.resolve();
210
272
  const next = prev.catch(() => { }).then(async () => {
211
273
  await this.ensureDir();
212
- try {
213
- await fs.appendFile(sessionFilePath(this.historyDir, sessionId), serializedLine, 'utf8');
214
- }
215
- catch (error) {
216
- this.dropCompactCache(sessionId);
217
- throw error;
218
- }
219
- this.updateCompactCacheAfterAppend(sessionId, serializedLine, generation);
274
+ await fs.appendFile(sessionFilePath(this.historyDir, sessionId), serializedLine, 'utf8');
220
275
  });
221
276
  this.writeChains.set(sessionId, next);
222
277
  return next;
@@ -229,15 +284,6 @@ export class ConversationHistoryRepo {
229
284
  return null;
230
285
  }
231
286
  }
232
- async readStreamHistory(sessionId) {
233
- const filePath = sessionFilePath(this.historyDir, sessionId);
234
- try {
235
- return await readHistoryStream(sessionId, filePath, { includeToolDebug: false });
236
- }
237
- catch {
238
- return null;
239
- }
240
- }
241
287
  async rewriteTruncatedSession(sessionId, turnIndex) {
242
288
  const raw = await this.readHistoryFile(sessionId);
243
289
  if (raw === null)
@@ -248,49 +294,6 @@ export class ConversationHistoryRepo {
248
294
  await fs.writeFile(sessionFilePath(this.historyDir, sessionId), kept.length ? kept.join('\n') + '\n' : '', 'utf8');
249
295
  return removed;
250
296
  }
251
- async scanCompactHistory(sessionId) {
252
- const filePath = sessionFilePath(this.historyDir, sessionId);
253
- try {
254
- const accumulator = await this.compactHistoryAccumulatorReader(sessionId, filePath, { includeToolDebug: false });
255
- const history = accumulator.snapshot();
256
- return history ? { accumulator, value: projectCompactHistory(history) } : null;
257
- }
258
- catch {
259
- return null;
260
- }
261
- }
262
- async stableCompactHistory(sessionId) {
263
- for (let attempt = 0; attempt < 2; attempt++) {
264
- const generation = this.currentGeneration(sessionId);
265
- const history = await this.scanCompactHistory(sessionId);
266
- if (this.currentGeneration(sessionId) !== generation) {
267
- await this.awaitWriteChain(sessionId);
268
- const cached = this.readCompactCache(sessionId);
269
- if (cached !== undefined)
270
- return cached;
271
- continue;
272
- }
273
- this.storeCompactCache(sessionId, history?.value ?? null, generation, history?.accumulator);
274
- return history?.value ?? null;
275
- }
276
- await this.awaitWriteChain(sessionId);
277
- const cached = this.readCompactCache(sessionId);
278
- if (cached !== undefined)
279
- return cached;
280
- return this.serializedCompactHistory(sessionId);
281
- }
282
- async serializedCompactHistory(sessionId) {
283
- let history = null;
284
- const generation = this.currentGeneration(sessionId);
285
- const prev = this.writeChains.get(sessionId) ?? Promise.resolve();
286
- const next = prev.catch(() => { }).then(async () => { history = await this.scanCompactHistory(sessionId); });
287
- this.writeChains.set(sessionId, next);
288
- await next;
289
- if (this.currentGeneration(sessionId) === generation) {
290
- this.storeCompactCache(sessionId, history?.value ?? null, generation, history?.accumulator);
291
- }
292
- return history?.value ?? null;
293
- }
294
297
  /** Append a user message — starts a new turn (turn boundaries are derived on read).
295
298
  * An optional `ts` override lets the caller share a single timestamp with the
296
299
  * EventBus event so the web UI's content-based de-dup produces identical keys. */
@@ -389,7 +392,6 @@ export class ConversationHistoryRepo {
389
392
  * (for the edit marker + attachment reuse), or null when the turn does not exist.
390
393
  */
391
394
  async truncateFromTurn(sessionId, turnIndex) {
392
- const generation = this.bumpGeneration(sessionId);
393
395
  let removed = null;
394
396
  const prev = this.writeChains.get(sessionId) ?? Promise.resolve();
395
397
  const next = prev.catch(() => { }).then(async () => {
@@ -397,13 +399,15 @@ export class ConversationHistoryRepo {
397
399
  removed = await this.rewriteTruncatedSession(sessionId, turnIndex);
398
400
  }
399
401
  catch (error) {
402
+ this.bumpEpoch(sessionId);
400
403
  this.dropCompactCache(sessionId);
401
404
  throw error;
402
405
  }
403
- if (removed)
406
+ // An out-of-range rewind rewrote nothing, so the resident fold is still a valid prefix.
407
+ if (removed) {
408
+ this.bumpEpoch(sessionId);
404
409
  this.dropCompactCache(sessionId);
405
- else
406
- this.markCompactCacheGeneration(sessionId, generation);
410
+ }
407
411
  });
408
412
  this.writeChains.set(sessionId, next);
409
413
  await next;
@@ -416,12 +420,14 @@ export class ConversationHistoryRepo {
416
420
  */
417
421
  async getHistory(sessionId, options = {}) {
418
422
  await this.awaitWriteChain(sessionId);
419
- // Streamed rather than read whole. Both routes retain the same amount — the file never has to
420
- // exist as one string — but streaming is markedly faster on the transcripts that matter:
421
- // measured end to end on a 25MB session, 812ms against 2071ms, with peak RSS 69MB against 75MB.
422
- // The exception is a session whose individual rows run to tens of MB (one such file out of
423
- // 1919 here): readline reassembles each row from chunks, so that one peaks at 118MB / 3.2s
424
- // against 48MB / 2.4s. Retained heap is unchanged either way (3.12MB vs 3.10MB).
423
+ // The resident model is folded WITHOUT tool DEBUG payloads, which is what every transcript read
424
+ // asks for — those reads share it and pay only for the bytes appended since the last one.
425
+ // A DEBUG read wants the lossless inputs the model dropped, so it still streams the file whole;
426
+ // it is rare (server DEBUG only) and never on the UI's hot path.
427
+ if (options.includeToolDebug === false) {
428
+ const entry = await this.ensureModel(sessionId);
429
+ return entry?.accumulator.snapshot() ?? null;
430
+ }
425
431
  try {
426
432
  return await readHistoryStream(sessionId, sessionFilePath(this.historyDir, sessionId), options);
427
433
  }
@@ -431,13 +437,25 @@ export class ConversationHistoryRepo {
431
437
  }
432
438
  async getCompactHistory(sessionId) {
433
439
  await this.awaitWriteChain(sessionId);
434
- const cached = this.readCompactCache(sessionId);
435
- return cached !== undefined ? cached : this.stableCompactHistory(sessionId);
440
+ const entry = await this.ensureModel(sessionId);
441
+ return entry ? this.compactOf(entry) : null;
442
+ }
443
+ /**
444
+ * The compact projection plus the cursor a caller needs to ask for the next delta. The cursor is
445
+ * `<epoch>:<revision>`: the epoch changes when the session is rewritten, which is precisely when
446
+ * a held cursor stops meaning anything and the caller must take a full snapshot again.
447
+ */
448
+ async getCompactHistoryAt(sessionId) {
449
+ await this.awaitWriteChain(sessionId);
450
+ const entry = await this.ensureModel(sessionId);
451
+ if (!entry)
452
+ return { value: null, cursor: `${this.currentEpoch(sessionId)}:0` };
453
+ return { value: this.compactOf(entry), cursor: `${entry.epoch}:${entry.accumulator.revision}` };
436
454
  }
437
455
  async getSubagentHistory(sessionId, subagentId) {
438
456
  await this.awaitWriteChain(sessionId);
439
- const history = await this.readStreamHistory(sessionId);
440
- const projected = projectSubagentHistory(history, subagentId);
457
+ const entry = await this.ensureModel(sessionId);
458
+ const projected = projectSubagentHistory(entry?.accumulator.snapshot() ?? null, subagentId);
441
459
  return { ...projected, sessionId };
442
460
  }
443
461
  /** Load one tool's lossless DEBUG payload without attaching every result to the transcript. */
@@ -446,6 +464,10 @@ export class ConversationHistoryRepo {
446
464
  const stream = createReadStream(sessionFilePath(this.historyDir, sessionId), { encoding: 'utf8' });
447
465
  const lines = createInterface({ input: stream, crlfDelay: Infinity });
448
466
  let details = null;
467
+ // Same size policy as the fold: the rows we already read ARE the payload, so their combined
468
+ // line length is the measure. Nothing is re-serialized to weigh it.
469
+ let chars = 0;
470
+ const stamp = (value) => isOverDebugToolWarningChars(chars) ? { ...value, overCharacterThreshold: true } : value;
449
471
  try {
450
472
  for await (const line of lines) {
451
473
  if (!line.includes(toolRef))
@@ -460,16 +482,18 @@ export class ConversationHistoryRepo {
460
482
  if (event.toolUseId !== toolRef)
461
483
  continue;
462
484
  if (event.type === 'tool') {
485
+ chars += line.length;
463
486
  details = { ...(details ?? {}), toolRef, toolInput: event.fullInput };
464
487
  }
465
488
  else if (event.type === 'debug-tool-result') {
466
- return {
489
+ chars += line.length;
490
+ return stamp({
467
491
  ...(details ?? {}), toolRef,
468
492
  toolResult: { content: event.text ?? '', isError: event.isError === true },
469
- };
493
+ });
470
494
  }
471
495
  }
472
- return details;
496
+ return details ? stamp(details) : null;
473
497
  }
474
498
  catch {
475
499
  return null;
@@ -535,15 +559,14 @@ export class ConversationHistoryRepo {
535
559
  return found ?? null;
536
560
  }
537
561
  async clear(sessionId) {
538
- const generation = this.bumpGeneration(sessionId);
539
562
  const prev = this.writeChains.get(sessionId) ?? Promise.resolve();
540
563
  const next = prev.catch(() => { }).then(async () => {
564
+ this.bumpEpoch(sessionId);
541
565
  this.dropCompactCache(sessionId);
542
566
  try {
543
567
  await fs.unlink(sessionFilePath(this.historyDir, sessionId));
544
568
  }
545
569
  catch { /* already gone */ }
546
- this.markCompactCacheGeneration(sessionId, generation);
547
570
  });
548
571
  this.writeChains.set(sessionId, next);
549
572
  await next;
@@ -557,10 +580,10 @@ export class ConversationHistoryRepo {
557
580
  return removed;
558
581
  }
559
582
  async clearOneSession(sessionId) {
560
- const generation = this.bumpGeneration(sessionId);
561
583
  let removed = 0;
562
584
  const prev = this.writeChains.get(sessionId) ?? Promise.resolve();
563
585
  const next = prev.catch(() => { }).then(async () => {
586
+ this.bumpEpoch(sessionId);
564
587
  this.dropCompactCache(sessionId);
565
588
  try {
566
589
  await fs.unlink(sessionFilePath(this.historyDir, sessionId));
@@ -570,7 +593,6 @@ export class ConversationHistoryRepo {
570
593
  if (error.code !== 'ENOENT')
571
594
  throw error;
572
595
  }
573
- this.markCompactCacheGeneration(sessionId, generation);
574
596
  });
575
597
  this.writeChains.set(sessionId, next);
576
598
  await next;
@@ -27,6 +27,10 @@ export interface SessionRecord {
27
27
  lastUsedAt: string;
28
28
  label: string | null;
29
29
  profileName: string | null;
30
+ /** The agent template this session runs as — its execution environment (prompt, tools, skills,
31
+ * rules), the twin of `profileName` on the model axis. Absent/null means the session follows its
32
+ * channel's selection, and beneath that the global default. */
33
+ agentName?: string | null;
30
34
  backendSessionId?: string | null;
31
35
  lastReadAt?: string | null;
32
36
  scheduleId?: string | null;
@@ -214,6 +214,7 @@ function normalizeLegacyRecord(name, channelMap, raw) {
214
214
  lastUsedAt: toStringValue(raw.lastUsedAt),
215
215
  label,
216
216
  profileName: toNullableString(raw.profileName),
217
+ agentName: toOptionalNullableString(raw.agentName),
217
218
  backendSessionId: toOptionalNullableString(raw.backendSessionId),
218
219
  lastReadAt: toOptionalNullableString(raw.lastReadAt),
219
220
  scheduleId: toOptionalNullableString(raw.scheduleId),
@@ -356,6 +357,7 @@ function assertSessionRecord(raw, expectedId) {
356
357
  lastUsedAt: toStringValue(row?.lastUsedAt),
357
358
  label: toNullableString(row?.label),
358
359
  profileName: toNullableString(row?.profileName),
360
+ agentName: toOptionalNullableString(row?.agentName),
359
361
  backendSessionId: toOptionalNullableString(row?.backendSessionId),
360
362
  lastReadAt: toOptionalNullableString(row?.lastReadAt),
361
363
  scheduleId: toOptionalNullableString(row?.scheduleId),
@@ -383,6 +385,7 @@ function assertNewFormatRecord(raw, expectedId) {
383
385
  lastUsedAt: toStringValue(row?.lastUsedAt),
384
386
  label,
385
387
  profileName: toNullableString(row?.profileName),
388
+ agentName: toOptionalNullableString(row?.agentName),
386
389
  backendSessionId: toOptionalNullableString(row?.backendSessionId),
387
390
  lastReadAt: toOptionalNullableString(row?.lastReadAt),
388
391
  scheduleId: toOptionalNullableString(row?.scheduleId),
@@ -475,6 +478,7 @@ const PATCH_FIELD_READERS = {
475
478
  lastUsedAt: toStringValue,
476
479
  label: toNullableString,
477
480
  profileName: toNullableString,
481
+ agentName: toOptionalNullableString,
478
482
  backendSessionId: toOptionalNullableString,
479
483
  lastReadAt: toOptionalNullableString,
480
484
  scheduleId: toOptionalNullableString,
@@ -15,7 +15,7 @@ export interface PendingDeletion {
15
15
  }
16
16
  export type SessionRegistryData = Record<string, Session>;
17
17
  export type SessionRegistryRepoOptions = SessionRegistryJournalOptions;
18
- type UpdateFields = Partial<Pick<Session, 'lastUsedAt' | 'label' | 'profileName' | 'backendSessionId' | 'contextUsage' | 'browser'>> & {
18
+ type UpdateFields = Partial<Pick<Session, 'lastUsedAt' | 'label' | 'profileName' | 'agentName' | 'backendSessionId' | 'contextUsage' | 'browser'>> & {
19
19
  sessionId?: never;
20
20
  };
21
21
  export interface RegisterSessionOpts {
@@ -27,6 +27,7 @@ export interface RegisterSessionOpts {
27
27
  projectId?: string;
28
28
  label?: string | null;
29
29
  profileName?: string | null;
30
+ agentName?: string | null;
30
31
  backendSessionId?: string | null;
31
32
  scheduleId?: string | null;
32
33
  browser?: SessionBrowserOption | null;
@@ -111,6 +111,7 @@ export class SessionRegistryRepo {
111
111
  lastUsedAt: now,
112
112
  label: trimLabel(opts.label),
113
113
  profileName: opts.profileName ?? null,
114
+ agentName: opts.agentName ?? null,
114
115
  backendSessionId: opts.backendSessionId ?? null,
115
116
  scheduleId: opts.scheduleId ?? null,
116
117
  browser: opts.browser ?? null,
@@ -143,6 +144,7 @@ export class SessionRegistryRepo {
143
144
  lastUsedAt: updates.lastUsedAt ?? current.lastUsedAt,
144
145
  label: updates.label !== undefined ? trimLabel(updates.label) : current.label,
145
146
  profileName: updates.profileName !== undefined ? updates.profileName : current.profileName,
147
+ agentName: updates.agentName !== undefined ? updates.agentName : current.agentName,
146
148
  backendSessionId: updates.backendSessionId !== undefined
147
149
  ? updates.backendSessionId
148
150
  : current.backendSessionId,
@@ -29,13 +29,16 @@ export declare class TaskRepo {
29
29
  * Wait for any in-flight `runExclusive` / mutation to drain.
30
30
  * Acquire-release the mutex; FIFO ordering guarantees all preceding
31
31
  * operations have completed when this resolves.
32
- * Git sync is synchronous so it's always done by the time mutex releases.
32
+ * Mutations await `commitAndPush` inside the mutex, so git sync is always done by the time
33
+ * the mutex releases.
33
34
  * Known limitation: asyncPush errors may be lost during SIGTERM drain —
34
35
  * matching current task-store.ts behavior.
35
36
  */
36
37
  flush(): Promise<void>;
37
- /** Commit TASKS.yaml changes and push to origin/main */
38
- commitAndPush(message: string): void;
38
+ /** Commit TASKS.yaml changes and push to origin/main.
39
+ * Async: git runs on the shared event loop, so the three commands are awaited instead of
40
+ * blocking every session/socket in the process (they used to run via execSync). */
41
+ commitAndPush(message: string): Promise<void>;
39
42
  private asyncPush;
40
43
  }
41
44
  export declare const taskStore: TaskRepo;
@@ -3,7 +3,8 @@
3
3
  // pos: Serialized coordination center for TASKS.yaml changes. Based on core/AsyncMutex + atomicWrite (Pattern B)
4
4
  // S4: mutation shim methods removed, now lives in domain/tasks/mutator.ts
5
5
  import * as path from 'path';
6
- import { execSync, execFileSync, spawn } from 'child_process';
6
+ import { spawn } from 'child_process';
7
+ import { runFile } from '../core/exec-async.js';
7
8
  import { PROJECTS_DIR, DATA_DIR } from '../core/utils.js';
8
9
  import { scanAllTasks, scanAvailableTasks, getTaskStatsFromTasks, } from '../core/task-parser.js';
9
10
  import { createLogger } from '../core/log.js';
@@ -87,7 +88,8 @@ export class TaskRepo {
87
88
  * Wait for any in-flight `runExclusive` / mutation to drain.
88
89
  * Acquire-release the mutex; FIFO ordering guarantees all preceding
89
90
  * operations have completed when this resolves.
90
- * Git sync is synchronous so it's always done by the time mutex releases.
91
+ * Mutations await `commitAndPush` inside the mutex, so git sync is always done by the time
92
+ * the mutex releases.
91
93
  * Known limitation: asyncPush errors may be lost during SIGTERM drain —
92
94
  * matching current task-store.ts behavior.
93
95
  */
@@ -95,19 +97,33 @@ export class TaskRepo {
95
97
  await this.taskMutex.run(async () => { });
96
98
  }
97
99
  // --- Git sync ---
98
- /** Commit TASKS.yaml changes and push to origin/main */
99
- commitAndPush(message) {
100
+ /** Commit TASKS.yaml changes and push to origin/main.
101
+ * Async: git runs on the shared event loop, so the three commands are awaited instead of
102
+ * blocking every session/socket in the process (they used to run via execSync). */
103
+ async commitAndPush(message) {
100
104
  if (this.skipGit)
101
105
  return;
102
106
  try {
103
107
  const rel = path.relative(DATA_DIR, PROJECTS_DIR);
104
108
  const glob = `${rel}/*/TASKS.yaml`;
105
- execSync(`git add "${glob}"`, { cwd: DATA_DIR, timeout: 10000 });
106
- const status = execSync(`git status --porcelain -- "${glob}"`, {
107
- cwd: DATA_DIR, encoding: 'utf8', timeout: 5000,
108
- }).trim();
109
- if (status) {
110
- execFileSync('git', ['commit', '-m', message], { cwd: DATA_DIR, timeout: 10000 });
109
+ const added = await runFile('git', ['add', glob], { cwd: DATA_DIR, timeoutMs: 10000 });
110
+ if (!added.ok) {
111
+ log.error(`Git add failed: ${(added.stderr || added.stdout || added.error || '').trim()}`);
112
+ return;
113
+ }
114
+ const status = await runFile('git', ['status', '--porcelain', '--', glob], {
115
+ cwd: DATA_DIR, timeoutMs: 5000,
116
+ });
117
+ if (!status.ok) {
118
+ log.error(`Git status failed: ${(status.stderr || status.error || '').trim()}`);
119
+ return;
120
+ }
121
+ if (status.stdout.trim()) {
122
+ const committed = await runFile('git', ['commit', '-m', message], { cwd: DATA_DIR, timeoutMs: 10000 });
123
+ if (!committed.ok) {
124
+ log.error(`Git commit failed: ${(committed.stderr || committed.stdout || '').trim()}`);
125
+ return;
126
+ }
111
127
  log.info(`Committed: ${message}`);
112
128
  this.asyncPush();
113
129
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortex-agent/server",
3
- "version": "2026.9.21",
3
+ "version": "2026.9.25",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Autonomous agent system for long-running projects — mission-driven, multi-agent pipelines, self-evolving skills.",
@@ -17,6 +17,7 @@
17
17
  },
18
18
  "files": [
19
19
  "dist/",
20
+ "!dist/.tsbuildinfo",
20
21
  "defaults/",
21
22
  "web/dist/",
22
23
  "bundled-dependencies/",
@@ -0,0 +1,10 @@
1
+ Please update me when files in this folder change.
2
+
3
+ Shared theme tokens and browser application icons.
4
+
5
+ | filename | role | function |
6
+ |---|---|---|
7
+ | apple-touch-icon.png | asset | Identify the installed web application |
8
+ | favicon-32.png | asset | Identify browser tabs |
9
+ | favicon.svg | asset | Provide a scalable browser icon |
10
+ | theme.css | style | Define palette, glass and readable material tokens |