tenjin-cli 0.1.0-alpha.2 → 0.1.0-alpha.20

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 (215) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +161 -257
  3. package/dist/{_esm-FEASBWRP.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
  5. package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
  6. package/dist/chunk-2E6GVIRP.js +888 -0
  7. package/dist/chunk-2E6GVIRP.js.map +1 -0
  8. package/dist/chunk-2G2WLVHB.js +102 -0
  9. package/dist/chunk-2G2WLVHB.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-3BS55ANY.js +245 -0
  13. package/dist/chunk-3BS55ANY.js.map +1 -0
  14. package/dist/chunk-3KKKB2AQ.js +40 -0
  15. package/dist/chunk-3KKKB2AQ.js.map +1 -0
  16. package/dist/chunk-4AS52HUG.js +165 -0
  17. package/dist/chunk-4AS52HUG.js.map +1 -0
  18. package/dist/chunk-4M5FBWT5.js +368 -0
  19. package/dist/chunk-4M5FBWT5.js.map +1 -0
  20. package/dist/chunk-5FYKPQNX.js +1784 -0
  21. package/dist/chunk-5FYKPQNX.js.map +1 -0
  22. package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
  23. package/dist/chunk-5KD5HRAJ.js +241 -0
  24. package/dist/chunk-5KD5HRAJ.js.map +1 -0
  25. package/dist/chunk-72UHZRG6.js +231 -0
  26. package/dist/chunk-72UHZRG6.js.map +1 -0
  27. package/dist/chunk-7ACHDNJA.js +155 -0
  28. package/dist/chunk-7ACHDNJA.js.map +1 -0
  29. package/dist/chunk-7QKHZQKW.js +1680 -0
  30. package/dist/chunk-7QKHZQKW.js.map +1 -0
  31. package/dist/chunk-A36LQPHV.js +29 -0
  32. package/dist/chunk-A36LQPHV.js.map +1 -0
  33. package/dist/{chunk-UGX7YPX2.js → chunk-AWQPGIR6.js} +7 -9
  34. package/dist/{chunk-UGX7YPX2.js.map → chunk-AWQPGIR6.js.map} +1 -1
  35. package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
  36. package/dist/{chunk-XJIW7USF.js → chunk-BTX2QE2Y.js} +115 -11
  37. package/dist/chunk-BTX2QE2Y.js.map +1 -0
  38. package/dist/{chunk-OYMYCW7J.js → chunk-CCDOV45D.js} +588 -97
  39. package/dist/chunk-CCDOV45D.js.map +1 -0
  40. package/dist/chunk-CXUYCDPX.js +127 -0
  41. package/dist/chunk-CXUYCDPX.js.map +1 -0
  42. package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
  43. package/dist/chunk-HH3PDYIG.js +194 -0
  44. package/dist/chunk-HH3PDYIG.js.map +1 -0
  45. package/dist/{chunk-CYOF7ROH.js → chunk-HPWO4O6S.js} +3 -3
  46. package/dist/chunk-JLEF5WHM.js +132 -0
  47. package/dist/chunk-JLEF5WHM.js.map +1 -0
  48. package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
  49. package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
  50. package/dist/chunk-LHHMV4GU.js +27 -0
  51. package/dist/chunk-LHHMV4GU.js.map +1 -0
  52. package/dist/chunk-LI44XLMB.js +242 -0
  53. package/dist/chunk-LI44XLMB.js.map +1 -0
  54. package/dist/chunk-LN2HISWU.js +172 -0
  55. package/dist/chunk-LN2HISWU.js.map +1 -0
  56. package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
  57. package/dist/chunk-MEFB5KHA.js.map +1 -0
  58. package/dist/{chunk-NCE5NSN6.js → chunk-N35E6CM2.js} +140 -10
  59. package/dist/chunk-N35E6CM2.js.map +1 -0
  60. package/dist/chunk-NSG5TVZQ.js +447 -0
  61. package/dist/chunk-NSG5TVZQ.js.map +1 -0
  62. package/dist/chunk-O2JYBOUO.js +47 -0
  63. package/dist/chunk-O2JYBOUO.js.map +1 -0
  64. package/dist/{chunk-N62ROTMC.js → chunk-P42QX3QF.js} +14 -10
  65. package/dist/chunk-P42QX3QF.js.map +1 -0
  66. package/dist/chunk-PO4HAXAW.js +10528 -0
  67. package/dist/chunk-PO4HAXAW.js.map +1 -0
  68. package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
  69. package/dist/{chunk-S3IGX57D.js → chunk-RGVOODF4.js} +7703 -7475
  70. package/dist/chunk-RGVOODF4.js.map +1 -0
  71. package/dist/chunk-RPR2C2JO.js +112 -0
  72. package/dist/chunk-RPR2C2JO.js.map +1 -0
  73. package/dist/chunk-S2NRVRPF.js +171 -0
  74. package/dist/chunk-S2NRVRPF.js.map +1 -0
  75. package/dist/chunk-TGLKKLQG.js +11 -0
  76. package/dist/chunk-TGLKKLQG.js.map +1 -0
  77. package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
  78. package/dist/chunk-TU7XH3JJ.js +97 -0
  79. package/dist/chunk-TU7XH3JJ.js.map +1 -0
  80. package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
  81. package/dist/{chunk-Z6MFJV5Z.js → chunk-YEBNE5NW.js} +851 -500
  82. package/dist/chunk-YEBNE5NW.js.map +1 -0
  83. package/dist/chunk-YREKMJPP.js +131 -0
  84. package/dist/chunk-YREKMJPP.js.map +1 -0
  85. package/dist/{cli-4NNBEQYH.js → cli-XJQYUOHI.js} +355 -217
  86. package/dist/cli-XJQYUOHI.js.map +1 -0
  87. package/dist/config-KMJLFPSI.js +39 -0
  88. package/dist/dist-3LOO6M4U.js +2842 -0
  89. package/dist/dist-3LOO6M4U.js.map +1 -0
  90. package/dist/doctor-KMN55D7U.js +444 -0
  91. package/dist/doctor-KMN55D7U.js.map +1 -0
  92. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  93. package/dist/fund-LT6ZPGEQ.js +298 -0
  94. package/dist/fund-LT6ZPGEQ.js.map +1 -0
  95. package/dist/hook-command-U5XPEHAJ.js +1052 -0
  96. package/dist/hook-command-U5XPEHAJ.js.map +1 -0
  97. package/dist/index.js +11 -3
  98. package/dist/index.js.map +1 -1
  99. package/dist/install-MMNXJ5LM.js +61 -0
  100. package/dist/install-identity-B7FVIWML.js +27 -0
  101. package/dist/install-wallet-XMVUBCHS.js +107 -0
  102. package/dist/install-wallet-XMVUBCHS.js.map +1 -0
  103. package/dist/mcp-TUPRIPSI.js +10000 -0
  104. package/dist/mcp-TUPRIPSI.js.map +1 -0
  105. package/dist/paths-LRMWNTJP.js +51 -0
  106. package/dist/pay-XAWW3NV3.js +44 -0
  107. package/dist/redact-6W23GGJC.js +15 -0
  108. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
  109. package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
  110. package/dist/send-HESQYRKM.js +225 -0
  111. package/dist/send-HESQYRKM.js.map +1 -0
  112. package/dist/status-ANZPRZJJ.js +71 -0
  113. package/dist/status-ANZPRZJJ.js.map +1 -0
  114. package/dist/status-line-J3TUWVRQ.js +87 -0
  115. package/dist/status-line-J3TUWVRQ.js.map +1 -0
  116. package/dist/status-line-wiring-HSV7DXO5.js +29 -0
  117. package/dist/status-line-wiring-HSV7DXO5.js.map +1 -0
  118. package/dist/tenjin-daemon.mjs +20547 -0
  119. package/dist/tenjin-shim.mjs +251 -0
  120. package/dist/tenjin-vitest-reporter.mjs +49 -0
  121. package/dist/uninstall-GUU34YKP.js +165 -0
  122. package/dist/uninstall-GUU34YKP.js.map +1 -0
  123. package/dist/update-KO2NZRJ5.js +433 -0
  124. package/dist/update-KO2NZRJ5.js.map +1 -0
  125. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  126. package/dist/viemAdapter-By13KInL-X2VY6CY3.js.map +1 -0
  127. package/dist/wallet-3URC5QPK.js +33 -0
  128. package/dist/wallet-3URC5QPK.js.map +1 -0
  129. package/dist/wallet-kdf-worker.mjs +980 -0
  130. package/docs/agent-permissions.md +139 -0
  131. package/docs/safety-model.md +70 -0
  132. package/package.json +14 -9
  133. package/LICENSE +0 -21
  134. package/dist/buy-U35DQ6XM.js +0 -1598
  135. package/dist/buy-U35DQ6XM.js.map +0 -1
  136. package/dist/candidate-RLYCQMF5.js +0 -127
  137. package/dist/candidate-RLYCQMF5.js.map +0 -1
  138. package/dist/chunk-27ONARHV.js +0 -171
  139. package/dist/chunk-27ONARHV.js.map +0 -1
  140. package/dist/chunk-3OV7E5G5.js +0 -18
  141. package/dist/chunk-3OV7E5G5.js.map +0 -1
  142. package/dist/chunk-7KUW4MJD.js +0 -59
  143. package/dist/chunk-7KUW4MJD.js.map +0 -1
  144. package/dist/chunk-7PHSZKQS.js +0 -333
  145. package/dist/chunk-7PHSZKQS.js.map +0 -1
  146. package/dist/chunk-IYLHQMT5.js +0 -211
  147. package/dist/chunk-IYLHQMT5.js.map +0 -1
  148. package/dist/chunk-JPHG2JW3.js +0 -96
  149. package/dist/chunk-JPHG2JW3.js.map +0 -1
  150. package/dist/chunk-MUBUQVC3.js +0 -67
  151. package/dist/chunk-MUBUQVC3.js.map +0 -1
  152. package/dist/chunk-N62ROTMC.js.map +0 -1
  153. package/dist/chunk-NCE5NSN6.js.map +0 -1
  154. package/dist/chunk-OYMYCW7J.js.map +0 -1
  155. package/dist/chunk-QNP7H47L.js +0 -152
  156. package/dist/chunk-QNP7H47L.js.map +0 -1
  157. package/dist/chunk-RY4XKNV3.js +0 -140
  158. package/dist/chunk-RY4XKNV3.js.map +0 -1
  159. package/dist/chunk-S3IGX57D.js.map +0 -1
  160. package/dist/chunk-TFGSOPWR.js +0 -261
  161. package/dist/chunk-TFGSOPWR.js.map +0 -1
  162. package/dist/chunk-TLCMMYLY.js +0 -126
  163. package/dist/chunk-TLCMMYLY.js.map +0 -1
  164. package/dist/chunk-UO22YNY4.js +0 -69
  165. package/dist/chunk-UO22YNY4.js.map +0 -1
  166. package/dist/chunk-UPIEAMGH.js +0 -160
  167. package/dist/chunk-UPIEAMGH.js.map +0 -1
  168. package/dist/chunk-XJIW7USF.js.map +0 -1
  169. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  170. package/dist/chunk-YIYQ2ZNT.js +0 -286
  171. package/dist/chunk-YIYQ2ZNT.js.map +0 -1
  172. package/dist/chunk-YN5SHIXQ.js +0 -126
  173. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  174. package/dist/chunk-Z52RA3NC.js +0 -137
  175. package/dist/chunk-Z52RA3NC.js.map +0 -1
  176. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  177. package/dist/cli-4NNBEQYH.js.map +0 -1
  178. package/dist/config-2VSXWWHK.js +0 -21
  179. package/dist/doctor-JJPNIBYH.js +0 -20
  180. package/dist/inspect-JGYJWFDP.js +0 -96
  181. package/dist/inspect-JGYJWFDP.js.map +0 -1
  182. package/dist/install-ZQRMSRGW.js +0 -378
  183. package/dist/install-ZQRMSRGW.js.map +0 -1
  184. package/dist/lookup-WYVTOMVY.js +0 -113
  185. package/dist/lookup-WYVTOMVY.js.map +0 -1
  186. package/dist/outcome-HKKT6QIA.js +0 -66
  187. package/dist/outcome-HKKT6QIA.js.map +0 -1
  188. package/dist/publish-D76B3MBK.js +0 -1480
  189. package/dist/publish-D76B3MBK.js.map +0 -1
  190. package/dist/usdc-JIAJW4SV.js +0 -22
  191. package/dist/wallet-6QKS6UHW.js +0 -179
  192. package/dist/wallet-6QKS6UHW.js.map +0 -1
  193. package/dist/wallet-PA54CRBL.js +0 -30
  194. package/skills/tenjin/SKILL.md +0 -199
  195. package/skills/tenjin-publish/SKILL.md +0 -96
  196. package/skills/tenjin-search/SKILL.md +0 -122
  197. /package/dist/{_esm-FEASBWRP.js.map → _esm-CE7KNONL.js.map} +0 -0
  198. /package/dist/{ccip-NQXCEK2U.js.map → ccip-7RMRLAGV.js.map} +0 -0
  199. /package/dist/{ccip-XR5NE5QK.js.map → ccip-NLCSCHKI.js.map} +0 -0
  200. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
  201. /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
  202. /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
  203. /package/dist/{chunk-CYOF7ROH.js.map → chunk-HPWO4O6S.js.map} +0 -0
  204. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  205. /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
  206. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
  207. /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
  208. /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
  209. /package/dist/{config-2VSXWWHK.js.map → config-KMJLFPSI.js.map} +0 -0
  210. /package/dist/{doctor-JJPNIBYH.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  211. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → install-MMNXJ5LM.js.map} +0 -0
  212. /package/dist/{secp256k1-N3ZHU7LB.js.map → install-identity-B7FVIWML.js.map} +0 -0
  213. /package/dist/{usdc-JIAJW4SV.js.map → paths-LRMWNTJP.js.map} +0 -0
  214. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → pay-XAWW3NV3.js.map} +0 -0
  215. /package/dist/{wallet-PA54CRBL.js.map → redact-6W23GGJC.js.map} +0 -0
@@ -0,0 +1,27 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/prompt.ts
4
+ import { createInterface } from "node:readline";
5
+ function promptYesNo(prompt, opts = {}) {
6
+ const { defaultYes = false, input = process.stdin, output = process.stderr } = opts;
7
+ return new Promise((resolve) => {
8
+ const rl = createInterface({ input, output });
9
+ let settled = false;
10
+ const settle = (value) => {
11
+ if (settled) return;
12
+ settled = true;
13
+ rl.close();
14
+ resolve(value);
15
+ };
16
+ rl.once("close", () => settle(false));
17
+ rl.question(prompt, (answer) => {
18
+ const a = answer.trim().toLowerCase();
19
+ settle(a === "" ? defaultYes : a === "y" || a === "yes");
20
+ });
21
+ });
22
+ }
23
+
24
+ export {
25
+ promptYesNo
26
+ };
27
+ //# sourceMappingURL=chunk-LHHMV4GU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/prompt.ts"],"sourcesContent":["import { createInterface } from 'node:readline';\n\nexport interface PromptYesNoOptions {\n /** What an EMPTY answer means; the closing of stdin (ctrl-D) is always false. */\n defaultYes?: boolean;\n /** Injectable streams for tests; label/echo go to stderr, never stdout. */\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\n/**\n * The one y/n reader every confirm gate shares (buy, send, install). \"y\"/\"yes\"\n * (any case) is true, an empty answer follows `defaultYes` (explicit at each\n * call site), anything else is false, and stdin closing mid-prompt resolves\n * false rather than hanging. The prompt writes to stderr so stdout stays a\n * single JSON envelope.\n */\nexport function promptYesNo(prompt: string, opts: PromptYesNoOptions = {}): Promise<boolean> {\n const { defaultYes = false, input = process.stdin, output = process.stderr } = opts;\n return new Promise((resolve) => {\n const rl = createInterface({ input, output });\n let settled = false;\n const settle = (value: boolean): void => {\n if (settled) return;\n settled = true;\n rl.close();\n resolve(value);\n };\n rl.once('close', () => settle(false));\n rl.question(prompt, (answer) => {\n const a = answer.trim().toLowerCase();\n settle(a === '' ? defaultYes : a === 'y' || a === 'yes');\n });\n });\n}\n"],"mappings":";;;AAAA,SAAS,uBAAuB;AAiBzB,SAAS,YAAY,QAAgB,OAA2B,CAAC,GAAqB;AAC3F,QAAM,EAAE,aAAa,OAAO,QAAQ,QAAQ,OAAO,SAAS,QAAQ,OAAO,IAAI;AAC/E,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,KAAK,gBAAgB,EAAE,OAAO,OAAO,CAAC;AAC5C,QAAI,UAAU;AACd,UAAM,SAAS,CAAC,UAAyB;AACvC,UAAI,QAAS;AACb,gBAAU;AACV,SAAG,MAAM;AACT,cAAQ,KAAK;AAAA,IACf;AACA,OAAG,KAAK,SAAS,MAAM,OAAO,KAAK,CAAC;AACpC,OAAG,SAAS,QAAQ,CAAC,WAAW;AAC9B,YAAM,IAAI,OAAO,KAAK,EAAE,YAAY;AACpC,aAAO,MAAM,KAAK,aAAa,MAAM,OAAO,MAAM,KAAK;AAAA,IACzD,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
@@ -0,0 +1,242 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ getUsdcBalance
4
+ } from "./chunk-BTX2QE2Y.js";
5
+ import {
6
+ commitLocalWallet,
7
+ createLocalWallet,
8
+ describeWallet,
9
+ parkOutgoingWallet,
10
+ prepareLocalWallet,
11
+ resolvePassphraseForCreate,
12
+ resolveWalletProvider,
13
+ restoreParkedWallet,
14
+ verifyAndPreserveOutgoingWallet,
15
+ walletExistsError,
16
+ walletFileExists
17
+ } from "./chunk-YEBNE5NW.js";
18
+ import {
19
+ LockTimeoutError,
20
+ withFileLock
21
+ } from "./chunk-MEFB5KHA.js";
22
+ import {
23
+ toMoney
24
+ } from "./chunk-O2JYBOUO.js";
25
+ import {
26
+ loadRawConfig,
27
+ resolveSettings
28
+ } from "./chunk-CCDOV45D.js";
29
+ import {
30
+ CliError
31
+ } from "./chunk-JLEF5WHM.js";
32
+ import {
33
+ walletPath
34
+ } from "./chunk-TU7XH3JJ.js";
35
+
36
+ // src/commands/wallet.ts
37
+ import { mkdir } from "node:fs/promises";
38
+ import { join } from "node:path";
39
+ var FUNDING_LINE = "Fund it with `tenjin wallet fund` (card via Coinbase), or send USDC on Base. $5 covers ~50 typical resources.";
40
+ var KEY_STORAGE = "encrypted (keystore v3, scrypt)";
41
+ var isWindows = process.platform === "win32";
42
+ async function runWalletCreate(ctx, opts = {}) {
43
+ const {
44
+ address,
45
+ walletPath: path,
46
+ source,
47
+ replaced
48
+ } = await createWalletLocked(ctx.dataDir, opts);
49
+ const warnings = custodyWarnings();
50
+ return {
51
+ data: {
52
+ address,
53
+ walletPath: path,
54
+ provider: "local",
55
+ policyEnforcement: "client-only",
56
+ keyStorage: KEY_STORAGE,
57
+ passphraseSource: source,
58
+ ...replaced !== void 0 ? {
59
+ replaced: {
60
+ address: replaced.address,
61
+ archivedWalletPath: replaced.archivedPath,
62
+ passphrasePreserved: replaced.passphraseLocation,
63
+ ...replaced.unarchivedReason !== void 0 ? { unarchivedReason: replaced.unarchivedReason } : {}
64
+ }
65
+ } : {},
66
+ warnings
67
+ },
68
+ humanLines: [
69
+ `Wallet created: ${address}`,
70
+ `Key stored ${KEY_STORAGE}.`,
71
+ passphraseNote(source, address),
72
+ ...replaced !== void 0 ? replacedNote(replaced, path) : [],
73
+ FUNDING_LINE,
74
+ ...warnings
75
+ ]
76
+ };
77
+ }
78
+ function replacedNote(replaced, activeWalletPath) {
79
+ const passphraseLine = replaced.passphraseLocation === "store" ? `its passphrase is preserved in the OS credential store (service tenjin-cli, account ${replaced.account}).` : replaced.passphraseLocation === "env" ? "its passphrase is TENJIN_WALLET_PASSPHRASE \u2014 keep that value." : replaced.unarchivedReason === "rejected-characters" ? "its passphrase was NOT archived: the macOS keychain writer only stores machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it." : replaced.unarchivedReason === "no-store" ? "its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it." : "its passphrase was NOT archived: the OS credential store write failed. It exists only where you keep it.";
80
+ return [
81
+ `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,
82
+ `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,
83
+ `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \`mv ${replaced.archivedPath} ${activeWalletPath}\`.`
84
+ ];
85
+ }
86
+ async function createWalletLocked(dir, opts) {
87
+ await mkdir(dir, { recursive: true, mode: 448 });
88
+ const lockPath = join(dir, "wallet.create.lock");
89
+ try {
90
+ return await withFileLock(lockPath, async () => {
91
+ const env = opts.env ?? process.env;
92
+ let source = "env";
93
+ const passphraseFor = async (forAddress) => {
94
+ const resolved = await resolvePassphraseForCreate(
95
+ { env, dir, ...opts.passphrase },
96
+ forAddress
97
+ );
98
+ source = resolved.source;
99
+ return resolved.passphrase;
100
+ };
101
+ if (!await walletFileExists(dir)) {
102
+ const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);
103
+ return { address, walletPath: path, source };
104
+ }
105
+ if (opts.replace !== true) throw walletExistsError(dir);
106
+ const preserved = await verifyAndPreserveOutgoingWallet({
107
+ dir,
108
+ env,
109
+ ...opts.passphrase !== void 0 ? { passphrase: opts.passphrase } : {}
110
+ });
111
+ const prepared = await prepareLocalWallet(passphraseFor);
112
+ const archivedPath = await parkOutgoingWallet(dir, preserved.account);
113
+ try {
114
+ const { address, walletPath: path } = await commitLocalWallet(dir, prepared);
115
+ return { address, walletPath: path, source, replaced: { ...preserved, archivedPath } };
116
+ } catch (err) {
117
+ try {
118
+ await restoreParkedWallet(dir, archivedPath);
119
+ } catch (restoreErr) {
120
+ throw new CliError(
121
+ "INTERNAL",
122
+ "Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.",
123
+ {
124
+ fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it \u2014 move it aside first. Then restore with \`mv ${archivedPath} ${walletPath(dir)}\`.`,
125
+ cause: restoreErr
126
+ }
127
+ );
128
+ }
129
+ throw new CliError(
130
+ "INTERNAL",
131
+ "Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.",
132
+ {
133
+ fix: "Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.",
134
+ cause: err
135
+ }
136
+ );
137
+ }
138
+ });
139
+ } catch (err) {
140
+ if (err instanceof LockTimeoutError) {
141
+ throw new CliError("INTERNAL", err.message, {
142
+ fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,
143
+ cause: err
144
+ });
145
+ }
146
+ throw err;
147
+ }
148
+ }
149
+ function passphraseNote(source, address) {
150
+ const account = address.toLowerCase();
151
+ switch (source) {
152
+ case "keychain":
153
+ return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;
154
+ case "dpapi":
155
+ return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;
156
+ case "secret-service":
157
+ return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;
158
+ case "env":
159
+ return "Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.";
160
+ case "prompt":
161
+ return "Remember your passphrase: it is required to sign and cannot be recovered.";
162
+ }
163
+ }
164
+ async function runWalletShow(ctx, opts = {}) {
165
+ const provider = resolveWalletProvider(ctx, opts);
166
+ const desc = await describeWallet(provider);
167
+ const {
168
+ walletPath: path,
169
+ keyStorage,
170
+ passphraseSource,
171
+ archivedWallets,
172
+ warnings
173
+ } = await provider.diagnostics();
174
+ const humanLines = [`Address: ${desc.address}`, `Key source: ${desc.credentialSource}`];
175
+ if (keyStorage !== void 0) humanLines.push(`Key storage: ${keyStorage}`);
176
+ if (passphraseSource !== void 0) humanLines.push(`Passphrase: ${passphraseSource}`);
177
+ if (archivedWallets !== void 0 && archivedWallets.length > 0) {
178
+ humanLines.push(
179
+ `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(", ")}`
180
+ );
181
+ }
182
+ humanLines.push(...warnings);
183
+ return {
184
+ data: {
185
+ address: desc.address,
186
+ provider: desc.provider,
187
+ credentialSource: desc.credentialSource,
188
+ policyEnforcement: desc.policyEnforcement,
189
+ ...path !== void 0 ? { walletPath: path } : {},
190
+ ...keyStorage !== void 0 ? { keyStorage } : {},
191
+ ...passphraseSource !== void 0 ? { passphraseSource } : {},
192
+ ...archivedWallets !== void 0 && archivedWallets.length > 0 ? { archivedWallets } : {},
193
+ warnings
194
+ },
195
+ humanLines
196
+ };
197
+ }
198
+ async function runWalletBalance(ctx, opts = {}) {
199
+ const provider = resolveWalletProvider(ctx, opts);
200
+ const desc = await describeWallet(provider);
201
+ const config = await loadRawConfig(ctx.dataDir);
202
+ const rpcUrl = resolveSettings({
203
+ config,
204
+ flags: { baseUrl: ctx.flags.baseUrl },
205
+ env: process.env
206
+ }).rpcUrl.value;
207
+ let atomic;
208
+ try {
209
+ atomic = await getUsdcBalance(desc.address, rpcUrl);
210
+ } catch (err) {
211
+ throw new CliError("RPC_ERROR", `Could not read the USDC balance from ${rpcUrl}.`, {
212
+ fix: "Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.",
213
+ cause: err
214
+ });
215
+ }
216
+ const balance = toMoney(atomic.toString());
217
+ return {
218
+ data: { address: desc.address, balance },
219
+ humanLines: [`Balance: ${balance.usd} USDC on Base`]
220
+ };
221
+ }
222
+ function custodyWarnings() {
223
+ const warnings = [];
224
+ if (hasEnvKey()) {
225
+ warnings.push("TENJIN_WALLET_KEY is set and shadows this file at runtime.");
226
+ }
227
+ if (isWindows) {
228
+ warnings.push("File permissions are not enforced on Windows; the key file is not restricted.");
229
+ }
230
+ return warnings;
231
+ }
232
+ function hasEnvKey() {
233
+ const envKey = process.env.TENJIN_WALLET_KEY;
234
+ return envKey !== void 0 && envKey.length > 0;
235
+ }
236
+
237
+ export {
238
+ runWalletCreate,
239
+ runWalletShow,
240
+ runWalletBalance
241
+ };
242
+ //# sourceMappingURL=chunk-LI44XLMB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/wallet.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { walletPath } from '../lib/paths';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { toMoney } from '../lib/money';\nimport { getUsdcBalance } from '../lib/usdc';\nimport {\n commitLocalWallet,\n createLocalWallet,\n describeWallet,\n parkOutgoingWallet,\n prepareLocalWallet,\n resolveWalletProvider,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n type ArchivedWalletInfo,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { walletExistsError, walletFileExists } from '../lib/wallet/store';\nimport { resolvePassphraseForCreate, type PassphraseSource } from '../lib/wallet/passphrase';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst FUNDING_LINE =\n 'Fund it with `tenjin wallet fund` (card via Coinbase), or send USDC on Base. $5 covers ~50 typical resources.';\nconst KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\nconst isWindows = process.platform === 'win32';\n\nexport interface WalletCreateOptions {\n /**\n * Explicitly replace the existing active wallet (mirrors the `--yes`-style\n * explicit-flag precedent): the outgoing wallet is ARCHIVED — passphrase\n * verified against its keystore and preserved under its own address, keystore\n * parked beside the new one — never destroyed. Without it, create refuses\n * when a wallet exists. There is always exactly ONE active wallet.\n */\n replace?: boolean;\n /** Test seam for passphrase resolution (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n /**\n * The environment TENJIN_WALLET_PASSPHRASE is read from; defaults to\n * process.env. A seam rather than a global read so a caller (and above all a\n * test) can settle the passphrase source WITHOUT mutating the real process\n * environment, which under a parallel runner leaks across whole test files.\n */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const {\n address,\n walletPath: path,\n source,\n replaced,\n } = await createWalletLocked(ctx.dataDir, opts);\n\n const warnings = custodyWarnings();\n return {\n data: {\n address,\n walletPath: path,\n provider: 'local',\n policyEnforcement: 'client-only',\n keyStorage: KEY_STORAGE,\n passphraseSource: source,\n ...(replaced !== undefined\n ? {\n replaced: {\n address: replaced.address,\n archivedWalletPath: replaced.archivedPath,\n passphrasePreserved: replaced.passphraseLocation,\n ...(replaced.unarchivedReason !== undefined\n ? { unarchivedReason: replaced.unarchivedReason }\n : {}),\n },\n }\n : {}),\n warnings,\n },\n humanLines: [\n `Wallet created: ${address}`,\n `Key stored ${KEY_STORAGE}.`,\n passphraseNote(source, address),\n ...(replaced !== undefined ? replacedNote(replaced, path) : []),\n FUNDING_LINE,\n ...warnings,\n ],\n };\n}\n\n/** Where the outgoing wallet's funds live, why they remain reachable, and how to restore it. */\nfunction replacedNote(replaced: ArchivedWalletInfo, activeWalletPath: string): string[] {\n const passphraseLine =\n replaced.passphraseLocation === 'store'\n ? `its passphrase is preserved in the OS credential store (service tenjin-cli, account ${replaced.account}).`\n : replaced.passphraseLocation === 'env'\n ? 'its passphrase is TENJIN_WALLET_PASSPHRASE — keep that value.'\n : replaced.unarchivedReason === 'rejected-characters'\n ? 'its passphrase was NOT archived: the macOS keychain writer only stores machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it.'\n : replaced.unarchivedReason === 'no-store'\n ? 'its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it.'\n : 'its passphrase was NOT archived: the OS credential store write failed. It exists only where you keep it.';\n return [\n `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,\n `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,\n `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \\`mv ${replaced.archivedPath} ${activeWalletPath}\\`.`,\n ];\n}\n\n/**\n * Run the whole create critical section under a cross-process file lock: the\n * existence pre-check, the passphrase generate-and-store, and the no-clobber\n * write. Without the lock these interleave across two concurrent creates — each\n * generates a distinct passphrase and persists it to the OS store BEFORE the\n * exclusive file write, so a different process could win the file while this\n * one's per-address entry names a wallet that never landed. Serializing means\n * the loser blocks until the winner commits, then trips the exists check and\n * exits WALLET_EXISTS having never generated or stored a passphrase. The\n * store-before-write ordering stays (it still guards the single-process crash\n * window), and the exclusive write stays the final authority.\n *\n * The passphrase is resolved inside the prepare step's address callback so the\n * OS-store entry is keyed to the new wallet's own address (issue #32).\n *\n * `--replace` ordering closes the no-active-wallet window: verify-and-preserve\n * the outgoing wallet (no file moves), fully PREPARE the replacement (key,\n * stored passphrase, encrypted keystore — every fallible step) while the old\n * wallet is still active, and only then park the old keystore and commit the\n * new one. A commit failure rolls the park back, so at every exit either the\n * old or the new wallet is the active one.\n */\nasync function createWalletLocked(\n dir: string,\n opts: WalletCreateOptions,\n): Promise<{\n address: string;\n walletPath: string;\n source: PassphraseSource;\n replaced?: ArchivedWalletInfo;\n}> {\n // Ensure the data dir exists so the lock's own mkdir has a parent on a fresh\n // install; the exclusive wallet write below re-ensures it at 0700 regardless.\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = join(dir, 'wallet.create.lock');\n try {\n return await withFileLock(lockPath, async () => {\n const env = opts.env ?? process.env;\n let source: PassphraseSource = 'env';\n const passphraseFor = async (forAddress: string): Promise<string> => {\n const resolved = await resolvePassphraseForCreate(\n { env, dir, ...opts.passphrase },\n forAddress,\n );\n source = resolved.source;\n return resolved.passphrase;\n };\n\n if (!(await walletFileExists(dir))) {\n const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);\n return { address, walletPath: path, source };\n }\n\n if (opts.replace !== true) throw walletExistsError(dir);\n const preserved = await verifyAndPreserveOutgoingWallet({\n dir,\n env,\n ...(opts.passphrase !== undefined ? { passphrase: opts.passphrase } : {}),\n });\n const prepared = await prepareLocalWallet(passphraseFor);\n const archivedPath = await parkOutgoingWallet(dir, preserved.account);\n try {\n const { address, walletPath: path } = await commitLocalWallet(dir, prepared);\n return { address, walletPath: path, source, replaced: { ...preserved, archivedPath } };\n } catch (err) {\n try {\n await restoreParkedWallet(dir, archivedPath);\n } catch (restoreErr) {\n // The no-clobber restore also refuses when a wallet.json appeared out\n // of band (commit EEXIST) — never overwrite it; name both files.\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.',\n {\n fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it — move it aside first. Then restore with \\`mv ${archivedPath} ${walletPath(dir)}\\`.`,\n cause: restoreErr,\n },\n );\n }\n // Old wallet restored as the active one; say so rather than surfacing a\n // raw fs error (or a WALLET_EXISTS whose fix suggests re-running --replace).\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.',\n {\n fix: 'Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.',\n cause: err,\n },\n );\n }\n });\n } catch (err) {\n // A lock timeout is not the user's error; surface it as INTERNAL with the one\n // manual step (there is no auto-steal), keeping the JSON error contract. Every\n // other error — notably the loser's WALLET_EXISTS — propagates unchanged.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\n/** Where the encryption passphrase lives, and what the user must remember. */\nfunction passphraseNote(source: PassphraseSource, address: string): string {\n const account = address.toLowerCase();\n switch (source) {\n case 'keychain':\n return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'dpapi':\n return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;\n case 'secret-service':\n return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'env':\n return 'Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.';\n case 'prompt':\n return 'Remember your passphrase: it is required to sign and cannot be recovered.';\n }\n}\n\nexport async function runWalletShow(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n // Diagnostics are the provider's own: a remote provider reports no local file\n // path or perms warning, so `show` never contaminates a remote wallet's output\n // with a stale local wallet.json's state. keyStorage/passphraseSource are the\n // custody posture reported without decrypting or requiring a passphrase.\n const {\n walletPath: path,\n keyStorage,\n passphraseSource,\n archivedWallets,\n warnings,\n } = await provider.diagnostics();\n\n const humanLines = [`Address: ${desc.address}`, `Key source: ${desc.credentialSource}`];\n if (keyStorage !== undefined) humanLines.push(`Key storage: ${keyStorage}`);\n if (passphraseSource !== undefined) humanLines.push(`Passphrase: ${passphraseSource}`);\n if (archivedWallets !== undefined && archivedWallets.length > 0) {\n // A recovery hint, not a wallet switcher: exactly one wallet is ever active.\n humanLines.push(\n `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(', ')}`,\n );\n }\n humanLines.push(...warnings);\n\n return {\n data: {\n address: desc.address,\n provider: desc.provider,\n credentialSource: desc.credentialSource,\n policyEnforcement: desc.policyEnforcement,\n ...(path !== undefined ? { walletPath: path } : {}),\n ...(keyStorage !== undefined ? { keyStorage } : {}),\n ...(passphraseSource !== undefined ? { passphraseSource } : {}),\n ...(archivedWallets !== undefined && archivedWallets.length > 0 ? { archivedWallets } : {}),\n warnings,\n },\n humanLines,\n };\n}\n\nexport async function runWalletBalance(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n\n const config = await loadRawConfig(ctx.dataDir);\n const rpcUrl = resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n }).rpcUrl.value;\n\n let atomic: bigint;\n try {\n atomic = await getUsdcBalance(desc.address, rpcUrl);\n } catch (err) {\n throw new CliError('RPC_ERROR', `Could not read the USDC balance from ${rpcUrl}.`, {\n fix: 'Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.',\n cause: err,\n });\n }\n\n const balance = toMoney(atomic.toString());\n return {\n data: { address: desc.address, balance },\n humanLines: [`Balance: ${balance.usd} USDC on Base`],\n };\n}\n\nfunction custodyWarnings(): string[] {\n const warnings: string[] = [];\n if (hasEnvKey()) {\n warnings.push('TENJIN_WALLET_KEY is set and shadows this file at runtime.');\n }\n if (isWindows) {\n warnings.push('File permissions are not enforced on Windows; the key file is not restricted.');\n }\n return warnings;\n}\n\nfunction hasEnvKey(): boolean {\n const envKey = process.env.TENJIN_WALLET_KEY;\n return envKey !== undefined && envKey.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,YAAY;AAwBrB,IAAM,eACJ;AACF,IAAM,cAAc;AACpB,IAAM,YAAY,QAAQ,aAAa;AAsBvC,eAAsB,gBACpB,KACA,OAA4B,CAAC,GACL;AACxB,QAAM;AAAA,IACJ;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,EACF,IAAI,MAAM,mBAAmB,IAAI,SAAS,IAAI;AAE9C,QAAM,WAAW,gBAAgB;AACjC,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,MACA,YAAY;AAAA,MACZ,UAAU;AAAA,MACV,mBAAmB;AAAA,MACnB,YAAY;AAAA,MACZ,kBAAkB;AAAA,MAClB,GAAI,aAAa,SACb;AAAA,QACE,UAAU;AAAA,UACR,SAAS,SAAS;AAAA,UAClB,oBAAoB,SAAS;AAAA,UAC7B,qBAAqB,SAAS;AAAA,UAC9B,GAAI,SAAS,qBAAqB,SAC9B,EAAE,kBAAkB,SAAS,iBAAiB,IAC9C,CAAC;AAAA,QACP;AAAA,MACF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;AAE1C,QAAM,SAAS,MAAM,cAAc,IAAI,OAAO;AAC9C,QAAM,SAAS,gBAAgB;AAAA,IAC7B;AAAA,IACA,OAAO,EAAE,SAAS,IAAI,MAAM,QAAQ;AAAA,IACpC,KAAK,QAAQ;AAAA,EACf,CAAC,EAAE,OAAO;AAEV,MAAI;AACJ,MAAI;AACF,aAAS,MAAM,eAAe,KAAK,SAAS,MAAM;AAAA,EACpD,SAAS,KAAK;AACZ,UAAM,IAAI,SAAS,aAAa,wCAAwC,MAAM,KAAK;AAAA,MACjF,KAAK;AAAA,MACL,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AAEA,QAAM,UAAU,QAAQ,OAAO,SAAS,CAAC;AACzC,SAAO;AAAA,IACL,MAAM,EAAE,SAAS,KAAK,SAAS,QAAQ;AAAA,IACvC,YAAY,CAAC,YAAY,QAAQ,GAAG,eAAe;AAAA,EACrD;AACF;AAEA,SAAS,kBAA4B;AACnC,QAAM,WAAqB,CAAC;AAC5B,MAAI,UAAU,GAAG;AACf,aAAS,KAAK,4DAA4D;AAAA,EAC5E;AACA,MAAI,WAAW;AACb,aAAS,KAAK,+EAA+E;AAAA,EAC/F;AACA,SAAO;AACT;AAEA,SAAS,YAAqB;AAC5B,QAAM,SAAS,QAAQ,IAAI;AAC3B,SAAO,WAAW,UAAa,OAAO,SAAS;AACjD;","names":[]}
@@ -0,0 +1,172 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ inspectHooksFile
4
+ } from "./chunk-5FYKPQNX.js";
5
+ import {
6
+ CliError,
7
+ writeFileAtomic
8
+ } from "./chunk-JLEF5WHM.js";
9
+
10
+ // src/router/status-line-wiring.ts
11
+ import { readFile, stat } from "node:fs/promises";
12
+ var STATUS_LINE_COMMAND = "tenjin status-line";
13
+ var STATUS_LINE_REFRESH_SECONDS = 1;
14
+ var OUR_MARKER = STATUS_LINE_COMMAND;
15
+ var MODES = ["own", "compose", "skip"];
16
+ function statusLineMode(value) {
17
+ const mode = MODES.find((known) => known === value);
18
+ if (mode === void 0) {
19
+ throw new CliError("USAGE", `--status-line takes ${MODES.join(", ")}, not "${value}".`, {
20
+ fix: "Run `tenjin install --status-line own`."
21
+ });
22
+ }
23
+ return mode;
24
+ }
25
+ function classifyStatusLine(value) {
26
+ if (value === null || value === void 0) return "absent";
27
+ const command = typeof value === "string" ? value : typeof value === "object" && !Array.isArray(value) ? value.command : void 0;
28
+ if (typeof command !== "string" || command.trim().length === 0) return "foreign";
29
+ if (command.trim() === OUR_MARKER) return "ours";
30
+ return command.includes(OUR_MARKER) ? "composed" : "foreign";
31
+ }
32
+ function ours() {
33
+ return {
34
+ type: "command",
35
+ command: STATUS_LINE_COMMAND,
36
+ refreshInterval: STATUS_LINE_REFRESH_SECONDS
37
+ };
38
+ }
39
+ var shQuote = (value) => `'${value.replaceAll("'", String.raw`'\''`)}'`;
40
+ var shUnquote = (value) => value.replaceAll(String.raw`'\''`, "'");
41
+ function composedScript(existing) {
42
+ return [
43
+ "event=$(cat)",
44
+ `yours=$(printf %s "$event" | ${existing})`,
45
+ `tenjin=$(printf %s "$event" | ${STATUS_LINE_COMMAND})`,
46
+ 'printf %s "$yours${tenjin:+ \xB7 $tenjin}"'
47
+ ].join("; ");
48
+ }
49
+ function decomposeCommand(command) {
50
+ const trimmed = command.trim();
51
+ if (!trimmed.startsWith("sh -c '") || !trimmed.endsWith("'")) return null;
52
+ const script = shUnquote(trimmed.slice("sh -c '".length, -1));
53
+ const prefix = 'event=$(cat); yours=$(printf %s "$event" | ';
54
+ if (!script.startsWith(prefix)) return null;
55
+ const rest = script.slice(prefix.length);
56
+ const suffix = `); tenjin=$(printf %s "$event" | ${STATUS_LINE_COMMAND}); printf %s "$yours\${tenjin:+ \xB7 $tenjin}"`;
57
+ if (!rest.endsWith(suffix)) return null;
58
+ const existing = rest.slice(0, -suffix.length);
59
+ return existing.length > 0 && composedScript(existing) === script ? existing : null;
60
+ }
61
+ function composeCommand(existing) {
62
+ return `sh -c ${shQuote(composedScript(existing))}`;
63
+ }
64
+ function commandOf(value) {
65
+ const command = typeof value === "string" ? value : typeof value === "object" && value !== null && !Array.isArray(value) ? value.command : void 0;
66
+ return typeof command === "string" && command.trim().length > 0 ? command.trim() : void 0;
67
+ }
68
+ function composeFor(value) {
69
+ const command = commandOf(value);
70
+ return command === void 0 ? void 0 : composeCommand(command);
71
+ }
72
+ async function ensureStatusLine(settingsPath, opts = {}) {
73
+ const found = await inspectHooksFile(settingsPath);
74
+ if ("refusal" in found) {
75
+ return { path: settingsPath, state: "absent", wrote: false, warning: found.refusal.reason };
76
+ }
77
+ const { path, settings } = found;
78
+ const current = settings.statusLine;
79
+ const state = classifyStatusLine(current);
80
+ if (opts.mode === "skip") {
81
+ return { path, state, wrote: false, ...state === "foreign" ? kept(current) : {} };
82
+ }
83
+ if (opts.mode === "compose") {
84
+ const composed = composeFor(current);
85
+ if (composed === void 0) return writeStatusLine(found, ours(), "ours");
86
+ const base = typeof current === "object" && current !== null && !Array.isArray(current) ? current : ours();
87
+ return state === "composed" ? { path, state, wrote: false, command: composed } : writeStatusLine(found, { ...base, command: composed }, "composed");
88
+ }
89
+ if (state === "foreign") {
90
+ return { path, state, wrote: false, ...kept(current) };
91
+ }
92
+ if (state === "composed") return { path, state, wrote: false };
93
+ if (state === "absent" && opts.refreshOnly === true) {
94
+ return { path, state, wrote: false };
95
+ }
96
+ return writeStatusLine(found, ours(), "ours");
97
+ }
98
+ async function removeStatusLine(settingsPath) {
99
+ const found = await inspectHooksFile(settingsPath);
100
+ if ("refusal" in found) {
101
+ return { path: settingsPath, state: "absent", wrote: false, warning: found.refusal.reason };
102
+ }
103
+ const { path, settings } = found;
104
+ const current = settings.statusLine;
105
+ const state = classifyStatusLine(current);
106
+ if (state === "ours") return writeStatusLine(found, void 0, "absent");
107
+ if (state === "composed") {
108
+ const command = commandOf(current);
109
+ const original = command === void 0 ? null : decomposeCommand(command);
110
+ if (original === null) return { path, state, wrote: false };
111
+ const kept2 = { ...current, command: original };
112
+ return writeStatusLine(found, kept2, "foreign");
113
+ }
114
+ return { path, state, wrote: false };
115
+ }
116
+ async function inspectStatusLine(settingsPath) {
117
+ const found = await inspectHooksFile(settingsPath);
118
+ if ("refusal" in found) {
119
+ return { path: settingsPath, state: "absent", warning: found.refusal.reason };
120
+ }
121
+ return { path: found.path, state: classifyStatusLine(found.settings.statusLine) };
122
+ }
123
+ function kept(current) {
124
+ const compose = composeFor(current);
125
+ return compose === void 0 ? {} : { compose };
126
+ }
127
+ async function writeStatusLine(found, value, state) {
128
+ const { path, raw, settings } = found;
129
+ const next = { ...settings };
130
+ if (value === void 0) delete next.statusLine;
131
+ else next.statusLine = value;
132
+ const body = `${JSON.stringify(next, null, 2)}
133
+ `;
134
+ const result = {
135
+ path,
136
+ state,
137
+ wrote: false,
138
+ ...typeof value?.command === "string" ? { command: value.command } : {}
139
+ };
140
+ if (body === raw) return result;
141
+ const mode = await stat(path).then((s) => ({ mode: s.mode & 511 })).catch(() => ({}));
142
+ if (raw !== null && await readFile(path, "utf8").catch(() => null) !== raw) {
143
+ return {
144
+ ...result,
145
+ state: classifyStatusLine(settings.statusLine),
146
+ warning: "changed-since-read"
147
+ };
148
+ }
149
+ try {
150
+ await writeFileAtomic(path, body, mode);
151
+ } catch (err) {
152
+ return {
153
+ ...result,
154
+ state: classifyStatusLine(settings.statusLine),
155
+ warning: err instanceof Error ? err.message : String(err)
156
+ };
157
+ }
158
+ return { ...result, wrote: true };
159
+ }
160
+
161
+ export {
162
+ STATUS_LINE_COMMAND,
163
+ STATUS_LINE_REFRESH_SECONDS,
164
+ statusLineMode,
165
+ classifyStatusLine,
166
+ decomposeCommand,
167
+ composeCommand,
168
+ ensureStatusLine,
169
+ removeStatusLine,
170
+ inspectStatusLine
171
+ };
172
+ //# sourceMappingURL=chunk-LN2HISWU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/status-line-wiring.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { CliError } from '../lib/errors';\nimport { inspectHooksFile } from '../lib/harness-hooks';\n\n/**\n * The `statusLine` key in Claude Code's settings file: the one setting the live\n * footer needs, and the one piece of harness configuration a person is most\n * likely to have already set for themselves.\n *\n * SO IT IS NEVER REPLACED. An existing status line that is not ours is left\n * exactly as it is, and `install` prints the composition line instead;\n * `--status-line compose` writes that line only because it was asked for by\n * name. Writing over it and saying so in the output destroys a configuration\n * this CLI did not create.\n *\n * OWNERSHIP IS ONE MARKER, the command naming `tenjin status-line`, used by\n * `install`, `install --refresh`, `uninstall` and `doctor` alike, so the four\n * can never disagree about which status line is Tenjin's.\n */\n\n/** The command `install` registers, in the shape the hook entries use: a plain\n * command line on PATH, with no path into this build's dist directory. */\nexport const STATUS_LINE_COMMAND = 'tenjin status-line';\n/** Claude Code re-runs the command on this interval, in seconds. */\nexport const STATUS_LINE_REFRESH_SECONDS = 1;\n/** The marker that makes a status line ours, composed or not. */\nconst OUR_MARKER = STATUS_LINE_COMMAND;\n\n/** What the user asked for, when they asked. Absent means the default path. */\nexport type StatusLineMode = 'own' | 'compose' | 'skip';\n\nconst MODES: readonly StatusLineMode[] = ['own', 'compose', 'skip'];\n\n/** `--status-line <mode>`, refused rather than guessed at. */\nexport function statusLineMode(value: string): StatusLineMode {\n const mode = MODES.find((known) => known === value);\n if (mode === undefined) {\n throw new CliError('USAGE', `--status-line takes ${MODES.join(', ')}, not \"${value}\".`, {\n fix: 'Run `tenjin install --status-line own`.',\n });\n }\n return mode;\n}\n\n/**\n * What is in the file: ours alone, ours appended to someone else's, someone\n * else's alone, or nothing.\n */\nexport type StatusLineState = 'ours' | 'composed' | 'foreign' | 'absent';\n\nexport interface StatusLineResult {\n path: string;\n state: StatusLineState;\n /** True when this run changed the file. */\n wrote: boolean;\n /** The command now registered, when one of ours is. */\n command?: string;\n /** The exact command to set by hand, printed when a foreign line is kept. */\n compose?: string;\n /** Why nothing was written, for a file this run would not touch. */\n warning?: string;\n}\n\nexport function classifyStatusLine(value: unknown): StatusLineState {\n if (value === null || value === undefined) return 'absent';\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n // A status line whose command this build cannot read is still the user's.\n if (typeof command !== 'string' || command.trim().length === 0) return 'foreign';\n if (command.trim() === OUR_MARKER) return 'ours';\n return command.includes(OUR_MARKER) ? 'composed' : 'foreign';\n}\n\nfunction ours(): Record<string, unknown> {\n return {\n type: 'command',\n command: STATUS_LINE_COMMAND,\n refreshInterval: STATUS_LINE_REFRESH_SECONDS,\n };\n}\n\nconst shQuote = (value: string): string => `'${value.replaceAll(\"'\", String.raw`'\\''`)}'`;\nconst shUnquote = (value: string): string => value.replaceAll(String.raw`'\\''`, \"'\");\n\n/** The inner script, with the user's own command as the one hole in it. */\nfunction composedScript(existing: string): string {\n return [\n 'event=$(cat)',\n `yours=$(printf %s \"$event\" | ${existing})`,\n `tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND})`,\n 'printf %s \"$yours${tenjin:+ · $tenjin}\"',\n ].join('; ');\n}\n\n/**\n * The command a composition was built from, or null when this is not a\n * composition this build wrote. It is the exact inverse of\n * {@link composeCommand}: a hand-edited line matches nothing and is kept whole,\n * because guessing at someone's shell is how an uninstall breaks a prompt.\n */\nexport function decomposeCommand(command: string): string | null {\n const trimmed = command.trim();\n if (!trimmed.startsWith(\"sh -c '\") || !trimmed.endsWith(\"'\")) return null;\n const script = shUnquote(trimmed.slice(\"sh -c '\".length, -1));\n const prefix = 'event=$(cat); yours=$(printf %s \"$event\" | ';\n if (!script.startsWith(prefix)) return null;\n const rest = script.slice(prefix.length);\n const suffix = `); tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND}); printf %s \"$yours\\${tenjin:+ · $tenjin}\"`;\n if (!rest.endsWith(suffix)) return null;\n const existing = rest.slice(0, -suffix.length);\n return existing.length > 0 && composedScript(existing) === script ? existing : null;\n}\n\n/**\n * The user's status line with ours appended after a separator, on one line.\n *\n * The harness writes its event on stdin ONCE, so a composition cannot simply\n * run two commands in sequence: the event is captured first and replayed into\n * each. Ours contributes nothing when this session has no activity, and the\n * separator goes with it, so a quiet session looks exactly as it did before.\n */\nexport function composeCommand(existing: string): string {\n return `sh -c ${shQuote(composedScript(existing))}`;\n}\n\n/** The command a status-line setting runs, in either shape it can take. */\nfunction commandOf(value: unknown): string | undefined {\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n return typeof command === 'string' && command.trim().length > 0 ? command.trim() : undefined;\n}\n\n/** What a foreign status line's owner is told to set, verbatim. */\nfunction composeFor(value: unknown): string | undefined {\n const command = commandOf(value);\n return command === undefined ? undefined : composeCommand(command);\n}\n\nexport interface EnsureStatusLineOpts {\n mode?: StatusLineMode;\n /**\n * `install --refresh` and the refresh `tenjin update` spawns: converge a\n * status line of ours that is already registered, and ADD NOTHING. A machine\n * whose owner removed ours, or never had it, keeps that answer across every\n * upgrade without a second place to record it.\n */\n refreshOnly?: boolean;\n}\n\nexport async function ensureStatusLine(\n settingsPath: string,\n opts: EnsureStatusLineOpts = {},\n): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (opts.mode === 'skip') {\n return { path, state, wrote: false, ...(state === 'foreign' ? kept(current) : {}) };\n }\n if (opts.mode === 'compose') {\n const composed = composeFor(current);\n if (composed === undefined) return writeStatusLine(found, ours(), 'ours');\n // THEIR OBJECT, with the command swapped. Rebuilding it from ours would\n // drop whatever else they had set on it, such as their own padding.\n const base =\n typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : ours();\n return state === 'composed'\n ? { path, state, wrote: false, command: composed }\n : writeStatusLine(found, { ...base, command: composed }, 'composed');\n }\n if (state === 'foreign') {\n // NOT REPLACED, AND NOT WRITTEN AROUND. The user keeps what they set, and\n // gets the one command that adds ours to it.\n return { path, state, wrote: false, ...kept(current) };\n }\n if (state === 'composed') return { path, state, wrote: false };\n if (state === 'absent' && opts.refreshOnly === true) {\n return { path, state, wrote: false };\n }\n return writeStatusLine(found, ours(), 'ours');\n}\n\n/** `uninstall`: take out a status line of OURS, and only if it is ours alone. */\nexport async function removeStatusLine(settingsPath: string): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (state === 'ours') return writeStatusLine(found, undefined, 'absent');\n // A COMPOSED LINE IS MOSTLY THE USER'S TEXT, so it is not deleted: the half\n // this build wrote is unwound and their own command is put back exactly as it\n // was. A composition that was hand-edited since inverts to nothing and is\n // left whole, because guessing at someone's shell is the worse failure.\n if (state === 'composed') {\n const command = commandOf(current);\n const original = command === undefined ? null : decomposeCommand(command);\n if (original === null) return { path, state, wrote: false };\n const kept = { ...(current as Record<string, unknown>), command: original };\n return writeStatusLine(found, kept, 'foreign');\n }\n return { path, state, wrote: false };\n}\n\n/** What `doctor` reports, without writing anything. */\nexport async function inspectStatusLine(\n settingsPath: string,\n): Promise<{ path: string; state: StatusLineState; warning?: string }> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', warning: found.refusal.reason };\n }\n return { path: found.path, state: classifyStatusLine(found.settings.statusLine) };\n}\n\nfunction kept(current: unknown): { compose?: string } {\n const compose = composeFor(current);\n return compose === undefined ? {} : { compose };\n}\n\ntype Inspection = { path: string; raw: string | null; settings: Record<string, unknown> };\n\n/**\n * One key, written through the same read-compare-write the hooks writer uses:\n * every other key is copied through in its original order, the bytes are\n * re-read before the rename so a concurrent edit is refused rather than lost,\n * and the file keeps its mode.\n */\nasync function writeStatusLine(\n found: Inspection,\n value: Record<string, unknown> | undefined,\n state: StatusLineState,\n): Promise<StatusLineResult> {\n const { path, raw, settings } = found;\n const next: Record<string, unknown> = { ...settings };\n if (value === undefined) delete next.statusLine;\n else next.statusLine = value;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const result: StatusLineResult = {\n path,\n state,\n wrote: false,\n ...(typeof value?.command === 'string' ? { command: value.command } : {}),\n };\n if (body === raw) return result;\n const mode = await stat(path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n if (raw !== null && (await readFile(path, 'utf8').catch(() => null)) !== raw) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: 'changed-since-read',\n };\n }\n try {\n await writeFileAtomic(path, body, mode);\n } catch (err) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: err instanceof Error ? err.message : String(err),\n };\n }\n return { ...result, wrote: true };\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AAuBxB,IAAM,sBAAsB;AAE5B,IAAM,8BAA8B;AAE3C,IAAM,aAAa;AAKnB,IAAM,QAAmC,CAAC,OAAO,WAAW,MAAM;AAG3D,SAAS,eAAe,OAA+B;AAC5D,QAAM,OAAO,MAAM,KAAK,CAAC,UAAU,UAAU,KAAK;AAClD,MAAI,SAAS,QAAW;AACtB,UAAM,IAAI,SAAS,SAAS,uBAAuB,MAAM,KAAK,IAAI,CAAC,UAAU,KAAK,MAAM;AAAA,MACtF,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAqBO,SAAS,mBAAmB,OAAiC;AAClE,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,QAAM,UACJ,OAAO,UAAU,WACb,QACA,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAC9C,MAAgC,UACjC;AAER,MAAI,OAAO,YAAY,YAAY,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AAW,QAAO,KAAK;AAAA,MAChC,MAAK,aAAa;AACvB,QAAM,OAAO,GAAG,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA;AAC7C,QAAM,SAA2B;AAAA,IAC/B;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,GAAI,OAAO,OAAO,YAAY,WAAW,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,EACzE;AACA,MAAI,SAAS,IAAK,QAAO;AACzB,QAAM,OAAO,MAAM,KAAK,IAAI,EACzB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,IAAM,EAAE,EACtC,MAAM,OAAO,CAAC,EAAE;AACnB,MAAI,QAAQ,QAAS,MAAM,SAAS,MAAM,MAAM,EAAE,MAAM,MAAM,IAAI,MAAO,KAAK;AAC5E,WAAO;AAAA,MACL,GAAG;AAAA,MACH,OAAO,mBAAmB,SAAS,UAAU;AAAA,MAC7C,SAAS;AAAA,IACX;AAAA,EACF;AACA,MAAI;AACF,UAAM,gBAAgB,MAAM,MAAM,IAAI;AAAA,EACxC,SAAS,KAAK;AACZ,WAAO;AAAA,MACL,GAAG;AAAA,MACH,OAAO,mBAAmB,SAAS,UAAU;AAAA,MAC7C,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,IAC1D;AAAA,EACF;AACA,SAAO,EAAE,GAAG,QAAQ,OAAO,KAAK;AAClC;","names":["kept"]}
@@ -1,8 +1,10 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
 
3
3
  // src/lib/lock.ts
4
- import { mkdir, rm, writeFile } from "fs/promises";
5
- import { join } from "path";
4
+ import { mkdirSync, rmSync } from "node:fs";
5
+ import { writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ var owned = /* @__PURE__ */ new Set();
6
8
  var DEFAULTS = { timeoutMs: 5e3, retryMs: 25 };
7
9
  var LockTimeoutError = class extends Error {
8
10
  lockPath;
@@ -20,7 +22,8 @@ async function withFileLock(lockPath, fn, opts = {}) {
20
22
  const deadline = Date.now() + timeoutMs;
21
23
  for (; ; ) {
22
24
  try {
23
- await mkdir(lockPath);
25
+ mkdirSync(lockPath);
26
+ owned.add(lockPath);
24
27
  break;
25
28
  } catch (err) {
26
29
  if (!isEexist(err)) throw err;
@@ -34,7 +37,12 @@ async function withFileLock(lockPath, fn, opts = {}) {
34
37
  try {
35
38
  return await fn();
36
39
  } finally {
37
- await rm(lockPath, { recursive: true, force: true }).catch(() => void 0);
40
+ try {
41
+ rmSync(lockPath, { recursive: true, force: true });
42
+ owned.delete(lockPath);
43
+ } catch (err) {
44
+ opts.onReleaseError?.(lockPath, err);
45
+ }
38
46
  }
39
47
  }
40
48
  function isEexist(err) {
@@ -48,4 +56,4 @@ export {
48
56
  LockTimeoutError,
49
57
  withFileLock
50
58
  };
51
- //# sourceMappingURL=chunk-YBMMV4Y4.js.map
59
+ //# sourceMappingURL=chunk-MEFB5KHA.js.map
@@ -0,0 +1 @@
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 * NO LONGER MIRRORED IN THE HOOKS. The generated scripts used to reimplement\n * this protocol byte for byte — they run as standalone .mjs files outside the\n * CLI and cannot import this module, yet wrote the same searches.json, and two\n * writers of one file that disagree about the mutex have no mutex. That file is\n * gone (tenjin-agent#209): hook state is one SQLite database and WAL serializes\n * the writers, so nothing outside this module implements this protocol any more.\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 === 'EEXIST';\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,cAAc;AAClC,SAAS,iBAAiB;AAC1B,SAAS,YAAY;AAgBrB,IAAM,QAAQ,oBAAI,IAAY;AAyC9B,IAAM,WAAW,EAAE,WAAW,KAAM,SAAS,GAAG;AAIzC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC;AAAA,EACT,YAAY,UAAkB,WAAmB;AAC/C;AAAA,MACE,iCAAiC,QAAQ,UAAU,SAAS;AAAA,IAC9D;AACA,SAAK,OAAO;AACZ,SAAK,WAAW;AAAA,EAClB;AACF;AAkBA,eAAsB,aACpB,UACA,IACA,OAAwB,CAAC,GACb;AACZ,QAAM,EAAE,WAAW,QAAQ,IAAI,EAAE,GAAG,UAAU,GAAG,KAAK;AACtD,QAAM,WAAW,KAAK,UAAU,MAAM;AACtC,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,aAAS;AACP,QAAI;AAMF,gBAAU,QAAQ;AAClB,YAAM,IAAI,QAAQ;AAClB;AAAA,IACF,SAAS,KAAK;AACZ,UAAI,CAAC,SAAS,GAAG,EAAG,OAAM;AAC1B,UAAI,KAAK,IAAI,KAAK,SAAU,OAAM,IAAI,iBAAiB,UAAU,SAAS;AAC1E,YAAM,MAAM,OAAO;AAAA,IACrB;AAAA,EACF;AACA,QAAM,UAAU,UAAU,KAAK,UAAU,EAAE,KAAK,QAAQ,KAAK,YAAY,KAAK,IAAI,EAAE,CAAC,CAAC,EAAE;AAAA,IACtF,MAAM;AAAA,EACR;AACA,MAAI;AACF,WAAO,MAAM,GAAG;AAAA,EAClB,UAAE;AAWA,QAAI;AACF,aAAO,UAAU,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AACjD,YAAM,OAAO,QAAQ;AAAA,IACvB,SAAS,KA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