token-goat 2.9.29 → 2.9.31

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 (197) hide show
  1. package/README.md +53 -42
  2. package/SECURITY.md +37 -11
  3. package/THIRD_PARTY_NOTICES.md +41 -4
  4. package/dist/native/linux-arm64/tg-hook +0 -0
  5. package/dist/native/linux-x64/tg-hook +0 -0
  6. package/dist/native/win32-arm64/tg-hook.exe +0 -0
  7. package/dist/native/win32-x64/tg-hook.exe +0 -0
  8. package/dist/ort-wasm-simd-threaded.mjs +59 -0
  9. package/dist/{token-goat-chunk-SE6E4BKJ.mjs → token-goat-chunk-25TRAWET.mjs} +23 -6
  10. package/dist/token-goat-chunk-2KXO6V2B.mjs +203 -0
  11. package/dist/{token-goat-chunk-UXSXQQIY.mjs → token-goat-chunk-2M7E4PF7.mjs} +43 -14
  12. package/dist/token-goat-chunk-2UPZGKKY.mjs +188 -0
  13. package/dist/token-goat-chunk-2WLPWKHV.mjs +135 -0
  14. package/dist/token-goat-chunk-2XBMMDBD.mjs +126 -0
  15. package/dist/token-goat-chunk-32ZOY4N5.mjs +23 -0
  16. package/dist/token-goat-chunk-3EZRNKTK.mjs +188 -0
  17. package/dist/token-goat-chunk-4ADZHI7J.mjs +63 -0
  18. package/dist/token-goat-chunk-4GBVPH3D.mjs +242 -0
  19. package/dist/{token-goat-chunk-2WOUYWLM.mjs → token-goat-chunk-4GILLLWY.mjs} +34 -7
  20. package/dist/token-goat-chunk-4NAPX7BA.mjs +90 -0
  21. package/dist/{token-goat-chunk-NMBWLRHW.mjs → token-goat-chunk-4SC7UJYV.mjs} +9981 -11563
  22. package/dist/token-goat-chunk-4SMRO4TO.mjs +366 -0
  23. package/dist/{token-goat-chunk-O6I2XU4P.mjs → token-goat-chunk-4ZBFWLXF.mjs} +310 -441
  24. package/dist/token-goat-chunk-57BIAXJL.mjs +286 -0
  25. package/dist/token-goat-chunk-5AC66HNP.mjs +115 -0
  26. package/dist/token-goat-chunk-5IMLKSOP.mjs +145 -0
  27. package/dist/token-goat-chunk-5RG5SBL6.mjs +221 -0
  28. package/dist/{token-goat-chunk-RRNZMM3A.mjs → token-goat-chunk-5Y6ZYL6U.mjs} +21 -2
  29. package/dist/token-goat-chunk-646E6U44.mjs +398 -0
  30. package/dist/token-goat-chunk-65N4RHP4.mjs +33 -0
  31. package/dist/{token-goat-chunk-6AK46ZT7.mjs → token-goat-chunk-6DG6HWP3.mjs} +13 -3
  32. package/dist/token-goat-chunk-6ENQSNRZ.mjs +573 -0
  33. package/dist/token-goat-chunk-6ZY4GNF2.mjs +91 -0
  34. package/dist/{token-goat-chunk-E5TK5DNO.mjs → token-goat-chunk-76FGDLRO.mjs} +574 -340
  35. package/dist/{token-goat-chunk-TGOXNAHW.mjs → token-goat-chunk-7EZTZOMC.mjs} +780 -767
  36. package/dist/token-goat-chunk-7MAOA6X4.mjs +3647 -0
  37. package/dist/token-goat-chunk-7R2ZVVAX.mjs +218 -0
  38. package/dist/{token-goat-chunk-TCQANXYC.mjs → token-goat-chunk-AM5V6GSX.mjs} +18 -2
  39. package/dist/token-goat-chunk-AUNGYYQX.mjs +184 -0
  40. package/dist/token-goat-chunk-AUQYRMMH.mjs +2985 -0
  41. package/dist/token-goat-chunk-B3PEKBYG.mjs +128 -0
  42. package/dist/{token-goat-chunk-KOPIR3KZ.mjs → token-goat-chunk-BA4HI6BW.mjs} +1910 -165
  43. package/dist/{token-goat-chunk-52NSDWYY.mjs → token-goat-chunk-BFCWY73P.mjs} +58 -20
  44. package/dist/token-goat-chunk-BPGCUMR7.mjs +30 -0
  45. package/dist/token-goat-chunk-BWGFUZZE.mjs +25 -0
  46. package/dist/token-goat-chunk-C75NA7PL.mjs +322 -0
  47. package/dist/token-goat-chunk-CBIQ7WTD.mjs +87 -0
  48. package/dist/token-goat-chunk-CETM74KC.mjs +307 -0
  49. package/dist/token-goat-chunk-CIMQ2BB3.mjs +233 -0
  50. package/dist/{token-goat-chunk-DNSPXQXQ.mjs → token-goat-chunk-CJLS3CDL.mjs} +70 -18
  51. package/dist/{token-goat-chunk-MELOKFDJ.mjs → token-goat-chunk-CO3UYX6G.mjs} +7 -1
  52. package/dist/token-goat-chunk-COPNXRJM.mjs +154 -0
  53. package/dist/token-goat-chunk-CSJ5L3NL.mjs +479 -0
  54. package/dist/token-goat-chunk-CVCEVUGK.mjs +315 -0
  55. package/dist/token-goat-chunk-CXHOFN7R.mjs +371 -0
  56. package/dist/token-goat-chunk-D735C4QM.mjs +603 -0
  57. package/dist/{token-goat-chunk-E4ZOJIZK.mjs → token-goat-chunk-DGS2LVNA.mjs} +70 -160
  58. package/dist/{token-goat-chunk-L7H3U27L.mjs → token-goat-chunk-DOWRSMWO.mjs} +1 -1
  59. package/dist/token-goat-chunk-E45INMY3.mjs +71 -0
  60. package/dist/token-goat-chunk-EC5F37F4.mjs +244 -0
  61. package/dist/{token-goat-chunk-XTQAOTSO.mjs → token-goat-chunk-EDBDRVH5.mjs} +4 -1
  62. package/dist/token-goat-chunk-EELTBKDM.mjs +613 -0
  63. package/dist/token-goat-chunk-EVMZJ27Z.mjs +147 -0
  64. package/dist/token-goat-chunk-EXKGNHEG.mjs +2096 -0
  65. package/dist/{token-goat-chunk-YOOVFPTP.mjs → token-goat-chunk-F4HYL64R.mjs} +12 -2
  66. package/dist/token-goat-chunk-F6PAUIEK.mjs +624 -0
  67. package/dist/token-goat-chunk-FDSREWLX.mjs +692 -0
  68. package/dist/{token-goat-chunk-NMTKNYGF.mjs → token-goat-chunk-FNFBKLRD.mjs} +74 -9
  69. package/dist/token-goat-chunk-G5PJ7AGM.mjs +36 -0
  70. package/dist/token-goat-chunk-GGGG7RWB.mjs +236 -0
  71. package/dist/{token-goat-chunk-TDUT2CL6.mjs → token-goat-chunk-GL3ETKSC.mjs} +276 -19
  72. package/dist/{token-goat-chunk-7CPMDFGB.mjs → token-goat-chunk-GVB2MUST.mjs} +265 -1567
  73. package/dist/token-goat-chunk-GWFLAUMQ.mjs +307 -0
  74. package/dist/token-goat-chunk-HAVAOB3S.mjs +87 -0
  75. package/dist/token-goat-chunk-HLPW63A7.mjs +48 -0
  76. package/dist/token-goat-chunk-HU4TORC5.mjs +1377 -0
  77. package/dist/token-goat-chunk-I7VKZZAW.mjs +35 -0
  78. package/dist/token-goat-chunk-IA6XSPE3.mjs +218 -0
  79. package/dist/token-goat-chunk-IAGXMHIK.mjs +863 -0
  80. package/dist/{token-goat-chunk-435UQTKD.mjs → token-goat-chunk-IK2DRMFX.mjs} +129 -74
  81. package/dist/{token-goat-chunk-ZER6EAXZ.mjs → token-goat-chunk-INNPTRUX.mjs} +2954 -2783
  82. package/dist/token-goat-chunk-JJ5BX4F4.mjs +129 -0
  83. package/dist/token-goat-chunk-JVFSHVFJ.mjs +129 -0
  84. package/dist/token-goat-chunk-KGEFFSHD.mjs +50 -0
  85. package/dist/token-goat-chunk-KKUFXAPD.mjs +25 -0
  86. package/dist/token-goat-chunk-KQBLRPBN.mjs +433 -0
  87. package/dist/token-goat-chunk-LCNQ2CNN.mjs +497 -0
  88. package/dist/token-goat-chunk-M3LFJDPU.mjs +58 -0
  89. package/dist/token-goat-chunk-M52KPT3C.mjs +87 -0
  90. package/dist/token-goat-chunk-MBEG42H7.mjs +150 -0
  91. package/dist/{token-goat-chunk-EVC4TOLE.mjs → token-goat-chunk-METECDOH.mjs} +3 -12
  92. package/dist/{token-goat-chunk-2AWQ2R5X.mjs → token-goat-chunk-MHX7XCC3.mjs} +3 -2
  93. package/dist/token-goat-chunk-MNWKPRAL.mjs +13 -0
  94. package/dist/token-goat-chunk-N5LSOVSU.mjs +137 -0
  95. package/dist/{token-goat-chunk-DPNLUJWB.mjs → token-goat-chunk-N5MMR2IW.mjs} +30 -8
  96. package/dist/token-goat-chunk-N7B3JQ2C.mjs +160 -0
  97. package/dist/{token-goat-chunk-VMFWNHGR.mjs → token-goat-chunk-NISNMD7T.mjs} +2545 -2953
  98. package/dist/token-goat-chunk-NMD42SFQ.mjs +434 -0
  99. package/dist/token-goat-chunk-NOSS5VWY.mjs +174 -0
  100. package/dist/token-goat-chunk-NSNSPPBG.mjs +69 -0
  101. package/dist/token-goat-chunk-OBOFIHKN.mjs +38 -0
  102. package/dist/token-goat-chunk-OBRFJ5O5.mjs +76 -0
  103. package/dist/token-goat-chunk-ODBT2USM.mjs +800 -0
  104. package/dist/token-goat-chunk-OS5EM5PP.mjs +107 -0
  105. package/dist/token-goat-chunk-OUKDTVNU.mjs +1178 -0
  106. package/dist/token-goat-chunk-OXFMP75N.mjs +566 -0
  107. package/dist/{token-goat-chunk-ASLWOQ3I.mjs → token-goat-chunk-OYIYKDDT.mjs} +2 -1
  108. package/dist/{token-goat-chunk-67BNIKKO.mjs → token-goat-chunk-P6HQSWQ3.mjs} +55 -47
  109. package/dist/token-goat-chunk-P6VGNTQT.mjs +71 -0
  110. package/dist/token-goat-chunk-PFWIMH2E.mjs +261 -0
  111. package/dist/token-goat-chunk-PJZXIS3G.mjs +39 -0
  112. package/dist/token-goat-chunk-PUO5INXP.mjs +606 -0
  113. package/dist/token-goat-chunk-PX5PQWTY.mjs +462 -0
  114. package/dist/token-goat-chunk-Q5QDBC6O.mjs +111 -0
  115. package/dist/token-goat-chunk-QFNQXSDT.mjs +40 -0
  116. package/dist/token-goat-chunk-QH7YVYOY.mjs +3957 -0
  117. package/dist/token-goat-chunk-QLMUHEPB.mjs +43 -0
  118. package/dist/{token-goat-chunk-PYSUADX4.mjs → token-goat-chunk-QQOJIHL3.mjs} +50 -14
  119. package/dist/token-goat-chunk-QQTWJY2O.mjs +85 -0
  120. package/dist/token-goat-chunk-QYHO5CPH.mjs +93 -0
  121. package/dist/token-goat-chunk-RELAVWAD.mjs +27 -0
  122. package/dist/token-goat-chunk-RSLPOBKQ.mjs +339 -0
  123. package/dist/token-goat-chunk-SAMFDIS2.mjs +712 -0
  124. package/dist/token-goat-chunk-SDELXLDM.mjs +48 -0
  125. package/dist/{token-goat-chunk-PGTH2U4C.mjs → token-goat-chunk-SOAFZNNZ.mjs} +164 -40
  126. package/dist/{token-goat-chunk-G23DWHV4.mjs → token-goat-chunk-SRTHT7KV.mjs} +33 -15
  127. package/dist/token-goat-chunk-T5P5ACNQ.mjs +212 -0
  128. package/dist/token-goat-chunk-T5YGG4V3.mjs +45 -0
  129. package/dist/token-goat-chunk-TAUZ4OFS.mjs +110 -0
  130. package/dist/token-goat-chunk-TM6MC754.mjs +40 -0
  131. package/dist/token-goat-chunk-TWUKBOMP.mjs +72 -0
  132. package/dist/token-goat-chunk-U2KSB4SG.mjs +56 -0
  133. package/dist/token-goat-chunk-U4WHMG6Y.mjs +898 -0
  134. package/dist/token-goat-chunk-UA5V6P3P.mjs +122 -0
  135. package/dist/token-goat-chunk-UGJHGR5A.mjs +52 -0
  136. package/dist/{token-goat-chunk-RQGGMPCR.mjs → token-goat-chunk-UOUDVA5U.mjs} +76 -16
  137. package/dist/{token-goat-chunk-HNFZZHFW.mjs → token-goat-chunk-URRJ33GR.mjs} +22 -4
  138. package/dist/token-goat-chunk-UZOROKIS.mjs +165 -0
  139. package/dist/token-goat-chunk-VIHGGGEI.mjs +4234 -0
  140. package/dist/token-goat-chunk-VTJLAA7P.mjs +21 -0
  141. package/dist/token-goat-chunk-VWDXLT4F.mjs +678 -0
  142. package/dist/token-goat-chunk-VWZA2H4P.mjs +368 -0
  143. package/dist/{token-goat-chunk-QO3LXVVR.mjs → token-goat-chunk-VXEXMJDL.mjs} +2964 -3153
  144. package/dist/token-goat-chunk-WBA5SKT4.mjs +547 -0
  145. package/dist/{token-goat-chunk-ONXH6NZ5.mjs → token-goat-chunk-WDH44VAU.mjs} +19 -22
  146. package/dist/token-goat-chunk-X2SUP3EI.mjs +107 -0
  147. package/dist/token-goat-chunk-X3BELZSJ.mjs +125 -0
  148. package/dist/{token-goat-chunk-RLP6J7WR.mjs → token-goat-chunk-XLRBNZCC.mjs} +40 -21
  149. package/dist/{token-goat-chunk-S4VSXURL.mjs → token-goat-chunk-XRKUX6CM.mjs} +4 -0
  150. package/dist/token-goat-chunk-XX6O25RN.mjs +82 -0
  151. package/dist/token-goat-chunk-XZSUHBVS.mjs +65 -0
  152. package/dist/token-goat-chunk-Y2ZTQOCL.mjs +35 -0
  153. package/dist/{token-goat-chunk-UA5BKWWQ.mjs → token-goat-chunk-YB4VMGK2.mjs} +15 -4
  154. package/dist/token-goat-chunk-YBIIY3HR.mjs +51 -0
  155. package/dist/{token-goat-chunk-PKRWMHVP.mjs → token-goat-chunk-YHVDKQBR.mjs} +389 -221
  156. package/dist/token-goat-chunk-YJB5XLWI.mjs +26 -0
  157. package/dist/{token-goat-chunk-PQ53BSCF.mjs → token-goat-chunk-YKB6AQG3.mjs} +53 -31
  158. package/dist/token-goat-chunk-YMTG2YA5.mjs +35 -0
  159. package/dist/token-goat-chunk-YPBZYQRV.mjs +40 -0
  160. package/dist/{token-goat-chunk-HUYUHODZ.mjs → token-goat-chunk-YY6AVUFL.mjs} +13246 -12247
  161. package/dist/token-goat-chunk-Z7N5OMMP.mjs +98 -0
  162. package/dist/{token-goat-chunk-BGHSSJUA.mjs → token-goat-chunk-ZFOBKUWH.mjs} +1 -1
  163. package/dist/token-goat-chunk-ZMBL6UVV.mjs +110 -0
  164. package/dist/token-goat-chunk-ZNMNUPAZ.mjs +938 -0
  165. package/dist/token-goat-hook-client.cjs +87 -23
  166. package/dist/token-goat-hook-client.mjs +3 -3
  167. package/dist/token-goat-hook.mjs +76 -31
  168. package/dist/token-goat.core.mjs +6 -6
  169. package/docs/C4_RUNTIME_ARCHITECTURE.md +2 -2
  170. package/docs/cli.md +113 -60
  171. package/docs/install.md +63 -20
  172. package/docs/security.md +10 -8
  173. package/package.json +18 -7
  174. package/scripts/verify-native-dist.mjs +386 -0
  175. package/dist/token-goat-chunk-2NNUA2LR.mjs +0 -143
  176. package/dist/token-goat-chunk-44BM7DDQ.mjs +0 -294
  177. package/dist/token-goat-chunk-BGYOZ6DO.mjs +0 -24
  178. package/dist/token-goat-chunk-C5YPNZKQ.mjs +0 -318
  179. package/dist/token-goat-chunk-CIQ2FTY3.mjs +0 -1990
  180. package/dist/token-goat-chunk-D4ETHJD6.mjs +0 -246
  181. package/dist/token-goat-chunk-DNRPXHYH.mjs +0 -1062
  182. package/dist/token-goat-chunk-EUSDXRXU.mjs +0 -1429
  183. package/dist/token-goat-chunk-FTP4U4QA.mjs +0 -64
  184. package/dist/token-goat-chunk-G7IWXCFF.mjs +0 -456
  185. package/dist/token-goat-chunk-GLXRTTLE.mjs +0 -36
  186. package/dist/token-goat-chunk-H5J3C56Q.mjs +0 -1511
  187. package/dist/token-goat-chunk-IVWI2OCK.mjs +0 -368
  188. package/dist/token-goat-chunk-JTKCQMQA.mjs +0 -418
  189. package/dist/token-goat-chunk-LZNBQTDK.mjs +0 -26
  190. package/dist/token-goat-chunk-ORNFMIER.mjs +0 -295
  191. package/dist/token-goat-chunk-RTMVLHWX.mjs +0 -7113
  192. package/dist/token-goat-chunk-VQ6F6T7X.mjs +0 -36
  193. package/dist/token-goat-chunk-VZQEWRVH.mjs +0 -312
  194. package/dist/token-goat-chunk-XYWPOSCN.mjs +0 -807
  195. package/dist/token-goat-chunk-YAGLESS3.mjs +0 -23
  196. package/dist/token-goat-chunk-YKSRAWUU.mjs +0 -33
  197. package/dist/token-goat-chunk-Z6KBMOBI.mjs +0 -53
@@ -0,0 +1,497 @@
1
+ import { createRequire as __cjsRequire } from 'node:module';
2
+ const require = __cjsRequire(import.meta.url);
3
+ import {
4
+ projectNotesFor
5
+ } from "./token-goat-chunk-GWFLAUMQ.mjs";
6
+ import {
7
+ computeAdaptiveBudget,
8
+ getContextPressure,
9
+ isNoisePath,
10
+ loadSessionCache
11
+ } from "./token-goat-chunk-NMD42SFQ.mjs";
12
+ import {
13
+ listSiblingSessionStates,
14
+ sessionSidecarPath
15
+ } from "./token-goat-chunk-WBA5SKT4.mjs";
16
+ import {
17
+ getBashOutput
18
+ } from "./token-goat-chunk-KQBLRPBN.mjs";
19
+ import {
20
+ blobPath,
21
+ indexRecallEntry,
22
+ isBlobStale,
23
+ loadBlob,
24
+ storeBlob
25
+ } from "./token-goat-chunk-4ZBFWLXF.mjs";
26
+ import {
27
+ WEB_FETCH_KEY_SEP,
28
+ epochReadCounts,
29
+ getSessionBashOutputs,
30
+ getSessionBashReruns,
31
+ getSessionFiles,
32
+ getSessionWebFetches,
33
+ mergeEpochBase,
34
+ wasEditedSinceCompaction
35
+ } from "./token-goat-chunk-GL3ETKSC.mjs";
36
+ import {
37
+ redactSecrets
38
+ } from "./token-goat-chunk-T5P5ACNQ.mjs";
39
+ import {
40
+ loadConfig
41
+ } from "./token-goat-chunk-7EZTZOMC.mjs";
42
+ import {
43
+ shortFingerprint
44
+ } from "./token-goat-chunk-4GBVPH3D.mjs";
45
+ import {
46
+ registerReset
47
+ } from "./token-goat-chunk-YZAAZU2S.mjs";
48
+ import {
49
+ ensureDirSync,
50
+ runGit,
51
+ toKB
52
+ } from "./token-goat-chunk-HU4TORC5.mjs";
53
+ import {
54
+ foldPath,
55
+ resolveOnPath,
56
+ spawnResolvedSync
57
+ } from "./token-goat-chunk-AM5V6GSX.mjs";
58
+ import {
59
+ UNTRUSTED_FILE_TAG,
60
+ displaySafePath,
61
+ displaySafeText,
62
+ neutralizeSpokenMarkers
63
+ } from "./token-goat-chunk-FNFBKLRD.mjs";
64
+ import {
65
+ init_define_import_meta_env
66
+ } from "./token-goat-chunk-A37V4PBF.mjs";
67
+
68
+ // src/manifest.ts
69
+ init_define_import_meta_env();
70
+
71
+ // src/web_cache.ts
72
+ init_define_import_meta_env();
73
+ import * as fs from "node:fs";
74
+ var WEB_OUTPUT_SUBDIR = "web_outputs";
75
+ var _byId = /* @__PURE__ */ new Map();
76
+ var _rawById = /* @__PURE__ */ new Map();
77
+ var _urlIndex = /* @__PURE__ */ new Map();
78
+ function cacheIdForUrl(url) {
79
+ return shortFingerprint(url);
80
+ }
81
+ function storeWebOutput(url, content, dedupKey = url, rawContent) {
82
+ const cacheId = cacheIdForUrl(dedupKey);
83
+ const redactedContent = redactSecrets(content).text;
84
+ _byId.set(cacheId, redactedContent);
85
+ _urlIndex.set(url, cacheId);
86
+ const redactedRaw = rawContent !== void 0 && rawContent !== content ? redactSecrets(rawContent).text : void 0;
87
+ if (redactedRaw !== void 0) _rawById.set(cacheId, redactedRaw);
88
+ else _rawById.delete(cacheId);
89
+ storeBlob(WEB_OUTPUT_SUBDIR, cacheId, redactedRaw !== void 0 ? { url, content: redactedContent, raw: redactedRaw } : { url, content: redactedContent });
90
+ const redactedUrl = redactSecrets(url).text;
91
+ indexRecallEntry("web", cacheId, redactedUrl, `${redactedUrl}
92
+ ${redactedContent}`, Date.now());
93
+ return cacheId;
94
+ }
95
+ function coerceWebBlob(raw) {
96
+ if (raw === null || typeof raw !== "object") return null;
97
+ const o = raw;
98
+ if (typeof o["content"] !== "string") return null;
99
+ return { url: typeof o["url"] === "string" ? o["url"] : null, content: o["content"], raw: typeof o["raw"] === "string" ? o["raw"] : null };
100
+ }
101
+ function getWebOutput(cacheId) {
102
+ const hit = _byId.get(cacheId);
103
+ if (hit !== void 0) return hit;
104
+ if (isBlobStale(WEB_OUTPUT_SUBDIR, cacheId)) return null;
105
+ const blob = coerceWebBlob(loadBlob(WEB_OUTPUT_SUBDIR, cacheId));
106
+ if (blob === null) return null;
107
+ _byId.set(cacheId, blob.content);
108
+ if (blob.raw !== null) _rawById.set(cacheId, blob.raw);
109
+ if (blob.url !== null) _urlIndex.set(blob.url, cacheId);
110
+ return blob.content;
111
+ }
112
+ function hasWebOutput(cacheId) {
113
+ if (_byId.has(cacheId)) return true;
114
+ const p = blobPath(WEB_OUTPUT_SUBDIR, cacheId);
115
+ if (p === null || isBlobStale(WEB_OUTPUT_SUBDIR, cacheId)) return false;
116
+ return fs.existsSync(p);
117
+ }
118
+ function getWebOutputRaw(cacheId) {
119
+ const cleaned = getWebOutput(cacheId);
120
+ if (cleaned === null) return null;
121
+ return _rawById.get(cacheId) ?? cleaned;
122
+ }
123
+ function getWebOutputByUrlFromDisk(url, dedupKey = url) {
124
+ const cacheId = cacheIdForUrl(dedupKey);
125
+ const content = getWebOutput(cacheId);
126
+ if (content === null) return null;
127
+ return { cacheId, content };
128
+ }
129
+ registerReset(() => {
130
+ _byId = /* @__PURE__ */ new Map();
131
+ _rawById = /* @__PURE__ */ new Map();
132
+ _urlIndex = /* @__PURE__ */ new Map();
133
+ }, { perRequest: true });
134
+
135
+ // src/manifest_fit.ts
136
+ init_define_import_meta_env();
137
+ var RESERVE_SHARE = 0.25;
138
+ function cost(lines) {
139
+ let n = 0;
140
+ for (const line of lines) n += line.length + 1;
141
+ return n;
142
+ }
143
+ var moreLine = (n) => `- ...and ${n} more`;
144
+ function rowsThatFit(s, room) {
145
+ const rows = s.rows ?? [];
146
+ const fixed = cost(s.header) + cost(s.footer ?? []);
147
+ if (rows.length === 0) return fixed <= room ? 0 : null;
148
+ const limit = Math.min(rows.length, s.maxRows ?? rows.length);
149
+ const prefix = [0];
150
+ for (let i = 0; i < limit; i++) prefix.push(prefix[i] + rows[i].length + 1);
151
+ for (let k = limit; k >= 1; k--) {
152
+ const tail = k < rows.length ? moreLine(rows.length - k).length + 1 : 0;
153
+ if (fixed + prefix[k] + tail <= room) return k;
154
+ }
155
+ return null;
156
+ }
157
+ function render(s, k) {
158
+ const rows = s.rows ?? [];
159
+ const lines = [...s.header, ...rows.slice(0, k), ...s.footer ?? []];
160
+ if (rows.length > 0 && k < rows.length) lines.push(moreLine(rows.length - k));
161
+ return lines;
162
+ }
163
+ function fitSections(sections, budget) {
164
+ const shown = sections.map(() => null);
165
+ let room = budget + 1;
166
+ const place = (indices2, limit) => {
167
+ let spent = 0;
168
+ for (const i of indices2) {
169
+ const k = rowsThatFit(sections[i], Math.min(limit, room) - spent);
170
+ if (k === null) continue;
171
+ shown[i] = k;
172
+ spent += cost(render(sections[i], k));
173
+ }
174
+ room -= spent;
175
+ };
176
+ const indices = sections.map((_, i) => i);
177
+ place(indices.filter((i) => sections[i].priority === 0 && sections[i].reserved !== true), room);
178
+ place(indices.filter((i) => sections[i].reserved === true), Math.floor(budget * RESERVE_SHARE));
179
+ const rest = indices.filter((i) => sections[i].priority !== 0 && sections[i].reserved !== true);
180
+ rest.sort((a, b) => sections[a].priority - sections[b].priority || a - b);
181
+ place(rest, room);
182
+ const lines = [];
183
+ const omitted = [];
184
+ sections.forEach((s, i) => {
185
+ const k = shown[i];
186
+ if (k === null || k === void 0) omitted.push(s.header.find((l) => l !== "") ?? "");
187
+ else lines.push(...render(s, k));
188
+ });
189
+ return { text: lines.join("\n"), shown: shown.map((k) => k ?? 0), omitted };
190
+ }
191
+
192
+ // src/manifest.ts
193
+ var MEM_EPOCH_TIMEOUT_MS = 2e3;
194
+ var MAX_ROWS = 40;
195
+ function renderReadRow(entry) {
196
+ const kb = Math.max(1, toKB(entry.sizeBytes));
197
+ const plural = entry.readCount === 1 ? "read" : "reads";
198
+ const edited = entry.wasEdited ? ", edited" : "";
199
+ return `- ${displaySafePath(entry.path)} (${kb}kb, ${entry.readCount} ${plural}${edited})`;
200
+ }
201
+ function renderSymbolReadRow(entry) {
202
+ return `- ${displaySafePath(entry.path)} (symbols: ${(entry.symbols_read ?? []).map(displaySafeText).join(", ")})`;
203
+ }
204
+ function mergeManifestFiles(parent, siblingFiles) {
205
+ const byPath = /* @__PURE__ */ new Map();
206
+ for (const f of parent) byPath.set(foldPath(f.path), f);
207
+ for (const f of siblingFiles) {
208
+ const key = foldPath(f.path);
209
+ const prev = byPath.get(key);
210
+ if (prev === void 0) {
211
+ byPath.set(key, f);
212
+ continue;
213
+ }
214
+ const mergedSymbols = [.../* @__PURE__ */ new Set([...prev.symbols_read ?? [], ...f.symbols_read ?? []])];
215
+ const fullReadCount = Math.max(prev.fullReadCount ?? 0, f.fullReadCount ?? 0);
216
+ const lastFullReadAt = Math.max(prev.lastFullReadAt ?? -1, f.lastFullReadAt ?? -1);
217
+ const epochBase = mergeEpochBase(prev.epochBase, f.epochBase);
218
+ const lastEditedAt = Math.max(prev.lastEditedAt ?? 0, f.lastEditedAt ?? 0);
219
+ byPath.set(key, {
220
+ path: prev.path,
221
+ readCount: Math.max(prev.readCount, f.readCount),
222
+ lastReadAt: Math.max(prev.lastReadAt, f.lastReadAt),
223
+ ...fullReadCount > 0 ? { fullReadCount } : {},
224
+ ...lastFullReadAt >= 0 ? { lastFullReadAt } : {},
225
+ wasEdited: prev.wasEdited || f.wasEdited,
226
+ ...lastEditedAt > 0 ? { lastEditedAt } : {},
227
+ sizeBytes: f.lastReadAt >= prev.lastReadAt ? f.sizeBytes : prev.sizeBytes,
228
+ ...prev.wasTruncated || f.wasTruncated ? { wasTruncated: true } : {},
229
+ ...mergedSymbols.length > 0 ? { symbols_read: mergedSymbols } : {},
230
+ ...epochBase !== void 0 ? { epochBase } : {}
231
+ });
232
+ }
233
+ return Array.from(byPath.values());
234
+ }
235
+ function renderWebFetchRow(key, cacheId, live = true) {
236
+ const [url = key, prompt = ""] = key.split(WEB_FETCH_KEY_SEP);
237
+ if (!live) return `- ${displaySafeText(url)} (cache expired)`;
238
+ const promptSuffix = prompt ? `, prompt: ${neutralizeSpokenMarkers(JSON.stringify(prompt))}` : "";
239
+ return `- ${displaySafeText(url)} (cacheId: ${cacheId}${promptSuffix})`;
240
+ }
241
+ function renderWebFetchRows(entries) {
242
+ const live = entries.map(([, cacheId]) => hasWebOutput(cacheId));
243
+ if (entries.length > 0 && !live.includes(true)) {
244
+ const urls = entries.map(([key]) => displaySafeText(key.split(WEB_FETCH_KEY_SEP)[0] ?? key));
245
+ return [`- ${entries.length} fetched page${entries.length === 1 ? "" : "s"}, cache expired: ${urls.join(", ")}`];
246
+ }
247
+ return entries.map(([key, cacheId], n) => renderWebFetchRow(key, cacheId, live[n]));
248
+ }
249
+ function selectManifestFiles(siblings) {
250
+ const ownFiles = [...getSessionFiles().values()];
251
+ const siblingFiles = siblings.flatMap((s) => s.files);
252
+ const files = siblingFiles.length > 0 ? mergeManifestFiles(ownFiles, siblingFiles) : ownFiles;
253
+ const editedFiles = files.filter((f) => f.wasEdited);
254
+ const readFiles = files.filter((f) => f.readCount > 0 && !f.wasEdited && !isNoisePath(f.path));
255
+ const symbolOnlyFiles = files.filter((f) => f.readCount === 0 && !f.wasEdited && (f.symbols_read?.length ?? 0) > 0);
256
+ return { files, readFiles, editedFiles, symbolOnlyFiles };
257
+ }
258
+ function selectManifestWebFetches(siblings) {
259
+ const merged = /* @__PURE__ */ new Map();
260
+ for (const sibling of siblings) for (const [key, cacheId] of sibling.webFetches) merged.set(key, cacheId);
261
+ for (const [key, cacheId] of getSessionWebFetches()) merged.set(key, cacheId);
262
+ return [...merged.entries()];
263
+ }
264
+ function manifestPrintedPaths(sessionId, limit, cwd, transcriptPath) {
265
+ const { printed } = buildManifestParts(sessionId, cwd, transcriptPath);
266
+ return printed.slice(0, limit);
267
+ }
268
+ function buildManifestParts(sessionId, cwd, transcriptPath) {
269
+ const siblings = sessionId !== void 0 ? listSiblingSessionStates(sessionId) : [];
270
+ const { files, readFiles, editedFiles, symbolOnlyFiles } = selectManifestFiles(siblings);
271
+ const webFetches = selectManifestWebFetches(siblings);
272
+ const fileSections = [];
273
+ const fileSection = (header, entries, render2, priority) => {
274
+ if (entries.length === 0) return [];
275
+ const section = { header: ["", header], rows: entries.map(render2), priority, maxRows: MAX_ROWS };
276
+ fileSections.push({ entries, section });
277
+ return [section];
278
+ };
279
+ const notes = projectNotesFor(cwd);
280
+ const webRows = renderWebFetchRows(webFetches);
281
+ const sections = [
282
+ { header: ["## Session context", `Files read: ${readFiles.length}`, `Files edited: ${editedFiles.length}`], priority: 0 },
283
+ ...fileSection("### Edited files", editedFiles, (entry) => `- ${displaySafePath(entry.path)}`, 1),
284
+ ...notes === null ? [] : [notesSection(notes)],
285
+ ...fileSection("### Surgically read files (symbol/section reads, never read whole)", symbolOnlyFiles, renderSymbolReadRow, 3),
286
+ ...fileSection("### Read files", readFiles, renderReadRow, 4),
287
+ ...webRows.length === 0 ? [] : [{ header: ["", "### Web URLs fetched"], rows: webRows, priority: 5, maxRows: MAX_ROWS }],
288
+ ...buildSafeToDiscardSection(files),
289
+ ...buildMemEpochSection()
290
+ ];
291
+ const fit = fitManifest(sections, sessionId, cwd, transcriptPath);
292
+ const seen = /* @__PURE__ */ new Set();
293
+ const printed = [];
294
+ for (const { entries, section } of fileSections) {
295
+ const count = fit.shown[sections.indexOf(section)] ?? 0;
296
+ for (const entry of entries.slice(0, count)) {
297
+ const path = displaySafePath(entry.path);
298
+ if (seen.has(path)) continue;
299
+ seen.add(path);
300
+ printed.push(path);
301
+ }
302
+ }
303
+ return { text: fit.text, printed };
304
+ }
305
+ function buildManifest(sessionId, cwd, transcriptPath) {
306
+ return buildManifestParts(sessionId, cwd, transcriptPath).text;
307
+ }
308
+ function gitDirtySignals(cwd) {
309
+ const timeoutMs = loadConfig().hints.git_hint_max_ms;
310
+ let hasPendingDiff = false;
311
+ try {
312
+ const diffResult = runGit(["diff", "--no-color", "--stat", "HEAD"], { cwd, timeoutMs });
313
+ hasPendingDiff = diffResult.exitCode === 0 && diffResult.stdout.trim() !== "";
314
+ } catch {
315
+ }
316
+ let hasUncommittedChanges = false;
317
+ try {
318
+ const statusResult = runGit(["status", "--porcelain"], { cwd, timeoutMs });
319
+ hasUncommittedChanges = statusResult.exitCode === 0 && statusResult.stdout.trim() !== "";
320
+ } catch {
321
+ }
322
+ return { hasPendingDiff, hasUncommittedChanges };
323
+ }
324
+ function adaptiveCharBonus(sessionId, cwd, transcriptPath) {
325
+ if (!cwd) return 0;
326
+ const cache = loadSessionCache(sessionId ?? "") ?? {};
327
+ const ageSecs = cache.created_ts !== void 0 ? Math.max(0, Date.now() / 1e3 - cache.created_ts) : 0;
328
+ const contextPressure = getContextPressure(cache, transcriptPath);
329
+ const { hasPendingDiff, hasUncommittedChanges } = gitDirtySignals(cwd);
330
+ if (!hasPendingDiff && !hasUncommittedChanges) return 0;
331
+ const baseline = computeAdaptiveBudget(cache, ageSecs, { contextPressure });
332
+ const withGitSignal = computeAdaptiveBudget(cache, ageSecs, { hasPendingDiff, hasUncommittedChanges, contextPressure });
333
+ const deltaTokens = Math.max(0, withGitSignal - baseline);
334
+ return deltaTokens * 3;
335
+ }
336
+ function fitManifest(sections, sessionId, cwd, transcriptPath) {
337
+ const full = fitSections(sections, Infinity);
338
+ const cap = loadConfig().compact_assist.max_manifest_chars;
339
+ if (cap <= 0 || full.text.length <= cap) return full;
340
+ const effectiveCap = cap + adaptiveCharBonus(sessionId, cwd, transcriptPath);
341
+ if (full.text.length <= effectiveCap) return full;
342
+ const fit = fitSections(sections, effectiveCap);
343
+ const gone = fit.omitted.length > 0 ? `; sections omitted: ${fit.omitted.map((h) => h.replace(/^#+\s*/, "")).join(", ")}` : "";
344
+ const notice = `
345
+ ...(manifest truncated at ${effectiveCap} chars; ${full.text.length - fit.text.length} chars omitted${gone})`;
346
+ return { text: closeCutFence(fit.text) + notice, shown: fit.shown };
347
+ }
348
+ function closeCutFence(kept) {
349
+ const open = `<${UNTRUSTED_FILE_TAG}>`;
350
+ const close = `
351
+ </${UNTRUSTED_FILE_TAG}>`;
352
+ const lastOpen = kept.lastIndexOf(open);
353
+ if (lastOpen === -1 || kept.includes(close, lastOpen)) return kept;
354
+ let body = kept;
355
+ for (let n = close.length - 1; n > 0; n--) {
356
+ if (body.endsWith(close.slice(0, n))) {
357
+ body = body.slice(0, -n);
358
+ break;
359
+ }
360
+ }
361
+ return body + close;
362
+ }
363
+ function notesSection(notes) {
364
+ const lines = notes.split("\n");
365
+ const open = lines.indexOf(`<${UNTRUSTED_FILE_TAG}>`);
366
+ const close = lines.lastIndexOf(`</${UNTRUSTED_FILE_TAG}>`);
367
+ if (open === -1 || close < open) return { header: ["", ...lines], priority: 2 };
368
+ const rows = [];
369
+ for (const line of lines.slice(open + 1, close)) {
370
+ if (rows.length > 0 && !line.startsWith("- ")) rows[rows.length - 1] += "\n" + line;
371
+ else rows.push(line);
372
+ }
373
+ return { header: ["", ...lines.slice(0, open + 1)], rows, footer: lines.slice(close), priority: 2, maxRows: MAX_ROWS };
374
+ }
375
+ function readIsSuperseded(f) {
376
+ const { reads, fullReads } = epochReadCounts(f);
377
+ if (wasEditedSinceCompaction(f)) return fullReads > 0;
378
+ return fullReads > 1 || reads > 1 && fullReads > 0 && f.lastFullReadAt !== void 0 && f.lastFullReadAt >= f.lastReadAt;
379
+ }
380
+ function buildSafeToDiscardSection(files) {
381
+ const rerunHashes = getSessionBashReruns();
382
+ const bashOutputs = getSessionBashOutputs();
383
+ const rerunHashSet = new Set(rerunHashes);
384
+ const rerunRows = [];
385
+ for (const hash of rerunHashes) {
386
+ const id = bashOutputs.find(([h]) => h === hash)?.[1];
387
+ if (id === void 0) continue;
388
+ const entry = getBashOutput(id);
389
+ if (entry === null) continue;
390
+ const flatCommand = neutralizeSpokenMarkers(entry.command.replace(/[\t\r\n]+/g, " "));
391
+ rerunRows.push("- `" + flatCommand + "` \u2014 an older run of this exact command was superseded; recall the surviving copy with `bash-output " + id + " --full`");
392
+ }
393
+ const supersededReadRows = [];
394
+ for (const f of files) {
395
+ if (readIsSuperseded(f)) {
396
+ const reason = wasEditedSinceCompaction(f) ? "edited after being read" : "re-read " + epochReadCounts(f).reads + "x";
397
+ supersededReadRows.push("- " + displaySafePath(f.path) + " (" + reason + " \u2014 only the latest content already in context is current)");
398
+ }
399
+ }
400
+ const cachedOutputRows = [];
401
+ for (const [hash, id] of bashOutputs) {
402
+ if (rerunHashSet.has(hash)) continue;
403
+ const entry = getBashOutput(id);
404
+ if (entry === null) continue;
405
+ const flatCommand = neutralizeSpokenMarkers(entry.command.replace(/[\t\r\n]+/g, " "));
406
+ cachedOutputRows.push("- `" + flatCommand + "` \u2014 recallable via `bash-output " + id + " --full`");
407
+ }
408
+ const total = rerunRows.length + supersededReadRows.length + cachedOutputRows.length;
409
+ if (total === 0) return [];
410
+ const title = "### SAFE_TO_DISCARD (" + total + " items \u2014 provably inert; each is recallable, not gone)";
411
+ const groups = [
412
+ ["Superseded reruns (" + rerunRows.length + "):", rerunRows],
413
+ ["Superseded file reads (" + supersededReadRows.length + "):", supersededReadRows],
414
+ ["Other cached bash outputs (" + cachedOutputRows.length + "):", cachedOutputRows]
415
+ ];
416
+ const sections = [];
417
+ for (const [header, rows] of groups) {
418
+ if (rows.length === 0) continue;
419
+ sections.push({ header: sections.length === 0 ? ["", title, "", header] : ["", header], rows, priority: 9, reserved: true, maxRows: MAX_ROWS });
420
+ }
421
+ return sections;
422
+ }
423
+ function buildMemEpochSection(timeoutMs = MEM_EPOCH_TIMEOUT_MS) {
424
+ let result;
425
+ try {
426
+ const resolved = resolveOnPath("mem");
427
+ if (resolved === null) return [];
428
+ result = spawnResolvedSync(resolved, ["epoch"], {
429
+ encoding: "utf-8",
430
+ timeout: timeoutMs,
431
+ windowsHide: true
432
+ });
433
+ } catch {
434
+ return [];
435
+ }
436
+ if (result.error !== void 0 || result.status !== 0) return [];
437
+ const stdout = typeof result.stdout === "string" ? result.stdout.trim() : "";
438
+ if (!/^\d+$/.test(stdout)) return [];
439
+ return [{
440
+ header: ["", "### mem epoch", `mem epoch: ${stdout} (no live TGMEM block is tracked in this session -- only the epoch counter is folded in; see buildMemEpochSection's doc comment)`],
441
+ priority: 9,
442
+ reserved: true
443
+ }];
444
+ }
445
+ var MANIFEST_PREAMBLE = "When summarizing this session, keep the file paths and symbol names below exactly as written -- they are the handles the next turn needs to resume work. Do not paraphrase them into prose.";
446
+ var MANIFEST_RECOVERY_PREAMBLE = "The conversation was just compacted. Below is what this session touched, recovered from token-goat's own ledger rather than from the summary -- use it to re-establish paths and symbol names the summary may have dropped.";
447
+ var BUDGET_ESCALATION_MARKER = "TG-BUDGET-ESCALATION:";
448
+ function summaryBudgetDirective(budgetChars) {
449
+ if (budgetChars <= 0) return "";
450
+ return ` Aim for at most ${budgetChars} characters. Prefer a shorter summary that keeps every path, symbol, command and decision over a longer one that reproduces tool output verbatim: cite the recall id (\`token-goat bash-output <id> --full\`) rather than quoting the output again. If this session genuinely cannot be summarized within that target without losing state the next turn needs, exceed it and open the summary with a single line reading \`${BUDGET_ESCALATION_MARKER} <one-sentence reason>\`.`;
451
+ }
452
+
453
+ // src/compact_dropped.ts
454
+ init_define_import_meta_env();
455
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
456
+ import { dirname } from "node:path";
457
+ var DROPPED_SUFFIX = ".compact-dropped";
458
+ function recordCompactDroppedPaths(stateKey, paths) {
459
+ const target = sessionSidecarPath(stateKey, DROPPED_SUFFIX);
460
+ if (target === null) return;
461
+ try {
462
+ if (paths === null || paths.length === 0) {
463
+ rmSync(target, { force: true });
464
+ return;
465
+ }
466
+ ensureDirSync(dirname(target));
467
+ writeFileSync(target, JSON.stringify(paths), "utf8");
468
+ } catch {
469
+ }
470
+ }
471
+ function readCompactDroppedPaths(stateKey) {
472
+ const target = sessionSidecarPath(stateKey, DROPPED_SUFFIX);
473
+ if (target === null) return [];
474
+ try {
475
+ const parsed = JSON.parse(readFileSync(target, "utf8"));
476
+ return Array.isArray(parsed) ? parsed.filter((p) => typeof p === "string" && p !== "") : [];
477
+ } catch {
478
+ return [];
479
+ }
480
+ }
481
+
482
+ export {
483
+ WEB_OUTPUT_SUBDIR,
484
+ storeWebOutput,
485
+ getWebOutput,
486
+ getWebOutputRaw,
487
+ getWebOutputByUrlFromDisk,
488
+ renderWebFetchRows,
489
+ manifestPrintedPaths,
490
+ buildManifest,
491
+ MANIFEST_PREAMBLE,
492
+ MANIFEST_RECOVERY_PREAMBLE,
493
+ BUDGET_ESCALATION_MARKER,
494
+ summaryBudgetDirective,
495
+ recordCompactDroppedPaths,
496
+ readCompactDroppedPaths
497
+ };
@@ -0,0 +1,58 @@
1
+ import { createRequire as __cjsRequire } from 'node:module';
2
+ const require = __cjsRequire(import.meta.url);
3
+ import {
4
+ getDb,
5
+ pathEqClause
6
+ } from "./token-goat-chunk-GVB2MUST.mjs";
7
+ import {
8
+ findProject
9
+ } from "./token-goat-chunk-4GBVPH3D.mjs";
10
+ import {
11
+ canonicalize,
12
+ foldPath
13
+ } from "./token-goat-chunk-AM5V6GSX.mjs";
14
+ import {
15
+ normalizePath
16
+ } from "./token-goat-chunk-FNFBKLRD.mjs";
17
+ import {
18
+ globalDbPath
19
+ } from "./token-goat-chunk-CO3UYX6G.mjs";
20
+ import {
21
+ init_define_import_meta_env
22
+ } from "./token-goat-chunk-A37V4PBF.mjs";
23
+
24
+ // src/indexed_roots.ts
25
+ init_define_import_meta_env();
26
+ import * as path from "node:path";
27
+ function indexedRootOf(dir) {
28
+ const project = findProject(dir);
29
+ if (project !== null) return normalizePath(project.root);
30
+ try {
31
+ return normalizePath(canonicalize(path.resolve(dir)));
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+ function recordIndexedRoot(dir, dbPath = globalDbPath()) {
37
+ try {
38
+ const root = indexedRootOf(dir);
39
+ if (root === null) return;
40
+ getDb(dbPath).prepare("INSERT INTO indexed_roots (root, indexed_ms) VALUES (?, ?) ON CONFLICT(root) DO UPDATE SET indexed_ms = excluded.indexed_ms").run(root, Date.now());
41
+ } catch {
42
+ }
43
+ }
44
+ function isIndexedRoot(dir, dbPath = globalDbPath()) {
45
+ if (dir === void 0) return false;
46
+ try {
47
+ const root = indexedRootOf(dir);
48
+ if (root === null) return false;
49
+ return getDb(dbPath).prepare(`SELECT 1 FROM indexed_roots WHERE ${pathEqClause("root")} LIMIT 1`).get(foldPath(root)) !== void 0;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+
55
+ export {
56
+ recordIndexedRoot,
57
+ isIndexedRoot
58
+ };
@@ -0,0 +1,87 @@
1
+ import { createRequire as __cjsRequire } from 'node:module';
2
+ const require = __cjsRequire(import.meta.url);
3
+ import {
4
+ fenceUntrusted,
5
+ fenceWithMatches
6
+ } from "./token-goat-chunk-4NAPX7BA.mjs";
7
+ import {
8
+ estimateTokens,
9
+ trimToBudget
10
+ } from "./token-goat-chunk-BFCWY73P.mjs";
11
+ import {
12
+ GUARD_UNITS_PER_TOKEN,
13
+ guardUnits
14
+ } from "./token-goat-chunk-XX6O25RN.mjs";
15
+ import {
16
+ redactSecrets
17
+ } from "./token-goat-chunk-T5P5ACNQ.mjs";
18
+ import {
19
+ loadConfig
20
+ } from "./token-goat-chunk-7EZTZOMC.mjs";
21
+ import {
22
+ UNTRUSTED_FILE_TAG,
23
+ scanForInjectionPatterns
24
+ } from "./token-goat-chunk-FNFBKLRD.mjs";
25
+ import {
26
+ init_define_import_meta_env
27
+ } from "./token-goat-chunk-A37V4PBF.mjs";
28
+
29
+ // src/fence_cap.ts
30
+ init_define_import_meta_env();
31
+ function guardThenFence(text, command, tag) {
32
+ const cfg = loadConfig();
33
+ if (!cfg.overflow_guard.enabled) return fenceUntrusted(text, tag);
34
+ const budget = cfg.overflow_guard.max_tokens;
35
+ let capped = trimToBudget(text, budget, command);
36
+ let reserve = 0;
37
+ for (let pass = 0; pass < 8; pass++) {
38
+ const excess = estimateTokens(fenceThenMarker(capped, text, (body) => fenceWithMatches(body, scanUnrecorded(body), tag))) - budget;
39
+ if (excess <= 0) break;
40
+ reserve += excess;
41
+ capped = trimToBudget(text, budget, command, { reserveTokens: reserve });
42
+ }
43
+ return fenceThenMarker(capped, text, (body) => fenceUntrusted(body, tag));
44
+ }
45
+ function fenceThenMarker(capped, text, fence) {
46
+ if (capped === text) return fence(text);
47
+ const markerAt = capped.lastIndexOf("\n");
48
+ return `${fence(capped.slice(0, markerAt))}
49
+ ${capped.slice(markerAt + 1)}`;
50
+ }
51
+ function scanUnrecorded(text) {
52
+ try {
53
+ return scanForInjectionPatterns(text);
54
+ } catch {
55
+ return [];
56
+ }
57
+ }
58
+ function guardRedactAndFence(text, command, tag) {
59
+ return guardThenFence(redactSecrets(text).text, command, tag);
60
+ }
61
+ function guardAndFenceFileText(text, command) {
62
+ return guardRedactAndFence(text, command, UNTRUSTED_FILE_TAG);
63
+ }
64
+ function capListField(obj, key, render) {
65
+ const full = render(obj);
66
+ const cfg = loadConfig();
67
+ if (!cfg.overflow_guard.enabled) return full;
68
+ const budget = cfg.overflow_guard.max_tokens * GUARD_UNITS_PER_TOKEN;
69
+ const items = obj[key];
70
+ if (guardUnits(full) <= budget || items.length <= 1) return full;
71
+ const cut = (kept) => render({ ...obj, [key]: items.slice(0, kept), truncated: true, totalCount: items.length });
72
+ let lo = 1;
73
+ let hi = items.length - 1;
74
+ while (lo < hi) {
75
+ const mid = lo + hi + 1 >> 1;
76
+ if (guardUnits(cut(mid)) <= budget) lo = mid;
77
+ else hi = mid - 1;
78
+ }
79
+ return cut(lo);
80
+ }
81
+
82
+ export {
83
+ guardThenFence,
84
+ guardRedactAndFence,
85
+ guardAndFenceFileText,
86
+ capListField
87
+ };