operon-agents-core 0.1.0-alpha.2 → 0.1.0-alpha.21

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 (289) hide show
  1. package/dist/agent/agent.d.ts +8 -7
  2. package/dist/agent/compose-hooks.d.ts +10 -1
  3. package/dist/agent/compose-hooks.js +61 -6
  4. package/dist/agent/concurrency.js +1 -1
  5. package/dist/agent/context-report.d.ts +2 -2
  6. package/dist/agent/durable-state.d.ts +22 -0
  7. package/dist/agent/durable-state.js +54 -0
  8. package/dist/agent/index.d.ts +2 -2
  9. package/dist/agent/index.js +1 -1
  10. package/dist/agent/instruction-context.d.ts +6 -6
  11. package/dist/agent/instruction-context.js +23 -23
  12. package/dist/agent/profile-builtins.js +1 -1
  13. package/dist/agent/run-support.d.ts +1 -1
  14. package/dist/agent/run-support.js +6 -5
  15. package/dist/agent/runner.d.ts +25 -22
  16. package/dist/agent/runner.js +217 -121
  17. package/dist/agent/session.d.ts +262 -156
  18. package/dist/agent/session.js +590 -418
  19. package/dist/agent/subagent-tools.js +3 -3
  20. package/dist/agent/subagent.js +28 -13
  21. package/dist/agent/toolset.d.ts +1 -0
  22. package/dist/agent/toolset.js +13 -7
  23. package/dist/agent/workflow/journal.d.ts +2 -2
  24. package/dist/agent/workflow/journal.js +2 -2
  25. package/dist/agent/workflow/manager.d.ts +1 -1
  26. package/dist/agent/workflow/manager.js +1 -1
  27. package/dist/agent/workflow/prompt.js +2 -2
  28. package/dist/agent/workflow/sandbox.d.ts +1 -1
  29. package/dist/agent/workflow/sandbox.js +1 -1
  30. package/dist/agent/workflow/tool.js +30 -43
  31. package/dist/agent/worktree.d.ts +8 -8
  32. package/dist/agent/worktree.js +15 -15
  33. package/dist/capabilities/assembler.d.ts +29 -5
  34. package/dist/capabilities/assembler.js +85 -9
  35. package/dist/capabilities/background/code-task.d.ts +43 -0
  36. package/dist/capabilities/background/code-task.js +75 -0
  37. package/dist/capabilities/background/command-task.d.ts +9 -2
  38. package/dist/capabilities/background/command-task.js +22 -6
  39. package/dist/capabilities/background/index.d.ts +6 -1
  40. package/dist/capabilities/background/index.js +26 -20
  41. package/dist/capabilities/background/manager.d.ts +57 -1
  42. package/dist/capabilities/background/manager.js +210 -45
  43. package/dist/capabilities/background/persist-disk.d.ts +1 -1
  44. package/dist/capabilities/background/persist-disk.js +1 -1
  45. package/dist/capabilities/background/persist.js +4 -2
  46. package/dist/capabilities/background/projections.d.ts +16 -0
  47. package/dist/capabilities/background/projections.js +86 -0
  48. package/dist/capabilities/background/stall-watchdog.d.ts +41 -0
  49. package/dist/capabilities/background/stall-watchdog.js +85 -0
  50. package/dist/capabilities/background/task.d.ts +8 -7
  51. package/dist/capabilities/background/tools.js +33 -7
  52. package/dist/capabilities/capability-data.d.ts +52 -0
  53. package/dist/capabilities/capability-data.js +88 -0
  54. package/dist/capabilities/capability-state.d.ts +2 -4
  55. package/dist/capabilities/capability-state.js +5 -23
  56. package/dist/capabilities/capability.d.ts +203 -38
  57. package/dist/capabilities/compaction/index.js +10 -4
  58. package/dist/capabilities/compaction/service.d.ts +20 -5
  59. package/dist/capabilities/compaction/service.js +27 -11
  60. package/dist/capabilities/goal/goal-store.d.ts +76 -12
  61. package/dist/capabilities/goal/goal-store.js +137 -53
  62. package/dist/capabilities/goal/index.d.ts +1 -1
  63. package/dist/capabilities/goal/index.js +30 -7
  64. package/dist/capabilities/index.d.ts +9 -6
  65. package/dist/capabilities/index.js +4 -3
  66. package/dist/capabilities/plan/index.js +22 -5
  67. package/dist/capabilities/plan/plan-mode.d.ts +30 -9
  68. package/dist/capabilities/plan/plan-mode.js +57 -32
  69. package/dist/capabilities/plan/tools.js +1 -1
  70. package/dist/capabilities/skills/flow-provider.js +3 -3
  71. package/dist/capabilities/skills/index.d.ts +13 -1
  72. package/dist/capabilities/skills/index.js +30 -21
  73. package/dist/capabilities/skills/parser.d.ts +2 -2
  74. package/dist/capabilities/skills/parser.js +3 -3
  75. package/dist/capabilities/skills/registry.d.ts +5 -6
  76. package/dist/capabilities/skills/registry.js +6 -9
  77. package/dist/capabilities/skills/scanner.d.ts +3 -3
  78. package/dist/capabilities/skills/scanner.js +14 -14
  79. package/dist/capabilities/skills/service.d.ts +2 -1
  80. package/dist/capabilities/skills/service.js +3 -3
  81. package/dist/capabilities/skills/skill-tool.d.ts +2 -0
  82. package/dist/capabilities/skills/skill-tool.js +1 -1
  83. package/dist/capabilities/task/index.js +2 -1
  84. package/dist/capabilities/task/persist-disk.d.ts +1 -1
  85. package/dist/capabilities/task/persist-disk.js +1 -1
  86. package/dist/capabilities/task/persist.js +1 -1
  87. package/dist/capabilities/todo/index.js +11 -6
  88. package/dist/capabilities/todo/injector.js +2 -1
  89. package/dist/capabilities/todo/todo-store.d.ts +28 -7
  90. package/dist/capabilities/todo/todo-store.js +44 -11
  91. package/dist/capabilities/todo/tools.js +8 -3
  92. package/dist/capabilities/tool-provider.d.ts +3 -3
  93. package/dist/capabilities/user-hooks/engine.d.ts +3 -3
  94. package/dist/capabilities/user-hooks/engine.js +7 -7
  95. package/dist/capabilities/user-hooks/index.js +2 -1
  96. package/dist/capabilities/workflow/index.d.ts +5 -3
  97. package/dist/capabilities/workflow/index.js +3 -2
  98. package/dist/commands/index.js +34 -32
  99. package/dist/config/index.d.ts +1 -1
  100. package/dist/config/provider-manager.js +0 -28
  101. package/dist/config/schema.d.ts +53 -4
  102. package/dist/config/schema.js +53 -1
  103. package/dist/events/events.d.ts +43 -11
  104. package/dist/events/events.js +1 -0
  105. package/dist/events/index.d.ts +2 -2
  106. package/dist/events/index.js +1 -1
  107. package/dist/events/projection.d.ts +49 -1
  108. package/dist/events/projection.js +144 -19
  109. package/dist/events/publisher.js +2 -21
  110. package/dist/home.d.ts +1 -1
  111. package/dist/home.js +1 -1
  112. package/dist/index.d.ts +3 -2
  113. package/dist/index.js +2 -1
  114. package/dist/internal.d.ts +5 -2
  115. package/dist/internal.js +5 -2
  116. package/dist/llm/define-model.d.ts +4 -0
  117. package/dist/llm/define-model.js +63 -25
  118. package/dist/llm/index.d.ts +1 -0
  119. package/dist/llm/index.js +1 -0
  120. package/dist/llm/model.d.ts +2 -0
  121. package/dist/llm/provider.d.ts +17 -0
  122. package/dist/llm/provider.js +14 -0
  123. package/dist/llm/retry.js +1 -1
  124. package/dist/loop/context.d.ts +21 -1
  125. package/dist/loop/context.js +47 -9
  126. package/dist/loop/events.d.ts +5 -1
  127. package/dist/loop/index.d.ts +2 -2
  128. package/dist/loop/index.js +1 -1
  129. package/dist/loop/interruption.d.ts +9 -4
  130. package/dist/loop/interruption.js +11 -25
  131. package/dist/loop/run-turn.d.ts +16 -3
  132. package/dist/loop/run-turn.js +13 -4
  133. package/dist/loop/steer.d.ts +78 -12
  134. package/dist/loop/steer.js +101 -38
  135. package/dist/loop/tool-call.d.ts +13 -2
  136. package/dist/loop/tool-call.js +135 -5
  137. package/dist/loop/turn-step.d.ts +13 -2
  138. package/dist/loop/turn-step.js +29 -7
  139. package/dist/loop/types.d.ts +6 -0
  140. package/dist/mcp/auth-tool.d.ts +3 -1
  141. package/dist/mcp/auth-tool.js +2 -2
  142. package/dist/mcp/capability.d.ts +13 -0
  143. package/dist/mcp/capability.js +36 -17
  144. package/dist/mcp/config-loader.d.ts +5 -5
  145. package/dist/mcp/config-loader.js +17 -17
  146. package/dist/mcp/credentials.d.ts +35 -0
  147. package/dist/mcp/credentials.js +2 -0
  148. package/dist/mcp/filter.d.ts +2 -2
  149. package/dist/mcp/index.d.ts +4 -3
  150. package/dist/mcp/index.js +1 -1
  151. package/dist/mcp/manager.d.ts +108 -6
  152. package/dist/mcp/manager.js +262 -18
  153. package/dist/mcp/oauth/callback-server.d.ts +10 -1
  154. package/dist/mcp/oauth/callback-server.js +82 -16
  155. package/dist/mcp/oauth/index.d.ts +2 -2
  156. package/dist/mcp/oauth/provider.d.ts +18 -0
  157. package/dist/mcp/oauth/provider.js +31 -1
  158. package/dist/mcp/oauth/service.d.ts +9 -3
  159. package/dist/mcp/oauth/service.js +29 -4
  160. package/dist/mcp/sdk-transport.js +1 -1
  161. package/dist/mcp/server.js +1 -1
  162. package/dist/permission/auto-approver/prompts-data.d.ts +1 -1
  163. package/dist/permission/auto-approver/prompts-data.js +1 -1
  164. package/dist/permission/manager.d.ts +5 -3
  165. package/dist/permission/manager.js +7 -3
  166. package/dist/permission/policies.d.ts +2 -2
  167. package/dist/permission/policies.js +4 -4
  168. package/dist/plugins/fields.d.ts +14 -0
  169. package/dist/plugins/fields.js +30 -0
  170. package/dist/plugins/hooks.d.ts +2 -2
  171. package/dist/plugins/hooks.js +12 -12
  172. package/dist/plugins/index.js +1 -0
  173. package/dist/plugins/manager.d.ts +8 -3
  174. package/dist/plugins/manager.js +18 -7
  175. package/dist/plugins/manifest.d.ts +2 -2
  176. package/dist/plugins/manifest.js +101 -91
  177. package/dist/plugins/marketplace.js +76 -57
  178. package/dist/plugins/store.d.ts +3 -3
  179. package/dist/plugins/store.js +6 -6
  180. package/dist/protocol/index.d.ts +1 -1
  181. package/dist/store/catalog-store.d.ts +4 -1
  182. package/dist/store/catalog-store.js +5 -1
  183. package/dist/store/checkpointing-store.d.ts +41 -0
  184. package/dist/store/checkpointing-store.js +86 -0
  185. package/dist/store/disk-store.d.ts +8 -0
  186. package/dist/store/disk-store.js +127 -5
  187. package/dist/store/index.d.ts +3 -2
  188. package/dist/store/index.js +2 -1
  189. package/dist/store/log-store.d.ts +9 -1
  190. package/dist/store/log-store.js +68 -4
  191. package/dist/store/migrate.d.ts +8 -2
  192. package/dist/store/migrate.js +9 -2
  193. package/dist/store/origin.d.ts +31 -6
  194. package/dist/store/origin.js +0 -14
  195. package/dist/store/pg.d.ts +1 -0
  196. package/dist/store/pg.js +37 -2
  197. package/dist/store/redis.d.ts +1 -0
  198. package/dist/store/redis.js +30 -0
  199. package/dist/store/repository.d.ts +13 -1
  200. package/dist/store/repository.js +45 -2
  201. package/dist/store/session-catalog.d.ts +4 -0
  202. package/dist/store/session-catalog.js +6 -0
  203. package/dist/store/storage.js +3 -0
  204. package/dist/store/store.d.ts +97 -34
  205. package/dist/store/store.js +64 -10
  206. package/dist/telemetry/appender.d.ts +43 -0
  207. package/dist/telemetry/appender.js +46 -0
  208. package/dist/telemetry/events.d.ts +142 -0
  209. package/dist/telemetry/events.js +141 -0
  210. package/dist/telemetry/index.d.ts +10 -0
  211. package/dist/telemetry/index.js +6 -0
  212. package/dist/telemetry/projection.d.ts +23 -0
  213. package/dist/telemetry/projection.js +185 -0
  214. package/dist/telemetry/redact.d.ts +20 -0
  215. package/dist/telemetry/redact.js +40 -0
  216. package/dist/telemetry/service.d.ts +49 -0
  217. package/dist/telemetry/service.js +137 -0
  218. package/dist/testing.d.ts +58 -0
  219. package/dist/testing.js +123 -0
  220. package/dist/tool/background.d.ts +9 -6
  221. package/dist/tool/background.js +7 -1
  222. package/dist/tool/builtin/ask-user-question.js +6 -5
  223. package/dist/tool/builtin/bash.d.ts +6 -0
  224. package/dist/tool/builtin/bash.js +79 -42
  225. package/dist/tool/builtin/edit.js +82 -109
  226. package/dist/tool/builtin/glob.js +13 -13
  227. package/dist/tool/builtin/grep.js +13 -13
  228. package/dist/tool/builtin/read.js +25 -15
  229. package/dist/tool/builtin/write.js +49 -33
  230. package/dist/tool/define.d.ts +14 -8
  231. package/dist/tool/define.js +8 -2
  232. package/dist/tool/{machine-base.d.ts → environment-base.d.ts} +37 -37
  233. package/dist/tool/{machine-base.js → environment-base.js} +45 -119
  234. package/dist/tool/{machine-local.d.ts → environment-local.d.ts} +9 -8
  235. package/dist/tool/{machine-local.js → environment-local.js} +60 -81
  236. package/dist/tool/{machine-null.d.ts → environment-null.d.ts} +9 -9
  237. package/dist/tool/{machine-null.js → environment-null.js} +9 -9
  238. package/dist/tool/{machine-ssh.d.ts → environment-ssh.d.ts} +33 -18
  239. package/dist/tool/{machine-ssh.js → environment-ssh.js} +118 -149
  240. package/dist/tool/{machine.d.ts → environment.d.ts} +53 -82
  241. package/dist/tool/environment.js +2 -0
  242. package/dist/tool/file-freshness.d.ts +33 -19
  243. package/dist/tool/file-freshness.js +39 -30
  244. package/dist/tool/filesystem-tools.d.ts +1 -1
  245. package/dist/tool/filesystem-tools.js +1 -1
  246. package/dist/tool/git-context.d.ts +2 -2
  247. package/dist/tool/git-context.js +8 -8
  248. package/dist/tool/index.d.ts +12 -12
  249. package/dist/tool/index.js +12 -10
  250. package/dist/tool/policies/path-access.d.ts +4 -4
  251. package/dist/tool/policies/path-access.js +12 -12
  252. package/dist/tool/questions.d.ts +8 -0
  253. package/dist/tool/search/catalog.d.ts +37 -0
  254. package/dist/tool/search/catalog.js +182 -0
  255. package/dist/tool/search/deferral.d.ts +3 -2
  256. package/dist/tool/search/loaded.d.ts +32 -0
  257. package/dist/tool/search/loaded.js +96 -0
  258. package/dist/tool/search/search-tool.d.ts +2 -6
  259. package/dist/tool/search/search-tool.js +16 -15
  260. package/dist/tool/shell-env.js +4 -0
  261. package/dist/tool/support/bash-paths.js +38 -7
  262. package/dist/tool/support/{machine-ops.d.ts → environment-ops.d.ts} +12 -14
  263. package/dist/tool/support/{machine-ops.js → environment-ops.js} +21 -2
  264. package/dist/tool/support/git-worktree.d.ts +3 -3
  265. package/dist/tool/support/git-worktree.js +6 -6
  266. package/dist/tool/support/rg-locator.d.ts +6 -6
  267. package/dist/tool/support/rg-locator.js +6 -6
  268. package/dist/tool/support/ripgrep-run.d.ts +5 -5
  269. package/dist/tool/support/ripgrep-run.js +3 -3
  270. package/dist/tool/support/tool-path.d.ts +3 -3
  271. package/dist/tool/support/tool-path.js +7 -7
  272. package/dist/tool/types.d.ts +54 -10
  273. package/dist/tool/web/fetch-url.js +1 -1
  274. package/dist/tool/web/web-search.js +1 -1
  275. package/dist/tool/workspace-spec.d.ts +3 -3
  276. package/dist/tool/workspace-spec.js +27 -27
  277. package/dist/tracing/bridge.d.ts +9 -1
  278. package/dist/tracing/bridge.js +307 -77
  279. package/dist/tracing/index.d.ts +2 -2
  280. package/dist/tracing/otel.d.ts +28 -1
  281. package/dist/tracing/otel.js +150 -38
  282. package/dist/tracing/processor.d.ts +22 -0
  283. package/dist/tracing/processor.js +2 -0
  284. package/dist/tracing/spans.d.ts +54 -0
  285. package/dist/tracing/spans.js +5 -0
  286. package/package.json +6 -2
  287. package/dist/tool/machine.js +0 -15
  288. package/dist/tool/search/activation.d.ts +0 -13
  289. package/dist/tool/search/activation.js +0 -31
package/dist/store/pg.js CHANGED
@@ -56,6 +56,9 @@ const SCHEMA_STATEMENTS = [
56
56
  // index keeps that predicate from touching them at all.
57
57
  `create index if not exists session_meta_live on session_meta (updated_at desc, id desc) where deleted_at is null`,
58
58
  `create index if not exists session_meta_recency on session_meta (updated_at desc, id desc)`,
59
+ // The root agent's running usage (JSON) — see `SessionSummary.usage`. Added after the table
60
+ // first shipped, hence an ALTER rather than a column in the CREATE.
61
+ `alter table session_meta add column if not exists usage text`,
59
62
  ];
60
63
  /** Tree session store for one session over a shared pool. Tree/migration/blobs live in LogSessionStore. */
61
64
  export class PgSessionStore extends LogSessionStore {
@@ -194,6 +197,9 @@ export class PgSessionRepository {
194
197
  return patch({ updatedAt });
195
198
  await exec.query(`update session_meta set title=$2, updated_at=$3 where id=$1`, [id, title, updatedAt]);
196
199
  },
200
+ usage: async (usage) => {
201
+ await exec.query(`update session_meta set usage=$2 where id=$1`, [id, JSON.stringify(usage)]);
202
+ },
197
203
  };
198
204
  return new CatalogSessionStore(raw, observer);
199
205
  }
@@ -230,7 +236,7 @@ export class PgSessionRepository {
230
236
  }
231
237
  async get(id) {
232
238
  await this.ready();
233
- const { rows } = await this.pool.query(`select m.id, m.work_dir, m.owner_key, m.deleted_at, m.title, m.created_at, m.updated_at,
239
+ const { rows } = await this.pool.query(`select m.id, m.work_dir, m.owner_key, m.deleted_at, m.title, m.created_at, m.updated_at, m.usage,
234
240
  case when s.session_id is null then 'idle' else 'interrupted' end as durable_state
235
241
  from session_meta m left join session_state s on s.session_id=m.id and s.key='interrupt'
236
242
  where m.id=$1`, [id]);
@@ -246,6 +252,7 @@ export class PgSessionRepository {
246
252
  createdAt: Number(row.created_at),
247
253
  updatedAt: Number(row.updated_at),
248
254
  durableState: parseDurableState(row.durable_state),
255
+ ...usageField(row.usage),
249
256
  };
250
257
  }
251
258
  async list(filter) {
@@ -264,7 +271,7 @@ export class PgSessionRepository {
264
271
  if (filter?.includeDeleted !== true)
265
272
  conditions.push("m.deleted_at is null");
266
273
  const where = conditions.length === 0 ? "" : `where ${conditions.join(" and ")} `;
267
- const { rows } = await this.pool.query(`select m.id, m.work_dir, m.owner_key, m.deleted_at, m.title, m.created_at, m.updated_at,
274
+ const { rows } = await this.pool.query(`select m.id, m.work_dir, m.owner_key, m.deleted_at, m.title, m.created_at, m.updated_at, m.usage,
268
275
  case when s.session_id is null then 'idle' else 'interrupted' end as durable_state
269
276
  from session_meta m left join session_state s on s.session_id=m.id and s.key='interrupt'
270
277
  ${where}order by m.updated_at desc, m.id desc`, params);
@@ -277,6 +284,7 @@ export class PgSessionRepository {
277
284
  createdAt: Number(r.created_at),
278
285
  updatedAt: Number(r.updated_at),
279
286
  durableState: parseDurableState(r.durable_state),
287
+ ...usageField(r.usage),
280
288
  }));
281
289
  }
282
290
  async fork(sourceId, input) {
@@ -299,6 +307,11 @@ export class PgSessionRepository {
299
307
  on conflict (id) do nothing returning id`, [id, workDir, ownerKey ?? null, title ?? null, now]);
300
308
  if (ins.rows.length === 0)
301
309
  throw new SessionRepositoryConflictError(id);
310
+ // The fork's log is a copy, so its running usage is the source's.
311
+ const usage = await exec.query(`select usage from session_meta where id=$1`, [sourceId]);
312
+ if (typeof usage.rows[0]?.usage === "string") {
313
+ await exec.query(`update session_meta set usage=$2 where id=$1`, [id, usage.rows[0].usage]);
314
+ }
302
315
  // Copy log + state into the new id; blobs are content-addressed + global, so they're shared.
303
316
  await exec.query(`insert into session_log(session_id, address, line) select $1, address, line from session_log where session_id=$2 order by seq`, [id, sourceId]);
304
317
  await exec.query(`insert into session_state(session_id, key, value) select $1, key, value from session_state where session_id=$2`, [id, sourceId]);
@@ -323,6 +336,14 @@ export class PgSessionRepository {
323
336
  await this.ready();
324
337
  await this.pool.query(`update session_meta set deleted_at=null, updated_at=$2 where id=$1 and deleted_at is not null`, [id, Date.now()]);
325
338
  }
339
+ async rename(id, title) {
340
+ await this.ready();
341
+ await this.pool.query(`update session_meta set title=$2, updated_at=$3 where id=$1`, [
342
+ id,
343
+ title.length > 0 ? title : null,
344
+ Date.now(),
345
+ ]);
346
+ }
326
347
  async close() {
327
348
  if (this.ownsPool)
328
349
  await this.pool.end?.();
@@ -332,6 +353,20 @@ export class PgSessionRepository {
332
353
  export function pgStorage(options) {
333
354
  return storageOver(new PgSessionRepository(options.pool, options.ownsPool ?? false));
334
355
  }
356
+ /** The summary's `usage`, from the column's JSON; nothing when absent or unreadable. */
357
+ function usageField(value) {
358
+ if (typeof value !== "string" || value === "")
359
+ return {};
360
+ try {
361
+ const parsed = JSON.parse(value);
362
+ return typeof parsed === "object" && parsed !== null && typeof parsed.totalTokens === "number"
363
+ ? { usage: parsed }
364
+ : {};
365
+ }
366
+ catch {
367
+ return {};
368
+ }
369
+ }
335
370
  function parseDurableState(value) {
336
371
  return value === "interrupted" ? "interrupted" : "idle";
337
372
  }
@@ -82,6 +82,7 @@ export declare class RedisSessionRepository implements SessionRepository {
82
82
  fork(sourceId: string, input?: ForkSessionInput): Promise<SessionHandle>;
83
83
  delete(id: string, options?: DeleteSessionOptions): Promise<void>;
84
84
  restore(id: string): Promise<void>;
85
+ rename(id: string, title: string): Promise<void>;
85
86
  close(): Promise<void>;
86
87
  }
87
88
  /** Redis-backed {@link SessionStorage}. Inject an `ioredis` client; no schema setup is needed. */
@@ -169,6 +169,11 @@ export class RedisSessionRepository {
169
169
  await this.client.zadd(this.sessionsKey, updatedAt, id);
170
170
  },
171
171
  durableState: () => undefined,
172
+ usage: async (usage) => {
173
+ if ((await this.client.exists(this.metaKey(id))) === 0)
174
+ return;
175
+ await this.client.hset(this.metaKey(id), "usage", JSON.stringify(usage));
176
+ },
172
177
  metadata: async (value, updatedAt) => {
173
178
  const title = sessionMetaTitle(value);
174
179
  if ((await this.client.exists(this.metaKey(id))) === 0)
@@ -205,6 +210,7 @@ export class RedisSessionRepository {
205
210
  createdAt: Number(m.created_at),
206
211
  updatedAt: Number(m.updated_at),
207
212
  durableState: parseDurableState(m.durable_state),
213
+ ...usageField(m.usage),
208
214
  };
209
215
  }
210
216
  // Known limitation (create/fork): the commands below are not wrapped in a MULTI/transaction,
@@ -310,6 +316,9 @@ export class RedisSessionRepository {
310
316
  durableState: parseDurableState(src.durable_state),
311
317
  };
312
318
  await this.writeMeta(meta);
319
+ // The fork's log is a copy, so its running usage is the source's.
320
+ if (src.usage)
321
+ await this.client.hset(this.metaKey(id), "usage", src.usage);
313
322
  const store = this.storeFor(id);
314
323
  await store.putState("meta", meta);
315
324
  return { id, workDir, createdAt: now, store };
@@ -341,6 +350,13 @@ export class RedisSessionRepository {
341
350
  await this.client.hset(this.metaKey(id), "deleted_at", "", "updated_at", String(now));
342
351
  await this.client.zadd(this.sessionsKey, now, id);
343
352
  }
353
+ async rename(id, title) {
354
+ if ((await this.client.exists(this.metaKey(id))) === 0)
355
+ return;
356
+ const now = Date.now();
357
+ await this.client.hset(this.metaKey(id), "title", title, "updated_at", String(now));
358
+ await this.client.zadd(this.sessionsKey, now, id);
359
+ }
344
360
  async close() {
345
361
  if (this.ownsClient)
346
362
  await this.client.quit?.();
@@ -358,6 +374,20 @@ function normalizeRedisSequence(value) {
358
374
  throw new Error(`invalid Redis sequence "${value}"`);
359
375
  return normalized;
360
376
  }
377
+ /** The summary's `usage`, from the meta hash's JSON field; nothing when absent or unreadable. */
378
+ function usageField(value) {
379
+ if (value === undefined || value === "")
380
+ return {};
381
+ try {
382
+ const parsed = JSON.parse(value);
383
+ return typeof parsed === "object" && parsed !== null && typeof parsed.totalTokens === "number"
384
+ ? { usage: parsed }
385
+ : {};
386
+ }
387
+ catch {
388
+ return {};
389
+ }
390
+ }
361
391
  function parseDurableState(value) {
362
392
  return value === "interrupted" ? "interrupted" : "idle";
363
393
  }
@@ -1,5 +1,6 @@
1
1
  import { type DurableSessionState } from "./catalog-store.ts";
2
- import type { SessionStore } from "./store.ts";
2
+ import { type SessionStore } from "./store.ts";
3
+ import type { Usage } from "../protocol/index.ts";
3
4
  export interface SessionMeta {
4
5
  readonly id: string;
5
6
  readonly workDir: string;
@@ -24,6 +25,13 @@ export interface SessionSummary {
24
25
  readonly updatedAt: number;
25
26
  /** Durable control state only. Live `running` belongs to the open HarnessSession. */
26
27
  readonly durableState: DurableSessionState;
28
+ /**
29
+ * The root agent's token usage over the session's whole life, as of its last finished turn —
30
+ * readable without opening the session. Subagents' usage is not included (it is audited in
31
+ * their own shards). A read model like the rest of the summary: absent until the first turn
32
+ * ends, and possibly one turn behind after a crash, until the next turn ends.
33
+ */
34
+ readonly usage?: Usage;
27
35
  }
28
36
  export interface SessionHandle {
29
37
  readonly id: string;
@@ -96,6 +104,8 @@ export interface SessionRepository {
96
104
  delete(id: string, options?: DeleteSessionOptions): Promise<void>;
97
105
  /** Clear a soft delete. No-op when the session is absent or was never deleted. */
98
106
  restore(id: string): Promise<void>;
107
+ /** Set (or clear, with an empty string) the session's title. No-op when the session is absent. */
108
+ rename(id: string, title: string): Promise<void>;
99
109
  }
100
110
  export declare class SessionRepositoryNotFoundError extends Error {
101
111
  readonly sessionId: string;
@@ -115,6 +125,7 @@ export declare class MemorySessionRepository implements SessionRepository {
115
125
  fork(sourceId: string, input?: ForkSessionInput): Promise<SessionHandle>;
116
126
  delete(id: string, options?: DeleteSessionOptions): Promise<void>;
117
127
  restore(id: string): Promise<void>;
128
+ rename(id: string, title: string): Promise<void>;
118
129
  private memoryObserver;
119
130
  }
120
131
  export declare class DiskSessionRepository implements SessionRepository {
@@ -133,6 +144,7 @@ export declare class DiskSessionRepository implements SessionRepository {
133
144
  fork(sourceId: string, input?: ForkSessionInput): Promise<SessionHandle>;
134
145
  delete(id: string, options?: DeleteSessionOptions): Promise<void>;
135
146
  restore(id: string): Promise<void>;
147
+ rename(id: string, title: string): Promise<void>;
136
148
  /** Rewrite the session's own `meta` state with (or without) the delete mark. */
137
149
  private markDiskMeta;
138
150
  private diskStore;
@@ -4,6 +4,7 @@ import { CatalogSessionStore } from "./catalog-store.js";
4
4
  import { DiskSessionStore } from "./disk-store.js";
5
5
  import { MemoryStore } from "./log-store.js";
6
6
  import { appendSessionCatalogRecord, readSessionCatalog, } from "./session-catalog.js";
7
+ import { AUDIT_ADDRESS } from "./store.js";
7
8
  import { encodeWorkdirKey, normalizeWorkDir } from "./workdir-key.js";
8
9
  export class SessionRepositoryNotFoundError extends Error {
9
10
  sessionId;
@@ -72,7 +73,7 @@ export class MemorySessionRepository {
72
73
  }
73
74
  async get(id) {
74
75
  const entry = this.sessions.get(id);
75
- return entry === undefined ? undefined : summaryFromMeta(entry.meta);
76
+ return entry === undefined ? undefined : withUsage(summaryFromMeta(entry.meta), entry.usage);
76
77
  }
77
78
  async list(filter) {
78
79
  const wanted = filter?.workDir !== undefined ? normalizeWorkDir(filter.workDir) : undefined;
@@ -82,7 +83,7 @@ export class MemorySessionRepository {
82
83
  .filter(({ meta }) => (wanted === undefined || meta.workDir === wanted)
83
84
  && (owner === undefined || meta.ownerKey === owner)
84
85
  && (deleted || meta.deletedAt === undefined))
85
- .map(({ meta }) => summaryFromMeta(meta))
86
+ .map(({ meta, usage }) => withUsage(summaryFromMeta(meta), usage))
86
87
  .sort((a, b) => b.updatedAt - a.updatedAt);
87
88
  }
88
89
  async fork(sourceId, input) {
@@ -102,6 +103,8 @@ export class MemorySessionRepository {
102
103
  const addresses = new Set();
103
104
  for await (const record of source.handle.store.readRecords())
104
105
  addresses.add(record.address ?? "main");
106
+ // A read without an address leaves the audit shard out; the fork carries it all the same.
107
+ addresses.add(AUDIT_ADDRESS);
105
108
  for (const address of addresses) {
106
109
  for await (const record of source.handle.store.readRecords({ address }))
107
110
  await target.appendRecord(record);
@@ -119,6 +122,10 @@ export class MemorySessionRepository {
119
122
  if (value !== null)
120
123
  await target.putState(key, value);
121
124
  }
125
+ // The fork's log is a copy, so its running usage is the source's.
126
+ const forkedEntry = this.sessions.get(forked.id);
127
+ if (forkedEntry !== undefined && source.usage !== undefined)
128
+ forkedEntry.usage = source.usage;
122
129
  return forked;
123
130
  }
124
131
  async delete(id, options) {
@@ -141,6 +148,14 @@ export class MemorySessionRepository {
141
148
  entry.meta = { ...rest, updatedAt: Date.now() };
142
149
  await entry.handle.store.putState("meta", entry.meta);
143
150
  }
151
+ async rename(id, title) {
152
+ const entry = this.sessions.get(id);
153
+ if (entry === undefined)
154
+ return;
155
+ const { title: _dropped, ...rest } = entry.meta;
156
+ entry.meta = { ...rest, ...(title.length > 0 ? { title } : {}), updatedAt: Date.now() };
157
+ await entry.handle.store.putState("meta", entry.meta);
158
+ }
144
159
  memoryObserver(id) {
145
160
  const patch = (values) => {
146
161
  const current = this.sessions.get(id);
@@ -155,9 +170,17 @@ export class MemorySessionRepository {
155
170
  const meta = asSessionMeta(value);
156
171
  patch({ ...(meta?.title !== undefined ? { title: meta.title } : {}), updatedAt: at });
157
172
  },
173
+ usage: (usage) => {
174
+ const current = this.sessions.get(id);
175
+ if (current !== undefined)
176
+ current.usage = usage;
177
+ },
158
178
  };
159
179
  }
160
180
  }
181
+ function withUsage(summary, usage) {
182
+ return usage === undefined ? summary : { ...summary, usage };
183
+ }
161
184
  export class DiskSessionRepository {
162
185
  sessionsDir;
163
186
  catalog;
@@ -263,6 +286,8 @@ export class DiskSessionRepository {
263
286
  createdAt: now,
264
287
  updatedAt: now,
265
288
  durableState: source.durableState,
289
+ // The fork's log is a copy, so its running usage is the source's.
290
+ ...(source.usage !== undefined ? { usage: source.usage } : {}),
266
291
  },
267
292
  });
268
293
  const store = this.diskStore(id, raw);
@@ -295,6 +320,21 @@ export class DiskSessionRepository {
295
320
  const { deletedAt: _dropped, ...rest } = entry;
296
321
  await this.writeCatalog({ op: "upsert", entry: { ...rest, updatedAt: Date.now() } });
297
322
  }
323
+ async rename(id, title) {
324
+ await this.ensureReconciled();
325
+ const entry = (await this.ensureCatalog()).get(id);
326
+ if (entry === undefined)
327
+ return;
328
+ const raw = new DiskSessionStore(entry.sessionDir);
329
+ const meta = asSessionMeta(await raw.getState("meta"));
330
+ if (meta === undefined)
331
+ return;
332
+ const updatedAt = Date.now();
333
+ const { title: _dropped, ...rest } = meta;
334
+ await raw.putState("meta", { ...rest, ...(title.length > 0 ? { title } : {}), updatedAt });
335
+ const { title: _entryTitle, ...entryRest } = entry;
336
+ await this.writeCatalog({ op: "upsert", entry: { ...entryRest, ...(title.length > 0 ? { title } : {}), updatedAt } });
337
+ }
298
338
  /** Rewrite the session's own `meta` state with (or without) the delete mark. */
299
339
  async markDiskMeta(entry, patch) {
300
340
  const raw = new DiskSessionStore(entry.sessionDir);
@@ -318,6 +358,7 @@ export class DiskSessionRepository {
318
358
  updatedAt: at,
319
359
  });
320
360
  },
361
+ usage: (usage) => this.patchDiskCatalog(id, { usage }),
321
362
  flush: async () => {
322
363
  await this.flushActivity();
323
364
  await this.catalogWrite;
@@ -446,6 +487,7 @@ function summaryFromCatalog(entry) {
446
487
  createdAt: entry.createdAt,
447
488
  updatedAt: entry.updatedAt,
448
489
  durableState: entry.durableState,
490
+ ...(entry.usage !== undefined ? { usage: entry.usage } : {}),
449
491
  };
450
492
  }
451
493
  function applyCatalogRecord(catalog, record) {
@@ -465,6 +507,7 @@ function applyCatalogRecord(catalog, record) {
465
507
  ...(record.title !== undefined ? { title: record.title ?? undefined } : {}),
466
508
  ...(record.updatedAt !== undefined ? { updatedAt: Math.max(current.updatedAt, record.updatedAt) } : {}),
467
509
  ...(record.durableState !== undefined ? { durableState: record.durableState } : {}),
510
+ ...(record.usage !== undefined ? { usage: record.usage } : {}),
468
511
  });
469
512
  }
470
513
  function asSessionMeta(value) {
@@ -1,4 +1,5 @@
1
1
  import type { DurableSessionState } from "./catalog-store.ts";
2
+ import type { Usage } from "../protocol/index.ts";
2
3
  export interface DiskSessionCatalogEntry {
3
4
  readonly sessionId: string;
4
5
  readonly sessionDir: string;
@@ -11,6 +12,8 @@ export interface DiskSessionCatalogEntry {
11
12
  readonly createdAt: number;
12
13
  readonly updatedAt: number;
13
14
  readonly durableState: DurableSessionState;
15
+ /** See `SessionSummary.usage`. */
16
+ readonly usage?: Usage;
14
17
  }
15
18
  export type DiskSessionCatalogRecord = {
16
19
  readonly op: "upsert";
@@ -21,6 +24,7 @@ export type DiskSessionCatalogRecord = {
21
24
  readonly title?: string | null;
22
25
  readonly updatedAt?: number;
23
26
  readonly durableState?: DurableSessionState;
27
+ readonly usage?: Usage;
24
28
  } | {
25
29
  readonly op: "delete";
26
30
  readonly sessionId: string;
@@ -37,6 +37,7 @@ export async function readSessionCatalog(sessionsDir) {
37
37
  ...current,
38
38
  ...(record.title !== undefined ? { title: record.title ?? undefined } : {}),
39
39
  ...(record.durableState !== undefined ? { durableState: record.durableState } : {}),
40
+ ...(record.usage !== undefined ? { usage: record.usage } : {}),
40
41
  ...(record.updatedAt !== undefined
41
42
  ? { updatedAt: Math.max(current.updatedAt, record.updatedAt) }
42
43
  : {}),
@@ -65,6 +66,7 @@ function parseCatalogLine(line, sessionsDir) {
65
66
  ...(typeof parsed.title === "string" || parsed.title === null ? { title: parsed.title } : {}),
66
67
  ...(typeof parsed.updatedAt === "number" ? { updatedAt: parsed.updatedAt } : {}),
67
68
  ...(durableState !== undefined ? { durableState } : {}),
69
+ ...(isUsage(parsed.usage) ? { usage: parsed.usage } : {}),
68
70
  };
69
71
  }
70
72
  if (parsed.op !== "upsert" || !isRecord(parsed.entry))
@@ -94,6 +96,7 @@ function parseCatalogLine(line, sessionsDir) {
94
96
  createdAt: entry.createdAt,
95
97
  updatedAt: entry.updatedAt,
96
98
  durableState,
99
+ ...(isUsage(entry.usage) ? { usage: entry.usage } : {}),
97
100
  },
98
101
  };
99
102
  }
@@ -101,6 +104,9 @@ function parseCatalogLine(line, sessionsDir) {
101
104
  return undefined;
102
105
  }
103
106
  }
107
+ function isUsage(value) {
108
+ return typeof value === "object" && value !== null && typeof value.totalTokens === "number";
109
+ }
104
110
  function parseDurableState(value) {
105
111
  return value === "idle" || value === "interrupted" ? value : undefined;
106
112
  }
@@ -28,6 +28,9 @@ class RepositoryStorage {
28
28
  restore(id) {
29
29
  return this.repo.restore(id);
30
30
  }
31
+ rename(id, title) {
32
+ return this.repo.rename(id, title);
33
+ }
31
34
  async scratch(workDir = SCRATCH_WORKDIR) {
32
35
  return (await this.repo.create({ workDir })).store;
33
36
  }
@@ -1,5 +1,5 @@
1
1
  import type { ImageContent, Message, TextContent, Usage } from "../protocol/index.ts";
2
- import type { ExternalPromptOrigin, PromptOrigin } from "./origin.ts";
2
+ import type { CompactionSummaryOrigin, LoadedToolSchema, PromptOrigin } from "./origin.ts";
3
3
  /**
4
4
  * A record in a session's append log. The log is a FLAT, linear, append-only stream
5
5
  * — NOT a tree. Each address has its own shard; a shard's
@@ -15,8 +15,10 @@ export type AgentRecord = {
15
15
  readonly eventId?: string;
16
16
  /** Wall-clock stamp (ms). Set by the store if the writer omitted it. */
17
17
  readonly time?: number;
18
- /** Which conversation shard this record belongs to (defaults to `main`). */
18
+ /** Which shard this record belongs to (defaults to `main`). */
19
19
  readonly address?: string;
20
+ /** On a record in the audit shard (`AUDIT_ADDRESS`): the conversation shard it is about. */
21
+ readonly about?: string;
20
22
  } & AgentRecordBody;
21
23
  export type AgentRecordBody = {
22
24
  readonly type: "metadata";
@@ -30,21 +32,21 @@ export type AgentRecordBody = {
30
32
  readonly type: "context.replace";
31
33
  readonly messages: readonly Message[];
32
34
  readonly origins?: readonly (PromptOrigin | null)[];
35
+ readonly checkpoint?: CheckpointState;
33
36
  } | {
34
37
  readonly type: "context.apply_compaction";
35
38
  readonly summary: string;
36
39
  /** Timestamp of the live summary message, so cold replay rebuilds it byte-for-byte. */
37
- readonly summaryTimestamp?: number;
38
- readonly cutoff: number;
40
+ readonly summaryTimestamp: number;
41
+ readonly kept: readonly Message[];
42
+ /** Parallel to `kept`. */
43
+ readonly keptOrigins?: readonly (PromptOrigin | null)[];
39
44
  readonly compactedCount: number;
40
45
  readonly tokensBefore: number;
41
46
  readonly tokensAfter: number;
42
- } | {
43
- readonly type: "inbox.received";
44
- readonly input: string;
45
- readonly origin: ExternalPromptOrigin;
46
- /** Delivery mode as accepted — `steer` targets a running turn, `follow_up` queues after it. */
47
- readonly mode: "auto" | "steer" | "follow_up";
47
+ /** See `CompactionSummaryOrigin.loadedTools`; folded onto the summary's origin. */
48
+ readonly loadedTools?: readonly LoadedToolSchema[];
49
+ readonly checkpoint?: CheckpointState;
48
50
  } | {
49
51
  readonly type: "custom_message";
50
52
  readonly customType: string;
@@ -68,17 +70,12 @@ export type AgentRecordBody = {
68
70
  /** The approval-rule subject of the approved call — the pattern an
69
71
  * `approve for session` grant memorizes. */
70
72
  readonly approvalRule?: string;
71
- /** "session" when the user granted approve-for-session; folded back into the
72
- * session's approval-pattern set on reopen. */
73
+ /** "session" when the user granted approve-for-session. Audit only: the session's grants
74
+ * are restored from its stored permission state (`session:permission`). */
73
75
  readonly scope?: string;
74
76
  } | {
75
77
  readonly type: "permission.set_mode";
76
78
  readonly mode: string;
77
- } | {
78
- readonly type: "config.update";
79
- readonly model?: string;
80
- readonly thinking?: string;
81
- readonly tools?: readonly string[];
82
79
  }
83
80
  /** Durable commit record for transferring the conversation head to a new root shard. */
84
81
  | {
@@ -122,33 +119,90 @@ export type AgentRecordBody = {
122
119
  readonly data: unknown;
123
120
  };
124
121
  /**
125
- * THE STORAGE RULE — what lives where:
122
+ * What a checkpoint carries besides the history: the shard's lifecycle at that instant
123
+ * (`#frame` — its agent, open turn, queued steers; see `FrameCheckpoint`), which a reader
124
+ * starting at the checkpoint could not otherwise fold, since the turn that compacted began
125
+ * before it. Session and capability state are NOT here: they live in the store's key/value
126
+ * side as current values (see `CapabilityDurableState`).
127
+ */
128
+ export type CheckpointState = Readonly<Record<string, unknown>>;
129
+ export type CheckpointRecord = Extract<AgentRecord, {
130
+ type: "context.replace" | "context.apply_compaction";
131
+ }>;
132
+ /** True for the self-contained history resets a shard can be replayed from. */
133
+ export declare function isCheckpointRecord(record: {
134
+ readonly type: string;
135
+ }): record is CheckpointRecord;
136
+ /**
137
+ * THE STORAGE RULE — what lives where (every record type, event and KV key is tabulated in
138
+ * docs/records-and-events.md; add a row there when you add one):
126
139
  *
127
- * - The append log (①) is the record for CONVERSATION-derived state. Anything whose loss
128
- * loses conversation information — history, audit — is a record, and its current-state
129
- * views are REDUCTIONS of it (a forward pass over the shard's records).
140
+ * - The append log (①) is the record of the CONVERSATION: what the model saw (history, read
141
+ * from the shard's newest checkpoint — see `isCheckpointRecord`), the durable events a client
142
+ * pages through (`event.lifecycle`, `usage.record`, `guardrail.blocked`), and the structure a
143
+ * resume follows (handoff commits, subagent meta, workflow journals, managed control input).
144
+ * Current state is NOT a reduction of it: the session and its capabilities keep their state as
145
+ * current values in KV (② (e)), and a reopen reads those, never the log.
146
+ * - AUDIT lives in its own shard (`AUDIT_ADDRESS`): approvals, permission-mode changes, a
147
+ * capability's own records, engine diagnostics. Nothing restores, replays or projects from
148
+ * it, a read without an address leaves it out, and its writes are best effort.
130
149
  * - BACKGROUND-TASK lifecycle is the one deliberate exception: a background task's status
131
150
  * (running → completed/failed/lost) lives in a dedicated per-task store, NOT a reduction of
132
151
  * the log — disk sessions keep it under `<sessionDir>/tasks/<id>/`, other backends in KV
133
152
  * state (see capabilities/background/persist.ts). This is what lets a task orphaned by a dead
134
153
  * process be reconciled to `lost` on reopen. The spawn ack + settle notification stay in the
135
154
  * log as the model-facing conversation record, but are no longer the reconcile source of
136
- * truth. `session.listSubagents()`/`listWorkflows()` PROJECT that task store — a foreground
155
+ * truth. `session.background?.listSubagents() ?? []`/`listWorkflows()` PROJECT that task store — a foreground
137
156
  * subagent/workflow is a plain tool call (conversation + its own shard), never a task.
138
- * - KV state (②) may hold only (a) handles to external systems (`machine`), (b)
139
- * rebuildable foreground control state (`interrupt`), (c) capability current-state (goal/plan/permission/
140
- * config/cron/subagents), and (d) the background task store on non-disk backends. If deleting
141
- * a KV key would lose information not recoverable elsewhere, that information belonged in the
142
- * log or the task store.
143
- * - The Machine filesystem holds work products (process logs, plan drafts) —
157
+ * - KV state (②) may hold only (a) handles to external systems (`environment`), (b)
158
+ * rebuildable foreground control state (`interrupt`) and indexes (`checkpoint:*` — where a
159
+ * shard's newest checkpoint is), (c) capability current-state a capability keeps there itself
160
+ * (cron/subagents), (d) the background task store on non-disk backends, and (e) session and
161
+ * capability durable state — `session:permission`, `session:usage`, and each
162
+ * `CapabilityDurableState` under `durable:<capability>:<address>` — which is the authority
163
+ * for that state: the log keeps what the model saw of it, never its current value.
164
+ * - The Environment filesystem holds work products (process logs, plan drafts) —
144
165
  * cache-grade relative to the log; harvest what must outlive it into a record.
145
166
  * - Pure runtime (live output tails) is not storage at all: its durable record is the
146
167
  * entity it drives.
147
168
  */
148
- export type StateKey = "interrupt" | "meta" | "machine" | "cron" | (string & {});
169
+ export type StateKey = "interrupt" | "meta" | "environment" | "cron" | (string & {});
149
170
  export interface ReadRecordsFilter {
171
+ /** One shard. Without it, every CONVERSATION shard — the audit shard (`AUDIT_ADDRESS`) is only
172
+ * ever read by naming it, so no whole-log reader (a reopen, a projection, `events.list`) pays
173
+ * for it or sees it. */
150
174
  readonly address?: string;
175
+ /**
176
+ * Start at the shard's newest checkpoint (see `isCheckpointRecord`) instead of its head —
177
+ * without `address`, EVERY shard from its own newest checkpoint, merged in append order.
178
+ * Replaying from a checkpoint yields the same history and state as replaying the whole shard,
179
+ * because a checkpoint does not depend on what precedes it — so a store that cannot locate one
180
+ * (or does not implement this) may return the whole shard, and the result is still correct,
181
+ * only slower.
182
+ */
183
+ readonly fromCheckpoint?: boolean;
151
184
  }
185
+ /**
186
+ * The audit shard: records about the session that nothing restores, replays or projects from —
187
+ * approvals, permission-mode changes, an extension's own records (`SessionContext.record`), and
188
+ * the engine's diagnostics. It is an ordinary shard to the backends (so a fork copies it and a
189
+ * delete removes it), but a read without an address leaves it out, and writing to it is best
190
+ * effort: losing an audit record never changes what the session does.
191
+ */
192
+ export declare const AUDIT_ADDRESS = "audit";
193
+ /** Append `body` to the audit shard; `about` names the conversation shard it concerns. */
194
+ export declare function appendAudit(store: SessionStore, body: AgentRecordBody, about?: string): Promise<string>;
195
+ /** The audit shard's records in append order (its leading `metadata` record left out). */
196
+ export declare function readAudit(store: SessionStore): Promise<AgentRecord[]>;
197
+ /** Where capability `owner`'s current state for journal `address` is kept in KV state. */
198
+ export declare function durableStateKey(owner: string, address: string): StateKey;
199
+ /** The session's own current state in KV: its runtime permission state, and its running usage
200
+ * (the root agent's turns only — see `SessionSummary.usage`). */
201
+ export declare const SESSION_PERMISSION_KEY: StateKey;
202
+ export declare const SESSION_USAGE_KEY: StateKey;
203
+ /** KV key under which a store indexes a shard's newest checkpoint. An index, not state:
204
+ * stale or missing, the reader falls back to the shard's head. */
205
+ export declare function checkpointIndexKey(address: string): StateKey;
152
206
  /** One durable append-log record together with its store-assigned position.
153
207
  * `sequence` is stable for the lifetime of the session: rewrites may migrate or
154
208
  * offload `record`, but must never renumber it. Gaps are valid. */
@@ -221,9 +275,9 @@ interface ReducedHistory {
221
275
  * Reduce a shard's records (append order) into live history, in a single forward pass.
222
276
  *
223
277
  * History-bearing records (`context.append_message` / `custom_message`) append a message;
224
- * `context.replace` resets the list; `context.apply_compaction` drops the first `cutoff`
225
- * messages and prepends the summary. Everything else (metadata / usage / approval / config /
226
- * handoff / custom) is audit/bookkeeping and never enters history.
278
+ * `context.replace` resets the list; `context.apply_compaction` resets it to the summary plus
279
+ * the kept tail. Everything else (metadata / usage / approval / handoff / custom) is
280
+ * audit/bookkeeping and never enters history.
227
281
  */
228
282
  /**
229
283
  * The mutable pair every history fold maintains. `origins[i]` describes `messages[i]`.
@@ -241,8 +295,17 @@ export interface HistoryFold {
241
295
  export declare function foldAppend(state: HistoryFold, message: Message, origin?: PromptOrigin): void;
242
296
  /** Reset the list to `messages` (micro-compaction's trim commits through this). */
243
297
  export declare function foldReplace(state: HistoryFold, messages: readonly Message[], origins?: readonly (PromptOrigin | null)[]): void;
244
- /** Drop the first `cutoff` messages and prepend the summary in their place. */
245
- export declare function foldCompaction(state: HistoryFold, cutoff: number, summary: string, summaryTimestamp?: number): void;
298
+ /**
299
+ * Drop the first `cutoff` messages and prepend the summary in their place — the LIVE splice, as
300
+ * the `history.compacted` event describes it to a consumer already holding the history. Replay
301
+ * of a record does not use this: the record is self-contained (see `foldCompactionRecord`).
302
+ */
303
+ export declare function foldCompaction(state: HistoryFold, cutoff: number, summary: string, summaryTimestamp?: number, loadedTools?: readonly LoadedToolSchema[]): void;
304
+ /** Reset to `[summary, ...kept]` — a compaction record replayed on its own. */
305
+ export declare function foldCompactionRecord(state: HistoryFold, record: Extract<AgentRecord, {
306
+ type: "context.apply_compaction";
307
+ }>): void;
308
+ export declare function compactionSummaryOrigin(loadedTools?: readonly LoadedToolSchema[]): CompactionSummaryOrigin;
246
309
  export declare function reduceHistory(records: readonly AgentRecord[]): ReducedHistory;
247
310
  export declare function summaryMessage(summary: string, timestamp?: number): Message;
248
311
  export declare function customMessage(content: string | (TextContent | ImageContent)[], timestamp?: number): Message;