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

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 (284) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +100 -266
  3. package/dist/{_esm-FEASBWRP.js → _esm-MEXZI5DL.js} +9 -10
  4. package/dist/alive-J64H46HI.js +31 -0
  5. package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
  6. package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
  7. package/dist/chunk-27EPWVOY.js +108 -0
  8. package/dist/chunk-27EPWVOY.js.map +1 -0
  9. package/dist/chunk-2SNUOHAT.js +75 -0
  10. package/dist/chunk-2SNUOHAT.js.map +1 -0
  11. package/dist/{chunk-Z6MFJV5Z.js → chunk-2XLC3AEX.js} +857 -504
  12. package/dist/chunk-2XLC3AEX.js.map +1 -0
  13. package/dist/chunk-3623BLPV.js +184 -0
  14. package/dist/chunk-3623BLPV.js.map +1 -0
  15. package/dist/chunk-3UCIG4TG.js +65 -0
  16. package/dist/chunk-3UCIG4TG.js.map +1 -0
  17. package/dist/chunk-4ZZO6ULA.js +151 -0
  18. package/dist/chunk-4ZZO6ULA.js.map +1 -0
  19. package/dist/chunk-5C32RLTA.js +115 -0
  20. package/dist/chunk-5C32RLTA.js.map +1 -0
  21. package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
  22. package/dist/chunk-5K5W4S66.js +105 -0
  23. package/dist/chunk-5K5W4S66.js.map +1 -0
  24. package/dist/chunk-5MARFNSB.js +2018 -0
  25. package/dist/chunk-5MARFNSB.js.map +1 -0
  26. package/dist/{chunk-CYOF7ROH.js → chunk-6E5R45ZO.js} +3 -3
  27. package/dist/chunk-77TCKDEC.js +1987 -0
  28. package/dist/chunk-77TCKDEC.js.map +1 -0
  29. package/dist/chunk-7EKYXMUO.js +7536 -0
  30. package/dist/chunk-7EKYXMUO.js.map +1 -0
  31. package/dist/chunk-7Q5FDF65.js +159 -0
  32. package/dist/chunk-7Q5FDF65.js.map +1 -0
  33. package/dist/chunk-7QKHZQKW.js +1680 -0
  34. package/dist/chunk-7QKHZQKW.js.map +1 -0
  35. package/dist/{chunk-MUBUQVC3.js → chunk-7WEQQJLG.js} +6 -5
  36. package/dist/{chunk-MUBUQVC3.js.map → chunk-7WEQQJLG.js.map} +1 -1
  37. package/dist/chunk-7WU4OPLP.js +244 -0
  38. package/dist/chunk-7WU4OPLP.js.map +1 -0
  39. package/dist/chunk-7ZRL2LBQ.js +192 -0
  40. package/dist/chunk-7ZRL2LBQ.js.map +1 -0
  41. package/dist/chunk-A36LQPHV.js +29 -0
  42. package/dist/chunk-A36LQPHV.js.map +1 -0
  43. package/dist/chunk-AGZ7PJKY.js +326 -0
  44. package/dist/chunk-AGZ7PJKY.js.map +1 -0
  45. package/dist/chunk-AKWGE6JQ.js +49 -0
  46. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  47. package/dist/chunk-B7HUUJOK.js +29 -0
  48. package/dist/chunk-B7HUUJOK.js.map +1 -0
  49. package/dist/{chunk-S3IGX57D.js → chunk-BL3332HQ.js} +290 -7361
  50. package/dist/chunk-BL3332HQ.js.map +1 -0
  51. package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
  52. package/dist/chunk-D65GNPS3.js +12708 -0
  53. package/dist/chunk-D65GNPS3.js.map +1 -0
  54. package/dist/chunk-DOQGNFHM.js +121 -0
  55. package/dist/chunk-DOQGNFHM.js.map +1 -0
  56. package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
  57. package/dist/chunk-FW75G2W4.js +406 -0
  58. package/dist/chunk-FW75G2W4.js.map +1 -0
  59. package/dist/chunk-GA7JETVM.js +150 -0
  60. package/dist/chunk-GA7JETVM.js.map +1 -0
  61. package/dist/chunk-I3EQFHCD.js +175 -0
  62. package/dist/chunk-I3EQFHCD.js.map +1 -0
  63. package/dist/chunk-JKKAIPTU.js +108 -0
  64. package/dist/chunk-JKKAIPTU.js.map +1 -0
  65. package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
  66. package/dist/{chunk-NCE5NSN6.js → chunk-K3I7C2MO.js} +142 -12
  67. package/dist/chunk-K3I7C2MO.js.map +1 -0
  68. package/dist/chunk-K72RURN3.js +239 -0
  69. package/dist/chunk-K72RURN3.js.map +1 -0
  70. package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
  71. package/dist/chunk-KOGZDMHO.js +21 -0
  72. package/dist/chunk-KOGZDMHO.js.map +1 -0
  73. package/dist/chunk-KXQ4UIP7.js +228 -0
  74. package/dist/chunk-KXQ4UIP7.js.map +1 -0
  75. package/dist/chunk-KXVP2VKA.js +194 -0
  76. package/dist/chunk-KXVP2VKA.js.map +1 -0
  77. package/dist/chunk-LEFIX6RS.js +100 -0
  78. package/dist/chunk-LEFIX6RS.js.map +1 -0
  79. package/dist/chunk-LHHMV4GU.js +27 -0
  80. package/dist/chunk-LHHMV4GU.js.map +1 -0
  81. package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
  82. package/dist/chunk-MEFB5KHA.js.map +1 -0
  83. package/dist/chunk-MNXS2U45.js +1768 -0
  84. package/dist/chunk-MNXS2U45.js.map +1 -0
  85. package/dist/{chunk-UGX7YPX2.js → chunk-NEFNKLBE.js} +9 -11
  86. package/dist/{chunk-UGX7YPX2.js.map → chunk-NEFNKLBE.js.map} +1 -1
  87. package/dist/chunk-OHRR5OYM.js +63 -0
  88. package/dist/chunk-OHRR5OYM.js.map +1 -0
  89. package/dist/chunk-ORWL5BSN.js +269 -0
  90. package/dist/chunk-ORWL5BSN.js.map +1 -0
  91. package/dist/chunk-P4NH7OUK.js +398 -0
  92. package/dist/chunk-P4NH7OUK.js.map +1 -0
  93. package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
  94. package/dist/chunk-QSCPK4F5.js +145 -0
  95. package/dist/chunk-QSCPK4F5.js.map +1 -0
  96. package/dist/chunk-QXP3Z3JN.js +131 -0
  97. package/dist/chunk-QXP3Z3JN.js.map +1 -0
  98. package/dist/{chunk-XJIW7USF.js → chunk-R5LCN54M.js} +118 -9
  99. package/dist/chunk-R5LCN54M.js.map +1 -0
  100. package/dist/chunk-S4SAZ7OD.js +30 -0
  101. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  102. package/dist/chunk-SJLTEINJ.js +117 -0
  103. package/dist/chunk-SJLTEINJ.js.map +1 -0
  104. package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
  105. package/dist/chunk-UKY4CHNC.js +498 -0
  106. package/dist/chunk-UKY4CHNC.js.map +1 -0
  107. package/dist/chunk-UQUOVWBG.js +114 -0
  108. package/dist/chunk-UQUOVWBG.js.map +1 -0
  109. package/dist/chunk-V6BSF6OC.js +260 -0
  110. package/dist/chunk-V6BSF6OC.js.map +1 -0
  111. package/dist/chunk-WJXLQXJY.js +43 -0
  112. package/dist/chunk-WJXLQXJY.js.map +1 -0
  113. package/dist/chunk-WK7F3B2E.js +114 -0
  114. package/dist/chunk-WK7F3B2E.js.map +1 -0
  115. package/dist/chunk-XKESD27X.js +10 -0
  116. package/dist/chunk-XKESD27X.js.map +1 -0
  117. package/dist/chunk-XQJXNMSB.js +23 -0
  118. package/dist/chunk-XQJXNMSB.js.map +1 -0
  119. package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
  120. package/dist/chunk-Y527D4TV.js +56 -0
  121. package/dist/chunk-Y527D4TV.js.map +1 -0
  122. package/dist/chunk-YFPY4ONH.js +127 -0
  123. package/dist/chunk-YFPY4ONH.js.map +1 -0
  124. package/dist/{chunk-OYMYCW7J.js → chunk-YVFXE7RR.js} +606 -97
  125. package/dist/chunk-YVFXE7RR.js.map +1 -0
  126. package/dist/clack-EZ7TDWQU.js +19 -0
  127. package/dist/claude-cli-2YKABJJZ.js +31 -0
  128. package/dist/{cli-SBXI5AMS.js → cli-D5OE3URZ.js} +458 -218
  129. package/dist/cli-D5OE3URZ.js.map +1 -0
  130. package/dist/codex-event-PPNVRRDH.js +16 -0
  131. package/dist/codex-host-2RJOJW2B.js +28 -0
  132. package/dist/codex-install-UUZ6QMBQ.js +221 -0
  133. package/dist/codex-install-UUZ6QMBQ.js.map +1 -0
  134. package/dist/config-ZD4OB2DO.js +51 -0
  135. package/dist/dist-3LOO6M4U.js +2842 -0
  136. package/dist/dist-3LOO6M4U.js.map +1 -0
  137. package/dist/doctor-KBR34Q4B.js +601 -0
  138. package/dist/doctor-KBR34Q4B.js.map +1 -0
  139. package/dist/env-proxy-XL4P73MZ.js +15 -0
  140. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  141. package/dist/ethersCompat-Df4a6QIZ-THAVUGIJ.js.map +1 -0
  142. package/dist/fund-5ITKQGYF.js +372 -0
  143. package/dist/fund-5ITKQGYF.js.map +1 -0
  144. package/dist/hook-command-4TYCHHRL.js +39 -0
  145. package/dist/hook-command-4TYCHHRL.js.map +1 -0
  146. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  147. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +15 -0
  148. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  149. package/dist/hosts/claude/tenjin/hooks/hooks.json +224 -0
  150. package/dist/hosts/claude/tenjin/hooks/register.tsx +589 -0
  151. package/dist/hosts/claude/tenjin/types/index.d.ts +41 -0
  152. package/dist/hosts/codex/.agents/plugins/marketplace.json +20 -0
  153. package/dist/hosts/codex/tenjin/.codex-plugin/plugin.json +16 -0
  154. package/dist/hosts/codex/tenjin/.mcp.json +12 -0
  155. package/dist/hosts/codex/tenjin/hooks/hooks.json +52 -0
  156. package/dist/hosts-FWZOV26H.js +216 -0
  157. package/dist/hosts-FWZOV26H.js.map +1 -0
  158. package/dist/index.js +21 -2
  159. package/dist/index.js.map +1 -1
  160. package/dist/install-XWGE4Q7L.js +77 -0
  161. package/dist/install-XWGE4Q7L.js.map +1 -0
  162. package/dist/install-identity-K7EJIQFP.js +30 -0
  163. package/dist/install-identity-K7EJIQFP.js.map +1 -0
  164. package/dist/install-wallet-XQ6XFZV4.js +117 -0
  165. package/dist/install-wallet-XQ6XFZV4.js.map +1 -0
  166. package/dist/mcp-3LIJSSJB.js +13553 -0
  167. package/dist/mcp-3LIJSSJB.js.map +1 -0
  168. package/dist/package-ZKQFDWLE.js +37 -0
  169. package/dist/package-ZKQFDWLE.js.map +1 -0
  170. package/dist/paths-POPTXJO6.js +61 -0
  171. package/dist/paths-POPTXJO6.js.map +1 -0
  172. package/dist/pay-WHBERZ3W.js +55 -0
  173. package/dist/pay-WHBERZ3W.js.map +1 -0
  174. package/dist/payments-KVICEKD2.js +110 -0
  175. package/dist/payments-KVICEKD2.js.map +1 -0
  176. package/dist/plugin-registration-5TIA564H.js +54 -0
  177. package/dist/plugin-registration-5TIA564H.js.map +1 -0
  178. package/dist/redact-6W23GGJC.js +15 -0
  179. package/dist/redact-6W23GGJC.js.map +1 -0
  180. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
  181. package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
  182. package/dist/send-7G7Y7DLN.js +228 -0
  183. package/dist/send-7G7Y7DLN.js.map +1 -0
  184. package/dist/status-OF7RH5HM.js +120 -0
  185. package/dist/status-OF7RH5HM.js.map +1 -0
  186. package/dist/status-line-XOUE6MPL.js +90 -0
  187. package/dist/status-line-XOUE6MPL.js.map +1 -0
  188. package/dist/uninstall-JXUAFNDB.js +158 -0
  189. package/dist/uninstall-JXUAFNDB.js.map +1 -0
  190. package/dist/update-ZKUERSO2.js +44 -0
  191. package/dist/update-ZKUERSO2.js.map +1 -0
  192. package/dist/usdc-OGOGEHV2.js +40 -0
  193. package/dist/usdc-OGOGEHV2.js.map +1 -0
  194. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-S3DA7DFW.js} +5 -5
  195. package/dist/viemAdapter-By13KInL-S3DA7DFW.js.map +1 -0
  196. package/dist/wallet-2HA6W4R4.js +43 -0
  197. package/dist/wallet-2HA6W4R4.js.map +1 -0
  198. package/dist/wallet-kdf-worker.mjs +980 -0
  199. package/docs/agent-permissions.md +196 -0
  200. package/docs/safety-model.md +59 -0
  201. package/docs/troubleshooting.md +13 -0
  202. package/package.json +28 -19
  203. package/LICENSE +0 -21
  204. package/dist/buy-EE6SEXP6.js +0 -1598
  205. package/dist/buy-EE6SEXP6.js.map +0 -1
  206. package/dist/candidate-ERMSYYQZ.js +0 -127
  207. package/dist/candidate-ERMSYYQZ.js.map +0 -1
  208. package/dist/chunk-3OV7E5G5.js +0 -18
  209. package/dist/chunk-3OV7E5G5.js.map +0 -1
  210. package/dist/chunk-4ONXEEQL.js +0 -152
  211. package/dist/chunk-4ONXEEQL.js.map +0 -1
  212. package/dist/chunk-662MSGZB.js +0 -286
  213. package/dist/chunk-662MSGZB.js.map +0 -1
  214. package/dist/chunk-7KUW4MJD.js +0 -59
  215. package/dist/chunk-7KUW4MJD.js.map +0 -1
  216. package/dist/chunk-AWPAWHNX.js +0 -333
  217. package/dist/chunk-AWPAWHNX.js.map +0 -1
  218. package/dist/chunk-DXTQ3CSI.js +0 -171
  219. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  220. package/dist/chunk-ESPNTPQ2.js +0 -207
  221. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  222. package/dist/chunk-FJPLRISB.js +0 -79
  223. package/dist/chunk-FJPLRISB.js.map +0 -1
  224. package/dist/chunk-GO75V3NZ.js +0 -160
  225. package/dist/chunk-GO75V3NZ.js.map +0 -1
  226. package/dist/chunk-JPHG2JW3.js +0 -96
  227. package/dist/chunk-JPHG2JW3.js.map +0 -1
  228. package/dist/chunk-NCE5NSN6.js.map +0 -1
  229. package/dist/chunk-OYMYCW7J.js.map +0 -1
  230. package/dist/chunk-RY4XKNV3.js +0 -140
  231. package/dist/chunk-RY4XKNV3.js.map +0 -1
  232. package/dist/chunk-S3IGX57D.js.map +0 -1
  233. package/dist/chunk-TLCMMYLY.js +0 -126
  234. package/dist/chunk-TLCMMYLY.js.map +0 -1
  235. package/dist/chunk-UO22YNY4.js +0 -69
  236. package/dist/chunk-UO22YNY4.js.map +0 -1
  237. package/dist/chunk-XHC6FCGZ.js +0 -261
  238. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  239. package/dist/chunk-XJIW7USF.js.map +0 -1
  240. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  241. package/dist/chunk-YN5SHIXQ.js +0 -126
  242. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  243. package/dist/chunk-Z52RA3NC.js +0 -137
  244. package/dist/chunk-Z52RA3NC.js.map +0 -1
  245. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  246. package/dist/cli-SBXI5AMS.js.map +0 -1
  247. package/dist/config-VELDKLHY.js +0 -21
  248. package/dist/doctor-T3KWNNP2.js +0 -20
  249. package/dist/inspect-LMKOXE4Y.js +0 -96
  250. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  251. package/dist/install-LEX3ENQ6.js +0 -387
  252. package/dist/install-LEX3ENQ6.js.map +0 -1
  253. package/dist/lookup-ZPN2Q67N.js +0 -129
  254. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  255. package/dist/outcome-N7TAK6WR.js +0 -66
  256. package/dist/outcome-N7TAK6WR.js.map +0 -1
  257. package/dist/publish-BKBQQAW4.js +0 -1478
  258. package/dist/publish-BKBQQAW4.js.map +0 -1
  259. package/dist/usdc-JIAJW4SV.js +0 -22
  260. package/dist/wallet-CWEMYVIH.js +0 -179
  261. package/dist/wallet-CWEMYVIH.js.map +0 -1
  262. package/dist/wallet-PA54CRBL.js +0 -30
  263. package/skills/tenjin/SKILL.md +0 -199
  264. package/skills/tenjin-publish/SKILL.md +0 -111
  265. package/skills/tenjin-search/SKILL.md +0 -133
  266. /package/dist/{_esm-FEASBWRP.js.map → _esm-MEXZI5DL.js.map} +0 -0
  267. /package/dist/{ccip-NQXCEK2U.js.map → alive-J64H46HI.js.map} +0 -0
  268. /package/dist/{ccip-XR5NE5QK.js.map → ccip-7RMRLAGV.js.map} +0 -0
  269. /package/dist/{config-VELDKLHY.js.map → ccip-NLCSCHKI.js.map} +0 -0
  270. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
  271. /package/dist/{chunk-CYOF7ROH.js.map → chunk-6E5R45ZO.js.map} +0 -0
  272. /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
  273. /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
  274. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  275. /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
  276. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
  277. /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
  278. /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
  279. /package/dist/{doctor-T3KWNNP2.js.map → clack-EZ7TDWQU.js.map} +0 -0
  280. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → claude-cli-2YKABJJZ.js.map} +0 -0
  281. /package/dist/{secp256k1-N3ZHU7LB.js.map → codex-event-PPNVRRDH.js.map} +0 -0
  282. /package/dist/{usdc-JIAJW4SV.js.map → codex-host-2RJOJW2B.js.map} +0 -0
  283. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → config-ZD4OB2DO.js.map} +0 -0
  284. /package/dist/{wallet-PA54CRBL.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
@@ -0,0 +1,498 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ fetchFailureToCliError,
4
+ httpRequest
5
+ } from "./chunk-AGZ7PJKY.js";
6
+ import {
7
+ external_exports
8
+ } from "./chunk-YVFXE7RR.js";
9
+
10
+ // src/router/decision.ts
11
+ var ROUTER_PATH = "/api/x402-router";
12
+ var RequestSchema = external_exports.object({
13
+ url: external_exports.string().min(1).max(16384),
14
+ method: external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]),
15
+ headers: external_exports.record(external_exports.string(), external_exports.string()),
16
+ body: external_exports.string().max(256 * 1024).optional()
17
+ });
18
+ var ContractSchema = external_exports.object({
19
+ /** Flat, for display and for the result check; never re-encoded into a call:
20
+ * the server built `request` from them and this client sends that verbatim. */
21
+ arguments: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
22
+ resultSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
23
+ request: RequestSchema
24
+ });
25
+ var DiagnosticsSchema = external_exports.object({
26
+ reasonCode: external_exports.string().min(1).max(64),
27
+ stage: external_exports.string().min(1).max(32),
28
+ missing: external_exports.array(external_exports.string().max(200)).max(60),
29
+ nextAction: external_exports.string().max(500)
30
+ });
31
+ var IdSchema = external_exports.string().regex(/^[A-Za-z0-9_-]{8,64}$/).describe(
32
+ "The turn id, an OPAQUE HANDLE: it is the one piece of server text this client puts in a model-facing line, so the alphabet is pinned here rather than escaped later."
33
+ );
34
+ var RefusedSchema = external_exports.strictObject({
35
+ reason: external_exports.string().max(2e3).optional(),
36
+ diagnostics: DiagnosticsSchema
37
+ });
38
+ var LabelSchema = external_exports.string().min(1).max(32);
39
+ var CapabilityFields = {
40
+ capabilityId: external_exports.string().min(1).max(200),
41
+ category: external_exports.string().min(1).max(64),
42
+ /** The service's own name, not the x402 reseller in front of it. */
43
+ provider: external_exports.string().min(1).max(120),
44
+ label: LabelSchema.optional(),
45
+ capabilityDescription: external_exports.string().min(1).max(500),
46
+ /** What the provider charges, atomic USDC. The `request` tool refuses a live
47
+ * 402 above it; `gateSpend` still caps the amount actually signed. */
48
+ providerPriceAtomic: external_exports.string().regex(/^\d+$/)
49
+ };
50
+ function checkHint(decision, ctx) {
51
+ if (/[\p{Cc}\p{Cf}]/u.test(decision.hint)) {
52
+ ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint is one plain line" });
53
+ }
54
+ if (!decision.hint.includes("request({")) {
55
+ ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint names the call to make" });
56
+ }
57
+ if (!decision.hint.includes(decision.id)) {
58
+ ctx.addIssue({
59
+ code: "custom",
60
+ path: ["hint"],
61
+ message: "a hint carries this answer's own id"
62
+ });
63
+ }
64
+ }
65
+ var DiscoveredCandidateSchema = external_exports.strictObject({
66
+ source: external_exports.string().min(1).max(64),
67
+ provider: external_exports.string().min(1).max(120),
68
+ url: external_exports.string().min(1).max(2048),
69
+ method: external_exports.enum(["GET", "POST"]),
70
+ description: external_exports.string().max(500),
71
+ providerPriceAtomic: external_exports.string().regex(/^\d+$/),
72
+ network: external_exports.string().min(1).max(64),
73
+ payTo: external_exports.string().min(1).max(200),
74
+ input: external_exports.strictObject({
75
+ location: external_exports.enum(["body", "query"]),
76
+ schema: external_exports.record(external_exports.string(), external_exports.unknown())
77
+ })
78
+ });
79
+ var JobField = external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/);
80
+ var JobFieldStateSchema = external_exports.strictObject({
81
+ field: JobField,
82
+ values: external_exports.array(external_exports.string().min(1).max(64)).min(1).max(8)
83
+ });
84
+ var POLL_REFERENCE = /^\$(input|result)\.([A-Za-z_][A-Za-z0-9_]{0,63})$/;
85
+ var JobSchema = external_exports.strictObject({
86
+ pollUrl: external_exports.union([
87
+ external_exports.strictObject({
88
+ field: JobField.optional(),
89
+ header: external_exports.string().regex(/^[A-Za-z0-9-]{1,64}$/).optional()
90
+ }).refine((at) => at.field !== void 0 || at.header !== void 0, "a field or a header"),
91
+ external_exports.strictObject({ fixed: external_exports.string().min(1).max(2048) })
92
+ ]),
93
+ /** Sent once like a poll after the result is saved, never after a save
94
+ * that failed: it frees the seller's copy (AiSpace's `/complete`). Its
95
+ * answer is ignored. */
96
+ completeUrl: external_exports.strictObject({ fixed: external_exports.string().min(1).max(2048) }).optional(),
97
+ pollMethod: external_exports.enum(["GET", "POST"]),
98
+ pollBody: external_exports.record(JobField, external_exports.unknown()).refine(
99
+ (body) => Object.values(body).every(
100
+ (value) => typeof value !== "string" || !value.startsWith("$") || POLL_REFERENCE.test(value)
101
+ ),
102
+ "a $ value is $input.<field> or $result.<field>"
103
+ ).optional(),
104
+ running: external_exports.union([
105
+ external_exports.strictObject({ httpStatus: external_exports.array(external_exports.number().int().min(200).max(299)).min(1).max(8) }),
106
+ JobFieldStateSchema
107
+ ]),
108
+ failed: JobFieldStateSchema.optional(),
109
+ everyS: external_exports.number().int().min(1).max(30),
110
+ maxWaitS: external_exports.number().int().min(1).max(600),
111
+ keepH: external_exports.number().int().min(1).max(48),
112
+ always: external_exports.literal(true).optional()
113
+ }).refine((job) => !job.pollBody || job.pollMethod === "POST", "only a POST poll has a body");
114
+ var ToolSpecSchema = external_exports.strictObject({
115
+ capabilityId: external_exports.string().min(1).max(200),
116
+ provider: external_exports.string().min(1).max(120),
117
+ /** The display name, on a catalog service's spec; a Bazaar spec has none. */
118
+ label: LabelSchema.optional(),
119
+ /** The input field that takes a pending search's query or fetch's URL. */
120
+ holds: external_exports.strictObject({
121
+ WebSearch: external_exports.string().min(1).max(64).optional(),
122
+ WebFetch: external_exports.string().min(1).max(64).optional()
123
+ }).optional(),
124
+ /** What a paid result is. `media` means its files (bytes, links or inline
125
+ * base64) are saved locally; absent on a Bazaar spec. */
126
+ output: external_exports.enum(["json", "text", "media"]).optional(),
127
+ description: external_exports.string().min(1).max(500),
128
+ priceAtomic: external_exports.string().regex(/^\d+$/),
129
+ priceVaries: external_exports.boolean(),
130
+ maxAmountAtomic: external_exports.string().regex(/^\d+$/),
131
+ payTo: external_exports.string().min(1).max(200),
132
+ network: external_exports.string().min(1).max(64),
133
+ asset: external_exports.string().min(1).max(200),
134
+ request: external_exports.strictObject({
135
+ method: external_exports.enum(["GET", "POST"]),
136
+ url: external_exports.string().min(1).max(2048),
137
+ fields: external_exports.record(external_exports.string(), external_exports.enum(["path", "query", "body"])),
138
+ location: external_exports.enum(["query", "body"])
139
+ }),
140
+ input: external_exports.record(external_exports.string(), external_exports.unknown()),
141
+ pinned: external_exports.record(external_exports.string(), external_exports.unknown()),
142
+ example: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
143
+ returns: external_exports.string().min(1).max(200).optional(),
144
+ returnsExample: external_exports.unknown().optional(),
145
+ resultSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
146
+ /** The fields the result promises (type, properties, items, required). The
147
+ * agent is handed only these; the whole body is saved to a file. */
148
+ outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
149
+ /** How a call answered before its result is ready is finished. */
150
+ job: JobSchema.optional(),
151
+ /** A media service that runs several takes of one call: `count` up to `max`. */
152
+ takes: external_exports.strictObject({ max: external_exports.number().int().min(2).max(5) }).optional()
153
+ });
154
+ var OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });
155
+ var SpecsSchema = external_exports.array(OfferSpecSchema).min(1).max(8).optional();
156
+ var PlainLine = (max) => external_exports.string().min(1).max(max).refine((text) => !/[\p{Cc}\p{Cf}]/u.test(text), "one plain line");
157
+ var ChoicesSchema = external_exports.strictObject({
158
+ group: PlainLine(64),
159
+ default: PlainLine(64),
160
+ input: external_exports.array(PlainLine(64)).min(1).max(16),
161
+ options: external_exports.array(
162
+ external_exports.strictObject({
163
+ key: PlainLine(64),
164
+ label: PlainLine(120),
165
+ strength: PlainLine(300),
166
+ id: IdSchema
167
+ })
168
+ ).min(2).max(4),
169
+ all: external_exports.strictObject({ totalAtomic: external_exports.string().regex(/^\d+$/) })
170
+ });
171
+ var ALL_CHOICES = "all";
172
+ function checkChoices(decision, ctx) {
173
+ const { choices } = decision;
174
+ if (choices === void 0) return;
175
+ const issue = (message) => ctx.addIssue({ code: "custom", path: ["choices"], message });
176
+ const keys = choices.options.map((option) => option.key);
177
+ const ids = choices.options.map((option) => option.id);
178
+ if (new Set(keys).size !== keys.length) issue("each choice key is named once");
179
+ if (new Set(ids).size !== ids.length) issue("each choice id is named once");
180
+ if (keys.includes(ALL_CHOICES)) issue(`"${ALL_CHOICES}" runs every choice, so it is no key`);
181
+ const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));
182
+ if (ids.some((id) => !specIds.has(id))) issue("every choice carries its spec");
183
+ const fallback = choices.options.find((option) => option.key === choices.default);
184
+ if (fallback === void 0) issue("the default is one of the choices");
185
+ else if (fallback.id !== decision.id) issue("the default choice is this answer's own offer");
186
+ }
187
+ var DiscoveredSchema = external_exports.strictObject({
188
+ action: external_exports.literal("discovered"),
189
+ id: IdSchema,
190
+ candidate: DiscoveredCandidateSchema,
191
+ /** THE LINE, FINISHED, as on `execute`: it carries the seller's
192
+ * description and the input it takes. */
193
+ hint: external_exports.string().min(1).max(2e3),
194
+ specs: SpecsSchema,
195
+ choices: ChoicesSchema.optional()
196
+ }).superRefine(checkHint).superRefine(checkChoices);
197
+ var HookDecisionSchema = external_exports.discriminatedUnion("action", [
198
+ external_exports.strictObject({
199
+ action: external_exports.literal("execute"),
200
+ id: IdSchema,
201
+ ...CapabilityFields,
202
+ /** The x402 URL a lookup would pay, for the line the server writes. */
203
+ endpoint: external_exports.string().min(1).max(2048),
204
+ /** What to pass in `query`, in the service's own terms. */
205
+ usage: external_exports.string().min(1).max(300),
206
+ /**
207
+ * THE LINE, FINISHED. The server writes it with the real id in it and, on a
208
+ * native call, the exact search or URL that was denied. The client injects
209
+ * it and composes nothing, which is why there is no hint builder here any
210
+ * more: two sides writing the same sentence is how they drift. The same
211
+ * bound as a discovered line's.
212
+ */
213
+ hint: external_exports.string().min(1).max(2e3),
214
+ specs: SpecsSchema,
215
+ /**
216
+ * HOW THE OFFER IS DELIVERED, sent because this build lists `fields`.
217
+ * `augment` is the free docs lookup before a search: the client shows no
218
+ * line and puts what `augmentUrl` returns above the search's own
219
+ * results. `offer` is every line the client shows. Absent (a server
220
+ * from before the token), a free curated offer before a search is read
221
+ * as `augment`, as builds before this one did.
222
+ */
223
+ delivery: external_exports.enum(["offer", "augment"]).optional(),
224
+ augmentUrl: external_exports.string().url().max(2048).optional()
225
+ }).superRefine(checkHint),
226
+ DiscoveredSchema,
227
+ RefusedSchema.extend({ action: external_exports.literal("native") }),
228
+ RefusedSchema.extend({ action: external_exports.literal("needs_input") })
229
+ ]);
230
+ var ToolDecisionSchema = external_exports.discriminatedUnion("action", [
231
+ external_exports.strictObject({
232
+ action: external_exports.literal("execute"),
233
+ ...CapabilityFields,
234
+ contract: ContractSchema
235
+ }),
236
+ /**
237
+ * A query with no id, answered with the spec of the service the server
238
+ * picked under a fresh `id`: kept like a hook's, and never run in the same
239
+ * call. `hint` is the line, with the skeleton of the next call:
240
+ * `request({id, input: {...}})` with the required fields. `input` is what a
241
+ * router from before the binder's removal still sends on a bound pick: it
242
+ * is accepted so that answer parses, and never read, so it never runs.
243
+ */
244
+ external_exports.strictObject({
245
+ action: external_exports.literal("spec"),
246
+ id: IdSchema,
247
+ spec: ToolSpecSchema,
248
+ hint: external_exports.string().min(1).max(2e3),
249
+ input: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
250
+ }).superRefine(checkHint),
251
+ DiscoveredSchema,
252
+ RefusedSchema.extend({ action: external_exports.literal("native") }),
253
+ RefusedSchema.extend({ action: external_exports.literal("needs_input") })
254
+ ]);
255
+ function envelope(decision) {
256
+ return external_exports.strictObject({
257
+ schemaVersion: external_exports.literal(1),
258
+ routerVersion: external_exports.string().min(1).max(64),
259
+ decision,
260
+ /** A plain sentence about the CALL, such as an id that had expired. Never a
261
+ * failure: the decision beside it ran anyway. */
262
+ note: external_exports.string().max(500).optional(),
263
+ jev: external_exports.object({ calls: external_exports.number(), latencyMs: external_exports.number() }).optional()
264
+ });
265
+ }
266
+ var HookResponseSchema = envelope(HookDecisionSchema);
267
+ var ToolResponseSchema = envelope(ToolDecisionSchema);
268
+ var BrowseRowSchema = external_exports.strictObject({
269
+ id: external_exports.string().min(1).max(200).regex(/^[A-Za-z0-9._:-]+$/),
270
+ label: external_exports.string().min(1).max(120),
271
+ does: external_exports.string().min(1).max(500),
272
+ price: external_exports.string().min(1).max(32),
273
+ free: external_exports.boolean(),
274
+ kind: external_exports.string().min(1).max(120)
275
+ });
276
+ var BrowseResponseSchema = external_exports.strictObject({
277
+ schemaVersion: external_exports.literal(1),
278
+ routerVersion: external_exports.string().min(1).max(64),
279
+ rows: external_exports.array(BrowseRowSchema).max(200)
280
+ });
281
+ var CLIENT_ACCEPTS = ["catalog", "spec", "label", "fields", "jobs"];
282
+ var BAZAAR_ACCEPT = "bazaar";
283
+ function acceptsFor(bazaar) {
284
+ return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];
285
+ }
286
+ function buildHookBody(packet, extras = {}) {
287
+ return {
288
+ schemaVersion: 1,
289
+ ...extras.sessionId !== void 0 ? { sessionId: extras.sessionId } : {},
290
+ ...extras.accepts !== void 0 ? { accepts: [...extras.accepts] } : {},
291
+ ...extras.harness !== void 0 ? { harness: extras.harness } : {},
292
+ packet
293
+ };
294
+ }
295
+ function buildToolBody(request) {
296
+ return {
297
+ schemaVersion: 1,
298
+ ...request.query !== void 0 ? { query: request.query } : {},
299
+ ...request.id !== void 0 ? { id: request.id } : {},
300
+ ...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {},
301
+ ...request.accepts !== void 0 ? { accepts: [...request.accepts] } : {},
302
+ ...request.harness !== void 0 ? { harness: request.harness } : {}
303
+ };
304
+ }
305
+ function buildBrowseBody(request) {
306
+ return {
307
+ schemaVersion: 1,
308
+ browse: request.browse,
309
+ accepts: [...request.accepts],
310
+ ...request.harness !== void 0 ? { harness: request.harness } : {}
311
+ };
312
+ }
313
+ function buildToolSpecBody(request) {
314
+ return {
315
+ schemaVersion: 1,
316
+ tool: request.tool,
317
+ accepts: [...request.accepts],
318
+ ...request.harness !== void 0 ? { harness: request.harness } : {}
319
+ };
320
+ }
321
+ var RouteSkipped = class extends Error {
322
+ /** `unreached`: the paid call could not reach the router
323
+ * ({@link isUnreachable}), so the free path, on the same host, is not
324
+ * tried and the call reads as that transport failure. */
325
+ constructor(why, unreached) {
326
+ super(`routing fee not paid: ${why}`);
327
+ this.why = why;
328
+ this.unreached = unreached;
329
+ }
330
+ why;
331
+ unreached;
332
+ };
333
+ var CHANNEL_BUSY = "channel_busy";
334
+ var PAID_PATH_ABSENT = "paid_path_absent";
335
+ var PAYMENT_FAILED = "payment_failed";
336
+ var DEADLINE_AFTER_PAYMENT_SENT = "deadline_after_payment_sent";
337
+ async function requestDecision(kind, request, deps) {
338
+ const url = new URL(deps.route?.path ?? ROUTER_PATH, deps.baseUrl).toString();
339
+ const options = {
340
+ method: "POST",
341
+ timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,
342
+ blockRedirects: true,
343
+ jsonBody: kind === "hook" ? buildHookBody(request.packet, {
344
+ ...request.sessionId !== void 0 ? { sessionId: request.sessionId } : {},
345
+ accepts: acceptsFor(deps.acceptsBazaar === true),
346
+ harness: deps.harness ?? "claude"
347
+ }) : buildToolBody({
348
+ ...request.query !== void 0 ? { query: request.query } : {},
349
+ ...request.id !== void 0 ? { id: request.id } : {},
350
+ ...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {},
351
+ accepts: acceptsFor(deps.acceptsBazaar === true),
352
+ harness: deps.harness ?? "claude"
353
+ }),
354
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
355
+ };
356
+ const started = Date.now();
357
+ const schema = kind === "hook" ? HookResponseSchema : ToolResponseSchema;
358
+ let response;
359
+ try {
360
+ response = await (deps.route?.send ?? httpRequest)(url, options);
361
+ } catch (err) {
362
+ if (!(err instanceof RouteSkipped)) throw err;
363
+ if (err.unreached !== void 0) return readDecision(err.unreached, schema);
364
+ const left = options.timeoutMs - (Date.now() - started);
365
+ if (left <= 0) return { status: "skipped", why: err.why };
366
+ response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {
367
+ ...options,
368
+ timeoutMs: left
369
+ });
370
+ const free = readDecision(response, schema);
371
+ if (free.status === "failed") {
372
+ return {
373
+ status: "failed",
374
+ reason: free.reason,
375
+ ...free.errorCode !== void 0 ? { errorCode: free.errorCode } : {},
376
+ // Still no answer, which must not end another call's backoff.
377
+ ...free.noAnswer === true ? { noAnswer: true } : {},
378
+ freePath: err.why
379
+ };
380
+ }
381
+ return free.status === "skipped" ? free : { ...free, freePath: err.why };
382
+ }
383
+ return readDecision(response, schema);
384
+ }
385
+ async function requestBrowse(browse, deps) {
386
+ return readDecision(
387
+ await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {
388
+ method: "POST",
389
+ timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,
390
+ blockRedirects: true,
391
+ jsonBody: buildBrowseBody({
392
+ browse,
393
+ accepts: acceptsFor(deps.acceptsBazaar === true),
394
+ harness: deps.harness ?? "claude"
395
+ }),
396
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
397
+ }),
398
+ BrowseResponseSchema
399
+ );
400
+ }
401
+ async function requestToolSpec(tool, deps) {
402
+ return readDecision(
403
+ await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {
404
+ method: "POST",
405
+ timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,
406
+ blockRedirects: true,
407
+ jsonBody: buildToolSpecBody({
408
+ tool,
409
+ accepts: acceptsFor(deps.acceptsBazaar === true),
410
+ harness: deps.harness ?? "claude"
411
+ }),
412
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
413
+ }),
414
+ ToolResponseSchema
415
+ );
416
+ }
417
+ var OUTCOME_TIMEOUT_MS = 3e3;
418
+ async function reportSpecOutcome(outcome, deps) {
419
+ try {
420
+ await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {
421
+ method: "POST",
422
+ timeoutMs: OUTCOME_TIMEOUT_MS,
423
+ blockRedirects: true,
424
+ jsonBody: buildOutcomeBody(outcome, deps.harness ?? "claude"),
425
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
426
+ });
427
+ } catch {
428
+ }
429
+ }
430
+ function buildOutcomeBody(outcome, harness) {
431
+ return {
432
+ schemaVersion: 1,
433
+ id: outcome.id,
434
+ ...harness !== void 0 ? { harness } : {},
435
+ status: outcome.status,
436
+ ...outcome.reason !== void 0 ? { reason: outcome.reason } : {},
437
+ ...outcome.httpStatus !== void 0 ? { httpStatus: outcome.httpStatus } : {},
438
+ ...outcome.ms !== void 0 ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}
439
+ };
440
+ }
441
+ function readDecision(response, schema) {
442
+ if (!response.ok) {
443
+ return {
444
+ status: "failed",
445
+ reason: fetchFailureToCliError(response).message,
446
+ ...isUnreachable(response) ? { unreachable: true } : {},
447
+ ...response.status === void 0 ? { noAnswer: true } : {}
448
+ };
449
+ }
450
+ if (response.status < 200 || response.status >= 300) {
451
+ const named = errorOf(response.json);
452
+ return {
453
+ status: "failed",
454
+ // The backend's own code and message, never a bare status line: a typed
455
+ // refusal the host could act on was arriving as "answered 400".
456
+ reason: named === null ? `The router endpoint answered ${response.status}.` : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,
457
+ ...named !== null ? { errorCode: named.code } : {}
458
+ };
459
+ }
460
+ const parsed = schema.safeParse(response.json);
461
+ if (!parsed.success) {
462
+ return { status: "failed", reason: "The router returned a decision this build cannot read." };
463
+ }
464
+ return { status: "decided", decision: parsed.data };
465
+ }
466
+ function errorOf(body) {
467
+ if (body === null || typeof body !== "object") return null;
468
+ const error = body.error;
469
+ if (error === null || typeof error !== "object") return null;
470
+ const { code, message } = error;
471
+ if (typeof code !== "string" || code.length === 0 || code.length > 64) return null;
472
+ const text = typeof message === "string" ? message.slice(0, 500) : "";
473
+ return { code, message: text };
474
+ }
475
+ var RESET_CODES = /* @__PURE__ */ new Set(["ECONNRESET", "UND_ERR_SOCKET"]);
476
+ function isUnreachable(failure) {
477
+ return failure.kind === "network" && failure.status === void 0 && failure.transport !== void 0 && !RESET_CODES.has(failure.transport.code ?? "");
478
+ }
479
+
480
+ export {
481
+ ROUTER_PATH,
482
+ POLL_REFERENCE,
483
+ JobSchema,
484
+ OfferSpecSchema,
485
+ ChoicesSchema,
486
+ ALL_CHOICES,
487
+ RouteSkipped,
488
+ CHANNEL_BUSY,
489
+ PAID_PATH_ABSENT,
490
+ PAYMENT_FAILED,
491
+ DEADLINE_AFTER_PAYMENT_SENT,
492
+ requestDecision,
493
+ requestBrowse,
494
+ requestToolSpec,
495
+ reportSpecOutcome,
496
+ isUnreachable
497
+ };
498
+ //# sourceMappingURL=chunk-UKY4CHNC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { FetchJsonFailure, HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\nimport type { Harness } from './names';\n\n/**\n * `POST /api/x402-router`: ONE DECISION PER LOOKUP. On the free path it costs\n * nothing. Inside `tenjin mcp`, while the server answers its paid path, the\n * same body goes to that path through the stock x402 client\n * ({@link DecisionRoute}, `routing-payer.ts`); a call that path cannot take\n * falls back to the free path. The rest of this note describes the free path,\n * which is unchanged.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * The bounded packet travels with the hook request and the backend keeps it\n * against the decision id until that id expires. What this client keeps is\n * each offer's spec, by its id (`specs.ts`).\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\n/** A display name the server gives a capability, sent because this build\n * lists `label`. Shown exactly as given; absent, a surface says\n * {@link UNLABELLED}. */\nconst LabelSchema = z.string().min(1).max(32);\n\n/** What a surface names a lookup whose decision carries no `label`. */\nexport const UNLABELLED = 'Tenjin lookup';\n\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n label: LabelSchema.optional(),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When a Tenjin list service does the\n * task the gate picked, or no task fits and a listed x402 service could do the\n * step, the server names that one service: who sells it, where, for how much,\n * and the input it takes. A Tenjin list service arrives here under its catalog\n * id, because this build sends `catalog`. The candidate is the seller's own\n * listing, so every field is data for the host to judge, never an instruction;\n * the host builds the `input` and the tool call pays through the same `runPay`\n * path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.strictObject({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.strictObject({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/** A field name a job reads from an answer or writes into a poll body. */\nconst JobField = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/);\n\n/** A body field whose value names a state: Treza's `status: \"running\"`. */\nconst JobFieldStateSchema = z.strictObject({\n field: JobField,\n values: z.array(z.string().min(1).max(64)).min(1).max(8),\n});\n\n/** A poll body value naming a field of the call's input or of the submit's\n * answer; any other value is sent as written. */\nexport const POLL_REFERENCE = /^\\$(input|result)\\.([A-Za-z_][A-Za-z0-9_]{0,63})$/;\n\n/**\n * HOW A CALL WHOSE SELLER ANSWERS BEFORE THE RESULT IS READY IS FINISHED, sent\n * on a spec only because this build asks for it (`accepts: [\"jobs\"]`): where\n * the status is (a field or header of the submit's answer, or one fixed URL),\n * how a poll is sent, what says it is still running or failed, how often and\n * how long to poll, and how many hours the job can be resumed. `always`: the\n * seller never answers inline. A poll is never signed: the take's one payment\n * is its submit. Every field is the server's: the poll and complete URLs are\n * still checked here against the submit's host (`jobs.ts`).\n */\nexport const JobSchema = z\n .strictObject({\n pollUrl: z.union([\n z\n .strictObject({\n field: JobField.optional(),\n header: z\n .string()\n .regex(/^[A-Za-z0-9-]{1,64}$/)\n .optional(),\n })\n .refine((at) => at.field !== undefined || at.header !== undefined, 'a field or a header'),\n z.strictObject({ fixed: z.string().min(1).max(2_048) }),\n ]),\n /** Sent once like a poll after the result is saved, never after a save\n * that failed: it frees the seller's copy (AiSpace's `/complete`). Its\n * answer is ignored. */\n completeUrl: z.strictObject({ fixed: z.string().min(1).max(2_048) }).optional(),\n pollMethod: z.enum(['GET', 'POST']),\n pollBody: z\n .record(JobField, z.unknown())\n .refine(\n (body) =>\n Object.values(body).every(\n (value) =>\n typeof value !== 'string' || !value.startsWith('$') || POLL_REFERENCE.test(value),\n ),\n 'a $ value is $input.<field> or $result.<field>',\n )\n .optional(),\n running: z.union([\n z.strictObject({ httpStatus: z.array(z.number().int().min(200).max(299)).min(1).max(8) }),\n JobFieldStateSchema,\n ]),\n failed: JobFieldStateSchema.optional(),\n everyS: z.number().int().min(1).max(30),\n maxWaitS: z.number().int().min(1).max(600),\n keepH: z.number().int().min(1).max(48),\n always: z.literal(true).optional(),\n })\n .refine((job) => !job.pollBody || job.pollMethod === 'POST', 'only a POST poll has a body');\nexport type Job = z.infer<typeof JobSchema>;\n\n/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n /** The display name, on a catalog service's spec; a Bazaar spec has none. */\n label: LabelSchema.optional(),\n /** The input field that takes a pending search's query or fetch's URL. */\n holds: z\n .strictObject({\n WebSearch: z.string().min(1).max(64).optional(),\n WebFetch: z.string().min(1).max(64).optional(),\n })\n .optional(),\n /** What a paid result is. `media` means its files (bytes, links or inline\n * base64) are saved locally; absent on a Bazaar spec. */\n output: z.enum(['json', 'text', 'media']).optional(),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.strictObject({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n /** The fields the result promises (type, properties, items, required). The\n * agent is handed only these; the whole body is saved to a file. */\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n /** How a call answered before its result is ready is finished. */\n job: JobSchema.optional(),\n /** A media service that runs several takes of one call: `count` up to `max`. */\n takes: z.strictObject({ max: z.number().int().min(2).max(5) }).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer, any other service it\n * lists, and each option of a choice set. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(8).optional();\n\n/** Words this client shows the model itself, in its own line: one plain line. */\nconst PlainLine = (max: number) =>\n z\n .string()\n .min(1)\n .max(max)\n .refine((text) => !/[\\p{Cc}\\p{Cf}]/u.test(text), 'one plain line');\n\n/**\n * SERVICES THE USER PICKS BETWEEN, OR RUNS ALL OF. Sent only beside a\n * discovered offer, to a build that lists `catalog` in `accepts`. Each option\n * is a real offer: its own id, its own spec in `specs`, and its own one\n * payment, so `request({id, choice})` runs exactly the spec\n * `request({id: option.id})` would. `all` runs every option side by side, one\n * payment each. The set is the server's data: changing it is a deploy there,\n * not a release here. `input` names the open fields the options share, the\n * only ones an `all` call may carry.\n */\nexport const ChoicesSchema = z.strictObject({\n group: PlainLine(64),\n default: PlainLine(64),\n input: z.array(PlainLine(64)).min(1).max(16),\n options: z\n .array(\n z.strictObject({\n key: PlainLine(64),\n label: PlainLine(120),\n strength: PlainLine(300),\n id: IdSchema,\n }),\n )\n .min(2)\n .max(4),\n all: z.strictObject({ totalAtomic: z.string().regex(/^\\d+$/) }),\n});\nexport type Choices = z.infer<typeof ChoicesSchema>;\n\n/** The word that runs every option, so no option may take it as its key. */\nexport const ALL_CHOICES = 'all';\n\n/**\n * A CHOICE NAMES ONLY WHAT THIS ANSWER CARRIES: each key and id once, `all`\n * free for the whole set, a spec for every option, and the default option is\n * the offer this answer's id already names. A set that breaks any of these is\n * a protocol error, and the turn falls back like any unreadable answer.\n */\nfunction checkChoices(\n decision: { id: string; specs?: { id: string }[] | undefined; choices?: Choices | undefined },\n ctx: z.RefinementCtx,\n): void {\n const { choices } = decision;\n if (choices === undefined) return;\n const issue = (message: string) => ctx.addIssue({ code: 'custom', path: ['choices'], message });\n const keys = choices.options.map((option) => option.key);\n const ids = choices.options.map((option) => option.id);\n if (new Set(keys).size !== keys.length) issue('each choice key is named once');\n if (new Set(ids).size !== ids.length) issue('each choice id is named once');\n if (keys.includes(ALL_CHOICES)) issue(`\"${ALL_CHOICES}\" runs every choice, so it is no key`);\n const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));\n if (ids.some((id) => !specIds.has(id))) issue('every choice carries its spec');\n const fallback = choices.options.find((option) => option.key === choices.default);\n if (fallback === undefined) issue('the default is one of the choices');\n else if (fallback.id !== decision.id) issue(\"the default choice is this answer's own offer\");\n}\n\n/** The same answer on both calls: the hook's offer, and the tool's answer\n * when a query with no id found a service nobody curated. */\nconst DiscoveredSchema = z\n .strictObject({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n choices: ChoicesSchema.optional(),\n })\n .superRefine(checkHint)\n .superRefine(checkChoices);\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n /**\n * HOW THE OFFER IS DELIVERED, sent because this build lists `fields`.\n * `augment` is the free docs lookup before a search: the client shows no\n * line and puts what `augmentUrl` returns above the search's own\n * results. `offer` is every line the client shows. Absent (a server\n * from before the token), a free curated offer before a search is read\n * as `augment`, as builds before this one did.\n */\n delivery: z.enum(['offer', 'augment']).optional(),\n augmentUrl: z.string().url().max(2_048).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's, and never run in the same\n * call. `hint` is the line, with the skeleton of the next call:\n * `request({id, input: {...}})` with the required fields. `input` is what a\n * router from before the binder's removal still sends on a bound pick: it\n * is accepted so that answer parses, and never read, so it never runs.\n */\n z\n .strictObject({\n action: z.literal('spec'),\n id: IdSchema,\n spec: ToolSpecSchema,\n hint: z.string().min(1).max(2_000),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\n/**\n * ONE ROW OF THE TOOL LIST, as the free browse answers it: the tool's id, its\n * display name (a list entry's upstream name runs to 120 characters), what it\n * does, its price as the server writes it, and its kind. Strict like every\n * answer here, with the server's own bounds. The id is the one field the model\n * sends back, so its alphabet is pinned; the text is flattened to one line\n * where it is shown (`tool.ts`).\n */\nconst BrowseRowSchema = z.strictObject({\n id: z\n .string()\n .min(1)\n .max(200)\n .regex(/^[A-Za-z0-9._:-]+$/),\n label: z.string().min(1).max(120),\n does: z.string().min(1).max(500),\n price: z.string().min(1).max(32),\n free: z.boolean(),\n kind: z.string().min(1).max(120),\n});\nexport type BrowseRow = z.infer<typeof BrowseRowSchema>;\n\nconst BrowseResponseSchema = z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n rows: z.array(BrowseRowSchema).max(200),\n});\nexport type BrowseResponse = z.infer<typeof BrowseResponseSchema>;\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool' | 'browse';\n\n/**\n * What this client can act on beyond the curated answers, sent on every call.\n * Each token names one kind of feature this build parses and runs, and the\n * server ignores a token it does not know, so the list only ever grows.\n * `label` takes each catalog service's display name on its spec and both\n * `execute` answers, and the offer line that starts at it. `fields` takes\n * each spec's `holds` and `output`, and the hook `execute`'s `delivery` and\n * `augmentUrl`. `catalog` takes Tenjin's reviewed list of third-party services as\n * `discovered` offers under their catalog ids, with each spec's `holds` and\n * `output`, and `choices`, a set of options the user picks between or runs\n * all of, beside a discovered offer from a compare group. A build that sends\n * `discovered` in its place gets the same services under their\n * `discovered:tenjin:` ids. `spec` asks for each offered service's request\n * spec beside its line, and for the picked service's spec in place of a\n * decision on a query with no id, which only a build that parses them can\n * take: the decision schemas are strict. `jobs` asks for each spec's `job`,\n * for the services that never answer inline, and for `count` on a media\n * offer's line. `bazaar` widens discovery to the open Bazaar and is sent only\n * while `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = ['catalog', 'spec', 'label', 'fields', 'jobs'];\nexport const BAZAAR_ACCEPT = 'bazaar';\n\n/** The `accepts` this build sends, with the open Bazaar or without it. */\nexport function acceptsFor(bazaar: boolean): string[] {\n return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: { sessionId?: string; accepts?: readonly string[]; harness?: Harness } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n ...(extras.harness !== undefined ? { harness: extras.harness } : {}),\n packet,\n };\n}\n\n/** The exact body the tool call sends. `id` is the offer the query is for,\n * sent only for an offer with no spec kept; `gateHint` is evidence, never\n * authority. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n gateHint?: GateHint;\n accepts?: readonly string[];\n harness?: Harness;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n };\n}\n\n/** The free browse of the tool list: `browse` is the need, or `\"\"` for every\n * tool by kind. No gate call and no Jev on the server. */\nexport function buildBrowseBody(request: {\n browse: string;\n accepts: readonly string[];\n harness?: Harness;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n browse: request.browse,\n accepts: [...request.accepts],\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n };\n}\n\n/** A browse row's id, answered with that tool's spec under a fresh offer id. */\nexport function buildToolSpecBody(request: {\n tool: string;\n accepts: readonly string[];\n harness?: Harness;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n tool: request.tool,\n accepts: [...request.accepts],\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n return { success: schemaFor(kind).safeParse(value).success };\n}\n\nfunction schemaFor(kind: CallKind) {\n return kind === 'hook'\n ? HookResponseSchema\n : kind === 'tool'\n ? ToolResponseSchema\n : BrowseResponseSchema;\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n /**\n * The host asking. The server filters out the lookups that host's own tools\n * already do, and nothing else: never payment, limits or the fee. Absent is\n * `claude`, and every production caller sends it.\n */\n harness?: Harness;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n /** The paid path, when `tenjin mcp` takes it: the body goes to `path` and is\n * sent by `send`, which pays the routing fee with the stock x402 client.\n * Absent is the free path. */\n route?: DecisionRoute;\n}\n\n/** How a routing call reaches the paid path. `send` throws\n * {@link RouteSkipped} when it has no paid answer for the call, which then\n * takes the free path. */\nexport interface DecisionRoute {\n path: string;\n send: (url: string, options: HttpRequestOptions) => Promise<HttpResult>;\n /** What this route's calls deposited into the routing channel and the\n * router took, 0n for none: the caller says so once, where it is read. */\n deposited?: () => bigint;\n}\n\n/** The paid path gave this call no answer: the wallet locked, low or over\n * its spend limits, the channel busy, or the payment failed. */\nexport class RouteSkipped extends Error {\n /** `unreached`: the paid call could not reach the router\n * ({@link isUnreachable}), so the free path, on the same host, is not\n * tried and the call reads as that transport failure. */\n constructor(\n readonly why: string,\n readonly unreached?: FetchJsonFailure,\n ) {\n super(`routing fee not paid: ${why}`);\n }\n}\n\n/** Another session's call was in flight on the wallet's routing channel. */\nexport const CHANNEL_BUSY = 'channel_busy';\n/** The server answered no paid path. */\nexport const PAID_PATH_ABSENT = 'paid_path_absent';\n/** The paid call got no answer, a refused payment or a server error. */\nexport const PAYMENT_FAILED = 'payment_failed';\n/** The payment went out and the call's budget ran out before its answer:\n * no fault. `tenjin mcp` lets the request finish, so it is recorded. */\nexport const DEADLINE_AFTER_PAYMENT_SENT = 'deadline_after_payment_sent';\n\nexport type DecisionOutcome<T> =\n /** `freePath`: the paid path skipped the call for this reason and it went\n * to the free path instead, unpaid. */\n | { status: 'decided'; decision: T; freePath?: string }\n /** On the free path nothing was paid and nothing could be, so a failure here\n * costs the turn a routing answer and nothing else. */\n | {\n status: 'failed';\n reason: string;\n errorCode?: string;\n freePath?: string;\n /** The router could not be reached at all ({@link isUnreachable}). */\n unreachable?: true;\n /** No answer came back at all: a transport failure or a timeout. */\n noAnswer?: true;\n }\n /** The paid path gave no answer ({@link RouteSkipped}) and no time was left\n * for the free path: the native tool runs. */\n | { status: 'skipped'; why: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id and answers with\n * each offered service's spec. The tool sends `{ query }`, which the backend\n * answers with the spec of the service its gate picks, or `{ query, id }` for\n * the free docs offer, which has no spec and is bound from the query. Every\n * provider call is built here, from a spec, or for the docs lookup by the\n * backend from the query.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(deps.route?.path ?? ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n const started = Date.now();\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n let response: HttpResult;\n try {\n response = await (deps.route?.send ?? httpRequest)(url, options);\n } catch (err) {\n if (!(err instanceof RouteSkipped)) throw err;\n if (err.unreached !== undefined) return readDecision(err.unreached, schema);\n const left = options.timeoutMs - (Date.now() - started);\n if (left <= 0) return { status: 'skipped', why: err.why };\n // A CALL THE PAID PATH COULD NOT TAKE STILL ROUTES, on the free path,\n // unpaid, inside what is left of its budget, and says why.\n response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n ...options,\n timeoutMs: left,\n });\n const free = readDecision(response, schema);\n // A failure here ran on what a paid attempt left of the budget, so it says\n // nothing about the router being down: it never starts the backoff.\n if (free.status === 'failed') {\n return {\n status: 'failed',\n reason: free.reason,\n ...(free.errorCode !== undefined ? { errorCode: free.errorCode } : {}),\n // Still no answer, which must not end another call's backoff.\n ...(free.noAnswer === true ? { noAnswer: true as const } : {}),\n freePath: err.why,\n };\n }\n return free.status === 'skipped' ? free : { ...free, freePath: err.why };\n }\n return readDecision(response, schema);\n}\n\n/**\n * THE TWO FREE READS OF THE TOOL LIST. `{browse}` lists the tools that fit a\n * need (or all of them, by kind, for `\"\"`), and `{tool}` answers a browse\n * row's id with that tool's spec under a fresh offer id, exactly as a query\n * with no id is answered. Neither makes a gate call on the server, neither is\n * charged the routing fee, and neither pays anything here, so both always take\n * the free path: `deps.route` is never read.\n */\nexport async function requestBrowse(\n browse: string,\n deps: Omit<DecisionDeps, 'route'>,\n): Promise<DecisionOutcome<BrowseResponse>> {\n return readDecision(\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildBrowseBody({\n browse,\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n BrowseResponseSchema,\n );\n}\n\n/** `{tool}`: a browse row's spec, kept by the caller under the answer's id. */\nexport async function requestToolSpec(\n tool: string,\n deps: Omit<DecisionDeps, 'route'>,\n): Promise<DecisionOutcome<ToolResponse>> {\n return readDecision(\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildToolSpecBody({\n tool,\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n ToolResponseSchema,\n );\n}\n\n/** Why a call from a spec stopped before anything was signed: the input did\n * not fit, the live terms were not the spec's, the provider answered\n * something else, it could not be reached, or the wallet could not pay. */\nexport type UnpaidReason = 'input' | 'terms' | 'provider' | 'unreachable' | 'wallet';\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n /** `unpaid`: stopped before anything was signed, which the server never\n * counts as the offer taken. `running`: paid, and the seller was still\n * rendering when the call ended. */\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval' | 'unpaid' | 'running';\n /** On `unpaid` only, where the server requires it. */\n reason?: UnpaidReason;\n httpStatus?: number;\n ms?: number;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken,\n * or that a call for it stopped before payment and why. Never throws and never\n * waits on anything the caller needs: a lost report costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl' | 'harness'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome, deps.harness ?? 'claude'),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/** The exact body of an outcome report, pinned to the shared fixtures. */\nexport function buildOutcomeBody(outcome: SpecOutcome, harness?: Harness): Record<string, unknown> {\n return {\n schemaVersion: 1,\n id: outcome.id,\n ...(harness !== undefined ? { harness } : {}),\n status: outcome.status,\n ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),\n ...(outcome.httpStatus !== undefined ? { httpStatus: outcome.httpStatus } : {}),\n ...(outcome.ms !== undefined ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}),\n };\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) {\n return {\n status: 'failed',\n reason: fetchFailureToCliError(response).message,\n ...(isUnreachable(response) ? { unreachable: true as const } : {}),\n ...(response.status === undefined ? { noAnswer: true as const } : {}),\n };\n }\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n\n/** A dropped socket, which a fresh connection usually gets past. */\nconst RESET_CODES = new Set(['ECONNRESET', 'UND_ERR_SOCKET']);\n\n/**\n * A ROUTER THAT CANNOT BE REACHED: the transport named the layer that refused\n * the connection (DNS, TLS, a refused connection, a proxy refusing the tunnel)\n * and no status came back. Never the call's own timeout: that is the gate's\n * few seconds, and a slow decision or a cold start must not take the router\n * away from every session. Never a status, even with a body that failed to\n * read, and never a reset socket, which the free path retries on a fresh one.\n */\nexport function isUnreachable(failure: FetchJsonFailure): boolean {\n return (\n failure.kind === 'network' &&\n failure.status === undefined &&\n failure.transport !== undefined &&\n !RESET_CODES.has(failure.transport.code ?? '')\n );\n}\n"],"mappings":";;;;;;;;;;AA4BO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAAM,IAAI,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