tenjin-cli 0.1.0-alpha.34 → 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 (332) hide show
  1. package/NOTICE.md +30 -0
  2. package/README.md +20 -18
  3. package/dist/{_esm-MMYV66AX.js → _esm-2KST7HQ7.js} +4 -4
  4. package/dist/{alive-VOIL5W3I.js → alive-5TV22PNF.js} +13 -13
  5. package/dist/{auth-UHD3QFX4.js → auth-XI7BJFLW.js} +4 -4
  6. package/dist/balance-DFHC6XEU.js +71 -0
  7. package/dist/{ccip-CS7K5QRQ.js → ccip-HOW3DZYF.js} +3 -3
  8. package/dist/{chunk-RJ5HRPAZ.js → chunk-24XKUN2S.js} +68 -10
  9. package/dist/chunk-24XKUN2S.js.map +1 -0
  10. package/dist/chunk-2L7TDGLV.js +56 -0
  11. package/dist/chunk-2L7TDGLV.js.map +1 -0
  12. package/dist/{chunk-PZHBPGDE.js → chunk-34SAECKZ.js} +34 -10
  13. package/dist/chunk-34SAECKZ.js.map +1 -0
  14. package/dist/{chunk-EQZ2CCWC.js → chunk-3Y2EHT4F.js} +5 -2
  15. package/dist/chunk-3Y2EHT4F.js.map +1 -0
  16. package/dist/{chunk-FSYH7J75.js → chunk-3Y6BHIN6.js} +3 -3
  17. package/dist/{chunk-FZZWTDWP.js → chunk-3YPL6T3P.js} +6 -6
  18. package/dist/{chunk-JEZMWJEF.js → chunk-44MVIRZH.js} +4 -4
  19. package/dist/{chunk-27FIHFXF.js → chunk-45MMSBHA.js} +5 -5
  20. package/dist/{chunk-QXP3Z3JN.js → chunk-4MBCJFY4.js} +35 -3
  21. package/dist/chunk-4MBCJFY4.js.map +1 -0
  22. package/dist/chunk-4TPL54KW.js +227 -0
  23. package/dist/chunk-4TPL54KW.js.map +1 -0
  24. package/dist/{chunk-7JB6SYJX.js → chunk-54ELBTKE.js} +2 -2
  25. package/dist/{chunk-6J64MQFD.js → chunk-5F4OB5B3.js} +21 -15
  26. package/dist/chunk-5F4OB5B3.js.map +1 -0
  27. package/dist/{chunk-PYVQ74D5.js → chunk-5HN4KVQU.js} +189 -117
  28. package/dist/chunk-5HN4KVQU.js.map +1 -0
  29. package/dist/{chunk-VFKPIIV2.js → chunk-5J4E5GYI.js} +35 -32
  30. package/dist/chunk-5J4E5GYI.js.map +1 -0
  31. package/dist/chunk-5USBZ2MU.js +58 -0
  32. package/dist/chunk-5USBZ2MU.js.map +1 -0
  33. package/dist/chunk-64WOMNYR.js +183 -0
  34. package/dist/chunk-64WOMNYR.js.map +1 -0
  35. package/dist/{chunk-APWELUI7.js → chunk-65RS4LQS.js} +57 -43
  36. package/dist/chunk-65RS4LQS.js.map +1 -0
  37. package/dist/{chunk-HWZO6HYZ.js → chunk-6QMDUDF2.js} +3 -3
  38. package/dist/{chunk-FNBGRKS6.js → chunk-7V25UAQO.js} +2 -2
  39. package/dist/chunk-BGA4DO5M.js +719 -0
  40. package/dist/chunk-BGA4DO5M.js.map +1 -0
  41. package/dist/chunk-BVP7YK2J.js +706 -0
  42. package/dist/chunk-BVP7YK2J.js.map +1 -0
  43. package/dist/chunk-C265QIMJ.js +83 -0
  44. package/dist/chunk-C265QIMJ.js.map +1 -0
  45. package/dist/{chunk-MXN2ZEUB.js → chunk-D6M3ZK66.js} +2 -2
  46. package/dist/chunk-D6M3ZK66.js.map +1 -0
  47. package/dist/chunk-DJ36BM62.js +78 -0
  48. package/dist/chunk-DJ36BM62.js.map +1 -0
  49. package/dist/{chunk-JOKPBYXP.js → chunk-DTEWAVNE.js} +2 -2
  50. package/dist/chunk-F2KJAJ7T.js +13 -0
  51. package/dist/chunk-F2KJAJ7T.js.map +1 -0
  52. package/dist/{chunk-KAILF7QA.js → chunk-F43CV6UC.js} +2 -2
  53. package/dist/{chunk-ACO7ZCR2.js → chunk-FKVJKLPI.js} +2 -2
  54. package/dist/{chunk-43HLS2HM.js → chunk-FYFHH7V5.js} +54 -3
  55. package/dist/{chunk-43HLS2HM.js.map → chunk-FYFHH7V5.js.map} +1 -1
  56. package/dist/{chunk-2F5JUAHZ.js → chunk-GAJC4BQZ.js} +3 -3
  57. package/dist/{chunk-L7N73ZAW.js → chunk-HAZAN4UM.js} +2 -2
  58. package/dist/{chunk-6QJZA6EX.js → chunk-HI5XQOX2.js} +2 -2
  59. package/dist/{chunk-BOENA6XR.js → chunk-HKGUKAQW.js} +6 -6
  60. package/dist/{chunk-LJSCGIYH.js → chunk-HPRVFJPM.js} +2 -2
  61. package/dist/{chunk-OO6FIBL7.js → chunk-HZKANST2.js} +3 -6
  62. package/dist/chunk-HZKANST2.js.map +1 -0
  63. package/dist/{chunk-UVDJ5SSQ.js → chunk-I557SAOM.js} +8 -2
  64. package/dist/chunk-I557SAOM.js.map +1 -0
  65. package/dist/{chunk-SDUOJRSV.js → chunk-IGLWLH73.js} +3 -3
  66. package/dist/{chunk-3AKH7ODX.js → chunk-INSIW65E.js} +5 -5
  67. package/dist/{chunk-PNHNXUSL.js → chunk-IULCDMVG.js} +12 -1
  68. package/dist/chunk-IULCDMVG.js.map +1 -0
  69. package/dist/{chunk-JF4T4HCQ.js → chunk-IVNSUAVC.js} +10 -5
  70. package/dist/chunk-IVNSUAVC.js.map +1 -0
  71. package/dist/chunk-JDQZCREI.js +87 -0
  72. package/dist/chunk-JDQZCREI.js.map +1 -0
  73. package/dist/{chunk-2P3NJTHE.js → chunk-JHFFUVON.js} +23 -23
  74. package/dist/{chunk-7JVARP5R.js → chunk-JTILUN4W.js} +55 -29
  75. package/dist/{chunk-7JVARP5R.js.map → chunk-JTILUN4W.js.map} +1 -1
  76. package/dist/{chunk-2TO5F6CT.js → chunk-K5KNGC4I.js} +8 -8
  77. package/dist/{chunk-HUWTFKEM.js → chunk-KAQ4Q3TO.js} +3 -3
  78. package/dist/{chunk-E6VP6MQM.js → chunk-KGUE5AVX.js} +4 -4
  79. package/dist/chunk-KGUE5AVX.js.map +1 -0
  80. package/dist/{chunk-GS5RZF7U.js → chunk-KLDMLWXT.js} +2 -2
  81. package/dist/{chunk-HN2EN6P4.js → chunk-KNKDMTHU.js} +5 -5
  82. package/dist/chunk-LDA6TAYQ.js +95 -0
  83. package/dist/chunk-LDA6TAYQ.js.map +1 -0
  84. package/dist/chunk-LWSSIZOY.js +347 -0
  85. package/dist/chunk-LWSSIZOY.js.map +1 -0
  86. package/dist/{chunk-5VWQSCDO.js → chunk-MAHNZA6C.js} +89 -9
  87. package/dist/chunk-MAHNZA6C.js.map +1 -0
  88. package/dist/{chunk-46HAB26L.js → chunk-MEWZCIA6.js} +56 -9
  89. package/dist/chunk-MEWZCIA6.js.map +1 -0
  90. package/dist/{chunk-R2KMLONN.js → chunk-MJDO4EXD.js} +4 -4
  91. package/dist/{chunk-IHVUE3XF.js → chunk-NJA6NT3A.js} +3 -3
  92. package/dist/{chunk-TSIID2LV.js → chunk-ODRPASFP.js} +375 -1166
  93. package/dist/chunk-ODRPASFP.js.map +1 -0
  94. package/dist/{chunk-S3JKF3IK.js → chunk-OJJFANO6.js} +3 -3
  95. package/dist/{chunk-56SOPRM2.js → chunk-OQWPRFAC.js} +344 -4
  96. package/dist/chunk-OQWPRFAC.js.map +1 -0
  97. package/dist/{chunk-QEZZDIQT.js → chunk-P6YQWIT2.js} +4053 -4039
  98. package/dist/chunk-P6YQWIT2.js.map +1 -0
  99. package/dist/{chunk-GGGEGMWC.js → chunk-Q6RSJCXB.js} +9 -9
  100. package/dist/{chunk-OTIUEUIS.js → chunk-QKEUKBRK.js} +7 -7
  101. package/dist/{chunk-X52BVGCJ.js → chunk-QQDPRTLP.js} +5 -5
  102. package/dist/chunk-QQYCYAKI.js +79 -0
  103. package/dist/chunk-QQYCYAKI.js.map +1 -0
  104. package/dist/chunk-R4KDH477.js +1064 -0
  105. package/dist/chunk-R4KDH477.js.map +1 -0
  106. package/dist/{chunk-6AQSUBNR.js → chunk-RGCPELQN.js} +2 -2
  107. package/dist/{chunk-AXODGQ23.js → chunk-RGVCOG2S.js} +9 -2
  108. package/dist/{chunk-AXODGQ23.js.map → chunk-RGVCOG2S.js.map} +1 -1
  109. package/dist/chunk-SOLNJ3AZ.js +209 -0
  110. package/dist/chunk-SOLNJ3AZ.js.map +1 -0
  111. package/dist/{chunk-LQ33RLHL.js → chunk-TFT2X7SH.js} +3 -3
  112. package/dist/chunk-TVWCLUBI.js +293 -0
  113. package/dist/chunk-TVWCLUBI.js.map +1 -0
  114. package/dist/{chunk-VH7JMLTG.js → chunk-UIB33QQP.js} +25 -16
  115. package/dist/chunk-UIB33QQP.js.map +1 -0
  116. package/dist/chunk-V6GIVALQ.js +1889 -0
  117. package/dist/chunk-V6GIVALQ.js.map +1 -0
  118. package/dist/{chunk-IVHGQNIN.js → chunk-VHXCPXUS.js} +8 -8
  119. package/dist/{chunk-7DW7GAM6.js → chunk-VU6GMWF6.js} +2 -2
  120. package/dist/chunk-VWZYE3NC.js +8415 -0
  121. package/dist/chunk-VWZYE3NC.js.map +1 -0
  122. package/dist/{chunk-3X4GOMXT.js → chunk-W2GXIARJ.js} +12 -7
  123. package/dist/chunk-W2GXIARJ.js.map +1 -0
  124. package/dist/chunk-W4G3K3V7.js +288 -0
  125. package/dist/chunk-W4G3K3V7.js.map +1 -0
  126. package/dist/{chunk-FHXTEVO7.js → chunk-W74LJ5OT.js} +21 -28
  127. package/dist/chunk-W74LJ5OT.js.map +1 -0
  128. package/dist/{chunk-FOEPH67T.js → chunk-W7ELYLYK.js} +1 -74
  129. package/dist/chunk-W7ELYLYK.js.map +1 -0
  130. package/dist/{chunk-YU3DLVSQ.js → chunk-XSCGUO2U.js} +5 -5
  131. package/dist/{chunk-EPCIJLLU.js → chunk-XWROSMI5.js} +9 -9
  132. package/dist/{chunk-HMT6L65V.js → chunk-YJGEVBKZ.js} +4 -4
  133. package/dist/{chunk-7U3P4PB7.js → chunk-ZEYA2WWX.js} +4 -4
  134. package/dist/chunk-ZEYA2WWX.js.map +1 -0
  135. package/dist/chunk-ZRC7Z5X3.js +82 -0
  136. package/dist/chunk-ZRC7Z5X3.js.map +1 -0
  137. package/dist/{chunk-I47ARU5G.js → chunk-ZS7JIUJ3.js} +2 -2
  138. package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
  139. package/dist/claude-install-BAUSJMW3.js +64 -0
  140. package/dist/{cli-BFDKEX53.js → cli-QY4KKA3D.js} +116 -49
  141. package/dist/cli-QY4KKA3D.js.map +1 -0
  142. package/dist/{client-XMWEKXX7.js → client-3YQKORVK.js} +4 -4
  143. package/dist/{codex-host-B6NAUWL6.js → codex-host-ZON3S6HU.js} +5 -5
  144. package/dist/{codex-install-GTGO5FYN.js → codex-install-HZV2DOAB.js} +62 -47
  145. package/dist/codex-install-HZV2DOAB.js.map +1 -0
  146. package/dist/{config-THJANIU5.js → config-QZOBMTEL.js} +18 -18
  147. package/dist/{config-names-JU54HYWY.js → config-names-Z5NZD5R2.js} +18 -18
  148. package/dist/{config-rules-VNU23RL4.js → config-rules-YOYHS6YL.js} +19 -19
  149. package/dist/config-subagents-WQV2ZAD5.js +362 -0
  150. package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
  151. package/dist/{connect-HPWS7U63.js → connect-YDWTYU4B.js} +28 -27
  152. package/dist/{connect-HPWS7U63.js.map → connect-YDWTYU4B.js.map} +1 -1
  153. package/dist/core-0a66n3e7-TTP554XV.js +127 -0
  154. package/dist/core-0a66n3e7-TTP554XV.js.map +1 -0
  155. package/dist/core-0bmnpbz2-C2JIRVZO.js +10790 -0
  156. package/dist/core-0bmnpbz2-C2JIRVZO.js.map +1 -0
  157. package/dist/core-9je8ee1j-74DGHWPV.js +30 -0
  158. package/dist/core-9je8ee1j-74DGHWPV.js.map +1 -0
  159. package/dist/core-wadgcjfh-TSZFQZGH.js +666 -0
  160. package/dist/core-wadgcjfh-TSZFQZGH.js.map +1 -0
  161. package/dist/core-zg882d22-LKV5DZYW.js +37 -0
  162. package/dist/core-zg882d22-LKV5DZYW.js.map +1 -0
  163. package/dist/{decision-JIIHDTOF.js → decision-QSKHOGCO.js} +6 -6
  164. package/dist/{doctor-4MMHBRDU.js → doctor-ZWJXRD75.js} +67 -66
  165. package/dist/doctor-ZWJXRD75.js.map +1 -0
  166. package/dist/{explicit-AGENAX6E.js → explicit-ME2NRADQ.js} +45 -42
  167. package/dist/{explicit-AGENAX6E.js.map → explicit-ME2NRADQ.js.map} +1 -1
  168. package/dist/flush-stdio-NYIJ3QXT.js +18 -0
  169. package/dist/{fund-MLXUH24Q.js → fund-VF7TLDJH.js} +110 -34
  170. package/dist/fund-VF7TLDJH.js.map +1 -0
  171. package/dist/{hook-command-UB7FOEUL.js → hook-command-VZ27MGWO.js} +21 -20
  172. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  173. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  174. package/dist/hosts/claude/tenjin/hooks/hook-data.ts +152 -0
  175. package/dist/hosts/claude/tenjin/hooks/hooks.json +7 -0
  176. package/dist/hosts/claude/tenjin/hooks/model-viewer.tsx +2987 -0
  177. package/dist/hosts/claude/tenjin/hooks/register.tsx +265 -30
  178. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
  179. package/dist/hosts/claude/tenjin/types/index.d.ts +133 -0
  180. package/dist/{hosts-WNQKYKP2.js → hosts-3EMTVM4H.js} +5 -3
  181. package/dist/index.js +16 -13
  182. package/dist/index.js.map +1 -1
  183. package/dist/{install-Q5SHHEDH.js → install-ZA7L2UF3.js} +34 -30
  184. package/dist/{install-funding-EGSW2KEP.js → install-funding-JDGYTF72.js} +9 -13
  185. package/dist/{install-identity-OID43B4D.js → install-identity-FFAYEFLX.js} +8 -8
  186. package/dist/{install-wallet-TZFWY5GK.js → install-wallet-2SFOVE3Q.js} +48 -33
  187. package/dist/{install-wallet-TZFWY5GK.js.map → install-wallet-2SFOVE3Q.js.map} +1 -1
  188. package/dist/mcp-36S6MK3C.js +67642 -0
  189. package/dist/mcp-36S6MK3C.js.map +1 -0
  190. package/dist/new-install-5L4GY3LN.js +51 -0
  191. package/dist/{package-NRHU7HBR.js → package-BONDXSV3.js} +2 -2
  192. package/dist/{passphrase-3JEVW5XG.js → passphrase-T4ULBN4M.js} +4 -4
  193. package/dist/{pay-I47AIUQR.js → pay-CMV5KL74.js} +37 -30
  194. package/dist/{payments-A5FNI5GN.js → payments-Z6UBZL4Z.js} +10 -10
  195. package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
  196. package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
  197. package/dist/{routing-quote-QQW2I5MH.js → routing-quote-AHLAREXR.js} +16 -18
  198. package/dist/{run-4SHEOBIU.js → run-JH7ELYAM.js} +41 -38
  199. package/dist/{runtime-BABJMHY7.js → runtime-2GX4ALJP.js} +12 -12
  200. package/dist/{runtime-activate-N6VLQI2C.js → runtime-activate-IDQ2NCSP.js} +9 -9
  201. package/dist/{runtime-launchers-GMAUICRW.js → runtime-launchers-YAPKCBHV.js} +7 -7
  202. package/dist/{runtime-place-DOEWFTF3.js → runtime-place-4POL4KK4.js} +3 -3
  203. package/dist/{send-ECXS6JEO.js → send-ELXFKEKY.js} +17 -17
  204. package/dist/{status-AHE5HSR7.js → status-FXUFWJDM.js} +89 -36
  205. package/dist/status-FXUFWJDM.js.map +1 -0
  206. package/dist/{status-line-63XFJAXR.js → status-line-IH5JBWBC.js} +11 -11
  207. package/dist/{streamableHttp-Z3YF6LTQ.js → streamableHttp-CP2ZQBIK.js} +4 -4
  208. package/dist/{uninstall-YGQPRCVY.js → uninstall-LJZUKM4D.js} +42 -38
  209. package/dist/{uninstall-YGQPRCVY.js.map → uninstall-LJZUKM4D.js.map} +1 -1
  210. package/dist/{update-GTLMLFA3.js → update-EUIX72IX.js} +34 -30
  211. package/dist/{usage-FCWP2CHO.js → usage-EKDC7LUC.js} +13 -13
  212. package/dist/{usdc-25RNBYYR.js → usdc-YIHK2OMC.js} +5 -5
  213. package/dist/{viemAdapter-By13KInL-3CG63XDX.js → viemAdapter-By13KInL-PRLSIESK.js} +2 -2
  214. package/dist/viemAdapter-By13KInL-PRLSIESK.js.map +1 -0
  215. package/dist/wallet-HSW757W6.js +80 -0
  216. package/dist/wallet-HSW757W6.js.map +1 -0
  217. package/docs/agent-permissions.md +19 -11
  218. package/docs/router-reference.md +21 -12
  219. package/docs/safety-model.md +4 -2
  220. package/docs/subagents-internals.md +97 -0
  221. package/docs/subagents.md +348 -0
  222. package/package.json +4 -1
  223. package/dist/balance-RQW5T5FB.js +0 -55
  224. package/dist/chunk-3X4GOMXT.js.map +0 -1
  225. package/dist/chunk-46HAB26L.js.map +0 -1
  226. package/dist/chunk-56SOPRM2.js.map +0 -1
  227. package/dist/chunk-5VWQSCDO.js.map +0 -1
  228. package/dist/chunk-6J64MQFD.js.map +0 -1
  229. package/dist/chunk-7U3P4PB7.js.map +0 -1
  230. package/dist/chunk-APWELUI7.js.map +0 -1
  231. package/dist/chunk-E6VP6MQM.js.map +0 -1
  232. package/dist/chunk-EQZ2CCWC.js.map +0 -1
  233. package/dist/chunk-FHXTEVO7.js.map +0 -1
  234. package/dist/chunk-FOEPH67T.js.map +0 -1
  235. package/dist/chunk-IVXPIIZJ.js +0 -91
  236. package/dist/chunk-IVXPIIZJ.js.map +0 -1
  237. package/dist/chunk-JF4T4HCQ.js.map +0 -1
  238. package/dist/chunk-LPQNZKSG.js +0 -269
  239. package/dist/chunk-LPQNZKSG.js.map +0 -1
  240. package/dist/chunk-MXN2ZEUB.js.map +0 -1
  241. package/dist/chunk-OO6FIBL7.js.map +0 -1
  242. package/dist/chunk-PNHNXUSL.js.map +0 -1
  243. package/dist/chunk-PYVQ74D5.js.map +0 -1
  244. package/dist/chunk-PZHBPGDE.js.map +0 -1
  245. package/dist/chunk-QEZZDIQT.js.map +0 -1
  246. package/dist/chunk-QXP3Z3JN.js.map +0 -1
  247. package/dist/chunk-RJ5HRPAZ.js.map +0 -1
  248. package/dist/chunk-TSIID2LV.js.map +0 -1
  249. package/dist/chunk-UVDJ5SSQ.js.map +0 -1
  250. package/dist/chunk-VFKPIIV2.js.map +0 -1
  251. package/dist/chunk-VH7JMLTG.js.map +0 -1
  252. package/dist/claude-install-7CVYQ73E.js +0 -60
  253. package/dist/cli-BFDKEX53.js.map +0 -1
  254. package/dist/codex-install-GTGO5FYN.js.map +0 -1
  255. package/dist/doctor-4MMHBRDU.js.map +0 -1
  256. package/dist/fund-MLXUH24Q.js.map +0 -1
  257. package/dist/mcp-CC3H7LFO.js +0 -3655
  258. package/dist/mcp-CC3H7LFO.js.map +0 -1
  259. package/dist/status-AHE5HSR7.js.map +0 -1
  260. package/dist/wallet-CJGEHP2Q.js +0 -64
  261. /package/dist/{_esm-MMYV66AX.js.map → _esm-2KST7HQ7.js.map} +0 -0
  262. /package/dist/{alive-VOIL5W3I.js.map → alive-5TV22PNF.js.map} +0 -0
  263. /package/dist/{auth-UHD3QFX4.js.map → auth-XI7BJFLW.js.map} +0 -0
  264. /package/dist/{balance-RQW5T5FB.js.map → balance-DFHC6XEU.js.map} +0 -0
  265. /package/dist/{ccip-CS7K5QRQ.js.map → ccip-HOW3DZYF.js.map} +0 -0
  266. /package/dist/{chunk-FSYH7J75.js.map → chunk-3Y6BHIN6.js.map} +0 -0
  267. /package/dist/{chunk-FZZWTDWP.js.map → chunk-3YPL6T3P.js.map} +0 -0
  268. /package/dist/{chunk-JEZMWJEF.js.map → chunk-44MVIRZH.js.map} +0 -0
  269. /package/dist/{chunk-27FIHFXF.js.map → chunk-45MMSBHA.js.map} +0 -0
  270. /package/dist/{chunk-7JB6SYJX.js.map → chunk-54ELBTKE.js.map} +0 -0
  271. /package/dist/{chunk-HWZO6HYZ.js.map → chunk-6QMDUDF2.js.map} +0 -0
  272. /package/dist/{chunk-FNBGRKS6.js.map → chunk-7V25UAQO.js.map} +0 -0
  273. /package/dist/{chunk-JOKPBYXP.js.map → chunk-DTEWAVNE.js.map} +0 -0
  274. /package/dist/{chunk-KAILF7QA.js.map → chunk-F43CV6UC.js.map} +0 -0
  275. /package/dist/{chunk-ACO7ZCR2.js.map → chunk-FKVJKLPI.js.map} +0 -0
  276. /package/dist/{chunk-2F5JUAHZ.js.map → chunk-GAJC4BQZ.js.map} +0 -0
  277. /package/dist/{chunk-L7N73ZAW.js.map → chunk-HAZAN4UM.js.map} +0 -0
  278. /package/dist/{chunk-6QJZA6EX.js.map → chunk-HI5XQOX2.js.map} +0 -0
  279. /package/dist/{chunk-BOENA6XR.js.map → chunk-HKGUKAQW.js.map} +0 -0
  280. /package/dist/{chunk-LJSCGIYH.js.map → chunk-HPRVFJPM.js.map} +0 -0
  281. /package/dist/{chunk-SDUOJRSV.js.map → chunk-IGLWLH73.js.map} +0 -0
  282. /package/dist/{chunk-3AKH7ODX.js.map → chunk-INSIW65E.js.map} +0 -0
  283. /package/dist/{chunk-2P3NJTHE.js.map → chunk-JHFFUVON.js.map} +0 -0
  284. /package/dist/{chunk-2TO5F6CT.js.map → chunk-K5KNGC4I.js.map} +0 -0
  285. /package/dist/{chunk-HUWTFKEM.js.map → chunk-KAQ4Q3TO.js.map} +0 -0
  286. /package/dist/{chunk-GS5RZF7U.js.map → chunk-KLDMLWXT.js.map} +0 -0
  287. /package/dist/{chunk-HN2EN6P4.js.map → chunk-KNKDMTHU.js.map} +0 -0
  288. /package/dist/{chunk-R2KMLONN.js.map → chunk-MJDO4EXD.js.map} +0 -0
  289. /package/dist/{chunk-IHVUE3XF.js.map → chunk-NJA6NT3A.js.map} +0 -0
  290. /package/dist/{chunk-S3JKF3IK.js.map → chunk-OJJFANO6.js.map} +0 -0
  291. /package/dist/{chunk-GGGEGMWC.js.map → chunk-Q6RSJCXB.js.map} +0 -0
  292. /package/dist/{chunk-OTIUEUIS.js.map → chunk-QKEUKBRK.js.map} +0 -0
  293. /package/dist/{chunk-X52BVGCJ.js.map → chunk-QQDPRTLP.js.map} +0 -0
  294. /package/dist/{chunk-6AQSUBNR.js.map → chunk-RGCPELQN.js.map} +0 -0
  295. /package/dist/{chunk-LQ33RLHL.js.map → chunk-TFT2X7SH.js.map} +0 -0
  296. /package/dist/{chunk-IVHGQNIN.js.map → chunk-VHXCPXUS.js.map} +0 -0
  297. /package/dist/{chunk-7DW7GAM6.js.map → chunk-VU6GMWF6.js.map} +0 -0
  298. /package/dist/{chunk-YU3DLVSQ.js.map → chunk-XSCGUO2U.js.map} +0 -0
  299. /package/dist/{chunk-EPCIJLLU.js.map → chunk-XWROSMI5.js.map} +0 -0
  300. /package/dist/{chunk-HMT6L65V.js.map → chunk-YJGEVBKZ.js.map} +0 -0
  301. /package/dist/{chunk-I47ARU5G.js.map → chunk-ZS7JIUJ3.js.map} +0 -0
  302. /package/dist/{claude-cli-2YKABJJZ.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
  303. /package/dist/{claude-install-7CVYQ73E.js.map → claude-install-BAUSJMW3.js.map} +0 -0
  304. /package/dist/{client-XMWEKXX7.js.map → client-3YQKORVK.js.map} +0 -0
  305. /package/dist/{codex-host-B6NAUWL6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
  306. /package/dist/{config-THJANIU5.js.map → config-QZOBMTEL.js.map} +0 -0
  307. /package/dist/{config-names-JU54HYWY.js.map → config-names-Z5NZD5R2.js.map} +0 -0
  308. /package/dist/{config-rules-VNU23RL4.js.map → config-rules-YOYHS6YL.js.map} +0 -0
  309. /package/dist/{decision-JIIHDTOF.js.map → decision-QSKHOGCO.js.map} +0 -0
  310. /package/dist/{hook-command-UB7FOEUL.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
  311. /package/dist/{hosts-WNQKYKP2.js.map → hook-command-VZ27MGWO.js.map} +0 -0
  312. /package/dist/{install-Q5SHHEDH.js.map → hosts-3EMTVM4H.js.map} +0 -0
  313. /package/dist/{install-funding-EGSW2KEP.js.map → install-ZA7L2UF3.js.map} +0 -0
  314. /package/dist/{install-identity-OID43B4D.js.map → install-funding-JDGYTF72.js.map} +0 -0
  315. /package/dist/{package-NRHU7HBR.js.map → install-identity-FFAYEFLX.js.map} +0 -0
  316. /package/dist/{passphrase-3JEVW5XG.js.map → new-install-5L4GY3LN.js.map} +0 -0
  317. /package/dist/{pay-I47AIUQR.js.map → package-BONDXSV3.js.map} +0 -0
  318. /package/dist/{routing-quote-QQW2I5MH.js.map → passphrase-T4ULBN4M.js.map} +0 -0
  319. /package/dist/{run-4SHEOBIU.js.map → pay-CMV5KL74.js.map} +0 -0
  320. /package/dist/{payments-A5FNI5GN.js.map → payments-Z6UBZL4Z.js.map} +0 -0
  321. /package/dist/{runtime-activate-N6VLQI2C.js.map → routing-quote-AHLAREXR.js.map} +0 -0
  322. /package/dist/{runtime-launchers-GMAUICRW.js.map → run-JH7ELYAM.js.map} +0 -0
  323. /package/dist/{runtime-BABJMHY7.js.map → runtime-2GX4ALJP.js.map} +0 -0
  324. /package/dist/{runtime-place-DOEWFTF3.js.map → runtime-activate-IDQ2NCSP.js.map} +0 -0
  325. /package/dist/{update-GTLMLFA3.js.map → runtime-launchers-YAPKCBHV.js.map} +0 -0
  326. /package/dist/{usdc-25RNBYYR.js.map → runtime-place-4POL4KK4.js.map} +0 -0
  327. /package/dist/{send-ECXS6JEO.js.map → send-ELXFKEKY.js.map} +0 -0
  328. /package/dist/{status-line-63XFJAXR.js.map → status-line-IH5JBWBC.js.map} +0 -0
  329. /package/dist/{streamableHttp-Z3YF6LTQ.js.map → streamableHttp-CP2ZQBIK.js.map} +0 -0
  330. /package/dist/{viemAdapter-By13KInL-3CG63XDX.js.map → update-EUIX72IX.js.map} +0 -0
  331. /package/dist/{usage-FCWP2CHO.js.map → usage-EKDC7LUC.js.map} +0 -0
  332. /package/dist/{wallet-CJGEHP2Q.js.map → usdc-YIHK2OMC.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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AmB;AAAA,MACvC,WAAW,OAAO;AAAA,MAClB,gBAAgB,OAAO;AAAA,MACvB,qBAAqB,OAAO;AAAA,IAC9B,GAAG;AACD,YAAM,SAAS,MAAMC,OAAM,WAAW,EAAE;AAAA,QACtC,MAAM;AAAA,QACN,CAAC,UAAiC;AAChC,cAAI,MAAM,SAAS,SAAU,QAAO;AACpC,gBAAM;AAAA,QACR;AAAA,MACF;AACA,UAAI,OAAQ,QAAO;AAAA,IACrB;AACA,WAAO,UAAU;AAAA,EACnB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,eAAsB,wBACpB,SACqC;AACrC,MAAI,QAAQ,aAAa,QAAS,QAAO;AACzC,QAAM,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,QAA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import {
7
7
  } from "./chunk-DI4QAGRZ.js";
8
8
  import {
9
9
  package_default
10
- } from "./chunk-EQZ2CCWC.js";
10
+ } from "./chunk-3Y2EHT4F.js";
11
11
 
12
12
  // src/lib/client-meta.ts
13
13
  var TENJIN_PRODUCT = `tenjin-cli/${package_default.version}`;
@@ -323,4 +323,4 @@ export {
323
323
  httpRequest,
324
324
  fetchFailureToCliError
325
325
  };
326
- //# sourceMappingURL=chunk-MXN2ZEUB.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;AACnC,MAAI,SAAS,WAAW,EAAG,QAAO;AAClC,QAAM,WAAW,GAAG,cAAc,IAAI,SAAS,KAAK,GAAG,CAAC,IAAI,cAAc;AAC1E,SAAO,SAAS,UAAU,wBAAwB,WAAW;AAC/D;AAGA,SAAS,eAAe,KAAmC;AACzD,MAAI,QAAQ,UAAa,CAAC,mBAAmB,KAAK,GAAG,EAAG,QAAO,CAAC;AAGhE,QAAM,SAAS,IAAI,MAAM,GAAG,EAAE,OAAO,CAAC,UAAU,MAAM,SAAS,KAAK,CAAC,cAAc,KAAK,CAAC;AACzF,SAAO,OAAO,MAAM,CAAC,UAAU,WAAW,KAAK,KAAK,CAAC,IAAI,SAAS,CAAC;AACrE;AAMA,SAAS,cAAc,OAAwB;AAC7C,QAAM,QAAQ,MAAM,YAAY;AAEhC,MAAI,UAAU,eAAe,YAAY,EAAG,QAAO;AACnD,SAAO,kBAAkB,KAAK,CAAC,SAAS;AACtC,UAAM,MAAM,KAAK,YAAY;AAC7B,WAAO,UAAU,OAAO,MAAM,WAAW,GAAG,GAAG,GAAG;AAAA,EACpD,CAAC;AACH;;;ACxFA,IAAM,2BAA2B;AAG1B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AAI,IAAI,EAAG,QAAO,EAAE,OAAO,OAAO,KAAK;AACrD,UAAI,SAAS,KAAK,IAAI,EAAG,QAAO,EAAE,OAAO,OAAO,KAAK;AACrD,UAAI,cAAc,IAAI,IAAI,EAAG,QAAO,EAAE,OAAO,WAAW,KAAK;AAAA,IAC/D;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAYA,SAAS,uBAAuB,KAA+B;AAC7D,MAAI,SAAS;AACb,MAAI;AACF,aAAS,IAAI,IAAI,GAAG,EAAE;AAAA,EACxB,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SACE,GAAG,MAAM;AAAA,EAGb;AACF;","names":[]}
@@ -0,0 +1,78 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ style
4
+ } from "./chunk-KLDMLWXT.js";
5
+
6
+ // src/lib/live-line.ts
7
+ var FRAMES = "\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F";
8
+ var FRAME_MS = 80;
9
+ var DETAIL_COLUMN = 26;
10
+ var CLEAR_LINE = "\r\x1B[2K";
11
+ function liveLine(stream, opts = {}) {
12
+ const tty = opts.tty ?? stream.isTTY === true;
13
+ const every = opts.setInterval ?? ((fn, ms) => setInterval(fn, ms).unref());
14
+ const cancel = opts.clearInterval ?? ((h) => clearInterval(h));
15
+ const paint = (format, text) => style(format, text, stream);
16
+ const write = (text) => {
17
+ try {
18
+ stream.write(text);
19
+ } catch {
20
+ }
21
+ };
22
+ let timer;
23
+ let frame = 0;
24
+ let current;
25
+ let lastPlain;
26
+ const draw = () => {
27
+ if (current === void 0) return;
28
+ const glyph = paint("blue", FRAMES[frame % FRAMES.length]);
29
+ const aside = current.aside !== void 0 ? ` ${paint("dim", current.aside)}` : "";
30
+ write(`${CLEAR_LINE} ${glyph} ${current.text}${aside}`);
31
+ frame++;
32
+ };
33
+ const clear = () => {
34
+ if (timer !== void 0) {
35
+ cancel(timer);
36
+ timer = void 0;
37
+ }
38
+ if (tty && current !== void 0) write(CLEAR_LINE);
39
+ current = void 0;
40
+ };
41
+ const keep = (text) => {
42
+ clear();
43
+ write(`${text}
44
+ `);
45
+ };
46
+ return {
47
+ spin(text, aside) {
48
+ if (!tty) {
49
+ if (lastPlain !== text) write(` \u2026 ${text}${aside !== void 0 ? ` ${aside}` : ""}
50
+ `);
51
+ lastPlain = text;
52
+ return;
53
+ }
54
+ current = { text, ...aside !== void 0 ? { aside } : {} };
55
+ if (timer === void 0) timer = every(draw, FRAME_MS);
56
+ draw();
57
+ },
58
+ ok(text, detail) {
59
+ lastPlain = void 0;
60
+ const pad = " ".repeat(Math.max(2, DETAIL_COLUMN - text.length));
61
+ keep(` ${paint("green", "\u2713")} ${text}${detail !== void 0 ? `${pad}${detail}` : ""}`);
62
+ },
63
+ warn(text) {
64
+ lastPlain = void 0;
65
+ keep(` ${paint("yellow", "!")} ${text}`);
66
+ },
67
+ line(text) {
68
+ lastPlain = void 0;
69
+ keep(text);
70
+ },
71
+ stop: clear
72
+ };
73
+ }
74
+
75
+ export {
76
+ liveLine
77
+ };
78
+ //# sourceMappingURL=chunk-DJ36BM62.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/live-line.ts"],"sourcesContent":["import { style, type StyleFormat } from './output';\n\n/**\n * ONE STATUS LINE THAT REWRITES ITSELF IN PLACE, for a wait a person watches\n * (`tenjin fund`, `tenjin balance --wait`). On a terminal the current state\n * spins with braille frames every 80 ms and is replaced by the next; a state\n * that is done is printed as a `✓` line that stays. Anywhere else (stderr\n * redirected to a file) each new state is one plain `…` line, written once,\n * so a log reads as the same story without a frame per tick.\n *\n * Everything goes to the stream it is given (stderr): stdout keeps the\n * command's own result, and nothing here ever throws.\n */\n\nconst FRAMES = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';\nconst FRAME_MS = 80;\n/** Where a `✓` line's detail starts, so amounts line up under each other. */\nconst DETAIL_COLUMN = 26;\nconst CLEAR_LINE = '\\r\\x1b[2K';\n\nexport interface LiveLine {\n /** The state now in progress, with an optional quiet aside (the link's time left). */\n spin(text: string, aside?: string): void;\n /** A finished state, kept on screen: `✓ text detail`. */\n ok(text: string, detail?: string): void;\n /** A state that needs a word but is not a failure of this command: `! text`. */\n warn(text: string): void;\n /** Any other line, kept on screen. */\n line(text: string): void;\n /** Clear the spinning line, if any. Safe to call twice. */\n stop(): void;\n}\n\nexport interface LiveLineOptions {\n /** Draw frames in place. Defaults to the stream's own `isTTY`. */\n tty?: boolean;\n /** Test seams for the frame timer. */\n setInterval?: (fn: () => void, ms: number) => unknown;\n clearInterval?: (handle: unknown) => void;\n}\n\nexport function liveLine(stream: NodeJS.WritableStream, opts: LiveLineOptions = {}): LiveLine {\n const tty = opts.tty ?? (stream as { isTTY?: unknown }).isTTY === true;\n const every = opts.setInterval ?? ((fn, ms) => setInterval(fn, ms).unref());\n const cancel = opts.clearInterval ?? ((h) => clearInterval(h as NodeJS.Timeout));\n const paint = (format: StyleFormat, text: string) => style(format, text, stream);\n const write = (text: string) => {\n try {\n stream.write(text);\n } catch {\n // A status line that cannot be drawn changes nothing about the wait.\n }\n };\n\n let timer: unknown;\n let frame = 0;\n let current: { text: string; aside?: string } | undefined;\n let lastPlain: string | undefined;\n\n const draw = () => {\n if (current === undefined) return;\n const glyph = paint('blue', FRAMES[frame % FRAMES.length]!);\n const aside = current.aside !== undefined ? ` ${paint('dim', current.aside)}` : '';\n write(`${CLEAR_LINE} ${glyph} ${current.text}${aside}`);\n frame++;\n };\n const clear = () => {\n if (timer !== undefined) {\n cancel(timer);\n timer = undefined;\n }\n if (tty && current !== undefined) write(CLEAR_LINE);\n current = undefined;\n };\n const keep = (text: string) => {\n clear();\n write(`${text}\\n`);\n };\n\n return {\n spin(text, aside) {\n if (!tty) {\n if (lastPlain !== text) write(` … ${text}${aside !== undefined ? ` ${aside}` : ''}\\n`);\n lastPlain = text;\n return;\n }\n current = { text, ...(aside !== undefined ? { aside } : {}) };\n if (timer === undefined) timer = every(draw, FRAME_MS);\n draw();\n },\n ok(text, detail) {\n lastPlain = undefined;\n const pad = ' '.repeat(Math.max(2, DETAIL_COLUMN - text.length));\n keep(` ${paint('green', '✓')} ${text}${detail !== undefined ? `${pad}${detail}` : ''}`);\n },\n warn(text) {\n lastPlain = undefined;\n keep(` ${paint('yellow', '!')} ${text}`);\n },\n line(text) {\n lastPlain = undefined;\n keep(text);\n },\n stop: clear,\n };\n}\n"],"mappings":";;;;;;AAcA,IAAM,SAAS;AACf,IAAM,WAAW;AAEjB,IAAM,gBAAgB;AACtB,IAAM,aAAa;AAuBZ,SAAS,SAAS,QAA+B,OAAwB,CAAC,GAAa;AAC5F,QAAM,MAAM,KAAK,OAAQ,OAA+B,UAAU;AAClE,QAAM,QAAQ,KAAK,gBAAgB,CAAC,IAAI,OAAO,YAAY,IAAI,EAAE,EAAE,MAAM;AACzE,QAAM,SAAS,KAAK,kBAAkB,CAAC,MAAM,cAAc,CAAmB;AAC9E,QAAM,QAAQ,CAAC,QAAqB,SAAiB,MAAM,QAAQ,MAAM,MAAM;AAC/E,QAAM,QAAQ,CAAC,SAAiB;AAC9B,QAAI;AACF,aAAO,MAAM,IAAI;AAAA,IACnB,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,MAAI;AACJ,MAAI,QAAQ;AACZ,MAAI;AACJ,MAAI;AAEJ,QAAM,OAAO,MAAM;AACjB,QAAI,YAAY,OAAW;AAC3B,UAAM,QAAQ,MAAM,QAAQ,OAAO,QAAQ,OAAO,MAAM,CAAE;AAC1D,UAAM,QAAQ,QAAQ,UAAU,SAAY,KAAK,MAAM,OAAO,QAAQ,KAAK,CAAC,KAAK;AACjF,UAAM,GAAG,UAAU,KAAK,KAAK,IAAI,QAAQ,IAAI,GAAG,KAAK,EAAE;AACvD;AAAA,EACF;AACA,QAAM,QAAQ,MAAM;AAClB,QAAI,UAAU,QAAW;AACvB,aAAO,KAAK;AACZ,cAAQ;AAAA,IACV;AACA,QAAI,OAAO,YAAY,OAAW,OAAM,UAAU;AAClD,cAAU;AAAA,EACZ;AACA,QAAM,OAAO,CAAC,SAAiB;AAC7B,UAAM;AACN,UAAM,GAAG,IAAI;AAAA,CAAI;AAAA,EACnB;AAEA,SAAO;AAAA,IACL,KAAK,MAAM,OAAO;AAChB,UAAI,CAAC,KAAK;AACR,YAAI,cAAc,KAAM,OAAM,YAAO,IAAI,GAAG,UAAU,SAAY,KAAK,KAAK,KAAK,EAAE;AAAA,CAAI;AACvF,oBAAY;AACZ;AAAA,MACF;AACA,gBAAU,EAAE,MAAM,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC,EAAG;AAC5D,UAAI,UAAU,OAAW,SAAQ,MAAM,MAAM,QAAQ;AACrD,WAAK;AAAA,IACP;AAAA,IACA,GAAG,MAAM,QAAQ;AACf,kBAAY;AACZ,YAAM,MAAM,IAAI,OAAO,KAAK,IAAI,GAAG,gBAAgB,KAAK,MAAM,CAAC;AAC/D,WAAK,KAAK,MAAM,SAAS,QAAG,CAAC,IAAI,IAAI,GAAG,WAAW,SAAY,GAAG,GAAG,GAAG,MAAM,KAAK,EAAE,EAAE;AAAA,IACzF;AAAA,IACA,KAAK,MAAM;AACT,kBAAY;AACZ,WAAK,KAAK,MAAM,UAAU,GAAG,CAAC,IAAI,IAAI,EAAE;AAAA,IAC1C;AAAA,IACA,KAAK,MAAM;AACT,kBAAY;AACZ,WAAK,IAAI;AAAA,IACX;AAAA,IACA,MAAM;AAAA,EACR;AACF;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  SEND_MAX_UNSET,
4
4
  loadRawConfig,
5
5
  resolveSettings
6
- } from "./chunk-VH7JMLTG.js";
6
+ } from "./chunk-UIB33QQP.js";
7
7
 
8
8
  // src/lib/settings.ts
9
9
  import { readFile, stat } from "node:fs/promises";
@@ -111,4 +111,4 @@ export {
111
111
  projectRoot,
112
112
  pathExists
113
113
  };
114
- //# sourceMappingURL=chunk-JOKPBYXP.js.map
114
+ //# sourceMappingURL=chunk-DTEWAVNE.js.map
@@ -0,0 +1,13 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/router/gate.ts
4
+ var GATE_TIMEOUT_MS = 3500;
5
+ var UNPAID_GATE_TIMEOUT_MS = 3500;
6
+ var DEPOSIT_GATE_TIMEOUT_MS = 4500;
7
+
8
+ export {
9
+ GATE_TIMEOUT_MS,
10
+ UNPAID_GATE_TIMEOUT_MS,
11
+ DEPOSIT_GATE_TIMEOUT_MS
12
+ };
13
+ //# sourceMappingURL=chunk-F2KJAJ7T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/gate.ts"],"sourcesContent":["/**\n * THE HOOK'S TIME BUDGET, which is the only thing this module still owns.\n *\n * There is no separate gate call any more: the hook asks the paid route,\n * `POST /api/x402-router/route`, for the one decision, and the backend answers\n * as soon as the native-versus-paid question is settled, binding whatever it\n * chose in the background. What used to live here, the `/prepare` client and the\n * category-shaped hint validator, went with that second round trip.\n */\n\n/**\n * The hook's whole budget is 5 s (`ROUTE_HOOK_TIMEOUT_SECONDS`, the timeout\n * `install` writes for each routing leg), and a paid decision gets 3.5 s of it.\n * Inside `tenjin mcp` those 3.5 s hold the paid route too: the 402, the SDK's\n * chain read and the paid request, or a wait for the background top-up that\n * funds the channel (`routing-payer.ts`). 1.5 s are left for startup, the\n * transcript read and the reply, and 500 ms on a call that carries a deposit,\n * which only a router with no `warm` form gets ({@link DEPOSIT_GATE_TIMEOUT_MS});\n * `wire.test.ts` pins the sums.\n * The expected wait is about 1 s: the backend answers on the gate question and\n * binds afterwards.\n *\n * AN ABORT HERE IS A LOST HINT, not a lost turn. The hook falls back to one\n * line telling the model to call `request` with its own query, and the tool\n * makes the decision instead. One of four live prompts was swallowed at a 1.5 s\n * abort against a backend measured at 0.4 to 0.5 s, so this holds the slack the\n * harness budget was already leaving unused.\n */\nexport const GATE_TIMEOUT_MS = 3_500;\n\n/** A hook without the MCP payer keeps the same 3.5 s decision wait.\n * The server gets only the time left when the decision request is sent. */\nexport const UNPAID_GATE_TIMEOUT_MS = 3_500;\n\n/**\n * A CALL THAT CARRIES A DEPOSIT gets the rest of the hook leg instead: the\n * first paid call on a channel waits on verify, the gate and the on-chain\n * deposit in a row (5.0 s measured on Base), so 3.5 s cut it short. It is the\n * leg's 5 s less the 500 ms for startup, the transcript read and the reply,\n * so the leg still never runs past the timeout `install` writes; `wire.test.ts`\n * pins that. A leg carries a deposit only while the router has no `warm`\n * form: otherwise the background top-up makes every deposit.\n */\nexport const DEPOSIT_GATE_TIMEOUT_MS = 4_500;\n"],"mappings":";;;AA4BO,IAAM,kBAAkB;AAIxB,IAAM,yBAAyB;AAW/B,IAAM,0BAA0B;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  package_default
4
- } from "./chunk-EQZ2CCWC.js";
4
+ } from "./chunk-3Y2EHT4F.js";
5
5
 
6
6
  // src/router/mcp-processes.ts
7
7
  import { execFile } from "node:child_process";
@@ -195,4 +195,4 @@ export {
195
195
  readProcessSnapshot,
196
196
  readMcpServers
197
197
  };
198
- //# sourceMappingURL=chunk-KAILF7QA.js.map
198
+ //# sourceMappingURL=chunk-F43CV6UC.js.map
@@ -28,7 +28,7 @@ var o = [{
28
28
  async function s(e) {
29
29
  let a3;
30
30
  try {
31
- a3 = await import("./_esm-MMYV66AX.js");
31
+ a3 = await import("./_esm-2KST7HQ7.js");
32
32
  } catch {
33
33
  throw new r(i.MISSING_PROVIDER_LIBRARY, "viem installed (npm install viem)", "viem not found");
34
34
  }
@@ -67,4 +67,4 @@ export {
67
67
  a2 as a,
68
68
  s
69
69
  };
70
- //# sourceMappingURL=chunk-ACO7ZCR2.js.map
70
+ //# sourceMappingURL=chunk-FKVJKLPI.js.map
@@ -5,7 +5,7 @@ import {
5
5
  emptyLedger,
6
6
  readLedger,
7
7
  spentOf
8
- } from "./chunk-LJSCGIYH.js";
8
+ } from "./chunk-HPRVFJPM.js";
9
9
  import {
10
10
  withFileLock
11
11
  } from "./chunk-2W4DQQUU.js";
@@ -184,9 +184,60 @@ async function releaseUnchargedExposure(dir, nonce, opts = {}) {
184
184
  return null;
185
185
  }
186
186
  }
187
+ async function creditRefundedExposure(dir, run, refundedAtomic, opts = {}) {
188
+ const path = spendLedgerPath(dir);
189
+ const nowMs = (opts.now ?? Date.now)();
190
+ try {
191
+ return await withFileLock(`${path}.lock`, async () => {
192
+ const { ledger } = await readLedger(path);
193
+ if (ledger === null || nowMs - ledger.windowStartMs >= (opts.windowMs ?? DEFAULT_WINDOW_MS)) {
194
+ return 0n;
195
+ }
196
+ const exposures = ledger.exposures ?? [];
197
+ const own = exposures.filter((e) => e.nonce.startsWith(run.prefix) && e.mode !== "manual");
198
+ if (own.length === 0) return 0n;
199
+ const counted = own.reduce((sum, e) => sum + BigInt(e.amountAtomic), 0n);
200
+ const amount = refundedAtomic < counted ? refundedAtomic : counted;
201
+ const less = (value, fallback) => {
202
+ const current = BigInt(value ?? fallback);
203
+ return (current > amount ? current - amount : 0n).toString();
204
+ };
205
+ await writeFileAtomic(
206
+ path,
207
+ `${JSON.stringify(
208
+ {
209
+ ...ledger,
210
+ committedAtomic: less(ledger.committedAtomic, "0"),
211
+ automaticCommittedAtomic: less(ledger.automaticCommittedAtomic, ledger.committedAtomic),
212
+ settledAtomic: less(ledger.settledAtomic, ledger.committedAtomic),
213
+ exposures: [
214
+ ...exposures.filter((e) => !own.includes(e)),
215
+ ...counted > amount ? [
216
+ {
217
+ nonce: run.kept,
218
+ amountAtomic: (counted - amount).toString(),
219
+ atMs: nowMs,
220
+ mode: "automatic"
221
+ }
222
+ ] : []
223
+ ]
224
+ },
225
+ null,
226
+ 2
227
+ )}
228
+ `,
229
+ { mode: 384, dirMode: 448 }
230
+ );
231
+ return amount;
232
+ });
233
+ } catch {
234
+ return null;
235
+ }
236
+ }
187
237
 
188
238
  export {
189
239
  createLocalSpendAuthorizer,
190
- releaseUnchargedExposure
240
+ releaseUnchargedExposure,
241
+ creditRefundedExposure
191
242
  };
192
- //# sourceMappingURL=chunk-43HLS2HM.js.map
243
+ //# sourceMappingURL=chunk-FYFHH7V5.js.map