tenjin-cli 0.1.0-alpha.33 → 0.1.0-alpha.35

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 (495) hide show
  1. package/NOTICE.md +110 -0
  2. package/README.md +87 -81
  3. package/dist/{_esm-BIN7VY2L.js → _esm-2KST7HQ7.js} +7 -7
  4. package/dist/alive-5TV22PNF.js +51 -0
  5. package/dist/auth-XI7BJFLW.js +47 -0
  6. package/dist/{auto-update-Y24UL56V.js → auto-update-7L24KDWA.js} +4 -5
  7. package/dist/balance-DFHC6XEU.js +71 -0
  8. package/dist/{ccip-DHDFKTQV.js → ccip-HOW3DZYF.js} +4 -4
  9. package/dist/chunk-24XKUN2S.js +202 -0
  10. package/dist/chunk-24XKUN2S.js.map +1 -0
  11. package/dist/chunk-2L7TDGLV.js +56 -0
  12. package/dist/chunk-2L7TDGLV.js.map +1 -0
  13. package/dist/{chunk-C2Q76BVM.js → chunk-2U7H35IP.js} +29 -7
  14. package/dist/chunk-2U7H35IP.js.map +1 -0
  15. package/dist/chunk-2W4DQQUU.js +176 -0
  16. package/dist/chunk-2W4DQQUU.js.map +1 -0
  17. package/dist/{chunk-LRW6S53P.js → chunk-34SAECKZ.js} +35 -11
  18. package/dist/chunk-34SAECKZ.js.map +1 -0
  19. package/dist/{chunk-2I4QTOLB.js → chunk-3MZ7DYRO.js} +1 -1
  20. package/dist/chunk-3MZ7DYRO.js.map +1 -0
  21. package/dist/{chunk-RVPYTUP4.js → chunk-3Y2EHT4F.js} +13 -9
  22. package/dist/chunk-3Y2EHT4F.js.map +1 -0
  23. package/dist/chunk-3Y6BHIN6.js +169 -0
  24. package/dist/chunk-3Y6BHIN6.js.map +1 -0
  25. package/dist/{chunk-4K7TQHNP.js → chunk-3YPL6T3P.js} +17 -33
  26. package/dist/chunk-3YPL6T3P.js.map +1 -0
  27. package/dist/{chunk-E7SW44LM.js → chunk-44MVIRZH.js} +121 -6
  28. package/dist/chunk-44MVIRZH.js.map +1 -0
  29. package/dist/chunk-45MMSBHA.js +321 -0
  30. package/dist/chunk-45MMSBHA.js.map +1 -0
  31. package/dist/{chunk-3FMZGI7I.js → chunk-4CE6TMI5.js} +1 -1
  32. package/dist/chunk-4CE6TMI5.js.map +1 -0
  33. package/dist/{chunk-QXP3Z3JN.js → chunk-4MBCJFY4.js} +35 -3
  34. package/dist/chunk-4MBCJFY4.js.map +1 -0
  35. package/dist/chunk-4TPL54KW.js +227 -0
  36. package/dist/chunk-4TPL54KW.js.map +1 -0
  37. package/dist/chunk-54ELBTKE.js +1615 -0
  38. package/dist/chunk-54ELBTKE.js.map +1 -0
  39. package/dist/{chunk-NDGZDTSJ.js → chunk-5F4OB5B3.js} +115 -57
  40. package/dist/chunk-5F4OB5B3.js.map +1 -0
  41. package/dist/chunk-5HN4KVQU.js +3348 -0
  42. package/dist/chunk-5HN4KVQU.js.map +1 -0
  43. package/dist/{chunk-ZDZERB6L.js → chunk-5J4E5GYI.js} +572 -407
  44. package/dist/chunk-5J4E5GYI.js.map +1 -0
  45. package/dist/{chunk-ZNNXRNFD.js → chunk-5N4GGUBN.js} +48 -6
  46. package/dist/chunk-5N4GGUBN.js.map +1 -0
  47. package/dist/chunk-5USBZ2MU.js +58 -0
  48. package/dist/chunk-5USBZ2MU.js.map +1 -0
  49. package/dist/chunk-64WOMNYR.js +183 -0
  50. package/dist/chunk-64WOMNYR.js.map +1 -0
  51. package/dist/{chunk-ILNIZ5I2.js → chunk-65RS4LQS.js} +1825 -1715
  52. package/dist/chunk-65RS4LQS.js.map +1 -0
  53. package/dist/{chunk-IE7P2BZE.js → chunk-6QMDUDF2.js} +3 -3
  54. package/dist/{chunk-IADZOXKN.js → chunk-7SLOTLO7.js} +19 -697
  55. package/dist/chunk-7SLOTLO7.js.map +1 -0
  56. package/dist/{chunk-WFSPCCVW.js → chunk-7V25UAQO.js} +99 -99
  57. package/dist/{chunk-WFSPCCVW.js.map → chunk-7V25UAQO.js.map} +1 -1
  58. package/dist/chunk-BGA4DO5M.js +719 -0
  59. package/dist/chunk-BGA4DO5M.js.map +1 -0
  60. package/dist/chunk-BVP7YK2J.js +706 -0
  61. package/dist/chunk-BVP7YK2J.js.map +1 -0
  62. package/dist/chunk-C265QIMJ.js +83 -0
  63. package/dist/chunk-C265QIMJ.js.map +1 -0
  64. package/dist/{chunk-XQJXNMSB.js → chunk-CRG54LEB.js} +1 -1
  65. package/dist/chunk-CRG54LEB.js.map +1 -0
  66. package/dist/{chunk-KG3D7FIF.js → chunk-CZJOMUBP.js} +2 -2
  67. package/dist/{chunk-36RVGZNY.js → chunk-D6M3ZK66.js} +22 -39
  68. package/dist/chunk-D6M3ZK66.js.map +1 -0
  69. package/dist/{chunk-3UCIG4TG.js → chunk-DI4QAGRZ.js} +1 -11
  70. package/dist/chunk-DI4QAGRZ.js.map +1 -0
  71. package/dist/{chunk-JKKAIPTU.js → chunk-DIH2G3YG.js} +47 -10
  72. package/dist/chunk-DIH2G3YG.js.map +1 -0
  73. package/dist/chunk-DJ36BM62.js +78 -0
  74. package/dist/chunk-DJ36BM62.js.map +1 -0
  75. package/dist/chunk-DTEWAVNE.js +114 -0
  76. package/dist/chunk-DTEWAVNE.js.map +1 -0
  77. package/dist/chunk-F2KJAJ7T.js +13 -0
  78. package/dist/chunk-F2KJAJ7T.js.map +1 -0
  79. package/dist/{chunk-BF4XHEQK.js → chunk-F3QPGYOY.js} +6 -6
  80. package/dist/chunk-F3QPGYOY.js.map +1 -0
  81. package/dist/{chunk-3GNJXKIT.js → chunk-F43CV6UC.js} +2 -2
  82. package/dist/{chunk-J57UC3DD.js → chunk-FKVJKLPI.js} +3 -3
  83. package/dist/{chunk-V2LQLN5H.js → chunk-FYFHH7V5.js} +59 -8
  84. package/dist/{chunk-V2LQLN5H.js.map → chunk-FYFHH7V5.js.map} +1 -1
  85. package/dist/chunk-GAJC4BQZ.js +1096 -0
  86. package/dist/chunk-GAJC4BQZ.js.map +1 -0
  87. package/dist/{chunk-DOQGNFHM.js → chunk-GH5UKMZD.js} +2 -12
  88. package/dist/{chunk-DOQGNFHM.js.map → chunk-GH5UKMZD.js.map} +1 -1
  89. package/dist/{chunk-WYXUQGOL.js → chunk-HAZAN4UM.js} +7 -6
  90. package/dist/chunk-HAZAN4UM.js.map +1 -0
  91. package/dist/chunk-HI5XQOX2.js +393 -0
  92. package/dist/chunk-HI5XQOX2.js.map +1 -0
  93. package/dist/chunk-HKGUKAQW.js +488 -0
  94. package/dist/chunk-HKGUKAQW.js.map +1 -0
  95. package/dist/{chunk-SO3XRZPX.js → chunk-HPRVFJPM.js} +6 -6
  96. package/dist/{chunk-L6JEXB3E.js → chunk-HQR4BWKX.js} +3 -131
  97. package/dist/chunk-HQR4BWKX.js.map +1 -0
  98. package/dist/chunk-HZKANST2.js +177 -0
  99. package/dist/chunk-HZKANST2.js.map +1 -0
  100. package/dist/{chunk-UUGOUOVT.js → chunk-I557SAOM.js} +8 -2
  101. package/dist/chunk-I557SAOM.js.map +1 -0
  102. package/dist/{chunk-TC2WZLSC.js → chunk-IGLWLH73.js} +8 -7
  103. package/dist/chunk-IGLWLH73.js.map +1 -0
  104. package/dist/chunk-ILWCKCOI.js +58 -0
  105. package/dist/chunk-ILWCKCOI.js.map +1 -0
  106. package/dist/{chunk-2GP3HRYK.js → chunk-INSIW65E.js} +182 -182
  107. package/dist/{chunk-MPZUYCAP.js → chunk-IULCDMVG.js} +12 -1
  108. package/dist/chunk-IULCDMVG.js.map +1 -0
  109. package/dist/{chunk-INTFHMU4.js → chunk-IVNSUAVC.js} +25 -26
  110. package/dist/chunk-IVNSUAVC.js.map +1 -0
  111. package/dist/chunk-JDQZCREI.js +87 -0
  112. package/dist/chunk-JDQZCREI.js.map +1 -0
  113. package/dist/chunk-JHFFUVON.js +1050 -0
  114. package/dist/chunk-JHFFUVON.js.map +1 -0
  115. package/dist/{chunk-RL5UUDT4.js → chunk-JNUKLSMZ.js} +3 -3
  116. package/dist/chunk-JTILUN4W.js +2933 -0
  117. package/dist/chunk-JTILUN4W.js.map +1 -0
  118. package/dist/{chunk-OJNTCYQQ.js → chunk-JTX3BUDK.js} +37 -53
  119. package/dist/chunk-JTX3BUDK.js.map +1 -0
  120. package/dist/{chunk-X5ZBP3IY.js → chunk-JUUBBBY5.js} +2 -2
  121. package/dist/chunk-JUUBBBY5.js.map +1 -0
  122. package/dist/chunk-JWAK7JQB.js +15 -0
  123. package/dist/chunk-JWAK7JQB.js.map +1 -0
  124. package/dist/{chunk-UXZONNEQ.js → chunk-K5KNGC4I.js} +34 -31
  125. package/dist/chunk-K5KNGC4I.js.map +1 -0
  126. package/dist/chunk-KAQ4Q3TO.js +135 -0
  127. package/dist/chunk-KAQ4Q3TO.js.map +1 -0
  128. package/dist/chunk-KFVJYLVL.js +125 -0
  129. package/dist/chunk-KFVJYLVL.js.map +1 -0
  130. package/dist/chunk-KGUE5AVX.js +69 -0
  131. package/dist/chunk-KGUE5AVX.js.map +1 -0
  132. package/dist/{chunk-FVIGCDSV.js → chunk-KLDMLWXT.js} +11 -85
  133. package/dist/chunk-KLDMLWXT.js.map +1 -0
  134. package/dist/chunk-KNKDMTHU.js +453 -0
  135. package/dist/chunk-KNKDMTHU.js.map +1 -0
  136. package/dist/chunk-LDA6TAYQ.js +95 -0
  137. package/dist/chunk-LDA6TAYQ.js.map +1 -0
  138. package/dist/chunk-LWSSIZOY.js +347 -0
  139. package/dist/chunk-LWSSIZOY.js.map +1 -0
  140. package/dist/{chunk-ZURZHELF.js → chunk-MAHNZA6C.js} +158 -41
  141. package/dist/chunk-MAHNZA6C.js.map +1 -0
  142. package/dist/chunk-MEWZCIA6.js +220 -0
  143. package/dist/chunk-MEWZCIA6.js.map +1 -0
  144. package/dist/{chunk-2SNUOHAT.js → chunk-MEZJ3I63.js} +49 -1
  145. package/dist/chunk-MEZJ3I63.js.map +1 -0
  146. package/dist/chunk-MJDO4EXD.js +353 -0
  147. package/dist/chunk-MJDO4EXD.js.map +1 -0
  148. package/dist/chunk-NJA6NT3A.js +6595 -0
  149. package/dist/chunk-NJA6NT3A.js.map +1 -0
  150. package/dist/{chunk-LHHMV4GU.js → chunk-NVSKJPRC.js} +1 -1
  151. package/dist/{chunk-LHHMV4GU.js.map → chunk-NVSKJPRC.js.map} +1 -1
  152. package/dist/{chunk-4YOZGGTZ.js → chunk-OC7K2DVZ.js} +5 -5
  153. package/dist/chunk-OC7K2DVZ.js.map +1 -0
  154. package/dist/chunk-ODRPASFP.js +2078 -0
  155. package/dist/chunk-ODRPASFP.js.map +1 -0
  156. package/dist/chunk-OJJFANO6.js +133 -0
  157. package/dist/chunk-OJJFANO6.js.map +1 -0
  158. package/dist/{chunk-JNJWBTU2.js → chunk-OQWPRFAC.js} +332 -882
  159. package/dist/chunk-OQWPRFAC.js.map +1 -0
  160. package/dist/chunk-P4I7BFNJ.js +11 -0
  161. package/dist/chunk-P4I7BFNJ.js.map +1 -0
  162. package/dist/{chunk-SNNSAGMT.js → chunk-P6YQWIT2.js} +4058 -4039
  163. package/dist/chunk-P6YQWIT2.js.map +1 -0
  164. package/dist/{chunk-JRGFKVAZ.js → chunk-PETQ5WEA.js} +2 -2
  165. package/dist/{chunk-HMWYAUA6.js → chunk-Q6RSJCXB.js} +29 -69
  166. package/dist/chunk-Q6RSJCXB.js.map +1 -0
  167. package/dist/{chunk-U3IKUGRP.js → chunk-QKEUKBRK.js} +17 -23
  168. package/dist/chunk-QKEUKBRK.js.map +1 -0
  169. package/dist/{chunk-2RWB7RKE.js → chunk-QKYUCITR.js} +174 -5814
  170. package/dist/chunk-QKYUCITR.js.map +1 -0
  171. package/dist/chunk-QQDPRTLP.js +127 -0
  172. package/dist/chunk-QQDPRTLP.js.map +1 -0
  173. package/dist/chunk-QQYCYAKI.js +79 -0
  174. package/dist/chunk-QQYCYAKI.js.map +1 -0
  175. package/dist/chunk-R4KDH477.js +1064 -0
  176. package/dist/chunk-R4KDH477.js.map +1 -0
  177. package/dist/chunk-R5TR2DIK.js +119 -0
  178. package/dist/chunk-R5TR2DIK.js.map +1 -0
  179. package/dist/chunk-R62PKTAG.js +66 -0
  180. package/dist/chunk-R62PKTAG.js.map +1 -0
  181. package/dist/{chunk-BFDQ4WNW.js → chunk-RFZA7PSM.js} +4 -5
  182. package/dist/chunk-RFZA7PSM.js.map +1 -0
  183. package/dist/chunk-RGCPELQN.js +219 -0
  184. package/dist/chunk-RGCPELQN.js.map +1 -0
  185. package/dist/chunk-RGVCOG2S.js +910 -0
  186. package/dist/chunk-RGVCOG2S.js.map +1 -0
  187. package/dist/chunk-SOLNJ3AZ.js +209 -0
  188. package/dist/chunk-SOLNJ3AZ.js.map +1 -0
  189. package/dist/chunk-TFT2X7SH.js +77 -0
  190. package/dist/chunk-TFT2X7SH.js.map +1 -0
  191. package/dist/chunk-TUCKEEXE.js +2 -0
  192. package/dist/chunk-TVWCLUBI.js +293 -0
  193. package/dist/chunk-TVWCLUBI.js.map +1 -0
  194. package/dist/chunk-U4TRWSVE.js +78 -0
  195. package/dist/chunk-U4TRWSVE.js.map +1 -0
  196. package/dist/chunk-UIB33QQP.js +379 -0
  197. package/dist/chunk-UIB33QQP.js.map +1 -0
  198. package/dist/chunk-V6GIVALQ.js +1889 -0
  199. package/dist/chunk-V6GIVALQ.js.map +1 -0
  200. package/dist/chunk-VHXCPXUS.js +366 -0
  201. package/dist/chunk-VHXCPXUS.js.map +1 -0
  202. package/dist/{chunk-HGZEPQUT.js → chunk-VU6GMWF6.js} +17 -8
  203. package/dist/chunk-VU6GMWF6.js.map +1 -0
  204. package/dist/chunk-VWZYE3NC.js +8415 -0
  205. package/dist/chunk-VWZYE3NC.js.map +1 -0
  206. package/dist/{chunk-AGMVASXZ.js → chunk-W2GXIARJ.js} +88 -11
  207. package/dist/chunk-W2GXIARJ.js.map +1 -0
  208. package/dist/chunk-W4G3K3V7.js +288 -0
  209. package/dist/chunk-W4G3K3V7.js.map +1 -0
  210. package/dist/chunk-W74LJ5OT.js +588 -0
  211. package/dist/chunk-W74LJ5OT.js.map +1 -0
  212. package/dist/chunk-W7ELYLYK.js +233 -0
  213. package/dist/chunk-W7ELYLYK.js.map +1 -0
  214. package/dist/{chunk-BPMWXTFX.js → chunk-WFZX352D.js} +7 -7
  215. package/dist/chunk-WXA3WTPF.js +20 -0
  216. package/dist/chunk-WXA3WTPF.js.map +1 -0
  217. package/dist/chunk-XRGFH7FI.js +454 -0
  218. package/dist/chunk-XRGFH7FI.js.map +1 -0
  219. package/dist/chunk-XSCGUO2U.js +330 -0
  220. package/dist/chunk-XSCGUO2U.js.map +1 -0
  221. package/dist/chunk-XWROSMI5.js +1039 -0
  222. package/dist/chunk-XWROSMI5.js.map +1 -0
  223. package/dist/chunk-Y2EXZ47H.js +40 -0
  224. package/dist/chunk-Y2EXZ47H.js.map +1 -0
  225. package/dist/chunk-YJGEVBKZ.js +47 -0
  226. package/dist/chunk-YJGEVBKZ.js.map +1 -0
  227. package/dist/{chunk-6CMM6YCB.js → chunk-YWWMISDY.js} +2 -2
  228. package/dist/{chunk-WXA2BWTE.js → chunk-ZCT5DJ3G.js} +2 -48
  229. package/dist/chunk-ZCT5DJ3G.js.map +1 -0
  230. package/dist/chunk-ZEYA2WWX.js +982 -0
  231. package/dist/chunk-ZEYA2WWX.js.map +1 -0
  232. package/dist/chunk-ZRC7Z5X3.js +82 -0
  233. package/dist/chunk-ZRC7Z5X3.js.map +1 -0
  234. package/dist/{chunk-3AIHRXKO.js → chunk-ZS7JIUJ3.js} +12 -10
  235. package/dist/chunk-ZS7JIUJ3.js.map +1 -0
  236. package/dist/{clack-EZ7TDWQU.js → clack-Q4RNC5VE.js} +2 -6
  237. package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
  238. package/dist/claude-install-BAUSJMW3.js +64 -0
  239. package/dist/{cli-E36SPKBW.js → cli-QY4KKA3D.js} +632 -150
  240. package/dist/cli-QY4KKA3D.js.map +1 -0
  241. package/dist/client-3YQKORVK.js +710 -0
  242. package/dist/client-3YQKORVK.js.map +1 -0
  243. package/dist/{codex-event-ZO2GEFE6.js → codex-event-EUTCAOTQ.js} +3 -5
  244. package/dist/{codex-host-KECJVTA2.js → codex-host-ZON3S6HU.js} +7 -7
  245. package/dist/{codex-install-HQZDGFXW.js → codex-install-HZV2DOAB.js} +242 -88
  246. package/dist/codex-install-HZV2DOAB.js.map +1 -0
  247. package/dist/config-QZOBMTEL.js +57 -0
  248. package/dist/config-names-Z5NZD5R2.js +224 -0
  249. package/dist/config-names-Z5NZD5R2.js.map +1 -0
  250. package/dist/config-rules-YOYHS6YL.js +55 -0
  251. package/dist/config-subagents-WQV2ZAD5.js +362 -0
  252. package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
  253. package/dist/connect-YDWTYU4B.js +1020 -0
  254. package/dist/connect-YDWTYU4B.js.map +1 -0
  255. package/dist/core-0a66n3e7-TTP554XV.js +127 -0
  256. package/dist/core-0a66n3e7-TTP554XV.js.map +1 -0
  257. package/dist/core-0bmnpbz2-C2JIRVZO.js +10790 -0
  258. package/dist/core-0bmnpbz2-C2JIRVZO.js.map +1 -0
  259. package/dist/core-9je8ee1j-74DGHWPV.js +30 -0
  260. package/dist/core-9je8ee1j-74DGHWPV.js.map +1 -0
  261. package/dist/core-wadgcjfh-TSZFQZGH.js +666 -0
  262. package/dist/core-wadgcjfh-TSZFQZGH.js.map +1 -0
  263. package/dist/core-zg882d22-LKV5DZYW.js +37 -0
  264. package/dist/core-zg882d22-LKV5DZYW.js.map +1 -0
  265. package/dist/decision-QSKHOGCO.js +145 -0
  266. package/dist/{doctor-I6XQEKWD.js → doctor-ZWJXRD75.js} +162 -148
  267. package/dist/doctor-ZWJXRD75.js.map +1 -0
  268. package/dist/{env-proxy-R6ZMLQTT.js → env-proxy-XLSLHBKQ.js} +2 -2
  269. package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js → ethersCompat-Df4a6QIZ-K3DMHR6Y.js} +5 -5
  270. package/dist/explicit-ME2NRADQ.js +371 -0
  271. package/dist/explicit-ME2NRADQ.js.map +1 -0
  272. package/dist/flush-stdio-NYIJ3QXT.js +18 -0
  273. package/dist/fund-VF7TLDJH.js +722 -0
  274. package/dist/fund-VF7TLDJH.js.map +1 -0
  275. package/dist/hook-command-VZ27MGWO.js +49 -0
  276. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  277. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  278. package/dist/hosts/claude/tenjin/hooks/hook-data.ts +152 -0
  279. package/dist/hosts/claude/tenjin/hooks/hooks.json +7 -0
  280. package/dist/hosts/claude/tenjin/hooks/model-viewer.tsx +2987 -0
  281. package/dist/hosts/claude/tenjin/hooks/register.tsx +527 -56
  282. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
  283. package/dist/hosts/claude/tenjin/types/index.d.ts +144 -1
  284. package/dist/{hosts-DVQJ32QC.js → hosts-3EMTVM4H.js} +7 -6
  285. package/dist/index.js +18 -15
  286. package/dist/index.js.map +1 -1
  287. package/dist/install-ZA7L2UF3.js +115 -0
  288. package/dist/install-funding-JDGYTF72.js +30 -0
  289. package/dist/install-identity-FFAYEFLX.js +30 -0
  290. package/dist/{install-wallet-5M4OTYLX.js → install-wallet-2SFOVE3Q.js} +68 -53
  291. package/dist/install-wallet-2SFOVE3Q.js.map +1 -0
  292. package/dist/mcp-36S6MK3C.js +67642 -0
  293. package/dist/mcp-36S6MK3C.js.map +1 -0
  294. package/dist/new-install-5L4GY3LN.js +51 -0
  295. package/dist/{package-IJFGMWEV.js → package-BONDXSV3.js} +2 -2
  296. package/dist/{passphrase-IFTDS3CU.js → passphrase-T4ULBN4M.js} +16 -12
  297. package/dist/{paths-XCSAKISU.js → paths-O2KDWZ76.js} +18 -28
  298. package/dist/pay-CMV5KL74.js +74 -0
  299. package/dist/{payments-HFPPWHTV.js → payments-Z6UBZL4Z.js} +36 -26
  300. package/dist/payments-Z6UBZL4Z.js.map +1 -0
  301. package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
  302. package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
  303. package/dist/{redact-D7ASVWKL.js → redact-LOTHE5TS.js} +2 -8
  304. package/dist/redact-LOTHE5TS.js.map +1 -0
  305. package/dist/routing-quote-AHLAREXR.js +40 -0
  306. package/dist/routing-quote-AHLAREXR.js.map +1 -0
  307. package/dist/run-JH7ELYAM.js +88 -0
  308. package/dist/run-JH7ELYAM.js.map +1 -0
  309. package/dist/runtime-2GX4ALJP.js +410 -0
  310. package/dist/runtime-2GX4ALJP.js.map +1 -0
  311. package/dist/runtime-activate-IDQ2NCSP.js +39 -0
  312. package/dist/runtime-activate-IDQ2NCSP.js.map +1 -0
  313. package/dist/{runtime-fetch-ZSSSK72Y.js → runtime-fetch-6LOBHBEN.js} +4 -4
  314. package/dist/runtime-fetch-6LOBHBEN.js.map +1 -0
  315. package/dist/runtime-launchers-YAPKCBHV.js +31 -0
  316. package/dist/runtime-launchers-YAPKCBHV.js.map +1 -0
  317. package/dist/{runtime-layout-WIDILZ6K.js → runtime-layout-QHZQJV7C.js} +5 -4
  318. package/dist/runtime-layout-QHZQJV7C.js.map +1 -0
  319. package/dist/runtime-place-4POL4KK4.js +37 -0
  320. package/dist/runtime-place-4POL4KK4.js.map +1 -0
  321. package/dist/runtime-provenance-MNJGVBV2.js +12 -0
  322. package/dist/runtime-provenance-MNJGVBV2.js.map +1 -0
  323. package/dist/{secp256k1-ZZZT2CAX.js → secp256k1-N5P2GVGF.js} +3 -3
  324. package/dist/secp256k1-N5P2GVGF.js.map +1 -0
  325. package/dist/{send-GCVEAQKL.js → send-ELXFKEKY.js} +35 -32
  326. package/dist/send-ELXFKEKY.js.map +1 -0
  327. package/dist/status-FXUFWJDM.js +404 -0
  328. package/dist/status-FXUFWJDM.js.map +1 -0
  329. package/dist/{status-line-OPCXDHL2.js → status-line-IH5JBWBC.js} +51 -43
  330. package/dist/status-line-IH5JBWBC.js.map +1 -0
  331. package/dist/streamableHttp-CP2ZQBIK.js +768 -0
  332. package/dist/streamableHttp-CP2ZQBIK.js.map +1 -0
  333. package/dist/{uninstall-BAWRBXXQ.js → uninstall-LJZUKM4D.js} +76 -76
  334. package/dist/uninstall-LJZUKM4D.js.map +1 -0
  335. package/dist/update-EUIX72IX.js +68 -0
  336. package/dist/update-EUIX72IX.js.map +1 -0
  337. package/dist/usage-EKDC7LUC.js +180 -0
  338. package/dist/usage-EKDC7LUC.js.map +1 -0
  339. package/dist/{usdc-VG4CIOUK.js → usdc-YIHK2OMC.js} +8 -12
  340. package/dist/usdc-YIHK2OMC.js.map +1 -0
  341. package/dist/{viemAdapter-By13KInL-DOFTEIJV.js → viemAdapter-By13KInL-PRLSIESK.js} +5 -5
  342. package/dist/viemAdapter-By13KInL-PRLSIESK.js.map +1 -0
  343. package/dist/wallet-HSW757W6.js +80 -0
  344. package/dist/wallet-HSW757W6.js.map +1 -0
  345. package/dist/wallet-kdf-worker.mjs +1433 -818
  346. package/docs/agent-permissions.md +88 -155
  347. package/docs/router-reference.md +236 -0
  348. package/docs/safety-model.md +31 -33
  349. package/docs/subagents-internals.md +97 -0
  350. package/docs/subagents.md +348 -0
  351. package/docs/troubleshooting.md +10 -6
  352. package/package.json +12 -8
  353. package/scripts/installers/install.sh +7 -1
  354. package/dist/alive-GSOWKUOY.js +0 -38
  355. package/dist/chunk-2I4QTOLB.js.map +0 -1
  356. package/dist/chunk-2M2VPI2E.js +0 -560
  357. package/dist/chunk-2M2VPI2E.js.map +0 -1
  358. package/dist/chunk-2RWB7RKE.js.map +0 -1
  359. package/dist/chunk-2SNUOHAT.js.map +0 -1
  360. package/dist/chunk-3623BLPV.js +0 -184
  361. package/dist/chunk-3623BLPV.js.map +0 -1
  362. package/dist/chunk-36RVGZNY.js.map +0 -1
  363. package/dist/chunk-3AIHRXKO.js.map +0 -1
  364. package/dist/chunk-3FMZGI7I.js.map +0 -1
  365. package/dist/chunk-3UCIG4TG.js.map +0 -1
  366. package/dist/chunk-4K7TQHNP.js.map +0 -1
  367. package/dist/chunk-4LMUQMBH.js +0 -29
  368. package/dist/chunk-4LMUQMBH.js.map +0 -1
  369. package/dist/chunk-4USCZ2NI.js +0 -228
  370. package/dist/chunk-4USCZ2NI.js.map +0 -1
  371. package/dist/chunk-4YOZGGTZ.js.map +0 -1
  372. package/dist/chunk-62KNUYWD.js +0 -111
  373. package/dist/chunk-62KNUYWD.js.map +0 -1
  374. package/dist/chunk-A5GKIG5O.js +0 -2037
  375. package/dist/chunk-A5GKIG5O.js.map +0 -1
  376. package/dist/chunk-AGMVASXZ.js.map +0 -1
  377. package/dist/chunk-BF4XHEQK.js.map +0 -1
  378. package/dist/chunk-BFDQ4WNW.js.map +0 -1
  379. package/dist/chunk-C2Q76BVM.js.map +0 -1
  380. package/dist/chunk-CEXSOI5R.js +0 -808
  381. package/dist/chunk-CEXSOI5R.js.map +0 -1
  382. package/dist/chunk-E7SW44LM.js.map +0 -1
  383. package/dist/chunk-EDJWHDDL.js +0 -33
  384. package/dist/chunk-EDJWHDDL.js.map +0 -1
  385. package/dist/chunk-FVIGCDSV.js.map +0 -1
  386. package/dist/chunk-GTTUCOPD.js +0 -105
  387. package/dist/chunk-GTTUCOPD.js.map +0 -1
  388. package/dist/chunk-HDPUXS3Z.js +0 -122
  389. package/dist/chunk-HDPUXS3Z.js.map +0 -1
  390. package/dist/chunk-HGGWCP7W.js +0 -120
  391. package/dist/chunk-HGGWCP7W.js.map +0 -1
  392. package/dist/chunk-HGZEPQUT.js.map +0 -1
  393. package/dist/chunk-HMWYAUA6.js.map +0 -1
  394. package/dist/chunk-IADZOXKN.js.map +0 -1
  395. package/dist/chunk-ILNIZ5I2.js.map +0 -1
  396. package/dist/chunk-INTFHMU4.js.map +0 -1
  397. package/dist/chunk-JKKAIPTU.js.map +0 -1
  398. package/dist/chunk-JNJWBTU2.js.map +0 -1
  399. package/dist/chunk-KM7RY2ZS.js +0 -246
  400. package/dist/chunk-KM7RY2ZS.js.map +0 -1
  401. package/dist/chunk-KOGZDMHO.js +0 -21
  402. package/dist/chunk-KOGZDMHO.js.map +0 -1
  403. package/dist/chunk-L6JEXB3E.js.map +0 -1
  404. package/dist/chunk-LRW6S53P.js.map +0 -1
  405. package/dist/chunk-LXAYUOXI.js +0 -511
  406. package/dist/chunk-LXAYUOXI.js.map +0 -1
  407. package/dist/chunk-MEFB5KHA.js +0 -59
  408. package/dist/chunk-MEFB5KHA.js.map +0 -1
  409. package/dist/chunk-MPZUYCAP.js.map +0 -1
  410. package/dist/chunk-NDGZDTSJ.js.map +0 -1
  411. package/dist/chunk-OJNTCYQQ.js.map +0 -1
  412. package/dist/chunk-P3LFTKE7.js +0 -58
  413. package/dist/chunk-P3LFTKE7.js.map +0 -1
  414. package/dist/chunk-QXP3Z3JN.js.map +0 -1
  415. package/dist/chunk-RVPYTUP4.js.map +0 -1
  416. package/dist/chunk-SNNSAGMT.js.map +0 -1
  417. package/dist/chunk-TC2WZLSC.js.map +0 -1
  418. package/dist/chunk-TKPF35W6.js +0 -29
  419. package/dist/chunk-TKPF35W6.js.map +0 -1
  420. package/dist/chunk-U3IKUGRP.js.map +0 -1
  421. package/dist/chunk-UUGOUOVT.js.map +0 -1
  422. package/dist/chunk-UXZONNEQ.js.map +0 -1
  423. package/dist/chunk-WXA2BWTE.js.map +0 -1
  424. package/dist/chunk-WYXUQGOL.js.map +0 -1
  425. package/dist/chunk-X5ZBP3IY.js.map +0 -1
  426. package/dist/chunk-XKESD27X.js +0 -10
  427. package/dist/chunk-XKESD27X.js.map +0 -1
  428. package/dist/chunk-XQJXNMSB.js.map +0 -1
  429. package/dist/chunk-Y527D4TV.js +0 -56
  430. package/dist/chunk-Y527D4TV.js.map +0 -1
  431. package/dist/chunk-ZDZERB6L.js.map +0 -1
  432. package/dist/chunk-ZNNXRNFD.js.map +0 -1
  433. package/dist/chunk-ZURZHELF.js.map +0 -1
  434. package/dist/cli-E36SPKBW.js.map +0 -1
  435. package/dist/codex-install-HQZDGFXW.js.map +0 -1
  436. package/dist/config-HY2E4GGW.js +0 -55
  437. package/dist/doctor-I6XQEKWD.js.map +0 -1
  438. package/dist/fund-2QRO7OJL.js +0 -378
  439. package/dist/fund-2QRO7OJL.js.map +0 -1
  440. package/dist/hook-command-2UBCSZG6.js +0 -43
  441. package/dist/install-ILUX5C4A.js +0 -107
  442. package/dist/install-identity-TZKGY6LQ.js +0 -31
  443. package/dist/install-wallet-5M4OTYLX.js.map +0 -1
  444. package/dist/mcp-LE4DUS22.js +0 -14127
  445. package/dist/mcp-LE4DUS22.js.map +0 -1
  446. package/dist/pay-WCG3IH4R.js +0 -55
  447. package/dist/payments-HFPPWHTV.js.map +0 -1
  448. package/dist/plugin-registration-PZFI5GZW.js +0 -68
  449. package/dist/runtime-UZOKSUZX.js +0 -1321
  450. package/dist/runtime-UZOKSUZX.js.map +0 -1
  451. package/dist/send-GCVEAQKL.js.map +0 -1
  452. package/dist/status-HCVAOCN7.js +0 -150
  453. package/dist/status-HCVAOCN7.js.map +0 -1
  454. package/dist/status-line-OPCXDHL2.js.map +0 -1
  455. package/dist/uninstall-BAWRBXXQ.js.map +0 -1
  456. package/dist/update-CACXLQLR.js +0 -56
  457. package/dist/wallet-QL4UUXEZ.js +0 -55
  458. /package/dist/{_esm-BIN7VY2L.js.map → _esm-2KST7HQ7.js.map} +0 -0
  459. /package/dist/{alive-GSOWKUOY.js.map → alive-5TV22PNF.js.map} +0 -0
  460. /package/dist/{auto-update-Y24UL56V.js.map → auth-XI7BJFLW.js.map} +0 -0
  461. /package/dist/{ccip-DHDFKTQV.js.map → auto-update-7L24KDWA.js.map} +0 -0
  462. /package/dist/{clack-EZ7TDWQU.js.map → balance-DFHC6XEU.js.map} +0 -0
  463. /package/dist/{claude-cli-2YKABJJZ.js.map → ccip-HOW3DZYF.js.map} +0 -0
  464. /package/dist/{chunk-IE7P2BZE.js.map → chunk-6QMDUDF2.js.map} +0 -0
  465. /package/dist/{chunk-KG3D7FIF.js.map → chunk-CZJOMUBP.js.map} +0 -0
  466. /package/dist/{chunk-3GNJXKIT.js.map → chunk-F43CV6UC.js.map} +0 -0
  467. /package/dist/{chunk-J57UC3DD.js.map → chunk-FKVJKLPI.js.map} +0 -0
  468. /package/dist/{chunk-SO3XRZPX.js.map → chunk-HPRVFJPM.js.map} +0 -0
  469. /package/dist/{chunk-2GP3HRYK.js.map → chunk-INSIW65E.js.map} +0 -0
  470. /package/dist/{chunk-RL5UUDT4.js.map → chunk-JNUKLSMZ.js.map} +0 -0
  471. /package/dist/{chunk-JRGFKVAZ.js.map → chunk-PETQ5WEA.js.map} +0 -0
  472. /package/dist/{codex-event-ZO2GEFE6.js.map → chunk-TUCKEEXE.js.map} +0 -0
  473. /package/dist/{chunk-BPMWXTFX.js.map → chunk-WFZX352D.js.map} +0 -0
  474. /package/dist/{chunk-6CMM6YCB.js.map → chunk-YWWMISDY.js.map} +0 -0
  475. /package/dist/{codex-host-KECJVTA2.js.map → clack-Q4RNC5VE.js.map} +0 -0
  476. /package/dist/{config-HY2E4GGW.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
  477. /package/dist/{env-proxy-R6ZMLQTT.js.map → claude-install-BAUSJMW3.js.map} +0 -0
  478. /package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js.map → codex-event-EUTCAOTQ.js.map} +0 -0
  479. /package/dist/{hook-command-2UBCSZG6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
  480. /package/dist/{hosts-DVQJ32QC.js.map → config-QZOBMTEL.js.map} +0 -0
  481. /package/dist/{install-ILUX5C4A.js.map → config-rules-YOYHS6YL.js.map} +0 -0
  482. /package/dist/{install-identity-TZKGY6LQ.js.map → decision-QSKHOGCO.js.map} +0 -0
  483. /package/dist/{package-IJFGMWEV.js.map → env-proxy-XLSLHBKQ.js.map} +0 -0
  484. /package/dist/{passphrase-IFTDS3CU.js.map → ethersCompat-Df4a6QIZ-K3DMHR6Y.js.map} +0 -0
  485. /package/dist/{paths-XCSAKISU.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
  486. /package/dist/{pay-WCG3IH4R.js.map → hook-command-VZ27MGWO.js.map} +0 -0
  487. /package/dist/{plugin-registration-PZFI5GZW.js.map → hosts-3EMTVM4H.js.map} +0 -0
  488. /package/dist/{redact-D7ASVWKL.js.map → install-ZA7L2UF3.js.map} +0 -0
  489. /package/dist/{runtime-fetch-ZSSSK72Y.js.map → install-funding-JDGYTF72.js.map} +0 -0
  490. /package/dist/{runtime-layout-WIDILZ6K.js.map → install-identity-FFAYEFLX.js.map} +0 -0
  491. /package/dist/{secp256k1-ZZZT2CAX.js.map → new-install-5L4GY3LN.js.map} +0 -0
  492. /package/dist/{update-CACXLQLR.js.map → package-BONDXSV3.js.map} +0 -0
  493. /package/dist/{usdc-VG4CIOUK.js.map → passphrase-T4ULBN4M.js.map} +0 -0
  494. /package/dist/{viemAdapter-By13KInL-DOFTEIJV.js.map → paths-O2KDWZ76.js.map} +0 -0
  495. /package/dist/{wallet-QL4UUXEZ.js.map → pay-CMV5KL74.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/model-job.ts","../src/router/model-worker-control.ts","../src/router/windows-worker-config.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { lstat, mkdir, opendir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { holdLock, isHeldLockName, sweepHeldLocks, withHeldLock } from '../lib/held-lock';\nimport { LockTimeoutError } from '../lib/lock';\nimport { canonicalHash } from '../lib/request-schema';\nimport { WORKER_ENDS } from './model-worker-control';\nimport { readJsonFile, sweep, writePrivate } from './store-files';\n\nconst jobSchema = z.object({\n id: z.uuid(),\n sessionId: z.string(),\n turnId: z.string(),\n callId: z.string(),\n root: z.string(),\n task: z.string(),\n native: z.record(z.string(), z.unknown()),\n nativeTool: z.enum(['Agent', 'Task']).optional(),\n /** The parent's model request that made the call, as the host numbers it. */\n step: z.string().optional(),\n /** The agent id of the native subagent that made the call and receives its offer; absent for the main loop. */\n caller: z.string().optional(),\n decision: z.record(z.string(), z.unknown()),\n capAtomic: z.string().regex(/^\\d+$/),\n state: z.enum([\n 'routing',\n 'offered',\n 'native',\n 'running',\n 'cancelling',\n 'completed',\n 'cancelled',\n 'unknown',\n ]),\n expiresAt: z.number(),\n result: z.string().optional(),\n /**\n * The process that accepted the job and runs its worker, and when. For diagnosis only: whether\n * a runner is alive is the runner lock (see {@link ModelJobStore.holdRunner}), never this pid.\n */\n runner: z.object({ pid: z.number().int(), acceptedAt: z.number() }).optional(),\n});\nexport type ModelJob = z.infer<typeof jobSchema>;\nexport const modelJobSchema = jobSchema;\n\n/**\n * A model store's lock: `<path>.held`, which ends with the process that holds it, so a holder\n * killed mid-update never blocks a later operation and nothing is taken over from a live one.\n * It protects one read-modify-write of the store's records for a few milliseconds, and waits\n * up to 5 s before the caller fails (before any money moves).\n */\nexport const modelLock = <T>(path: string, fn: () => Promise<T>): Promise<T> =>\n withHeldLock(path, fn);\n\n/** Local job, conversation and budget records are removed this long after their last write. */\nexport const MODEL_RECORD_TTL_MS = 7 * 24 * 60 * 60_000;\n\n/** What a later accept of a worker that died with its process answers. */\nexport const STRANDED_HANDBACK = {\n status: 'unknown',\n endedBy: 'session_ended',\n ended: WORKER_ENDS.session_ended,\n stopReason: { kind: 'interrupted', reason: 'session_ended' },\n nextStep:\n 'This worker stopped when its session or Tenjin process ended, as a native subagent does. It cannot be continued. If the work is still needed, start a fresh assignment with the needed context.',\n} as const;\n\n/**\n * Removes every model record file not written for {@link MODEL_RECORD_TTL_MS}, EXCEPT the files\n * of a job that is still live: a job has no wall time, so one that waits for a permission\n * answer for days has an old record that its run still needs (its budget file holds what it\n * has spent). A live job is a record still `running` or `cancelling` (the caller ends the\n * records of dead processes first, see `strand`), and every file named for its id is kept.\n * Age alone never decides for such a job. Never throws.\n */\nexport async function sweepModelRecords(dataDir: string, now = Date.now()): Promise<void> {\n // A running continuation spends from its original job's files (budget, record, result,\n // conversation), which carry the original's id and the handle's, not its own.\n const live = new Set<string>();\n const uuid = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;\n for (const job of await new ModelJobStore(dataDir).unfinished().catch(() => [] as ModelJob[])) {\n live.add(job.id.toLowerCase());\n for (const named of [job.decision.jobId, job.decision.workerHandle]) {\n const id = typeof named === 'string' ? uuid.exec(named)?.[0] : undefined;\n if (id) live.add(id.toLowerCase());\n }\n }\n const jobId = (name: string) =>\n /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i.exec(name)?.[1];\n const idle = async (name: string, path: string) => {\n const id = jobId(name);\n if (id && live.has(id.toLowerCase())) return false;\n return now - (await lstat(path)).mtimeMs > MODEL_RECORD_TTL_MS;\n };\n // A lock file is never aged out by its mtime: an unwritten file's never changes, so a lock\n // that guards live state would be deleted. The store-wide locks and the pace locks (no job id\n // in the name) stay; a job's own lock files go with the job, only through `discardHeldLock`.\n const old = async (name: string, path: string) =>\n isHeldLockName(name) ? false : idle(name, path);\n for (const store of ['model-jobs', 'model-conversations']) {\n const dir = join(dataDir, store);\n await sweep(dir, old, { limit: 50_000 });\n await sweepHeldLocks(\n dir,\n async (name) => jobId(name) !== undefined && idle(name, join(dir, name)),\n );\n }\n}\ntype NewJob = Omit<ModelJob, 'id' | 'state' | 'expiresAt'>;\n/** A held call whose offer never ran to completion: its unchanged repeat keeps it native. */\nconst REPEATABLE: readonly ModelJob['state'][] = ['offered', 'cancelled', 'unknown'];\n/** How long an offer can be accepted, and how long after a worker stopped its call repeats free. */\nconst OFFER_MS = 15 * 60_000;\nconst unresolved = (job: ModelJob) =>\n job.state !== 'native' &&\n job.state !== 'completed' &&\n (job.expiresAt > Date.now() || ['running', 'cancelling'].includes(job.state));\n\n/** Why a subagent call the hook saw got no offer. Codes only: never the assignment. */\n/**\n * What a job's routing call was authorized to charge, as this client recorded it when the\n * call was made. Every job this client stores carries it; one that does not is invalid.\n */\nexport function routingAuthorizedAtomic(decision: Record<string, unknown>): bigint {\n const value = decision.routingAuthorizedAtomic;\n if (typeof value !== 'string' || !/^\\d{1,30}$/.test(value))\n throw new Error('The job has no routing authorization');\n return BigInt(value);\n}\nexport const NO_OFFER_CODES = [\n 'kept_native',\n 'no_session',\n 'host_unqualified',\n 'no_consent',\n 'permission_mode',\n 'worker_unqualified',\n 'input_filter',\n 'caller_unqualified',\n 'scope_not_covered',\n 'parent_context_unavailable',\n 'over_size_limit',\n 'job_cap_too_low',\n 'job_cap_lowered',\n 'capture_error',\n 'route_error',\n 'fee_above_ceiling',\n 'server_declined',\n 'invalid_offer',\n 'superseded',\n 'expired',\n 'interrupted',\n] as const;\nconst noOfferSchema = z.object({\n at: z.number(),\n sessionId: z.string(),\n tool: z.string(),\n code: z.enum(NO_OFFER_CODES),\n /** A field name, a mode or the server's own code. */\n detail: z\n .string()\n .regex(/^[A-Za-z0-9_.:-]{1,64}$/)\n .optional(),\n bytes: z.number().optional(),\n limit: z.number().optional(),\n offerId: z.uuid().optional(),\n /** Set when a native subagent made the call, not the main loop. */\n from: z.literal('subagent').optional(),\n});\nexport type NoOffer = z.infer<typeof noOfferSchema>;\nconst NO_OFFERS_KEPT = 200;\nconst NO_OFFERS_FILE = 'no-offers.json';\n/** Open offers one assignment text can have at once before the oldest stops repeating free. */\nconst REPEATS_KEPT = 16;\n\n/**\n * What \"unchanged\" means for a repeated Agent call. Every field counts and key\n * order does not. Whitespace around a top-level string is ignored; whitespace\n * inside it is not. A field set to null or false, and `subagent_type:\n * \"general-purpose\"`, mean the same as leaving the field out.\n */\nfunction repeatKey(native: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(native).flatMap(([key, raw]) => {\n const value = typeof raw === 'string' ? raw.trim() : raw;\n return value === null ||\n value === false ||\n (key === 'subagent_type' && value === 'general-purpose')\n ? []\n : [[key, value]];\n }),\n );\n}\n\n/** Immutable held calls, atomic selection: a job a call. */\nexport class ModelJobStore {\n private dir: string;\n constructor(dataDir: string) {\n this.dir = join(dataDir, 'model-jobs');\n }\n private path(id: string) {\n if (!z.uuid().safeParse(id).success) throw new Error('Invalid model job');\n return join(this.dir, `${id}.json`);\n }\n private callPath(sessionId: string, callId: string) {\n return join(this.dir, `call-${canonicalHash({ sessionId, callId })}.json`);\n }\n /** The held Claude calls with this content in this session and root, oldest first. */\n private async repeatIds(path: string): Promise<string[]> {\n const index = await readJsonFile(path, 4000);\n return (Array.isArray(index?.ids) ? index.ids : []).filter(\n (id): id is string => z.uuid().safeParse(id).success,\n );\n }\n private repeatPath(\n sessionId: string,\n root: string,\n tool: string,\n native: Record<string, unknown>,\n ) {\n return join(\n this.dir,\n `repeat-${canonicalHash({ sessionId, root, tool, native: repeatKey(native) })}.json`,\n );\n }\n private async locked<T>(fn: () => Promise<T>) {\n await mkdir(this.dir, { recursive: true, mode: 0o700 });\n return modelLock(join(this.dir, 'lock'), fn);\n }\n private async read(id: string) {\n const raw = await readJsonFile(this.path(id), 1_000_000);\n const p = jobSchema.safeParse(raw);\n return p.success ? p.data : null;\n }\n /** Every held call is its own job, whatever else its session has open or running. */\n async offer(input: NewJob, state: 'routing' | 'offered' = 'offered'): Promise<ModelJob> {\n return this.locked(async () => {\n const index = this.callPath(input.sessionId, input.callId);\n const previous = await readJsonFile(index, 1000);\n const old = typeof previous?.id === 'string' ? await this.read(previous.id) : null;\n if (old && unresolved(old)) {\n // The same call seen twice is one job: no second route, no second fee.\n if (\n old.callId === input.callId &&\n canonicalHash(old.native) === canonicalHash(input.native)\n )\n return old;\n throw new Error('This call id already names another unresolved delegation');\n }\n const job: ModelJob = {\n ...input,\n id: randomUUID(),\n state,\n expiresAt: Date.now() + OFFER_MS,\n };\n const serialized = JSON.stringify(job);\n if (Buffer.byteLength(serialized) > 1_000_000)\n throw new Error('Complete model assignment exceeds private record size limit');\n await writePrivate(this.path(job.id), serialized);\n await writePrivate(index, JSON.stringify({ id: job.id }));\n if (input.nativeTool) {\n const path = this.repeatPath(input.sessionId, input.root, input.nativeTool, input.native);\n const ids = [...(await this.repeatIds(path)), job.id].slice(-REPEATS_KEPT);\n await writePrivate(path, JSON.stringify({ ids }));\n }\n return job;\n });\n }\n /**\n * A job by its own id, in any turn and from any process, for the session\n * that owns it. Another session gets nothing, as for an id that never was.\n */\n async owned(id: string, session: string): Promise<ModelJob | null> {\n if (!z.uuid().safeParse(id).success) return null;\n const job = await this.read(id);\n return job?.sessionId === session ? job : null;\n }\n /** Fences one job by its own id, for its session: nothing else of the session is touched. */\n async fenceOwned(\n id: string,\n session: string,\n state: 'cancelling' | 'cancelled' = 'cancelled',\n ): Promise<void> {\n return this.locked(async () => this.fenced(await this.owned(id, session), state));\n }\n private async fenced(job: ModelJob | null, state: 'cancelling' | 'cancelled') {\n if (!job || ['native', 'completed', 'cancelled', 'unknown'].includes(job.state)) return;\n await writePrivate(this.path(job.id), JSON.stringify({ ...job, state }));\n }\n async decided(id: string, decision: Record<string, unknown>) {\n return this.locked(async () => {\n const job = await this.read(id);\n if (!job || job.state !== 'routing') return;\n await writePrivate(\n this.path(id),\n JSON.stringify({\n ...job,\n decision,\n state: decision.action === 'model' ? 'offered' : 'native',\n }),\n );\n });\n }\n /** Every record still `running` or `cancelling`, whichever session owns it. Never throws. */\n async unfinished(): Promise<ModelJob[]> {\n const found: ModelJob[] = [];\n try {\n let seen = 0;\n for await (const entry of await opendir(this.dir)) {\n if (++seen > 50_000) break;\n const id = /^(.+)\\.json$/.exec(entry.name)?.[1];\n if (!entry.isFile() || !id || !z.uuid().safeParse(id).success) continue;\n const job = await this.read(id);\n if (job && ['running', 'cancelling'].includes(job.state)) found.push(job);\n }\n } catch {\n // No store yet, or not readable: nothing to repair.\n }\n return found;\n }\n /** The runner lock of a job: `<id>.runner.held` in the store. */\n private runnerPath(id: string) {\n if (!z.uuid().safeParse(id).success) throw new Error('Invalid model job');\n return join(this.dir, `${id}.runner`);\n }\n /**\n * Takes the job's runner lock, which the process that accepts the job holds from BEFORE\n * {@link accept} until after the job's last `finish`: a runner is alive exactly while its\n * lock is held, in any process, pid namespace or platform, and no pid is consulted. Waits up\n * to 5 s (a second accept of the same offer), then throws LockTimeoutError. Release it when\n * accept returns null.\n */\n async holdRunner(id: string): Promise<() => void> {\n const path = this.runnerPath(id);\n await mkdir(this.dir, { recursive: true, mode: 0o700 });\n return holdLock(path);\n }\n /** Once, on disk. The offer is accepted from any turn of its session. */\n async accept(id: string, session: string): Promise<ModelJob | null> {\n return this.locked(async () => {\n const job = await this.read(id);\n if (\n !job ||\n job.sessionId !== session ||\n job.expiresAt <= Date.now() ||\n job.state !== 'offered'\n )\n return null;\n job.state = 'running';\n job.runner = { pid: process.pid, acceptedAt: Date.now() };\n await writePrivate(this.path(id), JSON.stringify(job));\n return job;\n });\n }\n /**\n * Ends a record whose runner is gone: no process holds its runner lock, so the process that\n * accepted it has ended (or never held it). The record becomes `unknown` and is returned. Null\n * while a runner holds the lock, in this process or another. The probe is one attempt and\n * holds the lock while the record is rewritten, so no runner can start under it. The lock\n * order is runner, then job, as in `accept`.\n */\n async strand(id: string): Promise<ModelJob | null> {\n const first = await this.read(id);\n if (!first || !['running', 'cancelling'].includes(first.state)) return first;\n await mkdir(this.dir, { recursive: true, mode: 0o700 });\n let release: () => void;\n try {\n release = await holdLock(this.runnerPath(id), { timeoutMs: 0 });\n } catch (error) {\n if (error instanceof LockTimeoutError) return null;\n throw error;\n }\n try {\n return await this.locked(async () => {\n const job = await this.read(id);\n if (!job || !['running', 'cancelling'].includes(job.state)) return job;\n const ended: ModelJob = {\n ...job,\n state: 'unknown',\n expiresAt: Math.max(job.expiresAt, Date.now() + OFFER_MS),\n result: JSON.stringify(STRANDED_HANDBACK),\n };\n await writePrivate(this.path(id), JSON.stringify(ended));\n return ended;\n });\n } finally {\n release();\n }\n }\n /**\n * Claude: the parent keeps an offered call native by sending it again\n * unchanged. Matched by content, never by call ID, so the host's permission\n * review sees the call that runs. Once per offer: a match ends the offer, so\n * it cannot be accepted after, and a later repeat is a new call. It matches\n * in the same session, workspace root and agent loop (`caller`, the native\n * subagent that made the offered call, or none for the main loop) until the\n * offer expires, or for the same time after its accepted worker stopped. No\n * turn boundary is read.\n *\n * Several open offers can hold the same content. One repeat settles one of\n * them, the oldest first. A call made by the same model request (`step`) as\n * an offered call was written before that offer was read: it is a second\n * call, not its repeat, and is judged by itself.\n *\n * @returns the offer the repeat settled, else null.\n */\n async nativeRepeat(\n session: string,\n root: string,\n tool: 'Agent' | 'Task',\n native: Record<string, unknown>,\n step?: string,\n caller?: string,\n ): Promise<string | null> {\n return this.locked(async () => {\n for (const id of await this.repeatIds(this.repeatPath(session, root, tool, native))) {\n const job = await this.read(id);\n if (\n !job ||\n job.sessionId !== session ||\n job.root !== root ||\n job.nativeTool !== tool ||\n !REPEATABLE.includes(job.state) ||\n job.expiresAt <= Date.now() ||\n // An offer is kept native by the loop it was made to, not by another's same call.\n job.caller !== caller ||\n (step !== undefined && job.step === step) ||\n canonicalHash(repeatKey(job.native)) !== canonicalHash(repeatKey(native))\n )\n continue;\n await writePrivate(this.path(job.id), JSON.stringify({ ...job, state: 'native' }));\n return job.id;\n }\n return null;\n });\n }\n async finish(id: string, state: 'completed' | 'cancelled' | 'unknown', result?: string) {\n return this.locked(async () => {\n const job = await this.read(id);\n if (!job || !['running', 'cancelling'].includes(job.state)) return;\n await writePrivate(\n this.path(id),\n JSON.stringify({\n ...job,\n state,\n // A worker that stopped leaves its call a free native repeat, from now.\n ...(state === 'completed'\n ? {}\n : { expiresAt: Math.max(job.expiresAt, Date.now() + OFFER_MS) }),\n ...(result ? { result } : {}),\n }),\n );\n });\n }\n /** Records why a call got no offer, newest last, in one bounded private file. Never throws. */\n async noOffer(entry: Omit<NoOffer, 'at'>): Promise<void> {\n try {\n const parsed = noOfferSchema.safeParse({ ...entry, at: Date.now() });\n if (!parsed.success) return;\n await this.locked(async () => {\n const kept = (await this.noOffers()).filter(\n (old) => parsed.data.at - old.at < MODEL_RECORD_TTL_MS,\n );\n await writePrivate(\n join(this.dir, NO_OFFERS_FILE),\n JSON.stringify({ records: [...kept, parsed.data].slice(-NO_OFFERS_KEPT) }),\n );\n });\n } catch {\n // Diagnostics only: a failed write never changes what the call does.\n }\n }\n /** The kept no-offer records, oldest first. */\n async noOffers(): Promise<NoOffer[]> {\n const raw = await readJsonFile(join(this.dir, NO_OFFERS_FILE), 200_000).catch(() => null);\n return Array.isArray(raw?.records)\n ? raw.records.flatMap((entry) => {\n const parsed = noOfferSchema.safeParse(entry);\n return parsed.success ? [parsed.data] : [];\n })\n : [];\n }\n}\n","import { stable } from '../lib/request-schema';\n\nexport type WorkerStop = {\n kind: 'harness_limit' | 'provider_limit' | 'execution_failure' | 'not_started';\n reason:\n | 'startup_timeout'\n | 'turn_guard'\n | 'budget_guard'\n | 'structured_output_guard'\n | 'output_limit'\n | 'context_limit'\n | 'model_call_failed'\n | 'model_call_timeout'\n | 'payment_refused'\n | 'provider_failed'\n | 'worker_execution';\n turns?: number;\n /** The router's HTTP status, when a model call got an answer that was not a result. */\n status?: number;\n /** The payer's own code for a paid call it could not complete, such as `payment_failed`. */\n payer?: string;\n /** The router's fixed error code for that answer, such as `invalid_model_request`. */\n code?: string;\n};\n\n/**\n * A MODEL CALL THROUGH THE ROUTER THAT RETURNED NO RESULT, with what can be told about\n * why: it timed out, the router answered with another status, the job's ceiling or the\n * payer refused it, or it failed otherwise. The message stays the transport's own; the\n * detail is fixed codes only, so it can reach the parent and the stored handback.\n */\nexport class ModelCallFailed extends Error {\n constructor(\n message: string,\n readonly detail: {\n cause: 'failed' | 'timeout' | 'budget' | 'payment_refused' | 'provider';\n status?: number;\n payer?: string;\n /** The router confirms nothing was charged: no payment was sent, or its record\n * says the failed call cost nothing and its reservation was released. */\n uncharged?: true;\n /** The router's `Retry-After`, in milliseconds, when it sent one. */\n retryAfterMs?: number;\n /** The router's fixed error code (`{error: {code}}`), never its message. */\n code?: string;\n /** Provider events of a streamed reply had already reached the worker's child: the\n * call is never tried again as if nothing happened. */\n relayed?: true;\n },\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'ModelCallFailed';\n }\n}\n\n/**\n * A MODEL CALL TRIED AGAIN, as the DeepSeek harness tries one: up to 5 retries after the\n * first try (6 tries), 500 ms doubling to 10 s with 0.1 jitter, or the router's\n * `Retry-After`. Only a call the router confirms cost nothing, and only for a rate limit,\n * a server or provider error, a timeout or a call that never reached it. Never an\n * uncertain or a charged call, never a request the bridge or the router refused as\n * malformed, never a reply the provider refused to give.\n */\nexport const MODEL_RETRY = { tries: 6, baseMs: 500, maxMs: 10_000, jitter: 0.1, hintMs: 60_000 };\n/**\n * The router's code for a reply the provider refused to give (a `refusal` stop). The\n * DeepSeek harness fails such a turn at once (`CONTENT_REFUSED`, outside its retried\n * codes): the same request would be refused again. A router that names no refusal answers\n * one as `incomplete_model_response`, which cannot be told from an empty reply and is\n * tried again with it.\n */\nexport const MODEL_REFUSED_CODE = 'model_refused';\n/**\n * The router's codes for a reply it cut: no byte from the provider for its idle limit, or\n * the call's total deadline. Its record of such a call always reads `state: \"unknown\"`,\n * the name of its failed state, so that alone says nothing of a charge: the transport\n * calls a cut reply uncharged only on a cancelled voucher together with a zero charge\n * (`cutCostNothing`). So proven, it is tried again as the DeepSeek harness tries a\n * timeout; any other record, or none, leaves it uncertain and never tried again.\n */\nexport const MODEL_CUT_REPLY_CODES: ReadonlySet<string> = new Set([\n 'model_stream_idle',\n 'model_deadline_exceeded',\n]);\nexport function retryableModelCall(error: unknown): error is ModelCallFailed {\n if (!(error instanceof ModelCallFailed) || error.detail.uncharged !== true) return false;\n // Events already reached the child: a new try would repeat what it has seen.\n if (error.detail.relayed === true) return false;\n const { cause, status, code } = error.detail;\n if (code === MODEL_REFUSED_CODE) return false;\n if (cause === 'provider' || cause === 'timeout') return true;\n return cause === 'failed' && (status === undefined || status === 429 || status >= 500);\n}\nexport async function withModelRetry<T>(\n call: () => Promise<T>,\n signal: AbortSignal,\n onRetry: (attempt: number, error: ModelCallFailed) => void,\n wait: (ms: number, signal: AbortSignal) => Promise<void> = sleepFor,\n random: () => number = Math.random,\n): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await call();\n } catch (error) {\n if (attempt >= MODEL_RETRY.tries || signal.aborted || !retryableModelCall(error)) throw error;\n const hint = error.detail.retryAfterMs;\n const backoff = Math.min(MODEL_RETRY.maxMs, MODEL_RETRY.baseMs * 2 ** (attempt - 1));\n const ms =\n hint !== undefined\n ? Math.min(hint, MODEL_RETRY.hintMs)\n : Math.round(backoff * (1 + MODEL_RETRY.jitter * (2 * random() - 1)));\n onRetry(attempt, error);\n await wait(ms, signal);\n }\n }\n}\nexport function sleepFor(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(signal.reason);\n const timer = setTimeout(resolve, ms);\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n { once: true },\n );\n });\n}\n/** A `Retry-After` header in milliseconds: seconds or an HTTP date; undefined otherwise. */\nexport function retryAfterMs(header: string | null, now = Date.now()): number | undefined {\n if (!header) return undefined;\n const seconds = Number(header);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);\n const at = Date.parse(header);\n return Number.isNaN(at) ? undefined : Math.max(0, at - now);\n}\n\n/** Whether a failure, or one of its causes, is a timer's abort (`AbortSignal.timeout`). */\nexport function timedOut(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; depth < 4 && typeof current === 'object' && current !== null; depth++) {\n const value = current as { name?: unknown; cause?: unknown };\n if (value.name === 'TimeoutError') return true;\n current = value.cause;\n }\n return false;\n}\n\n/** The worker's stop for a model call that failed, else the error as it was. */\nexport function modelCallStop(error: unknown): unknown {\n if (!(error instanceof ModelCallFailed)) return error;\n const { cause, status, payer, code } = error.detail;\n return new ModelWorkerStopped({\n kind: cause === 'budget' ? 'harness_limit' : 'execution_failure',\n reason:\n cause === 'budget'\n ? 'budget_guard'\n : cause === 'timeout'\n ? 'model_call_timeout'\n : cause === 'payment_refused'\n ? 'payment_refused'\n : cause === 'provider'\n ? 'provider_failed'\n : 'model_call_failed',\n ...(status !== undefined && Number.isInteger(status) && status >= 100 && status <= 599\n ? { status }\n : {}),\n ...(payer !== undefined && /^[a-z][a-z_]{0,47}$/.test(payer) ? { payer } : {}),\n ...(code !== undefined && /^[a-z][a-z0-9_]{0,63}$/.test(code) ? { code } : {}),\n });\n}\n\n/** Only bounded machine-readable diagnostics cross the worker boundary. */\nexport class ModelWorkerStopped extends Error {\n constructor(\n readonly stop: WorkerStop,\n options?: ErrorOptions,\n ) {\n super(`Worker stopped: ${stop.reason}`, options);\n this.name = 'ModelWorkerStopped';\n }\n}\n\n/**\n * Who or what ended a worker that did not end by itself, as one fixed code and\n * the plain words the parent reads beside it. A native subagent's result says\n * why it stopped too; a job once read `cancelled` with nothing to tell by what.\n */\nexport const WORKER_ENDS = {\n parent_cancel: 'The parent cancelled it with subagent({cancel}).',\n agent_stopped: \"The person stopped the worker's agent.\",\n host_aborted: 'The host ended the call that was running it.',\n session_ended: 'Its session or its Tenjin process ended.',\n turn_limit: \"It reached the job's turn limit.\",\n budget: 'It reached its spending limit.',\n output_limit: \"It reached the model's output limit.\",\n context_limit: \"It reached the model's context limit.\",\n not_started: 'Its Claude Code did not start.',\n model_call_failed:\n 'Its model call through Tenjin returned no result; that call stays reserved until its receipt is read.',\n model_call_timeout:\n 'Its model call through Tenjin timed out; that call stays reserved until its receipt is read.',\n payment_refused: 'Tenjin refused to pay for its next model call, and sent nothing for it.',\n provider: 'DeepSeek could not take its next request, and nothing was charged for that call.',\n refused: 'DeepSeek refused to answer this request, and nothing was charged for that call.',\n worker_error: 'The worker or the provider failed.',\n} as const;\nexport type WorkerEnd = keyof typeof WORKER_ENDS;\n\n/** The end code of a worker that stopped without an abort, from its stop reason. */\nexport function workerEnd(stop: WorkerStop | undefined): WorkerEnd {\n switch (stop?.reason) {\n case 'turn_guard':\n return 'turn_limit';\n case 'budget_guard':\n return 'budget';\n case 'output_limit':\n case 'context_limit':\n case 'model_call_failed':\n case 'model_call_timeout':\n case 'payment_refused':\n return stop.reason;\n case 'provider_failed':\n // A refusal is its own end: the parent and the person read why, not a bare\n // provider failure. It is still never tried again (`retryableModelCall`).\n return stop.code === MODEL_REFUSED_CODE ? 'refused' : 'provider';\n case 'startup_timeout':\n return 'not_started';\n default:\n return 'worker_error';\n }\n}\n\nexport function workerStop(error: unknown): WorkerStop | undefined {\n return error instanceof ModelWorkerStopped ? error.stop : undefined;\n}\n\nexport function workerResultError(result: {\n subtype: string;\n num_turns?: number;\n stop_reason?: string | null;\n}): ModelWorkerStopped {\n const turns =\n Number.isSafeInteger(result.num_turns) &&\n result.num_turns! >= 0 &&\n result.num_turns! <= 1_000_000\n ? result.num_turns\n : undefined;\n let stop: WorkerStop;\n switch (result.subtype) {\n case 'error_max_turns':\n stop = { kind: 'harness_limit', reason: 'turn_guard' };\n break;\n case 'error_max_budget_usd':\n stop = { kind: 'harness_limit', reason: 'budget_guard' };\n break;\n case 'error_max_structured_output_retries':\n stop = { kind: 'harness_limit', reason: 'structured_output_guard' };\n break;\n default:\n stop =\n result.stop_reason === 'max_tokens' || result.stop_reason === 'max_output_tokens'\n ? { kind: 'provider_limit', reason: 'output_limit' }\n : result.stop_reason === 'prompt_too_long'\n ? { kind: 'provider_limit', reason: 'context_limit' }\n : { kind: 'execution_failure', reason: 'worker_execution' };\n }\n return new ModelWorkerStopped({ ...stop, ...(turns === undefined ? {} : { turns }) });\n}\n\n/**\n * THE REPEAT REMINDER OF THE DEEPSEEK HARNESS (its `repeat-tool-reminder` guard, as\n * shipped): the same tool with the same arguments, key order aside, 3, 5 and 8 times in a\n * row. Advisory only: no call is blocked, delayed or changed. Every call the model makes\n * counts, also one that is then denied, and no tool is left out: the harness ships with\n * an empty exclude list, so a to-do list update counts and breaks a run of repeats as any\n * other call does. Past 8 a run is silent. The two texts are the harness's own: the\n * gentle one at the first count, then the detailed one with the tool, the run's length\n * and the first 500 characters of the arguments.\n */\nconst REPEAT_COUNTS = [3, 5, 8];\nconst REPEAT_ARGUMENT_CHARS = 500;\nconst GENTLE_REPEAT_REMINDER =\n 'You are repeating the exact same tool call with identical arguments. ' +\n 'Carefully analyze the previous result before calling again: if the task is ' +\n 'not complete, try a different approach or different arguments instead of ' +\n 'repeating the call.';\nfunction detailedRepeatReminder(tool: string, count: number, canonical: string): string {\n const shown =\n canonical.length <= REPEAT_ARGUMENT_CHARS\n ? canonical\n : `${canonical.slice(0, REPEAT_ARGUMENT_CHARS)}… (+${canonical.length - REPEAT_ARGUMENT_CHARS} more chars)`;\n return (\n 'Repeated tool call detected:\\n' +\n `- tool: ${tool}\\n` +\n `- consecutive_calls: ${count}\\n` +\n `- arguments: ${shown}\\n` +\n 'The repeated calls are not making progress. Do not call this tool with ' +\n 'these exact arguments again. Inspect the latest result and choose a ' +\n 'different action, different arguments, or finish the task if enough ' +\n 'evidence has been gathered.'\n );\n}\nexport class WorkerRepeatReminder {\n private previous: string | undefined;\n private count = 0;\n\n /** One call the model made: the reminder to hand it at a count of 3, 5 or 8. */\n observe(tool: string, input: unknown): { count: number; text: string } | undefined {\n let canonical: string;\n try {\n canonical = stable(input);\n } catch {\n this.previous = undefined;\n this.count = 0;\n return;\n }\n const identity = JSON.stringify([tool, canonical]);\n this.count = identity === this.previous ? this.count + 1 : 1;\n this.previous = identity;\n if (!REPEAT_COUNTS.includes(this.count)) return;\n return {\n count: this.count,\n text:\n this.count === REPEAT_COUNTS[0]\n ? GENTLE_REPEAT_REMINDER\n : detailedRepeatReminder(tool, this.count, canonical),\n };\n }\n}\n","import { constants } from 'node:fs';\nimport { access, lstat, realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { win32 } from 'node:path';\nimport { z } from 'zod';\nimport { loadRawConfig } from '../lib/config';\nimport {\n defaultDataDir,\n passphraseRecordPath,\n realOr,\n spendLedgerPath,\n walletPath,\n} from '../lib/paths';\nimport { modelConsentSchema } from './model-settings';\n\nconst localPath = z\n .string()\n .regex(/^[A-Za-z]:[\\\\/][^:\"<>|?*]+$/)\n .refine((path) => Array.from(path).every((character) => character.charCodeAt(0) >= 32));\nconst executablePath = localPath.refine((path) => win32.extname(path).toLowerCase() === '.exe');\nconst configSchema = z.strictObject({\n version: z.literal(1),\n workerSid: z.string().regex(/^S-1-5-21-(?:\\d{1,10}-){3}\\d{1,10}$/),\n launcherPath: executablePath,\n claudePath: executablePath,\n configDir: localPath,\n routerOrigin: z.url().refine((url) => URL.canParse(url) && new URL(url).origin === url),\n shellAccess: z.literal('native-windows'),\n});\nexport type WindowsWorkerConfig = z.infer<typeof configSchema>;\n\nfunction within(root: string, path: string): boolean {\n const relative = win32.relative(root, path);\n return (\n relative === '' ||\n (relative !== '..' && !relative.startsWith('..\\\\') && !win32.isAbsolute(relative))\n );\n}\n\n/** Resolves setup paths under the controller's authority. The launcher checks the worker account. */\nexport async function validateWindowsWorkerConfig(\n input: unknown,\n dataDir: string,\n): Promise<WindowsWorkerConfig | null> {\n if (process.platform !== 'win32') return null;\n const parsed = configSchema.safeParse(input);\n if (!parsed.success) return null;\n const { launcherPath, claudePath, configDir } = parsed.data;\n try {\n const [launcherExe, claudeExe, profile, controllerData, defaultData, controllerProfile] =\n await Promise.all([\n realpath(launcherPath),\n realpath(claudePath),\n realpath(configDir),\n realOr(dataDir),\n realOr(defaultDataDir()),\n realOr(win32.join(homedir(), '.claude')),\n ]);\n const canonical = configSchema.safeParse({\n ...parsed.data,\n launcherPath: launcherExe,\n claudePath: claudeExe,\n configDir: profile,\n });\n if (!canonical.success || win32.relative(launcherExe, claudeExe) === '') return null;\n for (const privateDir of [controllerData, defaultData, controllerProfile]) {\n if (\n within(privateDir, profile) ||\n within(profile, privateDir) ||\n within(privateDir, launcherExe) ||\n within(privateDir, claudeExe)\n )\n return null;\n }\n const [launcherStat, claudeStat, profileStat] = await Promise.all([\n stat(launcherExe),\n stat(claudeExe),\n stat(profile),\n ]);\n if (!launcherStat.isFile() || !claudeStat.isFile() || !profileStat.isDirectory()) return null;\n await Promise.all(\n [launcherExe, claudeExe, profile].map((path) => access(path, constants.R_OK)),\n );\n for (const privateFile of [\n win32.join(profile, '.credentials.json'),\n walletPath(profile),\n spendLedgerPath(profile),\n passphraseRecordPath(profile),\n ]) {\n const exists = await lstat(privateFile).then(\n () => true,\n (error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return false;\n throw error;\n },\n );\n if (exists) return null;\n }\n return canonical.data;\n } catch {\n return null;\n }\n}\n\n/** Read only user config. A saved path that now resolves elsewhere loses its grant. */\nexport async function loadWindowsWorkerConfig(\n dataDir: string,\n): Promise<WindowsWorkerConfig | null> {\n if (process.platform !== 'win32') return null;\n const router = (await loadRawConfig(dataDir).catch(() => null))?.router;\n if (router?.subagents !== true) return null;\n const record = configSchema.safeParse(router.windowsWorker);\n const consent = modelConsentSchema.safeParse(router.subagentConsent);\n if (!record.success || !consent.success || consent.data.routerOrigin !== record.data.routerOrigin)\n return null;\n const config = await validateWindowsWorkerConfig(record.data, dataDir);\n if (\n !config ||\n win32.relative(config.launcherPath, record.data.launcherPath) !== '' ||\n win32.relative(config.claudePath, record.data.claudePath) !== '' ||\n win32.relative(config.configDir, record.data.configDir) !== ''\n )\n return null;\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,OAAO,eAAe;AACtC,SAAS,YAAY;;;AC6Bd,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACS,QAeT,SACA;AACA,UAAM,SAAS,OAAO;AAjBb;AAkBT,SAAK,OAAO;AAAA,EACd;AAAA,EAnBW;AAoBb;AAUO,IAAM,cAAc,EAAE,OAAO,GAAG,QAAQ,KAAK,OAAO,KAAQ,QAAQ,KAAK,QAAQ,IAAO;AAQxF,IAAM,qBAAqB;AAS3B,IAAM,wBAA6C,oBAAI,IAAI;AAAA,EAChE;AAAA,EACA;AACF,CAAC;AACM,SAAS,mBAAmB,OA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UAAU,MAAM,cAAc,OAAO,EAAE,MAAM,MAAM,IAAI,IAAI;AACjE,MAAI,QAAQ,cAAc,KAAM,QAAO;AACvC,QAAM,SAAS,aAAa,UAAU,OAAO,aAAa;AAC1D,QAAM,UAAU,mBAAmB,UAAU,OAAO,eAAe;AACnE,MAAI,CAAC,OAAO,WAAW,CAAC,QAAQ,WAAW,QAAQ,KAAK,iBAAiB,OAAO,KAAK;AACnF,WAAO;AACT,QAAM,SAAS,MAAM,4BAA4B,OAAO,MAAM,OAAO;AACrE,MACE,CAAC,UACD,MAAM,SAAS,OAAO,cAAc,OAAO,KAAK,YAAY,MAAM,MAClE,MAAM,SAAS,OAAO,YAAY,OAAO,KAAK,UAAU,MAAM,MAC9D,MAAM,SAAS,OAAO,WAAW,OAAO,KAAK,SAAS,MAAM;AAE5D,WAAO;AACT,SAAO;AACT;","names":["lstat","lstat"]}
@@ -0,0 +1,83 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ hasCode
4
+ } from "./chunk-3MZ7DYRO.js";
5
+
6
+ // src/lib/flush-stdio.ts
7
+ var STDIO = { stdout: process.stdout, stderr: process.stderr };
8
+ var lost;
9
+ var paymentSent = false;
10
+ var guarded = /* @__PURE__ */ new WeakSet();
11
+ function notePaymentSent() {
12
+ paymentSent = true;
13
+ }
14
+ async function exitAfter(run, stdio = STDIO) {
15
+ guardStdio(stdio);
16
+ const code = await run();
17
+ await flushStdio(stdio);
18
+ process.exit(await exitCodeAfter(code, stdio));
19
+ }
20
+ function guardStdio(stdio = STDIO) {
21
+ for (const name of ["stdout", "stderr"]) {
22
+ const stream = stdio[name];
23
+ if (guarded.has(stream)) continue;
24
+ guarded.add(stream);
25
+ stream.on("error", (err) => noteWriteError(name, err));
26
+ }
27
+ }
28
+ function noteWriteError(stream, err) {
29
+ if (hasCode(err, "EPIPE")) return;
30
+ lost ??= { stream, err };
31
+ }
32
+ async function exitCodeAfter(code, stdio = STDIO) {
33
+ if (lost === void 0) return code;
34
+ if (lost.stream === "stdout") {
35
+ await report(stdio.stderr, lostOutputLine(lost.err));
36
+ }
37
+ return code !== 0 ? code : paymentSent ? 4 : 1;
38
+ }
39
+ function lostOutputLine(err) {
40
+ const why = err instanceof Error ? err.message : String(err);
41
+ return paymentSent ? `tenjin: the output could not be written (${why}) after a payment authorization was sent, so you may have been charged. Check \`tenjin payments\` before paying again.
42
+ ` : `tenjin: the output could not be written (${why}).
43
+ `;
44
+ }
45
+ async function report(stream, line) {
46
+ if (stream.destroyed || stream.writableEnded) return;
47
+ try {
48
+ stream.write(line);
49
+ } catch {
50
+ return;
51
+ }
52
+ await flushed(stream, "stderr");
53
+ }
54
+ async function flushStdio(stdio = STDIO) {
55
+ await Promise.all([flushed(stdio.stdout, "stdout"), flushed(stdio.stderr, "stderr")]);
56
+ }
57
+ function flushed(stream, name) {
58
+ return new Promise((resolve) => {
59
+ if (stream.destroyed || stream.writableEnded) {
60
+ resolve();
61
+ return;
62
+ }
63
+ const failed = (err) => {
64
+ if (!hasCode(err, "ERR_STREAM_DESTROYED")) noteWriteError(name, err);
65
+ resolve();
66
+ };
67
+ stream.once("error", failed);
68
+ try {
69
+ stream.write("", (err) => err ? failed(err) : resolve());
70
+ } catch (err) {
71
+ failed(err);
72
+ }
73
+ });
74
+ }
75
+
76
+ export {
77
+ notePaymentSent,
78
+ exitAfter,
79
+ guardStdio,
80
+ exitCodeAfter,
81
+ flushStdio
82
+ };
83
+ //# sourceMappingURL=chunk-C265QIMJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/flush-stdio.ts"],"sourcesContent":["import type { Writable } from 'node:stream';\nimport { hasCode } from './errno';\n\n/** The bin's two output streams. */\nexport interface Stdio {\n stdout: Writable;\n stderr: Writable;\n}\n\nconst STDIO: Stdio = { stdout: process.stdout, stderr: process.stderr };\n\n/** The first output error that was not a closed pipe, for this process. */\nlet lost: { stream: keyof Stdio; err: unknown } | undefined;\n/** A payment's authorization left this process ({@link notePaymentSent}). */\nlet paymentSent = false;\nconst guarded = new WeakSet<Writable>();\n\n/**\n * A payment's authorization left this process: an output failure after it\n * says the authorization was sent and may have charged, and points to\n * `tenjin payments` to check. `runPay` calls it once the paid leg is sent.\n */\nexport function notePaymentSent(): void {\n paymentSent = true;\n}\n\n/**\n * THE BIN'S LAST STEP, IN THIS ORDER: take stdio's errors, run the command,\n * drain what it printed, exit. A write to a pipe whose reader went away fails\n * a tick later, as an `error` event on the stream, and with no listener Node\n * crashes on it: exit 1 instead of the command's own code. The listeners go\n * on before the command runs, so no write it makes can crash the process,\n * however early its reader left; {@link flushStdio} then waits out what is\n * still queued.\n *\n * The command keeps its own code, unless output was lost: see\n * {@link exitCodeAfter}. The exit is explicit: a process left to end on its\n * own keeps `tenjin mcp` alive after SIGTERM while its stdin stays open.\n */\nexport async function exitAfter(run: () => Promise<number>, stdio: Stdio = STDIO): Promise<never> {\n guardStdio(stdio);\n const code = await run();\n await flushStdio(stdio);\n process.exit(await exitCodeAfter(code, stdio));\n}\n\n/**\n * A STREAM'S ERRORS, TAKEN for the rest of the process. A reader that went\n * away (EPIPE) leaves nothing to write to: never a crash, and never a\n * failure, so the command keeps its status. Any other error (a full disk, a\n * file at its size limit) lost output the reader needed, and is kept for\n * {@link exitCodeAfter}. Installed once per stream.\n */\nexport function guardStdio(stdio: Stdio = STDIO): void {\n for (const name of ['stdout', 'stderr'] as const) {\n const stream = stdio[name];\n if (guarded.has(stream)) continue;\n guarded.add(stream);\n stream.on('error', (err: unknown) => noteWriteError(name, err));\n }\n}\n\nfunction noteWriteError(stream: keyof Stdio, err: unknown): void {\n if (hasCode(err, 'EPIPE')) return;\n lost ??= { stream, err };\n}\n\n/**\n * THE EXIT CODE, ONCE OUTPUT IS DRAINED. With nothing lost, the command's\n * own. With output lost, it is said on stderr when stderr is not the stream\n * that failed, and the exit is nonzero: the command's own failing code, else\n * 4 after a payment (a failure after an approved spend) and 1 otherwise.\n * After a payment the line says the authorization was sent and may have\n * charged, so the reader checks `tenjin payments` before paying again. It\n * claims no charge and no saved record, since neither is known here.\n */\nexport async function exitCodeAfter(code: number, stdio: Stdio = STDIO): Promise<number> {\n if (lost === undefined) return code;\n if (lost.stream === 'stdout') {\n await report(stdio.stderr, lostOutputLine(lost.err));\n }\n return code !== 0 ? code : paymentSent ? 4 : 1;\n}\n\n/** The line said on stderr; a system error's message carries its code. */\nfunction lostOutputLine(err: unknown): string {\n const why = err instanceof Error ? err.message : String(err);\n return paymentSent\n ? `tenjin: the output could not be written (${why}) after a payment authorization was sent, so you may have been charged. Check \\`tenjin payments\\` before paying again.\\n`\n : `tenjin: the output could not be written (${why}).\\n`;\n}\n\nasync function report(stream: Writable, line: string): Promise<void> {\n if (stream.destroyed || stream.writableEnded) return;\n try {\n stream.write(line);\n } catch {\n return;\n }\n await flushed(stream, 'stderr');\n}\n\n/**\n * EVERY BYTE WRITTEN, THEN EXIT. On a pipe Node writes stdout asynchronously,\n * and `process.exit` ends the process at once: whatever the reader had not\n * taken yet (past the pipe's 64 KB) was dropped, which cut printed `tenjin\n * pay` bodies off at 426 KB and 557 KB. An empty write's callback runs only\n * after every write queued before it has gone to the OS, so waiting on it on\n * each stream loses nothing. A stream already closed has nothing left to wait\n * for. A write that fails while it drains is judged as {@link guardStdio}\n * judges one: a reader that went away is taken, and any other error is kept,\n * so it fails the exit too. An error before this runs is the guard's to take:\n * the bin installs it before the command.\n *\n * It waits as long as the reader takes, as a process that ends on its own\n * would: a reader that never reads holds the exit.\n */\nexport async function flushStdio(stdio: Stdio = STDIO): Promise<void> {\n await Promise.all([flushed(stdio.stdout, 'stdout'), flushed(stdio.stderr, 'stderr')]);\n}\n\nfunction flushed(stream: Writable, name: keyof Stdio): Promise<void> {\n return new Promise((resolve) => {\n if (stream.destroyed || stream.writableEnded) {\n resolve();\n return;\n }\n const failed = (err: unknown): void => {\n // A stream destroyed under a queued write fails that write with\n // ERR_STREAM_DESTROYED; its cause came as the stream's own error event.\n if (!hasCode(err, 'ERR_STREAM_DESTROYED')) noteWriteError(name, err);\n resolve();\n };\n stream.once('error', failed);\n try {\n stream.write('', (err?: Error | null) => (err ? failed(err) : resolve()));\n } catch (err) {\n failed(err);\n }\n });\n}\n"],"mappings":";;;;;;AASA,IAAM,QAAe,EAAE,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,OAAO;AAGtE,IAAI;AAEJ,IAAI,cAAc;AAClB,IAAM,UAAU,oBAAI,QAAkB;AAO/B,SAAS,kBAAwB;AACtC,gBAAc;AAChB;AAeA,eAAsB,UAAU,KAA4B,QAAe,OAAuB;AAChG,aAAW,KAAK;AAChB,QAAM,OAAO,MAAM,IAAI;AACvB,QAAM,WAAW,KAAK;AACtB,UAAQ,KAAK,MAAM,cAAc,MAAM,KAAK,CAAC;AAC/C;AASO,SAAS,WAAW,QAAe,OAAa;AACrD,aAAW,QAAQ,CAAC,UAAU,QAAQ,GAAY;AAChD,UAAM,SAAS,MAAM,IAAI;AACzB,QAAI,QAAQ,IAAI,MAAM,EAAG;AACzB,YAAQ,IAAI,MAAM;AAClB,WAAO,GAAG,SAAS,CAAC,QAAiB,eAAe,MAAM,GAAG,CAAC;AAAA,EAChE;AACF;AAEA,SAAS,eAAe,QAAqB,KAAoB;AAC/D,MAAI,QAAQ,KAAK,OAAO,EAAG;AAC3B,WAAS,EAAE,QAAQ,IAAI;AACzB;AAWA,eAAsB,cAAc,MAAc,QAAe,OAAwB;AACvF,MAAI,SAAS,OAAW,QAAO;AAC/B,MAAI,KAAK,WAAW,UAAU;AAC5B,UAAM,OAAO,MAAM,QAAQ,eAAe,KAAK,GAAG,CAAC;AAAA,EACrD;AACA,SAAO,SAAS,IAAI,OAAO,cAAc,IAAI;AAC/C;AAGA,SAAS,eAAe,KAAsB;AAC5C,QAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,SAAO,cACH,4CAA4C,GAAG;AAAA,IAC/C,4CAA4C,GAAG;AAAA;AACrD;AAEA,eAAe,OAAO,QAAkB,MAA6B;AACnE,MAAI,OAAO,aAAa,OAAO,cAAe;AAC9C,MAAI;AACF,WAAO,MAAM,IAAI;AAAA,EACnB,QAAQ;AACN;AAAA,EACF;AACA,QAAM,QAAQ,QAAQ,QAAQ;AAChC;AAiBA,eAAsB,WAAW,QAAe,OAAsB;AACpE,QAAM,QAAQ,IAAI,CAAC,QAAQ,MAAM,QAAQ,QAAQ,GAAG,QAAQ,MAAM,QAAQ,QAAQ,CAAC,CAAC;AACtF;AAEA,SAAS,QAAQ,QAAkB,MAAkC;AACnE,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI,OAAO,aAAa,OAAO,eAAe;AAC5C,cAAQ;AACR;AAAA,IACF;AACA,UAAM,SAAS,CAAC,QAAuB;AAGrC,UAAI,CAAC,QAAQ,KAAK,sBAAsB,EAAG,gBAAe,MAAM,GAAG;AACnE,cAAQ;AAAA,IACV;AACA,WAAO,KAAK,SAAS,MAAM;AAC3B,QAAI;AACF,aAAO,MAAM,IAAI,CAAC,QAAwB,MAAM,OAAO,GAAG,IAAI,QAAQ,CAAE;AAAA,IAC1E,SAAS,KAAK;AACZ,aAAO,GAAG;AAAA,IACZ;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -20,4 +20,4 @@ export {
20
20
  isSameDeployment,
21
21
  knownDeploymentOrigins
22
22
  };
23
- //# sourceMappingURL=chunk-XQJXNMSB.js.map
23
+ //# sourceMappingURL=chunk-CRG54LEB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/production-origin.ts"],"sourcesContent":["/**\n * The one place the production Tenjin origin is written down. Every shipped\n * default, fallback, identity string, and piece of operator copy that names the\n * live site derives from here; `production-origin.test.ts` checks the config\n * default, the User-Agent and the package homepage against it.\n *\n * This is NOT the base URL a command talks to. Ordinary requests resolve\n * `baseUrl` through config/flag/env precedence (`CONFIG_DEFAULTS.baseUrl` merely\n * starts from this value); `fund` alone pins production with no override surface\n * at all (owner decision, 2026-08-12) because its mint signs with the wallet key.\n * `fund.test.ts` and `client-meta.test.ts` each hold their own written-out copy,\n * so flipping this line alone reds the suite instead of moving the money path.\n */\nexport const PRODUCTION_ORIGIN = 'https://tenjin.sh';\n\n/**\n * The bare host, for prose and messages that name the site rather than link to\n * it. Derived, not written twice: a flip cannot leave the two disagreeing.\n */\nexport const PRODUCTION_HOST = new URL(PRODUCTION_ORIGIN).host;\n\n/**\n * Every origin the ONE production deployment answers on, as `URL.origin` spells\n * it. Membership means a request to any of them reaches the same server,\n * publishers, prices, and SIWX domain acceptance. It exists because the server\n * builds candidate URLs from its own `NEXT_PUBLIC_APP_URL`, not the request\n * host, so when that global names one origin a CLI on the other would see\n * every candidate as off-origin.\n *\n * Membership is NOT trust and NOT an allowlist of places the CLI may pay, but it\n * IS the widest set a wallet-signed credential can reach, so widening it is a\n * security change. Removal runbook: docs/safety-model.md.\n */\nconst KNOWN_DEPLOYMENT_ORIGINS: ReadonlySet<string> = new Set([\n PRODUCTION_ORIGIN,\n 'https://tenjin.blog',\n]);\n\n/**\n * Do these two origins name the same deployment? Exact match, or two members of\n * the set. BOTH sides must be members, so a self-hosted or preview base gains no\n * alias and keeps today's strict compare, and a differing scheme or port is a\n * different origin that aliases to nothing. Takes `URL.origin` strings; anything\n * else is not a member and falls through to the exact compare.\n */\nexport function isSameDeployment(a: string, b: string): boolean {\n if (a === b) return true;\n return KNOWN_DEPLOYMENT_ORIGINS.has(a) && KNOWN_DEPLOYMENT_ORIGINS.has(b);\n}\n\n/** The set as a plain array, for the generated hook script that cannot import. */\nexport function knownDeploymentOrigins(): string[] {\n return [...KNOWN_DEPLOYMENT_ORIGINS];\n}\n"],"mappings":";;;AAaO,IAAM,oBAAoB;AAM1B,IAAM,kBAAkB,IAAI,IAAI,iBAAiB,EAAE;AAc1D,IAAM,2BAAgD,oBAAI,IAAI;AAAA,EAC5D;AAAA,EACA;AACF,CAAC;AASM,SAAS,iBAAiB,GAAW,GAAoB;AAC9D,MAAI,MAAM,EAAG,QAAO;AACpB,SAAO,yBAAyB,IAAI,CAAC,KAAK,yBAAyB,IAAI,CAAC;AAC1E;AAGO,SAAS,yBAAmC;AACjD,SAAO,CAAC,GAAG,wBAAwB;AACrC;","names":[]}
@@ -15,7 +15,7 @@ import {
15
15
  swap32IfBE,
16
16
  toBytes,
17
17
  u32
18
- } from "./chunk-BPMWXTFX.js";
18
+ } from "./chunk-WFZX352D.js";
19
19
 
20
20
  // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js
21
21
  var _0n = BigInt(0);
@@ -201,4 +201,4 @@ var keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
201
201
  export {
202
202
  keccak_256
203
203
  };
204
- //# sourceMappingURL=chunk-KG3D7FIF.js.map
204
+ //# sourceMappingURL=chunk-CZJOMUBP.js.map
@@ -1,35 +1,31 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- package_default
4
- } from "./chunk-RVPYTUP4.js";
5
2
  import {
6
3
  PRODUCTION_ORIGIN
7
- } from "./chunk-XQJXNMSB.js";
4
+ } from "./chunk-CRG54LEB.js";
8
5
  import {
9
6
  CliError
10
- } from "./chunk-3UCIG4TG.js";
7
+ } from "./chunk-DI4QAGRZ.js";
8
+ import {
9
+ package_default
10
+ } from "./chunk-3Y2EHT4F.js";
11
11
 
12
12
  // src/lib/client-meta.ts
13
13
  var TENJIN_PRODUCT = `tenjin-cli/${package_default.version}`;
14
14
  var TENJIN_PRODUCT_NAME = "tenjin-cli";
15
15
  var WEBSEARCH_HOOK_PRODUCT_NAME = "tenjin-websearch-hook";
16
- var WEBSEARCH_HOOK_PRODUCT = `${WEBSEARCH_HOOK_PRODUCT_NAME}/${package_default.version}`;
17
16
  var OWN_PRODUCT_NAMES = [TENJIN_PRODUCT_NAME, WEBSEARCH_HOOK_PRODUCT_NAME];
18
17
  var TENJIN_COMMENT = `(+${PRODUCTION_ORIGIN})`;
19
18
  var TENJIN_USER_AGENT = `${TENJIN_PRODUCT} ${TENJIN_COMMENT}`;
20
- var WEBSEARCH_HOOK_USER_AGENT = `${WEBSEARCH_HOOK_PRODUCT} ${TENJIN_COMMENT}`;
21
19
  var CALLER_USER_AGENT_ENV = "TENJIN_CALLER_USER_AGENT";
22
20
  var USER_AGENT_MAX_LENGTH = 512;
23
21
  var PRODUCT_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:\/[!#$%&'*+.^_`|~0-9A-Za-z-]+)?$/;
24
22
  var PRINTABLE_ASCII_RE = /^[\x20-\x7e]*$/;
25
23
  function composeUserAgent(input = {}) {
26
- const product = input.product ?? TENJIN_PRODUCT;
27
- const alone = `${product} ${TENJIN_COMMENT}`;
28
24
  const raw = input.caller ?? (input.env ?? process.env)[CALLER_USER_AGENT_ENV];
29
25
  const products = callerProducts(raw);
30
- if (products.length === 0) return alone;
31
- const composed = `${product} ${products.join(" ")} ${TENJIN_COMMENT}`;
32
- return composed.length <= USER_AGENT_MAX_LENGTH ? composed : alone;
26
+ if (products.length === 0) return TENJIN_USER_AGENT;
27
+ const composed = `${TENJIN_PRODUCT} ${products.join(" ")} ${TENJIN_COMMENT}`;
28
+ return composed.length <= USER_AGENT_MAX_LENGTH ? composed : TENJIN_USER_AGENT;
33
29
  }
34
30
  function callerProducts(raw) {
35
31
  if (raw === void 0 || !PRINTABLE_ASCII_RE.test(raw)) return [];
@@ -46,21 +42,7 @@ function isOwnIdentity(token) {
46
42
  }
47
43
 
48
44
  // src/lib/http.ts
49
- var SHELF_BYPASS_HEADER = "x-vercel-protection-bypass";
50
- function shelfBypassHeaders(url, bypass) {
51
- if (bypass === void 0 || bypass.secret.length === 0) return {};
52
- let origin;
53
- try {
54
- origin = new URL(url).origin;
55
- } catch {
56
- return {};
57
- }
58
- if (origin !== bypass.origin) return {};
59
- return { [SHELF_BYPASS_HEADER]: bypass.secret };
60
- }
61
- function carriesBypassKey(headers) {
62
- return Object.keys(headers).some((name) => name.toLowerCase() === SHELF_BYPASS_HEADER);
63
- }
45
+ var PROTECTION_BYPASS_HEADER = "x-vercel-protection-bypass";
64
46
  var INSTALL_ID_HEADER = "tenjin-install-id";
65
47
  var tenjinIdentity;
66
48
  function setTenjinIdentity(identity) {
@@ -92,7 +74,7 @@ function carriesSignedMaterial(headers) {
92
74
  }
93
75
  function isReservedRequestHeader(name) {
94
76
  const lowered = name.toLowerCase();
95
- return CREDENTIAL_HEADERS.has(lowered) || lowered === SHELF_BYPASS_HEADER || lowered === INSTALL_ID_HEADER || lowered.startsWith("payment-") || lowered.startsWith("x-payment");
77
+ return CREDENTIAL_HEADERS.has(lowered) || lowered === PROTECTION_BYPASS_HEADER || lowered === INSTALL_ID_HEADER || lowered.startsWith("payment-") || lowered.startsWith("x-payment");
96
78
  }
97
79
  var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
98
80
  var TRANSPORT_HEADERS = /* @__PURE__ */ new Set(["host", "content-length", "content-type", "user-agent"]);
@@ -114,6 +96,9 @@ function timeoutFailure(url, timeoutMs) {
114
96
  };
115
97
  }
116
98
  var MAX_BINARY_BODY_BYTES = 200 * 1024 * 1024;
99
+ function capText(bytes) {
100
+ return bytes >= 1048576 ? `${Math.round(bytes / 1048576)} MB` : `${bytes}-byte`;
101
+ }
117
102
  async function readCapped(res, max) {
118
103
  const declared = Number(res.headers.get("content-length") ?? "0");
119
104
  if (Number.isFinite(declared) && declared > max) {
@@ -145,7 +130,7 @@ function isBinaryContentType(contentType) {
145
130
  function prepareRequest(url, opts) {
146
131
  try {
147
132
  let body;
148
- const merged = new Headers({ ...opts.headers, ...shelfBypassHeaders(url, opts.bypass) });
133
+ const merged = new Headers(opts.headers ?? {});
149
134
  if (opts.jsonBody !== void 0) {
150
135
  body = JSON.stringify(opts.jsonBody);
151
136
  merged.set("content-type", "application/json");
@@ -156,14 +141,12 @@ function prepareRequest(url, opts) {
156
141
  if (wantsAccept && !merged.has("accept")) merged.set("accept", "application/json");
157
142
  const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());
158
143
  const signed = carriesSignedMaterial(headers);
159
- const bypassed = carriesBypassKey(headers);
160
144
  return {
161
145
  ok: true,
162
146
  headers,
163
147
  body,
164
148
  signed,
165
- bypassed,
166
- pinned: signed || bypassed || opts.blockRedirects === true
149
+ pinned: signed || opts.blockRedirects === true
167
150
  };
168
151
  } catch (err) {
169
152
  return {
@@ -181,18 +164,17 @@ async function httpRequest(url, opts) {
181
164
  timedOut = true;
182
165
  controller.abort();
183
166
  }, opts.timeoutMs);
184
- const signal = opts.signal === void 0 ? controller.signal : AbortSignal.any([controller.signal, opts.signal]);
185
167
  try {
186
168
  const prepared = prepareRequest(url, opts);
187
169
  if (!prepared.ok) return prepared;
188
- const { headers, body, signed, bypassed, pinned } = prepared;
170
+ const { headers, body, signed, pinned } = prepared;
189
171
  let res;
190
172
  try {
191
173
  res = await doFetch(url, {
192
174
  method: opts.method ?? "GET",
193
175
  headers: opts.anonymous === true ? headers : { ...headers, ...await tenjinIdentityHeaders(url) },
194
176
  body,
195
- signal,
177
+ signal: controller.signal,
196
178
  ...pinned ? { redirect: "manual" } : {}
197
179
  });
198
180
  } catch (err) {
@@ -213,7 +195,7 @@ async function httpRequest(url, opts) {
213
195
  kind: "blocked-redirect",
214
196
  status: res.status,
215
197
  ...requestId !== void 0 ? { requestId } : {},
216
- message: signed ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; refusing to follow it, because the signature is bound to the configured origin.` : bypassed ? `Request to ${url} was redirected (${res.status}) while carrying the team shelf's bypass key; refusing to follow it, because the key opens only the configured origin.` : `Request to ${url} was redirected (${res.status}); refusing to follow it, because the response must come from the configured origin.`
198
+ message: signed ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; refusing to follow it, because the signature is bound to the configured origin.` : `Request to ${url} was redirected (${res.status}); refusing to follow it, because the response must come from the configured origin.`
217
199
  };
218
200
  }
219
201
  let text;
@@ -227,7 +209,7 @@ async function httpRequest(url, opts) {
227
209
  kind: "network",
228
210
  status: res.status,
229
211
  ...requestId !== void 0 ? { requestId } : {},
230
- message: `Request to ${url} returned a file over the ${Math.round((opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES) / 1048576)} MB cap; it was not kept.`
212
+ message: `Request to ${url} returned a file over the ${capText(opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES)} cap; it was not kept.`
231
213
  };
232
214
  }
233
215
  bytes = read;
@@ -272,7 +254,7 @@ async function httpRequest(url, opts) {
272
254
  }
273
255
  }
274
256
  function fetchFailureToCliError(failure, opts = {}) {
275
- const code = failure.kind === "network" || failure.kind === "timeout" ? "NETWORK_ERROR" : failure.kind === "invalid-json" ? "CONTRACT_MISMATCH" : failure.kind === "oversized-header" ? "CHALLENGE_TOO_LARGE" : "API_UNREACHABLE";
257
+ const code = failure.kind === "network" || failure.kind === "timeout" ? "NETWORK_ERROR" : failure.kind === "oversized-header" ? "CHALLENGE_TOO_LARGE" : "API_UNREACHABLE";
276
258
  const fix = opts.fix ?? (failure.kind === "oversized-header" ? "Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes." : void 0);
277
259
  return new CliError(code, failure.message, {
278
260
  ...fix !== void 0 ? { fix } : {},
@@ -336,8 +318,9 @@ export {
336
318
  composeUserAgent,
337
319
  setTenjinIdentity,
338
320
  requestHeaderProblem,
321
+ MAX_BINARY_BODY_BYTES,
339
322
  isBinaryContentType,
340
323
  httpRequest,
341
324
  fetchFailureToCliError
342
325
  };
343
- //# sourceMappingURL=chunk-36RVGZNY.js.map
326
+ //# sourceMappingURL=chunk-D6M3ZK66.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/client-meta.ts","../src/lib/http.ts"],"sourcesContent":["import pkg from '../../package.json';\nimport { PRODUCTION_ORIGIN } from './production-origin';\n\n/**\n * The RFC 9110 product token naming this CLI. It leads every User-Agent\n * because the server's `parseUserAgentProduct()` attributes on the first\n * product only, and the CLI is what sent the request.\n */\nexport const TENJIN_PRODUCT = `tenjin-cli/${pkg.version}`;\n\n/** The product name alone, which identifies a copy of us in a handoff. */\nexport const TENJIN_PRODUCT_NAME = 'tenjin-cli';\n\n/** The product an earlier build's WebSearch hook led with; a handoff may still carry it. */\nexport const WEBSEARCH_HOOK_PRODUCT_NAME = 'tenjin-websearch-hook';\n\n/** Every identity of ours a handoff may carry, which composition drops rather\n * than duplicate. */\nexport const OWN_PRODUCT_NAMES = [TENJIN_PRODUCT_NAME, WEBSEARCH_HOOK_PRODUCT_NAME];\n\n/**\n * The identifying comment. It rides last so a caller's products keep their\n * order, and stripping it recovers the caller's sequence from a composed field.\n */\nexport const TENJIN_COMMENT = `(+${PRODUCTION_ORIGIN})`;\n\n/**\n * The CLI's identity on every HTTP request, sent as `User-Agent` from the\n * shared transport (`http.ts`).\n */\nexport const TENJIN_USER_AGENT = `${TENJIN_PRODUCT} ${TENJIN_COMMENT}`;\n\n/** The handoff seam for an agent that launches the CLI as a subprocess. */\nexport const CALLER_USER_AGENT_ENV = 'TENJIN_CALLER_USER_AGENT';\n\n/** The server's bound: a longer field is discarded whole, never truncated. */\nexport const USER_AGENT_MAX_LENGTH = 512;\n\n/**\n * One RFC 9110 product: a token, optionally `/token`. The handoff accepts only\n * a sequence of these, no comments or free text, which keeps user, wallet,\n * session and machine identifiers out structurally rather than by blocklist.\n */\nexport const PRODUCT_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+)?$/;\n\n/** Printable ASCII, the only range the server parses; also excludes CR/LF/tab. */\nexport const PRINTABLE_ASCII_RE = /^[\\x20-\\x7e]*$/;\n\nexport interface ComposeUserAgentInput {\n /** A caller's product sequence, passed programmatically; wins over the env. */\n caller?: string | undefined;\n /** Environment seam; defaults to `process.env`. */\n env?: NodeJS.ProcessEnv;\n}\n\n/**\n * Compose the field the transport sends: the Tenjin product, the caller's\n * products in order, then the Tenjin comment. The handoff is self-reported\n * telemetry; nothing here or on the server may use it for entitlement, spend\n * or trust.\n *\n * Idempotent: our own product and comment are dropped from the caller value\n * before the rebuild, so re-composing a composed field (a retry, an agent\n * re-exporting its env) never adds a second `tenjin-cli` token.\n *\n * Rejection is total: a non-printable, non-product or overlong handoff is\n * omitted whole, because truncating a product token would mint a false one.\n */\nexport function composeUserAgent(input: ComposeUserAgentInput = {}): string {\n const raw = input.caller ?? (input.env ?? process.env)[CALLER_USER_AGENT_ENV];\n const products = callerProducts(raw);\n if (products.length === 0) return TENJIN_USER_AGENT;\n const composed = `${TENJIN_PRODUCT} ${products.join(' ')} ${TENJIN_COMMENT}`;\n return composed.length <= USER_AGENT_MAX_LENGTH ? composed : TENJIN_USER_AGENT;\n}\n\n/** The caller's products, or none at all when any part of the handoff is unusable. */\nfunction callerProducts(raw: string | undefined): string[] {\n if (raw === undefined || !PRINTABLE_ASCII_RE.test(raw)) return [];\n // Printable ASCII leaves the space as the only whitespace, so it is the only\n // separator a product sequence can have.\n const tokens = raw.split(' ').filter((token) => token.length > 0 && !isOwnIdentity(token));\n return tokens.every((token) => PRODUCT_RE.test(token)) ? tokens : [];\n}\n\n/**\n * Our own identity inside a caller value, matched case-insensitively: a copy\n * of ours in any casing is still a duplicate identity.\n */\nfunction isOwnIdentity(token: string): boolean {\n const lower = token.toLowerCase();\n // Lower both sides, so a constant that gains a capital still matches.\n if (lower === TENJIN_COMMENT.toLowerCase()) return true;\n return OWN_PRODUCT_NAMES.some((name) => {\n const own = name.toLowerCase();\n return lower === own || lower.startsWith(`${own}/`);\n });\n}\n","import { CliError } from './errors';\nimport { composeUserAgent } from './client-meta';\n\n/**\n * Vercel's \"Protection Bypass for Automation\" header: a door key to someone's\n * protected deployment. This client never sets it, and neither an operator's\n * `-H` nor a spec may (see {@link isReservedRequestHeader}): a request that\n * carried one would hand the key to whatever host it went to.\n */\nconst PROTECTION_BYPASS_HEADER = 'x-vercel-protection-bypass';\n\n/** The anonymous install id: a random UUID minted once per data dir. */\nexport const INSTALL_ID_HEADER = 'tenjin-install-id';\n\n/**\n * Who is using the router, for Tenjin's own request telemetry: an anonymous\n * install id, random and tied to nothing but the data dir.\n *\n * The transport decides where it goes, from the REQUEST URL, so a call site\n * cannot send it to a provider by believing it is talking to Tenjin. `pay` runs over this transport\n * to third-party sellers, and none of them gets the header.\n *\n * Process-wide rather than a per-call option because it is not a per-call\n * decision: every request to Tenjin carries it, and threading it through forty\n * call sites is forty chances to forget one. Set only by the process entry (the\n * CLI's `index.ts`), so an in-process test that never sets it sends exactly\n * what it always did.\n *\n * Redirects are left to the request's usual transport: an unpinned request\n * follows them as `fetch` does, headers and all. Tenjin's origins redirect only\n * to Tenjin's own hosts, and the id is not a credential, so it is not worth the\n * redirect pin signed headers get.\n */\nexport interface TenjinIdentity {\n /** The origins that are Tenjin's own for this process. */\n origins: () => Promise<readonly string[]>;\n /** The install id; absent when it could not be read or created. */\n installId: () => Promise<string | undefined>;\n}\n\nlet tenjinIdentity: TenjinIdentity | undefined;\n\nexport function setTenjinIdentity(identity: TenjinIdentity | undefined): void {\n tenjinIdentity = identity;\n}\n\n/**\n * The telemetry headers for `url`, or nothing. NEVER THROWS: a data dir that\n * cannot be read costs the request its telemetry and nothing else.\n */\nexport async function tenjinIdentityHeaders(url: string): Promise<Record<string, string>> {\n const identity = tenjinIdentity;\n if (identity === undefined) return {};\n try {\n if (!(await identity.origins()).includes(new URL(url).origin)) return {};\n const id = await identity.installId();\n return id !== undefined ? { [INSTALL_ID_HEADER]: id } : {};\n } catch {\n return {};\n }\n}\n\n/**\n * The one place the identity is written for anything that can import it; the\n * transport funnels its Headers through it, so a second entry point on this\n * side cannot ship without it. `.set` on a Headers\n * object is what makes this total: a caller header spelled `User-Agent` in any\n * case lands in the same slot and is overwritten, never duplicated, so a\n * call-specific header cannot erase the composed field or add a second one.\n */\nfunction applyUserAgent(headers: Headers, callerUserAgent?: string): Headers {\n headers.set('user-agent', composeUserAgent({ caller: callerUserAgent }));\n return headers;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `blocked-redirect`\n * (a 3xx a pinned request may not follow), `oversized-header` (a response\n * header block too large to read).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'blocked-redirect' | 'oversized-header';\n status?: number;\n requestId?: string;\n message: string;\n /**\n * On `network`: the layer the error chain names, when it names one. The\n * origin never answered, so a caller that blames it (or its base URL) gives\n * the wrong fix. See {@link transportFailure}.\n */\n transport?: TransportFailure;\n /**\n * On a `timeout` that came after the response headers did (`httpRequest`\n * only): a case-insensitive lookup over them. A seller can name where a long\n * job's result will be with its first byte, and only the body ran out of time.\n */\n header?: (name: string) => string | undefined;\n}\n\n/** Which layer refused a request that never reached the origin. */\nexport interface TransportFailure {\n layer: 'proxy' | 'dns' | 'tls' | 'connect';\n /** The socket's own error code, for every layer but `proxy`. */\n code?: string;\n /** What the proxy answered to `CONNECT`, for `proxy` only. */\n proxyStatus?: number;\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect: nothing signed\n * may leave for a host the request did not name, and `fetch`'s default\n * `redirect: 'follow'` re-sends request headers verbatim to the new host (Node\n * strips only `Authorization`). A 3xx anywhere on the signed origin would\n * therefore hand a signature BOUND TO THAT DOMAIN to whoever `Location` points\n * at, replayable against it for the signature's lifetime.\n *\n * Detected by header NAME rather than by a caller-supplied \"this is signed\" flag\n * so the protection cannot be forgotten at a call site: attaching the credential\n * is what arms it. Matched case-insensitively. Kept as literals so the base\n * transport keeps its single dependency; `http.test.ts` pins them against the\n * real constants in `lib/siwx` and the x402 payment headers.\n *\n * Both wallet-signed families this CLI sends are here: the SIWX auth header,\n * and the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance).\n * `tenjin-session-delegation` is a reusable SIWX signature this client no\n * longer sends; it stays so a spec can never set it.\n */\nconst CREDENTIAL_HEADERS = new Set([\n 'sign-in-with-x',\n 'payment-signature',\n 'x-payment',\n 'tenjin-session-delegation',\n]);\n\nfunction carriesSignedMaterial(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));\n}\n\n/**\n * A request header name an operator may not set: the wallet-signed material\n * above, a deployment-protection bypass key, this install's identity, and the\n * x402 payment namespace. Kept beside the set so the two cannot drift.\n */\nexport function isReservedRequestHeader(name: string): boolean {\n const lowered = name.toLowerCase();\n return (\n CREDENTIAL_HEADERS.has(lowered) ||\n lowered === PROTECTION_BYPASS_HEADER ||\n lowered === INSTALL_ID_HEADER ||\n lowered.startsWith('payment-') ||\n lowered.startsWith('x-payment')\n );\n}\n\n/** One header name, as RFC 9110 spells a token. */\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n/** Names the transport or the body encoding own. */\nconst TRANSPORT_HEADERS = new Set(['host', 'content-length', 'content-type', 'user-agent']);\n\n/**\n * Why a request header someone else names (an operator's `-H`, a catalog\n * spec) cannot ride a paid request, or null when it can: `name` for a name\n * that is not a token or a value that is empty, `reserved` for a name this\n * client signs or sets itself or the transport owns, `value` for a value over\n * 1,024 characters or one that spans lines. `ownContentType` lets the caller\n * name `content-type`, for a body this client does not encode.\n */\nexport function requestHeaderProblem(\n name: string,\n value: string,\n ownContentType = false,\n): 'name' | 'reserved' | 'value' | null {\n if (!HEADER_NAME.test(name) || value.length === 0) return 'name';\n const lowered = name.toLowerCase();\n const contentType = ownContentType && lowered === 'content-type';\n if (isReservedRequestHeader(lowered) || (TRANSPORT_HEADERS.has(lowered) && !contentType)) {\n return 'reserved';\n }\n if (value.length > 1_024 || /[\\r\\n]/.test(value)) return 'value';\n return null;\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status: the pay flow needs the body on a 402, and the router's\n * calls need a 4xx validation envelope. It never throws on a transport or\n * protocol failure: it returns the discriminated FetchJsonFailure so callers\n * map each class uniformly. `fetchImpl` is injectable so tests never touch the\n * network.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n timeoutMs: number;\n headers?: Record<string, string>;\n /**\n * INTERNAL. A caller's own product sequence, composed BEHIND the CLI's\n * identity (see `composeUserAgent`). The package ships a `bin` and no\n * `exports` map, so this is not a supported seam for code outside this repo:\n * the documented handoff is the `TENJIN_CALLER_USER_AGENT` environment\n * variable, which is what a subprocess launcher sets and what this falls back\n * to. Kept as an option so an in-repo caller can pass a value the environment\n * does not carry.\n */\n callerUserAgent?: string;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n /**\n * A body the CALLER already encoded, sent byte for byte with no content-type\n * of this transport's choosing: the router's provider leg is handed a request\n * the server built, and re-encoding it would make the bytes signed for and\n * the bytes sent two different things. The caller's own `headers` carry the\n * content type. Ignored when `jsonBody` is set.\n */\n rawBody?: string;\n fetchImpl?: typeof fetch;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact, following a\n * cross-origin redirect would let another host's bytes be recorded as if the\n * origin asked for served them. Off by default, so other requests keep normal\n * transport.\n */\n blockRedirects?: boolean;\n /**\n * Keep a binary body as bytes. A sound, an image or any other non-text\n * payload decoded as text is corrupted, so with this set a response whose\n * content type is not text ({@link isBinaryContentType}) comes back with\n * `bytes` and an empty `text`. `tenjin pay` sets it on every lane (the\n * router's provider leg and a direct pay); every other caller reads text as\n * before.\n */\n binaryBody?: boolean;\n /** The cap on such a body; over it the response is a failure, never a\n * buffer that grows without bound. Defaults to {@link MAX_BINARY_BODY_BYTES}. */\n maxBinaryBytes?: number;\n /**\n * Send no install id, and mint none. For a request that checks the network\n * rather than uses Tenjin (the reachability probe), so it never counts as an\n * install in request telemetry.\n */\n anonymous?: boolean;\n}\n\n/** The same cap the router's linked-media download uses. */\nexport const MAX_BINARY_BODY_BYTES = 200 * 1024 * 1024;\n\n/** A body cap as a person reads it: whole MB, or bytes under one. */\nfunction capText(bytes: number): string {\n return bytes >= 1_048_576 ? `${Math.round(bytes / 1_048_576)} MB` : `${bytes}-byte`;\n}\n\n/**\n * The body's bytes, read chunk by chunk and abandoned the moment they pass\n * `max`; null over the cap. A declared length over it is refused unread.\n */\nasync function readCapped(res: Response, max: number): Promise<Uint8Array | null> {\n const declared = Number(res.headers.get('content-length') ?? '0');\n if (Number.isFinite(declared) && declared > max) {\n await res.body?.cancel().catch(() => undefined);\n return null;\n }\n if (res.body === null) return new Uint8Array();\n const reader = res.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > max) {\n await reader.cancel().catch(() => undefined);\n return null;\n }\n chunks.push(value);\n }\n return new Uint8Array(Buffer.concat(chunks));\n}\n\n/**\n * A content type whose body is not text: anything that is not `text/*` and\n * not a JSON, XML, JavaScript, YAML or form type. An absent header is text, as\n * it always was here.\n */\nexport function isBinaryContentType(contentType: string | undefined): boolean {\n const type = (contentType ?? '').split(';')[0]!.trim().toLowerCase();\n if (type.length === 0) return false;\n if (type.startsWith('text/')) return false;\n return !/(?:json|xml|javascript|ecmascript|yaml|x-www-form-urlencoded)/.test(type);\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n /** The raw body text; what a non-JSON endpoint actually said (`pay` delivers it). */\n text: string;\n /** The body's bytes, only for a binary body read with `binaryBody`; `text`\n * is then empty. */\n bytes?: Uint8Array;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\n/** The wire form of one request: what to send, and whether it may follow a redirect. */\ninterface PreparedRequest {\n ok: true;\n headers: Record<string, string>;\n body: string | undefined;\n signed: boolean;\n pinned: boolean;\n}\n\n/**\n * Assemble the request and DERIVE its redirect decision from the headers that\n * were actually built, in one place and one pass. The redirect flags are\n * returned rather than assigned, so they have no value until the headers do:\n * there is no state in which `pinned` is readable but not yet computed, which\n * is what would let a signed request follow a 3xx to another host. Anything\n * that refuses here (`new Headers` throws on a malformed caller header) becomes\n * the same discriminated failure a dead socket does, because this transport\n * documents a returned failure for every refusal, not an exception.\n */\nfunction prepareRequest(url: string, opts: HttpRequestOptions): PreparedRequest | FetchJsonFailure {\n try {\n let body: string | undefined;\n const merged = new Headers(opts.headers ?? {});\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n merged.set('content-type', 'application/json');\n } else if (opts.rawBody !== undefined) {\n body = opts.rawBody;\n }\n const wantsAccept =\n opts.method === 'POST' ||\n opts.method === 'PUT' ||\n opts.method === 'PATCH' ||\n body !== undefined;\n if (wantsAccept && !merged.has('accept')) merged.set('accept', 'application/json');\n // An `accept`/`content-type` set here wins the slot regardless of how a\n // caller cased its own copy.\n const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());\n\n // Signed requests opt out of redirect following entirely; see CREDENTIAL_HEADERS.\n // A caller can also pin an unsigned request (blockRedirects) when the\n // response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n return {\n ok: true,\n headers,\n body,\n signed,\n pinned: signed || opts.blockRedirects === true,\n };\n } catch (err) {\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n };\n }\n}\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, pinned } = prepared;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers:\n opts.anonymous === true ? headers : { ...headers, ...(await tenjinIdentityHeaders(url)) },\n body,\n signal: controller.signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (isHeaderOverflow(err)) return oversizedHeaderFailure(url);\n const transport = transportFailure(err);\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n ...(transport !== undefined ? { transport } : {}),\n };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED on a redirect the request was not allowed to follow. This\n // returns a failure rather than the 3xx response so no caller can mistake an\n // unfollowed redirect for a normal status and retry it by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: signed\n ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; ` +\n 'refusing to follow it, because the signature is bound to the configured origin.'\n : `Request to ${url} was redirected (${res.status}); ` +\n 'refusing to follow it, because the response must come from the configured origin.',\n };\n }\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n let bytes: Uint8Array | undefined;\n try {\n if (opts.binaryBody === true && isBinaryContentType(res.headers.get('content-type') ?? '')) {\n const read = await readCapped(res, opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES);\n if (read === null) {\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} returned a file over the ${capText(opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES)} cap; it was not kept.`,\n };\n }\n bytes = read;\n text = '';\n } else {\n text = await res.text();\n }\n } catch (err) {\n if (timedOut) {\n return {\n ...timeoutFailure(url, opts.timeoutMs),\n header: (name) => res.headers.get(name) ?? undefined,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n text,\n ...(bytes !== undefined ? { bytes } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an oversized header block is CHALLENGE_TOO_LARGE, and a\n * blocked redirect is API_UNREACHABLE. Callers that need a check-specific code\n * build their own CliError; this is the default the rest lean on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'oversized-header'\n ? 'CHALLENGE_TOO_LARGE'\n : 'API_UNREACHABLE';\n // The one failure with a remedy nobody can apply from inside the process, so\n // it names the operator's knob rather than suggesting a retry.\n // The knob, with no claim about payment: a caller that knows its leg passes\n // its own `fix` and says what happened to the money there.\n const fix =\n opts.fix ??\n (failure.kind === 'oversized-header'\n ? 'Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes.'\n : undefined);\n return new CliError(code, failure.message, {\n ...(fix !== undefined ? { fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Does this transport failure mean the response HEADERS were too big for this\n * process to read?\n *\n * Node caps them at 16 KiB unless `--max-http-header-size` says otherwise, and\n * an x402 challenge is a header: a seller that embeds its whole output schema\n * in one can exceed the cap on its own (AnyAPI's is 52 KB, measured\n * 2026-09-22). undici then aborts the request and the generic path reported\n * `fetch failed` with no status and nothing naming the cause, which reads as\n * \"the endpoint is down\" for a seller that is answering perfectly.\n *\n * The message is undici's, matched on its stable text and on the code it\n * attaches; the CAUSE is the one that carries either, so both are checked.\n */\nfunction isHeaderOverflow(err: unknown): boolean {\n const seen = [err, (err as { cause?: unknown } | null)?.cause];\n return seen.some((candidate) => {\n if (candidate === null || typeof candidate !== 'object') return false;\n const code = (candidate as { code?: unknown }).code;\n if (code === 'UND_ERR_HEADERS_OVERFLOW' || code === 'HPE_HEADER_OVERFLOW') return true;\n const message = (candidate as { message?: unknown }).message;\n return typeof message === 'string' && /headers overflow|header overflow/i.test(message);\n });\n}\n\nconst DNS_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'EAI_FAIL', 'EAI_NODATA', 'EAI_NONAME']);\nconst CONNECT_CODES = new Set([\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ETIMEDOUT',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\nconst TLS_CODE = /^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_|SELF_SIGNED_|DEPTH_ZERO_)/;\n/** undici's text when a proxy answers `CONNECT` with anything but 200. */\nconst PROXY_REFUSAL = /Proxy response \\((\\d{3})\\)/;\n\n/**\n * The layer a `fetch failed` came from, read down the `cause` chain. fetch\n * wraps the real error twice: a proxy refusing the tunnel is\n * `TypeError: fetch failed`, then `Request was cancelled.`, then undici's\n * `UND_ERR_ABORTED` with the proxy's status in its message (Node 24.18,\n * measured 2026-10-05). Undefined when no link names a layer.\n */\nexport function transportFailure(err: unknown): TransportFailure | undefined {\n let link: unknown = err;\n for (let depth = 0; depth < 5 && link !== null && typeof link === 'object'; depth += 1) {\n const { code, message, cause } = link as { code?: unknown; message?: unknown; cause?: unknown };\n const proxy = typeof message === 'string' ? PROXY_REFUSAL.exec(message) : null;\n if (proxy !== null) return { layer: 'proxy', proxyStatus: Number(proxy[1]) };\n if (typeof code === 'string') {\n if (DNS_CODES.has(code)) return { layer: 'dns', code };\n if (TLS_CODE.test(code)) return { layer: 'tls', code };\n if (CONNECT_CODES.has(code)) return { layer: 'connect', code };\n }\n link = cause;\n }\n return undefined;\n}\n\n/**\n * The named refusal for that case. NOT a `network` failure: nothing is wrong\n * with the connection, and a caller that retries gets the same 52 KB again.\n *\n * SAYS NOTHING ABOUT PAYMENT. This transport serves the unpaid probe and the\n * paid retry alike and cannot tell them apart, so a message asserting either\n * way is wrong on one of them: it read as \"nothing was sent\" on a leg where a\n * signed authorization had already left. The leg adds that sentence, because\n * the leg is what knows; see `runPay`.\n */\nfunction oversizedHeaderFailure(url: string): FetchJsonFailure {\n let origin = url;\n try {\n origin = new URL(url).origin;\n } catch {\n // Keep the raw string; this is a diagnostic, not a destination.\n }\n return {\n ok: false,\n kind: 'oversized-header',\n message:\n `${origin} answered with a response header block larger than this process will read. ` +\n 'An x402 challenge travels in a header, and a seller that embeds its whole output ' +\n 'schema in one can exceed the limit, so the response could not be read.',\n };\n}\n"],"mappings":";;;;;;;;;;;;AAQO,IAAM,iBAAiB,cAAc,gBAAI,OAAO;AAGhD,IAAM,sBAAsB;AAG5B,IAAM,8BAA8B;AAIpC,IAAM,oBAAoB,CAAC,qBAAqB,2BAA2B;AAM3E,IAAM,iBAAiB,KAAK,iBAAiB;AAM7C,IAAM,oBAAoB,GAAG,cAAc,IAAI,cAAc;AAG7D,IAAM,wBAAwB;AAG9B,IAAM,wBAAwB;AAO9B,IAAM,aAAa;AAGnB,IAAM,qBAAqB;AAsB3B,SAAS,iBAAiB,QAA+B,CAAC,GAAW;AAC1E,QAAM,MAAM,MAAM,WAAW,MAAM,OAAO,QAAQ,KAAK,qBAAqB;AAC5E,QAAM,WAAW,eAAe,GAAG;A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K_ERROR: 1,
17
17
  INTERNAL: 1,
18
- NOT_IMPLEMENTED: 1,
19
18
  POLICY_REFUSED: 3,
20
19
  PAYMENT_FAILED: 4,
21
20
  RESOURCE_NOT_FOUND: 1,
22
- SEARCH_NOT_FOUND: 1,
23
21
  RATE_LIMITED: 1,
24
- // A publish awaiting confirmation or hard-blocked is understood-but-refused (3),
25
- // the same posture as POLICY_REFUSED; a write that failed after approval is a
26
- // settlement-class failure (4), like PAYMENT_FAILED.
27
- NEEDS_CONFIRMATION: 3,
28
- PUBLISH_BLOCKED: 3,
29
- PUBLISH_FAILED: 4,
30
22
  // A send that reverted or stalled AFTER the human approved it and it was
31
23
  // broadcast: the post-decision failure class (4), like PAYMENT_FAILED.
32
24
  SEND_FAILED: 4,
33
- // A delete the operator confirmed and the server then refused: same class.
34
- DELETE_FAILED: 4,
35
25
  UPDATE_FAILED: 1,
36
26
  // Refused BEFORE any signature existed: the Bazaar lane's fail-closed check.
37
27
  REGISTRY_MISMATCH: 3,
@@ -62,4 +52,4 @@ var CliError = class extends Error {
62
52
  export {
63
53
  CliError
64
54
  };
65
- //# sourceMappingURL=chunk-3UCIG4TG.js.map
55
+ //# sourceMappingURL=chunk-DI4QAGRZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/errors.ts"],"sourcesContent":["import type { ErrorCode } from '../schemas';\n\n/**\n * The process exit code is API (spec 10): 0 success, 1 runtime/network, 2 usage,\n * 3 understood-but-refused (a policy refusal, a payment that needs consent), 4 a\n * failure AFTER an approved spend (a settlement or a send that failed).\n */\nexport type ExitCode = 1 | 2 | 3 | 4;\n\nexport interface CliErrorOptions {\n /** A copy-pasteable command or one-line remediation. */\n fix?: string;\n /** Structured detail for machine consumers; serialized into the envelope. */\n details?: unknown;\n /** Override the default exit code for this error's code. */\n exitCode?: ExitCode;\n /** Underlying cause, preserved on the Error but never serialized. */\n cause?: unknown;\n}\n\n/**\n * Default code -> exit-code mapping. USAGE/CONFIG_INVALID are malformed\n * invocations (2); WALLET_EXISTS/REFUSED are understood-but-refused (3);\n * everything else is a runtime/network failure (1). A CliError may override its\n * own exit code, but the table is the default every caller relies on.\n */\nconst EXIT_BY_CODE: Record<ErrorCode, ExitCode> = {\n NODE_UNSUPPORTED: 1,\n USAGE: 2,\n CONFIG_INVALID: 2,\n WALLET_EXISTS: 3,\n WALLET_MISSING: 1,\n WALLET_INVALID_KEY: 1,\n PROVIDER_ERROR: 1,\n RPC_ERROR: 1,\n API_UNREACHABLE: 1,\n CONTRACT_MISMATCH: 1,\n REFUSED: 3,\n NETWORK_ERROR: 1,\n INTERNAL: 1,\n POLICY_REFUSED: 3,\n PAYMENT_FAILED: 4,\n RESOURCE_NOT_FOUND: 1,\n RATE_LIMITED: 1,\n // A send that reverted or stalled AFTER the human approved it and it was\n // broadcast: the post-decision failure class (4), like PAYMENT_FAILED.\n SEND_FAILED: 4,\n UPDATE_FAILED: 1,\n // Refused BEFORE any signature existed: the Bazaar lane's fail-closed check.\n REGISTRY_MISMATCH: 3,\n // The seller's 402 challenge does not fit this process's header limit, so the\n // terms could not be read and nothing was sent. Understood and refused (3),\n // not a transport failure: the connection was fine and a retry changes\n // nothing without an operator raising `--max-http-header-size`.\n CHALLENGE_TOO_LARGE: 3,\n};\n\nexport function exitCodeFor(code: ErrorCode): ExitCode {\n return EXIT_BY_CODE[code];\n}\n\n/**\n * The one error type commands throw. It carries the machine `code`, the resolved\n * `exitCode`, and an optional `fix`/`details` that flow straight into the failure\n * envelope. Commands throw it; the CLI dispatcher catches, serializes, and exits.\n */\nexport class CliError extends Error {\n readonly code: ErrorCode;\n readonly exitCode: ExitCode;\n readonly fix?: string;\n readonly details?: unknown;\n\n constructor(code: ErrorCode, message: string, opts: CliErrorOptions = {}) {\n super(message, opts.cause !== undefined ? { cause: opts.cause } : undefined);\n this.name = 'CliError';\n this.code = code;\n this.exitCode = opts.exitCode ?? exitCodeFor(code);\n this.fix = opts.fix;\n this.details = opts.details;\n }\n}\n"],"mappings":";;;AA0BA,IAAM,eAA4C;AAAA,EAChD,kBAAkB;AAAA,EAClB,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,oBAAoB;AAAA,EACpB,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,eAAe;AAAA,EACf,UAAU;AAAA,EACV,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,oBAAoB;AAAA,EACpB,cAAc;AAAA;AAAA;AAAA,EAGd,aAAa;AAAA,EACb,eAAe;AAAA;AAAA,EAEf,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKnB,qBAAqB;AACvB;AAEO,SAAS,YAAY,MAA2B;AACrD,SAAO,aAAa,IAAI;AAC1B;AAOO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAAiB,SAAiB,OAAwB,CAAC,GAAG;AACxE,UAAM,SAAS,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,MAAS;AAC3E,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW,KAAK,YAAY,YAAY,IAAI;AACjD,SAAK,MAAM,KAAK;AAChB,SAAK,UAAU,KAAK;AAAA,EACtB;AACF;","names":[]}