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.4.txt CHANGED
@@ -1,4 +1,4 @@
1
- # stitchkit/server — stitchkit docs slice, part 4 of 5
1
+ # stitchkit/server — stitchkit docs slice, part 4 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.
@@ -6,10 +6,11 @@
6
6
 
7
7
  Parts of this slice:
8
8
  - `llms/server.txt`: Guide: HTTP server (docs/guide/server.md)
9
- - `llms/server.2.txt`: Guide: HTTP server (docs/guide/server.md) · Guide: Realtime (docs/guide/realtime.md)
10
- - `llms/server.3.txt`: Guide: Realtime (docs/guide/realtime.md)
11
- - `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)
12
- - `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)
13
14
 
14
15
  Also read:
15
16
  - see `llms/testing.txt` for the Testing & deployment guide
@@ -18,6 +19,202 @@ Also read:
18
19
  # Guide: Realtime (docs/guide/realtime.md) (continued)
19
20
  ==============================================================================
20
21
 
22
+ ## Bring-your-own transport
23
+
24
+ Sometimes the transport is neither HTTP nor Socket.IO — a desktop app whose UI
25
+ webview talks to its own local Bun sidecar over a raw WebSocket, an IPC channel,
26
+ a queue worker. You can still drive it from one `defineContract`: share the
27
+ contract's Zod schemas to validate each inbound frame, run your handlers, and
28
+ reuse the contract metadata below. You own **both** the wire (framing,
29
+ handshake, reconnect) *and* the per-call validate-run loop — stitchkit ships the
30
+ contract and its metadata, not a transport engine. A reliable-RPC-over-raw-
31
+ WebSocket engine would be a competing WebSocket transport
32
+ ([ADR 0008](../decisions/0008-thin-wrappers.md)); the wire stays yours.
33
+
34
+ Two pieces of the contract carry straight over to a bring-your-own lane:
35
+
36
+ - **`source` is an open tag.** `TransportSource` is `'http' | 'mcp' | 'agent' |
37
+ 'cli' | (string & {})`, so a handler or hook can tell your transport's calls
38
+ apart — tag them `source: 'local-ws'` and read `ctx.source`.
39
+ - **`idempotent` drives replay-on-reconnect** — see below.
40
+
41
+ ### Durability — `idempotent` + replay
42
+
43
+ If the sidecar can restart mid-call, the client decides what to do with an
44
+ in-flight request on reconnect from the operation's **idempotency**, declared on
45
+ the contract:
46
+
47
+ ```ts
48
+ export const runtimeContract = defineContract({ prefix: 'runtime' }, {
49
+ 'tasks.setDone': { method: 'POST', path: '/done', desc: '…',
50
+ idempotent: true, input: taskDone, output: ok }, // re-send after reconnect — same result
51
+ 'capture.start': { method: 'POST', path: '/start', desc: '…',
52
+ output: snapshot }, // unset → one-shot, do not re-send
53
+ })
54
+ ```
55
+
56
+ `idempotent` rides through to `MethodDef.idempotent`; the core attaches no
57
+ behaviour. Your reconnect logic reads it: replay an idempotent call (the
58
+ durability guarantee — the user's action is not lost), reject a non-idempotent
59
+ one rather than fire a second side effect. Pair it with
60
+ [sticky events](#sticky-events) (`createRetainedTopics`) so a reconnected client
61
+ also catches up on the latest pushed state.
62
+
63
+ This is deliberately *not* a reliable-RPC engine — that would be a competing
64
+ WebSocket transport ([ADR 0008](../decisions/0008-thin-wrappers.md)). stitchkit
65
+ gives you the contract and the metadata (`idempotent`, the open `source` tag,
66
+ `createRetainedTopics`); the wire and the per-call execution stay yours. See
67
+ [ADR 0028](../decisions/0028-revert-contract-dispatcher.md).
68
+
69
+ ## Authenticated room registry and replay
70
+
71
+ `bindSocketRegistry` composes over `bindRealtimeServer`; it never authenticates
72
+ a socket a second time and never creates another outbound validator. The
73
+ identity in `connection.raw.data` has already passed the Socket.IO handshake.
74
+
75
+ `rooms(identity)` names the rooms a connecting identity may be in; the registry
76
+ joins them and refuses a later `join` to any other. The disconnect listener is
77
+ attached before that lookup is awaited, so a socket that drops while its
78
+ permissions are still being resolved never becomes a member. `registry.room(name)` mints
79
+ the opaque `AuthorizedSocketRoom` for a name — the token proves the name came
80
+ through this registry, not that anyone is in the room, so a room with no open
81
+ tab is an ordinary `emitTo` target that reports zero recipients. The registry
82
+ owns join/leave, multiple sockets per identity, immutable snapshots and
83
+ listener cleanup.
84
+
85
+ Replay is revisioned: while a socket's snapshot is open, frames sent through
86
+ `emitTo` to its rooms are held back and delivered after the snapshot, so the
87
+ socket never sees a delta for state its snapshot already contains, nor a
88
+ snapshot that predates a delta it already received. A snapshot taken across a
89
+ `revision` change is retried up to `replayAttempts` (default 3). The hold-back buffer is
90
+ bounded by `maxBufferedFrames` (default 1000): past it the attempt is abandoned
91
+ and retried, and when the attempts are spent `onResyncRequired(socketId,
92
+ identity)` fires with nothing half-delivered — the application decides what a
93
+ resync means for that socket. A retry relies on the fresh snapshot carrying
94
+ what the abandoned frames carried, which holds when every emitted change also
95
+ moves `revision`; without a `revision` the registry has no way to tell, so
96
+ declare one wherever replay matters. Room tokens are recognised, not
97
+ remembered: a token the application keeps stays valid for the life of the
98
+ registry, and a name seen once does not live on in a map. This ordering exists only for frames that go
99
+ through `emitTo`; a broadcast through `realtime.to(room).emit` reaches the
100
+ socket immediately, replay or not, so keep room traffic whose order matters
101
+ relative to the snapshot on the registry.
102
+
103
+ ## Session-scoped watches and query cache
104
+
105
+ Pass the captured login operation as `createWatchClient(contract, { transport,
106
+ session })`. It adds a lifetime nonce to watch keys and detaches on invalidation;
107
+ a late frame for a previous login cannot match a new client's key on the same socket.
108
+ Both client and server must support the new optional `WatchKey.instance` field.
109
+ The nonce is not authorization: the server still admits a verified identity and
110
+ uses `hub.attach(subscriber, { key: verifiedScope, signal: revocationSignal })`.
111
+ The scope key must change with session and permission boundaries.
112
+
113
+ One scope and one question share one source and one read, however many client
114
+ instances watch it: the hub routes each frame to every instance under its own
115
+ key. A new tab of the same session costs a route, not a read.
116
+
117
+ ### Capacity
118
+
119
+ A hub admits at most `maxSources` sources (1024) and `maxSubscribers` attached
120
+ subscribers (1024); a client holds at most `maxKeys` keys (1024) and
121
+ `maxListenersPerKey` listeners per key (128). Every excess is a refusal, never
122
+ unbounded state: `open` answers `{ accepted: false, reason }` — including for a
123
+ subscriber attached over capacity, whose `attach` returns a watcher that refuses
124
+ every `open` — and a client's `subscribe` throws. A client handle takes its key
125
+ when it subscribes, so handles a render creates and never subscribes cost
126
+ nothing. A connection handler that throws closes that connection and is logged;
127
+ the server goes on. A subscriber attached over capacity is not tracked: its
128
+ refusals stand until it reconnects.
129
+
130
+ A read that fails sends its subscribers `unavailable` / `source-error` with the
131
+ `code` and `message` of an `AppError`, which is written for its caller. Any other
132
+ error reaches only the hub's `logger`; the browser reads `The watched read failed`. Set larger finite limits for larger workloads, and
133
+ `reconcileIntervalMs` when a lost invalidation must recover without a reconnect.
134
+
135
+ `createCacheBridge` can bind watched handles directly:
136
+
137
+ ```ts
138
+ const bridge = createCacheBridge({
139
+ socket, queryClient, handlers: {}, session,
140
+ watched: [{
141
+ handle: watches.list({ folderId }),
142
+ queryKey: ['items', session.id, folderId],
143
+ state: frame => showWatchState(frame),
144
+ }],
145
+ })
146
+ bridge.connect()
147
+ ```
148
+
149
+ A value updates that exact query; non-live state marks it stale while retaining its
150
+ value. The existing phases (`opening`, `live`, `unavailable`, `resync-required`)
151
+ remain the status model. Do not replace unavailable data with an empty collection.
152
+ Session invalidation removes bound queries. Include the session identity in query
153
+ keys and guard any application-level side effects with that same operation.
154
+
155
+ Use existing shared watches for paginated lists and selected-detail queries; bind
156
+ each exact argument set to its query key. No global domain/query registry or new
157
+ UI components are needed. Reconnect and revision/delta recovery remain owned by the
158
+ watch client; silent lost notifications are repaired by hub reconciliation.
159
+
160
+ ## Account-scoped device presence
161
+
162
+ When an account spans multiple online devices (desktop, mobile, web) that advertise typed
163
+ capability state and accept targeted remote commands, mount device presence onto your existing
164
+ `RealtimeServerHandle` instead of opening a second connection:
165
+
166
+ ```ts
167
+ // shared/presence.ts
168
+ import { createDevicePresenceContract } from 'stitchkit/realtime'
169
+ import { z } from 'zod'
170
+
171
+ export const devicePresence = createDevicePresenceContract({
172
+ mic: {
173
+ state: z.strictObject({ recording: z.boolean() }),
174
+ command: z.discriminatedUnion('action', [
175
+ z.strictObject({ action: z.literal('start') }),
176
+ z.strictObject({ action: z.literal('stop') }),
177
+ ]),
178
+ result: z.strictObject({ recording: z.boolean() }),
179
+ },
180
+ })
181
+
182
+ // server (stitchkit/server)
183
+ import { bindDevicePresence } from 'stitchkit/server'
184
+
185
+ const presence = bindDevicePresence(devicePresence, socket, {
186
+ accountOf: (identity) => identity.userId ?? null, // null refuses non-user principals
187
+ })
188
+ // Call presence.readmit(socketId) after logout or permission changes to evict immediately.
189
+
190
+ // device client (stitchkit/realtime)
191
+ import { createDevicePresenceClient } from 'stitchkit/realtime'
192
+
193
+ const client = createDevicePresenceClient(devicePresence, {
194
+ transport,
195
+ device: { deviceId: 'desktop-1', name: 'Desktop', platform: 'macos' },
196
+ capabilities: ['mic'],
197
+ initialStates: { mic: { recording: false } },
198
+ })
199
+
200
+ const offMic = client.onCommand('mic', async (command) => ({
201
+ recording: command.action === 'start',
202
+ }))
203
+
204
+ // Send a typed command from another device in the same account:
205
+ const ack = await client.sendCommand({
206
+ targetDeviceId: 'desktop-1',
207
+ capability: 'mic',
208
+ command: { action: 'stop' },
209
+ })
210
+ ```
211
+
212
+ Each account's online device list is versioned (`revision`), capacity-bounded
213
+ (`maxDevicesPerAccount`), and scoped strictly to `accountOf(handshakeIdentity)`. Local capability
214
+ states are republished automatically after reconnect (`publishState(capability, state | null)`),
215
+ and `createDevicePresenceRelayAdapter` in `stitchkit/realtime` can mirror a `DeviceRelayAgent`'s
216
+ liveness into a `DevicePresenceRelayStateSchema` capability slot.
217
+
21
218
  ## User Device Relay (`stitchkit/device-relay`)
22
219
 
23
220
  `stitchkit/device-relay` is a peer-free evolving entrypoint for reaching a user-owned device behind
@@ -68,1023 +265,3 @@ const agent = createDeviceRelayAgent({
68
265
  reconnected consumer can resume without unbounded hub buffering.
69
266
  - **Horizontal scale:** replace `createMemoryRelayBroker()` with your own `RelayBrokerPort` (for
70
267
  example over Redis or Postgres pub/sub) when multiple server instances hold device sockets.
71
-
72
- ==============================================================================
73
- # Guide: Auth & errors (docs/guide/auth-and-errors.md)
74
- ==============================================================================
75
-
76
- # Auth & errors
77
-
78
- Client-side login/session operations may legitimately answer `401`. Declare
79
- that policy with contract-owned matchers instead of path strings:
80
-
81
- ```ts
82
- const http = createHttpClient({
83
- baseUrl,
84
- suppressUnauthorizedFor: contractEndpointMatchers(publicAuth, ['login', 'verify']),
85
- })
86
- ```
87
-
88
- Only the selected operations suppress the global `unauthorized` event; a 401
89
- from any neighbouring protected route still signals session expiry.
90
-
91
- stitchkit carries no domain model — it does not know what a user is. What it
92
- provides is the *control flow*: a scope on every endpoint, one hook that
93
- enforces it, and one error model shared by every transport. The identity and
94
- the scope vocabulary are yours.
95
-
96
- ## Scopes
97
-
98
- An endpoint declares a `scope` — a free string. The contract `meta.scope` is the
99
- default for endpoints that declare none. (Authored through
100
- [`createContractFactory<Scope>()`](./contracts.md#scope), both the contract's
101
- scope and any endpoint override are held to your own union instead.)
102
-
103
- ```ts
104
- export const posts = defineContract({ prefix: 'posts', scope: 'user' }, {
105
- list: { method: 'GET', path: '/', desc: 'List posts', scope: 'public', output: /* … */ },
106
- create: { method: 'POST', path: '/', desc: 'Create', /* inherits 'user' */ },
107
- remove: { method: 'DELETE', path: '/:id', desc: 'Delete', scope: 'admin' },
108
- })
109
- ```
110
-
111
- The framework attaches no meaning to the strings — `'public'`, `'user'`,
112
- `'admin'` mean whatever your auth hook decides.
113
-
114
- ## `createAuthHook`
115
-
116
- `createAuthHook` builds one scope gate that can run in both HTTP and tool
117
- lifecycles. On HTTP it belongs in `hooks.authorize`: StitchKit validates path
118
- params, resolves identity and scope, and rejects `401`/`403` **before reading a
119
- JSON or multipart body**. On MCP, agent and CLI surfaces it belongs in
120
- `access.gate.beforeHandle` (`access: { gate: { beforeHandle: authHook } }`),
121
- because those transports have already received their
122
- arguments before the common tool runner starts.
123
-
124
- ```ts
125
- import { createAuthHook, createServer } from 'stitchkit/server'
126
-
127
- const authHook = createAuthHook<User>({
128
- resolve: (ctx) => resolveSession(ctx), // → a User, or null
129
- rules: {
130
- public: 'public', // always pass
131
- user: 'authenticated', // any resolved identity passes
132
- admin: (user) => user.isAdmin, // custom predicate
133
- },
134
- inject: (ctx, user) => { ctx.user = user },
135
- })
136
-
137
- createServer({ services, hooks: { authorize: authHook } })
138
- ```
139
-
140
- ### `AuthRule`
141
-
142
- The value of each `rules` entry, keyed by scope:
143
-
144
- - **`'public'`** — always passes; the identity is attached if present.
145
- - **`'authenticated'`** — any resolved identity passes; no identity ⇒ 401.
146
- - **a function** `(identity, ctx) => boolean | contribution`, sync or async — a custom
147
- check. It receives request metadata and validated path params, so a
148
- resource-scoped rule can do a DB lookup. It cannot read `input` or files: the
149
- body has deliberately not been consumed yet. `false` denies, `true` passes,
150
- and a returned plain object passes and contributes inferred handler fields.
151
-
152
- #### Resource-scoped rule — reading a path/prefix param
153
-
154
- For a multi-tenant API (`pathPrefix: '/tenants/:tenantId'`, see
155
- [Route groups → param prefixes](./server.md#param-prefixes-resource-scoped-paths)),
156
- the rule gates access to the tenant in the path. A `:param` from the group prefix
157
- or the endpoint is on the **context root** as `ctx.<name>` (a raw `string`):
158
-
159
- ```ts
160
- const authHook = createAuthHook<User>({
161
- resolve: sessionResolver,
162
- rules: {
163
- public: 'public',
164
- // gate the tenant in the path — ctx.tenantId comes from the group prefix
165
- tenant: async (user, ctx) => userCanAccessTenant(user.id, String(ctx.tenantId)),
166
- } satisfies Record<Scope, AuthRule<User>>,
167
- // derive per-request facts onto ctx for handlers (role within this tenant, …)
168
- inject: async (ctx, user) => {
169
- ctx.user = user
170
- if (user) ctx.tenantRole = await roleInTenant(user.id, String(ctx.tenantId))
171
- },
172
- })
173
- ```
174
-
175
- `inject` runs on every request (identity may be `null`) — use it to put the
176
- identity *and* any derived values (role, parent-id) on `ctx` for handlers. Read
177
- them back as `ctx.tenantRole` (typed `unknown` — narrow at the read site). The
178
- endpoints under the group declare `scope: 'tenant'`.
179
-
180
- When the async authorization lookup already produced handler data, return it
181
- instead of repeating the lookup in `inject` and a handwritten scope map:
182
-
183
- ```ts
184
- const auth = createAuthHook({
185
- resolve: sessionResolver,
186
- rules: {
187
- project: async (user, ctx) => {
188
- const membership = await findMembership(user.id, String(ctx.projectId))
189
- return membership
190
- ? { userId: user.id, projectId: membership.projectId, role: membership.role }
191
- : false
192
- },
193
- },
194
- })
195
-
196
- const implementFor = createScopedImplement<AuthScopes<typeof auth>>()
197
- ```
198
-
199
- Contributions are merged only after full validation. Runtime-owned context keys,
200
- arrays, class instances, accessors, symbols, unsafe prototypes and partial proxy
201
- reads fail without mutating context. `false | object` contributes required
202
- fields; `true | object` correctly makes them optional.
203
-
204
- ### `AuthHookConfig`
205
-
206
- | Field | Purpose |
207
- |-------|---------|
208
- | `resolve` | `(ctx) => identity \| null` — HTTP identity from `ctx.req` (cookie / bearer + lookup) |
209
- | `resolveFromContext` | `(ctx) => identity \| null` — identity on a tool call (no `req`) |
210
- | `rules` | access rule per scope; `endpoint.scope` is the key |
211
- | `defaultScope` | scope applied when an endpoint declares none |
212
- | `inject` | write the resolved identity onto `ctx` for handlers |
213
- | `onAnonymous` | thrown when a scope needs an identity and there is none (default 401) |
214
- | `onForbidden` | thrown when an identity is present but the rule rejects it (default 403) |
215
-
216
- Annotate `rules` with `satisfies Record<MyScope, AuthRule<User>>` so the compiler
217
- catches a scope you forgot to cover. With the scoped rule objects below, widen
218
- the annotation to
219
- `satisfies Record<MyScope, AuthRule<User> | ScopedAuthRule<User, AuthRuleContribution>>`
220
- — it keeps the coverage check and does not disturb the derivation. (When every
221
- scope comes from the derived map, the check is already implicit: a scope missing
222
- from `rules` is no key of the map, and a contract using it fails to compile.)
223
-
224
- ### Scoped rules — the map `createScopedImplement` consumes
225
-
226
- A rule may take an object form, `{ rule, inject }`, where `inject` **returns**
227
- the fields this scope contributes. That return type is a declaration the hook
228
- derives a scope→context map from — feed it to
229
- [`createScopedImplement`](./server.md#per-scope-handler-context--createscopedimplement)
230
- and the map can never drift from the hook, because it is computed from it:
231
-
232
- ```ts
233
- const authHook = createAuthHook({
234
- resolve: sessionResolver, // no explicit generic — let it infer
235
- rules: {
236
- public: { rule: 'public', inject: (user) => ({ userId: user.id }) },
237
- user: { rule: 'authenticated', inject: (user) => ({ userId: user.id }) },
238
- admin: {
239
- rule: (user) => user.admin,
240
- inject: (user) => ({ userId: user.id, isAdmin: user.admin }),
241
- },
242
- },
243
- })
244
-
245
- export const implementFor = createScopedImplement<AuthScopes<typeof authHook>>()
246
- ```
247
-
248
- - A `'public'` rule's fields come out **optional**: public admits the anonymous
249
- caller, it does not refuse to know the logged-in one — `resolve` and `inject`
250
- still run, so a public `me` / `logout` handler reads `ctx.userId` as
251
- `string | undefined` and narrows, instead of being pushed toward a cast by a
252
- `public: object` map.
253
- - Any other rule's fields are required — the rule rejected the request before
254
- the handler if no identity resolved.
255
- - A scope with no rule is no key of the derived map, so a contract using it
256
- fails to compile — the type-level mirror of the hook's fail-closed
257
- `no rule for scope` throw.
258
-
259
- The per-rule `inject` runs after the shared one, only when an identity
260
- resolved, and **before** the rule check — it may run for an identity the rule
261
- then rejects, so keep it pure and synchronous (an async `inject` is a compile
262
- error, and a runtime one for untyped callers: merging a Promise would merge
263
- nothing). Write rule objects inline in `rules` — a hoisted, annotated rule
264
- widens its inject and degrades that scope's fields to `object`.
265
-
266
- Derivation needs the identity generic to be **inferred** (write no explicit
267
- `createAuthHook<User>` — TypeScript has no partial inference); with an explicit
268
- generic, or fields injected outside the hook, keep the hand-written map.
269
- → ADR 0078
270
-
271
- ### Multiple auth domains — `composeAuthHooks`
272
-
273
- Independent identity domains should keep separate resolvers and rules. Compose
274
- their canonical hooks and derive one handler context without a manual dispatcher
275
- or scope-map intersection:
276
-
277
- ```ts
278
- const userAuth = createAuthHook({
279
- resolve: resolveUser,
280
- resolveFromContext: resolveToolUser,
281
- rules: {
282
- user: (user) => ({ userId: user.id }),
283
- workspace: (user) => ({ userId: user.id }),
284
- },
285
- })
286
-
287
- const workspaceAuth = createAuthHook({
288
- resolve: resolveMembership,
289
- resolveFromContext: resolveToolMembership,
290
- rules: {
291
- workspace: (membership) => ({ workspaceId: membership.workspaceId }),
292
- },
293
- })
294
-
295
- export const auth = composeAuthHooks({
296
- hooks: [userAuth, workspaceAuth],
297
- defaultScope: 'user',
298
- })
299
- export const implementFor = createScopedImplement<AuthScopes<typeof auth>>()
300
- ```
301
-
302
- Only hooks that declare the selected scope run. An unknown scope fails closed;
303
- when several hooks own one scope, every owner must pass in declaration order.
304
- Each owner evaluates on an isolated shadow context. StitchKit validates all
305
- changed fields, rejects reserved/unsafe fields and cross-owner key collisions,
306
- then commits the combined contribution once. A rejected or cancelled composite
307
- therefore exposes no partial fields to the handler.
308
-
309
- Isolation is per-key, not deep: a contribution is the set of context keys whose
310
- descriptor changed. Mutating an existing value **in place**
311
- (`ctx.user.role = 'admin'`) edits the object every owner already shares, so it
312
- is neither reported as a contribution nor checked for collisions — contribute
313
- new fields instead of editing another owner's object. External side effects
314
- likewise remain consumer-owned and are not rolled back.
315
-
316
- The composite's `defaultScope` is the only implicit scope. A child hook's own
317
- default must be absent or equal to it, so reordering hooks cannot change which
318
- scope protects an endpoint.
319
-
320
- ### Auth on the tool surface — `resolveFromContext`
321
-
322
- The same hook guards every transport, but the lifecycle slot and identity
323
- source differ:
324
-
325
- - **HTTP** — `hooks.authorize` calls `resolve(ctx)` from `ctx.req` (a cookie or
326
- bearer token) before body parsing.
327
- - **Tool calls (MCP / agent)** — there is no `req`. The transport authenticated
328
- the caller (an MCP API key) and `buildMcpServer`'s `context` injected the
329
- identity into `ctx`. `access.gate.beforeHandle` calls
330
- `resolveFromContext(ctx)` to locate it.
331
-
332
- ```ts
333
- const authHook = createAuthHook<User>({
334
- resolve: (ctx) => resolveSession(ctx), // HTTP — from ctx.req
335
- resolveFromContext: (ctx) => ctx.user ?? null, // tool — from injected ctx
336
- rules: { public: 'public', user: 'authenticated', admin: (u) => u.isAdmin },
337
- })
338
- ```
339
-
340
- The **scope check is identical** on both surfaces — only identity resolution
341
- differs. If you omit `resolveFromContext`, a scoped tool call has no identity
342
- and **fails closed** (rejected by `onAnonymous`) — the hook never silently
343
- passes a tool call it cannot authenticate. → [ADR 0014](../decisions/0014-tool-http-parity.md)
344
-
345
- ```ts
346
- createServer({ services, hooks: { authorize: authHook } })
347
- createMcpHandler({ services, access: { gate: { beforeHandle: authHook } } })
348
- ```
349
-
350
- ## `createBearerResolver`
351
-
352
- For API-key or bearer-token auth (the usual MCP case), `createBearerResolver`
353
- strips `Authorization: Bearer <token>` and hands the raw token to your lookup:
354
-
355
- ```ts
356
- import { createBearerResolver } from 'stitchkit/server'
357
-
358
- const resolve = createBearerResolver<User>({
359
- lookup: (token, req) => db.apiKeys.resolve(token), // → User, or null
360
- })
361
- ```
362
-
363
- Use it as `createMcpHandler`'s `auth`, or inside `createAuthHook`'s `resolve`.
364
-
365
- ## JWT
366
-
367
- `verifyJwt(token, secret)` verifies an HS256 JWT and returns its payload, or
368
- throws `unauthorized`. It pins the algorithm (the token's own `alg` can never
369
- pick the scheme), checks `exp` and `nbf`, and **requires `exp`**: a token
370
- without one would stay valid for as long as the secret does. Pass
371
- `expiration: 'optional'` only for tokens whose lifetime you bound elsewhere (a
372
- session row, a revocation list); a present `exp` is still enforced. Sign with
373
- `signJwt(payload, secret, { expiresInSec })`.
374
-
375
- ```ts
376
- import { verifyJwt, extractToken } from 'stitchkit/server'
377
- import { env } from './env'
378
-
379
- const token = extractToken(req) // from Authorization, or a cookie name
380
- if (!token) throw unauthorized('Bearer token is required')
381
- const payload = await verifyJwt(token, env.JWT_SECRET)
382
- ```
383
-
384
- `extractToken(req, cookieName?)` reads a bearer token from the `Authorization`
385
- header, or from the named cookie.
386
-
387
- ## Signed links
388
-
389
- `<audio src>`, `<img src>` and a plain navigation send no `Authorization` header, so an endpoint
390
- that serves private bytes cannot see the page's session. The server signs a short-lived link
391
- instead, and the endpoint's auth gate accepts it:
392
-
393
- ```ts
394
- import { createAuthHook, signLink, verifySignedLink } from 'stitchkit/server'
395
-
396
- // Where the page asks for the recording: a link it can put in `<audio src>`.
397
- const src = await signLink({
398
- secret: env.MEDIA_LINK_SECRET, method: 'GET',
399
- url: `/media/${recordingId}?for=${userId}`, expiresInSeconds: 300,
400
- })
401
-
402
- // The `rawResponse` endpoint under `scope: 'viewer'` needs no guard of its own.
403
- const auth = createAuthHook<Viewer>({
404
- resolve: async (ctx) => {
405
- if (ctx.req) {
406
- const link = await verifySignedLink(ctx.req, { secret: env.MEDIA_LINK_SECRET })
407
- if (link.ok) return { userId: new URL(ctx.req.url).searchParams.get('for') }
408
- }
409
- return resolveSession(ctx)
410
- },
411
- rules: { viewer: 'authenticated' },
412
- })
413
- ```
414
-
415
- `signLink` appends `expires` (Unix seconds) and `signature`, an HMAC-SHA-256 over the method, the
416
- path and every other query parameter, so a link opens one request: another path, method or edited
417
- parameter is `forged`. What the link is for — whose recording — rides in a parameter you add, and
418
- the signature covers it. Nothing is stored; rotating the secret ends every link at once. The host
419
- is not signed, so a proxy may change the origin, but the path and query must reach the server as
420
- they were signed. A lifetime is 1 second to `MAX_SIGNED_LINK_SECONDS` (seven days); a secret
421
- shorter than 32 characters throws. `verifySignedLink` returns `{ ok: true, expiresAt }` or a
422
- `reason` — `unsigned`, `malformed`, `forged`, `expired` — and a raw route calls it the same way.
423
- A link is a bearer credential until it expires: anyone holding it opens that one request.
424
-
425
- ## Telegram Mini Apps
426
-
427
- A Mini App hands its backend an `initData` query string that Telegram signed
428
- with a key derived from the bot token. `verifyTelegramInitData` checks that
429
- signature and reports what the string says — and refuses with a **reason**,
430
- because an application answers a stale string differently from a forged one.
431
-
432
- ```ts
433
- import { verifyTelegramInitData } from 'stitchkit/telegram'
434
- import { unauthorized } from 'stitchkit/contract'
435
- import { env } from './env'
436
-
437
- const result = await verifyTelegramInitData({
438
- initData,
439
- botToken: env.BOT_TOKEN,
440
- maxAgeSeconds: 3600, // default: one day
441
- })
442
- if (!result.valid) {
443
- // 'missing-hash' | 'signature-mismatch' | 'malformed' | 'expired'
444
- throw unauthorized(result.reason === 'expired' ? 'Reopen the app' : 'Invalid session')
445
- }
446
- const telegramId = result.data.user?.id
447
- ```
448
-
449
- Three things it does that a hand-written check usually does not:
450
-
451
- - the **signature is checked first**, before `auth_date` or anything else is
452
- read — an expiry inside an unverified payload is a number the sender chose;
453
- - digests are compared **without an early exit**, so the time a rejection takes
454
- is not a measurement of how much of the digest was right;
455
- - `raw` keeps every signed pair, so a field Telegram adds after this release
456
- does not need a release to reach.
457
-
458
- The user arrives `camelCase` — `firstName`, `languageCode` — as `TelegramUser`.
459
- A bot meets the same person as grammY's `ctx.from`, in Telegram's `snake_case`;
460
- `parseTelegramUser(ctx.from)` gives the same `TelegramUser`, so one
461
- `ensureAccount(user)` serves the Mini App and the chat.
462
-
463
- `maxAgeSeconds` defaults to one day (`86400`): a signed string is otherwise a
464
- credential that never expires, so there is no unbounded mode. Set the lifetime
465
- your session is worth — shorter for a sign-in exchange, longer for a Mini App
466
- kept open for days.
467
-
468
- The module is server-only and pulls in no bot library — the token never belongs
469
- in a browser bundle. `stitchkit/application/grammy` remains the lifecycle
470
- adapter for an injected grammY bot. Its companion,
471
- `classifyTelegramSendFailure`, names why a send was refused and separates *retry
472
- this send* from *stop addressing this recipient*:
473
-
474
- ```ts
475
- import { classifyTelegramSendFailure } from 'stitchkit/telegram'
476
-
477
- try {
478
- await bot.api.sendMessage(chatId, text)
479
- } catch (error) {
480
- const failure = classifyTelegramSendFailure(error)
481
- if (failure.recipientUnreachable) await markUnreachable(chatId, failure.reason)
482
- else if (failure.retryable) await requeue(chatId, failure.retryAfterSeconds)
483
- }
484
- ```
485
-
486
- The two flags are separate because one answer cannot serve both. A rate limit is
487
- retryable and implicates nobody; a blocked user is unreachable and no retry
488
- helps; a message Telegram could not parse is *neither* — the recipient is fine
489
- and our payload is wrong, which is the case a list of substrings quietly counts
490
- against the user. An unrecognised refusal leaves the recipient reachable: losing
491
- a working subscriber forever costs more than one wasted send.
492
-
493
- `bot-to-bot-disabled` is permanent but deliberately not `recipientUnreachable`:
494
- Telegram returns it when either bot has not enabled Bot to Bot messaging, so the
495
- missing setting may be the sender's. Do not retry it, and do not close the
496
- recipient's row on it.
497
-
498
- `TELEGRAM_SEND_FAILURE_REASONS` lists every reason. A table keyed by
499
- `TelegramSendFailureReason` — error codes, the text a person reads — fails to
500
- compile when a release adds one, instead of falling through to a default:
501
-
502
- ```ts
503
- const codes: Record<TelegramSendFailureReason, string> = {
504
- 'blocked-by-user': 'E_BLOCKED',
505
- /* … every reason … */
506
- }
507
- ```
508
-
509
- The rest of what a bot is assembled from — its resources, journal, operator
510
- channel, broadcasts and local Bot API files — is in [Telegram bots](telegram.md).
511
-
512
- ## Cookies
513
-
514
- ```ts
515
- import { defineCookie } from 'stitchkit/server'
516
-
517
- const session = defineCookie({ name: 'sid', httpOnly: true, secure: true, sameSite: 'Lax', path: '/' })
518
-
519
- session.get(req) // string | undefined
520
- session.set('abc123') // → a Set-Cookie header value
521
- session.clear() // → a Set-Cookie value that expires it
522
- ```
523
-
524
- `defineCookie` bundles a cookie's name and options into a typed handle, so the
525
- config is not repeated at every call site. `parseCookies(header)`,
526
- `parseCookieHeader(header)` and `serializeCookie(name, value, opts)` are the
527
- lower-level primitives.
528
-
529
- **Two cookies, one name.** A browser sends every cookie whose domain and path
530
- match, so a `sid` on `.example.com` and a `sid` on `app.example.com` both arrive
531
- — in an order the browser chooses (RFC 6265 §5.4) and a server should not rely
532
- on (§4.2.2). `get` returns the **last** one by default, which is a fact of the
533
- header order, not a rule: the same session then validates in one browser and
534
- not in another. Name the behaviour you rely on, or refuse to guess:
535
-
536
- ```ts
537
- const session = defineCookie({ name: 'sid', domain: '.example.com', duplicates: 'reject' })
538
-
539
- session.get(req) // undefined when two *different* values arrive; the one value when they agree
540
- session.getAll(req) // every candidate, in header order — validate each, clear the loser
541
- ```
542
-
543
- `duplicates: 'reject'` turns the lottery into "no session", which a login page
544
- handles; `'first'` and `'last'` exist so an application can state which coin it
545
- flips. For a session cookie on a parent domain the durable fix is `getAll`:
546
- validate each candidate and answer with `clear()` for the one that lost, so the
547
- next request carries one.
548
-
549
- To set a cookie from a schema-validated JSON endpoint without losing its typed
550
- client result, declare [`responseMeta`](./server.md#typed-json-response-metadata)
551
- and append the generated value:
552
-
553
- ```ts
554
- complete: async ({ response }) => {
555
- response.headers.append('Set-Cookie', session.set('abc123'))
556
- return authenticatedUser
557
- }
558
- ```
559
-
560
- Append once per cookie; StitchKit preserves separate `Set-Cookie` fields through
561
- both Bun and Node. Cookie/session policy remains application logic.
562
-
563
- ## The error model
564
-
565
- One error type, `AppError`, is shared by the contract, the server and the
566
- client. It carries a stable `code`, an HTTP `status`, and optional structured
567
- `details` and a `hint`.
568
-
569
- ### Throwing errors
570
-
571
- Throw `AppError` directly, or use a typed helper — the idiomatic path:
572
-
573
- | Helper | Status | Code |
574
- |--------|--------|------|
575
- | `notFound(message?)` | 404 | `NOT_FOUND` |
576
- | `badRequest(message, details?)` | 400 | `BAD_REQUEST` |
577
- | `unauthorized(message?)` | 401 | `UNAUTHORIZED` |
578
- | `forbidden(message?)` | 403 | `FORBIDDEN` |
579
- | `conflict(message?, details?)` | 409 | `CONFLICT` |
580
- | `rateLimited(message?)` | 429 | `RATE_LIMITED` |
581
- | `throw new AppError(code, { message?, details?, status? })` | `STITCH_ERROR_STATUS[code]`, else 500 | any `code` |
582
-
583
- ```ts
584
- import { notFound, badRequest } from 'stitchkit/server'
585
-
586
- const note = db.get(ctx.params.id)
587
- if (!note) notFound('Note not found')
588
- if (ctx.input.title.length > 200) badRequest('Title too long', { max: 200 })
589
- ```
590
-
591
- Each helper has a `never` return type — TypeScript knows execution stops, so the
592
- code after it is correctly narrowed.
593
-
594
- You can subclass `AppError` for a domain error model (`class FeatureLocked extends
595
- AppError`). `AppError.is(err)` identifies any instance — a direct one, a subclass,
596
- even a copy from another bundle chunk or realm — by a global brand rather than
597
- `instanceof`, so a domain error keeps its `code` / `details` / `hint` on every
598
- transport (HTTP, MCP, agent). → ADR 0032.
599
-
600
- ### The error envelope
601
-
602
- `AppError.toJSON()` renders the public envelope every transport returns:
603
-
604
- ```json
605
- { "error": { "code": "NOT_FOUND", "message": "Note not found" } }
606
- ```
607
-
608
- `details` and `hint` are included when present. On HTTP this is the response
609
- body with the matching status; for an MCP or agent call the same `code` and
610
- `details` come back as a tool error. A schema-validation failure on the request
611
- is turned into a `400 VALIDATION_ERROR` automatically — and it carries the
612
- offending fields as structured `details.issues`, so a machine client matches on
613
- them instead of parsing the text `message`:
614
-
615
- `path` and `code` are the framework's. **`message` is not** — it is `issue.message`
616
- as Zod produced it, so for a `.refine()` it is whatever the schema's author wrote.
617
- The framework never puts a submitted value into it, and its own messages describe
618
- types rather than values (`expected string, received undefined`, `Invalid UUID`),
619
- but that is a property of today's messages, not a guarantee anyone is in a
620
- position to make: the text belongs to whoever declared the schema. Forward `path`
621
- and `code` to an end user freely; treat `message` as internal unless you wrote
622
- every refine in the contract.
623
-
624
- ```json
625
- {
626
- "error": {
627
- "code": "VALIDATION_ERROR",
628
- "message": "name: Invalid input\nage: Invalid input",
629
- "details": {
630
- "issues": [
631
- { "path": "name", "code": "invalid_type", "message": "Invalid input" },
632
- { "path": "age", "code": "invalid_type", "message": "Invalid input" }
633
- ]
634
- }
635
- }
636
- }
637
- ```
638
-
639
- Use the exported `zodIssues(error)` to build the same structured list from a
640
- `ZodError` in your own hook.
641
-
642
- ### On the client
643
-
644
- The client parses that envelope back into an `ApiError` with the same `code`,
645
- `status`, `details` and `hint`, plus the response `x-request-id` as optional
646
- readonly `traceId` — see [Typed client → ApiError](./client.md#apierror). The
647
- error round-trips without adding correlation data to the response body.
648
-
649
- ### Stitch codes vs your codes
650
-
651
- A `code` is a free string — your app codes (`BOT_NOT_FOUND`, …) are yours and the
652
- core never models them (ADR 0002). But stitchkit itself emits a set of its own:
653
- `BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `UNKNOWN_OPERATION`,
654
- `METHOD_NOT_ALLOWED`,
655
- `CONFLICT`, `RATE_LIMITED`, `REQUEST_ABORTED`, `REQUEST_TIMEOUT`,
656
- `VALIDATION_ERROR`, `FILE_INVALID_PATH`,
657
- `FILE_OUTSIDE_ROOT`, `FILE_NOT_FOUND`, `FILE_NOT_REGULAR`,
658
- `FILE_INSPECTION_REJECTED`, `FILE_TOO_LARGE`, `FILE_EXISTS`,
659
- `REALTIME_CONTRACT_VIOLATION`, `APPLICATION_NOT_ACCEPTING`, `NOT_IMPLEMENTED`,
660
- `WAIT_TIMEOUT`,
661
- `WAIT_FAILED`, `CLI_COMMAND_UNAVAILABLE`, `CLI_PRESENTATION_FAILED`, `DOWNLOAD_NOT_FOUND`, `VIEW_HTTP_ERROR`,
662
- `CONNECTION_TIMEOUT`, `CONNECTION_RESPONSE_TOO_LARGE`,
663
- `CONNECTION_REQUEST_FAILED`, `HTTP_ERROR`, `UPSTREAM_TOOL_ERROR`, `MCP_STRUCTURED_CONTENT_MISSING`,
664
- `OPERATION_NOT_SUCCEEDED`, `OPERATION_BUSY`, `OPERATION_RESPONSE_TOO_LARGE`,
665
- `OPERATION_PROCESS_FAILED`, `STREAM_ITEM_INVALID`, `STREAM_FRAME_TOO_LARGE`,
666
- `STREAM_TERMINAL_MISSING`, `STREAM_LIFETIME_EXCEEDED`,
667
- `GRAMMY_WEBHOOK_NOT_ACCEPTING`, `SANDBOX_UNAVAILABLE`, `SANDBOX_INSUFFICIENT`,
668
- `SPILL_REFERENCE_UNKNOWN`, `INTERNAL_SERVER_ERROR` — a set that grows in
669
- ordinary releases, each addition named in the changelog. They are
670
- published as **`STITCH_ERROR_STATUS`** (the `code → status` map) and
671
- **`StitchErrorCode`** (its `keyof`), with **`isStitchErrorCode()`** (→ ADR 0026).
672
-
673
- > This list is enumerated here for reading, and the enumeration is what goes
674
- > stale — it once dropped `APPLICATION_NOT_ACCEPTING`, which made the map below
675
- > stop compiling. `Object.keys(STITCH_ERROR_STATUS)` is the answer that cannot;
676
- > `packages/core/tests/error-registry-completeness.test.ts` keeps the registry
677
- > itself complete against the source.
678
-
679
- If you translate stitch's framework errors into your own wire codes in an
680
- `onError` hook, you choose how the set's growth reaches you. Keying the map by
681
- `StitchErrorCode` makes it exhaustive, so a code stitch adds or renames becomes
682
- a compile error rather than an unfamiliar code on your wire — worth it when the
683
- envelope is a published contract, at the cost of an edit on those releases:
684
-
685
- ```ts
686
- // Exhaustive on purpose: the annotation is what turns a new stitch code into a
687
- // compile error here. Drop it (or use `satisfies` on a partial map) to let an
688
- // unmapped code travel as itself instead.
689
- // `Partial`, not an exhaustive `Record`: the set grows in ordinary releases, and
690
- // a map written exhaustively stops compiling on every addition. Codes you leave
691
- // out fall through to `unmappedCode`.
692
- const STITCH_TO_APP: Partial<Record<StitchErrorCode, AppCode>> = {
693
- NOT_FOUND: 'NOT_FOUND', UNKNOWN_OPERATION: 'NOT_FOUND',
694
- METHOD_NOT_ALLOWED: 'METHOD_NOT_ALLOWED',
695
- BAD_REQUEST: 'VALIDATION_ERROR', VALIDATION_ERROR: 'VALIDATION_ERROR',
696
- UNAUTHORIZED: 'UNAUTHORIZED', FORBIDDEN: 'FORBIDDEN', CONFLICT: 'CONFLICT',
697
- RATE_LIMITED: 'RATE_LIMITED', INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR',
698
- REALTIME_CONTRACT_VIOLATION: 'INTERNAL_SERVER_ERROR',
699
- FILE_INVALID_PATH: 'VALIDATION_ERROR', FILE_OUTSIDE_ROOT: 'VALIDATION_ERROR',
700
- FILE_NOT_FOUND: 'NOT_FOUND', FILE_NOT_REGULAR: 'VALIDATION_ERROR',
701
- FILE_INSPECTION_REJECTED: 'VALIDATION_ERROR', FILE_TOO_LARGE: 'VALIDATION_ERROR',
702
- FILE_EXISTS: 'CONFLICT',
703
- }
704
- onError: (ctx, err) => {
705
- if (AppError.is(err) && isStitchErrorCode(err.code)) {
706
- return jsonError(STITCH_TO_APP[err.code], err.status) // keep stitch's status
707
- }
708
- // … your own AppError / normalizeError path
709
- }
710
- ```
711
-
712
- ## One application vocabulary and one wire map
713
-
714
- `defineErrors` can also resolve StitchKit's framework codes into the same
715
- application vocabulary. A status fallback is explicit because several
716
- application codes may legally share one HTTP status:
717
-
718
- ```ts
719
- const vocabulary = defineErrors(
720
- {
721
- VALIDATION_ERROR: { status: 400, message: 'Invalid request' },
722
- INTERNAL_ERROR: { status: 500, message: 'Internal error' },
723
- },
724
- {
725
- fallback: { 400: 'VALIDATION_ERROR', 500: 'INTERNAL_ERROR' },
726
- map: { FILE_TOO_LARGE: 'VALIDATION_ERROR' },
727
- },
728
- )
729
-
730
- const onError = createErrorHook({ vocabulary })
731
- // `vocabulary` *is* the wire map: `codeMap` and `unmappedCode` cannot sit
732
- // beside it — the type forbids the combination and the runtime refuses it.
733
- // A `map` target must be declared under the framework code's own status
734
- // (`NOT_FOUND` → a 404 code, never a 410 one): the wire keeps the framework
735
- // status and carries your code, so `defineErrors` refuses the mismatch where
736
- // it already refuses a `fallback` under the wrong status.
737
- ```
738
-
739
- An explicit per-code `map` wins over a status fallback. With
740
- `exhaustive: true`, `map` must be a complete `Record<StitchErrorCode, AppCode>`
741
- at compile time. Transport boundaries identify errors with `AppError.is`, not
742
- `instanceof`, so two bundled copies still agree.
743
-
744
- ## Domain errors — `defineErrors`
745
-
746
- Declare each domain code, HTTP status, default message and optional
747
- structured-details schema in one immutable registry. The generated functions
748
- construct typed branded `AppError` instances; ordinary `throw` remains explicit
749
- at the call site:
750
-
751
- ```ts
752
- import { z } from 'zod'
753
-
754
- export const { errors, codes, definitions, isCode } = defineErrors({
755
- SESSION_NOT_FOUND: { status: 404, message: 'No such session' },
756
- QUOTA_EXCEEDED: {
757
- status: 429,
758
- message: 'Monthly quota exhausted',
759
- details: z.object({ retryAfterSeconds: z.number().int().positive() }),
760
- },
761
- })
762
-
763
- throw errors.SESSION_NOT_FOUND() // uses the declared message
764
- throw errors.QUOTA_EXCEEDED({
765
- message: 'Try later', // overrides it here only
766
- details: { retryAfterSeconds: 30 },
767
- hint: 'Wait for the current window to expire',
768
- })
769
-
770
- // Construction without throwing is useful for composition or inspection.
771
- const error = errors.QUOTA_EXCEEDED({ details: { retryAfterSeconds: 30 } })
772
- definitions.QUOTA_EXCEEDED.status // 429 — same source, no copied status map
773
- definitions[code].message // the declared text, by a `code` variable
774
-
775
- // client — match the code, never a magic string
776
- if (err instanceof ApiError && err.code === codes.SESSION_NOT_FOUND) { … }
777
- ```
778
-
779
- `message` is optional: declare it once instead of repeating the sentence at every
780
- `throw`, and a per-call `message` still wins. A code without one keeps the
781
- existing fallback — `AppError.message` is the code itself. An empty declared
782
- message is rejected when the registry is declared, not when the error is thrown.
783
-
784
- **The tool envelope has no `message` field**, and what the model sees depends on
785
- whether the code declares `details`:
786
-
787
- | | HTTP / typed client | MCP / agent / CLI |
788
- |---|---|---|
789
- | code **with** a `details` schema | the declared message | no text at all — only `details` and `hint` |
790
- | code **without** one | the declared message | the same text, delivered as `details.message` |
791
-
792
- The model-facing envelope is `{ error, retryable, details?, _hint? }`; for a code with no
793
- details schema the framework fills `details` with `{ message }`, so declaring a
794
- message changes what the model reads there; without one it is the code itself. Put
795
- anything the model must reliably read in `details` or `hint`, not in `message`.
796
-
797
- With no `details` schema, the options object forbids `details`. A required
798
- `z.object` makes `details` required; `z.object(...).optional()` makes it
799
- optional. Supplied details are parsed when the error is constructed, before any
800
- transport sees them. `code` remains literal and the parsed details type is
801
- retained on the returned `AppError`.
802
-
803
- HTTP renders the complete code/status/message/details/hint. Tool transports keep
804
- their established model-facing projection (code/details/hint, without HTTP
805
- status), while `invokeOrThrow` recovers the exact normalized `AppError`. The
806
- codes and schemas remain application-owned; StitchKit stays domain-free.
807
-
808
- ### The codes an operation refuses with
809
-
810
- An endpoint names the domain codes it can refuse with in `refuses`, by listing the
811
- factories `defineErrors` returned. Every factory carries its `code` and
812
- `definition`, so the list is the declaration — no second string list to drift:
813
-
814
- ```ts
815
- const { errors } = defineErrors({
816
- NOT_IDLE: { status: 409, message: 'Session is busy' },
817
- MIN_AWAKE: { status: 409, details: z.object({ profile: z.string(), minimum: z.number().int() }) },
818
- PROFILE_UNAVAILABLE: { status: 503 },
819
- })
820
-
821
- export const sessions = defineContract({ prefix: 'session' }, {
822
- sleep: {
823
- method: 'POST', path: '/sleep', desc: 'Put a session to sleep',
824
- input: z.object({ id: z.string() }),
825
- output: z.object({ ok: z.boolean() }),
826
- refuses: [errors.NOT_IDLE, errors.MIN_AWAKE],
827
- },
828
- })
829
- ```
830
-
831
- One declaration, three readers:
832
-
833
- - **The server holds the handler to it.** An `AppError` whose code the operation
834
- did not declare — and that is no framework code (`NOT_FOUND`, `FORBIDDEN`, …) —
835
- leaves as `INTERNAL_SERVER_ERROR` (500) with the message `Operation session.sleep
836
- failed with a code it does not declare`, on HTTP, MCP, the agent surface, the CLI
837
- and mid-stream alike, exactly as an output that breaks its schema does. The
838
- original error stays on `cause`, so `onError` and the logs still see it; the
839
- caller does not. An `implementRemote` proxy is held to the same list even when its
840
- origin is not. A failure that is no `AppError` keeps its usual handling, and an
841
- operation without `refuses` runs unchanged.
842
- - **The typed client reads it.** [`client.sleep.refusal(error)`](client.md#read-a-refusal-the-operation-declared)
843
- narrows `code` to the declared codes plus the framework and client codes, and
844
- types `details` by the code's schema.
845
- - **The descriptor carries it** for a reader without types: `MethodDef.refuses`
846
- (code, status, retryability, message, details schema), `x-stitchkit-refusals`
847
- with one response per declared status in OpenAPI, `refusals` in the surface
848
- manifest, and the contract fingerprint. Each changes only for an operation that
849
- declares `refuses`.
850
-
851
- `defineContract` refuses an entry that is not a factory from `defineErrors` (a bare
852
- code string) and a code listed twice, naming the endpoint and the index.
853
- Declaring is opt-in per operation: start with the operations whose callers branch
854
- on a code. → ADR 0330
855
-
856
- ## `createErrorHook`
857
-
858
- `createErrorHook` is the code-map above, packaged — you supply a `codeMap` and
859
- the envelope shape, it does the normalisation (including the
860
- never-leak-an-internal-message rule for a raw throw):
861
-
862
- ```ts
863
- const onError = createErrorHook({
864
- // Map the codes you have an opinion about.
865
- codeMap: {
866
- BAD_REQUEST: 'bad_request', VALIDATION_ERROR: 'bad_request',
867
- UNAUTHORIZED: 'unauthenticated', FORBIDDEN: 'forbidden',
868
- NOT_FOUND: 'not_found', UNKNOWN_OPERATION: 'not_found',
869
- METHOD_NOT_ALLOWED: 'not_found',
870
- CONFLICT: 'conflict', RATE_LIMITED: 'rate_limited',
871
- INTERNAL_SERVER_ERROR: 'internal',
872
- },
873
- // Optional: one public vocabulary entry for every other stitchkit code.
874
- // A resolver `(code) => ...` is also accepted for grouping code families.
875
- unmappedCode: 'framework_error',
876
- // `ctx` is the request's RuntimeContext — read `ctx.traceId` for a
877
- // correlation id in the envelope. Declaring it is optional.
878
- render: (info, ctx) => ({
879
- ok: false,
880
- error: { code: info.code, message: info.message },
881
- traceId: ctx.traceId,
882
- }),
883
- })
884
-
885
- createServer({ services, hooks: { onError } })
886
- ```
887
-
888
- `codeMap` is partial: map the codes you have an opinion about. By default a
889
- stitchkit code you did not list travels as itself. Set `unmappedCode` to one
890
- wire-code when your public vocabulary has a catch-all, or to a function such as
891
- `(code) => code.startsWith('FILE_') ? 'storage_error' : 'framework_error'` when
892
- framework code families need different buckets. An explicit `codeMap` entry
893
- always wins. Codes your project throws itself do not belong to StitchKit's
894
- vocabulary, so they never pass through this fallback and remain unchanged.
895
-
896
- One `satisfies` is the **opt-in** to the stricter deal:
897
-
898
- ```ts
899
- codeMap: { /* … every code … */ } satisfies Record<StitchErrorCode, string>,
900
- ```
901
-
902
- That makes the map exhaustive on your side, so a release that adds a code stops
903
- your build until you decide what the new code is called on your wire. Take it
904
- when your envelope is a published contract and a code surfacing in stitchkit's
905
- spelling would violate it; leave it off when passing one through is fine.
906
- Neither choice is silent — the changelog names every added code.
907
-
908
- Both `onError` and `render` may be asynchronous and receive the matched endpoint
909
- as their final argument. The observer is awaited before rendering, so it can
910
- resolve identity or enrich the request context even for failures raised before
911
- `beforeHandle`:
912
-
913
- ```ts
914
- const onError = createErrorHook({
915
- onError: async (_error, _info, ctx, endpoint) => {
916
- await attributeFailedRequest(ctx, endpoint)
917
- },
918
- render: (info, ctx) => ({
919
- error: { code: info.code },
920
- actorId: ctx.actorId,
921
- }),
922
- })
923
- ```
924
-
925
- `endpoint` is `undefined` when the failure happened before route resolution.
926
- Synchronous callbacks and renderers that declare fewer parameters continue to
927
- work normally.
928
-
929
- Input that fails the contract's `params` / `input` schema reaches `render` as
930
- `VALIDATION_ERROR` 400 — a client fault is an honest 400, not a 500 — and the
931
- offending fields arrive as structured `info.details.issues`, so your `render`
932
- can surface them to a machine client without parsing the message.
933
-
934
- Only the contract boundary produces `VALIDATION_ERROR`. A `ZodError` your
935
- handler throws — parsing an upstream answer, a database row, a config value —
936
- is the server's own schema failing: it is answered as `INTERNAL_SERVER_ERROR`
937
- 500 with the generic message, and the `ZodError` text goes to the log and the
938
- audit row, never to the caller. To refuse the caller's input from inside a
939
- handler, throw `badRequest(message, details)` (or an `AppError`) yourself.
940
-
941
- If you write a **bespoke** `onError` instead of using `createErrorHook`, run the
942
- thrown value through the exported `normalizeError` to get the same classification.
943
- Invalid input reaches your hook as an `AppError` with code `VALIDATION_ERROR`,
944
- its `details.issues` and the `ZodError` as `cause`:
945
-
946
- ```ts
947
- import { normalizeError } from 'stitchkit/server'
948
-
949
- onError: (ctx, err) => {
950
- const e = normalizeError(err) // AppError as is (VALIDATION_ERROR 400 for input), else generic 500
951
- return jsonError(e.code, e.status, e.message)
952
- }
953
- ```
954
-
955
- ==============================================================================
956
- # Guide: Multi-tenant (docs/guide/multi-tenant.md)
957
- ==============================================================================
958
-
959
- # Multi-tenant / resource-scoped paths
960
-
961
- A walkthrough of one mainstream scenario end-to-end: a SaaS API scoped by a path
962
- segment — `/tenants/:tenantId/widgets/...` — where the same `tenantId` gates
963
- access in auth and is injected into tool calls (one API key → many tenants).
964
-
965
- Every piece below already exists; this recipe wires them into one flow. Each step
966
- links to its reference section.
967
-
968
- ## 1. The contract — tenant-agnostic
969
-
970
- Endpoints know nothing about the tenant; the path segment lives on the group, not
971
- the endpoint:
972
-
973
- ```ts
974
- export const widgets = defineContract(
975
- { prefix: 'widgets', scope: 'tenant' },
976
- {
977
- list: { method: 'GET', path: '/', desc: 'List widgets', output: WidgetList },
978
- create: { method: 'POST', path: '/', desc: 'Create a widget', input: NewWidget, output: Widget },
979
- },
980
- )
981
- ```
982
-
983
- ## 2. The server — a param prefix
984
-
985
- Mount the service under a group whose `pathPrefix` carries `:tenantId`. The
986
- matched value is on the context root as `ctx.tenantId`
987
- ([details](./server.md#param-prefixes-resource-scoped-paths)):
988
-
989
- ```ts
990
- createServer({
991
- groups: [
992
- { pathPrefix: '/tenants/:tenantId', services: [widgetsService], hooks: { authorize: authHook } },
993
- ],
994
- })
995
- // → /tenants/:tenantId/widgets
996
- ```
997
-
998
- With more than one scope, let **`scopePrefixes`** map `scope → prefix` and mount
999
- the flat `services` list — no hand-partitioning, the mapping lives in one place
1000
- ([details](./server.md#scope-driven-mounting-scopeprefixes), → ADR 0024):
1001
-
1002
- ```ts
1003
- createServer({
1004
- services, // mixed scopes, listed once
1005
- scopePrefixes: { tenant: 'tenants/:tenantId', project: 'projects/:projectId' },
1006
- hooks: { authorize: authHook },
1007
- })
1008
- // `tenant`-scoped → /tenants/:tenantId/..., `project` → /projects/:projectId/..., the rest flat
1009
- ```
1010
-
1011
- Handlers read `ctx.tenantId` (a raw `string` — narrow it). To get it typed inside
1012
- `ctx.params`, add `tenantId` to the endpoint's `params` schema (a `z.strictObject`
1013
- that omits it will reject the request). When each scope guarantees different
1014
- injected fields, declare the scope map once with
1015
- [`createScopedImplement`](./server.md#per-scope-handler-context--createscopedimplement):
1016
-
1017
- ```ts
1018
- export const implementFor = createScopedImplement<{
1019
- public: object
1020
- tenant: { tenantId: string; userId: string }
1021
- project: { projectId: string; userId: string }
1022
- }>()
1023
- ```
1024
-
1025
- Each handler is then typed by its endpoint's effective scope — no superset
1026
- context that promises a `tenantId` a `public` handler never receives. A contract
1027
- that mixes scopes across its endpoints needs no splitting.
1028
-
1029
- ## 3. Auth — gate the tenant in the path
1030
-
1031
- The `tenant` scope rule reads the prefix param and checks access; `inject` puts
1032
- the identity and derived facts on `ctx`
1033
- ([details](./auth-and-errors.md#resource-scoped-rule--reading-a-pathprefix-param)):
1034
-
1035
- ```ts
1036
- const authHook = createAuthHook<User>({
1037
- resolve: sessionResolver,
1038
- rules: {
1039
- public: 'public',
1040
- tenant: (user, ctx) => userCanAccessTenant(user.id, String(ctx.tenantId)),
1041
- } satisfies Record<Scope, AuthRule<User>>,
1042
- inject: (ctx, user) => { ctx.user = user },
1043
- })
1044
- ```
1045
-
1046
- ## 4. The client — a per-tenant `pathPrefix`
1047
-
1048
- `createClient`'s third argument prepends the tenant segment; `stripPrefixKeys`
1049
- keeps `tenantId` out of the body/query
1050
- ([details](./client.md#contractclientconfig--per-tenant--resource-scoped-clients)):
1051
-
1052
- ```ts
1053
- const widgetsApi = createClient(widgets, http, {
1054
- pathPrefix: ({ tenantId }) => `tenants/${tenantId}/`,
1055
- stripPrefixKeys: ['tenantId'],
1056
- })
1057
-
1058
- widgetsApi.list({ tenantId: 't_123' }) // GET /tenants/t_123/widgets
1059
- ```
1060
-
1061
- `stripPrefixKeys` (a `const` tuple) also makes the consumed keys **typed,
1062
- required args** on every method — `tenantId` above is type-checked, not a runtime
1063
- surprise — so no hand-written scoped-client wrapper is needed (→ ADR 0025).
1064
-
1065
- ## 5. The AI surface — `extend` injects the tenant
1066
-
1067
- One API key serves every tenant: the model passes `tenantId` per call, `resolve`
1068
- validates it and puts it on `ctx` — so the *same* handler that reads `ctx.tenantId`
1069
- over HTTP serves the tool call
1070
- ([details](./mcp-and-agents.md#adding-tool-only-args--extend)):
1071
-
1072
- ```ts
1073
- createMcpHandler({
1074
- serverInfo, auth,
1075
- services: [widgetsService],
1076
- access: { gate: { beforeHandle: authHook } },
1077
- extend: {
1078
- schema: { tenantId: z.string().describe('Tenant to act on') },
1079
- resolve: async ({ tenantId }) => ({ tenantId: String(tenantId) }),
1080
- filter: (_s, m) => m.scope === 'tenant',
1081
- },
1082
- })
1083
- ```
1084
-
1085
- ## The through-line
1086
-
1087
- `ctx.tenantId` is the single join point: the **prefix param** puts it there on
1088
- HTTP, `extend`'s **resolve** puts it there on a tool call. Handlers and the auth
1089
- rule read it the same way on both surfaces — one contract, every surface, no
1090
- per-transport tenant plumbing.