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,1265 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ isPublicAddress
4
+ } from "./chunk-LAIZ2AQA.js";
5
+ import {
6
+ requestToolAccess
7
+ } from "./chunk-S2NRVRPF.js";
8
+ import {
9
+ ROUTER_PATH,
10
+ requestDecision
11
+ } from "./chunk-UY2TOI3B.js";
12
+ import {
13
+ rememberingBalanceReader
14
+ } from "./chunk-QHILSA6G.js";
15
+ import {
16
+ evaluateSpendPolicy,
17
+ readSpendSummary,
18
+ spentOf
19
+ } from "./chunk-U2ATFMKZ.js";
20
+ import {
21
+ REQUEST_TOOL
22
+ } from "./chunk-TGLKKLQG.js";
23
+ import {
24
+ mask
25
+ } from "./chunk-7QKHZQKW.js";
26
+ import {
27
+ augmentOf,
28
+ bindDecision,
29
+ claimQuery,
30
+ claimRedirect,
31
+ markAugment,
32
+ markOffered,
33
+ newCallId,
34
+ noteSession,
35
+ pruneProgress,
36
+ pruneSessions,
37
+ redirectClaimed,
38
+ sessionDir,
39
+ wasOffered,
40
+ writeProgress
41
+ } from "./chunk-QF4SSCQV.js";
42
+ import {
43
+ composeUserAgent
44
+ } from "./chunk-2AQO4YDI.js";
45
+ import {
46
+ routerSettings
47
+ } from "./chunk-C363JZN2.js";
48
+ import "./chunk-2I4QTOLB.js";
49
+ import {
50
+ resolveContextSettings
51
+ } from "./chunk-IOB7URFH.js";
52
+ import {
53
+ parseUsdToAtomic,
54
+ toMoney
55
+ } from "./chunk-O2JYBOUO.js";
56
+ import {
57
+ external_exports,
58
+ isSameDeployment,
59
+ loadRawConfig,
60
+ resolveExperimentalBazaar,
61
+ resolveSettings
62
+ } from "./chunk-W3LVZ2EN.js";
63
+ import "./chunk-RCJQARZF.js";
64
+ import "./chunk-JLEF5WHM.js";
65
+ import {
66
+ walletPath
67
+ } from "./chunk-K6AXXYCG.js";
68
+ import "./chunk-ZXTAQYNA.js";
69
+
70
+ // src/router/hooks.ts
71
+ import { readFile } from "node:fs/promises";
72
+ import { homedir } from "node:os";
73
+
74
+ // src/router/context.ts
75
+ import { open } from "node:fs/promises";
76
+ import { isIP } from "node:net";
77
+ import { dirname, join } from "node:path";
78
+ var MAX_HISTORY = 6;
79
+ var MAX_PACKET_BYTES = 16 * 1024;
80
+ var MAX_MESSAGE_CHARS = 16e3;
81
+ var MAX_TRANSCRIPT_BYTES = 4e6;
82
+ var MAX_LITERAL_URLS = 8;
83
+ var MAX_LITERAL_URL_CHARS = 2e3;
84
+ var MAX_PENDING_CHARS = 4e3;
85
+ var MAX_OUTCOME_ERROR_CHARS = 1e3;
86
+ var MASK_MARGIN = 4096;
87
+ function subjectOf(pending) {
88
+ return "query" in pending ? pending.query : "url" in pending ? pending.url : pending.question;
89
+ }
90
+ function withSubject(pending, subject) {
91
+ if ("query" in pending) return { tool: pending.tool, query: subject };
92
+ if ("url" in pending) return { tool: pending.tool, url: subject };
93
+ return { tool: pending.tool, question: subject };
94
+ }
95
+ var URL_RE = /\bhttps?:\/\/[^\s<>"'`)\]]+/gi;
96
+ function literalUrlsIn(text) {
97
+ const found = /* @__PURE__ */ new Set();
98
+ for (const match of text.matchAll(URL_RE)) {
99
+ const candidate = match[0].replace(/[.,;:!?]+$/, "");
100
+ try {
101
+ const normalized = new URL(candidate).toString();
102
+ if (normalized.length <= MAX_LITERAL_URL_CHARS) found.add(normalized);
103
+ } catch {
104
+ continue;
105
+ }
106
+ if (found.size >= MAX_LITERAL_URLS) break;
107
+ }
108
+ return [...found];
109
+ }
110
+ function fit(packet) {
111
+ const size = (value) => Buffer.byteLength(JSON.stringify(value));
112
+ const next = { ...packet, history: packet.history.slice(-MAX_HISTORY) };
113
+ while (next.history.length > 0 && size(next) > MAX_PACKET_BYTES) {
114
+ next.history = next.history.slice(1);
115
+ }
116
+ while (next.literalUrls.length > 0 && size(next) > MAX_PACKET_BYTES) {
117
+ next.literalUrls = next.literalUrls.slice(0, -1);
118
+ }
119
+ while (size(next) > MAX_PACKET_BYTES && next.current.text.length > 1) {
120
+ const over = size(next) - MAX_PACKET_BYTES;
121
+ const keep = Math.max(1, next.current.text.length - Math.max(over, 1));
122
+ next.current = { ...next.current, text: next.current.text.slice(0, keep) };
123
+ }
124
+ return next;
125
+ }
126
+ function seal(packet) {
127
+ const pending = packet.pendingCall;
128
+ const subject = pending === void 0 ? "" : subjectOf(pending);
129
+ const sealedSubject = maskWithin(subject, MAX_PENDING_CHARS);
130
+ const bound = (text) => maskWithin(text, MAX_MESSAGE_CHARS).text;
131
+ const sealedCurrent = maskWithin(packet.current.text, MAX_MESSAGE_CHARS);
132
+ const current = sealedCurrent.text;
133
+ const outcome = packet.nativeOutcome;
134
+ const sealed = fit({
135
+ current: { role: packet.current.role, text: current.length > 0 ? current : "(no task text)" },
136
+ history: packet.history.slice(-MAX_HISTORY).map((message) => ({ role: message.role, text: bound(message.text) })).filter((message) => message.text.length > 0),
137
+ literalUrls: packet.literalUrls.filter((url) => !isLocalTarget(url)).map(mask).filter((url) => url.length <= MAX_LITERAL_URL_CHARS),
138
+ historyStatus: packet.historyStatus,
139
+ ...pending === void 0 ? {} : { pendingCall: withSubject(pending, sealedSubject.text) },
140
+ ...outcome === void 0 ? {} : {
141
+ nativeOutcome: {
142
+ ...outcome,
143
+ ...outcome.error !== void 0 ? { error: maskWithin(outcome.error, MAX_OUTCOME_ERROR_CHARS).text } : {}
144
+ }
145
+ }
146
+ });
147
+ return {
148
+ packet: sealed,
149
+ subjectChanged: sealedSubject.changed,
150
+ localTarget: pending !== void 0 && "url" in pending && isLocalTarget(pending.url),
151
+ currentChanged: sealedCurrent.changed,
152
+ localUrl: packet.literalUrls.some(isLocalTarget)
153
+ };
154
+ }
155
+ function maskWithin(text, max) {
156
+ const window = text.slice(0, max + MASK_MARGIN);
157
+ const masked = mask(window);
158
+ const limit = window.length < text.length ? Math.min(max, masked.length - MASK_MARGIN) : max;
159
+ return { text: masked.slice(0, Math.max(0, limit)), changed: masked !== window };
160
+ }
161
+ var LOCAL_NAME = /(?:^|\.)(?:localhost|local)$/i;
162
+ function isLocalTarget(raw) {
163
+ let url;
164
+ try {
165
+ url = new URL(raw);
166
+ } catch {
167
+ return true;
168
+ }
169
+ if (url.protocol !== "http:" && url.protocol !== "https:") return true;
170
+ const host = url.hostname.replace(/^\[|\]$/g, "");
171
+ if (LOCAL_NAME.test(host)) return true;
172
+ return isIP(host) !== 0 && !isPublicAddress(host);
173
+ }
174
+ async function buildPromptPacket(transcriptPath, sessionId, prompt) {
175
+ const trimmed = prompt.trim();
176
+ const text = trimmed.length > 0 ? trimmed : "(empty prompt)";
177
+ const read = await readHistory(transcriptPath, { sessionId });
178
+ return {
179
+ current: { role: "user", text },
180
+ history: read ?? [],
181
+ literalUrls: literalUrlsIn(text),
182
+ historyStatus: read === null ? "unavailable" : "ok"
183
+ };
184
+ }
185
+ async function buildNativePacket(transcriptPath, sessionId, pending, opts = {}) {
186
+ const { agentId, nativeOutcome } = opts;
187
+ const subject = subjectOf(pending);
188
+ const read = await readHistory(transcriptPath, { sessionId });
189
+ const own = agentId === void 0 ? null : await readHistory(subagentTranscriptPath(transcriptPath, sessionId, agentId), {
190
+ sessionId,
191
+ agentId
192
+ });
193
+ const messages = own === null ? read ?? [] : [...read ?? [], ...own];
194
+ const lastUser = messages.map((message, index) => ({ message, index })).filter((entry) => entry.message.role === "user");
195
+ const current = lastUser.at(-1);
196
+ return {
197
+ current: current?.message ?? { role: "user", text: subject },
198
+ history: current === void 0 ? messages : messages.slice(0, current.index),
199
+ literalUrls: literalUrlsIn(`${current?.message.text ?? ""}
200
+ ${subject}`),
201
+ historyStatus: read === null && own === null ? "unavailable" : "ok",
202
+ pendingCall: pending,
203
+ ...nativeOutcome !== void 0 ? { nativeOutcome } : {}
204
+ };
205
+ }
206
+ var PATH_SEGMENT_RE = /^[A-Za-z0-9_-]{1,200}$/;
207
+ function subagentTranscriptPath(transcriptPath, sessionId, agentId) {
208
+ if (transcriptPath === void 0 || transcriptPath.length === 0) return void 0;
209
+ if (!PATH_SEGMENT_RE.test(sessionId) || !PATH_SEGMENT_RE.test(agentId)) return void 0;
210
+ return join(dirname(transcriptPath), sessionId, "subagents", `agent-${agentId}.jsonl`);
211
+ }
212
+ async function readHistory(path, scope) {
213
+ if (path === void 0 || path.length === 0) return null;
214
+ let raw;
215
+ let tail;
216
+ let file;
217
+ try {
218
+ file = await open(path, "r");
219
+ } catch {
220
+ return null;
221
+ }
222
+ try {
223
+ const stat = await file.stat();
224
+ if (!stat.isFile()) return null;
225
+ tail = stat.size > MAX_TRANSCRIPT_BYTES;
226
+ const read = tail ? await readTail(file, stat.size) : await readHead(file);
227
+ if (read === null) return null;
228
+ raw = read;
229
+ } catch {
230
+ return null;
231
+ } finally {
232
+ await file.close();
233
+ }
234
+ try {
235
+ const messages = parseRows(raw, scope);
236
+ if (tail && !messages.some((message) => message.role === "user")) return null;
237
+ return messages;
238
+ } catch {
239
+ return null;
240
+ }
241
+ }
242
+ async function readHead(file) {
243
+ const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);
244
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
245
+ if (bytesRead > MAX_TRANSCRIPT_BYTES) return null;
246
+ return buffer.subarray(0, bytesRead).toString("utf8");
247
+ }
248
+ async function readTail(file, size) {
249
+ const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);
250
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, size - buffer.length);
251
+ const window = buffer.subarray(0, bytesRead);
252
+ const newline = window.indexOf(10);
253
+ return newline === -1 ? null : window.subarray(newline + 1).toString("utf8");
254
+ }
255
+ function parseRows(raw, scope) {
256
+ const { sessionId, agentId } = scope;
257
+ let messages = [];
258
+ for (const line of raw.split("\n")) {
259
+ if (line.trim().length === 0) continue;
260
+ let row;
261
+ try {
262
+ row = JSON.parse(line);
263
+ } catch {
264
+ continue;
265
+ }
266
+ if (row === null || typeof row !== "object" || Array.isArray(row)) continue;
267
+ if (row.type === "system" && row.subtype === "compact_boundary") {
268
+ messages = [];
269
+ continue;
270
+ }
271
+ if (typeof row.sessionId === "string" && row.sessionId !== sessionId) continue;
272
+ if (row.isMeta === true) continue;
273
+ if (agentId === void 0 ? row.isSidechain === true : !ownSidechainRow(row, agentId)) {
274
+ continue;
275
+ }
276
+ if (row.type !== "user" && row.type !== "assistant") continue;
277
+ if (row.sessionId !== sessionId) continue;
278
+ let text;
279
+ try {
280
+ text = textOf(row.message);
281
+ } catch {
282
+ continue;
283
+ }
284
+ if (row.type === "user" && harnessUserRow(row, text)) continue;
285
+ if (text.length > 0) messages.push({ role: row.type, text });
286
+ }
287
+ return messages;
288
+ }
289
+ var LOCAL_COMMAND_OUTPUT = /^\s*<local-command-(?:stdout|stderr)>/;
290
+ var HANDBACK_PREFIXES = [
291
+ "<task-notification>",
292
+ "<agent-message",
293
+ "<teammate-message",
294
+ "<cross-session-message",
295
+ "Another Claude session sent a message"
296
+ ];
297
+ function isHandback(text) {
298
+ const trimmed = text.trimStart();
299
+ return HANDBACK_PREFIXES.some((prefix) => trimmed.startsWith(prefix));
300
+ }
301
+ var HARNESS_ORIGINS = /* @__PURE__ */ new Set(["task-notification", "peer"]);
302
+ function harnessUserRow(row, text) {
303
+ const origin = row.origin;
304
+ if (origin !== null && typeof origin === "object" && HARNESS_ORIGINS.has(origin.kind)) {
305
+ return true;
306
+ }
307
+ return isHandback(text) || LOCAL_COMMAND_OUTPUT.test(text);
308
+ }
309
+ function ownSidechainRow(row, agentId) {
310
+ return row.isSidechain === true && row.agentId === agentId && row.isMeta !== true;
311
+ }
312
+ function textOf(message) {
313
+ if (message === null || typeof message !== "object" || Array.isArray(message)) {
314
+ throw new Error("malformed message");
315
+ }
316
+ const content = message.content;
317
+ if (typeof content === "string") return content;
318
+ if (!Array.isArray(content)) throw new Error("malformed content");
319
+ const parts = [];
320
+ for (const part of content) {
321
+ if (part === null || typeof part !== "object" || typeof part.type !== "string") {
322
+ throw new Error("malformed block");
323
+ }
324
+ const block = part;
325
+ if (block.type !== "text") continue;
326
+ if (typeof block.text !== "string") throw new Error("malformed text block");
327
+ parts.push(block.text);
328
+ }
329
+ return parts.join("\n");
330
+ }
331
+
332
+ // src/router/gate.ts
333
+ var GATE_TIMEOUT_MS = 3500;
334
+
335
+ // src/router/augment.ts
336
+ import { spawn } from "node:child_process";
337
+ import { constants } from "node:fs";
338
+ import { open as open2, rm } from "node:fs/promises";
339
+ import { dirname as dirname2 } from "node:path";
340
+ var DOCS_QUERY_MAX = 500;
341
+ var PREFETCH_TIMEOUT_MS = 12e3;
342
+ var AUGMENT_WAIT_MS = 9e3;
343
+ var MAX_DOCS_CHARS = 1e5;
344
+ var MAX_BODY_BYTES = 1e6;
345
+ var POLL_MS = 100;
346
+ var PREFETCH_SCRIPT = [
347
+ "const { renameSync, rmSync, writeFileSync } = require('node:fs');",
348
+ "const { basename, dirname, join } = require('node:path');",
349
+ "const [url, out, agent, timeout, max] = process.argv.slice(1);",
350
+ "const tmp = join(dirname(out), '.' + basename(out) + '.' + process.pid + '.tmp');",
351
+ // The deadline is a plain timer that answers and exits, not an
352
+ // `AbortSignal.timeout`: that one's timer does not hold the process open, so
353
+ // a stalled lookup let it exit without writing anything.
354
+ "const timer = setTimeout(() => done(0, ''), Number(timeout));",
355
+ "const done = (status, text) => {",
356
+ " clearTimeout(timer);",
357
+ " try {",
358
+ " writeFileSync(tmp, JSON.stringify({ status, text }), { mode: 0o600, flag: 'wx' });",
359
+ " renameSync(tmp, out);",
360
+ " } catch {",
361
+ " try { rmSync(tmp, { force: true }); } catch {}",
362
+ " }",
363
+ " process.exit(0);",
364
+ "};",
365
+ "fetch(url, {",
366
+ " headers: { accept: 'text/plain', 'user-agent': agent },",
367
+ " redirect: 'error',",
368
+ "})",
369
+ " .then(async (res) => done(res.status, res.ok ? (await res.text()).slice(0, Number(max)) : ''))",
370
+ " .catch(() => done(0, ''));"
371
+ ].join("\n");
372
+ function spawnPrefetch(job) {
373
+ const child = spawn(
374
+ process.execPath,
375
+ [
376
+ "-e",
377
+ PREFETCH_SCRIPT,
378
+ job.url,
379
+ job.out,
380
+ job.userAgent,
381
+ String(PREFETCH_TIMEOUT_MS),
382
+ String(MAX_DOCS_CHARS)
383
+ ],
384
+ {
385
+ detached: true,
386
+ stdio: "ignore",
387
+ // Never the session's project: a live child would pin its worktree.
388
+ cwd: dirname2(job.out),
389
+ windowsHide: true
390
+ }
391
+ );
392
+ child.on("error", () => void 0);
393
+ child.unref();
394
+ }
395
+ function docsUrl(endpoint, query, baseUrl) {
396
+ let url;
397
+ let base;
398
+ try {
399
+ url = new URL(endpoint);
400
+ base = new URL(baseUrl);
401
+ } catch {
402
+ return null;
403
+ }
404
+ if (url.username !== "" || url.password !== "") return null;
405
+ if (!isSameDeployment(url.origin, base.origin)) return null;
406
+ url.searchParams.set("query", query.slice(0, DOCS_QUERY_MAX));
407
+ return url.toString();
408
+ }
409
+ async function startAugment(call, offer, baseUrl, deps) {
410
+ if (call.toolUseId === void 0) return false;
411
+ const url = docsUrl(offer.endpoint, call.query, baseUrl);
412
+ if (url === null) return false;
413
+ const now = deps.now?.() ?? Date.now();
414
+ if (!await claimQuery(deps.dataDir, call.sessionId, call.agentId, call.query, now)) {
415
+ return false;
416
+ }
417
+ const out = await markAugment(deps.dataDir, call.sessionId, call.toolUseId, offer.provider, now);
418
+ if (out === null) return false;
419
+ try {
420
+ (deps.prefetch ?? spawnPrefetch)({ url, out, userAgent: composeUserAgent() });
421
+ return true;
422
+ } catch {
423
+ return false;
424
+ }
425
+ }
426
+ async function finishAugment(call, deps) {
427
+ if (call.toolUseId === void 0) return null;
428
+ const now = deps.now?.() ?? Date.now();
429
+ const marker = await augmentOf(deps.dataDir, call.sessionId, call.toolUseId, now);
430
+ if (marker === null) return null;
431
+ if (call.search === null) return { updatedToolOutput: null };
432
+ const budget = Math.min(
433
+ deps.augmentWaitMs ?? AUGMENT_WAIT_MS,
434
+ PREFETCH_TIMEOUT_MS + 1e3 - (now - marker.at)
435
+ );
436
+ const answer = await awaitBody(marker.body, Date.now() + Math.max(0, budget));
437
+ await rm(marker.body, { force: true }).catch(() => void 0);
438
+ const text = answer?.status === 200 ? answer.text.trim() : "";
439
+ if (text.length === 0) return { updatedToolOutput: null };
440
+ return {
441
+ updatedToolOutput: {
442
+ ...call.search.raw,
443
+ results: [docsLine(marker.provider || "library", text), ...call.search.results]
444
+ }
445
+ };
446
+ }
447
+ function docsLine(provider, text) {
448
+ return `Tenjin router added ${provider} docs for this search (free). If they don't cover it, use the web results below.
449
+
450
+ ${text}`;
451
+ }
452
+ async function awaitBody(path, deadline) {
453
+ for (; ; ) {
454
+ const body = await readBody(path);
455
+ if (body !== null) return body;
456
+ const left = deadline - Date.now();
457
+ if (left <= 0) return null;
458
+ await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_MS, left)));
459
+ }
460
+ }
461
+ async function readBody(path) {
462
+ const file = await open2(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => void 0);
463
+ if (file === void 0) return null;
464
+ try {
465
+ if ((await file.stat()).size > MAX_BODY_BYTES) return { status: 0, text: "" };
466
+ const parsed = JSON.parse(await file.readFile("utf8"));
467
+ const { status, text } = parsed ?? {};
468
+ if (typeof status !== "number" || typeof text !== "string") return { status: 0, text: "" };
469
+ return { status, text: text.slice(0, MAX_DOCS_CHARS) };
470
+ } catch {
471
+ return { status: 0, text: "" };
472
+ } finally {
473
+ await file.close().catch(() => void 0);
474
+ }
475
+ }
476
+
477
+ // src/router/hooks.ts
478
+ var PromptEventSchema = external_exports.object({
479
+ session_id: external_exports.string().min(1).max(200),
480
+ /** The directory the session works in; `router.*` resolves from it. */
481
+ cwd: external_exports.string().optional(),
482
+ transcript_path: external_exports.string().optional(),
483
+ prompt: external_exports.string()
484
+ });
485
+ var NativeCallFields = {
486
+ session_id: external_exports.string().min(1).max(200),
487
+ /** The harness's own path for THIS session: the decision reads the same
488
+ * bounded history the prompt one does, so a restriction the user gave
489
+ * reaches both gates. */
490
+ transcript_path: external_exports.string().optional(),
491
+ tool_name: external_exports.enum(["WebSearch", "WebFetch"]),
492
+ tool_input: external_exports.record(external_exports.string(), external_exports.unknown()),
493
+ /** The harness's id for this one call, shared by its Pre and Post events. */
494
+ tool_use_id: external_exports.string().min(1).max(200).optional(),
495
+ /** Present only inside a subagent, which is the one caller that cannot reach
496
+ * the user to approve a spend. */
497
+ agent_id: external_exports.string().min(1).max(200).optional(),
498
+ /** The subagent's type, which names its definition file. */
499
+ agent_type: external_exports.string().min(1).max(200).optional(),
500
+ cwd: external_exports.string().optional()
501
+ };
502
+ var NativeEventSchema = external_exports.object({
503
+ hook_event_name: external_exports.literal("PreToolUse").optional(),
504
+ ...NativeCallFields
505
+ });
506
+ var ShortfallEventSchema = external_exports.object({
507
+ hook_event_name: external_exports.enum(["PostToolUse", "PostToolUseFailure"]),
508
+ ...NativeCallFields,
509
+ /** PostToolUse only: WebFetch's `{bytes, code, codeText, result, durationMs}`,
510
+ * or WebSearch's `{query, results, durationSeconds, searchCount}`. */
511
+ tool_response: external_exports.unknown().optional(),
512
+ /** PostToolUseFailure only: the failed call's own error, such as
513
+ * `getaddrinfo ENOTFOUND x.test`. */
514
+ error: external_exports.unknown().optional(),
515
+ is_interrupt: external_exports.boolean().optional()
516
+ });
517
+ var AskEventSchema = external_exports.object({
518
+ hook_event_name: external_exports.literal("PreToolUse").optional(),
519
+ ...NativeCallFields,
520
+ tool_name: external_exports.literal("AskUserQuestion")
521
+ });
522
+ var AnswerEventSchema = external_exports.object({
523
+ hook_event_name: external_exports.literal("PostToolUse"),
524
+ session_id: external_exports.string().min(1).max(200),
525
+ transcript_path: external_exports.string().optional(),
526
+ tool_name: external_exports.literal("AskUserQuestion"),
527
+ tool_input: external_exports.record(external_exports.string(), external_exports.unknown()),
528
+ tool_response: external_exports.unknown().optional(),
529
+ cwd: external_exports.string().optional()
530
+ });
531
+ var DelegationEventSchema = external_exports.object({
532
+ session_id: external_exports.string().min(1).max(200),
533
+ transcript_path: external_exports.string().optional(),
534
+ /** `Task` is the tool's older name; the matcher `install` writes takes both. */
535
+ tool_name: external_exports.enum(["Agent", "Task"]),
536
+ tool_input: external_exports.record(external_exports.string(), external_exports.unknown()),
537
+ cwd: external_exports.string().optional()
538
+ });
539
+ function decodeEvent(raw) {
540
+ const shortfall = ShortfallEventSchema.safeParse(raw);
541
+ if (shortfall.success) {
542
+ return {
543
+ kind: "shortfall",
544
+ eventName: shortfall.data.hook_event_name,
545
+ nativeOutcome: shortfallOf(shortfall.data),
546
+ search: searchOf(shortfall.data),
547
+ ...nativeCallOf(shortfall.data)
548
+ };
549
+ }
550
+ const native = NativeEventSchema.safeParse(raw);
551
+ if (native.success) return { kind: "native", ...nativeCallOf(native.data) };
552
+ const answer = AnswerEventSchema.safeParse(raw);
553
+ if (answer.success) {
554
+ return {
555
+ kind: "answer",
556
+ sessionId: answer.data.session_id,
557
+ ...optional("transcriptPath", answer.data.transcript_path),
558
+ answers: answersOf(answer.data.tool_response, answer.data.tool_input),
559
+ ...optional("cwd", answer.data.cwd)
560
+ };
561
+ }
562
+ const ask = AskEventSchema.safeParse(raw);
563
+ if (ask.success) {
564
+ const question = questionOf(ask.data.tool_input);
565
+ return {
566
+ kind: "ask",
567
+ ...callFieldsOf(ask.data),
568
+ pending: question === null ? null : { tool: "AskUserQuestion", question }
569
+ };
570
+ }
571
+ const delegation = DelegationEventSchema.safeParse(raw);
572
+ if (delegation.success) {
573
+ const input = delegation.data.tool_input;
574
+ return {
575
+ kind: "delegation",
576
+ sessionId: delegation.data.session_id,
577
+ ...optional("transcriptPath", delegation.data.transcript_path),
578
+ task: typeof input.prompt === "string" ? input.prompt : null,
579
+ // With no type the harness runs its general-purpose agent.
580
+ subagentType: typeof input.subagent_type === "string" ? input.subagent_type : "general-purpose",
581
+ toolInput: input,
582
+ ...optional("cwd", delegation.data.cwd)
583
+ };
584
+ }
585
+ const prompt = PromptEventSchema.safeParse(raw);
586
+ if (!prompt.success) return null;
587
+ return {
588
+ kind: "prompt",
589
+ sessionId: prompt.data.session_id,
590
+ ...optional("transcriptPath", prompt.data.transcript_path),
591
+ prompt: prompt.data.prompt,
592
+ ...optional("cwd", prompt.data.cwd)
593
+ };
594
+ }
595
+ function nativeCallOf(event) {
596
+ return {
597
+ ...callFieldsOf(event),
598
+ tool: event.tool_name,
599
+ pending: pendingCallOf(event.tool_name, event.tool_input)
600
+ };
601
+ }
602
+ function callFieldsOf(event) {
603
+ return {
604
+ sessionId: event.session_id,
605
+ ...optional("transcriptPath", event.transcript_path),
606
+ ...optional("toolUseId", event.tool_use_id),
607
+ ...optional("agentId", event.agent_id),
608
+ ...optional("agentType", event.agent_type),
609
+ ...optional("cwd", event.cwd)
610
+ };
611
+ }
612
+ function questionOf(input) {
613
+ const questions = Array.isArray(input.questions) ? input.questions : [];
614
+ const parts = [];
615
+ for (const entry of questions) {
616
+ if (entry === null || typeof entry !== "object") continue;
617
+ const { question, options } = entry;
618
+ if (typeof question === "string" && question.trim().length > 0) parts.push(question.trim());
619
+ for (const option of Array.isArray(options) ? options : []) {
620
+ if (option === null || typeof option !== "object") continue;
621
+ const { label, description } = option;
622
+ if (typeof label !== "string" || label.trim().length === 0) continue;
623
+ parts.push(
624
+ typeof description === "string" && description.trim().length > 0 ? `${label.trim()}: ${description.trim()}` : label.trim()
625
+ );
626
+ }
627
+ }
628
+ const joined = parts.join(" ");
629
+ return joined.length > 0 ? joined : null;
630
+ }
631
+ function answersOf(response, input) {
632
+ for (const holder of [response, input]) {
633
+ if (holder === null || typeof holder !== "object" || Array.isArray(holder)) continue;
634
+ const answers = holder.answers;
635
+ if (answers === null || typeof answers !== "object" || Array.isArray(answers)) continue;
636
+ const texts = Object.values(answers).filter((value) => typeof value === "string").map((value) => value.trim()).filter((value) => value.length > 0);
637
+ if (texts.length > 0) return texts.join("\n");
638
+ }
639
+ return null;
640
+ }
641
+ function searchOf(event) {
642
+ if (event.hook_event_name !== "PostToolUse" || event.tool_name !== "WebSearch") return null;
643
+ const response = event.tool_response;
644
+ if (response === null || typeof response !== "object" || Array.isArray(response)) return null;
645
+ const raw = response;
646
+ return Array.isArray(raw.results) ? { raw, results: raw.results } : null;
647
+ }
648
+ function optional(key, value) {
649
+ return value === void 0 ? {} : { [key]: value };
650
+ }
651
+ var ACKNOWLEDGEMENTS = /* @__PURE__ */ new Set(["y", "yes", "ok", "okay", "continue", "go", "sure", "thanks"]);
652
+ function promptSkipReason(prompt) {
653
+ const trimmed = prompt.trim();
654
+ if (isHandback(trimmed)) return "handback";
655
+ if (trimmed.startsWith("/")) return "slash";
656
+ const normalized = trimmed.toLowerCase().replace(/[.!,]+$/, "");
657
+ return ACKNOWLEDGEMENTS.has(normalized) ? "acknowledgement" : null;
658
+ }
659
+ var HINT_SOURCE = "Tenjin router (installed by the user)";
660
+ var BARE_CALL_RE = /(?<![\w$])request\(\{/g;
661
+ function toolNamed(hint) {
662
+ return hint.replace(BARE_CALL_RE, `${REQUEST_TOOL}({`);
663
+ }
664
+ function attributed(hint) {
665
+ return `${HINT_SOURCE}: ${toolNamed(hint)}`;
666
+ }
667
+ var ONE_BLOCK = "If this does not cover it, make your own call again: you will not be redirected twice in a row for the same search or URL.";
668
+ var ONE_BLOCK_QUESTION = "If this does not cover it, ask your question again: you will not be redirected twice in a row for the same question.";
669
+ function shortfallOffer(tool, hint) {
670
+ return `${HINT_SOURCE}: your ${tool} call came back short. Optional: ${toolNamed(hint)}`;
671
+ }
672
+ var NEAR_EMPTY_BYTES = 64;
673
+ function shortfallOf(event) {
674
+ if (event.hook_event_name === "PostToolUseFailure") {
675
+ if (event.is_interrupt === true) return null;
676
+ const error = typeof event.error === "string" ? event.error.trim() : "";
677
+ return error.length > 0 ? { error } : null;
678
+ }
679
+ const response = event.tool_response;
680
+ if (response === null || typeof response !== "object" || Array.isArray(response)) return null;
681
+ const fields = response;
682
+ if (event.tool_name === "WebFetch") {
683
+ const code = wholeNumber(fields.code, 999);
684
+ const bytes = wholeNumber(fields.bytes, Number.MAX_SAFE_INTEGER);
685
+ const outcome = {
686
+ ...code !== void 0 ? { code } : {},
687
+ ...bytes !== void 0 ? { bytes } : {}
688
+ };
689
+ if (code !== void 0 && isShortStatus(code)) return outcome;
690
+ const success = code === void 0 || code >= 200 && code < 300;
691
+ return success && bytes !== void 0 && bytes < NEAR_EMPTY_BYTES ? outcome : null;
692
+ }
693
+ const results = fields.results;
694
+ if (!Array.isArray(results)) return null;
695
+ const linked = results.some(
696
+ (entry) => entry !== null && typeof entry === "object" && Array.isArray(entry.content) && entry.content.length > 0
697
+ );
698
+ return linked ? null : { error: "Web search returned no results" };
699
+ }
700
+ var SHORT_STATUSES = /* @__PURE__ */ new Set([401, 402, 403, 429]);
701
+ function isShortStatus(code) {
702
+ return SHORT_STATUSES.has(code) || code >= 500 && code <= 599;
703
+ }
704
+ function wholeNumber(value, max) {
705
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max ? value : void 0;
706
+ }
707
+ function delegationOffer(hint) {
708
+ return `${HINT_SOURCE}, optional if your own tools fall short: ${toolNamed(hint)} Your own tools are fine when they are enough.`;
709
+ }
710
+ function resolveBaseUrl(deps, config) {
711
+ if (deps.baseUrl !== void 0) return deps.baseUrl;
712
+ return resolveSettings({ config, flags: {}, env: deps.env ?? process.env }).baseUrl.value;
713
+ }
714
+ var BALANCE_TIMEOUT_MS = 1e3;
715
+ function gateDeadline(deps) {
716
+ return (deps.now?.() ?? Date.now()) + (deps.timeoutMs ?? GATE_TIMEOUT_MS);
717
+ }
718
+ async function spendShortfall(decision, deps, deadline) {
719
+ const price = `$${toMoney(decision.providerPriceAtomic).usd}`;
720
+ const approval = (detail) => ({
721
+ withheld: "offer needs approval",
722
+ note: `Note: ${price} ${detail}; request will return needs_approval with the command the user runs to approve it \u2014 ask the user first.`
723
+ });
724
+ let rpcUrl;
725
+ try {
726
+ const settings = await resolveContextSettings(hookContext(deps));
727
+ const ledger = await readSpendSummary(deps.dataDir, {
728
+ ...deps.now !== void 0 ? { now: deps.now } : {}
729
+ });
730
+ const evaluation = evaluateSpendPolicy(settings.policy, {
731
+ amountAtomic: BigInt(decision.providerPriceAtomic),
732
+ creator: new URL(decision.endpoint).host,
733
+ sessionSpentAtomic: ledger === null ? 0n : spentOf(ledger)
734
+ });
735
+ if (evaluation.decision !== "allow") {
736
+ return approval(
737
+ evaluation.reason === "above_auto_spend" ? `is above this machine's automatic per-call limit ($${toMoney(settings.policy.maxAutoSpendAtomic.toString()).usd})` : "needs approval under this machine's spend limits"
738
+ );
739
+ }
740
+ rpcUrl = settings.rpcUrl;
741
+ } catch {
742
+ return approval("needs approval under this machine's spend limits");
743
+ }
744
+ if ((deps.env ?? process.env).TENJIN_WALLET_KEY?.trim()) return null;
745
+ const address = await walletAddress(deps.dataDir);
746
+ if (address === null) return null;
747
+ const readBalance = rememberingBalanceReader(deps.dataDir, {
748
+ ...deps.now !== void 0 ? { now: deps.now } : {}
749
+ });
750
+ const balance = await readBalance(address, rpcUrl, {
751
+ timeoutMs: Math.min(BALANCE_TIMEOUT_MS, deadline - (deps.now?.() ?? Date.now())),
752
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
753
+ });
754
+ if (balance === null) {
755
+ (deps.warn ?? ((line) => process.stderr.write(`${line}
756
+ `)))(
757
+ `tenjin hook: the wallet's USDC balance could not be read from ${new URL(rpcUrl).host}, so the spend policy alone decides`
758
+ );
759
+ return null;
760
+ }
761
+ return balance < BigInt(decision.providerPriceAtomic) ? {
762
+ withheld: "wallet needs USDC",
763
+ note: `Note: the wallet holds $${toMoney(balance.toString()).usd}; fund it with \`tenjin wallet fund\`.`
764
+ } : null;
765
+ }
766
+ async function vetOffer(offer, deps, deadline, canAskUser) {
767
+ const shortfall = await spendShortfall(termsOf(offer), deps, deadline);
768
+ if (shortfall === null) {
769
+ const note = await overCapNote(offer.hint, deps, canAskUser);
770
+ return { offer: note === null ? offer : { ...offer, hint: `${offer.hint} ${note}` } };
771
+ }
772
+ if (offer.action === "discovered" && canAskUser) {
773
+ return { offer: { ...offer, hint: `${offer.hint} ${shortfall.note}` } };
774
+ }
775
+ return { withheld: shortfall.withheld };
776
+ }
777
+ var LISTED_PRICE_RE = /about \$(\d+(?:\.\d+)?)(?= per call|: request\(| \(price can vary)|\$(\d+(?:\.\d+)?)(?=\): request\(| via https?:\/\/)/g;
778
+ var QUOTED_RE = /"(?:[^"\\]|\\.)*"/g;
779
+ async function overCapNote(hint, deps, canAskUser) {
780
+ const listed = [...hint.replace(QUOTED_RE, '""').matchAll(LISTED_PRICE_RE)].map(
781
+ (match) => match[1] ?? match[2]
782
+ );
783
+ if (listed.length === 0) return null;
784
+ let cap;
785
+ try {
786
+ cap = (await resolveContextSettings(hookContext(deps))).policy.maxAutoSpendAtomic;
787
+ } catch {
788
+ return null;
789
+ }
790
+ const over = [
791
+ ...new Set(
792
+ listed.filter((usd) => {
793
+ try {
794
+ return BigInt(parseUsdToAtomic(usd)) > cap;
795
+ } catch {
796
+ return false;
797
+ }
798
+ })
799
+ )
800
+ ];
801
+ if (over.length === 0) return null;
802
+ const prices = over.map((usd) => `$${usd}`).join(" and ");
803
+ const which = over.length > 1 ? "those services" : "that service";
804
+ return `Note: ${prices} ${over.length > 1 ? "are" : "is"} above this machine's automatic per-call limit ($${toMoney(cap.toString()).usd}), so request returns needs_approval for ${which}; ` + (canAskUser ? "prefer one within the limit, or ask the user first." : "use one within the limit.");
805
+ }
806
+ async function walletAddress(dataDir) {
807
+ try {
808
+ const record = JSON.parse(await readFile(walletPath(dataDir), "utf8"));
809
+ const address = record?.address;
810
+ return typeof address === "string" && /^0x[0-9a-fA-F]{40}$/.test(address) ? address : null;
811
+ } catch {
812
+ return null;
813
+ }
814
+ }
815
+ function agentLookup(cwd, deps) {
816
+ return { ...cwd !== void 0 ? { cwd } : {}, homeDir: deps.homeDir ?? homedir() };
817
+ }
818
+ function hookContext(deps) {
819
+ return {
820
+ flags: { json: true, timeout: deps.timeoutMs ?? GATE_TIMEOUT_MS },
821
+ dataDir: deps.dataDir,
822
+ io: { stdout: nullStream(), stderr: nullStream(), isTTY: false }
823
+ };
824
+ }
825
+ async function runPromptHook(raw, deps) {
826
+ const event = decodeEvent(raw);
827
+ if (event?.kind !== "prompt") return { response: null };
828
+ return offerOnUserText(event, event.prompt, "UserPromptSubmit", deps);
829
+ }
830
+ async function runAnswerHook(raw, deps) {
831
+ const event = decodeEvent(raw);
832
+ if (event?.kind !== "answer" || event.answers === null) return { response: null };
833
+ return offerOnUserText(event, event.answers, "PostToolUse", deps);
834
+ }
835
+ async function offerOnUserText(event, text, hookEventName, deps) {
836
+ const skipped = promptSkipReason(text);
837
+ if (skipped !== null) return { response: null, skipped };
838
+ const router = await routerFor(event.cwd, deps);
839
+ if (router === null) return { response: null };
840
+ const sealed = seal(
841
+ scoped(await buildPromptPacket(event.transcriptPath, event.sessionId, text), router.settings)
842
+ );
843
+ const footer = await openFooter(deps, event.sessionId, "prompt");
844
+ const deadline = gateDeadline(deps);
845
+ const outcome = await decide(sealed, deps, router.config, event.sessionId);
846
+ if (!isOffer(outcome)) {
847
+ await footer.close(outcome);
848
+ return { response: null, ...outcome !== null ? { action: outcome.action } : {} };
849
+ }
850
+ const vetted = await vetOffer(outcome, deps, deadline, true);
851
+ if (vetted.withheld !== void 0) {
852
+ await footer.close(outcome, { withheld: vetted.withheld });
853
+ return { response: null, action: outcome.action, withheld: true };
854
+ }
855
+ await footer.close(outcome);
856
+ return {
857
+ action: outcome.action,
858
+ id: outcome.id,
859
+ ...injection(hookEventName, attributed(vetted.offer.hint))
860
+ };
861
+ }
862
+ function injection(hookEventName, line) {
863
+ return { response: { hookSpecificOutput: { hookEventName, additionalContext: line } } };
864
+ }
865
+ function isOffer(decision) {
866
+ return decision?.action === "execute" || decision?.action === "discovered";
867
+ }
868
+ function termsOf(offer) {
869
+ if (offer.action === "execute") return offer;
870
+ const { candidate } = offer;
871
+ return {
872
+ provider: candidate.provider,
873
+ providerPriceAtomic: candidate.providerPriceAtomic,
874
+ endpoint: candidate.url
875
+ };
876
+ }
877
+ function isFree(offer) {
878
+ return offer.action === "execute" && offer.providerPriceAtomic === "0";
879
+ }
880
+ async function routeNativeCall(event, pending, deps, opts = {}) {
881
+ const { nativeOutcome, repeated } = opts;
882
+ const router = await routerFor(event.cwd, deps);
883
+ if (router === null) return { offer: null, outcome: { response: null } };
884
+ if (event.agentId !== void 0 && await requestToolAccess(event.agentType, agentLookup(event.cwd, deps)) !== "allowed") {
885
+ return { offer: null, outcome: { response: null, noRequestTool: true } };
886
+ }
887
+ if (opts.redirected !== void 0 && await opts.redirected()) {
888
+ const footer2 = await openFooter(deps, event.sessionId, opts.operation ?? "search");
889
+ await footer2.close(null, { withheld: "already redirected once" });
890
+ return { offer: null, outcome: { response: null, alreadyRedirected: true } };
891
+ }
892
+ const sealed = seal(
893
+ scoped(
894
+ await buildNativePacket(event.transcriptPath, event.sessionId, pending, {
895
+ ...event.agentId !== void 0 ? { agentId: event.agentId } : {},
896
+ ...nativeOutcome !== void 0 ? { nativeOutcome } : {}
897
+ }),
898
+ router.settings
899
+ )
900
+ );
901
+ const { packet } = sealed;
902
+ if (sealed.localTarget) return { offer: null, outcome: { response: null } };
903
+ if (sealed.subjectChanged) {
904
+ (deps.warn ?? ((line) => process.stderr.write(`${line}
905
+ `)))(
906
+ "tenjin hook: the native call carries a credential-shaped value, so it is not routed"
907
+ );
908
+ return { offer: null, outcome: { response: null } };
909
+ }
910
+ if (packet.historyStatus !== "ok") {
911
+ (deps.warn ?? ((line) => process.stderr.write(`${line}
912
+ `)))(
913
+ "tenjin hook: this session's transcript could not be read, so no paid lookup is offered"
914
+ );
915
+ return { offer: null, outcome: { response: null } };
916
+ }
917
+ const footer = await openFooter(deps, event.sessionId, opts.operation ?? "search");
918
+ const deadline = gateDeadline(deps);
919
+ const outcome = await decide(sealed, deps, router.config, event.sessionId);
920
+ if (!isOffer(outcome)) {
921
+ await footer.close(outcome);
922
+ return {
923
+ offer: null,
924
+ outcome: { response: null, ...outcome !== null ? { action: outcome.action } : {} }
925
+ };
926
+ }
927
+ if (opts.passFree === true && isFree(outcome)) {
928
+ await footer.close(outcome, { withheld: "free lookup, call runs" });
929
+ return { offer: outcome, free: true, baseUrl: resolveBaseUrl(deps, router.config) };
930
+ }
931
+ const vetted = await vetOffer(
932
+ outcome,
933
+ deps,
934
+ deadline,
935
+ event.agentId === void 0 && opts.canAskUser !== false
936
+ );
937
+ if (vetted.withheld !== void 0) {
938
+ await footer.close(outcome, { withheld: vetted.withheld });
939
+ return { offer: null, outcome: { response: null, action: outcome.action, withheld: true } };
940
+ }
941
+ if (repeated !== void 0 && await repeated()) {
942
+ await footer.close(outcome, { withheld: "already redirected once" });
943
+ return {
944
+ offer: null,
945
+ outcome: { response: null, action: outcome.action, alreadyRedirected: true }
946
+ };
947
+ }
948
+ await footer.close(outcome);
949
+ return { offer: vetted.offer };
950
+ }
951
+ async function runNativeHook(raw, deps) {
952
+ const event = decodeEvent(raw);
953
+ if (event?.kind !== "native" || event.pending === null) return { response: null };
954
+ const target = redirectTarget(event.pending);
955
+ const routed = await routeNativeCall(event, event.pending, deps, {
956
+ passFree: true,
957
+ repeated: async () => !await claimRedirect(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.()),
958
+ redirected: () => redirectClaimed(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.())
959
+ });
960
+ if (routed.offer === null) return routed.outcome;
961
+ if (routed.free === true) {
962
+ const { pending } = event;
963
+ const augmenting = pending.tool === "WebSearch" && await startAugment(
964
+ {
965
+ sessionId: event.sessionId,
966
+ query: pending.query,
967
+ ...event.agentId !== void 0 ? { agentId: event.agentId } : {},
968
+ ...event.toolUseId !== void 0 ? { toolUseId: event.toolUseId } : {}
969
+ },
970
+ routed.offer,
971
+ routed.baseUrl,
972
+ deps
973
+ );
974
+ return {
975
+ response: null,
976
+ action: "execute",
977
+ id: routed.offer.id,
978
+ free: true,
979
+ ...augmenting ? { augmenting: true } : {}
980
+ };
981
+ }
982
+ if (event.toolUseId !== void 0) {
983
+ await markOffered(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.());
984
+ }
985
+ return redirect(routed.offer);
986
+ }
987
+ function redirect(offer, oneBlock = ONE_BLOCK) {
988
+ return {
989
+ response: {
990
+ hookSpecificOutput: {
991
+ hookEventName: "PreToolUse",
992
+ permissionDecision: "deny",
993
+ // THE SERVER'S LINE, attributed and tool-named, then this client's one
994
+ // sentence. The line already carries the id and the exact search, URL
995
+ // or question that was denied.
996
+ permissionDecisionReason: `${attributed(offer.hint)} ${oneBlock}`
997
+ }
998
+ },
999
+ action: offer.action,
1000
+ id: offer.id
1001
+ };
1002
+ }
1003
+ async function runAskHook(raw, deps) {
1004
+ const event = decodeEvent(raw);
1005
+ if (event?.kind !== "ask" || event.pending === null) return { response: null };
1006
+ const target = redirectTarget(event.pending);
1007
+ const routed = await routeNativeCall(event, event.pending, deps, {
1008
+ passFree: true,
1009
+ operation: "prompt",
1010
+ canAskUser: false,
1011
+ repeated: async () => !await claimRedirect(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.()),
1012
+ redirected: () => redirectClaimed(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.())
1013
+ });
1014
+ if (routed.offer === null) return routed.outcome;
1015
+ if (routed.free === true) {
1016
+ return { response: null, action: routed.offer.action, id: routed.offer.id, free: true };
1017
+ }
1018
+ return redirect(routed.offer, ONE_BLOCK_QUESTION);
1019
+ }
1020
+ async function runShortfallHook(raw, deps) {
1021
+ const event = decodeEvent(raw);
1022
+ if (event?.kind !== "shortfall") return { response: null };
1023
+ const augment = await finishAugment(
1024
+ {
1025
+ sessionId: event.sessionId,
1026
+ search: event.search,
1027
+ ...event.toolUseId !== void 0 ? { toolUseId: event.toolUseId } : {}
1028
+ },
1029
+ deps
1030
+ );
1031
+ if (augment !== null && augment.updatedToolOutput !== null) {
1032
+ return {
1033
+ response: {
1034
+ hookSpecificOutput: {
1035
+ hookEventName: "PostToolUse",
1036
+ updatedToolOutput: augment.updatedToolOutput
1037
+ }
1038
+ },
1039
+ augmented: "added"
1040
+ };
1041
+ }
1042
+ const outcome = await offerOnShortfall(event, deps, augment !== null);
1043
+ return augment === null ? outcome : { ...outcome, augmented: "nothing" };
1044
+ }
1045
+ async function offerOnShortfall(event, deps, docsJustMissed = false) {
1046
+ const { nativeOutcome, pending, eventName } = event;
1047
+ if (nativeOutcome === null) return { response: null };
1048
+ if (pending === null) return { response: null };
1049
+ if (event.toolUseId !== void 0 && await wasOffered(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.())) {
1050
+ return { response: null, nativeOutcome, alreadyOffered: true };
1051
+ }
1052
+ const routed = await routeNativeCall(event, pending, deps, { nativeOutcome });
1053
+ if (routed.offer === null) return { ...routed.outcome, nativeOutcome };
1054
+ if (docsJustMissed && isFree(routed.offer))
1055
+ return { response: null, nativeOutcome, action: "execute" };
1056
+ return {
1057
+ response: {
1058
+ hookSpecificOutput: {
1059
+ hookEventName: eventName,
1060
+ // THE SERVER'S LINE, attributed and framed as the option it is. It
1061
+ // already carries the id and the exact search or URL that came back short.
1062
+ additionalContext: shortfallOffer(event.tool, routed.offer.hint)
1063
+ }
1064
+ },
1065
+ nativeOutcome,
1066
+ action: routed.offer.action,
1067
+ id: routed.offer.id
1068
+ };
1069
+ }
1070
+ async function runDelegationHook(raw, deps) {
1071
+ const event = decodeEvent(raw);
1072
+ if (event?.kind !== "delegation") return { response: null };
1073
+ const { task } = event;
1074
+ if (task === null || task.trim().length === 0) return { response: null };
1075
+ const router = await routerFor(event.cwd, deps);
1076
+ if (router === null) return { response: null };
1077
+ if (await requestToolAccess(event.subagentType, agentLookup(event.cwd, deps)) !== "allowed") {
1078
+ return { response: null, noRequestTool: true };
1079
+ }
1080
+ const sealed = seal(
1081
+ scoped(await buildPromptPacket(event.transcriptPath, event.sessionId, task), router.settings)
1082
+ );
1083
+ if (sealed.localUrl) return { response: null };
1084
+ if (sealed.currentChanged) {
1085
+ (deps.warn ?? ((line) => process.stderr.write(`${line}
1086
+ `)))(
1087
+ "tenjin hook: the delegated task carries a credential-shaped value, so it is not routed"
1088
+ );
1089
+ return { response: null };
1090
+ }
1091
+ if (sealed.packet.historyStatus !== "ok") return { response: null };
1092
+ const footer = await openFooter(deps, event.sessionId, "delegate");
1093
+ const deadline = gateDeadline(deps);
1094
+ const outcome = await decide(sealed, deps, router.config, event.sessionId);
1095
+ if (!isOffer(outcome)) {
1096
+ await footer.close(outcome);
1097
+ return { response: null, ...outcome !== null ? { action: outcome.action } : {} };
1098
+ }
1099
+ const vetted = await vetOffer(outcome, deps, deadline, false);
1100
+ if (vetted.withheld !== void 0) {
1101
+ await footer.close(outcome, { withheld: vetted.withheld });
1102
+ return { response: null, action: outcome.action, withheld: true };
1103
+ }
1104
+ await footer.close(outcome);
1105
+ return {
1106
+ response: {
1107
+ hookSpecificOutput: {
1108
+ hookEventName: "PreToolUse",
1109
+ // The whole input, with one line appended: `updatedInput` replaces it.
1110
+ updatedInput: {
1111
+ ...event.toolInput,
1112
+ prompt: `${task}
1113
+
1114
+ ${delegationOffer(outcome.hint)}`
1115
+ }
1116
+ }
1117
+ },
1118
+ action: outcome.action,
1119
+ id: outcome.id
1120
+ };
1121
+ }
1122
+ async function openFooter(deps, sessionId, operation) {
1123
+ const now = () => deps.now?.() ?? Date.now();
1124
+ const directory = sessionDir(deps.dataDir, sessionId);
1125
+ const callId = newCallId();
1126
+ await noteSession(deps.dataDir, sessionId, now());
1127
+ await writeProgress(
1128
+ directory,
1129
+ callId,
1130
+ { phase: "routing", operation, outcome: "selecting service" },
1131
+ now()
1132
+ );
1133
+ await pruneProgress(directory, now());
1134
+ await pruneSessions(deps.dataDir, now());
1135
+ return {
1136
+ close: async (decision, opts) => {
1137
+ const withheld = opts?.withheld;
1138
+ await writeProgress(
1139
+ directory,
1140
+ callId,
1141
+ {
1142
+ phase: "done",
1143
+ operation,
1144
+ outcome: withheld !== void 0 ? `native tools (${withheld})` : hookOutcome(decision)
1145
+ },
1146
+ now()
1147
+ );
1148
+ if (withheld === void 0 && isOffer(decision)) {
1149
+ await bindDecision(deps.dataDir, sessionId, decision.id, now());
1150
+ }
1151
+ }
1152
+ };
1153
+ }
1154
+ function hookOutcome(decision) {
1155
+ if (decision === null) return "native tools (router unavailable)";
1156
+ if (isOffer(decision)) return `paid lookup offered (${termsOf(decision).provider})`;
1157
+ if (decision.action === "native") return "native tools (no x402 payment)";
1158
+ return "needs input";
1159
+ }
1160
+ async function decide({ packet }, deps, config, sessionId) {
1161
+ const baseUrl = resolveBaseUrl(deps, config);
1162
+ const warn = deps.warn ?? ((line) => process.stderr.write(`${line}
1163
+ `));
1164
+ const outcome = await requestDecision(
1165
+ "hook",
1166
+ { packet, sessionId },
1167
+ {
1168
+ ctx: hookContext(deps),
1169
+ baseUrl,
1170
+ acceptsBazaar: resolveExperimentalBazaar(config).value === "on",
1171
+ timeoutMs: deps.timeoutMs ?? GATE_TIMEOUT_MS,
1172
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
1173
+ }
1174
+ );
1175
+ if (outcome.status === "failed") {
1176
+ warn(`tenjin hook: ${baseUrl}${ROUTER_PATH} ${outcome.reason}`);
1177
+ return null;
1178
+ }
1179
+ return outcome.decision.decision;
1180
+ }
1181
+ function nullStream() {
1182
+ return { write: () => true };
1183
+ }
1184
+ function redirectTarget(pending) {
1185
+ if (pending.tool === "WebSearch") return `WebSearch ${pending.query}`;
1186
+ if (pending.tool === "AskUserQuestion") return `AskUserQuestion ${pending.question}`;
1187
+ let url = pending.url;
1188
+ try {
1189
+ url = new URL(url).toString();
1190
+ } catch {
1191
+ }
1192
+ return `WebFetch ${url}`;
1193
+ }
1194
+ function pendingCallOf(tool, input) {
1195
+ const value = tool === "WebSearch" ? input.query : input.url;
1196
+ if (typeof value !== "string") return null;
1197
+ const subject = value.trim();
1198
+ if (subject.length === 0) return null;
1199
+ return tool === "WebSearch" ? { tool, query: subject } : { tool, url: subject };
1200
+ }
1201
+ async function routerFor(cwd, deps) {
1202
+ const warn = deps.warn ?? ((line) => process.stderr.write(`${line}
1203
+ `));
1204
+ try {
1205
+ const config = await loadRawConfig(deps.dataDir);
1206
+ const settings = await routerSettings(
1207
+ { cwd: cwd ?? process.cwd(), dataDir: deps.dataDir, config },
1208
+ { warn: (line) => warn(`tenjin hook: ${line}`) }
1209
+ );
1210
+ return settings.enabled.value ? { settings, config } : null;
1211
+ } catch (err) {
1212
+ warn(`tenjin hook: ${err instanceof Error ? err.message : String(err)}, so the router is off`);
1213
+ return null;
1214
+ }
1215
+ }
1216
+ function scoped(packet, router) {
1217
+ return router.context.value === "turn" ? { ...packet, history: [] } : packet;
1218
+ }
1219
+
1220
+ // src/router/hook-command.ts
1221
+ var MAX_EVENT_BYTES = 1e6;
1222
+ var STDIN_TIMEOUT_MS = 1e3;
1223
+ async function runHookCommand(kind, io, deps) {
1224
+ let response;
1225
+ try {
1226
+ const raw = await (deps.readEvent ?? readStdin)();
1227
+ const event = JSON.parse(raw);
1228
+ const outcome = kind === "prompt" ? await runPromptHook(event, deps) : kind === "native" ? await runNativeHook(event, deps) : kind === "shortfall" ? await runShortfallHook(event, deps) : kind === "ask" ? await runAskHook(event, deps) : kind === "answer" ? await runAnswerHook(event, deps) : await runDelegationHook(event, deps);
1229
+ response = outcome.response;
1230
+ } catch {
1231
+ response = null;
1232
+ }
1233
+ if (response !== null) io.stdout.write(`${JSON.stringify(response)}
1234
+ `);
1235
+ }
1236
+ async function readStdin() {
1237
+ return new Promise((resolve, reject) => {
1238
+ const chunks = [];
1239
+ let size = 0;
1240
+ const timer = setTimeout(() => reject(new Error("no harness event")), STDIN_TIMEOUT_MS);
1241
+ const done = (value) => {
1242
+ clearTimeout(timer);
1243
+ resolve(value);
1244
+ };
1245
+ process.stdin.on("data", (chunk) => {
1246
+ size += chunk.length;
1247
+ if (size > MAX_EVENT_BYTES) {
1248
+ clearTimeout(timer);
1249
+ reject(new Error("harness event too large"));
1250
+ return;
1251
+ }
1252
+ chunks.push(chunk);
1253
+ });
1254
+ process.stdin.once("end", () => done(Buffer.concat(chunks).toString("utf8")));
1255
+ process.stdin.once("error", () => {
1256
+ clearTimeout(timer);
1257
+ reject(new Error("harness event unreadable"));
1258
+ });
1259
+ });
1260
+ }
1261
+ export {
1262
+ STDIN_TIMEOUT_MS,
1263
+ runHookCommand
1264
+ };
1265
+ //# sourceMappingURL=hook-command-VVV2Q23L.js.map