dsh-plugin-dev-kb 1.8.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +186 -178
  2. package/README.en.md +172 -172
  3. package/README.md +183 -183
  4. package/kb/INDEX.md +236 -234
  5. package/kb/README.md +88 -88
  6. package/kb/extra/AGENTS.md +77 -77
  7. package/kb/extra/deepseek-llm-api-wire-extensions.md +162 -162
  8. package/kb/extra/deepseek-llm-api-wire-extensions.zh.md +162 -162
  9. package/kb/extra/defensive-patterns/package-surface.md +233 -232
  10. package/kb/extra/defensive-patterns/package-surface.zh.md +233 -232
  11. package/kb/extra/defensive-patterns/remote-and-api.md +117 -117
  12. package/kb/extra/defensive-patterns/remote-and-api.zh.md +117 -117
  13. package/kb/extra/development.md +221 -221
  14. package/kb/extra/development.zh.md +228 -228
  15. package/kb/extra/event-producer-consumer.md +133 -123
  16. package/kb/extra/event-producer-consumer.zh.md +135 -125
  17. package/kb/extra/module-graph.md +1961 -1888
  18. package/kb/extra/module-graph.zh.md +1963 -1890
  19. package/kb/extra/persistence-changes/2026-11-05-timeline-priority-notice.md +60 -0
  20. package/kb/extra/persistence-changes/2026-11-05-timeline-priority-notice.zh.md +60 -0
  21. package/kb/extra/persistence-changes/README.md +92 -92
  22. package/kb/extra/persistence-changes/README.zh.md +92 -92
  23. package/kb/extra/persistence-changes/historical-formats/README.md +75 -75
  24. package/kb/extra/persistence-changes/historical-formats/README.zh.md +75 -75
  25. package/kb/extra/persistence-changes/releases/README.md +103 -103
  26. package/kb/extra/persistence-changes/releases/README.zh.md +103 -103
  27. package/kb/extra/rescope.md +55 -55
  28. package/kb/extra/rescope.zh.md +55 -55
  29. package/kb/extra/subsystems/boot.md +631 -621
  30. package/kb/extra/subsystems/boot.zh.md +631 -621
  31. package/kb/extra/subsystems/computer-use.md +179 -137
  32. package/kb/extra/subsystems/computer-use.zh.md +179 -137
  33. package/kb/extra/subsystems/extensions.md +387 -384
  34. package/kb/extra/subsystems/extensions.zh.md +387 -384
  35. package/kb/extra/subsystems/feedback.md +418 -400
  36. package/kb/extra/subsystems/feedback.zh.md +418 -400
  37. package/kb/extra/subsystems/forge.md +2169 -1226
  38. package/kb/extra/subsystems/forge.zh.md +2171 -1226
  39. package/kb/extra/subsystems/liveshare.md +167 -158
  40. package/kb/extra/subsystems/liveshare.zh.md +167 -158
  41. package/kb/extra/subsystems/mcp.md +237 -234
  42. package/kb/extra/subsystems/mcp.zh.md +237 -234
  43. package/kb/extra/subsystems/office-kit.md +122 -0
  44. package/kb/extra/subsystems/office-kit.zh.md +122 -0
  45. package/kb/extra/subsystems/working-directory.md +95 -64
  46. package/kb/extra/subsystems/working-directory.zh.md +95 -64
  47. package/kb/extra/subsystems/worktrees.md +187 -127
  48. package/kb/extra/subsystems/worktrees.zh.md +187 -127
  49. package/kb/extra/upgrade-guide/v0.2.1-alpha.1/python-ptc-sandbox/guide.md +21 -21
  50. package/kb/extra/upgrade-guide/v0.2.1-alpha.1/python-ptc-sandbox/guide.zh.md +21 -21
  51. package/kb/extra/upgrade-guide/v0.2.1-rc.4/sandbox-unsupported-policy-error/guide.md +18 -0
  52. package/kb/extra/upgrade-guide/v0.2.1-rc.4/sandbox-unsupported-policy-error/guide.zh.md +18 -0
  53. package/kb/extra/upgrade-guide/v0.2.2-alpha.2/llm-error-builtin-codes/guide.md +18 -0
  54. package/kb/extra/upgrade-guide/v0.2.2-alpha.2/llm-error-builtin-codes/guide.zh.md +18 -0
  55. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-kit-package/guide.md +34 -0
  56. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-kit-package/guide.zh.md +34 -0
  57. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-operation-tools/guide.md +49 -0
  58. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-operation-tools/guide.zh.md +49 -0
  59. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-skill-resources/guide.md +36 -0
  60. package/kb/extra/upgrade-guide/v0.2.2-alpha.3/office-skill-resources/guide.zh.md +36 -0
  61. package/kb/extra/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md +26 -0
  62. package/kb/extra/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.zh.md +26 -0
  63. package/kb/extra/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md +22 -0
  64. package/kb/extra/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.zh.md +22 -0
  65. package/kb/extra/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md +21 -0
  66. package/kb/extra/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md +21 -0
  67. package/kb/extra/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md +23 -0
  68. package/kb/extra/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md +23 -0
  69. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.md +20 -0
  70. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.zh.md +20 -0
  71. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md +18 -0
  72. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md +18 -0
  73. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +23 -0
  74. package/kb/extra/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +23 -0
  75. package/kb/extra/upgrade-guide/v0.2.2-rc.1/dsh-doc-skill/guide.md +35 -0
  76. package/kb/extra/upgrade-guide/v0.2.2-rc.1/dsh-doc-skill/guide.zh.md +35 -0
  77. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md +26 -0
  78. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md +26 -0
  79. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md +26 -0
  80. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.zh.md +26 -0
  81. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.md +19 -0
  82. package/kb/extra/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.zh.md +19 -0
  83. package/kb/extra/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.md +26 -0
  84. package/kb/extra/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.zh.md +26 -0
  85. package/kb/extra/upgrade-guide/v0.2.2-rc.1/plugin-update-method/guide.md +22 -0
  86. package/kb/extra/upgrade-guide/v0.2.2-rc.1/plugin-update-method/guide.zh.md +22 -0
  87. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.md +25 -0
  88. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.zh.md +25 -0
  89. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.md +48 -0
  90. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.zh.md +48 -0
  91. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.md +45 -0
  92. package/kb/extra/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.zh.md +45 -0
  93. package/kb/extra/upgrade-guide/v0.2.2-rc.1/runtime-context-reminders/guide.md +19 -0
  94. package/kb/extra/upgrade-guide/v0.2.2-rc.1/runtime-context-reminders/guide.zh.md +19 -0
  95. package/kb/extra/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md +17 -0
  96. package/kb/extra/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.zh.md +17 -0
  97. package/kb/extra/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md +27 -0
  98. package/kb/extra/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md +27 -0
  99. package/kb/extra/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.md +20 -0
  100. package/kb/extra/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.zh.md +20 -0
  101. package/kb/extra/upgrade-guide/v0.2.2-rc.1/terminal-bundle-sidebar-backend/guide.md +19 -0
  102. package/kb/extra/upgrade-guide/v0.2.2-rc.1/terminal-bundle-sidebar-backend/guide.zh.md +19 -0
  103. package/kb/extra/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.md +18 -0
  104. package/kb/extra/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.zh.md +18 -0
  105. package/kb/extra/upgrade-guide/v0.2.2-rc.1/web-search-billing/guide.md +41 -0
  106. package/kb/extra/upgrade-guide/v0.2.2-rc.1/web-search-billing/guide.zh.md +41 -0
  107. package/kb/extra/upgrade-guide/v0.2.2-rc.1/window-drag-regions/guide.md +21 -0
  108. package/kb/extra/upgrade-guide/v0.2.2-rc.1/window-drag-regions/guide.zh.md +21 -0
  109. package/kb/extra/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.md +29 -0
  110. package/kb/extra/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.zh.md +29 -0
  111. package/kb/extra/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md +25 -0
  112. package/kb/extra/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.zh.md +25 -0
  113. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cordis-root-and-intercept-metadata/guide.md +31 -0
  114. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cordis-root-and-intercept-metadata/guide.zh.md +31 -0
  115. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-agents-without-preset/guide.md +24 -0
  116. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-agents-without-preset/guide.zh.md +24 -0
  117. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-macos-provider/guide.md +24 -0
  118. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-macos-provider/guide.zh.md +24 -0
  119. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-partial-observations/guide.md +19 -0
  120. package/kb/extra/upgrade-guide/v0.2.2-rc.2/cua-partial-observations/guide.zh.md +19 -0
  121. package/kb/extra/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.md +15 -0
  122. package/kb/extra/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.zh.md +15 -0
  123. package/kb/extra/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md +28 -0
  124. package/kb/extra/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md +28 -0
  125. package/kb/extra/upgrade-guide/v0.2.2-rc.2/package-export-cleanup/guide.md +36 -0
  126. package/kb/extra/upgrade-guide/v0.2.2-rc.2/package-export-cleanup/guide.zh.md +36 -0
  127. package/kb/extra/upgrade-guide/v0.2.2-rc.2/python-ptc-removal/guide.md +22 -0
  128. package/kb/extra/upgrade-guide/v0.2.2-rc.2/python-ptc-removal/guide.zh.md +22 -0
  129. package/kb/extra/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.md +31 -0
  130. package/kb/extra/upgrade-guide/v0.2.2-rc.2/session-status-package/guide.zh.md +31 -0
  131. package/kb/extra/upgrade-guide/v0.2.2-rc.2/shared-search-filter/guide.md +18 -0
  132. package/kb/extra/upgrade-guide/v0.2.2-rc.2/shared-search-filter/guide.zh.md +18 -0
  133. package/kb/extra/upgrade-guide/v0.2.2-rc.2/shell-fs-tool-error-codes/guide.md +30 -0
  134. package/kb/extra/upgrade-guide/v0.2.2-rc.2/shell-fs-tool-error-codes/guide.zh.md +30 -0
  135. package/kb/extra/web-styling.md +57 -57
  136. package/kb/extra/web-styling.zh.md +57 -57
  137. package/kb/meta/search-index.json +4508 -3980
  138. package/kb/meta/source.json +18 -18
  139. package/kb/site/develop/practice/llm-adapter.md +192 -192
  140. package/kb/site/en/develop/practice/llm-adapter.md +192 -192
  141. package/kb/site/en/guide/desktop-uninstall-cleanup.md +63 -0
  142. package/kb/site/en/guide/plugin-market.md +153 -151
  143. package/kb/site/en/guide/providers.md +234 -234
  144. package/kb/site/en/guide/quickstart.md +35 -34
  145. package/kb/site/en/reference/capability-seams.md +789 -767
  146. package/kb/site/en/reference/config-catalog.md +5432 -5128
  147. package/kb/site/en/reference/cookbook/adding-a-package.md +175 -175
  148. package/kb/site/en/reference/cookbook/adding-a-tool.md +105 -104
  149. package/kb/site/en/reference/cookbook/extension-cookbook.md +178 -135
  150. package/kb/site/en/reference/cordis-api/context.md +373 -369
  151. package/kb/site/en/reference/cordis-api/fiber.md +457 -433
  152. package/kb/site/en/reference/cordis-api/inherited.md +44 -44
  153. package/kb/site/en/reference/cordis-api/service.md +118 -107
  154. package/kb/site/en/reference/experimental-persistence-catalog.md +36 -23
  155. package/kb/site/en/reference/index.md +174 -174
  156. package/kb/site/en/reference/persistence-catalog.md +9453 -9432
  157. package/kb/site/en/reference/subsystems/compaction.md +288 -288
  158. package/kb/site/en/reference/subsystems/core.md +1172 -1171
  159. package/kb/site/en/reference/subsystems/credentials.md +526 -497
  160. package/kb/site/en/reference/subsystems/filesystem.md +708 -708
  161. package/kb/site/en/reference/subsystems/index.md +82 -82
  162. package/kb/site/en/reference/subsystems/llm-streaming.md +1290 -1288
  163. package/kb/site/en/reference/subsystems/lsp.md +230 -206
  164. package/kb/site/en/reference/subsystems/persistence.md +451 -432
  165. package/kb/site/en/reference/subsystems/plan.md +91 -91
  166. package/kb/site/en/reference/subsystems/ptc-runtime.md +295 -261
  167. package/kb/site/en/reference/subsystems/sandbox.md +250 -232
  168. package/kb/site/en/reference/subsystems/session-query.md +525 -515
  169. package/kb/site/en/reference/subsystems/session-reference.md +231 -229
  170. package/kb/site/en/reference/subsystems/session.md +1478 -1431
  171. package/kb/site/en/reference/subsystems/sidebar-right.md +165 -165
  172. package/kb/site/en/reference/subsystems/skills.md +356 -356
  173. package/kb/site/en/reference/subsystems/slots.md +235 -231
  174. package/kb/site/en/reference/subsystems/terminal.md +188 -188
  175. package/kb/site/en/reference/subsystems/tools.md +902 -891
  176. package/kb/site/en/reference/subsystems/user-questions.md +330 -327
  177. package/kb/site/en/reference/subsystems/web-client.md +161 -104
  178. package/kb/site/en/reference/subsystems/web-server.md +434 -351
  179. package/kb/site/en/reference/subsystems/web.md +268 -268
  180. package/kb/site/en/reference/subsystems/workflow.md +287 -282
  181. package/kb/site/en/reference/subsystems/workspace.md +743 -651
  182. package/kb/site/en/reference/tool-catalog.md +2867 -2704
  183. package/kb/site/guide/desktop-uninstall-cleanup.md +63 -0
  184. package/kb/site/guide/plugin-market.md +153 -151
  185. package/kb/site/guide/providers.md +234 -234
  186. package/kb/site/guide/quickstart.md +35 -34
  187. package/kb/site/reference/capability-seams.md +789 -767
  188. package/kb/site/reference/config-catalog.md +5432 -5128
  189. package/kb/site/reference/cookbook/adding-a-package.md +175 -175
  190. package/kb/site/reference/cookbook/adding-a-tool.md +107 -106
  191. package/kb/site/reference/cookbook/extension-cookbook.md +182 -139
  192. package/kb/site/reference/cordis-api/context.md +373 -369
  193. package/kb/site/reference/cordis-api/fiber.md +459 -435
  194. package/kb/site/reference/cordis-api/inherited.md +44 -44
  195. package/kb/site/reference/cordis-api/service.md +118 -107
  196. package/kb/site/reference/experimental-persistence-catalog.md +36 -23
  197. package/kb/site/reference/index.md +178 -178
  198. package/kb/site/reference/persistence-catalog.md +9453 -9432
  199. package/kb/site/reference/subsystems/compaction.md +288 -288
  200. package/kb/site/reference/subsystems/core.md +1184 -1183
  201. package/kb/site/reference/subsystems/credentials.md +526 -497
  202. package/kb/site/reference/subsystems/filesystem.md +708 -708
  203. package/kb/site/reference/subsystems/index.md +82 -82
  204. package/kb/site/reference/subsystems/llm-streaming.md +1296 -1294
  205. package/kb/site/reference/subsystems/lsp.md +230 -206
  206. package/kb/site/reference/subsystems/persistence.md +451 -432
  207. package/kb/site/reference/subsystems/plan.md +91 -91
  208. package/kb/site/reference/subsystems/ptc-runtime.md +295 -261
  209. package/kb/site/reference/subsystems/sandbox.md +250 -232
  210. package/kb/site/reference/subsystems/session-query.md +525 -515
  211. package/kb/site/reference/subsystems/session-reference.md +231 -229
  212. package/kb/site/reference/subsystems/session.md +1482 -1435
  213. package/kb/site/reference/subsystems/sidebar-right.md +165 -165
  214. package/kb/site/reference/subsystems/skills.md +356 -356
  215. package/kb/site/reference/subsystems/slots.md +239 -235
  216. package/kb/site/reference/subsystems/terminal.md +188 -188
  217. package/kb/site/reference/subsystems/tools.md +902 -891
  218. package/kb/site/reference/subsystems/user-questions.md +330 -327
  219. package/kb/site/reference/subsystems/web-client.md +161 -104
  220. package/kb/site/reference/subsystems/web-server.md +434 -351
  221. package/kb/site/reference/subsystems/web.md +268 -268
  222. package/kb/site/reference/subsystems/workflow.md +287 -282
  223. package/kb/site/reference/subsystems/workspace.md +743 -651
  224. package/kb/site/reference/tool-catalog.md +2872 -2709
  225. package/lib/index.js +359 -359
  226. package/package.json +68 -68
  227. package/skills/dsh-plugin-dev-kb.md +71 -70
  228. package/kb/extra/subsystems/office-to-pdf.md +0 -87
  229. package/kb/extra/subsystems/office-to-pdf.zh.md +0 -87
@@ -1,1171 +1,1172 @@
1
- ---
2
- editSource: "docs/subsystems/core.md"
3
- rawMarkdownPath: "en/reference/subsystems/core.md"
4
- outline: [2,3]
5
- ---
6
-
7
- # Core
8
-
9
- The **core** subsystem is [`packages/core`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/README.md) — the packages every composition boots: the event-sourced session log, system-prompt assembly, the tool registry, the agent types, and the concrete loop that drives them. This page explains what the `agent`/`agent-loop` pair declares — how an agent is created and owned, and the `Agent` handle's delivery, cancellation, and interception contracts — plus the two type patterns every subsystem follows. The group's dedicated pages and the rest of the folder are indexed in the [subsystems README](./index.md).
10
-
11
- ## The spine, package by package
12
-
13
- A turn flows through the six packages in one loop: the driver in [`agent-loop`](https://github.com/deepseek-ai/deepseek-harness/tree/master/packages/core/agent-loop) claims a queued prompt, opens a turn on the [session log](./session.md) (`ctx.sessions`), assembles the request prefix through [system-prompt](./system-prompt.md) (`ctx.systemPrompt`) and derives history from the log, streams the model response through the [LLM seam](./llm-streaming.md), dispatches tool calls through the [tool registry](./tools.md) (`ctx.tools`), and appends every model-visible fact back onto the log before the next step derives from it. The conversation vocabulary the loop moves — `Message`, `ContentBlock`, `StreamChunk`, the model request — is declared by [`packages/llm`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/llm/README.md) and documented on [llm-streaming.md](./llm-streaming.md).
14
-
15
- | Package | Owns | Page |
16
- |---|---|---|
17
- | `session/` | The append-only `SessionEvent` log and in-memory store — the single source of truth (`ctx.sessions`) | [session.md](./session.md) |
18
- | `system-prompt/` | Prompt-section and tool-schema assembly (`ctx.systemPrompt`) | [system-prompt.md](./system-prompt.md) |
19
- | `tools/` | The scoped tool registry and guarded execution pipeline (`ctx.tools`) | [tools.md](./tools.md) |
20
- | `agent/` | The `Agent` interface, live registry, initiator scope, and `agent/*` event vocabulary (`ctx.agents`) | this page |
21
- | `agent-loop/` | The concrete driver implementing the public `Agent` contract (`ctx.agentLoop`) | this page |
22
- | `scope/` | The scoped-registration primitive the registries and loop build per-agent scoping on | [scope.md](./scope.md) |
23
-
24
- `scope/` is the one non-service package: a dependency-free library (`createScope`/`scopeOf`/`scopeTarget`) that sits below `session/` and `system-prompt/` in the module graph precisely so they can consume it without a cycle. `agent-loop` is the one concrete implementation of the public `Agent` contract and lives here because it is the harness's default product loop; it runs each driver inside `ctx.agents.withInitiator()`. Extension plugins depend on `agent` — including when they need the initiating Agent — and never on `agent-loop` directly, so the loop stays swappable. [`dsh-base`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/bundle/base/README.md) is the default product composition, while [`dsh-sdk-minimal`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/bundle/sdk-minimal/README.md) declares a smaller standalone tree.
25
-
26
- ## Creation and ownership
27
-
28
- Consumers create agents through `ctx.agents` — `create()` builds a fresh session and agent under one caller-supplied `SessionId`, `resume()` loads a persisted session first — or declaratively through the loop's config entries. Programmatic creation returns the owner's handle:
29
-
30
- Source: [`packages/core/agent/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/index.ts)
31
-
32
- ```ts type-equiv
33
- /**
34
- * An owned agent plus its disposer, returned by {@link AgentRegistry.create} /
35
- * {@link AgentRegistry.resume}. The disposer is a CAPABILITY: among consumers,
36
- * only the holder can tear this agent down. The registered factory provider is
37
- * also a structural owner because the scoped agent depends on that provider's
38
- * service API; provider unload stops and drains every live handle it made.
39
- * `dispose()` stops the loop, awaits its exit, unregisters the agent, removes
40
- * its session from the store, and finally unwinds its scoped world.
41
- *
42
- * `ctx.agents.get(id)` still returns a bare {@link Agent} — the handle is
43
- * exposed only to the consumer owner that created it; the structural provider
44
- * reaches the same teardown internally. Config-created agents (the loop's own
45
- * startup) are owned by the loop fiber and never need a handle.
46
- */
47
- interface AgentHandle {
48
- agent: Agent
49
- dispose(): Promise<void>
50
- }
51
- ```
52
-
53
- `CreateAgentOptions` carries the shared identity and everything a fresh agent needs before publication: session metadata (`meta` — validated `cwd`, fork lineage, the `isSeeded` marker, origin classification, delegation depth, and `agentPreset`), the exact fork cut in sibling field `inheritedEventCount`, an optional `seed` replay prefix, per-agent `AgentOptions`, a creation-only cancellation `signal`, and `setup`. `ResumeAgentOptions` is the persisted-identity counterpart: `resumeSessionId`, `agentOptions`, `signal`, and `setup`. The `setup` callback (`AgentSetup`) receives `(agentCtx, agent)` after Session store entry and completed `session/created`, before Agent registration: the context owns scoped registrations, while the explicit Agent supplies the exact child Session without a reverse property on the Context. Everything registered through `agentCtx` exists before `agent/created` and the first prompt assembly. Setup may return a synchronous commit invoked immediately before publication; a setup rejection, commit throw, or owner disposal unwinds the transaction, removes the Session, and preserves restored pending input and already stored events.
54
-
55
- `AgentFactory` is the creation interface behind the registry: the loop registers its factory via `ctx.agents.setFactory()`, so consumers use `ctx.agents` without depending on the concrete loop package. The registry passes creation options and the caller Context to the factory; the caller Context owns the returned handle's lifetime. The exact `create`/`resume` signatures and rollback contracts are in the [generated section](#ctxagents--agentregistry) below.
56
-
57
- ## The agent handle
58
-
59
- `Agent` is the surface every plugin (UI, hooks, orchestrators) programs against; `ctx.agents.get(id)` returns it, and the [initiator scope](#initiating-agent) carries it. The concrete implementation is package-internal to dsh-agent-loop; nothing outside the loop depends on it. The unified `send` method exposes target and wakeup routing directly; `followup`, `steer`, and `inject` are fixed-preset aliases.
60
-
61
- Source: [`packages/core/agent/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/types.ts)
62
-
63
- ```ts type-equiv
64
- /** Public live-agent handle; the runtime face augments its live capabilities. */
65
- interface Agent {
66
- /** Session-backed Agent identity. */
67
- readonly id: SessionId
68
- /** Route fallback and output controls; live accessors apply until the Session records a selection or request. */
69
- readonly options: AgentOptions
70
- /** The live session this agent drives; its log is the durable source of truth. */
71
- readonly session: Session
72
- /** Agent-owned access to durable model selection for future steps. */
73
- readonly model: Model
74
- /** Agent-owned access to durable pending work. */
75
- readonly inbox: Inbox
76
- /** The current lifecycle state, mirrored on every `agent/status` transition. */
77
- readonly status: AgentStatus
78
- /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */
79
- readonly ctx: Context
80
-
81
- /**
82
- * Clear queued and steering work — unless `keepInbox` — and abort the active
83
- * turn or between-turn task. The first cause wins for that activity. With no
84
- * active activity, cancellation is a no-op and does not arm later work.
85
- * @param cause - the stable caller intent carried by the active operation signal.
86
- * @param options - cancellation options; `keepInbox` preserves pending work.
87
- */
88
- cancel(cause: AgentCancelCause, options?: CancelOptions): void
89
-
90
- /**
91
- * Resolve after the current whole-agent activity reaches quiescence. This
92
- * follows replacement work started before the observed driver retires,
93
- * but does not identify the settlement of any particular message.
94
- * @returns fulfillment after no active driver or maintenance task remains.
95
- */
96
- whenIdle(): Promise<void>
97
-
98
- /**
99
- * Run one non-turn maintenance task from the true idle phase. The task starts
100
- * synchronously after claiming that phase; later waking input remains in the
101
- * inbox until the task settles, while public status stays `idle`.
102
- * `whenIdle()` follows both the task and any waking work released behind it.
103
- * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}.
104
- * @throws synchronously when turn-driving or another maintenance task already owns the agent.
105
- * @returns the task promise.
106
- */
107
- runMaintenance<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>
108
-
109
- /**
110
- * Route identified input to an inbox boundary and optionally wake the driver.
111
- * Waking input submitted after active cancellation is queued for the next
112
- * turn and runs when the aborted activity converges to idle; a `disposed`
113
- * cancel leaves it parked. A wake submitted while already idle always opens
114
- * its turn boundary, even when its message is cleared before the driver
115
- * claims ([driver wake convergence](../../agent-loop/src/agent.ts)).
116
- * @param message - identified content and the source that supplied it.
117
- * @param target - the preferred next-turn or next-step inbox boundary.
118
- * @param wakeup - whether delivery may wake the driver.
119
- */
120
- send(message: UserMessage, target: InboxTarget, wakeup: boolean): void
121
-
122
- /**
123
- * Queue an ordinary follow-up turn and wake the driver. The item becomes the
124
- * sole ordinary message of its own turn.
125
- * @param message - identified prompt content and the source that supplied it.
126
- */
127
- followup(message: UserMessage): void
128
-
129
- /**
130
- * Submit steering for the nearest step. An idle driver starts a turn;
131
- * a running driver consumes it at its next step boundary.
132
- * A rejected step leaves steering parked in the inbox until the next
133
- * wake; cancellation or disposal may discard pending steering.
134
- * @param message - identified steering content and the source that supplied it.
135
- */
136
- steer(message: UserMessage): void
137
-
138
- /**
139
- * Queue model-facing context for the next pre-step without waking the
140
- * driver. A running driver claims it at the nearest later step boundary;
141
- * idle drivers leave it pending until follow-up or steering
142
- * wakes them. It may miss a request whose pre-step already claimed its
143
- * batch. Cancellation or disposal may discard pending context.
144
- * @param message - identified injected context and the source that supplied it.
145
- */
146
- inject(message: UserMessage): void
147
- }
148
- ```
149
-
150
- ```ts type-equiv
151
- /**
152
- * An agent's lifecycle state, emitted on every transition as `agent/status`:
153
- * `idle` means no driver is active; `running` begins when waking input starts
154
- * cancellable pre-step processing and lasts while the driver drains,
155
- * closes, or checkpoints turns. Disposal removes the agent from its registry;
156
- * it is not a third observable status.
157
- */
158
- type AgentStatus = 'idle' | 'running'
159
- ```
160
-
161
- ```ts type-equiv
162
- /** One process-local live assistant streaming publication. */
163
- type AssistantStreamFrame =
164
- | {
165
- readonly type: 'start'
166
- readonly attemptId: LlmAttemptId
167
- /** Monotone within one attached Agent lifecycle; replacement restarts at 1. */
168
- readonly revision: number
169
- readonly turn: number
170
- readonly step: number
171
- }
172
- | {
173
- readonly type: 'chunk'
174
- readonly attemptId: LlmAttemptId
175
- readonly revision: number
176
- /** Dense zero-based position within the attempt. */
177
- readonly index: number
178
- /** Safe-integer timestamp reused by the durable embedded stream. */
179
- readonly time: number
180
- readonly chunk: StreamChunk
181
- }
182
- | {
183
- readonly type: 'end'
184
- readonly attemptId: LlmAttemptId
185
- readonly revision: number
186
- /** Number of chunk frames emitted by this attempt. */
187
- readonly index: number
188
- /** Durable settlement committed before this notification, or live abandonment without one. */
189
- readonly outcome:
190
- | {
191
- readonly kind: 'committed'
192
- readonly eventType: 'assistant/message' | 'assistant/attempt'
193
- readonly seq: SessionSeq
194
- }
195
- | { readonly kind: 'abandoned' }
196
- }
197
- ```
198
-
199
- `running` describes the driver-wide drain interval and may span consecutive queued turns; it does not prove a turn is still open. Disposal removes the agent from the registry and emits `agent/disposed`; it is not a terminal status value. `followup()` returns no handle: its `MessageId` identifies durable inbox insertion, claim, and discard facts, not a later assistant output or turn ending. `whenIdle()` observes the whole agent, so callers may call a receipt-to-idle interval a run only when they explicitly own that interval ([decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-07-30-followup-enqueue-and-owned-runs.md)).
200
-
201
- ```ts type-equiv
202
- /**
203
- * Merge-extensible agent options. Route fields may be live accessors until the
204
- * Session records a selection or request; step preparation captures their value.
205
- * Persona belongs to system-prompt sections.
206
- */
207
- interface AgentOptions {
208
- /** Provider route (must have a registered adapter at call time). */
209
- provider?: string
210
- /** Model id interpreted by the selected provider adapter. */
211
- model?: string
212
- /** Adapter-owned reasoning effort for the selected provider/model route. */
213
- reasoningEffort?: ReasoningEffortId | undefined
214
- /** Maximum output tokens for each conversation-model request. */
215
- maxTokens?: number
216
- }
217
- ```
218
-
219
- Step preparation requires `provider` and `model` before prompt assembly. The deprecated `agent/request` hook may change request controls but must preserve that route. An explicit `reasoningEffort` seeds the first request on that route; exact-model resolution validates it, while omission allows the adapter default to materialize. When present, `maxTokens` must be a positive safe integer and caps every conversation-model request; omission allows the exact-model adapter default to materialize before the request header, or otherwise leaves provider behavior unchanged. An agent-scoped `deployment:persona-prefix` prompt section may shadow the global default persona.
220
-
221
- `AgentLoop` registers `modelSelection` on `ctx.sessionProjections` and exposes selection operations through each `agent.model` instance. `model/selection` records a complete choice without entering model history. A matching request header clears `pending`; the latest request remains `lastUsed`. Adapter-defaulted effort is omitted so later requests resolve the default again. `next` is null only before either a choice or a request is recorded; in that case `AgentOptions` supplies the route. The [Agent model API](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/README.md) describes selection precedence and resume policy.
222
-
223
- ```ts type-equiv
224
- /** Agent-owned access to the model choice for future steps. */
225
- interface Model {
226
- /**
227
- * Resolve the choice for the next step to begin preparation. Recorded choices
228
- * take precedence over the last request and then the Agent's live options.
229
- * This read neither starts a step nor changes an already-prepared step.
230
- * @returns a detached choice, or undefined when no source names both provider and model.
231
- */
232
- current(): Readonly<ModelSelection> | undefined
233
-
234
- /**
235
- * Replace the next step's complete selection. Omitted effort follows adapter
236
- * defaults without inheriting a previous effort or resolving defaults here.
237
- * An equal recorded choice is a no-op; an options-only fallback is
238
- * always recorded. Callers own model availability and capability validation.
239
- * The append uses the Session's existing persistence and failure guarantees.
240
- * @param selection - complete provider, model, and optional explicit effort.
241
- */
242
- select(selection: Readonly<ModelSelection>): void
243
-
244
- }
245
- ```
246
-
247
- ```ts type-equiv
248
- /** Complete provider, model, and optional reasoning effort chosen for one Session's model steps. */
249
- interface ModelSelection {
250
- /** Registered provider route. */
251
- provider: string
252
- /** Provider-owned model id. */
253
- model: string
254
- /** Adapter-owned reasoning effort, or provider/default behavior when absent. */
255
- reasoningEffort?: ReasoningEffortId
256
- }
257
- ```
258
-
259
- ```ts type-equiv
260
- /**
261
- * Durable model-selection state for one Session. An effort the adapter
262
- * defaulted on a recorded request is omitted, so later requests resolve the
263
- * default again instead of pinning it as a choice.
264
- */
265
- interface ModelSelectionProjectionState {
266
- /** Selection used by the latest recorded model request. */
267
- readonly lastUsed: ModelSelection | null
268
- /** Later recorded selection not yet used by a matching model request. */
269
- readonly pending: ModelSelection | null
270
- }
271
- ```
272
-
273
- ```ts type-equiv
274
- /** Client view of the durable model-selection fold. */
275
- interface ModelSelectionProjection {
276
- /** Selection used by the latest recorded model request. */
277
- readonly lastUsed: ModelSelection | null
278
- /** Selection the next model step uses; null while the Agent's initial options supply the route. */
279
- readonly next: ModelSelection | null
280
- }
281
- ```
282
-
283
- The inbox is the delivery vocabulary — two ordered pending-message lists the agent owns as a durable projection:
284
-
285
- ```ts type-equiv
286
- /** Agent-owned access to pending work; concrete storage belongs to the driver. */
287
- interface Inbox {
288
- /** Prompts awaiting individual turns. */
289
- readonly nextTurn: readonly UserMessage[]
290
- /** Input awaiting the next step boundary. */
291
- readonly nextStep: readonly UserMessage[]
292
-
293
- /** Durably cancel all pending input, clearing next-step before next-turn. */
294
- clear(): void
295
-
296
- /**
297
- * Append one message to a pending list.
298
- * @param target - pending list to extend.
299
- * @param message - message to append.
300
- */
301
- append(target: InboxTarget, message: UserMessage): void
302
-
303
- /**
304
- * Prepend one message to a pending list.
305
- * @param target - pending list to extend.
306
- * @param message - message to prepend.
307
- */
308
- prepend(target: InboxTarget, message: UserMessage): void
309
-
310
- /**
311
- * Replace one pending message in place.
312
- * @param messageId - identity of the pending message to replace.
313
- * @param newMessage - replacement message.
314
- * @returns whether the message was still pending.
315
- */
316
- replace(messageId: MessageId, newMessage: UserMessage): boolean
317
-
318
- /**
319
- * Remove one pending message.
320
- * @param messageId - identity of the pending message to remove.
321
- * @returns whether the message was still pending.
322
- */
323
- remove(messageId: MessageId): boolean
324
-
325
- /**
326
- * Apply standard splice semantics and durably record the normalized result.
327
- * @param target - pending list to mutate.
328
- * @param start - splice position.
329
- * @param deleteCount - maximum number of messages to remove.
330
- * @param inserted - messages to insert at the resolved position.
331
- * @returns messages removed by the splice.
332
- */
333
- splice(
334
- target: InboxTarget,
335
- start: number,
336
- deleteCount: number,
337
- inserted: UserMessage[],
338
- ): UserMessage[]
339
- }
340
- ```
341
-
342
- ```ts type-equiv
343
- /** One of the two ordered pending-message lists owned by an agent. */
344
- type InboxTarget = 'next-turn' | 'next-step'
345
- ```
346
-
347
- Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. The structural `Inbox` methods record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. At a step boundary, dsh-agent-loop's package-internal `ReactLoopInbox` removes the proposed batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without discarded notifications, then emits per-message claimed notifications. Loop-only pending detection and claiming are not part of `Agent.inbox`. The `AgentLoop` service registers the standard `inbox` projection before publishing its factory; its cell is the sole live state, and the same fold serves cold consumers even when no Agent exists. The fold rejects unsafe or out-of-range splice coordinates and duplicate identities across both lists, identifying malformed durable history by event seq. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications.
348
-
349
- Cancellation:
350
-
351
- ```ts type-equiv
352
- /** Options for {@link Agent.cancel}. */
353
- interface CancelOptions {
354
- /**
355
- * Preserve queued and steering inbox items instead of discarding them. The
356
- * active turn is still aborted, but un-started and pending work survives for a
357
- * later turn and no canceled inbox splice is logged.
358
- */
359
- keepInbox?: boolean | undefined
360
- }
361
- ```
362
-
363
- ```ts type-equiv
364
- /** Why an active agent driver was cancelled. */
365
- type AgentCancelCause =
366
- | { readonly kind: 'user' }
367
- | { readonly kind: 'parent' }
368
- | { readonly kind: 'hook'; readonly reason: string }
369
- | { readonly kind: 'disposed' }
370
- ```
371
-
372
- The cause is a TypeScript-enforced same-process input. An active cancellation holder exposes that same object as the runtime-only `AbortSignal.reason`; a signal grants cooperating listeners no classification authority. Durable `turn/end` records the outcome as `{ kind: 'aborted', reason: TurnEndCancelCause }`, so the cancel cause lands in the terminal result.
373
-
374
- The [event taxonomy](../index.md#events) owns the `agent/*` lifecycle, checkpoint, and waterfall contracts. Turn and step boundaries are durable session events rather than agent emits.
375
-
376
- ## Initiating Agent
377
-
378
- The process-local initiator carried by `ctx.agents` is the exact `Agent` above, not a separate frame or copied identity. Ambient presence is neither liveness proof nor authorization; the [initiator-scope decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md) defines its lifetime and scope rules.
379
-
380
- ## Interception decisions
381
-
382
- Pre-step decisions use the same identified `UserMessage` type as durable user-role input. The entered batch is authoritative and preserves every message's `id` and `source`. Hook bridges map their native decision fields onto this typed result.
383
-
384
- Source: [`packages/core/agent/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/types.ts)
385
-
386
- `agent/pre-step` receives one payload carrying the exclusive claimed batch (`messages`), the proposed step's coordinates (`turn`, `step`), and the current turn's cancellation `signal`. The initial proposal runs inside an open turn before any step; a tool continuation may submit an empty claimed batch between steps:
387
-
388
- It returns a `PreStepDecision`. Reject opens no step. Enter supplies the complete message batch appended after `step/start`; claimed messages omitted by the final decision remain removed, while input inserted after the claim stays pending:
389
-
390
- ```ts type-equiv
391
- /** Whether and with which messages the loop enters a proposed step. */
392
- type PreStepDecision =
393
- | { kind: 'reject' }
394
- | {
395
- kind: 'enter'
396
- messages: UserMessage[]
397
- /** Start a distinct model-message series before this step's admitted messages. */
398
- startsRequestSeries?: true
399
- }
400
- ```
401
-
402
- `agent/request-error` runs after a failed model step closes and before its turn closes. Listeners can repair durable state or await policy work while the failed turn's signal is still live. A handling listener returns `{ kind: 'retry' }` without calling `next()`; the default `undefined` leaves the failure terminal.
403
-
404
- ```ts type-equiv
405
- /** Action returned by a listener that owns model-request recovery. */
406
- type RequestErrorAction = { kind: 'retry' } | undefined
407
- ```
408
-
409
- `agent/pre-step` is the only waterfall listener chain before request derivation. `agent/turn-stopping` runs when a turn has no tool or steering continuation, before one final steering drain.
410
-
411
- `agent/created` carries a `SessionStartSource` (why the session lifecycle began; a bridge keys its SessionStart matcher on it):
412
-
413
- ```ts type-equiv
414
- /** Why a session lifecycle began; seeded creates are `startup`, while persisted loads are `resume`. */
415
- type SessionStartSource = 'startup' | 'resume' | 'clear' | 'compact'
416
- ```
417
-
418
- ## Sessions
419
-
420
- A `Session` is an **append-only log** of typed `SessionEvent`s — the single source of truth. The LLM message history is *derived* from the log (`deriveMessages()`), not stored separately. Every entry carries a monotonic `seq`, a `time`, and a `type`-discriminated `data` payload; surface variants may also list cited earlier events in `sourceEventSeqs` and carry a `surfaceOp`.
421
-
422
- The `SessionEvent` envelope's exact conditional fields, the thirteen core event variants (`turn/start`, `turn/end`, `step/start`, `step/end`, `user/message`, `system/message`, `assistant/message`, `assistant/attempt`, `tool/call`, `tool/result`, `request/header`, `request/context`, `session/end-seed`), the `deriveMessages()` projection rules, the `TurnEndReason` reasons, and the execution-enclosure and standalone-event rules are on **[session.md](./session.md)**. How the log is made durable — the `SessionPersistence` interface, JSONL provider, `session/flush` checkpoint, crash recovery, and `SessionHeader` — is on **[persistence.md](./persistence.md)**.
423
-
424
- ## `ToolDefinition`
425
-
426
- The one pipeline-authoring type that is core: what every registered tool *is* — a model-facing `ToolSchema` plus an `execute` function and optional final-content and UI callbacks. A tool author rarely constructs it by hand (the `defineTool` DSL builds it with typed arguments), but it is the contract the registry holds and the loop dispatches through.
427
-
428
- Its full fields, the `defineTool`/`ValueSchemaSpec`/`ParameterSchemaSpec` typed schema DSL, the `ToolExecution`/`ToolExecutionResult` waterfall types, and the tool-presentation UI types are on **[tools.md](./tools.md)**.
429
-
430
- ## Repo-wide type patterns
431
-
432
- Two patterns recur across every subsystem and are documented once, here.
433
-
434
- <a id="the-map--derived-union-pattern"></a>
435
-
436
- ### The `…Map → derived-union` pattern
437
-
438
- Almost every extensible sum type in the harness follows one pattern: an interface keyed by a discriminant tag (the `…Map`), from which the union is derived with `keyof`. Plugins add variants by **declaration merging** — no edit to the owning package.
439
-
440
- ```ts ignore-check
441
- // The pattern, schematically:
442
- interface ThingMap {
443
- 'a': { kind: 'a'; /* … */ }
444
- 'b': { kind: 'b'; /* … */ }
445
- }
446
- type ThingKind = keyof ThingMap // 'a' | 'b'
447
- type Thing = ThingMap[keyof ThingMap] // the discriminated union
448
-
449
- // A plugin extends it without touching the source package:
450
- declare module '@deepseek-ai/dsh-llm' {
451
- interface ThingMap {
452
- 'c': { kind: 'c'; /* … */ }
453
- }
454
- }
455
- ```
456
-
457
- Six canonical maps use this pattern; a plugin author extends these:
458
-
459
- | Map | Package | Derives | Catalog |
460
- |---|---|---|---|
461
- | `ContentBlockMap` | dsh-llm | `ContentBlock` | [llm-streaming.md](./llm-streaming.md#content-blocks-and-messages) |
462
- | `MessageSourceMap` | dsh-llm | `MessageSource` | [llm-streaming.md](./llm-streaming.md#content-blocks-and-messages) |
463
- | `LlmRequestPurposeMap` | dsh-llm | `LlmRequestPurpose` | [llm-streaming.md](./llm-streaming.md#the-model-request-and-result) |
464
- | `FinishReasonMap` | dsh-llm | `FinishReason` | [llm-streaming.md](./llm-streaming.md#the-model-request-and-result) |
465
- | `TurnEndReasonMap` | dsh-session | `TurnEndReason` | [session.md](./session.md) |
466
- | `SessionEventMap` | dsh-session | `SessionEvent` | [session.md](./session.md) |
467
-
468
- Two large discriminated unions are the ones consumers `switch` over most: **`StreamChunk`** (the streaming protocol) and **`SessionEvent`** (the log entry). Per the repo convention, `switch` on the tag — don't chain `if`s — so each arm narrows and a typo'd tag fails to compile.
469
-
470
- ### Branded IDs
471
-
472
- IDs passed between packages are **branded** — structurally strings, but non-interchangeable at the type level (a `SessionId` cannot be passed where a `ToolCallId` is expected). Construction uses the shared `brandString<T>()` helper or an owner-defined validating factory; comparison, logging, and JSON behave as ordinary strings.
473
-
474
- The `Branded<B>` primitive and stateless constructor live in [dsh-brand](https://github.com/deepseek-ai/deepseek-harness/tree/master/packages/util/brand), which has no harness capability dependency. `brandString<T>()` applies a compile-time-only string brand.
475
-
476
- Source: [`packages/util/brand/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/util/brand/src/index.ts)
477
-
478
- ```ts type-equiv
479
- /** A string carrying a compile-time-only brand `B`. */
480
- type Branded<B extends string> = string & { readonly [BRAND]: B }
481
- ```
482
-
483
- The two core IDs are `ToolCallId` (correlates a tool call with its result; dsh-llm) and `SessionId` (the shared live agent and durable session identity; dsh-session). Capability packages brand their own ids too, such as `JobId` in [jobs.md](./jobs.md).
484
-
485
- ## `TurnBoundaryProjection`
486
-
487
- `ctx.agents.turnBoundaryOf(session)` reads recorded turn and step positions without requiring a live Agent. The registry owns this state; consumers do not register its projection definition.
488
-
489
- Source: [`packages/core/agent/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/types.ts)
490
-
491
- ```ts type-equiv
492
- /** Turn and step positions recorded in a Session. */
493
- interface TurnBoundaryProjection {
494
- /** Seq of the open turn's `turn/start`, or null between turns. */
495
- readonly openTurnStartSeq: OptionalSessionSeq
496
- /** Seq of the latest `step/start` event, or null before the first step. */
497
- readonly lastStepStartSeq: OptionalSessionSeq
498
- /** The latest step boundary (`step/start` or `step/end`) and its seq, or null before the first step boundary. */
499
- readonly lastStepBoundary: { readonly kind: 'start' | 'end'; readonly seq: SessionSeq } | null
500
- /** Turn number of the latest `turn/start`; 0 before the first turn. */
501
- readonly lastTurn: number
502
- }
503
- ```
504
-
505
- <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
506
-
507
- <a id="cordis-surface"></a>
508
-
509
- ## Cordis API
510
-
511
- 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).
512
-
513
- <a id="ctxagentdefaultmodel--agentdefaultmodelconfig"></a>
514
-
515
- ### `ctx.agentDefaultModel` — `AgentDefaultModelConfig`
516
-
517
- Owns the default model selection independently of any Host or transport. Each operation reads the owning Config references.
518
-
519
- ```ts cordis-catalog
520
- /**
521
- * Read the current default model selection.
522
- * @returns a detached provider, model, and optional reasoning selection.
523
- */
524
- currentSelection(): ModelSelection
525
-
526
- /**
527
- * Save the complete default model selection. A deployment without a configuration
528
- * editor keeps its composition entry. Saves commit in submission order; a failed
529
- * save rejects its caller without blocking later saves.
530
- * @param next - resolved selection accepted by an entry point.
531
- * @returns fulfillment after the optional profile write settles.
532
- */
533
- async saveSelection(next: ModelSelection): Promise<void>
534
- ```
535
-
536
- Source: [`packages/core/agent-default-model/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent-default-model/src/index.ts)
537
-
538
- <a id="ctxagentloop--agentloop"></a>
539
-
540
- ### `ctx.agentLoop` — `AgentLoop`
541
-
542
- Concrete agent factory and driver service.
543
-
544
- ```ts cordis-catalog
545
- /**
546
- * Create an agent and session under one caller-supplied identity, owned by
547
- * the accessing fiber. Constructor-driven config calls mint a fresh combined
548
- * id before entering this boundary. When a persistence backend is mounted,
549
- * the session's durable identity and any seed are stored before publication.
550
- * @param id - shared agent/session identity.
551
- * @param options - concrete loop options.
552
- * @param meta - optional fresh-session workspace metadata.
553
- * @returns the published running agent.
554
- */
555
- async create(id: SessionId, options: AgentOptions = {}, meta: Pick<SessionHeader, 'cwd'> = {}): Promise<Agent>
556
-
557
- /**
558
- * Create an owned agent on a caller-supplied session id.
559
- * @param ownerCtx - caller context that structurally owns the lifecycle.
560
- * @param options - identities, optional live parent, session seed/metadata, loop options, setup, and cancellation.
561
- * @returns the published handle.
562
- */
563
- async createAgent(ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle>
564
-
565
- /**
566
- * Resume an owned agent from the configured persistence service.
567
- * @param ownerCtx - caller context that owns load, setup, and the live lifecycle.
568
- * @param options - persisted identity, optional live parent, loop options, setup, and cancellation.
569
- * @returns the published handle.
570
- */
571
- async resume(ownerCtx: Context, options: ResumeAgentOptions): Promise<AgentHandle>
572
- ```
573
-
574
- Types: [SessionHeader](./persistence.md)
575
-
576
- Source: [`packages/core/agent-loop/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent-loop/src/index.ts)
577
-
578
- <a id="ctxagentpresets--agentpresetregistry"></a>
579
-
580
- ### `ctx.agentPresets` — `AgentPresetRegistry`
581
-
582
- Registry of YAML-declared presets and the revisions live Agents retain.
583
-
584
- ```ts cordis-catalog
585
- /**
586
- * Read the preset recorded for a Session, including selections no longer in the roster.
587
- * @param session - Session whose committed preset selection is read.
588
- * @returns the recorded preset, or null when none was selected.
589
- */
590
- presetForSession(session: Session): string | null
591
-
592
- /** Register and eagerly load a definition; activation failure remains visible in the roster.
593
- * @param definition Parsed configuration supplied by the declaring plugin.
594
- * @returns Definition disposer after activation or its diagnostic settles; the declaring plugin owns it.
595
- */
596
- async register(definition: PresetDefinition): Promise<() => Promise<void>>
597
-
598
- /** Inspect retained revisions, or the exact revision an Agent joined.
599
- * @param ctx - optional Agent context; omission includes all retained revisions.
600
- * @returns detached module references and isolation diagnostics; no match returns an empty list.
601
- */
602
- inspectCompositions(ctx?: Context): AgentPresetInspection[]
603
-
604
- /** Read every declared preset, including activation failures.
605
- * @returns Display metadata and loading diagnostics.
606
- */
607
- async list(): Promise<AgentPreset[]>
608
-
609
- /** Read the selection roster.
610
- * @returns Current presets, each marked when it is the default.
611
- */
612
- @Remote('list') async remoteExportList(): Promise<AgentPresetRoster>
613
-
614
- /** Resolve an identity without starting an Agent.
615
- * @param id Explicit preset or the current default.
616
- * @returns Current metadata, including failure when activation failed.
617
- */
618
- async resolve(id?: string): Promise<AgentPreset>
619
-
620
- /** Read one declaration's child plugin list as YAML, for viewing only.
621
- * @param agentPreset Preset identity.
622
- * @returns The declared composition beside its published metadata.
623
- */
624
- @Remote('read') readDocument(agentPreset: string): Promise<AgentPresetDocument>
625
-
626
- /** Bind an unpublished Agent to the current preset revision.
627
- * @param ctx Agent context from its setup callback.
628
- * @param id Requested preset, or the default.
629
- * @returns Bound preset identity.
630
- */
631
- async mount(ctx: Context, id?: string): Promise<AgentPreset>
632
-
633
- /** Join a child to the exact revision retained by its parent.
634
- * @param ctx Child Agent context.
635
- * @param parent Parent Agent context.
636
- * @returns Inherited preset id, or undefined in a preset-free composition.
637
- */
638
- composeFrom(ctx: Context, parent: Context): string | undefined
639
-
640
- /** Read the preset a live Agent uses.
641
- * @param ctx Agent context.
642
- * @returns Its preset id, if bound.
643
- */
644
- composedPreset(ctx: Context): string | undefined
645
-
646
- /** Read a service supplied inside an Agent's isolated preset group.
647
- * @param agent Agent whose composition is queried.
648
- * @param name Cordis service name.
649
- * @returns The service, or undefined.
650
- */
651
- serviceFor<K extends string & keyof Context>(agent: { ctx: Context }, name: K): Context[K] | undefined
652
-
653
- /** Rebind a blank Agent; the caller owns the blank-session check.
654
- * @param ctx Agent context.
655
- * @param id Requested preset.
656
- * @returns The bound identity.
657
- */
658
- async recompose(ctx: Context, id: string): Promise<AgentPreset>
659
-
660
- /** Select a preset before a session starts its first turn. A Session whose
661
- * log records the preset and whose Agent runs its current revision keeps its
662
- * composition; nothing is logged or announced.
663
- * @param agent Target Agent.
664
- * @param agentPreset Requested identity.
665
- * @returns Committed preset identity.
666
- */
667
- @Remote('select') async select(agent: Agent, agentPreset: string): Promise<string>
668
-
669
- /** Read current registrations for cold transcript presentation.
670
- * @param id Preset identity or the default.
671
- * @returns A revision lease; dispose it after the scoped read completes.
672
- */
673
- async acquireScope(id?: string): Promise<{ key: ScopeKey } & AsyncDisposable>
674
-
675
- /** Read plugin rows without creating an Agent.
676
- * @returns Current declaration metadata and activation states.
677
- */
678
- compositionInventory(): Promise<AgentPresetComposition[]>
679
- ```
680
-
681
- Types: [ScopeKey](./scope.md) · [Session](./session.md)
682
-
683
- Source: [`packages/preset/agent-preset-registry/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/preset/agent-preset-registry/src/index.ts)
684
-
685
- <a id="ctxagents--agentregistry"></a>
686
-
687
- ### `ctx.agents` — `AgentRegistry`
688
-
689
- Agent service (`ctx.agents`): tracks live agents and carries the initiating Agent through one process-local asynchronous driver chain. Agent *creation* is provided by whichever plugin implements the AgentFactory (`@deepseek-ai/dsh-agent-loop`), registered via setFactory.
690
-
691
- Initiator methods provide same-process causal attribution only. Ambient presence is neither liveness proof nor authorization; subjects and owners remain explicit, as does identity at worker, process, persistence, and wire boundaries. Returned Promise boundaries drain during teardown, except a nested lineage that starts an owning-fiber unload is excluded from its own drain.
692
-
693
- ```ts cordis-catalog
694
- /**
695
- * Read the turn and step positions recorded in a Session.
696
- * @param session - Session whose committed events are read.
697
- * @returns the current turn and step positions; do not mutate the returned value.
698
- */
699
- turnBoundaryOf(session: Session): TurnBoundaryProjection
700
-
701
- /**
702
- * Read the Agent that initiated the inherited asynchronous driver chain.
703
- * Use this optional form for logging, tracing, metrics, or host attribution
704
- * that also supports agentless calls. When a parent creates a child, setup
705
- * reports the causal parent while the setup callback's Agent parameter
706
- * identifies the child.
707
- * @returns the inherited Agent, or `undefined` outside an initiator boundary
708
- * and inside an explicit clearing boundary.
709
- * @throws when this service instance has been disposed.
710
- */
711
- currentInitiator(): Agent | undefined
712
-
713
- /**
714
- * Read the initiating Agent and fail when no initiator boundary is active.
715
- * Use this for private helpers contractually below a driver, or for a
716
- * deployment-owned outbound request whose contract forbids agentless calls.
717
- * Generic or direct-call paths use optional lookup or explicit request fields.
718
- * @returns the inherited Agent.
719
- * @throws when no initiator is active or this service instance has been disposed.
720
- */
721
- requireInitiator(): Agent
722
-
723
- /**
724
- * Run an operation with one exact Agent as its process-local initiator. The
725
- * exact synchronous value or Promise returned by the operation is preserved.
726
- * Custom drivers and test harnesses wrap their complete returned foreground
727
- * lifetime.
728
- * A queue or wire receiver may establish this boundary only after validating
729
- * explicit identity and resolving the exact live Agent; this method does neither.
730
- * Detached work remains owned by the subsystem that starts it.
731
- * @param agent - initiating Agent to inherit; presence is neither liveness proof nor authorization.
732
- * @param operation - synchronous or asynchronous operation to invoke.
733
- * @returns the exact value returned by `operation`.
734
- * @throws when the initiator scope is closing/disposed, or when `operation` throws.
735
- */
736
- withInitiator<T>(agent: Agent, operation: () => T): T
737
-
738
- /**
739
- * Run an operation inside a boundary that hides any inherited initiating
740
- * Agent. The exact synchronous value or Promise is preserved.
741
- * Use this while creating lazy shared timers, queue pumps, pool maintenance,
742
- * watchers, or exporters so they do not inherit the first Agent that happens
743
- * to initialize them. It clears only initiator attribution, not explicit
744
- * fields, and does not own or drain detached resources.
745
- * @param operation - synchronous or asynchronous operation to invoke without an initiator.
746
- * @returns the exact value returned by `operation`.
747
- * @throws when the initiator scope is closing/disposed, or when `operation` throws.
748
- */
749
- withoutInitiator<T>(operation: () => T): T
750
-
751
- /**
752
- * Register the agent-creation factory (the loop calls this on construction,
753
- * effect-scoped). A traced Cordis service is canonicalized to its concrete
754
- * target; each create/resume call is then traced through that caller's
755
- * context so ownership follows the caller without stacking proxy layers.
756
- * Throws if a factory is already registered. Returns the disposer; on
757
- * dispose the factory slot is cleared.
758
- * @param factory - the loop-owned factory {@link create}/{@link resume} delegate to.
759
- * @returns the disposer that clears the factory slot. The exact
760
- * Cordis effect disposer (single-shot): composite (generator) effects may
761
- * yield it directly — exact identity nests the teardown in order.
762
- */
763
- setFactory(factory: AgentFactory): () => void
764
-
765
- /**
766
- * Create and publish a new agent through the registered factory.
767
- * Distinct from {@link register} (which records an already-constructed
768
- * agent): this constructs the agent and its session. Rejects if no factory is
769
- * registered or creation/setup fails. The resolved {@link AgentHandle} lets
770
- * the owner tear down exactly this agent.
771
- * @param options - shared identity, session seed/metadata, and agent options.
772
- * @returns the handle after setup, rollback-covered publication, and loop start complete.
773
- */
774
- async create(options: CreateAgentOptions): Promise<AgentHandle>
775
-
776
- /**
777
- * Load a persisted session and resume an agent on it through the registered
778
- * factory. Rejects if no factory is registered; the factory rejects if
779
- * session persistence is not configured or persistence/setup fails.
780
- * @param options - persisted identity, configuration, and setup.
781
- * @returns the handle after setup, rollback-covered publication, and loop start complete.
782
- */
783
- async resume(options: ResumeAgentOptions): Promise<AgentHandle>
784
-
785
- /**
786
- * Register a live agent with source `startup`. Rejects if the id is already registered or a
787
- * serial `agent/created` listener fails. Emits `agent/disposed`
788
- * when the calling fiber is disposed — both with the agent's scope carrier
789
- * (`scopeTarget(agent, agent)`): the subject is the agent in hand, so the
790
- * emits are scope-filtered regardless of which context invoked `register`
791
- * (calling through `agent.ctx` scopes EFFECTS; dispatch scoping always
792
- * requires passing the carrier). Await registration before using the agent.
793
- * @param agent - the already-constructed agent to record in the store.
794
- * @returns the awaitable Cordis effect disposer (single-shot; a repeat call
795
- * returns undefined without awaiting an in-flight teardown). Exact
796
- * identity is load-bearing: a composite (generator) effect that owns a
797
- * teardown ORDER — the agent factory's lifecycle chain — must yield THIS
798
- * function so Cordis nests the unregistration at that yield position;
799
- * yielding a wrapper would leave it disposing as a concurrent sibling on
800
- * owner unload, unregistering the agent (and emitting `agent/disposed`)
801
- * while its final turn is still draining.
802
- */
803
- register(agent: Agent): ReturnType<Context['effect']>
804
-
805
- /**
806
- * Insert an already-constructed agent without announcing it. This is the
807
- * advanced ordered-lifecycle primitive used by the async agent factory: it
808
- * first completes setup while the agent is unpublished, then assigns the
809
- * returned detach closure into its pre-installed composite teardown before
810
- * calling {@link announce}. Ordinary callers use {@link register}.
811
- * @param agent - the prepared, unpublished agent.
812
- * @returns an idempotent closure that removes this exact entry and emits
813
- * `agent/disposed` with listener failures contained. When called from a
814
- * `agent/created` listener, removal and disposal wait until the serial
815
- * creation dispatch settles.
816
- */
817
- enter(agent: Agent): () => void
818
-
819
- /**
820
- * Announce an agent previously inserted with {@link enter}.
821
- * @param agent - the live inserted agent to announce.
822
- * @param source - fresh creation, resume, clear, or compaction source.
823
- * @param signal - optional factory initialization cancellation signal passed to listeners.
824
- * @returns completion of the serial creation listeners; a listener failure rejects.
825
- * @throws if `agent` is not the exact live registry entry for its id, or its
826
- * creation announcement already began (including a reentrant call from a
827
- * creation listener).
828
- */
829
- async announce(agent: Agent, source: SessionStartSource, signal?: AbortSignal): Promise<void>
830
-
831
- /**
832
- * Look up a live agent.
833
- * @param id - the shared agent/session id to look up.
834
- * @returns the agent, or undefined when no live agent has that id.
835
- */
836
- get(id: SessionId): Agent | undefined
837
-
838
- /**
839
- * All live agents, in registration order.
840
- * @returns a fresh array; mutating it does not affect the registry.
841
- */
842
- list(): Agent[]
843
- ```
844
-
845
- Types: [Session](./session.md)
846
-
847
- Source: [`packages/core/agent/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/index.ts)
848
-
849
- <a id="agent-events"></a>
850
-
851
- ### `agent/*` events
852
-
853
- <a id="agentassistant-stream--emit"></a>
854
-
855
- #### `agent/assistant-stream` — emit
856
-
857
- Process-local assistant-stream publication. Chunk frames are transient; the loop appends one final v2 `assistant/message` or `assistant/attempt` with the same stream before a committed end frame.
858
-
859
- ```ts cordis-catalog
860
- /**
861
- * Process-local assistant-stream publication. Chunk frames are transient;
862
- * the loop appends one final v2 `assistant/message` or `assistant/attempt`
863
- * with the same stream before a committed end frame.
864
- * @param payload.agent - the agent whose attempt produced the frame.
865
- * @param payload.frame - one ordered start, chunk, or end publication.
866
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
867
- * @mode emit
868
- */
869
- 'agent/assistant-stream'(this: Scoped<Agent>, payload: { agent: Agent; frame: AssistantStreamFrame }): void
870
- ```
871
-
872
- Types: [Scoped](./scope.md)
873
-
874
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
875
-
876
- <a id="agentcreated--serial"></a>
877
-
878
- #### `agent/created` — serial
879
-
880
- An entered agent is ready for per-agent initialization after factory setup. Listeners run in order and are awaited before creation resolves. AgentLoop holds queued input until all listeners finish. A throw or rejection fails creation and skips later listeners. Disposal retains the scope and session until dispatch settles; listeners must not await agent.whenIdle() or their own owner's disposal.
881
-
882
- ```ts cordis-catalog
883
- /**
884
- * An entered agent is ready for per-agent initialization after factory setup.
885
- * Listeners run in order and are awaited before creation resolves. AgentLoop
886
- * holds queued input until all listeners finish. A throw or rejection fails
887
- * creation and skips later listeners. Disposal retains the scope and session
888
- * until dispatch settles; listeners must not await agent.whenIdle() or their
889
- * own owner's disposal.
890
- * @param payload.agent - the newly registered agent with its live session and completed setup.
891
- * @param payload.source - fresh creation, resume, clear, or compaction source.
892
- * @param payload.signal - factory initialization cancellation signal, when provided.
893
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
894
- * @mode serial
895
- */
896
- 'agent/created'(this: Scoped<Agent>, payload: { agent: Agent; source: SessionStartSource; signal?: AbortSignal }): undefined | Promise<undefined>
897
- ```
898
-
899
- Types: [Scoped](./scope.md)
900
-
901
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
902
-
903
- <a id="agentdisposed--emit"></a>
904
-
905
- #### `agent/disposed` — emit
906
-
907
- An agent left the registry; AgentLoop emits this after driver quiescence and scoped-registration unwind, but before session detachment. Custom registry users own their driver-ordering contract.
908
-
909
- ```ts cordis-catalog
910
- /**
911
- * An agent left the registry; AgentLoop emits this after driver quiescence
912
- * and scoped-registration unwind, but before session detachment. Custom
913
- * registry users own their driver-ordering contract.
914
- * @param payload.agent - the exact agent removed from the registry.
915
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
916
- * @mode emit
917
- */
918
- 'agent/disposed'(this: Scoped<Agent>, payload: { agent: Agent }): void
919
- ```
920
-
921
- Types: [Scoped](./scope.md)
922
-
923
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
924
-
925
- <a id="agenterror--emit"></a>
926
-
927
- #### `agent/error` — emit
928
-
929
- A step or turn errored. The machine reports a failure here even when the error has no in-turn position for a durable record.
930
-
931
- ```ts cordis-catalog
932
- /**
933
- * A step or turn errored. The machine reports a failure here even when
934
- * the error has no in-turn position for a durable record.
935
- * @param payload.agent - the agent whose turn errored.
936
- * @param payload.turn - the turn in which the failure surfaced.
937
- * @param payload.step - the step at which the failure surfaced.
938
- * @param payload.error - the failure, verbatim.
939
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
940
- * @mode emit
941
- */
942
- 'agent/error'(this: Scoped<Agent>, payload: { agent: Agent; turn: number; step: number; error: unknown }): void
943
- ```
944
-
945
- Types: [Scoped](./scope.md)
946
-
947
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
948
-
949
- <a id="agentinboxclaimed--emit"></a>
950
-
951
- #### `agent/inbox/claimed` — emit
952
-
953
- One message left the inbox inside its open turn. If the proposed step is rejected, the claimed message ends here: it is neither discarded nor re-emitted as a user/message, and the turn closes without a step.
954
-
955
- ```ts cordis-catalog
956
- /**
957
- * One message left the inbox inside its open turn. If the proposed step
958
- * is rejected, the claimed message ends here: it is neither discarded nor
959
- * re-emitted as a user/message, and the turn closes without a step.
960
- * @param payload.agent - the agent whose inbox changed.
961
- * @param payload.message - the claimed message.
962
- * @param payload.turn - the owning turn.
963
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
964
- * @mode emit
965
- */
966
- 'agent/inbox/claimed'(this: Scoped<Agent>, payload: { agent: Agent; message: UserMessage; turn: number }): void
967
- ```
968
-
969
- Types: [Scoped](./scope.md) · [UserMessage](./session.md)
970
-
971
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
972
-
973
- <a id="agentinboxdiscarded--emit"></a>
974
-
975
- #### `agent/inbox/discarded` — emit
976
-
977
- One message was discarded from the live inbox.
978
-
979
- ```ts cordis-catalog
980
- /**
981
- * One message was discarded from the live inbox.
982
- * @param payload.agent - the agent whose inbox changed.
983
- * @param payload.message - the discarded message.
984
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
985
- * @mode emit
986
- */
987
- 'agent/inbox/discarded'(this: Scoped<Agent>, payload: { agent: Agent; message: UserMessage }): void
988
- ```
989
-
990
- Types: [Scoped](./scope.md) · [UserMessage](./session.md)
991
-
992
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
993
-
994
- <a id="agentinboxinserted--emit"></a>
995
-
996
- #### `agent/inbox/inserted` — emit
997
-
998
- One message entered the live inbox.
999
-
1000
- ```ts cordis-catalog
1001
- /**
1002
- * One message entered the live inbox.
1003
- * @param payload.agent - the agent whose inbox changed.
1004
- * @param payload.message - the inserted message.
1005
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1006
- * @mode emit
1007
- */
1008
- 'agent/inbox/inserted'(this: Scoped<Agent>, payload: { agent: Agent; message: UserMessage }): void
1009
- ```
1010
-
1011
- Types: [Scoped](./scope.md) · [UserMessage](./session.md)
1012
-
1013
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1014
-
1015
- <a id="agentpre-step--waterfall"></a>
1016
-
1017
- #### `agent/pre-step` — waterfall
1018
-
1019
- Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages.
1020
-
1021
- ```ts cordis-catalog
1022
- /**
1023
- * Reject a proposed step or replace the messages that enter it. Calling
1024
- * `next()` preserves the current messages.
1025
- * @param payload.agent - the agent proposing the step.
1026
- * @param payload.messages - messages removed from the inbox for this step.
1027
- * @param payload.turn - the turn that will own the step.
1028
- * @param payload.step - the step proposed by the loop.
1029
- * @param payload.signal - the current turn's cancellation signal.
1030
- * @param payload.modelSelection - captured step selection, retained across retries; omitted effort uses adapter defaults.
1031
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1032
- * @mode waterfall
1033
- */
1034
- 'agent/pre-step'(this: Scoped<Agent>, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal; modelSelection: Readonly<ModelSelection> }, next: () => Promise<PreStepDecision>): Promise<PreStepDecision>
1035
- ```
1036
-
1037
- Types: [Scoped](./scope.md) · [UserMessage](./session.md)
1038
-
1039
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1040
-
1041
- <a id="agentrequest-error--waterfall"></a>
1042
-
1043
- #### `agent/request-error` — waterfall
1044
-
1045
- Handle one failed model-request attempt before the loop retries or closes its step. A listener returns `{ kind: 'retry' }` without calling `next()` when it owns recovery, or calls `next()` to delegate. The default `undefined` leaves the failure terminal.
1046
-
1047
- ```ts cordis-catalog
1048
- /**
1049
- * Handle one failed model-request attempt before the loop retries or closes
1050
- * its step. A listener returns `{ kind: 'retry' }` without calling `next()`
1051
- * when it owns recovery, or calls `next()` to delegate. The default
1052
- * `undefined` leaves the failure terminal.
1053
- * @param payload.agent - the agent whose request failed.
1054
- * @param payload.turn - the turn containing the failed request.
1055
- * @param payload.step - the step containing the failed request attempt.
1056
- * @param payload.provider - the provider selected for the failed request.
1057
- * @param payload.failure - serializable facts normalized at the final adapter boundary.
1058
- * @param payload.retryPolicy - the policy of the adapter registration that served the failed request.
1059
- * @param payload.signal - the turn abort signal.
1060
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1061
- * @mode waterfall
1062
- */
1063
- 'agent/request-error'(this: Scoped<Agent>, payload: { agent: Agent; turn: number; step: number; provider: string; failure: LlmFailure; retryPolicy: ResolvedRetryPolicy | undefined; signal: AbortSignal }, next: () => Promise<RequestErrorAction>): Promise<RequestErrorAction>
1064
- ```
1065
-
1066
- Types: [LlmFailure](./llm-streaming.md) · [ResolvedRetryPolicy](./llm-streaming.md) · [Scoped](./scope.md)
1067
-
1068
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1069
-
1070
- <a id="agentstatus--emit"></a>
1071
-
1072
- #### `agent/status` — emit
1073
-
1074
- Agent status changed (`idle` ⇄ `running`). A waking delivery enters `running` synchronously after reserving cancellation; `idle` means no driver remains scheduled or active.
1075
-
1076
- ```ts cordis-catalog
1077
- /**
1078
- * Agent status changed (`idle` ⇄ `running`). A waking delivery enters
1079
- * `running` synchronously after reserving cancellation; `idle` means no
1080
- * driver remains scheduled or active.
1081
- * @param payload.agent - the agent whose status flipped.
1082
- * @param payload.status - the status just entered (the transition's destination).
1083
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1084
- * @mode emit
1085
- */
1086
- 'agent/status'(this: Scoped<Agent>, payload: { agent: Agent; status: AgentStatus }): void
1087
- ```
1088
-
1089
- Types: [Scoped](./scope.md)
1090
-
1091
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1092
-
1093
- <a id="agentturn-stopping--serial"></a>
1094
-
1095
- #### `agent/turn-stopping` — serial
1096
-
1097
- The turn is about to close: the model owes no response (no live tool calls, no fresh steering). Awaited before the boundary commits — a listener that objects steers (`agent.steer(...)`) and the machine re-reads its inbox: fresh steering runs another step, none closes the turn. Data decides, so listener order cannot change the outcome. The inverse control (stop a tool loop early) is data too: a tool result carrying `concludesTurn` ends the turn at its step. The conclusion never short-circuits already-submitted next-step work: same-step `additionalContexts` or racing steering still runs, and the turn closes only when that inbox drains.
1098
-
1099
- ```ts cordis-catalog
1100
- /**
1101
- * The turn is about to close: the model owes no response (no live tool
1102
- * calls, no fresh steering). Awaited before the boundary commits — a
1103
- * listener that objects steers (`agent.steer(...)`) and the machine
1104
- * re-reads its inbox: fresh steering runs another step, none closes the
1105
- * turn. Data decides, so listener order cannot change the outcome. The
1106
- * inverse control (stop a tool loop early) is data too: a tool result
1107
- * carrying `concludesTurn` ends the turn at its step. The conclusion
1108
- * never short-circuits already-submitted next-step work: same-step
1109
- * `additionalContexts` or racing steering still runs, and the turn
1110
- * closes only when that inbox drains.
1111
- * @param payload.agent - the agent whose turn is at its stop boundary.
1112
- * @param payload.turn - the turn about to close.
1113
- * @param payload.signal - the current turn's explicit abort signal.
1114
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1115
- * @mode serial
1116
- */
1117
- 'agent/turn-stopping'(this: Scoped<Agent>, payload: { agent: Agent; turn: number; signal: AbortSignal }): Promise<void> | void
1118
- ```
1119
-
1120
- Types: [Scoped](./scope.md)
1121
-
1122
- Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1123
-
1124
- <a id="agent-loop-events"></a>
1125
-
1126
- ### `agent-loop/*` events
1127
-
1128
- <a id="agent-loopconfig-start-failed--emit"></a>
1129
-
1130
- #### `agent-loop/config-start-failed` — emit
1131
-
1132
- A declarative agent entry failed before it could publish a live agent. Consumers that buffer work for the configured identity use this transient signal to reject that work instead of waiting forever. Normal factory teardown suppresses failures from the cancelled startup attempt.
1133
-
1134
- ```ts cordis-catalog
1135
- /**
1136
- * A declarative agent entry failed before it could publish a live agent.
1137
- * Consumers that buffer work for the configured identity use this
1138
- * transient signal to reject that work instead of waiting forever. Normal
1139
- * factory teardown suppresses failures from the cancelled startup attempt.
1140
- * @param payload.sessionId - exact shared agent/session identity that failed startup.
1141
- * @param payload.error - persistence, setup, or publication failure.
1142
- * @mode emit
1143
- */
1144
- 'agent-loop/config-start-failed'(payload: { sessionId: SessionId; error: unknown }): void
1145
- ```
1146
-
1147
- Source: [`packages/core/agent-loop/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent-loop/src/index.ts)
1148
-
1149
- <a id="agent-preset-events"></a>
1150
-
1151
- ### `agent-preset/*` events
1152
-
1153
- <a id="agent-presetselected--emit"></a>
1154
-
1155
- #### `agent-preset/selected` — emit
1156
-
1157
- One session committed a different agent preset to its durable log. Consumers invalidate only state derived from that session's composition.
1158
-
1159
- ```ts cordis-catalog
1160
- /**
1161
- * One session committed a different agent preset to its durable log.
1162
- * Consumers invalidate only state derived from that session's composition.
1163
- * @mode emit
1164
- * @param sessionId - the session whose composition changed.
1165
- * @param agentPreset - the preset recorded by the committed selection.
1166
- */
1167
- 'agent-preset/selected'(sessionId: SessionId, agentPreset: string): void
1168
- ```
1169
-
1170
- Source: [`packages/preset/agent-preset-registry/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/preset/agent-preset-registry/src/types.ts)
1171
- <!-- END GENERATED cordis-surface -->
1
+ ---
2
+ editSource: "docs/subsystems/core.md"
3
+ rawMarkdownPath: "en/reference/subsystems/core.md"
4
+ outline: [2,3]
5
+ ---
6
+
7
+ # Core
8
+
9
+ The **core** subsystem is [`packages/core`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/README.md) — the packages every composition boots: the event-sourced session log, system-prompt assembly, the tool registry, the agent types, and the concrete loop that drives them. This page explains what the `agent`/`agent-loop` pair declares — how an agent is created and owned, and the `Agent` handle's delivery, cancellation, and interception contracts — plus the two type patterns every subsystem follows. The group's dedicated pages and the rest of the folder are indexed in the [subsystems README](./index.md).
10
+
11
+ ## The spine, package by package
12
+
13
+ A turn flows through the six packages in one loop: the driver in [`agent-loop`](https://github.com/deepseek-ai/deepseek-harness/tree/master/packages/core/agent-loop) claims a queued prompt, opens a turn on the [session log](./session.md) (`ctx.sessions`), assembles the request prefix through [system-prompt](./system-prompt.md) (`ctx.systemPrompt`) and derives history from the log, streams the model response through the [LLM seam](./llm-streaming.md), dispatches tool calls through the [tool registry](./tools.md) (`ctx.tools`), and appends every model-visible fact back onto the log before the next step derives from it. The conversation vocabulary the loop moves — `Message`, `ContentBlock`, `StreamChunk`, the model request — is declared by [`packages/llm`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/llm/README.md) and documented on [llm-streaming.md](./llm-streaming.md).
14
+
15
+ | Package | Owns | Page |
16
+ |---|---|---|
17
+ | `session/` | The append-only `SessionEvent` log and in-memory store — the single source of truth (`ctx.sessions`) | [session.md](./session.md) |
18
+ | `system-prompt/` | Prompt-section and tool-schema assembly (`ctx.systemPrompt`) | [system-prompt.md](./system-prompt.md) |
19
+ | `tools/` | The scoped tool registry and guarded execution pipeline (`ctx.tools`) | [tools.md](./tools.md) |
20
+ | `agent/` | The `Agent` interface, live registry, initiator scope, and `agent/*` event vocabulary (`ctx.agents`) | this page |
21
+ | `agent-loop/` | The concrete driver implementing the public `Agent` contract (`ctx.agentLoop`) | this page |
22
+ | `scope/` | The scoped-registration primitive the registries and loop build per-agent scoping on | [scope.md](./scope.md) |
23
+
24
+ `scope/` is the one non-service package: a dependency-free library (`createScope`/`scopeOf`/`scopeTarget`) that sits below `session/` and `system-prompt/` in the module graph precisely so they can consume it without a cycle. `agent-loop` is the one concrete implementation of the public `Agent` contract and lives here because it is the harness's default product loop; it runs each driver inside `ctx.agents.withInitiator()`. Extension plugins depend on `agent` — including when they need the initiating Agent — and never on `agent-loop` directly, so the loop stays swappable. [`dsh-base`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/bundle/base/README.md) is the default product composition, while [`dsh-sdk-minimal`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/bundle/sdk-minimal/README.md) declares a smaller standalone tree.
25
+
26
+ ## Creation and ownership
27
+
28
+ Consumers create agents through `ctx.agents` — `create()` builds a fresh session and agent under one caller-supplied `SessionId`, `resume()` loads a persisted session first — or declaratively through the loop's config entries. Programmatic creation returns the owner's handle:
29
+
30
+ Source: [`packages/core/agent/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/index.ts)
31
+
32
+ ```ts type-equiv
33
+ /**
34
+ * An owned agent plus its disposer, returned by {@link AgentRegistry.create} /
35
+ * {@link AgentRegistry.resume}. The disposer is a CAPABILITY: among consumers,
36
+ * only the holder can tear this agent down. The registered factory provider is
37
+ * also a structural owner because the scoped agent depends on that provider's
38
+ * service API; provider unload stops and drains every live handle it made.
39
+ * `dispose()` stops the loop, awaits its exit, unregisters the agent, removes
40
+ * its session from the store, and finally unwinds its scoped world.
41
+ *
42
+ * `ctx.agents.get(id)` still returns a bare {@link Agent} — the handle is
43
+ * exposed only to the consumer owner that created it; the structural provider
44
+ * reaches the same teardown internally. Config-created agents (the loop's own
45
+ * startup) are owned by the loop fiber and never need a handle.
46
+ */
47
+ interface AgentHandle {
48
+ agent: Agent
49
+ dispose(): Promise<void>
50
+ }
51
+ ```
52
+
53
+ `CreateAgentOptions` carries the shared identity and everything a fresh agent needs before publication: session metadata (`meta` — validated `cwd`, fork lineage, the `isSeeded` marker, origin classification, delegation depth, and `agentPreset`), the exact fork cut in sibling field `inheritedEventCount`, an optional `seed` replay prefix, per-agent `AgentOptions`, a creation-only cancellation `signal`, and `setup`. `ResumeAgentOptions` is the persisted-identity counterpart: `resumeSessionId`, `agentOptions`, `signal`, and `setup`. The `setup` callback (`AgentSetup`) receives `(agentCtx, agent)` after Session store entry and completed `session/created`, before Agent registration: the context owns scoped registrations, while the explicit Agent supplies the exact child Session without a reverse property on the Context. Everything registered through `agentCtx` exists before `agent/created` and the first prompt assembly. Setup may return a synchronous commit invoked immediately before publication; a setup rejection, commit throw, or owner disposal unwinds the transaction, removes the Session, and preserves restored pending input and already stored events.
54
+
55
+ `AgentFactory` is the creation interface behind the registry: the loop registers its factory via `ctx.agents.setFactory()`, so consumers use `ctx.agents` without depending on the concrete loop package. The registry passes creation options and the caller Context to the factory; the caller Context owns the returned handle's lifetime. The exact `create`/`resume` signatures and rollback contracts are in the [generated section](#ctxagents--agentregistry) below.
56
+
57
+ ## The agent handle
58
+
59
+ `Agent` is the surface every plugin (UI, hooks, orchestrators) programs against; `ctx.agents.get(id)` returns it, and the [initiator scope](#initiating-agent) carries it. The concrete implementation is package-internal to dsh-agent-loop; nothing outside the loop depends on it. The unified `send` method exposes target and wakeup routing directly; `followup`, `steer`, and `inject` are fixed-preset aliases.
60
+
61
+ Source: [`packages/core/agent/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/types.ts)
62
+
63
+ ```ts type-equiv
64
+ /** Public live-agent handle; the runtime face augments its live capabilities. */
65
+ interface Agent {
66
+ /** Session-backed Agent identity. */
67
+ readonly id: SessionId
68
+ /** Route fallback and output controls; live accessors apply until the Session records a selection or request. */
69
+ readonly options: AgentOptions
70
+ /** The live session this agent drives; its log is the durable source of truth. */
71
+ readonly session: Session
72
+ /** Agent-owned access to durable model selection for future steps. */
73
+ readonly model: Model
74
+ /** Agent-owned access to durable pending work. */
75
+ readonly inbox: Inbox
76
+ /** The current lifecycle state, mirrored on every `agent/status` transition. */
77
+ readonly status: AgentStatus
78
+ /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */
79
+ readonly ctx: Context
80
+
81
+ /**
82
+ * Clear queued and steering work — unless `keepInbox` — and abort the active
83
+ * turn or between-turn task. The first cause wins for that activity. With no
84
+ * active activity, cancellation is a no-op and does not arm later work.
85
+ * Queue-write failures still abort the activity and propagate to the caller.
86
+ * @param cause - the stable caller intent carried by the active operation signal.
87
+ * @param options - cancellation options; `keepInbox` preserves pending work.
88
+ */
89
+ cancel(cause: AgentCancelCause, options?: CancelOptions): void
90
+
91
+ /**
92
+ * Resolve after the current whole-agent activity reaches quiescence. This
93
+ * follows replacement work started before the observed driver retires,
94
+ * but does not identify the settlement of any particular message.
95
+ * @returns fulfillment after no active driver or maintenance task remains.
96
+ */
97
+ whenIdle(): Promise<void>
98
+
99
+ /**
100
+ * Run one non-turn maintenance task from the true idle phase. The task starts
101
+ * synchronously after claiming that phase; later waking input remains in the
102
+ * inbox until the task settles, while public status stays `idle`.
103
+ * `whenIdle()` follows both the task and any waking work released behind it.
104
+ * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}.
105
+ * @throws synchronously when turn-driving or another maintenance task already owns the agent.
106
+ * @returns the task promise.
107
+ */
108
+ runMaintenance<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>
109
+
110
+ /**
111
+ * Route identified input to an inbox boundary and optionally wake the driver.
112
+ * Waking input submitted after active cancellation is queued for the next
113
+ * turn and runs when the aborted activity converges to idle; a `disposed`
114
+ * cancel leaves it parked. A wake submitted while already idle always opens
115
+ * its turn boundary, even when its message is cleared before the driver
116
+ * claims ([driver wake convergence](../../agent-loop/src/agent.ts)).
117
+ * @param message - identified content and the source that supplied it.
118
+ * @param target - the preferred next-turn or next-step inbox boundary.
119
+ * @param wakeup - whether delivery may wake the driver.
120
+ */
121
+ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void
122
+
123
+ /**
124
+ * Queue an ordinary follow-up turn and wake the driver. The item becomes the
125
+ * sole ordinary message of its own turn.
126
+ * @param message - identified prompt content and the source that supplied it.
127
+ */
128
+ followup(message: UserMessage): void
129
+
130
+ /**
131
+ * Submit steering for the nearest step. An idle driver starts a turn;
132
+ * a running driver consumes it at its next step boundary.
133
+ * A rejected step leaves steering parked in the inbox until the next
134
+ * wake; cancellation or disposal may discard pending steering.
135
+ * @param message - identified steering content and the source that supplied it.
136
+ */
137
+ steer(message: UserMessage): void
138
+
139
+ /**
140
+ * Queue model-facing context for the next pre-step without waking the
141
+ * driver. A running driver claims it at the nearest later step boundary;
142
+ * idle drivers leave it pending until follow-up or steering
143
+ * wakes them. It may miss a request whose pre-step already claimed its
144
+ * batch. Cancellation or disposal may discard pending context.
145
+ * @param message - identified injected context and the source that supplied it.
146
+ */
147
+ inject(message: UserMessage): void
148
+ }
149
+ ```
150
+
151
+ ```ts type-equiv
152
+ /**
153
+ * An agent's lifecycle state, emitted on every transition as `agent/status`:
154
+ * `idle` means no driver is active; `running` begins when waking input starts
155
+ * cancellable pre-step processing and lasts while the driver drains,
156
+ * closes, or checkpoints turns. Disposal removes the agent from its registry;
157
+ * it is not a third observable status.
158
+ */
159
+ type AgentStatus = 'idle' | 'running'
160
+ ```
161
+
162
+ ```ts type-equiv
163
+ /** One process-local live assistant streaming publication. */
164
+ type AssistantStreamFrame =
165
+ | {
166
+ readonly type: 'start'
167
+ readonly attemptId: LlmAttemptId
168
+ /** Monotone within one attached Agent lifecycle; replacement restarts at 1. */
169
+ readonly revision: number
170
+ readonly turn: number
171
+ readonly step: number
172
+ }
173
+ | {
174
+ readonly type: 'chunk'
175
+ readonly attemptId: LlmAttemptId
176
+ readonly revision: number
177
+ /** Dense zero-based position within the attempt. */
178
+ readonly index: number
179
+ /** Safe-integer timestamp reused by the durable embedded stream. */
180
+ readonly time: number
181
+ readonly chunk: StreamChunk
182
+ }
183
+ | {
184
+ readonly type: 'end'
185
+ readonly attemptId: LlmAttemptId
186
+ readonly revision: number
187
+ /** Number of chunk frames emitted by this attempt. */
188
+ readonly index: number
189
+ /** Durable settlement committed before this notification, or live abandonment without one. */
190
+ readonly outcome:
191
+ | {
192
+ readonly kind: 'committed'
193
+ readonly eventType: 'assistant/message' | 'assistant/attempt'
194
+ readonly seq: SessionSeq
195
+ }
196
+ | { readonly kind: 'abandoned' }
197
+ }
198
+ ```
199
+
200
+ `running` describes the driver-wide drain interval and may span consecutive queued turns; it does not prove a turn is still open. Disposal removes the agent from the registry and emits `agent/disposed`; it is not a terminal status value. `followup()` returns no handle: its `MessageId` identifies durable inbox insertion, claim, and discard facts, not a later assistant output or turn ending. `whenIdle()` observes the whole agent, so callers may call a receipt-to-idle interval a run only when they explicitly own that interval ([decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-07-30-followup-enqueue-and-owned-runs.md)).
201
+
202
+ ```ts type-equiv
203
+ /**
204
+ * Merge-extensible agent options. Route fields may be live accessors until the
205
+ * Session records a selection or request; step preparation captures their value.
206
+ * Persona belongs to system-prompt sections.
207
+ */
208
+ interface AgentOptions {
209
+ /** Provider route (must have a registered adapter at call time). */
210
+ provider?: string
211
+ /** Model id interpreted by the selected provider adapter. */
212
+ model?: string
213
+ /** Adapter-owned reasoning effort for the selected provider/model route. */
214
+ reasoningEffort?: ReasoningEffortId | undefined
215
+ /** Maximum output tokens for each conversation-model request. */
216
+ maxTokens?: number
217
+ }
218
+ ```
219
+
220
+ Step preparation requires `provider` and `model` before prompt assembly. The deprecated `agent/request` hook may change request controls but must preserve that route. An explicit `reasoningEffort` seeds the first request on that route; exact-model resolution validates it, while omission allows the adapter default to materialize. When present, `maxTokens` must be a positive safe integer and caps every conversation-model request; omission allows the exact-model adapter default to materialize before the request header, or otherwise leaves provider behavior unchanged. An agent-scoped `deployment:persona-prefix` prompt section may shadow the global default persona.
221
+
222
+ `AgentLoop` registers `modelSelection` on `ctx.sessionProjections` and exposes selection operations through each `agent.model` instance. `model/selection` records a complete choice without entering model history. A matching request header clears `pending`; the latest request remains `lastUsed`. Adapter-defaulted effort is omitted so later requests resolve the default again. `next` is null only before either a choice or a request is recorded; in that case `AgentOptions` supplies the route. The [Agent model API](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/README.md) describes selection precedence and resume policy.
223
+
224
+ ```ts type-equiv
225
+ /** Agent-owned access to the model choice for future steps. */
226
+ interface Model {
227
+ /**
228
+ * Resolve the choice for the next step to begin preparation. Recorded choices
229
+ * take precedence over the last request and then the Agent's live options.
230
+ * This read neither starts a step nor changes an already-prepared step.
231
+ * @returns a detached choice, or undefined when no source names both provider and model.
232
+ */
233
+ current(): Readonly<ModelSelection> | undefined
234
+
235
+ /**
236
+ * Replace the next step's complete selection. Omitted effort follows adapter
237
+ * defaults without inheriting a previous effort or resolving defaults here.
238
+ * An equal recorded choice is a no-op; an options-only fallback is
239
+ * always recorded. Callers own model availability and capability validation.
240
+ * The append uses the Session's existing persistence and failure guarantees.
241
+ * @param selection - complete provider, model, and optional explicit effort.
242
+ */
243
+ select(selection: Readonly<ModelSelection>): void
244
+
245
+ }
246
+ ```
247
+
248
+ ```ts type-equiv
249
+ /** Complete provider, model, and optional reasoning effort chosen for one Session's model steps. */
250
+ interface ModelSelection {
251
+ /** Registered provider route. */
252
+ provider: string
253
+ /** Provider-owned model id. */
254
+ model: string
255
+ /** Adapter-owned reasoning effort, or provider/default behavior when absent. */
256
+ reasoningEffort?: ReasoningEffortId
257
+ }
258
+ ```
259
+
260
+ ```ts type-equiv
261
+ /**
262
+ * Durable model-selection state for one Session. An effort the adapter
263
+ * defaulted on a recorded request is omitted, so later requests resolve the
264
+ * default again instead of pinning it as a choice.
265
+ */
266
+ interface ModelSelectionProjectionState {
267
+ /** Selection used by the latest recorded model request. */
268
+ readonly lastUsed: ModelSelection | null
269
+ /** Later recorded selection not yet used by a matching model request. */
270
+ readonly pending: ModelSelection | null
271
+ }
272
+ ```
273
+
274
+ ```ts type-equiv
275
+ /** Client view of the durable model-selection fold. */
276
+ interface ModelSelectionProjection {
277
+ /** Selection used by the latest recorded model request. */
278
+ readonly lastUsed: ModelSelection | null
279
+ /** Selection the next model step uses; null while the Agent's initial options supply the route. */
280
+ readonly next: ModelSelection | null
281
+ }
282
+ ```
283
+
284
+ The inbox is the delivery vocabulary — two ordered pending-message lists the agent owns as a durable projection:
285
+
286
+ ```ts type-equiv
287
+ /** Agent-owned access to pending work; concrete storage belongs to the driver. */
288
+ interface Inbox {
289
+ /** Prompts awaiting individual turns. */
290
+ readonly nextTurn: readonly UserMessage[]
291
+ /** Input awaiting the next step boundary. */
292
+ readonly nextStep: readonly UserMessage[]
293
+
294
+ /** Durably cancel all pending input, clearing next-step before next-turn. */
295
+ clear(): void
296
+
297
+ /**
298
+ * Append one message to a pending list.
299
+ * @param target - pending list to extend.
300
+ * @param message - message to append.
301
+ */
302
+ append(target: InboxTarget, message: UserMessage): void
303
+
304
+ /**
305
+ * Prepend one message to a pending list.
306
+ * @param target - pending list to extend.
307
+ * @param message - message to prepend.
308
+ */
309
+ prepend(target: InboxTarget, message: UserMessage): void
310
+
311
+ /**
312
+ * Replace one pending message in place.
313
+ * @param messageId - identity of the pending message to replace.
314
+ * @param newMessage - replacement message.
315
+ * @returns whether the message was still pending.
316
+ */
317
+ replace(messageId: MessageId, newMessage: UserMessage): boolean
318
+
319
+ /**
320
+ * Remove one pending message.
321
+ * @param messageId - identity of the pending message to remove.
322
+ * @returns whether the message was still pending.
323
+ */
324
+ remove(messageId: MessageId): boolean
325
+
326
+ /**
327
+ * Apply standard splice semantics and durably record the normalized result.
328
+ * @param target - pending list to mutate.
329
+ * @param start - splice position.
330
+ * @param deleteCount - maximum number of messages to remove.
331
+ * @param inserted - messages to insert at the resolved position.
332
+ * @returns messages removed by the splice.
333
+ */
334
+ splice(
335
+ target: InboxTarget,
336
+ start: number,
337
+ deleteCount: number,
338
+ inserted: UserMessage[],
339
+ ): UserMessage[]
340
+ }
341
+ ```
342
+
343
+ ```ts type-equiv
344
+ /** One of the two ordered pending-message lists owned by an agent. */
345
+ type InboxTarget = 'next-turn' | 'next-step'
346
+ ```
347
+
348
+ Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. The structural `Inbox` methods record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. At a step boundary, dsh-agent-loop's package-internal `ReactLoopInbox` removes the proposed batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without discarded notifications, then emits per-message claimed notifications. Loop-only pending detection and claiming are not part of `Agent.inbox`. The `AgentLoop` service registers the standard `inbox` projection before publishing its factory; its cell is the sole live state, and the same fold serves cold consumers even when no Agent exists. The fold rejects unsafe or out-of-range splice coordinates and duplicate identities across both lists, identifying malformed durable history by event seq. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications.
349
+
350
+ Cancellation:
351
+
352
+ ```ts type-equiv
353
+ /** Options for {@link Agent.cancel}. */
354
+ interface CancelOptions {
355
+ /**
356
+ * Preserve queued and steering inbox items instead of discarding them. The
357
+ * active turn is still aborted, but un-started and pending work survives for a
358
+ * later turn and no canceled inbox splice is logged.
359
+ */
360
+ keepInbox?: boolean | undefined
361
+ }
362
+ ```
363
+
364
+ ```ts type-equiv
365
+ /** Why an active agent driver was cancelled. */
366
+ type AgentCancelCause =
367
+ | { readonly kind: 'user' }
368
+ | { readonly kind: 'parent' }
369
+ | { readonly kind: 'hook'; readonly reason: string }
370
+ | { readonly kind: 'disposed' }
371
+ ```
372
+
373
+ The cause is a TypeScript-enforced same-process input. An active cancellation holder exposes that same object as the runtime-only `AbortSignal.reason`; a signal grants cooperating listeners no classification authority. Durable `turn/end` records the outcome as `{ kind: 'aborted', reason: TurnEndCancelCause }`, so the cancel cause lands in the terminal result.
374
+
375
+ The [event taxonomy](../index.md#events) owns the `agent/*` lifecycle, checkpoint, and waterfall contracts. Turn and step boundaries are durable session events rather than agent emits.
376
+
377
+ ## Initiating Agent
378
+
379
+ The process-local initiator carried by `ctx.agents` is the exact `Agent` above, not a separate frame or copied identity. Ambient presence is neither liveness proof nor authorization; the [initiator-scope decision](https://github.com/deepseek-ai/deepseek-harness/blob/master/.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md) defines its lifetime and scope rules.
380
+
381
+ ## Interception decisions
382
+
383
+ Pre-step decisions use the same identified `UserMessage` type as durable user-role input. The entered batch is authoritative and preserves every message's `id` and `source`. Hook bridges map their native decision fields onto this typed result.
384
+
385
+ Source: [`packages/core/agent/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/types.ts)
386
+
387
+ `agent/pre-step` receives one payload carrying the exclusive claimed batch (`messages`), the proposed step's coordinates (`turn`, `step`), and the current turn's cancellation `signal`. The initial proposal runs inside an open turn before any step; a tool continuation may submit an empty claimed batch between steps:
388
+
389
+ It returns a `PreStepDecision`. Reject opens no step. Enter supplies the complete message batch appended after `step/start`; claimed messages omitted by the final decision remain removed, while input inserted after the claim stays pending:
390
+
391
+ ```ts type-equiv
392
+ /** Whether and with which messages the loop enters a proposed step. */
393
+ type PreStepDecision =
394
+ | { kind: 'reject' }
395
+ | {
396
+ kind: 'enter'
397
+ messages: UserMessage[]
398
+ /** Start a distinct model-message series before this step's admitted messages. */
399
+ startsRequestSeries?: true
400
+ }
401
+ ```
402
+
403
+ `agent/request-error` runs after a failed model step closes and before its turn closes. Listeners can repair durable state or await policy work while the failed turn's signal is still live. A handling listener returns `{ kind: 'retry' }` without calling `next()`; the default `undefined` leaves the failure terminal.
404
+
405
+ ```ts type-equiv
406
+ /** Action returned by a listener that owns model-request recovery. */
407
+ type RequestErrorAction = { kind: 'retry' } | undefined
408
+ ```
409
+
410
+ `agent/pre-step` is the only waterfall listener chain before request derivation. `agent/turn-stopping` runs when a turn has no tool or steering continuation, before one final steering drain.
411
+
412
+ `agent/created` carries a `SessionStartSource` (why the session lifecycle began; a bridge keys its SessionStart matcher on it):
413
+
414
+ ```ts type-equiv
415
+ /** Why a session lifecycle began; seeded creates are `startup`, while persisted loads are `resume`. */
416
+ type SessionStartSource = 'startup' | 'resume' | 'clear' | 'compact'
417
+ ```
418
+
419
+ ## Sessions
420
+
421
+ A `Session` is an **append-only log** of typed `SessionEvent`s — the single source of truth. The LLM message history is *derived* from the log (`deriveMessages()`), not stored separately. Every entry carries a monotonic `seq`, a `time`, and a `type`-discriminated `data` payload; surface variants may also list cited earlier events in `sourceEventSeqs` and carry a `surfaceOp`.
422
+
423
+ The `SessionEvent` envelope's exact conditional fields, the thirteen core event variants (`turn/start`, `turn/end`, `step/start`, `step/end`, `user/message`, `system/message`, `assistant/message`, `assistant/attempt`, `tool/call`, `tool/result`, `request/header`, `request/context`, `session/end-seed`), the `deriveMessages()` projection rules, the `TurnEndReason` reasons, and the execution-enclosure and standalone-event rules are on **[session.md](./session.md)**. How the log is made durable — the `SessionPersistence` interface, JSONL provider, `session/flush` checkpoint, crash recovery, and `SessionHeader` — is on **[persistence.md](./persistence.md)**.
424
+
425
+ ## `ToolDefinition`
426
+
427
+ The one pipeline-authoring type that is core: what every registered tool *is* — a model-facing `ToolSchema` plus an `execute` function and optional final-content and UI callbacks. A tool author rarely constructs it by hand (the `defineTool` DSL builds it with typed arguments), but it is the contract the registry holds and the loop dispatches through.
428
+
429
+ Its full fields, the `defineTool`/`ValueSchemaSpec`/`ParameterSchemaSpec` typed schema DSL, the `ToolExecution`/`ToolExecutionResult` waterfall types, and the tool-presentation UI types are on **[tools.md](./tools.md)**.
430
+
431
+ ## Repo-wide type patterns
432
+
433
+ Two patterns recur across every subsystem and are documented once, here.
434
+
435
+ <a id="the-map--derived-union-pattern"></a>
436
+
437
+ ### The `…Map → derived-union` pattern
438
+
439
+ Almost every extensible sum type in the harness follows one pattern: an interface keyed by a discriminant tag (the `…Map`), from which the union is derived with `keyof`. Plugins add variants by **declaration merging** — no edit to the owning package.
440
+
441
+ ```ts ignore-check
442
+ // The pattern, schematically:
443
+ interface ThingMap {
444
+ 'a': { kind: 'a'; /* … */ }
445
+ 'b': { kind: 'b'; /* … */ }
446
+ }
447
+ type ThingKind = keyof ThingMap // 'a' | 'b'
448
+ type Thing = ThingMap[keyof ThingMap] // the discriminated union
449
+
450
+ // A plugin extends it without touching the source package:
451
+ declare module '@deepseek-ai/dsh-llm' {
452
+ interface ThingMap {
453
+ 'c': { kind: 'c'; /* … */ }
454
+ }
455
+ }
456
+ ```
457
+
458
+ Six canonical maps use this pattern; a plugin author extends these:
459
+
460
+ | Map | Package | Derives | Catalog |
461
+ |---|---|---|---|
462
+ | `ContentBlockMap` | dsh-llm | `ContentBlock` | [llm-streaming.md](./llm-streaming.md#content-blocks-and-messages) |
463
+ | `MessageSourceMap` | dsh-llm | `MessageSource` | [llm-streaming.md](./llm-streaming.md#content-blocks-and-messages) |
464
+ | `LlmRequestPurposeMap` | dsh-llm | `LlmRequestPurpose` | [llm-streaming.md](./llm-streaming.md#the-model-request-and-result) |
465
+ | `FinishReasonMap` | dsh-llm | `FinishReason` | [llm-streaming.md](./llm-streaming.md#the-model-request-and-result) |
466
+ | `TurnEndReasonMap` | dsh-session | `TurnEndReason` | [session.md](./session.md) |
467
+ | `SessionEventMap` | dsh-session | `SessionEvent` | [session.md](./session.md) |
468
+
469
+ Two large discriminated unions are the ones consumers `switch` over most: **`StreamChunk`** (the streaming protocol) and **`SessionEvent`** (the log entry). Per the repo convention, `switch` on the tag — don't chain `if`s — so each arm narrows and a typo'd tag fails to compile.
470
+
471
+ ### Branded IDs
472
+
473
+ IDs passed between packages are **branded** — structurally strings, but non-interchangeable at the type level (a `SessionId` cannot be passed where a `ToolCallId` is expected). Construction uses the shared `brandString<T>()` helper or an owner-defined validating factory; comparison, logging, and JSON behave as ordinary strings.
474
+
475
+ The `Branded<B>` primitive and stateless constructor live in [dsh-brand](https://github.com/deepseek-ai/deepseek-harness/tree/master/packages/util/brand), which has no harness capability dependency. `brandString<T>()` applies a compile-time-only string brand.
476
+
477
+ Source: [`packages/util/brand/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/util/brand/src/index.ts)
478
+
479
+ ```ts type-equiv
480
+ /** A string carrying a compile-time-only brand `B`. */
481
+ type Branded<B extends string> = string & { readonly [BRAND]: B }
482
+ ```
483
+
484
+ The two core IDs are `ToolCallId` (correlates a tool call with its result; dsh-llm) and `SessionId` (the shared live agent and durable session identity; dsh-session). Capability packages brand their own ids too, such as `JobId` in [jobs.md](./jobs.md).
485
+
486
+ ## `TurnBoundaryProjection`
487
+
488
+ `ctx.agents.turnBoundaryOf(session)` reads recorded turn and step positions without requiring a live Agent. The registry owns this state; consumers do not register its projection definition.
489
+
490
+ Source: [`packages/core/agent/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/types.ts)
491
+
492
+ ```ts type-equiv
493
+ /** Turn and step positions recorded in a Session. */
494
+ interface TurnBoundaryProjection {
495
+ /** Seq of the open turn's `turn/start`, or null between turns. */
496
+ readonly openTurnStartSeq: OptionalSessionSeq
497
+ /** Seq of the latest `step/start` event, or null before the first step. */
498
+ readonly lastStepStartSeq: OptionalSessionSeq
499
+ /** The latest step boundary (`step/start` or `step/end`) and its seq, or null before the first step boundary. */
500
+ readonly lastStepBoundary: { readonly kind: 'start' | 'end'; readonly seq: SessionSeq } | null
501
+ /** Turn number of the latest `turn/start`; 0 before the first turn. */
502
+ readonly lastTurn: number
503
+ }
504
+ ```
505
+
506
+ <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
507
+
508
+ <a id="cordis-surface"></a>
509
+
510
+ ## Cordis API
511
+
512
+ 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).
513
+
514
+ <a id="ctxagentdefaultmodel--agentdefaultmodelconfig"></a>
515
+
516
+ ### `ctx.agentDefaultModel` — `AgentDefaultModelConfig`
517
+
518
+ Owns the default model selection independently of any Host or transport. Each operation reads the owning Config references.
519
+
520
+ ```ts cordis-catalog
521
+ /**
522
+ * Read the current default model selection.
523
+ * @returns a detached provider, model, and optional reasoning selection.
524
+ */
525
+ currentSelection(): ModelSelection
526
+
527
+ /**
528
+ * Save the complete default model selection. A deployment without a configuration
529
+ * editor keeps its composition entry. Saves commit in submission order; a failed
530
+ * save rejects its caller without blocking later saves.
531
+ * @param next - resolved selection accepted by an entry point.
532
+ * @returns fulfillment after the optional profile write settles.
533
+ */
534
+ async saveSelection(next: ModelSelection): Promise<void>
535
+ ```
536
+
537
+ Source: [`packages/core/agent-default-model/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent-default-model/src/index.ts)
538
+
539
+ <a id="ctxagentloop--agentloop"></a>
540
+
541
+ ### `ctx.agentLoop` — `AgentLoop`
542
+
543
+ Concrete agent factory and driver service.
544
+
545
+ ```ts cordis-catalog
546
+ /**
547
+ * Create an agent and session under one caller-supplied identity, owned by
548
+ * the accessing fiber. Constructor-driven config calls mint a fresh combined
549
+ * id before entering this boundary. When a persistence backend is mounted,
550
+ * the session's durable identity and any seed are stored before publication.
551
+ * @param id - shared agent/session identity.
552
+ * @param options - concrete loop options.
553
+ * @param meta - optional fresh-session workspace metadata.
554
+ * @returns the published running agent.
555
+ */
556
+ async create(id: SessionId, options: AgentOptions = {}, meta: Pick<SessionHeader, 'cwd'> = {}): Promise<Agent>
557
+
558
+ /**
559
+ * Create an owned agent on a caller-supplied session id.
560
+ * @param ownerCtx - caller context that structurally owns the lifecycle.
561
+ * @param options - identities, optional live parent, session seed/metadata, loop options, setup, and cancellation.
562
+ * @returns the published handle.
563
+ */
564
+ async createAgent(ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle>
565
+
566
+ /**
567
+ * Resume an owned agent from the configured persistence service.
568
+ * @param ownerCtx - caller context that owns load, setup, and the live lifecycle.
569
+ * @param options - persisted identity, optional live parent, loop options, setup, and cancellation.
570
+ * @returns the published handle.
571
+ */
572
+ async resume(ownerCtx: Context, options: ResumeAgentOptions): Promise<AgentHandle>
573
+ ```
574
+
575
+ Types: [SessionHeader](./persistence.md)
576
+
577
+ Source: [`packages/core/agent-loop/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent-loop/src/index.ts)
578
+
579
+ <a id="ctxagentpresets--agentpresetregistry"></a>
580
+
581
+ ### `ctx.agentPresets` — `AgentPresetRegistry`
582
+
583
+ Registry of YAML-declared presets and the revisions live Agents retain.
584
+
585
+ ```ts cordis-catalog
586
+ /**
587
+ * Read the preset recorded for a Session, including selections no longer in the roster.
588
+ * @param session - Session whose committed preset selection is read.
589
+ * @returns the recorded preset, or null when none was selected.
590
+ */
591
+ presetForSession(session: Session): string | null
592
+
593
+ /** Register and eagerly load a definition; activation failure remains visible in the roster.
594
+ * @param definition Parsed configuration supplied by the declaring plugin.
595
+ * @returns Definition disposer after activation or its diagnostic settles; the declaring plugin owns it.
596
+ */
597
+ async register(definition: PresetDefinition): Promise<() => Promise<void>>
598
+
599
+ /** Inspect retained revisions, or the exact revision an Agent joined.
600
+ * @param ctx - optional Agent context; omission includes all retained revisions.
601
+ * @returns detached module references and isolation diagnostics; no match returns an empty list.
602
+ */
603
+ inspectCompositions(ctx?: Context): AgentPresetInspection[]
604
+
605
+ /** Read every declared preset, including activation failures.
606
+ * @returns Display metadata and loading diagnostics.
607
+ */
608
+ async list(): Promise<AgentPreset[]>
609
+
610
+ /** Read the selection roster.
611
+ * @returns Current presets, each marked when it is the default.
612
+ */
613
+ @Remote('list') async remoteExportList(): Promise<AgentPresetRoster>
614
+
615
+ /** Resolve an identity without starting an Agent.
616
+ * @param id Explicit preset or the current default.
617
+ * @returns Current metadata, including failure when activation failed.
618
+ */
619
+ async resolve(id?: string): Promise<AgentPreset>
620
+
621
+ /** Read one declaration's child plugin list as YAML, for viewing only.
622
+ * @param agentPreset Preset identity.
623
+ * @returns The declared composition beside its published metadata.
624
+ */
625
+ @Remote('read') readDocument(agentPreset: string): Promise<AgentPresetDocument>
626
+
627
+ /** Bind an unpublished Agent to the current preset revision.
628
+ * @param ctx Agent context from its setup callback.
629
+ * @param id Requested preset, or the default.
630
+ * @returns Bound preset identity.
631
+ */
632
+ async mount(ctx: Context, id?: string): Promise<AgentPreset>
633
+
634
+ /** Join a child to the exact revision retained by its parent.
635
+ * @param ctx Child Agent context.
636
+ * @param parent Parent Agent context.
637
+ * @returns Inherited preset id, or undefined in a preset-free composition.
638
+ */
639
+ composeFrom(ctx: Context, parent: Context): string | undefined
640
+
641
+ /** Read the preset a live Agent uses.
642
+ * @param ctx Agent context.
643
+ * @returns Its preset id, if bound.
644
+ */
645
+ composedPreset(ctx: Context): string | undefined
646
+
647
+ /** Read a service supplied inside an Agent's isolated preset group.
648
+ * @param agent Agent whose composition is queried.
649
+ * @param name Cordis service name.
650
+ * @returns The service, or undefined.
651
+ */
652
+ serviceFor<K extends string & keyof Context>(agent: { ctx: Context }, name: K): Context[K] | undefined
653
+
654
+ /** Rebind a blank Agent; the caller owns the blank-session check.
655
+ * @param ctx Agent context.
656
+ * @param id Requested preset.
657
+ * @returns The bound identity.
658
+ */
659
+ async recompose(ctx: Context, id: string): Promise<AgentPreset>
660
+
661
+ /** Select a preset before a session starts its first turn. A Session whose
662
+ * log records the preset and whose Agent runs its current revision keeps its
663
+ * composition; nothing is logged or announced.
664
+ * @param agent Target Agent.
665
+ * @param agentPreset Requested identity.
666
+ * @returns Committed preset identity.
667
+ */
668
+ @Remote('select') async select(agent: Agent, agentPreset: string): Promise<string>
669
+
670
+ /** Read current registrations for cold transcript presentation.
671
+ * @param id Preset identity or the default.
672
+ * @returns A revision lease; dispose it after the scoped read completes.
673
+ */
674
+ async acquireScope(id?: string): Promise<{ key: ScopeKey } & AsyncDisposable>
675
+
676
+ /** Read plugin rows without creating an Agent.
677
+ * @returns Current declaration metadata and activation states.
678
+ */
679
+ compositionInventory(): Promise<AgentPresetComposition[]>
680
+ ```
681
+
682
+ Types: [ScopeKey](./scope.md) · [Session](./session.md)
683
+
684
+ Source: [`packages/preset/agent-preset-registry/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/preset/agent-preset-registry/src/index.ts)
685
+
686
+ <a id="ctxagents--agentregistry"></a>
687
+
688
+ ### `ctx.agents` — `AgentRegistry`
689
+
690
+ Agent service (`ctx.agents`): tracks live agents and carries the initiating Agent through one process-local asynchronous driver chain. Agent *creation* is provided by whichever plugin implements the AgentFactory (`@deepseek-ai/dsh-agent-loop`), registered via setFactory.
691
+
692
+ Initiator methods provide same-process causal attribution only. Ambient presence is neither liveness proof nor authorization; subjects and owners remain explicit, as does identity at worker, process, persistence, and wire boundaries. Returned Promise boundaries drain during teardown, except a nested lineage that starts an owning-fiber unload is excluded from its own drain.
693
+
694
+ ```ts cordis-catalog
695
+ /**
696
+ * Read the turn and step positions recorded in a Session.
697
+ * @param session - Session whose committed events are read.
698
+ * @returns the current turn and step positions; do not mutate the returned value.
699
+ */
700
+ turnBoundaryOf(session: Session): TurnBoundaryProjection
701
+
702
+ /**
703
+ * Read the Agent that initiated the inherited asynchronous driver chain.
704
+ * Use this optional form for logging, tracing, metrics, or host attribution
705
+ * that also supports agentless calls. When a parent creates a child, setup
706
+ * reports the causal parent while the setup callback's Agent parameter
707
+ * identifies the child.
708
+ * @returns the inherited Agent, or `undefined` outside an initiator boundary
709
+ * and inside an explicit clearing boundary.
710
+ * @throws when this service instance has been disposed.
711
+ */
712
+ currentInitiator(): Agent | undefined
713
+
714
+ /**
715
+ * Read the initiating Agent and fail when no initiator boundary is active.
716
+ * Use this for private helpers contractually below a driver, or for a
717
+ * deployment-owned outbound request whose contract forbids agentless calls.
718
+ * Generic or direct-call paths use optional lookup or explicit request fields.
719
+ * @returns the inherited Agent.
720
+ * @throws when no initiator is active or this service instance has been disposed.
721
+ */
722
+ requireInitiator(): Agent
723
+
724
+ /**
725
+ * Run an operation with one exact Agent as its process-local initiator. The
726
+ * exact synchronous value or Promise returned by the operation is preserved.
727
+ * Custom drivers and test harnesses wrap their complete returned foreground
728
+ * lifetime.
729
+ * A queue or wire receiver may establish this boundary only after validating
730
+ * explicit identity and resolving the exact live Agent; this method does neither.
731
+ * Detached work remains owned by the subsystem that starts it.
732
+ * @param agent - initiating Agent to inherit; presence is neither liveness proof nor authorization.
733
+ * @param operation - synchronous or asynchronous operation to invoke.
734
+ * @returns the exact value returned by `operation`.
735
+ * @throws when the initiator scope is closing/disposed, or when `operation` throws.
736
+ */
737
+ withInitiator<T>(agent: Agent, operation: () => T): T
738
+
739
+ /**
740
+ * Run an operation inside a boundary that hides any inherited initiating
741
+ * Agent. The exact synchronous value or Promise is preserved.
742
+ * Use this while creating lazy shared timers, queue pumps, pool maintenance,
743
+ * watchers, or exporters so they do not inherit the first Agent that happens
744
+ * to initialize them. It clears only initiator attribution, not explicit
745
+ * fields, and does not own or drain detached resources.
746
+ * @param operation - synchronous or asynchronous operation to invoke without an initiator.
747
+ * @returns the exact value returned by `operation`.
748
+ * @throws when the initiator scope is closing/disposed, or when `operation` throws.
749
+ */
750
+ withoutInitiator<T>(operation: () => T): T
751
+
752
+ /**
753
+ * Register the agent-creation factory (the loop calls this on construction,
754
+ * effect-scoped). A traced Cordis service is canonicalized to its concrete
755
+ * target; each create/resume call is then traced through that caller's
756
+ * context so ownership follows the caller without stacking proxy layers.
757
+ * Throws if a factory is already registered. Returns the disposer; on
758
+ * dispose the factory slot is cleared.
759
+ * @param factory - the loop-owned factory {@link create}/{@link resume} delegate to.
760
+ * @returns the disposer that clears the factory slot. The exact
761
+ * Cordis effect disposer (single-shot): composite (generator) effects may
762
+ * yield it directly — exact identity nests the teardown in order.
763
+ */
764
+ setFactory(factory: AgentFactory): () => void
765
+
766
+ /**
767
+ * Create and publish a new agent through the registered factory.
768
+ * Distinct from {@link register} (which records an already-constructed
769
+ * agent): this constructs the agent and its session. Rejects if no factory is
770
+ * registered or creation/setup fails. The resolved {@link AgentHandle} lets
771
+ * the owner tear down exactly this agent.
772
+ * @param options - shared identity, session seed/metadata, and agent options.
773
+ * @returns the handle after setup, rollback-covered publication, and loop start complete.
774
+ */
775
+ async create(options: CreateAgentOptions): Promise<AgentHandle>
776
+
777
+ /**
778
+ * Load a persisted session and resume an agent on it through the registered
779
+ * factory. Rejects if no factory is registered; the factory rejects if
780
+ * session persistence is not configured or persistence/setup fails.
781
+ * @param options - persisted identity, configuration, and setup.
782
+ * @returns the handle after setup, rollback-covered publication, and loop start complete.
783
+ */
784
+ async resume(options: ResumeAgentOptions): Promise<AgentHandle>
785
+
786
+ /**
787
+ * Register a live agent with source `startup`. Rejects if the id is already registered or a
788
+ * serial `agent/created` listener fails. Emits `agent/disposed`
789
+ * when the calling fiber is disposed — both with the agent's scope carrier
790
+ * (`scopeTarget(agent, agent)`): the subject is the agent in hand, so the
791
+ * emits are scope-filtered regardless of which context invoked `register`
792
+ * (calling through `agent.ctx` scopes EFFECTS; dispatch scoping always
793
+ * requires passing the carrier). Await registration before using the agent.
794
+ * @param agent - the already-constructed agent to record in the store.
795
+ * @returns the awaitable Cordis effect disposer (single-shot; a repeat call
796
+ * returns undefined without awaiting an in-flight teardown). Exact
797
+ * identity is load-bearing: a composite (generator) effect that owns a
798
+ * teardown ORDER — the agent factory's lifecycle chain — must yield THIS
799
+ * function so Cordis nests the unregistration at that yield position;
800
+ * yielding a wrapper would leave it disposing as a concurrent sibling on
801
+ * owner unload, unregistering the agent (and emitting `agent/disposed`)
802
+ * while its final turn is still draining.
803
+ */
804
+ register(agent: Agent): ReturnType<Context['effect']>
805
+
806
+ /**
807
+ * Insert an already-constructed agent without announcing it. This is the
808
+ * advanced ordered-lifecycle primitive used by the async agent factory: it
809
+ * first completes setup while the agent is unpublished, then assigns the
810
+ * returned detach closure into its pre-installed composite teardown before
811
+ * calling {@link announce}. Ordinary callers use {@link register}.
812
+ * @param agent - the prepared, unpublished agent.
813
+ * @returns an idempotent closure that removes this exact entry and emits
814
+ * `agent/disposed` with listener failures contained. When called from a
815
+ * `agent/created` listener, removal and disposal wait until the serial
816
+ * creation dispatch settles.
817
+ */
818
+ enter(agent: Agent): () => void
819
+
820
+ /**
821
+ * Announce an agent previously inserted with {@link enter}.
822
+ * @param agent - the live inserted agent to announce.
823
+ * @param source - fresh creation, resume, clear, or compaction source.
824
+ * @param signal - optional factory initialization cancellation signal passed to listeners.
825
+ * @returns completion of the serial creation listeners; a listener failure rejects.
826
+ * @throws if `agent` is not the exact live registry entry for its id, or its
827
+ * creation announcement already began (including a reentrant call from a
828
+ * creation listener).
829
+ */
830
+ async announce(agent: Agent, source: SessionStartSource, signal?: AbortSignal): Promise<void>
831
+
832
+ /**
833
+ * Look up a live agent.
834
+ * @param id - the shared agent/session id to look up.
835
+ * @returns the agent, or undefined when no live agent has that id.
836
+ */
837
+ get(id: SessionId): Agent | undefined
838
+
839
+ /**
840
+ * All live agents, in registration order.
841
+ * @returns a fresh array; mutating it does not affect the registry.
842
+ */
843
+ list(): Agent[]
844
+ ```
845
+
846
+ Types: [Session](./session.md)
847
+
848
+ Source: [`packages/core/agent/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/index.ts)
849
+
850
+ <a id="agent-events"></a>
851
+
852
+ ### `agent/*` events
853
+
854
+ <a id="agentassistant-stream--emit"></a>
855
+
856
+ #### `agent/assistant-stream` — emit
857
+
858
+ Process-local assistant-stream publication. Chunk frames are transient; the loop appends one final v2 `assistant/message` or `assistant/attempt` with the same stream before a committed end frame.
859
+
860
+ ```ts cordis-catalog
861
+ /**
862
+ * Process-local assistant-stream publication. Chunk frames are transient;
863
+ * the loop appends one final v2 `assistant/message` or `assistant/attempt`
864
+ * with the same stream before a committed end frame.
865
+ * @param payload.agent - the agent whose attempt produced the frame.
866
+ * @param payload.frame - one ordered start, chunk, or end publication.
867
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
868
+ * @mode emit
869
+ */
870
+ 'agent/assistant-stream'(this: Scoped<Agent>, payload: { agent: Agent; frame: AssistantStreamFrame }): void
871
+ ```
872
+
873
+ Types: [Scoped](./scope.md)
874
+
875
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
876
+
877
+ <a id="agentcreated--serial"></a>
878
+
879
+ #### `agent/created` — serial
880
+
881
+ An entered agent is ready for per-agent initialization after factory setup. Listeners run in order and are awaited before creation resolves. AgentLoop holds queued input until all listeners finish. A throw or rejection fails creation and skips later listeners. Disposal retains the scope and session until dispatch settles; listeners must not await agent.whenIdle() or their own owner's disposal.
882
+
883
+ ```ts cordis-catalog
884
+ /**
885
+ * An entered agent is ready for per-agent initialization after factory setup.
886
+ * Listeners run in order and are awaited before creation resolves. AgentLoop
887
+ * holds queued input until all listeners finish. A throw or rejection fails
888
+ * creation and skips later listeners. Disposal retains the scope and session
889
+ * until dispatch settles; listeners must not await agent.whenIdle() or their
890
+ * own owner's disposal.
891
+ * @param payload.agent - the newly registered agent with its live session and completed setup.
892
+ * @param payload.source - fresh creation, resume, clear, or compaction source.
893
+ * @param payload.signal - factory initialization cancellation signal, when provided.
894
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
895
+ * @mode serial
896
+ */
897
+ 'agent/created'(this: Scoped<Agent>, payload: { agent: Agent; source: SessionStartSource; signal?: AbortSignal }): undefined | Promise<undefined>
898
+ ```
899
+
900
+ Types: [Scoped](./scope.md)
901
+
902
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
903
+
904
+ <a id="agentdisposed--emit"></a>
905
+
906
+ #### `agent/disposed` — emit
907
+
908
+ An agent left the registry; AgentLoop emits this after driver quiescence and scoped-registration unwind, but before session detachment. Custom registry users own their driver-ordering contract.
909
+
910
+ ```ts cordis-catalog
911
+ /**
912
+ * An agent left the registry; AgentLoop emits this after driver quiescence
913
+ * and scoped-registration unwind, but before session detachment. Custom
914
+ * registry users own their driver-ordering contract.
915
+ * @param payload.agent - the exact agent removed from the registry.
916
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
917
+ * @mode emit
918
+ */
919
+ 'agent/disposed'(this: Scoped<Agent>, payload: { agent: Agent }): void
920
+ ```
921
+
922
+ Types: [Scoped](./scope.md)
923
+
924
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
925
+
926
+ <a id="agenterror--emit"></a>
927
+
928
+ #### `agent/error` — emit
929
+
930
+ A step or turn errored. The machine reports a failure here even when the error has no in-turn position for a durable record.
931
+
932
+ ```ts cordis-catalog
933
+ /**
934
+ * A step or turn errored. The machine reports a failure here even when
935
+ * the error has no in-turn position for a durable record.
936
+ * @param payload.agent - the agent whose turn errored.
937
+ * @param payload.turn - the turn in which the failure surfaced.
938
+ * @param payload.step - the step at which the failure surfaced.
939
+ * @param payload.error - the failure, verbatim.
940
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
941
+ * @mode emit
942
+ */
943
+ 'agent/error'(this: Scoped<Agent>, payload: { agent: Agent; turn: number; step: number; error: unknown }): void
944
+ ```
945
+
946
+ Types: [Scoped](./scope.md)
947
+
948
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
949
+
950
+ <a id="agentinboxclaimed--emit"></a>
951
+
952
+ #### `agent/inbox/claimed` — emit
953
+
954
+ One message left the inbox inside its open turn. If the proposed step is rejected, the claimed message ends here: it is neither discarded nor re-emitted as a user/message, and the turn closes without a step.
955
+
956
+ ```ts cordis-catalog
957
+ /**
958
+ * One message left the inbox inside its open turn. If the proposed step
959
+ * is rejected, the claimed message ends here: it is neither discarded nor
960
+ * re-emitted as a user/message, and the turn closes without a step.
961
+ * @param payload.agent - the agent whose inbox changed.
962
+ * @param payload.message - the claimed message.
963
+ * @param payload.turn - the owning turn.
964
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
965
+ * @mode emit
966
+ */
967
+ 'agent/inbox/claimed'(this: Scoped<Agent>, payload: { agent: Agent; message: UserMessage; turn: number }): void
968
+ ```
969
+
970
+ Types: [Scoped](./scope.md) · [UserMessage](./session.md)
971
+
972
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
973
+
974
+ <a id="agentinboxdiscarded--emit"></a>
975
+
976
+ #### `agent/inbox/discarded` — emit
977
+
978
+ One message was discarded from the live inbox.
979
+
980
+ ```ts cordis-catalog
981
+ /**
982
+ * One message was discarded from the live inbox.
983
+ * @param payload.agent - the agent whose inbox changed.
984
+ * @param payload.message - the discarded message.
985
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
986
+ * @mode emit
987
+ */
988
+ 'agent/inbox/discarded'(this: Scoped<Agent>, payload: { agent: Agent; message: UserMessage }): void
989
+ ```
990
+
991
+ Types: [Scoped](./scope.md) · [UserMessage](./session.md)
992
+
993
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
994
+
995
+ <a id="agentinboxinserted--emit"></a>
996
+
997
+ #### `agent/inbox/inserted` — emit
998
+
999
+ One message entered the live inbox.
1000
+
1001
+ ```ts cordis-catalog
1002
+ /**
1003
+ * One message entered the live inbox.
1004
+ * @param payload.agent - the agent whose inbox changed.
1005
+ * @param payload.message - the inserted message.
1006
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1007
+ * @mode emit
1008
+ */
1009
+ 'agent/inbox/inserted'(this: Scoped<Agent>, payload: { agent: Agent; message: UserMessage }): void
1010
+ ```
1011
+
1012
+ Types: [Scoped](./scope.md) · [UserMessage](./session.md)
1013
+
1014
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1015
+
1016
+ <a id="agentpre-step--waterfall"></a>
1017
+
1018
+ #### `agent/pre-step` — waterfall
1019
+
1020
+ Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages.
1021
+
1022
+ ```ts cordis-catalog
1023
+ /**
1024
+ * Reject a proposed step or replace the messages that enter it. Calling
1025
+ * `next()` preserves the current messages.
1026
+ * @param payload.agent - the agent proposing the step.
1027
+ * @param payload.messages - messages removed from the inbox for this step.
1028
+ * @param payload.turn - the turn that will own the step.
1029
+ * @param payload.step - the step proposed by the loop.
1030
+ * @param payload.signal - the current turn's cancellation signal.
1031
+ * @param payload.modelSelection - captured step selection, retained across retries; omitted effort uses adapter defaults.
1032
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1033
+ * @mode waterfall
1034
+ */
1035
+ 'agent/pre-step'(this: Scoped<Agent>, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal; modelSelection: Readonly<ModelSelection> }, next: () => Promise<PreStepDecision>): Promise<PreStepDecision>
1036
+ ```
1037
+
1038
+ Types: [Scoped](./scope.md) · [UserMessage](./session.md)
1039
+
1040
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1041
+
1042
+ <a id="agentrequest-error--waterfall"></a>
1043
+
1044
+ #### `agent/request-error` — waterfall
1045
+
1046
+ Handle one failed model-request attempt before the loop retries or closes its step. A listener returns `{ kind: 'retry' }` without calling `next()` when it owns recovery, or calls `next()` to delegate. The default `undefined` leaves the failure terminal.
1047
+
1048
+ ```ts cordis-catalog
1049
+ /**
1050
+ * Handle one failed model-request attempt before the loop retries or closes
1051
+ * its step. A listener returns `{ kind: 'retry' }` without calling `next()`
1052
+ * when it owns recovery, or calls `next()` to delegate. The default
1053
+ * `undefined` leaves the failure terminal.
1054
+ * @param payload.agent - the agent whose request failed.
1055
+ * @param payload.turn - the turn containing the failed request.
1056
+ * @param payload.step - the step containing the failed request attempt.
1057
+ * @param payload.provider - the provider selected for the failed request.
1058
+ * @param payload.failure - serializable facts normalized at the final adapter boundary.
1059
+ * @param payload.retryPolicy - the policy of the adapter registration that served the failed request.
1060
+ * @param payload.signal - the turn abort signal.
1061
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1062
+ * @mode waterfall
1063
+ */
1064
+ 'agent/request-error'(this: Scoped<Agent>, payload: { agent: Agent; turn: number; step: number; provider: string; failure: LlmFailure; retryPolicy: ResolvedRetryPolicy | undefined; signal: AbortSignal }, next: () => Promise<RequestErrorAction>): Promise<RequestErrorAction>
1065
+ ```
1066
+
1067
+ Types: [LlmFailure](./llm-streaming.md) · [ResolvedRetryPolicy](./llm-streaming.md) · [Scoped](./scope.md)
1068
+
1069
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1070
+
1071
+ <a id="agentstatus--emit"></a>
1072
+
1073
+ #### `agent/status` — emit
1074
+
1075
+ Agent status changed (`idle` ⇄ `running`). A waking delivery enters `running` synchronously after reserving cancellation; `idle` means no driver remains scheduled or active.
1076
+
1077
+ ```ts cordis-catalog
1078
+ /**
1079
+ * Agent status changed (`idle` ⇄ `running`). A waking delivery enters
1080
+ * `running` synchronously after reserving cancellation; `idle` means no
1081
+ * driver remains scheduled or active.
1082
+ * @param payload.agent - the agent whose status flipped.
1083
+ * @param payload.status - the status just entered (the transition's destination).
1084
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1085
+ * @mode emit
1086
+ */
1087
+ 'agent/status'(this: Scoped<Agent>, payload: { agent: Agent; status: AgentStatus }): void
1088
+ ```
1089
+
1090
+ Types: [Scoped](./scope.md)
1091
+
1092
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1093
+
1094
+ <a id="agentturn-stopping--serial"></a>
1095
+
1096
+ #### `agent/turn-stopping` — serial
1097
+
1098
+ The turn is about to close: the model owes no response (no live tool calls, no fresh steering). Awaited before the boundary commits — a listener that objects steers (`agent.steer(...)`) and the machine re-reads its inbox: fresh steering runs another step, none closes the turn. Data decides, so listener order cannot change the outcome. The inverse control (stop a tool loop early) is data too: a tool result carrying `concludesTurn` ends the turn at its step. The conclusion never short-circuits already-submitted next-step work: same-step `additionalContexts` or racing steering still runs, and the turn closes only when that inbox drains.
1099
+
1100
+ ```ts cordis-catalog
1101
+ /**
1102
+ * The turn is about to close: the model owes no response (no live tool
1103
+ * calls, no fresh steering). Awaited before the boundary commits — a
1104
+ * listener that objects steers (`agent.steer(...)`) and the machine
1105
+ * re-reads its inbox: fresh steering runs another step, none closes the
1106
+ * turn. Data decides, so listener order cannot change the outcome. The
1107
+ * inverse control (stop a tool loop early) is data too: a tool result
1108
+ * carrying `concludesTurn` ends the turn at its step. The conclusion
1109
+ * never short-circuits already-submitted next-step work: same-step
1110
+ * `additionalContexts` or racing steering still runs, and the turn
1111
+ * closes only when that inbox drains.
1112
+ * @param payload.agent - the agent whose turn is at its stop boundary.
1113
+ * @param payload.turn - the turn about to close.
1114
+ * @param payload.signal - the current turn's explicit abort signal.
1115
+ * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.
1116
+ * @mode serial
1117
+ */
1118
+ 'agent/turn-stopping'(this: Scoped<Agent>, payload: { agent: Agent; turn: number; signal: AbortSignal }): Promise<void> | void
1119
+ ```
1120
+
1121
+ Types: [Scoped](./scope.md)
1122
+
1123
+ Source: [`packages/core/agent/src/runtime-types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent/src/runtime-types.ts)
1124
+
1125
+ <a id="agent-loop-events"></a>
1126
+
1127
+ ### `agent-loop/*` events
1128
+
1129
+ <a id="agent-loopconfig-start-failed--emit"></a>
1130
+
1131
+ #### `agent-loop/config-start-failed` — emit
1132
+
1133
+ A declarative agent entry failed before it could publish a live agent. Consumers that buffer work for the configured identity use this transient signal to reject that work instead of waiting forever. Normal factory teardown suppresses failures from the cancelled startup attempt.
1134
+
1135
+ ```ts cordis-catalog
1136
+ /**
1137
+ * A declarative agent entry failed before it could publish a live agent.
1138
+ * Consumers that buffer work for the configured identity use this
1139
+ * transient signal to reject that work instead of waiting forever. Normal
1140
+ * factory teardown suppresses failures from the cancelled startup attempt.
1141
+ * @param payload.sessionId - exact shared agent/session identity that failed startup.
1142
+ * @param payload.error - persistence, setup, or publication failure.
1143
+ * @mode emit
1144
+ */
1145
+ 'agent-loop/config-start-failed'(payload: { sessionId: SessionId; error: unknown }): void
1146
+ ```
1147
+
1148
+ Source: [`packages/core/agent-loop/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/core/agent-loop/src/index.ts)
1149
+
1150
+ <a id="agent-preset-events"></a>
1151
+
1152
+ ### `agent-preset/*` events
1153
+
1154
+ <a id="agent-presetselected--emit"></a>
1155
+
1156
+ #### `agent-preset/selected` — emit
1157
+
1158
+ One session committed a different agent preset to its durable log. Consumers invalidate only state derived from that session's composition.
1159
+
1160
+ ```ts cordis-catalog
1161
+ /**
1162
+ * One session committed a different agent preset to its durable log.
1163
+ * Consumers invalidate only state derived from that session's composition.
1164
+ * @mode emit
1165
+ * @param sessionId - the session whose composition changed.
1166
+ * @param agentPreset - the preset recorded by the committed selection.
1167
+ */
1168
+ 'agent-preset/selected'(sessionId: SessionId, agentPreset: string): void
1169
+ ```
1170
+
1171
+ Source: [`packages/preset/agent-preset-registry/src/types.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/preset/agent-preset-registry/src/types.ts)
1172
+ <!-- END GENERATED cordis-surface -->