yepanywhere 0.9.0 → 0.9.2

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 (502) hide show
  1. package/bundled/@yep-anywhere/shared/dist/__tests__/long-context-effort-warning.test.js +19 -0
  2. package/bundled/@yep-anywhere/shared/dist/__tests__/long-context-effort-warning.test.js.map +1 -1
  3. package/bundled/@yep-anywhere/shared/dist/__tests__/model-prices.test.js +12 -0
  4. package/bundled/@yep-anywhere/shared/dist/__tests__/model-prices.test.js.map +1 -1
  5. package/bundled/@yep-anywhere/shared/dist/app-types.d.ts +2 -2
  6. package/bundled/@yep-anywhere/shared/dist/app-types.d.ts.map +1 -1
  7. package/bundled/@yep-anywhere/shared/dist/app-types.js +5 -5
  8. package/bundled/@yep-anywhere/shared/dist/app-types.js.map +1 -1
  9. package/bundled/@yep-anywhere/shared/dist/artifact-viewer.d.ts +21 -0
  10. package/bundled/@yep-anywhere/shared/dist/artifact-viewer.d.ts.map +1 -1
  11. package/bundled/@yep-anywhere/shared/dist/artifact-viewer.js +22 -1
  12. package/bundled/@yep-anywhere/shared/dist/artifact-viewer.js.map +1 -1
  13. package/bundled/@yep-anywhere/shared/dist/capability-ids.d.ts +6 -0
  14. package/bundled/@yep-anywhere/shared/dist/capability-ids.d.ts.map +1 -1
  15. package/bundled/@yep-anywhere/shared/dist/capability-ids.js +6 -0
  16. package/bundled/@yep-anywhere/shared/dist/capability-ids.js.map +1 -1
  17. package/bundled/@yep-anywhere/shared/dist/claude-sdk-schema/tool/ToolResultSchemas.d.ts +2 -2
  18. package/bundled/@yep-anywhere/shared/dist/find/documentFind.d.ts +41 -0
  19. package/bundled/@yep-anywhere/shared/dist/find/documentFind.d.ts.map +1 -0
  20. package/bundled/@yep-anywhere/shared/dist/find/documentFind.js +280 -0
  21. package/bundled/@yep-anywhere/shared/dist/find/documentFind.js.map +1 -0
  22. package/bundled/@yep-anywhere/shared/dist/find/frameFindAgent.d.ts +2 -0
  23. package/bundled/@yep-anywhere/shared/dist/find/frameFindAgent.d.ts.map +1 -0
  24. package/bundled/@yep-anywhere/shared/dist/find/frameFindAgent.generated.d.ts +2 -0
  25. package/bundled/@yep-anywhere/shared/dist/find/frameFindAgent.generated.d.ts.map +1 -0
  26. package/bundled/@yep-anywhere/shared/dist/find/frameFindAgent.generated.js +5 -0
  27. package/bundled/@yep-anywhere/shared/dist/find/frameFindAgent.generated.js.map +1 -0
  28. package/bundled/@yep-anywhere/shared/dist/find/frameFindAgent.js +59 -0
  29. package/bundled/@yep-anywhere/shared/dist/find/frameFindAgent.js.map +1 -0
  30. package/bundled/@yep-anywhere/shared/dist/find/protocol.d.ts +46 -0
  31. package/bundled/@yep-anywhere/shared/dist/find/protocol.d.ts.map +1 -0
  32. package/bundled/@yep-anywhere/shared/dist/find/protocol.js +45 -0
  33. package/bundled/@yep-anywhere/shared/dist/find/protocol.js.map +1 -0
  34. package/bundled/@yep-anywhere/shared/dist/index.d.ts +4 -2
  35. package/bundled/@yep-anywhere/shared/dist/index.d.ts.map +1 -1
  36. package/bundled/@yep-anywhere/shared/dist/index.js +3 -1
  37. package/bundled/@yep-anywhere/shared/dist/index.js.map +1 -1
  38. package/bundled/@yep-anywhere/shared/dist/long-context-effort-warning.d.ts +11 -11
  39. package/bundled/@yep-anywhere/shared/dist/long-context-effort-warning.d.ts.map +1 -1
  40. package/bundled/@yep-anywhere/shared/dist/long-context-effort-warning.js +26 -9
  41. package/bundled/@yep-anywhere/shared/dist/long-context-effort-warning.js.map +1 -1
  42. package/bundled/@yep-anywhere/shared/dist/model-prices.d.ts.map +1 -1
  43. package/bundled/@yep-anywhere/shared/dist/model-prices.js +9 -2
  44. package/bundled/@yep-anywhere/shared/dist/model-prices.js.map +1 -1
  45. package/bundled/@yep-anywhere/shared/dist/pdfjs.d.ts +7 -0
  46. package/bundled/@yep-anywhere/shared/dist/pdfjs.d.ts.map +1 -0
  47. package/bundled/@yep-anywhere/shared/dist/pdfjs.js +7 -0
  48. package/bundled/@yep-anywhere/shared/dist/pdfjs.js.map +1 -0
  49. package/bundled/@yep-anywhere/shared/dist/server-capabilities.d.ts +20 -0
  50. package/bundled/@yep-anywhere/shared/dist/server-capabilities.d.ts.map +1 -1
  51. package/bundled/@yep-anywhere/shared/dist/server-capabilities.js +22 -0
  52. package/bundled/@yep-anywhere/shared/dist/server-capabilities.js.map +1 -1
  53. package/bundled/@yep-anywhere/shared/dist/skill-invocations.d.ts.map +1 -1
  54. package/bundled/@yep-anywhere/shared/dist/skill-invocations.js +7 -10
  55. package/bundled/@yep-anywhere/shared/dist/skill-invocations.js.map +1 -1
  56. package/bundled/@yep-anywhere/shared/dist/types.d.ts +7 -0
  57. package/bundled/@yep-anywhere/shared/dist/types.d.ts.map +1 -1
  58. package/bundled/@yep-anywhere/shared/dist/types.js.map +1 -1
  59. package/bundled/@yep-anywhere/shared/package.json +1 -1
  60. package/client-dist/assets/AboutSettings-CCzudbSj.js +1 -0
  61. package/client-dist/assets/{ActivityPage-FgSG_9Sl.js → ActivityPage-Bn0LbMgE.js} +1 -1
  62. package/client-dist/assets/{AgentContextSettings-BfTCI7qG.js → AgentContextSettings-DI8jQVIx.js} +3 -3
  63. package/client-dist/assets/AgentsPage-Ci_iJt8T.js +2 -0
  64. package/client-dist/assets/App-rFnK5pnF.js +2 -0
  65. package/client-dist/assets/AppearanceSettings-DTYVt0W5.js +2 -0
  66. package/client-dist/assets/AppsSettings-hbh_sguk.js +1 -0
  67. package/client-dist/assets/AttachmentChip-BFve3lTD.js +1 -0
  68. package/client-dist/assets/{AuthContext-CVsoMulX.js → AuthContext-DmXjW0be.js} +1 -1
  69. package/client-dist/assets/{BangCommandDisplayObject-B8KrHDzH.js → BangCommandDisplayObject-BH2KRGnc.js} +1 -1
  70. package/client-dist/assets/BangCommandsPage-MfkuL8yS.js +1 -0
  71. package/client-dist/assets/BrowserDebugToolbarButton-BPghQu17.js +1 -0
  72. package/client-dist/assets/{CacheMissBillingSettings-Bfqlk9rA.js → CacheMissBillingSettings-rUgC-_DD.js} +2 -2
  73. package/client-dist/assets/{CodexUpdatePrompt-ChHtbla-.js → CodexUpdatePrompt-mT9K-f1e.js} +1 -1
  74. package/client-dist/assets/{CommittedRangeInput-C3Z7YUlS.js → CommittedRangeInput-BwuV6Q6c.js} +1 -1
  75. package/client-dist/assets/{CommittedRangeNumberInput-D497_5ff.js → CommittedRangeNumberInput-C5YSVltB.js} +1 -1
  76. package/client-dist/assets/ComputerControlSettings-MWIdP7SS.js +1 -0
  77. package/client-dist/assets/{ConversationPreviewPage-CTWx9N3v.js → ConversationPreviewPage-B47r7mUF.js} +2 -2
  78. package/client-dist/assets/DevelopmentSettings-BEAy_xq-.js +1 -0
  79. package/client-dist/assets/DevicesSettings-DKQOZkRN.js +1 -0
  80. package/client-dist/assets/EmulatorPage-DlsPq3nR.js +1 -0
  81. package/client-dist/assets/EmulatorSettings-C6Ye1k_Y.js +1 -0
  82. package/client-dist/assets/EnvironmentSettings-ou8UNqTa.js +1 -0
  83. package/client-dist/assets/FilePage-Cw2PaO5H.js +1 -0
  84. package/client-dist/assets/FilterDropdown-CACc6ysA.js +1 -0
  85. package/client-dist/assets/FilterDropdown-D11gXriH.css +1 -0
  86. package/client-dist/assets/FloatingActionButton-Bl1Eumxh.js +1 -0
  87. package/client-dist/assets/{GitStatusPage-879aktqc.js → GitStatusPage-CLTkgnDI.js} +3 -3
  88. package/client-dist/assets/GlobalSessionsPage-Bvzs4zmW.js +2 -0
  89. package/client-dist/assets/GlobalSessionsPage-dlTB6crv.css +1 -0
  90. package/client-dist/assets/{HeartbeatTextArea-CKxL-bdJ.js → HeartbeatTextArea-CtP5kx9R.js} +1 -1
  91. package/client-dist/assets/HostIdentityContext-DA7dMF-y.js +1 -0
  92. package/client-dist/assets/HostsPage-CBOYGC2-.js +1 -0
  93. package/client-dist/assets/{InboxContext-opkOiXDB.js → InboxContext-8PXoTbK1.js} +1 -1
  94. package/client-dist/assets/InboxPage-DWl7uzdw.js +1 -0
  95. package/client-dist/assets/IssueSettings-BVljRpuD.js +1 -0
  96. package/client-dist/assets/IssuesPage-BFxgsMkf.js +1 -0
  97. package/client-dist/assets/LifecycleWebhooksSettings-Qw_dN3F3.js +1 -0
  98. package/client-dist/assets/{LocalAccessSettings-BpmNC9pI.js → LocalAccessSettings-SWirs75o.js} +3 -3
  99. package/client-dist/assets/LocalMediaModal-B3KXtyEB.css +1 -0
  100. package/client-dist/assets/LocalMediaModal-B9eHVx6y.js +14 -0
  101. package/client-dist/assets/{LoginPage-Cu7cX9wS.js → LoginPage-CYWqVJ95.js} +1 -1
  102. package/client-dist/assets/{MessageAge-Cd1C0-Kr.js → MessageAge-CaPpa1nH.js} +1 -1
  103. package/client-dist/assets/{MessageDeliverySettings-B_9VqCMP.js → MessageDeliverySettings-BUSuGKlc.js} +2 -2
  104. package/client-dist/assets/MessageInput-a13ZPAHv.js +3 -0
  105. package/client-dist/assets/MessageInputToolbar-BIL_6i7G.css +1 -0
  106. package/client-dist/assets/MessageInputToolbar-CQGTnVea.js +58 -0
  107. package/client-dist/assets/MessageList-C7kAuWKg.js +4 -0
  108. package/client-dist/assets/MessageList-rD5OPsAJ.css +1 -0
  109. package/client-dist/assets/Modal-ClSjJagX.js +15 -0
  110. package/client-dist/assets/ModelSettings-Dnd4yzmI.js +1 -0
  111. package/client-dist/assets/NavigationLayout-BTFsWVtE.js +2 -0
  112. package/client-dist/assets/NewSessionPage-BfiAS-Mo.js +1 -0
  113. package/client-dist/assets/NotificationsSettings-B1ugQIp-.js +1 -0
  114. package/client-dist/assets/PageHeader-BjwH2pWD.js +1 -0
  115. package/client-dist/assets/PerformanceSettings-jJYF9SPY.js +1 -0
  116. package/client-dist/assets/{ProjectSessionDefaultsModal-Dq2_xDka.js → ProjectSessionDefaultsModal-G_0uxJEv.js} +1 -1
  117. package/client-dist/assets/ProjectTemplatesSettings-BQTCV3-3.js +1 -0
  118. package/client-dist/assets/ProjectsPage-suTd8s9l.js +1 -0
  119. package/client-dist/assets/ProviderBadge-P0VTI71n.js +1 -0
  120. package/client-dist/assets/{ProviderChildSessionDetail-tWrpaB_X.js → ProviderChildSessionDetail-D0472EW8.js} +35 -35
  121. package/client-dist/assets/ProviderChildSessionPage-9__sgY14.js +1 -0
  122. package/client-dist/assets/ProvidersSettings-Bwzy73Rk.js +1 -0
  123. package/client-dist/assets/{RecapAfterSecondsControl-qU0RMrUX.js → RecapAfterSecondsControl-CxuXyFSr.js} +1 -1
  124. package/client-dist/assets/{RelayProtocol-DjpPJk64.js → RelayProtocol-BpdH0COG.js} +1 -1
  125. package/client-dist/assets/RemoteAccessSettings-Dn7KB5nK.js +1 -0
  126. package/client-dist/assets/RemoteExecutorsSettings-Cjl4Y2rB.js +1 -0
  127. package/client-dist/assets/SchemaValidationContext-57RCj4c4.js +1 -0
  128. package/client-dist/assets/{SearchPreview-B25ksFLA.js → SearchPreview-OzVFWPJZ.js} +1 -1
  129. package/client-dist/assets/{SessionHeader.module-Co9s-JR3.js → SessionHeader.module-BpaFAQ-S.js} +1 -1
  130. package/client-dist/assets/SessionPage-BYthaEfZ.js +50 -0
  131. package/client-dist/assets/SessionPage-CXXEAwu2.css +1 -0
  132. package/client-dist/assets/{SettingsItem-B_rM9Vhi.js → SettingsItem-C9Vh5p7F.js} +1 -1
  133. package/client-dist/assets/{SettingsSection-DOwc_RwX.js → SettingsSection-BaPzETK6.js} +1 -1
  134. package/client-dist/assets/SourceControlSettings-DnqLg0db.js +1 -0
  135. package/client-dist/assets/{SourceFileHeaderActions-3_76js_o.js → SourceFileHeaderActions-PjhUGnn6.js} +1 -1
  136. package/client-dist/assets/SpeechControlMenu-BYVdEa3C.js +2 -0
  137. package/client-dist/assets/{SpeechSettings-BT4TnSgr.js → SpeechSettings-B6LkqfSK.js} +2 -2
  138. package/client-dist/assets/{SpeechSmartTurnControls-vIZ8a7Lb.js → SpeechSmartTurnControls-LPq9wBaM.js} +1 -1
  139. package/client-dist/assets/StorageSettings-DtsJnYaz.js +1 -0
  140. package/client-dist/assets/{ThinkingControls-CbZcYobp.js → ThinkingControls-DXbxdJRi.js} +1 -1
  141. package/client-dist/assets/ToolbarSettings-Nb2BKpnk.js +1 -0
  142. package/client-dist/assets/UsersSettings-BdvqmyqK.js +1 -0
  143. package/client-dist/assets/ViewerModePage-CfJJA5GL.css +1 -0
  144. package/client-dist/assets/ViewerModePage-DzRIpuYF.js +1 -0
  145. package/client-dist/assets/{VoiceInputButton-japn0Kx_.js → VoiceInputButton-CCgovfyf.js} +1 -1
  146. package/client-dist/assets/WorkstreamsPage-dlEUllSL.js +1 -0
  147. package/client-dist/assets/{YaServerProvider-OSxrnpr9.js → YaServerProvider-CN3tC5UL.js} +1 -1
  148. package/client-dist/assets/{YepAnywhereLogo-OH70DoR4.js → YepAnywhereLogo-5zFKWjQq.js} +1 -1
  149. package/client-dist/assets/{abnfDiagram-VCTEODGH-BK2byNq2.js → abnfDiagram-VCTEODGH-BWHUBcV3.js} +1 -1
  150. package/client-dist/assets/{arc-BZ7613Gf.js → arc-DKsIJWGD.js} +1 -1
  151. package/client-dist/assets/{architectureDiagram-5GKGNRK7-WEjy-r-z.js → architectureDiagram-5GKGNRK7-BuLImqW3.js} +1 -1
  152. package/client-dist/assets/{attachmentFileNames-BfFUuufi.js → attachmentFileNames-CBV_5g65.js} +1 -1
  153. package/client-dist/assets/{blockDiagram-I7D4REHJ-BOsYYXyW.js → blockDiagram-I7D4REHJ-CJ4Gh6sL.js} +1 -1
  154. package/client-dist/assets/{c4Diagram-7LVT6UL2-BRrAUZLE.js → c4Diagram-7LVT6UL2-WR43XvCI.js} +1 -1
  155. package/client-dist/assets/channel-PV8AAsuo.js +1 -0
  156. package/client-dist/assets/{chunk-2Q5K7J3B-ikUS9MZO.js → chunk-2Q5K7J3B-CiP4m_EA.js} +1 -1
  157. package/client-dist/assets/{chunk-5VM5RSS4-DqxRtuTQ.js → chunk-5VM5RSS4-BUAhj1h9.js} +1 -1
  158. package/client-dist/assets/{chunk-F27PBJKO-DQAhMVEw.js → chunk-F27PBJKO-BUZNwiGx.js} +1 -1
  159. package/client-dist/assets/{chunk-IMKFNOWR-B2QXI9W-.js → chunk-IMKFNOWR-CX1a0BCE.js} +1 -1
  160. package/client-dist/assets/{chunk-JWPE2WC7-Px4jgxzE.js → chunk-JWPE2WC7-C6tL-mLF.js} +1 -1
  161. package/client-dist/assets/{chunk-POPQ4Y6H-BTrXHY42.js → chunk-POPQ4Y6H-BzijGGWv.js} +1 -1
  162. package/client-dist/assets/{chunk-SVP7TREG-DufcbLSM.js → chunk-SVP7TREG-CsZImJKI.js} +1 -1
  163. package/client-dist/assets/{chunk-TICWLB2K-C6xArrXi.js → chunk-TICWLB2K-TwCtuDc1.js} +1 -1
  164. package/client-dist/assets/{chunk-XXDRQBXY-CtTuQMK6.js → chunk-XXDRQBXY-C-2EoNns.js} +1 -1
  165. package/client-dist/assets/classDiagram-ZZMXUADV-DvtSxfma.js +1 -0
  166. package/client-dist/assets/classDiagram-v2-VYDZK3BY-DvtSxfma.js +1 -0
  167. package/client-dist/assets/{client-sN_tbfxh.js → client-Ci_HPGfl.js} +2 -2
  168. package/client-dist/assets/{compactSettingsControls-BjKplkgf.js → compactSettingsControls-C9mLZh5H.js} +1 -1
  169. package/client-dist/assets/{cose-bilkent-JH36ORCC-Cn15YJGj.js → cose-bilkent-JH36ORCC-CmbEx2jT.js} +1 -1
  170. package/client-dist/assets/{cynefin-OW5HDTMX-CJkFJ0DX.js → cynefin-OW5HDTMX-BSQHHXFU.js} +1 -1
  171. package/client-dist/assets/{cynefinDiagram-5FMLGOSQ-CVX2L_eF.js → cynefinDiagram-5FMLGOSQ-C-62JZJD.js} +1 -1
  172. package/client-dist/assets/{dagre-GXQ25YYZ-BMbYVbaU.js → dagre-GXQ25YYZ-BBERQe_A.js} +1 -1
  173. package/client-dist/assets/de-Cgdxe5vX.js +6 -0
  174. package/client-dist/assets/{diagram-S7CK7UJ4-DTZ_P_Fh.js → diagram-S7CK7UJ4-muw11lmG.js} +1 -1
  175. package/client-dist/assets/{diagram-UQ7AKVKN-C6cgxro0.js → diagram-UQ7AKVKN-DpePWzAe.js} +1 -1
  176. package/client-dist/assets/{diagram-VSXAHHWV-MzNPAr2n.js → diagram-VSXAHHWV-DHX6AHUY.js} +1 -1
  177. package/client-dist/assets/{diagram-VX7I27RA-BZN6iloV.js → diagram-VX7I27RA-DYmR6NH_.js} +1 -1
  178. package/client-dist/assets/{diagram-Z3DM3KII-CtTiorxp.js → diagram-Z3DM3KII-BC1SenHB.js} +1 -1
  179. package/client-dist/assets/{ebnfDiagram-PWID7BFC-B28XYdqt.js → ebnfDiagram-PWID7BFC-EVpri6Ma.js} +1 -1
  180. package/client-dist/assets/{erDiagram-RLTQ6QDP-DlMmHWyy.js → erDiagram-RLTQ6QDP-DthztUaa.js} +1 -1
  181. package/client-dist/assets/es-gyRk85dY.js +6 -0
  182. package/client-dist/assets/{flowDiagram-HODETNUW-C5mVciwL.js → flowDiagram-HODETNUW-DEpC5nMx.js} +1 -1
  183. package/client-dist/assets/fr-Dx9lA8u-.js +6 -0
  184. package/client-dist/assets/{frontendReload-DT6MOpjg.js → frontendReload-CBdyvvdy.js} +1 -1
  185. package/client-dist/assets/{ganttDiagram-EL5Y4UJY-BTl7ZRTR.js → ganttDiagram-EL5Y4UJY-Csqji8t1.js} +1 -1
  186. package/client-dist/assets/{gitGraphDiagram-WWUBYQGX-BsG6KEKe.js → gitGraphDiagram-WWUBYQGX-DVX1SDIE.js} +1 -1
  187. package/client-dist/assets/{hostStorage-BoEdRarg.js → hostStorage-D1KAm3U1.js} +1 -1
  188. package/client-dist/assets/{index-D7q51uJV.js → index-BESqiBDI.js} +1 -1
  189. package/client-dist/assets/index-BkOdUxq4.js +2 -0
  190. package/client-dist/assets/index-CPb-36gi.css +1 -0
  191. package/client-dist/assets/index-CoR-vzsb.js +2 -0
  192. package/client-dist/assets/index-Cv3tQXyE.js +1 -0
  193. package/client-dist/assets/{index-CkZXrIi5.js → index-DSFMItgO.js} +1 -1
  194. package/client-dist/assets/index-umZg0LZ6.js +81 -0
  195. package/client-dist/assets/{infoDiagram-27XIBGKW-CkZcthz-.js → infoDiagram-27XIBGKW-CHm3qsd2.js} +1 -1
  196. package/client-dist/assets/{ishikawaDiagram-5VMMS53U-Cvqitz5U.js → ishikawaDiagram-5VMMS53U-tBRZwz-_.js} +1 -1
  197. package/client-dist/assets/ja-BOj7smkY.js +6 -0
  198. package/client-dist/assets/{journeyDiagram-3NMN7TZE-vCw00Cqy.js → journeyDiagram-3NMN7TZE-EJic7nqD.js} +1 -1
  199. package/client-dist/assets/{kanban-definition-UXKFOSKX-BZGCo-wX.js → kanban-definition-UXKFOSKX-DtzL6eeO.js} +1 -1
  200. package/client-dist/assets/{layout-D7JRfual.js → layout-gb-Axsoq.js} +1 -1
  201. package/client-dist/assets/{linear-O9cHRsA5.js → linear-CAe4xGbR.js} +1 -1
  202. package/client-dist/assets/long-context-effort-warning-C6XHizE1.js +1 -0
  203. package/client-dist/assets/{mermaid.core-CdC8AeOx.js → mermaid.core-BCu1nv8H.js} +5 -5
  204. package/client-dist/assets/{mindmap-definition-YA3MSWOX-CczC57z0.js → mindmap-definition-YA3MSWOX-C7-KSPtJ.js} +1 -1
  205. package/client-dist/assets/newSessionPrefill-DKcy0abh.js +1 -0
  206. package/client-dist/assets/{pegDiagram-XKGWAZYB-jTm4iBWK.js → pegDiagram-XKGWAZYB-iWVH9rbY.js} +1 -1
  207. package/client-dist/assets/{pieDiagram-E7YTZNPT-DfkDPuJg.js → pieDiagram-E7YTZNPT-VKD6PLHa.js} +1 -1
  208. package/client-dist/assets/providerChildSessions-Cd7oK6KQ.css +1 -0
  209. package/client-dist/assets/providerChildSessions-DbLFSybt.js +77 -0
  210. package/client-dist/assets/{quadrantDiagram-AXDQQJYC--bBZSIt1.js → quadrantDiagram-AXDQQJYC-AXFugcFl.js} +1 -1
  211. package/client-dist/assets/{railroadDiagram-O6MQD6OU-gbkMdGN6.js → railroadDiagram-O6MQD6OU-D6oZy6Al.js} +1 -1
  212. package/client-dist/assets/{recentProjectPathLinks-Ba20jx5b.js → recentProjectPathLinks-D0Dx6YXT.js} +2 -2
  213. package/client-dist/assets/{registerServiceWorker-CGxgV4Yi.js → registerServiceWorker-B8K2KVOY.js} +1 -1
  214. package/client-dist/assets/{relayEndpoints-0oIbn4eU.js → relayEndpoints-BTq9xppf.js} +1 -1
  215. package/client-dist/assets/{remoteRoutePaths-CiDZeM2I.js → remoteRoutePaths-D8htA0xa.js} +1 -1
  216. package/client-dist/assets/{requirementDiagram-BXWQKSXE-WfLCTewk.js → requirementDiagram-BXWQKSXE-Eqtb74It.js} +1 -1
  217. package/client-dist/assets/{sankeyDiagram-P5KCCOFB-BhJkx_M1.js → sankeyDiagram-P5KCCOFB-CxvDiZ1R.js} +1 -1
  218. package/client-dist/assets/{sequenceDiagram-WJ2MYXX4-_S-ZN-hK.js → sequenceDiagram-WJ2MYXX4-BbpkgW2L.js} +1 -1
  219. package/client-dist/assets/sessionHistorySearch.worker-DCkPlfGO.js +61 -0
  220. package/client-dist/assets/{sessionNavigationState-DKXD1sTS.js → sessionNavigationState-BXejf2ZW.js} +1 -1
  221. package/client-dist/assets/sessionRouteLayer-D9T2QT8G.js +1 -0
  222. package/client-dist/assets/{sizeCapture-INFHLROL-YfaR_7-Y.js → sizeCapture-INFHLROL-DcuwWD5r.js} +1 -1
  223. package/client-dist/assets/{sourceControlNavigationState-lyZ29oaF.js → sourceControlNavigationState-BJbTzWTE.js} +1 -1
  224. package/client-dist/assets/{speechDraftTransaction-zyWVCYTF.js → speechDraftTransaction-WhqFE1h9.js} +1 -1
  225. package/client-dist/assets/{stateDiagram-D77RDMKH-_N9FdD6m.js → stateDiagram-D77RDMKH-Cidpq73w.js} +1 -1
  226. package/client-dist/assets/stateDiagram-v2-MP3YSRHH-DFqKXxjz.js +1 -0
  227. package/client-dist/assets/{swimlanes-42K2YHIH-DUl5jFZz.js → swimlanes-42K2YHIH-Ba8C7MwG.js} +1 -1
  228. package/client-dist/assets/swimlanesDiagram-VR7AAH4N-3pW2TcAt.js +8 -0
  229. package/client-dist/assets/{timeline-definition-24CTP7MA-DtYzRl63.js → timeline-definition-24CTP7MA-CKefGvUK.js} +1 -1
  230. package/client-dist/assets/useAcliCommentarySetting-CBKAl7qr.js +9 -0
  231. package/client-dist/assets/useActivityBusState-C0dor9p7.js +1 -0
  232. package/client-dist/assets/{useBackgroundRevalidation-CULom4_W.js → useBackgroundRevalidation-C79HAUP3.js} +1 -1
  233. package/client-dist/assets/{useCodexUpdateStatus-BIDehnvt.js → useCodexUpdateStatus-CEZO_f2Y.js} +1 -1
  234. package/client-dist/assets/{useConnectedDevices-kBo43kbz.js → useConnectedDevices-Ds-DuUDc.js} +1 -1
  235. package/client-dist/assets/{useDocumentTitle-C06qawRj.js → useDocumentTitle-Xz5t-nlB.js} +1 -1
  236. package/client-dist/assets/{useEmulators-Bz8194e3.js → useEmulators-qS_cCZ3I.js} +1 -1
  237. package/client-dist/assets/{useFileActivity-CwkGwsQt.js → useFileActivity-BoW4X3DY.js} +1 -1
  238. package/client-dist/assets/{useFloatingActionButtonEnabled-C31rfHtR.js → useFloatingActionButtonEnabled-2_hw7nSa.js} +1 -1
  239. package/client-dist/assets/{useForkSummaryAutoOpen-D_SvtmbE.js → useForkSummaryAutoOpen-CS33Irpf.js} +1 -1
  240. package/client-dist/assets/{useGeneratedTitleLength-Cu-SoQ6T.js → useGeneratedTitleLength-D856ktVg.js} +1 -1
  241. package/client-dist/assets/{useKeepMobileKeyboardOpenAfterDelivery-C-cYLaEU.js → useKeepMobileKeyboardOpenAfterDelivery-Ba77SbWF.js} +1 -1
  242. package/client-dist/assets/useModelSettings-BdlYk1DT.js +1 -0
  243. package/client-dist/assets/{useNotifyInApp-BcLZ8ie_.js → useNotifyInApp-DcWe3dh4.js} +1 -1
  244. package/client-dist/assets/{useOnboarding-CYgE-Xsg.js → useOnboarding-CoE3WF8a.js} +1 -1
  245. package/client-dist/assets/{useProviders-C6kBPWYX.js → useProviders-CeN1PclA.js} +1 -1
  246. package/client-dist/assets/{useQuestionAsideSetting-6Excl6Pm.js → useQuestionAsideSetting-CPFw1u0y.js} +1 -1
  247. package/client-dist/assets/{useRecentSessions-CsmsGemq.js → useRecentSessions-ieTzzJu4.js} +2 -2
  248. package/client-dist/assets/{useRelativeNow-BdLaPgKO.js → useRelativeNow-Ca6QGcPa.js} +1 -1
  249. package/client-dist/assets/{useReloadNotifications-B0egr2ys.js → useReloadNotifications-Dm1jmdIb.js} +1 -1
  250. package/client-dist/assets/{useRemoteExecutors-Bgjgzif1.js → useRemoteExecutors-zBAQnQXH.js} +1 -1
  251. package/client-dist/assets/{useSidebarWidth-ut6NNk5Y.js → useSidebarWidth-CBCcbSLg.js} +1 -1
  252. package/client-dist/assets/{useSourceControlCleanLanding-DxrwogwF.js → useSourceControlCleanLanding-VDlft5tr.js} +1 -1
  253. package/client-dist/assets/{useStableToolPreviewRendering-CcrkchTG.js → useStableToolPreviewRendering-hbVp38Jd.js} +1 -1
  254. package/client-dist/assets/{useStreamingEnabled-EdvW04Vz.js → useStreamingEnabled-hU1g8i7_.js} +1 -1
  255. package/client-dist/assets/{useTabTitleActivityPreference-B0suFUHK.js → useTabTitleActivityPreference-DhREY7m2.js} +1 -1
  256. package/client-dist/assets/{useVhostAccess-2ZKr0Lcl.js → useVhostAccess-DUtn_sH1.js} +1 -1
  257. package/client-dist/assets/{useWorkflowTags-_4F_41YI.js → useWorkflowTags-DxbEBqtf.js} +1 -1
  258. package/client-dist/assets/{vennDiagram-4TSXK5OY-26XZDUe6.js → vennDiagram-4TSXK5OY-CSGBq-Ur.js} +1 -1
  259. package/client-dist/assets/{wardleyDiagram-VM6X3IG4-YvZ37BJ7.js → wardleyDiagram-VM6X3IG4-DIMvcaMb.js} +1 -1
  260. package/client-dist/assets/{xychartDiagram-S5SC5T6Z-BMT0MEGz.js → xychartDiagram-S5SC5T6Z-TYXSqT3w.js} +1 -1
  261. package/client-dist/assets/zh-CN-DadySLj9.js +7 -0
  262. package/client-dist/index.html +3 -3
  263. package/dist/app.d.ts.map +1 -1
  264. package/dist/app.js +29 -10
  265. package/dist/app.js.map +1 -1
  266. package/dist/artifacts/ArtifactServer.d.ts +2 -0
  267. package/dist/artifacts/ArtifactServer.d.ts.map +1 -1
  268. package/dist/artifacts/ArtifactServer.js +79 -1
  269. package/dist/artifacts/ArtifactServer.js.map +1 -1
  270. package/dist/auth/limitedUserPolicy.d.ts +9 -5
  271. package/dist/auth/limitedUserPolicy.d.ts.map +1 -1
  272. package/dist/auth/limitedUserPolicy.js +64 -35
  273. package/dist/auth/limitedUserPolicy.js.map +1 -1
  274. package/dist/auth/principal.d.ts +6 -0
  275. package/dist/auth/principal.d.ts.map +1 -1
  276. package/dist/auth/principal.js +6 -0
  277. package/dist/auth/principal.js.map +1 -1
  278. package/dist/frontend/static.d.ts.map +1 -1
  279. package/dist/frontend/static.js +2 -1
  280. package/dist/frontend/static.js.map +1 -1
  281. package/dist/middleware/authenticated-transport.d.ts +13 -0
  282. package/dist/middleware/authenticated-transport.d.ts.map +1 -1
  283. package/dist/middleware/authenticated-transport.js +12 -0
  284. package/dist/middleware/authenticated-transport.js.map +1 -1
  285. package/dist/middleware/limited-users.d.ts +9 -5
  286. package/dist/middleware/limited-users.d.ts.map +1 -1
  287. package/dist/middleware/limited-users.js +37 -23
  288. package/dist/middleware/limited-users.js.map +1 -1
  289. package/dist/routes/file-edit.d.ts +18 -0
  290. package/dist/routes/file-edit.d.ts.map +1 -0
  291. package/dist/routes/file-edit.js +244 -0
  292. package/dist/routes/file-edit.js.map +1 -0
  293. package/dist/routes/files.d.ts.map +1 -1
  294. package/dist/routes/files.js +34 -9
  295. package/dist/routes/files.js.map +1 -1
  296. package/dist/routes/pdfjs.d.ts +9 -0
  297. package/dist/routes/pdfjs.d.ts.map +1 -0
  298. package/dist/routes/pdfjs.js +34 -0
  299. package/dist/routes/pdfjs.js.map +1 -0
  300. package/dist/routes/public-file-shares.d.ts +6 -0
  301. package/dist/routes/public-file-shares.d.ts.map +1 -1
  302. package/dist/routes/public-file-shares.js +22 -10
  303. package/dist/routes/public-file-shares.js.map +1 -1
  304. package/dist/routes/public-shares.d.ts.map +1 -1
  305. package/dist/routes/public-shares.js +18 -1
  306. package/dist/routes/public-shares.js.map +1 -1
  307. package/dist/routes/recents.d.ts +4 -1
  308. package/dist/routes/recents.d.ts.map +1 -1
  309. package/dist/routes/recents.js +7 -0
  310. package/dist/routes/recents.js.map +1 -1
  311. package/dist/routes/sessions.d.ts.map +1 -1
  312. package/dist/routes/sessions.js +4 -0
  313. package/dist/routes/sessions.js.map +1 -1
  314. package/dist/routes/settings.d.ts +7 -2
  315. package/dist/routes/settings.d.ts.map +1 -1
  316. package/dist/routes/settings.js +43 -1
  317. package/dist/routes/settings.js.map +1 -1
  318. package/dist/routes/version.d.ts.map +1 -1
  319. package/dist/routes/version.js +1 -0
  320. package/dist/routes/version.js.map +1 -1
  321. package/dist/routes/ws-relay-handlers.d.ts +12 -0
  322. package/dist/routes/ws-relay-handlers.d.ts.map +1 -1
  323. package/dist/routes/ws-relay-handlers.js +25 -4
  324. package/dist/routes/ws-relay-handlers.js.map +1 -1
  325. package/dist/routes/ws-relay.d.ts.map +1 -1
  326. package/dist/routes/ws-relay.js +8 -0
  327. package/dist/routes/ws-relay.js.map +1 -1
  328. package/dist/sdk/providers/agent-self.js +1 -1
  329. package/dist/sdk/providers/agent-self.js.map +1 -1
  330. package/dist/sdk/providers/claude.d.ts +1 -0
  331. package/dist/sdk/providers/claude.d.ts.map +1 -1
  332. package/dist/sdk/providers/claude.js +7 -0
  333. package/dist/sdk/providers/claude.js.map +1 -1
  334. package/dist/sdk/providers/codex-model-catalog.d.ts.map +1 -1
  335. package/dist/sdk/providers/codex-model-catalog.js +5 -3
  336. package/dist/sdk/providers/codex-model-catalog.js.map +1 -1
  337. package/dist/sdk/providers/codex-protocol/generated/ContentItem.d.ts +4 -1
  338. package/dist/sdk/providers/codex-protocol/generated/ContentItem.d.ts.map +1 -1
  339. package/dist/sdk/providers/codex-protocol/generated/FunctionCallOutputContentItem.d.ts +4 -1
  340. package/dist/sdk/providers/codex-protocol/generated/FunctionCallOutputContentItem.d.ts.map +1 -1
  341. package/dist/sdk/providers/codex-protocol/generated/Personality.d.ts +3 -0
  342. package/dist/sdk/providers/codex-protocol/generated/Personality.d.ts.map +1 -1
  343. package/dist/sdk/providers/codex-protocol/generated/v2/McpAppDisplayMode.d.ts +2 -0
  344. package/dist/sdk/providers/codex-protocol/generated/v2/McpAppDisplayMode.d.ts.map +1 -0
  345. package/dist/sdk/providers/codex-protocol/generated/v2/{ThreadRollbackParams.js → McpAppDisplayMode.js} +1 -1
  346. package/dist/sdk/providers/codex-protocol/generated/v2/McpAppDisplayMode.js.map +1 -0
  347. package/dist/sdk/providers/codex-protocol/generated/v2/McpAppUi.d.ts +9 -0
  348. package/dist/sdk/providers/codex-protocol/generated/v2/McpAppUi.d.ts.map +1 -0
  349. package/dist/sdk/providers/codex-protocol/generated/v2/{ThreadRollbackResponse.js → McpAppUi.js} +1 -1
  350. package/dist/sdk/providers/codex-protocol/generated/v2/McpAppUi.js.map +1 -0
  351. package/dist/sdk/providers/codex-protocol/generated/v2/Thread.d.ts +1 -1
  352. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadForkResponse.d.ts +4 -0
  353. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadForkResponse.d.ts.map +1 -1
  354. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadItem.d.ts +6 -1
  355. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadItem.d.ts.map +1 -1
  356. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadResumeParams.d.ts +4 -0
  357. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadResumeParams.d.ts.map +1 -1
  358. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadResumeResponse.d.ts +9 -0
  359. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadResumeResponse.d.ts.map +1 -1
  360. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadStartParams.d.ts +9 -0
  361. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadStartParams.d.ts.map +1 -1
  362. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadStartResponse.d.ts +4 -0
  363. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadStartResponse.d.ts.map +1 -1
  364. package/dist/sdk/providers/codex-protocol/generated/v2/TurnStartParams.d.ts +7 -1
  365. package/dist/sdk/providers/codex-protocol/generated/v2/TurnStartParams.d.ts.map +1 -1
  366. package/dist/sdk/providers/codex-protocol/generated/v2/UserInput.d.ts +3 -0
  367. package/dist/sdk/providers/codex-protocol/generated/v2/UserInput.d.ts.map +1 -1
  368. package/dist/sdk/providers/codex-protocol/index.d.ts +0 -2
  369. package/dist/sdk/providers/codex-protocol/index.d.ts.map +1 -1
  370. package/dist/sdk/providers/codex.d.ts +23 -2
  371. package/dist/sdk/providers/codex.d.ts.map +1 -1
  372. package/dist/sdk/providers/codex.js +55 -22
  373. package/dist/sdk/providers/codex.js.map +1 -1
  374. package/dist/sdk/providers/index.d.ts.map +1 -1
  375. package/dist/sdk/providers/index.js +4 -1
  376. package/dist/sdk/providers/index.js.map +1 -1
  377. package/dist/sdk/providers/opencode.d.ts +9 -0
  378. package/dist/sdk/providers/opencode.d.ts.map +1 -1
  379. package/dist/sdk/providers/opencode.js +129 -76
  380. package/dist/sdk/providers/opencode.js.map +1 -1
  381. package/dist/sdk/providers/provider-session-owner.d.ts +9 -0
  382. package/dist/sdk/providers/provider-session-owner.d.ts.map +1 -1
  383. package/dist/sdk/providers/provider-session-owner.js +39 -3
  384. package/dist/sdk/providers/provider-session-owner.js.map +1 -1
  385. package/dist/sdk/providers/types.d.ts +13 -0
  386. package/dist/sdk/providers/types.d.ts.map +1 -1
  387. package/dist/sdk/providers/types.js.map +1 -1
  388. package/dist/services/ArtifactRebuildService.d.ts +67 -0
  389. package/dist/services/ArtifactRebuildService.d.ts.map +1 -0
  390. package/dist/services/ArtifactRebuildService.js +229 -0
  391. package/dist/services/ArtifactRebuildService.js.map +1 -0
  392. package/dist/services/DirtyFileEditorService.d.ts +2 -0
  393. package/dist/services/DirtyFileEditorService.d.ts.map +1 -1
  394. package/dist/services/DirtyFileEditorService.js +20 -1
  395. package/dist/services/DirtyFileEditorService.js.map +1 -1
  396. package/dist/services/PdfjsAssetCache.d.ts +20 -0
  397. package/dist/services/PdfjsAssetCache.d.ts.map +1 -0
  398. package/dist/services/PdfjsAssetCache.js +131 -0
  399. package/dist/services/PdfjsAssetCache.js.map +1 -0
  400. package/dist/services/SessionCatalogService.d.ts +27 -0
  401. package/dist/services/SessionCatalogService.d.ts.map +1 -1
  402. package/dist/services/SessionCatalogService.js +129 -34
  403. package/dist/services/SessionCatalogService.js.map +1 -1
  404. package/dist/sessions/opencode-reader.d.ts +2 -1
  405. package/dist/sessions/opencode-reader.d.ts.map +1 -1
  406. package/dist/sessions/opencode-reader.js +30 -1
  407. package/dist/sessions/opencode-reader.js.map +1 -1
  408. package/dist/sessions/types.d.ts +6 -0
  409. package/dist/sessions/types.d.ts.map +1 -1
  410. package/dist/supervisor/Process.d.ts +7 -0
  411. package/dist/supervisor/Process.d.ts.map +1 -1
  412. package/dist/supervisor/Process.js +48 -3
  413. package/dist/supervisor/Process.js.map +1 -1
  414. package/dist/supervisor/Supervisor.d.ts.map +1 -1
  415. package/dist/supervisor/Supervisor.js +11 -0
  416. package/dist/supervisor/Supervisor.js.map +1 -1
  417. package/dist/supervisor/types.d.ts +3 -1
  418. package/dist/supervisor/types.d.ts.map +1 -1
  419. package/dist/supervisor/types.js.map +1 -1
  420. package/package.json +3 -3
  421. package/client-dist/assets/AboutSettings-BlEONE7w.js +0 -1
  422. package/client-dist/assets/AgentsPage-CBku9RWz.js +0 -2
  423. package/client-dist/assets/App-DWHvFKob.js +0 -2
  424. package/client-dist/assets/AppearanceSettings-BSEBjSjr.js +0 -2
  425. package/client-dist/assets/AppsSettings-iDL6Xuaa.js +0 -1
  426. package/client-dist/assets/AttachmentChip-DHKr4EfG.js +0 -1
  427. package/client-dist/assets/BangCommandsPage-yX8grXp9.js +0 -1
  428. package/client-dist/assets/BrowserDebugToolbarButton-B-b7N4cr.js +0 -1
  429. package/client-dist/assets/ComputerControlSettings-DzRDwfJ1.js +0 -1
  430. package/client-dist/assets/DevelopmentSettings-Bf9gyeU0.js +0 -1
  431. package/client-dist/assets/DevicesSettings-dbZHFEEc.js +0 -1
  432. package/client-dist/assets/EmulatorPage-CKJwVTFq.js +0 -1
  433. package/client-dist/assets/EmulatorSettings-BV9Bg3Xk.js +0 -1
  434. package/client-dist/assets/EnvironmentSettings-DmOTuSwm.js +0 -1
  435. package/client-dist/assets/FilePage-DnPW5Pbc.js +0 -1
  436. package/client-dist/assets/FilterDropdown-CB_tRt6g.css +0 -1
  437. package/client-dist/assets/FilterDropdown-DpS1eMEf.js +0 -1
  438. package/client-dist/assets/FloatingActionButton-DBIoFwff.js +0 -1
  439. package/client-dist/assets/GlobalSessionsPage-Dbnuis89.css +0 -1
  440. package/client-dist/assets/GlobalSessionsPage-DcmQcX7q.js +0 -2
  441. package/client-dist/assets/HostIdentityContext-D5aBdejC.js +0 -1
  442. package/client-dist/assets/HostsPage-C1ZTrhJv.js +0 -1
  443. package/client-dist/assets/InboxPage-Cepu8VGM.js +0 -1
  444. package/client-dist/assets/IssueSettings-xRU8E-xR.js +0 -1
  445. package/client-dist/assets/IssuesPage-c6PUStFT.js +0 -1
  446. package/client-dist/assets/LifecycleWebhooksSettings-CZcZATjJ.js +0 -1
  447. package/client-dist/assets/MessageInput-B0t6b_Hd.js +0 -3
  448. package/client-dist/assets/MessageInputToolbar-DdP4tB2S.css +0 -1
  449. package/client-dist/assets/MessageInputToolbar-rhYW1xGJ.js +0 -58
  450. package/client-dist/assets/MessageList-Dcvfxbeq.css +0 -1
  451. package/client-dist/assets/MessageList-dH63bflu.js +0 -4
  452. package/client-dist/assets/Modal-QUinFhBP.js +0 -16
  453. package/client-dist/assets/ModelSettings-CcWkVSEK.js +0 -1
  454. package/client-dist/assets/NavigationLayout-BkOsag-J.js +0 -2
  455. package/client-dist/assets/NewSessionPage-DcZ9YjmC.js +0 -1
  456. package/client-dist/assets/NotificationsSettings-DoVzfeME.js +0 -1
  457. package/client-dist/assets/PageHeader-BaYMLVHI.js +0 -1
  458. package/client-dist/assets/PerformanceSettings-dwoVtUlX.js +0 -1
  459. package/client-dist/assets/ProjectTemplatesSettings-BlMWq1wb.js +0 -1
  460. package/client-dist/assets/ProjectsPage-B5VBairc.js +0 -1
  461. package/client-dist/assets/ProviderChildSessionPage-B3eTTTjF.js +0 -1
  462. package/client-dist/assets/ProvidersSettings-OUKp5-Hb.js +0 -1
  463. package/client-dist/assets/RemoteAccessSettings-Bn0ng7s4.js +0 -1
  464. package/client-dist/assets/RemoteExecutorsSettings-2Qh-9Qv_.js +0 -1
  465. package/client-dist/assets/SchemaValidationContext-CIAd7icg.js +0 -1
  466. package/client-dist/assets/SessionPage-B1g1UFEV.js +0 -49
  467. package/client-dist/assets/SessionPage-BiV0X3n1.css +0 -1
  468. package/client-dist/assets/SourceControlSettings-BQfC1KbV.js +0 -1
  469. package/client-dist/assets/SpeechControlMenu-BIv0O1la.js +0 -2
  470. package/client-dist/assets/StorageSettings-DQcG9Mbq.js +0 -1
  471. package/client-dist/assets/ToolbarSettings-CmHVAejU.js +0 -1
  472. package/client-dist/assets/UsersSettings-COgiiV9D.js +0 -1
  473. package/client-dist/assets/WorkstreamsPage-DKLRDEAp.js +0 -1
  474. package/client-dist/assets/channel-C-7AVqtf.js +0 -1
  475. package/client-dist/assets/classDiagram-ZZMXUADV-DkRr8VcO.js +0 -1
  476. package/client-dist/assets/classDiagram-v2-VYDZK3BY-DkRr8VcO.js +0 -1
  477. package/client-dist/assets/de-DKHK9Tu3.js +0 -6
  478. package/client-dist/assets/es-XSkBrKBg.js +0 -6
  479. package/client-dist/assets/fr-DKUJaPhN.js +0 -6
  480. package/client-dist/assets/index-BBpZzMBa.js +0 -2
  481. package/client-dist/assets/index-BUrcmRdN.js +0 -76
  482. package/client-dist/assets/index-CA-BRFYh.js +0 -1
  483. package/client-dist/assets/index-wA2zlxt-.css +0 -1
  484. package/client-dist/assets/ja-BDnQUlyD.js +0 -6
  485. package/client-dist/assets/long-context-effort-warning-BGls6uvf.js +0 -1
  486. package/client-dist/assets/newSessionPrefill-DkkSfnYR.js +0 -1
  487. package/client-dist/assets/providerChildSessions-ClrSXOQr.js +0 -80
  488. package/client-dist/assets/providerChildSessions-D2O1SLei.css +0 -1
  489. package/client-dist/assets/sessionHistorySearch.worker-BGlVvPYq.js +0 -60
  490. package/client-dist/assets/stateDiagram-v2-MP3YSRHH-CBvcZngO.js +0 -1
  491. package/client-dist/assets/swimlanesDiagram-VR7AAH4N-DKVyQBDp.js +0 -8
  492. package/client-dist/assets/useAcliCommentarySetting-DxndlmkH.js +0 -9
  493. package/client-dist/assets/useActivityBusState-CINl9yjP.js +0 -1
  494. package/client-dist/assets/useModelSettings-DoDJRymT.js +0 -1
  495. package/client-dist/assets/zh-CN-FVXKSeP_.js +0 -7
  496. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadRollbackParams.d.ts +0 -14
  497. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadRollbackParams.d.ts.map +0 -1
  498. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadRollbackParams.js.map +0 -1
  499. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadRollbackResponse.d.ts +0 -12
  500. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadRollbackResponse.d.ts.map +0 -1
  501. package/dist/sdk/providers/codex-protocol/generated/v2/ThreadRollbackResponse.js.map +0 -1
  502. /package/client-dist/assets/{Modal-EC-u4IZ7.css → index-EC-u4IZ7.css} +0 -0
@@ -1,4 +1,4 @@
1
- var Xn=Object.defineProperty;var Zn=(t,e,n)=>e in t?Xn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var l=(t,e,n)=>Zn(t,typeof e!="symbol"?e+"":e,n);import{b$ as ze,bc as es,be as ts,c0 as ns,bf as ss,bj as rs,c1 as is,c2 as os,c3 as Ye,c4 as as,c5 as cs,c6 as Ut,c7 as Ce,j as us,r as T,f as sn,c8 as ds}from"./index-BUrcmRdN.js";import{T as ls,R as hs,g as fs,i as ms,h as ps,j as gs,f as Ss,B as Ke,k as ys}from"./RelayProtocol-DjpPJk64.js";const pt=64*1024,bs=512*1024,vs=256*1024,Is=16,Cs=2*1024*1024,$t=1;class D extends Error{constructor(e,n){super(e),this.code=n,this.name="UploadError"}}function ws(t){if(t.type==="complete"&&"file"in t)return t.file;throw new D("Upload completed without file metadata","UPLOAD_ERROR")}function Ts(t){if(t.type==="complete"&&"stagedRef"in t)return t.stagedRef;throw new D("Upload completed without staged attachment metadata","UPLOAD_ERROR")}function rn(t){return new Promise(e=>setTimeout(e,t))}async function As(t){if(!((t.bufferedAmount??0)<=bs)){for(;t.readyState===$t&&(t.bufferedAmount??0)>vs;)await rn(Is);if(t.readyState!==$t)throw new D("WebSocket not connected","WS_CLOSED")}}function Ms(t){const e=t===void 0?Cs:t;if(e<=0)return{waitAfterSend:async()=>{}};const n=Date.now();let s=0;return{async waitAfterSend(r){s+=r;const i=s/e*1e3,o=Date.now()-n,a=i-o;a>1&&await rn(a)}}}async function on(t,e,n,s={},r=a=>new WebSocket(a),i=()=>()=>{},o){const{onProgress:a,signal:c}=s,d=Ms(s.maxBytesPerSecond);console.log("[Upload] Starting upload to:",t);const h=i("upload");return new Promise((f,m)=>{if(c!=null&&c.aborted){m(new D("Upload aborted","ABORTED"));return}console.log("[Upload] Creating WebSocket connection...");const p=r(t);let S=!1,g=!1;function y(){c==null||c.removeEventListener("abort",b)}const b=()=>{if(g)return;g=!0,S=!0,y();const w={type:"cancel"};try{p.send(JSON.stringify(w))}catch{}p.close(1e3,"Aborted by user"),m(new D("Upload aborted","ABORTED"))};c==null||c.addEventListener("abort",b);const v=w=>{try{const O=JSON.parse(w.data);switch(O.type){case"progress":{a==null||a(O.bytesReceived);break}case"complete":{g=!0,y(),p.close(1e3,"Upload complete");try{f(o(O))}catch(Kn){m(Kn)}break}case"error":{g=!0,y(),p.close(1e3,"Error received"),m(new D(O.message,O.code));break}}}catch{}},M=w=>{console.error("[Upload] WebSocket error:",w),!g&&(g=!0,y(),m(new D("WebSocket error","WS_ERROR")))},_=w=>{console.log("[Upload] WebSocket closed:",w.code,w.reason),!g&&(y(),S||(g=!0,m(new D(w.reason||"Connection closed unexpectedly","WS_CLOSED"))))},G=async()=>{console.log("[Upload] WebSocket connection opened");try{const w={type:"start",...e.batchId!==void 0?{batchId:e.batchId}:{},name:e.name,size:e.size,mimeType:e.mimeType,...e.width!==void 0?{width:e.width}:{},...e.height!==void 0?{height:e.height}:{}};p.send(JSON.stringify(w));for await(const O of n){if(S)break;p.send(O),await As(p),await d.waitAfterSend(O.length)}if(!S){const O={type:"end"};p.send(JSON.stringify(O))}}catch(w){if(g)return;g=!0,y(),p.close(1e3,"Error during upload"),m(w instanceof D?w:new D(w instanceof Error?w.message:"Upload failed","UPLOAD_ERROR"))}};p.addEventListener("open",G),p.addEventListener("message",v),p.addEventListener("error",M),p.addEventListener("close",_)}).finally(h)}async function Ps(t,e,n,s={},r=o=>new WebSocket(o),i){return on(t,e,n,s,r,i,ws)}async function js(t,e,n,s={},r=o=>new WebSocket(o),i){return on(t,e,n,s,r,i,Ts)}async function*an(t,e=pt){let n=0;for(;n<t.size;){const r=await t.slice(n,n+e).arrayBuffer();yield new Uint8Array(r),n+=e}}function Rs(t,e,n){const s=window.location.protocol==="https:"?"wss:":"ws:",r=window.location.host;return`${s}//${r}/api/projects/${t}/sessions/${e}/upload/ws`}function xs(t){const e=window.location.protocol==="https:"?"wss:":"ws:",n=window.location.host;return`${e}//${n}/api/attachments/staging/drafts/upload/ws`}async function Es(t,e,n,s={},r={}){var h,f;const{chunkSize:i=pt,...o}=s,a=Rs(t,e),c={name:n.name,size:n.size,mimeType:n.type||"application/octet-stream",...((h=s.imageDimensions)==null?void 0:h.width)!==void 0?{width:s.imageDimensions.width}:{},...((f=s.imageDimensions)==null?void 0:f.height)!==void 0?{height:s.imageDimensions.height}:{}},d=an(n,i);return Ps(a,c,d,o,r.createWebSocket,r.beginCriticalOperation)}async function _s(t,e={},n={}){var d,h;const{chunkSize:s=pt,batchId:r,...i}=e,o=xs(),a={...r!==void 0?{batchId:r}:{},name:t.name,size:t.size,mimeType:t.type||"application/octet-stream",...((d=e.imageDimensions)==null?void 0:d.width)!==void 0?{width:e.imageDimensions.width}:{},...((h=e.imageDimensions)==null?void 0:h.height)!==void 0?{height:e.imageDimensions.height}:{}},c=an(t,s);return js(o,a,c,i,n.createWebSocket,n.beginCriticalOperation)}const q={baseDelayMs:1e3,maxDelayMs:3e4,maxAttempts:10,jitterFactor:.3,staleThresholdMs:45e3,staleCheckIntervalMs:1e4,pongTimeoutMs:2e3},Os={setTimeout:(t,e)=>window.setTimeout(t,e),clearTimeout:t=>window.clearTimeout(t),setInterval:(t,e)=>window.setInterval(t,e),clearInterval:t=>window.clearInterval(t),now:()=>Date.now()},ks={isVisible:()=>typeof document<"u"&&!document.hidden,onVisibilityChange(t){if(typeof document>"u")return()=>{};const e=()=>t(!document.hidden);return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}};class cn{constructor(e={}){l(this,"_state","disconnected");l(this,"_reconnectAttempts",0);l(this,"_reconnectFn",null);l(this,"_sendPing",null);l(this,"_label",null);l(this,"_driveReconnect",!0);l(this,"_started",!1);l(this,"_lastEventTime",0);l(this,"_hasReceivedHeartbeat",!1);l(this,"_staleCheckIntervalId",null);l(this,"_hiddenSince",null);l(this,"_removeVisibilityListener",null);l(this,"_pendingPingId",null);l(this,"_pongTimeoutId",null);l(this,"_pingCounter",0);l(this,"_backoffTimerId",null);l(this,"_reconnectPromise",null);l(this,"_criticalOperationDepth",0);l(this,"_listeners",{stateChange:new Set,reconnectFailed:new Set,visibilityRestored:new Set});l(this,"config");l(this,"timers");l(this,"visibility");this.config={baseDelayMs:e.baseDelayMs??q.baseDelayMs,maxDelayMs:e.maxDelayMs??q.maxDelayMs,maxAttempts:e.maxAttempts??q.maxAttempts,jitterFactor:e.jitterFactor??q.jitterFactor,staleThresholdMs:e.staleThresholdMs??q.staleThresholdMs,staleCheckIntervalMs:e.staleCheckIntervalMs??q.staleCheckIntervalMs,pongTimeoutMs:e.pongTimeoutMs??q.pongTimeoutMs},this.timers=e.timers??Os,this.visibility=e.visibility??ks}get state(){return this._state}get reconnectAttempts(){return this._reconnectAttempts}start(e,n){this._reconnectFn=e,this._sendPing=(n==null?void 0:n.sendPing)??null,this._label=(n==null?void 0:n.label)??null,this._driveReconnect=(n==null?void 0:n.driveReconnect)??!0,!this._started&&(this._started=!0,this._setState("connected"),this._startStaleCheck(),this._startVisibilityListener())}stop(){this._started=!1,this._reconnectFn=null,this._sendPing=null,this._label=null,this._driveReconnect=!0,this._stopStaleCheck(),this._stopVisibilityListener(),this._cancelBackoff(),this._cancelPongTimeout(),this._reconnectPromise=null,this._hasReceivedHeartbeat=!1,this._hiddenSince=null,this._setState("disconnected")}recordEvent(){this._lastEventTime=this.timers.now()}recordHeartbeat(){this._hasReceivedHeartbeat=!0,this._lastEventTime=this.timers.now()}beginCriticalOperation(e){this._criticalOperationDepth+=1,this._pendingPingId=null,this._cancelPongTimeout(),this._log(`critical operation started${e?`: ${e}`:""} (depth=${this._criticalOperationDepth})`);let n=!1;return()=>{n||(n=!0,this._criticalOperationDepth=Math.max(0,this._criticalOperationDepth-1),this._log(`critical operation ended${e?`: ${e}`:""} (depth=${this._criticalOperationDepth})`))}}markConnected(){this._started&&(this._reconnectAttempts=0,this._reconnectPromise=null,this._cancelBackoff(),this._setState("connected"))}receivePong(e){e===this._pendingPingId&&(this._cancelPongTimeout(),this._pendingPingId=null,this._log("pong received, connection verified"))}handleError(e){const n=!ze(e);if(this._log(`error: ${e.message}, retryable=${n}`),this._state!=="reconnecting"){if(!n){this._setState("disconnected",`error: ${e.message}`),this._emitReconnectFailed(e);return}this._startReconnecting(`error: ${e.message}`)}}handleClose(e){const n=!e||!ze(e),s=(e==null?void 0:e.message)??"no error";if(this._log(`close: ${s}, retryable=${n}`),this._state!=="reconnecting"){if(e&&!n){this._setState("disconnected",`close: ${s}`),this._emitReconnectFailed(e);return}this._startReconnecting(`close: ${s}`)}}forceReconnect(e){if(this._shouldSuppressHealthReconnect(e)){this._log(`suppressing health reconnect during critical operation: ${e}`);return}this._log(`force reconnect${e?`: ${e}`:""}`),this._reconnectAttempts=0,this._cancelBackoff(),this._reconnectPromise=null,this._startReconnecting(e??"force")}on(e,n){const s=this._listeners[e];return s.add(n),()=>{s.delete(n)}}_log(e){const n=this._label?`[ConnectionManager:${this._label}]`:"[ConnectionManager]";console.log(`${n} ${e}`)}_setState(e,n){if(e===this._state)return;const s=this._state;this._state=e;const r=n?` (${n})`:"";this._log(`${s} → ${e}${r}`);for(const i of this._listeners.stateChange)i(e,s)}_emitReconnectFailed(e){for(const n of this._listeners.reconnectFailed)n(e)}_emitVisibilityRestored(){for(const e of this._listeners.visibilityRestored)e()}_startReconnecting(e){this._cancelPongTimeout(),this._pendingPingId=null,this._setState("reconnecting",e),this._scheduleReconnect()}_scheduleReconnect(){if(!this._started||!this._reconnectFn)return;if(!this._driveReconnect){this._log("passive manager observing reconnect state");return}if(this._reconnectAttempts>=this.config.maxAttempts){this._setState("disconnected"),this._emitReconnectFailed(new Error(`Reconnection failed after ${this.config.maxAttempts} attempts`));return}const e=this._getBackoffDelay(this._reconnectAttempts);this._reconnectAttempts++,this._log(`attempt ${this._reconnectAttempts}/${this.config.maxAttempts}, delay ${Math.round(e)}ms`),this._backoffTimerId=this.timers.setTimeout(()=>{this._backoffTimerId=null,this._executeReconnect()},e)}_executeReconnect(){if(!this._started||!this._reconnectFn||this._reconnectPromise)return;const e=this._reconnectFn,n=e();this._reconnectPromise=n,n.then(()=>{this._reconnectPromise===n&&this.markConnected()}).catch(s=>{if(this._reconnectPromise!==n)return;this._reconnectPromise=null;const r=s instanceof Error?s:new Error(String(s));if(this._log(`reconnect failed: ${r.message}`),ze(r)){this._setState("disconnected"),this._emitReconnectFailed(r);return}this._scheduleReconnect()})}_getBackoffDelay(e){const n=this.config.baseDelayMs*2**e,s=1+Math.random()*this.config.jitterFactor;return Math.min(this.config.maxDelayMs,n*s)}_cancelBackoff(){this._backoffTimerId!==null&&(this.timers.clearTimeout(this._backoffTimerId),this._backoffTimerId=null)}_startStaleCheck(){this._stopStaleCheck(),this._lastEventTime=this.timers.now(),this._staleCheckIntervalId=this.timers.setInterval(()=>{this._checkStale()},this.config.staleCheckIntervalMs)}_stopStaleCheck(){this._staleCheckIntervalId!==null&&(this.timers.clearInterval(this._staleCheckIntervalId),this._staleCheckIntervalId=null)}_checkStale(){if(this._state!=="connected"||!this._hasReceivedHeartbeat||this._criticalOperationDepth>0)return;const e=this.timers.now()-this._lastEventTime;e>=this.config.staleThresholdMs&&(this._log(`stale (${e}ms since last event)`),this.forceReconnect("stale"))}_startVisibilityListener(){this._removeVisibilityListener=this.visibility.onVisibilityChange(e=>{e?this._handleBecameVisible():(this._hiddenSince=this.timers.now(),this._log(`visibility hidden (${this._formatReconnectContext()})`))})}_stopVisibilityListener(){this._removeVisibilityListener&&(this._removeVisibilityListener(),this._removeVisibilityListener=null)}_handleBecameVisible(){const e=this._hiddenSince!==null?this.timers.now()-this._hiddenSince:null,n=`visibility visible${e!=null?` after ${e}ms hidden`:""}`;if(this._state!=="connected"){const r=this._formatReconnectContext();this._log(`${n}, keeping existing reconnect cycle (${r})`);return}if(this._hiddenSince=null,this._emitVisibilityRestored(),!this._sendPing){const r=this._formatReconnectContext();this._log(`${n}, no ping function (${r})`);return}if(this._criticalOperationDepth>0){const r=this._formatReconnectContext();this._log(`${n}, skipping ping during critical operation (${r})`);return}this._cancelPongTimeout();const s=String(++this._pingCounter);this._pendingPingId=s,this._log(`${n}, pinging (${this._formatReconnectContext()})`);try{this._sendPing(s)}catch{this._pendingPingId=null,this._log("ping send failed"),this.forceReconnect("ping-failed");return}this._pongTimeoutId=this.timers.setTimeout(()=>{this._pongTimeoutId=null,this._pendingPingId===s&&(this._log("pong timeout"),this._pendingPingId=null,this.forceReconnect("pong-timeout"))},this.config.pongTimeoutMs)}_cancelPongTimeout(){this._pongTimeoutId!==null&&(this.timers.clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null)}_shouldSuppressHealthReconnect(e){return this._criticalOperationDepth>0&&(e==="stale"||e==="ping-failed"||e==="pong-timeout")}_formatReconnectContext(){const e=[`state=${this._state}`];return this._reconnectAttempts>0&&e.push(`attempts=${this._reconnectAttempts}`),this._backoffTimerId!==null&&e.push("backoff=pending"),this._reconnectPromise&&e.push("reconnect=in-flight"),this._pendingPingId&&e.push(`pendingPing=${this._pendingPingId}`),this._criticalOperationDepth>0&&e.push(`criticalDepth=${this._criticalOperationDepth}`),e.join(", ")}}const Ds="";function Us(t){return t.timestamp===Ds}function ce(t){return t.uuid??t.id??""}function $s(t){const e=new Set;for(const s of t)e.add(ce(s));const n=new Set;for(const s of t){if(s.parentUuid&&e.has(s.parentUuid)&&!n.has(s.parentUuid))return!0;n.add(ce(s))}return!1}function Ns(t){if(t.length<=1||!$s(t))return t;const e=new Set;for(const o of t)e.add(ce(o));const n=[],s=new Set,r=new Map,i=o=>{const a=ce(o);if(a){if(s.has(a))return;s.add(a)}if(n.push(o),!a)return;const c=r.get(a);if(c){r.delete(a);for(const d of c)i(d)}};for(const o of t){const a=o.parentUuid;if(a&&e.has(a)&&!s.has(a)){const c=r.get(a)??[];c.push(o),r.set(a,c);continue}i(o)}if(r.size>0)for(const o of t){const a=ce(o);a&&!s.has(a)&&i(o)}return n}const un="_codexToolCorrelation";function st(t){if(!t||typeof t!="object")return null;const e=t[un];if(!e||typeof e!="object")return null;const n=e,s=n.origin;return s!=="command_execution"&&s!=="custom_tool_call"&&s!=="function_call"&&s!=="image_view"&&s!=="plan_update"||typeof n.turnId!="string"||typeof n.itemId!="string"?null:{origin:s,turnId:n.turnId,itemId:n.itemId,...typeof n.startedAt=="string"?{startedAt:n.startedAt}:{},...typeof n.durableCallId=="string"?{durableCallId:n.durableCallId}:{},...typeof n.liveItemId=="string"?{liveItemId:n.liveItemId}:{}}}class Fs{constructor(e={}){l(this,"mode","direct");l(this,"ws",null);l(this,"connectionPromise",null);l(this,"protocol");l(this,"options");l(this,"inboundChunks",new ls);l(this,"externalOnPong");this.options=e,this.protocol=new hs({sendMessage:n=>this.send(n),sendUploadChunk:(n,s,r)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");this.ws.send(fs(n,s,r))},ensureConnected:()=>this.ensureConnected(),isConnected:()=>{var n;return((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN}},{logPrefix:"[WebSocketConnection]"}),this.setConnectionManager(e.connectionManager??null)}setConnectionManager(e){this.options.connectionManager=e??void 0,this.updateProtocolPongHandler(),this.protocol.setOnInboundEvent(e?n=>{n.eventType==="heartbeat"?e.recordHeartbeat():e.recordEvent()}:void 0),this.protocol.setBeginCriticalOperation(e?n=>e.beginCriticalOperation(n):void 0)}getWsUrl(){const n=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`,s=ns();return s?`${n}?desktop_token=${encodeURIComponent(s)}`:n}async ensureConnected(){var e;if(((e=this.ws)==null?void 0:e.readyState)!==WebSocket.OPEN){if(this.connectionPromise)return this.connectionPromise;this.connectionPromise=this.connect();try{await this.connectionPromise}finally{this.connectionPromise=null}}}connect(){return new Promise((e,n)=>{var o,a;const s=this.getWsUrl();console.log("[WebSocketConnection] Connecting to",s),(a=(o=this.options).onSocketStateChange)==null||a.call(o,"connecting");const r=this.options.createWebSocket?this.options.createWebSocket(s):new WebSocket(s);r.binaryType="arraybuffer",r.onerror=c=>{console.error("[WebSocketConnection] Error:",c)},r.onclose=c=>{var h,f,m;console.log("[WebSocketConnection] Closed:",c.code,c.reason),this.ws=null,this.inboundChunks.reset();const d=new es(c.code,c.reason);this.protocol.rejectAllPending(d),this.protocol.notifySubscriptionsClosed(d),(f=(h=this.options).onSocketStateChange)==null||f.call(h,"disconnected"),(m=this.options.connectionManager)==null||m.handleClose(d)},r.onmessage=c=>{this.handleMessage(c.data)};const i=setTimeout(()=>{r.readyState!==WebSocket.OPEN&&(r.close(),n(new Error("WebSocket connection timeout")))},1e4);r.onopen=()=>{var c,d,h;clearTimeout(i),console.log("[WebSocketConnection] Connected"),this.ws=r,this.sendCapabilities(),(c=this.options.connectionManager)==null||c.markConnected(),(h=(d=this.options).onSocketStateChange)==null||h.call(d,"connected"),e()}})}handleMessage(e){var s,r;let n;if(ms(e))try{const i=this.inboundChunks.acceptFrame(e);if(!i)return;n=ps(i)}catch(i){i instanceof gs?console.warn(`[WebSocketConnection] Binary frame error (${i.code}):`,i.message):console.warn("[WebSocketConnection] Failed to decode binary frame:",i),i instanceof Ss&&((s=this.ws)==null||s.close(1002,"Invalid transport chunk sequence"));return}else if(typeof e=="string"){if(this.inboundChunks.hasPendingMessage){this.inboundChunks.reset(),(r=this.ws)==null||r.close(1002,"Transport chunk sequence interrupted");return}try{n=JSON.parse(e)}catch{console.warn("[WebSocketConnection] Failed to parse message:",e);return}}else{console.warn("[WebSocketConnection] Ignoring unknown message type");return}this.protocol.routeMessage(n)}sendCapabilities(){const e={type:"client_capabilities",version:ss(),capabilityBits:[],formats:[Ke.JSON,Ke.BINARY_UPLOAD,Ke.TRANSPORT_CHUNK]};this.send(e)}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");this.ws.send(ys(e))}async fetch(e,n){return this.protocol.fetch(e,n)}async fetchBlob(e){return this.protocol.fetchBlob(e)}async fetchResponse(e,n){return this.protocol.fetchResponse(e,n)}subscribeSession(e,n,s,r){return this.protocol.subscribeSession(e,n,s,r)}subscribeActivity(e){return this.protocol.subscribeActivity(e)}subscribeGlossary(e,n){return this.protocol.subscribeGlossary(e,n)}subscribeWorktree(e,n,s){return this.protocol.subscribeWorktree(e,n,s)}subscribeSessionWatch(e,n,s){return this.protocol.subscribeSessionWatch(e,n,s)}async upload(e,n,s,r){return this.protocol.upload(e,n,s,r)}async uploadStagedAttachment(e,n){return this.protocol.uploadStagedAttachment(e,n)}sendPing(e){this.protocol.sendPing(e)}setOnPong(e){this.externalOnPong=e,this.updateProtocolPongHandler()}updateProtocolPongHandler(){const e=this.options.connectionManager,n=this.externalOnPong;this.protocol.setOnPong(e||n?s=>{e==null||e.receivePong(s),n==null||n(s)}:void 0)}async reconnect(){const e=new ts;this.protocol.rejectAllPending(e),this.protocol.notifySubscriptionsClosed(e),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null,this.inboundChunks.reset()),this.connectionPromise=null,await this.ensureConnected()}sendMessage(e){this.send(e)}onDeviceMessage(e){return this.protocol.onDeviceMessage(e)}close(){var e,n;this.protocol.close(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.onopen=null,this.ws.close(),this.ws=null,this.inboundChunks.reset()),(n=(e=this.options).onSocketStateChange)==null||n.call(e,"disconnected")}}function Ls(t){const e=t.split("?",1)[0]??"";return e==="/local-image"||e==="/local-file"||/^\/projects\/[^/]+\/files\/raw$/.test(e)}class Qs{constructor(e){l(this,"listeners",new Set);l(this,"visibilityRestoredListeners",new Set);this.getSnapshotFn=e}getSnapshot(){return this.getSnapshotFn()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}subscribeVisibilityRestored(e){return this.visibilityRestoredListeners.add(e),()=>{this.visibilityRestoredListeners.delete(e)}}emit(){const e=[...this.listeners];for(const n of e)n()}emitVisibilityRestored(){const e=[...this.visibilityRestoredListeners];for(const n of e)n()}}class Bs{constructor(e={}){l(this,"kind","localhost");l(this,"capabilities",{sameOriginUrls:!0,device:{send:async e=>{this.assertNotDisposed(),await this.streamConnection.ensureConnected(),this.streamConnection.sendMessage(e)},onMessage:e=>this.streamConnection.onDeviceMessage(e)}});l(this,"status");l(this,"streamManager");l(this,"streamConnection");l(this,"mutableStatus");l(this,"uploadWebSocketFactory");l(this,"streamManagerStarted",!1);l(this,"streamSocketState","idle");l(this,"uploadSocketStates",new Map);l(this,"activeStreamSubscriptions",0);l(this,"activeUploads",0);l(this,"lastStreamError");l(this,"disposed",!1);l(this,"removeManagerStateListener",null);l(this,"removeManagerFailureListener",null);l(this,"removeManagerVisibilityListener",null);this.streamManager=new cn(e.connectionManagerConfig),this.uploadWebSocketFactory=e.uploadWebSocketFactory,this.streamConnection=new Fs({createWebSocket:e.streamWebSocketFactory,connectionManager:this.streamManager,onSocketStateChange:n=>this.handleStreamSocketState(n)}),this.mutableStatus=new Qs(()=>this.createSnapshot()),this.status=this.mutableStatus}fetch(e,n){return this.assertNotDisposed(),rs(e,n)}fetchBlob(e){return this.assertNotDisposed(),is(e,Ls(e)?{cache:"no-cache"}:void 0)}fetchResponse(e,n){return this.assertNotDisposed(),os(e,n)}upload(e,n,s,r){return this.assertNotDisposed(),this.withUploadChannel(i=>Es(e,n,s,r,{createWebSocket:i,beginCriticalOperation:o=>this.streamManager.beginCriticalOperation(o)}))}uploadStagedAttachment(e,n){return this.assertNotDisposed(),this.withUploadChannel(s=>_s(e,n,{createWebSocket:s,beginCriticalOperation:r=>this.streamManager.beginCriticalOperation(r)}))}subscribeSession(e,n,s,r){return this.trackStreamSubscription(i=>this.streamConnection.subscribeSession(e,i,s,r))(n)}subscribeSessionWatch(e,n,s){return this.trackStreamSubscription(r=>this.streamConnection.subscribeSessionWatch(e,r,s))(n)}subscribeActivity(e){return this.trackStreamSubscription(n=>this.streamConnection.subscribeActivity(n))(e)}subscribeGlossary(e,n){return this.trackStreamSubscription(s=>this.streamConnection.subscribeGlossary(e,s))(n)}subscribeWorktree(e,n,s){return this.trackStreamSubscription(r=>this.streamConnection.subscribeWorktree(e,n,r))(s)}async reconnect(){this.assertNotDisposed()}dispose(){var e,n,s;this.disposed||(this.disposed=!0,(e=this.removeManagerStateListener)==null||e.call(this),(n=this.removeManagerFailureListener)==null||n.call(this),(s=this.removeManagerVisibilityListener)==null||s.call(this),this.removeManagerStateListener=null,this.removeManagerFailureListener=null,this.removeManagerVisibilityListener=null,this.streamManager.stop(),this.streamConnection.close(),this.streamSocketState="disconnected",this.mutableStatus.emit())}handleStreamSocketState(e){this.disposed||(this.streamSocketState=e==="connected"?"connected":e,e==="connected"&&(this.lastStreamError=void 0,this.startStreamManager()),this.mutableStatus.emit())}startStreamManager(){if(this.streamManagerStarted){this.streamManager.markConnected();return}this.streamManagerStarted=!0,this.removeManagerStateListener=this.streamManager.on("stateChange",()=>this.mutableStatus.emit()),this.removeManagerFailureListener=this.streamManager.on("reconnectFailed",e=>{this.lastStreamError=e.message,this.mutableStatus.emit()}),this.removeManagerVisibilityListener=this.streamManager.on("visibilityRestored",()=>this.mutableStatus.emitVisibilityRestored()),this.streamManager.start(()=>this.streamConnection.reconnect(),{sendPing:e=>this.streamConnection.sendPing(e),label:"localhost-stream"})}trackStreamSubscription(e){return n=>{this.assertNotDisposed(),this.activeStreamSubscriptions+=1,this.mutableStatus.emit();let s=!1;const r=()=>{s||(s=!0,this.activeStreamSubscriptions=Math.max(0,this.activeStreamSubscriptions-1),this.mutableStatus.emit())},o=e({onEvent:(a,c,d)=>{a==="heartbeat"?this.streamManager.recordHeartbeat():this.streamManager.recordEvent(),n.onEvent(a,c,d)},onOpen:()=>{var a;this.startStreamManager(),this.streamManager.markConnected(),(a=n.onOpen)==null||a.call(n)},onError:a=>{var c;this.lastStreamError=a.message,this.streamManager.handleError(a),r(),(c=n.onError)==null||c.call(n,a)},onClose:a=>{var c;a&&(this.lastStreamError=a.message,this.streamManager.handleClose(a)),r(),(c=n.onClose)==null||c.call(n,a)}});return{close:()=>o.close()}}}async withUploadChannel(e){this.activeUploads+=1,this.mutableStatus.emit();const n=[],s=r=>{const i=this.uploadWebSocketFactory?this.uploadWebSocketFactory(r):new WebSocket(r);return n.push(this.trackUploadSocket(i)),i};try{return await e(s)}finally{for(const r of n)r();this.activeUploads=Math.max(0,this.activeUploads-1),this.mutableStatus.emit()}}trackUploadSocket(e){const n=o=>{this.uploadSocketStates.has(e)&&(this.uploadSocketStates.set(e,o),this.mutableStatus.emit())},s=()=>n("connected"),r=()=>n("disconnected"),i=()=>n("disconnected");return this.uploadSocketStates.set(e,e.readyState===WebSocket.OPEN?"connected":"connecting"),e.addEventListener("open",s),e.addEventListener("close",r),e.addEventListener("error",i),this.mutableStatus.emit(),()=>{e.removeEventListener("open",s),e.removeEventListener("close",r),e.removeEventListener("error",i),this.uploadSocketStates.delete(e),this.mutableStatus.emit()}}createSnapshot(){const e=[{name:"same-origin-http",state:"stateless"},{name:"stream-websocket",state:this.getStreamChannelState(),activeSubscriptions:this.activeStreamSubscriptions,...this.streamManager.reconnectAttempts>0?{reconnectAttempts:this.streamManager.reconnectAttempts}:{},...this.lastStreamError?{lastError:this.lastStreamError}:{}}];return this.activeUploads>0&&e.push({name:"upload-websocket",state:this.getUploadChannelState(),activeSubscriptions:this.activeUploads}),{kind:this.kind,state:"ready",channels:e}}getStreamChannelState(){if(this.disposed)return"disconnected";if(!this.streamManagerStarted)return this.streamSocketState;switch(this.streamManager.state){case"connected":return"connected";case"reconnecting":return"reconnecting";case"disconnected":return this.streamSocketState==="connecting"?"connecting":"disconnected"}}getUploadChannelState(){if(this.uploadSocketStates.size===0)return"connecting";let e=!1;for(const n of this.uploadSocketStates.values()){if(n==="connected")return"connected";n==="connecting"&&(e=!0)}return e?"connecting":"disconnected"}assertNotDisposed(){if(this.disposed)throw new Error("LocalhostSourceTransport has been disposed")}}const Ws=15e3;class Gs{constructor(e){l(this,"listeners",new Set);l(this,"visibilityRestoredListeners",new Set);this.getSnapshotFn=e}getSnapshot(){return this.getSnapshotFn()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}subscribeVisibilityRestored(e){return this.visibilityRestoredListeners.add(e),()=>{this.visibilityRestoredListeners.delete(e)}}emit(){const e=[...this.listeners];for(const n of e)n()}emitVisibilityRestored(){const e=[...this.visibilityRestoredListeners];for(const n of e)n()}}class dn{constructor(e,n={}){l(this,"kind");l(this,"status");l(this,"capabilities");l(this,"channelName");l(this,"managerLabel");l(this,"readyTimeoutMs");l(this,"manager");l(this,"mutableStatus");l(this,"reconnectConnection");l(this,"connection",null);l(this,"slotState","detached");l(this,"activeSubscriptions",0);l(this,"lastError");l(this,"disposed",!1);l(this,"removeManagerStateListener",null);l(this,"removeManagerFailureListener",null);l(this,"removeManagerVisibilityListener",null);l(this,"attachWaiters",new Set);l(this,"deviceHandlers",new Set);l(this,"deviceUnsubscribers",new Map);this.kind=e.kind,this.channelName=e.channelName,this.managerLabel=e.managerLabel,this.readyTimeoutMs=n.readyTimeoutMs??Ws,this.manager=new cn(n.connectionManagerConfig),this.reconnectConnection=e.reconnect,this.mutableStatus=new Gs(()=>this.createSnapshot()),this.status=this.mutableStatus,this.capabilities={sameOriginUrls:e.sameOriginUrls,...e.device?{device:{send:s=>this.sendDeviceMessage(s),onMessage:s=>this.addDeviceHandler(s)}}:{},...e.speech?{speech:{open:()=>this.openSpeechSocket()}}:{}},this.removeManagerStateListener=this.manager.on("stateChange",()=>{this.mutableStatus.emit()}),this.removeManagerFailureListener=this.manager.on("reconnectFailed",s=>{this.lastError=s.message,this.mutableStatus.emit()}),this.removeManagerVisibilityListener=this.manager.on("visibilityRestored",()=>this.mutableStatus.emitVisibilityRestored())}attach(e,n={}){var s,r,i;this.assertNotDisposed(),this.connection&&this.connection!==e?((r=(s=this.connection).setConnectionManager)==null||r.call(s,null),this.detachDeviceHandlers(),this.manager.stop()):this.connection===e&&this.detachDeviceHandlers(),this.connection=e,this.slotState=n.state??"ready",(i=e.setConnectionManager)==null||i.call(e,this.manager),this.startPassiveManager(),this.attachDeviceHandlers(),this.resolveAttachWaiters(e),this.mutableStatus.emit()}detach(){var e,n;this.disposed||((n=(e=this.connection)==null?void 0:e.setConnectionManager)==null||n.call(e,null),this.detachDeviceHandlers(),this.connection=null,this.slotState="detached",this.manager.stop(),this.mutableStatus.emit())}fetch(e,n){return this.assertNotDisposed(),this.withConnection(s=>s.fetch(e,n))}fetchBlob(e){return this.assertNotDisposed(),this.withConnection(n=>n.fetchBlob(e))}fetchResponse(e,n){return this.assertNotDisposed(),this.withConnection(s=>s.fetchResponse(e,n))}upload(e,n,s,r){return this.assertNotDisposed(),this.withConnection(i=>i.upload(e,n,s,r))}uploadStagedAttachment(e,n){return this.assertNotDisposed(),this.withConnection(s=>s.uploadStagedAttachment(e,n))}subscribeSession(e,n,s,r){return this.subscribeNow(n,(i,o)=>i.subscribeSession(e,o,s,r))}subscribeSessionWatch(e,n,s){return this.subscribeNow(n,(r,i)=>r.subscribeSessionWatch(e,i,s))}subscribeActivity(e){return this.subscribeNow(e,(n,s)=>n.subscribeActivity(s))}subscribeGlossary(e,n){return this.subscribeNow(n,(s,r)=>s.subscribeGlossary(e,r))}subscribeWorktree(e,n,s){return this.subscribeNow(s,(r,i)=>r.subscribeWorktree(e,n,i))}async reconnect(){this.assertNotDisposed();const e=await this.waitForConnection();this.slotState="connecting",this.mutableStatus.emit(),await this.reconnectConnection(e),this.slotState="ready",this.manager.markConnected(),this.mutableStatus.emit()}dispose(){var e,n,s,r,i,o;this.disposed||(this.disposed=!0,this.rejectAttachWaiters(new Ye(this.kind)),(e=this.removeManagerStateListener)==null||e.call(this),(n=this.removeManagerFailureListener)==null||n.call(this),(s=this.removeManagerVisibilityListener)==null||s.call(this),this.removeManagerStateListener=null,this.removeManagerFailureListener=null,this.removeManagerVisibilityListener=null,this.detachDeviceHandlers(),(i=(r=this.connection)==null?void 0:r.setConnectionManager)==null||i.call(r,null),(o=this.connection)==null||o.close(),this.connection=null,this.slotState="detached",this.manager.stop(),this.mutableStatus.emit())}getAttachedConnection(){return this.connection}startPassiveManager(){this.connection&&(this.manager.start(()=>{const n=this.connection;return n?this.reconnectConnection(n):Promise.reject(this.createNotReadyError())},{sendPing:n=>{var s;return(s=this.connection)==null?void 0:s.sendPing(n)},label:this.managerLabel,driveReconnect:!0}),this.slotState==="ready"&&this.manager.markConnected())}subscribeNow(e,n){this.assertNotDisposed();const s=this.connection;if(!s){let c=!1;return queueMicrotask(()=>{var d;c||(d=e.onError)==null||d.call(e,this.createNotReadyError())}),{close:()=>{c=!0}}}this.activeSubscriptions+=1,this.mutableStatus.emit();let r=!1;const i=()=>{r||(r=!0,this.activeSubscriptions=Math.max(0,this.activeSubscriptions-1),this.mutableStatus.emit())},a=n(s,{onEvent:(c,d,h)=>{e.onEvent(c,d,h)},onOpen:()=>{var c;(c=e.onOpen)==null||c.call(e)},onError:c=>{var d;this.lastError=c.message,i(),(d=e.onError)==null||d.call(e,c)},onClose:c=>{var d;c&&(this.lastError=c.message),i(),(d=e.onClose)==null||d.call(e,c)}});return{close:()=>{i(),a.close()}}}async withConnection(e){const n=await this.waitForConnection();if(this.manager.state==="disconnected")throw this.createDisconnectedError();return e(n)}waitForConnection(){return this.disposed?Promise.reject(new Ye(this.kind)):this.connection?Promise.resolve(this.connection):new Promise((e,n)=>{let s;const r={resolve:i=>{clearTimeout(s),this.attachWaiters.delete(r),e(i)},reject:i=>{clearTimeout(s),this.attachWaiters.delete(r),n(i)}};s=setTimeout(()=>{this.attachWaiters.delete(r),n(this.createNotReadyError())},this.readyTimeoutMs),this.attachWaiters.add(r)})}resolveAttachWaiters(e){const n=[...this.attachWaiters];for(const s of n)s.resolve(e)}rejectAttachWaiters(e){const n=[...this.attachWaiters];for(const s of n)s.reject(e)}createNotReadyError(){return new as({kind:this.kind,state:this.getSourceState(),channel:this.channelName,timeoutMs:this.readyTimeoutMs})}createDisconnectedError(){return new cs({kind:this.kind,channel:this.channelName,lastError:this.lastError})}createSnapshot(){return{kind:this.kind,state:this.getSourceState(),channels:[this.createChannelSnapshot()]}}createChannelSnapshot(){return{name:this.channelName,state:this.getChannelState(),activeSubscriptions:this.activeSubscriptions,...this.manager.reconnectAttempts>0?{reconnectAttempts:this.manager.reconnectAttempts}:{},...this.lastError?{lastError:this.lastError}:{}}}getSourceState(){if(this.disposed||!this.connection)return"disconnected";if(this.slotState==="connecting")return"connecting";switch(this.manager.state){case"connected":return"ready";case"reconnecting":return"reconnecting";case"disconnected":return"disconnected"}}getChannelState(){if(this.disposed||!this.connection)return"disconnected";if(this.slotState==="connecting")return"connecting";switch(this.manager.state){case"connected":return"connected";case"reconnecting":return"reconnecting";case"disconnected":return"disconnected"}}async sendDeviceMessage(e){const n=await this.waitForConnection();if(!n.sendMessage)throw new Ut({kind:this.kind,operation:"device signaling",channel:this.channelName});n.sendMessage(e)}addDeviceHandler(e){this.deviceHandlers.add(e);const n=this.attachDeviceHandler(e);return n&&this.deviceUnsubscribers.set(e,n),()=>{var s;(s=this.deviceUnsubscribers.get(e))==null||s(),this.deviceUnsubscribers.delete(e),this.deviceHandlers.delete(e)}}attachDeviceHandlers(){for(const e of this.deviceHandlers){const n=this.attachDeviceHandler(e);n&&this.deviceUnsubscribers.set(e,n)}}detachDeviceHandlers(){for(const e of this.deviceUnsubscribers.values())e();this.deviceUnsubscribers.clear()}attachDeviceHandler(e){const n=this.connection;return n!=null&&n.onDeviceMessage?n.onDeviceMessage(e):null}async openSpeechSocket(){const e=await this.waitForConnection();if(!e.openSpeechSocket)throw new Ut({kind:this.kind,operation:"speech socket",channel:this.channelName});return e.openSpeechSocket()}assertNotDisposed(){if(this.disposed)throw new Ye(this.kind)}}class Hs extends dn{constructor(e={}){super({kind:"websocket",channelName:"multiplex-websocket",managerLabel:"source-websocket",sameOriginUrls:e.sameOriginUrls??!0,device:!0,speech:!1,reconnect:n=>n.reconnect()},e)}}class Js extends dn{constructor(e={}){super({kind:"secure",channelName:"secure-websocket",managerLabel:"source-secure",sameOriginUrls:!1,device:!0,speech:!0,reconnect:n=>n.forceReconnect()},e)}}const Nt=t=>{let e;const n=new Set,s=(d,h)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const m=e;e=h??(typeof f!="object"||f===null)?f:Object.assign({},e,f),n.forEach(p=>p(e,m))}},r=()=>e,a={setState:s,getState:r,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=e=t(s,r,a);return a},Vs=(t=>t?Nt(t):Nt),qs=t=>t;function A(t,e=qs){const n=Ce.useSyncExternalStore(t.subscribe,Ce.useCallback(()=>e(t.getState()),[t,e]),Ce.useCallback(()=>e(t.getInitialState()),[t,e]));return Ce.useDebugValue(n),n}function dc(t,e){return{awaitingFirstRows:e===0&&(t==null?void 0:t.complete)===!1&&t.refreshing,refreshError:t!=null&&t.refreshError?new Error(t.refreshError):null}}function P(t,e){const n=t.sessions.aliases;if(!n.size)return e;let s=e;const r=new Set;for(;!r.has(s);){r.add(s);const i=n.get(s);if(!i)break;s=i}return s}const oe="all-projects",rt=[],zs=[],Ys={status:"running"},fe=["needsAttention","active","recentActivity","unread8h","unread24h"];function gt(t){return{needsAttention:t(),active:t(),recentActivity:t(),unread8h:t(),unread24h:t()}}const Ks=["needsAttention","active"];function lc(t){return{scope:"global-sessions",projectId:t.projectId??null,searchQuery:t.searchQuery||void 0,limit:t.limit,includeArchived:t.includeArchived,starred:t.starred}}function Be(t){var n;const e={scope:t.scope,projectId:t.projectId??null,searchQuery:((n=t.searchQuery)==null?void 0:n.trim())||null,limit:t.limit??null,includeArchived:t.includeArchived===!0,starred:t.starred===!0};return JSON.stringify(e)}function De(t){return t==="in-turn"||t==="waiting-input"}function Xs(t,e){return e?t.sessions.entities.get(P(t,e)):void 0}function Zs(t,e){var s;if(!e)return null;const n=P(t,e);return((s=t.providerRuntime.bySessionId.get(n))==null?void 0:s.status)??null}function er(t,e){return t.sessions.queries.get(Be(e))}function tr(t,e){return e?t.projects.entities.get(e):void 0}function nr(t){const e=t.projects.queries.get(oe);return e?e.ids.flatMap(n=>{const s=t.projects.entities.get(n);return s?[s]:[]}):[]}function sr(t,e){var n;return e?((n=t.projectQueues.byProject.get(e))==null?void 0:n.items)??rt:rt}function rr(t,e){const n={};for(const s of e){const r=t.projectQueues.byProject.get(s);r&&(n[s]=r.items)}return n}function ir(t,e){const n=new Set(e);return(t.projectQueues.globalItemsObservedAt!==void 0?t.projectQueues.globalItems:[...t.projectQueues.byProject.values()].flatMap(r=>r.items)).filter(r=>n.has(r.projectId))}function or(t){return t.projectQueues.dispatchState}function ar(t){return t.projectQueues.recoveredSessionQueues}function cr(t){const e={};for(const[n,s]of t.projectQueues.projectStatusesByProject)e[n]=s.status;return e}function Ft(t){return t.filter(e=>e.status==="queued"||e.status==="failed").length}function ur(t,e){const n=new Set;let s=0;for(const r of e){n.add(r.id);const i=t.projectQueues.byProject.get(r.id),o=r.snapshotObservedAt??Number.NEGATIVE_INFINITY;i&&i.observedAt>=o?s+=Ft(i.items):s+=r.projectQueueCount??0}for(const[r,i]of t.projectQueues.byProject)n.has(r)||(s+=Ft(i.items));return s}function dr(t,e){const n=new Set;for(const s of e){const r=sr(t,s);for(const i of r)i.target.type==="existing-session"&&n.add(i.target.sessionId)}return n}function lr(t){return t.localDecorations.draftSessionIds}function hr(t){return!t.projectId||!t.updatedAt?null:{sessionId:t.id,projectId:t.projectId,projectName:t.projectName??"",sessionTitle:t.title??null,updatedAt:t.updatedAt,customTitle:t.customTitle,isStarred:t.isStarred,pendingInputType:t.pendingInputType,activity:t.activity,activityInferredFromInboxTier:t.activityInferredFromInboxTier,hasUnread:t.hasUnread,asyncQuestions:t.asyncQuestions,nonHumanUserTurn:t.nonHumanUserTurn}}function te(t,e){return t.inbox.tiers[e].flatMap(n=>{const s=t.sessions.entities.get(n);if(!s)return[];const r=hr(s);return r?[r]:[]})}function fr(t){return{...t.inbox.catalog?{catalog:t.inbox.catalog}:{},needsAttention:te(t,"needsAttention"),active:te(t,"active"),recentActivity:te(t,"recentActivity"),unread8h:te(t,"unread8h"),unread24h:te(t,"unread24h")}}function mr(t){return{needsAttention:t.inbox.tiers.needsAttention.length,active:t.inbox.tiers.active.length,total:fe.reduce((e,n)=>e+t.inbox.tiers[n].length,0)}}function pr(t,e,n){const s=t.get(e)??{needsAttention:0,active:0,total:0};t.set(e,{needsAttention:s.needsAttention+(n==="needsAttention"?1:0),active:s.active+(n==="active"?1:0),total:s.total+1})}function gr(t){var n;const e=new Map;for(const s of fe)for(const r of t.inbox.tiers[s]){const i=(n=t.sessions.entities.get(r))==null?void 0:n.projectId;i&&pr(e,i,s)}return e}function Sr(t,e){if(!e)return[];const n=[];for(const s of Ks)for(const r of t.inbox.tiers[s]){const i=t.sessions.entities.get(r);(i==null?void 0:i.projectId)===e&&n.push(r)}return n}function yr(t){return t.inbox.tiers.active.length}function Lt(t){return t.updatedAt&&Date.parse(t.updatedAt)||0}function br(t,e){return Lt(e)-Lt(t)}function Qt(t){return t.activeStartedAt??t.eventCreatedAt??t.observedAt}function vr(t,e){return Qt(t)-Qt(e)}function Ir(t){const e=t.filter(s=>De(s.activity)).sort(vr),n=t.filter(s=>!De(s.activity)).sort(br);return[...e,...n]}function Cr(t){return wr(Array.from(t.sessions.entities.values()))}function wr(t){return Ir(t.filter(e=>e.isStarred===!0&&e.isArchived!==!0))}function Tr(t,e){const n=Be(e),s=t.sessions.queries.get(n);return s?s.ids.flatMap(r=>{const i=t.sessions.entities.get(r);return i?[i]:[]}):[]}const x=Number.NEGATIVE_INFINITY,Ar=6e4,Mr=256;function ln(){return{sessions:{entities:new Map,queries:new Map,aliases:new Map},projects:{entities:new Map,queries:new Map},projectQueues:{byProject:new Map,globalItems:rt,dispatchState:Ys,recoveredSessionQueues:zs,projectStatusesByProject:new Map},inbox:{tiers:gt(()=>[])},localDecorations:{draftSessionIds:new Set},providerRuntime:{bySessionId:new Map}}}function Q(t,e){const n=P(t,e);return t.sessions.entities.get(n)??{id:n,observedAt:x}}function B(t,e){const n=P(t,e.id),s=e.parentSessionId?P(t,e.parentSessionId):e.parentSessionId,r=e.forkedFromSessionId?P(t,e.forkedFromSessionId):e.forkedFromSessionId,i=n===e.id&&s===e.parentSessionId&&r===e.forkedFromSessionId?e:{...e,id:n,parentSessionId:s,forkedFromSessionId:r},o=new Map(t.sessions.entities);return o.set(n,i),{...t,sessions:{...t.sessions,entities:o}}}function Ee(t,e){const n=new Set,s=[];for(const r of e){const i=P(t,r);n.has(i)||(n.add(i),s.push(i))}return s}const Bt={contentObservedAt:["title","fullTitle","createdAt","updatedAt","messageCount","provider","model","initialPrompt","lastAgentText","lastHumanTurnAt","asyncQuestions","providerChildren"],metadataObservedAt:["nonHumanUserTurn","customTitle","isArchived","isStarred","autoResumeDisabled","parentSessionId","parentSessionKind","forkedFromSessionId","clearloop","executor"],projectObservedAt:["projectId","projectName"],lifecycleObservedAt:["ownership","activity","activityInferredFromInboxTier","pendingInputType","activeStartedAt"],unreadObservedAt:["hasUnread"]};function Wt(t,e,n){if(!t&&!e)return;if(!t)return e;if(!e)return{...t,id:n};const s=(i,o)=>{const a=t[i]??x,c=e[i]??x,[d,h]=c>=a?[e,t]:[t,e],f=[];for(const p of o){const S=d[p]!==void 0?d[p]:h[p];S!==void 0&&f.push([p,S])}const m=Math.max(a,c);return m!==x&&f.push([i,m]),Object.fromEntries(f)},r={id:n,observedAt:Math.max(t.observedAt,e.observedAt)};for(const i of Object.keys(Bt))Object.assign(r,s(i,Bt[i]));return(t.snapshotObservedAt!==void 0||e.snapshotObservedAt!==void 0)&&(r.snapshotObservedAt=Math.max(t.snapshotObservedAt??x,e.snapshotObservedAt??x)),(t.eventCreatedAt!==void 0||e.eventCreatedAt!==void 0)&&(r.eventCreatedAt=Math.min(t.eventCreatedAt??Number.POSITIVE_INFINITY,e.eventCreatedAt??Number.POSITIVE_INFINITY)),r}function Pr(t,e){var i,o;let n=e.target;if(e.target.type==="existing-session"){const a=P(t,e.target.sessionId);a!==e.target.sessionId&&(n={...e.target,sessionId:a})}const s=(i=e.createdFrom)!=null&&i.sessionId?P(t,e.createdFrom.sessionId):(o=e.createdFrom)==null?void 0:o.sessionId,r=e.createdFrom&&s!==e.createdFrom.sessionId?{...e.createdFrom,sessionId:s}:e.createdFrom;return n===e.target&&r===e.createdFrom?e:{...e,target:n,createdFrom:r}}function Ue(t,e){let n=!1;const s=e.map(r=>{const i=Pr(t,r);return n||(n=i!==r),i});return n?s:e}function hn(t,e){let n=!1;const s=e.map(r=>{const i=P(t,r.sessionId);return i===r.sessionId?r:(n=!0,{...r,sessionId:i})});return n?s:e}function jr(t,e){if(t===e)return!0;if(!t||!e)return!1;const n=Object.keys(t),s=Object.keys(e);return n.length!==s.length?!1:n.every(r=>{const i=r;return t[i]===e[i]})}function Rr(t,e){return t.id===e.id&&t.path===e.path&&t.name===e.name&&t.sessionCount===e.sessionCount&&jr(t.sessionCountsByProvider,e.sessionCountsByProvider)&&t.activeOwnedCount===e.activeOwnedCount&&t.activeExternalCount===e.activeExternalCount&&t.projectQueueBlockingCount===e.projectQueueBlockingCount&&t.lastActivity===e.lastActivity}function fn(t,e,n){const s=t.projects.entities.get(e.id);if(s){if(n<(s.snapshotObservedAt??x))return t;if(Rr(s,e)){if(n===s.snapshotObservedAt)return t;const i=new Map(t.projects.entities);return i.set(e.id,{...s,observedAt:Math.max(s.observedAt,n),snapshotObservedAt:n}),{...t,projects:{...t.projects,entities:i}}}}const r=new Map(t.projects.entities);return r.set(e.id,{...e,observedAt:Math.max((s==null?void 0:s.observedAt)??x,n),snapshotObservedAt:n}),{...t,projects:{...t.projects,entities:r}}}function xr(t,e,n){const s=t.projects.queries.get(oe);if(s&&n<s.requestStartedAt)return t;const r=e.map(o=>o.id);if(s&&s.ids.length===r.length&&s.ids.every((o,a)=>o===r[a])){if(n===s.requestStartedAt)return t;const o=new Map(t.projects.queries);return o.set(oe,{...s,requestStartedAt:n,fetchedAt:Date.now()}),{...t,projects:{...t.projects,queries:o}}}const i=new Map(t.projects.queries);return i.set(oe,{key:oe,ids:r,requestStartedAt:n,fetchedAt:Date.now()}),{...t,projects:{...t.projects,queries:i}}}function _e(t,e){return t===e?!0:JSON.stringify(t)===JSON.stringify(e)}function St(t,e){return t===e?!0:t.length!==e.length?!1:t.every((n,s)=>{const r=e[s];return r?n.id===r.id&&n.projectId===r.projectId&&_e(n.target,r.target)&&n.targetTitle===r.targetTitle&&n.targetFullTitle===r.targetFullTitle&&n.messagePreview===r.messagePreview&&_e(n.message,r.message)&&n.createdAt===r.createdAt&&n.updatedAt===r.updatedAt&&_e(n.createdFrom,r.createdFrom)&&n.status===r.status&&n.attachmentCount===r.attachmentCount&&n.lastError===r.lastError&&n.lastAttemptAt===r.lastAttemptAt:!1})}function mn(t,e){if(!(t!=null&&t.length))return e;const n=new Map(t.map(i=>[i.id,i]));let s=!1;const r=e.map(i=>{if(i.targetTitle!==void 0&&i.targetFullTitle!==void 0)return i;const o=n.get(i.id);if(!o||!_e(i.target,o.target))return i;const a=i.targetTitle!==void 0?i.targetTitle:o.targetTitle,c=i.targetFullTitle!==void 0?i.targetFullTitle:o.targetFullTitle;return a===i.targetTitle&&c===i.targetFullTitle?i:(s=!0,{...i,...a!==void 0?{targetTitle:a}:{},...c!==void 0?{targetFullTitle:c}:{}})});return s?r:e}function Er(t,e){if(t.length!==e.length)return!1;const n=new Set(t.map(s=>s.id));return e.every(s=>n.has(s.id))}function _r(t,e,n){if(t.length===0)return n;const s=t.filter(a=>a.projectId===e);if(s.length===0)return n.length>0?[...t,...n]:t;if(Er(s,n)){let a=0;return t.map(c=>c.projectId===e?n[a++]:c)}const r=new Map(n.map(a=>[a.id,a])),i=new Set,o=[];for(const a of t){if(a.projectId!==e){o.push(a);continue}const c=r.get(a.id);c&&(o.push(c),i.add(c.id))}for(const a of n)i.has(a.id)||o.push(a);return o}function Or(t,e){return fe.every(n=>{const s=t[n],r=e[n];return s.length===r.length&&s.every((i,o)=>i===r[o])})}function kr(t,e){if(t===e)return!0;if(t.size!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function Dr(t,e){return JSON.stringify(t)===JSON.stringify(e)}function Ur(t,e){return JSON.stringify(t)===JSON.stringify(e)}function $r(t,e){return t===e?!0:JSON.stringify(t)===JSON.stringify(e)}function Nr(t,e){return JSON.stringify(t)===JSON.stringify(e)}function pn(t,e,n,s,r){const i=P(t,e),o=t.providerRuntime.bySessionId.get(i);if(o&&r<o.observedAt)return t;if(s===null){if(!o)return t;const c=new Map(t.providerRuntime.bySessionId);return c.delete(i),{...t,providerRuntime:{...t.providerRuntime,bySessionId:c}}}if(o&&r===o.observedAt&&o.projectId===n&&$r(o.status,s))return t;const a=new Map(t.providerRuntime.bySessionId);return a.set(i,{sessionId:i,projectId:n,status:s,observedAt:r}),{...t,providerRuntime:{...t.providerRuntime,bySessionId:a}}}function gn(t,e,n){return!e||n<(t.projectQueues.dispatchStateObservedAt??x)||Dr(t.projectQueues.dispatchState,e)&&n===t.projectQueues.dispatchStateObservedAt?t:{...t,projectQueues:{...t.projectQueues,dispatchState:e,dispatchStateObservedAt:n}}}function Sn(t,e,n,s){if(!e)return t;let r=null;const i=new Set(Object.keys(e));for(const[o,a]of Object.entries(e)){const c=t.projectQueues.projectStatusesByProject.get(o);c&&c.observedAt>n||c&&c.observedAt===n&&Nr(c.status,a)||(r||(r=new Map(t.projectQueues.projectStatusesByProject)),r.set(o,{projectId:o,status:a,observedAt:n}))}if(s==="replace")for(const[o,a]of t.projectQueues.projectStatusesByProject)i.has(o)||a.observedAt>n||(r||(r=new Map(t.projectQueues.projectStatusesByProject)),r.delete(o));return r?{...t,projectQueues:{...t.projectQueues,projectStatusesByProject:r}}:t}function Fr(t,e,n){if(!e)return t;const s=hn(t,e);return n<(t.projectQueues.recoveredSessionQueuesObservedAt??x)||Ur(t.projectQueues.recoveredSessionQueues,s)&&n===t.projectQueues.recoveredSessionQueuesObservedAt?t:{...t,projectQueues:{...t.projectQueues,recoveredSessionQueues:s,recoveredSessionQueuesObservedAt:n}}}function yt(t,e,n){let s=gn(t,e.dispatchState,n);s=Sn(s,e.projectStatuses,n,"merge");const r=s.projectQueues.byProject.get(e.projectId),i=Ue(s,e.items),o=mn(r==null?void 0:r.items,i);if(r){if(n<(r.snapshotObservedAt??x))return s;if(St(r.items,o)){const c=new Map(s.projectQueues.byProject);return c.set(e.projectId,{...r,observedAt:Math.max(r.observedAt,n),snapshotObservedAt:n}),s={...s,projectQueues:{...s.projectQueues,byProject:c}},s.projectQueues.globalItemsObservedAt!==void 0&&n>=s.projectQueues.globalItemsObservedAt?Gt(s,e.projectId,o,n):s}}const a=new Map(s.projectQueues.byProject);return a.set(e.projectId,{projectId:e.projectId,items:o,observedAt:Math.max((r==null?void 0:r.observedAt)??x,n),snapshotObservedAt:n}),s={...s,projectQueues:{...s.projectQueues,byProject:a}},s.projectQueues.globalItemsObservedAt!==void 0&&n>=s.projectQueues.globalItemsObservedAt?Gt(s,e.projectId,o,n):s}function Gt(t,e,n,s){const r=_r(t.projectQueues.globalItems,e,n);return St(t.projectQueues.globalItems,r)&&s===t.projectQueues.globalItemsObservedAt?t:{...t,projectQueues:{...t.projectQueues,globalItems:r,globalItemsObservedAt:s}}}function Lr(t,e,n){if(n<(t.projectQueues.globalItemsObservedAt??x))return t;const s=new Map,r=mn(t.projectQueues.globalItems,Ue(t,e.items));for(const a of r){const c=s.get(a.projectId);c?c.push(a):s.set(a.projectId,[a])}let i=t;for(const[a,c]of s)i=yt(i,{projectId:a,items:c},n);let o=null;for(const[a,c]of i.projectQueues.byProject)s.has(a)||(c.snapshotObservedAt??x)>n||(o||(o=new Map(i.projectQueues.byProject)),o.delete(a));return o&&(i={...i,projectQueues:{...i.projectQueues,byProject:o}}),(!St(i.projectQueues.globalItems,r)||n!==i.projectQueues.globalItemsObservedAt)&&(i={...i,projectQueues:{...i.projectQueues,globalItems:r,globalItemsObservedAt:n}}),i=gn(i,e.dispatchState,n),i=Sn(i,e.projectStatuses,n,"replace"),Fr(i,e.recoveredSessionQueues,n)}function Qr(t,e,n){let s=Q(t,e.sessionId);s=pe(s,{title:e.sessionTitle,asyncQuestions:e.asyncQuestions,updatedAt:e.updatedAt},n),s=Se(s,{projectId:e.projectId,projectName:e.projectName},n),s=ge(s,{customTitle:e.customTitle,nonHumanUserTurn:e.nonHumanUserTurn,isStarred:e.isStarred},n);const r=e.activity??(e.pendingInputType?"waiting-input":null);return s=ye(s,{activity:r,activityInferredFromInboxTier:!1,pendingInputType:e.pendingInputType},n),s=We(s,e.hasUnread,n),B(t,s)}function Br(t,e,n){var c;if(t.inbox.requestStartedAt!==void 0&&n<t.inbox.requestStartedAt)return t;const s=W(n,"partial-snapshot","inbox");let r=t;const i=gt(()=>[]),o=new Set;for(const d of fe)for(const h of e[d]){const f=P(r,h.sessionId);o.has(f)||(o.add(f),i[d].push(f)),r=Qr(r,h,s)}const a=Or(r.inbox.tiers,i)?r.inbox.tiers:i;return{...r,inbox:{...r.inbox,tiers:((c=e.catalog)==null?void 0:c.complete)===!1?r.inbox.tiers:a,catalog:e.catalog,requestStartedAt:n,fetchedAt:Date.now()}}}function Wr(t){return t==="in-turn"||t==="waiting-input"?t:void 0}function W(t,e,n){return{observedAt:t,kind:e,source:n}}function me(t,e){return t.observedAt>=(e??x)}function C(t,e,n){return e!==void 0&&(n||t===void 0)}function pe(t,e,n){if(Object.values(e).every(r=>r===void 0))return t;const s=me(n,t.contentObservedAt);return{...t,...C(t.title,e.title,s)?{title:e.title}:{},...C(t.fullTitle,e.fullTitle,s)?{fullTitle:e.fullTitle}:{},...C(t.createdAt,e.createdAt,s)?{createdAt:e.createdAt}:{},...C(t.updatedAt,e.updatedAt,s)?{updatedAt:e.updatedAt}:{},...C(t.messageCount,e.messageCount,s)?{messageCount:e.messageCount}:{},...C(t.provider,e.provider,s)?{provider:e.provider}:{},...C(t.model,e.model,s)?{model:e.model}:{},...C(t.initialPrompt,e.initialPrompt,s)?{initialPrompt:e.initialPrompt}:{},...C(t.lastAgentText,e.lastAgentText,s)?{lastAgentText:e.lastAgentText}:{},...C(t.lastHumanTurnAt,e.lastHumanTurnAt,s)?{lastHumanTurnAt:e.lastHumanTurnAt}:{},...C(t.providerChildren,e.providerChildren,s)?{providerChildren:e.providerChildren}:{},...C(t.asyncQuestions,e.asyncQuestions,s)?{asyncQuestions:e.asyncQuestions}:{},...s?{contentObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function ge(t,e,n){if(Object.values(e).every(r=>r===void 0))return t;const s=me(n,t.metadataObservedAt);return{...t,...C(t.customTitle,e.customTitle,s)?{customTitle:e.customTitle}:{},...C(t.nonHumanUserTurn,e.nonHumanUserTurn,s)?{nonHumanUserTurn:e.nonHumanUserTurn}:{},...C(t.isArchived,e.isArchived,s)?{isArchived:e.isArchived}:{},...C(t.isStarred,e.isStarred,s)?{isStarred:e.isStarred}:{},...C(t.autoResumeDisabled,e.autoResumeDisabled,s)?{autoResumeDisabled:e.autoResumeDisabled}:{},...e.parentSessionId===null?s?{parentSessionId:void 0}:{}:C(t.parentSessionId,e.parentSessionId,s)?{parentSessionId:e.parentSessionId}:{},...e.parentSessionKind===null?s?{parentSessionKind:void 0}:{}:C(t.parentSessionKind,e.parentSessionKind,s)?{parentSessionKind:e.parentSessionKind}:{},...e.forkedFromSessionId===null?s?{forkedFromSessionId:void 0}:{}:C(t.forkedFromSessionId,e.forkedFromSessionId,s)?{forkedFromSessionId:e.forkedFromSessionId}:{},...e.clearloop===null?s?{clearloop:void 0}:{}:C(t.clearloop,e.clearloop,s)?{clearloop:e.clearloop}:{},...C(t.executor,e.executor,s)?{executor:e.executor}:{},...s?{metadataObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function Se(t,e,n){if(Object.values(e).every(r=>r===void 0))return t;const s=me(n,t.projectObservedAt);return{...t,...C(t.projectId,e.projectId,s)?{projectId:e.projectId}:{},...C(t.projectName,e.projectName,s)?{projectName:e.projectName}:{},...s?{projectObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function bt(t,e,n){const s=t.projectId===void 0||e.projectId===void 0||t.projectId===e.projectId;return Se(t,{projectId:t.projectId===void 0?e.projectId:void 0,projectName:s&&t.projectName===void 0?e.projectName:void 0},n)}function ye(t,e,n){if(e.ownership===void 0&&e.activity===void 0&&e.activityInferredFromInboxTier===void 0&&e.pendingInputType===void 0)return t;const s=me(n,t.lifecycleObservedAt),r=Wr(e.activity),i=De(t.activity),o=s?r:t.activity,a=De(o),c=s?o==="waiting-input"?e.pendingInputType:void 0:o==="waiting-input"&&C(t.pendingInputType,e.pendingInputType,s)?e.pendingInputType:t.pendingInputType;return{...t,...C(t.ownership,e.ownership,s)?{ownership:e.ownership}:{},activity:o,activityInferredFromInboxTier:s&&o?e.activityInferredFromInboxTier===!0:s?void 0:t.activityInferredFromInboxTier,activeStartedAt:s?a?i?t.activeStartedAt:n.observedAt:void 0:t.activeStartedAt,pendingInputType:c,...s?{lifecycleObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function We(t,e,n){if(e===void 0)return t;const s=me(n,t.unreadObservedAt);return!s&&t.hasUnread!==void 0?t:{...t,hasUnread:e,...s?{unreadObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function Gr(t,e,n){let s=Q(t,e.id);return s=pe(s,{title:e.title,fullTitle:e.fullTitle,createdAt:e.createdAt,updatedAt:e.updatedAt,messageCount:e.messageCount,provider:e.provider,model:e.model,initialPrompt:e.initialPrompt,lastAgentText:e.lastAgentText,lastHumanTurnAt:e.lastHumanTurnAt,asyncQuestions:e.asyncQuestions,providerChildren:e.providerChildren},n),s=ge(s,{customTitle:e.customTitle,nonHumanUserTurn:e.nonHumanUserTurn,isArchived:e.isArchived,isStarred:e.isStarred,clearloop:e.clearloop,autoResumeDisabled:e.autoResumeDisabled,parentSessionId:e.parentSessionId,parentSessionKind:e.parentSessionKind,forkedFromSessionId:e.forkedFromSessionId,executor:e.executor},n),s=Se(s,{projectId:e.projectId,projectName:e.projectName},n),s=ye(s,{ownership:e.ownership,activity:e.activity,pendingInputType:e.pendingInputType},n),s=We(s,e.hasUnread,n),s={...s,snapshotObservedAt:Math.max(s.snapshotObservedAt??x,n.observedAt),observedAt:Math.max(s.observedAt,n.observedAt)},B(t,s)}function Hr(t,e,n){var c;const s=Be(e.query),r=t.sessions.queries.get(s);if(r&&n<r.requestStartedAt)return t;const i=Ee(t,e.sessions.map(d=>d.id));let o=i;if((e.mode==="append"||((c=e.catalog)==null?void 0:c.complete)===!1)&&r)o=[...r.ids,...i.filter(d=>!r.ids.includes(d))];else if(e.mode==="prepend"&&r){const d=new Set(i);o=[...i,...r.ids.filter(h=>!d.has(h))]}else r&&(o=Jr(t,e.query,r.ids,i,n));const a=new Map(t.sessions.queries);return a.set(s,{key:s,descriptor:e.query,catalog:e.catalog,ids:o,hasMore:e.hasMore,requestStartedAt:n,fetchedAt:Date.now()}),{...t,sessions:{...t.sessions,queries:a}}}function Jr(t,e,n,s,r){const i=new Set(s),o=n.filter(a=>{if(i.has(a))return!1;const c=t.sessions.entities.get(a);return!!c&&Vr(c,r)&&qr(c,e)});return o.length>0?[...o,...s]:[...s]}function Vr(t,e){if(t.eventCreatedAt===void 0)return!1;const n=e-t.eventCreatedAt;return n>=0&&n<=Ar}function qr(t,e){var n;return!((n=e.searchQuery)!=null&&n.trim()||e.projectId&&t.projectId!==e.projectId||e.includeArchived!==!0&&t.isArchived===!0||e.starred===!0&&t.isStarred!==!0)}function zr(t,e,n=Date.now()){const s=W(n,"partial-snapshot","session-metadata");let r=Q(t,e.id);return r=pe(r,{title:e.title,fullTitle:e.fullTitle},s),r=ge(r,{customTitle:e.customTitle,nonHumanUserTurn:e.nonHumanUserTurn},s),r=Se(r,{projectId:e.projectId},s),B(t,r)}function Yr(t,e,n=Date.now()){const s=W(n,e.catalog?"partial-snapshot":"full-snapshot","global-sessions");let r=t;for(const i of e.sessions)r=Gr(r,i,s);return Hr(r,e,n)}function Kr(t,e,n=Date.now()){let s=t;for(const r of e.projects)s=fn(s,r,n);return xr(s,e.projects,n)}function Xr(t,e,n=Date.now()){return fn(t,e.project,n)}function Zr(t,e,n=Date.now()){return yt(t,e,n)}function ei(t,e,n=Date.now()){return Lr(t,e,n)}function ti(t,e,n=Date.now()){return yt(t,{projectId:e.projectId,items:e.items,dispatchState:e.dispatchState},n)}function ni(t,e,n=Date.now()){return Br(t,e,n)}function si(t,e){const n=P(t,e.oldSessionId),s=P(t,e.newSessionId);if(n===s)return t;const r=new Map(t.sessions.aliases);r.delete(s);for(const[b,v]of r)P(t,v)===n&&r.set(b,s);for(r.delete(e.oldSessionId),r.set(e.oldSessionId,s),n!==e.oldSessionId&&(r.delete(n),r.set(n,s));r.size>Mr;){const b=r.keys().next().value;if(b===void 0)break;r.delete(b)}let i={...t,sessions:{...t.sessions,aliases:r}};const o=new Map(i.sessions.entities);let a;for(const[b,v]of o)b!==s&&P(i,b)===s&&(a=Wt(a,v,s),o.delete(b));const c=Wt(a,o.get(s),s);c&&o.set(s,c);for(const[b,v]of o){const M=v.parentSessionId?P(i,v.parentSessionId):void 0,_=v.forkedFromSessionId?P(i,v.forkedFromSessionId):void 0;(M!==v.parentSessionId||_!==v.forkedFromSessionId)&&o.set(b,{...v,parentSessionId:M,forkedFromSessionId:_})}const d=new Map(i.sessions.queries);for(const[b,v]of d){const M=Ee(i,v.ids);(M.length!==v.ids.length||M.some((_,G)=>_!==v.ids[G]))&&d.set(b,{...v,ids:M})}i={...i,sessions:{...i.sessions,entities:o,queries:d}};const h=gt(()=>[]),f=new Set;for(const b of fe)for(const v of Ee(i,i.inbox.tiers[b]))f.has(v)||(f.add(v),h[b].push(v));const m=new Map(i.projectQueues.byProject);for(const[b,v]of m){const M=Ue(i,v.items);M!==v.items&&m.set(b,{...v,items:M})}const p=Ue(i,i.projectQueues.globalItems),S=hn(i,i.projectQueues.recoveredSessionQueues),g=new Map(i.providerRuntime.bySessionId);let y=g.get(s);for(const[b,v]of g)b===s||P(i,b)!==s||((!y||v.observedAt>y.observedAt)&&(y={...v,sessionId:s}),g.delete(b));return y&&g.set(s,{...y,sessionId:s}),{...i,projectQueues:{...i.projectQueues,byProject:m,globalItems:p,recoveredSessionQueues:S},inbox:{...i.inbox,tiers:h},localDecorations:{...i.localDecorations,draftSessionIds:new Set(Ee(i,[...i.localDecorations.draftSessionIds]))},providerRuntime:{...i.providerRuntime,bySessionId:g}}}function yn(t,e,n=Date.now()){const s=new Set([...e].map(r=>P(t,r)));return kr(t.localDecorations.draftSessionIds,s)?t:{...t,localDecorations:{...t.localDecorations,draftSessionIds:s,draftObservedAt:n}}}function ri(t,e,n=Date.now()){return pn(t,e.sessionId,e.projectId,e.providerRuntimeStatus,n)}function ii(t,e,n=Date.now()){return e.providerRuntimeStatus===void 0?t:pn(t,e.sessionId,e.projectId,e.providerRuntimeStatus,n)}function bn(t,e,n=Date.now()){const s=W(n,"partial-event","session-created"),r=e.session;let i=Q(t,r.id);return i=pe(i,{title:r.title,fullTitle:r.fullTitle,createdAt:r.createdAt,updatedAt:r.updatedAt,messageCount:r.messageCount,provider:r.provider,model:r.model,initialPrompt:r.initialPrompt,lastAgentText:r.lastAgentText,lastHumanTurnAt:r.lastHumanTurnAt,asyncQuestions:r.asyncQuestions,providerChildren:r.providerChildren},s),i=ge(i,{customTitle:r.customTitle,nonHumanUserTurn:r.nonHumanUserTurn,isArchived:r.isArchived,isStarred:r.isStarred,clearloop:r.clearloop,parentSessionId:r.parentSessionId,parentSessionKind:r.parentSessionKind,forkedFromSessionId:r.forkedFromSessionId},s),i=bt(i,{projectId:r.projectId,projectName:r.projectName??i.projectName},s),i=ye(i,{ownership:r.ownership,activity:r.activity,pendingInputType:r.pendingInputType},s),i=We(i,r.hasUnread,s),B(t,{...i,eventCreatedAt:n,observedAt:Math.max(i.observedAt,n)})}function oi(t,e,n=Date.now()){const s=W(n,"partial-event","session-updated"),r=pe(Q(t,e.sessionId),{title:e.title,updatedAt:e.updatedAt,messageCount:e.messageCount,model:e.model,lastAgentText:e.lastAgentText,asyncQuestions:e.asyncQuestions},s);return B(t,r)}function vn(t,e,n=Date.now()){const s=W(n,"partial-event","metadata-changed"),r=ge(Q(t,e.sessionId),{customTitle:e.title,nonHumanUserTurn:e.nonHumanUserTurn,isArchived:e.archived,isStarred:e.starred,parentSessionId:e.parentSessionId,parentSessionKind:e.parentSessionKind,forkedFromSessionId:e.forkedFromSessionId,clearloop:e.clearloop},s),i=e.projectId!==void 0&&r.projectId!==void 0&&e.projectId!==r.projectId?{...r,projectName:void 0}:r,o=Se(i,{projectId:e.projectId},s);return B(t,o)}function ai(t,e,n=Date.now()){const s=W(n,"partial-event","session-status");let r=Q(t,e.sessionId);return r=bt(r,{projectId:e.projectId},s),r=ye(r,{ownership:e.ownership,activity:e.ownership.owner==="none"?"idle":r.activity,pendingInputType:r.pendingInputType},s),B(t,r)}function ci(t,e,n=Date.now()){const s=W(n,"partial-event","process-state");let r=Q(t,e.sessionId);return r=bt(r,{projectId:e.projectId},s),r=ye(r,{activity:e.activity,pendingInputType:e.pendingInputType},s),B(t,r)}function ui(t,e,n=Date.now()){const s=W(n,"partial-event","session-seen"),r=We(Q(t,e.sessionId),Us(e),s);return B(t,r)}const it=new Set;function In(t){for(const e of it)e(t)}function di(t){return it.add(t),()=>it.delete(t)}const le=1;function Ge(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function L(t){return typeof t=="string"&&t.trim()?t:null}function Xe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function li(t){if(!Ge(t))return null;const e=L(t.id),n=L(t.batchId),s=L(t.originalName),r=L(t.name),i=L(t.mimeType),o=L(t.createdAt),a=L(t.updatedAt),c=Xe(t.size);if(!e||!n||!s||!r||!i||!o||!a||c===void 0)return null;const d=Xe(t.width),h=Xe(t.height);return{id:e,batchId:n,originalName:s,name:r,size:c,mimeType:i,...d!==void 0?{width:d}:{},...h!==void 0?{height:h}:{},createdAt:o,updatedAt:a}}function hi(t){if(!Ge(t))return null;const e=L(t.batchId),n=L(t.updatedAt);if(!e||!n||!Array.isArray(t.refs))return null;const s=t.refs.map(li).filter(r=>r!==null);return s.length===0?null:{batchId:e,refs:s,updatedAt:n}}function fi(t){if(!Ge(t)||t.version!==le||typeof t.text!="string")return null;const e=hi(t.attachments);return{version:le,text:t.text,...e?{attachments:e}:{},...t.pendingSend===!0?{pendingSend:!0}:{}}}function mi(t){return/^\s*\{\s*"version"\s*:/.test(t)}function Y(t){if(!t)return{envelope:null,legacy:!1,invalidEnvelope:!1};try{const e=JSON.parse(t),n=fi(e);if(n)return{envelope:n,legacy:!1,invalidEnvelope:!1};if(Ge(e)&&"version"in e)return{envelope:null,legacy:!1,invalidEnvelope:!0}}catch{if(mi(t))return{envelope:null,legacy:!1,invalidEnvelope:!0}}return{envelope:{version:le,text:t},legacy:!0,invalidEnvelope:!1}}function Cn(t){var e;return!!(t&&(t.text.trim()||(((e=t.attachments)==null?void 0:e.refs.length)??0)>0))}function H(t){return Cn(Y(t).envelope)}function hc(t){var e;return((e=Y(t).envelope)==null?void 0:e.text)??""}function fc(t){var e;return((e=Y(t).envelope)==null?void 0:e.attachments)??null}function mc(t){var e;return((e=Y(t).envelope)==null?void 0:e.pendingSend)===!0}function vt(t){return Cn(t)?JSON.stringify(t):null}function pi(t,e){const n=Y(e).envelope;return vt({version:le,text:t,...n!=null&&n.attachments?{attachments:n.attachments}:{}})}function gi(t){const e=Y(t).envelope;return e!=null&&e.text.trim()?vt({...e,pendingSend:!0}):null}function Si(t,e){const n=Y(e).envelope,s=t&&t.refs.length>0?t:void 0;return vt({version:le,text:(n==null?void 0:n.text)??"",...s?{attachments:s}:{},...n!=null&&n.pendingSend?{pendingSend:!0}:{}})}const $e="draft-message-",ot="local",wn="draft-message:",It="draft-index-message:",Ct="draft-presence-message:";function X(t){return encodeURIComponent(t)}function wt({sourceKey:t,sessionId:e}){return t===ot?`${$e}${e}`:`${wn}${X(t)}:${X(e)}`}function Tn(t){return`${It}${X(t)}`}function yi({sourceKey:t,sessionId:e}){return`${Ct}${X(t)}:${X(e)}`}function bi(t){return!t||t.startsWith(It)?!1:!!(t.startsWith(Ct)||t.startsWith($e)||t.startsWith(wn))}function vi(t){try{const e=localStorage.getItem(Tn(t));if(!e)return new Set;const n=JSON.parse(e);return Array.isArray(n)?new Set(n.filter(s=>typeof s=="string")):new Set}catch{return new Set}}function Ii(t){const e=new Set;try{const n=`${Ct}${X(t)}:`;for(let s=0;s<localStorage.length;s+=1){const r=localStorage.key(s);if(!(r!=null&&r.startsWith(n)))continue;const i=r.slice(n.length);if(i)try{e.add(decodeURIComponent(i))}catch{}}}catch{}return e}function An(t,e){try{const n=yi(t);return localStorage.getItem(n)!==null===e?{changed:!1,synchronized:!0}:(e?localStorage.setItem(n,"1"):localStorage.removeItem(n),{changed:!0,synchronized:!0})}catch{return{changed:!1,synchronized:!1}}}function Tt(t,e){return An(t,H(e)).changed}function At(t,e){try{const n=wt(t),s=localStorage.getItem(n),r=e(s);r?localStorage.setItem(n,r):localStorage.removeItem(n),Tt(t,r);const i=H(s),o=H(r);i!==o&&In({storageKey:n,hasContent:o,sessionDraft:t})}catch{}}function pc(t,e){At(t,n=>pi(e,n))}function gc(t,e){At(t,n=>Si(e,n))}function Sc(t){At(t,e=>gi(e)??e)}function yc(t){try{const e=wt(t),n=localStorage.getItem(e);localStorage.removeItem(e),Tt(t,""),H(n)&&In({storageKey:e,hasContent:!1,sessionDraft:t})}catch{}}function Ci(t=ot){const e=new Set;try{const n=vi(t),s=Ii(t);for(const i of n)s.add(i);let r=!0;for(const i of s){const o=localStorage.getItem(wt({sourceKey:t,sessionId:i}));H(o)&&e.add(i);const a=An({sourceKey:t,sessionId:i},H(o)).synchronized;n.has(i)&&H(o)&&!a&&(r=!1)}if(n.size>0&&r&&localStorage.removeItem(Tn(t)),t!==ot)return e;for(let i=0;i<localStorage.length;i++){const o=localStorage.key(i);if(!(o!=null&&o.startsWith($e))||o.startsWith(It))continue;const a=localStorage.getItem(o);if(H(a)){const c=o.slice($e.length);e.add(c),Tt({sourceKey:t,sessionId:c},a)}}}catch{}return e}const Mn=T.createContext(null);function bc({children:t,runtime:e}){return us.jsx(Mn.Provider,{value:e,children:t})}function Mt(){return T.useContext(Mn)}function vc(t){return t}function Ic(t){return`host:${t}`}function Cc(t){return`direct:${t}`}const Pn="local",wi="remote:none",at=new Map,ct=new Set;let ut=Pn;const we=new Map,Te=new Map;function Ti(){return Vs(()=>ln())}function $(t){let e=at.get(t);return e||(e=Ti(),at.set(t,e)),e}function dt(){return ut}function Ai(t){return ct.add(t),()=>{ct.delete(t)}}function Pt(){return T.useSyncExternalStore(Ai,dt,dt)}function Mi(t){if(t!==ut){ut=t;for(const e of Array.from(ct))e()}}function j(){const t=Mt(),e=Pt();return T.useMemo(()=>(t==null?void 0:t.summary.getStore())??$(e),[t,e])}function Pi(t){const e=at.get(t);e==null||e.setState(ln(),!0)}function K(t,e){const n=t.getState(),s=e(n);s!==n&&t.setState(s,!0)}function E(t,e){K($(t),e)}function ji(t,e){E(t,n=>ci(n,e))}function Ri(t,e){E(t,n=>ai(n,e))}function xi(t,e){E(t,n=>ui(n,e))}function Ei(t,e){E(t,n=>oi(n,e))}function _i(t,e){E(t,n=>vn(n,e))}function Oi(t,e){E(t,n=>bn(n,e))}function ki(t,e){E(t,n=>si(n,e))}function Di(t,e){E(t,n=>ti(n,e))}function Ui(t,e){E(t,n=>ri(n,e))}function N(t,e,n){return sn.onSource(t,e,n)}function $i(t,e){return sn.retainSourceStream(t,e)}function Ni(t){return[N(t,"process-state-changed",e=>ji(t,e)),N(t,"provider-runtime-status-changed",e=>Ui(t,e)),N(t,"session-status-changed",e=>Ri(t,e)),N(t,"session-seen",e=>xi(t,e)),N(t,"session-updated",e=>Ei(t,e)),N(t,"session-metadata-changed",e=>_i(t,e)),N(t,"session-created",e=>Oi(t,e)),N(t,"session-id-remapped",e=>ki(t,e)),N(t,"project-queue-changed",e=>Di(t,e))]}function Fi(t,e){let n=we.get(t);n||(n={retainCount:0,unsubscribers:Ni(t)},we.set(t,n)),n.retainCount+=1;const s=e?$i(t,e):()=>{};let r=!1;return()=>{if(r)return;r=!0,s();const i=we.get(t);if(i&&(i.retainCount=Math.max(0,i.retainCount-1),i.retainCount===0)){for(const o of i.unsubscribers)o();we.delete(t)}}}function jn(t,e){return Fi(t,e)}function R(){const t=Mt(),e=Pt();T.useEffect(()=>t?t.summary.retainActivitySubscription():jn(e),[t,e])}function Li(t,e,n=Date.now()){E(t,s=>yn(s,e,n))}function Qi(t,e,n=Date.now()){E(t,s=>ii(s,e,n))}function Ht(t){Li(t,Ci(t))}function Bi(t){const e=t.sessionDraft;e&&E(e.sourceKey,n=>{const s=n.localDecorations.draftSessionIds;if(s.has(e.sessionId)===t.hasContent)return n;const r=new Set(s);return t.hasContent?r.add(e.sessionId):r.delete(e.sessionId),yn(n,r,Date.now())})}function Wi(t){if(Ht(t),typeof window>"u")return()=>{};const e=s=>{bi(s.key)&&Ht(t)};window.addEventListener("storage",e);const n=di(s=>{var r;((r=s.sessionDraft)==null?void 0:r.sourceKey)===t&&Bi(s)});return()=>{window.removeEventListener("storage",e),n()}}function Gi(t){let e=Te.get(t);e||(e={retainCount:0,release:Wi(t)},Te.set(t,e)),e.retainCount+=1;let n=!1;return()=>{if(n)return;n=!0;const s=Te.get(t);s&&(s.retainCount=Math.max(0,s.retainCount-1),s.retainCount===0&&(s.release(),Te.delete(t)))}}function Rn(t){return Gi(t)}function Hi(){const t=Mt(),e=Pt();T.useEffect(()=>t?t.summary.retainDraftDecorations():Rn(e),[t,e])}function Ji(t){return $(t).getState()}function Vi(t,e,n=Date.now()){K($(t),s=>Yr(s,e,n))}function qi(t,e,n=Date.now()){K($(t),s=>ni(s,e,n))}function zi(t,e,n=Date.now()){K($(t),s=>Kr(s,e,n))}function Yi(t,e,n=Date.now()){K($(t),s=>Xr(s,e,n))}function Ki(t,e,n=Date.now()){K($(t),s=>Zr(s,e,n))}function Xi(t,e,n=Date.now()){K($(t),s=>ei(s,e,n))}function wc(t,e,n=Date.now()){E(t,s=>zr(s,e,n))}function Zi(t,e,n=Date.now()){E(t,s=>bn(s,e,n))}function eo(t,e,n=Date.now()){E(t,s=>vn(s,e,n))}function He(){R();const t=j();return A(t)}function Tc(t){R();const e=j();return A(e,n=>Xs(n,t))}function Ac(t){R();const e=j();return A(e,n=>Zs(n,t))}function Mc(t){R();const e=j();return A(e,n=>tr(n,t))}function Pc(){const t=He();return T.useMemo(()=>nr(t),[t])}function jc(t){R();const e=j(),n=A(e,i=>i.projectQueues.byProject),s=t.join("\0"),r=T.useMemo(()=>s?s.split("\0"):[],[s]);return T.useMemo(()=>{const i=e.getState();return rr({...i,projectQueues:{...i.projectQueues,byProject:n}},r)},[e,n,r])}function Rc(t){R();const e=j(),n=A(e,i=>i.projectQueues),s=t.join("\0"),r=T.useMemo(()=>s?s.split("\0"):[],[s]);return T.useMemo(()=>ir({...e.getState(),projectQueues:n},r),[e,n,r])}function xc(){R();const t=j();return A(t,or)}function Ec(){R();const t=j();return A(t,ar)}function _c(){R();const t=j(),e=A(t,n=>n.projectQueues.projectStatusesByProject);return T.useMemo(()=>{const n=t.getState();return cr({...n,projectQueues:{...n.projectQueues,projectStatusesByProject:e}})},[t,e])}function Oc(t){R();const e=j(),n=A(e,i=>i.projectQueues.byProject),s=t.map(i=>`${i.id}:${i.projectQueueCount??0}:${i.snapshotObservedAt??""}`).join("\0"),r=T.useMemo(()=>t.map(i=>({id:i.id,projectQueueCount:i.projectQueueCount,snapshotObservedAt:i.snapshotObservedAt})),[t,s]);return T.useMemo(()=>{const i=e.getState();return ur({...i,projectQueues:{...i.projectQueues,byProject:n}},r)},[e,n,r])}function kc(){R();const t=j(),e=A(t,n=>n.projectQueues.byProject);return T.useMemo(()=>[...e.values()].flatMap(n=>n.items).sort((n,s)=>{const r=n.createdAt.localeCompare(s.createdAt);return r!==0?r:n.id.localeCompare(s.id)}),[e])}function Dc(t){R();const e=j(),n=A(e,i=>i.projectQueues.byProject),s=t.join("\0"),r=T.useMemo(()=>s?s.split("\0"):[],[s]);return T.useMemo(()=>{const i=e.getState();return dr({...i,projectQueues:{...i.projectQueues,byProject:n}},r)},[e,n,r])}function Uc(){Hi();const t=j();return A(t,lr)}function $c(){const t=He();return T.useMemo(()=>fr(t),[t])}function Nc(){R();const t=j(),e=A(t,r=>r.inbox.tiers.needsAttention.length),n=A(t,r=>r.inbox.tiers.active.length),s=A(t,r=>mr(r).total);return T.useMemo(()=>({needsAttention:e,active:n,total:s}),[e,n,s])}function Fc(){R();const t=j(),e=A(t,s=>s.inbox.tiers),n=A(t,s=>s.sessions.entities);return T.useMemo(()=>{const s=t.getState();return gr({...s,sessions:{...s.sessions,entities:n},inbox:{...s.inbox,tiers:e}})},[t,e,n])}function Lc(t){R();const e=j(),n=A(e,r=>r.inbox.tiers),s=A(e,r=>r.sessions.entities);return T.useMemo(()=>{const r=e.getState();return Sr({...r,sessions:{...r.sessions,entities:s},inbox:{...r.inbox,tiers:n}},t)},[e,n,s,t])}function Qc(){R();const t=j();return A(t,yr)}function Bc(){const t=He();return T.useMemo(()=>Cr(t),[t])}function Wc(t){const e=He(),n=Be(t);return T.useMemo(()=>Tr(e,t),[e,n,t])}function Gc(t){R();const e=j();return A(e,n=>er(n,t))}const Jt=new WeakMap,lt=6400,Ne=64;function to(t){try{const e=JSON.stringify(t);return e===void 0?lt:e.length*2+Ne}catch{return lt}}function no(t,e=!0){if(typeof t!="object"||t===null)return Ne;const n=Jt.get(t);if(n!==void 0)return n;if(!e)return lt;const s=to(t);return Jt.set(t,s),s}function Ze(t,e,n){if(n&&typeof t=="object"&&t!==null){if(n.has(t))return 0;n.add(t)}return no(t,e)}function xn(t,e={}){const n=e.measureUncached??!0,s=e.seen;let r=0;for(const i of t.messages)r+=Ze(i,n,s);for(const i of Object.values(t.agentContent)){r+=Ne;for(const o of i.messages)r+=Ze(o,n,s)}for(const i of Object.values(t.markdownAugments))r+=Ze(i,n,s);for(const[i,o]of t.toolUseToAgentEntries)r+=(i.length+o.length)*2+Ne;return r}function so(t){if(t.type!=="user")return!1;const e=t.tempId,n=t.messageMetadata;return typeof e=="string"||n!==void 0}function V(t){return(t._source??"sdk")!=="jsonl"&&so(t)}function ro(t){const e=t.tempId;return typeof e=="string"&&e?e:null}function io(t){const e=t.messageMetadata;if(!e||typeof e!="object")return null;const n=e.deliveryIntent;return typeof n=="string"?n:null}function Hc(t){return t.length>0&&t.every(n=>V(n))?"sent":"confirmed"}function Jc(t){if(t.length===0||!t.every(n=>V(n)))return null;let e=null;for(const n of t){if(io(n)!=="steer")return null;const s=ro(n);if(!s||(e??(e=s),s!==e))return null}return e}const oo=200,Vc=3e3;function qc(t){const e=Math.max(0,t.length-oo);for(let n=t.length-1;n>=e;n-=1){const s=t[n];if(s&&V(s))return!0}return!1}function zc(t){return t.hasUnconfirmedSelfSends||t.pendingSendCount>0}function I(t){return t.uuid??t.id??""}const ao=300*1e3,ht=60*1e3,Oe=60*ht,ke=24*Oe,co=7*ke;function Z(t){if(t==null)return null;const e=typeof t=="number"?t:new Date(t).getTime();return Number.isFinite(e)?e:null}function Yc(t){let e=null;for(const n of t){const s=Z(n.timestamp);s!==null&&(e=e===null?s:Math.max(e,s))}return e}function Kc(t){let e=null;for(const n of t){const s=Z(n.timestamp);s!==null&&(e=e===null?s:Math.min(e,s))}return e}function Xc(t,e,n=ao){return t!=null?e-t>=n:!1}function Zc(t,e){const n=Math.max(0,e-t);if(n<ht)return"now";if(n<Oe)return`${Math.floor(n/ht)}m`;if(n<ke)return`${Math.floor(n/Oe)}h`;if(n<co){const s=Math.floor(n/ke),r=Math.floor(n%ke/Oe);return r>0?`${s}d ${r}h`:`${s}d`}return new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function eu(t){return new Date(t).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function Je(t,e){const n=t.length-1,s=t[n];if(s&&I(s)===e)return n;for(let r=n-1;r>=0;r-=1){const i=t[r];if(i&&I(i)===e)return r}return-1}function Ve(t){var e;return t.content??((e=t.message)==null?void 0:e.content)}function uo(t){var n;const e=(n=t.message)==null?void 0:n.role;if(e==="user"||e==="assistant"||e==="system")return e;if(t.role==="user"||t.role==="assistant"||t.role==="system")return t.role}function Fe(t){if(t.parentUuid==null)return null;const e=t.type;return e!=="user"&&e!=="assistant"?null:`${t.parentUuid}:${e}:${uo(t)??""}`}function lo(t,e){const n=Fe(e);if(!n)return!1;const s=I(e);return t.some(r=>(r._source??"sdk")!=="jsonl"||I(r)===s?!1:Fe(r)===n)}function ho(t,e){const n=new Set;for(const r of e){const i=Fe(r);i&&n.add(i)}if(n.size===0)return t;const s=t.filter(r=>{if((r._source??"sdk")==="jsonl")return!0;const i=Fe(r);return i?!n.has(i):!0});return s.length===t.length?t:s}function ee(t,e,n){if(!t)return{...e,_source:n};const s=t._source??"sdk";if(n==="jsonl")return{...t,...e,_source:"jsonl"};if(s==="jsonl")return t;const r={...e,_source:"sdk"};return r.tempId===void 0&&t.tempId!==void 0&&(r.tempId=t.tempId),r.messageMetadata===void 0&&t.messageMetadata!==void 0&&(r.messageMetadata=t.messageMetadata),r}function fo(t,e){var c;if(e.length===0)return t;const n=new Map(e.map((d,h)=>[I(d),h]));let s=-1,r=t.length;const i=Z((c=e[0])==null?void 0:c.timestamp);for(let d=0;d<t.length;d+=1){const h=t[d];s=Math.max(s,n.get(I(h))??-1);const f=Z(h.timestamp);r===t.length&&i!==null&&f!==null&&f>i&&(r=d)}const o=[];let a=0;for(let d=0;d<=t.length;d+=1){s<0&&d===r&&(o.push(...e),a=e.length);const h=t[d];if(!h)break;const f=n.get(I(h));if(f===void 0){o.push(h);continue}const m=f===s?e.length:f+1;for(;a<m;)o.push(e[a++])}return o}function mo(t,e,n){const s=new Map(t.map(c=>[I(c),c]));for(const c of e){const d=I(c),h=s.get(d);s.set(d,ee(h,c,"jsonl"))}const r=[],i=new Set,o=n!=null&&n.preserveIncomingOrder?fo(t,e):[...t,...e];for(const c of o){const d=I(c);i.has(d)||(r.push(s.get(d)??c),i.add(d))}const a=ho(r,e);return n!=null&&n.skipDagOrdering?{messages:a}:{messages:Ns(a)}}function En(t,e){if(e.isReplay===!0&&lo(t,e))return{messages:t,index:-1};const n=I(e),s=Je(t,n);if(s>=0){const r=t[s],i=ee(r,e,"sdk");if(r===i||JSON.stringify(r)===JSON.stringify(i))return{messages:t,index:s};const o=[...t];return o[s]=i,{messages:o,index:s}}return{messages:[...t,{...e,_source:"sdk"}],index:t.length}}const _n=2e3,jt=2e3,Rt=3e4,xt=400,po=[`
1
+ var Xn=Object.defineProperty;var Zn=(t,e,n)=>e in t?Xn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var l=(t,e,n)=>Zn(t,typeof e!="symbol"?e+"":e,n);import{b$ as ze,bc as es,be as ts,c0 as ns,bf as ss,bj as rs,c1 as is,c2 as os,c3 as Ye,c4 as as,c5 as cs,c6 as Ut,c7 as Ce,j as us,r as T,f as sn,c8 as ds}from"./index-umZg0LZ6.js";import{T as ls,R as hs,g as fs,i as ms,h as ps,j as gs,f as Ss,B as Ke,k as ys}from"./RelayProtocol-BpdH0COG.js";const pt=64*1024,bs=512*1024,vs=256*1024,Is=16,Cs=2*1024*1024,$t=1;class D extends Error{constructor(e,n){super(e),this.code=n,this.name="UploadError"}}function ws(t){if(t.type==="complete"&&"file"in t)return t.file;throw new D("Upload completed without file metadata","UPLOAD_ERROR")}function Ts(t){if(t.type==="complete"&&"stagedRef"in t)return t.stagedRef;throw new D("Upload completed without staged attachment metadata","UPLOAD_ERROR")}function rn(t){return new Promise(e=>setTimeout(e,t))}async function As(t){if(!((t.bufferedAmount??0)<=bs)){for(;t.readyState===$t&&(t.bufferedAmount??0)>vs;)await rn(Is);if(t.readyState!==$t)throw new D("WebSocket not connected","WS_CLOSED")}}function Ms(t){const e=t===void 0?Cs:t;if(e<=0)return{waitAfterSend:async()=>{}};const n=Date.now();let s=0;return{async waitAfterSend(r){s+=r;const i=s/e*1e3,o=Date.now()-n,a=i-o;a>1&&await rn(a)}}}async function on(t,e,n,s={},r=a=>new WebSocket(a),i=()=>()=>{},o){const{onProgress:a,signal:c}=s,d=Ms(s.maxBytesPerSecond);console.log("[Upload] Starting upload to:",t);const h=i("upload");return new Promise((f,m)=>{if(c!=null&&c.aborted){m(new D("Upload aborted","ABORTED"));return}console.log("[Upload] Creating WebSocket connection...");const p=r(t);let S=!1,g=!1;function y(){c==null||c.removeEventListener("abort",b)}const b=()=>{if(g)return;g=!0,S=!0,y();const w={type:"cancel"};try{p.send(JSON.stringify(w))}catch{}p.close(1e3,"Aborted by user"),m(new D("Upload aborted","ABORTED"))};c==null||c.addEventListener("abort",b);const v=w=>{try{const O=JSON.parse(w.data);switch(O.type){case"progress":{a==null||a(O.bytesReceived);break}case"complete":{g=!0,y(),p.close(1e3,"Upload complete");try{f(o(O))}catch(Kn){m(Kn)}break}case"error":{g=!0,y(),p.close(1e3,"Error received"),m(new D(O.message,O.code));break}}}catch{}},M=w=>{console.error("[Upload] WebSocket error:",w),!g&&(g=!0,y(),m(new D("WebSocket error","WS_ERROR")))},_=w=>{console.log("[Upload] WebSocket closed:",w.code,w.reason),!g&&(y(),S||(g=!0,m(new D(w.reason||"Connection closed unexpectedly","WS_CLOSED"))))},G=async()=>{console.log("[Upload] WebSocket connection opened");try{const w={type:"start",...e.batchId!==void 0?{batchId:e.batchId}:{},name:e.name,size:e.size,mimeType:e.mimeType,...e.width!==void 0?{width:e.width}:{},...e.height!==void 0?{height:e.height}:{}};p.send(JSON.stringify(w));for await(const O of n){if(S)break;p.send(O),await As(p),await d.waitAfterSend(O.length)}if(!S){const O={type:"end"};p.send(JSON.stringify(O))}}catch(w){if(g)return;g=!0,y(),p.close(1e3,"Error during upload"),m(w instanceof D?w:new D(w instanceof Error?w.message:"Upload failed","UPLOAD_ERROR"))}};p.addEventListener("open",G),p.addEventListener("message",v),p.addEventListener("error",M),p.addEventListener("close",_)}).finally(h)}async function Ps(t,e,n,s={},r=o=>new WebSocket(o),i){return on(t,e,n,s,r,i,ws)}async function js(t,e,n,s={},r=o=>new WebSocket(o),i){return on(t,e,n,s,r,i,Ts)}async function*an(t,e=pt){let n=0;for(;n<t.size;){const r=await t.slice(n,n+e).arrayBuffer();yield new Uint8Array(r),n+=e}}function Rs(t,e,n){const s=window.location.protocol==="https:"?"wss:":"ws:",r=window.location.host;return`${s}//${r}/api/projects/${t}/sessions/${e}/upload/ws`}function xs(t){const e=window.location.protocol==="https:"?"wss:":"ws:",n=window.location.host;return`${e}//${n}/api/attachments/staging/drafts/upload/ws`}async function Es(t,e,n,s={},r={}){var h,f;const{chunkSize:i=pt,...o}=s,a=Rs(t,e),c={name:n.name,size:n.size,mimeType:n.type||"application/octet-stream",...((h=s.imageDimensions)==null?void 0:h.width)!==void 0?{width:s.imageDimensions.width}:{},...((f=s.imageDimensions)==null?void 0:f.height)!==void 0?{height:s.imageDimensions.height}:{}},d=an(n,i);return Ps(a,c,d,o,r.createWebSocket,r.beginCriticalOperation)}async function _s(t,e={},n={}){var d,h;const{chunkSize:s=pt,batchId:r,...i}=e,o=xs(),a={...r!==void 0?{batchId:r}:{},name:t.name,size:t.size,mimeType:t.type||"application/octet-stream",...((d=e.imageDimensions)==null?void 0:d.width)!==void 0?{width:e.imageDimensions.width}:{},...((h=e.imageDimensions)==null?void 0:h.height)!==void 0?{height:e.imageDimensions.height}:{}},c=an(t,s);return js(o,a,c,i,n.createWebSocket,n.beginCriticalOperation)}const q={baseDelayMs:1e3,maxDelayMs:3e4,maxAttempts:10,jitterFactor:.3,staleThresholdMs:45e3,staleCheckIntervalMs:1e4,pongTimeoutMs:2e3},Os={setTimeout:(t,e)=>window.setTimeout(t,e),clearTimeout:t=>window.clearTimeout(t),setInterval:(t,e)=>window.setInterval(t,e),clearInterval:t=>window.clearInterval(t),now:()=>Date.now()},ks={isVisible:()=>typeof document<"u"&&!document.hidden,onVisibilityChange(t){if(typeof document>"u")return()=>{};const e=()=>t(!document.hidden);return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}};class cn{constructor(e={}){l(this,"_state","disconnected");l(this,"_reconnectAttempts",0);l(this,"_reconnectFn",null);l(this,"_sendPing",null);l(this,"_label",null);l(this,"_driveReconnect",!0);l(this,"_started",!1);l(this,"_lastEventTime",0);l(this,"_hasReceivedHeartbeat",!1);l(this,"_staleCheckIntervalId",null);l(this,"_hiddenSince",null);l(this,"_removeVisibilityListener",null);l(this,"_pendingPingId",null);l(this,"_pongTimeoutId",null);l(this,"_pingCounter",0);l(this,"_backoffTimerId",null);l(this,"_reconnectPromise",null);l(this,"_criticalOperationDepth",0);l(this,"_listeners",{stateChange:new Set,reconnectFailed:new Set,visibilityRestored:new Set});l(this,"config");l(this,"timers");l(this,"visibility");this.config={baseDelayMs:e.baseDelayMs??q.baseDelayMs,maxDelayMs:e.maxDelayMs??q.maxDelayMs,maxAttempts:e.maxAttempts??q.maxAttempts,jitterFactor:e.jitterFactor??q.jitterFactor,staleThresholdMs:e.staleThresholdMs??q.staleThresholdMs,staleCheckIntervalMs:e.staleCheckIntervalMs??q.staleCheckIntervalMs,pongTimeoutMs:e.pongTimeoutMs??q.pongTimeoutMs},this.timers=e.timers??Os,this.visibility=e.visibility??ks}get state(){return this._state}get reconnectAttempts(){return this._reconnectAttempts}start(e,n){this._reconnectFn=e,this._sendPing=(n==null?void 0:n.sendPing)??null,this._label=(n==null?void 0:n.label)??null,this._driveReconnect=(n==null?void 0:n.driveReconnect)??!0,!this._started&&(this._started=!0,this._setState("connected"),this._startStaleCheck(),this._startVisibilityListener())}stop(){this._started=!1,this._reconnectFn=null,this._sendPing=null,this._label=null,this._driveReconnect=!0,this._stopStaleCheck(),this._stopVisibilityListener(),this._cancelBackoff(),this._cancelPongTimeout(),this._reconnectPromise=null,this._hasReceivedHeartbeat=!1,this._hiddenSince=null,this._setState("disconnected")}recordEvent(){this._lastEventTime=this.timers.now()}recordHeartbeat(){this._hasReceivedHeartbeat=!0,this._lastEventTime=this.timers.now()}beginCriticalOperation(e){this._criticalOperationDepth+=1,this._pendingPingId=null,this._cancelPongTimeout(),this._log(`critical operation started${e?`: ${e}`:""} (depth=${this._criticalOperationDepth})`);let n=!1;return()=>{n||(n=!0,this._criticalOperationDepth=Math.max(0,this._criticalOperationDepth-1),this._log(`critical operation ended${e?`: ${e}`:""} (depth=${this._criticalOperationDepth})`))}}markConnected(){this._started&&(this._reconnectAttempts=0,this._reconnectPromise=null,this._cancelBackoff(),this._setState("connected"))}receivePong(e){e===this._pendingPingId&&(this._cancelPongTimeout(),this._pendingPingId=null,this._log("pong received, connection verified"))}handleError(e){const n=!ze(e);if(this._log(`error: ${e.message}, retryable=${n}`),this._state!=="reconnecting"){if(!n){this._setState("disconnected",`error: ${e.message}`),this._emitReconnectFailed(e);return}this._startReconnecting(`error: ${e.message}`)}}handleClose(e){const n=!e||!ze(e),s=(e==null?void 0:e.message)??"no error";if(this._log(`close: ${s}, retryable=${n}`),this._state!=="reconnecting"){if(e&&!n){this._setState("disconnected",`close: ${s}`),this._emitReconnectFailed(e);return}this._startReconnecting(`close: ${s}`)}}forceReconnect(e){if(this._shouldSuppressHealthReconnect(e)){this._log(`suppressing health reconnect during critical operation: ${e}`);return}this._log(`force reconnect${e?`: ${e}`:""}`),this._reconnectAttempts=0,this._cancelBackoff(),this._reconnectPromise=null,this._startReconnecting(e??"force")}on(e,n){const s=this._listeners[e];return s.add(n),()=>{s.delete(n)}}_log(e){const n=this._label?`[ConnectionManager:${this._label}]`:"[ConnectionManager]";console.log(`${n} ${e}`)}_setState(e,n){if(e===this._state)return;const s=this._state;this._state=e;const r=n?` (${n})`:"";this._log(`${s} → ${e}${r}`);for(const i of this._listeners.stateChange)i(e,s)}_emitReconnectFailed(e){for(const n of this._listeners.reconnectFailed)n(e)}_emitVisibilityRestored(){for(const e of this._listeners.visibilityRestored)e()}_startReconnecting(e){this._cancelPongTimeout(),this._pendingPingId=null,this._setState("reconnecting",e),this._scheduleReconnect()}_scheduleReconnect(){if(!this._started||!this._reconnectFn)return;if(!this._driveReconnect){this._log("passive manager observing reconnect state");return}if(this._reconnectAttempts>=this.config.maxAttempts){this._setState("disconnected"),this._emitReconnectFailed(new Error(`Reconnection failed after ${this.config.maxAttempts} attempts`));return}const e=this._getBackoffDelay(this._reconnectAttempts);this._reconnectAttempts++,this._log(`attempt ${this._reconnectAttempts}/${this.config.maxAttempts}, delay ${Math.round(e)}ms`),this._backoffTimerId=this.timers.setTimeout(()=>{this._backoffTimerId=null,this._executeReconnect()},e)}_executeReconnect(){if(!this._started||!this._reconnectFn||this._reconnectPromise)return;const e=this._reconnectFn,n=e();this._reconnectPromise=n,n.then(()=>{this._reconnectPromise===n&&this.markConnected()}).catch(s=>{if(this._reconnectPromise!==n)return;this._reconnectPromise=null;const r=s instanceof Error?s:new Error(String(s));if(this._log(`reconnect failed: ${r.message}`),ze(r)){this._setState("disconnected"),this._emitReconnectFailed(r);return}this._scheduleReconnect()})}_getBackoffDelay(e){const n=this.config.baseDelayMs*2**e,s=1+Math.random()*this.config.jitterFactor;return Math.min(this.config.maxDelayMs,n*s)}_cancelBackoff(){this._backoffTimerId!==null&&(this.timers.clearTimeout(this._backoffTimerId),this._backoffTimerId=null)}_startStaleCheck(){this._stopStaleCheck(),this._lastEventTime=this.timers.now(),this._staleCheckIntervalId=this.timers.setInterval(()=>{this._checkStale()},this.config.staleCheckIntervalMs)}_stopStaleCheck(){this._staleCheckIntervalId!==null&&(this.timers.clearInterval(this._staleCheckIntervalId),this._staleCheckIntervalId=null)}_checkStale(){if(this._state!=="connected"||!this._hasReceivedHeartbeat||this._criticalOperationDepth>0)return;const e=this.timers.now()-this._lastEventTime;e>=this.config.staleThresholdMs&&(this._log(`stale (${e}ms since last event)`),this.forceReconnect("stale"))}_startVisibilityListener(){this._removeVisibilityListener=this.visibility.onVisibilityChange(e=>{e?this._handleBecameVisible():(this._hiddenSince=this.timers.now(),this._log(`visibility hidden (${this._formatReconnectContext()})`))})}_stopVisibilityListener(){this._removeVisibilityListener&&(this._removeVisibilityListener(),this._removeVisibilityListener=null)}_handleBecameVisible(){const e=this._hiddenSince!==null?this.timers.now()-this._hiddenSince:null,n=`visibility visible${e!=null?` after ${e}ms hidden`:""}`;if(this._state!=="connected"){const r=this._formatReconnectContext();this._log(`${n}, keeping existing reconnect cycle (${r})`);return}if(this._hiddenSince=null,this._emitVisibilityRestored(),!this._sendPing){const r=this._formatReconnectContext();this._log(`${n}, no ping function (${r})`);return}if(this._criticalOperationDepth>0){const r=this._formatReconnectContext();this._log(`${n}, skipping ping during critical operation (${r})`);return}this._cancelPongTimeout();const s=String(++this._pingCounter);this._pendingPingId=s,this._log(`${n}, pinging (${this._formatReconnectContext()})`);try{this._sendPing(s)}catch{this._pendingPingId=null,this._log("ping send failed"),this.forceReconnect("ping-failed");return}this._pongTimeoutId=this.timers.setTimeout(()=>{this._pongTimeoutId=null,this._pendingPingId===s&&(this._log("pong timeout"),this._pendingPingId=null,this.forceReconnect("pong-timeout"))},this.config.pongTimeoutMs)}_cancelPongTimeout(){this._pongTimeoutId!==null&&(this.timers.clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null)}_shouldSuppressHealthReconnect(e){return this._criticalOperationDepth>0&&(e==="stale"||e==="ping-failed"||e==="pong-timeout")}_formatReconnectContext(){const e=[`state=${this._state}`];return this._reconnectAttempts>0&&e.push(`attempts=${this._reconnectAttempts}`),this._backoffTimerId!==null&&e.push("backoff=pending"),this._reconnectPromise&&e.push("reconnect=in-flight"),this._pendingPingId&&e.push(`pendingPing=${this._pendingPingId}`),this._criticalOperationDepth>0&&e.push(`criticalDepth=${this._criticalOperationDepth}`),e.join(", ")}}const Ds="";function Us(t){return t.timestamp===Ds}function ce(t){return t.uuid??t.id??""}function $s(t){const e=new Set;for(const s of t)e.add(ce(s));const n=new Set;for(const s of t){if(s.parentUuid&&e.has(s.parentUuid)&&!n.has(s.parentUuid))return!0;n.add(ce(s))}return!1}function Ns(t){if(t.length<=1||!$s(t))return t;const e=new Set;for(const o of t)e.add(ce(o));const n=[],s=new Set,r=new Map,i=o=>{const a=ce(o);if(a){if(s.has(a))return;s.add(a)}if(n.push(o),!a)return;const c=r.get(a);if(c){r.delete(a);for(const d of c)i(d)}};for(const o of t){const a=o.parentUuid;if(a&&e.has(a)&&!s.has(a)){const c=r.get(a)??[];c.push(o),r.set(a,c);continue}i(o)}if(r.size>0)for(const o of t){const a=ce(o);a&&!s.has(a)&&i(o)}return n}const un="_codexToolCorrelation";function st(t){if(!t||typeof t!="object")return null;const e=t[un];if(!e||typeof e!="object")return null;const n=e,s=n.origin;return s!=="command_execution"&&s!=="custom_tool_call"&&s!=="function_call"&&s!=="image_view"&&s!=="plan_update"||typeof n.turnId!="string"||typeof n.itemId!="string"?null:{origin:s,turnId:n.turnId,itemId:n.itemId,...typeof n.startedAt=="string"?{startedAt:n.startedAt}:{},...typeof n.durableCallId=="string"?{durableCallId:n.durableCallId}:{},...typeof n.liveItemId=="string"?{liveItemId:n.liveItemId}:{}}}class Fs{constructor(e={}){l(this,"mode","direct");l(this,"ws",null);l(this,"connectionPromise",null);l(this,"protocol");l(this,"options");l(this,"inboundChunks",new ls);l(this,"externalOnPong");this.options=e,this.protocol=new hs({sendMessage:n=>this.send(n),sendUploadChunk:(n,s,r)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");this.ws.send(fs(n,s,r))},ensureConnected:()=>this.ensureConnected(),isConnected:()=>{var n;return((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN}},{logPrefix:"[WebSocketConnection]"}),this.setConnectionManager(e.connectionManager??null)}setConnectionManager(e){this.options.connectionManager=e??void 0,this.updateProtocolPongHandler(),this.protocol.setOnInboundEvent(e?n=>{n.eventType==="heartbeat"?e.recordHeartbeat():e.recordEvent()}:void 0),this.protocol.setBeginCriticalOperation(e?n=>e.beginCriticalOperation(n):void 0)}getWsUrl(){const n=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`,s=ns();return s?`${n}?desktop_token=${encodeURIComponent(s)}`:n}async ensureConnected(){var e;if(((e=this.ws)==null?void 0:e.readyState)!==WebSocket.OPEN){if(this.connectionPromise)return this.connectionPromise;this.connectionPromise=this.connect();try{await this.connectionPromise}finally{this.connectionPromise=null}}}connect(){return new Promise((e,n)=>{var o,a;const s=this.getWsUrl();console.log("[WebSocketConnection] Connecting to",s),(a=(o=this.options).onSocketStateChange)==null||a.call(o,"connecting");const r=this.options.createWebSocket?this.options.createWebSocket(s):new WebSocket(s);r.binaryType="arraybuffer",r.onerror=c=>{console.error("[WebSocketConnection] Error:",c)},r.onclose=c=>{var h,f,m;console.log("[WebSocketConnection] Closed:",c.code,c.reason),this.ws=null,this.inboundChunks.reset();const d=new es(c.code,c.reason);this.protocol.rejectAllPending(d),this.protocol.notifySubscriptionsClosed(d),(f=(h=this.options).onSocketStateChange)==null||f.call(h,"disconnected"),(m=this.options.connectionManager)==null||m.handleClose(d)},r.onmessage=c=>{this.handleMessage(c.data)};const i=setTimeout(()=>{r.readyState!==WebSocket.OPEN&&(r.close(),n(new Error("WebSocket connection timeout")))},1e4);r.onopen=()=>{var c,d,h;clearTimeout(i),console.log("[WebSocketConnection] Connected"),this.ws=r,this.sendCapabilities(),(c=this.options.connectionManager)==null||c.markConnected(),(h=(d=this.options).onSocketStateChange)==null||h.call(d,"connected"),e()}})}handleMessage(e){var s,r;let n;if(ms(e))try{const i=this.inboundChunks.acceptFrame(e);if(!i)return;n=ps(i)}catch(i){i instanceof gs?console.warn(`[WebSocketConnection] Binary frame error (${i.code}):`,i.message):console.warn("[WebSocketConnection] Failed to decode binary frame:",i),i instanceof Ss&&((s=this.ws)==null||s.close(1002,"Invalid transport chunk sequence"));return}else if(typeof e=="string"){if(this.inboundChunks.hasPendingMessage){this.inboundChunks.reset(),(r=this.ws)==null||r.close(1002,"Transport chunk sequence interrupted");return}try{n=JSON.parse(e)}catch{console.warn("[WebSocketConnection] Failed to parse message:",e);return}}else{console.warn("[WebSocketConnection] Ignoring unknown message type");return}this.protocol.routeMessage(n)}sendCapabilities(){const e={type:"client_capabilities",version:ss(),capabilityBits:[],formats:[Ke.JSON,Ke.BINARY_UPLOAD,Ke.TRANSPORT_CHUNK]};this.send(e)}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");this.ws.send(ys(e))}async fetch(e,n){return this.protocol.fetch(e,n)}async fetchBlob(e){return this.protocol.fetchBlob(e)}async fetchResponse(e,n){return this.protocol.fetchResponse(e,n)}subscribeSession(e,n,s,r){return this.protocol.subscribeSession(e,n,s,r)}subscribeActivity(e){return this.protocol.subscribeActivity(e)}subscribeGlossary(e,n){return this.protocol.subscribeGlossary(e,n)}subscribeWorktree(e,n,s){return this.protocol.subscribeWorktree(e,n,s)}subscribeSessionWatch(e,n,s){return this.protocol.subscribeSessionWatch(e,n,s)}async upload(e,n,s,r){return this.protocol.upload(e,n,s,r)}async uploadStagedAttachment(e,n){return this.protocol.uploadStagedAttachment(e,n)}sendPing(e){this.protocol.sendPing(e)}setOnPong(e){this.externalOnPong=e,this.updateProtocolPongHandler()}updateProtocolPongHandler(){const e=this.options.connectionManager,n=this.externalOnPong;this.protocol.setOnPong(e||n?s=>{e==null||e.receivePong(s),n==null||n(s)}:void 0)}async reconnect(){const e=new ts;this.protocol.rejectAllPending(e),this.protocol.notifySubscriptionsClosed(e),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null,this.inboundChunks.reset()),this.connectionPromise=null,await this.ensureConnected()}sendMessage(e){this.send(e)}onDeviceMessage(e){return this.protocol.onDeviceMessage(e)}close(){var e,n;this.protocol.close(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.onopen=null,this.ws.close(),this.ws=null,this.inboundChunks.reset()),(n=(e=this.options).onSocketStateChange)==null||n.call(e,"disconnected")}}function Ls(t){const e=t.split("?",1)[0]??"";return e==="/local-image"||e==="/local-file"||/^\/projects\/[^/]+\/files\/raw$/.test(e)}class Qs{constructor(e){l(this,"listeners",new Set);l(this,"visibilityRestoredListeners",new Set);this.getSnapshotFn=e}getSnapshot(){return this.getSnapshotFn()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}subscribeVisibilityRestored(e){return this.visibilityRestoredListeners.add(e),()=>{this.visibilityRestoredListeners.delete(e)}}emit(){const e=[...this.listeners];for(const n of e)n()}emitVisibilityRestored(){const e=[...this.visibilityRestoredListeners];for(const n of e)n()}}class Bs{constructor(e={}){l(this,"kind","localhost");l(this,"capabilities",{sameOriginUrls:!0,device:{send:async e=>{this.assertNotDisposed(),await this.streamConnection.ensureConnected(),this.streamConnection.sendMessage(e)},onMessage:e=>this.streamConnection.onDeviceMessage(e)}});l(this,"status");l(this,"streamManager");l(this,"streamConnection");l(this,"mutableStatus");l(this,"uploadWebSocketFactory");l(this,"streamManagerStarted",!1);l(this,"streamSocketState","idle");l(this,"uploadSocketStates",new Map);l(this,"activeStreamSubscriptions",0);l(this,"activeUploads",0);l(this,"lastStreamError");l(this,"disposed",!1);l(this,"removeManagerStateListener",null);l(this,"removeManagerFailureListener",null);l(this,"removeManagerVisibilityListener",null);this.streamManager=new cn(e.connectionManagerConfig),this.uploadWebSocketFactory=e.uploadWebSocketFactory,this.streamConnection=new Fs({createWebSocket:e.streamWebSocketFactory,connectionManager:this.streamManager,onSocketStateChange:n=>this.handleStreamSocketState(n)}),this.mutableStatus=new Qs(()=>this.createSnapshot()),this.status=this.mutableStatus}fetch(e,n){return this.assertNotDisposed(),rs(e,n)}fetchBlob(e){return this.assertNotDisposed(),is(e,Ls(e)?{cache:"no-cache"}:void 0)}fetchResponse(e,n){return this.assertNotDisposed(),os(e,n)}upload(e,n,s,r){return this.assertNotDisposed(),this.withUploadChannel(i=>Es(e,n,s,r,{createWebSocket:i,beginCriticalOperation:o=>this.streamManager.beginCriticalOperation(o)}))}uploadStagedAttachment(e,n){return this.assertNotDisposed(),this.withUploadChannel(s=>_s(e,n,{createWebSocket:s,beginCriticalOperation:r=>this.streamManager.beginCriticalOperation(r)}))}subscribeSession(e,n,s,r){return this.trackStreamSubscription(i=>this.streamConnection.subscribeSession(e,i,s,r))(n)}subscribeSessionWatch(e,n,s){return this.trackStreamSubscription(r=>this.streamConnection.subscribeSessionWatch(e,r,s))(n)}subscribeActivity(e){return this.trackStreamSubscription(n=>this.streamConnection.subscribeActivity(n))(e)}subscribeGlossary(e,n){return this.trackStreamSubscription(s=>this.streamConnection.subscribeGlossary(e,s))(n)}subscribeWorktree(e,n,s){return this.trackStreamSubscription(r=>this.streamConnection.subscribeWorktree(e,n,r))(s)}async reconnect(){this.assertNotDisposed()}dispose(){var e,n,s;this.disposed||(this.disposed=!0,(e=this.removeManagerStateListener)==null||e.call(this),(n=this.removeManagerFailureListener)==null||n.call(this),(s=this.removeManagerVisibilityListener)==null||s.call(this),this.removeManagerStateListener=null,this.removeManagerFailureListener=null,this.removeManagerVisibilityListener=null,this.streamManager.stop(),this.streamConnection.close(),this.streamSocketState="disconnected",this.mutableStatus.emit())}handleStreamSocketState(e){this.disposed||(this.streamSocketState=e==="connected"?"connected":e,e==="connected"&&(this.lastStreamError=void 0,this.startStreamManager()),this.mutableStatus.emit())}startStreamManager(){if(this.streamManagerStarted){this.streamManager.markConnected();return}this.streamManagerStarted=!0,this.removeManagerStateListener=this.streamManager.on("stateChange",()=>this.mutableStatus.emit()),this.removeManagerFailureListener=this.streamManager.on("reconnectFailed",e=>{this.lastStreamError=e.message,this.mutableStatus.emit()}),this.removeManagerVisibilityListener=this.streamManager.on("visibilityRestored",()=>this.mutableStatus.emitVisibilityRestored()),this.streamManager.start(()=>this.streamConnection.reconnect(),{sendPing:e=>this.streamConnection.sendPing(e),label:"localhost-stream"})}trackStreamSubscription(e){return n=>{this.assertNotDisposed(),this.activeStreamSubscriptions+=1,this.mutableStatus.emit();let s=!1;const r=()=>{s||(s=!0,this.activeStreamSubscriptions=Math.max(0,this.activeStreamSubscriptions-1),this.mutableStatus.emit())},o=e({onEvent:(a,c,d)=>{a==="heartbeat"?this.streamManager.recordHeartbeat():this.streamManager.recordEvent(),n.onEvent(a,c,d)},onOpen:()=>{var a;this.startStreamManager(),this.streamManager.markConnected(),(a=n.onOpen)==null||a.call(n)},onError:a=>{var c;this.lastStreamError=a.message,this.streamManager.handleError(a),r(),(c=n.onError)==null||c.call(n,a)},onClose:a=>{var c;a&&(this.lastStreamError=a.message,this.streamManager.handleClose(a)),r(),(c=n.onClose)==null||c.call(n,a)}});return{close:()=>o.close()}}}async withUploadChannel(e){this.activeUploads+=1,this.mutableStatus.emit();const n=[],s=r=>{const i=this.uploadWebSocketFactory?this.uploadWebSocketFactory(r):new WebSocket(r);return n.push(this.trackUploadSocket(i)),i};try{return await e(s)}finally{for(const r of n)r();this.activeUploads=Math.max(0,this.activeUploads-1),this.mutableStatus.emit()}}trackUploadSocket(e){const n=o=>{this.uploadSocketStates.has(e)&&(this.uploadSocketStates.set(e,o),this.mutableStatus.emit())},s=()=>n("connected"),r=()=>n("disconnected"),i=()=>n("disconnected");return this.uploadSocketStates.set(e,e.readyState===WebSocket.OPEN?"connected":"connecting"),e.addEventListener("open",s),e.addEventListener("close",r),e.addEventListener("error",i),this.mutableStatus.emit(),()=>{e.removeEventListener("open",s),e.removeEventListener("close",r),e.removeEventListener("error",i),this.uploadSocketStates.delete(e),this.mutableStatus.emit()}}createSnapshot(){const e=[{name:"same-origin-http",state:"stateless"},{name:"stream-websocket",state:this.getStreamChannelState(),activeSubscriptions:this.activeStreamSubscriptions,...this.streamManager.reconnectAttempts>0?{reconnectAttempts:this.streamManager.reconnectAttempts}:{},...this.lastStreamError?{lastError:this.lastStreamError}:{}}];return this.activeUploads>0&&e.push({name:"upload-websocket",state:this.getUploadChannelState(),activeSubscriptions:this.activeUploads}),{kind:this.kind,state:"ready",channels:e}}getStreamChannelState(){if(this.disposed)return"disconnected";if(!this.streamManagerStarted)return this.streamSocketState;switch(this.streamManager.state){case"connected":return"connected";case"reconnecting":return"reconnecting";case"disconnected":return this.streamSocketState==="connecting"?"connecting":"disconnected"}}getUploadChannelState(){if(this.uploadSocketStates.size===0)return"connecting";let e=!1;for(const n of this.uploadSocketStates.values()){if(n==="connected")return"connected";n==="connecting"&&(e=!0)}return e?"connecting":"disconnected"}assertNotDisposed(){if(this.disposed)throw new Error("LocalhostSourceTransport has been disposed")}}const Ws=15e3;class Gs{constructor(e){l(this,"listeners",new Set);l(this,"visibilityRestoredListeners",new Set);this.getSnapshotFn=e}getSnapshot(){return this.getSnapshotFn()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}subscribeVisibilityRestored(e){return this.visibilityRestoredListeners.add(e),()=>{this.visibilityRestoredListeners.delete(e)}}emit(){const e=[...this.listeners];for(const n of e)n()}emitVisibilityRestored(){const e=[...this.visibilityRestoredListeners];for(const n of e)n()}}class dn{constructor(e,n={}){l(this,"kind");l(this,"status");l(this,"capabilities");l(this,"channelName");l(this,"managerLabel");l(this,"readyTimeoutMs");l(this,"manager");l(this,"mutableStatus");l(this,"reconnectConnection");l(this,"connection",null);l(this,"slotState","detached");l(this,"activeSubscriptions",0);l(this,"lastError");l(this,"disposed",!1);l(this,"removeManagerStateListener",null);l(this,"removeManagerFailureListener",null);l(this,"removeManagerVisibilityListener",null);l(this,"attachWaiters",new Set);l(this,"deviceHandlers",new Set);l(this,"deviceUnsubscribers",new Map);this.kind=e.kind,this.channelName=e.channelName,this.managerLabel=e.managerLabel,this.readyTimeoutMs=n.readyTimeoutMs??Ws,this.manager=new cn(n.connectionManagerConfig),this.reconnectConnection=e.reconnect,this.mutableStatus=new Gs(()=>this.createSnapshot()),this.status=this.mutableStatus,this.capabilities={sameOriginUrls:e.sameOriginUrls,...e.device?{device:{send:s=>this.sendDeviceMessage(s),onMessage:s=>this.addDeviceHandler(s)}}:{},...e.speech?{speech:{open:()=>this.openSpeechSocket()}}:{}},this.removeManagerStateListener=this.manager.on("stateChange",()=>{this.mutableStatus.emit()}),this.removeManagerFailureListener=this.manager.on("reconnectFailed",s=>{this.lastError=s.message,this.mutableStatus.emit()}),this.removeManagerVisibilityListener=this.manager.on("visibilityRestored",()=>this.mutableStatus.emitVisibilityRestored())}attach(e,n={}){var s,r,i;this.assertNotDisposed(),this.connection&&this.connection!==e?((r=(s=this.connection).setConnectionManager)==null||r.call(s,null),this.detachDeviceHandlers(),this.manager.stop()):this.connection===e&&this.detachDeviceHandlers(),this.connection=e,this.slotState=n.state??"ready",(i=e.setConnectionManager)==null||i.call(e,this.manager),this.startPassiveManager(),this.attachDeviceHandlers(),this.resolveAttachWaiters(e),this.mutableStatus.emit()}detach(){var e,n;this.disposed||((n=(e=this.connection)==null?void 0:e.setConnectionManager)==null||n.call(e,null),this.detachDeviceHandlers(),this.connection=null,this.slotState="detached",this.manager.stop(),this.mutableStatus.emit())}fetch(e,n){return this.assertNotDisposed(),this.withConnection(s=>s.fetch(e,n))}fetchBlob(e){return this.assertNotDisposed(),this.withConnection(n=>n.fetchBlob(e))}fetchResponse(e,n){return this.assertNotDisposed(),this.withConnection(s=>s.fetchResponse(e,n))}upload(e,n,s,r){return this.assertNotDisposed(),this.withConnection(i=>i.upload(e,n,s,r))}uploadStagedAttachment(e,n){return this.assertNotDisposed(),this.withConnection(s=>s.uploadStagedAttachment(e,n))}subscribeSession(e,n,s,r){return this.subscribeNow(n,(i,o)=>i.subscribeSession(e,o,s,r))}subscribeSessionWatch(e,n,s){return this.subscribeNow(n,(r,i)=>r.subscribeSessionWatch(e,i,s))}subscribeActivity(e){return this.subscribeNow(e,(n,s)=>n.subscribeActivity(s))}subscribeGlossary(e,n){return this.subscribeNow(n,(s,r)=>s.subscribeGlossary(e,r))}subscribeWorktree(e,n,s){return this.subscribeNow(s,(r,i)=>r.subscribeWorktree(e,n,i))}async reconnect(){this.assertNotDisposed();const e=await this.waitForConnection();this.slotState="connecting",this.mutableStatus.emit(),await this.reconnectConnection(e),this.slotState="ready",this.manager.markConnected(),this.mutableStatus.emit()}dispose(){var e,n,s,r,i,o;this.disposed||(this.disposed=!0,this.rejectAttachWaiters(new Ye(this.kind)),(e=this.removeManagerStateListener)==null||e.call(this),(n=this.removeManagerFailureListener)==null||n.call(this),(s=this.removeManagerVisibilityListener)==null||s.call(this),this.removeManagerStateListener=null,this.removeManagerFailureListener=null,this.removeManagerVisibilityListener=null,this.detachDeviceHandlers(),(i=(r=this.connection)==null?void 0:r.setConnectionManager)==null||i.call(r,null),(o=this.connection)==null||o.close(),this.connection=null,this.slotState="detached",this.manager.stop(),this.mutableStatus.emit())}getAttachedConnection(){return this.connection}startPassiveManager(){this.connection&&(this.manager.start(()=>{const n=this.connection;return n?this.reconnectConnection(n):Promise.reject(this.createNotReadyError())},{sendPing:n=>{var s;return(s=this.connection)==null?void 0:s.sendPing(n)},label:this.managerLabel,driveReconnect:!0}),this.slotState==="ready"&&this.manager.markConnected())}subscribeNow(e,n){this.assertNotDisposed();const s=this.connection;if(!s){let c=!1;return queueMicrotask(()=>{var d;c||(d=e.onError)==null||d.call(e,this.createNotReadyError())}),{close:()=>{c=!0}}}this.activeSubscriptions+=1,this.mutableStatus.emit();let r=!1;const i=()=>{r||(r=!0,this.activeSubscriptions=Math.max(0,this.activeSubscriptions-1),this.mutableStatus.emit())},a=n(s,{onEvent:(c,d,h)=>{e.onEvent(c,d,h)},onOpen:()=>{var c;(c=e.onOpen)==null||c.call(e)},onError:c=>{var d;this.lastError=c.message,i(),(d=e.onError)==null||d.call(e,c)},onClose:c=>{var d;c&&(this.lastError=c.message),i(),(d=e.onClose)==null||d.call(e,c)}});return{close:()=>{i(),a.close()}}}async withConnection(e){const n=await this.waitForConnection();if(this.manager.state==="disconnected")throw this.createDisconnectedError();return e(n)}waitForConnection(){return this.disposed?Promise.reject(new Ye(this.kind)):this.connection?Promise.resolve(this.connection):new Promise((e,n)=>{let s;const r={resolve:i=>{clearTimeout(s),this.attachWaiters.delete(r),e(i)},reject:i=>{clearTimeout(s),this.attachWaiters.delete(r),n(i)}};s=setTimeout(()=>{this.attachWaiters.delete(r),n(this.createNotReadyError())},this.readyTimeoutMs),this.attachWaiters.add(r)})}resolveAttachWaiters(e){const n=[...this.attachWaiters];for(const s of n)s.resolve(e)}rejectAttachWaiters(e){const n=[...this.attachWaiters];for(const s of n)s.reject(e)}createNotReadyError(){return new as({kind:this.kind,state:this.getSourceState(),channel:this.channelName,timeoutMs:this.readyTimeoutMs})}createDisconnectedError(){return new cs({kind:this.kind,channel:this.channelName,lastError:this.lastError})}createSnapshot(){return{kind:this.kind,state:this.getSourceState(),channels:[this.createChannelSnapshot()]}}createChannelSnapshot(){return{name:this.channelName,state:this.getChannelState(),activeSubscriptions:this.activeSubscriptions,...this.manager.reconnectAttempts>0?{reconnectAttempts:this.manager.reconnectAttempts}:{},...this.lastError?{lastError:this.lastError}:{}}}getSourceState(){if(this.disposed||!this.connection)return"disconnected";if(this.slotState==="connecting")return"connecting";switch(this.manager.state){case"connected":return"ready";case"reconnecting":return"reconnecting";case"disconnected":return"disconnected"}}getChannelState(){if(this.disposed||!this.connection)return"disconnected";if(this.slotState==="connecting")return"connecting";switch(this.manager.state){case"connected":return"connected";case"reconnecting":return"reconnecting";case"disconnected":return"disconnected"}}async sendDeviceMessage(e){const n=await this.waitForConnection();if(!n.sendMessage)throw new Ut({kind:this.kind,operation:"device signaling",channel:this.channelName});n.sendMessage(e)}addDeviceHandler(e){this.deviceHandlers.add(e);const n=this.attachDeviceHandler(e);return n&&this.deviceUnsubscribers.set(e,n),()=>{var s;(s=this.deviceUnsubscribers.get(e))==null||s(),this.deviceUnsubscribers.delete(e),this.deviceHandlers.delete(e)}}attachDeviceHandlers(){for(const e of this.deviceHandlers){const n=this.attachDeviceHandler(e);n&&this.deviceUnsubscribers.set(e,n)}}detachDeviceHandlers(){for(const e of this.deviceUnsubscribers.values())e();this.deviceUnsubscribers.clear()}attachDeviceHandler(e){const n=this.connection;return n!=null&&n.onDeviceMessage?n.onDeviceMessage(e):null}async openSpeechSocket(){const e=await this.waitForConnection();if(!e.openSpeechSocket)throw new Ut({kind:this.kind,operation:"speech socket",channel:this.channelName});return e.openSpeechSocket()}assertNotDisposed(){if(this.disposed)throw new Ye(this.kind)}}class Hs extends dn{constructor(e={}){super({kind:"websocket",channelName:"multiplex-websocket",managerLabel:"source-websocket",sameOriginUrls:e.sameOriginUrls??!0,device:!0,speech:!1,reconnect:n=>n.reconnect()},e)}}class Js extends dn{constructor(e={}){super({kind:"secure",channelName:"secure-websocket",managerLabel:"source-secure",sameOriginUrls:!1,device:!0,speech:!0,reconnect:n=>n.forceReconnect()},e)}}const Nt=t=>{let e;const n=new Set,s=(d,h)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const m=e;e=h??(typeof f!="object"||f===null)?f:Object.assign({},e,f),n.forEach(p=>p(e,m))}},r=()=>e,a={setState:s,getState:r,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=e=t(s,r,a);return a},Vs=(t=>t?Nt(t):Nt),qs=t=>t;function A(t,e=qs){const n=Ce.useSyncExternalStore(t.subscribe,Ce.useCallback(()=>e(t.getState()),[t,e]),Ce.useCallback(()=>e(t.getInitialState()),[t,e]));return Ce.useDebugValue(n),n}function dc(t,e){return{awaitingFirstRows:e===0&&(t==null?void 0:t.complete)===!1&&t.refreshing,refreshError:t!=null&&t.refreshError?new Error(t.refreshError):null}}function P(t,e){const n=t.sessions.aliases;if(!n.size)return e;let s=e;const r=new Set;for(;!r.has(s);){r.add(s);const i=n.get(s);if(!i)break;s=i}return s}const oe="all-projects",rt=[],zs=[],Ys={status:"running"},fe=["needsAttention","active","recentActivity","unread8h","unread24h"];function gt(t){return{needsAttention:t(),active:t(),recentActivity:t(),unread8h:t(),unread24h:t()}}const Ks=["needsAttention","active"];function lc(t){return{scope:"global-sessions",projectId:t.projectId??null,searchQuery:t.searchQuery||void 0,limit:t.limit,includeArchived:t.includeArchived,starred:t.starred}}function Be(t){var n;const e={scope:t.scope,projectId:t.projectId??null,searchQuery:((n=t.searchQuery)==null?void 0:n.trim())||null,limit:t.limit??null,includeArchived:t.includeArchived===!0,starred:t.starred===!0};return JSON.stringify(e)}function De(t){return t==="in-turn"||t==="waiting-input"}function Xs(t,e){return e?t.sessions.entities.get(P(t,e)):void 0}function Zs(t,e){var s;if(!e)return null;const n=P(t,e);return((s=t.providerRuntime.bySessionId.get(n))==null?void 0:s.status)??null}function er(t,e){return t.sessions.queries.get(Be(e))}function tr(t,e){return e?t.projects.entities.get(e):void 0}function nr(t){const e=t.projects.queries.get(oe);return e?e.ids.flatMap(n=>{const s=t.projects.entities.get(n);return s?[s]:[]}):[]}function sr(t,e){var n;return e?((n=t.projectQueues.byProject.get(e))==null?void 0:n.items)??rt:rt}function rr(t,e){const n={};for(const s of e){const r=t.projectQueues.byProject.get(s);r&&(n[s]=r.items)}return n}function ir(t,e){const n=new Set(e);return(t.projectQueues.globalItemsObservedAt!==void 0?t.projectQueues.globalItems:[...t.projectQueues.byProject.values()].flatMap(r=>r.items)).filter(r=>n.has(r.projectId))}function or(t){return t.projectQueues.dispatchState}function ar(t){return t.projectQueues.recoveredSessionQueues}function cr(t){const e={};for(const[n,s]of t.projectQueues.projectStatusesByProject)e[n]=s.status;return e}function Ft(t){return t.filter(e=>e.status==="queued"||e.status==="failed").length}function ur(t,e){const n=new Set;let s=0;for(const r of e){n.add(r.id);const i=t.projectQueues.byProject.get(r.id),o=r.snapshotObservedAt??Number.NEGATIVE_INFINITY;i&&i.observedAt>=o?s+=Ft(i.items):s+=r.projectQueueCount??0}for(const[r,i]of t.projectQueues.byProject)n.has(r)||(s+=Ft(i.items));return s}function dr(t,e){const n=new Set;for(const s of e){const r=sr(t,s);for(const i of r)i.target.type==="existing-session"&&n.add(i.target.sessionId)}return n}function lr(t){return t.localDecorations.draftSessionIds}function hr(t){return!t.projectId||!t.updatedAt?null:{sessionId:t.id,projectId:t.projectId,projectName:t.projectName??"",sessionTitle:t.title??null,updatedAt:t.updatedAt,customTitle:t.customTitle,isStarred:t.isStarred,pendingInputType:t.pendingInputType,activity:t.activity,activityInferredFromInboxTier:t.activityInferredFromInboxTier,hasUnread:t.hasUnread,asyncQuestions:t.asyncQuestions,nonHumanUserTurn:t.nonHumanUserTurn}}function te(t,e){return t.inbox.tiers[e].flatMap(n=>{const s=t.sessions.entities.get(n);if(!s)return[];const r=hr(s);return r?[r]:[]})}function fr(t){return{...t.inbox.catalog?{catalog:t.inbox.catalog}:{},needsAttention:te(t,"needsAttention"),active:te(t,"active"),recentActivity:te(t,"recentActivity"),unread8h:te(t,"unread8h"),unread24h:te(t,"unread24h")}}function mr(t){return{needsAttention:t.inbox.tiers.needsAttention.length,active:t.inbox.tiers.active.length,total:fe.reduce((e,n)=>e+t.inbox.tiers[n].length,0)}}function pr(t,e,n){const s=t.get(e)??{needsAttention:0,active:0,total:0};t.set(e,{needsAttention:s.needsAttention+(n==="needsAttention"?1:0),active:s.active+(n==="active"?1:0),total:s.total+1})}function gr(t){var n;const e=new Map;for(const s of fe)for(const r of t.inbox.tiers[s]){const i=(n=t.sessions.entities.get(r))==null?void 0:n.projectId;i&&pr(e,i,s)}return e}function Sr(t,e){if(!e)return[];const n=[];for(const s of Ks)for(const r of t.inbox.tiers[s]){const i=t.sessions.entities.get(r);(i==null?void 0:i.projectId)===e&&n.push(r)}return n}function yr(t){return t.inbox.tiers.active.length}function Lt(t){return t.updatedAt&&Date.parse(t.updatedAt)||0}function br(t,e){return Lt(e)-Lt(t)}function Qt(t){return t.activeStartedAt??t.eventCreatedAt??t.observedAt}function vr(t,e){return Qt(t)-Qt(e)}function Ir(t){const e=t.filter(s=>De(s.activity)).sort(vr),n=t.filter(s=>!De(s.activity)).sort(br);return[...e,...n]}function Cr(t){return wr(Array.from(t.sessions.entities.values()))}function wr(t){return Ir(t.filter(e=>e.isStarred===!0&&e.isArchived!==!0))}function Tr(t,e){const n=Be(e),s=t.sessions.queries.get(n);return s?s.ids.flatMap(r=>{const i=t.sessions.entities.get(r);return i?[i]:[]}):[]}const x=Number.NEGATIVE_INFINITY,Ar=6e4,Mr=256;function ln(){return{sessions:{entities:new Map,queries:new Map,aliases:new Map},projects:{entities:new Map,queries:new Map},projectQueues:{byProject:new Map,globalItems:rt,dispatchState:Ys,recoveredSessionQueues:zs,projectStatusesByProject:new Map},inbox:{tiers:gt(()=>[])},localDecorations:{draftSessionIds:new Set},providerRuntime:{bySessionId:new Map}}}function Q(t,e){const n=P(t,e);return t.sessions.entities.get(n)??{id:n,observedAt:x}}function B(t,e){const n=P(t,e.id),s=e.parentSessionId?P(t,e.parentSessionId):e.parentSessionId,r=e.forkedFromSessionId?P(t,e.forkedFromSessionId):e.forkedFromSessionId,i=n===e.id&&s===e.parentSessionId&&r===e.forkedFromSessionId?e:{...e,id:n,parentSessionId:s,forkedFromSessionId:r},o=new Map(t.sessions.entities);return o.set(n,i),{...t,sessions:{...t.sessions,entities:o}}}function Ee(t,e){const n=new Set,s=[];for(const r of e){const i=P(t,r);n.has(i)||(n.add(i),s.push(i))}return s}const Bt={contentObservedAt:["title","fullTitle","createdAt","updatedAt","messageCount","provider","model","initialPrompt","lastAgentText","lastHumanTurnAt","asyncQuestions","providerChildren"],metadataObservedAt:["nonHumanUserTurn","customTitle","isArchived","isStarred","autoResumeDisabled","parentSessionId","parentSessionKind","forkedFromSessionId","clearloop","executor"],projectObservedAt:["projectId","projectName"],lifecycleObservedAt:["ownership","activity","activityInferredFromInboxTier","pendingInputType","activeStartedAt"],unreadObservedAt:["hasUnread"]};function Wt(t,e,n){if(!t&&!e)return;if(!t)return e;if(!e)return{...t,id:n};const s=(i,o)=>{const a=t[i]??x,c=e[i]??x,[d,h]=c>=a?[e,t]:[t,e],f=[];for(const p of o){const S=d[p]!==void 0?d[p]:h[p];S!==void 0&&f.push([p,S])}const m=Math.max(a,c);return m!==x&&f.push([i,m]),Object.fromEntries(f)},r={id:n,observedAt:Math.max(t.observedAt,e.observedAt)};for(const i of Object.keys(Bt))Object.assign(r,s(i,Bt[i]));return(t.snapshotObservedAt!==void 0||e.snapshotObservedAt!==void 0)&&(r.snapshotObservedAt=Math.max(t.snapshotObservedAt??x,e.snapshotObservedAt??x)),(t.eventCreatedAt!==void 0||e.eventCreatedAt!==void 0)&&(r.eventCreatedAt=Math.min(t.eventCreatedAt??Number.POSITIVE_INFINITY,e.eventCreatedAt??Number.POSITIVE_INFINITY)),r}function Pr(t,e){var i,o;let n=e.target;if(e.target.type==="existing-session"){const a=P(t,e.target.sessionId);a!==e.target.sessionId&&(n={...e.target,sessionId:a})}const s=(i=e.createdFrom)!=null&&i.sessionId?P(t,e.createdFrom.sessionId):(o=e.createdFrom)==null?void 0:o.sessionId,r=e.createdFrom&&s!==e.createdFrom.sessionId?{...e.createdFrom,sessionId:s}:e.createdFrom;return n===e.target&&r===e.createdFrom?e:{...e,target:n,createdFrom:r}}function Ue(t,e){let n=!1;const s=e.map(r=>{const i=Pr(t,r);return n||(n=i!==r),i});return n?s:e}function hn(t,e){let n=!1;const s=e.map(r=>{const i=P(t,r.sessionId);return i===r.sessionId?r:(n=!0,{...r,sessionId:i})});return n?s:e}function jr(t,e){if(t===e)return!0;if(!t||!e)return!1;const n=Object.keys(t),s=Object.keys(e);return n.length!==s.length?!1:n.every(r=>{const i=r;return t[i]===e[i]})}function Rr(t,e){return t.id===e.id&&t.path===e.path&&t.name===e.name&&t.sessionCount===e.sessionCount&&jr(t.sessionCountsByProvider,e.sessionCountsByProvider)&&t.activeOwnedCount===e.activeOwnedCount&&t.activeExternalCount===e.activeExternalCount&&t.projectQueueBlockingCount===e.projectQueueBlockingCount&&t.lastActivity===e.lastActivity}function fn(t,e,n){const s=t.projects.entities.get(e.id);if(s){if(n<(s.snapshotObservedAt??x))return t;if(Rr(s,e)){if(n===s.snapshotObservedAt)return t;const i=new Map(t.projects.entities);return i.set(e.id,{...s,observedAt:Math.max(s.observedAt,n),snapshotObservedAt:n}),{...t,projects:{...t.projects,entities:i}}}}const r=new Map(t.projects.entities);return r.set(e.id,{...e,observedAt:Math.max((s==null?void 0:s.observedAt)??x,n),snapshotObservedAt:n}),{...t,projects:{...t.projects,entities:r}}}function xr(t,e,n){const s=t.projects.queries.get(oe);if(s&&n<s.requestStartedAt)return t;const r=e.map(o=>o.id);if(s&&s.ids.length===r.length&&s.ids.every((o,a)=>o===r[a])){if(n===s.requestStartedAt)return t;const o=new Map(t.projects.queries);return o.set(oe,{...s,requestStartedAt:n,fetchedAt:Date.now()}),{...t,projects:{...t.projects,queries:o}}}const i=new Map(t.projects.queries);return i.set(oe,{key:oe,ids:r,requestStartedAt:n,fetchedAt:Date.now()}),{...t,projects:{...t.projects,queries:i}}}function _e(t,e){return t===e?!0:JSON.stringify(t)===JSON.stringify(e)}function St(t,e){return t===e?!0:t.length!==e.length?!1:t.every((n,s)=>{const r=e[s];return r?n.id===r.id&&n.projectId===r.projectId&&_e(n.target,r.target)&&n.targetTitle===r.targetTitle&&n.targetFullTitle===r.targetFullTitle&&n.messagePreview===r.messagePreview&&_e(n.message,r.message)&&n.createdAt===r.createdAt&&n.updatedAt===r.updatedAt&&_e(n.createdFrom,r.createdFrom)&&n.status===r.status&&n.attachmentCount===r.attachmentCount&&n.lastError===r.lastError&&n.lastAttemptAt===r.lastAttemptAt:!1})}function mn(t,e){if(!(t!=null&&t.length))return e;const n=new Map(t.map(i=>[i.id,i]));let s=!1;const r=e.map(i=>{if(i.targetTitle!==void 0&&i.targetFullTitle!==void 0)return i;const o=n.get(i.id);if(!o||!_e(i.target,o.target))return i;const a=i.targetTitle!==void 0?i.targetTitle:o.targetTitle,c=i.targetFullTitle!==void 0?i.targetFullTitle:o.targetFullTitle;return a===i.targetTitle&&c===i.targetFullTitle?i:(s=!0,{...i,...a!==void 0?{targetTitle:a}:{},...c!==void 0?{targetFullTitle:c}:{}})});return s?r:e}function Er(t,e){if(t.length!==e.length)return!1;const n=new Set(t.map(s=>s.id));return e.every(s=>n.has(s.id))}function _r(t,e,n){if(t.length===0)return n;const s=t.filter(a=>a.projectId===e);if(s.length===0)return n.length>0?[...t,...n]:t;if(Er(s,n)){let a=0;return t.map(c=>c.projectId===e?n[a++]:c)}const r=new Map(n.map(a=>[a.id,a])),i=new Set,o=[];for(const a of t){if(a.projectId!==e){o.push(a);continue}const c=r.get(a.id);c&&(o.push(c),i.add(c.id))}for(const a of n)i.has(a.id)||o.push(a);return o}function Or(t,e){return fe.every(n=>{const s=t[n],r=e[n];return s.length===r.length&&s.every((i,o)=>i===r[o])})}function kr(t,e){if(t===e)return!0;if(t.size!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function Dr(t,e){return JSON.stringify(t)===JSON.stringify(e)}function Ur(t,e){return JSON.stringify(t)===JSON.stringify(e)}function $r(t,e){return t===e?!0:JSON.stringify(t)===JSON.stringify(e)}function Nr(t,e){return JSON.stringify(t)===JSON.stringify(e)}function pn(t,e,n,s,r){const i=P(t,e),o=t.providerRuntime.bySessionId.get(i);if(o&&r<o.observedAt)return t;if(s===null){if(!o)return t;const c=new Map(t.providerRuntime.bySessionId);return c.delete(i),{...t,providerRuntime:{...t.providerRuntime,bySessionId:c}}}if(o&&r===o.observedAt&&o.projectId===n&&$r(o.status,s))return t;const a=new Map(t.providerRuntime.bySessionId);return a.set(i,{sessionId:i,projectId:n,status:s,observedAt:r}),{...t,providerRuntime:{...t.providerRuntime,bySessionId:a}}}function gn(t,e,n){return!e||n<(t.projectQueues.dispatchStateObservedAt??x)||Dr(t.projectQueues.dispatchState,e)&&n===t.projectQueues.dispatchStateObservedAt?t:{...t,projectQueues:{...t.projectQueues,dispatchState:e,dispatchStateObservedAt:n}}}function Sn(t,e,n,s){if(!e)return t;let r=null;const i=new Set(Object.keys(e));for(const[o,a]of Object.entries(e)){const c=t.projectQueues.projectStatusesByProject.get(o);c&&c.observedAt>n||c&&c.observedAt===n&&Nr(c.status,a)||(r||(r=new Map(t.projectQueues.projectStatusesByProject)),r.set(o,{projectId:o,status:a,observedAt:n}))}if(s==="replace")for(const[o,a]of t.projectQueues.projectStatusesByProject)i.has(o)||a.observedAt>n||(r||(r=new Map(t.projectQueues.projectStatusesByProject)),r.delete(o));return r?{...t,projectQueues:{...t.projectQueues,projectStatusesByProject:r}}:t}function Fr(t,e,n){if(!e)return t;const s=hn(t,e);return n<(t.projectQueues.recoveredSessionQueuesObservedAt??x)||Ur(t.projectQueues.recoveredSessionQueues,s)&&n===t.projectQueues.recoveredSessionQueuesObservedAt?t:{...t,projectQueues:{...t.projectQueues,recoveredSessionQueues:s,recoveredSessionQueuesObservedAt:n}}}function yt(t,e,n){let s=gn(t,e.dispatchState,n);s=Sn(s,e.projectStatuses,n,"merge");const r=s.projectQueues.byProject.get(e.projectId),i=Ue(s,e.items),o=mn(r==null?void 0:r.items,i);if(r){if(n<(r.snapshotObservedAt??x))return s;if(St(r.items,o)){const c=new Map(s.projectQueues.byProject);return c.set(e.projectId,{...r,observedAt:Math.max(r.observedAt,n),snapshotObservedAt:n}),s={...s,projectQueues:{...s.projectQueues,byProject:c}},s.projectQueues.globalItemsObservedAt!==void 0&&n>=s.projectQueues.globalItemsObservedAt?Gt(s,e.projectId,o,n):s}}const a=new Map(s.projectQueues.byProject);return a.set(e.projectId,{projectId:e.projectId,items:o,observedAt:Math.max((r==null?void 0:r.observedAt)??x,n),snapshotObservedAt:n}),s={...s,projectQueues:{...s.projectQueues,byProject:a}},s.projectQueues.globalItemsObservedAt!==void 0&&n>=s.projectQueues.globalItemsObservedAt?Gt(s,e.projectId,o,n):s}function Gt(t,e,n,s){const r=_r(t.projectQueues.globalItems,e,n);return St(t.projectQueues.globalItems,r)&&s===t.projectQueues.globalItemsObservedAt?t:{...t,projectQueues:{...t.projectQueues,globalItems:r,globalItemsObservedAt:s}}}function Lr(t,e,n){if(n<(t.projectQueues.globalItemsObservedAt??x))return t;const s=new Map,r=mn(t.projectQueues.globalItems,Ue(t,e.items));for(const a of r){const c=s.get(a.projectId);c?c.push(a):s.set(a.projectId,[a])}let i=t;for(const[a,c]of s)i=yt(i,{projectId:a,items:c},n);let o=null;for(const[a,c]of i.projectQueues.byProject)s.has(a)||(c.snapshotObservedAt??x)>n||(o||(o=new Map(i.projectQueues.byProject)),o.delete(a));return o&&(i={...i,projectQueues:{...i.projectQueues,byProject:o}}),(!St(i.projectQueues.globalItems,r)||n!==i.projectQueues.globalItemsObservedAt)&&(i={...i,projectQueues:{...i.projectQueues,globalItems:r,globalItemsObservedAt:n}}),i=gn(i,e.dispatchState,n),i=Sn(i,e.projectStatuses,n,"replace"),Fr(i,e.recoveredSessionQueues,n)}function Qr(t,e,n){let s=Q(t,e.sessionId);s=pe(s,{title:e.sessionTitle,asyncQuestions:e.asyncQuestions,updatedAt:e.updatedAt},n),s=Se(s,{projectId:e.projectId,projectName:e.projectName},n),s=ge(s,{customTitle:e.customTitle,nonHumanUserTurn:e.nonHumanUserTurn,isStarred:e.isStarred},n);const r=e.activity??(e.pendingInputType?"waiting-input":null);return s=ye(s,{activity:r,activityInferredFromInboxTier:!1,pendingInputType:e.pendingInputType},n),s=We(s,e.hasUnread,n),B(t,s)}function Br(t,e,n){var c;if(t.inbox.requestStartedAt!==void 0&&n<t.inbox.requestStartedAt)return t;const s=W(n,"partial-snapshot","inbox");let r=t;const i=gt(()=>[]),o=new Set;for(const d of fe)for(const h of e[d]){const f=P(r,h.sessionId);o.has(f)||(o.add(f),i[d].push(f)),r=Qr(r,h,s)}const a=Or(r.inbox.tiers,i)?r.inbox.tiers:i;return{...r,inbox:{...r.inbox,tiers:((c=e.catalog)==null?void 0:c.complete)===!1?r.inbox.tiers:a,catalog:e.catalog,requestStartedAt:n,fetchedAt:Date.now()}}}function Wr(t){return t==="in-turn"||t==="waiting-input"?t:void 0}function W(t,e,n){return{observedAt:t,kind:e,source:n}}function me(t,e){return t.observedAt>=(e??x)}function C(t,e,n){return e!==void 0&&(n||t===void 0)}function pe(t,e,n){if(Object.values(e).every(r=>r===void 0))return t;const s=me(n,t.contentObservedAt);return{...t,...C(t.title,e.title,s)?{title:e.title}:{},...C(t.fullTitle,e.fullTitle,s)?{fullTitle:e.fullTitle}:{},...C(t.createdAt,e.createdAt,s)?{createdAt:e.createdAt}:{},...C(t.updatedAt,e.updatedAt,s)?{updatedAt:e.updatedAt}:{},...C(t.messageCount,e.messageCount,s)?{messageCount:e.messageCount}:{},...C(t.provider,e.provider,s)?{provider:e.provider}:{},...C(t.model,e.model,s)?{model:e.model}:{},...C(t.initialPrompt,e.initialPrompt,s)?{initialPrompt:e.initialPrompt}:{},...C(t.lastAgentText,e.lastAgentText,s)?{lastAgentText:e.lastAgentText}:{},...C(t.lastHumanTurnAt,e.lastHumanTurnAt,s)?{lastHumanTurnAt:e.lastHumanTurnAt}:{},...C(t.providerChildren,e.providerChildren,s)?{providerChildren:e.providerChildren}:{},...C(t.asyncQuestions,e.asyncQuestions,s)?{asyncQuestions:e.asyncQuestions}:{},...s?{contentObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function ge(t,e,n){if(Object.values(e).every(r=>r===void 0))return t;const s=me(n,t.metadataObservedAt);return{...t,...C(t.customTitle,e.customTitle,s)?{customTitle:e.customTitle}:{},...C(t.nonHumanUserTurn,e.nonHumanUserTurn,s)?{nonHumanUserTurn:e.nonHumanUserTurn}:{},...C(t.isArchived,e.isArchived,s)?{isArchived:e.isArchived}:{},...C(t.isStarred,e.isStarred,s)?{isStarred:e.isStarred}:{},...C(t.autoResumeDisabled,e.autoResumeDisabled,s)?{autoResumeDisabled:e.autoResumeDisabled}:{},...e.parentSessionId===null?s?{parentSessionId:void 0}:{}:C(t.parentSessionId,e.parentSessionId,s)?{parentSessionId:e.parentSessionId}:{},...e.parentSessionKind===null?s?{parentSessionKind:void 0}:{}:C(t.parentSessionKind,e.parentSessionKind,s)?{parentSessionKind:e.parentSessionKind}:{},...e.forkedFromSessionId===null?s?{forkedFromSessionId:void 0}:{}:C(t.forkedFromSessionId,e.forkedFromSessionId,s)?{forkedFromSessionId:e.forkedFromSessionId}:{},...e.clearloop===null?s?{clearloop:void 0}:{}:C(t.clearloop,e.clearloop,s)?{clearloop:e.clearloop}:{},...C(t.executor,e.executor,s)?{executor:e.executor}:{},...s?{metadataObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function Se(t,e,n){if(Object.values(e).every(r=>r===void 0))return t;const s=me(n,t.projectObservedAt);return{...t,...C(t.projectId,e.projectId,s)?{projectId:e.projectId}:{},...C(t.projectName,e.projectName,s)?{projectName:e.projectName}:{},...s?{projectObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function bt(t,e,n){const s=t.projectId===void 0||e.projectId===void 0||t.projectId===e.projectId;return Se(t,{projectId:t.projectId===void 0?e.projectId:void 0,projectName:s&&t.projectName===void 0?e.projectName:void 0},n)}function ye(t,e,n){if(e.ownership===void 0&&e.activity===void 0&&e.activityInferredFromInboxTier===void 0&&e.pendingInputType===void 0)return t;const s=me(n,t.lifecycleObservedAt),r=Wr(e.activity),i=De(t.activity),o=s?r:t.activity,a=De(o),c=s?o==="waiting-input"?e.pendingInputType:void 0:o==="waiting-input"&&C(t.pendingInputType,e.pendingInputType,s)?e.pendingInputType:t.pendingInputType;return{...t,...C(t.ownership,e.ownership,s)?{ownership:e.ownership}:{},activity:o,activityInferredFromInboxTier:s&&o?e.activityInferredFromInboxTier===!0:s?void 0:t.activityInferredFromInboxTier,activeStartedAt:s?a?i?t.activeStartedAt:n.observedAt:void 0:t.activeStartedAt,pendingInputType:c,...s?{lifecycleObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function We(t,e,n){if(e===void 0)return t;const s=me(n,t.unreadObservedAt);return!s&&t.hasUnread!==void 0?t:{...t,hasUnread:e,...s?{unreadObservedAt:n.observedAt}:{},observedAt:Math.max(t.observedAt,n.observedAt)}}function Gr(t,e,n){let s=Q(t,e.id);return s=pe(s,{title:e.title,fullTitle:e.fullTitle,createdAt:e.createdAt,updatedAt:e.updatedAt,messageCount:e.messageCount,provider:e.provider,model:e.model,initialPrompt:e.initialPrompt,lastAgentText:e.lastAgentText,lastHumanTurnAt:e.lastHumanTurnAt,asyncQuestions:e.asyncQuestions,providerChildren:e.providerChildren},n),s=ge(s,{customTitle:e.customTitle,nonHumanUserTurn:e.nonHumanUserTurn,isArchived:e.isArchived,isStarred:e.isStarred,clearloop:e.clearloop,autoResumeDisabled:e.autoResumeDisabled,parentSessionId:e.parentSessionId,parentSessionKind:e.parentSessionKind,forkedFromSessionId:e.forkedFromSessionId,executor:e.executor},n),s=Se(s,{projectId:e.projectId,projectName:e.projectName},n),s=ye(s,{ownership:e.ownership,activity:e.activity,pendingInputType:e.pendingInputType},n),s=We(s,e.hasUnread,n),s={...s,snapshotObservedAt:Math.max(s.snapshotObservedAt??x,n.observedAt),observedAt:Math.max(s.observedAt,n.observedAt)},B(t,s)}function Hr(t,e,n){var c;const s=Be(e.query),r=t.sessions.queries.get(s);if(r&&n<r.requestStartedAt)return t;const i=Ee(t,e.sessions.map(d=>d.id));let o=i;if((e.mode==="append"||((c=e.catalog)==null?void 0:c.complete)===!1)&&r)o=[...r.ids,...i.filter(d=>!r.ids.includes(d))];else if(e.mode==="prepend"&&r){const d=new Set(i);o=[...i,...r.ids.filter(h=>!d.has(h))]}else r&&(o=Jr(t,e.query,r.ids,i,n));const a=new Map(t.sessions.queries);return a.set(s,{key:s,descriptor:e.query,catalog:e.catalog,ids:o,hasMore:e.hasMore,requestStartedAt:n,fetchedAt:Date.now()}),{...t,sessions:{...t.sessions,queries:a}}}function Jr(t,e,n,s,r){const i=new Set(s),o=n.filter(a=>{if(i.has(a))return!1;const c=t.sessions.entities.get(a);return!!c&&Vr(c,r)&&qr(c,e)});return o.length>0?[...o,...s]:[...s]}function Vr(t,e){if(t.eventCreatedAt===void 0)return!1;const n=e-t.eventCreatedAt;return n>=0&&n<=Ar}function qr(t,e){var n;return!((n=e.searchQuery)!=null&&n.trim()||e.projectId&&t.projectId!==e.projectId||e.includeArchived!==!0&&t.isArchived===!0||e.starred===!0&&t.isStarred!==!0)}function zr(t,e,n=Date.now()){const s=W(n,"partial-snapshot","session-metadata");let r=Q(t,e.id);return r=pe(r,{title:e.title,fullTitle:e.fullTitle},s),r=ge(r,{customTitle:e.customTitle,nonHumanUserTurn:e.nonHumanUserTurn},s),r=Se(r,{projectId:e.projectId},s),B(t,r)}function Yr(t,e,n=Date.now()){const s=W(n,e.catalog?"partial-snapshot":"full-snapshot","global-sessions");let r=t;for(const i of e.sessions)r=Gr(r,i,s);return Hr(r,e,n)}function Kr(t,e,n=Date.now()){let s=t;for(const r of e.projects)s=fn(s,r,n);return xr(s,e.projects,n)}function Xr(t,e,n=Date.now()){return fn(t,e.project,n)}function Zr(t,e,n=Date.now()){return yt(t,e,n)}function ei(t,e,n=Date.now()){return Lr(t,e,n)}function ti(t,e,n=Date.now()){return yt(t,{projectId:e.projectId,items:e.items,dispatchState:e.dispatchState},n)}function ni(t,e,n=Date.now()){return Br(t,e,n)}function si(t,e){const n=P(t,e.oldSessionId),s=P(t,e.newSessionId);if(n===s)return t;const r=new Map(t.sessions.aliases);r.delete(s);for(const[b,v]of r)P(t,v)===n&&r.set(b,s);for(r.delete(e.oldSessionId),r.set(e.oldSessionId,s),n!==e.oldSessionId&&(r.delete(n),r.set(n,s));r.size>Mr;){const b=r.keys().next().value;if(b===void 0)break;r.delete(b)}let i={...t,sessions:{...t.sessions,aliases:r}};const o=new Map(i.sessions.entities);let a;for(const[b,v]of o)b!==s&&P(i,b)===s&&(a=Wt(a,v,s),o.delete(b));const c=Wt(a,o.get(s),s);c&&o.set(s,c);for(const[b,v]of o){const M=v.parentSessionId?P(i,v.parentSessionId):void 0,_=v.forkedFromSessionId?P(i,v.forkedFromSessionId):void 0;(M!==v.parentSessionId||_!==v.forkedFromSessionId)&&o.set(b,{...v,parentSessionId:M,forkedFromSessionId:_})}const d=new Map(i.sessions.queries);for(const[b,v]of d){const M=Ee(i,v.ids);(M.length!==v.ids.length||M.some((_,G)=>_!==v.ids[G]))&&d.set(b,{...v,ids:M})}i={...i,sessions:{...i.sessions,entities:o,queries:d}};const h=gt(()=>[]),f=new Set;for(const b of fe)for(const v of Ee(i,i.inbox.tiers[b]))f.has(v)||(f.add(v),h[b].push(v));const m=new Map(i.projectQueues.byProject);for(const[b,v]of m){const M=Ue(i,v.items);M!==v.items&&m.set(b,{...v,items:M})}const p=Ue(i,i.projectQueues.globalItems),S=hn(i,i.projectQueues.recoveredSessionQueues),g=new Map(i.providerRuntime.bySessionId);let y=g.get(s);for(const[b,v]of g)b===s||P(i,b)!==s||((!y||v.observedAt>y.observedAt)&&(y={...v,sessionId:s}),g.delete(b));return y&&g.set(s,{...y,sessionId:s}),{...i,projectQueues:{...i.projectQueues,byProject:m,globalItems:p,recoveredSessionQueues:S},inbox:{...i.inbox,tiers:h},localDecorations:{...i.localDecorations,draftSessionIds:new Set(Ee(i,[...i.localDecorations.draftSessionIds]))},providerRuntime:{...i.providerRuntime,bySessionId:g}}}function yn(t,e,n=Date.now()){const s=new Set([...e].map(r=>P(t,r)));return kr(t.localDecorations.draftSessionIds,s)?t:{...t,localDecorations:{...t.localDecorations,draftSessionIds:s,draftObservedAt:n}}}function ri(t,e,n=Date.now()){return pn(t,e.sessionId,e.projectId,e.providerRuntimeStatus,n)}function ii(t,e,n=Date.now()){return e.providerRuntimeStatus===void 0?t:pn(t,e.sessionId,e.projectId,e.providerRuntimeStatus,n)}function bn(t,e,n=Date.now()){const s=W(n,"partial-event","session-created"),r=e.session;let i=Q(t,r.id);return i=pe(i,{title:r.title,fullTitle:r.fullTitle,createdAt:r.createdAt,updatedAt:r.updatedAt,messageCount:r.messageCount,provider:r.provider,model:r.model,initialPrompt:r.initialPrompt,lastAgentText:r.lastAgentText,lastHumanTurnAt:r.lastHumanTurnAt,asyncQuestions:r.asyncQuestions,providerChildren:r.providerChildren},s),i=ge(i,{customTitle:r.customTitle,nonHumanUserTurn:r.nonHumanUserTurn,isArchived:r.isArchived,isStarred:r.isStarred,clearloop:r.clearloop,parentSessionId:r.parentSessionId,parentSessionKind:r.parentSessionKind,forkedFromSessionId:r.forkedFromSessionId},s),i=bt(i,{projectId:r.projectId,projectName:r.projectName??i.projectName},s),i=ye(i,{ownership:r.ownership,activity:r.activity,pendingInputType:r.pendingInputType},s),i=We(i,r.hasUnread,s),B(t,{...i,eventCreatedAt:n,observedAt:Math.max(i.observedAt,n)})}function oi(t,e,n=Date.now()){const s=W(n,"partial-event","session-updated"),r=pe(Q(t,e.sessionId),{title:e.title,updatedAt:e.updatedAt,messageCount:e.messageCount,model:e.model,lastAgentText:e.lastAgentText,asyncQuestions:e.asyncQuestions},s);return B(t,r)}function vn(t,e,n=Date.now()){const s=W(n,"partial-event","metadata-changed"),r=ge(Q(t,e.sessionId),{customTitle:e.title,nonHumanUserTurn:e.nonHumanUserTurn,isArchived:e.archived,isStarred:e.starred,parentSessionId:e.parentSessionId,parentSessionKind:e.parentSessionKind,forkedFromSessionId:e.forkedFromSessionId,clearloop:e.clearloop},s),i=e.projectId!==void 0&&r.projectId!==void 0&&e.projectId!==r.projectId?{...r,projectName:void 0}:r,o=Se(i,{projectId:e.projectId},s);return B(t,o)}function ai(t,e,n=Date.now()){const s=W(n,"partial-event","session-status");let r=Q(t,e.sessionId);return r=bt(r,{projectId:e.projectId},s),r=ye(r,{ownership:e.ownership,activity:e.ownership.owner==="none"?"idle":r.activity,pendingInputType:r.pendingInputType},s),B(t,r)}function ci(t,e,n=Date.now()){const s=W(n,"partial-event","process-state");let r=Q(t,e.sessionId);return r=bt(r,{projectId:e.projectId},s),r=ye(r,{activity:e.activity,pendingInputType:e.pendingInputType},s),B(t,r)}function ui(t,e,n=Date.now()){const s=W(n,"partial-event","session-seen"),r=We(Q(t,e.sessionId),Us(e),s);return B(t,r)}const it=new Set;function In(t){for(const e of it)e(t)}function di(t){return it.add(t),()=>it.delete(t)}const le=1;function Ge(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function L(t){return typeof t=="string"&&t.trim()?t:null}function Xe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function li(t){if(!Ge(t))return null;const e=L(t.id),n=L(t.batchId),s=L(t.originalName),r=L(t.name),i=L(t.mimeType),o=L(t.createdAt),a=L(t.updatedAt),c=Xe(t.size);if(!e||!n||!s||!r||!i||!o||!a||c===void 0)return null;const d=Xe(t.width),h=Xe(t.height);return{id:e,batchId:n,originalName:s,name:r,size:c,mimeType:i,...d!==void 0?{width:d}:{},...h!==void 0?{height:h}:{},createdAt:o,updatedAt:a}}function hi(t){if(!Ge(t))return null;const e=L(t.batchId),n=L(t.updatedAt);if(!e||!n||!Array.isArray(t.refs))return null;const s=t.refs.map(li).filter(r=>r!==null);return s.length===0?null:{batchId:e,refs:s,updatedAt:n}}function fi(t){if(!Ge(t)||t.version!==le||typeof t.text!="string")return null;const e=hi(t.attachments);return{version:le,text:t.text,...e?{attachments:e}:{},...t.pendingSend===!0?{pendingSend:!0}:{}}}function mi(t){return/^\s*\{\s*"version"\s*:/.test(t)}function Y(t){if(!t)return{envelope:null,legacy:!1,invalidEnvelope:!1};try{const e=JSON.parse(t),n=fi(e);if(n)return{envelope:n,legacy:!1,invalidEnvelope:!1};if(Ge(e)&&"version"in e)return{envelope:null,legacy:!1,invalidEnvelope:!0}}catch{if(mi(t))return{envelope:null,legacy:!1,invalidEnvelope:!0}}return{envelope:{version:le,text:t},legacy:!0,invalidEnvelope:!1}}function Cn(t){var e;return!!(t&&(t.text.trim()||(((e=t.attachments)==null?void 0:e.refs.length)??0)>0))}function H(t){return Cn(Y(t).envelope)}function hc(t){var e;return((e=Y(t).envelope)==null?void 0:e.text)??""}function fc(t){var e;return((e=Y(t).envelope)==null?void 0:e.attachments)??null}function mc(t){var e;return((e=Y(t).envelope)==null?void 0:e.pendingSend)===!0}function vt(t){return Cn(t)?JSON.stringify(t):null}function pi(t,e){const n=Y(e).envelope;return vt({version:le,text:t,...n!=null&&n.attachments?{attachments:n.attachments}:{}})}function gi(t){const e=Y(t).envelope;return e!=null&&e.text.trim()?vt({...e,pendingSend:!0}):null}function Si(t,e){const n=Y(e).envelope,s=t&&t.refs.length>0?t:void 0;return vt({version:le,text:(n==null?void 0:n.text)??"",...s?{attachments:s}:{},...n!=null&&n.pendingSend?{pendingSend:!0}:{}})}const $e="draft-message-",ot="local",wn="draft-message:",It="draft-index-message:",Ct="draft-presence-message:";function X(t){return encodeURIComponent(t)}function wt({sourceKey:t,sessionId:e}){return t===ot?`${$e}${e}`:`${wn}${X(t)}:${X(e)}`}function Tn(t){return`${It}${X(t)}`}function yi({sourceKey:t,sessionId:e}){return`${Ct}${X(t)}:${X(e)}`}function bi(t){return!t||t.startsWith(It)?!1:!!(t.startsWith(Ct)||t.startsWith($e)||t.startsWith(wn))}function vi(t){try{const e=localStorage.getItem(Tn(t));if(!e)return new Set;const n=JSON.parse(e);return Array.isArray(n)?new Set(n.filter(s=>typeof s=="string")):new Set}catch{return new Set}}function Ii(t){const e=new Set;try{const n=`${Ct}${X(t)}:`;for(let s=0;s<localStorage.length;s+=1){const r=localStorage.key(s);if(!(r!=null&&r.startsWith(n)))continue;const i=r.slice(n.length);if(i)try{e.add(decodeURIComponent(i))}catch{}}}catch{}return e}function An(t,e){try{const n=yi(t);return localStorage.getItem(n)!==null===e?{changed:!1,synchronized:!0}:(e?localStorage.setItem(n,"1"):localStorage.removeItem(n),{changed:!0,synchronized:!0})}catch{return{changed:!1,synchronized:!1}}}function Tt(t,e){return An(t,H(e)).changed}function At(t,e){try{const n=wt(t),s=localStorage.getItem(n),r=e(s);r?localStorage.setItem(n,r):localStorage.removeItem(n),Tt(t,r);const i=H(s),o=H(r);i!==o&&In({storageKey:n,hasContent:o,sessionDraft:t})}catch{}}function pc(t,e){At(t,n=>pi(e,n))}function gc(t,e){At(t,n=>Si(e,n))}function Sc(t){At(t,e=>gi(e)??e)}function yc(t){try{const e=wt(t),n=localStorage.getItem(e);localStorage.removeItem(e),Tt(t,""),H(n)&&In({storageKey:e,hasContent:!1,sessionDraft:t})}catch{}}function Ci(t=ot){const e=new Set;try{const n=vi(t),s=Ii(t);for(const i of n)s.add(i);let r=!0;for(const i of s){const o=localStorage.getItem(wt({sourceKey:t,sessionId:i}));H(o)&&e.add(i);const a=An({sourceKey:t,sessionId:i},H(o)).synchronized;n.has(i)&&H(o)&&!a&&(r=!1)}if(n.size>0&&r&&localStorage.removeItem(Tn(t)),t!==ot)return e;for(let i=0;i<localStorage.length;i++){const o=localStorage.key(i);if(!(o!=null&&o.startsWith($e))||o.startsWith(It))continue;const a=localStorage.getItem(o);if(H(a)){const c=o.slice($e.length);e.add(c),Tt({sourceKey:t,sessionId:c},a)}}}catch{}return e}const Mn=T.createContext(null);function bc({children:t,runtime:e}){return us.jsx(Mn.Provider,{value:e,children:t})}function Mt(){return T.useContext(Mn)}function vc(t){return t}function Ic(t){return`host:${t}`}function Cc(t){return`direct:${t}`}const Pn="local",wi="remote:none",at=new Map,ct=new Set;let ut=Pn;const we=new Map,Te=new Map;function Ti(){return Vs(()=>ln())}function $(t){let e=at.get(t);return e||(e=Ti(),at.set(t,e)),e}function dt(){return ut}function Ai(t){return ct.add(t),()=>{ct.delete(t)}}function Pt(){return T.useSyncExternalStore(Ai,dt,dt)}function Mi(t){if(t!==ut){ut=t;for(const e of Array.from(ct))e()}}function j(){const t=Mt(),e=Pt();return T.useMemo(()=>(t==null?void 0:t.summary.getStore())??$(e),[t,e])}function Pi(t){const e=at.get(t);e==null||e.setState(ln(),!0)}function K(t,e){const n=t.getState(),s=e(n);s!==n&&t.setState(s,!0)}function E(t,e){K($(t),e)}function ji(t,e){E(t,n=>ci(n,e))}function Ri(t,e){E(t,n=>ai(n,e))}function xi(t,e){E(t,n=>ui(n,e))}function Ei(t,e){E(t,n=>oi(n,e))}function _i(t,e){E(t,n=>vn(n,e))}function Oi(t,e){E(t,n=>bn(n,e))}function ki(t,e){E(t,n=>si(n,e))}function Di(t,e){E(t,n=>ti(n,e))}function Ui(t,e){E(t,n=>ri(n,e))}function N(t,e,n){return sn.onSource(t,e,n)}function $i(t,e){return sn.retainSourceStream(t,e)}function Ni(t){return[N(t,"process-state-changed",e=>ji(t,e)),N(t,"provider-runtime-status-changed",e=>Ui(t,e)),N(t,"session-status-changed",e=>Ri(t,e)),N(t,"session-seen",e=>xi(t,e)),N(t,"session-updated",e=>Ei(t,e)),N(t,"session-metadata-changed",e=>_i(t,e)),N(t,"session-created",e=>Oi(t,e)),N(t,"session-id-remapped",e=>ki(t,e)),N(t,"project-queue-changed",e=>Di(t,e))]}function Fi(t,e){let n=we.get(t);n||(n={retainCount:0,unsubscribers:Ni(t)},we.set(t,n)),n.retainCount+=1;const s=e?$i(t,e):()=>{};let r=!1;return()=>{if(r)return;r=!0,s();const i=we.get(t);if(i&&(i.retainCount=Math.max(0,i.retainCount-1),i.retainCount===0)){for(const o of i.unsubscribers)o();we.delete(t)}}}function jn(t,e){return Fi(t,e)}function R(){const t=Mt(),e=Pt();T.useEffect(()=>t?t.summary.retainActivitySubscription():jn(e),[t,e])}function Li(t,e,n=Date.now()){E(t,s=>yn(s,e,n))}function Qi(t,e,n=Date.now()){E(t,s=>ii(s,e,n))}function Ht(t){Li(t,Ci(t))}function Bi(t){const e=t.sessionDraft;e&&E(e.sourceKey,n=>{const s=n.localDecorations.draftSessionIds;if(s.has(e.sessionId)===t.hasContent)return n;const r=new Set(s);return t.hasContent?r.add(e.sessionId):r.delete(e.sessionId),yn(n,r,Date.now())})}function Wi(t){if(Ht(t),typeof window>"u")return()=>{};const e=s=>{bi(s.key)&&Ht(t)};window.addEventListener("storage",e);const n=di(s=>{var r;((r=s.sessionDraft)==null?void 0:r.sourceKey)===t&&Bi(s)});return()=>{window.removeEventListener("storage",e),n()}}function Gi(t){let e=Te.get(t);e||(e={retainCount:0,release:Wi(t)},Te.set(t,e)),e.retainCount+=1;let n=!1;return()=>{if(n)return;n=!0;const s=Te.get(t);s&&(s.retainCount=Math.max(0,s.retainCount-1),s.retainCount===0&&(s.release(),Te.delete(t)))}}function Rn(t){return Gi(t)}function Hi(){const t=Mt(),e=Pt();T.useEffect(()=>t?t.summary.retainDraftDecorations():Rn(e),[t,e])}function Ji(t){return $(t).getState()}function Vi(t,e,n=Date.now()){K($(t),s=>Yr(s,e,n))}function qi(t,e,n=Date.now()){K($(t),s=>ni(s,e,n))}function zi(t,e,n=Date.now()){K($(t),s=>Kr(s,e,n))}function Yi(t,e,n=Date.now()){K($(t),s=>Xr(s,e,n))}function Ki(t,e,n=Date.now()){K($(t),s=>Zr(s,e,n))}function Xi(t,e,n=Date.now()){K($(t),s=>ei(s,e,n))}function wc(t,e,n=Date.now()){E(t,s=>zr(s,e,n))}function Zi(t,e,n=Date.now()){E(t,s=>bn(s,e,n))}function eo(t,e,n=Date.now()){E(t,s=>vn(s,e,n))}function He(){R();const t=j();return A(t)}function Tc(t){R();const e=j();return A(e,n=>Xs(n,t))}function Ac(t){R();const e=j();return A(e,n=>Zs(n,t))}function Mc(t){R();const e=j();return A(e,n=>tr(n,t))}function Pc(){const t=He();return T.useMemo(()=>nr(t),[t])}function jc(t){R();const e=j(),n=A(e,i=>i.projectQueues.byProject),s=t.join("\0"),r=T.useMemo(()=>s?s.split("\0"):[],[s]);return T.useMemo(()=>{const i=e.getState();return rr({...i,projectQueues:{...i.projectQueues,byProject:n}},r)},[e,n,r])}function Rc(t){R();const e=j(),n=A(e,i=>i.projectQueues),s=t.join("\0"),r=T.useMemo(()=>s?s.split("\0"):[],[s]);return T.useMemo(()=>ir({...e.getState(),projectQueues:n},r),[e,n,r])}function xc(){R();const t=j();return A(t,or)}function Ec(){R();const t=j();return A(t,ar)}function _c(){R();const t=j(),e=A(t,n=>n.projectQueues.projectStatusesByProject);return T.useMemo(()=>{const n=t.getState();return cr({...n,projectQueues:{...n.projectQueues,projectStatusesByProject:e}})},[t,e])}function Oc(t){R();const e=j(),n=A(e,i=>i.projectQueues.byProject),s=t.map(i=>`${i.id}:${i.projectQueueCount??0}:${i.snapshotObservedAt??""}`).join("\0"),r=T.useMemo(()=>t.map(i=>({id:i.id,projectQueueCount:i.projectQueueCount,snapshotObservedAt:i.snapshotObservedAt})),[t,s]);return T.useMemo(()=>{const i=e.getState();return ur({...i,projectQueues:{...i.projectQueues,byProject:n}},r)},[e,n,r])}function kc(){R();const t=j(),e=A(t,n=>n.projectQueues.byProject);return T.useMemo(()=>[...e.values()].flatMap(n=>n.items).sort((n,s)=>{const r=n.createdAt.localeCompare(s.createdAt);return r!==0?r:n.id.localeCompare(s.id)}),[e])}function Dc(t){R();const e=j(),n=A(e,i=>i.projectQueues.byProject),s=t.join("\0"),r=T.useMemo(()=>s?s.split("\0"):[],[s]);return T.useMemo(()=>{const i=e.getState();return dr({...i,projectQueues:{...i.projectQueues,byProject:n}},r)},[e,n,r])}function Uc(){Hi();const t=j();return A(t,lr)}function $c(){const t=He();return T.useMemo(()=>fr(t),[t])}function Nc(){R();const t=j(),e=A(t,r=>r.inbox.tiers.needsAttention.length),n=A(t,r=>r.inbox.tiers.active.length),s=A(t,r=>mr(r).total);return T.useMemo(()=>({needsAttention:e,active:n,total:s}),[e,n,s])}function Fc(){R();const t=j(),e=A(t,s=>s.inbox.tiers),n=A(t,s=>s.sessions.entities);return T.useMemo(()=>{const s=t.getState();return gr({...s,sessions:{...s.sessions,entities:n},inbox:{...s.inbox,tiers:e}})},[t,e,n])}function Lc(t){R();const e=j(),n=A(e,r=>r.inbox.tiers),s=A(e,r=>r.sessions.entities);return T.useMemo(()=>{const r=e.getState();return Sr({...r,sessions:{...r.sessions,entities:s},inbox:{...r.inbox,tiers:n}},t)},[e,n,s,t])}function Qc(){R();const t=j();return A(t,yr)}function Bc(){const t=He();return T.useMemo(()=>Cr(t),[t])}function Wc(t){const e=He(),n=Be(t);return T.useMemo(()=>Tr(e,t),[e,n,t])}function Gc(t){R();const e=j();return A(e,n=>er(n,t))}const Jt=new WeakMap,lt=6400,Ne=64;function to(t){try{const e=JSON.stringify(t);return e===void 0?lt:e.length*2+Ne}catch{return lt}}function no(t,e=!0){if(typeof t!="object"||t===null)return Ne;const n=Jt.get(t);if(n!==void 0)return n;if(!e)return lt;const s=to(t);return Jt.set(t,s),s}function Ze(t,e,n){if(n&&typeof t=="object"&&t!==null){if(n.has(t))return 0;n.add(t)}return no(t,e)}function xn(t,e={}){const n=e.measureUncached??!0,s=e.seen;let r=0;for(const i of t.messages)r+=Ze(i,n,s);for(const i of Object.values(t.agentContent)){r+=Ne;for(const o of i.messages)r+=Ze(o,n,s)}for(const i of Object.values(t.markdownAugments))r+=Ze(i,n,s);for(const[i,o]of t.toolUseToAgentEntries)r+=(i.length+o.length)*2+Ne;return r}function so(t){if(t.type!=="user")return!1;const e=t.tempId,n=t.messageMetadata;return typeof e=="string"||n!==void 0}function V(t){return(t._source??"sdk")!=="jsonl"&&so(t)}function ro(t){const e=t.tempId;return typeof e=="string"&&e?e:null}function io(t){const e=t.messageMetadata;if(!e||typeof e!="object")return null;const n=e.deliveryIntent;return typeof n=="string"?n:null}function Hc(t){return t.length>0&&t.every(n=>V(n))?"sent":"confirmed"}function Jc(t){if(t.length===0||!t.every(n=>V(n)))return null;let e=null;for(const n of t){if(io(n)!=="steer")return null;const s=ro(n);if(!s||(e??(e=s),s!==e))return null}return e}const oo=200,Vc=3e3;function qc(t){const e=Math.max(0,t.length-oo);for(let n=t.length-1;n>=e;n-=1){const s=t[n];if(s&&V(s))return!0}return!1}function zc(t){return t.hasUnconfirmedSelfSends||t.pendingSendCount>0}function I(t){return t.uuid??t.id??""}const ao=300*1e3,ht=60*1e3,Oe=60*ht,ke=24*Oe,co=7*ke;function Z(t){if(t==null)return null;const e=typeof t=="number"?t:new Date(t).getTime();return Number.isFinite(e)?e:null}function Yc(t){let e=null;for(const n of t){const s=Z(n.timestamp);s!==null&&(e=e===null?s:Math.max(e,s))}return e}function Kc(t){let e=null;for(const n of t){const s=Z(n.timestamp);s!==null&&(e=e===null?s:Math.min(e,s))}return e}function Xc(t,e,n=ao){return t!=null?e-t>=n:!1}function Zc(t,e){const n=Math.max(0,e-t);if(n<ht)return"now";if(n<Oe)return`${Math.floor(n/ht)}m`;if(n<ke)return`${Math.floor(n/Oe)}h`;if(n<co){const s=Math.floor(n/ke),r=Math.floor(n%ke/Oe);return r>0?`${s}d ${r}h`:`${s}d`}return new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function eu(t){return new Date(t).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium"})}function Je(t,e){const n=t.length-1,s=t[n];if(s&&I(s)===e)return n;for(let r=n-1;r>=0;r-=1){const i=t[r];if(i&&I(i)===e)return r}return-1}function Ve(t){var e;return t.content??((e=t.message)==null?void 0:e.content)}function uo(t){var n;const e=(n=t.message)==null?void 0:n.role;if(e==="user"||e==="assistant"||e==="system")return e;if(t.role==="user"||t.role==="assistant"||t.role==="system")return t.role}function Fe(t){if(t.parentUuid==null)return null;const e=t.type;return e!=="user"&&e!=="assistant"?null:`${t.parentUuid}:${e}:${uo(t)??""}`}function lo(t,e){const n=Fe(e);if(!n)return!1;const s=I(e);return t.some(r=>(r._source??"sdk")!=="jsonl"||I(r)===s?!1:Fe(r)===n)}function ho(t,e){const n=new Set;for(const r of e){const i=Fe(r);i&&n.add(i)}if(n.size===0)return t;const s=t.filter(r=>{if((r._source??"sdk")==="jsonl")return!0;const i=Fe(r);return i?!n.has(i):!0});return s.length===t.length?t:s}function ee(t,e,n){if(!t)return{...e,_source:n};const s=t._source??"sdk";if(n==="jsonl")return{...t,...e,_source:"jsonl"};if(s==="jsonl")return t;const r={...e,_source:"sdk"};return r.tempId===void 0&&t.tempId!==void 0&&(r.tempId=t.tempId),r.messageMetadata===void 0&&t.messageMetadata!==void 0&&(r.messageMetadata=t.messageMetadata),r}function fo(t,e){var c;if(e.length===0)return t;const n=new Map(e.map((d,h)=>[I(d),h]));let s=-1,r=t.length;const i=Z((c=e[0])==null?void 0:c.timestamp);for(let d=0;d<t.length;d+=1){const h=t[d];s=Math.max(s,n.get(I(h))??-1);const f=Z(h.timestamp);r===t.length&&i!==null&&f!==null&&f>i&&(r=d)}const o=[];let a=0;for(let d=0;d<=t.length;d+=1){s<0&&d===r&&(o.push(...e),a=e.length);const h=t[d];if(!h)break;const f=n.get(I(h));if(f===void 0){o.push(h);continue}const m=f===s?e.length:f+1;for(;a<m;)o.push(e[a++])}return o}function mo(t,e,n){const s=new Map(t.map(c=>[I(c),c]));for(const c of e){const d=I(c),h=s.get(d);s.set(d,ee(h,c,"jsonl"))}const r=[],i=new Set,o=n!=null&&n.preserveIncomingOrder?fo(t,e):[...t,...e];for(const c of o){const d=I(c);i.has(d)||(r.push(s.get(d)??c),i.add(d))}const a=ho(r,e);return n!=null&&n.skipDagOrdering?{messages:a}:{messages:Ns(a)}}function En(t,e){if(e.isReplay===!0&&lo(t,e))return{messages:t,index:-1};const n=I(e),s=Je(t,n);if(s>=0){const r=t[s],i=ee(r,e,"sdk");if(r===i||JSON.stringify(r)===JSON.stringify(i))return{messages:t,index:s};const o=[...t];return o[s]=i,{messages:o,index:s}}return{messages:[...t,{...e,_source:"sdk"}],index:t.length}}const _n=2e3,jt=2e3,Rt=3e4,xt=400,po=[`
2
2
 
3
3
  User uploaded files in .attachments:
4
4
  `,`
@@ -8,4 +8,4 @@ User uploaded files:
8
8
  `):null}function bo(t){const e=po.map(a=>({marker:a,index:t.indexOf(a)})).filter(({index:a})=>a!==-1).sort((a,c)=>a.index-c.index)[0];if(!e)return{text:t,attachmentPaths:[]};const n=t.slice(0,e.index),s=t.slice(e.index+e.marker.length),r=/^- \[(?:.+?)\]\((?:<(.+?)>|(.+?))\) \((?:[^)]*)\)$/,i=/^- .+? \([^)]+\): (.+)$/,o=[];for(const a of s.split(`
9
9
  `)){const c=a.trim(),d=c.match(r);if(d){o.push(d[1]??d[2]??"");continue}const h=c.match(i);h&&o.push(h[1]??"")}return{text:n,attachmentPaths:o.filter(a=>a.trim().length>0)}}function qt(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object")return"";const n=e.path;if(typeof n=="string"&&n.trim().length>0)return n;const s=e.id;return typeof s=="string"?s:""}).filter(e=>e.trim().length>0):[]}function Un(t){return t.replace(/\r\n/g,`
10
10
  `).trim()}function Qe(t){var a;const e=ne.get(t);if(e!==void 0)return e;if(!U(t))return ne.set(t,null),null;const n=Dn(t);if(n===null)return ne.set(t,null),null;const s=bo(n),r=new Set([...s.attachmentPaths,...qt(t.attachments),...qt((a=t.message)==null?void 0:a.attachments)]),i=Un(s.text);if(r.size===0)return ne.set(t,null),null;const o=`visible-user|${i}|attachments:${Array.from(r).sort().join("|")}`;return ne.set(t,o),o}function J(t){if(typeof t.timestamp!="string")return null;const e=Date.parse(t.timestamp);return Number.isFinite(e)?e:null}const $n=6e4;function vo(t){return(t._source??"sdk")==="jsonl"&&t.deferredSource==="queue-operation"&&U(t)}function Nn(t){return(t._source??"sdk")==="sdk"&&U(t)}function Io(t){if(!V(t))return!1;const e=t.messageMetadata;return e!==null&&typeof e=="object"&&e.deliveryIntent==="steer"}function Fn(t){const e=Dn(t);return e===null?null:Un(e)}function Co(t){return _t(wo(t),V,$n)}function wo(t){const e=Math.max(0,t.length-xt);let n=null,s=null;for(let d=e;d<t.length;d+=1){const h=t[d];if(!h)continue;const f=vo(h);if(!f&&!Nn(h))continue;const m=J(h),p=Fn(h);if(m===null||!p)continue;const S={index:d,timestampMs:m,text:p};f?(n??(n=[]),n.push(S)):(s??(s=[]),s.push(S))}if(!n||!s)return t;const r=[],i=new Set;for(const d of n){let h=null;for(const f of s){if(i.has(f.index)||f.text!==d.text)continue;const m=Math.abs(f.timestampMs-d.timestampMs);m>$n||(!h||m<Math.abs(h.timestampMs-d.timestampMs))&&(h=f)}h&&(i.add(h.index),r.push({echoIndex:h.index,rowIndex:d.index}))}if(r.length===0)return t;const o=new Map,a=new Set;for(const{echoIndex:d,rowIndex:h}of r){const f=t[d],m=t[h];if(!f||!m)continue;const{uuid:p,...S}=ee(f,m,"jsonl"),g=m.uuid;o.set(Math.min(d,h),typeof g=="string"?{...S,uuid:g}:S),a.add(Math.max(d,h))}if(a.size===0)return t;const c=[];for(let d=0;d<t.length;d+=1){if(a.has(d))continue;const h=o.get(d)??t[d];h&&c.push(h)}return c}function To(t){return(t._source??"sdk")==="jsonl"&&t.deferredSource===void 0&&U(t)}function Ao(t,e,n,s,r){const i=n.filter(c=>!s.has(c.index)&&c.timestampMs<=e+r),o=(c,d)=>{if(c.length===0)return[];for(let h=d;h<i.length;h+=1){const f=i[h];if(!f||!c.startsWith(f.text))continue;let m=c.slice(f.text.length);if(m.length>0){const S=m.replace(/^\s+/,"");if(S.length===m.length)continue;m=S}const p=o(m,h+1);if(p)return[f,...p]}return null},a=o(t,0);return a&&a.length>0?a:null}function _t(t,e,n){const s=Math.max(0,t.length-xt);let r=null,i=null;for(let d=s;d<t.length;d+=1){const h=t[d];if(!h)continue;const f=To(h),m=!f&&Nn(h)&&e(h);if(!f&&!m)continue;const p=J(h),S=Fn(h);if(p===null||!S)continue;const g={index:d,timestampMs:p,text:S};f?(r??(r=[]),r.push(g)):(i??(i=[]),i.push(g))}if(!r||!i)return t;const o=new Map,a=new Set;for(const d of r){const h=Ao(d.text,d.timestampMs,i,a,n);if(!h)continue;const f=t[d.index],m=h[0]&&t[h[0].index];if(!f||!m)continue;const{uuid:p,...S}=ee(m,f,"jsonl"),g=f.uuid,y=h.map(b=>t[b.index].tempId).filter(b=>typeof b=="string");o.set(d.index,{...S,...typeof g=="string"?{uuid:g}:{},...y.length>0?{tempIds:y}:{}});for(const b of h)a.add(b.index)}if(a.size===0)return t;const c=[];for(let d=0;d<t.length;d+=1){if(a.has(d))continue;const h=o.get(d)??t[d];h&&c.push(h)}return c}function Mo(t){return _t(t,Io,jt)}const Po=2e3;function jo(t){return _t(t,V,Po)}function Ln(t,e,n){if(n!=null&&n.excludeTools&&Et(e))return!1;const s=Le(e),r=J(e);if(!s||r===null)return!1;const i=(n==null?void 0:n.windowMs)??_n,o=(n==null?void 0:n.replayWindowMs)??jt,a=(n==null?void 0:n.firstUserTurnWindowMs)??Rt,c=xt,d=Math.max(0,t.length-c);for(let h=t.length-1;h>=d;h-=1){const f=t[h];if((f==null?void 0:f._source)!=="jsonl")continue;const m=J(f);if(m===null)continue;const p=U(f)&&U(e)&&!So(t,h),S=Le(f)===s,g=Qe(f),y=p&&g!==null&&g===Qe(e);if(!S&&!y)continue;const b=kn(f,e,{windowMs:i,replayWindowMs:o,firstUserTurnWindowMs:a},p);if(Math.abs(m-r)<=b)return!0}return!1}function Ro(t,e){const n=(e==null?void 0:e.windowMs)??_n,s=(e==null?void 0:e.replayWindowMs)??jt,r=(e==null?void 0:e.firstUserTurnWindowMs)??Rt,i=Math.max(n,s,r),o=(e==null?void 0:e.excludeTools)===!0,a=t.map((d,h)=>({message:d,originalIndex:h,timestampMs:J(d),fingerprint:Le(d),visibleUserTurnFingerprint:Qe(d)})).sort((d,h)=>d.timestampMs===null&&h.timestampMs===null?d.originalIndex-h.originalIndex:d.timestampMs===null?1:h.timestampMs===null?-1:d.timestampMs!==h.timestampMs?d.timestampMs-h.timestampMs:d.originalIndex-h.originalIndex),c=[];for(const d of a){let h=!1;if(d.fingerprint&&d.timestampMs!==null&&!(o&&Et(d.message)))for(let f=c.length-1;f>=0;f-=1){const m=c[f];if(!m||m.timestampMs===null)continue;if(d.timestampMs-m.timestampMs>i)break;const p=U(m.message)&&U(d.message)&&!yo(c,f),S=m.fingerprint===d.fingerprint,g=p&&m.visibleUserTurnFingerprint!==null&&m.visibleUserTurnFingerprint===d.visibleUserTurnFingerprint;if(!S&&!g)continue;const y=m.message._source,b=d.message._source,v=y===b,M=y!==void 0&&b!==void 0&&!v,_=g&&v&&y==="sdk",G=v&&y!==void 0&&(m.timestampMs===d.timestampMs||_);if(!M&&!G)continue;const w=b??y;if(!w)continue;const O=kn(m.message,d.message,{windowMs:n,replayWindowMs:s,firstUserTurnWindowMs:r},p);if(!(d.timestampMs-m.timestampMs>O)){m.message=ee(m.message,d.message,w),m.timestampMs=J(m.message)??m.timestampMs,m.fingerprint=Le(m.message),m.visibleUserTurnFingerprint=Qe(m.message),h=!0;break}}h||c.push(d)}return c.map(d=>d.message)}const xo=1e4;function se(t){return t==="custom_tool_call"||t==="function_call"}function de(t){return t==null?String(t):typeof t=="string"?JSON.stringify(t):typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"?String(t):Array.isArray(t)?`[${t.map(de).join(",")}]`:typeof t=="object"?`{${Object.entries(t).sort(([n],[s])=>n.localeCompare(s)).map(([n,s])=>`${JSON.stringify(n)}:${de(s)}`).join(",")}}`:String(t)}function ae(t,e){const n=Ve(t);if(!Array.isArray(n))return null;const s=n.find(r=>!!r&&typeof r=="object"&&r.type===e);return s&&typeof s=="object"?s:null}function Eo(t){if(typeof t.name!="string")return null;if(t.name==="ViewImage"){const e=t.input;if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e.path;return typeof n!="string"?null:`${t.name}:${de({path:n})}`}return`${t.name}:${de(t.input)}:${de(t._displayActions)}`}function _o(t,e){const n=e.startedAt??t.timestamp;if(typeof n!="string")return null;const s=Date.parse(n);return Number.isFinite(s)?s:null}function Oo(t){const e=[];for(let n=0;n<t.length;n+=1){const s=t[n];if(!s)continue;const r=st(s),i=ae(s,"tool_use");if(!r||!i)continue;const o=_o(s,r);if(o===null)continue;const a=i.id,c=Eo(i);typeof a!="string"||!c||e.push({fingerprint:c,metadata:r,timestampMs:o,toolUseId:a})}return e}function ko(t,e,n){var o;const s=a=>Array.isArray(a)?a.map(c=>!c||typeof c!="object"||c.type!==e?c:e==="tool_use"?{...c,id:n}:{...c,tool_use_id:n}):a,r=(o=t.message)==null?void 0:o.content,i=t.content;return{...t,...Array.isArray(i)?{content:s(i)}:{},...t.message&&Array.isArray(r)?{message:{...t.message,content:s(r)}}:{}}}function zt(t,e){return{...t,[un]:e}}function Do(t,e){return ee(t,e,(e._source??"sdk")==="jsonl"?"jsonl":"sdk")}function Uo(t){const e=Oo(t),n=e.filter(p=>!se(p.metadata.origin)),s=e.filter(p=>se(p.metadata.origin)),r=new Map,i=new Map;for(const p of t){const S=st(p);S&&(!se(S.origin)&&S.durableCallId&&(r.set(S.itemId,S.durableCallId),i.set(S.durableCallId,S.itemId)),se(S.origin)&&S.liveItemId&&(r.set(S.liveItemId,S.itemId),i.set(S.itemId,S.liveItemId)))}if(r.size===0&&(n.length===0||s.length===0))return t;const o=new Set(r.keys());for(const p of s){if(i.has(p.toolUseId))continue;let S=null,g=Number.POSITIVE_INFINITY;for(const y of n){if(o.has(y.metadata.itemId)||y.metadata.turnId!==p.metadata.turnId||y.fingerprint!==p.fingerprint)continue;const b=Math.abs(y.timestampMs-p.timestampMs);b>xo||b<g&&(S=y,g=b)}S&&(r.set(S.metadata.itemId,p.toolUseId),i.set(p.toolUseId,S.metadata.itemId),o.add(S.metadata.itemId))}if(r.size===0)return t;const a=new Set;let c=!1;const d=t.map(p=>{const S=st(p);if(!S)return p;if(se(S.origin)){const M=ae(p,"tool_use"),_=ae(p,"tool_result"),G=typeof(M==null?void 0:M.id)=="string"?M.id:typeof(_==null?void 0:_.tool_use_id)=="string"?_.tool_use_id:S.itemId,w=i.get(G);return!w||S.liveItemId===w?p:(a.add(G),c=!0,zt(p,{...S,liveItemId:w}))}const g=r.get(S.itemId);if(!g)return p;a.add(g);const y=ae(p,"tool_use")!==null,b=ae(p,"tool_result")!==null;if(!y&&!b)return p;c=!0;const v=ko(p,y?"tool_use":"tool_result",g);return zt({...v,uuid:y?g:`${g}-result`},{...S,durableCallId:g})});if(!c)return t;const h=new Set([...a].flatMap(p=>[p,`${p}-result`])),f=[],m=new Map;for(const p of d){const S=I(p),g=m.get(S);if(g===void 0||!h.has(S)){m.set(S,f.length),f.push(p);continue}const y=f[g];y&&(f[g]=Do(y,p))}return f}class $o{constructor(){l(this,"id","claude-ollama");l(this,"displayName","Claude + Ollama");l(this,"capabilities",{supportsDag:!0,supportsCloning:!0,needsApproxMessageDedup:!1,dedupQueueOperationEchoes:!0});l(this,"metadata",{description:"Legacy Claude SDK transport for local Ollama models. New setups should use Claude Gateway.",limitations:["Deprecated compatibility provider","Model quality varies by model","No token counting","Requires Ollama 0.14+"],website:"https://ollama.com",cliName:"ollama"})}}class No{constructor(){l(this,"id","claude");l(this,"displayName","Claude");l(this,"capabilities",{supportsDag:!0,supportsCloning:!0,needsApproxMessageDedup:!1,dedupQueueOperationEchoes:!0});l(this,"metadata",{description:"Anthropic's Claude Code SDK. Full tool transparency, real-time streaming, and permission modes.",limitations:[],website:"https://claude.ai/download",cliName:"claude"})}}class Fo{constructor(){l(this,"id","claude-gateway");l(this,"displayName","Claude Gateway");l(this,"capabilities",{supportsDag:!0,supportsCloning:!0,needsApproxMessageDedup:!1,dedupQueueOperationEchoes:!0});l(this,"metadata",{description:"Claude Code routed through an isolated Anthropic-compatible LLM gateway.",limitations:["Only gateway-advertised models are available","Model availability and behavior depend on the configured gateway","Reasoning controls depend on the gateway"],website:"https://code.claude.com/docs/en/llm-gateway-connect",cliName:"claude"})}}class Lo{constructor(){l(this,"id","codex");l(this,"displayName","Codex");l(this,"capabilities",{supportsDag:!1,supportsCloning:!0,needsApproxMessageDedup:!1});l(this,"metadata",{description:"OpenAI's Codex CLI. Full editing capabilities with cloud-based reasoning.",limitations:["Edit details not visible (black box)","Best for fire-and-forget tasks"],website:"https://openai.com/index/introducing-codex/",cliName:"codex"})}}class Qo{constructor(){l(this,"id","codex-oss");l(this,"displayName","Codex OSS");l(this,"capabilities",{supportsDag:!1,supportsCloning:!0,needsApproxMessageDedup:!0,approxDedupExcludesTools:!0});l(this,"metadata",{description:"Codex with local models via Ollama. All operations visible through shell commands.",limitations:["Requires Ollama running locally","Model quality varies","More verbose output"],website:"https://github.com/openai/codex",cliName:"codex"})}}class Bo{constructor(){l(this,"id","gemini-acp");l(this,"displayName","Gemini (ACP)");l(this,"capabilities",{supportsDag:!1,supportsCloning:!1,needsApproxMessageDedup:!1});l(this,"metadata",{description:"Google's Gemini CLI via Agent Client Protocol. Full agentic capabilities with server-side tool execution.",limitations:["Requires gemini CLI with --experimental-acp support","Tool execution happens on server"],website:"https://github.com/google-gemini/gemini-cli",cliName:"gemini"})}}class Wo{constructor(){l(this,"id","gemini");l(this,"displayName","Gemini");l(this,"capabilities",{supportsDag:!1,supportsCloning:!1,needsApproxMessageDedup:!1});l(this,"metadata",{description:"Google's Gemini CLI. Read-only tools for code exploration and analysis.",limitations:["Read-only (no file edits or bash commands)","Best for research and planning tasks"],website:"https://github.com/google-gemini/gemini-cli",cliName:"gemini"})}}class Go{constructor(){l(this,"id","grok");l(this,"displayName","Grok Build");l(this,"capabilities",{supportsDag:!1,supportsCloning:!1,needsApproxMessageDedup:!1,dedupSelfSendUserEchoes:!0});l(this,"metadata",{description:"xAI Grok Build via Agent Client Protocol. Experimental integration with structured tool and thinking updates.",limitations:["Requires the grok CLI to be installed and logged in","Session history replay is currently summary-only"],website:"https://docs.x.ai/build",cliName:"grok"})}}class Ho{constructor(){l(this,"id","opencode");l(this,"displayName","OpenCode");l(this,"capabilities",{supportsDag:!1,supportsCloning:!1,needsApproxMessageDedup:!0});l(this,"metadata",{description:"Multi-provider agent with tool streaming via SSE. Supports various LLM backends.",limitations:["Tool approval flow still under investigation","Transcript rendering WIP: 22/48 sampled export parts map to visible blocks","Experimental integration"],website:"https://opencode.ai",cliName:"opencode"})}}class Jo{constructor(){l(this,"id","pi");l(this,"displayName","pi");l(this,"capabilities",{supportsDag:!1,supportsCloning:!1,needsApproxMessageDedup:!0});l(this,"metadata",{description:"Mario Zechner's provider-agnostic coding agent, driven headless via `pi --mode rpc`. Bring-your-own keys across many model providers.",limitations:["Requires the pi CLI to be installed","Some provider-specific controls are still rough-draft compared with the pi TUI","Tools run autonomously — YA permission-mode approval bridge not wired yet"],website:"https://github.com/earendil-works/pi",cliName:"pi"})}}const Qn={codex:new Lo,claude:new No,"claude-gateway":new Fo,"claude-ollama":new $o,gemini:new Wo,"gemini-acp":new Bo,grok:new Go,"codex-oss":new Qo,opencode:new Ho,pi:new Jo};function tu(){return Object.values(Qn)}class Yt{constructor(e){l(this,"capabilities",{supportsDag:!1,supportsCloning:!1,needsApproxMessageDedup:!1});l(this,"metadata");this.id=e,this.metadata={description:"Unknown provider",limitations:[],website:"",cliName:e}}get displayName(){return this.id}}function be(t){return t?Qn[t]??new Yt(t):new Yt("unknown")}const Bn=20,Vo=30,Kt=2,Wn=6e4;function Gn(t){var e;return typeof((e=t.message)==null?void 0:e.content)=="string"?t.message.content:typeof t.content=="string"?t.content:void 0}function Hn(t){var n;const e=((n=t.message)==null?void 0:n.content)??t.content;return Array.isArray(e)?e:void 0}function qo(t){const e=Gn(t);if(e!==void 0)return e;const n=Hn(t);if(!n)return;const s=n.map(r=>r&&typeof r=="object"&&r.type==="text"&&typeof r.text=="string"?r.text:"").filter(Boolean);return s.length>0?s.join(`
11
- `):void 0}function zo(t){const e=Hn(t);return e!==void 0&&e.length>0&&e.every(n=>n!==null&&typeof n=="object"&&n.type==="tool_result")}function Yo(t){var e;return t.isMeta!==!0?!1:((e=qo(t))==null?void 0:e.trimStart().startsWith("Base directory for this skill:"))===!0}function Ko(t){const e=t.trim(),n=/<command-name>[\s\S]*<\/command-name>/.test(e),s=e.replace(/<command-name>[\s\S]*?<\/command-name>/g,"").replace(/<command-message>[\s\S]*?<\/command-message>/g,"").replace(/<command-args>[\s\S]*?<\/command-args>/g,"").trim();return/^<local-command-caveat>[\s\S]*<\/local-command-caveat>$/.test(e)||/^<local-command-stdout>[\s\S]*<\/local-command-stdout>$/.test(e)||n&&s===""}function Xo(t){if(t.isCompactSummary===!0||zo(t)||Yo(t))return!0;const e=Gn(t);return typeof e=="string"&&Ko(e)}function Jn(t){return t.type==="system"&&t.subtype==="compact_boundary"}function Vn(t){var s;const e=(s=t.message)==null?void 0:s.role,n=typeof t.role=="string"?t.role:typeof e=="string"?e:void 0;return(t.type==="user"||n==="user")&&!Xo(t)}function Zo(t){return Jn(t)?"compact_boundary":Vn(t)?"user_turn":null}function ea(t){return t===void 0||!Number.isFinite(t)?Bn:Math.max(1,Math.floor(t))}function ta(t){return t===Bn?Vo:Math.max(t+1,Math.ceil(t*1.5))}function nu({enabled:t,followingBottom:e,historyExpanded:n,tailFrom:s,structuralRevision:r,lastEvaluatedStructuralRevision:i,completedTranscriptGrowth:o,pendingCandidateEligibleAfterMs:a,nowMs:c}){return!t||n||!e||s!==void 0&&s.length>0?!1:r!==i?!0:o&&a!==void 0&&c>a}function su({messages:t,nowMs:e,tailTurns:n}){const s=ea(n),r=ta(s);let i=0,o=0,a=null,c=null,d=!1,h=!1;for(let b=t.length-1;b>=0;b-=1){const v=t[b];if(!v)continue;const M=Zo(v);if(M==="user_turn"){if(i+=1,i===s&&(a=b),i>r){d=!0;break}}else M==="compact_boundary"&&(o+=1,o===Kt&&(c=b),o>Kt&&(h=!0));if(h&&i<s)break}if(!d&&!h)return{kind:"none",reason:"below_threshold"};let f,m;if(d&&a!==null&&(!h||c===null||a>c))f=a,m="user_turn";else if(c!==null)f=c,m="compact_boundary";else return{kind:"none",reason:"below_threshold"};if(f<=0)return{kind:"none",reason:"candidate_at_start"};const p=t[f];if(!p)return{kind:"none",reason:"missing_message_id"};const S=I(p);if(!S)return{kind:"none",reason:"missing_message_id"};const g=Z(p.timestamp);if(g===null)return{kind:"none",reason:"invalid_timestamp"};const y={startIndex:f,startMessageId:S,reason:m,boundaryTimestampMs:g,eligibleAfterMs:g+Wn,turnTarget:s,turnTrigger:r};return e>y.eligibleAfterMs?{kind:"ready",candidate:y}:{kind:"deferred",candidate:y}}const na=new Set(["call_id","parentToolUseId","parent_tool_use_id","toolUseId","tool_use_id"]),sa=new Set(["agentId","agent_id"]);function Xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function z(t,e){if(typeof e!="string")return;const n=e.trim();n&&t.add(n)}function ra(t,e){const n=[/^agentId:\s*([^\s(),]+)/gm,/"agent_id"\s*:\s*"([^"]+)"/g,/"agentId"\s*:\s*"([^"]+)"/g];for(const s of n)for(const r of t.matchAll(s))z(e,r[1])}function ft(t,e,n){if(typeof t=="string"){ra(t,e.agentIds);return}if(typeof t!="object"||t===null||n.has(t))return;if(n.add(t),Array.isArray(t)){for(const r of t)ft(r,e,n);return}const s=t;s.type==="tool_use"&&z(e.toolUseIds,s.id),(s.type==="function_call"||s.type==="function_call_output")&&z(e.toolUseIds,s.call_id),Xt(s.toolUse)&&z(e.toolUseIds,s.toolUse.id),Xt(s.tool_use)&&z(e.toolUseIds,s.tool_use.id);for(const[r,i]of Object.entries(s))na.has(r)&&z(e.toolUseIds,i),sa.has(r)&&z(e.agentIds,i),ft(i,e,n)}function Zt(t,e){const n=new Set;for(const s of t)ft(s,e,n)}function ia(t){return t==="pending"||t==="running"}function oa(t,e,n){const s={agentIds:new Set,toolUseIds:new Set};Zt(t,s);for(const[o,a]of Object.entries(e))ia(a.status)&&s.agentIds.add(o);const r=new Set;let i=!0;for(;i;){i=!1;for(const[o,a]of n)if(s.toolUseIds.has(o)||s.agentIds.has(a)){const c=s.agentIds.size;s.agentIds.add(a),i||(i=s.agentIds.size!==c)}for(const o of Array.from(s.agentIds)){if(r.has(o))continue;r.add(o);const a=e[o];if(!a)continue;const c=s.agentIds.size,d=s.toolUseIds.size;Zt(a.messages,s),i||(i=s.agentIds.size!==c||s.toolUseIds.size!==d)}}return s}function aa(t,e){const n=Object.entries(t).filter(([s])=>e.has(s));return n.length===Object.keys(t).length?t:Object.fromEntries(n)}function ca(t,e){const n=t.filter(([s,r])=>e.toolUseIds.has(s)||e.agentIds.has(r));return n.length===t.length?t:n}function ua(t,e){const n=Object.entries(t).filter(([s])=>e.has(s));return n.length===Object.keys(t).length?t:Object.fromEntries(n)}function da(t,e,n){const s=t.pagination;let r=0,i=0;for(const o of t.messages)Jn(o)&&(r+=1),Vn(o)&&(i+=1);return{hasOlderMessages:!0,totalMessageCount:Math.max((s==null?void 0:s.totalMessageCount)??0,t.messages.length),returnedMessageCount:e.length,truncatedBeforeMessageId:n.startMessageId,totalCompactions:Math.max((s==null?void 0:s.totalCompactions)??0,r),...(s==null?void 0:s.totalUserTurns)!==void 0&&{totalUserTurns:Math.max(s.totalUserTurns,i)},truncatedBy:n.reason}}function la(t,e){const n=Je(t.messages,e.startMessageId);if(n<=0)return t;const s=t.messages[n];if(!s)return t;const r=Z(s.timestamp);if(r===null||e.nowMs<=r+Wn)return t;const i=t.messages.slice(n),o=new Set(i.map(I).filter(c=>c.length>0)),a=oa(i,t.agentContent,t.toolUseToAgentEntries);return{...t,messages:i,activeWindowTrimRevision:t.activeWindowTrimRevision+1,pagination:da(t,i,e),markdownAugments:aa(t.markdownAugments,o),toolUseToAgentEntries:ca(t.toolUseToAgentEntries,a),agentContent:ua(t.agentContent,a.agentIds)}}function Ot(){return{messages:[],session:null,agentContent:{},markdownAugments:{},toolUseToAgentEntries:[],maxPersistedTimestampMs:Number.NEGATIVE_INFINITY,deferredMessages:[],activeWindowTrimRevision:0}}function kt(t,e){return be(t).capabilities.needsApproxMessageDedup||t==="codex"&&!e}function ha(t){return be(t).capabilities.dedupQueueOperationEchoes===!0}function fa(t){return be(t).capabilities.dedupSelfSendUserEchoes===!0}function Dt(t,e){return{excludeTools:be(t).capabilities.approxDedupExcludesTools===!0||t==="codex"&&!e}}function qn(t){return typeof t.yaRecapSource=="string"}function re(t){for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n&&(n._source??"sdk")==="jsonl"&&!qn(n))return I(n)}}function Me(t,e){let n=t;for(const s of e){if(qn(s))continue;const r=J(s);r!==null&&r>n&&(n=r)}return n}function Pe(t){return t.map(e=>({...e,_source:"jsonl"}))}function ma(t,e,n,s){const r=mo(t,e,{skipDagOrdering:!be(n).capabilities.supportsDag,preserveIncomingOrder:n==="codex"&&s});return he(r.messages,n,s)}function pa(t,e,n,s){let r=e;for(const i of t)V(i)&&(r=En(r,i).messages);return he(r,n,s)}function qe(t){const e=t.filter(n=>!n._isStreaming);return e.length===t.length?t:e}function ga(t,e){if(t.tempId===e)return!0;const s=t.tempIds;return Array.isArray(s)&&s.includes(e)}function Sa(t,e){const n=`rewound-group-${e.id}`;if(t.some(g=>I(g)===n))return t;const s=t.findIndex(g=>I(g)===e.cutMessageId);if(s<0)return t;const r=t[s],i=typeof r.rewoundGroupId=="string"&&r.rewoundGroupId?r.rewoundGroupId:void 0,o=i?{rewoundParentGroupId:i}:void 0;let a=0,c=-1;const d=new Set,h=t.slice(s+1).map((g,y)=>{const b=g;if(b.rewoundGroupId||typeof b.timestamp=="string"&&b.timestamp>e.at)return g;a+=1,c<0&&(c=y);const v=I(g);return v&&d.add(v),{...g,rewoundGroupId:e.id,...o}});if(a===0)return t;const f=new Set;for(const g of h){const y=g;y.subtype==="rewound_group"&&typeof y.rewoundGroupId=="string"&&y.rewoundGroupId!==e.id&&(y.rewoundParentGroupId||typeof y.parentUuid=="string"&&d.has(y.parentUuid)&&f.add(y.rewoundGroupId))}const m=f.size?h.map(g=>{const y=g.rewoundGroupId;return typeof y=="string"&&f.has(y)?{...g,rewoundParentGroupId:e.id}:g}):h,p=r.timestamp,S={type:"system",subtype:"rewound_group",uuid:n,id:n,parentUuid:e.cutMessageId,timestamp:typeof p=="string"?p:e.at,content:"",isSynthetic:!0,rewoundGroupId:e.id,...o,rewoundGroup:{reason:e.reason,cutTurnIndex:e.cutTurnIndex,droppedTurnCount:e.droppedTurnCount,rowCount:a,at:e.at,...e.clearloopIteration!==void 0?{clearloopIteration:e.clearloopIteration}:{},...e.clearloopTotal!==void 0?{clearloopTotal:e.clearloopTotal}:{},...e.clearloopPrompt?{clearloopPrompt:e.clearloopPrompt}:{}}};return[...t.slice(0,s+1),...m.slice(0,c),S,...m.slice(c)]}function ya(t,e){const n=t.filter(s=>!V(s)||!ga(s,e));return n.length===t.length?t:n}function ba(t){var n;if(t.type!=="assistant")return!1;const e=(n=t.message)==null?void 0:n.content;return typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.every(s=>{if(!s||typeof s!="object")return!0;const r=s;return r.type==="text"?typeof r.text!="string"||r.text.trim()==="":r.type==="thinking"?typeof r.thinking!="string"||r.thinking.trim()==="":!1}):!1}function he(t,e,n){const s=e==="codex"||e==="codex-oss"?Uo(t):t,r=kt(e,n)?Ro(s,Dt(e,n)):s,i=e==="codex-oss"||e==="codex"&&!n?Mo(r):r,o=fa(e)?jo(i):i;return ha(e)?Co(o):o}function va(t,e){return t===void 0?e:e===void 0?t:Math.max(t,e)}function Ia(t,e,n){if(!t)return;const s=va(t.totalUserTurns,e==null?void 0:e.totalUserTurns);return{...t,totalMessageCount:Math.max(t.totalMessageCount,(e==null?void 0:e.totalMessageCount)??0,n),returnedMessageCount:Math.max(t.returnedMessageCount,(e==null?void 0:e.returnedMessageCount)??0,n),totalCompactions:Math.max(t.totalCompactions,(e==null?void 0:e.totalCompactions)??0),...s!==void 0&&{totalUserTurns:s}}}function Ca(t,e){var m;const n=(m=t.session)==null?void 0:m.provider,s=e.message,r=s.isReplay===!0,i=J(s),o=I(s),a=o!==void 0&&t.messages.some(p=>(p._source??"sdk")==="jsonl"&&I(p)===o),c=r&&(n==="codex"&&e.codexStreamDurableIdAlignment===!0?a:i!==null&&i<=t.maxPersistedTimestampMs);if(s._isStreaming===!0&&e.streamingEnabled===!1){const p=qe(t.messages);return p===t.messages?t:{...t,messages:p}}if(c||(e.fromBufferedReplay||r)&&kt(n,e.codexStreamDurableIdAlignment===!0)&&(ba(s)||Ln(t.messages,s,Dt(n,e.codexStreamDurableIdAlignment===!0))))return t;const h=En(t.messages,s),f=he(h.messages,n,e.codexStreamDurableIdAlignment===!0);return f===t.messages?t:{...t,messages:f}}function wa(t,e,n,s){const r=t[e]??{messages:[],status:"running"};if(n._isStreaming===!0&&s===!1){const o=qe(r.messages);if(o===r.messages)return t;if(o.length===0&&r.contextUsage===void 0){const a={...t};return delete a[e],a}return{...t,[e]:{...r,messages:o}}}const i=I(n);return Je(r.messages,i)!==-1?t:{...t,[e]:{...r,messages:[...r.messages,n],status:"running"}}}function Ta(t,e){const n=wa(t.agentContent,e.agentId,e.message,e.streamingEnabled);return n===t.agentContent?t:{...t,agentContent:n}}function zn(t,e){const n=I(e);if(!n)return t;const s=Je(t,n);if(s>=0){const r=[...t];return r[s]=e,r}return[...t,e]}function Aa(t,e,n){const s=t[e]??{messages:[],status:"running"},r=zn(s.messages,n);return r===s.messages?t:{...t,[e]:{...s,messages:r}}}function Ma(t,e,n){const s=t[e];if(s){const r=new Set(n.messages.map(o=>I(o))),i=s.messages.filter(o=>!r.has(I(o)));return{...t,[e]:{messages:[...n.messages,...i],status:s.status==="running"?"running":n.status}}}return{...t,[e]:n}}function Pa(t,e,n){const s=t[e]??{messages:[],status:"running"};return{...t,[e]:{...s,contextUsage:n}}}function ja(t,e){const n=t[e];if(!n)return t;const s=qe(n.messages);return s===n.messages?t:{...t,[e]:{...n,messages:s}}}function Ra(t,e,n,s){if(kt(n,s))for(const r of e){if((r._source??"sdk")!=="jsonl")continue;const i=I(r);if(i&&Ln([r],t,Dt(n,s)))return i}}function je(t,e,n,s,r=t.markdownAugments){const i=Object.entries(r);if(i.length===0)return r;const o=new Set(e.map(d=>I(d)).filter(Boolean)),a=new Map(t.messages.map(d=>[I(d),d]).filter(([d])=>d.length>0));let c=r;for(const[d,h]of i){if(o.has(d))continue;const f=a.get(d);if(!f)continue;const m=Ra(f,e,n,s);!m||m===d||(c===r&&(c={...r}),c[m]||(c[m]=h),delete c[d])}return c}function Yn(t,e){var n;switch(e.type){case"restoreRouteSnapshot":return{...t,messages:e.snapshot.messages,session:e.snapshot.session,pagination:e.snapshot.pagination,agentContent:e.snapshot.agentContent,markdownAugments:e.snapshot.markdownAugments??{},toolUseToAgentEntries:e.snapshot.toolUseToAgentEntries,deferredMessages:[],lastMessageId:e.snapshot.lastMessageId??re(e.snapshot.messages),maxPersistedTimestampMs:e.snapshot.maxPersistedTimestampMs};case"loadPersistedTranscript":{const s=Pe(e.messages),r=he(s,e.session.provider,e.codexStreamDurableIdAlignment===!0),i=e.markdownAugments?{...t.markdownAugments,...e.markdownAugments}:t.markdownAugments;return{...t,messages:r,session:e.session,pagination:e.pagination,agentContent:e.agentContent??{},markdownAugments:je(t,r,e.session.provider,e.codexStreamDurableIdAlignment===!0,i),toolUseToAgentEntries:e.toolUseToAgentEntries??[],deferredMessages:e.deferredMessages??[],lastMessageId:re(r),maxPersistedTimestampMs:Me(Number.NEGATIVE_INFINITY,s)}}case"setSessionMetadata":return e.session===t.session?t:{...t,session:e.session};case"applyStreamMessage":return Ca(t,e);case"applyStreamSubagentMessage":return Ta(t,e);case"upsertStreamingPlaceholder":{if(e.agentId){const r=Aa(t.agentContent,e.agentId,e.message);return r===t.agentContent?t:{...t,agentContent:r}}const s=zn(t.messages,e.message);return s===t.messages?t:{...t,messages:s}}case"mergeLoadedAgentContent":return{...t,agentContent:Ma(t.agentContent,e.agentId,e.content)};case"updateAgentContextUsage":return{...t,agentContent:Pa(t.agentContent,e.agentId,e.contextUsage)};case"clearAgentStreamingPlaceholders":{const s=ja(t.agentContent,e.agentId);return s===t.agentContent?t:{...t,agentContent:s}}case"clearStreamingPlaceholders":{const s=qe(t.messages);return s===t.messages?t:{...t,messages:s}}case"removeUnconfirmedSelfSend":{const s=ya(t.messages,e.tempId);return s===t.messages?t:{...t,messages:s}}case"applyRewind":{const s=Sa(t.messages,e.record);return s===t.messages?t:{...t,messages:s}}case"registerToolUseAgent":return t.toolUseToAgentEntries.some(([s])=>s===e.toolUseId)?t:{...t,toolUseToAgentEntries:[...t.toolUseToAgentEntries,[e.toolUseId,e.agentId]]};case"applyCatchupMessages":{const s=Pe(e.messages),r=e.session??t.session,i=r==null?void 0:r.provider,o=ma(t.messages,s,i,e.codexStreamDurableIdAlignment===!0);return{...t,messages:o,session:r,pagination:Ia(t.pagination,e.pagination,o.length),markdownAugments:je(t,o,i,e.codexStreamDurableIdAlignment===!0),lastMessageId:re(o),maxPersistedTimestampMs:Me(t.maxPersistedTimestampMs,s)}}case"replaceTailWindow":{const s=Pe(e.messages),r=pa(t.messages,s,e.session.provider,e.codexStreamDurableIdAlignment===!0);return{...t,messages:r,session:e.session,pagination:e.pagination,markdownAugments:je(t,r,e.session.provider,e.codexStreamDurableIdAlignment===!0),lastMessageId:re(r),maxPersistedTimestampMs:Me(t.maxPersistedTimestampMs,s)}}case"trimLoadedWindow":return la(t,e);case"prependOlderMessages":{const s=Pe(e.messages),r=(n=t.session)==null?void 0:n.provider,i=[...s,...t.messages],o=he(i,r,e.codexStreamDurableIdAlignment===!0);return{...t,messages:o,pagination:e.pagination??t.pagination,markdownAugments:je(t,o,r,e.codexStreamDurableIdAlignment===!0),lastMessageId:re(o),maxPersistedTimestampMs:Me(t.maxPersistedTimestampMs,s)}}case"applyFinalMarkdownAugment":{const s=t.markdownAugments[e.messageId];return(s==null?void 0:s.html)===e.augment.html?t:{...t,markdownAugments:{...t.markdownAugments,[e.messageId]:e.augment}}}}}function mt(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}function en(t){return Yn(Ot(),{type:"restoreRouteSnapshot",snapshot:t})}function xa(t,e){if(t.session)return{messages:t.messages,session:t.session,pagination:t.pagination,agentContent:t.agentContent,markdownAugments:t.markdownAugments,toolUseToAgentEntries:t.toolUseToAgentEntries,lastMessageId:t.lastMessageId,maxPersistedTimestampMs:t.maxPersistedTimestampMs,scrollSnapshot:e?mt(e):void 0}}class Ea{constructor(){l(this,"stateValue");l(this,"subscriptions",new Set)}get hasSubscriptions(){return this.subscriptions.size>0}get state(){return this.stateValue}initialize(e){this.stateValue||(this.stateValue=e)}replaceState(e){this.stateValue=e,this.notify()}resetState(){return this.stateValue?(this.stateValue=Ot(),this.notify(),!0):!1}clear(){return this.stateValue?(this.stateValue=void 0,this.notify(),!0):!1}subscribe(e,n,s){const r={selector:e,listener:n,equality:s,value:e(this.state)};return this.subscriptions.add(r),()=>{this.subscriptions.delete(r)}}notify(){for(const e of Array.from(this.subscriptions)){const n=e.selector(this.stateValue);e.equality(e.value,n)||(e.value=n,e.listener())}}}const _a=300*1e3,Oa=3,ka=24*1024*1024,ve={ttlMs:_a,maxEntries:Oa,maxBytes:ka};function ru(t){Object.assign(ve,t)}function iu(){return{...ve}}function k(t){return(t==null?void 0:t.nowMs)??Date.now()}function ie(t){return(t==null?void 0:t.ttlMs)??ve.ttlMs}function Da(t){return(t==null?void 0:t.maxEntries)??ve.maxEntries}function et(t){return(t==null?void 0:t.maxBytes)??ve.maxBytes}class Ua{constructor(e,n){l(this,"metadata",null);l(this,"scrollSnapshotValue");l(this,"store",new Ea);this.key=e,this.input=n}get hasRecord(){return this.metadata!==null}get hasSubscriptions(){return this.store.hasSubscriptions}get state(){return this.metadata?this.store.state:void 0}get retainCount(){var e;return((e=this.metadata)==null?void 0:e.retainCount)??0}get approxBytes(){var e;return((e=this.metadata)==null?void 0:e.approxBytes)??0}get scrollSnapshot(){return this.scrollSnapshotValue}get lastAccessedAt(){var e;return((e=this.metadata)==null?void 0:e.lastAccessedAt)??0}markAccessed(e){this.metadata&&(this.metadata.lastAccessedAt=e)}ensureRecord(e,n){return this.metadata||(this.metadata={retainCount:0,createdAt:e,updatedAt:e,lastAccessedAt:e,expiresAt:e+ie(n),approxBytes:0},this.store.initialize(Ot())),this.metadata}replaceState(e,n,s,r,i){const o=this.metadata;this.metadata={retainCount:(o==null?void 0:o.retainCount)??0,createdAt:(o==null?void 0:o.createdAt)??n,updatedAt:n,lastAccessedAt:n,expiresAt:n+ie(s),approxBytes:r},this.store.replaceState(e),this.scrollSnapshotValue=i?mt(i):void 0}applyState(e,n,s,r){const i=this.ensureRecord(n,s);i.updatedAt=n,i.lastAccessedAt=n,i.expiresAt=n+ie(s),i.approxBytes=r,this.store.replaceState(e)}setScrollSnapshot(e,n){return this.metadata?(this.scrollSnapshotValue=mt(e),this.metadata.updatedAt=n,this.metadata.lastAccessedAt=n,!0):!1}clearScrollSnapshot(){return this.scrollSnapshotValue?(this.scrollSnapshotValue=void 0,!0):!1}resetState(e,n){!this.metadata||!this.store.resetState()||(this.metadata.updatedAt=e,this.metadata.lastAccessedAt=e,this.metadata.expiresAt=e+ie(n),this.metadata.approxBytes=0)}incrementRetain(e,n){const s=this.ensureRecord(e,n);s.retainCount+=1,s.lastAccessedAt=e}release(e,n){this.metadata&&(this.metadata.retainCount=Math.max(0,this.metadata.retainCount-1),this.metadata.lastAccessedAt=e,this.metadata.expiresAt=e+ie(n))}deleteRecord(){return this.metadata?(this.metadata=null,this.scrollSnapshotValue=void 0,this.store.clear(),!0):!1}deleteIfExpired(e){return!this.metadata||this.metadata.retainCount>0||this.metadata.expiresAt>e?!1:this.deleteRecord()}subscribe(e,n,s){return this.store.subscribe(e,n,s)}toStats(){const e=this.state;if(!this.metadata||!e)throw new Error("Cannot build stats for an empty session detail entry");return{key:this.key,sourceKey:this.input.sourceKey,projectId:this.input.projectId,sessionId:this.input.sessionId,tailTurns:this.input.tailTurns,tailFrom:this.input.tailFrom,messageCount:e.messages.length,agentEntryCount:Object.keys(e.agentContent).length,approxBytes:this.metadata.approxBytes,retainCount:this.metadata.retainCount,createdAt:this.metadata.createdAt,updatedAt:this.metadata.updatedAt,lastAccessedAt:this.metadata.lastAccessedAt,expiresAt:this.metadata.expiresAt,hasScrollSnapshot:this.scrollSnapshotValue!==void 0}}estimateBytes(e){const n=this.state;return n?xn(n,e):0}}function Re(t){return encodeURIComponent(t)}function F({sourceKey:t,projectId:e,sessionId:n,initialHistoryCompactions:s,tailTurns:r,tailFrom:i}){const o=[Re(t),Re(e),Re(n)].join(":"),a=[s!==void 0?`initialHistory=${s??"unlimited"}`:"",r!==void 0?`tailTurns=${r}`:"",i?`tailFrom=${Re(i)}`:""].filter(Boolean).join("&");return a?`${o}?${a}`:o}function tt(t,e=!0){return xn(t,{measureUncached:e})}function tn(t){return t.type==="restoreRouteSnapshot"||t.type==="loadPersistedTranscript"}class $a{constructor(){l(this,"entries",new Map)}read(e,n={}){var s;return(s=this.readEntry(e,n))==null?void 0:s.state}readRouteSnapshot(e,n={}){const s=this.readEntry(e,n);return s!=null&&s.state?xa(s.state,s.scrollSnapshot):void 0}readScrollSnapshot(e,n={}){var s;return(s=this.readEntry(e,n))==null?void 0:s.scrollSnapshot}readSelected(e,n,s={}){const r=this.read(e,s);return r?n(r):void 0}writeRouteSnapshot(e,n,s={}){const r=k(s),i=F(e);this.evictExpired({nowMs:r});const o=en(n),a=tt(o);if(a>et(s)){const d=this.entries.get(i);return(!d||d.retainCount===0)&&this.deleteRecordByKey(i),!1}return this.getOrCreateEntry(e).replaceState(o,r,s,a,n.scrollSnapshot),this.evictLeastRecentlyUsed(s),!0}replaceRouteSnapshot(e,n,s={}){const r=k(s),i=F(e);this.evictExpired({nowMs:r});const o=en(n),a=tt(o);return this.getOrCreateEntry(e).replaceState(o,r,s,a,n.scrollSnapshot),this.evictLeastRecentlyUsed(s,new Set([i])),!0}dispatch(e,n,s={}){const r=k(s),i=F(e),o=this.entries.get(i);if(!(o!=null&&o.hasRecord)&&!tn(n))return;const a=o!=null&&o.hasRecord?o:this.ensureEntry(e,r,s),c=a.state;if(!c)return;const d=Yn(c,n);if(d===c)return a.markAccessed(r),c;const h=tt(d,tn(n));a.applyState(d,r,s,h);const f=n.type==="restoreRouteSnapshot"?n.snapshot.scrollSnapshot:n.type==="loadPersistedTranscript"?n.scrollSnapshot:void 0;if(f&&a.setScrollSnapshot(f,r),a.approxBytes>et(s)&&a.retainCount===0){this.deleteRecordByKey(i);return}return this.evictLeastRecentlyUsed(s),d}patchScrollSnapshot(e,n,s={}){const r=k(s),i=F(e),o=this.entries.get(i);!o||this.deleteIfExpired(o,r)||o.setScrollSnapshot(n,r)}subscribe(e,n,s,r=Object.is){const i=this.getOrCreateEntry(e),o=i.subscribe(n,s,r);return()=>{o(),this.deleteEntryIfIdle(i)}}retain(e,n={}){const s=k(n);this.ensureEntry(e,s,n).incrementRetain(s,n);let i=!1;return()=>{i||(i=!0,this.release(e,{...n,nowMs:k(n)}))}}release(e,n={}){const s=k(n),r=this.entries.get(F(e));r&&(r.release(s,n),this.deleteEntryIfIdle(r))}evictExpired(e={}){const n=k(e);let s=0;for(const r of Array.from(this.entries.values()))this.deleteIfExpired(r,n)&&(s+=1);return s}clear(){for(const e of Array.from(this.entries.values()))e.retainCount>0||(e.deleteRecord(),this.deleteEntryIfIdle(e))}clearScrollSnapshots(){for(const e of Array.from(this.entries.values()))e.clearScrollSnapshot()}deleteEntry(e){const n=F(e);return this.deleteRecordByKey(n)}resetEntryState(e,n={}){const s=k(n),r=F(e),i=this.entries.get(r);if(!i)return;const o=i.state;!o||o.session===null&&o.messages.length===0||i.resetState(s,n)}getStats(){const e=this.recordEntries(),n=e.filter(i=>i.retainCount>0),s=e.filter(i=>i.retainCount===0),r=e.map(i=>i.toStats());return{entryCount:r.length,retainedEntryCount:n.length,warmCacheEntryCount:s.length,approxBytes:nt(e),dedupedApproxBytes:this.dedupedApproxBytes(e),retainedApproxBytes:nt(n),retainedDedupedApproxBytes:this.dedupedApproxBytes(n),warmCacheApproxBytes:nt(s),warmCacheDedupedApproxBytes:this.dedupedApproxBytes(s),entries:r}}ensureEntry(e,n,s){const r=this.getOrCreateEntry(e);return r.ensureRecord(n,s),r}readEntry(e,n){const s=k(n),r=F(e),i=this.entries.get(r);if(i&&!this.deleteIfExpired(i,s))return i.markAccessed(s),i}deleteIfExpired(e,n){const s=e.deleteIfExpired(n);return s&&this.deleteEntryIfIdle(e),s}evictLeastRecentlyUsed(e,n=new Set){const s=Da(e),r=et(e),i=()=>this.recordEntries().filter(a=>a.retainCount===0&&!n.has(a.key)).sort((a,c)=>a.lastAccessedAt-c.lastAccessedAt);for(;this.recordEntries().length>s;){const a=i()[0];if(!a)break;a.deleteRecord(),this.deleteEntryIfIdle(a)}let o=0;for(const a of this.recordEntries())o+=a.approxBytes;if(!(o<=r))for(;this.dedupedApproxBytes()>r;){const a=i()[0];if(!a)break;a.deleteRecord(),this.deleteEntryIfIdle(a)}}dedupedApproxBytes(e=this.recordEntries()){const n=new Set;let s=0;for(const r of e)s+=r.estimateBytes({measureUncached:!1,seen:n});return s}getOrCreateEntry(e){const n=F(e);let s=this.entries.get(n);return s||(s=new Ua(n,e),this.entries.set(n,s)),s}deleteRecordByKey(e){const n=this.entries.get(e);if(!n)return!1;const s=n.deleteRecord();return this.deleteEntryIfIdle(n),s}deleteEntryIfIdle(e){!e.hasRecord&&!e.hasSubscriptions&&this.entries.delete(e.key)}recordEntries(){return Array.from(this.entries.values()).filter(e=>e.hasRecord)}}function nt(t){return t.reduce((e,n)=>e+n.approxBytes,0)}function Na(){return new $a}const Ie=Na();function ou(){Ie.clear()}function au(){Ie.clearScrollSnapshots()}function cu(){return Ie.evictExpired()}function uu(){const t=Ie.getStats();return{totalBytes:t.dedupedApproxBytes,liveRetainedBytes:t.retainedDedupedApproxBytes,liveRetainedEntryCount:t.retainedEntryCount,warmCacheBytes:t.warmCacheDedupedApproxBytes,warmCacheEntryCount:t.warmCacheEntryCount}}const nn={kind:"localhost"},Fa={kind:"secure"};function La(t){switch(t.kind){case"localhost":return new Bs(t.options);case"websocket":return new Hs(t.options);case"secure":return new Js(t.options);case"custom":return t.createTransport()}}function Qa(t,e){return t.kind!==e.kind?!1:t.kind==="custom"&&e.kind==="custom"?t.createTransport===e.createTransport:!0}const Ba={getSession:t=>{const{projectId:e,sessionId:n}=t;if(t.fullHistory===!0){if(!t.fullHistoryReason.trim())throw new Error("Full-history session request requires a reason.");return xe.getSession(e,n,void 0,{fullHistory:!0,fullHistoryReason:t.fullHistoryReason,...t.tailTurns!==void 0?{tailTurns:t.tailTurns}:{},...t.tailFrom?{tailFrom:t.tailFrom}:{}})}const{afterMessageId:s,tailCompactions:r,beforeMessageId:i,tailTurns:o}=t,{tailFrom:a}=t;let c;if(!(!!s||r!==void 0||i!==void 0||o!==void 0||a!==void 0))throw new Error("Session detail request requires bounds or explicit fullHistory.");return(r!==void 0||i!==void 0||o!==void 0||a!==void 0)&&(c={tailCompactions:r,beforeMessageId:i,tailTurns:o,tailFrom:a}),c?xe.getSession(e,n,s,c):xe.getSession(e,n,s)},getSessionMetadata:({projectId:t,sessionId:e})=>xe.getSessionMetadata(t,e)},Wa={cache:Ie};function Ga(t,e){return{sourceKey:t,getStore:()=>$(t),getSnapshot:()=>Ji(t),clear:()=>Pi(t),retainActivitySubscription:()=>jn(t,e()),retainDraftDecorations:()=>Rn(t),reportGlobalSessionsCollectionSnapshot:(n,s)=>{Vi(t,n,s)},reportInboxCollectionSnapshot:(n,s)=>{qi(t,n,s)},reportProjectsCollectionSnapshot:(n,s)=>{zi(t,n,s)},reportProjectCollectionSnapshot:(n,s)=>{Yi(t,n,s)},reportProjectQueueCollectionSnapshot:(n,s)=>{Ki(t,n,s)},reportProjectQueueGlobalCollectionSnapshot:(n,s)=>{Xi(t,n,s)},reportProviderRuntimeStatusSnapshot:(n,s)=>{Qi(t,n,s)},reportSessionCollectionCreated:(n,s)=>{Zi(t,n,s)},reportSessionCollectionMetadataChanged:(n,s)=>{eo(t,n,s)}}}class Ha{constructor(e={}){l(this,"runtimes",new Map);l(this,"transports",new Map);l(this,"transportRegistrations",new Map);l(this,"apiClient");l(this,"sessionDetails");l(this,"defaultTransportRegistration");l(this,"createSummaryRuntime");l(this,"readCurrentSourceKey");l(this,"writeCurrentSourceKey");this.apiClient=e.apiClient??Ba,this.sessionDetails=e.sessionDetails??Wa,this.defaultTransportRegistration=e.defaultTransportRegistration??nn,this.createSummaryRuntime=e.createSummaryRuntime??Ga,this.readCurrentSourceKey=e.getCurrentSourceKey??dt,this.writeCurrentSourceKey=e.setCurrentSourceKey??Mi}registerSourceTransport(e,n){const s=this.resolveTransportRegistration(e);this.transportRegistrations.set(e,n);const r=this.transports.get(e);if(!r)return this.createAndStoreTransport(e,n);if(Qa(s,n))return r;r.dispose();const i=this.createAndStoreTransport(e,n),o=this.runtimes.get(e);return o&&(o.transport=i),i}getOrCreateSourceTransport(e){const n=this.transports.get(e);return n||this.createAndStoreTransport(e,this.resolveTransportRegistration(e))}getOrCreateSourceRuntime(e){let n=this.runtimes.get(e);if(!n){const s=this.getOrCreateSourceTransport(e),r={sourceKey:e,transport:s,api:this.apiClient,summary:null,sessionDetails:this.sessionDetails};r.summary=this.createSummaryRuntime(e,()=>r.transport),n=r,this.runtimes.set(e,n)}return n}getCurrentSourceRuntime(){return this.getOrCreateSourceRuntime(this.readCurrentSourceKey())}setCurrentSourceKey(e){this.writeCurrentSourceKey(e)}disposeSource(e){var n;this.runtimes.delete(e),(n=this.transports.get(e))==null||n.dispose(),this.transports.delete(e),this.transportRegistrations.delete(e)}resetForTests(){for(const e of this.transports.values())e.dispose();this.runtimes.clear(),this.transports.clear(),this.transportRegistrations.clear()}resolveTransportRegistration(e){const n=this.transportRegistrations.get(e);return n||(e===Pn?nn:e===wi?Fa:this.defaultTransportRegistration)}createAndStoreTransport(e,n){const s=La(n);return this.transports.set(e,s),s}}const Ja=new Ha;function Va(){return Ja}async function u(t,e){return Va().getCurrentSourceRuntime().transport.fetch(t,e)}const qa={getAuthStatus:()=>u("/auth/status"),enableAuth:t=>u("/auth/enable",{method:"POST",body:JSON.stringify({password:t})}),disableAuth:()=>u("/auth/disable",{method:"POST"}),setupAccount:t=>u("/auth/setup",{method:"POST",body:JSON.stringify({password:t})}),login:(t,e)=>u("/auth/login",{method:"POST",body:JSON.stringify(e?{password:t,username:e}:{password:t})}),logout:()=>u("/auth/logout",{method:"POST"}),changePassword:t=>u("/auth/change-password",{method:"POST",body:JSON.stringify({newPassword:t})}),setLocalhostAccess:t=>u("/auth/localhost-access",{method:"POST",body:JSON.stringify({open:t})})},za={getActingPrincipal:()=>u("/users/me"),listUsers:()=>u("/users"),getUserUsage:()=>u("/users/usage"),createUser:t=>u("/users",{method:"POST",body:JSON.stringify(t)}),updateUser:(t,e)=>u(`/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)}),deleteUser:t=>u(`/users/${encodeURIComponent(t)}`,{method:"DELETE"}),switchUser:t=>u("/users/switch",{method:"POST",body:JSON.stringify({username:t})}),logoutUser:()=>u("/users/logout",{method:"POST"})},Ya={getBrowserProfiles:()=>u("/browser-profiles"),deleteBrowserProfile:t=>u(`/browser-profiles/${encodeURIComponent(t)}`,{method:"DELETE"})},Ka={getFile:(t,e,n=!1,s,r,i)=>{const o=new URLSearchParams({path:e});return n&&o.set("highlight","true"),s!==void 0&&o.set("line",String(s)),r!==void 0&&o.set("lineEnd",String(r)),i==="range"&&o.set("view","range"),u(`/projects/${t}/files?${o.toString()}`)},getFileRawUrl:(t,e,n=!1)=>{const s=new URLSearchParams({path:e});return n&&s.set("download","true"),`/api/projects/${t}/files/raw?${s.toString()}`},expandDiffContext:(t,e,n,s,r)=>u(`/projects/${t}/diff/expand`,{method:"POST",body:JSON.stringify({filePath:e,oldString:n,newString:s,originalFile:r})})},Xa={getGitStatus:(t,e={})=>{const n=e.useUntrackedCache?"cache":e.omitUntracked?"none":null;return u(`/projects/${t}/git${n?`?untracked=${n}`:""}`)},getGitUntrackedFolder:(t,e)=>u(`/projects/${t}/git/untracked-folder?path=${encodeURIComponent(e)}`),listGitUntrackedFiles:(t,e={})=>{const n=new URLSearchParams;e.path&&n.set("path",e.path),e.q&&n.set("q",e.q);const s=n.size>0?`?${n.toString()}`:"";return u(`/projects/${t}/git/untracked-files${s}`)},checkGitRemote:t=>u(`/projects/${t}/git/check-remote`,{method:"POST"}),getGitIncomingCommits:t=>u(`/projects/${t}/git/incoming-commits`),getGitIntegrationOptions:t=>u(`/projects/${t}/git/integration-options`),pullGit:t=>u(`/projects/${t}/git/pull`,{method:"POST"}),pushGit:t=>u(`/projects/${t}/git/push`,{method:"POST"}),getGitDiff:(t,e)=>u(`/projects/${t}/git/diff`,{method:"POST",body:JSON.stringify(e)}),getGitCommits:(t,e)=>{const n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.set("limit",String(e.limit)),(e==null?void 0:e.skip)!==void 0&&n.set("skip",String(e.skip));const s=n.toString()?`?${n.toString()}`:"";return u(`/projects/${t}/git/commits${s}`)},getGitCommit:(t,e)=>u(`/projects/${t}/git/commit/${encodeURIComponent(e)}`),getGitCommitSearchManifest:t=>u(`/projects/${t}/git/commit-search-manifest`),getGitCommitSearchRecords:(t,e)=>u(`/projects/${t}/git/commit-search-records`,{method:"POST",body:JSON.stringify({shas:e})}),getGitCommitDiff:(t,e)=>u(`/projects/${t}/git/commit-diff`,{method:"POST",body:JSON.stringify(e)}),getGitComparison:(t,e)=>u(`/projects/${t}/git/compare/${encodeURIComponent(e)}`),getGitInclusiveComparison:(t,e)=>u(`/projects/${t}/git/range-to-head/${encodeURIComponent(e)}`),getGitComparisonDiff:(t,e)=>u(`/projects/${t}/git/compare-diff`,{method:"POST",body:JSON.stringify(e)}),getGitInclusiveComparisonDiff:(t,e)=>u(`/projects/${t}/git/range-to-head-diff`,{method:"POST",body:JSON.stringify(e)}),getGitFileProjections:t=>u(`/projects/${t}/git/file-projections`),getGitFileRevision:(t,e)=>{const n=new URLSearchParams({path:e.path});return e.rev&&n.set("rev",e.rev),e.origPath&&n.set("origPath",e.origPath),u(`/projects/${t}/git/file-revision?${n.toString()}`)},getGitFileProjectionDiff:(t,e)=>u(`/projects/${t}/git/file-projection-diff`,{method:"POST",body:JSON.stringify(e)}),getGitBlame:(t,e,n)=>{const s=new URLSearchParams({path:e});return n&&s.set("rev",n),u(`/projects/${t}/git/blame?${s.toString()}`)},listGitFiles:(t,e)=>{const n=new URLSearchParams;e!=null&&e.q&&n.set("q",e.q),(e==null?void 0:e.limit)!==void 0&&n.set("limit",String(e.limit));const s=n.toString()?`?${n.toString()}`:"";return u(`/projects/${t}/git/files${s}`)},listGitWorkingTreeFiles:(t,e)=>{const n=new URLSearchParams;e&&(n.set("tracked",String(e.tracked)),n.set("untracked",String(e.untracked)),n.set("ignored",String(e.ignored)));const s=n.size>0?`?${n.toString()}`:"";return u(`/projects/${t}/git/working-tree-files${s}`)},searchGit:(t,e)=>{const n=new URLSearchParams({q:e.q,kind:e.kind});return e.limit!==void 0&&n.set("limit",String(e.limit)),u(`/projects/${t}/git/search?${n.toString()}`)}},Za={listReviewComments:t=>u(`/projects/${t}/review/comments`),addReviewComment:(t,e,n)=>u(`/projects/${t}/review/comments`,{method:"POST",body:JSON.stringify({anchor:e,text:n})}),updateReviewComment:(t,e,n)=>u(`/projects/${t}/review/comments/${e}`,{method:"PATCH",body:JSON.stringify(n)}),deleteReviewComment:(t,e)=>u(`/projects/${t}/review/comments/${e}`,{method:"DELETE"}),previewReview:t=>u(`/projects/${t}/review/preview`,{method:"POST"}),submitReview:(t,e,n,s,r)=>u(`/projects/${t}/review/submit`,{method:"POST",body:JSON.stringify({include:e,target:n,newSession:s,...r?{submissionId:r.id,name:r.name}:{}})}),listReviewSubmissions:(t,e)=>{const n=new URLSearchParams;e!=null&&e.cursor&&n.set("cursor",e.cursor),e!=null&&e.limit&&n.set("limit",String(e.limit));const s=n.size>0?`?${n}`:"";return u(`/projects/${t}/review/submissions${s}`)},getReviewSubmission:(t,e)=>u(`/projects/${t}/review/submissions/${encodeURIComponent(e)}`),addReviewFollowUp:(t,e,n)=>u(`/projects/${t}/review/sites/${encodeURIComponent(e)}/follow-ups`,{method:"POST",body:JSON.stringify({text:n})}),resolveReviewSite:(t,e)=>u(`/projects/${t}/review/sites/${encodeURIComponent(e)}/resolve`,{method:"POST"}),acknowledgeReviewSubmission:(t,e)=>u(`/projects/${t}/review/submissions/${encodeURIComponent(e)}/acknowledge`,{method:"POST"}),refreshReviewSubmissionResponse:(t,e)=>u(`/projects/${t}/review/submissions/${encodeURIComponent(e)}/refresh-response`,{method:"POST"}),listReviewSiteStates:t=>u(`/projects/${t}/review/submissions?limit=1&includeSiteStates=1`).then(e=>e.siteStates??[]),listReviewInbox:()=>u("/review/inbox")},ec={getOnboardingStatus:()=>u("/onboarding"),completeOnboarding:()=>u("/onboarding/complete",{method:"POST"}),resetOnboarding:()=>u("/onboarding/reset",{method:"POST"})},tc={getPushPublicKey:()=>u("/push/vapid-public-key"),subscribePush:(t,e,n)=>u("/push/subscribe",{method:"POST",body:JSON.stringify({browserProfileId:t,subscription:e,deviceName:n})}),unsubscribePush:t=>u("/push/unsubscribe",{method:"POST",body:JSON.stringify({browserProfileId:t})}),getPushSubscriptions:()=>u("/push/subscriptions"),testPush:(t,e,n,s)=>u("/push/test",{method:"POST",body:JSON.stringify({browserProfileId:t,message:e,urgency:n,deliveryUrgency:s})}),deletePushSubscription:t=>u(`/push/subscriptions/${encodeURIComponent(t)}`,{method:"DELETE"})},nc={getNotificationSettings:()=>u("/push/settings"),updateNotificationSettings:t=>u("/push/settings",{method:"PUT",body:JSON.stringify(t)})},sc={getRecents:t=>u(t?`/recents?limit=${t}`:"/recents"),recordVisit:(t,e)=>u("/recents/visit",{method:"POST",body:JSON.stringify({sessionId:t,projectId:e})}),clearRecents:()=>u("/recents",{method:"DELETE"})},rc={getVersion:t=>u(t!=null&&t.fresh?"/version?fresh=1":"/version"),getServerInfo:()=>u("/server-info"),getEnvSettings:()=>u("/env-settings"),restartServer:()=>u("/server/restart",{method:"POST"})};function ic(t){return{markSessionSeen:(e,n,s,r)=>t(`/sessions/${e}/mark-seen`,{method:"POST",body:JSON.stringify({timestamp:n,messageId:s,nonHumanUserTurnMessageId:r})}),markSessionUnread:e=>t(`/sessions/${e}/mark-seen`,{method:"DELETE"}),searchSessionContent:(e,n)=>t("/sessions/content-search",{method:"POST",body:JSON.stringify(e),signal:n}),getSession:(e,n,s,r)=>{const i=new URLSearchParams;s&&i.set("afterMessageId",s),(r==null?void 0:r.tailCompactions)!==void 0&&i.set("tailCompactions",String(r.tailCompactions)),r!=null&&r.beforeMessageId&&i.set("beforeMessageId",r.beforeMessageId),(r==null?void 0:r.tailTurns)!==void 0&&i.set("tailTurns",String(r.tailTurns)),r!=null&&r.tailFrom&&i.set("tailFrom",r.tailFrom),r!=null&&r.fullHistory&&i.set("fullHistory","1"),r!=null&&r.fullHistoryReason&&i.set("fullHistoryReason",r.fullHistoryReason);const o=i.toString();return t(`/projects/${e}/sessions/${n}${o?`?${o}`:""}`)},getSessionMetadata:(e,n)=>t(`/projects/${e}/sessions/${n}/metadata`),resumeSession:(e,n,s,r,i,o,a,c)=>t(`/projects/${e}/sessions/${n}/resume`,{method:"POST",body:JSON.stringify({message:s,mode:r==null?void 0:r.mode,model:r==null?void 0:r.model,serviceTier:r==null?void 0:r.serviceTier,thinking:r==null?void 0:r.thinking,showThinking:r==null?void 0:r.showThinking,provider:r==null?void 0:r.provider,executor:r==null?void 0:r.executor,recapMode:r==null?void 0:r.recapMode,recapAfterSeconds:r==null?void 0:r.recapAfterSeconds,promptSuggestionMode:r==null?void 0:r.promptSuggestionMode,helperSideModel:r==null?void 0:r.helperSideModel,resumeMode:r==null?void 0:r.resumeMode,attachments:i,tempId:o,clientTimestamp:a,messageMetadata:c})}),reactivateSession:(e,n,s)=>t(`/projects/${e}/sessions/${n}/reactivate`,{method:"POST",body:JSON.stringify({mode:s==null?void 0:s.mode,model:s==null?void 0:s.model,provider:s==null?void 0:s.provider,executor:s==null?void 0:s.executor,recapAfterSeconds:s==null?void 0:s.recapAfterSeconds})}),abortProcess:(e,n)=>t(`/processes/${e}/abort`,{method:"POST",...n!=null&&n.blockResume?{body:JSON.stringify({blockResume:!0})}:{}}),getProcessInfo:e=>t(`/sessions/${e}/process`),updateSessionMetadata:(e,n)=>t(`/sessions/${e}/metadata`,{method:"PUT",body:JSON.stringify(n)}),cloneSession:(e,n,s,r,i)=>t(`/projects/${e}/sessions/${n}/clone`,{method:"POST",body:JSON.stringify({title:s,provider:r,parentSessionId:i})}),sendConversationContext:(e,n,s)=>t(`/projects/${e}/sessions/${n}/conversation-context`,{method:"POST",body:JSON.stringify(s)})}}function du(t){return t.unchanged===!0}function oc(t){const e=new URLSearchParams;t!=null&&t.summaryMode&&e.set("summaryMode",t.summaryMode),t!=null&&t.project&&e.set("project",t.project),t!=null&&t.q&&e.set("q",t.q),t!=null&&t.after&&e.set("after",t.after),t!=null&&t.limit&&e.set("limit",String(t.limit)),t!=null&&t.includeArchived&&e.set("includeArchived","true"),t!=null&&t.starred&&e.set("starred","true"),t!=null&&t.includeStats&&e.set("includeStats","true"),(t==null?void 0:t.knownGeneration)!==void 0&&e.set("knownGeneration",String(t.knownGeneration));const n=e.toString();return u(n?`/sessions?${n}`:"/sessions")}const xe={...ic(u),...rc,getNetworkBinding:()=>u("/network-binding"),setNetworkBinding:t=>u("/network-binding",{method:"PUT",body:JSON.stringify(t)}),disableNetworkBinding:()=>u("/network-binding",{method:"DELETE"}),getProviders:t=>u(t!=null&&t.refresh?"/providers?refresh=1":"/providers",t!=null&&t.refresh?{headers:{"Cache-Control":"no-cache"}}:void 0),getProvider:(t,e)=>u(`/providers/${encodeURIComponent(t)}${e!=null&&e.refresh?"?refresh=1":""}`,e!=null&&e.refresh?{headers:{"Cache-Control":"no-cache"}}:void 0),getProviderSubscriptionUsage:(t,e)=>u(`/providers/${encodeURIComponent(t)}/subscription-usage${e!=null&&e.refresh?"?refresh=1":""}`,e!=null&&e.refresh?{headers:{"Cache-Control":"no-cache"}}:void 0),getProjects:()=>u("/projects"),addProject:(t,e)=>u("/projects",{method:"POST",body:JSON.stringify({path:t,...e!=null&&e.create?{create:!0}:{},...e!=null&&e.name?{name:e.name}:{},...e!=null&&e.codeName?{codeName:e.codeName}:{}})}),updateProjectName:(t,e)=>u(`/projects/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify({name:e})}),getProject:t=>u(`/projects/${t}`),updateProjectCodeName:(t,e)=>u(`/projects/${encodeURIComponent(t)}/code-name`,{method:"PATCH",body:JSON.stringify({codeName:e})}),updateProjectCaption:(t,e)=>u(`/projects/${encodeURIComponent(t)}/caption`,{method:"PATCH",body:JSON.stringify({caption:e})}),getProjectSessionDefaults:t=>u(`/projects/${t}/session-defaults`),updateProjectSessionDefaults:(t,e)=>u(`/projects/${t}/session-defaults`,{method:"PATCH",body:JSON.stringify(e)}),deleteProject:t=>u(`/projects/${t}`,{method:"DELETE"}),reclassifySessionProject:(t,e,n)=>u(`/projects/${t}/sessions/${e}/project`,{method:"PUT",body:JSON.stringify({projectId:n})}),refreshSessionPreview:(t,e)=>u(`/projects/${t}/sessions/${e}/refresh-preview`,{method:"POST"}),getProjectQueue:t=>u(`/projects/${t}/queue`),getProjectWorkstreams:t=>u(`/projects/${t}/workstreams`),getProjectWorkstreamCheckoutPreview:(t,e)=>{const n=new URLSearchParams({label:e});return u(`/projects/${t}/workstreams/checkout-preview?${n}`)},createProjectWorkstream:(t,e)=>u(`/projects/${t}/workstreams`,{method:"POST",body:JSON.stringify(e)}),getProjectQueueItems:()=>u("/project-queue"),pauseProjectQueueDispatch:()=>u("/project-queue/pause",{method:"POST"}),resumeProjectQueueDispatch:()=>u("/project-queue/resume",{method:"POST"}),promoteProjectQueueNow:(t,e={})=>u(`/project-queue/${encodeURIComponent(t)}/promote-now`,{method:"POST",body:JSON.stringify(e)}),createProjectQueueItem:(t,e)=>u(`/projects/${t}/queue`,{method:"POST",body:JSON.stringify(e)}),updateProjectQueueItem:(t,e,n)=>u(`/projects/${t}/queue/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteProjectQueueItem:(t,e)=>u(`/projects/${t}/queue/${encodeURIComponent(e)}`,{method:"DELETE"}),retryProjectQueueItem:(t,e)=>u(`/projects/${t}/queue/${encodeURIComponent(e)}/retry`,{method:"POST"}),moveProjectQueueItemToTop:(t,e)=>u(`/projects/${t}/queue/${encodeURIComponent(e)}/move-to-top`,{method:"POST"}),getAgentSession:(t,e,n)=>u(`/projects/${t}/sessions/${e}/agents/${n}`),getAgentMappings:(t,e)=>u(`/projects/${t}/sessions/${e}/agents`),startSession:(t,e,n,s,r,i)=>u(`/projects/${t}/sessions`,{method:"POST",body:JSON.stringify({message:e,mode:n==null?void 0:n.mode,model:n==null?void 0:n.model,serviceTier:n==null?void 0:n.serviceTier,thinking:n==null?void 0:n.thinking,showThinking:n==null?void 0:n.showThinking,provider:n==null?void 0:n.provider,computerControl:n==null?void 0:n.computerControl,executor:n==null?void 0:n.executor,sandboxLevel:n==null?void 0:n.sandboxLevel,sandboxNetworkFirewall:n==null?void 0:n.sandboxNetworkFirewall,recapMode:n==null?void 0:n.recapMode,recapAfterSeconds:n==null?void 0:n.recapAfterSeconds,promptSuggestionMode:n==null?void 0:n.promptSuggestionMode,helperSideModel:n==null?void 0:n.helperSideModel,workstreamId:n==null?void 0:n.workstreamId,attachments:s,clientTimestamp:r,messageMetadata:i})}),createSession:(t,e)=>u(`/projects/${t}/sessions/create`,{method:"POST",body:JSON.stringify({mode:e==null?void 0:e.mode,model:e==null?void 0:e.model,serviceTier:e==null?void 0:e.serviceTier,thinking:e==null?void 0:e.thinking,showThinking:e==null?void 0:e.showThinking,provider:e==null?void 0:e.provider,computerControl:e==null?void 0:e.computerControl,executor:e==null?void 0:e.executor,sandboxLevel:e==null?void 0:e.sandboxLevel,sandboxNetworkFirewall:e==null?void 0:e.sandboxNetworkFirewall,recapMode:e==null?void 0:e.recapMode,recapAfterSeconds:e==null?void 0:e.recapAfterSeconds,promptSuggestionMode:e==null?void 0:e.promptSuggestionMode,helperSideModel:e==null?void 0:e.helperSideModel,workstreamId:e==null?void 0:e.workstreamId})}),startDetachedSession:(t,e,n,s,r)=>u("/sessions",{method:"POST",body:JSON.stringify({message:t,mode:e==null?void 0:e.mode,model:e==null?void 0:e.model,serviceTier:e==null?void 0:e.serviceTier,thinking:e==null?void 0:e.thinking,showThinking:e==null?void 0:e.showThinking,provider:e==null?void 0:e.provider,computerControl:e==null?void 0:e.computerControl,executor:e==null?void 0:e.executor,sandboxLevel:e==null?void 0:e.sandboxLevel,sandboxNetworkFirewall:e==null?void 0:e.sandboxNetworkFirewall,recapMode:e==null?void 0:e.recapMode,recapAfterSeconds:e==null?void 0:e.recapAfterSeconds,promptSuggestionMode:e==null?void 0:e.promptSuggestionMode,helperSideModel:e==null?void 0:e.helperSideModel,attachments:n,clientTimestamp:s,messageMetadata:r})}),createDetachedSession:t=>u("/sessions/create",{method:"POST",body:JSON.stringify({mode:t==null?void 0:t.mode,model:t==null?void 0:t.model,serviceTier:t==null?void 0:t.serviceTier,thinking:t==null?void 0:t.thinking,showThinking:t==null?void 0:t.showThinking,provider:t==null?void 0:t.provider,computerControl:t==null?void 0:t.computerControl,executor:t==null?void 0:t.executor,sandboxLevel:t==null?void 0:t.sandboxLevel,sandboxNetworkFirewall:t==null?void 0:t.sandboxNetworkFirewall,recapMode:t==null?void 0:t.recapMode,recapAfterSeconds:t==null?void 0:t.recapAfterSeconds,promptSuggestionMode:t==null?void 0:t.promptSuggestionMode,helperSideModel:t==null?void 0:t.helperSideModel})}),restartSession:(t,e,n)=>u(`/projects/${t}/sessions/${e}/restart`,{method:"POST",body:JSON.stringify({mode:n==null?void 0:n.mode,model:n==null?void 0:n.model,serviceTier:n==null?void 0:n.serviceTier,thinking:n==null?void 0:n.thinking,showThinking:n==null?void 0:n.showThinking,provider:n==null?void 0:n.provider,executor:n==null?void 0:n.executor,sandboxLevel:n==null?void 0:n.sandboxLevel,sandboxNetworkFirewall:n==null?void 0:n.sandboxNetworkFirewall,recapMode:n==null?void 0:n.recapMode,recapAfterSeconds:n==null?void 0:n.recapAfterSeconds,promptSuggestionMode:n==null?void 0:n.promptSuggestionMode,helperSideModel:n==null?void 0:n.helperSideModel,reason:n==null?void 0:n.reason,restartMode:n==null?void 0:n.restartMode,forkUpToMessageId:n==null?void 0:n.forkUpToMessageId,sourceUrl:n==null?void 0:n.sourceUrl,handoffText:n==null?void 0:n.handoffText})}),getRestartHandoff:(t,e,n)=>u(`/projects/${t}/sessions/${e}/restart/handoff${n!=null&&n.sourceUrl?`?sourceUrl=${encodeURIComponent(n.sourceUrl)}`:""}`),forkSession:(t,e,n)=>u(`/projects/${t}/sessions/${e}/fork`,{method:"POST",body:JSON.stringify(n??{})}),forkSessionWithSummary:(t,e,n)=>u(`/projects/${t}/sessions/${e}/fork-summary`,{method:"POST",body:JSON.stringify({sourceMessageId:n.sourceMessageId,instructions:n.instructions,mode:n.mode,autoOpenWhenReady:n.autoOpenWhenReady})}),proposeSessionRetitle:(t,e,n)=>u(`/projects/${t}/sessions/${e}/retitle`,{method:"POST",body:JSON.stringify({currentTitle:n==null?void 0:n.currentTitle,lengthTarget:n==null?void 0:n.lengthTarget})}),cancelForkSessionWithSummary:(t,e,n)=>u(`/projects/${t}/sessions/${e}/fork-summary/${n}/cancel`,{method:"POST"}),updateForkSummaryDisplayObject:(t,e,n,s)=>u(`/projects/${t}/sessions/${e}/fork-summary/${n}`,{method:"PATCH",body:JSON.stringify(s)}),runBangCommand:(t,e,n,s)=>u(`/projects/${t}/sessions/${e}/bang-commands`,{method:"POST",body:JSON.stringify({command:n,placementAfterMessageId:s})}),killBangCommand:(t,e,n)=>u(`/projects/${t}/sessions/${e}/bang-commands/${n}/kill`,{method:"POST"}),fetchBangCommandOutput:(t,e,n)=>u(`/projects/${t}/sessions/${e}/bang-commands/${n}/output`),deleteBangCommand:(t,e,n)=>u(`/projects/${t}/sessions/${e}/bang-commands/${n}`,{method:"DELETE"}),fetchBangCompletions:(t,e,n,s)=>u(`/projects/${t}/bang-completions?token=${encodeURIComponent(e)}&kind=${n}&line=${encodeURIComponent(s)}`),fetchBangCommandHistory:()=>u("/bang-commands"),queueMessage:(t,e,n,s,r,i,o,a,c,d,h)=>u(`/sessions/${t}/messages`,{method:"POST",body:JSON.stringify({message:e,mode:n,attachments:s,tempId:r,thinking:i,showThinking:h,serviceTier:d,deferred:o,clientTimestamp:a,messageMetadata:c})}),cancelDeferredMessage:(t,e)=>u(`/sessions/${t}/deferred/${encodeURIComponent(e)}`,{method:"DELETE"}),rewindSession:(t,e,n)=>u(`/projects/${t}/sessions/${e}/rewind`,{method:"POST",body:JSON.stringify(n)}),startClearloop:(t,e,n)=>u(`/projects/${t}/sessions/${e}/clearloop`,{method:"POST",body:JSON.stringify(n)}),updateClearloop:(t,e,n)=>u(`/projects/${t}/sessions/${e}/clearloop`,{method:"PATCH",body:JSON.stringify(n)}),cancelClearloop:(t,e)=>u(`/projects/${t}/sessions/${e}/clearloop`,{method:"DELETE"}),cancelUnconfirmedSteerMessage:(t,e)=>u(`/sessions/${t}/steering/${encodeURIComponent(e)}`,{method:"DELETE"}),steerDeferredMessagesThrough:(t,e)=>u(`/sessions/${t}/deferred/${encodeURIComponent(e)}/steer`,{method:"POST"}),deleteRecoveredQueuedMessage:(t,e)=>u(`/sessions/${t}/recovered-queue/${encodeURIComponent(e)}`,{method:"DELETE"}),resumeRecoveredQueuedMessage:(t,e)=>u(`/sessions/${t}/recovered-queue/${encodeURIComponent(e)}/resume`,{method:"POST"}),steerRecoveredQueuedMessage:(t,e)=>u(`/sessions/${t}/recovered-queue/${encodeURIComponent(e)}/steer`,{method:"POST"}),interruptProcess:t=>u(`/processes/${t}/interrupt`,{method:"POST"}),requestRecap:(t,e)=>u(`/processes/${t}/recap`,{method:"POST",...e===void 0?{}:{body:JSON.stringify({hiddenSinceMs:e})}}),requestSessionRecap:(t,e,n)=>u(`/projects/${t}/sessions/${e}/recap`,{method:"POST",...n===void 0?{}:{body:JSON.stringify({hiddenSinceMs:n})}}),setProcessRecapConfig:(t,e)=>u(`/processes/${t}/recap-config`,{method:"POST",body:JSON.stringify(e)}),getProcessModels:t=>u(`/processes/${t}/models`),setProcessModel:(t,e)=>u(`/processes/${t}/model`,{method:"POST",body:JSON.stringify({model:e})}),setProcessConfig:(t,e)=>u(`/processes/${t}/config`,{method:"POST",body:JSON.stringify(e)}),respondToInput:(t,e,n,s,r)=>u(`/sessions/${t}/input`,{method:"POST",body:JSON.stringify({requestId:e,response:n,answers:s,feedback:r})}),getPendingInputRequest:t=>u(`/sessions/${t}/pending-input`),setPermissionMode:(t,e)=>u(`/sessions/${t}/mode`,{method:"PUT",body:JSON.stringify({mode:e})}),markSessionDone:t=>u(`/sessions/${t}/done`,{method:"POST"}),archiveSession:t=>u(`/sessions/${t}/archive`,{method:"POST"}),terminateSession:t=>u(`/sessions/${t}/terminate`,{method:"POST"}),getLastSeen:()=>u("/notifications/last-seen"),...tc,getConnections:()=>u("/connections"),...nc,...Ka,...Xa,...Za,getInbox:(t,e)=>{const n=new URLSearchParams;return t&&n.set("projectId",t),e&&n.set("summaryMode",e),u(n.size?`/inbox?${n}`:"/inbox")},getGlobalSessions:oc,getGlobalSessionStats:()=>u("/sessions/stats"),...qa,...za,...sc,...ec,...Ya,getServerSettings:()=>u("/settings"),getHostAwakeStatus:(t=!1)=>u(`/settings/host-awake/status${t?"?refresh=1":""}`),updateServerSettings:t=>u("/settings",{method:"PUT",body:JSON.stringify(t,(e,n)=>n===void 0?null:n)}),getBrowserSettingsBackup:()=>u("/settings/browser-backup"),saveBrowserSettingsBackup:t=>u("/settings/browser-backup",{method:"PUT",body:JSON.stringify(t)}),getFileAccessInfo:()=>u("/settings/file-access"),getCacheMissBillingEvents:(t=200,e=!1)=>u(`/settings/cache-miss-billing/events?limit=${encodeURIComponent(String(t))}${e?"&includeExpectedExpiry=1":""}`),detectGatewayServiceEffort:t=>u("/settings/gateway-services/effort",{method:"POST",body:JSON.stringify({url:t})}),discoverHelperTargetModels:t=>u("/settings/helper-targets/models",{method:"POST",body:JSON.stringify({baseUrl:t})}),getCodexUpdateStatus:t=>u(`/codex/updates${t?"?force=true":""}`),installCodexUpdate:()=>u("/codex/updates/install",{method:"POST"}),getRemoteExecutors:()=>u("/settings/remote-executors"),updateRemoteExecutors:t=>u("/settings/remote-executors",{method:"PUT",body:JSON.stringify({executors:t})}),testRemoteExecutor:t=>u(`/settings/remote-executors/${encodeURIComponent(t)}/test`,{method:"POST"}),getSharingStatus:()=>u("/sharing/status"),shareSession:(t,e)=>u("/sharing/upload",{method:"POST",body:JSON.stringify({html:t,title:e})}),getPublicShareStatus:()=>u("/public-shares/status"),getPublicSessionShareStatus:(t,e)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}`),getPublicShares:(t={})=>{const e=new URLSearchParams;t.cursor&&e.set("cursor",t.cursor),t.limit&&e.set("limit",String(t.limit)),t.projectId&&e.set("projectId",t.projectId),t.sessionId&&e.set("sessionId",t.sessionId),t.mode&&e.set("mode",t.mode);const n=e.toString();return u(`/public-shares${n?`?${n}`:""}`)},revokePublicShare:t=>u(`/public-shares/${encodeURIComponent(t)}`,{method:"DELETE"}),revokeAllPublicShares:()=>u("/public-shares/revoke-all",{method:"POST",body:JSON.stringify({confirmation:"revoke-all-public-shares"})}),freezePublicShares:t=>u("/public-shares/freeze-live",{method:"POST",body:JSON.stringify({shareIds:t,confirmation:ds})}),createPublicSessionShare:t=>u("/public-shares",{method:"POST",body:JSON.stringify(t)}),getPublicFileShares:(t,e)=>{const n=new URLSearchParams({projectId:t,path:e});return u(`/public-file-shares?${n}`)},createPublicFileShare:t=>u("/public-file-shares",{method:"POST",body:JSON.stringify(t)}),revokePublicFileShare:t=>u(`/public-file-shares/${encodeURIComponent(t)}`,{method:"DELETE"}),revokePublicSessionShares:(t,e)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}`,{method:"DELETE"}),freezePublicSessionLiveShares:(t,e)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}/freeze-live`,{method:"POST"}),freezePublicSessionViewerToken:(t,e,n)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}/viewers/${encodeURIComponent(n)}/freeze`,{method:"POST"}),disconnectPublicSessionViewerToken:(t,e,n)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}/viewers/${encodeURIComponent(n)}`,{method:"DELETE"}),getDevices:()=>u("/devices"),startDevice:t=>u(`/devices/${encodeURIComponent(t)}/start`,{method:"POST"}),stopDevice:t=>u(`/devices/${encodeURIComponent(t)}/stop`,{method:"POST"}),downloadDeviceBridge:()=>u("/devices/bridge/download",{method:"POST"}),getEmulators:()=>u("/devices"),startEmulator:t=>u(`/devices/${encodeURIComponent(t)}/start`,{method:"POST"}),stopEmulator:t=>u(`/devices/${encodeURIComponent(t)}/stop`,{method:"POST"}),downloadEmulatorBridge:()=>u("/devices/bridge/download",{method:"POST"})},lu={projects:!0,uploads:!0,temp:!0,home:!1,custom:[]};export{Ji as $,gi as A,yc as B,Va as C,lu as D,tu as E,I as F,ic as G,Wc as H,fe as I,Ic as J,Cc as K,vc as L,Mi as M,Pn as N,Nc as O,Fc as P,Ai as Q,wi as R,bc as S,Mt as T,be as U,Z as V,Xc as W,Yc as X,ao as Y,Kc as Z,Lc as _,xe as a,wc as a0,jc as a1,Rc as a2,xc as a3,Ec as a4,_c as a5,Pc as a6,Mc as a7,lc as a8,Gc as a9,Hc as aA,Jc as aB,du as aa,Tc as ab,He as ac,Qc as ad,Bc as ae,Oc as af,kc as ag,ou as ah,au as ai,cu as aj,ru as ak,V as al,re as am,su as an,F as ao,Zo as ap,nu as aq,Sa as ar,Vn as as,iu as at,qc as au,Vc as av,zc as aw,U as ax,Ve as ay,Ac as az,Pt as b,dc as c,eu as d,uu as e,Zc as f,dt as g,u as h,Dc as i,Uc as j,H as k,Cn as l,pc as m,pi as n,Tt as o,In as p,wt as q,hc as r,di as s,Y as t,$c as u,mc as v,fc as w,gc as x,Si as y,Sc as z};
11
+ `):void 0}function zo(t){const e=Hn(t);return e!==void 0&&e.length>0&&e.every(n=>n!==null&&typeof n=="object"&&n.type==="tool_result")}function Yo(t){var e;return t.isMeta!==!0?!1:((e=qo(t))==null?void 0:e.trimStart().startsWith("Base directory for this skill:"))===!0}function Ko(t){const e=t.trim(),n=/<command-name>[\s\S]*<\/command-name>/.test(e),s=e.replace(/<command-name>[\s\S]*?<\/command-name>/g,"").replace(/<command-message>[\s\S]*?<\/command-message>/g,"").replace(/<command-args>[\s\S]*?<\/command-args>/g,"").trim();return/^<local-command-caveat>[\s\S]*<\/local-command-caveat>$/.test(e)||/^<local-command-stdout>[\s\S]*<\/local-command-stdout>$/.test(e)||n&&s===""}function Xo(t){if(t.isCompactSummary===!0||zo(t)||Yo(t))return!0;const e=Gn(t);return typeof e=="string"&&Ko(e)}function Jn(t){return t.type==="system"&&t.subtype==="compact_boundary"}function Vn(t){var s;const e=(s=t.message)==null?void 0:s.role,n=typeof t.role=="string"?t.role:typeof e=="string"?e:void 0;return(t.type==="user"||n==="user")&&!Xo(t)}function Zo(t){return Jn(t)?"compact_boundary":Vn(t)?"user_turn":null}function ea(t){return t===void 0||!Number.isFinite(t)?Bn:Math.max(1,Math.floor(t))}function ta(t){return t===Bn?Vo:Math.max(t+1,Math.ceil(t*1.5))}function nu({enabled:t,followingBottom:e,historyExpanded:n,tailFrom:s,structuralRevision:r,lastEvaluatedStructuralRevision:i,completedTranscriptGrowth:o,pendingCandidateEligibleAfterMs:a,nowMs:c}){return!t||n||!e||s!==void 0&&s.length>0?!1:r!==i?!0:o&&a!==void 0&&c>a}function su({messages:t,nowMs:e,tailTurns:n}){const s=ea(n),r=ta(s);let i=0,o=0,a=null,c=null,d=!1,h=!1;for(let b=t.length-1;b>=0;b-=1){const v=t[b];if(!v)continue;const M=Zo(v);if(M==="user_turn"){if(i+=1,i===s&&(a=b),i>r){d=!0;break}}else M==="compact_boundary"&&(o+=1,o===Kt&&(c=b),o>Kt&&(h=!0));if(h&&i<s)break}if(!d&&!h)return{kind:"none",reason:"below_threshold"};let f,m;if(d&&a!==null&&(!h||c===null||a>c))f=a,m="user_turn";else if(c!==null)f=c,m="compact_boundary";else return{kind:"none",reason:"below_threshold"};if(f<=0)return{kind:"none",reason:"candidate_at_start"};const p=t[f];if(!p)return{kind:"none",reason:"missing_message_id"};const S=I(p);if(!S)return{kind:"none",reason:"missing_message_id"};const g=Z(p.timestamp);if(g===null)return{kind:"none",reason:"invalid_timestamp"};const y={startIndex:f,startMessageId:S,reason:m,boundaryTimestampMs:g,eligibleAfterMs:g+Wn,turnTarget:s,turnTrigger:r};return e>y.eligibleAfterMs?{kind:"ready",candidate:y}:{kind:"deferred",candidate:y}}const na=new Set(["call_id","parentToolUseId","parent_tool_use_id","toolUseId","tool_use_id"]),sa=new Set(["agentId","agent_id"]);function Xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function z(t,e){if(typeof e!="string")return;const n=e.trim();n&&t.add(n)}function ra(t,e){const n=[/^agentId:\s*([^\s(),]+)/gm,/"agent_id"\s*:\s*"([^"]+)"/g,/"agentId"\s*:\s*"([^"]+)"/g];for(const s of n)for(const r of t.matchAll(s))z(e,r[1])}function ft(t,e,n){if(typeof t=="string"){ra(t,e.agentIds);return}if(typeof t!="object"||t===null||n.has(t))return;if(n.add(t),Array.isArray(t)){for(const r of t)ft(r,e,n);return}const s=t;s.type==="tool_use"&&z(e.toolUseIds,s.id),(s.type==="function_call"||s.type==="function_call_output")&&z(e.toolUseIds,s.call_id),Xt(s.toolUse)&&z(e.toolUseIds,s.toolUse.id),Xt(s.tool_use)&&z(e.toolUseIds,s.tool_use.id);for(const[r,i]of Object.entries(s))na.has(r)&&z(e.toolUseIds,i),sa.has(r)&&z(e.agentIds,i),ft(i,e,n)}function Zt(t,e){const n=new Set;for(const s of t)ft(s,e,n)}function ia(t){return t==="pending"||t==="running"}function oa(t,e,n){const s={agentIds:new Set,toolUseIds:new Set};Zt(t,s);for(const[o,a]of Object.entries(e))ia(a.status)&&s.agentIds.add(o);const r=new Set;let i=!0;for(;i;){i=!1;for(const[o,a]of n)if(s.toolUseIds.has(o)||s.agentIds.has(a)){const c=s.agentIds.size;s.agentIds.add(a),i||(i=s.agentIds.size!==c)}for(const o of Array.from(s.agentIds)){if(r.has(o))continue;r.add(o);const a=e[o];if(!a)continue;const c=s.agentIds.size,d=s.toolUseIds.size;Zt(a.messages,s),i||(i=s.agentIds.size!==c||s.toolUseIds.size!==d)}}return s}function aa(t,e){const n=Object.entries(t).filter(([s])=>e.has(s));return n.length===Object.keys(t).length?t:Object.fromEntries(n)}function ca(t,e){const n=t.filter(([s,r])=>e.toolUseIds.has(s)||e.agentIds.has(r));return n.length===t.length?t:n}function ua(t,e){const n=Object.entries(t).filter(([s])=>e.has(s));return n.length===Object.keys(t).length?t:Object.fromEntries(n)}function da(t,e,n){const s=t.pagination;let r=0,i=0;for(const o of t.messages)Jn(o)&&(r+=1),Vn(o)&&(i+=1);return{hasOlderMessages:!0,totalMessageCount:Math.max((s==null?void 0:s.totalMessageCount)??0,t.messages.length),returnedMessageCount:e.length,truncatedBeforeMessageId:n.startMessageId,totalCompactions:Math.max((s==null?void 0:s.totalCompactions)??0,r),...(s==null?void 0:s.totalUserTurns)!==void 0&&{totalUserTurns:Math.max(s.totalUserTurns,i)},truncatedBy:n.reason}}function la(t,e){const n=Je(t.messages,e.startMessageId);if(n<=0)return t;const s=t.messages[n];if(!s)return t;const r=Z(s.timestamp);if(r===null||e.nowMs<=r+Wn)return t;const i=t.messages.slice(n),o=new Set(i.map(I).filter(c=>c.length>0)),a=oa(i,t.agentContent,t.toolUseToAgentEntries);return{...t,messages:i,activeWindowTrimRevision:t.activeWindowTrimRevision+1,pagination:da(t,i,e),markdownAugments:aa(t.markdownAugments,o),toolUseToAgentEntries:ca(t.toolUseToAgentEntries,a),agentContent:ua(t.agentContent,a.agentIds)}}function Ot(){return{messages:[],session:null,agentContent:{},markdownAugments:{},toolUseToAgentEntries:[],maxPersistedTimestampMs:Number.NEGATIVE_INFINITY,deferredMessages:[],activeWindowTrimRevision:0}}function kt(t,e){return be(t).capabilities.needsApproxMessageDedup||t==="codex"&&!e}function ha(t){return be(t).capabilities.dedupQueueOperationEchoes===!0}function fa(t){return be(t).capabilities.dedupSelfSendUserEchoes===!0}function Dt(t,e){return{excludeTools:be(t).capabilities.approxDedupExcludesTools===!0||t==="codex"&&!e}}function qn(t){return typeof t.yaRecapSource=="string"}function re(t){for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n&&(n._source??"sdk")==="jsonl"&&!qn(n))return I(n)}}function Me(t,e){let n=t;for(const s of e){if(qn(s))continue;const r=J(s);r!==null&&r>n&&(n=r)}return n}function Pe(t){return t.map(e=>({...e,_source:"jsonl"}))}function ma(t,e,n,s){const r=mo(t,e,{skipDagOrdering:!be(n).capabilities.supportsDag,preserveIncomingOrder:n==="codex"&&s});return he(r.messages,n,s)}function pa(t,e,n,s){let r=e;for(const i of t)V(i)&&(r=En(r,i).messages);return he(r,n,s)}function qe(t){const e=t.filter(n=>!n._isStreaming);return e.length===t.length?t:e}function ga(t,e){if(t.tempId===e)return!0;const s=t.tempIds;return Array.isArray(s)&&s.includes(e)}function Sa(t,e){const n=`rewound-group-${e.id}`;if(t.some(g=>I(g)===n))return t;const s=t.findIndex(g=>I(g)===e.cutMessageId);if(s<0)return t;const r=t[s],i=typeof r.rewoundGroupId=="string"&&r.rewoundGroupId?r.rewoundGroupId:void 0,o=i?{rewoundParentGroupId:i}:void 0;let a=0,c=-1;const d=new Set,h=t.slice(s+1).map((g,y)=>{const b=g;if(b.rewoundGroupId||typeof b.timestamp=="string"&&b.timestamp>e.at)return g;a+=1,c<0&&(c=y);const v=I(g);return v&&d.add(v),{...g,rewoundGroupId:e.id,...o}});if(a===0)return t;const f=new Set;for(const g of h){const y=g;y.subtype==="rewound_group"&&typeof y.rewoundGroupId=="string"&&y.rewoundGroupId!==e.id&&(y.rewoundParentGroupId||typeof y.parentUuid=="string"&&d.has(y.parentUuid)&&f.add(y.rewoundGroupId))}const m=f.size?h.map(g=>{const y=g.rewoundGroupId;return typeof y=="string"&&f.has(y)?{...g,rewoundParentGroupId:e.id}:g}):h,p=r.timestamp,S={type:"system",subtype:"rewound_group",uuid:n,id:n,parentUuid:e.cutMessageId,timestamp:typeof p=="string"?p:e.at,content:"",isSynthetic:!0,rewoundGroupId:e.id,...o,rewoundGroup:{reason:e.reason,cutTurnIndex:e.cutTurnIndex,droppedTurnCount:e.droppedTurnCount,rowCount:a,at:e.at,...e.clearloopIteration!==void 0?{clearloopIteration:e.clearloopIteration}:{},...e.clearloopTotal!==void 0?{clearloopTotal:e.clearloopTotal}:{},...e.clearloopPrompt?{clearloopPrompt:e.clearloopPrompt}:{}}};return[...t.slice(0,s+1),...m.slice(0,c),S,...m.slice(c)]}function ya(t,e){const n=t.filter(s=>!V(s)||!ga(s,e));return n.length===t.length?t:n}function ba(t){var n;if(t.type!=="assistant")return!1;const e=(n=t.message)==null?void 0:n.content;return typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.every(s=>{if(!s||typeof s!="object")return!0;const r=s;return r.type==="text"?typeof r.text!="string"||r.text.trim()==="":r.type==="thinking"?typeof r.thinking!="string"||r.thinking.trim()==="":!1}):!1}function he(t,e,n){const s=e==="codex"||e==="codex-oss"?Uo(t):t,r=kt(e,n)?Ro(s,Dt(e,n)):s,i=e==="codex-oss"||e==="codex"&&!n?Mo(r):r,o=fa(e)?jo(i):i;return ha(e)?Co(o):o}function va(t,e){return t===void 0?e:e===void 0?t:Math.max(t,e)}function Ia(t,e,n){if(!t)return;const s=va(t.totalUserTurns,e==null?void 0:e.totalUserTurns);return{...t,totalMessageCount:Math.max(t.totalMessageCount,(e==null?void 0:e.totalMessageCount)??0,n),returnedMessageCount:Math.max(t.returnedMessageCount,(e==null?void 0:e.returnedMessageCount)??0,n),totalCompactions:Math.max(t.totalCompactions,(e==null?void 0:e.totalCompactions)??0),...s!==void 0&&{totalUserTurns:s}}}function Ca(t,e){var m;const n=(m=t.session)==null?void 0:m.provider,s=e.message,r=s.isReplay===!0,i=J(s),o=I(s),a=o!==void 0&&t.messages.some(p=>(p._source??"sdk")==="jsonl"&&I(p)===o),c=r&&(n==="codex"&&e.codexStreamDurableIdAlignment===!0?a:i!==null&&i<=t.maxPersistedTimestampMs);if(s._isStreaming===!0&&e.streamingEnabled===!1){const p=qe(t.messages);return p===t.messages?t:{...t,messages:p}}if(c||(e.fromBufferedReplay||r)&&kt(n,e.codexStreamDurableIdAlignment===!0)&&(ba(s)||Ln(t.messages,s,Dt(n,e.codexStreamDurableIdAlignment===!0))))return t;const h=En(t.messages,s),f=he(h.messages,n,e.codexStreamDurableIdAlignment===!0);return f===t.messages?t:{...t,messages:f}}function wa(t,e,n,s){const r=t[e]??{messages:[],status:"running"};if(n._isStreaming===!0&&s===!1){const o=qe(r.messages);if(o===r.messages)return t;if(o.length===0&&r.contextUsage===void 0){const a={...t};return delete a[e],a}return{...t,[e]:{...r,messages:o}}}const i=I(n);return Je(r.messages,i)!==-1?t:{...t,[e]:{...r,messages:[...r.messages,n],status:"running"}}}function Ta(t,e){const n=wa(t.agentContent,e.agentId,e.message,e.streamingEnabled);return n===t.agentContent?t:{...t,agentContent:n}}function zn(t,e){const n=I(e);if(!n)return t;const s=Je(t,n);if(s>=0){const r=[...t];return r[s]=e,r}return[...t,e]}function Aa(t,e,n){const s=t[e]??{messages:[],status:"running"},r=zn(s.messages,n);return r===s.messages?t:{...t,[e]:{...s,messages:r}}}function Ma(t,e,n){const s=t[e];if(s){const r=new Set(n.messages.map(o=>I(o))),i=s.messages.filter(o=>!r.has(I(o)));return{...t,[e]:{messages:[...n.messages,...i],status:s.status==="running"?"running":n.status}}}return{...t,[e]:n}}function Pa(t,e,n){const s=t[e]??{messages:[],status:"running"};return{...t,[e]:{...s,contextUsage:n}}}function ja(t,e){const n=t[e];if(!n)return t;const s=qe(n.messages);return s===n.messages?t:{...t,[e]:{...n,messages:s}}}function Ra(t,e,n,s){if(kt(n,s))for(const r of e){if((r._source??"sdk")!=="jsonl")continue;const i=I(r);if(i&&Ln([r],t,Dt(n,s)))return i}}function je(t,e,n,s,r=t.markdownAugments){const i=Object.entries(r);if(i.length===0)return r;const o=new Set(e.map(d=>I(d)).filter(Boolean)),a=new Map(t.messages.map(d=>[I(d),d]).filter(([d])=>d.length>0));let c=r;for(const[d,h]of i){if(o.has(d))continue;const f=a.get(d);if(!f)continue;const m=Ra(f,e,n,s);!m||m===d||(c===r&&(c={...r}),c[m]||(c[m]=h),delete c[d])}return c}function Yn(t,e){var n;switch(e.type){case"restoreRouteSnapshot":return{...t,messages:e.snapshot.messages,session:e.snapshot.session,pagination:e.snapshot.pagination,agentContent:e.snapshot.agentContent,markdownAugments:e.snapshot.markdownAugments??{},toolUseToAgentEntries:e.snapshot.toolUseToAgentEntries,deferredMessages:[],lastMessageId:e.snapshot.lastMessageId??re(e.snapshot.messages),maxPersistedTimestampMs:e.snapshot.maxPersistedTimestampMs};case"loadPersistedTranscript":{const s=Pe(e.messages),r=he(s,e.session.provider,e.codexStreamDurableIdAlignment===!0),i=e.markdownAugments?{...t.markdownAugments,...e.markdownAugments}:t.markdownAugments;return{...t,messages:r,session:e.session,pagination:e.pagination,agentContent:e.agentContent??{},markdownAugments:je(t,r,e.session.provider,e.codexStreamDurableIdAlignment===!0,i),toolUseToAgentEntries:e.toolUseToAgentEntries??[],deferredMessages:e.deferredMessages??[],lastMessageId:re(r),maxPersistedTimestampMs:Me(Number.NEGATIVE_INFINITY,s)}}case"setSessionMetadata":return e.session===t.session?t:{...t,session:e.session};case"applyStreamMessage":return Ca(t,e);case"applyStreamSubagentMessage":return Ta(t,e);case"upsertStreamingPlaceholder":{if(e.agentId){const r=Aa(t.agentContent,e.agentId,e.message);return r===t.agentContent?t:{...t,agentContent:r}}const s=zn(t.messages,e.message);return s===t.messages?t:{...t,messages:s}}case"mergeLoadedAgentContent":return{...t,agentContent:Ma(t.agentContent,e.agentId,e.content)};case"updateAgentContextUsage":return{...t,agentContent:Pa(t.agentContent,e.agentId,e.contextUsage)};case"clearAgentStreamingPlaceholders":{const s=ja(t.agentContent,e.agentId);return s===t.agentContent?t:{...t,agentContent:s}}case"clearStreamingPlaceholders":{const s=qe(t.messages);return s===t.messages?t:{...t,messages:s}}case"removeUnconfirmedSelfSend":{const s=ya(t.messages,e.tempId);return s===t.messages?t:{...t,messages:s}}case"applyRewind":{const s=Sa(t.messages,e.record);return s===t.messages?t:{...t,messages:s}}case"registerToolUseAgent":return t.toolUseToAgentEntries.some(([s])=>s===e.toolUseId)?t:{...t,toolUseToAgentEntries:[...t.toolUseToAgentEntries,[e.toolUseId,e.agentId]]};case"applyCatchupMessages":{const s=Pe(e.messages),r=e.session??t.session,i=r==null?void 0:r.provider,o=ma(t.messages,s,i,e.codexStreamDurableIdAlignment===!0);return{...t,messages:o,session:r,pagination:Ia(t.pagination,e.pagination,o.length),markdownAugments:je(t,o,i,e.codexStreamDurableIdAlignment===!0),lastMessageId:re(o),maxPersistedTimestampMs:Me(t.maxPersistedTimestampMs,s)}}case"replaceTailWindow":{const s=Pe(e.messages),r=pa(t.messages,s,e.session.provider,e.codexStreamDurableIdAlignment===!0);return{...t,messages:r,session:e.session,pagination:e.pagination,markdownAugments:je(t,r,e.session.provider,e.codexStreamDurableIdAlignment===!0),lastMessageId:re(r),maxPersistedTimestampMs:Me(t.maxPersistedTimestampMs,s)}}case"trimLoadedWindow":return la(t,e);case"prependOlderMessages":{const s=Pe(e.messages),r=(n=t.session)==null?void 0:n.provider,i=[...s,...t.messages],o=he(i,r,e.codexStreamDurableIdAlignment===!0);return{...t,messages:o,pagination:e.pagination??t.pagination,markdownAugments:je(t,o,r,e.codexStreamDurableIdAlignment===!0),lastMessageId:re(o),maxPersistedTimestampMs:Me(t.maxPersistedTimestampMs,s)}}case"applyFinalMarkdownAugment":{const s=t.markdownAugments[e.messageId];return(s==null?void 0:s.html)===e.augment.html?t:{...t,markdownAugments:{...t.markdownAugments,[e.messageId]:e.augment}}}}}function mt(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}function en(t){return Yn(Ot(),{type:"restoreRouteSnapshot",snapshot:t})}function xa(t,e){if(t.session)return{messages:t.messages,session:t.session,pagination:t.pagination,agentContent:t.agentContent,markdownAugments:t.markdownAugments,toolUseToAgentEntries:t.toolUseToAgentEntries,lastMessageId:t.lastMessageId,maxPersistedTimestampMs:t.maxPersistedTimestampMs,scrollSnapshot:e?mt(e):void 0}}class Ea{constructor(){l(this,"stateValue");l(this,"subscriptions",new Set)}get hasSubscriptions(){return this.subscriptions.size>0}get state(){return this.stateValue}initialize(e){this.stateValue||(this.stateValue=e)}replaceState(e){this.stateValue=e,this.notify()}resetState(){return this.stateValue?(this.stateValue=Ot(),this.notify(),!0):!1}clear(){return this.stateValue?(this.stateValue=void 0,this.notify(),!0):!1}subscribe(e,n,s){const r={selector:e,listener:n,equality:s,value:e(this.state)};return this.subscriptions.add(r),()=>{this.subscriptions.delete(r)}}notify(){for(const e of Array.from(this.subscriptions)){const n=e.selector(this.stateValue);e.equality(e.value,n)||(e.value=n,e.listener())}}}const _a=300*1e3,Oa=3,ka=24*1024*1024,ve={ttlMs:_a,maxEntries:Oa,maxBytes:ka};function ru(t){Object.assign(ve,t)}function iu(){return{...ve}}function k(t){return(t==null?void 0:t.nowMs)??Date.now()}function ie(t){return(t==null?void 0:t.ttlMs)??ve.ttlMs}function Da(t){return(t==null?void 0:t.maxEntries)??ve.maxEntries}function et(t){return(t==null?void 0:t.maxBytes)??ve.maxBytes}class Ua{constructor(e,n){l(this,"metadata",null);l(this,"scrollSnapshotValue");l(this,"store",new Ea);this.key=e,this.input=n}get hasRecord(){return this.metadata!==null}get hasSubscriptions(){return this.store.hasSubscriptions}get state(){return this.metadata?this.store.state:void 0}get retainCount(){var e;return((e=this.metadata)==null?void 0:e.retainCount)??0}get approxBytes(){var e;return((e=this.metadata)==null?void 0:e.approxBytes)??0}get scrollSnapshot(){return this.scrollSnapshotValue}get lastAccessedAt(){var e;return((e=this.metadata)==null?void 0:e.lastAccessedAt)??0}markAccessed(e){this.metadata&&(this.metadata.lastAccessedAt=e)}ensureRecord(e,n){return this.metadata||(this.metadata={retainCount:0,createdAt:e,updatedAt:e,lastAccessedAt:e,expiresAt:e+ie(n),approxBytes:0},this.store.initialize(Ot())),this.metadata}replaceState(e,n,s,r,i){const o=this.metadata;this.metadata={retainCount:(o==null?void 0:o.retainCount)??0,createdAt:(o==null?void 0:o.createdAt)??n,updatedAt:n,lastAccessedAt:n,expiresAt:n+ie(s),approxBytes:r},this.store.replaceState(e),this.scrollSnapshotValue=i?mt(i):void 0}applyState(e,n,s,r){const i=this.ensureRecord(n,s);i.updatedAt=n,i.lastAccessedAt=n,i.expiresAt=n+ie(s),i.approxBytes=r,this.store.replaceState(e)}setScrollSnapshot(e,n){return this.metadata?(this.scrollSnapshotValue=mt(e),this.metadata.updatedAt=n,this.metadata.lastAccessedAt=n,!0):!1}clearScrollSnapshot(){return this.scrollSnapshotValue?(this.scrollSnapshotValue=void 0,!0):!1}resetState(e,n){!this.metadata||!this.store.resetState()||(this.metadata.updatedAt=e,this.metadata.lastAccessedAt=e,this.metadata.expiresAt=e+ie(n),this.metadata.approxBytes=0)}incrementRetain(e,n){const s=this.ensureRecord(e,n);s.retainCount+=1,s.lastAccessedAt=e}release(e,n){this.metadata&&(this.metadata.retainCount=Math.max(0,this.metadata.retainCount-1),this.metadata.lastAccessedAt=e,this.metadata.expiresAt=e+ie(n))}deleteRecord(){return this.metadata?(this.metadata=null,this.scrollSnapshotValue=void 0,this.store.clear(),!0):!1}deleteIfExpired(e){return!this.metadata||this.metadata.retainCount>0||this.metadata.expiresAt>e?!1:this.deleteRecord()}subscribe(e,n,s){return this.store.subscribe(e,n,s)}toStats(){const e=this.state;if(!this.metadata||!e)throw new Error("Cannot build stats for an empty session detail entry");return{key:this.key,sourceKey:this.input.sourceKey,projectId:this.input.projectId,sessionId:this.input.sessionId,tailTurns:this.input.tailTurns,tailFrom:this.input.tailFrom,messageCount:e.messages.length,agentEntryCount:Object.keys(e.agentContent).length,approxBytes:this.metadata.approxBytes,retainCount:this.metadata.retainCount,createdAt:this.metadata.createdAt,updatedAt:this.metadata.updatedAt,lastAccessedAt:this.metadata.lastAccessedAt,expiresAt:this.metadata.expiresAt,hasScrollSnapshot:this.scrollSnapshotValue!==void 0}}estimateBytes(e){const n=this.state;return n?xn(n,e):0}}function Re(t){return encodeURIComponent(t)}function F({sourceKey:t,projectId:e,sessionId:n,initialHistoryCompactions:s,tailTurns:r,tailFrom:i}){const o=[Re(t),Re(e),Re(n)].join(":"),a=[s!==void 0?`initialHistory=${s??"unlimited"}`:"",r!==void 0?`tailTurns=${r}`:"",i?`tailFrom=${Re(i)}`:""].filter(Boolean).join("&");return a?`${o}?${a}`:o}function tt(t,e=!0){return xn(t,{measureUncached:e})}function tn(t){return t.type==="restoreRouteSnapshot"||t.type==="loadPersistedTranscript"}class $a{constructor(){l(this,"entries",new Map)}read(e,n={}){var s;return(s=this.readEntry(e,n))==null?void 0:s.state}readRouteSnapshot(e,n={}){const s=this.readEntry(e,n);return s!=null&&s.state?xa(s.state,s.scrollSnapshot):void 0}readScrollSnapshot(e,n={}){var s;return(s=this.readEntry(e,n))==null?void 0:s.scrollSnapshot}readSelected(e,n,s={}){const r=this.read(e,s);return r?n(r):void 0}writeRouteSnapshot(e,n,s={}){const r=k(s),i=F(e);this.evictExpired({nowMs:r});const o=en(n),a=tt(o);if(a>et(s)){const d=this.entries.get(i);return(!d||d.retainCount===0)&&this.deleteRecordByKey(i),!1}return this.getOrCreateEntry(e).replaceState(o,r,s,a,n.scrollSnapshot),this.evictLeastRecentlyUsed(s),!0}replaceRouteSnapshot(e,n,s={}){const r=k(s),i=F(e);this.evictExpired({nowMs:r});const o=en(n),a=tt(o);return this.getOrCreateEntry(e).replaceState(o,r,s,a,n.scrollSnapshot),this.evictLeastRecentlyUsed(s,new Set([i])),!0}dispatch(e,n,s={}){const r=k(s),i=F(e),o=this.entries.get(i);if(!(o!=null&&o.hasRecord)&&!tn(n))return;const a=o!=null&&o.hasRecord?o:this.ensureEntry(e,r,s),c=a.state;if(!c)return;const d=Yn(c,n);if(d===c)return a.markAccessed(r),c;const h=tt(d,tn(n));a.applyState(d,r,s,h);const f=n.type==="restoreRouteSnapshot"?n.snapshot.scrollSnapshot:n.type==="loadPersistedTranscript"?n.scrollSnapshot:void 0;if(f&&a.setScrollSnapshot(f,r),a.approxBytes>et(s)&&a.retainCount===0){this.deleteRecordByKey(i);return}return this.evictLeastRecentlyUsed(s),d}patchScrollSnapshot(e,n,s={}){const r=k(s),i=F(e),o=this.entries.get(i);!o||this.deleteIfExpired(o,r)||o.setScrollSnapshot(n,r)}subscribe(e,n,s,r=Object.is){const i=this.getOrCreateEntry(e),o=i.subscribe(n,s,r);return()=>{o(),this.deleteEntryIfIdle(i)}}retain(e,n={}){const s=k(n);this.ensureEntry(e,s,n).incrementRetain(s,n);let i=!1;return()=>{i||(i=!0,this.release(e,{...n,nowMs:k(n)}))}}release(e,n={}){const s=k(n),r=this.entries.get(F(e));r&&(r.release(s,n),this.deleteEntryIfIdle(r))}evictExpired(e={}){const n=k(e);let s=0;for(const r of Array.from(this.entries.values()))this.deleteIfExpired(r,n)&&(s+=1);return s}clear(){for(const e of Array.from(this.entries.values()))e.retainCount>0||(e.deleteRecord(),this.deleteEntryIfIdle(e))}clearScrollSnapshots(){for(const e of Array.from(this.entries.values()))e.clearScrollSnapshot()}deleteEntry(e){const n=F(e);return this.deleteRecordByKey(n)}resetEntryState(e,n={}){const s=k(n),r=F(e),i=this.entries.get(r);if(!i)return;const o=i.state;!o||o.session===null&&o.messages.length===0||i.resetState(s,n)}getStats(){const e=this.recordEntries(),n=e.filter(i=>i.retainCount>0),s=e.filter(i=>i.retainCount===0),r=e.map(i=>i.toStats());return{entryCount:r.length,retainedEntryCount:n.length,warmCacheEntryCount:s.length,approxBytes:nt(e),dedupedApproxBytes:this.dedupedApproxBytes(e),retainedApproxBytes:nt(n),retainedDedupedApproxBytes:this.dedupedApproxBytes(n),warmCacheApproxBytes:nt(s),warmCacheDedupedApproxBytes:this.dedupedApproxBytes(s),entries:r}}ensureEntry(e,n,s){const r=this.getOrCreateEntry(e);return r.ensureRecord(n,s),r}readEntry(e,n){const s=k(n),r=F(e),i=this.entries.get(r);if(i&&!this.deleteIfExpired(i,s))return i.markAccessed(s),i}deleteIfExpired(e,n){const s=e.deleteIfExpired(n);return s&&this.deleteEntryIfIdle(e),s}evictLeastRecentlyUsed(e,n=new Set){const s=Da(e),r=et(e),i=()=>this.recordEntries().filter(a=>a.retainCount===0&&!n.has(a.key)).sort((a,c)=>a.lastAccessedAt-c.lastAccessedAt);for(;this.recordEntries().length>s;){const a=i()[0];if(!a)break;a.deleteRecord(),this.deleteEntryIfIdle(a)}let o=0;for(const a of this.recordEntries())o+=a.approxBytes;if(!(o<=r))for(;this.dedupedApproxBytes()>r;){const a=i()[0];if(!a)break;a.deleteRecord(),this.deleteEntryIfIdle(a)}}dedupedApproxBytes(e=this.recordEntries()){const n=new Set;let s=0;for(const r of e)s+=r.estimateBytes({measureUncached:!1,seen:n});return s}getOrCreateEntry(e){const n=F(e);let s=this.entries.get(n);return s||(s=new Ua(n,e),this.entries.set(n,s)),s}deleteRecordByKey(e){const n=this.entries.get(e);if(!n)return!1;const s=n.deleteRecord();return this.deleteEntryIfIdle(n),s}deleteEntryIfIdle(e){!e.hasRecord&&!e.hasSubscriptions&&this.entries.delete(e.key)}recordEntries(){return Array.from(this.entries.values()).filter(e=>e.hasRecord)}}function nt(t){return t.reduce((e,n)=>e+n.approxBytes,0)}function Na(){return new $a}const Ie=Na();function ou(){Ie.clear()}function au(){Ie.clearScrollSnapshots()}function cu(){return Ie.evictExpired()}function uu(){const t=Ie.getStats();return{totalBytes:t.dedupedApproxBytes,liveRetainedBytes:t.retainedDedupedApproxBytes,liveRetainedEntryCount:t.retainedEntryCount,warmCacheBytes:t.warmCacheDedupedApproxBytes,warmCacheEntryCount:t.warmCacheEntryCount}}const nn={kind:"localhost"},Fa={kind:"secure"};function La(t){switch(t.kind){case"localhost":return new Bs(t.options);case"websocket":return new Hs(t.options);case"secure":return new Js(t.options);case"custom":return t.createTransport()}}function Qa(t,e){return t.kind!==e.kind?!1:t.kind==="custom"&&e.kind==="custom"?t.createTransport===e.createTransport:!0}const Ba={getSession:t=>{const{projectId:e,sessionId:n}=t;if(t.fullHistory===!0){if(!t.fullHistoryReason.trim())throw new Error("Full-history session request requires a reason.");return xe.getSession(e,n,void 0,{fullHistory:!0,fullHistoryReason:t.fullHistoryReason,...t.tailTurns!==void 0?{tailTurns:t.tailTurns}:{},...t.tailFrom?{tailFrom:t.tailFrom}:{}})}const{afterMessageId:s,tailCompactions:r,beforeMessageId:i,tailTurns:o}=t,{tailFrom:a}=t;let c;if(!(!!s||r!==void 0||i!==void 0||o!==void 0||a!==void 0))throw new Error("Session detail request requires bounds or explicit fullHistory.");return(r!==void 0||i!==void 0||o!==void 0||a!==void 0)&&(c={tailCompactions:r,beforeMessageId:i,tailTurns:o,tailFrom:a}),c?xe.getSession(e,n,s,c):xe.getSession(e,n,s)},getSessionMetadata:({projectId:t,sessionId:e})=>xe.getSessionMetadata(t,e)},Wa={cache:Ie};function Ga(t,e){return{sourceKey:t,getStore:()=>$(t),getSnapshot:()=>Ji(t),clear:()=>Pi(t),retainActivitySubscription:()=>jn(t,e()),retainDraftDecorations:()=>Rn(t),reportGlobalSessionsCollectionSnapshot:(n,s)=>{Vi(t,n,s)},reportInboxCollectionSnapshot:(n,s)=>{qi(t,n,s)},reportProjectsCollectionSnapshot:(n,s)=>{zi(t,n,s)},reportProjectCollectionSnapshot:(n,s)=>{Yi(t,n,s)},reportProjectQueueCollectionSnapshot:(n,s)=>{Ki(t,n,s)},reportProjectQueueGlobalCollectionSnapshot:(n,s)=>{Xi(t,n,s)},reportProviderRuntimeStatusSnapshot:(n,s)=>{Qi(t,n,s)},reportSessionCollectionCreated:(n,s)=>{Zi(t,n,s)},reportSessionCollectionMetadataChanged:(n,s)=>{eo(t,n,s)}}}class Ha{constructor(e={}){l(this,"runtimes",new Map);l(this,"transports",new Map);l(this,"transportRegistrations",new Map);l(this,"apiClient");l(this,"sessionDetails");l(this,"defaultTransportRegistration");l(this,"createSummaryRuntime");l(this,"readCurrentSourceKey");l(this,"writeCurrentSourceKey");this.apiClient=e.apiClient??Ba,this.sessionDetails=e.sessionDetails??Wa,this.defaultTransportRegistration=e.defaultTransportRegistration??nn,this.createSummaryRuntime=e.createSummaryRuntime??Ga,this.readCurrentSourceKey=e.getCurrentSourceKey??dt,this.writeCurrentSourceKey=e.setCurrentSourceKey??Mi}registerSourceTransport(e,n){const s=this.resolveTransportRegistration(e);this.transportRegistrations.set(e,n);const r=this.transports.get(e);if(!r)return this.createAndStoreTransport(e,n);if(Qa(s,n))return r;r.dispose();const i=this.createAndStoreTransport(e,n),o=this.runtimes.get(e);return o&&(o.transport=i),i}getOrCreateSourceTransport(e){const n=this.transports.get(e);return n||this.createAndStoreTransport(e,this.resolveTransportRegistration(e))}getOrCreateSourceRuntime(e){let n=this.runtimes.get(e);if(!n){const s=this.getOrCreateSourceTransport(e),r={sourceKey:e,transport:s,api:this.apiClient,summary:null,sessionDetails:this.sessionDetails};r.summary=this.createSummaryRuntime(e,()=>r.transport),n=r,this.runtimes.set(e,n)}return n}getCurrentSourceRuntime(){return this.getOrCreateSourceRuntime(this.readCurrentSourceKey())}setCurrentSourceKey(e){this.writeCurrentSourceKey(e)}disposeSource(e){var n;this.runtimes.delete(e),(n=this.transports.get(e))==null||n.dispose(),this.transports.delete(e),this.transportRegistrations.delete(e)}resetForTests(){for(const e of this.transports.values())e.dispose();this.runtimes.clear(),this.transports.clear(),this.transportRegistrations.clear()}resolveTransportRegistration(e){const n=this.transportRegistrations.get(e);return n||(e===Pn?nn:e===wi?Fa:this.defaultTransportRegistration)}createAndStoreTransport(e,n){const s=La(n);return this.transports.set(e,s),s}}const Ja=new Ha;function Va(){return Ja}async function u(t,e){return Va().getCurrentSourceRuntime().transport.fetch(t,e)}const qa={getAuthStatus:()=>u("/auth/status"),enableAuth:t=>u("/auth/enable",{method:"POST",body:JSON.stringify({password:t})}),disableAuth:()=>u("/auth/disable",{method:"POST"}),setupAccount:t=>u("/auth/setup",{method:"POST",body:JSON.stringify({password:t})}),login:(t,e)=>u("/auth/login",{method:"POST",body:JSON.stringify(e?{password:t,username:e}:{password:t})}),logout:()=>u("/auth/logout",{method:"POST"}),changePassword:t=>u("/auth/change-password",{method:"POST",body:JSON.stringify({newPassword:t})}),setLocalhostAccess:t=>u("/auth/localhost-access",{method:"POST",body:JSON.stringify({open:t})})},za={getActingPrincipal:()=>u("/users/me"),listUsers:()=>u("/users"),getUserUsage:()=>u("/users/usage"),createUser:t=>u("/users",{method:"POST",body:JSON.stringify(t)}),updateUser:(t,e)=>u(`/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)}),deleteUser:t=>u(`/users/${encodeURIComponent(t)}`,{method:"DELETE"}),switchUser:t=>u("/users/switch",{method:"POST",body:JSON.stringify({username:t})}),logoutUser:()=>u("/users/logout",{method:"POST"})},Ya={getBrowserProfiles:()=>u("/browser-profiles"),deleteBrowserProfile:t=>u(`/browser-profiles/${encodeURIComponent(t)}`,{method:"DELETE"})},Ka={getFile:(t,e,n=!1,s,r,i)=>{const o=new URLSearchParams({path:e});return n&&o.set("highlight","true"),s!==void 0&&o.set("line",String(s)),r!==void 0&&o.set("lineEnd",String(r)),i==="range"&&o.set("view","range"),u(`/projects/${t}/files?${o.toString()}`)},getFileMetadata:(t,e)=>{const n=new URLSearchParams({path:e,metadata:"only"});return u(`/projects/${t}/files?${n.toString()}`)},getFileRawUrl:(t,e,n=!1)=>{const s=new URLSearchParams({path:e});return n&&s.set("download","true"),`/api/projects/${t}/files/raw?${s.toString()}`},expandDiffContext:(t,e,n,s,r)=>u(`/projects/${t}/diff/expand`,{method:"POST",body:JSON.stringify({filePath:e,oldString:n,newString:s,originalFile:r})})},Xa={getGitStatus:(t,e={})=>{const n=e.useUntrackedCache?"cache":e.omitUntracked?"none":null;return u(`/projects/${t}/git${n?`?untracked=${n}`:""}`)},getGitUntrackedFolder:(t,e)=>u(`/projects/${t}/git/untracked-folder?path=${encodeURIComponent(e)}`),listGitUntrackedFiles:(t,e={})=>{const n=new URLSearchParams;e.path&&n.set("path",e.path),e.q&&n.set("q",e.q);const s=n.size>0?`?${n.toString()}`:"";return u(`/projects/${t}/git/untracked-files${s}`)},checkGitRemote:t=>u(`/projects/${t}/git/check-remote`,{method:"POST"}),getGitIncomingCommits:t=>u(`/projects/${t}/git/incoming-commits`),getGitIntegrationOptions:t=>u(`/projects/${t}/git/integration-options`),pullGit:t=>u(`/projects/${t}/git/pull`,{method:"POST"}),pushGit:t=>u(`/projects/${t}/git/push`,{method:"POST"}),getGitDiff:(t,e)=>u(`/projects/${t}/git/diff`,{method:"POST",body:JSON.stringify(e)}),getGitCommits:(t,e)=>{const n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.set("limit",String(e.limit)),(e==null?void 0:e.skip)!==void 0&&n.set("skip",String(e.skip));const s=n.toString()?`?${n.toString()}`:"";return u(`/projects/${t}/git/commits${s}`)},getGitCommit:(t,e)=>u(`/projects/${t}/git/commit/${encodeURIComponent(e)}`),getGitCommitSearchManifest:t=>u(`/projects/${t}/git/commit-search-manifest`),getGitCommitSearchRecords:(t,e)=>u(`/projects/${t}/git/commit-search-records`,{method:"POST",body:JSON.stringify({shas:e})}),getGitCommitDiff:(t,e)=>u(`/projects/${t}/git/commit-diff`,{method:"POST",body:JSON.stringify(e)}),getGitComparison:(t,e)=>u(`/projects/${t}/git/compare/${encodeURIComponent(e)}`),getGitInclusiveComparison:(t,e)=>u(`/projects/${t}/git/range-to-head/${encodeURIComponent(e)}`),getGitComparisonDiff:(t,e)=>u(`/projects/${t}/git/compare-diff`,{method:"POST",body:JSON.stringify(e)}),getGitInclusiveComparisonDiff:(t,e)=>u(`/projects/${t}/git/range-to-head-diff`,{method:"POST",body:JSON.stringify(e)}),getGitFileProjections:t=>u(`/projects/${t}/git/file-projections`),getGitFileRevision:(t,e)=>{const n=new URLSearchParams({path:e.path});return e.rev&&n.set("rev",e.rev),e.origPath&&n.set("origPath",e.origPath),u(`/projects/${t}/git/file-revision?${n.toString()}`)},getGitFileProjectionDiff:(t,e)=>u(`/projects/${t}/git/file-projection-diff`,{method:"POST",body:JSON.stringify(e)}),getGitBlame:(t,e,n)=>{const s=new URLSearchParams({path:e});return n&&s.set("rev",n),u(`/projects/${t}/git/blame?${s.toString()}`)},listGitFiles:(t,e)=>{const n=new URLSearchParams;e!=null&&e.q&&n.set("q",e.q),(e==null?void 0:e.limit)!==void 0&&n.set("limit",String(e.limit));const s=n.toString()?`?${n.toString()}`:"";return u(`/projects/${t}/git/files${s}`)},listGitWorkingTreeFiles:(t,e)=>{const n=new URLSearchParams;e&&(n.set("tracked",String(e.tracked)),n.set("untracked",String(e.untracked)),n.set("ignored",String(e.ignored)));const s=n.size>0?`?${n.toString()}`:"";return u(`/projects/${t}/git/working-tree-files${s}`)},searchGit:(t,e)=>{const n=new URLSearchParams({q:e.q,kind:e.kind});return e.limit!==void 0&&n.set("limit",String(e.limit)),u(`/projects/${t}/git/search?${n.toString()}`)}},Za={listReviewComments:t=>u(`/projects/${t}/review/comments`),addReviewComment:(t,e,n)=>u(`/projects/${t}/review/comments`,{method:"POST",body:JSON.stringify({anchor:e,text:n})}),updateReviewComment:(t,e,n)=>u(`/projects/${t}/review/comments/${e}`,{method:"PATCH",body:JSON.stringify(n)}),deleteReviewComment:(t,e)=>u(`/projects/${t}/review/comments/${e}`,{method:"DELETE"}),previewReview:t=>u(`/projects/${t}/review/preview`,{method:"POST"}),submitReview:(t,e,n,s,r)=>u(`/projects/${t}/review/submit`,{method:"POST",body:JSON.stringify({include:e,target:n,newSession:s,...r?{submissionId:r.id,name:r.name}:{}})}),listReviewSubmissions:(t,e)=>{const n=new URLSearchParams;e!=null&&e.cursor&&n.set("cursor",e.cursor),e!=null&&e.limit&&n.set("limit",String(e.limit));const s=n.size>0?`?${n}`:"";return u(`/projects/${t}/review/submissions${s}`)},getReviewSubmission:(t,e)=>u(`/projects/${t}/review/submissions/${encodeURIComponent(e)}`),addReviewFollowUp:(t,e,n)=>u(`/projects/${t}/review/sites/${encodeURIComponent(e)}/follow-ups`,{method:"POST",body:JSON.stringify({text:n})}),resolveReviewSite:(t,e)=>u(`/projects/${t}/review/sites/${encodeURIComponent(e)}/resolve`,{method:"POST"}),acknowledgeReviewSubmission:(t,e)=>u(`/projects/${t}/review/submissions/${encodeURIComponent(e)}/acknowledge`,{method:"POST"}),refreshReviewSubmissionResponse:(t,e)=>u(`/projects/${t}/review/submissions/${encodeURIComponent(e)}/refresh-response`,{method:"POST"}),listReviewSiteStates:t=>u(`/projects/${t}/review/submissions?limit=1&includeSiteStates=1`).then(e=>e.siteStates??[]),listReviewInbox:()=>u("/review/inbox")},ec={getOnboardingStatus:()=>u("/onboarding"),completeOnboarding:()=>u("/onboarding/complete",{method:"POST"}),resetOnboarding:()=>u("/onboarding/reset",{method:"POST"})},tc={getPushPublicKey:()=>u("/push/vapid-public-key"),subscribePush:(t,e,n)=>u("/push/subscribe",{method:"POST",body:JSON.stringify({browserProfileId:t,subscription:e,deviceName:n})}),unsubscribePush:t=>u("/push/unsubscribe",{method:"POST",body:JSON.stringify({browserProfileId:t})}),getPushSubscriptions:()=>u("/push/subscriptions"),testPush:(t,e,n,s)=>u("/push/test",{method:"POST",body:JSON.stringify({browserProfileId:t,message:e,urgency:n,deliveryUrgency:s})}),deletePushSubscription:t=>u(`/push/subscriptions/${encodeURIComponent(t)}`,{method:"DELETE"})},nc={getNotificationSettings:()=>u("/push/settings"),updateNotificationSettings:t=>u("/push/settings",{method:"PUT",body:JSON.stringify(t)})},sc={getRecents:t=>u(t?`/recents?limit=${t}`:"/recents"),recordVisit:(t,e)=>u("/recents/visit",{method:"POST",body:JSON.stringify({sessionId:t,projectId:e})}),clearRecents:()=>u("/recents",{method:"DELETE"})},rc={getVersion:t=>u(t!=null&&t.fresh?"/version?fresh=1":"/version"),getServerInfo:()=>u("/server-info"),getEnvSettings:()=>u("/env-settings"),restartServer:()=>u("/server/restart",{method:"POST"})};function ic(t){return{markSessionSeen:(e,n,s,r)=>t(`/sessions/${e}/mark-seen`,{method:"POST",body:JSON.stringify({timestamp:n,messageId:s,nonHumanUserTurnMessageId:r})}),markSessionUnread:e=>t(`/sessions/${e}/mark-seen`,{method:"DELETE"}),searchSessionContent:(e,n)=>t("/sessions/content-search",{method:"POST",body:JSON.stringify(e),signal:n}),getSession:(e,n,s,r)=>{const i=new URLSearchParams;s&&i.set("afterMessageId",s),(r==null?void 0:r.tailCompactions)!==void 0&&i.set("tailCompactions",String(r.tailCompactions)),r!=null&&r.beforeMessageId&&i.set("beforeMessageId",r.beforeMessageId),(r==null?void 0:r.tailTurns)!==void 0&&i.set("tailTurns",String(r.tailTurns)),r!=null&&r.tailFrom&&i.set("tailFrom",r.tailFrom),r!=null&&r.fullHistory&&i.set("fullHistory","1"),r!=null&&r.fullHistoryReason&&i.set("fullHistoryReason",r.fullHistoryReason);const o=i.toString();return t(`/projects/${e}/sessions/${n}${o?`?${o}`:""}`)},getSessionMetadata:(e,n)=>t(`/projects/${e}/sessions/${n}/metadata`),resumeSession:(e,n,s,r,i,o,a,c)=>t(`/projects/${e}/sessions/${n}/resume`,{method:"POST",body:JSON.stringify({message:s,mode:r==null?void 0:r.mode,model:r==null?void 0:r.model,serviceTier:r==null?void 0:r.serviceTier,thinking:r==null?void 0:r.thinking,showThinking:r==null?void 0:r.showThinking,provider:r==null?void 0:r.provider,executor:r==null?void 0:r.executor,recapMode:r==null?void 0:r.recapMode,recapAfterSeconds:r==null?void 0:r.recapAfterSeconds,promptSuggestionMode:r==null?void 0:r.promptSuggestionMode,helperSideModel:r==null?void 0:r.helperSideModel,resumeMode:r==null?void 0:r.resumeMode,attachments:i,tempId:o,clientTimestamp:a,messageMetadata:c})}),reactivateSession:(e,n,s)=>t(`/projects/${e}/sessions/${n}/reactivate`,{method:"POST",body:JSON.stringify({mode:s==null?void 0:s.mode,model:s==null?void 0:s.model,provider:s==null?void 0:s.provider,executor:s==null?void 0:s.executor,recapAfterSeconds:s==null?void 0:s.recapAfterSeconds})}),abortProcess:(e,n)=>t(`/processes/${e}/abort`,{method:"POST",...n!=null&&n.blockResume?{body:JSON.stringify({blockResume:!0})}:{}}),getProcessInfo:e=>t(`/sessions/${e}/process`),updateSessionMetadata:(e,n)=>t(`/sessions/${e}/metadata`,{method:"PUT",body:JSON.stringify(n)}),cloneSession:(e,n,s,r,i)=>t(`/projects/${e}/sessions/${n}/clone`,{method:"POST",body:JSON.stringify({title:s,provider:r,parentSessionId:i})}),sendConversationContext:(e,n,s)=>t(`/projects/${e}/sessions/${n}/conversation-context`,{method:"POST",body:JSON.stringify(s)})}}function du(t){return t.unchanged===!0}function oc(t){const e=new URLSearchParams;t!=null&&t.summaryMode&&e.set("summaryMode",t.summaryMode),t!=null&&t.project&&e.set("project",t.project),t!=null&&t.q&&e.set("q",t.q),t!=null&&t.after&&e.set("after",t.after),t!=null&&t.limit&&e.set("limit",String(t.limit)),t!=null&&t.includeArchived&&e.set("includeArchived","true"),t!=null&&t.starred&&e.set("starred","true"),t!=null&&t.includeStats&&e.set("includeStats","true"),(t==null?void 0:t.knownGeneration)!==void 0&&e.set("knownGeneration",String(t.knownGeneration));const n=e.toString();return u(n?`/sessions?${n}`:"/sessions")}const xe={...ic(u),...rc,getNetworkBinding:()=>u("/network-binding"),setNetworkBinding:t=>u("/network-binding",{method:"PUT",body:JSON.stringify(t)}),disableNetworkBinding:()=>u("/network-binding",{method:"DELETE"}),getProviders:t=>u(t!=null&&t.refresh?"/providers?refresh=1":"/providers",t!=null&&t.refresh?{headers:{"Cache-Control":"no-cache"}}:void 0),getProvider:(t,e)=>u(`/providers/${encodeURIComponent(t)}${e!=null&&e.refresh?"?refresh=1":""}`,e!=null&&e.refresh?{headers:{"Cache-Control":"no-cache"}}:void 0),getProviderSubscriptionUsage:(t,e)=>u(`/providers/${encodeURIComponent(t)}/subscription-usage${e!=null&&e.refresh?"?refresh=1":""}`,e!=null&&e.refresh?{headers:{"Cache-Control":"no-cache"}}:void 0),getProjects:()=>u("/projects"),addProject:(t,e)=>u("/projects",{method:"POST",body:JSON.stringify({path:t,...e!=null&&e.create?{create:!0}:{},...e!=null&&e.name?{name:e.name}:{},...e!=null&&e.codeName?{codeName:e.codeName}:{}})}),updateProjectName:(t,e)=>u(`/projects/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify({name:e})}),getProject:t=>u(`/projects/${t}`),updateProjectCodeName:(t,e)=>u(`/projects/${encodeURIComponent(t)}/code-name`,{method:"PATCH",body:JSON.stringify({codeName:e})}),updateProjectCaption:(t,e)=>u(`/projects/${encodeURIComponent(t)}/caption`,{method:"PATCH",body:JSON.stringify({caption:e})}),getProjectSessionDefaults:t=>u(`/projects/${t}/session-defaults`),updateProjectSessionDefaults:(t,e)=>u(`/projects/${t}/session-defaults`,{method:"PATCH",body:JSON.stringify(e)}),deleteProject:t=>u(`/projects/${t}`,{method:"DELETE"}),reclassifySessionProject:(t,e,n)=>u(`/projects/${t}/sessions/${e}/project`,{method:"PUT",body:JSON.stringify({projectId:n})}),refreshSessionPreview:(t,e)=>u(`/projects/${t}/sessions/${e}/refresh-preview`,{method:"POST"}),getProjectQueue:t=>u(`/projects/${t}/queue`),getProjectWorkstreams:t=>u(`/projects/${t}/workstreams`),getProjectWorkstreamCheckoutPreview:(t,e)=>{const n=new URLSearchParams({label:e});return u(`/projects/${t}/workstreams/checkout-preview?${n}`)},createProjectWorkstream:(t,e)=>u(`/projects/${t}/workstreams`,{method:"POST",body:JSON.stringify(e)}),getProjectQueueItems:()=>u("/project-queue"),pauseProjectQueueDispatch:()=>u("/project-queue/pause",{method:"POST"}),resumeProjectQueueDispatch:()=>u("/project-queue/resume",{method:"POST"}),promoteProjectQueueNow:(t,e={})=>u(`/project-queue/${encodeURIComponent(t)}/promote-now`,{method:"POST",body:JSON.stringify(e)}),createProjectQueueItem:(t,e)=>u(`/projects/${t}/queue`,{method:"POST",body:JSON.stringify(e)}),updateProjectQueueItem:(t,e,n)=>u(`/projects/${t}/queue/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteProjectQueueItem:(t,e)=>u(`/projects/${t}/queue/${encodeURIComponent(e)}`,{method:"DELETE"}),retryProjectQueueItem:(t,e)=>u(`/projects/${t}/queue/${encodeURIComponent(e)}/retry`,{method:"POST"}),moveProjectQueueItemToTop:(t,e)=>u(`/projects/${t}/queue/${encodeURIComponent(e)}/move-to-top`,{method:"POST"}),getAgentSession:(t,e,n)=>u(`/projects/${t}/sessions/${e}/agents/${n}`),getAgentMappings:(t,e)=>u(`/projects/${t}/sessions/${e}/agents`),startSession:(t,e,n,s,r,i)=>u(`/projects/${t}/sessions`,{method:"POST",body:JSON.stringify({message:e,mode:n==null?void 0:n.mode,model:n==null?void 0:n.model,serviceTier:n==null?void 0:n.serviceTier,thinking:n==null?void 0:n.thinking,showThinking:n==null?void 0:n.showThinking,provider:n==null?void 0:n.provider,computerControl:n==null?void 0:n.computerControl,executor:n==null?void 0:n.executor,sandboxLevel:n==null?void 0:n.sandboxLevel,sandboxNetworkFirewall:n==null?void 0:n.sandboxNetworkFirewall,recapMode:n==null?void 0:n.recapMode,recapAfterSeconds:n==null?void 0:n.recapAfterSeconds,promptSuggestionMode:n==null?void 0:n.promptSuggestionMode,helperSideModel:n==null?void 0:n.helperSideModel,workstreamId:n==null?void 0:n.workstreamId,attachments:s,clientTimestamp:r,messageMetadata:i})}),createSession:(t,e)=>u(`/projects/${t}/sessions/create`,{method:"POST",body:JSON.stringify({mode:e==null?void 0:e.mode,model:e==null?void 0:e.model,serviceTier:e==null?void 0:e.serviceTier,thinking:e==null?void 0:e.thinking,showThinking:e==null?void 0:e.showThinking,provider:e==null?void 0:e.provider,computerControl:e==null?void 0:e.computerControl,executor:e==null?void 0:e.executor,sandboxLevel:e==null?void 0:e.sandboxLevel,sandboxNetworkFirewall:e==null?void 0:e.sandboxNetworkFirewall,recapMode:e==null?void 0:e.recapMode,recapAfterSeconds:e==null?void 0:e.recapAfterSeconds,promptSuggestionMode:e==null?void 0:e.promptSuggestionMode,helperSideModel:e==null?void 0:e.helperSideModel,workstreamId:e==null?void 0:e.workstreamId})}),startDetachedSession:(t,e,n,s,r)=>u("/sessions",{method:"POST",body:JSON.stringify({message:t,mode:e==null?void 0:e.mode,model:e==null?void 0:e.model,serviceTier:e==null?void 0:e.serviceTier,thinking:e==null?void 0:e.thinking,showThinking:e==null?void 0:e.showThinking,provider:e==null?void 0:e.provider,computerControl:e==null?void 0:e.computerControl,executor:e==null?void 0:e.executor,sandboxLevel:e==null?void 0:e.sandboxLevel,sandboxNetworkFirewall:e==null?void 0:e.sandboxNetworkFirewall,recapMode:e==null?void 0:e.recapMode,recapAfterSeconds:e==null?void 0:e.recapAfterSeconds,promptSuggestionMode:e==null?void 0:e.promptSuggestionMode,helperSideModel:e==null?void 0:e.helperSideModel,attachments:n,clientTimestamp:s,messageMetadata:r})}),createDetachedSession:t=>u("/sessions/create",{method:"POST",body:JSON.stringify({mode:t==null?void 0:t.mode,model:t==null?void 0:t.model,serviceTier:t==null?void 0:t.serviceTier,thinking:t==null?void 0:t.thinking,showThinking:t==null?void 0:t.showThinking,provider:t==null?void 0:t.provider,computerControl:t==null?void 0:t.computerControl,executor:t==null?void 0:t.executor,sandboxLevel:t==null?void 0:t.sandboxLevel,sandboxNetworkFirewall:t==null?void 0:t.sandboxNetworkFirewall,recapMode:t==null?void 0:t.recapMode,recapAfterSeconds:t==null?void 0:t.recapAfterSeconds,promptSuggestionMode:t==null?void 0:t.promptSuggestionMode,helperSideModel:t==null?void 0:t.helperSideModel})}),restartSession:(t,e,n)=>u(`/projects/${t}/sessions/${e}/restart`,{method:"POST",body:JSON.stringify({mode:n==null?void 0:n.mode,model:n==null?void 0:n.model,serviceTier:n==null?void 0:n.serviceTier,thinking:n==null?void 0:n.thinking,showThinking:n==null?void 0:n.showThinking,provider:n==null?void 0:n.provider,executor:n==null?void 0:n.executor,sandboxLevel:n==null?void 0:n.sandboxLevel,sandboxNetworkFirewall:n==null?void 0:n.sandboxNetworkFirewall,recapMode:n==null?void 0:n.recapMode,recapAfterSeconds:n==null?void 0:n.recapAfterSeconds,promptSuggestionMode:n==null?void 0:n.promptSuggestionMode,helperSideModel:n==null?void 0:n.helperSideModel,reason:n==null?void 0:n.reason,restartMode:n==null?void 0:n.restartMode,forkUpToMessageId:n==null?void 0:n.forkUpToMessageId,sourceUrl:n==null?void 0:n.sourceUrl,handoffText:n==null?void 0:n.handoffText})}),getRestartHandoff:(t,e,n)=>u(`/projects/${t}/sessions/${e}/restart/handoff${n!=null&&n.sourceUrl?`?sourceUrl=${encodeURIComponent(n.sourceUrl)}`:""}`),forkSession:(t,e,n)=>u(`/projects/${t}/sessions/${e}/fork`,{method:"POST",body:JSON.stringify(n??{})}),forkSessionWithSummary:(t,e,n)=>u(`/projects/${t}/sessions/${e}/fork-summary`,{method:"POST",body:JSON.stringify({sourceMessageId:n.sourceMessageId,instructions:n.instructions,mode:n.mode,autoOpenWhenReady:n.autoOpenWhenReady})}),proposeSessionRetitle:(t,e,n)=>u(`/projects/${t}/sessions/${e}/retitle`,{method:"POST",body:JSON.stringify({currentTitle:n==null?void 0:n.currentTitle,lengthTarget:n==null?void 0:n.lengthTarget})}),cancelForkSessionWithSummary:(t,e,n)=>u(`/projects/${t}/sessions/${e}/fork-summary/${n}/cancel`,{method:"POST"}),updateForkSummaryDisplayObject:(t,e,n,s)=>u(`/projects/${t}/sessions/${e}/fork-summary/${n}`,{method:"PATCH",body:JSON.stringify(s)}),runBangCommand:(t,e,n,s)=>u(`/projects/${t}/sessions/${e}/bang-commands`,{method:"POST",body:JSON.stringify({command:n,placementAfterMessageId:s})}),killBangCommand:(t,e,n)=>u(`/projects/${t}/sessions/${e}/bang-commands/${n}/kill`,{method:"POST"}),fetchBangCommandOutput:(t,e,n)=>u(`/projects/${t}/sessions/${e}/bang-commands/${n}/output`),deleteBangCommand:(t,e,n)=>u(`/projects/${t}/sessions/${e}/bang-commands/${n}`,{method:"DELETE"}),fetchBangCompletions:(t,e,n,s)=>u(`/projects/${t}/bang-completions?token=${encodeURIComponent(e)}&kind=${n}&line=${encodeURIComponent(s)}`),fetchBangCommandHistory:()=>u("/bang-commands"),queueMessage:(t,e,n,s,r,i,o,a,c,d,h)=>u(`/sessions/${t}/messages`,{method:"POST",body:JSON.stringify({message:e,mode:n,attachments:s,tempId:r,thinking:i,showThinking:h,serviceTier:d,deferred:o,clientTimestamp:a,messageMetadata:c})}),cancelDeferredMessage:(t,e)=>u(`/sessions/${t}/deferred/${encodeURIComponent(e)}`,{method:"DELETE"}),rewindSession:(t,e,n)=>u(`/projects/${t}/sessions/${e}/rewind`,{method:"POST",body:JSON.stringify(n)}),startClearloop:(t,e,n)=>u(`/projects/${t}/sessions/${e}/clearloop`,{method:"POST",body:JSON.stringify(n)}),updateClearloop:(t,e,n)=>u(`/projects/${t}/sessions/${e}/clearloop`,{method:"PATCH",body:JSON.stringify(n)}),cancelClearloop:(t,e)=>u(`/projects/${t}/sessions/${e}/clearloop`,{method:"DELETE"}),cancelUnconfirmedSteerMessage:(t,e)=>u(`/sessions/${t}/steering/${encodeURIComponent(e)}`,{method:"DELETE"}),steerDeferredMessagesThrough:(t,e)=>u(`/sessions/${t}/deferred/${encodeURIComponent(e)}/steer`,{method:"POST"}),deleteRecoveredQueuedMessage:(t,e)=>u(`/sessions/${t}/recovered-queue/${encodeURIComponent(e)}`,{method:"DELETE"}),resumeRecoveredQueuedMessage:(t,e)=>u(`/sessions/${t}/recovered-queue/${encodeURIComponent(e)}/resume`,{method:"POST"}),steerRecoveredQueuedMessage:(t,e)=>u(`/sessions/${t}/recovered-queue/${encodeURIComponent(e)}/steer`,{method:"POST"}),interruptProcess:t=>u(`/processes/${t}/interrupt`,{method:"POST"}),requestRecap:(t,e)=>u(`/processes/${t}/recap`,{method:"POST",...e===void 0?{}:{body:JSON.stringify({hiddenSinceMs:e})}}),requestSessionRecap:(t,e,n)=>u(`/projects/${t}/sessions/${e}/recap`,{method:"POST",...n===void 0?{}:{body:JSON.stringify({hiddenSinceMs:n})}}),setProcessRecapConfig:(t,e)=>u(`/processes/${t}/recap-config`,{method:"POST",body:JSON.stringify(e)}),getProcessModels:t=>u(`/processes/${t}/models`),setProcessModel:(t,e)=>u(`/processes/${t}/model`,{method:"POST",body:JSON.stringify({model:e})}),setProcessConfig:(t,e)=>u(`/processes/${t}/config`,{method:"POST",body:JSON.stringify(e)}),respondToInput:(t,e,n,s,r)=>u(`/sessions/${t}/input`,{method:"POST",body:JSON.stringify({requestId:e,response:n,answers:s,feedback:r})}),getPendingInputRequest:t=>u(`/sessions/${t}/pending-input`),setPermissionMode:(t,e)=>u(`/sessions/${t}/mode`,{method:"PUT",body:JSON.stringify({mode:e})}),markSessionDone:t=>u(`/sessions/${t}/done`,{method:"POST"}),archiveSession:t=>u(`/sessions/${t}/archive`,{method:"POST"}),terminateSession:t=>u(`/sessions/${t}/terminate`,{method:"POST"}),getLastSeen:()=>u("/notifications/last-seen"),...tc,getConnections:()=>u("/connections"),...nc,...Ka,...Xa,...Za,getInbox:(t,e)=>{const n=new URLSearchParams;return t&&n.set("projectId",t),e&&n.set("summaryMode",e),u(n.size?`/inbox?${n}`:"/inbox")},getGlobalSessions:oc,getGlobalSessionStats:()=>u("/sessions/stats"),...qa,...za,...sc,...ec,...Ya,getServerSettings:()=>u("/settings"),getHostAwakeStatus:(t=!1)=>u(`/settings/host-awake/status${t?"?refresh=1":""}`),updateServerSettings:t=>u("/settings",{method:"PUT",body:JSON.stringify(t,(e,n)=>n===void 0?null:n)}),getBrowserSettingsBackup:()=>u("/settings/browser-backup"),saveBrowserSettingsBackup:t=>u("/settings/browser-backup",{method:"PUT",body:JSON.stringify(t)}),getFileAccessInfo:()=>u("/settings/file-access"),getCacheMissBillingEvents:(t=200,e=!1)=>u(`/settings/cache-miss-billing/events?limit=${encodeURIComponent(String(t))}${e?"&includeExpectedExpiry=1":""}`),detectGatewayServiceEffort:t=>u("/settings/gateway-services/effort",{method:"POST",body:JSON.stringify({url:t})}),discoverHelperTargetModels:t=>u("/settings/helper-targets/models",{method:"POST",body:JSON.stringify({baseUrl:t})}),getCodexUpdateStatus:t=>u(`/codex/updates${t?"?force=true":""}`),installCodexUpdate:()=>u("/codex/updates/install",{method:"POST"}),getRemoteExecutors:()=>u("/settings/remote-executors"),updateRemoteExecutors:t=>u("/settings/remote-executors",{method:"PUT",body:JSON.stringify({executors:t})}),testRemoteExecutor:t=>u(`/settings/remote-executors/${encodeURIComponent(t)}/test`,{method:"POST"}),getSharingStatus:()=>u("/sharing/status"),shareSession:(t,e)=>u("/sharing/upload",{method:"POST",body:JSON.stringify({html:t,title:e})}),getPublicShareStatus:()=>u("/public-shares/status"),getPublicSessionShareStatus:(t,e)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}`),getPublicShares:(t={})=>{const e=new URLSearchParams;t.cursor&&e.set("cursor",t.cursor),t.limit&&e.set("limit",String(t.limit)),t.projectId&&e.set("projectId",t.projectId),t.sessionId&&e.set("sessionId",t.sessionId),t.mode&&e.set("mode",t.mode);const n=e.toString();return u(`/public-shares${n?`?${n}`:""}`)},revokePublicShare:t=>u(`/public-shares/${encodeURIComponent(t)}`,{method:"DELETE"}),revokeAllPublicShares:()=>u("/public-shares/revoke-all",{method:"POST",body:JSON.stringify({confirmation:"revoke-all-public-shares"})}),freezePublicShares:t=>u("/public-shares/freeze-live",{method:"POST",body:JSON.stringify({shareIds:t,confirmation:ds})}),createPublicSessionShare:t=>u("/public-shares",{method:"POST",body:JSON.stringify(t)}),getPublicFileShares:(t,e)=>{const n=new URLSearchParams({projectId:t,path:e});return u(`/public-file-shares?${n}`)},createPublicFileShare:t=>u("/public-file-shares",{method:"POST",body:JSON.stringify(t)}),revokePublicFileShare:t=>u(`/public-file-shares/${encodeURIComponent(t)}`,{method:"DELETE"}),revokePublicSessionShares:(t,e)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}`,{method:"DELETE"}),freezePublicSessionLiveShares:(t,e)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}/freeze-live`,{method:"POST"}),freezePublicSessionViewerToken:(t,e,n)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}/viewers/${encodeURIComponent(n)}/freeze`,{method:"POST"}),disconnectPublicSessionViewerToken:(t,e,n)=>u(`/public-shares/sessions/${encodeURIComponent(t)}/${encodeURIComponent(e)}/viewers/${encodeURIComponent(n)}`,{method:"DELETE"}),getDevices:()=>u("/devices"),startDevice:t=>u(`/devices/${encodeURIComponent(t)}/start`,{method:"POST"}),stopDevice:t=>u(`/devices/${encodeURIComponent(t)}/stop`,{method:"POST"}),downloadDeviceBridge:()=>u("/devices/bridge/download",{method:"POST"}),getEmulators:()=>u("/devices"),startEmulator:t=>u(`/devices/${encodeURIComponent(t)}/start`,{method:"POST"}),stopEmulator:t=>u(`/devices/${encodeURIComponent(t)}/stop`,{method:"POST"}),downloadEmulatorBridge:()=>u("/devices/bridge/download",{method:"POST"})},lu={projects:!0,uploads:!0,temp:!0,home:!1,custom:[]};export{Ji as $,gi as A,yc as B,Va as C,lu as D,Ai as E,tu as F,Mt as G,I as H,fe as I,ic as J,Wc as K,Ic as L,Cc as M,vc as N,Mi as O,Pn as P,Nc as Q,wi as R,bc as S,Fc as T,be as U,Z as V,Xc as W,Yc as X,ao as Y,Kc as Z,Lc as _,xe as a,wc as a0,jc as a1,Rc as a2,xc as a3,Ec as a4,_c as a5,Pc as a6,Mc as a7,lc as a8,Gc as a9,Hc as aA,Jc as aB,du as aa,Tc as ab,He as ac,Qc as ad,Bc as ae,Oc as af,kc as ag,ou as ah,au as ai,cu as aj,ru as ak,V as al,re as am,su as an,F as ao,Zo as ap,nu as aq,Sa as ar,Vn as as,iu as at,qc as au,Vc as av,zc as aw,U as ax,Ve as ay,Ac as az,Pt as b,dc as c,eu as d,uu as e,Zc as f,dt as g,u as h,Dc as i,Uc as j,H as k,Cn as l,pc as m,pi as n,Tt as o,In as p,wt as q,hc as r,di as s,Y as t,$c as u,mc as v,fc as w,gc as x,Si as y,Sc as z};