tenjin-cli 0.1.0-alpha.31 → 0.1.0-alpha.32

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 (258) hide show
  1. package/README.md +5 -5
  2. package/dist/{_esm-MEXZI5DL.js → _esm-RLLC72MS.js} +128 -132
  3. package/dist/{alive-J64H46HI.js → alive-MROUMFH3.js} +13 -6
  4. package/dist/auto-update-OPWMRZLS.js +22 -0
  5. package/dist/{ccip-7RMRLAGV.js → ccip-DHDFKTQV.js} +2 -2
  6. package/dist/chunk-2GNOFONN.js +560 -0
  7. package/dist/chunk-2GNOFONN.js.map +1 -0
  8. package/dist/{chunk-TTNESUPQ.js → chunk-2GP3HRYK.js} +2120 -193
  9. package/dist/chunk-2GP3HRYK.js.map +1 -0
  10. package/dist/chunk-3AIHRXKO.js +72 -0
  11. package/dist/chunk-3AIHRXKO.js.map +1 -0
  12. package/dist/{chunk-LEFIX6RS.js → chunk-3DIL66VX.js} +31 -11
  13. package/dist/chunk-3DIL66VX.js.map +1 -0
  14. package/dist/{chunk-S4SAZ7OD.js → chunk-3FMZGI7I.js} +12 -2
  15. package/dist/{chunk-S4SAZ7OD.js.map → chunk-3FMZGI7I.js.map} +1 -1
  16. package/dist/{chunk-7Q5FDF65.js → chunk-445VQTVM.js} +3 -3
  17. package/dist/{chunk-A36LQPHV.js → chunk-4LMUQMBH.js} +1 -1
  18. package/dist/{chunk-A36LQPHV.js.map → chunk-4LMUQMBH.js.map} +1 -1
  19. package/dist/{chunk-KXQ4UIP7.js → chunk-4USCZ2NI.js} +2 -2
  20. package/dist/chunk-62KNUYWD.js +111 -0
  21. package/dist/chunk-62KNUYWD.js.map +1 -0
  22. package/dist/{chunk-POUWHWID.js → chunk-6CMM6YCB.js} +3 -3
  23. package/dist/{chunk-POUWHWID.js.map → chunk-6CMM6YCB.js.map} +1 -1
  24. package/dist/{chunk-5MARFNSB.js → chunk-AD226HDR.js} +49 -30
  25. package/dist/chunk-AD226HDR.js.map +1 -0
  26. package/dist/chunk-ADV4LDTB.js +106 -0
  27. package/dist/chunk-ADV4LDTB.js.map +1 -0
  28. package/dist/{chunk-7WU4OPLP.js → chunk-AV5NZMYO.js} +5 -3
  29. package/dist/{chunk-7WU4OPLP.js.map → chunk-AV5NZMYO.js.map} +1 -1
  30. package/dist/chunk-B7EM4GGF.js +198 -0
  31. package/dist/chunk-B7EM4GGF.js.map +1 -0
  32. package/dist/chunk-BFDQ4WNW.js +119 -0
  33. package/dist/chunk-BFDQ4WNW.js.map +1 -0
  34. package/dist/{chunk-2XLC3AEX.js → chunk-BI673VEJ.js} +536 -510
  35. package/dist/chunk-BI673VEJ.js.map +1 -0
  36. package/dist/chunk-CEXSOI5R.js +808 -0
  37. package/dist/chunk-CEXSOI5R.js.map +1 -0
  38. package/dist/{chunk-FW75G2W4.js → chunk-CISYM4EO.js} +5 -5
  39. package/dist/{chunk-B7HUUJOK.js → chunk-D3ZURCG7.js} +3 -3
  40. package/dist/chunk-D5TOQSO4.js +474 -0
  41. package/dist/chunk-D5TOQSO4.js.map +1 -0
  42. package/dist/{chunk-UQUOVWBG.js → chunk-DRDUIZIA.js} +7 -7
  43. package/dist/{chunk-27EPWVOY.js → chunk-DW4YTVR3.js} +2 -2
  44. package/dist/chunk-E7LGOMH6.js +449 -0
  45. package/dist/chunk-E7LGOMH6.js.map +1 -0
  46. package/dist/{chunk-QSCPK4F5.js → chunk-E7SW44LM.js} +4 -11
  47. package/dist/chunk-E7SW44LM.js.map +1 -0
  48. package/dist/chunk-EDJWHDDL.js +33 -0
  49. package/dist/chunk-EDJWHDDL.js.map +1 -0
  50. package/dist/chunk-F3ED5WTR.js +13 -0
  51. package/dist/chunk-F3ED5WTR.js.map +1 -0
  52. package/dist/chunk-G75OPGAK.js +111 -0
  53. package/dist/chunk-G75OPGAK.js.map +1 -0
  54. package/dist/{chunk-R5LCN54M.js → chunk-GAKUQHKA.js} +13 -17
  55. package/dist/{chunk-R5LCN54M.js.map → chunk-GAKUQHKA.js.map} +1 -1
  56. package/dist/{chunk-4ZZO6ULA.js → chunk-HDPUXS3Z.js} +19 -48
  57. package/dist/chunk-HDPUXS3Z.js.map +1 -0
  58. package/dist/{chunk-ORWL5BSN.js → chunk-HGZEPQUT.js} +2 -2
  59. package/dist/{chunk-6E5R45ZO.js → chunk-HREHWL32.js} +4 -4
  60. package/dist/{chunk-6E5R45ZO.js.map → chunk-HREHWL32.js.map} +1 -1
  61. package/dist/{chunk-KXVP2VKA.js → chunk-I5TDIUKM.js} +15 -34
  62. package/dist/chunk-I5TDIUKM.js.map +1 -0
  63. package/dist/{chunk-7QKHZQKW.js → chunk-IADZOXKN.js} +39 -6
  64. package/dist/chunk-IADZOXKN.js.map +1 -0
  65. package/dist/{chunk-P4NH7OUK.js → chunk-IDTRSAHE.js} +2 -2
  66. package/dist/{chunk-YFPY4ONH.js → chunk-JEVQ5LKO.js} +4 -4
  67. package/dist/chunk-JNJWBTU2.js +3497 -0
  68. package/dist/chunk-JNJWBTU2.js.map +1 -0
  69. package/dist/{chunk-MNXS2U45.js → chunk-JRZBBPO6.js} +167 -86
  70. package/dist/chunk-JRZBBPO6.js.map +1 -0
  71. package/dist/{chunk-WJXLQXJY.js → chunk-MPZUYCAP.js} +4 -1
  72. package/dist/{chunk-WJXLQXJY.js.map → chunk-MPZUYCAP.js.map} +1 -1
  73. package/dist/{chunk-SJLTEINJ.js → chunk-OJNTCYQQ.js} +17 -1
  74. package/dist/chunk-OJNTCYQQ.js.map +1 -0
  75. package/dist/{chunk-AGZ7PJKY.js → chunk-OTWLERSW.js} +22 -5
  76. package/dist/chunk-OTWLERSW.js.map +1 -0
  77. package/dist/{chunk-NEFNKLBE.js → chunk-PJNENX2A.js} +1535 -422
  78. package/dist/chunk-PJNENX2A.js.map +1 -0
  79. package/dist/{chunk-UKY4CHNC.js → chunk-PKHI276N.js} +8 -4
  80. package/dist/chunk-PKHI276N.js.map +1 -0
  81. package/dist/{chunk-5K5W4S66.js → chunk-QF3LSMGS.js} +2 -2
  82. package/dist/{chunk-XZKD7DIF.js → chunk-RL5UUDT4.js} +3 -3
  83. package/dist/{chunk-XZKD7DIF.js.map → chunk-RL5UUDT4.js.map} +1 -1
  84. package/dist/{chunk-OHRR5OYM.js → chunk-SFASB5FL.js} +10 -4
  85. package/dist/chunk-SFASB5FL.js.map +1 -0
  86. package/dist/{chunk-YVFXE7RR.js → chunk-SNNSAGMT.js} +7279 -2627
  87. package/dist/chunk-SNNSAGMT.js.map +1 -0
  88. package/dist/{chunk-WK7F3B2E.js → chunk-SO3XRZPX.js} +3 -3
  89. package/dist/chunk-SYOS5CAC.js +176 -0
  90. package/dist/chunk-SYOS5CAC.js.map +1 -0
  91. package/dist/chunk-TAW4UFFF.js +293 -0
  92. package/dist/chunk-TAW4UFFF.js.map +1 -0
  93. package/dist/{hosts-FWZOV26H.js → chunk-TF5HCP33.js} +79 -24
  94. package/dist/chunk-TF5HCP33.js.map +1 -0
  95. package/dist/{chunk-AKWGE6JQ.js → chunk-UUGOUOVT.js} +37 -2
  96. package/dist/chunk-UUGOUOVT.js.map +1 -0
  97. package/dist/{chunk-7ZRL2LBQ.js → chunk-V2LQLN5H.js} +6 -6
  98. package/dist/{chunk-K72RURN3.js → chunk-VJUVFZ2D.js} +2 -2
  99. package/dist/{chunk-77TCKDEC.js → chunk-VOZA6O7K.js} +663 -477
  100. package/dist/chunk-VOZA6O7K.js.map +1 -0
  101. package/dist/{chunk-D65GNPS3.js → chunk-VUGQTZ2L.js} +208 -84
  102. package/dist/chunk-VUGQTZ2L.js.map +1 -0
  103. package/dist/chunk-WOM257PW.js +393 -0
  104. package/dist/chunk-WOM257PW.js.map +1 -0
  105. package/dist/chunk-WYXUQGOL.js +191 -0
  106. package/dist/chunk-WYXUQGOL.js.map +1 -0
  107. package/dist/chunk-X5ZBP3IY.js +97 -0
  108. package/dist/chunk-X5ZBP3IY.js.map +1 -0
  109. package/dist/{chunk-5C32RLTA.js → chunk-YUY4SAGM.js} +17 -2
  110. package/dist/chunk-YUY4SAGM.js.map +1 -0
  111. package/dist/{cli-D5OE3URZ.js → cli-FB4LOA5A.js} +144 -63
  112. package/dist/{cli-D5OE3URZ.js.map → cli-FB4LOA5A.js.map} +1 -1
  113. package/dist/{codex-event-PPNVRRDH.js → codex-event-TYVES3UX.js} +2 -2
  114. package/dist/{codex-host-2RJOJW2B.js → codex-host-WW4H2SKT.js} +7 -6
  115. package/dist/codex-install-2C623HPW.js +393 -0
  116. package/dist/codex-install-2C623HPW.js.map +1 -0
  117. package/dist/{config-ZD4OB2DO.js → config-HOVJFEKD.js} +21 -17
  118. package/dist/doctor-NKU4V5OV.js +1312 -0
  119. package/dist/doctor-NKU4V5OV.js.map +1 -0
  120. package/dist/{env-proxy-XL4P73MZ.js → env-proxy-R6ZMLQTT.js} +6 -2
  121. package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js → ethersCompat-Df4a6QIZ-X6YZWAML.js} +3 -3
  122. package/dist/{fund-5ITKQGYF.js → fund-WEBHTZGN.js} +37 -36
  123. package/dist/{fund-5ITKQGYF.js.map → fund-WEBHTZGN.js.map} +1 -1
  124. package/dist/hook-command-ZA2PNKS6.js +44 -0
  125. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  126. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  127. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +82 -0
  128. package/dist/hosts/codex/tenjin/.mcp.json +3 -0
  129. package/dist/hosts/codex/tenjin/hooks/hooks.json +51 -5
  130. package/dist/hosts-AV5MHBAU.js +38 -0
  131. package/dist/index.js +28 -8
  132. package/dist/index.js.map +1 -1
  133. package/dist/{install-XWGE4Q7L.js → install-PT4EZS4R.js} +53 -30
  134. package/dist/{install-identity-K7EJIQFP.js → install-identity-5A4OE6YC.js} +11 -10
  135. package/dist/install-wallet-SAAPKB73.js +281 -0
  136. package/dist/install-wallet-SAAPKB73.js.map +1 -0
  137. package/dist/{mcp-3LIJSSJB.js → mcp-HAWKCTPQ.js} +785 -210
  138. package/dist/mcp-HAWKCTPQ.js.map +1 -0
  139. package/dist/{mine.wasm-6PIT3DK6.js → mine.wasm-QFAHIFPY.js} +2 -2
  140. package/dist/{mine.wasm-6PIT3DK6.js.map → mine.wasm-QFAHIFPY.js.map} +1 -1
  141. package/dist/{package-ZKQFDWLE.js → package-SR2WB6MK.js} +4 -2
  142. package/dist/passphrase-IFTDS3CU.js +44 -0
  143. package/dist/{paths-POPTXJO6.js → paths-XCSAKISU.js} +10 -2
  144. package/dist/{pay-WHBERZ3W.js → pay-OXC3WKYV.js} +29 -29
  145. package/dist/{payments-KVICEKD2.js → payments-3KHMP2MG.js} +15 -14
  146. package/dist/{payments-KVICEKD2.js.map → payments-3KHMP2MG.js.map} +1 -1
  147. package/dist/plugin-registration-N3GRIZVM.js +67 -0
  148. package/dist/{redact-6W23GGJC.js → redact-D7ASVWKL.js} +2 -2
  149. package/dist/runtime-UVNUA3AS.js +1203 -0
  150. package/dist/runtime-UVNUA3AS.js.map +1 -0
  151. package/dist/runtime-fetch-EKFRNR6Z.js +20 -0
  152. package/dist/runtime-layout-BDWZG2TQ.js +25 -0
  153. package/dist/{send-7G7Y7DLN.js → send-HMKJLT34.js} +24 -22
  154. package/dist/{send-7G7Y7DLN.js.map → send-HMKJLT34.js.map} +1 -1
  155. package/dist/{status-OF7RH5HM.js → status-RWXIIWYS.js} +55 -25
  156. package/dist/status-RWXIIWYS.js.map +1 -0
  157. package/dist/{status-line-XOUE6MPL.js → status-line-77XYZP7E.js} +10 -9
  158. package/dist/{status-line-XOUE6MPL.js.map → status-line-77XYZP7E.js.map} +1 -1
  159. package/dist/uninstall-D5G67UJH.js +480 -0
  160. package/dist/uninstall-D5G67UJH.js.map +1 -0
  161. package/dist/update-LRNOEGSB.js +53 -0
  162. package/dist/update-LRNOEGSB.js.map +1 -0
  163. package/dist/{usdc-OGOGEHV2.js → usdc-D6X7EIQ2.js} +6 -8
  164. package/dist/usdc-D6X7EIQ2.js.map +1 -0
  165. package/dist/{viemAdapter-By13KInL-S3DA7DFW.js → viemAdapter-By13KInL-RL742ETX.js} +3 -3
  166. package/dist/viemAdapter-By13KInL-RL742ETX.js.map +1 -0
  167. package/dist/wallet-XFYC27BR.js +55 -0
  168. package/dist/wallet-XFYC27BR.js.map +1 -0
  169. package/dist/wallet-kdf-worker.mjs +8 -8
  170. package/docs/agent-permissions.md +40 -22
  171. package/docs/safety-model.md +1 -1
  172. package/docs/troubleshooting.md +72 -1
  173. package/package.json +14 -1
  174. package/dist/ccip-NLCSCHKI.js +0 -19
  175. package/dist/chunk-2XLC3AEX.js.map +0 -1
  176. package/dist/chunk-4ZZO6ULA.js.map +0 -1
  177. package/dist/chunk-5C32RLTA.js.map +0 -1
  178. package/dist/chunk-5IEP5EGE.js +0 -5332
  179. package/dist/chunk-5IEP5EGE.js.map +0 -1
  180. package/dist/chunk-5MARFNSB.js.map +0 -1
  181. package/dist/chunk-77TCKDEC.js.map +0 -1
  182. package/dist/chunk-7EKYXMUO.js +0 -7536
  183. package/dist/chunk-7EKYXMUO.js.map +0 -1
  184. package/dist/chunk-7QKHZQKW.js.map +0 -1
  185. package/dist/chunk-AGZ7PJKY.js.map +0 -1
  186. package/dist/chunk-AKWGE6JQ.js.map +0 -1
  187. package/dist/chunk-BL3332HQ.js +0 -7611
  188. package/dist/chunk-BL3332HQ.js.map +0 -1
  189. package/dist/chunk-D65GNPS3.js.map +0 -1
  190. package/dist/chunk-EGELTSPU.js +0 -2865
  191. package/dist/chunk-EGELTSPU.js.map +0 -1
  192. package/dist/chunk-GA7JETVM.js +0 -150
  193. package/dist/chunk-GA7JETVM.js.map +0 -1
  194. package/dist/chunk-I3EQFHCD.js +0 -175
  195. package/dist/chunk-I3EQFHCD.js.map +0 -1
  196. package/dist/chunk-K3I7C2MO.js +0 -1185
  197. package/dist/chunk-K3I7C2MO.js.map +0 -1
  198. package/dist/chunk-KXVP2VKA.js.map +0 -1
  199. package/dist/chunk-LEFIX6RS.js.map +0 -1
  200. package/dist/chunk-MNXS2U45.js.map +0 -1
  201. package/dist/chunk-NEFNKLBE.js.map +0 -1
  202. package/dist/chunk-OHRR5OYM.js.map +0 -1
  203. package/dist/chunk-QSCPK4F5.js.map +0 -1
  204. package/dist/chunk-SJLTEINJ.js.map +0 -1
  205. package/dist/chunk-TTNESUPQ.js.map +0 -1
  206. package/dist/chunk-UKY4CHNC.js.map +0 -1
  207. package/dist/chunk-V6BSF6OC.js +0 -260
  208. package/dist/chunk-V6BSF6OC.js.map +0 -1
  209. package/dist/chunk-YVFXE7RR.js.map +0 -1
  210. package/dist/codex-install-UUZ6QMBQ.js +0 -221
  211. package/dist/codex-install-UUZ6QMBQ.js.map +0 -1
  212. package/dist/doctor-KBR34Q4B.js +0 -601
  213. package/dist/doctor-KBR34Q4B.js.map +0 -1
  214. package/dist/hook-command-4TYCHHRL.js +0 -39
  215. package/dist/hosts-FWZOV26H.js.map +0 -1
  216. package/dist/install-wallet-XQ6XFZV4.js +0 -117
  217. package/dist/install-wallet-XQ6XFZV4.js.map +0 -1
  218. package/dist/mcp-3LIJSSJB.js.map +0 -1
  219. package/dist/plugin-registration-5TIA564H.js +0 -54
  220. package/dist/status-OF7RH5HM.js.map +0 -1
  221. package/dist/uninstall-JXUAFNDB.js +0 -158
  222. package/dist/uninstall-JXUAFNDB.js.map +0 -1
  223. package/dist/update-ZKUERSO2.js +0 -44
  224. package/dist/wallet-2HA6W4R4.js +0 -43
  225. /package/dist/{_esm-MEXZI5DL.js.map → _esm-RLLC72MS.js.map} +0 -0
  226. /package/dist/{alive-J64H46HI.js.map → alive-MROUMFH3.js.map} +0 -0
  227. /package/dist/{ccip-7RMRLAGV.js.map → auto-update-OPWMRZLS.js.map} +0 -0
  228. /package/dist/{ccip-NLCSCHKI.js.map → ccip-DHDFKTQV.js.map} +0 -0
  229. /package/dist/{chunk-7Q5FDF65.js.map → chunk-445VQTVM.js.map} +0 -0
  230. /package/dist/{chunk-KXQ4UIP7.js.map → chunk-4USCZ2NI.js.map} +0 -0
  231. /package/dist/{chunk-FW75G2W4.js.map → chunk-CISYM4EO.js.map} +0 -0
  232. /package/dist/{chunk-B7HUUJOK.js.map → chunk-D3ZURCG7.js.map} +0 -0
  233. /package/dist/{chunk-UQUOVWBG.js.map → chunk-DRDUIZIA.js.map} +0 -0
  234. /package/dist/{chunk-27EPWVOY.js.map → chunk-DW4YTVR3.js.map} +0 -0
  235. /package/dist/{chunk-ORWL5BSN.js.map → chunk-HGZEPQUT.js.map} +0 -0
  236. /package/dist/{chunk-P4NH7OUK.js.map → chunk-IDTRSAHE.js.map} +0 -0
  237. /package/dist/{chunk-YFPY4ONH.js.map → chunk-JEVQ5LKO.js.map} +0 -0
  238. /package/dist/{chunk-5K5W4S66.js.map → chunk-QF3LSMGS.js.map} +0 -0
  239. /package/dist/{chunk-WK7F3B2E.js.map → chunk-SO3XRZPX.js.map} +0 -0
  240. /package/dist/{chunk-7ZRL2LBQ.js.map → chunk-V2LQLN5H.js.map} +0 -0
  241. /package/dist/{chunk-K72RURN3.js.map → chunk-VJUVFZ2D.js.map} +0 -0
  242. /package/dist/{codex-event-PPNVRRDH.js.map → codex-event-TYVES3UX.js.map} +0 -0
  243. /package/dist/{codex-host-2RJOJW2B.js.map → codex-host-WW4H2SKT.js.map} +0 -0
  244. /package/dist/{config-ZD4OB2DO.js.map → config-HOVJFEKD.js.map} +0 -0
  245. /package/dist/{env-proxy-XL4P73MZ.js.map → env-proxy-R6ZMLQTT.js.map} +0 -0
  246. /package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js.map → ethersCompat-Df4a6QIZ-X6YZWAML.js.map} +0 -0
  247. /package/dist/{hook-command-4TYCHHRL.js.map → hook-command-ZA2PNKS6.js.map} +0 -0
  248. /package/dist/{install-XWGE4Q7L.js.map → hosts-AV5MHBAU.js.map} +0 -0
  249. /package/dist/{install-identity-K7EJIQFP.js.map → install-PT4EZS4R.js.map} +0 -0
  250. /package/dist/{package-ZKQFDWLE.js.map → install-identity-5A4OE6YC.js.map} +0 -0
  251. /package/dist/{paths-POPTXJO6.js.map → package-SR2WB6MK.js.map} +0 -0
  252. /package/dist/{pay-WHBERZ3W.js.map → passphrase-IFTDS3CU.js.map} +0 -0
  253. /package/dist/{plugin-registration-5TIA564H.js.map → paths-XCSAKISU.js.map} +0 -0
  254. /package/dist/{redact-6W23GGJC.js.map → pay-OXC3WKYV.js.map} +0 -0
  255. /package/dist/{update-ZKUERSO2.js.map → plugin-registration-N3GRIZVM.js.map} +0 -0
  256. /package/dist/{usdc-OGOGEHV2.js.map → redact-D7ASVWKL.js.map} +0 -0
  257. /package/dist/{viemAdapter-By13KInL-S3DA7DFW.js.map → runtime-fetch-EKFRNR6Z.js.map} +0 -0
  258. /package/dist/{wallet-2HA6W4R4.js.map → runtime-layout-BDWZG2TQ.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/paths.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\n/**\n * Where the CLI keeps its config and wallet. Defaults to ~/.tenjin, overridable\n * via TENJIN_DATA_DIR (CI, ephemeral agents, and every test — which point it at\n * a temp dir so the real home is never touched).\n */\nexport function dataDir(env: NodeJS.ProcessEnv = process.env): string {\n const override = env.TENJIN_DATA_DIR;\n // Absolute, always: the daemon compares this string against its own\n // `data_dir` and is spawned with it as `cwd`, so a relative override must\n // mean the same directory from every process.\n if (override !== undefined && override.length > 0) return resolve(override);\n return defaultDataDir();\n}\n\n/**\n * The data dir a run with no override resolves. Split out of {@link dataDir} so\n * a caller holding a home directory can ask whether some other profile IS the\n * default one, without a second copy of the `.tenjin` literal.\n */\nexport function defaultDataDir(home: string = homedir()): string {\n return join(home, '.tenjin');\n}\n\n/**\n * Tenjin's own runtime: copies of the CLI, the Node that runs them and the\n * plugin folder Claude Code loads, so neither an npm folder nor the `node` on\n * PATH has to outlive an upgrade. Only the default data dir has one; see\n * `src/lib/runtime.ts`.\n */\nexport function runtimeDir(dir: string = dataDir()): string {\n return join(dir, 'runtime');\n}\n\n/**\n * Where the `tenjin` launcher goes: `~/.local/bin`, the folder the XDG layout\n * and most shells' defaults already put on PATH, and none of a Node version\n * manager's.\n */\nexport function launcherDir(home: string = homedir()): string {\n return join(home, '.local', 'bin');\n}\n\nexport function configPath(dir: string = dataDir()): string {\n return join(dir, 'config.json');\n}\n\nexport function walletPath(dir: string = dataDir()): string {\n return join(dir, 'wallet.json');\n}\n\n/**\n * The anonymous install id sent to Tenjin as `tenjin-install-id` (lib/install-identity).\n * Under the data dir so it survives upgrades and reinstalls of the CLI itself.\n */\nexport function installIdPath(dir: string = dataDir()): string {\n return join(dir, 'install-id');\n}\n\n/**\n * Where the delegated P-256 session key + its wallet-signed SIWX delegation are\n * cached (B3, D35). A short-lived (≤24h) hot key: lower stakes than wallet.json,\n * but still written 0600 and address-bound so a wallet change invalidates it.\n */\nexport function sessionPath(dir: string = dataDir()): string {\n return join(dir, 'session.json');\n}\n\n/**\n * Where the client-side rolling spend ledger lives (lib/wallet/spend.ts).\n *\n * Its own file, NOT session.json: the two schemas are incompatible and both\n * readers treat a parse failure as \"absent\", so a shared path meant each writer\n * silently destroyed the other's file — a session key wiped the spend window, and\n * the next spend wiped the session key.\n */\nexport function spendLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'spend.json');\n}\n\n/**\n * The wallet's last USDC balance read (lib/usdc-balance). A pure cache, a\n * minute long: an unreadable file is simply read again from the chain.\n */\nexport function balanceCachePath(dir: string = dataDir()): string {\n return join(dir, 'balance.json');\n}\n\n/**\n * Where the once-a-day \"a newer tenjin-cli exists\" check caches the registry\n * answer. A pure cache: nothing here is authoritative, so an unreadable file is\n * simply re-fetched.\n */\nexport function updateCheckPath(dir: string = dataDir()): string {\n return join(dir, 'update-check.json');\n}\n\n/**\n * Where `install` writes the standalone harness hook scripts. Under the data dir\n * rather than the harness's own config directory: the scripts are ours, a harness\n * only ever holds the path to them, and one location serves every harness.\n */\nexport function hooksDir(dir: string = dataDir()): string {\n return join(dir, 'hooks');\n}\n\n/**\n * How the marketplace has been answering the dispatch hook lately, so a run of\n * failures stops the arm instead of paying the fetch budget per subagent through\n * an outage. Hook-written, unlocked, and cheap to lose, since a missing file\n * reads as \"healthy\". Its own file because two hooks writing one unlocked file\n * would erase each other.\n */\nexport function hookHealthPath(dir: string = dataDir()): string {\n return join(dir, 'hook-health.json');\n}\n\n/**\n * Where the LEGACY (pre-per-wallet) Windows DPAPI passphrase blob lives. The\n * file holds a DPAPI CurrentUser ciphertext, not the passphrase in plaintext.\n * New writes go to the per-wallet path below; this one is only read as a\n * migration fallback and removed after a verified per-wallet copy exists.\n */\nexport function passphraseBlobPath(dir: string = dataDir()): string {\n return join(dir, 'passphrase.dpapi');\n}\n\n/**\n * The per-wallet Windows DPAPI passphrase blob: one file per wallet address\n * (lowercase), so creating a new wallet never clobbers an old wallet's blob.\n * Only ever written on win32; other platforms use their own OS store.\n */\nexport function passphraseBlobPathFor(account: string, dir: string = dataDir()): string {\n return join(dir, `passphrase.${account}.dpapi`);\n}\n\n/**\n * The sidecar that records WHERE each wallet's passphrase was saved\n * (`src/lib/passphrase-record.ts`), keyed by lowercase address. A separate\n * file rather than a field in wallet.json, so the funded key file is never\n * rewritten and an older CLI still reads it. No sidecar means today's lookup\n * order, unchanged.\n */\nexport function passphraseRecordPath(dir: string = dataDir()): string {\n return join(dir, 'passphrase-store.json');\n}\n\n/**\n * The per-wallet passphrase FILE store: the plaintext passphrase, mode 0600 in\n * a 0700 directory, no trailing newline. Not encrypted; the same trade-off the\n * GitHub CLI makes with its `hosts.yml` token. Used only where no OS credential\n * store exists (headless Linux, WSL, a sandbox) or when the user chose\n * `--insecure-storage`; never as the fallback for a keychain that is merely\n * locked. One file per wallet address (lowercase), like the DPAPI blob above.\n */\nexport function passphraseFilePathFor(account: string, dir: string = dataDir()): string {\n return join(dir, `passphrase.${account}.plain`);\n}\n\n/**\n * Where `wallet create --replace` parks the outgoing wallet's keystore, keyed by\n * its lowercase address so successive replaces can never collide. Together with\n * the wallet's per-address passphrase entry in the OS store, this file keeps the\n * replaced wallet's funds recoverable; it is never read by the active-wallet\n * path.\n */\nexport function archivedWalletPath(account: string, dir: string = dataDir()): string {\n return join(dir, `wallet.${account}.json.bak`);\n}\n\n/**\n * The loop daemon's own state, all under the data dir (tenjin-notes\n * loop-redesign/02-redesign.md §4, §10).\n */\nexport function loopDbPath(dir: string = dataDir()): string {\n return join(dir, 'loop.db');\n}\n\n/** 32 random bytes, hex, 0600. Minted by `tenjin daemon start`, rotated only by\n * reinstall, NEVER deleted by the daemon: every transport reads it, and an idle\n * exit that removed it would strand them all. */\nexport function daemonTokenPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.token');\n}\n\n/** `{ pid, port, started_at, data_dir }`, advisory: written after the bind,\n * removed at exit only by the process whose pid it names. Liveness is\n * `GET /health`, never this file alone. */\nexport function daemonPidPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.pid');\n}\n\n/** Where a detached daemon's stdout and stderr go, and where the shim writes its\n * one `daemon-down` line when it cannot reach one. */\nexport function daemonLogPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.log');\n}\n\n/** An empty file whose mtime is the last spawn attempt; the shim's backoff. */\nexport function daemonSpawnPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.spawn');\n}\n\n/** The single-file daemon bundle `tenjin daemon start` copies from `dist`. */\nexport function daemonBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-daemon.mjs');\n}\n\n/** The ensure-and-forward shim the two `command` hook entries run. */\nexport function shimBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-shim.mjs');\n}\n\n/** Tenjin's own vitest reporter, copied beside the bundles. NOT A HOOK ENTRY\n * and never spawned: a repo's own `vitest.config.ts` imports it by this\n * absolute path, which is why `doctor` can hint at it verbatim. */\nexport const VITEST_REPORTER_FILE = 'tenjin-vitest-reporter.mjs';\n\nexport function vitestReporterPath(dir: string = dataDir()): string {\n return join(hooksDir(dir), VITEST_REPORTER_FILE);\n}\n\n/**\n * Where a router lookup that bought a file (a sound, an image) saves it. The\n * bytes cannot ride in the tool result, so the result names this file instead.\n */\nexport function downloadsDir(dir: string = dataDir()): string {\n return join(dir, 'downloads');\n}\n\n/**\n * One JSON line per paid router call: what was bought, from whom, for how much,\n * the settlement it carried and the files it saved. The user's own record; only\n * reconcile reads it back (`tenjin payments reconcile`, and the `request` tool's\n * pass beside each lookup), to settle what was left unknown.\n */\nexport function paidLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'paid', 'ledger.jsonl');\n}\n\n/**\n * One file per take of a paid router call whose seller was still working when\n * the call ended: where to poll, until when, and what it saved. `request({job})`\n * resumes from it in any later process.\n */\nexport function jobsDir(dir: string = dataDir()): string {\n return join(dir, 'jobs');\n}\n\n/**\n * One file per quote: a router call over the automatic limits, kept with its\n * exact plan until the user approves it, it runs once, or it expires.\n */\nexport function quotesDir(dir: string = dataDir()): string {\n return join(dir, 'quotes');\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAOvB,SAAS,QAAQ,MAAyB,QAAQ,KAAa;AACpE,QAAM,WAAW,IAAI;AAIrB,MAAI,aAAa,UAAa,SAAS,SAAS,EAAG,QAAO,QAAQ,QAAQ;AAC1E,SAAO,eAAe;AACxB;AAOO,SAAS,eAAe,OAAe,QAAQ,GAAW;AAC/D,SAAO,KAAK,MAAM,SAAS;AAC7B;AAQO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,SAAS;AAC5B;AAOO,SAAS,YAAY,OAAe,QAAQ,GAAW;AAC5D,SAAO,KAAK,MAAM,UAAU,KAAK;AACnC;AAEO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,aAAa;AAChC;AAEO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,aAAa;AAChC;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AAQ,GAAW;AAC7D,SAAO,KAAK,KAAK,YAAY;AAC/B;AAGO,SAAS,gBAAgB,MAAc,QAAQ,GAAW;AAC/D,SAAO,KAAK,KAAK,cAAc;AACjC;AAGO,SAAS,iBAAiB,MAAc,QAAQ,GAAW;AAChE,SAAO,KAAK,SAAS,GAAG,GAAG,mBAAmB;AAChD;AAGO,SAAS,eAAe,MAAc,QAAQ,GAAW;AAC9D,SAAO,KAAK,SAAS,GAAG,GAAG,iBAAiB;AAC9C;AAKO,IAAM,uBAAuB;AAE7B,SAAS,mBAAmB,MAAc,QAAQ,GAAW;AAClE,SAAO,KAAK,SAAS,GAAG,GAAG,oBAAoB;AACjD;AAMO,SAAS,aAAa,MAAc,QAAQ,GAAW;AAC5D,SAAO,KAAK,KAAK,WAAW;AAC9B;AAQO,SAAS,eAAe,MAAc,QAAQ,GAAW;AAC9D,SAAO,KAAK,KAAK,QAAQ,cAAc;AACzC;AAOO,SAAS,QAAQ,MAAc,QAAQ,GAAW;AACvD,SAAO,KAAK,KAAK,MAAM;AACzB;AAMO,SAAS,UAAU,MAAc,QAAQ,GAAW;AACzD,SAAO,KAAK,KAAK,QAAQ;AAC3B;","names":[]}
@@ -1,13 +1,13 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ package_default
4
+ } from "./chunk-YUY4SAGM.js";
2
5
  import {
3
6
  PRODUCTION_ORIGIN
4
7
  } from "./chunk-XQJXNMSB.js";
5
8
  import {
6
9
  CliError
7
10
  } from "./chunk-3UCIG4TG.js";
8
- import {
9
- package_default
10
- } from "./chunk-5C32RLTA.js";
11
11
 
12
12
  // src/lib/client-meta.ts
13
13
  var TENJIN_PRODUCT = `tenjin-cli/${package_default.version}`;
@@ -90,6 +90,22 @@ var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
90
90
  function carriesSignedMaterial(headers) {
91
91
  return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));
92
92
  }
93
+ function isReservedRequestHeader(name) {
94
+ const lowered = name.toLowerCase();
95
+ return CREDENTIAL_HEADERS.has(lowered) || lowered === SHELF_BYPASS_HEADER || lowered === INSTALL_ID_HEADER || lowered.startsWith("payment-") || lowered.startsWith("x-payment");
96
+ }
97
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
98
+ var TRANSPORT_HEADERS = /* @__PURE__ */ new Set(["host", "content-length", "content-type", "user-agent"]);
99
+ function requestHeaderProblem(name, value, ownContentType = false) {
100
+ if (!HEADER_NAME.test(name) || value.length === 0) return "name";
101
+ const lowered = name.toLowerCase();
102
+ const contentType = ownContentType && lowered === "content-type";
103
+ if (isReservedRequestHeader(lowered) || TRANSPORT_HEADERS.has(lowered) && !contentType) {
104
+ return "reserved";
105
+ }
106
+ if (value.length > 1024 || /[\r\n]/.test(value)) return "value";
107
+ return null;
108
+ }
93
109
  function timeoutFailure(url, timeoutMs) {
94
110
  return {
95
111
  ok: false,
@@ -136,7 +152,7 @@ function prepareRequest(url, opts) {
136
152
  } else if (opts.rawBody !== void 0) {
137
153
  body = opts.rawBody;
138
154
  }
139
- const wantsAccept = opts.method === "POST" || opts.method === "PUT" || body !== void 0;
155
+ const wantsAccept = opts.method === "POST" || opts.method === "PUT" || opts.method === "PATCH" || body !== void 0;
140
156
  if (wantsAccept && !merged.has("accept")) merged.set("accept", "application/json");
141
157
  const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());
142
158
  const signed = carriesSignedMaterial(headers);
@@ -319,8 +335,9 @@ function oversizedHeaderFailure(url) {
319
335
  export {
320
336
  composeUserAgent,
321
337
  setTenjinIdentity,
338
+ requestHeaderProblem,
322
339
  isBinaryContentType,
323
340
  httpRequest,
324
341
  fetchFailureToCliError
325
342
  };
326
- //# sourceMappingURL=chunk-AGZ7PJKY.js.map
343
+ //# sourceMappingURL=chunk-OTWLERSW.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 the\n * shared transport sends, because the server's `parseUserAgentProduct()` (tenjin\n * PR #544) attributes on the FIRST product only and the CLI is the user agent\n * that constructed and sent the request.\n */\nexport const TENJIN_PRODUCT = `tenjin-cli/${pkg.version}`;\n\n/** The product NAME alone, which is what identifies a copy of us in a handoff. */\nexport const TENJIN_PRODUCT_NAME = 'tenjin-cli';\n\n/**\n * The product the WebSearch hook leads with, so a ridealong query is separable\n * from a deliberate `tenjin search`. Leading is the mechanism: the server\n * attributes on the FIRST User-Agent product, landing here in `client_name`.\n *\n * The separation is the deliverable, not any one consumer: whatever judges hook\n * demand needs these populations distinguishable at ingest (tenjin#704,\n * tenjin-agent#179). A rename breaks no filter today, it merges them again. */\nexport const WEBSEARCH_HOOK_PRODUCT_NAME = 'tenjin-websearch-hook';\nexport const WEBSEARCH_HOOK_PRODUCT = `${WEBSEARCH_HOOK_PRODUCT_NAME}/${pkg.version}`;\n\n/** Every identity of ours a handoff may carry, which composition drops rather\n * than duplicate, whichever product is leading. */\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 the order\n * they were handed off in, and so stripping it is enough to recover the caller's\n * sequence from an already-composed field (see `composeUserAgent`).\n */\nexport const TENJIN_COMMENT = `(+${PRODUCTION_ORIGIN})`;\n\n/**\n * The CLI's identity on every HTTP request, sent as the standard `User-Agent`\n * header from the shared transport (`http.ts`). `X-Tenjin-Client` is retired and\n * this CLI sends it nowhere.\n */\nexport const TENJIN_USER_AGENT = `${TENJIN_PRODUCT} ${TENJIN_COMMENT}`;\n\n/** The same field for the WebSearch hook, which identifies as its own product. */\nexport const WEBSEARCH_HOOK_USER_AGENT = `${WEBSEARCH_HOOK_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 a\n * sequence of these and nothing else (no comments, no free text), which is what\n * structurally keeps a user, wallet, session, hostname, or machine identifier\n * out of the field rather than a blocklist that has to guess at one.\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 /** The product to lead with; the WebSearch hook passes its own. */\n product?: string;\n}\n\n/**\n * Compose the field the transport sends: the Tenjin product, then the caller's\n * products in their original order, then the Tenjin comment. The handoff is\n * SELF-REPORTED TELEMETRY and never trusted policy input; nothing here or on the\n * server may read it to decide entitlement, spend, or trust.\n *\n * Idempotent by construction: the caller value is decomposed into tokens, our own\n * product and comment are dropped from it, and the field is rebuilt from\n * `TENJIN_PRODUCT`, so re-composing an already-composed field (a retry, a nested\n * helper, an agent re-exporting the env it received) yields the same string\n * rather than a second `tenjin-cli` token. Caller products survive byte for byte.\n *\n * Rejection is total, never partial: a non-printable, non-product, or overlong\n * handoff is OMITTED and the Tenjin identity travels alone, because truncating a\n * product token would mint a different, false identity.\n */\nexport function composeUserAgent(input: ComposeUserAgentInput = {}): string {\n const product = input.product ?? TENJIN_PRODUCT;\n const alone = `${product} ${TENJIN_COMMENT}`;\n const raw = input.caller ?? (input.env ?? process.env)[CALLER_USER_AGENT_ENV];\n const products = callerProducts(raw);\n if (products.length === 0) return alone;\n const composed = `${product} ${products.join(' ')} ${TENJIN_COMMENT}`;\n return composed.length <= USER_AGENT_MAX_LENGTH ? composed : alone;\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 product\n * token is case-sensitive to the server, but a copy of ours in any casing is\n * still a duplicate identity, and dropping it is what makes composition total.\n */\nfunction isOwnIdentity(token: string): boolean {\n const lower = token.toLowerCase();\n // Both sides are lowered: comparing a lowered token against a constant that is\n // merely all-lowercase TODAY would break silently the day either gains a\n // capital, and it fails safe (the stale copy stops matching, then fails\n // PRODUCT_RE, and the whole handoff drops), so nothing would notice.\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 * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `search`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers, merged onto the User-Agent this module always sends. */\n headers?: Record<string, string>;\n /** The team shelf's bypass secret and its origin; see {@link ShelfBypass}. */\n bypass?: ShelfBypass;\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}\n\n/**\n * The team shelf's Vercel \"Protection Bypass for Automation\" header.\n *\n * A door key for a protected preview deployment, not a credential of anyone's:\n * it gets a request past Deployment Protection and authenticates nobody. It is\n * NOT in {@link CREDENTIAL_HEADERS}, whose members are wallet-signed material a\n * redirect target could REPLAY — this one cannot be replayed into a signature.\n * It is still a secret, and DISCLOSING it is the whole harm: whoever holds it\n * walks into the team shelf. So it pins redirects exactly as a signed header\n * does (see {@link carriesBypassKey}), and where it may go is decided here and\n * nowhere else.\n */\nexport const SHELF_BYPASS_HEADER = 'x-vercel-protection-bypass';\n\n/**\n * A bypass secret and the origin it belongs to.\n *\n * THE ORIGIN IS PART OF THE VALUE, and that is the whole design. The CLI talks\n * to two shelves in team mode — the team's own deployment and the public\n * marketplace — and a caller that decides \"this request is to the team shelf, so\n * attach the key\" is a caller that eventually gets it wrong once. So callers\n * pass the pair and this transport does the compare: the header is attached from\n * the REQUEST URL, so a request to any other host cannot carry it, whatever the\n * call site believed.\n */\nexport interface ShelfBypass {\n /** `URL.origin` of the shelf the secret opens (the configured `baseUrl`). */\n origin: string;\n secret: string;\n}\n\n/** The bypass header for `url`, or nothing. Exported for the hook-script mirror\n * test, which runs the generated copy of this rule against this one. */\nexport function shelfBypassHeaders(\n url: string,\n bypass: ShelfBypass | undefined,\n): Record<string, string> {\n if (bypass === undefined || bypass.secret.length === 0) return {};\n let origin: string;\n try {\n origin = new URL(url).origin;\n } catch {\n return {};\n }\n if (origin !== bypass.origin) return {};\n return { [SHELF_BYPASS_HEADER]: bypass.secret };\n}\n\n/**\n * Whether the request being assembled actually carries the door key.\n *\n * A request that carries it MUST NOT follow a redirect. `fetch`'s default\n * `redirect: 'follow'` re-sends request headers verbatim to the new host (Node\n * strips only `Authorization`), so a single 3xx anywhere on the shelf origin —\n * the Vercel Authentication interstitial a rotated bypass secret gets, a domain\n * alias, a CDN rule — would hand the team shelf's key to whatever `Location`\n * names. Nothing else is needed to walk in afterwards, so the key never leaves\n * the origin it was paired with, not even one hop.\n *\n * Read off the BUILT headers rather than off `opts.bypass`, for the same reason\n * {@link CREDENTIAL_HEADERS} is matched by name: attaching the secret is what\n * arms the protection, so an off-origin request (which gets no header) keeps\n * ordinary transport and a call site cannot forget to ask for the pin.\n */\nfunction carriesBypassKey(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => name.toLowerCase() === SHELF_BYPASS_HEADER);\n}\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 * Same shape as {@link ShelfBypass}, for the same reason: the transport decides\n * where it goes, from the REQUEST URL, so a call site cannot send it to a\n * 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 two process entries\n * (the CLI's `index.ts` and the daemon), so an in-process test that never sets\n * it sends exactly 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 the bypass key and 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; both\n * transports funnel their Headers through it, so a third 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/** The same write for `fetchJson`'s plain-object headers; Headers.entries() is lowercase-keyed. */\nfunction withUserAgent(\n callerHeaders?: Record<string, string>,\n callerUserAgent?: string,\n): Record<string, string> {\n return Object.fromEntries(\n applyUserAgent(new Headers(callerHeaders ?? {}), callerUserAgent).entries(),\n );\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\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), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json' | 'blocked-redirect' | 'oversized-header';\n status?: number;\n requestId?: string;\n message: string;\n /**\n * On `invalid-json`, and on `http` when the status is 401/403: the response\n * looks like an access-protection or sign-in page rather than an API answer.\n * See {@link accessGateSignals} for what \"looks like\" means. Callers use it to\n * point at the missing credential instead of at the base URL, which is the one\n * setting that was already correct (#218).\n */\n gateSuspected?: boolean;\n /**\n * Present (true) only where the response left the host that was asked for:\n * `gateSuspected`'s STRONGER signal (the final URL's host differs), or, on\n * `blocked-redirect`, a `Location` that resolves to another host. An HTML\n * content-type alone proves a page came back, not who sent it, and a 3xx\n * alone proves only that the URL moved; leaving the host is what lets a\n * caller name access protection outright.\n */\n gateOffOrigin?: boolean;\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 * Does this response read as a protection page rather than as an API answer?\n *\n * Two independent signals, reported separately because they prove different\n * amounts (the caller's wording must not outrun the evidence):\n *\n * - an HTML content-type, because a Vercel Deployment Protection interstitial\n * and every sign-in wall answer with a page;\n * - a final URL whose host is not the one asked for, because a gate that\n * redirects to sign in lands the probe on another host and `fetch` follows it\n * silently on the unpinned requests this function serves.\n *\n * Decided HERE because this transport is the only place holding the `Response`;\n * a caller re-deriving it from the failure message would be guessing. An\n * unreadable final URL is NOT suspicion: `res.url` is empty on a synthesized\n * Response, so only a host that reads AND differs counts.\n */\nfunction accessGateSignals(\n requestedUrl: string,\n res: Response,\n): { gateSuspected: boolean; gateOffOrigin?: true } {\n const html = /^\\s*text\\/html\\b/i.test(res.headers.get('content-type') ?? '');\n let offOrigin = false;\n if (res.url.length > 0) {\n try {\n offOrigin = new URL(requestedUrl).host !== new URL(res.url).host;\n } catch {\n offOrigin = false;\n }\n }\n return {\n gateSuspected: html || offOrigin,\n ...(offOrigin ? { gateOffOrigin: true as const } : {}),\n };\n}\n\n/**\n * Does an unfollowed 3xx point off the host that was asked for?\n *\n * The pinned branch never follows, so `res.url` is still the requested URL and\n * `Location` is the only evidence about where the hop went. That distinction\n * carries the whole verdict downstream: a gate's sign-in interstitial lands on\n * another host, while an `http://` base URL that 301s to https, or a host\n * normalising to its canonical name, does not, and reading either as a refused\n * credential blames the wrong setting. A relative target resolves against the\n * request, so it is same-host by construction; a missing or unparseable one is\n * NOT an off-host claim.\n */\nfunction redirectLeavesHost(requestedUrl: string, location: string | null): boolean {\n if (location === null || location.length === 0) return false;\n try {\n return new URL(requestedUrl).host !== new URL(location, requestedUrl).host;\n } catch {\n return false;\n }\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect. `resource-ref`\n * pins the invariant — \"nothing signed may leave for a host the user did not\n * configure\" — but `assertOnBaseOrigin` only checks the URL the caller asked\n * for, and `fetch`'s default `redirect: 'follow'` re-sends request headers\n * verbatim to the new host (Node strips only `Authorization`). A 3xx anywhere on\n * the configured origin would therefore hand a signature BOUND TO THE REAL\n * DOMAIN to whoever `Location` points at, replayable against it for the\n * 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 * All three wallet-signed families this CLI sends are here: the SIWX auth\n * header, the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance even\n * though `read-client` pins v2), and `tenjin-session-delegation` — a REUSABLE\n * session-lifetime SIWX signature `session-key` attaches to every session-signed\n * write, which makes it the most replayable credential of the set. The RFC 9421\n * `Signature`/`Signature-Input` pair riding alongside it is deliberately absent:\n * it covers method, URL, and body digest, so it is not usefully replayable at\n * another host.\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 this client sets itself and an operator may not: the\n * wallet-signed material above, the shelf bypass secret, this install's\n * identity, and the x402 payment namespace. Kept beside the set so the two\n * cannot drift.\n */\nexport function isReservedRequestHeader(name: string): boolean {\n const lowered = name.toLowerCase();\n return (\n CREDENTIAL_HEADERS.has(lowered) ||\n lowered === SHELF_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\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n // `new Headers` throws on a malformed caller header, so building them stays\n // inside the catch that turns any pre-flight refusal into the same\n // discriminated network failure a dead socket gets.\n let pinned = false;\n try {\n const headers = withUserAgent(\n { ...opts.headers, ...shelfBypassHeaders(url, opts.bypass) },\n opts.callerUserAgent,\n );\n // fetchJson sends no signed material — doctor's probes and the contract\n // checks are anonymous — so the door key is the one thing here worth\n // pinning, and it pins the same way it does in httpRequest.\n pinned = carriesBypassKey(headers);\n res = await doFetch(url, {\n signal: controller.signal,\n headers: { ...headers, ...(await tenjinIdentityHeaders(url)) },\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED, ahead of the ordinary non-2xx branch, so an unfollowed 3xx is\n // never reported as a plain HTTP status a caller might retry 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 // Where it pointed, not that it pointed: only a hop that leaves the host\n // asked for is evidence about the key. Same-host 3xx happens to a base\n // URL that needs fixing, with a perfectly good key.\n ...(redirectLeavesHost(url, res.headers.get('location'))\n ? { gateOffOrigin: true as const }\n : {}),\n message:\n `Request to ${url} was redirected (${res.status}) while carrying the team shelf's ` +\n 'bypass key; refusing to follow it, because the key opens only the configured origin.',\n };\n }\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n // 401/403 is one of the three shapes deployment protection answers with\n // (200 HTML and a 30x interstitial are the others), so the gate signals\n // ride here too. Other statuses stay unmarked: a 404 or 500 HTML page is\n // an ordinary broken deployment, not a credential problem.\n ...(res.status === 401 || res.status === 403 ? accessGateSignals(url, res) : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n ...accessGateSignals(url, res),\n message: `Response from ${url} was not valid JSON`,\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\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\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. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and search/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** The team shelf's bypass secret and its origin; see {@link ShelfBypass}. */\n bypass?: ShelfBypass;\n /** INTERNAL; see `FetchJsonOptions.callerUserAgent`. */\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 * A caller's own abort, combined with (never replacing) `timeoutMs`. The loop's\n * legs pass the fire's signal here so a harness that closed its socket stops the\n * request in flight; a caller with no such signal is unchanged.\n */\n signal?: AbortSignal;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact (`fetchRead`: the\n * 200 is written to the library as an entitlement record under the\n * server-chosen id/slug), following a cross-origin redirect would let\n * another host's bytes be recorded as if the configured origin served them.\n * Off by default so search/outcome/publish/doctor keep normal 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`. The router's provider leg sets it; every other\n * caller reads text as 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/**\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 bypassed: 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 // The bypass rides in with the caller's headers rather than being set after\n // them, so a caller cannot spell it a second way and win the slot.\n const merged = new Headers({ ...opts.headers, ...shelfBypassHeaders(url, opts.bypass) });\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 // So does a request carrying the team shelf's bypass key: it cannot be\n // replayed, but a 3xx would DISCLOSE it, and that is the whole harm (see\n // carriesBypassKey). A caller can also pin an unsigned, keyless request\n // (blockRedirects) when the response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n const bypassed = carriesBypassKey(headers);\n return {\n ok: true,\n headers,\n body,\n signed,\n bypassed,\n pinned: signed || bypassed || 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 // The caller's abort is combined with the timeout rather than chosen between:\n // whichever fires first ends the request, and `timedOut` still says which.\n const signal =\n opts.signal === undefined\n ? controller.signal\n : AbortSignal.any([controller.signal, opts.signal]);\n\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, bypassed, 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,\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 : bypassed\n ? `Request to ${url} was redirected (${res.status}) while carrying the team shelf's ` +\n 'bypass key; refusing to follow it, because the key opens only 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 ${Math.round((opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES) / 1_048_576)} MB 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 `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans 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 === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\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":";;;;;;;;;;;;AASO,IAAM,iBAAiB,cAAc,gBAAI,OAAO;AAGhD,IAAM,sBAAsB;AAU5B,IAAM,8BAA8B;AACpC,IAAM,yBAAyB,GAAG,2BAA2B,IAAI,gBAAI,OAAO;AAI5E,IAAM,oBAAoB,CAAC,qBAAqB,2BAA2B;AAO3E,IAAM,iBAAiB,KAAK,iBAAiB;AAO7C,IAAM,oBAAoB,GAAG,cAAc,IAAI,cAAc;AAG7D,IAAM,4BAA4B,GAAG,sBAAsB,IAAI,cAAc;AAG7E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