@acryldev/plugin-context 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/LICENSE +21 -0
  2. package/docs/README.md +160 -0
  3. package/docs/delivery/local-live.md +113 -0
  4. package/docs/delivery/marketplace.md +16 -0
  5. package/docs/docs.json +2836 -0
  6. package/docs/extending/agent-preset.md +37 -0
  7. package/docs/extending/chat-command.md +28 -0
  8. package/docs/extending/client-slot.md +135 -0
  9. package/docs/extending/config-schema.md +7 -0
  10. package/docs/extending/cordis-core.md +63 -0
  11. package/docs/extending/desktop-app.md +53 -0
  12. package/docs/extending/desktop-main.md +25 -0
  13. package/docs/extending/event-hook.md +14 -0
  14. package/docs/extending/host-route.md +33 -0
  15. package/docs/extending/llm-adapter.md +38 -0
  16. package/docs/extending/packaging.md +53 -0
  17. package/docs/extending/prompt-contribution.md +9 -0
  18. package/docs/extending/service.md +13 -0
  19. package/docs/extending/skill-provider.md +9 -0
  20. package/docs/extending/state-and-persistence.md +71 -0
  21. package/docs/extending/three-role-capability.md +33 -0
  22. package/docs/extending/tool-plugin.md +24 -0
  23. package/docs/extending/tui-command.md +8 -0
  24. package/docs/extending/tui-components.md +61 -0
  25. package/docs/extending/ui-branding.md +43 -0
  26. package/docs/extending/ui-components.md +56 -0
  27. package/docs/extending/ui-customization.md +41 -0
  28. package/docs/extending/ui-library.md +66 -0
  29. package/docs/extending/ui-theme.md +55 -0
  30. package/docs/extending/workspace-tab.md +50 -0
  31. package/docs/maps/events.md +108 -0
  32. package/docs/maps/mount-points.md +154 -0
  33. package/docs/maps/slot-contracts.md +3376 -0
  34. package/docs/maps/taxonomy.md +306 -0
  35. package/docs/maps/theme-tokens.md +115 -0
  36. package/docs/maps/ui-components.md +26 -0
  37. package/docs/reference/cookbook/adding-a-package.md +174 -0
  38. package/docs/reference/cookbook/adding-a-remote-api.md +199 -0
  39. package/docs/reference/cookbook/adding-a-settings-card.md +74 -0
  40. package/docs/reference/cookbook/adding-a-tool.md +103 -0
  41. package/docs/reference/cookbook/adding-an-llm-adapter.md +45 -0
  42. package/docs/reference/cookbook/extension-cookbook.md +134 -0
  43. package/docs/reference/cordis-api/context.md +366 -0
  44. package/docs/reference/cordis-api/events.md +209 -0
  45. package/docs/reference/cordis-api/fiber.md +377 -0
  46. package/docs/reference/cordis-api/inherited.md +40 -0
  47. package/docs/reference/cordis-api/registry.md +154 -0
  48. package/docs/reference/cordis-api/service.md +104 -0
  49. package/docs/reference/cordis-guides/cordis-usage-cheatsheet.md +167 -0
  50. package/docs/reference/cordis-guides/cordis_system_guide_for_coding_agents.md +4666 -0
  51. package/docs/reference/cordis-guides/development-canvas-plugin.md +109 -0
  52. package/docs/reference/cordis-guides/hello-world-plugin-guide.md +517 -0
  53. package/docs/reference/harness/agent-lifecycle.md +93 -0
  54. package/docs/reference/harness/architecture.md +168 -0
  55. package/docs/reference/harness/capability-seams.md +675 -0
  56. package/docs/reference/harness/config-catalog.md +4523 -0
  57. package/docs/reference/harness/cordis-primer.md +47 -0
  58. package/docs/reference/harness/defensive-patterns.md +35 -0
  59. package/docs/reference/harness/event-producer-consumer.md +111 -0
  60. package/docs/reference/harness/glossary.md +47 -0
  61. package/docs/reference/harness/tool-catalog.md +2721 -0
  62. package/docs/reference/harness/tool-execution-pipeline.md +67 -0
  63. package/docs/reference/subsystems/README.md +75 -0
  64. package/docs/reference/subsystems/agent-team.md +233 -0
  65. package/docs/reference/subsystems/approval.md +172 -0
  66. package/docs/reference/subsystems/attachment.md +363 -0
  67. package/docs/reference/subsystems/boot.md +324 -0
  68. package/docs/reference/subsystems/browser-use.md +69 -0
  69. package/docs/reference/subsystems/client-modules.md +186 -0
  70. package/docs/reference/subsystems/client-resources.md +94 -0
  71. package/docs/reference/subsystems/commands.md +225 -0
  72. package/docs/reference/subsystems/compaction.md +286 -0
  73. package/docs/reference/subsystems/computer-use.md +58 -0
  74. package/docs/reference/subsystems/conversation.md +287 -0
  75. package/docs/reference/subsystems/core.md +1107 -0
  76. package/docs/reference/subsystems/credentials.md +497 -0
  77. package/docs/reference/subsystems/deliverables.md +180 -0
  78. package/docs/reference/subsystems/extensions.md +386 -0
  79. package/docs/reference/subsystems/feedback.md +402 -0
  80. package/docs/reference/subsystems/filesystem.md +532 -0
  81. package/docs/reference/subsystems/goal.md +315 -0
  82. package/docs/reference/subsystems/invariants.md +90 -0
  83. package/docs/reference/subsystems/jobs.md +501 -0
  84. package/docs/reference/subsystems/llm-streaming.md +1131 -0
  85. package/docs/reference/subsystems/lsp.md +204 -0
  86. package/docs/reference/subsystems/mcp.md +141 -0
  87. package/docs/reference/subsystems/office-to-pdf.md +89 -0
  88. package/docs/reference/subsystems/otel.md +46 -0
  89. package/docs/reference/subsystems/permission-presets.md +169 -0
  90. package/docs/reference/subsystems/persistence.md +418 -0
  91. package/docs/reference/subsystems/plan.md +89 -0
  92. package/docs/reference/subsystems/product-telemetry.md +81 -0
  93. package/docs/reference/subsystems/ptc-runtime.md +234 -0
  94. package/docs/reference/subsystems/sandbox.md +223 -0
  95. package/docs/reference/subsystems/schedule.md +545 -0
  96. package/docs/reference/subsystems/scope.md +61 -0
  97. package/docs/reference/subsystems/session-projection.md +358 -0
  98. package/docs/reference/subsystems/session-query.md +511 -0
  99. package/docs/reference/subsystems/session-reference.md +226 -0
  100. package/docs/reference/subsystems/session-telemetry.md +214 -0
  101. package/docs/reference/subsystems/session-title.md +206 -0
  102. package/docs/reference/subsystems/session.md +1300 -0
  103. package/docs/reference/subsystems/settings.md +157 -0
  104. package/docs/reference/subsystems/shell.md +316 -0
  105. package/docs/reference/subsystems/sidebar-right.md +160 -0
  106. package/docs/reference/subsystems/skills.md +354 -0
  107. package/docs/reference/subsystems/slots.md +201 -0
  108. package/docs/reference/subsystems/spill.md +126 -0
  109. package/docs/reference/subsystems/ssh.md +137 -0
  110. package/docs/reference/subsystems/storage.md +262 -0
  111. package/docs/reference/subsystems/subagent.md +762 -0
  112. package/docs/reference/subsystems/subprocess.md +323 -0
  113. package/docs/reference/subsystems/system-prompt.md +226 -0
  114. package/docs/reference/subsystems/terminal.md +186 -0
  115. package/docs/reference/subsystems/todo.md +34 -0
  116. package/docs/reference/subsystems/token-meter.md +108 -0
  117. package/docs/reference/subsystems/tools.md +749 -0
  118. package/docs/reference/subsystems/typert.md +489 -0
  119. package/docs/reference/subsystems/user-questions.md +309 -0
  120. package/docs/reference/subsystems/voice-input.md +166 -0
  121. package/docs/reference/subsystems/web-client.md +102 -0
  122. package/docs/reference/subsystems/web-server.md +228 -0
  123. package/docs/reference/subsystems/web.md +208 -0
  124. package/docs/reference/subsystems/webhook.md +72 -0
  125. package/docs/reference/subsystems/workflow.md +280 -0
  126. package/docs/reference/subsystems/workspace.md +661 -0
  127. package/docs/start-here/blueprints.md +33 -0
  128. package/docs/start-here/this-runtime.md +84 -0
  129. package/docs/start-here/troubleshooting.md +29 -0
  130. package/docs/start-here/trust-and-safety.md +39 -0
  131. package/docs/start-here/verify-before-done.md +46 -0
  132. package/example-plugins/README.md +45 -0
  133. package/example-plugins/packages/agent-preset-reviewer/agent.cordis.yml +18 -0
  134. package/example-plugins/packages/agent-preset-reviewer/preset.yml +3 -0
  135. package/example-plugins/packages/capability-swap-consumer/cordis.patch.yml +3 -0
  136. package/example-plugins/packages/capability-swap-consumer/index.js +14 -0
  137. package/example-plugins/packages/capability-swap-consumer/package.json +25 -0
  138. package/example-plugins/packages/capability-swap-provider-loud/cordis.patch.yml +3 -0
  139. package/example-plugins/packages/capability-swap-provider-loud/index.js +20 -0
  140. package/example-plugins/packages/capability-swap-provider-loud/package.json +25 -0
  141. package/example-plugins/packages/capability-swap-provider-quiet/cordis.patch.yml +3 -0
  142. package/example-plugins/packages/capability-swap-provider-quiet/index.js +20 -0
  143. package/example-plugins/packages/capability-swap-provider-quiet/package.json +25 -0
  144. package/example-plugins/packages/chat-command-basic/cordis.patch.yml +3 -0
  145. package/example-plugins/packages/chat-command-basic/index.js +26 -0
  146. package/example-plugins/packages/chat-command-basic/package.json +25 -0
  147. package/example-plugins/packages/client-chat-message-action/client.js +46 -0
  148. package/example-plugins/packages/client-chat-message-action/cordis.patch.yml +3 -0
  149. package/example-plugins/packages/client-chat-message-action/index.js +9 -0
  150. package/example-plugins/packages/client-chat-message-action/package.json +31 -0
  151. package/example-plugins/packages/client-slot-header-action/client.js +57 -0
  152. package/example-plugins/packages/client-slot-header-action/cordis.patch.yml +3 -0
  153. package/example-plugins/packages/client-slot-header-action/index.js +13 -0
  154. package/example-plugins/packages/client-slot-header-action/package.json +31 -0
  155. package/example-plugins/packages/client-slot-sidebar-tab/client.js +57 -0
  156. package/example-plugins/packages/client-slot-sidebar-tab/cordis.patch.yml +3 -0
  157. package/example-plugins/packages/client-slot-sidebar-tab/index.js +9 -0
  158. package/example-plugins/packages/client-slot-sidebar-tab/package.json +32 -0
  159. package/example-plugins/packages/client-theme-override/client.js +52 -0
  160. package/example-plugins/packages/client-theme-override/cordis.patch.yml +3 -0
  161. package/example-plugins/packages/client-theme-override/index.js +9 -0
  162. package/example-plugins/packages/client-theme-override/package.json +30 -0
  163. package/example-plugins/packages/client-tool-view/client.js +47 -0
  164. package/example-plugins/packages/client-tool-view/cordis.patch.yml +3 -0
  165. package/example-plugins/packages/client-tool-view/index.js +24 -0
  166. package/example-plugins/packages/client-tool-view/package.json +34 -0
  167. package/example-plugins/packages/client-ui-components/client.js +77 -0
  168. package/example-plugins/packages/client-ui-components/cordis.patch.yml +3 -0
  169. package/example-plugins/packages/client-ui-components/index.js +9 -0
  170. package/example-plugins/packages/client-ui-components/package.json +31 -0
  171. package/example-plugins/packages/client-ui-library/client.js +715 -0
  172. package/example-plugins/packages/client-ui-library/cordis.patch.yml +3 -0
  173. package/example-plugins/packages/client-ui-library/index.js +9 -0
  174. package/example-plugins/packages/client-ui-library/package.json +37 -0
  175. package/example-plugins/packages/client-workspace-tab/client.js +72 -0
  176. package/example-plugins/packages/client-workspace-tab/cordis.patch.yml +3 -0
  177. package/example-plugins/packages/client-workspace-tab/index.js +9 -0
  178. package/example-plugins/packages/client-workspace-tab/package.json +30 -0
  179. package/example-plugins/packages/config-schema-basic/cordis.patch.yml +3 -0
  180. package/example-plugins/packages/config-schema-basic/index.js +19 -0
  181. package/example-plugins/packages/config-schema-basic/package.json +25 -0
  182. package/example-plugins/packages/desktop-main-profile-info/cordis.patch.yml +3 -0
  183. package/example-plugins/packages/desktop-main-profile-info/index.js +22 -0
  184. package/example-plugins/packages/desktop-main-profile-info/package.json +25 -0
  185. package/example-plugins/packages/event-hook-basic/cordis.patch.yml +3 -0
  186. package/example-plugins/packages/event-hook-basic/index.js +17 -0
  187. package/example-plugins/packages/event-hook-basic/package.json +22 -0
  188. package/example-plugins/packages/generated-capability-template/cordis.patch.yml +3 -0
  189. package/example-plugins/packages/generated-capability-template/index.js +16 -0
  190. package/example-plugins/packages/generated-capability-template/package.json +42 -0
  191. package/example-plugins/packages/host-route-basic/cordis.patch.yml +3 -0
  192. package/example-plugins/packages/host-route-basic/index.js +20 -0
  193. package/example-plugins/packages/host-route-basic/package.json +29 -0
  194. package/example-plugins/packages/lifecycle-function-basic/cordis.patch.yml +3 -0
  195. package/example-plugins/packages/lifecycle-function-basic/index.js +12 -0
  196. package/example-plugins/packages/lifecycle-function-basic/package.json +15 -0
  197. package/example-plugins/packages/lifecycle-function-hot-shim/cordis.patch.yml +3 -0
  198. package/example-plugins/packages/lifecycle-function-hot-shim/impl.js +5 -0
  199. package/example-plugins/packages/lifecycle-function-hot-shim/index.js +18 -0
  200. package/example-plugins/packages/lifecycle-function-hot-shim/package.json +23 -0
  201. package/example-plugins/packages/lifecycle-hooks-observer/cordis.patch.yml +3 -0
  202. package/example-plugins/packages/lifecycle-hooks-observer/index.js +23 -0
  203. package/example-plugins/packages/lifecycle-hooks-observer/package.json +22 -0
  204. package/example-plugins/packages/llm-adapter-echo/cordis.patch.yml +3 -0
  205. package/example-plugins/packages/llm-adapter-echo/index.js +42 -0
  206. package/example-plugins/packages/llm-adapter-echo/package.json +25 -0
  207. package/example-plugins/packages/prompt-assemble-hook/cordis.patch.yml +3 -0
  208. package/example-plugins/packages/prompt-assemble-hook/index.js +22 -0
  209. package/example-plugins/packages/prompt-assemble-hook/package.json +22 -0
  210. package/example-plugins/packages/prompt-contribution-basic/cordis.patch.yml +3 -0
  211. package/example-plugins/packages/prompt-contribution-basic/index.js +18 -0
  212. package/example-plugins/packages/prompt-contribution-basic/package.json +22 -0
  213. package/example-plugins/packages/service-consumer-greeter/cordis.patch.yml +3 -0
  214. package/example-plugins/packages/service-consumer-greeter/index.js +14 -0
  215. package/example-plugins/packages/service-consumer-greeter/package.json +22 -0
  216. package/example-plugins/packages/service-provider-greeter/cordis.patch.yml +3 -0
  217. package/example-plugins/packages/service-provider-greeter/index.js +22 -0
  218. package/example-plugins/packages/service-provider-greeter/package.json +25 -0
  219. package/example-plugins/packages/settings-section-basic/cordis.patch.yml +3 -0
  220. package/example-plugins/packages/settings-section-basic/index.js +34 -0
  221. package/example-plugins/packages/settings-section-basic/package.json +26 -0
  222. package/example-plugins/packages/skill-provider-basic/cordis.patch.yml +3 -0
  223. package/example-plugins/packages/skill-provider-basic/index.js +31 -0
  224. package/example-plugins/packages/skill-provider-basic/package.json +22 -0
  225. package/example-plugins/packages/state-host-store/client.js +57 -0
  226. package/example-plugins/packages/state-host-store/cordis.patch.yml +3 -0
  227. package/example-plugins/packages/state-host-store/index.js +90 -0
  228. package/example-plugins/packages/state-host-store/package.json +31 -0
  229. package/example-plugins/packages/state-workspace-file/cordis.patch.yml +3 -0
  230. package/example-plugins/packages/state-workspace-file/index.js +52 -0
  231. package/example-plugins/packages/state-workspace-file/package.json +25 -0
  232. package/example-plugins/packages/tool-basic/cordis.patch.yml +3 -0
  233. package/example-plugins/packages/tool-basic/index.js +25 -0
  234. package/example-plugins/packages/tool-basic/package.json +25 -0
  235. package/example-plugins/packages/tool-policy-hook/cordis.patch.yml +3 -0
  236. package/example-plugins/packages/tool-policy-hook/index.js +28 -0
  237. package/example-plugins/packages/tool-policy-hook/package.json +25 -0
  238. package/example-plugins/packages/tui-command-basic/cordis.patch.yml +3 -0
  239. package/example-plugins/packages/tui-command-basic/index.js +24 -0
  240. package/example-plugins/packages/tui-command-basic/package.json +22 -0
  241. package/example-plugins/packages/tui-overlay-themed/cordis.patch.yml +3 -0
  242. package/example-plugins/packages/tui-overlay-themed/index.js +65 -0
  243. package/example-plugins/packages/tui-overlay-themed/package.json +25 -0
  244. package/example-plugins/packages/tui-ui-library/cordis.patch.yml +3 -0
  245. package/example-plugins/packages/tui-ui-library/index.js +73 -0
  246. package/example-plugins/packages/tui-ui-library/package.json +29 -0
  247. package/example-plugins/packages/web-page-branding/cordis.patch.yml +3 -0
  248. package/example-plugins/packages/web-page-branding/index.js +31 -0
  249. package/example-plugins/packages/web-page-branding/package.json +22 -0
  250. package/example-plugins/scenarios.json +11 -0
  251. package/index.js +384 -0
  252. package/lib/blend-apply.js +107 -0
  253. package/lib/blend-capture.js +249 -0
  254. package/lib/blend-ledger.js +76 -0
  255. package/lib/contract.js +5 -0
  256. package/lib/install.js +516 -0
  257. package/lib/lookup.js +67 -0
  258. package/lib/manifest.js +56 -0
  259. package/lib/pack-root.js +22 -0
  260. package/lib/provenance.js +110 -0
  261. package/lib/publish.js +64 -0
  262. package/lib/reconcile.js +83 -0
  263. package/lib/router.js +55 -0
  264. package/lib/scopes.js +82 -0
  265. package/lib/skills.js +54 -0
  266. package/lib/stage.js +157 -0
  267. package/lib/verify.js +77 -0
  268. package/package.json +56 -3
  269. package/scripts/lib/indexes.mjs +45 -0
  270. package/scripts/lib/manifest.mjs +127 -0
  271. package/scripts/lib/maps.mjs +482 -0
  272. package/skills/acryl-add-provider-or-capability/SKILL.md +12 -0
  273. package/skills/acryl-add-ui/SKILL.md +18 -0
  274. package/skills/acryl-build-plugin/SKILL.md +21 -0
  275. package/skills/acryl-change-plugin/SKILL.md +16 -0
  276. package/skills/acryl-desktop-shell/SKILL.md +12 -0
  277. package/skills/acryl-diagnose-plugin/SKILL.md +10 -0
  278. package/skills/acryl-fix-plugin/SKILL.md +12 -0
  279. package/skills/acryl-improve-ui/SKILL.md +10 -0
  280. package/skills/acryl-remove-plugin/SKILL.md +11 -0
  281. package/skills/acryl-restyle-ui/SKILL.md +14 -0
  282. package/skills/acryl-share-plugin/SKILL.md +23 -0
  283. package/skills/acryl-tui-ui/SKILL.md +12 -0
  284. package/README.md +0 -3
@@ -0,0 +1,1131 @@
1
+ <!-- Synced from deepseek-harness:docs/subsystems/llm-streaming.md @ 639ed01539. Do not edit; run scripts/sync-corpus.mjs. Relative links inside may not resolve here. -->
2
+
3
+ # LLM Streaming
4
+
5
+ English | [中文](llm-streaming.zh.md)
6
+
7
+ The conversation and streaming types from [`packages/llm`](../../packages/llm/README.md): durable `Message` values, request-only user inputs, shared `ContentBlock` variants, the fully assembled model request, the raw `StreamChunk` protocol, the adapter contract every adapter must implement, and the shared assembler. The [core packages](core.md) hold and log these values on every turn; this page declares them.
8
+
9
+ Source: [`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts)
10
+
11
+ <a id="content-blocks-and-messages"></a>
12
+
13
+ ## Content blocks and messages
14
+
15
+ A conversation is `Message`s; a message is an array of typed **content blocks**. The block union derives from `ContentBlockMap`.
16
+
17
+ Source: [`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts)
18
+
19
+ ```ts type-equiv
20
+ /**
21
+ * Merge-extensible content blocks keyed by `type`. New core blocks must land
22
+ * with adapter, UI, and compaction support. Tool-change blocks belong to
23
+ * developer messages; `projectToolUpdates` selects what each route receives.
24
+ */
25
+ interface ContentBlockMap {
26
+ 'text': TextBlock
27
+ 'reasoning': ReasoningBlock
28
+ 'image': ImageBlock
29
+ 'file': FileBlock
30
+ 'tool-call': ToolCallBlock
31
+ 'tool-addition': ToolAdditionBlock
32
+ 'tool-removal': ToolRemovalBlock
33
+ }
34
+ ```
35
+
36
+ The block interfaces (full fields in source): `TextBlock` (`text`), `ReasoningBlock` (thinking, distinct from visible text), `ImageBlock` (a durable [image attachment](attachment.md)), `FileBlock` (a durable verbatim [file attachment](attachment.md) that request assembly projects to handle text for every route), and `ToolCallBlock` (`id: ToolCallId`, `name`, raw-JSON `arguments`). Tool results are first-class `ToolResultMessage` values with `toolCallId`, result `content`, and optional `isError`; they are not content blocks. `ContentBlock = ContentBlockMap[ContentBlockType]`. A new modality belongs in the merge-extensible map only when its adapter, UI, compaction, and durable replay paths honor it. Developer tool-change blocks are projected according to the resolved route capability.
37
+
38
+ Image access belongs to request serialization rather than the durable attachment or deterministic request-image version. `resolveImageAttachmentAccess()` combines the attachment provider's optional host object path with a mapping supplied by the consumer for the current tool execution filesystem. The result is available only for that request and does not participate in `variantId`.
39
+
40
+ Source: [`packages/llm/llm/src/content.ts`](../../packages/llm/llm/src/content.ts)
41
+
42
+ ```ts type-equiv
43
+ /** Execution-world path that model tools can use to read one normalized attachment. */
44
+ interface ImageAttachmentAccess {
45
+ /** Absolute path to immutable normalized bytes; callers must treat it as read-only. */
46
+ readonlyPath: string
47
+ }
48
+ ```
49
+
50
+ Source: [`packages/llm/llm/src/message.ts`](../../packages/llm/llm/src/message.ts)
51
+
52
+ A `Message` is one identified, immutable role/source/content value. Model-produced assistant messages name the provider and model that produced them and carry optional adapter-private replay data in their source:
53
+
54
+ ```ts type-equiv
55
+ /** Provider/model identity and adapter-private replay data for an assistant message. */
56
+ interface AssistantProviderMetadata {
57
+ /** Provider route that produced the message. */
58
+ provider: string
59
+ /** Provider model id that produced the message. */
60
+ model: string
61
+ /**
62
+ * Lossless-JSON adapter state needed to replay the provider response.
63
+ * `LlmRuntime` exposes it to a target adapter only when that adapter instance
64
+ * currently owns both this historical provider and the target provider.
65
+ */
66
+ replayState?: unknown
67
+ }
68
+ ```
69
+
70
+ ```ts type-equiv
71
+ /** Any persisted conversation message, discriminated by its `role`. */
72
+ type Message = MessageRoleMap[keyof MessageRoleMap]
73
+ ```
74
+
75
+ `DeveloperMessage` records incremental agent session changes in conversation order with the `developer` role. `ToolAdditionBlock.toolName` activates the definition selected by the containing Session event's historical header reference; `ToolRemovalBlock.toolName` removes the active definition. Both blocks are rejected in other message roles. `deferLoading` independently requests deferred definition loading without requiring an addition record. See [Session](../../packages/core/session/README.md) for header binding and the [LLM package](../../packages/llm/llm/README.md#known-limitations-and-deferred-work) for provider support limits. `ToolUpdate` is `in-history` or `addition-only` on resolved and prepared model metadata. `GenerateOptions.toolHistory` carries `ToolHistory`: initial `tools` and ordered `updates`, each binding a developer `messageId` to its historically resolved `additions`. The runtime projects this state into provider declarations; it does not change the active tool list in logged headers.
76
+
77
+ Where a message came from is itself a merge-extensible sum type:
78
+
79
+ ```ts type-equiv
80
+ /**
81
+ * Where a message (or injected content) came from, in the harness's own
82
+ * vocabulary. Merge-extensible sum type - each producer declares its own
83
+ * `kind` in its own module; there is no shared catch-all `plugin` kind.
84
+ * Model and tool sources answer their role messages; user messages carry any
85
+ * producer's kind, and consumers fall through unknown kinds.
86
+ */
87
+ interface MessageSourceMap {
88
+ user: { kind: 'user' }
89
+ model: ModelMessageSource
90
+ tool: ToolMessageSource
91
+ 'system-prompt': SystemPromptMessageSource
92
+ }
93
+ ```
94
+
95
+ Producer identity and presentation form are independent. `kind` answers *who produced this*; the optional `form` answers *what kind of information this is*, and consumers decide how to present it. Several producers may share one form, and one producer may emit more than one form over a session. The values are semantic and grow one at a time; an absent or unrecognized value uses the documented default and is presented as opaque content:
96
+
97
+ ```ts type-equiv
98
+ /**
99
+ * The kind of information in producer-supplied context, declared by the
100
+ * producer in the same `MessageSource`.
101
+ *
102
+ * `MessageSource.kind` answers *who produced this*; `form` answers *what kind
103
+ * of thing it is*, and the two axes are deliberately independent - several
104
+ * producers share one form, and one producer may emit more than one form over
105
+ * a session.
106
+ *
107
+ * The vocabulary is SEMANTIC, never visual: a value states that the content is
108
+ * a file's instructions or a catalog of available items, and a consumer decides
109
+ * what that looks like. Colors, icons, ordering, and collapse defaults are the
110
+ * consumer's business and must not enter this union. It grows one value at a
111
+ * time as producers gain the structured fields their form needs; an absent or
112
+ * unknown value is the documented default, presented as opaque content.
113
+ */
114
+ type ContextForm =
115
+ /** Instructions read out of workspace files the model is expected to follow. */
116
+ | 'instructions'
117
+ /** A catalog of items available in this session, republished as it changes. */
118
+ | 'catalog'
119
+ /** Current state, where a later snapshot from the same producer supersedes an earlier one. */
120
+ | 'snapshot'
121
+ /** A one-off account of something that just happened; it supersedes nothing. */
122
+ | 'notice'
123
+ /** A message another agent addressed to this one. */
124
+ | 'relay'
125
+ /** Material lifted out of another session's log, possibly reduced on the way in. */
126
+ | 'recall'
127
+ ```
128
+
129
+ ```ts type-equiv
130
+ /** One named contribution to a `snapshot`-form context, in assembly order. */
131
+ interface ContextSnapshotSection {
132
+ /** The contributing subsystem's name. */
133
+ readonly name: string
134
+ /** That contribution's model-facing text, exactly as assembled. */
135
+ readonly text: string
136
+ }
137
+ ```
138
+
139
+ ```ts type-equiv
140
+ /**
141
+ * Producer-declared {@link ContextForm} and the fields that form requires,
142
+ * mixed into the source types that carry one.
143
+ *
144
+ * Discriminated by `form` so a producer cannot select a form without the
145
+ * fields needed to present it: a `notice` must record its one-line
146
+ * account, a `snapshot` its sections. Omitting `form` stays valid - an
147
+ * undeclared context is the documented default.
148
+ */
149
+ type ContextFormed =
150
+ | { readonly form?: never }
151
+ | { readonly form: 'instructions' }
152
+ | { readonly form: 'catalog' }
153
+ | {
154
+ readonly form: 'snapshot'
155
+ /** The named contributions this snapshot assembled, in order. */
156
+ readonly sections: readonly ContextSnapshotSection[]
157
+ }
158
+ | {
159
+ readonly form: 'notice'
160
+ /** One-line account of what happened, shown without expanding the row. */
161
+ readonly summary: string
162
+ }
163
+ | { readonly form: 'relay' }
164
+ | { readonly form: 'recall' }
165
+ ```
166
+
167
+ <a id="streamchunk--the-raw-protocol"></a>
168
+
169
+ ## `StreamChunk` - the raw protocol
170
+
171
+ A streaming response interleaves several typed blocks (text, reasoning, multiple tool calls). `index` ties each delta to its block; `block-end` carries the fully-assembled `ContentBlock` so consumers don't have to re-assemble deltas themselves. It is a **closed** discriminated union - a `switch` over `type` ends with `assertNever`, so adding a variant breaks compilation at every consumer that must handle it.
172
+
173
+ ```ts type-equiv
174
+ /**
175
+ * Adapter-private lossless-JSON state for replaying a successful response,
176
+ * carried by a terminal `finish` chunk and stored on the assembled assistant
177
+ * message's model source. Both halves stay opaque to the harness; only the
178
+ * split is shared vocabulary, so assembly can keep stored metadata aligned
179
+ * with stored content without reading either half.
180
+ */
181
+ interface ReplayEnvelope {
182
+ /** Response-level adapter-private metadata (ids, native stop reason). */
183
+ response: unknown
184
+ /**
185
+ * Per-block adapter-private metadata, one entry per emitted block in
186
+ * first-seen stream order. When assembly drops a block it drops the entry at
187
+ * the same position; entries whose length does not match the emitted block
188
+ * count discard the whole envelope. An adapter whose metadata is independent
189
+ * of block structure omits this field and the envelope passes through
190
+ * assembly unchanged.
191
+ */
192
+ blocks?: readonly unknown[]
193
+ }
194
+ ```
195
+
196
+ ```ts type-equiv
197
+ /**
198
+ * Raw streaming protocol emitted by adapters.
199
+ * Block indexes correlate interleaved deltas, and `block-end` carries the
200
+ * assembled block. Adapters emit usage before the terminal finish and nothing
201
+ * afterward; tool arguments remain raw JSON strings. An adapter implementation
202
+ * may throw, but `LlmRuntime.stream()` normalizes that failure to a terminal
203
+ * `error` or `aborted` finish before exposing it to consumers.
204
+ */
205
+ type StreamChunk =
206
+ | { type: 'block-start'; index: number; blockType: ContentBlockType }
207
+ | { type: 'text-delta'; index: number; text: string }
208
+ | { type: 'reasoning-delta'; index: number; text: string }
209
+ | { type: 'tool-call-delta'; index: number; id: ToolCallId; name?: string; argumentsDelta: string }
210
+ | { type: 'block-end'; index: number; block: ContentBlock }
211
+ | { type: 'usage'; usage: TokenUsage }
212
+ | {
213
+ type: 'finish'
214
+ reason: FinishReason
215
+ /** Replay metadata for a successful response; see {@link ReplayEnvelope}. */
216
+ replayState?: ReplayEnvelope
217
+ }
218
+ ```
219
+
220
+ <a id="compact-assistant-streams"></a>
221
+
222
+ ## Compact Assistant streams
223
+
224
+ `AssistantStreamAccumulator` pairs each `StreamChunk` with its original safe-integer timestamp and produces `AssistantStreamRecord[]`. Consecutive text, reasoning, or tool-argument deltas for the same block become one record with `time0`, exact timestamp gaps, and one array entry per original delta; every other chunk stays a timestamped raw record. This representation removes repeated event envelopes without joining token boundaries or dropping terminal, usage, block, failure, or replay facts.
225
+
226
+ `snapshot()` returns a detached immutable stream. `expandAssistantStream()` strictly checks record keys, member counts, indexes, timestamps, tool-call identity, and lossless JSON before recreating the exact timed chunk sequence. The Session log embeds this stream in `assistant/message` for a surface result or `assistant/attempt` for an attempt with no surface message.
227
+
228
+ Process-local `agent/assistant-stream` frames carry live presentation. Durable replay and restore validation still expand the embedded settlement; telemetry, token accounting, and Host folds read the compact records directly. Record-level readers (`assistantStreamFirstTokenTime`, `assistantStreamHasVisibleContent`, `assistantStreamHasVisibleText`, `lastAssistantStreamChunk`, `assistantStreamChunks`, `joinAssistantStreamText`, `assembleAssistantStream`, and the per-run `runFirstTokenTime` and `runFirstVisibleTime`) answer consumer questions in one pass over the records with early exit, so a large history costs O(records) per settlement instead of O(members) expansion ([fold decision](../../.agents/notes/implemented/architecture/2026-09-06-embedded-stream-record-readers.md)). `expandAssistantStream()` remains the validating path for records read at a durable boundary and for consumers that need every member.
229
+
230
+ ## `LlmFailure`
231
+
232
+ Every thrown or in-band final-adapter failure normalizes to one serializable provider-neutral payload. `providerRetryAfterMs` is a validated positive delay requested by the provider, not a retry decision; `ProviderRequestId` is an opaque branded string for diagnostics.
233
+
234
+ ```ts type-equiv
235
+ /** Serializable provider or transport failure facts; policy decides whether they are retryable. */
236
+ interface LlmFailure {
237
+ /** Human-readable provider or transport failure. */
238
+ readonly message: string
239
+ /** Stable provider-neutral machine-routing code. */
240
+ readonly code: string
241
+ /** HTTP status returned by the provider, when available. */
242
+ readonly status?: number
243
+ /** Provider-requested delay in milliseconds, when valid and available. */
244
+ readonly providerRetryAfterMs?: number
245
+ /** Opaque provider-issued request identifier for diagnostics. */
246
+ readonly requestId?: ProviderRequestId
247
+ /**
248
+ * With code `IMAGE_OFFLOAD_REQUIRED`: how many more of the oldest retained
249
+ * image occurrences the route needs offloaded before the same request fits
250
+ * its exact byte accounting. `dsh-compaction-image-offload` records the
251
+ * selected occurrences in an `image/offload` event and retries the step.
252
+ */
253
+ readonly offloadImages?: number
254
+ }
255
+ ```
256
+
257
+ ## Request-image pricing
258
+
259
+ An adapter whose provider charges visual tokens for request images declares per-route pricing by overriding `LlmAdapter.imageRequestPricing`, and `ctx.llm.imageRequestPricing(provider, model)` resolves it synchronously for consumers. The token meter resolves the routed model's pricing on every measurement so compaction pressure, retention, and range selection price image history as the routed request actually sends it; the DeepSeek adapter prices each retained occurrence at its per-model request target with the published vision accounting and each occurrence selected by a logged image-offload decision as its placeholder text, while provider usage remains the authoritative anchor for completed requests.
260
+
261
+ ```ts type-equiv
262
+ /**
263
+ * Request price of one ordered image occurrence under one exact model route's
264
+ * request projection. Every occurrence resolves to the pair the wire actually
265
+ * carries: provider visual tokens for a retained image, plus the model-visible
266
+ * text sent with or instead of it (request-preview handle, offload placeholder,
267
+ * or text-only substitution). The caller prices `text` with its own text
268
+ * estimator so provider pricing never fixes a text tokenization.
269
+ */
270
+ interface LlmImageRequestPrice {
271
+ /** Provider visual tokens for the retained request image; 0 when only text represents this occurrence. */
272
+ visualTokens: number
273
+ /** Model-visible text sent for this occurrence, to be priced by the caller's text estimator. */
274
+ text: string
275
+ }
276
+ ```
277
+
278
+ ```ts type-equiv
279
+ /**
280
+ * Provider-side request-image pricing for one exact model route. Implemented
281
+ * by adapters whose provider charges visual tokens; consumers (the token
282
+ * meter) resolve it synchronously per measurement, so implementations must not
283
+ * perform I/O.
284
+ */
285
+ interface LlmImageRequestPricing {
286
+ /**
287
+ * Price every image occurrence of one request projection.
288
+ * @param images - surface image blocks in request order, one entry per occurrence; an `offloaded` block
289
+ * is priced as its placeholder text.
290
+ * @returns one price per occurrence, aligned by index with `images`.
291
+ */
292
+ priceImages(images: readonly ImageBlock[]): readonly LlmImageRequestPrice[]
293
+ }
294
+ ```
295
+
296
+ ## The adapter contract
297
+
298
+ Every adapter MUST obey these, and every consumer may rely on them:
299
+
300
+ - **`usage` before `finish`, nothing after `finish`.** Defer both to the provider's end-of-stream marker so a trailing usage-only chunk can't violate the ordering.
301
+ - **Tool-call `arguments` stay raw JSON strings end-to-end.** Partial fragments stream via `argumentsDelta`; a provider that hands back parsed objects re-stringifies at `block-end`.
302
+ - **Two sanctioned error paths, one `LlmFailure` type.** A failure may either THROW from `stream()` (transport/protocol errors) **or** end the stream with `finish {kind:'error'|'aborted', failure}` (provider in-band errors, for adapters that can't throw mid-stream). `LlmError.failure` carries the same `LlmFailure`. After the call selects its adapter, the stream preserves the exact thrown `Error` object and associates immutable facts plus the serving registration's immutable retry policy with that call; the agent loop commits the attempt stream as `assistant/attempt`, closes the failed step, and offers the error, facts, immutable prior-retried facts, serving policy, and turn signal to `agent/request-error`. A handling listener returns `{ kind: 'retry' }` after its awaited repair; absent recovery the structured failure becomes the turn error, and no surface Assistant message or tool side effect is committed for that attempt.
303
+ - **One adapter call is one provider attempt.** Adapters disable library retries. Agent-level recovery opens another durable numbered turn; direct `ctx.llm.stream()` callers remain single-attempt.
304
+ - **Provider stalls are bounded at the transport.** Both shipping remote adapters expose positive finite `streamIdleTimeoutMs` with a five-minute default. The watchdog arms only while iterator `next()` is outstanding, uses one stable signal for the whole request, maps its own expiry to `TIMEOUT`, and keeps an earlier caller abort as `ABORTED`.
305
+ - **Context overflow has one canonical code.** Both DeepSeek adapters classify explicit provider detail through `isContextWindowExceededError()` and surface `CONTEXT_WINDOW_EXCEEDED`, whether the failure arrives as a thrown HTTP `LlmError` or an in-band finish error. Consumers route on the code, never provider text.
306
+ - **An empty completion is a retryable error, not a silent success.** Both adapters map a terminal `stop` finish that carried no content blocks to `finish {kind:'error'}` with the canonical `EMPTY_RESPONSE` code, and `dsh-llm-retry` retries it by default.
307
+ - **Every provider HTTP request carries the app-attribution header.** Adapters send `attributionHeaders()` (below) - the `User-Agent` baseline - and prove it with a wire-level test.
308
+ - **Replay state is adapter-owned; its split is shared.** A successful `finish` may carry a `ReplayEnvelope`: opaque response-level metadata plus optional per-block entries aligned with the emitted block sequence. The alignment is the harness's vocabulary - when assembly drops a block it drops the entry at the same position, so stored metadata always describes stored content. The loop stores the pruned envelope with the assembled assistant message. On a later request, `LlmRuntime` passes the state only when the historical provider and target provider are currently registered to the exact same adapter instance. That adapter validates the state and owns any cross-model or cross-provider conversion; other adapters receive the provider-neutral content plus provider/model fields without the private state. Durable content stays authoritative: a stored state the reading adapter cannot use degrades that one message to provider-neutral conversion with a diagnostic instead of failing the request.
309
+
310
+ ## `ResolvedRetryPolicy`
311
+
312
+ Retry configuration resolves before route registration into an immutable discriminated union. Normal mode carries `mode: 'normal'`, finite `maxRetries`, `retryableCodes`, and required `initialDelayMs`, `maxDelayMs`, and `jitterRatio`; always mode carries `mode: 'always'` and the same required backoff fields without a finite maximum. Omitting a provider policy uses the normal default of five retries. Layered settings may retain normal-only `maxRetries` or `retryableCodes` after switching to always mode; the resolver ignores those inactive fields and captures the pure always policy. `LlmRuntime.providerRetryPolicy(provider)` returns the registered value, and `llmRetryPolicyOf(stream)` returns the value captured from the serving registration after the call selects it, so later route disposal or replacement cannot change an in-flight failure's recovery policy. The [generated config catalog](../config-catalog.md) lists the optional input fields.
313
+
314
+ ## `AppIdentity` - app attribution
315
+
316
+ The static public application identity every adapter sends to providers ([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts)). `attributionHeaders(identity?)` maps it to the standard `User-Agent` header only; OpenRouter-specific app attribution headers are intentionally not supported by this contract. The default `APP_IDENTITY` sources its version from the package manifest; every field is a public product fact - no secrets, paths, session ids, or per-user identifiers, and nothing per-request may influence the values. Rationale: [Mandatory `User-Agent` attribution](../../.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md).
317
+
318
+ ```ts type-equiv
319
+ /**
320
+ * Static public application identity sent to LLM providers.
321
+ *
322
+ * Every field is a public product fact, safe on every request: no secrets,
323
+ * local paths, session ids, prompt text, or per-user identifiers belong here,
324
+ * and nothing per-request may influence the values.
325
+ */
326
+ interface AppIdentity {
327
+ /** `User-Agent` product token (lowercase, hyphenated). */
328
+ product: string
329
+ /** Product version; sourced from package metadata, never hand-copied. */
330
+ version: string
331
+ /** Repository home URL of the app, used as the `User-Agent` comment. */
332
+ url: string
333
+ }
334
+ ```
335
+
336
+ ## `TokenUsage`
337
+
338
+ Per-call token accounting. Counts are **disjoint**: `inputTokens` is uncached input only; cached input is reported separately, and billed input is the sum of the three. Adapters whose providers fold cache hits into a single prompt total (DeepSeek's `prompt_tokens`) subtract them back out. Optional `totalTokens` is an exact aggregate prompt-plus-output count preserved from the provider or reconstructed from authoritative aggregate counters; adapters omit it when unavailable or inconsistent. `reasoningTokens`, when present, is informational detail already included in `outputTokens`; totals must not add it again.
339
+
340
+ ```ts type-equiv
341
+ /**
342
+ * Token accounting for one model call (cache fields are optional).
343
+ *
344
+ * Counts are DISJOINT: `inputTokens` is uncached input only; cached input is
345
+ * reported separately as `cacheReadTokens`/`cacheWriteTokens` (billed input =
346
+ * sum of the three). Adapters whose providers fold cache hits into a total
347
+ * prompt count (DeepSeek's `prompt_tokens`) subtract them out.
348
+ */
349
+ interface TokenUsage {
350
+ inputTokens: number
351
+ outputTokens: number
352
+ /**
353
+ * Exact full-call total including aggregate prompt and output tokens.
354
+ *
355
+ * Adapters preserve a provider total or derive it from authoritative
356
+ * aggregate prompt/output counters; they omit it when unavailable or
357
+ * inconsistent.
358
+ */
359
+ totalTokens?: number
360
+ cacheReadTokens?: number
361
+ cacheWriteTokens?: number
362
+ reasoningTokens?: number
363
+ }
364
+ ```
365
+
366
+ ## `BlockAssembler`
367
+
368
+ `BlockAssembler` ([`packages/llm/llm/src/assembler.ts`](../../packages/llm/llm/src/assembler.ts)) is the single shared implementation that folds a `StreamChunk` stream back into `ContentBlock`s, usage, finish reason, and replay state. The loop logs the raw chunks while feeding the same chunks through an assembler, then stores the assembled assistant content with the provider and model that produced it. A consumer that needs the assembled result without re-implementing the fold uses this.
369
+
370
+ One keep/drop decision covers content and metadata together: a `max-tokens` finish drops every tool call because a truncated call is unsafe to execute, and the same decision prunes the replay envelope's per-block entry at each dropped position. `blocks()` and `replayState` therefore cannot disagree, whatever assembly removes.
371
+
372
+ ```ts public-api
373
+ /**
374
+ * Incrementally assembles raw {@link StreamChunk}s into complete
375
+ * {@link ContentBlock}s and a final assistant {@link Message}.
376
+ *
377
+ * The agent loop feeds it while logging raw chunks for replay fidelity, then
378
+ * reads `blocks()` / `message()` / `usage` / `finish` once the stream ends,
379
+ * or `interruptedBlocks()` when cancellation cut the stream short.
380
+ *
381
+ * Tolerant of delta-only protocols (no block-start/end); deltas arriving for
382
+ * an index already closed by `block-end` are ignored (malformed stream) so a
383
+ * misbehaving adapter cannot grow memory or corrupt a completed block.
384
+ */
385
+ declare class BlockAssembler {
386
+ /**
387
+ * Feed one chunk into the assembly state.
388
+ * @param chunk - the next raw chunk, in stream order.
389
+ */
390
+ push(chunk: StreamChunk): void;
391
+ /**
392
+ * Assemble all blocks seen so far, in stream order.
393
+ * @returns one block per seen index, except that max-token truncation drops
394
+ * tool calls that cannot be executed safely; an open block assembles from
395
+ * its accumulated deltas (an unknown block type never closed by `block-end` throws).
396
+ */
397
+ blocks(): ContentBlock[];
398
+ /**
399
+ * Assemble the prefix an interrupted stream can safely finalize: closed and
400
+ * open text/reasoning blocks with non-whitespace content, in stream order.
401
+ * Tool calls are omitted because interruption precedes dispatch; retaining
402
+ * one would require a fabricated result. Open unknown blocks are also omitted.
403
+ * @returns the kept blocks; empty when nothing streamed before the interruption.
404
+ */
405
+ interruptedBlocks(): ContentBlock[];
406
+ /** Usage from the `usage` chunk; undefined until one arrives. */
407
+ get usage(): TokenUsage | undefined;
408
+ /** Finish reason from the `finish` chunk; `{kind: 'stop'}` when the stream ended without one. */
409
+ get finish(): FinishReason;
410
+ /**
411
+ * Replay metadata from the terminal finish chunk, if any, with per-block
412
+ * entries pruned in step with {@link blocks}. Undefined when the envelope's
413
+ * entries do not align with the emitted blocks.
414
+ */
415
+ get replayState(): ReplayEnvelope | undefined;
416
+ /**
417
+ * The assembled assistant message.
418
+ * @param source - provider/model attribution (without the `kind` tag) for the assembled message.
419
+ * @returns a frozen assistant-role message over `blocks()` (same open-block assembly rules).
420
+ */
421
+ message(source: Omit<ModelMessageSource, 'kind'>): AssistantMessage;
422
+ }
423
+ ```
424
+
425
+ <a id="the-model-request-and-result"></a>
426
+
427
+ ## The model request
428
+
429
+ One model call is a fully-assembled `GenerateOptions`. The adapter answers with a raw [`StreamChunk`](#streamchunk--the-raw-protocol) stream; the consumer assembles it with [`BlockAssembler`](#blockassembler).
430
+
431
+ Source: [`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts)
432
+
433
+ Provider and model discovery uses small provider-neutral descriptors. A model catalog is advisory: routing still keys on a registered provider.
434
+
435
+ Registering an adapter returns a handle: the disposer, plus the atomic route replacement a plugin whose route set is user-configurable needs.
436
+
437
+ ```ts type-equiv
438
+ /**
439
+ * What {@link LlmRuntime.registerAdapter} returns: the disposer, plus an
440
+ * atomic route replacement for the same adapter instance.
441
+ */
442
+ interface AdapterRegistrationHandle {
443
+ /** Release every route this registration currently holds. */
444
+ (): void
445
+ /**
446
+ * Replace this registration's routes with `providers`, keeping the same
447
+ * adapter instance. The candidate set is validated in full first - a
448
+ * conflict with another adapter, an invalid name, or bad provider metadata
449
+ * throws and leaves the current routes untouched - and the swap itself is
450
+ * one synchronous section, so no request can observe a gap. An empty array
451
+ * is legal here (a settings section that emptied holds zero routes while
452
+ * staying registered), unlike an empty initial registration.
453
+ *
454
+ * Throws `LlmError` with code `REGISTRATION_DISPOSED` once the registration
455
+ * has been released: its routes are gone and its disposer has already run,
456
+ * so anything registered afterwards would have no owner left to release it.
457
+ * @param providers - the complete next route set for this registration.
458
+ */
459
+ replace(providers: string[]): void
460
+ }
461
+ ```
462
+
463
+ ```ts type-equiv
464
+ /** Display metadata for one registered provider route. */
465
+ interface LlmProviderInfo {
466
+ /** Provider route key used by {@link GenerateOptions.provider}. */
467
+ id: string
468
+ /** Human-readable provider name for selectors and diagnostics. */
469
+ name: string
470
+ }
471
+ ```
472
+
473
+ Adapter plugins additionally declare which routes *could* run through `registerConfigurableProviders()`, addressing each one's user-settings section, so configuration surfaces can offer dormant providers before any route registers.
474
+
475
+ ```ts type-equiv
476
+ /**
477
+ * One provider route an adapter plugin can activate through configuration,
478
+ * whether or not the route is currently registered. Configuration surfaces
479
+ * merge this directory with `listProviders()` to offer every configurable
480
+ * provider alongside its live/dormant state.
481
+ */
482
+ interface LlmConfigurableProvider {
483
+ /** Provider route key this entry activates when configured. */
484
+ provider: string
485
+ /** Human-readable provider name for configuration surfaces. */
486
+ displayName: string
487
+ /** User-settings namespace whose section configures this provider. */
488
+ settingsNs: string
489
+ /**
490
+ * Path from that namespace's section root to this provider's profile
491
+ * object; empty when the whole section is the profile.
492
+ */
493
+ settingsPath: readonly string[]
494
+ /**
495
+ * Whether the owning adapter knows this route only because configuration
496
+ * declared it - a gateway or self-hosted server it ships nothing about.
497
+ * Absent means the adapter draws no such distinction; false means it does
498
+ * and this route is one of its own. Only the adapter can answer: a stored
499
+ * profile is how a user-added route AND a corrected shipped one both look
500
+ * from outside.
501
+ */
502
+ declared?: boolean
503
+ /** Configuration diagnostic for repair; unaffected models may remain serviceable. */
504
+ error?: string
505
+ }
506
+ ```
507
+
508
+ ```ts type-equiv
509
+ /** One adapter-discovered model; catalog membership is advisory, not request validation. */
510
+ interface LlmModelInfo {
511
+ /** Provider route that owns this model entry. */
512
+ provider: string
513
+ /** Model id passed to {@link GenerateOptions.model}. */
514
+ id: string
515
+ /** Human-readable model name for selectors. */
516
+ name: string
517
+ /** Optional user-facing distinction from otherwise similar models. */
518
+ description?: string
519
+ /** Accepted request modalities; absent means unknown, while an explicit omission is negative capability. */
520
+ inputModalities?: readonly ModelModality[]
521
+ }
522
+ ```
523
+
524
+ Correctness-sensitive metadata is resolved separately from the advisory catalog and is owned by the adapter serving the exact route. Context capacity, adapter call defaults, reasoning choices, and the system prompt update mode share one exact-model result so consumers do not repeat authoritative model resolution. `SystemPromptUpdate` has the single value `'in-history'`: the model reads the latest `system` message at any position of `messages` as the complete effective system prompt, so the agent loop can append a changed prompt after the cached history instead of rewriting message 0 ([decision rule](../../packages/core/agent-loop/README.md#understand-the-implementation)); an absent mode means only a leading system message is read, and `normalizeModelInfo` rejects any other value with `INVALID_MODEL_INFO`.
525
+
526
+ ```ts type-equiv
527
+ /** Provider-owned context capacity for one exact provider/model route. */
528
+ interface LlmModelContext {
529
+ /** Maximum combined request and response context in tokens. */
530
+ contextWindow: number
531
+ }
532
+ ```
533
+
534
+ Reasoning effort is another exact-route capability. The core brands identifiers but does not enumerate their values; each adapter owns the ordered set, display names, and optional deployment default.
535
+
536
+ ```ts type-equiv
537
+ /** Adapter-owned identifier for one model's selectable reasoning effort. */
538
+ type ReasoningEffortId = Branded<'ReasoningEffortId'>
539
+ ```
540
+
541
+ ```ts type-equiv
542
+ /** Display metadata for one adapter-owned reasoning effort. */
543
+ interface LlmReasoningEffortInfo {
544
+ /** Opaque stable value accepted by {@link GenerateOptions.reasoningEffort}. */
545
+ id: ReasoningEffortId
546
+ /** Human-readable effort name for selectors and diagnostics. */
547
+ name: string
548
+ /** Optional user-facing distinction from otherwise similar efforts. */
549
+ description?: string
550
+ }
551
+ ```
552
+
553
+ ```ts type-equiv
554
+ /** Selectable reasoning efforts for one exact provider/model route. */
555
+ interface LlmModelReasoningInfo {
556
+ /** Supported efforts in adapter-preferred display order. */
557
+ efforts: readonly LlmReasoningEffortInfo[]
558
+ /**
559
+ * Adapter-configured default materialized into requests when callers omit
560
+ * an effort. Absence preserves the provider's own default.
561
+ */
562
+ defaultEffort?: ReasoningEffortId
563
+ }
564
+ ```
565
+
566
+ ```ts type-equiv
567
+ /** Exact-route model metadata resolved by its owning adapter. */
568
+ interface LlmResolvedModelInfo extends LlmModelInfo {
569
+ /** Provider-owned context capacity when known. */
570
+ context?: LlmModelContext
571
+ /** Adapter-configured per-request output cap materialized when callers omit one. */
572
+ defaultMaxTokens?: number
573
+ /** Adapter-owned selectable reasoning levels when exposed. */
574
+ reasoning?: LlmModelReasoningInfo
575
+ /** Declared mid-conversation system prompt handling; absent means only a leading system message is read. */
576
+ systemPromptUpdate?: SystemPromptUpdate
577
+ /** Declared mid-conversation tool declaration handling; absent means every request declares the complete tool list. */
578
+ toolUpdate?: ToolUpdate
579
+ }
580
+ ```
581
+
582
+ Auxiliary callers can provide user content without a durable identity or source. Existing `Message[]` histories remain valid request inputs. Session writes, Agent delivery, and recorded title requests continue to require durable messages.
583
+
584
+ ```ts type-equiv
585
+ /** User input for one LLM request; it has no durable Session identity or source. */
586
+ interface RequestUserInput {
587
+ readonly role: 'user'
588
+ readonly content: UserMessage['content']
589
+ readonly id?: never
590
+ readonly source?: never
591
+ }
592
+ ```
593
+
594
+ ```ts type-equiv
595
+ /** A durable conversation message or a user input used only for one request. */
596
+ type RequestMessage = Message | RequestUserInput
597
+ ```
598
+
599
+ ```ts type-equiv
600
+ /** A single model request, fully assembled. */
601
+ interface GenerateOptions {
602
+ /** Registered provider route selecting the adapter instance. */
603
+ provider: string
604
+ model: string
605
+ /** Adapter-owned reasoning effort selected for this exact model. */
606
+ reasoningEffort?: ReasoningEffortId
607
+ /**
608
+ * Ordered conversation messages, exactly as the provider sees them. A
609
+ * loop-built request passes the derived history (dsh-agent-loop), whose
610
+ * leading system-role message carries the system prompt; a hand-built
611
+ * one-shot may include identity-free user inputs.
612
+ */
613
+ messages: RequestMessage[]
614
+ /**
615
+ * System prompt text for one-shot callers; adapters map it to the provider's
616
+ * system slot ahead of `messages`. Loop-built requests leave it undefined.
617
+ */
618
+ system?: string
619
+ /** Tool schemas (adapters map to the provider's `tools` field). */
620
+ tools?: ToolSchema[]
621
+ /** Session-folded tool history used for route projection; omission sends complete declarations without tool updates. */
622
+ toolHistory?: ToolHistory
623
+ temperature?: number
624
+ maxTokens?: number
625
+ /**
626
+ * Stop sequences: generation halts as soon as the model produces any one of
627
+ * these strings (adapters map to the provider's stop field, e.g. OpenAI
628
+ * `stop`). The stop string itself is not included in the output.
629
+ */
630
+ stop?: string[]
631
+ signal?: AbortSignal
632
+ /**
633
+ * Session identity stamped by the loop for request routing. Replay uses it
634
+ * to separate cursors; adapters may map it to model-hidden transport metadata.
635
+ */
636
+ sessionId?: Branded<'SessionId'>
637
+ /**
638
+ * Provider-neutral classification for an auxiliary model call. Adapters may
639
+ * map the purpose to model-hidden transport metadata or purpose-specific
640
+ * generation policy. Ordinary conversation requests leave it unset.
641
+ */
642
+ purpose?: 'compaction' | 'session-title'
643
+ }
644
+ ```
645
+
646
+ Why a model response stopped is a merge-extensible reason. Terminal provider failures carry the streaming contract's [`LlmFailure`](#llmfailure):
647
+
648
+ ```ts type-equiv
649
+ /**
650
+ * Why a model response stopped.
651
+ * Merge-extensible so adapters can surface provider-specific reasons.
652
+ */
653
+ interface FinishReasonMap {
654
+ 'stop': { kind: 'stop' }
655
+ 'tool-calls': { kind: 'tool-calls' }
656
+ 'max-tokens': { kind: 'max-tokens' }
657
+ 'aborted': { kind: 'aborted'; failure: LlmFailure }
658
+ 'error': { kind: 'error'; failure: LlmFailure }
659
+ }
660
+ ```
661
+
662
+ `FinishReason = FinishReasonMap[keyof FinishReasonMap]`. `TokenUsage` (per-call accounting with disjoint cache fields) is detailed [below](#tokenusage).
663
+
664
+ `GenerateOptions.tools` carries `ToolSchema` - the JSON-schema description of a tool, as sent to the model. It is declared in dsh-llm (not dsh-tools) precisely because it is part of the request the loop assembles every step:
665
+
666
+ ```ts type-equiv
667
+ /**
668
+ * JSON-schema description of a tool, as sent to the model.
669
+ *
670
+ * Declared here (not in dsh-tools) because it is part of {@link GenerateOptions};
671
+ * dsh-tools' ToolDefinition and dsh-system-prompt's PromptAssembly both import
672
+ * it from this package.
673
+ */
674
+ interface ToolSchema {
675
+ /**
676
+ * Requests deferred loading of the tool definition into model context,
677
+ * independently of whether a tool-addition block records the tool.
678
+ * Uses Anthropic's defer_loading terminology.
679
+ */
680
+ deferLoading?: true
681
+ name: string
682
+ description: string
683
+ /** JSON Schema object for the arguments. */
684
+ parameters: Record<string, unknown>
685
+ }
686
+ ```
687
+
688
+ The model-facing `ToolSchema` is the wire type; the registered `ToolDefinition` that produces it (schema + `execute`) is on [tools.md](tools.md).
689
+
690
+ A provider a surface is still drafting has no route and no catalog, so interrogation is described separately: the request carries the draft the user is editing, and the reply is candidates a surface may adopt rather than a catalog it must serve.
691
+
692
+ ```ts type-equiv
693
+ /**
694
+ * One interrogation of a provider endpoint that configuration has not stored
695
+ * yet. Configuration surfaces send the draft a user is still editing, so the
696
+ * request carries the endpoint and credential directly instead of naming a
697
+ * route: a provider being added has no route to name.
698
+ */
699
+ interface LlmModelDiscoveryRequest {
700
+ /**
701
+ * Route the draft is editing, when it edits an existing one. A route whose
702
+ * adapter already knows its models answers from that knowledge instead of
703
+ * asking the endpoint - the adapter's own registry is the better answer, and
704
+ * it costs no network call.
705
+ */
706
+ provider?: string
707
+ /**
708
+ * Endpoint to interrogate. Optional because a route the adapter already
709
+ * describes needs none; a route it does not must supply one.
710
+ */
711
+ baseURL?: string
712
+ /** Wire protocol the endpoint speaks, when the draft names one. */
713
+ api?: string
714
+ /** Credential for this interrogation alone; the harness never stores it. */
715
+ apiKey?: string
716
+ }
717
+ ```
718
+
719
+ ```ts type-equiv
720
+ /**
721
+ * One model an endpoint reports about itself. Every field but the id is
722
+ * optional because most provider listings disclose an id and nothing else;
723
+ * a surface adopting one of these still owes the capacities its adapter needs.
724
+ */
725
+ interface LlmDiscoveredModel {
726
+ /** Model id the endpoint accepts. */
727
+ id: string
728
+ /** Human-readable name when the endpoint supplies one. */
729
+ name?: string
730
+ /** Maximum combined request and response context, when disclosed. */
731
+ contextWindow?: number
732
+ /** Maximum output tokens, when disclosed. */
733
+ maxTokens?: number
734
+ /** Accepted input types when disclosed by the catalog or endpoint; absent means unknown. */
735
+ inputModalities?: readonly ModelModality[]
736
+ }
737
+ ```
738
+
739
+ ### The request envelope: `LlmCallConfig` and the logged header
740
+
741
+ The loop builds each request from logged state. `EpochHeader` records call config, marks the fields supplied by adapter defaults, and records the authoritative returned tool order (configured by `toolOrder`, or lexicographic when unset) through full `request/header` snapshots. The rendered prompt is derived history - the `system/message` at surface node 0, plus any later system node an `in-history` route appended - so the header and the derived history together make the request reconstructable from the session log. See [session.md](session.md#the-request-header-event-requestheader) and the [reconstructability Agent Note](../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md).
742
+
743
+ `agent/request` receives a frozen call-config seed and may return a replacement to switch provider, model, reasoning effort, or sampling. Before the waterfall, the loop removes values marked as adapter defaults so exact-model preparation materializes the selected route's current values; unmarked explicit settings remain in the proposal. After the waterfall, preparation rejects unsupported explicit effort ids without clamping and logs the effective config plus the fields supplied by adapter defaults under the turn signal. On step admission, this waterfall and preparation run after assembly and `step/start` but before the system prompt and accepted user batch are committed; cancellation during either commits neither. The prepared capability governs prompt reconciliation, and the call keeps one adapter registration through dispatch. Requests reaching `llm/stream` are deep-frozen, so mutation throws, and carry a process-local loop identity so observers do not confuse separately logged frozen auxiliary calls with conversation requests.
744
+
745
+ On the wire, a loop-built request is the derived history alone: the rendered prompt travels as the leading `system`-role message (surface node 0, a `system/message` event) and, when the prepared call declares `systemPromptUpdate: 'in-history'`, a non-empty changed prompt may follow the cached history as a later `system`-role message that the model reads as the effective prompt; the request's `system` field is unset - `GenerateOptions.system` serves direct one-shot callers such as title providers. An empty rendering leaves no system messages in derived history, even when earlier requests retained several prompt versions. The logged request ends with the newest `user/message` on a turn's first step and the previous step's tool results on later steps. The dev invariant recomputes exactly this equation against every loop-built request and rejects a loop request carrying a `system` field.
746
+
747
+ FIXME(call-config-shape): revisit which remaining fields are genuinely epoch-level for cache purposes (`model` and the model-owned reasoning effort are explicit; the sampling scalars sit here out of caution).
748
+
749
+ ```ts type-equiv
750
+ /**
751
+ * Provider, model, reasoning effort, and sampling scalars of one conversation's
752
+ * requests. Every field maps 1:1 onto the same-named `GenerateOptions` field;
753
+ * the loop builds requests from the logged header rather than accepting these
754
+ * per call.
755
+ */
756
+ interface LlmCallConfig {
757
+ provider: string
758
+ model: string
759
+ reasoningEffort?: ReasoningEffortId
760
+ temperature?: number
761
+ maxTokens?: number
762
+ stop?: string[]
763
+ }
764
+ ```
765
+
766
+ ```ts type-equiv
767
+ /**
768
+ * Effective config fields supplied by exact-model adapter resolution rather
769
+ * than by the caller's request proposal.
770
+ */
771
+ interface LlmCallConfigAdapterDefaults {
772
+ reasoningEffort?: true
773
+ maxTokens?: true
774
+ }
775
+ ```
776
+
777
+ ## Official DeepSeek request extensions
778
+
779
+ `ctx.deepseekLlmApiExtensions` is the provider-specific registry for additive top-level fields on `deepseek-official` requests. Contributor plugins use `register(field, provider)` to claim one field; the adapter calls `prepare(request)` after serializing its base body and merges the returned fields before HTTP. The prepared `accept()` transaction runs after 2xx, so a contributor can commit delivery state without treating a transport or provider rejection as acceptance. Preparation, collision, and acceptance failures use `REQUEST_EXTENSION` and fail the model request. A merged body that fails to serialize is sent without extension fields; acceptance is skipped and the provider plugin logs the omitted field names.
780
+
781
+ The [wire reference](../deepseek-llm-api-wire-extensions.md) defines the exact request headers, extension transaction, field versions, and receiver obligations. The shipped composition registers [`dsh_session_log`](../../packages/session/session-log-deepseek/README.md) as a lossless incremental canonical-log suffix and [`dsh_plugin_packages`](../../packages/llm/plugin-package-inventory-deepseek/README.md) as the complete active Loader-backed package set. These fields remain outside model messages and are absent from the pi-ai adapter path.
782
+
783
+ ## Service and provider contracts
784
+
785
+ `LlmAdapter` is the provider contract: subclass, implement `stream()`, and register one adapter instance with `ctx.llm.registerAdapter(providers, adapter)`. `GenerateOptions.provider` selects the registered adapter; `GenerateOptions.model` is passed to that adapter and need not be registered at lifecycle start. Duplicate provider routes fail atomically. Optional `providerRetryPolicy()` is captured per route with normal defaults, while `providerInfo()` and asynchronous `listModels()` feed `LlmRuntime.listProviders()` / `listModels()` with detached selector metadata. That catalog is advisory rather than a request whitelist: the adapter remains authoritative and may accept unlisted model ids. One asynchronous `resolveModel()` query returns exact model identity plus optional correctness-sensitive context capacity, an adapter-configured `defaultMaxTokens`, and ordered model-owned reasoning ids with an optional deployment default; absent fields mean unavailable metadata or provider-owned behavior, not invalid catalog membership. The resolver receives optional cancellation and must settle promptly after abort. `LlmRuntime.resolveModelInfo()` validates and detaches the aggregate. At the final adapter boundary, `resolveCallConfig()` materializes the output default only when `maxTokens` is absent and validates and materializes reasoning, so direct calls cannot bypass either configured behavior; direct dispatch captures one registration before awaiting that resolution. The agent loop instead uses `prepareCall()` to keep the same registration across model resolution, durable header logging, and dispatch, retain detached context metadata from that exact lookup, and report which config fields the adapter defaulted. Adapter lookup happens at the terminal continuation of the `llm/stream` waterfall, so a listener may short-circuit the call or route a mutable one-shot request before lookup. AgentLoop observes a request attempt once the outer waterfall returns a stream handle; that limited boundary does not prove a lazy terminal adapter was constructed or began provider I/O. The `block-start` / `block-end` `index` correlation and the assembler together mean an adapter only has to emit well-formed chunks - block reassembly is not each adapter's problem. [architecture.md](../architecture.md#turn-flow) shows where `ctx.llm.stream()` and the `llm/stream` waterfall sit in one turn.
786
+
787
+ ```ts type-equiv
788
+ /** One model call whose config and adapter registration were resolved together. */
789
+ interface PreparedLlmCall {
790
+ /** Detached, deep-frozen config with any adapter-owned default materialized. */
791
+ readonly config: LlmCallConfig
792
+ /** Immutable retry policy captured with the adapter registration. */
793
+ readonly retryPolicy: ResolvedRetryPolicy
794
+ /** Detached context metadata resolved with the registration-bound call. */
795
+ readonly context?: LlmModelContext
796
+ /** Exact model modalities captured with the adapter dispatch generation. */
797
+ readonly inputModalities?: readonly ModelModality[]
798
+ /** Exact model system prompt update mode captured with the adapter dispatch generation. */
799
+ readonly systemPromptUpdate?: SystemPromptUpdate
800
+ /** Exact model tool update mode captured with the adapter dispatch generation. */
801
+ readonly toolUpdate?: ToolUpdate
802
+ /** Config fields materialized by the captured adapter rather than proposed by the caller. */
803
+ readonly adapterDefaults: LlmCallConfigAdapterDefaults
804
+ /**
805
+ * Dispatch this call once through the registration captured during
806
+ * preparation. The request's call-config fields must match {@link config};
807
+ * reuse or mismatch fails with `INVALID_PREPARED_CALL`.
808
+ * @param options - fully assembled request carrying the prepared config.
809
+ * @returns the chunk stream, including the `llm/stream` waterfall.
810
+ */
811
+ stream(options: GenerateOptions): AsyncIterable<StreamChunk>
812
+ }
813
+ ```
814
+
815
+ ```ts public-api
816
+ /**
817
+ * Provider-wire adapter for the harness message and stream vocabulary. Register implementations
818
+ * with `ctx.llm.registerAdapter(providers, adapter)`. Every provider HTTP request must include
819
+ * `attributionHeaders()`; prove the headers are added in the wire request or library header hook. The direct-fetch
820
+ * DeepSeek and library-backed pi-ai adapters meet this contract through different internals.
821
+ */
822
+ declare abstract class LlmAdapter {
823
+ /**
824
+ * Describe one provider route owned by this adapter.
825
+ * @param provider - a route passed to `registerAdapter()` for this instance.
826
+ * @returns detached display metadata whose id must equal `provider`.
827
+ */
828
+ providerInfo(provider: string): LlmProviderInfo;
829
+ /**
830
+ * Return the provider-owned retry policy captured with this route.
831
+ * @param _provider - a route passed to `registerAdapter()` for this instance.
832
+ * @returns a resolved policy, or `undefined` to use the normal defaults.
833
+ */
834
+ providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;
835
+ /**
836
+ * Resolve provider-side request-image pricing for one exact model route.
837
+ * The default declares none, so consumers fall back to their own neutral
838
+ * estimate. Implementations must answer synchronously without I/O; the
839
+ * token meter resolves this per measurement.
840
+ * @param _provider - a route passed to `registerAdapter()` for this instance.
841
+ * @param _model - exact model id passed to {@link GenerateOptions.model}.
842
+ * @returns route-owned image pricing, or `undefined` when the route declares none.
843
+ */
844
+ imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;
845
+ /**
846
+ * List models this adapter can currently advertise for one owned provider.
847
+ * Core routing accepts unlisted model ids; catalog-driven entry points such
848
+ * as the GUI may require membership. Adapters used there must advertise
849
+ * their available models; the base empty catalog offers no GUI selection.
850
+ * @param _provider - one provider route owned by this adapter.
851
+ * @returns discoverable models in adapter-preferred order.
852
+ */
853
+ listModels(_provider: string): Promise<readonly LlmModelInfo[]>;
854
+ /**
855
+ * Resolve all metadata available for one exact model. This query is
856
+ * independent of the advisory catalog and does not validate request routing.
857
+ * @param provider - one provider route owned by this adapter.
858
+ * @param model - exact model id passed to {@link GenerateOptions.model}.
859
+ * @param _signal - cancellation for this exact-model lookup; asynchronous
860
+ * implementations must settle promptly after it aborts.
861
+ * @returns provider/model identity plus any context, call-default, and reasoning metadata.
862
+ */
863
+ resolveModel(
864
+ provider: string,
865
+ model: string,
866
+ _signal?: AbortSignal,
867
+ ): Promise<LlmResolvedModelInfo>;
868
+ /**
869
+ * Bind exact model metadata and the eventual request dispatch to one adapter generation.
870
+ * Dynamic adapters override this so settings changes between preparation and
871
+ * dispatch cannot combine one generation's capabilities with another's endpoint.
872
+ * @param provider - registered provider route.
873
+ * @param model - exact model id.
874
+ * @param signal - cancellation for model resolution.
875
+ * @returns model metadata and a one-generation stream entry point.
876
+ */
877
+ async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise<PreparedAdapterCall>;
878
+ /**
879
+ * Stream one model call as raw chunks. The only required method.
880
+ * @param options - the fully-assembled request; implementations must honor `options.signal`.
881
+ * @returns the chunk stream, obeying the adapter contract documented on `StreamChunk`.
882
+ */
883
+ abstract stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
884
+ }
885
+ ```
886
+
887
+ `ContentBlockType` (the key set the `index`-correlated blocks carry) derives from [`ContentBlockMap`](#content-blocks-and-messages) above.
888
+
889
+ <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) - do not edit between markers -->
890
+
891
+ <a id="cordis-surface"></a>
892
+
893
+ ## Cordis API
894
+
895
+ 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).
896
+
897
+ <a id="ctxdeepseekllmapiextensions--deepseekllmapiextensionregistry"></a>
898
+
899
+ ### `ctx.deepseekLlmApiExtensions` - `DeepSeekLlmApiExtensionRegistry`
900
+
901
+ Registry of independently owned top-level fields for official DeepSeek requests.
902
+
903
+ ```ts cordis-catalog
904
+ /**
905
+ * Register the sole provider of one top-level request field. Registration is effect-scoped.
906
+ * @param field - declaration-merged field owned by the provider.
907
+ * @param provider - request-time field preparation and optional acceptance behavior.
908
+ * @returns disposer that releases the field.
909
+ */
910
+ register<K extends keyof DeepSeekLlmApiExtensionMap>( field: K, provider: DeepSeekLlmApiExtensionProvider<DeepSeekLlmApiExtensionMap[K]>, ): () => Promise<void>
911
+
912
+ /**
913
+ * Prepare every currently registered field from one immutable base request.
914
+ * Preparation failures reject before HTTP dispatch. Field values are cloned and frozen;
915
+ * providers retain no mutable alias to the outgoing request.
916
+ * @param request - exact serialized request facts before extension fields.
917
+ * @returns detached fields and their idempotent joint acceptance transaction.
918
+ */
919
+ async prepare(request: DeepSeekLlmApiExtensionRequest): Promise<PreparedDeepSeekLlmApiExtensions>
920
+ ```
921
+
922
+ Source: [`packages/llm/deepseek-llm-api-extensions/src/index.ts`](../../packages/llm/deepseek-llm-api-extensions/src/index.ts)
923
+
924
+ <a id="ctxllm--llmruntime"></a>
925
+
926
+ ### `ctx.llm` - `LlmRuntime`
927
+
928
+ The abstract `llm` service: an adapter registry plus a streaming model-call API, interceptable via the `llm/stream` waterfall.
929
+
930
+ ```ts cordis-catalog
931
+ /**
932
+ * Register an adapter for the given provider routes. Throws `LlmError` with code
933
+ * `DUPLICATE_ADAPTER` if any provider already has an adapter (all-or-nothing).
934
+ * Disposed with the fiber.
935
+ * @param providers - every provider route this adapter should serve.
936
+ * @param adapter - the adapter that streams calls for those providers.
937
+ * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.
938
+ */
939
+ registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle
940
+
941
+ /**
942
+ * Describe provider routes with a registered adapter.
943
+ * @returns detached provider metadata in registration order.
944
+ */
945
+ @Remote listProviders(): LlmProviderInfo[]
946
+
947
+ /**
948
+ * Declare provider routes an adapter plugin can activate through
949
+ * configuration. Registration is all-or-nothing: an empty list, invalid
950
+ * entry, or a provider already declared by any registration throws
951
+ * `LlmError` without registering the rest. Disposed with the fiber.
952
+ * @param entries - every configurable provider this plugin owns.
953
+ * @returns a handle that withdraws all of them, and can atomically replace them.
954
+ */
955
+ registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle
956
+
957
+ /**
958
+ * List every declared configurable provider, registered or dormant.
959
+ * @returns detached directory entries in declaration order.
960
+ */
961
+ @Remote listConfigurableProviders(): LlmConfigurableProvider[]
962
+
963
+ /**
964
+ * Offer to interrogate provider endpoints on behalf of the settings
965
+ * namespace this plugin owns. The namespace is the key because that is what
966
+ * a configuration surface already holds from the configurable-provider
967
+ * directory, and because a provider being *added* has no route to name yet.
968
+ * Disposed with the fiber.
969
+ * @param settingsNs - the namespace whose profiles this discovery serves.
970
+ * @param discover - interrogates one endpoint and must honor the supplied signal.
971
+ * @returns the disposer that withdraws the offer.
972
+ */
973
+ registerModelDiscovery( settingsNs: string, discover: ( request: LlmModelDiscoveryRequest, signal?: AbortSignal, ) => Promise<readonly LlmDiscoveredModel[]>, ): () => void
974
+
975
+ /**
976
+ * Interrogate one provider endpoint for the models it advertises. The
977
+ * request describes a draft, not a stored route, so nothing here reads or
978
+ * writes settings or credentials - the caller owns both, and the reply is
979
+ * candidate metadata a surface may offer for adoption.
980
+ * @param settingsNs - namespace whose registered discovery serves this draft.
981
+ * @param request - the endpoint, protocol, and one-shot credential to use.
982
+ * @param signal - caller cancellation.
983
+ * @returns the advertised models, deduplicated in endpoint order.
984
+ */
985
+ async discoverModels( settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal, ): Promise<LlmDiscoveredModel[]>
986
+
987
+ /**
988
+ * Remote adapter for one draft provider interrogation.
989
+ * @param settingsNs - namespace whose registered discovery serves this draft.
990
+ * @param request - endpoint, protocol, and one-shot credential to use.
991
+ * @param signal - caller cancellation supplied by the Remote carrier.
992
+ * @returns advertised models in endpoint order.
993
+ * @throws RemoteError with `llm/model-discovery-rejected` when discovery refuses or fails.
994
+ */
995
+ @Remote('discoverModels') async remoteDiscoverModels( settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal, ): Promise<LlmDiscoveredModel[]>
996
+
997
+ /**
998
+ * Resolve the retry policy captured when one provider route was registered.
999
+ * @param provider - registered provider route to inspect.
1000
+ * @returns the provider-owned policy, with normal defaults already resolved.
1001
+ */
1002
+ providerRetryPolicy(provider: string): ResolvedRetryPolicy
1003
+
1004
+ /**
1005
+ * Resolve provider-side request-image pricing for one exact route, or
1006
+ * `undefined` when the provider is unregistered or declares none. Unknown
1007
+ * providers degrade to `undefined` rather than throwing because callers
1008
+ * price durable history whose route may no longer be mounted.
1009
+ * @param provider - provider route named by a request header.
1010
+ * @param model - exact model id named by the same header.
1011
+ * @returns the owning adapter's image pricing for the route, when declared.
1012
+ */
1013
+ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined
1014
+
1015
+ /**
1016
+ * Resolve the exact text one durable file occurrence contributes to every
1017
+ * provider request in the current execution environment.
1018
+ * @param ref - durable verbatim file reference from model history.
1019
+ * @returns the same deterministic handle text used at adapter dispatch.
1020
+ */
1021
+ fileRequestText(ref: FileAttachmentRef): string
1022
+
1023
+ /**
1024
+ * Discover models advertised by one registered provider. Catalog membership
1025
+ * does not constrain core routing. Catalog-driven entry points may restrict
1026
+ * selection and submission to the advertised models.
1027
+ * @param provider - registered provider route to inspect.
1028
+ * @returns detached model metadata in adapter-preferred order.
1029
+ */
1030
+ async listModels(provider: string): Promise<LlmModelInfo[]>
1031
+
1032
+ /**
1033
+ * Resolve and validate all metadata from the adapter that owns one exact
1034
+ * route. The result is detached from adapter-owned objects; catalog
1035
+ * membership remains advisory and does not control request routing.
1036
+ * @param provider - registered provider route to inspect.
1037
+ * @param model - exact model id passed to the adapter.
1038
+ * @param signal - optional cancellation for adapter-owned asynchronous lookup.
1039
+ * @returns exact model identity plus available context and reasoning metadata.
1040
+ */
1041
+ async resolveModelInfo( provider: string, model: string, signal?: AbortSignal, ): Promise<LlmResolvedModelInfo>
1042
+
1043
+ /**
1044
+ * Validate a conversation call config against its exact model capability and
1045
+ * materialize adapter-configured defaults. Unsupported explicit efforts
1046
+ * reject before provider I/O; no clamping or aliasing is performed. This
1047
+ * standalone query does not bind a later dispatch; use {@link prepareCall}
1048
+ * when logging and streaming must share one adapter registration.
1049
+ * @param config - provider/model route and optional request controls.
1050
+ * @param signal - optional cancellation for adapter-owned capability lookup.
1051
+ * @returns a detached config only when a default must be materialized.
1052
+ */
1053
+ async resolveCallConfig(config: LlmCallConfig, signal?: AbortSignal): Promise<LlmCallConfig>
1054
+
1055
+ /**
1056
+ * Resolve one call under its current adapter registration. The returned
1057
+ * one-shot handle keeps that registration across header logging and dispatch,
1058
+ * so HMR cannot combine one adapter's capability result with another adapter.
1059
+ * @param config - provider/model route and optional request controls.
1060
+ * @param signal - optional cancellation for adapter-owned capability lookup.
1061
+ * @returns a prepared config and its registration-bound stream entry point.
1062
+ */
1063
+ async prepareCall(config: LlmCallConfig, signal?: AbortSignal): Promise<PreparedLlmCall>
1064
+
1065
+ /**
1066
+ * Stream one model call as raw chunks (token-level deltas). Replay state is
1067
+ * retained only when the same adapter instance owns its historical provider
1068
+ * and the target provider. Final adapter selection remains fixed through
1069
+ * asynchronous exact-model resolution and dispatch. Adapter selection,
1070
+ * dispatch, and iteration failures become terminal `error` or `aborted`
1071
+ * finish chunks; middleware, nested-call, cleanup, and consumer failures
1072
+ * remain thrown.
1073
+ * @param options - the full request; `options.provider` selects the adapter.
1074
+ * @returns the chunk stream, possibly wrapped by `llm/stream` listeners.
1075
+ */
1076
+ stream(options: GenerateOptions): AsyncIterable<StreamChunk>
1077
+ ```
1078
+
1079
+ Types: [FileAttachmentRef](attachment.md)
1080
+
1081
+ Source: [`packages/llm/llm/src/index.ts`](../../packages/llm/llm/src/index.ts)
1082
+
1083
+ <a id="llm-events"></a>
1084
+
1085
+ ### `llm/*` events
1086
+
1087
+ <a id="llmadapters-updated--emit"></a>
1088
+
1089
+ #### `llm/adapters-updated` - emit
1090
+
1091
+ The provider topology changed: an adapter registered or unregistered routes, or the configurable-provider directory gained or lost entries. This payload-free registry notification fires at each commit point (including registration disposal); consumers re-read `listProviders()`, `listModels()`, or `listConfigurableProviders()` for the new state. Observer failures are contained and cannot veto the registry mutation.
1092
+
1093
+ ```ts cordis-catalog
1094
+ /**
1095
+ * The provider topology changed: an adapter registered or unregistered
1096
+ * routes, or the configurable-provider directory gained or lost entries.
1097
+ * This payload-free registry notification fires at each commit point
1098
+ * (including registration disposal); consumers re-read `listProviders()`,
1099
+ * `listModels()`, or `listConfigurableProviders()` for the new state.
1100
+ * Observer failures are contained and cannot veto the registry mutation.
1101
+ * @mode emit
1102
+ */
1103
+ 'llm/adapters-updated'(): void
1104
+ ```
1105
+
1106
+ Source: [`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts)
1107
+
1108
+ <a id="llmstream--waterfall"></a>
1109
+
1110
+ #### `llm/stream` - waterfall
1111
+
1112
+ Waterfall around every streaming model call (retry, replay, routing). Bound to the LlmRuntime; call `next()` to reach the resolved adapter's stream, or yield your own chunks to short-circuit.
1113
+
1114
+ ```ts cordis-catalog
1115
+ /**
1116
+ * Waterfall around every streaming model call (retry, replay, routing).
1117
+ * Bound to the {@link LlmRuntime}; call `next()` to reach the resolved
1118
+ * adapter's stream, or yield your own chunks to short-circuit.
1119
+ * @param options - the full request. A LOOP-built request carries the
1120
+ * process-local {@link markAgentLoopRequest} identity and arrives deep-frozen
1121
+ * (mutation throws): its content is a pure function of the session log (the
1122
+ * reconstructability Agent Note), so listeners read it, never rewrite it.
1123
+ * Hand-built calls do not carry that marker; callers own their request
1124
+ * inputs and must keep them unchanged until the stream settles.
1125
+ * @mode waterfall
1126
+ */
1127
+ 'llm/stream'(this: LlmRuntime, options: GenerateOptions, next: () => AsyncIterable<StreamChunk>): AsyncIterable<StreamChunk>
1128
+ ```
1129
+
1130
+ Source: [`packages/llm/llm/src/index.ts`](../../packages/llm/llm/src/index.ts)
1131
+ <!-- END GENERATED cordis-surface -->