@acryldev/plugin-context 0.0.0-stage → 0.1.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 (284) hide show
  1. package/LICENSE +21 -0
  2. package/docs/README.md +160 -0
  3. package/docs/delivery/local-live.md +113 -0
  4. package/docs/delivery/marketplace.md +16 -0
  5. package/docs/docs.json +2836 -0
  6. package/docs/extending/agent-preset.md +37 -0
  7. package/docs/extending/chat-command.md +28 -0
  8. package/docs/extending/client-slot.md +135 -0
  9. package/docs/extending/config-schema.md +7 -0
  10. package/docs/extending/cordis-core.md +63 -0
  11. package/docs/extending/desktop-app.md +53 -0
  12. package/docs/extending/desktop-main.md +25 -0
  13. package/docs/extending/event-hook.md +14 -0
  14. package/docs/extending/host-route.md +33 -0
  15. package/docs/extending/llm-adapter.md +38 -0
  16. package/docs/extending/packaging.md +53 -0
  17. package/docs/extending/prompt-contribution.md +9 -0
  18. package/docs/extending/service.md +13 -0
  19. package/docs/extending/skill-provider.md +9 -0
  20. package/docs/extending/state-and-persistence.md +71 -0
  21. package/docs/extending/three-role-capability.md +33 -0
  22. package/docs/extending/tool-plugin.md +24 -0
  23. package/docs/extending/tui-command.md +8 -0
  24. package/docs/extending/tui-components.md +61 -0
  25. package/docs/extending/ui-branding.md +43 -0
  26. package/docs/extending/ui-components.md +56 -0
  27. package/docs/extending/ui-customization.md +41 -0
  28. package/docs/extending/ui-library.md +66 -0
  29. package/docs/extending/ui-theme.md +55 -0
  30. package/docs/extending/workspace-tab.md +50 -0
  31. package/docs/maps/events.md +108 -0
  32. package/docs/maps/mount-points.md +154 -0
  33. package/docs/maps/slot-contracts.md +3376 -0
  34. package/docs/maps/taxonomy.md +306 -0
  35. package/docs/maps/theme-tokens.md +115 -0
  36. package/docs/maps/ui-components.md +26 -0
  37. package/docs/reference/cookbook/adding-a-package.md +174 -0
  38. package/docs/reference/cookbook/adding-a-remote-api.md +199 -0
  39. package/docs/reference/cookbook/adding-a-settings-card.md +74 -0
  40. package/docs/reference/cookbook/adding-a-tool.md +103 -0
  41. package/docs/reference/cookbook/adding-an-llm-adapter.md +45 -0
  42. package/docs/reference/cookbook/extension-cookbook.md +134 -0
  43. package/docs/reference/cordis-api/context.md +366 -0
  44. package/docs/reference/cordis-api/events.md +209 -0
  45. package/docs/reference/cordis-api/fiber.md +377 -0
  46. package/docs/reference/cordis-api/inherited.md +40 -0
  47. package/docs/reference/cordis-api/registry.md +154 -0
  48. package/docs/reference/cordis-api/service.md +104 -0
  49. package/docs/reference/cordis-guides/cordis-usage-cheatsheet.md +167 -0
  50. package/docs/reference/cordis-guides/cordis_system_guide_for_coding_agents.md +4666 -0
  51. package/docs/reference/cordis-guides/development-canvas-plugin.md +109 -0
  52. package/docs/reference/cordis-guides/hello-world-plugin-guide.md +517 -0
  53. package/docs/reference/harness/agent-lifecycle.md +93 -0
  54. package/docs/reference/harness/architecture.md +168 -0
  55. package/docs/reference/harness/capability-seams.md +675 -0
  56. package/docs/reference/harness/config-catalog.md +4523 -0
  57. package/docs/reference/harness/cordis-primer.md +47 -0
  58. package/docs/reference/harness/defensive-patterns.md +35 -0
  59. package/docs/reference/harness/event-producer-consumer.md +111 -0
  60. package/docs/reference/harness/glossary.md +47 -0
  61. package/docs/reference/harness/tool-catalog.md +2721 -0
  62. package/docs/reference/harness/tool-execution-pipeline.md +67 -0
  63. package/docs/reference/subsystems/README.md +75 -0
  64. package/docs/reference/subsystems/agent-team.md +233 -0
  65. package/docs/reference/subsystems/approval.md +172 -0
  66. package/docs/reference/subsystems/attachment.md +363 -0
  67. package/docs/reference/subsystems/boot.md +324 -0
  68. package/docs/reference/subsystems/browser-use.md +69 -0
  69. package/docs/reference/subsystems/client-modules.md +186 -0
  70. package/docs/reference/subsystems/client-resources.md +94 -0
  71. package/docs/reference/subsystems/commands.md +225 -0
  72. package/docs/reference/subsystems/compaction.md +286 -0
  73. package/docs/reference/subsystems/computer-use.md +58 -0
  74. package/docs/reference/subsystems/conversation.md +287 -0
  75. package/docs/reference/subsystems/core.md +1107 -0
  76. package/docs/reference/subsystems/credentials.md +497 -0
  77. package/docs/reference/subsystems/deliverables.md +180 -0
  78. package/docs/reference/subsystems/extensions.md +386 -0
  79. package/docs/reference/subsystems/feedback.md +402 -0
  80. package/docs/reference/subsystems/filesystem.md +532 -0
  81. package/docs/reference/subsystems/goal.md +315 -0
  82. package/docs/reference/subsystems/invariants.md +90 -0
  83. package/docs/reference/subsystems/jobs.md +501 -0
  84. package/docs/reference/subsystems/llm-streaming.md +1131 -0
  85. package/docs/reference/subsystems/lsp.md +204 -0
  86. package/docs/reference/subsystems/mcp.md +141 -0
  87. package/docs/reference/subsystems/office-to-pdf.md +89 -0
  88. package/docs/reference/subsystems/otel.md +46 -0
  89. package/docs/reference/subsystems/permission-presets.md +169 -0
  90. package/docs/reference/subsystems/persistence.md +418 -0
  91. package/docs/reference/subsystems/plan.md +89 -0
  92. package/docs/reference/subsystems/product-telemetry.md +81 -0
  93. package/docs/reference/subsystems/ptc-runtime.md +234 -0
  94. package/docs/reference/subsystems/sandbox.md +223 -0
  95. package/docs/reference/subsystems/schedule.md +545 -0
  96. package/docs/reference/subsystems/scope.md +61 -0
  97. package/docs/reference/subsystems/session-projection.md +358 -0
  98. package/docs/reference/subsystems/session-query.md +511 -0
  99. package/docs/reference/subsystems/session-reference.md +226 -0
  100. package/docs/reference/subsystems/session-telemetry.md +214 -0
  101. package/docs/reference/subsystems/session-title.md +206 -0
  102. package/docs/reference/subsystems/session.md +1300 -0
  103. package/docs/reference/subsystems/settings.md +157 -0
  104. package/docs/reference/subsystems/shell.md +316 -0
  105. package/docs/reference/subsystems/sidebar-right.md +160 -0
  106. package/docs/reference/subsystems/skills.md +354 -0
  107. package/docs/reference/subsystems/slots.md +201 -0
  108. package/docs/reference/subsystems/spill.md +126 -0
  109. package/docs/reference/subsystems/ssh.md +137 -0
  110. package/docs/reference/subsystems/storage.md +262 -0
  111. package/docs/reference/subsystems/subagent.md +762 -0
  112. package/docs/reference/subsystems/subprocess.md +323 -0
  113. package/docs/reference/subsystems/system-prompt.md +226 -0
  114. package/docs/reference/subsystems/terminal.md +186 -0
  115. package/docs/reference/subsystems/todo.md +34 -0
  116. package/docs/reference/subsystems/token-meter.md +108 -0
  117. package/docs/reference/subsystems/tools.md +749 -0
  118. package/docs/reference/subsystems/typert.md +489 -0
  119. package/docs/reference/subsystems/user-questions.md +309 -0
  120. package/docs/reference/subsystems/voice-input.md +166 -0
  121. package/docs/reference/subsystems/web-client.md +102 -0
  122. package/docs/reference/subsystems/web-server.md +228 -0
  123. package/docs/reference/subsystems/web.md +208 -0
  124. package/docs/reference/subsystems/webhook.md +72 -0
  125. package/docs/reference/subsystems/workflow.md +280 -0
  126. package/docs/reference/subsystems/workspace.md +661 -0
  127. package/docs/start-here/blueprints.md +33 -0
  128. package/docs/start-here/this-runtime.md +84 -0
  129. package/docs/start-here/troubleshooting.md +29 -0
  130. package/docs/start-here/trust-and-safety.md +39 -0
  131. package/docs/start-here/verify-before-done.md +46 -0
  132. package/example-plugins/README.md +45 -0
  133. package/example-plugins/packages/agent-preset-reviewer/agent.cordis.yml +18 -0
  134. package/example-plugins/packages/agent-preset-reviewer/preset.yml +3 -0
  135. package/example-plugins/packages/capability-swap-consumer/cordis.patch.yml +3 -0
  136. package/example-plugins/packages/capability-swap-consumer/index.js +14 -0
  137. package/example-plugins/packages/capability-swap-consumer/package.json +25 -0
  138. package/example-plugins/packages/capability-swap-provider-loud/cordis.patch.yml +3 -0
  139. package/example-plugins/packages/capability-swap-provider-loud/index.js +20 -0
  140. package/example-plugins/packages/capability-swap-provider-loud/package.json +25 -0
  141. package/example-plugins/packages/capability-swap-provider-quiet/cordis.patch.yml +3 -0
  142. package/example-plugins/packages/capability-swap-provider-quiet/index.js +20 -0
  143. package/example-plugins/packages/capability-swap-provider-quiet/package.json +25 -0
  144. package/example-plugins/packages/chat-command-basic/cordis.patch.yml +3 -0
  145. package/example-plugins/packages/chat-command-basic/index.js +26 -0
  146. package/example-plugins/packages/chat-command-basic/package.json +25 -0
  147. package/example-plugins/packages/client-chat-message-action/client.js +46 -0
  148. package/example-plugins/packages/client-chat-message-action/cordis.patch.yml +3 -0
  149. package/example-plugins/packages/client-chat-message-action/index.js +9 -0
  150. package/example-plugins/packages/client-chat-message-action/package.json +31 -0
  151. package/example-plugins/packages/client-slot-header-action/client.js +57 -0
  152. package/example-plugins/packages/client-slot-header-action/cordis.patch.yml +3 -0
  153. package/example-plugins/packages/client-slot-header-action/index.js +13 -0
  154. package/example-plugins/packages/client-slot-header-action/package.json +31 -0
  155. package/example-plugins/packages/client-slot-sidebar-tab/client.js +57 -0
  156. package/example-plugins/packages/client-slot-sidebar-tab/cordis.patch.yml +3 -0
  157. package/example-plugins/packages/client-slot-sidebar-tab/index.js +9 -0
  158. package/example-plugins/packages/client-slot-sidebar-tab/package.json +32 -0
  159. package/example-plugins/packages/client-theme-override/client.js +52 -0
  160. package/example-plugins/packages/client-theme-override/cordis.patch.yml +3 -0
  161. package/example-plugins/packages/client-theme-override/index.js +9 -0
  162. package/example-plugins/packages/client-theme-override/package.json +30 -0
  163. package/example-plugins/packages/client-tool-view/client.js +47 -0
  164. package/example-plugins/packages/client-tool-view/cordis.patch.yml +3 -0
  165. package/example-plugins/packages/client-tool-view/index.js +24 -0
  166. package/example-plugins/packages/client-tool-view/package.json +34 -0
  167. package/example-plugins/packages/client-ui-components/client.js +77 -0
  168. package/example-plugins/packages/client-ui-components/cordis.patch.yml +3 -0
  169. package/example-plugins/packages/client-ui-components/index.js +9 -0
  170. package/example-plugins/packages/client-ui-components/package.json +31 -0
  171. package/example-plugins/packages/client-ui-library/client.js +715 -0
  172. package/example-plugins/packages/client-ui-library/cordis.patch.yml +3 -0
  173. package/example-plugins/packages/client-ui-library/index.js +9 -0
  174. package/example-plugins/packages/client-ui-library/package.json +37 -0
  175. package/example-plugins/packages/client-workspace-tab/client.js +72 -0
  176. package/example-plugins/packages/client-workspace-tab/cordis.patch.yml +3 -0
  177. package/example-plugins/packages/client-workspace-tab/index.js +9 -0
  178. package/example-plugins/packages/client-workspace-tab/package.json +30 -0
  179. package/example-plugins/packages/config-schema-basic/cordis.patch.yml +3 -0
  180. package/example-plugins/packages/config-schema-basic/index.js +19 -0
  181. package/example-plugins/packages/config-schema-basic/package.json +25 -0
  182. package/example-plugins/packages/desktop-main-profile-info/cordis.patch.yml +3 -0
  183. package/example-plugins/packages/desktop-main-profile-info/index.js +22 -0
  184. package/example-plugins/packages/desktop-main-profile-info/package.json +25 -0
  185. package/example-plugins/packages/event-hook-basic/cordis.patch.yml +3 -0
  186. package/example-plugins/packages/event-hook-basic/index.js +17 -0
  187. package/example-plugins/packages/event-hook-basic/package.json +22 -0
  188. package/example-plugins/packages/generated-capability-template/cordis.patch.yml +3 -0
  189. package/example-plugins/packages/generated-capability-template/index.js +16 -0
  190. package/example-plugins/packages/generated-capability-template/package.json +42 -0
  191. package/example-plugins/packages/host-route-basic/cordis.patch.yml +3 -0
  192. package/example-plugins/packages/host-route-basic/index.js +20 -0
  193. package/example-plugins/packages/host-route-basic/package.json +29 -0
  194. package/example-plugins/packages/lifecycle-function-basic/cordis.patch.yml +3 -0
  195. package/example-plugins/packages/lifecycle-function-basic/index.js +12 -0
  196. package/example-plugins/packages/lifecycle-function-basic/package.json +15 -0
  197. package/example-plugins/packages/lifecycle-function-hot-shim/cordis.patch.yml +3 -0
  198. package/example-plugins/packages/lifecycle-function-hot-shim/impl.js +5 -0
  199. package/example-plugins/packages/lifecycle-function-hot-shim/index.js +18 -0
  200. package/example-plugins/packages/lifecycle-function-hot-shim/package.json +23 -0
  201. package/example-plugins/packages/lifecycle-hooks-observer/cordis.patch.yml +3 -0
  202. package/example-plugins/packages/lifecycle-hooks-observer/index.js +23 -0
  203. package/example-plugins/packages/lifecycle-hooks-observer/package.json +22 -0
  204. package/example-plugins/packages/llm-adapter-echo/cordis.patch.yml +3 -0
  205. package/example-plugins/packages/llm-adapter-echo/index.js +42 -0
  206. package/example-plugins/packages/llm-adapter-echo/package.json +25 -0
  207. package/example-plugins/packages/prompt-assemble-hook/cordis.patch.yml +3 -0
  208. package/example-plugins/packages/prompt-assemble-hook/index.js +22 -0
  209. package/example-plugins/packages/prompt-assemble-hook/package.json +22 -0
  210. package/example-plugins/packages/prompt-contribution-basic/cordis.patch.yml +3 -0
  211. package/example-plugins/packages/prompt-contribution-basic/index.js +18 -0
  212. package/example-plugins/packages/prompt-contribution-basic/package.json +22 -0
  213. package/example-plugins/packages/service-consumer-greeter/cordis.patch.yml +3 -0
  214. package/example-plugins/packages/service-consumer-greeter/index.js +14 -0
  215. package/example-plugins/packages/service-consumer-greeter/package.json +22 -0
  216. package/example-plugins/packages/service-provider-greeter/cordis.patch.yml +3 -0
  217. package/example-plugins/packages/service-provider-greeter/index.js +22 -0
  218. package/example-plugins/packages/service-provider-greeter/package.json +25 -0
  219. package/example-plugins/packages/settings-section-basic/cordis.patch.yml +3 -0
  220. package/example-plugins/packages/settings-section-basic/index.js +34 -0
  221. package/example-plugins/packages/settings-section-basic/package.json +26 -0
  222. package/example-plugins/packages/skill-provider-basic/cordis.patch.yml +3 -0
  223. package/example-plugins/packages/skill-provider-basic/index.js +31 -0
  224. package/example-plugins/packages/skill-provider-basic/package.json +22 -0
  225. package/example-plugins/packages/state-host-store/client.js +57 -0
  226. package/example-plugins/packages/state-host-store/cordis.patch.yml +3 -0
  227. package/example-plugins/packages/state-host-store/index.js +90 -0
  228. package/example-plugins/packages/state-host-store/package.json +31 -0
  229. package/example-plugins/packages/state-workspace-file/cordis.patch.yml +3 -0
  230. package/example-plugins/packages/state-workspace-file/index.js +52 -0
  231. package/example-plugins/packages/state-workspace-file/package.json +25 -0
  232. package/example-plugins/packages/tool-basic/cordis.patch.yml +3 -0
  233. package/example-plugins/packages/tool-basic/index.js +25 -0
  234. package/example-plugins/packages/tool-basic/package.json +25 -0
  235. package/example-plugins/packages/tool-policy-hook/cordis.patch.yml +3 -0
  236. package/example-plugins/packages/tool-policy-hook/index.js +28 -0
  237. package/example-plugins/packages/tool-policy-hook/package.json +25 -0
  238. package/example-plugins/packages/tui-command-basic/cordis.patch.yml +3 -0
  239. package/example-plugins/packages/tui-command-basic/index.js +24 -0
  240. package/example-plugins/packages/tui-command-basic/package.json +22 -0
  241. package/example-plugins/packages/tui-overlay-themed/cordis.patch.yml +3 -0
  242. package/example-plugins/packages/tui-overlay-themed/index.js +65 -0
  243. package/example-plugins/packages/tui-overlay-themed/package.json +25 -0
  244. package/example-plugins/packages/tui-ui-library/cordis.patch.yml +3 -0
  245. package/example-plugins/packages/tui-ui-library/index.js +73 -0
  246. package/example-plugins/packages/tui-ui-library/package.json +29 -0
  247. package/example-plugins/packages/web-page-branding/cordis.patch.yml +3 -0
  248. package/example-plugins/packages/web-page-branding/index.js +31 -0
  249. package/example-plugins/packages/web-page-branding/package.json +22 -0
  250. package/example-plugins/scenarios.json +11 -0
  251. package/index.js +384 -0
  252. package/lib/blend-apply.js +107 -0
  253. package/lib/blend-capture.js +249 -0
  254. package/lib/blend-ledger.js +76 -0
  255. package/lib/contract.js +5 -0
  256. package/lib/install.js +516 -0
  257. package/lib/lookup.js +67 -0
  258. package/lib/manifest.js +56 -0
  259. package/lib/pack-root.js +22 -0
  260. package/lib/provenance.js +110 -0
  261. package/lib/publish.js +64 -0
  262. package/lib/reconcile.js +83 -0
  263. package/lib/router.js +55 -0
  264. package/lib/scopes.js +82 -0
  265. package/lib/skills.js +54 -0
  266. package/lib/stage.js +157 -0
  267. package/lib/verify.js +77 -0
  268. package/package.json +56 -3
  269. package/scripts/lib/indexes.mjs +45 -0
  270. package/scripts/lib/manifest.mjs +127 -0
  271. package/scripts/lib/maps.mjs +482 -0
  272. package/skills/acryl-add-provider-or-capability/SKILL.md +12 -0
  273. package/skills/acryl-add-ui/SKILL.md +18 -0
  274. package/skills/acryl-build-plugin/SKILL.md +21 -0
  275. package/skills/acryl-change-plugin/SKILL.md +16 -0
  276. package/skills/acryl-desktop-shell/SKILL.md +12 -0
  277. package/skills/acryl-diagnose-plugin/SKILL.md +10 -0
  278. package/skills/acryl-fix-plugin/SKILL.md +12 -0
  279. package/skills/acryl-improve-ui/SKILL.md +10 -0
  280. package/skills/acryl-remove-plugin/SKILL.md +11 -0
  281. package/skills/acryl-restyle-ui/SKILL.md +14 -0
  282. package/skills/acryl-share-plugin/SKILL.md +23 -0
  283. package/skills/acryl-tui-ui/SKILL.md +12 -0
  284. package/README.md +0 -3
@@ -0,0 +1,1300 @@
1
+ <!-- Synced from deepseek-harness:docs/subsystems/session.md @ 639ed01539. Do not edit; run scripts/sync-corpus.mjs. Relative links inside may not resolve here. -->
2
+
3
+ # Sessions
4
+
5
+ English | [中文](session.zh.md)
6
+
7
+ The in-memory, event-sourced model of [dsh-session](../../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).
8
+
9
+ Source: [`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts)
10
+
11
+ ## `SessionEventMap` - the event vocabulary
12
+
13
+ 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.
14
+
15
+ ```ts type-equiv
16
+ /** A user-role specialization of the shared message representation. */
17
+ interface UserMessage extends MessageBase {
18
+ readonly role: 'user'
19
+ }
20
+ ```
21
+
22
+ ```ts type-equiv
23
+ /**
24
+ * The merge-extensible, append-only source of truth for an agent interaction.
25
+ * Message history is derived from this log. Every event is lossless JSON and
26
+ * sequence numbers stay contiguous. Assistant attempt events embed their exact
27
+ * compact raw streams so persistence stores one durable settlement per attempt.
28
+ */
29
+ interface SessionEventMap {
30
+ /**
31
+ * Opens turn `turn` before the loop claims queued input or runs pre-step.
32
+ * Rejection, empty input, cancellation, or failure may close it with no
33
+ * step; otherwise the following identified `user/message` event or batch
34
+ * records the messages entering the step.
35
+ */
36
+ 'turn/start': { turn: number }
37
+ /**
38
+ * Closes turn `turn` with the {@link TurnEndReason} that ended it. A turn
39
+ * with no entered step has no `step/start` or `step/end`. The loop does not await a
40
+ * flush at turn boundaries: `dsh-session-checkpoint-policy` owns the
41
+ * per-request durability checkpoint, and consumers that read storage after
42
+ * `whenIdle()` flush themselves. Success commits the turn; rejection is
43
+ * reported live and does not prevent later work.
44
+ */
45
+ 'turn/end': { turn: number; reason: TurnEndReason }
46
+ /** Opens step `step` of turn `turn` - one model call plus the tool executions it requested. */
47
+ 'step/start': { turn: number; step: number }
48
+ /** Closes step `step` of turn `turn`. */
49
+ 'step/end': { turn: number; step: number }
50
+ /**
51
+ * A user-role message on the model-visible surface: a direct human prompt
52
+ * (the queued message claimed for this turn), a synthetic `agent.inject()`
53
+ * context (file-change notices, subdir AGENTS.md, skill content, cron
54
+ * notifications, …), or an entered goal continuation round. All three
55
+ * project their `content` verbatim; `source` tells them apart.
56
+ */
57
+ 'user/message': UserMessage
58
+ /** An incremental agent session change admitted at the named turn and step. */
59
+ 'developer/message': {
60
+ turn: number
61
+ step: number
62
+ message: DeveloperMessage
63
+ /** Earlier request/header defining every tool addition; required exactly when additions are present. */
64
+ headerSeq?: SessionSeq
65
+ }
66
+ /**
67
+ * The rendered system prompt on the model-visible surface. The loop appends
68
+ * the first one as surface node 0 before the step's first `user/message`.
69
+ * A prepared in-history route can append nonempty changes in a continuing
70
+ * series. An incapable route or new series normalizes text to the first system
71
+ * node. Normalization empties nonempty later nodes, then rewrites the head if
72
+ * needed, through logged per-node replacements. An empty rendering always
73
+ * clears all active system nodes, leaving no older instructions model-visible.
74
+ * Empty later nodes are dormant and project to no message; an empty head with
75
+ * no active later node records "no system prompt". Restored nonempty text follows
76
+ * the same route and series rule; empty nodes never restore older text.
77
+ */
78
+ 'system/message': { turn: number; step: number; message: SystemMessage }
79
+ /**
80
+ * Assembled assistant message for one step (derived history uses this).
81
+ * Carries the step's `usage` when the adapter reported token accounting, so
82
+ * the model output and its accounting travel together (there is no separate
83
+ * usage record). `usage` is absent when the adapter reported none. A turn
84
+ * cancelled mid-stream finalizes its delivered text/reasoning prefix as this
85
+ * event with `interrupted: true`; undispatched tool calls are absent. The
86
+ * marker distinguishes that prefix without re-deriving interruption from turn
87
+ * boundaries. An aborted turn with no such event streamed no visible content.
88
+ */
89
+ 'assistant/message': {
90
+ turn: number
91
+ step: number
92
+ message: AssistantMessage
93
+ /** Exact timed model stream, compacted without joining delta boundaries. */
94
+ stream: AssistantStreamRecord[]
95
+ usage?: TokenUsage
96
+ interrupted?: true
97
+ }
98
+ /**
99
+ * One model attempt that committed no surface message. The embedded stream
100
+ * preserves a failed, retried, cancelled, or stream-error attempt that
101
+ * reached settlement without fabricating model-visible history.
102
+ */
103
+ 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] }
104
+ /**
105
+ * The model requested one tool invocation: `name` with the raw `arguments`
106
+ * JSON string exactly as the model produced it (unparsed). `callId` pairs the
107
+ * call with its `tool/result`.
108
+ */
109
+ 'tool/call': { turn: number; step: number; callId: ToolCallId; name: string; arguments: string }
110
+ /**
111
+ * A completed tool call's model-facing result, optional internal failure
112
+ * identity and user-facing reason, and optional tool-private `meta`
113
+ * presentation payload. The reason remains outside the model-facing message.
114
+ * `meta` is
115
+ * opaque to the core (the producing tool owns its shape and reads it back in
116
+ * `presentResult`) but MUST be JSON-serializable: `Session.append`
117
+ * runtime-validates all event data with `isJsonValue`, so a non-serializable
118
+ * `meta` is rejected at the source, and the durable log reproduces the
119
+ * identical card on replay. Absent
120
+ * unless the tool attaches one (e.g. `dsh-tool-fs` carries its result-time
121
+ * contextual diff here).
122
+ */
123
+ 'tool/result': {
124
+ turn: number
125
+ step: number
126
+ message: ToolResultMessage
127
+ /**
128
+ * Optional failure identity and raw user-facing reason, outside model content;
129
+ * allowed only when the message has `isError: true`.
130
+ */
131
+ error?: { name: string; code: string; reason?: string }
132
+ meta?: JsonValue
133
+ }
134
+ /**
135
+ * Full header for the next request, appended inside its step before dispatch.
136
+ * It is log-only; the latest snapshot reconstructs the request header.
137
+ */
138
+ 'request/header': {
139
+ header: EpochHeader
140
+ reason: RequestHeaderReason
141
+ /** This request begins a distinct model-message series, independently of the header reason. */
142
+ startsSeries?: true
143
+ }
144
+ /**
145
+ * Route metadata for the next request, logged only when the route, capacity,
146
+ * or system prompt update mode changes. It does not participate in request
147
+ * reconstruction or header equality. Prompt admission uses the bound prepared
148
+ * call's capability, not this snapshot from an earlier request.
149
+ */
150
+ 'request/context': RequestContext
151
+ /**
152
+ * Separates inherited or restored history from later lifecycle-owned work.
153
+ * This log-only marker need not be at {@link Session.firstLiveSeq}: a fork
154
+ * seed can already contain its tagged marker and child-owned synthetic
155
+ * closers before construction.
156
+ *
157
+ * A fresh fork child owns one `{ inherited: true }` marker at its exact
158
+ * inherited-prefix cut, even when that prefix ends in an ancestor marker.
159
+ * `buildForkSeed` appends that marker before any synthetic closers; the
160
+ * `Session` constructor supplies it when given only the inherited prefix.
161
+ * The last tagged marker is the current Session's cut; untagged markers
162
+ * keep ordinary restore and replay lifecycle boundaries.
163
+ *
164
+ * Only the `Session` constructor and `buildForkSeed` may create this marker.
165
+ * The invariant companion deliberately constrains nothing here, so a plugin
166
+ * appending one would silently classify every live bracket before it as seed history.
167
+ *
168
+ * An owner of a standalone open/close bracket (`compaction/start` …
169
+ * `compaction/end`) reads it because seed history and live work are otherwise
170
+ * byte-identical: an unmatched opening marker before this event belongs to
171
+ * an ended lifecycle, whatever ended it. NOT a liveness signal about other
172
+ * writers - a concurrently live session holds its own boundary elsewhere,
173
+ * so tolerating concurrent writers needs a signal beyond the log.
174
+ */
175
+ 'session/end-seed': { inherited?: true }
176
+ }
177
+ ```
178
+
179
+ `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.
180
+
181
+ <a id="the-request-header-event-requestheader"></a>
182
+
183
+ ### The request header event: `request/header`
184
+
185
+ 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](../../.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.
186
+
187
+ ```ts type-equiv
188
+ /**
189
+ * Logged request state outside derived history: call config and tools. The
190
+ * system prompt is derived history - surface node 0, a `system/message` event.
191
+ * The latest full `request/header` snapshot reconstructs the header; canonical
192
+ * empty optional fields are absent.
193
+ */
194
+ interface EpochHeader {
195
+ /** The conversation's call configuration (provider, model, reasoning effort, and sampling scalars). */
196
+ config: LlmCallConfig
197
+ /** Effective config fields materialized from the exact adapter rather than proposed by a caller. */
198
+ adapterDefaults?: LlmCallConfigAdapterDefaults
199
+ /** Assembled tool schemas; absent for a tool-less request. */
200
+ tools?: ToolSchema[]
201
+ /** Retired request text; system prompts belong to system/message events.
202
+ * @persistenceReserved
203
+ */
204
+ system?: never
205
+ }
206
+ ```
207
+
208
+ 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](../../.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.
209
+
210
+ ### The route capacity event: `request/context`
211
+
212
+ 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 reconstruction invariant. 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](../../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`.
213
+
214
+ ```ts type-equiv
215
+ /** Registration-bound metadata for one resolved model route. */
216
+ interface RequestContext {
217
+ /** Registered provider route the metadata belongs to. */
218
+ provider: string
219
+ /** Provider-owned model id the metadata belongs to. */
220
+ model: string
221
+ /** Maximum combined request and response context in tokens, when advertised. */
222
+ contextWindow?: number
223
+ /** `'in-history'` when the route reads the latest `system` message at any position as the effective system prompt. */
224
+ systemPromptUpdate?: SystemPromptUpdate
225
+ }
226
+ ```
227
+
228
+ ## `SessionEvent<T>` - one log entry
229
+
230
+ 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.
231
+
232
+ ```ts type-equiv
233
+ /** Sequence number of one existing event in a Session log. */
234
+ type SessionSeq = BrandedNumber<'SessionSeq'>
235
+ ```
236
+
237
+ ```ts type-equiv
238
+ /** A Session log gap, prefix length, or read offset, which may equal the event count. */
239
+ type SessionLogOffset = BrandedNumber<'SessionLogOffset'>
240
+ ```
241
+
242
+ ```ts type-equiv
243
+ /** Inclusive Session event watermark, or `-1` before any event exists. */
244
+ type SessionSeqCursor = SessionSeq | -1
245
+ ```
246
+
247
+ ```ts type-equiv
248
+ /** One existing Session event position, or explicit absence. */
249
+ type OptionalSessionSeq = SessionSeq | null
250
+ ```
251
+
252
+ `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.
253
+
254
+ ```ts type-equiv
255
+ /**
256
+ * One immutable entry in the session log.
257
+ *
258
+ * A proper discriminated union over `type` (not independent `type`/`data`
259
+ * unions), so `switch (event.type)` narrows `event.data` without casts.
260
+ *
261
+ * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional:
262
+ * they only exist on {@link SurfaceEventType} variants (`system/message`, `user/message`,
263
+ * `assistant/message`, `tool/result`).
264
+ * Non-surface events (boundary markers, attempts, errors) never carry
265
+ * surface metadata - the compiler enforces this at `Session.append()`
266
+ * call sites.
267
+ */
268
+ type SessionEvent<T extends SessionEventType = SessionEventType> = {
269
+ [K in SessionEventType]: {
270
+ type: K
271
+ /** Monotonic sequence number within the session. */
272
+ seq: SessionSeq
273
+ /** Unix epoch milliseconds. */
274
+ time: number
275
+ data: SessionEventMap[K]
276
+ /**
277
+ * Marks an event a reader may safely skip when it does not recognize
278
+ * `type`. Absent means required: a reader meeting an unrecognized type
279
+ * without this marker MUST refuse to reconstruct the session instead of
280
+ * silently dropping the event, because an unrecognized required event may
281
+ * change how the rest of the log is interpreted. A writer sets `true` only
282
+ * on purely informational records whose loss cannot affect reconstruction;
283
+ * defaulting to required means a forgotten marker over-refuses (an
284
+ * inconvenience) rather than silently resuming a gutted session.
285
+ */
286
+ ignorable?: true
287
+ } & (K extends SurfaceEventType ? SurfaceIntent<K> : {
288
+ surfaceOp?: never
289
+ sourceEventSeqs?: never
290
+ })
291
+ }[T]
292
+ ```
293
+
294
+ `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`.
295
+
296
+ 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.
297
+
298
+ ## Surface types
299
+
300
+ 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](../../.agents/notes/implemented/architecture/2026-06-18-session-surface.md).
301
+
302
+ ### `SurfaceEventType` - the message-producing subset of event types
303
+
304
+ ```ts type-equiv
305
+ /**
306
+ * The subset of {@link SessionEventType} values whose events produce LLM
307
+ * messages and are eligible to appear on the ordered surface. Only these
308
+ * event types may carry {@link SurfaceOp}; system, user, and tool events may also cite
309
+ * earlier sources through {@link SessionEvent.sourceEventSeqs}.
310
+ */
311
+ type SurfaceEventType =
312
+ | 'system/message'
313
+ | 'developer/message'
314
+ | 'user/message'
315
+ | 'assistant/message'
316
+ | 'tool/result'
317
+ ```
318
+
319
+ ### `SurfaceOp` - how an event entered the surface
320
+
321
+ ```ts type-equiv
322
+ /**
323
+ * How a session event entered the ordered surface. Only valid on
324
+ * {@link SurfaceEventType} events.
325
+ *
326
+ * - `'append'`: added to the tail - normal path for user/assistant/tool
327
+ * messages.
328
+ * - `{ op: 'replace', startSeq, endSeq }`: replaces surface nodes from `startSeq`
329
+ * (inclusive) through `endSeq` (inclusive) with this node. Both must exist as
330
+ * surface nodes in the current surface. `startSeq === endSeq` replaces a single
331
+ * node. The node's {@link SessionEvent.sourceEventSeqs} must include every
332
+ * shadowed surface node. Used by compaction; any surface-replacing producer
333
+ * may use it.
334
+ */
335
+ type SurfaceOp =
336
+ | 'append'
337
+ | { op: 'replace'; startSeq: SessionSeq; endSeq: SessionSeq }
338
+ ```
339
+
340
+ `'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.
341
+
342
+ ### `SurfaceIntent` - the parameter to `session.append()`
343
+
344
+ ```ts type-equiv
345
+ /**
346
+ * Surface placement and cited source-event seqs for {@link Session.append}. Required on
347
+ * message-producing events and forbidden on log-only events.
348
+ */
349
+ type SurfaceIntent<T extends SurfaceEventType = SurfaceEventType> = {
350
+ surfaceOp: SurfaceOp
351
+ } & (T extends 'assistant/message' ? {
352
+ /** Assistant messages embed their provider stream instead of citing source events. */
353
+ sourceEventSeqs?: never
354
+ } : {
355
+ /** Complete non-empty set of known earlier source-event seqs. */
356
+ sourceEventSeqs?: SessionSeq[]
357
+ })
358
+ ```
359
+
360
+ 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](../../packages/core/session/README.md)). Non-surface types reject it at compile time.
361
+
362
+ `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.
363
+
364
+ <a id="plugin-owned-message-projections"></a>
365
+ ### Plugin-owned message projections
366
+
367
+ 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.
368
+
369
+ ```ts type-equiv
370
+ /** Readonly history immediately before a message-projection event. */
371
+ interface SessionMessageProjectionContext {
372
+ /** Current message-producing event sequences in model-visible order. */
373
+ nodes: readonly SessionSeq[]
374
+ /** Contiguous event window; entries at or beyond the candidate seq are not committed inputs. */
375
+ events: readonly SessionEvent[]
376
+ /** Absolute sequence of the window's first event. */
377
+ baseSeq: SessionLogOffset
378
+ /** Previously projected messages keyed by their original event sequences. */
379
+ messages: ReadonlyMap<SessionSeq, Message>
380
+ }
381
+ ```
382
+
383
+ ```ts type-equiv
384
+ /** Pure interpretation of one plugin-owned event that changes existing message content. */
385
+ interface SessionMessageProjection<T extends SessionEventType = SessionEventType> {
386
+ /** Event interpreted by this definition; declare it with `@messageProjection` in SessionEventMap. */
387
+ type: T
388
+ /**
389
+ * Validate the complete durable decision before returning any updates. Preserve
390
+ * message identities and publish immutable copies without mutating the input.
391
+ * @param event - candidate event, not yet applied to the supplied history.
392
+ * @param context - history preceding this decision.
393
+ * @returns changed current messages keyed by their original sequences.
394
+ * @throws when the durable decision cannot be applied to this history.
395
+ */
396
+ project(event: SessionEvent<T>, context: SessionMessageProjectionContext): ReadonlyMap<SessionSeq, Message>
397
+ }
398
+ ```
399
+
400
+ ### `SessionSurface` - the live readonly surface projection
401
+
402
+ `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.
403
+
404
+ `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.
405
+
406
+ ```ts type-equiv
407
+ /** Readonly live projection of the message-producing session events. */
408
+ interface SessionSurface {
409
+ /** Current surface event sequences in model-visible order. */
410
+ readonly nodes: readonly SessionSeq[]
411
+ /** Monotonic count of committed positional replacements. */
412
+ readonly replaceGeneration: number
413
+ /** Monotonic count of committed replacements and plugin-owned message changes. */
414
+ readonly contentGeneration: number
415
+ }
416
+ ```
417
+
418
+ ### `SurfaceFoldReplacement` and `SurfaceFoldResult` - a complete surface replay
419
+
420
+ `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.
421
+
422
+ ```ts type-equiv
423
+ /** One replacement operation observed while folding a session surface. */
424
+ interface SurfaceFoldReplacement {
425
+ /** Seq of the event that replaced the prior surface range. */
426
+ seq: SessionSeq
427
+ /** Declared inclusive start seq of the replaced surface range. */
428
+ start: SessionSeq
429
+ /** Declared inclusive end seq of the replaced surface range. */
430
+ end: SessionSeq
431
+ /** Actual surface entries removed by the operation, in surface order. */
432
+ shadowedSeqs: SessionSeq[]
433
+ }
434
+ ```
435
+
436
+ ```ts type-equiv
437
+ /** Complete result of replaying the surface operations in a session log. */
438
+ interface SurfaceFoldResult {
439
+ /** Current surface event sequences in model-visible order. */
440
+ nodes: SessionSeq[]
441
+ /** Replacement operations in event order. */
442
+ replacements: SurfaceFoldReplacement[]
443
+ /** Immutable projected messages, keyed by their original event sequences. */
444
+ projectedMessages: ReadonlyMap<SessionSeq, Message>
445
+ }
446
+ ```
447
+
448
+ ## `Session` public API
449
+
450
+ 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).
451
+
452
+ ```ts public-api
453
+ /**
454
+ * An event-sourced session: an append-only log of {@link SessionEvent}s.
455
+ *
456
+ * Plain class (not a Service) - create live instances via
457
+ * `ctx.sessions.create()` and detached instances via {@link create}.
458
+ * Seeding with an existing event log replays/forks a session.
459
+ * @typert object
460
+ */
461
+ declare class Session {
462
+ /** The ordered surface over this session's event log. */
463
+ get surface(): SessionSurface;
464
+ /**
465
+ * Detached, deep-frozen creation metadata (format version, cwd, lineage,
466
+ * and whether fork history exists). Supplied by the store via `ctx.sessions.create()`. When a
467
+ * `Session` is created without a store-owned header, a minimal header is
468
+ * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
469
+ * `session.header` is always present. Kept out of the event log - it is a
470
+ * storage concern, not replayable conversation state.
471
+ */
472
+ readonly header: SessionHeader;
473
+ /** Number of leading events inherited from this Session's fork parent. */
474
+ readonly inheritedEventCount: SessionLogOffset;
475
+ /** The session identity, derived from its durable header's single copy. */
476
+ get id(): SessionId;
477
+ /**
478
+ * The constructor seed length (0 without one), before any marker appended
479
+ * during construction. Seed events never publish on `session/event`. A
480
+ * marker appended before the store attaches occupies this seq without
481
+ * publishing either; otherwise this seq is available for the next append.
482
+ *
483
+ * This in-process offset is not persisted. A fork seed can already contain
484
+ * the child's inherited marker and synthetic closers, so its child-owned
485
+ * history starts at {@link inheritedEventCount}, before this offset. A
486
+ * resumed Session's seed contains its full stored log, while its inherited
487
+ * count keeps the durable fork cut. Consumers needing complete canonical
488
+ * history start at seq 0.
489
+ */
490
+ readonly firstLiveSeq: SessionLogOffset;
491
+ /**
492
+ * First event produced for this object lifecycle. A new fork includes its
493
+ * child-owned seed marker and closers; a restored Session starts after its
494
+ * complete stored prefix. This in-process capture offset is not persisted.
495
+ */
496
+ readonly firstLifecycleSeq: SessionLogOffset;
497
+
498
+ /**
499
+ * Create a detached session by validating and snapshotting borrowed seed
500
+ * events and storage metadata.
501
+ * @param id - session identity.
502
+ * @param seed - optional borrowed replay or fork events.
503
+ * @param header - optional borrowed storage metadata.
504
+ * @param inheritedEventCount - exact fork-inherited prefix length for a seeded header.
505
+ * @param projections - pure interpreters for plugin-owned message changes.
506
+ * @returns a detached session.
507
+ * @throws when a seed event requires a missing message interpreter or fails validation.
508
+ */
509
+ static create(
510
+ id: SessionId,
511
+ seed?: readonly SessionEvent[],
512
+ header?: SessionHeader,
513
+ inheritedEventCount?: SessionLogOffset,
514
+ projections?: readonly SessionMessageProjection[],
515
+ ): Session;
516
+ /**
517
+ * Restore a detached session by adopting an independently owned or deeply frozen seed.
518
+ * Runtime-required event fields, event envelopes, sequence continuity, surface
519
+ * transitions, and header fields are validated without copying or freezing events.
520
+ * Embedded Assistant streams remain opaque until a stream consumer or storage
521
+ * verifier reads them.
522
+ * @param id - restored session identity.
523
+ * @param seed - independently owned or deeply frozen events.
524
+ * @param header - independently owned storage metadata.
525
+ * @param inheritedEventCount - exact fork-inherited prefix length decoded from storage.
526
+ * @param eventState - aliasing state carried from the operation that produced the seed.
527
+ * @param projections - pure interpreters for plugin-owned message changes.
528
+ * @returns a restored detached session.
529
+ * @throws when a seed event requires a missing message interpreter or fails validation.
530
+ */
531
+ static fromRestore(
532
+ id: SessionId,
533
+ seed: readonly SessionEvent[],
534
+ header: SessionHeader,
535
+ inheritedEventCount: SessionLogOffset,
536
+ eventState: SessionSeedEventState,
537
+ projections?: readonly SessionMessageProjection[],
538
+ ): Session;
539
+ /**
540
+ * Return the immutable event stored at one exact sequence number.
541
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
542
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
543
+ * @param seq - event sequence number.
544
+ * @returns the accepted event, or undefined when the log does not contain it.
545
+ */
546
+ eventAt(seq: SessionSeq): SessionEvent | undefined;
547
+ /**
548
+ * Materialize an immutable snapshot of a half-open event sequence range.
549
+ * A full current snapshot is reused until the next append; every previously
550
+ * returned snapshot remains stable after later appends.
551
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
552
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
553
+ * @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
554
+ * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
555
+ * @returns a frozen array of the selected deeply frozen events.
556
+ */
557
+ snapshotEvents(
558
+ fromSeq: SessionLogOffset = SessionLogOffset(0),
559
+ toSeqExclusive: SessionLogOffset = this.seq,
560
+ ): readonly SessionEvent[];
561
+ /**
562
+ * Return this Session's events after its fork-inherited prefix.
563
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
564
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
565
+ * @returns a fresh array containing child-owned events in log order.
566
+ */
567
+ ownEvents(): readonly SessionEvent[];
568
+ /**
569
+ * Whether one existing event position is outside the fork-inherited prefix.
570
+ * @param seq - event position in this Session.
571
+ * @returns true when the event belongs to this Session rather than its parent.
572
+ */
573
+ isOwnSeq(seq: SessionSeq): boolean;
574
+ /** The next event's sequence number - always the log length (the `seq = log.length` contiguity contract). */
575
+ get seq(): SessionLogOffset;
576
+ /**
577
+ * Append one typed event to the log and synchronously notify observers via
578
+ * the store-owned, module-private publication hooks. The hot path never blocks
579
+ * on I/O - persistence plugins buffer asynchronously. Once the event enters
580
+ * the log, the append is committed: observer failures are logged and
581
+ * contained per listener, so they do not change the return value or prevent
582
+ * later listeners from observing the same accepted event.
583
+ *
584
+ * @param type - The event type (key of {@link SessionEventMap}).
585
+ * @param data - The event payload; must be JSON-serializable.
586
+ * @param opts - Surface metadata: `surfaceOp` controls how the event enters
587
+ * the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier
588
+ * events this one derives from. REQUIRED for
589
+ * {@link SurfaceEventType} events (every message-producing event must
590
+ * declare how it joins the surface, the sole source of derived model
591
+ * history) and
592
+ * rejected by the compiler for non-surface types like `turn/start` or
593
+ * `assistant/attempt`. Assistant messages embed their exact provider
594
+ * stream and cannot cite top-level source events.
595
+ * @returns the logged event - its assigned `seq`/`time` plus the SNAPSHOT of
596
+ * `data` that entered the log, so reading `event.data` back sees the logged
597
+ * value, never the caller's still-mutable input.
598
+ * @throws if `data` or surface metadata is not losslessly JSON-serializable
599
+ * (BigInt, function, symbol, undefined, negative zero, non-finite number,
600
+ * circular reference, sparse array, or an exotic object such as
601
+ * Map/Set/Date/class instance), or when the candidate violates the
602
+ * request-header empty-field or tool-error consistency rules, or the
603
+ * canonical surface contract (marker shape and eligibility, unique
604
+ * earlier source-event references, positional replacement validity, and complete
605
+ * shadowed-node coverage). One iterative pass reads, validates, and
606
+ * copies each nested value once, so a stateful getter cannot supply one value
607
+ * to validation and another to storage. The event log is the durable source
608
+ * of truth, so a bad event fails at the append site rather than later during
609
+ * a backend flush. A synchronous internal dispatch validation failure or an
610
+ * append reentered while this acceptance/publication boundary is open also
611
+ * rejects before the log changes.
612
+ */
613
+ append<T extends SessionEventType>(
614
+ type: T,
615
+ data: SessionEventMap[T],
616
+ ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent<T>] : []
617
+ ): SessionEvent<T>;
618
+ /**
619
+ * The {@link EpochHeader} in force after the log's last header event - the
620
+ * header the NEXT request will be compared against - or undefined before
621
+ * the first `request/header` snapshot. The live, incrementally-maintained
622
+ * form of `foldRequestHeader(session.snapshotEvents())`: each header event is folded
623
+ * once, when first seen, so a per-step read costs O(new events).
624
+ * @returns the folded header, or undefined when no header event exists yet.
625
+ */
626
+ requestHeader(): EpochHeader | undefined;
627
+ /**
628
+ * Return the latest resolved route metadata, or `undefined` before the first
629
+ * `request/context` event. Each event is folded once.
630
+ * @returns the latest immutable route metadata.
631
+ */
632
+ requestContext(): RequestContext | undefined;
633
+ /**
634
+ * Fold unseen committed events into capability-independent tool history.
635
+ * Initial access reconstructs inherited history; later reads consume only new events.
636
+ * @returns an immutable snapshot for LLM request projection, including historical addition definitions.
637
+ */
638
+ toolHistory(): ToolHistory;
639
+ /**
640
+ * Derive the LLM message history by walking the ordered sequences of
641
+ * message-producing events maintained by `surfaceOp` markers. The
642
+ * surface is the single source of derived history: every message-producing
643
+ * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
644
+ * turn boundary) is correctly absent, and a compaction `replace` deletes the
645
+ * shadowed nodes from the derivation. The projection rules are
646
+ * {@link deriveEventMessage}, with logged message projections applied
647
+ * without changing node membership or message identity.
648
+ *
649
+ * CACHED: pure tail growth costs O(new nodes); a replacement or message projection
650
+ * ({@link SessionSurface.contentGeneration}) rebuilds. The returned array is
651
+ * a fresh snapshot per call (later appends never grow an array a caller
652
+ * already holds); the `Message` objects in it are SHARED and **deep-frozen**.
653
+ * Unchanged content reuses frozen event data; projected blocks are frozen
654
+ * derived copies. Consumers cannot mutate the log through either form.
655
+ * @returns a fresh array of the shared, frozen derived history.
656
+ */
657
+ deriveMessages(): Message[];
658
+ /**
659
+ * Project one event with all committed message projections applied.
660
+ * The original durable event remains unchanged.
661
+ * @param event - the event to project.
662
+ * @returns the derived message, or null when the event produces none.
663
+ */
664
+ deriveEventMessage(event: SessionEvent): Message | null;
665
+ }
666
+ ```
667
+
668
+ ## Derived history: `deriveMessages()` and `deriveEventMessage()`
669
+
670
+ `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:
671
+
672
+ - `user/message` → a user message carrying exact `content`; an optional envelope remains log-only display metadata.
673
+ - `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.
674
+ - `tool/result` → a first-class tool-role message carrying its result content and tool-call identity.
675
+ - `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.
676
+
677
+ 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.
678
+
679
+ ## Live-session fork API
680
+
681
+ `ctx.sessions.create(id, { seed, meta })` is the low-level replay/fork primitive. For ordinary live-session forks, `SessionStore` exposes one policy API:
682
+
683
+ - `fork(source, boundary?, childSessionId?)` accepts a live `Session` object or live `SessionId`, selects source events through the inclusive `SessionSeq` boundary (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, `parentSession`, `isSeeded: true`, the exact `inheritedEventCount`, and inherited `cwd`.
684
+
685
+ 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.
686
+
687
+ ## Why a turn ended: `TurnEndReasonMap`
688
+
689
+ `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.
690
+
691
+ ```ts type-equiv
692
+ /** Durable cancellation cause, including imports whose original coarse record carried no cause. */
693
+ type TurnEndCancelCause = AgentCancelCause | { readonly kind: 'legacy' }
694
+ ```
695
+
696
+ ```ts type-equiv
697
+ /**
698
+ * Why a turn ended. Merge-extensible sum type.
699
+ */
700
+ interface TurnEndReasonMap {
701
+ completed: { kind: 'completed' }
702
+ /** A cancellation request interrupted the live turn. */
703
+ aborted: { kind: 'aborted'; reason: TurnEndCancelCause }
704
+
705
+ blocked: { kind: 'blocked' }
706
+ /**
707
+ * The turn failed. `error` is always a structured failure: the `LlmError`
708
+ * facts verbatim, or `{ message: errorChain(error), code: 'UNKNOWN' }`
709
+ * flattened from any other error.
710
+ */
711
+ error: { kind: 'error'; error: LlmFailure }
712
+ /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */
713
+ 'max-tokens': { kind: 'max-tokens' }
714
+ /**
715
+ * A crash-orphaned turn was closed after the fact: agent-loop resume appends
716
+ * this closer for a stored log whose last turn never ended, and session-query
717
+ * synthesizes it on cold reads. The loop never emits this marker live, and
718
+ * the events recorded before the crash remain intact.
719
+ */
720
+ interrupted: { kind: 'interrupted' }
721
+ /**
722
+ * Fork-seed construction closed a turn that was still open at the fork
723
+ * boundary in the source session. Only fork seeds carry this marker - the
724
+ * loop never emits it - and the source events before the boundary remain
725
+ * intact in the child.
726
+ */
727
+ forked: { kind: 'forked' }
728
+ }
729
+ ```
730
+
731
+ `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.
732
+
733
+ ## Execution enclosure and standalone events
734
+
735
+ 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)`.
736
+
737
+ 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](../../.agents/notes/implemented/simplification/2026-07-28-remove-synthetic-log-only-turns.md).
738
+
739
+ ## The end-seed boundary: `session/end-seed`
740
+
741
+ `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.
742
+
743
+ 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.
744
+
745
+ 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/*`.
746
+
747
+ 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.
748
+
749
+ ## Plugin-contributed log-only events
750
+
751
+ 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; the compaction seam's `compaction/*` semantics are discussed on [compaction.md](compaction.md).
752
+
753
+ 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).
754
+
755
+ 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.
756
+
757
+ ## Durability contract
758
+
759
+ 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.
760
+
761
+ The backends that consume this contract are on [persistence.md](persistence.md).
762
+
763
+ ## Remote catalog and workspace opening
764
+
765
+ `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.
766
+
767
+ `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.
768
+
769
+ 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.
770
+
771
+ <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) - do not edit between markers -->
772
+
773
+ <a id="cordis-surface"></a>
774
+
775
+ ## Cordis API
776
+
777
+ 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).
778
+
779
+ <a id="ctxsessioncontroller--sessioncontroller"></a>
780
+
781
+ ### `ctx.sessionController` - `SessionController`
782
+
783
+ Host service backing the generated `ctx.remote.session` namespace.
784
+
785
+ ```ts cordis-catalog
786
+ /**
787
+ * Resolve or resume one ordinary Session for another Host API domain.
788
+ * @param sessionId - Session identity whose Agent owns the operation.
789
+ * @returns the live Agent or the stable Session-domain failure.
790
+ */
791
+ resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult>
792
+
793
+ /**
794
+ * Inspect one attached or persisted Session without activating its Agent.
795
+ * @param sessionId - durable Session identity.
796
+ * @param signal - optional caller cancellation for persistence reads.
797
+ * @returns the current attached state or persisted header and event prefix.
798
+ */
799
+ inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise<SessionInspection>
800
+
801
+ /**
802
+ * Read all visible Session rows without resuming an Agent.
803
+ * @param _request - reserved empty list request.
804
+ * @param signal - cancellation for persistence reads.
805
+ * @returns visible Session summaries ordered by activity.
806
+ */
807
+ @Remote('list') async list(_request: SessionListRequest, signal: AbortSignal): Promise<SessionListValue>
808
+
809
+ /**
810
+ * Search visible Session content without resuming an Agent.
811
+ * @param request - literal message-content query.
812
+ * @param signal - cancellation for list and search reads.
813
+ * @returns authorized bounded Session search results.
814
+ */
815
+ @Remote('search') search(request: SessionSearchRequest, signal: AbortSignal): Promise<SessionSearchValue>
816
+
817
+ /**
818
+ * Create or idempotently adopt one ordinary Session.
819
+ * @param request - requested identity, location, and Agent preset.
820
+ * @returns the Session identity and resolved preset when configured.
821
+ */
822
+ @Remote('create') create(request: SessionCreateRequest): Promise<SessionCreateValue>
823
+
824
+ /**
825
+ * Select one Session-local model after explicitly resuming the Session; save the default in the background.
826
+ * @param request - Session identity and requested model selection.
827
+ * @returns the normalized selection installed for the Session, without waiting for default persistence.
828
+ */
829
+ @Remote('selectModel') selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue>
830
+
831
+ /**
832
+ * Select the first available account model after login when no provider API key is configured.
833
+ * @returns after saving the first available model or retaining the existing default.
834
+ */
835
+ @Remote async initializeDefaultModel(): Promise<void>
836
+
837
+ /**
838
+ * Describe every currently routable model for Host-generation selectors.
839
+ * @returns provider-grouped models, the deployment default, and isolated provider failures.
840
+ */
841
+ @Remote('modelCatalog') modelCatalog(): Promise<ModelCatalog>
842
+
843
+ /**
844
+ * Report whether this deployment can hand a Session workspace path to a native desktop.
845
+ * @returns true when the matching open operation is available.
846
+ */
847
+ @Remote canOpenWorkspacePath(): boolean
848
+
849
+ /**
850
+ * Describe the serving desktop for authenticated file-action routes.
851
+ * @returns Host name, configured availability, and platform-specific file-manager behavior.
852
+ */
853
+ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | 'explorer' | 'directory' | null }
854
+
855
+ /**
856
+ * Verify one path through the composed filesystem and open it on the Host desktop.
857
+ * @param request - path after best-effort Session workspace resolution.
858
+ * @param signal - caller lifetime; abort terminates the native command.
859
+ * @returns confirmation after the native opener accepts the path.
860
+ * @throws RemoteError when the request is invalid, has no verified Host mapping, is cancelled, or the opener fails.
861
+ */
862
+ @Remote('openWorkspacePath') async openWorkspacePath( request: SessionOpenWorkspacePathRequest, signal: AbortSignal, ): Promise<SessionOpenWorkspacePathValue>
863
+
864
+ /**
865
+ * Query current file handlers on the serving desktop without activating an Agent.
866
+ * @param request - file path in Host filesystem syntax.
867
+ * @param signal - caller lifetime, propagated to filesystem and desktop queries.
868
+ * @returns OS application names, icons, and default selection; empty when desktop opening is unavailable.
869
+ * @throws RemoteError when the path is invalid, the query is cancelled, or native discovery fails.
870
+ */
871
+ @Remote('workspacePathApplications') async workspacePathApplications( request: { readonly path: string }, signal: AbortSignal, ): Promise<readonly SessionWorkspacePathApplication[]>
872
+
873
+ /**
874
+ * Rename one Session after explicitly resuming it.
875
+ * @param request - Session identity and proposed title.
876
+ * @returns the accepted title and durable event sequence.
877
+ */
878
+ @Remote('rename') rename(request: SessionRenameRequest): Promise<SessionRenameValue>
879
+
880
+ /**
881
+ * Fork one cold-readable exact event prefix into a new Session. An omitted
882
+ * boundary selects the latest completed-turn prefix; an open cut receives
883
+ * synthetic fork closers.
884
+ * @param request - source Session and optional exact inclusive event boundary.
885
+ * @returns the new Session identity.
886
+ */
887
+ @Remote('fork') fork(request: SessionForkRequest): Promise<SessionForkValue>
888
+
889
+ /**
890
+ * Admit one prompt after explicitly resuming its Session.
891
+ * @param request - Session identity, prompt content, source metadata, and delivery mode.
892
+ * @param signal - caller cancellation before prompt admission begins.
893
+ * @returns acknowledgement that the Agent accepted the prompt.
894
+ */
895
+ @Remote('prompt') prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<SessionPromptValue>
896
+
897
+ /**
898
+ * Read one image proven reachable from the addressed Session log.
899
+ * @param request - Session and attachment identities used for authorization.
900
+ * @returns the durable attachment reference and base64-encoded bytes.
901
+ */
902
+ @Remote('attachment') attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue>
903
+
904
+ /**
905
+ * Mutate one still-pending queue occurrence, resuming a cold Agent first.
906
+ * @param request - Session, queue item, and requested mutation.
907
+ * @returns acknowledgement that the queue mutation was applied.
908
+ */
909
+ @Remote('updateQueue') updateQueue(request: SessionUpdateQueueRequest): Promise<SessionUpdateQueueValue>
910
+
911
+ /**
912
+ * Cancel one active Agent turn without dropping its pending inbox.
913
+ * @param request - Session whose active Agent turn is cancelled.
914
+ * @returns acknowledgement that cancellation was requested.
915
+ */
916
+ @Remote('cancel') cancel(request: SessionCancelRequest): SessionCancelValue
917
+
918
+ /**
919
+ * Read one cold-safe, message-aligned Session history page.
920
+ * @param request - durable address, backward cursor, and page budget.
921
+ * @param signal - cancellation for persistence reads.
922
+ * @returns one chronological page.
923
+ */
924
+ @Remote('page') page(request: SessionPageRequest, signal: AbortSignal): Promise<SessionPage>
925
+
926
+ /**
927
+ * Follow one Session log from its opening or resume cursor.
928
+ * @param request - durable address and last committed sequence already held by the caller.
929
+ * @param signal - cancellation owned by the Remote stream carrier.
930
+ * @returns a complete opening snapshot followed by gap-free durable event
931
+ * frames and optional cursorless assistant-stream frames.
932
+ */
933
+ @Remote({ mode: 'stream' }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame>
934
+
935
+ /**
936
+ * Read all registered projections without activating an Agent.
937
+ * @param request - Session whose current values are required.
938
+ * @param signal - cancellation for the Session observation.
939
+ * @returns complete baseline, or null when the Session does not exist.
940
+ */
941
+ @Remote('projections') async projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise<SessionProjectionsValue>
942
+
943
+ /**
944
+ * Stream a complete live-control baseline followed by replacement frames.
945
+ * @param signal - cancellation owned by the Remote stream carrier.
946
+ * @returns one complete baseline followed by live replacement frames.
947
+ */
948
+ @Remote({ mode: 'stream' }) control(signal: AbortSignal): AsyncIterable<SessionControlFrame>
949
+ ```
950
+
951
+ Types: [SessionId](core.md) · [SessionInspection](persistence.md) · [SessionSearchRequest](session-query.md)
952
+
953
+ Source: [`packages/api/session-controller/src/index.ts`](../../packages/api/session-controller/src/index.ts)
954
+
955
+ <a id="ctxsessions--sessionstore"></a>
956
+
957
+ ### `ctx.sessions` - `SessionStore`
958
+
959
+ In-memory session store (`ctx.sessions`).
960
+
961
+ 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.
962
+
963
+ ```ts cordis-catalog
964
+ /**
965
+ * Register one event interpreter for live creation, restore, and fork.
966
+ * Disposing the contribution makes sessions that used it refuse further derivation.
967
+ * @param projection - pure definition owned by the event's plugin.
968
+ * @returns the fiber-owned disposer.
969
+ * @throws when another definition already owns this event type.
970
+ */
971
+ registerMessageProjection(projection: SessionMessageProjection): () => Promise<void>
972
+
973
+ /**
974
+ * Create a session owned by the calling fiber: disposing that fiber stops
975
+ * event notification and removes the session from the store. `options.seed`
976
+ * populates the session with a copy of those events (replay/fork);
977
+ * `options.meta` attaches creation metadata (validated absolute `cwd`, seed
978
+ * and parent lineage, and delegation depth) as the immutable
979
+ * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).
980
+ *
981
+ * For an agent whose session must be torn down IN ORDER with its loop (so the
982
+ * loop's final events are published before the store attachment ends), do NOT use this
983
+ * - fold the session lifecycle into the agent's own effect via
984
+ * {@link prepare} + {@link enter} + {@link announce} (see
985
+ * `dsh-agent-loop`'s creation transaction).
986
+ *
987
+ * @param id - the session id; omitted, the store mints `session-<n>`.
988
+ * @param options - seed events and/or creation metadata for the header.
989
+ * @returns the live session, already entered and announced.
990
+ * @throws if a session with `id` already exists, metadata is not a plain
991
+ * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
992
+ * non-absolute path (storage backends key directories off it).
993
+ */
994
+ create(id?: SessionId, options?: CreateSessionOptions): Session
995
+
996
+ /**
997
+ * Build a session WITHOUT entering it into the store - validate the id/cwd and
998
+ * construct the {@link Session} (with its immutable {@link SessionHeader}).
999
+ * Pairs with {@link enter} + {@link announce}: a caller that owns a composite
1000
+ * `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
1001
+ * effect so a fiber unload tears the session + agent down as a single ORDERED
1002
+ * chain rather than as racing sibling effects - which would remove the publication hooks
1003
+ * before the driver's closing events commit, dropping them.
1004
+ *
1005
+ * @param id - the session id; omitted, the store mints `session-<n>`.
1006
+ * @param options - seed events and/or creation metadata for the header. With
1007
+ * `eventState`, every seed event is either independently owned or any
1008
+ * shared value is deeply frozen; {@link Session.fromRestore} validates and
1009
+ * adopts those values without copying or freezing them.
1010
+ * @returns the constructed session, NOT yet in the store.
1011
+ * @throws if a session with `id` already exists, metadata is not a plain
1012
+ * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
1013
+ * non-absolute path.
1014
+ */
1015
+ prepare(id?: SessionId, options?: PrepareSessionOptions): Session
1016
+
1017
+ /**
1018
+ * Enter a {@link prepare}d session into the store: install the module-private
1019
+ * append publication hooks and add it to the store. Returns the DETACH
1020
+ * disposer (hooks + store removal). Does NOT emit `session/created` -
1021
+ * the caller yields this disposer inside its effect and THEN calls
1022
+ * {@link announce}, so a throwing `session/created` listener rolls the attach
1023
+ * back instead of leaking it.
1024
+ *
1025
+ * Re-checks the id for a duplicate: `prepare` and `enter` are public
1026
+ * cross-package primitives and a caller may interleave arbitrary work (or
1027
+ * another create) between them, so a stale prepared session must NOT overwrite
1028
+ * a live store entry of the same id - its detach disposer would later delete
1029
+ * the REAL session. The {@link create} convenience and the agent factory call
1030
+ * the two back-to-back so they never trip this, but the public API cannot
1031
+ * assume that.
1032
+ *
1033
+ * @param session - a {@link prepare}d session not yet in the store.
1034
+ * @returns the detach disposer (publication hooks + store removal). When called from
1035
+ * a synchronous `session/created` listener, removal and disposal wait until
1036
+ * that creation dispatch unwinds.
1037
+ * @throws if a session with this id is already in the store.
1038
+ */
1039
+ enter(session: Session): () => void
1040
+
1041
+ /** Emit `session/created` exactly once for an {@link enter}ed session (with
1042
+ * the carrier {@link enter} captured). Separate from {@link enter} so the
1043
+ * caller can yield the detach disposer first (rollback safety - see
1044
+ * {@link enter}).
1045
+ * @param session - the entered session to announce to listeners.
1046
+ * @throws if the session is not live or its announcement already began,
1047
+ * including a reentrant call from a creation listener. */
1048
+ announce(session: Session): void
1049
+
1050
+ /**
1051
+ * Dispatch the awaited `session/flush` durability checkpoint for `session`,
1052
+ * with the carrier captured at {@link enter}. THE flush entry point: the
1053
+ * store owns the carrier, so callers (the checkpoint policy's per-request
1054
+ * barrier, goal-round-driver's idle checkpoint, teardown drains, and consumers
1055
+ * that flush themselves before reading storage) must come through here
1056
+ * rather than dispatch a raw `ctx.parallel('session/flush', …)` - one owner,
1057
+ * one spelling, and the scoped-dispatch invariant can pin it.
1058
+ * @param session - the session whose buffered events must reach durable storage.
1059
+ * @returns whether at least one durability listener participated, after every
1060
+ * listener has settled successfully.
1061
+ * @throws the first registered listener failure after every listener settles.
1062
+ */
1063
+ async flush(session: Session): Promise<boolean>
1064
+
1065
+ /**
1066
+ * Look up a live session.
1067
+ * @param id - the session id to look up.
1068
+ * @returns the session, or undefined when no live session has that id.
1069
+ */
1070
+ get(id: SessionId): Session | undefined
1071
+
1072
+ /**
1073
+ * All live sessions, in creation order.
1074
+ * @returns a fresh array; mutating it does not affect the store.
1075
+ */
1076
+ list(): Session[]
1077
+
1078
+ /**
1079
+ * Create a live child session from an exact prefix of a live source.
1080
+ * `boundary` is an inclusive source event seq; omitted means the source's
1081
+ * current last event. An open tail receives synthetic tool results and
1082
+ * step/turn closers with the forked cause. Closed steps and turns remain
1083
+ * unchanged, including any failed tool calls already missing results.
1084
+ * `inheritedEventCount` counts only copied source events, excluding these closers.
1085
+ *
1086
+ * @param source - Live source session object or id.
1087
+ * @param boundary - Inclusive source event seq to fork through; omitted means
1088
+ * the source's current last event, and omitted on an empty source forks an
1089
+ * empty child.
1090
+ * @param childSessionId - Optional child session id; omitted delegates to
1091
+ * `SessionStore`'s id policy.
1092
+ * @returns The created live child session.
1093
+ */
1094
+ fork(source: SessionForkSource, boundary?: SessionSeq, childSessionId?: SessionId): Session
1095
+ ```
1096
+
1097
+ Types: [CreateSessionOptions](persistence.md) · [PrepareSessionOptions](persistence.md) · [SessionId](core.md)
1098
+
1099
+ Source: [`packages/core/session/src/index.ts`](../../packages/core/session/src/index.ts)
1100
+
1101
+ <a id="api-session-events"></a>
1102
+
1103
+ ### `api-session/*` events
1104
+
1105
+ <a id="api-sessionactivity--emit"></a>
1106
+
1107
+ #### `api-session/activity` - emit
1108
+
1109
+ One user-authored durable message advanced Session list activity.
1110
+
1111
+ ```ts cordis-catalog
1112
+ /**
1113
+ * One user-authored durable message advanced Session list activity.
1114
+ * @mode emit
1115
+ * @param sessionId - addressed Session identity.
1116
+ * @param updatedAt - durable message time used for list ordering.
1117
+ */
1118
+ 'api-session/activity'(sessionId: SessionId, updatedAt: number): void
1119
+ ```
1120
+
1121
+ Types: [SessionId](core.md)
1122
+
1123
+ Source: [`packages/api/session-controller/src/types.ts`](../../packages/api/session-controller/src/types.ts)
1124
+
1125
+ <a id="api-sessionadded--emit"></a>
1126
+
1127
+ #### `api-session/added` - emit
1128
+
1129
+ A Session became visible or its Agent was created or disposed. Consumers upsert the summary and replace its current running and availability state.
1130
+
1131
+ ```ts cordis-catalog
1132
+ /**
1133
+ * A Session became visible or its Agent was created or disposed.
1134
+ * Consumers upsert the summary and replace its current running and availability state.
1135
+ * @mode emit
1136
+ * @param summary - current list row for the Session.
1137
+ */
1138
+ 'api-session/added'(summary: SessionSummary): void
1139
+ ```
1140
+
1141
+ Source: [`packages/api/session-controller/src/types.ts`](../../packages/api/session-controller/src/types.ts)
1142
+
1143
+ <a id="api-sessionerror--emit"></a>
1144
+
1145
+ #### `api-session/error` - emit
1146
+
1147
+ One Agent failed outside a durable turn position.
1148
+
1149
+ ```ts cordis-catalog
1150
+ /**
1151
+ * One Agent failed outside a durable turn position.
1152
+ * @mode emit
1153
+ * @param sessionId - Agent and Session identity.
1154
+ * @param message - user-safe failure chain.
1155
+ */
1156
+ 'api-session/error'(sessionId: SessionId, message: string): void
1157
+ ```
1158
+
1159
+ Types: [SessionId](core.md)
1160
+
1161
+ Source: [`packages/api/session-controller/src/types.ts`](../../packages/api/session-controller/src/types.ts)
1162
+
1163
+ <a id="api-sessionremoved--emit"></a>
1164
+
1165
+ #### `api-session/removed` - emit
1166
+
1167
+ A Session left the live Host registry.
1168
+
1169
+ ```ts cordis-catalog
1170
+ /**
1171
+ * A Session left the live Host registry.
1172
+ * @mode emit
1173
+ * @param sessionId - removed Session identity.
1174
+ */
1175
+ 'api-session/removed'(sessionId: SessionId): void
1176
+ ```
1177
+
1178
+ Types: [SessionId](core.md)
1179
+
1180
+ Source: [`packages/api/session-controller/src/types.ts`](../../packages/api/session-controller/src/types.ts)
1181
+
1182
+ <a id="api-sessionstatus--emit"></a>
1183
+
1184
+ #### `api-session/status` - emit
1185
+
1186
+ One Agent changed running state.
1187
+
1188
+ ```ts cordis-catalog
1189
+ /**
1190
+ * One Agent changed running state.
1191
+ * @mode emit
1192
+ * @param sessionId - Agent and Session identity.
1193
+ * @param running - whether the Agent is running.
1194
+ */
1195
+ 'api-session/status'(sessionId: SessionId, running: boolean): void
1196
+ ```
1197
+
1198
+ Types: [SessionId](core.md)
1199
+
1200
+ Source: [`packages/api/session-controller/src/types.ts`](../../packages/api/session-controller/src/types.ts)
1201
+
1202
+ <a id="session-events"></a>
1203
+
1204
+ ### `session/*` events
1205
+
1206
+ <a id="sessioncreated--emit"></a>
1207
+
1208
+ #### `session/created` - emit
1209
+
1210
+ 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.
1211
+
1212
+ ```ts cordis-catalog
1213
+ /**
1214
+ * Creation announcement during session publication. A synchronous throw vetoes and rolls
1215
+ * back with a paired disposal; detach requested during dispatch is deferred.
1216
+ * A returned-promise rejection is logged but cannot retroactively veto this
1217
+ * synchronous boundary.
1218
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
1219
+ * receive only sessions entered through that agent's context.
1220
+ * @param session - the session just entered and announced.
1221
+ * @dshScopeScan unsupported
1222
+ * @mode emit
1223
+ */
1224
+ 'session/created'(this: Scoped<Session>, session: Session): void
1225
+ ```
1226
+
1227
+ Types: [Scoped](scope.md)
1228
+
1229
+ Source: [`packages/core/session/src/index.ts`](../../packages/core/session/src/index.ts)
1230
+
1231
+ <a id="sessiondisposed--emit"></a>
1232
+
1233
+ #### `session/disposed` - emit
1234
+
1235
+ 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.
1236
+
1237
+ ```ts cordis-catalog
1238
+ /**
1239
+ * Emitted once when an announced session leaves the store, including
1240
+ * publication rollback, but never for an entry whose creation announcement
1241
+ * did not begin. Listener failures are logged and contained.
1242
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope.
1243
+ * @param session - the session that is no longer live in the store.
1244
+ * @dshScopeScan unsupported
1245
+ * @mode emit
1246
+ */
1247
+ 'session/disposed'(this: Scoped<Session>, session: Session): void
1248
+ ```
1249
+
1250
+ Types: [Scoped](scope.md)
1251
+
1252
+ Source: [`packages/core/session/src/index.ts`](../../packages/core/session/src/index.ts)
1253
+
1254
+ <a id="sessionevent--emit"></a>
1255
+
1256
+ #### `session/event` - emit
1257
+
1258
+ 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.
1259
+
1260
+ ```ts cordis-catalog
1261
+ /**
1262
+ * Post-commit, fire-and-forget append feed. The listener snapshot resolves
1263
+ * before the log push, but callbacks run after it; observer failures are
1264
+ * logged and contained without making the committed append fail.
1265
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
1266
+ * receive only events from sessions entered through that agent's context.
1267
+ * @param session - the session whose log grew.
1268
+ * @param event - the appended event, exactly as recorded.
1269
+ * @dshScopeScan unsupported
1270
+ * @mode emit
1271
+ */
1272
+ 'session/event'(this: Scoped<Session>, session: Session, event: SessionEvent): void
1273
+ ```
1274
+
1275
+ Types: [Scoped](scope.md)
1276
+
1277
+ Source: [`packages/core/session/src/index.ts`](../../packages/core/session/src/index.ts)
1278
+
1279
+ <a id="sessionflush--parallel"></a>
1280
+
1281
+ #### `session/flush` - parallel
1282
+
1283
+ 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.
1284
+
1285
+ ```ts cordis-catalog
1286
+ /**
1287
+ * Awaited parallel durability checkpoint: every listener runs and the
1288
+ * caller awaits all of them, with no waterfall veto. Scope-filtered dispatch
1289
+ * (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
1290
+ * @param session - the session whose buffered events must reach durable storage.
1291
+ * @dshScopeScan unsupported
1292
+ * @mode parallel
1293
+ */
1294
+ 'session/flush'(this: Scoped<Session>, session: Session): Promise<void> | void
1295
+ ```
1296
+
1297
+ Types: [Scoped](scope.md)
1298
+
1299
+ Source: [`packages/core/session/src/index.ts`](../../packages/core/session/src/index.ts)
1300
+ <!-- END GENERATED cordis-surface -->