dsh-plugin-dev-kb 1.8.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +186 -178
  2. package/README.en.md +172 -172
  3. package/README.md +183 -183
  4. package/kb/INDEX.md +236 -234
  5. package/kb/README.md +88 -88
  6. package/kb/extra/AGENTS.md +77 -77
  7. package/kb/extra/deepseek-llm-api-wire-extensions.md +162 -162
  8. package/kb/extra/deepseek-llm-api-wire-extensions.zh.md +162 -162
  9. package/kb/extra/defensive-patterns/package-surface.md +233 -232
  10. package/kb/extra/defensive-patterns/package-surface.zh.md +233 -232
  11. package/kb/extra/defensive-patterns/remote-and-api.md +117 -117
  12. package/kb/extra/defensive-patterns/remote-and-api.zh.md +117 -117
  13. package/kb/extra/development.md +221 -221
  14. package/kb/extra/development.zh.md +228 -228
  15. package/kb/extra/event-producer-consumer.md +133 -123
  16. package/kb/extra/event-producer-consumer.zh.md +135 -125
  17. package/kb/extra/module-graph.md +1961 -1888
  18. package/kb/extra/module-graph.zh.md +1963 -1890
  19. package/kb/extra/persistence-changes/2026-11-05-timeline-priority-notice.md +60 -0
  20. package/kb/extra/persistence-changes/2026-11-05-timeline-priority-notice.zh.md +60 -0
  21. package/kb/extra/persistence-changes/README.md +92 -92
  22. package/kb/extra/persistence-changes/README.zh.md +92 -92
  23. package/kb/extra/persistence-changes/historical-formats/README.md +75 -75
  24. package/kb/extra/persistence-changes/historical-formats/README.zh.md +75 -75
  25. package/kb/extra/persistence-changes/releases/README.md +103 -103
  26. package/kb/extra/persistence-changes/releases/README.zh.md +103 -103
  27. package/kb/extra/rescope.md +55 -55
  28. package/kb/extra/rescope.zh.md +55 -55
  29. package/kb/extra/subsystems/boot.md +631 -621
  30. package/kb/extra/subsystems/boot.zh.md +631 -621
  31. package/kb/extra/subsystems/computer-use.md +179 -137
  32. package/kb/extra/subsystems/computer-use.zh.md +179 -137
  33. package/kb/extra/subsystems/extensions.md +387 -384
  34. package/kb/extra/subsystems/extensions.zh.md +387 -384
  35. package/kb/extra/subsystems/feedback.md +418 -400
  36. package/kb/extra/subsystems/feedback.zh.md +418 -400
  37. package/kb/extra/subsystems/forge.md +2169 -1226
  38. package/kb/extra/subsystems/forge.zh.md +2171 -1226
  39. package/kb/extra/subsystems/liveshare.md +167 -158
  40. package/kb/extra/subsystems/liveshare.zh.md +167 -158
  41. package/kb/extra/subsystems/mcp.md +237 -234
  42. package/kb/extra/subsystems/mcp.zh.md +237 -234
  43. package/kb/extra/subsystems/office-kit.md +122 -0
  44. package/kb/extra/subsystems/office-kit.zh.md +122 -0
  45. package/kb/extra/subsystems/working-directory.md +95 -64
  46. package/kb/extra/subsystems/working-directory.zh.md +95 -64
  47. package/kb/extra/subsystems/worktrees.md +187 -127
  48. package/kb/extra/subsystems/worktrees.zh.md +187 -127
  49. package/kb/extra/upgrade-guide/v0.2.1-alpha.1/python-ptc-sandbox/guide.md +21 -21
  50. package/kb/extra/upgrade-guide/v0.2.1-alpha.1/python-ptc-sandbox/guide.zh.md +21 -21
  51. package/kb/extra/upgrade-guide/v0.2.1-rc.4/sandbox-unsupported-policy-error/guide.md +18 -0
  52. package/kb/extra/upgrade-guide/v0.2.1-rc.4/sandbox-unsupported-policy-error/guide.zh.md +18 -0
  53. package/kb/extra/upgrade-guide/v0.2.2-alpha.2/llm-error-builtin-codes/guide.md +18 -0
  54. package/kb/extra/upgrade-guide/v0.2.2-alpha.2/llm-error-builtin-codes/guide.zh.md +18 -0
  55. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-kit-package/guide.md +34 -0
  56. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-kit-package/guide.zh.md +34 -0
  57. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-operation-tools/guide.md +49 -0
  58. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-operation-tools/guide.zh.md +49 -0
  59. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-skill-resources/guide.md +36 -0
  60. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-skill-resources/guide.zh.md +36 -0
  61. package/kb/extra/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md +26 -0
  62. package/kb/extra/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.zh.md +26 -0
  63. package/kb/extra/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md +22 -0
  64. package/kb/extra/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.zh.md +22 -0
  65. package/kb/extra/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md +21 -0
  66. package/kb/extra/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md +21 -0
  67. package/kb/extra/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md +23 -0
  68. package/kb/extra/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md +23 -0
  69. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.md +20 -0
  70. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.zh.md +20 -0
  71. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md +18 -0
  72. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md +18 -0
  73. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +23 -0
  74. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +23 -0
  75. package/kb/extra/upgrade-guide/v0.2.2-rc.1/dsh-doc-skill/guide.md +35 -0
  76. package/kb/extra/upgrade-guide/v0.2.2-rc.1/dsh-doc-skill/guide.zh.md +35 -0
  77. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md +26 -0
  78. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md +26 -0
  79. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md +26 -0
  80. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.zh.md +26 -0
  81. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.md +19 -0
  82. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.zh.md +19 -0
  83. package/kb/extra/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.md +26 -0
  84. package/kb/extra/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.zh.md +26 -0
  85. package/kb/extra/upgrade-guide/v0.2.2-rc.1/plugin-update-method/guide.md +22 -0
  86. package/kb/extra/upgrade-guide/v0.2.2-rc.1/plugin-update-method/guide.zh.md +22 -0
  87. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.md +25 -0
  88. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.zh.md +25 -0
  89. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.md +48 -0
  90. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.zh.md +48 -0
  91. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.md +45 -0
  92. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.zh.md +45 -0
  93. package/kb/extra/upgrade-guide/v0.2.2-rc.1/runtime-context-reminders/guide.md +19 -0
  94. package/kb/extra/upgrade-guide/v0.2.2-rc.1/runtime-context-reminders/guide.zh.md +19 -0
  95. package/kb/extra/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md +17 -0
  96. package/kb/extra/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.zh.md +17 -0
  97. package/kb/extra/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md +27 -0
  98. package/kb/extra/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md +27 -0
  99. package/kb/extra/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.md +20 -0
  100. package/kb/extra/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.zh.md +20 -0
  101. package/kb/extra/upgrade-guide/v0.2.2-rc.1/terminal-bundle-sidebar-backend/guide.md +19 -0
  102. package/kb/extra/upgrade-guide/v0.2.2-rc.1/terminal-bundle-sidebar-backend/guide.zh.md +19 -0
  103. package/kb/extra/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.md +18 -0
  104. package/kb/extra/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.zh.md +18 -0
  105. package/kb/extra/upgrade-guide/v0.2.2-rc.1/web-search-billing/guide.md +41 -0
  106. package/kb/extra/upgrade-guide/v0.2.2-rc.1/web-search-billing/guide.zh.md +41 -0
  107. package/kb/extra/upgrade-guide/v0.2.2-rc.1/window-drag-regions/guide.md +21 -0
  108. package/kb/extra/upgrade-guide/v0.2.2-rc.1/window-drag-regions/guide.zh.md +21 -0
  109. package/kb/extra/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.md +29 -0
  110. package/kb/extra/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.zh.md +29 -0
  111. package/kb/extra/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md +25 -0
  112. package/kb/extra/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.zh.md +25 -0
  113. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cordis-root-and-intercept-metadata/guide.md +31 -0
  114. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cordis-root-and-intercept-metadata/guide.zh.md +31 -0
  115. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-agents-without-preset/guide.md +24 -0
  116. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-agents-without-preset/guide.zh.md +24 -0
  117. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-macos-provider/guide.md +24 -0
  118. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-macos-provider/guide.zh.md +24 -0
  119. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-partial-observations/guide.md +19 -0
  120. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-partial-observations/guide.zh.md +19 -0
  121. package/kb/extra/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.md +15 -0
  122. package/kb/extra/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.zh.md +15 -0
  123. package/kb/extra/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md +28 -0
  124. package/kb/extra/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md +28 -0
  125. package/kb/extra/upgrade-guide/v0.2.2-rc.2/package-export-cleanup/guide.md +36 -0
  126. package/kb/extra/upgrade-guide/v0.2.2-rc.2/package-export-cleanup/guide.zh.md +36 -0
  127. package/kb/extra/upgrade-guide/v0.2.2-rc.2/python-ptc-removal/guide.md +22 -0
  128. package/kb/extra/upgrade-guide/v0.2.2-rc.2/python-ptc-removal/guide.zh.md +22 -0
  129. package/kb/extra/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md +31 -0
  130. package/kb/extra/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md +31 -0
  131. package/kb/extra/upgrade-guide/v0.2.2-rc.2/shared-search-filter/guide.md +18 -0
  132. package/kb/extra/upgrade-guide/v0.2.2-rc.2/shared-search-filter/guide.zh.md +18 -0
  133. package/kb/extra/upgrade-guide/v0.2.2-rc.2/shell-fs-tool-error-codes/guide.md +30 -0
  134. package/kb/extra/upgrade-guide/v0.2.2-rc.2/shell-fs-tool-error-codes/guide.zh.md +30 -0
  135. package/kb/extra/web-styling.md +57 -57
  136. package/kb/extra/web-styling.zh.md +57 -57
  137. package/kb/meta/search-index.json +4508 -3980
  138. package/kb/meta/source.json +18 -18
  139. package/kb/site/develop/practice/llm-adapter.md +192 -192
  140. package/kb/site/en/develop/practice/llm-adapter.md +192 -192
  141. package/kb/site/en/guide/desktop-uninstall-cleanup.md +63 -0
  142. package/kb/site/en/guide/plugin-market.md +153 -151
  143. package/kb/site/en/guide/providers.md +234 -234
  144. package/kb/site/en/guide/quickstart.md +35 -34
  145. package/kb/site/en/reference/capability-seams.md +789 -767
  146. package/kb/site/en/reference/config-catalog.md +5432 -5128
  147. package/kb/site/en/reference/cookbook/adding-a-package.md +175 -175
  148. package/kb/site/en/reference/cookbook/adding-a-tool.md +105 -104
  149. package/kb/site/en/reference/cookbook/extension-cookbook.md +178 -135
  150. package/kb/site/en/reference/cordis-api/context.md +373 -369
  151. package/kb/site/en/reference/cordis-api/fiber.md +457 -433
  152. package/kb/site/en/reference/cordis-api/inherited.md +44 -44
  153. package/kb/site/en/reference/cordis-api/service.md +118 -107
  154. package/kb/site/en/reference/experimental-persistence-catalog.md +36 -23
  155. package/kb/site/en/reference/index.md +174 -174
  156. package/kb/site/en/reference/persistence-catalog.md +9453 -9432
  157. package/kb/site/en/reference/subsystems/compaction.md +288 -288
  158. package/kb/site/en/reference/subsystems/core.md +1172 -1171
  159. package/kb/site/en/reference/subsystems/credentials.md +526 -497
  160. package/kb/site/en/reference/subsystems/filesystem.md +708 -708
  161. package/kb/site/en/reference/subsystems/index.md +82 -82
  162. package/kb/site/en/reference/subsystems/llm-streaming.md +1290 -1288
  163. package/kb/site/en/reference/subsystems/lsp.md +230 -206
  164. package/kb/site/en/reference/subsystems/persistence.md +451 -432
  165. package/kb/site/en/reference/subsystems/plan.md +91 -91
  166. package/kb/site/en/reference/subsystems/ptc-runtime.md +295 -261
  167. package/kb/site/en/reference/subsystems/sandbox.md +250 -232
  168. package/kb/site/en/reference/subsystems/session-query.md +525 -515
  169. package/kb/site/en/reference/subsystems/session-reference.md +231 -229
  170. package/kb/site/en/reference/subsystems/session.md +1478 -1431
  171. package/kb/site/en/reference/subsystems/sidebar-right.md +165 -165
  172. package/kb/site/en/reference/subsystems/skills.md +356 -356
  173. package/kb/site/en/reference/subsystems/slots.md +235 -231
  174. package/kb/site/en/reference/subsystems/terminal.md +188 -188
  175. package/kb/site/en/reference/subsystems/tools.md +902 -891
  176. package/kb/site/en/reference/subsystems/user-questions.md +330 -327
  177. package/kb/site/en/reference/subsystems/web-client.md +161 -104
  178. package/kb/site/en/reference/subsystems/web-server.md +434 -351
  179. package/kb/site/en/reference/subsystems/web.md +268 -268
  180. package/kb/site/en/reference/subsystems/workflow.md +287 -282
  181. package/kb/site/en/reference/subsystems/workspace.md +743 -651
  182. package/kb/site/en/reference/tool-catalog.md +2867 -2704
  183. package/kb/site/guide/desktop-uninstall-cleanup.md +63 -0
  184. package/kb/site/guide/plugin-market.md +153 -151
  185. package/kb/site/guide/providers.md +234 -234
  186. package/kb/site/guide/quickstart.md +35 -34
  187. package/kb/site/reference/capability-seams.md +789 -767
  188. package/kb/site/reference/config-catalog.md +5432 -5128
  189. package/kb/site/reference/cookbook/adding-a-package.md +175 -175
  190. package/kb/site/reference/cookbook/adding-a-tool.md +107 -106
  191. package/kb/site/reference/cookbook/extension-cookbook.md +182 -139
  192. package/kb/site/reference/cordis-api/context.md +373 -369
  193. package/kb/site/reference/cordis-api/fiber.md +459 -435
  194. package/kb/site/reference/cordis-api/inherited.md +44 -44
  195. package/kb/site/reference/cordis-api/service.md +118 -107
  196. package/kb/site/reference/experimental-persistence-catalog.md +36 -23
  197. package/kb/site/reference/index.md +178 -178
  198. package/kb/site/reference/persistence-catalog.md +9453 -9432
  199. package/kb/site/reference/subsystems/compaction.md +288 -288
  200. package/kb/site/reference/subsystems/core.md +1184 -1183
  201. package/kb/site/reference/subsystems/credentials.md +526 -497
  202. package/kb/site/reference/subsystems/filesystem.md +708 -708
  203. package/kb/site/reference/subsystems/index.md +82 -82
  204. package/kb/site/reference/subsystems/llm-streaming.md +1296 -1294
  205. package/kb/site/reference/subsystems/lsp.md +230 -206
  206. package/kb/site/reference/subsystems/persistence.md +451 -432
  207. package/kb/site/reference/subsystems/plan.md +91 -91
  208. package/kb/site/reference/subsystems/ptc-runtime.md +295 -261
  209. package/kb/site/reference/subsystems/sandbox.md +250 -232
  210. package/kb/site/reference/subsystems/session-query.md +525 -515
  211. package/kb/site/reference/subsystems/session-reference.md +231 -229
  212. package/kb/site/reference/subsystems/session.md +1482 -1435
  213. package/kb/site/reference/subsystems/sidebar-right.md +165 -165
  214. package/kb/site/reference/subsystems/skills.md +356 -356
  215. package/kb/site/reference/subsystems/slots.md +239 -235
  216. package/kb/site/reference/subsystems/terminal.md +188 -188
  217. package/kb/site/reference/subsystems/tools.md +902 -891
  218. package/kb/site/reference/subsystems/user-questions.md +330 -327
  219. package/kb/site/reference/subsystems/web-client.md +161 -104
  220. package/kb/site/reference/subsystems/web-server.md +434 -351
  221. package/kb/site/reference/subsystems/web.md +268 -268
  222. package/kb/site/reference/subsystems/workflow.md +287 -282
  223. package/kb/site/reference/subsystems/workspace.md +743 -651
  224. package/kb/site/reference/tool-catalog.md +2872 -2709
  225. package/lib/index.js +359 -359
  226. package/package.json +68 -68
  227. package/skills/dsh-plugin-dev-kb.md +71 -70
  228. package/kb/extra/subsystems/office-to-pdf.md +0 -87
  229. package/kb/extra/subsystems/office-to-pdf.zh.md +0 -87
@@ -1,1431 +1,1478 @@
1
- ---
2
- editSource: "docs/subsystems/session.md"
3
- rawMarkdownPath: "en/reference/subsystems/session.md"
4
- outline: [2,3]
5
- ---
6
-
7
- # Sessions
8
-
9
- The in-memory, event-sourced model of [dsh-session](https://github.com/deepseek-ai/deepseek-harness/tree/master/packages/core/session). A `Session` is an **append-only log** of typed `SessionEvent`s — the single source of truth for an agent's whole interaction history. The LLM message history is *derived* from the log, never stored separately; replay is re-derivation from the same events. How the log is made **durable** (the persistence seam, backends, crash recovery) is the sibling concern on [persistence.md](./persistence.md).
10
-
11
- Source: [`packages/core/session/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/types.ts)
12
-
13
- ## `SessionEventMap` — the event vocabulary
14
-
15
- The append-only event types. Merge-extensible: a plugin declares extra event types via declaration merging — e.g. the [compaction seam](./compaction.md) adds `compaction/start` / `compaction/summary` / `compaction/end`, and `@deepseek-ai/dsh-hook-protocol` adds log-only `hook/invoked` / `hook/result` records for a hook bridge. Like `compaction/*`, these are NOT `SurfaceEventType`s (no `surfaceOp`). The generated [persistence log event catalog](../persistence-catalog.md) enumerates every member — core and merged — with its payload, surface badge, and declaration site.
16
-
17
- ```ts type-equiv
18
- /** A user-role specialization of the shared message representation. */
19
- interface UserMessage extends MessageBase {
20
- readonly role: 'user'
21
- }
22
- ```
23
-
24
- ```ts type-equiv
25
- /**
26
- * The merge-extensible, append-only source of truth for an agent interaction.
27
- * Message history is derived from this log. Every event is lossless JSON and
28
- * sequence numbers stay contiguous. Assistant attempt events embed their exact
29
- * compact raw streams so persistence stores one durable settlement per attempt.
30
- */
31
- interface SessionEventMap {
32
- /**
33
- * Opens turn `turn` before the loop claims queued input or runs pre-step.
34
- * Rejection, empty input, cancellation, or failure may close it with no
35
- * step; otherwise the following identified `user/message` event or batch
36
- * records the messages entering the step.
37
- */
38
- 'turn/start': { turn: number }
39
- /**
40
- * Closes turn `turn` with the {@link TurnEndReason} that ended it. A turn
41
- * with no entered step has no `step/start` or `step/end`. The loop does not await a
42
- * flush at turn boundaries: `dsh-session-checkpoint-policy` owns the
43
- * per-request durability checkpoint, and consumers that read storage after
44
- * `whenIdle()` flush themselves. Success commits the turn; rejection is
45
- * reported live and does not prevent later work.
46
- */
47
- 'turn/end': { turn: number; reason: TurnEndReason }
48
- /** Opens step `step` of turn `turn` — one model call plus the tool executions it requested. */
49
- 'step/start': { turn: number; step: number }
50
- /** Closes step `step` of turn `turn`. */
51
- 'step/end': { turn: number; step: number }
52
- /**
53
- * A user-role message on the model-visible surface: a direct human prompt
54
- * (the queued message claimed for this turn), a synthetic `agent.inject()`
55
- * context (file-change notices, subdir AGENTS.md, skill content, cron
56
- * notifications, …), or an entered goal continuation round. All three
57
- * project their `content` verbatim; `source` tells them apart.
58
- */
59
- 'user/message': UserMessage
60
- /** An incremental agent session change admitted at the named turn and step. */
61
- 'developer/message': {
62
- turn: number
63
- step: number
64
- message: DeveloperMessage
65
- /** Earlier request/header defining every tool addition; required exactly when additions are present. */
66
- headerSeq?: SessionSeq
67
- }
68
- /**
69
- * The rendered system prompt on the model-visible surface. The loop appends
70
- * the first one as surface node 0 before the step's first `user/message`.
71
- * A prepared in-history route can append nonempty changes in a continuing
72
- * series. An incapable route, or a new series whose effective text differs,
73
- * normalizes text to the first system node; a series start whose latest
74
- * surviving node already holds the rendering leaves it in place.
75
- * Normalization empties nonempty later nodes, then rewrites the head if
76
- * needed, through logged per-node replacements. An empty rendering always
77
- * clears all active system nodes, leaving no older instructions model-visible.
78
- * Empty later nodes are dormant and project to no message; an empty head with
79
- * no active later node records "no system prompt". Restored nonempty text follows
80
- * the same route and series rule; empty nodes never restore older text.
81
- */
82
- 'system/message': { turn: number; step: number; message: SystemMessage }
83
- /**
84
- * Assembled assistant message for one step (derived history uses this).
85
- * Carries the step's `usage` when the adapter reported token accounting, so
86
- * the model output and its accounting travel together (there is no separate
87
- * usage record). `usage` is absent when the adapter reported none. A turn
88
- * cancelled mid-stream finalizes its delivered text/reasoning prefix as this
89
- * event with `interrupted: true`; undispatched tool calls are absent. The
90
- * marker distinguishes that prefix without re-deriving interruption from turn
91
- * boundaries. An aborted turn with no such event streamed no visible content.
92
- */
93
- 'assistant/message': {
94
- turn: number
95
- step: number
96
- message: AssistantMessage
97
- /** Exact timed model stream, compacted without joining delta boundaries. */
98
- stream: AssistantStreamRecord[]
99
- usage?: TokenUsage
100
- interrupted?: true
101
- }
102
- /**
103
- * One model attempt that committed no surface message. The embedded stream
104
- * preserves a failed, retried, cancelled, or stream-error attempt that
105
- * reached settlement without fabricating model-visible history.
106
- */
107
- 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] }
108
- /**
109
- * The model requested one tool invocation: `name` with the raw `arguments`
110
- * JSON string exactly as the model produced it (unparsed). `callId` pairs the
111
- * call with its `tool/result`.
112
- */
113
- 'tool/call': { turn: number; step: number; callId: ToolCallId; name: string; arguments: string }
114
- /**
115
- * A completed tool call's model-facing result, optional internal failure
116
- * identity and user-facing reason, and optional tool-private `meta`
117
- * presentation payload. The reason remains outside the model-facing message.
118
- * `meta` is
119
- * opaque to the core (the producing tool owns its shape and reads it back in
120
- * `presentResult`) but MUST be JSON-serializable: `Session.append`
121
- * runtime-validates all event data with `isJsonValue`, so a non-serializable
122
- * `meta` is rejected at the source, and the durable log reproduces the
123
- * identical card on replay. Absent
124
- * unless the tool attaches one (e.g. `dsh-tool-fs` carries its result-time
125
- * contextual diff here).
126
- */
127
- 'tool/result': {
128
- turn: number
129
- step: number
130
- message: ToolResultMessage
131
- /**
132
- * Optional failure identity and raw user-facing reason, outside model content;
133
- * allowed only when the message has `isError: true`.
134
- */
135
- error?: { name: string; code: string; reason?: string }
136
- meta?: JsonValue
137
- }
138
- /**
139
- * Full header for the next request, appended inside its step before dispatch.
140
- * It is log-only; the latest snapshot reconstructs the request header.
141
- */
142
- 'request/header': {
143
- header: EpochHeader
144
- reason: RequestHeaderReason
145
- /** This request begins a distinct model-message series, independently of the header reason. */
146
- startsSeries?: true
147
- }
148
- /**
149
- * Route metadata for the next request, logged only when the route, capacity,
150
- * or system prompt update mode changes. It does not participate in request
151
- * reconstruction or header equality. Prompt admission uses the bound prepared
152
- * call's capability, not this snapshot from an earlier request.
153
- */
154
- 'request/context': RequestContext
155
- /**
156
- * Separates inherited or restored history from later lifecycle-owned work.
157
- * This log-only marker need not be at {@link Session.firstLiveSeq}: a fork
158
- * seed can already contain its tagged marker and child-owned synthetic
159
- * closers before construction.
160
- *
161
- * A fresh fork child owns one `{ inherited: true }` marker at its exact
162
- * inherited-prefix cut, even when that prefix ends in an ancestor marker.
163
- * `buildForkSeed` appends that marker before any synthetic closers; the
164
- * `Session` constructor supplies it when given only the inherited prefix.
165
- * The last tagged marker is the current Session's cut; untagged markers
166
- * keep ordinary restore and replay lifecycle boundaries.
167
- *
168
- * Only the `Session` constructor and `buildForkSeed` may create this marker.
169
- * Session append does not reject other writers, so a plugin appending one
170
- * would silently classify every live bracket before it as seed history.
171
- *
172
- * An owner of a standalone open/close bracket (`compaction/start` …
173
- * `compaction/end`) reads it because seed history and live work are otherwise
174
- * byte-identical: an unmatched opening marker before this event belongs to
175
- * an ended lifecycle, whatever ended it. NOT a liveness signal about other
176
- * writers — a concurrently live session holds its own boundary elsewhere,
177
- * so tolerating concurrent writers needs a signal beyond the log.
178
- */
179
- 'session/end-seed': { inherited?: true }
180
- }
181
- ```
182
-
183
- `UserMessage` is the identified, frozen user-role value shared by ordinary prompts, injected context, steering, and live inbox events. Event wrappers add only event-local position or outcome facts; the loop adds only driver-owned routing state while an item remains pending.
184
-
185
- <a id="the-request-header-event-requestheader"></a>
186
-
187
- ### The request header event: `request/header`
188
-
189
- The request envelope — the `EpochHeader` (call config + markers for adapter-supplied defaults + assembled tool schemas) — is logged session state, so every conversation request is a pure function of the log (the reconstructability Agent Note). The rendered system prompt is not part of the header: it is derived history, the `system/message` event at surface node 0 and any later in-history system node ([decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md)), so a prompt change replaces or appends a system node and leaves the header unchanged. A full `request/header` snapshot with reason `'initial'` or `'resume'` records each loop-instance boundary; a changed request appends a snapshot with reason `'change'`; and an unchanged envelope beginning an explicitly declared message series or following a surface replacement appends a snapshot with reason `'series'`. An `'initial'`, `'resume'`, or `'change'` snapshot carries `startsSeries: true` when that request also begins a series; reason `'series'` already records that fact. Ordinary append-only later Turns, further Steps, and retries in the same model-message series inherit the latest snapshot. `foldRequestHeader(events)` reconstructs the header by selecting the latest snapshot. The event is not a `SurfaceEventType`: it produces no LLM message.
190
-
191
- ```ts type-equiv
192
- /**
193
- * Logged request state outside derived history: call config and tools. The
194
- * system prompt is derived history — surface node 0, a `system/message` event.
195
- * The latest full `request/header` snapshot reconstructs the header; canonical
196
- * empty optional fields are absent.
197
- */
198
- interface EpochHeader {
199
- /** The conversation's call configuration (provider, model, reasoning effort, and sampling scalars). */
200
- config: LlmCallConfig
201
- /** Effective config fields materialized from the exact adapter rather than proposed by a caller. */
202
- adapterDefaults?: LlmCallConfigAdapterDefaults
203
- /** Assembled tool schemas; absent for a tool-less request. */
204
- tools?: ToolSchema[]
205
- /** Retired request text; system prompts belong to system/message events.
206
- * @persistenceReserved
207
- */
208
- system?: never
209
- }
210
- ```
211
-
212
- Current event acceptance requires canonical `request/header.header`: any `system` field is forbidden, and `tools: []` and `adapterDefaults: {}` must be omitted. Whitespace-only system-message content, `config.stop: []`, and nested extensions remain unchanged. Seed, append, and current persistence reads reject noncanonical headers rather than silently normalizing them; [the V3 envelope decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-09-06-v3-canonical-session-envelopes.md) owns historical conversion. Legacy v0 logs containing `request/header-delta` or its full-snapshot `fallback` reason are rejected rather than replayed incompletely.
213
-
214
- ### The route capacity event: `request/context`
215
-
216
- The context metadata of the route a request resolved to is separate logged state, appended beside `request/header` inside the same step and only when the provider, model, capacity, or `systemPromptUpdate` mode differs from the previous record. It stays outside `EpochHeader` because that type is the reconstruction contract compared field-wise by `headerEquals`: capacity and the update mode describe a route, not a request input, so folding them in would let a route change register as a request-envelope `change` and would pull adapter metadata into the loop's request reconstruction. Like `request/header`, it is not a `SurfaceEventType` and produces no LLM message. `session.requestContext()` folds the latest record incrementally; the agent loop reads that record's `systemPromptUpdate` when it decides whether a changed system prompt replaces the latest system node or is appended after the cached history ([decision rule](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent-loop/README.md#understand-the-implementation)). A route whose adapter advertises no capacity is recorded with `contextWindow` absent, so the new record clears an older route's capacity; a route without a declared update mode likewise clears an older route's `systemPromptUpdate`.
217
-
218
- ```ts type-equiv
219
- /** Registration-bound metadata for one resolved model route. */
220
- interface RequestContext {
221
- /** Registered provider route the metadata belongs to. */
222
- provider: string
223
- /** Provider-owned model id the metadata belongs to. */
224
- model: string
225
- /** Maximum combined request and response context in tokens, when advertised. */
226
- contextWindow?: number
227
- /** `'in-history'` when the route reads the latest `system` message at any position as the effective system prompt. */
228
- systemPromptUpdate?: SystemPromptUpdate
229
- }
230
- ```
231
-
232
- ## `SessionEvent<T>` — one log entry
233
-
234
- A proper discriminated union over `type` (not independent `type`/`data` unions), so `switch (event.type)` narrows `event.data` without casts. `seq` is the monotonic position in the log (`seq = log.length`); `time` is epoch ms.
235
-
236
- ```ts type-equiv
237
- /** Sequence number of one existing event in a Session log. */
238
- type SessionSeq = BrandedNumber<'SessionSeq'>
239
- ```
240
-
241
- ```ts type-equiv
242
- /** A Session log gap, prefix length, or read offset, which may equal the event count. */
243
- type SessionLogOffset = BrandedNumber<'SessionLogOffset'>
244
- ```
245
-
246
- ```ts type-equiv
247
- /** Inclusive Session event watermark, or `-1` before any event exists. */
248
- type SessionSeqCursor = SessionSeq | -1
249
- ```
250
-
251
- ```ts type-equiv
252
- /** One existing Session event position, or explicit absence. */
253
- type OptionalSessionSeq = SessionSeq | null
254
- ```
255
-
256
- `SessionSeq(value)` and `SessionLogOffset(value)` admit only non-negative safe integers and reject negative zero. They add compile-time brands without changing the serialized number; arithmetic returns an ordinary `number` that callers must admit again through the constructor for its intended role.
257
-
258
- ```ts type-equiv
259
- /**
260
- * One immutable entry in the session log.
261
- *
262
- * A proper discriminated union over `type` (not independent `type`/`data`
263
- * unions), so `switch (event.type)` narrows `event.data` without casts.
264
- *
265
- * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional:
266
- * they only exist on {@link SurfaceEventType} variants (`system/message`, `user/message`,
267
- * `assistant/message`, `tool/result`).
268
- * Non-surface events (boundary markers, attempts, errors) never carry
269
- * surface metadata — the compiler enforces this at `Session.append()`
270
- * call sites.
271
- */
272
- type SessionEvent<T extends SessionEventType = SessionEventType> = {
273
- [K in SessionEventType]: {
274
- type: K
275
- /** Monotonic sequence number within the session. */
276
- seq: SessionSeq
277
- /** Unix epoch milliseconds. */
278
- time: number
279
- data: SessionEventMap[K]
280
- /**
281
- * Marks an event a reader may safely skip when it does not recognize
282
- * `type`. Absent means required: a reader meeting an unrecognized type
283
- * without this marker MUST refuse to reconstruct the session instead of
284
- * silently dropping the event, because an unrecognized required event may
285
- * change how the rest of the log is interpreted. A writer sets `true` only
286
- * on purely informational records whose loss cannot affect reconstruction;
287
- * defaulting to required means a forgotten marker over-refuses (an
288
- * inconvenience) rather than silently resuming a gutted session.
289
- */
290
- ignorable?: true
291
- } & (K extends SurfaceEventType ? SurfaceIntent<K> : {
292
- surfaceOp?: never
293
- sourceEventSeqs?: never
294
- })
295
- }[T]
296
- ```
297
-
298
- `SessionEventType = keyof SessionEventMap`. Because `SessionEventMap` is merge-extensible, switches over `SessionEvent` must NOT use `assertNever` — a plugin-added variant is a valid unknown value; handle the known cases and fall through `default`.
299
-
300
- Every surface event requires `surfaceOp`; known log-only events forbid both surface metadata fields. Native unknown or obsolete ignorable envelopes remain opaque. `assistant/message` embeds its provider stream and forbids `sourceEventSeqs`. System, user, and tool surface events may cite a complete non-empty set of unique earlier events when source attribution or replacement coverage requires it. A `tool/result` may carry `data.error` only when its message has `isError: true`; failure identity remains optional for failed results.
301
-
302
- ## Surface types
303
-
304
- The message-producing types (`SurfaceEventType` — `system/message`, `developer/message`, `user/message`, `assistant/message`, `tool/result`) carry surface metadata declaring how they join the ordered derived surface. `system/message` holds the rendered system prompt: the loop appends the first one as surface node 0 and, when the prompt changes, replaces exactly the latest system node or appends a new one on an in-history route; the surface fold rejects any other replacement covering a `system/message` at node 0, while a later system node is ordinary history that a compaction replacement may shadow. See the [session surface Agent Note](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-06-18-session-surface.md).
305
-
306
- ### `SurfaceEventType` — the message-producing subset of event types
307
-
308
- ```ts type-equiv
309
- /**
310
- * The subset of {@link SessionEventType} values whose events produce LLM
311
- * messages and are eligible to appear on the ordered surface. Only these
312
- * event types may carry {@link SurfaceOp}; system, user, and tool events may also cite
313
- * earlier sources through {@link SessionEvent.sourceEventSeqs}.
314
- */
315
- type SurfaceEventType =
316
- | 'system/message'
317
- | 'developer/message'
318
- | 'user/message'
319
- | 'assistant/message'
320
- | 'tool/result'
321
- ```
322
-
323
- ### `SurfaceOp` — how an event entered the surface
324
-
325
- ```ts type-equiv
326
- /**
327
- * How a session event entered the ordered surface. Only valid on
328
- * {@link SurfaceEventType} events.
329
- *
330
- * - `'append'`: added to the tail — normal path for user/assistant/tool
331
- * messages.
332
- * - `{ op: 'replace', startSeq, endSeq }`: replaces surface nodes from `startSeq`
333
- * (inclusive) through `endSeq` (inclusive) with this node. Both must exist as
334
- * surface nodes in the current surface. `startSeq === endSeq` replaces a single
335
- * node. The node's {@link SessionEvent.sourceEventSeqs} must include every
336
- * shadowed surface node. Used by compaction; any surface-replacing producer
337
- * may use it.
338
- */
339
- type SurfaceOp =
340
- | 'append'
341
- | { op: 'replace'; startSeq: SessionSeq; endSeq: SessionSeq }
342
- ```
343
-
344
- `'append'` is the normal tail-append path. `replace` contains exactly `op`, `startSeq`, and `endSeq`, with no aliases or extra keys. It shadows the inclusive span between those current surface event sequences and inserts the new event in their place; equal endpoints replace one entry. Endpoints must precede the replacing event, but their relative order is surface order, not numeric sequence order.
345
-
346
- ### `SurfaceIntent` — the parameter to `session.append()`
347
-
348
- ```ts type-equiv
349
- /**
350
- * Surface placement and cited source-event seqs for {@link Session.append}. Required on
351
- * message-producing events and forbidden on log-only events.
352
- */
353
- type SurfaceIntent<T extends SurfaceEventType = SurfaceEventType> = {
354
- surfaceOp: SurfaceOp
355
- } & (T extends 'assistant/message' ? {
356
- /** Assistant messages embed their provider stream instead of citing source events. */
357
- sourceEventSeqs?: never
358
- } : {
359
- /** Complete non-empty set of known earlier source-event seqs. */
360
- sourceEventSeqs?: SessionSeq[]
361
- })
362
- ```
363
-
364
- Required for `SurfaceEventType` events — every message-producing event must declare how it joins the surface, the sole source of derived model history. A human-facing transcript is the other projection and reads the log's append-origin events instead, because the surface deliberately shadows the ranges a replacement summarizes (`isAppendSurfaceEvent` in [dsh-session](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/README.md)). Non-surface types reject it at compile time.
365
-
366
- `assistant/message` cannot carry `sourceEventSeqs`; its `stream` owns exact provider evidence. Other surface events omit the field when they cite no earlier event and use a complete non-empty list when they do.
367
-
368
- <a id="plugin-owned-message-projections"></a>
369
- ### Plugin-owned message projections
370
-
371
- Content-changing plugins mark their event declaration with `@messageProjection` and register a pure definition through `ctx.sessions.registerMessageProjection()`. Session validates the complete decision through that definition before commit, applies its immutable message updates, and advances `contentGeneration`. It rejects missing interpreters, including on restore and detached folding; unloading a used definition blocks cached reads. Detached readers pass explicit definitions to `foldSurface(events, projections)` and apply `projectedMessages` through `deriveEventMessage()`. The installed format catalog assembles first-party definitions for offline readers. The [image-offload plugin](./compaction.md#image-offload) owns its image-specific event and interpretation.
372
-
373
- ```ts type-equiv
374
- /** Readonly history immediately before a message-projection event. */
375
- interface SessionMessageProjectionContext {
376
- /** Current message-producing event sequences in model-visible order. */
377
- nodes: readonly SessionSeq[]
378
- /** Contiguous event window; entries at or beyond the candidate seq are not committed inputs. */
379
- events: readonly SessionEvent[]
380
- /** Absolute sequence of the window's first event. */
381
- baseSeq: SessionLogOffset
382
- /** Previously projected messages keyed by their original event sequences. */
383
- messages: ReadonlyMap<SessionSeq, Message>
384
- }
385
- ```
386
-
387
- ```ts type-equiv
388
- /** Pure interpretation of one plugin-owned event that changes existing message content. */
389
- interface SessionMessageProjection<T extends SessionEventType = SessionEventType> {
390
- /** Event interpreted by this definition; declare it with `@messageProjection` in SessionEventMap. */
391
- type: T
392
- /**
393
- * Validate the complete durable decision before returning any updates. Preserve
394
- * message identities and publish immutable copies without mutating the input.
395
- * @param event - candidate event, not yet applied to the supplied history.
396
- * @param context - history preceding this decision.
397
- * @returns changed current messages keyed by their original sequences.
398
- * @throws when the durable decision cannot be applied to this history.
399
- */
400
- project(event: SessionEvent<T>, context: SessionMessageProjectionContext): ReadonlyMap<SessionSeq, Message>
401
- }
402
- ```
403
-
404
- ### `SessionSurface` — the live readonly surface projection
405
-
406
- `Session.surface` returns the session's stable `SessionSurface` view. The same incremental manager validates append candidates before commit and advances this projection from committed events; callers can observe membership and replacement generation but cannot invoke validation.
407
-
408
- `SurfaceManager(log, baseSeq?, projections?)` can instead fold a contiguous loaded window whose first event has the absolute sequence `baseSeq`. Every event remains contiguous in that absolute sequence space, and a replacement that crosses the window head fails because its declared range is absent.
409
-
410
- ```ts type-equiv
411
- /** Readonly live projection of the message-producing session events. */
412
- interface SessionSurface {
413
- /** Current surface event sequences in model-visible order. */
414
- readonly nodes: readonly SessionSeq[]
415
- /** Monotonic count of committed positional replacements. */
416
- readonly replaceGeneration: number
417
- /** Monotonic count of committed replacements and plugin-owned message changes. */
418
- readonly contentGeneration: number
419
- }
420
- ```
421
-
422
- ### `SurfaceFoldReplacement` and `SurfaceFoldResult` — a complete surface replay
423
-
424
- `foldSurface(events, projections)` returns detached current event sequences together with the actual sequences shadowed by each declared replacement range. The live manager uses the same transitions without retaining replacement history. Its `replaceGeneration` increments for each committed replacement so incremental consumers can distinguish pure tail growth from a rewrite.
425
-
426
- ```ts type-equiv
427
- /** One replacement operation observed while folding a session surface. */
428
- interface SurfaceFoldReplacement {
429
- /** Seq of the event that replaced the prior surface range. */
430
- seq: SessionSeq
431
- /** Declared inclusive start seq of the replaced surface range. */
432
- start: SessionSeq
433
- /** Declared inclusive end seq of the replaced surface range. */
434
- end: SessionSeq
435
- /** Actual surface entries removed by the operation, in surface order. */
436
- shadowedSeqs: SessionSeq[]
437
- }
438
- ```
439
-
440
- ```ts type-equiv
441
- /** Complete result of replaying the surface operations in a session log. */
442
- interface SurfaceFoldResult {
443
- /** Current surface event sequences in model-visible order. */
444
- nodes: SessionSeq[]
445
- /** Replacement operations in event order. */
446
- replacements: SurfaceFoldReplacement[]
447
- /** Immutable projected messages, keyed by their original event sequences. */
448
- projectedMessages: ReadonlyMap<SessionSeq, Message>
449
- }
450
- ```
451
-
452
- ## `Session` public API
453
-
454
- The body-stripped declaration keeps the plain class's detached factory, state accessors, append method, and history projections synchronized with source. Store operations remain in the generated [`ctx.sessions` section](#ctxsessions--sessionstore).
455
-
456
- ```ts public-api
457
- /**
458
- * An event-sourced session: an append-only log of {@link SessionEvent}s.
459
- *
460
- * Plain class (not a Service) — create live instances via
461
- * `ctx.sessions.create()` and detached instances via {@link create}.
462
- * Seeding with an existing event log replays/forks a session.
463
- * @typert object
464
- */
465
- declare class Session {
466
- /** The ordered surface over this session's event log. */
467
- get surface(): SessionSurface;
468
- /**
469
- * Detached, deep-frozen creation metadata (format version, cwd, lineage,
470
- * and whether fork history exists). Supplied by the store via `ctx.sessions.create()`. When a
471
- * `Session` is created without a store-owned header, a minimal header is
472
- * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
473
- * `session.header` is always present. Kept out of the event log — it is a
474
- * storage concern, not replayable conversation state.
475
- */
476
- readonly header: SessionHeader;
477
- /** Number of leading events inherited from this Session's fork parent. */
478
- readonly inheritedEventCount: SessionLogOffset;
479
- /** The session identity, derived from its durable header's single copy. */
480
- get id(): SessionId;
481
- /**
482
- * The constructor seed length (0 without one), before any marker appended
483
- * during construction. Seed events never publish on `session/event`. A
484
- * marker appended before the store attaches occupies this seq without
485
- * publishing either; otherwise this seq is available for the next append.
486
- *
487
- * This in-process offset is not persisted. A fork seed can already contain
488
- * the child's inherited marker and synthetic closers, so its child-owned
489
- * history starts at {@link inheritedEventCount}, before this offset. A
490
- * resumed Session's seed contains its full stored log, while its inherited
491
- * count keeps the durable fork cut. Consumers needing complete canonical
492
- * history start at seq 0.
493
- */
494
- readonly firstLiveSeq: SessionLogOffset;
495
- /**
496
- * First event produced for this object lifecycle. A new fork includes its
497
- * child-owned seed marker and closers; a restored Session starts after its
498
- * complete stored prefix. This in-process capture offset is not persisted.
499
- */
500
- readonly firstLifecycleSeq: SessionLogOffset;
501
-
502
- /**
503
- * Create a detached session by validating and snapshotting borrowed seed
504
- * events and storage metadata.
505
- * @param id - session identity.
506
- * @param seed - optional borrowed replay or fork events.
507
- * @param header - optional borrowed storage metadata.
508
- * @param inheritedEventCount - exact fork-inherited prefix length for a seeded header.
509
- * @param projections - pure interpreters for plugin-owned message changes.
510
- * @returns a detached session.
511
- * @throws when a seed event requires a missing message interpreter or fails validation.
512
- */
513
- static create(
514
- id: SessionId,
515
- seed?: readonly SessionEvent[],
516
- header?: SessionHeader,
517
- inheritedEventCount?: SessionLogOffset,
518
- projections?: readonly SessionMessageProjection[],
519
- ): Session;
520
- /**
521
- * Restore a detached session by adopting an independently owned or deeply frozen seed.
522
- * Runtime-required event fields, event envelopes, sequence continuity, surface
523
- * transitions, and header fields are validated without copying or freezing events.
524
- * Embedded Assistant streams remain opaque until a stream consumer or storage
525
- * verifier reads them.
526
- * @param id - restored session identity.
527
- * @param seed - independently owned or deeply frozen events.
528
- * @param header - independently owned storage metadata.
529
- * @param inheritedEventCount - exact fork-inherited prefix length decoded from storage.
530
- * @param eventState - aliasing state carried from the operation that produced the seed.
531
- * @param projections - pure interpreters for plugin-owned message changes.
532
- * @returns a restored detached session.
533
- * @throws when a seed event requires a missing message interpreter or fails validation.
534
- */
535
- static fromRestore(
536
- id: SessionId,
537
- seed: readonly SessionEvent[],
538
- header: SessionHeader,
539
- inheritedEventCount: SessionLogOffset,
540
- eventState: SessionSeedEventState,
541
- projections?: readonly SessionMessageProjection[],
542
- ): Session;
543
- /**
544
- * Return the immutable event stored at one exact sequence number.
545
- * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
546
- * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
547
- * @param seq - event sequence number.
548
- * @returns the accepted event, or undefined when the log does not contain it.
549
- */
550
- eventAt(seq: SessionSeq): SessionEvent | undefined;
551
- /**
552
- * Materialize an immutable snapshot of a half-open event sequence range.
553
- * A full current snapshot is reused until the next append; every previously
554
- * returned snapshot remains stable after later appends.
555
- * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
556
- * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
557
- * @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
558
- * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
559
- * @returns a frozen array of the selected deeply frozen events.
560
- */
561
- snapshotEvents(
562
- fromSeq: SessionLogOffset = SessionLogOffset(0),
563
- toSeqExclusive: SessionLogOffset = this.seq,
564
- ): readonly SessionEvent[];
565
- /**
566
- * Return this Session's events after its fork-inherited prefix.
567
- * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
568
- * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
569
- * @returns a fresh array containing child-owned events in log order.
570
- */
571
- ownEvents(): readonly SessionEvent[];
572
- /**
573
- * Whether one existing event position is outside the fork-inherited prefix.
574
- * @param seq - event position in this Session.
575
- * @returns true when the event belongs to this Session rather than its parent.
576
- */
577
- isOwnSeq(seq: SessionSeq): boolean;
578
- /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
579
- get seq(): SessionLogOffset;
580
- /**
581
- * Append one typed event to the log and synchronously notify observers via
582
- * the store-owned, module-private publication hooks. The hot path never blocks
583
- * on I/O — persistence plugins buffer asynchronously. Once the event enters
584
- * the log, the append is committed: observer failures are logged and
585
- * contained per listener, so they do not change the return value or prevent
586
- * later listeners from observing the same accepted event.
587
- * Independent Sessions append without notifying store observers. Once a store
588
- * prepares or enters the instance, writes require a completed creation
589
- * announcement and remain disabled after removal.
590
- *
591
- * @param type - The event type (key of {@link SessionEventMap}).
592
- * @param data - The event payload; must be JSON-serializable.
593
- * @param opts - Surface metadata: `surfaceOp` controls how the event enters
594
- * the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier
595
- * events this one derives from. REQUIRED for
596
- * {@link SurfaceEventType} events (every message-producing event must
597
- * declare how it joins the surface, the sole source of derived model
598
- * history) and
599
- * rejected by the compiler for non-surface types like `turn/start` or
600
- * `assistant/attempt`. Assistant messages embed their exact provider
601
- * stream and cannot cite top-level source events.
602
- * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
603
- * `data` that entered the log, so reading `event.data` back sees the logged
604
- * value, never the caller's still-mutable input.
605
- * @throws if a store-owned Session is unentered or its creation announcement
606
- * has not completed, or if `data` or surface
607
- * metadata is not losslessly JSON-serializable
608
- * (BigInt, function, symbol, undefined, negative zero, non-finite number,
609
- * circular reference, sparse array, or an exotic object such as
610
- * Map/Set/Date/class instance), or when the candidate violates the
611
- * request-header empty-field or tool-error consistency rules, or the
612
- * canonical surface contract (marker shape and eligibility, unique
613
- * earlier source-event references, positional replacement validity, and complete
614
- * shadowed-node coverage). One iterative pass reads, validates, and
615
- * copies each nested value once, so a stateful getter cannot supply one value
616
- * to validation and another to storage. The event log is the durable source
617
- * of truth, so a bad event fails at the append site rather than later during
618
- * a backend flush. A synchronous internal dispatch validation failure or an
619
- * append reentered while this acceptance/publication boundary is open also
620
- * rejects before the log changes.
621
- */
622
- append<T extends SessionEventType>(
623
- type: T,
624
- data: SessionEventMap[T],
625
- ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent<T>] : []
626
- ): SessionEvent<T>;
627
- /**
628
- * The {@link EpochHeader} in force after the log's last header event — the
629
- * header the NEXT request will be compared against — or undefined before
630
- * the first `request/header` snapshot. The live, incrementally-maintained
631
- * form of `foldRequestHeader(session.snapshotEvents())`: each header event is folded
632
- * once, when first seen, so a per-step read costs O(new events).
633
- * @returns the folded header, or undefined when no header event exists yet.
634
- */
635
- requestHeader(): EpochHeader | undefined;
636
- /**
637
- * Return the latest resolved route metadata, or `undefined` before the first
638
- * `request/context` event. Each event is folded once.
639
- * @returns the latest immutable route metadata.
640
- */
641
- requestContext(): RequestContext | undefined;
642
- /**
643
- * Fold unseen committed events into capability-independent tool history.
644
- * Initial access reconstructs inherited history; later reads consume only new events.
645
- * @returns an immutable snapshot for LLM request projection, including historical addition definitions.
646
- */
647
- toolHistory(): ToolHistory;
648
- /**
649
- * Derive the LLM message history by walking the ordered sequences of
650
- * message-producing events maintained by `surfaceOp` markers. The
651
- * surface is the single source of derived history: every message-producing
652
- * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
653
- * turn boundary) is correctly absent, and a compaction `replace` deletes the
654
- * shadowed nodes from the derivation. The projection rules are
655
- * {@link deriveEventMessage}, with logged message projections applied
656
- * without changing node membership or message identity.
657
- *
658
- * CACHED: pure tail growth costs O(new nodes); a replacement or message projection
659
- * ({@link SessionSurface.contentGeneration}) rebuilds. The returned array is
660
- * a fresh snapshot per call (later appends never grow an array a caller
661
- * already holds); the `Message` objects in it are SHARED and **deep-frozen**.
662
- * Unchanged content reuses frozen event data; projected blocks are frozen
663
- * derived copies. Consumers cannot mutate the log through either form.
664
- * @returns a fresh array of the shared, frozen derived history.
665
- */
666
- deriveMessages(): Message[];
667
- /**
668
- * Project one event with all committed message projections applied.
669
- * The original durable event remains unchanged.
670
- * @param event - the event to project.
671
- * @returns the derived message, or null when the event produces none.
672
- */
673
- deriveEventMessage(event: SessionEvent): Message | null;
674
- }
675
- ```
676
-
677
- ## Derived history: `deriveMessages()` and `deriveEventMessage()`
678
-
679
- `Session.deriveMessages()` projects the event log into the `Message[]` the model sees — cached (each surface node projected once, when first seen; a surface rewrite rebuilds) and frozen (a fresh array per call over shared, deep-frozen messages, so mutating logged history through a projection is unrepresentable). `deriveEventMessage(event)` is the per-node pure function the fold applies — public so external reconstructors project a log prefix with exactly the same rules and cannot disagree with the cache. The projection rules:
680
-
681
- - `user/message` → a user message carrying exact `content`; an optional envelope remains log-only display metadata.
682
- - `assistant/message` → an assistant message with the provider and model that produced it plus optional adapter-private replay state. Its embedded compact stream is replay, usage, and UI evidence rather than a second message. An **empty-content** `assistant/message` is also skipped — a max-tokens step cut off with no content still records an `assistant/message` to hold its stream, usage, provider, and model, but a content-less assistant turn must not enter the provider transcript.
683
- - `tool/result` → a first-class tool-role message carrying its result content and tool-call identity.
684
- - `user/message` (injected context, i.e. non-`user` source) → a user-role message carrying its `content` verbatim at its chronological position; its typed source names the producer and carries any producer-specific data.
685
-
686
- Everything else (`turn/*`, `step/*`, `assistant/attempt`, plugin-owned `llm/retry`) is structural and does not project into a message. Token accounting expands the embedded stream on each `assistant/message` or `assistant/attempt`, while the message's top-level `usage` remains the committed-message authority when present. A failed model-request attempt therefore retains its provider usage without fabricating an assistant message. Current logical validation rejects request headers and assistant messages that omit provider/model instead of guessing a route; supported historical representations are normalized and validated by their adjacent format edge before a current Session exists.
687
-
688
- ## Live-session fork API
689
-
690
- `ctx.sessions.create(id, { seed, meta })` is the low-level replay/fork primitive. For ordinary live-session forks, `SessionStore` exposes one policy API:
691
-
692
- - `fork(source, boundary?, childSessionId?)` accepts a live `Session` object or live `SessionId`, selects source events through the inclusive `SessionSeq` boundary (default: current last event), closes any open tail, then creates an independent live session with deep-cloned seed events, `isSeeded: true`, the exact `inheritedEventCount`, and inherited `cwd`, without `parentSession`.
693
-
694
- An explicit `boundary` lets callers fork from any stable between-turn position, including a previous `turn/end` or a later standalone log-only event, even if the source has newer events or an open current turn. The API rejects a prefix that ends inside an open turn instead of clipping silently. `dsh-subagent-fork-in-process` keeps its completed-prefix clipping because tool-time delegation usually starts while the parent turn is open; ordinary session branching should make the requested boundary explicit.
695
-
696
- ## Why a turn ended: `TurnEndReasonMap`
697
-
698
- `turn/start` has no trigger field. The entered `user/message` batch records what entered each step, `llm/retry` records request recovery, and idle injection remains pending until a waking delivery reaches a later pre-step. Live turns retain the typed [`AgentCancelCause`](./core.md#the-agent-handle) that stopped the driver; persistence uses the additional `{ kind: 'legacy' }` cause only when importing a supported coarse cancellation record that did not store its caller.
699
-
700
- ```ts type-equiv
701
- /** Durable cancellation cause, including imports whose original coarse record carried no cause. */
702
- type TurnEndCancelCause = AgentCancelCause | { readonly kind: 'legacy' }
703
- ```
704
-
705
- ```ts type-equiv
706
- /**
707
- * Why a turn ended. Merge-extensible sum type.
708
- */
709
- interface TurnEndReasonMap {
710
- completed: { kind: 'completed' }
711
- /** A cancellation request interrupted the live turn. */
712
- aborted: { kind: 'aborted'; reason: TurnEndCancelCause }
713
-
714
- blocked: { kind: 'blocked' }
715
- /**
716
- * The turn failed. `error` is always a structured failure: the `LlmError`
717
- * facts verbatim, or `{ message: errorChain(error), code }` flattened from
718
- * any other error, where `code` is `TOOL_ACTIVATION_FAILED` for a failed
719
- * tool condition and `UNKNOWN` otherwise.
720
- */
721
- error: { kind: 'error'; error: LlmFailure }
722
- /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */
723
- 'max-tokens': { kind: 'max-tokens' }
724
- /**
725
- * A crash-orphaned turn was closed after the fact: agent-loop resume appends
726
- * this closer for a stored log whose last turn never ended, and session-query
727
- * synthesizes it on cold reads. The loop never emits this marker live, and
728
- * the events recorded before the crash remain intact.
729
- */
730
- interrupted: { kind: 'interrupted' }
731
- /**
732
- * Fork-seed construction closed a turn that was still open at the fork
733
- * boundary in the source session. Only fork seeds carry this marker — the
734
- * loop never emits it — and the source events before the boundary remain
735
- * intact in the child.
736
- */
737
- forked: { kind: 'forked' }
738
- }
739
- ```
740
-
741
- `max-tokens` mirrors the model-call `FinishReason` of the same name: any `max-tokens` step in a turn makes the whole turn end `max-tokens` rather than `completed` (the cut-short fact wins over a later continuation), so a consumer can tell a clean stop from a truncated one. Cancellation and errors remain distinct outcomes. The loop emits neither `interrupted` nor `forked` live: crash recovery synthesizes `interrupted` (see [persistence.md](./persistence.md)), while fork-seed construction synthesizes `forked`. The map is merge-extensible.
742
-
743
- ## Execution enclosure and standalone events
744
-
745
- A turn encloses one model-loop execution, not the whole session log. AgentLoop records injected `user/message` events only from entering pre-step batches inside a turn; plugin-owned log-only events may still appear between `turn/end` and the next `turn/start`, consuming event seqs without incrementing turn numbers. Persistence admits every contiguous accepted event into a bounded durable batch, while crash repair closes only a genuinely open trailing turn. A producer that needs an immediate durability barrier explicitly awaits `ctx.sessions.flush(session)`.
746
-
747
- Merge-extensible event relations belong to the plugin that declares them, so core does not reject an unknown event merely because no turn is open. See [the standalone-event decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/simplification/2026-07-28-remove-synthetic-log-only-turns.md).
748
-
749
- ## The end-seed boundary: `session/end-seed`
750
-
751
- `buildForkSeed` appends `session/end-seed { inherited: true }` at the exact inherited-prefix cut before adding synthetic fork closers. The `Session` constructor retains that prepared marker or appends one when given only the inherited prefix. A restore retains the tagged marker and appends an ordinary `session/end-seed {}` only when its complete stored seed does not already end in a marker. Both forms are log-only and produce no message; only the constructor and `buildForkSeed` may create them.
752
-
753
- For fork lineage, locate the LAST marker whose payload carries `inherited: true`; current-format decoding requires it exactly when `SessionHeader.isSeeded` is true and derives `inheritedEventCount` from its seq. For lifecycle ownership, locate the last `session/end-seed` of either form. Reopening a seed that already ends in any marker does not append another ordinary marker.
754
-
755
- It exists because seed history and live work are otherwise byte-identical, which defeats any plugin owning a standalone open/close bracket: an unmatched `compaction/start` reads the same whether the writer crashed mid-compaction or is compacting right now. An opening marker before `session/end-seed` came from the constructor seed and belongs to an ended lifecycle, whatever ended it (a crash, a succeeding process, or a fork out of a still-running parent), so its owner may treat it as dead. That covers only brackets *this* session inherited: a concurrently live session holding an open bracket over the same history has its own boundary elsewhere, so tolerating concurrent writers needs a liveness signal beyond the log. Core writes the boundary and reads nothing from it — a bracket's vocabulary stays with its owning plugin, which is why crash repair closes turn/step/tool boundaries and never `compaction/*`.
756
-
757
- Consumers that order Sessions by human activity exclude this boundary: picking a Session up is not work, so ordering by the log tail would float every opened Session to the top.
758
-
759
- ## Plugin-contributed log-only events
760
-
761
- A plugin may declaration-merge extra `SessionEventMap` types. These are **log-only**: NOT `SurfaceEventType`s (they carry no `surfaceOp` and contribute nothing to derived history). Their owner decides whether they belong to an open execution turn or may stand between turns. The generated [persistence log event catalog](../persistence-catalog.md) enumerates every core and plugin-contributed event; the compaction seam's `compaction/*` semantics are discussed on [compaction.md](./compaction.md).
762
-
763
- When several events in one plugin-owned family assemble into one Web Client Conversation Node, every start, update, result, resource, or interruption event in that family carries or independently derives the same stable business id. This requirement applies to correlated Node families, not to every Session event; it lets the client group each event without guessing from adjacency or scanning history. See the [Conversation subsystem](./conversation.md).
764
-
765
- The hook bridges' `hook/invoked` / `hook/result` pairs (from `@deepseek-ai/dsh-hook-protocol`) correlate by `handlerId`. `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, and `Stop` fire inside the loop's open turn, so their `hook/*` records are turn-enclosed by construction. `SessionStart` gets no `hook/*` record because it runs before turn 1; its context remains pending in the inbox until a waking delivery opens a turn.
766
-
767
- ### Plugin records
768
-
769
- Experimental packages declare plugin-owned state in `PluginRecordMap`: `appendPluginRecord()` uses each declaration to type its name and payload, and appends an event marked `ignorable: true` in the `plugin:` namespace. `pluginRecordOf()` reads stored records with unknown payloads regardless of current declarations. The [experimental persistence catalog](../experimental-persistence-catalog.md) lists current declarations. The [package README](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/README.md#write-experimental-plugin-records) owns the caller restriction, retention, and read path.
770
-
771
- ```ts type-equiv
772
- /**
773
- * Event type of an experimental plugin record: `plugin:` followed by
774
- * slash-separated segments of lowercase letters, digits, `.`, `_`, and `-`,
775
- * each starting with a letter or digit. A record type is never a
776
- * {@link SessionEventMap} member.
777
- */
778
- type PluginRecordType = `plugin:${string}`
779
- ```
780
-
781
- ```ts type-equiv
782
- /**
783
- * Payloads written by experimental packages, keyed by their `plugin:` record
784
- * names. Packages augment this map to type writes and enter the current plugin
785
- * record catalog; these declarations do not enter {@link SessionEventMap} or
786
- * released persistence schemas. Stored records still require owner validation.
787
- */
788
- interface PluginRecordMap {}
789
- ```
790
-
791
- ```ts type-equiv
792
- /**
793
- * One committed experimental plugin record, read from the log by
794
- * `pluginRecordOf`. The record's owner validates `data` before use, because a
795
- * restored record carries whatever JSON an earlier build of its owner wrote,
796
- * or a V3 event that a format migration renamed into the `plugin:` namespace held.
797
- */
798
- interface PluginRecord {
799
- /** The record type, chosen by the owning plugin. */
800
- readonly type: PluginRecordType
801
- /** The record's position in the Session log. */
802
- readonly seq: SessionSeq
803
- /** Unix epoch milliseconds at append. */
804
- readonly time: number
805
- /** The JSON payload as committed. */
806
- readonly data: unknown
807
- }
808
- ```
809
-
810
- ## Durability contract
811
-
812
- What a persistence backend relies on: the durable log persists every event losslessly, and every Assistant attempt is one `assistant/message` or `assistant/attempt` whose embedded compact stream preserves the original timed chunks. `seq` stays contiguous across these settlements and all interleaved events. A backend may choose its own storage framing for an event batch as long as a handle's `read()` returns the exact appended events; current JSONL writes one row per event (see [persistence.md](./persistence.md)). All `event.data` must be JSON-serializable; `Session.append` enforces this at the source (throwing on non-serializable data), so a bad event never enters the log and `session.snapshotEvents()` always equals what a backend can persist. Adding an event type that carries non-serializable data, corrupts core execution nesting, or violates its owner's declared relation is a breaking change to the on-disk format.
813
-
814
- The backends that consume this contract are on [persistence.md](./persistence.md).
815
-
816
- ## Remote catalog and workspace opening
817
-
818
- `ModelCatalog` is the Host-generation model directory returned by `session/modelCatalog`: it carries the deployment default, routable provider ids, successful provider groups, and isolated provider failures. It is not derived from one Session and remains separate from Session projections.
819
-
820
- `SessionOpenWorkspacePathRequest` carries an absolute or workspace-resolved `path`; optional `action: "reveal"` selects file-manager navigation instead of default-application opening. `SessionOpenWorkspacePathValue` confirms that the Host accepted the native handoff. A Session-aware Client resolves relative paths against its current Session cwd when known; the controller hands the path to the opener unchanged and reports invalid requests, cancellation, and opener failures through the Session Remote error vocabulary.
821
-
822
- The optional `application` selects a registered file handler without changing the system default; `workspacePathApplications({ path })` returns current handlers, names, icons, and default selection after Host path verification.
823
-
824
- ## Session-log upload exclusions
825
-
826
- `ctx.sessionLogDeepSeek.registerExclusion()` registers a caller-owned predicate over `SessionLogUploadRequest`. Any match omits the log contribution and its acceptance callback before reading Session events. No match preserves normal upload eligibility. The [package README](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/session/session-log-deepseek/README.md#upload-exclusions) defines failure and disposal behavior.
827
-
828
- ```ts type-equiv
829
- /** Request identity inspected before preparing a Session-log contribution. */
830
- interface SessionLogUploadRequest {
831
- /** Live Session whose canonical log would be contributed. */
832
- readonly sessionId: SessionId
833
- /** Auxiliary request classification; absent for ordinary conversation requests. */
834
- readonly purpose?: string
835
- }
836
- ```
837
-
838
- ```ts type-equiv
839
- /**
840
- * Synchronous, side-effect-free upload exclusion owned by its registering plugin.
841
- * @param request - request identity; the predicate must not mutate it.
842
- * @returns `true` to omit the log field and acceptance callback, or `false` to keep checking eligibility.
843
- */
844
- type SessionLogUploadExclusion = (request: SessionLogUploadRequest) => boolean
845
- ```
846
-
847
- <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
848
-
849
- <a id="cordis-surface"></a>
850
-
851
- ## Cordis API
852
-
853
- Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md).
854
-
855
- <a id="ctxsessioncontroller--sessioncontroller"></a>
856
-
857
- ### `ctx.sessionController` — `SessionController`
858
-
859
- Host service backing the generated `ctx.remote.session` namespace.
860
-
861
- ```ts cordis-catalog
862
- /**
863
- * Resolve or resume one ordinary Session for another Host API domain.
864
- * @param sessionId - Session identity whose Agent owns the operation.
865
- * @returns the live Agent or the stable Session-domain failure.
866
- */
867
- resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult>
868
-
869
- /**
870
- * Read all visible Session rows without resuming an Agent.
871
- * @param _request - reserved empty list request.
872
- * @param signal - cancellation for persistence reads and summary generation.
873
- * @returns visible Session summaries ordered by activity.
874
- */
875
- @Remote('list') async list(_request: SessionListRequest, signal: AbortSignal): Promise<SessionListValue>
876
-
877
- /**
878
- * Search visible Session content without resuming an Agent. A non-owner
879
- * receives only the hits whose Session `allows()` admits; `hasMore`
880
- * describes the bounded result before that filtering.
881
- * @param request - literal message-content query.
882
- * @param signal - cancellation for list and search reads.
883
- * @returns authorized bounded Session search results.
884
- */
885
- @Remote('search') async search(request: SessionSearchRequest, signal: AbortSignal): Promise<SessionSearchValue>
886
-
887
- /**
888
- * Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable.
889
- * @param request - optional blank Session to reuse, location, and Agent preset.
890
- * @returns the created or reused Session identity and its preset when configured.
891
- */
892
- @Remote('create') create(request: SessionCreateRequest): Promise<SessionCreateValue>
893
-
894
- /**
895
- * Select one Session-local model after explicitly resuming the Session; save the default in the background.
896
- * @param request - Session identity and requested model selection.
897
- * @returns the normalized selection installed for the Session, without waiting for default persistence.
898
- */
899
- @Remote('selectModel') selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue>
900
-
901
- /**
902
- * Select the first available account model after login when no provider API key is configured.
903
- * @returns after saving the first available model or retaining the existing default.
904
- */
905
- @Remote async initializeDefaultModel(): Promise<void>
906
-
907
- /**
908
- * Describe every currently routable model for Host-generation selectors.
909
- * @returns provider-grouped models, the deployment default, and isolated provider failures.
910
- */
911
- @Remote('modelCatalog') modelCatalog(): Promise<ModelCatalog>
912
-
913
- /**
914
- * Report whether this deployment can hand a Session workspace path to a native desktop.
915
- * @returns true when the matching open operation is available.
916
- */
917
- @Remote canOpenWorkspacePath(): boolean
918
-
919
- /**
920
- * Describe the serving desktop for authenticated file-action routes.
921
- * @returns Host name, configured availability, and platform-specific file-manager behavior.
922
- */
923
- workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | 'explorer' | 'directory' | null }
924
-
925
- /**
926
- * Verify one path through the composed filesystem and open it on the Host desktop.
927
- * @param request - path after best-effort Session workspace resolution.
928
- * @param signal - caller lifetime; abort terminates the native command.
929
- * @returns confirmation after the native opener accepts the path.
930
- * @throws RemoteError when the request is invalid, has no verified Host mapping, is cancelled, or the opener fails.
931
- */
932
- @Remote('openWorkspacePath') async openWorkspacePath( request: SessionOpenWorkspacePathRequest, signal: AbortSignal, ): Promise<SessionOpenWorkspacePathValue>
933
-
934
- /**
935
- * Query current file handlers on the serving desktop without activating an Agent.
936
- * @param request - file path in Host filesystem syntax.
937
- * @param signal - caller lifetime, propagated to filesystem and desktop queries.
938
- * @returns OS application names, icons, and default selection; empty when desktop opening is unavailable.
939
- * @throws RemoteError when the path is invalid, the query is cancelled, or native discovery fails.
940
- */
941
- @Remote('workspacePathApplications') async workspacePathApplications( request: { readonly path: string }, signal: AbortSignal, ): Promise<readonly SessionWorkspacePathApplication[]>
942
-
943
- /**
944
- * Rename one Session after explicitly resuming it.
945
- * @param request - Session identity and proposed title.
946
- * @returns the accepted title and durable event sequence.
947
- */
948
- @Remote('rename') rename(request: SessionRenameRequest): Promise<SessionRenameValue>
949
-
950
- /**
951
- * Fork one cold-readable exact event prefix into a new Session. An omitted
952
- * boundary selects the latest completed-turn prefix; an open cut receives
953
- * synthetic fork closers.
954
- * @param request - source Session, optional exact inclusive event boundary, and migration preflight choice.
955
- * @returns the new Session identity.
956
- */
957
- @Remote('fork') async fork(request: SessionForkRequest): Promise<SessionForkValue>
958
-
959
- /**
960
- * Admit one prompt after explicitly resuming its Session.
961
- * @param request - Session identity, prompt content, source metadata, and delivery mode.
962
- * @param signal - caller cancellation before prompt admission begins.
963
- * @returns acknowledgement that the Agent accepted the prompt.
964
- */
965
- @Remote('prompt') async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<SessionPromptValue>
966
-
967
- /**
968
- * Read one image from the attachment store after gateway authorization.
969
- * @param request - image reference and gateway permission scope; Session existence is not checked.
970
- * @returns the durable attachment reference and base64-encoded bytes.
971
- */
972
- @Remote('attachment') attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue>
973
-
974
- /**
975
- * Mutate one still-pending queue occurrence, resuming a cold Agent first.
976
- * @param request - Session, queue item, and requested mutation.
977
- * @returns acknowledgement that the queue mutation was applied.
978
- */
979
- @Remote('updateQueue') updateQueue(request: SessionUpdateQueueRequest): Promise<SessionUpdateQueueValue>
980
-
981
- /**
982
- * Cancel one active Agent turn without dropping its pending inbox.
983
- * @param request - Session whose active Agent turn is cancelled.
984
- * @returns acknowledgement that cancellation was requested.
985
- */
986
- @Remote('cancel') cancel(request: SessionCancelRequest): SessionCancelValue
987
-
988
- /**
989
- * Read one cold-safe, message-aligned Session history page.
990
- * @param request - durable address, optional fixed cut, backward cursor, and page budget.
991
- * @param signal - cancellation for persistence reads.
992
- * @returns one chronological page with its inclusive cursor.
993
- */
994
- @Remote events(request: SessionPageRequest, signal: AbortSignal): Promise<SessionEventsPage>
995
-
996
- /**
997
- * Subscribe to Session events without reading a snapshot.
998
- * @param request - Session address.
999
- * @param signal - subscription cancellation.
1000
- * @returns readiness and subsequent events, without a snapshot.
1001
- */
1002
- @Remote({ mode: 'stream' }) observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable<SessionEventFrame>
1003
-
1004
- /**
1005
- * Subscribe to Session projection changes.
1006
- * @param request - target Session.
1007
- * @param signal - subscription cancellation.
1008
- * @returns readiness followed by one projection change frame per committed event.
1009
- */
1010
- @Remote({ mode: 'stream' }) observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable<SessionProjectionFrame>
1011
-
1012
- /**
1013
- * Read passive Session state.
1014
- * @param request - target Session.
1015
- * @param signal - read cancellation.
1016
- * @returns current passive state.
1017
- */
1018
- @Remote state(request: SessionStateRequest, signal: AbortSignal): Promise<SessionState>
1019
-
1020
- /**
1021
- * Subscribe to complete Session state replacements.
1022
- * @param request - target Session.
1023
- * @param signal - subscription cancellation.
1024
- * @returns complete passive state replacements.
1025
- */
1026
- @Remote({ mode: 'stream' }) observeState(request: SessionStateRequest, signal: AbortSignal): AsyncIterable<SessionState>
1027
-
1028
- /**
1029
- * Wait for Session quiescence or pending input with bounded assistant output.
1030
- * @param request - Session, wait bounds and output window.
1031
- * @param signal - caller cancellation.
1032
- * @returns stopping state and bounded assistant output.
1033
- */
1034
- @Remote wait(request: SessionWaitRequest, signal: AbortSignal): Promise<SessionWaitValue>
1035
-
1036
- /**
1037
- * Follow one Session log from its opening or resume cursor.
1038
- * @param request - durable address and last committed sequence already held by the caller.
1039
- * @param signal - cancellation owned by the Remote stream carrier.
1040
- * @returns a complete opening snapshot followed by gap-free durable event
1041
- * frames and optional cursorless assistant-stream frames.
1042
- */
1043
- @Remote({ mode: 'stream' }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame>
1044
-
1045
- /**
1046
- * Read exact projections, returning cached hints only when migration is required.
1047
- * @param request - Session whose current values are required.
1048
- * @param signal - cancellation for the Session read.
1049
- * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent.
1050
- */
1051
- @Remote('projections') projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise<SessionProjectionsValue>
1052
-
1053
- /**
1054
- * Stream a complete live-control baseline followed by replacement frames.
1055
- * @param signal - cancellation owned by the Remote stream carrier.
1056
- * @returns one complete baseline followed by live replacement frames.
1057
- */
1058
- @Remote({ mode: 'stream' }) async *control(signal: AbortSignal): AsyncIterable<SessionControlFrame>
1059
- ```
1060
-
1061
- Types: [SessionId](./core.md) · [SessionSearchRequest](./session-query.md)
1062
-
1063
- Source: [`packages/api/session-controller/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/index.ts)
1064
-
1065
- <a id="ctxsessionlogdeepseek--sessionlogdeepseekservice"></a>
1066
-
1067
- ### `ctx.sessionLogDeepSeek` — `SessionLogDeepSeekService`
1068
-
1069
- Incremental Session-log contributor with caller-owned upload exclusions.
1070
-
1071
- ```ts cordis-catalog
1072
- /**
1073
- * Exclude matching requests before reading or preparing their log contribution.
1074
- * Any matching rule suppresses both the field and its acceptance callback. With
1075
- * no matching rules, normal upload eligibility applies. A throwing rule fails
1076
- * this contribution; the request-extension registry omits it and reports the error.
1077
- * @param exclude - synchronous, side-effect-free predicate; `true` skips this upload.
1078
- * @returns effect disposer that removes this registration when called or when the caller unloads.
1079
- */
1080
- registerExclusion(exclude: SessionLogUploadExclusion): () => Promise<void>
1081
- ```
1082
-
1083
- Source: [`packages/session/session-log-deepseek/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/session/session-log-deepseek/src/index.ts)
1084
-
1085
- <a id="ctxsessions--sessionstore"></a>
1086
-
1087
- ### `ctx.sessions` — `SessionStore`
1088
-
1089
- In-memory session store (`ctx.sessions`).
1090
-
1091
- Persistence is intentionally not implemented here — the agent lifecycle attaches a session-log writer to each published session's write handle; a session published outside that lifecycle persists nothing.
1092
-
1093
- ```ts cordis-catalog
1094
- /**
1095
- * Register one event interpreter for live creation, restore, and fork.
1096
- * Disposing the contribution makes sessions that used it refuse further derivation.
1097
- * @param projection - pure definition owned by the event's plugin.
1098
- * @returns the fiber-owned disposer.
1099
- * @throws when another definition already owns this event type.
1100
- */
1101
- registerMessageProjection(projection: SessionMessageProjection): () => Promise<void>
1102
-
1103
- /**
1104
- * Create a session owned by the calling fiber: disposing that fiber stops
1105
- * event notification and removes the session from the store. `options.seed`
1106
- * populates the session with a copy of those events (replay/fork);
1107
- * `options.meta` attaches creation metadata (validated absolute `cwd`, seed
1108
- * and parent lineage, and delegation depth) as the immutable
1109
- * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).
1110
- *
1111
- * For an agent whose session must be torn down IN ORDER with its loop (so the
1112
- * loop's final events are published before the store attachment ends), do NOT use this
1113
- * — fold the session lifecycle into the agent's own effect via
1114
- * {@link prepare} + {@link enter} + {@link announce} (see
1115
- * `dsh-agent-loop`'s creation transaction).
1116
- *
1117
- * @param id - the session id; omitted, the store mints `session-<n>`.
1118
- * @param options - seed events and/or creation metadata for the header.
1119
- * @returns the live session, already entered and announced.
1120
- * @throws if a session with `id` already exists, metadata is not a plain
1121
- * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
1122
- * non-absolute path (storage backends key directories off it).
1123
- */
1124
- create(id?: SessionId, options?: CreateSessionOptions): Session
1125
-
1126
- /**
1127
- * Build a session WITHOUT entering it into the store — validate the id/cwd and
1128
- * construct the {@link Session} (with its immutable {@link SessionHeader}).
1129
- * Pairs with {@link enter} + {@link announce}: a caller that owns a composite
1130
- * `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
1131
- * effect so a fiber unload tears the session + agent down as a single ORDERED
1132
- * chain rather than as racing sibling effects — which would remove the publication hooks
1133
- * before the driver's closing events commit, dropping them.
1134
- *
1135
- * @param id - the session id; omitted, the store mints `session-<n>`.
1136
- * @param options - seed events and/or creation metadata for the header. With
1137
- * `eventState`, every seed event is either independently owned or any
1138
- * shared value is deeply frozen; {@link Session.fromRestore} validates and
1139
- * adopts those values without copying or freezing them.
1140
- * @returns the store-owned session, not yet entered and read-only until announced.
1141
- * @throws if a session with `id` already exists, metadata is not a plain
1142
- * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
1143
- * non-absolute path.
1144
- */
1145
- prepare(id?: SessionId, options?: PrepareSessionOptions): Session
1146
-
1147
- /**
1148
- * Enter a session into the store: install the module-private
1149
- * append publication hooks and add it to the store. Writes remain disabled
1150
- * until {@link announce} completes successfully. Returns the DETACH
1151
- * disposer (hooks + store removal). Does NOT emit `session/created` —
1152
- * the caller yields this disposer inside its effect and THEN calls
1153
- * {@link announce}, so a throwing `session/created` listener rolls the attach
1154
- * back instead of leaking it.
1155
- *
1156
- * Re-checks the id for a duplicate: `prepare` and `enter` are public
1157
- * cross-package primitives and a caller may interleave arbitrary work (or
1158
- * another create) between them, so a stale prepared session must NOT overwrite
1159
- * a live store entry of the same id — its detach disposer would later delete
1160
- * the REAL session. The {@link create} convenience and the agent factory call
1161
- * the two back-to-back so they never trip this, but the public API cannot
1162
- * assume that.
1163
- *
1164
- * @param session - an unentered session; independent instances become store-owned.
1165
- * @returns the detach disposer (publication hooks + store removal). When called from
1166
- * a synchronous `session/created` listener, removal and disposal wait until
1167
- * that creation dispatch unwinds.
1168
- * @throws if a session with this id is already in the store.
1169
- */
1170
- enter(session: Session): () => void
1171
-
1172
- /** Emit `session/created` exactly once for an {@link enter}ed session (with
1173
- * the carrier {@link enter} captured). Separate from {@link enter} so the
1174
- * caller can yield the detach disposer first (rollback safety — see
1175
- * {@link enter}). The Session remains read-only throughout synchronous
1176
- * dispatch; successful completion enables appends. A failed announcement
1177
- * leaves it read-only and cannot be retried.
1178
- * @param session - the entered session to announce to listeners.
1179
- * @throws if the session is not live or its announcement already began,
1180
- * including a reentrant call from a creation listener. */
1181
- announce(session: Session): void
1182
-
1183
- /**
1184
- * Dispatch the awaited `session/flush` durability checkpoint for `session`,
1185
- * with the carrier captured at {@link enter}. THE flush entry point: the
1186
- * store owns the carrier, so callers (the checkpoint policy's per-request
1187
- * barrier, goal-round-driver's idle checkpoint, teardown drains, and consumers
1188
- * that flush themselves before reading storage) must come through here
1189
- * rather than dispatch a raw `ctx.parallel('session/flush', …)` — one owner
1190
- * and one spelling.
1191
- * @param session - the session whose buffered events must reach durable storage.
1192
- * @returns whether at least one durability listener participated, after every
1193
- * listener has settled successfully.
1194
- * @throws the first registered listener failure after every listener settles.
1195
- */
1196
- async flush(session: Session): Promise<boolean>
1197
-
1198
- /**
1199
- * Look up a live session.
1200
- * @param id - the session id to look up.
1201
- * @returns the session, or undefined when no live session has that id.
1202
- */
1203
- get(id: SessionId): Session | undefined
1204
-
1205
- /**
1206
- * All live sessions, in creation order.
1207
- * @returns a fresh array; mutating it does not affect the store.
1208
- */
1209
- list(): Session[]
1210
-
1211
- /**
1212
- * Create an independent live session from an exact prefix of a live source.
1213
- * `boundary` is an inclusive source event seq; omitted means the source's
1214
- * current last event. An open tail receives synthetic tool results and
1215
- * step/turn closers with the forked cause. Closed steps and turns remain
1216
- * unchanged, including any failed tool calls already missing results.
1217
- * `inheritedEventCount` counts only copied source events, excluding these closers.
1218
- *
1219
- * @param source - Live source session object or id.
1220
- * @param boundary - Inclusive source event seq to fork through; omitted means
1221
- * the source's current last event, and omitted on an empty source forks an
1222
- * empty child.
1223
- * @param childSessionId - Optional child session id; omitted delegates to
1224
- * `SessionStore`'s id policy.
1225
- * @returns The created live child session.
1226
- */
1227
- fork(source: SessionForkSource, boundary?: SessionSeq, childSessionId?: SessionId): Session
1228
- ```
1229
-
1230
- Types: [CreateSessionOptions](./persistence.md) · [PrepareSessionOptions](./persistence.md) · [SessionId](./core.md)
1231
-
1232
- Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1233
-
1234
- <a id="api-session-events"></a>
1235
-
1236
- ### `api-session/*` events
1237
-
1238
- <a id="api-sessionactivity--emit"></a>
1239
-
1240
- #### `api-session/activity` — emit
1241
-
1242
- One user-authored durable message advanced Session list activity.
1243
-
1244
- ```ts cordis-catalog
1245
- /**
1246
- * One user-authored durable message advanced Session list activity.
1247
- * @mode emit
1248
- * @param sessionId - addressed Session identity.
1249
- * @param updatedAt - durable message time used for list ordering.
1250
- */
1251
- 'api-session/activity'(sessionId: SessionId, updatedAt: number): void
1252
- ```
1253
-
1254
- Types: [SessionId](./core.md)
1255
-
1256
- Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1257
-
1258
- <a id="api-sessionadded--emit"></a>
1259
-
1260
- #### `api-session/added` — emit
1261
-
1262
- A Session became visible or its Agent was created or disposed. Consumers upsert the summary and replace its current running and availability state.
1263
-
1264
- ```ts cordis-catalog
1265
- /**
1266
- * A Session became visible or its Agent was created or disposed.
1267
- * Consumers upsert the summary and replace its current running and availability state.
1268
- * @mode emit
1269
- * @param summary - current list row for the Session.
1270
- */
1271
- 'api-session/added'(summary: SessionSummary): void
1272
- ```
1273
-
1274
- Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1275
-
1276
- <a id="api-sessionerror--emit"></a>
1277
-
1278
- #### `api-session/error` — emit
1279
-
1280
- One Agent failed outside a durable turn position.
1281
-
1282
- ```ts cordis-catalog
1283
- /**
1284
- * One Agent failed outside a durable turn position.
1285
- * @mode emit
1286
- * @param sessionId - Agent and Session identity.
1287
- * @param message - user-safe failure chain.
1288
- */
1289
- 'api-session/error'(sessionId: SessionId, message: string): void
1290
- ```
1291
-
1292
- Types: [SessionId](./core.md)
1293
-
1294
- Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1295
-
1296
- <a id="api-sessionremoved--emit"></a>
1297
-
1298
- #### `api-session/removed` — emit
1299
-
1300
- A Session left the live Host registry.
1301
-
1302
- ```ts cordis-catalog
1303
- /**
1304
- * A Session left the live Host registry.
1305
- * @mode emit
1306
- * @param sessionId - removed Session identity.
1307
- */
1308
- 'api-session/removed'(sessionId: SessionId): void
1309
- ```
1310
-
1311
- Types: [SessionId](./core.md)
1312
-
1313
- Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1314
-
1315
- <a id="api-sessionstatus--emit"></a>
1316
-
1317
- #### `api-session/status` — emit
1318
-
1319
- One Agent changed running state.
1320
-
1321
- ```ts cordis-catalog
1322
- /**
1323
- * One Agent changed running state.
1324
- * @mode emit
1325
- * @param sessionId - Agent and Session identity.
1326
- * @param running - whether the Agent is running.
1327
- */
1328
- 'api-session/status'(sessionId: SessionId, running: boolean): void
1329
- ```
1330
-
1331
- Types: [SessionId](./core.md)
1332
-
1333
- Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1334
-
1335
- <a id="session-events"></a>
1336
-
1337
- ### `session/*` events
1338
-
1339
- <a id="sessioncreated--emit"></a>
1340
-
1341
- #### `session/created` — emit
1342
-
1343
- Read-only creation announcement after store entry. New events reject until every synchronous listener has returned successfully. A synchronous throw vetoes creation and rolls back with a paired disposal; detach requested during dispatch is deferred. A returned-promise rejection is logged but cannot retroactively veto this synchronous boundary. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only sessions entered through that agent's context.
1344
-
1345
- ```ts cordis-catalog
1346
- /**
1347
- * Read-only creation announcement after store entry.
1348
- * New events reject until every synchronous listener has returned successfully.
1349
- * A synchronous throw vetoes creation and rolls back with a paired disposal;
1350
- * detach requested during dispatch is deferred.
1351
- * A returned-promise rejection is logged but cannot retroactively veto this
1352
- * synchronous boundary.
1353
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
1354
- * receive only sessions entered through that agent's context.
1355
- * @param session - the session just entered and announced.
1356
- * @mode emit
1357
- */
1358
- 'session/created'(this: Scoped<Session>, session: Session): void
1359
- ```
1360
-
1361
- Types: [Scoped](./scope.md)
1362
-
1363
- Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1364
-
1365
- <a id="sessiondisposed--emit"></a>
1366
-
1367
- #### `session/disposed` — emit
1368
-
1369
- Emitted once when an announced session leaves the store, including publication rollback, but never for an entry whose creation announcement did not begin. Listener failures are logged and contained. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope.
1370
-
1371
- ```ts cordis-catalog
1372
- /**
1373
- * Emitted once when an announced session leaves the store, including
1374
- * publication rollback, but never for an entry whose creation announcement
1375
- * did not begin. Listener failures are logged and contained.
1376
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope.
1377
- * @param session - the session that is no longer live in the store.
1378
- * @mode emit
1379
- */
1380
- 'session/disposed'(this: Scoped<Session>, session: Session): void
1381
- ```
1382
-
1383
- Types: [Scoped](./scope.md)
1384
-
1385
- Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1386
-
1387
- <a id="sessionevent--emit"></a>
1388
-
1389
- #### `session/event` — emit
1390
-
1391
- Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context.
1392
-
1393
- ```ts cordis-catalog
1394
- /**
1395
- * Post-commit, fire-and-forget append feed. The listener snapshot resolves
1396
- * before the log push, but callbacks run after it; observer failures are
1397
- * logged and contained without making the committed append fail.
1398
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
1399
- * receive only events from sessions entered through that agent's context.
1400
- * @param session - the session whose log grew.
1401
- * @param event - the appended event, exactly as recorded.
1402
- * @mode emit
1403
- */
1404
- 'session/event'(this: Scoped<Session>, session: Session, event: SessionEvent): void
1405
- ```
1406
-
1407
- Types: [Scoped](./scope.md)
1408
-
1409
- Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1410
-
1411
- <a id="sessionflush--parallel"></a>
1412
-
1413
- #### `session/flush` — parallel
1414
-
1415
- Awaited parallel durability checkpoint: every listener runs and the caller awaits all of them, with no waterfall veto. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
1416
-
1417
- ```ts cordis-catalog
1418
- /**
1419
- * Awaited parallel durability checkpoint: every listener runs and the
1420
- * caller awaits all of them, with no waterfall veto. Scope-filtered dispatch
1421
- * (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
1422
- * @param session - the session whose buffered events must reach durable storage.
1423
- * @mode parallel
1424
- */
1425
- 'session/flush'(this: Scoped<Session>, session: Session): Promise<void> | void
1426
- ```
1427
-
1428
- Types: [Scoped](./scope.md)
1429
-
1430
- Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1431
- <!-- END GENERATED cordis-surface -->
1
+ ---
2
+ editSource: "docs/subsystems/session.md"
3
+ rawMarkdownPath: "en/reference/subsystems/session.md"
4
+ outline: [2,3]
5
+ ---
6
+
7
+ # Sessions
8
+
9
+ The in-memory, event-sourced model of [dsh-session](https://github.com/deepseek-ai/deepseek-harness/tree/master/packages/core/session). A `Session` is an **append-only log** of typed `SessionEvent`s — the single source of truth for an agent's whole interaction history. The LLM message history is *derived* from the log, never stored separately; replay is re-derivation from the same events. How the log is made **durable** (the persistence seam, backends, crash recovery) is the sibling concern on [persistence.md](./persistence.md).
10
+
11
+ Source: [`packages/core/session/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/types.ts)
12
+
13
+ ## `SessionEventMap` — the event vocabulary
14
+
15
+ The append-only event types. Merge-extensible: a plugin declares extra event types via declaration merging — e.g. the [compaction seam](./compaction.md) adds `compaction/start` / `compaction/summary` / `compaction/end`, and `@deepseek-ai/dsh-hook-protocol` adds log-only `hook/invoked` / `hook/result` records for a hook bridge. Like `compaction/*`, these are NOT `SurfaceEventType`s (no `surfaceOp`). The generated [persistence log event catalog](../persistence-catalog.md) enumerates every member — core and merged — with its payload, surface badge, and declaration site.
16
+
17
+ ```ts type-equiv
18
+ /** A user-role specialization of the shared message representation. */
19
+ interface UserMessage extends MessageBase {
20
+ readonly role: 'user'
21
+ }
22
+ ```
23
+
24
+ ```ts type-equiv
25
+ /**
26
+ * The merge-extensible, append-only source of truth for an agent interaction.
27
+ * Message history is derived from this log. Every event is lossless JSON and
28
+ * sequence numbers stay contiguous. Assistant attempt events embed their exact
29
+ * compact raw streams so persistence stores one durable settlement per attempt.
30
+ */
31
+ interface SessionEventMap {
32
+ /**
33
+ * Opens turn `turn` before the loop claims queued input or runs pre-step.
34
+ * Rejection, empty input, cancellation, or failure may close it with no
35
+ * step; otherwise the following identified `user/message` event or batch
36
+ * records the messages entering the step.
37
+ */
38
+ 'turn/start': { turn: number }
39
+ /**
40
+ * Closes turn `turn` with the {@link TurnEndReason} that ended it. A turn
41
+ * with no entered step has no `step/start` or `step/end`. The loop does not await a
42
+ * flush at turn boundaries: `dsh-session-checkpoint-policy` owns the
43
+ * per-request durability checkpoint, and consumers that read storage after
44
+ * `whenIdle()` flush themselves. Success commits the turn; rejection is
45
+ * reported live and does not prevent later work.
46
+ */
47
+ 'turn/end': { turn: number; reason: TurnEndReason }
48
+ /** Opens step `step` of turn `turn` — one model call plus the tool executions it requested. */
49
+ 'step/start': { turn: number; step: number }
50
+ /** Closes step `step` of turn `turn`. */
51
+ 'step/end': { turn: number; step: number }
52
+ /**
53
+ * A user-role message on the model-visible surface: a direct human prompt
54
+ * (the queued message claimed for this turn), a synthetic `agent.inject()`
55
+ * context (file-change notices, subdir AGENTS.md, skill content, cron
56
+ * notifications, …), or an entered goal continuation round. All three
57
+ * project their `content` verbatim; `source` tells them apart.
58
+ */
59
+ 'user/message': UserMessage
60
+ /** An incremental agent session change admitted at the named turn and step. */
61
+ 'developer/message': {
62
+ turn: number
63
+ step: number
64
+ message: DeveloperMessage
65
+ /** Earlier request/header defining every tool addition; required exactly when additions are present. */
66
+ headerSeq?: SessionSeq
67
+ }
68
+ /**
69
+ * The rendered system prompt on the model-visible surface. The loop appends
70
+ * the first one as surface node 0 before the step's first `user/message`.
71
+ * A prepared in-history route can append nonempty changes in a continuing
72
+ * series. An incapable route, or a new series whose effective text differs,
73
+ * normalizes text to the first system node; a series start whose latest
74
+ * surviving node already holds the rendering leaves it in place.
75
+ * Normalization empties nonempty later nodes, then rewrites the head if
76
+ * needed, through logged per-node replacements. An empty rendering always
77
+ * clears all active system nodes, leaving no older instructions model-visible.
78
+ * Empty later nodes are dormant and project to no message; an empty head with
79
+ * no active later node records "no system prompt". Restored nonempty text follows
80
+ * the same route and series rule; empty nodes never restore older text.
81
+ */
82
+ 'system/message': { turn: number; step: number; message: SystemMessage }
83
+ /**
84
+ * Assembled assistant message for one step (derived history uses this).
85
+ * Carries the step's `usage` when the adapter reported token accounting, so
86
+ * the model output and its accounting travel together (there is no separate
87
+ * usage record). `usage` is absent when the adapter reported none. A turn
88
+ * cancelled mid-stream finalizes its delivered text/reasoning prefix as this
89
+ * event with `interrupted: true`; undispatched tool calls are absent. The
90
+ * marker distinguishes that prefix without re-deriving interruption from turn
91
+ * boundaries. An aborted turn with no such event streamed no visible content.
92
+ */
93
+ 'assistant/message': {
94
+ turn: number
95
+ step: number
96
+ message: AssistantMessage
97
+ /** Exact timed model stream, compacted without joining delta boundaries. */
98
+ stream: AssistantStreamRecord[]
99
+ usage?: TokenUsage
100
+ interrupted?: true
101
+ }
102
+ /**
103
+ * One model attempt that committed no surface message. The embedded stream
104
+ * preserves a failed, retried, cancelled, or stream-error attempt that
105
+ * reached settlement without fabricating model-visible history.
106
+ */
107
+ 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] }
108
+ /**
109
+ * The model requested one tool invocation: `name` with the raw `arguments`
110
+ * JSON string exactly as the model produced it (unparsed). `callId` pairs the
111
+ * call with its `tool/result`.
112
+ */
113
+ 'tool/call': { turn: number; step: number; callId: ToolCallId; name: string; arguments: string }
114
+ /**
115
+ * A completed tool call's model-facing result, optional internal failure
116
+ * identity and user-facing reason, and optional tool-private `meta`
117
+ * presentation payload. The reason remains outside the model-facing message.
118
+ * `meta` is
119
+ * opaque to the core (the producing tool owns its shape and reads it back in
120
+ * `presentResult`) but MUST be JSON-serializable: `Session.append`
121
+ * runtime-validates all event data with `isJsonValue`, so a non-serializable
122
+ * `meta` is rejected at the source, and the durable log reproduces the
123
+ * identical card on replay. Absent
124
+ * unless the tool attaches one (e.g. `dsh-tool-fs` carries its result-time
125
+ * contextual diff here).
126
+ */
127
+ 'tool/result': {
128
+ turn: number
129
+ step: number
130
+ message: ToolResultMessage
131
+ /**
132
+ * Optional failure identity and raw user-facing reason, outside model content;
133
+ * allowed only when the message has `isError: true`.
134
+ */
135
+ error?: { name: string; code: string; reason?: string }
136
+ meta?: JsonValue
137
+ }
138
+ /**
139
+ * Full header for the next request, appended inside its step before dispatch.
140
+ * It is log-only; the latest snapshot reconstructs the request header.
141
+ */
142
+ 'request/header': {
143
+ header: EpochHeader
144
+ reason: RequestHeaderReason
145
+ /** This request begins a distinct model-message series, independently of the header reason. */
146
+ startsSeries?: true
147
+ }
148
+ /**
149
+ * Route metadata for the next request, logged only when the route, capacity,
150
+ * or system prompt update mode changes. It does not participate in request
151
+ * reconstruction or header equality. Prompt admission uses the bound prepared
152
+ * call's capability, not this snapshot from an earlier request.
153
+ */
154
+ 'request/context': RequestContext
155
+ /**
156
+ * Separates inherited or restored history from later lifecycle-owned work.
157
+ * This log-only marker need not be at {@link Session.firstLiveSeq}: a fork
158
+ * seed can already contain its tagged marker and child-owned synthetic
159
+ * closers before construction.
160
+ *
161
+ * A fresh fork child owns one `{ inherited: true }` marker at its exact
162
+ * inherited-prefix cut, even when that prefix ends in an ancestor marker.
163
+ * `buildForkSeed` appends that marker before any synthetic closers; the
164
+ * `Session` constructor supplies it when given only the inherited prefix.
165
+ * The last tagged marker is the current Session's cut; untagged markers
166
+ * keep ordinary restore and replay lifecycle boundaries.
167
+ *
168
+ * Only the `Session` constructor and `buildForkSeed` may create this marker.
169
+ * Session append does not reject other writers, so a plugin appending one
170
+ * would silently classify every live bracket before it as seed history.
171
+ *
172
+ * An owner of a standalone open/close bracket (`compaction/start` …
173
+ * `compaction/end`) reads it because seed history and live work are otherwise
174
+ * byte-identical: an unmatched opening marker before this event belongs to
175
+ * an ended lifecycle, whatever ended it. NOT a liveness signal about other
176
+ * writers — a concurrently live session holds its own boundary elsewhere,
177
+ * so tolerating concurrent writers needs a signal beyond the log.
178
+ */
179
+ 'session/end-seed': { inherited?: true }
180
+ }
181
+ ```
182
+
183
+ `UserMessage` is the identified, frozen user-role value shared by ordinary prompts, injected context, steering, and live inbox events. Event wrappers add only event-local position or outcome facts; the loop adds only driver-owned routing state while an item remains pending.
184
+
185
+ <a id="the-request-header-event-requestheader"></a>
186
+
187
+ ### The request header event: `request/header`
188
+
189
+ The request envelope — the `EpochHeader` (call config + markers for adapter-supplied defaults + assembled tool schemas) — is logged session state, so every conversation request is a pure function of the log (the reconstructability Agent Note). The rendered system prompt is not part of the header: it is derived history, the `system/message` event at surface node 0 and any later in-history system node ([decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md)), so a prompt change replaces or appends a system node and leaves the header unchanged. A full `request/header` snapshot with reason `'initial'` or `'resume'` records each loop-instance boundary; a changed request appends a snapshot with reason `'change'`; and an unchanged envelope beginning an explicitly declared message series or following a surface replacement appends a snapshot with reason `'series'`. An `'initial'`, `'resume'`, or `'change'` snapshot carries `startsSeries: true` when that request also begins a series; reason `'series'` already records that fact. Ordinary append-only later Turns, further Steps, and retries in the same model-message series inherit the latest snapshot. `foldRequestHeader(events)` reconstructs the header by selecting the latest snapshot. The event is not a `SurfaceEventType`: it produces no LLM message.
190
+
191
+ ```ts type-equiv
192
+ /**
193
+ * Logged request state outside derived history: call config and tools. The
194
+ * system prompt is derived history — surface node 0, a `system/message` event.
195
+ * The latest full `request/header` snapshot reconstructs the header; canonical
196
+ * empty optional fields are absent.
197
+ */
198
+ interface EpochHeader {
199
+ /** The conversation's call configuration (provider, model, reasoning effort, and sampling scalars). */
200
+ config: LlmCallConfig
201
+ /** Effective config fields materialized from the exact adapter rather than proposed by a caller. */
202
+ adapterDefaults?: LlmCallConfigAdapterDefaults
203
+ /** Assembled tool schemas; absent for a tool-less request. */
204
+ tools?: ToolSchema[]
205
+ /** Retired request text; system prompts belong to system/message events.
206
+ * @persistenceReserved
207
+ */
208
+ system?: never
209
+ }
210
+ ```
211
+
212
+ Current event acceptance requires canonical `request/header.header`: any `system` field is forbidden, and `tools: []` and `adapterDefaults: {}` must be omitted. Whitespace-only system-message content, `config.stop: []`, and nested extensions remain unchanged. Seed, append, and current persistence reads reject noncanonical headers rather than silently normalizing them; [the V3 envelope decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-09-06-v3-canonical-session-envelopes.md) owns historical conversion. Legacy v0 logs containing `request/header-delta` or its full-snapshot `fallback` reason are rejected rather than replayed incompletely.
213
+
214
+ ### The route capacity event: `request/context`
215
+
216
+ The context metadata of the route a request resolved to is separate logged state, appended beside `request/header` inside the same step and only when the provider, model, capacity, or `systemPromptUpdate` mode differs from the previous record. It stays outside `EpochHeader` because that type is the reconstruction contract compared field-wise by `headerEquals`: capacity and the update mode describe a route, not a request input, so folding them in would let a route change register as a request-envelope `change` and would pull adapter metadata into the loop's request reconstruction. Like `request/header`, it is not a `SurfaceEventType` and produces no LLM message. `session.requestContext()` folds the latest record incrementally; the agent loop reads that record's `systemPromptUpdate` when it decides whether a changed system prompt replaces the latest system node or is appended after the cached history ([decision rule](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent-loop/README.md#understand-the-implementation)). A route whose adapter advertises no capacity is recorded with `contextWindow` absent, so the new record clears an older route's capacity; a route without a declared update mode likewise clears an older route's `systemPromptUpdate`.
217
+
218
+ ```ts type-equiv
219
+ /** Registration-bound metadata for one resolved model route. */
220
+ interface RequestContext {
221
+ /** Registered provider route the metadata belongs to. */
222
+ provider: string
223
+ /** Provider-owned model id the metadata belongs to. */
224
+ model: string
225
+ /** Maximum combined request and response context in tokens, when advertised. */
226
+ contextWindow?: number
227
+ /** `'in-history'` when the route reads the latest `system` message at any position as the effective system prompt. */
228
+ systemPromptUpdate?: SystemPromptUpdate
229
+ }
230
+ ```
231
+
232
+ ## `SessionEvent<T>` — one log entry
233
+
234
+ A proper discriminated union over `type` (not independent `type`/`data` unions), so `switch (event.type)` narrows `event.data` without casts. `seq` is the monotonic position in the log (`seq = log.length`); `time` is epoch ms.
235
+
236
+ ```ts type-equiv
237
+ /** Sequence number of one existing event in a Session log. */
238
+ type SessionSeq = BrandedNumber<'SessionSeq'>
239
+ ```
240
+
241
+ ```ts type-equiv
242
+ /** A Session log gap, prefix length, or read offset, which may equal the event count. */
243
+ type SessionLogOffset = BrandedNumber<'SessionLogOffset'>
244
+ ```
245
+
246
+ ```ts type-equiv
247
+ /** Inclusive Session event watermark, or `-1` before any event exists. */
248
+ type SessionSeqCursor = SessionSeq | -1
249
+ ```
250
+
251
+ ```ts type-equiv
252
+ /** One existing Session event position, or explicit absence. */
253
+ type OptionalSessionSeq = SessionSeq | null
254
+ ```
255
+
256
+ `SessionSeq(value)` and `SessionLogOffset(value)` admit only non-negative safe integers and reject negative zero. They add compile-time brands without changing the serialized number; arithmetic returns an ordinary `number` that callers must admit again through the constructor for its intended role.
257
+
258
+ ```ts type-equiv
259
+ /**
260
+ * One immutable entry in the session log.
261
+ *
262
+ * A proper discriminated union over `type` (not independent `type`/`data`
263
+ * unions), so `switch (event.type)` narrows `event.data` without casts.
264
+ *
265
+ * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional:
266
+ * they only exist on {@link SurfaceEventType} variants (`system/message`, `user/message`,
267
+ * `assistant/message`, `tool/result`).
268
+ * Non-surface events (boundary markers, attempts, errors) never carry
269
+ * surface metadata — the compiler enforces this at `Session.append()`
270
+ * call sites.
271
+ */
272
+ type SessionEvent<T extends SessionEventType = SessionEventType> = {
273
+ [K in SessionEventType]: {
274
+ type: K
275
+ /** Monotonic sequence number within the session. */
276
+ seq: SessionSeq
277
+ /** Unix epoch milliseconds. */
278
+ time: number
279
+ data: SessionEventMap[K]
280
+ /**
281
+ * Marks an event a reader may safely skip when it does not recognize
282
+ * `type`. Absent means required: a reader meeting an unrecognized type
283
+ * without this marker MUST refuse to reconstruct the session instead of
284
+ * silently dropping the event, because an unrecognized required event may
285
+ * change how the rest of the log is interpreted. A writer sets `true` only
286
+ * on purely informational records whose loss cannot affect reconstruction;
287
+ * defaulting to required means a forgotten marker over-refuses (an
288
+ * inconvenience) rather than silently resuming a gutted session.
289
+ */
290
+ ignorable?: true
291
+ } & (K extends SurfaceEventType ? SurfaceIntent<K> : {
292
+ surfaceOp?: never
293
+ sourceEventSeqs?: never
294
+ })
295
+ }[T]
296
+ ```
297
+
298
+ `SessionEventType = keyof SessionEventMap`. Because `SessionEventMap` is merge-extensible, switches over `SessionEvent` must NOT use `assertNever` — a plugin-added variant is a valid unknown value; handle the known cases and fall through `default`.
299
+
300
+ Every surface event requires `surfaceOp`; known log-only events forbid both surface metadata fields. Native unknown or obsolete ignorable envelopes remain opaque. `assistant/message` embeds its provider stream and forbids `sourceEventSeqs`. System, user, and tool surface events may cite a complete non-empty set of unique earlier events when source attribution or replacement coverage requires it. A `tool/result` may carry `data.error` only when its message has `isError: true`; failure identity remains optional for failed results.
301
+
302
+ ## Surface types
303
+
304
+ The message-producing types (`SurfaceEventType` — `system/message`, `developer/message`, `user/message`, `assistant/message`, `tool/result`) carry surface metadata declaring how they join the ordered derived surface. `system/message` holds the rendered system prompt: the loop appends the first one as surface node 0 and, when the prompt changes, replaces exactly the latest system node or appends a new one on an in-history route; the surface fold rejects any other replacement covering a `system/message` at node 0, while a later system node is ordinary history that a compaction replacement may shadow. See the [session surface Agent Note](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-06-18-session-surface.md).
305
+
306
+ ### `SurfaceEventType` — the message-producing subset of event types
307
+
308
+ ```ts type-equiv
309
+ /**
310
+ * The subset of {@link SessionEventType} values whose events produce LLM
311
+ * messages and are eligible to appear on the ordered surface. Only these
312
+ * event types may carry {@link SurfaceOp}; system, user, and tool events may also cite
313
+ * earlier sources through {@link SessionEvent.sourceEventSeqs}.
314
+ */
315
+ type SurfaceEventType =
316
+ | 'system/message'
317
+ | 'developer/message'
318
+ | 'user/message'
319
+ | 'assistant/message'
320
+ | 'tool/result'
321
+ ```
322
+
323
+ ### `SurfaceOp` — how an event entered the surface
324
+
325
+ ```ts type-equiv
326
+ /**
327
+ * How a session event entered the ordered surface. Only valid on
328
+ * {@link SurfaceEventType} events.
329
+ *
330
+ * - `'append'`: added to the tail — normal path for user/assistant/tool
331
+ * messages.
332
+ * - `{ op: 'replace', startSeq, endSeq }`: replaces surface nodes from `startSeq`
333
+ * (inclusive) through `endSeq` (inclusive) with this node. Both must exist as
334
+ * surface nodes in the current surface. `startSeq === endSeq` replaces a single
335
+ * node. The node's {@link SessionEvent.sourceEventSeqs} must include every
336
+ * shadowed surface node. Used by compaction; any surface-replacing producer
337
+ * may use it.
338
+ */
339
+ type SurfaceOp =
340
+ | 'append'
341
+ | { op: 'replace'; startSeq: SessionSeq; endSeq: SessionSeq }
342
+ ```
343
+
344
+ `'append'` is the normal tail-append path. `replace` contains exactly `op`, `startSeq`, and `endSeq`, with no aliases or extra keys. It shadows the inclusive span between those current surface event sequences and inserts the new event in their place; equal endpoints replace one entry. Endpoints must precede the replacing event, but their relative order is surface order, not numeric sequence order.
345
+
346
+ ### `SurfaceIntent` — the parameter to `session.append()`
347
+
348
+ ```ts type-equiv
349
+ /**
350
+ * Surface placement and cited source-event seqs for {@link Session.append}. Required on
351
+ * message-producing events and forbidden on log-only events.
352
+ */
353
+ type SurfaceIntent<T extends SurfaceEventType = SurfaceEventType> = {
354
+ surfaceOp: SurfaceOp
355
+ } & (T extends 'assistant/message' ? {
356
+ /** Assistant messages embed their provider stream instead of citing source events. */
357
+ sourceEventSeqs?: never
358
+ } : {
359
+ /** Complete non-empty set of known earlier source-event seqs. */
360
+ sourceEventSeqs?: SessionSeq[]
361
+ })
362
+ ```
363
+
364
+ Required for `SurfaceEventType` events — every message-producing event must declare how it joins the surface, the sole source of derived model history. A human-facing transcript is the other projection and reads the log's append-origin events instead, because the surface deliberately shadows the ranges a replacement summarizes (`isAppendSurfaceEvent` in [dsh-session](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/README.md)). Non-surface types reject it at compile time.
365
+
366
+ `assistant/message` cannot carry `sourceEventSeqs`; its `stream` owns exact provider evidence. Other surface events omit the field when they cite no earlier event and use a complete non-empty list when they do.
367
+
368
+ <a id="plugin-owned-message-projections"></a>
369
+ ### Plugin-owned message projections
370
+
371
+ Content-changing plugins mark their event declaration with `@messageProjection` and register a pure definition through `ctx.sessions.registerMessageProjection()`. Session validates the complete decision through that definition before commit, applies its immutable message updates, and advances `contentGeneration`. It rejects missing interpreters, including on restore and detached folding; unloading a used definition blocks cached reads. Detached readers pass explicit definitions to `foldSurface(events, projections)` and apply `projectedMessages` through `deriveEventMessage()`. The installed format catalog assembles first-party definitions for offline readers. The [image-offload plugin](./compaction.md#image-offload) owns its image-specific event and interpretation.
372
+
373
+ ```ts type-equiv
374
+ /** Readonly history immediately before a message-projection event. */
375
+ interface SessionMessageProjectionContext {
376
+ /** Current message-producing event sequences in model-visible order. */
377
+ nodes: readonly SessionSeq[]
378
+ /** Contiguous event window; entries at or beyond the candidate seq are not committed inputs. */
379
+ events: readonly SessionEvent[]
380
+ /** Absolute sequence of the window's first event. */
381
+ baseSeq: SessionLogOffset
382
+ /** Previously projected messages keyed by their original event sequences. */
383
+ messages: ReadonlyMap<SessionSeq, Message>
384
+ }
385
+ ```
386
+
387
+ ```ts type-equiv
388
+ /** Pure interpretation of one plugin-owned event that changes existing message content. */
389
+ interface SessionMessageProjection<T extends SessionEventType = SessionEventType> {
390
+ /** Event interpreted by this definition; declare it with `@messageProjection` in SessionEventMap. */
391
+ type: T
392
+ /**
393
+ * Validate the complete durable decision before returning any updates. Preserve
394
+ * message identities and publish immutable copies without mutating the input.
395
+ * @param event - candidate event, not yet applied to the supplied history.
396
+ * @param context - history preceding this decision.
397
+ * @returns changed current messages keyed by their original sequences.
398
+ * @throws when the durable decision cannot be applied to this history.
399
+ */
400
+ project(event: SessionEvent<T>, context: SessionMessageProjectionContext): ReadonlyMap<SessionSeq, Message>
401
+ }
402
+ ```
403
+
404
+ ### `SessionSurface` — the live readonly surface projection
405
+
406
+ `Session.surface` returns the session's stable `SessionSurface` view. The same incremental manager validates append candidates before commit and advances this projection from committed events; callers can observe membership and replacement generation but cannot invoke validation.
407
+
408
+ `SurfaceManager(log, baseSeq?, projections?)` can instead fold a contiguous loaded window whose first event has the absolute sequence `baseSeq`. Every event remains contiguous in that absolute sequence space, and a replacement that crosses the window head fails because its declared range is absent.
409
+
410
+ ```ts type-equiv
411
+ /** Readonly live projection of the message-producing session events. */
412
+ interface SessionSurface {
413
+ /** Current surface event sequences in model-visible order. */
414
+ readonly nodes: readonly SessionSeq[]
415
+ /** Monotonic count of committed positional replacements. */
416
+ readonly replaceGeneration: number
417
+ /** Monotonic count of committed replacements and plugin-owned message changes. */
418
+ readonly contentGeneration: number
419
+ }
420
+ ```
421
+
422
+ ### `SurfaceFoldReplacement` and `SurfaceFoldResult` — a complete surface replay
423
+
424
+ `foldSurface(events, projections)` returns detached current event sequences together with the actual sequences shadowed by each declared replacement range. The live manager uses the same transitions without retaining replacement history. Its `replaceGeneration` increments for each committed replacement so incremental consumers can distinguish pure tail growth from a rewrite.
425
+
426
+ ```ts type-equiv
427
+ /** One replacement operation observed while folding a session surface. */
428
+ interface SurfaceFoldReplacement {
429
+ /** Seq of the event that replaced the prior surface range. */
430
+ seq: SessionSeq
431
+ /** Declared inclusive start seq of the replaced surface range. */
432
+ start: SessionSeq
433
+ /** Declared inclusive end seq of the replaced surface range. */
434
+ end: SessionSeq
435
+ /** Actual surface entries removed by the operation, in surface order. */
436
+ shadowedSeqs: SessionSeq[]
437
+ }
438
+ ```
439
+
440
+ ```ts type-equiv
441
+ /** Complete result of replaying the surface operations in a session log. */
442
+ interface SurfaceFoldResult {
443
+ /** Current surface event sequences in model-visible order. */
444
+ nodes: SessionSeq[]
445
+ /** Replacement operations in event order. */
446
+ replacements: SurfaceFoldReplacement[]
447
+ /** Immutable projected messages, keyed by their original event sequences. */
448
+ projectedMessages: ReadonlyMap<SessionSeq, Message>
449
+ }
450
+ ```
451
+
452
+ ## `Session` public API
453
+
454
+ ### `SessionEventInput` — one proposed event
455
+
456
+ ```ts type-equiv
457
+ /** One positional event call proposed for append, without assigned sequence or time. */
458
+ type SessionEventInput = {
459
+ [K in SessionEventType]: readonly [type: K, data: SessionEventMap[K], ...opts: K extends SurfaceEventType ? [opts: SurfaceIntent<K>] : []]
460
+ }[SessionEventType]
461
+ ```
462
+
463
+ Each array member keeps its event type paired with its payload and requires surface intent only for message-producing events.
464
+
465
+ The body-stripped declaration keeps the plain class's detached factory, state accessors, append method, and history projections synchronized with source. Store operations remain in the generated [`ctx.sessions` section](#ctxsessions--sessionstore).
466
+
467
+ ```ts public-api
468
+ /**
469
+ * An event-sourced session: an append-only log of {@link SessionEvent}s.
470
+ *
471
+ * Plain class (not a Service) — create live instances via
472
+ * `ctx.sessions.create()` and detached instances via {@link create}.
473
+ * Seeding with an existing event log replays/forks a session.
474
+ * @typert object
475
+ */
476
+ declare class Session {
477
+ /** The ordered surface over this session's event log. */
478
+ get surface(): SessionSurface;
479
+ /**
480
+ * Detached, deep-frozen creation metadata (format version, cwd, lineage,
481
+ * and whether fork history exists). Supplied by the store via `ctx.sessions.create()`. When a
482
+ * `Session` is created without a store-owned header, a minimal header is
483
+ * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
484
+ * `session.header` is always present. Kept out of the event log — it is a
485
+ * storage concern, not replayable conversation state.
486
+ */
487
+ readonly header: SessionHeader;
488
+ /** Number of leading events inherited from this Session's fork parent. */
489
+ readonly inheritedEventCount: SessionLogOffset;
490
+ /** The session identity, derived from its durable header's single copy. */
491
+ get id(): SessionId;
492
+ /**
493
+ * The constructor seed length (0 without one), before any marker appended
494
+ * during construction. Seed events never publish on `session/event`. A
495
+ * marker appended before the store attaches occupies this seq without
496
+ * publishing either; otherwise this seq is available for the next append.
497
+ *
498
+ * This in-process offset is not persisted. A fork seed can already contain
499
+ * the child's inherited marker and synthetic closers, so its child-owned
500
+ * history starts at {@link inheritedEventCount}, before this offset. A
501
+ * resumed Session's seed contains its full stored log, while its inherited
502
+ * count keeps the durable fork cut. Consumers needing complete canonical
503
+ * history start at seq 0.
504
+ */
505
+ readonly firstLiveSeq: SessionLogOffset;
506
+ /**
507
+ * First event produced for this object lifecycle. A new fork includes its
508
+ * child-owned seed marker and closers; a restored Session starts after its
509
+ * complete stored prefix. This in-process capture offset is not persisted.
510
+ */
511
+ readonly firstLifecycleSeq: SessionLogOffset;
512
+
513
+ /**
514
+ * Create a detached session by validating and snapshotting borrowed seed
515
+ * events and storage metadata.
516
+ * @param id - session identity.
517
+ * @param seed - optional borrowed replay or fork events.
518
+ * @param header - optional borrowed storage metadata.
519
+ * @param inheritedEventCount - exact fork-inherited prefix length for a seeded header.
520
+ * @param projections - pure interpreters for plugin-owned message changes.
521
+ * @returns a detached session.
522
+ * @throws when a seed event requires a missing message interpreter or fails validation.
523
+ */
524
+ static create(
525
+ id: SessionId,
526
+ seed?: readonly SessionEvent[],
527
+ header?: SessionHeader,
528
+ inheritedEventCount?: SessionLogOffset,
529
+ projections?: readonly SessionMessageProjection[],
530
+ ): Session;
531
+ /**
532
+ * Restore a detached session by adopting an independently owned or deeply frozen seed.
533
+ * Runtime-required event fields, event envelopes, sequence continuity, surface
534
+ * transitions, and header fields are validated without copying or freezing events.
535
+ * Embedded Assistant streams remain opaque until a stream consumer or storage
536
+ * verifier reads them.
537
+ * @param id - restored session identity.
538
+ * @param seed - independently owned or deeply frozen events.
539
+ * @param header - independently owned storage metadata.
540
+ * @param inheritedEventCount - exact fork-inherited prefix length decoded from storage.
541
+ * @param eventState - aliasing state carried from the operation that produced the seed.
542
+ * @param projections - pure interpreters for plugin-owned message changes.
543
+ * @returns a restored detached session.
544
+ * @throws when a seed event requires a missing message interpreter or fails validation.
545
+ */
546
+ static fromRestore(
547
+ id: SessionId,
548
+ seed: readonly SessionEvent[],
549
+ header: SessionHeader,
550
+ inheritedEventCount: SessionLogOffset,
551
+ eventState: SessionSeedEventState,
552
+ projections?: readonly SessionMessageProjection[],
553
+ ): Session;
554
+ /**
555
+ * Return the immutable event stored at one exact sequence number.
556
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
557
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
558
+ * @param seq - event sequence number.
559
+ * @returns the accepted event, or undefined when the log does not contain it.
560
+ */
561
+ eventAt(seq: SessionSeq): SessionEvent | undefined;
562
+ /**
563
+ * Materialize an immutable snapshot of a half-open event sequence range.
564
+ * A full current snapshot is reused until the next append; every previously
565
+ * returned snapshot remains stable after later appends.
566
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
567
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
568
+ * @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
569
+ * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
570
+ * @returns a frozen array of the selected deeply frozen events.
571
+ */
572
+ snapshotEvents(
573
+ fromSeq: SessionLogOffset = SessionLogOffset(0),
574
+ toSeqExclusive: SessionLogOffset = this.seq,
575
+ ): readonly SessionEvent[];
576
+ /**
577
+ * Return this Session's events after its fork-inherited prefix.
578
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
579
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
580
+ * @returns a fresh array containing child-owned events in log order.
581
+ */
582
+ ownEvents(): readonly SessionEvent[];
583
+ /**
584
+ * Whether one existing event position is outside the fork-inherited prefix.
585
+ * @param seq - event position in this Session.
586
+ * @returns true when the event belongs to this Session rather than its parent.
587
+ */
588
+ isOwnSeq(seq: SessionSeq): boolean;
589
+ /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
590
+ get seq(): SessionLogOffset;
591
+ /** Current event while synchronously notifying a batch's observers. */
592
+ get currentBatchPublication(): SessionEvent | undefined;
593
+ /**
594
+ * Append consecutive events together after validating every candidate and dispatch.
595
+ * Observers read the complete committed log and final message surface.
596
+ * Listener registration changes during publication take effect on the next append.
597
+ * Persistence listeners retain their own durability rules.
598
+ * @param inputs - event payloads and surface intents in commit order. An empty array records no events.
599
+ * @returns immutable committed events in the same order.
600
+ * @throws if the Session cannot accept writes, including an empty append, or any candidate or synchronous dispatch validation fails.
601
+ */
602
+ append(inputs: readonly SessionEventInput[]): readonly SessionEvent[];
603
+ /**
604
+ * Append one typed event to the log and synchronously notify observers via
605
+ * the store-owned, module-private publication hooks. The hot path never blocks
606
+ * on I/O — persistence plugins buffer asynchronously. Once the event enters
607
+ * the log, the append is committed: observer failures are logged and
608
+ * contained per listener, so they do not change the return value or prevent
609
+ * later listeners from observing the same accepted event.
610
+ * Independent Sessions append without notifying store observers. Once a store
611
+ * prepares or enters the instance, writes require a completed creation
612
+ * announcement and remain disabled after removal.
613
+ *
614
+ * @param type - The event type (key of {@link SessionEventMap}).
615
+ * @param data - The event payload; must be JSON-serializable.
616
+ * @param opts - Surface metadata: `surfaceOp` controls how the event enters
617
+ * the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier
618
+ * events this one derives from. REQUIRED for
619
+ * {@link SurfaceEventType} events (every message-producing event must
620
+ * declare how it joins the surface, the sole source of derived model
621
+ * history) and
622
+ * rejected by the compiler for non-surface types like `turn/start` or
623
+ * `assistant/attempt`. Assistant messages embed their exact provider
624
+ * stream and cannot cite top-level source events.
625
+ * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
626
+ * `data` that entered the log, so reading `event.data` back sees the logged
627
+ * value, never the caller's still-mutable input.
628
+ * @throws if a store-owned Session is unentered or its creation announcement
629
+ * has not completed, or if `data` or surface
630
+ * metadata is not losslessly JSON-serializable
631
+ * (BigInt, function, symbol, undefined, negative zero, non-finite number,
632
+ * circular reference, sparse array, or an exotic object such as
633
+ * Map/Set/Date/class instance), or when the candidate violates the
634
+ * request-header empty-field or tool-error consistency rules, or the
635
+ * canonical surface contract (marker shape and eligibility, unique
636
+ * earlier source-event references, positional replacement validity, and complete
637
+ * shadowed-node coverage). One iterative pass reads, validates, and
638
+ * copies each nested value once, so a stateful getter cannot supply one value
639
+ * to validation and another to storage. The event log is the durable source
640
+ * of truth, so a bad event fails at the append site rather than later during
641
+ * a backend flush. A synchronous internal dispatch validation failure or an
642
+ * append reentered while this acceptance/publication boundary is open also
643
+ * rejects before the log changes.
644
+ */
645
+ append<T extends SessionEventType>(
646
+ type: T,
647
+ data: SessionEventMap[T],
648
+ ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent<T>] : []
649
+ ): SessionEvent<T>;
650
+ /**
651
+ * The {@link EpochHeader} in force after the log's last header event — the
652
+ * header the NEXT request will be compared against — or undefined before
653
+ * the first `request/header` snapshot. The live, incrementally-maintained
654
+ * form of `foldRequestHeader(session.snapshotEvents())`: each header event is folded
655
+ * once, when first seen, so a per-step read costs O(new events).
656
+ * @returns the folded header, or undefined when no header event exists yet.
657
+ */
658
+ requestHeader(): EpochHeader | undefined;
659
+ /**
660
+ * Return the latest resolved route metadata, or `undefined` before the first
661
+ * `request/context` event. Each event is folded once.
662
+ * @returns the latest immutable route metadata.
663
+ */
664
+ requestContext(): RequestContext | undefined;
665
+ /**
666
+ * Fold unseen committed events into capability-independent tool history.
667
+ * Initial access reconstructs inherited history; later reads consume only new events.
668
+ * @returns an immutable snapshot for LLM request projection, including historical addition definitions.
669
+ */
670
+ toolHistory(): ToolHistory;
671
+ /**
672
+ * Derive the LLM message history by walking the ordered sequences of
673
+ * message-producing events maintained by `surfaceOp` markers. The
674
+ * surface is the single source of derived history: every message-producing
675
+ * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
676
+ * turn boundary) is correctly absent, and a compaction `replace` deletes the
677
+ * shadowed nodes from the derivation. The projection rules are
678
+ * {@link deriveEventMessage}, with logged message projections applied
679
+ * without changing node membership or message identity.
680
+ *
681
+ * CACHED: pure tail growth costs O(new nodes); a replacement or message projection
682
+ * ({@link SessionSurface.contentGeneration}) rebuilds. The returned array is
683
+ * a fresh snapshot per call (later appends never grow an array a caller
684
+ * already holds); the `Message` objects in it are SHARED and **deep-frozen**.
685
+ * Unchanged content reuses frozen event data; projected blocks are frozen
686
+ * derived copies. Consumers cannot mutate the log through either form.
687
+ * @returns a fresh array of the shared, frozen derived history.
688
+ */
689
+ deriveMessages(): Message[];
690
+ /**
691
+ * Project one event with all committed message projections applied.
692
+ * The original durable event remains unchanged.
693
+ * @param event - the event to project.
694
+ * @returns the derived message, or null when the event produces none.
695
+ */
696
+ deriveEventMessage(event: SessionEvent): Message | null;
697
+ }
698
+ ```
699
+
700
+ ## Derived history: `deriveMessages()` and `deriveEventMessage()`
701
+
702
+ `Session.deriveMessages()` projects the event log into the `Message[]` the model sees — cached (each surface node projected once, when first seen; a surface rewrite rebuilds) and frozen (a fresh array per call over shared, deep-frozen messages, so mutating logged history through a projection is unrepresentable). `deriveEventMessage(event)` is the per-node pure function the fold applies — public so external reconstructors project a log prefix with exactly the same rules and cannot disagree with the cache. The projection rules:
703
+
704
+ - `user/message` → a user message carrying exact `content`; an optional envelope remains log-only display metadata.
705
+ - `assistant/message` → an assistant message with the provider and model that produced it plus optional adapter-private replay state. Its embedded compact stream is replay, usage, and UI evidence rather than a second message. An **empty-content** `assistant/message` is also skipped — a max-tokens step cut off with no content still records an `assistant/message` to hold its stream, usage, provider, and model, but a content-less assistant turn must not enter the provider transcript.
706
+ - `tool/result` → a first-class tool-role message carrying its result content and tool-call identity.
707
+ - `user/message` (injected context, i.e. non-`user` source) → a user-role message carrying its `content` verbatim at its chronological position; its typed source names the producer and carries any producer-specific data.
708
+
709
+ Everything else (`turn/*`, `step/*`, `assistant/attempt`, plugin-owned `llm/retry`) is structural and does not project into a message. Token accounting expands the embedded stream on each `assistant/message` or `assistant/attempt`, while the message's top-level `usage` remains the committed-message authority when present. A failed model-request attempt therefore retains its provider usage without fabricating an assistant message. Current logical validation rejects request headers and assistant messages that omit provider/model instead of guessing a route; supported historical representations are normalized and validated by their adjacent format edge before a current Session exists.
710
+
711
+ ## Live-session fork API
712
+
713
+ `ctx.sessions.create(id, { seed, meta })` is the low-level replay/fork primitive. For ordinary live-session forks, `SessionStore` exposes one policy API:
714
+
715
+ - `fork(source, boundary?, childSessionId?)` accepts a live `Session` object or live `SessionId`, selects source events through the inclusive `SessionSeq` boundary (default: current last event), closes any open tail, then creates an independent live session with deep-cloned seed events, `isSeeded: true`, the exact `inheritedEventCount`, and inherited `cwd`, without `parentSession`.
716
+
717
+ An explicit `boundary` lets callers fork from any stable between-turn position, including a previous `turn/end` or a later standalone log-only event, even if the source has newer events or an open current turn. The API rejects a prefix that ends inside an open turn instead of clipping silently. `dsh-subagent-fork-in-process` keeps its completed-prefix clipping because tool-time delegation usually starts while the parent turn is open; ordinary session branching should make the requested boundary explicit.
718
+
719
+ ## Why a turn ended: `TurnEndReasonMap`
720
+
721
+ `turn/start` has no trigger field. The entered `user/message` batch records what entered each step, `llm/retry` records request recovery, and idle injection remains pending until a waking delivery reaches a later pre-step. Live turns retain the typed [`AgentCancelCause`](./core.md#the-agent-handle) that stopped the driver; persistence uses the additional `{ kind: 'legacy' }` cause only when importing a supported coarse cancellation record that did not store its caller.
722
+
723
+ ```ts type-equiv
724
+ /** Durable cancellation cause, including imports whose original coarse record carried no cause. */
725
+ type TurnEndCancelCause = AgentCancelCause | { readonly kind: 'legacy' }
726
+ ```
727
+
728
+ ```ts type-equiv
729
+ /**
730
+ * Why a turn ended. Merge-extensible sum type.
731
+ */
732
+ interface TurnEndReasonMap {
733
+ completed: { kind: 'completed' }
734
+ /** A cancellation request interrupted the live turn. */
735
+ aborted: { kind: 'aborted'; reason: TurnEndCancelCause }
736
+
737
+ blocked: { kind: 'blocked' }
738
+ /**
739
+ * The turn failed. `error` is always a structured failure: the `LlmError`
740
+ * facts verbatim, or `{ message: errorChain(error), code }` flattened from
741
+ * any other error, where `code` is `TOOL_ACTIVATION_FAILED` for a failed
742
+ * tool condition and `UNKNOWN` otherwise.
743
+ */
744
+ error: { kind: 'error'; error: LlmFailure }
745
+ /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */
746
+ 'max-tokens': { kind: 'max-tokens' }
747
+ /**
748
+ * A crash-orphaned turn was closed after the fact: agent-loop resume appends
749
+ * this closer for a stored log whose last turn never ended, and session-query
750
+ * synthesizes it on cold reads. The loop never emits this marker live, and
751
+ * the events recorded before the crash remain intact.
752
+ */
753
+ interrupted: { kind: 'interrupted' }
754
+ /**
755
+ * Fork-seed construction closed a turn that was still open at the fork
756
+ * boundary in the source session. Only fork seeds carry this marker — the
757
+ * loop never emits it — and the source events before the boundary remain
758
+ * intact in the child.
759
+ */
760
+ forked: { kind: 'forked' }
761
+ }
762
+ ```
763
+
764
+ `max-tokens` mirrors the model-call `FinishReason` of the same name: any `max-tokens` step in a turn makes the whole turn end `max-tokens` rather than `completed` (the cut-short fact wins over a later continuation), so a consumer can tell a clean stop from a truncated one. Cancellation and errors remain distinct outcomes. The loop emits neither `interrupted` nor `forked` live: crash recovery synthesizes `interrupted` (see [persistence.md](./persistence.md)), while fork-seed construction synthesizes `forked`. The map is merge-extensible.
765
+
766
+ ## Execution enclosure and standalone events
767
+
768
+ A turn encloses one model-loop execution, not the whole session log. AgentLoop records injected `user/message` events only from entering pre-step batches inside a turn; plugin-owned log-only events may still appear between `turn/end` and the next `turn/start`, consuming event seqs without incrementing turn numbers. Persistence admits every contiguous accepted event into a bounded durable batch, while crash repair closes only a genuinely open trailing turn. A producer that needs an immediate durability barrier explicitly awaits `ctx.sessions.flush(session)`.
769
+
770
+ Merge-extensible event relations belong to the plugin that declares them, so core does not reject an unknown event merely because no turn is open. See [the standalone-event decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/simplification/2026-07-28-remove-synthetic-log-only-turns.md).
771
+
772
+ ## The end-seed boundary: `session/end-seed`
773
+
774
+ `buildForkSeed` appends `session/end-seed { inherited: true }` at the exact inherited-prefix cut before adding synthetic fork closers. The `Session` constructor retains that prepared marker or appends one when given only the inherited prefix. A restore retains the tagged marker and appends an ordinary `session/end-seed {}` only when its complete stored seed does not already end in a marker. Both forms are log-only and produce no message; only the constructor and `buildForkSeed` may create them.
775
+
776
+ For fork lineage, locate the LAST marker whose payload carries `inherited: true`; current-format decoding requires it exactly when `SessionHeader.isSeeded` is true and derives `inheritedEventCount` from its seq. For lifecycle ownership, locate the last `session/end-seed` of either form. Reopening a seed that already ends in any marker does not append another ordinary marker.
777
+
778
+ It exists because seed history and live work are otherwise byte-identical, which defeats any plugin owning a standalone open/close bracket: an unmatched `compaction/start` reads the same whether the writer crashed mid-compaction or is compacting right now. An opening marker before `session/end-seed` came from the constructor seed and belongs to an ended lifecycle, whatever ended it (a crash, a succeeding process, or a fork out of a still-running parent), so its owner may treat it as dead. That covers only brackets *this* session inherited: a concurrently live session holding an open bracket over the same history has its own boundary elsewhere, so tolerating concurrent writers needs a liveness signal beyond the log. Core writes the boundary and reads nothing from it — a bracket's vocabulary stays with its owning plugin, which is why crash repair closes turn/step/tool boundaries and never `compaction/*`.
779
+
780
+ Consumers that order Sessions by human activity exclude this boundary: picking a Session up is not work, so ordering by the log tail would float every opened Session to the top.
781
+
782
+ ## Plugin-contributed log-only events
783
+
784
+ A plugin may declaration-merge extra `SessionEventMap` types. These are **log-only**: NOT `SurfaceEventType`s (they carry no `surfaceOp` and contribute nothing to derived history). Their owner decides whether they belong to an open execution turn or may stand between turns. The generated [persistence log event catalog](../persistence-catalog.md) enumerates every core and plugin-contributed event; the compaction seam's `compaction/*` semantics are discussed on [compaction.md](./compaction.md).
785
+
786
+ When several events in one plugin-owned family assemble into one Web Client Conversation Node, every start, update, result, resource, or interruption event in that family carries or independently derives the same stable business id. This requirement applies to correlated Node families, not to every Session event; it lets the client group each event without guessing from adjacency or scanning history. See the [Conversation subsystem](./conversation.md).
787
+
788
+ The hook bridges' `hook/invoked` / `hook/result` pairs (from `@deepseek-ai/dsh-hook-protocol`) correlate by `handlerId`. `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, and `Stop` fire inside the loop's open turn, so their `hook/*` records are turn-enclosed by construction. `SessionStart` gets no `hook/*` record because it runs before turn 1; its context remains pending in the inbox until a waking delivery opens a turn.
789
+
790
+ ### Plugin records
791
+
792
+ Experimental packages declare plugin-owned state in `PluginRecordMap`: `appendPluginRecord()` uses each declaration to type its name and payload, and appends an event marked `ignorable: true` in the `plugin:` namespace. `pluginRecordOf()` reads stored records with unknown payloads regardless of current declarations. The [experimental persistence catalog](../experimental-persistence-catalog.md) lists current declarations. The [package README](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/README.md#write-experimental-plugin-records) owns the caller restriction, retention, and read path.
793
+
794
+ ```ts type-equiv
795
+ /**
796
+ * Event type of an experimental plugin record: `plugin:` followed by
797
+ * slash-separated segments of lowercase letters, digits, `.`, `_`, and `-`,
798
+ * each starting with a letter or digit. A record type is never a
799
+ * {@link SessionEventMap} member.
800
+ */
801
+ type PluginRecordType = `plugin:${string}`
802
+ ```
803
+
804
+ ```ts type-equiv
805
+ /**
806
+ * Payloads written by experimental packages, keyed by their `plugin:` record
807
+ * names. Packages augment this map to type writes and enter the current plugin
808
+ * record catalog; these declarations do not enter {@link SessionEventMap} or
809
+ * released persistence schemas. Stored records still require owner validation.
810
+ */
811
+ interface PluginRecordMap {}
812
+ ```
813
+
814
+ ```ts type-equiv
815
+ /**
816
+ * One committed experimental plugin record, read from the log by
817
+ * `pluginRecordOf`. The record's owner validates `data` before use, because a
818
+ * restored record carries whatever JSON an earlier build of its owner wrote,
819
+ * or a V3 event that a format migration renamed into the `plugin:` namespace held.
820
+ */
821
+ interface PluginRecord {
822
+ /** The record type, chosen by the owning plugin. */
823
+ readonly type: PluginRecordType
824
+ /** The record's position in the Session log. */
825
+ readonly seq: SessionSeq
826
+ /** Unix epoch milliseconds at append. */
827
+ readonly time: number
828
+ /** The JSON payload as committed. */
829
+ readonly data: unknown
830
+ }
831
+ ```
832
+
833
+ ## Durability contract
834
+
835
+ What a persistence backend relies on: the durable log persists every event losslessly, and every Assistant attempt is one `assistant/message` or `assistant/attempt` whose embedded compact stream preserves the original timed chunks. `seq` stays contiguous across these settlements and all interleaved events. A backend may choose its own storage framing for an event batch as long as a handle's `read()` returns the exact appended events; current JSONL writes one row per event (see [persistence.md](./persistence.md)). All `event.data` must be JSON-serializable; `Session.append` enforces this at the source (throwing on non-serializable data), so a bad event never enters the log and `session.snapshotEvents()` always equals what a backend can persist. Adding an event type that carries non-serializable data, corrupts core execution nesting, or violates its owner's declared relation is a breaking change to the on-disk format.
836
+
837
+ The backends that consume this contract are on [persistence.md](./persistence.md).
838
+
839
+ ## Remote catalog and workspace opening
840
+
841
+ `ModelCatalog` is the Host-generation model directory returned by `session/modelCatalog`: it carries the deployment default, routable provider ids, successful provider groups, and isolated provider failures. It is not derived from one Session and remains separate from Session projections.
842
+
843
+ `SessionOpenWorkspacePathRequest` carries an absolute or workspace-resolved `path`; optional `action: "reveal"` selects file-manager navigation instead of default-application opening. `SessionOpenWorkspacePathValue` confirms that the Host accepted the native handoff. A Session-aware Client resolves relative paths against its current Session cwd when known; the controller hands the path to the opener unchanged and reports invalid requests, cancellation, and opener failures through the Session Remote error vocabulary.
844
+
845
+ The optional `application` selects a registered file handler without changing the system default; `workspacePathApplications({ path })` returns current handlers, names, icons, and default selection after Host path verification.
846
+
847
+ ## Session-log upload exclusions
848
+
849
+ `ctx.sessionLogDeepSeek.registerExclusion()` registers a caller-owned predicate over `SessionLogUploadRequest`. Any match omits the log contribution and its acceptance callback before reading Session events. No match preserves normal upload eligibility. The [package README](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/session/session-log-deepseek/README.md#upload-exclusions) defines failure and disposal behavior.
850
+
851
+ ```ts type-equiv
852
+ /** Request identity inspected before preparing a Session-log contribution. */
853
+ interface SessionLogUploadRequest {
854
+ /** Live Session whose canonical log would be contributed. */
855
+ readonly sessionId: SessionId
856
+ /** Auxiliary request classification; absent for ordinary conversation requests. */
857
+ readonly purpose?: string
858
+ }
859
+ ```
860
+
861
+ ```ts type-equiv
862
+ /**
863
+ * Synchronous, side-effect-free upload exclusion owned by its registering plugin.
864
+ * @param request - request identity; the predicate must not mutate it.
865
+ * @returns `true` to omit the log field and acceptance callback, or `false` to keep checking eligibility.
866
+ */
867
+ type SessionLogUploadExclusion = (request: SessionLogUploadRequest) => boolean
868
+ ```
869
+
870
+ <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
871
+
872
+ <a id="cordis-surface"></a>
873
+
874
+ ## Cordis API
875
+
876
+ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md).
877
+
878
+ <a id="ctxsessioncontroller--sessioncontroller"></a>
879
+
880
+ ### `ctx.sessionController` — `SessionController`
881
+
882
+ Host service backing the generated `ctx.remote.session` namespace.
883
+
884
+ ```ts cordis-catalog
885
+ /**
886
+ * Resolve or resume one ordinary Session for another Host API domain.
887
+ * @param sessionId - Session identity whose Agent owns the operation.
888
+ * @returns the live Agent or the stable Session-domain failure.
889
+ */
890
+ resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult>
891
+
892
+ /**
893
+ * Read all visible Session rows without resuming an Agent.
894
+ * @param _request - reserved empty list request.
895
+ * @param signal - cancellation for persistence reads and summary generation.
896
+ * @returns visible Session summaries ordered by activity.
897
+ */
898
+ @Remote('list') async list(_request: SessionListRequest, signal: AbortSignal): Promise<SessionListValue>
899
+
900
+ /**
901
+ * Search visible Session content without resuming an Agent. A non-owner
902
+ * receives only the hits whose Session `allows()` admits; `hasMore`
903
+ * describes the bounded result before that filtering.
904
+ * @param request - literal message-content query.
905
+ * @param signal - cancellation for list and search reads.
906
+ * @returns authorized bounded Session search results.
907
+ */
908
+ @Remote('search') async search(request: SessionSearchRequest, signal: AbortSignal): Promise<SessionSearchValue>
909
+
910
+ /**
911
+ * Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable.
912
+ * @param request - optional blank Session to reuse, location, and Agent preset.
913
+ * @returns the created or reused Session identity and its preset when configured.
914
+ */
915
+ @Remote('create') create(request: SessionCreateRequest): Promise<SessionCreateValue>
916
+
917
+ /**
918
+ * Select one Session-local model after explicitly resuming the Session; save the default in the background.
919
+ * @param request - Session identity and requested model selection.
920
+ * @returns the normalized selection installed for the Session, without waiting for default persistence.
921
+ */
922
+ @Remote('selectModel') selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue>
923
+
924
+ /**
925
+ * Select the first available account model after login when no provider API key is configured.
926
+ * @returns after saving the first available model or retaining the existing default.
927
+ */
928
+ @Remote async initializeDefaultModel(): Promise<void>
929
+
930
+ /**
931
+ * Describe every currently routable model for Host-generation selectors.
932
+ * @returns provider-grouped models, the deployment default, and isolated provider failures.
933
+ */
934
+ @Remote('modelCatalog') modelCatalog(): Promise<ModelCatalog>
935
+
936
+ /**
937
+ * Report whether this deployment can hand a Session workspace path to a native desktop.
938
+ * @returns true when the matching open operation is available.
939
+ */
940
+ @Remote canOpenWorkspacePath(): boolean
941
+
942
+ /**
943
+ * Describe the serving desktop for authenticated file-action routes.
944
+ * @returns Host name, configured availability, and platform-specific file-manager behavior.
945
+ */
946
+ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | 'explorer' | 'directory' | null }
947
+
948
+ /**
949
+ * Verify one path through the composed filesystem and open it on the Host desktop.
950
+ * @param request - path after best-effort Session workspace resolution.
951
+ * @param signal - caller lifetime; abort terminates the native command.
952
+ * @returns confirmation after the native opener accepts the path.
953
+ * @throws RemoteError when the request is invalid, has no verified Host mapping, is cancelled, or the opener fails.
954
+ */
955
+ @Remote('openWorkspacePath') async openWorkspacePath( request: SessionOpenWorkspacePathRequest, signal: AbortSignal, ): Promise<SessionOpenWorkspacePathValue>
956
+
957
+ /**
958
+ * Query current file handlers on the serving desktop without activating an Agent.
959
+ * @param request - file path in Host filesystem syntax.
960
+ * @param signal - caller lifetime, propagated to filesystem and desktop queries.
961
+ * @returns OS application names, icons, and default selection; empty when desktop opening is unavailable.
962
+ * @throws RemoteError when the path is invalid, the query is cancelled, or native discovery fails.
963
+ */
964
+ @Remote('workspacePathApplications') async workspacePathApplications( request: { readonly path: string }, signal: AbortSignal, ): Promise<readonly SessionWorkspacePathApplication[]>
965
+
966
+ /**
967
+ * Rename one Session after explicitly resuming it.
968
+ * @param request - Session identity and proposed title.
969
+ * @returns the accepted title and durable event sequence.
970
+ */
971
+ @Remote('rename') rename(request: SessionRenameRequest): Promise<SessionRenameValue>
972
+
973
+ /**
974
+ * Fork one cold-readable exact event prefix into a new Session. An omitted
975
+ * boundary selects the latest completed-turn prefix; an open cut receives
976
+ * synthetic fork closers.
977
+ * @param request - source Session, optional exact inclusive event boundary, and migration preflight choice.
978
+ * @returns the new Session identity.
979
+ */
980
+ @Remote('fork') async fork(request: SessionForkRequest): Promise<SessionForkValue>
981
+
982
+ /**
983
+ * Admit one prompt after explicitly resuming its Session.
984
+ * @param request - Session identity, prompt content, source metadata, and delivery mode.
985
+ * @param signal - caller cancellation before prompt admission begins.
986
+ * @returns acknowledgement that the Agent accepted the prompt.
987
+ */
988
+ @Remote('prompt') async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<SessionPromptValue>
989
+
990
+ /**
991
+ * Read one image from the attachment store after gateway authorization.
992
+ * @param request - image reference and gateway permission scope; Session existence is not checked.
993
+ * @returns the durable attachment reference and base64-encoded bytes.
994
+ */
995
+ @Remote('attachment') attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue>
996
+
997
+ /**
998
+ * Mutate one still-pending queue occurrence, resuming a cold Agent first.
999
+ * @param request - Session, queue item, and requested mutation.
1000
+ * @returns acknowledgement that the queue mutation was applied.
1001
+ */
1002
+ @Remote('updateQueue') updateQueue(request: SessionUpdateQueueRequest): Promise<SessionUpdateQueueValue>
1003
+
1004
+ /**
1005
+ * Cancel one active Agent turn without dropping its pending inbox.
1006
+ * @param request - Session whose active Agent turn is cancelled.
1007
+ * @returns acknowledgement that cancellation was requested.
1008
+ */
1009
+ @Remote('cancel') cancel(request: SessionCancelRequest): SessionCancelValue
1010
+
1011
+ /**
1012
+ * Read one cold-safe, message-aligned Session history page.
1013
+ * @param request - durable address, optional fixed cut, backward cursor, and page budget.
1014
+ * @param signal - cancellation for persistence reads.
1015
+ * @returns one chronological page with its inclusive cursor.
1016
+ */
1017
+ @Remote events(request: SessionPageRequest, signal: AbortSignal): Promise<SessionEventsPage>
1018
+
1019
+ /**
1020
+ * Subscribe to Session events without reading a snapshot.
1021
+ * @param request - Session address.
1022
+ * @param signal - subscription cancellation.
1023
+ * @returns readiness and subsequent events, without a snapshot.
1024
+ */
1025
+ @Remote({ mode: 'stream' }) observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable<SessionEventFrame>
1026
+
1027
+ /**
1028
+ * Subscribe to Session projection changes.
1029
+ * @param request - target Session.
1030
+ * @param signal - subscription cancellation.
1031
+ * @returns readiness followed by one projection change frame per committed event.
1032
+ */
1033
+ @Remote({ mode: 'stream' }) observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable<SessionProjectionFrame>
1034
+
1035
+ /**
1036
+ * Read passive Session state.
1037
+ * @param request - target Session.
1038
+ * @param signal - read cancellation.
1039
+ * @returns current passive state.
1040
+ */
1041
+ @Remote state(request: SessionStateRequest, signal: AbortSignal): Promise<SessionState>
1042
+
1043
+ /**
1044
+ * Subscribe to complete Session state replacements.
1045
+ * @param request - target Session.
1046
+ * @param signal - subscription cancellation.
1047
+ * @returns complete passive state replacements.
1048
+ */
1049
+ @Remote({ mode: 'stream' }) observeState(request: SessionStateRequest, signal: AbortSignal): AsyncIterable<SessionState>
1050
+
1051
+ /**
1052
+ * Wait for Session quiescence or pending input with bounded assistant output.
1053
+ * @param request - Session, wait bounds and output window.
1054
+ * @param signal - caller cancellation.
1055
+ * @returns stopping state and bounded assistant output.
1056
+ */
1057
+ @Remote wait(request: SessionWaitRequest, signal: AbortSignal): Promise<SessionWaitValue>
1058
+
1059
+ /**
1060
+ * Follow one Session log from its opening or resume cursor.
1061
+ * @param request - durable address and last committed sequence already held by the caller.
1062
+ * @param signal - cancellation owned by the Remote stream carrier.
1063
+ * @returns a complete opening snapshot followed by gap-free durable event
1064
+ * frames and optional cursorless assistant-stream frames.
1065
+ */
1066
+ @Remote({ mode: 'stream' }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame>
1067
+
1068
+ /**
1069
+ * Read exact projections, returning cached hints only when migration is required.
1070
+ * @param request - Session whose current values are required.
1071
+ * @param signal - cancellation for the Session read.
1072
+ * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent.
1073
+ */
1074
+ @Remote('projections') projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise<SessionProjectionsValue>
1075
+
1076
+ /**
1077
+ * Stream a complete live-control baseline followed by replacement frames.
1078
+ * @param signal - cancellation owned by the Remote stream carrier.
1079
+ * @returns one complete baseline followed by live replacement frames.
1080
+ */
1081
+ @Remote({ mode: 'stream' }) async *control(signal: AbortSignal): AsyncIterable<SessionControlFrame>
1082
+ ```
1083
+
1084
+ Types: [SessionId](./core.md) · [SessionSearchRequest](./session-query.md)
1085
+
1086
+ Source: [`packages/api/session-controller/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/index.ts)
1087
+
1088
+ <a id="ctxsessionlogdeepseek--sessionlogdeepseekservice"></a>
1089
+
1090
+ ### `ctx.sessionLogDeepSeek` — `SessionLogDeepSeekService`
1091
+
1092
+ Incremental Session-log contributor with caller-owned upload exclusions.
1093
+
1094
+ ```ts cordis-catalog
1095
+ /**
1096
+ * Exclude matching requests before reading or preparing their log contribution.
1097
+ * Any matching rule suppresses both the field and its acceptance callback. With
1098
+ * no matching rules, normal upload eligibility applies. A throwing rule fails
1099
+ * this contribution; the request-extension registry omits it and reports the error.
1100
+ * @param exclude - synchronous, side-effect-free predicate; `true` skips this upload.
1101
+ * @returns effect disposer that removes this registration when called or when the caller unloads.
1102
+ */
1103
+ registerExclusion(exclude: SessionLogUploadExclusion): () => Promise<void>
1104
+ ```
1105
+
1106
+ Source: [`packages/session/session-log-deepseek/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/session/session-log-deepseek/src/index.ts)
1107
+
1108
+ <a id="ctxsessions--sessionstore"></a>
1109
+
1110
+ ### `ctx.sessions` — `SessionStore`
1111
+
1112
+ In-memory session store (`ctx.sessions`).
1113
+
1114
+ Persistence is intentionally not implemented here — the agent lifecycle attaches a session-log writer to each published session's write handle; a session published outside that lifecycle persists nothing.
1115
+
1116
+ ```ts cordis-catalog
1117
+ /**
1118
+ * Register one event interpreter for live creation, restore, and fork.
1119
+ * Disposing the contribution makes sessions that used it refuse further derivation.
1120
+ * @param projection - pure definition owned by the event's plugin.
1121
+ * @returns the fiber-owned disposer.
1122
+ * @throws when another definition already owns this event type.
1123
+ */
1124
+ registerMessageProjection(projection: SessionMessageProjection): () => Promise<void>
1125
+
1126
+ /**
1127
+ * Create a session owned by the calling fiber: disposing that fiber stops
1128
+ * event notification and removes the session from the store. `options.seed`
1129
+ * populates the session with a copy of those events (replay/fork);
1130
+ * `options.meta` attaches creation metadata (validated absolute `cwd`, seed
1131
+ * and parent lineage, and delegation depth) as the immutable
1132
+ * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).
1133
+ *
1134
+ * For an agent whose session must be torn down IN ORDER with its loop (so the
1135
+ * loop's final events are published before the store attachment ends), do NOT use this
1136
+ * — fold the session lifecycle into the agent's own effect via
1137
+ * {@link prepare} + {@link enter} + {@link announce} (see
1138
+ * `dsh-agent-loop`'s creation transaction).
1139
+ *
1140
+ * @param id - the session id; omitted, the store mints `session-<n>`.
1141
+ * @param options - seed events and/or creation metadata for the header.
1142
+ * @returns the live session, already entered and announced.
1143
+ * @throws if a session with `id` already exists, metadata is not a plain
1144
+ * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
1145
+ * non-absolute path (storage backends key directories off it).
1146
+ */
1147
+ create(id?: SessionId, options?: CreateSessionOptions): Session
1148
+
1149
+ /**
1150
+ * Build a session WITHOUT entering it into the store — validate the id/cwd and
1151
+ * construct the {@link Session} (with its immutable {@link SessionHeader}).
1152
+ * Pairs with {@link enter} + {@link announce}: a caller that owns a composite
1153
+ * `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
1154
+ * effect so a fiber unload tears the session + agent down as a single ORDERED
1155
+ * chain rather than as racing sibling effects — which would remove the publication hooks
1156
+ * before the driver's closing events commit, dropping them.
1157
+ *
1158
+ * @param id - the session id; omitted, the store mints `session-<n>`.
1159
+ * @param options - seed events and/or creation metadata for the header. With
1160
+ * `eventState`, every seed event is either independently owned or any
1161
+ * shared value is deeply frozen; {@link Session.fromRestore} validates and
1162
+ * adopts those values without copying or freezing them.
1163
+ * @returns the store-owned session, not yet entered and read-only until announced.
1164
+ * @throws if a session with `id` already exists, metadata is not a plain
1165
+ * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
1166
+ * non-absolute path.
1167
+ */
1168
+ prepare(id?: SessionId, options?: PrepareSessionOptions): Session
1169
+
1170
+ /**
1171
+ * Enter a session into the store: install the module-private
1172
+ * append publication hooks and add it to the store. Writes remain disabled
1173
+ * until {@link announce} completes successfully. Returns the DETACH
1174
+ * disposer (hooks + store removal). Does NOT emit `session/created` —
1175
+ * the caller yields this disposer inside its effect and THEN calls
1176
+ * {@link announce}, so a throwing `session/created` listener rolls the attach
1177
+ * back instead of leaking it.
1178
+ *
1179
+ * Re-checks the id for a duplicate: `prepare` and `enter` are public
1180
+ * cross-package primitives and a caller may interleave arbitrary work (or
1181
+ * another create) between them, so a stale prepared session must NOT overwrite
1182
+ * a live store entry of the same id — its detach disposer would later delete
1183
+ * the REAL session. The {@link create} convenience and the agent factory call
1184
+ * the two back-to-back so they never trip this, but the public API cannot
1185
+ * assume that.
1186
+ *
1187
+ * @param session - an unentered session; independent instances become store-owned.
1188
+ * @returns the detach disposer (publication hooks + store removal). When called from
1189
+ * a synchronous `session/created` listener, removal and disposal wait until
1190
+ * that creation dispatch unwinds.
1191
+ * @throws if a session with this id is already in the store.
1192
+ */
1193
+ enter(session: Session): () => void
1194
+
1195
+ /** Emit `session/created` exactly once for an {@link enter}ed session (with
1196
+ * the carrier {@link enter} captured). Separate from {@link enter} so the
1197
+ * caller can yield the detach disposer first (rollback safety — see
1198
+ * {@link enter}). The Session remains read-only throughout synchronous
1199
+ * dispatch; successful completion enables appends. A failed announcement
1200
+ * leaves it read-only and cannot be retried.
1201
+ * @param session - the entered session to announce to listeners.
1202
+ * @throws if the session is not live or its announcement already began,
1203
+ * including a reentrant call from a creation listener. */
1204
+ announce(session: Session): void
1205
+
1206
+ /**
1207
+ * Dispatch the awaited `session/flush` durability checkpoint for `session`,
1208
+ * with the carrier captured at {@link enter}. THE flush entry point: the
1209
+ * store owns the carrier, so callers (the checkpoint policy's per-request
1210
+ * barrier, goal-round-driver's idle checkpoint, teardown drains, and consumers
1211
+ * that flush themselves before reading storage) must come through here
1212
+ * rather than dispatch a raw `ctx.parallel('session/flush', …)` — one owner
1213
+ * and one spelling.
1214
+ * @param session - the session whose buffered events must reach durable storage.
1215
+ * @returns whether at least one durability listener participated, after every
1216
+ * listener has settled successfully.
1217
+ * @throws the first registered listener failure after every listener settles.
1218
+ */
1219
+ async flush(session: Session): Promise<boolean>
1220
+
1221
+ /**
1222
+ * Look up a live session.
1223
+ * @param id - the session id to look up.
1224
+ * @returns the session, or undefined when no live session has that id.
1225
+ */
1226
+ get(id: SessionId): Session | undefined
1227
+
1228
+ /**
1229
+ * All live sessions, in creation order.
1230
+ * @returns a fresh array; mutating it does not affect the store.
1231
+ */
1232
+ list(): Session[]
1233
+
1234
+ /**
1235
+ * Create an independent live session from an exact prefix of a live source.
1236
+ * `boundary` is an inclusive source event seq; omitted means the source's
1237
+ * current last event. An open tail receives synthetic tool results and
1238
+ * step/turn closers with the forked cause. Closed steps and turns remain
1239
+ * unchanged, including any failed tool calls already missing results.
1240
+ * `inheritedEventCount` counts only copied source events, excluding these closers.
1241
+ *
1242
+ * @param source - Live source session object or id.
1243
+ * @param boundary - Inclusive source event seq to fork through; omitted means
1244
+ * the source's current last event, and omitted on an empty source forks an
1245
+ * empty child.
1246
+ * @param childSessionId - Optional child session id; omitted delegates to
1247
+ * `SessionStore`'s id policy.
1248
+ * @returns The created live child session.
1249
+ */
1250
+ fork(source: SessionForkSource, boundary?: SessionSeq, childSessionId?: SessionId): Session
1251
+ ```
1252
+
1253
+ Types: [CreateSessionOptions](./persistence.md) · [PrepareSessionOptions](./persistence.md) · [SessionId](./core.md)
1254
+
1255
+ Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1256
+
1257
+ <a id="api-session-events"></a>
1258
+
1259
+ ### `api-session/*` events
1260
+
1261
+ <a id="api-sessionactivity--emit"></a>
1262
+
1263
+ #### `api-session/activity` — emit
1264
+
1265
+ One user-authored durable message advanced Session list activity.
1266
+
1267
+ ```ts cordis-catalog
1268
+ /**
1269
+ * One user-authored durable message advanced Session list activity.
1270
+ * @mode emit
1271
+ * @param sessionId - addressed Session identity.
1272
+ * @param updatedAt - durable message time used for list ordering.
1273
+ */
1274
+ 'api-session/activity'(sessionId: SessionId, updatedAt: number): void
1275
+ ```
1276
+
1277
+ Types: [SessionId](./core.md)
1278
+
1279
+ Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1280
+
1281
+ <a id="api-sessionadded--emit"></a>
1282
+
1283
+ #### `api-session/added` — emit
1284
+
1285
+ A Session became visible or its Agent was created or disposed. Consumers upsert the summary and replace its current running and availability state.
1286
+
1287
+ ```ts cordis-catalog
1288
+ /**
1289
+ * A Session became visible or its Agent was created or disposed.
1290
+ * Consumers upsert the summary and replace its current running and availability state.
1291
+ * @mode emit
1292
+ * @param summary - current list row for the Session.
1293
+ */
1294
+ 'api-session/added'(summary: SessionSummary): void
1295
+ ```
1296
+
1297
+ Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1298
+
1299
+ <a id="api-sessionerror--emit"></a>
1300
+
1301
+ #### `api-session/error` — emit
1302
+
1303
+ One Agent failed outside a durable turn position.
1304
+
1305
+ ```ts cordis-catalog
1306
+ /**
1307
+ * One Agent failed outside a durable turn position.
1308
+ * @mode emit
1309
+ * @param sessionId - Agent and Session identity.
1310
+ * @param message - user-safe failure chain.
1311
+ */
1312
+ 'api-session/error'(sessionId: SessionId, message: string): void
1313
+ ```
1314
+
1315
+ Types: [SessionId](./core.md)
1316
+
1317
+ Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1318
+
1319
+ <a id="api-sessionremoved--emit"></a>
1320
+
1321
+ #### `api-session/removed` — emit
1322
+
1323
+ A Session left the live Host registry.
1324
+
1325
+ ```ts cordis-catalog
1326
+ /**
1327
+ * A Session left the live Host registry.
1328
+ * @mode emit
1329
+ * @param sessionId - removed Session identity.
1330
+ */
1331
+ 'api-session/removed'(sessionId: SessionId): void
1332
+ ```
1333
+
1334
+ Types: [SessionId](./core.md)
1335
+
1336
+ Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1337
+
1338
+ <a id="api-sessionstatus--emit"></a>
1339
+
1340
+ #### `api-session/status` — emit
1341
+
1342
+ One Agent changed running state.
1343
+
1344
+ ```ts cordis-catalog
1345
+ /**
1346
+ * One Agent changed running state.
1347
+ * @mode emit
1348
+ * @param sessionId - Agent and Session identity.
1349
+ * @param running - whether the Agent is running.
1350
+ */
1351
+ 'api-session/status'(sessionId: SessionId, running: boolean): void
1352
+ ```
1353
+
1354
+ Types: [SessionId](./core.md)
1355
+
1356
+ Source: [`packages/api/session-controller/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/api/session-controller/src/types.ts)
1357
+
1358
+ <a id="session-events"></a>
1359
+
1360
+ ### `session/*` events
1361
+
1362
+ <a id="sessioncreated--emit"></a>
1363
+
1364
+ #### `session/created` — emit
1365
+
1366
+ Read-only creation announcement after store entry. New events reject until every synchronous listener has returned successfully. A synchronous throw vetoes creation and rolls back with a paired disposal; detach requested during dispatch is deferred. A returned-promise rejection is logged but cannot retroactively veto this synchronous boundary. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only sessions entered through that agent's context.
1367
+
1368
+ ```ts cordis-catalog
1369
+ /**
1370
+ * Read-only creation announcement after store entry.
1371
+ * New events reject until every synchronous listener has returned successfully.
1372
+ * A synchronous throw vetoes creation and rolls back with a paired disposal;
1373
+ * detach requested during dispatch is deferred.
1374
+ * A returned-promise rejection is logged but cannot retroactively veto this
1375
+ * synchronous boundary.
1376
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
1377
+ * receive only sessions entered through that agent's context.
1378
+ * @param session - the session just entered and announced.
1379
+ * @mode emit
1380
+ */
1381
+ 'session/created'(this: Scoped<Session>, session: Session): void
1382
+ ```
1383
+
1384
+ Types: [Scoped](./scope.md)
1385
+
1386
+ Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1387
+
1388
+ <a id="sessiondisposed--emit"></a>
1389
+
1390
+ #### `session/disposed` — emit
1391
+
1392
+ Emitted once when an announced session leaves the store, including publication rollback, but never for an entry whose creation announcement did not begin. Listener failures are logged and contained. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope.
1393
+
1394
+ ```ts cordis-catalog
1395
+ /**
1396
+ * Emitted once when an announced session leaves the store, including
1397
+ * publication rollback, but never for an entry whose creation announcement
1398
+ * did not begin. Listener failures are logged and contained.
1399
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope.
1400
+ * @param session - the session that is no longer live in the store.
1401
+ * @mode emit
1402
+ */
1403
+ 'session/disposed'(this: Scoped<Session>, session: Session): void
1404
+ ```
1405
+
1406
+ Types: [Scoped](./scope.md)
1407
+
1408
+ Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1409
+
1410
+ <a id="sessionevent--emit"></a>
1411
+
1412
+ #### `session/event` — emit
1413
+
1414
+ Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Array append commits every member before publishing them in order; `session.seq` and `session.surface` already include the complete batch. `session.currentBatchPublication` identifies the member being delivered. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context.
1415
+
1416
+ ```ts cordis-catalog
1417
+ /**
1418
+ * Post-commit, fire-and-forget append feed. The listener snapshot resolves
1419
+ * before the log push, but callbacks run after it; observer failures are
1420
+ * logged and contained without making the committed append fail.
1421
+ * Array append commits every member before publishing them in order;
1422
+ * `session.seq` and `session.surface` already include the complete batch.
1423
+ * `session.currentBatchPublication` identifies the member being delivered.
1424
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
1425
+ * receive only events from sessions entered through that agent's context.
1426
+ * @param session - the session whose log grew.
1427
+ * @param event - the appended event, exactly as recorded.
1428
+ * @mode emit
1429
+ */
1430
+ 'session/event'(this: Scoped<Session>, session: Session, event: SessionEvent): void
1431
+ ```
1432
+
1433
+ Types: [Scoped](./scope.md)
1434
+
1435
+ Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1436
+
1437
+ <a id="sessionflush--parallel"></a>
1438
+
1439
+ #### `session/flush` — parallel
1440
+
1441
+ Awaited parallel durability checkpoint: every listener runs and the caller awaits all of them, with no waterfall veto. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
1442
+
1443
+ ```ts cordis-catalog
1444
+ /**
1445
+ * Awaited parallel durability checkpoint: every listener runs and the
1446
+ * caller awaits all of them, with no waterfall veto. Scope-filtered dispatch
1447
+ * (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
1448
+ * @param session - the session whose buffered events must reach durable storage.
1449
+ * @mode parallel
1450
+ */
1451
+ 'session/flush'(this: Scoped<Session>, session: Session): Promise<void> | void
1452
+ ```
1453
+
1454
+ Types: [Scoped](./scope.md)
1455
+
1456
+ Source: [`packages/core/session/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
1457
+
1458
+ <a id="timeline-events"></a>
1459
+
1460
+ ### `timeline/*` events
1461
+
1462
+ <a id="timelinepriority--emit"></a>
1463
+
1464
+ #### `timeline/priority` — emit
1465
+
1466
+ A saved user edit entered or left P0. Model task patches do not emit it.
1467
+
1468
+ ```ts cordis-catalog
1469
+ /**
1470
+ * A saved user edit entered or left P0. Model task patches do not emit it.
1471
+ * @mode emit
1472
+ * @param session - the session that owns the task.
1473
+ */
1474
+ 'timeline/priority'(session: Session): void
1475
+ ```
1476
+
1477
+ Source: [`packages/experimental/timeline/src/storage.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/experimental/timeline/src/storage.ts)
1478
+ <!-- END GENERATED cordis-surface -->