@ashlr/hub 3.11.5 → 3.12.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 (271) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/dist/authority-surface.json +3 -3
  3. package/dist/build-identity.json +2 -2
  4. package/dist/core/authority/trust-roots.js +7 -1
  5. package/dist/core/authority/trust-roots.js.map +1 -1
  6. package/dist/core/universe/builtins/preparation/manifest.json +1 -1
  7. package/dist/core/universe/builtins/preparation/preparation-bridge.mjs +8 -2
  8. package/dist/core/universe/builtins/preparation/preparation-verification-fixtures.mjs +7 -1
  9. package/dist/core/web/public/next/assets/{ActionMenu-DffwPklw.js → ActionMenu-B4-39f2S.js} +2 -2
  10. package/dist/core/web/public/next/assets/{ActionMenu-DffwPklw.js.map → ActionMenu-B4-39f2S.js.map} +1 -1
  11. package/dist/core/web/public/next/assets/{Advanced-CxzE6ekM.js → Advanced-B-LqYXvd.js} +2 -2
  12. package/dist/core/web/public/next/assets/{Advanced-CxzE6ekM.js.map → Advanced-B-LqYXvd.js.map} +1 -1
  13. package/dist/core/web/public/next/assets/{App-DFlp-vdv.js → App-E2zCDRxm.js} +2 -2
  14. package/dist/core/web/public/next/assets/{App-DFlp-vdv.js.map → App-E2zCDRxm.js.map} +1 -1
  15. package/dist/core/web/public/next/assets/{AppsSection-Ct2O605-.js → AppsSection-8wXPPhZb.js} +2 -2
  16. package/dist/core/web/public/next/assets/{AppsSection-Ct2O605-.js.map → AppsSection-8wXPPhZb.js.map} +1 -1
  17. package/dist/core/web/public/next/assets/{AreaTrend-o-GLl2Is.js → AreaTrend-BFimExYn.js} +2 -2
  18. package/dist/core/web/public/next/assets/{AreaTrend-o-GLl2Is.js.map → AreaTrend-BFimExYn.js.map} +1 -1
  19. package/dist/core/web/public/next/assets/{AutonomyOffState-CXhXpsim.js → AutonomyOffState-B5eEkmiz.js} +2 -2
  20. package/dist/core/web/public/next/assets/{AutonomyOffState-CXhXpsim.js.map → AutonomyOffState-B5eEkmiz.js.map} +1 -1
  21. package/dist/core/web/public/next/assets/AutonomySection-B46igJKR.js +2 -0
  22. package/dist/core/web/public/next/assets/{AutonomySection-BTg7yVa1.js.map → AutonomySection-B46igJKR.js.map} +1 -1
  23. package/dist/core/web/public/next/assets/{BranchBar-BjPFtGsj.js → BranchBar-BRkrEQGs.js} +2 -2
  24. package/dist/core/web/public/next/assets/{BranchBar-BjPFtGsj.js.map → BranchBar-BRkrEQGs.js.map} +1 -1
  25. package/dist/core/web/public/next/assets/{BudgetControl-ng6swoZp.js → BudgetControl-T_RjPrw9.js} +2 -2
  26. package/dist/core/web/public/next/assets/{BudgetControl-ng6swoZp.js.map → BudgetControl-T_RjPrw9.js.map} +1 -1
  27. package/dist/core/web/public/next/assets/{Button-OjVJSrFq.js → Button-BhO-WKPp.js} +2 -2
  28. package/dist/core/web/public/next/assets/{Button-OjVJSrFq.js.map → Button-BhO-WKPp.js.map} +1 -1
  29. package/dist/core/web/public/next/assets/{CapacityStrip-Bx4c3dxD.js → CapacityStrip-CkFz5vq2.js} +2 -2
  30. package/dist/core/web/public/next/assets/{CapacityStrip-Bx4c3dxD.js.map → CapacityStrip-CkFz5vq2.js.map} +1 -1
  31. package/dist/core/web/public/next/assets/{ChartFrame-B_w2Siqg.js → ChartFrame-SygZ7B3x.js} +2 -2
  32. package/dist/core/web/public/next/assets/{ChartFrame-B_w2Siqg.js.map → ChartFrame-SygZ7B3x.js.map} +1 -1
  33. package/dist/core/web/public/next/assets/{ChatSection-Bisj9R6E.js → ChatSection-D6WybBpB.js} +3 -3
  34. package/dist/core/web/public/next/assets/{ChatSection-Bisj9R6E.js.map → ChatSection-D6WybBpB.js.map} +1 -1
  35. package/dist/core/web/public/next/assets/{CloudBudgetForm-5Gf4iAok.js → CloudBudgetForm-Bd91iStN.js} +2 -2
  36. package/dist/core/web/public/next/assets/{CloudBudgetForm-5Gf4iAok.js.map → CloudBudgetForm-Bd91iStN.js.map} +1 -1
  37. package/dist/core/web/public/next/assets/{CommandPalette-iTpk6I8r.js → CommandPalette-B6SgDJH-.js} +2 -2
  38. package/dist/core/web/public/next/assets/{CommandPalette-iTpk6I8r.js.map → CommandPalette-B6SgDJH-.js.map} +1 -1
  39. package/dist/core/web/public/next/assets/{CommandSection-D8ZihzvE.js → CommandSection-DgMGoepd.js} +2 -2
  40. package/dist/core/web/public/next/assets/{CommandSection-D8ZihzvE.js.map → CommandSection-DgMGoepd.js.map} +1 -1
  41. package/dist/core/web/public/next/assets/{ConfirmDialog-_S9iE-cJ.js → ConfirmDialog-Bv4hdK2T.js} +2 -2
  42. package/dist/core/web/public/next/assets/{ConfirmDialog-_S9iE-cJ.js.map → ConfirmDialog-Bv4hdK2T.js.map} +1 -1
  43. package/dist/core/web/public/next/assets/{DeleteChatDialog-KUYUygiA.js → DeleteChatDialog-CH1Ix8Eh.js} +2 -2
  44. package/dist/core/web/public/next/assets/{DeleteChatDialog-KUYUygiA.js.map → DeleteChatDialog-CH1Ix8Eh.js.map} +1 -1
  45. package/dist/core/web/public/next/assets/{Dialog-BuIaG6HF.js → Dialog-BSsIFNqD.js} +2 -2
  46. package/dist/core/web/public/next/assets/{Dialog-BuIaG6HF.js.map → Dialog-BSsIFNqD.js.map} +1 -1
  47. package/dist/core/web/public/next/assets/{DiffPane-De4IQt82.js → DiffPane-BpNuJmth.js} +2 -2
  48. package/dist/core/web/public/next/assets/{DiffPane-De4IQt82.js.map → DiffPane-BpNuJmth.js.map} +1 -1
  49. package/dist/core/web/public/next/assets/{DiffViewer-B75t6Ile.js → DiffViewer-CJarUvs0.js} +2 -2
  50. package/dist/core/web/public/next/assets/{DiffViewer-B75t6Ile.js.map → DiffViewer-CJarUvs0.js.map} +1 -1
  51. package/dist/core/web/public/next/assets/{DockHost-BPqyhtCP.js → DockHost-DW9q0NdR.js} +2 -2
  52. package/dist/core/web/public/next/assets/{DockHost-BPqyhtCP.js.map → DockHost-DW9q0NdR.js.map} +1 -1
  53. package/dist/core/web/public/next/assets/{EmptyState-DXkT4vhW.js → EmptyState-DPrd2aak.js} +2 -2
  54. package/dist/core/web/public/next/assets/{EmptyState-DXkT4vhW.js.map → EmptyState-DPrd2aak.js.map} +1 -1
  55. package/dist/core/web/public/next/assets/{Epistemic-CfqFe_aP.js → Epistemic-D7MxSmED.js} +2 -2
  56. package/dist/core/web/public/next/assets/{Epistemic-CfqFe_aP.js.map → Epistemic-D7MxSmED.js.map} +1 -1
  57. package/dist/core/web/public/next/assets/{FleetSection-B7f-XBiX.js → FleetSection-BdZN6rGS.js} +3 -3
  58. package/dist/core/web/public/next/assets/{FleetSection-B7f-XBiX.js.map → FleetSection-BdZN6rGS.js.map} +1 -1
  59. package/dist/core/web/public/next/assets/{Funnel-pXYySwXQ.js → Funnel-BeNQZWv2.js} +2 -2
  60. package/dist/core/web/public/next/assets/{Funnel-pXYySwXQ.js.map → Funnel-BeNQZWv2.js.map} +1 -1
  61. package/dist/core/web/public/next/assets/{GearTray-gj6lT7ba.js → GearTray-CIPtzeIx.js} +2 -2
  62. package/dist/core/web/public/next/assets/{GearTray-gj6lT7ba.js.map → GearTray-CIPtzeIx.js.map} +1 -1
  63. package/dist/core/web/public/next/assets/{GrowthSection-D8e9m9Wy.js → GrowthSection-iiQg6wvK.js} +2 -2
  64. package/dist/core/web/public/next/assets/{GrowthSection-D8e9m9Wy.js.map → GrowthSection-iiQg6wvK.js.map} +1 -1
  65. package/dist/core/web/public/next/assets/{HandoffDialog-VfKxKhxF.js → HandoffDialog-DrQ6ofuy.js} +2 -2
  66. package/dist/core/web/public/next/assets/{HandoffDialog-VfKxKhxF.js.map → HandoffDialog-DrQ6ofuy.js.map} +1 -1
  67. package/dist/core/web/public/next/assets/{Input-u1YR_Ogl.js → Input-C0MQxEM6.js} +2 -2
  68. package/dist/core/web/public/next/assets/{Input-u1YR_Ogl.js.map → Input-C0MQxEM6.js.map} +1 -1
  69. package/dist/core/web/public/next/assets/{LeaderCard-BDELBrnx.js → LeaderCard-BRr3_yE-.js} +2 -2
  70. package/dist/core/web/public/next/assets/{LeaderCard-BDELBrnx.js.map → LeaderCard-BRr3_yE-.js.map} +1 -1
  71. package/dist/core/web/public/next/assets/{MatrixHeatmap-NKLF2srR.js → MatrixHeatmap-DZvZeWXL.js} +2 -2
  72. package/dist/core/web/public/next/assets/{MatrixHeatmap-NKLF2srR.js.map → MatrixHeatmap-DZvZeWXL.js.map} +1 -1
  73. package/dist/core/web/public/next/assets/McpSection-BRuCcTjT.js +2 -0
  74. package/dist/core/web/public/next/assets/{McpSection-D1tDvlRa.js.map → McpSection-BRuCcTjT.js.map} +1 -1
  75. package/dist/core/web/public/next/assets/{MessageMarkdown-DlfLEJxu.js → MessageMarkdown-bRvD5nSc.js} +3 -3
  76. package/dist/core/web/public/next/assets/{MessageMarkdown-DlfLEJxu.js.map → MessageMarkdown-bRvD5nSc.js.map} +1 -1
  77. package/dist/core/web/public/next/assets/{MessageMarkdownRenderer-BYZzI115.js → MessageMarkdownRenderer-FjjkPKA2.js} +2 -2
  78. package/dist/core/web/public/next/assets/{MessageMarkdownRenderer-BYZzI115.js.map → MessageMarkdownRenderer-FjjkPKA2.js.map} +1 -1
  79. package/dist/core/web/public/next/assets/{Meter-BSVhU43Q.js → Meter-CFNLpwA-.js} +2 -2
  80. package/dist/core/web/public/next/assets/{Meter-BSVhU43Q.js.map → Meter-CFNLpwA-.js.map} +1 -1
  81. package/dist/core/web/public/next/assets/{MindSection-lqV2e_Sq.js → MindSection-BTIiQS8P.js} +2 -2
  82. package/dist/core/web/public/next/assets/{MindSection-lqV2e_Sq.js.map → MindSection-BTIiQS8P.js.map} +1 -1
  83. package/dist/core/web/public/next/assets/{MutationTokenDialog-CLGP72g6.js → MutationTokenDialog-T7gv3a9r.js} +2 -2
  84. package/dist/core/web/public/next/assets/{MutationTokenDialog-CLGP72g6.js.map → MutationTokenDialog-T7gv3a9r.js.map} +1 -1
  85. package/dist/core/web/public/next/assets/{NeedsYouDrawer-D992XTOn.js → NeedsYouDrawer-lYN4G_aM.js} +2 -2
  86. package/dist/core/web/public/next/assets/{NeedsYouDrawer-D992XTOn.js.map → NeedsYouDrawer-lYN4G_aM.js.map} +1 -1
  87. package/dist/core/web/public/next/assets/{NeedsYouList-eBOlJr0b.js → NeedsYouList-BgH8ezqf.js} +2 -2
  88. package/dist/core/web/public/next/assets/{NeedsYouList-eBOlJr0b.js.map → NeedsYouList-BgH8ezqf.js.map} +1 -1
  89. package/dist/core/web/public/next/assets/{NewChatDialog-DoYTH26M.js → NewChatDialog-Db5Xjrk8.js} +2 -2
  90. package/dist/core/web/public/next/assets/{NewChatDialog-DoYTH26M.js.map → NewChatDialog-Db5Xjrk8.js.map} +1 -1
  91. package/dist/core/web/public/next/assets/{OnboardingFlow-D3yfITK1.js → OnboardingFlow-LoY-zuSe.js} +2 -2
  92. package/dist/core/web/public/next/assets/{OnboardingFlow-D3yfITK1.js.map → OnboardingFlow-LoY-zuSe.js.map} +1 -1
  93. package/dist/core/web/public/next/assets/OnboardingGate-C4VXn7BJ.js +3 -0
  94. package/dist/core/web/public/next/assets/{OnboardingGate-DrDEVBqw.js.map → OnboardingGate-C4VXn7BJ.js.map} +1 -1
  95. package/dist/core/web/public/next/assets/{PreviewPane-ULN673zm.js → PreviewPane-BPBbcROb.js} +2 -2
  96. package/dist/core/web/public/next/assets/{PreviewPane-ULN673zm.js.map → PreviewPane-BPBbcROb.js.map} +1 -1
  97. package/dist/core/web/public/next/assets/{ProviderLogo-8WaUjTlN.js → ProviderLogo-CT2cSfkg.js} +2 -2
  98. package/dist/core/web/public/next/assets/{ProviderLogo-8WaUjTlN.js.map → ProviderLogo-CT2cSfkg.js.map} +1 -1
  99. package/dist/core/web/public/next/assets/{RailStatus-Ckw9nvYU.js → RailStatus-Vgl0GYtd.js} +2 -2
  100. package/dist/core/web/public/next/assets/{RailStatus-Ckw9nvYU.js.map → RailStatus-Vgl0GYtd.js.map} +1 -1
  101. package/dist/core/web/public/next/assets/{RefreshIndicator-DGubF4vR.js → RefreshIndicator-CSyqpY_q.js} +2 -2
  102. package/dist/core/web/public/next/assets/{RefreshIndicator-DGubF4vR.js.map → RefreshIndicator-CSyqpY_q.js.map} +1 -1
  103. package/dist/core/web/public/next/assets/{ResourcePoolConsoleApp-BahEaY4d.js → ResourcePoolConsoleApp-BX2nkdmZ.js} +2 -2
  104. package/dist/core/web/public/next/assets/{ResourcePoolConsoleApp-BahEaY4d.js.map → ResourcePoolConsoleApp-BX2nkdmZ.js.map} +1 -1
  105. package/dist/core/web/public/next/assets/{ResourcesChrome-C2ZrA7la.js → ResourcesChrome-B2U2lO1H.js} +3 -3
  106. package/dist/core/web/public/next/assets/{ResourcesChrome-C2ZrA7la.js.map → ResourcesChrome-B2U2lO1H.js.map} +1 -1
  107. package/dist/core/web/public/next/assets/{ResourcesDrawer-BC93fzwQ.js → ResourcesDrawer-DlUKOjl9.js} +2 -2
  108. package/dist/core/web/public/next/assets/{ResourcesDrawer-BC93fzwQ.js.map → ResourcesDrawer-DlUKOjl9.js.map} +1 -1
  109. package/dist/core/web/public/next/assets/{RouteErrorBoundary-BvhHNpE_.js → RouteErrorBoundary-BaC7YVzR.js} +2 -2
  110. package/dist/core/web/public/next/assets/{RouteErrorBoundary-BvhHNpE_.js.map → RouteErrorBoundary-BaC7YVzR.js.map} +1 -1
  111. package/dist/core/web/public/next/assets/{RunInCloudAction-Dywfnw0C.js → RunInCloudAction-D5PDHJPE.js} +2 -2
  112. package/dist/core/web/public/next/assets/{RunInCloudAction-Dywfnw0C.js.map → RunInCloudAction-D5PDHJPE.js.map} +1 -1
  113. package/dist/core/web/public/next/assets/{SeatSelector-CH7hTgwy.js → SeatSelector-Cg75LInq.js} +2 -2
  114. package/dist/core/web/public/next/assets/{SeatSelector-CH7hTgwy.js.map → SeatSelector-Cg75LInq.js.map} +1 -1
  115. package/dist/core/web/public/next/assets/{Segmented-Wynbg0F5.js → Segmented-CametjLt.js} +2 -2
  116. package/dist/core/web/public/next/assets/{Segmented-Wynbg0F5.js.map → Segmented-CametjLt.js.map} +1 -1
  117. package/dist/core/web/public/next/assets/{Select-DMyLCkId.js → Select-De52fghU.js} +2 -2
  118. package/dist/core/web/public/next/assets/{Select-DMyLCkId.js.map → Select-De52fghU.js.map} +1 -1
  119. package/dist/core/web/public/next/assets/{SessionGate-8RtQFWeZ.js → SessionGate-CzlcNq3O.js} +2 -2
  120. package/dist/core/web/public/next/assets/{SessionGate-8RtQFWeZ.js.map → SessionGate-CzlcNq3O.js.map} +1 -1
  121. package/dist/core/web/public/next/assets/{SessionInsightChip-zBJbKv2L.js → SessionInsightChip-Bk_Owa7u.js} +2 -2
  122. package/dist/core/web/public/next/assets/{SessionInsightChip-zBJbKv2L.js.map → SessionInsightChip-Bk_Owa7u.js.map} +1 -1
  123. package/dist/core/web/public/next/assets/{SessionSearch-DfJIcxxM.js → SessionSearch-C6C8DHN8.js} +2 -2
  124. package/dist/core/web/public/next/assets/{SessionSearch-DfJIcxxM.js.map → SessionSearch-C6C8DHN8.js.map} +1 -1
  125. package/dist/core/web/public/next/assets/{SettingsSection-Da9RYyH5.js → SettingsSection-mI9wQYZg.js} +2 -2
  126. package/dist/core/web/public/next/assets/{SettingsSection-Da9RYyH5.js.map → SettingsSection-mI9wQYZg.js.map} +1 -1
  127. package/dist/core/web/public/next/assets/{Sheet-DhXyIDmq.js → Sheet-CJhK9Dqv.js} +2 -2
  128. package/dist/core/web/public/next/assets/{Sheet-DhXyIDmq.js.map → Sheet-CJhK9Dqv.js.map} +1 -1
  129. package/dist/core/web/public/next/assets/{ShortcutsOverlay-Bi5f-wUw.js → ShortcutsOverlay-DDW-i9Fc.js} +2 -2
  130. package/dist/core/web/public/next/assets/{ShortcutsOverlay-Bi5f-wUw.js.map → ShortcutsOverlay-DDW-i9Fc.js.map} +1 -1
  131. package/dist/core/web/public/next/assets/{Sidebar-BuO3sViG.js → Sidebar-DT7ykaqS.js} +3 -3
  132. package/dist/core/web/public/next/assets/{Sidebar-BuO3sViG.js.map → Sidebar-DT7ykaqS.js.map} +1 -1
  133. package/dist/core/web/public/next/assets/{Slider-Bd9YFWEV.js → Slider-Bwd9HfXl.js} +2 -2
  134. package/dist/core/web/public/next/assets/{Slider-Bd9YFWEV.js.map → Slider-Bwd9HfXl.js.map} +1 -1
  135. package/dist/core/web/public/next/assets/{StatTile-DScTd3c-.js → StatTile-DPZ5yyaU.js} +2 -2
  136. package/dist/core/web/public/next/assets/{StatTile-DScTd3c-.js.map → StatTile-DPZ5yyaU.js.map} +1 -1
  137. package/dist/core/web/public/next/assets/{StatusBadge-DQ1UtQAJ.js → StatusBadge-DHKRtttH.js} +2 -2
  138. package/dist/core/web/public/next/assets/{StatusBadge-DQ1UtQAJ.js.map → StatusBadge-DHKRtttH.js.map} +1 -1
  139. package/dist/core/web/public/next/assets/{StepBand-BB3IJxhr.js → StepBand-DQykLkk_.js} +2 -2
  140. package/dist/core/web/public/next/assets/{StepBand-BB3IJxhr.js.map → StepBand-DQykLkk_.js.map} +1 -1
  141. package/dist/core/web/public/next/assets/{Surface-DWMtQe3Q.js → Surface-D--LXgQm.js} +2 -2
  142. package/dist/core/web/public/next/assets/{Surface-DWMtQe3Q.js.map → Surface-D--LXgQm.js.map} +1 -1
  143. package/dist/core/web/public/next/assets/{Swimlane-DcENqtdp.js → Swimlane-BzH6OCee.js} +2 -2
  144. package/dist/core/web/public/next/assets/{Swimlane-DcENqtdp.js.map → Swimlane-BzH6OCee.js.map} +1 -1
  145. package/dist/core/web/public/next/assets/{Switch-CenChEYf.js → Switch-PMixU6b0.js} +2 -2
  146. package/dist/core/web/public/next/assets/{Switch-CenChEYf.js.map → Switch-PMixU6b0.js.map} +1 -1
  147. package/dist/core/web/public/next/assets/{Tag-D4k5E3u0.js → Tag-fordBsrJ.js} +2 -2
  148. package/dist/core/web/public/next/assets/{Tag-D4k5E3u0.js.map → Tag-fordBsrJ.js.map} +1 -1
  149. package/dist/core/web/public/next/assets/{TerminalPane-DCQTukcE.js → TerminalPane-BSnGdUuF.js} +2 -2
  150. package/dist/core/web/public/next/assets/{TerminalPane-DCQTukcE.js.map → TerminalPane-BSnGdUuF.js.map} +1 -1
  151. package/dist/core/web/public/next/assets/{UniverseConsoleApp-DsuWT0pi.js → UniverseConsoleApp-DtXFhAhw.js} +2 -2
  152. package/dist/core/web/public/next/assets/{UniverseConsoleApp-DsuWT0pi.js.map → UniverseConsoleApp-DtXFhAhw.js.map} +1 -1
  153. package/dist/core/web/public/next/assets/{UniverseView-DyI5ApsA.js → UniverseView-sWm3pnTW.js} +2 -2
  154. package/dist/core/web/public/next/assets/{UniverseView-DyI5ApsA.js.map → UniverseView-sWm3pnTW.js.map} +1 -1
  155. package/dist/core/web/public/next/assets/{UsageSection-Imr28nwK.js → UsageSection-CiD1DbuF.js} +2 -2
  156. package/dist/core/web/public/next/assets/{UsageSection-Imr28nwK.js.map → UsageSection-CiD1DbuF.js.map} +1 -1
  157. package/dist/core/web/public/next/assets/{VerseConsoleApp-DeuBEvAO.js → VerseConsoleApp-BCY5uSok.js} +3 -3
  158. package/dist/core/web/public/next/assets/{VerseConsoleApp-DeuBEvAO.js.map → VerseConsoleApp-BCY5uSok.js.map} +1 -1
  159. package/dist/core/web/public/next/assets/{Workspace-CpxBO98E.js → Workspace-BQSZFSeO.js} +5 -5
  160. package/dist/core/web/public/next/assets/{Workspace-CpxBO98E.js.map → Workspace-BQSZFSeO.js.map} +1 -1
  161. package/dist/core/web/public/next/assets/{actions-DE8NoWV_.js → actions-Ci6I4C0l.js} +2 -2
  162. package/dist/core/web/public/next/assets/{actions-DE8NoWV_.js.map → actions-Ci6I4C0l.js.map} +1 -1
  163. package/dist/core/web/public/next/assets/{apps-model-CFGCUu9p.js → apps-model-DlwnfqwJ.js} +2 -2
  164. package/dist/core/web/public/next/assets/{apps-model-CFGCUu9p.js.map → apps-model-DlwnfqwJ.js.map} +1 -1
  165. package/dist/core/web/public/next/assets/{authority-model-CmnfJzmM.js → authority-model-BFuPezSo.js} +2 -2
  166. package/dist/core/web/public/next/assets/{authority-model-CmnfJzmM.js.map → authority-model-BFuPezSo.js.map} +1 -1
  167. package/dist/core/web/public/next/assets/{budget-queries-DjrPRFwl.js → budget-queries-DsAjH8ac.js} +2 -2
  168. package/dist/core/web/public/next/assets/{budget-queries-DjrPRFwl.js.map → budget-queries-DsAjH8ac.js.map} +1 -1
  169. package/dist/core/web/public/next/assets/{capacity-strip-model-C7cdQnuK.js → capacity-strip-model-Dn1cNOhz.js} +2 -2
  170. package/dist/core/web/public/next/assets/{capacity-strip-model-C7cdQnuK.js.map → capacity-strip-model-Dn1cNOhz.js.map} +1 -1
  171. package/dist/core/web/public/next/assets/{charts-DUD_jprE.js → charts-C_xJbJiw.js} +2 -2
  172. package/dist/core/web/public/next/assets/{charts-DUD_jprE.js.map → charts-C_xJbJiw.js.map} +1 -1
  173. package/dist/core/web/public/next/assets/{cloud-model-DoxBMDvx.js → cloud-model-CX407gPY.js} +2 -2
  174. package/dist/core/web/public/next/assets/{cloud-model-DoxBMDvx.js.map → cloud-model-CX407gPY.js.map} +1 -1
  175. package/dist/core/web/public/next/assets/{cloud-queries-CTGvO-k-.js → cloud-queries-QAhpExlz.js} +2 -2
  176. package/dist/core/web/public/next/assets/{cloud-queries-CTGvO-k-.js.map → cloud-queries-QAhpExlz.js.map} +1 -1
  177. package/dist/core/web/public/next/assets/{command-catalog-CmrHNFzh.js → command-catalog-CF0cQQac.js} +2 -2
  178. package/dist/core/web/public/next/assets/{command-catalog-CmrHNFzh.js.map → command-catalog-CF0cQQac.js.map} +1 -1
  179. package/dist/core/web/public/next/assets/{context-model-9xywbXxX.js → context-model-Co4wh3SM.js} +2 -2
  180. package/dist/core/web/public/next/assets/{context-model-9xywbXxX.js.map → context-model-Co4wh3SM.js.map} +1 -1
  181. package/dist/core/web/public/next/assets/{context-model-2Owp2jYF.js → context-model-DV1zCfAm.js} +2 -2
  182. package/dist/core/web/public/next/assets/{context-model-2Owp2jYF.js.map → context-model-DV1zCfAm.js.map} +1 -1
  183. package/dist/core/web/public/next/assets/{context-queries-wvcRnV-I.js → context-queries-CktFQqSS.js} +2 -2
  184. package/dist/core/web/public/next/assets/{context-queries-wvcRnV-I.js.map → context-queries-CktFQqSS.js.map} +1 -1
  185. package/dist/core/web/public/next/assets/{control-queries-DB6Kh7UN.js → control-queries-DAvlh_YM.js} +2 -2
  186. package/dist/core/web/public/next/assets/{control-queries-DB6Kh7UN.js.map → control-queries-DAvlh_YM.js.map} +1 -1
  187. package/dist/core/web/public/next/assets/{copy-setup-CJQhFl-4.js → copy-setup-CqRSfELB.js} +2 -2
  188. package/dist/core/web/public/next/assets/{copy-setup-CJQhFl-4.js.map → copy-setup-CqRSfELB.js.map} +1 -1
  189. package/dist/core/web/public/next/assets/{dock-icons-BBUGl4tE.js → dock-icons-BFuBbqJl.js} +2 -2
  190. package/dist/core/web/public/next/assets/{dock-icons-BBUGl4tE.js.map → dock-icons-BFuBbqJl.js.map} +1 -1
  191. package/dist/core/web/public/next/assets/{fleet-model-BRfRWkZl.js → fleet-model-Dfd5JyLR.js} +2 -2
  192. package/dist/core/web/public/next/assets/{fleet-model-BRfRWkZl.js.map → fleet-model-Dfd5JyLR.js.map} +1 -1
  193. package/dist/core/web/public/next/assets/{fleet-queries-tU6UEXN2.js → fleet-queries-RtMTd5rR.js} +2 -2
  194. package/dist/core/web/public/next/assets/{fleet-queries-tU6UEXN2.js.map → fleet-queries-RtMTd5rR.js.map} +1 -1
  195. package/dist/core/web/public/next/assets/{focus-trap-BGOceFvj.js → focus-trap-BdrbWfC4.js} +2 -2
  196. package/dist/core/web/public/next/assets/{focus-trap-BGOceFvj.js.map → focus-trap-BdrbWfC4.js.map} +1 -1
  197. package/dist/core/web/public/next/assets/{format-DEAaVF6X.js → format-Dk4Fmxax.js} +2 -2
  198. package/dist/core/web/public/next/assets/{format-DEAaVF6X.js.map → format-Dk4Fmxax.js.map} +1 -1
  199. package/dist/core/web/public/next/assets/{git-model-53iRLInY.js → git-model-_BnI_Ogh.js} +2 -2
  200. package/dist/core/web/public/next/assets/{git-model-53iRLInY.js.map → git-model-_BnI_Ogh.js.map} +1 -1
  201. package/dist/core/web/public/next/assets/{global-CXHHMz9o.js → global-CNNGMril.js} +2 -2
  202. package/dist/core/web/public/next/assets/{global-CXHHMz9o.js.map → global-CNNGMril.js.map} +1 -1
  203. package/dist/core/web/public/next/assets/{guarded-runners-B8zFVBVZ.js → guarded-runners-DPh2d32e.js} +2 -2
  204. package/dist/core/web/public/next/assets/{guarded-runners-B8zFVBVZ.js.map → guarded-runners-DPh2d32e.js.map} +1 -1
  205. package/dist/core/web/public/next/assets/{icons-D4s-jlxX.js → icons-0haWy6nh.js} +2 -2
  206. package/dist/core/web/public/next/assets/{icons-D4s-jlxX.js.map → icons-0haWy6nh.js.map} +1 -1
  207. package/dist/core/web/public/next/assets/{index-BG177cPN.js → index-QesfXBsb.js} +3 -3
  208. package/dist/core/web/public/next/assets/{index-BG177cPN.js.map → index-QesfXBsb.js.map} +1 -1
  209. package/dist/core/web/public/next/assets/{live-model-CEf01wrW.js → live-model-De-q0ZFK.js} +2 -2
  210. package/dist/core/web/public/next/assets/{live-model-CEf01wrW.js.map → live-model-De-q0ZFK.js.map} +1 -1
  211. package/dist/core/web/public/next/assets/{mind.module-D_xk6HIQ.js → mind.module-BrK2nFOL.js} +2 -2
  212. package/dist/core/web/public/next/assets/{mind.module-D_xk6HIQ.js.map → mind.module-BrK2nFOL.js.map} +1 -1
  213. package/dist/core/web/public/next/assets/{mutations-CbTSofVH.js → mutations-DTCtKCn_.js} +2 -2
  214. package/dist/core/web/public/next/assets/{mutations-CbTSofVH.js.map → mutations-DTCtKCn_.js.map} +1 -1
  215. package/dist/core/web/public/next/assets/{nav-CmZcbPFJ.js → nav-KmGX0CVz.js} +2 -2
  216. package/dist/core/web/public/next/assets/{nav-CmZcbPFJ.js.map → nav-KmGX0CVz.js.map} +1 -1
  217. package/dist/core/web/public/next/assets/{overnight-queries-CR0b_j-V.js → overnight-queries-mlO0xzsr.js} +2 -2
  218. package/dist/core/web/public/next/assets/{overnight-queries-CR0b_j-V.js.map → overnight-queries-mlO0xzsr.js.map} +1 -1
  219. package/dist/core/web/public/next/assets/primitives-D0Fb3TtS.js +1 -0
  220. package/dist/core/web/public/next/assets/{queries-rvRsAGW2.js → queries-CyBE8nsW.js} +2 -2
  221. package/dist/core/web/public/next/assets/{queries-rvRsAGW2.js.map → queries-CyBE8nsW.js.map} +1 -1
  222. package/dist/core/web/public/next/assets/{reasoning-pref-DMPQkujg.js → reasoning-pref-CaoA4_Vl.js} +2 -2
  223. package/dist/core/web/public/next/assets/{reasoning-pref-DMPQkujg.js.map → reasoning-pref-CaoA4_Vl.js.map} +1 -1
  224. package/dist/core/web/public/next/assets/{reveal-anchor-BKk2wZZZ.js → reveal-anchor-BP1VqnPU.js} +2 -2
  225. package/dist/core/web/public/next/assets/{reveal-anchor-BKk2wZZZ.js.map → reveal-anchor-BP1VqnPU.js.map} +1 -1
  226. package/dist/core/web/public/next/assets/{seat-subscription-CLn2ReSZ.js → seat-subscription-C5Tvr0WQ.js} +2 -2
  227. package/dist/core/web/public/next/assets/{seat-subscription-CLn2ReSZ.js.map → seat-subscription-C5Tvr0WQ.js.map} +1 -1
  228. package/dist/core/web/public/next/assets/{sidebar-model-CjQLvdag.js → sidebar-model-B5Qk95k_.js} +2 -2
  229. package/dist/core/web/public/next/assets/{sidebar-model-CjQLvdag.js.map → sidebar-model-B5Qk95k_.js.map} +1 -1
  230. package/dist/core/web/public/next/assets/{slots-DRxNosZg.js → slots-DHKQDoE6.js} +3 -3
  231. package/dist/core/web/public/next/assets/{slots-DRxNosZg.js.map → slots-DHKQDoE6.js.map} +1 -1
  232. package/dist/core/web/public/next/assets/{surface-data-DshUC_TU.js → surface-data-CchClvHo.js} +2 -2
  233. package/dist/core/web/public/next/assets/{surface-data-DshUC_TU.js.map → surface-data-CchClvHo.js.map} +1 -1
  234. package/dist/core/web/public/next/assets/surface-prefetch-BWr0LBQn.js +2 -0
  235. package/dist/core/web/public/next/assets/{surface-prefetch-DO8r4ttQ.js.map → surface-prefetch-BWr0LBQn.js.map} +1 -1
  236. package/dist/core/web/public/next/assets/{tasks-model-BKPFZAmZ.js → tasks-model-D6WFVULI.js} +2 -2
  237. package/dist/core/web/public/next/assets/{tasks-model-BKPFZAmZ.js.map → tasks-model-D6WFVULI.js.map} +1 -1
  238. package/dist/core/web/public/next/assets/{terminal-icons-DoeQkP3y.js → terminal-icons-BvCvuXk2.js} +2 -2
  239. package/dist/core/web/public/next/assets/{terminal-icons-DoeQkP3y.js.map → terminal-icons-BvCvuXk2.js.map} +1 -1
  240. package/dist/core/web/public/next/assets/{usage-queries-MnUeYzwp.js → usage-queries-D1SU1t7r.js} +2 -2
  241. package/dist/core/web/public/next/assets/{usage-queries-MnUeYzwp.js.map → usage-queries-D1SU1t7r.js.map} +1 -1
  242. package/dist/core/web/public/next/assets/{use-guarded-action-P12MfNwU.js → use-guarded-action-BZmBv7CJ.js} +2 -2
  243. package/dist/core/web/public/next/assets/{use-guarded-action-P12MfNwU.js.map → use-guarded-action-BZmBv7CJ.js.map} +1 -1
  244. package/dist/core/web/public/next/assets/{use-ticker-DIvAZ4Ey.js → use-ticker-CkJ4-0wU.js} +2 -2
  245. package/dist/core/web/public/next/assets/{use-ticker-DIvAZ4Ey.js.map → use-ticker-CkJ4-0wU.js.map} +1 -1
  246. package/dist/core/web/public/next/assets/{use-token-gate-DfEja7Wr.js → use-token-gate-CYcfk_GS.js} +2 -2
  247. package/dist/core/web/public/next/assets/{use-token-gate-DfEja7Wr.js.map → use-token-gate-CYcfk_GS.js.map} +1 -1
  248. package/dist/core/web/public/next/assets/{useOnboarding-CkOHadqC.js → useOnboarding-CujRS6PK.js} +2 -2
  249. package/dist/core/web/public/next/assets/{useOnboarding-CkOHadqC.js.map → useOnboarding-CujRS6PK.js.map} +1 -1
  250. package/dist/core/web/public/next/assets/{useSeatsRefresh-BDlbDlIU.js → useSeatsRefresh-BEaQdkZs.js} +2 -2
  251. package/dist/core/web/public/next/assets/{useSeatsRefresh-BDlbDlIU.js.map → useSeatsRefresh-BEaQdkZs.js.map} +1 -1
  252. package/dist/core/web/public/next/assets/{useVerseTranscript-BGtA55k2.js → useVerseTranscript-BQ0J6Xhx.js} +2 -2
  253. package/dist/core/web/public/next/assets/{useVerseTranscript-BGtA55k2.js.map → useVerseTranscript-BQ0J6Xhx.js.map} +1 -1
  254. package/dist/core/web/public/next/assets/{verse-icons-wOet9JZy.js → verse-icons-DndgEgKS.js} +2 -2
  255. package/dist/core/web/public/next/assets/{verse-icons-wOet9JZy.js.map → verse-icons-DndgEgKS.js.map} +1 -1
  256. package/dist/core/web/public/next/assets/{verse-model-CSzzdyu2.js → verse-model-MMySehjj.js} +2 -2
  257. package/dist/core/web/public/next/assets/{verse-model-CSzzdyu2.js.map → verse-model-MMySehjj.js.map} +1 -1
  258. package/dist/core/web/public/next/assets/{warmup-CecO_Nk0.js → warmup-CNEH_-be.js} +3 -3
  259. package/dist/core/web/public/next/assets/{warmup-CecO_Nk0.js.map → warmup-CNEH_-be.js.map} +1 -1
  260. package/dist/core/web/public/next/assets/{why-seat-model-D68ZA7G8.js → why-seat-model-jlDTwYSc.js} +2 -2
  261. package/dist/core/web/public/next/assets/{why-seat-model-D68ZA7G8.js.map → why-seat-model-jlDTwYSc.js.map} +1 -1
  262. package/dist/core/web/public/next/assets/{workspace-model-BdIVybKr.js → workspace-model-Dukb2wwv.js} +2 -2
  263. package/dist/core/web/public/next/assets/{workspace-model-BdIVybKr.js.map → workspace-model-Dukb2wwv.js.map} +1 -1
  264. package/dist/core/web/public/next/index.html +1 -1
  265. package/dist/release-dependency-inventory.json +1 -1
  266. package/package.json +1 -1
  267. package/dist/core/web/public/next/assets/AutonomySection-BTg7yVa1.js +0 -2
  268. package/dist/core/web/public/next/assets/McpSection-D1tDvlRa.js +0 -2
  269. package/dist/core/web/public/next/assets/OnboardingGate-DrDEVBqw.js +0 -3
  270. package/dist/core/web/public/next/assets/primitives-DNI-uJBd.js +0 -1
  271. package/dist/core/web/public/next/assets/surface-prefetch-DO8r4ttQ.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"context-model-9xywbXxX.js","names":[],"sources":["../../../../../../src/web-ui/routes/verse/usage/context-model.ts"],"sourcesContent":["/**\n * routes/verse/usage/context-model.ts — the ONE projection of context facts\n * for every surface that shows a seat: the seat picker's rows, the new-chat\n * dialog's context block, the resources panel's \"This chat\" efficiency block,\n * and the Usage section's per-seat efficiency table.\n *\n * WHY ONE MODULE. Before V3.9 every surface read `seat.contextWindow` (the\n * DEFAULT model's window) or the session's creation-time window, and three of\n * them rendered \"200k\" for a 1M Claude model. The arithmetic now lives in\n * core/verse/context-math.ts, shared with the server; this module is only the\n * wording and the aggregation, so the picker, the dialog and the panel cannot\n * describe one model's budget three different ways.\n *\n * HONESTY RULES this module enforces (docs/VERSE-CONTEXT.md):\n *\n * 1. UNKNOWN IS NOT A NUMBER. A model whose budget is unknown reads \"window\n * unknown\", never a default dressed as a fact. A Verse fallback window is\n * marked \"est.\", and its source says so in words.\n * 2. AN UPPER BOUND IS NOT A MEASUREMENT. Codex's turn total sums every model\n * call; until its rollout is read, occupancy is \"≤ N\", and any statistic\n * built on such a reading carries the same flag.\n * 3. NO CACHE REPORTED IS NOT A 0% HIT RATE. A provider that reported no\n * cache activity at all (Ollama; codex on its very first call) gets \"none\n * reported\", not a 0% that reads \"caching is broken\".\n * 4. NOTHING HERE SPENDS. Every figure is derived from what the server\n * already returned (seats, sessions, the open chat's event log).\n *\n * Pure: no React, no I/O.\n */\nimport {\n CACHE_IDLE_TTL_MS,\n budgetFor,\n cacheHitRatio,\n fitVerdict,\n hasExpansiveMode,\n sessionOverheadTokens,\n} from '../../../../core/verse/context-math.js';\nimport type {\n VerseContextBudget,\n VerseContextFit,\n VerseContextMode,\n VerseEngine,\n VerseEvent,\n VerseFitVerdict,\n VerseModelOption,\n VerseSeat,\n VerseSession,\n VerseUsage,\n VerseWindowSource,\n} from '../../../../core/verse/types.js';\nimport { CODEX_EXPANSIVE_METERING_NOTE, formatContextWindow, modelOptionFor, seatUnavailableReason, sessionContextBudget, WINDOW_SOURCE_TEXT } from '../verse-model.js';\nimport { formatTokens } from '../verse-readouts.js';\nimport { formatWholePercent } from '../autonomy/format.js';\n\n// ---------------------------------------------------------------------------\n// Models and modes\n// ---------------------------------------------------------------------------\n\n/**\n * A seat's option for a model id, matching through the alias table (a chat\n * remembered on `claude-opus-5.5` is the catalog's `claude-opus-5-5`). The\n * lookup itself is verse-model's `modelOptionFor`, the one the context meter\n * uses, so the picker and the meter can never resolve one id two ways.\n */\nexport function seatModelOption(seat: VerseSeat | null | undefined, modelId: string): VerseModelOption | null {\n return seat ? modelOptionFor([seat], { seatId: seat.id, model: modelId }) : null;\n}\n\n/** `mode` when this model has a budget for it, else `standard` — never a mode the CLI cannot be told. */\nexport function resolveContextMode(option: VerseModelOption | null | undefined, mode: VerseContextMode): VerseContextMode {\n return mode !== 'standard' && budgetFor(option, mode) !== null ? mode : 'standard';\n}\n\n/** The budget a model runs with in a mode (resolved), or null when even its standard window is unknown. */\nexport function effectiveBudget(option: VerseModelOption | null | undefined, mode: VerseContextMode): VerseContextBudget | null {\n return budgetFor(option, resolveContextMode(option, mode));\n}\n\n/** Why this model cannot be chosen on this seat, or null when it can. The seat's own outage wins. */\nexport function modelUnavailableReason(seat: VerseSeat, option: VerseModelOption): string | null {\n const seatReason = seatUnavailableReason(seat);\n if (seatReason !== null) return seatReason;\n const reason = option.unavailableReason;\n return typeof reason === 'string' && reason.trim().length > 0 ? reason.trim() : null;\n}\n\nexport const CONTEXT_MODE_LABEL: Record<VerseContextMode, string> = {\n standard: 'Standard',\n expansive: 'Expansive',\n};\n\n/** How each seat's CLI is named when its pinned version is shown. */\nexport const ENGINE_CLI_NAME: Record<VerseEngine, string> = {\n claude: 'Claude Code',\n codex: 'Codex CLI',\n grok: 'Grok CLI',\n local: 'Claude Code',\n};\n\n/** \"Claude Code 2.1.257\" — the binary this seat is pinned to; null when unknown (local seats, old servers). */\nexport function seatCliLine(seat: VerseSeat): string | null {\n const version = typeof seat.cliVersion === 'string' ? seat.cliVersion.trim() : '';\n return version.length > 0 ? `${ENGINE_CLI_NAME[seat.engine]} ${version}` : null;\n}\n\n/** The seat's own plain-language context facts (binary skew, catalog not yet fetched, …). */\nexport function seatContextNotes(seat: VerseSeat): string[] {\n return (seat.notes ?? []).filter((n): n is string => typeof n === 'string' && n.trim().length > 0);\n}\n\n// ---------------------------------------------------------------------------\n// Window provenance\n// ---------------------------------------------------------------------------\n\n// Window provenance wording is verse-model's `WINDOW_SOURCE_TEXT` — the\n// meter's tooltip, the picker and the resources panel all read that one table.\n\nexport function isEstimatedWindow(source: VerseWindowSource | null | undefined): boolean {\n return source === 'fallback';\n}\n\n// ---------------------------------------------------------------------------\n// Picker and dialog wording\n// ---------------------------------------------------------------------------\n\n/**\n * The compact per-model phrase a picker row carries: \"1M ctx · compacts ≈367k\".\n * Uses the budget for `mode` when the model has one, and names the mode only\n * when it is not the default, so an ordinary row stays short.\n */\nexport function modelContextPhrase(option: VerseModelOption, mode: VerseContextMode = 'standard'): string {\n const resolved = resolveContextMode(option, mode);\n const budget = budgetFor(option, resolved);\n if (!budget) return 'window unknown';\n const window = `${formatContextWindow(budget.contextWindow)} ctx${isEstimatedWindow(option.windowSource) ? ' (est.)' : ''}`;\n const compacts = budget.autoCompactAt === null ? '' : ` · compacts ≈${formatTokens(budget.autoCompactAt)}`;\n return `${window}${compacts}${resolved === 'expansive' ? ' (expansive)' : ''}`;\n}\n\n/**\n * The full sentence for a tooltip or the dialog: the window, where each mode\n * compacts, and how the window is known.\n */\nexport function modelContextSentence(option: VerseModelOption): string {\n const standard = budgetFor(option, 'standard');\n const expansive = hasExpansiveMode(option) ? budgetFor(option, 'expansive') : null;\n const parts: string[] = [];\n if (!standard) {\n parts.push('Context window unknown for this model.');\n } else {\n const where = standard.autoCompactAt === null\n ? ''\n : `; compacts at about ${formatTokens(standard.autoCompactAt)}${expansive ? ' in Standard' : ''}`;\n parts.push(`${formatContextWindow(standard.contextWindow)}-token window${where}.`);\n }\n if (expansive) {\n parts.push(`Expansive runs to about ${formatTokens(expansive.autoCompactAt ?? expansive.contextWindow)} before compacting.`);\n }\n if (option.windowSource) parts.push(`Window ${WINDOW_SOURCE_TEXT[option.windowSource]}.`);\n return parts.join(' ');\n}\n\n/**\n * The metering caveat an Expansive cost sentence must carry for this engine,\n * or null when there is none. The wording is verse-model's\n * CODEX_EXPANSIVE_METERING_NOTE — ONE sentence for the new-chat dialog, the\n * handoff dialog, the in-chat mode menu and the \"Expansive could help\" chip.\n * The ratio those surfaces quote (≈3.2× for a 785k vs 245k codex turn) counts\n * re-sent TOKENS only; GPT-5.6-class requests above 272k reportedly also\n * count about 2× against plan limits (docs/VERSE-CONTEXT.md §2.3, a single\n * secondary source), so the note is worded as reported, never as a measured\n * multiplier. Standard never crosses 272k; Expansive does by design.\n */\nexport function expansiveMeteringNote(engine: VerseEngine | null | undefined): string | null {\n return engine === 'codex' ? CODEX_EXPANSIVE_METERING_NOTE : null;\n}\n\n/**\n * \"A turn at 967k re-sends 2.6× the tokens of one at 367k.\" — the only ratio\n * any Expansive cost sentence quotes, and it is arithmetic on the model's own\n * budgets. Null when either compaction point is unknown. It comes BEFORE the\n * codex metering note, whose \"twice that\" refers to it.\n */\nexport function expansiveRatioSentence(option: VerseModelOption | null | undefined): string | null {\n const standard = budgetFor(option, 'standard');\n const expansive = budgetFor(option, 'expansive');\n const stdCap = standard ? standard.autoCompactAt ?? standard.contextWindow : null;\n const expCap = expansive ? expansive.autoCompactAt ?? expansive.contextWindow : null;\n if (stdCap === null || expCap === null || stdCap <= 0) return null;\n return `A turn at ${formatTokens(expCap)} re-sends ${(expCap / stdCap).toFixed(1)}× the tokens of one at ${formatTokens(stdCap)}.`;\n}\n\n/**\n * What each mode costs, in plain words, for the mode selector. Numbers come\n * from the model's own budgets; the only ratio quoted is arithmetic (every\n * turn re-sends everything held, so a turn at X re-sends X/Y of one at Y) —\n * a token ratio, not a usage multiplier, which is why codex also carries the\n * shared metering caveat.\n */\nexport function contextModeDescription(engine: VerseEngine, option: VerseModelOption, mode: VerseContextMode): string {\n const standard = budgetFor(option, 'standard');\n const expansive = budgetFor(option, 'expansive');\n const stdCap = standard ? standard.autoCompactAt ?? standard.contextWindow : null;\n const expCap = expansive ? expansive.autoCompactAt ?? expansive.contextWindow : null;\n if (mode === 'standard' || expCap === null) {\n if (stdCap === null) return 'The CLI compacts at its own default point for this model.';\n return engine === 'claude'\n ? `Compacts at about ${formatTokens(stdCap)}. Every turn re-sends the whole context, so holding it under this point keeps each turn cheaper and recall sharper.`\n : `Compacts at about ${formatTokens(stdCap)} — the CLI's own default budget for this model.`;\n }\n const ratio = expansiveRatioSentence(option);\n const metering = expansiveMeteringNote(engine);\n return `Runs to about ${formatTokens(expCap)} before compacting — for tightly coupled, cross-cutting work that needs everything in view at once. Each turn re-sends everything held, so a long expansive chat uses noticeably more of your plan per turn.${ratio ? ` ${ratio}` : ''}${metering ? ` ${metering}` : ''}`;\n}\n\n/** Why a model offers no mode choice, for the one line where the selector would be. */\nexport function noModeReason(engine: VerseEngine, option: VerseModelOption): string {\n if (!budgetFor(option, 'standard')) return 'This model’s window is unknown, so Verse cannot offer a larger budget for it.';\n if (engine === 'grok' || engine === 'local') return 'One budget: this CLI compacts at its own fixed point, and Verse cannot raise it per chat.';\n return 'One budget: this model has no larger window to expand into.';\n}\n\n// ---------------------------------------------------------------------------\n// Context fit\n// ---------------------------------------------------------------------------\n\n/** Short form for a picker row, where it sits beside the capacity words. */\nexport const FIT_SHORT: Record<VerseFitVerdict, string> = {\n fits: 'code fits',\n tight: 'code fits, tight',\n expansive: 'code needs expansive',\n split: 'code too big — split',\n};\n\n/** Badge text for the chosen model. */\nexport const FIT_LABEL: Record<VerseFitVerdict, string> = {\n fits: 'Fits',\n tight: 'Tight fit',\n expansive: 'Needs expansive',\n split: 'Split the work',\n};\n\n/** A fit reading that is a FLOOR (a root hit its file or time cap). */\nexport function fitIsFloor(fit: VerseContextFit): boolean {\n return fit.roots.some((r) => r.truncated);\n}\n\n/**\n * The verdict for a model IN THE MODE THE CHAT WOULD RUN IN, or null when its\n * budget is unknown (never guessed).\n *\n * `engine` is the seat's engine: the fixed prompt added to the code is that\n * CLI's estimate (context-math `sessionOverheadTokens` — ≈15k local, ≈25k\n * claude), not one flat figure. With a flat 30k a 64k local seat (compacts\n * ≈32.5k) called anything over ~2.5k tokens of code \"too big — split\". Null\n * falls back to the largest estimate.\n *\n * In Standard this is context-math's `fitVerdict` as is — including\n * \"expansive\", the suggestion that only the bigger budget holds the code. In\n * Expansive the bigger budget IS the budget, so the same thresholds are\n * applied to it: the code fits, fits tightly, or no single context on this\n * model holds it. Without this, a chat already set to Expansive would still be\n * told its code \"fits tightly under ≈367k\" — true of a budget it is not using.\n */\nexport function modelFit(\n tokens: number | null | undefined,\n option: VerseModelOption | null | undefined,\n mode: VerseContextMode,\n engine: VerseEngine | null,\n): VerseFitVerdict | null {\n if (typeof tokens !== 'number' || !Number.isFinite(tokens) || tokens < 0) return null;\n const overhead = sessionOverheadTokens(engine);\n if (resolveContextMode(option, mode) === 'expansive' && option) {\n const expansive = budgetFor(option, 'expansive')!;\n return fitVerdict(tokens, { ...option, contextWindow: expansive.contextWindow, autoCompactAt: expansive.autoCompactAt, expansive: null }, overhead);\n }\n return fitVerdict(tokens, option, overhead);\n}\n\n/**\n * The sentence under the fit badge, for the verdict `modelFit` gave in the\n * chat's mode. In Standard a tight fit also names the Expansive budget when\n * one exists, and \"needs expansive\" says what to do — suggestions only;\n * nothing here switches the mode.\n */\nexport function fitExplanation(input: {\n verdict: VerseFitVerdict;\n tokens: number;\n option: VerseModelOption;\n mode: VerseContextMode;\n floor?: boolean;\n}): string {\n const amount = `${input.floor ? 'at least ' : ''}~${formatTokens(input.tokens)} tokens of tracked code`;\n const inExpansive = resolveContextMode(input.option, input.mode) === 'expansive';\n const standard = budgetFor(input.option, 'standard');\n const expansive = budgetFor(input.option, 'expansive');\n const stdCap = standard ? formatTokens(standard.autoCompactAt ?? standard.contextWindow) : null;\n const expCap = expansive ? formatTokens(expansive.autoCompactAt ?? expansive.contextWindow) : null;\n const cap = inExpansive ? expCap : stdCap;\n const budget = inExpansive ? 'Expansive budget' : 'budget';\n switch (input.verdict) {\n case 'fits':\n return `All ${amount} fits well inside this model's ${budget}${cap ? ` (compacts ≈${cap})` : ''}, with room left for the conversation.`;\n case 'tight': {\n const roomier = !inExpansive && expCap !== null && hasExpansiveMode(input.option)\n ? ` Expansive (≈${expCap}) would hold it with room to spare.`\n : '';\n return `${capitalize(amount)} fits under the ≈${cap ?? '?'} compaction point${inExpansive ? ' of the Expansive budget' : ''}, with little room for the conversation — expect it to compact if the agent reads widely.${roomier}`;\n }\n case 'expansive':\n return `${capitalize(amount)} is more than the Standard budget (≈${stdCap ?? '?'}) holds; only Expansive (≈${expCap ?? '?'}) takes it all. Switch to Expansive, or narrow the folders to the part you are changing.`;\n case 'split':\n return `${capitalize(amount)} is more than any single context on this model holds${expCap ? `, even Expansive (≈${expCap})` : ''}. Split the work: fan it out across several chats, each scoped to one folder or subsystem, or narrow this chat to the part you are changing.`;\n }\n}\n\n/**\n * How the working-set figure is made — shown once, beside the badge. Names the\n * fixed-prompt figure the verdict added, and calls it an estimate: no CLI\n * reports its base prompt before a turn has run.\n */\nexport function fitMethodNote(engine: VerseEngine | null): string {\n const cli = engine ? ` for ${ENGINE_CLI_NAME[engine]}` : '';\n return `Estimated from the size of tracked text files (bytes ÷ 4), plus an estimated ~${formatTokens(sessionOverheadTokens(engine))} of fixed prompt${cli} that every chat starts with. An upper bound — agents rarely read everything.`;\n}\n\nfunction capitalize(text: string): string {\n return text.length === 0 ? text : text.charAt(0).toUpperCase() + text.slice(1);\n}\n\n// ---------------------------------------------------------------------------\n// One session's context\n// ---------------------------------------------------------------------------\n\nexport interface SessionContextView {\n tokens: number;\n /** False when `tokens` is an upper bound (codex before its rollout is read). */\n exact: boolean;\n window: number | null;\n autoCompactAt: number | null;\n /** How the window is known; null when nothing says (no window, or a stored one without provenance). */\n source: VerseWindowSource | null;\n mode: VerseContextMode;\n /** The session's model has a real expansive budget on its seat. */\n hasModes: boolean;\n}\n\n/**\n * The window a session is measured against, by the precedence every surface\n * shares — runtime → the seat's CURRENT catalog budget for the model and mode\n * → what the record stored → the seat default. The precedence itself lives in\n * verse-model's `sessionContextBudget` (the context meter reads it too); this\n * only adds whether the model offers a second mode, for the panels here.\n */\nexport function sessionContext(session: VerseSession, seats: readonly VerseSeat[]): SessionContextView {\n const budget = sessionContextBudget(seats, session);\n return {\n tokens: Math.floor(budget.contextTokens),\n exact: budget.exact,\n window: budget.contextWindow,\n autoCompactAt: budget.autoCompactAt,\n source: budget.source,\n mode: budget.mode,\n hasModes: hasExpansiveMode(budget.option),\n };\n}\n\n/**\n * Cache-hit ratio, except when the provider reported no cache activity at all\n * — then null (\"none reported\"), because 0% would claim caching failed when\n * the truth is that nothing was said about it.\n */\nexport function reportedCacheHitRatio(usage: Pick<VerseUsage, 'inputTokens' | 'cacheReadTokens' | 'cacheCreationTokens'>): number | null {\n if (usage.cacheReadTokens <= 0 && usage.cacheCreationTokens <= 0) return null;\n return cacheHitRatio(usage);\n}\n\n/** A 0–1 ratio as a whole percent; a real sliver reads \"<1%\", never \"0%\". */\nexport function formatRatio(ratio: number | null): string {\n if (ratio === null || !Number.isFinite(ratio)) return '—';\n return formatWholePercent(ratio);\n}\n\nexport interface TurnContextStats {\n /** Turns with at least one context reading. */\n turns: number;\n /** Mean of each turn's context (its largest trustworthy reading); null with no turns. */\n average: number | null;\n /** Largest per-turn context seen. */\n peak: number | null;\n /** False when any counted turn had only an upper-bound reading. */\n exact: boolean;\n /** Compactions recorded in the log. */\n compactions: number;\n /** Cache-hit ratio of the most recent turn (see `reportedCacheHitRatio`). */\n lastTurnCacheHit: number | null;\n}\n\n/**\n * Context per turn from the open chat's event log.\n *\n * A turn's context is its LARGEST trustworthy reading: within one turn the\n * prompt only grows, except across a compaction, and the peak is what the\n * turn actually paid for. Exact readings (`context` events, usage frames not\n * flagged as upper bounds) win; a turn whose only reading is codex's turn\n * total contributes that total and flags the statistic as an upper bound —\n * that figure can be many times the real prompt, so it is never mixed in\n * where an exact one exists.\n */\nexport function turnContextStats(events: readonly VerseEvent[]): TurnContextStats {\n const perTurn = new Map<string, { exact: number | null; bound: number | null }>();\n let compactions = 0;\n let lastUsage: VerseUsage | null = null;\n const note = (turnId: string, tokens: number, exact: boolean): void => {\n if (!Number.isFinite(tokens) || tokens < 0) return;\n const entry = perTurn.get(turnId) ?? { exact: null, bound: null };\n if (exact) entry.exact = Math.max(entry.exact ?? 0, tokens);\n else entry.bound = Math.max(entry.bound ?? 0, tokens);\n perTurn.set(turnId, entry);\n };\n for (const event of events) {\n switch (event.type) {\n case 'usage':\n lastUsage = event.usage;\n note(event.turnId, event.usage.contextTokens, event.usage.contextTokensExact !== false);\n break;\n case 'context':\n if (event.turnId !== null) note(event.turnId, event.contextTokens, event.exact);\n break;\n case 'compaction':\n compactions += 1;\n break;\n default:\n break;\n }\n }\n let sum = 0;\n let peak: number | null = null;\n let exact = true;\n let turns = 0;\n for (const entry of perTurn.values()) {\n const value = entry.exact ?? entry.bound;\n if (value === null) continue;\n if (entry.exact === null) exact = false;\n turns += 1;\n sum += value;\n peak = peak === null ? value : Math.max(peak, value);\n }\n return {\n turns,\n average: turns === 0 ? null : Math.round(sum / turns),\n peak,\n exact,\n compactions,\n lastTurnCacheHit: lastUsage === null ? null : reportedCacheHitRatio(lastUsage),\n };\n}\n\nexport interface IdleCacheWarning {\n idleMs: number;\n tokens: number;\n /** A local model: the cost is time, not spend. */\n local: boolean;\n}\n\n/**\n * The next turn of an idle chat re-reads its whole context uncached once the\n * provider's prompt cache has expired (CACHE_IDLE_TTL_MS). Below the fixed\n * prompt every new chat on this engine pays anyway (its estimate) there is\n * nothing worth warning about.\n */\nexport function idleCacheWarning(\n session: Pick<VerseSession, 'status' | 'engine'>,\n tokens: number,\n now: number,\n /**\n * When the chat last TALKED to its provider (`lastTurnActivityAt(events)`),\n * never `session.updatedAt`: a rename or mode switch moves that without\n * warming the provider's cache. Null (no turn yet / log not loaded) → no warning.\n */\n lastActivityAt: string | null,\n): IdleCacheWarning | null {\n if (session.status === 'running' || lastActivityAt === null) return null;\n const last = Date.parse(lastActivityAt);\n if (!Number.isFinite(last)) return null;\n const idleMs = now - last;\n if (idleMs < CACHE_IDLE_TTL_MS || tokens < sessionOverheadTokens(session.engine)) return null;\n return { idleMs, tokens, local: session.engine === 'local' };\n}\n\n// ---------------------------------------------------------------------------\n// Per-seat efficiency across sessions (Usage section)\n// ---------------------------------------------------------------------------\n\nexport interface SeatEfficiencyRow {\n seatId: string;\n label: string;\n engine: VerseEngine;\n /** The seat is no longer in the roster (its sessions remain on disk). */\n retired: boolean;\n sessions: number;\n turns: number;\n /** input + cache read + cache write: every prompt token the seat was sent. */\n promptTokens: number;\n outputTokens: number;\n /** Null when the provider reported no cache activity on any of these sessions. */\n cacheHitRatio: number | null;\n compactions: number;\n expansiveSessions: number;\n /** The fullest context among these sessions right now, as a share of its window. */\n fullest: { sessionId: string; title: string; tokens: number; window: number | null; exact: boolean } | null;\n}\n\n/**\n * \"Fullest\" is a share of the window when both windows are known; a context\n * with a known window outranks one without (its fullness is a fact, the other\n * a size); two unknown windows compare by size.\n */\nfunction fuller(a: NonNullable<SeatEfficiencyRow['fullest']>, b: NonNullable<SeatEfficiencyRow['fullest']>): boolean {\n if (a.window !== null && b.window !== null) return a.tokens / a.window > b.tokens / b.window;\n if (a.window !== null) return true;\n if (b.window !== null) return false;\n return a.tokens > b.tokens;\n}\n\n/**\n * Aggregate every session by seat. Ratios are computed from SUMS, never as a\n * mean of per-session ratios — a two-turn chat must not weigh as much as a\n * two-hundred-turn one. Seats with no sessions are omitted rather than shown\n * as zeros. Sorted by prompt tokens, largest first: that is where efficiency\n * matters most.\n */\nexport function seatEfficiency(sessions: readonly VerseSession[], seats: readonly VerseSeat[]): SeatEfficiencyRow[] {\n const bySeat = new Map<string, VerseSession[]>();\n for (const s of sessions) {\n const list = bySeat.get(s.seatId) ?? [];\n list.push(s);\n bySeat.set(s.seatId, list);\n }\n const rows: SeatEfficiencyRow[] = [];\n for (const [seatId, list] of bySeat) {\n const seat = seats.find((s) => s.id === seatId) ?? null;\n let input = 0;\n let read = 0;\n let write = 0;\n let output = 0;\n let turns = 0;\n let compactions = 0;\n let expansiveSessions = 0;\n let fullest: SeatEfficiencyRow['fullest'] = null;\n for (const s of list) {\n input += s.usage.inputTokens;\n read += s.usage.cacheReadTokens;\n write += s.usage.cacheCreationTokens;\n output += s.usage.outputTokens;\n turns += s.turnCount;\n compactions += s.compactionCount ?? 0;\n // The mode as the meter resolves it (verse-model sessionContextBudget),\n // counted before the empty-reading skip: the mode is a fact about the\n // chat, not about its reading.\n const view = sessionContext(s, seats);\n if (view.mode === 'expansive') expansiveSessions += 1;\n if (view.tokens <= 0) continue;\n const candidate = { sessionId: s.id, title: s.title, tokens: view.tokens, window: view.window, exact: view.exact };\n if (fullest === null || fuller(candidate, fullest)) fullest = candidate;\n }\n rows.push({\n seatId,\n label: seat?.label ?? seatId,\n engine: seat?.engine ?? list[0]!.engine,\n retired: seat === null,\n sessions: list.length,\n turns,\n promptTokens: input + read + write,\n outputTokens: output,\n cacheHitRatio: reportedCacheHitRatio({ inputTokens: input, cacheReadTokens: read, cacheCreationTokens: write }),\n compactions,\n expansiveSessions,\n fullest,\n });\n }\n return rows.sort((a, b) => b.promptTokens - a.promptTokens || a.label.localeCompare(b.label));\n}\n"],"mappings":"oKAgEA,SAAgB,EAAgB,EAAoC,EAA0C,CAC5G,OAAO,EAAO,EAAe,CAAC,CAAI,EAAG,CAAE,OAAQ,EAAK,GAAI,MAAO,CAAQ,CAAC,EAAI,IAC9E,CAGA,SAAgB,EAAmB,EAA6C,EAA0C,CACxH,OAAO,IAAS,YAAc,EAAU,EAAQ,CAAI,IAAM,KAAO,EAAO,UAC1E,CAGA,SAAgB,EAAgB,E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,OAAQ,GAAM,QAAU,EAAK,EAAE,CAAE,OACjC,QAAS,IAAS,KAClB,SAAU,EAAK,OACf,QACA,aAAc,EAAQ,EAAO,EAC7B,aAAc,EACd,cAAe,EAAsB,CAAE,YAAa,EAAO,gBAAiB,EAAM,oBAAqB,CAAM,CAAC,EAC9G,cACA,oBACA,SACF,CAAC,CACH,CACA,OAAO,EAAK,MAAM,EAAG,IAAM,EAAE,aAAe,EAAE,cAAgB,EAAE,MAAM,cAAc,EAAE,KAAK,CAAC,CAC9F"}
1
+ {"version":3,"file":"context-model-Co4wh3SM.js","names":[],"sources":["../../../../../../src/web-ui/routes/verse/usage/context-model.ts"],"sourcesContent":["/**\n * routes/verse/usage/context-model.ts — the ONE projection of context facts\n * for every surface that shows a seat: the seat picker's rows, the new-chat\n * dialog's context block, the resources panel's \"This chat\" efficiency block,\n * and the Usage section's per-seat efficiency table.\n *\n * WHY ONE MODULE. Before V3.9 every surface read `seat.contextWindow` (the\n * DEFAULT model's window) or the session's creation-time window, and three of\n * them rendered \"200k\" for a 1M Claude model. The arithmetic now lives in\n * core/verse/context-math.ts, shared with the server; this module is only the\n * wording and the aggregation, so the picker, the dialog and the panel cannot\n * describe one model's budget three different ways.\n *\n * HONESTY RULES this module enforces (docs/VERSE-CONTEXT.md):\n *\n * 1. UNKNOWN IS NOT A NUMBER. A model whose budget is unknown reads \"window\n * unknown\", never a default dressed as a fact. A Verse fallback window is\n * marked \"est.\", and its source says so in words.\n * 2. AN UPPER BOUND IS NOT A MEASUREMENT. Codex's turn total sums every model\n * call; until its rollout is read, occupancy is \"≤ N\", and any statistic\n * built on such a reading carries the same flag.\n * 3. NO CACHE REPORTED IS NOT A 0% HIT RATE. A provider that reported no\n * cache activity at all (Ollama; codex on its very first call) gets \"none\n * reported\", not a 0% that reads \"caching is broken\".\n * 4. NOTHING HERE SPENDS. Every figure is derived from what the server\n * already returned (seats, sessions, the open chat's event log).\n *\n * Pure: no React, no I/O.\n */\nimport {\n CACHE_IDLE_TTL_MS,\n budgetFor,\n cacheHitRatio,\n fitVerdict,\n hasExpansiveMode,\n sessionOverheadTokens,\n} from '../../../../core/verse/context-math.js';\nimport type {\n VerseContextBudget,\n VerseContextFit,\n VerseContextMode,\n VerseEngine,\n VerseEvent,\n VerseFitVerdict,\n VerseModelOption,\n VerseSeat,\n VerseSession,\n VerseUsage,\n VerseWindowSource,\n} from '../../../../core/verse/types.js';\nimport { CODEX_EXPANSIVE_METERING_NOTE, formatContextWindow, modelOptionFor, seatUnavailableReason, sessionContextBudget, WINDOW_SOURCE_TEXT } from '../verse-model.js';\nimport { formatTokens } from '../verse-readouts.js';\nimport { formatWholePercent } from '../autonomy/format.js';\n\n// ---------------------------------------------------------------------------\n// Models and modes\n// ---------------------------------------------------------------------------\n\n/**\n * A seat's option for a model id, matching through the alias table (a chat\n * remembered on `claude-opus-5.5` is the catalog's `claude-opus-5-5`). The\n * lookup itself is verse-model's `modelOptionFor`, the one the context meter\n * uses, so the picker and the meter can never resolve one id two ways.\n */\nexport function seatModelOption(seat: VerseSeat | null | undefined, modelId: string): VerseModelOption | null {\n return seat ? modelOptionFor([seat], { seatId: seat.id, model: modelId }) : null;\n}\n\n/** `mode` when this model has a budget for it, else `standard` — never a mode the CLI cannot be told. */\nexport function resolveContextMode(option: VerseModelOption | null | undefined, mode: VerseContextMode): VerseContextMode {\n return mode !== 'standard' && budgetFor(option, mode) !== null ? mode : 'standard';\n}\n\n/** The budget a model runs with in a mode (resolved), or null when even its standard window is unknown. */\nexport function effectiveBudget(option: VerseModelOption | null | undefined, mode: VerseContextMode): VerseContextBudget | null {\n return budgetFor(option, resolveContextMode(option, mode));\n}\n\n/** Why this model cannot be chosen on this seat, or null when it can. The seat's own outage wins. */\nexport function modelUnavailableReason(seat: VerseSeat, option: VerseModelOption): string | null {\n const seatReason = seatUnavailableReason(seat);\n if (seatReason !== null) return seatReason;\n const reason = option.unavailableReason;\n return typeof reason === 'string' && reason.trim().length > 0 ? reason.trim() : null;\n}\n\nexport const CONTEXT_MODE_LABEL: Record<VerseContextMode, string> = {\n standard: 'Standard',\n expansive: 'Expansive',\n};\n\n/** How each seat's CLI is named when its pinned version is shown. */\nexport const ENGINE_CLI_NAME: Record<VerseEngine, string> = {\n claude: 'Claude Code',\n codex: 'Codex CLI',\n grok: 'Grok CLI',\n local: 'Claude Code',\n};\n\n/** \"Claude Code 2.1.257\" — the binary this seat is pinned to; null when unknown (local seats, old servers). */\nexport function seatCliLine(seat: VerseSeat): string | null {\n const version = typeof seat.cliVersion === 'string' ? seat.cliVersion.trim() : '';\n return version.length > 0 ? `${ENGINE_CLI_NAME[seat.engine]} ${version}` : null;\n}\n\n/** The seat's own plain-language context facts (binary skew, catalog not yet fetched, …). */\nexport function seatContextNotes(seat: VerseSeat): string[] {\n return (seat.notes ?? []).filter((n): n is string => typeof n === 'string' && n.trim().length > 0);\n}\n\n// ---------------------------------------------------------------------------\n// Window provenance\n// ---------------------------------------------------------------------------\n\n// Window provenance wording is verse-model's `WINDOW_SOURCE_TEXT` — the\n// meter's tooltip, the picker and the resources panel all read that one table.\n\nexport function isEstimatedWindow(source: VerseWindowSource | null | undefined): boolean {\n return source === 'fallback';\n}\n\n// ---------------------------------------------------------------------------\n// Picker and dialog wording\n// ---------------------------------------------------------------------------\n\n/**\n * The compact per-model phrase a picker row carries: \"1M ctx · compacts ≈367k\".\n * Uses the budget for `mode` when the model has one, and names the mode only\n * when it is not the default, so an ordinary row stays short.\n */\nexport function modelContextPhrase(option: VerseModelOption, mode: VerseContextMode = 'standard'): string {\n const resolved = resolveContextMode(option, mode);\n const budget = budgetFor(option, resolved);\n if (!budget) return 'window unknown';\n const window = `${formatContextWindow(budget.contextWindow)} ctx${isEstimatedWindow(option.windowSource) ? ' (est.)' : ''}`;\n const compacts = budget.autoCompactAt === null ? '' : ` · compacts ≈${formatTokens(budget.autoCompactAt)}`;\n return `${window}${compacts}${resolved === 'expansive' ? ' (expansive)' : ''}`;\n}\n\n/**\n * The full sentence for a tooltip or the dialog: the window, where each mode\n * compacts, and how the window is known.\n */\nexport function modelContextSentence(option: VerseModelOption): string {\n const standard = budgetFor(option, 'standard');\n const expansive = hasExpansiveMode(option) ? budgetFor(option, 'expansive') : null;\n const parts: string[] = [];\n if (!standard) {\n parts.push('Context window unknown for this model.');\n } else {\n const where = standard.autoCompactAt === null\n ? ''\n : `; compacts at about ${formatTokens(standard.autoCompactAt)}${expansive ? ' in Standard' : ''}`;\n parts.push(`${formatContextWindow(standard.contextWindow)}-token window${where}.`);\n }\n if (expansive) {\n parts.push(`Expansive runs to about ${formatTokens(expansive.autoCompactAt ?? expansive.contextWindow)} before compacting.`);\n }\n if (option.windowSource) parts.push(`Window ${WINDOW_SOURCE_TEXT[option.windowSource]}.`);\n return parts.join(' ');\n}\n\n/**\n * The metering caveat an Expansive cost sentence must carry for this engine,\n * or null when there is none. The wording is verse-model's\n * CODEX_EXPANSIVE_METERING_NOTE — ONE sentence for the new-chat dialog, the\n * handoff dialog, the in-chat mode menu and the \"Expansive could help\" chip.\n * The ratio those surfaces quote (≈3.2× for a 785k vs 245k codex turn) counts\n * re-sent TOKENS only; GPT-5.6-class requests above 272k reportedly also\n * count about 2× against plan limits (docs/VERSE-CONTEXT.md §2.3, a single\n * secondary source), so the note is worded as reported, never as a measured\n * multiplier. Standard never crosses 272k; Expansive does by design.\n */\nexport function expansiveMeteringNote(engine: VerseEngine | null | undefined): string | null {\n return engine === 'codex' ? CODEX_EXPANSIVE_METERING_NOTE : null;\n}\n\n/**\n * \"A turn at 967k re-sends 2.6× the tokens of one at 367k.\" — the only ratio\n * any Expansive cost sentence quotes, and it is arithmetic on the model's own\n * budgets. Null when either compaction point is unknown. It comes BEFORE the\n * codex metering note, whose \"twice that\" refers to it.\n */\nexport function expansiveRatioSentence(option: VerseModelOption | null | undefined): string | null {\n const standard = budgetFor(option, 'standard');\n const expansive = budgetFor(option, 'expansive');\n const stdCap = standard ? standard.autoCompactAt ?? standard.contextWindow : null;\n const expCap = expansive ? expansive.autoCompactAt ?? expansive.contextWindow : null;\n if (stdCap === null || expCap === null || stdCap <= 0) return null;\n return `A turn at ${formatTokens(expCap)} re-sends ${(expCap / stdCap).toFixed(1)}× the tokens of one at ${formatTokens(stdCap)}.`;\n}\n\n/**\n * What each mode costs, in plain words, for the mode selector. Numbers come\n * from the model's own budgets; the only ratio quoted is arithmetic (every\n * turn re-sends everything held, so a turn at X re-sends X/Y of one at Y) —\n * a token ratio, not a usage multiplier, which is why codex also carries the\n * shared metering caveat.\n */\nexport function contextModeDescription(engine: VerseEngine, option: VerseModelOption, mode: VerseContextMode): string {\n const standard = budgetFor(option, 'standard');\n const expansive = budgetFor(option, 'expansive');\n const stdCap = standard ? standard.autoCompactAt ?? standard.contextWindow : null;\n const expCap = expansive ? expansive.autoCompactAt ?? expansive.contextWindow : null;\n if (mode === 'standard' || expCap === null) {\n if (stdCap === null) return 'The CLI compacts at its own default point for this model.';\n return engine === 'claude'\n ? `Compacts at about ${formatTokens(stdCap)}. Every turn re-sends the whole context, so holding it under this point keeps each turn cheaper and recall sharper.`\n : `Compacts at about ${formatTokens(stdCap)} — the CLI's own default budget for this model.`;\n }\n const ratio = expansiveRatioSentence(option);\n const metering = expansiveMeteringNote(engine);\n return `Runs to about ${formatTokens(expCap)} before compacting — for tightly coupled, cross-cutting work that needs everything in view at once. Each turn re-sends everything held, so a long expansive chat uses noticeably more of your plan per turn.${ratio ? ` ${ratio}` : ''}${metering ? ` ${metering}` : ''}`;\n}\n\n/** Why a model offers no mode choice, for the one line where the selector would be. */\nexport function noModeReason(engine: VerseEngine, option: VerseModelOption): string {\n if (!budgetFor(option, 'standard')) return 'This model’s window is unknown, so Verse cannot offer a larger budget for it.';\n if (engine === 'grok' || engine === 'local') return 'One budget: this CLI compacts at its own fixed point, and Verse cannot raise it per chat.';\n return 'One budget: this model has no larger window to expand into.';\n}\n\n// ---------------------------------------------------------------------------\n// Context fit\n// ---------------------------------------------------------------------------\n\n/** Short form for a picker row, where it sits beside the capacity words. */\nexport const FIT_SHORT: Record<VerseFitVerdict, string> = {\n fits: 'code fits',\n tight: 'code fits, tight',\n expansive: 'code needs expansive',\n split: 'code too big — split',\n};\n\n/** Badge text for the chosen model. */\nexport const FIT_LABEL: Record<VerseFitVerdict, string> = {\n fits: 'Fits',\n tight: 'Tight fit',\n expansive: 'Needs expansive',\n split: 'Split the work',\n};\n\n/** A fit reading that is a FLOOR (a root hit its file or time cap). */\nexport function fitIsFloor(fit: VerseContextFit): boolean {\n return fit.roots.some((r) => r.truncated);\n}\n\n/**\n * The verdict for a model IN THE MODE THE CHAT WOULD RUN IN, or null when its\n * budget is unknown (never guessed).\n *\n * `engine` is the seat's engine: the fixed prompt added to the code is that\n * CLI's estimate (context-math `sessionOverheadTokens` — ≈15k local, ≈25k\n * claude), not one flat figure. With a flat 30k a 64k local seat (compacts\n * ≈32.5k) called anything over ~2.5k tokens of code \"too big — split\". Null\n * falls back to the largest estimate.\n *\n * In Standard this is context-math's `fitVerdict` as is — including\n * \"expansive\", the suggestion that only the bigger budget holds the code. In\n * Expansive the bigger budget IS the budget, so the same thresholds are\n * applied to it: the code fits, fits tightly, or no single context on this\n * model holds it. Without this, a chat already set to Expansive would still be\n * told its code \"fits tightly under ≈367k\" — true of a budget it is not using.\n */\nexport function modelFit(\n tokens: number | null | undefined,\n option: VerseModelOption | null | undefined,\n mode: VerseContextMode,\n engine: VerseEngine | null,\n): VerseFitVerdict | null {\n if (typeof tokens !== 'number' || !Number.isFinite(tokens) || tokens < 0) return null;\n const overhead = sessionOverheadTokens(engine);\n if (resolveContextMode(option, mode) === 'expansive' && option) {\n const expansive = budgetFor(option, 'expansive')!;\n return fitVerdict(tokens, { ...option, contextWindow: expansive.contextWindow, autoCompactAt: expansive.autoCompactAt, expansive: null }, overhead);\n }\n return fitVerdict(tokens, option, overhead);\n}\n\n/**\n * The sentence under the fit badge, for the verdict `modelFit` gave in the\n * chat's mode. In Standard a tight fit also names the Expansive budget when\n * one exists, and \"needs expansive\" says what to do — suggestions only;\n * nothing here switches the mode.\n */\nexport function fitExplanation(input: {\n verdict: VerseFitVerdict;\n tokens: number;\n option: VerseModelOption;\n mode: VerseContextMode;\n floor?: boolean;\n}): string {\n const amount = `${input.floor ? 'at least ' : ''}~${formatTokens(input.tokens)} tokens of tracked code`;\n const inExpansive = resolveContextMode(input.option, input.mode) === 'expansive';\n const standard = budgetFor(input.option, 'standard');\n const expansive = budgetFor(input.option, 'expansive');\n const stdCap = standard ? formatTokens(standard.autoCompactAt ?? standard.contextWindow) : null;\n const expCap = expansive ? formatTokens(expansive.autoCompactAt ?? expansive.contextWindow) : null;\n const cap = inExpansive ? expCap : stdCap;\n const budget = inExpansive ? 'Expansive budget' : 'budget';\n switch (input.verdict) {\n case 'fits':\n return `All ${amount} fits well inside this model's ${budget}${cap ? ` (compacts ≈${cap})` : ''}, with room left for the conversation.`;\n case 'tight': {\n const roomier = !inExpansive && expCap !== null && hasExpansiveMode(input.option)\n ? ` Expansive (≈${expCap}) would hold it with room to spare.`\n : '';\n return `${capitalize(amount)} fits under the ≈${cap ?? '?'} compaction point${inExpansive ? ' of the Expansive budget' : ''}, with little room for the conversation — expect it to compact if the agent reads widely.${roomier}`;\n }\n case 'expansive':\n return `${capitalize(amount)} is more than the Standard budget (≈${stdCap ?? '?'}) holds; only Expansive (≈${expCap ?? '?'}) takes it all. Switch to Expansive, or narrow the folders to the part you are changing.`;\n case 'split':\n return `${capitalize(amount)} is more than any single context on this model holds${expCap ? `, even Expansive (≈${expCap})` : ''}. Split the work: fan it out across several chats, each scoped to one folder or subsystem, or narrow this chat to the part you are changing.`;\n }\n}\n\n/**\n * How the working-set figure is made — shown once, beside the badge. Names the\n * fixed-prompt figure the verdict added, and calls it an estimate: no CLI\n * reports its base prompt before a turn has run.\n */\nexport function fitMethodNote(engine: VerseEngine | null): string {\n const cli = engine ? ` for ${ENGINE_CLI_NAME[engine]}` : '';\n return `Estimated from the size of tracked text files (bytes ÷ 4), plus an estimated ~${formatTokens(sessionOverheadTokens(engine))} of fixed prompt${cli} that every chat starts with. An upper bound — agents rarely read everything.`;\n}\n\nfunction capitalize(text: string): string {\n return text.length === 0 ? text : text.charAt(0).toUpperCase() + text.slice(1);\n}\n\n// ---------------------------------------------------------------------------\n// One session's context\n// ---------------------------------------------------------------------------\n\nexport interface SessionContextView {\n tokens: number;\n /** False when `tokens` is an upper bound (codex before its rollout is read). */\n exact: boolean;\n window: number | null;\n autoCompactAt: number | null;\n /** How the window is known; null when nothing says (no window, or a stored one without provenance). */\n source: VerseWindowSource | null;\n mode: VerseContextMode;\n /** The session's model has a real expansive budget on its seat. */\n hasModes: boolean;\n}\n\n/**\n * The window a session is measured against, by the precedence every surface\n * shares — runtime → the seat's CURRENT catalog budget for the model and mode\n * → what the record stored → the seat default. The precedence itself lives in\n * verse-model's `sessionContextBudget` (the context meter reads it too); this\n * only adds whether the model offers a second mode, for the panels here.\n */\nexport function sessionContext(session: VerseSession, seats: readonly VerseSeat[]): SessionContextView {\n const budget = sessionContextBudget(seats, session);\n return {\n tokens: Math.floor(budget.contextTokens),\n exact: budget.exact,\n window: budget.contextWindow,\n autoCompactAt: budget.autoCompactAt,\n source: budget.source,\n mode: budget.mode,\n hasModes: hasExpansiveMode(budget.option),\n };\n}\n\n/**\n * Cache-hit ratio, except when the provider reported no cache activity at all\n * — then null (\"none reported\"), because 0% would claim caching failed when\n * the truth is that nothing was said about it.\n */\nexport function reportedCacheHitRatio(usage: Pick<VerseUsage, 'inputTokens' | 'cacheReadTokens' | 'cacheCreationTokens'>): number | null {\n if (usage.cacheReadTokens <= 0 && usage.cacheCreationTokens <= 0) return null;\n return cacheHitRatio(usage);\n}\n\n/** A 0–1 ratio as a whole percent; a real sliver reads \"<1%\", never \"0%\". */\nexport function formatRatio(ratio: number | null): string {\n if (ratio === null || !Number.isFinite(ratio)) return '—';\n return formatWholePercent(ratio);\n}\n\nexport interface TurnContextStats {\n /** Turns with at least one context reading. */\n turns: number;\n /** Mean of each turn's context (its largest trustworthy reading); null with no turns. */\n average: number | null;\n /** Largest per-turn context seen. */\n peak: number | null;\n /** False when any counted turn had only an upper-bound reading. */\n exact: boolean;\n /** Compactions recorded in the log. */\n compactions: number;\n /** Cache-hit ratio of the most recent turn (see `reportedCacheHitRatio`). */\n lastTurnCacheHit: number | null;\n}\n\n/**\n * Context per turn from the open chat's event log.\n *\n * A turn's context is its LARGEST trustworthy reading: within one turn the\n * prompt only grows, except across a compaction, and the peak is what the\n * turn actually paid for. Exact readings (`context` events, usage frames not\n * flagged as upper bounds) win; a turn whose only reading is codex's turn\n * total contributes that total and flags the statistic as an upper bound —\n * that figure can be many times the real prompt, so it is never mixed in\n * where an exact one exists.\n */\nexport function turnContextStats(events: readonly VerseEvent[]): TurnContextStats {\n const perTurn = new Map<string, { exact: number | null; bound: number | null }>();\n let compactions = 0;\n let lastUsage: VerseUsage | null = null;\n const note = (turnId: string, tokens: number, exact: boolean): void => {\n if (!Number.isFinite(tokens) || tokens < 0) return;\n const entry = perTurn.get(turnId) ?? { exact: null, bound: null };\n if (exact) entry.exact = Math.max(entry.exact ?? 0, tokens);\n else entry.bound = Math.max(entry.bound ?? 0, tokens);\n perTurn.set(turnId, entry);\n };\n for (const event of events) {\n switch (event.type) {\n case 'usage':\n lastUsage = event.usage;\n note(event.turnId, event.usage.contextTokens, event.usage.contextTokensExact !== false);\n break;\n case 'context':\n if (event.turnId !== null) note(event.turnId, event.contextTokens, event.exact);\n break;\n case 'compaction':\n compactions += 1;\n break;\n default:\n break;\n }\n }\n let sum = 0;\n let peak: number | null = null;\n let exact = true;\n let turns = 0;\n for (const entry of perTurn.values()) {\n const value = entry.exact ?? entry.bound;\n if (value === null) continue;\n if (entry.exact === null) exact = false;\n turns += 1;\n sum += value;\n peak = peak === null ? value : Math.max(peak, value);\n }\n return {\n turns,\n average: turns === 0 ? null : Math.round(sum / turns),\n peak,\n exact,\n compactions,\n lastTurnCacheHit: lastUsage === null ? null : reportedCacheHitRatio(lastUsage),\n };\n}\n\nexport interface IdleCacheWarning {\n idleMs: number;\n tokens: number;\n /** A local model: the cost is time, not spend. */\n local: boolean;\n}\n\n/**\n * The next turn of an idle chat re-reads its whole context uncached once the\n * provider's prompt cache has expired (CACHE_IDLE_TTL_MS). Below the fixed\n * prompt every new chat on this engine pays anyway (its estimate) there is\n * nothing worth warning about.\n */\nexport function idleCacheWarning(\n session: Pick<VerseSession, 'status' | 'engine'>,\n tokens: number,\n now: number,\n /**\n * When the chat last TALKED to its provider (`lastTurnActivityAt(events)`),\n * never `session.updatedAt`: a rename or mode switch moves that without\n * warming the provider's cache. Null (no turn yet / log not loaded) → no warning.\n */\n lastActivityAt: string | null,\n): IdleCacheWarning | null {\n if (session.status === 'running' || lastActivityAt === null) return null;\n const last = Date.parse(lastActivityAt);\n if (!Number.isFinite(last)) return null;\n const idleMs = now - last;\n if (idleMs < CACHE_IDLE_TTL_MS || tokens < sessionOverheadTokens(session.engine)) return null;\n return { idleMs, tokens, local: session.engine === 'local' };\n}\n\n// ---------------------------------------------------------------------------\n// Per-seat efficiency across sessions (Usage section)\n// ---------------------------------------------------------------------------\n\nexport interface SeatEfficiencyRow {\n seatId: string;\n label: string;\n engine: VerseEngine;\n /** The seat is no longer in the roster (its sessions remain on disk). */\n retired: boolean;\n sessions: number;\n turns: number;\n /** input + cache read + cache write: every prompt token the seat was sent. */\n promptTokens: number;\n outputTokens: number;\n /** Null when the provider reported no cache activity on any of these sessions. */\n cacheHitRatio: number | null;\n compactions: number;\n expansiveSessions: number;\n /** The fullest context among these sessions right now, as a share of its window. */\n fullest: { sessionId: string; title: string; tokens: number; window: number | null; exact: boolean } | null;\n}\n\n/**\n * \"Fullest\" is a share of the window when both windows are known; a context\n * with a known window outranks one without (its fullness is a fact, the other\n * a size); two unknown windows compare by size.\n */\nfunction fuller(a: NonNullable<SeatEfficiencyRow['fullest']>, b: NonNullable<SeatEfficiencyRow['fullest']>): boolean {\n if (a.window !== null && b.window !== null) return a.tokens / a.window > b.tokens / b.window;\n if (a.window !== null) return true;\n if (b.window !== null) return false;\n return a.tokens > b.tokens;\n}\n\n/**\n * Aggregate every session by seat. Ratios are computed from SUMS, never as a\n * mean of per-session ratios — a two-turn chat must not weigh as much as a\n * two-hundred-turn one. Seats with no sessions are omitted rather than shown\n * as zeros. Sorted by prompt tokens, largest first: that is where efficiency\n * matters most.\n */\nexport function seatEfficiency(sessions: readonly VerseSession[], seats: readonly VerseSeat[]): SeatEfficiencyRow[] {\n const bySeat = new Map<string, VerseSession[]>();\n for (const s of sessions) {\n const list = bySeat.get(s.seatId) ?? [];\n list.push(s);\n bySeat.set(s.seatId, list);\n }\n const rows: SeatEfficiencyRow[] = [];\n for (const [seatId, list] of bySeat) {\n const seat = seats.find((s) => s.id === seatId) ?? null;\n let input = 0;\n let read = 0;\n let write = 0;\n let output = 0;\n let turns = 0;\n let compactions = 0;\n let expansiveSessions = 0;\n let fullest: SeatEfficiencyRow['fullest'] = null;\n for (const s of list) {\n input += s.usage.inputTokens;\n read += s.usage.cacheReadTokens;\n write += s.usage.cacheCreationTokens;\n output += s.usage.outputTokens;\n turns += s.turnCount;\n compactions += s.compactionCount ?? 0;\n // The mode as the meter resolves it (verse-model sessionContextBudget),\n // counted before the empty-reading skip: the mode is a fact about the\n // chat, not about its reading.\n const view = sessionContext(s, seats);\n if (view.mode === 'expansive') expansiveSessions += 1;\n if (view.tokens <= 0) continue;\n const candidate = { sessionId: s.id, title: s.title, tokens: view.tokens, window: view.window, exact: view.exact };\n if (fullest === null || fuller(candidate, fullest)) fullest = candidate;\n }\n rows.push({\n seatId,\n label: seat?.label ?? seatId,\n engine: seat?.engine ?? list[0]!.engine,\n retired: seat === null,\n sessions: list.length,\n turns,\n promptTokens: input + read + write,\n outputTokens: output,\n cacheHitRatio: reportedCacheHitRatio({ inputTokens: input, cacheReadTokens: read, cacheCreationTokens: write }),\n compactions,\n expansiveSessions,\n fullest,\n });\n }\n return rows.sort((a, b) => b.promptTokens - a.promptTokens || a.label.localeCompare(b.label));\n}\n"],"mappings":"oK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AAa,GAAqB,GAChD,EAAK,QAAU,EAAG,SACtB,IAAM,EAAY,CAAE,UAAW,EAAE,GAAI,MAAO,EAAE,MAAO,OAAQ,EAAK,OAAQ,OAAQ,EAAK,OAAQ,MAAO,EAAK,KAAM,GAC7G,IAAY,MAAQ,EAAO,EAAW,CAAO,KAAG,EAAU,EAChE,CACA,EAAK,KAAK,CACR,SACA,MAAO,GAAM,OAAS,EACtB,OAAQ,GAAM,QAAU,EAAK,EAAE,CAAE,OACjC,QAAS,IAAS,KAClB,SAAU,EAAK,OACf,QACA,aAAc,EAAQ,EAAO,EAC7B,aAAc,EACd,cAAe,EAAsB,CAAE,YAAa,EAAO,gBAAiB,EAAM,oBAAqB,CAAM,CAAC,EAC9G,cACA,oBACA,SACF,CAAC,CACH,CACA,OAAO,EAAK,MAAM,EAAG,IAAM,EAAE,aAAe,EAAE,cAAgB,EAAE,MAAM,cAAc,EAAE,KAAK,CAAC,CAC9F"}
@@ -1,3 +1,3 @@
1
- import{B as e,D as t,H as n,I as r,M as i,P as a,R as o,l as s,o as c}from"./verse-model-CSzzdyu2.js";import"./transient-events-nTLhMBND.js";import{_ as l,t as u,y as d}from"./format-DEAaVF6X.js";var f=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],p=65536,m=12e3,h=[`This conversation is about to continue in a fresh session that has none of its context.`,`Write the handoff note that new session should start from. Do not edit files or run commands for this — only write the note.`,``,`Cover, concretely:`,`- The goal, and what "done" looks like.`,`- Decisions made so far, each with the reason it was made.`,`- Current state: what is finished, what is half-done, what is untested.`,`- Files changed and anything not yet committed.`,`- How to verify the work (exact commands).`,`- Open questions, risks, and approaches already tried that did not work.`,``,`Keep it under 600 words. Prefer file paths and commands over prose.`].join(`
1
+ import{B as e,D as t,H as n,I as r,M as i,P as a,R as o,l as s,o as c}from"./verse-model-MMySehjj.js";import"./transient-events-nTLhMBND.js";import{_ as l,t as u,y as d}from"./format-Dk4Fmxax.js";var f=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],p=65536,m=12e3,h=[`This conversation is about to continue in a fresh session that has none of its context.`,`Write the handoff note that new session should start from. Do not edit files or run commands for this — only write the note.`,``,`Cover, concretely:`,`- The goal, and what "done" looks like.`,`- Decisions made so far, each with the reason it was made.`,`- Current state: what is finished, what is half-done, what is untested.`,`- Files changed and anything not yet committed.`,`- How to verify the work (exact commands).`,`- Open questions, risks, and approaches already tried that did not work.`,``,`Keep it under 600 words. Prefer file paths and commands over prose.`].join(`
2
2
  `),g=65536,_=139264,v=6144,y=/\s·\spart\s(\d+)$/;function b(e){let t=e.replace(/\s+/g,` `).trim(),n=y.exec(t),r=(n?t.slice(0,n.index):t)||`Untitled chat`,i=` · part ${n?Number.parseInt(n[1],10)+1:2}`,a=120-i.length;return`${r.length>a?`${r.slice(0,a-1).trimEnd()}…`:r}${i}`}function x(e,t){if(!e)return null;let n=e.models.find(e=>e.id===t);if(n)return n;let r=a(t);return e.models.find(e=>a(e.id)===r)??null}function S(e,t,n=Date.now()){return e?e.health.state===`unavailable`?`${e.label} is unavailable: ${u(d(e.health.summary??`no reason given`,n))}.`:t?t.unavailableReason?`${t.label} cannot run on ${e.label}: ${u(d(t.unavailableReason,n))}.`:null:`Pick a model on this seat.`:`Pick a seat to continue on.`}function C(e,t){let n=e.find(e=>e.id===t.seatId);if(n&&n.health.state!==`unavailable`){let e=x(n,t.model);if(e&&!e.unavailableReason)return{seatId:n.id,model:e.id};let r=n.models.find(e=>!e.unavailableReason);if(r)return{seatId:n.id,model:r.id}}for(let t of e){if(t.health.state===`unavailable`)continue;let e=t.models.find(e=>!e.unavailableReason);if(e)return{seatId:t.id,model:e.id}}return null}function w(e){let{option:t,target:n,source:r,preferences:o}=e,s=e=>e!==void 0&&i(t,e)!==null;if(n!==null&&n.seatId===r.seatId&&a(n.model)===a(r.model)&&s(r.contextMode??`standard`))return r.contextMode??`standard`;let c=n?o?.seats[n.seatId]?.contextMode:void 0;return s(c)?c:`standard`}function T(e,t){return i(e,t)===null?void 0:t}function E(e,n){let r=i(e,n);if(!r)return null;let a=`${c(r.contextWindow)} window`;return r.autoCompactAt===null?a:`${a} · compacts ≈${t(r.autoCompactAt)}`}function D(e,a,s,c){let u=r(e),d=n(c),f=u+d,p=o(u,a,d),m=`~${t(u)} tokens of handoff + an estimated ~${t(d)} of fixed prompt`,h=i(a,`standard`),g=h?h.autoCompactAt??h.contextWindow:null,_={verdict:p,handoffTokens:u,overheadTokens:d,needTokens:f};switch(p){case`fits`:return{..._,tone:`ok`,text:`Fits: ${m} leaves most of the budget before the first compaction.`};case`tight`:return{..._,tone:`warn`,text:`Tight: ${m} is ${l(f/(g??f)*100)} of where this model compacts — the new chat will compact early.`};case`expansive`:return s===`expansive`?{..._,tone:`warn`,text:`Fits only the expansive budget: ${m}.`}:{..._,tone:`danger`,text:`Too big for the standard budget (${m}). Switch to Expansive, or trim the handoff.`};case`split`:return{..._,tone:`danger`,text:`Too big for one context on this model (${m}). Trim the handoff or pick a seat with a larger window.`};default:return{..._,verdict:null,tone:`unknown`,text:`This model’s window is not known, so there is no fit estimate.`}}}function O(t){return e(t)}function k(e,t){return e===`local`?`Runs on this machine with ${t}; it spends no subscription usage.`:`Sends one turn to ${t} and spends from its usage. The automatic preview costs nothing.`}var A=typeof TextEncoder==`function`?new TextEncoder:null;function j(e){if(A)return A.encode(e).length;let t=0;for(let n of e){let e=n.codePointAt(0)??0;t+=e<128?1:e<2048?2:e<65536?3:4}return t}var M=65536,N=_;function P(e){return j(JSON.stringify(e)??``)}function F(e){if(!Number.isFinite(e)||e<0)return`—`;if(e<1024)return`${e} B`;let t=e/1024;return`${t<10?t.toFixed(1).replace(/\.0$/,``):Math.round(t)} KB`}function I(e,t=Date.now()){if(!e)return null;let n=s(e,t);return n?n===`now`?`just now`:/^\d+[mhd]$/.test(n)?`${n} ago`:`on ${n}`:null}var L=[{label:`a private key`,re:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{label:`an Anthropic API key`,re:/\bsk-ant-[A-Za-z0-9_-]{20,}/},{label:`an OpenAI-style API key`,re:/\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/},{label:`an xAI API key`,re:/\bxai-[A-Za-z0-9]{32,}/},{label:`a GitHub token`,re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}|\bgithub_pat_[A-Za-z0-9_]{40,}/},{label:`an AWS access key`,re:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/},{label:`a Slack token`,re:/\bxox[abprs]-[A-Za-z0-9-]{10,}/},{label:`a Google API key`,re:/\bAIza[0-9A-Za-z_-]{35}\b/},{label:`a Stripe secret key`,re:/\b(?:sk|rk)_live_[0-9A-Za-z]{20,}/}],R=v,z=`Reading and editing memory here spends nothing. On a paid seat it is not free to use: each new chat’s system prompt carries a memory block of up to ${R/1024} KB, re-sent every turn (cached after the first), and the agent reads and updates MEMORY.md as it works. Local seats spend nothing.`;function B(e){for(let{label:t,re:n}of L)if(n.test(e))return t;return null}var V=`[REDACTED]`;function H(e){return e.split(V).length-1}function U(e){let t=[];for(let n of e.toLowerCase().split(/\s+/))n&&!t.includes(n)&&t.push(n);return t}function W(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function G(e,t){let n=[...t].filter(e=>e.length>0).sort((e,t)=>t.length-e.length);if(n.length===0||e.length===0)return e?[{text:e,match:!1}]:[];let r=new RegExp(n.map(W).join(`|`),`gi`),i=[],a=0;for(let t of e.matchAll(r)){let n=t.index??0;t[0].length!==0&&(n>a&&i.push({text:e.slice(a,n),match:!1}),i.push({text:t[0],match:!0}),a=n+t[0].length)}return a<e.length&&i.push({text:e.slice(a),match:!1}),i}function K(e){let t=new Map;for(let n of e){let e=t.get(n.sessionId);if(!e){t.set(n.sessionId,{sessionId:n.sessionId,title:n.title,projectPath:n.projectPath,engine:n.engine,top:n,count:1,latestAt:n.at});continue}e.count+=1,n.at>e.latestAt&&(e.latestAt=n.at)}return[...t.values()]}export{k as C,h as D,m as E,p as O,S,f as T,H as _,V as a,U as b,C as c,D as d,b as f,O as g,x as h,z as i,g as k,F as l,P as m,R as n,E as o,G as p,N as r,w as s,M as t,K as u,I as v,j as w,B as x,T as y};
3
- //# sourceMappingURL=context-model-2Owp2jYF.js.map
3
+ //# sourceMappingURL=context-model-DV1zCfAm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-model-2Owp2jYF.js","names":[],"sources":["../../../../../../src/core/verse/types.ts","../../../../../../src/web-ui/routes/verse/context/context-model.ts"],"sourcesContent":["/**\n * Ashlr Verse — interactive multi-turn session contract (V1).\n *\n * A Verse session binds one project directory to one execution seat\n * (engine + account + model). Each user turn spawns ONE vendor CLI process\n * that resumes the vendor-native conversation by id, streams normalized\n * events, and exits. No long-lived stdin is held between turns.\n *\n * Seats:\n * claude -> `claude -p ... --output-format stream-json` via a native-profile launcher (account pinned by CLAUDE_CONFIG_DIR)\n * local -> the plain `claude` binary with ANTHROPIC_BASE_URL pointed at Ollama (Anthropic-compatible API); model = Ollama tag\n * codex -> `codex exec --json` / `codex exec resume <threadId> --json` via a native-profile launcher (CODEX_HOME pinned)\n * grok -> `grok -p ... --output-format streaming-messages-json` via a native-profile launcher (GROK_HOME pinned)\n *\n * Nothing in this module reads secrets. Account identity is pinned by the\n * launcher command recorded in ~/.ashlr/account-connections/connections.json.\n */\nimport type { TRANSIENT_EVENT_TYPE_LIST } from './transient-events.js';\n\nexport type VerseEngine = 'claude' | 'codex' | 'grok' | 'local';\n\nexport type VerseSessionStatus = 'idle' | 'running' | 'error';\n\n/** One selectable execution seat shown in the model/account picker. */\nexport interface VerseSeat {\n /** Stable id, e.g. `claude`, `codex-personal`, `grok`, `local:qwen3-coder-next:ctx64k`. */\n id: string;\n engine: VerseEngine;\n /** Human label, e.g. \"Claude Code\", \"Personal Codex\", \"Grok\", \"Qwen3-Coder-Next (local)\". */\n label: string;\n /** Account id from connections.json for native seats; `local` for Ollama seats. */\n accountId: string;\n /** Models this seat can run. First entry is the default. */\n models: VerseModelOption[];\n /** Best-known context window in tokens for the default model (null when unknown). */\n contextWindow: number | null;\n /** Latest health/usage evidence, if any. Never an admission input in V1. */\n health: VerseSeatHealth;\n /**\n * V2.1 ADDITIVE. The subscription capacity behind this seat, so the seat\n * list can render a meter without a second request.\n *\n * Absent (`undefined`) for LOCAL seats: an Ollama tag has no subscription\n * and no provider window. Its real constraint is machine memory, which is\n * reported by `VerseBootstrap.localRuntime`, not by a quota. Absent on a\n * native seat means the server could not build a record for that account\n * at all — `health.state` says what it does know.\n */\n capacity?: VerseSeatCapacity;\n /**\n * V3.9 ADDITIVE. The version of the CLI binary this seat is PINNED to (its\n * native-profile launcher execs one exact file). Absent when unknown and on\n * local seats. A pinned binary never updates itself, so a model that needs a\n * newer CLI is listed with `unavailableReason` rather than silently failing.\n */\n cliVersion?: string;\n /**\n * V3.9 ADDITIVE. Plain-language facts about this seat's context setup the UI\n * must show rather than imply (binary skew, catalog not yet fetched, …).\n * Absent when there is nothing to say, so ordinary seats keep their shape.\n */\n notes?: string[];\n}\n\n/**\n * Where a context-window figure came from, so nothing on screen implies more\n * certainty than it has (docs/VERSE-CONTEXT.md §1).\n *\n * - `runtime` — the CLI reported it for THIS turn (claude/grok\n * `result.modelUsage.<m>.contextWindow`, codex rollout\n * `token_count.info.model_context_window`, Ollama\n * `/api/ps`). Wins over everything else.\n * - `provider-catalog` — the seat's own served catalog on disk (codex/grok\n * `native-state/models_cache.json`).\n * - `cli-catalog` — read out of the pinned CLI binary's embedded catalog\n * and recorded here with the version it was read from.\n * - `documented` — the provider's published model table.\n * - `fallback` — a named default; the UI marks it as an estimate.\n */\nexport type VerseWindowSource = 'runtime' | 'provider-catalog' | 'cli-catalog' | 'documented' | 'fallback';\n\n/**\n * How much context a session is allowed to accumulate before the CLI compacts.\n *\n * - `standard` — the default. Evidence-based budget per engine: Claude 1M\n * models compact near 400k instead of ~967k; Codex, Grok and\n * local run their native windows.\n * - `expansive` — opt-in. Claude runs its full native window (CLI `auto`),\n * Codex raises `model_context_window` to the model's catalog\n * maximum (872k on GPT-6 / GPT-5.6). Costs more usage per turn,\n * buys simultaneous visibility for coupled, cross-cutting work.\n *\n * A mode that does not exist for a model (Grok, local, 200k Claude models,\n * GPT-5.5) is simply absent from that model's option — never faked.\n */\nexport type VerseContextMode = 'standard' | 'expansive';\n\nexport const VERSE_CONTEXT_MODES: readonly VerseContextMode[] = ['standard', 'expansive'];\n\n/** One mode's budget for a model on a seat. */\nexport interface VerseContextBudget {\n /** The window the CLI measures against in this mode (the meter's denominator). */\n contextWindow: number;\n /** Token count at which the CLI auto-compacts in this mode; null when unknown. */\n autoCompactAt: number | null;\n /**\n * The RAW window value the CLI must be TOLD to reach this budget, when that\n * differs from `contextWindow` — codex measures against 95% of the window it\n * is configured with, so expansive GPT-6 is `providerWindow: 872_000`\n * (`-c model_context_window=872000`) but `contextWindow: 828_400`.\n */\n providerWindow?: number | null;\n}\n\nexport interface VerseModelOption {\n id: string;\n label: string;\n /** Standard-mode window the CLI measures against (codex: the 95% effective window). */\n contextWindow: number | null;\n /**\n * V3.9 ADDITIVE — every field below is optional so records and fixtures\n * written before it keep validating. Absent means \"not known\", never zero.\n */\n /** Standard-mode auto-compaction point. */\n autoCompactAt?: number | null;\n /** Present ONLY when this model on this seat has a real expansive mode. */\n expansive?: VerseContextBudget | null;\n /** The CLI's default max output for this model, when known. */\n maxOutputTokens?: number | null;\n windowSource?: VerseWindowSource;\n /** Minimum CLI version that knows this model id (e.g. '2.1.280'); null when any. */\n minCliVersion?: string | null;\n /**\n * Why this model cannot run on this seat right now, in plain language (e.g.\n * \"needs Claude Code 2.1.280; this seat runs 2.1.257\"). Null/absent = runnable.\n * Listed rather than hidden so the operator learns WHY a model is missing.\n */\n unavailableReason?: string | null;\n}\n\nexport interface VerseSeatHealth {\n state: 'ready' | 'degraded' | 'unavailable' | 'unknown';\n /** e.g. \"5h window 72% used, resets 14:00\" — plain text, already sanitized. */\n summary: string | null;\n windows: Array<{ id: string; usedPercent: number | null; resetsAt: string | null }>;\n observedAt: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Seat capacity (V2.1, additive) — see docs/VERSE-TELEMETRY-V2.md, which is\n// the authority for every honesty rule encoded in these shapes.\n//\n// This file is imported by the BROWSER bundle, so it may not import\n// `core/verse/accounts.ts` (node:fs). The shapes below therefore restate the\n// provider-record shapes structurally. `seats.ts` assigns the account record's\n// values straight into them, so a divergence in `core/verse/accounts.ts` stops\n// `seats.ts` compiling — that assignment is the drift guard.\n// ---------------------------------------------------------------------------\n\n/** One provider-reported quota window, as carried on a seat. */\nexport interface VerseSeatWindow {\n id: string;\n /** Provider-reported percent, or null for NO SIGNAL — which is not zero. */\n usedPercent: number | null;\n /**\n * Machine-readable reset instant. STRUCTURALLY ALWAYS NULL for Claude: that\n * provider publishes only a sentence, which lives in `resetDescription` and\n * is rendered verbatim. The server never synthesizes an instant from it.\n * (3.10.1: the Command burn-down chart may place the reset on its time axis\n * via `resetInstantFromWords` in web-ui command-model, but only for the\n * collector's exact \"Mon D at H:MMam (Area/Zone)\" form and only when the\n * result lands within one window of now; anything else stays words.)\n */\n resetsAt: string | null;\n /** The provider's own reset wording, verbatim (\"resets Sep 25 at 7pm (America/New_York)\"). */\n resetDescription: string | null;\n /**\n * TRUE only when the provider explicitly FLAGGED the limit. Such a window's\n * `usedPercent` is the SENTINEL 100 — a denial, not a measurement — and must\n * be labelled \"limit reached\", never \"100% used\".\n */\n limitReached: boolean;\n /** False when `usedPercent` is a flagged sentinel rather than a reading. */\n measured: boolean;\n}\n\n/**\n * Codex credits, INDEPENDENT of the window: a fully used weekly window with a\n * spendable balance is not blocked. `null` is \"no signal\", never \"no credits\".\n */\nexport interface VerseSeatCredits {\n hasCredits: boolean;\n unlimited: boolean;\n /** Provider-reported decimal string, kept verbatim — never rounded. */\n balance: string | null;\n}\n\n/**\n * The coarse \"can I use this seat right now\" verdict. Deliberately coarse: the\n * exact numbers are in `windows`, and a verdict that pretended to more\n * precision than the providers give would be a lie.\n *\n * - `ready` — a reading exists and the binding window has headroom.\n * - `tight` — the binding window is at/above the warn threshold, OR it is\n * spent while Codex credits remain spendable (not blocked).\n * - `exhausted` — the binding window is spent and nothing else is left.\n * - `signed-out` — the account is not authenticated; reconnect it.\n * - `unknown` — NO window carried a percent. Not zero, not healthy.\n */\nexport type VerseSeatUsability = 'ready' | 'tight' | 'exhausted' | 'signed-out' | 'unknown';\n\n/**\n * Where a seat's windows came from, so nothing implies freshness it lacks.\n * Mirrors `VerseEvidenceSource` in `core/verse/accounts.ts`.\n */\nexport type VerseSeatEvidenceSource = 'collector' | 'shared-evidence' | 'baseline' | 'none';\n\n/** Everything the seat list needs to draw a capacity meter honestly. */\nexport interface VerseSeatCapacity {\n /** e.g. \"max\", \"pro\", \"SuperGrok\". Null when the provider gave none. */\n planType: string | null;\n /**\n * THE CONSTRAINT THAT ACTUALLY BLOCKS WORK: the window with the highest\n * `usedPercent`. Null when no window carried a percent at all.\n */\n binding: VerseSeatWindow | null;\n /** Every window the provider reported, in provider order. */\n windows: VerseSeatWindow[];\n /** Codex only; null for every other provider and when no signal exists. */\n credits: VerseSeatCredits | null;\n usability: VerseSeatUsability;\n observedAt: string | null;\n evidenceSource: VerseSeatEvidenceSource;\n /** Plain-language provider facts the UI must show instead of implying a fault. */\n notes: string[];\n}\n\nexport interface VerseProject {\n path: string;\n name: string;\n /** From ~/.ashlr/enrollment.json when present. */\n enrolled: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Workspaces (V2.2, ADDITIVE) — see docs/VERSE-WORKSPACES.md §1.\n//\n// A session bound to ONE directory cannot express \"this service plus the\n// shared library it depends on\", which is most real work. A workspace is a\n// NAMED set of roots with exactly one marked primary.\n//\n// `VerseSession.projectPath` keeps its meaning — it IS the primary root — so\n// every session record, adapter and test written before workspaces existed\n// still loads and still runs. Nothing rewrites saved chat history.\n//\n// ENROLLMENT IS NOT PART OF THIS SHAPE ON PURPOSE. A workspace says what a\n// session may REACH; `~/.ashlr/enrollment.json` says what the AUTONOMOUS lane\n// may mutate, and the two are deliberately separate registries. Membership in\n// a workspace grants no enrollment: `enrolled` below is READ from the\n// registry per root and is never written by anything in this feature.\n// ---------------------------------------------------------------------------\n\n/** One directory in a workspace. Exactly one root in a workspace is primary. */\nexport interface VerseWorkspaceRoot {\n /** Absolute, physically resolved path (symlinks followed). */\n path: string;\n /** Display name; defaults to the basename. */\n name: string;\n /**\n * The session's cwd and the value `projectPath` carries. Exactly one root\n * per workspace has this set.\n */\n primary: boolean;\n}\n\n/**\n * A named set of roots.\n *\n * ONE TYPE, TWO USES, DELIBERATELY. An interactive session binds to a\n * workspace to decide what it can reach; the autonomous lane reads the same\n * workspace as a SECTION — \"these repositories collaborate, work on them\n * together\" — when `section` is true. They were not split because the thing\n * being named is identical in both: a set of directories that belong to one\n * piece of work. Two registries of named repo groups would drift.\n *\n * What is NOT on this type is priority. A repo may belong to several\n * workspaces, so a per-membership rank would give one repo several\n * contradictory ranks. Priority is therefore an attribute OF THE REPO, held\n * once per path in the same registry — see `VerseRootPriority`.\n */\nexport interface VerseWorkspace {\n id: string;\n name: string;\n /** Primary first, then the extras in the order they were added. */\n roots: VerseWorkspaceRoot[];\n /**\n * Offer this workspace to the autonomous lane as a section.\n *\n * GRANTS NOTHING. The fleet still reaches only what\n * `~/.ashlr/enrollment.json` permits; a section can group and order those\n * repos and nothing else. A member that is not enrolled stays unreachable.\n */\n section: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Relative standing of one repository in the autonomous lane's attention.\n *\n * ORDERING ONLY, NEVER ADMISSION. `critical` on an unenrolled repo is still\n * refused by `assertMayMutate`; `low` on an enrolled one is still permitted.\n * An ordinal rather than a number because the operator's judgement here is\n * \"this matters more than that\", and a 0-100 score would invent a precision\n * nobody holds.\n *\n * Absent means `normal`, which is how every repo already behaves — so a\n * registry with no priorities at all reproduces today's flat list exactly.\n */\nexport type VerseRootPriority = 'critical' | 'high' | 'normal' | 'low';\n\nexport const VERSE_ROOT_PRIORITIES: readonly VerseRootPriority[] =\n ['critical', 'high', 'normal', 'low'];\n\nexport const VERSE_DEFAULT_ROOT_PRIORITY: VerseRootPriority = 'normal';\n\n/** Sort weight; lower sorts first. Never a budget, never a multiplier. */\nexport const VERSE_ROOT_PRIORITY_RANK: Record<VerseRootPriority, number> = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n};\n\n/** One enrolled repository as the autonomy scope view ranks it. */\nexport interface VerseAutonomyScopeEntry {\n path: string;\n name: string;\n priority: VerseRootPriority;\n /** Sections (workspaces with `section: true`) this repo belongs to. */\n sections: Array<{ id: string; name: string }>;\n /** True when a focus section is set and this repo is outside it. */\n outsideFocus: boolean;\n}\n\n/**\n * The autonomous lane's scope, ORDERED.\n *\n * Built by INTERSECTING section membership with the enrollment registry, so\n * it can only ever be a subset of what enrollment already allows. Sections\n * add ordering and grouping; they never add reach.\n */\nexport interface VerseAutonomyScopeView {\n focusSectionId: string | null;\n focusSectionName: string | null;\n /** Enrolled repos, most important first. */\n entries: VerseAutonomyScopeEntry[];\n /**\n * Paths a section names that are NOT enrolled. Listed so the blast radius\n * is legible in both directions — these are exactly the repos a section\n * does NOT give the fleet.\n */\n unenrolledSectionRoots: string[];\n}\n\n/**\n * Per-root git identity. A turn that edits two repos produces two diffs, so\n * the transcript has to be able to attribute each file to the right one.\n *\n * `remote` is the canonical `owner/repo` for a GitHub origin and null for\n * anything else — deliberately NOT the raw remote URL, which can carry a\n * token in its userinfo and would then reach an API response.\n */\nexport interface VerseRootGit {\n branch: string;\n /** Count of porcelain entries; 0 is clean. */\n dirty: number;\n ahead: number;\n behind: number;\n remote: string | null;\n}\n\n/** A root as the client sees it: identity, reachability and honest scope. */\nexport interface VerseRootStatus {\n path: string;\n name: string;\n primary: boolean;\n exists: boolean;\n /**\n * Read live from the enrollment registry. FALSE means the interactive lane\n * still works on this root while the autonomous lane refuses it — being in\n * a workspace never changes this.\n */\n enrolled: boolean;\n /** Null when the root is not a git repository, or git is unavailable. */\n git: VerseRootGit | null;\n /**\n * False when the session's engine has no way to be granted this root (Grok's\n * CLI exposes `--cwd` and nothing else). The root is still listed, because\n * hiding it would misrepresent what the workspace is.\n */\n reachable: boolean;\n}\n\n/** GET /api/verse/sessions/:id/roots */\nexport interface VerseSessionRootsResponse {\n sessionId: string;\n workspaceId: string | null;\n workspaceName: string | null;\n roots: VerseRootStatus[];\n /**\n * Plain-language facts the UI must show rather than imply: an unreachable\n * root on a Grok seat, or a root the autonomous lane will refuse.\n */\n notes: string[];\n}\n\n/** GET /api/verse/workspaces */\nexport interface VerseWorkspacesResponse {\n workspaces: VerseWorkspace[];\n /** Live per-root facts, keyed by workspace id, so one read draws the list. */\n status: Record<string, VerseRootStatus[]>;\n /** Per-repo priority, keyed by canonical path. Absent key means `normal`. */\n priorities: Record<string, VerseRootPriority>;\n focusSectionId: string | null;\n}\n\n/** POST /api/verse/workspaces */\nexport interface VerseWorkspaceCreateRequest {\n name: string;\n /** Absolute paths. The first is the primary. */\n roots: string[];\n /** Also offer this set to the autonomous lane as a section. Default false. */\n section?: boolean;\n}\n\n/** POST /api/verse/workspaces/:id/update */\nexport interface VerseWorkspaceUpdateRequest {\n name?: string;\n /** When present, replaces the root set wholesale. First entry is primary. */\n roots?: string[];\n section?: boolean;\n}\n\n/** POST /api/verse/workspaces/priority */\nexport interface VerseRootPriorityRequest {\n path: string;\n priority: VerseRootPriority;\n}\n\n/** POST /api/verse/workspaces/focus — `sectionId: null` clears the focus. */\nexport interface VerseFocusSectionRequest {\n sectionId: string | null;\n}\n\n/** Hard cap on roots per workspace — a blast radius, not a UI limit. */\nexport const VERSE_MAX_WORKSPACE_ROOTS = 8;\n\n/**\n * Every root a session can reach, primary first.\n *\n * Pure and total: a record written before workspaces existed has no\n * `extraRoots` and yields exactly `[projectPath]`, which is what every caller\n * assumed before this existed.\n */\nexport function verseSessionRoots(\n session: Pick<VerseSession, 'projectPath' | 'extraRoots'>,\n): string[] {\n const out = [session.projectPath];\n for (const root of session.extraRoots ?? []) {\n if (typeof root === 'string' && root.length > 0 && !out.includes(root)) out.push(root);\n }\n return out;\n}\n\nexport interface VerseUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n /**\n * Prompt size of the most recent assistant call = live context occupancy.\n * Stored UNCLAMPED: a reading above the window is information (the CLI is\n * about to compact or overflow), and only the UI decides how to draw it.\n */\n contextTokens: number;\n contextWindow: number | null;\n /** V3.9 ADDITIVE. Where `contextWindow` came from; absent on old records. */\n contextWindowSource?: VerseWindowSource;\n /** V3.9 ADDITIVE. Auto-compaction point for the session's current mode. */\n autoCompactAt?: number | null;\n /**\n * V3.9 ADDITIVE. False when `contextTokens` is an UPPER BOUND rather than a\n * measurement (codex before its rollout is readable: the turn total sums\n * every model call). Absent means exact.\n */\n contextTokensExact?: boolean;\n}\n\nexport interface VerseSession {\n id: string;\n title: string;\n /**\n * The PRIMARY root: the process cwd and the folder every pre-workspace\n * client already reads. Unchanged in meaning, which is why no session\n * record ever has to be rewritten.\n */\n projectPath: string;\n /**\n * V2.2 ADDITIVE. Roots BEYOND the primary, pinned at creation time.\n *\n * Absent on every record written before workspaces existed, and absent on\n * a single-root session today — so the on-disk shape of an ordinary chat\n * does not change at all.\n *\n * PINNED, not referenced: a session keeps the roots it was created with\n * even if the named workspace is later edited or deleted, for the same\n * reason `launch.anthropicBaseUrl` is pinned — a conversation must not\n * silently gain reach because config moved underneath it.\n */\n extraRoots?: string[];\n /** V2.2 ADDITIVE. Provenance of the pinned roots; absent for an ad-hoc set. */\n workspaceId?: string;\n workspaceName?: string;\n engine: VerseEngine;\n accountId: string;\n seatId: string;\n model: string;\n /** Vendor conversation id used for resume (claude/grok: our uuid; codex: thread id from output). */\n nativeSessionId: string | null;\n createdAt: string;\n updatedAt: string;\n status: VerseSessionStatus;\n turnCount: number;\n usage: VerseUsage;\n lastError: string | null;\n /**\n * V3.9 ADDITIVE. The session's context budget. Every record written by 3.9+\n * carries it explicitly, so ABSENT means a pre-3.9 record: the engine\n * materializes it on first touch — `expansive` for a Claude 1M model (that\n * is the native ~967k compaction those chats always ran with, so upgrading\n * never forces a paid compaction), `standard` otherwise (= native).\n * Changeable mid-session (POST /sessions/:id/context-mode): it changes CLI\n * flags, not prompt content — but switching DOWN below the current\n * occupancy makes the CLI compact on its next turn.\n */\n contextMode?: VerseContextMode;\n /** V3.9 ADDITIVE. Native compactions observed so far (claude/grok compact_boundary, codex rollout `compacted`). */\n compactionCount?: number;\n /** V3.9 ADDITIVE. Set when this session was started as a handoff from another. */\n handoffFrom?: { sessionId: string; title: string };\n /**\n * V3.9 ADDITIVE. Shared project memory was offered to this session's CLI at\n * creation. Pinned, like the roots: a conversation must not silently gain a\n * writable directory because a preference moved underneath it.\n */\n memoryEnabled?: boolean;\n /**\n * V3.10 ADDITIVE (contract: unit C0; written by C3's engine). The operator's\n * per-chat effort and permission choices, applied from the NEXT turn — a\n * running turn keeps the argv it was launched with. Absent (every record\n * before 3.10, and any key never set) = the engine default: permission mode\n * `accept-edits`, effort = the CLI's own default.\n *\n * A MODEL change is deliberately NOT stored here: it rewrites `model` above,\n * which every launch already reads — one field, one truth.\n */\n controls?: VerseSessionControls;\n}\n\n/**\n * V3.10. Permission modes a chat can run in (SPEC-310C §0.6), in picker order.\n * - `plan` — the CLI plans and edits nothing.\n * - `accept-edits` — the default: edits applied without asking.\n * - `auto` — the CLI's own auto mode.\n * - `bypass` — every check skipped. Shown red and confirmed PER CHAT:\n * never a default, never inherited by a new chat.\n * Adapters map these to each CLI's spelling (claude `acceptEdits` /\n * `bypassPermissions`, grok `dontAsk`, …). An engine that cannot honour one\n * reports it unavailable WITH a reason rather than approximating it. The\n * in-page \"Ask\" mode (answering permission prompts in the UI) is 3.11.\n */\nexport const VERSE_PERMISSION_MODES = ['plan', 'accept-edits', 'auto', 'bypass'] as const;\nexport type VersePermissionMode = (typeof VERSE_PERMISSION_MODES)[number];\nexport const VERSE_DEFAULT_PERMISSION_MODE: VersePermissionMode = 'accept-edits';\n\n/**\n * V3.10. Reasoning effort, the union across engines — claude `--effort`\n * (low · medium · high · xhigh · max) and codex `model_reasoning_effort`\n * (minimal · low · medium · high · xhigh). Each seat offers only the subset\n * its CLI accepts; the rest come back unavailable with a reason.\n */\nexport const VERSE_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;\nexport type VerseEffort = (typeof VERSE_EFFORTS)[number];\n\n/** V3.10. `VerseSession.controls` — absent key = engine default (see there). */\nexport interface VerseSessionControls {\n effort?: VerseEffort;\n permissionMode?: VersePermissionMode;\n}\n\n/** Normalized event stream. `seq` is monotonic per session and is the SSE id. */\nexport type VerseEvent =\n | { seq: number; at: string; type: 'user-message'; turnId: string; text: string }\n | { seq: number; at: string; type: 'turn-started'; turnId: string; pid: number | null }\n | { seq: number; at: string; type: 'text-delta'; turnId: string; text: string }\n | { seq: number; at: string; type: 'assistant-message'; turnId: string; text: string }\n /**\n * Reasoning the CLI chose to show. V3.10 ADDITIVE optional fields (absent on\n * older records = unknown, never \"false\"/\"0\"):\n * - `redacted` the CLI sent a signature-only / redacted block, so `text` is\n * empty but the model DID think (the UI says \"Thought 12s\").\n * - `durationMs` wall time the block took to stream, when measured.\n * - `kind` see VerseThinkingKind.\n */\n | {\n seq: number;\n at: string;\n type: 'thinking';\n turnId: string;\n text: string;\n redacted?: boolean;\n durationMs?: number;\n kind?: VerseThinkingKind;\n }\n | { seq: number; at: string; type: 'tool-use'; turnId: string; toolUseId: string; name: string; input: unknown }\n | { seq: number; at: string; type: 'tool-result'; turnId: string; toolUseId: string; output: string; isError: boolean }\n | { seq: number; at: string; type: 'usage'; turnId: string; usage: VerseUsage }\n | { seq: number; at: string; type: 'turn-done'; turnId: string; ok: boolean; nativeSessionId: string | null; durationMs: number }\n /**\n * `code` (V3.10 ADDITIVE, optional) is a stable machine key for errors the UI\n * or engine acts on — see VERSE_ERROR_CODES. Absent = uncategorised.\n */\n | { seq: number; at: string; type: 'error'; turnId: string | null; message: string; code?: string }\n | { seq: number; at: string; type: 'cancelled'; turnId: string }\n /**\n * V3.9. The CLI compacted its own conversation. Token counts are the CLI's\n * own (`compact_metadata.pre_tokens/post_tokens` on claude/grok). Codex\n * rollouts mark only THAT a compaction happened, so its counts are the last\n * `token_count` reading before the marker and the first one after it —\n * measured, but by Verse, not stated by the CLI; its `durationMs` is null.\n * Any count may be null when no reading brackets the compaction.\n */\n | {\n seq: number;\n at: string;\n type: 'compaction';\n turnId: string | null;\n trigger: 'auto' | 'manual';\n preTokens: number | null;\n postTokens: number | null;\n durationMs: number | null;\n }\n /**\n * V3.9. A context-occupancy READING that is not a usage delta — e.g. codex's\n * rollout `token_count` (exact last-call prompt size and the window the CLI\n * measured it against), polled mid-turn and read again after it. Replaces\n * the session's `contextTokens`; never summed. The engine fills\n * `autoCompactAt` for the window in force.\n */\n | {\n seq: number;\n at: string;\n type: 'context';\n turnId: string | null;\n contextTokens: number;\n contextWindow: number | null;\n exact: boolean;\n autoCompactAt?: number | null;\n /**\n * Where `contextWindow` came from. A CLI reading is `runtime`; the event\n * the engine writes after a MODE SWITCH carries the new budget's catalog\n * source, so a client never relabels a catalog figure as a measurement.\n * Absent on events from before this field existed (treat as `runtime`).\n */\n contextWindowSource?: VerseWindowSource;\n }\n // ── V3.10 TRANSIENT events ────────────────────────────────────────────────\n // Never written to the session log; fanned out to live SSE listeners only\n // (see VERSE_TRANSIENT_EVENT_TYPES for the wire rules). A reload therefore\n // never shows them — everything they convey is either ephemeral (a spinner)\n // or re-stated by a persisted event at turn end (`thinking`, `usage`).\n /** A chunk of streamed reasoning text for the in-flight thinking block. */\n | { seq: number; at: string; type: 'thinking-delta'; turnId: string; text: string }\n /**\n * The CLI reports reasoning volume without text (claude\n * `system/thinking_tokens`). An ESTIMATE, rate-limited by the adapter.\n */\n | { seq: number; at: string; type: 'thinking-progress'; turnId: string; estimatedTokens: number }\n /**\n * What the running turn is doing right now. `tool` names the running tool\n * when phase is `tool`. `outTokens`/`tokPerSec` are absent when unmeasured.\n */\n | {\n seq: number;\n at: string;\n type: 'progress';\n turnId: string;\n phase: VerseProgressPhase;\n tool?: string;\n elapsedMs: number;\n outTokens?: number;\n tokPerSec?: number;\n }\n /** A human-readable notice about the turn's plumbing (API retry, preflight, no-output watchdog). */\n | { seq: number; at: string; type: 'status'; turnId: string | null; kind: VerseStatusKind; message: string }\n // ── V3.10 PERSISTED events ────────────────────────────────────────────────\n /**\n * The engine recovered from a lost native conversation (e.g. the vendor\n * thread vanished) by starting a new native session seeded with the handoff\n * note (`how: 'handoff'`) or a bare new session (`new-native-session`).\n */\n | { seq: number; at: string; type: 'recovered'; turnId: string | null; how: VerseRecoveryHow; message: string }\n /**\n * The log hit its cap and events with `seq < droppedBefore` were dropped at\n * a TURN boundary (never mid-turn). `turnId` is always null — it is present\n * only so code reading `event.turnId` across the union keeps typechecking.\n */\n | { seq: number; at: string; type: 'history-truncated'; turnId: null; droppedBefore: number };\n\nexport type VerseEventType = VerseEvent['type'];\n\n/** V3.10. `summary` = vendor-summarised reasoning, `raw` = verbatim, `progress` = a heading/placeholder only. */\nexport type VerseThinkingKind = 'summary' | 'raw' | 'progress';\n\n/** V3.10. Phase of a running turn, carried by the transient `progress` event. */\nexport type VerseProgressPhase = 'thinking' | 'tool' | 'writing' | 'waiting';\n\n/** V3.10. What a transient `status` notice is about. */\nexport type VerseStatusKind = 'retry' | 'preflight' | 'watchdog';\n\n/** V3.10. How a `recovered` event restored the conversation. */\nexport type VerseRecoveryHow = 'new-native-session' | 'handoff';\n\n/**\n * V3.10. Known `error.code` values. `code` stays `string` on the wire so an\n * older client never rejects a newer code; these are the ones Verse acts on.\n * - `native-thread-missing` — the vendor conversation to resume no longer exists.\n * - `session-in-use` — the CLI refused because the native session id is locked.\n */\nexport const VERSE_ERROR_CODES = ['native-thread-missing', 'session-in-use'] as const;\nexport type VerseErrorCode = (typeof VERSE_ERROR_CODES)[number];\n\n/**\n * V3.10. Event types that are NEVER persisted — emitted to live SSE listeners\n * only. The list and its guard live in ./transient-events.ts (re-exported\n * here): the web chat's first-paint store needs the guard, and importing it\n * from this module put every runtime value exported here — the handoff\n * prompt, the effort tables — into the chat's first-paint chunk.\n */\nexport { VERSE_TRANSIENT_EVENT_TYPES, isTransientVerseEvent } from './transient-events.js';\n\nexport type VerseTransientEventType = (typeof TRANSIENT_EVENT_TYPE_LIST)[number];\nexport type VerseTransientEvent = Extract<VerseEvent, { type: VerseTransientEventType }>;\nexport type VersePersistedEvent = Exclude<VerseEvent, { type: VerseTransientEventType }>;\n\n/**\n * Which endpoint a LOCAL seat sends its turns to.\n *\n * - `ollama` — the historical lane: the plain `claude` binary with\n * ANTHROPIC_BASE_URL pointed straight at Ollama's\n * Anthropic-compatible endpoint on :11434. Ollama\n * serialises this model architecture, so a fleet of local\n * agents on this lane is a queue (docs/LOCAL-FLEET.md).\n * - `llama-server` — the same binary pointed at the local Anthropic\n * normalising proxy that fronts llama-server. That proxy\n * is the ONLY way to reach llama-server's parallel slots\n * and the prompt-cache fix, because Qwen3.8's chat\n * template rejects Claude Code's request shape unless the\n * proxy rewrites it on the way through.\n *\n * DISPATCH ONLY. Model DISCOVERY stays on Ollama in both lanes — llama-server\n * implements neither `/api/tags` nor `/api/show`, which is where every local\n * seat's identity, context window and `tools` capability comes from.\n */\nexport type VerseLocalDispatch = 'ollama' | 'llama-server';\n\n/** What a client is told about this machine's local serving situation. */\nexport interface VerseLocalRuntimeSummary {\n /** Ollama reachable? Drives the local seats and an inline hint when false. */\n ollama: { reachable: boolean; baseUrl: string; models: string[] };\n /**\n * Where local seats DISPATCH turns, reported only when that is NOT the\n * default Ollama lane.\n *\n * Absent means `ollama`, i.e. exactly what every existing client already\n * assumes — so opting in is visible on the wire and NOT opting in changes no\n * payload at all.\n */\n dispatch?: { lane: VerseLocalDispatch; baseUrl: string };\n}\n\n/** GET /api/verse/bootstrap */\nexport interface VerseBootstrap {\n seats: VerseSeat[];\n projects: VerseProject[];\n sessions: VerseSession[];\n /** Whether POST routes are enabled on this server (`ashlr serve --allow-dispatch` / `ashlr verse`). */\n dispatchEnabled: boolean;\n localRuntime: VerseLocalRuntimeSummary;\n}\n\n/**\n * GET /api/verse/seats (V2.1)\n *\n * WHY THIS ROUTE EXISTS: `bootstrap` is a MOUNT-TIME snapshot. A client that\n * opened the app before the collector's first cycle finished would show\n * \"unknown\" forever. This is the same seat list, cheap enough to poll, and it\n * always reflects the collector's CURRENT state rather than a cached one.\n */\nexport interface VerseSeatsResponse {\n /** When this body was built. */\n sampledAt: string;\n seats: VerseSeat[];\n localRuntime: VerseBootstrap['localRuntime'];\n}\n\n/**\n * POST /api/verse/sessions\n *\n * Two spellings, never mixed (the API rejects the mix rather than silently\n * preferring one):\n * - `workspaceId` alone — the named workspace supplies primary and extras.\n * - `projectPath` (+ optional `extraRoots`) — an ad-hoc set, which is also\n * exactly the pre-workspace request shape.\n */\nexport interface VerseCreateSessionRequest {\n projectPath: string;\n seatId: string;\n model?: string;\n title?: string;\n /** V2.2 ADDITIVE. Absolute paths beyond the primary. */\n extraRoots?: string[];\n /** V2.2 ADDITIVE. Bind to a named workspace instead of naming paths. */\n workspaceId?: string;\n /**\n * SERVER-FILLED. The API resolves this from the registry once `workspaceId`\n * is validated, and never reads it off the request body — so a session can\n * not be labelled with a workspace name that is not the one it was built\n * from.\n */\n workspaceName?: string;\n /**\n * V3.9 ADDITIVE. Absent → the seat's preferred mode (preferences.json), else\n * `standard`. `expansive` on a model with no expansive budget is rejected.\n */\n contextMode?: VerseContextMode;\n /**\n * V3.9 ADDITIVE. Start this session as a handoff from an existing one. The\n * server resolves the source's title itself (never from the body) and pins\n * `handoffFrom`; the handoff TEXT is sent by the client as turn 1, after the\n * operator has read it — nothing is spent on their behalf.\n */\n handoffFromSessionId?: string;\n}\n\n/** POST /api/verse/sessions/:id/turns */\nexport interface VerseTurnRequest {\n text: string;\n}\nexport interface VerseTurnResponse {\n turnId: string;\n session: VerseSession;\n}\n\n/** GET /api/verse/sessions/:id */\nexport interface VerseSessionDetail {\n session: VerseSession;\n events: VerseEvent[];\n}\n\n/** Adapter input: how to launch one turn. Pure data, produced by the engine, consumed by the spawner. */\nexport interface VerseTurnLaunch {\n argv: string[];\n cwd: string;\n /** Extra env layered over a minimal base (PATH/HOME/TMPDIR/LANG). Never contains secrets. */\n env: Record<string, string>;\n /** Text written to stdin (codex); null when the prompt is in argv. */\n stdin: string | null;\n}\n\nexport const VERSE_MAX_TURN_TEXT_BYTES = 64 * 1024;\nexport const VERSE_MAX_EVENTS_PER_SESSION = 20_000;\nexport const VERSE_TURN_TIMEOUT_MS = 30 * 60 * 1000;\n/**\n * LAST-RESORT fallbacks, used only when neither the runtime, the seat's own\n * catalog, nor the verified per-model table (core/verse/model-windows.ts) knows\n * the model. Each mirrors what the CLI ITSELF assumes for an unknown id, so the\n * meter never claims more than the CLI will allow:\n *\n * - claude 200_000 — Claude Code's `Mg()` default for an unrecognized model.\n * Every KNOWN Claude id carries its real window (1M for the 5.x family,\n * Opus 4.8 and Sonnet 5) in the per-model table instead.\n * - codex 258_400 — 272_000 × the 95% `effective_context_window_percent`\n * every codex catalog entry carries; the figure codex's own rollouts report\n * as `model_context_window` (65,440 of 65,440 observed events).\n * - grok 500_000 — `context_window` for every grok-4.x id in the seat catalog.\n * - local 65_536 — the num_ctx the default local tag pins.\n */\nexport const VERSE_DEFAULT_CONTEXT_WINDOWS: Record<string, number> = {\n claude: 200_000,\n codex: 258_400,\n grok: 500_000,\n local: 65_536,\n};\n\n// ---------------------------------------------------------------------------\n// V3.9 context orchestration — request/response shapes (docs/VERSE-CONTEXT.md)\n// ---------------------------------------------------------------------------\n\n/** GET /api/verse/preferences — the operator's standing context choices. */\nexport interface VersePreferences {\n version: 1;\n /** Per-seat default context mode for NEW sessions. Absent = `standard`. */\n seats: Record<string, { contextMode?: VerseContextMode }>;\n /** Shared project memory. On by default; listed canonical paths opt out. */\n memory: { enabled: boolean; disabledProjects: string[] };\n /**\n * V3.10 ADDITIVE. Stream vendor-summarised reasoning on non-local seats\n * (claude `--thinking-display summarized`). Absent = on (Mason's default).\n */\n thinkingDisplay?: boolean;\n}\n\n/**\n * POST /api/verse/preferences — exactly ONE of the three forms per request, so\n * a body can never change more than the operator clicked.\n */\nexport type VersePreferencesUpdate =\n | { seatId: string; contextMode: VerseContextMode }\n | { memoryEnabled: boolean }\n | { projectPath: string; memoryEnabled: boolean };\n\n/** POST /api/verse/sessions/:id/context-mode */\nexport interface VerseContextModeRequest {\n mode: VerseContextMode;\n}\n\n/** POST /api/verse/sessions/:id/handoff-preview */\nexport interface VerseHandoffPreviewRequest {\n /**\n * Include the latest assistant message verbatim (capped) as the agent's own\n * summary — used after \"Ask this seat to summarize\" produced one.\n */\n includeLastAssistant?: boolean;\n /** Optional operator focus line, e.g. \"finish the migration of X\". ≤ 500 chars. */\n focus?: string;\n}\n\n/** Deterministic, zero-spend handoff note built from the session's event log. */\nexport interface VerseHandoffPreview {\n sourceSessionId: string;\n sourceTitle: string;\n /** The exact text to send as turn 1 of the new session. ≤ VERSE_HANDOFF_MAX_CHARS. */\n text: string;\n stats: {\n chars: number;\n /** chars / 4, rounded up — the same estimator the fit badges use. */\n estTokens: number;\n turnsCovered: number;\n filesTouched: number;\n /** Sections dropped to respect the cap, by name; empty when nothing was cut. */\n truncated: string[];\n };\n}\n\nexport const VERSE_HANDOFF_MAX_CHARS = 12_000;\n\n/**\n * The canned turn behind \"Ask this seat to summarize first\". Shared by the UI\n * (which sends it as an ordinary turn through the normal spend chokepoint) and\n * the handoff builder (which must NOT carry it into the new session as the\n * operator's \"latest ask\" — the new chat would otherwise be told to write a\n * handoff note instead of continuing the work).\n *\n * Written so the reply is useful as turn 1 of a session that has NONE of this\n * context. It asks for no tool use on purpose: a summary that starts editing\n * files is not a summary, and a read-only turn is also the cheapest one.\n */\nexport const VERSE_HANDOFF_SUMMARY_REQUEST = [\n 'This conversation is about to continue in a fresh session that has none of its context.',\n 'Write the handoff note that new session should start from. Do not edit files or run commands for this — only write the note.',\n '',\n 'Cover, concretely:',\n '- The goal, and what \"done\" looks like.',\n '- Decisions made so far, each with the reason it was made.',\n '- Current state: what is finished, what is half-done, what is untested.',\n '- Files changed and anything not yet committed.',\n '- How to verify the work (exact commands).',\n '- Open questions, risks, and approaches already tried that did not work.',\n '',\n 'Keep it under 600 words. Prefer file paths and commands over prose.',\n].join('\\n');\n\n/** GET /api/verse/context-fit — how big the reachable code is, in tokens. */\nexport interface VerseContextFitRoot {\n path: string;\n /** Tracked text files counted (git ls-files, binaries and >1 MB files skipped). */\n files: number;\n bytes: number;\n estTokens: number;\n /** True when the scan hit its file or time cap; estTokens is then a floor. */\n truncated: boolean;\n}\n\nexport interface VerseContextFit {\n roots: VerseContextFitRoot[];\n totalEstTokens: number;\n /** Always 'bytes/4' today; named so a better estimator can be introduced honestly. */\n estimator: 'bytes/4';\n sampledAt: string;\n}\n\n/**\n * Per-model verdict for a working set (see context-math.ts `fitVerdict`):\n * fits in standard, tight in standard, fits only in expansive, or too big for\n * any single context (split the work).\n */\nexport type VerseFitVerdict = 'fits' | 'tight' | 'expansive' | 'split';\n\n/** GET /api/verse/search?q=&limit= — keyword search over past sessions. Zero spend. */\nexport interface VerseSearchHit {\n sessionId: string;\n title: string;\n projectPath: string;\n engine: VerseEngine;\n seq: number;\n at: string;\n kind: 'user' | 'assistant';\n /** ≤ 240 chars around the first match, whitespace-collapsed. */\n snippet: string;\n score: number;\n}\n\nexport interface VerseSearchResponse {\n query: string;\n hits: VerseSearchHit[];\n /** Sessions actually scanned (the scan is bounded; see session-search.ts). */\n scannedSessions: number;\n truncated: boolean;\n}\n\n/** GET/POST /api/verse/memory — shared project memory for one project. */\nexport interface VerseProjectMemory {\n projectPath: string;\n enabled: boolean;\n /** Contents of MEMORY.md ('' when absent). */\n content: string;\n bytes: number;\n updatedAt: string | null;\n /** Other files the agents created in the memory directory (names only). */\n files: string[];\n /**\n * Present (true) only when `content` as SENT differs from the bytes on disk:\n * the public-JSON sanitizer rewrote the home path to `~` or replaced a\n * secret-looking value with `[REDACTED]`. The file itself is untouched; a\n * save that would write placeholders over real values is refused (409\n * VERSE_MEMORY_REDACTED), so the editor must say so before the operator types.\n */\n contentSanitized?: boolean;\n}\n\n/** POST /api/verse/memory */\nexport interface VerseProjectMemoryWrite {\n projectPath: string;\n content: string;\n}\n\nexport const VERSE_MEMORY_MAX_BYTES = 64 * 1024;\n\n/**\n * POST /api/verse/memory's own JSON body cap: JSON escaping can double the\n * content (every newline becomes `\\\\n`), plus room for the other fields. Every\n * other route keeps the 64 KiB default. Shared so the browser's pre-check can\n * never refuse a save the server would accept.\n */\nexport const VERSE_MEMORY_BODY_MAX_BYTES = 2 * VERSE_MEMORY_MAX_BYTES + 8 * 1024;\n\n/** Cap on the memory block appended to each session's system prompt. */\nexport const VERSE_MEMORY_BLOCK_MAX_BYTES = 6 * 1024;\n","/**\n * routes/verse/context/context-model.ts — the pure half of the context\n * components (handoff dialog, memory panel, session search). No React, no\n * I/O, so every rule the components render is pinned by a plain unit test.\n *\n * Every number shown here comes from context-math.ts (the one module the\n * server and the browser share), so \"compacts ≈367k\" in the handoff dialog is\n * the same figure the meter and the seat picker show.\n */\nimport type { VerseEngine, VerseModelOption, VerseSeat, VerseSession } from '../../../data/api-types.js';\nimport type {\n VerseContextMode,\n VerseFitVerdict,\n VersePreferences,\n VerseSearchHit,\n} from '../../../../core/verse/types.js';\nimport { VERSE_MEMORY_BLOCK_MAX_BYTES, VERSE_MEMORY_BODY_MAX_BYTES } from '../../../../core/verse/types.js';\nimport {\n budgetFor,\n canonicalModelId,\n estimateTokensFromChars,\n fitVerdict,\n hasExpansiveMode,\n sessionOverheadTokens,\n} from '../../../../core/verse/context-math.js';\nimport { formatContextWindow, formatRelative } from '../verse-model.js';\nimport { asClause, percentText, tidyProse } from '../autonomy/format.js';\nimport { formatTokens } from '../verse-readouts.js';\n\n// ---------------------------------------------------------------------------\n// Handoff\n// ---------------------------------------------------------------------------\n\n// The canned \"Ask this seat to summarize first\" turn is\n// VERSE_HANDOFF_SUMMARY_REQUEST in core/verse/types.ts, not a copy here: the\n// handoff builder on the server matches that exact text to keep it OUT of the\n// new session's \"latest requests\" (otherwise the new chat is told to write\n// another handoff note). A local copy that drifted by one character would\n// silently defeat that filter.\n\n/** Mirrors session-engine's TITLE_MAX so a title we send is never cut by the server instead. */\nexport const TITLE_MAX_CHARS = 120;\n\nconst PART_SUFFIX = /\\s·\\spart\\s(\\d+)$/;\n\n/**\n * Title for the session a handoff continues in: \"Fix the login bug · part 2\".\n * A continuation of a continuation counts up rather than stacking suffixes, so\n * the sidebar reads \"part 3\", never \"part 2 · part 2\".\n */\nexport function handoffTitle(sourceTitle: string): string {\n const collapsed = sourceTitle.replace(/\\s+/g, ' ').trim();\n const match = PART_SUFFIX.exec(collapsed);\n const base = (match ? collapsed.slice(0, match.index) : collapsed) || 'Untitled chat';\n const next = match ? Number.parseInt(match[1]!, 10) + 1 : 2;\n const suffix = ` · part ${next}`;\n const room = TITLE_MAX_CHARS - suffix.length;\n const clipped = base.length > room ? `${base.slice(0, room - 1).trimEnd()}…` : base;\n return `${clipped}${suffix}`;\n}\n\n/**\n * A seat's catalog entry for a model id. Exact id first, then canonical — a\n * session created before the alias fix stores `claude-opus-5.5` while the\n * catalog now lists `claude-opus-5-5` (context-math VERSE_MODEL_ID_ALIASES).\n */\nexport function modelOption(seat: VerseSeat | null | undefined, modelId: string): VerseModelOption | null {\n if (!seat) return null;\n const exact = seat.models.find((m) => m.id === modelId);\n if (exact) return exact;\n const canonical = canonicalModelId(modelId);\n return seat.models.find((m) => canonicalModelId(m.id) === canonical) ?? null;\n}\n\n/**\n * Why a seat+model cannot take a new session right now; null when it can.\n *\n * The seat's own reason is embedded as a clause: its closing period is\n * dropped (no \"exhausted..\") and any ISO instant in it — a health summary\n * saying when usage resets — is read as the viewer's local time.\n */\nexport function targetUnavailableReason(\n seat: VerseSeat | null | undefined,\n option: VerseModelOption | null,\n now: number = Date.now(),\n): string | null {\n if (!seat) return 'Pick a seat to continue on.';\n if (seat.health.state === 'unavailable') {\n return `${seat.label} is unavailable: ${asClause(tidyProse(seat.health.summary ?? 'no reason given', now))}.`;\n }\n if (!option) return 'Pick a model on this seat.';\n if (option.unavailableReason) {\n return `${option.label} cannot run on ${seat.label}: ${asClause(tidyProse(option.unavailableReason, now))}.`;\n }\n return null;\n}\n\nexport interface HandoffTarget {\n seatId: string;\n model: string;\n}\n\n/**\n * Where a handoff lands by default: the SAME seat and model (the common case\n * is \"same agent, fresh context\"). When that model can no longer run there,\n * the seat's first runnable model; when the seat itself is gone or\n * unavailable, the first runnable model on any available seat, in the seat\n * list's own order.\n */\nexport function defaultHandoffTarget(seats: readonly VerseSeat[], source: Pick<VerseSession, 'seatId' | 'model'>): HandoffTarget | null {\n const own = seats.find((s) => s.id === source.seatId);\n if (own && own.health.state !== 'unavailable') {\n const same = modelOption(own, source.model);\n if (same && !same.unavailableReason) return { seatId: own.id, model: same.id };\n const runnable = own.models.find((m) => !m.unavailableReason);\n if (runnable) return { seatId: own.id, model: runnable.id };\n }\n for (const seat of seats) {\n if (seat.health.state === 'unavailable') continue;\n const runnable = seat.models.find((m) => !m.unavailableReason);\n if (runnable) return { seatId: seat.id, model: runnable.id };\n }\n return null;\n}\n\n/**\n * The mode a handoff starts in. Only a mode that EXISTS for the target model\n * is ever returned (a mode with no budget would be refused by the server).\n *\n * 1. Same seat and model as the source → keep the source's mode. \"Continue in\n * a fresh chat\" means the same settings with a clean context; an operator\n * who chose expansive for this work chose it for the work.\n * 2. Otherwise the target seat's standing preference (preferences.json).\n * 3. Otherwise standard.\n */\nexport function defaultHandoffMode(input: {\n option: VerseModelOption | null;\n target: HandoffTarget | null;\n source: Pick<VerseSession, 'seatId' | 'model' | 'contextMode'>;\n preferences: VersePreferences | null | undefined;\n}): VerseContextMode {\n const { option, target, source, preferences } = input;\n const valid = (mode: VerseContextMode | undefined): mode is VerseContextMode =>\n mode !== undefined && budgetFor(option, mode) !== null;\n const sameModel = target !== null && target.seatId === source.seatId\n && canonicalModelId(target.model) === canonicalModelId(source.model);\n if (sameModel && valid(source.contextMode ?? 'standard')) return source.contextMode ?? 'standard';\n const preferred = target ? preferences?.seats[target.seatId]?.contextMode : undefined;\n if (valid(preferred)) return preferred;\n return 'standard';\n}\n\n/**\n * The mode to put on the create request, or undefined to leave it to the\n * server. A mode is sent only when the model has a budget for it — which is\n * exactly the server's acceptance rule — so what the dialog shows is what is\n * created, and an unknown-window model is never refused over a mode it could\n * not have.\n */\nexport function requestMode(option: VerseModelOption | null, mode: VerseContextMode): VerseContextMode | undefined {\n return budgetFor(option, mode) !== null ? mode : undefined;\n}\n\n/** \"1M window · compacts ≈367k\" for a model in a mode; null when the budget is unknown. */\nexport function budgetLine(option: VerseModelOption | null, mode: VerseContextMode): string | null {\n const budget = budgetFor(option, mode);\n if (!budget) return null;\n const window = `${formatContextWindow(budget.contextWindow)} window`;\n return budget.autoCompactAt === null ? window : `${window} · compacts ≈${formatTokens(budget.autoCompactAt)}`;\n}\n\nexport interface HandoffFit {\n verdict: VerseFitVerdict | null;\n /** The handoff text's own estimate (chars / 4). */\n handoffTokens: number;\n /** The target engine's estimated fixed prompt (context-math `sessionOverheadTokens`). */\n overheadTokens: number;\n /** Handoff + that fixed prompt: what the new session holds before its first reply. */\n needTokens: number;\n /** One sentence for the dialog. */\n text: string;\n tone: 'ok' | 'warn' | 'danger' | 'unknown';\n}\n\n/**\n * Will the new session START comfortably? The handoff is small by design\n * (≤ 12k chars ≈ 3k tokens), but every fresh session also carries the CLI's\n * fixed prompt — a large share of a 64k local slot — so this is a real\n * question on small windows, and the sentence shows both halves of the sum\n * rather than a bare verdict.\n *\n * The fixed prompt is the TARGET seat's engine estimate (local ≈15k measured,\n * claude ≈25k, …), not one flat figure: a flat 30k called every handoff to a\n * 64k local seat \"too big for one context\" when the real sum was ~20k. It is\n * still an estimate — no CLI reports its base prompt before the first turn —\n * so the sentence says \"estimated\" rather than presenting it as a reading.\n * `engine` null (target seat not known yet) falls back to the largest estimate.\n */\nexport function handoffFit(\n textChars: number,\n option: VerseModelOption | null,\n mode: VerseContextMode,\n engine: VerseEngine | null,\n): HandoffFit {\n const handoffTokens = estimateTokensFromChars(textChars);\n const overheadTokens = sessionOverheadTokens(engine);\n const needTokens = handoffTokens + overheadTokens;\n const verdict = fitVerdict(handoffTokens, option, overheadTokens);\n const sum = `~${formatTokens(handoffTokens)} tokens of handoff + an estimated ~${formatTokens(overheadTokens)} of fixed prompt`;\n const standard = budgetFor(option, 'standard');\n const standardCap = standard ? standard.autoCompactAt ?? standard.contextWindow : null;\n const base = { verdict, handoffTokens, overheadTokens, needTokens };\n switch (verdict) {\n case 'fits':\n return { ...base, tone: 'ok', text: `Fits: ${sum} leaves most of the budget before the first compaction.` };\n case 'tight':\n return {\n ...base,\n tone: 'warn',\n text: `Tight: ${sum} is ${percentText((needTokens / (standardCap ?? needTokens)) * 100)} of where this model compacts — the new chat will compact early.`,\n };\n case 'expansive':\n return mode === 'expansive'\n ? { ...base, tone: 'warn', text: `Fits only the expansive budget: ${sum}.` }\n : { ...base, tone: 'danger', text: `Too big for the standard budget (${sum}). Switch to Expansive, or trim the handoff.` };\n case 'split':\n return { ...base, tone: 'danger', text: `Too big for one context on this model (${sum}). Trim the handoff or pick a seat with a larger window.` };\n default:\n return { ...base, verdict: null, tone: 'unknown', text: 'This model’s window is not known, so there is no fit estimate.' };\n }\n}\n\n/** True when the target model has a real expansive budget (context-math, re-exported for the dialog). */\nexport function offersExpansive(option: VerseModelOption | null): boolean {\n return hasExpansiveMode(option);\n}\n\n/** A local turn runs on this machine; every other engine spends subscription usage. */\nexport function turnCostSentence(engine: VerseEngine, seatLabel: string): string {\n return engine === 'local'\n ? `Runs on this machine with ${seatLabel}; it spends no subscription usage.`\n : `Sends one turn to ${seatLabel} and spends from its usage. The automatic preview costs nothing.`;\n}\n\n// ---------------------------------------------------------------------------\n// Bytes\n// ---------------------------------------------------------------------------\n\nconst encoder = typeof TextEncoder === 'function' ? new TextEncoder() : null;\n\n/** UTF-8 byte length — the unit the server's caps (64 KB memory content, 64 KB turn) are written in. */\nexport function utf8Bytes(text: string): number {\n if (encoder) return encoder.encode(text).length;\n // Fallback for an environment with no TextEncoder: count code points by width.\n let bytes = 0;\n for (const ch of text) {\n const cp = ch.codePointAt(0) ?? 0;\n bytes += cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4;\n }\n return bytes;\n}\n\n/**\n * The API's default request-body cap: `readBody` in src/core/web/api.ts, which\n * every /api/verse POST uses unless its route passes a larger one (only\n * POST /memory does — see MEMORY_BODY_MAX_BYTES). A write travels as JSON, so what must fit is\n * the ENCODED body — every `\\n` and `\"` escaped to two bytes — not the text\n * alone; the editors measure it so a refusal happens on screen instead of as\n * \"request body too large\".\n */\nexport const API_BODY_MAX_BYTES = 65_536;\n\n/**\n * POST /api/verse/memory's own body cap — mirrors `VERSE_MEMORY_BODY_MAX_BYTES`\n * in src/core/verse/verse-api.ts (a server module the browser cannot import):\n * room for 64 KiB of content in which EVERY byte escapes to two, plus the\n * project path and the JSON around it. The server still holds the CONTENT to\n * VERSE_MEMORY_MAX_BYTES after parsing. Guarding the memory editor with the\n * 64 KiB default instead blocked saves the server accepts — a 60–64 KB\n * MEMORY.md with ordinary line breaks could not be edited from the panel,\n * which is the exact case the server's larger cap exists for.\n */\nexport const MEMORY_BODY_MAX_BYTES = VERSE_MEMORY_BODY_MAX_BYTES;\n\n/** UTF-8 size of `body` exactly as the client will send it. */\nexport function jsonBodyBytes(body: unknown): number {\n return utf8Bytes(JSON.stringify(body) ?? '');\n}\n\nexport function formatBytes(bytes: number): string {\n if (!Number.isFinite(bytes) || bytes < 0) return '—';\n if (bytes < 1024) return `${bytes} B`;\n const kb = bytes / 1024;\n return `${kb < 10 ? kb.toFixed(1).replace(/\\.0$/, '') : Math.round(kb)} KB`;\n}\n\n/**\n * A relative time that reads as a phrase: \"just now\", \"5m ago\", \"on Sep 19\".\n * `formatRelative` (verse-model) is sized for a 5ch sidebar column and reads\n * as a bare token; prose needs the preposition.\n */\nexport function relativePhrase(iso: string | null | undefined, now: number = Date.now()): string | null {\n if (!iso) return null;\n const short = formatRelative(iso, now);\n if (!short) return null;\n if (short === 'now') return 'just now';\n // Only the relative tokens (\"5m\", \"3h\", \"2d\") take \"ago\". Anything else is a\n // DATE, whatever the locale prints: \"Sep 1\" (en-US) but \"1 Sept\" (en-GB)\n // and \"1. Sept.\" (de) start with a digit — testing for a leading digit\n // printed \"Last completed 1 Sept ago.\" outside the US.\n return /^\\d+[mhd]$/.test(short) ? `${short} ago` : `on ${short}`;\n}\n\n// ---------------------------------------------------------------------------\n// Memory\n// ---------------------------------------------------------------------------\n\n/**\n * Shapes that are almost certainly credentials. MEMORY.md is sent to every\n * seat's model on every turn, so a pasted key would travel to every provider\n * — the panel warns BEFORE the save rather than trusting the server's scrub\n * to catch it on the way out. Conservative on purpose: a false alarm on prose\n * would teach the operator to ignore the warning.\n */\nconst SECRET_PATTERNS: ReadonlyArray<{ label: string; re: RegExp }> = [\n { label: 'a private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },\n { label: 'an Anthropic API key', re: /\\bsk-ant-[A-Za-z0-9_-]{20,}/ },\n { label: 'an OpenAI-style API key', re: /\\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/ },\n { label: 'an xAI API key', re: /\\bxai-[A-Za-z0-9]{32,}/ },\n { label: 'a GitHub token', re: /\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}|\\bgithub_pat_[A-Za-z0-9_]{40,}/ },\n { label: 'an AWS access key', re: /\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/ },\n { label: 'a Slack token', re: /\\bxox[abprs]-[A-Za-z0-9-]{10,}/ },\n { label: 'a Google API key', re: /\\bAIza[0-9A-Za-z_-]{35}\\b/ },\n { label: 'a Stripe secret key', re: /\\b(?:sk|rk)_live_[0-9A-Za-z]{20,}/ },\n];\n\n/**\n * Mirrors `VERSE_MEMORY_BLOCK_MAX_BYTES` in src/core/verse/project-memory.ts\n * (a node module the browser cannot import): the most memory text a chat's\n * instructions carry, however large MEMORY.md itself is.\n */\nexport const MEMORY_BLOCK_MAX_BYTES = VERSE_MEMORY_BLOCK_MAX_BYTES;\n\n/**\n * What memory costs, in the one wording the memory panel and the resources\n * panel share. Memory is ON by default and snapshotted into every new chat's\n * system prompt (claude `--append-system-prompt`, codex `developer_instructions`,\n * grok `--rules`), which re-rides every turn, and it asks writable seats to\n * read and update MEMORY.md — tool calls and output. On a paid seat that is\n * real (if small, mostly cached) usage, so \"nothing here spends\" would be\n * false for exactly the operator deciding whether to leave it on near a limit.\n * Reading and editing the file from the panel is still free.\n */\nexport const MEMORY_SPEND_NOTE =\n `Reading and editing memory here spends nothing. On a paid seat it is not free to use: each new chat’s system prompt carries a memory block of up to ${MEMORY_BLOCK_MAX_BYTES / 1024} KB, re-sent every turn (cached after the first), and the agent reads and updates MEMORY.md as it works. Local seats spend nothing.`;\n\n/** The first credential shape found, as a phrase (\"a GitHub token\"), or null. */\nexport function secretLike(text: string): string | null {\n for (const { label, re } of SECRET_PATTERNS) if (re.test(text)) return label;\n return null;\n}\n\n/**\n * The placeholder the server's scrubber (src/core/util/scrub.ts) writes over\n * secret-shaped text in every rule. In a memory view flagged\n * `contentSanitized`, each one stands for a REAL value still in MEMORY.md.\n */\nexport const REDACTION_MARKER = '[REDACTED]';\n\n/** How many redaction placeholders a text carries. */\nexport function redactionMarkers(text: string): number {\n return text.split(REDACTION_MARKER).length - 1;\n}\n\n// ---------------------------------------------------------------------------\n// Search\n// ---------------------------------------------------------------------------\n\n/** Below this many characters a keyword search over every message is noise, not recall. */\nexport const SEARCH_MIN_CHARS = 2;\n/** Keystrokes inside this window collapse into one request. */\nexport const SEARCH_DEBOUNCE_MS = 250;\n/** Hits asked for per search — enough to fill the sidebar twice over. */\nexport const SEARCH_LIMIT = 30;\n\n/** Whitespace-separated terms, lowercased and de-duplicated (the server ANDs them). */\nexport function searchTerms(query: string): string[] {\n const out: string[] = [];\n for (const raw of query.toLowerCase().split(/\\s+/)) {\n if (raw && !out.includes(raw)) out.push(raw);\n }\n return out;\n}\n\nexport interface HighlightSegment {\n text: string;\n match: boolean;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Split `text` into plain and matched runs for every term, case-insensitive.\n * Longest terms first so \"migrate\" wins over \"migrat\" at the same position.\n */\nexport function highlightSegments(text: string, terms: readonly string[]): HighlightSegment[] {\n const usable = [...terms].filter((t) => t.length > 0).sort((a, b) => b.length - a.length);\n if (usable.length === 0 || text.length === 0) return text ? [{ text, match: false }] : [];\n const re = new RegExp(usable.map(escapeRegExp).join('|'), 'gi');\n const out: HighlightSegment[] = [];\n let last = 0;\n for (const m of text.matchAll(re)) {\n const start = m.index ?? 0;\n if (m[0].length === 0) continue;\n if (start > last) out.push({ text: text.slice(last, start), match: false });\n out.push({ text: m[0], match: true });\n last = start + m[0].length;\n }\n if (last < text.length) out.push({ text: text.slice(last), match: false });\n return out;\n}\n\nexport interface SessionSearchGroup {\n sessionId: string;\n title: string;\n projectPath: string;\n engine: VerseEngine;\n /** The best-scoring hit in this session (the server returns hits best-first). */\n top: VerseSearchHit;\n /** Every hit this session contributed to the response. */\n count: number;\n /** Newest hit time, for the row's relative time. */\n latestAt: string;\n}\n\n/**\n * One row per session. The server ranks MESSAGES; the sidebar lists CHATS,\n * and five rows for one chat would push every other match off screen. Order\n * is the order each session first appears, i.e. by its best hit.\n */\nexport function groupSearchHits(hits: readonly VerseSearchHit[]): SessionSearchGroup[] {\n const groups = new Map<string, SessionSearchGroup>();\n for (const hit of hits) {\n const existing = groups.get(hit.sessionId);\n if (!existing) {\n groups.set(hit.sessionId, {\n sessionId: hit.sessionId,\n title: hit.title,\n projectPath: hit.projectPath,\n engine: hit.engine,\n top: hit,\n count: 1,\n latestAt: hit.at,\n });\n continue;\n }\n existing.count += 1;\n if (hit.at > existing.latestAt) existing.latestAt = hit.at;\n }\n return [...groups.values()];\n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AO,EAAK,CAAC,EACpC,EAAO,EAAQ,EAAE,EAAE,CAAC,OACtB,CAEA,OADI,EAAO,EAAK,QAAQ,EAAI,KAAK,CAAE,KAAM,EAAK,MAAM,CAAI,EAAG,MAAO,EAAM,CAAC,EAClE,CACT,CAoBA,SAAgB,EAAgB,EAAuD,CACrF,IAAM,EAAS,IAAI,IACnB,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAW,EAAO,IAAI,EAAI,SAAS,EACzC,GAAI,CAAC,EAAU,CACb,EAAO,IAAI,EAAI,UAAW,CACxB,UAAW,EAAI,UACf,MAAO,EAAI,MACX,YAAa,EAAI,YACjB,OAAQ,EAAI,OACZ,IAAK,EACL,MAAO,EACP,SAAU,EAAI,EAChB,CAAC,EACD,QACF,CACA,EAAS,OAAS,EACd,EAAI,GAAK,EAAS,WAAU,EAAS,SAAW,EAAI,GAC1D,CACA,MAAO,CAAC,GAAG,EAAO,OAAO,CAAC,CAC5B"}
1
+ {"version":3,"file":"context-model-DV1zCfAm.js","names":[],"sources":["../../../../../../src/core/verse/types.ts","../../../../../../src/web-ui/routes/verse/context/context-model.ts"],"sourcesContent":["/**\n * Ashlr Verse — interactive multi-turn session contract (V1).\n *\n * A Verse session binds one project directory to one execution seat\n * (engine + account + model). Each user turn spawns ONE vendor CLI process\n * that resumes the vendor-native conversation by id, streams normalized\n * events, and exits. No long-lived stdin is held between turns.\n *\n * Seats:\n * claude -> `claude -p ... --output-format stream-json` via a native-profile launcher (account pinned by CLAUDE_CONFIG_DIR)\n * local -> the plain `claude` binary with ANTHROPIC_BASE_URL pointed at Ollama (Anthropic-compatible API); model = Ollama tag\n * codex -> `codex exec --json` / `codex exec resume <threadId> --json` via a native-profile launcher (CODEX_HOME pinned)\n * grok -> `grok -p ... --output-format streaming-messages-json` via a native-profile launcher (GROK_HOME pinned)\n *\n * Nothing in this module reads secrets. Account identity is pinned by the\n * launcher command recorded in ~/.ashlr/account-connections/connections.json.\n */\nimport type { TRANSIENT_EVENT_TYPE_LIST } from './transient-events.js';\n\nexport type VerseEngine = 'claude' | 'codex' | 'grok' | 'local';\n\nexport type VerseSessionStatus = 'idle' | 'running' | 'error';\n\n/** One selectable execution seat shown in the model/account picker. */\nexport interface VerseSeat {\n /** Stable id, e.g. `claude`, `codex-personal`, `grok`, `local:qwen3-coder-next:ctx64k`. */\n id: string;\n engine: VerseEngine;\n /** Human label, e.g. \"Claude Code\", \"Personal Codex\", \"Grok\", \"Qwen3-Coder-Next (local)\". */\n label: string;\n /** Account id from connections.json for native seats; `local` for Ollama seats. */\n accountId: string;\n /** Models this seat can run. First entry is the default. */\n models: VerseModelOption[];\n /** Best-known context window in tokens for the default model (null when unknown). */\n contextWindow: number | null;\n /** Latest health/usage evidence, if any. Never an admission input in V1. */\n health: VerseSeatHealth;\n /**\n * V2.1 ADDITIVE. The subscription capacity behind this seat, so the seat\n * list can render a meter without a second request.\n *\n * Absent (`undefined`) for LOCAL seats: an Ollama tag has no subscription\n * and no provider window. Its real constraint is machine memory, which is\n * reported by `VerseBootstrap.localRuntime`, not by a quota. Absent on a\n * native seat means the server could not build a record for that account\n * at all — `health.state` says what it does know.\n */\n capacity?: VerseSeatCapacity;\n /**\n * V3.9 ADDITIVE. The version of the CLI binary this seat is PINNED to (its\n * native-profile launcher execs one exact file). Absent when unknown and on\n * local seats. A pinned binary never updates itself, so a model that needs a\n * newer CLI is listed with `unavailableReason` rather than silently failing.\n */\n cliVersion?: string;\n /**\n * V3.9 ADDITIVE. Plain-language facts about this seat's context setup the UI\n * must show rather than imply (binary skew, catalog not yet fetched, …).\n * Absent when there is nothing to say, so ordinary seats keep their shape.\n */\n notes?: string[];\n}\n\n/**\n * Where a context-window figure came from, so nothing on screen implies more\n * certainty than it has (docs/VERSE-CONTEXT.md §1).\n *\n * - `runtime` — the CLI reported it for THIS turn (claude/grok\n * `result.modelUsage.<m>.contextWindow`, codex rollout\n * `token_count.info.model_context_window`, Ollama\n * `/api/ps`). Wins over everything else.\n * - `provider-catalog` — the seat's own served catalog on disk (codex/grok\n * `native-state/models_cache.json`).\n * - `cli-catalog` — read out of the pinned CLI binary's embedded catalog\n * and recorded here with the version it was read from.\n * - `documented` — the provider's published model table.\n * - `fallback` — a named default; the UI marks it as an estimate.\n */\nexport type VerseWindowSource = 'runtime' | 'provider-catalog' | 'cli-catalog' | 'documented' | 'fallback';\n\n/**\n * How much context a session is allowed to accumulate before the CLI compacts.\n *\n * - `standard` — the default. Evidence-based budget per engine: Claude 1M\n * models compact near 400k instead of ~967k; Codex, Grok and\n * local run their native windows.\n * - `expansive` — opt-in. Claude runs its full native window (CLI `auto`),\n * Codex raises `model_context_window` to the model's catalog\n * maximum (872k on GPT-6 / GPT-5.6). Costs more usage per turn,\n * buys simultaneous visibility for coupled, cross-cutting work.\n *\n * A mode that does not exist for a model (Grok, local, 200k Claude models,\n * GPT-5.5) is simply absent from that model's option — never faked.\n */\nexport type VerseContextMode = 'standard' | 'expansive';\n\nexport const VERSE_CONTEXT_MODES: readonly VerseContextMode[] = ['standard', 'expansive'];\n\n/** One mode's budget for a model on a seat. */\nexport interface VerseContextBudget {\n /** The window the CLI measures against in this mode (the meter's denominator). */\n contextWindow: number;\n /** Token count at which the CLI auto-compacts in this mode; null when unknown. */\n autoCompactAt: number | null;\n /**\n * The RAW window value the CLI must be TOLD to reach this budget, when that\n * differs from `contextWindow` — codex measures against 95% of the window it\n * is configured with, so expansive GPT-6 is `providerWindow: 872_000`\n * (`-c model_context_window=872000`) but `contextWindow: 828_400`.\n */\n providerWindow?: number | null;\n}\n\nexport interface VerseModelOption {\n id: string;\n label: string;\n /** Standard-mode window the CLI measures against (codex: the 95% effective window). */\n contextWindow: number | null;\n /**\n * V3.9 ADDITIVE — every field below is optional so records and fixtures\n * written before it keep validating. Absent means \"not known\", never zero.\n */\n /** Standard-mode auto-compaction point. */\n autoCompactAt?: number | null;\n /** Present ONLY when this model on this seat has a real expansive mode. */\n expansive?: VerseContextBudget | null;\n /** The CLI's default max output for this model, when known. */\n maxOutputTokens?: number | null;\n windowSource?: VerseWindowSource;\n /** Minimum CLI version that knows this model id (e.g. '2.1.280'); null when any. */\n minCliVersion?: string | null;\n /**\n * Why this model cannot run on this seat right now, in plain language (e.g.\n * \"needs Claude Code 2.1.280; this seat runs 2.1.257\"). Null/absent = runnable.\n * Listed rather than hidden so the operator learns WHY a model is missing.\n */\n unavailableReason?: string | null;\n}\n\nexport interface VerseSeatHealth {\n state: 'ready' | 'degraded' | 'unavailable' | 'unknown';\n /** e.g. \"5h window 72% used, resets 14:00\" — plain text, already sanitized. */\n summary: string | null;\n windows: Array<{ id: string; usedPercent: number | null; resetsAt: string | null }>;\n observedAt: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Seat capacity (V2.1, additive) — see docs/VERSE-TELEMETRY-V2.md, which is\n// the authority for every honesty rule encoded in these shapes.\n//\n// This file is imported by the BROWSER bundle, so it may not import\n// `core/verse/accounts.ts` (node:fs). The shapes below therefore restate the\n// provider-record shapes structurally. `seats.ts` assigns the account record's\n// values straight into them, so a divergence in `core/verse/accounts.ts` stops\n// `seats.ts` compiling — that assignment is the drift guard.\n// ---------------------------------------------------------------------------\n\n/** One provider-reported quota window, as carried on a seat. */\nexport interface VerseSeatWindow {\n id: string;\n /** Provider-reported percent, or null for NO SIGNAL — which is not zero. */\n usedPercent: number | null;\n /**\n * Machine-readable reset instant. STRUCTURALLY ALWAYS NULL for Claude: that\n * provider publishes only a sentence, which lives in `resetDescription` and\n * is rendered verbatim. The server never synthesizes an instant from it.\n * (3.10.1: the Command burn-down chart may place the reset on its time axis\n * via `resetInstantFromWords` in web-ui command-model, but only for the\n * collector's exact \"Mon D at H:MMam (Area/Zone)\" form and only when the\n * result lands within one window of now; anything else stays words.)\n */\n resetsAt: string | null;\n /** The provider's own reset wording, verbatim (\"resets Sep 25 at 7pm (America/New_York)\"). */\n resetDescription: string | null;\n /**\n * TRUE only when the provider explicitly FLAGGED the limit. Such a window's\n * `usedPercent` is the SENTINEL 100 — a denial, not a measurement — and must\n * be labelled \"limit reached\", never \"100% used\".\n */\n limitReached: boolean;\n /** False when `usedPercent` is a flagged sentinel rather than a reading. */\n measured: boolean;\n}\n\n/**\n * Codex credits, INDEPENDENT of the window: a fully used weekly window with a\n * spendable balance is not blocked. `null` is \"no signal\", never \"no credits\".\n */\nexport interface VerseSeatCredits {\n hasCredits: boolean;\n unlimited: boolean;\n /** Provider-reported decimal string, kept verbatim — never rounded. */\n balance: string | null;\n}\n\n/**\n * The coarse \"can I use this seat right now\" verdict. Deliberately coarse: the\n * exact numbers are in `windows`, and a verdict that pretended to more\n * precision than the providers give would be a lie.\n *\n * - `ready` — a reading exists and the binding window has headroom.\n * - `tight` — the binding window is at/above the warn threshold, OR it is\n * spent while Codex credits remain spendable (not blocked).\n * - `exhausted` — the binding window is spent and nothing else is left.\n * - `signed-out` — the account is not authenticated; reconnect it.\n * - `unknown` — NO window carried a percent. Not zero, not healthy.\n */\nexport type VerseSeatUsability = 'ready' | 'tight' | 'exhausted' | 'signed-out' | 'unknown';\n\n/**\n * Where a seat's windows came from, so nothing implies freshness it lacks.\n * Mirrors `VerseEvidenceSource` in `core/verse/accounts.ts`.\n */\nexport type VerseSeatEvidenceSource = 'collector' | 'shared-evidence' | 'baseline' | 'none';\n\n/** Everything the seat list needs to draw a capacity meter honestly. */\nexport interface VerseSeatCapacity {\n /** e.g. \"max\", \"pro\", \"SuperGrok\". Null when the provider gave none. */\n planType: string | null;\n /**\n * THE CONSTRAINT THAT ACTUALLY BLOCKS WORK: the window with the highest\n * `usedPercent`. Null when no window carried a percent at all.\n */\n binding: VerseSeatWindow | null;\n /** Every window the provider reported, in provider order. */\n windows: VerseSeatWindow[];\n /** Codex only; null for every other provider and when no signal exists. */\n credits: VerseSeatCredits | null;\n usability: VerseSeatUsability;\n observedAt: string | null;\n evidenceSource: VerseSeatEvidenceSource;\n /** Plain-language provider facts the UI must show instead of implying a fault. */\n notes: string[];\n}\n\nexport interface VerseProject {\n path: string;\n name: string;\n /** From ~/.ashlr/enrollment.json when present. */\n enrolled: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Workspaces (V2.2, ADDITIVE) — see docs/VERSE-WORKSPACES.md §1.\n//\n// A session bound to ONE directory cannot express \"this service plus the\n// shared library it depends on\", which is most real work. A workspace is a\n// NAMED set of roots with exactly one marked primary.\n//\n// `VerseSession.projectPath` keeps its meaning — it IS the primary root — so\n// every session record, adapter and test written before workspaces existed\n// still loads and still runs. Nothing rewrites saved chat history.\n//\n// ENROLLMENT IS NOT PART OF THIS SHAPE ON PURPOSE. A workspace says what a\n// session may REACH; `~/.ashlr/enrollment.json` says what the AUTONOMOUS lane\n// may mutate, and the two are deliberately separate registries. Membership in\n// a workspace grants no enrollment: `enrolled` below is READ from the\n// registry per root and is never written by anything in this feature.\n// ---------------------------------------------------------------------------\n\n/** One directory in a workspace. Exactly one root in a workspace is primary. */\nexport interface VerseWorkspaceRoot {\n /** Absolute, physically resolved path (symlinks followed). */\n path: string;\n /** Display name; defaults to the basename. */\n name: string;\n /**\n * The session's cwd and the value `projectPath` carries. Exactly one root\n * per workspace has this set.\n */\n primary: boolean;\n}\n\n/**\n * A named set of roots.\n *\n * ONE TYPE, TWO USES, DELIBERATELY. An interactive session binds to a\n * workspace to decide what it can reach; the autonomous lane reads the same\n * workspace as a SECTION — \"these repositories collaborate, work on them\n * together\" — when `section` is true. They were not split because the thing\n * being named is identical in both: a set of directories that belong to one\n * piece of work. Two registries of named repo groups would drift.\n *\n * What is NOT on this type is priority. A repo may belong to several\n * workspaces, so a per-membership rank would give one repo several\n * contradictory ranks. Priority is therefore an attribute OF THE REPO, held\n * once per path in the same registry — see `VerseRootPriority`.\n */\nexport interface VerseWorkspace {\n id: string;\n name: string;\n /** Primary first, then the extras in the order they were added. */\n roots: VerseWorkspaceRoot[];\n /**\n * Offer this workspace to the autonomous lane as a section.\n *\n * GRANTS NOTHING. The fleet still reaches only what\n * `~/.ashlr/enrollment.json` permits; a section can group and order those\n * repos and nothing else. A member that is not enrolled stays unreachable.\n */\n section: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Relative standing of one repository in the autonomous lane's attention.\n *\n * ORDERING ONLY, NEVER ADMISSION. `critical` on an unenrolled repo is still\n * refused by `assertMayMutate`; `low` on an enrolled one is still permitted.\n * An ordinal rather than a number because the operator's judgement here is\n * \"this matters more than that\", and a 0-100 score would invent a precision\n * nobody holds.\n *\n * Absent means `normal`, which is how every repo already behaves — so a\n * registry with no priorities at all reproduces today's flat list exactly.\n */\nexport type VerseRootPriority = 'critical' | 'high' | 'normal' | 'low';\n\nexport const VERSE_ROOT_PRIORITIES: readonly VerseRootPriority[] =\n ['critical', 'high', 'normal', 'low'];\n\nexport const VERSE_DEFAULT_ROOT_PRIORITY: VerseRootPriority = 'normal';\n\n/** Sort weight; lower sorts first. Never a budget, never a multiplier. */\nexport const VERSE_ROOT_PRIORITY_RANK: Record<VerseRootPriority, number> = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n};\n\n/** One enrolled repository as the autonomy scope view ranks it. */\nexport interface VerseAutonomyScopeEntry {\n path: string;\n name: string;\n priority: VerseRootPriority;\n /** Sections (workspaces with `section: true`) this repo belongs to. */\n sections: Array<{ id: string; name: string }>;\n /** True when a focus section is set and this repo is outside it. */\n outsideFocus: boolean;\n}\n\n/**\n * The autonomous lane's scope, ORDERED.\n *\n * Built by INTERSECTING section membership with the enrollment registry, so\n * it can only ever be a subset of what enrollment already allows. Sections\n * add ordering and grouping; they never add reach.\n */\nexport interface VerseAutonomyScopeView {\n focusSectionId: string | null;\n focusSectionName: string | null;\n /** Enrolled repos, most important first. */\n entries: VerseAutonomyScopeEntry[];\n /**\n * Paths a section names that are NOT enrolled. Listed so the blast radius\n * is legible in both directions — these are exactly the repos a section\n * does NOT give the fleet.\n */\n unenrolledSectionRoots: string[];\n}\n\n/**\n * Per-root git identity. A turn that edits two repos produces two diffs, so\n * the transcript has to be able to attribute each file to the right one.\n *\n * `remote` is the canonical `owner/repo` for a GitHub origin and null for\n * anything else — deliberately NOT the raw remote URL, which can carry a\n * token in its userinfo and would then reach an API response.\n */\nexport interface VerseRootGit {\n branch: string;\n /** Count of porcelain entries; 0 is clean. */\n dirty: number;\n ahead: number;\n behind: number;\n remote: string | null;\n}\n\n/** A root as the client sees it: identity, reachability and honest scope. */\nexport interface VerseRootStatus {\n path: string;\n name: string;\n primary: boolean;\n exists: boolean;\n /**\n * Read live from the enrollment registry. FALSE means the interactive lane\n * still works on this root while the autonomous lane refuses it — being in\n * a workspace never changes this.\n */\n enrolled: boolean;\n /** Null when the root is not a git repository, or git is unavailable. */\n git: VerseRootGit | null;\n /**\n * False when the session's engine has no way to be granted this root (Grok's\n * CLI exposes `--cwd` and nothing else). The root is still listed, because\n * hiding it would misrepresent what the workspace is.\n */\n reachable: boolean;\n}\n\n/** GET /api/verse/sessions/:id/roots */\nexport interface VerseSessionRootsResponse {\n sessionId: string;\n workspaceId: string | null;\n workspaceName: string | null;\n roots: VerseRootStatus[];\n /**\n * Plain-language facts the UI must show rather than imply: an unreachable\n * root on a Grok seat, or a root the autonomous lane will refuse.\n */\n notes: string[];\n}\n\n/** GET /api/verse/workspaces */\nexport interface VerseWorkspacesResponse {\n workspaces: VerseWorkspace[];\n /** Live per-root facts, keyed by workspace id, so one read draws the list. */\n status: Record<string, VerseRootStatus[]>;\n /** Per-repo priority, keyed by canonical path. Absent key means `normal`. */\n priorities: Record<string, VerseRootPriority>;\n focusSectionId: string | null;\n}\n\n/** POST /api/verse/workspaces */\nexport interface VerseWorkspaceCreateRequest {\n name: string;\n /** Absolute paths. The first is the primary. */\n roots: string[];\n /** Also offer this set to the autonomous lane as a section. Default false. */\n section?: boolean;\n}\n\n/** POST /api/verse/workspaces/:id/update */\nexport interface VerseWorkspaceUpdateRequest {\n name?: string;\n /** When present, replaces the root set wholesale. First entry is primary. */\n roots?: string[];\n section?: boolean;\n}\n\n/** POST /api/verse/workspaces/priority */\nexport interface VerseRootPriorityRequest {\n path: string;\n priority: VerseRootPriority;\n}\n\n/** POST /api/verse/workspaces/focus — `sectionId: null` clears the focus. */\nexport interface VerseFocusSectionRequest {\n sectionId: string | null;\n}\n\n/** Hard cap on roots per workspace — a blast radius, not a UI limit. */\nexport const VERSE_MAX_WORKSPACE_ROOTS = 8;\n\n/**\n * Every root a session can reach, primary first.\n *\n * Pure and total: a record written before workspaces existed has no\n * `extraRoots` and yields exactly `[projectPath]`, which is what every caller\n * assumed before this existed.\n */\nexport function verseSessionRoots(\n session: Pick<VerseSession, 'projectPath' | 'extraRoots'>,\n): string[] {\n const out = [session.projectPath];\n for (const root of session.extraRoots ?? []) {\n if (typeof root === 'string' && root.length > 0 && !out.includes(root)) out.push(root);\n }\n return out;\n}\n\nexport interface VerseUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n /**\n * Prompt size of the most recent assistant call = live context occupancy.\n * Stored UNCLAMPED: a reading above the window is information (the CLI is\n * about to compact or overflow), and only the UI decides how to draw it.\n */\n contextTokens: number;\n contextWindow: number | null;\n /** V3.9 ADDITIVE. Where `contextWindow` came from; absent on old records. */\n contextWindowSource?: VerseWindowSource;\n /** V3.9 ADDITIVE. Auto-compaction point for the session's current mode. */\n autoCompactAt?: number | null;\n /**\n * V3.9 ADDITIVE. False when `contextTokens` is an UPPER BOUND rather than a\n * measurement (codex before its rollout is readable: the turn total sums\n * every model call). Absent means exact.\n */\n contextTokensExact?: boolean;\n}\n\nexport interface VerseSession {\n id: string;\n title: string;\n /**\n * The PRIMARY root: the process cwd and the folder every pre-workspace\n * client already reads. Unchanged in meaning, which is why no session\n * record ever has to be rewritten.\n */\n projectPath: string;\n /**\n * V2.2 ADDITIVE. Roots BEYOND the primary, pinned at creation time.\n *\n * Absent on every record written before workspaces existed, and absent on\n * a single-root session today — so the on-disk shape of an ordinary chat\n * does not change at all.\n *\n * PINNED, not referenced: a session keeps the roots it was created with\n * even if the named workspace is later edited or deleted, for the same\n * reason `launch.anthropicBaseUrl` is pinned — a conversation must not\n * silently gain reach because config moved underneath it.\n */\n extraRoots?: string[];\n /** V2.2 ADDITIVE. Provenance of the pinned roots; absent for an ad-hoc set. */\n workspaceId?: string;\n workspaceName?: string;\n engine: VerseEngine;\n accountId: string;\n seatId: string;\n model: string;\n /** Vendor conversation id used for resume (claude/grok: our uuid; codex: thread id from output). */\n nativeSessionId: string | null;\n createdAt: string;\n updatedAt: string;\n status: VerseSessionStatus;\n turnCount: number;\n usage: VerseUsage;\n lastError: string | null;\n /**\n * V3.9 ADDITIVE. The session's context budget. Every record written by 3.9+\n * carries it explicitly, so ABSENT means a pre-3.9 record: the engine\n * materializes it on first touch — `expansive` for a Claude 1M model (that\n * is the native ~967k compaction those chats always ran with, so upgrading\n * never forces a paid compaction), `standard` otherwise (= native).\n * Changeable mid-session (POST /sessions/:id/context-mode): it changes CLI\n * flags, not prompt content — but switching DOWN below the current\n * occupancy makes the CLI compact on its next turn.\n */\n contextMode?: VerseContextMode;\n /** V3.9 ADDITIVE. Native compactions observed so far (claude/grok compact_boundary, codex rollout `compacted`). */\n compactionCount?: number;\n /** V3.9 ADDITIVE. Set when this session was started as a handoff from another. */\n handoffFrom?: { sessionId: string; title: string };\n /**\n * V3.9 ADDITIVE. Shared project memory was offered to this session's CLI at\n * creation. Pinned, like the roots: a conversation must not silently gain a\n * writable directory because a preference moved underneath it.\n */\n memoryEnabled?: boolean;\n /**\n * V3.10 ADDITIVE (contract: unit C0; written by C3's engine). The operator's\n * per-chat effort and permission choices, applied from the NEXT turn — a\n * running turn keeps the argv it was launched with. Absent (every record\n * before 3.10, and any key never set) = the engine default: permission mode\n * `accept-edits`, effort = the CLI's own default.\n *\n * A MODEL change is deliberately NOT stored here: it rewrites `model` above,\n * which every launch already reads — one field, one truth.\n */\n controls?: VerseSessionControls;\n}\n\n/**\n * V3.10. Permission modes a chat can run in (SPEC-310C §0.6), in picker order.\n * - `plan` — the CLI plans and edits nothing.\n * - `accept-edits` — the default: edits applied without asking.\n * - `auto` — the CLI's own auto mode.\n * - `bypass` — every check skipped. Shown red and confirmed PER CHAT:\n * never a default, never inherited by a new chat.\n * Adapters map these to each CLI's spelling (claude `acceptEdits` /\n * `bypassPermissions`, grok `dontAsk`, …). An engine that cannot honour one\n * reports it unavailable WITH a reason rather than approximating it. The\n * in-page \"Ask\" mode (answering permission prompts in the UI) is 3.11.\n */\nexport const VERSE_PERMISSION_MODES = ['plan', 'accept-edits', 'auto', 'bypass'] as const;\nexport type VersePermissionMode = (typeof VERSE_PERMISSION_MODES)[number];\nexport const VERSE_DEFAULT_PERMISSION_MODE: VersePermissionMode = 'accept-edits';\n\n/**\n * V3.10. Reasoning effort, the union across engines — claude `--effort`\n * (low · medium · high · xhigh · max) and codex `model_reasoning_effort`\n * (minimal · low · medium · high · xhigh). Each seat offers only the subset\n * its CLI accepts; the rest come back unavailable with a reason.\n */\nexport const VERSE_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;\nexport type VerseEffort = (typeof VERSE_EFFORTS)[number];\n\n/** V3.10. `VerseSession.controls` — absent key = engine default (see there). */\nexport interface VerseSessionControls {\n effort?: VerseEffort;\n permissionMode?: VersePermissionMode;\n}\n\n/** Normalized event stream. `seq` is monotonic per session and is the SSE id. */\nexport type VerseEvent =\n | { seq: number; at: string; type: 'user-message'; turnId: string; text: string }\n | { seq: number; at: string; type: 'turn-started'; turnId: string; pid: number | null }\n | { seq: number; at: string; type: 'text-delta'; turnId: string; text: string }\n | { seq: number; at: string; type: 'assistant-message'; turnId: string; text: string }\n /**\n * Reasoning the CLI chose to show. V3.10 ADDITIVE optional fields (absent on\n * older records = unknown, never \"false\"/\"0\"):\n * - `redacted` the CLI sent a signature-only / redacted block, so `text` is\n * empty but the model DID think (the UI says \"Thought 12s\").\n * - `durationMs` wall time the block took to stream, when measured.\n * - `kind` see VerseThinkingKind.\n */\n | {\n seq: number;\n at: string;\n type: 'thinking';\n turnId: string;\n text: string;\n redacted?: boolean;\n durationMs?: number;\n kind?: VerseThinkingKind;\n }\n | { seq: number; at: string; type: 'tool-use'; turnId: string; toolUseId: string; name: string; input: unknown }\n | { seq: number; at: string; type: 'tool-result'; turnId: string; toolUseId: string; output: string; isError: boolean }\n | { seq: number; at: string; type: 'usage'; turnId: string; usage: VerseUsage }\n | { seq: number; at: string; type: 'turn-done'; turnId: string; ok: boolean; nativeSessionId: string | null; durationMs: number }\n /**\n * `code` (V3.10 ADDITIVE, optional) is a stable machine key for errors the UI\n * or engine acts on — see VERSE_ERROR_CODES. Absent = uncategorised.\n */\n | { seq: number; at: string; type: 'error'; turnId: string | null; message: string; code?: string }\n | { seq: number; at: string; type: 'cancelled'; turnId: string }\n /**\n * V3.9. The CLI compacted its own conversation. Token counts are the CLI's\n * own (`compact_metadata.pre_tokens/post_tokens` on claude/grok). Codex\n * rollouts mark only THAT a compaction happened, so its counts are the last\n * `token_count` reading before the marker and the first one after it —\n * measured, but by Verse, not stated by the CLI; its `durationMs` is null.\n * Any count may be null when no reading brackets the compaction.\n */\n | {\n seq: number;\n at: string;\n type: 'compaction';\n turnId: string | null;\n trigger: 'auto' | 'manual';\n preTokens: number | null;\n postTokens: number | null;\n durationMs: number | null;\n }\n /**\n * V3.9. A context-occupancy READING that is not a usage delta — e.g. codex's\n * rollout `token_count` (exact last-call prompt size and the window the CLI\n * measured it against), polled mid-turn and read again after it. Replaces\n * the session's `contextTokens`; never summed. The engine fills\n * `autoCompactAt` for the window in force.\n */\n | {\n seq: number;\n at: string;\n type: 'context';\n turnId: string | null;\n contextTokens: number;\n contextWindow: number | null;\n exact: boolean;\n autoCompactAt?: number | null;\n /**\n * Where `contextWindow` came from. A CLI reading is `runtime`; the event\n * the engine writes after a MODE SWITCH carries the new budget's catalog\n * source, so a client never relabels a catalog figure as a measurement.\n * Absent on events from before this field existed (treat as `runtime`).\n */\n contextWindowSource?: VerseWindowSource;\n }\n // ── V3.10 TRANSIENT events ────────────────────────────────────────────────\n // Never written to the session log; fanned out to live SSE listeners only\n // (see VERSE_TRANSIENT_EVENT_TYPES for the wire rules). A reload therefore\n // never shows them — everything they convey is either ephemeral (a spinner)\n // or re-stated by a persisted event at turn end (`thinking`, `usage`).\n /** A chunk of streamed reasoning text for the in-flight thinking block. */\n | { seq: number; at: string; type: 'thinking-delta'; turnId: string; text: string }\n /**\n * The CLI reports reasoning volume without text (claude\n * `system/thinking_tokens`). An ESTIMATE, rate-limited by the adapter.\n */\n | { seq: number; at: string; type: 'thinking-progress'; turnId: string; estimatedTokens: number }\n /**\n * What the running turn is doing right now. `tool` names the running tool\n * when phase is `tool`. `outTokens`/`tokPerSec` are absent when unmeasured.\n */\n | {\n seq: number;\n at: string;\n type: 'progress';\n turnId: string;\n phase: VerseProgressPhase;\n tool?: string;\n elapsedMs: number;\n outTokens?: number;\n tokPerSec?: number;\n }\n /** A human-readable notice about the turn's plumbing (API retry, preflight, no-output watchdog). */\n | { seq: number; at: string; type: 'status'; turnId: string | null; kind: VerseStatusKind; message: string }\n // ── V3.10 PERSISTED events ────────────────────────────────────────────────\n /**\n * The engine recovered from a lost native conversation (e.g. the vendor\n * thread vanished) by starting a new native session seeded with the handoff\n * note (`how: 'handoff'`) or a bare new session (`new-native-session`).\n */\n | { seq: number; at: string; type: 'recovered'; turnId: string | null; how: VerseRecoveryHow; message: string }\n /**\n * The log hit its cap and events with `seq < droppedBefore` were dropped at\n * a TURN boundary (never mid-turn). `turnId` is always null — it is present\n * only so code reading `event.turnId` across the union keeps typechecking.\n */\n | { seq: number; at: string; type: 'history-truncated'; turnId: null; droppedBefore: number };\n\nexport type VerseEventType = VerseEvent['type'];\n\n/** V3.10. `summary` = vendor-summarised reasoning, `raw` = verbatim, `progress` = a heading/placeholder only. */\nexport type VerseThinkingKind = 'summary' | 'raw' | 'progress';\n\n/** V3.10. Phase of a running turn, carried by the transient `progress` event. */\nexport type VerseProgressPhase = 'thinking' | 'tool' | 'writing' | 'waiting';\n\n/** V3.10. What a transient `status` notice is about. */\nexport type VerseStatusKind = 'retry' | 'preflight' | 'watchdog';\n\n/** V3.10. How a `recovered` event restored the conversation. */\nexport type VerseRecoveryHow = 'new-native-session' | 'handoff';\n\n/**\n * V3.10. Known `error.code` values. `code` stays `string` on the wire so an\n * older client never rejects a newer code; these are the ones Verse acts on.\n * - `native-thread-missing` — the vendor conversation to resume no longer exists.\n * - `session-in-use` — the CLI refused because the native session id is locked.\n */\nexport const VERSE_ERROR_CODES = ['native-thread-missing', 'session-in-use'] as const;\nexport type VerseErrorCode = (typeof VERSE_ERROR_CODES)[number];\n\n/**\n * V3.10. Event types that are NEVER persisted — emitted to live SSE listeners\n * only. The list and its guard live in ./transient-events.ts (re-exported\n * here): the web chat's first-paint store needs the guard, and importing it\n * from this module put every runtime value exported here — the handoff\n * prompt, the effort tables — into the chat's first-paint chunk.\n */\nexport { VERSE_TRANSIENT_EVENT_TYPES, isTransientVerseEvent } from './transient-events.js';\n\nexport type VerseTransientEventType = (typeof TRANSIENT_EVENT_TYPE_LIST)[number];\nexport type VerseTransientEvent = Extract<VerseEvent, { type: VerseTransientEventType }>;\nexport type VersePersistedEvent = Exclude<VerseEvent, { type: VerseTransientEventType }>;\n\n/**\n * Which endpoint a LOCAL seat sends its turns to.\n *\n * - `ollama` — the historical lane: the plain `claude` binary with\n * ANTHROPIC_BASE_URL pointed straight at Ollama's\n * Anthropic-compatible endpoint on :11434. Ollama\n * serialises this model architecture, so a fleet of local\n * agents on this lane is a queue (docs/LOCAL-FLEET.md).\n * - `llama-server` — the same binary pointed at the local Anthropic\n * normalising proxy that fronts llama-server. That proxy\n * is the ONLY way to reach llama-server's parallel slots\n * and the prompt-cache fix, because Qwen3.8's chat\n * template rejects Claude Code's request shape unless the\n * proxy rewrites it on the way through.\n *\n * DISPATCH ONLY. Model DISCOVERY stays on Ollama in both lanes — llama-server\n * implements neither `/api/tags` nor `/api/show`, which is where every local\n * seat's identity, context window and `tools` capability comes from.\n */\nexport type VerseLocalDispatch = 'ollama' | 'llama-server';\n\n/** What a client is told about this machine's local serving situation. */\nexport interface VerseLocalRuntimeSummary {\n /** Ollama reachable? Drives the local seats and an inline hint when false. */\n ollama: { reachable: boolean; baseUrl: string; models: string[] };\n /**\n * Where local seats DISPATCH turns, reported only when that is NOT the\n * default Ollama lane.\n *\n * Absent means `ollama`, i.e. exactly what every existing client already\n * assumes — so opting in is visible on the wire and NOT opting in changes no\n * payload at all.\n */\n dispatch?: { lane: VerseLocalDispatch; baseUrl: string };\n}\n\n/** GET /api/verse/bootstrap */\nexport interface VerseBootstrap {\n seats: VerseSeat[];\n projects: VerseProject[];\n sessions: VerseSession[];\n /** Whether POST routes are enabled on this server (`ashlr serve --allow-dispatch` / `ashlr verse`). */\n dispatchEnabled: boolean;\n localRuntime: VerseLocalRuntimeSummary;\n}\n\n/**\n * GET /api/verse/seats (V2.1)\n *\n * WHY THIS ROUTE EXISTS: `bootstrap` is a MOUNT-TIME snapshot. A client that\n * opened the app before the collector's first cycle finished would show\n * \"unknown\" forever. This is the same seat list, cheap enough to poll, and it\n * always reflects the collector's CURRENT state rather than a cached one.\n */\nexport interface VerseSeatsResponse {\n /** When this body was built. */\n sampledAt: string;\n seats: VerseSeat[];\n localRuntime: VerseBootstrap['localRuntime'];\n}\n\n/**\n * POST /api/verse/sessions\n *\n * Two spellings, never mixed (the API rejects the mix rather than silently\n * preferring one):\n * - `workspaceId` alone — the named workspace supplies primary and extras.\n * - `projectPath` (+ optional `extraRoots`) — an ad-hoc set, which is also\n * exactly the pre-workspace request shape.\n */\nexport interface VerseCreateSessionRequest {\n projectPath: string;\n seatId: string;\n model?: string;\n title?: string;\n /** V2.2 ADDITIVE. Absolute paths beyond the primary. */\n extraRoots?: string[];\n /** V2.2 ADDITIVE. Bind to a named workspace instead of naming paths. */\n workspaceId?: string;\n /**\n * SERVER-FILLED. The API resolves this from the registry once `workspaceId`\n * is validated, and never reads it off the request body — so a session can\n * not be labelled with a workspace name that is not the one it was built\n * from.\n */\n workspaceName?: string;\n /**\n * V3.9 ADDITIVE. Absent → the seat's preferred mode (preferences.json), else\n * `standard`. `expansive` on a model with no expansive budget is rejected.\n */\n contextMode?: VerseContextMode;\n /**\n * V3.9 ADDITIVE. Start this session as a handoff from an existing one. The\n * server resolves the source's title itself (never from the body) and pins\n * `handoffFrom`; the handoff TEXT is sent by the client as turn 1, after the\n * operator has read it — nothing is spent on their behalf.\n */\n handoffFromSessionId?: string;\n}\n\n/** POST /api/verse/sessions/:id/turns */\nexport interface VerseTurnRequest {\n text: string;\n}\nexport interface VerseTurnResponse {\n turnId: string;\n session: VerseSession;\n}\n\n/** GET /api/verse/sessions/:id */\nexport interface VerseSessionDetail {\n session: VerseSession;\n events: VerseEvent[];\n}\n\n/** Adapter input: how to launch one turn. Pure data, produced by the engine, consumed by the spawner. */\nexport interface VerseTurnLaunch {\n argv: string[];\n cwd: string;\n /** Extra env layered over a minimal base (PATH/HOME/TMPDIR/LANG). Never contains secrets. */\n env: Record<string, string>;\n /** Text written to stdin (codex); null when the prompt is in argv. */\n stdin: string | null;\n}\n\nexport const VERSE_MAX_TURN_TEXT_BYTES = 64 * 1024;\nexport const VERSE_MAX_EVENTS_PER_SESSION = 20_000;\nexport const VERSE_TURN_TIMEOUT_MS = 30 * 60 * 1000;\n/**\n * LAST-RESORT fallbacks, used only when neither the runtime, the seat's own\n * catalog, nor the verified per-model table (core/verse/model-windows.ts) knows\n * the model. Each mirrors what the CLI ITSELF assumes for an unknown id, so the\n * meter never claims more than the CLI will allow:\n *\n * - claude 200_000 — Claude Code's `Mg()` default for an unrecognized model.\n * Every KNOWN Claude id carries its real window (1M for the 5.x family,\n * Opus 4.8 and Sonnet 5) in the per-model table instead.\n * - codex 258_400 — 272_000 × the 95% `effective_context_window_percent`\n * every codex catalog entry carries; the figure codex's own rollouts report\n * as `model_context_window` (65,440 of 65,440 observed events).\n * - grok 500_000 — `context_window` for every grok-4.x id in the seat catalog.\n * - local 65_536 — the num_ctx the default local tag pins.\n */\nexport const VERSE_DEFAULT_CONTEXT_WINDOWS: Record<string, number> = {\n claude: 200_000,\n codex: 258_400,\n grok: 500_000,\n local: 65_536,\n};\n\n// ---------------------------------------------------------------------------\n// V3.9 context orchestration — request/response shapes (docs/VERSE-CONTEXT.md)\n// ---------------------------------------------------------------------------\n\n/** GET /api/verse/preferences — the operator's standing context choices. */\nexport interface VersePreferences {\n version: 1;\n /** Per-seat default context mode for NEW sessions. Absent = `standard`. */\n seats: Record<string, { contextMode?: VerseContextMode }>;\n /** Shared project memory. On by default; listed canonical paths opt out. */\n memory: { enabled: boolean; disabledProjects: string[] };\n /**\n * V3.10 ADDITIVE. Stream vendor-summarised reasoning on non-local seats\n * (claude `--thinking-display summarized`). Absent = on (Mason's default).\n */\n thinkingDisplay?: boolean;\n}\n\n/**\n * POST /api/verse/preferences — exactly ONE of the three forms per request, so\n * a body can never change more than the operator clicked.\n */\nexport type VersePreferencesUpdate =\n | { seatId: string; contextMode: VerseContextMode }\n | { memoryEnabled: boolean }\n | { projectPath: string; memoryEnabled: boolean };\n\n/** POST /api/verse/sessions/:id/context-mode */\nexport interface VerseContextModeRequest {\n mode: VerseContextMode;\n}\n\n/** POST /api/verse/sessions/:id/handoff-preview */\nexport interface VerseHandoffPreviewRequest {\n /**\n * Include the latest assistant message verbatim (capped) as the agent's own\n * summary — used after \"Ask this seat to summarize\" produced one.\n */\n includeLastAssistant?: boolean;\n /** Optional operator focus line, e.g. \"finish the migration of X\". ≤ 500 chars. */\n focus?: string;\n}\n\n/** Deterministic, zero-spend handoff note built from the session's event log. */\nexport interface VerseHandoffPreview {\n sourceSessionId: string;\n sourceTitle: string;\n /** The exact text to send as turn 1 of the new session. ≤ VERSE_HANDOFF_MAX_CHARS. */\n text: string;\n stats: {\n chars: number;\n /** chars / 4, rounded up — the same estimator the fit badges use. */\n estTokens: number;\n turnsCovered: number;\n filesTouched: number;\n /** Sections dropped to respect the cap, by name; empty when nothing was cut. */\n truncated: string[];\n };\n}\n\nexport const VERSE_HANDOFF_MAX_CHARS = 12_000;\n\n/**\n * The canned turn behind \"Ask this seat to summarize first\". Shared by the UI\n * (which sends it as an ordinary turn through the normal spend chokepoint) and\n * the handoff builder (which must NOT carry it into the new session as the\n * operator's \"latest ask\" — the new chat would otherwise be told to write a\n * handoff note instead of continuing the work).\n *\n * Written so the reply is useful as turn 1 of a session that has NONE of this\n * context. It asks for no tool use on purpose: a summary that starts editing\n * files is not a summary, and a read-only turn is also the cheapest one.\n */\nexport const VERSE_HANDOFF_SUMMARY_REQUEST = [\n 'This conversation is about to continue in a fresh session that has none of its context.',\n 'Write the handoff note that new session should start from. Do not edit files or run commands for this — only write the note.',\n '',\n 'Cover, concretely:',\n '- The goal, and what \"done\" looks like.',\n '- Decisions made so far, each with the reason it was made.',\n '- Current state: what is finished, what is half-done, what is untested.',\n '- Files changed and anything not yet committed.',\n '- How to verify the work (exact commands).',\n '- Open questions, risks, and approaches already tried that did not work.',\n '',\n 'Keep it under 600 words. Prefer file paths and commands over prose.',\n].join('\\n');\n\n/** GET /api/verse/context-fit — how big the reachable code is, in tokens. */\nexport interface VerseContextFitRoot {\n path: string;\n /** Tracked text files counted (git ls-files, binaries and >1 MB files skipped). */\n files: number;\n bytes: number;\n estTokens: number;\n /** True when the scan hit its file or time cap; estTokens is then a floor. */\n truncated: boolean;\n}\n\nexport interface VerseContextFit {\n roots: VerseContextFitRoot[];\n totalEstTokens: number;\n /** Always 'bytes/4' today; named so a better estimator can be introduced honestly. */\n estimator: 'bytes/4';\n sampledAt: string;\n}\n\n/**\n * Per-model verdict for a working set (see context-math.ts `fitVerdict`):\n * fits in standard, tight in standard, fits only in expansive, or too big for\n * any single context (split the work).\n */\nexport type VerseFitVerdict = 'fits' | 'tight' | 'expansive' | 'split';\n\n/** GET /api/verse/search?q=&limit= — keyword search over past sessions. Zero spend. */\nexport interface VerseSearchHit {\n sessionId: string;\n title: string;\n projectPath: string;\n engine: VerseEngine;\n seq: number;\n at: string;\n kind: 'user' | 'assistant';\n /** ≤ 240 chars around the first match, whitespace-collapsed. */\n snippet: string;\n score: number;\n}\n\nexport interface VerseSearchResponse {\n query: string;\n hits: VerseSearchHit[];\n /** Sessions actually scanned (the scan is bounded; see session-search.ts). */\n scannedSessions: number;\n truncated: boolean;\n}\n\n/** GET/POST /api/verse/memory — shared project memory for one project. */\nexport interface VerseProjectMemory {\n projectPath: string;\n enabled: boolean;\n /** Contents of MEMORY.md ('' when absent). */\n content: string;\n bytes: number;\n updatedAt: string | null;\n /** Other files the agents created in the memory directory (names only). */\n files: string[];\n /**\n * Present (true) only when `content` as SENT differs from the bytes on disk:\n * the public-JSON sanitizer rewrote the home path to `~` or replaced a\n * secret-looking value with `[REDACTED]`. The file itself is untouched; a\n * save that would write placeholders over real values is refused (409\n * VERSE_MEMORY_REDACTED), so the editor must say so before the operator types.\n */\n contentSanitized?: boolean;\n}\n\n/** POST /api/verse/memory */\nexport interface VerseProjectMemoryWrite {\n projectPath: string;\n content: string;\n}\n\nexport const VERSE_MEMORY_MAX_BYTES = 64 * 1024;\n\n/**\n * POST /api/verse/memory's own JSON body cap: JSON escaping can double the\n * content (every newline becomes `\\\\n`), plus room for the other fields. Every\n * other route keeps the 64 KiB default. Shared so the browser's pre-check can\n * never refuse a save the server would accept.\n */\nexport const VERSE_MEMORY_BODY_MAX_BYTES = 2 * VERSE_MEMORY_MAX_BYTES + 8 * 1024;\n\n/** Cap on the memory block appended to each session's system prompt. */\nexport const VERSE_MEMORY_BLOCK_MAX_BYTES = 6 * 1024;\n","/**\n * routes/verse/context/context-model.ts — the pure half of the context\n * components (handoff dialog, memory panel, session search). No React, no\n * I/O, so every rule the components render is pinned by a plain unit test.\n *\n * Every number shown here comes from context-math.ts (the one module the\n * server and the browser share), so \"compacts ≈367k\" in the handoff dialog is\n * the same figure the meter and the seat picker show.\n */\nimport type { VerseEngine, VerseModelOption, VerseSeat, VerseSession } from '../../../data/api-types.js';\nimport type {\n VerseContextMode,\n VerseFitVerdict,\n VersePreferences,\n VerseSearchHit,\n} from '../../../../core/verse/types.js';\nimport { VERSE_MEMORY_BLOCK_MAX_BYTES, VERSE_MEMORY_BODY_MAX_BYTES } from '../../../../core/verse/types.js';\nimport {\n budgetFor,\n canonicalModelId,\n estimateTokensFromChars,\n fitVerdict,\n hasExpansiveMode,\n sessionOverheadTokens,\n} from '../../../../core/verse/context-math.js';\nimport { formatContextWindow, formatRelative } from '../verse-model.js';\nimport { asClause, percentText, tidyProse } from '../autonomy/format.js';\nimport { formatTokens } from '../verse-readouts.js';\n\n// ---------------------------------------------------------------------------\n// Handoff\n// ---------------------------------------------------------------------------\n\n// The canned \"Ask this seat to summarize first\" turn is\n// VERSE_HANDOFF_SUMMARY_REQUEST in core/verse/types.ts, not a copy here: the\n// handoff builder on the server matches that exact text to keep it OUT of the\n// new session's \"latest requests\" (otherwise the new chat is told to write\n// another handoff note). A local copy that drifted by one character would\n// silently defeat that filter.\n\n/** Mirrors session-engine's TITLE_MAX so a title we send is never cut by the server instead. */\nexport const TITLE_MAX_CHARS = 120;\n\nconst PART_SUFFIX = /\\s·\\spart\\s(\\d+)$/;\n\n/**\n * Title for the session a handoff continues in: \"Fix the login bug · part 2\".\n * A continuation of a continuation counts up rather than stacking suffixes, so\n * the sidebar reads \"part 3\", never \"part 2 · part 2\".\n */\nexport function handoffTitle(sourceTitle: string): string {\n const collapsed = sourceTitle.replace(/\\s+/g, ' ').trim();\n const match = PART_SUFFIX.exec(collapsed);\n const base = (match ? collapsed.slice(0, match.index) : collapsed) || 'Untitled chat';\n const next = match ? Number.parseInt(match[1]!, 10) + 1 : 2;\n const suffix = ` · part ${next}`;\n const room = TITLE_MAX_CHARS - suffix.length;\n const clipped = base.length > room ? `${base.slice(0, room - 1).trimEnd()}…` : base;\n return `${clipped}${suffix}`;\n}\n\n/**\n * A seat's catalog entry for a model id. Exact id first, then canonical — a\n * session created before the alias fix stores `claude-opus-5.5` while the\n * catalog now lists `claude-opus-5-5` (context-math VERSE_MODEL_ID_ALIASES).\n */\nexport function modelOption(seat: VerseSeat | null | undefined, modelId: string): VerseModelOption | null {\n if (!seat) return null;\n const exact = seat.models.find((m) => m.id === modelId);\n if (exact) return exact;\n const canonical = canonicalModelId(modelId);\n return seat.models.find((m) => canonicalModelId(m.id) === canonical) ?? null;\n}\n\n/**\n * Why a seat+model cannot take a new session right now; null when it can.\n *\n * The seat's own reason is embedded as a clause: its closing period is\n * dropped (no \"exhausted..\") and any ISO instant in it — a health summary\n * saying when usage resets — is read as the viewer's local time.\n */\nexport function targetUnavailableReason(\n seat: VerseSeat | null | undefined,\n option: VerseModelOption | null,\n now: number = Date.now(),\n): string | null {\n if (!seat) return 'Pick a seat to continue on.';\n if (seat.health.state === 'unavailable') {\n return `${seat.label} is unavailable: ${asClause(tidyProse(seat.health.summary ?? 'no reason given', now))}.`;\n }\n if (!option) return 'Pick a model on this seat.';\n if (option.unavailableReason) {\n return `${option.label} cannot run on ${seat.label}: ${asClause(tidyProse(option.unavailableReason, now))}.`;\n }\n return null;\n}\n\nexport interface HandoffTarget {\n seatId: string;\n model: string;\n}\n\n/**\n * Where a handoff lands by default: the SAME seat and model (the common case\n * is \"same agent, fresh context\"). When that model can no longer run there,\n * the seat's first runnable model; when the seat itself is gone or\n * unavailable, the first runnable model on any available seat, in the seat\n * list's own order.\n */\nexport function defaultHandoffTarget(seats: readonly VerseSeat[], source: Pick<VerseSession, 'seatId' | 'model'>): HandoffTarget | null {\n const own = seats.find((s) => s.id === source.seatId);\n if (own && own.health.state !== 'unavailable') {\n const same = modelOption(own, source.model);\n if (same && !same.unavailableReason) return { seatId: own.id, model: same.id };\n const runnable = own.models.find((m) => !m.unavailableReason);\n if (runnable) return { seatId: own.id, model: runnable.id };\n }\n for (const seat of seats) {\n if (seat.health.state === 'unavailable') continue;\n const runnable = seat.models.find((m) => !m.unavailableReason);\n if (runnable) return { seatId: seat.id, model: runnable.id };\n }\n return null;\n}\n\n/**\n * The mode a handoff starts in. Only a mode that EXISTS for the target model\n * is ever returned (a mode with no budget would be refused by the server).\n *\n * 1. Same seat and model as the source → keep the source's mode. \"Continue in\n * a fresh chat\" means the same settings with a clean context; an operator\n * who chose expansive for this work chose it for the work.\n * 2. Otherwise the target seat's standing preference (preferences.json).\n * 3. Otherwise standard.\n */\nexport function defaultHandoffMode(input: {\n option: VerseModelOption | null;\n target: HandoffTarget | null;\n source: Pick<VerseSession, 'seatId' | 'model' | 'contextMode'>;\n preferences: VersePreferences | null | undefined;\n}): VerseContextMode {\n const { option, target, source, preferences } = input;\n const valid = (mode: VerseContextMode | undefined): mode is VerseContextMode =>\n mode !== undefined && budgetFor(option, mode) !== null;\n const sameModel = target !== null && target.seatId === source.seatId\n && canonicalModelId(target.model) === canonicalModelId(source.model);\n if (sameModel && valid(source.contextMode ?? 'standard')) return source.contextMode ?? 'standard';\n const preferred = target ? preferences?.seats[target.seatId]?.contextMode : undefined;\n if (valid(preferred)) return preferred;\n return 'standard';\n}\n\n/**\n * The mode to put on the create request, or undefined to leave it to the\n * server. A mode is sent only when the model has a budget for it — which is\n * exactly the server's acceptance rule — so what the dialog shows is what is\n * created, and an unknown-window model is never refused over a mode it could\n * not have.\n */\nexport function requestMode(option: VerseModelOption | null, mode: VerseContextMode): VerseContextMode | undefined {\n return budgetFor(option, mode) !== null ? mode : undefined;\n}\n\n/** \"1M window · compacts ≈367k\" for a model in a mode; null when the budget is unknown. */\nexport function budgetLine(option: VerseModelOption | null, mode: VerseContextMode): string | null {\n const budget = budgetFor(option, mode);\n if (!budget) return null;\n const window = `${formatContextWindow(budget.contextWindow)} window`;\n return budget.autoCompactAt === null ? window : `${window} · compacts ≈${formatTokens(budget.autoCompactAt)}`;\n}\n\nexport interface HandoffFit {\n verdict: VerseFitVerdict | null;\n /** The handoff text's own estimate (chars / 4). */\n handoffTokens: number;\n /** The target engine's estimated fixed prompt (context-math `sessionOverheadTokens`). */\n overheadTokens: number;\n /** Handoff + that fixed prompt: what the new session holds before its first reply. */\n needTokens: number;\n /** One sentence for the dialog. */\n text: string;\n tone: 'ok' | 'warn' | 'danger' | 'unknown';\n}\n\n/**\n * Will the new session START comfortably? The handoff is small by design\n * (≤ 12k chars ≈ 3k tokens), but every fresh session also carries the CLI's\n * fixed prompt — a large share of a 64k local slot — so this is a real\n * question on small windows, and the sentence shows both halves of the sum\n * rather than a bare verdict.\n *\n * The fixed prompt is the TARGET seat's engine estimate (local ≈15k measured,\n * claude ≈25k, …), not one flat figure: a flat 30k called every handoff to a\n * 64k local seat \"too big for one context\" when the real sum was ~20k. It is\n * still an estimate — no CLI reports its base prompt before the first turn —\n * so the sentence says \"estimated\" rather than presenting it as a reading.\n * `engine` null (target seat not known yet) falls back to the largest estimate.\n */\nexport function handoffFit(\n textChars: number,\n option: VerseModelOption | null,\n mode: VerseContextMode,\n engine: VerseEngine | null,\n): HandoffFit {\n const handoffTokens = estimateTokensFromChars(textChars);\n const overheadTokens = sessionOverheadTokens(engine);\n const needTokens = handoffTokens + overheadTokens;\n const verdict = fitVerdict(handoffTokens, option, overheadTokens);\n const sum = `~${formatTokens(handoffTokens)} tokens of handoff + an estimated ~${formatTokens(overheadTokens)} of fixed prompt`;\n const standard = budgetFor(option, 'standard');\n const standardCap = standard ? standard.autoCompactAt ?? standard.contextWindow : null;\n const base = { verdict, handoffTokens, overheadTokens, needTokens };\n switch (verdict) {\n case 'fits':\n return { ...base, tone: 'ok', text: `Fits: ${sum} leaves most of the budget before the first compaction.` };\n case 'tight':\n return {\n ...base,\n tone: 'warn',\n text: `Tight: ${sum} is ${percentText((needTokens / (standardCap ?? needTokens)) * 100)} of where this model compacts — the new chat will compact early.`,\n };\n case 'expansive':\n return mode === 'expansive'\n ? { ...base, tone: 'warn', text: `Fits only the expansive budget: ${sum}.` }\n : { ...base, tone: 'danger', text: `Too big for the standard budget (${sum}). Switch to Expansive, or trim the handoff.` };\n case 'split':\n return { ...base, tone: 'danger', text: `Too big for one context on this model (${sum}). Trim the handoff or pick a seat with a larger window.` };\n default:\n return { ...base, verdict: null, tone: 'unknown', text: 'This model’s window is not known, so there is no fit estimate.' };\n }\n}\n\n/** True when the target model has a real expansive budget (context-math, re-exported for the dialog). */\nexport function offersExpansive(option: VerseModelOption | null): boolean {\n return hasExpansiveMode(option);\n}\n\n/** A local turn runs on this machine; every other engine spends subscription usage. */\nexport function turnCostSentence(engine: VerseEngine, seatLabel: string): string {\n return engine === 'local'\n ? `Runs on this machine with ${seatLabel}; it spends no subscription usage.`\n : `Sends one turn to ${seatLabel} and spends from its usage. The automatic preview costs nothing.`;\n}\n\n// ---------------------------------------------------------------------------\n// Bytes\n// ---------------------------------------------------------------------------\n\nconst encoder = typeof TextEncoder === 'function' ? new TextEncoder() : null;\n\n/** UTF-8 byte length — the unit the server's caps (64 KB memory content, 64 KB turn) are written in. */\nexport function utf8Bytes(text: string): number {\n if (encoder) return encoder.encode(text).length;\n // Fallback for an environment with no TextEncoder: count code points by width.\n let bytes = 0;\n for (const ch of text) {\n const cp = ch.codePointAt(0) ?? 0;\n bytes += cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4;\n }\n return bytes;\n}\n\n/**\n * The API's default request-body cap: `readBody` in src/core/web/api.ts, which\n * every /api/verse POST uses unless its route passes a larger one (only\n * POST /memory does — see MEMORY_BODY_MAX_BYTES). A write travels as JSON, so what must fit is\n * the ENCODED body — every `\\n` and `\"` escaped to two bytes — not the text\n * alone; the editors measure it so a refusal happens on screen instead of as\n * \"request body too large\".\n */\nexport const API_BODY_MAX_BYTES = 65_536;\n\n/**\n * POST /api/verse/memory's own body cap — mirrors `VERSE_MEMORY_BODY_MAX_BYTES`\n * in src/core/verse/verse-api.ts (a server module the browser cannot import):\n * room for 64 KiB of content in which EVERY byte escapes to two, plus the\n * project path and the JSON around it. The server still holds the CONTENT to\n * VERSE_MEMORY_MAX_BYTES after parsing. Guarding the memory editor with the\n * 64 KiB default instead blocked saves the server accepts — a 60–64 KB\n * MEMORY.md with ordinary line breaks could not be edited from the panel,\n * which is the exact case the server's larger cap exists for.\n */\nexport const MEMORY_BODY_MAX_BYTES = VERSE_MEMORY_BODY_MAX_BYTES;\n\n/** UTF-8 size of `body` exactly as the client will send it. */\nexport function jsonBodyBytes(body: unknown): number {\n return utf8Bytes(JSON.stringify(body) ?? '');\n}\n\nexport function formatBytes(bytes: number): string {\n if (!Number.isFinite(bytes) || bytes < 0) return '—';\n if (bytes < 1024) return `${bytes} B`;\n const kb = bytes / 1024;\n return `${kb < 10 ? kb.toFixed(1).replace(/\\.0$/, '') : Math.round(kb)} KB`;\n}\n\n/**\n * A relative time that reads as a phrase: \"just now\", \"5m ago\", \"on Sep 19\".\n * `formatRelative` (verse-model) is sized for a 5ch sidebar column and reads\n * as a bare token; prose needs the preposition.\n */\nexport function relativePhrase(iso: string | null | undefined, now: number = Date.now()): string | null {\n if (!iso) return null;\n const short = formatRelative(iso, now);\n if (!short) return null;\n if (short === 'now') return 'just now';\n // Only the relative tokens (\"5m\", \"3h\", \"2d\") take \"ago\". Anything else is a\n // DATE, whatever the locale prints: \"Sep 1\" (en-US) but \"1 Sept\" (en-GB)\n // and \"1. Sept.\" (de) start with a digit — testing for a leading digit\n // printed \"Last completed 1 Sept ago.\" outside the US.\n return /^\\d+[mhd]$/.test(short) ? `${short} ago` : `on ${short}`;\n}\n\n// ---------------------------------------------------------------------------\n// Memory\n// ---------------------------------------------------------------------------\n\n/**\n * Shapes that are almost certainly credentials. MEMORY.md is sent to every\n * seat's model on every turn, so a pasted key would travel to every provider\n * — the panel warns BEFORE the save rather than trusting the server's scrub\n * to catch it on the way out. Conservative on purpose: a false alarm on prose\n * would teach the operator to ignore the warning.\n */\nconst SECRET_PATTERNS: ReadonlyArray<{ label: string; re: RegExp }> = [\n { label: 'a private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },\n { label: 'an Anthropic API key', re: /\\bsk-ant-[A-Za-z0-9_-]{20,}/ },\n { label: 'an OpenAI-style API key', re: /\\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/ },\n { label: 'an xAI API key', re: /\\bxai-[A-Za-z0-9]{32,}/ },\n { label: 'a GitHub token', re: /\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}|\\bgithub_pat_[A-Za-z0-9_]{40,}/ },\n { label: 'an AWS access key', re: /\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/ },\n { label: 'a Slack token', re: /\\bxox[abprs]-[A-Za-z0-9-]{10,}/ },\n { label: 'a Google API key', re: /\\bAIza[0-9A-Za-z_-]{35}\\b/ },\n { label: 'a Stripe secret key', re: /\\b(?:sk|rk)_live_[0-9A-Za-z]{20,}/ },\n];\n\n/**\n * Mirrors `VERSE_MEMORY_BLOCK_MAX_BYTES` in src/core/verse/project-memory.ts\n * (a node module the browser cannot import): the most memory text a chat's\n * instructions carry, however large MEMORY.md itself is.\n */\nexport const MEMORY_BLOCK_MAX_BYTES = VERSE_MEMORY_BLOCK_MAX_BYTES;\n\n/**\n * What memory costs, in the one wording the memory panel and the resources\n * panel share. Memory is ON by default and snapshotted into every new chat's\n * system prompt (claude `--append-system-prompt`, codex `developer_instructions`,\n * grok `--rules`), which re-rides every turn, and it asks writable seats to\n * read and update MEMORY.md — tool calls and output. On a paid seat that is\n * real (if small, mostly cached) usage, so \"nothing here spends\" would be\n * false for exactly the operator deciding whether to leave it on near a limit.\n * Reading and editing the file from the panel is still free.\n */\nexport const MEMORY_SPEND_NOTE =\n `Reading and editing memory here spends nothing. On a paid seat it is not free to use: each new chat’s system prompt carries a memory block of up to ${MEMORY_BLOCK_MAX_BYTES / 1024} KB, re-sent every turn (cached after the first), and the agent reads and updates MEMORY.md as it works. Local seats spend nothing.`;\n\n/** The first credential shape found, as a phrase (\"a GitHub token\"), or null. */\nexport function secretLike(text: string): string | null {\n for (const { label, re } of SECRET_PATTERNS) if (re.test(text)) return label;\n return null;\n}\n\n/**\n * The placeholder the server's scrubber (src/core/util/scrub.ts) writes over\n * secret-shaped text in every rule. In a memory view flagged\n * `contentSanitized`, each one stands for a REAL value still in MEMORY.md.\n */\nexport const REDACTION_MARKER = '[REDACTED]';\n\n/** How many redaction placeholders a text carries. */\nexport function redactionMarkers(text: string): number {\n return text.split(REDACTION_MARKER).length - 1;\n}\n\n// ---------------------------------------------------------------------------\n// Search\n// ---------------------------------------------------------------------------\n\n/** Below this many characters a keyword search over every message is noise, not recall. */\nexport const SEARCH_MIN_CHARS = 2;\n/** Keystrokes inside this window collapse into one request. */\nexport const SEARCH_DEBOUNCE_MS = 250;\n/** Hits asked for per search — enough to fill the sidebar twice over. */\nexport const SEARCH_LIMIT = 30;\n\n/** Whitespace-separated terms, lowercased and de-duplicated (the server ANDs them). */\nexport function searchTerms(query: string): string[] {\n const out: string[] = [];\n for (const raw of query.toLowerCase().split(/\\s+/)) {\n if (raw && !out.includes(raw)) out.push(raw);\n }\n return out;\n}\n\nexport interface HighlightSegment {\n text: string;\n match: boolean;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Split `text` into plain and matched runs for every term, case-insensitive.\n * Longest terms first so \"migrate\" wins over \"migrat\" at the same position.\n */\nexport function highlightSegments(text: string, terms: readonly string[]): HighlightSegment[] {\n const usable = [...terms].filter((t) => t.length > 0).sort((a, b) => b.length - a.length);\n if (usable.length === 0 || text.length === 0) return text ? [{ text, match: false }] : [];\n const re = new RegExp(usable.map(escapeRegExp).join('|'), 'gi');\n const out: HighlightSegment[] = [];\n let last = 0;\n for (const m of text.matchAll(re)) {\n const start = m.index ?? 0;\n if (m[0].length === 0) continue;\n if (start > last) out.push({ text: text.slice(last, start), match: false });\n out.push({ text: m[0], match: true });\n last = start + m[0].length;\n }\n if (last < text.length) out.push({ text: text.slice(last), match: false });\n return out;\n}\n\nexport interface SessionSearchGroup {\n sessionId: string;\n title: string;\n projectPath: string;\n engine: VerseEngine;\n /** The best-scoring hit in this session (the server returns hits best-first). */\n top: VerseSearchHit;\n /** Every hit this session contributed to the response. */\n count: number;\n /** Newest hit time, for the row's relative time. */\n latestAt: string;\n}\n\n/**\n * One row per session. The server ranks MESSAGES; the sidebar lists CHATS,\n * and five rows for one chat would push every other match off screen. Order\n * is the order each session first appears, i.e. by its best hit.\n */\nexport function groupSearchHits(hits: readonly VerseSearchHit[]): SessionSearchGroup[] {\n const groups = new Map<string, SessionSearchGroup>();\n for (const hit of hits) {\n const existing = groups.get(hit.sessionId);\n if (!existing) {\n groups.set(hit.sessionId, {\n sessionId: hit.sessionId,\n title: hit.title,\n projectPath: hit.projectPath,\n engine: hit.engine,\n top: hit,\n count: 1,\n latestAt: hit.at,\n });\n continue;\n }\n existing.count += 1;\n if (hit.at > existing.latestAt) existing.latestAt = hit.at;\n }\n return [...groups.values()];\n}\n"],"mappings":"oMAglBA,IAAa,EAAgB,CAAC,UAAW,MAAO,SAAU,OAAQ,QAAS,KAAK,EAiSnE,EAA4B,MAqF5B,EAA0B,KAa1B,EAAgC,CAC3C,0FACA,+HACA,GACA,qBACA,0CACA,6DACA,0EACA,kDACA,6CACA,2EACA,GACA,qEACF,CAAC,CAAC,KAAK;CAAI,EA4EE,EAAyB,MAQzB,EAA8B,OAG9B,EAA+B,KC5gCtC,EAAc,oBAOpB,SAAgB,EAAa,EAA6B,CACxD,IAAM,EAAY,EAAY,QAAQ,OAAQ,GAAG,CAAC,CAAC,KAAK,EAClD,EAAQ,EAAY,KAAK,CAAS,EAClC,GAAQ,EAAQ,EAAU,MAAM,EAAG,EAAM,KAAK,EAAI,IAAc,gBAEhE,EAAS,WADF,EAAQ,OAAO,SAAS,EAAM,GAAK,EAAE,EAAI,EAAI,IAEpD,EAAA,IAAyB,EAAO,OAEtC,MAAO,GADS,EAAK,OAAS,EAAO,GAAG,EAAK,MAAM,EAAG,EAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,GAAK,IAC3D,GACtB,CAOA,SAAgB,EAAY,EAAoC,EAA0C,CACxG,GAAI,CAAC,EAAM,OAAO,KAClB,IAAM,EAAQ,EAAK,OAAO,KAAM,GAAM,EAAE,KAAO,CAAO,EACtD,GAAI,EAAO,OA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,CAAE,OAAM,MAAO,EAAM,CAAC,EAAI,CAAC,EACxF,IAAM,EAAK,IAAI,OAAO,EAAO,IAAI,CAAY,CAAC,CAAC,KAAK,GAAG,EAAG,IAAI,EACxD,EAA0B,CAAC,EAC7B,EAAO,EACX,IAAK,IAAM,KAAK,EAAK,SAAS,CAAE,EAAG,CACjC,IAAM,EAAQ,EAAE,OAAS,EACrB,EAAE,EAAE,CAAC,SAAW,IAChB,EAAQ,GAAM,EAAI,KAAK,CAAE,KAAM,EAAK,MAAM,EAAM,CAAK,EAAG,MAAO,EAAM,CAAC,EAC1E,EAAI,KAAK,CAAE,KAAM,EAAE,GAAI,MAAO,EAAK,CAAC,EACpC,EAAO,EAAQ,EAAE,EAAE,CAAC,OACtB,CAEA,OADI,EAAO,EAAK,QAAQ,EAAI,KAAK,CAAE,KAAM,EAAK,MAAM,CAAI,EAAG,MAAO,EAAM,CAAC,EAClE,CACT,CAoBA,SAAgB,EAAgB,EAAuD,CACrF,IAAM,EAAS,IAAI,IACnB,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAW,EAAO,IAAI,EAAI,SAAS,EACzC,GAAI,CAAC,EAAU,CACb,EAAO,IAAI,EAAI,UAAW,CACxB,UAAW,EAAI,UACf,MAAO,EAAI,MACX,YAAa,EAAI,YACjB,OAAQ,EAAI,OACZ,IAAK,EACL,MAAO,EACP,SAAU,EAAI,EAChB,CAAC,EACD,QACF,CACA,EAAS,OAAS,EACd,EAAI,GAAK,EAAS,WAAU,EAAS,SAAW,EAAI,GAC1D,CACA,MAAO,CAAC,GAAG,EAAO,OAAO,CAAC,CAC5B"}
@@ -1,2 +1,2 @@
1
- import{D as e,E as t,H as n,P as r,U as i,j as a,l as o,o as s}from"./global-CXHHMz9o.js";import{f as c,i as l,r as u,w as d}from"./VerseConsoleApp-DeuBEvAO.js";import{l as f}from"./verse-store-DNVRuiJL.js";import{t as p}from"./format-DEAaVF6X.js";var m=`verse-preferences`,h=`verse-memory:`;async function g(e){try{let t=await e.json();if(typeof t.error==`string`&&t.error)return t.error;if(typeof t.note==`string`&&t.note)return t.note}catch{}return null}async function _(t,n){let r=await fetch(t,{method:`GET`,credentials:`same-origin`,headers:{"x-ashlr-read-client":e()},signal:n});if(r.status===401)throw a(),new s(`Read session expired.`,401,t);if(!r.ok){let e=await g(r);throw new s(`GET ${t} failed (HTTP ${r.status})${e?`: ${p(e)}`:``}.`,r.status,t,e)}return await r.json()}async function v(e,n){let i=t();if(!i)throw new l;let a=await o(e,n,i);return r(),a}function y(e,t){let n=t.toString();return n?`${e}?${n}`:e}async function b(e,t){let r={mode:t},i=await v(d(e,`/context-mode`),r);return f(e,i),n(u),i}async function x(e,t={}){let n={};t.includeLastAssistant===!0&&(n.includeLastAssistant=!0);let r=typeof t.focus==`string`?t.focus.trim().slice(0,500):``;return r&&(n.focus=r),v(d(e,`/handoff-preview`),n)}async function S(e){let{source:t}=e,n={projectPath:t.projectPath,seatId:e.seatId,handoffFromSessionId:t.id},r=(t.extraRoots??[]).filter(e=>typeof e==`string`&&e.length>0&&e!==t.projectPath);r.length>0&&(n.extraRoots=r),e.model&&(n.model=e.model),e.contextMode&&(n.contextMode=e.contextMode);let i=e.title?.trim();i&&(n.title=i);let a=await v(`/api/verse/sessions`,n);return c(),a}function C(e){return _(`/api/verse/preferences`,e)}var w={key:m,fetch:e=>C(e)};async function T(e){let t=await v(`/api/verse/preferences`,e);return n(m),i(h),t}function E(e){let t=new URLSearchParams,n=e.workspaceId?.trim()??``,r=e.projectPath?.trim()??``,i=(e.extraRoots??[]).map(e=>e.trim()).filter(e=>e.length>0);if(n){if(r||i.length>0)throw Error(`Estimate a workspace or a folder set, not both.`);t.set(`workspaceId`,n)}else if(r){t.set(`projectPath`,r);for(let e of i)t.append(`extraRoots`,e)}else throw Error(`Pick a project or a workspace to estimate.`);return y(`/api/verse/context-fit`,t)}function D(e,t){return _(E(e),t)}function O(e,t,n){let r=new URLSearchParams({q:e});return typeof t==`number`&&Number.isFinite(t)&&r.set(`limit`,String(Math.max(1,Math.min(50,Math.floor(t))))),_(y(`/api/verse/search`,r),n)}function k(e){return`${h}${e}`}function A(e,t){return _(y(`/api/verse/memory`,new URLSearchParams({projectPath:e})),t)}function j(e){return{key:k(e),fetch:t=>A(e,t)}}async function M(e,t){let r=await v(`/api/verse/memory`,{projectPath:e,content:t});return n(k(e)),r}export{A as a,T as c,M as d,C as i,w as l,D as n,O as o,x as r,b as s,S as t,j as u};
2
- //# sourceMappingURL=context-queries-wvcRnV-I.js.map
1
+ import{D as e,E as t,H as n,P as r,U as i,j as a,l as o,o as s}from"./global-CNNGMril.js";import{f as c,i as l,r as u,w as d}from"./VerseConsoleApp-BCY5uSok.js";import{l as f}from"./verse-store-DNVRuiJL.js";import{t as p}from"./format-Dk4Fmxax.js";var m=`verse-preferences`,h=`verse-memory:`;async function g(e){try{let t=await e.json();if(typeof t.error==`string`&&t.error)return t.error;if(typeof t.note==`string`&&t.note)return t.note}catch{}return null}async function _(t,n){let r=await fetch(t,{method:`GET`,credentials:`same-origin`,headers:{"x-ashlr-read-client":e()},signal:n});if(r.status===401)throw a(),new s(`Read session expired.`,401,t);if(!r.ok){let e=await g(r);throw new s(`GET ${t} failed (HTTP ${r.status})${e?`: ${p(e)}`:``}.`,r.status,t,e)}return await r.json()}async function v(e,n){let i=t();if(!i)throw new l;let a=await o(e,n,i);return r(),a}function y(e,t){let n=t.toString();return n?`${e}?${n}`:e}async function b(e,t){let r={mode:t},i=await v(d(e,`/context-mode`),r);return f(e,i),n(u),i}async function x(e,t={}){let n={};t.includeLastAssistant===!0&&(n.includeLastAssistant=!0);let r=typeof t.focus==`string`?t.focus.trim().slice(0,500):``;return r&&(n.focus=r),v(d(e,`/handoff-preview`),n)}async function S(e){let{source:t}=e,n={projectPath:t.projectPath,seatId:e.seatId,handoffFromSessionId:t.id},r=(t.extraRoots??[]).filter(e=>typeof e==`string`&&e.length>0&&e!==t.projectPath);r.length>0&&(n.extraRoots=r),e.model&&(n.model=e.model),e.contextMode&&(n.contextMode=e.contextMode);let i=e.title?.trim();i&&(n.title=i);let a=await v(`/api/verse/sessions`,n);return c(),a}function C(e){return _(`/api/verse/preferences`,e)}var w={key:m,fetch:e=>C(e)};async function T(e){let t=await v(`/api/verse/preferences`,e);return n(m),i(h),t}function E(e){let t=new URLSearchParams,n=e.workspaceId?.trim()??``,r=e.projectPath?.trim()??``,i=(e.extraRoots??[]).map(e=>e.trim()).filter(e=>e.length>0);if(n){if(r||i.length>0)throw Error(`Estimate a workspace or a folder set, not both.`);t.set(`workspaceId`,n)}else if(r){t.set(`projectPath`,r);for(let e of i)t.append(`extraRoots`,e)}else throw Error(`Pick a project or a workspace to estimate.`);return y(`/api/verse/context-fit`,t)}function D(e,t){return _(E(e),t)}function O(e,t,n){let r=new URLSearchParams({q:e});return typeof t==`number`&&Number.isFinite(t)&&r.set(`limit`,String(Math.max(1,Math.min(50,Math.floor(t))))),_(y(`/api/verse/search`,r),n)}function k(e){return`${h}${e}`}function A(e,t){return _(y(`/api/verse/memory`,new URLSearchParams({projectPath:e})),t)}function j(e){return{key:k(e),fetch:t=>A(e,t)}}async function M(e,t){let r=await v(`/api/verse/memory`,{projectPath:e,content:t});return n(k(e)),r}export{A as a,T as c,M as d,C as i,w as l,D as n,O as o,x as r,b as s,S as t,j as u};
2
+ //# sourceMappingURL=context-queries-CktFQqSS.js.map