dsh-plugin-dev-kb 1.0.0

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 (234) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -0
  3. package/cordis.patch.yml +12 -0
  4. package/kb/INDEX.md +210 -0
  5. package/kb/README.md +69 -0
  6. package/kb/extra/AGENTS.md +75 -0
  7. package/kb/extra/api-gateway.md +164 -0
  8. package/kb/extra/api-gateway.zh.md +164 -0
  9. package/kb/extra/cookbook/adding-a-vendored-package.md +59 -0
  10. package/kb/extra/cookbook/adding-a-vendored-package.zh.md +59 -0
  11. package/kb/extra/cookbook/maintaining-dsh-code-review.md +64 -0
  12. package/kb/extra/cookbook/maintaining-dsh-code-review.zh.md +64 -0
  13. package/kb/extra/cookbook/responding-to-pr-review-on-a-stack.md +32 -0
  14. package/kb/extra/cookbook/responding-to-pr-review-on-a-stack.zh.md +32 -0
  15. package/kb/extra/defensive-patterns.md +33 -0
  16. package/kb/extra/defensive-patterns.zh.md +33 -0
  17. package/kb/extra/development.md +171 -0
  18. package/kb/extra/development.zh.md +171 -0
  19. package/kb/extra/event-producer-consumer.md +76 -0
  20. package/kb/extra/event-producer-consumer.zh.md +78 -0
  21. package/kb/extra/glossary.md +45 -0
  22. package/kb/extra/glossary.zh.md +45 -0
  23. package/kb/extra/graph-atlas.md +24 -0
  24. package/kb/extra/graph-atlas.zh.md +26 -0
  25. package/kb/extra/i18n/README.md +60 -0
  26. package/kb/extra/i18n/README.zh.md +60 -0
  27. package/kb/extra/i18n/style-samples.md +87 -0
  28. package/kb/extra/i18n/terminology.md +214 -0
  29. package/kb/extra/i18n/translation-prompt.md +263 -0
  30. package/kb/extra/i18n/translation-rules.md +69 -0
  31. package/kb/extra/i18n/translation-rules.zh.md +69 -0
  32. package/kb/extra/module-graph.md +1641 -0
  33. package/kb/extra/module-graph.zh.md +1643 -0
  34. package/kb/extra/postmortem/0001-acp-default-export-drops-inject.md +113 -0
  35. package/kb/extra/postmortem/0001-acp-default-export-drops-inject.zh.md +113 -0
  36. package/kb/extra/postmortem/0002-js-expression-disabled-filesystem-tools.md +47 -0
  37. package/kb/extra/postmortem/0002-js-expression-disabled-filesystem-tools.zh.md +47 -0
  38. package/kb/extra/postmortem/0003-web-agent-gui-feedback-loop.md +53 -0
  39. package/kb/extra/postmortem/0003-web-agent-gui-feedback-loop.zh.md +53 -0
  40. package/kb/extra/postmortem/0004-landlock-partial-notice-misclassified-child-failures.md +55 -0
  41. package/kb/extra/postmortem/0004-landlock-partial-notice-misclassified-child-failures.zh.md +55 -0
  42. package/kb/extra/postmortem/README.md +18 -0
  43. package/kb/extra/postmortem/README.zh.md +18 -0
  44. package/kb/extra/rescope.md +53 -0
  45. package/kb/extra/rescope.zh.md +53 -0
  46. package/kb/extra/subsystems/attachment.md +125 -0
  47. package/kb/extra/subsystems/attachment.zh.md +125 -0
  48. package/kb/extra/subsystems/extensions.md +364 -0
  49. package/kb/extra/subsystems/extensions.zh.md +364 -0
  50. package/kb/extra/subsystems/feedback.md +266 -0
  51. package/kb/extra/subsystems/feedback.zh.md +266 -0
  52. package/kb/extra/testing.md +49 -0
  53. package/kb/extra/testing.zh.md +49 -0
  54. package/kb/extra/web-styling.md +25 -0
  55. package/kb/extra/web-styling.zh.md +25 -0
  56. package/kb/meta/search-index.json +1328 -0
  57. package/kb/meta/site-pages.txt +168 -0
  58. package/kb/meta/source.json +13 -0
  59. package/kb/meta/topics.md +75 -0
  60. package/kb/site/develop/basic/config.md +108 -0
  61. package/kb/site/develop/basic/index.md +146 -0
  62. package/kb/site/develop/basic/publish.md +185 -0
  63. package/kb/site/develop/basic/tool.md +54 -0
  64. package/kb/site/develop/cordis-tutorial/01-first-plugin.md +95 -0
  65. package/kb/site/develop/cordis-tutorial/02-lifecycle-and-effects.md +98 -0
  66. package/kb/site/develop/cordis-tutorial/03-services.md +98 -0
  67. package/kb/site/develop/cordis-tutorial/04-events.md +144 -0
  68. package/kb/site/develop/cordis-tutorial/05-config.md +84 -0
  69. package/kb/site/develop/cordis-tutorial/06-composition-and-hmr.md +113 -0
  70. package/kb/site/develop/cordis-tutorial/07-into-the-harness.md +107 -0
  71. package/kb/site/develop/cordis-tutorial/index.md +62 -0
  72. package/kb/site/develop/framework/events.md +145 -0
  73. package/kb/site/develop/framework/index.md +139 -0
  74. package/kb/site/develop/framework/service.md +152 -0
  75. package/kb/site/develop/practice/index.md +157 -0
  76. package/kb/site/develop/practice/llm-adapter.md +190 -0
  77. package/kb/site/en/develop/basic/config.md +108 -0
  78. package/kb/site/en/develop/basic/index.md +146 -0
  79. package/kb/site/en/develop/basic/publish.md +185 -0
  80. package/kb/site/en/develop/basic/tool.md +54 -0
  81. package/kb/site/en/develop/cordis-tutorial/01-first-plugin.md +95 -0
  82. package/kb/site/en/develop/cordis-tutorial/02-lifecycle-and-effects.md +98 -0
  83. package/kb/site/en/develop/cordis-tutorial/03-services.md +98 -0
  84. package/kb/site/en/develop/cordis-tutorial/04-events.md +144 -0
  85. package/kb/site/en/develop/cordis-tutorial/05-config.md +84 -0
  86. package/kb/site/en/develop/cordis-tutorial/06-composition-and-hmr.md +113 -0
  87. package/kb/site/en/develop/cordis-tutorial/07-into-the-harness.md +107 -0
  88. package/kb/site/en/develop/cordis-tutorial/index.md +60 -0
  89. package/kb/site/en/develop/framework/events.md +145 -0
  90. package/kb/site/en/develop/framework/index.md +139 -0
  91. package/kb/site/en/develop/framework/service.md +150 -0
  92. package/kb/site/en/develop/practice/index.md +157 -0
  93. package/kb/site/en/develop/practice/llm-adapter.md +190 -0
  94. package/kb/site/en/guide/providers-custom-form.png +0 -0
  95. package/kb/site/en/guide/providers-models-page.png +0 -0
  96. package/kb/site/en/guide/providers.md +100 -0
  97. package/kb/site/en/guide/python-sdk.md +106 -0
  98. package/kb/site/en/guide/quickstart.md +32 -0
  99. package/kb/site/en/index.md +8 -0
  100. package/kb/site/en/reference/agent-lifecycle.md +86 -0
  101. package/kb/site/en/reference/capability-seams.md +475 -0
  102. package/kb/site/en/reference/config-catalog.md +3155 -0
  103. package/kb/site/en/reference/cookbook/adding-a-conversation-node.md +235 -0
  104. package/kb/site/en/reference/cookbook/adding-a-package.md +120 -0
  105. package/kb/site/en/reference/cookbook/adding-a-settings-card.md +102 -0
  106. package/kb/site/en/reference/cookbook/adding-a-tool.md +96 -0
  107. package/kb/site/en/reference/cookbook/adding-an-llm-adapter.md +45 -0
  108. package/kb/site/en/reference/cookbook/extension-cookbook.md +131 -0
  109. package/kb/site/en/reference/cordis-api/context.md +368 -0
  110. package/kb/site/en/reference/cordis-api/events.md +211 -0
  111. package/kb/site/en/reference/cordis-api/fiber.md +379 -0
  112. package/kb/site/en/reference/cordis-api/inherited.md +43 -0
  113. package/kb/site/en/reference/cordis-api/registry.md +156 -0
  114. package/kb/site/en/reference/cordis-api/service.md +106 -0
  115. package/kb/site/en/reference/cordis-primer.md +46 -0
  116. package/kb/site/en/reference/index.md +131 -0
  117. package/kb/site/en/reference/persistence-catalog.md +949 -0
  118. package/kb/site/en/reference/subsystems/approval.md +173 -0
  119. package/kb/site/en/reference/subsystems/client-modules.md +121 -0
  120. package/kb/site/en/reference/subsystems/code-runtime.md +194 -0
  121. package/kb/site/en/reference/subsystems/commands.md +190 -0
  122. package/kb/site/en/reference/subsystems/compaction.md +241 -0
  123. package/kb/site/en/reference/subsystems/core.md +1073 -0
  124. package/kb/site/en/reference/subsystems/credentials.md +136 -0
  125. package/kb/site/en/reference/subsystems/filesystem.md +498 -0
  126. package/kb/site/en/reference/subsystems/goal.md +280 -0
  127. package/kb/site/en/reference/subsystems/index.md +58 -0
  128. package/kb/site/en/reference/subsystems/invariants.md +91 -0
  129. package/kb/site/en/reference/subsystems/jobs.md +293 -0
  130. package/kb/site/en/reference/subsystems/llm-streaming.md +920 -0
  131. package/kb/site/en/reference/subsystems/lsp.md +205 -0
  132. package/kb/site/en/reference/subsystems/permission-presets.md +134 -0
  133. package/kb/site/en/reference/subsystems/persistence.md +388 -0
  134. package/kb/site/en/reference/subsystems/plan.md +90 -0
  135. package/kb/site/en/reference/subsystems/sandbox.md +221 -0
  136. package/kb/site/en/reference/subsystems/schedule.md +189 -0
  137. package/kb/site/en/reference/subsystems/scope.md +62 -0
  138. package/kb/site/en/reference/subsystems/session-projection.md +265 -0
  139. package/kb/site/en/reference/subsystems/session-query.md +498 -0
  140. package/kb/site/en/reference/subsystems/session-reference.md +111 -0
  141. package/kb/site/en/reference/subsystems/session-telemetry.md +197 -0
  142. package/kb/site/en/reference/subsystems/session-title.md +207 -0
  143. package/kb/site/en/reference/subsystems/session.md +852 -0
  144. package/kb/site/en/reference/subsystems/settings.md +313 -0
  145. package/kb/site/en/reference/subsystems/shell.md +306 -0
  146. package/kb/site/en/reference/subsystems/skills.md +334 -0
  147. package/kb/site/en/reference/subsystems/spill.md +120 -0
  148. package/kb/site/en/reference/subsystems/storage.md +232 -0
  149. package/kb/site/en/reference/subsystems/subagent.md +737 -0
  150. package/kb/site/en/reference/subsystems/subprocess.md +327 -0
  151. package/kb/site/en/reference/subsystems/system-prompt.md +210 -0
  152. package/kb/site/en/reference/subsystems/terminal.md +187 -0
  153. package/kb/site/en/reference/subsystems/token-meter.md +93 -0
  154. package/kb/site/en/reference/subsystems/tools.md +723 -0
  155. package/kb/site/en/reference/subsystems/typert.md +339 -0
  156. package/kb/site/en/reference/subsystems/user-questions.md +181 -0
  157. package/kb/site/en/reference/subsystems/web-server.md +111 -0
  158. package/kb/site/en/reference/subsystems/web.md +202 -0
  159. package/kb/site/en/reference/subsystems/workflow.md +281 -0
  160. package/kb/site/en/reference/subsystems/workspace.md +231 -0
  161. package/kb/site/en/reference/tool-catalog.md +1877 -0
  162. package/kb/site/en/reference/tool-execution-pipeline.md +66 -0
  163. package/kb/site/guide/providers-custom-form.zh.png +0 -0
  164. package/kb/site/guide/providers-models-page.zh.png +0 -0
  165. package/kb/site/guide/providers.md +100 -0
  166. package/kb/site/guide/python-sdk.md +106 -0
  167. package/kb/site/guide/quickstart.md +32 -0
  168. package/kb/site/index.md +8 -0
  169. package/kb/site/reference/agent-lifecycle.md +86 -0
  170. package/kb/site/reference/capability-seams.md +475 -0
  171. package/kb/site/reference/config-catalog.md +3154 -0
  172. package/kb/site/reference/cookbook/adding-a-conversation-node.md +235 -0
  173. package/kb/site/reference/cookbook/adding-a-package.md +120 -0
  174. package/kb/site/reference/cookbook/adding-a-settings-card.md +102 -0
  175. package/kb/site/reference/cookbook/adding-a-tool.md +98 -0
  176. package/kb/site/reference/cookbook/adding-an-llm-adapter.md +45 -0
  177. package/kb/site/reference/cookbook/extension-cookbook.md +133 -0
  178. package/kb/site/reference/cordis-api/context.md +368 -0
  179. package/kb/site/reference/cordis-api/events.md +211 -0
  180. package/kb/site/reference/cordis-api/fiber.md +379 -0
  181. package/kb/site/reference/cordis-api/inherited.md +43 -0
  182. package/kb/site/reference/cordis-api/registry.md +156 -0
  183. package/kb/site/reference/cordis-api/service.md +106 -0
  184. package/kb/site/reference/cordis-primer.md +52 -0
  185. package/kb/site/reference/index.md +135 -0
  186. package/kb/site/reference/persistence-catalog.md +949 -0
  187. package/kb/site/reference/subsystems/approval.md +173 -0
  188. package/kb/site/reference/subsystems/client-modules.md +121 -0
  189. package/kb/site/reference/subsystems/code-runtime.md +194 -0
  190. package/kb/site/reference/subsystems/commands.md +190 -0
  191. package/kb/site/reference/subsystems/compaction.md +241 -0
  192. package/kb/site/reference/subsystems/core.md +1081 -0
  193. package/kb/site/reference/subsystems/credentials.md +136 -0
  194. package/kb/site/reference/subsystems/filesystem.md +498 -0
  195. package/kb/site/reference/subsystems/goal.md +280 -0
  196. package/kb/site/reference/subsystems/index.md +58 -0
  197. package/kb/site/reference/subsystems/invariants.md +91 -0
  198. package/kb/site/reference/subsystems/jobs.md +293 -0
  199. package/kb/site/reference/subsystems/llm-streaming.md +926 -0
  200. package/kb/site/reference/subsystems/lsp.md +205 -0
  201. package/kb/site/reference/subsystems/permission-presets.md +134 -0
  202. package/kb/site/reference/subsystems/persistence.md +388 -0
  203. package/kb/site/reference/subsystems/plan.md +90 -0
  204. package/kb/site/reference/subsystems/sandbox.md +221 -0
  205. package/kb/site/reference/subsystems/schedule.md +189 -0
  206. package/kb/site/reference/subsystems/scope.md +62 -0
  207. package/kb/site/reference/subsystems/session-projection.md +265 -0
  208. package/kb/site/reference/subsystems/session-query.md +498 -0
  209. package/kb/site/reference/subsystems/session-reference.md +111 -0
  210. package/kb/site/reference/subsystems/session-telemetry.md +197 -0
  211. package/kb/site/reference/subsystems/session-title.md +207 -0
  212. package/kb/site/reference/subsystems/session.md +854 -0
  213. package/kb/site/reference/subsystems/settings.md +313 -0
  214. package/kb/site/reference/subsystems/shell.md +306 -0
  215. package/kb/site/reference/subsystems/skills.md +334 -0
  216. package/kb/site/reference/subsystems/spill.md +120 -0
  217. package/kb/site/reference/subsystems/storage.md +232 -0
  218. package/kb/site/reference/subsystems/subagent.md +739 -0
  219. package/kb/site/reference/subsystems/subprocess.md +327 -0
  220. package/kb/site/reference/subsystems/system-prompt.md +210 -0
  221. package/kb/site/reference/subsystems/terminal.md +187 -0
  222. package/kb/site/reference/subsystems/token-meter.md +93 -0
  223. package/kb/site/reference/subsystems/tools.md +723 -0
  224. package/kb/site/reference/subsystems/typert.md +339 -0
  225. package/kb/site/reference/subsystems/user-questions.md +181 -0
  226. package/kb/site/reference/subsystems/web-server.md +111 -0
  227. package/kb/site/reference/subsystems/web.md +202 -0
  228. package/kb/site/reference/subsystems/workflow.md +281 -0
  229. package/kb/site/reference/subsystems/workspace.md +231 -0
  230. package/kb/site/reference/tool-catalog.md +1880 -0
  231. package/kb/site/reference/tool-execution-pipeline.md +66 -0
  232. package/package.json +40 -0
  233. package/scripts/rebuild-index.mjs +88 -0
  234. package/skills/dsh-plugin-dev-kb.md +66 -0
@@ -0,0 +1,852 @@
1
+ ---
2
+ editSource: "docs/subsystems/session.md"
3
+ outline: [2,3]
4
+ ---
5
+
6
+ # Sessions
7
+
8
+ 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).
9
+
10
+ Source: [`packages/core/session/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/types.ts)
11
+
12
+ ## `SessionEventMap` — the event vocabulary
13
+
14
+ 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.
15
+
16
+ ```ts type-equiv
17
+ /** A user-role specialization of the one shared message representation. */
18
+ interface UserMessage extends Message {
19
+ readonly role: 'user'
20
+ }
21
+ ```
22
+
23
+ ```ts type-equiv
24
+ /**
25
+ * The merge-extensible, append-only source of truth for an agent interaction.
26
+ * Message history is derived from this log. Every event is lossless JSON and
27
+ * sequence numbers stay contiguous, including raw chunks, so persistence can
28
+ * store the canonical log verbatim.
29
+ */
30
+ interface SessionEventMap {
31
+ /**
32
+ * Opens turn `turn` before the loop claims queued input or runs pre-step.
33
+ * Rejection, empty input, cancellation, or failure may close it with no
34
+ * step; otherwise the following identified `user/message` event or batch
35
+ * records the messages entering the step.
36
+ */
37
+ 'turn/start': { turn: number }
38
+ /**
39
+ * Closes turn `turn` with the {@link TurnEndReason} that ended it. A turn
40
+ * with no entered step has no `step/start` or `step/end`. The loop does not await a
41
+ * flush at turn boundaries: `dsh-session-checkpoint-policy` owns the
42
+ * per-request durability checkpoint, and consumers that read storage after
43
+ * `whenIdle()` flush themselves. Success commits the turn; rejection is
44
+ * reported live and does not prevent later work.
45
+ */
46
+ 'turn/end': { turn: number; reason: TurnEndReason }
47
+ /** Opens step `step` of turn `turn` — one model call plus the tool executions it requested. */
48
+ 'step/start': { turn: number; step: number }
49
+ /** Closes step `step` of turn `turn`. */
50
+ 'step/end': { turn: number; step: number }
51
+ /**
52
+ * A user-role message on the model-visible surface: a direct human prompt
53
+ * (the queued message claimed for this turn), a synthetic `agent.inject()`
54
+ * context (file-change notices, subdir AGENTS.md, skill content, cron
55
+ * notifications, …), or an entered goal continuation round. All three
56
+ * project their `content` verbatim; `source` tells them apart.
57
+ */
58
+ 'user/message': UserMessage
59
+ /** Raw stream chunk — token-level replay fidelity. */
60
+ 'assistant/chunk': { turn: number; step: number; chunk: StreamChunk }
61
+ /**
62
+ * Assembled assistant message for one step (derived history uses this).
63
+ * Carries the step's `usage` when the adapter reported token accounting, so
64
+ * the model output and its accounting travel together (there is no separate
65
+ * usage record). `usage` is absent when the adapter reported none.
66
+ */
67
+ 'assistant/message': { turn: number; step: number; message: AssistantMessage; usage?: TokenUsage }
68
+ /**
69
+ * The model requested one tool invocation: `name` with the raw `arguments`
70
+ * JSON string exactly as the model produced it (unparsed). `callId` pairs the
71
+ * call with its `tool/result`.
72
+ */
73
+ 'tool/call': { turn: number; step: number; callId: CallId; name: string; arguments: string }
74
+ /**
75
+ * A completed tool call's model-facing result, optional internal failure
76
+ * identity, and optional tool-private `meta` presentation payload. `meta` is
77
+ * opaque to the core (the producing tool owns its shape and reads it back in
78
+ * `presentResult`) but MUST be JSON-serializable: `Session.append`
79
+ * runtime-validates all event data with `isJsonValue`, so a non-serializable
80
+ * `meta` is rejected at the source, and the durable log reproduces the
81
+ * identical card on replay. Absent
82
+ * unless the tool attaches one (e.g. `dsh-tool-fs` carries its result-time
83
+ * contextual diff here).
84
+ */
85
+ 'tool/result': {
86
+ turn: number
87
+ step: number
88
+ message: ToolResultMessage
89
+ error?: { name: string; code: string }
90
+ meta?: JsonValue
91
+ }
92
+ /** Whole-list snapshot; latest write wins on replay. Log-only UI state; never derived history. */
93
+ 'todo/write': { todos: TodoItem[] }
94
+ /**
95
+ * Full header for the next request, appended inside its step before dispatch.
96
+ * It is log-only; the latest snapshot reconstructs the request header.
97
+ */
98
+ 'request/header': { header: EpochHeader; reason: RequestHeaderReason }
99
+ /**
100
+ * Route metadata for the next request, logged only when the route or capacity
101
+ * changes. It does not participate in request reconstruction or header equality.
102
+ */
103
+ 'request/context': RequestContext
104
+ /**
105
+ * Marks the end of a constructor seed. Events before it have smaller seq
106
+ * values and came from the seed (resume, fork, or replay); this lifecycle
107
+ * produced none of them. This log-only event is the durable projection of
108
+ * {@link Session.firstLiveSeq}. Its payload is empty — position and `time`
109
+ * carry the meaning.
110
+ *
111
+ * Locate the LAST one in stored history. A seed already ending in one is not
112
+ * re-marked, so reopening an untouched session does not grow its log per
113
+ * pickup and the event need not be at the current `firstLiveSeq`.
114
+ *
115
+ * `Session`'s constructor is the only legitimate writer. The invariant
116
+ * companion deliberately constrains nothing here, so a plugin appending one
117
+ * would silently classify every live bracket before it as seed history.
118
+ *
119
+ * An owner of a standalone open/close bracket (`compaction/start` …
120
+ * `compaction/end`) reads it because seed history and live work are otherwise
121
+ * byte-identical: an unmatched opening marker before this event belongs to
122
+ * an ended lifecycle, whatever ended it. NOT a liveness signal about other
123
+ * writers — a concurrently live session holds its own boundary elsewhere,
124
+ * so tolerating concurrent writers needs a signal beyond the log.
125
+ */
126
+ 'session/end-seed': Record<string, never>
127
+ }
128
+ ```
129
+
130
+ `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.
131
+
132
+ ### `TodoItem` — one todo-list entry
133
+
134
+ The unit of the `todo/write` event's whole-list snapshot. Deliberately minimal — a `content` line and a three-state `status` (no id, priority, or `activeForm`): the list is replaced wholesale on every write, so entries need no stable identity. See the [todo_write Agent Note](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/feature/2026-06-29-todo-write-tool.md).
135
+
136
+ ```ts type-equiv
137
+ /**
138
+ * One entry in an agent's todo list — the unit of the `todo/write`
139
+ * {@link SessionEventMap} event's whole-list snapshot.
140
+ *
141
+ * Deliberately minimal: a human-readable `content` line and a three-state
142
+ * `status`. No id, priority, or `activeForm` — the list is replaced wholesale
143
+ * on every write (last-write-wins), so entries need no stable identity. The
144
+ * three statuses describe the complete portable lifecycle needed by model and
145
+ * UI consumers.
146
+ */
147
+ interface TodoItem {
148
+ /** What this task is — a short imperative line shown in the UI. */
149
+ content: string
150
+ /** Lifecycle state. `in_progress` marks a task being worked now; parallel work may mark several. */
151
+ status: 'pending' | 'in_progress' | 'completed'
152
+ }
153
+ ```
154
+
155
+ <a id="the-request-header-event-requestheader"></a>
156
+
157
+ ### The request header event: `request/header`
158
+
159
+ The request envelope — the `EpochHeader` (call config + markers for adapter-supplied defaults + rendered system prompt + assembled tool schemas) — is logged session state, so every conversation request is a pure function of the log (the reconstructability Agent Note). A full `request/header` snapshot with reason `'initial'` or `'resume'` records each loop-instance boundary; a later changed request records another full snapshot with reason `'change'`. `foldRequestHeader(events)` reconstructs the header by selecting the latest snapshot. The event is not a `SurfaceEventType`: it produces no LLM message.
160
+
161
+ ```ts type-equiv
162
+ /**
163
+ * Logged request state outside derived history: call config, system prompt, and
164
+ * tools. The latest full `request/header` snapshot reconstructs it; canonical
165
+ * empty optional fields are absent.
166
+ */
167
+ interface EpochHeader {
168
+ /** The conversation's call configuration (provider, model, reasoning effort, and sampling scalars). */
169
+ config: LlmCallConfig
170
+ /** Effective config fields materialized from the exact adapter rather than proposed by a caller. */
171
+ adapterDefaults?: LlmCallConfigAdapterDefaults
172
+ /** Rendered system prompt text; absent for a system-less request. */
173
+ system?: string
174
+ /** Assembled tool schemas; absent for a tool-less request. */
175
+ tools?: ToolSchema[]
176
+ }
177
+ ```
178
+
179
+ Canonical form represents an empty system prompt or tool list as an absent field, matching how requests are built. Legacy v0 logs containing the legacy `request/header-delta` event or its full-snapshot `fallback` reason are rejected at seed, append, and persistence-load boundaries rather than replayed incompletely.
180
+
181
+ ### The route capacity event: `request/context`
182
+
183
+ 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, or capacity differs from the previous record. It stays outside `EpochHeader` because that type is the reconstruction contract compared field-wise by `headerEquals`: capacity describes a route, not a request input, so folding it in would let a capacity change register as a request-envelope `change` and would pull adapter metadata into the loop's reconstruction invariant. Like `request/header`, it is not a `SurfaceEventType` and produces no LLM message. `session.requestContext()` folds the latest record incrementally. A route whose adapter advertises no capacity is recorded with `contextWindow` absent, so the new record clears an older route's capacity.
184
+
185
+ ```ts type-equiv
186
+ /** Registration-bound metadata for one resolved model route. */
187
+ interface RequestContext {
188
+ /** Registered provider route the metadata belongs to. */
189
+ provider: string
190
+ /** Provider-owned model id the metadata belongs to. */
191
+ model: string
192
+ /** Maximum combined request and response context in tokens, when advertised. */
193
+ contextWindow?: number
194
+ }
195
+ ```
196
+
197
+ ## `SessionEvent<T>` — one log entry
198
+
199
+ 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.
200
+
201
+ ```ts type-equiv
202
+ /**
203
+ * One immutable entry in the session log.
204
+ *
205
+ * A proper discriminated union over `type` (not independent `type`/`data`
206
+ * unions), so `switch (event.type)` narrows `event.data` without casts.
207
+ *
208
+ * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional:
209
+ * they only exist on {@link SurfaceEventType} variants (`user/message`,
210
+ * `assistant/message`, `tool/result`).
211
+ * Non-surface events (boundary markers, chunks, usage, errors) never carry
212
+ * surface metadata — the compiler enforces this at `Session.append()`
213
+ * call sites.
214
+ */
215
+ type SessionEvent<T extends SessionEventType = SessionEventType> = {
216
+ [K in SessionEventType]: {
217
+ type: K
218
+ /** Monotonic sequence number within the session. */
219
+ seq: number
220
+ /** Unix epoch milliseconds. */
221
+ time: number
222
+ data: SessionEventMap[K]
223
+ /**
224
+ * Marks an event a reader may safely skip when it does not recognize
225
+ * `type`. Absent means required: a reader meeting an unrecognized type
226
+ * without this marker MUST refuse to reconstruct the session instead of
227
+ * silently dropping the event, because an unrecognized required event may
228
+ * change how the rest of the log is interpreted. A writer sets `true` only
229
+ * on purely informational records whose loss cannot affect reconstruction;
230
+ * defaulting to required means a forgotten marker over-refuses (an
231
+ * inconvenience) rather than silently resuming a gutted session.
232
+ */
233
+ ignorable?: true
234
+ } & (K extends SurfaceEventType ? {
235
+ /**
236
+ * Seq numbers of earlier events that this event cites as sources
237
+ * (e.g. the `assistant/chunk` seqs that built an `assistant/message`,
238
+ * or the surface nodes shadowed by a compaction replace node). An
239
+ * `assistant/message` may carry a present empty array for a known empty
240
+ * provider stream; when the field is absent, the event does not record which
241
+ * earlier events produced the message.
242
+ */
243
+ sourceEventSeqs?: number[]
244
+ /** How this event entered the surface; absent for non-surface events. */
245
+ surfaceOp?: SurfaceOp
246
+ } : object)
247
+ }[T]
248
+ ```
249
+
250
+ `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`.
251
+
252
+ For `assistant/message`, a present `sourceEventSeqs: []` is a complete known-empty provider stream, while a legacy or foreign event with no field does not record which earlier events produced the message. The loop writes the field for every successful model call; every other surface event requires a non-empty list when the field is present.
253
+
254
+ ## Surface types
255
+
256
+ The three message-producing types (`SurfaceEventType` — `user/message`, `assistant/message`, `tool/result`) carry surface metadata declaring how they join the ordered derived surface. 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).
257
+
258
+ ### `SurfaceEventType` — the message-producing subset of event types
259
+
260
+ ```ts type-equiv
261
+ /**
262
+ * The subset of {@link SessionEventType} values whose events produce LLM
263
+ * messages and are eligible to appear on the ordered surface. Only these
264
+ * event types may carry {@link SurfaceOp} and {@link SessionEvent.sourceEventSeqs}.
265
+ */
266
+ type SurfaceEventType =
267
+ | 'user/message'
268
+ | 'assistant/message'
269
+ | 'tool/result'
270
+ ```
271
+
272
+ ### `SurfaceOp` — how an event entered the surface
273
+
274
+ ```ts type-equiv
275
+ /**
276
+ * How a session event entered the ordered surface. Only valid on
277
+ * {@link SurfaceEventType} events.
278
+ *
279
+ * - `'append'`: added to the tail — normal path for user/assistant/tool
280
+ * messages.
281
+ * - `{ op: 'replace', start, end }`: replaces surface nodes from `start`
282
+ * (inclusive) through `end` (inclusive) with this node. Both must exist as
283
+ * surface nodes in the current surface. `start === end` replaces a single
284
+ * node. The node's {@link SessionEvent.sourceEventSeqs} must include every
285
+ * shadowed surface node. Used by compaction; any surface-replacing producer
286
+ * may use it.
287
+ */
288
+ type SurfaceOp =
289
+ | 'append'
290
+ | { op: 'replace'; start: number; end: number }
291
+ ```
292
+
293
+ `'append'` is the normal tail-append path. `replace` shadows surface entries from `start` through `end` inclusive (both must be valid surface seqs; `start === end` replaces a single entry) and inserts the new event in their place.
294
+
295
+ ### `SurfaceIntent` — the parameter to `session.append()`
296
+
297
+ ```ts type-equiv
298
+ /**
299
+ * Surface placement and cited source-event seqs for {@link Session.append}. Required on
300
+ * message-producing events and forbidden on log-only events.
301
+ */
302
+ interface SurfaceIntent {
303
+ surfaceOp: SurfaceOp
304
+ /**
305
+ * Complete set of known source-event seqs. `assistant/message` may use a
306
+ * present empty array for a known empty provider stream; when the field is
307
+ * absent, the event does not record which earlier events produced the message.
308
+ * Other surface events require a non-empty set when this field is present.
309
+ */
310
+ sourceEventSeqs?: number[]
311
+ }
312
+ ```
313
+
314
+ 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.
315
+
316
+ Only `assistant/message` may carry a present empty `sourceEventSeqs`; when the field is absent, the event does not record which earlier events produced the message, and the provider may still have emitted chunks.
317
+
318
+ ### `SessionSurface` — the live readonly surface projection
319
+
320
+ `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.
321
+
322
+ `SurfaceManager(log, baseSeq?)` 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.
323
+
324
+ ```ts type-equiv
325
+ /** Readonly live projection of the message-producing session events. */
326
+ interface SessionSurface {
327
+ /** Current surface event sequences in model-visible order. */
328
+ readonly nodes: readonly number[]
329
+ /** Monotonic count of committed positional replacements. */
330
+ readonly replaceGeneration: number
331
+ }
332
+ ```
333
+
334
+ ### `SurfaceFoldReplacement` and `SurfaceFoldResult` — a complete surface replay
335
+
336
+ `foldSurface(events)` 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.
337
+
338
+ ```ts type-equiv
339
+ /** One replacement operation observed while folding a session surface. */
340
+ interface SurfaceFoldReplacement {
341
+ /** Seq of the event that replaced the prior surface range. */
342
+ seq: number
343
+ /** Declared inclusive start seq of the replaced surface range. */
344
+ start: number
345
+ /** Declared inclusive end seq of the replaced surface range. */
346
+ end: number
347
+ /** Actual surface entries removed by the operation, in surface order. */
348
+ shadowedSeqs: number[]
349
+ }
350
+ ```
351
+
352
+ ```ts type-equiv
353
+ /** Complete result of replaying the surface operations in a session log. */
354
+ interface SurfaceFoldResult {
355
+ /** Current surface event sequences in model-visible order. */
356
+ nodes: number[]
357
+ /** Replacement operations in event order. */
358
+ replacements: SurfaceFoldReplacement[]
359
+ }
360
+ ```
361
+
362
+ ## `Session` public API
363
+
364
+ 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).
365
+
366
+ ```ts public-api
367
+ /**
368
+ * An event-sourced session: an append-only log of {@link SessionEvent}s.
369
+ *
370
+ * Plain class (not a Service) — create live instances via
371
+ * `ctx.sessions.create()` and detached instances via {@link create}.
372
+ * Seeding with an existing event log replays/forks a session.
373
+ * @typert object
374
+ */
375
+ declare class Session {
376
+ /** The ordered surface over this session's event log. */
377
+ get surface(): SessionSurface;
378
+ /**
379
+ * Detached, deep-frozen creation metadata (format version, cwd, lineage,
380
+ * seed boundary). Supplied by the store via `ctx.sessions.create()`. When a
381
+ * `Session` is created without a store-owned header, a minimal header is
382
+ * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
383
+ * `session.header` is always present. Kept out of the event log — it is a
384
+ * storage concern, not replayable conversation state.
385
+ */
386
+ readonly header: SessionHeader;
387
+ /** The session identity, derived from its durable header's single copy. */
388
+ get id(): SessionId;
389
+ /**
390
+ * The first seq appended IN THIS PROCESS: the length of the constructor
391
+ * seed (0 without one). Events with smaller seq values entered through
392
+ * construction — replay, fork, or resume — and were never published on the
393
+ * `session/event` firehose (constructor seeds do not emit), so consumers
394
+ * that replay the log as a publication substitute (telemetry adoption)
395
+ * start here. Distinct from `header.seedLength`, the DURABLE fork-lineage
396
+ * boundary: a resumed session's constructor seed is its full stored log,
397
+ * while its header keeps the original fork value — this field is the
398
+ * in-process construction fact.
399
+ *
400
+ * Not persisted itself: a seeded session projects it into the log as the
401
+ * `session/end-seed` event, which is what a consumer reading STORED history
402
+ * reads. Locate the LAST such event, not necessarily one at this seq — a
403
+ * seed already ending in one is not re-marked, so reopening an untouched
404
+ * session leaves that event at a smaller seq than `firstLiveSeq`. Prefer
405
+ * this field in-process: it is exact before the marker reaches storage.
406
+ *
407
+ * When this lifecycle appends the marker, it occupies this seq before the
408
+ * store attaches and therefore does not publish either. Otherwise this seq
409
+ * holds an ordinary published write.
410
+ */
411
+ readonly firstLiveSeq: number;
412
+ /**
413
+ * Create a detached session by validating and snapshotting borrowed seed
414
+ * events and storage metadata.
415
+ * @param id - session identity.
416
+ * @param seed - optional borrowed replay or fork events.
417
+ * @param header - optional borrowed storage metadata.
418
+ * @returns a detached session.
419
+ */
420
+ static create(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader): Session;
421
+ /**
422
+ * Restore a detached session by taking ownership of fresh persistence values.
423
+ * The storage format, event envelopes, sequence continuity, surface transitions,
424
+ * and header fields are validated before the restored objects are frozen.
425
+ * @param id - restored session identity.
426
+ * @param seed - fresh detached events whose ownership is transferred.
427
+ * @param header - fresh detached metadata whose ownership is transferred.
428
+ * @returns a restored detached session.
429
+ */
430
+ static fromRestore(id: SessionId, seed: readonly SessionEvent[], header: SessionHeader): Session;
431
+ /**
432
+ * An immutable snapshot of the append-only event log. The snapshot is reused
433
+ * until the next append; a previously returned array does not grow later.
434
+ * Events and their nested data are deep-frozen at acceptance, so neither a
435
+ * cast nor ordinary JavaScript can rewrite durable history.
436
+ */
437
+ get events(): readonly SessionEvent[];
438
+ /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
439
+ get seq(): number;
440
+ /**
441
+ * Append one typed event to the log and synchronously notify observers via
442
+ * the store-owned, module-private publication hooks. The hot path never blocks
443
+ * on I/O — persistence plugins buffer asynchronously. Once the event enters
444
+ * the log, the append is committed: observer failures are logged and
445
+ * contained per listener, so they do not change the return value or prevent
446
+ * later listeners from observing the same accepted event.
447
+ *
448
+ * @param type - The event type (key of {@link SessionEventMap}).
449
+ * @param data - The event payload; must be JSON-serializable.
450
+ * @param opts - Surface metadata: `surfaceOp` controls how the event enters
451
+ * the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier
452
+ * events this one derives from. REQUIRED for
453
+ * {@link SurfaceEventType} events (every message-producing event must
454
+ * declare how it joins the surface, the sole source of derived model
455
+ * history) and
456
+ * rejected by the compiler for non-surface types like `turn/start` or
457
+ * `assistant/chunk`.
458
+ * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
459
+ * `data` that entered the log, so reading `event.data` back sees the logged
460
+ * value, never the caller's still-mutable input.
461
+ * @throws if `data` or surface metadata is not losslessly JSON-serializable
462
+ * (BigInt, function, symbol, undefined, negative zero, non-finite number,
463
+ * circular reference, sparse array, or an exotic object such as
464
+ * Map/Set/Date/class instance), or when the candidate violates the
465
+ * canonical surface contract (marker shape and eligibility, unique
466
+ * earlier source-event references, positional replacement validity, and complete
467
+ * shadowed-node coverage). One recursive pass reads, validates, and
468
+ * copies each nested value once, so a stateful getter cannot supply one value
469
+ * to validation and another to storage. The event log is the durable source
470
+ * of truth, so a bad event fails at the append site rather than later during
471
+ * a backend flush. A synchronous internal dispatch validation failure or an
472
+ * append reentered while this acceptance/publication boundary is open also
473
+ * rejects before the log changes.
474
+ */
475
+ append<T extends SessionEventType>(
476
+ type: T,
477
+ data: SessionEventMap[T],
478
+ ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent] : []
479
+ ): SessionEvent<T>;
480
+ /**
481
+ * The {@link EpochHeader} in force after the log's last header event — the
482
+ * header the NEXT request will be compared against — or undefined before
483
+ * the first `request/header` snapshot. The live, incrementally-maintained
484
+ * form of `foldRequestHeader(session.events)`: each header event is folded
485
+ * once, when first seen, so a per-step read costs O(new events).
486
+ * @returns the folded header, or undefined when no header event exists yet.
487
+ */
488
+ requestHeader(): EpochHeader | undefined;
489
+ /**
490
+ * Return the latest resolved route metadata, or `undefined` before the first
491
+ * `request/context` event. Each event is folded once.
492
+ * @returns the latest immutable route metadata.
493
+ */
494
+ requestContext(): RequestContext | undefined;
495
+ /**
496
+ * Derive the LLM message history by walking the ordered sequences of
497
+ * message-producing events maintained by `surfaceOp` markers. The
498
+ * surface is the single source of derived history: every message-producing
499
+ * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
500
+ * turn boundary) is correctly absent, and a compaction `replace` deletes the
501
+ * shadowed nodes from the derivation. The projection rules are
502
+ * {@link deriveEventMessage}, folded per node.
503
+ *
504
+ * CACHED: each surface node is projected exactly once, when first seen — a
505
+ * call costs O(new nodes), and a surface rewrite (a `replace`;
506
+ * {@link SessionSurface.replaceGeneration}) rebuilds. The returned array is
507
+ * a fresh snapshot per call (later appends never grow an array a caller
508
+ * already holds); the `Message` objects in it are SHARED and **deep-frozen**.
509
+ * Their content reuses the already frozen durable event data, so the cache
510
+ * needs no second deep clone and consumers still cannot mutate the log.
511
+ * @returns a fresh array of the shared, frozen derived history.
512
+ */
513
+ deriveMessages(): Message[];
514
+ /**
515
+ * Instance face of the pure per-node `deriveEventMessage` export from
516
+ * `surface.ts`.
517
+ * @param event - the event to project.
518
+ * @returns the derived message, or null when the event produces none.
519
+ */
520
+ deriveEventMessage(event: SessionEvent): Message | null;
521
+ }
522
+ ```
523
+
524
+ ## Derived history: `deriveMessages()` and `deriveEventMessage()`
525
+
526
+ `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 and the dev invariant project a log prefix with exactly the same rules and cannot disagree with the cache. The projection rules:
527
+
528
+ - `user/message` → a user message carrying exact `content`; an optional envelope remains log-only display metadata.
529
+ - `assistant/message` → an assistant message with the provider and model that produced it plus optional adapter-private replay state. Raw `assistant/chunk` events are replay/UI data and are **skipped** in derivation (the assembled message is authoritative). 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 usage, provider, and model, but a content-less assistant turn must not enter the provider transcript.
530
+ - `tool/result` → a user message carrying a `tool-result` block.
531
+ - `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.
532
+
533
+ Everything else (`turn/*`, `step/*`, plugin-owned `llm/retry`) is structural and does not project into a message. Token accounting reads per-step `assistant/chunk { type: 'usage' }` records and treats `assistant/message.usage` as the committed-step fallback when no usage chunk exists; failed model-request attempts have no assistant message, so their usage chunk is the durable accounting record. Because this unreleased format intentionally has no compatibility promise, seed/load validation rejects request headers and assistant messages that omit provider/model instead of guessing a route for historical data.
534
+
535
+ ## Live-session fork API
536
+
537
+ `ctx.sessions.create(id, { seed, meta })` is the low-level replay/fork primitive. For ordinary live-session forks, `SessionStore` exposes one policy API:
538
+
539
+ - `fork(source, boundary?, childSessionId?)` accepts a live `Session` object or live `SessionId`, selects source events through the inclusive `boundary` seq (default: current last event), requires the selected prefix to end outside an open turn, then creates a live child session with deep-cloned seed events plus child metadata (`parentSession`, `seedLength`, and inherited `cwd`).
540
+
541
+ 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. Broader execution-relation sanity stays in the existing `dsh-invariants` plugin and persistence repair path rather than being duplicated in `fork()`. `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.
542
+
543
+ ## Why a turn ended: `TurnEndReasonMap`
544
+
545
+ `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.
546
+
547
+ ```ts type-equiv
548
+ /** Durable cancellation cause, including imports whose original coarse record carried no cause. */
549
+ type TurnEndCancelCause = AgentCancelCause | { readonly kind: 'legacy' }
550
+ ```
551
+
552
+ ```ts type-equiv
553
+ /**
554
+ * Why a turn ended. Merge-extensible sum type.
555
+ */
556
+ interface TurnEndReasonMap {
557
+ completed: { kind: 'completed' }
558
+ /** A cancellation request interrupted the live turn. */
559
+ aborted: { kind: 'aborted'; reason: TurnEndCancelCause }
560
+
561
+ blocked: { kind: 'blocked' }
562
+ /**
563
+ * The turn failed. `error` is always a structured failure: the `LlmError`
564
+ * facts verbatim, or `{ message: errorChain(error), code: 'UNKNOWN' }`
565
+ * flattened from any other error.
566
+ */
567
+ error: { kind: 'error'; error: LlmFailure }
568
+ /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */
569
+ 'max-tokens': { kind: 'max-tokens' }
570
+ /**
571
+ * A persistence backend closed a crash-orphaned turn on reload. The loop never
572
+ * emits this marker, and the events recorded before the crash remain intact.
573
+ */
574
+ interrupted: { kind: 'interrupted' }
575
+ }
576
+ ```
577
+
578
+ `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. `interrupted` is the one reason no loop emits—it is synthesized by crash recovery (see [persistence.md](./persistence.md)). The map is merge-extensible.
579
+
580
+ ## Execution enclosure and standalone events
581
+
582
+ 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)`.
583
+
584
+ The optional `dsh-session/invariant` companion enforces the relations owned by core: turn and step numbering, execution-event enclosure, and same-step tool call/result pairing. 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).
585
+
586
+ ## The end-seed boundary: `session/end-seed`
587
+
588
+ A seeded session — resume, fork, or replay — appends this log-only event immediately after its constructor seed, as its first live write. Events before it have smaller seq values and came from the seed. It is the durable projection of `firstLiveSeq`: that field answers where this lifecycle's writes start for a consumer holding the object, while the event answers the same question for one holding only stored bytes. The payload is empty, so position and `time` carry the whole meaning, and it produces no message. `Session`'s constructor is the only legitimate writer.
589
+
590
+ An explicitly supplied empty seed writes `session/end-seed` at seq 0, which distinguishes an empty resumed session from a fresh one. A seed already ending in `session/end-seed` is not re-marked, so reopening an untouched session does not grow its log per pickup. Locate the LAST `session/end-seed` in stored history rather than assuming one exists at `firstLiveSeq`: after a pickup with no work, the event has a smaller seq than the next lifecycle's `firstLiveSeq`.
591
+
592
+ 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/*`.
593
+
594
+ 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.
595
+
596
+ ## Plugin-contributed log-only events
597
+
598
+ 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, and enforces any relation in its own invariant companion. The generated [persistence log event catalog](../persistence-catalog.md) enumerates every core and plugin-contributed event with its payload, surface badge, and declaration site; the compaction seam's `compaction/*` semantics are discussed on [compaction.md](./compaction.md).
599
+
600
+ 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 Node cookbook](../cookbook/adding-a-conversation-node.md).
601
+
602
+ 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 (see [the hook-bridges Agent Note](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/feature/2026-06-30-hook-bridges.md)).
603
+
604
+ ## Durability contract
605
+
606
+ What a persistence backend relies on: the durable log persists every event losslessly, **including** `assistant/chunk` — `seq` must stay contiguous, so chunks cannot be filtered out of the canonical log. A backend may choose its own storage encoding for an event batch as long as `load` returns the exact appended events (the JSONL backend's default packed chunk rows are such an encoding — 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.events` 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.
607
+
608
+ The backends that consume this contract are on [persistence.md](./persistence.md).
609
+
610
+ <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
611
+
612
+ <a id="cordis-surface"></a>
613
+
614
+ ## Cordis API
615
+
616
+ 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`) — this section is byte-identical in both language sides of the page. 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).
617
+
618
+ <a id="ctxsessions--sessionstore"></a>
619
+
620
+ ### `ctx.sessions` — `SessionStore`
621
+
622
+ In-memory session store (`ctx.sessions`).
623
+
624
+ Persistence is intentionally not implemented here — persistence plugins subscribe to `session/event` and flush on `session/flush` / dispose.
625
+
626
+ ```ts cordis-catalog
627
+ /**
628
+ * Create a session owned by the calling fiber: disposing that fiber stops
629
+ * event notification and removes the session from the store. `options.seed`
630
+ * populates the session with a copy of those events (replay/fork);
631
+ * `options.meta` attaches creation metadata (validated absolute `cwd`, seed
632
+ * and parent lineage, and delegation depth) as the immutable
633
+ * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).
634
+ *
635
+ * For an agent whose session must be torn down IN ORDER with its loop (so the
636
+ * loop's final events are published before the store attachment ends), do NOT use this
637
+ * — fold the session lifecycle into the agent's own effect via
638
+ * {@link prepare} + {@link enter} + {@link announce} (see
639
+ * `dsh-agent-loop`'s creation transaction).
640
+ *
641
+ * @param id - the session id; omitted, the store mints `session-<n>`.
642
+ * @param options - seed events and/or creation metadata for the header.
643
+ * @returns the live session, already entered and announced.
644
+ * @throws if a session with `id` already exists, metadata is not a plain
645
+ * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
646
+ * non-absolute path (storage backends key directories off it).
647
+ */
648
+ create(id?: SessionId, options?: CreateSessionOptions): Session
649
+
650
+ /**
651
+ * Build a session WITHOUT entering it into the store — validate the id/cwd and
652
+ * construct the {@link Session} (with its immutable {@link SessionHeader}).
653
+ * Pairs with {@link enter} + {@link announce}: a caller that owns a composite
654
+ * `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
655
+ * effect so a fiber unload tears the session + agent down as a single ORDERED
656
+ * chain rather than as racing sibling effects — which would remove the publication hooks
657
+ * before the driver's closing events commit, dropping them.
658
+ *
659
+ * @param id - the session id; omitted, the store mints `session-<n>`.
660
+ * @param options - seed events and/or creation metadata for the header. With
661
+ * `seedSource: 'persistence'`, metadata and events must be fresh detached
662
+ * graphs whose ownership transfers to this call: they are validated and
663
+ * frozen in place through {@link Session.fromRestore}, so the caller must
664
+ * retain no mutable aliases.
665
+ * @returns the constructed session, NOT yet in the store.
666
+ * @throws if a session with `id` already exists, metadata is not a plain
667
+ * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
668
+ * non-absolute path.
669
+ */
670
+ prepare(id?: SessionId, options?: PrepareSessionOptions): Session
671
+
672
+ /**
673
+ * Enter a {@link prepare}d session into the store: install the module-private
674
+ * append publication hooks and add it to the store. Returns the DETACH
675
+ * disposer (hooks + store removal). Does NOT emit `session/created` —
676
+ * the caller yields this disposer inside its effect and THEN calls
677
+ * {@link announce}, so a throwing `session/created` listener rolls the attach
678
+ * back instead of leaking it.
679
+ *
680
+ * Re-checks the id for a duplicate: `prepare` and `enter` are public
681
+ * cross-package primitives and a caller may interleave arbitrary work (or
682
+ * another create) between them, so a stale prepared session must NOT overwrite
683
+ * a live store entry of the same id — its detach disposer would later delete
684
+ * the REAL session. The {@link create} convenience and the agent factory call
685
+ * the two back-to-back so they never trip this, but the public API cannot
686
+ * assume that.
687
+ *
688
+ * @param session - a {@link prepare}d session not yet in the store.
689
+ * @returns the detach disposer (publication hooks + store removal). When called from
690
+ * a synchronous `session/created` listener, removal and disposal wait until
691
+ * that creation dispatch unwinds.
692
+ * @throws if a session with this id is already in the store.
693
+ */
694
+ enter(session: Session): () => void
695
+
696
+ /** Emit `session/created` exactly once for an {@link enter}ed session (with
697
+ * the carrier {@link enter} captured). Separate from {@link enter} so the
698
+ * caller can yield the detach disposer first (rollback safety — see
699
+ * {@link enter}).
700
+ * @param session - the entered session to announce to listeners.
701
+ * @throws if the session is not live or its announcement already began,
702
+ * including a reentrant call from a creation listener. */
703
+ announce(session: Session): void
704
+
705
+ /**
706
+ * Dispatch the awaited `session/flush` durability checkpoint for `session`,
707
+ * with the carrier captured at {@link enter}. THE flush entry point: the
708
+ * store owns the carrier, so callers (the checkpoint policy's per-request
709
+ * barrier, goal-round-driver's idle checkpoint, teardown drains, and consumers
710
+ * that flush themselves before reading storage) must come through here
711
+ * rather than dispatch a raw `ctx.parallel('session/flush', …)` — one owner,
712
+ * one spelling, and the scoped-dispatch invariant can pin it.
713
+ * @param session - the session whose buffered events must reach durable storage.
714
+ * @returns whether at least one durability listener participated, after every
715
+ * listener has settled successfully.
716
+ * @throws the first registered listener failure after every listener settles.
717
+ */
718
+ async flush(session: Session): Promise<boolean>
719
+
720
+ /**
721
+ * Look up a live session.
722
+ * @param id - the session id to look up.
723
+ * @returns the session, or undefined when no live session has that id.
724
+ */
725
+ get(id: SessionId): Session | undefined
726
+
727
+ /**
728
+ * All live sessions, in creation order.
729
+ * @returns a fresh array; mutating it does not affect the store.
730
+ */
731
+ list(): Session[]
732
+
733
+ /**
734
+ * Create a live child session from a stable prefix of a live source.
735
+ * `boundary` is an inclusive source event seq; omitted means the source's
736
+ * current last event. The selected slice may end with a between-turn event
737
+ * but must not end inside an open turn.
738
+ *
739
+ * @param source - Live source session object or id.
740
+ * @param boundary - Inclusive source event seq to fork through; omitted means
741
+ * the source's current last event, and omitted on an empty source forks an
742
+ * empty child.
743
+ * @param childSessionId - Optional child session id; omitted delegates to
744
+ * `SessionStore`'s id policy.
745
+ * @returns The created live child session.
746
+ */
747
+ fork(source: SessionForkSource, boundary?: number, childSessionId?: SessionId): Session
748
+ ```
749
+
750
+ Types: [CreateSessionOptions](./persistence.md) · [PrepareSessionOptions](./persistence.md) · [SessionId](./core.md)
751
+
752
+ Source: [`packages/core/session/src/index.ts:792`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
753
+
754
+ <a id="session-events"></a>
755
+
756
+ ### `session/*` events
757
+
758
+ <a id="sessioncreated--emit"></a>
759
+
760
+ #### `session/created` — emit
761
+
762
+ Creation announcement during session publication. A synchronous throw vetoes 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.
763
+
764
+ ```ts cordis-catalog
765
+ /**
766
+ * Creation announcement during session publication. A synchronous throw vetoes and rolls
767
+ * back with a paired disposal; detach requested during dispatch is deferred.
768
+ * A returned-promise rejection is logged but cannot retroactively veto this
769
+ * synchronous boundary.
770
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
771
+ * receive only sessions entered through that agent's context.
772
+ * @param session - the session just entered and announced.
773
+ * @dshScopeScan unsupported
774
+ * @mode emit
775
+ */
776
+ 'session/created'(this: Scoped<Session>, session: Session): void
777
+ ```
778
+
779
+ Types: [Scoped](./scope.md)
780
+
781
+ Source: [`packages/core/session/src/index.ts:54`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
782
+
783
+ <a id="sessiondisposed--emit"></a>
784
+
785
+ #### `session/disposed` — emit
786
+
787
+ 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.
788
+
789
+ ```ts cordis-catalog
790
+ /**
791
+ * Emitted once when an announced session leaves the store, including
792
+ * publication rollback, but never for an entry whose creation announcement
793
+ * did not begin. Listener failures are logged and contained.
794
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope.
795
+ * @param session - the session that is no longer live in the store.
796
+ * @dshScopeScan unsupported
797
+ * @mode emit
798
+ */
799
+ 'session/disposed'(this: Scoped<Session>, session: Session): void
800
+ ```
801
+
802
+ Types: [Scoped](./scope.md)
803
+
804
+ Source: [`packages/core/session/src/index.ts:64`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
805
+
806
+ <a id="sessionevent--emit"></a>
807
+
808
+ #### `session/event` — emit
809
+
810
+ 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.
811
+
812
+ ```ts cordis-catalog
813
+ /**
814
+ * Post-commit, fire-and-forget append feed. The listener snapshot resolves
815
+ * before the log push, but callbacks run after it; observer failures are
816
+ * logged and contained without making the committed append fail.
817
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
818
+ * receive only events from sessions entered through that agent's context.
819
+ * @param session - the session whose log grew.
820
+ * @param event - the appended event, exactly as recorded.
821
+ * @dshScopeScan unsupported
822
+ * @mode emit
823
+ */
824
+ 'session/event'(this: Scoped<Session>, session: Session, event: SessionEvent): void
825
+ ```
826
+
827
+ Types: [Scoped](./scope.md)
828
+
829
+ Source: [`packages/core/session/src/index.ts:76`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
830
+
831
+ <a id="sessionflush--parallel"></a>
832
+
833
+ #### `session/flush` — parallel
834
+
835
+ 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.
836
+
837
+ ```ts cordis-catalog
838
+ /**
839
+ * Awaited parallel durability checkpoint: every listener runs and the
840
+ * caller awaits all of them, with no waterfall veto. Scope-filtered dispatch
841
+ * (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
842
+ * @param session - the session whose buffered events must reach durable storage.
843
+ * @dshScopeScan unsupported
844
+ * @mode parallel
845
+ */
846
+ 'session/flush'(this: Scoped<Session>, session: Session): Promise<void> | void
847
+ ```
848
+
849
+ Types: [Scoped](./scope.md)
850
+
851
+ Source: [`packages/core/session/src/index.ts:85`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/session/src/index.ts)
852
+ <!-- END GENERATED cordis-surface -->