@acryldev/plugin-context 0.0.0-stage → 0.1.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 (284) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/docs/README.md +160 -0
  4. package/docs/delivery/local-live.md +113 -0
  5. package/docs/delivery/marketplace.md +16 -0
  6. package/docs/docs.json +2836 -0
  7. package/docs/extending/agent-preset.md +37 -0
  8. package/docs/extending/chat-command.md +28 -0
  9. package/docs/extending/client-slot.md +135 -0
  10. package/docs/extending/config-schema.md +7 -0
  11. package/docs/extending/cordis-core.md +63 -0
  12. package/docs/extending/desktop-app.md +53 -0
  13. package/docs/extending/desktop-main.md +25 -0
  14. package/docs/extending/event-hook.md +14 -0
  15. package/docs/extending/host-route.md +33 -0
  16. package/docs/extending/llm-adapter.md +38 -0
  17. package/docs/extending/packaging.md +53 -0
  18. package/docs/extending/prompt-contribution.md +9 -0
  19. package/docs/extending/service.md +13 -0
  20. package/docs/extending/skill-provider.md +9 -0
  21. package/docs/extending/state-and-persistence.md +71 -0
  22. package/docs/extending/three-role-capability.md +33 -0
  23. package/docs/extending/tool-plugin.md +24 -0
  24. package/docs/extending/tui-command.md +8 -0
  25. package/docs/extending/tui-components.md +61 -0
  26. package/docs/extending/ui-branding.md +43 -0
  27. package/docs/extending/ui-components.md +56 -0
  28. package/docs/extending/ui-customization.md +41 -0
  29. package/docs/extending/ui-library.md +66 -0
  30. package/docs/extending/ui-theme.md +55 -0
  31. package/docs/extending/workspace-tab.md +50 -0
  32. package/docs/maps/events.md +108 -0
  33. package/docs/maps/mount-points.md +154 -0
  34. package/docs/maps/slot-contracts.md +3376 -0
  35. package/docs/maps/taxonomy.md +306 -0
  36. package/docs/maps/theme-tokens.md +115 -0
  37. package/docs/maps/ui-components.md +26 -0
  38. package/docs/reference/cookbook/adding-a-package.md +174 -0
  39. package/docs/reference/cookbook/adding-a-remote-api.md +199 -0
  40. package/docs/reference/cookbook/adding-a-settings-card.md +74 -0
  41. package/docs/reference/cookbook/adding-a-tool.md +103 -0
  42. package/docs/reference/cookbook/adding-an-llm-adapter.md +45 -0
  43. package/docs/reference/cookbook/extension-cookbook.md +134 -0
  44. package/docs/reference/cordis-api/context.md +366 -0
  45. package/docs/reference/cordis-api/events.md +209 -0
  46. package/docs/reference/cordis-api/fiber.md +377 -0
  47. package/docs/reference/cordis-api/inherited.md +40 -0
  48. package/docs/reference/cordis-api/registry.md +154 -0
  49. package/docs/reference/cordis-api/service.md +104 -0
  50. package/docs/reference/cordis-guides/cordis-usage-cheatsheet.md +167 -0
  51. package/docs/reference/cordis-guides/cordis_system_guide_for_coding_agents.md +4666 -0
  52. package/docs/reference/cordis-guides/development-canvas-plugin.md +109 -0
  53. package/docs/reference/cordis-guides/hello-world-plugin-guide.md +517 -0
  54. package/docs/reference/harness/agent-lifecycle.md +93 -0
  55. package/docs/reference/harness/architecture.md +168 -0
  56. package/docs/reference/harness/capability-seams.md +675 -0
  57. package/docs/reference/harness/config-catalog.md +4523 -0
  58. package/docs/reference/harness/cordis-primer.md +47 -0
  59. package/docs/reference/harness/defensive-patterns.md +35 -0
  60. package/docs/reference/harness/event-producer-consumer.md +111 -0
  61. package/docs/reference/harness/glossary.md +47 -0
  62. package/docs/reference/harness/tool-catalog.md +2721 -0
  63. package/docs/reference/harness/tool-execution-pipeline.md +67 -0
  64. package/docs/reference/subsystems/README.md +75 -0
  65. package/docs/reference/subsystems/agent-team.md +233 -0
  66. package/docs/reference/subsystems/approval.md +172 -0
  67. package/docs/reference/subsystems/attachment.md +363 -0
  68. package/docs/reference/subsystems/boot.md +324 -0
  69. package/docs/reference/subsystems/browser-use.md +69 -0
  70. package/docs/reference/subsystems/client-modules.md +186 -0
  71. package/docs/reference/subsystems/client-resources.md +94 -0
  72. package/docs/reference/subsystems/commands.md +225 -0
  73. package/docs/reference/subsystems/compaction.md +286 -0
  74. package/docs/reference/subsystems/computer-use.md +58 -0
  75. package/docs/reference/subsystems/conversation.md +287 -0
  76. package/docs/reference/subsystems/core.md +1107 -0
  77. package/docs/reference/subsystems/credentials.md +497 -0
  78. package/docs/reference/subsystems/deliverables.md +180 -0
  79. package/docs/reference/subsystems/extensions.md +386 -0
  80. package/docs/reference/subsystems/feedback.md +402 -0
  81. package/docs/reference/subsystems/filesystem.md +532 -0
  82. package/docs/reference/subsystems/goal.md +315 -0
  83. package/docs/reference/subsystems/invariants.md +90 -0
  84. package/docs/reference/subsystems/jobs.md +501 -0
  85. package/docs/reference/subsystems/llm-streaming.md +1131 -0
  86. package/docs/reference/subsystems/lsp.md +204 -0
  87. package/docs/reference/subsystems/mcp.md +141 -0
  88. package/docs/reference/subsystems/office-to-pdf.md +89 -0
  89. package/docs/reference/subsystems/otel.md +46 -0
  90. package/docs/reference/subsystems/permission-presets.md +169 -0
  91. package/docs/reference/subsystems/persistence.md +418 -0
  92. package/docs/reference/subsystems/plan.md +89 -0
  93. package/docs/reference/subsystems/product-telemetry.md +81 -0
  94. package/docs/reference/subsystems/ptc-runtime.md +234 -0
  95. package/docs/reference/subsystems/sandbox.md +223 -0
  96. package/docs/reference/subsystems/schedule.md +545 -0
  97. package/docs/reference/subsystems/scope.md +61 -0
  98. package/docs/reference/subsystems/session-projection.md +358 -0
  99. package/docs/reference/subsystems/session-query.md +511 -0
  100. package/docs/reference/subsystems/session-reference.md +226 -0
  101. package/docs/reference/subsystems/session-telemetry.md +214 -0
  102. package/docs/reference/subsystems/session-title.md +206 -0
  103. package/docs/reference/subsystems/session.md +1300 -0
  104. package/docs/reference/subsystems/settings.md +157 -0
  105. package/docs/reference/subsystems/shell.md +316 -0
  106. package/docs/reference/subsystems/sidebar-right.md +160 -0
  107. package/docs/reference/subsystems/skills.md +354 -0
  108. package/docs/reference/subsystems/slots.md +201 -0
  109. package/docs/reference/subsystems/spill.md +126 -0
  110. package/docs/reference/subsystems/ssh.md +137 -0
  111. package/docs/reference/subsystems/storage.md +262 -0
  112. package/docs/reference/subsystems/subagent.md +762 -0
  113. package/docs/reference/subsystems/subprocess.md +323 -0
  114. package/docs/reference/subsystems/system-prompt.md +226 -0
  115. package/docs/reference/subsystems/terminal.md +186 -0
  116. package/docs/reference/subsystems/todo.md +34 -0
  117. package/docs/reference/subsystems/token-meter.md +108 -0
  118. package/docs/reference/subsystems/tools.md +749 -0
  119. package/docs/reference/subsystems/typert.md +489 -0
  120. package/docs/reference/subsystems/user-questions.md +309 -0
  121. package/docs/reference/subsystems/voice-input.md +166 -0
  122. package/docs/reference/subsystems/web-client.md +102 -0
  123. package/docs/reference/subsystems/web-server.md +228 -0
  124. package/docs/reference/subsystems/web.md +208 -0
  125. package/docs/reference/subsystems/webhook.md +72 -0
  126. package/docs/reference/subsystems/workflow.md +280 -0
  127. package/docs/reference/subsystems/workspace.md +661 -0
  128. package/docs/start-here/blueprints.md +33 -0
  129. package/docs/start-here/this-runtime.md +84 -0
  130. package/docs/start-here/troubleshooting.md +29 -0
  131. package/docs/start-here/trust-and-safety.md +39 -0
  132. package/docs/start-here/verify-before-done.md +46 -0
  133. package/example-plugins/README.md +45 -0
  134. package/example-plugins/packages/agent-preset-reviewer/agent.cordis.yml +18 -0
  135. package/example-plugins/packages/agent-preset-reviewer/preset.yml +3 -0
  136. package/example-plugins/packages/capability-swap-consumer/cordis.patch.yml +3 -0
  137. package/example-plugins/packages/capability-swap-consumer/index.js +14 -0
  138. package/example-plugins/packages/capability-swap-consumer/package.json +25 -0
  139. package/example-plugins/packages/capability-swap-provider-loud/cordis.patch.yml +3 -0
  140. package/example-plugins/packages/capability-swap-provider-loud/index.js +20 -0
  141. package/example-plugins/packages/capability-swap-provider-loud/package.json +25 -0
  142. package/example-plugins/packages/capability-swap-provider-quiet/cordis.patch.yml +3 -0
  143. package/example-plugins/packages/capability-swap-provider-quiet/index.js +20 -0
  144. package/example-plugins/packages/capability-swap-provider-quiet/package.json +25 -0
  145. package/example-plugins/packages/chat-command-basic/cordis.patch.yml +3 -0
  146. package/example-plugins/packages/chat-command-basic/index.js +26 -0
  147. package/example-plugins/packages/chat-command-basic/package.json +25 -0
  148. package/example-plugins/packages/client-chat-message-action/client.js +46 -0
  149. package/example-plugins/packages/client-chat-message-action/cordis.patch.yml +3 -0
  150. package/example-plugins/packages/client-chat-message-action/index.js +9 -0
  151. package/example-plugins/packages/client-chat-message-action/package.json +31 -0
  152. package/example-plugins/packages/client-slot-header-action/client.js +57 -0
  153. package/example-plugins/packages/client-slot-header-action/cordis.patch.yml +3 -0
  154. package/example-plugins/packages/client-slot-header-action/index.js +13 -0
  155. package/example-plugins/packages/client-slot-header-action/package.json +31 -0
  156. package/example-plugins/packages/client-slot-sidebar-tab/client.js +57 -0
  157. package/example-plugins/packages/client-slot-sidebar-tab/cordis.patch.yml +3 -0
  158. package/example-plugins/packages/client-slot-sidebar-tab/index.js +9 -0
  159. package/example-plugins/packages/client-slot-sidebar-tab/package.json +32 -0
  160. package/example-plugins/packages/client-theme-override/client.js +52 -0
  161. package/example-plugins/packages/client-theme-override/cordis.patch.yml +3 -0
  162. package/example-plugins/packages/client-theme-override/index.js +9 -0
  163. package/example-plugins/packages/client-theme-override/package.json +30 -0
  164. package/example-plugins/packages/client-tool-view/client.js +47 -0
  165. package/example-plugins/packages/client-tool-view/cordis.patch.yml +3 -0
  166. package/example-plugins/packages/client-tool-view/index.js +24 -0
  167. package/example-plugins/packages/client-tool-view/package.json +34 -0
  168. package/example-plugins/packages/client-ui-components/client.js +77 -0
  169. package/example-plugins/packages/client-ui-components/cordis.patch.yml +3 -0
  170. package/example-plugins/packages/client-ui-components/index.js +9 -0
  171. package/example-plugins/packages/client-ui-components/package.json +31 -0
  172. package/example-plugins/packages/client-ui-library/client.js +715 -0
  173. package/example-plugins/packages/client-ui-library/cordis.patch.yml +3 -0
  174. package/example-plugins/packages/client-ui-library/index.js +9 -0
  175. package/example-plugins/packages/client-ui-library/package.json +37 -0
  176. package/example-plugins/packages/client-workspace-tab/client.js +72 -0
  177. package/example-plugins/packages/client-workspace-tab/cordis.patch.yml +3 -0
  178. package/example-plugins/packages/client-workspace-tab/index.js +9 -0
  179. package/example-plugins/packages/client-workspace-tab/package.json +30 -0
  180. package/example-plugins/packages/config-schema-basic/cordis.patch.yml +3 -0
  181. package/example-plugins/packages/config-schema-basic/index.js +19 -0
  182. package/example-plugins/packages/config-schema-basic/package.json +25 -0
  183. package/example-plugins/packages/desktop-main-profile-info/cordis.patch.yml +3 -0
  184. package/example-plugins/packages/desktop-main-profile-info/index.js +22 -0
  185. package/example-plugins/packages/desktop-main-profile-info/package.json +25 -0
  186. package/example-plugins/packages/event-hook-basic/cordis.patch.yml +3 -0
  187. package/example-plugins/packages/event-hook-basic/index.js +17 -0
  188. package/example-plugins/packages/event-hook-basic/package.json +22 -0
  189. package/example-plugins/packages/generated-capability-template/cordis.patch.yml +3 -0
  190. package/example-plugins/packages/generated-capability-template/index.js +16 -0
  191. package/example-plugins/packages/generated-capability-template/package.json +42 -0
  192. package/example-plugins/packages/host-route-basic/cordis.patch.yml +3 -0
  193. package/example-plugins/packages/host-route-basic/index.js +20 -0
  194. package/example-plugins/packages/host-route-basic/package.json +29 -0
  195. package/example-plugins/packages/lifecycle-function-basic/cordis.patch.yml +3 -0
  196. package/example-plugins/packages/lifecycle-function-basic/index.js +12 -0
  197. package/example-plugins/packages/lifecycle-function-basic/package.json +15 -0
  198. package/example-plugins/packages/lifecycle-function-hot-shim/cordis.patch.yml +3 -0
  199. package/example-plugins/packages/lifecycle-function-hot-shim/impl.js +5 -0
  200. package/example-plugins/packages/lifecycle-function-hot-shim/index.js +18 -0
  201. package/example-plugins/packages/lifecycle-function-hot-shim/package.json +23 -0
  202. package/example-plugins/packages/lifecycle-hooks-observer/cordis.patch.yml +3 -0
  203. package/example-plugins/packages/lifecycle-hooks-observer/index.js +23 -0
  204. package/example-plugins/packages/lifecycle-hooks-observer/package.json +22 -0
  205. package/example-plugins/packages/llm-adapter-echo/cordis.patch.yml +3 -0
  206. package/example-plugins/packages/llm-adapter-echo/index.js +42 -0
  207. package/example-plugins/packages/llm-adapter-echo/package.json +25 -0
  208. package/example-plugins/packages/prompt-assemble-hook/cordis.patch.yml +3 -0
  209. package/example-plugins/packages/prompt-assemble-hook/index.js +22 -0
  210. package/example-plugins/packages/prompt-assemble-hook/package.json +22 -0
  211. package/example-plugins/packages/prompt-contribution-basic/cordis.patch.yml +3 -0
  212. package/example-plugins/packages/prompt-contribution-basic/index.js +18 -0
  213. package/example-plugins/packages/prompt-contribution-basic/package.json +22 -0
  214. package/example-plugins/packages/service-consumer-greeter/cordis.patch.yml +3 -0
  215. package/example-plugins/packages/service-consumer-greeter/index.js +14 -0
  216. package/example-plugins/packages/service-consumer-greeter/package.json +22 -0
  217. package/example-plugins/packages/service-provider-greeter/cordis.patch.yml +3 -0
  218. package/example-plugins/packages/service-provider-greeter/index.js +22 -0
  219. package/example-plugins/packages/service-provider-greeter/package.json +25 -0
  220. package/example-plugins/packages/settings-section-basic/cordis.patch.yml +3 -0
  221. package/example-plugins/packages/settings-section-basic/index.js +34 -0
  222. package/example-plugins/packages/settings-section-basic/package.json +26 -0
  223. package/example-plugins/packages/skill-provider-basic/cordis.patch.yml +3 -0
  224. package/example-plugins/packages/skill-provider-basic/index.js +31 -0
  225. package/example-plugins/packages/skill-provider-basic/package.json +22 -0
  226. package/example-plugins/packages/state-host-store/client.js +57 -0
  227. package/example-plugins/packages/state-host-store/cordis.patch.yml +3 -0
  228. package/example-plugins/packages/state-host-store/index.js +90 -0
  229. package/example-plugins/packages/state-host-store/package.json +31 -0
  230. package/example-plugins/packages/state-workspace-file/cordis.patch.yml +3 -0
  231. package/example-plugins/packages/state-workspace-file/index.js +52 -0
  232. package/example-plugins/packages/state-workspace-file/package.json +25 -0
  233. package/example-plugins/packages/tool-basic/cordis.patch.yml +3 -0
  234. package/example-plugins/packages/tool-basic/index.js +25 -0
  235. package/example-plugins/packages/tool-basic/package.json +25 -0
  236. package/example-plugins/packages/tool-policy-hook/cordis.patch.yml +3 -0
  237. package/example-plugins/packages/tool-policy-hook/index.js +28 -0
  238. package/example-plugins/packages/tool-policy-hook/package.json +25 -0
  239. package/example-plugins/packages/tui-command-basic/cordis.patch.yml +3 -0
  240. package/example-plugins/packages/tui-command-basic/index.js +24 -0
  241. package/example-plugins/packages/tui-command-basic/package.json +22 -0
  242. package/example-plugins/packages/tui-overlay-themed/cordis.patch.yml +3 -0
  243. package/example-plugins/packages/tui-overlay-themed/index.js +65 -0
  244. package/example-plugins/packages/tui-overlay-themed/package.json +25 -0
  245. package/example-plugins/packages/tui-ui-library/cordis.patch.yml +3 -0
  246. package/example-plugins/packages/tui-ui-library/index.js +73 -0
  247. package/example-plugins/packages/tui-ui-library/package.json +29 -0
  248. package/example-plugins/packages/web-page-branding/cordis.patch.yml +3 -0
  249. package/example-plugins/packages/web-page-branding/index.js +31 -0
  250. package/example-plugins/packages/web-page-branding/package.json +22 -0
  251. package/example-plugins/scenarios.json +11 -0
  252. package/index.js +384 -0
  253. package/lib/blend-apply.js +107 -0
  254. package/lib/blend-capture.js +249 -0
  255. package/lib/blend-ledger.js +76 -0
  256. package/lib/contract.js +5 -0
  257. package/lib/install.js +516 -0
  258. package/lib/lookup.js +67 -0
  259. package/lib/manifest.js +56 -0
  260. package/lib/pack-root.js +22 -0
  261. package/lib/provenance.js +110 -0
  262. package/lib/publish.js +64 -0
  263. package/lib/reconcile.js +83 -0
  264. package/lib/router.js +55 -0
  265. package/lib/scopes.js +82 -0
  266. package/lib/skills.js +54 -0
  267. package/lib/stage.js +157 -0
  268. package/lib/verify.js +77 -0
  269. package/package.json +58 -3
  270. package/scripts/lib/indexes.mjs +45 -0
  271. package/scripts/lib/manifest.mjs +127 -0
  272. package/scripts/lib/maps.mjs +482 -0
  273. package/skills/acryl-add-provider-or-capability/SKILL.md +12 -0
  274. package/skills/acryl-add-ui/SKILL.md +18 -0
  275. package/skills/acryl-build-plugin/SKILL.md +21 -0
  276. package/skills/acryl-change-plugin/SKILL.md +16 -0
  277. package/skills/acryl-desktop-shell/SKILL.md +12 -0
  278. package/skills/acryl-diagnose-plugin/SKILL.md +10 -0
  279. package/skills/acryl-fix-plugin/SKILL.md +12 -0
  280. package/skills/acryl-improve-ui/SKILL.md +10 -0
  281. package/skills/acryl-remove-plugin/SKILL.md +11 -0
  282. package/skills/acryl-restyle-ui/SKILL.md +14 -0
  283. package/skills/acryl-share-plugin/SKILL.md +23 -0
  284. package/skills/acryl-tui-ui/SKILL.md +12 -0
@@ -0,0 +1,174 @@
1
+ <!-- Synced from deepseek-harness:docs/cookbook/adding-a-package.md @ 639ed01539. Do not edit; run scripts/sync-corpus.mjs. Relative links inside may not resolve here. -->
2
+
3
+ # Cookbook: adding a workspace package
4
+
5
+ English | [中文](adding-a-package.zh.md)
6
+
7
+ The file-by-file checklist for a new `@deepseek-ai/dsh-<name>` package. This checklist is validated against the bash and adapter packages as templates; if it drifts from them, fix it here.
8
+
9
+ ## 1. Create the package
10
+
11
+ ```
12
+ packages/<group>/<pkg>/
13
+ package.json # copy from packages/core/tools, adjust name/description/deps
14
+ tsconfig.json # extends ../../../tsconfig.base.json, rootDir src,
15
+ # outDir lib/types, references: ../../../vendor/cosmokit,
16
+ # ../../../vendor/cordis (+ ../../../vendor/schemastery if
17
+ # you use Config, + ../../<group>/<dep> for each dsh dep)
18
+ src/index.ts # service default export or plugin (name/inject/apply/Config)
19
+ locale/en.json # optional display metadata: meta.title and meta.description
20
+ locale/zh.json # translations using the same fields
21
+ README.md # service API, events, extension points, design notes,
22
+ # + gated Model Experience context blocks or short form
23
+ # + the gated "Known Limitations and Deferred Work" section
24
+ # (or a whitelist entry in scripts/verify-package-readme-limitations.ts)
25
+ ```
26
+
27
+ Choose an existing group when one matches the package's role (`core`, `llm`, `shell`, `compaction`, `subagent`, `todo`, `session`, `client`/`host`, `util`, or `test-support`). A new group is allowed, but it is a pure container: no `package.json`, no source files, and packages still sit exactly one level below it.
28
+
29
+ package.json invariants (enforced by `pnpm run constraints` / `scripts/check-workspace-constraints.ts`): `private: true`, a `version` matching the root `package.json`, `type: module`, `main: "lib/index.js"`, `types: "lib/types/index.d.ts"`, `exports["."].types: "./lib/types/index.d.ts"`, `exports["."].default: "./lib/index.js"`, `@deepseek-ai/cordis` in BOTH peerDependencies and devDependencies (same range). Mirror every dsh peer dependency in devDependencies. `@deepseek-ai/schemastery` goes in `dependencies` (it is a runtime validator), matching agent-loop. The `files` list contains exactly `lib/index.js`, `lib/types/**/*.d.ts`, and package-specific runtime artifacts recognized by the gate; a package that publishes `./invariant` also includes `lib/invariant.js`. A package whose runtime export points into the emitted tree also includes `lib/types/**/*.js`. Do not publish `src`, declaration maps, JS maps, or stale root declaration files. CLI app packages with a package `bin` include `lib/bin.js` immediately after `lib/index.js` in `files`.
30
+
31
+ In-package relative imports use explicit `.ts` specifiers in source (for example, `export * from './types.ts'`). The compiler rewrites those to `.js` in emitted JS and leaves explicit `.ts` specifiers in declarations, which standard NodeNext/Node16 TypeScript consumers resolve to the sibling `.d.ts` files.
32
+
33
+ ## 2. Register it in the root configs
34
+
35
+ | File | Change |
36
+ |---|---|
37
+ | `tsconfig.base.json` | no edit for an existing group; for a new group, add a `./packages/<group>/*/src` candidate to the `@deepseek-ai/dsh-*` wildcard |
38
+ | `tsconfig.host.json` (Host package) or `tsconfig.client.json` (Client package) | add `{ "path": "./packages/<group>/<pkg>" }` to `references` - an ordinary package belongs to exactly one aggregate, never both. `api/remotes` uses a repository-specific split because the Host generates a contract that the Client consumes in a later phase; new packages must not copy it ([layout](../development.md#typescript-project-layout)) |
39
+
40
+ A `packages/client/*` package additionally extends `tsconfig.base.client.json` instead of `tsconfig.base.json`, and a client plugin package declares `dsh.client` in package.json, exports `./client`, and calls the shared tsdown preset (`packages/client/tsdown.client.ts`) - see [packages/client/AGENTS.md](../../packages/client/AGENTS.md) for the client-side contract.
41
+
42
+ Covered automatically by globs or package-manifest discovery - no edits needed: root `package.json` workspaces, `scripts/publint-all.ts`, `tsdown.config.ts`, `.oxlintrc.json`, `scripts/check-workspace-constraints.ts`.
43
+
44
+ ## 3. Decide the package topology
45
+
46
+ For a swappable capability, separate Service Definition / Service Provider / Consumer roles into packages when they evolve independently (see docs/architecture.md § "Capability seams" - the shell trio is the template). A single-purpose plugin stays one package.
47
+
48
+ ### Name the role that exists
49
+
50
+ Name the stable current responsibility. Do not name the first implementation, a possible future expansion, or the Cordis base class. An interface package names the capability. An implementation package adds the mechanism, protocol, environment, or vendor that distinguishes it. Use `local` only when same-host execution is part of the contract.
51
+
52
+ Use a singular `ctx` key for one engine, runtime, policy, controller, resolver, store, or current configuration. Use a plural key for a registry or a service that owns multiple named members. The class role and key number must agree. Do not reuse one Cordis `Context` key for incompatible host and client declarations. TypeScript declaration merging sees both faces even when they use separate runtime contexts. Add the role suffix when the natural plural already belongs to another face.
53
+
54
+ | Word | Use it when | Do not use it when |
55
+ |---|---|---|
56
+ | `Controller` | It accepts commands or user intent and changes one existing domain or presentation state. | It executes arbitrary work, owns a provider fleet, or only converts values for display. |
57
+ | `Store` | It owns one data set and mainly offers CRUD, snapshot, or subscription operations for that data. | It validates a state machine, arbitrates authority, dispatches work, or owns provider precedence. A map does not make a class a store. |
58
+ | `Directory` | It exposes entries and metadata for discovery or selection. | Producers register arbitrary implementations into it, or callers execute work through it. |
59
+ | `Presenter` | It is a pure conversion from domain values or tool arguments to render intent. | It performs I/O, subscribes, mutates state, or owns lifecycle. |
60
+ | `Registry` | It owns a dynamic set of named registrations, including lookup, duplicate or precedence rules, lifetime, and disposal. | Its main contract is dispatch, execution, cancellation, policy, or orchestration. |
61
+ | `Runtime` | It runs live work and owns dispatch, cancellation, provider coordination, or operation lifecycle across calls. | It only stores records, returns a catalog, resolves one value, or holds configuration. |
62
+ | `Resolver` | It computes or locates one answer from supplied inputs without owning that answer's lifecycle. | It owns a mutable collection or long-running execution. |
63
+ | `Binder` | It attaches one declared interface to a caller context or lifecycle and returns the bound value. | It owns the value as a collection, controls its domain state, or only converts data. |
64
+ | `Engine` | It implements a domain algorithm or stateful execution model. | It only selects a provider or forwards across a protocol boundary. |
65
+ | `Policy` | It decides what is allowed, selected, limited, or observed. | It performs the mechanism that the decision permits. |
66
+ | `Executor` | It runs one explicit request or resolved specification in one capability. | It owns a broad application lifecycle or provider catalog. |
67
+ | `Gateway` | It adapts a process, network, RPC, or API boundary. | It only registers same-process services or stores metadata. |
68
+ | `Provider` | It supplies one implementation of a capability definition. Add a mechanism or vendor qualifier when several can exist. | It is the capability definition, provider registry, or consumer runtime. |
69
+ | `Backend` | It implements replaceable lower-level persistence, transport, or execution behind a defined interface. | It is a user-facing service or one returned live-resource reference. |
70
+ | `Handle` | It refers to one live resource and controls or observes that resource. | It creates and manages the complete resource pool. |
71
+ | `Config` | It owns one resolved configuration value or one tightly bounded record and its update contract. | It stores a general collection, executes work, or exposes unrelated settings. |
72
+ | `Service` | It owns a cohesive domain service that no sharper role above states honestly. | The name exists only because the class extends Cordis `Service`. |
73
+
74
+ Use `SDK` only for the JSON-RPC client/server protocol used by the supported Python and TypeScript SDKs. DeepSeek Harness itself is an agent harness, not an SDK project. Use the canonical product spelling `Typert`, never `TypeRT` or `typeRT`.
75
+
76
+ <a id="4-write-the-package-readme"></a>
77
+
78
+ ## 4. Write the package README
79
+
80
+ Keep package-specific service API, config, events, extension points, and design notes first. Choose the frontmatter `kind` from the four kind labels in the [dsh-doc metadata reference](../../.agents/skills/dsh-doc/references/metadata-links-i18n.md#the-kind-system) - group, reference, library, or bundle - matching the package's repository position and entry shape; each kind selects one README template. The limitations section records durable consumer gaps and non-obvious maintainer constraints owned by this package; ordinary cleanup stays in its source TODO or Agent Note. An indirect Model Experience sentence may name the consumer that surfaces this package's contribution, but it does not restate that consumer's implementation. End a package README with this canonical sequence:
81
+
82
+ ````markdown
83
+ ## Model Experience
84
+
85
+ ### Request context and condition
86
+
87
+ #### What the model sees
88
+
89
+ The exact data-dependent fields, an anchored generated-catalog link, or an introduction to the verbatim literal below.
90
+
91
+ ##### Verbatim text for this field, when needed
92
+
93
+ ```markdown
94
+ Stable system-prompt prose of any length, or another long non-generated literal, copied exactly from source.
95
+ ```
96
+
97
+ #### Token effect
98
+
99
+ Fixed, conditional, retained, replaced, capped, or zero-direct token effect.
100
+
101
+ #### KV Cache effect
102
+
103
+ Append-only, prefix-stable, replacing, or independent behavior, including the exact conditions that may invalidate reuse.
104
+
105
+ ## Known Limitations and Deferred Work
106
+
107
+ - **Consumer-visible gap** - exact missing operation or case, its consequence, and any maintainer constraint.
108
+ ````
109
+
110
+ Fill Model Experience from the implementation. Use one H3 per direct, conditional, capped, lifetime, or auxiliary model-context entry, with the three ordered H4 fields shown above and one prose paragraph under each. Quote stable text owned by the package: system-prompt prose goes in a titled H5 plus `markdown` fence under the field that introduces it-normally `What the model sees`-other short literals stay inline with named placeholders, and other long literals use the same nested form. Summarize only data-dependent or provider-owned text. A tool-schema entry links its anchored section in the generated [tool catalog](../tool-catalog.md) and states only deltas absent there. Keep prompt and schema entries separate when scoping can hide one without the other. In `KV Cache effect`, distinguish append-only growth, a stable repeated prefix, replacement of earlier request tokens, and an independent model request, then name the package-owned changes that can invalidate reuse. “Does not invalidate” means the package preserves an already-reusable prefix; provider cache availability and eviction remain outside the package contract. The [prose standard](../../.agents/skills/dsh-prose-standard/SKILL.md) governs completeness and ownership; the verifier enforces the required section structure.
111
+
112
+ A package with no context effect or one consumer-owned path uses the audited `None, as ` or `Indirectly, through ` sentence in [`SENTENCE_MODEL_EXPERIENCE`](../../scripts/verify-package-readme-model-experience.ts), followed by a `KV Cache effect` H4 and one non-empty paragraph; a model-agnostic generic package may instead join `NO_MODEL_EXPERIENCE_SECTION`. Do not expand either case into a description of another package's work. The limitations [allowlist](../../scripts/verify-package-readme-limitations.ts) is independent. The [Model Experience Agent Note](../../.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.md) records the rationale.
113
+
114
+ <a id="plugin-display-metadata"></a>
115
+
116
+ ## 5. Add optional plugin display metadata
117
+
118
+ For an npm package plugin, define its title and description in `locale/en.json`. Other language files, such as `locale/zh.json`, use the same fields:
119
+
120
+ ```json
121
+ {
122
+ "meta": {
123
+ "title": "Workspace Tools",
124
+ "description": "Tools for your workspace."
125
+ }
126
+ }
127
+ ```
128
+
129
+ Merge these entries into `package.json`, retaining existing runtime exports and publication files:
130
+
131
+ ```json
132
+ {
133
+ "exports": {
134
+ "./package.json": "./package.json",
135
+ "./locale/*.json": "./locale/*.json"
136
+ },
137
+ "files": ["locale/*.json"]
138
+ }
139
+ ```
140
+
141
+ Keep language files together in `locale/`, with `en.json` as the discovery entry. Fields are optional; present values must be non-empty strings. Missing files or fields permit fallback, while malformed JSON or invalid fields produce a per-plugin diagnostic.
142
+
143
+ Fields fall back independently before view-specific name formatting, using the existing locale language chain first:
144
+
145
+ - Title: locale `meta.title` → `package.json.name` → complete Cordis plugin name.
146
+ - Description: locale `meta.description` → `package.json.description` → no description.
147
+
148
+ Export `<package name>/locale/en.json` for locale lookup; expose `<package name>/package.json` for package-field fallback or an icon declaration.
149
+
150
+ For an image on bundle cards, details, and component rows, set top-level `"icon": "./icon.svg"` in that exported manifest and include the image in `files`. The path is relative to the declaring manifest's directory, including for independently exported plugin manifests. SVG, PNG, JPEG (`.jpg`/`.jpeg`), and WebP files are supported up to 256 KiB. Absolute paths, URLs, paths outside that directory, and symlinks resolving outside it are rejected. Images need no separate export and must be self-contained; SVG is rendered as an image, not inline HTML. The Host returns a data URL without activating the plugin. Invalid declarations or unreadable files produce a metadata diagnostic while retaining valid text; missing or undecodable images use the panel's default artwork.
151
+
152
+ Installed bundle cards and details, component lists and configuration details, and Settings' plugin inventory display this metadata, including disabled and preset plugins. Reads do not activate plugins.
153
+
154
+ Only Settings shortens literal package-name and module-name fallbacks by removing npm scope and Cordis/DSH prefixes; Plugin Manager keeps complete names. Locale titles and descriptions remain unchanged. A row configuration page can use its registered summary when the plugin has no display description.
155
+
156
+ The Install view still uses npm registry information from `pnpm view`, not locale metadata.
157
+
158
+ Verify the result:
159
+
160
+ 1. Run `pnpm run verify-package-meta` from the repository root to check fields, resource exports, and publication coverage.
161
+ 2. Switch an installed plugin's applicable Plugin Manager and Settings entries between English and Chinese; check the title, description, per-field fallback, and Settings-only compact technical names.
162
+
163
+ See the [plugin metadata Agent Note](../../.agents/notes/implemented/architecture/2026-09-18-localized-package-metadata.md) for resource ownership and non-activation rationale.
164
+
165
+ ## 6. Verify
166
+
167
+ ```sh
168
+ pnpm install # registers the workspace
169
+ pnpm run doc-sync
170
+ pnpm run constraints && pnpm run typecheck && pnpm run lint
171
+ pnpm run build && pnpm run hygiene
172
+ ```
173
+
174
+ Follow the [repository testing policy](../testing.md) for the behavior-specific checks and coverage required by the new package.
@@ -0,0 +1,199 @@
1
+ <!-- Synced from deepseek-harness:docs/cookbook/adding-a-remote-api.md @ 639ed01539. Do not edit; run scripts/sync-corpus.mjs. Relative links inside may not resolve here. -->
2
+
3
+ # Cookbook: adding a Remote API
4
+
5
+ English | [中文](adding-a-remote-api.zh.md)
6
+
7
+ Adding or changing a `ctx.remote` endpoint takes the five steps on this page: declare the method, declare its failures, register it on the package, consume it on the Client, and test it. Decorator semantics, lookup resolution, the generation pipeline, and the `/api` route are the mechanism and belong to the [API Gateway reference](../api-gateway.md); this page gives the action for each step and the conventions it must satisfy. Why the programming interface looks like this is in the [Typert Remote method calls Agent Note](../../.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.md), and why a failure is one `RemoteError` plus a code table is in the [failure vocabulary Agent Note](../../.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md).
8
+
9
+ ## 1. Declare the API
10
+
11
+ The owner is a Host-side Cordis service: extend `TypertRemoteService` so the service key and the wire namespace are bound together, then mark the exposed methods with `@Remote`. Mark the business method itself when its signature already satisfies the wire conventions; write a `remoteExport*` adapter only when the shape has to change (adding `signal`, reordering parameters, exporting another name), and let that adapter call the unrenamed business method. Lookup objects (`Agent`, `Session`) may only occupy top-level parameter positions, and a method that supports cooperative cancellation takes `signal: AbortSignal` as its final parameter.
12
+
13
+ ```ts
14
+ import type { Context } from '@deepseek-ai/cordis'
15
+ import type { Agent } from '@deepseek-ai/dsh-agent'
16
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
17
+
18
+ /** One stored note as a Client reads it. */
19
+ export interface NoteRow {
20
+ readonly noteId: string
21
+ readonly title: string
22
+ }
23
+
24
+ declare module '@deepseek-ai/cordis' {
25
+ interface Context {
26
+ notesController: NotesController
27
+ }
28
+ }
29
+
30
+ export class NotesController extends TypertRemoteService {
31
+ constructor(ctx: Context) {
32
+ super(ctx, 'notesController', { namespace: 'notes' })
33
+ }
34
+
35
+ /**
36
+ * @param agent - lookup parameter the Gateway resolves from its wire identity.
37
+ * @param signal - carrier cancellation, always the final parameter.
38
+ * @returns the notes this Agent's session owns.
39
+ */
40
+ @Remote('list')
41
+ async remoteExportList(agent: Agent, signal: AbortSignal): Promise<NoteRow[]> {
42
+ return await this.list(agent, signal)
43
+ }
44
+
45
+ /** The in-process API the adapter above delegates to, unchanged by it. */
46
+ async list(agent: Agent, signal: AbortSignal): Promise<NoteRow[]> {
47
+ signal.throwIfAborted()
48
+ return await Promise.resolve([{ noteId: `${agent.id}-1`, title: 'draft' }])
49
+ }
50
+ }
51
+ ```
52
+
53
+ ## 2. Declare the failures
54
+
55
+ A Remote failure is one class, `RemoteError`: merge the domain codes into `RemoteErrorDetailsMap` through declaration merging and `throw new RemoteError(code, message, details)` at the failure point. Do not build a family of domain error classes, and do not write an exit-mapping function; an exception unrelated to this endpoint is not pre-classified, because the Gateway folds it into `gateway/internal`. Write a `catch` only to classify an arbitrary provider exception as one domain code, and attach the original exception as `cause`.
56
+
57
+ A code reads `<domain>/<reason>`, and its declaration has four placement rules:
58
+
59
+ - One producer only: declare it in the producing package, next to the throw.
60
+ - Several packages produce it: declare it in the lowest domain package both depend on (`session/not-found` in `core/session`, `workspace/not-found` in `dsh-workspace`).
61
+ - The carrier codes `gateway/bad-request`, `gateway/cancelled`, and `gateway/internal` are declared in protocol, and the Gateway infrastructure codes in gateway - use them, never copy them.
62
+ - A local failure that never crosses the wire stays out of the code table; express it with the caller's own type.
63
+
64
+ ```ts
65
+ import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
66
+
67
+ declare module '@deepseek-ai/dsh-typert-protocol' {
68
+ interface RemoteErrorDetailsMap {
69
+ /** No stored note carries that id. */
70
+ 'note/not-found': { readonly noteId: string }
71
+ /** The store refused an otherwise valid write. */
72
+ 'note/rejected': { readonly noteId: string }
73
+ }
74
+ }
75
+
76
+ declare const stored: ReadonlyMap<string, string>
77
+ declare function persist(noteId: string, title: string): Promise<void>
78
+
79
+ export async function rename(noteId: string, title: string): Promise<void> {
80
+ if (!stored.has(noteId)) {
81
+ throw new RemoteError('note/not-found', `no note "${noteId}"`, { noteId })
82
+ }
83
+ try {
84
+ await persist(noteId, title)
85
+ } catch (error: unknown) {
86
+ const message = error instanceof Error ? error.message : String(error)
87
+ throw new RemoteError('note/rejected', message, { noteId }, { cause: error })
88
+ }
89
+ }
90
+ ```
91
+
92
+ ## 3. Register it on the package
93
+
94
+ `@Remote` must live in a Loader entry plugin package; when the owner is an abstract seam, the controller goes in the matching package under `packages/api/`. The manifest gains the two generated entries and the protocol peer dependency, while on the Client side the `@deepseek-ai/dsh-api-remotes` assembly mounts the contribution and re-exports the type vocabulary that consumers need. Which generated artifact each entry points at, and how the generation pipeline is ordered, are in the [API Gateway reference](../api-gateway.md).
95
+
96
+ ```json
97
+ {
98
+ "exports": {
99
+ "./typert": { "types": "./lib/typert.host.d.ts", "default": "./lib/typert.host.js" },
100
+ "./remote": { "types": "./lib/typert.remote-client.d.ts", "default": "./lib/typert.remote-client.js" }
101
+ },
102
+ "peerDependencies": { "@deepseek-ai/dsh-typert-protocol": "workspace:*" },
103
+ "devDependencies": { "@deepseek-ai/dsh-typert-protocol": "workspace:*" }
104
+ }
105
+ ```
106
+
107
+ Rerun `pnpm run build:lib` after changing a signature, the code table, the namespace, or an export name, because that is what hands the Client its new declarations and codecs; changing only an implementation body needs no regeneration.
108
+
109
+ ## 4. Consume it on the Client
110
+
111
+ The calling plugin declares both `remote` and `remote.<namespace>` in its `inject`, and the call site writes `ctx.remote.<namespace>.<method>(...)` directly: no `Pick<ClientRemote, …>` narrowing, no hand-written method signature, no wire relay object. The result is a `RemoteResult<T>`, so branch on `if (!result.ok)` in place and discriminate by `code` rather than `instanceof` - a code branch narrows `details` on its own. An exception-flow site writes `throw result.error` (it is a real Error); whoever catches it uses `isRemoteFailure` to tell a Remote failure from a local defect and rethrows the defect. Do not write a defensive catch: a Remote call does not reject, and an assembly mistake should crash.
112
+
113
+ Fixed Host facts come from `ctx.remote.$host`: `home` and `isLoopback` are plain reads with no subscription and no generation counter, and `home` is `undefined` until the first ready frame. Refresh after a reconnect through `ctx.on('connection/reset')` or a domain's own remote event. When the caller aborts a unary call, the outcome is `gateway/cancelled` on the error branch rather than a throw.
114
+
115
+ ```ts ignore-check
116
+ import type { Context } from '@deepseek-ai/cordis'
117
+ import { isRemoteFailure } from '@deepseek-ai/dsh-api-gateway/client'
118
+ import type {} from '@deepseek-ai/dsh-api-remotes/client'
119
+
120
+ export const inject = ['remote', 'remote.notes']
121
+
122
+ declare const ctx: Context
123
+
124
+ /** Store-side read: the error branch is handled where the code is meaningful. */
125
+ export async function noteTitles(): Promise<readonly string[]> {
126
+ const result = await ctx.remote.notes.list()
127
+ if (!result.ok) {
128
+ if (result.error.code === 'note/not-found') return []
129
+ throw result.error
130
+ }
131
+ return result.value.map(row => row.title)
132
+ }
133
+
134
+ /** Action-side: a Remote failure becomes copy; a local fault keeps crashing. */
135
+ export async function renderTitles(): Promise<string> {
136
+ try {
137
+ return (await noteTitles()).join(', ')
138
+ } catch (error: unknown) {
139
+ if (!isRemoteFailure(error)) throw error
140
+ return `unavailable (${error.code})`
141
+ }
142
+ }
143
+
144
+ /** Fixed Host facts as plain reads. */
145
+ export function hostLabel(): string {
146
+ const { home, isLoopback } = ctx.remote.$host
147
+ return home ?? (isLoopback ? 'local host' : 'remote host')
148
+ }
149
+ ```
150
+
151
+ ## 5. Test it
152
+
153
+ On the owner side, assert the code that was thrown: recover the failure with `remoteErrorOf` after catching, then compare `code` and the details fields you care about with `toMatchObject` - never deep-compare the error object with `toEqual`, and never assert `instanceof`.
154
+
155
+ ```ts
156
+ import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'
157
+ import { expect, it } from 'vitest'
158
+
159
+ declare function rename(noteId: string, title: string): Promise<void>
160
+
161
+ it('refuses an unknown note before writing', async () => {
162
+ const failure = await rename('n-404', 'fresh title').catch((error: unknown) => error)
163
+
164
+ expect(remoteErrorOf(failure)).toMatchObject({
165
+ code: 'note/not-found',
166
+ details: { noteId: 'n-404' },
167
+ })
168
+ })
169
+ ```
170
+
171
+ A Client-side double returns real instances: take the `RemoteError` and `TestRemote` value imports from `@deepseek-ai/dsh-client-test-runtime`, because a value import from the `api-remotes` facade would load the unbuilt assembly chain. `TestRemote.$host` is a plain field a spec assigns directly.
172
+
173
+ ```ts ignore-check
174
+ import { Context } from '@deepseek-ai/cordis'
175
+ import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
176
+ import { expect, it } from 'vitest'
177
+
178
+ it('renders the failure code the Host reported', async () => {
179
+ const ctx = new Context()
180
+ const remote = new TestRemote(ctx, {
181
+ notes: {
182
+ list: () => Promise.resolve({
183
+ ok: false as const,
184
+ error: new RemoteError('note/not-found', 'no note "n-404"', { noteId: 'n-404' }),
185
+ }),
186
+ },
187
+ })
188
+ remote.$host = { home: '/home/fixture', isLoopback: true }
189
+
190
+ await expect(ctx.remote.notes.list()).resolves.toMatchObject({ error: { code: 'note/not-found' } })
191
+ })
192
+ ```
193
+
194
+ ## Verify
195
+
196
+ 1. `pnpm run build:lib`: mandatory once a signature, the code table, the namespace, or an export name changed, because it produces the Client declarations and codecs.
197
+ 2. `pnpm run typecheck`: both the Host and the Client program, where a code merged into an unreachable package turns red.
198
+ 3. Run both sides' specs by name: `npx vitest run <owner spec> <client spec>`.
199
+ 4. Add a recorded-session snapshot when the endpoint reaches a product-visible surface, per the [testing policy](../testing.md).
@@ -0,0 +1,74 @@
1
+ <!-- Synced from deepseek-harness:docs/cookbook/adding-a-settings-card.md @ 639ed01539. Do not edit; run scripts/sync-corpus.mjs. Relative links inside may not resolve here. -->
2
+
3
+ # Cookbook: live configuration forms
4
+
5
+ English | [中文](adding-a-settings-card.zh.md)
6
+
7
+ Declare live fields in the plugin Config schema and expose them through a product-owned settings card. The exported `Config` interface describes the values received by the plugin, including each `Volatile<T>` reference.
8
+
9
+ ## 1. Declare live fields
10
+
11
+ ```ts
12
+ import type { Context, Volatile } from '@deepseek-ai/cordis'
13
+ import z from '@deepseek-ai/schemastery'
14
+
15
+ export interface Config {
16
+ endpoint: Volatile<string | undefined>
17
+ retries: Volatile<number>
18
+ }
19
+
20
+ export const Config = z.object({
21
+ endpoint: z.string().volatile(),
22
+ retries: z.number().step(1).min(0).default(3).volatile(),
23
+ })
24
+
25
+ export function apply(ctx: Context, config: Config): void {
26
+ ctx.on('loader/volatile-update', () => {
27
+ ctx.logger.info('Retry limit: %d', config.retries.get())
28
+ })
29
+ }
30
+ ```
31
+
32
+ Read `.get()` when starting an operation. A request that needs a consistent snapshot captures its values once. Use `.check()` for cross-field Config validation; these checks run on the Host before persistence and are omitted from serialized form schemas.
33
+
34
+ ## 2. Compose the plugin
35
+
36
+ Give each instance a unique profile entry id. The base bundle mounts settings and config-editor. For custom profiles, see their package READMEs before mounting the same services.
37
+
38
+ `role('secret')` keeps a value out of form responses. Use credential references for values managed by the credentials domain. Ordinary fields stay out of the settings schema.
39
+
40
+ ## 3. Verify editing
41
+
42
+ Change a field in Plugins and save. Verify the profile patch, the next consumer operation, unchanged plugin instance identity, and restoration after restart. Reject an invalid value and verify that neither the file nor the live value changed.
43
+
44
+ Custom plugin pages receive `form.state` and `form.mutate(operations, expectedRevision)` from the Plugins page owner. The Host validates full Config and applies edits through ConfigEditor and volatile HMR. The [plugin settings package](../../packages/client/ui-settings-plugins/README.md) owns the existing card examples.
45
+
46
+ ## 4. Contribute to another plugin's page
47
+
48
+ A plugin with something to say about a bundle, a row, or an official plugin it does not own registers into `plugins.detail.actions` (a control at the head of the page), `plugins.detail.badge` (a tag beside the title), or `plugins.detail.section` (a section under the page's own content). Every entry is rendered with the page's `subject` - `{ kind: 'bundle', pkg }`, `{ kind: 'row', pkg, row }`, or `{ kind: 'item', id }` - and returns null for a subject it has nothing for:
49
+
50
+ ```tsx ignore-check
51
+ ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({
52
+ name: 'plugins.detail.badge',
53
+ id: 'acme-update',
54
+ locale: 'acmeUpdate',
55
+ }, ({ t, subject }) => subject.kind === 'bundle' && hasUpdate(subject.pkg) ? <Tag tone="info">{t('update')}</Tag> : null))
56
+ ```
57
+
58
+ ## 5. Where the browser half rides
59
+
60
+ The browser half is served to the page by the [client module system](../../packages/client/modules), which scans the enabled Loader entries for packages declaring `dsh.client` and serves each one's built `./client` export - but it attaches a package's half to the Loader row whose specifier is the bare package name. A row mounted from a subpath export never carries a half, so a bundle that splits one package into several rows keeps its half on the root row, and every page it registers goes away when that row is switched off. A sub-plugin whose page must outlive the other rows ships as its own package.
61
+
62
+ The built `./client` file must be in the client module system's lazy-CJS factory format: one script that registers the package name and a `factory(require)` with the page's module loader, described in the [client module system's README](../../packages/client/modules/README.md). The `clientBundle` tsdown preset that emits it lives in `packages/client/tsdown.client.ts` rather than in a published package, so a package outside this repository reproduces that build itself.
63
+
64
+ ```jsonc
65
+ {
66
+ "exports": {
67
+ ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" },
68
+ "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }
69
+ },
70
+ "dsh": { "client": { "platform": "web", "inject": ["@deepseek-ai/dsh-client-ui-settings"] } }
71
+ }
72
+ ```
73
+
74
+ A companion package for a built-in namespace is the same browser half in a client-only package with an empty Host `apply`, listed in the web composition's plugin roster ([`packages/bundle/web-app/cordis.patch.yml`](../../packages/bundle/web-app/cordis.patch.yml)) and registering into `plugins.item` through `ctx.configForms.whileServed`, so the page exists exactly while the Host serves the namespace.
@@ -0,0 +1,103 @@
1
+ <!-- Synced from deepseek-harness:docs/cookbook/adding-a-tool.md @ 639ed01539. Do not edit; run scripts/sync-corpus.mjs. Relative links inside may not resolve here. -->
2
+
3
+ # Tool authoring reference
4
+
5
+ English | [中文](adding-a-tool.zh.md)
6
+
7
+ Reference for the contracts a model-facing tool must satisfy. For an ordered first tool, follow [Build a tool](../user/develop/basic/tool.md). `packages/shell/tool-bash` is the production-grade three-package example.
8
+
9
+ ## The minimal shape
10
+
11
+ ```ts
12
+ import { readFile } from 'node:fs/promises'
13
+ import type { Context } from '@deepseek-ai/cordis'
14
+ import { defineTool } from '@deepseek-ai/dsh-tools'
15
+
16
+ export const name = 'my-tool'
17
+ export const inject = ['tools']
18
+
19
+ export function apply(ctx: Context) {
20
+ ctx.tools.register(defineTool({
21
+ name: 'read_file',
22
+ description: 'Read a file from disk.', // what the model sees
23
+ parameters: {
24
+ path: { type: 'string', required: true, description: 'Absolute path' },
25
+ limit: { type: 'number' }, // optional by default
26
+ },
27
+ output: {
28
+ schema: { type: 'string' },
29
+ render: (_args, value) => [{ type: 'text', text: value }],
30
+ },
31
+ async execute(args, exec) {
32
+ // args is TYPED from the schema: { path: string; limit?: number }
33
+ // exec carries immutable identity + token; signal is the operational field
34
+ return readFile(args.path, { encoding: 'utf8', signal: exec.signal })
35
+ },
36
+ }))
37
+ }
38
+ ```
39
+
40
+ Registration is effect-based: disposing the plugin fiber unregisters the tool. Schemas flow into the system-prompt assembly automatically.
41
+
42
+ ## Rules of the execute() contract
43
+
44
+ - **Args are validated for you.** `defineTool` validates model-generated `arguments` against the unified `ParameterSchemaSpec` before `execute` runs (types, required keys, literal constraints, exact-one unions, and nested values), so inside `execute` the args match `InferArgs`. Explicit object nodes declare `additionalProperties: true | false`; the implicit parameter root stays open. You still hand-check constraints the DSL does not express, such as non-empty strings, positive numbers, or cross-field rules. Raw JSON-Schema tools registered directly own their input validation.
45
+ - **Registration borrows your readonly definition.** A typed same-process contribution is not a serialization boundary; do not mutate its schema or replace callbacks after registration. `schemas()` materializes only the explicit model-facing projection. To hot-swap a tool, dispose its owning effect and register the replacement; mutable state inside the callback's closure remains ordinary plugin state.
46
+ - **Execution identity is protected.** The registry materializes `arguments` as detached lossless JSON in one recursive pass, freezes that value before policy starts, and assigns an opaque `exec.token`; `callId`, `name`, `arguments`, `agent`, `token`, the required caller-owned `signal`, and an optional enclosing-transport `parent` token stay immutable through dispatch. `parent` is identity-only and exposes no live outer execution. Treat `args` as readonly input. Only an around-dispatch wrapper receives a mutable view, and it may replace and restore the required `exec.signal` to impose a deadline but cannot remove it.
47
+ - **Declare and return one canonical JSON value.** `output.schema` uses `ValueSchemaSpec` and may have an object, array, scalar, or null root. `execute` returns only the inferred value; the registry snapshots it as lossless JSON, validates it, freezes it, and passes it to `output.render(args, value)`. Do not return content blocks from the body or make callers parse prose for ids and fields.
48
+ - **Throwing or returning an invalid value means `isError`.** The registry catches throws and contains schema, renderer, metadata-projector, and lossless-JSON failures before observers run. Throw for infrastructure failures. Represent a successful domain outcome in the canonical value even when its Native renderer explains a non-ideal state, such as a non-zero process exit.
49
+ - **Honor `exec.signal`.** Cancel in-flight work when it fires.
50
+ - **Project durable card data with `presentationMeta` (optional).** `output.presentationMeta(args, value)` derives replayable JSON from the same canonical value. The core persists it on `tool/result` and hands it to `presentResult`, so a card that needs result-time facts-such as `write`/`edit` applied hunks-survives replay without persisting the canonical value. The projector is skipped for nested Code dispatches because they have no cards.
51
+ - **Use `exec.agent` for async notifications.** `agent.inject({ content, source: { kind: 'plugin', plugin: '<name>' } })` appends durable context the NEXT model request sees - it is not a wake-up (an idle agent stays idle). Guard against disposed agents (try/catch).
52
+
53
+ ## Long-running work
54
+
55
+ Gate `run_in_background` with producer config, then register through `ctx.jobs.start({ kind, label, owner: exec.agent, run })`. The registry rejects a pre-aborted invocation before the producer body; the runtime validates ownership and task-controller availability before `run()` starts work, then supplies the id, session fence, generic control tools, notices, and owner cleanup. A successful background branch returns a typed canonical handle such as `{ kind: 'background', jobId }`; its Native renderer may keep human prose such as `started background job bash-1`, but PTC mode must never parse that prose to recover the id.
56
+
57
+ The spec supplies synchronous `cancel`, a non-rejecting `done` that settles after resource cleanup, and either pull `output` sources the registry pumps into the job's output ring or pushes through the `JobHandle` its starter receives; `dsh-tool-jobs` renders the model's consuming read from that ring. A pre-aborted call is a failure because no task exists whose id could satisfy the successful output schema. Once `ctx.jobs.start()` publishes the id, use a task-owned cancellation signal rather than `exec.signal`: later outer-call cancellation stops waiting for the call but does not kill published work; `job_kill`, owner disposal, and service teardown own that lifetime. Foreground work remains coupled to `exec.signal`. See the [background job runtime Agent Note](../../.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md) and `dsh-tool-bash` for a stream producer.
58
+
59
+ ## Execution policy and observation
60
+
61
+ Prefer not to build deployment policy into the tool. Use `tools/pre-execute` for extensible allow/deny/ask policy (the [permission-gate example](extension-cookbook.md#a-hook-plugin-permission-gate-example)), `ctx.tools.guard()` for a final monotonic deny that later listeners cannot undo, `tools/execute` to wrap dispatch with a deadline, retry, or metrics collection, `tools/post-execute` to replace presentation content or the returned value, block the result, or attach model-facing context, and `tools/result` to observe the immutable normalized outcome. A content replacement leaves programmatic access to `value` intact; confidentiality policy blocks or replaces the value. A sandboxing implementation can also run inside the tool's executor implementation; the [`dsh-tools` README](../../packages/core/tools/README.md#extension-points) defines each extension point's inputs, order, return values, and failure behavior.
62
+
63
+ ## PTC mode reaches your tool for free
64
+
65
+ In [PTC mode](../../packages/core/tools/README.md), every visible registered tool is available as `await tools.<name>(args)` without extra integration. The generated `ToolArgsMap` and `ToolOutputMap` derive exact argument and canonical-return types from the same schemas, and calls re-enter the normal execution pipeline. A successful call resolves to the final canonical JSON value after policy, not to rendered Native content. A failed call rejects with the real `ToolCallError`; programs can inspect only its `name`, `toolName`, and human-readable `message`, not internal error codes or a failure union.
66
+
67
+ Design `output.schema` as a useful programmatic API: return handles and fields directly, allow scalar/array/null roots when they are the honest value, and keep human explanation in `output.render`. Intermediate values are execution-local, are not persisted or prompt-truncated, and have no byte cap, so the producer's truthful acquisition bounds and process memory still matter. Only the outer `run_code` logs/result cross the configurable output cap and model-facing spill pipeline.
68
+
69
+ ## How your tool renders in a UI
70
+
71
+ Your tool's `output.render` returns model-facing content; its **UI card** is a separate concern declared through pure presentation projections and optional `presentCall` / `presentResult` methods. Design these alongside the canonical value. A tool with no UI presentation falls back to a generic card (title = tool name, raw args as input).
72
+
73
+ Both methods return a **`card`-tagged render intent** - pick the card kind that matches what your tool does:
74
+
75
+ - `presentCall(args)` → a `ToolCallView` (the PENDING card):
76
+ - `{ card: 'generic', title, kind?, rawInput?, content?, locations? }` - the default. Set `kind` for an icon (`read`/`search`/…); set `locations: [{ path, line? }]` for any file your tool touches so a capable editor follows along / jumps to it.
77
+ - `{ card: 'terminal', title, description?, cwd? }` - your call IS a shell command. `title` is the command, `description` renders above the terminal card. (tool-bash.)
78
+ - `{ card: 'diff', title, diffs, locations? }` - your call creates or modifies a file. `diffs: [{ path, oldText, newText }]` (`oldText: null` for a new file) renders as an inline diff card. (tool-fs `write`/`edit`.)
79
+ - `presentResult(args, { content, isError, meta? })` returns the completed card:
80
+ - `generic` supplies an optional title and content.
81
+ - `terminal` supplies raw output and optional exit metadata; each UI renders its capable or fallback view.
82
+ - `diff` supplies applied hunks, often derived by `output.presentationMeta` and carried in persisted `result.meta` so replay reproduces them. Mutation tools keep a diff result because the completed view replaces the pending card.
83
+ - `read` supplies a completed file window reconstructed from persisted `result.meta`: the file `path`, a 1-based `offset`, the returned `lines` (each keeping its file line number), `totalLines`, and an optional `lang` highlight hint; a UI without the `read` capability falls back to the raw result content. There is no `read` call view - a read call's pending state stays a generic card, since content exists only after `execute`. (tool-fs `read`.)
84
+ - `search` supplies a discovery result reconstructed from persisted `result.meta`: grouped-by-file matches (`shape: 'matches'`, grep) or a flat path list (`shape: 'paths'`, glob), plus `truncated`/`total` so a UI never presents a capped result as complete. The view carries no result text (a UI without a search card falls back to the raw result content), and there is no `search` call view - a discovery call's pending state stays a generic card, since matches exist only after `execute`. (tool-fs-search `grep`/`glob`.)
85
+ - `web` supplies a completed web retrieval, discriminated by `kind: 'search' | 'fetch'` (the structured search sources or the fetch summary), derived from `result.meta`; it carries no body copy, so a UI without the `web` capability falls back to the raw result content. (tool-web `web_search`/`web_fetch`.)
86
+
87
+ Hard rules (they bite if broken):
88
+
89
+ - **Purity.** These run on live streaming AND on session-log REPLAY, so they must be pure functions of `args` (+ the result) - NO I/O, NO reading session state, NO clock/random. A diff is derived from the args (`write` uses `oldText: null` because a call-time presenter has no prior file content); the UI adapter, not the tool, supplies session context. If you find yourself wanting the file's old content or the working directory inside `presentCall`, stop - that belongs in durable result metadata or the adapter, not the presenter.
90
+ - **UI-only formatting stays out of the model result.** A fenced ` ```console ` block, a diff, a relativized path-none of these belongs in the canonical value or Native content merely to serve a UI. `output.render` owns model-facing prose; `presentationMeta` plus the card presenters own replayable UI state. A `terminal` result view carries raw output and the adapter adds any fallback framing.
91
+ - **`defineTool` soft-validates the display path.** Malformed or older logged arguments make the wrapper return `undefined` (a generic fallback) rather than throw - display must never crash a replay.
92
+
93
+ The neutral vocabulary lives in `dsh-tools`; tools never import a UI or transport type. Consumers of this API map each `card` into their own view. The design and the why are in [the render-intent-union Agent Note](../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md); `dsh-tool-fs` (generic/diff) and `dsh-tool-bash` (terminal) are the reference implementations.
94
+
95
+ ## Web Client presentation
96
+
97
+ The built-in Web Client does not consume `presentCall` or `presentResult`. Session `page` and `follow` transport raw `tool/call` and `tool/result` events, including persisted `result.meta`. A Client plugin registers its wire tool name in the `tool.call.toolview` keyed slot and derives component props from the `ToolCallBlock` arguments, content, error, metadata, existing PTC dispatch `parentCallId`, and Session path facts. It validates these wire values locally and returns the generic row for malformed or unsupported input.
98
+
99
+ Use `output.presentationMeta(args, value)` when an existing Web card needs bounded structured result facts that model-facing content cannot preserve losslessly. Do not store React props or a selected card in metadata, import a Host tool implementation into a browser bundle, or create another Client presenter registry. Defining Host presentation methods alone does not add a specialized Web card. The [Client-derived presentation Agent Note](../../.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md) defines ownership, fallback, and equivalence requirements.
100
+
101
+ ## Verification
102
+
103
+ Follow the [repository testing policy](../testing.md) and the owning package's test documentation. A shipped model- or UI-visible change requires the assembled coverage specified there.
@@ -0,0 +1,45 @@
1
+ <!-- Synced from deepseek-harness:docs/cookbook/adding-an-llm-adapter.md @ 639ed01539. Do not edit; run scripts/sync-corpus.mjs. Relative links inside may not resolve here. -->
2
+
3
+ # Cookbook: adding an LLM adapter
4
+
5
+ English | [中文](adding-an-llm-adapter.zh.md)
6
+
7
+ How to connect a new model provider. Reference implementations: `packages/llm/llm-deepseek` (direct HTTP, SSE framed by `eventsource-parser`) and `packages/llm/llm-pi-ai` (wrapping an LLM library). Read the `StreamChunk` doc in `packages/llm/llm/src/types.ts` first - it records the protocol conventions both adapters were verified against.
8
+
9
+ ## The shape
10
+
11
+ ```ts ignore-check
12
+ class MyAdapter extends LlmAdapter {
13
+ async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> { … }
14
+ }
15
+
16
+ export const name = 'llm-myprovider'
17
+ export const inject = ['llm']
18
+ export const Config: z<Config> = z.object({ apiKey: z.string(), … })
19
+
20
+ export function apply(ctx: Context, config: Config) {
21
+ ctx.llm.registerAdapter(['my-provider'], new MyAdapter(…))
22
+ }
23
+ ```
24
+
25
+ Registration is effect-based (HMR-safe); one adapter per provider route - duplicates throw, and multi-route registration is all-or-nothing. `options.provider` selects the adapter and `options.model` is the provider model id, so a dynamic catalog adapter can serve new models without lifecycle reconfiguration. Secrets are cordis-native: schemastery Config with env fallbacks, fed from cordis.yml via `!!js process.env.MY_KEY`. Never read ad-hoc key files in code.
26
+
27
+ ## Protocol obligations (the contract two implementations verified)
28
+
29
+ - Emit `usage` BEFORE `finish`; emit NOTHING after `finish`. The robust way: buffer finish/usage until the provider's end-of-stream marker, then flush (handles providers that send trailing usage-only chunks).
30
+ - Tool-call `arguments` are RAW JSON strings end-to-end; stream fragments as `argumentsDelta`. If your provider hands back parsed objects, re-stringify at `block-end`.
31
+ - Allocate block `index`es in first-seen stream order; reuse the index for every delta of the same block.
32
+ - Errors have exactly two sanctioned paths: THROW from `stream()` (transport and protocol failures - use `LlmError` with a stable code), or end the stream with `finish {kind: 'error' | 'aborted'}` (provider in-band failures). Consumers handle both; pick per failure class and document it.
33
+ - Honor `options.signal` (pass it to fetch / your SDK).
34
+ - A `GenerateOptions` field your provider cannot honor (e.g. a `stop` list on a provider without stop sequences): throw `LlmError(..., 'UNSUPPORTED_OPTION')` rather than silently dropping it.
35
+ - If the provider requires response ids, signatures, or other native metadata on follow-up calls, emit the minimal lossless-JSON projection as `finish.replayState`. Validate it when rebuilding history. `LlmRuntime` passes it only when the historical provider route and target provider route are currently owned by the exact same adapter instance; your adapter decides whether same-model, cross-model, or cross-provider restoration is legal. Never infer native replay from provider/model names alone when state is absent.
36
+
37
+ Provider-specific thinking-mode toggles remain in the adapter's Config. Exact model metadata uses one provider-neutral capability seam: implement `resolveModel()` with provider/model identity and optional `context` and `reasoning` fields, declare a configured `defaultEffort` only when one exists, and honor the resolver's optional `AbortSignal`. Reasoning efforts are ordered opaque ids mapped to provider requests by the adapter. Preserve the adapter's authoritative selectable list, including an adapter-defined `off` when supported, without exposing final wire spellings or clamping unsupported values; an id need not equal its wire representation.
38
+
39
+ ## Implementation structure
40
+
41
+ Keep wire types, request serialization, transport parsing, chunk translation, and the adapter class as separate responsibilities; [`llm-deepseek`](../../packages/llm/llm-deepseek/README.md) is the reference layout.
42
+
43
+ ## Verification
44
+
45
+ Follow the [repository testing policy](../testing.md), which owns adapter coverage, real-provider checks, and published-entry requirements.