stitchkit 0.136.8 → 0.137.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 (342) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/agent-runtime/stores/branch-observations.d.ts +19 -19
  3. package/dist/agent-runtime/stores/schedule-contract.d.ts.map +1 -1
  4. package/dist/agent-runtime/stores/schedule-records.d.ts.map +1 -1
  5. package/dist/agent-runtime/stores/schedule-tools.d.ts.map +1 -1
  6. package/dist/agent-runtime/stores/sql-rows.d.ts +36 -36
  7. package/dist/agent-runtime/terminal-commit.d.ts +5 -5
  8. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts +52 -52
  9. package/dist/agent-runtime/testing/store-conformance-support.d.ts +26 -26
  10. package/dist/browser/client-executors.d.ts +2 -3
  11. package/dist/browser/client-executors.d.ts.map +1 -1
  12. package/dist/browser/realtime-client.d.ts +6 -1
  13. package/dist/browser/realtime-client.d.ts.map +1 -1
  14. package/dist/browser/socket-io-client.d.ts.map +1 -1
  15. package/dist/browser/socket-io-contract.d.ts +2 -0
  16. package/dist/browser/socket-io-contract.d.ts.map +1 -1
  17. package/dist/contract/define-validation.d.ts +6 -0
  18. package/dist/contract/define-validation.d.ts.map +1 -1
  19. package/dist/contract/define.d.ts +1 -1
  20. package/dist/contract/define.d.ts.map +1 -1
  21. package/dist/contract/error-mapping.d.ts +71 -0
  22. package/dist/contract/error-mapping.d.ts.map +1 -0
  23. package/dist/contract/errors.d.ts +8 -0
  24. package/dist/contract/errors.d.ts.map +1 -1
  25. package/dist/contract/factory.d.ts +8 -0
  26. package/dist/contract/factory.d.ts.map +1 -1
  27. package/dist/contract/fragments.d.ts +45 -0
  28. package/dist/contract/fragments.d.ts.map +1 -0
  29. package/dist/contract/normalize.d.ts +6 -3
  30. package/dist/contract/normalize.d.ts.map +1 -1
  31. package/dist/contract/operation-read.d.ts +38 -0
  32. package/dist/contract/operation-read.d.ts.map +1 -0
  33. package/dist/contract/stream.d.ts.map +1 -1
  34. package/dist/contract/time-zone.d.ts +31 -0
  35. package/dist/contract/time-zone.d.ts.map +1 -0
  36. package/dist/contract/tool-options.d.ts +1 -1
  37. package/dist/contract/tool-options.d.ts.map +1 -1
  38. package/dist/device-relay/hub.d.ts +1 -1
  39. package/dist/device-relay/hub.d.ts.map +1 -1
  40. package/dist/entrypoints/agent-executor/acp.js +9 -9
  41. package/dist/entrypoints/agent-executor/claude-sdk.js +11 -11
  42. package/dist/entrypoints/agent-executor/claude.js +8 -8
  43. package/dist/entrypoints/agent-executor/codex.js +15 -15
  44. package/dist/entrypoints/agent-executor/testing.js +11 -11
  45. package/dist/entrypoints/agent-executor.js +14 -13
  46. package/dist/entrypoints/agent-runtime/ai-sdk.js +5 -5
  47. package/dist/entrypoints/agent-runtime/anthropic.js +1 -1
  48. package/dist/entrypoints/agent-runtime/browser.js +5 -5
  49. package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
  50. package/dist/entrypoints/agent-runtime/harness.js +14 -15
  51. package/dist/entrypoints/agent-runtime/openai.js +1 -1
  52. package/dist/entrypoints/agent-runtime/openrouter.js +7 -7
  53. package/dist/entrypoints/agent-runtime/postgres.js +5 -5
  54. package/dist/entrypoints/agent-runtime/realtime.js +8 -8
  55. package/dist/entrypoints/agent-runtime/sandbox.js +7 -7
  56. package/dist/entrypoints/agent-runtime/sqlite/bun.js +6 -6
  57. package/dist/entrypoints/agent-runtime/sqlite/node.js +6 -6
  58. package/dist/entrypoints/agent-runtime/testing.js +5 -5
  59. package/dist/entrypoints/agent-runtime.js +33 -29
  60. package/dist/entrypoints/application/diagnostic-journal.js +3 -3
  61. package/dist/entrypoints/application/directory-inbox.js +1 -1
  62. package/dist/entrypoints/application/grammy.js +1 -1
  63. package/dist/entrypoints/application/opentelemetry.js +2 -2
  64. package/dist/entrypoints/application.js +10 -10
  65. package/dist/entrypoints/cli/publish.js +8 -8
  66. package/dist/entrypoints/cli.d.ts +2 -0
  67. package/dist/entrypoints/cli.d.ts.map +1 -1
  68. package/dist/entrypoints/cli.js +518 -59
  69. package/dist/entrypoints/contract.d.ts +5 -1
  70. package/dist/entrypoints/contract.d.ts.map +1 -1
  71. package/dist/entrypoints/contract.js +25 -7
  72. package/dist/entrypoints/device-relay.js +20 -10
  73. package/dist/entrypoints/files/packaging.js +2 -2
  74. package/dist/entrypoints/files.js +10 -10
  75. package/dist/entrypoints/handler.d.ts +1 -1
  76. package/dist/entrypoints/handler.d.ts.map +1 -1
  77. package/dist/entrypoints/handler.js +12 -12
  78. package/dist/entrypoints/http.js +13 -12
  79. package/dist/entrypoints/index.js +36 -18
  80. package/dist/entrypoints/live.d.ts +2 -1
  81. package/dist/entrypoints/live.d.ts.map +1 -1
  82. package/dist/entrypoints/live.js +630 -1
  83. package/dist/entrypoints/node.d.ts +5 -0
  84. package/dist/entrypoints/node.d.ts.map +1 -1
  85. package/dist/entrypoints/node.js +36 -16
  86. package/dist/entrypoints/observability.js +25 -10
  87. package/dist/entrypoints/postgres.d.ts +1 -0
  88. package/dist/entrypoints/postgres.d.ts.map +1 -1
  89. package/dist/entrypoints/postgres.js +66 -0
  90. package/dist/entrypoints/primitives.js +11 -4
  91. package/dist/entrypoints/process.js +7 -7
  92. package/dist/entrypoints/react.js +1 -1
  93. package/dist/entrypoints/realtime.js +3 -3
  94. package/dist/entrypoints/remote.js +6 -29
  95. package/dist/entrypoints/server.d.ts +6 -1
  96. package/dist/entrypoints/server.d.ts.map +1 -1
  97. package/dist/entrypoints/server.js +93 -32
  98. package/dist/entrypoints/service-host/macos.js +6 -6
  99. package/dist/entrypoints/service-host/work.js +6 -6
  100. package/dist/entrypoints/service-host.js +10 -10
  101. package/dist/entrypoints/spend.js +2 -1
  102. package/dist/entrypoints/sync.js +5 -5
  103. package/dist/entrypoints/telegram.js +8 -8
  104. package/dist/entrypoints/testing.d.ts +1 -0
  105. package/dist/entrypoints/testing.d.ts.map +1 -1
  106. package/dist/entrypoints/testing.js +1501 -13
  107. package/dist/entrypoints/tools/agent.js +6 -7
  108. package/dist/entrypoints/tools/connections.js +9 -11
  109. package/dist/entrypoints/tools/contract.js +1 -2
  110. package/dist/entrypoints/tools/invoker.js +4 -5
  111. package/dist/entrypoints/tools/mcp.js +10 -11
  112. package/dist/entrypoints/tools/toolkit.d.ts +1 -1
  113. package/dist/entrypoints/tools/toolkit.d.ts.map +1 -1
  114. package/dist/entrypoints/tools/toolkit.js +29 -24
  115. package/dist/entrypoints/tools.js +28 -30
  116. package/dist/entrypoints/tracking/contract.js +2 -1
  117. package/dist/entrypoints/xlsx.js +5 -8
  118. package/dist/{index-033tyx59.js → index-0zw0hcyg.js} +4 -1
  119. package/dist/{index-zcq3dby3.js → index-1bjwfnnj.js} +1 -1
  120. package/dist/{index-3zt0r4y0.js → index-1cfacbe2.js} +4 -4
  121. package/dist/{index-gj4wdts6.js → index-1ckh9qx1.js} +1 -1
  122. package/dist/index-1pvwmbxp.js +1435 -0
  123. package/dist/{index-0s75mjh7.js → index-2e4hdh32.js} +1 -1
  124. package/dist/{index-3shdhzt6.js → index-2j0pqxkn.js} +12 -6
  125. package/dist/index-3k8w02se.js +28 -0
  126. package/dist/{index-7fjbdga8.js → index-3pb4ccj2.js} +8 -0
  127. package/dist/{index-w7e402wx.js → index-48kb4gqq.js} +46 -7
  128. package/dist/{index-cv9b7fz2.js → index-6rws2xf5.js} +8 -0
  129. package/dist/{index-bbpygynk.js → index-77w5vx0g.js} +1 -1
  130. package/dist/index-7dz1ngaf.js +35 -0
  131. package/dist/{index-y68gavb5.js → index-7n4atsm4.js} +1 -1
  132. package/dist/index-8ef1bfea.js +71 -0
  133. package/dist/{index-0x4mnwg5.js → index-8k3y9nd4.js} +6 -9
  134. package/dist/{index-ezwsqyad.js → index-8rkdkefj.js} +40 -23
  135. package/dist/{index-3cwq5byx.js → index-9nax7tkn.js} +2 -2
  136. package/dist/{index-dz6tstcp.js → index-9r6emjwz.js} +1 -1
  137. package/dist/{index-32ew02z1.js → index-c4b7d6ej.js} +5 -5
  138. package/dist/index-ceshyndf.js +284 -0
  139. package/dist/{index-w161azza.js → index-d13rw31w.js} +6 -6
  140. package/dist/{index-1h0dtfz3.js → index-dmm7vs3f.js} +1 -1
  141. package/dist/{index-ypm85xwe.js → index-dp8j2e77.js} +1 -1
  142. package/dist/{index-qqd979f7.js → index-edycjvrv.js} +9 -9
  143. package/dist/{index-18qdpbcq.js → index-egpf9dv0.js} +200 -1479
  144. package/dist/{index-fatke81t.js → index-ezgvsj9w.js} +2 -2
  145. package/dist/{index-chapre0y.js → index-f3e7tj1g.js} +1 -1
  146. package/dist/{index-df5xr2f9.js → index-frsd2a94.js} +16 -1
  147. package/dist/index-fy9mmek1.js +95 -0
  148. package/dist/{index-2331y2tf.js → index-g0gvfzrx.js} +12 -12
  149. package/dist/index-gpe8d1ka.js +19 -0
  150. package/dist/{index-4p2zx593.js → index-gyw4qd0m.js} +1 -1
  151. package/dist/index-gzqy81tw.js +172 -0
  152. package/dist/{index-yrhw10ef.js → index-h34c510q.js} +8 -4
  153. package/dist/{index-rr94xcj6.js → index-h527p1yj.js} +10 -4
  154. package/dist/{index-qj0sq69b.js → index-hgf1tbgz.js} +76 -16
  155. package/dist/{index-smvmnz5y.js → index-hvpan32x.js} +1 -1
  156. package/dist/{index-4gbybjg6.js → index-hxawqrb6.js} +2 -2
  157. package/dist/{index-0k1ba0ss.js → index-j91jffhv.js} +1 -1
  158. package/dist/{index-d01akj5n.js → index-jr4kwetx.js} +8 -8
  159. package/dist/{index-xqppqn97.js → index-ka6z48zc.js} +315 -69
  160. package/dist/{index-by8w2461.js → index-kw0segzt.js} +104 -3
  161. package/dist/{index-6f4fjygr.js → index-m5t4dr7h.js} +29 -7
  162. package/dist/{index-afaq0nc4.js → index-n0egp1ke.js} +1 -1
  163. package/dist/{index-9fzjgg86.js → index-n74rb1dq.js} +2 -2
  164. package/dist/{index-dwq6a6sq.js → index-pt25vmhc.js} +33 -16
  165. package/dist/{index-vwg0n3e6.js → index-pyazb8q4.js} +23 -14
  166. package/dist/{index-5md04mwc.js → index-qpjjbkc5.js} +4 -4
  167. package/dist/{index-08a3qfr8.js → index-r1qt6zgj.js} +1 -1
  168. package/dist/{index-ctaxjpa4.js → index-r709pqed.js} +1 -1
  169. package/dist/{index-2zrx0nzv.js → index-rzc40z6e.js} +3 -5
  170. package/dist/{index-gq35s3bm.js → index-s5axtd56.js} +2 -2
  171. package/dist/{index-edpkm3k7.js → index-scpcps66.js} +669 -16
  172. package/dist/{index-ry8m2mhg.js → index-sf2mt6wj.js} +1 -1
  173. package/dist/{index-tjhhsnjv.js → index-t1213r0t.js} +1 -1
  174. package/dist/{index-gvgtmt7a.js → index-t7efje30.js} +2 -2
  175. package/dist/{index-w3s79kcb.js → index-tzyk36dy.js} +1 -1
  176. package/dist/{index-8tn10tp6.js → index-v64bvwjr.js} +1 -1
  177. package/dist/{index-1fhbe4e4.js → index-vksbsqpb.js} +1 -1
  178. package/dist/{index-dxft2mnm.js → index-wdg7bswj.js} +1 -1
  179. package/dist/{index-ppy23bd2.js → index-wjx1zs2r.js} +7 -578
  180. package/dist/{index-efbzm2se.js → index-x2r0ma9t.js} +1 -1
  181. package/dist/{index-kd48gk7d.js → index-x8py72a3.js} +1 -1
  182. package/dist/index-xvydbxmk.js +1404 -0
  183. package/dist/index-xwaphv0d.js +31 -0
  184. package/dist/{index-a09r9ff0.js → index-y44j39yk.js} +1 -1
  185. package/dist/{index-7mjsb7zv.js → index-ybrrxjhb.js} +1 -1
  186. package/dist/{index-xsrma0jd.js → index-ysthxsa8.js} +6 -6
  187. package/dist/{index-6p5pshcd.js → index-yyh3ey4b.js} +1 -1
  188. package/dist/{index-mr3njw67.js → index-z6hq9j8j.js} +1 -1
  189. package/dist/{index-67mzzkdv.js → index-z72agxdn.js} +2 -2
  190. package/dist/{index-e4w0sfm1.js → index-z78mtc16.js} +1 -1
  191. package/dist/{index-7csn6pva.js → index-ze94h4ph.js} +5 -0
  192. package/dist/internal/json-stringify.d.ts +12 -0
  193. package/dist/internal/json-stringify.d.ts.map +1 -1
  194. package/dist/internal/unix-client-error.d.ts +4 -0
  195. package/dist/internal/unix-client-error.d.ts.map +1 -1
  196. package/dist/live/watch-contract.d.ts +4 -0
  197. package/dist/live/watch-contract.d.ts.map +1 -1
  198. package/dist/live/watch-fanout-frame.d.ts +81 -0
  199. package/dist/live/watch-fanout-frame.d.ts.map +1 -0
  200. package/dist/live/watch-fanout.d.ts +57 -0
  201. package/dist/live/watch-fanout.d.ts.map +1 -0
  202. package/dist/observability/audit.d.ts.map +1 -1
  203. package/dist/observability/spool-core.d.ts +1 -0
  204. package/dist/observability/spool-core.d.ts.map +1 -1
  205. package/dist/observability/spool-drain.d.ts +48 -0
  206. package/dist/observability/spool-drain.d.ts.map +1 -0
  207. package/dist/observability/spool.d.ts +12 -6
  208. package/dist/observability/spool.d.ts.map +1 -1
  209. package/dist/postgres/rollback-transaction.d.ts +61 -0
  210. package/dist/postgres/rollback-transaction.d.ts.map +1 -0
  211. package/dist/primitives/deadline.d.ts +4 -4
  212. package/dist/primitives/deadline.d.ts.map +1 -1
  213. package/dist/server/error-hook.d.ts +3 -32
  214. package/dist/server/error-hook.d.ts.map +1 -1
  215. package/dist/server/local-consent-key.d.ts +104 -0
  216. package/dist/server/local-consent-key.d.ts.map +1 -0
  217. package/dist/server/local-control-journal.d.ts +51 -0
  218. package/dist/server/local-control-journal.d.ts.map +1 -0
  219. package/dist/server/local-control-reporter.d.ts +32 -0
  220. package/dist/server/local-control-reporter.d.ts.map +1 -0
  221. package/dist/server/local-control.d.ts +48 -0
  222. package/dist/server/local-control.d.ts.map +1 -0
  223. package/dist/server/local-host-clients.d.ts +105 -0
  224. package/dist/server/local-host-clients.d.ts.map +1 -0
  225. package/dist/server/middleware/trust-fence.d.ts +20 -0
  226. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  227. package/dist/spend/receipt-spool.d.ts +9 -4
  228. package/dist/spend/receipt-spool.d.ts.map +1 -1
  229. package/dist/testing/tool-surface-checks.d.ts +89 -0
  230. package/dist/testing/tool-surface-checks.d.ts.map +1 -0
  231. package/dist/testing/tool-surface-cli-callable.d.ts +63 -0
  232. package/dist/testing/tool-surface-cli-callable.d.ts.map +1 -0
  233. package/dist/testing/tool-surface-dead-refs.d.ts +32 -0
  234. package/dist/testing/tool-surface-dead-refs.d.ts.map +1 -0
  235. package/dist/testing/tool-surface-gates.d.ts +72 -0
  236. package/dist/testing/tool-surface-gates.d.ts.map +1 -0
  237. package/dist/testing/tool-surface-parity-drivers.d.ts +56 -0
  238. package/dist/testing/tool-surface-parity-drivers.d.ts.map +1 -0
  239. package/dist/testing/tool-surface-parity.d.ts +28 -0
  240. package/dist/testing/tool-surface-parity.d.ts.map +1 -0
  241. package/dist/testing/tool-surface-ratchet.d.ts +71 -0
  242. package/dist/testing/tool-surface-ratchet.d.ts.map +1 -0
  243. package/dist/tools/agent-tools.d.ts +3 -0
  244. package/dist/tools/agent-tools.d.ts.map +1 -1
  245. package/dist/tools/cli/command.d.ts +3 -0
  246. package/dist/tools/cli/command.d.ts.map +1 -1
  247. package/dist/tools/cli/create-cli.d.ts.map +1 -1
  248. package/dist/tools/cli/format.d.ts +3 -6
  249. package/dist/tools/cli/format.d.ts.map +1 -1
  250. package/dist/tools/cli/invoke.d.ts +4 -0
  251. package/dist/tools/cli/invoke.d.ts.map +1 -1
  252. package/dist/tools/cli/local-key-command.d.ts +53 -0
  253. package/dist/tools/cli/local-key-command.d.ts.map +1 -0
  254. package/dist/tools/cli/managed-surface.d.ts.map +1 -1
  255. package/dist/tools/cli/run-managed.d.ts.map +1 -1
  256. package/dist/tools/cli/run-stream.d.ts.map +1 -1
  257. package/dist/tools/cli/runner.d.ts +8 -3
  258. package/dist/tools/cli/runner.d.ts.map +1 -1
  259. package/dist/tools/cli/secret.d.ts +55 -0
  260. package/dist/tools/cli/secret.d.ts.map +1 -0
  261. package/dist/tools/cli/session.d.ts +2 -2
  262. package/dist/tools/cli/session.d.ts.map +1 -1
  263. package/dist/tools/cli/stream.d.ts.map +1 -1
  264. package/dist/tools/cli/unix-outcome.d.ts +6 -0
  265. package/dist/tools/cli/unix-outcome.d.ts.map +1 -1
  266. package/dist/tools/execute-result.d.ts +20 -0
  267. package/dist/tools/execute-result.d.ts.map +1 -1
  268. package/dist/tools/execute.d.ts +3 -0
  269. package/dist/tools/execute.d.ts.map +1 -1
  270. package/dist/tools/internal/json-projection.d.ts +13 -9
  271. package/dist/tools/internal/json-projection.d.ts.map +1 -1
  272. package/dist/tools/internal/remote-error.d.ts +15 -0
  273. package/dist/tools/internal/remote-error.d.ts.map +1 -0
  274. package/dist/tools/internal/surface-projector.d.ts +2 -0
  275. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  276. package/dist/tools/invoker.d.ts +3 -0
  277. package/dist/tools/invoker.d.ts.map +1 -1
  278. package/dist/tools/mcp/handler.d.ts.map +1 -1
  279. package/dist/tools/mcp/lazy-discovery.d.ts +2 -0
  280. package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -1
  281. package/dist/tools/mcp/mount.d.ts +5 -0
  282. package/dist/tools/mcp/mount.d.ts.map +1 -1
  283. package/dist/tools/mcp/register.d.ts +2 -0
  284. package/dist/tools/mcp/register.d.ts.map +1 -1
  285. package/dist/tools/mcp/runtime-tools.d.ts +2 -0
  286. package/dist/tools/mcp/runtime-tools.d.ts.map +1 -1
  287. package/dist/tools/mcp/stdio.d.ts.map +1 -1
  288. package/dist/tools/mount.d.ts +3 -0
  289. package/dist/tools/mount.d.ts.map +1 -1
  290. package/dist/tools/read-operation.d.ts +2 -6
  291. package/dist/tools/read-operation.d.ts.map +1 -1
  292. package/dist/tools/remote.d.ts.map +1 -1
  293. package/dist/tools/runtime-tool.d.ts.map +1 -1
  294. package/dist/tools/toolkit.d.ts +10 -3
  295. package/dist/tools/toolkit.d.ts.map +1 -1
  296. package/dist/xlsx/schema.d.ts.map +1 -1
  297. package/llms/cli.2.txt +10 -8
  298. package/llms/cli.3.txt +2 -0
  299. package/llms/cli.txt +18 -3
  300. package/llms/contract.txt +47 -5
  301. package/llms/handler.txt +1 -1
  302. package/llms/live.txt +82 -0
  303. package/llms/node.txt +5 -0
  304. package/llms/observability.2.txt +1 -1
  305. package/llms/observability.txt +6 -0
  306. package/llms/postgres.txt +1 -0
  307. package/llms/server.2.txt +206 -240
  308. package/llms/server.3.txt +242 -202
  309. package/llms/server.4.txt +202 -1025
  310. package/llms/server.5.txt +1053 -255
  311. package/llms/server.6.txt +274 -0
  312. package/llms/server.txt +32 -116
  313. package/llms/spend.txt +8 -7
  314. package/llms/stitchkit.2.txt +13 -35
  315. package/llms/stitchkit.3.txt +27 -0
  316. package/llms/stitchkit.txt +81 -81
  317. package/llms/testing.txt +40 -0
  318. package/llms/tools-toolkit.txt +2 -2
  319. package/llms/tools.2.txt +29 -20
  320. package/llms/{upgrading-0.128.0-0.129.0.txt → upgrading-0.128.0-0.131.0.txt} +101 -3
  321. package/llms/{upgrading-0.130.0-0.136.0.txt → upgrading-0.132.0-0.137.0.txt} +62 -101
  322. package/llms/upgrading.txt +2 -2
  323. package/llms-full.txt +590 -171
  324. package/llms.txt +13 -13
  325. package/package.json +1 -1
  326. package/dist/index-9118dw8d.js +0 -603
  327. package/dist/index-9vj869rx.js +0 -19
  328. package/dist/index-a1rjr381.js +0 -114
  329. package/dist/index-dacxr7nf.js +0 -17
  330. package/dist/index-dm50x3by.js +0 -63
  331. package/dist/index-dmrx8xma.js +0 -163
  332. package/dist/index-ednf2cxs.js +0 -37
  333. package/dist/{index-e4zt2x70.js → index-3czppvrr.js} +3 -3
  334. package/dist/{index-42n9jycn.js → index-3f79t32b.js} +3 -3
  335. package/dist/{index-mfe9a266.js → index-84n49vam.js} +0 -0
  336. package/dist/{index-f16b7rze.js → index-er1tp8de.js} +3 -3
  337. package/dist/{index-k137ezb6.js → index-f5d0fdcf.js} +3 -3
  338. package/dist/{index-65p8v81y.js → index-psz8qrz0.js} +3 -3
  339. package/dist/{index-kadgaw1s.js → index-r8cq86h1.js} +0 -0
  340. package/dist/{index-1yky29qg.js → index-tyyvbarf.js} +0 -0
  341. package/dist/{index-tjakdpf2.js → index-wq71v08n.js} +3 -3
  342. package/dist/{index-7an2fs5h.js → index-wswcpbm4.js} +3 -3
package/llms/server.5.txt CHANGED
@@ -1,268 +1,1066 @@
1
- # stitchkit/server — stitchkit docs slice, part 5 of 5
1
+ # stitchkit/server — stitchkit docs slice, part 5 of 6
2
2
 
3
3
  > Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
4
4
  > `llms.txt` in this package.
5
+ > Continues in `llms/server.6.txt`.
5
6
 
6
7
  Parts of this slice:
7
8
  - `llms/server.txt`: Guide: HTTP server (docs/guide/server.md)
8
- - `llms/server.2.txt`: Guide: HTTP server (docs/guide/server.md) · Guide: Realtime (docs/guide/realtime.md)
9
- - `llms/server.3.txt`: Guide: Realtime (docs/guide/realtime.md)
10
- - `llms/server.4.txt`: Guide: Realtime (docs/guide/realtime.md) · Guide: Auth & errors (docs/guide/auth-and-errors.md) · Guide: Multi-tenant (docs/guide/multi-tenant.md)
11
- - `llms/server.5.txt`: API reference: `stitchkit/server` (docs/api/reference.md)
9
+ - `llms/server.2.txt`: Guide: HTTP server (docs/guide/server.md)
10
+ - `llms/server.3.txt`: Guide: HTTP server (docs/guide/server.md) · Guide: Realtime (docs/guide/realtime.md)
11
+ - `llms/server.4.txt`: Guide: Realtime (docs/guide/realtime.md)
12
+ - `llms/server.5.txt`: Guide: Auth & errors (docs/guide/auth-and-errors.md) · Guide: Multi-tenant (docs/guide/multi-tenant.md)
13
+ - `llms/server.6.txt`: API reference: `stitchkit/server` (docs/api/reference.md)
12
14
 
13
15
  Also read:
14
16
  - see `llms/testing.txt` for the Testing & deployment guide
15
17
 
16
18
  ==============================================================================
17
- # API reference: `stitchkit/server` (docs/api/reference.md)
19
+ # Guide: Auth & errors (docs/guide/auth-and-errors.md)
18
20
  ==============================================================================
19
21
 
20
- ## `stitchkit/server`
21
-
22
- `EndpointHandlerContext` is the server endpoint handler’s inferred params, input, files and runtime context.
23
-
24
- Server-only. Builds and runs the HTTP server, and carries the server primitives.
25
- Also re-exports the error helpers from `stitchkit/contract`.
26
-
27
- ### Server & handlers
28
-
29
- | Export | Kind | Summary |
30
- |--------|------|---------|
31
- | `createServer` | function | build the router and start `Bun.serve` — [guide](../guide/server.md#createserver) |
32
- | `createHandler` | function | the router as a bare `(req) => Response` — [guide](../guide/server.md#createserver) |
33
- | `createLocalHostGuard` / `LocalHostGuard` / `LocalHostGuardConfig` / `LocalHostRefusal` | function / _types_ | a host that serves only its own machine's windows: loopback `Host`, allowed `Origin`, a constant-time Bearer secret — as `hooks.onRequest` and as Socket.IO `allowRequest` and `handshake`, with `cors` for the same origins (`undefined` when `origins` is empty for native-only hosts) — [guide](../guide/server.md#a-host-beside-its-own-window) |
34
- | `implement` | function | bind a contract to typed handlers — [guide](../guide/server.md#implement) |
35
- | `withContractIdentity` | function | the given services plus the one answering `contractIdentityContract` with their fingerprint — the list to mount — [guide](../guide/client.md#which-contract-does-the-server-speak) |
36
- | `createImplement` | function | fix the handler context type once |
37
- | `createScopedImplement` | function | fix one scope→context map, then type every handler by its endpoint's effective scope; `.declare(contract)(handlers)` types without binding for the registry path, `.stream(scope, …)` covers streaming multipart — [guide](../guide/server.md#per-scope-handler-context--createscopedimplement) |
38
- | `ScopedHandlers` | _type_ | handler map typed per endpoint by its effective scope |
39
- | `ScopeContexts` | _type_ | scope → extra context fields map accepted by `createScopedImplement` |
40
- | `EffectiveScope` | _type_ | an endpoint's own `scope`, else its contract's group scope |
41
- | `createScopedImplementRegistry` | function | the registry form of `createScopedImplement` — one contract registry, handlers still typed per endpoint scope |
42
- | `ScopedRegistryHandlers` | _type_ | scoped handler registry inferred from a contract registry |
43
- | `ScopedImplementationRegistry` | _type_ | contract registry whose every group scope is a key of the scope map |
44
- | `StreamScope` | _type_ | the scope `createScopedImplement(...).stream` accepts for one endpoint |
45
- | `ExactScopedRegistryHandlers` | _type_ | fail-first scoped registry shape that rejects extra registry and endpoint keys |
46
- | `implementRegistry` | function | bind one exact contract registry to one exact backend handler registry |
47
- | `createImplementRegistry` | function | context-typed factory for `implementRegistry` |
48
- | `ImplementationRegistry` | _type_ | flat literal registry of concrete contracts accepted by `implementRegistry` |
49
- | `ImplementOptions` | _type_ | `{ onMissingHandler }` — how a binding treats a contract endpoint with no handler |
50
- | `MissingHandlerPolicy` | _type_ | `'throw'` (default) or `'stub'`, the dev-stand policy that mounts a `501` instead of refusing to start |
51
- | `KeyedServices` | _type_ | registry result: the mount-ordered `ServiceDef[]` carrying the same services under `.byKey` |
52
- | `RegistryHandlers` | _type_ | exact backend handler registry inferred from a contract registry |
53
- | `ExactRegistryHandlers` | _type_ | fail-first handler shape that rejects extra registry and endpoint keys |
54
- | `staticRoute` | function | a raw route that serves a contained directory through `serveFile` (`Range` / `304` / validators) |
55
- | `StaticRouteOptions` | _type_ | `{ cacheControl, allowedDotNames }` — what `staticRoute` adds to every file it serves, and which dot-segment names it serves (none by default) |
56
- | `serveFile` | function | serve a file with `Range` / `304` / `HEAD` — [guide](../guide/server.md#serving-files--range-requests) |
57
- | `parseByteRange` | function | parse a single `Range` header → range / `unsatisfiable` / `null` |
58
- | `isWithinDir` | function | path containment — `(root, resolvedTarget) => boolean`; call it before `serveFile` on any URL-derived path |
59
- | `weakETag` | function | a weak `ETag` from size + mtime |
60
- | `ServeFileOptions` | _type_ | options for `serveFile` |
61
- | `ByteRange` | _type_ | an inclusive `{ start, end }` byte range |
62
- | `respondJson` | function | a raw route's JSON response (`204` for null/undefined) |
63
- | `errorResponse` | function | any thrown value → the framework error envelope + `x-request-id` |
64
- | `normalizeError` | function | any thrown value → an `AppError` (an `AppError` as is — contract input failures arrive as `VALIDATION_ERROR` 400 with structured `details.issues`; anything else, a `ZodError` from handler code included, generic 500) — the framework's canonical classification, for a bespoke `onError` |
65
- | `NormalizeErrorOptions` | _type_ | `logUnexpected` defaults to logging the raw server-side cause; tool adapters disable process dumps while their existing observers retain that cause |
66
- | `errorCode` | function | the stable error code for a thrown value (side-effect-free — for log attribution) |
67
- | `formatZodError` | function | a `ZodError` → a readable, field-summarised string |
68
- | `zodIssues` | function | a `ZodError` → structured `{ path, code, message }[]` — the machine-readable sibling of `formatZodError` |
69
- | `ZodIssueSummary` | _type_ | one structured validation issue (`{ path, code, message }`) |
70
- | `parseBody` | function | parse + Zod-validate a JSON body → `data` or `null` (no throw); reads at most `options.maxBytes` (1 MiB by default) and is `null` for a larger body |
71
- | `HandlerConfig` | _type_ | config for `createHandler`, including optional `maxJsonBodyBytes`; bound to `BunServer` on this entrypoint |
72
- | `BunServerConfig` | _type_ | config for `createServer` (Bun); `unix` listens on a unix domain socket (mutually exclusive with `port`/`hostname`) — [details](../guide/server.md#local-daemon-over-a-unix-socket) |
73
- | `defineRequestIngress` / `RequestIngress` / `RequestIngressSource` | function / _type_ | a typed key the code that builds a `Request` attaches a value to (`attach(request, value)`) and an endpoint, `authorize`, `beforeHandle` or `onError` reads from its `ctx` (`from(ctx)`); a header, `clone()` and `new Request(request)` carry nothing, a second `attach` is refused, and `ctx.req` is the very request the handler received — [guide](../guide/server.md#request-attributes-from-the-ingress) |
74
- | `ProxyOriginConfig` | _type_ | explicit real-peer trust for Bun `createServer({ proxyOrigin })`; strict external-scheme normalization before composition — [details](../guide/server.md#external-origin-behind-a-trusted-proxy) |
75
- | `UnixListenConfig` | _type_ | unix listener — a socket path bound under the process umask, or `{ path, mode }` for a socket born with exactly `mode` (`bindUnixSocket`) |
76
- | `BunServerHandle` | _type_ | managed Bun handle (`url`, `port`, `runtime`, `status`, `shutdown`) |
77
- | `ManagedServerHandle` | _type_ | shared lifecycle shape generic over the runtime escape hatch |
78
- | `ShutdownOptionsSchema` / `ShutdownOptions` | schema / _type_ | HTTP/application grace, a separate WebSocket close-handshake bound, bounded forced-completion timeout, retry hint and optional external abort signal |
79
- | `ShutdownStatusSchema` / `ShutdownStatus` | schema / _type_ | live state and request/WebSocket counters; owned streams remain pending through source cleanup |
80
- | `ShutdownResultSchema` / `ShutdownResult` | schema / _type_ | clean/forced result with final counters, outer-force snapshots and `forcedWebSockets` including bounded realtime terminations |
81
- | `ShutdownStateSchema` / `ShutdownState` | schema / _type_ | managed lifecycle state machine |
82
- | `ServiceDef` | _type_ | the result of `implement` |
83
- | `MethodDef` | _type_ | one resolved endpoint inside a service |
84
- | `OperationIdentity` | _type_ | path-free service/action/scope/method/optional `effect?` identity shared by contract and native tool operations; repeatable-read derivation (`readOnlyHint` and CLI view withholding) follows explicit `annotations.readOnlyHint` → `effect: 'write'` (non-read) → `effect: 'read'` (read unless `destructiveHint: true`) → `GET` fallback (unless `destructiveHint: true`) |
85
- | `Handlers` | _type_ | the typed handler map `implement` expects |
86
- | `LifecycleHooks` | _type_ | `onRequest` / pre-body `authorize` / `beforeHandle` / `afterHandle` / `onError` |
87
- | `composeLifecycleHooks` | function | compose HTTP lifecycle phases in declaration order with short-circuit/fallthrough semantics |
88
- | `AuthorizationContext` | _type_ | HTTP pre-body context with validated params, `input: undefined` and no files |
89
- | `RouteGroup` | _type_ | a prefixed group of services with its own hooks; matched errors try group `onError` → global `onError` → standard envelope, keeping the original error on fallback — [precedence](../guide/server.md#lifecycle-hooks) |
90
- | `RawRoute` | _type_ | a non-contract `Request → Response` route with a concrete `BunServer` context and optional stable `serviceName` / `action` observability identity |
91
- | `RawRouteContext` | _type_ | the Bun-bound routing context a raw handler receives |
92
- | `BunServer` | _type_ | the `Bun.serve` instance type |
93
- | `ServerPassthrough` | _type_ | extra `Bun.serve` options |
94
- | `StitchLogger` | _type_ | the custom-logger interface |
95
- | `LoggingConfig` | _type_ | the `logging` object — `logger` / `format` / `skip` / `enrich` |
96
- | `LogFormat` | _type_ | `'pretty'` or `'json'` — what the built-in formatter writes |
97
- | `LogOutcome` | _type_ | how a request finished, as `enrich` sees it |
98
- | `FetchHandler` | _type_ | what `createHandler` returns, bound to `BunServer` here |
99
- | `FetchComposition` | _type_ | the Bun-bound `wrapFetch` seam |
100
-
101
- ### Auth
102
-
103
- | Export | Kind | Summary |
104
- |--------|------|---------|
105
- | `createAuthHook` | function | one scope gate for HTTP `authorize` and tool `beforeHandle` — [guide](../guide/auth-and-errors.md#createauthhook) |
106
- | `composeAuthHooks` | function | route multiple canonical auth domains by owned scope and atomically commit their typed contributions |
107
- | `createErrorHook` | function | an async-capable, endpoint-aware `onError` hook from a `defineErrors` vocabulary or a code map, plus an envelope renderer — [guide](../guide/auth-and-errors.md#createerrorhook) |
108
- | `ErrorHookBase` / `ErrorHookMapping` | _type_ | common hook fields and the vocabulary-or-map branch accepted by `createErrorHook` |
109
- | `ErrorHookConfig` | _type_ | async observer/renderer config with partial `codeMap` and optional typed `unmappedCode` fallback |
110
- | `ResolvedError` | _type_ | the normalised error handed to `createErrorHook`'s `render` |
111
- | `createBearerResolver` | function | a bearer-token identity resolver |
112
- | `signJwt` | function | sign an HS256 JWT |
113
- | `VerifyJwtOptions` | _type_ | options for `verifyJwt` — `leewaySeconds`, `issuer`, `audience`, `expiration` (`'required'` by default) |
114
- | `verifyJwt` | function | verify an HS256 JWT |
115
- | `signLink` / `SignLinkOptions` | function / _type_ | a short-lived link for a request that cannot carry a header (`<audio src>`, `<img src>`): appends `expires` and an HMAC-SHA-256 `signature` over the method, path and every query parameter — [guide](../guide/auth-and-errors.md#signed-links) |
116
- | `verifySignedLink` / `VerifySignedLinkOptions` | function / _type_ | check a request against its link (signature compared with a constant-time comparison, then expiry); call it from `createAuthHook`'s `resolve` or a raw route |
117
- | `SignedLinkVerdict` / `SignedLinkRefusal` | _types_ | `{ ok: true, expiresAt }` or `{ ok: false, reason }` with `unsigned`, `malformed`, `expired` or `forged` |
118
- | `MAX_SIGNED_LINK_SECONDS` | constant | the longest lifetime `signLink` accepts: seven days |
119
- | `extractToken` | function | read a bearer token from header or cookie |
120
- | `deriveCodeChallenge` | function | PKCE — derive the `code_challenge` from a verifier |
121
- | `verifyPkce` | function | PKCE — verify a verifier against a stored challenge |
122
- | `AuthHook` | _type_ | the hook `createAuthHook` returns |
123
- | `AuthHookConfig` | _type_ | config for `createAuthHook` |
124
- | `AuthRule` | _type_ | `'public' \| 'authenticated' \| predicate` |
125
- | `AuthRuleContribution` | _type_ | plain context fields a sync/async rule may contribute after authorizing |
126
- | `ScopedAuthRule` | _type_ | a rule plus its typed context contribution — `{ rule, inject? }` |
127
- | `AuthRules` | _type_ | the `rules` map: bare rules or scoped rules |
128
- | `RuleScopes` | _type_ | scope→context map derived from a `rules` object; `'public'` fields become optional |
129
- | `ScopedAuthHook` | _type_ | an auth hook carrying its derived scope map at the type level |
130
- | `AuthScopes` | _type_ | recover the derived map — `createScopedImplement<AuthScopes<typeof hook>>()` |
131
- | `ComposeAuthHooksConfig` | _type_ | ordered canonical hooks plus the optional explicit composite default scope |
132
- | `ComposedAuthScopes` | _type_ | scope→context map derived from every owner in a composed auth hook |
133
- | `BearerResolverConfig` | _type_ | config for `createBearerResolver` |
134
- | `JwtPayload` | _type_ | a decoded JWT payload |
135
- | `SignJwtOptions` | _type_ | options for `signJwt` (expiry, claims) |
136
- | `PkceMethod` | _type_ | the PKCE challenge method — `'S256' \| 'plain'` |
137
-
138
- ### Cookies & CORS
139
-
140
- | Export | Kind | Summary |
141
- |--------|------|---------|
142
- | `defineCookie` | function | a typed cookie `get` / `getAll` / `set` / `clear` handle; `duplicates` names what `get` answers when two cookies share the name — [guide](../guide/auth-and-errors.md#cookies) |
143
- | `parseCookies` | function | parse a `Cookie` header to a record (the last of two same-named cookies wins) |
144
- | `parseCookieHeader` | function | parse a `Cookie` header to `[name, value]` pairs in header order, duplicates kept |
145
- | `serializeCookie` | function | build a `Set-Cookie` value |
146
- | `corsHeaders` | function | compute CORS response headers |
147
- | `corsPreflightResponse` | function | build a preflight `Response` |
148
- | `DEFAULT_CORS_ALLOW_HEADERS` | const | the default `Access-Control-Allow-Headers` (incl. `traceparent`) — extend it when overriding `cors.headers` |
149
- | `DEFAULT_CORS_EXPOSE_HEADERS` | const | the default `Access-Control-Expose-Headers` (incl. `Content-Disposition`, `ETag`, `Content-Range`, `X-Build-Id`) — extend it when overriding `cors.exposeHeaders`, or a cross-origin page loses the build id |
150
- | `CookieDef` | _type_ | the `defineCookie` handle |
151
- | `CookieOptions` | _type_ | cookie attributes, plus the `duplicates` read policy |
152
- | `CookieDuplicatesPolicy` | _type_ | `'last'` (default) / `'first'` / `'reject'` — `reject` yields `undefined` for two different values and the value when they agree |
153
- | `CorsConfig` | _type_ | static CORS policy: origin (or list, or `'*'`) and one `credentials` flag |
154
- | `CorsOriginPolicy` | _type_ | CORS decided per request: `origin(origin)` answers each exact serialized origin, sync or async; no `credentials` beside it. Decided once per request for every exit, always `Vary: Origin`, a throw or malformed answer grants nothing and runs nothing; a safelisted `text/plain` body needs a grant with credentials |
155
- | `CorsOriginDecision` | _type_ | what the policy answers: `false` or `{ credentials: boolean }` |
156
-
157
- ### Realtime (server)
158
-
159
- | `bindSocketRegistry` | function | room membership and consistent replay over an already-authenticated realtime server |
160
- | `AuthorizedSocketRoom` / `SocketRegistry` / `SocketRegistryConnection` / `SocketRegistryOptions` / `SocketRegistryServer` / `SocketRegistrySnapshot` / `SocketReplayFrame` | _type_ | authorized room token, structural server boundary, replay frames and immutable registry state |
161
- | `bindDevicePresence` | function | mounts account-scoped online device presence, ephemeral capability state slots and targeted remote commands onto an existing `RealtimeServerHandle` |
162
- | `DevicePresenceServer` / `DevicePresenceServerOptions` / `DevicePresenceServerSnapshot` / `DevicePresenceAccountResolver` | _type_ | mounted server registry handle, `accountOf` authorization callback and diagnostic snapshot for `bindDevicePresence` |
163
- | Export | Kind | Summary |
164
- |--------|------|---------|
165
- | `createSocketIOServer` | function | the typed Socket.IO server — [guide](../guide/realtime.md#server--createsocketioserver) |
166
- | `bindRealtimeServer` | function | inferred, runtime-validated connection and broadcast boundary |
167
- | `RealtimeServer` | _type_ | validated broadcast and connection API inferred from a realtime contract |
168
- | `RealtimeServerConnection` | _type_ | one validated connection with raw socket access for auth and rooms |
169
- | `RealtimeServerHandle` | _type_ | minimal Socket.IO server handle accepted by `bindRealtimeServer`; carries the handshake identity type through to `connection.raw.data` |
170
- | `SocketIORequestPolicy` | _type_ | runtime-neutral async-capable Web `Request` handshake admission policy |
171
- | `SocketIOServerConfig` | _type_ | config for `createSocketIOServer`; `handshake` is the typed identity gate — [guide](../guide/realtime.md#handshake-auth--cookie-or-token) |
172
- | `SocketIOPeerLoaders` | _type_ | `peers: { server, bunEngine }` — literal dynamic imports written in YOUR source, so a bundler puts the optional peers inside a self-contained artifact. Omit for the lazy default |
173
- | `SocketIOHandshakeConfig` | _type_ | the `handshake` gate — Zod `schema` over `handshake.auth` plus optional async `verify`; the result lands typed in `socket.data` |
174
- | `SocketIOServerHandle` | _type_ | typed Socket.IO server plus Bun mount fields and idempotent lifecycle |
175
- | `SocketIOServerLifecycle` | _type_ | non-generic Bun mount/shutdown portion accepted by `createServer` |
176
- | `composeWebSocketHandlers` | function | compose one Bun `websocket` from N lanes — a raw binary lane beside Socket.IO ([guide](../guide/realtime.md#raw-binary-lane-bun)) |
177
- | `webSocketLane` | function | a typed, cast-free lane for `composeWebSocketHandlers` |
178
- | `socketIoLane` | function | the Socket.IO catch-all lane for `composeWebSocketHandlers` |
179
- | `ComposedLane` | _type_ | a lane bridged to the loose data type |
180
- | `WebSocketLane` | _type_ | a typed lane (`{ match, handlers }`) |
181
- | `WebSocketComposeConfig` | _type_ | server-wide tuning for the composed handler |
182
-
183
- ### Primitives
184
-
185
- | `createFileStateStore` | function | cross-process locked atomic JSON state updates over one Zod schema |
186
- | `FileStateStoreCorruption` / `FileStateStoreOptions` | _type_ | explicit corrupt-state report/policy, lock timing and the state read cap `maxBytes`; a transition whose resulting state encodes to the bytes it started from writes nothing |
187
- | Export | Kind | Summary |
188
- |--------|------|---------|
189
- | `streamSSE` | function | an async generator → SSE `Response` — [guide](../guide/server.md#sse-streaming) |
190
- | `streamingRoute` | function | a long-lived subscription route: idle timeout, heartbeat, opening flush, cancellation — [guide](../guide/server.md#long-lived-subscriptions) |
191
- | `ndjsonRoute` | function | `streamingRoute` framed as NDJSON |
192
- | `sseRoute` | function | `streamingRoute` framed as SSE |
193
- | `DEFAULT_STREAM_HEARTBEAT_MS` | const | 5000 — deliberately well under Bun's ten-second idle threshold |
194
- | `MultipartLifecycle` | _type_ | request-scoped rollback ownership for accepted streamed handles |
195
- | `MultipartResult` | _type_ | what `parseMultipart` returns |
196
- | `parseMultipart` | function | parse a typed buffered/streaming multipart descriptor — [guide](../guide/server.md#multipart) |
197
- | `defineMultipartStream` | function | bind typed streaming file receivers and a final endpoint handler |
198
- | `createMultipartStream` | function | fix one handler context type for streaming multipart endpoints |
199
- | `MultipartStreamConfig` | _type_ | receivers plus the context-typed handler accepted by the streaming builders |
200
- | `MultipartFileMetadata` | _type_ | field, filename, declared media type and optional declared size |
201
- | `MultipartReceiver` | _type_ | consumer-owned Web-stream storage receiver |
202
- | `MultipartReceiverResult` | _type_ | receiver value plus rollback cleanup |
203
- | `StreamingMultipartImplementation` | _type_ | receiver registry and handler shape inferred by `defineMultipartStream` |
204
- | `bindReleaseRefreshSignal` / `ReleaseRefreshSignalOptions` / `ReleaseRefreshSignal` | function / _type_ | a deploy signal (`SIGUSR2`, the one user-defined signal the process vocabulary has) refreshes a `stitchkit/release` marker, whose subscribers tell every socket; never throws at the signal — [guide](../guide/release.md) |
205
- | `bindProcessSignals` | function | bind `SIGINT` / `SIGTERM` to one managed `shutdown()` — one chain, force on a later signal, default disposition on the one after — [guide](../guide/testing-and-deployment.md#process-signals--bindprocesssignals) |
206
- | `ProcessSignalsOptions` | _type_ | config for `bindProcessSignals` |
207
- | `ProcessSignalsBinding` | _type_ | the `{ promise, close }` handle `bindProcessSignals` returns |
208
- | `ProcessSignalsErrorPhase` | _type_ | `'prepare' \| 'shutdown' \| 'complete'` — which phase an `onError` report came from |
209
- | `SignalSource` | _type_ | injectable signal source — `process` by default |
210
- | `ProcessSignalName` | _type_ | signal names the binding accepts (owned, so the published types need no `@types/node`) |
211
- | `ShutdownTarget` | _type_ | the `shutdown`-only slice a binding needs — an interface, so a [composite target](../guide/testing-and-deployment.md#composite-shutdown-target--parallel-domain-drains) can drain several domains under one signal machine |
212
- | `createRateLimiter` | function | token-bucket rate limiting — [guide](../guide/server.md#rate-limiting) |
213
- | `createCache` | function | an in-memory TTL cache |
214
- | `CacheOptions` | _type_ | bounded-cache options, including the maximum retained entry count |
215
- | `cacheHeaders` | function | build a `Cache-Control` header |
216
- | `EventBusOptions` | _type_ | options for `createEventBus` |
217
- | `EventHandler` | _type_ | one event-bus subscriber |
218
- | `DefaultEventMap` | _type_ | the default event map — `Record<string, unknown>` |
219
- | `createEventBus` | function | typed in-process pub/sub — [guide](../guide/server.md#event-bus) |
220
- | `generateTraceId` | function | a fresh trace id |
221
- | `resolveTraceId` | function | the default per-request trace-id resolver |
222
- | `extractIp` | function | the caller IP from a request |
223
- | `isPublicIp` | function | whether an address belongs to the public internet; anything unparseable is not |
224
- | `resolveSocketIp` | function | the real socket peer IP from the runtime (`server.requestIP` on Bun, `req.ip` under `srvx`); headers are not read |
225
- | `getClientInfo` | function | caller IP + user-agent |
226
- | `EventBus` | _type_ | the `createEventBus` handle |
227
- | `RateLimitConfig` | _type_ | config for `createRateLimiter` |
228
- | `ClientIpOptions` | _type_ | socket peer and trusted-proxy config for `extractIp` / `getClientInfo` |
229
- | `StreamingRouteOptions` | _type_ | options for `streamingRoute` / `ndjsonRoute` / `sseRoute` |
230
- | `StreamingSourceContext` | _type_ | what a streaming source is given, including the cancellation `signal` |
231
- | `StreamingFormat` | _type_ | `'ndjson' \| 'sse'` |
232
- | `createUnixClientTransport` | function | owned Fetch-compatible Unix-socket transport on Bun and Node; enforces parent-directory, symlink, non-group/world-writable, and owner-UID (`expectedOwnerUid`, defaulting to current EUID) checks on every dispatch and redirect — [guide](../guide/client.md#unix-domain-sockets) |
233
- | `UnixClientTransportConfig` | _type_ | absolute socket path, optional `expectedOwnerUid` for cross-UID group-accessible local daemons, request/header/connection/redirect bounds, and an explicit bounded-or-streaming response policy |
234
- | `UnixClientTransport` | _type_ | `{ fetch, closed, close() }`; `close()` settles owned active work |
235
- | `UnixResponseBodyMode` | _type_ | `bounded \| streaming`; bounded is the 16 MiB cumulative default, streaming keeps pull-driven buffering without a lifetime total |
236
- | `UnixClientTransportError` | class | stable transport failure with `code` and dispatch certainty in `delivery` |
237
- | `UnixClientTransportErrorCode` | _type_ | finite Unix transport failure-code union |
238
- | `UnixClientDeliveryState` | _type_ | `not-dispatched \| possibly-dispatched \| response-received`; input to application retry policy, never an implicit retry |
239
-
240
- ### OpenAPI
241
-
242
- | Export | Kind | Summary |
243
- |--------|------|---------|
244
- | `generateOpenApiDocument` | function | an OpenAPI 3.1 document from contract services — [ADR 0018](../decisions/0018-openapi-generation.md) |
245
- | `openApiRoute` | function | a `RawRoute` that serves the document as JSON |
246
- | `OpenApiConfig` | _type_ | config for `generateOpenApiDocument` (incl. `includeMethod` — curate a public subset) — [guide](../guide/server.md#curating-the-spec--includemethod) |
247
- | `OpenApiDocument` | _type_ | the generated document |
248
- | `OpenApiInfo` | _type_ | the spec `info` block |
249
- | `OpenApiSecurity` | _type_ | `OpenApiConfig.security` — named schemes and the schemes each protected scope accepts — [guide](../guide/server.md#security-schemes--security) |
250
- | `OpenApiSecurityScheme` | _type_ | one way a caller presents its credential: HTTP bearer or basic, or an API key in a header, query or cookie |
251
- | `OpenApiServer` | _type_ | a spec `servers` entry |
252
-
253
- ---
254
-
255
- ### Trust fence
256
-
257
- Refuses a request whose `Host` is not a declared authority, at both admission points — the socket
258
- lane never reaches the hooks on either runtime.
259
- → [ADR 0151](../decisions/0151-a-trust-fence-names-its-lanes-because-one-of-them-bypasses-hooks.md).
260
-
261
- | Export | Kind | Summary |
262
- |--------|------|---------|
263
- | `createTrustFence` | function | `hooks` for the HTTP lane and `allowRequest` for the Socket.IO lane; a bare 403 that never says which rule refused |
264
- | `isLoopbackAddress` | function | whether an address is this machine — for the auth rule a privileged operation belongs in, not for the fence |
265
- | `TrustFence` / `TrustFenceConfig` / `TrustRefusal` / `TrustRefusalReason` / `TrustLane` | _types_ | the two admission points, the declared authorities, and why and where a request was refused |
266
- | `RouteGroupHooks` | _type_ | a route group's hooks — `LifecycleHooks` without `onRequest`, which runs before the group is known |
267
-
268
- ---
22
+ # Auth & errors
23
+
24
+ Client-side login/session operations may legitimately answer `401`. Declare
25
+ that policy with contract-owned matchers instead of path strings:
26
+
27
+ ```ts
28
+ const http = createHttpClient({
29
+ baseUrl,
30
+ suppressUnauthorizedFor: contractEndpointMatchers(publicAuth, ['login', 'verify']),
31
+ })
32
+ ```
33
+
34
+ Only the selected operations suppress the global `unauthorized` event; a 401
35
+ from any neighbouring protected route still signals session expiry.
36
+
37
+ stitchkit carries no domain model — it does not know what a user is. What it
38
+ provides is the *control flow*: a scope on every endpoint, one hook that
39
+ enforces it, and one error model shared by every transport. The identity and
40
+ the scope vocabulary are yours.
41
+
42
+ ## Scopes
43
+
44
+ An endpoint declares a `scope` — a free string. The contract `meta.scope` is the
45
+ default for endpoints that declare none. (Authored through
46
+ [`createContractFactory<Scope>()`](./contracts.md#scope), both the contract's
47
+ scope and any endpoint override are held to your own union instead.)
48
+
49
+ ```ts
50
+ export const posts = defineContract({ prefix: 'posts', scope: 'user' }, {
51
+ list: { method: 'GET', path: '/', desc: 'List posts', scope: 'public', output: /* … */ },
52
+ create: { method: 'POST', path: '/', desc: 'Create', /* inherits 'user' */ },
53
+ remove: { method: 'DELETE', path: '/:id', desc: 'Delete', scope: 'admin' },
54
+ })
55
+ ```
56
+
57
+ The framework attaches no meaning to the strings — `'public'`, `'user'`,
58
+ `'admin'` mean whatever your auth hook decides.
59
+
60
+ ## `createAuthHook`
61
+
62
+ `createAuthHook` builds one scope gate that can run in both HTTP and tool
63
+ lifecycles. On HTTP it belongs in `hooks.authorize`: StitchKit validates path
64
+ params, resolves identity and scope, and rejects `401`/`403` **before reading a
65
+ JSON or multipart body**. On MCP, agent and CLI surfaces it belongs in
66
+ `access.gate.beforeHandle` (`access: { gate: { beforeHandle: authHook } }`),
67
+ because those transports have already received their
68
+ arguments before the common tool runner starts.
69
+
70
+ ```ts
71
+ import { createAuthHook, createServer } from 'stitchkit/server'
72
+
73
+ const authHook = createAuthHook<User>({
74
+ resolve: (ctx) => resolveSession(ctx), // → a User, or null
75
+ rules: {
76
+ public: 'public', // always pass
77
+ user: 'authenticated', // any resolved identity passes
78
+ admin: (user) => user.isAdmin, // custom predicate
79
+ },
80
+ inject: (ctx, user) => { ctx.user = user },
81
+ })
82
+
83
+ createServer({ services, hooks: { authorize: authHook } })
84
+ ```
85
+
86
+ ### `AuthRule`
87
+
88
+ The value of each `rules` entry, keyed by scope:
89
+
90
+ - **`'public'`** — always passes; the identity is attached if present.
91
+ - **`'authenticated'`** — any resolved identity passes; no identity ⇒ 401.
92
+ - **a function** `(identity, ctx) => boolean | contribution`, sync or async — a custom
93
+ check. It receives request metadata and validated path params, so a
94
+ resource-scoped rule can do a DB lookup. It cannot read `input` or files: the
95
+ body has deliberately not been consumed yet. `false` denies, `true` passes,
96
+ and a returned plain object passes and contributes inferred handler fields.
97
+
98
+ #### Resource-scoped rule — reading a path/prefix param
99
+
100
+ For a multi-tenant API (`pathPrefix: '/tenants/:tenantId'`, see
101
+ [Route groups → param prefixes](./server.md#param-prefixes-resource-scoped-paths)),
102
+ the rule gates access to the tenant in the path. A `:param` from the group prefix
103
+ or the endpoint is on the **context root** as `ctx.<name>` (a raw `string`):
104
+
105
+ ```ts
106
+ const authHook = createAuthHook<User>({
107
+ resolve: sessionResolver,
108
+ rules: {
109
+ public: 'public',
110
+ // gate the tenant in the path — ctx.tenantId comes from the group prefix
111
+ tenant: async (user, ctx) => userCanAccessTenant(user.id, String(ctx.tenantId)),
112
+ } satisfies Record<Scope, AuthRule<User>>,
113
+ // derive per-request facts onto ctx for handlers (role within this tenant, …)
114
+ inject: async (ctx, user) => {
115
+ ctx.user = user
116
+ if (user) ctx.tenantRole = await roleInTenant(user.id, String(ctx.tenantId))
117
+ },
118
+ })
119
+ ```
120
+
121
+ `inject` runs on every request (identity may be `null`) — use it to put the
122
+ identity *and* any derived values (role, parent-id) on `ctx` for handlers. Read
123
+ them back as `ctx.tenantRole` (typed `unknown` — narrow at the read site). The
124
+ endpoints under the group declare `scope: 'tenant'`.
125
+
126
+ When the async authorization lookup already produced handler data, return it
127
+ instead of repeating the lookup in `inject` and a handwritten scope map:
128
+
129
+ ```ts
130
+ const auth = createAuthHook({
131
+ resolve: sessionResolver,
132
+ rules: {
133
+ project: async (user, ctx) => {
134
+ const membership = await findMembership(user.id, String(ctx.projectId))
135
+ return membership
136
+ ? { userId: user.id, projectId: membership.projectId, role: membership.role }
137
+ : false
138
+ },
139
+ },
140
+ })
141
+
142
+ const implementFor = createScopedImplement<AuthScopes<typeof auth>>()
143
+ ```
144
+
145
+ Contributions are merged only after full validation. Runtime-owned context keys,
146
+ arrays, class instances, accessors, symbols, unsafe prototypes and partial proxy
147
+ reads fail without mutating context. `false | object` contributes required
148
+ fields; `true | object` correctly makes them optional.
149
+
150
+ ### `AuthHookConfig`
151
+
152
+ | Field | Purpose |
153
+ |-------|---------|
154
+ | `resolve` | `(ctx) => identity \| null` — HTTP identity from `ctx.req` (cookie / bearer + lookup) |
155
+ | `resolveFromContext` | `(ctx) => identity \| null` — identity on a tool call (no `req`) |
156
+ | `rules` | access rule per scope; `endpoint.scope` is the key |
157
+ | `defaultScope` | scope applied when an endpoint declares none |
158
+ | `inject` | write the resolved identity onto `ctx` for handlers |
159
+ | `onAnonymous` | thrown when a scope needs an identity and there is none (default 401) |
160
+ | `onForbidden` | thrown when an identity is present but the rule rejects it (default 403) |
161
+
162
+ Annotate `rules` with `satisfies Record<MyScope, AuthRule<User>>` so the compiler
163
+ catches a scope you forgot to cover. With the scoped rule objects below, widen
164
+ the annotation to
165
+ `satisfies Record<MyScope, AuthRule<User> | ScopedAuthRule<User, AuthRuleContribution>>`
166
+ — it keeps the coverage check and does not disturb the derivation. (When every
167
+ scope comes from the derived map, the check is already implicit: a scope missing
168
+ from `rules` is no key of the map, and a contract using it fails to compile.)
169
+
170
+ ### Scoped rules — the map `createScopedImplement` consumes
171
+
172
+ A rule may take an object form, `{ rule, inject }`, where `inject` **returns**
173
+ the fields this scope contributes. That return type is a declaration the hook
174
+ derives a scope→context map from — feed it to
175
+ [`createScopedImplement`](./server.md#per-scope-handler-context--createscopedimplement)
176
+ and the map can never drift from the hook, because it is computed from it:
177
+
178
+ ```ts
179
+ const authHook = createAuthHook({
180
+ resolve: sessionResolver, // no explicit generic — let it infer
181
+ rules: {
182
+ public: { rule: 'public', inject: (user) => ({ userId: user.id }) },
183
+ user: { rule: 'authenticated', inject: (user) => ({ userId: user.id }) },
184
+ admin: {
185
+ rule: (user) => user.admin,
186
+ inject: (user) => ({ userId: user.id, isAdmin: user.admin }),
187
+ },
188
+ },
189
+ })
190
+
191
+ export const implementFor = createScopedImplement<AuthScopes<typeof authHook>>()
192
+ ```
193
+
194
+ - A `'public'` rule's fields come out **optional**: public admits the anonymous
195
+ caller, it does not refuse to know the logged-in one — `resolve` and `inject`
196
+ still run, so a public `me` / `logout` handler reads `ctx.userId` as
197
+ `string | undefined` and narrows, instead of being pushed toward a cast by a
198
+ `public: object` map.
199
+ - Any other rule's fields are required — the rule rejected the request before
200
+ the handler if no identity resolved.
201
+ - A scope with no rule is no key of the derived map, so a contract using it
202
+ fails to compile — the type-level mirror of the hook's fail-closed
203
+ `no rule for scope` throw.
204
+
205
+ The per-rule `inject` runs after the shared one, only when an identity
206
+ resolved, and **before** the rule check — it may run for an identity the rule
207
+ then rejects, so keep it pure and synchronous (an async `inject` is a compile
208
+ error, and a runtime one for untyped callers: merging a Promise would merge
209
+ nothing). Write rule objects inline in `rules` — a hoisted, annotated rule
210
+ widens its inject and degrades that scope's fields to `object`.
211
+
212
+ Derivation needs the identity generic to be **inferred** (write no explicit
213
+ `createAuthHook<User>` — TypeScript has no partial inference); with an explicit
214
+ generic, or fields injected outside the hook, keep the hand-written map.
215
+ → ADR 0078
216
+
217
+ ### Multiple auth domains — `composeAuthHooks`
218
+
219
+ Independent identity domains should keep separate resolvers and rules. Compose
220
+ their canonical hooks and derive one handler context without a manual dispatcher
221
+ or scope-map intersection:
222
+
223
+ ```ts
224
+ const userAuth = createAuthHook({
225
+ resolve: resolveUser,
226
+ resolveFromContext: resolveToolUser,
227
+ rules: {
228
+ user: (user) => ({ userId: user.id }),
229
+ workspace: (user) => ({ userId: user.id }),
230
+ },
231
+ })
232
+
233
+ const workspaceAuth = createAuthHook({
234
+ resolve: resolveMembership,
235
+ resolveFromContext: resolveToolMembership,
236
+ rules: {
237
+ workspace: (membership) => ({ workspaceId: membership.workspaceId }),
238
+ },
239
+ })
240
+
241
+ export const auth = composeAuthHooks({
242
+ hooks: [userAuth, workspaceAuth],
243
+ defaultScope: 'user',
244
+ })
245
+ export const implementFor = createScopedImplement<AuthScopes<typeof auth>>()
246
+ ```
247
+
248
+ Only hooks that declare the selected scope run. An unknown scope fails closed;
249
+ when several hooks own one scope, every owner must pass in declaration order.
250
+ Each owner evaluates on an isolated shadow context. StitchKit validates all
251
+ changed fields, rejects reserved/unsafe fields and cross-owner key collisions,
252
+ then commits the combined contribution once. A rejected or cancelled composite
253
+ therefore exposes no partial fields to the handler.
254
+
255
+ Isolation is per-key, not deep: a contribution is the set of context keys whose
256
+ descriptor changed. Mutating an existing value **in place**
257
+ (`ctx.user.role = 'admin'`) edits the object every owner already shares, so it
258
+ is neither reported as a contribution nor checked for collisions — contribute
259
+ new fields instead of editing another owner's object. External side effects
260
+ likewise remain consumer-owned and are not rolled back.
261
+
262
+ The composite's `defaultScope` is the only implicit scope. A child hook's own
263
+ default must be absent or equal to it, so reordering hooks cannot change which
264
+ scope protects an endpoint.
265
+
266
+ ### Auth on the tool surface — `resolveFromContext`
267
+
268
+ The same hook guards every transport, but the lifecycle slot and identity
269
+ source differ:
270
+
271
+ - **HTTP** — `hooks.authorize` calls `resolve(ctx)` from `ctx.req` (a cookie or
272
+ bearer token) before body parsing.
273
+ - **Tool calls (MCP / agent)** — there is no `req`. The transport authenticated
274
+ the caller (an MCP API key) and `buildMcpServer`'s `context` injected the
275
+ identity into `ctx`. `access.gate.beforeHandle` calls
276
+ `resolveFromContext(ctx)` to locate it.
277
+
278
+ ```ts
279
+ const authHook = createAuthHook<User>({
280
+ resolve: (ctx) => resolveSession(ctx), // HTTP — from ctx.req
281
+ resolveFromContext: (ctx) => ctx.user ?? null, // tool — from injected ctx
282
+ rules: { public: 'public', user: 'authenticated', admin: (u) => u.isAdmin },
283
+ })
284
+ ```
285
+
286
+ The **scope check is identical** on both surfaces — only identity resolution
287
+ differs. If you omit `resolveFromContext`, a scoped tool call has no identity
288
+ and **fails closed** (rejected by `onAnonymous`) — the hook never silently
289
+ passes a tool call it cannot authenticate. → [ADR 0014](../decisions/0014-tool-http-parity.md)
290
+
291
+ ```ts
292
+ createServer({ services, hooks: { authorize: authHook } })
293
+ createMcpHandler({ services, access: { gate: { beforeHandle: authHook } } })
294
+ ```
295
+
296
+ ## `createBearerResolver`
297
+
298
+ For API-key or bearer-token auth (the usual MCP case), `createBearerResolver`
299
+ strips `Authorization: Bearer <token>` and hands the raw token to your lookup:
300
+
301
+ ```ts
302
+ import { createBearerResolver } from 'stitchkit/server'
303
+
304
+ const resolve = createBearerResolver<User>({
305
+ lookup: (token, req) => db.apiKeys.resolve(token), // → User, or null
306
+ })
307
+ ```
308
+
309
+ Use it as `createMcpHandler`'s `auth`, or inside `createAuthHook`'s `resolve`.
310
+
311
+ ## JWT
312
+
313
+ `verifyJwt(token, secret)` verifies an HS256 JWT and returns its payload, or
314
+ throws `unauthorized`. It pins the algorithm (the token's own `alg` can never
315
+ pick the scheme), checks `exp` and `nbf`, and **requires `exp`**: a token
316
+ without one would stay valid for as long as the secret does. Pass
317
+ `expiration: 'optional'` only for tokens whose lifetime you bound elsewhere (a
318
+ session row, a revocation list); a present `exp` is still enforced. Sign with
319
+ `signJwt(payload, secret, { expiresInSec })`.
320
+
321
+ ```ts
322
+ import { verifyJwt, extractToken } from 'stitchkit/server'
323
+ import { env } from './env'
324
+
325
+ const token = extractToken(req) // from Authorization, or a cookie name
326
+ if (!token) throw unauthorized('Bearer token is required')
327
+ const payload = await verifyJwt(token, env.JWT_SECRET)
328
+ ```
329
+
330
+ `extractToken(req, cookieName?)` reads a bearer token from the `Authorization`
331
+ header, or from the named cookie.
332
+
333
+ ## Signed links
334
+
335
+ `<audio src>`, `<img src>` and a plain navigation send no `Authorization` header, so an endpoint
336
+ that serves private bytes cannot see the page's session. The server signs a short-lived link
337
+ instead, and the endpoint's auth gate accepts it:
338
+
339
+ ```ts
340
+ import { createAuthHook, signLink, verifySignedLink } from 'stitchkit/server'
341
+
342
+ // Where the page asks for the recording: a link it can put in `<audio src>`.
343
+ const src = await signLink({
344
+ secret: env.MEDIA_LINK_SECRET, method: 'GET',
345
+ url: `/media/${recordingId}?for=${userId}`, expiresInSeconds: 300,
346
+ })
347
+
348
+ // The `rawResponse` endpoint under `scope: 'viewer'` needs no guard of its own.
349
+ const auth = createAuthHook<Viewer>({
350
+ resolve: async (ctx) => {
351
+ if (ctx.req) {
352
+ const link = await verifySignedLink(ctx.req, { secret: env.MEDIA_LINK_SECRET })
353
+ if (link.ok) return { userId: new URL(ctx.req.url).searchParams.get('for') }
354
+ }
355
+ return resolveSession(ctx)
356
+ },
357
+ rules: { viewer: 'authenticated' },
358
+ })
359
+ ```
360
+
361
+ `signLink` appends `expires` (Unix seconds) and `signature`, an HMAC-SHA-256 over the method, the
362
+ path and every other query parameter, so a link opens one request: another path, method or edited
363
+ parameter is `forged`. What the link is for — whose recording — rides in a parameter you add, and
364
+ the signature covers it. Nothing is stored; rotating the secret ends every link at once. The host
365
+ is not signed, so a proxy may change the origin, but the path and query must reach the server as
366
+ they were signed. A lifetime is 1 second to `MAX_SIGNED_LINK_SECONDS` (seven days); a secret
367
+ shorter than 32 characters throws. `verifySignedLink` returns `{ ok: true, expiresAt }` or a
368
+ `reason` — `unsigned`, `malformed`, `forged`, `expired` — and a raw route calls it the same way.
369
+ A link is a bearer credential until it expires: anyone holding it opens that one request.
370
+
371
+ ## Telegram Mini Apps
372
+
373
+ A Mini App hands its backend an `initData` query string that Telegram signed
374
+ with a key derived from the bot token. `verifyTelegramInitData` checks that
375
+ signature and reports what the string says — and refuses with a **reason**,
376
+ because an application answers a stale string differently from a forged one.
377
+
378
+ ```ts
379
+ import { verifyTelegramInitData } from 'stitchkit/telegram'
380
+ import { unauthorized } from 'stitchkit/contract'
381
+ import { env } from './env'
382
+
383
+ const result = await verifyTelegramInitData({
384
+ initData,
385
+ botToken: env.BOT_TOKEN,
386
+ maxAgeSeconds: 3600, // default: one day
387
+ })
388
+ if (!result.valid) {
389
+ // 'missing-hash' | 'signature-mismatch' | 'malformed' | 'expired'
390
+ throw unauthorized(result.reason === 'expired' ? 'Reopen the app' : 'Invalid session')
391
+ }
392
+ const telegramId = result.data.user?.id
393
+ ```
394
+
395
+ Three things it does that a hand-written check usually does not:
396
+
397
+ - the **signature is checked first**, before `auth_date` or anything else is
398
+ read — an expiry inside an unverified payload is a number the sender chose;
399
+ - digests are compared **without an early exit**, so the time a rejection takes
400
+ is not a measurement of how much of the digest was right;
401
+ - `raw` keeps every signed pair, so a field Telegram adds after this release
402
+ does not need a release to reach.
403
+
404
+ The user arrives `camelCase` — `firstName`, `languageCode` — as `TelegramUser`.
405
+ A bot meets the same person as grammY's `ctx.from`, in Telegram's `snake_case`;
406
+ `parseTelegramUser(ctx.from)` gives the same `TelegramUser`, so one
407
+ `ensureAccount(user)` serves the Mini App and the chat.
408
+
409
+ `maxAgeSeconds` defaults to one day (`86400`): a signed string is otherwise a
410
+ credential that never expires, so there is no unbounded mode. Set the lifetime
411
+ your session is worth — shorter for a sign-in exchange, longer for a Mini App
412
+ kept open for days.
413
+
414
+ The module is server-only and pulls in no bot library — the token never belongs
415
+ in a browser bundle. `stitchkit/application/grammy` remains the lifecycle
416
+ adapter for an injected grammY bot. Its companion,
417
+ `classifyTelegramSendFailure`, names why a send was refused and separates *retry
418
+ this send* from *stop addressing this recipient*:
419
+
420
+ ```ts
421
+ import { classifyTelegramSendFailure } from 'stitchkit/telegram'
422
+
423
+ try {
424
+ await bot.api.sendMessage(chatId, text)
425
+ } catch (error) {
426
+ const failure = classifyTelegramSendFailure(error)
427
+ if (failure.recipientUnreachable) await markUnreachable(chatId, failure.reason)
428
+ else if (failure.retryable) await requeue(chatId, failure.retryAfterSeconds)
429
+ }
430
+ ```
431
+
432
+ The two flags are separate because one answer cannot serve both. A rate limit is
433
+ retryable and implicates nobody; a blocked user is unreachable and no retry
434
+ helps; a message Telegram could not parse is *neither* — the recipient is fine
435
+ and our payload is wrong, which is the case a list of substrings quietly counts
436
+ against the user. An unrecognised refusal leaves the recipient reachable: losing
437
+ a working subscriber forever costs more than one wasted send.
438
+
439
+ `bot-to-bot-disabled` is permanent but deliberately not `recipientUnreachable`:
440
+ Telegram returns it when either bot has not enabled Bot to Bot messaging, so the
441
+ missing setting may be the sender's. Do not retry it, and do not close the
442
+ recipient's row on it.
443
+
444
+ `TELEGRAM_SEND_FAILURE_REASONS` lists every reason. A table keyed by
445
+ `TelegramSendFailureReason` — error codes, the text a person reads — fails to
446
+ compile when a release adds one, instead of falling through to a default:
447
+
448
+ ```ts
449
+ const codes: Record<TelegramSendFailureReason, string> = {
450
+ 'blocked-by-user': 'E_BLOCKED',
451
+ /* … every reason … */
452
+ }
453
+ ```
454
+
455
+ The rest of what a bot is assembled from — its resources, journal, operator
456
+ channel, broadcasts and local Bot API files — is in [Telegram bots](telegram.md).
457
+
458
+ ## Cookies
459
+
460
+ ```ts
461
+ import { defineCookie } from 'stitchkit/server'
462
+
463
+ const session = defineCookie({ name: 'sid', httpOnly: true, secure: true, sameSite: 'Lax', path: '/' })
464
+
465
+ session.get(req) // string | undefined
466
+ session.set('abc123') // → a Set-Cookie header value
467
+ session.clear() // → a Set-Cookie value that expires it
468
+ ```
469
+
470
+ `defineCookie` bundles a cookie's name and options into a typed handle, so the
471
+ config is not repeated at every call site. `parseCookies(header)`,
472
+ `parseCookieHeader(header)` and `serializeCookie(name, value, opts)` are the
473
+ lower-level primitives.
474
+
475
+ **Two cookies, one name.** A browser sends every cookie whose domain and path
476
+ match, so a `sid` on `.example.com` and a `sid` on `app.example.com` both arrive
477
+ — in an order the browser chooses (RFC 6265 §5.4) and a server should not rely
478
+ on (§4.2.2). `get` returns the **last** one by default, which is a fact of the
479
+ header order, not a rule: the same session then validates in one browser and
480
+ not in another. Name the behaviour you rely on, or refuse to guess:
481
+
482
+ ```ts
483
+ const session = defineCookie({ name: 'sid', domain: '.example.com', duplicates: 'reject' })
484
+
485
+ session.get(req) // undefined when two *different* values arrive; the one value when they agree
486
+ session.getAll(req) // every candidate, in header order — validate each, clear the loser
487
+ ```
488
+
489
+ `duplicates: 'reject'` turns the lottery into "no session", which a login page
490
+ handles; `'first'` and `'last'` exist so an application can state which coin it
491
+ flips. For a session cookie on a parent domain the durable fix is `getAll`:
492
+ validate each candidate and answer with `clear()` for the one that lost, so the
493
+ next request carries one.
494
+
495
+ To set a cookie from a schema-validated JSON endpoint without losing its typed
496
+ client result, declare [`responseMeta`](./server.md#typed-json-response-metadata)
497
+ and append the generated value:
498
+
499
+ ```ts
500
+ complete: async ({ response }) => {
501
+ response.headers.append('Set-Cookie', session.set('abc123'))
502
+ return authenticatedUser
503
+ }
504
+ ```
505
+
506
+ Append once per cookie; StitchKit preserves separate `Set-Cookie` fields through
507
+ both Bun and Node. Cookie/session policy remains application logic.
508
+
509
+ ## The error model
510
+
511
+ One error type, `AppError`, is shared by the contract, the server and the
512
+ client. It carries a stable `code`, an HTTP `status`, and optional structured
513
+ `details` and a `hint`.
514
+
515
+ ### Throwing errors
516
+
517
+ Throw `AppError` directly, or use a typed helper — the idiomatic path:
518
+
519
+ | Helper | Status | Code |
520
+ |--------|--------|------|
521
+ | `notFound(message?)` | 404 | `NOT_FOUND` |
522
+ | `badRequest(message, details?)` | 400 | `BAD_REQUEST` |
523
+ | `unauthorized(message?)` | 401 | `UNAUTHORIZED` |
524
+ | `forbidden(message?)` | 403 | `FORBIDDEN` |
525
+ | `conflict(message?, details?)` | 409 | `CONFLICT` |
526
+ | `rateLimited(message?)` | 429 | `RATE_LIMITED` |
527
+ | `throw new AppError(code, { message?, details?, status? })` | `STITCH_ERROR_STATUS[code]`, else 500 | any `code` |
528
+
529
+ ```ts
530
+ import { notFound, badRequest } from 'stitchkit/server'
531
+
532
+ const note = db.get(ctx.params.id)
533
+ if (!note) notFound('Note not found')
534
+ if (ctx.input.title.length > 200) badRequest('Title too long', { max: 200 })
535
+ ```
536
+
537
+ Each helper has a `never` return type — TypeScript knows execution stops, so the
538
+ code after it is correctly narrowed.
539
+
540
+ You can subclass `AppError` for a domain error model (`class FeatureLocked extends
541
+ AppError`). `AppError.is(err)` identifies any instance — a direct one, a subclass,
542
+ even a copy from another bundle chunk or realm — by a global brand rather than
543
+ `instanceof`, so a domain error keeps its `code` / `details` / `hint` on every
544
+ transport (HTTP, MCP, agent). → ADR 0032.
545
+
546
+ ### The error envelope
547
+
548
+ `AppError.toJSON()` renders the public envelope every transport returns:
549
+
550
+ ```json
551
+ { "error": { "code": "NOT_FOUND", "message": "Note not found" } }
552
+ ```
553
+
554
+ `details` and `hint` are included when present. On HTTP this is the response
555
+ body with the matching status; for an MCP or agent call the same `code` and
556
+ `details` come back as a tool error. A schema-validation failure on the request
557
+ is turned into a `400 VALIDATION_ERROR` automatically — and it carries the
558
+ offending fields as structured `details.issues`, so a machine client matches on
559
+ them instead of parsing the text `message`:
560
+
561
+ `path` and `code` are the framework's. **`message` is not** — it is `issue.message`
562
+ as Zod produced it, so for a `.refine()` it is whatever the schema's author wrote.
563
+ The framework never puts a submitted value into it, and its own messages describe
564
+ types rather than values (`expected string, received undefined`, `Invalid UUID`),
565
+ but that is a property of today's messages, not a guarantee anyone is in a
566
+ position to make: the text belongs to whoever declared the schema. Forward `path`
567
+ and `code` to an end user freely; treat `message` as internal unless you wrote
568
+ every refine in the contract.
569
+
570
+ ```json
571
+ {
572
+ "error": {
573
+ "code": "VALIDATION_ERROR",
574
+ "message": "name: Invalid input\nage: Invalid input",
575
+ "details": {
576
+ "issues": [
577
+ { "path": "name", "code": "invalid_type", "message": "Invalid input" },
578
+ { "path": "age", "code": "invalid_type", "message": "Invalid input" }
579
+ ]
580
+ }
581
+ }
582
+ }
583
+ ```
584
+
585
+ Use the exported `zodIssues(error)` to build the same structured list from a
586
+ `ZodError` in your own hook.
587
+
588
+ ### On the client
589
+
590
+ The client parses that envelope back into an `ApiError` with the same `code`,
591
+ `status`, `details` and `hint`, plus the response `x-request-id` as optional
592
+ readonly `traceId` — see [Typed client → ApiError](./client.md#apierror). The
593
+ error round-trips without adding correlation data to the response body.
594
+
595
+ ### Stitch codes vs your codes
596
+
597
+ A `code` is a free string — your app codes (`BOT_NOT_FOUND`, …) are yours and the
598
+ core never models them (ADR 0002). But stitchkit itself emits a set of its own:
599
+ `BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `UNKNOWN_OPERATION`,
600
+ `METHOD_NOT_ALLOWED`,
601
+ `CONFLICT`, `RATE_LIMITED`, `REQUEST_ABORTED`, `REQUEST_TIMEOUT`,
602
+ `VALIDATION_ERROR`, `FILE_INVALID_PATH`,
603
+ `FILE_OUTSIDE_ROOT`, `FILE_NOT_FOUND`, `FILE_NOT_REGULAR`,
604
+ `FILE_INSPECTION_REJECTED`, `FILE_TOO_LARGE`, `FILE_EXISTS`,
605
+ `REALTIME_CONTRACT_VIOLATION`, `APPLICATION_NOT_ACCEPTING`, `NOT_IMPLEMENTED`,
606
+ `WAIT_TIMEOUT`,
607
+ `WAIT_FAILED`, `CLI_COMMAND_UNAVAILABLE`, `CLI_PRESENTATION_FAILED`, `DOWNLOAD_NOT_FOUND`, `VIEW_HTTP_ERROR`,
608
+ `CONNECTION_TIMEOUT`, `CONNECTION_RESPONSE_TOO_LARGE`,
609
+ `CONNECTION_REQUEST_FAILED`, `HTTP_ERROR`, `UPSTREAM_TOOL_ERROR`, `MCP_STRUCTURED_CONTENT_MISSING`,
610
+ `OPERATION_NOT_SUCCEEDED`, `OPERATION_BUSY`, `OPERATION_RESPONSE_TOO_LARGE`,
611
+ `OPERATION_PROCESS_FAILED`, `STREAM_ITEM_INVALID`, `STREAM_FRAME_TOO_LARGE`,
612
+ `STREAM_TERMINAL_MISSING`, `STREAM_LIFETIME_EXCEEDED`,
613
+ `GRAMMY_WEBHOOK_NOT_ACCEPTING`, `SANDBOX_UNAVAILABLE`, `SANDBOX_INSUFFICIENT`,
614
+ `SPILL_REFERENCE_UNKNOWN`, `HEADERS_TOO_LARGE`, `REQUEST_TOO_LARGE`,
615
+ `CONTROL_API_BUSY`, `ROLE_NOT_ALLOWED`, `KEYS_MANAGE_REQUIRED`, `INIT_DENIED`,
616
+ `INIT_TIMEOUT`, `CONSENT_PENDING`, `INTERNAL_SERVER_ERROR` — a set that grows in
617
+ ordinary releases, each addition named in the changelog. They are
618
+ published as **`STITCH_ERROR_STATUS`** (the `code → status` map) and
619
+ **`StitchErrorCode`** (its `keyof`), with **`isStitchErrorCode()`** (→ ADR 0026).
620
+
621
+ > This list is enumerated here for reading, and the enumeration is what goes
622
+ > stale — it once dropped `APPLICATION_NOT_ACCEPTING`, which made the map below
623
+ > stop compiling. `Object.keys(STITCH_ERROR_STATUS)` is the answer that cannot;
624
+ > `packages/core/tests/error-registry-completeness.test.ts` keeps the registry
625
+ > itself complete against the source.
626
+
627
+ If you translate stitch's framework errors into your own wire codes in an
628
+ `onError` hook, you choose how the set's growth reaches you. Keying the map by
629
+ `StitchErrorCode` makes it exhaustive, so a code stitch adds or renames becomes
630
+ a compile error rather than an unfamiliar code on your wire — worth it when the
631
+ envelope is a published contract, at the cost of an edit on those releases:
632
+
633
+ ```ts
634
+ // Exhaustive on purpose: the annotation is what turns a new stitch code into a
635
+ // compile error here. Drop it (or use `satisfies` on a partial map) to let an
636
+ // unmapped code travel as itself instead.
637
+ // `Partial`, not an exhaustive `Record`: the set grows in ordinary releases, and
638
+ // a map written exhaustively stops compiling on every addition. Codes you leave
639
+ // out fall through to `unmappedCode`.
640
+ const STITCH_TO_APP: Partial<Record<StitchErrorCode, AppCode>> = {
641
+ NOT_FOUND: 'NOT_FOUND', UNKNOWN_OPERATION: 'NOT_FOUND',
642
+ METHOD_NOT_ALLOWED: 'METHOD_NOT_ALLOWED',
643
+ BAD_REQUEST: 'VALIDATION_ERROR', VALIDATION_ERROR: 'VALIDATION_ERROR',
644
+ UNAUTHORIZED: 'UNAUTHORIZED', FORBIDDEN: 'FORBIDDEN', CONFLICT: 'CONFLICT',
645
+ RATE_LIMITED: 'RATE_LIMITED', INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR',
646
+ REALTIME_CONTRACT_VIOLATION: 'INTERNAL_SERVER_ERROR',
647
+ FILE_INVALID_PATH: 'VALIDATION_ERROR', FILE_OUTSIDE_ROOT: 'VALIDATION_ERROR',
648
+ FILE_NOT_FOUND: 'NOT_FOUND', FILE_NOT_REGULAR: 'VALIDATION_ERROR',
649
+ FILE_INSPECTION_REJECTED: 'VALIDATION_ERROR', FILE_TOO_LARGE: 'VALIDATION_ERROR',
650
+ FILE_EXISTS: 'CONFLICT',
651
+ }
652
+ onError: (ctx, err) => {
653
+ if (AppError.is(err) && isStitchErrorCode(err.code)) {
654
+ return jsonError(STITCH_TO_APP[err.code], err.status) // keep stitch's status
655
+ }
656
+ // … your own AppError / normalizeError path
657
+ }
658
+ ```
659
+
660
+ ## One application vocabulary and one wire map
661
+
662
+ `defineErrors` can also resolve StitchKit's framework codes into the same
663
+ application vocabulary. A status fallback is explicit because several
664
+ application codes may legally share one HTTP status:
665
+
666
+ ```ts
667
+ const vocabulary = defineErrors(
668
+ {
669
+ VALIDATION_ERROR: { status: 400, message: 'Invalid request' },
670
+ INTERNAL_ERROR: { status: 500, message: 'Internal error' },
671
+ },
672
+ {
673
+ fallback: { 400: 'VALIDATION_ERROR', 500: 'INTERNAL_ERROR' },
674
+ map: { FILE_TOO_LARGE: 'VALIDATION_ERROR' },
675
+ },
676
+ )
677
+
678
+ const onError = createErrorHook({ vocabulary })
679
+ // `vocabulary` *is* the wire map: `codeMap` and `unmappedCode` cannot sit
680
+ // beside it — the type forbids the combination and the runtime refuses it.
681
+ // A `map` target must be declared under the framework code's own status
682
+ // (`NOT_FOUND` → a 404 code, never a 410 one): the wire keeps the framework
683
+ // status and carries your code, so `defineErrors` refuses the mismatch where
684
+ // it already refuses a `fallback` under the wrong status.
685
+ ```
686
+
687
+ An explicit per-code `map` wins over a status fallback. With
688
+ `exhaustive: true`, `map` must be a complete `Record<StitchErrorCode, AppCode>`
689
+ at compile time. Transport boundaries identify errors with `AppError.is`, not
690
+ `instanceof`, so two bundled copies still agree.
691
+
692
+ Pass the same `ErrorCodeMapping` (`{ vocabulary }`, `{ codeMap, unmappedCode? }`, and
693
+ optional `redact` to replace public messages and drop details/hints for internal wire codes)
694
+ to every surface so HTTP, MCP, agent tools, and CLI emit one error vocabulary:
695
+
696
+ ```ts
697
+ import type { ErrorCodeMapping } from 'stitchkit/contract'
698
+ import { createErrorHook } from 'stitchkit/server'
699
+ import { createToolkit } from 'stitchkit/tools/toolkit'
700
+
701
+ const errors: ErrorCodeMapping = {
702
+ vocabulary,
703
+ redact: { INTERNAL_ERROR: 'Internal server error' },
704
+ }
705
+
706
+ const onError = createErrorHook({
707
+ ...errors,
708
+ render: (info) => ({ ok: false, error: { code: info.code, message: info.message } }),
709
+ })
710
+ const tools = createToolkit<AppContext>({ errors })
711
+ // tools.createMcpHandler(...), tools.mountAgentTools(...), tools.createCli(...)
712
+ // all inherit `errors` automatically (or pass `errors` directly on any mount or invoker).
713
+ ```
714
+
715
+ CLI keeps its default exit codes (`DEFAULT_EXIT_CODES`, e.g. exit `4` for `NOT_FOUND` even
716
+ when mapped to `not_found`) unless you override the wire code in `exitCodes`, and server-side
717
+ audit logs keep the raw thrown message behind internal errors even when `redact` masks the
718
+ wire payload.
719
+
720
+ ## Domain errors — `defineErrors`
721
+
722
+ Declare each domain code, HTTP status, default message and optional
723
+ structured-details schema in one immutable registry. The generated functions
724
+ construct typed branded `AppError` instances; ordinary `throw` remains explicit
725
+ at the call site:
726
+
727
+ ```ts
728
+ import { z } from 'zod'
729
+
730
+ export const { errors, codes, definitions, isCode } = defineErrors({
731
+ SESSION_NOT_FOUND: { status: 404, message: 'No such session' },
732
+ QUOTA_EXCEEDED: {
733
+ status: 429,
734
+ message: 'Monthly quota exhausted',
735
+ details: z.object({ retryAfterSeconds: z.number().int().positive() }),
736
+ },
737
+ })
738
+
739
+ throw errors.SESSION_NOT_FOUND() // uses the declared message
740
+ throw errors.QUOTA_EXCEEDED({
741
+ message: 'Try later', // overrides it here only
742
+ details: { retryAfterSeconds: 30 },
743
+ hint: 'Wait for the current window to expire',
744
+ })
745
+
746
+ // Construction without throwing is useful for composition or inspection.
747
+ const error = errors.QUOTA_EXCEEDED({ details: { retryAfterSeconds: 30 } })
748
+ definitions.QUOTA_EXCEEDED.status // 429 — same source, no copied status map
749
+ definitions[code].message // the declared text, by a `code` variable
750
+
751
+ // client — match the code, never a magic string
752
+ if (err instanceof ApiError && err.code === codes.SESSION_NOT_FOUND) { … }
753
+ ```
754
+
755
+ `message` is optional: declare it once instead of repeating the sentence at every
756
+ `throw`, and a per-call `message` still wins. A code without one keeps the
757
+ existing fallback — `AppError.message` is the code itself. An empty declared
758
+ message is rejected when the registry is declared, not when the error is thrown.
759
+
760
+ **The tool envelope has no `message` field**, and what the model sees depends on
761
+ whether the code declares `details`:
762
+
763
+ | | HTTP / typed client | MCP / agent / CLI |
764
+ |---|---|---|
765
+ | code **with** a `details` schema | the declared message | no text at all — only `details` and `hint` |
766
+ | code **without** one | the declared message | the same text, delivered as `details.message` |
767
+
768
+ The model-facing envelope is `{ error, retryable, details?, _hint? }`; for a code with no
769
+ details schema the framework fills `details` with `{ message }`, so declaring a
770
+ message changes what the model reads there; without one it is the code itself. Put
771
+ anything the model must reliably read in `details` or `hint`, not in `message`.
772
+
773
+ With no `details` schema, the options object forbids `details`. A required
774
+ `z.object` makes `details` required; `z.object(...).optional()` makes it
775
+ optional. Supplied details are parsed when the error is constructed, before any
776
+ transport sees them. `code` remains literal and the parsed details type is
777
+ retained on the returned `AppError`.
778
+
779
+ HTTP renders the complete code/status/message/details/hint. Tool transports keep
780
+ their established model-facing projection (code/details/hint, without HTTP
781
+ status), while `invokeOrThrow` recovers the exact normalized `AppError`. The
782
+ codes and schemas remain application-owned; StitchKit stays domain-free.
783
+
784
+ ### The codes an operation refuses with
785
+
786
+ An endpoint names the domain codes it can refuse with in `refuses`, by listing the
787
+ factories `defineErrors` returned. Every factory carries its `code` and
788
+ `definition`, so the list is the declaration — no second string list to drift:
789
+
790
+ ```ts
791
+ const { errors } = defineErrors({
792
+ NOT_IDLE: { status: 409, message: 'Session is busy' },
793
+ MIN_AWAKE: { status: 409, details: z.object({ profile: z.string(), minimum: z.number().int() }) },
794
+ PROFILE_UNAVAILABLE: { status: 503 },
795
+ })
796
+
797
+ export const sessions = defineContract({ prefix: 'session' }, {
798
+ sleep: {
799
+ method: 'POST', path: '/sleep', desc: 'Put a session to sleep',
800
+ input: z.object({ id: z.string() }),
801
+ output: z.object({ ok: z.boolean() }),
802
+ refuses: [errors.NOT_IDLE, errors.MIN_AWAKE],
803
+ },
804
+ })
805
+ ```
806
+
807
+ One declaration, three readers:
808
+
809
+ - **The server holds the handler to it.** An `AppError` whose code the operation
810
+ did not declare — and that is no framework code (`NOT_FOUND`, `FORBIDDEN`, …) —
811
+ leaves as `INTERNAL_SERVER_ERROR` (500) with the message `Operation session.sleep
812
+ failed with a code it does not declare`, on HTTP, MCP, the agent surface, the CLI
813
+ and mid-stream alike, exactly as an output that breaks its schema does. The
814
+ original error stays on `cause`, so `onError` and the logs still see it; the
815
+ caller does not. An `implementRemote` proxy is held to the same list even when its
816
+ origin is not. A failure that is no `AppError` keeps its usual handling, and an
817
+ operation without `refuses` runs unchanged.
818
+ - **The typed client reads it.** [`client.sleep.refusal(error)`](client.md#read-a-refusal-the-operation-declared)
819
+ narrows `code` to the declared codes plus the framework and client codes, and
820
+ types `details` by the code's schema.
821
+ - **The descriptor carries it** for a reader without types: `MethodDef.refuses`
822
+ (code, status, retryability, message, details schema), `x-stitchkit-refusals`
823
+ with one response per declared status in OpenAPI, `refusals` in the surface
824
+ manifest, and the contract fingerprint. Each changes only for an operation that
825
+ declares `refuses`.
826
+
827
+ `defineContract` refuses an entry that is not a factory from `defineErrors` (a bare
828
+ code string) and a code listed twice, naming the endpoint and the index.
829
+ Declaring is opt-in per operation: start with the operations whose callers branch
830
+ on a code. → ADR 0330
831
+
832
+ ## `createErrorHook`
833
+
834
+ `createErrorHook` is the code-map above, packaged — you supply a `codeMap` and
835
+ the envelope shape, it does the normalisation (including the
836
+ never-leak-an-internal-message rule for a raw throw):
837
+
838
+ ```ts
839
+ const onError = createErrorHook({
840
+ // Map the codes you have an opinion about.
841
+ codeMap: {
842
+ BAD_REQUEST: 'bad_request', VALIDATION_ERROR: 'bad_request',
843
+ UNAUTHORIZED: 'unauthenticated', FORBIDDEN: 'forbidden',
844
+ NOT_FOUND: 'not_found', UNKNOWN_OPERATION: 'not_found',
845
+ METHOD_NOT_ALLOWED: 'not_found',
846
+ CONFLICT: 'conflict', RATE_LIMITED: 'rate_limited',
847
+ INTERNAL_SERVER_ERROR: 'internal',
848
+ },
849
+ // Optional: one public vocabulary entry for every other stitchkit code.
850
+ // A resolver `(code) => ...` is also accepted for grouping code families.
851
+ unmappedCode: 'framework_error',
852
+ // `ctx` is the request's RuntimeContext — read `ctx.traceId` for a
853
+ // correlation id in the envelope. Declaring it is optional.
854
+ render: (info, ctx) => ({
855
+ ok: false,
856
+ error: { code: info.code, message: info.message },
857
+ traceId: ctx.traceId,
858
+ }),
859
+ })
860
+
861
+ createServer({ services, hooks: { onError } })
862
+ ```
863
+
864
+ `codeMap` is partial: map the codes you have an opinion about. By default a
865
+ stitchkit code you did not list travels as itself. Set `unmappedCode` to one
866
+ wire-code when your public vocabulary has a catch-all, or to a function such as
867
+ `(code) => code.startsWith('FILE_') ? 'storage_error' : 'framework_error'` when
868
+ framework code families need different buckets. An explicit `codeMap` entry
869
+ always wins. Codes your project throws itself do not belong to StitchKit's
870
+ vocabulary, so they never pass through this fallback and remain unchanged.
871
+
872
+ One `satisfies` is the **opt-in** to the stricter deal:
873
+
874
+ ```ts
875
+ codeMap: { /* … every code … */ } satisfies Record<StitchErrorCode, string>,
876
+ ```
877
+
878
+ That makes the map exhaustive on your side, so a release that adds a code stops
879
+ your build until you decide what the new code is called on your wire. Take it
880
+ when your envelope is a published contract and a code surfacing in stitchkit's
881
+ spelling would violate it; leave it off when passing one through is fine.
882
+ Neither choice is silent — the changelog names every added code.
883
+
884
+ Both `onError` and `render` may be asynchronous and receive the matched endpoint
885
+ as their final argument. The observer is awaited before rendering, so it can
886
+ resolve identity or enrich the request context even for failures raised before
887
+ `beforeHandle`:
888
+
889
+ ```ts
890
+ const onError = createErrorHook({
891
+ onError: async (_error, _info, ctx, endpoint) => {
892
+ await attributeFailedRequest(ctx, endpoint)
893
+ },
894
+ render: (info, ctx) => ({
895
+ error: { code: info.code },
896
+ actorId: ctx.actorId,
897
+ }),
898
+ })
899
+ ```
900
+
901
+ `endpoint` is `undefined` when the failure happened before route resolution.
902
+ Synchronous callbacks and renderers that declare fewer parameters continue to
903
+ work normally.
904
+
905
+ Input that fails the contract's `params` / `input` schema reaches `render` as
906
+ `VALIDATION_ERROR` 400 — a client fault is an honest 400, not a 500 — and the
907
+ offending fields arrive as structured `info.details.issues`, so your `render`
908
+ can surface them to a machine client without parsing the message.
909
+
910
+ Only the contract boundary produces `VALIDATION_ERROR`. A `ZodError` your
911
+ handler throws — parsing an upstream answer, a database row, a config value —
912
+ is the server's own schema failing: it is answered as `INTERNAL_SERVER_ERROR`
913
+ 500 with the generic message, and the `ZodError` text goes to the log and the
914
+ audit row, never to the caller. To refuse the caller's input from inside a
915
+ handler, throw `badRequest(message, details)` (or an `AppError`) yourself.
916
+
917
+ If you write a **bespoke** `onError` instead of using `createErrorHook`, run the
918
+ thrown value through the exported `normalizeError` to get the same classification.
919
+ Invalid input reaches your hook as an `AppError` with code `VALIDATION_ERROR`,
920
+ its `details.issues` and the `ZodError` as `cause`:
921
+
922
+ ```ts
923
+ import { normalizeError } from 'stitchkit/server'
924
+
925
+ onError: (ctx, err) => {
926
+ const e = normalizeError(err) // AppError as is (VALIDATION_ERROR 400 for input), else generic 500
927
+ return jsonError(e.code, e.status, e.message)
928
+ }
929
+ ```
930
+
931
+ ==============================================================================
932
+ # Guide: Multi-tenant (docs/guide/multi-tenant.md)
933
+ ==============================================================================
934
+
935
+ # Multi-tenant / resource-scoped paths
936
+
937
+ A walkthrough of one mainstream scenario end-to-end: a SaaS API scoped by a path
938
+ segment — `/tenants/:tenantId/widgets/...` — where the same `tenantId` gates
939
+ access in auth and is injected into tool calls (one API key → many tenants).
940
+
941
+ Every piece below already exists; this recipe wires them into one flow. Each step
942
+ links to its reference section.
943
+
944
+ ## 1. The contract — tenant-agnostic
945
+
946
+ Endpoints know nothing about the tenant; the path segment lives on the group, not
947
+ the endpoint:
948
+
949
+ ```ts
950
+ export const widgets = defineContract(
951
+ { prefix: 'widgets', scope: 'tenant' },
952
+ {
953
+ list: { method: 'GET', path: '/', desc: 'List widgets', output: WidgetList },
954
+ create: { method: 'POST', path: '/', desc: 'Create a widget', input: NewWidget, output: Widget },
955
+ },
956
+ )
957
+ ```
958
+
959
+ ## 2. The server — a param prefix
960
+
961
+ Mount the service under a group whose `pathPrefix` carries `:tenantId`. The
962
+ matched value is on the context root as `ctx.tenantId`
963
+ ([details](./server.md#param-prefixes-resource-scoped-paths)):
964
+
965
+ ```ts
966
+ createServer({
967
+ groups: [
968
+ { pathPrefix: '/tenants/:tenantId', services: [widgetsService], hooks: { authorize: authHook } },
969
+ ],
970
+ })
971
+ // → /tenants/:tenantId/widgets
972
+ ```
973
+
974
+ With more than one scope, let **`scopePrefixes`** map `scope → prefix` and mount
975
+ the flat `services` list — no hand-partitioning, the mapping lives in one place
976
+ ([details](./server.md#scope-driven-mounting-scopeprefixes), → ADR 0024):
977
+
978
+ ```ts
979
+ createServer({
980
+ services, // mixed scopes, listed once
981
+ scopePrefixes: { tenant: 'tenants/:tenantId', project: 'projects/:projectId' },
982
+ hooks: { authorize: authHook },
983
+ })
984
+ // `tenant`-scoped → /tenants/:tenantId/..., `project` → /projects/:projectId/..., the rest flat
985
+ ```
986
+
987
+ Handlers read `ctx.tenantId` (a raw `string` — narrow it). To get it typed inside
988
+ `ctx.params`, add `tenantId` to the endpoint's `params` schema (a `z.strictObject`
989
+ that omits it will reject the request). When each scope guarantees different
990
+ injected fields, declare the scope map once with
991
+ [`createScopedImplement`](./server.md#per-scope-handler-context--createscopedimplement):
992
+
993
+ ```ts
994
+ export const implementFor = createScopedImplement<{
995
+ public: object
996
+ tenant: { tenantId: string; userId: string }
997
+ project: { projectId: string; userId: string }
998
+ }>()
999
+ ```
1000
+
1001
+ Each handler is then typed by its endpoint's effective scope — no superset
1002
+ context that promises a `tenantId` a `public` handler never receives. A contract
1003
+ that mixes scopes across its endpoints needs no splitting.
1004
+
1005
+ ## 3. Auth — gate the tenant in the path
1006
+
1007
+ The `tenant` scope rule reads the prefix param and checks access; `inject` puts
1008
+ the identity and derived facts on `ctx`
1009
+ ([details](./auth-and-errors.md#resource-scoped-rule--reading-a-pathprefix-param)):
1010
+
1011
+ ```ts
1012
+ const authHook = createAuthHook<User>({
1013
+ resolve: sessionResolver,
1014
+ rules: {
1015
+ public: 'public',
1016
+ tenant: (user, ctx) => userCanAccessTenant(user.id, String(ctx.tenantId)),
1017
+ } satisfies Record<Scope, AuthRule<User>>,
1018
+ inject: (ctx, user) => { ctx.user = user },
1019
+ })
1020
+ ```
1021
+
1022
+ ## 4. The client — a per-tenant `pathPrefix`
1023
+
1024
+ `createClient`'s third argument prepends the tenant segment; `stripPrefixKeys`
1025
+ keeps `tenantId` out of the body/query
1026
+ ([details](./client.md#contractclientconfig--per-tenant--resource-scoped-clients)):
1027
+
1028
+ ```ts
1029
+ const widgetsApi = createClient(widgets, http, {
1030
+ pathPrefix: ({ tenantId }) => `tenants/${tenantId}/`,
1031
+ stripPrefixKeys: ['tenantId'],
1032
+ })
1033
+
1034
+ widgetsApi.list({ tenantId: 't_123' }) // GET /tenants/t_123/widgets
1035
+ ```
1036
+
1037
+ `stripPrefixKeys` (a `const` tuple) also makes the consumed keys **typed,
1038
+ required args** on every method — `tenantId` above is type-checked, not a runtime
1039
+ surprise — so no hand-written scoped-client wrapper is needed (→ ADR 0025).
1040
+
1041
+ ## 5. The AI surface — `extend` injects the tenant
1042
+
1043
+ One API key serves every tenant: the model passes `tenantId` per call, `resolve`
1044
+ validates it and puts it on `ctx` — so the *same* handler that reads `ctx.tenantId`
1045
+ over HTTP serves the tool call
1046
+ ([details](./mcp-and-agents.md#adding-tool-only-args--extend)):
1047
+
1048
+ ```ts
1049
+ createMcpHandler({
1050
+ serverInfo, auth,
1051
+ services: [widgetsService],
1052
+ access: { gate: { beforeHandle: authHook } },
1053
+ extend: {
1054
+ schema: { tenantId: z.string().describe('Tenant to act on') },
1055
+ resolve: async ({ tenantId }) => ({ tenantId: String(tenantId) }),
1056
+ filter: (_s, m) => m.scope === 'tenant',
1057
+ },
1058
+ })
1059
+ ```
1060
+
1061
+ ## The through-line
1062
+
1063
+ `ctx.tenantId` is the single join point: the **prefix param** puts it there on
1064
+ HTTP, `extend`'s **resolve** puts it there on a tool call. Handlers and the auth
1065
+ rule read it the same way on both surfaces — one contract, every surface, no
1066
+ per-transport tenant plumbing.