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

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 (246) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +149 -264
  3. package/dist/{_esm-FEASBWRP.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/alive-3J3CHOQP.js +21 -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-2SNUOHAT.js +75 -0
  8. package/dist/chunk-2SNUOHAT.js.map +1 -0
  9. package/dist/chunk-3O2BQIF6.js +2227 -0
  10. package/dist/chunk-3O2BQIF6.js.map +1 -0
  11. package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
  12. package/dist/chunk-5LJCEMFD.js +12700 -0
  13. package/dist/chunk-5LJCEMFD.js.map +1 -0
  14. package/dist/chunk-6W5GYG3W.js +128 -0
  15. package/dist/chunk-6W5GYG3W.js.map +1 -0
  16. package/dist/chunk-7EKYXMUO.js +7536 -0
  17. package/dist/chunk-7EKYXMUO.js.map +1 -0
  18. package/dist/chunk-7QKHZQKW.js +1680 -0
  19. package/dist/chunk-7QKHZQKW.js.map +1 -0
  20. package/dist/chunk-A36LQPHV.js +29 -0
  21. package/dist/chunk-A36LQPHV.js.map +1 -0
  22. package/dist/chunk-AEG2PXBP.js +192 -0
  23. package/dist/chunk-AEG2PXBP.js.map +1 -0
  24. package/dist/chunk-AKWGE6JQ.js +49 -0
  25. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  26. package/dist/chunk-AWFUPKTM.js +238 -0
  27. package/dist/chunk-AWFUPKTM.js.map +1 -0
  28. package/dist/{chunk-UGX7YPX2.js → chunk-AWQPGIR6.js} +7 -9
  29. package/dist/{chunk-UGX7YPX2.js.map → chunk-AWQPGIR6.js.map} +1 -1
  30. package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
  31. package/dist/chunk-EBVIKMCH.js +108 -0
  32. package/dist/chunk-EBVIKMCH.js.map +1 -0
  33. package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
  34. package/dist/{chunk-S3IGX57D.js → chunk-EL56RW2J.js} +166 -7237
  35. package/dist/chunk-EL56RW2J.js.map +1 -0
  36. package/dist/chunk-HE2MS4QO.js +256 -0
  37. package/dist/chunk-HE2MS4QO.js.map +1 -0
  38. package/dist/{chunk-CYOF7ROH.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-IOODYAXL.js +324 -0
  40. package/dist/chunk-IOODYAXL.js.map +1 -0
  41. package/dist/chunk-JMM6YE7J.js +2174 -0
  42. package/dist/chunk-JMM6YE7J.js.map +1 -0
  43. package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
  44. package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
  45. package/dist/chunk-KHE6L6TD.js +416 -0
  46. package/dist/chunk-KHE6L6TD.js.map +1 -0
  47. package/dist/chunk-KOGZDMHO.js +21 -0
  48. package/dist/chunk-KOGZDMHO.js.map +1 -0
  49. package/dist/chunk-KYFZTGMC.js +237 -0
  50. package/dist/chunk-KYFZTGMC.js.map +1 -0
  51. package/dist/chunk-LFZJM56J.js +159 -0
  52. package/dist/chunk-LFZJM56J.js.map +1 -0
  53. package/dist/chunk-LHHMV4GU.js +27 -0
  54. package/dist/chunk-LHHMV4GU.js.map +1 -0
  55. package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
  56. package/dist/chunk-MEFB5KHA.js.map +1 -0
  57. package/dist/{chunk-NCE5NSN6.js → chunk-N35E6CM2.js} +140 -10
  58. package/dist/chunk-N35E6CM2.js.map +1 -0
  59. package/dist/chunk-NZIP4PA2.js +114 -0
  60. package/dist/chunk-NZIP4PA2.js.map +1 -0
  61. package/dist/chunk-O2FRQ2L2.js +168 -0
  62. package/dist/chunk-O2FRQ2L2.js.map +1 -0
  63. package/dist/chunk-OK2TDZQU.js +404 -0
  64. package/dist/chunk-OK2TDZQU.js.map +1 -0
  65. package/dist/chunk-ORWL5BSN.js +269 -0
  66. package/dist/chunk-ORWL5BSN.js.map +1 -0
  67. package/dist/{chunk-Z6MFJV5Z.js → chunk-OSYTBCUC.js} +850 -499
  68. package/dist/chunk-OSYTBCUC.js.map +1 -0
  69. package/dist/chunk-P7LABKCW.js +90 -0
  70. package/dist/chunk-P7LABKCW.js.map +1 -0
  71. package/dist/chunk-PAYV4XUA.js +151 -0
  72. package/dist/chunk-PAYV4XUA.js.map +1 -0
  73. package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
  74. package/dist/chunk-QUVVWYJW.js +112 -0
  75. package/dist/chunk-QUVVWYJW.js.map +1 -0
  76. package/dist/chunk-RAULEAZ6.js +228 -0
  77. package/dist/chunk-RAULEAZ6.js.map +1 -0
  78. package/dist/chunk-S4SAZ7OD.js +30 -0
  79. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  80. package/dist/chunk-SJLTEINJ.js +117 -0
  81. package/dist/chunk-SJLTEINJ.js.map +1 -0
  82. package/dist/chunk-SPAVAYSW.js +125 -0
  83. package/dist/chunk-SPAVAYSW.js.map +1 -0
  84. package/dist/chunk-TTBKWWTV.js +1605 -0
  85. package/dist/chunk-TTBKWWTV.js.map +1 -0
  86. package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
  87. package/dist/chunk-U6YQ6FRI.js +378 -0
  88. package/dist/chunk-U6YQ6FRI.js.map +1 -0
  89. package/dist/chunk-VFMQTSXG.js +29 -0
  90. package/dist/chunk-VFMQTSXG.js.map +1 -0
  91. package/dist/chunk-VUFAK2LW.js +115 -0
  92. package/dist/chunk-VUFAK2LW.js.map +1 -0
  93. package/dist/chunk-VZGAONSJ.js +194 -0
  94. package/dist/chunk-VZGAONSJ.js.map +1 -0
  95. package/dist/{chunk-OYMYCW7J.js → chunk-WO5BJNIB.js} +682 -53
  96. package/dist/chunk-WO5BJNIB.js.map +1 -0
  97. package/dist/chunk-WVUSXNIE.js +39 -0
  98. package/dist/chunk-WVUSXNIE.js.map +1 -0
  99. package/dist/chunk-XKESD27X.js +10 -0
  100. package/dist/chunk-XKESD27X.js.map +1 -0
  101. package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
  102. package/dist/{chunk-XJIW7USF.js → chunk-YFQOA5AU.js} +118 -9
  103. package/dist/chunk-YFQOA5AU.js.map +1 -0
  104. package/dist/chunk-YHKXNYTB.js +105 -0
  105. package/dist/chunk-YHKXNYTB.js.map +1 -0
  106. package/dist/{cli-SBXI5AMS.js → cli-O5SN7ZJ4.js} +382 -214
  107. package/dist/cli-O5SN7ZJ4.js.map +1 -0
  108. package/dist/config-OJQI27LT.js +45 -0
  109. package/dist/dist-3LOO6M4U.js +2842 -0
  110. package/dist/dist-3LOO6M4U.js.map +1 -0
  111. package/dist/doctor-IQQJHGGM.js +590 -0
  112. package/dist/doctor-IQQJHGGM.js.map +1 -0
  113. package/dist/env-proxy-XL4P73MZ.js +15 -0
  114. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  115. package/dist/fund-WEV6DMTD.js +365 -0
  116. package/dist/fund-WEV6DMTD.js.map +1 -0
  117. package/dist/hook-command-D2P3ILRV.js +32 -0
  118. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  119. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  120. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  121. package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
  122. package/dist/index.js +21 -2
  123. package/dist/index.js.map +1 -1
  124. package/dist/install-TUCRF32I.js +60 -0
  125. package/dist/install-identity-WHPNMNMQ.js +26 -0
  126. package/dist/install-wallet-MA27FTQ5.js +113 -0
  127. package/dist/install-wallet-MA27FTQ5.js.map +1 -0
  128. package/dist/mcp-QML7ZMPH.js +13427 -0
  129. package/dist/mcp-QML7ZMPH.js.map +1 -0
  130. package/dist/package-LGKYOEPV.js +37 -0
  131. package/dist/package-LGKYOEPV.js.map +1 -0
  132. package/dist/paths-POPTXJO6.js +61 -0
  133. package/dist/paths-POPTXJO6.js.map +1 -0
  134. package/dist/pay-2C2UBBXJ.js +51 -0
  135. package/dist/pay-2C2UBBXJ.js.map +1 -0
  136. package/dist/payments-C44QUFXU.js +106 -0
  137. package/dist/payments-C44QUFXU.js.map +1 -0
  138. package/dist/redact-6W23GGJC.js +15 -0
  139. package/dist/redact-6W23GGJC.js.map +1 -0
  140. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
  141. package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
  142. package/dist/send-KVJX4XIR.js +222 -0
  143. package/dist/send-KVJX4XIR.js.map +1 -0
  144. package/dist/status-S7C3WMSH.js +115 -0
  145. package/dist/status-S7C3WMSH.js.map +1 -0
  146. package/dist/status-line-YR2T5HC4.js +86 -0
  147. package/dist/status-line-YR2T5HC4.js.map +1 -0
  148. package/dist/uninstall-HY6LKIIT.js +149 -0
  149. package/dist/uninstall-HY6LKIIT.js.map +1 -0
  150. package/dist/update-OJV22LR3.js +36 -0
  151. package/dist/update-OJV22LR3.js.map +1 -0
  152. package/dist/usdc-JK4RRFFQ.js +39 -0
  153. package/dist/usdc-JK4RRFFQ.js.map +1 -0
  154. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  155. package/dist/viemAdapter-By13KInL-X2VY6CY3.js.map +1 -0
  156. package/dist/wallet-PD2IMZDU.js +39 -0
  157. package/dist/wallet-PD2IMZDU.js.map +1 -0
  158. package/dist/wallet-kdf-worker.mjs +980 -0
  159. package/docs/agent-permissions.md +180 -0
  160. package/docs/safety-model.md +59 -0
  161. package/docs/troubleshooting.md +13 -0
  162. package/package.json +28 -19
  163. package/LICENSE +0 -21
  164. package/dist/buy-EE6SEXP6.js +0 -1598
  165. package/dist/buy-EE6SEXP6.js.map +0 -1
  166. package/dist/candidate-ERMSYYQZ.js +0 -127
  167. package/dist/candidate-ERMSYYQZ.js.map +0 -1
  168. package/dist/chunk-3OV7E5G5.js +0 -18
  169. package/dist/chunk-3OV7E5G5.js.map +0 -1
  170. package/dist/chunk-4ONXEEQL.js +0 -152
  171. package/dist/chunk-4ONXEEQL.js.map +0 -1
  172. package/dist/chunk-662MSGZB.js +0 -286
  173. package/dist/chunk-662MSGZB.js.map +0 -1
  174. package/dist/chunk-7KUW4MJD.js +0 -59
  175. package/dist/chunk-7KUW4MJD.js.map +0 -1
  176. package/dist/chunk-AWPAWHNX.js +0 -333
  177. package/dist/chunk-AWPAWHNX.js.map +0 -1
  178. package/dist/chunk-DXTQ3CSI.js +0 -171
  179. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  180. package/dist/chunk-ESPNTPQ2.js +0 -207
  181. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  182. package/dist/chunk-FJPLRISB.js +0 -79
  183. package/dist/chunk-FJPLRISB.js.map +0 -1
  184. package/dist/chunk-GO75V3NZ.js +0 -160
  185. package/dist/chunk-GO75V3NZ.js.map +0 -1
  186. package/dist/chunk-JPHG2JW3.js +0 -96
  187. package/dist/chunk-JPHG2JW3.js.map +0 -1
  188. package/dist/chunk-MUBUQVC3.js +0 -67
  189. package/dist/chunk-MUBUQVC3.js.map +0 -1
  190. package/dist/chunk-NCE5NSN6.js.map +0 -1
  191. package/dist/chunk-OYMYCW7J.js.map +0 -1
  192. package/dist/chunk-RY4XKNV3.js +0 -140
  193. package/dist/chunk-RY4XKNV3.js.map +0 -1
  194. package/dist/chunk-S3IGX57D.js.map +0 -1
  195. package/dist/chunk-TLCMMYLY.js +0 -126
  196. package/dist/chunk-TLCMMYLY.js.map +0 -1
  197. package/dist/chunk-UO22YNY4.js +0 -69
  198. package/dist/chunk-UO22YNY4.js.map +0 -1
  199. package/dist/chunk-XHC6FCGZ.js +0 -261
  200. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  201. package/dist/chunk-XJIW7USF.js.map +0 -1
  202. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  203. package/dist/chunk-YN5SHIXQ.js +0 -126
  204. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  205. package/dist/chunk-Z52RA3NC.js +0 -137
  206. package/dist/chunk-Z52RA3NC.js.map +0 -1
  207. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  208. package/dist/cli-SBXI5AMS.js.map +0 -1
  209. package/dist/config-VELDKLHY.js +0 -21
  210. package/dist/doctor-T3KWNNP2.js +0 -20
  211. package/dist/inspect-LMKOXE4Y.js +0 -96
  212. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  213. package/dist/install-LEX3ENQ6.js +0 -387
  214. package/dist/install-LEX3ENQ6.js.map +0 -1
  215. package/dist/lookup-ZPN2Q67N.js +0 -129
  216. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  217. package/dist/outcome-N7TAK6WR.js +0 -66
  218. package/dist/outcome-N7TAK6WR.js.map +0 -1
  219. package/dist/publish-BKBQQAW4.js +0 -1478
  220. package/dist/publish-BKBQQAW4.js.map +0 -1
  221. package/dist/usdc-JIAJW4SV.js +0 -22
  222. package/dist/wallet-CWEMYVIH.js +0 -179
  223. package/dist/wallet-CWEMYVIH.js.map +0 -1
  224. package/dist/wallet-PA54CRBL.js +0 -30
  225. package/skills/tenjin/SKILL.md +0 -199
  226. package/skills/tenjin-publish/SKILL.md +0 -111
  227. package/skills/tenjin-search/SKILL.md +0 -133
  228. /package/dist/{_esm-FEASBWRP.js.map → _esm-CE7KNONL.js.map} +0 -0
  229. /package/dist/{ccip-NQXCEK2U.js.map → alive-3J3CHOQP.js.map} +0 -0
  230. /package/dist/{ccip-XR5NE5QK.js.map → ccip-7RMRLAGV.js.map} +0 -0
  231. /package/dist/{config-VELDKLHY.js.map → ccip-NLCSCHKI.js.map} +0 -0
  232. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
  233. /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
  234. /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
  235. /package/dist/{chunk-CYOF7ROH.js.map → chunk-HPWO4O6S.js.map} +0 -0
  236. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  237. /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
  238. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
  239. /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
  240. /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
  241. /package/dist/{doctor-T3KWNNP2.js.map → config-OJQI27LT.js.map} +0 -0
  242. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
  243. /package/dist/{secp256k1-N3ZHU7LB.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  244. /package/dist/{usdc-JIAJW4SV.js.map → hook-command-D2P3ILRV.js.map} +0 -0
  245. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → install-TUCRF32I.js.map} +0 -0
  246. /package/dist/{wallet-PA54CRBL.js.map → install-identity-WHPNMNMQ.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/clack.ts"],"sourcesContent":["import type { Readable, Writable } from 'node:stream';\n\n/**\n * The pretty-prompt renderer behind the install walkthrough's seams.\n *\n * @clack/prompts is a devDependency BUNDLED by tsup (published `dependencies`\n * stays `{}`), and every entry point here is behind a dynamic `import()` so it\n * lands in its own split chunk: a `search` or `doctor` run never parses it.\n *\n * Nothing in this module is reachable from a machine run. Commands call it only\n * on the real interactive path (a TTY on both stdout and stdin, no `--json`),\n * and always through an injectable seam, so unit tests supply answers directly\n * and never touch clack or a terminal.\n *\n * Prompts render on STDERR, like every other prompt in this CLI: stdout carries\n * the human walkthrough (or a single JSON envelope) and must not be interleaved\n * with prompt chrome.\n */\n\n/** Cancel (ctrl-C, escape) is not an answer. Callers map `null` to their own default. */\nexport type Cancelled = null;\n\nexport interface SelectChoice<T extends string> {\n value: T;\n label: string;\n /** The one line of consequence shown beside the label. */\n hint?: string;\n}\n\n/** Streams a prompt reads and draws on. Injected by tests; defaults to the real ones. */\ninterface PromptStreams {\n input?: Readable;\n output?: Writable;\n}\n\n/** DECTCUM show-cursor. Written on the EOF path in case the prompt did not get to. */\nconst SHOW_CURSOR = '\\x1b[?25h';\n\n/**\n * Settle a prompt when its input goes away instead of hanging forever.\n *\n * Ctrl-D at a clack prompt leaves its promise unsettled: no resolve, no reject,\n * no cancel symbol. The process then dies on an unsettled top-level await with\n * exit 13, nothing printed, and the cursor still hidden. The readline seam this\n * replaced handled it on purpose (\"ctrl-D mid-prompt reads as the default\"), and\n * that behavior has to survive the renderer swap.\n *\n * \"Input goes away\" is two different events, and only covering one of them was\n * the original bug:\n *\n * - The STREAM ends. A pipe closes, a harness detaches, stdin was already at\n * EOF. Caught via `end` / `close`.\n * - The ctrl-D BYTE (0x04) arrives with the stream still open. This is what a\n * real terminal sends, and it is the common case. A prompt puts stdin in raw\n * mode, where 0x04 is ordinary data rather than EOF, so no stream event ever\n * fires; clack has no binding for it and simply keeps waiting. Caught via the\n * `keypress` decoder readline installs, which is a read-only view of the same\n * bytes: listening there takes nothing away from the prompt, where a `data`\n * listener would risk flipping the stream to flowing before clack reads it.\n *\n * Two mechanisms settle it, because one of them is advisory. The AbortSignal is\n * clack's own teardown: it flips the prompt to `cancel`, which restores the\n * cursor and raw mode and resolves with the cancel symbol. The race is the\n * guarantee, for a prompt that is not yet listening or never settles anyway; on\n * that path we restore the cursor ourselves, since no prompt did.\n */\nfunction withInputEnd<T>(\n streams: Required<PromptStreams>,\n onEnd: T,\n run: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const controller = new AbortController();\n let settleEnd: (() => void) | undefined;\n const ended = new Promise<T>((resolve) => {\n settleEnd = () => {\n streams.output.write(SHOW_CURSOR);\n resolve(onEnd);\n };\n });\n\n const end = (): void => {\n controller.abort();\n settleEnd?.();\n };\n const onKeypress = (_text: string | undefined, key?: { name?: string; ctrl?: boolean }): void => {\n if (key?.ctrl === true && key.name === 'd') end();\n };\n\n streams.input.on('keypress', onKeypress);\n // A stream that finished before we got here never emits `end` again, so ask.\n if (streams.input.readableEnded) {\n queueMicrotask(end);\n } else {\n streams.input.once('end', end);\n streams.input.once('close', end);\n }\n\n return Promise.race([run(controller.signal), ended]).finally(() => {\n streams.input.off('keypress', onKeypress);\n streams.input.off('end', end);\n streams.input.off('close', end);\n });\n}\n\nfunction resolveStreams(streams: PromptStreams): Required<PromptStreams> {\n return { input: streams.input ?? process.stdin, output: streams.output ?? process.stderr };\n}\n\n/**\n * A single-choice list. Returns the chosen value, or `null` when the operator\n * cancelled or the input ended, both of which callers treat as \"leave everything\n * as it was\".\n */\nexport async function selectOne<T extends string>(opts: {\n message: string;\n choices: readonly SelectChoice<T>[];\n initialValue: T;\n streams?: PromptStreams;\n}): Promise<T | Cancelled> {\n const { select, isCancel } = await import('@clack/prompts');\n const streams = resolveStreams(opts.streams ?? {});\n return withInputEnd<T | Cancelled>(streams, null, async (signal) => {\n // Instantiated at `string`, not at `T`: clack's `Option<Value>` is a conditional\n // type that a generic `T extends string` cannot resolve. The values come from\n // this call's own choices, so narrowing the answer back is sound.\n const answer = await select<string>({\n message: opts.message,\n options: opts.choices.map((c) => ({\n value: c.value as string,\n label: c.label,\n ...(c.hint !== undefined ? { hint: c.hint } : {}),\n })),\n initialValue: opts.initialValue,\n input: streams.input,\n output: streams.output,\n signal,\n });\n return isCancel(answer) ? null : (answer as T);\n });\n}\n\n/** A multi-choice list. Returns the selected values, or `null` when cancelled. */\nexport async function selectMany<T extends string>(opts: {\n message: string;\n choices: readonly SelectChoice<T>[];\n initialValues: readonly T[];\n required?: boolean;\n streams?: PromptStreams;\n}): Promise<T[] | Cancelled> {\n const { multiselect, isCancel } = await import('@clack/prompts');\n const streams = resolveStreams(opts.streams ?? {});\n return withInputEnd<T[] | Cancelled>(streams, null, async (signal) => {\n const answer = await multiselect<string>({\n message: opts.message,\n options: opts.choices.map((c) => ({\n value: c.value as string,\n label: c.label,\n ...(c.hint !== undefined ? { hint: c.hint } : {}),\n })),\n initialValues: [...opts.initialValues] as string[],\n required: opts.required ?? true,\n input: streams.input,\n output: streams.output,\n signal,\n });\n return isCancel(answer) ? null : (answer as T[]);\n });\n}\n\n/** A one-line answer. Returns what was typed, or `null` when cancelled or the input ended. */\nexport async function askText(opts: {\n message: string;\n placeholder?: string;\n streams?: PromptStreams;\n}): Promise<string | Cancelled> {\n const { text, isCancel } = await import('@clack/prompts');\n const streams = resolveStreams(opts.streams ?? {});\n return withInputEnd<string | Cancelled>(streams, null, async (signal) => {\n const answer = await text({\n message: opts.message,\n ...(opts.placeholder !== undefined ? { placeholder: opts.placeholder } : {}),\n input: streams.input,\n output: streams.output,\n signal,\n });\n return isCancel(answer) ? null : answer;\n });\n}\n\n/** A yes/no confirm. Cancelling, or an input that ends, reads as no. */\nexport async function confirmChoice(\n message: string,\n initialValue = true,\n streams: PromptStreams = {},\n): Promise<boolean> {\n const { confirm, isCancel } = await import('@clack/prompts');\n const resolved = resolveStreams(streams);\n return withInputEnd<boolean>(resolved, false, async (signal) => {\n const answer = await confirm({\n message,\n initialValue,\n input: resolved.input,\n output: resolved.output,\n signal,\n });\n return isCancel(answer) ? false : answer;\n });\n}\n\n/** Open the walkthrough's prompt sequence with a title bar. */\nexport async function intro(message: string): Promise<void> {\n const clack = await import('@clack/prompts');\n clack.intro(message, { output: process.stderr });\n}\n\n/** Close it, so the last prompt is not left dangling above plain stdout lines. */\nexport async function outro(message: string): Promise<void> {\n const clack = await import('@clack/prompts');\n clack.outro(message, { output: process.stderr });\n}\n"],"mappings":";;;AAoCA,IAAM,cAAc;AA8BpB,SAAS,aACP,SACA,OACA,KACY;AACZ,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI;AACJ,QAAM,QAAQ,IAAI,QAAW,CAAC,YAAY;AACxC,gBAAY,MAAM;AAChB,cAAQ,OAAO,MAAM,WAAW;AAChC,cAAQ,KAAK;AAAA,IACf;AAAA,EACF,CAAC;AAED,QAAM,MAAM,MAAY;AACtB,eAAW,MAAM;AACjB,gBAAY;AAAA,EACd;AACA,QAAM,aAAa,CAAC,OAA2B,QAAkD;AAC/F,QAAI,KAAK,SAAS,QAAQ,IAAI,SAAS,IAAK,KAAI;AAAA,EAClD;AAEA,UAAQ,MAAM,GAAG,YAAY,UAAU;AAEvC,MAAI,QAAQ,MAAM,eAAe;AAC/B,mBAAe,GAAG;AAAA,EACpB,OAAO;AACL,YAAQ,MAAM,KAAK,OAAO,GAAG;AAC7B,YAAQ,MAAM,KAAK,SAAS,GAAG;AAAA,EACjC;AAEA,SAAO,QAAQ,KAAK,CAAC,IAAI,WAAW,MAAM,GAAG,KAAK,CAAC,EAAE,QAAQ,MAAM;AACjE,YAAQ,MAAM,IAAI,YAAY,UAAU;AACxC,YAAQ,MAAM,IAAI,OAAO,GAAG;AAC5B,YAAQ,MAAM,IAAI,SAAS,GAAG;AAAA,EAChC,CAAC;AACH;AAEA,SAAS,eAAe,SAAiD;AACvE,SAAO,EAAE,OAAO,QAAQ,SAAS,QAAQ,OAAO,QAAQ,QAAQ,UAAU,QAAQ,OAAO;AAC3F;AAOA,eAAsB,UAA4B,MAKvB;AACzB,QAAM,EAAE,QAAQ,SAAS,IAAI,MAAM,OAAO,oBAAgB;AAC1D,QAAM,UAAU,eAAe,KAAK,WAAW,CAAC,CAAC;AACjD,SAAO,aAA4B,SAAS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C;AACH;","names":[]}
@@ -0,0 +1,151 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ evaluateSpendPolicy
4
+ } from "./chunk-2SNUOHAT.js";
5
+ import {
6
+ hasCode
7
+ } from "./chunk-2I4QTOLB.js";
8
+ import {
9
+ formatUsdDisplay
10
+ } from "./chunk-WO5BJNIB.js";
11
+
12
+ // src/router/fee.ts
13
+ import { createHash } from "node:crypto";
14
+ import { mkdir, open, readFile, readdir, rm } from "node:fs/promises";
15
+ import { join } from "node:path";
16
+ var ROUTE_PAID_PATH = "/api/x402-router/route";
17
+ var ROUTING_FEE_ATOMIC = 3000n;
18
+ var CHANNEL_DEPOSIT_ATOMIC = 250000n;
19
+ var SUGGESTED_FUND_USD = "5";
20
+ var ROUTING_DEPOSIT_KEY = "routing-deposit:";
21
+ var REFUSED = {
22
+ not_allowlisted: "not_allowlisted",
23
+ session_budget_exceeded: "budget_reached",
24
+ above_auto_spend: "limit_below_deposit"
25
+ };
26
+ function refusedWhy(reason) {
27
+ return REFUSED[reason] ?? reason;
28
+ }
29
+ function feeRefusal(policy, host) {
30
+ const evaluation = evaluateSpendPolicy(
31
+ { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },
32
+ { mode: "automatic", amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n }
33
+ );
34
+ return evaluation.decision === "allow" ? null : refusedWhy(evaluation.reason);
35
+ }
36
+ var FEE_REQUIRED = "fee_required";
37
+ function isFeeRequired(response) {
38
+ const decision = response?.decision;
39
+ const diagnostics = decision?.diagnostics;
40
+ return decision?.action === "native" && diagnostics?.reasonCode === FEE_REQUIRED;
41
+ }
42
+ var UNPAID = {
43
+ wallet_low: {
44
+ reason: `the wallet holds less than the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,
45
+ fix: `Fund it with \`tenjin wallet fund ${SUGGESTED_FUND_USD}\`.`
46
+ },
47
+ wallet_locked: {
48
+ reason: "`tenjin mcp` cannot unlock the wallet without a prompt",
49
+ fix: "Set TENJIN_WALLET_PASSPHRASE in the environment Claude Code starts from, then restart Claude Code."
50
+ },
51
+ no_wallet: {
52
+ reason: "this machine has no wallet",
53
+ fix: "Run `tenjin doctor`."
54
+ },
55
+ limit_below_deposit: {
56
+ reason: `the per-call spend limit is below the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,
57
+ fix: "Run `tenjin doctor`."
58
+ },
59
+ budget_reached: {
60
+ reason: "the daily spend limit has no room left for the routing fee or its deposit",
61
+ fix: "Run `tenjin doctor`."
62
+ },
63
+ not_allowlisted: {
64
+ reason: "allowlistCreators does not include the router",
65
+ fix: "Run `tenjin doctor`."
66
+ },
67
+ payment_failed: {
68
+ reason: "the routing payment failed",
69
+ fix: "Run `tenjin doctor`."
70
+ },
71
+ [FEE_REQUIRED]: {
72
+ reason: "the router now charges it, and this session cannot pay it",
73
+ fix: "Run `tenjin doctor`."
74
+ }
75
+ };
76
+ var NO_FAULT = /* @__PURE__ */ new Set([
77
+ "channel_busy",
78
+ "paid_path_absent",
79
+ "busy",
80
+ "no_call",
81
+ "deadline_after_payment_sent"
82
+ ]);
83
+ function unpaid(why) {
84
+ if (NO_FAULT.has(why)) return null;
85
+ return UNPAID[why] ?? UNPAID["payment_failed"];
86
+ }
87
+ function depositSentence(amountAtomic) {
88
+ return `Tenjin moved $${usd(amountAtomic)} into prepaid routing credit; each routing call uses $${usd(ROUTING_FEE_ATOMIC)}.`;
89
+ }
90
+ function unpaidSentence(why) {
91
+ const u = unpaid(why);
92
+ if (u === null) return null;
93
+ return `Tenjin routing could not pay its $${usd(ROUTING_FEE_ATOMIC)} fee (${u.reason}), so calls take the free path until that is fixed. ${u.fix}`;
94
+ }
95
+ var ADDRESS_RE = /^0x[0-9a-f]{40}$/;
96
+ function payerDir(dataDir, payer) {
97
+ const name = payer.toLowerCase();
98
+ if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);
99
+ return join(dataDir, "router", "fee", name);
100
+ }
101
+ function usd(atomic) {
102
+ return formatUsdDisplay(atomic.toString());
103
+ }
104
+ var NOTICE_KEEP_MS = 7 * 864e5;
105
+ async function firstNoticeFor(dataDir, sessionId, now) {
106
+ const dir = join(dataDir, "router", "notices");
107
+ const name = createHash("sha256").update(sessionId).digest("hex").slice(0, 32);
108
+ const created = await createExclusive(join(dir, name), String(now));
109
+ if (created) {
110
+ for (const entry of await readdir(dir).catch(() => [])) {
111
+ const path = join(dir, entry);
112
+ const at = Number(await readFile(path, "utf8").catch(() => "NaN"));
113
+ if (!Number.isFinite(at) || now - at > NOTICE_KEEP_MS) await rm(path, { force: true });
114
+ }
115
+ }
116
+ return created;
117
+ }
118
+ async function createExclusive(path, body) {
119
+ try {
120
+ await mkdir(join(path, ".."), { recursive: true, mode: 448 });
121
+ const handle = await open(path, "wx", 384);
122
+ try {
123
+ await handle.writeFile(body);
124
+ } finally {
125
+ await handle.close();
126
+ }
127
+ return true;
128
+ } catch (err) {
129
+ if (hasCode(err, "EEXIST")) return false;
130
+ throw err;
131
+ }
132
+ }
133
+
134
+ export {
135
+ ROUTE_PAID_PATH,
136
+ ROUTING_FEE_ATOMIC,
137
+ CHANNEL_DEPOSIT_ATOMIC,
138
+ SUGGESTED_FUND_USD,
139
+ ROUTING_DEPOSIT_KEY,
140
+ refusedWhy,
141
+ feeRefusal,
142
+ FEE_REQUIRED,
143
+ isFeeRequired,
144
+ unpaid,
145
+ depositSentence,
146
+ unpaidSentence,
147
+ payerDir,
148
+ usd,
149
+ firstNoticeFor
150
+ };
151
+ //# sourceMappingURL=chunk-PAYV4XUA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/fee.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { mkdir, open, readFile, readdir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { hasCode } from '../lib/errno';\nimport { formatUsdDisplay } from '../lib/money';\nimport { evaluateSpendPolicy, type PolicyReason, type SpendPolicy } from '../lib/policy';\nimport type { DecisionRoute } from './decision';\n\n/**\n * THE ROUTING FEE, WITHOUT ANYTHING THAT PAYS. Every routing call on the paid\n * path pays $0.003 over x402 `batch-settlement`, and the stock SDK client in\n * `tenjin mcp` does all of it (`routing-payer.ts`). Everything else, `tenjin\n * hook` included, is the free path exactly as before this fee existed.\n *\n * Hook-safe: `tenjin hook` loads this module, and its chunk graph stays free\n * of the wallet and the x402 SDK (`dist-chunks.test.ts`).\n */\n\nexport const ROUTE_PAID_PATH = '/api/x402-router/route';\n\n/** The flat fee per routing call, atomic USDC ($0.003). */\nexport const ROUTING_FEE_ATOMIC = 3_000n;\n/** The largest channel deposit, atomic USDC ($0.25), made inline by the SDK\n * on the first paid call of a channel that cannot cover the next fee. */\nexport const CHANNEL_DEPOSIT_ATOMIC = 250_000n;\n/**\n * The top-up every \"fund the wallet\" hint names, in USD: the checkout's Apple\n * Pay and Google Pay minimum, which covers the routing deposit and a few\n * hundred lookups. `tenjin wallet fund` sends it to the checkout as a preset.\n */\nexport const SUGGESTED_FUND_USD = '5';\n/** The spend ledger key a deposit's exposure is recorded under, before its id. */\nexport const ROUTING_DEPOSIT_KEY = 'routing-deposit:';\n\n/** A spend refusal, as the reason the call was not paid. */\nconst REFUSED: Partial<Record<PolicyReason, string>> = {\n not_allowlisted: 'not_allowlisted',\n session_budget_exceeded: 'budget_reached',\n above_auto_spend: 'limit_below_deposit',\n};\n\n/** The reason a spend refusal leaves a routing call unpaid. */\nexport function refusedWhy(reason: PolicyReason): string {\n return REFUSED[reason] ?? reason;\n}\n\n/**\n * THE DEPOSIT IS THE SPEND. It meets the whole policy once, the day's budget\n * included, when the SDK's `depositStrategy` reserves it. Each fee paid from\n * it then gets only the per-payment checks: the per-call limit, the creator\n * allowlist (the router's host) and an explicit zero daily limit. It is never\n * refused for the day's running total, which the deposit already consumed.\n * Null when those checks allow the fee.\n */\nexport function feeRefusal(policy: SpendPolicy, host: string): string | null {\n const evaluation = evaluateSpendPolicy(\n { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },\n { mode: 'automatic', amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n },\n );\n return evaluation.decision === 'allow' ? null : refusedWhy(evaluation.reason);\n}\n\n/** The paid path for this call, or null for the free path. `tenjin mcp` passes\n * its payer's; absent, every call is free. */\nexport type RouteFor = (baseUrl: string) => Promise<DecisionRoute | null>;\n\n/** The free path's reason code once the server routes only paid calls. */\nexport const FEE_REQUIRED = 'fee_required';\n\n/** Whether a decision is the free path's `fee_required` answer. */\nexport function isFeeRequired(response: unknown): boolean {\n const decision = (response as { decision?: { action?: unknown; diagnostics?: unknown } })\n ?.decision;\n const diagnostics = decision?.diagnostics as { reasonCode?: unknown } | undefined;\n return decision?.action === 'native' && diagnostics?.reasonCode === FEE_REQUIRED;\n}\n\n/**\n * WHY A CALL WAS NOT PAID, for the user: the reason and the fix, keyed by the\n * payer's skip reason (or `fee_required`, when the free path answered it and\n * nothing else explains why). Null for a reason that is no fault and needs no\n * fix: another session's call on the channel, a server with no paid path, or\n * a call queued past its own budget, or a payment still out when the call's\n * budget ran out (it finishes in the background).\n */\nconst UNPAID: Record<string, { reason: string; fix: string }> = {\n wallet_low: {\n reason: `the wallet holds less than the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,\n fix: `Fund it with \\`tenjin wallet fund ${SUGGESTED_FUND_USD}\\`.`,\n },\n wallet_locked: {\n reason: '`tenjin mcp` cannot unlock the wallet without a prompt',\n fix: 'Set TENJIN_WALLET_PASSPHRASE in the environment Claude Code starts from, then restart Claude Code.',\n },\n no_wallet: {\n reason: 'this machine has no wallet',\n fix: 'Run `tenjin doctor`.',\n },\n limit_below_deposit: {\n reason: `the per-call spend limit is below the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,\n fix: 'Run `tenjin doctor`.',\n },\n budget_reached: {\n reason: 'the daily spend limit has no room left for the routing fee or its deposit',\n fix: 'Run `tenjin doctor`.',\n },\n not_allowlisted: {\n reason: 'allowlistCreators does not include the router',\n fix: 'Run `tenjin doctor`.',\n },\n payment_failed: {\n reason: 'the routing payment failed',\n fix: 'Run `tenjin doctor`.',\n },\n [FEE_REQUIRED]: {\n reason: 'the router now charges it, and this session cannot pay it',\n fix: 'Run `tenjin doctor`.',\n },\n};\nconst NO_FAULT = new Set([\n 'channel_busy',\n 'paid_path_absent',\n 'busy',\n 'no_call',\n 'deadline_after_payment_sent',\n]);\n\n/** The reason and fix for an unpaid call, or null when it needs no word. */\nexport function unpaid(why: string): { reason: string; fix: string } | null {\n if (NO_FAULT.has(why)) return null;\n return UNPAID[why] ?? UNPAID['payment_failed']!;\n}\n\n/**\n * The one line said when a routing call's deposit went through: the money is\n * prepaid credit the next calls draw from, not a lookup it bought. It still\n * counts toward the daily limit ({@link feeRefusal}).\n */\nexport function depositSentence(amountAtomic: bigint): string {\n return `Tenjin moved $${usd(amountAtomic)} into prepaid routing credit; each routing call uses $${usd(ROUTING_FEE_ATOMIC)}.`;\n}\n\n/** The one line the user sees, once per session, when a call was not paid. */\nexport function unpaidSentence(why: string): string | null {\n const u = unpaid(why);\n if (u === null) return null;\n return `Tenjin routing could not pay its $${usd(ROUTING_FEE_ATOMIC)} fee (${u.reason}), so calls take the free path until that is fixed. ${u.fix}`;\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/;\n\n/** One wallet's folder: the SDK's file storage for its routing channel\n * (`client/<channelId>.json`). */\nexport function payerDir(dataDir: string, payer: string): string {\n const name = payer.toLowerCase();\n if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);\n return join(dataDir, 'router', 'fee', name);\n}\n\n/** Atomic USDC as dollars with at least two decimals, never a float. */\nexport function usd(atomic: bigint): string {\n return formatUsdDisplay(atomic.toString());\n}\n\n/** How long a session's notice marker is kept. */\nconst NOTICE_KEEP_MS = 7 * 86_400_000;\n\n/**\n * TRUE ONCE PER SESSION: the first caller for a session id creates its marker\n * and gets true; every later one gets false. Each marker holds the time it was\n * made, and those older than a week go on the way past, so the directory does\n * not grow with every session ever run.\n */\nexport async function firstNoticeFor(\n dataDir: string,\n sessionId: string,\n now: number,\n): Promise<boolean> {\n const dir = join(dataDir, 'router', 'notices');\n const name = createHash('sha256').update(sessionId).digest('hex').slice(0, 32);\n const created = await createExclusive(join(dir, name), String(now));\n if (created) {\n for (const entry of await readdir(dir).catch(() => [] as string[])) {\n const path = join(dir, entry);\n const at = Number(await readFile(path, 'utf8').catch(() => 'NaN'));\n if (!Number.isFinite(at) || now - at > NOTICE_KEEP_MS) await rm(path, { force: true });\n }\n }\n return created;\n}\n\nasync function createExclusive(path: string, body: string): Promise<boolean> {\n try {\n await mkdir(join(path, '..'), { recursive: true, mode: 0o700 });\n const handle = await open(path, 'wx', 0o600);\n try {\n await handle.writeFile(body);\n } finally {\n await handle.close();\n }\n return true;\n } catch (err) {\n if (hasCode(err, 'EEXIST')) return false;\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,MAAM,UAAU,SAAS,UAAU;AACnD,SAAS,YAAY;AAgBd,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,yBAAyB;AAM/B,IAAM,qBAAqB;AAE3B,IAAM,sBAAsB;AAGnC,IAAM,UAAiD;AAAA,EACrD,iBAAiB;AAAA,EACjB,yBAAyB;AAAA,EACzB,kBAAkB;AACpB;AAGO,SAAS,WAAW,QAA8B;AACvD,SAAO,QAAQ,MAAM,KAAK;AAC5B;AAUO,SAAS,WAAW,QAAqB,MAA6B;AAC3E,QAAM,aAAa;AAAA,IACjB,EAAE,GAAG,QAAQ,qBAAqB,OAAO,wBAAwB,KAAK,KAAK,KAAK;AAAA,IAChF,EAAE,MAAM,aAAa,cAAc,oBAAoB,SAAS,MAAM,oBAAoB,GAAG;AAAA,EAC/F;AACA,SAAO,W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AM,OAAO,MAAM;AAAA,IACrB;AACA,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,QAAQ,KAAK,QAAQ,EAAG,QAAO;AACnC,UAAM;AAAA,EACR;AACF;","names":[]}
@@ -5,7 +5,7 @@ import {
5
5
  p,
6
6
  r,
7
7
  t
8
- } from "./chunk-HSDCI7OV.js";
8
+ } from "./chunk-XZKD7DIF.js";
9
9
 
10
10
  // node_modules/.pnpm/@signinwithethereum+siwe@4.2.0_viem@2.55.2_typescript@6.0.3_zod@4.4.3_/node_modules/@signinwithethereum/siwe/dist/ethersCompat-Df4a6QIZ.js
11
11
  var a2 = "6492649264926492649264926492649264926492649264926492649264926492";
@@ -80,4 +80,4 @@ export {
80
80
  c,
81
81
  f
82
82
  };
83
- //# sourceMappingURL=chunk-ZABPQJ3M.js.map
83
+ //# sourceMappingURL=chunk-POUWHWID.js.map
@@ -0,0 +1,112 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ setTenjinIdentity
4
+ } from "./chunk-IOODYAXL.js";
5
+ import {
6
+ hasCode
7
+ } from "./chunk-2I4QTOLB.js";
8
+ import {
9
+ isTeamModeConfig
10
+ } from "./chunk-AWFUPKTM.js";
11
+ import {
12
+ knownDeploymentOrigins,
13
+ loadRawConfig,
14
+ resolveSettings
15
+ } from "./chunk-WO5BJNIB.js";
16
+ import {
17
+ writeFileAtomicExclusive
18
+ } from "./chunk-O2FRQ2L2.js";
19
+ import {
20
+ installIdPath
21
+ } from "./chunk-SJLTEINJ.js";
22
+
23
+ // src/lib/install-identity.ts
24
+ import { randomUUID } from "node:crypto";
25
+ import { readFile } from "node:fs/promises";
26
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
27
+ function parseInstallId(raw) {
28
+ const id = raw.trim();
29
+ return UUID_RE.test(id) ? id : void 0;
30
+ }
31
+ async function readOrCreateInstallId(dir) {
32
+ const path = installIdPath(dir);
33
+ try {
34
+ return parseInstallId(await readFile(path, "utf8"));
35
+ } catch (err) {
36
+ if (!hasCode(err, "ENOENT")) return void 0;
37
+ }
38
+ const id = randomUUID();
39
+ try {
40
+ await writeFileAtomicExclusive(path, `${id}
41
+ `, { mode: 384, dirMode: 448 });
42
+ return id;
43
+ } catch (err) {
44
+ if (!hasCode(err, "EEXIST")) return void 0;
45
+ }
46
+ try {
47
+ return parseInstallId(await readFile(path, "utf8"));
48
+ } catch {
49
+ return void 0;
50
+ }
51
+ }
52
+ function tryOrigin(url) {
53
+ try {
54
+ return new URL(url).origin;
55
+ } catch {
56
+ return void 0;
57
+ }
58
+ }
59
+ function tenjinOrigins(s) {
60
+ const origins = new Set(knownDeploymentOrigins());
61
+ const baseOrigin = tryOrigin(s.baseUrl);
62
+ if (baseOrigin !== void 0 && !s.teamMode) origins.add(baseOrigin);
63
+ return [...origins];
64
+ }
65
+ function identityFor(dir, origins) {
66
+ let install;
67
+ return {
68
+ origins,
69
+ installId: () => install ??= readOrCreateInstallId(dir)
70
+ };
71
+ }
72
+ var baseUrlFlag;
73
+ function noteBaseUrlFlag(flag) {
74
+ baseUrlFlag = flag;
75
+ }
76
+ function enableCliIdentity(dir, env = process.env) {
77
+ let origins;
78
+ setTenjinIdentity(
79
+ identityFor(dir, () => {
80
+ origins ??= (async () => {
81
+ const config = await loadRawConfig(dir);
82
+ const s = resolveSettings({ config, flags: { baseUrl: baseUrlFlag }, env });
83
+ return tenjinOrigins({
84
+ baseUrl: s.baseUrl.value,
85
+ teamMode: isTeamModeConfig(config)
86
+ });
87
+ })();
88
+ return origins;
89
+ })
90
+ );
91
+ }
92
+ function enableDaemonIdentity(dir, config) {
93
+ setTenjinIdentity(
94
+ identityFor(dir, async () => {
95
+ const c = config();
96
+ return tenjinOrigins({
97
+ baseUrl: c.baseUrl,
98
+ teamMode: isTeamModeConfig(c)
99
+ });
100
+ })
101
+ );
102
+ }
103
+
104
+ export {
105
+ readOrCreateInstallId,
106
+ tenjinOrigins,
107
+ identityFor,
108
+ noteBaseUrlFlag,
109
+ enableCliIdentity,
110
+ enableDaemonIdentity
111
+ };
112
+ //# sourceMappingURL=chunk-QUVVWYJW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/install-identity.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { writeFileAtomicExclusive } from './atomic-json';\nimport { loadRawConfig, resolveSettings } from './config';\nimport { hasCode } from './errno';\nimport { setTenjinIdentity, type TenjinIdentity } from './http';\nimport { installIdPath } from './paths';\nimport { knownDeploymentOrigins } from './production-origin';\nimport { isTeamModeConfig } from './settings';\n\n/**\n * The install id the transport attaches to Tenjin-bound requests (see\n * `TenjinIdentity` in lib/http), and the rule for which origins are Tenjin's.\n *\n * Nothing here may fail a request: every read that goes wrong is an absent\n * header. There is no opt-out for alpha; the id is random, anonymous, and not a\n * credential.\n */\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction parseInstallId(raw: string): string | undefined {\n const id = raw.trim();\n return UUID_RE.test(id) ? id : undefined;\n}\n\n/**\n * This data dir's install id, minted on first need. Created no-clobber, so two\n * processes racing on a first run agree on the winner's id rather than each\n * keeping its own. A file that exists but does not hold a UUID is left alone and\n * sends nothing: overwriting it would be a new id for the same install.\n */\nexport async function readOrCreateInstallId(dir: string): Promise<string | undefined> {\n const path = installIdPath(dir);\n try {\n return parseInstallId(await readFile(path, 'utf8'));\n } catch (err) {\n if (!hasCode(err, 'ENOENT')) return undefined;\n }\n const id = randomUUID();\n try {\n await writeFileAtomicExclusive(path, `${id}\\n`, { mode: 0o600, dirMode: 0o700 });\n return id;\n } catch (err) {\n if (!hasCode(err, 'EEXIST')) return undefined;\n }\n try {\n return parseInstallId(await readFile(path, 'utf8'));\n } catch {\n return undefined;\n }\n}\n\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The origins that get the header: Tenjin's own deployments and the base URL\n * this run is pointed at, overrides included (a local dev server is Tenjin too).\n * Not `publicShelfUrl`: its default is already one of Tenjin's deployments, and\n * a custom one may be a host Tenjin does not run.\n *\n * NOT a team shelf. In team mode `baseUrl` is the team's own deployment, which\n * Tenjin does not operate, so on a team machine the base URL is left out unless\n * it is one of Tenjin's own origins anyway. `isTeamModeConfig` reads the file,\n * so a `--base-url` on one run cannot switch that exclusion off.\n */\nexport function tenjinOrigins(s: { baseUrl: string; teamMode: boolean }): string[] {\n const origins = new Set(knownDeploymentOrigins());\n const baseOrigin = tryOrigin(s.baseUrl);\n if (baseOrigin !== undefined && !s.teamMode) origins.add(baseOrigin);\n return [...origins];\n}\n\n/** An identity for one data dir. The install id is read once per process. */\nexport function identityFor(\n dir: string,\n origins: () => Promise<readonly string[]>,\n): TenjinIdentity {\n let install: Promise<string | undefined> | undefined;\n return {\n origins,\n installId: () => (install ??= readOrCreateInstallId(dir)),\n };\n}\n\n/**\n * The run's `--base-url`, recorded by the CLI once it has parsed the global\n * flags. The origins are resolved on the first request, which comes after that.\n */\nlet baseUrlFlag: string | undefined;\n\nexport function noteBaseUrlFlag(flag: string | undefined): void {\n baseUrlFlag = flag;\n}\n\n/**\n * Turn the header on for this CLI process. Called from the entry only, never\n * from `main`, so in-process tests of the command tree never mint an id.\n */\nexport function enableCliIdentity(dir: string, env: NodeJS.ProcessEnv = process.env): void {\n let origins: Promise<readonly string[]> | undefined;\n setTenjinIdentity(\n identityFor(dir, () => {\n origins ??= (async () => {\n const config = await loadRawConfig(dir);\n const s = resolveSettings({ config, flags: { baseUrl: baseUrlFlag }, env });\n return tenjinOrigins({\n baseUrl: s.baseUrl.value,\n teamMode: isTeamModeConfig(config),\n });\n })();\n return origins;\n }),\n );\n}\n\n/**\n * Turn the header on for the loop daemon. No flag or env layer, like the rest\n * of the daemon's config, and re-read per request because the daemon reloads\n * config.json when it changes.\n */\nexport function enableDaemonIdentity(\n dir: string,\n config: () => { baseUrl: string; publicShelfUrl: string; shelfBypassSecret: string },\n): void {\n setTenjinIdentity(\n identityFor(dir, async () => {\n const c = config();\n return tenjinOrigins({\n baseUrl: c.baseUrl,\n teamMode: isTeamModeConfig(c),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AAkBzB,IAAM,UAAU;AAEhB,SAAS,eAAe,KAAiC;AACvD,QAAM,KAAK,IAAI,KAAK;AACpB,SAAO,QAAQ,KAAK,EAAE,IAAI,KAAK;AACjC;AAQA,eAAsB,sBAAsB,KAA0C;AACpF,QAAM,OAAO,cAAc,GAAG;AAC9B,MAAI;AACF,WAAO,eAAe,MAAM,SAAS,MAAM,MAAM,CAAC;AAAA,EACpD,SAAS,KAAK;AACZ,QAAI,CAAC,QAAQ,KAAK,QAAQ,EAAG,QAAO;AAAA,EACtC;AACA,QAAM,KAAK,WAAW;AACtB,MAAI;AACF,UAAM,yBAAyB,MAAM,GAAG,EAAE;AAAA,GAAM,EAAE,MAAM,KAAO,SAAS,IAAM,CAAC;AAC/E,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,CAAC,QAAQ,KAAK,QAAQ,EAAG,QAAO;AAAA,EACtC;AACA,MAAI;AACF,WAAO,eAAe,MAAM,SAAS,MAAM,MAAM,CAAC;AAAA,EACpD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,UAAU,KAAiC;AAClD,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAaO,SAAS,cAAc,GAAqD;AACjF,QAAM,UAAU,IAAI,IAAI,uBAAuB,CAAC;AAChD,QAAM,aAAa,UAAU,EAAE,OAAO;AACtC,MAAI,eAAe,UAAa,CAAC,EAAE,SAAU,SAAQ,IAAI,UAAU;AACnE,SAAO,CAAC,GAAG,OAAO;AACpB;AAGO,SAAS,YACd,KACA,SACgB;AAChB,MAAI;AACJ,SAAO;AAAA,IACL;AAAA,IACA,WAAW,MAAO,YAAY,sBAAsB,GAAG;AAAA,EACzD;AACF;AAMA,IAAI;AAEG,SAAS,gBAAgB,MAAgC;AAC9D,gBAAc;AAChB;AAMO,SAAS,kBAAkB,KAAa,MAAyB,QAAQ,KAAW;AACzF,MAAI;AACJ;AAAA,IACE,YAAY,KAAK,MAAM;AACrB,mBAAa,YAAY;AACvB,cAAM,SAAS,MAAM,cAAc,GAAG;AACtC,cAAM,IAAI,gBAAgB,EAAE,QAAQ,OAAO,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;AAC1E,eAAO,cAAc;AAAA,UACnB,SAAS,EAAE,QAAQ;AAAA,UACnB,UAAU,iBAAiB,MAAM;AAAA,QACnC,CAAC;AAAA,MACH,GAAG;AACH,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;AAOO,SAAS,qBACd,KACA,QACM;AACN;AAAA,IACE,YAAY,KAAK,YAAY;AAC3B,YAAM,IAAI,OAAO;AACjB,aAAO,cAAc;AAAA,QACnB,SAAS,EAAE;AAAA,QACX,UAAU,iBAAiB,CAAC;AAAA,MAC9B,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -0,0 +1,228 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ LEGACY_MCP_SERVER_NAME,
4
+ LEGACY_REQUEST_TOOL,
5
+ requestToolName
6
+ } from "./chunk-WVUSXNIE.js";
7
+ import {
8
+ writeFileAtomic
9
+ } from "./chunk-O2FRQ2L2.js";
10
+
11
+ // src/router/agent-tools.ts
12
+ import { readdir, readFile } from "node:fs/promises";
13
+ import { dirname, join, resolve } from "node:path";
14
+ var MCP_INHERITING_BUILTINS = /* @__PURE__ */ new Set([
15
+ "general-purpose",
16
+ "Explore",
17
+ "Plan"
18
+ ]);
19
+ var MAX_AGENT_FILE_BYTES = 256 * 1024;
20
+ var TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;
21
+ async function requestToolAccess(agentType, lookup, tool = requestToolName()) {
22
+ if (agentType === void 0 || !TYPE_RE.test(agentType)) return "unknown";
23
+ try {
24
+ const text = await findDefinition(agentType, lookup);
25
+ if (text !== null) return accessOf(text, tool);
26
+ return MCP_INHERITING_BUILTINS.has(agentType) ? "allowed" : "unknown";
27
+ } catch {
28
+ return "unknown";
29
+ }
30
+ }
31
+ function accessOf(definition, tool = requestToolName()) {
32
+ const frontmatter = frontmatterOf(definition);
33
+ if (frontmatter === null) return "unknown";
34
+ const disallowed = listField(frontmatter, "disallowedTools");
35
+ if (disallowed !== void 0 && disallowed.some((entry) => namesRequestTool(entry, tool) || namesLegacyTool(entry))) {
36
+ return "excluded";
37
+ }
38
+ const tools = listField(frontmatter, "tools");
39
+ if (tools === void 0) return "allowed";
40
+ return tools.some((entry) => namesRequestTool(entry, tool)) ? "allowed" : "excluded";
41
+ }
42
+ function namesRequestTool(entry, tool) {
43
+ if (entry === tool || entry === tool.replace(/__request$/, "")) return true;
44
+ return entry.endsWith("*") && tool.startsWith(entry.slice(0, -1));
45
+ }
46
+ function namesLegacyTool(entry) {
47
+ return namesRequestTool(entry, LEGACY_REQUEST_TOOL) || entry === `mcp__${LEGACY_MCP_SERVER_NAME}`;
48
+ }
49
+ async function agentsWithoutRequestTool(lookup, tool = requestToolName()) {
50
+ const found = [];
51
+ const seen = /* @__PURE__ */ new Set();
52
+ for (const directory of agentDirs(lookup)) {
53
+ for (const { name, text } of await definitionsIn(directory)) {
54
+ const type = nameOf(text) ?? name;
55
+ if (seen.has(type)) continue;
56
+ seen.add(type);
57
+ if (accessOf(text, tool) === "excluded") found.push(type);
58
+ }
59
+ }
60
+ return found.sort();
61
+ }
62
+ async function findDefinition(agentType, lookup) {
63
+ for (const directory of agentDirs(lookup)) {
64
+ const text = await definitionIn(directory, agentType);
65
+ if (text !== null) return text;
66
+ }
67
+ const colon = agentType.indexOf(":");
68
+ if (colon > 0) {
69
+ const plugin = agentType.slice(0, colon);
70
+ const agent = agentType.slice(colon + 1);
71
+ for (const root of await pluginRoots(plugin, lookup.homeDir)) {
72
+ const text = await definitionIn(join(root, "agents"), agent);
73
+ if (text !== null) return text;
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+ function agentDirs(lookup) {
79
+ const dirs = [];
80
+ if (lookup.cwd !== void 0 && lookup.cwd.length > 0) {
81
+ let current = resolve(lookup.cwd);
82
+ for (; ; ) {
83
+ dirs.push(join(current, ".claude", "agents"));
84
+ const parent = dirname(current);
85
+ if (parent === current) break;
86
+ current = parent;
87
+ }
88
+ }
89
+ const user = join(resolve(lookup.homeDir), ".claude", "agents");
90
+ return [...dirs.filter((d) => d !== user), user];
91
+ }
92
+ async function definitionIn(directory, agentType) {
93
+ const direct = await readBounded(join(directory, `${agentType}.md`));
94
+ if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;
95
+ for (const { text } of await definitionsIn(directory)) {
96
+ if (nameOf(text) === agentType) return text;
97
+ }
98
+ return null;
99
+ }
100
+ async function definitionsIn(directory) {
101
+ let names;
102
+ try {
103
+ names = (await readdir(directory)).filter((n) => n.endsWith(".md")).slice(0, 200);
104
+ } catch {
105
+ return [];
106
+ }
107
+ const out = [];
108
+ for (const file of names) {
109
+ const text = await readBounded(join(directory, file));
110
+ if (text !== null) out.push({ name: file.slice(0, -3), text });
111
+ }
112
+ return out;
113
+ }
114
+ async function pluginRoots(plugin, homeDir) {
115
+ const raw = await readBounded(join(homeDir, ".claude", "plugins", "installed_plugins.json"));
116
+ if (raw === null) return [];
117
+ const parsed = JSON.parse(raw);
118
+ const roots = [];
119
+ for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {
120
+ if (key.split("@")[0] !== plugin || !Array.isArray(entries)) continue;
121
+ for (const entry of entries) {
122
+ const path = entry.installPath;
123
+ if (typeof path === "string" && path.length > 0) roots.push(path);
124
+ }
125
+ }
126
+ return roots;
127
+ }
128
+ async function readBounded(path) {
129
+ try {
130
+ const text = await readFile(path, "utf8");
131
+ return text.length > MAX_AGENT_FILE_BYTES ? null : text;
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+ function frontmatterOf(text) {
137
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
138
+ const open = lines.findIndex((l) => l.trim().length > 0);
139
+ if (open === -1 || lines[open]?.trim() !== "---") return null;
140
+ const end = lines.findIndex((l, i) => i > open && l.trim() === "---");
141
+ return end === -1 ? null : lines.slice(open + 1, end);
142
+ }
143
+ function nameOf(text) {
144
+ const frontmatter = frontmatterOf(text);
145
+ if (frontmatter === null) return null;
146
+ const line = frontmatter.find((l) => /^name\s*:/.test(l));
147
+ const value = line === void 0 ? "" : unquote(line.slice(line.indexOf(":") + 1).trim());
148
+ return value.length > 0 ? value : null;
149
+ }
150
+ function listField(frontmatter, key) {
151
+ const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\s*:`).test(l));
152
+ if (index === -1) return void 0;
153
+ const line = frontmatter[index];
154
+ const inline = line.slice(line.indexOf(":") + 1).trim();
155
+ if (inline.length > 0) {
156
+ const body = inline.startsWith("[") && inline.endsWith("]") ? inline.slice(1, -1) : inline;
157
+ return body.split(",").map((part) => unquote(part.trim())).filter((part) => part.length > 0);
158
+ }
159
+ const items = [];
160
+ for (const next of frontmatter.slice(index + 1)) {
161
+ const item = /^\s+-\s*(.*)$/.exec(next);
162
+ if (item === null) {
163
+ if (next.trim().length === 0) continue;
164
+ break;
165
+ }
166
+ const value = unquote(item[1].trim());
167
+ if (value.length > 0) items.push(value);
168
+ }
169
+ return items;
170
+ }
171
+ function unquote(value) {
172
+ const quoted = /^(['"])(.*)\1$/.exec(value);
173
+ return quoted === null ? value : quoted[2];
174
+ }
175
+
176
+ // src/router/router-memo.ts
177
+ import { createHash } from "node:crypto";
178
+ import { readFile as readFile2, rm } from "node:fs/promises";
179
+ import { join as join2 } from "node:path";
180
+ var UNREACHABLE_BACKOFF_MS = 6e4;
181
+ function memoPath(dataDir, kind, baseUrl) {
182
+ const origin = new URL(baseUrl).origin;
183
+ const key = createHash("sha256").update(origin).digest("hex").slice(0, 16);
184
+ return join2(dataDir, "router-memo", `${kind}-${key}.json`);
185
+ }
186
+ async function readRouterMemo(dataDir, kind, baseUrl, now) {
187
+ try {
188
+ const raw = JSON.parse(await readFile2(memoPath(dataDir, kind, baseUrl), "utf8"));
189
+ if (raw === null || typeof raw !== "object") return null;
190
+ const { at, until, detail } = raw;
191
+ if (typeof at !== "number" || typeof until !== "number") return null;
192
+ if (at > now || until <= now) return null;
193
+ return { at, until, ...typeof detail === "string" ? { detail } : {} };
194
+ } catch {
195
+ return null;
196
+ }
197
+ }
198
+ async function writeRouterMemo(dataDir, kind, baseUrl, memo) {
199
+ const body = {
200
+ at: memo.now,
201
+ until: memo.now + memo.ttlMs,
202
+ ...memo.detail !== void 0 ? { detail: memo.detail.slice(0, 300) } : {}
203
+ };
204
+ try {
205
+ await writeFileAtomic(memoPath(dataDir, kind, baseUrl), `${JSON.stringify(body)}
206
+ `, {
207
+ mode: 384,
208
+ dirMode: 448
209
+ });
210
+ } catch {
211
+ }
212
+ }
213
+ async function clearRouterMemo(dataDir, kind, baseUrl) {
214
+ try {
215
+ await rm(memoPath(dataDir, kind, baseUrl), { force: true });
216
+ } catch {
217
+ }
218
+ }
219
+
220
+ export {
221
+ requestToolAccess,
222
+ agentsWithoutRequestTool,
223
+ UNREACHABLE_BACKOFF_MS,
224
+ readRouterMemo,
225
+ writeRouterMemo,
226
+ clearRouterMemo
227
+ };
228
+ //# sourceMappingURL=chunk-RAULEAZ6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/agent-tools.ts","../src/router/router-memo.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { LEGACY_MCP_SERVER_NAME, LEGACY_REQUEST_TOOL, requestToolName } from './names';\n\n/**\n * CAN THIS SUBAGENT CALL `request` AT ALL? An offer to an agent whose definition\n * leaves the tool out is a line it cannot act on, and a router call spent to\n * write it. Claude Code defines a custom agent in a Markdown file whose\n * frontmatter may carry `tools:` (an allowlist) and `disallowedTools:`; this\n * reads that, and nothing else, and never writes to it.\n *\n * ONLY `allowed` IS ACTED ON. A subagent is redirected or offered a lookup\n * only when this KNOWS it can make the call: a definition whose tools cover\n * the request tool (or that has no `tools:` and so inherits everything), or a\n * built-in in {@link MCP_INHERITING_BUILTINS}. Every other built-in, and any\n * type with no definition this can find or read, is `unknown`, and `unknown`\n * gets no router call: `claude-code-guide` ships with Bash, Read, WebFetch and\n * WebSearch and no MCP tools, and denying its WebFetch would strand it exactly\n * as #377 reported.\n *\n * WHERE A DEFINITION LIVES, in the harness's own precedence: the project's\n * `.claude/agents` (from `cwd` up to the filesystem root, nearest first), then\n * `~/.claude/agents`, then an installed plugin's `agents/` for a `plugin:agent`\n * type. A file is found by its name first and by its frontmatter `name:`\n * second, because the type is the `name:` and the file name only usually\n * matches it.\n */\n\nexport type RequestToolAccess = 'allowed' | 'excluded' | 'unknown';\n\n/**\n * The built-in agent types that have no definition file and still inherit MCP\n * tools, so can call the request tool. From Claude Code's own Agent tool\n * listing (2.1.28x): `general-purpose` has every tool, and `Explore` and `Plan`\n * exclude only editing and agent tools, never MCP. Built-ins with a fixed tool\n * list, such as `claude-code-guide` (Bash, Read, WebFetch, WebSearch) and\n * `statusline-setup` (Read, Edit), are deliberately absent.\n */\nexport const MCP_INHERITING_BUILTINS: ReadonlySet<string> = new Set([\n 'general-purpose',\n 'Explore',\n 'Plan',\n]);\n\nexport interface AgentLookup {\n cwd?: string;\n homeDir: string;\n}\n\nconst MAX_AGENT_FILE_BYTES = 256 * 1024;\nconst TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;\n\nexport async function requestToolAccess(\n agentType: string | undefined,\n lookup: AgentLookup,\n tool: string = requestToolName(),\n): Promise<RequestToolAccess> {\n if (agentType === undefined || !TYPE_RE.test(agentType)) return 'unknown';\n try {\n const text = await findDefinition(agentType, lookup);\n if (text !== null) return accessOf(text, tool);\n return MCP_INHERITING_BUILTINS.has(agentType) ? 'allowed' : 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n/**\n * What one definition's frontmatter says about the request tool, named as the\n * leg's harness exposes it (`tool`).\n *\n * THE OLD NAME, AFTER THE RENAME. An agent whose `tools:` names only\n * `mcp__x402__request` cannot call the plugin's tool, so it counts as excluded\n * and doctor names the new name to add. One whose `disallowedTools:` names the\n * old tool or server meant to keep paid lookups out, so it stays excluded.\n * SHIM: the old-name branch goes on or after 2026-12-01.\n */\nexport function accessOf(definition: string, tool: string = requestToolName()): RequestToolAccess {\n const frontmatter = frontmatterOf(definition);\n if (frontmatter === null) return 'unknown';\n const disallowed = listField(frontmatter, 'disallowedTools');\n if (\n disallowed !== undefined &&\n disallowed.some((entry) => namesRequestTool(entry, tool) || namesLegacyTool(entry))\n ) {\n return 'excluded';\n }\n const tools = listField(frontmatter, 'tools');\n if (tools === undefined) return 'allowed';\n return tools.some((entry) => namesRequestTool(entry, tool)) ? 'allowed' : 'excluded';\n}\n\n/**\n * Does one `tools:` or `disallowedTools:` entry cover the request tool? The\n * tool itself, its bare server (`mcp__plugin_tenjin_router`), or any\n * `*`-suffixed pattern the tool's name starts with: `*`, `mcp__*`,\n * `mcp__plugin_tenjin_router__*` and every prefix between.\n */\nfunction namesRequestTool(entry: string, tool: string): boolean {\n if (entry === tool || entry === tool.replace(/__request$/, '')) return true;\n return entry.endsWith('*') && tool.startsWith(entry.slice(0, -1));\n}\n\n/** The settings install's tool or server, by literal or wildcard. */\nfunction namesLegacyTool(entry: string): boolean {\n return namesRequestTool(entry, LEGACY_REQUEST_TOOL) || entry === `mcp__${LEGACY_MCP_SERVER_NAME}`;\n}\n\n/**\n * Every custom agent this project and this user define whose tools leave the\n * request tool out, for `doctor` to name. Plugin agents are not listed: their\n * files are not the user's to edit.\n */\nexport async function agentsWithoutRequestTool(\n lookup: AgentLookup,\n tool: string = requestToolName(),\n): Promise<string[]> {\n const found: string[] = [];\n const seen = new Set<string>();\n for (const directory of agentDirs(lookup)) {\n for (const { name, text } of await definitionsIn(directory)) {\n const type = nameOf(text) ?? name;\n if (seen.has(type)) continue;\n seen.add(type);\n if (accessOf(text, tool) === 'excluded') found.push(type);\n }\n }\n return found.sort();\n}\n\nasync function findDefinition(agentType: string, lookup: AgentLookup): Promise<string | null> {\n for (const directory of agentDirs(lookup)) {\n const text = await definitionIn(directory, agentType);\n if (text !== null) return text;\n }\n const colon = agentType.indexOf(':');\n if (colon > 0) {\n const plugin = agentType.slice(0, colon);\n const agent = agentType.slice(colon + 1);\n for (const root of await pluginRoots(plugin, lookup.homeDir)) {\n const text = await definitionIn(join(root, 'agents'), agent);\n if (text !== null) return text;\n }\n }\n return null;\n}\n\nfunction agentDirs(lookup: AgentLookup): string[] {\n const dirs: string[] = [];\n if (lookup.cwd !== undefined && lookup.cwd.length > 0) {\n let current = resolve(lookup.cwd);\n for (;;) {\n dirs.push(join(current, '.claude', 'agents'));\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n }\n const user = join(resolve(lookup.homeDir), '.claude', 'agents');\n // The user's directory is also an ancestor of most projects; it counts once,\n // in its own place in the order.\n return [...dirs.filter((d) => d !== user), user];\n}\n\nasync function definitionIn(directory: string, agentType: string): Promise<string | null> {\n const direct = await readBounded(join(directory, `${agentType}.md`));\n if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;\n for (const { text } of await definitionsIn(directory)) {\n if (nameOf(text) === agentType) return text;\n }\n return null;\n}\n\nasync function definitionsIn(directory: string): Promise<{ name: string; text: string }[]> {\n let names: string[];\n try {\n names = (await readdir(directory)).filter((n) => n.endsWith('.md')).slice(0, 200);\n } catch {\n return [];\n }\n const out: { name: string; text: string }[] = [];\n for (const file of names) {\n const text = await readBounded(join(directory, file));\n if (text !== null) out.push({ name: file.slice(0, -3), text });\n }\n return out;\n}\n\n/** Install paths `installed_plugins.json` records for `<plugin>@<marketplace>`. */\nasync function pluginRoots(plugin: string, homeDir: string): Promise<string[]> {\n const raw = await readBounded(join(homeDir, '.claude', 'plugins', 'installed_plugins.json'));\n if (raw === null) return [];\n const parsed = JSON.parse(raw) as { plugins?: Record<string, unknown> };\n const roots: string[] = [];\n for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {\n if (key.split('@')[0] !== plugin || !Array.isArray(entries)) continue;\n for (const entry of entries) {\n const path = (entry as { installPath?: unknown }).installPath;\n if (typeof path === 'string' && path.length > 0) roots.push(path);\n }\n }\n return roots;\n}\n\nasync function readBounded(path: string): Promise<string | null> {\n try {\n const text = await readFile(path, 'utf8');\n return text.length > MAX_AGENT_FILE_BYTES ? null : text;\n } catch {\n return null;\n }\n}\n\nfunction frontmatterOf(text: string): string[] | null {\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n return end === -1 ? null : lines.slice(open + 1, end);\n}\n\nfunction nameOf(text: string): string | null {\n const frontmatter = frontmatterOf(text);\n if (frontmatter === null) return null;\n const line = frontmatter.find((l) => /^name\\s*:/.test(l));\n const value = line === undefined ? '' : unquote(line.slice(line.indexOf(':') + 1).trim());\n return value.length > 0 ? value : null;\n}\n\n/**\n * A top-level list field in the three spellings agent files use: `a, b, c`,\n * `[a, b]`, or a block of `- a` lines. `undefined` when the key is absent.\n */\nfunction listField(frontmatter: string[], key: string): string[] | undefined {\n const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\\\s*:`).test(l));\n if (index === -1) return undefined;\n const line = frontmatter[index]!;\n const inline = line.slice(line.indexOf(':') + 1).trim();\n if (inline.length > 0) {\n const body = inline.startsWith('[') && inline.endsWith(']') ? inline.slice(1, -1) : inline;\n return body\n .split(',')\n .map((part) => unquote(part.trim()))\n .filter((part) => part.length > 0);\n }\n const items: string[] = [];\n for (const next of frontmatter.slice(index + 1)) {\n const item = /^\\s+-\\s*(.*)$/.exec(next);\n if (item === null) {\n if (next.trim().length === 0) continue;\n break;\n }\n const value = unquote(item[1]!.trim());\n if (value.length > 0) items.push(value);\n }\n return items;\n}\n\nfunction unquote(value: string): string {\n const quoted = /^(['\"])(.*)\\1$/.exec(value);\n return quoted === null ? value : quoted[2]!;\n}\n","import { createHash } from 'node:crypto';\nimport { readFile, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\n\n/**\n * ONE MEMO FOR \"DO NOT ASK THE ROUTER YET\", per machine and per router origin,\n * in the data dir, so every hook leg and every `tenjin mcp` process reads the\n * same answer. Two facts use it:\n *\n * - `unreachable`: a routing leg's call could not reach the router (DNS, TLS,\n * a refused connection, a proxy refusing the tunnel; see `isUnreachable`). For\n * {@link UNREACHABLE_BACKOFF_MS} every leg skips the router and the native\n * tool runs at once, instead of each prompt and search waiting out the gate.\n * Doctor's probe ends it early when it reaches the router.\n * - `paid-path-absent`: the router answered no paid path (the fee is off), so\n * calls take the free path without asking for an hour, or until the free\n * path answers `fee_required`.\n *\n * A memo is a file written atomically and read with the clock: one older than\n * its window, or dated in the future, reads as absent, so nothing cleans up\n * after it. An unreadable file reads as absent too: the cost of a lost memo is\n * one more call to the router.\n */\nexport type RouterMemoKind = 'unreachable' | 'paid-path-absent';\n\nexport interface RouterMemo {\n /** When it was written, in epoch ms. */\n at: number;\n /** When it ends, in epoch ms. */\n until: number;\n /** What happened, for doctor. */\n detail?: string;\n}\n\n/** How long routing legs skip a router that did not answer. */\nexport const UNREACHABLE_BACKOFF_MS = 60_000;\n\nfunction memoPath(dataDir: string, kind: RouterMemoKind, baseUrl: string): string {\n const origin = new URL(baseUrl).origin;\n const key = createHash('sha256').update(origin).digest('hex').slice(0, 16);\n return join(dataDir, 'router-memo', `${kind}-${key}.json`);\n}\n\n/** The memo in force at `now`, or null. Never throws. */\nexport async function readRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n now: number,\n): Promise<RouterMemo | null> {\n try {\n const raw = JSON.parse(await readFile(memoPath(dataDir, kind, baseUrl), 'utf8')) as unknown;\n if (raw === null || typeof raw !== 'object') return null;\n const { at, until, detail } = raw as Record<string, unknown>;\n if (typeof at !== 'number' || typeof until !== 'number') return null;\n if (at > now || until <= now) return null;\n return { at, until, ...(typeof detail === 'string' ? { detail } : {}) };\n } catch {\n return null;\n }\n}\n\n/** Starts a memo of `ttlMs` from `now`. Never throws. */\nexport async function writeRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n memo: { now: number; ttlMs: number; detail?: string },\n): Promise<void> {\n const body: RouterMemo = {\n at: memo.now,\n until: memo.now + memo.ttlMs,\n ...(memo.detail !== undefined ? { detail: memo.detail.slice(0, 300) } : {}),\n };\n try {\n await writeFileAtomic(memoPath(dataDir, kind, baseUrl), `${JSON.stringify(body)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch {\n // Best effort: a memo that did not land costs one more call.\n }\n}\n\n/** Ends a memo before its window does. Never throws. */\nexport async function clearRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n): Promise<void> {\n try {\n await rm(memoPath(dataDir, kind, baseUrl), { force: true });\n } catch {\n // Best effort: the window ends it anyway.\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,SAAS,MAAM,eAAe;AAqChC,IAAM,0BAA+C,oBAAI,IAAI;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,IAAM,uBAAuB,MAAM;AACnC,IAAM,UAAU;AAEhB,eAAsB,kBACpB,WACA,QACA,OAAe,gBAAgB,GACH;AAC5B,MAAI,cAAc,UAAa,CAAC,QAAQ,KAAK,SAAS,EAAG,QAAO;AAChE,MAAI;AAC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B,IAAI,KAAK;AAAA,IACT,OAAO,KAAK,MAAM,KAAK;AAAA,IACvB,GAAI,KAAK,WAAW,SAAY,EAAE,QAAQ,KAAK,OAAO,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC;AAAA,EAC3E;AACA,MAAI;AACF,UAAM,gBAAgB,SAAS,SAAS,MAAM,OAAO,GAAG,GAAG,KAAK,UAAU,IAAI,CAAC;AAAA,GAAM;AAAA,MACnF,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH,QAAQ;AAAA,EAER;AACF;AAGA,eAAsB,gBACpB,SACA,MACA,SACe;AACf,MAAI;AACF,UAAM,GAAG,SAAS,SAAS,MAAM,OAAO,GAAG,EAAE,OAAO,KAAK,CAAC;AAAA,EAC5D,QAAQ;AAAA,EAER;AACF;","names":["readFile","join","join","readFile"]}
@@ -0,0 +1,30 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/env-proxy.ts
4
+ import * as http from "node:http";
5
+ var PROXY_VARIABLES = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"];
6
+ var nodeSetGlobalProxy = http.setGlobalProxyFromEnv;
7
+ function proxyVariable(env) {
8
+ return PROXY_VARIABLES.find((name) => (env[name] ?? "") !== "");
9
+ }
10
+ function envProxySupported(setGlobal = nodeSetGlobalProxy) {
11
+ return typeof setGlobal === "function";
12
+ }
13
+ function useEnvProxy(env, setGlobal = nodeSetGlobalProxy ?? null) {
14
+ if (proxyVariable(env) === void 0) return "none";
15
+ if (typeof setGlobal !== "function") return "unsupported";
16
+ try {
17
+ setGlobal(env);
18
+ return "set";
19
+ } catch {
20
+ return "invalid";
21
+ }
22
+ }
23
+
24
+ export {
25
+ PROXY_VARIABLES,
26
+ proxyVariable,
27
+ envProxySupported,
28
+ useEnvProxy
29
+ };
30
+ //# sourceMappingURL=chunk-S4SAZ7OD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/env-proxy.ts"],"sourcesContent":["import * as http from 'node:http';\n\n/** Named, never quoted: a proxy URL can carry its own credentials. */\nexport const PROXY_VARIABLES = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'] as const;\n\ntype SetGlobalProxy = (env: NodeJS.ProcessEnv) => () => void;\n\n/** Node 24.14 added it. `engines` admits 22.0, where it is absent. */\nconst nodeSetGlobalProxy = (http as { setGlobalProxyFromEnv?: SetGlobalProxy })\n .setGlobalProxyFromEnv;\n\n/** The first proxy variable this environment sets, or undefined. */\nexport function proxyVariable(env: NodeJS.ProcessEnv): string | undefined {\n return PROXY_VARIABLES.find((name) => (env[name] ?? '') !== '');\n}\n\n/** Can this Node route `fetch` through the proxy the environment names? */\nexport function envProxySupported(setGlobal: unknown = nodeSetGlobalProxy): boolean {\n return typeof setGlobal === 'function';\n}\n\nexport type EnvProxyResult = 'none' | 'set' | 'unsupported' | 'invalid';\n\n/**\n * Send `fetch` and `https.request` through the proxy the environment names.\n * Node's `fetch` ignores HTTPS_PROXY, HTTP_PROXY and NO_PROXY unless\n * NODE_USE_ENV_PROXY=1, so on a network where the proxy is the only way out the\n * harness reaches the internet and Tenjin does not. Called once by the bin\n * entry, so the CLI, the hooks and `tenjin mcp` all get it. Never throws: a\n * proxy URL Node cannot parse leaves the transport as it was.\n */\nexport function useEnvProxy(\n env: NodeJS.ProcessEnv,\n setGlobal: SetGlobalProxy | null = nodeSetGlobalProxy ?? null,\n): EnvProxyResult {\n if (proxyVariable(env) === undefined) return 'none';\n if (typeof setGlobal !== 'function') return 'unsupported';\n try {\n setGlobal(env);\n return 'set';\n } catch {\n return 'invalid';\n }\n}\n"],"mappings":";;;AAAA,YAAY,UAAU;AAGf,IAAM,kBAAkB,CAAC,eAAe,eAAe,cAAc,YAAY;AAKxF,IAAM,qBACH;AAGI,SAAS,cAAc,KAA4C;AACxE,SAAO,gBAAgB,KAAK,CAAC,UAAU,IAAI,IAAI,KAAK,QAAQ,EAAE;AAChE;AAGO,SAAS,kBAAkB,YAAqB,oBAA6B;AAClF,SAAO,OAAO,cAAc;AAC9B;AAYO,SAAS,YACd,KACA,YAAmC,sBAAsB,MACzC;AAChB,MAAI,cAAc,GAAG,MAAM,OAAW,QAAO;AAC7C,MAAI,OAAO,cAAc,WAAY,QAAO;AAC5C,MAAI;AACF,cAAU,GAAG;AACb,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}