tenjin-cli 0.1.0-alpha.14 → 0.1.0-alpha.16

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 (253) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +41 -295
  3. package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
  5. package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
  6. package/dist/chunk-25TJPVBF.js +353 -0
  7. package/dist/chunk-25TJPVBF.js.map +1 -0
  8. package/dist/chunk-2BKS2FVE.js +93 -0
  9. package/dist/chunk-2BKS2FVE.js.map +1 -0
  10. package/dist/chunk-2QYORQBF.js +55 -0
  11. package/dist/chunk-2QYORQBF.js.map +1 -0
  12. package/dist/{chunk-ACBEHJAH.js → chunk-2U5ZVEV3.js} +14 -16
  13. package/dist/chunk-2U5ZVEV3.js.map +1 -0
  14. package/dist/{chunk-MJSXP4LW.js → chunk-3AJS6LLN.js} +11 -8
  15. package/dist/chunk-3AJS6LLN.js.map +1 -0
  16. package/dist/{chunk-OWVVI4VQ.js → chunk-3AUDA53C.js} +7650 -7361
  17. package/dist/chunk-3AUDA53C.js.map +1 -0
  18. package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
  19. package/dist/chunk-56MOAIP5.js.map +1 -0
  20. package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
  21. package/dist/chunk-5X4SZ5BF.js +227 -0
  22. package/dist/chunk-5X4SZ5BF.js.map +1 -0
  23. package/dist/chunk-7WEQQJLG.js +68 -0
  24. package/dist/chunk-7WEQQJLG.js.map +1 -0
  25. package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
  26. package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
  27. package/dist/{chunk-PAOVPSP6.js → chunk-BBVUVBUO.js} +517 -138
  28. package/dist/chunk-BBVUVBUO.js.map +1 -0
  29. package/dist/{chunk-ETKZWJ4B.js → chunk-BFFM2WFK.js} +8 -8
  30. package/dist/chunk-BFFM2WFK.js.map +1 -0
  31. package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
  32. package/dist/chunk-DMZZLPZN.js +205 -0
  33. package/dist/chunk-DMZZLPZN.js.map +1 -0
  34. package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
  35. package/dist/chunk-EGELTSPU.js.map +1 -0
  36. package/dist/chunk-GULLJQXA.js +698 -0
  37. package/dist/chunk-GULLJQXA.js.map +1 -0
  38. package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-HVRC33OL.js +174 -0
  40. package/dist/chunk-HVRC33OL.js.map +1 -0
  41. package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
  42. package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
  43. package/dist/chunk-L3PVMIYQ.js +10328 -0
  44. package/dist/chunk-L3PVMIYQ.js.map +1 -0
  45. package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
  46. package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
  47. package/dist/chunk-MEFB5KHA.js.map +1 -0
  48. package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
  49. package/dist/chunk-N35E6CM2.js.map +1 -0
  50. package/dist/chunk-OCBHUHWB.js +69 -0
  51. package/dist/chunk-OCBHUHWB.js.map +1 -0
  52. package/dist/chunk-OIM4HLN6.js +1405 -0
  53. package/dist/chunk-OIM4HLN6.js.map +1 -0
  54. package/dist/{chunk-PKW3H26Z.js → chunk-OJLYNM4Z.js} +56 -33
  55. package/dist/chunk-OJLYNM4Z.js.map +1 -0
  56. package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
  57. package/dist/chunk-PZEN5PHN.js +285 -0
  58. package/dist/chunk-PZEN5PHN.js.map +1 -0
  59. package/dist/chunk-SKAHDQH7.js +1785 -0
  60. package/dist/chunk-SKAHDQH7.js.map +1 -0
  61. package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
  62. package/dist/{chunk-QWBUKIP2.js → chunk-U5DXNFJC.js} +23 -94
  63. package/dist/chunk-U5DXNFJC.js.map +1 -0
  64. package/dist/chunk-USS336NF.js +165 -0
  65. package/dist/chunk-USS336NF.js.map +1 -0
  66. package/dist/{chunk-UO22YNY4.js → chunk-WH7OWT6G.js} +49 -1
  67. package/dist/chunk-WH7OWT6G.js.map +1 -0
  68. package/dist/chunk-WXC57XGG.js +29 -0
  69. package/dist/chunk-WXC57XGG.js.map +1 -0
  70. package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
  71. package/dist/{chunk-7GJQ5RGA.js → chunk-YEETV6IW.js} +1077 -1039
  72. package/dist/chunk-YEETV6IW.js.map +1 -0
  73. package/dist/{chunk-B676GPS2.js → chunk-YJHHCWM3.js} +39 -16
  74. package/dist/chunk-YJHHCWM3.js.map +1 -0
  75. package/dist/{cli-U2BEUA55.js → cli-M3XCSOU6.js} +295 -349
  76. package/dist/cli-M3XCSOU6.js.map +1 -0
  77. package/dist/config-MXOX7XDR.js +41 -0
  78. package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
  79. package/dist/doctor-LU4YIZWM.js +349 -0
  80. package/dist/doctor-LU4YIZWM.js.map +1 -0
  81. package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  82. package/dist/{chunk-3ZW7HPY5.js → fund-A54P2QFK.js} +81 -22
  83. package/dist/fund-A54P2QFK.js.map +1 -0
  84. package/dist/hook-command-U6KWPEDQ.js +377 -0
  85. package/dist/hook-command-U6KWPEDQ.js.map +1 -0
  86. package/dist/index.js +8 -3
  87. package/dist/index.js.map +1 -1
  88. package/dist/install-XUM2XSHW.js +53 -0
  89. package/dist/install-wallet-QIOFORTX.js +105 -0
  90. package/dist/install-wallet-QIOFORTX.js.map +1 -0
  91. package/dist/{run-CJWPGMIQ.js → mcp-HJC2PLRV.js} +3725 -10661
  92. package/dist/mcp-HJC2PLRV.js.map +1 -0
  93. package/dist/paths-P2N4JTDZ.js +49 -0
  94. package/dist/pay-SBXZEPEP.js +37 -0
  95. package/dist/redact-46ZHF2NH.js +17 -0
  96. package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
  97. package/dist/{send-C5EOKXOU.js → send-ASD2ZXJD.js} +28 -30
  98. package/dist/send-ASD2ZXJD.js.map +1 -0
  99. package/dist/{chunk-NAAMHWSI.js → skill-placement-NFVHY6A3.js} +159 -12
  100. package/dist/skill-placement-NFVHY6A3.js.map +1 -0
  101. package/dist/status-T2SDB57A.js +63 -0
  102. package/dist/status-T2SDB57A.js.map +1 -0
  103. package/dist/status-line-CGPUSDMC.js +71 -0
  104. package/dist/status-line-CGPUSDMC.js.map +1 -0
  105. package/dist/status-line-wiring-BYPHTYZE.js +30 -0
  106. package/dist/tenjin-daemon.mjs +20060 -0
  107. package/dist/tenjin-shim.mjs +251 -0
  108. package/dist/tenjin-vitest-reporter.mjs +49 -0
  109. package/dist/uninstall-FKYZHAM3.js +144 -0
  110. package/dist/uninstall-FKYZHAM3.js.map +1 -0
  111. package/dist/{update-24Y2CQTT.js → update-ANJ2AOTN.js} +133 -17
  112. package/dist/update-ANJ2AOTN.js.map +1 -0
  113. package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  114. package/dist/wallet-PWAHVKWW.js +31 -0
  115. package/dist/wallet-kdf-worker.mjs +980 -0
  116. package/docs/agent-permissions.md +68 -342
  117. package/docs/safety-model.md +25 -6
  118. package/package.json +8 -7
  119. package/LICENSE +0 -21
  120. package/dist/buy-2JBYPHAI.js +0 -46
  121. package/dist/chunk-3P3ES4XU.js +0 -144
  122. package/dist/chunk-3P3ES4XU.js.map +0 -1
  123. package/dist/chunk-3ZW7HPY5.js.map +0 -1
  124. package/dist/chunk-47PP7TAG.js.map +0 -1
  125. package/dist/chunk-4UHNXY6B.js +0 -786
  126. package/dist/chunk-4UHNXY6B.js.map +0 -1
  127. package/dist/chunk-4Y53PDH6.js +0 -213
  128. package/dist/chunk-4Y53PDH6.js.map +0 -1
  129. package/dist/chunk-54AJIO3E.js +0 -198
  130. package/dist/chunk-54AJIO3E.js.map +0 -1
  131. package/dist/chunk-736DW4V3.js +0 -65
  132. package/dist/chunk-736DW4V3.js.map +0 -1
  133. package/dist/chunk-7GJQ5RGA.js.map +0 -1
  134. package/dist/chunk-7NADDA2V.js +0 -161
  135. package/dist/chunk-7NADDA2V.js.map +0 -1
  136. package/dist/chunk-ACBEHJAH.js.map +0 -1
  137. package/dist/chunk-B676GPS2.js.map +0 -1
  138. package/dist/chunk-DAZAXFSF.js +0 -1357
  139. package/dist/chunk-DAZAXFSF.js.map +0 -1
  140. package/dist/chunk-DTCXO7HS.js +0 -791
  141. package/dist/chunk-DTCXO7HS.js.map +0 -1
  142. package/dist/chunk-ETKZWJ4B.js.map +0 -1
  143. package/dist/chunk-FDUD3W5V.js +0 -317
  144. package/dist/chunk-FDUD3W5V.js.map +0 -1
  145. package/dist/chunk-GEHL43VE.js +0 -711
  146. package/dist/chunk-GEHL43VE.js.map +0 -1
  147. package/dist/chunk-IU2HVT3Y.js +0 -313
  148. package/dist/chunk-IU2HVT3Y.js.map +0 -1
  149. package/dist/chunk-IUQZ4Z7M.js +0 -162
  150. package/dist/chunk-IUQZ4Z7M.js.map +0 -1
  151. package/dist/chunk-IXZJ3JOO.js +0 -614
  152. package/dist/chunk-IXZJ3JOO.js.map +0 -1
  153. package/dist/chunk-J6FUAIRR.js +0 -205
  154. package/dist/chunk-J6FUAIRR.js.map +0 -1
  155. package/dist/chunk-L6G35FU5.js +0 -105
  156. package/dist/chunk-L6G35FU5.js.map +0 -1
  157. package/dist/chunk-LSWP7MU2.js +0 -290
  158. package/dist/chunk-LSWP7MU2.js.map +0 -1
  159. package/dist/chunk-M2O56UK7.js.map +0 -1
  160. package/dist/chunk-MJSXP4LW.js.map +0 -1
  161. package/dist/chunk-MJZZTKCC.js.map +0 -1
  162. package/dist/chunk-NAAMHWSI.js.map +0 -1
  163. package/dist/chunk-O75FOHXS.js +0 -372
  164. package/dist/chunk-O75FOHXS.js.map +0 -1
  165. package/dist/chunk-OWVVI4VQ.js.map +0 -1
  166. package/dist/chunk-PAOVPSP6.js.map +0 -1
  167. package/dist/chunk-PCX2JQ2J.js +0 -233
  168. package/dist/chunk-PCX2JQ2J.js.map +0 -1
  169. package/dist/chunk-PKW3H26Z.js.map +0 -1
  170. package/dist/chunk-PQZVDCCA.js +0 -125
  171. package/dist/chunk-PQZVDCCA.js.map +0 -1
  172. package/dist/chunk-QWBUKIP2.js.map +0 -1
  173. package/dist/chunk-SGK2B724.js +0 -67
  174. package/dist/chunk-SGK2B724.js.map +0 -1
  175. package/dist/chunk-UHTVXQ2O.js +0 -140
  176. package/dist/chunk-UHTVXQ2O.js.map +0 -1
  177. package/dist/chunk-UO22YNY4.js.map +0 -1
  178. package/dist/chunk-VEAERJVJ.js +0 -43
  179. package/dist/chunk-VEAERJVJ.js.map +0 -1
  180. package/dist/chunk-VRPLZERE.js +0 -1421
  181. package/dist/chunk-VRPLZERE.js.map +0 -1
  182. package/dist/chunk-W4VW5XYB.js +0 -149
  183. package/dist/chunk-W4VW5XYB.js.map +0 -1
  184. package/dist/chunk-WU5CZPLD.js +0 -145
  185. package/dist/chunk-WU5CZPLD.js.map +0 -1
  186. package/dist/chunk-WYLMJQVH.js +0 -240
  187. package/dist/chunk-WYLMJQVH.js.map +0 -1
  188. package/dist/chunk-XGZ5EVMB.js +0 -35
  189. package/dist/chunk-XGZ5EVMB.js.map +0 -1
  190. package/dist/chunk-XVPQGCH4.js +0 -176
  191. package/dist/chunk-XVPQGCH4.js.map +0 -1
  192. package/dist/chunk-ZOBNS7CX.js.map +0 -1
  193. package/dist/chunk-ZQIQ55KK.js +0 -51
  194. package/dist/chunk-ZQIQ55KK.js.map +0 -1
  195. package/dist/cli-U2BEUA55.js.map +0 -1
  196. package/dist/config-CNUIX23Q.js +0 -32
  197. package/dist/doctor-QJJXRWTO.js +0 -31
  198. package/dist/edit-HJ44P44P.js +0 -40
  199. package/dist/fund-Y5IAHZ5D.js +0 -40
  200. package/dist/inspect-NFQ6SQQQ.js +0 -37
  201. package/dist/install-DXX7PVUP.js +0 -854
  202. package/dist/install-DXX7PVUP.js.map +0 -1
  203. package/dist/outcome-ANV4QIED.js +0 -24
  204. package/dist/publish-PCBTCXCZ.js +0 -42
  205. package/dist/read-W7QVRBVD.js +0 -160
  206. package/dist/read-W7QVRBVD.js.map +0 -1
  207. package/dist/run-CJWPGMIQ.js.map +0 -1
  208. package/dist/search-JGAVKTYJ.js +0 -25
  209. package/dist/secp256k1-XRPVBC6V.js.map +0 -1
  210. package/dist/send-C5EOKXOU.js.map +0 -1
  211. package/dist/session-OBCUUIFX.js +0 -89
  212. package/dist/session-OBCUUIFX.js.map +0 -1
  213. package/dist/skill-heal-D6EPLPS6.js +0 -84
  214. package/dist/skill-heal-D6EPLPS6.js.map +0 -1
  215. package/dist/uninstall-OWJNJ5LI.js +0 -73
  216. package/dist/uninstall-OWJNJ5LI.js.map +0 -1
  217. package/dist/update-24Y2CQTT.js.map +0 -1
  218. package/dist/usdc-4VCDHFWX.js +0 -38
  219. package/dist/usdc-4VCDHFWX.js.map +0 -1
  220. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
  221. package/dist/wallet-OFXDIIGP.js +0 -33
  222. package/dist/wallet-OFXDIIGP.js.map +0 -1
  223. package/dist/wallet-SLRIYJ2U.js +0 -42
  224. package/dist/wallet-SLRIYJ2U.js.map +0 -1
  225. package/docs/command-reference.md +0 -261
  226. package/skills/tenjin/SKILL.md +0 -364
  227. package/skills/tenjin-publish/SKILL.md +0 -224
  228. package/skills/tenjin-publish/references/maintain.md +0 -39
  229. package/skills/tenjin-search/SKILL.md +0 -149
  230. package/skills/tenjin-search/references/permissions.md +0 -106
  231. /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
  232. /package/dist/{buy-2JBYPHAI.js.map → ccip-7RMRLAGV.js.map} +0 -0
  233. /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
  234. /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
  235. /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
  236. /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
  237. /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  238. /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
  239. /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
  240. /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
  241. /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
  242. /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
  243. /package/dist/{ccip-ZGGWQN4X.js.map → config-MXOX7XDR.js.map} +0 -0
  244. /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
  245. /package/dist/{config-CNUIX23Q.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  246. /package/dist/{doctor-QJJXRWTO.js.map → install-XUM2XSHW.js.map} +0 -0
  247. /package/dist/{edit-HJ44P44P.js.map → paths-P2N4JTDZ.js.map} +0 -0
  248. /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-SBXZEPEP.js.map} +0 -0
  249. /package/dist/{fund-Y5IAHZ5D.js.map → redact-46ZHF2NH.js.map} +0 -0
  250. /package/dist/{inspect-NFQ6SQQQ.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
  251. /package/dist/{outcome-ANV4QIED.js.map → status-line-wiring-BYPHTYZE.js.map} +0 -0
  252. /package/dist/{publish-PCBTCXCZ.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
  253. /package/dist/{search-JGAVKTYJ.js.map → wallet-PWAHVKWW.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/session-key.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while `read` can import the present half ALONE and\n * stay structurally unable to open a keystore. Do not move a signer-touching\n * function down into `session-present.ts`: read's import-graph pin is what makes\n * \"read cannot mint and cannot pay\" a property of the code rather than a promise.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: `session start` and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAyEnB,IAAM,mBAAmB;AAEhC,IAAM,iBAAiB,KAAK,KAAK,KAAK;AA0BtC,IAAM,SAAS,UAAU;AAEzB,SAAS,sBAAwD;AAC/D,SAAO,OAAO,YAAY,EAAE,MAAM,SAAS,YAAY,QAAQ,GAAG,MAAM;AAAA,IACtE;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAGA,SAAS,YAAY,OAA2B;AAC9C,SAAO,OAAO,KAAK,KAAK,EAAE,SAAS,WAAW;AAChD;AAGO,SAAS,oBACd,cACA,QACA,OACU;AACV,SAAO;AAAA,IACL,kCAAkC,YAAY;AAAA,IAC9C,0BAA0B,MAAM;AAAA,IAChC,4BAA4B,KAAK;AAAA,EACnC;AACF;AAQA,eAAsB,iBACpB,QACA,OAAuB,CAAC,GACF;AACtB,QAAM,MAAM,KAAK,OAAO,KAAK;AAC7B,QAAM,OAAO,MAAM,oBAAoB;AACvC,QAAM,SAAS,IAAI,WAAW,MAAM,OAAO,UAAU,OAAO,KAAK,SAAS,CAAC;AAC3E,QAAM,eAAe,YAAY,MAAM;AACvC,QAAM,MAAO,MAAM,OAAO,UAAU,OAAO,KAAK,UAAU;AAE1D,QAAM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AAO,OAAO;AACnD,YAAM,SAAS,SAAS,OAAO,OAAO;AACtC,UACE,WAAW,QACX,gBAAgB,QAAQ,OAAO,OAAO,SAAS,IAAI,GAAG,OAAO,OAAO,MAAM,GAC1E;AACA,iBAAS;AACT,eAAO;AAAA,MACT;AAAA,IACF;AACA,aAAS,MAAM,iBAAiB,QAAQ,IAAI;AAC5C,uBAAmB;AACnB,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,MAAM,WAAW,KAAK;AACpB,YAAM,OAAO,MAAM,OAAO;AAC1B,aAAO,gBAAgB,MAAM,KAAK,IAAI;AAAA,IACxC;AAAA,IACA,MAAM,QAAQ,MAAM;AAClB,YAAM,WAAW,YAAY,IAAI;AACjC,UAAI,aAAa,QAAS,QAAO;AACjC,UAAI,aAAa,eAAe;AAC9B,iBAAS;AACT,2BAAmB;AAAA,MACrB;AAGA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAOO,SAAS,eAAe,QAAqC;AAClE,SAAO;AAAA,IACL,MAAM,aAAa;AACjB,YAAM,SAAS,MAAM,gBAAgB,OAAO,QAAQ;AAAA,QAClD,SAAS,OAAO;AAAA,QAChB,SAAS,OAAO;AAAA,MAClB,CAAC;AACD,aAAO,EAAE,kBAAkB,OAAO;AAAA,IACpC;AAAA,IACA,MAAM,QAAQ,MAAM;AAGlB,aAAO,SAAS,wBAAwB,SAAS,mBAAmB,SAAS;AAAA,IAC/E;AAAA,EACF;AACF;","names":[]}
@@ -1,240 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- resolveThroughLink
4
- } from "./chunk-NAAMHWSI.js";
5
- import {
6
- STOP_HOOK_FILE,
7
- WEBSEARCH_HOOK_FILE
8
- } from "./chunk-DTCXO7HS.js";
9
- import {
10
- FREE_VERB_RULES,
11
- LEGACY_ALLOWLIST_RULES,
12
- MODE_GATED_RULES,
13
- claudeSettingsPath
14
- } from "./chunk-IU2HVT3Y.js";
15
- import {
16
- hooksDir
17
- } from "./chunk-ZQIQ55KK.js";
18
- import {
19
- CLI_SKILL_NAMES,
20
- HOSTED_SKILL_NAME,
21
- SHIPPED_SKILL_FILES,
22
- readSkillFile,
23
- skillFrontmatterName,
24
- skillsDirsFor
25
- } from "./chunk-QWBUKIP2.js";
26
- import {
27
- writeFileAtomic
28
- } from "./chunk-PAOVPSP6.js";
29
-
30
- // src/lib/uninstall.ts
31
- import { lstat, readFile, readdir, rm, rmdir, realpath } from "fs/promises";
32
- import { lstatSync } from "fs";
33
- import { dirname, join } from "path";
34
- var KEPT_ITEMS = [
35
- "your wallet, config (publish.mode included, so a later install resumes it), library, and search history under ~/.tenjin",
36
- "anything an older version left in ~/.tenjin/candidates (nothing reads it now)"
37
- ];
38
- var REMOVED_FROM_DATA_DIR = "the generated hook scripts in ~/.tenjin/hooks (install writes them back)";
39
- var SKILLS_MARKER = "<!-- tenjin-cli:skills -->";
40
- function isPlainObject(value) {
41
- return typeof value === "object" && value !== null && !Array.isArray(value);
42
- }
43
- function ownsHookEntry(entry) {
44
- if (!isPlainObject(entry)) return false;
45
- const handlers = entry.hooks;
46
- if (!Array.isArray(handlers)) return false;
47
- return handlers.some(
48
- (h) => isPlainObject(h) && typeof h.command === "string" && (h.command.includes(WEBSEARCH_HOOK_FILE) || h.command.includes(STOP_HOOK_FILE))
49
- );
50
- }
51
- async function removeFromSettings(homeDir) {
52
- const declaredPath = claudeSettingsPath(homeDir);
53
- const skip = (path2, skipped, warning) => ({
54
- path: path2,
55
- hooks: [],
56
- rules: [],
57
- skipped,
58
- ...warning !== void 0 ? { warning } : {}
59
- });
60
- const entry = await lstat(declaredPath).catch(() => null);
61
- if (entry === null) return skip(declaredPath, "absent");
62
- let path;
63
- try {
64
- path = await realpath(declaredPath);
65
- } catch (err) {
66
- return skip(
67
- declaredPath,
68
- "unresolvable",
69
- `${declaredPath} could not be resolved (${err.message}); it was left exactly as it is.`
70
- );
71
- }
72
- let raw;
73
- try {
74
- raw = await readFile(path, "utf8");
75
- } catch (err) {
76
- return skip(
77
- path,
78
- "unreadable",
79
- `${path} could not be read (${err.message}); it was left exactly as it is.`
80
- );
81
- }
82
- let parsed;
83
- try {
84
- parsed = JSON.parse(raw);
85
- } catch (err) {
86
- return skip(
87
- path,
88
- "unparsable",
89
- `${path} is not valid JSON (${err.message}); it was left exactly as it is.`
90
- );
91
- }
92
- if (!isPlainObject(parsed)) {
93
- return skip(path, "unexpected-shape", `${path} is not a JSON object; it was left as it is.`);
94
- }
95
- const settings = parsed;
96
- const removedHooks = [];
97
- const removedRules = [];
98
- let next = settings;
99
- const hooksValue = settings.hooks;
100
- if (hooksValue !== void 0 && !isPlainObject(hooksValue)) {
101
- return skip(
102
- path,
103
- "unexpected-shape",
104
- `${path} has a "hooks" key that is not an object; it was left exactly as it is.`
105
- );
106
- }
107
- if (isPlainObject(hooksValue)) {
108
- const nextHooks = {};
109
- for (const [event, value] of Object.entries(hooksValue)) {
110
- if (!Array.isArray(value)) {
111
- nextHooks[event] = value;
112
- continue;
113
- }
114
- const kept = value.filter((e) => !ownsHookEntry(e));
115
- if (kept.length !== value.length) removedHooks.push(event);
116
- const emptiedByUs = kept.length === 0 && value.length > 0;
117
- if (!emptiedByUs) nextHooks[event] = kept;
118
- }
119
- next = { ...next, hooks: nextHooks };
120
- if (Object.keys(nextHooks).length === 0) delete next.hooks;
121
- }
122
- const permissions = settings.permissions;
123
- if (isPlainObject(permissions) && Array.isArray(permissions.allow)) {
124
- const ours = /* @__PURE__ */ new Set([
125
- ...FREE_VERB_RULES,
126
- ...LEGACY_ALLOWLIST_RULES,
127
- ...MODE_GATED_RULES
128
- ]);
129
- const kept = permissions.allow.filter((r) => !(typeof r === "string" && ours.has(r)));
130
- if (kept.length !== permissions.allow.length) {
131
- for (const rule of permissions.allow) {
132
- if (typeof rule === "string" && ours.has(rule)) removedRules.push(rule);
133
- }
134
- const nextPermissions = { ...permissions, allow: kept };
135
- if (kept.length === 0) delete nextPermissions.allow;
136
- next = { ...next, permissions: nextPermissions };
137
- if (Object.keys(nextPermissions).length === 0) delete next.permissions;
138
- }
139
- }
140
- if (removedHooks.length === 0 && removedRules.length === 0) {
141
- return { path, hooks: [], rules: [] };
142
- }
143
- const current = await readFile(path, "utf8").catch(() => null);
144
- if (current !== raw) {
145
- return skip(
146
- path,
147
- "changed-since-read",
148
- `${path} changed while it was being updated, so nothing was removed from it. Re-run \`tenjin uninstall\`.`
149
- );
150
- }
151
- await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}
152
- `);
153
- return { path, hooks: removedHooks, rules: removedRules };
154
- }
155
- async function removeHookScripts(dataDir) {
156
- const dir = hooksDir(dataDir);
157
- const removed = [];
158
- for (const file of [WEBSEARCH_HOOK_FILE, STOP_HOOK_FILE]) {
159
- const path = join(dir, file);
160
- if (lstatSync(path, { throwIfNoEntry: false })?.isFile() !== true) continue;
161
- await rm(path, { force: true });
162
- removed.push(path);
163
- }
164
- const rest = await readdir(dir).catch(() => null);
165
- if (rest !== null && rest.length === 0) {
166
- const gone = await rmdir(dir).then(
167
- () => true,
168
- () => false
169
- );
170
- if (gone) return { scripts: removed, removedDir: dir };
171
- }
172
- return { scripts: removed };
173
- }
174
- async function removeSkills(homeDir) {
175
- const removed = [];
176
- const names = [...CLI_SKILL_NAMES, HOSTED_SKILL_NAME];
177
- for (const dir of skillsDirsFor(homeDir)) {
178
- if (lstatSync(dir, { throwIfNoEntry: false })?.isDirectory() !== true) continue;
179
- for (const name of names) {
180
- const skillDir = join(dir, name);
181
- if (lstatSync(skillDir, { throwIfNoEntry: false })?.isDirectory() !== true) continue;
182
- const path = join(skillDir, "SKILL.md");
183
- if (lstatSync(path, { throwIfNoEntry: false })?.isFile() !== true) continue;
184
- const read = await readSkillFile(path);
185
- if (read.kind !== "ok") continue;
186
- if (skillFrontmatterName(read.bytes.toString("utf8")) !== name) continue;
187
- const shipped = SHIPPED_SKILL_FILES[name];
188
- const subdirs = /* @__PURE__ */ new Set();
189
- for (const rel of shipped) {
190
- if (rel === "SKILL.md") continue;
191
- const file = join(skillDir, rel);
192
- subdirs.add(dirname(file));
193
- if (lstatSync(file, { throwIfNoEntry: false })?.isFile() !== true) continue;
194
- await rm(file, { force: true });
195
- }
196
- await rm(path, { force: true });
197
- for (const dir2 of [...subdirs].sort((a, b) => b.length - a.length)) {
198
- const left = await readdir(dir2).catch(() => null);
199
- if (left !== null && left.length === 0) await rmdir(dir2).catch(() => void 0);
200
- }
201
- const rest = await readdir(skillDir).catch(() => null);
202
- if (rest !== null && rest.length === 0) {
203
- await rmdir(skillDir).catch(() => void 0);
204
- }
205
- removed.push(skillDir);
206
- }
207
- }
208
- return removed;
209
- }
210
- async function removeMarkerLines(homeDir) {
211
- const cleaned = [];
212
- for (const path of markerFiles(homeDir)) {
213
- const read = await readSkillFile(path);
214
- if (read.kind !== "ok") continue;
215
- const text = read.bytes.toString("utf8");
216
- if (!text.split("\n").some((l) => l.startsWith(SKILLS_MARKER))) continue;
217
- const kept = text.split("\n").filter((l) => !l.startsWith(SKILLS_MARKER));
218
- const writeTo = await resolveThroughLink(path, "the Tenjin pointer");
219
- await writeFileAtomic(writeTo, kept.join("\n"));
220
- cleaned.push(path);
221
- }
222
- return cleaned;
223
- }
224
- function markerFiles(homeDir) {
225
- return [
226
- join(homeDir, ".claude", "CLAUDE.md"),
227
- join(homeDir, ".agents", "AGENTS.md"),
228
- join(homeDir, ".codex", "AGENTS.md")
229
- ];
230
- }
231
-
232
- export {
233
- KEPT_ITEMS,
234
- REMOVED_FROM_DATA_DIR,
235
- removeFromSettings,
236
- removeHookScripts,
237
- removeSkills,
238
- removeMarkerLines
239
- };
240
- //# sourceMappingURL=chunk-WYLMJQVH.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/uninstall.ts"],"sourcesContent":["import { lstat, readFile, readdir, rm, rmdir, realpath } from 'node:fs/promises';\nimport { lstatSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport {\n claudeSettingsPath,\n FREE_VERB_RULES,\n LEGACY_ALLOWLIST_RULES,\n MODE_GATED_RULES,\n} from './harness-permissions';\nimport { STOP_HOOK_FILE, WEBSEARCH_HOOK_FILE } from './hook-scripts';\nimport { hooksDir } from './paths';\nimport { SHIPPED_SKILL_FILES } from './skills-source';\nimport { resolveThroughLink } from './skill-writer';\nimport {\n CLI_SKILL_NAMES,\n HOSTED_SKILL_NAME,\n readSkillFile,\n skillFrontmatterName,\n skillsDirsFor,\n} from './skill-wiring';\n\n/**\n * The reverse of `install`, and ONLY of `install`.\n *\n * Every removal here is gated on OWNERSHIP rather than position or path alone,\n * reusing the rules the writers already use: a hook entry is ours when its\n * command names one of our two script filenames (lib/harness-hooks.ts), a skill\n * directory is ours when its SKILL.md frontmatter claims our skill's name\n * (lib/skill-heal.ts), a permission rule is ours when it is one of the free-verb\n * rules we wrote. Anything that merely sits at one of our paths belongs to\n * somebody else and is left alone.\n *\n * WHAT IS NEVER TOUCHED: anything under the data dir. The wallet, the config,\n * the library receipts, the search ledger, and whatever an older version left\n * in `candidates/` are all the operator's property, and their loss is\n * unrecoverable (a wallet holds funds). `install` did not create them, so\n * uninstall does not remove them, and the command says so in its own output\n * rather than leaving it to the docs.\n *\n * SETTINGS.JSON IS EDITED IN ONE PASS. Hooks and permission rules live in the\n * same file, so removing them separately would mean two whole-file\n * read-modify-writes and two chances to lose a concurrent edit by Claude Code.\n * One pass, one optimistic-concurrency check, one refusal.\n */\n\n/** Everything the command found and acted on, for both the receipt and the JSON. */\nexport interface UninstallReport {\n settings: SettingsOutcome;\n skills: string[];\n scripts: string[];\n hooksDir?: string;\n markers: string[];\n kept: string[];\n}\n\nexport interface SettingsOutcome {\n path: string;\n /** Hook events whose entry was ours and was removed. */\n hooks: string[];\n /** Free-verb rules removed from `permissions.allow`. */\n rules: string[];\n /** Absent when the file was edited (or had nothing of ours in it). */\n skipped?: SettingsSkipReason;\n warning?: string;\n}\n\nexport type SettingsSkipReason =\n | 'absent'\n | 'unresolvable'\n | 'unreadable'\n | 'unparsable'\n | 'unexpected-shape'\n | 'changed-since-read';\n\n/**\n * What uninstall deliberately leaves behind, named in the output every run.\n *\n * Stated as one rule and its ONE exception, rather than an inventory: everything\n * under the data dir is the operator's, so a list edited every time a file is\n * added or retired is a list that will eventually be wrong. The exception has to\n * be named, though. `~/.tenjin/hooks/*.mjs` is generated by `install`, is deleted\n * here, and is under the same directory the rule calls untouched, so the\n * unqualified version contradicted what the run in front of the operator had just\n * reported removing. `candidates/` is named explicitly because it is the one\n * directory nothing writes any more: an older version's parked drafts are still\n * sitting there, and someone who wants them needs the path.\n *\n * `publish.mode` is called out inside the config item because it is the one kept\n * value that GRANTS something on the next `install`: the rules come back under the\n * remembered mode. That is the intended model (installing is the consent, each\n * time), and docs/agent-permissions.md carries the full paragraph, but an operator\n * uninstalling to revoke should not have to find it there.\n */\nexport const KEPT_ITEMS: readonly string[] = [\n 'your wallet, config (publish.mode included, so a later install resumes it), library, and search history under ~/.tenjin',\n 'anything an older version left in ~/.tenjin/candidates (nothing reads it now)',\n];\n\n/**\n * The one thing under the data dir this command DOES remove, named beside\n * {@link KEPT_ITEMS} so the boundary reads as a boundary.\n */\nexport const REMOVED_FROM_DATA_DIR =\n 'the generated hook scripts in ~/.tenjin/hooks (install writes them back)';\n\n/** The legacy pointer line `install` used to write into CLAUDE.md / AGENTS.md. */\nexport const SKILLS_MARKER = '<!-- tenjin-cli:skills -->';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Ours by the same rule that wrote it: the command names one of our scripts. */\nfunction ownsHookEntry(entry: unknown): boolean {\n if (!isPlainObject(entry)) return false;\n const handlers = entry.hooks;\n if (!Array.isArray(handlers)) return false;\n return handlers.some(\n (h) =>\n isPlainObject(h) &&\n typeof h.command === 'string' &&\n (h.command.includes(WEBSEARCH_HOOK_FILE) || h.command.includes(STOP_HOOK_FILE)),\n );\n}\n\n/**\n * Strip our hook entries and our free-verb rules from ~/.claude/settings.json,\n * leaving every other entry, rule, and key exactly where it was.\n *\n * Removal is BY OWNERSHIP, never by index: an entry we did not write keeps its\n * position even when one of ours is removed from in front of it. An emptied\n * `hooks.<event>` array is dropped rather than left as `[]`, and an emptied\n * `hooks` or `permissions.allow` likewise, so a full uninstall leaves the file\n * as it would have been had install never run — but only when WE emptied them.\n */\nexport async function removeFromSettings(homeDir: string): Promise<SettingsOutcome> {\n const declaredPath = claudeSettingsPath(homeDir);\n const skip = (path: string, skipped: SettingsSkipReason, warning?: string): SettingsOutcome => ({\n path,\n hooks: [],\n rules: [],\n skipped,\n ...(warning !== undefined ? { warning } : {}),\n });\n\n const entry = await lstat(declaredPath).catch(() => null);\n if (entry === null) return skip(declaredPath, 'absent');\n\n let path: string;\n try {\n path = await realpath(declaredPath);\n } catch (err) {\n return skip(\n declaredPath,\n 'unresolvable',\n `${declaredPath} could not be resolved (${(err as Error).message}); it was left exactly as it is.`,\n );\n }\n\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n return skip(\n path,\n 'unreadable',\n `${path} could not be read (${(err as Error).message}); it was left exactly as it is.`,\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return skip(\n path,\n 'unparsable',\n `${path} is not valid JSON (${(err as Error).message}); it was left exactly as it is.`,\n );\n }\n if (!isPlainObject(parsed)) {\n return skip(path, 'unexpected-shape', `${path} is not a JSON object; it was left as it is.`);\n }\n\n const settings = parsed;\n const removedHooks: string[] = [];\n const removedRules: string[] = [];\n let next: Record<string, unknown> = settings;\n\n const hooksValue = settings.hooks;\n if (hooksValue !== undefined && !isPlainObject(hooksValue)) {\n return skip(\n path,\n 'unexpected-shape',\n `${path} has a \"hooks\" key that is not an object; it was left exactly as it is.`,\n );\n }\n if (isPlainObject(hooksValue)) {\n const nextHooks: Record<string, unknown> = {};\n for (const [event, value] of Object.entries(hooksValue)) {\n if (!Array.isArray(value)) {\n nextHooks[event] = value;\n continue;\n }\n const kept = value.filter((e) => !ownsHookEntry(e));\n if (kept.length !== value.length) removedHooks.push(event);\n // An event WE emptied loses its key entirely; one that still holds someone\n // else's entry keeps it, and an array that was already empty before we\n // looked is left as we found it.\n const emptiedByUs = kept.length === 0 && value.length > 0;\n if (!emptiedByUs) nextHooks[event] = kept;\n }\n next = { ...next, hooks: nextHooks };\n if (Object.keys(nextHooks).length === 0) delete next.hooks;\n }\n\n const permissions = settings.permissions;\n if (isPlainObject(permissions) && Array.isArray(permissions.allow)) {\n // What THIS version writes, plus what any prior version wrote. A rule we\n // retired is still a rule we put there, and leaving it behind would strand a\n // dead allow-line for a command that no longer exists. The mode-gated pair is\n // reclaimed WHATEVER the mode says: uninstall removes what this CLI wrote,\n // and the mode that justified those rules is about to have no CLI behind it.\n const ours = new Set<string>([\n ...FREE_VERB_RULES,\n ...LEGACY_ALLOWLIST_RULES,\n ...MODE_GATED_RULES,\n ]);\n const kept = permissions.allow.filter((r) => !(typeof r === 'string' && ours.has(r)));\n if (kept.length !== permissions.allow.length) {\n for (const rule of permissions.allow) {\n if (typeof rule === 'string' && ours.has(rule)) removedRules.push(rule);\n }\n const nextPermissions: Record<string, unknown> = { ...permissions, allow: kept };\n if (kept.length === 0) delete nextPermissions.allow;\n next = { ...next, permissions: nextPermissions };\n if (Object.keys(nextPermissions).length === 0) delete next.permissions;\n }\n }\n\n if (removedHooks.length === 0 && removedRules.length === 0) {\n return { path, hooks: [], rules: [] };\n }\n\n // The same optimistic-concurrency contract the writers hold: this is a\n // whole-file replacement built from a snapshot, and Claude Code writes this\n // file too, so a change that landed underneath us is refused rather than\n // erased.\n const current = await readFile(path, 'utf8').catch(() => null);\n if (current !== raw) {\n return skip(\n path,\n 'changed-since-read',\n `${path} changed while it was being updated, so nothing was removed from it. Re-run \\`tenjin uninstall\\`.`,\n );\n }\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`);\n return { path, hooks: removedHooks, rules: removedRules };\n}\n\n/**\n * Delete the generated hook scripts and, when it is left empty, the directory\n * that held them. Only our two filenames: a file someone else parked in there is\n * both left alone and reason to keep the directory.\n */\nexport async function removeHookScripts(dataDir: string): Promise<{\n scripts: string[];\n removedDir?: string;\n}> {\n const dir = hooksDir(dataDir);\n const removed: string[] = [];\n for (const file of [WEBSEARCH_HOOK_FILE, STOP_HOOK_FILE]) {\n const path = join(dir, file);\n // isFile, not mere existence: a directory parked at a script path would make\n // the non-recursive `rm` throw EISDIR and abort the uninstall halfway.\n if (lstatSync(path, { throwIfNoEntry: false })?.isFile() !== true) continue;\n await rm(path, { force: true });\n removed.push(path);\n }\n const rest = await readdir(dir).catch(() => null);\n if (rest !== null && rest.length === 0) {\n // `rmdir`, not a recursive `rm`: it removes an EMPTY directory and nothing\n // else, so a file that appeared between the listing and this call keeps the\n // directory instead of being swept away with it.\n const gone = await rmdir(dir).then(\n () => true,\n () => false,\n );\n if (gone) return { scripts: removed, removedDir: dir };\n }\n return { scripts: removed };\n}\n\n/**\n * Remove the skills we installed, in every harness location.\n *\n * REMOVES THE FILES WE SHIPPED, NOT THE DIRECTORY THEY SIT IN. Everything else in\n * that directory belongs to the operator — notes, a local override, anything\n * they put beside our files — and a recursive delete of a directory we only\n * partly own is the data-loss shape this repo already unlearned once on the\n * write side (see lib/skill-writer.ts: \"Only the files this package SHIPS are\n * read and written\"). So: unlink each path in {@link SHIPPED_SKILL_FILES}, then\n * remove a directory only if nothing is left in it, exactly as\n * `removeHookScripts` does one function up. A skill that ships a `references/`\n * subdirectory has that pruned the same way, deepest first — an operator file\n * beside ours keeps both itself and the directory it is in.\n *\n * Ours means the SKILL.md frontmatter still claims the name we wrote, the rule\n * `skill-heal` uses to decide it may rewrite a file. A skill someone replaced\n * with their own is not ours to delete just for sitting at our path, and neither\n * is a directory reached through a symlink.\n */\nexport async function removeSkills(homeDir: string): Promise<string[]> {\n const removed: string[] = [];\n const names = [...CLI_SKILL_NAMES, HOSTED_SKILL_NAME];\n for (const dir of skillsDirsFor(homeDir)) {\n if (lstatSync(dir, { throwIfNoEntry: false })?.isDirectory() !== true) continue;\n for (const name of names) {\n const skillDir = join(dir, name);\n if (lstatSync(skillDir, { throwIfNoEntry: false })?.isDirectory() !== true) continue;\n const path = join(skillDir, 'SKILL.md');\n if (lstatSync(path, { throwIfNoEntry: false })?.isFile() !== true) continue;\n const read = await readSkillFile(path);\n if (read.kind !== 'ok') continue;\n if (skillFrontmatterName(read.bytes.toString('utf8')) !== name) continue;\n // SKILL.md is the ownership proof, so it is checked first and removed\n // last: a run that dies partway leaves the frontmatter that lets the next\n // one recognize the directory as ours.\n const shipped = SHIPPED_SKILL_FILES[name];\n const subdirs = new Set<string>();\n for (const rel of shipped) {\n if (rel === 'SKILL.md') continue;\n const file = join(skillDir, rel);\n // The directory is a prune CANDIDATE whether or not our file is still in\n // it: an operator who deleted the file by hand would otherwise be left\n // with an empty `references/` that nothing ever clears.\n subdirs.add(dirname(file));\n if (lstatSync(file, { throwIfNoEntry: false })?.isFile() !== true) continue;\n await rm(file, { force: true });\n }\n await rm(path, { force: true });\n // Only when OUR files were the only things in there. An operator file keeps\n // both itself and the directory; `rmdir` refuses a non-empty one anyway,\n // so the check and the call agree even if something lands in between.\n // Deepest first, so an emptied `references/` cannot keep its parent alive.\n for (const dir of [...subdirs].sort((a, b) => b.length - a.length)) {\n const left = await readdir(dir).catch(() => null);\n if (left !== null && left.length === 0) await rmdir(dir).catch(() => undefined);\n }\n const rest = await readdir(skillDir).catch(() => null);\n if (rest !== null && rest.length === 0) {\n await rmdir(skillDir).catch(() => undefined);\n }\n removed.push(skillDir);\n }\n }\n return removed;\n}\n\n/**\n * Drop the legacy pointer line from the files an older `install` wrote it into.\n * The line is found by its marker, never by exact text, so a drifted copy from\n * any earlier version is recognized; everything around it is preserved byte for\n * byte, because these files are the operator's own notes.\n *\n * Written through the link for the same reason the writers were: `writeFileAtomic`\n * commits with a rename, so committing at a declared path would replace a\n * dotfiles-managed symlink with a regular file and strand its target. A file we\n * cannot read, or one that is not a regular file, is skipped rather than fixed.\n */\nexport async function removeMarkerLines(homeDir: string): Promise<string[]> {\n const cleaned: string[] = [];\n for (const path of markerFiles(homeDir)) {\n const read = await readSkillFile(path);\n if (read.kind !== 'ok') continue;\n const text = read.bytes.toString('utf8');\n if (!text.split('\\n').some((l) => l.startsWith(SKILLS_MARKER))) continue;\n // ANCHORED to the start of the line, which is the only way install ever\n // wrote it. `includes` would take a whole line of the operator's own prose\n // for quoting the marker inside a sentence or a code fence.\n const kept = text.split('\\n').filter((l) => !l.startsWith(SKILLS_MARKER));\n const writeTo = await resolveThroughLink(path, 'the Tenjin pointer');\n // A file that held nothing but our line is emptied rather than deleted:\n // install created it in that case, but the operator may have pointed a\n // dotfiles link at it since, and an empty file is inert either way.\n await writeFileAtomic(writeTo, kept.join('\\n'));\n cleaned.push(path);\n }\n return cleaned;\n}\n\n/** Every file `install` has ever written the pointer line into. */\nexport function markerFiles(homeDir: string): string[] {\n return [\n join(homeDir, '.claude', 'CLAUDE.md'),\n join(homeDir, '.agents', 'AGENTS.md'),\n join(homeDir, '.codex', 'AGENTS.md'),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,SAAS,IAAI,OAAO,gBAAgB;AAC9D,SAAS,iBAAiB;AAC1B,SAAS,SAAS,YAAY;AA4FvB,IAAM,aAAgC;AAAA,EAC3C;AAAA,EACA;AACF;AAMO,IAAM,wBACX;AAGK,IAAM,gBAAgB;AAE7B,SAAS,cAAc,OAAkD;AACvE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAGA,SAAS,cAAc,OAAyB;AAC9C,MAAI,CAAC,cAAc,KAAK,EAAG,QAAO;AAClC,QAAM,WAAW,MAAM;AACvB,MAAI,CAAC,MAAM,QAAQ,QAAQ,EAAG,QAAO;AACrC,SAAO,SAAS;AAAA,IACd,CAAC,MACC,cAAc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KAAK,WAAW,GAAG;AACtC,cAAM,MAAM,QAAQ,EAAE,MAAM,MAAM,MAAS;AAAA,MAC7C;AACA,cAAQ,KAAK,QAAQ;AAAA,IACvB;AAAA,EACF;AACA,SAAO;AACT;AAaA,eAAsB,kBAAkB,SAAoC;AAC1E,QAAM,UAAoB,CAAC;AAC3B,aAAW,QAAQ,YAAY,OAAO,GAAG;AACvC,UAAM,OAAO,MAAM,cAAc,IAAI;AACrC,QAAI,KAAK,SAAS,KAAM;AACxB,UAAM,OAAO,KAAK,MAAM,SAAS,MAAM;AACvC,QAAI,CAAC,KAAK,MAAM,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,WAAW,aAAa,CAAC,EAAG;AAIhE,UAAM,OAAO,KAAK,MAAM,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,WAAW,aAAa,CAAC;AACxE,UAAM,UAAU,MAAM,mBAAmB,MAAM,oBAAoB;AAInE,UAAM,gBAAgB,SAAS,KAAK,KAAK,IAAI,CAAC;AAC9C,YAAQ,KAAK,IAAI;AAAA,EACnB;AACA,SAAO;AACT;AAGO,SAAS,YAAY,SAA2B;AACrD,SAAO;AAAA,IACL,KAAK,SAAS,WAAW,WAAW;AAAA,IACpC,KAAK,SAAS,WAAW,WAAW;AAAA,IACpC,KAAK,SAAS,UAAU,WAAW;AAAA,EACrC;AACF;","names":["path","dir"]}
@@ -1,35 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- CliError
4
- } from "./chunk-PAOVPSP6.js";
5
-
6
- // src/lib/url.ts
7
- function trimSlash(url) {
8
- return url.replace(/\/+$/, "");
9
- }
10
- function tryOriginOf(url) {
11
- let parsed;
12
- try {
13
- parsed = new URL(url);
14
- } catch {
15
- return null;
16
- }
17
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
18
- return parsed.origin;
19
- }
20
- function originOf(url) {
21
- const origin = tryOriginOf(url);
22
- if (origin === null) {
23
- throw new CliError("USAGE", `Invalid base URL: ${JSON.stringify(url)}`, {
24
- fix: "Set an absolute http(s) base URL: `tenjin config set baseUrl <url>`."
25
- });
26
- }
27
- return origin;
28
- }
29
-
30
- export {
31
- trimSlash,
32
- tryOriginOf,
33
- originOf
34
- };
35
- //# sourceMappingURL=chunk-XGZ5EVMB.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/url.ts"],"sourcesContent":["import { CliError } from './errors';\n\n/** Drop trailing slashes from a base URL so `${base}/path` never doubles a slash. */\nexport function trimSlash(url: string): string {\n return url.replace(/\\/+$/, '');\n}\n\n/**\n * The `scheme://host[:port]` of an http(s) URL, or null if it is not one.\n *\n * Non-http schemes are rejected rather than passed through, and that is the whole\n * reason this is not a one-line `new URL(url).origin`: for any non-special\n * scheme the WHATWG origin is the opaque string `\"null\"`, so `foo://tenjin.blog`\n * and `bar://evil.example` compare EQUAL. This value binds a wallet-derived\n * credential to one deployment, so an equal-comparing sentinel is exactly the\n * failure it exists to prevent — the same shape as the unparseable case, just\n * spelled differently.\n */\nexport function tryOriginOf(url: string): string | null {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;\n return parsed.origin;\n}\n\n/**\n * `tryOriginOf` for callers that cannot proceed without an origin. Throws USAGE\n * rather than returning a sentinel; anything that must survive a bad base URL\n * (diagnostics, above all) uses `tryOriginOf` and handles the null.\n */\nexport function originOf(url: string): string {\n const origin = tryOriginOf(url);\n if (origin === null) {\n throw new CliError('USAGE', `Invalid base URL: ${JSON.stringify(url)}`, {\n fix: 'Set an absolute http(s) base URL: `tenjin config set baseUrl <url>`.',\n });\n }\n return origin;\n}\n"],"mappings":";;;;;;AAGO,SAAS,UAAU,KAAqB;AAC7C,SAAO,IAAI,QAAQ,QAAQ,EAAE;AAC/B;AAaO,SAAS,YAAY,KAA4B;AACtD,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,GAAG;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,OAAO,aAAa,WAAW,OAAO,aAAa,SAAU,QAAO;AACxE,SAAO,OAAO;AAChB;AAOO,SAAS,SAAS,KAAqB;AAC5C,QAAM,SAAS,YAAY,GAAG;AAC9B,MAAI,WAAW,MAAM;AACnB,UAAM,IAAI,SAAS,SAAS,qBAAqB,KAAK,UAAU,GAAG,CAAC,IAAI;AAAA,MACtE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":[]}
@@ -1,176 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- assertOnBaseOrigin
4
- } from "./chunk-4Y53PDH6.js";
5
- import {
6
- recordSearch
7
- } from "./chunk-7NADDA2V.js";
8
- import {
9
- MAX_LIMIT,
10
- buildSearchRequest,
11
- postSearch
12
- } from "./chunk-FDUD3W5V.js";
13
- import {
14
- sanitizeForTerminal
15
- } from "./chunk-B676GPS2.js";
16
- import {
17
- resolveContextSettings
18
- } from "./chunk-PKW3H26Z.js";
19
- import {
20
- formatUsdDisplay,
21
- isPaidPrice,
22
- parseUsdToAtomic
23
- } from "./chunk-736DW4V3.js";
24
- import {
25
- CliError
26
- } from "./chunk-PAOVPSP6.js";
27
-
28
- // src/commands/search.ts
29
- async function runSearch(args, ctx, deps = {}) {
30
- const settings = await resolveContextSettings(ctx);
31
- const input = { question: args.question };
32
- if (args.maxPrice !== void 0) input.maxPrice = parseUsdToAtomic(args.maxPrice);
33
- if (args.freshWithin !== void 0) input.freshWithin = args.freshWithin;
34
- if (args.limit !== void 0) input.limit = parseLimit(args.limit);
35
- if (args.appliesTo !== void 0 && args.appliesTo.length > 0) {
36
- input.appliesTo = parseAppliesTo(args.appliesTo);
37
- }
38
- const sessionId = readSessionId(deps.env ?? process.env);
39
- const request = buildSearchRequest(input);
40
- const response = await postSearch(request, {
41
- baseUrl: settings.baseUrl,
42
- timeoutMs: ctx.flags.timeout,
43
- evalCohort: settings.evalCohort,
44
- ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
45
- });
46
- const candidates = response.candidates ?? [];
47
- for (const c of candidates) {
48
- try {
49
- assertOnBaseOrigin(c.url, settings.baseUrl, "search candidate URL");
50
- } catch (err) {
51
- throw new CliError(
52
- "CONTRACT_MISMATCH",
53
- `Search candidate ${c.resourceId} points off the configured base URL.`,
54
- { cause: err }
55
- );
56
- }
57
- }
58
- for (const b of response.browse ?? []) {
59
- try {
60
- assertOnBaseOrigin(b.url, settings.baseUrl, "browse pointer URL");
61
- } catch (err) {
62
- throw new CliError(
63
- "CONTRACT_MISMATCH",
64
- `Browse pointer ${b.resourceId} points off the configured base URL.`,
65
- { cause: err }
66
- );
67
- }
68
- }
69
- await recordSearch(ctx.dataDir, {
70
- searchId: response.searchId,
71
- at: (/* @__PURE__ */ new Date()).toISOString(),
72
- question: request.question,
73
- decision: response.decision,
74
- // A deliberate search, as opposed to one the WebSearch hook rode along with.
75
- // The Stop hook nags on the two differently, so the tag has to be written
76
- // here rather than inferred later from anything.
77
- source: "cli",
78
- // Usually absent; see readSessionId. An unstamped entry is raised in every
79
- // session, which is the safe direction for a reminder.
80
- ...sessionId !== void 0 ? { sessionId } : {},
81
- candidates: candidates.map((c) => ({
82
- resourceId: c.resourceId,
83
- url: c.url,
84
- title: c.title,
85
- price: c.price
86
- })),
87
- // The pointers stay unrecorded on purpose (see below); only how many of them
88
- // cost money, so `outcome` can tell a MISS that offered a payable browse tail
89
- // from one that offered nothing to buy. A zero-priced pointer does not count:
90
- // `read` delivers it for nothing, so there was no purchase to decline. Zero on
91
- // a CANDIDATES decision, where the contract carries no browse array and the
92
- // parser drops any that appears.
93
- paidBrowseCount: (response.browse ?? []).filter((b) => isPaidPrice(b.price) === true).length
94
- });
95
- const browse = response.browse ?? [];
96
- const browseHint = browse.length > 0 ? [
97
- `no match, ${browse.length} piece(s) you could browse: ${browse.map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`).join("; ")}`
98
- ] : [];
99
- const truncatedHint = response.truncated === true ? [
100
- request.limit < MAX_LIMIT ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)` : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`
101
- ] : [];
102
- const humanLines = response.decision === "MISS" ? [
103
- `MISS, no candidates (searchId ${response.searchId})`,
104
- ...browseHint,
105
- ...truncatedHint,
106
- publishBackLine(response.searchId)
107
- ] : [
108
- `${candidates.length} candidate(s) (searchId ${response.searchId}):`,
109
- // Dollars for the same reason the browse hint uses them: this is the
110
- // human's cue to size the spend against gates they entered in decimal
111
- // USD. The machine `candidates` array in --json keeps atomic.
112
- ...candidates.map(
113
- (c, i) => ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`
114
- ),
115
- ...truncatedHint
116
- ];
117
- const data = response.decision === "MISS" ? { ...response, publishBack: publishBackHint(response.searchId) } : response;
118
- return { data, humanLines };
119
- }
120
- function readSessionId(env) {
121
- return firstNonEmpty(env.TENJIN_SESSION_ID) ?? firstNonEmpty(env.CLAUDE_CODE_SESSION_ID);
122
- }
123
- function firstNonEmpty(raw) {
124
- if (typeof raw !== "string") return void 0;
125
- const trimmed = raw.trim();
126
- return trimmed.length > 0 ? trimmed : void 0;
127
- }
128
- function publishBackHint(searchId) {
129
- return {
130
- searchId,
131
- reason: "Nothing on the marketplace answered this. If you solve it, publish it back.",
132
- // Both arms carry the searchId, because both are commands to run verbatim and
133
- // a publish without it leaves this very loop open (see publish's --search-id).
134
- // The second arm is DECLINE, not park: nothing is saved to come back to, and
135
- // reporting the outcome is what closes the loop so it never raises again.
136
- publish: `tenjin publish <file.md> --json --search-id ${searchId}`,
137
- decline: `tenjin outcome --search-id ${searchId} --status regenerated --json`
138
- };
139
- }
140
- function publishBackLine(searchId) {
141
- return `Nobody has published this yet - if you solve it, publish it back (tenjin publish <file.md> --search-id ${searchId}); if you will not, close the loop: tenjin outcome --search-id ${searchId} --status regenerated`;
142
- }
143
- function parseLimit(raw) {
144
- const n = Number(raw);
145
- if (!Number.isInteger(n)) {
146
- throw new CliError("USAGE", `Invalid --limit: ${JSON.stringify(raw)}`, {
147
- fix: "Pass an integer between 1 and 10."
148
- });
149
- }
150
- return n;
151
- }
152
- function parseAppliesTo(pairs) {
153
- const out = {};
154
- for (const pair of pairs) {
155
- const eq = pair.indexOf("=");
156
- if (eq <= 0) {
157
- throw new CliError("USAGE", `Invalid --applies-to: ${JSON.stringify(pair)}`, {
158
- fix: "Use key=value, e.g. --applies-to products=Vercel."
159
- });
160
- }
161
- const key = pair.slice(0, eq).trim();
162
- const values = pair.slice(eq + 1).split(",").map((v) => v.trim()).filter((v) => v.length > 0);
163
- if (values.length === 0) {
164
- throw new CliError("USAGE", `--applies-to ${JSON.stringify(key)} has no values`, {
165
- fix: "Give each key at least one value, e.g. products=Vercel."
166
- });
167
- }
168
- out[key] = [...out[key] ?? [], ...values];
169
- }
170
- return out;
171
- }
172
-
173
- export {
174
- runSearch
175
- };
176
- //# sourceMappingURL=chunk-XVPQGCH4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/search.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, isPaidPrice, parseUsdToAtomic } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildSearchRequest, postSearch, MAX_LIMIT, type SearchInput } from '../lib/agent-api';\nimport { recordSearch } from '../lib/search-store';\nimport { assertOnBaseOrigin } from '../lib/resource-ref';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin search \"<question>\"`, one POST to /api/agent/search. Prints the compact\n * CANDIDATES/MISS response (spec 10) and records the searchId + candidates\n * locally so `outcome --last` and `buy <resourceId>` can use them. No wallet, no\n * signing: search is anonymous.\n *\n * The machine envelope is the server's response verbatim plus exactly one\n * CLI-owned key, `publishBack`, and only on a MISS. It carries no server data: it\n * is the local searchId and the two commands that close the loop, which is\n * information the CLI owns and the contract does not describe.\n *\n * Search is the breadth step: a candidate is a lean hit (identity, price,\n * freshness, why it matched), and the full answer card comes from `tenjin inspect`,\n * which is free. So a candidate line stays short on purpose.\n *\n * The response's `searchId` is the outcome-reporting capability for\n * POST /api/searches/<searchId>/outcomes. tenjin#463 renamed the field (from\n * `lookupId`) and tenjin#616 dropped the `/agent` prefix from the path; this\n * client follows both end to end, so nothing on the wire or in the local store\n * still speaks `lookupId` or the prefixed spelling.\n */\n\nexport interface SearchArgs {\n question: string;\n /** Decimal USD at the edge (O1); converted to atomic for the wire. */\n maxPrice?: string;\n freshWithin?: string;\n limit?: string;\n /** Raw `k=v` / `k=v1,v2` pairs from repeated --applies-to. */\n appliesTo?: string[];\n}\n\nexport interface SearchDeps {\n fetchImpl?: typeof fetch;\n /** Environment seam (TENJIN_SESSION_ID); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runSearch(\n args: SearchArgs,\n ctx: CommandContext,\n deps: SearchDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const input: SearchInput = { question: args.question };\n if (args.maxPrice !== undefined) input.maxPrice = parseUsdToAtomic(args.maxPrice);\n if (args.freshWithin !== undefined) input.freshWithin = args.freshWithin;\n if (args.limit !== undefined) input.limit = parseLimit(args.limit);\n if (args.appliesTo !== undefined && args.appliesTo.length > 0) {\n input.appliesTo = parseAppliesTo(args.appliesTo);\n }\n\n const sessionId = readSessionId(deps.env ?? process.env);\n const request = buildSearchRequest(input);\n const response = await postSearch(request, {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n evalCohort: settings.evalCohort,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const candidates = response.candidates ?? [];\n // Ingest trust boundary: a candidate url that points off the configured origin\n // would later route a wallet-signed SIWX header and payment to that host via\n // `buy <resourceId>`. Refuse the whole response as a contract violation.\n for (const c of candidates) {\n try {\n assertOnBaseOrigin(c.url, settings.baseUrl, 'search candidate URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Search candidate ${c.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n // Browse pointers are never buyable through `buy <resourceId>` (they are not\n // recorded), but their urls are still emitted into the agent's transcript, so\n // they get the same origin check rather than a weaker one.\n for (const b of response.browse ?? []) {\n try {\n assertOnBaseOrigin(b.url, settings.baseUrl, 'browse pointer URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Browse pointer ${b.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n await recordSearch(ctx.dataDir, {\n searchId: response.searchId,\n at: new Date().toISOString(),\n question: request.question,\n decision: response.decision,\n // A deliberate search, as opposed to one the WebSearch hook rode along with.\n // The Stop hook nags on the two differently, so the tag has to be written\n // here rather than inferred later from anything.\n source: 'cli',\n // Usually absent; see readSessionId. An unstamped entry is raised in every\n // session, which is the safe direction for a reminder.\n ...(sessionId !== undefined ? { sessionId } : {}),\n candidates: candidates.map((c) => ({\n resourceId: c.resourceId,\n url: c.url,\n title: c.title,\n price: c.price,\n })),\n // The pointers stay unrecorded on purpose (see below); only how many of them\n // cost money, so `outcome` can tell a MISS that offered a payable browse tail\n // from one that offered nothing to buy. A zero-priced pointer does not count:\n // `read` delivers it for nothing, so there was no purchase to decline. Zero on\n // a CANDIDATES decision, where the contract carries no browse array and the\n // parser drops any that appears.\n paidBrowseCount: (response.browse ?? []).filter((b) => isPaidPrice(b.price) === true).length,\n });\n\n // A MISS may carry up to 3 browse pointers from the broad corpus. They are\n // pointers, NOT candidates: rendered as ONE hint line with no scores and no\n // per-item detail, so a MISS still reads as a MISS and an agent is never\n // nudged to treat a browse pointer as an answer. The machine JSON keeps the\n // full `browse` array; this line is only the human tail.\n //\n // The price rides this line because a browse url IS payable: it is the read\n // endpoint that answers a 402, and `buy <url>` resolves the URL arm by origin\n // without consulting the search store, so a browse pointer can be bought even\n // though `buy <resourceId>` can never reach one. All spend gates (price cap,\n // session budget, allowlist, confirm) still run; showing the price keeps the\n // only human-visible surface from being a blind spend.\n //\n // It renders in DOLLARS, not atomic units, because the whole point of the line\n // is that a human can size the spend against the gates they set, and every gate\n // is entered in decimal USD (`--max-price 0.10`, the `maxAutoSpend` config).\n // `formatUsdDisplay` is the canonical human-copy form (always two decimals, so\n // a dime reads \"0.10\" and not \"0.1\"); the machine `browse` array in --json still\n // carries the exact atomic string, per the money-units contract in the README.\n const browse = response.browse ?? [];\n const browseHint =\n browse.length > 0\n ? [\n `no match, ${browse.length} piece(s) you could browse: ${browse\n .map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`)\n .join('; ')}`,\n ]\n : [];\n\n // `truncated` means the server's size backstop dropped candidates, either a\n // trailing few the limit had room for or a single oversized one. The response\n // ceiling GROWS with the number of candidates returned (tenjin#501), so the\n // remedy is counter-intuitive and worth stating outright: a larger --limit\n // recovers the tail, a smaller one returns strictly fewer. Only at the maximum\n // is the tail unrecoverable and narrowing the question the answer.\n //\n // The CLI knows the limit it sent, so it names the next step instead of\n // restating the rule and leaving the reader to work out which half applies.\n // The flag stays in the machine envelope (--json) untouched, where it is\n // omitted rather than false when it did not fire.\n //\n // Rendering it on a MISS too is DEFENSIVE, not wire behavior: the server only\n // ever sets the flag alongside candidates it dropped. Handling both keeps the\n // flag from going unrendered if that ever changes.\n const truncatedHint =\n response.truncated === true\n ? [\n request.limit < MAX_LIMIT\n ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)`\n : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`,\n ]\n : [];\n\n // The publish-back line rides humanLines like every other rendering, so `--json`\n // suppresses it the way that flag's own help promises. It used to go straight to\n // stderr, which no output mode gates: an agent asking for a machine envelope got\n // ~260 bytes of human prose alongside it.\n const humanLines =\n response.decision === 'MISS'\n ? [\n `MISS, no candidates (searchId ${response.searchId})`,\n ...browseHint,\n ...truncatedHint,\n publishBackLine(response.searchId),\n ]\n : [\n `${candidates.length} candidate(s) (searchId ${response.searchId}):`,\n // Dollars for the same reason the browse hint uses them: this is the\n // human's cue to size the spend against gates they entered in decimal\n // USD. The machine `candidates` array in --json keeps atomic.\n ...candidates.map(\n (c, i) =>\n ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`,\n ),\n ...truncatedHint,\n ];\n\n // The one CLI-owned field in this envelope. Everything else is the server's\n // response verbatim (spec 10), so the addition is namespaced under a key the\n // contract does not define and is present ONLY on a MISS: a MISS is the moment\n // the demand this searcher just expressed can still be met, and the searchId is\n // what ties the answer they are about to derive back to it. A CANDIDATES\n // response is byte-identical to what it was.\n const data =\n response.decision === 'MISS'\n ? { ...response, publishBack: publishBackHint(response.searchId) }\n : response;\n\n return { data, humanLines };\n}\n\n/**\n * The session to stamp this search with, so the Stop hook can tell one session's\n * open loops from a sibling's, or undefined when nothing can say.\n *\n * Two sources, in precedence order. TENJIN_SESSION_ID is the explicit operator\n * override and wins. CLAUDE_CODE_SESSION_ID is what Claude Code exports to Bash\n * tool subprocesses, which is what a `tenjin search` runs as; its value is the\n * same `session_id` the hook scripts are handed on stdin, so a CLI search and a\n * WebSearch-hook search in one session stamp identically. It is verified against\n * a live session rather than documented, hence the fallback rather than a\n * requirement: on a harness that does not export it this stays undefined, and\n * undefined is the safe answer — the hook raises an unstamped entry in every\n * session rather than in none.\n */\nfunction readSessionId(env: NodeJS.ProcessEnv): string | undefined {\n return firstNonEmpty(env.TENJIN_SESSION_ID) ?? firstNonEmpty(env.CLAUDE_CODE_SESSION_ID);\n}\n\nfunction firstNonEmpty(raw: string | undefined): string | undefined {\n if (typeof raw !== 'string') return undefined;\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/** The publish-back hint, as machine fields rather than prose to re-parse. */\nfunction publishBackHint(searchId: string): {\n searchId: string;\n reason: string;\n publish: string;\n decline: string;\n} {\n return {\n searchId,\n reason: 'Nothing on the marketplace answered this. If you solve it, publish it back.',\n // Both arms carry the searchId, because both are commands to run verbatim and\n // a publish without it leaves this very loop open (see publish's --search-id).\n // The second arm is DECLINE, not park: nothing is saved to come back to, and\n // reporting the outcome is what closes the loop so it never raises again.\n publish: `tenjin publish <file.md> --json --search-id ${searchId}`,\n decline: `tenjin outcome --search-id ${searchId} --status regenerated --json`,\n };\n}\n\n/** The same hint as one rendered line for a human. */\nfunction publishBackLine(searchId: string): string {\n return `Nobody has published this yet - if you solve it, publish it back (tenjin publish <file.md> --search-id ${searchId}); if you will not, close the loop: tenjin outcome --search-id ${searchId} --status regenerated`;\n}\n\nfunction parseLimit(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n)) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(raw)}`, {\n fix: 'Pass an integer between 1 and 10.',\n });\n }\n return n;\n}\n\n/** `products=Vercel` or `products=Vercel,Next` → { products: [\"Vercel\",\"Next\"] }. Repeated\n * keys merge their values. */\nfunction parseAppliesTo(pairs: string[]): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf('=');\n if (eq <= 0) {\n throw new CliError('USAGE', `Invalid --applies-to: ${JSON.stringify(pair)}`, {\n fix: 'Use key=value, e.g. --applies-to products=Vercel.',\n });\n }\n const key = pair.slice(0, eq).trim();\n const values = pair\n .slice(eq + 1)\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v.length > 0);\n if (values.length === 0) {\n throw new CliError('USAGE', `--applies-to ${JSON.stringify(key)} has no values`, {\n fix: 'Give each key at least one value, e.g. products=Vercel.',\n });\n }\n out[key] = [...(out[key] ?? []), ...values];\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AAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,UAAM,MAAM,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK;AACnC,UAAM,SAAS,KACZ,MAAM,KAAK,CAAC,EACZ,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAC7B,QAAI,OAAO,WAAW,GAAG;AACvB,YAAM,IAAI,SAAS,SAAS,gBAAgB,KAAK,UAAU,GAAG,CAAC,kBAAkB;AAAA,QAC/E,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,QAAI,GAAG,IAAI,CAAC,GAAI,IAAI,GAAG,KAAK,CAAC,GAAI,GAAG,MAAM;AAAA,EAC5C;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/lock.ts"],"sourcesContent":["import { mkdirSync, rmSync } from 'node:fs';\nimport { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Locks this process currently holds. Ownership starts the instant `mkdir`\n * succeeds and ends when the release has removed the directory, so there is no\n * window where a lock is on disk and unaccounted for. A removal that FAILS keeps\n * the lock owned: the directory is still on disk, no successor can claim the path\n * while it exists, and a signal-time release gets another attempt. The one place\n * ownership is dropped without a successful removal is `releaseOwnedLocks`, which\n * runs only as the process exits, where a claim held by a dying process helps\n * nobody.\n *\n * It exists because the default signal action terminates WITHOUT running\n * `finally`: without this, one Ctrl-C leaves a lock nothing will ever clean and\n * every later run of the same command times out on it.\n */\nconst owned = new Set<string>();\n\n/** Does this process hold any lock right now? */\nexport function ownsAnyLock(): boolean {\n return owned.size > 0;\n}\n\n/**\n * Synchronously attempt to release every lock this process holds. BEST EFFORT: a\n * path that refuses to be removed is left on disk and the next run's timeout names\n * it. Safe to call from a signal handler, and a no-op when this process holds\n * none, so a run merely QUEUED behind another cannot remove that other run's lock.\n */\nexport function releaseOwnedLocks(): void {\n for (const path of owned) {\n // NEVER throws. This runs inside a signal handler, and a throw there is an\n // uncaught exception: the process dies with code 1 and a stack trace instead\n // of the diagnostic and exit 130 the handler promises. One lock we could not\n // remove must not cost the report, or the exit code, or the other locks.\n try {\n rmSync(path, { recursive: true, force: true });\n } catch {\n // Left behind; the next run's timeout names the path.\n }\n }\n owned.clear();\n}\n\nexport interface FileLockOptions {\n /** Give up acquiring after this long (ms). */\n timeoutMs?: number;\n /** Poll interval between acquisition attempts (ms). */\n retryMs?: number;\n /**\n * Called when the lock could not be removed on release. The protected work\n * succeeded, so this is not a failure of the command; it is a leftover that will\n * block later runs, and the caller is the only one able to say so.\n */\n onReleaseError?: (lockPath: string, err: unknown) => void;\n}\n\nconst DEFAULTS = { timeoutMs: 5000, retryMs: 25 };\n\n/** Thrown when the lock cannot be acquired within `timeoutMs`. Carries the lock\n * path so a caller can surface the manual-recovery step in its own error contract. */\nexport class LockTimeoutError extends Error {\n readonly lockPath: string;\n constructor(lockPath: string, timeoutMs: number) {\n super(\n `Timed out waiting for lock at ${lockPath} after ${timeoutMs}ms; if no other tenjin process is running, remove that directory and retry.`,\n );\n this.name = 'LockTimeoutError';\n this.lockPath = lockPath;\n }\n}\n\n/**\n * Minimal cross-process mutex: the lock IS a directory, and mkdir is atomic, so a\n * second holder gets EEXIST and retries with backoff until `timeoutMs`, then\n * throws LockTimeoutError. There is deliberately NO auto-steal of a \"stale\" lock:\n * concurrent waiters each judging a lock stale could remove a fresh holder's\n * directory and lose its update. A crashed holder's lock is recovered by hand (the\n * timeout error names the path); the pid+acquiredAt meta exists only to make that\n * manual call diagnosable. Always released in the finally.\n *\n * ⚠ MIRRORED, MUST UPDATE TOGETHER. The generated WebSearch hook script in\n * lib/hook-scripts.ts (`withStoreLock`) reimplements this protocol byte for byte,\n * because it runs as a standalone .mjs outside the CLI and cannot import this\n * module, yet writes the same searches.json. If you change what the lock IS\n * (directory vs file), where it lives, or the no-stale-steal rule, change it\n * there too. Two writers of one file that disagree about the mutex have no mutex.\n * lib/hook-scripts.test.ts pins the two together and fails loudly on drift.\n */\nexport async function withFileLock<T>(\n lockPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const { timeoutMs, retryMs } = { ...DEFAULTS, ...opts };\n const metaPath = join(lockPath, 'meta');\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n // SYNCHRONOUS, for the same reason the release is: `await mkdir` finishes the\n // syscall before the continuation records ownership, so between the two the\n // directory is on disk and unclaimed. A signal there exits without removing\n // it and, with no stale recovery, nothing ever will. mkdirSync and the add\n // are one uninterruptible step.\n mkdirSync(lockPath);\n owned.add(lockPath); // owned from here, released only in the finally below\n break; // acquired\n } catch (err) {\n if (!isEexist(err)) throw err;\n if (Date.now() >= deadline) throw new LockTimeoutError(lockPath, timeoutMs);\n await delay(retryMs);\n }\n }\n await writeFile(metaPath, JSON.stringify({ pid: process.pid, acquiredAt: Date.now() })).catch(\n () => undefined,\n );\n try {\n return await fn();\n } finally {\n // SYNCHRONOUS, and in this order, because both are load-bearing. A signal\n // handler cannot run between two synchronous statements, so there is no instant\n // where the lock is on disk but unclaimed (a signal would exit without removing\n // it, and with no stale recovery nothing ever would) nor one where it is\n // claimed after release (a signal would remove whatever SUCCESSOR had since\n // acquired the path). An `await` here reopens the first window: `rm` yields, the\n // handler runs, sees no ownership, and leaves the directory behind.\n //\n // With no stealing, nothing else ever removes or replaces this directory, so\n // the lock here is provably the one we created — the unconditional rm is sound.\n try {\n rmSync(lockPath, { recursive: true, force: true });\n owned.delete(lockPath);\n } catch (err) {\n // KEEP ownership when the removal fails: the successor-steal risk only\n // exists once the directory is gone and someone else can take the path, so a\n // removal that failed leaves it on disk and still ours, and a signal-time\n // release gets another attempt. That only helps while THIS process lives,\n // though; once it exits normally the leftover blocks every later run, so the\n // caller is told rather than left to discover it as a timeout.\n opts.onReleaseError?.(lockPath, err);\n }\n }\n}\n\nfunction isEexist(err: unknown): boolean {\n return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'EEXI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