opencode-quota-gui 0.0.0-stage → 1.0.0

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 (849) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +245 -2
  3. package/dist/bin/opencode-quota-gui.d.ts +4 -0
  4. package/dist/bin/opencode-quota-gui.d.ts.map +1 -0
  5. package/dist/bin/opencode-quota-gui.js +75 -0
  6. package/dist/bin/opencode-quota-gui.js.map +1 -0
  7. package/dist/contracts/build-identity.d.ts +8 -0
  8. package/dist/contracts/build-identity.d.ts.map +1 -0
  9. package/dist/contracts/build-identity.js +1 -0
  10. package/dist/contracts/dashboard.d.ts +358 -0
  11. package/dist/contracts/dashboard.d.ts.map +1 -0
  12. package/dist/contracts/dashboard.js +3 -0
  13. package/dist/contracts/dashboard.js.map +1 -0
  14. package/dist/contracts/guards.d.ts +14 -0
  15. package/dist/contracts/guards.d.ts.map +1 -0
  16. package/dist/contracts/guards.js +56 -0
  17. package/dist/contracts/guards.js.map +1 -0
  18. package/dist/contracts/identity.d.ts +41 -0
  19. package/dist/contracts/identity.d.ts.map +1 -0
  20. package/dist/contracts/identity.js +27 -0
  21. package/dist/contracts/identity.js.map +1 -0
  22. package/dist/contracts/openai-quota.d.ts +34 -0
  23. package/dist/contracts/openai-quota.d.ts.map +1 -0
  24. package/dist/contracts/openai-quota.js +19 -0
  25. package/dist/contracts/openai-quota.js.map +1 -0
  26. package/dist/contracts/ranges.d.ts +48 -0
  27. package/dist/contracts/ranges.d.ts.map +1 -0
  28. package/dist/contracts/ranges.js +84 -0
  29. package/dist/contracts/ranges.js.map +1 -0
  30. package/dist/contracts/settings.d.ts +4 -0
  31. package/dist/contracts/settings.d.ts.map +1 -0
  32. package/dist/contracts/settings.js +14 -0
  33. package/dist/contracts/settings.js.map +1 -0
  34. package/dist/contracts/time-zone.d.ts +33 -0
  35. package/dist/contracts/time-zone.d.ts.map +1 -0
  36. package/dist/contracts/time-zone.js +217 -0
  37. package/dist/contracts/time-zone.js.map +1 -0
  38. package/dist/data/modelsdev-pricing.min.json +1064 -0
  39. package/dist/gui/aggregation.d.ts +55 -0
  40. package/dist/gui/aggregation.d.ts.map +1 -0
  41. package/dist/gui/aggregation.js +792 -0
  42. package/dist/gui/aggregation.js.map +1 -0
  43. package/dist/gui/analytics-bridge.d.ts +50 -0
  44. package/dist/gui/analytics-bridge.d.ts.map +1 -0
  45. package/dist/gui/analytics-bridge.js +382 -0
  46. package/dist/gui/analytics-bridge.js.map +1 -0
  47. package/dist/gui/analytics-engine.d.ts +61 -0
  48. package/dist/gui/analytics-engine.d.ts.map +1 -0
  49. package/dist/gui/analytics-engine.js +2381 -0
  50. package/dist/gui/analytics-engine.js.map +1 -0
  51. package/dist/gui/analytics-indexes.d.ts +34 -0
  52. package/dist/gui/analytics-indexes.d.ts.map +1 -0
  53. package/dist/gui/analytics-indexes.js +142 -0
  54. package/dist/gui/analytics-indexes.js.map +1 -0
  55. package/dist/gui/analytics-model.d.ts +48 -0
  56. package/dist/gui/analytics-model.d.ts.map +1 -0
  57. package/dist/gui/analytics-model.js +824 -0
  58. package/dist/gui/analytics-model.js.map +1 -0
  59. package/dist/gui/analytics-protocol.d.ts +102 -0
  60. package/dist/gui/analytics-protocol.d.ts.map +1 -0
  61. package/dist/gui/analytics-protocol.js +11 -0
  62. package/dist/gui/analytics-protocol.js.map +1 -0
  63. package/dist/gui/analytics-reader.d.ts +14 -0
  64. package/dist/gui/analytics-reader.d.ts.map +1 -0
  65. package/dist/gui/analytics-reader.js +15 -0
  66. package/dist/gui/analytics-reader.js.map +1 -0
  67. package/dist/gui/analytics-service.d.ts +49 -0
  68. package/dist/gui/analytics-service.d.ts.map +1 -0
  69. package/dist/gui/analytics-service.js +187 -0
  70. package/dist/gui/analytics-service.js.map +1 -0
  71. package/dist/gui/analytics-state.d.ts +183 -0
  72. package/dist/gui/analytics-state.d.ts.map +1 -0
  73. package/dist/gui/analytics-state.js +692 -0
  74. package/dist/gui/analytics-state.js.map +1 -0
  75. package/dist/gui/analytics-worker-runtime.d.ts +11 -0
  76. package/dist/gui/analytics-worker-runtime.d.ts.map +1 -0
  77. package/dist/gui/analytics-worker-runtime.js +98 -0
  78. package/dist/gui/analytics-worker-runtime.js.map +1 -0
  79. package/dist/gui/analytics-worker.d.ts +2 -0
  80. package/dist/gui/analytics-worker.d.ts.map +1 -0
  81. package/dist/gui/analytics-worker.js +64 -0
  82. package/dist/gui/analytics-worker.js.map +1 -0
  83. package/dist/gui/config.d.ts +53 -0
  84. package/dist/gui/config.d.ts.map +1 -0
  85. package/dist/gui/config.js +679 -0
  86. package/dist/gui/config.js.map +1 -0
  87. package/dist/gui/identity.d.ts +23 -0
  88. package/dist/gui/identity.d.ts.map +1 -0
  89. package/dist/gui/identity.js +57 -0
  90. package/dist/gui/identity.js.map +1 -0
  91. package/dist/gui/lifecycle.d.ts +82 -0
  92. package/dist/gui/lifecycle.d.ts.map +1 -0
  93. package/dist/gui/lifecycle.js +402 -0
  94. package/dist/gui/lifecycle.js.map +1 -0
  95. package/dist/gui/log.d.ts +23 -0
  96. package/dist/gui/log.d.ts.map +1 -0
  97. package/dist/gui/log.js +37 -0
  98. package/dist/gui/log.js.map +1 -0
  99. package/dist/gui/provider-cards.d.ts +58 -0
  100. package/dist/gui/provider-cards.d.ts.map +1 -0
  101. package/dist/gui/provider-cards.js +413 -0
  102. package/dist/gui/provider-cards.js.map +1 -0
  103. package/dist/gui/server.d.ts +60 -0
  104. package/dist/gui/server.d.ts.map +1 -0
  105. package/dist/gui/server.js +815 -0
  106. package/dist/gui/server.js.map +1 -0
  107. package/dist/gui/settings-file-opener.d.ts +34 -0
  108. package/dist/gui/settings-file-opener.d.ts.map +1 -0
  109. package/dist/gui/settings-file-opener.js +110 -0
  110. package/dist/gui/settings-file-opener.js.map +1 -0
  111. package/dist/gui/snapshot-service.d.ts +128 -0
  112. package/dist/gui/snapshot-service.d.ts.map +1 -0
  113. package/dist/gui/snapshot-service.js +591 -0
  114. package/dist/gui/snapshot-service.js.map +1 -0
  115. package/dist/gui/sources.d.ts +94 -0
  116. package/dist/gui/sources.d.ts.map +1 -0
  117. package/dist/gui/sources.js +404 -0
  118. package/dist/gui/sources.js.map +1 -0
  119. package/dist/gui/sse.d.ts +32 -0
  120. package/dist/gui/sse.d.ts.map +1 -0
  121. package/dist/gui/sse.js +100 -0
  122. package/dist/gui/sse.js.map +1 -0
  123. package/dist/gui/time-zone.d.ts +10 -0
  124. package/dist/gui/time-zone.d.ts.map +1 -0
  125. package/dist/gui/time-zone.js +21 -0
  126. package/dist/gui/time-zone.js.map +1 -0
  127. package/dist/index.d.ts +13 -0
  128. package/dist/index.d.ts.map +1 -0
  129. package/dist/index.js +12 -0
  130. package/dist/index.js.map +1 -0
  131. package/dist/lib/accounting-format.d.ts +54 -0
  132. package/dist/lib/accounting-format.d.ts.map +1 -0
  133. package/dist/lib/accounting-format.js +271 -0
  134. package/dist/lib/accounting-format.js.map +1 -0
  135. package/dist/lib/alibaba-auth.d.ts +46 -0
  136. package/dist/lib/alibaba-auth.d.ts.map +1 -0
  137. package/dist/lib/alibaba-auth.js +193 -0
  138. package/dist/lib/alibaba-auth.js.map +1 -0
  139. package/dist/lib/alibaba-coding-plan-local-quota.d.ts +47 -0
  140. package/dist/lib/alibaba-coding-plan-local-quota.d.ts.map +1 -0
  141. package/dist/lib/alibaba-coding-plan-local-quota.js +146 -0
  142. package/dist/lib/alibaba-coding-plan-local-quota.js.map +1 -0
  143. package/dist/lib/alibaba-token-plan.d.ts +91 -0
  144. package/dist/lib/alibaba-token-plan.d.ts.map +1 -0
  145. package/dist/lib/alibaba-token-plan.js +527 -0
  146. package/dist/lib/alibaba-token-plan.js.map +1 -0
  147. package/dist/lib/anthropic-auth.d.ts +29 -0
  148. package/dist/lib/anthropic-auth.d.ts.map +1 -0
  149. package/dist/lib/anthropic-auth.js +37 -0
  150. package/dist/lib/anthropic-auth.js.map +1 -0
  151. package/dist/lib/anthropic.d.ts +104 -0
  152. package/dist/lib/anthropic.d.ts.map +1 -0
  153. package/dist/lib/anthropic.js +1134 -0
  154. package/dist/lib/anthropic.js.map +1 -0
  155. package/dist/lib/api-key-resolver.d.ts +227 -0
  156. package/dist/lib/api-key-resolver.d.ts.map +1 -0
  157. package/dist/lib/api-key-resolver.js +336 -0
  158. package/dist/lib/api-key-resolver.js.map +1 -0
  159. package/dist/lib/atomic-json.d.ts +11 -0
  160. package/dist/lib/atomic-json.d.ts.map +1 -0
  161. package/dist/lib/atomic-json.js +64 -0
  162. package/dist/lib/atomic-json.js.map +1 -0
  163. package/dist/lib/chutes-config.d.ts +15 -0
  164. package/dist/lib/chutes-config.d.ts.map +1 -0
  165. package/dist/lib/chutes-config.js +28 -0
  166. package/dist/lib/chutes-config.js.map +1 -0
  167. package/dist/lib/chutes.d.ts +12 -0
  168. package/dist/lib/chutes.d.ts.map +1 -0
  169. package/dist/lib/chutes.js +60 -0
  170. package/dist/lib/chutes.js.map +1 -0
  171. package/dist/lib/cli-reports.d.ts +30 -0
  172. package/dist/lib/cli-reports.d.ts.map +1 -0
  173. package/dist/lib/cli-reports.js +172 -0
  174. package/dist/lib/cli-reports.js.map +1 -0
  175. package/dist/lib/cli-show.d.ts +30 -0
  176. package/dist/lib/cli-show.d.ts.map +1 -0
  177. package/dist/lib/cli-show.js +213 -0
  178. package/dist/lib/cli-show.js.map +1 -0
  179. package/dist/lib/cli-status.d.ts +8 -0
  180. package/dist/lib/cli-status.d.ts.map +1 -0
  181. package/dist/lib/cli-status.js +98 -0
  182. package/dist/lib/cli-status.js.map +1 -0
  183. package/dist/lib/command-parsing.d.ts +43 -0
  184. package/dist/lib/command-parsing.d.ts.map +1 -0
  185. package/dist/lib/command-parsing.js +103 -0
  186. package/dist/lib/command-parsing.js.map +1 -0
  187. package/dist/lib/config-file-utils.d.ts +46 -0
  188. package/dist/lib/config-file-utils.d.ts.map +1 -0
  189. package/dist/lib/config-file-utils.js +194 -0
  190. package/dist/lib/config-file-utils.js.map +1 -0
  191. package/dist/lib/config-write-target.d.ts +28 -0
  192. package/dist/lib/config-write-target.d.ts.map +1 -0
  193. package/dist/lib/config-write-target.js +159 -0
  194. package/dist/lib/config-write-target.js.map +1 -0
  195. package/dist/lib/config.d.ts +119 -0
  196. package/dist/lib/config.d.ts.map +1 -0
  197. package/dist/lib/config.js +1327 -0
  198. package/dist/lib/config.js.map +1 -0
  199. package/dist/lib/copilot.d.ts +78 -0
  200. package/dist/lib/copilot.d.ts.map +1 -0
  201. package/dist/lib/copilot.js +1111 -0
  202. package/dist/lib/copilot.js.map +1 -0
  203. package/dist/lib/cursor-detection.d.ts +18 -0
  204. package/dist/lib/cursor-detection.d.ts.map +1 -0
  205. package/dist/lib/cursor-detection.js +189 -0
  206. package/dist/lib/cursor-detection.js.map +1 -0
  207. package/dist/lib/cursor-pricing.d.ts +34 -0
  208. package/dist/lib/cursor-pricing.d.ts.map +1 -0
  209. package/dist/lib/cursor-pricing.js +235 -0
  210. package/dist/lib/cursor-pricing.js.map +1 -0
  211. package/dist/lib/cursor-usage.d.ts +33 -0
  212. package/dist/lib/cursor-usage.d.ts.map +1 -0
  213. package/dist/lib/cursor-usage.js +109 -0
  214. package/dist/lib/cursor-usage.js.map +1 -0
  215. package/dist/lib/deepseek-auth.d.ts +15 -0
  216. package/dist/lib/deepseek-auth.d.ts.map +1 -0
  217. package/dist/lib/deepseek-auth.js +28 -0
  218. package/dist/lib/deepseek-auth.js.map +1 -0
  219. package/dist/lib/deepseek.d.ts +40 -0
  220. package/dist/lib/deepseek.d.ts.map +1 -0
  221. package/dist/lib/deepseek.js +118 -0
  222. package/dist/lib/deepseek.js.map +1 -0
  223. package/dist/lib/display-sanitize.d.ts +20 -0
  224. package/dist/lib/display-sanitize.d.ts.map +1 -0
  225. package/dist/lib/display-sanitize.js +178 -0
  226. package/dist/lib/display-sanitize.js.map +1 -0
  227. package/dist/lib/entries.d.ts +365 -0
  228. package/dist/lib/entries.d.ts.map +1 -0
  229. package/dist/lib/entries.js +69 -0
  230. package/dist/lib/entries.js.map +1 -0
  231. package/dist/lib/env-template.d.ts +26 -0
  232. package/dist/lib/env-template.d.ts.map +1 -0
  233. package/dist/lib/env-template.js +36 -0
  234. package/dist/lib/env-template.js.map +1 -0
  235. package/dist/lib/format-utils.d.ts +89 -0
  236. package/dist/lib/format-utils.d.ts.map +1 -0
  237. package/dist/lib/format-utils.js +206 -0
  238. package/dist/lib/format-utils.js.map +1 -0
  239. package/dist/lib/format.d.ts +25 -0
  240. package/dist/lib/format.d.ts.map +1 -0
  241. package/dist/lib/format.js +300 -0
  242. package/dist/lib/format.js.map +1 -0
  243. package/dist/lib/glm-coding-plan.d.ts +19 -0
  244. package/dist/lib/glm-coding-plan.d.ts.map +1 -0
  245. package/dist/lib/glm-coding-plan.js +81 -0
  246. package/dist/lib/glm-coding-plan.js.map +1 -0
  247. package/dist/lib/google-agy-companion.d.ts +8 -0
  248. package/dist/lib/google-agy-companion.d.ts.map +1 -0
  249. package/dist/lib/google-agy-companion.js +64 -0
  250. package/dist/lib/google-agy-companion.js.map +1 -0
  251. package/dist/lib/google-agy.d.ts +48 -0
  252. package/dist/lib/google-agy.d.ts.map +1 -0
  253. package/dist/lib/google-agy.js +572 -0
  254. package/dist/lib/google-agy.js.map +1 -0
  255. package/dist/lib/google-companion-credentials.d.ts +70 -0
  256. package/dist/lib/google-companion-credentials.d.ts.map +1 -0
  257. package/dist/lib/google-companion-credentials.js +315 -0
  258. package/dist/lib/google-companion-credentials.js.map +1 -0
  259. package/dist/lib/google-gemini-cli-companion.d.ts +8 -0
  260. package/dist/lib/google-gemini-cli-companion.d.ts.map +1 -0
  261. package/dist/lib/google-gemini-cli-companion.js +64 -0
  262. package/dist/lib/google-gemini-cli-companion.js.map +1 -0
  263. package/dist/lib/google-gemini-cli.d.ts +47 -0
  264. package/dist/lib/google-gemini-cli.d.ts.map +1 -0
  265. package/dist/lib/google-gemini-cli.js +481 -0
  266. package/dist/lib/google-gemini-cli.js.map +1 -0
  267. package/dist/lib/google-token-cache.d.ts +27 -0
  268. package/dist/lib/google-token-cache.d.ts.map +1 -0
  269. package/dist/lib/google-token-cache.js +52 -0
  270. package/dist/lib/google-token-cache.js.map +1 -0
  271. package/dist/lib/grouped-entry-normalization.d.ts +12 -0
  272. package/dist/lib/grouped-entry-normalization.d.ts.map +1 -0
  273. package/dist/lib/grouped-entry-normalization.js +124 -0
  274. package/dist/lib/grouped-entry-normalization.js.map +1 -0
  275. package/dist/lib/grouped-header-format.d.ts +5 -0
  276. package/dist/lib/grouped-header-format.d.ts.map +1 -0
  277. package/dist/lib/grouped-header-format.js +16 -0
  278. package/dist/lib/grouped-header-format.js.map +1 -0
  279. package/dist/lib/gui-config-target.d.ts +12 -0
  280. package/dist/lib/gui-config-target.d.ts.map +1 -0
  281. package/dist/lib/gui-config-target.js +88 -0
  282. package/dist/lib/gui-config-target.js.map +1 -0
  283. package/dist/lib/home-dir-display.d.ts +10 -0
  284. package/dist/lib/home-dir-display.d.ts.map +1 -0
  285. package/dist/lib/home-dir-display.js +108 -0
  286. package/dist/lib/home-dir-display.js.map +1 -0
  287. package/dist/lib/http.d.ts +19 -0
  288. package/dist/lib/http.d.ts.map +1 -0
  289. package/dist/lib/http.js +47 -0
  290. package/dist/lib/http.js.map +1 -0
  291. package/dist/lib/init-installer.d.ts +146 -0
  292. package/dist/lib/init-installer.d.ts.map +1 -0
  293. package/dist/lib/init-installer.js +1056 -0
  294. package/dist/lib/init-installer.js.map +1 -0
  295. package/dist/lib/jsonc.d.ts +17 -0
  296. package/dist/lib/jsonc.d.ts.map +1 -0
  297. package/dist/lib/jsonc.js +23 -0
  298. package/dist/lib/jsonc.js.map +1 -0
  299. package/dist/lib/kilo-config.d.ts +15 -0
  300. package/dist/lib/kilo-config.d.ts.map +1 -0
  301. package/dist/lib/kilo-config.js +27 -0
  302. package/dist/lib/kilo-config.js.map +1 -0
  303. package/dist/lib/kilo.d.ts +32 -0
  304. package/dist/lib/kilo.d.ts.map +1 -0
  305. package/dist/lib/kilo.js +265 -0
  306. package/dist/lib/kilo.js.map +1 -0
  307. package/dist/lib/kimi-auth.d.ts +49 -0
  308. package/dist/lib/kimi-auth.d.ts.map +1 -0
  309. package/dist/lib/kimi-auth.js +82 -0
  310. package/dist/lib/kimi-auth.js.map +1 -0
  311. package/dist/lib/kimi-endpoints.d.ts +10 -0
  312. package/dist/lib/kimi-endpoints.d.ts.map +1 -0
  313. package/dist/lib/kimi-endpoints.js +18 -0
  314. package/dist/lib/kimi-endpoints.js.map +1 -0
  315. package/dist/lib/kimi.d.ts +26 -0
  316. package/dist/lib/kimi.d.ts.map +1 -0
  317. package/dist/lib/kimi.js +230 -0
  318. package/dist/lib/kimi.js.map +1 -0
  319. package/dist/lib/maintainer-announcements.d.ts +46 -0
  320. package/dist/lib/maintainer-announcements.d.ts.map +1 -0
  321. package/dist/lib/maintainer-announcements.js +155 -0
  322. package/dist/lib/maintainer-announcements.js.map +1 -0
  323. package/dist/lib/map-with-concurrency.d.ts +2 -0
  324. package/dist/lib/map-with-concurrency.d.ts.map +1 -0
  325. package/dist/lib/map-with-concurrency.js +17 -0
  326. package/dist/lib/map-with-concurrency.js.map +1 -0
  327. package/dist/lib/markdown-table.d.ts +51 -0
  328. package/dist/lib/markdown-table.d.ts.map +1 -0
  329. package/dist/lib/markdown-table.js +179 -0
  330. package/dist/lib/markdown-table.js.map +1 -0
  331. package/dist/lib/mimo-config.d.ts +29 -0
  332. package/dist/lib/mimo-config.d.ts.map +1 -0
  333. package/dist/lib/mimo-config.js +146 -0
  334. package/dist/lib/mimo-config.js.map +1 -0
  335. package/dist/lib/mimo.d.ts +35 -0
  336. package/dist/lib/mimo.d.ts.map +1 -0
  337. package/dist/lib/mimo.js +236 -0
  338. package/dist/lib/mimo.js.map +1 -0
  339. package/dist/lib/minimax-auth.d.ts +62 -0
  340. package/dist/lib/minimax-auth.d.ts.map +1 -0
  341. package/dist/lib/minimax-auth.js +206 -0
  342. package/dist/lib/minimax-auth.js.map +1 -0
  343. package/dist/lib/minimax-endpoints.d.ts +10 -0
  344. package/dist/lib/minimax-endpoints.d.ts.map +1 -0
  345. package/dist/lib/minimax-endpoints.js +19 -0
  346. package/dist/lib/minimax-endpoints.js.map +1 -0
  347. package/dist/lib/modelsdev-pricing.d.ts +93 -0
  348. package/dist/lib/modelsdev-pricing.d.ts.map +1 -0
  349. package/dist/lib/modelsdev-pricing.js +674 -0
  350. package/dist/lib/modelsdev-pricing.js.map +1 -0
  351. package/dist/lib/nanogpt-config.d.ts +15 -0
  352. package/dist/lib/nanogpt-config.d.ts.map +1 -0
  353. package/dist/lib/nanogpt-config.js +31 -0
  354. package/dist/lib/nanogpt-config.js.map +1 -0
  355. package/dist/lib/nanogpt.d.ts +48 -0
  356. package/dist/lib/nanogpt.d.ts.map +1 -0
  357. package/dist/lib/nanogpt.js +251 -0
  358. package/dist/lib/nanogpt.js.map +1 -0
  359. package/dist/lib/ollama-cloud-config.d.ts +15 -0
  360. package/dist/lib/ollama-cloud-config.d.ts.map +1 -0
  361. package/dist/lib/ollama-cloud-config.js +27 -0
  362. package/dist/lib/ollama-cloud-config.js.map +1 -0
  363. package/dist/lib/ollama-cloud.d.ts +14 -0
  364. package/dist/lib/ollama-cloud.d.ts.map +1 -0
  365. package/dist/lib/ollama-cloud.js +186 -0
  366. package/dist/lib/ollama-cloud.js.map +1 -0
  367. package/dist/lib/openai.d.ts +68 -0
  368. package/dist/lib/openai.d.ts.map +1 -0
  369. package/dist/lib/openai.js +394 -0
  370. package/dist/lib/openai.js.map +1 -0
  371. package/dist/lib/opencode-auth-sqlite.d.ts +17 -0
  372. package/dist/lib/opencode-auth-sqlite.d.ts.map +1 -0
  373. package/dist/lib/opencode-auth-sqlite.js +105 -0
  374. package/dist/lib/opencode-auth-sqlite.js.map +1 -0
  375. package/dist/lib/opencode-auth.d.ts +146 -0
  376. package/dist/lib/opencode-auth.d.ts.map +1 -0
  377. package/dist/lib/opencode-auth.js +465 -0
  378. package/dist/lib/opencode-auth.js.map +1 -0
  379. package/dist/lib/opencode-config-editor.d.ts +62 -0
  380. package/dist/lib/opencode-config-editor.d.ts.map +1 -0
  381. package/dist/lib/opencode-config-editor.js +387 -0
  382. package/dist/lib/opencode-config-editor.js.map +1 -0
  383. package/dist/lib/opencode-config-providers.d.ts +24 -0
  384. package/dist/lib/opencode-config-providers.d.ts.map +1 -0
  385. package/dist/lib/opencode-config-providers.js +144 -0
  386. package/dist/lib/opencode-config-providers.js.map +1 -0
  387. package/dist/lib/opencode-config-read.d.ts +23 -0
  388. package/dist/lib/opencode-config-read.d.ts.map +1 -0
  389. package/dist/lib/opencode-config-read.js +30 -0
  390. package/dist/lib/opencode-config-read.js.map +1 -0
  391. package/dist/lib/opencode-console-auth.d.ts +47 -0
  392. package/dist/lib/opencode-console-auth.d.ts.map +1 -0
  393. package/dist/lib/opencode-console-auth.js +63 -0
  394. package/dist/lib/opencode-console-auth.js.map +1 -0
  395. package/dist/lib/opencode-db-path.d.ts +9 -0
  396. package/dist/lib/opencode-db-path.d.ts.map +1 -0
  397. package/dist/lib/opencode-db-path.js +16 -0
  398. package/dist/lib/opencode-db-path.js.map +1 -0
  399. package/dist/lib/opencode-go-auth.d.ts +16 -0
  400. package/dist/lib/opencode-go-auth.d.ts.map +1 -0
  401. package/dist/lib/opencode-go-auth.js +42 -0
  402. package/dist/lib/opencode-go-auth.js.map +1 -0
  403. package/dist/lib/opencode-go.d.ts +17 -0
  404. package/dist/lib/opencode-go.d.ts.map +1 -0
  405. package/dist/lib/opencode-go.js +278 -0
  406. package/dist/lib/opencode-go.js.map +1 -0
  407. package/dist/lib/opencode-runtime-paths.d.ts +17 -0
  408. package/dist/lib/opencode-runtime-paths.d.ts.map +1 -0
  409. package/dist/lib/opencode-runtime-paths.js +24 -0
  410. package/dist/lib/opencode-runtime-paths.js.map +1 -0
  411. package/dist/lib/opencode-sqlite.d.ts +11 -0
  412. package/dist/lib/opencode-sqlite.d.ts.map +1 -0
  413. package/dist/lib/opencode-sqlite.js +88 -0
  414. package/dist/lib/opencode-sqlite.js.map +1 -0
  415. package/dist/lib/opencode-storage.d.ts +306 -0
  416. package/dist/lib/opencode-storage.d.ts.map +1 -0
  417. package/dist/lib/opencode-storage.js +1269 -0
  418. package/dist/lib/opencode-storage.js.map +1 -0
  419. package/dist/lib/opencode-version.d.ts +6 -0
  420. package/dist/lib/opencode-version.d.ts.map +1 -0
  421. package/dist/lib/opencode-version.js +26 -0
  422. package/dist/lib/opencode-version.js.map +1 -0
  423. package/dist/lib/opencode-zen.d.ts +55 -0
  424. package/dist/lib/opencode-zen.d.ts.map +1 -0
  425. package/dist/lib/opencode-zen.js +348 -0
  426. package/dist/lib/opencode-zen.js.map +1 -0
  427. package/dist/lib/openrouter.d.ts +16 -0
  428. package/dist/lib/openrouter.d.ts.map +1 -0
  429. package/dist/lib/openrouter.js +50 -0
  430. package/dist/lib/openrouter.js.map +1 -0
  431. package/dist/lib/private-state-paths.d.ts +10 -0
  432. package/dist/lib/private-state-paths.d.ts.map +1 -0
  433. package/dist/lib/private-state-paths.js +28 -0
  434. package/dist/lib/private-state-paths.js.map +1 -0
  435. package/dist/lib/provider-add-command.d.ts +35 -0
  436. package/dist/lib/provider-add-command.d.ts.map +1 -0
  437. package/dist/lib/provider-add-command.js +204 -0
  438. package/dist/lib/provider-add-command.js.map +1 -0
  439. package/dist/lib/provider-add-json-v1-questionnaire.d.ts +32 -0
  440. package/dist/lib/provider-add-json-v1-questionnaire.d.ts.map +1 -0
  441. package/dist/lib/provider-add-json-v1-questionnaire.js +336 -0
  442. package/dist/lib/provider-add-json-v1-questionnaire.js.map +1 -0
  443. package/dist/lib/provider-add.d.ts +21 -0
  444. package/dist/lib/provider-add.d.ts.map +1 -0
  445. package/dist/lib/provider-add.js +219 -0
  446. package/dist/lib/provider-add.js.map +1 -0
  447. package/dist/lib/provider-availability.d.ts +13 -0
  448. package/dist/lib/provider-availability.d.ts.map +1 -0
  449. package/dist/lib/provider-availability.js +20 -0
  450. package/dist/lib/provider-availability.js.map +1 -0
  451. package/dist/lib/provider-metadata.d.ts +32 -0
  452. package/dist/lib/provider-metadata.d.ts.map +1 -0
  453. package/dist/lib/provider-metadata.js +90 -0
  454. package/dist/lib/provider-metadata.js.map +1 -0
  455. package/dist/lib/provider-model-matching.d.ts +12 -0
  456. package/dist/lib/provider-model-matching.d.ts.map +1 -0
  457. package/dist/lib/provider-model-matching.js +23 -0
  458. package/dist/lib/provider-model-matching.js.map +1 -0
  459. package/dist/lib/provider-registration.d.ts +321 -0
  460. package/dist/lib/provider-registration.d.ts.map +1 -0
  461. package/dist/lib/provider-registration.js +335 -0
  462. package/dist/lib/provider-registration.js.map +1 -0
  463. package/dist/lib/quota-accounting-projection.d.ts +9 -0
  464. package/dist/lib/quota-accounting-projection.d.ts.map +1 -0
  465. package/dist/lib/quota-accounting-projection.js +254 -0
  466. package/dist/lib/quota-accounting-projection.js.map +1 -0
  467. package/dist/lib/quota-columns.d.ts +38 -0
  468. package/dist/lib/quota-columns.d.ts.map +1 -0
  469. package/dist/lib/quota-columns.js +129 -0
  470. package/dist/lib/quota-columns.js.map +1 -0
  471. package/dist/lib/quota-command-format.d.ts +34 -0
  472. package/dist/lib/quota-command-format.d.ts.map +1 -0
  473. package/dist/lib/quota-command-format.js +240 -0
  474. package/dist/lib/quota-command-format.js.map +1 -0
  475. package/dist/lib/quota-dialog-command-specs.d.ts +63 -0
  476. package/dist/lib/quota-dialog-command-specs.d.ts.map +1 -0
  477. package/dist/lib/quota-dialog-command-specs.js +145 -0
  478. package/dist/lib/quota-dialog-command-specs.js.map +1 -0
  479. package/dist/lib/quota-dialog-commands.d.ts +75 -0
  480. package/dist/lib/quota-dialog-commands.d.ts.map +1 -0
  481. package/dist/lib/quota-dialog-commands.js +586 -0
  482. package/dist/lib/quota-dialog-commands.js.map +1 -0
  483. package/dist/lib/quota-entry-display.d.ts +7 -0
  484. package/dist/lib/quota-entry-display.d.ts.map +1 -0
  485. package/dist/lib/quota-entry-display.js +59 -0
  486. package/dist/lib/quota-entry-display.js.map +1 -0
  487. package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
  488. package/dist/lib/quota-exhaustion-projection.d.ts.map +1 -0
  489. package/dist/lib/quota-exhaustion-projection.js +105 -0
  490. package/dist/lib/quota-exhaustion-projection.js.map +1 -0
  491. package/dist/lib/quota-export-types.d.ts +96 -0
  492. package/dist/lib/quota-export-types.d.ts.map +1 -0
  493. package/dist/lib/quota-export-types.js +2 -0
  494. package/dist/lib/quota-export-types.js.map +1 -0
  495. package/dist/lib/quota-export.d.ts +44 -0
  496. package/dist/lib/quota-export.d.ts.map +1 -0
  497. package/dist/lib/quota-export.js +221 -0
  498. package/dist/lib/quota-export.js.map +1 -0
  499. package/dist/lib/quota-format-style.d.ts +21 -0
  500. package/dist/lib/quota-format-style.d.ts.map +1 -0
  501. package/dist/lib/quota-format-style.js +38 -0
  502. package/dist/lib/quota-format-style.js.map +1 -0
  503. package/dist/lib/quota-providers-local.d.ts +55 -0
  504. package/dist/lib/quota-providers-local.d.ts.map +1 -0
  505. package/dist/lib/quota-providers-local.js +327 -0
  506. package/dist/lib/quota-providers-local.js.map +1 -0
  507. package/dist/lib/quota-providers-remote.d.ts +27 -0
  508. package/dist/lib/quota-providers-remote.d.ts.map +1 -0
  509. package/dist/lib/quota-providers-remote.js +678 -0
  510. package/dist/lib/quota-providers-remote.js.map +1 -0
  511. package/dist/lib/quota-providers.d.ts +158 -0
  512. package/dist/lib/quota-providers.d.ts.map +1 -0
  513. package/dist/lib/quota-providers.js +1160 -0
  514. package/dist/lib/quota-providers.js.map +1 -0
  515. package/dist/lib/quota-render-data.d.ts +135 -0
  516. package/dist/lib/quota-render-data.d.ts.map +1 -0
  517. package/dist/lib/quota-render-data.js +462 -0
  518. package/dist/lib/quota-render-data.js.map +1 -0
  519. package/dist/lib/quota-report-message.d.ts +22 -0
  520. package/dist/lib/quota-report-message.d.ts.map +1 -0
  521. package/dist/lib/quota-report-message.js +36 -0
  522. package/dist/lib/quota-report-message.js.map +1 -0
  523. package/dist/lib/quota-reset-notifications.d.ts +20 -0
  524. package/dist/lib/quota-reset-notifications.d.ts.map +1 -0
  525. package/dist/lib/quota-reset-notifications.js +331 -0
  526. package/dist/lib/quota-reset-notifications.js.map +1 -0
  527. package/dist/lib/quota-retry-wait.d.ts +36 -0
  528. package/dist/lib/quota-retry-wait.d.ts.map +1 -0
  529. package/dist/lib/quota-retry-wait.js +67 -0
  530. package/dist/lib/quota-retry-wait.js.map +1 -0
  531. package/dist/lib/quota-runtime-context.d.ts +56 -0
  532. package/dist/lib/quota-runtime-context.d.ts.map +1 -0
  533. package/dist/lib/quota-runtime-context.js +113 -0
  534. package/dist/lib/quota-runtime-context.js.map +1 -0
  535. package/dist/lib/quota-state-codec.d.ts +16 -0
  536. package/dist/lib/quota-state-codec.d.ts.map +1 -0
  537. package/dist/lib/quota-state-codec.js +475 -0
  538. package/dist/lib/quota-state-codec.js.map +1 -0
  539. package/dist/lib/quota-state.d.ts +28 -0
  540. package/dist/lib/quota-state.d.ts.map +1 -0
  541. package/dist/lib/quota-state.js +473 -0
  542. package/dist/lib/quota-state.js.map +1 -0
  543. package/dist/lib/quota-stats-format.d.ts +29 -0
  544. package/dist/lib/quota-stats-format.d.ts.map +1 -0
  545. package/dist/lib/quota-stats-format.js +459 -0
  546. package/dist/lib/quota-stats-format.js.map +1 -0
  547. package/dist/lib/quota-stats.d.ts +174 -0
  548. package/dist/lib/quota-stats.d.ts.map +1 -0
  549. package/dist/lib/quota-stats.js +713 -0
  550. package/dist/lib/quota-stats.js.map +1 -0
  551. package/dist/lib/quota-status.d.ts +58 -0
  552. package/dist/lib/quota-status.d.ts.map +1 -0
  553. package/dist/lib/quota-status.js +865 -0
  554. package/dist/lib/quota-status.js.map +1 -0
  555. package/dist/lib/quota-surface-data.d.ts +21 -0
  556. package/dist/lib/quota-surface-data.d.ts.map +1 -0
  557. package/dist/lib/quota-surface-data.js +361 -0
  558. package/dist/lib/quota-surface-data.js.map +1 -0
  559. package/dist/lib/quota-telemetry.d.ts +45 -0
  560. package/dist/lib/quota-telemetry.d.ts.map +1 -0
  561. package/dist/lib/quota-telemetry.js +304 -0
  562. package/dist/lib/quota-telemetry.js.map +1 -0
  563. package/dist/lib/report-document.d.ts +90 -0
  564. package/dist/lib/report-document.d.ts.map +1 -0
  565. package/dist/lib/report-document.js +190 -0
  566. package/dist/lib/report-document.js.map +1 -0
  567. package/dist/lib/resolved-auth-identity.d.ts +36 -0
  568. package/dist/lib/resolved-auth-identity.d.ts.map +1 -0
  569. package/dist/lib/resolved-auth-identity.js +192 -0
  570. package/dist/lib/resolved-auth-identity.js.map +1 -0
  571. package/dist/lib/runtime-provider-ids.d.ts +4 -0
  572. package/dist/lib/runtime-provider-ids.d.ts.map +1 -0
  573. package/dist/lib/runtime-provider-ids.js +10 -0
  574. package/dist/lib/runtime-provider-ids.js.map +1 -0
  575. package/dist/lib/scoped-update-migration.d.ts +103 -0
  576. package/dist/lib/scoped-update-migration.d.ts.map +1 -0
  577. package/dist/lib/scoped-update-migration.js +348 -0
  578. package/dist/lib/scoped-update-migration.js.map +1 -0
  579. package/dist/lib/scoped-update.d.ts +78 -0
  580. package/dist/lib/scoped-update.d.ts.map +1 -0
  581. package/dist/lib/scoped-update.js +640 -0
  582. package/dist/lib/scoped-update.js.map +1 -0
  583. package/dist/lib/session-tokens-format.d.ts +36 -0
  584. package/dist/lib/session-tokens-format.d.ts.map +1 -0
  585. package/dist/lib/session-tokens-format.js +111 -0
  586. package/dist/lib/session-tokens-format.js.map +1 -0
  587. package/dist/lib/session-tokens.d.ts +27 -0
  588. package/dist/lib/session-tokens.d.ts.map +1 -0
  589. package/dist/lib/session-tokens.js +55 -0
  590. package/dist/lib/session-tokens.js.map +1 -0
  591. package/dist/lib/synthetic-config.d.ts +15 -0
  592. package/dist/lib/synthetic-config.d.ts.map +1 -0
  593. package/dist/lib/synthetic-config.js +28 -0
  594. package/dist/lib/synthetic-config.js.map +1 -0
  595. package/dist/lib/synthetic.d.ts +12 -0
  596. package/dist/lib/synthetic.d.ts.map +1 -0
  597. package/dist/lib/synthetic.js +173 -0
  598. package/dist/lib/synthetic.js.map +1 -0
  599. package/dist/lib/toast-format-grouped.d.ts +25 -0
  600. package/dist/lib/toast-format-grouped.d.ts.map +1 -0
  601. package/dist/lib/toast-format-grouped.js +296 -0
  602. package/dist/lib/toast-format-grouped.js.map +1 -0
  603. package/dist/lib/token-buckets.d.ts +24 -0
  604. package/dist/lib/token-buckets.d.ts.map +1 -0
  605. package/dist/lib/token-buckets.js +28 -0
  606. package/dist/lib/token-buckets.js.map +1 -0
  607. package/dist/lib/token-cost.d.ts +10 -0
  608. package/dist/lib/token-cost.d.ts.map +1 -0
  609. package/dist/lib/token-cost.js +16 -0
  610. package/dist/lib/token-cost.js.map +1 -0
  611. package/dist/lib/tui-compact-format.d.ts +10 -0
  612. package/dist/lib/tui-compact-format.d.ts.map +1 -0
  613. package/dist/lib/tui-compact-format.js +460 -0
  614. package/dist/lib/tui-compact-format.js.map +1 -0
  615. package/dist/lib/tui-panel-state.d.ts +15 -0
  616. package/dist/lib/tui-panel-state.d.ts.map +1 -0
  617. package/dist/lib/tui-panel-state.js +2 -0
  618. package/dist/lib/tui-panel-state.js.map +1 -0
  619. package/dist/lib/tui-prompt-bar-format.d.ts +25 -0
  620. package/dist/lib/tui-prompt-bar-format.d.ts.map +1 -0
  621. package/dist/lib/tui-prompt-bar-format.js +206 -0
  622. package/dist/lib/tui-prompt-bar-format.js.map +1 -0
  623. package/dist/lib/tui-sidebar-format.d.ts +13 -0
  624. package/dist/lib/tui-sidebar-format.d.ts.map +1 -0
  625. package/dist/lib/tui-sidebar-format.js +34 -0
  626. package/dist/lib/tui-sidebar-format.js.map +1 -0
  627. package/dist/lib/types.d.ts +724 -0
  628. package/dist/lib/types.d.ts.map +1 -0
  629. package/dist/lib/types.js +83 -0
  630. package/dist/lib/types.js.map +1 -0
  631. package/dist/lib/usage-ownership.d.ts +47 -0
  632. package/dist/lib/usage-ownership.d.ts.map +1 -0
  633. package/dist/lib/usage-ownership.js +98 -0
  634. package/dist/lib/usage-ownership.js.map +1 -0
  635. package/dist/lib/version.d.ts +2 -0
  636. package/dist/lib/version.d.ts.map +1 -0
  637. package/dist/lib/version.js +33 -0
  638. package/dist/lib/version.js.map +1 -0
  639. package/dist/lib/xai.d.ts +52 -0
  640. package/dist/lib/xai.d.ts.map +1 -0
  641. package/dist/lib/xai.js +253 -0
  642. package/dist/lib/xai.js.map +1 -0
  643. package/dist/lib/zai-auth.d.ts +15 -0
  644. package/dist/lib/zai-auth.d.ts.map +1 -0
  645. package/dist/lib/zai-auth.js +37 -0
  646. package/dist/lib/zai-auth.js.map +1 -0
  647. package/dist/lib/zai.d.ts +5 -0
  648. package/dist/lib/zai.d.ts.map +1 -0
  649. package/dist/lib/zai.js +14 -0
  650. package/dist/lib/zai.js.map +1 -0
  651. package/dist/lib/zhipu-auth.d.ts +15 -0
  652. package/dist/lib/zhipu-auth.d.ts.map +1 -0
  653. package/dist/lib/zhipu-auth.js +42 -0
  654. package/dist/lib/zhipu-auth.js.map +1 -0
  655. package/dist/lib/zhipu.d.ts +5 -0
  656. package/dist/lib/zhipu.d.ts.map +1 -0
  657. package/dist/lib/zhipu.js +13 -0
  658. package/dist/lib/zhipu.js.map +1 -0
  659. package/dist/plugin.d.ts +10 -0
  660. package/dist/plugin.d.ts.map +1 -0
  661. package/dist/plugin.js +95 -0
  662. package/dist/plugin.js.map +1 -0
  663. package/dist/providers/accounting-decimal.d.ts +2 -0
  664. package/dist/providers/accounting-decimal.d.ts.map +1 -0
  665. package/dist/providers/accounting-decimal.js +23 -0
  666. package/dist/providers/accounting-decimal.js.map +1 -0
  667. package/dist/providers/alibaba-coding-plan.d.ts +3 -0
  668. package/dist/providers/alibaba-coding-plan.d.ts.map +1 -0
  669. package/dist/providers/alibaba-coding-plan.js +122 -0
  670. package/dist/providers/alibaba-coding-plan.js.map +1 -0
  671. package/dist/providers/alibaba-token-plan.d.ts +3 -0
  672. package/dist/providers/alibaba-token-plan.d.ts.map +1 -0
  673. package/dist/providers/alibaba-token-plan.js +90 -0
  674. package/dist/providers/alibaba-token-plan.js.map +1 -0
  675. package/dist/providers/anthropic.d.ts +9 -0
  676. package/dist/providers/anthropic.d.ts.map +1 -0
  677. package/dist/providers/anthropic.js +236 -0
  678. package/dist/providers/anthropic.js.map +1 -0
  679. package/dist/providers/cache-policies.d.ts +61 -0
  680. package/dist/providers/cache-policies.d.ts.map +1 -0
  681. package/dist/providers/cache-policies.js +210 -0
  682. package/dist/providers/cache-policies.js.map +1 -0
  683. package/dist/providers/chutes.d.ts +6 -0
  684. package/dist/providers/chutes.d.ts.map +1 -0
  685. package/dist/providers/chutes.js +50 -0
  686. package/dist/providers/chutes.js.map +1 -0
  687. package/dist/providers/copilot.d.ts +9 -0
  688. package/dist/providers/copilot.d.ts.map +1 -0
  689. package/dist/providers/copilot.js +323 -0
  690. package/dist/providers/copilot.js.map +1 -0
  691. package/dist/providers/cursor.d.ts +3 -0
  692. package/dist/providers/cursor.d.ts.map +1 -0
  693. package/dist/providers/cursor.js +182 -0
  694. package/dist/providers/cursor.js.map +1 -0
  695. package/dist/providers/deepseek.d.ts +9 -0
  696. package/dist/providers/deepseek.d.ts.map +1 -0
  697. package/dist/providers/deepseek.js +111 -0
  698. package/dist/providers/deepseek.js.map +1 -0
  699. package/dist/providers/glm-coding-plan-provider.d.ts +56 -0
  700. package/dist/providers/glm-coding-plan-provider.d.ts.map +1 -0
  701. package/dist/providers/glm-coding-plan-provider.js +146 -0
  702. package/dist/providers/glm-coding-plan-provider.js.map +1 -0
  703. package/dist/providers/google-account-format.d.ts +7 -0
  704. package/dist/providers/google-account-format.d.ts.map +1 -0
  705. package/dist/providers/google-account-format.js +52 -0
  706. package/dist/providers/google-account-format.js.map +1 -0
  707. package/dist/providers/google-agy.d.ts +17 -0
  708. package/dist/providers/google-agy.d.ts.map +1 -0
  709. package/dist/providers/google-agy.js +256 -0
  710. package/dist/providers/google-agy.js.map +1 -0
  711. package/dist/providers/google-gemini-cli.d.ts +17 -0
  712. package/dist/providers/google-gemini-cli.d.ts.map +1 -0
  713. package/dist/providers/google-gemini-cli.js +228 -0
  714. package/dist/providers/google-gemini-cli.js.map +1 -0
  715. package/dist/providers/kilo.d.ts +6 -0
  716. package/dist/providers/kilo.d.ts.map +1 -0
  717. package/dist/providers/kilo.js +145 -0
  718. package/dist/providers/kilo.js.map +1 -0
  719. package/dist/providers/kimi-code.d.ts +4 -0
  720. package/dist/providers/kimi-code.d.ts.map +1 -0
  721. package/dist/providers/kimi-code.js +175 -0
  722. package/dist/providers/kimi-code.js.map +1 -0
  723. package/dist/providers/mimo.d.ts +3 -0
  724. package/dist/providers/mimo.d.ts.map +1 -0
  725. package/dist/providers/mimo.js +149 -0
  726. package/dist/providers/mimo.js.map +1 -0
  727. package/dist/providers/minimax-coding-plan.d.ts +26 -0
  728. package/dist/providers/minimax-coding-plan.d.ts.map +1 -0
  729. package/dist/providers/minimax-coding-plan.js +391 -0
  730. package/dist/providers/minimax-coding-plan.js.map +1 -0
  731. package/dist/providers/nanogpt.d.ts +6 -0
  732. package/dist/providers/nanogpt.d.ts.map +1 -0
  733. package/dist/providers/nanogpt.js +160 -0
  734. package/dist/providers/nanogpt.js.map +1 -0
  735. package/dist/providers/ollama-cloud.d.ts +9 -0
  736. package/dist/providers/ollama-cloud.d.ts.map +1 -0
  737. package/dist/providers/ollama-cloud.js +129 -0
  738. package/dist/providers/ollama-cloud.js.map +1 -0
  739. package/dist/providers/openai.d.ts +6 -0
  740. package/dist/providers/openai.d.ts.map +1 -0
  741. package/dist/providers/openai.js +313 -0
  742. package/dist/providers/openai.js.map +1 -0
  743. package/dist/providers/opencode-go.d.ts +4 -0
  744. package/dist/providers/opencode-go.d.ts.map +1 -0
  745. package/dist/providers/opencode-go.js +294 -0
  746. package/dist/providers/opencode-go.js.map +1 -0
  747. package/dist/providers/opencode-zen.d.ts +3 -0
  748. package/dist/providers/opencode-zen.d.ts.map +1 -0
  749. package/dist/providers/opencode-zen.js +221 -0
  750. package/dist/providers/opencode-zen.js.map +1 -0
  751. package/dist/providers/openrouter.d.ts +6 -0
  752. package/dist/providers/openrouter.d.ts.map +1 -0
  753. package/dist/providers/openrouter.js +32 -0
  754. package/dist/providers/openrouter.js.map +1 -0
  755. package/dist/providers/quota-providers.d.ts +6 -0
  756. package/dist/providers/quota-providers.d.ts.map +1 -0
  757. package/dist/providers/quota-providers.js +287 -0
  758. package/dist/providers/quota-providers.js.map +1 -0
  759. package/dist/providers/registry.d.ts +9 -0
  760. package/dist/providers/registry.d.ts.map +1 -0
  761. package/dist/providers/registry.js +71 -0
  762. package/dist/providers/registry.js.map +1 -0
  763. package/dist/providers/result-helpers.d.ts +61 -0
  764. package/dist/providers/result-helpers.d.ts.map +1 -0
  765. package/dist/providers/result-helpers.js +117 -0
  766. package/dist/providers/result-helpers.js.map +1 -0
  767. package/dist/providers/synthetic.d.ts +6 -0
  768. package/dist/providers/synthetic.d.ts.map +1 -0
  769. package/dist/providers/synthetic.js +79 -0
  770. package/dist/providers/synthetic.js.map +1 -0
  771. package/dist/providers/xai.d.ts +6 -0
  772. package/dist/providers/xai.d.ts.map +1 -0
  773. package/dist/providers/xai.js +122 -0
  774. package/dist/providers/xai.js.map +1 -0
  775. package/dist/providers/zai.d.ts +2 -0
  776. package/dist/providers/zai.d.ts.map +1 -0
  777. package/dist/providers/zai.js +24 -0
  778. package/dist/providers/zai.js.map +1 -0
  779. package/dist/providers/zhipu.d.ts +2 -0
  780. package/dist/providers/zhipu.d.ts.map +1 -0
  781. package/dist/providers/zhipu.js +21 -0
  782. package/dist/providers/zhipu.js.map +1 -0
  783. package/dist/rpc.d.ts +72 -0
  784. package/dist/rpc.d.ts.map +1 -0
  785. package/dist/rpc.js +77 -0
  786. package/dist/rpc.js.map +1 -0
  787. package/dist/ui/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  788. package/dist/ui/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  789. package/dist/ui/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  790. package/dist/ui/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  791. package/dist/ui/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  792. package/dist/ui/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  793. package/dist/ui/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  794. package/dist/ui/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  795. package/dist/ui/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  796. package/dist/ui/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  797. package/dist/ui/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  798. package/dist/ui/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  799. package/dist/ui/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  800. package/dist/ui/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  801. package/dist/ui/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  802. package/dist/ui/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  803. package/dist/ui/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  804. package/dist/ui/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  805. package/dist/ui/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  806. package/dist/ui/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  807. package/dist/ui/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  808. package/dist/ui/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  809. package/dist/ui/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  810. package/dist/ui/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  811. package/dist/ui/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  812. package/dist/ui/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  813. package/dist/ui/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  814. package/dist/ui/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  815. package/dist/ui/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  816. package/dist/ui/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  817. package/dist/ui/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  818. package/dist/ui/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  819. package/dist/ui/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  820. package/dist/ui/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  821. package/dist/ui/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  822. package/dist/ui/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  823. package/dist/ui/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  824. package/dist/ui/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  825. package/dist/ui/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  826. package/dist/ui/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  827. package/dist/ui/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  828. package/dist/ui/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  829. package/dist/ui/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  830. package/dist/ui/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  831. package/dist/ui/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  832. package/dist/ui/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  833. package/dist/ui/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  834. package/dist/ui/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  835. package/dist/ui/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  836. package/dist/ui/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  837. package/dist/ui/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  838. package/dist/ui/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  839. package/dist/ui/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  840. package/dist/ui/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  841. package/dist/ui/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  842. package/dist/ui/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  843. package/dist/ui/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  844. package/dist/ui/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  845. package/dist/ui/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  846. package/dist/ui/assets/index-BvKGj9wc.js +8 -0
  847. package/dist/ui/assets/index-wlxynmbV.css +1 -0
  848. package/dist/ui/index.html +13 -0
  849. package/package.json +123 -3
@@ -0,0 +1,2381 @@
1
+ /**
2
+ * Worker-only analytics engine.
3
+ *
4
+ * Every refresh stages a complete candidate inside one
5
+ * `withOpenCodeStorageSnapshot` transaction (identity + metadata + revision
6
+ * membership + changed-ID payload). Historical extent, the trusted source
7
+ * `time_updated` cursor, and wall-time frontier freshness are separate: normal
8
+ * global refreshes read only the inclusive cursor-overlap delta, scoped reads
9
+ * never advance the cursor, and a persisted 7-day repair re-reads the indexed
10
+ * extent plus cached scopes. There is no autonomous timer; work is
11
+ * request-driven.
12
+ */
13
+ import { performance } from "node:perf_hooks";
14
+ import { isRangeKey, rangeWindow } from "../contracts/ranges.js";
15
+ import { compareOpenCodeSourceIdentity, } from "../lib/opencode-storage.js";
16
+ import { createUsageAnalytics, UNKNOWN_PROJECT_ID } from "./aggregation.js";
17
+ import { createAnalyticsIndexes } from "./analytics-indexes.js";
18
+ import { createAnalyticsModel } from "./analytics-model.js";
19
+ import { createAnalyticsReader } from "./analytics-reader.js";
20
+ import { ANALYTICS_PRESENTATION_SESSION_LIMIT, compactFingerprintOf, defaultAnalyticsPresentationPath, defaultAnalyticsSnapshotPath, fingerprintOf, loadAnalyticsPresentation, loadAnalyticsSnapshot, rowFromFingerprint, saveAnalyticsPresentation, saveAnalyticsSnapshot, } from "./analytics-state.js";
21
+ import { resolveHostTimeZone } from "./time-zone.js";
22
+ export const ANALYTICS_REFRESH_INTERVAL_MS = 600_000;
23
+ /** Explicit, rare full reconciliation cadence (persisted across restarts). */
24
+ export const ANALYTICS_FULL_REPAIR_INTERVAL_MS = 7 * 24 * 60 * 60_000;
25
+ /** Inclusive replay overlap for equal/late `time_updated` values (clock skew). */
26
+ export const ANALYTICS_SOURCE_CURSOR_OVERLAP_MS = 5 * 60_000;
27
+ const MAX_SCOPE_BATCH = 8;
28
+ const MAX_PROJECT_CACHE = 12;
29
+ const PRESENTATION_SAVE_INTERVAL_MS = 60_000;
30
+ /**
31
+ * Idle grace before the automatic 7d -> 30d extension starts. A zero-delay
32
+ * timer only yields one event-loop turn and can immediately queue a long
33
+ * synchronous SQL read ahead of foreground navigation.
34
+ */
35
+ export const ANALYTICS_THIRTY_DAY_EXTENSION_DELAY_MS = 2_000;
36
+ /** Bounded busy retries; a later 7d response schedules a fresh attempt. */
37
+ const LOW_PRIORITY_EXTENSION_MAX_DEFERRALS = 1;
38
+ const HOME_PRECOMPUTE_RANGES = ["24h", "7d", "30d"];
39
+ /**
40
+ * Fixed instrumentation labels. Each phase is timed around the operation it
41
+ * names and accumulates for the engine lifetime:
42
+ *
43
+ * - `presentationLoad` / `indexLoad`: the awaited sidecar/index loads only.
44
+ * - `metadataRead`: session and project index reads (one count per read).
45
+ * - `revisionDiscovery`: the projected revision scan read.
46
+ * - `historicalPayloadRead`: every non-changed-ID row payload read, including
47
+ * global extent windows, scoped project/tree reads, and compaction markers.
48
+ * - `changedPayloadRead`: `messageIDs`-keyed payload reads after revision diffs.
49
+ * - `modelUpdate`: model clear/setMetadata/apply work, including hydration.
50
+ * - `dtoAggregation`: model home/project derivation and session DTO assembly;
51
+ * `ensureModel()` is excluded and counted under `modelUpdate` instead.
52
+ * - `persistenceWrite`: each awaited snapshot/presentation save.
53
+ *
54
+ * Phases deliberately exclude cache hits and queueing. Metrics contain only
55
+ * these labels plus counts and durations; no session/project/message identity
56
+ * or other data is recorded.
57
+ */
58
+ const PHASE_LABELS = [
59
+ "presentationLoad",
60
+ "indexLoad",
61
+ "metadataRead",
62
+ "revisionDiscovery",
63
+ "historicalPayloadRead",
64
+ "changedPayloadRead",
65
+ "modelUpdate",
66
+ "dtoAggregation",
67
+ "persistenceWrite",
68
+ ];
69
+ class AnalyticsLookupError extends Error {
70
+ code;
71
+ constructor(code) {
72
+ super(code);
73
+ this.name = "AnalyticsLookupError";
74
+ this.code = code;
75
+ }
76
+ }
77
+ /**
78
+ * Revision watermark attached to a bulk payload row without allocating a
79
+ * parallel map for every row.
80
+ */
81
+ const WATERMARK = Symbol("analyticsWatermark");
82
+ const RANGE_WIDTH = {
83
+ "24h": 1,
84
+ "7d": 7,
85
+ "30d": 30,
86
+ lifetime: 10_000,
87
+ };
88
+ function widerRange(a, b) {
89
+ if (a === undefined)
90
+ return b;
91
+ return RANGE_WIDTH[a] >= RANGE_WIDTH[b] ? a : b;
92
+ }
93
+ function emptyState() {
94
+ return {
95
+ sessions: {},
96
+ projects: {},
97
+ fingerprints: [],
98
+ fingerprintIndex: new Map(),
99
+ occurrences: new Map(),
100
+ frontierAtMs: 0,
101
+ };
102
+ }
103
+ function projectIdOf(session) {
104
+ const value = session.projectID?.trim();
105
+ return value ? value : UNKNOWN_PROJECT_ID;
106
+ }
107
+ function coversSince(sinceMs, extent) {
108
+ if (!extent)
109
+ return false;
110
+ if (sinceMs === undefined)
111
+ return extent.sinceMs === undefined;
112
+ if (extent.sinceMs !== undefined && extent.sinceMs > sinceMs)
113
+ return false;
114
+ return extent.untilMs >= sinceMs;
115
+ }
116
+ function mergeExtent(current, sinceMs, untilMs) {
117
+ if (!current) {
118
+ return sinceMs === undefined ? { untilMs } : { sinceMs, untilMs };
119
+ }
120
+ if (current.sinceMs === undefined || sinceMs === undefined) {
121
+ return { untilMs: Math.max(current.untilMs, untilMs) };
122
+ }
123
+ return {
124
+ sinceMs: Math.min(current.sinceMs, sinceMs),
125
+ untilMs: Math.max(current.untilMs, untilMs),
126
+ };
127
+ }
128
+ function sessionRevisionSignature(sessions, ids) {
129
+ return ids
130
+ .map((id) => {
131
+ const session = sessions[id];
132
+ return `${id}:${session?.title ?? ""}:${session?.parentID ?? ""}:${session?.time?.created ?? ""}:${session?.time?.updated ?? ""}:${session?.agent ?? ""}`;
133
+ })
134
+ .join("|");
135
+ }
136
+ /** Parent/project topology only; title and timestamp churn must not reindex. */
137
+ function sessionIndexSignature(sessions) {
138
+ return Object.values(sessions)
139
+ .map((session) => `${session.id}\u0000${session.parentID ?? ""}\u0000${projectIdOf(session)}`)
140
+ .sort()
141
+ .join("\u0001");
142
+ }
143
+ function projectSignature(projectId, range, sessionIds) {
144
+ return `${projectId}|${range}|${sessionIds.join(",")}`;
145
+ }
146
+ function metadataChanged(previous, next) {
147
+ return JSON.stringify(previous) !== JSON.stringify(next);
148
+ }
149
+ function compareIds(a, b) {
150
+ return a < b ? -1 : a > b ? 1 : 0;
151
+ }
152
+ /** Positive completion time only for completed assistant rows; 0 otherwise. */
153
+ function revisionCompletedAt(revision) {
154
+ return revision.type === "assistant" &&
155
+ revision.completedAtMs !== null &&
156
+ revision.completedAtMs > 0
157
+ ? revision.completedAtMs
158
+ : 0;
159
+ }
160
+ export function createAnalyticsEngine(options = {}) {
161
+ const reader = options.reader ?? createAnalyticsReader();
162
+ const now = options.now ?? Date.now;
163
+ const timeZone = options.timeZone ?? resolveHostTimeZone();
164
+ const snapshotPath = options.snapshotPath ?? defaultAnalyticsSnapshotPath();
165
+ const refreshIntervalMs = options.refreshIntervalMs !== undefined && Number.isFinite(options.refreshIntervalMs)
166
+ ? Math.max(0, options.refreshIntervalMs)
167
+ : ANALYTICS_REFRESH_INTERVAL_MS;
168
+ const fullRepairIntervalMs = options.fullRepairIntervalMs !== undefined && Number.isFinite(options.fullRepairIntervalMs)
169
+ ? Math.max(0, options.fullRepairIntervalMs)
170
+ : ANALYTICS_FULL_REPAIR_INTERVAL_MS;
171
+ const loadSnapshot = options.loadSnapshot ?? loadAnalyticsSnapshot;
172
+ const saveSnapshot = options.saveSnapshot ?? saveAnalyticsSnapshot;
173
+ const presentationPath = options.snapshotPath === undefined
174
+ ? defaultAnalyticsPresentationPath(snapshotPath)
175
+ : `${snapshotPath}.presentation.json`;
176
+ const loadPresentation = options.loadPresentation ?? loadAnalyticsPresentation;
177
+ const savePresentation = options.savePresentation ?? saveAnalyticsPresentation;
178
+ // Instrumentation-only accounting; it never affects control flow or results.
179
+ const phaseTotals = new Map();
180
+ function recordPhase(label, startedAtMs) {
181
+ const totalMs = performance.now() - startedAtMs;
182
+ const entry = phaseTotals.get(label);
183
+ if (entry) {
184
+ entry.count += 1;
185
+ entry.totalMs += totalMs;
186
+ }
187
+ else {
188
+ phaseTotals.set(label, { count: 1, totalMs });
189
+ }
190
+ }
191
+ function measureSync(label, work) {
192
+ const startedAtMs = performance.now();
193
+ try {
194
+ return work();
195
+ }
196
+ finally {
197
+ recordPhase(label, startedAtMs);
198
+ }
199
+ }
200
+ async function measureAsync(label, work) {
201
+ const startedAtMs = performance.now();
202
+ try {
203
+ return await work();
204
+ }
205
+ finally {
206
+ recordPhase(label, startedAtMs);
207
+ }
208
+ }
209
+ function phaseMetrics() {
210
+ const metrics = {};
211
+ for (const label of PHASE_LABELS) {
212
+ const entry = phaseTotals.get(label);
213
+ metrics[label] = entry
214
+ ? { count: entry.count, totalMs: entry.totalMs }
215
+ : { count: 0, totalMs: 0 };
216
+ }
217
+ return metrics;
218
+ }
219
+ const model = createAnalyticsModel({ timeZone });
220
+ const indexes = createAnalyticsIndexes();
221
+ let state = emptyState();
222
+ let lastSessionIndexSignature = "";
223
+ let loaded = false;
224
+ let loading;
225
+ let indexLoaded = false;
226
+ let indexLoading;
227
+ let warmPresentation;
228
+ let warmSourceIdentity;
229
+ let warmIdentityVerification;
230
+ let warmIdentityVerifiedGeneration = -1;
231
+ let coverageTrusted = false;
232
+ let sidecarNewerThanIndex = false;
233
+ let lowPriorityTimer;
234
+ let closed = false;
235
+ let closing = false;
236
+ let closePromise;
237
+ let modelHydrated = false;
238
+ let modelDirty = true;
239
+ let lastPresentationSaveAtMs = 0;
240
+ let presentationSavedAtMs = 0;
241
+ let generation = 0;
242
+ const projectFreshAt = new Map();
243
+ const detailFreshAt = new Map();
244
+ const closeWriteTimeoutMs = options.closeWriteTimeoutMs !== undefined && Number.isFinite(options.closeWriteTimeoutMs)
245
+ ? Math.max(0, options.closeWriteTimeoutMs)
246
+ : 2_000;
247
+ let pendingGlobal;
248
+ let pendingMetadataOnly = false;
249
+ const pendingDetailSessions = new Set();
250
+ const pendingProjectScopes = new Map();
251
+ let refreshPromise;
252
+ const lastGlobalRange = { value: undefined };
253
+ const lastDetailSessionIds = new Set();
254
+ const lastProjectScopes = new Map();
255
+ let lastGlobalAttemptAtMs = 0;
256
+ let lastScopedAttemptAtMs = 0;
257
+ let unavailable = false;
258
+ let peakHeapUsed = 0;
259
+ let peakRss = 0;
260
+ // Persistence is serialized so an older generation can never rename over a
261
+ // newer one, and writes capture the generation they are allowed to publish.
262
+ let writeChain = Promise.resolve();
263
+ let snapshotWritePending;
264
+ let presentationWritePending;
265
+ let compactRevision = 0;
266
+ let compactDirty = false;
267
+ let writeDrainScheduled = false;
268
+ function samplePeak() {
269
+ const usage = process.memoryUsage();
270
+ if (usage.heapUsed > peakHeapUsed)
271
+ peakHeapUsed = usage.heapUsed;
272
+ if (usage.rss > peakRss)
273
+ peakRss = usage.rss;
274
+ }
275
+ function setWatermark(row, value) {
276
+ row[WATERMARK] = value;
277
+ }
278
+ const detailSignatures = new Map();
279
+ const detailCompactions = new Map();
280
+ const projectSignatures = new Map();
281
+ const projectCoverage = new Map();
282
+ const detailCoverage = new Map();
283
+ function rowOf(occurrence) {
284
+ const fingerprint = state.fingerprints[occurrence.fingerprintIndex];
285
+ if (!fingerprint)
286
+ return undefined;
287
+ return rowFromFingerprint(fingerprint, occurrence);
288
+ }
289
+ function internFingerprint(row) {
290
+ const fingerprint = fingerprintOf(row);
291
+ let index = state.fingerprintIndex.get(fingerprint);
292
+ if (index === undefined) {
293
+ index = state.fingerprints.length;
294
+ state.fingerprints.push(compactFingerprintOf(row));
295
+ state.fingerprintIndex.set(fingerprint, index);
296
+ }
297
+ return { index, fingerprint };
298
+ }
299
+ function setRow(row, updatedAtMs, agent) {
300
+ const { index } = internFingerprint(row);
301
+ const occurrence = {
302
+ fingerprintIndex: index,
303
+ sessionID: row.sessionID,
304
+ messageID: row.messageID,
305
+ updatedAtMs,
306
+ };
307
+ if (agent !== undefined)
308
+ occurrence.agent = agent;
309
+ state.occurrences.set(row.messageID, occurrence);
310
+ indexes.upsert(occurrence);
311
+ }
312
+ function trimMap(map, limit) {
313
+ while (map.size > limit) {
314
+ const oldest = map.keys().next().value;
315
+ if (oldest === undefined)
316
+ return;
317
+ map.delete(oldest);
318
+ }
319
+ }
320
+ function trimSet(set, limit) {
321
+ while (set.size > limit) {
322
+ const oldest = set.values().next().value;
323
+ if (oldest === undefined)
324
+ return;
325
+ set.delete(oldest);
326
+ }
327
+ }
328
+ /**
329
+ * Loads only the small warm presentation sidecar. The big index loads lazily
330
+ * so the first useful home/project/session view never waits for occurrences.
331
+ */
332
+ async function ensureLoaded() {
333
+ if (loaded)
334
+ return;
335
+ if (loading)
336
+ return loading;
337
+ loading = (async () => {
338
+ try {
339
+ warmPresentation = await measureAsync("presentationLoad", () => loadPresentation(presentationPath));
340
+ }
341
+ catch {
342
+ warmPresentation = undefined;
343
+ }
344
+ if (warmPresentation) {
345
+ state.presentation = warmPresentation;
346
+ warmSourceIdentity = warmPresentation.sourceIdentity;
347
+ presentationSavedAtMs = warmPresentation.savedAtMs ?? 0;
348
+ if (warmPresentation.coverage)
349
+ state.extent = warmPresentation.coverage;
350
+ const warmFreshness = warmPresentation.frontierAtMs ?? warmPresentation.savedAtMs;
351
+ if (warmFreshness !== undefined) {
352
+ state.frontierAtMs = Math.max(state.frontierAtMs, warmFreshness);
353
+ }
354
+ }
355
+ loaded = true;
356
+ })().finally(() => {
357
+ loading = undefined;
358
+ });
359
+ return loading;
360
+ }
361
+ /**
362
+ * A sidecar hit must not bypass a definite source replacement. This opens the
363
+ * lightweight identity-only snapshot (no metadata, revision, or payload scan).
364
+ * An unavailable source keeps the last good DTOs for a stale response.
365
+ */
366
+ function warmCacheAllowed() {
367
+ if (!warmPresentation)
368
+ return Promise.resolve(true);
369
+ if (warmIdentityVerification && warmIdentityVerifiedGeneration === generation) {
370
+ return warmIdentityVerification;
371
+ }
372
+ const checkGeneration = generation;
373
+ warmIdentityVerifiedGeneration = checkGeneration;
374
+ warmIdentityVerification = (async () => {
375
+ let result;
376
+ try {
377
+ result = await reader.withSnapshot((snapshot) => snapshot.identity);
378
+ }
379
+ catch {
380
+ unavailable = true;
381
+ return true;
382
+ }
383
+ if (result.status !== "ok") {
384
+ unavailable = true;
385
+ return true;
386
+ }
387
+ if (compareOpenCodeSourceIdentity(warmPresentation?.sourceIdentity, result.value) !== "changed") {
388
+ return true;
389
+ }
390
+ warmPresentation = undefined;
391
+ warmSourceIdentity = undefined;
392
+ warmIdentityVerifiedGeneration = -1;
393
+ state.presentation = undefined;
394
+ state.extent = undefined;
395
+ state.frontierAtMs = 0;
396
+ return false;
397
+ })();
398
+ return warmIdentityVerification;
399
+ }
400
+ /** Loads the persisted compact index (occurrences/fingerprints/identity). */
401
+ async function ensureIndexLoaded() {
402
+ await ensureLoaded();
403
+ if (indexLoaded)
404
+ return;
405
+ if (indexLoading)
406
+ return indexLoading;
407
+ indexLoading = (async () => {
408
+ let persisted;
409
+ try {
410
+ persisted = await measureAsync("indexLoad", () => loadSnapshot(snapshotPath));
411
+ }
412
+ catch {
413
+ persisted = undefined;
414
+ }
415
+ if (persisted) {
416
+ state = persisted;
417
+ coverageTrusted = true;
418
+ const persistedIdentity = persisted.sourceIdentity;
419
+ const warmIdentity = warmPresentation?.sourceIdentity;
420
+ const warmSavedAtMs = warmPresentation?.savedAtMs;
421
+ const persistedSavedAtMs = persisted.savedAtMs;
422
+ const sameIdentity = warmPresentation !== undefined &&
423
+ persistedIdentity !== undefined &&
424
+ warmIdentity !== undefined &&
425
+ compareOpenCodeSourceIdentity(persistedIdentity, warmIdentity) === "same";
426
+ const notOlder = warmSavedAtMs !== undefined &&
427
+ persistedSavedAtMs !== undefined &&
428
+ warmSavedAtMs >= persistedSavedAtMs;
429
+ if (sameIdentity && notOlder) {
430
+ // The sidecar may serve its cached DTOs, but only the compact index
431
+ // certifies loaded occurrences, cursor, extent, and freshness. A
432
+ // newer savedAt alone is not checkpoint proof; merging sidecar
433
+ // coverage would let a failed snapshot write hide missing history.
434
+ state.presentation = warmPresentation;
435
+ const uncertified = warmPresentation?.frontierAtMs === 0 || warmPresentation?.coverage === undefined;
436
+ sidecarNewerThanIndex =
437
+ uncertified ||
438
+ (warmSavedAtMs !== undefined &&
439
+ persistedSavedAtMs !== undefined &&
440
+ warmSavedAtMs > persistedSavedAtMs);
441
+ if (sidecarNewerThanIndex)
442
+ coverageTrusted = false;
443
+ // Re-check the source lazily on the next cached serve after loading
444
+ // the compact index; a replacement may have happened while the index
445
+ // was being read.
446
+ warmIdentityVerification = undefined;
447
+ warmIdentityVerifiedGeneration = -1;
448
+ }
449
+ else if (warmPresentation) {
450
+ // A missing/mismatched token or an older sidecar cannot certify these
451
+ // DTOs against the persisted index; never let it shadow newer data.
452
+ state.presentation = undefined;
453
+ warmPresentation = undefined;
454
+ warmSourceIdentity = undefined;
455
+ sidecarNewerThanIndex = false;
456
+ }
457
+ presentationSavedAtMs =
458
+ state.presentation !== undefined
459
+ ? (warmSavedAtMs ?? presentationSavedAtMs)
460
+ : (persistedSavedAtMs ?? presentationSavedAtMs);
461
+ }
462
+ indexes.rebuild(state.occurrences.values(), state.sessions);
463
+ lastSessionIndexSignature = sessionIndexSignature(state.sessions);
464
+ indexLoaded = true;
465
+ })().finally(() => {
466
+ indexLoading = undefined;
467
+ });
468
+ return indexLoading;
469
+ }
470
+ function ensureModel() {
471
+ if (modelHydrated && !modelDirty)
472
+ return;
473
+ measureSync("modelUpdate", () => {
474
+ model.clear();
475
+ model.setMetadata(state.sessions, state.projects);
476
+ const rows = function* rowsForModel() {
477
+ for (const occurrence of state.occurrences.values()) {
478
+ const row = rowOf(occurrence);
479
+ if (row)
480
+ yield row;
481
+ }
482
+ };
483
+ model.apply(rows(), []);
484
+ });
485
+ modelHydrated = true;
486
+ modelDirty = false;
487
+ }
488
+ /**
489
+ * Minimal scoped dataset for the shared session DTO builder: tree rows plus
490
+ * every stored occurrence that shares a tree fingerprint (fork owners). The
491
+ * metadata is narrowed to those rows' sessions plus their ancestors so the
492
+ * shared builder never rebuilds unrelated session/project trees.
493
+ */
494
+ function sessionDataset(sessionId) {
495
+ const ids = indexes.treeIds(sessionId);
496
+ const fingerprintIndexes = new Set();
497
+ const includedSessionIds = new Set(ids);
498
+ for (const messageID of indexes.sessionMessages(ids)) {
499
+ const occurrence = state.occurrences.get(messageID);
500
+ if (occurrence)
501
+ fingerprintIndexes.add(occurrence.fingerprintIndex);
502
+ }
503
+ const messages = [];
504
+ for (const messageID of indexes.fingerprintMessages(fingerprintIndexes)) {
505
+ const occurrence = state.occurrences.get(messageID);
506
+ if (!occurrence)
507
+ continue;
508
+ const row = rowOf(occurrence);
509
+ if (!row)
510
+ continue;
511
+ messages.push(row);
512
+ includedSessionIds.add(occurrence.sessionID);
513
+ }
514
+ const sessions = {};
515
+ for (const id of includedSessionIds) {
516
+ let ancestorId = id;
517
+ const seen = new Set();
518
+ while (ancestorId !== undefined && !seen.has(ancestorId)) {
519
+ seen.add(ancestorId);
520
+ const session = state.sessions[ancestorId];
521
+ if (!session)
522
+ break;
523
+ sessions[ancestorId] = session;
524
+ ancestorId = session.parentID;
525
+ }
526
+ }
527
+ const projects = {};
528
+ const focus = state.sessions[sessionId];
529
+ if (focus) {
530
+ const projectId = projectIdOf(focus);
531
+ const info = state.projects[projectId];
532
+ if (info)
533
+ projects[projectId] = info;
534
+ }
535
+ return {
536
+ sessions,
537
+ projects,
538
+ messages,
539
+ compactions: detailCompactions.get(sessionId) ?? [],
540
+ };
541
+ }
542
+ function stateHasProject(projectId) {
543
+ return (Object.hasOwn(state.projects, projectId) || indexes.projectSessions(projectId).length > 0);
544
+ }
545
+ function isStale(atMs) {
546
+ if (unavailable)
547
+ return true;
548
+ return atMs - state.frontierAtMs >= refreshIntervalMs;
549
+ }
550
+ function isDetailFresh(sessionId, atMs) {
551
+ const freshAt = detailFreshAt.get(sessionId);
552
+ return freshAt !== undefined && atMs - freshAt < refreshIntervalMs;
553
+ }
554
+ function dueForAttempt(job, atMs) {
555
+ const baseline = job.globalRange !== undefined
556
+ ? Math.max(state.frontierAtMs, lastGlobalAttemptAtMs)
557
+ : lastScopedAttemptAtMs;
558
+ return atMs - baseline >= refreshIntervalMs;
559
+ }
560
+ function setHomeCache(range, snapshot) {
561
+ const presentation = state.presentation ?? { home: {}, project: [] };
562
+ presentation.home[range] = snapshot;
563
+ state.presentation = presentation;
564
+ }
565
+ function cacheHome(range, snapshot, atMs) {
566
+ setHomeCache(range, snapshot);
567
+ persistPresentation(atMs);
568
+ }
569
+ function cacheProject(snapshot, atMs) {
570
+ const presentation = state.presentation ?? { home: {}, project: [] };
571
+ const filtered = presentation.project.filter(([projectId, range]) => projectId !== snapshot.projectId || range !== snapshot.range);
572
+ filtered.push([snapshot.projectId, snapshot.range, snapshot]);
573
+ while (filtered.length > MAX_PROJECT_CACHE)
574
+ filtered.shift();
575
+ presentation.project = filtered;
576
+ state.presentation = presentation;
577
+ persistPresentation(atMs);
578
+ }
579
+ function cachedProject(projectId, range) {
580
+ const entry = state.presentation?.project.find(([id, entryRange]) => id === projectId && entryRange === range);
581
+ const snapshot = entry?.[2];
582
+ return snapshot?.usage.timeZone === timeZone ? snapshot : undefined;
583
+ }
584
+ function projectScopeCovered(projectId, range, atMs) {
585
+ const coverage = projectCoverage.get(projectId);
586
+ if (!coverage)
587
+ return false;
588
+ if (coverage.signature !== projectSignature(projectId, range, indexes.projectSessions(projectId))) {
589
+ return false;
590
+ }
591
+ return coversSince(rangeWindow(range, atMs).sinceMs, coverage);
592
+ }
593
+ /**
594
+ * The only epochs a cached Home/Project window may be advanced to are actual
595
+ * successful sync epochs. Wall-clock time, a cached DTO's generatedAt, or a
596
+ * project-only scope refresh must never create one.
597
+ */
598
+ function homeCertifiedSyncAtMs(range, atMs) {
599
+ if (!indexLoaded || !coverageTrusted || state.frontierAtMs <= 0)
600
+ return undefined;
601
+ if (!coversSince(rangeWindow(range, atMs).sinceMs, state.extent))
602
+ return undefined;
603
+ return state.frontierAtMs;
604
+ }
605
+ function projectCertifiedSyncAtMs(projectId, range, atMs) {
606
+ let certified;
607
+ if (indexLoaded &&
608
+ coverageTrusted &&
609
+ state.frontierAtMs > 0 &&
610
+ coversSince(rangeWindow(range, atMs).sinceMs, state.extent)) {
611
+ certified = state.frontierAtMs;
612
+ }
613
+ const projectFresh = projectFreshAt.get(projectId);
614
+ if (projectFresh !== undefined && projectScopeCovered(projectId, range, atMs)) {
615
+ certified = certified === undefined ? projectFresh : Math.max(certified, projectFresh);
616
+ }
617
+ return certified;
618
+ }
619
+ function cachedSession(sessionId) {
620
+ const entry = state.presentation?.session?.find(([id]) => id === sessionId);
621
+ const snapshot = entry?.[1];
622
+ return snapshot?.timeZone === timeZone ? snapshot : undefined;
623
+ }
624
+ /** Cache a fresh session DTO as the newest LRU entry (oldest-first order). */
625
+ function cacheSession(sessionId, snapshot, atMs) {
626
+ const presentation = state.presentation ?? { home: {}, project: [] };
627
+ const session = (presentation.session ?? []).filter(([id]) => id !== sessionId);
628
+ session.push([sessionId, snapshot]);
629
+ while (session.length > ANALYTICS_PRESENTATION_SESSION_LIMIT)
630
+ session.shift();
631
+ presentation.session = session;
632
+ state.presentation = presentation;
633
+ persistPresentation(atMs);
634
+ }
635
+ function touchSessionCache(sessionId, atMs) {
636
+ const presentation = state.presentation;
637
+ const session = presentation?.session;
638
+ if (!presentation || !session)
639
+ return;
640
+ const index = session.findIndex(([id]) => id === sessionId);
641
+ if (index < 0)
642
+ return;
643
+ const [entry] = session.splice(index, 1);
644
+ if (!entry)
645
+ return;
646
+ session.push(entry);
647
+ while (session.length > ANALYTICS_PRESENTATION_SESSION_LIMIT)
648
+ session.shift();
649
+ persistPresentation(atMs);
650
+ }
651
+ /**
652
+ * Drops cached session DTOs for a changed detail tree. The compact index
653
+ * carries no detail markers, so a marker-only scoped refresh must notify the
654
+ * host and rewrite the small sidecar even when usage data is unchanged.
655
+ */
656
+ function invalidateCachedSessions(sessionIds) {
657
+ const presentation = state.presentation;
658
+ const session = presentation?.session;
659
+ if (!presentation || !session || session.length === 0)
660
+ return false;
661
+ const next = session.filter(([, snapshot]) => {
662
+ if (sessionIds.has(snapshot.focusSessionId))
663
+ return false;
664
+ return !snapshot.nodes.some((node) => sessionIds.has(node.sessionId));
665
+ });
666
+ if (next.length === session.length)
667
+ return false;
668
+ if (next.length > 0)
669
+ presentation.session = next;
670
+ else
671
+ delete presentation.session;
672
+ state.presentation = presentation;
673
+ return true;
674
+ }
675
+ function hasUsefulPresentation() {
676
+ const presentation = state.presentation;
677
+ return (presentation !== undefined &&
678
+ (Object.keys(presentation.home).length > 0 ||
679
+ presentation.project.length > 0 ||
680
+ (presentation.session?.length ?? 0) > 0));
681
+ }
682
+ /**
683
+ * Before the compact index is loaded, the sidecar identity is not installed
684
+ * on the state (it must not certify indexed data). Preserve it only in the
685
+ * serialized DTO sidecar so a restart can still validate the warm cache.
686
+ */
687
+ function presentationStateForWrite() {
688
+ let view = state;
689
+ if (view.sourceIdentity === undefined && warmSourceIdentity !== undefined) {
690
+ view = { ...view, sourceIdentity: warmSourceIdentity };
691
+ }
692
+ if (compactDirty) {
693
+ // The DTOs may be newer than the last successful compact checkpoint.
694
+ // Omit coverage/freshness so restart cannot derive missing ranges from
695
+ // that unchecked index; cached DTOs can still be served while catching up.
696
+ view = { ...view };
697
+ delete view.extent;
698
+ view.frontierAtMs = 0;
699
+ }
700
+ return view;
701
+ }
702
+ async function drainWrites() {
703
+ for (;;) {
704
+ const snapshotJob = snapshotWritePending;
705
+ snapshotWritePending = undefined;
706
+ const presentationJob = presentationWritePending;
707
+ presentationWritePending = undefined;
708
+ if (!snapshotJob && !presentationJob)
709
+ return;
710
+ if (snapshotJob) {
711
+ const writtenRevision = snapshotJob.revision;
712
+ const saved = await measureAsync("persistenceWrite", () => saveSnapshot(snapshotPath, state, snapshotJob.atMs).catch(() => false));
713
+ if (saved && compactRevision === writtenRevision) {
714
+ compactDirty = false;
715
+ }
716
+ else if (!saved) {
717
+ compactDirty = true;
718
+ }
719
+ }
720
+ if (presentationJob &&
721
+ presentationJob.generation === generation &&
722
+ (presentationJob.force || hasUsefulPresentation())) {
723
+ presentationSavedAtMs = presentationJob.savedAtMs;
724
+ await measureAsync("persistenceWrite", () => savePresentation(presentationPath, presentationStateForWrite(), presentationJob.savedAtMs).catch(() => false));
725
+ }
726
+ }
727
+ }
728
+ function scheduleWriteDrain() {
729
+ if (writeDrainScheduled)
730
+ return;
731
+ writeDrainScheduled = true;
732
+ writeChain = writeChain.then(drainWrites, drainWrites).finally(() => {
733
+ writeDrainScheduled = false;
734
+ if (snapshotWritePending || presentationWritePending)
735
+ scheduleWriteDrain();
736
+ });
737
+ }
738
+ /** Wait for the serialized writer to become idle after a final queue. */
739
+ async function drainAllWrites() {
740
+ for (;;) {
741
+ const chain = writeChain;
742
+ await chain.catch(() => undefined);
743
+ if (!writeDrainScheduled && !snapshotWritePending && !presentationWritePending)
744
+ return;
745
+ if (!writeDrainScheduled)
746
+ scheduleWriteDrain();
747
+ }
748
+ }
749
+ function queueSnapshotWrite(atMs, force = false) {
750
+ if ((closed || closing) && !force)
751
+ return;
752
+ compactDirty = true;
753
+ snapshotWritePending = { revision: compactRevision, atMs };
754
+ scheduleWriteDrain();
755
+ }
756
+ function queuePresentationWrite(atMs, savedAtMs = atMs, force = false) {
757
+ if (closed || closing)
758
+ return;
759
+ if (!force && !hasUsefulPresentation())
760
+ return;
761
+ if (!state.presentation)
762
+ return;
763
+ presentationWritePending = { generation, atMs, savedAtMs, force };
764
+ scheduleWriteDrain();
765
+ }
766
+ /** Final flush bypasses the cache-write throttle during close. */
767
+ function queueFinalPresentationWrite(atMs, savedAtMs) {
768
+ if (!hasUsefulPresentation())
769
+ return;
770
+ lastPresentationSaveAtMs = atMs;
771
+ presentationWritePending = { generation, atMs, savedAtMs, force: false };
772
+ scheduleWriteDrain();
773
+ }
774
+ function persistPresentation(atMs) {
775
+ if (closed || closing || atMs - lastPresentationSaveAtMs < PRESENTATION_SAVE_INTERVAL_MS) {
776
+ return;
777
+ }
778
+ lastPresentationSaveAtMs = atMs;
779
+ // Before the compact index is loaded, keep the sidecar's original save
780
+ // time. A warm LRU touch must not make an older sidecar look newer than a
781
+ // newer persisted index.
782
+ queuePresentationWrite(atMs, indexLoaded ? atMs : presentationSavedAtMs);
783
+ }
784
+ function homeSnapshotWithStaleness(snapshot, range, atMs, stale) {
785
+ return {
786
+ ...snapshot,
787
+ generatedAtMs: atMs,
788
+ range,
789
+ stale,
790
+ providers: { ...snapshot.providers, polledAtMs: atMs },
791
+ usage: { ...snapshot.usage, stale },
792
+ };
793
+ }
794
+ function projectSnapshotWithStaleness(snapshot, stale) {
795
+ return {
796
+ ...snapshot,
797
+ stale,
798
+ usage: { ...snapshot.usage, stale },
799
+ };
800
+ }
801
+ function deriveProjectSnapshot(projectId, range, atMs) {
802
+ const stale = isStale(atMs);
803
+ const snapshot = measureSync("dtoAggregation", () => model.project(projectId, range, atMs));
804
+ return {
805
+ ...snapshot,
806
+ stale,
807
+ usage: { ...snapshot.usage, stale },
808
+ };
809
+ }
810
+ /**
811
+ * Advance cached finite Home/Project DTOs to their actual certified sync
812
+ * epoch. Home only moves on a successful global refresh; project entries may
813
+ * also move on a matching scoped refresh. If the model cannot rebuild a
814
+ * moved entry, expire it so the next request hydrates/rebuilds lazily.
815
+ */
816
+ function refreshFinitePresentationWindows(atMs, globalRefresh) {
817
+ const presentation = state.presentation;
818
+ if (!presentation)
819
+ return false;
820
+ const canDerive = modelHydrated && !modelDirty;
821
+ let changed = false;
822
+ if (globalRefresh) {
823
+ for (const key of Object.keys(presentation.home)) {
824
+ if (!isRangeKey(key) || key === "lifetime")
825
+ continue;
826
+ const snapshot = presentation.home[key];
827
+ const certified = homeCertifiedSyncAtMs(key, atMs);
828
+ if (!snapshot || certified === undefined || snapshot.usage.window.untilMs >= certified) {
829
+ continue;
830
+ }
831
+ if (canDerive) {
832
+ presentation.home[key] = deriveHomeSnapshot(key, certified);
833
+ }
834
+ else {
835
+ delete presentation.home[key];
836
+ }
837
+ changed = true;
838
+ }
839
+ }
840
+ if (presentation.project.length > 0) {
841
+ let projectChanged = false;
842
+ const next = [];
843
+ for (const [projectId, range, snapshot] of presentation.project) {
844
+ const certified = projectCertifiedSyncAtMs(projectId, range, atMs);
845
+ if (range === "lifetime" || certified === undefined) {
846
+ next.push([projectId, range, snapshot]);
847
+ continue;
848
+ }
849
+ if (snapshot.usage.window.untilMs >= certified) {
850
+ next.push([projectId, range, snapshot]);
851
+ continue;
852
+ }
853
+ if (canDerive) {
854
+ next.push([projectId, range, deriveProjectSnapshot(projectId, range, certified)]);
855
+ }
856
+ projectChanged = true;
857
+ }
858
+ if (projectChanged) {
859
+ presentation.project = next;
860
+ changed = true;
861
+ }
862
+ }
863
+ if (changed)
864
+ state.presentation = presentation;
865
+ return changed;
866
+ }
867
+ function deriveHomeSnapshot(range, atMs) {
868
+ const stale = isStale(atMs);
869
+ const snapshot = measureSync("dtoAggregation", () => model.home(range, atMs));
870
+ return {
871
+ generatedAtMs: atMs,
872
+ range,
873
+ stale,
874
+ providers: { cards: [], enabledProviders: [], polledAtMs: atMs },
875
+ usage: { ...snapshot.usage, stale },
876
+ projects: snapshot.projects,
877
+ };
878
+ }
879
+ /**
880
+ * Once 30d is indexed, derive the three bounded Home DTOs together while the
881
+ * model is already hydrated. Missing entries are filled; this never triggers
882
+ * a second model hydration.
883
+ */
884
+ function precomputeHomeSnapshots(atMs) {
885
+ if (!modelHydrated || modelDirty || !coverageTrusted)
886
+ return;
887
+ if (!coversSince(rangeWindow("30d", atMs).sinceMs, state.extent))
888
+ return;
889
+ let changed = false;
890
+ for (const range of HOME_PRECOMPUTE_RANGES) {
891
+ const cachedHome = state.presentation?.home[range];
892
+ if (cachedHome !== undefined && cachedHome.usage.timeZone === timeZone)
893
+ continue;
894
+ if (cachedHome !== undefined)
895
+ delete state.presentation?.home[range];
896
+ const certified = homeCertifiedSyncAtMs(range, atMs);
897
+ if (certified === undefined)
898
+ continue;
899
+ setHomeCache(range, deriveHomeSnapshot(range, certified));
900
+ changed = true;
901
+ }
902
+ if (changed)
903
+ queuePresentationWrite(atMs);
904
+ }
905
+ /**
906
+ * The UI's default finite view is 7d. After that response is ready, extend
907
+ * once to 30d after a short idle grace. A foreground request that arrives
908
+ * during the grace (or a refresh already in flight) wins: the extension
909
+ * retries at most once, then leaves rescheduling to the next 7d response.
910
+ * This is not preemption; a synchronous SQLite read that has already started
911
+ * still runs to completion. Lifetime is never scheduled automatically.
912
+ */
913
+ function scheduleThirtyDayExtension(range, atMs) {
914
+ if (range !== "7d" || closed || closing || lowPriorityTimer !== undefined)
915
+ return;
916
+ if (coversSince(rangeWindow("30d", atMs).sinceMs, state.extent))
917
+ return;
918
+ const hasPendingRefreshWork = () => refreshPromise !== undefined ||
919
+ pendingGlobal !== undefined ||
920
+ pendingMetadataOnly ||
921
+ pendingDetailSessions.size > 0 ||
922
+ pendingProjectScopes.size > 0;
923
+ let deferrals = 0;
924
+ const arm = () => {
925
+ const timer = setTimeout(() => {
926
+ lowPriorityTimer = undefined;
927
+ if (closed || closing)
928
+ return;
929
+ const scheduledAtMs = now();
930
+ if (coversSince(rangeWindow("30d", scheduledAtMs).sinceMs, state.extent))
931
+ return;
932
+ if (hasPendingRefreshWork()) {
933
+ if (deferrals < LOW_PRIORITY_EXTENSION_MAX_DEFERRALS) {
934
+ deferrals += 1;
935
+ arm();
936
+ }
937
+ return;
938
+ }
939
+ void requestRefresh({
940
+ globalRange: "30d",
941
+ detailSessionIds: [],
942
+ projectScopes: [],
943
+ }).catch(() => { });
944
+ }, ANALYTICS_THIRTY_DAY_EXTENSION_DELAY_MS);
945
+ timer.unref?.();
946
+ lowPriorityTimer = timer;
947
+ };
948
+ arm();
949
+ }
950
+ function buildCandidate(snapshot, job, atMs) {
951
+ const identity = snapshot.identity;
952
+ const comparison = compareOpenCodeSourceIdentity(state.sourceIdentity, identity);
953
+ if (comparison === "unavailable")
954
+ return "unavailable";
955
+ // A truly pristine in-memory state is the first baseline, not a source
956
+ // replacement; it has nothing to clear and needs no lifetime projection.
957
+ const pristine = comparison === "changed" &&
958
+ state.sourceIdentity === undefined &&
959
+ state.occurrences.size === 0 &&
960
+ Object.keys(state.sessions).length === 0 &&
961
+ state.presentation === undefined;
962
+ const replaced = comparison === "changed" && !pristine;
963
+ const readHistoricalRows = (params = {}) => measureSync("historicalPayloadRead", () => snapshot.readCompletedAssistantRows(params));
964
+ const readChangedRows = (messageIDs) => measureSync("changedPayloadRead", () => snapshot.readCompletedAssistantRows({ messageIDs }));
965
+ const sessions = measureSync("metadataRead", () => snapshot.readAllSessionsIndex());
966
+ const projects = measureSync("metadataRead", () => snapshot.readProjectsIndex());
967
+ // Stage metadata topology without touching committed indexes until commit.
968
+ const candidateIndexes = createAnalyticsIndexes();
969
+ candidateIndexes.setSessions(sessions);
970
+ const globalRefresh = job.globalRange !== undefined;
971
+ const effectiveExtent = replaced ? undefined : state.extent;
972
+ const priorCursor = replaced ? undefined : state.sourceCursorAtMs;
973
+ const priorRepairAtMs = replaced ? undefined : state.lastFullRepairAtMs;
974
+ const repairDue = globalRefresh &&
975
+ (job.repair === true ||
976
+ priorRepairAtMs === undefined ||
977
+ atMs - priorRepairAtMs >= fullRepairIntervalMs ||
978
+ // A wall-clock rollback can move the inclusive window past unseen
979
+ // source timestamps; reconcile fully rather than skip them.
980
+ (priorCursor !== undefined && atMs < priorCursor));
981
+ // Establish the source cursor either from a cheap physical frontier (no
982
+ // stored contribution needs membership) or from one full revision
983
+ // projection. Normal refreshes use only the cursor-overlap delta.
984
+ let revisionSnapshot;
985
+ let fullProjection = false;
986
+ let cursorBaseline = false;
987
+ let deltaValid = false;
988
+ let sourceCursorAtMs;
989
+ if (globalRefresh) {
990
+ const emptyBaseline = priorCursor === undefined && state.occurrences.size === 0 && !replaced;
991
+ if (emptyBaseline) {
992
+ const frontier = measureSync("revisionDiscovery", () => snapshot.readMessageRevisionFrontier());
993
+ sourceCursorAtMs =
994
+ frontier.available && frontier.updatedAtAvailable
995
+ ? Math.min(frontier.maxUpdatedAtMs ?? 0, atMs)
996
+ : null;
997
+ cursorBaseline = true;
998
+ }
999
+ else if (priorCursor !== undefined && !repairDue) {
1000
+ revisionSnapshot = measureSync("revisionDiscovery", () => snapshot.readMessageRevisions({
1001
+ updatedSinceMs: Math.max(0, priorCursor - ANALYTICS_SOURCE_CURSOR_OVERLAP_MS),
1002
+ }));
1003
+ if (!revisionSnapshot.available)
1004
+ return "unavailable";
1005
+ if (!revisionSnapshot.updatedAtAvailable) {
1006
+ // The storage filter is not applicable without a time_updated column,
1007
+ // so this result is already the full identity set.
1008
+ fullProjection = true;
1009
+ }
1010
+ else if (!revisionSnapshot.completedAtAvailable) {
1011
+ // The timestamp filter applied, but completion identity is missing;
1012
+ // reconcile the full identity set conservatively.
1013
+ revisionSnapshot = measureSync("revisionDiscovery", () => snapshot.readMessageRevisions());
1014
+ if (!revisionSnapshot.available)
1015
+ return "unavailable";
1016
+ fullProjection = true;
1017
+ }
1018
+ }
1019
+ else {
1020
+ revisionSnapshot = measureSync("revisionDiscovery", () => snapshot.readMessageRevisions());
1021
+ if (!revisionSnapshot.available)
1022
+ return "unavailable";
1023
+ fullProjection = true;
1024
+ }
1025
+ if (revisionSnapshot) {
1026
+ fullProjection =
1027
+ fullProjection ||
1028
+ !revisionSnapshot.updatedAtAvailable ||
1029
+ !revisionSnapshot.completedAtAvailable;
1030
+ const revisions = revisionSnapshot.revisions;
1031
+ if (!fullProjection) {
1032
+ // Deterministic time-then-id order keeps equal timestamps and
1033
+ // lexically earlier late commits replayable and idempotent.
1034
+ revisions.sort((a, b) => (a.updatedAtMs ?? Number.NEGATIVE_INFINITY) -
1035
+ (b.updatedAtMs ?? Number.NEGATIVE_INFINITY) || compareIds(a.messageID, b.messageID));
1036
+ }
1037
+ let maxUpdated = priorCursor;
1038
+ for (const revision of revisions) {
1039
+ if (revision.updatedAtMs !== null &&
1040
+ (maxUpdated === undefined || revision.updatedAtMs > maxUpdated)) {
1041
+ maxUpdated = revision.updatedAtMs;
1042
+ }
1043
+ }
1044
+ sourceCursorAtMs =
1045
+ revisionSnapshot.updatedAtAvailable && revisionSnapshot.completedAtAvailable
1046
+ ? Math.min(maxUpdated ?? 0, atMs)
1047
+ : null;
1048
+ }
1049
+ deltaValid = !fullProjection && revisionSnapshot !== undefined && !repairDue;
1050
+ }
1051
+ const bulkRows = [];
1052
+ const bulkMap = new Map();
1053
+ const changedMap = new Map();
1054
+ const changedIds = new Map();
1055
+ const removalKeys = new Set();
1056
+ const authoritativePayloadIDs = new Set();
1057
+ const watermarks = revisionSnapshot !== undefined && !fullProjection && revisionSnapshot.updatedAtAvailable
1058
+ ? new Map(revisionSnapshot.revisions.map((revision) => [
1059
+ revision.messageID,
1060
+ revision.updatedAtMs,
1061
+ ]))
1062
+ : undefined;
1063
+ const stageChanged = (row, updatedAtMs) => {
1064
+ const key = row.messageID;
1065
+ authoritativePayloadIDs.add(key);
1066
+ const entry = {
1067
+ row,
1068
+ updatedAtMs,
1069
+ // The source payload reader projects the agent field; an absent agent
1070
+ // is authoritative there and must not be confused with a cached
1071
+ // synthetic occurrence that simply has no transient agent loaded.
1072
+ agentProjected: true,
1073
+ };
1074
+ if (row.agent !== undefined)
1075
+ entry.agent = row.agent;
1076
+ changedMap.set(key, entry);
1077
+ removalKeys.delete(key);
1078
+ };
1079
+ const stageBulk = (row, updatedAtMs) => {
1080
+ const key = row.messageID;
1081
+ authoritativePayloadIDs.add(key);
1082
+ const existing = bulkMap.get(key);
1083
+ if (existing) {
1084
+ if (updatedAtMs !== undefined)
1085
+ setWatermark(existing, updatedAtMs);
1086
+ return;
1087
+ }
1088
+ setWatermark(row, updatedAtMs !== undefined
1089
+ ? updatedAtMs
1090
+ : row.updatedAtMs !== undefined
1091
+ ? row.updatedAtMs
1092
+ : (watermarks?.get(key) ?? null));
1093
+ bulkMap.set(key, row);
1094
+ bulkRows.push(row);
1095
+ };
1096
+ // Removed session metadata is authoritative for its stored occurrences.
1097
+ // The session index narrows the walk to messages of sessions that actually
1098
+ // disappeared; the committed occurrence index is never rebuilt here.
1099
+ if (!replaced) {
1100
+ const removedSessionIds = new Set();
1101
+ for (const id of Object.keys(state.sessions)) {
1102
+ if (!Object.hasOwn(sessions, id))
1103
+ removedSessionIds.add(id);
1104
+ }
1105
+ if (removedSessionIds.size > 0) {
1106
+ for (const messageID of indexes.sessionMessages(removedSessionIds)) {
1107
+ removalKeys.add(messageID);
1108
+ }
1109
+ }
1110
+ }
1111
+ const fullRepairRead = fullProjection && !replaced && effectiveExtent !== undefined;
1112
+ // Even a scope-only snapshot has no global extent but can carry cached
1113
+ // occurrences. A full projection/baseline must still refresh those cached
1114
+ // payloads by id, not only the newly requested extent.
1115
+ const fullCachedRepairRead = fullProjection && !replaced;
1116
+ const window = job.globalRange ? rangeWindow(job.globalRange, atMs) : undefined;
1117
+ let nextExtent = effectiveExtent;
1118
+ let extentChanged = false;
1119
+ if (window) {
1120
+ const prior = effectiveExtent;
1121
+ if (!prior) {
1122
+ for (const row of readHistoricalRows({
1123
+ ...(window.sinceMs === undefined ? {} : { completedSinceMs: window.sinceMs }),
1124
+ completedUntilMs: atMs,
1125
+ })) {
1126
+ stageBulk(row);
1127
+ }
1128
+ }
1129
+ else if (!fullRepairRead) {
1130
+ // Extend only the actually missing older side of the extent.
1131
+ if (window.sinceMs === undefined) {
1132
+ if (prior.sinceMs !== undefined) {
1133
+ for (const row of readHistoricalRows({ completedUntilMs: prior.sinceMs })) {
1134
+ stageBulk(row);
1135
+ }
1136
+ }
1137
+ }
1138
+ else if (prior.sinceMs !== undefined && window.sinceMs < prior.sinceMs) {
1139
+ // Bounded requests inside an already-lifetime extent are covered;
1140
+ // only a genuinely older requested start needs an extra read.
1141
+ for (const row of readHistoricalRows({
1142
+ completedSinceMs: window.sinceMs,
1143
+ completedUntilMs: prior.sinceMs,
1144
+ })) {
1145
+ stageBulk(row);
1146
+ }
1147
+ }
1148
+ // The completion frontier is already supplied by a valid revision
1149
+ // delta, and a full repair below re-reads the whole extent; do not
1150
+ // re-read the same leaving payload every refresh.
1151
+ if (prior.untilMs < atMs && !deltaValid) {
1152
+ for (const row of readHistoricalRows({
1153
+ completedSinceMs: prior.untilMs,
1154
+ completedUntilMs: atMs,
1155
+ })) {
1156
+ stageBulk(row);
1157
+ }
1158
+ }
1159
+ }
1160
+ nextExtent = mergeExtent(effectiveExtent, window.sinceMs, atMs);
1161
+ extentChanged = true;
1162
+ }
1163
+ // A full reconciliation re-reads the indexed extent (and, below, cached
1164
+ // scopes) so payload edits that did not move the source timestamp repair.
1165
+ if (fullRepairRead && nextExtent) {
1166
+ for (const row of readHistoricalRows({
1167
+ ...(nextExtent.sinceMs === undefined ? {} : { completedSinceMs: nextExtent.sinceMs }),
1168
+ completedUntilMs: nextExtent.untilMs,
1169
+ })) {
1170
+ stageBulk(row);
1171
+ }
1172
+ }
1173
+ const completedMembership = revisionSnapshot?.completedAtAvailable === true;
1174
+ if (fullProjection && !completedMembership && !replaced && nextExtent) {
1175
+ // No completion identity: the extent payload read above is authoritative
1176
+ // for completion/type membership inside the indexed extent.
1177
+ for (const [key, occurrence] of state.occurrences) {
1178
+ const fingerprint = state.fingerprints[occurrence.fingerprintIndex];
1179
+ if (!fingerprint)
1180
+ continue;
1181
+ if (fingerprint[1] > atMs)
1182
+ continue;
1183
+ if (nextExtent.sinceMs !== undefined && fingerprint[1] < nextExtent.sinceMs)
1184
+ continue;
1185
+ removalKeys.add(key);
1186
+ }
1187
+ }
1188
+ const detailSignatureChanges = [];
1189
+ const detailCompactionChanges = [];
1190
+ const detailCoverageChanges = [];
1191
+ const projectSignatureChanges = [];
1192
+ const projectCoverageChanges = [];
1193
+ const reusedScopes = [];
1194
+ const reconciledOwnerMessageIDs = new Set();
1195
+ /**
1196
+ * Safe owner-read elision: a valid global delta reconciled in this same
1197
+ * transaction already staged every external row that could share a scoped
1198
+ * fingerprint, but only when the loaded completion extent covers every
1199
+ * scoped time. Wall-clock/global freshness alone proves nothing about
1200
+ * external source changes and never takes this path.
1201
+ */
1202
+ const ownershipReconciledInSnapshot = globalRefresh && deltaValid && nextExtent !== undefined;
1203
+ const timesCoveredByExtent = (times) => {
1204
+ if (!ownershipReconciledInSnapshot || !nextExtent)
1205
+ return false;
1206
+ for (const time of times) {
1207
+ if (time > nextExtent.untilMs)
1208
+ return false;
1209
+ if (nextExtent.sinceMs !== undefined && time < nextExtent.sinceMs)
1210
+ return false;
1211
+ }
1212
+ return true;
1213
+ };
1214
+ /**
1215
+ * Cross-scope fork owners must stay in the contribution set for exact
1216
+ * ownership. Query only the exact completion timestamps of the scope
1217
+ * instead of projecting every row in the min/max span.
1218
+ */
1219
+ /**
1220
+ * Scoped-only reads have no global revision scan, so a known external fork
1221
+ * owner can be stale. Resolve its current identity through the fingerprint
1222
+ * reverse index and the scoped message-ID revision projection; update or
1223
+ * remove it before ownership is evaluated. A same-snapshot global delta
1224
+ * already reconciled every stored occurrence, so this is skipped then.
1225
+ */
1226
+ const reconcileKnownExternalOwners = (read) => {
1227
+ if (ownershipReconciledInSnapshot || read.fingerprints.size === 0)
1228
+ return;
1229
+ const candidates = new Set();
1230
+ for (const fingerprint of read.fingerprints) {
1231
+ const fingerprintIndex = state.fingerprintIndex.get(fingerprint);
1232
+ if (fingerprintIndex === undefined)
1233
+ continue;
1234
+ for (const messageID of indexes.fingerprintMessages([fingerprintIndex])) {
1235
+ if (reconciledOwnerMessageIDs.has(messageID))
1236
+ continue;
1237
+ if (bulkMap.has(messageID) || changedMap.has(messageID))
1238
+ continue;
1239
+ const occurrence = state.occurrences.get(messageID);
1240
+ if (!occurrence || read.ids.has(occurrence.sessionID))
1241
+ continue;
1242
+ candidates.add(messageID);
1243
+ }
1244
+ }
1245
+ if (candidates.size === 0)
1246
+ return;
1247
+ const revisions = measureSync("revisionDiscovery", () => snapshot.readMessageRevisions({ messageIDs: [...candidates] }));
1248
+ if (!revisions.available)
1249
+ return;
1250
+ const byId = new Map(revisions.revisions.map((revision) => [revision.messageID, revision]));
1251
+ const changedForOwner = new Map();
1252
+ for (const messageID of candidates) {
1253
+ reconciledOwnerMessageIDs.add(messageID);
1254
+ const occurrence = state.occurrences.get(messageID);
1255
+ if (!occurrence)
1256
+ continue;
1257
+ const revision = byId.get(messageID);
1258
+ if (!revision) {
1259
+ removalKeys.add(messageID);
1260
+ continue;
1261
+ }
1262
+ if (revisions.completedAtAvailable) {
1263
+ if (revisionCompletedAt(revision) === 0) {
1264
+ removalKeys.add(messageID);
1265
+ continue;
1266
+ }
1267
+ }
1268
+ const fingerprint = state.fingerprints[occurrence.fingerprintIndex];
1269
+ const identityChanged = !revisions.updatedAtAvailable ||
1270
+ !revisions.completedAtAvailable ||
1271
+ revision.updatedAtMs === null ||
1272
+ !fingerprint ||
1273
+ revision.sessionID !== occurrence.sessionID ||
1274
+ revision.completedAtMs !== fingerprint[1] ||
1275
+ revision.updatedAtMs !== occurrence.updatedAtMs;
1276
+ if (identityChanged)
1277
+ changedForOwner.set(messageID, revision.updatedAtMs);
1278
+ }
1279
+ if (changedForOwner.size === 0)
1280
+ return;
1281
+ const resolved = new Set();
1282
+ const rows = readChangedRows([...changedForOwner.keys()]);
1283
+ for (const row of rows) {
1284
+ if (!changedForOwner.has(row.messageID))
1285
+ continue;
1286
+ const updatedAtMs = changedForOwner.get(row.messageID) ?? null;
1287
+ resolved.add(row.messageID);
1288
+ stageChanged(row, updatedAtMs);
1289
+ }
1290
+ for (const messageID of changedForOwner.keys()) {
1291
+ if (!resolved.has(messageID) && state.occurrences.has(messageID)) {
1292
+ removalKeys.add(messageID);
1293
+ }
1294
+ }
1295
+ };
1296
+ const discoverExternalOwners = (read) => {
1297
+ if (read.times.size === 0)
1298
+ return;
1299
+ reconcileKnownExternalOwners(read);
1300
+ if (timesCoveredByExtent(read.times))
1301
+ return;
1302
+ const candidates = readHistoricalRows({ completedAtTimes: [...read.times] });
1303
+ for (const row of candidates) {
1304
+ if (read.ids.has(row.sessionID))
1305
+ continue;
1306
+ if (!read.times.has(row.completedAtMs))
1307
+ continue;
1308
+ if (!read.fingerprints.has(fingerprintOf(row)))
1309
+ continue;
1310
+ if (bulkMap.has(row.messageID) || changedMap.has(row.messageID))
1311
+ continue;
1312
+ const occurrence = state.occurrences.get(row.messageID);
1313
+ if (occurrence) {
1314
+ const stored = state.fingerprints[occurrence.fingerprintIndex];
1315
+ if (stored &&
1316
+ occurrence.sessionID === row.sessionID &&
1317
+ occurrence.updatedAtMs === (row.updatedAtMs ?? null) &&
1318
+ fingerprintOf(rowFromFingerprint(stored, occurrence)) === fingerprintOf(row)) {
1319
+ continue;
1320
+ }
1321
+ }
1322
+ stageChanged(row, row.updatedAtMs ?? null);
1323
+ }
1324
+ };
1325
+ const markReusedScopesDirty = (sessionID, completedAtMs) => {
1326
+ for (const scope of reusedScopes) {
1327
+ if (!scope.sessionIds.has(sessionID)) {
1328
+ // A new/changed external copy at a cached scope time can change the
1329
+ // deterministic owner even though it belongs to another session.
1330
+ if (completedAtMs > 0 && scope.read.times.has(completedAtMs))
1331
+ scope.dirty = true;
1332
+ continue;
1333
+ }
1334
+ if (completedAtMs === 0) {
1335
+ scope.dirty = true;
1336
+ continue;
1337
+ }
1338
+ if (completedAtMs > scope.untilMs)
1339
+ continue;
1340
+ if (scope.sinceMs !== undefined && completedAtMs < scope.sinceMs)
1341
+ continue;
1342
+ scope.dirty = true;
1343
+ }
1344
+ };
1345
+ const revisionEligibleInReusedScope = (sessionID, completedAtMs) => {
1346
+ for (const scope of reusedScopes) {
1347
+ if (!scope.sessionIds.has(sessionID))
1348
+ continue;
1349
+ if (completedAtMs > scope.untilMs)
1350
+ continue;
1351
+ if (scope.sinceMs !== undefined && completedAtMs < scope.sinceMs)
1352
+ continue;
1353
+ return true;
1354
+ }
1355
+ return false;
1356
+ };
1357
+ for (const scope of job.projectScopes) {
1358
+ const scopeWindow = rangeWindow(scope.range, atMs);
1359
+ const ids = candidateIndexes.projectSessions(scope.projectId);
1360
+ if (ids.length === 0)
1361
+ continue;
1362
+ const signature = projectSignature(scope.projectId, scope.range, ids);
1363
+ const scopeSessions = new Set(ids);
1364
+ const priorCoverage = projectCoverage.get(scope.projectId);
1365
+ const coveredByGlobalExtent = globalRefresh && deltaValid && coversSince(scopeWindow.sinceMs, nextExtent);
1366
+ const reusableCoverage = globalRefresh && deltaValid && priorCoverage?.signature === signature;
1367
+ if (coveredByGlobalExtent) {
1368
+ // The valid global delta already reconciles this whole window; the
1369
+ // project DTO derives from the shared model, so no scoped payload.
1370
+ }
1371
+ else if (reusableCoverage) {
1372
+ // Cached coverage: the valid global delta already updates existing
1373
+ // occurrences and stages new eligible ids. No historical payload read.
1374
+ const read = { ids: scopeSessions, fingerprints: new Set(), times: new Set() };
1375
+ for (const messageID of indexes.sessionMessages(scopeSessions)) {
1376
+ if (removalKeys.has(messageID))
1377
+ continue;
1378
+ const occurrence = state.occurrences.get(messageID);
1379
+ if (!occurrence)
1380
+ continue;
1381
+ const fingerprint = state.fingerprints[occurrence.fingerprintIndex];
1382
+ if (!fingerprint)
1383
+ continue;
1384
+ if (fingerprint[1] > atMs)
1385
+ continue;
1386
+ if (scopeWindow.sinceMs !== undefined && fingerprint[1] < scopeWindow.sinceMs)
1387
+ continue;
1388
+ read.fingerprints.add(fingerprintOf(rowFromFingerprint(fingerprint, occurrence)));
1389
+ read.times.add(fingerprint[1]);
1390
+ }
1391
+ reusedScopes.push({
1392
+ sessionIds: scopeSessions,
1393
+ sinceMs: scopeWindow.sinceMs,
1394
+ untilMs: atMs,
1395
+ read,
1396
+ dirty: false,
1397
+ });
1398
+ }
1399
+ else {
1400
+ for (const messageID of indexes.sessionMessages(scopeSessions)) {
1401
+ const occurrence = state.occurrences.get(messageID);
1402
+ if (!occurrence)
1403
+ continue;
1404
+ const fingerprint = state.fingerprints[occurrence.fingerprintIndex];
1405
+ if (fingerprint &&
1406
+ fingerprint[1] <= atMs &&
1407
+ (scopeWindow.sinceMs === undefined || fingerprint[1] >= scopeWindow.sinceMs)) {
1408
+ removalKeys.add(messageID);
1409
+ }
1410
+ }
1411
+ const rows = readHistoricalRows({
1412
+ sessionIDs: ids,
1413
+ ...(scopeWindow.sinceMs === undefined ? {} : { completedSinceMs: scopeWindow.sinceMs }),
1414
+ completedUntilMs: atMs,
1415
+ });
1416
+ const read = { ids: scopeSessions, fingerprints: new Set(), times: new Set() };
1417
+ for (const row of rows) {
1418
+ read.fingerprints.add(fingerprintOf(row));
1419
+ read.times.add(row.completedAtMs);
1420
+ stageBulk(row);
1421
+ }
1422
+ discoverExternalOwners(read);
1423
+ }
1424
+ projectCoverageChanges.push([
1425
+ scope.projectId,
1426
+ {
1427
+ signature,
1428
+ sessionIds: ids,
1429
+ ...(scopeWindow.sinceMs === undefined ? {} : { sinceMs: scopeWindow.sinceMs }),
1430
+ untilMs: atMs,
1431
+ },
1432
+ ]);
1433
+ projectSignatureChanges.push([scope.projectId, signature]);
1434
+ }
1435
+ for (const focusId of job.detailSessionIds) {
1436
+ const focus = sessions[focusId];
1437
+ if (!focus) {
1438
+ detailSignatureChanges.push([focusId, ""]);
1439
+ continue;
1440
+ }
1441
+ const ids = candidateIndexes.treeIds(focusId);
1442
+ const idSet = new Set(ids);
1443
+ const scopedRevisions = measureSync("revisionDiscovery", () => snapshot.readMessageRevisions({ sessionIDs: ids }));
1444
+ const scopedWatermarks = new Map();
1445
+ if (scopedRevisions.available) {
1446
+ for (const revision of scopedRevisions.revisions) {
1447
+ scopedWatermarks.set(revision.messageID, revision.updatedAtMs);
1448
+ }
1449
+ }
1450
+ const signature = sessionRevisionSignature(sessions, ids);
1451
+ const read = { ids: idSet, fingerprints: new Set(), times: new Set() };
1452
+ const warmPayloads = !replaced &&
1453
+ !repairDue &&
1454
+ detailCoverage.has(focusId) &&
1455
+ detailCompactions.has(focusId) &&
1456
+ scopedRevisions.available &&
1457
+ scopedRevisions.updatedAtAvailable &&
1458
+ scopedRevisions.completedAtAvailable;
1459
+ if (warmPayloads) {
1460
+ // Warm detail: the full tree payload (including transient agents) was
1461
+ // already loaded. Reconcile identities through the revision diff and
1462
+ // fetch payloads only for changed/new ids.
1463
+ const previousMessageIDs = new Set(indexes.sessionMessages(ids));
1464
+ const seenMessageIDs = new Set();
1465
+ const changedForDetail = new Map();
1466
+ let detailDirty = false;
1467
+ for (const revision of scopedRevisions.revisions) {
1468
+ seenMessageIDs.add(revision.messageID);
1469
+ const occurrence = state.occurrences.get(revision.messageID);
1470
+ const completed = revisionCompletedAt(revision);
1471
+ if (completed === 0) {
1472
+ if (occurrence) {
1473
+ removalKeys.add(revision.messageID);
1474
+ detailDirty = true;
1475
+ }
1476
+ continue;
1477
+ }
1478
+ if (!occurrence) {
1479
+ changedForDetail.set(revision.messageID, revision.updatedAtMs);
1480
+ detailDirty = true;
1481
+ continue;
1482
+ }
1483
+ const fingerprint = state.fingerprints[occurrence.fingerprintIndex];
1484
+ if (revision.updatedAtMs === null ||
1485
+ !fingerprint ||
1486
+ occurrence.sessionID !== revision.sessionID ||
1487
+ completed !== fingerprint[1] ||
1488
+ revision.updatedAtMs !== occurrence.updatedAtMs) {
1489
+ changedForDetail.set(revision.messageID, revision.updatedAtMs);
1490
+ detailDirty = true;
1491
+ continue;
1492
+ }
1493
+ const row = rowOf(occurrence);
1494
+ if (row) {
1495
+ read.fingerprints.add(fingerprintOf(row));
1496
+ read.times.add(row.completedAtMs);
1497
+ }
1498
+ }
1499
+ for (const messageID of previousMessageIDs) {
1500
+ if (!seenMessageIDs.has(messageID)) {
1501
+ removalKeys.add(messageID);
1502
+ detailDirty = true;
1503
+ }
1504
+ }
1505
+ if (changedForDetail.size > 0) {
1506
+ const resolved = new Set();
1507
+ const rows = readChangedRows([...changedForDetail.keys()]);
1508
+ for (const row of rows) {
1509
+ if (!changedForDetail.has(row.messageID))
1510
+ continue;
1511
+ const entry = changedForDetail.get(row.messageID) ?? null;
1512
+ resolved.add(row.messageID);
1513
+ stageChanged(row, entry);
1514
+ read.fingerprints.add(fingerprintOf(row));
1515
+ read.times.add(row.completedAtMs);
1516
+ }
1517
+ for (const messageID of changedForDetail.keys()) {
1518
+ if (!resolved.has(messageID) && state.occurrences.has(messageID)) {
1519
+ removalKeys.add(messageID);
1520
+ detailDirty = true;
1521
+ }
1522
+ }
1523
+ }
1524
+ if (globalRefresh && deltaValid) {
1525
+ // The same-snapshot global delta can certify exact owner discovery;
1526
+ // defer it until changed payloads are known so no-change warm detail
1527
+ // performs no historical payload read.
1528
+ reusedScopes.push({
1529
+ sessionIds: idSet,
1530
+ untilMs: atMs,
1531
+ read,
1532
+ dirty: detailDirty,
1533
+ });
1534
+ }
1535
+ else {
1536
+ discoverExternalOwners(read);
1537
+ }
1538
+ const markers = measureSync("historicalPayloadRead", () => snapshot.readCompactionMarkers({ sessionIDs: ids }));
1539
+ detailCompactionChanges.push([focusId, markers]);
1540
+ detailCoverageChanges.push([focusId, { signature: ids.join("\u0001"), untilMs: atMs }]);
1541
+ }
1542
+ else {
1543
+ // First detail load (or a schema without revision times) needs the full
1544
+ // tree payload because agents and compaction markers are not in the
1545
+ // revision projection.
1546
+ for (const messageID of indexes.sessionMessages(idSet))
1547
+ removalKeys.add(messageID);
1548
+ const rows = readHistoricalRows({ sessionIDs: ids });
1549
+ for (const row of rows) {
1550
+ read.fingerprints.add(fingerprintOf(row));
1551
+ read.times.add(row.completedAtMs);
1552
+ stageBulk(row, scopedWatermarks.get(row.messageID) ?? null);
1553
+ }
1554
+ discoverExternalOwners(read);
1555
+ const markers = measureSync("historicalPayloadRead", () => snapshot.readCompactionMarkers({ sessionIDs: ids }));
1556
+ detailCompactionChanges.push([focusId, markers]);
1557
+ detailCoverageChanges.push([focusId, { signature: ids.join("\u0001"), untilMs: atMs }]);
1558
+ }
1559
+ detailSignatureChanges.push([focusId, signature]);
1560
+ }
1561
+ // A full repair must revisit every cached payload outside this refresh's
1562
+ // authoritative extent/scope reads. Otherwise an unchanged timestamp or
1563
+ // completion token hides a payload edit in an older/evicted scope or a
1564
+ // restart-restored occurrence.
1565
+ if (fullCachedRepairRead) {
1566
+ const unreadIDs = [];
1567
+ for (const key of state.occurrences.keys()) {
1568
+ if (!authoritativePayloadIDs.has(key) && !removalKeys.has(key))
1569
+ unreadIDs.push(key);
1570
+ }
1571
+ if (unreadIDs.length > 0) {
1572
+ const resolved = new Set();
1573
+ const rows = readChangedRows(unreadIDs);
1574
+ for (const row of rows) {
1575
+ resolved.add(row.messageID);
1576
+ stageChanged(row, row.updatedAtMs ?? null);
1577
+ }
1578
+ for (const key of unreadIDs) {
1579
+ if (!resolved.has(key))
1580
+ removalKeys.add(key);
1581
+ }
1582
+ }
1583
+ }
1584
+ // Apply the projected revision delta after every payload/membership read.
1585
+ // Only a full projection may sweep stored rows as deleted.
1586
+ const seenKeys = fullProjection && revisionSnapshot?.completedAtAvailable ? new Set() : undefined;
1587
+ const extentSince = nextExtent?.sinceMs;
1588
+ const extentUntil = nextExtent?.untilMs ?? atMs;
1589
+ if (revisionSnapshot?.completedAtAvailable) {
1590
+ for (const revision of revisionSnapshot.revisions) {
1591
+ const key = revision.messageID;
1592
+ const completed = revisionCompletedAt(revision);
1593
+ const bulkRow = bulkMap.get(key);
1594
+ if (bulkRow)
1595
+ setWatermark(bulkRow, revision.updatedAtMs);
1596
+ const occurrence = replaced ? undefined : state.occurrences.get(key);
1597
+ if (occurrence) {
1598
+ seenKeys?.add(key);
1599
+ if (completed === 0) {
1600
+ // Completion/type reversal is authoritative for this id only.
1601
+ removalKeys.add(key);
1602
+ markReusedScopesDirty(revision.sessionID, 0);
1603
+ continue;
1604
+ }
1605
+ const fingerprint = state.fingerprints[occurrence.fingerprintIndex];
1606
+ // A null/non-numeric source timestamp cannot prove the payload is
1607
+ // unchanged, so re-read it conservatively on every delta.
1608
+ const unknownTimestamp = revisionSnapshot.updatedAtAvailable && revision.updatedAtMs === null;
1609
+ const changed = unknownTimestamp ||
1610
+ !fingerprint ||
1611
+ occurrence.sessionID !== revision.sessionID ||
1612
+ completed !== fingerprint[1] ||
1613
+ (revisionSnapshot.updatedAtAvailable &&
1614
+ revision.updatedAtMs !== occurrence.updatedAtMs);
1615
+ if (changed) {
1616
+ markReusedScopesDirty(revision.sessionID, completed);
1617
+ if (!bulkRow)
1618
+ changedIds.set(key, { updatedAtMs: revision.updatedAtMs });
1619
+ }
1620
+ }
1621
+ else if (!replaced && !bulkRow && completed > 0 && window) {
1622
+ markReusedScopesDirty(revision.sessionID, completed);
1623
+ const inGlobalExtent = completed <= extentUntil && (extentSince === undefined || completed >= extentSince);
1624
+ if (inGlobalExtent || revisionEligibleInReusedScope(revision.sessionID, completed)) {
1625
+ changedIds.set(key, { updatedAtMs: revision.updatedAtMs });
1626
+ }
1627
+ }
1628
+ }
1629
+ if (seenKeys && !replaced) {
1630
+ for (const key of state.occurrences.keys()) {
1631
+ if (!seenKeys.has(key))
1632
+ removalKeys.add(key);
1633
+ }
1634
+ }
1635
+ }
1636
+ if (changedIds.size > 0) {
1637
+ const resolved = new Set();
1638
+ const rows = readChangedRows([...changedIds.keys()]);
1639
+ for (const row of rows) {
1640
+ const entry = changedIds.get(row.messageID);
1641
+ if (!entry)
1642
+ continue;
1643
+ resolved.add(row.messageID);
1644
+ stageChanged(row, entry.updatedAtMs);
1645
+ }
1646
+ for (const key of changedIds.keys()) {
1647
+ if (!resolved.has(key) && state.occurrences.has(key))
1648
+ removalKeys.add(key);
1649
+ }
1650
+ }
1651
+ // Cached project scopes skipped their payload read. If the delta touched
1652
+ // them, recover exact cross-scope fork owners from stored/changed rows
1653
+ // without rereading the project's historical payload.
1654
+ for (const scope of reusedScopes) {
1655
+ if (!scope.dirty)
1656
+ continue;
1657
+ const read = { ids: scope.sessionIds, fingerprints: new Set(), times: new Set() };
1658
+ const seen = new Set();
1659
+ const addRow = (row) => {
1660
+ if (!scope.sessionIds.has(row.sessionID))
1661
+ return;
1662
+ if (row.completedAtMs > scope.untilMs)
1663
+ return;
1664
+ if (scope.sinceMs !== undefined && row.completedAtMs < scope.sinceMs)
1665
+ return;
1666
+ read.fingerprints.add(fingerprintOf(row));
1667
+ read.times.add(row.completedAtMs);
1668
+ };
1669
+ for (const messageID of indexes.sessionMessages(scope.sessionIds)) {
1670
+ seen.add(messageID);
1671
+ if (removalKeys.has(messageID))
1672
+ continue;
1673
+ const changed = changedMap.get(messageID);
1674
+ if (changed) {
1675
+ addRow(changed.row);
1676
+ continue;
1677
+ }
1678
+ const occurrence = state.occurrences.get(messageID);
1679
+ if (!occurrence)
1680
+ continue;
1681
+ const row = rowOf(occurrence);
1682
+ if (row)
1683
+ addRow(row);
1684
+ }
1685
+ for (const [messageID, entry] of changedMap) {
1686
+ if (seen.has(messageID))
1687
+ continue;
1688
+ addRow(entry.row);
1689
+ }
1690
+ discoverExternalOwners(read);
1691
+ }
1692
+ return {
1693
+ identity,
1694
+ sessions,
1695
+ projects,
1696
+ replaced,
1697
+ bulkRows,
1698
+ changedMap,
1699
+ removalKeys,
1700
+ nextExtent,
1701
+ extentChanged,
1702
+ detailSignatures: detailSignatureChanges,
1703
+ detailCompactions: detailCompactionChanges,
1704
+ detailCoverageChanges,
1705
+ projectSignatures: projectSignatureChanges,
1706
+ projectCoverages: projectCoverageChanges,
1707
+ ...(globalRefresh ? { sourceCursorAtMs } : {}),
1708
+ ...(globalRefresh && (cursorBaseline || fullProjection) ? { repairCompletedAtMs: atMs } : {}),
1709
+ };
1710
+ }
1711
+ /** Drops fingerprint tuples no occurrence references (small periodic GC). */
1712
+ function pruneFingerprints() {
1713
+ const used = new Set();
1714
+ for (const occurrence of state.occurrences.values()) {
1715
+ used.add(occurrence.fingerprintIndex);
1716
+ }
1717
+ if (used.size === state.fingerprints.length)
1718
+ return;
1719
+ const remap = new Map();
1720
+ const next = [];
1721
+ const nextIndex = new Map();
1722
+ for (let oldIndex = 0; oldIndex < state.fingerprints.length; oldIndex += 1) {
1723
+ if (!used.has(oldIndex))
1724
+ continue;
1725
+ const tuple = state.fingerprints[oldIndex];
1726
+ if (!tuple)
1727
+ continue;
1728
+ const fingerprint = fingerprintOf(rowFromFingerprint(tuple, { sessionID: "", messageID: "" }));
1729
+ const newIndex = next.length;
1730
+ remap.set(oldIndex, newIndex);
1731
+ next.push(tuple);
1732
+ nextIndex.set(fingerprint, newIndex);
1733
+ }
1734
+ for (const occurrence of state.occurrences.values()) {
1735
+ const mapped = remap.get(occurrence.fingerprintIndex);
1736
+ if (mapped !== undefined)
1737
+ occurrence.fingerprintIndex = mapped;
1738
+ }
1739
+ state.fingerprints = next;
1740
+ state.fingerprintIndex = nextIndex;
1741
+ // Fingerprint buckets are positional: rebuild them once after the remap.
1742
+ indexes.rebuild(state.occurrences.values(), state.sessions);
1743
+ }
1744
+ async function refreshBatch(job) {
1745
+ await ensureIndexLoaded();
1746
+ const atMs = now();
1747
+ const priorSourceCursorAtMs = state.sourceCursorAtMs;
1748
+ const priorLastFullRepairAtMs = state.lastFullRepairAtMs;
1749
+ const priorExtentSinceMs = state.extent?.sinceMs;
1750
+ const priorSourceIdentity = state.sourceIdentity;
1751
+ if (job.globalRange !== undefined)
1752
+ lastGlobalAttemptAtMs = atMs;
1753
+ else
1754
+ lastScopedAttemptAtMs = atMs;
1755
+ // The rare full reconciliation is explicit and clock-driven. It also
1756
+ // repairs the scopes this worker has cached, so unchanged/backdated edits
1757
+ // in scoped data are caught by the same persisted cadence.
1758
+ let effectiveJob = job;
1759
+ const repairDue = job.globalRange !== undefined &&
1760
+ (state.lastFullRepairAtMs === undefined ||
1761
+ atMs - state.lastFullRepairAtMs >= fullRepairIntervalMs ||
1762
+ (state.sourceCursorAtMs !== undefined && atMs < state.sourceCursorAtMs) ||
1763
+ job.repair === true);
1764
+ if (repairDue) {
1765
+ const projectScopes = new Map();
1766
+ for (const scope of job.projectScopes) {
1767
+ projectScopes.set(scope.projectId, widerRange(projectScopes.get(scope.projectId), scope.range));
1768
+ }
1769
+ for (const [projectId, range] of lastProjectScopes) {
1770
+ projectScopes.set(projectId, widerRange(projectScopes.get(projectId), range));
1771
+ }
1772
+ // Persisted project DTO entries are a scoped cache too; repair them when
1773
+ // they survived a restart even though the in-memory scope list is empty.
1774
+ for (const [projectId, range] of state.presentation?.project ?? []) {
1775
+ projectScopes.set(projectId, widerRange(projectScopes.get(projectId), range));
1776
+ }
1777
+ effectiveJob = {
1778
+ ...job,
1779
+ repair: true,
1780
+ projectScopes: [...projectScopes.entries()].map(([projectId, range]) => ({
1781
+ projectId,
1782
+ range,
1783
+ })),
1784
+ detailSessionIds: [...new Set([...job.detailSessionIds, ...lastDetailSessionIds])],
1785
+ };
1786
+ }
1787
+ let result;
1788
+ try {
1789
+ result = await reader.withSnapshot((snapshot) => buildCandidate(snapshot, effectiveJob, atMs));
1790
+ }
1791
+ catch {
1792
+ unavailable = true;
1793
+ return;
1794
+ }
1795
+ if (result.status !== "ok") {
1796
+ unavailable = true;
1797
+ return;
1798
+ }
1799
+ if (result.value === "unavailable") {
1800
+ unavailable = true;
1801
+ return;
1802
+ }
1803
+ const candidate = result.value;
1804
+ samplePeak();
1805
+ const sessionsChanged = metadataChanged(state.sessions, candidate.sessions);
1806
+ const projectsChanged = metadataChanged(state.projects, candidate.projects);
1807
+ const nextSessionIndexSignature = sessionIndexSignature(candidate.sessions);
1808
+ const sessionIndexChanged = candidate.replaced || nextSessionIndexSignature !== lastSessionIndexSignature;
1809
+ // Apply synchronously after the transaction has returned.
1810
+ if (candidate.replaced) {
1811
+ state.occurrences.clear();
1812
+ state.fingerprints = [];
1813
+ state.fingerprintIndex.clear();
1814
+ state.extent = undefined;
1815
+ state.presentation = undefined;
1816
+ state.sourceCursorAtMs = undefined;
1817
+ state.lastFullRepairAtMs = undefined;
1818
+ warmPresentation = undefined;
1819
+ warmSourceIdentity = undefined;
1820
+ warmIdentityVerification = undefined;
1821
+ warmIdentityVerifiedGeneration = -1;
1822
+ projectSignatures.clear();
1823
+ detailSignatures.clear();
1824
+ detailCompactions.clear();
1825
+ detailCoverage.clear();
1826
+ projectCoverage.clear();
1827
+ projectFreshAt.clear();
1828
+ detailFreshAt.clear();
1829
+ indexes.rebuild([], {});
1830
+ lastSessionIndexSignature = "";
1831
+ measureSync("modelUpdate", () => model.clear());
1832
+ modelHydrated = false;
1833
+ modelDirty = true;
1834
+ }
1835
+ const removals = [];
1836
+ const upserts = [];
1837
+ const agentUpserts = [];
1838
+ const agentAffectedSessionIds = new Set();
1839
+ let updatedAtChanged = false;
1840
+ let occurrenceRemoved = false;
1841
+ // The final staged row is the only authoritative payload for a message id:
1842
+ // changedMap wins over a bulk projection, and a retained row cancels any
1843
+ // provisional scope removal. Classify it against the still-committed
1844
+ // occurrence before applying removals so unchanged rows stay no-ops.
1845
+ const changedKeys = new Set(candidate.changedMap.keys());
1846
+ const finalKeys = new Set(changedKeys);
1847
+ for (const row of candidate.bulkRows)
1848
+ finalKeys.add(row.messageID);
1849
+ const applyStagedRow = (row, updatedAtMs, agentProjected) => {
1850
+ const key = row.messageID;
1851
+ const occurrence = state.occurrences.get(key);
1852
+ if (!occurrence) {
1853
+ setRow(row, updatedAtMs, row.agent);
1854
+ upserts.push(row);
1855
+ return;
1856
+ }
1857
+ const oldRow = rowOf(occurrence);
1858
+ const sameContribution = oldRow !== undefined &&
1859
+ occurrence.sessionID === row.sessionID &&
1860
+ fingerprintOf(oldRow) === fingerprintOf(row);
1861
+ if (!sameContribution) {
1862
+ if (oldRow)
1863
+ removals.push(oldRow);
1864
+ setRow(row, updatedAtMs, row.agent);
1865
+ upserts.push(row);
1866
+ return;
1867
+ }
1868
+ if (updatedAtMs !== occurrence.updatedAtMs) {
1869
+ occurrence.updatedAtMs = updatedAtMs;
1870
+ updatedAtChanged = true;
1871
+ }
1872
+ if (agentProjected && row.agent !== occurrence.agent) {
1873
+ if (row.agent === undefined)
1874
+ delete occurrence.agent;
1875
+ else
1876
+ occurrence.agent = row.agent;
1877
+ agentUpserts.push(row);
1878
+ agentAffectedSessionIds.add(row.sessionID);
1879
+ }
1880
+ };
1881
+ for (const entry of candidate.changedMap.values()) {
1882
+ applyStagedRow(entry.row, entry.updatedAtMs, entry.agentProjected ?? true);
1883
+ }
1884
+ for (const row of candidate.bulkRows) {
1885
+ if (changedKeys.has(row.messageID))
1886
+ continue;
1887
+ // Both bulk and changed payloads come from the source reader, which
1888
+ // projects agent; cached synthetic rows never enter this final set.
1889
+ applyStagedRow(row, row[WATERMARK] ?? null, true);
1890
+ }
1891
+ for (const key of candidate.removalKeys) {
1892
+ if (finalKeys.has(key))
1893
+ continue;
1894
+ const occurrence = state.occurrences.get(key);
1895
+ if (!occurrence)
1896
+ continue;
1897
+ const row = rowOf(occurrence);
1898
+ if (row)
1899
+ removals.push(row);
1900
+ state.occurrences.delete(key);
1901
+ indexes.remove(key);
1902
+ occurrenceRemoved = true;
1903
+ }
1904
+ state.sessions = candidate.sessions;
1905
+ state.projects = candidate.projects;
1906
+ if (sessionIndexChanged) {
1907
+ indexes.setSessions(candidate.sessions);
1908
+ lastSessionIndexSignature = nextSessionIndexSignature;
1909
+ }
1910
+ state.sourceIdentity = candidate.identity;
1911
+ if (candidate.extentChanged)
1912
+ state.extent = candidate.nextExtent;
1913
+ // A scoped-only refresh never certifies global freshness or advances the
1914
+ // source cursor; only a successful global candidate may do either.
1915
+ if (effectiveJob.globalRange !== undefined) {
1916
+ state.frontierAtMs = atMs;
1917
+ coverageTrusted = true;
1918
+ sidecarNewerThanIndex = false;
1919
+ }
1920
+ if (candidate.sourceCursorAtMs !== undefined) {
1921
+ if (candidate.sourceCursorAtMs === null)
1922
+ state.sourceCursorAtMs = undefined;
1923
+ else
1924
+ state.sourceCursorAtMs = candidate.sourceCursorAtMs;
1925
+ }
1926
+ if (candidate.repairCompletedAtMs !== undefined) {
1927
+ state.lastFullRepairAtMs = candidate.repairCompletedAtMs;
1928
+ }
1929
+ unavailable = false;
1930
+ for (const [focusId, signature] of candidate.detailSignatures) {
1931
+ if (signature === "") {
1932
+ detailSignatures.delete(focusId);
1933
+ detailCompactions.delete(focusId);
1934
+ detailCoverage.delete(focusId);
1935
+ detailFreshAt.delete(focusId);
1936
+ }
1937
+ else {
1938
+ detailSignatures.set(focusId, signature);
1939
+ detailFreshAt.set(focusId, atMs);
1940
+ }
1941
+ }
1942
+ for (const [focusId, coverage] of candidate.detailCoverageChanges) {
1943
+ detailCoverage.set(focusId, coverage);
1944
+ }
1945
+ const markerChangedFocusIds = new Set();
1946
+ for (const [focusId, markers] of candidate.detailCompactions) {
1947
+ if (metadataChanged(detailCompactions.get(focusId) ?? [], markers)) {
1948
+ markerChangedFocusIds.add(focusId);
1949
+ }
1950
+ detailCompactions.set(focusId, markers);
1951
+ }
1952
+ for (const [projectId, signature] of candidate.projectSignatures) {
1953
+ projectSignatures.set(projectId, signature);
1954
+ projectFreshAt.set(projectId, atMs);
1955
+ }
1956
+ for (const [projectId, coverage] of candidate.projectCoverages) {
1957
+ projectCoverage.set(projectId, coverage);
1958
+ }
1959
+ trimMap(detailSignatures, MAX_SCOPE_BATCH * 4);
1960
+ trimMap(detailCompactions, MAX_SCOPE_BATCH * 4);
1961
+ trimMap(detailCoverage, MAX_SCOPE_BATCH * 4);
1962
+ trimMap(detailFreshAt, MAX_SCOPE_BATCH * 4);
1963
+ trimMap(projectSignatures, MAX_SCOPE_BATCH * 4);
1964
+ trimMap(projectCoverage, MAX_SCOPE_BATCH * 4);
1965
+ trimMap(projectFreshAt, MAX_SCOPE_BATCH * 4);
1966
+ const dataChanged = candidate.replaced ||
1967
+ occurrenceRemoved ||
1968
+ removals.length > 0 ||
1969
+ upserts.length > 0 ||
1970
+ sessionsChanged ||
1971
+ projectsChanged;
1972
+ const cursorChanged = candidate.sourceCursorAtMs !== undefined && state.sourceCursorAtMs !== priorSourceCursorAtMs;
1973
+ const repairChanged = candidate.repairCompletedAtMs !== undefined &&
1974
+ state.lastFullRepairAtMs !== priorLastFullRepairAtMs;
1975
+ const extentSinceChanged = state.extent?.sinceMs !== priorExtentSinceMs;
1976
+ const identityEstablished = priorSourceIdentity === undefined && state.sourceIdentity !== undefined;
1977
+ let sessionCacheInvalidated = false;
1978
+ if (!dataChanged && agentAffectedSessionIds.size > 0) {
1979
+ sessionCacheInvalidated = invalidateCachedSessions(agentAffectedSessionIds);
1980
+ }
1981
+ if (!dataChanged && markerChangedFocusIds.size > 0) {
1982
+ const affectedSessionIds = new Set();
1983
+ for (const focusId of markerChangedFocusIds) {
1984
+ affectedSessionIds.add(focusId);
1985
+ for (const sessionId of indexes.treeIds(focusId))
1986
+ affectedSessionIds.add(sessionId);
1987
+ }
1988
+ if (invalidateCachedSessions(affectedSessionIds))
1989
+ sessionCacheInvalidated = true;
1990
+ }
1991
+ if (dataChanged || candidate.extentChanged || sessionCacheInvalidated) {
1992
+ generation += 1;
1993
+ // Extending empty coverage is not a visible data change; keep the sidecar
1994
+ // and avoid a no-op host notification in that case.
1995
+ if (dataChanged)
1996
+ state.presentation = undefined;
1997
+ }
1998
+ if (modelHydrated) {
1999
+ const modelUpserts = agentUpserts.length > 0 ? [...upserts, ...agentUpserts] : upserts;
2000
+ if (removals.length > 0 || modelUpserts.length > 0 || sessionsChanged || projectsChanged) {
2001
+ measureSync("modelUpdate", () => {
2002
+ if (sessionsChanged || projectsChanged) {
2003
+ model.setMetadata(candidate.sessions, candidate.projects);
2004
+ }
2005
+ if (removals.length > 0 || modelUpserts.length > 0) {
2006
+ model.apply(modelUpserts, removals);
2007
+ }
2008
+ });
2009
+ }
2010
+ }
2011
+ else {
2012
+ modelDirty = true;
2013
+ }
2014
+ if (removals.length > 0 && state.fingerprints.length > state.occurrences.size + 32) {
2015
+ pruneFingerprints();
2016
+ }
2017
+ const globalRefresh = effectiveJob.globalRange !== undefined;
2018
+ const finitePresentationChanged = refreshFinitePresentationWindows(atMs, globalRefresh);
2019
+ if (globalRefresh)
2020
+ precomputeHomeSnapshots(atMs);
2021
+ samplePeak();
2022
+ // A no-change refresh only moves wall freshness (and possibly the extent's
2023
+ // until bound); the compact index already carries the prior cursor/data.
2024
+ // Persist it only when an index-bearing field actually changed.
2025
+ const snapshotNeeded = dataChanged ||
2026
+ updatedAtChanged ||
2027
+ cursorChanged ||
2028
+ repairChanged ||
2029
+ extentSinceChanged ||
2030
+ identityEstablished;
2031
+ if (snapshotNeeded) {
2032
+ compactRevision += 1;
2033
+ queueSnapshotWrite(atMs);
2034
+ }
2035
+ else if (compactDirty) {
2036
+ // A failed/blocked compact write stays dirty across no-change refreshes
2037
+ // until the checkpoint for its revision succeeds.
2038
+ queueSnapshotWrite(atMs);
2039
+ }
2040
+ if (hasUsefulPresentation() || sessionCacheInvalidated || finitePresentationChanged) {
2041
+ queuePresentationWrite(atMs, atMs, sessionCacheInvalidated || finitePresentationChanged);
2042
+ }
2043
+ if ((dataChanged || sessionCacheInvalidated) && !closed && !closing) {
2044
+ try {
2045
+ options.onGeneration?.(generation);
2046
+ }
2047
+ catch {
2048
+ // A host notification failure never breaks the refresh.
2049
+ }
2050
+ }
2051
+ }
2052
+ function takeBatch() {
2053
+ const globalRange = pendingGlobal;
2054
+ pendingGlobal = undefined;
2055
+ const detailSessionIds = [...pendingDetailSessions].slice(0, MAX_SCOPE_BATCH);
2056
+ for (const id of detailSessionIds)
2057
+ pendingDetailSessions.delete(id);
2058
+ const projectScopes = [...pendingProjectScopes.entries()]
2059
+ .slice(0, MAX_SCOPE_BATCH)
2060
+ .map(([projectId, range]) => ({ projectId, range }));
2061
+ for (const scope of projectScopes)
2062
+ pendingProjectScopes.delete(scope.projectId);
2063
+ if (globalRange === undefined && detailSessionIds.length === 0 && projectScopes.length === 0) {
2064
+ if (!pendingMetadataOnly)
2065
+ return undefined;
2066
+ pendingMetadataOnly = false;
2067
+ }
2068
+ return { globalRange, detailSessionIds, projectScopes };
2069
+ }
2070
+ function kickRefresh() {
2071
+ if (!refreshPromise) {
2072
+ refreshPromise = (async () => {
2073
+ await Promise.resolve();
2074
+ for (;;) {
2075
+ const batch = takeBatch();
2076
+ if (!batch) {
2077
+ await Promise.resolve();
2078
+ const retry = takeBatch();
2079
+ if (!retry)
2080
+ break;
2081
+ await refreshBatch(retry);
2082
+ continue;
2083
+ }
2084
+ await refreshBatch(batch);
2085
+ }
2086
+ })().finally(() => {
2087
+ refreshPromise = undefined;
2088
+ if (pendingGlobal !== undefined ||
2089
+ pendingDetailSessions.size > 0 ||
2090
+ pendingProjectScopes.size > 0) {
2091
+ void kickRefresh();
2092
+ }
2093
+ });
2094
+ }
2095
+ return refreshPromise;
2096
+ }
2097
+ function requestRefresh(job) {
2098
+ if (closed)
2099
+ return Promise.reject(new Error("analytics closed"));
2100
+ if (job.globalRange !== undefined) {
2101
+ pendingGlobal = widerRange(pendingGlobal, job.globalRange);
2102
+ lastGlobalRange.value = widerRange(lastGlobalRange.value, job.globalRange);
2103
+ }
2104
+ for (const id of job.detailSessionIds) {
2105
+ pendingDetailSessions.add(id);
2106
+ lastDetailSessionIds.add(id);
2107
+ trimSet(lastDetailSessionIds, MAX_SCOPE_BATCH * 4);
2108
+ }
2109
+ for (const scope of job.projectScopes) {
2110
+ pendingProjectScopes.set(scope.projectId, widerRange(pendingProjectScopes.get(scope.projectId), scope.range));
2111
+ lastProjectScopes.set(scope.projectId, widerRange(lastProjectScopes.get(scope.projectId), scope.range));
2112
+ trimMap(lastProjectScopes, MAX_SCOPE_BATCH * 4);
2113
+ }
2114
+ return kickRefresh();
2115
+ }
2116
+ function requestBackground(job, force = false) {
2117
+ if (closed || closing || (!force && !dueForAttempt(job, now())))
2118
+ return;
2119
+ void requestRefresh(job).catch(() => { });
2120
+ }
2121
+ return {
2122
+ async home(range) {
2123
+ if (!isRangeKey(range))
2124
+ throw new AnalyticsLookupError("bad-request");
2125
+ if (closed)
2126
+ throw new Error("analytics closed");
2127
+ await ensureLoaded();
2128
+ const atMs = now();
2129
+ const window = rangeWindow(range, atMs);
2130
+ lastGlobalRange.value = widerRange(lastGlobalRange.value, range);
2131
+ const cachedEntry = state.presentation?.home[range];
2132
+ const cached = cachedEntry?.usage.timeZone === timeZone ? cachedEntry : undefined;
2133
+ if (cached && (await warmCacheAllowed())) {
2134
+ let current = cached;
2135
+ let expired = false;
2136
+ const certified = homeCertifiedSyncAtMs(range, atMs);
2137
+ if (range !== "lifetime" &&
2138
+ certified !== undefined &&
2139
+ current.usage.window.untilMs < certified) {
2140
+ if (modelHydrated && !modelDirty) {
2141
+ current = deriveHomeSnapshot(range, certified);
2142
+ cacheHome(range, current, atMs);
2143
+ }
2144
+ else {
2145
+ delete state.presentation?.home[range];
2146
+ expired = true;
2147
+ }
2148
+ }
2149
+ if (!expired) {
2150
+ const missingCoverage = !coversSince(window.sinceMs, state.extent);
2151
+ const stale = sidecarNewerThanIndex || isStale(atMs) || missingCoverage;
2152
+ if (stale) {
2153
+ requestBackground({ globalRange: range, detailSessionIds: [], projectScopes: [] }, sidecarNewerThanIndex || missingCoverage);
2154
+ }
2155
+ scheduleThirtyDayExtension(range, atMs);
2156
+ return homeSnapshotWithStaleness(current, range, atMs, stale);
2157
+ }
2158
+ }
2159
+ await ensureIndexLoaded();
2160
+ if (!coverageTrusted || !coversSince(window.sinceMs, state.extent)) {
2161
+ await requestRefresh({ globalRange: range, detailSessionIds: [], projectScopes: [] });
2162
+ if (unavailable &&
2163
+ state.occurrences.size === 0 &&
2164
+ Object.keys(state.sessions).length === 0) {
2165
+ throw new AnalyticsLookupError("unavailable");
2166
+ }
2167
+ }
2168
+ const stale = isStale(now());
2169
+ if (stale) {
2170
+ requestBackground({ globalRange: range, detailSessionIds: [], projectScopes: [] });
2171
+ }
2172
+ ensureModel();
2173
+ const certified = homeCertifiedSyncAtMs(range, atMs);
2174
+ const result = deriveHomeSnapshot(range, range !== "lifetime" && certified !== undefined ? certified : atMs);
2175
+ cacheHome(range, result, atMs);
2176
+ precomputeHomeSnapshots(atMs);
2177
+ scheduleThirtyDayExtension(range, atMs);
2178
+ return homeSnapshotWithStaleness(result, range, atMs, stale);
2179
+ },
2180
+ async project(projectId, range) {
2181
+ if (!isRangeKey(range))
2182
+ throw new AnalyticsLookupError("bad-request");
2183
+ if (closed)
2184
+ throw new Error("analytics closed");
2185
+ if (!projectId)
2186
+ throw new AnalyticsLookupError("bad-request");
2187
+ await ensureLoaded();
2188
+ const atMs = now();
2189
+ lastProjectScopes.set(projectId, widerRange(lastProjectScopes.get(projectId), range));
2190
+ const cached = cachedProject(projectId, range);
2191
+ if (cached && (await warmCacheAllowed())) {
2192
+ let current = cached;
2193
+ let expired = false;
2194
+ const certified = projectCertifiedSyncAtMs(projectId, range, atMs);
2195
+ if (certified !== undefined && current.usage.window.untilMs < certified) {
2196
+ if (modelHydrated && !modelDirty) {
2197
+ current = deriveProjectSnapshot(projectId, range, certified);
2198
+ cacheProject(current, atMs);
2199
+ }
2200
+ else if (range !== "lifetime") {
2201
+ const presentation = state.presentation;
2202
+ if (presentation) {
2203
+ presentation.project = presentation.project.filter(([id, entryRange]) => id !== projectId || entryRange !== range);
2204
+ state.presentation = presentation;
2205
+ }
2206
+ expired = true;
2207
+ }
2208
+ }
2209
+ if (!expired) {
2210
+ const stale = sidecarNewerThanIndex ||
2211
+ certified === undefined ||
2212
+ unavailable ||
2213
+ atMs - certified >= refreshIntervalMs;
2214
+ if (stale) {
2215
+ requestBackground({ detailSessionIds: [], projectScopes: [{ projectId, range }] }, sidecarNewerThanIndex || certified === undefined);
2216
+ }
2217
+ return projectSnapshotWithStaleness(current, stale);
2218
+ }
2219
+ }
2220
+ await ensureIndexLoaded();
2221
+ const certifiedBefore = projectCertifiedSyncAtMs(projectId, range, atMs);
2222
+ const covered = certifiedBefore !== undefined;
2223
+ if (!covered || !stateHasProject(projectId)) {
2224
+ await requestRefresh({
2225
+ detailSessionIds: [],
2226
+ projectScopes: [{ projectId, range }],
2227
+ });
2228
+ }
2229
+ if (!stateHasProject(projectId))
2230
+ throw new AnalyticsLookupError("project-not-found");
2231
+ const certified = projectCertifiedSyncAtMs(projectId, range, atMs);
2232
+ const stale = sidecarNewerThanIndex ||
2233
+ certified === undefined ||
2234
+ unavailable ||
2235
+ atMs - certified >= refreshIntervalMs;
2236
+ if (stale) {
2237
+ requestBackground({ detailSessionIds: [], projectScopes: [{ projectId, range }] }, sidecarNewerThanIndex || certified === undefined);
2238
+ }
2239
+ ensureModel();
2240
+ const result = measureSync("dtoAggregation", () => {
2241
+ const snapshot = model.project(projectId, range, range !== "lifetime" && certified !== undefined ? certified : atMs);
2242
+ return {
2243
+ ...snapshot,
2244
+ stale,
2245
+ usage: { ...snapshot.usage, stale },
2246
+ };
2247
+ });
2248
+ cacheProject(result, atMs);
2249
+ return result;
2250
+ },
2251
+ async session(sessionId) {
2252
+ if (closed)
2253
+ throw new Error("analytics closed");
2254
+ if (!sessionId)
2255
+ throw new AnalyticsLookupError("bad-request");
2256
+ await ensureLoaded();
2257
+ lastDetailSessionIds.add(sessionId);
2258
+ trimSet(lastDetailSessionIds, MAX_SCOPE_BATCH * 4);
2259
+ const cached = cachedSession(sessionId);
2260
+ if (cached && (await warmCacheAllowed())) {
2261
+ touchSessionCache(sessionId, now());
2262
+ requestBackground({ detailSessionIds: [sessionId], projectScopes: [] }, sidecarNewerThanIndex);
2263
+ return cached;
2264
+ }
2265
+ await ensureIndexLoaded();
2266
+ let focus = state.sessions[sessionId];
2267
+ if (!focus) {
2268
+ await requestRefresh({ detailSessionIds: [sessionId], projectScopes: [] });
2269
+ focus = state.sessions[sessionId];
2270
+ if (!focus)
2271
+ throw new AnalyticsLookupError("session-not-found");
2272
+ }
2273
+ const ids = indexes.treeIds(sessionId);
2274
+ const signature = sessionRevisionSignature(state.sessions, ids);
2275
+ const markers = detailCompactions.get(sessionId);
2276
+ if (detailSignatures.get(sessionId) !== signature || markers === undefined) {
2277
+ await requestRefresh({ detailSessionIds: [sessionId], projectScopes: [] });
2278
+ }
2279
+ if (!isDetailFresh(sessionId, now())) {
2280
+ requestBackground({ detailSessionIds: [sessionId], projectScopes: [] });
2281
+ }
2282
+ // Session detail reuses the shared aggregation DTO builder over the
2283
+ // scoped tree plus global owner candidates instead of duplicating it.
2284
+ try {
2285
+ const result = measureSync("dtoAggregation", () => createUsageAnalytics(sessionDataset(sessionId), { timeZone }).session(sessionId));
2286
+ cacheSession(sessionId, result, now());
2287
+ return result;
2288
+ }
2289
+ catch {
2290
+ throw new AnalyticsLookupError("session-not-found");
2291
+ }
2292
+ },
2293
+ async refresh() {
2294
+ if (closed)
2295
+ throw new Error("analytics closed");
2296
+ await ensureIndexLoaded();
2297
+ const atMs = now();
2298
+ const hasInterests = lastGlobalRange.value !== undefined ||
2299
+ lastDetailSessionIds.size > 0 ||
2300
+ lastProjectScopes.size > 0;
2301
+ if (!hasInterests)
2302
+ pendingMetadataOnly = true;
2303
+ await requestRefresh({
2304
+ ...(lastGlobalRange.value === undefined ? {} : { globalRange: lastGlobalRange.value }),
2305
+ detailSessionIds: [...lastDetailSessionIds],
2306
+ projectScopes: [...lastProjectScopes.entries()]
2307
+ .filter(([, range]) => lastGlobalRange.value === undefined ||
2308
+ !coversSince(rangeWindow(range, atMs).sinceMs, state.extent))
2309
+ .map(([projectId, range]) => ({ projectId, range })),
2310
+ });
2311
+ },
2312
+ async stats() {
2313
+ const usage = process.memoryUsage();
2314
+ samplePeak();
2315
+ return {
2316
+ rss: usage.rss,
2317
+ heapTotal: usage.heapTotal,
2318
+ heapUsed: usage.heapUsed,
2319
+ external: usage.external,
2320
+ arrayBuffers: usage.arrayBuffers,
2321
+ peakHeapUsed,
2322
+ peakRss,
2323
+ phases: phaseMetrics(),
2324
+ };
2325
+ },
2326
+ async gc() {
2327
+ const periodic = globalThis.gc;
2328
+ if (typeof periodic === "function") {
2329
+ periodic();
2330
+ return true;
2331
+ }
2332
+ const bun = globalThis.Bun;
2333
+ if (bun?.gc) {
2334
+ bun.gc(true);
2335
+ return true;
2336
+ }
2337
+ return false;
2338
+ },
2339
+ async close() {
2340
+ if (closePromise)
2341
+ return closePromise;
2342
+ if (closed)
2343
+ return;
2344
+ closing = true;
2345
+ closePromise = (async () => {
2346
+ if (lowPriorityTimer !== undefined) {
2347
+ clearTimeout(lowPriorityTimer);
2348
+ lowPriorityTimer = undefined;
2349
+ }
2350
+ pendingGlobal = undefined;
2351
+ pendingMetadataOnly = false;
2352
+ pendingDetailSessions.clear();
2353
+ pendingProjectScopes.clear();
2354
+ const closeAtMs = now();
2355
+ if (compactDirty)
2356
+ queueSnapshotWrite(closeAtMs, true);
2357
+ queueFinalPresentationWrite(closeAtMs, indexLoaded ? closeAtMs : presentationSavedAtMs);
2358
+ const drained = drainAllWrites();
2359
+ await new Promise((resolve) => {
2360
+ const timer = setTimeout(resolve, closeWriteTimeoutMs);
2361
+ void drained.finally(() => {
2362
+ clearTimeout(timer);
2363
+ resolve();
2364
+ });
2365
+ });
2366
+ closed = true;
2367
+ lastDetailSessionIds.clear();
2368
+ lastProjectScopes.clear();
2369
+ detailSignatures.clear();
2370
+ detailCompactions.clear();
2371
+ detailCoverage.clear();
2372
+ projectSignatures.clear();
2373
+ projectCoverage.clear();
2374
+ projectFreshAt.clear();
2375
+ detailFreshAt.clear();
2376
+ })();
2377
+ return await closePromise;
2378
+ },
2379
+ };
2380
+ }
2381
+ //# sourceMappingURL=analytics-engine.js.map