@seanhogg/builderforce-webcontainers 2026.10.11 → 2026.10.14

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 (372) hide show
  1. package/README.md +22 -0
  2. package/dist/adaptive/controller.d.ts +39 -0
  3. package/dist/adaptive/controller.d.ts.map +1 -0
  4. package/dist/adaptive/controller.js +108 -0
  5. package/dist/adaptive/controller.js.map +1 -0
  6. package/dist/adaptive/costModel.d.ts +37 -0
  7. package/dist/adaptive/costModel.d.ts.map +1 -0
  8. package/dist/adaptive/costModel.js +102 -0
  9. package/dist/adaptive/costModel.js.map +1 -0
  10. package/dist/adaptive/planner.d.ts +22 -0
  11. package/dist/adaptive/planner.d.ts.map +1 -0
  12. package/dist/adaptive/planner.js +114 -0
  13. package/dist/adaptive/planner.js.map +1 -0
  14. package/dist/adaptive/types.d.ts +138 -0
  15. package/dist/adaptive/types.d.ts.map +1 -0
  16. package/dist/adaptive/types.js +12 -0
  17. package/dist/adaptive/types.js.map +1 -0
  18. package/dist/assets.js +2 -2
  19. package/dist/check/cachedFetch.js.map +1 -1
  20. package/dist/check/index.d.ts +6 -1
  21. package/dist/check/index.d.ts.map +1 -1
  22. package/dist/check/index.js +6 -1
  23. package/dist/check/index.js.map +1 -1
  24. package/dist/componentCompilers.d.ts.map +1 -1
  25. package/dist/componentCompilers.js.map +1 -1
  26. package/dist/esbuildWasm.js.map +1 -1
  27. package/dist/host.d.ts +11 -5
  28. package/dist/host.d.ts.map +1 -1
  29. package/dist/host.js +19 -8
  30. package/dist/host.js.map +1 -1
  31. package/dist/inference/backends/mock.d.ts +24 -0
  32. package/dist/inference/backends/mock.d.ts.map +1 -0
  33. package/dist/inference/backends/mock.js +55 -0
  34. package/dist/inference/backends/mock.js.map +1 -0
  35. package/dist/inference/backends/onnx.d.ts +33 -0
  36. package/dist/inference/backends/onnx.d.ts.map +1 -0
  37. package/dist/inference/backends/onnx.js +60 -0
  38. package/dist/inference/backends/onnx.js.map +1 -0
  39. package/dist/inference/backends/webllm.d.ts +27 -0
  40. package/dist/inference/backends/webllm.d.ts.map +1 -0
  41. package/dist/inference/backends/webllm.js +52 -0
  42. package/dist/inference/backends/webllm.js.map +1 -0
  43. package/dist/inference/backends/wllama.d.ts +29 -0
  44. package/dist/inference/backends/wllama.d.ts.map +1 -0
  45. package/dist/inference/backends/wllama.js +51 -0
  46. package/dist/inference/backends/wllama.js.map +1 -0
  47. package/dist/inference/capabilities.d.ts +20 -0
  48. package/dist/inference/capabilities.d.ts.map +1 -0
  49. package/dist/inference/capabilities.js +33 -0
  50. package/dist/inference/capabilities.js.map +1 -0
  51. package/dist/inference/client.d.ts +45 -0
  52. package/dist/inference/client.d.ts.map +1 -0
  53. package/dist/inference/client.js +201 -0
  54. package/dist/inference/client.js.map +1 -0
  55. package/dist/inference/modelCache.d.ts +71 -0
  56. package/dist/inference/modelCache.d.ts.map +1 -0
  57. package/dist/inference/modelCache.js +91 -0
  58. package/dist/inference/modelCache.js.map +1 -0
  59. package/dist/inference/protocol.d.ts +94 -0
  60. package/dist/inference/protocol.d.ts.map +1 -0
  61. package/dist/inference/protocol.js +19 -0
  62. package/dist/inference/protocol.js.map +1 -0
  63. package/dist/inference/tokenStream.d.ts +26 -0
  64. package/dist/inference/tokenStream.d.ts.map +1 -0
  65. package/dist/inference/tokenStream.js +79 -0
  66. package/dist/inference/tokenStream.js.map +1 -0
  67. package/dist/inference/types.d.ts +108 -0
  68. package/dist/inference/types.d.ts.map +1 -0
  69. package/dist/inference/types.js +8 -0
  70. package/dist/inference/types.js.map +1 -0
  71. package/dist/inference/worker.bundle.js +5 -0
  72. package/dist/inference/worker.d.ts +35 -0
  73. package/dist/inference/worker.d.ts.map +1 -0
  74. package/dist/inference/worker.js +157 -0
  75. package/dist/inference/worker.js.map +1 -0
  76. package/dist/inference/workerEntry.d.ts +15 -0
  77. package/dist/inference/workerEntry.d.ts.map +1 -0
  78. package/dist/inference/workerEntry.js +17 -0
  79. package/dist/inference/workerEntry.js.map +1 -0
  80. package/dist/kvcache/advanced.d.ts +39 -0
  81. package/dist/kvcache/advanced.d.ts.map +1 -0
  82. package/dist/kvcache/advanced.js +59 -0
  83. package/dist/kvcache/advanced.js.map +1 -0
  84. package/dist/kvcache/compatibility.d.ts +14 -0
  85. package/dist/kvcache/compatibility.d.ts.map +1 -0
  86. package/dist/kvcache/compatibility.js +44 -0
  87. package/dist/kvcache/compatibility.js.map +1 -0
  88. package/dist/kvcache/lru.d.ts +45 -0
  89. package/dist/kvcache/lru.d.ts.map +1 -0
  90. package/dist/kvcache/lru.js +91 -0
  91. package/dist/kvcache/lru.js.map +1 -0
  92. package/dist/kvcache/paged.d.ts +86 -0
  93. package/dist/kvcache/paged.d.ts.map +1 -0
  94. package/dist/kvcache/paged.js +238 -0
  95. package/dist/kvcache/paged.js.map +1 -0
  96. package/dist/kvcache/quant.d.ts +30 -0
  97. package/dist/kvcache/quant.d.ts.map +1 -0
  98. package/dist/kvcache/quant.js +73 -0
  99. package/dist/kvcache/quant.js.map +1 -0
  100. package/dist/kvcache/radix.d.ts +28 -0
  101. package/dist/kvcache/radix.d.ts.map +1 -0
  102. package/dist/kvcache/radix.js +58 -0
  103. package/dist/kvcache/radix.js.map +1 -0
  104. package/dist/kvcache/runtime.d.ts +11 -0
  105. package/dist/kvcache/runtime.d.ts.map +1 -0
  106. package/dist/kvcache/runtime.js +204 -0
  107. package/dist/kvcache/runtime.js.map +1 -0
  108. package/dist/kvcache/types.d.ts +151 -0
  109. package/dist/kvcache/types.d.ts.map +1 -0
  110. package/dist/kvcache/types.js +10 -0
  111. package/dist/kvcache/types.js.map +1 -0
  112. package/dist/learning/fingerprint.d.ts +17 -0
  113. package/dist/learning/fingerprint.d.ts.map +1 -0
  114. package/dist/learning/fingerprint.js +46 -0
  115. package/dist/learning/fingerprint.js.map +1 -0
  116. package/dist/learning/index.d.ts +5 -0
  117. package/dist/learning/index.d.ts.map +1 -0
  118. package/dist/learning/index.js +3 -0
  119. package/dist/learning/index.js.map +1 -0
  120. package/dist/learning/learner.d.ts +21 -0
  121. package/dist/learning/learner.d.ts.map +1 -0
  122. package/dist/learning/learner.js +272 -0
  123. package/dist/learning/learner.js.map +1 -0
  124. package/dist/learning/ledger.d.ts +26 -0
  125. package/dist/learning/ledger.d.ts.map +1 -0
  126. package/dist/learning/ledger.js +40 -0
  127. package/dist/learning/ledger.js.map +1 -0
  128. package/dist/learning/selection.d.ts +44 -0
  129. package/dist/learning/selection.d.ts.map +1 -0
  130. package/dist/learning/selection.js +111 -0
  131. package/dist/learning/selection.js.map +1 -0
  132. package/dist/learning/stats.d.ts +19 -0
  133. package/dist/learning/stats.d.ts.map +1 -0
  134. package/dist/learning/stats.js +31 -0
  135. package/dist/learning/stats.js.map +1 -0
  136. package/dist/learning/types.d.ts +133 -0
  137. package/dist/learning/types.d.ts.map +1 -0
  138. package/dist/learning/types.js +8 -0
  139. package/dist/learning/types.js.map +1 -0
  140. package/dist/memory/envProbe.d.ts +16 -0
  141. package/dist/memory/envProbe.d.ts.map +1 -0
  142. package/dist/memory/envProbe.js +28 -0
  143. package/dist/memory/envProbe.js.map +1 -0
  144. package/dist/memory/estimates.d.ts +46 -0
  145. package/dist/memory/estimates.d.ts.map +1 -0
  146. package/dist/memory/estimates.js +72 -0
  147. package/dist/memory/estimates.js.map +1 -0
  148. package/dist/memory/eviction.d.ts +42 -0
  149. package/dist/memory/eviction.d.ts.map +1 -0
  150. package/dist/memory/eviction.js +143 -0
  151. package/dist/memory/eviction.js.map +1 -0
  152. package/dist/memory/manager.d.ts +34 -0
  153. package/dist/memory/manager.d.ts.map +1 -0
  154. package/dist/memory/manager.js +346 -0
  155. package/dist/memory/manager.js.map +1 -0
  156. package/dist/memory/managerTypes.d.ts +49 -0
  157. package/dist/memory/managerTypes.d.ts.map +1 -0
  158. package/dist/memory/managerTypes.js +7 -0
  159. package/dist/memory/managerTypes.js.map +1 -0
  160. package/dist/memory/pressure.d.ts +56 -0
  161. package/dist/memory/pressure.d.ts.map +1 -0
  162. package/dist/memory/pressure.js +80 -0
  163. package/dist/memory/pressure.js.map +1 -0
  164. package/dist/memory/spillTier.d.ts +47 -0
  165. package/dist/memory/spillTier.d.ts.map +1 -0
  166. package/dist/memory/spillTier.js +128 -0
  167. package/dist/memory/spillTier.js.map +1 -0
  168. package/dist/memory/storageSink.d.ts +69 -0
  169. package/dist/memory/storageSink.d.ts.map +1 -0
  170. package/dist/memory/storageSink.js +221 -0
  171. package/dist/memory/storageSink.js.map +1 -0
  172. package/dist/memory/types.d.ts +202 -0
  173. package/dist/memory/types.d.ts.map +1 -0
  174. package/dist/memory/types.js +15 -0
  175. package/dist/memory/types.js.map +1 -0
  176. package/dist/memory/victims.d.ts +32 -0
  177. package/dist/memory/victims.d.ts.map +1 -0
  178. package/dist/memory/victims.js +74 -0
  179. package/dist/memory/victims.js.map +1 -0
  180. package/dist/memory/workspace.d.ts +34 -0
  181. package/dist/memory/workspace.d.ts.map +1 -0
  182. package/dist/memory/workspace.js +55 -0
  183. package/dist/memory/workspace.js.map +1 -0
  184. package/dist/memoryIntegration/index.d.ts +8 -0
  185. package/dist/memoryIntegration/index.d.ts.map +1 -0
  186. package/dist/memoryIntegration/index.js +4 -0
  187. package/dist/memoryIntegration/index.js.map +1 -0
  188. package/dist/memoryIntegration/knowledgeMemory.d.ts +43 -0
  189. package/dist/memoryIntegration/knowledgeMemory.d.ts.map +1 -0
  190. package/dist/memoryIntegration/knowledgeMemory.js +285 -0
  191. package/dist/memoryIntegration/knowledgeMemory.js.map +1 -0
  192. package/dist/memoryIntegration/persistence.d.ts +15 -0
  193. package/dist/memoryIntegration/persistence.d.ts.map +1 -0
  194. package/dist/memoryIntegration/persistence.js +43 -0
  195. package/dist/memoryIntegration/persistence.js.map +1 -0
  196. package/dist/memoryIntegration/text.d.ts +57 -0
  197. package/dist/memoryIntegration/text.d.ts.map +1 -0
  198. package/dist/memoryIntegration/text.js +179 -0
  199. package/dist/memoryIntegration/text.js.map +1 -0
  200. package/dist/memoryIntegration/types.d.ts +131 -0
  201. package/dist/memoryIntegration/types.d.ts.map +1 -0
  202. package/dist/memoryIntegration/types.js +11 -0
  203. package/dist/memoryIntegration/types.js.map +1 -0
  204. package/dist/ml.d.ts +52 -0
  205. package/dist/ml.d.ts.map +1 -0
  206. package/dist/ml.js +33 -0
  207. package/dist/ml.js.map +1 -0
  208. package/dist/node/childRelay.d.ts +10 -0
  209. package/dist/node/childRelay.d.ts.map +1 -1
  210. package/dist/node/childRelay.js +12 -2
  211. package/dist/node/childRelay.js.map +1 -1
  212. package/dist/node/index.js.map +1 -1
  213. package/dist/node/portResponder.d.ts +2 -0
  214. package/dist/node/portResponder.d.ts.map +1 -1
  215. package/dist/node/portResponder.js +3 -3
  216. package/dist/node/portResponder.js.map +1 -1
  217. package/dist/node/processHost.d.ts +4 -1
  218. package/dist/node/processHost.d.ts.map +1 -1
  219. package/dist/node/processHost.js +19 -16
  220. package/dist/node/processHost.js.map +1 -1
  221. package/dist/node/protocol.d.ts +1 -0
  222. package/dist/node/protocol.d.ts.map +1 -1
  223. package/dist/node/responseWire.d.ts.map +1 -1
  224. package/dist/node/worker.js +116 -109
  225. package/dist/node/workerProcess.js +1 -1
  226. package/dist/node/workerProcess.js.map +1 -1
  227. package/dist/prefetch/admission.d.ts +41 -0
  228. package/dist/prefetch/admission.d.ts.map +1 -0
  229. package/dist/prefetch/admission.js +49 -0
  230. package/dist/prefetch/admission.js.map +1 -0
  231. package/dist/prefetch/loadRegistry.d.ts +56 -0
  232. package/dist/prefetch/loadRegistry.d.ts.map +1 -0
  233. package/dist/prefetch/loadRegistry.js +108 -0
  234. package/dist/prefetch/loadRegistry.js.map +1 -0
  235. package/dist/prefetch/predictor.d.ts +40 -0
  236. package/dist/prefetch/predictor.d.ts.map +1 -0
  237. package/dist/prefetch/predictor.js +178 -0
  238. package/dist/prefetch/predictor.js.map +1 -0
  239. package/dist/prefetch/prefetcher.d.ts +37 -0
  240. package/dist/prefetch/prefetcher.d.ts.map +1 -0
  241. package/dist/prefetch/prefetcher.js +339 -0
  242. package/dist/prefetch/prefetcher.js.map +1 -0
  243. package/dist/prefetch/residentStore.d.ts +49 -0
  244. package/dist/prefetch/residentStore.d.ts.map +1 -0
  245. package/dist/prefetch/residentStore.js +87 -0
  246. package/dist/prefetch/residentStore.js.map +1 -0
  247. package/dist/prefetch/selfTuner.d.ts +40 -0
  248. package/dist/prefetch/selfTuner.d.ts.map +1 -0
  249. package/dist/prefetch/selfTuner.js +78 -0
  250. package/dist/prefetch/selfTuner.js.map +1 -0
  251. package/dist/prefetch/stats.d.ts +52 -0
  252. package/dist/prefetch/stats.d.ts.map +1 -0
  253. package/dist/prefetch/stats.js +72 -0
  254. package/dist/prefetch/stats.js.map +1 -0
  255. package/dist/prefetch/streaming.d.ts +132 -0
  256. package/dist/prefetch/streaming.d.ts.map +1 -0
  257. package/dist/prefetch/streaming.js +141 -0
  258. package/dist/prefetch/streaming.js.map +1 -0
  259. package/dist/prefetch/targetIndex.d.ts +18 -0
  260. package/dist/prefetch/targetIndex.d.ts.map +1 -0
  261. package/dist/prefetch/targetIndex.js +32 -0
  262. package/dist/prefetch/targetIndex.js.map +1 -0
  263. package/dist/prefetch/types.d.ts +283 -0
  264. package/dist/prefetch/types.d.ts.map +1 -0
  265. package/dist/prefetch/types.js +19 -0
  266. package/dist/prefetch/types.js.map +1 -0
  267. package/dist/previewBridge.d.ts +6 -0
  268. package/dist/previewBridge.d.ts.map +1 -1
  269. package/dist/previewBridge.js +25 -5
  270. package/dist/previewBridge.js.map +1 -1
  271. package/dist/previewMessages.d.ts +4 -3
  272. package/dist/previewMessages.d.ts.map +1 -1
  273. package/dist/previewMessages.js +12 -6
  274. package/dist/previewMessages.js.map +1 -1
  275. package/dist/process-worker.js +116 -109
  276. package/dist/relay.html +1 -1
  277. package/dist/shared/clock.d.ts +7 -0
  278. package/dist/shared/clock.d.ts.map +1 -0
  279. package/dist/shared/clock.js +10 -0
  280. package/dist/shared/clock.js.map +1 -0
  281. package/dist/shared/hardwareProbe.d.ts +26 -0
  282. package/dist/shared/hardwareProbe.d.ts.map +1 -0
  283. package/dist/shared/hardwareProbe.js +62 -0
  284. package/dist/shared/hardwareProbe.js.map +1 -0
  285. package/dist/shared/idb.d.ts +41 -0
  286. package/dist/shared/idb.d.ts.map +1 -0
  287. package/dist/shared/idb.js +184 -0
  288. package/dist/shared/idb.js.map +1 -0
  289. package/dist/shared/tokens.d.ts +7 -0
  290. package/dist/shared/tokens.d.ts.map +1 -0
  291. package/dist/shared/tokens.js +9 -0
  292. package/dist/shared/tokens.js.map +1 -0
  293. package/dist/snapshotStore.d.ts +2 -1
  294. package/dist/snapshotStore.d.ts.map +1 -1
  295. package/dist/snapshotStore.js +27 -12
  296. package/dist/snapshotStore.js.map +1 -1
  297. package/dist/styleCompilers.d.ts.map +1 -1
  298. package/dist/styleCompilers.js.map +1 -1
  299. package/dist/transport.js.map +1 -1
  300. package/package.json +11 -5
  301. package/src/adaptive/controller.ts +151 -0
  302. package/src/adaptive/costModel.ts +131 -0
  303. package/src/adaptive/planner.ts +127 -0
  304. package/src/adaptive/types.ts +137 -0
  305. package/src/check/index.ts +6 -1
  306. package/src/host.ts +33 -11
  307. package/src/inference/backends/mock.ts +77 -0
  308. package/src/inference/backends/onnx.ts +91 -0
  309. package/src/inference/backends/webllm.ts +79 -0
  310. package/src/inference/backends/wllama.ts +79 -0
  311. package/src/inference/capabilities.ts +46 -0
  312. package/src/inference/client.ts +276 -0
  313. package/src/inference/modelCache.ts +145 -0
  314. package/src/inference/protocol.ts +119 -0
  315. package/src/inference/tokenStream.ts +92 -0
  316. package/src/inference/types.ts +115 -0
  317. package/src/inference/worker.ts +191 -0
  318. package/src/inference/workerEntry.ts +18 -0
  319. package/src/kvcache/advanced.ts +86 -0
  320. package/src/kvcache/compatibility.ts +51 -0
  321. package/src/kvcache/lru.ts +100 -0
  322. package/src/kvcache/paged.ts +270 -0
  323. package/src/kvcache/quant.ts +88 -0
  324. package/src/kvcache/radix.ts +68 -0
  325. package/src/kvcache/runtime.ts +239 -0
  326. package/src/kvcache/types.ts +167 -0
  327. package/src/learning/fingerprint.ts +50 -0
  328. package/src/learning/index.ts +15 -0
  329. package/src/learning/learner.ts +304 -0
  330. package/src/learning/ledger.ts +54 -0
  331. package/src/learning/selection.ts +137 -0
  332. package/src/learning/stats.ts +39 -0
  333. package/src/learning/types.ts +142 -0
  334. package/src/memory/envProbe.ts +30 -0
  335. package/src/memory/estimates.ts +98 -0
  336. package/src/memory/eviction.ts +145 -0
  337. package/src/memory/manager.ts +380 -0
  338. package/src/memory/managerTypes.ts +61 -0
  339. package/src/memory/pressure.ts +120 -0
  340. package/src/memory/spillTier.ts +159 -0
  341. package/src/memory/storageSink.ts +289 -0
  342. package/src/memory/types.ts +217 -0
  343. package/src/memory/victims.ts +80 -0
  344. package/src/memory/workspace.ts +74 -0
  345. package/src/memoryIntegration/index.ts +7 -0
  346. package/src/memoryIntegration/knowledgeMemory.ts +339 -0
  347. package/src/memoryIntegration/persistence.ts +54 -0
  348. package/src/memoryIntegration/text.ts +185 -0
  349. package/src/memoryIntegration/types.ts +145 -0
  350. package/src/ml.ts +180 -0
  351. package/src/node/childRelay.ts +16 -3
  352. package/src/node/portResponder.ts +5 -3
  353. package/src/node/processHost.ts +16 -15
  354. package/src/node/protocol.ts +1 -1
  355. package/src/node/workerProcess.ts +1 -1
  356. package/src/prefetch/admission.ts +74 -0
  357. package/src/prefetch/loadRegistry.ts +156 -0
  358. package/src/prefetch/predictor.ts +199 -0
  359. package/src/prefetch/prefetcher.ts +369 -0
  360. package/src/prefetch/residentStore.ts +121 -0
  361. package/src/prefetch/selfTuner.ts +110 -0
  362. package/src/prefetch/stats.ts +120 -0
  363. package/src/prefetch/streaming.ts +231 -0
  364. package/src/prefetch/targetIndex.ts +40 -0
  365. package/src/prefetch/types.ts +307 -0
  366. package/src/previewBridge.ts +25 -5
  367. package/src/previewMessages.ts +11 -6
  368. package/src/shared/clock.ts +9 -0
  369. package/src/shared/hardwareProbe.ts +68 -0
  370. package/src/shared/idb.ts +203 -0
  371. package/src/shared/tokens.ts +8 -0
  372. package/src/snapshotStore.ts +25 -10
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Phase 3 — the browser-storage spill tier of the residency manager.
3
+ *
4
+ * Owns the in-memory spill index (what is retained in the storage sink and how
5
+ * many bytes it holds) and every write to / delete from the sink. The index is
6
+ * the bound: `bytes()` never exceeds the storage budget, even under concurrent
7
+ * spills, because bytes are RESERVED synchronously before the sink write is
8
+ * awaited and released when it settles.
9
+ *
10
+ * Storage is best-effort: a failed delete never resurrects an index entry, and
11
+ * a failed write leaves nothing charged.
12
+ */
13
+
14
+ import type { SpilledRecord, StorageSink } from './storageSink.js';
15
+ import type { ResidentEntry } from './types.js';
16
+
17
+ export interface SpillTierOptions {
18
+ storage?: StorageSink;
19
+ /** Cap on bytes retained in storage. 0 disables retention. */
20
+ budgetBytes: number;
21
+ now: () => number;
22
+ /** Called once per successful spill (for the manager's event log). */
23
+ onSpill(entry: ResidentEntry, reason: string): void;
24
+ }
25
+
26
+ export interface SpillTier {
27
+ /** True when a sink is configured and the storage budget allows retention. */
28
+ readonly enabled: boolean;
29
+ get(id: string): SpilledRecord | undefined;
30
+ has(id: string): boolean;
31
+ readonly count: number;
32
+ /** Bytes committed in storage (reservations in flight are not included). */
33
+ bytes(): number;
34
+ /** Retain an entry in storage, trimming the oldest spills to make room. */
35
+ retain(entry: ResidentEntry, reason: string): Promise<boolean>;
36
+ /**
37
+ * Drop a spill. The index entry is removed synchronously (before the first
38
+ * await); the sink delete is best-effort. Returns whether a spill existed.
39
+ */
40
+ forget(id: string): Promise<boolean>;
41
+ /**
42
+ * Read a spill back from storage as a RAM-tier entry charged at the spilled
43
+ * footprint. Undefined (and the index entry dropped) when storage lost it.
44
+ */
45
+ reload(id: string): Promise<ResidentEntry | undefined>;
46
+ }
47
+
48
+ /** Storage budget: explicit > 0, else the quota hint, else 4× the RAM budget. `0` disables. */
49
+ export function resolveStorageBudget(
50
+ configured: number | undefined,
51
+ storageQuotaBytes: number,
52
+ byteBudget: number,
53
+ ): number {
54
+ if (configured === 0) return 0;
55
+ if (typeof configured === 'number' && Number.isFinite(configured) && configured > 0) return configured;
56
+ if (storageQuotaBytes > 0) return storageQuotaBytes;
57
+ return byteBudget * 4;
58
+ }
59
+
60
+ export function createSpillTier(options: SpillTierOptions): SpillTier {
61
+ const { storage, budgetBytes } = options;
62
+ const enabled = storage !== undefined && budgetBytes > 0;
63
+ const index = new Map<string, SpilledRecord>();
64
+ let committed = 0;
65
+ let reserved = 0;
66
+
67
+ function setIndex(record: SpilledRecord): void {
68
+ removeIndex(record.id);
69
+ index.set(record.id, record);
70
+ committed += record.bytes;
71
+ }
72
+
73
+ function removeIndex(id: string): SpilledRecord | undefined {
74
+ const record = index.get(id);
75
+ if (!record) return undefined;
76
+ index.delete(id);
77
+ committed -= record.bytes;
78
+ return record;
79
+ }
80
+
81
+ async function deleteQuietly(record: SpilledRecord): Promise<void> {
82
+ try {
83
+ await storage?.delete(record);
84
+ } catch {
85
+ // Storage is best-effort. The in-memory spill index is the bound.
86
+ }
87
+ }
88
+
89
+ function fits(incomingBytes: number): boolean {
90
+ return committed + reserved + incomingBytes <= budgetBytes;
91
+ }
92
+
93
+ async function trim(incomingBytes: number): Promise<void> {
94
+ const ordered = [...index.values()].sort((a, b) => a.spilledAt - b.spilledAt || a.id.localeCompare(b.id));
95
+ for (const oldest of ordered) {
96
+ if (fits(incomingBytes)) return;
97
+ // A concurrent call may already have dropped or replaced this record.
98
+ if (index.get(oldest.id) !== oldest) continue;
99
+ removeIndex(oldest.id);
100
+ await deleteQuietly(oldest);
101
+ }
102
+ }
103
+
104
+ return {
105
+ enabled,
106
+ get: (id) => index.get(id),
107
+ has: (id) => index.has(id),
108
+ get count() {
109
+ return index.size;
110
+ },
111
+ bytes: () => committed,
112
+
113
+ async retain(entry, reason) {
114
+ if (!enabled || !storage) return false;
115
+ if (!(entry.bytes >= 0) || entry.bytes > budgetBytes) return false;
116
+ const previous = removeIndex(entry.id);
117
+ // Replacing a spill; a failed delete must not block the new write.
118
+ if (previous) await deleteQuietly(previous);
119
+ await trim(entry.bytes);
120
+ // Check and reserve in the same synchronous step: a concurrent retain
121
+ // awaiting its own write can no longer push storage past the budget.
122
+ if (!fits(entry.bytes)) return false;
123
+ reserved += entry.bytes;
124
+ try {
125
+ const stored = await storage.spill({ ...entry, tier: 'storage' }, options.now());
126
+ setIndex(stored);
127
+ options.onSpill(entry, reason);
128
+ return true;
129
+ } catch {
130
+ return false;
131
+ } finally {
132
+ reserved -= entry.bytes;
133
+ }
134
+ },
135
+
136
+ async forget(id) {
137
+ const record = removeIndex(id);
138
+ if (!record) return false;
139
+ await deleteQuietly(record);
140
+ return true;
141
+ },
142
+
143
+ async reload(id) {
144
+ const record = index.get(id);
145
+ if (!record || !storage) return undefined;
146
+ let restored: ResidentEntry | undefined;
147
+ try {
148
+ restored = await storage.reload(record);
149
+ } catch {
150
+ restored = undefined;
151
+ }
152
+ if (!restored) {
153
+ if (index.get(id) === record) removeIndex(id);
154
+ return undefined;
155
+ }
156
+ return { ...restored, id, tier: 'ram', bytes: record.bytes };
157
+ },
158
+ };
159
+ }
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Phase 3 — browser-storage residency sink.
3
+ *
4
+ * CPU-only environments have no VRAM. Cold weights spill to browser storage
5
+ * and reload from there. This sink is the residency view over the Phase 1
6
+ * IndexedDB `ModelCache` (`src/inference/modelCache.ts`): it does not open a
7
+ * second database and does not reimplement persistence. Tests inject
8
+ * `createMemoryModelCache()`; the browser injects `createModelCache()`.
9
+ *
10
+ * Spilled bytes are NOT charged against the RAM byte budget. A reload copies
11
+ * them back into a resident entry the caller admits.
12
+ */
13
+
14
+ import type { ModelCache, ModelCacheEntry } from '../inference/modelCache.js';
15
+ import type { ResidentEntry } from './types.js';
16
+
17
+ /** A spill record. Payload bytes live in the Phase 1 model cache. */
18
+ export interface SpilledRecord {
19
+ id: string;
20
+ group: string;
21
+ component?: string;
22
+ bytes: number;
23
+ reloadCostMs: number;
24
+ reuseProbability: number;
25
+ /** Model-cache key the payload was stored under. */
26
+ cacheKey: string;
27
+ spilledAt: number;
28
+ }
29
+
30
+ export interface StorageSink {
31
+ /** Persist a resident's payload and return the spill record. */
32
+ spill(entry: ResidentEntry, now: number): Promise<SpilledRecord>;
33
+ /** Reload a spilled record's payload. Undefined if storage lost it. */
34
+ reload(record: SpilledRecord): Promise<ResidentEntry | undefined>;
35
+ /** Drop a spill. Best-effort. */
36
+ delete(record: SpilledRecord): Promise<void>;
37
+ /** Ids currently spilled, for diagnostics. */
38
+ keys(): Promise<string[]>;
39
+ }
40
+
41
+ export interface StorageSinkOptions {
42
+ /** Phase 1 model cache. Required — this module does not open IndexedDB itself. */
43
+ cache: ModelCache;
44
+ /**
45
+ * Encode an opaque payload to bytes for the model cache.
46
+ * Default: binary payloads (ArrayBuffer, SharedArrayBuffer, any TypedArray,
47
+ * DataView) are stored as their raw bytes and come back as the same type;
48
+ * everything else is UTF-8 JSON.
49
+ */
50
+ encode?: (payload: unknown) => ArrayBuffer;
51
+ /**
52
+ * Inverse of `encode` for non-binary payloads. Default: UTF-8 JSON parse,
53
+ * falling back to the raw buffer. Binary payloads written by the default
54
+ * encoder never pass through here.
55
+ */
56
+ decode?: (bytes: ArrayBuffer) => unknown;
57
+ }
58
+
59
+ const CACHE_PREFIX = 'bfwc-resident:';
60
+
61
+ /** Copy the exact encoded bytes. `TextEncoder#encode().buffer` may be a larger pooled slab. */
62
+ function exactBuffer(bytes: Uint8Array): ArrayBuffer {
63
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
64
+ }
65
+
66
+ /**
67
+ * Adapt a Phase 1 `ModelCache` into a residency spill sink.
68
+ * One cache key per resident id. Metadata rides in the cache entry's
69
+ * quantization/params fields plus a JSON header stored ahead of the payload,
70
+ * so a reload reconstructs the resident without a second store.
71
+ */
72
+ export function createModelCacheSink(options: StorageSinkOptions): StorageSink {
73
+ const decode = options.decode ?? defaultDecode;
74
+ const cache = options.cache;
75
+
76
+ return {
77
+ async spill(entry, now) {
78
+ const encoded: EncodedPayload = options.encode
79
+ ? { encoding: 'custom', bytes: options.encode(entry.payload) }
80
+ : defaultEncode(entry.payload);
81
+ const header = encodeHeader(entry, now, encoded.encoding);
82
+ const bytes = concat(header, encoded.bytes);
83
+ await cache.put(cacheKey(entry.id), {
84
+ quantization: entry.component ?? 'resident',
85
+ paramsB: entry.bytes / 1e9,
86
+ bytes,
87
+ size: bytes.byteLength,
88
+ });
89
+ return {
90
+ id: entry.id,
91
+ group: entry.group,
92
+ component: entry.component,
93
+ bytes: entry.bytes,
94
+ reloadCostMs: entry.reloadCostMs,
95
+ reuseProbability: entry.reuseProbability,
96
+ cacheKey: cacheKey(entry.id),
97
+ spilledAt: now,
98
+ };
99
+ },
100
+ async reload(record) {
101
+ const stored = await cache.get(record.cacheKey);
102
+ if (!stored) return undefined;
103
+ const split = splitHeader(stored.bytes);
104
+ if (!split) return undefined;
105
+ const header = decodeHeader(split.header);
106
+ return {
107
+ id: record.id,
108
+ group: header?.group ?? record.group,
109
+ component: header?.component ?? record.component,
110
+ bytes: record.bytes,
111
+ reloadCostMs: record.reloadCostMs,
112
+ reuseProbability: record.reuseProbability,
113
+ tier: 'ram',
114
+ payload: decodePayload(header?.encoding, split.payload, decode),
115
+ };
116
+ },
117
+ async delete(record) {
118
+ await cache.delete(record.cacheKey);
119
+ },
120
+ async keys() {
121
+ const all = await cache.keys();
122
+ return all.filter((key) => key.startsWith(CACHE_PREFIX)).map((key) => key.slice(CACHE_PREFIX.length));
123
+ },
124
+ };
125
+ }
126
+
127
+ /**
128
+ * In-memory sink for tests that do not want IndexedDB. Still ModelCache-shaped.
129
+ * The payload is kept by reference, so binary payloads (ArrayBuffer,
130
+ * TypedArray) reload as the very same object — nothing is serialized.
131
+ */
132
+ export function createMemorySink(): StorageSink {
133
+ const records = new Map<string, { record: SpilledRecord; entry: ResidentEntry }>();
134
+ return {
135
+ async spill(entry, now) {
136
+ const record: SpilledRecord = {
137
+ id: entry.id,
138
+ group: entry.group,
139
+ component: entry.component,
140
+ bytes: entry.bytes,
141
+ reloadCostMs: entry.reloadCostMs,
142
+ reuseProbability: entry.reuseProbability,
143
+ cacheKey: cacheKey(entry.id),
144
+ spilledAt: now,
145
+ };
146
+ records.set(entry.id, { record, entry: { ...entry, tier: 'storage' } });
147
+ return record;
148
+ },
149
+ async reload(record) {
150
+ const found = records.get(record.id);
151
+ if (!found) return undefined;
152
+ return { ...found.entry, tier: 'ram' };
153
+ },
154
+ async delete(record) {
155
+ records.delete(record.id);
156
+ },
157
+ async keys() {
158
+ return [...records.keys()];
159
+ },
160
+ };
161
+ }
162
+
163
+ function cacheKey(id: string): string {
164
+ return `${CACHE_PREFIX}${id}`;
165
+ }
166
+
167
+ /**
168
+ * Little-endian uint32 length prefix, then UTF-8 JSON. The header records how
169
+ * the payload was encoded so binary payloads are restored as binary. Headers
170
+ * written before `encoding` existed decode as JSON, as they always did.
171
+ */
172
+ function encodeHeader(entry: ResidentEntry, now: number, encoding: PayloadEncoding): Uint8Array {
173
+ const json = new TextEncoder().encode(JSON.stringify({
174
+ group: entry.group,
175
+ component: entry.component,
176
+ bytes: entry.bytes,
177
+ spilledAt: now,
178
+ encoding,
179
+ }));
180
+ const header = new Uint8Array(4 + json.byteLength);
181
+ new DataView(header.buffer).setUint32(0, json.byteLength, true);
182
+ header.set(json, 4);
183
+ return header;
184
+ }
185
+
186
+ function concat(header: Uint8Array, payload: ArrayBuffer): ArrayBuffer {
187
+ const body = new Uint8Array(payload);
188
+ const out = new Uint8Array(header.byteLength + body.byteLength);
189
+ out.set(header, 0);
190
+ out.set(body, header.byteLength);
191
+ return exactBuffer(out);
192
+ }
193
+
194
+ function splitHeader(bytes: ArrayBuffer): { header: string; payload: ArrayBuffer } | undefined {
195
+ if (bytes.byteLength < 4) return undefined;
196
+ const length = new DataView(bytes).getUint32(0, true);
197
+ if (!Number.isFinite(length) || length < 0 || 4 + length > bytes.byteLength) return undefined;
198
+ return {
199
+ header: new TextDecoder().decode(bytes.slice(4, 4 + length)),
200
+ payload: bytes.slice(4 + length),
201
+ };
202
+ }
203
+
204
+ function decodeHeader(header: string): { group?: string; component?: string; encoding?: string } | undefined {
205
+ try {
206
+ const parsed = JSON.parse(header) as { group?: string; component?: string; encoding?: string };
207
+ return parsed;
208
+ } catch {
209
+ return undefined;
210
+ }
211
+ }
212
+
213
+ /**
214
+ * How a payload was encoded. `json` / `custom` go through `decode`; the rest
215
+ * are raw bytes restored as their original binary type.
216
+ */
217
+ type PayloadEncoding = 'json' | 'custom' | 'arraybuffer' | 'dataview' | `typed:${string}`;
218
+
219
+ interface EncodedPayload {
220
+ encoding: PayloadEncoding;
221
+ bytes: ArrayBuffer;
222
+ }
223
+
224
+ type TypedArrayCtor = new (buffer: ArrayBuffer) => ArrayBufferView;
225
+
226
+ /** TypedArray constructors this realm has, by name. Resolved lazily (BigInt arrays may be absent). */
227
+ function typedArrayCtor(name: string): TypedArrayCtor | undefined {
228
+ const known = [
229
+ 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array',
230
+ 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array',
231
+ ];
232
+ if (!known.includes(name)) return undefined;
233
+ const ctor = (globalThis as unknown as Record<string, unknown>)[name];
234
+ return typeof ctor === 'function' ? (ctor as TypedArrayCtor) : undefined;
235
+ }
236
+
237
+ /** Brand check that also works across realms (workers, iframes, test environments). */
238
+ function tagOf(value: unknown): string {
239
+ return Object.prototype.toString.call(value);
240
+ }
241
+
242
+ function copyBytes(view: { buffer: ArrayBufferLike; byteOffset: number; byteLength: number }): ArrayBuffer {
243
+ const out = new Uint8Array(view.byteLength);
244
+ out.set(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
245
+ return out.buffer as ArrayBuffer;
246
+ }
247
+
248
+ function defaultEncode(payload: unknown): EncodedPayload {
249
+ const tag = tagOf(payload);
250
+ if (tag === '[object ArrayBuffer]' || tag === '[object SharedArrayBuffer]') {
251
+ const buffer = payload as ArrayBufferLike;
252
+ return { encoding: 'arraybuffer', bytes: copyBytes({ buffer, byteOffset: 0, byteLength: buffer.byteLength }) };
253
+ }
254
+ if (ArrayBuffer.isView(payload)) {
255
+ const bytes = copyBytes(payload);
256
+ if (tag === '[object DataView]') return { encoding: 'dataview', bytes };
257
+ const name = payload.constructor?.name ?? '';
258
+ if (typedArrayCtor(name)) return { encoding: `typed:${name}`, bytes };
259
+ // An exotic view (a subclass): keep the bytes, restore as a plain buffer.
260
+ return { encoding: 'arraybuffer', bytes };
261
+ }
262
+ return { encoding: 'json', bytes: exactBuffer(new TextEncoder().encode(JSON.stringify(payload ?? null))) };
263
+ }
264
+
265
+ function decodePayload(
266
+ encoding: string | undefined,
267
+ bytes: ArrayBuffer,
268
+ decode: (bytes: ArrayBuffer) => unknown,
269
+ ): unknown {
270
+ if (encoding === 'arraybuffer') return bytes;
271
+ if (encoding === 'dataview') return new DataView(bytes);
272
+ if (encoding?.startsWith('typed:')) {
273
+ const ctor = typedArrayCtor(encoding.slice('typed:'.length));
274
+ return ctor ? new ctor(bytes) : bytes;
275
+ }
276
+ return decode(bytes);
277
+ }
278
+
279
+ function defaultDecode(bytes: ArrayBuffer): unknown {
280
+ const text = new TextDecoder().decode(bytes);
281
+ try {
282
+ return JSON.parse(text);
283
+ } catch {
284
+ return bytes;
285
+ }
286
+ }
287
+
288
+ /** Re-export the Phase 1 entry type so callers need not import inference for a spill. */
289
+ export type { ModelCacheEntry };
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Phase 3 — Hierarchical Memory & Residency Management: types.
3
+ *
4
+ * Owns WHERE model weights and layer components live (RAM / optional VRAM hint /
5
+ * browser storage) and HOW they are admitted, quoted, and evicted under a hard
6
+ * byte budget. It does not decide WHEN to run inference — that is the Adaptive
7
+ * Heterogeneous Execution Controller in `src/adaptive/`.
8
+ *
9
+ * Browser-compatible only: pure TypeScript, no native code, no dependencies.
10
+ * SharedArrayBuffer and WebGPU are optional probed facts, never gates.
11
+ * CPU-only is the primary path: residency falls back to system RAM + IndexedDB
12
+ * (the Phase 1 `ModelCache`) when no GPU is present.
13
+ */
14
+
15
+ /** Where a resident entry's bytes currently live. */
16
+ export type ResidencyTier = 'ram' | 'vram' | 'storage';
17
+
18
+ /**
19
+ * One cacheable unit: a whole model, a layer, or a component (KV head, embedding).
20
+ * `bytes` is the footprint the budget accounts for. Payload is opaque — the
21
+ * manager never interprets it, so eviction cannot corrupt inference state.
22
+ */
23
+ export interface ResidentEntry {
24
+ /** Stable id, e.g. `model:tiny-q4` or `model:tiny-q4/layer:7`. */
25
+ id: string;
26
+ /** Logical group the quota applies to (a model id, a component class). */
27
+ group: string;
28
+ /** Optional finer bucket inside the group (`layer`, `kv`, `embed`). */
29
+ component?: string;
30
+ /** Footprint in bytes. Must be >= 0. The hard budget counts this, not payload. */
31
+ bytes: number;
32
+ /** Estimated cost to reload this entry from storage or network, in ms. */
33
+ reloadCostMs: number;
34
+ /**
35
+ * Estimated probability this entry is reused before the next pressure event,
36
+ * in [0, 1]. Combined with reload cost to score eviction candidates.
37
+ */
38
+ reuseProbability: number;
39
+ /** Where the bytes live. `vram` is a hint only — never required. */
40
+ tier: ResidencyTier;
41
+ /** Opaque payload. Retained so a hit returns the same object the caller put. */
42
+ payload?: unknown;
43
+ /** Optional hint that this entry is pinned and must not be evicted. */
44
+ pinned?: boolean;
45
+ }
46
+
47
+ /** A resident entry plus the bookkeeping the strategies and stats read. */
48
+ export interface TrackedEntry extends ResidentEntry {
49
+ /** Monotonic admission sequence (LRU recency, ARC MRU). */
50
+ admittedAt: number;
51
+ /** Last successful touch sequence. */
52
+ lastUsedAt: number;
53
+ /** Touch count since admission (LFU). */
54
+ hits: number;
55
+ /** ARC list membership. Absent for non-ARC strategies. */
56
+ arcList?: 't1' | 't2' | 'b1' | 'b2';
57
+ }
58
+
59
+ /** Result of a `get`. A miss is `{ hit: false }` — never throws for absence. */
60
+ export interface LookupResult {
61
+ hit: boolean;
62
+ entry?: TrackedEntry;
63
+ }
64
+
65
+ /** Why an admission or eviction happened. Explainable, for audit and Phase 4. */
66
+ export type ResidencyEventKind =
67
+ | 'admit'
68
+ | 'hit'
69
+ | 'miss'
70
+ | 'evict'
71
+ | 'pin'
72
+ | 'unpin'
73
+ | 'pressure'
74
+ | 'workspace-grow'
75
+ | 'workspace-shrink'
76
+ | 'spill'
77
+ | 'reload';
78
+
79
+ export interface ResidencyEvent {
80
+ kind: ResidencyEventKind;
81
+ /** Entry the event concerns, when there is one. */
82
+ id?: string;
83
+ /** Bytes freed (evict/shrink) or consumed (admit/grow). */
84
+ bytes?: number;
85
+ /** Human-readable reason. */
86
+ reason: string;
87
+ at: number;
88
+ }
89
+
90
+ /** Aggregate counters. `hitRate` is hits / (hits + misses); 0 when unused. */
91
+ export interface ResidencyStats {
92
+ hits: number;
93
+ misses: number;
94
+ admissions: number;
95
+ evictions: number;
96
+ spills: number;
97
+ reloads: number;
98
+ /** Bytes currently charged against the hard budget (RAM + VRAM residents). */
99
+ usedBytes: number;
100
+ /** Configured hard cap. */
101
+ byteBudget: number;
102
+ /** Bytes of the dynamic workspace currently allocated. */
103
+ workspaceBytes: number;
104
+ /** Residents currently held in RAM or VRAM. */
105
+ residentCount: number;
106
+ /** Residents spilled to browser storage (not charged against the RAM budget). */
107
+ spilledCount: number;
108
+ /** Bytes retained in browser storage. Bounded by `storageBudgetBytes`. */
109
+ spilledBytes: number;
110
+ hitRate: number;
111
+ }
112
+
113
+ /** Pressure reading. Facts the manager acts on; callers may also observe them. */
114
+ export interface MemoryPressure {
115
+ /** usedBytes / byteBudget, in [0, 1+] (can exceed 1 only before eviction runs). */
116
+ utilization: number;
117
+ /** True when utilization >= the configured pressure threshold. */
118
+ pressured: boolean;
119
+ /** Bytes that must be freed to get back under the target watermark. */
120
+ reclaimBytes: number;
121
+ /** Optional VRAM hint in bytes. 0 when no GPU was probed. */
122
+ vramBytes: number;
123
+ /** System RAM hint in bytes (navigator.deviceMemory when present). */
124
+ ramBytes: number;
125
+ /** Browser storage quota hint in bytes, when the environment reports one. */
126
+ storageQuotaBytes: number;
127
+ }
128
+
129
+ /**
130
+ * Pluggable eviction strategy. The manager owns the map; the strategy only
131
+ * decides order. Strategies must be pure over the snapshot they are given so
132
+ * they stay swappable and unit-testable without a manager.
133
+ */
134
+ export interface EvictionStrategy {
135
+ readonly name: 'lru' | 'lfu' | 'arc' | 'cost-aware' | (string & {});
136
+ /**
137
+ * Rank `candidates` (already filtered to evictable, unpinned residents)
138
+ * from most-evictable to least. Return a new array; do not mutate inputs.
139
+ */
140
+ rank(candidates: readonly TrackedEntry[]): TrackedEntry[];
141
+ /**
142
+ * Optional hook so ARC (and similar) can record a hit/miss against its
143
+ * ghost lists. Default strategies ignore this.
144
+ */
145
+ observe?(event: { kind: 'hit' | 'miss' | 'admit' | 'evict'; entry: TrackedEntry }): void;
146
+ }
147
+
148
+ /** Per-group and optional per-component byte quotas. */
149
+ export interface Quota {
150
+ /** Group these bytes belong to (usually a model id). */
151
+ group: string;
152
+ /** Optional component bucket inside the group. Omit for a group-wide cap. */
153
+ component?: string;
154
+ /** Hard cap in bytes for this group (or group+component). */
155
+ byteCap: number;
156
+ }
157
+
158
+ export interface MemoryManagerConfig {
159
+ /**
160
+ * Hard byte budget for RAM+VRAM residents. Eviction runs until
161
+ * `usedBytes + incoming <= byteBudget`. Required — there is no implicit
162
+ * unbounded default.
163
+ */
164
+ byteBudget: number;
165
+ /** Eviction strategy. Default: cost-aware. */
166
+ strategy?: EvictionStrategy;
167
+ /** Per-layer / per-component quotas. Enforced on admission, before the global budget. */
168
+ quotas?: readonly Quota[];
169
+ /**
170
+ * Utilization at or above which the manager reports pressure and shrinks
171
+ * the workspace. Default 0.85.
172
+ */
173
+ pressureThreshold?: number;
174
+ /**
175
+ * After pressure eviction, utilization is brought down to this watermark.
176
+ * Default 0.7. Must be <= pressureThreshold.
177
+ */
178
+ targetWatermark?: number;
179
+ /**
180
+ * Dynamic workspace bounds. The workspace grows on hits while headroom
181
+ * remains and shrinks under pressure, always inside [min, max] and always
182
+ * inside the residual byte budget.
183
+ */
184
+ workspace?: { minBytes: number; maxBytes: number; initialBytes?: number };
185
+ /**
186
+ * Optional VRAM budget hint in bytes. 0 (default) means CPU-only: no entry
187
+ * is placed in `vram`, and the hint is reported as a fact.
188
+ */
189
+ vramBudgetBytes?: number;
190
+ /** System RAM hint. Default: probed `navigator.deviceMemory`, else 4 GiB. */
191
+ ramBytes?: number;
192
+ /** Browser storage quota hint. Default: probed `navigator.storage.estimate`, else 0. */
193
+ storageQuotaBytes?: number;
194
+ /**
195
+ * Cap on bytes retained in the browser-storage sink. Evicted RAM residents
196
+ * spill here until this cap, then the oldest spills are dropped. Default:
197
+ * `storageQuotaBytes` when it is set, otherwise `4 * byteBudget`. `0`
198
+ * disables retention (a spill is not kept).
199
+ */
200
+ storageBudgetBytes?: number;
201
+ /** Retain at most this many explainable events. Default 256. */
202
+ eventLogLimit?: number;
203
+ /** Clock for tests. Default `Date.now`. */
204
+ now?: () => number;
205
+ }
206
+
207
+ /** Options for a single admission. */
208
+ export interface AdmitOptions {
209
+ /**
210
+ * When the budget cannot fit this entry even after evicting every unpinned
211
+ * resident, spill it to browser storage instead of rejecting. Default true
212
+ * when a storage sink is configured, false otherwise.
213
+ */
214
+ spill?: boolean;
215
+ /** Pin on admission so later eviction cannot drop it. */
216
+ pin?: boolean;
217
+ }