theokit 0.43.12 → 0.45.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 (305) hide show
  1. package/dist/{actions-virtual-module-RSFRPJQZ.js → actions-virtual-module-67K4POQ2.js} +20 -20
  2. package/dist/actions-virtual-module-67K4POQ2.js.map +1 -0
  3. package/dist/{actions-virtual-module-HG66SZ7T.js → actions-virtual-module-LLDDAQWY.js} +4 -3
  4. package/dist/{actions-virtual-module-HG66SZ7T.js.map → actions-virtual-module-LLDDAQWY.js.map} +1 -1
  5. package/dist/adapters/web-shim.js +1 -1
  6. package/dist/adapters/web-shim.js.map +1 -1
  7. package/dist/adapters/ws-shim.js +1 -1
  8. package/dist/adapters/ws-shim.js.map +1 -1
  9. package/dist/{agent-OXRRKB55.js → agent-WFULT3OB.js} +2 -2
  10. package/dist/{agents-typed-client-ZP7BKJB3.js → agents-typed-client-TNHCUU7Q.js} +2 -2
  11. package/dist/agents-typed-client-TNHCUU7Q.js.map +1 -0
  12. package/dist/{app-typed-client-USLAMN7X.js → app-typed-client-N5WUE2CP.js} +62 -24
  13. package/dist/app-typed-client-N5WUE2CP.js.map +1 -0
  14. package/dist/{app-typed-client-GDF2OMJ2.js → app-typed-client-S3VR4ZA3.js} +47 -8
  15. package/dist/app-typed-client-S3VR4ZA3.js.map +1 -0
  16. package/dist/{body-parser-web-NNEJGX6Y.js → body-parser-web-4Z2QTPDU.js} +2 -2
  17. package/dist/body-parser-web-4Z2QTPDU.js.map +1 -0
  18. package/dist/boot/index.js +4 -4
  19. package/dist/boot/index.js.map +1 -1
  20. package/dist/{broadcast-4SX7R5XE.js → broadcast-H64DJRBE.js} +3 -3
  21. package/dist/broadcast-H64DJRBE.js.map +1 -0
  22. package/dist/{build-MQHIJROR.js → build-YQ6MXOV6.js} +13 -4
  23. package/dist/build-YQ6MXOV6.js.map +1 -0
  24. package/dist/{build-request-body-preview-FVBQ7LCE.js → build-request-body-preview-CKWWBF2M.js} +2 -2
  25. package/dist/build-request-body-preview-CKWWBF2M.js.map +1 -0
  26. package/dist/{chunk-26ECIX74.js → chunk-2ADKT37V.js} +5 -5
  27. package/dist/chunk-2ADKT37V.js.map +1 -0
  28. package/dist/{chunk-JIL74SFK.js → chunk-37ZO643S.js} +9 -9
  29. package/dist/chunk-37ZO643S.js.map +1 -0
  30. package/dist/{chunk-ESC54TAK.js → chunk-3DGIANAN.js} +1 -1
  31. package/dist/chunk-3DGIANAN.js.map +1 -0
  32. package/dist/{chunk-6FK7FKY6.js → chunk-47FFT43U.js} +1 -1
  33. package/dist/chunk-47FFT43U.js.map +1 -0
  34. package/dist/{chunk-ZJQ4O76G.js → chunk-4FWBKX6G.js} +1 -1
  35. package/dist/chunk-4FWBKX6G.js.map +1 -0
  36. package/dist/{chunk-NM4WF3XD.js → chunk-4PBJ266F.js} +1 -1
  37. package/dist/chunk-4PBJ266F.js.map +1 -0
  38. package/dist/{chunk-7MQOHNHE.js → chunk-52PDWL5S.js} +1 -1
  39. package/dist/chunk-52PDWL5S.js.map +1 -0
  40. package/dist/{chunk-575PAX5L.js → chunk-5AMXBU2R.js} +62 -38
  41. package/dist/chunk-5AMXBU2R.js.map +1 -0
  42. package/dist/{chunk-JQJN6LFK.js → chunk-62EU2BVZ.js} +2 -2
  43. package/dist/chunk-62EU2BVZ.js.map +1 -0
  44. package/dist/{chunk-SJIRP73B.js → chunk-646CA6RV.js} +2 -2
  45. package/dist/chunk-646CA6RV.js.map +1 -0
  46. package/dist/{chunk-ASDXVRJD.js → chunk-6KDXP472.js} +4 -4
  47. package/dist/chunk-6KDXP472.js.map +1 -0
  48. package/dist/chunk-6LNIGF5P.js +46 -0
  49. package/dist/chunk-6LNIGF5P.js.map +1 -0
  50. package/dist/{chunk-IE6C4KZX.js → chunk-6VDYQ4I6.js} +11 -496
  51. package/dist/chunk-6VDYQ4I6.js.map +1 -0
  52. package/dist/chunk-7IHWXDJJ.js +1 -0
  53. package/dist/chunk-7IHWXDJJ.js.map +1 -0
  54. package/dist/{chunk-JQSKBMXP.js → chunk-7LVM22VG.js} +1 -1
  55. package/dist/chunk-7LVM22VG.js.map +1 -0
  56. package/dist/{chunk-UVXB2ER7.js → chunk-7SABX4DJ.js} +1 -1
  57. package/dist/chunk-7SABX4DJ.js.map +1 -0
  58. package/dist/{chunk-X32XEJXR.js → chunk-ACKBVBUI.js} +1 -1
  59. package/dist/chunk-ACKBVBUI.js.map +1 -0
  60. package/dist/{chunk-UUFYP2UM.js → chunk-AM3QABW5.js} +3 -3
  61. package/dist/chunk-AM3QABW5.js.map +1 -0
  62. package/dist/{chunk-FH3DYBAN.js → chunk-ANS4ELRH.js} +1 -1
  63. package/dist/chunk-ANS4ELRH.js.map +1 -0
  64. package/dist/{chunk-UD3LFGDL.js → chunk-AVQU5CQF.js} +1 -1
  65. package/dist/chunk-AVQU5CQF.js.map +1 -0
  66. package/dist/{chunk-CJNMJUHE.js → chunk-B7ONQ4QJ.js} +2 -2
  67. package/dist/{chunk-WSJKACWB.js → chunk-C34PMLSN.js} +1 -1
  68. package/dist/chunk-C34PMLSN.js.map +1 -0
  69. package/dist/{chunk-DJFMAWH5.js → chunk-EIRQM55C.js} +6 -5
  70. package/dist/chunk-EIRQM55C.js.map +1 -0
  71. package/dist/{chunk-ZEGYW52B.js → chunk-FB2HBNIC.js} +1 -1
  72. package/dist/chunk-FB2HBNIC.js.map +1 -0
  73. package/dist/chunk-FXZZS7YW.js +605 -0
  74. package/dist/chunk-FXZZS7YW.js.map +1 -0
  75. package/dist/{chunk-HGUZWG2C.js → chunk-FZG3JYB3.js} +8 -47
  76. package/dist/chunk-FZG3JYB3.js.map +1 -0
  77. package/dist/{chunk-V3LJN2GS.js → chunk-GAPBPRPP.js} +1 -1
  78. package/dist/chunk-GAPBPRPP.js.map +1 -0
  79. package/dist/chunk-GUBN5UTT.js +1 -0
  80. package/dist/chunk-GUBN5UTT.js.map +1 -0
  81. package/dist/{chunk-6OXCZMW3.js → chunk-HEK4SET7.js} +5 -5
  82. package/dist/chunk-HEK4SET7.js.map +1 -0
  83. package/dist/{chunk-N2D5AVRR.js → chunk-HRCNHWLP.js} +7 -109
  84. package/dist/chunk-HRCNHWLP.js.map +1 -0
  85. package/dist/{chunk-C3ZZ56YZ.js → chunk-JA2ZAT5Q.js} +1 -1
  86. package/dist/chunk-JA2ZAT5Q.js.map +1 -0
  87. package/dist/{chunk-L2S2R3TI.js → chunk-KBGGQK4I.js} +25 -8
  88. package/dist/chunk-KBGGQK4I.js.map +1 -0
  89. package/dist/{chunk-VPISAMXU.js → chunk-KD5G3YXI.js} +4 -4
  90. package/dist/chunk-KD5G3YXI.js.map +1 -0
  91. package/dist/{chunk-VMEWD57H.js → chunk-KPKLIUUL.js} +1 -1
  92. package/dist/chunk-KPKLIUUL.js.map +1 -0
  93. package/dist/{chunk-4HAU7AJM.js → chunk-L4Y6RJ4E.js} +3 -3
  94. package/dist/chunk-L4Y6RJ4E.js.map +1 -0
  95. package/dist/{chunk-OVHW23YC.js → chunk-L5Z6IY5U.js} +5 -5
  96. package/dist/chunk-L5Z6IY5U.js.map +1 -0
  97. package/dist/{chunk-JBCHWRKF.js → chunk-MTEWLGVY.js} +2 -2
  98. package/dist/chunk-MTEWLGVY.js.map +1 -0
  99. package/dist/{chunk-XZ6B2Y2R.js → chunk-MWP4YXWJ.js} +1 -1
  100. package/dist/chunk-MWP4YXWJ.js.map +1 -0
  101. package/dist/{chunk-5QW7IQQU.js → chunk-NTDN54XO.js} +1 -1
  102. package/dist/chunk-NTDN54XO.js.map +1 -0
  103. package/dist/{chunk-7BIM27LV.js → chunk-OIGJOYX6.js} +1 -1
  104. package/dist/chunk-OIGJOYX6.js.map +1 -0
  105. package/dist/{chunk-TSLSIRBR.js → chunk-OLGPYOLO.js} +2 -2
  106. package/dist/chunk-OLGPYOLO.js.map +1 -0
  107. package/dist/{chunk-6NEXVBPY.js → chunk-RWNSW4FM.js} +1 -1
  108. package/dist/chunk-RWNSW4FM.js.map +1 -0
  109. package/dist/{chunk-E25FBYJP.js → chunk-SAFGDIPQ.js} +1 -1
  110. package/dist/chunk-SAFGDIPQ.js.map +1 -0
  111. package/dist/{chunk-OP7QCTR5.js → chunk-SEELKQUM.js} +2 -2
  112. package/dist/chunk-SEELKQUM.js.map +1 -0
  113. package/dist/{chunk-4B2ZMX45.js → chunk-SSYDEKWF.js} +1 -1
  114. package/dist/chunk-SSYDEKWF.js.map +1 -0
  115. package/dist/{chunk-DQVBL2G4.js → chunk-SZU6BOMV.js} +75 -53
  116. package/dist/chunk-SZU6BOMV.js.map +1 -0
  117. package/dist/{chunk-65EFIUDD.js → chunk-U267AOWS.js} +1 -1
  118. package/dist/chunk-U267AOWS.js.map +1 -0
  119. package/dist/{chunk-FX72VHAE.js → chunk-U3H53IIN.js} +6 -6
  120. package/dist/chunk-U3H53IIN.js.map +1 -0
  121. package/dist/{chunk-OPLICDUB.js → chunk-UW2TEAGR.js} +1 -1
  122. package/dist/chunk-UW2TEAGR.js.map +1 -0
  123. package/dist/{chunk-2WH6SD3C.js → chunk-UYMCKHML.js} +4 -4
  124. package/dist/chunk-UYMCKHML.js.map +1 -0
  125. package/dist/{chunk-OI6DK6ZJ.js → chunk-VFU7DTUL.js} +6 -4
  126. package/dist/chunk-VFU7DTUL.js.map +1 -0
  127. package/dist/{chunk-IAJ2JVEH.js → chunk-VSLTKX5L.js} +1 -1
  128. package/dist/chunk-VSLTKX5L.js.map +1 -0
  129. package/dist/{chunk-YB5DJJ4U.js → chunk-VZTYCAO6.js} +1 -1
  130. package/dist/chunk-VZTYCAO6.js.map +1 -0
  131. package/dist/chunk-WDGYCBNI.js +65 -0
  132. package/dist/chunk-WDGYCBNI.js.map +1 -0
  133. package/dist/chunk-WPJOTQA5.js +1 -0
  134. package/dist/chunk-WPJOTQA5.js.map +1 -0
  135. package/dist/{chunk-DGUM43GV.js → chunk-XTHN6JBX.js} +1 -1
  136. package/dist/chunk-XTHN6JBX.js.map +1 -0
  137. package/dist/{chunk-HZ6USUHC.js → chunk-YOIVCCZT.js} +1 -1
  138. package/dist/chunk-YOIVCCZT.js.map +1 -0
  139. package/dist/cli/index.js +8 -8
  140. package/dist/client/core.d.ts +5 -259
  141. package/dist/client/core.js +13 -9
  142. package/dist/client/core.js.map +1 -1
  143. package/dist/client/index.d.ts +7 -96
  144. package/dist/client/index.js +19 -67
  145. package/dist/client/index.js.map +1 -1
  146. package/dist/{controller-swc-transform-JJRMTSDY.js → controller-swc-transform-T7ZTD55V.js} +2 -2
  147. package/dist/controller-swc-transform-T7ZTD55V.js.map +1 -0
  148. package/dist/{cookies-MJKMGJ7N.js → cookies-SOXUQJXG.js} +3 -3
  149. package/dist/cookies-SOXUQJXG.js.map +1 -0
  150. package/dist/{dev-WQ4LWCAW.js → dev-YNO26JS3.js} +8 -7
  151. package/dist/{dev-WQ4LWCAW.js.map → dev-YNO26JS3.js.map} +1 -1
  152. package/dist/{dev-emit-HLGJK3PP.js → dev-emit-F54Y5TIU.js} +5 -5
  153. package/dist/dev-emit-F54Y5TIU.js.map +1 -0
  154. package/dist/devtools/entry.js +61 -53
  155. package/dist/devtools/entry.js.map +1 -1
  156. package/dist/dispatcher-MXKF3CRH.js +8 -0
  157. package/dist/dispatcher-MXKF3CRH.js.map +1 -0
  158. package/dist/index.js +25 -25
  159. package/dist/index.js.map +1 -1
  160. package/dist/{info-75U6GCMD.js → info-ICDTPJDC.js} +3 -3
  161. package/dist/{internal-api-JFORKYLR.js → internal-api-NO24QAXC.js} +10 -8
  162. package/dist/{internal-api-DV3H5NNV.js → internal-api-S7WK2WCY.js} +20 -20
  163. package/dist/internal-api-S7WK2WCY.js.map +1 -0
  164. package/dist/{load-config-XP7NSSA7.js → load-config-ICCNMO74.js} +3 -3
  165. package/dist/{mcp-FF3NTCHB.js → mcp-3S6A4A4Q.js} +3 -3
  166. package/dist/{openapi-ZPXYRAM2.js → openapi-NIYA2VBG.js} +3 -3
  167. package/dist/react-query/index.js +2 -2
  168. package/dist/react-query/index.js.map +1 -1
  169. package/dist/{routes-ZVDKABXZ.js → routes-2RD4S5PZ.js} +3 -3
  170. package/dist/{schema-FBOTN46F.js → schema-S553QCAU.js} +2 -2
  171. package/dist/server/agent/index.d.ts +3 -72
  172. package/dist/server/agent/index.js +4 -4
  173. package/dist/server/agent/index.js.map +1 -1
  174. package/dist/server/auth/index.js +4 -4
  175. package/dist/server/auth/index.js.map +1 -1
  176. package/dist/server/cost/index.js +2 -2
  177. package/dist/server/cost/index.js.map +1 -1
  178. package/dist/server/cron/index.js +6 -6
  179. package/dist/server/cron/index.js.map +1 -1
  180. package/dist/server/define/index.d.ts +2 -2
  181. package/dist/server/define/index.js +4 -4
  182. package/dist/server/define/index.js.map +1 -1
  183. package/dist/server/http/index.js +11 -11
  184. package/dist/server/http/index.js.map +1 -1
  185. package/dist/server/index.d.ts +3 -3
  186. package/dist/server/index.js +41 -41
  187. package/dist/server/index.js.map +1 -1
  188. package/dist/server/jobs/index.js +7 -7
  189. package/dist/server/jobs/index.js.map +1 -1
  190. package/dist/server/observability/index.d.ts +8 -1
  191. package/dist/server/observability/index.js +5 -5
  192. package/dist/server/observability/index.js.map +1 -1
  193. package/dist/server/plugins/index.js +3 -3
  194. package/dist/server/plugins/index.js.map +1 -1
  195. package/dist/server/rate-limit/index.js +4 -4
  196. package/dist/server/rate-limit/index.js.map +1 -1
  197. package/dist/server/realtime/index.js +2 -2
  198. package/dist/server/realtime/index.js.map +1 -1
  199. package/dist/server/scan/index.js +7 -7
  200. package/dist/server/scan/index.js.map +1 -1
  201. package/dist/server/security/index.js +5 -5
  202. package/dist/server/security/index.js.map +1 -1
  203. package/dist/server/storage/index.js +2 -2
  204. package/dist/server/storage/index.js.map +1 -1
  205. package/dist/server/webhook/index.js +3 -3
  206. package/dist/server/webhook/index.js.map +1 -1
  207. package/dist/server-error-to-envelope-UM7DEVM4.js +8 -0
  208. package/dist/server-error-to-envelope-UM7DEVM4.js.map +1 -0
  209. package/dist/{server-routes-hmr-RI7SYNT2.js → server-routes-hmr-6CRNSEWF.js} +2 -2
  210. package/dist/server-routes-hmr-6CRNSEWF.js.map +1 -0
  211. package/dist/{services-typed-client-AU6DKXAO.js → services-typed-client-IXNOPVZA.js} +3 -3
  212. package/dist/services-typed-client-IXNOPVZA.js.map +1 -0
  213. package/dist/{start-2U3FUCJX.js → start-TVT7BZ4V.js} +35 -11
  214. package/dist/start-TVT7BZ4V.js.map +1 -0
  215. package/dist/vite-plugin/index.js +25 -25
  216. package/dist/vite-plugin/index.js.map +1 -1
  217. package/dist/{vite-plugin-D2NTPZNC.js → vite-plugin-K64KQZSU.js} +8 -7
  218. package/package.json +11 -10
  219. package/dist/actions-virtual-module-RSFRPJQZ.js.map +0 -1
  220. package/dist/agents-typed-client-ZP7BKJB3.js.map +0 -1
  221. package/dist/app-typed-client-GDF2OMJ2.js.map +0 -1
  222. package/dist/app-typed-client-USLAMN7X.js.map +0 -1
  223. package/dist/body-parser-web-NNEJGX6Y.js.map +0 -1
  224. package/dist/build-MQHIJROR.js.map +0 -1
  225. package/dist/build-request-body-preview-FVBQ7LCE.js.map +0 -1
  226. package/dist/chunk-26ECIX74.js.map +0 -1
  227. package/dist/chunk-2WH6SD3C.js.map +0 -1
  228. package/dist/chunk-4B2ZMX45.js.map +0 -1
  229. package/dist/chunk-4HAU7AJM.js.map +0 -1
  230. package/dist/chunk-575PAX5L.js.map +0 -1
  231. package/dist/chunk-5QW7IQQU.js.map +0 -1
  232. package/dist/chunk-65EFIUDD.js.map +0 -1
  233. package/dist/chunk-6FK7FKY6.js.map +0 -1
  234. package/dist/chunk-6NEXVBPY.js.map +0 -1
  235. package/dist/chunk-6OXCZMW3.js.map +0 -1
  236. package/dist/chunk-7BIM27LV.js.map +0 -1
  237. package/dist/chunk-7MQOHNHE.js.map +0 -1
  238. package/dist/chunk-ASDXVRJD.js.map +0 -1
  239. package/dist/chunk-C3ZZ56YZ.js.map +0 -1
  240. package/dist/chunk-DJFMAWH5.js.map +0 -1
  241. package/dist/chunk-DQVBL2G4.js.map +0 -1
  242. package/dist/chunk-E25FBYJP.js.map +0 -1
  243. package/dist/chunk-E3JH6YUM.js +0 -1
  244. package/dist/chunk-ESC54TAK.js.map +0 -1
  245. package/dist/chunk-FH3DYBAN.js.map +0 -1
  246. package/dist/chunk-FX72VHAE.js.map +0 -1
  247. package/dist/chunk-HGUZWG2C.js.map +0 -1
  248. package/dist/chunk-HZ6USUHC.js.map +0 -1
  249. package/dist/chunk-IAJ2JVEH.js.map +0 -1
  250. package/dist/chunk-IE6C4KZX.js.map +0 -1
  251. package/dist/chunk-JBCHWRKF.js.map +0 -1
  252. package/dist/chunk-JHEAWR3L.js +0 -1
  253. package/dist/chunk-JIL74SFK.js.map +0 -1
  254. package/dist/chunk-JQJN6LFK.js.map +0 -1
  255. package/dist/chunk-JQSKBMXP.js.map +0 -1
  256. package/dist/chunk-KPRJS3II.js +0 -505
  257. package/dist/chunk-KPRJS3II.js.map +0 -1
  258. package/dist/chunk-L2S2R3TI.js.map +0 -1
  259. package/dist/chunk-N2D5AVRR.js.map +0 -1
  260. package/dist/chunk-NM4WF3XD.js.map +0 -1
  261. package/dist/chunk-NPMCKOX4.js +0 -1
  262. package/dist/chunk-NPMCKOX4.js.map +0 -1
  263. package/dist/chunk-OI6DK6ZJ.js.map +0 -1
  264. package/dist/chunk-OP7QCTR5.js.map +0 -1
  265. package/dist/chunk-OPLICDUB.js.map +0 -1
  266. package/dist/chunk-OVHW23YC.js.map +0 -1
  267. package/dist/chunk-SJIRP73B.js.map +0 -1
  268. package/dist/chunk-TSLSIRBR.js.map +0 -1
  269. package/dist/chunk-UD3LFGDL.js.map +0 -1
  270. package/dist/chunk-UUFYP2UM.js.map +0 -1
  271. package/dist/chunk-UVXB2ER7.js.map +0 -1
  272. package/dist/chunk-V3LJN2GS.js.map +0 -1
  273. package/dist/chunk-VMEWD57H.js.map +0 -1
  274. package/dist/chunk-VPISAMXU.js.map +0 -1
  275. package/dist/chunk-WSJKACWB.js.map +0 -1
  276. package/dist/chunk-X32XEJXR.js.map +0 -1
  277. package/dist/chunk-XZ6B2Y2R.js.map +0 -1
  278. package/dist/chunk-YB5DJJ4U.js.map +0 -1
  279. package/dist/chunk-ZEGYW52B.js.map +0 -1
  280. package/dist/chunk-ZJQ4O76G.js.map +0 -1
  281. package/dist/controller-swc-transform-JJRMTSDY.js.map +0 -1
  282. package/dist/cookies-MJKMGJ7N.js.map +0 -1
  283. package/dist/dev-emit-HLGJK3PP.js.map +0 -1
  284. package/dist/dispatcher-DLKIXYNO.js +0 -8
  285. package/dist/dispatcher-DLKIXYNO.js.map +0 -1
  286. package/dist/internal-api-DV3H5NNV.js.map +0 -1
  287. package/dist/internal-api-JFORKYLR.js.map +0 -1
  288. package/dist/load-config-XP7NSSA7.js.map +0 -1
  289. package/dist/schema-FBOTN46F.js.map +0 -1
  290. package/dist/server-error-to-envelope-EOFUIUNB.js +0 -8
  291. package/dist/server-error-to-envelope-EOFUIUNB.js.map +0 -1
  292. package/dist/server-routes-hmr-RI7SYNT2.js.map +0 -1
  293. package/dist/services-typed-client-AU6DKXAO.js.map +0 -1
  294. package/dist/start-2U3FUCJX.js.map +0 -1
  295. package/dist/vite-plugin-D2NTPZNC.js.map +0 -1
  296. /package/dist/{agent-OXRRKB55.js.map → agent-WFULT3OB.js.map} +0 -0
  297. /package/dist/{chunk-CJNMJUHE.js.map → chunk-B7ONQ4QJ.js.map} +0 -0
  298. /package/dist/{info-75U6GCMD.js.map → info-ICDTPJDC.js.map} +0 -0
  299. /package/dist/{broadcast-4SX7R5XE.js.map → internal-api-NO24QAXC.js.map} +0 -0
  300. /package/dist/{chunk-DGUM43GV.js.map → load-config-ICCNMO74.js.map} +0 -0
  301. /package/dist/{mcp-FF3NTCHB.js.map → mcp-3S6A4A4Q.js.map} +0 -0
  302. /package/dist/{openapi-ZPXYRAM2.js.map → openapi-NIYA2VBG.js.map} +0 -0
  303. /package/dist/{routes-ZVDKABXZ.js.map → routes-2RD4S5PZ.js.map} +0 -0
  304. /package/dist/{chunk-E3JH6YUM.js.map → schema-S553QCAU.js.map} +0 -0
  305. /package/dist/{chunk-JHEAWR3L.js.map → vite-plugin-K64KQZSU.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/observability/span.ts","../src/server/observability/adapters/noop.ts","../src/server/observability/adapters/console.ts","../src/server/observability/otlp-serializer.ts","../src/server/observability/adapters/theo-cloud.ts","../src/server/observability/adapter-registry.ts","../src/server/observability/middleware.ts","../src/server/observability/define-adapter.ts"],"sourcesContent":["/**\n * SpanHandle implementation — records timing + attributes.\n *\n * Used by console and theo-cloud adapters. Noop adapter uses NoopSpan.\n */\nimport type { SpanHandle, SpanAttributes } from './adapters/types.js'\n\nexport interface SpanData {\n name: string\n attributes: Record<string, string | number | boolean>\n status: 'ok' | 'error'\n statusMessage?: string\n startTimeMs: number\n endTimeMs?: number\n durationMs?: number\n}\n\nexport class SpanImpl implements SpanHandle {\n private readonly data: SpanData\n private ended = false\n\n constructor(name: string, attributes?: SpanAttributes) {\n this.data = {\n name,\n attributes: {},\n status: 'ok',\n startTimeMs: Date.now(),\n }\n if (attributes) {\n for (const [k, v] of Object.entries(attributes)) {\n if (v !== undefined) this.data.attributes[k] = v\n }\n }\n }\n\n setAttribute(key: string, value: string | number | boolean): void {\n if (!this.ended) this.data.attributes[key] = value\n }\n\n setStatus(status: 'ok' | 'error', message?: string): void {\n if (!this.ended) {\n this.data.status = status\n this.data.statusMessage = message\n }\n }\n\n end(): void {\n if (this.ended) return // idempotent\n this.ended = true\n this.data.endTimeMs = Date.now()\n this.data.durationMs = this.data.endTimeMs - this.data.startTimeMs\n }\n\n /** Read-only access to span data (for adapters to export). */\n getData(): SpanData {\n return { ...this.data, attributes: { ...this.data.attributes } }\n }\n\n isEnded(): boolean {\n return this.ended\n }\n}\n\n/** Noop span — used by NoopAdapter and post-shutdown fallback (EC-2). */\nexport class NoopSpan implements SpanHandle {\n setAttribute(): void {}\n setStatus(): void {}\n end(): void {}\n}\n","/**\n * NoopObservabilityAdapter — silent fallback.\n *\n * All methods are no-ops. Never throws, never blocks.\n * Used as the default when no other adapter is configured.\n * EC-2: startSpan after shutdown returns a noop span (no crash).\n */\nimport { NoopSpan } from '../span.js'\n\nimport type { ObservabilityAdapter, SpanHandle, SpanAttributes } from './types.js'\n\nexport class NoopObservabilityAdapter implements ObservabilityAdapter {\n readonly name = 'noop'\n private isShutdown = false\n\n startSpan(_name: string, _attributes?: SpanAttributes): SpanHandle {\n return new NoopSpan()\n }\n\n // Null Object: discarding the call IS the behaviour. An empty body is the honest\n // implementation — a fabricated one would only hide that from the next reader.\n /* eslint-disable @typescript-eslint/no-empty-function -- no-op adapter by design */\n counter(_name: string, _value: number, _attributes?: SpanAttributes): void {}\n histogram(_name: string, _value: number, _attributes?: SpanAttributes): void {}\n log(\n _level: 'debug' | 'info' | 'warn' | 'error',\n _message: string,\n _attributes?: SpanAttributes,\n ): void {}\n /* eslint-enable @typescript-eslint/no-empty-function */\n\n // Not `async`: there is nothing to await, and declaring it so would claim otherwise.\n flush(): Promise<void> {\n return Promise.resolve()\n }\n\n shutdown(): Promise<void> {\n this.isShutdown = true\n return Promise.resolve()\n }\n}\n","/**\n * ConsoleObservabilityAdapter — dev-mode console output.\n *\n * Emits JSON-structured lines to a configurable writer (default: process.stderr).\n * Inspired by Hono middleware timing pattern.\n */\nimport { SpanImpl, NoopSpan, type SpanData } from '../span.js'\n\nimport type { ObservabilityAdapter, SpanHandle, SpanAttributes } from './types.js'\n\ninterface ConsoleAdapterOptions {\n /** Writer function — defaults to process.stderr.write. */\n write?: (line: string) => void\n}\n\nexport class ConsoleObservabilityAdapter implements ObservabilityAdapter {\n readonly name = 'console'\n private write: (line: string) => void\n private isShutdown = false\n private spans: SpanImpl[] = []\n\n constructor(options: ConsoleAdapterOptions = {}) {\n this.write = options.write ?? ((line: string) => process.stderr.write(line + '\\n'))\n }\n\n startSpan(name: string, attributes?: SpanAttributes): SpanHandle {\n if (this.isShutdown) return new NoopSpan()\n const span = new SpanImpl(name, attributes)\n this.spans.push(span)\n return {\n setAttribute: (k, v) => {\n span.setAttribute(k, v)\n },\n setStatus: (s, m) => {\n span.setStatus(s, m)\n },\n end: () => {\n span.end()\n this.emitSpan(span.getData())\n },\n }\n }\n\n counter(name: string, value: number, attributes?: SpanAttributes): void {\n if (this.isShutdown) return\n this.emit({\n type: 'counter',\n metric: name,\n value,\n attributes: attributes ?? {},\n timestamp: Date.now(),\n })\n }\n\n histogram(name: string, value: number, attributes?: SpanAttributes): void {\n if (this.isShutdown) return\n this.emit({\n type: 'histogram',\n metric: name,\n value,\n attributes: attributes ?? {},\n timestamp: Date.now(),\n })\n }\n\n log(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n attributes?: SpanAttributes,\n ): void {\n if (this.isShutdown) return\n this.emit({ type: 'log', level, message, attributes: attributes ?? {}, timestamp: Date.now() })\n }\n\n // Not `async`: this adapter writes synchronously, so there is nothing to await.\n flush(): Promise<void> {\n return Promise.resolve()\n }\n\n shutdown(): Promise<void> {\n this.isShutdown = true\n return Promise.resolve()\n }\n\n private emitSpan(data: SpanData): void {\n this.emit({\n type: 'span',\n name: data.name,\n status: data.status,\n duration_ms: data.durationMs ?? 0,\n attributes: data.attributes,\n timestamp: data.startTimeMs,\n })\n }\n\n private emit(record: Record<string, unknown>): void {\n this.write(JSON.stringify(record))\n }\n}\n","/**\n * Lightweight OTLP JSON serializer — ~50 LoC, no @opentelemetry/* dependency.\n *\n * Per ADR D456: in-house serializer for the theo-cloud adapter.\n * Produces valid ExportTraceServiceRequest JSON (OTLP v1.0).\n * Pinned to OTLP JSON v1.0 (stable since 2023).\n */\nimport type { SpanData } from './span.js'\n\ninterface OtlpSpan {\n traceId: string\n spanId: string\n name: string\n kind: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes: { key: string; value: { stringValue?: string; intValue?: string; boolValue?: boolean } }[]\n status: { code: number; message?: string }\n}\n\ninterface ExportTraceServiceRequest {\n resourceSpans: [{\n scopeSpans: [{\n scope: { name: string; version: string }\n spans: OtlpSpan[]\n }]\n }]\n}\n\n/** Convert SpanData[] to OTLP JSON bytes (Uint8Array). */\nexport function serializeSpansToOtlp(spans: SpanData[], serviceName = 'theokit'): Uint8Array {\n const otlpSpans: OtlpSpan[] = spans.map((s) => ({\n traceId: randomHex(32),\n spanId: randomHex(16),\n name: s.name,\n kind: 2, // SPAN_KIND_SERVER\n startTimeUnixNano: String(s.startTimeMs * 1_000_000),\n endTimeUnixNano: String((s.endTimeMs ?? s.startTimeMs) * 1_000_000),\n attributes: Object.entries(s.attributes).map(([key, value]) => ({\n key,\n value: typeof value === 'string'\n ? { stringValue: value }\n : typeof value === 'number'\n ? { intValue: String(value) }\n : { boolValue: value },\n })),\n status: { code: s.status === 'ok' ? 1 : 2, message: s.statusMessage },\n }))\n\n const request: ExportTraceServiceRequest = {\n resourceSpans: [{\n scopeSpans: [{\n scope: { name: serviceName, version: '1.0.0' },\n spans: otlpSpans,\n }],\n }],\n }\n\n return new TextEncoder().encode(JSON.stringify(request))\n}\n\nfunction randomHex(length: number): string {\n const bytes = new Uint8Array(length / 2)\n globalThis.crypto.getRandomValues(bytes)\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n","/**\n * TheoCloudObservabilityAdapter — OTLP/HTTP batched export for TheoCloud.\n *\n * Zero-config via env vars (THEO_CLOUD_INGEST_URL, THEO_CLOUD_API_KEY).\n * Batches spans and flushes via native fetch() POST.\n *\n * EC-1: flush failure logs warning, does NOT throw, does NOT retry (KISS).\n * EC-2: startSpan after shutdown returns noop span.\n */\nimport { serializeSpansToOtlp } from '../otlp-serializer.js'\nimport { SpanImpl, NoopSpan, type SpanData } from '../span.js'\n\nimport type { ObservabilityAdapter, SpanHandle, SpanAttributes } from './types.js'\n\ninterface TheoCloudAdapterOptions {\n /** TheoCloud ingest endpoint URL. */\n ingestUrl: string\n /** TheoCloud API key for authentication. */\n token: string\n /** Flush interval in ms (default: 5000). */\n flushIntervalMs?: number\n /** Mock fetch for testing (never in production). */\n _mockFetch?: typeof globalThis.fetch\n}\n\nexport class TheoCloudObservabilityAdapter implements ObservabilityAdapter {\n readonly name = 'theo-cloud'\n private pendingSpans: SpanData[] = []\n private isShutdown = false\n private readonly opts: Required<Pick<TheoCloudAdapterOptions, 'ingestUrl' | 'token'>> &\n TheoCloudAdapterOptions\n\n constructor(options: TheoCloudAdapterOptions) {\n this.opts = { flushIntervalMs: 5000, ...options }\n }\n\n startSpan(name: string, attributes?: SpanAttributes): SpanHandle {\n if (this.isShutdown) return new NoopSpan()\n const span = new SpanImpl(name, attributes)\n return {\n setAttribute: (k, v) => {\n span.setAttribute(k, v)\n },\n setStatus: (s, m) => {\n span.setStatus(s, m)\n },\n end: () => {\n span.end()\n this.pendingSpans.push(span.getData())\n },\n }\n }\n\n /* eslint-disable @typescript-eslint/no-empty-function -- metrics not shipped by this adapter yet; an empty body is honest, a fabricated one is not */\n counter(_name: string, _value: number, _attributes?: SpanAttributes): void {}\n histogram(_name: string, _value: number, _attributes?: SpanAttributes): void {}\n log(\n _level: 'debug' | 'info' | 'warn' | 'error',\n _message: string,\n _attributes?: SpanAttributes,\n ): void {}\n /* eslint-enable @typescript-eslint/no-empty-function */\n\n async flush(): Promise<void> {\n if (this.isShutdown || this.pendingSpans.length === 0) return\n\n const spans = this.pendingSpans.splice(0)\n const body = serializeSpansToOtlp(spans) as unknown as BodyInit\n const fetchFn = this.opts._mockFetch ?? globalThis.fetch\n\n try {\n await fetchFn(this.opts.ingestUrl, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${this.opts.token}`,\n },\n body,\n })\n } catch (err) {\n // EC-1: log warning, don't throw, don't retry\n console.error(\n `[theokit:observability] flush failed: ${err instanceof Error ? err.message : 'unknown error'}`,\n )\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.isShutdown) return\n await this.flush()\n this.isShutdown = true\n }\n}\n","/**\n * Adapter registry — resolves the active observability adapter.\n *\n * Per ADR D457 (v1.1) priority chain:\n * 1. Explicit config (theo.config.ts observability.provider) — ALWAYS wins\n * 2. THEO_CLOUD_INGEST_URL env → theo-cloud adapter\n * 3. NODE_ENV=development → console adapter\n * 4. Fallback → noop adapter\n */\nimport { ConsoleObservabilityAdapter } from './adapters/console.js'\nimport { NoopObservabilityAdapter } from './adapters/noop.js'\nimport { TheoCloudObservabilityAdapter } from './adapters/theo-cloud.js'\nimport type { ObservabilityAdapter } from './adapters/types.js'\n\ninterface ResolveAdapterOptions {\n env: Record<string, string | undefined>\n config?: {\n provider?: ObservabilityAdapter\n }\n}\n\n/**\n * Resolve the observability adapter from config + env.\n * Called once at boot — returns the active adapter for the process lifetime.\n */\nexport function resolveAdapter(options: ResolveAdapterOptions): ObservabilityAdapter {\n // 1. Explicit config ALWAYS wins (EC-4)\n if (options.config?.provider) {\n return options.config.provider\n }\n\n // 2. TheoCloud env vars → theo-cloud adapter\n const ingestUrl = options.env.THEO_CLOUD_INGEST_URL\n const apiKey = options.env.THEO_CLOUD_API_KEY\n if (ingestUrl && apiKey) {\n return new TheoCloudObservabilityAdapter({ ingestUrl, token: apiKey })\n }\n\n // 3. Development → console adapter\n if (options.env.NODE_ENV === 'development') {\n return new ConsoleObservabilityAdapter()\n }\n\n // 4. Fallback → noop\n return new NoopObservabilityAdapter()\n}\n","/**\n * Auto-instrumentation middleware — creates spans for every HTTP request.\n *\n * Registers as a standard TheoKit plugin via existing hook system.\n * No changes to plugin-runner needed.\n *\n * Per blueprint Pattern 2 (Hono middleware timing):\n * - onRequest: start span with method + path\n * - onResponse: end span with status + duration\n * - onError: set span status to error\n */\nimport type { ObservabilityAdapter, SpanHandle } from './adapters/types.js'\n\ninterface PluginContext {\n requestId: string\n request: { method: string; url: string }\n response?: { statusCode: number }\n}\n\ninterface ObservabilityPlugin {\n name: string\n onRequest(ctx: PluginContext): Promise<void>\n onResponse(ctx: PluginContext): Promise<void>\n onError(ctx: PluginContext & { error: unknown }): Promise<void>\n}\n\n// Active spans keyed by requestId — cleared on response/error\nconst activeSpans = new Map<string, SpanHandle>()\n\n/**\n * Create an observability plugin that auto-instruments HTTP requests.\n *\n * EC-5: For SSE responses, span ends on response close, not headers sent.\n * The caller should invoke onResponse when the stream actually closes.\n */\nexport function createObservabilityPlugin(adapter: ObservabilityAdapter): ObservabilityPlugin {\n return {\n name: 'theokit:observability',\n\n // NOT `async`: every hook here is synchronous work on an in-memory span map. Declaring them\n // async would advertise awaiting that never happens (M56).\n onRequest(ctx: PluginContext): Promise<void> {\n const url = new URL(ctx.request.url, 'http://localhost')\n const span = adapter.startSpan('http.request', {\n method: ctx.request.method,\n path: url.pathname,\n requestId: ctx.requestId,\n })\n activeSpans.set(ctx.requestId, span)\n return Promise.resolve()\n },\n\n onResponse(ctx: PluginContext): Promise<void> {\n const span = activeSpans.get(ctx.requestId)\n if (!span) return Promise.resolve()\n activeSpans.delete(ctx.requestId)\n\n if (ctx.response) {\n span.setAttribute('status', ctx.response.statusCode)\n }\n span.setStatus('ok')\n span.end()\n\n adapter.counter('http.requests', 1, {\n method: ctx.request.method,\n status: ctx.response?.statusCode ?? 0,\n })\n return Promise.resolve()\n },\n\n onError(ctx: PluginContext & { error: unknown }): Promise<void> {\n const span = activeSpans.get(ctx.requestId)\n if (!span) return Promise.resolve()\n activeSpans.delete(ctx.requestId)\n\n const message = ctx.error instanceof Error ? ctx.error.message : 'unknown error'\n span.setAttribute('error', true)\n span.setStatus('error', message)\n span.end()\n\n adapter.counter('http.errors', 1, {\n method: ctx.request.method,\n })\n return Promise.resolve()\n },\n }\n}\n","/**\n * defineObservabilityAdapter() — public API for custom adapters.\n *\n * The escape hatch for self-host users who want Datadog, Grafana, Honeycomb, etc.\n * Validates the adapter shape and returns a typed ObservabilityAdapter.\n *\n * @example\n * ```ts\n * const datadogAdapter = defineObservabilityAdapter({\n * name: 'datadog',\n * startSpan: (name, attrs) => { ... },\n * counter: (name, value) => { ... },\n * histogram: (name, value) => { ... },\n * log: (level, message) => { ... },\n * flush: async () => { ... },\n * shutdown: async () => { ... },\n * })\n *\n * // theo.config.ts\n * export default defineConfig({\n * observability: { provider: datadogAdapter },\n * })\n * ```\n */\nimport type { ObservabilityAdapter, SpanHandle, SpanAttributes } from './adapters/types.js'\n\ninterface DefineAdapterConfig {\n name: string\n startSpan(name: string, attributes?: SpanAttributes): SpanHandle\n counter(name: string, value: number, attributes?: SpanAttributes): void\n histogram(name: string, value: number, attributes?: SpanAttributes): void\n log(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n attributes?: SpanAttributes,\n ): void\n flush(): Promise<void>\n shutdown(): Promise<void>\n}\n\nexport function defineObservabilityAdapter(config: DefineAdapterConfig): ObservabilityAdapter {\n return {\n name: config.name,\n startSpan: (name, attrs) => config.startSpan(name, attrs),\n counter: (name, value, attrs) => {\n config.counter(name, value, attrs)\n },\n histogram: (name, value, attrs) => {\n config.histogram(name, value, attrs)\n },\n log: (level, message, attrs) => {\n config.log(level, message, attrs)\n },\n flush: () => config.flush(),\n shutdown: () => config.shutdown(),\n }\n}\n"],"mappings":";AAiBO,IAAM,WAAN,MAAqC;AAAA,EACzB;AAAA,EACT,QAAQ;AAAA,EAEhB,YAAY,MAAc,YAA6B;AACrD,SAAK,OAAO;AAAA,MACV;AAAA,MACA,YAAY,CAAC;AAAA,MACb,QAAQ;AAAA,MACR,aAAa,KAAK,IAAI;AAAA,IACxB;AACA,QAAI,YAAY;AACd,iBAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,UAAU,GAAG;AAC/C,YAAI,MAAM,OAAW,MAAK,KAAK,WAAW,CAAC,IAAI;AAAA,MACjD;AAAA,IACF;AAAA,EACF;AAAA,EAEA,aAAa,KAAa,OAAwC;AAChE,QAAI,CAAC,KAAK,MAAO,MAAK,KAAK,WAAW,GAAG,IAAI;AAAA,EAC/C;AAAA,EAEA,UAAU,QAAwB,SAAwB;AACxD,QAAI,CAAC,KAAK,OAAO;AACf,WAAK,KAAK,SAAS;AACnB,WAAK,KAAK,gB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AAiB,GAAG;AAAA,QAClC,QAAQ,IAAI,QAAQ;AAAA,QACpB,QAAQ,IAAI,UAAU,cAAc;AAAA,MACtC,CAAC;AACD,aAAO,QAAQ,QAAQ;AAAA,IACzB;AAAA,IAEA,QAAQ,KAAwD;AAC9D,YAAM,OAAO,YAAY,IAAI,IAAI,SAAS;AAC1C,UAAI,CAAC,KAAM,QAAO,QAAQ,QAAQ;AAClC,kBAAY,OAAO,IAAI,SAAS;AAEhC,YAAM,UAAU,IAAI,iBAAiB,QAAQ,IAAI,MAAM,UAAU;AACjE,WAAK,aAAa,SAAS,IAAI;AAC/B,WAAK,UAAU,SAAS,OAAO;AAC/B,WAAK,IAAI;AAET,cAAQ,QAAQ,eAAe,GAAG;AAAA,QAChC,QAAQ,IAAI,QAAQ;AAAA,MACtB,CAAC;AACD,aAAO,QAAQ,QAAQ;AAAA,IACzB;AAAA,EACF;AACF;;;AC9CO,SAAS,2BAA2B,QAAmD;AAC5F,SAAO;AAAA,IACL,MAAM,OAAO;AAAA,IACb,WAAW,CAAC,MAAM,UAAU,OAAO,UAAU,MAAM,KAAK;AAAA,IACxD,SAAS,CAAC,MAAM,OAAO,UAAU;AAC/B,aAAO,QAAQ,MAAM,OAAO,KAAK;AAAA,IACnC;AAAA,IACA,WAAW,CAAC,MAAM,OAAO,UAAU;AACjC,aAAO,UAAU,MAAM,OAAO,KAAK;AAAA,IACrC;AAAA,IACA,KAAK,CAAC,OAAO,SAAS,UAAU;AAC9B,aAAO,IAAI,OAAO,SAAS,KAAK;AAAA,IAClC;AAAA,IACA,OAAO,MAAM,OAAO,MAAM;AAAA,IAC1B,UAAU,MAAM,OAAO,SAAS;AAAA,EAClC;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/http/controller-dispatch.ts","../src/server/http/batch-handler.ts","../src/server/http/cors.ts","../src/server/http/trace-context.ts","../src/server/security/csp-report.ts","../src/server/security/csrf-readiness-endpoint.ts","../src/server/security/csrf-readiness-store.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Controller files are walked from the developer's `serverDir/controllers`\n * (a build-time config path), never from HTTP input. No injection vector.\n */\nimport { readdirSync, type Dirent } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { join } from 'node:path'\n\nimport { createDecoratorHandler, isControllerClass, type ServeAgent } from '@theokit/http'\n\nimport { dispatchCsrfWarn } from '../security/csrf-warn-dispatch.js'\nimport { enforceCsrf, type DisallowedConfig } from '../security/csrf.js'\n\nimport { incomingMessageToWebRequest } from './node-request.js'\nimport { sendError } from './send-response.js'\n\n/** A decorator controller constructor (`@Controller` class). */\ntype ControllerClass = new (...args: never[]) => object\n\n/** Loads a controller module by absolute path. In dev this is Vite's `ssrLoadModule`\n * (the Task 1.1 swc transform has already compiled the parameter decorators); tests\n * inject `@theokit/http`'s `loadControllerWithSwc`. */\nexport type ControllerModuleLoader = (absPath: string) => Promise<Record<string, unknown>>\n\n/** A built controller route table exposed as a pure Web-Standard handler. */\ninterface ControllerDispatcher {\n /** `null` = no controller route matched — the host owns the miss (404 / fall-through). */\n dispatch(request: Request): Promise<Response | null>\n /** Non-executing route probe — true when a controller route owns `method` + `pathname`. */\n matches(method: string, pathname: string): boolean\n}\n\n// State-mutating methods get CSRF, mirroring the file-route pipeline (execute.ts).\nconst CSRF_PROTECTED_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/** Recursively collect `*.controller.ts` files under `dir` (absolute paths). */\nfunction findControllerFiles(dir: string): string[] {\n const found: string[] = []\n const walk = (current: string): void => {\n let entries: Dirent[]\n try {\n entries = readdirSync(current, { withFileTypes: true })\n } catch {\n return // dir doesn't exist — no controllers\n }\n for (const entry of entries) {\n const full = join(current, entry.name)\n if (entry.isDirectory()) walk(full)\n else if (entry.name.endsWith('.controller.ts')) found.push(full)\n }\n }\n walk(dir)\n return found\n}\n\n/** A discovered controller: its source file + the loaded `@Controller` class. */\ninterface ControllerModule {\n filePath: string\n cls: ControllerClass\n}\n\n/**\n * Load every `@Controller` class under `controllersDir` via the injected loader,\n * keeping each class paired with its source file (needed by the typed-client\n * codegen to emit `import type { X } from '<file>'`). Non-controller exports are\n * ignored (`isControllerClass` — reused from @theokit/http).\n */\nexport async function scanControllerModules(\n controllersDir: string,\n loadModule: ControllerModuleLoader,\n): Promise<ControllerModule[]> {\n const files = findControllerFiles(controllersDir)\n const modules: ControllerModule[] = []\n for (const filePath of files) {\n const mod = await loadModule(filePath)\n for (const exported of Object.values(mod)) {\n if (typeof exported === 'function' && isControllerClass(exported)) {\n modules.push({ filePath, cls: exported as ControllerClass })\n }\n }\n }\n return modules\n}\n\n/** Load every `@Controller` class under `controllersDir` (classes only). */\nasync function scanControllers(\n controllersDir: string,\n loadModule: ControllerModuleLoader,\n): Promise<ControllerClass[]> {\n const modules = await scanControllerModules(controllersDir, loadModule)\n return modules.map((m) => m.cls)\n}\n\n/**\n * Scan `controllersDir` and build a Web-Standard dispatcher over the decorator\n * controllers found. Returns `null` when the directory has no controllers, so\n * the host can skip the controller path entirely (zero cost for routes-only apps).\n *\n * Dispatch REUSES @theokit/http's `createDecoratorHandler` (match + `@Param`\n * binding + `@Body` validation + Response building) — never re-implemented (ADR-1).\n */\nexport async function createControllerDispatcher(opts: {\n controllersDir: string\n loadModule: ControllerModuleLoader\n /** M47 — serves `@Expose`-bound agent routes (theo supplies a `mountAgent`-backed impl). */\n serveAgent?: ServeAgent\n}): Promise<ControllerDispatcher | null> {\n const classes = await scanControllers(opts.controllersDir, opts.loadModule)\n if (classes.length === 0) return null\n const handle = createDecoratorHandler({ controllers: classes, serveAgent: opts.serveAgent })\n return {\n dispatch: (request) => handle(request),\n matches: (method, pathname) => handle.matches(method, pathname),\n }\n}\n\n/** Write a buffered Web `Response` (controllers never stream) to a Node response. */\nasync function writeControllerResponse(res: ServerResponse, response: Response): Promise<void> {\n const headersBag: Record<string, string> = {}\n for (const [k, v] of response.headers) {\n if (k.toLowerCase() !== 'set-cookie') headersBag[k] = v\n }\n const setCookies = response.headers.getSetCookie()\n if (setCookies.length > 0) res.setHeader('Set-Cookie', setCookies)\n res.writeHead(response.status, headersBag)\n const body = response.body ? await response.text() : ''\n res.end(body || undefined)\n}\n\n/**\n * The `api-middleware` fall-through in one call: scan `controllersDir`, build the\n * dispatcher, and serve the request. Builds a body-ful Web `Request` (`@Body`\n * needs the body; the raw stream is undrained at a route miss) and enforces CSRF\n * with the SAME gate file routes use (parity). Returns `true` when a controller\n * handled it (or CSRF blocked it), `false` when there are no controllers OR none\n * matched (the host continues to its own 404). Built per-miss so controller edits\n * reflect via HMR.\n */\nexport async function dispatchControllerRequest(args: {\n controllersDir: string\n loadModule: ControllerModuleLoader\n req: IncomingMessage\n res: ServerResponse\n csrfMode: 'off' | 'warn' | 'strict'\n disallowed?: DisallowedConfig\n requestId: string\n /** M47 — serves `@Expose`-bound agent routes (mountAgent-backed); omit for routes-only apps. */\n serveAgent?: ServeAgent\n}): Promise<boolean> {\n const { req, res, csrfMode, disallowed, requestId } = args\n const dispatcher = await createControllerDispatcher({\n controllersDir: args.controllersDir,\n loadModule: args.loadModule,\n serveAgent: args.serveAgent,\n })\n if (!dispatcher) return false\n\n const method = (req.method ?? 'GET').toUpperCase()\n const webRequest = incomingMessageToWebRequest(req)\n const pathname = new URL(webRequest.url).pathname\n\n // CSRF parity: enforce ONLY when a protected-method controller route actually\n // owns this path (probe with the non-executing matcher — never double-dispatch,\n // which would run the handler + its side effects). An unrouted path falls\n // through to the host's own 404, not a 403.\n if (CSRF_PROTECTED_METHODS.has(method) && dispatcher.matches(method, pathname)) {\n const decision = enforceCsrf(\n req,\n csrfMode,\n { warn: dispatchCsrfWarn, path: req.url },\n disallowed,\n )\n if (!decision.allow) {\n sendError(\n res,\n 'CSRF_INVALID',\n decision.reason ?? 'CSRF check failed',\n 403,\n undefined,\n requestId,\n )\n return true\n }\n }\n\n const response = await dispatcher.dispatch(webRequest)\n if (response === null) return false\n await writeControllerResponse(res, response)\n return true\n}\n","/**\n * T1.4 — Server-side batch handler.\n *\n * Receives `{ requests: [...] }` POSTed to `/api/__theo_batch__` and returns\n * `{ results: [...] }` with per-item error isolation. EC-2: items cannot\n * override auth/forwarded headers (would be a session-bypass vector).\n */\n\nimport { z } from 'zod'\n\nexport const STRIPPED_HEADERS = [\n 'authorization',\n 'cookie',\n 'x-forwarded-for',\n 'x-forwarded-host',\n 'x-forwarded-proto',\n 'x-real-ip',\n 'host',\n] as const\n\nexport const BATCH_PATH = '/api/__theo_batch__'\nconst DEFAULT_MAX_BATCH = 32\n\nexport class BatchPathConflictError extends Error {\n constructor(path: string) {\n super(\n `Server route conflicts with reserved batch path ${path}. ` +\n `Rename the route or disable batching in theo.config.ts.`,\n )\n this.name = 'BatchPathConflictError'\n }\n}\n\nconst batchRequestSchema = z.object({\n path: z.string().min(1),\n method: z.string().min(1),\n query: z.record(z.string(), z.unknown()).optional(),\n body: z.unknown().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n})\n\nconst batchPayloadSchema = z.object({\n requests: z.array(batchRequestSchema).min(1),\n})\n\nexport type BatchRequestItem = z.infer<typeof batchRequestSchema>\nexport type BatchPayload = z.infer<typeof batchPayloadSchema>\n\nexport type BatchExecuteFn = (\n req: BatchRequestItem,\n) => Promise<{ data: unknown } | { error: { message: string; code?: string } }>\n\nexport interface HandleBatchOptions {\n execute: BatchExecuteFn\n /** Max number of items per batch. Default 32. */\n max?: number\n /** Outer-request headers that override per-item headers in STRIPPED_HEADERS. */\n outerHeaders?: Record<string, string>\n}\n\nexport type BatchResultItem = { data: unknown } | { error: { message: string; code?: string } }\n\nexport interface BatchResponse {\n results: BatchResultItem[]\n}\n\n/**\n * Sanitize a per-item header object: keys in STRIPPED_HEADERS are removed,\n * then the outer request's values for those keys are layered on top so that\n * downstream middlewares see the real session/auth headers.\n */\nfunction sanitizeItemHeaders(\n itemHeaders: Record<string, string> | undefined,\n outerHeaders: Record<string, string> | undefined,\n): Record<string, string> {\n const out: Record<string, string> = {}\n if (itemHeaders) {\n for (const [k, v] of Object.entries(itemHeaders)) {\n const lower = k.toLowerCase()\n if (!(STRIPPED_HEADERS as readonly string[]).includes(lower)) {\n out[lower] = v\n }\n }\n }\n if (outerHeaders) {\n for (const stripped of STRIPPED_HEADERS) {\n // `Object.hasOwn` defends against missing keys without triggering\n // `no-unnecessary-condition` (TypeScript types `outerHeaders` keys\n // as defined; `hasOwn` keeps the conditional honest at runtime).\n if (Object.hasOwn(outerHeaders, stripped)) {\n out[stripped] = outerHeaders[stripped]\n }\n }\n }\n return out\n}\n\n/**\n * Validate + execute a batch request.\n *\n * CR-028 fix: previously the signature was `payload: BatchPayload`,\n * suggesting the caller had already validated. In reality `api-middleware`\n * passes `JSON.parse(rawBody) as BatchPayload` — an unsafe cast over raw\n * HTTP input. We widen the input type to `unknown` so the type system\n * forces validation, then run Zod once at this single trust boundary.\n */\nexport async function handleBatchRequest(\n payload: unknown,\n options: HandleBatchOptions,\n): Promise<BatchResponse> {\n const parsed = batchPayloadSchema.parse(payload)\n const max = options.max ?? DEFAULT_MAX_BATCH\n if (parsed.requests.length > max) {\n throw new Error(`Batch size ${parsed.requests.length} exceeds max ${max}`)\n }\n\n const results: BatchResultItem[] = []\n for (const item of parsed.requests) {\n const sanitized: BatchRequestItem = {\n ...item,\n headers: sanitizeItemHeaders(item.headers, options.outerHeaders),\n }\n try {\n const r = await options.execute(sanitized)\n results.push(r)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n results.push({ error: { message } })\n }\n }\n return { results }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\n/**\n * T1.2 — CORS middleware.\n *\n * Single global middleware that runs FIRST in the request pipeline:\n * CORS preflight → rate limit → CSRF → security headers → handler\n *\n * Preflight (`OPTIONS` with `Access-Control-Request-Method`) is handled\n * by `handlePreflight`, which short-circuits the response with 204 +\n * Access-Control-* headers.\n *\n * Non-preflight requests pass through; `applyHeaders` adds\n * `Access-Control-Allow-Origin` (echoing the request's Origin),\n * `Access-Control-Expose-Headers`, and `Access-Control-Allow-Credentials`.\n *\n * Per ADR D3: preflight responses are deterministic and only the matched\n * origin is echoed back (never `'*'` when credentials are enabled —\n * required by the CORS spec).\n */\n\n// `'*'` is conceptually distinct from a regular host string (it means\n// \"any origin\"), but TypeScript-wise it is just `string`, so we collapse\n// the union and document the wildcard via the type's name. Callers should\n// still pass the literal `'*'` to mean \"allow anywhere\" for readability.\nexport type CorsOrigin =\n | string\n | RegExp\n | readonly (string | RegExp)[]\n | ((origin: string) => boolean)\n\nexport interface CorsConfig {\n origins: CorsOrigin\n methods?: readonly ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD')[]\n allowedHeaders?: readonly string[]\n exposedHeaders?: readonly string[]\n credentials?: boolean\n maxAge?: number\n}\n\nexport interface CorsHandler {\n handlePreflight(req: IncomingMessage, res: ServerResponse): boolean\n applyHeaders(req: IncomingMessage, res: ServerResponse): void\n}\n\nconst DEFAULT_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'] as const\nconst DEFAULT_ALLOWED_HEADERS = ['Content-Type', 'X-Theo-Action', 'Authorization'] as const\nconst DEFAULT_MAX_AGE = 600\n\n/**\n * Read the request Origin header. Per Node typing, it can be a string,\n * string[] (proxy doubled), or undefined. We take the FIRST non-empty\n * value (consistent with `csrf.ts:121-122`).\n */\nfunction readOrigin(req: IncomingMessage): string | undefined {\n const raw = req.headers.origin\n if (raw === undefined) return undefined\n if (Array.isArray(raw)) {\n return raw.find((v): v is string => typeof v === 'string' && v.length > 0)\n }\n return raw\n}\n\n/**\n * Test whether `origin` is allowed by `allowed`. Pure function — no I/O.\n *\n * EC-8: callback variants that throw are fail-closed (deny). Without\n * this, a transient datastore outage would silently widen CORS during\n * the failure window.\n */\nexport function matchesOrigin(origin: string, allowed: CorsOrigin): boolean {\n if (allowed === '*') return true\n if (typeof allowed === 'string') return origin === allowed\n if (allowed instanceof RegExp) {\n allowed.lastIndex = 0\n return allowed.test(origin)\n }\n if (Array.isArray(allowed)) {\n for (const entry of allowed) {\n if (typeof entry === 'string' && origin === entry) return true\n if (entry instanceof RegExp) {\n entry.lastIndex = 0\n if (entry.test(origin)) return true\n }\n }\n return false\n }\n if (typeof allowed === 'function') {\n // EC-8: fail-closed on any throw\n try {\n return allowed(origin)\n } catch {\n return false\n }\n }\n return false\n}\n\nexport function createCorsHandler(config: CorsConfig): CorsHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflight(req, res) {\n if (req.method !== 'OPTIONS') return false\n const acMethod = req.headers['access-control-request-method']\n if (!acMethod) return false\n const origin = readOrigin(req)\n if (!origin) return false\n\n if (!matchesOrigin(origin, config.origins)) {\n res.statusCode = 403\n res.end()\n return true\n }\n\n // Echo the matched origin (NEVER '*' when credentials are enabled —\n // browsers reject wildcard responses with credentials per CORS spec).\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Access-Control-Allow-Methods', methods.join(', '))\n res.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(', '))\n res.setHeader('Access-Control-Max-Age', maxAge)\n // Mark the response as origin-varying so caches don't poison\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n res.statusCode = 204\n res.end()\n return true\n },\n\n applyHeaders(req, res) {\n const origin = readOrigin(req)\n if (!origin) return\n if (!matchesOrigin(origin, config.origins)) return\n\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders && config.exposedHeaders.length > 0) {\n res.setHeader('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n\n/**\n * T5a.2 Phase B slice 5/6 — Web-Standards CORS handler.\n *\n * Mirror of `createCorsHandler(config): CorsHandler` for the Web `Request`\n * shape. Same `CorsConfig`, same `matchesOrigin` logic (pure helper\n * already), same security guarantees (echo matched origin only — never\n * `'*'` when credentials enabled; EC-8 fail-closed on callback throw).\n *\n * Signature differences vs the IncomingMessage pair:\n * - `handlePreflightRequest(request, config): Response | null` — returns\n * `Response` when this is a CORS preflight; `null` when not. Caller\n * short-circuits accordingly (same control-flow semantic as boolean).\n * - `applyCorsHeaders(request, target, config): void` — mutates a\n * `Headers` instance in place. Caller passes the headers they're\n * building for their Response.\n */\nexport interface CorsWebHandler {\n handlePreflightRequest(request: Request): Response | null\n applyCorsHeaders(request: Request, target: Headers): void\n}\n\nexport function createCorsWebHandler(config: CorsConfig): CorsWebHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflightRequest(request) {\n if (request.method !== 'OPTIONS') return null\n const acMethod = request.headers.get('access-control-request-method')\n if (acMethod === null || acMethod.length === 0) return null\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return null\n\n if (!matchesOrigin(origin, config.origins)) {\n return new Response(null, { status: 403 })\n }\n\n // Echo matched origin only (security: never `'*'` when credentials\n // enabled — browsers reject per CORS spec).\n const headers = new Headers({\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods': methods.join(', '),\n 'Access-Control-Allow-Headers': allowedHeaders.join(', '),\n 'Access-Control-Max-Age': maxAge,\n Vary: 'Origin',\n })\n if (credentials) headers.set('Access-Control-Allow-Credentials', 'true')\n return new Response(null, { status: 204, headers })\n },\n\n applyCorsHeaders(request, target) {\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return\n if (!matchesOrigin(origin, config.origins)) return\n\n target.set('Access-Control-Allow-Origin', origin)\n target.set('Vary', 'Origin')\n if (credentials) target.set('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders !== undefined && config.exposedHeaders.length > 0) {\n target.set('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n","// T5a.1b — Web Crypto migration. randomUUID() moved to globalThis.crypto.\n// IncomingMessage stays as a type-only import (runtime-clean — TS erases at\n// build); full IncomingMessage→Request boundary migration deferred to a\n// later T5a.1c+ slice per ADR-0028 incremental leaf-first sequence.\nimport type { IncomingMessage } from 'node:http'\n\n/**\n * Phase 7 — Observability: traceId propagation (D7).\n *\n * Extract a stable identifier from incoming requests so a single value\n * correlates the client request, every server log line, the response\n * envelope, and any downstream span. Precedence:\n *\n * 1. `traceparent` (W3C Trace Context — `00-{32-hex}-{16-hex}-{flags}`)\n * 2. `x-request-id` (Heroku / GCP / generic proxy header)\n * 3. Generated UUID (fresh per request)\n *\n * UUIDs are accepted as trace identifiers by every major vendor that\n * does not enforce strict 32-hex (Datadog, Honeycomb, Sentry, Logflare,\n * Axiom, etc). We don't need ULIDs to ship this surface.\n */\n\nexport const TRACE_HEADER = 'x-trace-id'\nexport const TRACE_PARENT_HEADER = 'traceparent'\nconst REQUEST_ID_HEADER = 'x-request-id'\n\n// W3C Trace Context: 00-<trace-id 32 hex>-<span-id 16 hex>-<flags 2 hex>\nconst TRACEPARENT_RE = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/\n\n/**\n * Parse a W3C Trace Context `traceparent` header value. Returns the\n * 32-hex trace-id when valid (and not the reserved all-zeros), else\n * `null`.\n */\nexport function parseTraceparent(value: string): string | null {\n if (!value) return null\n const m = TRACEPARENT_RE.exec(value)\n if (!m) return null\n const traceId = m[1]\n // W3C: trace-id of all zeroes is invalid by spec\n if (/^0+$/.test(traceId)) return null\n return traceId\n}\n\n/**\n * Pick the first string value out of an IncomingMessage header. Node\n * collapses repeated headers into arrays; proxies sometimes do this for\n * `x-request-id`. Empty strings count as absent.\n */\nfunction pickHeader(value: string | string[] | undefined): string | null {\n if (Array.isArray(value)) {\n for (const v of value) {\n if (typeof v === 'string' && v.length > 0) return v\n }\n return null\n }\n if (typeof value === 'string' && value.length > 0) return value\n return null\n}\n\n/**\n * T5a.2 Phase C slice 1/2 — pure traceId resolution from pre-extracted\n * header values. Shared between IncomingMessage and Web Request wrappers.\n */\nfunction resolveTraceIdFromHeaders(traceparent: string | null, requestId: string | null): string {\n if (traceparent !== null) {\n const parsed = parseTraceparent(traceparent)\n if (parsed !== null) return parsed\n }\n if (requestId !== null) return requestId\n return globalThis.crypto.randomUUID()\n}\n\n/**\n * Resolve the request's traceId following the precedence above.\n */\nexport function extractTraceId(req: IncomingMessage): string {\n return resolveTraceIdFromHeaders(\n pickHeader(req.headers[TRACE_PARENT_HEADER]),\n pickHeader(req.headers[REQUEST_ID_HEADER]),\n )\n}\n\n/**\n * T5a.2 Phase C slice 1/2 — Web-Standards-shaped traceId resolver.\n *\n * Mirror of `extractTraceId(req: IncomingMessage)` for the Web `Request`\n * shape. Same precedence (`traceparent` → `x-request-id` → generated\n * UUID). Uses `request.headers.get(name)` (native Web `Headers` API)\n * instead of the Node indexer.\n *\n * **Multi-value note:** Web `Headers` collapses repeated headers into a\n * single comma-separated string at parse. The IncomingMessage path's\n * `pickHeader` \"first non-empty value\" semantic is naturally satisfied\n * because there's no array to pick from on the Web side — `.get()`\n * returns the comma-joined value, which for `traceparent` / `x-request-id`\n * is treated as a single string anyway (both headers are conventionally\n * single-valued).\n */\nexport function extractTraceIdFromRequest(request: Request): string {\n return resolveTraceIdFromHeaders(\n request.headers.get(TRACE_PARENT_HEADER),\n request.headers.get(REQUEST_ID_HEADER),\n )\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { safeAudit, type AuditLogger } from '../observability/audit-log.js'\n\n/**\n * T5.1 — Built-in CSP report endpoint.\n *\n * Browsers POST violation reports to `report-uri` (legacy `application/csp-report`)\n * or `Reporting API` (`application/reports+json`). Framework auto-registers this\n * endpoint so `cspMode: 'report-only'` is actually useful out of the box.\n *\n * Forwards normalized violations to:\n * - audit logger (`csp.violation`)\n * - devtools dispatcher (dev only, for Errors tab)\n * - optional user hook (Sentry, etc.)\n *\n * EC-2: browser MAY send `{\"csp-report\": null}`, empty `{}`, or\n * reports+json entries lacking `body`. Handler MUST short-circuit to\n * 204 (valid format, no violation), NEVER crash via null deref.\n */\n\nexport const CSP_REPORT_PATH = '/__theo/csp-report'\n\n/** Max body bytes accepted. Real CSP reports are < 2 KB; 16 KB is generous. */\nconst MAX_BODY = 16 * 1024\n\nexport interface CspViolation {\n blockedUrl: string\n documentUrl: string\n violatedDirective: string\n effectiveDirective?: string\n originalPolicy?: string\n disposition?: 'enforce' | 'report'\n statusCode?: number\n sourceFile?: string\n lineNumber?: number\n columnNumber?: number\n}\n\nexport interface CspReportHandlerOptions {\n auditLogger?: AuditLogger\n devtoolsDispatcher?: {\n onCspViolation?: (v: CspViolation) => void\n }\n /** Optional user-provided sink (Sentry, custom log router). Errors here are swallowed. */\n onViolation?: (v: CspViolation) => void\n}\n\n/**\n * Map a legacy `application/csp-report` payload to the internal shape.\n * Caller must ensure `raw` is a non-null object.\n */\nfunction pickHeader(value: string | string[] | undefined): string {\n if (typeof value === 'string') return value\n if (Array.isArray(value) && value.length > 0) return value[0]\n return ''\n}\n\nfunction toStringSafe(value: unknown, fallback = '(missing)'): string {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n return fallback\n}\n\nexport function normalizeLegacy(raw: Record<string, unknown>): CspViolation {\n return {\n blockedUrl: toStringSafe(raw['blocked-uri']),\n documentUrl: toStringSafe(raw['document-uri']),\n violatedDirective: toStringSafe(raw['violated-directive']),\n effectiveDirective:\n typeof raw['effective-directive'] === 'string' ? raw['effective-directive'] : undefined,\n originalPolicy: typeof raw['original-policy'] === 'string' ? raw['original-policy'] : undefined,\n disposition:\n raw.disposition === 'enforce' || raw.disposition === 'report' ? raw.disposition : undefined,\n statusCode: typeof raw['status-code'] === 'number' ? raw['status-code'] : undefined,\n sourceFile: typeof raw['source-file'] === 'string' ? raw['source-file'] : undefined,\n lineNumber: typeof raw['line-number'] === 'number' ? raw['line-number'] : undefined,\n columnNumber: typeof raw['column-number'] === 'number' ? raw['column-number'] : undefined,\n }\n}\n\n/**\n * Map a `reports+json` entry to the internal shape. Returns `null` if\n * the entry lacks a usable `body` object (EC-2).\n */\nexport function normalizeNew(entry: unknown): CspViolation | null {\n if (!entry || typeof entry !== 'object') return null\n const body = (entry as { body?: unknown }).body\n if (!body || typeof body !== 'object') return null\n const b = body as Record<string, unknown>\n return {\n blockedUrl: toStringSafe(b.blockedURL),\n documentUrl: toStringSafe(b.documentURL),\n violatedDirective: toStringSafe(b.violatedDirective),\n effectiveDirective: typeof b.effectiveDirective === 'string' ? b.effectiveDirective : undefined,\n originalPolicy: typeof b.originalPolicy === 'string' ? b.originalPolicy : undefined,\n disposition:\n b.disposition === 'enforce' || b.disposition === 'report' ? b.disposition : undefined,\n statusCode: typeof b.statusCode === 'number' ? b.statusCode : undefined,\n sourceFile: typeof b.sourceFile === 'string' ? b.sourceFile : undefined,\n lineNumber: typeof b.lineNumber === 'number' ? b.lineNumber : undefined,\n columnNumber: typeof b.columnNumber === 'number' ? b.columnNumber : undefined,\n }\n}\n\nasync function readBody(req: IncomingMessage, maxBytes: number): Promise<string> {\n return await new Promise<string>((resolve, reject) => {\n const chunks: Buffer[] = []\n let total = 0\n req.on('data', (chunk: Buffer) => {\n total += chunk.length\n if (total > maxBytes) {\n reject(new Error('body too large'))\n req.destroy()\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => {\n resolve(Buffer.concat(chunks).toString('utf8'))\n })\n req.on('error', reject)\n })\n}\n\nexport async function handleCspReport(\n req: IncomingMessage,\n res: ServerResponse,\n opts: CspReportHandlerOptions,\n): Promise<void> {\n const ctHeader = req.headers['content-type']\n const ct = pickHeader(ctHeader)\n\n let raw: string\n try {\n raw = await readBody(req, MAX_BODY)\n } catch {\n res.statusCode = 413\n res.end()\n return\n }\n\n let violations: CspViolation[]\n try {\n if (ct.startsWith('application/csp-report')) {\n // EC-2: browsers MAY POST {\"csp-report\": null} or {} on\n // disposition='report' policies. Guard against null/undefined/non-object.\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const inner = parsed['csp-report']\n if (!inner || typeof inner !== 'object') {\n res.statusCode = 204\n res.end()\n return\n }\n violations = [normalizeLegacy(inner as Record<string, unknown>)]\n } else if (ct.startsWith('application/reports+json')) {\n // EC-2: filter out entries lacking `body` BEFORE normalizing.\n const parsed: unknown = JSON.parse(raw)\n const entries = Array.isArray(parsed) ? parsed : []\n violations = entries.map((e) => normalizeNew(e)).filter((v): v is CspViolation => v !== null)\n } else {\n res.statusCode = 415\n res.end()\n return\n }\n } catch {\n res.statusCode = 400\n res.end()\n return\n }\n\n for (const v of violations) {\n safeAudit(opts.auditLogger, {\n action: 'csp.violation',\n metadata: v as unknown as Record<string, unknown>,\n })\n try {\n opts.devtoolsDispatcher?.onCspViolation?.(v)\n } catch {\n // dispatcher errors are isolated from the request\n }\n try {\n opts.onViolation?.(v)\n } catch {\n // user hook throws are swallowed — never crash the request\n }\n }\n\n res.statusCode = 204\n res.end()\n}\n\n/**\n * T5a.2 Phase B slice 4/6 — Web-Standards CSP report handler.\n *\n * Mirror of `handleCspReport(req: IncomingMessage, res: ServerResponse,\n * opts): Promise<void>` for the Web `Request` shape. Returns\n * `Response` directly instead of mutating `res`.\n *\n * Same content-type dispatch (legacy `application/csp-report` vs new\n * `application/reports+json`), same normalizers (`normalizeLegacy`,\n * `normalizeNew`), same side-effect loop (safeAudit + devtools + user\n * hook). The body cap is enforced post-read because Web Request body\n * streaming doesn't have a portable mid-stream rejection primitive\n * across CF Workers / Bun / Deno; CSP reports are < 2 KB typical, well\n * under MAX_BODY (16 KB).\n *\n * Returns:\n * - 204 on accepted reports OR no-op empty payload\n * - 413 on body too large (post-read check)\n * - 415 on unsupported content-type\n * - 400 on malformed JSON\n */\nasync function readBodyFromRequest(request: Request, maxBytes: number): Promise<string | null> {\n const contentLengthHeader = request.headers.get('content-length')\n if (contentLengthHeader !== null) {\n const declared = Number.parseInt(contentLengthHeader, 10)\n if (Number.isFinite(declared) && declared > maxBytes) return null\n }\n const text = await request.text()\n if (text.length > maxBytes) return null\n return text\n}\n\nfunction dispatchViolations(violations: CspViolation[], opts: CspReportHandlerOptions): void {\n for (const v of violations) {\n safeAudit(opts.auditLogger, {\n action: 'csp.violation',\n metadata: v as unknown as Record<string, unknown>,\n })\n try {\n opts.devtoolsDispatcher?.onCspViolation?.(v)\n } catch {\n // dispatcher errors are isolated from the request\n }\n try {\n opts.onViolation?.(v)\n } catch {\n // user hook throws are swallowed — never crash the request\n }\n }\n}\n\nexport async function handleCspReportRequest(\n request: Request,\n opts: CspReportHandlerOptions,\n): Promise<Response> {\n const ct = request.headers.get('content-type') ?? ''\n\n const raw = await readBodyFromRequest(request, MAX_BODY)\n if (raw === null) {\n return new Response(null, { status: 413 })\n }\n\n let violations: CspViolation[]\n try {\n if (ct.startsWith('application/csp-report')) {\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const inner = parsed['csp-report']\n if (!inner || typeof inner !== 'object') {\n return new Response(null, { status: 204 })\n }\n violations = [normalizeLegacy(inner as Record<string, unknown>)]\n } else if (ct.startsWith('application/reports+json')) {\n const parsed: unknown = JSON.parse(raw)\n const entries = Array.isArray(parsed) ? parsed : []\n violations = entries.map((e) => normalizeNew(e)).filter((v): v is CspViolation => v !== null)\n } else {\n return new Response(null, { status: 415 })\n }\n } catch {\n return new Response(null, { status: 400 })\n }\n\n dispatchViolations(violations, opts)\n return new Response(null, { status: 204 })\n}\n","/**\n * T2.2 — `/__theo/csrf-readiness` endpoint.\n *\n * GET /__theo/csrf-readiness → 200 + JSON summary\n * POST /__theo/csrf-readiness/reset → 204; clears the store\n *\n * The reset endpoint enforces CSRF (own dog food) — requires\n * `X-Theo-Action: 1` AND a matching Origin header (EC-15). This avoids\n * the endpoint being weaponizable from a cross-origin page when the\n * endpoint is opt-in exposed in production.\n *\n * Mount opt-in: in dev mode, the host wires this in unconditionally. In\n * production, only mount when `config.security.csrfTelemetry.exposeReadinessEndpoint === true`.\n * EC-10 parallel: returns 404 (via boolean false return) when the URL\n * does not match — the caller continues normal request handling.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport type { CsrfReadinessStore } from './csrf-readiness-store.js'\n\nexport const CSRF_READINESS_PATH = '/__theo/csrf-readiness'\nexport const CSRF_READINESS_RESET_PATH = '/__theo/csrf-readiness/reset'\n\nfunction originMatchesHost(req: IncomingMessage): boolean {\n const origin = req.headers.origin\n if (typeof origin !== 'string') return false\n const host = req.headers.host\n if (typeof host !== 'string') return false\n try {\n const parsed = new URL(origin)\n return parsed.host === host\n } catch {\n return false\n }\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'content-type': 'application/json' })\n res.end(JSON.stringify(body))\n}\n\nfunction sendNoContent(res: ServerResponse): void {\n res.writeHead(204)\n res.end()\n}\n\nfunction sendError(res: ServerResponse, status: number, code: string, message: string): void {\n res.writeHead(status, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ error: { code, message } }))\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async return for future telemetry hooks\nexport async function handleCsrfReadiness(\n req: IncomingMessage,\n res: ServerResponse,\n store: CsrfReadinessStore,\n): Promise<boolean> {\n const url = (req.url ?? '').split('?')[0]\n const method = req.method ?? 'GET'\n\n if (url === CSRF_READINESS_PATH) {\n if (method === 'GET') {\n sendJson(res, 200, store.summary())\n return true\n }\n sendError(res, 405, 'METHOD_NOT_ALLOWED', `Use GET on ${CSRF_READINESS_PATH}`)\n return true\n }\n\n if (url === CSRF_READINESS_RESET_PATH) {\n if (method !== 'POST') {\n sendError(res, 405, 'METHOD_NOT_ALLOWED', `Use POST on ${CSRF_READINESS_RESET_PATH}`)\n return true\n }\n // Enforce CSRF on our own endpoint (dog-food).\n const hasHeader = req.headers['x-theo-action'] === '1'\n if (!hasHeader || !originMatchesHost(req)) {\n sendError(res, 403, 'CSRF_INVALID', 'Reset requires X-Theo-Action: 1 + same-origin')\n return true\n }\n store.reset()\n sendNoContent(res)\n return true\n }\n\n return false\n}\n\n/**\n * T5a.2 Phase B slice 3/6 — Web-Standards-shaped CSRF readiness handler.\n *\n * Mirror of `handleCsrfReadiness(req: IncomingMessage, res: ServerResponse,\n * store): Promise<boolean>` for the Web `Request` shape. Returns\n * `Response | null` instead of mutating `res` and returning a boolean:\n * - `Response` → this handler claimed the URL; caller short-circuits.\n * - `null` → URL doesn't match our endpoint; caller continues normal dispatch.\n *\n * Same routes (GET `CSRF_READINESS_PATH`, POST `CSRF_READINESS_RESET_PATH`).\n * Same CSRF dog-food on reset (X-Theo-Action + same-origin).\n *\n * Wire into `executeWebRequest` integration via a future Phase B sub-slice\n * (consumer can also call this directly today via the\n * `theokit/server/security` sub-path).\n */\nfunction buildJsonResponse(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\nfunction buildErrorResponse(status: number, code: string, message: string): Response {\n return buildJsonResponse(status, { error: { code, message } })\n}\n\n/**\n * Returns true when `Origin` header and request URL host match (RFC 6454\n * same-origin check). Web-Standards counterpart of `originMatchesHost`.\n */\nfunction originMatchesHostFromRequest(request: Request): boolean {\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return false\n const host = request.headers.get('host')\n if (host === null || host.length === 0) {\n // Fallback: derive host from request.url (Web Request guarantees absolute URL)\n try {\n const reqHost = new URL(request.url).host\n const originHost = new URL(origin).host\n return originHost === reqHost\n } catch {\n return false\n }\n }\n try {\n return new URL(origin).host === host\n } catch {\n return false\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async return for future telemetry hooks\nexport async function handleCsrfReadinessRequest(\n request: Request,\n store: CsrfReadinessStore,\n): Promise<Response | null> {\n const url = new URL(request.url).pathname\n const method = request.method.toUpperCase()\n\n if (url === CSRF_READINESS_PATH) {\n if (method === 'GET') {\n return buildJsonResponse(200, store.summary())\n }\n return buildErrorResponse(405, 'METHOD_NOT_ALLOWED', `Use GET on ${CSRF_READINESS_PATH}`)\n }\n\n if (url === CSRF_READINESS_RESET_PATH) {\n if (method !== 'POST') {\n return buildErrorResponse(\n 405,\n 'METHOD_NOT_ALLOWED',\n `Use POST on ${CSRF_READINESS_RESET_PATH}`,\n )\n }\n // Enforce CSRF on our own endpoint (dog-food).\n const hasHeader = request.headers.get('x-theo-action') === '1'\n if (!hasHeader || !originMatchesHostFromRequest(request)) {\n return buildErrorResponse(\n 403,\n 'CSRF_INVALID',\n 'Reset requires X-Theo-Action: 1 + same-origin',\n )\n }\n store.reset()\n return new Response(null, { status: 204 })\n }\n\n return null\n}\n","/**\n * T2.2 — In-memory bounded counter for CSRF warn events.\n *\n * Aggregates `csrf.warn` payloads by `(method, path, reason)` triple.\n * Used by the `/__theo/csrf-readiness` endpoint to expose a summary the\n * developer (or devtools tab) can inspect, so users do NOT need to grep\n * stdout to know which endpoints will break under 0.3.0 strict CSRF.\n *\n * Bounded at 1000 distinct keys (EC-22). Eviction is LRU-by-insertion —\n * when the cap is hit, the oldest key is dropped and a re-record of an\n * evicted key starts fresh (count: 1).\n *\n * Single-threaded by virtue of the JS event loop; Map operations are\n * atomic. NOT shared across processes — each worker has its own store.\n */\n\nexport interface CsrfWarnRecord {\n method: string\n path: string\n reason: string\n}\n\nexport interface CsrfReadinessRouteSummary {\n method: string\n path: string\n reason: string\n count: number\n firstSeen: string\n lastSeen: string\n}\n\nexport interface CsrfReadinessSummary {\n generatedAt: string\n totalEvents: number\n routes: CsrfReadinessRouteSummary[]\n}\n\ninterface StoredEntry {\n count: number\n firstSeen: string\n lastSeen: string\n}\n\nexport class CsrfReadinessStore {\n static readonly MAX_ENTRIES = 1000\n private readonly entries = new Map<string, StoredEntry>()\n\n private keyFor(event: CsrfWarnRecord): string {\n return `${event.method}\u0000${event.path}\u0000${event.reason}`\n }\n\n record(event: CsrfWarnRecord): void {\n const key = this.keyFor(event)\n const now = new Date().toISOString()\n const existing = this.entries.get(key)\n if (existing) {\n existing.count++\n existing.lastSeen = now\n return\n }\n if (this.entries.size >= CsrfReadinessStore.MAX_ENTRIES) {\n const firstKey = this.entries.keys().next().value\n if (firstKey !== undefined) this.entries.delete(firstKey)\n }\n this.entries.set(key, { count: 1, firstSeen: now, lastSeen: now })\n }\n\n summary(): CsrfReadinessSummary {\n let total = 0\n const routes: CsrfReadinessRouteSummary[] = []\n for (const [key, entry] of this.entries) {\n const [method, path, reason] = key.split('\u0000')\n routes.push({\n method,\n path,\n reason,\n count: entry.count,\n firstSeen: entry.firstSeen,\n lastSeen: entry.lastSeen,\n })\n total += entry.count\n }\n return {\n generatedAt: new Date().toISOString(),\n totalEvents: total,\n routes,\n }\n }\n\n reset(): void {\n this.entries.clear()\n }\n}\n"],"mappings":";;;;;;;;;;;AAIA,SAAS,mBAAgC;AAEzC,SAAS,YAAY;AAErB,SAAS,wBAAwB,yBAA0C;AAyB3E,IAAM,yBAAyB,oBAAI,IAAI,CAAC,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAGzE,SAAS,oBAAoB,KAAuB;AAClD,QAAM,QAAkB,CAAC;AACzB,QAAM,OAAO,CAAC,YAA0B;AACtC,QAAI;AACJ,QAAI;AACF,gBAAU,YAAY,SAAS,EAAE,eAAe,KAAK,CAAC;AAAA,IACxD,QAAQ;AACN;AAAA,IACF;AACA,eAAW,SAAS,SAAS;AAC3B,YAAM,OAAO,KAAK,SAAS,MAAM,IAAI;AACrC,UAAI,MAAM,YAAY,EAAG,MAAK,IAAI;AAAA,eACzB,MAAM,KAAK,SAAS,gBAAgB,EAAG,OAAM,KAAK,IAAI;AAAA,IACjE;AAAA,EACF;AACA,OAAK,GAAG;AACR,SAAO;AACT;AAcA,eAAsB,sBACpB,gBACA,YAC6B;AAC7B,QAAM,QAAQ,oBAAoB,cAAc;AAChD,QA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AC7C,eAAW,CAAC,KAAK,KAAK,KAAK,KAAK,SAAS;AACvC,YAAM,CAAC,QAAQ,MAAM,MAAM,IAAI,IAAI,MAAM,IAAG;AAC5C,aAAO,KAAK;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO,MAAM;AAAA,QACb,WAAW,MAAM;AAAA,QACjB,UAAU,MAAM;AAAA,MAClB,CAAC;AACD,eAAS,MAAM;AAAA,IACjB;AACA,WAAO;AAAA,MACL,cAAa,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,aAAa;AAAA,MACb;AAAA,IACF;AAAA,EACF;AAAA,EAEA,QAAc;AACZ,SAAK,QAAQ,MAAM;AAAA,EACrB;AACF;","names":["pickHeader","sendError"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/realtime/channel-manager.ts"],"sourcesContent":["import type { WebSocketLike } from '../define/define-websocket.js'\n\nexport class ChannelManager {\n private rooms = new Map<string, Set<WebSocketLike>>()\n private wsRooms = new Map<WebSocketLike, Set<string>>()\n\n subscribe(ws: WebSocketLike, room: string): void {\n let roomSet = this.rooms.get(room)\n if (!roomSet) {\n roomSet = new Set()\n this.rooms.set(room, roomSet)\n }\n roomSet.add(ws)\n\n let wsSet = this.wsRooms.get(ws)\n if (!wsSet) {\n wsSet = new Set()\n this.wsRooms.set(ws, wsSet)\n }\n wsSet.add(room)\n }\n\n unsubscribe(ws: WebSocketLike, room: string): void {\n this.rooms.get(room)?.delete(ws)\n if (this.rooms.get(room)?.size === 0) this.rooms.delete(room)\n\n this.wsRooms.get(ws)?.delete(room)\n if (this.wsRooms.get(ws)?.size === 0) this.wsRooms.delete(ws)\n }\n\n broadcast(room: string, data: unknown, exclude?: WebSocketLike): void {\n const clients = this.rooms.get(room)\n if (!clients) return\n\n const msg = JSON.stringify(data)\n for (const ws of clients) {\n if (ws !== exclude) ws.send(msg)\n }\n }\n\n broadcastAll(data: unknown): void {\n const msg = JSON.stringify(data)\n const seen = new Set<WebSocketLike>()\n for (const clients of this.rooms.values()) {\n for (const ws of clients) {\n if (!seen.has(ws)) {\n ws.send(msg)\n seen.add(ws)\n }\n }\n }\n }\n\n getRoomSize(room: string): number {\n return this.rooms.get(room)?.size ?? 0\n }\n\n cleanup(ws: WebSocketLike): void {\n const rooms = this.wsRooms.get(ws)\n if (rooms) {\n for (const room of rooms) {\n this.rooms.get(room)?.delete(ws)\n if (this.rooms.get(room)?.size === 0) this.rooms.delete(room)\n }\n }\n this.wsRooms.delete(ws)\n }\n}\n"],"mappings":";AAEO,IAAM,iBAAN,MAAqB;AAAA,EAClB,QAAQ,oBAAI,IAAgC;AAAA,EAC5C,UAAU,oBAAI,IAAgC;AAAA,EAEtD,UAAU,IAAmB,MAAoB;AAC/C,QAAI,UAAU,KAAK,MAAM,IAAI,IAAI;AACjC,QAAI,CAAC,SAAS;AACZ,gBAAU,oBAAI,IAAI;AAClB,WAAK,MAAM,IAAI,MAAM,OAAO;AAAA,IAC9B;AACA,YAAQ,IAAI,EAAE;AAEd,QAAI,QAAQ,KAAK,QAAQ,IAAI,EAAE;AAC/B,QAAI,CAAC,OAAO;AACV,cAAQ,oBAAI,IAAI;AAChB,WAAK,QAAQ,IAAI,IAAI,KAAK;AAAA,IAC5B;AACA,UAAM,IAAI,IAAI;AAAA,EAChB;AAAA,EAEA,YAAY,IAAmB,MAAoB;AACjD,SAAK,MAAM,IAAI,IAAI,GAAG,OAAO,EAAE;AAC/B,QAAI,KAAK,MAAM,IAAI,IAAI,GAAG,SAAS,EAAG,MAAK,MAAM,OAAO,IAAI;AAE5D,SAAK,QAAQ,IAAI,EAAE,GAAG,OAAO,IAAI;AACjC,QAAI,KAAK,QAAQ,IAAI,EAAE,GAAG,SAAS,EAAG,MAAK,QAAQ,OAAO,EAAE;AAAA,EAC9D;AAAA,EAEA,UAAU,MAAc,MAAe,SAA+B;AACpE,UAAM,UAAU,KAAK,MAAM,IAAI,IAAI;AACnC,QAAI,CAAC,QAAS;AAEd,UAAM,MAAM,KAAK,UAAU,IAAI;AAC/B,eAAW,MAAM,SAAS;AACxB,UAAI,OAAO,QAAS,IAAG,KAAK,GAAG;AAAA,IACjC;AAAA,EACF;AAAA,EAEA,aAAa,MAAqB;AAChC,UAAM,MAAM,KAAK,UAAU,IAAI;AAC/B,UAAM,OAAO,oBAAI,IAAmB;AACpC,eAAW,WAAW,KAAK,MAAM,OAAO,GAAG;AACzC,iBAAW,MAAM,SAAS;AACxB,YAAI,CAAC,KAAK,IAAI,EAAE,GAAG;AACjB,aAAG,KAAK,GAAG;AACX,eAAK,IAAI,EAAE;AAAA,QACb;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,YAAY,MAAsB;AAChC,WAAO,KAAK,MAAM,IAAI,IAAI,GAAG,QAAQ;AAAA,EACvC;AAAA,EAEA,QAAQ,IAAyB;AAC/B,UAAM,QAAQ,KAAK,QAAQ,IAAI,EAAE;AACjC,QAAI,OAAO;AACT,iBAAW,QAAQ,OAAO;AACxB,aAAK,MAAM,IAAI,IAAI,GAAG,OAAO,EAAE;AAC/B,YAAI,KAAK,MAAM,IAAI,IAAI,GAAG,SAAS,EAAG,MAAK,MAAM,OAAO,IAAI;AAAA,MAC9D;AAAA,IACF;AACA,SAAK,QAAQ,OAAO,EAAE;AAAA,EACxB;AACF;","names":[]}
@@ -1 +0,0 @@
1
- //# sourceMappingURL=chunk-NPMCKOX4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/transformer.ts","../src/server/agent/agent-card-handler.ts","../src/server/agent/approve-agent.ts","../src/server/agent/list-approvals-handler.ts","../src/server/agent/handle-agent-run-reconnect.ts","../src/server/agent/thread-dispatcher.ts","../src/server/agent/thread-run-registry.ts","../src/server/agent/handle-thread-routes.ts","../src/server/agent/serve-aux-routes.ts","../src/server/http/node-web-adapter.ts"],"sourcesContent":["import superjson from 'superjson'\n\n/**\n * T5.2 — pluggable response/request transformer.\n *\n * `superjson` is the default, preserving Date/Map/Set/BigInt/etc.\n * `json` is the lightweight option (plain JSON.stringify/parse).\n * Users can supply a custom object implementing this contract.\n */\nexport interface TheoTransformer {\n name: string\n serialize: (value: unknown) => string\n deserialize: (raw: string) => unknown\n}\n\nexport const superjsonTransformer: TheoTransformer = {\n name: 'superjson',\n serialize: (v) => JSON.stringify(superjson.serialize(v)),\n deserialize: (raw) => {\n const parsed = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(parsed)\n },\n}\n\nexport const jsonTransformer: TheoTransformer = {\n name: 'json',\n serialize: (v) => JSON.stringify(v),\n deserialize: (raw) => JSON.parse(raw) as unknown,\n}\n\nconst BUILT_INS: Record<string, TheoTransformer> = {\n superjson: superjsonTransformer,\n json: jsonTransformer,\n}\n\nexport function resolveTransformer(\n selector: 'json' | 'superjson' | TheoTransformer,\n): TheoTransformer {\n if (typeof selector === 'string') {\n // selector is 'json' | 'superjson' literal — both keys exist in\n // BUILT_INS by construction. Type system guarantees a hit; we keep\n // a defensive fallback that the compiler cannot see is unreachable\n // at runtime, just in case someone adds a new literal to the union\n // but forgets to register the built-in.\n const built = BUILT_INS[selector]\n // Defensive: the public union ensures `built` is defined, but if a\n // future contributor extends the union without registering the impl,\n // the cast keeps the failure mode loud.\n if ((built as TheoTransformer | undefined) === undefined) {\n throw new Error(\n `Unknown transformer \"${selector}\". Built-in options: ${Object.keys(BUILT_INS).join(', ')}.`,\n )\n }\n return built\n }\n if (\n typeof selector !== 'object' ||\n typeof selector.serialize !== 'function' ||\n typeof selector.deserialize !== 'function'\n ) {\n throw new Error(\n `Custom transformer must have serialize and deserialize functions. Got: ${JSON.stringify(selector)}`,\n )\n }\n return selector\n}\n","/**\n * M15 (theokit-ai-first) — serve the A2A agent card at `/.well-known/<name>/agent-card.json`.\n *\n * `buildAgentCard` (@theokit/agents) is the pure generator; this handler compiles a loaded agent\n * module to its tools + streaming capability, builds the card, and returns it as a Web-Standard\n * JSON `Response` (G8). The dev middleware + prod handler branch to this before the agent POST route.\n */\nimport {\n type AgentManifestEntry,\n buildAgentCard,\n compileAgentModule,\n} from '@theokit/agents'\n\nconst WELL_KNOWN = /^\\/\\.well-known\\/([^/]+)\\/agent-card\\.json$/\n\n/** Return the agent name when `urlPath` is a well-known card path, else `null`. */\nexport function isAgentCardPath(urlPath: string): string | null {\n const match = WELL_KNOWN.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Build a minimal manifest entry (the subset `buildAgentCard` reads) from a compiled agent. */\nfunction toManifestEntry(name: string, route: string, mod: unknown): AgentManifestEntry {\n const compiled = compileAgentModule(mod, `agent card for \"${name}\"`)\n return {\n name,\n route,\n stream: compiled.stream,\n mainLoop: { method: '', strategy: '' },\n guards: [],\n interceptors: [],\n tools: compiled.tools.map((t) => ({\n name: t.name,\n description: t.description,\n approval: false,\n trace: false,\n audit: false,\n })),\n subAgents: [],\n }\n}\n\n/**\n * Serve the A2A card for a loaded agent module. Returns 200 with the card JSON, or 500 with an\n * error body if the module is not a valid agent (fail-clear, not a silent empty card).\n */\nexport function handleAgentCard(mod: unknown, name: string, route: string, baseUrl: string): Response {\n try {\n const card = buildAgentCard(toManifestEntry(name, route, mod), { baseUrl })\n return new Response(JSON.stringify(card), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n } catch (err) {\n return new Response(\n JSON.stringify({ error: { code: 'AGENT_CARD_FAILED', message: err instanceof Error ? err.message : 'card build failed' } }),\n { status: 500, headers: { 'content-type': 'application/json; charset=utf-8' } },\n )\n }\n}\n","/**\n * M4 (theokit-ai-first) — the HITL approve endpoint: `POST /api/agents/<name>/approve/<approvalId>`.\n *\n * The counterpart to `mountAgent`'s HITL pause. While a gated tool holds the SDK run paused (the\n * awaited `pre_tool_call` hook), the client POSTs here with `{ approved }`; this resolves the\n * pending approval in the shared registry, which un-pauses the run (allow) or vetoes the tool (deny).\n *\n * Web-Standard `Request` → `Response`, one wiring point shared by dev (vite middleware) and prod\n * (built server) so the two never drift (EC-4 parity with `mountAgent`). The registry is INJECTED —\n * dev/prod pass the process singleton (`getApprovalRegistry`), tests pass a fresh instance.\n */\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport type { ApprovalDecision, ApprovalRegistry } from './approval-registry.js'\n\n/** The path segment separating the agent name from the approval id. */\nconst APPROVE_SEGMENT = '/approve/'\n\n/**\n * Extract the `<approvalId>` from a `/api/agents/<name>/approve/<approvalId>` path.\n * Returns `null` when the path has no `/approve/` segment or an empty / nested id.\n */\nexport function parseApprovalId(urlPath: string): string | null {\n const at = urlPath.indexOf(APPROVE_SEGMENT)\n if (at === -1) return null\n const id = urlPath.slice(at + APPROVE_SEGMENT.length)\n return id.length > 0 && !id.includes('/') ? id : null\n}\n\n/** True when `urlPath` targets a HITL approve endpoint (used by dev/prod routing to branch early). */\nexport function isApprovalPath(urlPath: string): boolean {\n return urlPath.includes(APPROVE_SEGMENT)\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * M20 — cap on the serialized custom payload (16 KiB). A payload is a small structured note\n * (edited args, a reviewer comment), not a data channel — an oversized one is rejected fail-fast\n * rather than silently truncated (Rule 8).\n */\nconst MAX_PAYLOAD_BYTES = 16 * 1024\n\n/**\n * Extract an {@link ApprovalDecision} from an untrusted body; `null` when the shape is wrong.\n *\n * M20 — accepts an optional `reason` (string) and `payload` (object, capped at\n * {@link MAX_PAYLOAD_BYTES}). Backward-compatible: `{ approved }` and `{ approved, reason }` parse\n * unchanged. A non-object or oversized `payload` is rejected (returns `null` → the route 400s).\n *\n * @public\n */\nexport function parseApprovalBody(body: unknown): ApprovalDecision | null {\n if (typeof body !== 'object' || body === null) return null\n const b = body as Record<string, unknown>\n if (typeof b.approved !== 'boolean') return null\n const decision: ApprovalDecision = { approved: b.approved }\n if (b.reason !== undefined) {\n if (typeof b.reason !== 'string') return null\n decision.reason = b.reason\n }\n if (b.payload !== undefined) {\n if (typeof b.payload !== 'object' || b.payload === null || Array.isArray(b.payload)) return null\n if (JSON.stringify(b.payload).length > MAX_PAYLOAD_BYTES) return null\n decision.payload = b.payload\n }\n return decision\n}\n\n/**\n * Resolve a pending HITL approval. CSRF-guarded like `mountAgent` (the custom `X-Theo-Action`\n * header + Origin match) — a cross-origin POST must not approve a paused tool. Returns:\n * 403 CSRF_FAILED — strict CSRF check failed\n * 400 BAD_REQUEST — no `/approve/<id>` in the path, or body lacks a boolean `approved`\n * 404 NOT_PENDING — the id is unknown or already settled (idempotent double-submit)\n * 200 { resolved:true } — the approval was settled by this call\n */\nexport async function handleAgentApproval(\n request: Request,\n urlPath: string,\n registry: ApprovalRegistry,\n csrfMode: CsrfMode = 'strict',\n): Promise<Response> {\n if (csrfMode !== 'off') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid && csrfMode === 'strict') {\n return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n }\n\n const approvalId = parseApprovalId(urlPath)\n if (approvalId === null) {\n return jsonError(400, 'BAD_REQUEST', 'Approval path must be /api/agents/<name>/approve/<id>.')\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → handled below as a 400 */\n }\n const parsed = parseApprovalBody(body)\n if (parsed === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request body must contain a boolean `approved`.')\n }\n\n const resolved = registry.resolve(approvalId, parsed)\n if (!resolved) {\n return jsonError(404, 'NOT_PENDING', `No pending approval for id '${approvalId}'.`)\n }\n return new Response(JSON.stringify({ resolved: true }), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n })\n}\n","/**\n * M14 (theokit-ai-first) — GET /api/agents/<name>/approvals: list pending HITL approvals.\n *\n * Serves `ApprovalRegistry.list()` as JSON. Single-process contract (ADR 0038) — the list is\n * process-wide; the `<name>` segment is accepted for a future per-agent/durable store but the\n * in-process registry lists all pending approvals. Web Standards Response (G8).\n */\nimport type { ApprovalRegistry } from './approval-registry.js'\n\nconst LIST_PATH = /^\\/api\\/agents\\/([^/]+)\\/approvals$/\n\n/** Return the agent name when `urlPath` is the approvals-listing path, else `null`. */\nexport function isListApprovalsPath(urlPath: string): string | null {\n const match = LIST_PATH.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Serve the currently-pending approvals as `{ approvals: [...] }` JSON. */\nexport function handleListApprovals(registry: ApprovalRegistry): Response {\n return new Response(JSON.stringify({ approvals: registry.list() }), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n","import {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport type { RunEventCache } from './run-event-cache.js'\n\n/**\n * M37 (ADR-0046 D5) — the reconnect / observe endpoint handler for\n * `GET /api/agents/<name>/runs/<runId>/stream`.\n *\n * Replays the frames the client missed (`seq > Last-Event-ID`, SSE-native), then\n * — if the run is still live — follows the live tail; a SECOND client can\n * observe a run a first started. Run already ended ⇒ replay + `[DONE]`. Unknown\n * `runId` ⇒ 404. The request `AbortSignal` unsubscribes on disconnect.\n */\n\nconst RUN_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/runs\\/([^/]+)\\/stream$/\n\n/**\n * Match `GET /api/agents/<name>/runs/<runId>/stream`; returns the decoded\n * `{ name, runId }` or `null` to fall through (mirrors `isMcpPath` etc.).\n */\nexport function isAgentRunStreamPath(urlPath: string): { name: string; runId: string } | null {\n const m = RUN_STREAM_PATH.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), runId: decodeURIComponent(m[2]) } : null\n}\n\n/** Parse `Last-Event-ID` (a frame `seq`) to a number; absent/invalid ⇒ -1 (replay from the start). */\nfunction parseLastEventId(raw: string | null): number {\n if (raw === null) return -1\n const n = Number.parseInt(raw, 10)\n return Number.isInteger(n) && n >= 0 ? n : -1\n}\n\nexport function handleAgentRunReconnect(\n runId: string,\n request: Request,\n cache: RunEventCache,\n): Response {\n // Unknown run ⇒ 404 (a run never started here, or already evicted).\n if (!cache.has(runId)) {\n return new Response(\n JSON.stringify({ error: { code: 'RUN_NOT_FOUND', message: `Unknown run '${runId}'.` } }),\n {\n status: 404,\n headers: { 'content-type': 'application/json' },\n },\n )\n }\n\n const afterSeq = parseLastEventId(request.headers.get('last-event-id'))\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const safeEnqueue = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* controller already closed by an abort race — ignore */\n }\n }\n const close = (): void => {\n if (closed) return\n safeEnqueue(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n\n // Atomic: snapshot replay frames AND subscribe to the live tail in one tick.\n const res = cache.attach(\n runId,\n afterSeq,\n (frame) => {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n // Evicted between has() and attach() (rare TOCTOU) ⇒ just end the stream.\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n }\n if (res.ended) {\n close()\n return\n }\n // Client disconnects ⇒ detach the live listener + close.\n request.signal.addEventListener('abort', () => {\n res.unsubscribe()\n close()\n })\n },\n })\n\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS, [RUN_ID_HEADER]: runId } })\n}\n","/**\n * M39 (ADR-0048) — the thread follow-up dispatcher.\n *\n * Drives a run over the M37 durable cache HEADLESS — it iterates the SDK chunk\n * generator and `cache.append`s directly, NOT via a `Response` `ReadableStream`\n * (whose backpressure would stall a run with no HTTP reader). Subscribers read\n * from the cache via the thread / reconnect stream.\n *\n * - Post to an IDLE thread ⇒ start a run + pump.\n * - Post to an ACTIVE thread ⇒ FIFO-queue the follow-up.\n * - On terminal ⇒ `registry.endRun` hands back the next queued follow-up, which\n * is dispatched as a continuation on the SAME sessionId (⇒ the SDK continues\n * the conversation via its `ConversationStorageAdapter`).\n *\n * This adds NO agent loop — it reuses the SDK run (`startRun`) + the M37 cache.\n * Single-process (ADR-0048 D2).\n */\n\nimport type { UIMessageChunk } from 'ai'\n\nimport { type RunEventCache, mintRunId } from './run-event-cache.js'\nimport type { ThreadRunRegistry } from './thread-run-registry.js'\n\ninterface ThreadDispatchDeps {\n readonly registry: ThreadRunRegistry\n readonly cache: RunEventCache\n /** Start a run for a follow-up on `sessionId`; returns the SDK chunk stream. */\n readonly startRun: (sessionId: string, message: string) => AsyncIterable<UIMessageChunk>\n}\n\n/** Result of posting a follow-up: the started `runId` (idle thread) or `queued` (active thread). */\ntype PostFollowUpResult = { runId: string } | { queued: true }\n\n/**\n * Post a follow-up on a thread. IDLE ⇒ start a run (returns its `runId`); ACTIVE\n * ⇒ FIFO-queue it (returns `{ queued: true }`) — dispatched when the active run ends.\n */\nexport function postThreadFollowUp(\n deps: ThreadDispatchDeps,\n sessionId: string,\n message: string,\n): PostFollowUpResult {\n if (deps.registry.getActive(sessionId) !== null) {\n deps.registry.queue(sessionId, { message })\n return { queued: true }\n }\n return { runId: startAndPump(deps, sessionId, message) }\n}\n\n/** Mint a runId, mark the thread active, and pump the run into the cache headless. */\nfunction startAndPump(deps: ThreadDispatchDeps, sessionId: string, message: string): string {\n const runId = mintRunId()\n // Register the run in the cache SYNCHRONOUSLY (before the async pump appends its\n // first frame) so a subscriber resolving the active runId can attach immediately.\n deps.cache.begin(runId)\n deps.registry.startRun(sessionId, runId)\n pumpIntoCache(deps, sessionId, runId, deps.startRun(sessionId, message))\n return runId\n}\n\n/**\n * Drive `chunks` into the cache under `runId`, then end the run and dispatch the\n * next queued follow-up (if any) as a continuation. Fire-and-forget — the caller\n * does not await the run; subscribers observe it via the cache.\n */\nfunction pumpIntoCache(\n deps: ThreadDispatchDeps,\n sessionId: string,\n runId: string,\n chunks: AsyncIterable<UIMessageChunk>,\n): void {\n void (async () => {\n try {\n for await (const chunk of chunks) {\n deps.cache.append(runId, JSON.stringify(chunk))\n }\n } catch {\n // The SDK translator owns error semantics (surfaces failures as chunks);\n // the transport guarantees only a terminated, cache-ended run.\n } finally {\n deps.cache.end(runId)\n const next = deps.registry.endRun(sessionId, runId)\n if (next !== undefined) startAndPump(deps, sessionId, next.message)\n }\n })()\n}\n","/**\n * M39 (ADR-0048) — the in-process thread→run registry.\n *\n * A thread is the existing `sessionId` (the SDK conversation key). This registry\n * tracks, per thread, the single ACTIVE run, a FIFO queue of follow-ups to\n * dispatch as continuations, and one-shot \"next run\" waiters (so a client can\n * subscribe to a thread before posting a message and attach when the run starts).\n *\n * Pure state only — it never starts a run or touches the transport. The route\n * layer owns dispatch: on `endRun` it receives the next queued follow-up (if any)\n * and starts the continuation over the M37 durable transport.\n *\n * Single-process contract (ADR-0048 D2): a multi-instance deploy needs a shared\n * registry + leasing — that is infra (TheoCloud), explicitly out of M39. The\n * interface is injectable so a durable impl slots in later without touching the\n * routes. We do NOT build a distributed store now (YAGNI).\n */\n\n/** A follow-up message queued on an active thread, dispatched as a continuation. */\nexport interface FollowUp {\n readonly message: string\n}\n\nexport interface ThreadRunRegistry {\n /** The active runId for a thread, or `null` when the thread is idle. */\n getActive(sessionId: string): string | null\n /** Mark a run started for a thread (sets it active; fires + clears one-shot waiters). */\n startRun(sessionId: string, runId: string): void\n /**\n * Mark `runId` ended for a thread. A no-op unless `runId` is the current active\n * run (a stale terminal never clears a newer run). Clears the active run and\n * returns the next FIFO follow-up to dispatch as a continuation, or `undefined`.\n */\n endRun(sessionId: string, runId: string): FollowUp | undefined\n /** FIFO-enqueue a follow-up on a thread (dispatched when the active run ends). */\n queue(sessionId: string, followUp: FollowUp): void\n /**\n * Register a ONE-SHOT waiter fired with the runId of the NEXT run started on\n * this thread. Returns an unsubscribe fn. Used by subscribe-by-thread on an\n * idle thread (attach when the next run starts).\n */\n onNextRun(sessionId: string, cb: (runId: string) => void): () => void\n}\n\ninterface ThreadState {\n activeRunId: string | null\n readonly queue: FollowUp[]\n readonly waiters: Set<(runId: string) => void>\n}\n\nexport function createInProcessThreadRunRegistry(): ThreadRunRegistry {\n const threads = new Map<string, ThreadState>()\n const ensure = (sessionId: string): ThreadState => {\n let s = threads.get(sessionId)\n if (s === undefined) {\n s = { activeRunId: null, queue: [], waiters: new Set() }\n threads.set(sessionId, s)\n }\n return s\n }\n\n return {\n getActive(sessionId) {\n return threads.get(sessionId)?.activeRunId ?? null\n },\n startRun(sessionId, runId) {\n const s = ensure(sessionId)\n s.activeRunId = runId\n // Fire one-shot waiters, then clear them (single-threaded → no re-entrancy race).\n const waiters = [...s.waiters]\n s.waiters.clear()\n for (const cb of waiters) cb(runId)\n },\n endRun(sessionId, runId) {\n const s = threads.get(sessionId)\n if (s?.activeRunId !== runId) return undefined\n s.activeRunId = null\n return s.queue.shift()\n },\n queue(sessionId, followUp) {\n ensure(sessionId).queue.push(followUp)\n },\n onNextRun(sessionId, cb) {\n const s = ensure(sessionId)\n s.waiters.add(cb)\n return () => {\n s.waiters.delete(cb)\n }\n },\n }\n}\n\nlet serverRegistry: ThreadRunRegistry | undefined\n\n/** Process-wide singleton (mirrors `getRunEventCache` / `getApprovalRegistry`). */\nexport function getThreadRunRegistry(): ThreadRunRegistry {\n serverRegistry ??= createInProcessThreadRunRegistry()\n return serverRegistry\n}\n","/**\n * M39 (ADR-0048) — the thread signal routes over the M37 durable transport:\n *\n * - `POST /api/agents/<name>/threads/<sessionId>/message` — a follow-up. ACTIVE\n * run ⇒ FIFO-queue (dispatched as a continuation when it ends); IDLE ⇒ start a\n * run. Returns `202` (the run streams headless into the cache; observe it via\n * the thread stream). Spends LLM tokens ⇒ CSRF-gated (parity with mount-agent).\n * - `GET /api/agents/<name>/threads/<sessionId>/stream` — subscribe. ACTIVE ⇒\n * attach to the durable stream (reuse the M37 reconnect handler); IDLE ⇒ wait\n * (bounded) for the next run on the thread, then attach (subscribe-then-post).\n *\n * These DRIVE the SDK run (via `makeThreadStartRun`) + the M37 cache — no new loop.\n */\n\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { makeThreadStartRun } from './build-agent-streamer.js'\nimport {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport { handleAgentRunReconnect } from './handle-agent-run-reconnect.js'\nimport { parseAgentRequestBody } from './mount-agent.js'\nimport { getRunEventCache, type RunEventCache } from './run-event-cache.js'\nimport { postThreadFollowUp } from './thread-dispatcher.js'\nimport { getThreadRunRegistry, type ThreadRunRegistry } from './thread-run-registry.js'\n\nconst THREAD_MESSAGE_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/message$/\nconst THREAD_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/stream$/\n\n/** How long a subscribe-to-idle-thread waits for the next run before closing. */\nconst DEFAULT_IDLE_WAIT_MS = 30_000\n\nfunction matchThread(re: RegExp, urlPath: string): { name: string; sessionId: string } | null {\n const m = re.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), sessionId: decodeURIComponent(m[2]) } : null\n}\n\nexport const isThreadMessagePath = (urlPath: string) => matchThread(THREAD_MESSAGE_PATH, urlPath)\nexport const isThreadStreamPath = (urlPath: string) => matchThread(THREAD_STREAM_PATH, urlPath)\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Inputs for {@link handleThreadMessage} (bundled to stay within the arity budget). */\ninterface ThreadMessageArgs {\n readonly mod: unknown\n readonly apiKey: string\n readonly sessionId: string\n readonly request: Request\n readonly source: string\n readonly csrfMode?: CsrfMode\n}\n\n/** POST a follow-up on a thread. Returns `202` with `{ runId }` (started) or `{ queued: true }`. */\nexport async function handleThreadMessage(args: ThreadMessageArgs): Promise<Response> {\n const { mod, apiKey, sessionId, request, source, csrfMode = 'strict' } = args\n // A follow-up drives the agent (spends LLM tokens) — reject a cross-origin POST.\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → 400 below */\n }\n const input = parseAgentRequestBody(body)\n if (input === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request must contain a non-empty message.')\n }\n const result = postThreadFollowUp(\n {\n registry: getThreadRunRegistry(),\n cache: getRunEventCache(),\n startRun: makeThreadStartRun(mod, apiKey, source),\n },\n sessionId,\n input.message,\n )\n const headers: Record<string, string> = { 'content-type': 'application/json; charset=utf-8' }\n if ('runId' in result) headers[RUN_ID_HEADER] = result.runId\n return new Response(JSON.stringify(result), { status: 202, headers })\n}\n\n/** GET the thread's durable stream. Active ⇒ attach now; idle ⇒ wait (bounded) for the next run. */\nexport function handleThreadStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry = getThreadRunRegistry(),\n cache: RunEventCache = getRunEventCache(),\n idleWaitMs = DEFAULT_IDLE_WAIT_MS,\n): Response {\n const active = registry.getActive(sessionId)\n if (active !== null && cache.has(active)) {\n // Reuse the M37 reconnect handler — replay + live tail on the active run.\n return handleAgentRunReconnect(active, request, cache)\n }\n return waitThenAttachStream(sessionId, request, registry, cache, idleWaitMs)\n}\n\n/** Subscribe to an idle thread: wait (bounded) for the NEXT run to start, then attach + tail. */\nfunction waitThenAttachStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry,\n cache: RunEventCache,\n idleWaitMs: number,\n): Response {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const send = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* closed by an abort race */\n }\n }\n let detachAttach: (() => void) | undefined\n const close = (): void => {\n if (closed) return\n send(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n const offNext = registry.onNextRun(sessionId, (runId) => {\n const res = cache.attach(\n runId,\n -1,\n (frame) => {\n send(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) send(formatSseFrame(frame.seq, frame.data))\n if (res.ended) {\n close()\n return\n }\n detachAttach = res.unsubscribe\n })\n // HIGH-1 — the waiter teardown MUST run on BOTH the idle-wait timeout AND the\n // client abort, else the (one-shot) `onNextRun` waiter leaks in the registry\n // when a timed-out subscriber's session never receives another run.\n const teardownWaiter = (): void => {\n offNext()\n detachAttach?.()\n }\n const timer = setTimeout(() => {\n teardownWaiter()\n close()\n }, idleWaitMs)\n timer.unref()\n request.signal.addEventListener('abort', () => {\n teardownWaiter()\n clearTimeout(timer)\n close()\n })\n },\n })\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS } })\n}\n","/**\n * M15/M16 follow-up — shared dispatcher for the agent AUXILIARY routes that BOTH dev (vite\n * middleware) and prod (`theokit start` handler) must serve identically. Before this, these routes\n * were wired only into the dev middleware, so a built/deployed app served none of them (agent cards,\n * MCP, pending-approvals listing all 404'd in production).\n *\n * Single source of truth (DRY): one Web-Request→Response dispatcher, two callers. It handles the\n * routes that derive purely from the agent module + shared registry:\n * - **M15** `GET /.well-known/<name>/agent-card.json` → {@link handleAgentCard}\n * - **M14** `GET /api/agents/<name>/approvals` → {@link handleListApprovals}\n * - **M16** `POST /api/agents/<name>/mcp` → {@link handleMcpJsonRpc}\n *\n * Channels (M27) are NOT here: a channel webhook needs app-supplied `validators` + `onMessage`, so\n * the app wires `handleChannelWebhook` in its own route (it cannot be auto-derived from the module).\n * The HITL approve route stays in each caller (it carries caller-specific rate-limiting/CSRF plumbing).\n */\nimport type { AgentNode } from '../scan/agent-scan.js'\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { isAgentCardPath, handleAgentCard } from './agent-card-handler.js'\nimport { getApprovalRegistry } from './approval-registry.js'\nimport { handleAgentRunReconnect, isAgentRunStreamPath } from './handle-agent-run-reconnect.js'\nimport {\n handleThreadMessage,\n handleThreadStream,\n isThreadMessagePath,\n isThreadStreamPath,\n} from './handle-thread-routes.js'\nimport { isListApprovalsPath, handleListApprovals } from './list-approvals-handler.js'\nimport { extractAppResources } from './mcp-app-resources.js'\nimport { isMcpPath, handleMcpJsonRpc } from './mcp-handler.js'\nimport { getRunEventCache } from './run-event-cache.js'\n\n/** JSON error envelope (mirrors mount-agent.ts:37 — the parity source for the MCP CSRF gate). */\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Dependencies the aux dispatcher needs from its caller (dev or prod). */\ninterface AuxRouteDeps {\n /** Discovered agents (from `scanAgents`). */\n agents: readonly AgentNode[]\n /** Load an agent module from its file path (dev: vite loader; prod: dynamic import). */\n loadModule: (filePath: string) => Promise<unknown>\n /** Absolute base URL (`http(s)://host`) for the agent-card endpoint URLs. */\n baseUrl: string\n /**\n * M34 (#97) — CSRF enforcement mode for the MCP route. `POST /api/agents/<name>/mcp` drives the\n * agent (spends LLM tokens), so a cross-origin POST MUST be rejected in `'strict'` — parity with\n * the agent-run route (`mount-agent.ts:83-91`). Defaults to `'strict'` (safe-by-default); a caller\n * that already gated upstream may pass `'off'`.\n */\n csrfMode?: CsrfMode\n /**\n * M39 — lazily resolve the provider apiKey. Required only for the thread\n * follow-up route (which drives the agent); resolved on demand so non-agent\n * aux routes (card, approvals, stream) never need a provider key.\n */\n resolveApiKey?: () => string\n}\n\n/**\n * Serve an agent auxiliary route. Returns a `Response` when `urlPath` matches an aux route (card /\n * list-approvals / mcp) and the method + agent resolve; returns `null` to fall through (not an aux\n * route, wrong method, or unknown agent — the caller then owns the 404/next).\n */\nexport async function serveAgentAuxRoute(\n request: Request,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n const method = request.method.toUpperCase()\n\n // M15 — A2A agent card at `/.well-known/<name>/agent-card.json` (GET).\n const cardName = isAgentCardPath(urlPath)\n if (cardName !== null) {\n if (method !== 'GET') return null\n const agent = deps.agents.find((a) => a.name === cardName)\n if (!agent) return null\n const mod = await deps.loadModule(agent.filePath)\n return handleAgentCard(mod, agent.name, agent.agentPath, deps.baseUrl)\n }\n\n // M14 — GET /api/agents/<name>/approvals (pending HITL approvals).\n if (isListApprovalsPath(urlPath)) {\n if (method !== 'GET') return null\n return handleListApprovals(getApprovalRegistry())\n }\n\n // M37 — GET /api/agents/<name>/runs/<runId>/stream (durable reconnect / observe).\n // INTENTIONALLY open (no CSRF, no auth gate): a GET is not CSRF-vulnerable, the\n // run-start POST is already gated, and the `runId` is a 122-bit UUID (unguessable).\n // Observe-by-runId is a FEATURE (ADR-0046 D5) — a second client resumes a run a\n // first started. Do NOT add a custom-header CSRF check here: browsers send NO\n // custom headers with `EventSource`, so it would break native SSE reconnect.\n const runStream = isAgentRunStreamPath(urlPath)\n if (runStream !== null) {\n if (method !== 'GET') return null\n if (!deps.agents.some((a) => a.name === runStream.name)) return null\n return handleAgentRunReconnect(runStream.runId, request, getRunEventCache())\n }\n\n // M39 — thread signal routes (follow-up message + subscribe-by-thread). Extracted\n // to keep this dispatcher within the cognitive-complexity budget (G6).\n const threadResponse = await serveThreadRoute(request, method, urlPath, deps)\n if (threadResponse !== null) return threadResponse\n\n // M16 — POST /api/agents/<name>/mcp (JSON-RPC MCP server). Extracted to keep this dispatcher\n // within the cognitive-complexity budget (G6).\n const mcpName = isMcpPath(urlPath)\n if (mcpName !== null) {\n return serveMcpRoute(request, method, mcpName, deps)\n }\n\n return null\n}\n\n/**\n * M39 — serve the thread routes:\n * - `POST .../threads/<sessionId>/message` (follow-up) — loads the module, drives\n * the run headless via the thread dispatcher. Needs `resolveApiKey` (drives the\n * agent) → 501 when absent (rather than a silent 404).\n * - `GET .../threads/<sessionId>/stream` (subscribe) — attach to the active/next\n * run's durable stream. INTENTIONALLY open (GET, no custom headers — like the\n * M37 reconnect route).\n *\n * SECURITY (thread stream): unlike the M37 reconnect route — keyed on an\n * `mintRunId()` UUID (122-bit unguessable) — the thread stream is keyed on the\n * caller-supplied `sessionId`. The open GET is safe ONLY if the `sessionId` is\n * unguessable (e.g. a client-minted UUID). An app that uses a PREDICTABLE\n * sessionId (user id, email, sequential id) MUST add its own auth gate before\n * this endpoint, or any party who can guess the sessionId can read the thread's\n * live conversation stream. Documented in `docs/architecture/multi-surface-architecture.md`.\n *\n * Returns `null` to fall through (not a thread route, wrong method, unknown agent).\n */\nasync function serveThreadRoute(\n request: Request,\n method: string,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n const stream = isThreadStreamPath(urlPath)\n if (stream !== null) {\n if (method !== 'GET') return null\n if (!deps.agents.some((a) => a.name === stream.name)) return null\n return handleThreadStream(stream.sessionId, request)\n }\n\n const msg = isThreadMessagePath(urlPath)\n if (msg !== null) {\n if (method !== 'POST') return null\n const agent = deps.agents.find((a) => a.name === msg.name)\n if (!agent) return null\n if (deps.resolveApiKey === undefined) {\n // MEDIUM-1 — the path matched but the caller wired no provider-key resolver.\n // Fail loudly (501) instead of a silent 404 that reads as \"route not found\".\n return jsonError(\n 501,\n 'NOT_CONFIGURED',\n 'Thread follow-up requires a provider API key (resolveApiKey was not provided to serveAgentAuxRoute).',\n )\n }\n const mod = await deps.loadModule(agent.filePath)\n return handleThreadMessage({\n mod,\n apiKey: deps.resolveApiKey(),\n sessionId: msg.sessionId,\n request,\n source: `agent \"${msg.name}\"`,\n csrfMode: deps.csrfMode ?? 'strict',\n })\n }\n return null\n}\n\n/**\n * Serve the MCP route with the M34 gates: default-DENY opt-in → CSRF → dispatch. Returns `null` to\n * fall through (wrong method / unknown or non-opted-in agent), a 403 on CSRF failure, else the\n * JSON-RPC response.\n */\nasync function serveMcpRoute(\n request: Request,\n method: string,\n mcpName: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n if (method !== 'POST') return null\n const agent = deps.agents.find((a) => a.name === mcpName)\n if (!agent) return null\n\n const mod = await deps.loadModule(agent.filePath)\n\n // M34 — DEFAULT-DENY: an agent is NOT exposed on MCP unless it explicitly opts in with a named\n // `export const mcp = true` (blueprint D5 — default-EXPOSE is the footgun magnified by the\n // multi-surface thesis). Absent the opt-in, fall through to 404 (the agent is web-only). This is a\n // breaking change from the M16 auto-mount (documented in the CHANGELOG § Security).\n if (!isMcpExposed(mod)) return null\n\n // M34 (#97) — enforce CSRF BEFORE any work. The MCP route drives the agent (real LLM tokens), so a\n // cross-origin POST must be rejected — parity with the agent-run route (`mount-agent.ts:83-91`).\n const csrfMode = deps.csrfMode ?? 'strict'\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* malformed/empty JSON → handleMcpJsonRpc returns a -32600 envelope */\n }\n // M30 — pass the agent's declared `ui://` App resources (named `appResources` export) so the MCP\n // server advertises + serves them via resources/list + resources/read.\n return handleMcpJsonRpc(mod, agent.name, body, extractAppResources(mod))\n}\n\n/**\n * M34 — DEFAULT-DENY opt-in check: is this agent module exposed on the MCP surface? An agent opts in\n * with a named `export const mcp = true` (mirroring the `appResources` named-export convention).\n * Anything else (absent / falsy) → NOT exposed. Read at the emit layer (blueprint D5).\n */\nfunction isMcpExposed(mod: unknown): boolean {\n return (mod as { mcp?: unknown } | null | undefined)?.mcp === true\n}\n","/**\n * T5a.2 Phase G slice 5/N — Node adapter shim for the Web request handler.\n *\n * Bridges Node's `IncomingMessage` + `ServerResponse` shape to the\n * Web-Standards `executeWebRequest` (Phase A → G slices 1-4). Per\n * ADR-0028 R3a, the Node adapter is the ONLY place IncomingMessage ↔\n * Request conversion happens — every other layer of `server/` flows\n * through Web `Request`/`Response`.\n *\n * **Two conversions:**\n *\n * 1. `incomingMessageToWebRequest(req)` — Node → Web. Reads\n * `req.method`, `req.url`, `req.headers`, and (for POST/PUT/etc.)\n * drains the Node Readable body into a Web `ReadableStream`. The\n * request URL is resolved to absolute form using `req.headers.host`\n * (Web Request guarantees absolute URL).\n *\n * 2. `writeWebResponseToServerResponse(response, res)` — Web → Node.\n * Sets status code + status text, copies headers (including all\n * `Set-Cookie` values via `getSetCookie()`), then drains the Web\n * `ReadableStream` body into the Node ServerResponse.\n *\n * Plus the convenience composer `executeWebRequestFromNode(req, res,\n * routeModule, opts?)` that wires both ends — exactly what api-middleware\n * (and the prod CLI start path) need to migrate from the legacy\n * `executeRoute` to `executeWebRequest` without touching call sites.\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase G slice 5/N (closes the executor bridge surface).\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { executeWebRequest, type ExecuteWebRequestOptions } from '../web-handler.js'\n\nimport { incomingMessageToWebRequest } from './node-request.js'\n\n// The primitive `IncomingMessage` → Web `Request` converters live in\n// `node-request.js` (dependency-free, shared with the executor). Re-exported\n// here so existing importers of the adapter keep resolving them.\nexport { incomingMessageToWebRequest } from './node-request.js'\n\n/**\n * Write a Web `Response` into a Node `ServerResponse`. Mirrors the Node\n * `res.writeHead` + `res.end` pattern.\n *\n * Set-Cookie is the only multi-value header the Web spec exposes via\n * `getSetCookie()`. We append each entry individually so Node emits\n * separate `Set-Cookie:` lines per the HTTP spec.\n *\n * If the Response body is a `ReadableStream`, it's piped chunk-by-chunk\n * to `res`. Empty body (null) → just close.\n */\nexport async function writeWebResponseToServerResponse(\n response: Response,\n res: ServerResponse,\n): Promise<void> {\n // Status + headers FIRST (writeHead locks them).\n // EC-3: Set-Cookie needs special handling (writeHead's plain object\n // shape conflicts with multi-value headers; we set them via setHeader\n // BEFORE writeHead so the array form is preserved).\n const setCookies = response.headers.getSetCookie()\n if (setCookies.length > 0) {\n res.setHeader('Set-Cookie', setCookies)\n }\n const otherHeaders: Record<string, string> = {}\n for (const [key, value] of response.headers.entries()) {\n if (key.toLowerCase() === 'set-cookie') continue\n otherHeaders[key] = value\n }\n res.writeHead(response.status, response.statusText, otherHeaders)\n\n // Body — drain ReadableStream OR just end() for null body.\n if (response.body === null) {\n res.end()\n return\n }\n const reader = response.body.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n // Node's res.write accepts Uint8Array natively (no conversion needed).\n res.write(value)\n }\n res.end()\n } finally {\n reader.releaseLock()\n }\n}\n\n/**\n * Convenience composer — full request lifecycle Node → Web → Node.\n *\n * Use case: existing api-middleware (and the prod CLI start path)\n * receive Node `(req, res)` from `http.createServer`. To migrate to the\n * Web-Standards executor without rewriting every call site, wrap with\n * this composer:\n *\n * import * as users from './app/users/route.js'\n * await executeWebRequestFromNode(req, res, users, { csrfMode: 'strict' })\n *\n * The Web request is built, dispatched through executeWebRequest, and\n * the Response is drained back into `res`. Caller does NOT need to call\n * `res.end()` afterwards — this composer handles it.\n */\nexport async function executeWebRequestFromNode(\n req: IncomingMessage,\n res: ServerResponse,\n routeModule: Parameters<typeof executeWebRequest>[1],\n opts?: ExecuteWebRequestOptions,\n): Promise<void> {\n const webRequest = incomingMessageToWebRequest(req)\n const webResponse = await executeWebRequest(webRequest, routeModule, opts)\n await writeWebResponseToServerResponse(webResponse, res)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,eAAe;AAef,IAAM,uBAAwC;AAAA,EACnD,MAAM;AAAA,EACN,WAAW,CAAC,MAAM,KAAK,UAAU,UAAU,UAAU,CAAC,CAAC;AAAA,EACvD,aAAa,CAAC,QAAQ;AACpB,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,WAAO,UAAU,YAAY,MAAM;AAAA,EACrC;AACF;AAEO,IAAM,kBAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,WAAW,CAAC,MAAM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,KAAM;AAEV,UAAI,MAAM,KAAK;AAAA,IACjB;AACA,QAAI,IAAI;AAAA,EACV,UAAE;AACA,WAAO,YAAY;AAAA,EACrB;AACF;","names":["jsonError","jsonError"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/cost/track-agent-run.ts","../src/server/cost/usage-storage-memory.ts","../src/server/cost/track-agent-tools.ts"],"sourcesContent":["import type { AgentRunRecord } from '../../devtools/shared.js'\n\nimport type { UsageRecord, UsageStorageAdapter } from './cost-types.js'\n\nexport interface TrackAgentRunInput {\n userId: string\n model: string\n tokens: { input: number; output: number }\n costUsd: number\n /** Defaults to `new Date()`. */\n timestamp?: Date\n /** Optional execution status surfaced to devtools (default 'finished'). */\n status?: 'finished' | 'error' | 'aborted'\n}\n\nexport interface TrackAgentRunOptions {\n /** Adapter resolved from `theo.config.ts > cost.storage`. */\n storage: UsageStorageAdapter | undefined\n}\n\n// v1.1 EC-4 MUST FIX — universal dev gate (Vite OR tsup-bundled).\n// Both checks are statically replaceable by bundlers in prod build,\n// so the entire dispatcher import is tree-shaken from the prod bundle.\nconst __IS_DEV = (() => {\n try {\n return (import.meta as { env?: { DEV?: boolean } }).env?.DEV === true\n } catch {\n return process.env.NODE_ENV !== 'production'\n }\n})()\n\n/**\n * Record a single agent run's usage + cost. Companion to the client-side\n * `<CostMeter>` from `@theokit/ui`.\n *\n * EC-14: this function NEVER bubbles errors back to the caller. Adapter\n * failures (network outage, DB down, etc.) are logged via `console.warn`\n * and swallowed. The agent response MUST NOT fail because cost tracking\n * is degraded.\n *\n * No-op when `storage` is undefined (cost tracking unconfigured).\n *\n * In dev mode (Vite OR tsup-built with NODE_ENV != 'production'), fires a\n * `theokit-evolution-ci-and-dx` Phase 3 dispatcher event so the devtools\n * Agents tab can render the run. Prod tree-shakes the entire dispatcher\n * import via the `__IS_DEV` IIFE guard.\n *\n * @see docs/concepts/cost-tracking.md (when implemented in T6.3)\n */\nexport async function trackAgentRun(\n input: TrackAgentRunInput,\n opts: TrackAgentRunOptions,\n): Promise<void> {\n // Dev-only: surface run to devtools Agents tab (T3.1)\n if (__IS_DEV) {\n try {\n const mod = (await import('../../devtools/bridge/dispatcher.js')) as {\n dispatcher: { onAgentRun: (r: AgentRunRecord) => void }\n }\n mod.dispatcher.onAgentRun({\n // eslint-disable-next-line sonarjs/pseudo-random -- non-secret correlation id\n id: `run-${String(Date.now())}-${Math.random().toString(36).slice(2, 8)}`,\n timestamp: (input.timestamp ?? new Date()).getTime(),\n userId: input.userId,\n model: input.model,\n tokensInput: input.tokens.input,\n tokensOutput: input.tokens.output,\n costUsd: input.costUsd,\n status: input.status ?? 'finished',\n })\n } catch {\n // devtools dispatcher missing in some prod-like bundle — silently skip\n }\n }\n\n if (!opts.storage) return\n const record: UsageRecord = {\n userId: input.userId,\n model: input.model,\n tokens: input.tokens,\n costUsd: input.costUsd,\n timestamp: input.timestamp ?? new Date(),\n }\n try {\n await opts.storage.record(record)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n\n console.warn(\n `[theokit:cost] usage storage record failed: ${message}. ` +\n '(Response is unaffected — cost tracking degraded.)',\n )\n }\n}\n","import type { StorageAdapter } from '../storage/storage-types.js'\n\nimport type {\n ToolUsageRecord,\n UsageQuery,\n UsageRecord,\n UsageResult,\n UsageStorageAdapter,\n} from './cost-types.js'\n\n/**\n * In-memory usage storage for dev/tests. Unbounded — production\n * deployments MUST plug in a durable adapter (Postgres/Redis recipes\n * land with R0.6.7; documented in EC-114).\n *\n * Phase 5 — Production-Readiness #4: accepts both `UsageRecord` (LLM call,\n * kind='llm' or omitted) AND `ToolUsageRecord` (tool call, kind='tool').\n * `getUsage` only sums LLM records (tools have no token/cost dimension).\n *\n * EC-9 (backward compat): input without `kind` is normalized to `kind:'llm'`\n * — adapters from older versions stay working.\n *\n * Concurrency: Node's single-threaded event loop guarantees that\n * `Array.push` is atomic, so concurrent record() calls cannot lose data.\n */\nexport class InMemoryUsageStorage implements UsageStorageAdapter, StorageAdapter {\n readonly name = 'memory'\n readonly #records: (UsageRecord | ToolUsageRecord)[] = []\n\n /**\n * T2.3 — `StorageAdapter` lifecycle hook (ADR-0007 D6). In-memory storage\n * has no real cleanup to perform — this is intentionally a noop so the\n * adapter can be registered with `StorageManager.register()` and\n * participate in graceful shutdown without changing behavior.\n *\n * Does NOT clear stored records (dispose ≠ reset). For test reset use\n * a fresh instance.\n */\n dispose(): Promise<void> {\n // Intentional noop — see jsdoc above\n return Promise.resolve()\n }\n\n async record(input: UsageRecord | ToolUsageRecord): Promise<void> {\n // EC-9: normalize legacy input (no `kind` field) to kind:'llm'.\n const normalized: UsageRecord | ToolUsageRecord =\n 'kind' in input && input.kind === 'tool'\n ? { ...input }\n : ({ ...input, kind: 'llm' as const } satisfies UsageRecord)\n this.#records.push(normalized)\n return Promise.resolve()\n }\n\n async getUsage(query: UsageQuery): Promise<UsageResult> {\n const from = query.period.from.getTime()\n const to = query.period.to.getTime()\n let totalTokens = 0\n let totalCostUsd = 0\n let runs = 0\n for (const r of this.#records) {\n if (r.kind === 'tool') continue\n if (r.userId !== query.userId) continue\n const t = r.timestamp.getTime()\n if (t < from || t > to) continue\n totalTokens += r.tokens.input + r.tokens.output\n totalCostUsd += r.costUsd\n runs += 1\n }\n return Promise.resolve({ totalTokens, totalCostUsd, runs })\n }\n\n /** @internal — test helper to inspect raw record stream */\n __getRecords(): readonly (UsageRecord | ToolUsageRecord)[] {\n return this.#records\n }\n}\n","import type { ToolUsageRecord, UsageStorageAdapter } from './cost-types.js'\n\n/**\n * Phase 5 — Production-Readiness #4: tool lifecycle hooks for cost tracking.\n *\n * The SDK calls `onToolStart` → handler runs → `onToolEnd` (success) or\n * `onToolError` (throw). This factory returns the three callbacks ready to\n * attach to `Agent.create({ tools, onToolStart, onToolEnd, onToolError })`.\n *\n * Each successful tool call writes a `ToolUsageRecord{success:true}`; each\n * failure writes `ToolUsageRecord{success:false}` with `errorMessage` from\n * the thrown Error.\n *\n * Invariants:\n * - `onToolStart` records nothing yet (no duration available). Only stashes\n * a `startedAt` timestamp by `callId` in a per-factory Map.\n * - `onToolEnd` reads the stashed timestamp, computes `durationMs`, writes\n * a successful record. Removes the Map entry.\n * - `onToolError` analog with `success:false`.\n * - Hook throws are SWALLOWED to stderr — observation hooks must not crash\n * the run (per the v1.1.0 release contract).\n * - EC-8 (SHOULD TEST) — orphan starts (no matching End/Error) are pruned\n * on every onToolStart if older than 5 minutes. Bounded memory.\n * - EC-16 (DOCUMENT) — callId uniqueness is SDK contract; duplicate Start\n * for the same callId uses last-write-wins.\n */\n\nconst ORPHAN_TTL_MS = 5 * 60 * 1000\n\ninterface PendingStart {\n startedAt: number\n userId: string\n conversationId: string\n}\n\nexport interface TrackAgentToolsOptions {\n storage: UsageStorageAdapter\n /** Defaults to () => new Date() — overridable for deterministic testing. */\n now?: () => Date\n /** Identifier for the user — passed through to ToolUsageRecord.userId. */\n userId?: string\n /** Identifier for the conversation — passed through to ToolUsageRecord.conversationId. */\n conversationId?: string\n}\n\nexport interface ToolHookEvent {\n callId: string\n name: string\n // SDK shape — we only read these structurally\n [key: string]: unknown\n}\n\nexport interface TrackAgentToolsHooks {\n onToolStart: (event: ToolHookEvent) => void\n onToolEnd: (event: ToolHookEvent) => void\n onToolError: (event: ToolHookEvent) => void\n}\n\n/**\n * Create the three tool-lifecycle callbacks. Hand the returned object's\n * methods to `Agent.create({ tools, onToolStart, onToolEnd, onToolError })`.\n */\nexport function trackAgentTools(opts: TrackAgentToolsOptions): TrackAgentToolsHooks {\n const pending = new Map<string, PendingStart>()\n const now = opts.now ?? ((): Date => new Date())\n const userId = opts.userId ?? 'anonymous'\n const conversationId = opts.conversationId ?? 'unknown'\n\n function pruneOrphans(): void {\n const cutoff = now().getTime() - ORPHAN_TTL_MS\n for (const [id, p] of pending) {\n if (p.startedAt < cutoff) pending.delete(id)\n }\n }\n\n function safeRecord(record: ToolUsageRecord): void {\n Promise.resolve(opts.storage.record(record)).catch((err: unknown) => {\n const msg = err instanceof Error ? err.message : String(err)\n console.warn(`[theokit:trackAgentTools] storage.record failed: ${msg}`)\n })\n }\n\n return {\n onToolStart(event: ToolHookEvent): void {\n try {\n pruneOrphans()\n pending.set(event.callId, {\n startedAt: now().getTime(),\n userId,\n conversationId,\n })\n } catch (err) {\n console.warn(\n `[theokit:trackAgentTools] onToolStart hook crashed (swallowed): ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n },\n onToolEnd(event: ToolHookEvent): void {\n try {\n const start = pending.get(event.callId)\n const startedAt = start?.startedAt ?? now().getTime()\n const durationMs = start ? now().getTime() - startedAt : 0\n pending.delete(event.callId)\n if (!start) {\n console.warn(\n `[theokit:trackAgentTools] orphan onToolEnd for callId=${event.callId}; durationMs:0 recorded`,\n )\n }\n safeRecord({\n kind: 'tool',\n userId: start?.userId ?? userId,\n conversationId: start?.conversationId ?? conversationId,\n toolName: event.name,\n callId: event.callId,\n success: true,\n durationMs,\n timestamp: now(),\n })\n } catch (err) {\n console.warn(\n `[theokit:trackAgentTools] onToolEnd hook crashed (swallowed): ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n },\n onToolError(event: ToolHookEvent): void {\n try {\n const start = pending.get(event.callId)\n const startedAt = start?.startedAt ?? now().getTime()\n const durationMs = start ? now().getTime() - startedAt : 0\n pending.delete(event.callId)\n const error = event.error\n let errorMessage = 'unknown error'\n if (error instanceof Error) errorMessage = error.message\n else if (typeof error === 'string') errorMessage = error\n safeRecord({\n kind: 'tool',\n userId: start?.userId ?? userId,\n conversationId: start?.conversationId ?? conversationId,\n toolName: event.name,\n callId: event.callId,\n success: false,\n durationMs,\n errorMessage,\n timestamp: now(),\n })\n } catch (err) {\n console.warn(\n `[theokit:trackAgentTools] onToolError hook crashed (swallowed): ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n },\n }\n}\n\n/**\n * @internal — testing helper. Inspects the size of the pending-starts Map of\n * a factory instance. Not in the public API.\n */\nconst __internalsForTesting = {\n ORPHAN_TTL_MS,\n}\n"],"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AAY,OAAO,aAAa,IAAI,EAAE,QAAQ;AACpD,cAAM,aAAa,QAAQ,IAAI,EAAE,QAAQ,IAAI,YAAY;AACzD,gBAAQ,OAAO,MAAM,MAAM;AAC3B,cAAM,QAAQ,MAAM;AACpB,YAAI,eAAe;AACnB,YAAI,iBAAiB,MAAO,gBAAe,MAAM;AAAA,iBACxC,OAAO,UAAU,SAAU,gBAAe;AACnD,mBAAW;AAAA,UACT,MAAM;AAAA,UACN,QAAQ,OAAO,UAAU;AAAA,UACzB,gBAAgB,OAAO,kBAAkB;AAAA,UACzC,UAAU,MAAM;AAAA,UAChB,QAAQ,MAAM;AAAA,UACd,SAAS;AAAA,UACT;AAAA,UACA;AAAA,UACA,WAAW,IAAI;AAAA,QACjB,CAAC;AAAA,MACH,SAAS,KAAK;AACZ,gBAAQ;AAAA,UACN,mEACE,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CACjD;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/http/error-pages.ts","../src/server/http/static.ts"],"sourcesContent":["/**\n * T2.4 — Custom error pages loader.\n *\n * Loads optional `.theokit/client/404.html` and `500.html` from disk so adapters\n * (Node, CF, Vercel, Bun, Netlify, AWS Lambda, Deno) can pass them to the\n * shared `sendError` pipeline.\n *\n * EC-9: caps file size at 1MB. Files beyond the limit are skipped with a\n * console.warn and the default JSON error path is used.\n */\n\n/* eslint-disable security/detect-non-literal-fs-filename --\n * Loads `.theokit/client/404.html` and `500.html` from a directory `dir` that\n * is always the build output of the current project. The names are fixed\n * literals (`'404.html'` / `'500.html'`) — no HTTP input.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nexport const MAX_ERROR_HTML_BYTES = 1_048_576 // 1MB\n\nexport interface CustomErrorPages {\n custom404Html?: string\n custom500Html?: string\n}\n\nfunction loadIfSafe(dir: string, name: string): string | undefined {\n const path = resolve(dir, name)\n if (!existsSync(path)) return undefined\n try {\n const stat = statSync(path)\n if (stat.size > MAX_ERROR_HTML_BYTES) {\n console.warn(\n `[theokit] Custom error page ${name} is ${stat.size} bytes (max ${MAX_ERROR_HTML_BYTES}); skipping.`,\n )\n return undefined\n }\n return readFileSync(path, 'utf-8')\n } catch (err) {\n console.warn(`[theokit] Failed to read ${name}: ${(err as Error).message}`)\n return undefined\n }\n}\n\n/**\n * Load `.theokit/client/{404,500}.html` from the given client directory.\n * Returns object with both fields when present; missing pages remain undefined.\n */\nexport function loadCustomErrorPages(clientDir: string): CustomErrorPages {\n return {\n custom404Html: loadIfSafe(clientDir, '404.html'),\n custom500Html: loadIfSafe(clientDir, '500.html'),\n }\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Static-file server. The URL path IS user-controlled, BUT before any fs\n * call we resolve to absolute and reject with 403 if the resolved path\n * escapes `clientDir` (see EC-1 guard at line below). The guard is\n * authoritative; the rule cannot see it.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { resolve, extname } from 'node:path'\n\nconst MIME_TYPES: Record<string, string> = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.txt': 'text/plain',\n '.map': 'application/json',\n}\n\nexport function serveStaticFile(\n req: IncomingMessage,\n res: ServerResponse,\n clientDir: string,\n): boolean {\n const urlPath = (req.url ?? '/').split('?')[0]\n\n // Path traversal prevention (EC-1)\n const filePath = resolve(clientDir, '.' + urlPath)\n if (!filePath.startsWith(clientDir)) {\n res.writeHead(403)\n res.end('Forbidden')\n return true\n }\n\n if (!existsSync(filePath)) return false\n\n const stat = statSync(filePath)\n if (!stat.isFile()) return false\n\n const ext = extname(filePath)\n const contentType = MIME_TYPES[ext] ?? 'application/octet-stream'\n const content = readFileSync(filePath)\n\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': content.length,\n })\n res.end(content)\n return true\n}\n"],"mappings":";AAgBA,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,eAAe;AAEjB,IAAM,uBAAuB;AAOpC,SAAS,WAAW,KAAa,MAAkC;AACjE,QAAM,OAAO,QAAQ,KAAK,IAAI;AAC9B,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO;AAC9B,MAAI;AACF,UAAM,OAAO,SAAS,IAAI;AAC1B,QAAI,KAAK,OAAO,sBAAsB;AACpC,cAAQ;AAAA,QACN,+BAA+B,IAAI,OAAO,KAAK,IAAI,eAAe,oBAAoB;AAAA,MACxF;AACA,aAAO;AAAA,IACT;AACA,WAAO,aAAa,MAAM,OAAO;AAAA,EACnC,SAAS,KAAK;AACZ,YAAQ,KAAK,4BAA4B,IAAI,KAAM,IAAc,OAAO,EAAE;AAC1E,WAAO;AAAA,EACT;AACF;AAMO,SAAS,qBAAqB,WAAqC;AACxE,SAAO;AAAA,IACL,eAAe,WAAW,WAAW,UAAU;AAAA,IAC/C,eAAe,WAAW,WAAW,UAAU;AAAA,EACjD;AACF;;;AC/CA,SAAS,cAAAA,aAAY,gBAAAC,eAAc,YAAAC,iBAAgB;AAEnD,SAAS,WAAAC,UAAS,eAAe;AAEjC,IAAM,aAAqC;AAAA,EACzC,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AACV;AAEO,SAAS,gBACd,KACA,KACA,WACS;AACT,QAAM,WAAW,IAAI,OAAO,KAAK,MAAM,GAAG,EAAE,CAAC;AAG7C,QAAM,WAAWA,SAAQ,WAAW,MAAM,OAAO;AACjD,MAAI,CAAC,SAAS,WAAW,SAAS,GAAG;AACnC,QAAI,UAAU,GAAG;AACjB,QAAI,IAAI,WAAW;AACnB,WAAO;AAAA,EACT;AAEA,MAAI,CAACH,YAAW,QAAQ,EAAG,QAAO;AAElC,QAAM,OAAOE,UAAS,QAAQ;AAC9B,MAAI,CAAC,KAAK,OAAO,EAAG,QAAO;AAE3B,QAAM,MAAM,QAAQ,QAAQ;AAC5B,QAAM,cAAc,WAAW,GAAG,KAAK;AACvC,QAAM,UAAUD,cAAa,QAAQ;AAErC,MAAI,UAAU,KAAK;AAAA,IACjB,gBAAgB;AAAA,IAChB,kBAAkB,QAAQ;AAAA,EAC5B,CAAC;AACD,MAAI,IAAI,OAAO;AACf,SAAO;AACT;","names":["existsSync","readFileSync","statSync","resolve"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/jobs/define-job.ts","../src/server/jobs/job-backend.ts","../src/server/jobs/job-backend-memory.ts","../src/server/jobs/job-backend-postgres.ts","../src/server/jobs/job-runner.ts","../src/server/jobs/job-manifest.ts","../src/server/jobs/job-scan.ts"],"sourcesContent":["import type { JobDefinition, JobOptions } from './job-types.js'\n\nconst NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/\n\nfunction validateName(name: string): void {\n if (typeof name !== 'string' || !NAME_RE.test(name)) {\n throw new Error(\n `defineJob: invalid name \"${name}\". ` +\n 'Must be 1-64 chars, lowercase alphanumeric + hyphen, starting with [a-z0-9].',\n )\n }\n}\n\n/**\n * Declare a background job. Pure identity helper — no registration side\n * effect; the build-time scanner (T2.3) discovers definitions by walking\n * `server/jobs/` and emits `.theokit/jobs.json`.\n *\n * Per ADR-0003, handler returns `void` (or `Promise<void>`); no workflow\n * API. To run another job after this one, call `ctx.queue.enqueue` from\n * the handler.\n *\n * @example\n * ```ts\n * // server/jobs/process-document.ts\n * import { defineJob } from 'theokit/server'\n * import { z } from 'zod'\n *\n * export default defineJob('process-document', {\n * input: z.object({ documentId: z.string() }),\n * maxAttempts: 3,\n * async handler({ input, traceId }) {\n * // process input.documentId\n * },\n * })\n * ```\n */\nexport function defineJob<TInput = unknown>(\n name: string,\n options: JobOptions<TInput>,\n): JobDefinition<TInput> {\n validateName(name)\n return {\n name,\n maxAttempts: options.maxAttempts ?? 1,\n hasInputSchema: options.input !== undefined,\n handler: options.handler,\n inputSchema: options.input,\n }\n}\n","/**\n * Neutral `JobBackend` interface per ADR-0002.\n *\n * Implementations ship in core:\n * - `InMemoryJobBackend` (T2.2) — dev + tests; no external deps\n * - `PostgresJobBackend` (T3.1) — production; requires `pg` peer dep\n *\n * Community packages (`@theokit/jobs-redis`, `@theokit/jobs-sqs`, etc.)\n * implement this same interface to plug in alternate substrates without\n * modifying TheoKit core.\n */\n\nexport interface JobEnqueueInput {\n /** The job name (matches a `defineJob` declaration). */\n name: string\n /** Validated input (already passed through Zod or equivalent at the queue-client layer). */\n input: unknown\n /** Optional idempotency key for at-most-once dispatch within TTL. */\n idempotencyKey?: string\n /** Optional delay before the job becomes available for dispatch. */\n delaySeconds?: number\n /** W3C Trace Context propagation per ADR/R0.5.9. */\n traceparent?: string\n /** Maximum dispatch attempts (read from JobDefinition by the queue client). */\n maxAttempts?: number\n}\n\nexport interface JobLease {\n readonly jobId: string\n readonly name: string\n readonly input: unknown\n readonly attempts: number\n readonly maxAttempts: number\n readonly traceparent?: string\n readonly lockExpiresAt: Date\n}\n\nexport interface JobBackend {\n /** Human-readable name for logging (e.g., \"memory\", \"postgres\"). */\n readonly name: string\n\n /** Persist a job for later dispatch. Returns the generated jobId. */\n enqueue(input: JobEnqueueInput): Promise<{ jobId: string }>\n\n /** Worker loop polls for the next available leases. */\n dequeue(opts: { batchSize?: number; lockSeconds?: number }): Promise<JobLease[]>\n\n /** Mark a job complete (success). */\n ack(jobId: string): Promise<void>\n\n /** Mark a job failed; backend decides retry vs DLQ via attempts. */\n nack(jobId: string, opts: { error: string; nonRetryable?: boolean }): Promise<void>\n\n /** Optional: return existing jobId if `key` was enqueued within `ttlSeconds`. */\n idempotency?(key: string, ttlSeconds: number): Promise<{ jobId: string } | null>\n}\n\n/**\n * Thrown from a job handler to opt out of retry policy. The backend MUST\n * nack with `nonRetryable: true` and permanently remove the job.\n */\nexport class NonRetryableError extends Error {\n readonly code = 'NON_RETRYABLE'\n constructor(message: string) {\n super(message)\n this.name = 'NonRetryableError'\n }\n}\n","// T5a.1a — Web Standards migration (leaf-first slice). Web Crypto's\n// `crypto.randomUUID()` is available on globalThis in every supported\n// runtime per ADR-0028 (Node 22+, CF Workers, Bun, Deno, browsers).\n// No node:crypto import needed.\n\nimport type { JobBackend, JobEnqueueInput, JobLease } from './job-backend.js'\n\n/**\n * In-memory job backend for dev + tests + single-instance prototypes.\n *\n * Zero external dependencies. Storage is two Maps:\n * - `pending: Map<jobId, PendingEntry>` — all enqueued jobs (locked or not)\n * - `idempotencyMap: Map<key, { jobId; expiresAt }>` — dedup window\n *\n * Per ADR-0002: this is one of two first-party backends shipped in core.\n * Production deploys plug in PostgresJobBackend (T3.1).\n *\n * EC-104 (jobs-crons-webhooks-cost-tracking-plan): registers a\n * `process.on('beforeExit')` handler that clears pending dispatch timers\n * and logs a warning with the dropped count. Failure mode is visible,\n * not silent. `destroy()` removes the listener for test isolation.\n */\n\nexport interface InMemoryJobBackendOptions {\n /** Maximum pending entries before oldest is dropped + warning logged. */\n maxPending?: number\n}\n\ninterface PendingEntry {\n jobId: string\n name: string\n input: unknown\n attempts: number\n maxAttempts: number\n traceparent?: string\n availableAt: number\n lockExpiresAt: number | null\n dispatchTimer: NodeJS.Timeout | null\n}\n\ninterface IdempotencyEntry {\n jobId: string\n expiresAt: number\n}\n\nconst DEFAULT_MAX_PENDING = 10_000\n\nexport class InMemoryJobBackend implements JobBackend {\n readonly name = 'memory'\n readonly #pending = new Map<string, PendingEntry>()\n readonly #idempotency = new Map<string, IdempotencyEntry>()\n readonly #maxPending: number\n #beforeExitHandler: (() => void) | null = null\n #destroyed = false\n\n constructor(opts: InMemoryJobBackendOptions = {}) {\n this.#maxPending = opts.maxPending ?? DEFAULT_MAX_PENDING\n // EC-104 — register graceful shutdown handler. We keep a reference\n // so `destroy()` can remove it (test isolation; avoid leaking\n // listeners across vitest test files).\n this.#beforeExitHandler = (): void => {\n this.#cleanupOnShutdown()\n }\n process.on('beforeExit', this.#beforeExitHandler)\n }\n\n async enqueue(input: JobEnqueueInput): Promise<{ jobId: string }> {\n // Overflow eviction (visible failure, not silent leak)\n if (this.#pending.size >= this.#maxPending) {\n const oldestKey = this.#pending.keys().next().value\n if (oldestKey) {\n const oldest = this.#pending.get(oldestKey)\n if (oldest?.dispatchTimer) clearTimeout(oldest.dispatchTimer)\n this.#pending.delete(oldestKey)\n }\n\n console.warn(\n `[theokit:jobs:memory] pending overflow at ${this.#maxPending} — dropped oldest. ` +\n 'Switch to PostgresJobBackend for production.',\n )\n }\n\n // Idempotency dedup\n if (input.idempotencyKey) {\n const existing = this.#idempotency.get(input.idempotencyKey)\n const now = Date.now()\n if (existing && existing.expiresAt > now) {\n return { jobId: existing.jobId }\n }\n }\n\n const jobId = globalThis.crypto.randomUUID()\n const now = Date.now()\n const availableAt = now + (input.delaySeconds ?? 0) * 1000\n const entry: PendingEntry = {\n jobId,\n name: input.name,\n input: input.input,\n attempts: 0,\n maxAttempts: input.maxAttempts ?? 1,\n traceparent: input.traceparent,\n availableAt,\n lockExpiresAt: null,\n dispatchTimer: null,\n }\n this.#pending.set(jobId, entry)\n\n if (input.idempotencyKey) {\n // Default TTL window matches typical idempotency expectations;\n // explicit idempotency(key, ttl) check overrides per caller.\n this.#idempotency.set(input.idempotencyKey, {\n jobId,\n expiresAt: now + 60_000,\n })\n }\n\n return Promise.resolve({ jobId })\n }\n\n async dequeue(opts: { batchSize?: number; lockSeconds?: number }): Promise<JobLease[]> {\n const batchSize = opts.batchSize ?? 1\n const lockSeconds = opts.lockSeconds ?? 30\n const now = Date.now()\n\n const leases: JobLease[] = []\n for (const entry of this.#pending.values()) {\n if (leases.length >= batchSize) break\n // Skip if locked + lock still valid\n if (entry.lockExpiresAt !== null && entry.lockExpiresAt > now) continue\n // Skip if not yet available (delay)\n if (entry.availableAt > now) continue\n\n entry.lockExpiresAt = now + lockSeconds * 1000\n entry.attempts += 1\n leases.push({\n jobId: entry.jobId,\n name: entry.name,\n input: entry.input,\n attempts: entry.attempts,\n maxAttempts: entry.maxAttempts,\n traceparent: entry.traceparent,\n lockExpiresAt: new Date(entry.lockExpiresAt),\n })\n }\n return Promise.resolve(leases)\n }\n\n async ack(jobId: string): Promise<void> {\n const entry = this.#pending.get(jobId)\n if (entry?.dispatchTimer) clearTimeout(entry.dispatchTimer)\n this.#pending.delete(jobId)\n return Promise.resolve()\n }\n\n async nack(jobId: string, opts: { error: string; nonRetryable?: boolean }): Promise<void> {\n const entry = this.#pending.get(jobId)\n if (!entry) return Promise.resolve()\n if (opts.nonRetryable || entry.attempts >= entry.maxAttempts) {\n if (entry.dispatchTimer) clearTimeout(entry.dispatchTimer)\n this.#pending.delete(jobId)\n } else {\n // Release lock — becomes available again\n entry.lockExpiresAt = null\n }\n return Promise.resolve()\n }\n\n idempotency(key: string, ttlSeconds: number): Promise<{ jobId: string } | null> {\n const now = Date.now()\n const existing = this.#idempotency.get(key)\n if (!existing || existing.expiresAt <= now) {\n return Promise.resolve(null)\n }\n // Renew if caller's ttl differs\n existing.expiresAt = Math.max(existing.expiresAt, now + ttlSeconds * 1000)\n return Promise.resolve({ jobId: existing.jobId })\n }\n\n /**\n * Remove the beforeExit listener and clear all pending timers.\n * Idempotent — safe to call multiple times. Use in test teardown to\n * avoid leaking listeners across vitest test files.\n */\n destroy(): void {\n if (this.#destroyed) return\n this.#destroyed = true\n if (this.#beforeExitHandler) {\n process.off('beforeExit', this.#beforeExitHandler)\n this.#beforeExitHandler = null\n }\n for (const entry of this.#pending.values()) {\n if (entry.dispatchTimer) clearTimeout(entry.dispatchTimer)\n }\n }\n\n /** EC-104 test hook — invokes the shutdown handler synchronously. */\n triggerBeforeExitForTest(): void {\n this.#cleanupOnShutdown()\n }\n\n #cleanupOnShutdown(): void {\n const droppedCount = this.#pending.size\n for (const entry of this.#pending.values()) {\n if (entry.dispatchTimer) clearTimeout(entry.dispatchTimer)\n }\n if (droppedCount > 0) {\n console.warn(\n `[theokit:jobs:memory] ${droppedCount} jobs dropped on shutdown — ` +\n 'use PostgresJobBackend for durability across restarts.',\n )\n }\n }\n}\n","import type { PostgresFactory, StorageManager } from '../storage/storage-manager.js'\nimport type { PoolLike } from '../storage/storage-types.js'\n\nimport type { JobBackend, JobEnqueueInput, JobLease } from './job-backend.js'\n\n/**\n * Postgres-backed `JobBackend` per ADR-0002 (T3.1).\n *\n * Uses the Graphile Worker pattern:\n * - Single `theokit_jobs` table.\n * - Dequeue via `SELECT ... FOR UPDATE SKIP LOCKED` (concurrent workers\n * never race for the same job).\n * - Idempotency via UNIQUE INDEX on (name, idempotency_key).\n *\n * `pg` is an OPTIONAL peer dependency — the caller provides their own\n * `pg.Pool` (or compatible). This avoids forcing every TheoKit user to\n * install Postgres tooling for in-memory dev work.\n *\n * Pool size recommendation (EC-108): set `connectionTimeoutMillis` to\n * a finite value (e.g., 5000) so a saturated pool errors instead of\n * deadlocking. Suggested pool size: `min(workerConcurrency * 1.5, 20)`.\n *\n * @see https://github.com/graphile/worker (Postgres SKIP LOCKED reference)\n * @see docs/adr/0002-job-backend-interface-neutral-contract.md\n */\n\n/**\n * `PoolLike` moved to `../storage/storage-types.ts` (T0.2 / ADR-0007 D7) to\n * deduplicate the shape across multiple adapters. Re-exported here so existing\n * `import { PoolLike } from 'theokit/server'` (which routes through the jobs\n * barrel today) continues to compile unchanged.\n */\nexport type { PoolLike } from '../storage/storage-types.js'\n\nexport interface PostgresJobBackendOptions {\n pool: PoolLike\n /** Table name override (default `theokit_jobs`). */\n tableName?: string\n}\n\nconst DEFAULT_TABLE = 'theokit_jobs'\n\nexport class PostgresJobBackend implements JobBackend {\n readonly name = 'postgres'\n readonly #pool: PoolLike\n readonly #table: string\n\n constructor(opts: PostgresJobBackendOptions) {\n // Runtime guard for users who pass `pool: undefined` despite the type;\n // helps surface \"you forgot to install pg\" early with an actionable\n // error rather than a cryptic TypeError later.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!opts.pool) {\n throw new Error(\n 'PostgresJobBackend requires a `pool` option (pg.Pool or compatible). ' +\n 'Install pg via `pnpm add pg` and pass a configured Pool instance.',\n )\n }\n this.#pool = opts.pool\n this.#table = opts.tableName ?? DEFAULT_TABLE\n }\n\n /**\n * T2.1 — Construct a `PostgresJobBackend` using a pool managed by the\n * shared `StorageManager`. The manager caches the pool per `dbName`, so\n * repeated calls (in the same process) re-use the same connection pool.\n *\n * Equivalent to:\n * ```ts\n * const pool = manager.usePostgres(dbName, factory)\n * new PostgresJobBackend({ pool, ...options })\n * ```\n *\n * Errors thrown by the manager (unknown dbName, dangling server reference,\n * manager already disposed) propagate to the caller with actionable text.\n *\n * @see ADR-0007\n */\n static fromStorageManager(\n manager: StorageManager,\n dbName: string,\n factory: PostgresFactory,\n options?: Omit<PostgresJobBackendOptions, 'pool'>,\n ): PostgresJobBackend {\n const pool = manager.usePostgres(dbName, factory)\n return new PostgresJobBackend({ pool, ...options })\n }\n\n /**\n * Create or upgrade the schema. Idempotent (uses IF NOT EXISTS).\n * Call once at process start; safe to re-run on every deploy.\n */\n async migrate(): Promise<void> {\n const t = this.#table\n await this.#pool.query(`\n CREATE TABLE IF NOT EXISTS ${t} (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n input JSONB NOT NULL,\n attempts INT NOT NULL DEFAULT 0,\n max_attempts INT NOT NULL DEFAULT 1,\n available_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n locked_until TIMESTAMPTZ,\n traceparent TEXT,\n idempotency_key TEXT,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n )\n `)\n await this.#pool.query(`\n CREATE UNIQUE INDEX IF NOT EXISTS ${t}_idempotency_key_idx\n ON ${t} (name, idempotency_key)\n WHERE idempotency_key IS NOT NULL\n `)\n await this.#pool.query(`\n CREATE INDEX IF NOT EXISTS ${t}_available_at_idx\n ON ${t} (available_at)\n WHERE locked_until IS NULL\n `)\n }\n\n async enqueue(input: JobEnqueueInput): Promise<{ jobId: string }> {\n const id = randomId()\n const delaySeconds = input.delaySeconds ?? 0\n const t = this.#table\n\n // Idempotency: explicit SELECT-then-INSERT. The UNIQUE INDEX is the\n // safety net under race conditions (we surface the conflict by\n // re-selecting on insert-error). This 2-step path is pg-mem compatible\n // AND works on real Postgres.\n if (input.idempotencyKey) {\n const existing = await this.#pool.query<{ id: string }>(\n `SELECT id FROM ${t} WHERE name = $1 AND idempotency_key = $2 LIMIT 1`,\n [input.name, input.idempotencyKey],\n )\n if (existing.rows.length > 0) {\n return { jobId: existing.rows[0].id }\n }\n }\n\n await this.#pool.query(\n `INSERT INTO ${t} (id, name, input, max_attempts, available_at, traceparent, idempotency_key)\n VALUES ($1, $2, $3::jsonb, $4, NOW() + ($5 || ' seconds')::interval, $6, $7)`,\n [\n id,\n input.name,\n JSON.stringify(input.input),\n input.maxAttempts ?? 1,\n delaySeconds.toString(),\n input.traceparent ?? null,\n input.idempotencyKey ?? null,\n ],\n )\n return { jobId: id }\n }\n\n async dequeue(opts: { batchSize?: number; lockSeconds?: number }): Promise<JobLease[]> {\n const t = this.#table\n const batchSize = opts.batchSize ?? 1\n const lockSeconds = opts.lockSeconds ?? 30\n\n // Two-step pattern (pg-mem compatible AND real-Postgres compatible):\n // 1. SELECT FOR UPDATE SKIP LOCKED to claim candidate IDs.\n // 2. UPDATE in-place to mark lock_until + bump attempts.\n // On real Postgres, the FOR UPDATE SKIP LOCKED prevents concurrent\n // workers from seeing the same rows. On pg-mem the lock is silently\n // ignored, but pg-mem serializes all queries through one in-memory\n // db so the test still verifies single-claim semantics.\n const candidates = await this.#pool.query<{ id: string }>(\n `SELECT id FROM ${t}\n WHERE (locked_until IS NULL OR locked_until < NOW())\n AND available_at <= NOW()\n ORDER BY available_at ASC\n LIMIT $1\n FOR UPDATE SKIP LOCKED`,\n [batchSize],\n )\n\n if (candidates.rows.length === 0) return []\n\n const ids = candidates.rows.map((r) => r.id)\n // Build a parameterized IN clause: ($2, $3, ...). pg-mem's UPDATE\n // does not support `ANY($1::text[])`, so we materialize the list.\n // For batch sizes we expect (typically ≤100), this is fine.\n const placeholders = ids.map((_, i) => `$${i + 2}`).join(', ')\n\n const r = await this.#pool.query<{\n id: string\n name: string\n input: unknown\n attempts: number\n max_attempts: number\n traceparent: string | null\n locked_until: Date | string\n }>(\n `UPDATE ${t}\n SET locked_until = NOW() + ($1 || ' seconds')::interval,\n attempts = attempts + 1\n WHERE id IN (${placeholders})\n RETURNING id, name, input, attempts, max_attempts, traceparent, locked_until`,\n [lockSeconds.toString(), ...ids],\n )\n\n return r.rows.map((row) => ({\n jobId: row.id,\n name: row.name,\n input: row.input,\n attempts: row.attempts,\n maxAttempts: row.max_attempts,\n traceparent: row.traceparent ?? undefined,\n lockExpiresAt:\n row.locked_until instanceof Date ? row.locked_until : new Date(row.locked_until),\n }))\n }\n\n async ack(jobId: string): Promise<void> {\n await this.#pool.query(`DELETE FROM ${this.#table} WHERE id = $1`, [jobId])\n }\n\n async nack(jobId: string, opts: { error: string; nonRetryable?: boolean }): Promise<void> {\n const t = this.#table\n if (opts.nonRetryable) {\n await this.#pool.query(`DELETE FROM ${t} WHERE id = $1`, [jobId])\n return\n }\n // Check attempts >= maxAttempts → permanent removal.\n const r = await this.#pool.query<{\n attempts: number\n max_attempts: number\n }>(`SELECT attempts, max_attempts FROM ${t} WHERE id = $1`, [jobId])\n if (r.rows.length === 0) return\n const { attempts, max_attempts } = r.rows[0]\n if (attempts >= max_attempts) {\n await this.#pool.query(`DELETE FROM ${t} WHERE id = $1`, [jobId])\n } else {\n // Release lock — next dequeue picks it up again.\n await this.#pool.query(`UPDATE ${t} SET locked_until = NULL WHERE id = $1`, [jobId])\n }\n }\n\n async idempotency(key: string, _ttlSeconds: number): Promise<{ jobId: string } | null> {\n // The UNIQUE INDEX is the source of truth. Look for any non-deleted\n // row with this idempotency_key.\n const r = await this.#pool.query<{ id: string }>(\n `SELECT id FROM ${this.#table} WHERE idempotency_key = $1 LIMIT 1`,\n [key],\n )\n return r.rows.length > 0 ? { jobId: r.rows[0].id } : null\n }\n}\n\nfunction randomId(): string {\n // Use crypto.randomUUID if available; this is process-local, not DB-generated.\n // The DB UNIQUE constraint is on (name, idempotency_key), not on id, so\n // collisions across processes are functionally impossible.\n return globalThis.crypto.randomUUID()\n}\n","import {\n extractTraceContext,\n generateNewTraceContext,\n} from '../observability/trace-context-propagation.js'\n\nimport { type JobBackend, type JobLease, NonRetryableError } from './job-backend.js'\nimport type { JobContext, JobDefinition } from './job-types.js'\n\n/**\n * Job runner — pulls leases from a backend and invokes the matching\n * handler. Each invocation wires up `JobContext` with:\n * - `traceId` extracted from the lease's `traceparent` header (W3C\n * Trace Context per R0.5.9), OR a fresh generated trace_id when\n * the upstream had no traceparent OR it was malformed.\n * - `attempt` from the lease.\n * - `signal` that aborts when the lease times out.\n *\n * `tick()` runs one dequeue+dispatch cycle and returns when all leases\n * have been ack'd or nack'd. Production deploys call `tick()` in a loop\n * with backoff (the loop is outside this module's scope).\n *\n * EC-6 (trace continuity edge): when a lease has no traceparent OR a\n * malformed one, the handler still gets a valid traceId (generated) —\n * never null/undefined. The job MAY itself enqueue child jobs that\n * continue the new trace_id.\n */\n\nexport interface JobRunner {\n /** Run one dequeue+dispatch cycle. */\n tick(opts?: { batchSize?: number; lockSeconds?: number }): Promise<number>\n}\n\nexport function createJobRunner(\n backend: JobBackend,\n definitions: readonly JobDefinition[],\n): JobRunner {\n const byName = new Map<string, JobDefinition>()\n for (const def of definitions) {\n byName.set(def.name, def)\n }\n\n const runOne = async (lease: JobLease): Promise<void> => {\n const def = byName.get(lease.name)\n if (!def) {\n // Job name not registered in this runner's definition set. Nack\n // permanently — the lease can't be processed by this runner.\n await backend.nack(lease.jobId, {\n error: `No job definition for \"${lease.name}\"`,\n nonRetryable: true,\n })\n return\n }\n\n // Resolve trace ID from lease's traceparent, or fall back to fresh.\n let traceId: string\n if (lease.traceparent) {\n const headers = new Headers({ traceparent: lease.traceparent })\n const ctx = extractTraceContext(headers)\n traceId = ctx?.trace_id ?? generateNewTraceContext().trace_id\n } else {\n traceId = generateNewTraceContext().trace_id\n }\n\n // Optional Zod validation on input.\n let parsedInput: unknown = lease.input\n if (def.inputSchema) {\n try {\n parsedInput = def.inputSchema.parse(lease.input)\n } catch (err) {\n await backend.nack(lease.jobId, {\n error: `Input validation failed: ${err instanceof Error ? err.message : String(err)}`,\n nonRetryable: true,\n })\n return\n }\n }\n\n const abortController = new AbortController()\n // Auto-abort when lease expires\n const lockMs = lease.lockExpiresAt.getTime() - Date.now()\n const lockTimer = setTimeout(\n () => {\n abortController.abort()\n },\n Math.max(0, lockMs),\n )\n\n const jobCtx: JobContext = {\n traceId,\n input: parsedInput,\n signal: abortController.signal,\n attempt: lease.attempts,\n }\n\n try {\n await def.handler(jobCtx)\n await backend.ack(lease.jobId)\n } catch (err) {\n const isNonRetryable = err instanceof NonRetryableError\n await backend.nack(lease.jobId, {\n error: err instanceof Error ? err.message : String(err),\n nonRetryable: isNonRetryable,\n })\n } finally {\n clearTimeout(lockTimer)\n }\n }\n\n return {\n async tick(opts) {\n const leases = await backend.dequeue({\n batchSize: opts?.batchSize ?? 10,\n lockSeconds: opts?.lockSeconds ?? 30,\n })\n // Process leases sequentially — caller controls concurrency via\n // batchSize and tick frequency.\n for (const lease of leases) {\n await runOne(lease)\n }\n return leases.length\n },\n }\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { JobNode } from './job-scan.js'\n\nexport const JOB_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface JobManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport interface JobManifest {\n readonly schemaVersion: typeof JOB_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly jobs: readonly JobManifestEntry[]\n}\n\nexport function buildJobManifest(nodes: readonly JobNode[], projectRoot?: string): JobManifest {\n const jobs: JobManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n maxAttempts: n.maxAttempts,\n hasInputSchema: n.hasInputSchema,\n }))\n return {\n schemaVersion: JOB_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n jobs,\n }\n}\n\nexport function writeJobManifest(\n path: string,\n input: readonly JobNode[] | JobManifest,\n projectRoot?: string,\n): void {\n const manifest: JobManifest = isManifest(input) ? input : buildJobManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is JobManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'jobs' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport { importUserModule } from '../../config/import-user-module.js'\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { JobDefinition } from './job-types.js'\n\nexport interface JobNode {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport class DuplicateJobNameError extends Error {\n readonly code = 'DUPLICATE_JOB_NAME'\n constructor(\n public readonly jobName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate job name \"${jobName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Job names must be unique across server/jobs/.',\n )\n this.name = 'DuplicateJobNameError'\n }\n}\n\nconst JOB_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface JobModule {\n default?: unknown\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.handler === 'function' &&\n typeof def.maxAttempts === 'number' &&\n typeof def.hasInputSchema === 'boolean'\n )\n}\n\nexport async function scanJobs(jobsDir: string): Promise<JobNode[]> {\n if (!existsSync(jobsDir)) return []\n\n const filePaths: string[] = []\n walkSourceFiles(jobsDir, { extensions: JOB_EXTENSIONS }, (p) => {\n const base = basename(p)\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n\n const nodes: JobNode[] = []\n for (const filePath of filePaths) {\n let mod: JobModule\n try {\n mod = await importUserModule(filePath)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import job file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isJobDefinition(exported)) {\n throw new Error(\n `Job file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineJob(name, { handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n maxAttempts: exported.maxAttempts,\n hasInputSchema: exported.hasInputSchema,\n })\n }\n\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateJobNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => a.name.localeCompare(b.name))\n}\n"],"mappings":";;;;;;;;;;;;;;;AAEA,IAAM,UAAU;AAEhB,SAAS,aAAa,MAAoB;AACxC,MAAI,OAAO,SAAS,YAAY,CAAC,QAAQ,KAAK,IAAI,GAAG;AACnD,UAAM,IAA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