omnicell-router 0.2.0 → 0.7.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 (947) hide show
  1. package/README.md +70 -10
  2. package/README.zh-CN.md +57 -8
  3. package/RELEASING.md +6 -0
  4. package/RELEASING.zh-CN.md +5 -0
  5. package/backend/dist/auth/api-keys.d.ts +14 -2
  6. package/backend/dist/auth/api-keys.js +26 -14
  7. package/backend/dist/auth/model-access.d.ts +27 -10
  8. package/backend/dist/auth/model-access.js +34 -17
  9. package/backend/dist/capture/migrate/engine.d.ts +38 -0
  10. package/backend/dist/capture/migrate/engine.js +307 -0
  11. package/backend/dist/capture/migrate/index.d.ts +18 -0
  12. package/backend/dist/capture/migrate/index.js +18 -0
  13. package/backend/dist/capture/migrate/migrator.d.ts +113 -0
  14. package/backend/dist/capture/migrate/migrator.js +16 -0
  15. package/backend/dist/capture/migrate/registry.d.ts +16 -0
  16. package/backend/dist/capture/migrate/registry.js +19 -0
  17. package/backend/dist/capture/migrate/steps/v1-to-v2.d.ts +86 -0
  18. package/backend/dist/capture/migrate/steps/v1-to-v2.js +396 -0
  19. package/backend/dist/capture/recorder.d.ts +422 -272
  20. package/backend/dist/capture/recorder.js +873 -417
  21. package/backend/dist/capture/turn-boundary.d.ts +17 -0
  22. package/backend/dist/capture/turn-boundary.js +31 -0
  23. package/backend/dist/cli/clients/base.d.ts +158 -23
  24. package/backend/dist/cli/clients/base.js +150 -4
  25. package/backend/dist/cli/clients/claude.d.ts +3 -2
  26. package/backend/dist/cli/clients/claude.js +4 -3
  27. package/backend/dist/cli/clients/codex.d.ts +3 -2
  28. package/backend/dist/cli/clients/codex.js +4 -3
  29. package/backend/dist/cli/clients/core-adapters.d.ts +25 -0
  30. package/backend/dist/cli/clients/core-adapters.js +44 -0
  31. package/backend/dist/cli/clients/dsh.d.ts +5 -3
  32. package/backend/dist/cli/clients/dsh.js +29 -18
  33. package/backend/dist/cli/clients/grok.d.ts +53 -0
  34. package/backend/dist/cli/clients/grok.js +249 -0
  35. package/backend/dist/cli/clients/index.d.ts +28 -19
  36. package/backend/dist/cli/clients/index.js +156 -58
  37. package/backend/dist/cli/clients/kimi.d.ts +75 -0
  38. package/backend/dist/cli/clients/kimi.js +316 -0
  39. package/backend/dist/cli/clients/launcher.d.ts +48 -0
  40. package/backend/dist/cli/clients/launcher.js +41 -0
  41. package/backend/dist/cli/clients/omp.d.ts +43 -0
  42. package/backend/dist/cli/clients/omp.js +537 -0
  43. package/backend/dist/cli/clients/openclaw.d.ts +55 -0
  44. package/backend/dist/cli/clients/openclaw.js +525 -0
  45. package/backend/dist/cli/clients/opencode.d.ts +7 -20
  46. package/backend/dist/cli/clients/opencode.js +32 -159
  47. package/backend/dist/cli/clients/pi.d.ts +7 -21
  48. package/backend/dist/cli/clients/pi.js +87 -229
  49. package/backend/dist/cli/clients/plugin-adapters.d.ts +20 -0
  50. package/backend/dist/cli/clients/plugin-adapters.js +88 -0
  51. package/backend/dist/cli/clients/reserved.d.ts +51 -0
  52. package/backend/dist/cli/clients/reserved.js +53 -0
  53. package/backend/dist/cli/clients/workbuddy.d.ts +31 -0
  54. package/backend/dist/cli/clients/workbuddy.js +259 -0
  55. package/backend/dist/cli/daemon.d.ts +105 -27
  56. package/backend/dist/cli/daemon.js +509 -151
  57. package/backend/dist/cli/index.d.ts +6 -1
  58. package/backend/dist/cli/index.js +238 -22
  59. package/backend/dist/cli/paths.d.ts +86 -0
  60. package/backend/dist/cli/paths.js +269 -0
  61. package/backend/dist/cli/shim.d.ts +47 -1
  62. package/backend/dist/cli/shim.js +180 -13
  63. package/backend/dist/cli/types.d.ts +102 -16
  64. package/backend/dist/cli/types.js +5 -4
  65. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  66. package/backend/dist/compression/caveman.d.ts +2 -16
  67. package/backend/dist/compression/caveman.js +25 -37
  68. package/backend/dist/compression/headroom.d.ts +4 -3
  69. package/backend/dist/compression/headroom.js +2 -2
  70. package/backend/dist/compression/index.d.ts +5 -26
  71. package/backend/dist/compression/index.js +79 -17
  72. package/backend/dist/compression/tool-output.d.ts +2 -20
  73. package/backend/dist/compression/tool-output.js +40 -47
  74. package/backend/dist/config/comments-en.d.ts +17 -0
  75. package/backend/dist/config/comments-en.js +232 -0
  76. package/backend/dist/config/comments-zh.d.ts +10 -0
  77. package/backend/dist/config/comments-zh.js +217 -0
  78. package/backend/dist/config/defaults.d.ts +190 -2
  79. package/backend/dist/config/defaults.js +191 -2
  80. package/backend/dist/config/env-archive.js +77 -38
  81. package/backend/dist/config/env.d.ts +4 -0
  82. package/backend/dist/config/env.js +16 -0
  83. package/backend/dist/config/index.d.ts +48 -12
  84. package/backend/dist/config/index.js +794 -368
  85. package/backend/dist/config/layout.d.ts +29 -0
  86. package/backend/dist/config/layout.js +86 -0
  87. package/backend/dist/config/migrations/v0-to-v1.d.ts +105 -0
  88. package/backend/dist/config/migrations/v0-to-v1.js +78 -0
  89. package/backend/dist/config/migrations/v1-to-v2.d.ts +14 -0
  90. package/backend/dist/config/migrations/v1-to-v2.js +41 -0
  91. package/backend/dist/config/migrations/v2-to-v3.d.ts +34 -0
  92. package/backend/dist/config/migrations/v2-to-v3.js +66 -0
  93. package/backend/dist/config/migrations/v3-to-v4.d.ts +34 -0
  94. package/backend/dist/config/migrations/v3-to-v4.js +61 -0
  95. package/backend/dist/config/runtime.d.ts +13 -0
  96. package/backend/dist/config/runtime.js +26 -0
  97. package/backend/dist/config/schema.d.ts +28 -0
  98. package/backend/dist/config/schema.js +98 -0
  99. package/backend/dist/config/types.d.ts +501 -84
  100. package/backend/dist/forward-proxy/access-log.d.ts +173 -0
  101. package/backend/dist/forward-proxy/access-log.js +657 -0
  102. package/backend/dist/forward-proxy/ca-trust.d.ts +42 -0
  103. package/backend/dist/forward-proxy/ca-trust.js +242 -0
  104. package/backend/dist/forward-proxy/ca.d.ts +66 -2
  105. package/backend/dist/forward-proxy/ca.js +146 -11
  106. package/backend/dist/forward-proxy/caller-context.d.ts +18 -0
  107. package/backend/dist/forward-proxy/caller-context.js +20 -0
  108. package/backend/dist/forward-proxy/egress.d.ts +104 -0
  109. package/backend/dist/forward-proxy/egress.js +280 -0
  110. package/backend/dist/forward-proxy/h2-forward.d.ts +66 -0
  111. package/backend/dist/forward-proxy/h2-forward.js +526 -0
  112. package/backend/dist/forward-proxy/index.d.ts +13 -1
  113. package/backend/dist/forward-proxy/index.js +148 -7
  114. package/backend/dist/forward-proxy/interceptor.d.ts +16 -13
  115. package/backend/dist/forward-proxy/interceptor.js +35 -57
  116. package/backend/dist/forward-proxy/relay.d.ts +21 -1
  117. package/backend/dist/forward-proxy/relay.js +48 -1
  118. package/backend/dist/forward-proxy/rules.d.ts +148 -0
  119. package/backend/dist/forward-proxy/rules.js +280 -0
  120. package/backend/dist/forward-proxy/server.d.ts +102 -9
  121. package/backend/dist/forward-proxy/server.js +1310 -305
  122. package/backend/dist/forward-proxy/sni.d.ts +29 -7
  123. package/backend/dist/forward-proxy/sni.js +109 -47
  124. package/backend/dist/forward-proxy/system-proxy.d.ts +72 -0
  125. package/backend/dist/forward-proxy/system-proxy.js +303 -0
  126. package/backend/dist/forward-proxy/upstream-tls.d.ts +46 -0
  127. package/backend/dist/forward-proxy/upstream-tls.js +105 -0
  128. package/backend/dist/forward-proxy/ws-frames.d.ts +45 -0
  129. package/backend/dist/forward-proxy/ws-frames.js +153 -0
  130. package/backend/dist/harness/common/catalog-registry.d.ts +63 -0
  131. package/backend/dist/harness/common/catalog-registry.js +77 -0
  132. package/backend/dist/harness/common/github.d.ts +6 -0
  133. package/backend/dist/harness/common/github.js +13 -0
  134. package/backend/dist/harness/common/market.d.ts +590 -0
  135. package/backend/dist/harness/common/market.js +1079 -0
  136. package/backend/dist/harness/common/marketplace-rescan-scheduler.d.ts +24 -0
  137. package/backend/dist/harness/common/marketplace-rescan-scheduler.js +62 -0
  138. package/backend/dist/harness/{catalog-npm.d.ts → common/npm-catalog.d.ts} +5 -5
  139. package/backend/dist/harness/{catalog-npm.js → common/npm-catalog.js} +7 -7
  140. package/backend/dist/harness/common/npm-source.d.ts +29 -0
  141. package/backend/dist/harness/common/npm-source.js +121 -0
  142. package/backend/dist/harness/common/pypi-source.d.ts +28 -0
  143. package/backend/dist/harness/common/pypi-source.js +71 -0
  144. package/backend/dist/harness/common/source-views.d.ts +22 -0
  145. package/backend/dist/harness/common/source-views.js +25 -0
  146. package/backend/dist/harness/{stars.d.ts → common/stars.d.ts} +1 -1
  147. package/backend/dist/harness/{stars.js → common/stars.js} +2 -2
  148. package/backend/dist/harness/common/text.d.ts +11 -0
  149. package/backend/dist/harness/common/text.js +18 -0
  150. package/backend/dist/harness/config-file.d.ts +14 -1
  151. package/backend/dist/harness/config-file.js +38 -0
  152. package/backend/dist/harness/db-probe.d.ts +29 -0
  153. package/backend/dist/harness/db-probe.js +270 -0
  154. package/backend/dist/harness/detail.d.ts +10 -1
  155. package/backend/dist/harness/detail.js +144 -7
  156. package/backend/dist/harness/host/adapters/amp.d.ts +19 -0
  157. package/backend/dist/harness/host/adapters/amp.js +21 -0
  158. package/backend/dist/harness/host/adapters/antigravity.d.ts +18 -0
  159. package/backend/dist/harness/host/adapters/antigravity.js +21 -0
  160. package/backend/dist/harness/host/adapters/base.d.ts +225 -0
  161. package/backend/dist/harness/host/adapters/base.js +521 -0
  162. package/backend/dist/harness/host/adapters/claude.d.ts +54 -0
  163. package/backend/dist/harness/host/adapters/claude.js +145 -0
  164. package/backend/dist/harness/host/adapters/cline.d.ts +18 -0
  165. package/backend/dist/harness/host/adapters/cline.js +20 -0
  166. package/backend/dist/harness/host/adapters/codex.d.ts +54 -0
  167. package/backend/dist/harness/host/adapters/codex.js +133 -0
  168. package/backend/dist/harness/host/adapters/cursor.d.ts +18 -0
  169. package/backend/dist/harness/host/adapters/cursor.js +24 -0
  170. package/backend/dist/harness/host/adapters/declarative.d.ts +22 -0
  171. package/backend/dist/harness/host/adapters/declarative.js +38 -0
  172. package/backend/dist/harness/host/adapters/dsh.d.ts +76 -0
  173. package/backend/dist/harness/host/adapters/dsh.js +253 -0
  174. package/backend/dist/harness/host/adapters/factory.d.ts +36 -0
  175. package/backend/dist/harness/host/adapters/factory.js +34 -0
  176. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +17 -0
  177. package/backend/dist/harness/host/adapters/gemini-cli.js +19 -0
  178. package/backend/dist/harness/host/adapters/grok.d.ts +66 -0
  179. package/backend/dist/harness/host/adapters/grok.js +136 -0
  180. package/backend/dist/harness/{adapters → host/adapters}/index.d.ts +18 -5
  181. package/backend/dist/harness/{adapters → host/adapters}/index.js +73 -5
  182. package/backend/dist/harness/host/adapters/kimi.d.ts +30 -0
  183. package/backend/dist/harness/host/adapters/kimi.js +59 -0
  184. package/backend/dist/harness/host/adapters/omp.d.ts +55 -0
  185. package/backend/dist/harness/host/adapters/omp.js +90 -0
  186. package/backend/dist/harness/host/adapters/openclaw.d.ts +54 -0
  187. package/backend/dist/harness/host/adapters/openclaw.js +141 -0
  188. package/backend/dist/harness/host/adapters/opencode.d.ts +24 -0
  189. package/backend/dist/harness/host/adapters/opencode.js +48 -0
  190. package/backend/dist/harness/host/adapters/pi.d.ts +27 -0
  191. package/backend/dist/harness/host/adapters/pi.js +58 -0
  192. package/backend/dist/harness/host/adapters/types.d.ts +395 -0
  193. package/backend/dist/harness/host/adapters/types.js +17 -0
  194. package/backend/dist/harness/host/adapters/universal.d.ts +14 -0
  195. package/backend/dist/harness/host/adapters/universal.js +18 -0
  196. package/backend/dist/harness/host/adapters/windsurf.d.ts +20 -0
  197. package/backend/dist/harness/host/adapters/windsurf.js +22 -0
  198. package/backend/dist/harness/host/adapters/zed.d.ts +12 -0
  199. package/backend/dist/harness/host/adapters/zed.js +14 -0
  200. package/backend/dist/harness/host/claude-mcp-runtime.d.ts +6 -0
  201. package/backend/dist/harness/host/claude-mcp-runtime.js +56 -0
  202. package/backend/dist/harness/{discover.d.ts → host/discover.d.ts} +54 -18
  203. package/backend/dist/harness/{discover.js → host/discover.js} +314 -53
  204. package/backend/dist/harness/{drift.d.ts → host/drift.d.ts} +1 -1
  205. package/backend/dist/harness/{drift.js → host/drift.js} +1 -1
  206. package/backend/dist/harness/host/grok-mcp-runtime.d.ts +6 -0
  207. package/backend/dist/harness/host/grok-mcp-runtime.js +56 -0
  208. package/backend/dist/harness/{hosts.d.ts → host/hosts.d.ts} +3 -3
  209. package/backend/dist/harness/{hosts.js → host/hosts.js} +7 -2
  210. package/backend/dist/harness/host/index.d.ts +10 -0
  211. package/backend/dist/harness/host/index.js +12 -0
  212. package/backend/dist/harness/host/install-log.d.ts +22 -0
  213. package/backend/dist/harness/host/install-log.js +106 -0
  214. package/backend/dist/harness/{install.d.ts → host/install.d.ts} +32 -13
  215. package/backend/dist/harness/{install.js → host/install.js} +133 -50
  216. package/backend/dist/harness/host/inventory.d.ts +30 -0
  217. package/backend/dist/harness/{inventory.js → host/inventory.js} +107 -16
  218. package/backend/dist/harness/host/kimi-mcp-runtime.d.ts +6 -0
  219. package/backend/dist/harness/host/kimi-mcp-runtime.js +84 -0
  220. package/backend/dist/harness/{ledger.d.ts → host/ledger.d.ts} +1 -1
  221. package/backend/dist/harness/{ledger.js → host/ledger.js} +3 -3
  222. package/backend/dist/harness/{maintenance.d.ts → host/maintenance.d.ts} +23 -6
  223. package/backend/dist/harness/{maintenance.js → host/maintenance.js} +355 -63
  224. package/backend/dist/harness/{manifest.d.ts → host/manifest.d.ts} +11 -2
  225. package/backend/dist/harness/{manifest.js → host/manifest.js} +76 -15
  226. package/backend/dist/harness/host/marketplace-sync.d.ts +64 -0
  227. package/backend/dist/harness/host/marketplace-sync.js +231 -0
  228. package/backend/dist/harness/host/mcp-cli.d.ts +44 -0
  229. package/backend/dist/harness/host/mcp-cli.js +545 -0
  230. package/backend/dist/harness/host/mcp-edit.d.ts +89 -0
  231. package/backend/dist/harness/host/mcp-edit.js +342 -0
  232. package/backend/dist/harness/host/mcp-entry.d.ts +100 -0
  233. package/backend/dist/harness/host/mcp-entry.js +435 -0
  234. package/backend/dist/harness/host/mcp-inspector.d.ts +125 -0
  235. package/backend/dist/harness/host/mcp-inspector.js +634 -0
  236. package/backend/dist/harness/host/mcp-registry.d.ts +66 -0
  237. package/backend/dist/harness/host/mcp-registry.js +331 -0
  238. package/backend/dist/harness/host/mcp-runtime.d.ts +19 -0
  239. package/backend/dist/harness/host/mcp-runtime.js +22 -0
  240. package/backend/dist/harness/host/opencode-mcp-runtime.d.ts +7 -0
  241. package/backend/dist/harness/host/opencode-mcp-runtime.js +73 -0
  242. package/backend/dist/harness/{probe.d.ts → host/probe.d.ts} +4 -4
  243. package/backend/dist/harness/{probe.js → host/probe.js} +8 -8
  244. package/backend/dist/harness/{registry.d.ts → host/registry.d.ts} +1 -1
  245. package/backend/dist/harness/host/registry.js +28 -0
  246. package/backend/dist/harness/host/request.d.ts +56 -0
  247. package/backend/dist/harness/host/request.js +1 -0
  248. package/backend/dist/harness/{sources → host/resolvers}/clawhub.d.ts +1 -1
  249. package/backend/dist/harness/{sources → host/resolvers}/clawhub.js +1 -1
  250. package/backend/dist/harness/host/resolvers/git-marketplace.d.ts +16 -0
  251. package/backend/dist/harness/host/resolvers/git-marketplace.js +53 -0
  252. package/backend/dist/harness/{sources → host/resolvers}/github.d.ts +1 -1
  253. package/backend/dist/harness/{sources → host/resolvers}/github.js +2 -2
  254. package/backend/dist/harness/host/resolvers/npm.d.ts +2 -0
  255. package/backend/dist/harness/{sources → host/resolvers}/npm.js +16 -10
  256. package/backend/dist/harness/host/resolvers/pypi.d.ts +2 -0
  257. package/backend/dist/harness/host/resolvers/pypi.js +100 -0
  258. package/backend/dist/harness/host/scopes.d.ts +11 -0
  259. package/backend/dist/harness/host/scopes.js +12 -0
  260. package/backend/dist/harness/host/timeouts.d.ts +8 -0
  261. package/backend/dist/harness/host/timeouts.js +8 -0
  262. package/backend/dist/harness/host/writers/kimi-web.d.ts +70 -0
  263. package/backend/dist/harness/host/writers/kimi-web.js +222 -0
  264. package/backend/dist/harness/host/writers/mcp.d.ts +119 -0
  265. package/backend/dist/harness/host/writers/mcp.js +359 -0
  266. package/backend/dist/harness/host/writers/plugin.d.ts +176 -0
  267. package/backend/dist/harness/host/writers/plugin.js +528 -0
  268. package/backend/dist/harness/{writers → host/writers}/skill.d.ts +3 -3
  269. package/backend/dist/harness/{writers → host/writers}/skill.js +6 -3
  270. package/backend/dist/harness/lang.d.ts +14 -0
  271. package/backend/dist/harness/lang.js +33 -0
  272. package/backend/dist/harness/net.d.ts +33 -0
  273. package/backend/dist/harness/net.js +63 -0
  274. package/backend/dist/harness/plugin/adapters/antigravity.d.ts +11 -0
  275. package/backend/dist/harness/plugin/adapters/antigravity.js +14 -0
  276. package/backend/dist/harness/plugin/adapters/base.d.ts +107 -0
  277. package/backend/dist/harness/plugin/adapters/base.js +454 -0
  278. package/backend/dist/harness/plugin/adapters/claude.d.ts +28 -0
  279. package/backend/dist/harness/plugin/adapters/claude.js +63 -0
  280. package/backend/dist/harness/plugin/adapters/codex.d.ts +13 -0
  281. package/backend/dist/harness/plugin/adapters/codex.js +16 -0
  282. package/backend/dist/harness/plugin/adapters/cursor.d.ts +13 -0
  283. package/backend/dist/harness/plugin/adapters/cursor.js +16 -0
  284. package/backend/dist/harness/plugin/adapters/dsh-plugin-net.d.ts +20 -0
  285. package/backend/dist/harness/plugin/adapters/dsh-plugin-net.js +371 -0
  286. package/backend/dist/harness/plugin/adapters/dsh.d.ts +22 -0
  287. package/backend/dist/harness/plugin/adapters/dsh.js +50 -0
  288. package/backend/dist/harness/plugin/adapters/factory.d.ts +11 -0
  289. package/backend/dist/harness/plugin/adapters/factory.js +19 -0
  290. package/backend/dist/harness/plugin/adapters/gemini.d.ts +12 -0
  291. package/backend/dist/harness/plugin/adapters/gemini.js +22 -0
  292. package/backend/dist/harness/plugin/adapters/grok.d.ts +15 -0
  293. package/backend/dist/harness/plugin/adapters/grok.js +23 -0
  294. package/backend/dist/harness/plugin/adapters/index.d.ts +41 -0
  295. package/backend/dist/harness/plugin/adapters/index.js +143 -0
  296. package/backend/dist/harness/plugin/adapters/kimi.d.ts +6 -0
  297. package/backend/dist/harness/plugin/adapters/kimi.js +35 -0
  298. package/backend/dist/harness/plugin/adapters/omp.d.ts +19 -0
  299. package/backend/dist/harness/plugin/adapters/omp.js +26 -0
  300. package/backend/dist/harness/plugin/adapters/openclaw.d.ts +20 -0
  301. package/backend/dist/harness/plugin/adapters/openclaw.js +36 -0
  302. package/backend/dist/harness/plugin/adapters/pi-dev.d.ts +124 -0
  303. package/backend/dist/harness/plugin/adapters/pi-dev.js +420 -0
  304. package/backend/dist/harness/plugin/adapters/pi-github.d.ts +18 -0
  305. package/backend/dist/harness/plugin/adapters/pi-github.js +27 -0
  306. package/backend/dist/harness/plugin/adapters/universal.d.ts +11 -0
  307. package/backend/dist/harness/plugin/adapters/universal.js +18 -0
  308. package/backend/dist/harness/plugin/builtin.d.ts +13 -0
  309. package/backend/dist/harness/plugin/builtin.js +34 -0
  310. package/backend/dist/harness/plugin/catalog.d.ts +30 -0
  311. package/backend/dist/harness/plugin/catalog.js +200 -0
  312. package/backend/dist/harness/plugin/index.d.ts +9 -0
  313. package/backend/dist/harness/plugin/index.js +9 -0
  314. package/backend/dist/harness/plugin/types.d.ts +164 -0
  315. package/backend/dist/harness/plugin/types.js +1 -0
  316. package/backend/dist/harness/{clawhub.d.ts → skill/clawhub.d.ts} +28 -5
  317. package/backend/dist/harness/{clawhub.js → skill/clawhub.js} +170 -5
  318. package/backend/dist/harness/skill/skills-sh.d.ts +47 -0
  319. package/backend/dist/harness/skill/skills-sh.js +270 -0
  320. package/backend/dist/harness/skill/sources.d.ts +41 -0
  321. package/backend/dist/harness/skill/sources.js +131 -0
  322. package/backend/dist/harness/spi.d.ts +11 -7
  323. package/backend/dist/harness/tcp-reach.d.ts +30 -0
  324. package/backend/dist/harness/tcp-reach.js +61 -0
  325. package/backend/dist/harness/translation.d.ts +31 -13
  326. package/backend/dist/harness/translation.js +212 -62
  327. package/backend/dist/harness/types.d.ts +61 -16
  328. package/backend/dist/index.js +170 -16
  329. package/backend/dist/ir/adapters/anthropic-messages-stream.d.ts +18 -0
  330. package/backend/dist/ir/adapters/anthropic-messages-stream.js +266 -0
  331. package/backend/dist/ir/adapters/anthropic-messages.d.ts +30 -0
  332. package/backend/dist/ir/adapters/anthropic-messages.js +870 -0
  333. package/backend/dist/ir/adapters/google-gemini-stream.d.ts +22 -0
  334. package/backend/dist/ir/adapters/google-gemini-stream.js +246 -0
  335. package/backend/dist/ir/adapters/google-gemini.d.ts +9 -0
  336. package/backend/dist/ir/adapters/google-gemini.js +450 -0
  337. package/backend/dist/ir/adapters/openai-chat-stream.d.ts +41 -0
  338. package/backend/dist/ir/adapters/openai-chat-stream.js +369 -0
  339. package/backend/dist/ir/adapters/openai-chat.d.ts +17 -0
  340. package/backend/dist/ir/adapters/openai-chat.js +670 -0
  341. package/backend/dist/ir/adapters/openai-responses-output.d.ts +50 -0
  342. package/backend/dist/ir/adapters/openai-responses-output.js +353 -0
  343. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +12 -0
  344. package/backend/dist/ir/adapters/openai-responses-stream.js +193 -0
  345. package/backend/dist/ir/adapters/openai-responses.d.ts +14 -0
  346. package/backend/dist/ir/adapters/openai-responses.js +670 -0
  347. package/backend/dist/ir/capabilities.d.ts +41 -0
  348. package/backend/dist/ir/capabilities.js +147 -0
  349. package/backend/dist/ir/errors.d.ts +23 -0
  350. package/backend/dist/ir/errors.js +31 -0
  351. package/backend/dist/ir/index.d.ts +5 -0
  352. package/backend/dist/ir/index.js +5 -0
  353. package/backend/dist/ir/media.d.ts +2 -0
  354. package/backend/dist/ir/media.js +2 -0
  355. package/backend/dist/ir/stream.d.ts +17 -0
  356. package/backend/dist/ir/stream.js +250 -0
  357. package/backend/dist/ir/types.d.ts +523 -0
  358. package/backend/dist/ir/types.js +19 -0
  359. package/backend/dist/ir/validate.d.ts +18 -0
  360. package/backend/dist/ir/validate.js +272 -0
  361. package/backend/dist/metrics/request-cost.d.ts +3 -11
  362. package/backend/dist/metrics/request-cost.js +9 -27
  363. package/backend/dist/observability/failure-events.d.ts +20 -4
  364. package/backend/dist/observability/failure-events.js +9 -1
  365. package/backend/dist/observability/http-exchange.d.ts +75 -27
  366. package/backend/dist/observability/http-exchange.js +136 -39
  367. package/backend/dist/observability/request-identity.d.ts +40 -0
  368. package/backend/dist/observability/request-identity.js +102 -0
  369. package/backend/dist/observability/traffic-live-hidden.d.ts +24 -0
  370. package/backend/dist/observability/traffic-live-hidden.js +82 -0
  371. package/backend/dist/observability/upstream-body-redaction.d.ts +23 -0
  372. package/backend/dist/observability/upstream-body-redaction.js +72 -0
  373. package/backend/dist/observability/upstream-events.d.ts +16 -10
  374. package/backend/dist/observability/upstream-events.js +17 -11
  375. package/backend/dist/opencode/agents.d.ts +10 -2
  376. package/backend/dist/opencode/agents.js +22 -3
  377. package/backend/dist/opencode/catalog/auto-pull.d.ts +35 -1
  378. package/backend/dist/opencode/catalog/auto-pull.js +169 -33
  379. package/backend/dist/opencode/catalog/ocr-store.d.ts +6 -6
  380. package/backend/dist/opencode/catalog/ocr-store.js +2 -2
  381. package/backend/dist/opencode/catalog/overrides-store.d.ts +6 -5
  382. package/backend/dist/opencode/catalog/overrides-store.js +28 -3
  383. package/backend/dist/opencode/catalog/repository.d.ts +4 -0
  384. package/backend/dist/opencode/catalog/repository.js +19 -0
  385. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +4 -0
  386. package/backend/dist/opencode/catalog/sources/models-dev.js +15 -4
  387. package/backend/dist/opencode/catalog/types.d.ts +10 -7
  388. package/backend/dist/opencode/connector.d.ts +2 -2
  389. package/backend/dist/opencode/connector.js +2 -2
  390. package/backend/dist/opencode/credentials/def-materialize.d.ts +0 -5
  391. package/backend/dist/opencode/credentials/def-materialize.js +149 -11
  392. package/backend/dist/opencode/credentials/ocr-store.d.ts +18 -0
  393. package/backend/dist/opencode/credentials/ocr-store.js +88 -7
  394. package/backend/dist/opencode/credentials/opencode-v2-store.d.ts +24 -13
  395. package/backend/dist/opencode/credentials/opencode-v2-store.js +70 -29
  396. package/backend/dist/opencode/credentials/paths.d.ts +8 -0
  397. package/backend/dist/opencode/credentials/paths.js +10 -0
  398. package/backend/dist/opencode/credentials/sync.d.ts +1 -1
  399. package/backend/dist/opencode/credentials/sync.js +4 -4
  400. package/backend/dist/opencode/credentials/types.d.ts +40 -4
  401. package/backend/dist/opencode/probe.d.ts +9 -5
  402. package/backend/dist/opencode/probe.js +68 -15
  403. package/backend/dist/opencode/provider-defs.js +59 -2
  404. package/backend/dist/opencode/provider-package.d.ts +31 -0
  405. package/backend/dist/opencode/provider-package.js +70 -0
  406. package/backend/dist/opencode/user-config.d.ts +11 -17
  407. package/backend/dist/opencode/user-config.js +42 -66
  408. package/backend/dist/pipeline/credential-selection.d.ts +13 -0
  409. package/backend/dist/pipeline/credential-selection.js +29 -1
  410. package/backend/dist/pipeline/directives.d.ts +14 -22
  411. package/backend/dist/pipeline/directives.js +122 -68
  412. package/backend/dist/pipeline/orchestrator.d.ts +42 -7
  413. package/backend/dist/pipeline/orchestrator.js +736 -235
  414. package/backend/dist/pipeline/prompt-optimizer.d.ts +6 -13
  415. package/backend/dist/pipeline/prompt-optimizer.js +9 -52
  416. package/backend/dist/pipeline/streaming-posture.d.ts +29 -0
  417. package/backend/dist/pipeline/streaming-posture.js +27 -0
  418. package/backend/dist/pipeline/tool-pairing.d.ts +10 -0
  419. package/backend/dist/pipeline/tool-pairing.js +90 -0
  420. package/backend/dist/plugins/builtin/model-gateway.d.ts +30 -0
  421. package/backend/dist/plugins/builtin/model-gateway.js +98 -0
  422. package/backend/dist/plugins/config.d.ts +41 -0
  423. package/backend/dist/plugins/config.js +113 -0
  424. package/backend/dist/plugins/gateways.d.ts +98 -0
  425. package/backend/dist/plugins/gateways.js +151 -0
  426. package/backend/dist/plugins/host.d.ts +203 -0
  427. package/backend/dist/plugins/host.js +1310 -0
  428. package/backend/dist/plugins/manifest.d.ts +43 -0
  429. package/backend/dist/plugins/manifest.js +462 -0
  430. package/backend/dist/plugins/pack.d.ts +32 -0
  431. package/backend/dist/plugins/pack.js +222 -0
  432. package/backend/dist/plugins/seed.d.ts +53 -0
  433. package/backend/dist/plugins/seed.js +136 -0
  434. package/backend/dist/plugins/types.d.ts +721 -0
  435. package/backend/dist/plugins/types.js +1 -0
  436. package/backend/dist/projects/store.d.ts +56 -0
  437. package/backend/dist/projects/store.js +194 -0
  438. package/backend/dist/projects/types.d.ts +12 -0
  439. package/backend/dist/projects/types.js +1 -0
  440. package/backend/dist/protocols/chat-compat.d.ts +2 -0
  441. package/backend/dist/protocols/chat-compat.js +137 -0
  442. package/backend/dist/protocols/systemone/convert.d.ts +5 -4
  443. package/backend/dist/protocols/systemone/convert.js +72 -26
  444. package/backend/dist/protocols/systemone/decide.js +128 -51
  445. package/backend/dist/protocols/systemone/native.d.ts +1 -1
  446. package/backend/dist/protocols/systemone/native.js +6 -6
  447. package/backend/dist/providers/anthropic.js +6 -6
  448. package/backend/dist/providers/base.d.ts +8 -47
  449. package/backend/dist/providers/boot-direct.d.ts +20 -2
  450. package/backend/dist/providers/boot-direct.js +72 -23
  451. package/backend/dist/providers/compat/tool-markup-leak.d.ts +41 -0
  452. package/backend/dist/providers/compat/tool-markup-leak.js +57 -0
  453. package/backend/dist/providers/compat/tool-markup-recovery.d.ts +27 -0
  454. package/backend/dist/providers/compat/tool-markup-recovery.js +831 -0
  455. package/backend/dist/providers/dispatch.d.ts +5 -8
  456. package/backend/dist/providers/dispatch.js +18 -12
  457. package/backend/dist/providers/executors/anthropic-messages.d.ts +12 -0
  458. package/backend/dist/providers/executors/anthropic-messages.js +56 -0
  459. package/backend/dist/providers/executors/dispatch.d.ts +14 -0
  460. package/backend/dist/providers/executors/dispatch.js +71 -0
  461. package/backend/dist/providers/executors/google-gemini.d.ts +12 -0
  462. package/backend/dist/providers/executors/google-gemini.js +53 -0
  463. package/backend/dist/providers/executors/http-json.d.ts +19 -0
  464. package/backend/dist/providers/executors/http-json.js +125 -0
  465. package/backend/dist/providers/executors/http-stream.d.ts +53 -0
  466. package/backend/dist/providers/executors/http-stream.js +472 -0
  467. package/backend/dist/providers/executors/openai-chat.d.ts +13 -0
  468. package/backend/dist/providers/executors/openai-chat.js +89 -0
  469. package/backend/dist/providers/executors/openai-responses.d.ts +12 -0
  470. package/backend/dist/providers/executors/openai-responses.js +71 -0
  471. package/backend/dist/providers/executors/plugin-adapter.d.ts +9 -0
  472. package/backend/dist/providers/executors/plugin-adapter.js +31 -0
  473. package/backend/dist/providers/google.js +6 -6
  474. package/backend/dist/providers/openai-compatible.js +13 -13
  475. package/backend/dist/providers/opencode-proxy.js +6 -6
  476. package/backend/dist/providers/plugin-wires.d.ts +34 -0
  477. package/backend/dist/providers/plugin-wires.js +82 -0
  478. package/backend/dist/providers/pool-refresh.d.ts +14 -0
  479. package/backend/dist/providers/pool-refresh.js +13 -0
  480. package/backend/dist/providers/protocol.d.ts +4 -0
  481. package/backend/dist/providers/protocol.js +61 -0
  482. package/backend/dist/providers/provider-takedown.d.ts +59 -0
  483. package/backend/dist/providers/provider-takedown.js +135 -0
  484. package/backend/dist/providers/registry.d.ts +37 -21
  485. package/backend/dist/providers/registry.js +204 -109
  486. package/backend/dist/providers/responses.d.ts +4 -2
  487. package/backend/dist/providers/responses.js +12 -9
  488. package/backend/dist/providers/vocabulary.d.ts +24 -6
  489. package/backend/dist/providers/vocabulary.js +75 -33
  490. package/backend/dist/providers/wire.d.ts +12 -17
  491. package/backend/dist/providers/wire.js +43 -91
  492. package/backend/dist/proxy/manual-node-spec.d.ts +92 -0
  493. package/backend/dist/proxy/manual-node-spec.js +408 -0
  494. package/backend/dist/proxy/mihomo-binary.d.ts +39 -0
  495. package/backend/dist/proxy/mihomo-binary.js +267 -0
  496. package/backend/dist/proxy/mihomo-client.d.ts +94 -0
  497. package/backend/dist/proxy/mihomo-client.js +294 -0
  498. package/backend/dist/proxy/mihomo-config.d.ts +40 -0
  499. package/backend/dist/proxy/mihomo-config.js +152 -0
  500. package/backend/dist/proxy/mihomo-pac.d.ts +26 -0
  501. package/backend/dist/proxy/mihomo-pac.js +60 -0
  502. package/backend/dist/proxy/mihomo-rules-import.d.ts +43 -0
  503. package/backend/dist/proxy/mihomo-rules-import.js +193 -0
  504. package/backend/dist/proxy/mihomo-sidecar.d.ts +65 -0
  505. package/backend/dist/proxy/mihomo-sidecar.js +515 -0
  506. package/backend/dist/quota/engine.d.ts +9 -2
  507. package/backend/dist/quota/engine.js +19 -1
  508. package/backend/dist/quota/prober.d.ts +8 -4
  509. package/backend/dist/quota/prober.js +9 -10
  510. package/backend/dist/ratelimit/rate-limiter.d.ts +119 -6
  511. package/backend/dist/ratelimit/rate-limiter.js +358 -20
  512. package/backend/dist/ratelimit/window-store.d.ts +34 -0
  513. package/backend/dist/ratelimit/window-store.js +70 -0
  514. package/backend/dist/resilience/breaker-state.js +8 -1
  515. package/backend/dist/resilience/circuit-breaker-manager.d.ts +229 -132
  516. package/backend/dist/resilience/circuit-breaker-manager.js +566 -297
  517. package/backend/dist/resilience/circuit-breaker.d.ts +11 -0
  518. package/backend/dist/resilience/circuit-breaker.js +39 -7
  519. package/backend/dist/resilience/error-classifier.d.ts +31 -3
  520. package/backend/dist/resilience/error-classifier.js +159 -31
  521. package/backend/dist/resilience/health-prober.d.ts +21 -4
  522. package/backend/dist/resilience/health-prober.js +100 -18
  523. package/backend/dist/resilience/types.d.ts +56 -9
  524. package/backend/dist/resilience/types.js +1 -1
  525. package/backend/dist/router/index.d.ts +6 -29
  526. package/backend/dist/router/index.js +15 -61
  527. package/backend/dist/router/layer2-decision.d.ts +2 -2
  528. package/backend/dist/router/layer2-decision.js +22 -19
  529. package/backend/dist/router/request-traits.d.ts +4 -11
  530. package/backend/dist/router/request-traits.js +5 -13
  531. package/backend/dist/routes/console.js +1948 -253
  532. package/backend/dist/routes/environments.d.ts +3 -2
  533. package/backend/dist/routes/environments.js +8 -4
  534. package/backend/dist/routes/harness.d.ts +3 -1
  535. package/backend/dist/routes/harness.js +1164 -355
  536. package/backend/dist/routes/mihomo.d.ts +5 -0
  537. package/backend/dist/routes/mihomo.js +882 -0
  538. package/backend/dist/routes/projects.d.ts +2 -0
  539. package/backend/dist/routes/projects.js +90 -0
  540. package/backend/dist/routes/responses.d.ts +20 -1
  541. package/backend/dist/routes/responses.js +65 -3
  542. package/backend/dist/routes/translation.d.ts +9 -0
  543. package/backend/dist/routes/translation.js +155 -0
  544. package/backend/dist/server.d.ts +0 -15
  545. package/backend/dist/server.js +388 -105
  546. package/backend/dist/session/resp-store.d.ts +18 -49
  547. package/backend/dist/session/resp-store.js +114 -122
  548. package/backend/dist/session/session-manager.d.ts +237 -81
  549. package/backend/dist/session/session-manager.js +445 -180
  550. package/backend/dist/session/session-row.d.ts +157 -0
  551. package/backend/dist/session/session-row.js +120 -0
  552. package/backend/dist/surfaces/anthropic.d.ts +1 -15
  553. package/backend/dist/surfaces/anthropic.js +63 -44
  554. package/backend/dist/surfaces/chat-pipeline.d.ts +8 -4
  555. package/backend/dist/surfaces/chat-pipeline.js +102 -35
  556. package/backend/dist/surfaces/chat.d.ts +1 -9
  557. package/backend/dist/surfaces/chat.js +52 -29
  558. package/backend/dist/surfaces/decision-pipeline.js +26 -18
  559. package/backend/dist/surfaces/gateway-chat.d.ts +53 -0
  560. package/backend/dist/surfaces/gateway-chat.js +204 -0
  561. package/backend/dist/surfaces/ocr-headers.d.ts +25 -4
  562. package/backend/dist/surfaces/ocr-headers.js +52 -6
  563. package/backend/dist/surfaces/responses.d.ts +9 -1
  564. package/backend/dist/surfaces/responses.js +141 -141
  565. package/backend/dist/surfaces/systemone-probe.js +1 -1
  566. package/backend/dist/surfaces/systemone.d.ts +1 -1
  567. package/backend/dist/surfaces/systemone.js +1 -1
  568. package/backend/dist/surfaces/table.d.ts +15 -0
  569. package/backend/dist/surfaces/table.js +15 -0
  570. package/backend/dist/surfaces/transport-backpressure.d.ts +46 -0
  571. package/backend/dist/surfaces/transport-backpressure.js +122 -0
  572. package/backend/dist/surfaces/transport-fastify.js +92 -21
  573. package/backend/dist/surfaces/transport-node-http.js +92 -18
  574. package/backend/dist/surfaces/types.d.ts +74 -12
  575. package/backend/dist/trace/persist.d.ts +5 -0
  576. package/backend/dist/trace/persist.js +185 -24
  577. package/backend/dist/trace/tracker.d.ts +153 -16
  578. package/backend/dist/trace/tracker.js +77 -27
  579. package/backend/dist/translation/index.d.ts +151 -0
  580. package/backend/dist/translation/index.js +735 -0
  581. package/backend/dist/types/openai.d.ts +82 -1
  582. package/backend/dist/types/router.d.ts +71 -6
  583. package/backend/dist/types/router.js +33 -1
  584. package/backend/dist/update/check.d.ts +43 -0
  585. package/backend/dist/update/check.js +126 -0
  586. package/backend/dist/utils/chat-sse.d.ts +2 -22
  587. package/backend/dist/utils/chat-sse.js +1 -69
  588. package/backend/dist/utils/chat-stream.d.ts +2 -1
  589. package/backend/dist/utils/client-envelope.d.ts +108 -0
  590. package/backend/dist/utils/client-envelope.js +305 -0
  591. package/backend/dist/utils/event-ring.d.ts +8 -1
  592. package/backend/dist/utils/event-ring.js +13 -5
  593. package/backend/dist/utils/harness-profiles.d.ts +51 -0
  594. package/backend/dist/utils/harness-profiles.js +70 -0
  595. package/backend/dist/utils/percentile.d.ts +16 -0
  596. package/backend/dist/utils/percentile.js +29 -0
  597. package/backend/dist/utils/popularity.d.ts +4 -0
  598. package/backend/dist/utils/popularity.js +33 -0
  599. package/backend/dist/utils/probe-interval.d.ts +12 -0
  600. package/backend/dist/utils/probe-interval.js +16 -0
  601. package/backend/dist/utils/proxy-node.d.ts +13 -0
  602. package/backend/dist/utils/proxy-node.js +471 -0
  603. package/backend/dist/utils/proxy.d.ts +12 -0
  604. package/backend/dist/utils/proxy.js +44 -4
  605. package/backend/dist/utils/run-command.d.ts +42 -0
  606. package/backend/dist/utils/run-command.js +93 -0
  607. package/backend/dist/utils/self-url.d.ts +13 -0
  608. package/backend/dist/utils/self-url.js +90 -2
  609. package/backend/dist/utils/semver.d.ts +22 -0
  610. package/backend/dist/utils/semver.js +75 -0
  611. package/backend/dist/utils/stream-relay.d.ts +35 -0
  612. package/backend/dist/utils/stream-relay.js +1 -0
  613. package/backend/dist/utils/upstream-url-guard.d.ts +15 -0
  614. package/backend/dist/utils/upstream-url-guard.js +107 -0
  615. package/backend/dist/validator/parser.d.ts +2 -5
  616. package/backend/dist/validator/parser.js +12 -16
  617. package/backend/dist/validator/schema-assertion.d.ts +3 -2
  618. package/backend/dist/validator/schema-assertion.js +53 -8
  619. package/bin/ocr.js +2 -2
  620. package/frontend/dist/assets/index-CLvxJjp_.js +1476 -0
  621. package/frontend/dist/assets/index-CQSLGFTV.css +1 -0
  622. package/frontend/dist/assets/qoder.color-tVX5GCcD.svg +5 -0
  623. package/frontend/dist/index.html +2 -2
  624. package/frontend/dist/provider-logos/302ai.svg +7 -0
  625. package/frontend/dist/provider-logos/NOTICE.txt +39 -0
  626. package/frontend/dist/provider-logos/abacus.svg +14 -0
  627. package/frontend/dist/provider-logos/abliteration-ai.svg +6 -0
  628. package/frontend/dist/provider-logos/above.svg +3 -0
  629. package/frontend/dist/provider-logos/agentrouter.svg +4 -0
  630. package/frontend/dist/provider-logos/agnes.svg +1 -0
  631. package/frontend/dist/provider-logos/ai-router.svg +5 -0
  632. package/frontend/dist/provider-logos/ai21.svg +3 -0
  633. package/frontend/dist/provider-logos/aiand.svg +4 -0
  634. package/frontend/dist/provider-logos/aihubmix.svg +3 -0
  635. package/frontend/dist/provider-logos/aimlapi.svg +3 -0
  636. package/frontend/dist/provider-logos/ainetcafe.svg +1 -0
  637. package/frontend/dist/provider-logos/aixy.svg +4 -0
  638. package/frontend/dist/provider-logos/aki-io.svg +8 -0
  639. package/frontend/dist/provider-logos/alibaba-cn.svg +3 -0
  640. package/frontend/dist/provider-logos/alibaba-coding-plan-cn.svg +3 -0
  641. package/frontend/dist/provider-logos/alibaba-coding-plan.svg +3 -0
  642. package/frontend/dist/provider-logos/alibaba-token-plan-cn.svg +1 -0
  643. package/frontend/dist/provider-logos/alibaba-token-plan.svg +1 -0
  644. package/frontend/dist/provider-logos/alibaba.svg +3 -0
  645. package/frontend/dist/provider-logos/amazon-bedrock.svg +3 -0
  646. package/frontend/dist/provider-logos/ambient.svg +3 -0
  647. package/frontend/dist/provider-logos/amd.svg +3 -0
  648. package/frontend/dist/provider-logos/anthropic.svg +3 -0
  649. package/frontend/dist/provider-logos/anyapi.svg +3 -0
  650. package/frontend/dist/provider-logos/arcee.svg +3 -0
  651. package/frontend/dist/provider-logos/atomic-chat.svg +1 -0
  652. package/frontend/dist/provider-logos/auriko.svg +6 -0
  653. package/frontend/dist/provider-logos/azure-cognitive-services.svg +3 -0
  654. package/frontend/dist/provider-logos/azure.svg +3 -0
  655. package/frontend/dist/provider-logos/bailing.svg +3 -0
  656. package/frontend/dist/provider-logos/baseten.svg +3 -0
  657. package/frontend/dist/provider-logos/bee.svg +1 -0
  658. package/frontend/dist/provider-logos/berget.svg +3 -0
  659. package/frontend/dist/provider-logos/blueclaw.svg +3 -0
  660. package/frontend/dist/provider-logos/bothub.svg +33 -0
  661. package/frontend/dist/provider-logos/boundless.svg +12 -0
  662. package/frontend/dist/provider-logos/cerebras.svg +4 -0
  663. package/frontend/dist/provider-logos/chutes.svg +24 -0
  664. package/frontend/dist/provider-logos/clarifai.svg +3 -0
  665. package/frontend/dist/provider-logos/claudinio.svg +19 -0
  666. package/frontend/dist/provider-logos/cline-pass.svg +24 -0
  667. package/frontend/dist/provider-logos/cloudferro-sherlock.svg +5 -0
  668. package/frontend/dist/provider-logos/cloudflare-ai-gateway.svg +4 -0
  669. package/frontend/dist/provider-logos/cloudflare-workers-ai.svg +4 -0
  670. package/frontend/dist/provider-logos/cohere.svg +5 -0
  671. package/frontend/dist/provider-logos/commandcode.svg +11 -0
  672. package/frontend/dist/provider-logos/coralbricks.svg +6 -0
  673. package/frontend/dist/provider-logos/cortecs.svg +24 -0
  674. package/frontend/dist/provider-logos/crossmodel.svg +5 -0
  675. package/frontend/dist/provider-logos/crusoe.svg +23 -0
  676. package/frontend/dist/provider-logos/daoxe.svg +3 -0
  677. package/frontend/dist/provider-logos/databricks.svg +3 -0
  678. package/frontend/dist/provider-logos/deepinfra.svg +4 -0
  679. package/frontend/dist/provider-logos/deepseek.svg +3 -0
  680. package/frontend/dist/provider-logos/digitalocean.svg +6 -0
  681. package/frontend/dist/provider-logos/dinference.svg +1 -0
  682. package/frontend/dist/provider-logos/drun.svg +8 -0
  683. package/frontend/dist/provider-logos/ebcloud.svg +8 -0
  684. package/frontend/dist/provider-logos/echo.svg +7 -0
  685. package/frontend/dist/provider-logos/edenai.svg +8 -0
  686. package/frontend/dist/provider-logos/empiriolabs.svg +1 -0
  687. package/frontend/dist/provider-logos/engy.svg +1 -0
  688. package/frontend/dist/provider-logos/evroc.svg +3 -0
  689. package/frontend/dist/provider-logos/fastrouter.svg +3 -0
  690. package/frontend/dist/provider-logos/fireworks-ai.svg +3 -0
  691. package/frontend/dist/provider-logos/freemodel.svg +3 -0
  692. package/frontend/dist/provider-logos/friendli.svg +3 -0
  693. package/frontend/dist/provider-logos/frogbot.svg +36 -0
  694. package/frontend/dist/provider-logos/github-copilot.svg +3 -0
  695. package/frontend/dist/provider-logos/gitlab.svg +3 -0
  696. package/frontend/dist/provider-logos/gmicloud.svg +24 -0
  697. package/frontend/dist/provider-logos/google-vertex-anthropic.svg +10 -0
  698. package/frontend/dist/provider-logos/google-vertex.svg +10 -0
  699. package/frontend/dist/provider-logos/google.svg +3 -0
  700. package/frontend/dist/provider-logos/greenpt.svg +6 -0
  701. package/frontend/dist/provider-logos/groq.svg +3 -0
  702. package/frontend/dist/provider-logos/helicone.svg +6 -0
  703. package/frontend/dist/provider-logos/hetzner.svg +3 -0
  704. package/frontend/dist/provider-logos/hopper.svg +4 -0
  705. package/frontend/dist/provider-logos/hpc-ai.svg +446 -0
  706. package/frontend/dist/provider-logos/huggingface.svg +3 -0
  707. package/frontend/dist/provider-logos/hyper.svg +20 -0
  708. package/frontend/dist/provider-logos/impossibl.svg +3 -0
  709. package/frontend/dist/provider-logos/inception.svg +14 -0
  710. package/frontend/dist/provider-logos/inceptron.svg +14 -0
  711. package/frontend/dist/provider-logos/inco.svg +3 -0
  712. package/frontend/dist/provider-logos/infer.svg +4 -0
  713. package/frontend/dist/provider-logos/inference.svg +3 -0
  714. package/frontend/dist/provider-logos/inferx.svg +5 -0
  715. package/frontend/dist/provider-logos/infomaniak.svg +3 -0
  716. package/frontend/dist/provider-logos/io-net.svg +5 -0
  717. package/frontend/dist/provider-logos/iteracompute.svg +7 -0
  718. package/frontend/dist/provider-logos/jalapeno.svg +8 -0
  719. package/frontend/dist/provider-logos/jiekou.svg +4 -0
  720. package/frontend/dist/provider-logos/kenari.svg +4 -0
  721. package/frontend/dist/provider-logos/kilo.svg +4 -0
  722. package/frontend/dist/provider-logos/kimi-code-plan-cn.svg +3 -0
  723. package/frontend/dist/provider-logos/kimi-code-plan-global.svg +3 -0
  724. package/frontend/dist/provider-logos/klokintegration.svg +11 -0
  725. package/frontend/dist/provider-logos/kosmik.svg +28 -0
  726. package/frontend/dist/provider-logos/kuae-cloud-coding-plan.svg +3 -0
  727. package/frontend/dist/provider-logos/lilac.svg +6 -0
  728. package/frontend/dist/provider-logos/liquid.svg +1 -0
  729. package/frontend/dist/provider-logos/llmgateway-providers.svg +6 -0
  730. package/frontend/dist/provider-logos/llmgateway.svg +6 -0
  731. package/frontend/dist/provider-logos/llmtech.svg +6 -0
  732. package/frontend/dist/provider-logos/llmtr.svg +12 -0
  733. package/frontend/dist/provider-logos/lmstudio.svg +3 -0
  734. package/frontend/dist/provider-logos/longcat.svg +6 -0
  735. package/frontend/dist/provider-logos/lowrouter.svg +8 -0
  736. package/frontend/dist/provider-logos/lucidquery.svg +3 -0
  737. package/frontend/dist/provider-logos/lynkr.svg +1 -0
  738. package/frontend/dist/provider-logos/meganova.svg +3 -0
  739. package/frontend/dist/provider-logos/melious.svg +3 -0
  740. package/frontend/dist/provider-logos/merge-gateway.svg +4 -0
  741. package/frontend/dist/provider-logos/meta.svg +3 -0
  742. package/frontend/dist/provider-logos/minimax-cn-coding-plan.svg +3 -0
  743. package/frontend/dist/provider-logos/minimax-cn.svg +3 -0
  744. package/frontend/dist/provider-logos/minimax-coding-plan.svg +3 -0
  745. package/frontend/dist/provider-logos/minimax.svg +3 -0
  746. package/frontend/dist/provider-logos/mistral.svg +3 -0
  747. package/frontend/dist/provider-logos/mixlayer.svg +9 -0
  748. package/frontend/dist/provider-logos/moark.svg +3 -0
  749. package/frontend/dist/provider-logos/modal.svg +3 -0
  750. package/frontend/dist/provider-logos/model-oracle-ai.svg +11 -0
  751. package/frontend/dist/provider-logos/modelis.svg +1 -0
  752. package/frontend/dist/provider-logos/modelscope.svg +5 -0
  753. package/frontend/dist/provider-logos/modular.svg +3 -0
  754. package/frontend/dist/provider-logos/moonshotai-cn.svg +3 -0
  755. package/frontend/dist/provider-logos/moonshotai.svg +3 -0
  756. package/frontend/dist/provider-logos/morph.svg +24 -0
  757. package/frontend/dist/provider-logos/munito-eu.svg +1 -0
  758. package/frontend/dist/provider-logos/munito.svg +1 -0
  759. package/frontend/dist/provider-logos/nan.svg +1 -0
  760. package/frontend/dist/provider-logos/nano-gpt.svg +3 -0
  761. package/frontend/dist/provider-logos/nearai.svg +1 -0
  762. package/frontend/dist/provider-logos/nebius.svg +4 -0
  763. package/frontend/dist/provider-logos/neon.svg +3 -0
  764. package/frontend/dist/provider-logos/neosmith.svg +6 -0
  765. package/frontend/dist/provider-logos/neuralwatt.svg +27 -0
  766. package/frontend/dist/provider-logos/nova.svg +3 -0
  767. package/frontend/dist/provider-logos/novita-ai.svg +10 -0
  768. package/frontend/dist/provider-logos/nvidia.svg +3 -0
  769. package/frontend/dist/provider-logos/oci.svg +3 -0
  770. package/frontend/dist/provider-logos/ofox.svg +5 -0
  771. package/frontend/dist/provider-logos/ollama-cloud.svg +7 -0
  772. package/frontend/dist/provider-logos/openai.svg +3 -0
  773. package/frontend/dist/provider-logos/opencode-go.svg +4 -0
  774. package/frontend/dist/provider-logos/opencode.svg +4 -0
  775. package/frontend/dist/provider-logos/openreason.svg +8 -0
  776. package/frontend/dist/provider-logos/openrouter.svg +5 -0
  777. package/frontend/dist/provider-logos/opper.svg +3 -0
  778. package/frontend/dist/provider-logos/orcarouter.svg +2 -0
  779. package/frontend/dist/provider-logos/ovhcloud.svg +3 -0
  780. package/frontend/dist/provider-logos/pareto.svg +5 -0
  781. package/frontend/dist/provider-logos/pendra.svg +10 -0
  782. package/frontend/dist/provider-logos/perplexity-agent.svg +3 -0
  783. package/frontend/dist/provider-logos/perplexity.svg +3 -0
  784. package/frontend/dist/provider-logos/pioneer.svg +3 -0
  785. package/frontend/dist/provider-logos/poe.svg +7 -0
  786. package/frontend/dist/provider-logos/poolside.svg +3 -0
  787. package/frontend/dist/provider-logos/prime.svg +7 -0
  788. package/frontend/dist/provider-logos/privatemode-ai.svg +5 -0
  789. package/frontend/dist/provider-logos/qihang-ai.svg +9 -0
  790. package/frontend/dist/provider-logos/qiniu-ai.svg +7 -0
  791. package/frontend/dist/provider-logos/qvac.svg +6 -0
  792. package/frontend/dist/provider-logos/reflection.svg +3 -0
  793. package/frontend/dist/provider-logos/regolo-ai.svg +46 -0
  794. package/frontend/dist/provider-logos/requesty.svg +24 -0
  795. package/frontend/dist/provider-logos/routing-run.svg +4 -0
  796. package/frontend/dist/provider-logos/runinfra.svg +10 -0
  797. package/frontend/dist/provider-logos/sakana.svg +24 -0
  798. package/frontend/dist/provider-logos/salad-cloud.svg +15 -0
  799. package/frontend/dist/provider-logos/sambanova.svg +26 -0
  800. package/frontend/dist/provider-logos/sap-ai-core.svg +24 -0
  801. package/frontend/dist/provider-logos/sarvam.svg +24 -0
  802. package/frontend/dist/provider-logos/scaleway.svg +5 -0
  803. package/frontend/dist/provider-logos/scnet-token-plan.svg +8 -0
  804. package/frontend/dist/provider-logos/scx-ai.svg +1 -0
  805. package/frontend/dist/provider-logos/sensenova.svg +18 -0
  806. package/frontend/dist/provider-logos/siliconflow-cn.svg +3 -0
  807. package/frontend/dist/provider-logos/siliconflow.svg +3 -0
  808. package/frontend/dist/provider-logos/snowflake-cortex.svg +3 -0
  809. package/frontend/dist/provider-logos/stackit.svg +4 -0
  810. package/frontend/dist/provider-logos/standardcompute.svg +5 -0
  811. package/frontend/dist/provider-logos/stepfun-ai-step-plan.svg +16 -0
  812. package/frontend/dist/provider-logos/stepfun-ai.svg +16 -0
  813. package/frontend/dist/provider-logos/stepfun-step-plan.svg +16 -0
  814. package/frontend/dist/provider-logos/stepfun.svg +16 -0
  815. package/frontend/dist/provider-logos/subconscious.svg +3 -0
  816. package/frontend/dist/provider-logos/submodel.svg +3 -0
  817. package/frontend/dist/provider-logos/synthetic.svg +24 -0
  818. package/frontend/dist/provider-logos/tempr.svg +4 -0
  819. package/frontend/dist/provider-logos/tencent-coding-plan.svg +5 -0
  820. package/frontend/dist/provider-logos/tencent-token-plan.svg +3 -0
  821. package/frontend/dist/provider-logos/tencent-tokenhub.svg +3 -0
  822. package/frontend/dist/provider-logos/tensorx.svg +6 -0
  823. package/frontend/dist/provider-logos/the-grid-ai.svg +14 -0
  824. package/frontend/dist/provider-logos/thinkingmachines.svg +3 -0
  825. package/frontend/dist/provider-logos/tinfoil.svg +3 -0
  826. package/frontend/dist/provider-logos/togetherai.svg +4 -0
  827. package/frontend/dist/provider-logos/tokengo.svg +3 -0
  828. package/frontend/dist/provider-logos/tokenrouter.svg +4 -0
  829. package/frontend/dist/provider-logos/trustedrouter.svg +4 -0
  830. package/frontend/dist/provider-logos/umans-ai-coding-plan.svg +29 -0
  831. package/frontend/dist/provider-logos/umans-ai.svg +29 -0
  832. package/frontend/dist/provider-logos/unorouter.svg +7 -0
  833. package/frontend/dist/provider-logos/upstage.svg +24 -0
  834. package/frontend/dist/provider-logos/vancine.svg +6 -0
  835. package/frontend/dist/provider-logos/venice.svg +4 -0
  836. package/frontend/dist/provider-logos/vercel.svg +3 -0
  837. package/frontend/dist/provider-logos/vispark.svg +3 -0
  838. package/frontend/dist/provider-logos/vivgrid.svg +4 -0
  839. package/frontend/dist/provider-logos/volcengine-coding-plan.svg +1 -0
  840. package/frontend/dist/provider-logos/volcengine.svg +1 -0
  841. package/frontend/dist/provider-logos/vultr.svg +6 -0
  842. package/frontend/dist/provider-logos/wafer.ai.svg +3 -0
  843. package/frontend/dist/provider-logos/wallaby.svg +4 -0
  844. package/frontend/dist/provider-logos/wally.svg +1 -0
  845. package/frontend/dist/provider-logos/wandb.svg +6 -0
  846. package/frontend/dist/provider-logos/watsonx.svg +5 -0
  847. package/frontend/dist/provider-logos/xai.svg +3 -0
  848. package/frontend/dist/provider-logos/xiaomi-token-plan-ams.svg +3 -0
  849. package/frontend/dist/provider-logos/xiaomi-token-plan-cn.svg +3 -0
  850. package/frontend/dist/provider-logos/xiaomi-token-plan-sgp.svg +3 -0
  851. package/frontend/dist/provider-logos/xiaomi.svg +3 -0
  852. package/frontend/dist/provider-logos/xpersona.svg +8 -0
  853. package/frontend/dist/provider-logos/zai-coding-plan.svg +3 -0
  854. package/frontend/dist/provider-logos/zai.svg +3 -0
  855. package/frontend/dist/provider-logos/zeldoc.svg +3 -0
  856. package/frontend/dist/provider-logos/zenifra.svg +4 -0
  857. package/frontend/dist/provider-logos/zenmux.svg +4 -0
  858. package/frontend/dist/provider-logos/zhipuai-coding-plan.svg +3 -0
  859. package/frontend/dist/provider-logos/zhipuai.svg +3 -0
  860. package/package.json +13 -5
  861. package/backend/dist/cli/clients/opencode-proxy.d.ts +0 -16
  862. package/backend/dist/cli/clients/opencode-proxy.js +0 -372
  863. package/backend/dist/forward-proxy/bypass.d.ts +0 -20
  864. package/backend/dist/forward-proxy/bypass.js +0 -28
  865. package/backend/dist/harness/adapters/amp.d.ts +0 -2
  866. package/backend/dist/harness/adapters/amp.js +0 -7
  867. package/backend/dist/harness/adapters/claude.d.ts +0 -2
  868. package/backend/dist/harness/adapters/claude.js +0 -7
  869. package/backend/dist/harness/adapters/cline.d.ts +0 -2
  870. package/backend/dist/harness/adapters/cline.js +0 -6
  871. package/backend/dist/harness/adapters/codex.d.ts +0 -2
  872. package/backend/dist/harness/adapters/codex.js +0 -6
  873. package/backend/dist/harness/adapters/cursor.d.ts +0 -5
  874. package/backend/dist/harness/adapters/cursor.js +0 -10
  875. package/backend/dist/harness/adapters/declarative.d.ts +0 -62
  876. package/backend/dist/harness/adapters/declarative.js +0 -202
  877. package/backend/dist/harness/adapters/dsh.d.ts +0 -5
  878. package/backend/dist/harness/adapters/dsh.js +0 -6
  879. package/backend/dist/harness/adapters/gemini-cli.d.ts +0 -2
  880. package/backend/dist/harness/adapters/gemini-cli.js +0 -7
  881. package/backend/dist/harness/adapters/github-copilot.d.ts +0 -5
  882. package/backend/dist/harness/adapters/github-copilot.js +0 -10
  883. package/backend/dist/harness/adapters/opencode.d.ts +0 -2
  884. package/backend/dist/harness/adapters/opencode.js +0 -55
  885. package/backend/dist/harness/adapters/pi.d.ts +0 -1
  886. package/backend/dist/harness/adapters/pi.js +0 -22
  887. package/backend/dist/harness/adapters/types.d.ts +0 -174
  888. package/backend/dist/harness/adapters/types.js +0 -12
  889. package/backend/dist/harness/adapters/universal.d.ts +0 -6
  890. package/backend/dist/harness/adapters/universal.js +0 -10
  891. package/backend/dist/harness/adapters/windsurf.d.ts +0 -2
  892. package/backend/dist/harness/adapters/windsurf.js +0 -10
  893. package/backend/dist/harness/adapters/zed.d.ts +0 -2
  894. package/backend/dist/harness/adapters/zed.js +0 -6
  895. package/backend/dist/harness/awesome-opencode.d.ts +0 -40
  896. package/backend/dist/harness/awesome-opencode.js +0 -75
  897. package/backend/dist/harness/browse.d.ts +0 -202
  898. package/backend/dist/harness/browse.js +0 -1214
  899. package/backend/dist/harness/inventory.d.ts +0 -10
  900. package/backend/dist/harness/opencode-cafe.d.ts +0 -40
  901. package/backend/dist/harness/opencode-cafe.js +0 -85
  902. package/backend/dist/harness/opencode-ecosystem.d.ts +0 -34
  903. package/backend/dist/harness/opencode-ecosystem.js +0 -246
  904. package/backend/dist/harness/pi-dev.d.ts +0 -81
  905. package/backend/dist/harness/pi-dev.js +0 -187
  906. package/backend/dist/harness/registry.js +0 -26
  907. package/backend/dist/harness/scopes.d.ts +0 -21
  908. package/backend/dist/harness/scopes.js +0 -22
  909. package/backend/dist/harness/skills-sh.d.ts +0 -109
  910. package/backend/dist/harness/skills-sh.js +0 -178
  911. package/backend/dist/harness/smithery.d.ts +0 -64
  912. package/backend/dist/harness/smithery.js +0 -146
  913. package/backend/dist/harness/sources/awesome-opencode.d.ts +0 -11
  914. package/backend/dist/harness/sources/awesome-opencode.js +0 -39
  915. package/backend/dist/harness/sources/mcp-official.d.ts +0 -2
  916. package/backend/dist/harness/sources/mcp-official.js +0 -110
  917. package/backend/dist/harness/sources/npm.d.ts +0 -2
  918. package/backend/dist/harness/sources/opencode-cafe.d.ts +0 -11
  919. package/backend/dist/harness/sources/opencode-cafe.js +0 -41
  920. package/backend/dist/harness/sources/smithery.d.ts +0 -2
  921. package/backend/dist/harness/sources/smithery.js +0 -81
  922. package/backend/dist/harness/writers/extension.d.ts +0 -116
  923. package/backend/dist/harness/writers/extension.js +0 -219
  924. package/backend/dist/harness/writers/mcp.d.ts +0 -72
  925. package/backend/dist/harness/writers/mcp.js +0 -195
  926. package/backend/dist/observability/trace-id.d.ts +0 -40
  927. package/backend/dist/observability/trace-id.js +0 -134
  928. package/frontend/dist/assets/index-1o7qI-KJ.css +0 -1
  929. package/frontend/dist/assets/index-DvXKvNxl.js +0 -962
  930. package/frontend/dist/assets/inter-cyrillic-800-normal-C7MGvYyJ.woff2 +0 -0
  931. package/frontend/dist/assets/inter-cyrillic-800-normal-CCHyn08d.woff +0 -0
  932. package/frontend/dist/assets/inter-cyrillic-ext-800-normal-BZOjs1Xv.woff2 +0 -0
  933. package/frontend/dist/assets/inter-cyrillic-ext-800-normal-Ca-gJeZY.woff +0 -0
  934. package/frontend/dist/assets/inter-greek-800-normal-BU00tryP.woff +0 -0
  935. package/frontend/dist/assets/inter-greek-800-normal-CLIouy3y.woff2 +0 -0
  936. package/frontend/dist/assets/inter-greek-ext-800-normal-B--PVpEC.woff2 +0 -0
  937. package/frontend/dist/assets/inter-greek-ext-800-normal-DUe57HfS.woff +0 -0
  938. package/frontend/dist/assets/inter-latin-800-normal-BYj_oED-.woff2 +0 -0
  939. package/frontend/dist/assets/inter-latin-800-normal-D1mf63XC.woff +0 -0
  940. package/frontend/dist/assets/inter-latin-ext-800-normal-BOMpwxm3.woff +0 -0
  941. package/frontend/dist/assets/inter-latin-ext-800-normal-DZJjya6U.woff2 +0 -0
  942. package/frontend/dist/assets/inter-vietnamese-800-normal-Cm7tD1pz.woff2 +0 -0
  943. package/frontend/dist/assets/inter-vietnamese-800-normal-DDlpr_Ee.woff +0 -0
  944. /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.d.ts +0 -0
  945. /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.js +0 -0
  946. /package/backend/dist/harness/{skill-md.d.ts → skill/skill-md.d.ts} +0 -0
  947. /package/backend/dist/harness/{skill-md.js → skill/skill-md.js} +0 -0
@@ -4,6 +4,57 @@ import path from 'node:path';
4
4
  import { getEnvPaths } from '../config/env.js';
5
5
  import { renameWithRetry } from '../utils/atomic-write.js';
6
6
  import { DEFAULT_MAX_BODY_BYTES } from '../config/defaults.js';
7
+ import { setCaptureSecretRedaction } from '../observability/http-exchange.js';
8
+ import { redactUpstreamBody } from '../observability/upstream-body-redaction.js';
9
+ import { displayPromptText, firstDisplayText } from '../utils/client-envelope.js';
10
+ import { harnessProfileOf } from '../utils/harness-profiles.js';
11
+ import { NO_TURN } from './turn-boundary.js';
12
+ import { migrateArchiveRoot } from './migrate/index.js';
13
+ /**
14
+ * Header a client uses to DECLARE its human prompt (envelope layer 0) instead
15
+ * of relying on the gateway's inference. Display-only, same class as the
16
+ * session title and turn stamp — see utils/client-envelope.ts.
17
+ */
18
+ const PROMPT_HINT_HEADER = 'x-ocr-prompt-hint';
19
+ /**
20
+ * One capture EVENT — a single JSONL line = one phase (`request` or
21
+ * `response`) of one HTTP exchange. ADR-0024 five-layer ladder:
22
+ * `session ⊃ turn ⊃ request ⊃ exchange ⊃ event`.
23
+ *
24
+ * Every line is self-describing: it names its `requestId` (the request
25
+ * layer), `exchangeId` (the exchange layer), `turnIndex` (the turn layer)
26
+ * and `sessionId` (the session layer). No reader reconstructs a boundary
27
+ * from bodies, prompt text or message counts — all of those are written here.
28
+ *
29
+ * `direction` names the LEG, not a vector: `client` = client ↔ gateway,
30
+ * `upstream` = gateway ↔ provider. A response event carries the same
31
+ * `direction` as its request. There is no `gateway` leg.
32
+ */
33
+ export const CAPTURE_SCHEMA = 2;
34
+ /** The last exchange of a leg — the one that served the client. */
35
+ export function primaryExchange(summary, leg) {
36
+ let found;
37
+ for (const ex of summary.exchanges) {
38
+ if (ex.leg === leg && (found === undefined || ex.attempt >= found.attempt))
39
+ found = ex;
40
+ }
41
+ return found;
42
+ }
43
+ /** Convenience projection: one side of the primary exchange of a leg. */
44
+ export function exchangeEvent(summary, leg, phase) {
45
+ return primaryExchange(summary, leg)?.[phase];
46
+ }
47
+ const newRequestIndexState = () => ({
48
+ requests: 0,
49
+ turns: [],
50
+ byKey: new Map(),
51
+ });
52
+ /** Targeted line scans: the archive is compact JSON written by this recorder. */
53
+ const RE_CAPTURE_SESSION_ID = /"sessionId":"((?:[^"\\]|\\.)*)"/;
54
+ const RE_CAPTURE_TS = /"ts":(\d+)/;
55
+ const RE_CAPTURE_PROMPT_SUMMARY = /"promptSummary":("(?:[^"\\]|\\.)*")/;
56
+ const RE_CAPTURE_TURN_INDEX = /"turnIndex":(\d+)/;
57
+ const RE_CAPTURE_IS_PROMPT_START = /"isPromptStart":true/;
7
58
  const DATE_DIR_RE = /^\d{4}-\d{2}-\d{2}$/;
8
59
  // Session ids that are already filesystem-safe are kept verbatim for
9
60
  // browsability; anything else (path traversal, separators, excess length)
@@ -24,6 +75,14 @@ const TRUNCATION_SUFFIX = '...[TRUNCATED]';
24
75
  // listing in this class filters on isFile()/.jsonl, so it never surfaces as
25
76
  // a "session".
26
77
  const MEDIA_SUBDIR = 'media';
78
+ // Startup migration does NOT wait out the quiet window: at boot this process
79
+ // holds no append handle yet, and every rewrite re-checks the file right
80
+ // before the swap (see migrate/engine.ts), so a request that lands mid-pass
81
+ // makes the rewrite back off instead of losing bytes. An upgrading
82
+ // installation therefore sees its history immediately, not up to an hour
83
+ // later. The hourly sweep keeps the quiet window — by then the recorder IS
84
+ // appending, and a recently written shard is simply retried next hour.
85
+ const BOOT_MIGRATION_HOT_MS = 0;
27
86
  // Reader-side shape of the stored file name: `<64hex>.<ext>` — the route
28
87
  // accepts the bare hash (16–64 hex) and prefix-matches it against this.
29
88
  const MEDIA_FILE_RE = /^[0-9a-f]{16,64}\.[a-z0-9]{1,8}$/;
@@ -75,6 +134,11 @@ function humanBytes(n) {
75
134
  // archive read is in flight.
76
135
  const READ_WINDOW_FLOOR_BYTES = 8 * 1024 * 1024;
77
136
  const READ_WINDOW_CEIL_BYTES = 48 * 1024 * 1024;
137
+ /** Hard ceiling for the GROWING read window (page-driven growth, not the
138
+ * default window). Growth is requested by the console's pager, so it must
139
+ * stay memory-bounded regardless of how deep a click reaches: past this the
140
+ * response clamps `page`/`totalPages` and the pager self-heals. */
141
+ const READ_WINDOW_GROWTH_CEIL_BYTES = 3 * READ_WINDOW_CEIL_BYTES;
78
142
  /**
79
143
  * Last "completion_tokens" / "output_tokens" occurrence in a response body —
80
144
  * streaming SSE repeats it and the final chunk carries the cumulative total
@@ -101,7 +165,7 @@ const deriveCompletionTokens = (ev) => {
101
165
  /**
102
166
  * bodies='none' strips the wire bodies (lines, status, headers kept) —
103
167
  * metadata-first reads return KB instead of MB so the console paints the
104
- * turn list immediately; full bodies arrive on demand via readTurn (per
168
+ * turn list immediately; full bodies arrive on demand via readRequest (per
105
169
  * turn) or a bodies=full re-read (conversation lens).
106
170
  */
107
171
  const stripBodies = (events) => {
@@ -115,6 +179,27 @@ const stripBodies = (events) => {
115
179
  }
116
180
  }
117
181
  };
182
+ /**
183
+ * `bodies='chat'` retention: the conversation replay needs each ROUND
184
+ * OPENER's client-request body (it carries the full history up to that
185
+ * prompt) plus every response body; the multi-MB continuation request bodies
186
+ * repeat the same history and only bloat memory. Upstream request bodies are
187
+ * byte-identical to their client counterpart, so they always go.
188
+ */
189
+ const stripBodiesForChat = (events, keepRequests) => {
190
+ for (const ev of events) {
191
+ const wire = ev.wire;
192
+ if (!wire)
193
+ continue;
194
+ if (ev.phase === 'response') {
195
+ delete wire.requestBody;
196
+ continue;
197
+ }
198
+ delete wire.responseBody;
199
+ if (!(ev.direction === 'client' && keepRequests.has(ev)))
200
+ delete wire.requestBody;
201
+ }
202
+ };
118
203
  /**
119
204
  * Full request/response capture recorder (opt-in audit log).
120
205
  *
@@ -134,10 +219,16 @@ export class CaptureRecorder {
134
219
  maxBodyBytes;
135
220
  maxSessionBytes;
136
221
  storeMedia;
137
- // Per-session seal bookkeeping: cached byte size per archive path + which
138
- // archives already got their terminal `archive-overflow` line.
222
+ redactSecrets;
223
+ // Per-session SIZE-CAP bookkeeping: cached byte size per archive path, plus
224
+ // which archives already got their terminal `archive-overflow` line. This
225
+ // "seal" caps one runaway session; it has nothing to do with schema
226
+ // migration, which has no seal — a migrated archive always stays in the live
227
+ // root and stays readable.
139
228
  fileBytesCache = new Map();
140
229
  sealedFiles = new Set();
230
+ /** Whole-archive request/round summaries keyed by file stat signature. */
231
+ summaryCache = new Map();
141
232
  rootDir;
142
233
  sweepTimer;
143
234
  constructor(config) {
@@ -150,10 +241,16 @@ export class CaptureRecorder {
150
241
  this.maxBodyBytes = config?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
151
242
  this.maxSessionBytes = (config?.maxSessionMB ?? 512) * 1024 * 1024;
152
243
  this.storeMedia = config?.storeMedia ?? true;
244
+ // redactSecrets:false is no longer honored — live credentials must never
245
+ // land in the archive (S-06). The config key remains for forward-compat
246
+ // reads but is forced on.
247
+ setCaptureSecretRedaction(true);
248
+ this.redactSecrets = true;
153
249
  this.rootDir = path.resolve(config?.dir || getEnvPaths().captureDir);
154
250
  if (this.enabled) {
155
251
  this.ensureDir(this.rootDir);
156
252
  this.sweep();
253
+ void this.migrateArchives(BOOT_MIGRATION_HOT_MS);
157
254
  this.startSweepTimer();
158
255
  }
159
256
  }
@@ -180,6 +277,8 @@ export class CaptureRecorder {
180
277
  this.maxBodyBytes = cfg?.maxBodyBytes ?? this.maxBodyBytes;
181
278
  this.maxSessionBytes = (cfg?.maxSessionMB ?? this.maxSessionBytes / (1024 * 1024)) * 1024 * 1024;
182
279
  this.storeMedia = cfg?.storeMedia ?? this.storeMedia;
280
+ setCaptureSecretRedaction(true);
281
+ this.redactSecrets = true;
183
282
  const newDir = path.resolve(cfg?.dir || this.rootDir);
184
283
  if (newDir !== this.rootDir) {
185
284
  this.rootDir = newDir;
@@ -191,6 +290,7 @@ export class CaptureRecorder {
191
290
  this.ensureDir(this.rootDir);
192
291
  this.startSweepTimer();
193
292
  this.sweep();
293
+ void this.migrateArchives(BOOT_MIGRATION_HOT_MS);
194
294
  }
195
295
  else {
196
296
  this.stopSweepTimer();
@@ -200,7 +300,10 @@ export class CaptureRecorder {
200
300
  startSweepTimer() {
201
301
  if (this.sweepTimer)
202
302
  return;
203
- this.sweepTimer = setInterval(() => this.sweep(), 3_600_000);
303
+ this.sweepTimer = setInterval(() => {
304
+ this.sweep();
305
+ void this.migrateArchives();
306
+ }, 3_600_000);
204
307
  this.sweepTimer.unref?.();
205
308
  }
206
309
  stopSweepTimer() {
@@ -210,60 +313,19 @@ export class CaptureRecorder {
210
313
  }
211
314
  }
212
315
  /**
213
- * @deprecated Use `recordEvent()` instead. The turn-centric `CaptureRecord`
214
- * model has been superseded by `HttpExchangeEvent` (one event per HTTP
215
- * side, request and response are independent). `record()` is kept only
216
- * for back-compat with already-written archive files; the orchestrator
217
- * no longer calls it. New code MUST use `recordEvent()`.
218
- */
219
- async record(entry) {
220
- if (!this.enabled)
221
- return;
222
- const request = this.truncateField(entry.request);
223
- const upstreamRequest = this.truncateField(entry.upstreamRequest);
224
- const upstreamError = this.truncateField(entry.upstreamError);
225
- const response = this.truncateField(entry.response);
226
- // upstreamHttp is a fixed-shape HTTP summary (URL/method/status/headers/
227
- // ttfb/duration/attemptIndex/wireKind) — bounded by header whitelist, no
228
- // body payload, so it never approaches maxBodyBytes. Pass through.
229
- const record = {
230
- ...entry,
231
- id: `cap_${crypto.randomUUID().replace(/-/g, '').slice(0, 16)}`,
232
- ts: Date.now(),
233
- request: request.value,
234
- upstreamRequest: upstreamRequest.value,
235
- upstreamError: upstreamError.value,
236
- response: response.value,
237
- truncated: request.truncated || upstreamRequest.truncated || upstreamError.truncated || response.truncated || undefined,
238
- };
239
- const file = path.join(this.rootDir, CaptureRecorder.localDateDir(new Date(record.ts)), CaptureRecorder.sessionFileName(record.sessionId));
240
- try {
241
- this.ensureDir(path.dirname(file));
242
- await fs.promises.appendFile(file, JSON.stringify(record) + '\n', 'utf8');
243
- }
244
- catch (err) {
245
- console.warn(`[Capture] Failed to append to ${file}: ${err.message}`);
246
- }
247
- }
248
- /**
249
- * Append one HTTP-exchange event to the event stream. Each HTTP exchange
250
- * emits TWO events (one request, one response) sharing the same
251
- * `spanId`. One inference turn typically produces 2-4 events
252
- * sharing the same `traceId`. Synchronous callers (handler scope,
253
- * provider scope) can fire this the moment the wire side is known —
254
- * there is no longer a "wait for the response" barrier before the
255
- * request side is recorded.
256
- *
257
- * Same fail-open contract as `record()`: a capture failure must never
258
- * break the inference hot path.
316
+ * `schema`, `turnIndex`, `isPromptStart`, `turnDecision` and `attempt` are
317
+ * stamped HERE — the single write point — so every archive line is fully
318
+ * self-describing. Production emitters pass an explicit `TurnIdentity`
319
+ * allocated at the admission gate; emitters that have none (standalone
320
+ * surfaces, tests) get `NO_TURN`, the first-class "no prompt" value.
321
+ * Readers never fill these in.
259
322
  */
260
323
  async recordEvent(event) {
261
324
  if (!this.enabled)
262
325
  return;
263
326
  const ts = Date.now();
264
- // Bound wire bodies at the same maxBodyBytes cap as the legacy turn
265
- // schema — a 10MB request body must not blow past the per-line JSONL
266
- // budget and starve retention. `WireBody` is `string | { hex: string }`
327
+ // Bound wire bodies at the maxBodyBytes cap — a 10MB request body must
328
+ // not blow past the per-line JSONL budget and starve retention. `WireBody` is `string | { hex: string }`
267
329
  // — we count bytes in BOTH forms (UTF-8 string length, hex bytes via
268
330
  // halving). Truncation yields the same shape so the field type stays
269
331
  // stable for readers.
@@ -296,22 +358,42 @@ export class CaptureRecorder {
296
358
  // bodies only — responses are one-shot per turn, and a generated-image
297
359
  // payload in one IS the captured content.
298
360
  const dateDir = CaptureRecorder.localDateDir(new Date(ts));
299
- const truncatedReq = truncateBody(this.scrubMedia(event.wire?.requestBody, dateDir));
300
- const truncatedResp = truncateBody(event.wire?.responseBody);
361
+ // Body-side secret scrub (Bearer / known patterns) — header deny-list does
362
+ // not cover echoed keys inside JSON error bodies or client messages.
363
+ const scrubBody = (body) => {
364
+ if (typeof body !== 'string' || !body)
365
+ return body;
366
+ return redactUpstreamBody(body, { maxChars: 0, collapseWhitespace: false });
367
+ };
368
+ const truncatedReq = truncateBody(this.scrubMedia(scrubBody(event.wire?.requestBody), dateDir));
369
+ const truncatedResp = truncateBody(scrubBody(event.wire?.responseBody));
301
370
  const truncated = truncatedReq.truncated || truncatedResp.truncated || undefined;
302
371
  const wire = {
303
372
  ...event.wire,
304
373
  requestBody: truncatedReq.value ?? '',
305
374
  responseBody: truncatedResp.value ?? '',
306
375
  };
376
+ // A prompt-start client request gets a DISPLAY-ONLY prompt stamp. An
377
+ // emitter that supplied one (e.g. a harness surface with a non-chat body)
378
+ // keeps its own text; the stamp is never a boundary signal. The harness
379
+ // vocabulary is scoped from THIS wire dump's UA — a Claude Code turn whose
380
+ // `<system-reminder>` rides beside the human text is stamped with the
381
+ // human text, while an identical tag from another client stays verbatim.
382
+ const stampedPrompt = event.direction === 'client' &&
383
+ event.phase === 'request' &&
384
+ event.isPromptStart &&
385
+ event.promptSummary === undefined
386
+ ? CaptureRecorder.turnPromptStamp(truncatedReq.value ?? '', 120, CaptureRecorder.hintsOfHeaders(event.wire.requestHeaders))
387
+ : undefined;
307
388
  const full = {
389
+ ...NO_TURN,
308
390
  ...event,
391
+ schema: CAPTURE_SCHEMA,
392
+ attempt: event.attempt ?? 1,
309
393
  id: `evt_${crypto.randomUUID().replace(/-/g, '').slice(0, 16)}`,
310
394
  ts,
311
395
  wire,
312
- ...(event.direction === 'client' && event.phase === 'request'
313
- ? { promptSummary: CaptureRecorder.extractTurnPrompt(truncatedReq.value ?? '') }
314
- : {}),
396
+ ...(stampedPrompt !== undefined ? { promptSummary: stampedPrompt } : {}),
315
397
  ...(truncated ? { truncated: true } : {}),
316
398
  };
317
399
  const file = path.join(this.rootDir, CaptureRecorder.localDateDir(new Date(ts)), CaptureRecorder.sessionFileName(full.sessionId));
@@ -341,7 +423,7 @@ export class CaptureRecorder {
341
423
  const seal = JSON.stringify({
342
424
  eventType: 'archive-overflow',
343
425
  sessionId: full.sessionId,
344
- traceId: full.traceId,
426
+ requestId: full.requestId,
345
427
  ts,
346
428
  bytes,
347
429
  maxSessionMB: Math.round(this.maxSessionBytes / (1024 * 1024)),
@@ -381,6 +463,7 @@ export class CaptureRecorder {
381
463
  maxBodyBytes: this.maxBodyBytes,
382
464
  maxSessionMB: Math.round(this.maxSessionBytes / (1024 * 1024)),
383
465
  storeMedia: this.storeMedia,
466
+ redactSecrets: this.redactSecrets,
384
467
  totalBytes: dates.reduce((sum, d) => sum + d.bytes, 0),
385
468
  dateCount: dates.length,
386
469
  };
@@ -488,101 +571,72 @@ export class CaptureRecorder {
488
571
  try {
489
572
  const filePath = path.join(dir, f.name);
490
573
  const st = fs.statSync(filePath);
491
- // Per-session outcome tally for the console badges. Two line formats
492
- // share the archive:
493
- // - legacy cap_ turn records (one line per turn): counted directly.
494
- // - evt_ http-exchange events (2-4 lines per turn): collected and
495
- // grouped via groupEventsIntoTurns, so a turn counts once no
496
- // matter how many of its events carry an error status.
497
- let turns = 0;
574
+ // Per-REQUEST outcome tally for the console badges. Every line is a
575
+ // schema-2 http-exchange event; events are grouped by requestId so a
576
+ // failover with 6 legs still counts as one request and one outcome.
577
+ let requests = 0;
498
578
  let failed = 0;
499
579
  let lastStatus;
500
580
  let preview;
501
581
  let protocol;
502
- // Key attribution: collect the DISTINCT identities seen in the
503
- // archive (write order). Single-key sessions → one entry; rotated /
504
- // mixed-key sessions → the full set so per-app retrieval matches
505
- // every app that contributed. Legacy lines carry no apiKey.
582
+ // DISTINCT api-key identities seen in this archive, in write order.
506
583
  const seenKeys = new Map();
507
584
  let conversationKey;
508
585
  const streamEvents = [];
509
586
  try {
510
587
  // Ceiling: the tally needs EVERY line, so this is an uncapped
511
588
  // synchronous read bounded only by the per-session seal
512
- // (maxSessionMB, default 512 MB) — a date full of sealed-maximum
513
- // sessions can stall the event loop for seconds per listing.
514
- // Accepted: admin-console surface, operator-initiated, and the seal
515
- // is what keeps the worst case finite. Upgrade path: stream the file
516
- // in chunks (createReadStream + line splitter) or keep an on-disk
517
- // per-file turn counter.
589
+ // (maxSessionMB, default 512 MB). Admin-console surface,
590
+ // operator-initiated.
518
591
  const content = fs.readFileSync(filePath, 'utf8');
519
592
  for (const line of content.split(/\r?\n/)) {
520
593
  if (!line.trim())
521
594
  continue;
595
+ let rec;
522
596
  try {
523
- const rec = JSON.parse(line);
524
- // Terminal seal marker — metadata, never a turn. Skipping it here
525
- // keeps the legacy else-branch below from counting it as a
526
- // phantom turn (the same bug class as event lines vs turns).
527
- if (rec.eventType === 'archive-overflow')
528
- continue;
529
- if (rec.eventType === 'http-exchange') {
530
- streamEvents.push(rec);
531
- if (rec.apiKey && rec.apiKey.id && !seenKeys.has(String(rec.apiKey.id))) {
532
- seenKeys.set(String(rec.apiKey.id), {
533
- id: String(rec.apiKey.id),
534
- name: String(rec.apiKey.name ?? ''),
535
- });
536
- }
537
- if (conversationKey === undefined && typeof rec.conversationKey === 'string' && rec.conversationKey) {
538
- conversationKey = rec.conversationKey;
539
- }
540
- // First client request body = the session's opening turn.
541
- // extractSessionPreview also accepts the raw string form
542
- // (it strips a "...[TRUNCATED]" tail and repairs the cut
543
- // JSON), so pass the wire body through unparsed.
544
- if (preview === undefined &&
545
- rec.direction === 'client' &&
546
- rec.phase === 'request' &&
547
- rec.wire?.requestBody !== undefined) {
548
- preview = CaptureRecorder.extractSessionPreview(rec.wire.requestBody);
549
- }
550
- // Inbound-protocol badge: the FIRST client request's request
551
- // line wins; a req-less emission (empty line) keeps looking.
552
- if (protocol === undefined && rec.direction === 'client' && rec.phase === 'request') {
553
- protocol = CaptureRecorder.protocolFromRequestLine(rec.wire?.requestLine);
554
- }
555
- }
556
- else {
557
- turns++;
558
- const status = rec.status;
559
- if (status === 'error')
560
- failed++;
561
- if (status === 'ok' || status === 'error')
562
- lastStatus = status;
563
- // Files are append-only, so the first line with a request body
564
- // is the session's opening turn — capture its user text once.
565
- if (preview === undefined && rec.request !== undefined) {
566
- preview = CaptureRecorder.extractSessionPreview(rec.request);
567
- }
568
- }
597
+ rec = JSON.parse(line);
569
598
  }
570
599
  catch {
571
- // Corrupt line — counts as a turn but not a failure.
572
- turns++;
600
+ continue; // corrupt line — not a request
601
+ }
602
+ if (rec.eventType === 'archive-overflow')
603
+ continue;
604
+ if (rec.eventType !== 'http-exchange')
605
+ continue;
606
+ const ev = CaptureRecorder.parseArchivedEvent(rec);
607
+ if (ev)
608
+ streamEvents.push(ev);
609
+ if (rec.apiKey && rec.apiKey.id && !seenKeys.has(String(rec.apiKey.id))) {
610
+ const k = rec.apiKey;
611
+ seenKeys.set(String(k.id), { id: String(k.id), name: String(k.name ?? '') });
612
+ }
613
+ if (conversationKey === undefined && typeof rec.conversationKey === 'string' && rec.conversationKey) {
614
+ conversationKey = rec.conversationKey;
615
+ }
616
+ // First client request body = the session's opening prompt. The
617
+ // harness vocabulary comes from the SAME archived record's UA, so
618
+ // a replayed session resolves exactly what the live turn saw.
619
+ if (preview === undefined &&
620
+ rec.direction === 'client' &&
621
+ rec.phase === 'request' &&
622
+ rec.wire?.requestBody !== undefined) {
623
+ const archivedWire = rec.wire;
624
+ preview = CaptureRecorder.extractSessionPreview(archivedWire.requestBody, 120, CaptureRecorder.hintsOfHeaders(archivedWire.requestHeaders));
625
+ }
626
+ // Inbound-protocol badge: the FIRST client request line wins.
627
+ if (protocol === undefined && rec.direction === 'client' && rec.phase === 'request') {
628
+ protocol = CaptureRecorder.protocolFromRequestLine(rec.wire?.requestLine);
573
629
  }
574
630
  }
575
- // groupEventsIntoTurns returns chronological turns; iterate in
576
- // order so lastStatus reflects the FINAL turn's outcome.
577
- for (const t of CaptureRecorder.groupEventsIntoTurns(streamEvents)) {
578
- turns++;
579
- const hasError = Boolean(t.error) ||
580
- [t.clientRequest, t.gatewayResponse, t.upstreamRequest, t.upstreamResponse]
581
- .some(e => e?.status === 'error');
631
+ for (const r of CaptureRecorder.groupEventsIntoRequests(streamEvents)) {
632
+ requests++;
633
+ const clientResponse = exchangeEvent(r, 'client', 'response');
634
+ const hasError = Boolean(r.error) ||
635
+ r.exchanges.some(ex => ex.request?.status === 'error' || ex.response?.status === 'error');
582
636
  if (hasError)
583
637
  failed++;
584
- if (t.gatewayResponse)
585
- lastStatus = t.gatewayResponse.status === 'error' ? 'error' : 'ok';
638
+ if (clientResponse)
639
+ lastStatus = clientResponse.status === 'error' ? 'error' : 'ok';
586
640
  else if (hasError)
587
641
  lastStatus = 'error';
588
642
  }
@@ -596,7 +650,7 @@ export class CaptureRecorder {
596
650
  sessionId: f.name.slice(0, -JSONL_SUFFIX.length),
597
651
  bytes: st.size,
598
652
  mtimeMs: st.mtimeMs,
599
- turns,
653
+ requests,
600
654
  failed,
601
655
  lastStatus,
602
656
  preview,
@@ -618,8 +672,10 @@ export class CaptureRecorder {
618
672
  return filtered.sort((a, b) => b.mtimeMs - a.mtimeMs);
619
673
  }
620
674
  /**
621
- * Read records from one archive file, newest `limit` records in
622
- * chronological order. Reads at most the last readWindowBytes() of the file.
675
+ * Read the raw JSONL objects from the tail of one archive, newest `limit`
676
+ * lines in file order. No schema interpretation: archive-overflow seal
677
+ * markers are metadata and are filtered out, everything else is returned
678
+ * verbatim. Used by the generic console record view and the raw exporter.
623
679
  */
624
680
  readRecords(date, file, limit = 200) {
625
681
  const filePath = this.resolveArchiveFile(date, file);
@@ -649,8 +705,7 @@ export class CaptureRecorder {
649
705
  continue;
650
706
  try {
651
707
  const rec = JSON.parse(raw);
652
- // The seal marker is metadata, not a turn — the legacy timeline must
653
- // not grow a phantom record for it.
708
+ // The terminal seal marker is metadata, never a captured event.
654
709
  if (rec?.eventType === 'archive-overflow')
655
710
  continue;
656
711
  records.push(rec);
@@ -666,21 +721,30 @@ export class CaptureRecorder {
666
721
  }
667
722
  }
668
723
  /**
669
- * Read the last `readWindowBytes()` of one archive and parse its
670
- * http-exchange events. Async and yield-paced: the window can be tens of
671
- * MB and per-line JSON.parse is CPU-bound — parsing in batches with
672
- * event-loop yields keeps the gateway responsive while an archive read is
673
- * in flight. Never fails: corrupt lines are skipped.
724
+ * Read the last `bytes` of one archive and parse its http-exchange events.
725
+ * Async and yield-paced: the window can be tens of MB and per-line
726
+ * JSON.parse is CPU-bound — parsing in batches with event-loop yields keeps
727
+ * the gateway responsive while an archive read is in flight. Never fails:
728
+ * corrupt lines are skipped.
729
+ *
730
+ * `minBytes` lets a caller ask for a window LARGER than the default one —
731
+ * the console's backward pager grows the window until the page it wants is
732
+ * covered (see readEvents), so a session whose bodies blow past the default
733
+ * window is still fully browsable instead of silently ending at its tail.
674
734
  */
675
- async readWindowEvents(date, file) {
735
+ async readWindowEvents(date, file, minBytes = 0) {
676
736
  const filePath = this.resolveArchiveFile(date, file);
677
737
  if (!filePath)
678
- return { events: [], fileTruncated: false };
738
+ return { events: [], fileTruncated: false, fileBytes: 0, windowBytes: 0 };
679
739
  let text;
680
740
  let fileTruncated = false;
741
+ let fileBytes = 0;
742
+ let windowBytes = 0;
681
743
  try {
682
744
  const st = await fs.promises.stat(filePath);
683
- const readSize = Math.min(st.size, this.readWindowBytes());
745
+ fileBytes = st.size;
746
+ const readSize = Math.min(st.size, Math.max(this.readWindowBytes(), minBytes));
747
+ windowBytes = readSize;
684
748
  const fh = await fs.promises.open(filePath, 'r');
685
749
  try {
686
750
  const buf = Buffer.alloc(readSize);
@@ -693,7 +757,7 @@ export class CaptureRecorder {
693
757
  fileTruncated = readSize < st.size;
694
758
  }
695
759
  catch {
696
- return { events: [], fileTruncated: false };
760
+ return { events: [], fileTruncated: false, fileBytes: 0, windowBytes: 0 };
697
761
  }
698
762
  const lines = text.split(/\r?\n/);
699
763
  if (fileTruncated && lines.length > 0)
@@ -708,12 +772,12 @@ export class CaptureRecorder {
708
772
  try {
709
773
  const obj = JSON.parse(raw);
710
774
  if (obj.eventType === 'http-exchange') {
711
- const ev = obj;
775
+ const ev = CaptureRecorder.parseArchivedEvent(obj);
776
+ if (!ev)
777
+ continue;
712
778
  deriveCompletionTokens(ev);
713
779
  events.push(ev);
714
780
  }
715
- // cap_xxx entries (turn-centric) are skipped — the console reads
716
- // those via /api/admin/capture/:date/:file (readRecords path).
717
781
  }
718
782
  catch {
719
783
  // Corrupt/partial line — skip, never fail the whole read.
@@ -721,52 +785,123 @@ export class CaptureRecorder {
721
785
  if ((i + 1) % BATCH === 0)
722
786
  await yieldLoop();
723
787
  }
724
- return { events, fileTruncated };
788
+ return { events, fileTruncated, fileBytes, windowBytes };
789
+ }
790
+ /**
791
+ * Archive-line boundary validation — schema-2 only. A line is accepted
792
+ * only when it is a COMPLETE schema-2 http-exchange event: every scope
793
+ * field written by the admission gate must be present, including the
794
+ * first-class `turnIndex: null` for prompt-less requests. There is no
795
+ * legacy vocabulary, no field mapping and no derived fallback: a line is
796
+ * read in the shape the writer produced or not at all. A schema-1 archive
797
+ * is never read here — the migrator chain (`capture/migrate/`) rewrites it
798
+ * in place at boot, and it does so for EVERY line it can parse.
799
+ */
800
+ static parseArchivedEvent(obj) {
801
+ if (obj.schema !== CAPTURE_SCHEMA ||
802
+ obj.eventType !== 'http-exchange' ||
803
+ typeof obj.id !== 'string' || !obj.id ||
804
+ typeof obj.ts !== 'number' ||
805
+ typeof obj.requestId !== 'string' || !obj.requestId ||
806
+ typeof obj.exchangeId !== 'string' || !obj.exchangeId ||
807
+ typeof obj.sessionId !== 'string' ||
808
+ (obj.turnIndex !== null && typeof obj.turnIndex !== 'number') ||
809
+ typeof obj.isPromptStart !== 'boolean' ||
810
+ typeof obj.turnDecision !== 'string' ||
811
+ typeof obj.attempt !== 'number' ||
812
+ (obj.direction !== 'client' && obj.direction !== 'upstream') ||
813
+ (obj.phase !== 'request' && obj.phase !== 'response'))
814
+ return null;
815
+ return obj;
725
816
  }
726
817
  /**
727
- * Read HTTP exchange events from one archive file, newest `limit` events
728
- * in chronological order. Returns events + a `turns` summary that
729
- * groups the events by `traceId` (spanId-aware) so the console can
730
- * render them as logical turns. The underlying file is also bounded at
731
- * readWindowBytes() (pathologically large archives are tailed; the tail is
732
- * what matters). `bodies='none'` strips wire bodies for metadata-first
733
- * console reads — the tok/s chips keep working via the derived
734
- * `completionTokens` field, and full bodies come back on demand
735
- * (readTurn / bodies='full').
818
+ * Read the schema-2 events in one archive's tail window and project them
819
+ * into REQUESTS. Paging is in requests (the pager's unit): page 1 is the
820
+ * newest `limit` requests, and every exchange of a request always travels
821
+ * with it. `bodies='none'` strips wire bodies for metadata-first reads;
822
+ * `bodies='chat'` keeps only a prompt-start request's body plus responses.
823
+ *
824
+ * The read window GROWS to cover the requested page: a large body per
825
+ * request means a few requests can fill the default window. Growth doubles
826
+ * until the page fits, the whole file is read, or the growth ceiling is
827
+ * reached — past that the response clamps `page`/`totalPages`.
828
+ *
829
+ * `totalTurns` counts DISTINCT write-time `turnIndex` values in the window;
830
+ * it is not an ordinal and not a request count. Nothing here derives a turn
831
+ * boundary: the archive already carries `turnIndex`/`isPromptStart`.
736
832
  */
737
- async readEvents(date, file, limit = 500, bodies = 'full') {
738
- const { events, fileTruncated } = await this.readWindowEvents(date, file);
833
+ async readEvents(date, file, limit = 50, bodies = 'full', page = 1) {
834
+ const size = Math.max(1, limit);
835
+ const needed = page * size + 1;
836
+ let minBytes = 0;
837
+ let read = await this.readWindowEvents(date, file, minBytes);
838
+ for (;;) {
839
+ const groups = CaptureRecorder.groupEventsIntoRequests(read.events);
840
+ if (groups.length >= needed || !read.fileTruncated)
841
+ break;
842
+ const next = Math.min(Math.max(read.windowBytes * 2, this.readWindowBytes()), READ_WINDOW_GROWTH_CEIL_BYTES);
843
+ if (next <= read.windowBytes)
844
+ break;
845
+ minBytes = next;
846
+ read = await this.readWindowEvents(date, file, minBytes);
847
+ }
848
+ const { events, fileTruncated } = read;
849
+ const allRequests = CaptureRecorder.groupEventsIntoRequests(events);
850
+ const totals = CaptureRecorder.numberRequests(allRequests);
851
+ const totalPages = Math.max(1, Math.ceil(allRequests.length / size));
852
+ const pageNo = Math.min(Math.max(1, Math.trunc(page) || 1), totalPages);
853
+ const end = allRequests.length - (pageNo - 1) * size;
854
+ const sliceStart = Math.max(0, end - size);
855
+ const pageRequests = allRequests.slice(sliceStart, Math.max(sliceStart, end));
856
+ // Exactly the events of this page's requests, in wire order.
857
+ const visible = new Set();
858
+ for (const r of pageRequests)
859
+ for (const ev of CaptureRecorder.requestEvents(r))
860
+ visible.add(ev);
861
+ const newest = events.filter(ev => visible.has(ev));
739
862
  if (bodies === 'none')
740
863
  stripBodies(events);
741
- let newest = events.slice(-Math.max(1, limit));
742
- // Don't cut a turn in half: when the window starts mid-turn, the
743
- // leading events (upstream/gateway responses whose client-request fell
744
- // outside the window) would form a phantom incomplete turn with no
745
- // latency — drop everything before the first turn-start in the window.
746
- const firstTurnStart = newest.findIndex(e => e.direction === 'client' && e.phase === 'request');
747
- if (firstTurnStart > 0)
748
- newest = newest.slice(firstTurnStart);
749
- const turns = CaptureRecorder.groupEventsIntoTurns(newest);
750
- // Total logical turns over the whole read window — the header's turn count
751
- // must use this, not totalLines (raw event lines, 2-4 per turn).
752
- const totalTurns = CaptureRecorder.groupEventsIntoTurns(events).length;
753
- return { events: newest, turns, totalLines: events.length, totalTurns, fileTruncated };
864
+ else if (bodies === 'chat') {
865
+ const keepRequests = new Set();
866
+ for (const r of allRequests) {
867
+ const cr = exchangeEvent(r, 'client', 'request');
868
+ // Only the request that OPENED a turn carries a new prompt's history.
869
+ if (cr && r.isPromptStart)
870
+ keepRequests.add(cr);
871
+ }
872
+ stripBodiesForChat(events, keepRequests);
873
+ }
874
+ return {
875
+ events: newest,
876
+ requests: pageRequests,
877
+ totalLines: events.length,
878
+ totalRequests: totals.requests,
879
+ totalTurns: totals.turns,
880
+ windowComplete: !fileTruncated,
881
+ fileTruncated,
882
+ page: pageNo,
883
+ totalPages,
884
+ hasOlder: sliceStart > 0,
885
+ hasNewer: pageNo > 1,
886
+ };
754
887
  }
755
888
  /**
756
- * Read one turn's FULL wire bodies by the id of any of its events (the
757
- * console passes the client-request event id). The metadata-first console
758
- * flow fetches the heavy bodies here when a turn is opened. Returns null
759
- * when the id is unknown or falls outside the read window.
889
+ * Read one REQUEST's full wire bodies. The key is its `requestId` (what the
890
+ * console row and every React key carries); any of its event ids is accepted
891
+ * too for deep links. Returns null when the key is unknown or fell outside
892
+ * the read window. No re-derivation: the returned summary is the archive's
893
+ * own write-time identity over its `exchanges[]`.
760
894
  */
761
- async readTurn(date, file, eventId) {
895
+ async readRequest(date, file, requestOrEventId) {
762
896
  const { events } = await this.readWindowEvents(date, file);
763
- const anchor = events.find(e => e.id === eventId);
897
+ const anchor = events.find(e => e.id === requestOrEventId) ??
898
+ events.find(e => e.requestId === requestOrEventId);
764
899
  if (!anchor)
765
900
  return null;
766
- const subset = events.filter(e => e.traceId === anchor.traceId);
767
- const turns = CaptureRecorder.groupEventsIntoTurns(subset);
768
- const turn = turns.find(t => [t.clientRequest, t.gatewayResponse, t.upstreamRequest, t.upstreamResponse, t.decisionRequest, t.decisionResponse].some(e => e?.id === eventId));
769
- return turn ? { turn } : null;
901
+ const requests = CaptureRecorder.groupEventsIntoRequests(events);
902
+ CaptureRecorder.numberRequests(requests);
903
+ const request = requests.find(r => r.requestId === anchor.requestId);
904
+ return request ? { request } : null;
770
905
  }
771
906
  /* --------------------------------------------------- cross-date stitching */
772
907
  // conversationKey per archive path (first 64 KB head read). null = read
@@ -888,176 +1023,374 @@ export class CaptureRecorder {
888
1023
  * its request and response events landed in different date files.
889
1024
  * Fragment turn counts are per-file (the archive's physical layout), while
890
1025
  * `turns`/`totalTurns` cover the WHOLE conversation.
1026
+ *
1027
+ * `page` pages backwards exactly like the non-stitched read, over the
1028
+ * MERGED conversation timeline (a page can therefore mix shards). Paging
1029
+ * stays window-bounded: each fragment is read through its own tail window,
1030
+ * so history older than every window is export-only.
891
1031
  */
892
- async readEventsStitched(date, file, limit = 500, bodies = 'full') {
1032
+ async readEventsStitched(date, file, limit = 50, bodies = 'full', page = 1) {
893
1033
  const fragments = this.conversationFragments(date, file);
894
- const merged = new Map();
1034
+ const size = Math.max(1, limit);
1035
+ const needed = page * size + 1;
1036
+ let minBytes = 0;
1037
+ let merged = new Map();
895
1038
  let fileTruncated = false;
896
- const fragmentRows = [];
897
- for (const f of fragments) {
898
- const { events, fileTruncated: trunc } = await this.readWindowEvents(f.date, f.file);
899
- if (trunc)
900
- fileTruncated = true;
901
- for (const ev of events) {
902
- if (!merged.has(ev.id))
903
- merged.set(ev.id, ev);
1039
+ let fragmentRows = [];
1040
+ for (;;) {
1041
+ merged = new Map();
1042
+ fragmentRows = [];
1043
+ fileTruncated = false;
1044
+ let grew = false;
1045
+ let maxWindow = 0;
1046
+ for (const f of fragments) {
1047
+ const result = await this.readWindowEvents(f.date, f.file, minBytes);
1048
+ if (result.fileTruncated)
1049
+ fileTruncated = true;
1050
+ if (result.windowBytes > maxWindow)
1051
+ maxWindow = result.windowBytes;
1052
+ if (result.fileBytes > result.windowBytes)
1053
+ grew = true;
1054
+ for (const ev of result.events)
1055
+ if (!merged.has(ev.id))
1056
+ merged.set(ev.id, ev);
1057
+ fragmentRows.push({
1058
+ date: f.date,
1059
+ file: f.file,
1060
+ requests: CaptureRecorder.groupEventsIntoRequests(result.events).length,
1061
+ });
904
1062
  }
905
- fragmentRows.push({ date: f.date, file: f.file, turns: CaptureRecorder.groupEventsIntoTurns(events).length });
1063
+ const all = [...merged.values()].sort((a, b) => a.ts - b.ts);
1064
+ if (CaptureRecorder.groupEventsIntoRequests(all).length >= needed || !grew)
1065
+ break;
1066
+ const next = Math.min(Math.max(maxWindow * 2, this.readWindowBytes()), READ_WINDOW_GROWTH_CEIL_BYTES);
1067
+ if (next <= maxWindow)
1068
+ break;
1069
+ minBytes = next;
906
1070
  }
907
1071
  const all = [...merged.values()].sort((a, b) => a.ts - b.ts);
1072
+ const allRequests = CaptureRecorder.groupEventsIntoRequests(all);
1073
+ const totals = CaptureRecorder.numberRequests(allRequests);
1074
+ const totalPages = Math.max(1, Math.ceil(allRequests.length / size));
1075
+ const pageNo = Math.min(Math.max(1, Math.trunc(page) || 1), totalPages);
1076
+ const end = allRequests.length - (pageNo - 1) * size;
1077
+ const sliceStart = Math.max(0, end - size);
1078
+ const pageRequests = allRequests.slice(sliceStart, Math.max(sliceStart, end));
1079
+ const visible = new Set();
1080
+ for (const r of pageRequests)
1081
+ for (const ev of CaptureRecorder.requestEvents(r))
1082
+ visible.add(ev);
1083
+ const newest = all.filter(ev => visible.has(ev));
908
1084
  if (bodies === 'none')
909
1085
  stripBodies(all);
910
- let newest = all.slice(-Math.max(1, limit));
911
- // Same mid-turn guard as readEvents: drop leading orphan response events.
912
- const firstTurnStart = newest.findIndex(e => e.direction === 'client' && e.phase === 'request');
913
- if (firstTurnStart > 0)
914
- newest = newest.slice(firstTurnStart);
915
- const turns = CaptureRecorder.groupEventsIntoTurns(newest);
916
- const totalTurns = CaptureRecorder.groupEventsIntoTurns(all).length;
917
- return { events: newest, turns, totalLines: all.length, totalTurns, fileTruncated, fragments: fragmentRows };
1086
+ else if (bodies === 'chat') {
1087
+ const keepRequests = new Set();
1088
+ for (const r of allRequests) {
1089
+ const cr = exchangeEvent(r, 'client', 'request');
1090
+ if (cr && r.isPromptStart)
1091
+ keepRequests.add(cr);
1092
+ }
1093
+ stripBodiesForChat(all, keepRequests);
1094
+ }
1095
+ return {
1096
+ events: newest,
1097
+ requests: pageRequests,
1098
+ totalLines: all.length,
1099
+ totalRequests: totals.requests,
1100
+ totalTurns: totals.turns,
1101
+ windowComplete: !fileTruncated,
1102
+ fileTruncated,
1103
+ fragments: fragmentRows,
1104
+ page: pageNo,
1105
+ totalPages,
1106
+ hasOlder: sliceStart > 0,
1107
+ hasNewer: pageNo > 1,
1108
+ };
918
1109
  }
919
1110
  /**
920
- * readTurn across ALL fragments of the session: the anchor fragment's
921
- * window is tried first, then every other fragment — a turn archived in a
922
- * previous day's shard must still open its full wire bodies.
1111
+ * Resolve one request's full wire bodies across ALL fragments of the
1112
+ * session: a request archived in a previous day's shard must still open.
923
1113
  */
924
- async readTurnStitched(date, file, eventId) {
1114
+ async readRequestStitched(date, file, requestOrEventId) {
925
1115
  for (const f of this.conversationFragments(date, file)) {
926
- const result = await this.readTurn(f.date, f.file, eventId);
1116
+ const result = await this.readRequest(f.date, f.file, requestOrEventId);
927
1117
  if (result)
928
1118
  return result;
929
1119
  }
930
1120
  return null;
931
1121
  }
1122
+ /* -------------------------------------------------- exact archive summary */
932
1123
  /**
933
- * Group a flat list of HTTP exchange events into logical turns via
934
- * `traceId`. Each turn joins its four events: client-direction events
935
- * pair by `spanId`, upstream events attach to the trace's active turn
936
- * (last-write-wins across failover hops). SpanId-aware because a client
937
- * that sends a CONSTANT `x-request-id` on every request would otherwise
938
- * collapse the whole session into one turn.
939
- * Pure function — exported for unit tests.
1124
+ * EXACT whole-archive summary, not the read window: the request count and
1125
+ * the WRITE-TIME TURN INDEX (turnIndex + contiguous request range).
1126
+ *
1127
+ * Every request starts with exactly one client-request event, so counting
1128
+ * those lines counts requests without grouping. A client request carrying
1129
+ * `turnIndex: null` belongs to no turn and is counted as a request only.
1130
+ * The terminal `archive-overflow` seal line is metadata and is skipped.
1131
+ *
1132
+ * Streamed in chunks so a seal-maximum session (512 MB) never becomes one
1133
+ * string on the heap. Targeted regexes pull only the metadata — never
1134
+ * JSON.parse on the whole line, whose request body can be many MB. Turn
1135
+ * membership is read from the archive, never inferred from prompts,
1136
+ * message counts or resend heuristics.
1137
+ *
1138
+ * The result is DISPLAY ONLY: pagination still reads a bounded window.
940
1139
  */
941
- static groupEventsIntoTurns(events) {
942
- const byTrace = new Map();
943
- /** traceId → the turn upstream events should attach to (the latest). */
944
- const activeByTrace = new Map();
945
- const newTurn = (ev) => {
946
- const t = { traceId: ev.traceId, sessionId: ev.sessionId, model: ev.model };
947
- let list = byTrace.get(ev.traceId);
948
- if (!list) {
949
- list = [];
950
- byTrace.set(ev.traceId, list);
951
- }
952
- list.push(t);
953
- return t;
954
- };
955
- for (const ev of events) {
956
- let t;
957
- if (ev.direction === 'client' && ev.phase === 'request') {
958
- // A client request ALWAYS starts a new turn — even when the traceId
959
- // was already seen (a client sending a constant x-request-id on
960
- // every request gets one turn per request, not one giant merged
961
- // turn with last-write-wins fields).
962
- t = newTurn(ev);
963
- t.clientRequest = ev;
964
- t.promptSummary = ev.promptSummary;
965
- activeByTrace.set(ev.traceId, t);
966
- }
967
- else if (ev.direction === 'client' && ev.phase === 'response') {
968
- // Pair by spanId with the matching client request (newest first —
969
- // the common case is the latest turn of the trace).
970
- const list = byTrace.get(ev.traceId) ?? [];
971
- for (let i = list.length - 1; i >= 0; i--) {
972
- if (list[i].clientRequest?.spanId === ev.spanId) {
973
- t = list[i];
974
- break;
975
- }
1140
+ async captureSummary(date, file) {
1141
+ const filePath = this.resolveArchiveFile(date, file);
1142
+ if (!filePath)
1143
+ return { requests: 0, fragments: 1, turns: [] };
1144
+ const sig = this.archiveSignature([filePath]);
1145
+ const cached = sig ? this.summaryCache.get(sig) : undefined;
1146
+ if (cached)
1147
+ return cached;
1148
+ const state = newRequestIndexState();
1149
+ await this.scanRequestIndex(filePath, state);
1150
+ const summary = { requests: state.requests, fragments: 1, turns: state.turns };
1151
+ if (sig)
1152
+ this.rememberSummary(sig, summary);
1153
+ return summary;
1154
+ }
1155
+ /**
1156
+ * Whole STITCHED conversation: fragments in chronological order. One
1157
+ * client-request line lives in exactly one shard, so a request is counted
1158
+ * once; `byKey` carries the same (sessionId, turnIndex) across shards.
1159
+ */
1160
+ async captureSummaryStitched(date, file) {
1161
+ const fragments = this.conversationFragments(date, file)
1162
+ .slice()
1163
+ .sort((a, b) => a.date.localeCompare(b.date) || a.file.localeCompare(b.file));
1164
+ const paths = fragments
1165
+ .map(f => this.resolveArchiveFile(f.date, f.file))
1166
+ .filter((p) => Boolean(p));
1167
+ const sig = this.archiveSignature(paths);
1168
+ const cached = sig ? this.summaryCache.get(sig) : undefined;
1169
+ if (cached)
1170
+ return cached;
1171
+ const state = newRequestIndexState();
1172
+ for (const p of paths)
1173
+ await this.scanRequestIndex(p, state);
1174
+ const summary = { requests: state.requests, fragments: paths.length, turns: state.turns };
1175
+ if (sig)
1176
+ this.rememberSummary(sig, summary);
1177
+ return summary;
1178
+ }
1179
+ /** mtime+size signature — any append invalidates; a read-only archive hits. */
1180
+ archiveSignature(paths) {
1181
+ const parts = [];
1182
+ for (const p of paths) {
1183
+ try {
1184
+ const st = fs.statSync(p);
1185
+ parts.push(`${p}:${st.size}:${st.mtimeMs}`);
1186
+ }
1187
+ catch {
1188
+ return null;
1189
+ }
1190
+ }
1191
+ return parts.join('|');
1192
+ }
1193
+ /** Bounded LRU-ish cache: drop the oldest entry past 8 summaries. */
1194
+ rememberSummary(sig, summary) {
1195
+ this.summaryCache.delete(sig);
1196
+ this.summaryCache.set(sig, summary);
1197
+ while (this.summaryCache.size > 8) {
1198
+ const oldest = this.summaryCache.keys().next().value;
1199
+ if (oldest === undefined)
1200
+ break;
1201
+ this.summaryCache.delete(oldest);
1202
+ }
1203
+ }
1204
+ /**
1205
+ * One streamed metadata pass; appends to `state` so shards chain.
1206
+ * Byte-level: several event lines can share a multi-MB request body, so
1207
+ * the stream stays a Buffer and only a matching client-request line is
1208
+ * decoded. Only schema-2 lines are considered.
1209
+ */
1210
+ async scanRequestIndex(filePath, state) {
1211
+ const take = (line) => {
1212
+ if (line.length === 0)
1213
+ return;
1214
+ if (line.indexOf('"schema":2') < 0 ||
1215
+ line.indexOf('"eventType":"http-exchange"') < 0 ||
1216
+ line.indexOf('"direction":"client"') < 0 ||
1217
+ line.indexOf('"phase":"request"') < 0)
1218
+ return;
1219
+ const text = line.toString('utf8');
1220
+ state.requests++;
1221
+ const n = state.requests;
1222
+ const turnMatch = RE_CAPTURE_TURN_INDEX.exec(text);
1223
+ // `turnIndex: null` (prompt-less request) belongs to no turn.
1224
+ if (!turnMatch)
1225
+ return;
1226
+ const turnIndex = Number(turnMatch[1]);
1227
+ const sessionId = RE_CAPTURE_SESSION_ID.exec(text)?.[1] ?? '';
1228
+ const tsMatch = RE_CAPTURE_TS.exec(text);
1229
+ const ts = tsMatch ? Number(tsMatch[1]) : undefined;
1230
+ const isPromptStart = RE_CAPTURE_IS_PROMPT_START.test(text);
1231
+ const rawPrompt = RE_CAPTURE_PROMPT_SUMMARY.exec(text)?.[1];
1232
+ let prompt;
1233
+ if (isPromptStart && rawPrompt !== undefined) {
1234
+ try {
1235
+ prompt = JSON.parse(rawPrompt);
976
1236
  }
977
- if (!t)
978
- t = newTurn(ev); // response whose request fell outside the read window
979
- t.gatewayResponse = ev;
980
- }
981
- else if (ev.purpose === 'l2-decision') {
982
- // The L2 decision layer's HTTP leg shares the routed turn's trace but is NOT
983
- // failover traffic — route it to dedicated slots so the serving
984
- // leg's last-write-wins below never overwrites it. The decision layer fires
985
- // BEFORE candidate execution, so a plain upstream merge would erase
986
- // it and the console would only ever show one upstream call.
987
- t = activeByTrace.get(ev.traceId);
988
- if (!t) {
989
- t = newTurn(ev);
990
- activeByTrace.set(ev.traceId, t);
1237
+ catch {
1238
+ prompt = undefined; // truncated/sealed line — display-only field
991
1239
  }
992
- if (ev.phase === 'request')
993
- t.decisionRequest = ev;
994
- else
995
- t.decisionResponse = ev;
996
1240
  }
997
- else {
998
- // Upstream events attach to the trace's active turn. Failover hops
999
- // overwrite each other (last-write-wins) — the final attempt is
1000
- // the one that produced the gateway response.
1001
- t = activeByTrace.get(ev.traceId);
1002
- if (!t) {
1003
- t = newTurn(ev);
1004
- activeByTrace.set(ev.traceId, t);
1241
+ const key = `${sessionId}|${turnIndex}`;
1242
+ let entry = state.byKey.get(key);
1243
+ if (!entry) {
1244
+ entry = {
1245
+ turnIndex,
1246
+ ...(prompt !== undefined ? { prompt } : {}),
1247
+ ...(isPromptStart && ts !== undefined && Number.isFinite(ts) ? { startTs: ts } : {}),
1248
+ requests: 0,
1249
+ firstRequest: n,
1250
+ lastRequest: n,
1251
+ };
1252
+ state.byKey.set(key, entry);
1253
+ state.turns.push(entry);
1254
+ }
1255
+ else if (isPromptStart) {
1256
+ if (entry.prompt === undefined && prompt !== undefined)
1257
+ entry.prompt = prompt;
1258
+ if (entry.startTs === undefined && ts !== undefined && Number.isFinite(ts))
1259
+ entry.startTs = ts;
1260
+ entry.firstRequest = Math.min(entry.firstRequest, n);
1261
+ }
1262
+ entry.requests++;
1263
+ entry.lastRequest = n;
1264
+ };
1265
+ try {
1266
+ const stream = fs.createReadStream(filePath, { highWaterMark: 1 << 20 });
1267
+ let rest = Buffer.alloc(0);
1268
+ for await (const chunk of stream) {
1269
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1270
+ rest = rest.length > 0 ? Buffer.concat([rest, buf]) : buf;
1271
+ let start = 0;
1272
+ for (;;) {
1273
+ const nl = rest.indexOf(0x0a, start);
1274
+ if (nl < 0)
1275
+ break;
1276
+ take(rest.subarray(start, nl));
1277
+ start = nl + 1;
1005
1278
  }
1006
- if (ev.phase === 'request')
1007
- t.upstreamRequest = ev;
1008
- else
1009
- t.upstreamResponse = ev;
1010
- }
1011
- if (ev.error && !t.error)
1012
- t.error = ev.error;
1013
- }
1014
- const all = [];
1015
- for (const list of byTrace.values())
1016
- all.push(...list);
1017
- for (const t of all) {
1018
- if (t.clientRequest && t.gatewayResponse) {
1019
- t.gatewayLatencyMs = t.gatewayResponse.ts - t.clientRequest.ts;
1020
- }
1021
- if (t.upstreamRequest && t.upstreamResponse) {
1022
- t.upstreamLatencyMs = t.upstreamResponse.ts - t.upstreamRequest.ts;
1023
- }
1024
- if (t.decisionRequest && t.decisionResponse) {
1025
- t.decisionLatencyMs = t.decisionResponse.ts - t.decisionRequest.ts;
1026
- }
1027
- // TTFT / decode window per leg: the response event's firstByteTs splits
1028
- // the cycle latency into wait-for-first-token and decode phases. Derived
1029
- // only when the stamp exists (streamed legs; pre-stamp events stay
1030
- // undefined so the console shows '—' instead of a synthesized split).
1031
- const derive = (req, resp) => {
1032
- if (resp.firstByteTs === undefined)
1033
- return {};
1034
- return {
1035
- ttft: Math.max(0, resp.firstByteTs - req.ts),
1036
- gen: Math.max(0, resp.ts - resp.firstByteTs),
1279
+ if (start > 0)
1280
+ rest = rest.subarray(start);
1281
+ }
1282
+ if (rest.length > 0)
1283
+ take(rest);
1284
+ }
1285
+ catch {
1286
+ // Unreadable tail — answer what was counted.
1287
+ }
1288
+ }
1289
+ /**
1290
+ * Group a flat list of capture events into REQUESTS by the gateway-owned
1291
+ * `requestId`. Each request owns an `exchanges[]` list bucketed by
1292
+ * `(leg, attempt)`, so EVERY failover hop and the Layer-2 decision pair
1293
+ * survive — nothing is last-write-wins.
1294
+ *
1295
+ * No turn boundary, prompt, message count or ordinal is derived here:
1296
+ * `turnIndex` / `isPromptStart` / `turnDecision` are copied from the
1297
+ * write-time fields on the events, and `attempt` was stamped at emit time.
1298
+ * Pure function — exported for unit tests.
1299
+ */
1300
+ static groupEventsIntoRequests(events) {
1301
+ const byRequest = new Map();
1302
+ const exchangeByKey = new Map();
1303
+ const legOf = (ev) => ev.purpose === 'l2-decision' ? 'decision' : ev.direction === 'client' ? 'client' : 'upstream';
1304
+ for (const ev of events) {
1305
+ let summary = byRequest.get(ev.requestId);
1306
+ if (!summary) {
1307
+ summary = {
1308
+ requestId: ev.requestId,
1309
+ ...(ev.clientRequestId ? { clientRequestId: ev.clientRequestId } : {}),
1310
+ sessionId: ev.sessionId,
1311
+ model: ev.model,
1312
+ turnIndex: ev.turnIndex ?? null,
1313
+ isPromptStart: ev.isPromptStart ?? false,
1314
+ turnDecision: ev.turnDecision ?? 'no_prompt',
1315
+ exchanges: [],
1037
1316
  };
1038
- };
1039
- if (t.clientRequest && t.gatewayResponse) {
1040
- const d = derive(t.clientRequest, t.gatewayResponse);
1041
- t.gatewayTtftMs = d.ttft;
1042
- t.gatewayGenMs = d.gen;
1317
+ byRequest.set(ev.requestId, summary);
1318
+ }
1319
+ // The client-request event is authoritative for identity when present.
1320
+ if (ev.direction === 'client' && ev.phase === 'request') {
1321
+ summary.sessionId = ev.sessionId;
1322
+ summary.model = ev.model;
1323
+ summary.turnIndex = ev.turnIndex ?? null;
1324
+ summary.isPromptStart = ev.isPromptStart ?? false;
1325
+ summary.turnDecision = ev.turnDecision ?? 'no_prompt';
1326
+ if (ev.promptSummary !== undefined)
1327
+ summary.promptSummary = ev.promptSummary;
1328
+ }
1329
+ if (ev.error && !summary.error)
1330
+ summary.error = ev.error;
1331
+ const leg = legOf(ev);
1332
+ const key = `${ev.requestId}|${ev.exchangeId}`;
1333
+ let exchange = exchangeByKey.get(key);
1334
+ if (!exchange) {
1335
+ exchange = {
1336
+ leg,
1337
+ attempt: ev.attempt ?? 1,
1338
+ exchangeId: ev.exchangeId,
1339
+ ...(ev.purpose ? { purpose: ev.purpose } : {}),
1340
+ };
1341
+ exchangeByKey.set(key, exchange);
1342
+ summary.exchanges.push(exchange);
1343
+ }
1344
+ if (ev.phase === 'request') {
1345
+ exchange.request = ev;
1346
+ if (ev.stream !== undefined)
1347
+ exchange.requestStream = ev.stream;
1043
1348
  }
1044
- if (t.upstreamRequest && t.upstreamResponse) {
1045
- const d = derive(t.upstreamRequest, t.upstreamResponse);
1046
- t.upstreamTtftMs = d.ttft;
1047
- t.upstreamGenMs = d.gen;
1349
+ else {
1350
+ exchange.response = ev;
1351
+ if (ev.stream !== undefined)
1352
+ exchange.responseStream = ev.stream;
1048
1353
  }
1049
- if (t.decisionRequest && t.decisionResponse) {
1050
- const d = derive(t.decisionRequest, t.decisionResponse);
1051
- t.decisionTtftMs = d.ttft;
1052
- t.decisionGenMs = d.gen;
1354
+ }
1355
+ const all = [...byRequest.values()];
1356
+ for (const summary of all) {
1357
+ summary.exchanges.sort((a, b) => (a.request?.ts ?? a.response?.ts ?? 0) - (b.request?.ts ?? b.response?.ts ?? 0) ||
1358
+ a.attempt - b.attempt);
1359
+ for (const ex of summary.exchanges) {
1360
+ if (!ex.request || !ex.response)
1361
+ continue;
1362
+ ex.latencyMs = Math.max(0, ex.response.ts - ex.request.ts);
1363
+ if (ex.response.firstByteTs !== undefined) {
1364
+ ex.ttftMs = Math.max(0, ex.response.firstByteTs - ex.request.ts);
1365
+ ex.genMs = Math.max(0, ex.response.ts - ex.response.firstByteTs);
1366
+ }
1053
1367
  }
1054
1368
  }
1055
1369
  return all.sort((a, b) => {
1056
- const aTs = a.clientRequest?.ts ?? a.upstreamRequest?.ts ?? 0;
1057
- const bTs = b.clientRequest?.ts ?? b.upstreamRequest?.ts ?? 0;
1058
- return aTs - bTs;
1370
+ const ts = (t) => t.exchanges[0]?.request?.ts ?? t.exchanges[0]?.response?.ts ?? 0;
1371
+ return ts(a) - ts(b);
1059
1372
  });
1060
1373
  }
1374
+ /** Number requests 1..N inside the read window (the pager's unit). */
1375
+ static numberRequests(requests) {
1376
+ requests.forEach((r, i) => { r.requestNumber = i + 1; });
1377
+ const seen = new Set();
1378
+ for (const r of requests)
1379
+ if (r.turnIndex !== null)
1380
+ seen.add(r.turnIndex);
1381
+ return { requests: requests.length, turns: seen.size };
1382
+ }
1383
+ /** Events belonging to a request (used for body stripping + page slicing). */
1384
+ static requestEvents(request) {
1385
+ const out = [];
1386
+ for (const ex of request.exchanges) {
1387
+ if (ex.request)
1388
+ out.push(ex.request);
1389
+ if (ex.response)
1390
+ out.push(ex.response);
1391
+ }
1392
+ return out;
1393
+ }
1061
1394
  /**
1062
1395
  * Read the raw JSONL archive verbatim (for export/download). Unlike
1063
1396
  * readRecords this is NOT capped at the read window — exports should be
@@ -1067,16 +1400,10 @@ export class CaptureRecorder {
1067
1400
  * route. Accepted for an operator-initiated export; upgrade path is a
1068
1401
  * streaming download (createReadStream piped to the reply).
1069
1402
  *
1070
- * When `exclude` is non-empty, body fields are stripped and the rest is
1071
- * re-serialized — metadata (ts/status/model/routing/ids) always survives.
1072
- * Handles both line formats:
1073
- * - legacy cap_ turn records: `request` / `upstreamRequest` / `response`
1074
- * / `upstreamError` fields are deleted directly.
1075
- * - evt_ http-exchange events: the same exclude names map onto the
1076
- * matching wire side (`request` → client request body,
1077
- * `upstreamRequest`/`upstreamHttp` → upstream request body,
1078
- * `response`/`upstreamError` → response bodies + the error field).
1079
- * Corrupt lines are kept verbatim, same fail-open policy as every read.
1403
+ * When `exclude` is non-empty, the matching wire-side bodies of a schema-2
1404
+ * http-exchange event are blanked and the rest of the line is re-serialized;
1405
+ * metadata (ids / ts / status / model / routing / turn identity) always
1406
+ * survives. Seal markers and unparseable lines pass through verbatim.
1080
1407
  */
1081
1408
  readRawArchive(date, file, exclude) {
1082
1409
  const filePath = this.resolveArchiveFile(date, file);
@@ -1107,8 +1434,9 @@ export class CaptureRecorder {
1107
1434
  delete rec.error;
1108
1435
  }
1109
1436
  else {
1110
- for (const f of drop)
1111
- delete rec[f];
1437
+ // Seal marker / unparseable-as-event line: keep it exactly as written.
1438
+ out.push(line);
1439
+ continue;
1112
1440
  }
1113
1441
  out.push(JSON.stringify(rec));
1114
1442
  }
@@ -1213,6 +1541,56 @@ export class CaptureRecorder {
1213
1541
  return false;
1214
1542
  }
1215
1543
  }
1544
+ /* ------------------------------------------------------ schema migration */
1545
+ /**
1546
+ * Archive schema-transition pass (ADR-0008 section 5).
1547
+ *
1548
+ * COLD files are walked hop by hop through the steps registered in
1549
+ * `migrate/registry.ts`, resolved by `(from, to)`. That is how an upgrading
1550
+ * installation keeps its history: schema-1 lines become schema-2 lines IN
1551
+ * PLACE, and every line the pass can read comes out readable — a legacy
1552
+ * span sequence that does not close cleanly is repaired into the nearest
1553
+ * truth-bearing shape by the step itself, never set aside.
1554
+ *
1555
+ * Whole-file discipline: a file is rewritten atomically or left exactly as
1556
+ * it was. A line that is not parseable JSON is carried over byte-for-byte
1557
+ * (and counted in `unreadable`) instead of costing the file its other
1558
+ * thousand good rows.
1559
+ *
1560
+ * Runs at boot, on hot-apply enable and on the hourly sweep; fail-open per
1561
+ * file. Rewritten files invalidate the size/seal/summary caches.
1562
+ *
1563
+ * `hotMs` is the quiet window a file must sit in before it is touched.
1564
+ * Boot and hot-enable pass 0 (`BOOT_MIGRATION_HOT_MS`) so an upgraded
1565
+ * installation shows its history at once — safety there comes from the
1566
+ * re-check before each swap, not from waiting. The hourly sweep passes
1567
+ * `undefined` and keeps the default window, because by then this process is
1568
+ * appending and a shard written minutes ago is simply retried next hour.
1569
+ */
1570
+ async migrateArchives(hotMs) {
1571
+ if (!this.enabled)
1572
+ return;
1573
+ try {
1574
+ const res = await migrateArchiveRoot(this.rootDir, CAPTURE_SCHEMA, { hotMs });
1575
+ if (res.files > 0) {
1576
+ this.fileBytesCache.clear();
1577
+ this.sealedFiles.clear();
1578
+ this.summaryCache.clear();
1579
+ }
1580
+ // Reported, never silent: an upgrade that could not bring some data
1581
+ // forward must say so once per pass instead of leaving the operator to
1582
+ // wonder why a session looks short.
1583
+ if (res.unreadable > 0) {
1584
+ console.warn(`[Capture] ${res.unreadable} archive line(s) are not parseable JSON — carried over verbatim, unreadable by any reader`);
1585
+ }
1586
+ if (res.rejected > 0) {
1587
+ console.warn(`[Capture] ${res.rejected} archive file(s) could not be migrated and were left untouched for the next pass`);
1588
+ }
1589
+ }
1590
+ catch {
1591
+ // Fail-open: a capture problem must never break the inference hot path.
1592
+ }
1593
+ }
1216
1594
  /* ------------------------------------------------------------ retention */
1217
1595
  /**
1218
1596
  * Sweep retention: delete date directories older than the retention window,
@@ -1251,23 +1629,6 @@ export class CaptureRecorder {
1251
1629
  }
1252
1630
  }
1253
1631
  /* ------------------------------------------------------------- helpers */
1254
- truncateField(value) {
1255
- if (value === undefined || value === null)
1256
- return { value: undefined, truncated: false };
1257
- let json;
1258
- try {
1259
- json = JSON.stringify(value);
1260
- }
1261
- catch {
1262
- return { value: '[unserializable]', truncated: false };
1263
- }
1264
- if (Buffer.byteLength(json, 'utf8') <= this.maxBodyBytes) {
1265
- return { value, truncated: false };
1266
- }
1267
- // Approximate byte-budget slicing on the JSON string; stored as a plain
1268
- // string because truncated JSON is not parseable anyway.
1269
- return { value: json.slice(0, this.maxBodyBytes) + '...[TRUNCATED]', truncated: true };
1270
- }
1271
1632
  /* ------------------------------------------------------------ media scrub */
1272
1633
  /**
1273
1634
  * Replace base64 media payloads in a JSON request body with `[MEDIA …]`
@@ -1505,31 +1866,90 @@ export class CaptureRecorder {
1505
1866
  * text-part array), Responses API (`input`), and the truncated-string
1506
1867
  * form stored when a body exceeded maxBodyBytes. Fails open to undefined.
1507
1868
  */
1508
- static extractSessionPreview(request, cap = 120) {
1509
- const text = CaptureRecorder.firstUserText(request);
1869
+ static extractSessionPreview(request, cap = 120, hints = {}) {
1870
+ if (hints.declaredPrompt)
1871
+ return CaptureRecorder.clipDisplay(hints.declaredPrompt, cap);
1872
+ // First HUMAN text, not the first user-role message: Cursor opens with a
1873
+ // `<user_info>`/`<rules>` bundle and the prompt rides the NEXT message.
1874
+ // Same strict-then-permissive rule as the console session title, and the
1875
+ // same harness profile (the reader resolves it from the archived UA).
1876
+ const text = CaptureRecorder.firstHumanUserText(request, 0, hints.profile);
1510
1877
  if (!text)
1511
1878
  return undefined;
1879
+ return CaptureRecorder.clipDisplay(text, cap);
1880
+ }
1881
+ /**
1882
+ * Envelope resolution inputs for a captured request, resolved from the
1883
+ * ARCHIVED headers — the read plane has no live request, so a replayed
1884
+ * session must resolve exactly the vocabulary (and the self-declared prompt)
1885
+ * its live turn saw. Cased lookup because archives preserve the client's own
1886
+ * header spelling.
1887
+ */
1888
+ static hintsOfHeaders(headers) {
1889
+ if (!headers)
1890
+ return {};
1891
+ let userAgent;
1892
+ let declared;
1893
+ for (const [key, value] of Object.entries(headers)) {
1894
+ const name = key.toLowerCase();
1895
+ if (name === 'user-agent')
1896
+ userAgent = value;
1897
+ else if (name === PROMPT_HINT_HEADER)
1898
+ declared = value;
1899
+ }
1900
+ const flatDeclared = declared?.replace(/\s+/g, ' ').trim();
1901
+ return {
1902
+ profile: harnessProfileOf(userAgent),
1903
+ ...(flatDeclared ? { declaredPrompt: flatDeclared } : {}),
1904
+ };
1905
+ }
1906
+ /** Cap a one-line display text with an ellipsis. */
1907
+ static clipDisplay(text, cap) {
1512
1908
  const flat = text.replace(/\s+/g, ' ').trim();
1513
1909
  if (!flat)
1514
1910
  return undefined;
1515
1911
  return flat.length <= cap ? flat : flat.slice(0, cap - 1) + '…';
1516
1912
  }
1517
1913
  /**
1518
- * The LAST user message of a request body, flattened and capped — the
1519
- * current turn's prompt (history replay carries the full conversation;
1520
- * the tail is the fresh turn). Stamped onto client-request events at
1521
- * write time so metadata-only reads (`bodies=none`) can still render the
1522
- * turn prompt in the timeline. Same disclosure class as the session
1523
- * preview. Undefined when the body carries no user text.
1914
+ * The LAST user message of a request body, flattened and capped. Same
1915
+ * disclosure class as the session preview. Undefined when the body carries
1916
+ * no user text.
1917
+ *
1918
+ * NOT stamped verbatim: a body's last user message is only THIS turn's
1919
+ * question when the client appended it — agent loops resend the whole
1920
+ * history, so a tool-result continuation still ends its user list with the
1921
+ * previous turn's prompt. `turnPromptStamp` adds the positions the read
1922
+ * plane needs to tell those apart.
1923
+ */
1924
+ static extractTurnPrompt(request, cap = 120, hints = {}) {
1925
+ return CaptureRecorder.summarizePromptText(CaptureRecorder.lastUserSlot(request)?.text, cap, hints);
1926
+ }
1927
+ /**
1928
+ * Display-only last user message of a client-request body. Written ONLY on
1929
+ * the request that opened the turn (`isPromptStart`); the turn boundary is
1930
+ * decided structurally at the admission gate, never from this text.
1931
+ *
1932
+ * `hints` scopes the harness vocabulary to the client that sent the bytes
1933
+ * (the writer reads it off the live wire's UA); omitted, only the global
1934
+ * vocabulary plus the structural rules apply.
1524
1935
  */
1525
- static extractTurnPrompt(request, cap = 120) {
1526
- const text = CaptureRecorder.lastUserText(request);
1936
+ static turnPromptStamp(request, cap = 120, hints = {}) {
1937
+ return CaptureRecorder.summarizePromptText(CaptureRecorder.lastUserSlot(request)?.text, cap, hints);
1938
+ }
1939
+ /** Display form of a prompt: newlines flattened, empty bundle text dropped
1940
+ * (a metadata-only turn keeps NO prompt — the timeline renders the
1941
+ * empty-prompt glyph instead of quoting the client's context bundle as
1942
+ * this turn's question), capped with an ellipsis. A declared prompt
1943
+ * (envelope layer 0) is adopted verbatim. */
1944
+ static summarizePromptText(text, cap, hints = {}) {
1945
+ if (hints.declaredPrompt)
1946
+ return CaptureRecorder.clipDisplay(hints.declaredPrompt, cap);
1527
1947
  if (!text)
1528
1948
  return undefined;
1529
- const flat = text.replace(/\s+/g, ' ').trim();
1949
+ const flat = displayPromptText(text, { profile: hints.profile });
1530
1950
  if (!flat)
1531
1951
  return undefined;
1532
- return flat.length <= cap ? flat : flat.slice(0, cap - 1) + '…';
1952
+ return CaptureRecorder.clipDisplay(flat, cap);
1533
1953
  }
1534
1954
  /**
1535
1955
  * System One decision requests evaluate `state` — plain text or a
@@ -1564,53 +1984,71 @@ export class CaptureRecorder {
1564
1984
  static protocolFromRequestLine(requestLine) {
1565
1985
  if (typeof requestLine !== 'string')
1566
1986
  return undefined;
1567
- const m = /^\w+ ([^?\s]+)(?:\?\S*)? HTTP\//.exec(requestLine);
1987
+ // The path segment; tolerates ABSOLUTE-FORM lines (`POST https://host/p?q`
1988
+ // — the MITM client leg) by skipping an optional scheme+authority prefix.
1989
+ const m = /^\w+ (?:[a-z][a-z0-9+.-]*:\/\/[^/?\s]+)?([^?\s]+)(?:\?\S*)? HTTP\//.exec(requestLine);
1568
1990
  if (!m)
1569
1991
  return undefined;
1570
1992
  switch (m[1]) {
1571
1993
  case '/v1/chat/completions':
1572
- return 'chat';
1994
+ return 'openai-chat';
1573
1995
  case '/v1/messages':
1574
- return 'anthropic';
1996
+ return 'anthropic-messages';
1575
1997
  case '/v1/responses':
1576
- return 'responses';
1998
+ return 'openai-responses';
1577
1999
  case '/v1/systemone':
1578
2000
  return 'systemone';
1579
2001
  default:
1580
2002
  return undefined; // anything unrecognized
1581
2003
  }
1582
2004
  }
1583
- static lastUserText(request, depth = 0) {
2005
+ /**
2006
+ * The flattened text of a request body's LAST user slot. Display only:
2007
+ * `promptSummary` never decides a turn boundary. Bodies that are not a
2008
+ * message array still answers text where a surface has an obvious text
2009
+ * channel (plain-string `input`, System One `state`); unparseable bodies
2010
+ * answer none and render the empty-prompt glyph.
2011
+ */
2012
+ static lastUserSlot(request, depth = 0) {
1584
2013
  if (request === null || request === undefined || depth > 2)
1585
2014
  return undefined;
1586
2015
  if (typeof request === 'string') {
1587
- // Same truncation-repair contract as firstUserText.
2016
+ // Same truncation-repair contract as firstHumanUserText.
1588
2017
  const trimmed = request.endsWith(TRUNCATION_SUFFIX)
1589
2018
  ? request.slice(0, -TRUNCATION_SUFFIX.length)
1590
2019
  : request;
1591
2020
  try {
1592
- return CaptureRecorder.lastUserText(JSON.parse(trimmed), depth + 1);
2021
+ return CaptureRecorder.lastUserSlot(JSON.parse(trimmed), depth + 1);
1593
2022
  }
1594
2023
  catch {
1595
2024
  const repaired = CaptureRecorder.repairTruncatedJson(trimmed);
1596
2025
  if (repaired !== null)
1597
- return CaptureRecorder.lastUserText(repaired, depth + 1);
1598
- return trimmed.slice(0, 300);
2026
+ return CaptureRecorder.lastUserSlot(repaired, depth + 1);
2027
+ return { text: trimmed.slice(0, 300) };
1599
2028
  }
1600
2029
  }
1601
2030
  if (typeof request !== 'object')
1602
2031
  return undefined;
1603
2032
  const body = request;
1604
2033
  if (Array.isArray(body.messages))
1605
- return CaptureRecorder.userTextFromMessages(body.messages, 'last');
2034
+ return CaptureRecorder.lastUserSlotInMessages(body.messages);
1606
2035
  if (Array.isArray(body.input))
1607
- return CaptureRecorder.userTextFromMessages(body.input, 'last');
2036
+ return CaptureRecorder.lastUserSlotInMessages(body.input);
1608
2037
  if (typeof body.input === 'string')
1609
- return body.input;
2038
+ return { text: body.input };
1610
2039
  // System One decision surface — evaluated content lives in `state`.
1611
- return CaptureRecorder.stateText(body.state);
2040
+ return { text: CaptureRecorder.stateText(body.state) };
1612
2041
  }
1613
- static firstUserText(request, depth = 0) {
2042
+ /**
2043
+ * The FIRST user message that carries HUMAN text — the client-envelope
2044
+ * normalizer's rules, not the first user-role message. Cursor's agent opens
2045
+ * with a standalone `<user_info>`/`<rules>`/`<mcp_server_catalog>` bundle and
2046
+ * puts the real prompt in the NEXT `<user_query>` message, so taking the
2047
+ * first user role verbatim titled capture sessions with an OS banner. Same
2048
+ * strict-then-permissive rule as the console session title
2049
+ * (`firstDisplayText`), so every surface names a conversation identically.
2050
+ */
2051
+ static firstHumanUserText(request, depth = 0, profile) {
1614
2052
  if (request === null || request === undefined || depth > 2)
1615
2053
  return undefined;
1616
2054
  if (typeof request === 'string') {
@@ -1622,22 +2060,27 @@ export class CaptureRecorder {
1622
2060
  ? request.slice(0, -TRUNCATION_SUFFIX.length)
1623
2061
  : request;
1624
2062
  try {
1625
- return CaptureRecorder.firstUserText(JSON.parse(trimmed), depth + 1);
2063
+ return CaptureRecorder.firstHumanUserText(JSON.parse(trimmed), depth + 1, profile);
1626
2064
  }
1627
2065
  catch {
1628
2066
  const repaired = CaptureRecorder.repairTruncatedJson(trimmed);
1629
- if (repaired !== null)
1630
- return CaptureRecorder.firstUserText(repaired, depth + 1);
2067
+ if (repaired !== null) {
2068
+ return CaptureRecorder.firstHumanUserText(repaired, depth + 1, profile);
2069
+ }
1631
2070
  return trimmed.slice(0, 300);
1632
2071
  }
1633
2072
  }
1634
2073
  if (typeof request !== 'object')
1635
2074
  return undefined;
1636
2075
  const body = request;
1637
- if (Array.isArray(body.messages))
1638
- return CaptureRecorder.userTextFromMessages(body.messages, 'first');
1639
- if (Array.isArray(body.input))
1640
- return CaptureRecorder.userTextFromMessages(body.input, 'first');
2076
+ if (Array.isArray(body.messages)) {
2077
+ return (CaptureRecorder.firstHumanText(body.messages, profile) ??
2078
+ CaptureRecorder.stateText(body.state));
2079
+ }
2080
+ if (Array.isArray(body.input)) {
2081
+ return (CaptureRecorder.firstHumanText(body.input, profile) ??
2082
+ CaptureRecorder.stateText(body.state));
2083
+ }
1641
2084
  if (typeof body.input === 'string')
1642
2085
  return body.input;
1643
2086
  // System One decision surface — evaluated content lives in `state`.
@@ -1694,39 +2137,52 @@ export class CaptureRecorder {
1694
2137
  }
1695
2138
  return null;
1696
2139
  }
1697
- /** First role === 'user' entry; content as string or text-part array. */
1698
- static userTextFromMessages(messages, pick) {
1699
- // Walk forward for 'first', backward for 'last' — the session's opening
1700
- // message anchors the session preview; the LAST user message is the
1701
- // current turn's prompt (history replay means every request carries the
1702
- // full conversation, so the tail is the fresh turn).
1703
- const order = pick === 'first' ? messages : [...messages].reverse();
1704
- for (const m of order) {
1705
- if (!m || typeof m !== 'object')
2140
+ /**
2141
+ * Text of one message's content (string, or joined text parts). Undefined
2142
+ * for non-text content — the callers treat that differently on purpose.
2143
+ */
2144
+ static messageText(m) {
2145
+ if (!m || typeof m !== 'object' || !('content' in m))
2146
+ return undefined;
2147
+ const content = m.content;
2148
+ if (typeof content === 'string')
2149
+ return content;
2150
+ if (!Array.isArray(content))
2151
+ return undefined;
2152
+ const parts = content
2153
+ .map(p => (p && typeof p === 'object' && 'text' in p && typeof p.text === 'string' ? p.text : ''))
2154
+ .filter(Boolean);
2155
+ return parts.length > 0 ? parts.join(' ') : undefined;
2156
+ }
2157
+ /**
2158
+ * The last user message of a message array, flattened to display text.
2159
+ * Pure presentation: turn boundaries are decided structurally by
2160
+ * `classifyTurnBoundary`, never by this text or its position.
2161
+ */
2162
+ static lastUserSlotInMessages(messages) {
2163
+ for (let i = messages.length - 1; i >= 0; i--) {
2164
+ const msg = messages[i];
2165
+ if (!msg || typeof msg !== 'object' || !('role' in msg) || msg.role !== 'user')
1706
2166
  continue;
1707
- const msg = m;
1708
- if (msg.role !== 'user')
2167
+ return { text: CaptureRecorder.messageText(msg) };
2168
+ }
2169
+ return {};
2170
+ }
2171
+ /**
2172
+ * The FIRST user message that carries HUMAN text (client envelopes stripped)
2173
+ * — the capture session preview's opening prompt. Walks forward and skips
2174
+ * metadata-only / image-only messages, exactly like the console title.
2175
+ */
2176
+ static firstHumanText(messages, profile) {
2177
+ const texts = [];
2178
+ for (const msg of messages) {
2179
+ if (!msg || typeof msg !== 'object' || !('role' in msg) || msg.role !== 'user')
1709
2180
  continue;
1710
- const content = msg.content;
1711
- if (typeof content === 'string')
1712
- return content;
1713
- if (Array.isArray(content)) {
1714
- const parts = content
1715
- .map(p => (p && typeof p === 'object' && typeof p.text === 'string' ? p.text : ''))
1716
- .filter(Boolean);
1717
- if (parts.length > 0)
1718
- return parts.join(' ');
1719
- // Non-text parts only. In the backward walk a text-less tail means a
1720
- // tool-result continuation: that user message IS the current turn, so
1721
- // stamping an older user message would mislabel the turn — stop here.
1722
- // The forward walk keeps looking (session preview wants opening text).
1723
- if (pick === 'last')
1724
- return undefined;
1725
- continue; // images etc. — try the next user message
1726
- }
1727
- continue; // missing/non-text content (tool calls etc.) — try the next user message
1728
- }
1729
- return undefined;
2181
+ const text = CaptureRecorder.messageText(msg);
2182
+ if (text)
2183
+ texts.push(text);
2184
+ }
2185
+ return firstDisplayText(texts, 300, { profile });
1730
2186
  }
1731
2187
  /** Local-timezone YYYY-MM-DD — retention is by calendar day as users see it. */
1732
2188
  static localDateDir(d) {