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

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 (219) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +175 -256
  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-2AQO4YDI.js +291 -0
  7. package/dist/chunk-2AQO4YDI.js.map +1 -0
  8. package/dist/chunk-2QYORQBF.js +55 -0
  9. package/dist/chunk-2QYORQBF.js.map +1 -0
  10. package/dist/chunk-3EUTWC2B.js +194 -0
  11. package/dist/chunk-3EUTWC2B.js.map +1 -0
  12. package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
  13. package/dist/chunk-7QKHZQKW.js +1680 -0
  14. package/dist/chunk-7QKHZQKW.js.map +1 -0
  15. package/dist/chunk-A36LQPHV.js +29 -0
  16. package/dist/chunk-A36LQPHV.js.map +1 -0
  17. package/dist/{chunk-XJIW7USF.js → chunk-AQRUD5GQ.js} +115 -11
  18. package/dist/chunk-AQRUD5GQ.js.map +1 -0
  19. package/dist/{chunk-UGX7YPX2.js → chunk-AWQPGIR6.js} +7 -9
  20. package/dist/{chunk-UGX7YPX2.js.map → chunk-AWQPGIR6.js.map} +1 -1
  21. package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
  22. package/dist/chunk-C363JZN2.js +127 -0
  23. package/dist/chunk-C363JZN2.js.map +1 -0
  24. package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
  25. package/dist/chunk-ETW2ASBP.js +10562 -0
  26. package/dist/chunk-ETW2ASBP.js.map +1 -0
  27. package/dist/chunk-GHTPYKDT.js +112 -0
  28. package/dist/chunk-GHTPYKDT.js.map +1 -0
  29. package/dist/{chunk-CYOF7ROH.js → chunk-HPWO4O6S.js} +3 -3
  30. package/dist/chunk-IOB7URFH.js +242 -0
  31. package/dist/chunk-IOB7URFH.js.map +1 -0
  32. package/dist/chunk-IOIHYOU4.js +1784 -0
  33. package/dist/chunk-IOIHYOU4.js.map +1 -0
  34. package/dist/chunk-JLEF5WHM.js +132 -0
  35. package/dist/chunk-JLEF5WHM.js.map +1 -0
  36. package/dist/chunk-JN7TMXVF.js +172 -0
  37. package/dist/chunk-JN7TMXVF.js.map +1 -0
  38. package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
  39. package/dist/chunk-K6AXXYCG.js +109 -0
  40. package/dist/chunk-K6AXXYCG.js.map +1 -0
  41. package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
  42. package/dist/chunk-LAIZ2AQA.js +107 -0
  43. package/dist/chunk-LAIZ2AQA.js.map +1 -0
  44. package/dist/chunk-LHHMV4GU.js +27 -0
  45. package/dist/chunk-LHHMV4GU.js.map +1 -0
  46. package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
  47. package/dist/chunk-MEFB5KHA.js.map +1 -0
  48. package/dist/{chunk-NCE5NSN6.js → chunk-N35E6CM2.js} +140 -10
  49. package/dist/chunk-N35E6CM2.js.map +1 -0
  50. package/dist/chunk-N4DJEQAF.js +190 -0
  51. package/dist/chunk-N4DJEQAF.js.map +1 -0
  52. package/dist/chunk-O2JYBOUO.js +47 -0
  53. package/dist/chunk-O2JYBOUO.js.map +1 -0
  54. package/dist/chunk-OSUD6YZZ.js +451 -0
  55. package/dist/chunk-OSUD6YZZ.js.map +1 -0
  56. package/dist/chunk-OTPEH3AH.js +926 -0
  57. package/dist/chunk-OTPEH3AH.js.map +1 -0
  58. package/dist/chunk-PJEG2JIJ.js +242 -0
  59. package/dist/chunk-PJEG2JIJ.js.map +1 -0
  60. package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
  61. package/dist/chunk-QF4SSCQV.js +377 -0
  62. package/dist/chunk-QF4SSCQV.js.map +1 -0
  63. package/dist/chunk-QHILSA6G.js +82 -0
  64. package/dist/chunk-QHILSA6G.js.map +1 -0
  65. package/dist/chunk-QRFONFRW.js +231 -0
  66. package/dist/chunk-QRFONFRW.js.map +1 -0
  67. package/dist/{chunk-N62ROTMC.js → chunk-RCJQARZF.js} +14 -10
  68. package/dist/chunk-RCJQARZF.js.map +1 -0
  69. package/dist/{chunk-S3IGX57D.js → chunk-RGVOODF4.js} +7703 -7475
  70. package/dist/chunk-RGVOODF4.js.map +1 -0
  71. package/dist/chunk-S2NRVRPF.js +171 -0
  72. package/dist/chunk-S2NRVRPF.js.map +1 -0
  73. package/dist/chunk-SRVDXR6B.js +337 -0
  74. package/dist/chunk-SRVDXR6B.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-U2ATFMKZ.js +164 -0
  79. package/dist/chunk-U2ATFMKZ.js.map +1 -0
  80. package/dist/chunk-UY2TOI3B.js +208 -0
  81. package/dist/chunk-UY2TOI3B.js.map +1 -0
  82. package/dist/{chunk-OYMYCW7J.js → chunk-W3LVZ2EN.js} +605 -97
  83. package/dist/chunk-W3LVZ2EN.js.map +1 -0
  84. package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
  85. package/dist/{chunk-Z6MFJV5Z.js → chunk-YVODPFTL.js} +851 -500
  86. package/dist/chunk-YVODPFTL.js.map +1 -0
  87. package/dist/{cli-4NNBEQYH.js → cli-7KJ4QLUU.js} +367 -216
  88. package/dist/cli-7KJ4QLUU.js.map +1 -0
  89. package/dist/config-MSN6H4MD.js +41 -0
  90. package/dist/dist-3LOO6M4U.js +2842 -0
  91. package/dist/dist-3LOO6M4U.js.map +1 -0
  92. package/dist/doctor-ITUCKN6C.js +453 -0
  93. package/dist/doctor-ITUCKN6C.js.map +1 -0
  94. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  95. package/dist/fund-XPB4IIG5.js +298 -0
  96. package/dist/fund-XPB4IIG5.js.map +1 -0
  97. package/dist/hook-command-VVV2Q23L.js +1265 -0
  98. package/dist/hook-command-VVV2Q23L.js.map +1 -0
  99. package/dist/index.js +11 -3
  100. package/dist/index.js.map +1 -1
  101. package/dist/install-OSJRM2ME.js +63 -0
  102. package/dist/install-identity-YIWKQOUD.js +27 -0
  103. package/dist/install-wallet-BWJO2SUC.js +107 -0
  104. package/dist/install-wallet-BWJO2SUC.js.map +1 -0
  105. package/dist/mcp-KE5YKPS2.js +10174 -0
  106. package/dist/mcp-KE5YKPS2.js.map +1 -0
  107. package/dist/paths-MUXHUOCM.js +57 -0
  108. package/dist/pay-MUV2U232.js +46 -0
  109. package/dist/payments-4D27K4L2.js +48 -0
  110. package/dist/payments-4D27K4L2.js.map +1 -0
  111. package/dist/redact-6W23GGJC.js +15 -0
  112. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
  113. package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
  114. package/dist/send-BXHFKDBF.js +225 -0
  115. package/dist/send-BXHFKDBF.js.map +1 -0
  116. package/dist/status-3Z3YPRSE.js +71 -0
  117. package/dist/status-3Z3YPRSE.js.map +1 -0
  118. package/dist/status-line-CKRMGZ3Q.js +87 -0
  119. package/dist/status-line-CKRMGZ3Q.js.map +1 -0
  120. package/dist/status-line-wiring-GECLIIBT.js +29 -0
  121. package/dist/status-line-wiring-GECLIIBT.js.map +1 -0
  122. package/dist/tenjin-daemon.mjs +20598 -0
  123. package/dist/tenjin-shim.mjs +251 -0
  124. package/dist/tenjin-vitest-reporter.mjs +49 -0
  125. package/dist/uninstall-BZTVWJ7W.js +165 -0
  126. package/dist/uninstall-BZTVWJ7W.js.map +1 -0
  127. package/dist/update-IQQTEOI5.js +433 -0
  128. package/dist/update-IQQTEOI5.js.map +1 -0
  129. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  130. package/dist/viemAdapter-By13KInL-X2VY6CY3.js.map +1 -0
  131. package/dist/wallet-UFXQ57TZ.js +33 -0
  132. package/dist/wallet-UFXQ57TZ.js.map +1 -0
  133. package/dist/wallet-kdf-worker.mjs +980 -0
  134. package/docs/agent-permissions.md +141 -0
  135. package/docs/safety-model.md +70 -0
  136. package/package.json +14 -9
  137. package/LICENSE +0 -21
  138. package/dist/buy-U35DQ6XM.js +0 -1598
  139. package/dist/buy-U35DQ6XM.js.map +0 -1
  140. package/dist/candidate-RLYCQMF5.js +0 -127
  141. package/dist/candidate-RLYCQMF5.js.map +0 -1
  142. package/dist/chunk-27ONARHV.js +0 -171
  143. package/dist/chunk-27ONARHV.js.map +0 -1
  144. package/dist/chunk-3OV7E5G5.js +0 -18
  145. package/dist/chunk-3OV7E5G5.js.map +0 -1
  146. package/dist/chunk-7KUW4MJD.js +0 -59
  147. package/dist/chunk-7KUW4MJD.js.map +0 -1
  148. package/dist/chunk-7PHSZKQS.js +0 -333
  149. package/dist/chunk-7PHSZKQS.js.map +0 -1
  150. package/dist/chunk-IYLHQMT5.js +0 -211
  151. package/dist/chunk-IYLHQMT5.js.map +0 -1
  152. package/dist/chunk-JPHG2JW3.js +0 -96
  153. package/dist/chunk-JPHG2JW3.js.map +0 -1
  154. package/dist/chunk-MUBUQVC3.js +0 -67
  155. package/dist/chunk-MUBUQVC3.js.map +0 -1
  156. package/dist/chunk-N62ROTMC.js.map +0 -1
  157. package/dist/chunk-NCE5NSN6.js.map +0 -1
  158. package/dist/chunk-OYMYCW7J.js.map +0 -1
  159. package/dist/chunk-QNP7H47L.js +0 -152
  160. package/dist/chunk-QNP7H47L.js.map +0 -1
  161. package/dist/chunk-RY4XKNV3.js +0 -140
  162. package/dist/chunk-RY4XKNV3.js.map +0 -1
  163. package/dist/chunk-S3IGX57D.js.map +0 -1
  164. package/dist/chunk-TFGSOPWR.js +0 -261
  165. package/dist/chunk-TFGSOPWR.js.map +0 -1
  166. package/dist/chunk-TLCMMYLY.js +0 -126
  167. package/dist/chunk-TLCMMYLY.js.map +0 -1
  168. package/dist/chunk-UO22YNY4.js +0 -69
  169. package/dist/chunk-UO22YNY4.js.map +0 -1
  170. package/dist/chunk-UPIEAMGH.js +0 -160
  171. package/dist/chunk-UPIEAMGH.js.map +0 -1
  172. package/dist/chunk-XJIW7USF.js.map +0 -1
  173. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  174. package/dist/chunk-YIYQ2ZNT.js +0 -286
  175. package/dist/chunk-YIYQ2ZNT.js.map +0 -1
  176. package/dist/chunk-YN5SHIXQ.js +0 -126
  177. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  178. package/dist/chunk-Z52RA3NC.js +0 -137
  179. package/dist/chunk-Z52RA3NC.js.map +0 -1
  180. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  181. package/dist/cli-4NNBEQYH.js.map +0 -1
  182. package/dist/config-2VSXWWHK.js +0 -21
  183. package/dist/doctor-JJPNIBYH.js +0 -20
  184. package/dist/inspect-JGYJWFDP.js +0 -96
  185. package/dist/inspect-JGYJWFDP.js.map +0 -1
  186. package/dist/install-ZQRMSRGW.js +0 -378
  187. package/dist/install-ZQRMSRGW.js.map +0 -1
  188. package/dist/lookup-WYVTOMVY.js +0 -113
  189. package/dist/lookup-WYVTOMVY.js.map +0 -1
  190. package/dist/outcome-HKKT6QIA.js +0 -66
  191. package/dist/outcome-HKKT6QIA.js.map +0 -1
  192. package/dist/publish-D76B3MBK.js +0 -1480
  193. package/dist/publish-D76B3MBK.js.map +0 -1
  194. package/dist/usdc-JIAJW4SV.js +0 -22
  195. package/dist/wallet-6QKS6UHW.js +0 -179
  196. package/dist/wallet-6QKS6UHW.js.map +0 -1
  197. package/dist/wallet-PA54CRBL.js +0 -30
  198. package/skills/tenjin/SKILL.md +0 -199
  199. package/skills/tenjin-publish/SKILL.md +0 -96
  200. package/skills/tenjin-search/SKILL.md +0 -122
  201. /package/dist/{_esm-FEASBWRP.js.map → _esm-CE7KNONL.js.map} +0 -0
  202. /package/dist/{ccip-NQXCEK2U.js.map → ccip-7RMRLAGV.js.map} +0 -0
  203. /package/dist/{ccip-XR5NE5QK.js.map → ccip-NLCSCHKI.js.map} +0 -0
  204. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
  205. /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
  206. /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
  207. /package/dist/{chunk-CYOF7ROH.js.map → chunk-HPWO4O6S.js.map} +0 -0
  208. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  209. /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
  210. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
  211. /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
  212. /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
  213. /package/dist/{config-2VSXWWHK.js.map → config-MSN6H4MD.js.map} +0 -0
  214. /package/dist/{doctor-JJPNIBYH.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  215. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → install-OSJRM2ME.js.map} +0 -0
  216. /package/dist/{secp256k1-N3ZHU7LB.js.map → install-identity-YIWKQOUD.js.map} +0 -0
  217. /package/dist/{usdc-JIAJW4SV.js.map → paths-MUXHUOCM.js.map} +0 -0
  218. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → pay-MUV2U232.js.map} +0 -0
  219. /package/dist/{wallet-PA54CRBL.js.map → redact-6W23GGJC.js.map} +0 -0
@@ -0,0 +1,1784 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ package_default
4
+ } from "./chunk-RCJQARZF.js";
5
+ import {
6
+ CliError,
7
+ HARNESSES,
8
+ writeFileAtomic
9
+ } from "./chunk-JLEF5WHM.js";
10
+ import {
11
+ daemonBundlePath,
12
+ daemonLogPath,
13
+ daemonPidPath,
14
+ daemonSpawnPath,
15
+ daemonTokenPath,
16
+ hooksDir,
17
+ shimBundlePath,
18
+ vitestReporterPath
19
+ } from "./chunk-K6AXXYCG.js";
20
+
21
+ // src/lib/harness-permissions.ts
22
+ import { chmod, lstat, mkdir, readFile, realpath, stat as stat2 } from "node:fs/promises";
23
+ import { dirname, join as join4 } from "node:path";
24
+
25
+ // src/lib/codex-rules.ts
26
+ import { execFile } from "node:child_process";
27
+ import { rm, stat } from "node:fs/promises";
28
+ import { join as join3 } from "node:path";
29
+
30
+ // src/adapters/codex.ts
31
+ import { join as join2 } from "node:path";
32
+
33
+ // src/lib/grade.ts
34
+ var ENDED_AFTER_MS = 30 * 6e4;
35
+ var AGENT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
36
+
37
+ // src/hooks/constants.ts
38
+ var HARNESS_MS = 5e3;
39
+ var SPAWN_MS = 500;
40
+ var HEALTH_MS = 200;
41
+ var SPAWN_BACKOFF_MS = 6e4;
42
+ var MAX_BODY_BYTES = 4 * 1024 * 1024;
43
+ var LOG_TRUNCATE_BYTES = 5 * 1024 * 1024;
44
+ var CONTEXT_MAX = 1e4;
45
+ var STOP_GRACE_MS = 3e3;
46
+
47
+ // src/lib/codex-trust.ts
48
+ import { spawn } from "node:child_process";
49
+ import { join } from "node:path";
50
+ function codexConfigPath(home, env = process.env) {
51
+ return join(codexHome(home, env), "config.toml");
52
+ }
53
+ function isRecord(v) {
54
+ return typeof v === "object" && v !== null && !Array.isArray(v);
55
+ }
56
+ function foldTrust(rows, keys) {
57
+ const wanted = new Set(keys);
58
+ const mine = rows.filter((r) => typeof r.key === "string" && wanted.has(r.key));
59
+ if (mine.length === 0) return "untrusted";
60
+ const status = (r) => typeof r.trustStatus === "string" ? r.trustStatus : "unknown";
61
+ if (mine.some((r) => r.enabled === false)) return "disabled";
62
+ if (mine.some((r) => status(r) === "modified")) return "modified";
63
+ const good = mine.filter((r) => status(r) === "trusted" || status(r) === "managed");
64
+ if (good.length === 0) return "untrusted";
65
+ if (good.length < keys.length) return "partial";
66
+ return "trusted";
67
+ }
68
+ var PROBE_MS = 8e3;
69
+ async function withAppServer(home, env, timeoutMs, fn) {
70
+ let child;
71
+ try {
72
+ child = spawn("codex", ["app-server"], {
73
+ env: { ...env, CODEX_HOME: codexHome(home, env) },
74
+ stdio: ["pipe", "pipe", "ignore"]
75
+ });
76
+ } catch {
77
+ return null;
78
+ }
79
+ let dead = false;
80
+ const pending = /* @__PURE__ */ new Map();
81
+ const fail = () => {
82
+ dead = true;
83
+ for (const resolve2 of pending.values()) resolve2(void 0);
84
+ pending.clear();
85
+ };
86
+ child.on("error", fail);
87
+ child.on("exit", fail);
88
+ let buffered = "";
89
+ child.stdout?.setEncoding("utf8");
90
+ child.stdout?.on("data", (chunk) => {
91
+ buffered += chunk;
92
+ let cut = buffered.indexOf("\n");
93
+ while (cut !== -1) {
94
+ const line = buffered.slice(0, cut);
95
+ buffered = buffered.slice(cut + 1);
96
+ cut = buffered.indexOf("\n");
97
+ let msg;
98
+ try {
99
+ msg = JSON.parse(line);
100
+ } catch {
101
+ continue;
102
+ }
103
+ if (!isRecord(msg) || typeof msg.id !== "number") continue;
104
+ const waiting = pending.get(msg.id);
105
+ if (waiting === void 0) continue;
106
+ pending.delete(msg.id);
107
+ waiting(msg.error !== void 0 ? void 0 : msg.result);
108
+ }
109
+ });
110
+ let nextId = 1;
111
+ const send = (payload) => {
112
+ try {
113
+ child.stdin?.write(`${JSON.stringify(payload)}
114
+ `);
115
+ return true;
116
+ } catch {
117
+ return false;
118
+ }
119
+ };
120
+ const request = async (method, params) => {
121
+ if (dead) return void 0;
122
+ const id = ++nextId;
123
+ return await new Promise((resolve2) => {
124
+ const timer = setTimeout(() => {
125
+ pending.delete(id);
126
+ resolve2(void 0);
127
+ }, timeoutMs);
128
+ pending.set(id, (value) => {
129
+ clearTimeout(timer);
130
+ resolve2(value);
131
+ });
132
+ if (!send({ jsonrpc: "2.0", id, method, params })) {
133
+ pending.delete(id);
134
+ clearTimeout(timer);
135
+ resolve2(void 0);
136
+ }
137
+ });
138
+ };
139
+ try {
140
+ send({
141
+ jsonrpc: "2.0",
142
+ id: 1,
143
+ method: "initialize",
144
+ params: { clientInfo: { name: "tenjin", title: "tenjin", version: "1" } }
145
+ });
146
+ send({ jsonrpc: "2.0", method: "initialized", params: {} });
147
+ return await fn(request);
148
+ } catch {
149
+ return null;
150
+ } finally {
151
+ try {
152
+ child.stdin?.end();
153
+ } catch {
154
+ }
155
+ child.kill("SIGTERM");
156
+ }
157
+ }
158
+ async function listHooksViaAppServer(home, env, timeoutMs) {
159
+ return await withAppServer(home, env, timeoutMs, async (request) => {
160
+ const result = await request("hooks/list", { cwds: [] });
161
+ return result === void 0 ? null : rowsOf(result);
162
+ });
163
+ }
164
+ function rowsOf(result) {
165
+ if (!isRecord(result) || !Array.isArray(result.data)) return [];
166
+ const out = [];
167
+ for (const group of result.data) {
168
+ if (!isRecord(group) || !Array.isArray(group.hooks)) continue;
169
+ for (const hook of group.hooks) if (isRecord(hook)) out.push(hook);
170
+ }
171
+ return out;
172
+ }
173
+ async function trustCodexHooks(home, keys, ownedBy, opts = {}) {
174
+ const env = opts.env ?? process.env;
175
+ const timeoutMs = opts.timeoutMs ?? PROBE_MS;
176
+ if (keys.length === 0) return { ok: true, trusted: [] };
177
+ const run = async (request) => {
178
+ const before = await request("hooks/list", { cwds: [] });
179
+ if (before === void 0) {
180
+ return {
181
+ ok: false,
182
+ trusted: [],
183
+ failedAt: "list",
184
+ reason: "hooks/list did not answer"
185
+ };
186
+ }
187
+ const wanted = new Set(keys);
188
+ const mine = rowsOf(before).filter(
189
+ (r) => typeof r.key === "string" && wanted.has(r.key) && ownedBy(r)
190
+ );
191
+ if (mine.length !== keys.length) {
192
+ return {
193
+ ok: false,
194
+ trusted: [],
195
+ failedAt: "list",
196
+ reason: `Codex listed ${mine.length} of the ${keys.length} entries this install wrote`
197
+ };
198
+ }
199
+ const value = {};
200
+ for (const row of mine) {
201
+ const hash = typeof row.currentHash === "string" ? row.currentHash : null;
202
+ if (hash === null) {
203
+ return {
204
+ ok: false,
205
+ trusted: [],
206
+ failedAt: "list",
207
+ reason: "Codex reported an entry with no currentHash"
208
+ };
209
+ }
210
+ value[row.key] = { trusted_hash: hash, enabled: true };
211
+ }
212
+ const wrote = await request("config/batchWrite", {
213
+ edits: [{ keyPath: "hooks.state", value, mergeStrategy: "upsert" }],
214
+ reloadUserConfig: true
215
+ });
216
+ if (wrote === void 0) {
217
+ return {
218
+ ok: false,
219
+ trusted: [],
220
+ failedAt: "write",
221
+ reason: "config/batchWrite was refused"
222
+ };
223
+ }
224
+ const after = await request("hooks/list", { cwds: [] });
225
+ if (after === void 0) {
226
+ return {
227
+ ok: false,
228
+ trusted: [],
229
+ failedAt: "verify",
230
+ reason: "the verifying hooks/list did not answer"
231
+ };
232
+ }
233
+ const confirmed = rowsOf(after).filter(
234
+ (r) => typeof r.key === "string" && wanted.has(r.key) && ownedBy(r) && r.enabled !== false && (r.trustStatus === "trusted" || r.trustStatus === "managed") && r.currentHash === value[r.key]?.trusted_hash
235
+ );
236
+ if (confirmed.length !== keys.length) {
237
+ return {
238
+ ok: false,
239
+ trusted: confirmed.map((r) => r.key),
240
+ failedAt: "verify",
241
+ reason: `Codex confirmed ${confirmed.length} of ${keys.length} entries as trusted after the write`
242
+ };
243
+ }
244
+ return { ok: true, trusted: confirmed.map((r) => r.key) };
245
+ };
246
+ const outcome = opts.connect !== void 0 ? await run(opts.connect) : await withAppServer(home, env, timeoutMs, run);
247
+ return outcome ?? {
248
+ ok: false,
249
+ trusted: [],
250
+ failedAt: "list",
251
+ reason: "the codex app server could not be reached"
252
+ };
253
+ }
254
+ async function readCodexTrust(home, keys, opts = {}) {
255
+ const env = opts.env ?? process.env;
256
+ const configPath = codexConfigPath(home, env);
257
+ const base = { configPath, trusted: 0, expected: keys.length };
258
+ if (keys.length === 0) return { ...base, state: "unknown", source: "none" };
259
+ const list = await (opts.listHooks ?? ((h, e) => listHooksViaAppServer(h, e, opts.timeoutMs ?? PROBE_MS)))(home, env);
260
+ if (list !== null) {
261
+ const state = foldTrust(list, keys);
262
+ const wanted = new Set(keys);
263
+ const trusted = list.filter(
264
+ (r) => typeof r.key === "string" && wanted.has(r.key) && (r.trustStatus === "trusted" || r.trustStatus === "managed")
265
+ ).length;
266
+ return { ...base, trusted, state, source: "app-server" };
267
+ }
268
+ return { ...base, state: "unknown", source: "none" };
269
+ }
270
+
271
+ // src/adapters/error-markers.ts
272
+ var ERROR_MARKERS = [
273
+ // Test-runner verdicts. Uppercase only, and a whole word.
274
+ /\bFAIL\b/,
275
+ /AssertionError/,
276
+ /\b[1-9]\d* (?:failed|failing|errors?)\b/i,
277
+ // `Error:`, `TypeError:`, `ReferenceError:`, `ModuleNotFoundError:` — the
278
+ // JS and Python convention of naming the class before the colon — and the
279
+ // lowercase `error:` that rustc, gcc, clang, esbuild and git open a
280
+ // diagnostic line with. Line-start only: "an error: occurred" mid-sentence
281
+ // is prose.
282
+ /^[ \t]*(?:\w*Error|error):/m,
283
+ /Traceback \(most recent call last\)/,
284
+ /ModuleNotFoundError|ImportError:/,
285
+ /Cannot find module/i,
286
+ // A code the shell or a runner states outright. Never zero.
287
+ /exit code [1-9]\d*/i,
288
+ // libuv/POSIX codes: unambiguous, and the common real failures.
289
+ /\b(?:ENOENT|EADDRINUSE|ECONNREFUSED|EACCES|EPERM)\b/,
290
+ // Toolchain-specific prefixes: npm, pnpm, tsc, cargo, go, git.
291
+ /^[ \t]*npm ERR!/m,
292
+ /ERR_PNPM_/,
293
+ /error TS\d+:/,
294
+ /^[ \t]*error\[E\d+\]/m,
295
+ /^[ \t]*panic:/m,
296
+ /^[ \t]*fatal:/m,
297
+ /Unhandled(?:PromiseRejection|Rejection)/,
298
+ /segmentation fault/i
299
+ ];
300
+ function hasErrorMarker(text) {
301
+ return ERROR_MARKERS.some((re) => re.test(text));
302
+ }
303
+
304
+ // src/adapters/codex.ts
305
+ var NATIVE_TO_EVENT = {
306
+ SessionStart: "session.start",
307
+ UserPromptSubmit: "prompt",
308
+ PreToolUse: "tool.before",
309
+ PostToolUse: "tool.after",
310
+ SubagentStart: "agent.start",
311
+ SubagentStop: "agent.stop",
312
+ Stop: "turn.end"
313
+ };
314
+ var SHELL_TOOL = "Bash";
315
+ var PATCH_TOOL = "apply_patch";
316
+ var BLOCK_EVENTS = /* @__PURE__ */ new Set(["turn.end", "agent.stop"]);
317
+ function isRecord2(v) {
318
+ return typeof v === "object" && v !== null && !Array.isArray(v);
319
+ }
320
+ function str(v) {
321
+ return typeof v === "string" ? v : void 0;
322
+ }
323
+ var PATCH_PATH_RE = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/;
324
+ function patchPaths(patch) {
325
+ const out = [];
326
+ for (const line of patch.split("\n")) {
327
+ const m = PATCH_PATH_RE.exec(line.trimEnd());
328
+ const path = m?.[1]?.trim();
329
+ if (path !== void 0 && path.length > 0 && !out.includes(path)) out.push(path);
330
+ }
331
+ return out;
332
+ }
333
+ function canonicalTool(name, input) {
334
+ if (name === SHELL_TOOL) return { name, kind: "shell", command: str(input.command) ?? "" };
335
+ if (name === PATCH_TOOL)
336
+ return { name, kind: "edit", paths: patchPaths(str(input.command) ?? "") };
337
+ return { name, kind: "other" };
338
+ }
339
+ function decode(raw) {
340
+ if (!isRecord2(raw)) return null;
341
+ const native = str(raw.hook_event_name);
342
+ if (native === void 0) return null;
343
+ const event = NATIVE_TO_EVENT[native];
344
+ if (event === void 0) return null;
345
+ const session = str(raw.session_id);
346
+ if (session === void 0 || session.length === 0) return null;
347
+ const input = {
348
+ harness: "codex",
349
+ event,
350
+ native: { event: native },
351
+ session,
352
+ cwd: str(raw.cwd) ?? "",
353
+ raw
354
+ };
355
+ if (raw.agent_id !== void 0 && raw.agent_id !== null) {
356
+ const id = raw.agent_id;
357
+ if (typeof id !== "string" || !AGENT_ID_RE.test(id)) return null;
358
+ input.agent = id;
359
+ }
360
+ const turn = str(raw.turn_id);
361
+ if (turn !== void 0) input.turn = turn;
362
+ const prompt = str(raw.prompt);
363
+ if (prompt !== void 0) input.prompt = prompt;
364
+ const agentType = str(raw.agent_type);
365
+ if (agentType !== void 0) input.agentType = agentType;
366
+ const lastMessage = str(raw.last_assistant_message);
367
+ if (lastMessage !== void 0) input.lastMessage = lastMessage;
368
+ if (typeof raw.stop_hook_active === "boolean") input.stopFuse = raw.stop_hook_active;
369
+ const source = str(raw.source);
370
+ if (source !== void 0) input.source = source;
371
+ const path = str(raw.transcript_path);
372
+ const agentPath = str(raw.agent_transcript_path);
373
+ if (path !== void 0 || agentPath !== void 0) {
374
+ input.transcript = {};
375
+ if (path !== void 0) input.transcript.path = path;
376
+ if (agentPath !== void 0) input.transcript.agentPath = agentPath;
377
+ }
378
+ if (event === "tool.before" || event === "tool.after") {
379
+ const name = str(raw.tool_name) ?? "";
380
+ const tool = canonicalTool(name, isRecord2(raw.tool_input) ? raw.tool_input : {});
381
+ const callId = str(raw.tool_use_id);
382
+ if (callId !== void 0) tool.callId = callId;
383
+ if (event === "tool.after") {
384
+ const text = str(raw.tool_response);
385
+ if (text !== void 0) tool.result = { text };
386
+ if (tool.kind === "shell" && text !== void 0 && hasErrorMarker(text)) tool.ok = false;
387
+ }
388
+ input.tool = tool;
389
+ }
390
+ return input;
391
+ }
392
+ function encode(emit, input) {
393
+ if (emit === null || emit.context === void 0 || emit.context.length === 0) return null;
394
+ const text = emit.context.slice(0, CONTEXT_MAX);
395
+ if (BLOCK_EVENTS.has(input.event)) return { decision: "block", reason: text };
396
+ return { hookSpecificOutput: { hookEventName: input.native.event, additionalContext: text } };
397
+ }
398
+ function codexHome(home, env = process.env) {
399
+ const override = env.CODEX_HOME;
400
+ return override !== void 0 && override.length > 0 ? override : join2(home, ".codex");
401
+ }
402
+ function commandHandler(shimPath, timeoutSeconds) {
403
+ return {
404
+ type: "command",
405
+ command: `node ${JSON.stringify(shimPath)} --harness codex`,
406
+ timeout: timeoutSeconds
407
+ };
408
+ }
409
+ var registrar = {
410
+ configPath(home, env) {
411
+ return join2(codexHome(home, env), "hooks.json");
412
+ },
413
+ /**
414
+ * Seven `command` entries, every one through the shim: a Codex handler
415
+ * carries no URL or token, so the daemon is ensured on each fire and the
416
+ * entry holds nothing worth protecting. The matchers are the two hooked
417
+ * tool names the arms read; a child's fires arrive through the same entries.
418
+ */
419
+ plan({ shimPath, timeoutSeconds }) {
420
+ const command = [commandHandler(shimPath, timeoutSeconds)];
421
+ return [
422
+ { event: "SessionStart", hooks: command },
423
+ { event: "UserPromptSubmit", hooks: command },
424
+ { event: "PreToolUse", matcher: `${SHELL_TOOL}|${PATCH_TOOL}`, hooks: command },
425
+ { event: "PostToolUse", matcher: SHELL_TOOL, hooks: command },
426
+ { event: "SubagentStart", hooks: command },
427
+ { event: "SubagentStop", hooks: command },
428
+ { event: "Stop", hooks: command }
429
+ ];
430
+ },
431
+ /**
432
+ * Codex reads hooks once, at session start. `install` now trusts the entries
433
+ * it writes through Codex's own supported path (lib/codex-trust.ts), so the
434
+ * `/hooks` walkthrough this used to carry is gone; what is left is the one
435
+ * fact no installer can change, which is that the session already open still
436
+ * has the hook set it started with (tenjin-agent#343).
437
+ */
438
+ activation() {
439
+ return ["Start a new Codex session: hooks are read at session start."];
440
+ },
441
+ grant: {
442
+ path: codexRulesPath,
443
+ inspect: inspectCodexGrant,
444
+ write: wireCodexGrant,
445
+ remove: removeCodexGrant
446
+ },
447
+ trust: {
448
+ ensure: trustCodexHooks,
449
+ read: readCodexTrust
450
+ }
451
+ };
452
+ var codexAdapter = { id: "codex", decode, encode, registrar };
453
+
454
+ // src/lib/codex-rules.ts
455
+ function codexRulesPath(home, env = process.env) {
456
+ return join3(codexHome(home, env), "rules", "tenjin.rules");
457
+ }
458
+ function prefixTokens(rule) {
459
+ const m = /^Bash\(tenjin ((?:[a-z][a-z-]* )*[a-z][a-z-]*):\*\)$/.exec(rule);
460
+ const verbs = m?.[1];
461
+ if (verbs === void 0) return null;
462
+ return ["tenjin", ...verbs.split(" ")];
463
+ }
464
+ function prefixRuleLine(tokens) {
465
+ const pattern = tokens.map((t) => JSON.stringify(t)).join(", ");
466
+ return `prefix_rule(pattern=[${pattern}], decision="allow")`;
467
+ }
468
+ function grantedPrefixes(rules) {
469
+ return rules.map(prefixTokens).filter((t) => t !== null);
470
+ }
471
+ function rulesFileBody(rules) {
472
+ const lines = [
473
+ "# Written by `tenjin install`. Change it with `tenjin config set publish.mode`",
474
+ "# or `tenjin uninstall`, not by hand: the next install rewrites it whole.",
475
+ "# Your own rules live in default.rules and are never touched by Tenjin.",
476
+ "",
477
+ ...grantedPrefixes(rules).map(prefixRuleLine)
478
+ ];
479
+ return `${lines.join("\n")}
480
+ `;
481
+ }
482
+ async function verifyPrefixAllowed(rulesPath, tokens, env = process.env, timeoutMs = VERIFY_MS) {
483
+ return await new Promise((resolve2) => {
484
+ execFile(
485
+ "codex",
486
+ ["execpolicy", "check", "--rules", rulesPath, ...tokens],
487
+ { env, timeout: timeoutMs, windowsHide: true },
488
+ (_err, stdout) => {
489
+ if (typeof stdout !== "string" || stdout.length === 0) {
490
+ resolve2(null);
491
+ return;
492
+ }
493
+ try {
494
+ const parsed = JSON.parse(stdout);
495
+ const decision = typeof parsed === "object" && parsed !== null ? parsed.decision : void 0;
496
+ resolve2(decision === "allow");
497
+ } catch {
498
+ resolve2(null);
499
+ }
500
+ }
501
+ );
502
+ });
503
+ }
504
+ var VERIFY_MS = 5e3;
505
+ async function removeCodexGrant(home, env = process.env) {
506
+ const path = codexRulesPath(home, env);
507
+ const found = await stat(path).catch(() => null);
508
+ if (found === null || !found.isFile()) return { path, removed: false };
509
+ await rm(path, { force: true });
510
+ return { path, removed: true };
511
+ }
512
+
513
+ // src/lib/harness-permissions.ts
514
+ function claudeSettingsPath(homeDir) {
515
+ return join4(homeDir, ".claude", "settings.json");
516
+ }
517
+ async function inspectClaudeGrant(homeDir, mode) {
518
+ const found = await inspectAllowlist(homeDir, mode);
519
+ if ("result" in found) {
520
+ const refused = found.result;
521
+ return {
522
+ harness: "claude",
523
+ state: "unknown",
524
+ ...refused.path !== void 0 ? { path: refused.path } : {},
525
+ rules: [],
526
+ missing: [],
527
+ detail: refused.warning ?? `${claudeSettingsPath(homeDir)} could not be read.`,
528
+ ...refused.fix !== void 0 ? { fix: refused.fix } : {}
529
+ };
530
+ }
531
+ const missing = [...found.added];
532
+ return {
533
+ harness: "claude",
534
+ state: missing.length === 0 ? "granted" : "pending",
535
+ path: found.path,
536
+ rules: [...found.alreadyPresent],
537
+ missing,
538
+ detail: missing.length === 0 ? `${found.alreadyPresent.length} rules in ${found.path}` : `${missing.length} of this mode's rules are missing from ${found.path}`,
539
+ ...missing.length === 0 ? {} : { fix: "tenjin install" }
540
+ };
541
+ }
542
+ async function tighten(path) {
543
+ if (process.platform === "win32") return;
544
+ const found = await stat2(path).catch(() => null);
545
+ if (found === null || (found.mode & 63) === 0) return;
546
+ await chmod(path, 384).catch(() => void 0);
547
+ }
548
+ async function inspectCodexGrant(homeDir, mode, env = process.env) {
549
+ const path = codexRulesPath(homeDir, env);
550
+ const writable = rulesForPublishMode(mode);
551
+ const want = rulesFileBody(writable);
552
+ const rules = grantedPrefixes(writable).map((tokens) => tokens.join(" "));
553
+ const found = await readFile(path, "utf8").catch(() => null);
554
+ if (found !== want) {
555
+ return {
556
+ harness: "codex",
557
+ state: "pending",
558
+ path,
559
+ rules: [],
560
+ missing: rules,
561
+ detail: found === null ? `no grant is installed at ${path}` : `${path} does not match what publish.mode ${mode} calls for`,
562
+ fix: "tenjin install"
563
+ };
564
+ }
565
+ const probe = grantedPrefixes(writable).at(-1);
566
+ const agreed = probe === void 0 ? null : await verifyPrefixAllowed(path, probe, env);
567
+ if (agreed === false) {
568
+ return {
569
+ harness: "codex",
570
+ state: "pending",
571
+ path,
572
+ rules: [],
573
+ missing: rules,
574
+ detail: `${path} is installed but Codex does not read it as granting \`${probe?.join(" ")}\``,
575
+ fix: "tenjin install"
576
+ };
577
+ }
578
+ if (agreed === null) {
579
+ return {
580
+ harness: "codex",
581
+ state: "unknown",
582
+ path,
583
+ rules,
584
+ missing: [],
585
+ detail: `${rules.length} prefixes written to ${path}, but codex could not be asked whether it reads them as a grant`,
586
+ fix: "Check `codex execpolicy check --rules <file> tenjin publish x` on the machine itself."
587
+ };
588
+ }
589
+ return {
590
+ harness: "codex",
591
+ state: "granted",
592
+ path,
593
+ rules,
594
+ missing: [],
595
+ detail: `${rules.length} prefixes in ${path}, confirmed by codex execpolicy`
596
+ };
597
+ }
598
+ async function wireCodexGrant(homeDir, mode, env = process.env) {
599
+ const path = codexRulesPath(homeDir, env);
600
+ const rules = rulesForPublishMode(mode);
601
+ const body = rulesFileBody(rules);
602
+ const granted = grantedPrefixes(rules).map((t) => t.join(" "));
603
+ try {
604
+ await mkdir(dirname(path), { recursive: true });
605
+ const current = await readFile(path, "utf8").catch(() => null);
606
+ if (current === body) {
607
+ await tighten(path);
608
+ return { path, granted, wrote: false };
609
+ }
610
+ await writeFileAtomic(path, body, { mode: 384 });
611
+ return { path, granted, wrote: true };
612
+ } catch (err) {
613
+ return {
614
+ path,
615
+ granted: [],
616
+ wrote: false,
617
+ error: err instanceof Error ? err.message : String(err)
618
+ };
619
+ }
620
+ }
621
+ var FREE_VERB_RULES = [
622
+ "Bash(tenjin search:*)",
623
+ "Bash(tenjin wallet fund:*)",
624
+ "Bash(tenjin inspect:*)",
625
+ "Bash(tenjin read:*)",
626
+ "Bash(tenjin outcome:*)",
627
+ "Bash(tenjin doctor:*)",
628
+ "Bash(tenjin wallet show:*)",
629
+ "Bash(tenjin wallet balance:*)",
630
+ "Bash(tenjin config get:*)"
631
+ ];
632
+ var PUBLISH_MODE_RULE = "Bash(tenjin publish:*)";
633
+ var EDIT_MODE_RULE = "Bash(tenjin edit:*)";
634
+ var MODE_GATED_RULES = [PUBLISH_MODE_RULE, EDIT_MODE_RULE];
635
+ function rulesForPublishMode(mode) {
636
+ return mode === "review" ? FREE_VERB_RULES : [...FREE_VERB_RULES, ...MODE_GATED_RULES];
637
+ }
638
+ function retiredFor(mode) {
639
+ const retired = new Set(LEGACY_ALLOWLIST_RULES);
640
+ if (mode === "review") for (const rule of MODE_GATED_RULES) retired.add(rule);
641
+ return retired;
642
+ }
643
+ var LEGACY_ALLOWLIST_RULES = [
644
+ "Bash(tenjin candidate list:*)",
645
+ "Bash(tenjin fund:*)"
646
+ ];
647
+ var MODE_GRANT_UNDO = [
648
+ "tenjin install --publish-mode review",
649
+ "tenjin config set publish.mode review",
650
+ "tenjin uninstall"
651
+ ];
652
+ function modeGrantFor(mode, added, present, planned) {
653
+ const wasAdded = MODE_GATED_RULES.filter((r) => added.includes(r));
654
+ const wasPresent = MODE_GATED_RULES.filter((r) => present.includes(r));
655
+ const rules = [...wasAdded, ...wasPresent];
656
+ if (rules.length === 0) return void 0;
657
+ const state = wasAdded.length === 0 ? "already-present" : wasPresent.length === 0 ? "added" : "mixed";
658
+ const verb = state === "already-present" ? "already present" : state === "mixed" ? planned ? "would be in place" : "in place" : planned ? "would be added" : "added";
659
+ return {
660
+ rules: MODE_GATED_RULES.filter((r) => rules.includes(r)),
661
+ state,
662
+ disclosure: `${MODE_GATED_RULES.join(" and ")} ${verb}: on publish.mode ${mode} your agent can publish to the public marketplace under your identity, update its own posts, and open your wallet keystore to sign, without a harness prompt.`,
663
+ undo: [...MODE_GRANT_UNDO]
664
+ };
665
+ }
666
+ function fixFor(reason, harness = "claude") {
667
+ switch (reason) {
668
+ case "harness-unsupported":
669
+ return `No permission rules were written: ${harness} has no surface for them.`;
670
+ case "not-requested":
671
+ case "declined":
672
+ case "dry-run":
673
+ return "Add them with `tenjin install`.";
674
+ case "changed-since-read":
675
+ return "Another process changed the file mid-run; re-run `tenjin install`.";
676
+ default:
677
+ return "Fix the reported file, then run `tenjin install`.";
678
+ }
679
+ }
680
+ function tiers(added, alreadyPresent, mode, planned = false) {
681
+ const gated = new Set(MODE_GATED_RULES);
682
+ const grant = modeGrantFor(mode, added, alreadyPresent, planned);
683
+ return {
684
+ addedFree: added.filter((r) => !gated.has(r)),
685
+ alreadyPresentFree: alreadyPresent.filter((r) => !gated.has(r)),
686
+ ...grant !== void 0 ? { modeGrant: grant } : {}
687
+ };
688
+ }
689
+ function skip(harness, path, reason, warning) {
690
+ return {
691
+ harness,
692
+ ...path !== void 0 ? { path } : {},
693
+ added: [],
694
+ removed: [],
695
+ alreadyPresent: [],
696
+ addedFree: [],
697
+ alreadyPresentFree: [],
698
+ skipped: reason,
699
+ ...warning !== void 0 ? { warning } : {},
700
+ fix: fixFor(reason, harness)
701
+ };
702
+ }
703
+ function isPlainObject(value) {
704
+ return typeof value === "object" && value !== null && !Array.isArray(value);
705
+ }
706
+ async function writeSettings(path, next) {
707
+ const current = await stat2(path).catch(() => null);
708
+ await writeFileAtomic(
709
+ path,
710
+ `${JSON.stringify(next, null, 2)}
711
+ `,
712
+ current === null ? {} : { mode: current.mode & 511 }
713
+ );
714
+ }
715
+ async function retractModeGatedRules(homeDir) {
716
+ const found = await inspectAllowlist(homeDir, "review");
717
+ if ("result" in found) {
718
+ const refused = found.result;
719
+ return {
720
+ ...refused,
721
+ fix: `${refused.path ?? claudeSettingsPath(homeDir)} could not be read, so ${MODE_GATED_RULES.join(" and ")} may still be allowed there. Remove those lines by hand, or run \`tenjin uninstall\`.`
722
+ };
723
+ }
724
+ const { path, raw, settings, permissions, allow } = found;
725
+ const gated = new Set(MODE_GATED_RULES);
726
+ const removed = allow.filter((r) => typeof r === "string" && gated.has(r));
727
+ if (removed.length === 0) {
728
+ return {
729
+ harness: "claude",
730
+ path,
731
+ added: [],
732
+ alreadyPresent: [],
733
+ addedFree: [],
734
+ alreadyPresentFree: [],
735
+ removed: []
736
+ };
737
+ }
738
+ const kept = allow.filter((r) => !(typeof r === "string" && gated.has(r)));
739
+ const next = { ...settings, permissions: { ...permissions, allow: kept } };
740
+ const current = await readFile(path, "utf8").catch(() => null);
741
+ if (current !== raw) {
742
+ return skip(
743
+ "claude",
744
+ path,
745
+ "changed-since-read",
746
+ `${path} changed while it was being updated, so nothing was written. Re-run to retract ${MODE_GATED_RULES.join(" and ")}.`
747
+ );
748
+ }
749
+ await writeSettings(path, next);
750
+ return {
751
+ harness: "claude",
752
+ path,
753
+ added: [],
754
+ alreadyPresent: [],
755
+ addedFree: [],
756
+ alreadyPresentFree: [],
757
+ removed
758
+ };
759
+ }
760
+ async function wireFreeVerbAllowlist(homeDir, mode = "review") {
761
+ const found = await inspectAllowlist(homeDir, mode);
762
+ if ("result" in found) return found.result;
763
+ const { path, raw, settings, permissions, allow, added, alreadyPresent } = found;
764
+ const retired = retiredFor(mode);
765
+ const removed = allow.filter((r) => typeof r === "string" && retired.has(r));
766
+ if (added.length === 0 && removed.length === 0) {
767
+ return {
768
+ harness: "claude",
769
+ path,
770
+ added: [],
771
+ alreadyPresent,
772
+ ...tiers([], alreadyPresent, mode),
773
+ removed: []
774
+ };
775
+ }
776
+ const kept = allow.filter((r) => !(typeof r === "string" && retired.has(r)));
777
+ const next = {
778
+ ...settings,
779
+ permissions: { ...permissions, allow: [...kept, ...added] }
780
+ };
781
+ const current = await readFile(path, "utf8").catch(() => null);
782
+ if (current !== raw) {
783
+ return skip(
784
+ "claude",
785
+ path,
786
+ "changed-since-read",
787
+ `${path} changed while it was being updated, so nothing was written. Re-run \`tenjin install\`.`
788
+ );
789
+ }
790
+ await writeSettings(path, next);
791
+ return {
792
+ harness: "claude",
793
+ path,
794
+ added,
795
+ alreadyPresent,
796
+ ...tiers(added, alreadyPresent, mode),
797
+ removed
798
+ };
799
+ }
800
+ async function inspectFreeVerbRules(homeDir, mode = "review") {
801
+ const found = await inspectAllowlist(homeDir, mode);
802
+ if ("result" in found) return { pending: null };
803
+ if (found.added.length > 0) return { pending: found.added };
804
+ const retired = retiredFor(mode);
805
+ if (found.allow.some((r) => typeof r === "string" && retired.has(r))) return { pending: [] };
806
+ return {
807
+ pending: [],
808
+ satisfied: {
809
+ harness: "claude",
810
+ path: found.path,
811
+ added: [],
812
+ alreadyPresent: found.alreadyPresent,
813
+ ...tiers([], found.alreadyPresent, mode),
814
+ removed: []
815
+ }
816
+ };
817
+ }
818
+ async function inspectAllowlist(homeDir, mode) {
819
+ return inspectAllowlistAt(claudeSettingsPath(homeDir), rulesForPublishMode(mode));
820
+ }
821
+ async function inspectAllowlistAt(declaredPath, rules) {
822
+ const refuse = (p, reason, warning) => ({ result: skip("claude", p, reason, warning) });
823
+ const entry = await lstat(declaredPath).catch(() => null);
824
+ let path = declaredPath;
825
+ if (entry !== null) {
826
+ try {
827
+ path = await realpath(declaredPath);
828
+ } catch (err) {
829
+ return refuse(
830
+ declaredPath,
831
+ "unresolvable",
832
+ `${declaredPath} could not be resolved (${err.message}); it was left exactly as it is.`
833
+ );
834
+ }
835
+ }
836
+ let settings = {};
837
+ let raw = null;
838
+ if (entry !== null) {
839
+ try {
840
+ raw = await readFile(path, "utf8");
841
+ } catch (err) {
842
+ return refuse(
843
+ path,
844
+ "unreadable",
845
+ `${path} could not be read (${err.message}); no permissions were written.`
846
+ );
847
+ }
848
+ let parsed;
849
+ try {
850
+ parsed = JSON.parse(raw);
851
+ } catch (err) {
852
+ return refuse(
853
+ path,
854
+ "unparsable",
855
+ `${path} is not valid JSON (${err.message}); it was left exactly as it is.`
856
+ );
857
+ }
858
+ if (!isPlainObject(parsed)) {
859
+ return refuse(
860
+ path,
861
+ "unexpected-shape",
862
+ `${path} is not a JSON object; it was left exactly as it is.`
863
+ );
864
+ }
865
+ settings = parsed;
866
+ }
867
+ const permissionsValue = settings.permissions;
868
+ if (permissionsValue !== void 0 && !isPlainObject(permissionsValue)) {
869
+ return refuse(
870
+ path,
871
+ "unexpected-shape",
872
+ `${path} has a "permissions" key that is not an object; it was left exactly as it is.`
873
+ );
874
+ }
875
+ const permissions = permissionsValue ?? {};
876
+ const allowValue = permissions.allow;
877
+ if (allowValue !== void 0 && !Array.isArray(allowValue)) {
878
+ return refuse(
879
+ path,
880
+ "unexpected-shape",
881
+ `${path} has a "permissions.allow" key that is not an array; it was left exactly as it is.`
882
+ );
883
+ }
884
+ const allow = allowValue ?? [];
885
+ const present = new Set(allow.filter((e) => typeof e === "string"));
886
+ const added = rules.filter((rule) => !present.has(rule));
887
+ const alreadyPresent = rules.filter((rule) => present.has(rule));
888
+ return { path, raw, settings, permissions, allow, added, alreadyPresent: [...alreadyPresent] };
889
+ }
890
+ async function appendAllowlistRules(declaredPath, rules) {
891
+ const found = await inspectAllowlistAt(declaredPath, rules);
892
+ if ("result" in found) {
893
+ const result = found.result;
894
+ return {
895
+ path: result.path ?? declaredPath,
896
+ added: [],
897
+ alreadyPresent: [],
898
+ ...result.skipped !== void 0 ? { skipped: result.skipped } : {},
899
+ ...result.warning !== void 0 ? { warning: result.warning } : {}
900
+ };
901
+ }
902
+ const { path, raw, settings, permissions, allow, added, alreadyPresent } = found;
903
+ if (added.length === 0) return { path, added: [], alreadyPresent };
904
+ const next = { ...settings, permissions: { ...permissions, allow: [...allow, ...added] } };
905
+ const current = await readFile(path, "utf8").catch(() => null);
906
+ if (current !== raw) {
907
+ return {
908
+ path,
909
+ added: [],
910
+ alreadyPresent,
911
+ skipped: "changed-since-read",
912
+ warning: `${path} changed while it was being updated, so nothing was written. Re-run \`tenjin install\`.`
913
+ };
914
+ }
915
+ await writeSettings(path, next);
916
+ return { path, added, alreadyPresent };
917
+ }
918
+
919
+ // src/adapters/claude.ts
920
+ var NATIVE_TO_EVENT2 = {
921
+ SessionStart: "session.start",
922
+ UserPromptSubmit: "prompt",
923
+ PreToolUse: "tool.before",
924
+ PostToolUse: "tool.after",
925
+ PostToolUseFailure: "tool.after",
926
+ SubagentStart: "agent.start",
927
+ SubagentStop: "agent.stop",
928
+ Stop: "turn.end"
929
+ };
930
+ var TOOLS = {
931
+ web: /^WebSearch$/,
932
+ fetch: /^WebFetch$/,
933
+ dispatch: /^(Agent|Task)$/,
934
+ shell: /^Bash$/,
935
+ edit: /^(Edit|Write|MultiEdit)$/,
936
+ read: /^Read$/
937
+ };
938
+ function matcherOf(re) {
939
+ return re.source.replace(/^\^\(?/, "").replace(/\)?\$$/, "");
940
+ }
941
+ var SESSION_START_MATCHER = "startup|clear|compact";
942
+ function isRecord3(v) {
943
+ return typeof v === "object" && v !== null && !Array.isArray(v);
944
+ }
945
+ function str2(v) {
946
+ return typeof v === "string" ? v : void 0;
947
+ }
948
+ function toolKind(name) {
949
+ for (const kind of Object.keys(TOOLS)) if (TOOLS[kind].test(name)) return kind;
950
+ return "other";
951
+ }
952
+ function canonicalTool2(name, input) {
953
+ const kind = toolKind(name);
954
+ switch (kind) {
955
+ case "shell":
956
+ return { name, kind, command: str2(input.command) ?? "" };
957
+ case "edit":
958
+ case "read": {
959
+ const path = str2(input.file_path);
960
+ return { name, kind, paths: path === void 0 ? [] : [path] };
961
+ }
962
+ case "dispatch": {
963
+ const description = str2(input.description);
964
+ return {
965
+ name,
966
+ kind,
967
+ task: str2(input.prompt) ?? "",
968
+ ...description !== void 0 ? { description } : {}
969
+ };
970
+ }
971
+ case "web":
972
+ return { name, kind, query: str2(input.query) ?? "" };
973
+ case "fetch":
974
+ return { name, kind, url: str2(input.url) ?? "", prompt: str2(input.prompt) ?? "" };
975
+ default:
976
+ return { name, kind };
977
+ }
978
+ }
979
+ function toolResult(v) {
980
+ if (typeof v === "string") return { text: v };
981
+ if (!isRecord3(v)) return void 0;
982
+ const out = {};
983
+ const stdout = str2(v.stdout);
984
+ const stderr = str2(v.stderr);
985
+ const error = str2(v.error);
986
+ if (stdout !== void 0) out.stdout = stdout;
987
+ if (stderr !== void 0) out.stderr = stderr;
988
+ if (error !== void 0) out.error = error;
989
+ if (stdout === void 0 && stderr === void 0 && error === void 0) {
990
+ const text = str2(v.text) ?? str2(v.content) ?? str2(v.result);
991
+ if (text !== void 0) out.text = text;
992
+ }
993
+ return out;
994
+ }
995
+ function decode2(raw) {
996
+ if (!isRecord3(raw)) return null;
997
+ const native = str2(raw.hook_event_name);
998
+ if (native === void 0) return null;
999
+ const event = NATIVE_TO_EVENT2[native];
1000
+ if (event === void 0) return null;
1001
+ const session = str2(raw.session_id);
1002
+ if (session === void 0 || session.length === 0) return null;
1003
+ const input = {
1004
+ harness: "claude",
1005
+ event,
1006
+ native: { event: native },
1007
+ session,
1008
+ cwd: str2(raw.cwd) ?? "",
1009
+ raw
1010
+ };
1011
+ if (raw.agent_id !== void 0 && raw.agent_id !== null) {
1012
+ const id = raw.agent_id;
1013
+ if (typeof id !== "string" || !AGENT_ID_RE.test(id)) return null;
1014
+ input.agent = id;
1015
+ }
1016
+ const turn = str2(raw.prompt_id);
1017
+ if (turn !== void 0) input.turn = turn;
1018
+ const prompt = str2(raw.prompt);
1019
+ if (prompt !== void 0) input.prompt = prompt;
1020
+ const agentType = str2(raw.agent_type);
1021
+ if (agentType !== void 0) input.agentType = agentType;
1022
+ const lastMessage = str2(raw.last_assistant_message);
1023
+ if (lastMessage !== void 0) input.lastMessage = lastMessage;
1024
+ if (typeof raw.stop_hook_active === "boolean") input.stopFuse = raw.stop_hook_active;
1025
+ const source = str2(raw.source);
1026
+ if (source !== void 0) input.source = source;
1027
+ const path = str2(raw.transcript_path);
1028
+ const agentPath = str2(raw.agent_transcript_path);
1029
+ if (path !== void 0 || agentPath !== void 0) {
1030
+ input.transcript = {};
1031
+ if (path !== void 0) input.transcript.path = path;
1032
+ if (agentPath !== void 0) input.transcript.agentPath = agentPath;
1033
+ }
1034
+ if (event === "tool.before" || event === "tool.after") {
1035
+ const name = str2(raw.tool_name) ?? "";
1036
+ const tool = canonicalTool2(name, isRecord3(raw.tool_input) ? raw.tool_input : {});
1037
+ const callId = str2(raw.tool_use_id);
1038
+ if (callId !== void 0) tool.callId = callId;
1039
+ if (event === "tool.after") {
1040
+ if (native === "PostToolUseFailure") {
1041
+ tool.ok = false;
1042
+ if (typeof raw.error === "string") tool.result = { error: raw.error };
1043
+ else {
1044
+ const result = toolResult(raw.error);
1045
+ if (result !== void 0) tool.result = result;
1046
+ }
1047
+ } else {
1048
+ const result = toolResult(raw.tool_response);
1049
+ if (result !== void 0) tool.result = result;
1050
+ tool.ok = !(tool.kind === "shell" && hasErrorMarker((result?.stdout ?? "") + "\n" + (result?.stderr ?? "")));
1051
+ }
1052
+ if (typeof raw.is_interrupt === "boolean") tool.interrupted = raw.is_interrupt;
1053
+ }
1054
+ input.tool = tool;
1055
+ }
1056
+ return input;
1057
+ }
1058
+ function encode2(emit, input) {
1059
+ if (emit === null || emit.context === void 0 || emit.context.length === 0) return null;
1060
+ return {
1061
+ hookSpecificOutput: {
1062
+ hookEventName: input.native.event,
1063
+ additionalContext: emit.context.slice(0, CONTEXT_MAX)
1064
+ }
1065
+ };
1066
+ }
1067
+ function httpHandler(url, token, timeoutSeconds) {
1068
+ return {
1069
+ type: "http",
1070
+ url,
1071
+ headers: { Authorization: `Bearer ${token}` },
1072
+ timeout: timeoutSeconds
1073
+ };
1074
+ }
1075
+ function commandHandler2(shimPath, timeoutSeconds) {
1076
+ return {
1077
+ type: "command",
1078
+ command: `node ${JSON.stringify(shimPath)} --harness claude`,
1079
+ timeout: timeoutSeconds
1080
+ };
1081
+ }
1082
+ var registrar2 = {
1083
+ configPath(home) {
1084
+ return claudeSettingsPath(home);
1085
+ },
1086
+ /**
1087
+ * 9 `http` entries and 2 `command` entries (02-redesign.md §4). SessionStart
1088
+ * and UserPromptSubmit run the shim because every turn begins with a prompt:
1089
+ * the daemon is then up before any tool-path fire of that turn.
1090
+ */
1091
+ plan({ url, token, shimPath, timeoutSeconds }) {
1092
+ const http = [httpHandler(url, token, timeoutSeconds)];
1093
+ const command = [commandHandler2(shimPath, timeoutSeconds)];
1094
+ return [
1095
+ { event: "SessionStart", matcher: SESSION_START_MATCHER, hooks: command },
1096
+ { event: "UserPromptSubmit", hooks: command },
1097
+ // ONE entry for both web kinds. The arms are separate; the harness entry
1098
+ // is not, because a settings file with two PreToolUse entries whose
1099
+ // matchers overlap is two POSTs for one tool call.
1100
+ {
1101
+ event: "PreToolUse",
1102
+ matcher: `${matcherOf(TOOLS.web)}|${matcherOf(TOOLS.fetch)}`,
1103
+ hooks: http
1104
+ },
1105
+ { event: "PreToolUse", matcher: matcherOf(TOOLS.dispatch), hooks: http },
1106
+ {
1107
+ event: "PreToolUse",
1108
+ matcher: `${matcherOf(TOOLS.edit)}|${matcherOf(TOOLS.shell)}`,
1109
+ hooks: http
1110
+ },
1111
+ { event: "PostToolUse", matcher: matcherOf(TOOLS.shell), hooks: http },
1112
+ { event: "PostToolUse", matcher: matcherOf(TOOLS.read), hooks: http },
1113
+ { event: "PostToolUseFailure", matcher: matcherOf(TOOLS.shell), hooks: http },
1114
+ { event: "SubagentStart", hooks: http },
1115
+ { event: "SubagentStop", hooks: http },
1116
+ { event: "Stop", hooks: http }
1117
+ ];
1118
+ },
1119
+ grant: {
1120
+ path: claudeSettingsPath,
1121
+ inspect: inspectClaudeGrant,
1122
+ write: wireFreeVerbAllowlist
1123
+ }
1124
+ };
1125
+ var claudeAdapter = { id: "claude", decode: decode2, encode: encode2, registrar: registrar2 };
1126
+
1127
+ // src/adapters/registry.ts
1128
+ var ADAPTERS = {
1129
+ claude: claudeAdapter,
1130
+ codex: codexAdapter
1131
+ };
1132
+
1133
+ // src/lib/harness-hooks.ts
1134
+ import { chmod as chmod2, lstat as lstat2, readFile as readFile2, realpath as realpath2, stat as stat3 } from "node:fs/promises";
1135
+ import { resolve } from "node:path";
1136
+
1137
+ // src/daemon/control.ts
1138
+ import { randomBytes } from "node:crypto";
1139
+ import { copyFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
1140
+ import { dirname as dirname2, join as join5 } from "node:path";
1141
+ import { fileURLToPath } from "node:url";
1142
+
1143
+ // src/hooks/shim.ts
1144
+ import { spawn as spawn2 } from "node:child_process";
1145
+ import {
1146
+ appendFileSync,
1147
+ closeSync,
1148
+ existsSync,
1149
+ mkdirSync,
1150
+ openSync,
1151
+ readFileSync,
1152
+ statSync,
1153
+ unlinkSync,
1154
+ writeFileSync
1155
+ } from "node:fs";
1156
+ function missingRoutes(h, required) {
1157
+ const served = new Set(Array.isArray(h.harnesses) ? h.harnesses : []);
1158
+ return required.filter((harness) => !served.has(harness));
1159
+ }
1160
+ function readPid(dataDir2) {
1161
+ try {
1162
+ const raw = JSON.parse(readFileSync(daemonPidPath(dataDir2), "utf8"));
1163
+ if (typeof raw.pid === "number" && typeof raw.port === "number" && typeof raw.started_at === "number" && typeof raw.data_dir === "string") {
1164
+ return { pid: raw.pid, port: raw.port, started_at: raw.started_at, data_dir: raw.data_dir };
1165
+ }
1166
+ return null;
1167
+ } catch {
1168
+ return null;
1169
+ }
1170
+ }
1171
+ function readToken(dataDir2) {
1172
+ try {
1173
+ const t = readFileSync(daemonTokenPath(dataDir2), "utf8").trim();
1174
+ return t.length > 0 ? t : null;
1175
+ } catch {
1176
+ return null;
1177
+ }
1178
+ }
1179
+ async function health(port, timeoutMs = HEALTH_MS) {
1180
+ try {
1181
+ const res = await fetch(`http://127.0.0.1:${port}/health`, {
1182
+ signal: AbortSignal.timeout(timeoutMs)
1183
+ });
1184
+ if (!res.ok) return null;
1185
+ const body = await res.json();
1186
+ if (typeof body.pid !== "number" || typeof body.data_dir !== "string") return null;
1187
+ return body;
1188
+ } catch {
1189
+ return null;
1190
+ }
1191
+ }
1192
+ function daemonEnv(dataDir2, env = process.env) {
1193
+ const keep = [
1194
+ "PATH",
1195
+ "HOME",
1196
+ "USERPROFILE",
1197
+ "TMPDIR",
1198
+ "TEMP",
1199
+ "TMP",
1200
+ "HTTP_PROXY",
1201
+ "HTTPS_PROXY",
1202
+ "NO_PROXY",
1203
+ "http_proxy",
1204
+ "https_proxy",
1205
+ "no_proxy"
1206
+ ];
1207
+ const out = {};
1208
+ for (const k of keep) if (env[k] !== void 0) out[k] = env[k];
1209
+ out.TENJIN_DATA_DIR = dataDir2;
1210
+ return out;
1211
+ }
1212
+ function inBackoff(dataDir2, now = Date.now()) {
1213
+ try {
1214
+ return now - statSync(daemonSpawnPath(dataDir2)).mtimeMs < SPAWN_BACKOFF_MS;
1215
+ } catch {
1216
+ return false;
1217
+ }
1218
+ }
1219
+ function spawnDaemon(dataDir2, env = process.env) {
1220
+ mkdirSync(dataDir2, { recursive: true, mode: 448 });
1221
+ writeFileSync(daemonSpawnPath(dataDir2), "");
1222
+ const log = openSync(daemonLogPath(dataDir2), "a");
1223
+ try {
1224
+ const child = spawn2(process.execPath, [daemonBundlePath(dataDir2)], {
1225
+ detached: true,
1226
+ stdio: ["ignore", log, log],
1227
+ env: daemonEnv(dataDir2, env),
1228
+ // Never the hook's cwd: a detached daemon would pin a project worktree.
1229
+ cwd: dataDir2,
1230
+ windowsHide: true
1231
+ });
1232
+ child.unref();
1233
+ } finally {
1234
+ closeSync(log);
1235
+ }
1236
+ }
1237
+ function sleep(ms) {
1238
+ return new Promise((r) => setTimeout(r, ms));
1239
+ }
1240
+ async function ensureDaemon(dataDir2, opts = {}) {
1241
+ const now = opts.now ?? (() => Date.now());
1242
+ const pid = readPid(dataDir2);
1243
+ if (pid !== null) {
1244
+ const h = await health(pid.port);
1245
+ if (h !== null && h.data_dir === dataDir2) return { ok: true, health: h, spawned: false };
1246
+ }
1247
+ if (!existsSync(daemonBundlePath(dataDir2)))
1248
+ return { ok: false, reason: "no bundle; run `tenjin daemon start`" };
1249
+ if (inBackoff(dataDir2, now())) return { ok: false, reason: "spawn backoff" };
1250
+ try {
1251
+ spawnDaemon(dataDir2, opts.env);
1252
+ } catch (err) {
1253
+ return {
1254
+ ok: false,
1255
+ reason: `spawn failed: ${err instanceof Error ? err.message : String(err)}`
1256
+ };
1257
+ }
1258
+ const budget = opts.spawnMs ?? SPAWN_MS;
1259
+ const until = now() + budget;
1260
+ const settled = async () => {
1261
+ const fresh = readPid(dataDir2);
1262
+ if (fresh === null || pid !== null && fresh.started_at === pid.started_at) return null;
1263
+ const h = await health(fresh.port);
1264
+ return h !== null && h.data_dir === dataDir2 ? h : null;
1265
+ };
1266
+ const won = (h) => {
1267
+ try {
1268
+ unlinkSync(daemonSpawnPath(dataDir2));
1269
+ } catch {
1270
+ }
1271
+ return { ok: true, health: h, spawned: true };
1272
+ };
1273
+ while (now() < until) {
1274
+ await sleep(20);
1275
+ const h = await settled();
1276
+ if (h !== null) return won(h);
1277
+ }
1278
+ const late = await settled();
1279
+ if (late !== null) return won(late);
1280
+ return { ok: false, reason: `spawned but not healthy within ${budget} ms` };
1281
+ }
1282
+
1283
+ // src/daemon/control.ts
1284
+ var INSTALL_SPAWN_MS = 5e3;
1285
+ var BUNDLES = {
1286
+ "tenjin-daemon.mjs": daemonBundlePath,
1287
+ "tenjin-shim.mjs": shimBundlePath,
1288
+ "tenjin-vitest-reporter.mjs": vitestReporterPath
1289
+ };
1290
+ function defaultBundleDir() {
1291
+ return dirname2(fileURLToPath(import.meta.url));
1292
+ }
1293
+ function installDaemonFiles(dataDir2, bundleDir) {
1294
+ const written = [];
1295
+ mkdirSync2(hooksDir(dataDir2), { recursive: true, mode: 448 });
1296
+ for (const [name, target] of Object.entries(BUNDLES)) {
1297
+ const src = join5(bundleDir, name);
1298
+ if (!existsSync2(src)) {
1299
+ throw new CliError("INTERNAL", `Daemon bundle missing: ${src}`, {
1300
+ fix: `Reinstall tenjin-cli; the package ships dist/${Object.keys(BUNDLES).join(", dist/")}.`
1301
+ });
1302
+ }
1303
+ const dest = target(dataDir2);
1304
+ const staged = `${dest}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
1305
+ copyFileSync(src, staged);
1306
+ renameSync(staged, dest);
1307
+ written.push(dest);
1308
+ }
1309
+ if (readToken(dataDir2) === null) {
1310
+ writeFileSync2(daemonTokenPath(dataDir2), randomBytes(32).toString("hex"), { mode: 384 });
1311
+ written.push(daemonTokenPath(dataDir2));
1312
+ }
1313
+ return { written };
1314
+ }
1315
+ function alive(pid, kill) {
1316
+ try {
1317
+ kill(pid, 0);
1318
+ return true;
1319
+ } catch {
1320
+ return false;
1321
+ }
1322
+ }
1323
+ async function stopDaemon(dataDir2, deps = {}) {
1324
+ const kill = deps.kill ?? ((pid, sig) => process.kill(pid, sig));
1325
+ const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1326
+ const now = deps.now ?? (() => Date.now());
1327
+ const rec = readPid(dataDir2);
1328
+ if (rec === null || !alive(rec.pid, kill)) {
1329
+ if (rec !== null) rmSync(daemonPidPath(dataDir2), { force: true });
1330
+ return { state: "not-running" };
1331
+ }
1332
+ const h = await health(rec.port);
1333
+ if (h !== null && (h.pid !== rec.pid || h.data_dir !== dataDir2)) {
1334
+ rmSync(daemonPidPath(dataDir2), { force: true });
1335
+ return { state: "not-running" };
1336
+ }
1337
+ if (h === null) return { state: "unconfirmed", pid: rec.pid };
1338
+ kill(rec.pid, "SIGTERM");
1339
+ const until = now() + STOP_GRACE_MS;
1340
+ while (now() < until) {
1341
+ await sleep2(50);
1342
+ if (!alive(rec.pid, kill)) return { state: "stopped", pid: rec.pid };
1343
+ }
1344
+ try {
1345
+ kill(rec.pid, "SIGKILL");
1346
+ } catch {
1347
+ }
1348
+ rmSync(daemonPidPath(dataDir2), { force: true });
1349
+ return { state: "killed", pid: rec.pid };
1350
+ }
1351
+ async function startDaemon(dataDir2, deps = {}) {
1352
+ const { written } = installDaemonFiles(dataDir2, deps.bundleDir ?? defaultBundleDir());
1353
+ const rec = readPid(dataDir2);
1354
+ const running = rec === null ? null : await health(rec.port);
1355
+ let replaced = null;
1356
+ let reason;
1357
+ let short = [];
1358
+ let unconfirmed = null;
1359
+ if (running !== null && running.data_dir === dataDir2) {
1360
+ short = missingRoutes(running, deps.requires ?? []);
1361
+ const stale = running.version !== package_default.version ? "older-build" : short.length > 0 ? "missing-routes" : void 0;
1362
+ if (stale !== void 0) {
1363
+ const stopped = await stopDaemon(dataDir2, deps);
1364
+ if (stopped.state === "stopped" || stopped.state === "killed") {
1365
+ replaced = rec;
1366
+ reason = stale;
1367
+ } else if (stopped.state === "unconfirmed") unconfirmed = stopped.pid ?? null;
1368
+ }
1369
+ }
1370
+ const ensured = await ensureDaemon(dataDir2, {
1371
+ ...deps.env ? { env: deps.env } : {},
1372
+ spawnMs: deps.spawnMs ?? INSTALL_SPAWN_MS,
1373
+ ...deps.now ? { now: deps.now } : {}
1374
+ });
1375
+ if (!ensured.ok) {
1376
+ throw new CliError("INTERNAL", `Daemon did not start: ${ensured.reason}`, {
1377
+ fix: `Read ${join5(dataDir2, "daemon.log")}; if it names a port conflict, set \`tenjin config set loop.port <n>\`.`
1378
+ });
1379
+ }
1380
+ const stillShort = missingRoutes(ensured.health, deps.requires ?? []);
1381
+ if (stillShort.length > 0) {
1382
+ throw new CliError(
1383
+ "INTERNAL",
1384
+ `The daemon on 127.0.0.1:${ensured.health.port} (v${ensured.health.version}) has no route for ${stillShort.join(", ")}, so its hook entries would answer 404.`,
1385
+ { fix: "Run `tenjin daemon stop`, then re-run `tenjin install`." }
1386
+ );
1387
+ }
1388
+ return {
1389
+ health: ensured.health,
1390
+ spawned: ensured.spawned,
1391
+ replaced,
1392
+ ...reason !== void 0 ? { replacedReason: reason } : {},
1393
+ ...reason === "missing-routes" ? { missingRoutes: short } : {},
1394
+ unconfirmed,
1395
+ written
1396
+ };
1397
+ }
1398
+
1399
+ // src/lib/harness-hooks.ts
1400
+ var OUR_HOOK_FILES = ["tenjin-daemon.mjs", "tenjin-shim.mjs"];
1401
+ var OUR_HOOK_COMMAND = "tenjin hook ";
1402
+ var LOOP_URL_RE = new RegExp(`^http://127\\.0\\.0\\.1:\\d+/hook/(?:${HARNESSES.join("|")})$`);
1403
+ var HOOK_TIMEOUT_SECONDS = HARNESS_MS / 1e3;
1404
+ function skip2(reason, args) {
1405
+ return {
1406
+ harness: args.harness,
1407
+ ...args.path !== void 0 ? { path: args.path } : {},
1408
+ hooksDir: args.hooksDir,
1409
+ entries: 0,
1410
+ wrote: false,
1411
+ skipped: reason,
1412
+ ...args.warning !== void 0 ? { warning: args.warning } : {},
1413
+ ...args.fix !== void 0 ? { fix: args.fix } : {}
1414
+ };
1415
+ }
1416
+ function fixFor2(reason) {
1417
+ switch (reason) {
1418
+ case "declined":
1419
+ case "dry-run":
1420
+ return "Wire them with `tenjin install`.";
1421
+ case "daemon-down":
1422
+ return "Run `tenjin daemon start`, then re-run `tenjin install`.";
1423
+ case "changed-since-read":
1424
+ return "Another process changed the file mid-run; re-run `tenjin install`.";
1425
+ case "unwritable":
1426
+ return "The daemon, its bundles and the skills are already in place; only the hooks file could not be written. Fix its permissions (or its directory\u2019s), then re-run `tenjin install`.";
1427
+ default:
1428
+ return "Fix the reported file, then re-run `tenjin install`.";
1429
+ }
1430
+ }
1431
+ function isPlainObject2(value) {
1432
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1433
+ }
1434
+ function ownsHandler(handler, dataDir2) {
1435
+ if (!isPlainObject2(handler)) return false;
1436
+ const url = handler.url;
1437
+ if (typeof url === "string" && LOOP_URL_RE.test(url)) return true;
1438
+ const command = handler.command;
1439
+ if (typeof command !== "string") return false;
1440
+ if (command.includes(OUR_HOOK_COMMAND)) return true;
1441
+ if (OUR_HOOK_FILES.some((file) => command.includes(file))) return true;
1442
+ return command.includes(hooksDir(resolve(dataDir2)));
1443
+ }
1444
+ function ownsHookEntry(entry, dataDir2) {
1445
+ if (!isPlainObject2(entry)) return false;
1446
+ const handlers = entry.hooks;
1447
+ if (!Array.isArray(handlers)) return false;
1448
+ return handlers.some((h) => ownsHandler(h, dataDir2));
1449
+ }
1450
+ function pruneOurHandlers(entry, dataDir2) {
1451
+ if (!isPlainObject2(entry)) return entry;
1452
+ const handlers = entry.hooks;
1453
+ if (!Array.isArray(handlers)) return entry;
1454
+ const kept = handlers.filter((h) => !ownsHandler(h, dataDir2));
1455
+ if (kept.length === handlers.length) return entry;
1456
+ return kept.length === 0 ? null : { ...entry, hooks: kept };
1457
+ }
1458
+ function pruneHooks(hooks, dataDir2) {
1459
+ const next = {};
1460
+ const removed = [];
1461
+ for (const [event, value] of Object.entries(hooks)) {
1462
+ if (!Array.isArray(value)) {
1463
+ next[event] = value;
1464
+ continue;
1465
+ }
1466
+ const kept = value.map((e) => pruneOurHandlers(e, dataDir2)).filter((e) => e !== null);
1467
+ if (kept.length !== value.length) removed.push(event);
1468
+ const emptiedByUs = kept.length === 0 && value.length > 0;
1469
+ if (!emptiedByUs) next[event] = kept;
1470
+ }
1471
+ return { next, removed };
1472
+ }
1473
+ async function inspectHooksFile(declaredPath) {
1474
+ const entry = await lstat2(declaredPath).catch(() => null);
1475
+ let path = declaredPath;
1476
+ if (entry !== null) {
1477
+ try {
1478
+ path = await realpath2(declaredPath);
1479
+ } catch (err) {
1480
+ return {
1481
+ refusal: {
1482
+ reason: "unresolvable",
1483
+ path: declaredPath,
1484
+ message: `${declaredPath} could not be resolved (${err.message}); its "hooks" key was left exactly as it is.`
1485
+ }
1486
+ };
1487
+ }
1488
+ }
1489
+ let settings = {};
1490
+ let raw = null;
1491
+ if (entry !== null) {
1492
+ try {
1493
+ raw = await readFile2(path, "utf8");
1494
+ } catch (err) {
1495
+ return {
1496
+ refusal: {
1497
+ reason: "unreadable",
1498
+ path,
1499
+ message: `${path} could not be read (${err.message}); no hooks were registered.`
1500
+ }
1501
+ };
1502
+ }
1503
+ let parsed;
1504
+ try {
1505
+ parsed = JSON.parse(raw);
1506
+ } catch (err) {
1507
+ return {
1508
+ refusal: {
1509
+ reason: "unparsable",
1510
+ path,
1511
+ message: `${path} is not valid JSON (${err.message}); its "hooks" key was left exactly as it is.`
1512
+ }
1513
+ };
1514
+ }
1515
+ if (!isPlainObject2(parsed)) {
1516
+ return {
1517
+ refusal: {
1518
+ reason: "unexpected-shape",
1519
+ path,
1520
+ message: `${path} is not a JSON object; its "hooks" key was left exactly as it is.`
1521
+ }
1522
+ };
1523
+ }
1524
+ settings = parsed;
1525
+ }
1526
+ const hooksValue = settings.hooks;
1527
+ if (hooksValue !== void 0 && !isPlainObject2(hooksValue)) {
1528
+ return {
1529
+ refusal: {
1530
+ reason: "unexpected-shape",
1531
+ path,
1532
+ message: `${path} has a "hooks" key that is not an object; its "hooks" key was left exactly as it is.`
1533
+ }
1534
+ };
1535
+ }
1536
+ const hooks = {};
1537
+ for (const [event, list] of Object.entries(hooksValue ?? {})) {
1538
+ if (!Array.isArray(list)) {
1539
+ return {
1540
+ refusal: {
1541
+ reason: "unexpected-shape",
1542
+ path,
1543
+ message: `${path} has a "hooks.${event}" that is not an array of entries; its "hooks" key was left exactly as it is.`
1544
+ }
1545
+ };
1546
+ }
1547
+ hooks[event] = list;
1548
+ }
1549
+ return { path, raw, settings, hooks };
1550
+ }
1551
+ async function readHooksObject(path) {
1552
+ try {
1553
+ const parsed = JSON.parse(await readFile2(path, "utf8"));
1554
+ const hooks = isPlainObject2(parsed) ? parsed.hooks : void 0;
1555
+ return isPlainObject2(hooks) ? hooks : null;
1556
+ } catch {
1557
+ return null;
1558
+ }
1559
+ }
1560
+ function urlPort(url) {
1561
+ try {
1562
+ const port = Number(new URL(url).port);
1563
+ return Number.isFinite(port) && port > 0 ? port : null;
1564
+ } catch {
1565
+ return null;
1566
+ }
1567
+ }
1568
+ async function registeredHooks(adapter, homeDir, dataDir2, env = process.env) {
1569
+ const path = adapter.registrar.configPath(homeDir, env);
1570
+ const hooks = await readHooksObject(path);
1571
+ const out = { path, entries: 0, port: null, handlers: [] };
1572
+ if (hooks === null) return out;
1573
+ for (const [event, list] of Object.entries(hooks)) {
1574
+ if (!Array.isArray(list)) continue;
1575
+ list.forEach((entry, groupIndex) => {
1576
+ if (!ownsHookEntry(entry, dataDir2)) return;
1577
+ out.entries += 1;
1578
+ entry.hooks.forEach((handler, handlerIndex) => {
1579
+ if (!ownsHandler(handler, dataDir2)) return;
1580
+ out.handlers.push({ event, groupIndex, handlerIndex });
1581
+ if (!isPlainObject2(handler) || typeof handler.url !== "string") return;
1582
+ out.port ??= urlPort(handler.url);
1583
+ });
1584
+ });
1585
+ }
1586
+ return out;
1587
+ }
1588
+ async function writeHooks(opts) {
1589
+ const { adapter, homeDir, dataDir: dataDir2 } = opts;
1590
+ const env = opts.env ?? process.env;
1591
+ const harness = adapter.id;
1592
+ const dir = hooksDir(dataDir2);
1593
+ const declaredPath = opts.settingsPath ?? adapter.registrar.configPath(homeDir, env);
1594
+ const steps = adapter.registrar.activation?.(declaredPath);
1595
+ const activation = steps !== void 0 ? { activation: steps } : {};
1596
+ if (opts.plan !== void 0)
1597
+ return writePlainEntries(opts, opts.plan, declaredPath, dir, activation);
1598
+ let started;
1599
+ try {
1600
+ started = await (opts.start ?? startDaemon)(dataDir2, {
1601
+ ...opts.bundleDir !== void 0 ? { bundleDir: opts.bundleDir } : {},
1602
+ // The entries this call is about to write all post to this harness's
1603
+ // route, so a running daemon that has no such route is replaced before
1604
+ // they name it, whatever its version says (tenjin-agent#342).
1605
+ requires: [harness]
1606
+ });
1607
+ } catch (err) {
1608
+ return skip2("daemon-down", {
1609
+ harness,
1610
+ path: declaredPath,
1611
+ hooksDir: dir,
1612
+ warning: `${err instanceof Error ? err.message : String(err)}; no hook entry was written, so nothing points at a daemon that is not there.`,
1613
+ fix: fixFor2("daemon-down")
1614
+ });
1615
+ }
1616
+ const pid = readPid(dataDir2);
1617
+ const token = readToken(dataDir2);
1618
+ if (pid === null || token === null) {
1619
+ return skip2("daemon-down", {
1620
+ harness,
1621
+ path: declaredPath,
1622
+ hooksDir: dir,
1623
+ warning: `The daemon answered but left no ${pid === null ? "daemon.pid" : "daemon.token"} under ${dataDir2}, so no hook entry could name it.`,
1624
+ fix: fixFor2("daemon-down")
1625
+ });
1626
+ }
1627
+ const url = `http://127.0.0.1:${pid.port}/hook/${harness}`;
1628
+ const found = await inspectHooksFile(declaredPath);
1629
+ if ("refusal" in found) {
1630
+ return skip2(found.refusal.reason, {
1631
+ harness,
1632
+ path: found.refusal.path,
1633
+ hooksDir: dir,
1634
+ warning: found.refusal.message,
1635
+ fix: fixFor2(found.refusal.reason)
1636
+ });
1637
+ }
1638
+ const { path, raw, settings, hooks } = found;
1639
+ const plan = adapter.registrar.plan({
1640
+ url,
1641
+ token,
1642
+ shimPath: shimBundlePath(dataDir2),
1643
+ timeoutSeconds: HOOK_TIMEOUT_SECONDS
1644
+ });
1645
+ const planned = /* @__PURE__ */ new Map();
1646
+ for (const item of plan) {
1647
+ if (!isPlainObject2(item) || typeof item.event !== "string") continue;
1648
+ const { event, ...entry } = item;
1649
+ const list = planned.get(event) ?? [];
1650
+ list.push(entry);
1651
+ planned.set(event, list);
1652
+ }
1653
+ const nextHooks = pruneHooks(hooks, dataDir2).next;
1654
+ for (const [event, mine] of planned) {
1655
+ const kept = nextHooks[event];
1656
+ nextHooks[event] = Array.isArray(kept) ? [...kept, ...mine] : mine;
1657
+ }
1658
+ const next = `${JSON.stringify({ ...settings, hooks: nextHooks }, null, 2)}
1659
+ `;
1660
+ const carriesUrl = JSON.stringify(plan).includes(url);
1661
+ const result = {
1662
+ harness,
1663
+ path,
1664
+ hooksDir: dir,
1665
+ entries: plan.length,
1666
+ wrote: next !== raw,
1667
+ daemon: { pid: started.health.pid, port: pid.port, version: started.health.version },
1668
+ ...carriesUrl ? { url } : {},
1669
+ ...activation
1670
+ };
1671
+ if (next === raw) {
1672
+ await tightenFile(path);
1673
+ return result;
1674
+ }
1675
+ if (await readFile2(path, "utf8").catch(() => null) !== raw) {
1676
+ return skip2("changed-since-read", {
1677
+ harness,
1678
+ path,
1679
+ hooksDir: dir,
1680
+ warning: `${path} changed while it was being updated, so no hooks were registered. Re-run \`tenjin install\`.`,
1681
+ fix: fixFor2("changed-since-read")
1682
+ });
1683
+ }
1684
+ try {
1685
+ await writeFileAtomic(path, next, { mode: 384 });
1686
+ } catch (err) {
1687
+ return skip2("unwritable", {
1688
+ harness,
1689
+ path,
1690
+ hooksDir: dir,
1691
+ warning: `${path} could not be written (${err instanceof Error ? err.message : String(err)}); no hook entry was registered.`,
1692
+ fix: fixFor2("unwritable")
1693
+ });
1694
+ }
1695
+ return result;
1696
+ }
1697
+ async function tightenFile(path) {
1698
+ const found = await stat3(path).catch(() => null);
1699
+ if (found === null || (found.mode & 63) === 0) return;
1700
+ await chmod2(path, 384).catch(() => void 0);
1701
+ }
1702
+ async function writePlainEntries(opts, plan, declaredPath, dir, activation) {
1703
+ const harness = opts.adapter.id;
1704
+ const found = await inspectHooksFile(declaredPath);
1705
+ if ("refusal" in found) {
1706
+ return skip2(found.refusal.reason, {
1707
+ harness,
1708
+ path: found.refusal.path,
1709
+ hooksDir: dir,
1710
+ warning: found.refusal.message,
1711
+ fix: fixFor2(found.refusal.reason)
1712
+ });
1713
+ }
1714
+ const { path, raw, settings, hooks } = found;
1715
+ const nextHooks = pruneHooks(hooks, opts.dataDir).next;
1716
+ for (const [event, mine] of groupPlan(plan)) {
1717
+ const kept = nextHooks[event];
1718
+ nextHooks[event] = Array.isArray(kept) ? [...kept, ...mine] : mine;
1719
+ }
1720
+ const next = `${JSON.stringify({ ...settings, hooks: nextHooks }, null, 2)}
1721
+ `;
1722
+ const result = {
1723
+ harness,
1724
+ path,
1725
+ hooksDir: dir,
1726
+ entries: plan.length,
1727
+ wrote: next !== raw,
1728
+ ...activation
1729
+ };
1730
+ if (next === raw) {
1731
+ await tightenFile(path);
1732
+ return result;
1733
+ }
1734
+ if (await readFile2(path, "utf8").catch(() => null) !== raw) {
1735
+ return skip2("changed-since-read", {
1736
+ harness,
1737
+ path,
1738
+ hooksDir: dir,
1739
+ warning: `${path} changed while it was being updated, so no hooks were registered. Re-run \`tenjin install\`.`,
1740
+ fix: fixFor2("changed-since-read")
1741
+ });
1742
+ }
1743
+ try {
1744
+ await writeFileAtomic(path, next, { mode: 384 });
1745
+ } catch (err) {
1746
+ return skip2("unwritable", {
1747
+ harness,
1748
+ path,
1749
+ hooksDir: dir,
1750
+ warning: `${path} could not be written (${err instanceof Error ? err.message : String(err)}); no hook entry was registered.`,
1751
+ fix: fixFor2("unwritable")
1752
+ });
1753
+ }
1754
+ return result;
1755
+ }
1756
+ function groupPlan(plan) {
1757
+ const planned = /* @__PURE__ */ new Map();
1758
+ for (const item of plan) {
1759
+ if (!isPlainObject2(item) || typeof item.event !== "string") continue;
1760
+ const { event, ...entry } = item;
1761
+ const list = planned.get(event) ?? [];
1762
+ list.push(entry);
1763
+ planned.set(event, list);
1764
+ }
1765
+ return planned;
1766
+ }
1767
+
1768
+ export {
1769
+ claudeSettingsPath,
1770
+ MODE_GATED_RULES,
1771
+ retractModeGatedRules,
1772
+ wireFreeVerbAllowlist,
1773
+ inspectFreeVerbRules,
1774
+ appendAllowlistRules,
1775
+ claudeAdapter,
1776
+ ADAPTERS,
1777
+ ownsHookEntry,
1778
+ pruneOurHandlers,
1779
+ pruneHooks,
1780
+ inspectHooksFile,
1781
+ registeredHooks,
1782
+ writeHooks
1783
+ };
1784
+ //# sourceMappingURL=chunk-IOIHYOU4.js.map