openpond 0.0.69 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/dist/chunks/{app-layer-EXXOWJ5H.js → app-layer-XEYHFJHI.js} +2 -2
  2. package/dist/chunks/{app-server-runtime-7FBQBE3C.js → app-server-runtime-Y6MW4XCG.js} +7 -6
  3. package/dist/chunks/{apps-RZSDOFAG.js → apps-GSXUDK6V.js} +2 -2
  4. package/dist/chunks/{chunk-SFMNGWNO.js → chunk-2JABRRNR.js} +1 -1
  5. package/dist/chunks/{chunk-MMRJNSWY.js → chunk-6G6MDZLM.js} +1096 -120
  6. package/dist/chunks/{chunk-NPNIL6SQ.js → chunk-AN2EYCN3.js} +1 -1
  7. package/dist/chunks/{chunk-F36ZVO6U.js → chunk-CNTM26OW.js} +1 -1
  8. package/dist/chunks/{chunk-FEOLMLYU.js → chunk-EFET7LB7.js} +21 -2
  9. package/dist/chunks/{training-5CPTZRVC.js → chunk-J7PYGDRY.js} +251 -16
  10. package/dist/chunks/{chunk-Y57RTLVV.js → chunk-N3TGCM7J.js} +93 -35
  11. package/dist/chunks/{chunk-BLFIIAWZ.js → chunk-NTK22KJD.js} +68 -21
  12. package/dist/chunks/{chunk-QTN6HXOR.js → chunk-P6JLLWMI.js} +2 -2
  13. package/dist/chunks/chunk-R3C3MNSI.js +140 -0
  14. package/dist/chunks/{chunk-7C4OIFOC.js → chunk-TGM5IPYO.js} +31 -3
  15. package/dist/chunks/{chunk-OOM2PHBE.js → chunk-TZWAUV2L.js} +1130 -226
  16. package/dist/chunks/{cli-HIXVXM72.js → cli-L5VPOV6I.js} +6 -5
  17. package/dist/chunks/continual-FYDKLCO7.js +803 -0
  18. package/dist/chunks/{core-commands-34SVH6ZQ.js → core-commands-MAN3CSJQ.js} +3 -3
  19. package/dist/chunks/{desktop-test-66DPBNJX.js → desktop-test-OE5SST2W.js} +2 -2
  20. package/dist/chunks/{extension-ZMRHCDO3.js → extension-J3CIEDP4.js} +968 -19
  21. package/dist/chunks/{help-COHCZEP2.js → help-JNGJJFU5.js} +1 -1
  22. package/dist/chunks/{opchat-2PGW2GNN.js → opchat-6HEQJFLL.js} +2 -2
  23. package/dist/chunks/{organizations-NZ4OY56V.js → organizations-MWAPNOCK.js} +5 -4
  24. package/dist/chunks/{profile-GEMTRPUG.js → profile-P7HMONTZ.js} +2 -2
  25. package/dist/chunks/{project-agent-NX6YBGWC.js → project-agent-2RAK7GAZ.js} +2 -2
  26. package/dist/chunks/{sandbox-command-UEY53OJO.js → sandbox-command-G22CPFNK.js} +2 -2
  27. package/dist/chunks/{sandbox-template-YKYRB645.js → sandbox-template-S4WRUWJ6.js} +3 -3
  28. package/dist/chunks/{src-IXYDKOBI.js → src-A6O6ZGIL.js} +15899 -8010
  29. package/dist/chunks/{src-LKJBD5AM.js → src-BKBZ7WLO.js} +4 -3
  30. package/dist/chunks/taskset-BMI7KOWP.js +66 -0
  31. package/dist/chunks/{teams-bot-K6KZHZJV.js → teams-bot-5VBYEN7M.js} +2 -2
  32. package/dist/chunks/training-UPVSGDTB.js +17 -0
  33. package/dist/chunks/{workspaces-WXM72UZF.js → workspaces-XM5BY3MO.js} +4 -2
  34. package/dist/cli.js +13 -13
  35. package/dist/web/assets/App-DfiCmBv6.js +173 -0
  36. package/dist/web/assets/{AppDialog-DX-xs3KA.js → AppDialog-CSXu5wRu.js} +1 -1
  37. package/dist/web/assets/{AppTerminalPanel-CYVj_ITT.js → AppTerminalPanel-y2bVL2RV.js} +2 -2
  38. package/dist/web/assets/{AppsView-ByjyGog7.js → AppsView-Bs9pwD2H.js} +1 -1
  39. package/dist/web/assets/{BrowserSidebar-BDwtMAZl.js → BrowserSidebar-CUgT5V1m.js} +1 -1
  40. package/dist/web/assets/{CartesianChart-Dv6jJfPR.js → CartesianChart-DA85hfrP.js} +1 -1
  41. package/dist/web/assets/{CollaborationTabs-CC5AIhMh.js → CollaborationTabs-B8mlPhM3.js} +1 -1
  42. package/dist/web/assets/{CommandMenu-Ct0Sx7yP.js → CommandMenu-EwUGCeC_.js} +1 -1
  43. package/dist/web/assets/{CommunityView-C_zVE0jg.js → CommunityView-IHNq-YJz.js} +1 -1
  44. package/dist/web/assets/{ComposerCreateImproveStrip-CNn4OywM.js → ComposerCreateImproveStrip-qOL2zA26.js} +1 -1
  45. package/dist/web/assets/{GetStartedView-DRFpHDLd.js → GetStartedView-C2ypO0v7.js} +1 -1
  46. package/dist/web/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  47. package/dist/web/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  48. package/dist/web/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  49. package/dist/web/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  50. package/dist/web/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  51. package/dist/web/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  52. package/dist/web/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  53. package/dist/web/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  54. package/dist/web/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  55. package/dist/web/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  56. package/dist/web/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  57. package/dist/web/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  58. package/dist/web/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  59. package/dist/web/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  60. package/dist/web/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  61. package/dist/web/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  62. package/dist/web/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  63. package/dist/web/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  64. package/dist/web/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  65. package/dist/web/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  66. package/dist/web/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  67. package/dist/web/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  68. package/dist/web/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  69. package/dist/web/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  70. package/dist/web/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  71. package/dist/web/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  72. package/dist/web/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  73. package/dist/web/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  74. package/dist/web/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  75. package/dist/web/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  76. package/dist/web/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  77. package/dist/web/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  78. package/dist/web/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  79. package/dist/web/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  80. package/dist/web/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  81. package/dist/web/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  82. package/dist/web/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  83. package/dist/web/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  84. package/dist/web/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  85. package/dist/web/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  86. package/dist/web/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  87. package/dist/web/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  88. package/dist/web/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  89. package/dist/web/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  90. package/dist/web/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  91. package/dist/web/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  92. package/dist/web/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  93. package/dist/web/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  94. package/dist/web/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  95. package/dist/web/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  96. package/dist/web/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  97. package/dist/web/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  98. package/dist/web/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  99. package/dist/web/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  100. package/dist/web/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  101. package/dist/web/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  102. package/dist/web/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  103. package/dist/web/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  104. package/dist/web/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  105. package/dist/web/assets/LabModelVersionDetailPage-BK0eoUlW.js +1 -0
  106. package/dist/web/assets/{LabSkillSidebar-B9jY4AgE.js → LabSkillSidebar-CRPb4qBn.js} +1 -1
  107. package/dist/web/assets/LabsRoute-Bw-HD6QC.js +2 -0
  108. package/dist/web/assets/LabsRoute-CGFgymTX.css +1 -0
  109. package/dist/web/assets/MainChatThread-Cu6_UnNE.js +2 -0
  110. package/dist/web/assets/MainPane-k1iII9e9.js +8 -0
  111. package/dist/web/assets/MarkdownText-N60tvLug.js +268 -0
  112. package/dist/web/assets/Messages-CYQFLElK.js +10 -0
  113. package/dist/web/assets/{NativeSkillSidebar-DjebFRoi.js → NativeSkillSidebar-zbx7WmOk.js} +1 -1
  114. package/dist/web/assets/{NewExperienceSwitcher-C-bJxHxY.js → NewExperienceSwitcher-B0zev5Sx.js} +1 -1
  115. package/dist/web/assets/{NewProjectDialog-Cx8QcZm7.js → NewProjectDialog-lZlzrp-R.js} +1 -1
  116. package/dist/web/assets/{OutputsPage-Y9HM-SHX.js → OutputsPage-B4zYYUT5.js} +1 -1
  117. package/dist/web/assets/{ProjectsPage-BBr58yKT.js → ProjectsPage-97wgc84s.js} +1 -1
  118. package/dist/web/assets/RightChatPanelStack-I2znDCc7.js +1 -0
  119. package/dist/web/assets/{RightSidebarHomePanel-Dx-1elSI.js → RightSidebarHomePanel-BUcWVJi-.js} +1 -1
  120. package/dist/web/assets/ScheduledWorkPage-Bp-t0eVj.js +1 -0
  121. package/dist/web/assets/SettingsView-C1xyn1Y4.js +6 -0
  122. package/dist/web/assets/{TeamChatView-Bkyhu40R.js → TeamChatView-Fj5_yjVE.js} +2 -2
  123. package/dist/web/assets/{TerminalOverlay-CaCkZDzO.js → TerminalOverlay-D2WBeJvp.js} +1 -1
  124. package/dist/web/assets/{TrainingCreationPanel-Vvi41WNT.js → TrainingCreationPanel-dYW_dh3M.js} +1 -1
  125. package/dist/web/assets/{TrainingDraftPanel-C2C3hffI.js → TrainingDraftPanel-zeJWmmW6.js} +1 -1
  126. package/dist/web/assets/{UsageSettingsSection-DpPBd-ra.js → UsageSettingsSection-B6SBqYuB.js} +2 -2
  127. package/dist/web/assets/WorkSidebarPanel-BwbWKpOZ.js +1 -0
  128. package/dist/web/assets/{WorkspaceDiffPanel-D_zKOW4K.js → WorkspaceDiffPanel-D9Kp0vFw.js} +6 -6
  129. package/dist/web/assets/WorkspaceEnvironmentMenu-D-3YGp06.js +32 -0
  130. package/dist/web/assets/WorkspaceGitDialogs-BUbzUN4m.js +1 -0
  131. package/dist/web/assets/{WorkspaceMonacoEditor--GOVrHFp.js → WorkspaceMonacoEditor-CXPY7bBI.js} +3 -3
  132. package/dist/web/assets/{arrow-up-right-BRZWXpqJ.js → arrow-up-right-C7VWgGQP.js} +1 -1
  133. package/dist/web/assets/{chat-file-links-CgFHK89C.js → chat-file-links-CqfMdhHQ.js} +1 -1
  134. package/dist/web/assets/chevron-up-DD9Tei-Q.js +1 -0
  135. package/dist/web/assets/{clipboard-dPd_3lpG.js → clipboard-B-8k7mlT.js} +1 -1
  136. package/dist/web/assets/{cloud-upload-DOwvN4hp.js → cloud-upload-CUVFzURz.js} +1 -1
  137. package/dist/web/assets/{cssMode-BM4j9M0D.js → cssMode-DYvfmqoL.js} +1 -1
  138. package/dist/web/assets/{folder-open-DavjPCw4.js → folder-open-CnbcQIy8.js} +1 -1
  139. package/dist/web/assets/{folder-plus-Dyqast6G.js → folder-plus-BOaLAKy4.js} +1 -1
  140. package/dist/web/assets/{git-commit-horizontal-s3X0cQlz.js → git-commit-horizontal-DQeHsooT.js} +1 -1
  141. package/dist/web/assets/{htmlMode-Nlx7ckXa.js → htmlMode-BXEI-BVY.js} +1 -1
  142. package/dist/web/assets/index-CGMb_VXm.css +1 -0
  143. package/dist/web/assets/{index-5-B6FIuE.js → index-D-VK8mST.js} +1 -1
  144. package/dist/web/assets/index-D-WCyNdJ.js +1 -0
  145. package/dist/web/assets/{info-CVvrNOHr.js → info-DtzDuGLn.js} +1 -1
  146. package/dist/web/assets/{jsonMode-B7monA6g.js → jsonMode-Dosjh_hK.js} +1 -1
  147. package/dist/web/assets/{lspLanguageFeatures-CcJ9GDtK.js → lspLanguageFeatures-BNe-6FJA.js} +1 -1
  148. package/dist/web/assets/{minimize-2-O1DnznGK.js → minimize-2-DnxKN5oK.js} +1 -1
  149. package/dist/web/assets/{monaco.contribution-QOOCizYq.js → monaco.contribution-CfF-ajhi.js} +2 -2
  150. package/dist/web/assets/{monaco.contribution-2PozfA9g.js → monaco.contribution-CnkROzNv.js} +2 -2
  151. package/dist/web/assets/{monaco.contribution-BSJ2jQTi.js → monaco.contribution-Dyns81H2.js} +2 -2
  152. package/dist/web/assets/{monaco.contribution-BMAF2bmO.js → monaco.contribution-ytyanGyj.js} +2 -2
  153. package/dist/web/assets/{play-BpCc5ZbR.js → play-B3o6IAQd.js} +1 -1
  154. package/dist/web/assets/{python-BK41iew-.js → python-B7zZ_9Z_.js} +1 -1
  155. package/dist/web/assets/{refresh-cw-Csoy1ev1.js → refresh-cw-DSJZXa8S.js} +1 -1
  156. package/dist/web/assets/{save-Dbztj0W7.js → save-iC-AXHN6.js} +1 -1
  157. package/dist/web/assets/square-B2roZTxf.js +1 -0
  158. package/dist/web/assets/{toggleHighContrast-DrmwDpyz.js → toggleHighContrast-CjlV4YHK.js} +1 -1
  159. package/dist/web/assets/{training-daZlCtKV.css → training-eg6uFi3M.css} +1 -1
  160. package/dist/web/assets/{tsMode-CFgCMr7d.js → tsMode-XmKmSq0B.js} +1 -1
  161. package/dist/web/assets/{upload-C5nhiSMq.js → upload-BgHXNjfJ.js} +1 -1
  162. package/dist/web/assets/{useLocalAgentSchedules-LAsobERb.js → useLocalAgentSchedules-CVJz0AMr.js} +1 -1
  163. package/dist/web/assets/{wifi-off-BHxh2UbA.js → wifi-off-CneL8bDZ.js} +1 -1
  164. package/dist/web/assets/{workers-FKb-NyBI.js → workers-CT7VYBR5.js} +1 -1
  165. package/dist/web/assets/{yaml-C5DbF9S6.js → yaml-CF8jchCz.js} +1 -1
  166. package/dist/web/index.html +2 -2
  167. package/docs/command-reference.md +58 -2
  168. package/package.json +3 -1
  169. package/dist/web/assets/App-BF9L0JUv.js +0 -171
  170. package/dist/web/assets/LabModelVersionDetailPage-BzF-IVXQ.js +0 -1
  171. package/dist/web/assets/LabsRoute-CS_orT9s.css +0 -1
  172. package/dist/web/assets/LabsRoute-Di1Zs4gZ.js +0 -2
  173. package/dist/web/assets/MainChatThread-8VzlD8Hi.js +0 -2
  174. package/dist/web/assets/MainPane-StAOFINE.js +0 -6
  175. package/dist/web/assets/MarkdownText-B8D_ftSJ.js +0 -9
  176. package/dist/web/assets/Messages-TY62tiDp.js +0 -10
  177. package/dist/web/assets/RightChatPanelStack-DzUbDKwp.js +0 -1
  178. package/dist/web/assets/ScheduledWorkPage-BuXw_W8b.js +0 -1
  179. package/dist/web/assets/SettingsView-DB_zPHYY.js +0 -6
  180. package/dist/web/assets/WorkSidebarPanel-CeWGboTh.js +0 -1
  181. package/dist/web/assets/WorkspaceEnvironmentMenu-BTz9FISP.js +0 -32
  182. package/dist/web/assets/WorkspaceGitDialogs-BnBRUYpS.js +0 -1
  183. package/dist/web/assets/activity-DA5DNQwD.js +0 -1
  184. package/dist/web/assets/chevron-up-DSv2auz_.js +0 -1
  185. package/dist/web/assets/git-branch-zKnZdQiX.js +0 -1
  186. package/dist/web/assets/index-CQ3CPVHZ.css +0 -1
  187. package/dist/web/assets/index-CuoGlf-W.js +0 -1
  188. package/dist/web/assets/square-ju7fWa0W.js +0 -1
@@ -1,171 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-Ct0Sx7yP.js","./index-5-B6FIuE.js","./index-CQ3CPVHZ.css","./CommandMenu-hNQCm8mw.css","./SettingsView-DB_zPHYY.js","./chat-file-links-CgFHK89C.js","./refresh-cw-Csoy1ev1.js","./save-Dbztj0W7.js","./folder-open-DavjPCw4.js","./chevron-up-DSv2auz_.js","./play-BpCc5ZbR.js","./wifi-off-BHxh2UbA.js","./useLocalAgentSchedules-LAsobERb.js","./cloud-upload-DOwvN4hp.js","./git-commit-horizontal-s3X0cQlz.js","./index-CuoGlf-W.js","./folder-plus-Dyqast6G.js","./AppDialog-DX-xs3KA.js","./WorkspaceDiffPanel-D_zKOW4K.js","./MarkdownText-B8D_ftSJ.js","./desktop-files-BQj1J-ob.js","./training-model-data-CKOkpBBL.js","./info-CVvrNOHr.js","./minimize-2-O1DnznGK.js","./clipboard-dPd_3lpG.js","./SettingsView-BRPrJuP5.css","./git-dialogs-BZDqS1eT.css","./NewProjectDialog-Cx8QcZm7.js","./WorkspaceGitDialogs-BnBRUYpS.js","./git-branch-zKnZdQiX.js","./upload-C5nhiSMq.js","./WorkspaceEnvironmentMenu-BTz9FISP.js","./square-ju7fWa0W.js","./activity-DA5DNQwD.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-StAOFINE.js","./arrow-up-right-BRZWXpqJ.js"])))=>i.map(i=>d[i]);
2
- import{r as g,j as v,_ as Xo}from"./index-5-B6FIuE.js";var wf;function ge(e,t,n){function a(l,p){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:p,constr:s,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,p);const m=s.prototype,f=Object.keys(m);for(let S=0;S<f.length;S++){const y=f[S];y in l||(l[y]=m[y].bind(l))}}const r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function s(l){var p;const m=n?.Parent?new i:this;a(m,l),(p=m._zod).deferred??(p.deferred=[]);for(const f of m._zod.deferred)f();return m}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class Br extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ob extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(wf=globalThis).__zod_globalConfig??(wf.__zod_globalConfig={});const Hm=globalThis.__zod_globalConfig;function Qa(e){return Hm}function Nb(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,r])=>t.indexOf(+a)===-1).map(([a,r])=>r)}function Zu(e,t){return typeof t=="bigint"?t.toString():t}function ac(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qm(e){return e==null}function Bm(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function e_(e,t){const n=e/t,a=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<r?0:n-a}const If=Symbol("evaluating");function At(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==If)return a===void 0&&(a=If,a=n()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Qo(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function vo(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function Cf(e){return JSON.stringify(e)}function t_(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const $b="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ps(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const n_=ac(()=>{if(Hm.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Wr(e){if(ps(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(ps(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Db(e){return Wr(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const a_=new Set(["string","number","symbol"]);function Kr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yo(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function nt(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function o_(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const r_={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function i_(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=vo(e._zod.def,{get shape(){const s={};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&(s[l]=n.shape[l])}return Qo(this,"shape",s),s},checks:[]});return yo(e,i)}function s_(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=vo(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&delete s[l]}return Qo(this,"shape",s),s},checks:[]});return yo(e,i)}function l_(e,t){if(!Wr(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=vo(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Qo(this,"shape",i),i}});return yo(e,r)}function c_(e,t){if(!Wr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=vo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Qo(this,"shape",a),a}});return yo(e,n)}function d_(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=vo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Qo(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return yo(e,n)}function u_(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=vo(t._zod.def,{get shape(){const l=t._zod.def.shape,p={...l};if(n)for(const m in n){if(!(m in l))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(p[m]=e?new e({type:"optional",innerType:l[m]}):l[m])}else for(const m in l)p[m]=e?new e({type:"optional",innerType:l[m]}):l[m];return Qo(this,"shape",p),p},checks:[]});return yo(t,s)}function m_(e,t,n){const a=vo(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return Qo(this,"shape",i),i}});return yo(t,a)}function Nr(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function p_(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function $r(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function ml(e){return typeof e=="string"?e:e?.message}function eo(e,t,n){const a=e.message?e.message:ml(e.inst?._zod.def?.error?.(e))??ml(t?.error?.(e))??ml(n.customError?.(e))??ml(n.localeError?.(e))??"Invalid input",{inst:r,continue:i,input:s,...l}=e;return l.path??(l.path=[]),l.message=a,t?.reportInput&&(l.input=s),l}function Fm(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function fs(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const Lb=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Zu,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},zb=ge("$ZodError",Lb),Ub=ge("$ZodError",Lb,{Parent:Error});function f_(e,t=n=>n.message){const n={},a=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):a.push(t(r));return{formErrors:a,fieldErrors:n}}function h_(e,t=n=>n.message){const n={_errors:[]},a=(r,i=[])=>{for(const s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(l=>a({issues:l},[...i,...s.path]));else if(s.code==="invalid_key")a({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")a({issues:s.issues},[...i,...s.path]);else{const l=[...i,...s.path];if(l.length===0)n._errors.push(t(s));else{let p=n,m=0;for(;m<l.length;){const f=l[m];m===l.length-1?(p[f]=p[f]||{_errors:[]},p[f]._errors.push(t(s))):p[f]=p[f]||{_errors:[]},p=p[f],m++}}}};return a(e),n}const Vm=e=>(t,n,a,r)=>{const i=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Br;if(s.issues.length){const l=new(r?.Err??e)(s.issues.map(p=>eo(p,i,Qa())));throw $b(l,r?.callee),l}return s.value},Wm=e=>async(t,n,a,r)=>{const i=a?{...a,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const l=new(r?.Err??e)(s.issues.map(p=>eo(p,i,Qa())));throw $b(l,r?.callee),l}return s.value},oc=e=>(t,n,a)=>{const r=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new Br;return i.issues.length?{success:!1,error:new(e??zb)(i.issues.map(s=>eo(s,r,Qa())))}:{success:!0,data:i.value}},g_=oc(Ub),rc=e=>async(t,n,a)=>{const r=a?{...a,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>eo(s,r,Qa())))}:{success:!0,data:i.value}},b_=rc(Ub),v_=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Vm(e)(t,n,r)},y_=e=>(t,n,a)=>Vm(e)(t,n,a),S_=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Wm(e)(t,n,r)},x_=e=>async(t,n,a)=>Wm(e)(t,n,a),k_=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return oc(e)(t,n,r)},__=e=>(t,n,a)=>oc(e)(t,n,a),w_=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return rc(e)(t,n,r)},I_=e=>async(t,n,a)=>rc(e)(t,n,a),C_=/^[cC][0-9a-z]{6,}$/,R_=/^[0-9a-z]+$/,A_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,P_=/^[0-9a-vA-V]{20}$/,T_=/^[A-Za-z0-9]{27}$/,E_=/^[a-zA-Z0-9_-]{21}$/,M_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,j_=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Rf=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,O_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,N_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $_(){return new RegExp(N_,"u")}const D_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,L_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,z_=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,U_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,H_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Hb=/^[A-Za-z0-9_-]*$/,q_=/^https?$/,B_=/^\+[1-9]\d{6,14}$/,qb="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",F_=new RegExp(`^${qb}$`);function Bb(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function V_(e){return new RegExp(`^${Bb(e)}$`)}function W_(e){const t=Bb({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const a=`${t}(?:${n.join("|")})`;return new RegExp(`^${qb}T(?:${a})$`)}const K_=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},G_=/^-?\d+$/,Fb=/^-?\d+(?:\.\d+)?$/,Z_=/^(?:true|false)$/i,J_=/^null$/i,Y_=/^[^A-Z]*$/,X_=/^[^a-z]*$/,Zn=ge("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Vb={number:"number",bigint:"bigint",object:"date"},Wb=ge("$ZodCheckLessThan",(e,t)=>{Zn.init(e,t);const n=Vb[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Kb=ge("$ZodCheckGreaterThan",(e,t)=>{Zn.init(e,t);const n=Vb[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Q_=ge("$ZodCheckMultipleOf",(e,t)=>{Zn.init(e,t),e._zod.onattach.push(n=>{var a;(a=n._zod.bag).multipleOf??(a.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):e_(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),ew=ge("$ZodCheckNumberFormat",(e,t)=>{Zn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[r,i]=r_[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=r,l.maximum=i,n&&(l.pattern=G_)}),e._zod.check=s=>{const l=s.value;if(n){if(!Number.isInteger(l)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?s.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort});return}}l<r&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),l>i&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),tw=ge("$ZodCheckMaxLength",(e,t)=>{var n;Zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!qm(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const r=a.value;if(r.length<=t.maximum)return;const s=Fm(r);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),nw=ge("$ZodCheckMinLength",(e,t)=>{var n;Zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!qm(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const r=a.value;if(r.length>=t.minimum)return;const s=Fm(r);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),aw=ge("$ZodCheckLengthEquals",(e,t)=>{var n;Zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!qm(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=a=>{const r=a.value,i=r.length;if(i===t.length)return;const s=Fm(r),l=i>t.length;a.issues.push({origin:s,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),ic=ge("$ZodCheckStringFormat",(e,t)=>{var n,a;Zn.init(e,t),e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),ow=ge("$ZodCheckRegex",(e,t)=>{ic.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),rw=ge("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Y_),ic.init(e,t)}),iw=ge("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=X_),ic.init(e,t)}),sw=ge("$ZodCheckIncludes",(e,t)=>{Zn.init(e,t);const n=Kr(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),lw=ge("$ZodCheckStartsWith",(e,t)=>{Zn.init(e,t);const n=new RegExp(`^${Kr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=a=>{a.value.startsWith(t.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:a.value,inst:e,continue:!t.abort})}}),cw=ge("$ZodCheckEndsWith",(e,t)=>{Zn.init(e,t);const n=new RegExp(`.*${Kr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=a=>{a.value.endsWith(t.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:a.value,inst:e,continue:!t.abort})}}),dw=ge("$ZodCheckOverwrite",(e,t)=>{Zn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class uw{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const a=t.split(`
3
- `).filter(s=>s),r=Math.min(...a.map(s=>s.length-s.trimStart().length)),i=a.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,r=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,r.join(`
4
- `))}}const mw={major:4,minor:4,patch:3},Ut=ge("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=mw;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const r of a)for(const i of r._zod.onattach)i(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=(s,l,p)=>{let m=Nr(s),f;for(const S of l){if(S._zod.def.when){if(p_(s)||!S._zod.def.when(s))continue}else if(m)continue;const y=s.issues.length,k=S._zod.check(s);if(k instanceof Promise&&p?.async===!1)throw new Br;if(f||k instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await k,s.issues.length!==y&&(m||(m=Nr(s,y)))});else{if(s.issues.length===y)continue;m||(m=Nr(s,y))}}return f?f.then(()=>s):s},i=(s,l,p)=>{if(Nr(s))return s.aborted=!0,s;const m=r(l,a,p);if(m instanceof Promise){if(p.async===!1)throw new Br;return m.then(f=>e._zod.parse(f,p))}return e._zod.parse(m,p)};e._zod.run=(s,l)=>{if(l.skipChecks)return e._zod.parse(s,l);if(l.direction==="backward"){const m=e._zod.parse({value:s.value,issues:[]},{...l,skipChecks:!0});return m instanceof Promise?m.then(f=>i(f,s,l)):i(m,s,l)}const p=e._zod.parse(s,l);if(p instanceof Promise){if(l.async===!1)throw new Br;return p.then(m=>r(m,a,l))}return r(p,a,l)}}At(e,"~standard",()=>({validate:r=>{try{const i=g_(e,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return b_(e,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Km=ge("$ZodString",(e,t)=>{Ut.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??K_(e._zod.bag),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ht=ge("$ZodStringFormat",(e,t)=>{ic.init(e,t),Km.init(e,t)}),pw=ge("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=j_),Ht.init(e,t)}),fw=ge("$ZodUUID",(e,t)=>{if(t.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(a===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Rf(a))}else t.pattern??(t.pattern=Rf());Ht.init(e,t)}),hw=ge("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=O_),Ht.init(e,t)}),gw=ge("$ZodURL",(e,t)=>{Ht.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===q_.source&&!/^https?:\/\//i.test(a)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const r=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=r.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),bw=ge("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=$_()),Ht.init(e,t)}),vw=ge("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=E_),Ht.init(e,t)}),yw=ge("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=C_),Ht.init(e,t)}),Sw=ge("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=R_),Ht.init(e,t)}),xw=ge("$ZodULID",(e,t)=>{t.pattern??(t.pattern=A_),Ht.init(e,t)}),kw=ge("$ZodXID",(e,t)=>{t.pattern??(t.pattern=P_),Ht.init(e,t)}),_w=ge("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=T_),Ht.init(e,t)}),ww=ge("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=W_(t)),Ht.init(e,t)}),Iw=ge("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=F_),Ht.init(e,t)}),Cw=ge("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=V_(t)),Ht.init(e,t)}),Rw=ge("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=M_),Ht.init(e,t)}),Aw=ge("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=D_),Ht.init(e,t),e._zod.bag.format="ipv4"}),Pw=ge("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=L_),Ht.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Tw=ge("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=z_),Ht.init(e,t)}),Ew=ge("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=U_),Ht.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[r,i]=a;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Gb(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Mw=ge("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=H_),Ht.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Gb(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function jw(e){if(!Hb.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Gb(n)}const Ow=ge("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Hb),Ht.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{jw(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Nw=ge("$ZodE164",(e,t)=>{t.pattern??(t.pattern=B_),Ht.init(e,t)});function $w(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const r=JSON.parse(atob(a));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const Dw=ge("$ZodJWT",(e,t)=>{Ht.init(e,t),e._zod.check=n=>{$w(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Zb=ge("$ZodNumber",(e,t)=>{Ut.init(e,t),e._zod.pattern=e._zod.bag.pattern??Fb,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...i?{received:i}:{}}),n}}),Lw=ge("$ZodNumberFormat",(e,t)=>{ew.init(e,t),Zb.init(e,t)}),zw=ge("$ZodBoolean",(e,t)=>{Ut.init(e,t),e._zod.pattern=Z_,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),Uw=ge("$ZodNull",(e,t)=>{Ut.init(e,t),e._zod.pattern=J_,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),Hw=ge("$ZodUnknown",(e,t)=>{Ut.init(e,t),e._zod.parse=n=>n}),qw=ge("$ZodNever",(e,t)=>{Ut.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Af(e,t,n){e.issues.length&&t.issues.push(...$r(n,e.issues)),t.value[n]=e.value}const Bw=ge("$ZodArray",(e,t)=>{Ut.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const i=[];for(let s=0;s<r.length;s++){const l=r[s],p=t.element._zod.run({value:l,issues:[]},a);p instanceof Promise?i.push(p.then(m=>Af(m,n,s))):Af(p,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function zl(e,t,n,a,r,i){const s=n in a;if(e.issues.length){if(r&&i&&!s)return;t.issues.push(...$r(n,e.issues))}if(!s&&!r){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function Jb(e){const t=Object.keys(e.shape);for(const a of t)if(!e.shape?.[a]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const n=o_(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Yb(e,t,n,a,r,i){const s=[],l=r.keySet,p=r.catchall._zod,m=p.def.type,f=p.optin==="optional",S=p.optout==="optional";for(const y in t){if(y==="__proto__"||l.has(y))continue;if(m==="never"){s.push(y);continue}const k=p.run({value:t[y],issues:[]},a);k instanceof Promise?e.push(k.then(R=>zl(R,n,y,t,f,S))):zl(k,n,y,t,f,S)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const Fw=ge("$ZodObject",(e,t)=>{if(Ut.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const p={...l};return Object.defineProperty(t,"shape",{value:p}),p}})}const a=ac(()=>Jb(t));At(e._zod,"propValues",()=>{const l=t.shape,p={};for(const m in l){const f=l[m]._zod;if(f.values){p[m]??(p[m]=new Set);for(const S of f.values)p[m].add(S)}}return p});const r=ps,i=t.catchall;let s;e._zod.parse=(l,p)=>{s??(s=a.value);const m=l.value;if(!r(m))return l.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),l;l.value={};const f=[],S=s.shape;for(const y of s.keys){const k=S[y],R=k._zod.optin==="optional",A=k._zod.optout==="optional",D=k._zod.run({value:m[y],issues:[]},p);D instanceof Promise?f.push(D.then(z=>zl(z,l,y,m,R,A))):zl(D,l,y,m,R,A)}return i?Yb(f,m,l,p,a.value,e):f.length?Promise.all(f).then(()=>l):l}}),Vw=ge("$ZodObjectJIT",(e,t)=>{Fw.init(e,t);const n=e._zod.parse,a=ac(()=>Jb(t)),r=y=>{const k=new uw(["shape","payload","ctx"]),R=a.value,A=x=>{const I=Cf(x);return`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`};k.write("const input = payload.value;");const D=Object.create(null);let z=0;for(const x of R.keys)D[x]=`key_${z++}`;k.write("const newResult = {};");for(const x of R.keys){const I=D[x],P=Cf(x),j=y[x],T=j?._zod?.optin==="optional",F=j?._zod?.optout==="optional";k.write(`const ${I} = ${A(x)};`),T&&F?k.write(`
5
- if (${I}.issues.length) {
6
- if (${P} in input) {
7
- payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
8
- ...iss,
9
- path: iss.path ? [${P}, ...iss.path] : [${P}]
10
- })));
11
- }
12
- }
13
-
14
- if (${I}.value === undefined) {
15
- if (${P} in input) {
16
- newResult[${P}] = undefined;
17
- }
18
- } else {
19
- newResult[${P}] = ${I}.value;
20
- }
21
-
22
- `):T?k.write(`
23
- if (${I}.issues.length) {
24
- payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
25
- ...iss,
26
- path: iss.path ? [${P}, ...iss.path] : [${P}]
27
- })));
28
- }
29
-
30
- if (${I}.value === undefined) {
31
- if (${P} in input) {
32
- newResult[${P}] = undefined;
33
- }
34
- } else {
35
- newResult[${P}] = ${I}.value;
36
- }
37
-
38
- `):k.write(`
39
- const ${I}_present = ${P} in input;
40
- if (${I}.issues.length) {
41
- payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
42
- ...iss,
43
- path: iss.path ? [${P}, ...iss.path] : [${P}]
44
- })));
45
- }
46
- if (!${I}_present && !${I}.issues.length) {
47
- payload.issues.push({
48
- code: "invalid_type",
49
- expected: "nonoptional",
50
- input: undefined,
51
- path: [${P}]
52
- });
53
- }
54
-
55
- if (${I}_present) {
56
- if (${I}.value === undefined) {
57
- newResult[${P}] = undefined;
58
- } else {
59
- newResult[${P}] = ${I}.value;
60
- }
61
- }
62
-
63
- `)}k.write("payload.value = newResult;"),k.write("return payload;");const N=k.compile();return(x,I)=>N(y,x,I)};let i;const s=ps,l=!Hm.jitless,m=l&&n_.value,f=t.catchall;let S;e._zod.parse=(y,k)=>{S??(S=a.value);const R=y.value;return s(R)?l&&m&&k?.async===!1&&k.jitless!==!0?(i||(i=r(t.shape)),y=i(y,k),f?Yb([],R,y,k,S,e):y):n(y,k):(y.issues.push({expected:"object",code:"invalid_type",input:R,inst:e}),y)}});function Pf(e,t,n,a){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!Nr(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(s=>eo(s,a,Qa())))}),t)}const Xb=ge("$ZodUnion",(e,t)=>{Ut.init(e,t),At(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),At(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),At(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),At(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${a.map(r=>Bm(r.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,r)=>{if(n)return n(a,r);let i=!1;const s=[];for(const l of t.options){const p=l._zod.run({value:a.value,issues:[]},r);if(p instanceof Promise)s.push(p),i=!0;else{if(p.issues.length===0)return p;s.push(p)}}return i?Promise.all(s).then(l=>Pf(l,a,e,r)):Pf(s,a,e,r)}}),Ww=ge("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Xb.init(e,t);const n=e._zod.parse;At(e._zod,"propValues",()=>{const r={};for(const i of t.options){const s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[l,p]of Object.entries(s)){r[l]||(r[l]=new Set);for(const m of p)r[l].add(m)}}return r});const a=ac(()=>{const r=t.options,i=new Map;for(const s of r){const l=s._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const p of l){if(i.has(p))throw new Error(`Duplicate discriminator value "${String(p)}"`);i.set(p,s)}}return i});e._zod.parse=(r,i)=>{const s=r.value;if(!ps(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),r;const l=a.value.get(s?.[t.discriminator]);return l?l._zod.run(r,i):t.unionFallback||i.direction==="backward"?n(r,i):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(a.value.keys()),input:s,path:[t.discriminator],inst:e}),r)}}),Kw=ge("$ZodIntersection",(e,t)=>{Ut.init(e,t),e._zod.parse=(n,a)=>{const r=n.value,i=t.left._zod.run({value:r,issues:[]},a),s=t.right._zod.run({value:r,issues:[]},a);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([p,m])=>Tf(n,p,m)):Tf(n,i,s)}});function Ju(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Wr(e)&&Wr(t)){const n=Object.keys(t),a=Object.keys(e).filter(i=>n.indexOf(i)!==-1),r={...e,...t};for(const i of a){const s=Ju(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};r[i]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let a=0;a<e.length;a++){const r=e[a],i=t[a],s=Ju(r,i);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Tf(e,t,n){const a=new Map;let r;for(const l of t.issues)if(l.code==="unrecognized_keys"){r??(r=l);for(const p of l.keys)a.has(p)||a.set(p,{}),a.get(p).l=!0}else e.issues.push(l);for(const l of n.issues)if(l.code==="unrecognized_keys")for(const p of l.keys)a.has(p)||a.set(p,{}),a.get(p).r=!0;else e.issues.push(l);const i=[...a].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(i.length&&r&&e.issues.push({...r,keys:i}),Nr(e))return e;const s=Ju(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const Gw=ge("$ZodRecord",(e,t)=>{Ut.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;if(!Wr(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const i=[],s=t.keyType._zod.values;if(s){n.value={};const l=new Set;for(const m of s)if(typeof m=="string"||typeof m=="number"||typeof m=="symbol"){l.add(typeof m=="number"?m.toString():m);const f=t.keyType._zod.run({value:m,issues:[]},a);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(k=>eo(k,a,Qa())),input:m,path:[m],inst:e});continue}const S=f.value,y=t.valueType._zod.run({value:r[m],issues:[]},a);y instanceof Promise?i.push(y.then(k=>{k.issues.length&&n.issues.push(...$r(m,k.issues)),n.value[S]=k.value})):(y.issues.length&&n.issues.push(...$r(m,y.issues)),n.value[S]=y.value)}let p;for(const m in r)l.has(m)||(p=p??[],p.push(m));p&&p.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:p})}else{n.value={};for(const l of Reflect.ownKeys(r)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(r,l))continue;let p=t.keyType._zod.run({value:l,issues:[]},a);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&Fb.test(l)&&p.issues.length){const S=t.keyType._zod.run({value:Number(l),issues:[]},a);if(S instanceof Promise)throw new Error("Async schemas not supported in object keys currently");S.issues.length===0&&(p=S)}if(p.issues.length){t.mode==="loose"?n.value[l]=r[l]:n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(S=>eo(S,a,Qa())),input:l,path:[l],inst:e});continue}const f=t.valueType._zod.run({value:r[l],issues:[]},a);f instanceof Promise?i.push(f.then(S=>{S.issues.length&&n.issues.push(...$r(l,S.issues)),n.value[p.value]=S.value})):(f.issues.length&&n.issues.push(...$r(l,f.issues)),n.value[p.value]=f.value)}}return i.length?Promise.all(i).then(()=>n):n}}),Zw=ge("$ZodEnum",(e,t)=>{Ut.init(e,t);const n=Nb(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(r=>a_.has(typeof r)).map(r=>typeof r=="string"?Kr(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const s=r.value;return a.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Jw=ge("$ZodLiteral",(e,t)=>{if(Ut.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(a=>typeof a=="string"?Kr(a):a?Kr(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,r)=>{const i=a.value;return n.has(i)||a.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),a}}),Yw=ge("$ZodTransform",(e,t)=>{Ut.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new Ob(e.constructor.name);const r=t.transform(n.value,n);if(a.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(n.value=s,n.fallback=!0,n));if(r instanceof Promise)throw new Br;return n.value=r,n.fallback=!0,n}});function Ef(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Qb=ge("$ZodOptional",(e,t)=>{Ut.init(e,t),e._zod.optin="optional",e._zod.optout="optional",At(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),At(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bm(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const r=n.value,i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(s=>Ef(s,r)):Ef(i,r)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),Xw=ge("$ZodExactOptional",(e,t)=>{Qb.init(e,t),At(e._zod,"values",()=>t.innerType._zod.values),At(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),Qw=ge("$ZodNullable",(e,t)=>{Ut.init(e,t),At(e._zod,"optin",()=>t.innerType._zod.optin),At(e._zod,"optout",()=>t.innerType._zod.optout),At(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bm(n.source)}|null)$`):void 0}),At(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,a)=>n.value===null?n:t.innerType._zod.run(n,a)}),eI=ge("$ZodDefault",(e,t)=>{Ut.init(e,t),e._zod.optin="optional",At(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);if(n.value===void 0)return n.value=t.defaultValue,n;const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(i=>Mf(i,t)):Mf(r,t)}});function Mf(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const tI=ge("$ZodPrefault",(e,t)=>{Ut.init(e,t),e._zod.optin="optional",At(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>(a.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,a))}),nI=ge("$ZodNonOptional",(e,t)=>{Ut.init(e,t),At(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(a=>a!==void 0)):void 0}),e._zod.parse=(n,a)=>{const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(i=>jf(i,e)):jf(r,e)}});function jf(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const aI=ge("$ZodCatch",(e,t)=>{Ut.init(e,t),e._zod.optin="optional",At(e._zod,"optout",()=>t.innerType._zod.optout),At(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>eo(s,a,Qa()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(i=>eo(i,a,Qa()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),ev=ge("$ZodPipe",(e,t)=>{Ut.init(e,t),At(e._zod,"values",()=>t.in._zod.values),At(e._zod,"optin",()=>t.in._zod.optin),At(e._zod,"optout",()=>t.out._zod.optout),At(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const i=t.out._zod.run(n,a);return i instanceof Promise?i.then(s=>pl(s,t.in,a)):pl(i,t.in,a)}const r=t.in._zod.run(n,a);return r instanceof Promise?r.then(i=>pl(i,t.out,a)):pl(r,t.out,a)}});function pl(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const oI=ge("$ZodPreprocess",(e,t)=>{ev.init(e,t)}),rI=ge("$ZodReadonly",(e,t)=>{Ut.init(e,t),At(e._zod,"propValues",()=>t.innerType._zod.propValues),At(e._zod,"values",()=>t.innerType._zod.values),At(e._zod,"optin",()=>t.innerType?._zod?.optin),At(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(Of):Of(r)}});function Of(e){return e.value=Object.freeze(e.value),e}const iI=ge("$ZodCustom",(e,t)=>{Zn.init(e,t),Ut.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,r=t.fn(a);if(r instanceof Promise)return r.then(i=>Nf(i,n,a,e));Nf(r,n,a,e)}});function Nf(e,t,n,a){if(!e){const r={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(r.params=a._zod.def.params),t.issues.push(fs(r))}}var $f;class sI{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const a=n[0];return this._map.set(t,a),a&&typeof a=="object"&&"id"in a&&this._idmap.set(a.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const a={...this.get(n)??{}};delete a.id;const r={...a,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function lI(){return new sI}($f=globalThis).__zod_globalRegistry??($f.__zod_globalRegistry=lI());const is=globalThis.__zod_globalRegistry;function cI(e,t){return new e({type:"string",...nt(t)})}function dI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...nt(t)})}function Df(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...nt(t)})}function uI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...nt(t)})}function mI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...nt(t)})}function pI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...nt(t)})}function fI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...nt(t)})}function hI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...nt(t)})}function gI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...nt(t)})}function bI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...nt(t)})}function vI(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...nt(t)})}function yI(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...nt(t)})}function SI(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...nt(t)})}function xI(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...nt(t)})}function kI(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...nt(t)})}function _I(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...nt(t)})}function wI(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...nt(t)})}function II(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...nt(t)})}function CI(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...nt(t)})}function RI(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...nt(t)})}function AI(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...nt(t)})}function PI(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...nt(t)})}function TI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...nt(t)})}function EI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...nt(t)})}function MI(e,t){return new e({type:"string",format:"date",check:"string_format",...nt(t)})}function jI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...nt(t)})}function OI(e,t){return new e({type:"string",format:"duration",check:"string_format",...nt(t)})}function NI(e,t){return new e({type:"number",checks:[],...nt(t)})}function $I(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...nt(t)})}function DI(e,t){return new e({type:"boolean",...nt(t)})}function LI(e,t){return new e({type:"null",...nt(t)})}function zI(e){return new e({type:"unknown"})}function UI(e,t){return new e({type:"never",...nt(t)})}function Lf(e,t){return new Wb({check:"less_than",...nt(t),value:e,inclusive:!1})}function Ld(e,t){return new Wb({check:"less_than",...nt(t),value:e,inclusive:!0})}function zf(e,t){return new Kb({check:"greater_than",...nt(t),value:e,inclusive:!1})}function zd(e,t){return new Kb({check:"greater_than",...nt(t),value:e,inclusive:!0})}function Uf(e,t){return new Q_({check:"multiple_of",...nt(t),value:e})}function tv(e,t){return new tw({check:"max_length",...nt(t),maximum:e})}function Ul(e,t){return new nw({check:"min_length",...nt(t),minimum:e})}function nv(e,t){return new aw({check:"length_equals",...nt(t),length:e})}function HI(e,t){return new ow({check:"string_format",format:"regex",...nt(t),pattern:e})}function qI(e){return new rw({check:"string_format",format:"lowercase",...nt(e)})}function BI(e){return new iw({check:"string_format",format:"uppercase",...nt(e)})}function FI(e,t){return new sw({check:"string_format",format:"includes",...nt(t),includes:e})}function VI(e,t){return new lw({check:"string_format",format:"starts_with",...nt(t),prefix:e})}function WI(e,t){return new cw({check:"string_format",format:"ends_with",...nt(t),suffix:e})}function ai(e){return new dw({check:"overwrite",tx:e})}function KI(e){return ai(t=>t.normalize(e))}function GI(){return ai(e=>e.trim())}function ZI(){return ai(e=>e.toLowerCase())}function JI(){return ai(e=>e.toUpperCase())}function YI(){return ai(e=>t_(e))}function XI(e,t,n){return new e({type:"array",element:t,...nt(n)})}function QI(e,t,n){const a=nt(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function e1(e,t,n){return new e({type:"custom",check:"custom",fn:t,...nt(n)})}function t1(e,t){const n=n1(a=>(a.addIssue=r=>{if(typeof r=="string")a.issues.push(fs(r,a.value,n._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=a.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),a.issues.push(fs(i))}},e(a.value,a)),t);return n}function n1(e,t){const n=new Zn({check:"custom",...nt(t)});return n._zod.check=e,n}function av(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??is,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function rn(e,t,n={path:[],schemaPath:[]}){var a;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const l=e._zod.toJSONSchema?.();if(l)s.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,f);else{const y=s.schema,k=t.processors[r.type];if(!k)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);k(e,t,y,f)}const S=e._zod.parent;S&&(s.ref||(s.ref=S),rn(S,t,f),t.seen.get(S).isParent=!0)}const p=t.metadataRegistry.get(e);return p&&Object.assign(s.schema,p),t.io==="input"&&Mn(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((a=s.schema).default??(a.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function ov(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=new Map;for(const s of e.seen.entries()){const l=e.metadataRegistry.get(s[0])?.id;if(l){const p=a.get(l);if(p&&p!==s[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(l,s[0])}}const r=s=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const S=e.external.registry.get(s[0])?.id,y=e.external.uri??(R=>R);if(S)return{ref:y(S)};const k=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=k,{defId:k,ref:`${y("__shared")}#/${l}/${k}`}}if(s[1]===n)return{ref:"#"};const m=`#/${l}/`,f=s[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:m+f}},i=s=>{if(s[1].schema.$ref)return;const l=s[1],{ref:p,defId:m}=r(s);l.def={...l.schema},m&&(l.defId=m);const f=l.schema;for(const S in f)delete f[S];f.$ref=p};if(e.cycles==="throw")for(const s of e.seen.entries()){const l=s[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
64
-
65
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const l=s[1];if(t===s[0]){i(s);continue}if(e.external){const m=e.external.registry.get(s[0])?.id;if(t!==s[0]&&m){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(l.cycle){i(s);continue}if(l.count>1&&e.reused==="ref"){i(s);continue}}}function rv(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const p=e.seen.get(l);if(p.ref===null)return;const m=p.def??p.schema,f={...m},S=p.ref;if(p.ref=null,S){a(S);const k=e.seen.get(S),R=k.schema;if(R.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(R)):Object.assign(m,R),Object.assign(m,f),l._zod.parent===S)for(const D in m)D==="$ref"||D==="allOf"||D in f||delete m[D];if(R.$ref&&k.def)for(const D in m)D==="$ref"||D==="allOf"||D in k.def&&JSON.stringify(m[D])===JSON.stringify(k.def[D])&&delete m[D]}const y=l._zod.parent;if(y&&y!==S){a(y);const k=e.seen.get(y);if(k?.schema.$ref&&(m.$ref=k.schema.$ref,k.def))for(const R in m)R==="$ref"||R==="allOf"||R in k.def&&JSON.stringify(m[R])===JSON.stringify(k.def[R])&&delete m[R]}e.override({zodSchema:l,jsonSchema:m,path:p.path??[]})};for(const l of[...e.seen.entries()].reverse())a(l[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const l=e.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(l)}Object.assign(r,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&r.id===i&&delete r.id;const s=e.external?.defs??{};for(const l of e.seen.entries()){const p=l[1];p.def&&p.defId&&(p.def.id===p.defId&&delete p.def.id,s[p.defId]=p.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{const l=JSON.parse(JSON.stringify(r));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:Hl(t,"input",e.processors),output:Hl(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function Mn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;if(a.type==="transform")return!0;if(a.type==="array")return Mn(a.element,n);if(a.type==="set")return Mn(a.valueType,n);if(a.type==="lazy")return Mn(a.getter(),n);if(a.type==="promise"||a.type==="optional"||a.type==="nonoptional"||a.type==="nullable"||a.type==="readonly"||a.type==="default"||a.type==="prefault")return Mn(a.innerType,n);if(a.type==="intersection")return Mn(a.left,n)||Mn(a.right,n);if(a.type==="record"||a.type==="map")return Mn(a.keyType,n)||Mn(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Mn(a.in,n)||Mn(a.out,n);if(a.type==="object"){for(const r in a.shape)if(Mn(a.shape[r],n))return!0;return!1}if(a.type==="union"){for(const r of a.options)if(Mn(r,n))return!0;return!1}if(a.type==="tuple"){for(const r of a.items)if(Mn(r,n))return!0;return!!(a.rest&&Mn(a.rest,n))}return!1}const a1=(e,t={})=>n=>{const a=av({...n,processors:t});return rn(e,a),ov(a,e),rv(a,e)},Hl=(e,t,n={})=>a=>{const{libraryOptions:r,target:i}=a??{},s=av({...r??{},target:i,io:t,processors:n});return rn(e,s),ov(s,e),rv(s,e)},o1={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},r1=(e,t,n,a)=>{const r=n;r.type="string";const{minimum:i,maximum:s,format:l,patterns:p,contentEncoding:m}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof s=="number"&&(r.maxLength=s),l&&(r.format=o1[l]??l,r.format===""&&delete r.format,l==="time"&&delete r.format),m&&(r.contentEncoding=m),p&&p.size>0){const f=[...p];f.length===1?r.pattern=f[0].source:f.length>1&&(r.allOf=[...f.map(S=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:S.source}))])}},i1=(e,t,n,a)=>{const r=n,{minimum:i,maximum:s,format:l,multipleOf:p,exclusiveMaximum:m,exclusiveMinimum:f}=e._zod.bag;typeof l=="string"&&l.includes("int")?r.type="integer":r.type="number";const S=typeof f=="number"&&f>=(i??Number.NEGATIVE_INFINITY),y=typeof m=="number"&&m<=(s??Number.POSITIVE_INFINITY),k=t.target==="draft-04"||t.target==="openapi-3.0";S?k?(r.minimum=f,r.exclusiveMinimum=!0):r.exclusiveMinimum=f:typeof i=="number"&&(r.minimum=i),y?k?(r.maximum=m,r.exclusiveMaximum=!0):r.exclusiveMaximum=m:typeof s=="number"&&(r.maximum=s),typeof p=="number"&&(r.multipleOf=p)},s1=(e,t,n,a)=>{n.type="boolean"},l1=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},c1=(e,t,n,a)=>{n.not={}},d1=(e,t,n,a)=>{},u1=(e,t,n,a)=>{const r=e._zod.def,i=Nb(r.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},m1=(e,t,n,a)=>{const r=e._zod.def,i=[];for(const s of r.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){const s=i[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},p1=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},f1=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},h1=(e,t,n,a)=>{const r=n,i=e._zod.def,{minimum:s,maximum:l}=e._zod.bag;typeof s=="number"&&(r.minItems=s),typeof l=="number"&&(r.maxItems=l),r.type="array",r.items=rn(i.element,t,{...a,path:[...a.path,"items"]})},g1=(e,t,n,a)=>{const r=n,i=e._zod.def;r.type="object",r.properties={};const s=i.shape;for(const m in s)r.properties[m]=rn(s[m],t,{...a,path:[...a.path,"properties",m]});const l=new Set(Object.keys(s)),p=new Set([...l].filter(m=>{const f=i.shape[m]._zod;return t.io==="input"?f.optin===void 0:f.optout===void 0}));p.size>0&&(r.required=Array.from(p)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=rn(i.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},b1=(e,t,n,a)=>{const r=e._zod.def,i=r.inclusive===!1,s=r.options.map((l,p)=>rn(l,t,{...a,path:[...a.path,i?"oneOf":"anyOf",p]}));i?n.oneOf=s:n.anyOf=s},v1=(e,t,n,a)=>{const r=e._zod.def,i=rn(r.left,t,{...a,path:[...a.path,"allOf",0]}),s=rn(r.right,t,{...a,path:[...a.path,"allOf",1]}),l=m=>"allOf"in m&&Object.keys(m).length===1,p=[...l(i)?i.allOf:[i],...l(s)?s.allOf:[s]];n.allOf=p},y1=(e,t,n,a)=>{const r=n,i=e._zod.def;r.type="object";const s=i.keyType,p=s._zod.bag?.patterns;if(i.mode==="loose"&&p&&p.size>0){const f=rn(i.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});r.patternProperties={};for(const S of p)r.patternProperties[S.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=rn(i.keyType,t,{...a,path:[...a.path,"propertyNames"]})),r.additionalProperties=rn(i.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const m=s._zod.values;if(m){const f=[...m].filter(S=>typeof S=="string"||typeof S=="number");f.length>0&&(r.required=f)}},S1=(e,t,n,a)=>{const r=e._zod.def,i=rn(r.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=r.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},x1=(e,t,n,a)=>{const r=e._zod.def;rn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType},k1=(e,t,n,a)=>{const r=e._zod.def;rn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},_1=(e,t,n,a)=>{const r=e._zod.def;rn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},w1=(e,t,n,a)=>{const r=e._zod.def;rn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},I1=(e,t,n,a)=>{const r=e._zod.def,i=r.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?r.out:r.in:r.out;rn(s,t,a);const l=t.seen.get(e);l.ref=s},C1=(e,t,n,a)=>{const r=e._zod.def;rn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType,n.readOnly=!0},iv=(e,t,n,a)=>{const r=e._zod.def;rn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType},R1=ge("ZodISODateTime",(e,t)=>{ww.init(e,t),Kt.init(e,t)});function A1(e){return EI(R1,e)}const P1=ge("ZodISODate",(e,t)=>{Iw.init(e,t),Kt.init(e,t)});function T1(e){return MI(P1,e)}const E1=ge("ZodISOTime",(e,t)=>{Cw.init(e,t),Kt.init(e,t)});function M1(e){return jI(E1,e)}const j1=ge("ZodISODuration",(e,t)=>{Rw.init(e,t),Kt.init(e,t)});function O1(e){return OI(j1,e)}const N1=(e,t)=>{zb.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>h_(e,n)},flatten:{value:n=>f_(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Zu,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Zu,2)}},isEmpty:{get(){return e.issues.length===0}}})},la=ge("ZodError",N1,{Parent:Error}),$1=Vm(la),D1=Wm(la),L1=oc(la),z1=rc(la),U1=v_(la),H1=y_(la),q1=S_(la),B1=x_(la),F1=k_(la),V1=__(la),W1=w_(la),K1=I_(la),Hf=new WeakMap;function Rs(e,t,n){const a=Object.getPrototypeOf(e);let r=Hf.get(a);if(r||(r=new Set,Hf.set(a,r)),!r.has(t)){r.add(t);for(const i in n){const s=n[i];Object.defineProperty(a,i,{configurable:!0,enumerable:!1,get(){const l=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const qt=ge("ZodType",(e,t)=>(Ut.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Hl(e,"input"),output:Hl(e,"output")}}),e.toJSONSchema=a1(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>$1(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>L1(e,n,a),e.parseAsync=async(n,a)=>D1(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>z1(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>U1(e,n,a),e.decode=(n,a)=>H1(e,n,a),e.encodeAsync=async(n,a)=>q1(e,n,a),e.decodeAsync=async(n,a)=>B1(e,n,a),e.safeEncode=(n,a)=>F1(e,n,a),e.safeDecode=(n,a)=>V1(e,n,a),e.safeEncodeAsync=async(n,a)=>W1(e,n,a),e.safeDecodeAsync=async(n,a)=>K1(e,n,a),Rs(e,"ZodType",{check(...n){const a=this.def;return this.clone(vo(a,{checks:[...a.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return yo(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(LC(n,a))},superRefine(n,a){return this.check(zC(n,a))},overwrite(n){return this.check(ai(n))},optional(){return Vf(this)},exactOptional(){return CC(this)},nullable(){return Wf(this)},nullish(){return Vf(Wf(this))},nonoptional(n){return MC(this,n)},array(){return h(this)},or(n){return Cn([this,n])},and(n){return kC(this,n)},transform(n){return Kf(this,uv(n))},default(n){return PC(this,n)},prefault(n){return EC(this,n)},catch(n){return OC(this,n)},pipe(n){return Kf(this,n)},readonly(){return DC(this)},describe(n){const a=this.clone();return is.add(a,{description:n}),a},meta(...n){if(n.length===0)return is.get(this);const a=this.clone();return is.add(a,n[0]),a},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return is.get(e)?.description},configurable:!0}),e)),sv=ge("_ZodString",(e,t)=>{Km.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(a,r,i)=>r1(e,a,r);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Rs(e,"_ZodString",{regex(...a){return this.check(HI(...a))},includes(...a){return this.check(FI(...a))},startsWith(...a){return this.check(VI(...a))},endsWith(...a){return this.check(WI(...a))},min(...a){return this.check(Ul(...a))},max(...a){return this.check(tv(...a))},length(...a){return this.check(nv(...a))},nonempty(...a){return this.check(Ul(1,...a))},lowercase(a){return this.check(qI(a))},uppercase(a){return this.check(BI(a))},trim(){return this.check(GI())},normalize(...a){return this.check(KI(...a))},toLowerCase(){return this.check(ZI())},toUpperCase(){return this.check(JI())},slugify(){return this.check(YI())}})}),G1=ge("ZodString",(e,t)=>{Km.init(e,t),sv.init(e,t),e.email=n=>e.check(dI(Z1,n)),e.url=n=>e.check(hI(J1,n)),e.jwt=n=>e.check(TI(uC,n)),e.emoji=n=>e.check(gI(Y1,n)),e.guid=n=>e.check(Df(qf,n)),e.uuid=n=>e.check(uI(fl,n)),e.uuidv4=n=>e.check(mI(fl,n)),e.uuidv6=n=>e.check(pI(fl,n)),e.uuidv7=n=>e.check(fI(fl,n)),e.nanoid=n=>e.check(bI(X1,n)),e.guid=n=>e.check(Df(qf,n)),e.cuid=n=>e.check(vI(Q1,n)),e.cuid2=n=>e.check(yI(eC,n)),e.ulid=n=>e.check(SI(tC,n)),e.base64=n=>e.check(RI(lC,n)),e.base64url=n=>e.check(AI(cC,n)),e.xid=n=>e.check(xI(nC,n)),e.ksuid=n=>e.check(kI(aC,n)),e.ipv4=n=>e.check(_I(oC,n)),e.ipv6=n=>e.check(wI(rC,n)),e.cidrv4=n=>e.check(II(iC,n)),e.cidrv6=n=>e.check(CI(sC,n)),e.e164=n=>e.check(PI(dC,n)),e.datetime=n=>e.check(A1(n)),e.date=n=>e.check(T1(n)),e.time=n=>e.check(M1(n)),e.duration=n=>e.check(O1(n))});function o(e){return cI(G1,e)}const Kt=ge("ZodStringFormat",(e,t)=>{Ht.init(e,t),sv.init(e,t)}),Z1=ge("ZodEmail",(e,t)=>{hw.init(e,t),Kt.init(e,t)}),qf=ge("ZodGUID",(e,t)=>{pw.init(e,t),Kt.init(e,t)}),fl=ge("ZodUUID",(e,t)=>{fw.init(e,t),Kt.init(e,t)}),J1=ge("ZodURL",(e,t)=>{gw.init(e,t),Kt.init(e,t)}),Y1=ge("ZodEmoji",(e,t)=>{bw.init(e,t),Kt.init(e,t)}),X1=ge("ZodNanoID",(e,t)=>{vw.init(e,t),Kt.init(e,t)}),Q1=ge("ZodCUID",(e,t)=>{yw.init(e,t),Kt.init(e,t)}),eC=ge("ZodCUID2",(e,t)=>{Sw.init(e,t),Kt.init(e,t)}),tC=ge("ZodULID",(e,t)=>{xw.init(e,t),Kt.init(e,t)}),nC=ge("ZodXID",(e,t)=>{kw.init(e,t),Kt.init(e,t)}),aC=ge("ZodKSUID",(e,t)=>{_w.init(e,t),Kt.init(e,t)}),oC=ge("ZodIPv4",(e,t)=>{Aw.init(e,t),Kt.init(e,t)}),rC=ge("ZodIPv6",(e,t)=>{Pw.init(e,t),Kt.init(e,t)}),iC=ge("ZodCIDRv4",(e,t)=>{Tw.init(e,t),Kt.init(e,t)}),sC=ge("ZodCIDRv6",(e,t)=>{Ew.init(e,t),Kt.init(e,t)}),lC=ge("ZodBase64",(e,t)=>{Mw.init(e,t),Kt.init(e,t)}),cC=ge("ZodBase64URL",(e,t)=>{Ow.init(e,t),Kt.init(e,t)}),dC=ge("ZodE164",(e,t)=>{Nw.init(e,t),Kt.init(e,t)}),uC=ge("ZodJWT",(e,t)=>{Dw.init(e,t),Kt.init(e,t)}),lv=ge("ZodNumber",(e,t)=>{Zb.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(a,r,i)=>i1(e,a,r),Rs(e,"ZodNumber",{gt(a,r){return this.check(zf(a,r))},gte(a,r){return this.check(zd(a,r))},min(a,r){return this.check(zd(a,r))},lt(a,r){return this.check(Lf(a,r))},lte(a,r){return this.check(Ld(a,r))},max(a,r){return this.check(Ld(a,r))},int(a){return this.check(Bf(a))},safe(a){return this.check(Bf(a))},positive(a){return this.check(zf(0,a))},nonnegative(a){return this.check(zd(0,a))},negative(a){return this.check(Lf(0,a))},nonpositive(a){return this.check(Ld(0,a))},multipleOf(a,r){return this.check(Uf(a,r))},step(a,r){return this.check(Uf(a,r))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function d(e){return NI(lv,e)}const mC=ge("ZodNumberFormat",(e,t)=>{Lw.init(e,t),lv.init(e,t)});function Bf(e){return $I(mC,e)}const pC=ge("ZodBoolean",(e,t)=>{zw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>s1(e,n,a)});function C(e){return DI(pC,e)}const fC=ge("ZodNull",(e,t)=>{Uw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>l1(e,n,a)});function cv(e){return LI(fC,e)}const hC=ge("ZodUnknown",(e,t)=>{Hw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>d1()});function Se(){return zI(hC)}const gC=ge("ZodNever",(e,t)=>{qw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>c1(e,n,a)});function bC(e){return UI(gC,e)}const vC=ge("ZodArray",(e,t)=>{Bw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>h1(e,n,a,r),e.element=t.element,Rs(e,"ZodArray",{min(n,a){return this.check(Ul(n,a))},nonempty(n){return this.check(Ul(1,n))},max(n,a){return this.check(tv(n,a))},length(n,a){return this.check(nv(n,a))},unwrap(){return this.element}})});function h(e,t){return XI(vC,e,t)}const yC=ge("ZodObject",(e,t)=>{Vw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>g1(e,n,a,r),At(e,"shape",()=>t.shape),Rs(e,"ZodObject",{keyof(){return b(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Se()})},loose(){return this.clone({...this._zod.def,catchall:Se()})},strict(){return this.clone({...this._zod.def,catchall:bC()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return l_(this,n)},safeExtend(n){return c_(this,n)},merge(n){return d_(this,n)},pick(n){return i_(this,n)},omit(n){return s_(this,n)},partial(...n){return u_(mv,this,n[0])},required(...n){return m_(pv,this,n[0])}})});function c(e,t){const n={type:"object",shape:e??{},...nt(t)};return new yC(n)}const dv=ge("ZodUnion",(e,t)=>{Xb.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>b1(e,n,a,r),e.options=t.options});function Cn(e,t){return new dv({type:"union",options:e,...nt(t)})}const SC=ge("ZodDiscriminatedUnion",(e,t)=>{dv.init(e,t),Ww.init(e,t)});function dn(e,t,n){return new SC({type:"union",options:t,discriminator:e,...nt(n)})}const xC=ge("ZodIntersection",(e,t)=>{Kw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>v1(e,n,a,r)});function kC(e,t){return new xC({type:"intersection",left:e,right:t})}const Ff=ge("ZodRecord",(e,t)=>{Gw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>y1(e,n,a,r),e.keyType=t.keyType,e.valueType=t.valueType});function fe(e,t,n){return!t||!t._zod?new Ff({type:"record",keyType:o(),valueType:e,...nt(t)}):new Ff({type:"record",keyType:e,valueType:t,...nt(n)})}const Yu=ge("ZodEnum",(e,t)=>{Zw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(a,r,i)=>u1(e,a,r),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,r)=>{const i={};for(const s of a)if(n.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Yu({...t,checks:[],...nt(r),entries:i})},e.exclude=(a,r)=>{const i={...t.entries};for(const s of a)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Yu({...t,checks:[],...nt(r),entries:i})}});function b(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new Yu({type:"enum",entries:n,...nt(t)})}const _C=ge("ZodLiteral",(e,t)=>{Jw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>m1(e,n,a),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function w(e,t){return new _C({type:"literal",values:Array.isArray(e)?e:[e],...nt(t)})}const wC=ge("ZodTransform",(e,t)=>{Yw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>f1(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new Ob(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(fs(i,n.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(fs(s))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=r,n.fallback=!0,n)}});function uv(e){return new wC({type:"transform",transform:e})}const mv=ge("ZodOptional",(e,t)=>{Qb.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>iv(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function Vf(e){return new mv({type:"optional",innerType:e})}const IC=ge("ZodExactOptional",(e,t)=>{Xw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>iv(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function CC(e){return new IC({type:"optional",innerType:e})}const RC=ge("ZodNullable",(e,t)=>{Qw.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>S1(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function Wf(e){return new RC({type:"nullable",innerType:e})}const AC=ge("ZodDefault",(e,t)=>{eI.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>k1(e,n,a,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function PC(e,t){return new AC({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Db(t)}})}const TC=ge("ZodPrefault",(e,t)=>{tI.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>_1(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function EC(e,t){return new TC({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Db(t)}})}const pv=ge("ZodNonOptional",(e,t)=>{nI.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>x1(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function MC(e,t){return new pv({type:"nonoptional",innerType:e,...nt(t)})}const jC=ge("ZodCatch",(e,t)=>{aI.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>w1(e,n,a,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function OC(e,t){return new jC({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const fv=ge("ZodPipe",(e,t)=>{ev.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>I1(e,n,a,r),e.in=t.in,e.out=t.out});function Kf(e,t){return new fv({type:"pipe",in:e,out:t})}const NC=ge("ZodPreprocess",(e,t)=>{fv.init(e,t),oI.init(e,t)}),$C=ge("ZodReadonly",(e,t)=>{rI.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>C1(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function DC(e){return new $C({type:"readonly",innerType:e})}const hv=ge("ZodCustom",(e,t)=>{iI.init(e,t),qt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>p1(e,n)});function Ud(e,t){return QI(hv,(()=>!0),t)}function LC(e,t={}){return e1(hv,e,t)}function zC(e,t){return t1(e,t)}function UC(e,t){return new NC({type:"pipe",in:uv(e),out:t})}const Nn={custom:"custom"},Gm=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],er=b(Gm),sc=b(["active","preview","planned","deprecated"]),gv=b(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),HC=b(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),Gf=c({connected:C().default(!1),source:HC.default("none"),redacted:o().nullable().default(null),lastValidatedAt:o().nullable().default(null),lastError:o().nullable().default(null)}),Xu=c({hostedOpChat:C().default(!1),localRuntime:C().default(!0),localByok:C().default(!1),hostedByok:C().default(!1)}),qC=b(["hosted","provider","manual","none"]),Qu=c({chatCompletions:C().default(!0),streaming:C().default(!0),modelDiscovery:qC.default("none"),toolCalling:C().default(!1),reasoning:C().default(!1),imageInput:C().default(!1),structuredOutput:C().default(!1)}),BC=b(["hosted","provider","curated","manual","cache"]),em=c({streaming:C().default(!0),toolCalling:C().default(!1),reasoning:C().default(!1),vision:C().default(!1),structuredOutput:C().default(!1)}),FC=c({id:o().trim().min(1).max(300),providerId:er,displayName:o().trim().min(1).max(300),contextWindow:d().int().positive().nullable().default(null),outputLimit:d().int().positive().nullable().default(null),lifecycleStatus:sc.default("active"),source:BC,capabilities:em.default(()=>em.parse({})),raw:fe(o(),Se()).optional()}),VC=c({providerId:er,models:h(FC).default([]),fetchedAt:o().nullable().default(null),lastError:o().nullable().default(null),source:b(["none","hosted","provider","curated","manual"]).default("none")}),WC=c({enabled:C().default(!1),baseUrl:o().trim().min(1).max(2048).nullable().default(null),defaultModel:o().trim().min(1).max(300).nullable().default(null),modelOverrides:h(o().trim().min(1).max(300)).max(500).default([]),updatedAt:o().nullable().default(null)}),KC=c({enabled:C().optional(),baseUrl:o().trim().min(1).max(2048).nullable().optional(),defaultModel:o().trim().min(1).max(300).nullable().optional(),modelOverrides:h(o().trim().min(1).max(300)).max(500).optional()}),GC=c({id:o().trim().min(1).max(300),displayName:o().trim().min(1).max(300),contextWindow:d().int().positive().nullable().optional(),outputLimit:d().int().positive().nullable().optional(),lifecycleStatus:sc.optional(),capabilities:em.partial().optional()}),ZC=c({id:er,displayName:o().trim().min(1).max(160),lifecycleStatus:sc.default("active"),credentialModes:h(gv).default([]),routing:Xu,capabilities:Qu,defaultEnabled:C().optional(),defaultBaseUrl:o().trim().min(1).max(2048).nullable().optional(),defaultModel:o().trim().min(1).max(300).nullable().optional(),modelCacheSource:b(["none","hosted","provider","curated","manual"]),models:h(GC).default([])});c({version:w(1).default(1),generatedAt:o().datetime(),providers:h(ZC)});const JC=c({id:er,displayName:o().trim().min(1).max(160),lifecycleStatus:sc.default("active"),credentialModes:h(gv).default([]),routing:Xu.default(()=>Xu.parse({})),capabilities:Qu.default(()=>Qu.parse({})),credential:Gf.default(()=>Gf.parse({})),enabled:C().default(!1),available:C().default(!1),defaultModel:o().trim().min(1).max(300).nullable().default(null),modelIds:h(o().trim().min(1).max(300)).max(1e3).default([]),lastError:o().nullable().default(null)}),Zf=c({version:w(1).default(1),providers:fe(o(),WC).default({}),statuses:fe(o(),JC).default({}),modelCaches:fe(o(),VC).default({}),updatedAt:o().nullable().default(null)}),cn=c({providerId:er,modelId:o().trim().min(1).max(300)});c({providers:fe(o(),KC).optional()});c({source:b(["local_secret","env"]).default("local_secret"),value:o().min(1).max(2e4).optional(),envVar:o().trim().min(1).max(160).optional()}).superRefine((e,t)=>{e.source==="env"&&!e.envVar&&t.addIssue({code:"custom",path:["envVar"],message:"envVar is required when provider credential source is env."}),e.source==="local_secret"&&!e.value&&t.addIssue({code:"custom",path:["value"],message:"value is required when provider credential source is local_secret."})});c({source:b(["local_secret","env","chatgpt_subscription"]).optional()});c({modelId:o().trim().min(1).max(300).optional(),baseUrl:o().trim().min(1).max(2048).optional()});c({query:o().trim().max(200).optional(),refresh:C().default(!1),limit:d().int().positive().max(500).default(100)});c({query:o().trim().max(200).optional(),force:C().default(!1)});const YC=["coding","research","review","test","docs","planner","summarizer"];b(YC);const oi=o().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),bv=b(["none","worktree","copy_on_write"]),vv=b(["read_only","workspace_write","full_tools"]),yv=b(["disabled","parent_scoped"]),lc=b(["manual","balanced","proactive"]),XC=b(["queued","running","completed","failed","cancelled","needs_resume"]),Sv=["subagent.started","subagent.reported","subagent.completed","subagent.progress","subagent.failed","subagent.cancelled","subagent.cleanup","subagent.workspace_retained","subagent.workspace_retention_expiring","subagent.archived","subagent.message"];b(Sv);const QC=[{id:"coding",label:"Coding",description:"Make scoped code changes and return patch, diff, and test evidence.",defaultToolPolicy:"full_tools"},{id:"research",label:"Research",description:"Inspect docs, code, web or repo context and return cited findings.",defaultToolPolicy:"full_tools"},{id:"review",label:"Review",description:"Inspect diffs or implementation plans and return ranked findings.",defaultToolPolicy:"full_tools"},{id:"test",label:"Test",description:"Run or design validation in isolation and return command evidence.",defaultToolPolicy:"full_tools"},{id:"docs",label:"Docs",description:"Update or draft project documentation in an isolated target.",defaultToolPolicy:"full_tools"},{id:"planner",label:"Planner",description:"Decompose a goal into child assignments and context packs.",defaultToolPolicy:"full_tools"},{id:"summarizer",label:"Summarizer",description:"Compact transcripts, child results, and goal state for parent context.",defaultToolPolicy:"full_tools"}],Zm=c({id:oi,enabled:C().default(!0),modelRef:cn.nullable().default(null),isolationMode:bv.default("none"),maxConcurrentRuns:d().int().min(1).max(16).default(1),toolPolicy:vv.default("read_only"),background:C().default(!0),peerMessages:yv.default("parent_scoped")}),hs=c({enabled:C().default(!0),workspaceDefaultsVersion:w(1).default(1),toolDefaultsVersion:w(1).default(1),delegationMode:lc.default("manual"),defaultModelRef:cn.nullable().default(null),roles:h(Zm).max(64).default(()=>_v()),maxConcurrentRuns:d().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:d().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:d().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:dR(e.roles)})),cs=c({kind:b(["session","turn","file","diff","artifact"]),id:o().trim().min(1).max(500),label:o().trim().min(1).max(500)}),eR=c({kind:b(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:d().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:d().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:C().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),tR=b(["orient","edit","validate","report"]),nR=c({command:o().trim().min(1).max(2e3),status:b(["passed","failed","unknown"]).default("unknown"),exitCode:d().int().nullable().default(null),outputSummary:o().trim().max(5e3).nullable().default(null),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null)}),aR=c({phase:tR.default("orient"),inspectedFiles:h(o().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:h(o().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:h(o().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:h(o().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:h(o().trim().min(1).max(1e3)).max(200).default([]),changedFiles:h(o().trim().min(1).max(1e3)).max(500).default([]),patchRefs:h(cs).max(100).default([]),validationAttempts:h(nR).max(100).default([]),latestMeaningfulActivity:o().trim().max(5e3).nullable().default(null),currentBlocker:o().trim().max(5e3).nullable().default(null),updatedAt:o().nullable().default(null)}).default(()=>({phase:"orient",inspectedFiles:[],inspectedResources:[],repeatedSearches:[],repeatedReads:[],repeatedCommands:[],changedFiles:[],patchRefs:[],validationAttempts:[],latestMeaningfulActivity:null,currentBlocker:null,updatedAt:null})),oR=c({summary:o().trim().max(2e4).default(""),findings:h(o().trim().min(1).max(5e3)).max(200).default([]),artifacts:h(cs).max(200).default([]),patchRef:cs.nullable().default(null),diffRef:cs.nullable().default(null),testsRun:h(o().trim().min(1).max(2e3)).max(100).default([]),blockers:h(o().trim().min(1).max(5e3)).max(100).default([]),confidence:b(["low","medium","high"]).nullable().default(null),followUpNeeded:C().default(!1)}),xv=c({id:o().trim().min(1).max(200),parentSessionId:o().trim().min(1).max(200),parentTurnId:o().trim().min(1).max(200).nullable().default(null),childSessionId:o().trim().min(1).max(200).nullable().default(null),roleId:oi,objective:o().trim().min(1).max(5e4),modelRef:cn.nullable().default(null),isolationMode:bv.default("none"),toolPolicy:vv.default("read_only"),background:C().default(!0),peerMessages:yv.default("parent_scoped"),status:XC.default("queued"),progress:aR,evidenceRetention:eR,createdAt:o(),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null),updatedAt:o().nullable().default(null),error:o().nullable().default(null),report:oR.nullable().default(null),metadata:fe(o(),Se()).optional().default({})}),kv=b(["cleanup","archive","cleanup_and_archive"]);c({action:kv,reason:o().trim().min(1).max(2e3).nullable().default(null)});c({action:kv,run:xv,workspaceCleanup:fe(o(),Se()).nullable().default(null),sessionArchive:fe(o(),Se()).nullable().default(null),nextStep:o()});const rR=b(["question","answer","handoff","artifact","status","blocker"]),iR=b(["normal","interrupt"]),sR=c({status:b(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:h(o().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:h(o().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:o().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeParentReason:o().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:h(o().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:h(o().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:h(o().trim().min(1).max(200)).max(200).default([]),reason:o().trim().min(1).max(1e3).nullable().default(null)}),lR=c({id:o().trim().min(1).max(200),fromRunId:o().trim().min(1).max(200),toRunId:o().trim().min(1).max(200).nullable().default(null),toRole:oi.nullable().default(null),kind:rR,priority:iR.optional(),body:o().trim().min(1).max(5e4),refs:h(cs).max(100).default([]),delivery:sR.optional(),createdAt:o()});function _v(){return QC.map(e=>Zm.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function cR(){return hs.parse({})}function dR(e){const t=_v(),n=new Map(t.map(r=>[r.id,r])),a=[];for(const r of e??[]){const i=Zm.parse(r);n.has(i.id)?n.set(i.id,i):a.push(i)}return[...t.map(r=>n.get(r.id)??r),...a]}const uR=b(["session.started","session.title.updated","turn.started","assistant.delta","assistant.reasoning.delta","tool.started","tool.completed","skill.selected","skill.loaded","skill.load_failed","user_question.asked","user_question.answered","user_question.dismissed","approval.requested","approval.resolved","command.output","workspace_action","workspace_action_result","workspace.diff","create_improve.updated","session.context.updated","session.compaction.started","session.compaction.completed","session.compaction.failed","goal.continuation.started","goal.continuation.skipped","goal.continuation.failed","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","turn.completed","turn.failed","turn.interrupted","session.closed",...Sv,"diagnostic"]),Jf=c({id:o(),sequence:d().int().positive().optional(),sessionId:o().optional(),turnId:o().optional(),name:uR,timestamp:o(),source:b(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:o().optional(),appId:o().nullable().optional(),args:fe(o(),Se()).optional(),status:b(["started","completed","failed","pending"]).optional(),output:o().optional(),error:o().optional(),relatedDeploymentId:o().optional(),data:Se().optional()}),mR=c({id:o().trim().min(1).max(80),label:o().trim().min(1).max(160),description:o().trim().max(500).nullable().optional().default(null)}),pR=c({id:o().trim().min(1),sessionId:o().trim().min(1),turnId:o().trim().min(1),toolCallId:o().trim().min(1),question:o().trim().min(1).max(2e3),reason:o().trim().max(1e3).nullable().optional().default(null),options:h(mR).max(5).default([]),allowFreeform:C().default(!0),status:b(["pending","answered","dismissed"]),answer:c({optionId:o().trim().min(1).nullable(),text:o().max(4e3)}).nullable(),createdAt:o(),answeredAt:o().nullable()}),fR=c({questionId:o().trim().min(1),action:b(["answer","dismiss"]),optionId:o().trim().min(1).nullable().optional().default(null),text:o().trim().max(4e3).optional().default("")});c({kind:b(["session","project","draft"]),id:o().trim().min(1).max(300)});b(["unknown","idle","running","success","failed"]);b(["none","idle","running","success","failed","unknown"]);function hR(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _n={},hl={},so={},Yf;function As(){if(Yf)return so;Yf=1;function e(s){return typeof s>"u"||s===null}function t(s){return typeof s=="object"&&s!==null}function n(s){return Array.isArray(s)?s:e(s)?[]:[s]}function a(s,l){if(l){const p=Object.keys(l);for(let m=0,f=p.length;m<f;m+=1){const S=p[m];s[S]=l[S]}}return s}function r(s,l){let p="";for(let m=0;m<l;m+=1)p+=s;return p}function i(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return so.isNothing=e,so.isObject=t,so.toArray=n,so.repeat=r,so.isNegativeZero=i,so.extend=a,so}var Hd,Xf;function Ps(){if(Xf)return Hd;Xf=1;function e(n,a){let r="";const i=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(r+='in "'+n.mark.name+'" '),r+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!a&&n.mark.snippet&&(r+=`
66
-
67
- `+n.mark.snippet),i+" "+r):i}function t(n,a){Error.call(this),this.name="YAMLException",this.reason=n,this.mark=a,this.message=e(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t.prototype.toString=function(a){return this.name+": "+e(this,a)},Hd=t,Hd}var qd,Qf;function gR(){if(Qf)return qd;Qf=1;const e=As();function t(r,i,s,l,p){let m="",f="";const S=Math.floor(p/2)-1;return l-i>S&&(m=" ... ",i=l-S+m.length),s-l>S&&(f=" ...",s=l+S-f.length),{str:m+r.slice(i,s).replace(/\t/g,"→")+f,pos:l-i+m.length}}function n(r,i){return e.repeat(" ",i-r.length)+r}function a(r,i){if(i=Object.create(i||null),!r.buffer)return null;i.maxLength||(i.maxLength=79),typeof i.indent!="number"&&(i.indent=1),typeof i.linesBefore!="number"&&(i.linesBefore=3),typeof i.linesAfter!="number"&&(i.linesAfter=2);const s=/\r?\n|\r|\0/g,l=[0],p=[];let m,f=-1;for(;m=s.exec(r.buffer);)p.push(m.index),l.push(m.index+m[0].length),r.position<=m.index&&f<0&&(f=l.length-2);f<0&&(f=l.length-1);let S="";const y=Math.min(r.line+i.linesAfter,p.length).toString().length,k=i.maxLength-(i.indent+y+3);for(let A=1;A<=i.linesBefore&&!(f-A<0);A++){const D=t(r.buffer,l[f-A],p[f-A],r.position-(l[f]-l[f-A]),k);S=e.repeat(" ",i.indent)+n((r.line-A+1).toString(),y)+" | "+D.str+`
68
- `+S}const R=t(r.buffer,l[f],p[f],r.position,k);S+=e.repeat(" ",i.indent)+n((r.line+1).toString(),y)+" | "+R.str+`
69
- `,S+=e.repeat("-",i.indent+y+3+R.pos)+`^
70
- `;for(let A=1;A<=i.linesAfter&&!(f+A>=p.length);A++){const D=t(r.buffer,l[f+A],p[f+A],r.position-(l[f]-l[f+A]),k);S+=e.repeat(" ",i.indent)+n((r.line+A+1).toString(),y)+" | "+D.str+`
71
- `}return S.replace(/\n$/,"")}return qd=a,qd}var Bd,eh;function Dn(){if(eh)return Bd;eh=1;const e=Ps(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function a(i){const s={};return i!==null&&Object.keys(i).forEach(function(l){i[l].forEach(function(p){s[String(p)]=l})}),s}function r(i,s){if(s=s||{},Object.keys(s).forEach(function(l){if(t.indexOf(l)===-1)throw new e('Unknown option "'+l+'" is met in definition of "'+i+'" YAML type.')}),this.options=s,this.tag=i,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(l){return l},this.instanceOf=s.instanceOf||null,this.predicate=s.predicate||null,this.represent=s.represent||null,this.representName=s.representName||null,this.defaultStyle=s.defaultStyle||null,this.multi=s.multi||!1,this.styleAliases=a(s.styleAliases||null),n.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+i+'" YAML type.')}return Bd=r,Bd}var Fd,th;function wv(){if(th)return Fd;th=1;const e=Ps(),t=Dn();function n(i,s){const l=[];return i[s].forEach(function(p){let m=l.length;l.forEach(function(f,S){f.tag===p.tag&&f.kind===p.kind&&f.multi===p.multi&&(m=S)}),l[m]=p}),l}function a(){const i={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(l){l.multi?(i.multi[l.kind].push(l),i.multi.fallback.push(l)):i[l.kind][l.tag]=i.fallback[l.tag]=l}for(let l=0,p=arguments.length;l<p;l+=1)arguments[l].forEach(s);return i}function r(i){return this.extend(i)}return r.prototype.extend=function(s){let l=[],p=[];if(s instanceof t)p.push(s);else if(Array.isArray(s))p=p.concat(s);else if(s&&(Array.isArray(s.implicit)||Array.isArray(s.explicit)))s.implicit&&(l=l.concat(s.implicit)),s.explicit&&(p=p.concat(s.explicit));else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");l.forEach(function(f){if(!(f instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(f.loadKind&&f.loadKind!=="scalar")throw new e("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(f.multi)throw new e("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),p.forEach(function(f){if(!(f instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});const m=Object.create(r.prototype);return m.implicit=(this.implicit||[]).concat(l),m.explicit=(this.explicit||[]).concat(p),m.compiledImplicit=n(m,"implicit"),m.compiledExplicit=n(m,"explicit"),m.compiledTypeMap=a(m.compiledImplicit,m.compiledExplicit),m},Fd=r,Fd}var Vd,nh;function Iv(){if(nh)return Vd;nh=1;const e=Dn();return Vd=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),Vd}var Wd,ah;function Cv(){if(ah)return Wd;ah=1;const e=Dn();return Wd=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Wd}var Kd,oh;function Rv(){if(oh)return Kd;oh=1;const e=Dn();return Kd=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),Kd}var Gd,rh;function Av(){if(rh)return Gd;rh=1;const e=wv();return Gd=new e({explicit:[Iv(),Cv(),Rv()]}),Gd}var Zd,ih;function Pv(){if(ih)return Zd;ih=1;const e=Dn();function t(r){if(r===null)return!0;const i=r.length;return i===1&&r==="~"||i===4&&(r==="null"||r==="Null"||r==="NULL")}function n(){return null}function a(r){return r===null}return Zd=new e("tag:yaml.org,2002:null",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"}),Zd}var Jd,sh;function Tv(){if(sh)return Jd;sh=1;const e=Dn();function t(r){if(r===null)return!1;const i=r.length;return i===4&&(r==="true"||r==="True"||r==="TRUE")||i===5&&(r==="false"||r==="False"||r==="FALSE")}function n(r){return r==="true"||r==="True"||r==="TRUE"}function a(r){return Object.prototype.toString.call(r)==="[object Boolean]"}return Jd=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{lowercase:function(r){return r?"true":"false"},uppercase:function(r){return r?"TRUE":"FALSE"},camelcase:function(r){return r?"True":"False"}},defaultStyle:"lowercase"}),Jd}var Yd,lh;function Ev(){if(lh)return Yd;lh=1;const e=As(),t=Dn();function n(m){return m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102}function a(m){return m>=48&&m<=55}function r(m){return m>=48&&m<=57}function i(m){if(m===null)return!1;const f=m.length;let S=0,y=!1;if(!f)return!1;let k=m[S];if((k==="-"||k==="+")&&(k=m[++S]),k==="0"){if(S+1===f)return!0;if(k=m[++S],k==="b"){for(S++;S<f;S++){if(k=m[S],k!=="0"&&k!=="1")return!1;y=!0}return y&&isFinite(s(m))}if(k==="x"){for(S++;S<f;S++){if(!n(m.charCodeAt(S)))return!1;y=!0}return y&&isFinite(s(m))}if(k==="o"){for(S++;S<f;S++){if(!a(m.charCodeAt(S)))return!1;y=!0}return y&&isFinite(s(m))}}for(;S<f;S++){if(!r(m.charCodeAt(S)))return!1;y=!0}return y?isFinite(s(m)):!1}function s(m){let f=m,S=1,y=f[0];if((y==="-"||y==="+")&&(y==="-"&&(S=-1),f=f.slice(1),y=f[0]),f==="0")return 0;if(y==="0"){if(f[1]==="b")return S*parseInt(f.slice(2),2);if(f[1]==="x")return S*parseInt(f.slice(2),16);if(f[1]==="o")return S*parseInt(f.slice(2),8)}return S*parseInt(f,10)}function l(m){return s(m)}function p(m){return Object.prototype.toString.call(m)==="[object Number]"&&m%1===0&&!e.isNegativeZero(m)}return Yd=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:i,construct:l,predicate:p,represent:{binary:function(m){return m>=0?"0b"+m.toString(2):"-0b"+m.toString(2).slice(1)},octal:function(m){return m>=0?"0o"+m.toString(8):"-0o"+m.toString(8).slice(1)},decimal:function(m){return m.toString(10)},hexadecimal:function(m){return m>=0?"0x"+m.toString(16).toUpperCase():"-0x"+m.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),Yd}var Xd,ch;function Mv(){if(ch)return Xd;ch=1;const e=As(),t=Dn(),n=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),a=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function r(m){return m===null||!n.test(m)?!1:isFinite(parseFloat(m,10))?!0:a.test(m)}function i(m){let f=m.toLowerCase();const S=f[0]==="-"?-1:1;return"+-".indexOf(f[0])>=0&&(f=f.slice(1)),f===".inf"?S===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:f===".nan"?NaN:S*parseFloat(f,10)}const s=/^[-+]?[0-9]+e/;function l(m,f){if(isNaN(m))switch(f){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===m)switch(f){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===m)switch(f){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(m))return"-0.0";const S=m.toString(10);return s.test(S)?S.replace("e",".e"):S}function p(m){return Object.prototype.toString.call(m)==="[object Number]"&&(m%1!==0||e.isNegativeZero(m))}return Xd=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:r,construct:i,predicate:p,represent:l,defaultStyle:"lowercase"}),Xd}var Qd,dh;function jv(){return dh||(dh=1,Qd=Av().extend({implicit:[Pv(),Tv(),Ev(),Mv()]})),Qd}var eu,uh;function Ov(){return uh||(uh=1,eu=jv()),eu}var tu,mh;function Nv(){if(mh)return tu;mh=1;const e=Dn(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),n=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function a(s){return s===null?!1:t.exec(s)!==null||n.exec(s)!==null}function r(s){let l=0,p=null,m=t.exec(s);if(m===null&&(m=n.exec(s)),m===null)throw new Error("Date resolve error");const f=+m[1],S=+m[2]-1,y=+m[3];if(!m[4])return new Date(Date.UTC(f,S,y));const k=+m[4],R=+m[5],A=+m[6];if(m[7]){for(l=m[7].slice(0,3);l.length<3;)l+="0";l=+l}if(m[9]){const z=+m[10],N=+(m[11]||0);p=(z*60+N)*6e4,m[9]==="-"&&(p=-p)}const D=new Date(Date.UTC(f,S,y,k,R,A,l));return p&&D.setTime(D.getTime()-p),D}function i(s){return s.toISOString()}return tu=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:r,instanceOf:Date,represent:i}),tu}var nu,ph;function $v(){if(ph)return nu;ph=1;const e=Dn();function t(n){return n==="<<"||n===null}return nu=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),nu}var au,fh;function Dv(){if(fh)return au;fh=1;const e=Dn(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
72
- \r`;function n(s){if(s===null)return!1;let l=0;const p=s.length,m=t;for(let f=0;f<p;f++){const S=m.indexOf(s.charAt(f));if(!(S>64)){if(S<0)return!1;l+=6}}return l%8===0}function a(s){const l=s.replace(/[\r\n=]/g,""),p=l.length,m=t;let f=0;const S=[];for(let k=0;k<p;k++)k%4===0&&k&&(S.push(f>>16&255),S.push(f>>8&255),S.push(f&255)),f=f<<6|m.indexOf(l.charAt(k));const y=p%4*6;return y===0?(S.push(f>>16&255),S.push(f>>8&255),S.push(f&255)):y===18?(S.push(f>>10&255),S.push(f>>2&255)):y===12&&S.push(f>>4&255),new Uint8Array(S)}function r(s){let l="",p=0;const m=s.length,f=t;for(let y=0;y<m;y++)y%3===0&&y&&(l+=f[p>>18&63],l+=f[p>>12&63],l+=f[p>>6&63],l+=f[p&63]),p=(p<<8)+s[y];const S=m%3;return S===0?(l+=f[p>>18&63],l+=f[p>>12&63],l+=f[p>>6&63],l+=f[p&63]):S===2?(l+=f[p>>10&63],l+=f[p>>4&63],l+=f[p<<2&63],l+=f[64]):S===1&&(l+=f[p>>2&63],l+=f[p<<4&63],l+=f[64],l+=f[64]),l}function i(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return au=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:i,represent:r}),au}var ou,hh;function Lv(){if(hh)return ou;hh=1;const e=Dn(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(i){if(i===null)return!0;const s=[],l=i;for(let p=0,m=l.length;p<m;p+=1){const f=l[p];let S=!1;if(n.call(f)!=="[object Object]")return!1;let y;for(y in f)if(t.call(f,y))if(!S)S=!0;else return!1;if(!S)return!1;if(s.indexOf(y)===-1)s.push(y);else return!1}return!0}function r(i){return i!==null?i:[]}return ou=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:r}),ou}var ru,gh;function zv(){if(gh)return ru;gh=1;const e=Dn(),t=Object.prototype.toString;function n(r){if(r===null)return!0;const i=r,s=new Array(i.length);for(let l=0,p=i.length;l<p;l+=1){const m=i[l];if(t.call(m)!=="[object Object]")return!1;const f=Object.keys(m);if(f.length!==1)return!1;s[l]=[f[0],m[f[0]]]}return!0}function a(r){if(r===null)return[];const i=r,s=new Array(i.length);for(let l=0,p=i.length;l<p;l+=1){const m=i[l],f=Object.keys(m);s[l]=[f[0],m[f[0]]]}return s}return ru=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),ru}var iu,bh;function Uv(){if(bh)return iu;bh=1;const e=Dn(),t=Object.prototype.hasOwnProperty;function n(r){if(r===null)return!0;const i=r;for(const s in i)if(t.call(i,s)&&i[s]!==null)return!1;return!0}function a(r){return r!==null?r:{}}return iu=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),iu}var su,vh;function Jm(){return vh||(vh=1,su=Ov().extend({implicit:[Nv(),$v()],explicit:[Dv(),Lv(),zv(),Uv()]})),su}var yh;function bR(){if(yh)return hl;yh=1;const e=As(),t=Ps(),n=gR(),a=Jm(),r=Object.prototype.hasOwnProperty,i=1,s=2,l=3,p=4,m=1,f=2,S=3,y=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,k=/[\x85\u2028\u2029]/,R=/[,\[\]{}]/,A=/^(?:!|!!|![0-9A-Za-z-]+!)$/,D=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function z(u){return Object.prototype.toString.call(u)}function N(u){return u===10||u===13}function x(u){return u===9||u===32}function I(u){return u===9||u===32||u===10||u===13}function P(u){return u===44||u===91||u===93||u===123||u===125}function j(u){if(u>=48&&u<=57)return u-48;const M=u|32;return M>=97&&M<=102?M-97+10:-1}function T(u){return u===120?2:u===117?4:u===85?8:0}function F(u){return u>=48&&u<=57?u-48:-1}function q(u){switch(u){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
73
- `;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"…";case 95:return" ";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function $(u){return u<=65535?String.fromCharCode(u):String.fromCharCode((u-65536>>10)+55296,(u-65536&1023)+56320)}function V(u,M,H){M==="__proto__"?Object.defineProperty(u,M,{configurable:!0,enumerable:!0,writable:!0,value:H}):u[M]=H}const re=new Array(256),X=new Array(256);for(let u=0;u<256;u++)re[u]=q(u)?1:0,X[u]=q(u);function we(u,M){this.input=u,this.filename=M.filename||null,this.schema=M.schema||a,this.onWarning=M.onWarning||null,this.legacy=M.legacy||!1,this.json=M.json||!1,this.listener=M.listener||null,this.maxDepth=typeof M.maxDepth=="number"?M.maxDepth:100,this.maxTotalMergeKeys=typeof M.maxTotalMergeKeys=="number"?M.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=u.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function ye(u,M){const H={name:u.filename,buffer:u.input.slice(0,-1),position:u.position,line:u.line,column:u.position-u.lineStart};return H.snippet=n(H),new t(M,H)}function K(u,M){throw ye(u,M)}function Ee(u,M){u.onWarning&&u.onWarning.call(null,ye(u,M))}function xe(u,M,H){const ae=u.anchorMapTransactions;if(ae.length!==0){const O=ae[ae.length-1];r.call(O,M)||(O[M]={existed:r.call(u.anchorMap,M),value:u.anchorMap[M]})}u.anchorMap[M]=H}function se(u){u.anchorMapTransactions.push(Object.create(null))}function ke(u){const M=u.anchorMapTransactions.pop(),H=u.anchorMapTransactions;if(H.length===0)return;const ae=H[H.length-1],O=Object.keys(M);for(let Z=0,_=O.length;Z<_;Z+=1){const L=O[Z];r.call(ae,L)||(ae[L]=M[L])}}function ee(u){const M=u.anchorMapTransactions.pop(),H=Object.keys(M);for(let ae=H.length-1;ae>=0;ae-=1){const O=M[H[ae]];O.existed?u.anchorMap[H[ae]]=O.value:delete u.anchorMap[H[ae]]}}function pe(u){return{position:u.position,line:u.line,lineStart:u.lineStart,lineIndent:u.lineIndent,firstTabInLine:u.firstTabInLine,tag:u.tag,anchor:u.anchor,kind:u.kind,result:u.result}}function ve(u,M){u.position=M.position,u.line=M.line,u.lineStart=M.lineStart,u.lineIndent=M.lineIndent,u.firstTabInLine=M.firstTabInLine,u.tag=M.tag,u.anchor=M.anchor,u.kind=M.kind,u.result=M.result}const qe={YAML:function(M,H,ae){M.version!==null&&K(M,"duplication of %YAML directive"),ae.length!==1&&K(M,"YAML directive accepts exactly one argument");const O=/^([0-9]+)\.([0-9]+)$/.exec(ae[0]);O===null&&K(M,"ill-formed argument of the YAML directive");const Z=parseInt(O[1],10),_=parseInt(O[2],10);Z!==1&&K(M,"unacceptable YAML version of the document"),M.version=ae[0],M.checkLineBreaks=_<2,_!==1&&_!==2&&Ee(M,"unsupported YAML version of the document")},TAG:function(M,H,ae){let O;ae.length!==2&&K(M,"TAG directive accepts exactly two arguments");const Z=ae[0];O=ae[1],A.test(Z)||K(M,"ill-formed tag handle (first argument) of the TAG directive"),r.call(M.tagMap,Z)&&K(M,'there is a previously declared suffix for "'+Z+'" tag handle'),D.test(O)||K(M,"ill-formed tag prefix (second argument) of the TAG directive");try{O=decodeURIComponent(O)}catch{K(M,"tag prefix is malformed: "+O)}M.tagMap[Z]=O}};function Re(u,M,H,ae){if(M<H){const O=u.input.slice(M,H);if(ae)for(let Z=0,_=O.length;Z<_;Z+=1){const L=O.charCodeAt(Z);L===9||L>=32&&L<=1114111||K(u,"expected valid JSON character")}else y.test(O)&&K(u,"the stream contains non-printable characters");u.result+=O}}function ie(u,M,H,ae){e.isObject(H)||K(u,"cannot merge mappings; the provided source object is unacceptable");const O=Object.keys(H);for(let Z=0,_=O.length;Z<_;Z+=1){const L=O[Z];u.maxTotalMergeKeys!==-1&&++u.totalMergeKeys>u.maxTotalMergeKeys&&K(u,"merge keys exceeded maxTotalMergeKeys ("+u.maxTotalMergeKeys+")"),r.call(M,L)||(V(M,L,H[L]),ae[L]=!0)}}function Ie(u,M,H,ae,O,Z,_,L,oe){if(Array.isArray(O)){O=Array.prototype.slice.call(O);for(let Q=0,Y=O.length;Q<Y;Q+=1)Array.isArray(O[Q])&&K(u,"nested arrays are not supported inside keys"),typeof O=="object"&&z(O[Q])==="[object Object]"&&(O[Q]="[object Object]")}if(typeof O=="object"&&z(O)==="[object Object]"&&(O="[object Object]"),O=String(O),M===null&&(M={}),ae==="tag:yaml.org,2002:merge")if(Array.isArray(Z))for(let Q=0,Y=Z.length;Q<Y;Q+=1)ie(u,M,Z[Q],H);else ie(u,M,Z,H);else!u.json&&!r.call(H,O)&&r.call(M,O)&&(u.line=_||u.line,u.lineStart=L||u.lineStart,u.position=oe||u.position,K(u,"duplicated mapping key")),V(M,O,Z),delete H[O];return M}function $e(u){const M=u.input.charCodeAt(u.position);M===10?u.position++:M===13?(u.position++,u.input.charCodeAt(u.position)===10&&u.position++):K(u,"a line break is expected"),u.line+=1,u.lineStart=u.position,u.firstTabInLine=-1}function Je(u,M,H){let ae=0,O=u.input.charCodeAt(u.position);for(;O!==0;){for(;x(O);)O===9&&u.firstTabInLine===-1&&(u.firstTabInLine=u.position),O=u.input.charCodeAt(++u.position);if(M&&O===35)do O=u.input.charCodeAt(++u.position);while(O!==10&&O!==13&&O!==0);if(N(O))for($e(u),O=u.input.charCodeAt(u.position),ae++,u.lineIndent=0;O===32;)u.lineIndent++,O=u.input.charCodeAt(++u.position);else break}return H!==-1&&ae!==0&&u.lineIndent<H&&Ee(u,"deficient indentation"),ae}function et(u){let M=u.position,H=u.input.charCodeAt(M);return!!((H===45||H===46)&&H===u.input.charCodeAt(M+1)&&H===u.input.charCodeAt(M+2)&&(M+=3,H=u.input.charCodeAt(M),H===0||I(H)))}function st(u,M){M===1?u.result+=" ":M>1&&(u.result+=e.repeat(`
74
- `,M-1))}function Be(u,M,H){let ae,O,Z,_,L,oe;const Q=u.kind,Y=u.result;let ue=u.input.charCodeAt(u.position);if(I(ue)||P(ue)||ue===35||ue===38||ue===42||ue===33||ue===124||ue===62||ue===39||ue===34||ue===37||ue===64||ue===96)return!1;if(ue===63||ue===45){const le=u.input.charCodeAt(u.position+1);if(I(le)||H&&P(le))return!1}for(u.kind="scalar",u.result="",ae=O=u.position,Z=!1;ue!==0;){if(ue===58){const le=u.input.charCodeAt(u.position+1);if(I(le)||H&&P(le))break}else if(ue===35){const le=u.input.charCodeAt(u.position-1);if(I(le))break}else{if(u.position===u.lineStart&&et(u)||H&&P(ue))break;if(N(ue))if(_=u.line,L=u.lineStart,oe=u.lineIndent,Je(u,!1,-1),u.lineIndent>=M){Z=!0,ue=u.input.charCodeAt(u.position);continue}else{u.position=O,u.line=_,u.lineStart=L,u.lineIndent=oe;break}}Z&&(Re(u,ae,O,!1),st(u,u.line-_),ae=O=u.position,Z=!1),x(ue)||(O=u.position+1),ue=u.input.charCodeAt(++u.position)}return Re(u,ae,O,!1),u.result?!0:(u.kind=Q,u.result=Y,!1)}function He(u,M){let H,ae,O=u.input.charCodeAt(u.position);if(O!==39)return!1;for(u.kind="scalar",u.result="",u.position++,H=ae=u.position;(O=u.input.charCodeAt(u.position))!==0;)if(O===39)if(Re(u,H,u.position,!0),O=u.input.charCodeAt(++u.position),O===39)H=u.position,u.position++,ae=u.position;else return!0;else N(O)?(Re(u,H,ae,!0),st(u,Je(u,!1,M)),H=ae=u.position):u.position===u.lineStart&&et(u)?K(u,"unexpected end of the document within a single quoted scalar"):(u.position++,x(O)||(ae=u.position));K(u,"unexpected end of the stream within a single quoted scalar")}function Ne(u,M){let H,ae,O,Z=u.input.charCodeAt(u.position);if(Z!==34)return!1;for(u.kind="scalar",u.result="",u.position++,H=ae=u.position;(Z=u.input.charCodeAt(u.position))!==0;){if(Z===34)return Re(u,H,u.position,!0),u.position++,!0;if(Z===92){if(Re(u,H,u.position,!0),Z=u.input.charCodeAt(++u.position),N(Z))Je(u,!1,M);else if(Z<256&&re[Z])u.result+=X[Z],u.position++;else if((O=T(Z))>0){let _=O,L=0;for(;_>0;_--)Z=u.input.charCodeAt(++u.position),(O=j(Z))>=0?L=(L<<4)+O:K(u,"expected hexadecimal character");u.result+=$(L),u.position++}else K(u,"unknown escape sequence");H=ae=u.position}else N(Z)?(Re(u,H,ae,!0),st(u,Je(u,!1,M)),H=ae=u.position):u.position===u.lineStart&&et(u)?K(u,"unexpected end of the document within a double quoted scalar"):(u.position++,x(Z)||(ae=u.position))}K(u,"unexpected end of the stream within a double quoted scalar")}function E(u,M){let H=!0,ae,O,Z;const _=u.tag;let L;const oe=u.anchor;let Q,Y,ue,le;const ze=Object.create(null);let Pe,Oe,Ye,Le=u.input.charCodeAt(u.position);if(Le===91)Q=93,le=!1,L=[];else if(Le===123)Q=125,le=!0,L={};else return!1;for(u.anchor!==null&&xe(u,u.anchor,L),Le=u.input.charCodeAt(++u.position);Le!==0;){if(Je(u,!0,M),Le=u.input.charCodeAt(u.position),Le===Q)return u.position++,u.tag=_,u.anchor=oe,u.kind=le?"mapping":"sequence",u.result=L,!0;if(H?Le===44&&K(u,"expected the node content, but found ','"):K(u,"missed comma between flow collection entries"),Oe=Pe=Ye=null,Y=ue=!1,Le===63){const ut=u.input.charCodeAt(u.position+1);I(ut)&&(Y=ue=!0,u.position++,Je(u,!0,M))}ae=u.line,O=u.lineStart,Z=u.position,Ze(u,M,i,!1,!0),Oe=u.tag,Pe=u.result,Je(u,!0,M),Le=u.input.charCodeAt(u.position),(ue||u.line===ae)&&Le===58&&(Y=!0,Le=u.input.charCodeAt(++u.position),Je(u,!0,M),Ze(u,M,i,!1,!0),Ye=u.result),le?Ie(u,L,ze,Oe,Pe,Ye,ae,O,Z):Y?L.push(Ie(u,null,ze,Oe,Pe,Ye,ae,O,Z)):L.push(Pe),Je(u,!0,M),Le=u.input.charCodeAt(u.position),Le===44?(H=!0,Le=u.input.charCodeAt(++u.position)):H=!1}K(u,"unexpected end of the stream within a flow collection")}function U(u,M){let H,ae=m,O=!1,Z=!1,_=M,L=0,oe=!1,Q,Y=u.input.charCodeAt(u.position);if(Y===124)H=!1;else if(Y===62)H=!0;else return!1;for(u.kind="scalar",u.result="";Y!==0;)if(Y=u.input.charCodeAt(++u.position),Y===43||Y===45)m===ae?ae=Y===43?S:f:K(u,"repeat of a chomping mode identifier");else if((Q=F(Y))>=0)Q===0?K(u,"bad explicit indentation width of a block scalar; it cannot be less than one"):Z?K(u,"repeat of an indentation width identifier"):(_=M+Q-1,Z=!0);else break;if(x(Y)){do Y=u.input.charCodeAt(++u.position);while(x(Y));if(Y===35)do Y=u.input.charCodeAt(++u.position);while(!N(Y)&&Y!==0)}for(;Y!==0;){for($e(u),u.lineIndent=0,Y=u.input.charCodeAt(u.position);(!Z||u.lineIndent<_)&&Y===32;)u.lineIndent++,Y=u.input.charCodeAt(++u.position);if(!Z&&u.lineIndent>_&&(_=u.lineIndent),N(Y)){L++;continue}if(!Z&&_===0&&K(u,"missing indentation for block scalar"),u.lineIndent<_){ae===S?u.result+=e.repeat(`
75
- `,O?1+L:L):ae===m&&O&&(u.result+=`
76
- `);break}H?x(Y)?(oe=!0,u.result+=e.repeat(`
77
- `,O?1+L:L)):oe?(oe=!1,u.result+=e.repeat(`
78
- `,L+1)):L===0?O&&(u.result+=" "):u.result+=e.repeat(`
79
- `,L):u.result+=e.repeat(`
80
- `,O?1+L:L),O=!0,Z=!0,L=0;const ue=u.position;for(;!N(Y)&&Y!==0;)Y=u.input.charCodeAt(++u.position);Re(u,ue,u.position,!1)}return!0}function G(u,M){const H=u.tag,ae=u.anchor,O=[];let Z=!1;if(u.firstTabInLine!==-1)return!1;u.anchor!==null&&xe(u,u.anchor,O);let _=u.input.charCodeAt(u.position);for(;_!==0&&(u.firstTabInLine!==-1&&(u.position=u.firstTabInLine,K(u,"tab characters must not be used in indentation")),_===45);){const L=u.input.charCodeAt(u.position+1);if(!I(L))break;if(Z=!0,u.position++,Je(u,!0,-1)&&u.lineIndent<=M){O.push(null),_=u.input.charCodeAt(u.position);continue}const oe=u.line;if(Ze(u,M,l,!1,!0),O.push(u.result),Je(u,!0,-1),_=u.input.charCodeAt(u.position),(u.line===oe||u.lineIndent>M)&&_!==0)K(u,"bad indentation of a sequence entry");else if(u.lineIndent<M)break}return Z?(u.tag=H,u.anchor=ae,u.kind="sequence",u.result=O,!0):!1}function me(u,M,H){let ae,O,Z,_;const L=u.tag,oe=u.anchor,Q={},Y=Object.create(null);let ue=null,le=null,ze=null,Pe=!1,Oe=!1;if(u.firstTabInLine!==-1)return!1;u.anchor!==null&&xe(u,u.anchor,Q);let Ye=u.input.charCodeAt(u.position);for(;Ye!==0;){!Pe&&u.firstTabInLine!==-1&&(u.position=u.firstTabInLine,K(u,"tab characters must not be used in indentation"));const Le=u.input.charCodeAt(u.position+1),ut=u.line;if((Ye===63||Ye===58)&&I(Le))Ye===63?(Pe&&(Ie(u,Q,Y,ue,le,null,O,Z,_),ue=le=ze=null),Oe=!0,Pe=!0,ae=!0):Pe?(Pe=!1,ae=!0):K(u,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),u.position+=1,Ye=Le;else{if(O=u.line,Z=u.lineStart,_=u.position,!Ze(u,H,s,!1,!0))break;if(u.line===ut){for(Ye=u.input.charCodeAt(u.position);x(Ye);)Ye=u.input.charCodeAt(++u.position);if(Ye===58)Ye=u.input.charCodeAt(++u.position),I(Ye)||K(u,"a whitespace character is expected after the key-value separator within a block mapping"),Pe&&(Ie(u,Q,Y,ue,le,null,O,Z,_),ue=le=ze=null),Oe=!0,Pe=!1,ae=!1,ue=u.tag,le=u.result;else if(Oe)K(u,"can not read an implicit mapping pair; a colon is missed");else return u.tag=L,u.anchor=oe,!0}else if(Oe)K(u,"can not read a block mapping entry; a multiline key may not be an implicit key");else return u.tag=L,u.anchor=oe,!0}if((u.line===ut||u.lineIndent>M)&&(Pe&&(O=u.line,Z=u.lineStart,_=u.position),Ze(u,M,p,!0,ae)&&(Pe?le=u.result:ze=u.result),Pe||(Ie(u,Q,Y,ue,le,ze,O,Z,_),ue=le=ze=null),Je(u,!0,-1),Ye=u.input.charCodeAt(u.position)),(u.line===ut||u.lineIndent>M)&&Ye!==0)K(u,"bad indentation of a mapping entry");else if(u.lineIndent<M)break}return Pe&&Ie(u,Q,Y,ue,le,null,O,Z,_),Oe&&(u.tag=L,u.anchor=oe,u.kind="mapping",u.result=Q),Oe}function W(u){let M=!1,H=!1,ae,O,Z=u.input.charCodeAt(u.position);if(Z!==33)return!1;u.tag!==null&&K(u,"duplication of a tag property"),Z=u.input.charCodeAt(++u.position),Z===60?(M=!0,Z=u.input.charCodeAt(++u.position)):Z===33?(H=!0,ae="!!",Z=u.input.charCodeAt(++u.position)):ae="!";let _=u.position;if(M){do Z=u.input.charCodeAt(++u.position);while(Z!==0&&Z!==62);u.position<u.length?(O=u.input.slice(_,u.position),Z=u.input.charCodeAt(++u.position)):K(u,"unexpected end of the stream within a verbatim tag")}else{for(;Z!==0&&!I(Z);)Z===33&&(H?K(u,"tag suffix cannot contain exclamation marks"):(ae=u.input.slice(_-1,u.position+1),A.test(ae)||K(u,"named tag handle cannot contain such characters"),H=!0,_=u.position+1)),Z=u.input.charCodeAt(++u.position);O=u.input.slice(_,u.position),R.test(O)&&K(u,"tag suffix cannot contain flow indicator characters")}O&&!D.test(O)&&K(u,"tag name cannot contain such characters: "+O);try{O=decodeURIComponent(O)}catch{K(u,"tag name is malformed: "+O)}return M?u.tag=O:r.call(u.tagMap,ae)?u.tag=u.tagMap[ae]+O:ae==="!"?u.tag="!"+O:ae==="!!"?u.tag="tag:yaml.org,2002:"+O:K(u,'undeclared tag handle "'+ae+'"'),!0}function de(u){let M=u.input.charCodeAt(u.position);if(M!==38)return!1;u.anchor!==null&&K(u,"duplication of an anchor property"),M=u.input.charCodeAt(++u.position);const H=u.position;for(;M!==0&&!I(M)&&!P(M);)M=u.input.charCodeAt(++u.position);return u.position===H&&K(u,"name of an anchor node must contain at least one character"),u.anchor=u.input.slice(H,u.position),!0}function he(u){let M=u.input.charCodeAt(u.position);if(M!==42)return!1;M=u.input.charCodeAt(++u.position);const H=u.position;for(;M!==0&&!I(M)&&!P(M);)M=u.input.charCodeAt(++u.position);u.position===H&&K(u,"name of an alias node must contain at least one character");const ae=u.input.slice(H,u.position);return r.call(u.anchorMap,ae)||K(u,'unidentified alias "'+ae+'"'),u.result=u.anchorMap[ae],Je(u,!0,-1),!0}function We(u,M,H,ae){const O=pe(u);return se(u),ve(u,M),u.tag=null,u.anchor=null,u.kind=null,u.result=null,me(u,H,ae)&&u.kind==="mapping"?(ke(u),!0):(ee(u),ve(u,O),!1)}function Ze(u,M,H,ae,O){let Z,_,L=1,oe=!1,Q=!1,Y=null,ue,le,ze;u.depth>=u.maxDepth&&K(u,"nesting exceeded maxDepth ("+u.maxDepth+")"),u.depth+=1,u.listener!==null&&u.listener("open",u),u.tag=null,u.anchor=null,u.kind=null,u.result=null;const Pe=Z=_=p===H||l===H;if(ae&&Je(u,!0,-1)&&(oe=!0,u.lineIndent>M?L=1:u.lineIndent===M?L=0:u.lineIndent<M&&(L=-1)),L===1)for(;;){const Oe=u.input.charCodeAt(u.position),Ye=pe(u);if(oe&&(Oe===33&&u.tag!==null||Oe===38&&u.anchor!==null)||!W(u)&&!de(u))break;Y===null&&(Y=Ye),Je(u,!0,-1)?(oe=!0,_=Pe,u.lineIndent>M?L=1:u.lineIndent===M?L=0:u.lineIndent<M&&(L=-1)):_=!1}if(_&&(_=oe||O),L===1||p===H)if(i===H||s===H?le=M:le=M+1,ze=u.position-u.lineStart,L===1)if(_&&(G(u,ze)||me(u,ze,le))||E(u,le))Q=!0;else{const Oe=u.input.charCodeAt(u.position);Y!==null&&Pe&&!_&&Oe!==124&&Oe!==62&&We(u,Y,Y.position-Y.lineStart,le)||Z&&U(u,le)||He(u,le)||Ne(u,le)?Q=!0:he(u)?(Q=!0,(u.tag!==null||u.anchor!==null)&&K(u,"alias node should not have any properties")):Be(u,le,i===H)&&(Q=!0,u.tag===null&&(u.tag="?")),u.anchor!==null&&xe(u,u.anchor,u.result)}else L===0&&(Q=_&&G(u,ze));if(u.tag===null)u.anchor!==null&&xe(u,u.anchor,u.result);else if(u.tag==="?"){u.result!==null&&u.kind!=="scalar"&&K(u,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+u.kind+'"');for(let Oe=0,Ye=u.implicitTypes.length;Oe<Ye;Oe+=1)if(ue=u.implicitTypes[Oe],ue.resolve(u.result)){u.result=ue.construct(u.result),u.tag=ue.tag,u.anchor!==null&&xe(u,u.anchor,u.result);break}}else if(u.tag!=="!"){if(r.call(u.typeMap[u.kind||"fallback"],u.tag))ue=u.typeMap[u.kind||"fallback"][u.tag];else{ue=null;const Oe=u.typeMap.multi[u.kind||"fallback"];for(let Ye=0,Le=Oe.length;Ye<Le;Ye+=1)if(u.tag.slice(0,Oe[Ye].tag.length)===Oe[Ye].tag){ue=Oe[Ye];break}}ue||K(u,"unknown tag !<"+u.tag+">"),u.result!==null&&ue.kind!==u.kind&&K(u,"unacceptable node kind for !<"+u.tag+'> tag; it should be "'+ue.kind+'", not "'+u.kind+'"'),ue.resolve(u.result,u.tag)?(u.result=ue.construct(u.result,u.tag),u.anchor!==null&&xe(u,u.anchor,u.result)):K(u,"cannot resolve a node with !<"+u.tag+"> explicit tag")}return u.listener!==null&&u.listener("close",u),u.depth-=1,u.tag!==null||u.anchor!==null||Q}function tt(u){const M=u.position;let H=!1,ae;for(u.version=null,u.checkLineBreaks=u.legacy,u.tagMap=Object.create(null),u.anchorMap=Object.create(null);(ae=u.input.charCodeAt(u.position))!==0&&(Je(u,!0,-1),ae=u.input.charCodeAt(u.position),!(u.lineIndent>0||ae!==37));){H=!0,ae=u.input.charCodeAt(++u.position);let O=u.position;for(;ae!==0&&!I(ae);)ae=u.input.charCodeAt(++u.position);const Z=u.input.slice(O,u.position),_=[];for(Z.length<1&&K(u,"directive name must not be less than one character in length");ae!==0;){for(;x(ae);)ae=u.input.charCodeAt(++u.position);if(ae===35){do ae=u.input.charCodeAt(++u.position);while(ae!==0&&!N(ae));break}if(N(ae))break;for(O=u.position;ae!==0&&!I(ae);)ae=u.input.charCodeAt(++u.position);_.push(u.input.slice(O,u.position))}ae!==0&&$e(u),r.call(qe,Z)?qe[Z](u,Z,_):Ee(u,'unknown document directive "'+Z+'"')}if(Je(u,!0,-1),u.lineIndent===0&&u.input.charCodeAt(u.position)===45&&u.input.charCodeAt(u.position+1)===45&&u.input.charCodeAt(u.position+2)===45?(u.position+=3,Je(u,!0,-1)):H&&K(u,"directives end mark is expected"),Ze(u,u.lineIndent-1,p,!1,!0),Je(u,!0,-1),u.checkLineBreaks&&k.test(u.input.slice(M,u.position))&&Ee(u,"non-ASCII line breaks are interpreted as content"),u.documents.push(u.result),u.position===u.lineStart&&et(u)){u.input.charCodeAt(u.position)===46&&(u.position+=3,Je(u,!0,-1));return}u.position<u.length-1&&K(u,"end of the stream or a document separator is expected")}function at(u,M){u=String(u),M=M||{},u.length!==0&&(u.charCodeAt(u.length-1)!==10&&u.charCodeAt(u.length-1)!==13&&(u+=`
81
- `),u.charCodeAt(0)===65279&&(u=u.slice(1)));const H=new we(u,M),ae=u.indexOf("\0");for(ae!==-1&&(H.position=ae,K(H,"null byte is not allowed in input")),H.input+="\0";H.input.charCodeAt(H.position)===32;)H.lineIndent+=1,H.position+=1;for(;H.position<H.length-1;)tt(H);return H.documents}function Te(u,M,H){M!==null&&typeof M=="object"&&typeof H>"u"&&(H=M,M=null);const ae=at(u,H);if(typeof M!="function")return ae;for(let O=0,Z=ae.length;O<Z;O+=1)M(ae[O])}function De(u,M){const H=at(u,M);if(H.length!==0){if(H.length===1)return H[0];throw new t("expected a single document in the stream, but found more")}}return hl.loadAll=Te,hl.load=De,hl}var lu={},Sh;function vR(){if(Sh)return lu;Sh=1;const e=As(),t=Ps(),n=Jm(),a=Object.prototype.toString,r=Object.prototype.hasOwnProperty,i=65279,s=9,l=10,p=13,m=32,f=33,S=34,y=35,k=37,R=38,A=39,D=42,z=44,N=45,x=58,I=61,P=62,j=63,T=64,F=91,q=93,$=96,V=123,re=124,X=125,we={};we[0]="\\0",we[7]="\\a",we[8]="\\b",we[9]="\\t",we[10]="\\n",we[11]="\\v",we[12]="\\f",we[13]="\\r",we[27]="\\e",we[34]='\\"',we[92]="\\\\",we[133]="\\N",we[160]="\\_",we[8232]="\\L",we[8233]="\\P";const ye=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],K=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Ee(_,L){if(L===null)return{};const oe={},Q=Object.keys(L);for(let Y=0,ue=Q.length;Y<ue;Y+=1){let le=Q[Y],ze=String(L[le]);le.slice(0,2)==="!!"&&(le="tag:yaml.org,2002:"+le.slice(2));const Pe=_.compiledTypeMap.fallback[le];Pe&&r.call(Pe.styleAliases,ze)&&(ze=Pe.styleAliases[ze]),oe[le]=ze}return oe}function xe(_){let L,oe;const Q=_.toString(16).toUpperCase();if(_<=255)L="x",oe=2;else if(_<=65535)L="u",oe=4;else if(_<=4294967295)L="U",oe=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+L+e.repeat("0",oe-Q.length)+Q}const se=1,ke=2;function ee(_){this.schema=_.schema||n,this.indent=Math.max(1,_.indent||2),this.noArrayIndent=_.noArrayIndent||!1,this.skipInvalid=_.skipInvalid||!1,this.flowLevel=e.isNothing(_.flowLevel)?-1:_.flowLevel,this.styleMap=Ee(this.schema,_.styles||null),this.sortKeys=_.sortKeys||!1,this.lineWidth=_.lineWidth||80,this.noRefs=_.noRefs||!1,this.noCompatMode=_.noCompatMode||!1,this.condenseFlow=_.condenseFlow||!1,this.quotingType=_.quotingType==='"'?ke:se,this.forceQuotes=_.forceQuotes||!1,this.replacer=typeof _.replacer=="function"?_.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function pe(_,L){const oe=e.repeat(" ",L);let Q=0,Y="";const ue=_.length;for(;Q<ue;){let le;const ze=_.indexOf(`
82
- `,Q);ze===-1?(le=_.slice(Q),Q=ue):(le=_.slice(Q,ze+1),Q=ze+1),le.length&&le!==`
83
- `&&(Y+=oe),Y+=le}return Y}function ve(_,L){return`
84
- `+e.repeat(" ",_.indent*L)}function qe(_,L){for(let oe=0,Q=_.implicitTypes.length;oe<Q;oe+=1)if(_.implicitTypes[oe].resolve(L))return!0;return!1}function Re(_){return _===m||_===s}function ie(_){return _>=32&&_<=126||_>=161&&_<=55295&&_!==8232&&_!==8233||_>=57344&&_<=65533&&_!==i||_>=65536&&_<=1114111}function Ie(_){return ie(_)&&_!==i&&_!==p&&_!==l}function $e(_,L,oe){const Q=Ie(_),Y=Q&&!Re(_);return(oe?Q:Q&&_!==z&&_!==F&&_!==q&&_!==V&&_!==X)&&_!==y&&!(L===x&&!Y)||Ie(L)&&!Re(L)&&_===y||L===x&&Y}function Je(_){return ie(_)&&_!==i&&!Re(_)&&_!==N&&_!==j&&_!==x&&_!==z&&_!==F&&_!==q&&_!==V&&_!==X&&_!==y&&_!==R&&_!==D&&_!==f&&_!==re&&_!==I&&_!==P&&_!==A&&_!==S&&_!==k&&_!==T&&_!==$}function et(_){return!Re(_)&&_!==x}function st(_,L){const oe=_.charCodeAt(L);let Q;return oe>=55296&&oe<=56319&&L+1<_.length&&(Q=_.charCodeAt(L+1),Q>=56320&&Q<=57343)?(oe-55296)*1024+Q-56320+65536:oe}function Be(_){return/^\n* /.test(_)}const He=1,Ne=2,E=3,U=4,G=5;function me(_,L,oe,Q,Y,ue,le,ze){let Pe,Oe=0,Ye=null,Le=!1,ut=!1;const Gt=Q!==-1;let gn=-1,bn=Je(st(_,0))&&et(st(_,_.length-1));if(L||le)for(Pe=0;Pe<_.length;Oe>=65536?Pe+=2:Pe++){if(Oe=st(_,Pe),!ie(Oe))return G;bn=bn&&$e(Oe,Ye,ze),Ye=Oe}else{for(Pe=0;Pe<_.length;Oe>=65536?Pe+=2:Pe++){if(Oe=st(_,Pe),Oe===l)Le=!0,Gt&&(ut=ut||Pe-gn-1>Q&&_[gn+1]!==" ",gn=Pe);else if(!ie(Oe))return G;bn=bn&&$e(Oe,Ye,ze),Ye=Oe}ut=ut||Gt&&Pe-gn-1>Q&&_[gn+1]!==" "}return!Le&&!ut?bn&&!le&&!Y(_)?He:ue===ke?G:Ne:oe>9&&Be(_)?G:le?ue===ke?G:Ne:ut?U:E}function W(_,L,oe,Q,Y){_.dump=(function(){if(L.length===0)return _.quotingType===ke?'""':"''";if(!_.noCompatMode&&(ye.indexOf(L)!==-1||K.test(L)))return _.quotingType===ke?'"'+L+'"':"'"+L+"'";const ue=_.indent*Math.max(1,oe),le=_.lineWidth===-1?-1:Math.max(Math.min(_.lineWidth,40),_.lineWidth-ue),ze=Q||_.flowLevel>-1&&oe>=_.flowLevel;function Pe(Oe){return qe(_,Oe)}switch(me(L,ze,_.indent,le,Pe,_.quotingType,_.forceQuotes&&!Q,Y)){case He:return L;case Ne:return"'"+L.replace(/'/g,"''")+"'";case E:return"|"+de(L,_.indent)+he(pe(L,ue));case U:return">"+de(L,_.indent)+he(pe(We(L,le),ue));case G:return'"'+tt(L)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function de(_,L){const oe=Be(_)?String(L):"",Q=_[_.length-1]===`
85
- `,ue=Q&&(_[_.length-2]===`
86
- `||_===`
87
- `)?"+":Q?"":"-";return oe+ue+`
88
- `}function he(_){return _[_.length-1]===`
89
- `?_.slice(0,-1):_}function We(_,L){const oe=/(\n+)([^\n]*)/g;let Q=(function(){let ze=_.indexOf(`
90
- `);return ze=ze!==-1?ze:_.length,oe.lastIndex=ze,Ze(_.slice(0,ze),L)})(),Y=_[0]===`
91
- `||_[0]===" ",ue,le;for(;le=oe.exec(_);){const ze=le[1],Pe=le[2];ue=Pe[0]===" ",Q+=ze+(!Y&&!ue&&Pe!==""?`
92
- `:"")+Ze(Pe,L),Y=ue}return Q}function Ze(_,L){if(_===""||_[0]===" ")return _;const oe=/ [^ ]/g;let Q,Y=0,ue,le=0,ze=0,Pe="";for(;Q=oe.exec(_);)ze=Q.index,ze-Y>L&&(ue=le>Y?le:ze,Pe+=`
93
- `+_.slice(Y,ue),Y=ue+1),le=ze;return Pe+=`
94
- `,_.length-Y>L&&le>Y?Pe+=_.slice(Y,le)+`
95
- `+_.slice(le+1):Pe+=_.slice(Y),Pe.slice(1)}function tt(_){let L="",oe=0;for(let Q=0;Q<_.length;oe>=65536?Q+=2:Q++){oe=st(_,Q);const Y=we[oe];!Y&&ie(oe)?(L+=_[Q],oe>=65536&&(L+=_[Q+1])):L+=Y||xe(oe)}return L}function at(_,L,oe){let Q="";const Y=_.tag;for(let ue=0,le=oe.length;ue<le;ue+=1){let ze=oe[ue];_.replacer&&(ze=_.replacer.call(oe,String(ue),ze)),(H(_,L,ze,!1,!1)||typeof ze>"u"&&H(_,L,null,!1,!1))&&(Q!==""&&(Q+=","+(_.condenseFlow?"":" ")),Q+=_.dump)}_.tag=Y,_.dump="["+Q+"]"}function Te(_,L,oe,Q){let Y="";const ue=_.tag;for(let le=0,ze=oe.length;le<ze;le+=1){let Pe=oe[le];_.replacer&&(Pe=_.replacer.call(oe,String(le),Pe)),(H(_,L+1,Pe,!0,!0,!1,!0)||typeof Pe>"u"&&H(_,L+1,null,!0,!0,!1,!0))&&((!Q||Y!=="")&&(Y+=ve(_,L)),_.dump&&l===_.dump.charCodeAt(0)?Y+="-":Y+="- ",Y+=_.dump)}_.tag=ue,_.dump=Y||"[]"}function De(_,L,oe){let Q="";const Y=_.tag,ue=Object.keys(oe);for(let le=0,ze=ue.length;le<ze;le+=1){let Pe="";Q!==""&&(Pe+=", "),_.condenseFlow&&(Pe+='"');const Oe=ue[le];let Ye=oe[Oe];_.replacer&&(Ye=_.replacer.call(oe,Oe,Ye)),H(_,L,Oe,!1,!1)&&(_.dump.length>1024&&(Pe+="? "),Pe+=_.dump+(_.condenseFlow?'"':"")+":"+(_.condenseFlow?"":" "),H(_,L,Ye,!1,!1)&&(Pe+=_.dump,Q+=Pe))}_.tag=Y,_.dump="{"+Q+"}"}function u(_,L,oe,Q){let Y="";const ue=_.tag,le=Object.keys(oe);if(_.sortKeys===!0)le.sort();else if(typeof _.sortKeys=="function")le.sort(_.sortKeys);else if(_.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let ze=0,Pe=le.length;ze<Pe;ze+=1){let Oe="";(!Q||Y!=="")&&(Oe+=ve(_,L));const Ye=le[ze];let Le=oe[Ye];if(_.replacer&&(Le=_.replacer.call(oe,Ye,Le)),!H(_,L+1,Ye,!0,!0,!0))continue;const ut=_.tag!==null&&_.tag!=="?"||_.dump&&_.dump.length>1024;ut&&(_.dump&&l===_.dump.charCodeAt(0)?Oe+="?":Oe+="? "),Oe+=_.dump,ut&&(Oe+=ve(_,L)),H(_,L+1,Le,!0,ut)&&(_.dump&&l===_.dump.charCodeAt(0)?Oe+=":":Oe+=": ",Oe+=_.dump,Y+=Oe)}_.tag=ue,_.dump=Y||"{}"}function M(_,L,oe){const Q=oe?_.explicitTypes:_.implicitTypes;for(let Y=0,ue=Q.length;Y<ue;Y+=1){const le=Q[Y];if((le.instanceOf||le.predicate)&&(!le.instanceOf||typeof L=="object"&&L instanceof le.instanceOf)&&(!le.predicate||le.predicate(L))){if(oe?le.multi&&le.representName?_.tag=le.representName(L):_.tag=le.tag:_.tag="?",le.represent){const ze=_.styleMap[le.tag]||le.defaultStyle;let Pe;if(a.call(le.represent)==="[object Function]")Pe=le.represent(L,ze);else if(r.call(le.represent,ze))Pe=le.represent[ze](L,ze);else throw new t("!<"+le.tag+'> tag resolver accepts not "'+ze+'" style');_.dump=Pe}return!0}}return!1}function H(_,L,oe,Q,Y,ue,le){_.tag=null,_.dump=oe,M(_,oe,!1)||M(_,oe,!0);const ze=a.call(_.dump),Pe=Q;Q&&(Q=_.flowLevel<0||_.flowLevel>L);const Oe=ze==="[object Object]"||ze==="[object Array]";let Ye,Le;if(Oe&&(Ye=_.duplicates.indexOf(oe),Le=Ye!==-1),(_.tag!==null&&_.tag!=="?"||Le||_.indent!==2&&L>0)&&(Y=!1),Le&&_.usedDuplicates[Ye])_.dump="*ref_"+Ye;else{if(Oe&&Le&&!_.usedDuplicates[Ye]&&(_.usedDuplicates[Ye]=!0),ze==="[object Object]")Q&&Object.keys(_.dump).length!==0?(u(_,L,_.dump,Y),Le&&(_.dump="&ref_"+Ye+_.dump)):(De(_,L,_.dump),Le&&(_.dump="&ref_"+Ye+" "+_.dump));else if(ze==="[object Array]")Q&&_.dump.length!==0?(_.noArrayIndent&&!le&&L>0?Te(_,L-1,_.dump,Y):Te(_,L,_.dump,Y),Le&&(_.dump="&ref_"+Ye+_.dump)):(at(_,L,_.dump),Le&&(_.dump="&ref_"+Ye+" "+_.dump));else if(ze==="[object String]")_.tag!=="?"&&W(_,_.dump,L,ue,Pe);else{if(ze==="[object Undefined]")return!1;if(_.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+ze)}if(_.tag!==null&&_.tag!=="?"){let ut=encodeURI(_.tag[0]==="!"?_.tag.slice(1):_.tag).replace(/!/g,"%21");_.tag[0]==="!"?ut="!"+ut:ut.slice(0,18)==="tag:yaml.org,2002:"?ut="!!"+ut.slice(18):ut="!<"+ut+">",_.dump=ut+" "+_.dump}}return!0}function ae(_,L){const oe=[],Q=[];O(_,oe,Q);const Y=Q.length;for(let ue=0;ue<Y;ue+=1)L.duplicates.push(oe[Q[ue]]);L.usedDuplicates=new Array(Y)}function O(_,L,oe){if(_!==null&&typeof _=="object"){const Q=L.indexOf(_);if(Q!==-1)oe.indexOf(Q)===-1&&oe.push(Q);else if(L.push(_),Array.isArray(_))for(let Y=0,ue=_.length;Y<ue;Y+=1)O(_[Y],L,oe);else{const Y=Object.keys(_);for(let ue=0,le=Y.length;ue<le;ue+=1)O(_[Y[ue]],L,oe)}}}function Z(_,L){L=L||{};const oe=new ee(L);oe.noRefs||ae(_,oe);let Q=_;return oe.replacer&&(Q=oe.replacer.call({"":Q},"",Q)),H(oe,0,Q,!0,!0)?oe.dump+`
96
- `:""}return lu.dump=Z,lu}var xh;function yR(){if(xh)return _n;xh=1;const e=bR(),t=vR();function n(a,r){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+r+" instead, which is now safe by default.")}}return _n.Type=Dn(),_n.Schema=wv(),_n.FAILSAFE_SCHEMA=Av(),_n.JSON_SCHEMA=jv(),_n.CORE_SCHEMA=Ov(),_n.DEFAULT_SCHEMA=Jm(),_n.load=e.load,_n.loadAll=e.loadAll,_n.dump=t.dump,_n.YAMLException=Ps(),_n.types={binary:Dv(),float:Mv(),map:Rv(),null:Pv(),pairs:zv(),set:Uv(),timestamp:Nv(),bool:Tv(),int:Ev(),merge:$v(),omap:Lv(),seq:Cv(),str:Iv()},_n.safeLoad=n("safeLoad","load"),_n.safeLoadAll=n("safeLoadAll","loadAll"),_n.safeDump=n("safeDump","dump"),_n}var SR=yR();const xR=hR(SR),{Type:tV,Schema:nV,FAILSAFE_SCHEMA:aV,JSON_SCHEMA:oV,CORE_SCHEMA:rV,DEFAULT_SCHEMA:iV,load:sV,loadAll:lV,dump:cV,YAMLException:dV,types:uV,safeLoad:mV,safeLoadAll:pV,safeDump:fV}=xR,Ym=3e3,Xm=9999,hV="openpond.yaml",kR=["google","github","x"],Qm=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),kh=h(o().trim().min(1).max(1e3)).max(50),gs=o().trim().min(1).max(4096).refine(Fv,{message:"path must be a relative workspace path"}),_R=o().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),wR=o().trim().regex(/^sha256:[0-9a-f]{64}$/i),Hv=o().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),IR=c({ref:_R,digest:wR.optional(),registrySecretRef:o().trim().min(1).max(500).optional(),platform:w("linux/amd64").optional(),workspaceRoot:Hv.optional()}).strict(),CR=c({context:gs.default("."),path:gs.default("Dockerfile"),target:o().trim().min(1).max(191).optional(),buildArgs:fe(o().max(191),o().max(500)).optional(),registrySecretRefs:h(o().trim().min(1).max(500)).max(10).optional(),platform:w("linux/amd64").optional(),workspaceRoot:Hv.optional()}).strict(),RR=c({base:o().trim().min(1).max(120).optional(),snapshot:o().trim().min(1).max(191).optional(),image:IR.optional(),dockerfile:CR.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:Nn.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),qv=c({cpu:d().positive().max(8).optional(),memoryGb:d().positive().max(32).optional(),diskGb:d().positive().max(100).optional()}).strict(),AR=c({provider:b(kR),scopes:h(o().trim().min(1).max(200)).max(100).default([]),capabilities:h(o().trim().min(1).max(200)).max(100).default([])}).strict(),PR=c({models:h(o().trim().min(1).max(200)).max(100).default([]),scopes:h(o().trim().min(1).max(200)).max(100).default([])}).strict(),TR=c({opchat:PR.optional()}).catchall(fe(o(),Se())).default({}),ER=c({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:o().trim().min(1).max(256).optional(),storageGb:d().int().positive().max(100).optional(),deleteOnSandboxDelete:C().optional()}).strict(),MR=c({port:d().int().min(Ym).max(Xm).refine(e=>!Qm.has(e),{message:"preview port is reserved"}),protocol:w("http").default("http"),label:o().trim().min(1).max(80).optional(),access:b(["private","public"]).default("private"),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),Bv=c({command:o().trim().min(1).max(1e3),cwd:gs.optional(),timeoutSeconds:d().int().positive().max(86400).optional(),requiresStart:C().default(!1),ports:h(MR).max(20).default([]),artifactPaths:h(gs).max(100).default([])}).strict(),_h=Bv.extend({name:o().trim().min(1).max(80)}).strict(),jR=c({name:o().trim().min(1).max(80).optional(),service:o().trim().min(1).max(80).optional(),port:d().int().min(Ym).max(Xm).refine(e=>!Qm.has(e),{message:"app MCP port is reserved"}),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),OR=c({name:o().trim().min(1).max(80).optional(),port:d().int().min(Ym).max(Xm).refine(e=>!Qm.has(e),{message:"validation probe port is reserved"}),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:d().int().min(100).max(599).default(200)}).strict(),NR=fe(o(),Se()).refine(e=>e.type==="object","input schema must be a JSON schema object"),$R=c({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:C().default(!1),secret:C().default(!0),description:o().trim().max(500).optional()}).strict(),cu=o().trim().min(1).max(120),DR=c({name:o().trim().min(1).max(120),description:o().trim().max(500).optional(),cron:o().trim().min(1).max(500).optional(),rate:o().trim().min(1).max(500).optional(),once:cu.optional(),scheduleType:b(["rate","cron","once"]).optional(),scheduleExpression:o().trim().min(1).max(500).optional(),timezone:o().trim().min(1).max(100).optional(),enabled:C().default(!0),startAt:cu.optional(),endAt:cu.optional(),maxRuns:d().int().positive().nullable().optional(),runtimePolicy:b(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:o().trim().min(1).max(120).optional(),actionName:o().trim().min(1).max(120).optional(),command:o().trim().min(1).max(2e3).optional(),target:c({kind:b(["start","action","service","command"]).optional(),name:o().trim().min(1).max(120).optional(),actionName:o().trim().min(1).max(120).optional(),command:o().trim().min(1).max(2e3).optional(),requiresStart:C().optional()}).strict().optional(),requiresStart:C().optional(),budget:c({maxUsd:o().trim().min(1).max(40).optional()}).strict().optional(),resources:qv.optional(),quotas:fe(o(),Se()).optional(),lifecycle:fe(o(),Se()).optional(),retentionPolicy:fe(o(),Se()).optional(),env:h(c({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:o().optional(),secretRef:o().optional()}).strict()).max(100).optional(),integrationLeases:h(fe(o(),Se())).max(20).optional(),metadata:fe(o(),Se()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(l=>typeof l=="string"&&l.trim()).length!==1&&t.addIssue({code:Nn.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:Nn.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,r=e.target?.name??null,i=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?r:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!i&&t.addIssue({code:Nn.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!r&&t.addIssue({code:Nn.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:Nn.custom,path:["command"],message:"schedule command target is required"})}),LR=c({schemaVersion:w(1),name:o().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:o().trim().min(1).max(40),useCase:o().trim().min(1).max(80),description:o().trim().min(1).max(500),runtime:RR,resources:qv.optional(),setup:c({commands:kh.default([])}).strict().default({commands:[]}),validation:c({commands:kh.min(1),probes:h(OR).max(20).default([])}).strict(),start:Bv,actions:h(_h).max(20).default([]),services:h(_h).max(20).default([]),schedules:h(DR).max(20).default([]),mcp:c({endpoints:h(jR).max(10).default([])}).strict().default({endpoints:[]}),volumes:h(ER).max(5).default([]),integrations:c({requiredLeases:h(AR).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:TR,inputs:c({schema:NR.default({type:"object"}),env:h($R).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:c({paths:h(gs).max(100).default([])}).strict().default({paths:[]}),network:c({egress:b(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{UR(e,t),ep(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),HR(e,t),qR(e,t),BR(e,t),FR(e,t)}),zR=c({path:o(),message:o(),code:o()});function gV(e){return[{kind:"start",name:"start",...e.start,artifactPaths:uu(e.start,e)},...e.actions.map(t=>({kind:"action",name:t.name,command:t.command,cwd:t.cwd,timeoutSeconds:t.timeoutSeconds,requiresStart:t.requiresStart,ports:t.ports,artifactPaths:uu(t,e)})),...e.services.map(t=>({kind:"service",name:t.name,command:t.command,cwd:t.cwd,timeoutSeconds:t.timeoutSeconds,requiresStart:t.requiresStart,ports:t.ports,artifactPaths:uu(t,e)}))]}function Fv(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function ep(e,t,n,a){const r=new Set;for(const i of t){if(r.has(i)){e.addIssue({code:Nn.custom,path:[a],message:n});return}r.add(i)}}function UR(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];ep(t,n,"start, action, and service names must be unique","actions")}function HR(e,t){const n=du(e.inputs.schema.properties),a=new Set(e.volumes.map(r=>r.name).filter(r=>!!r));for(const[r,i]of Object.entries(n)){const s=du(i),l=du(s["x-openpond-upload"]??s.xOpenPondUpload),p=typeof l.targetPath=="string"&&l.targetPath.trim()?l.targetPath.trim():typeof l.path=="string"&&l.path.trim()?l.path.trim():"";if(!p)continue;const m=p.replace(/^workspace\//,"").replace(/^\/+/,"").replace(/\/+$/,"");if(!Fv(m)){t.addIssue({code:Nn.custom,path:["inputs","schema","properties",r,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const f=m.split("/");f[0]==="volumes"&&(!f[1]||!a.has(f[1]))&&t.addIssue({code:Nn.custom,path:["inputs","schema","properties",r,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function qR(e,t){ep(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function BR(e,t){const n=new Map(e.services.map(r=>[r.name,new Set(r.ports.map(i=>i.port))])),a=new Set([...e.start.ports.map(r=>r.port),...e.services.flatMap(r=>r.ports.map(i=>i.port))]);for(const[r,i]of e.mcp.endpoints.entries()){if(i.service){const s=n.get(i.service);if(!s){t.addIssue({code:Nn.custom,path:["mcp","endpoints",r,"service"],message:`app MCP service does not exist: ${i.service}`});continue}s.has(i.port)||t.addIssue({code:Nn.custom,path:["mcp","endpoints",r,"port"],message:`app MCP port ${i.port} is not declared on service ${i.service}`});continue}a.has(i.port)||t.addIssue({code:Nn.custom,path:["mcp","endpoints",r,"port"],message:`app MCP port ${i.port} is not declared on start or services`})}}function FR(e,t){const n=new Set(e.actions.map(r=>r.name)),a=new Set(e.services.map(r=>r.name));for(const[r,i]of e.schedules.entries()){const s=i.command??i.target?.command??null;if(i.target?.kind==="command"||s)continue;const l=i.actionName??i.action??i.target?.actionName??(i.target?.kind==="action"?i.target?.name:null);if(l&&!n.has(l)&&t.addIssue({code:Nn.custom,path:["schedules",r,"action"],message:`schedule action target does not exist: ${l}`}),i.target?.kind==="service"){const p=i.target.name??"";p&&!a.has(p)&&t.addIssue({code:Nn.custom,path:["schedules",r,"target","name"],message:`schedule service target does not exist: ${p}`})}}}function du(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function uu(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const VR=c({id:o(),name:o(),description:o().nullable(),scheduleType:o(),scheduleExpression:o(),enabled:C(),rawEnabled:C().optional(),syncStatus:o().nullable(),syncError:o().nullable().optional(),startAt:o().nullable(),endAt:o().nullable(),maxRuns:d().nullable(),executionCount:d().nullable(),lifecycleStatus:o().nullable(),lifecycleReason:o().nullable(),lastExecutionAt:o().nullable().optional(),lastExecutionStatus:o().nullable().optional(),lastRunNowAt:o().nullable().optional(),lastRunNowStatus:o().nullable().optional(),updatedAt:o(),deploymentId:o(),isProduction:C().optional(),payload:Se().optional()}).passthrough(),WR=c({total:d().int().nonnegative(),active:d().int().nonnegative(),paused:d().int().nonnegative(),enabled:d().int().nonnegative().optional(),disabled:d().int().nonnegative().optional(),nextRunAt:o().nullable().optional(),lastRunAt:o().nullable().optional(),schedules:h(VR).optional().default([]),truncated:C().optional()}).passthrough(),mu=c({name:o(),kind:b(["start","action","service"]),command:o(),cwd:o().nullable(),timeoutSeconds:d().nullable(),requiresStart:C(),ports:h(c({port:d(),protocol:o(),label:o().nullable(),access:o(),path:o()}).passthrough()).default([]),artifactPaths:h(o()).default([])}).passthrough(),KR=c({schemaVersion:w(1),source:w("openpond.yaml"),manifestName:o(),manifestVersion:o(),manifestUseCase:o(),manifestDescription:o(),manifestPath:o(),manifestHash:o(),inputSchema:fe(o(),Se()).default({}),env:h(c({name:o(),required:C(),secret:C(),description:o().nullable()}).passthrough()).default([]),start:mu,actions:h(mu).default([]),services:h(mu).default([]),defaultActionName:o().nullable(),updatedAt:o()}).passthrough(),GR=c({id:o(),name:o(),description:o().nullable(),visibility:o().nullable().optional(),gitOwner:o().nullable().optional(),gitRepo:o().nullable().optional(),gitHost:o().nullable().optional(),defaultBranch:o().nullable().optional(),sandbox:C().optional().default(!1),sandboxActionRegistry:KR.nullable().optional(),sandboxManifestHash:o().nullable().optional(),sandboxManifestPath:o().nullable().optional(),sandboxManifestSyncedAt:o().nullable().optional(),sandboxManifestError:o().nullable().optional(),updatedAt:o().nullable().optional(),latestDeployment:c({id:o().optional(),status:o().optional(),deploymentDomain:o().nullable().optional(),createdAt:o().optional(),isProduction:C().nullable().optional(),gitBranch:o().nullable().optional()}).nullable().optional(),scheduleSummary:WR.nullable().optional()}),ZR=c({detected:C(),rootPath:o(),manifestPath:o(),manifestHash:o().nullable().optional().default(null),manifest:fe(o(),Se()).nullable().optional().default(null),normalizedManifest:LR.nullable().optional().default(null),valid:C().optional().default(!1),diagnostics:h(zR).optional().default([])}),JR=c({appId:o(),appName:o(),gitOwner:o().nullable(),gitRepo:o().nullable(),gitHost:o().nullable(),defaultBranch:o().nullable(),linkedAt:o()}),Vv=c({teamId:o(),projectId:o(),projectSlug:o().nullable().optional().default(null),projectName:o().nullable().optional().default(null),sourceRepoUrl:o().nullable().optional().default(null),defaultBranch:o().nullable().optional().default(null),lastUploadedCommit:o().nullable().optional().default(null),lastUploadTransport:b(["git_head","snapshot","api_source_upload"]).nullable().optional().default(null),manifestPath:o().nullable().optional().default(null),manifestHash:o().nullable().optional().default(null),syncedAt:o().nullable().optional().default(null),linkedAt:o()}),YR=b(["github_repo","internal_repo","template","manual"]),XR=c({id:o(),teamId:o(),name:o(),slug:o().nullable().optional().default(null),sourceType:YR.optional().default("manual"),sourceLabel:o().nullable().optional().default(null),defaultBranch:o().nullable().optional().default(null),internalRepoPath:o().nullable().optional().default(null),manifestPath:o().nullable().optional().default(null),manifestHash:o().nullable().optional().default(null),syncedAt:o().nullable().optional().default(null),organizationName:o().nullable().optional().default(null),organizationSlug:o().nullable().optional().default(null),createdAt:o().nullable().optional().default(null),updatedAt:o().nullable().optional().default(null)}),QR=c({id:o(),name:o(),path:o(),workspacePath:o(),repoPath:o().nullable(),source:b(["folder","git"]),hiddenFromDefaultSidebar:C().optional(),sandboxTemplate:ZR.nullable().optional().default(null),linkedOpenPondApp:JR.nullable().optional().default(null),linkedSandboxProject:Vv.nullable().optional().default(null),preferredSandboxAgentId:o().nullable().optional().default(null),createdAt:o(),updatedAt:o()});c({path:o().trim().min(1).optional(),name:o().trim().min(1).max(120).optional(),createNew:C().optional(),baseDirectory:o().trim().min(1).max(4096).optional()}).superRefine((e,t)=>{if(e.createNew){e.name?.trim()||t.addIssue({code:"custom",path:["name"],message:"Project name is required when creating a new project."});return}e.path?.trim()||t.addIssue({code:"custom",path:["path"],message:"Project path is required."})});c({linkedSandboxProject:Vv.nullable().optional(),preferredSandboxAgentId:o().nullable().optional(),hiddenFromDefaultSidebar:C().optional()});const eA=["connected_app_search","connected_app_read","connected_app_write"],pu="https://openpond.ai",tp=["slack","google","github","turnkey","x","microsoft_teams","mcp"],np={slack:[Ot("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Ot("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Ot("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Ot("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Ot("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Ot("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Ot("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Ot("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Ot("google.comments.read","Read comments","Read Google file comments.","read",!0),Ot("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Ot("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Ot("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Ot("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Ot("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Ot("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Ot("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Ot("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Ot("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Ot("x.profile.read","Read profile","Read the connected X profile.","read",!0),Ot("x.search.read","Search X","Search public X posts when granted.","read",!0),Ot("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Ot("x.post.write","Post","Create approved X posts.","write",!0),Ot("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Ot("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Ot("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},ap={slack:[],microsoft_teams:[],google:[Et("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Et("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Et("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Et("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Et("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Et("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Et("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Et("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Et("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Et("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Et("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Et("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Et("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Et("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Et("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Et("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Et("github.pull_request.comment","write","Comment on pull request","Create an explicitly approved pull request comment and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref","body"]}),Et("github.pull_request.update","write","Update pull request","Apply an explicitly approved pull request metadata update and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref"]})],turnkey:[Et("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Et("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Et("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Et("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Et("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Et("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Et("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Et("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Et("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Et("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},tA={google:["# Google Connected App","","Use Google only through server-provided connected app tools. Never ask for or infer OAuth tokens.","Before reading or editing, identify the exact Drive file, Doc, Sheet, Slide, or comment thread. If the target is ambiguous, ask a short clarification or search first.","Use only declared Google operation ids: google.drive.search, google.drive.read_file, google.docs.read, google.comments.read, google.docs.update, google.comments.create, google.comments.resolve.","For writes, require explicit user intent, summarize the planned change, and verify the target identity before applying updates.","After a write, read back the changed object or relevant range and report the result with the provider file name or stable reference.","Prefer narrow reads over broad Drive scans. Do not expose private file ids unless the tool result already presents them as stable refs."].join(`
97
- `),github:["# GitHub Connected App","","Use GitHub only through server-provided connected app tools. Repository, issue, and pull request identity must be grounded before action.","Use only declared GitHub operation ids: github.repo.search, github.issue.search, github.pull_request.search, github.repo.read, github.issue.read, github.pull_request.read, github.issue.create, github.issue.comment, github.issue.update, github.pull_request.comment, github.pull_request.update.","For reads, name the owner/repo and issue or pull request number when available. If several targets match, ask or inspect before proceeding.","For writes, require explicit user intent and avoid destructive repository changes. Create issues only when the user clearly asks to submit or file a new issue. Prefer comments, labels, or metadata updates unless a stronger operation is clearly requested.","Do not claim CI, review, branch, or PR state changed until a tool result confirms it.","Keep local workspace git operations separate from connected GitHub operations unless the user explicitly asks to bridge them."].join(`
98
- `),turnkey:["# Turnkey Agent Wallet Connected App","","Use Turnkey only through server-provided connected app tools. Never ask for, expose, or infer API keys, P-256 credentials, wallet private keys, or lease material.","Use only declared Turnkey read operation ids: turnkey.wallets.read, turnkey.balances.read, and turnkey.activities.read.","Turnkey connected-app access is read-only. Do not claim that a transaction was created, signed, approved, rejected, or sent.","Use turnkey.wallets.read for the Agent Wallet address and metadata, turnkey.balances.read for supported-network balances, and turnkey.activities.read for recent Turnkey activity.","Report the wallet address and network with balance results, and distinguish an empty balance from a failed provider read."].join(`
99
- `),x:["# X Connected App","","Use X only through server-provided connected app tools. Distinguish profile, recent search, mention, post, and reply operations.","Use only declared X operation ids: x.profile.read, x.post.read, x.search.posts, x.mentions.search, x.mention.read, x.post.create, x.reply.create.","For x.com, twitter.com, or stable status URLs, first parse the status/post id and read the post with connected_app_read using operation x.post.read and ref set to the original URL, stable ref, or id. Do not open a browser before trying the X connector.","Use x.search.posts for discovery, related public posts, replies, quote-post searches, and conversation scans. It uses X API recent search, so report zero-result searches as zero recent public posts returned by X.","For conversation or reply collection, dedupe by returned post id/ref. Do not repeat the same search call unless the result exposes a usable cursor or next token; if pagination is unavailable, state that coverage is limited to returned recent-search results.","Reads can summarize recent public posts, connected-account profile details, and mentions when the capability is available.","Writes require explicit user intent for the exact post or reply. Do not publish drafts, jokes, endorsements, or replies unless the user clearly approves the content.","Before posting or replying, preserve account identity, quote the proposed content in summary form, and respect provider limits and policy boundaries.","After a write, verify the returned post or reply ref before reporting success."].join(`
100
- `),microsoft_teams:["# Microsoft Teams Connected App","","Microsoft Teams is currently an ingestion/native binding surface only. Do not expose Teams OAuth reads, replies, file operations, or sandbox leases.","Native Teams setup can bind chats or channels to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Teams actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
101
- `),slack:["# Slack Connected App","","Slack is currently an ingestion/native binding surface only. Do not expose Slack OAuth reads, replies, file operations, or sandbox leases.","Native Slack setup can bind channels or threads to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Slack actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
102
- `),mcp:["# OpenPond MCP Connected App","","Use OpenPond MCP only through server-provided tool discovery and call paths. Do not invent MCP tools or endpoints.","Treat MCP as team-scoped tooling, not an OAuth connector. Tool availability must come from server-confirmed discovery results.","Before calling an MCP tool, match the requested operation to the tool name, description, input schema, and allowed team context.","For writes or side effects, require explicit user intent and report only confirmed tool results."].join(`
103
- `)},bV=tp.map(e=>{const t=Kv(e),n=tA[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${xA(n)}`,charCount:n.length}});function nA(e){const t=op(e.provider);if(!t)return{ok:!1,error:`Connected app provider is not supported: ${e.provider}`};if(!t.leasePolicy.leaseable)return{ok:!1,error:`Connected app provider ${e.provider} is not leaseable for cloud connector execution.`};const n=gA(e.operation);if(e.toolName!==n)return{ok:!1,error:`Connected app tool ${e.toolName} does not match ${e.operation} operation.`};const a=e.operation==="write"?"write":"read",r=new Set(t.capabilities.filter(l=>l.access===a&&l.leaseable).map(l=>l.id)),i=e.capabilityIds.filter(l=>!r.has(l));if(i.length>0)return{ok:!1,error:`Connected app capability ${i[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=oA(e);return s.ok?{ok:!0,request:e}:s}function aA(e){const t=dc(e);return t?ap[t]:[]}function oA(e){const t=lA(e.args),n=aA(e.provider).filter(s=>s.operation===e.operation);if(n.length===0)return{ok:!1,error:`Connected app provider ${e.provider} does not declare ${e.operation} operations.`};if(!t)return e.operation==="write"?{ok:!1,error:`Connected app ${e.provider} write calls require a provider operation id.`}:{ok:!0,request:e};const a=n.find(s=>s.id===t);if(!a)return{ok:!1,error:`Connected app operation ${t} is not allowed for ${e.provider} ${e.operation}.`};const r=e.capabilityIds.filter(s=>!a.capabilityIds.includes(s));if(r.length>0)return{ok:!1,error:`Connected app operation ${a.id} does not allow capability ${r[0]}.`};const i=dA(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const l=i[s];if(l==null||typeof l=="string"&&!l.trim())return{ok:!1,error:`Connected app operation ${a.id} requires input.${s}.`}}return{ok:!0,request:e}}const rA=[{id:"slack",providerFamily:"slack",setupSurface:"native_bot",statusSource:"native_binding",label:"Slack",shortLabel:"Slack",kind:"native",category:"Chat",description:"Bind Slack channels or threads for ingestion into OpenPond profiles.",icon:"/connected-apps/slack.svg",installLabel:"Continue to Slack details"},{id:"google",providerFamily:"google",setupSurface:"oauth_connector",statusSource:"integration_connection",label:"Google",shortLabel:"Google",kind:"oauth",category:"Productivity",description:"Docs, Drive files, and comments for sandbox workflows.",icon:"/connected-apps/google.svg",installLabel:"Continue to Google details"},{id:"github",providerFamily:"github",setupSurface:"oauth_connector",statusSource:"integration_connection",label:"GitHub",shortLabel:"GitHub",kind:"oauth",category:"Developer tools",description:"Access repositories, issues, and pull requests.",icon:"/connected-apps/github.svg",installLabel:"Continue to GitHub details"},{id:"x",providerFamily:"x",setupSurface:"oauth_connector",statusSource:"integration_connection",label:"X",shortLabel:"X",kind:"oauth",category:"Productivity",description:"User profile, mentions, and approved reply access.",icon:"/connected-apps/x.svg",installLabel:"Continue to X details"},{id:"turnkey",providerFamily:"turnkey",setupSurface:"wallet_connector",statusSource:"integration_connection",label:"Turnkey Agent Wallet",shortLabel:"Turnkey",kind:"wallet",category:"Wallet",description:"Read your OpenPond Agent Wallet address, balances, and activity through policy-bound Turnkey access.",icon:"/connected-apps/turnkey.svg",installLabel:"Manage OpenPond wallet"},{id:"microsoft_teams",providerFamily:"microsoft_teams",setupSurface:"native_bot",statusSource:"native_binding",label:"Teams",shortLabel:"Teams",kind:"native",category:"Chat",description:"Bind Teams chats or channels for ingestion into OpenPond profiles.",icon:"/connected-apps/microsoft.svg",installLabel:"Continue to Teams details"},{id:"mcp",providerFamily:"mcp",setupSurface:"mcp_endpoint",statusSource:"mcp_endpoint",label:"OpenPond MCP",shortLabel:"MCP",kind:"mcp",category:"Tools",description:"Expose workspace tools through a team-scoped MCP endpoint.",icon:"/connected-apps/openpond-mcp.svg",installLabel:"Open MCP settings"}],cc=rA,iA=tp.map(e=>{const t=cc.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:ds(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:np[e],skills:fA(e),tools:hA(e),operations:ap[e],leasePolicy:bA(e)}});function Wv(e){const t=sA(e);return t?cc.find(n=>n.id===t)??null:null}function op(e){const t=dc(e);return t?iA.find(n=>n.id===t)??null:null}function vV(e){const t=Wv(e.appId),n=mA(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",r=new URL(a,n);t?.kind!=="mcp"&&r.searchParams.set("app",t?.deepLinkAppId??e.appId);const i=e.teamId?.trim();return i&&r.searchParams.set("teamId",i),r.toString()}function sA(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":cc.some(n=>n.id===t)?t:null:null}function dc(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":tp.includes(t)?t:Wv(t)?.providerFamily??null:null}function fu(e={}){const t=vA(e.connections??[]);return cc.map(n=>{const a=op(n.providerFamily),r=n.statusSource==="integration_connection"?t.filter(l=>l.provider===n.providerFamily):[],i=r.some(l=>l.status==="active"),s=yA(n,i);return{...n,providerLabel:a.label,setupSurfaceLabel:pA(n.setupSurface),status:s,statusLabel:SA(n,s,r),connections:r,connected:i,capabilities:wh(n,a.capabilities),capabilityLabels:wh(n,a.capabilities).map(l=>l.label),leasePolicy:a.leasePolicy}})}function Ot(e,t,n,a,r){return{id:e,label:t,description:n,access:a,leaseable:r}}function Et(e,t,n,a,r,i){return{id:e,operation:t,label:n,description:a,capabilityIds:r,...i?{input:i}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function lA(e){return cA(e.operation)}function cA(e){return typeof e=="string"&&e.trim()?e.trim():null}function dA(e,t){return t==="write"?uA(e.input)?e.input:{}:e}function uA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mA(e){const t=e?.trim();if(!t)return pu;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?pu:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return pu}}function ds(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function pA(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function fA(e){return[Kv(e)]}function Kv(e){return{name:`${e}-connected-app`,description:`Use ${ds(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function hA(e){if(e==="mcp")return[];const t=np[e],n=ap[e],a=t.filter(s=>s.access==="read").map(s=>s.id),r=t.filter(s=>s.access==="write").map(s=>s.id),i=[];return n.some(s=>s.operation==="search")&&i.push({name:"connected_app_search",description:`Search ${ds(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(s=>s.operation==="read")&&i.push({name:"connected_app_read",description:`Read a grounded ${ds(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),r.length>0&&n.some(s=>s.operation==="write")&&i.push({name:"connected_app_write",description:`Perform an explicitly approved ${ds(e)} write through a server-owned connected app connector.`,capabilityIds:r,write:!0}),i}function gA(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function bA(e){const t=np[e].filter(a=>a.leaseable).map(a=>a.id),n=e!=="mcp"&&t.length>0;return{leaseable:n,defaultTtlSeconds:n?e==="turnkey"?300:3600:null,allowedCapabilityIds:t,requiresProxy:n}}function wh(e,t){return e.setupSurface==="native_bot"?t.filter(n=>n.access==="setup"):e.setupSurface==="mcp_endpoint"?t:t.filter(n=>n.access!=="setup")}function vA(e){return e.flatMap(t=>{const n=dc(t.provider);return n?[{id:t.id??null,teamId:t.teamId?.trim()||null,provider:n,accountLabel:t.providerAccountName??null,workspaceLabel:t.providerWorkspaceName??null,scopes:Array.isArray(t.scopes)?t.scopes:[],capabilities:Array.isArray(t.capabilities)?t.capabilities:[],status:t.status?.trim().toLowerCase()||"active"}]:[]})}function yA(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function SA(e,t,n){if(t==="connected"){const a=n.filter(r=>r.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function xA(e){let t=5381;for(let n=0;n<e.length;n+=1)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}const kA=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),_A=b(["search","read","write"]),wA=b(eA);c({provider:kA,operation:_A,toolName:wA,sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),toolCallId:o().trim().min(1).max(300),userPrompt:o().max(2e5),connectionIds:h(o().trim().min(1).max(300)).min(1).max(8),capabilityIds:h(o().trim().min(1).max(200)).min(1).max(64),args:fe(o(),Se()).default({})}).strict().superRefine((e,t)=>{const n=nA(e);n.ok||t.addIssue({code:Nn.custom,message:n.error})});c({ok:C(),output:o().nullable().optional(),data:Se().optional()}).strict();const IA="local_path:";function Gv(e){return`${IA}${e.trim()}`}c({appId:o(),source:b(["openpond","github","local_git","local_folder","unknown"]),workspacePath:o(),repoPath:o(),initialized:C(),remoteUrl:o().nullable(),expectedRemoteUrl:o().nullable(),currentBranch:o().nullable(),headCommit:o().nullable().optional().default(null),upstreamBranch:o().nullable().optional().default(null),ahead:d().int().nonnegative().optional().default(0),behind:d().int().nonnegative().optional().default(0),diverged:C().optional().default(!1),linkedSourceHeadCommit:o().nullable().optional().default(null),aheadOfLinkedSource:d().int().nonnegative().optional().default(0),behindLinkedSource:d().int().nonnegative().optional().default(0),divergedFromLinkedSource:C().optional().default(!1),linkedSourceComparisonError:o().nullable().optional().default(null),lastFetchAt:o().nullable().optional().default(null),defaultBranch:o().nullable(),branches:h(o()),dirty:C(),changedFilesCount:d(),untrackedFilesCount:d(),error:o().nullable(),updatedAt:o()});const CA=c({path:o(),status:o(),additions:d(),deletions:d(),patch:o(),content:o().nullable().optional().default(null)}),RA=c({appId:o(),repoPath:o(),initialized:C(),dirty:C(),filesChanged:d(),additions:d(),deletions:d(),repoFiles:h(o()).optional().default([]),files:h(CA),error:o().nullable(),updatedAt:o()});c({branch:o().trim().min(1).max(160)});c({path:o().trim().min(1),content:o()});const Ih=c({line:d().int().nonnegative(),character:d().int().nonnegative()}),AA=c({start:Ih,end:Ih}),PA=c({path:o(),range:AA,severity:b(["error","warning","info","hint"]),message:o(),source:o().nullable().optional().default(null),code:o().nullable().optional().default(null)}),Zv=c({id:o(),root:o(),status:b(["connected","unavailable","error"]),message:o().nullable().optional().default(null)});c({path:o().trim().min(1),content:o().optional(),waitForDiagnostics:C().optional().default(!0)});c({appId:o(),path:o(),diagnostics:h(PA),servers:h(Zv),updatedAt:o()});const TA=c({operation:b(["hover","definition","references","documentSymbol"]),path:o().trim().min(1),content:o().optional(),line:d().int().nonnegative().optional(),character:d().int().nonnegative().optional()});c({appId:o(),operation:TA.shape.operation,path:o(),results:Se(),servers:h(Zv),updatedAt:o()});const EA=c({pinned:C().optional(),archived:C().optional(),order:d().optional()}),MA=fe(o(),EA),Jv=b(["local","sandbox"]),jA=b(["pinned","saved_for_later"]),Yv=c({id:o().min(1),workspaceKind:Jv,workspaceId:o().min(1),workspaceName:o().min(1),path:o().min(1),status:jA,order:d().int().nonnegative().nullable().default(null),sourceSessionId:o().min(1).nullable().default(null),available:C().default(!0),createdAt:o().min(1),updatedAt:o().min(1)});c({items:h(Yv)});c({workspaceKind:Jv,workspaceId:o().trim().min(1),workspaceName:o().trim().min(1),path:o().trim().min(1),status:b(["pinned","saved_for_later","none"]),order:d().int().nonnegative().nullable().optional(),sourceSessionId:o().trim().min(1).nullable().optional()});b(["pin","save_for_later","remove","list"]);function OA(e){let t=e.trim().replaceAll("\\","/");if(t=t.replace(/^(?:workspace|sandbox):file:/,""),t=t.replace(/^\/workspace\/app\//,""),t=t.replace(/^\.\//,""),!t||t.startsWith("/"))throw new Error("File path must be relative to the workspace.");const n=t.split("/").filter(a=>a&&a!==".");if(n.some(a=>a===".."))throw new Error("File path cannot leave the workspace.");if(n.length===0)throw new Error("File path is required.");return n.join("/")}function yV(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(OA(e.path))].join(":")}const NA=c({id:o(),name:o(),type:o(),status:o(),isActive:C().nullable(),price:o().nullable(),currency:o().nullable(),credits:o().nullable()}).passthrough(),$A=c({reachable:C(),authenticated:C().nullable(),apiBase:o(),latencyMs:d(),status:d().nullable(),service:o().nullable(),checkedAt:o(),error:o().nullable()}),DA=c({id:o().nullable(),email:o().nullable(),name:o().nullable(),handle:o().nullable(),image:o().nullable(),timezone:o().nullable(),isAdmin:C().nullable(),isVerified:C().nullable(),dailyAgentAppId:o().nullable(),dailyAgentDeploymentId:o().nullable(),credits:o().nullable()}),LA=c({handle:o(),baseUrl:o().nullable().optional()}),zA=c({state:b(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:LA.nullable(),label:o(),email:o().nullable(),avatarUrl:o().nullable(),environment:o().nullable(),baseUrl:o().nullable(),apiBaseUrl:o().nullable(),chatApiBaseUrl:o().nullable().optional().default(null),creditsLabel:o().nullable(),profile:DA.nullable(),products:h(NA),apiHealth:$A.nullable(),accounts:h(c({handle:o(),baseUrl:o().nullable(),apiBaseUrl:o().nullable().optional().default(null),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable(),isActive:C(),authHealth:b(["signed_out","signed_in","auth_error","unknown"]),displayLabel:o().nullable(),email:o().nullable().optional().default(null),avatarUrl:o().nullable()})),error:o().nullable()}),Ch=c({asOf:o().nullable(),refreshing:C(),lastRefreshError:o().nullable(),source:b(["fresh","cache","empty"])}),UA=c({available:C(),binaryPath:o().nullable(),version:o().nullable(),authHealth:b(["unknown","signed_in","signed_out","auth_error"]),account:c({type:o(),email:o().nullable(),planType:o().nullable(),label:o().nullable()}).nullable().default(null),appServer:c({status:b(["idle","starting","ready","error"]),lastError:o().nullable()})}),rp="gpt-5.6-sol",Ts="openpond-chat",Zo="openpond",bs=Ts,uc="default",mc="high",Es="ask",ri=er,ip=b(["default","auto-review","full-access"]),Ms=b(["ask","full-access","disabled"]),pc=b(["low","medium","high","xhigh"]),js=b(["sandbox_app","local_project","sandbox","sandbox_template"]);b(["openpond"]);const HA=b(["provider_usage","provider_tokenizer","model_family","heuristic"]),qA=c({provider:ri,model:o().min(1),usedTokens:d().int().nonnegative(),maxContextTokens:d().int().positive(),usableContextTokens:d().int().positive(),percentFull:d().min(0).max(100),source:HA,updatedAtEventId:o().nullable()}),tm=c({pinned:C().default(!1),projects:C().default(!1),cloudProjects:C().default(!1),chats:C().default(!1),savedForLater:C().default(!0)}),BA=b(["auto","off"]),FA=b(["typescript","python","rust"]),Xv=b(["auto","disabled","custom"]),Ba=c({mode:Xv.default("auto"),customCommand:o().trim().max(4096).default("")}),ql=c({languageServers:BA.default("auto"),diagnosticsWhileEditing:C().default(!0),checkOnSave:C().default(!0),languages:c({typescript:Ba.optional().default(()=>Ba.parse({})),python:Ba.optional().default(()=>Ba.parse({})),rust:Ba.optional().default(()=>Ba.parse({}))}).optional().default(()=>({typescript:Ba.parse({}),python:Ba.parse({}),rust:Ba.parse({})}))}),VA=c({language:FA,label:o(),mode:Xv,status:b(["found","missing","disabled","error"]),command:o().nullable(),message:o().nullable()});c({settings:ql,languages:h(VA),updatedAt:o()});const WA=c({id:o(),root:o(),status:b(["starting","connected","unavailable","error"]),message:o().nullable().optional().default(null),openedDocuments:d().int().nonnegative(),pendingRequests:d().int().nonnegative(),lastUsedAt:o(),stderrTail:o()});c({clients:h(WA),maxClients:d().int().positive(),idleTimeoutMs:d().int().positive(),updatedAt:o()});const nm=c({autoEnabled:C().default(!0),triggerPercent:d().int().min(50).max(95).default(85),summaryModel:b(["same_model"]).default("same_model")}),am=c({defaultModelRef:cn.nullable().default(null),creationMode:b(["defaults","customize"]).default("customize"),autoApproveEvidence:C().default(!1)}),Rh=c({defaultChatProvider:ri.default(Zo),defaultChatModel:o().min(1).default(bs),defaultChatModelRef:cn.nullable().optional(),subagents:hs.optional().default(()=>hs.parse({})),codexPermissionMode:ip.default(uc),codexReasoningEffort:pc.default(mc),openPondCommandAccessMode:Ms.default(Es),defaultBranchPrefix:o().trim().max(48).default("feat/"),defaultNewProjectDirectory:o().trim().max(4096).default(""),defaultTeamId:o().trim().max(191).nullable().default(null),advancedWorkspaceControls:C().default(!1),contextCompaction:nm.optional().default(()=>nm.parse({})),training:am.optional().default(()=>am.parse({})),sidebarWidth:d().int().min(244).max(560).default(332),diffPanelWidth:d().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:tm.optional().default(()=>tm.parse({})),editor:ql.optional().default(()=>ql.parse({}))}),KA="default",Qv=[{id:"default",name:"Balanced",source:"built_in",description:"Clear, useful, and concise.",content:`You are OpenPond Chat, a clear and useful AI assistant.
104
- Be concise, accurate, and direct.
105
- Do not use emojis.
106
- Ask only when missing information would materially change the answer.
107
- Prioritize practical next steps.`},{id:"pragmatic",name:"Pragmatic",source:"built_in",description:"Direct, practical, and engineering-minded.",content:`You are a pragmatic AI assistant with strong engineering judgment.
108
- Be direct, concrete, and outcome-focused.
109
- Do not use emojis.
110
- Prefer simple working solutions over clever abstractions.
111
- Call out weak assumptions plainly.`},{id:"friendly",name:"Friendly",source:"built_in",description:"Warm, conversational, and approachable.",content:`You are a friendly AI assistant.
112
- Use a warm, conversational tone without filler.
113
- Do not use emojis.
114
- Explain decisions clearly and keep the user moving.
115
- Be patient when clarifying tradeoffs.`},{id:"formal",name:"Formal",source:"built_in",description:"Polished, careful, and professional.",content:`You are a formal AI assistant.
116
- Use precise, professional language.
117
- Do not use emojis.
118
- Structure answers clearly and avoid casual phrasing.
119
- State uncertainty and assumptions explicitly.`},{id:"technical",name:"Technical",source:"built_in",description:"Precise, detailed, and implementation-focused.",content:`You are a technical AI assistant.
120
- Prioritize correctness, implementation detail, and edge cases.
121
- Do not use emojis.
122
- Use concise explanations, but include necessary specifics.
123
- Surface risks, constraints, and verification steps.`}],sp=o().trim().min(1).max(120),GA=c({id:sp,name:o(),source:b(["built_in","custom"]).default("custom"),description:o(),content:o()}),Ah=c({activeTemplateId:sp.default(KA),customized:C().default(!1),soul:o(),soulPath:o().nullable(),updatedAt:o().nullable(),templates:h(GA).default(()=>[...Qv])}),ZA=c({id:o(),host:o(),port:d(),startedAt:o(),storePath:o(),version:o(),runtimeVersion:o()}),lp=b(["chat","work","development"]);b(["chat","models","development"]);const JA="work",Fe=o().trim().min(1).nullable(),ca=fe(o(),Se()).default({}),YA=b(["direct_prompt_create","context_backed_create","create_as_agent","workflow_suggestion","local_extend","hosted_create","local_import","direct_prompt_improve","context_backed_improve","hosted_improve","lab_create","lab_improve","training"]),e0=b(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),XA=b(["create","improve","import","promote"]),QA=b(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","released","rejected","ready","ready_local","pushing_hosted","running_hosted_checks","published_hosted","blocked","failed","cancelled"]),gl=b(["always_require_plan_approval","approval_already_granted"]);b(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const eP=dn("kind",[c({kind:w("local"),sourceAuthority:w("local_profile"),activeProfile:o().trim().min(1).nullable(),repoPath:Fe,sourcePath:Fe,localHead:Fe,confirmationPolicy:gl.default("always_require_plan_approval")}),c({kind:w("hosted"),sourceAuthority:w("hosted_profile"),teamId:Fe,projectId:Fe,activeProfile:o().trim().min(1).nullable(),sourceRef:Fe,baseSha:Fe,confirmationPolicy:gl.default("always_require_plan_approval")}),c({kind:w("promote_local_to_hosted"),sourceAuthority:w("promote_local_to_hosted"),teamId:Fe,projectId:Fe,activeProfile:o().trim().min(1).nullable(),repoPath:Fe,sourcePath:Fe,localHead:Fe,hostedHead:Fe,sourceRef:Fe,confirmationPolicy:gl.default("always_require_plan_approval")}),c({kind:w("managed_artifact"),sourceAuthority:w("managed_artifact"),activeProfile:o().trim().min(1).nullable(),confirmationPolicy:gl.default("always_require_plan_approval")})]),tP=c({id:Fe,kind:b(["user","system","automation"]).default("user"),label:Fe}),nP=c({profileId:o().trim().min(1),conversationId:Fe,originTurnId:Fe,projectId:Fe,targetProject:c({id:Fe,name:Fe,workspacePath:Fe,sourceRef:Fe,baseSha:Fe}).nullable()}),ss=c({messageIds:h(o().trim().min(1)).default([]),conversationExcerpts:h(c({messageId:Fe,role:o().trim().min(1).nullable(),excerpt:o().trim().min(1),reason:o().trim().min(1).nullable()})).default([]),attachments:h(c({id:Fe,name:o().trim().min(1),mediaType:Fe,ref:Fe})).default([]),apps:h(c({id:o().trim().min(1),name:o().trim().min(1),connectionId:Fe,required:C().default(!1)})).default([]),tools:h(c({name:o().trim().min(1),inputSummary:Fe,outputSummary:Fe,artifactRefs:h(o().trim().min(1)).default([]),sideEffects:h(o().trim().min(1)).default([])})).default([]),signalRefs:h(o().trim().min(1)).default([]),evalRefs:h(o().trim().min(1)).default([]),targetRepoAssumptions:h(o().trim().min(1)).default([])}),Cr={id:Fe,displayName:Fe},cp=dn("kind",[c({kind:w("unselected"),...Cr}),c({kind:w("agent"),...Cr,defaultActionKey:Fe}),c({kind:w("skill"),...Cr,skillName:Fe}),c({kind:w("extension"),...Cr,slot:Fe}),c({kind:w("model"),...Cr,trainingPlanId:Fe,trainingJobId:Fe,artifactId:Fe}),c({kind:w("configuration"),...Cr,key:Fe})]),om=b(["agent","skill","extension","model","configuration"]),aP=c({schemaVersion:w("openpond.createImprove.evidenceSnapshot.v1"),id:o().trim().min(1),contentHash:o().trim().min(8),consent:c({status:b(["granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Fe,reviewedAt:o().trim().min(1)}),sources:h(c({kind:b(["signal","conversation","direct_correction","manual_intent","artifact"]),id:o().trim().min(1),sourceHash:o().trim().min(8),excerptRef:Fe})).min(1),reviewerIntent:o().trim().min(1),createdAt:o().trim().min(1),metadata:ca}),t0=c({schemaVersion:w("openpond.createImprove.tasksetRef.v1"),id:o().trim().min(1),revision:d().int().positive(),contentHash:o().trim().min(8),evidenceSnapshotIds:h(o().trim().min(1)).min(1),policyBoundary:c({policyVisibleFields:h(o().trim().min(1)).default([]),privilegedFields:h(o().trim().min(1)).default([]),hiddenGraderRefs:h(o().trim().min(1)).default([]),connectedAppScopes:h(o().trim().min(1)).default([])}),targetRecommendation:c({kind:om,rationale:h(o().trim().min(1)).min(1),confidence:d().min(0).max(1)}),authoringSplitRefs:h(o().trim().min(1)).default([]),privateSplitRefs:h(o().trim().min(1)).default([]),approvedBy:Fe,approvedAt:o().trim().min(1),metadata:ca}),oP=c({kind:b(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:o().trim().min(1),status:b(["declared","required","blocked","satisfied"]).default("declared"),detail:Fe,metadata:ca}),rP=c({mode:b(["chat","direct_action","chat_and_direct_actions"]),label:o().trim().min(1),detail:o().trim().min(1),defaultActionKey:Fe,directActionHint:Fe,artifactPolicy:o().trim().min(1)}),iP=c({schemaVersion:w("openpond.createImprove.plan.v1"),id:o().trim().min(1),runId:o().trim().min(1),status:b(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:o().trim().min(1),summary:o().trim().min(1),capturedContextSummary:o().trim().min(1),defaultChatAction:c({key:Fe,label:Fe,required:C().default(!0)}),sourcePlan:h(c({path:o().trim().min(1),operation:b(["create","update","delete","inspect"]),reason:o().trim().min(1)})).default([]),requirements:h(oP).default([]),checks:h(c({name:o().trim().min(1),command:o().trim().min(1),required:C().default(!0)})).default([]),approvalId:Fe,approvedAt:Fe,editedFromPlanId:Fe,metadata:ca,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),sP=c({id:o().trim().min(1),label:o().trim().min(1),value:o().trim().min(1),description:Fe,metadata:ca}),lP=c({value:o().trim().min(1),label:Fe,detail:Fe,answeredAt:o().trim().min(1),metadata:ca}),cP=c({id:o().trim().min(1),kind:b(["single_choice","free_text"]).default("single_choice"),title:o().trim().min(1),prompt:o().trim().min(1),required:C().default(!0),status:b(["pending","answered","skipped"]).default("pending"),options:h(sP).default([]),answer:lP.nullable().default(null),metadata:ca}),dP=c({schemaVersion:w("openpond.createImprove.workflowCapture.v1"),id:o().trim().min(1),runId:o().trim().min(1),command:e0,objective:o().trim().min(1),conversationExcerpts:ss.shape.conversationExcerpts,attachments:ss.shape.attachments,apps:ss.shape.apps,tools:ss.shape.tools,sideEffects:h(o().trim().min(1)).default([]),profileActions:h(o().trim().min(1)).default([]),externalProviders:h(o().trim().min(1)).default([]),environmentVariables:h(o().trim().min(1)).default([]),files:h(o().trim().min(1)).default([]),schedules:h(o().trim().min(1)).default([]),webhooks:h(o().trim().min(1)).default([]),channelTargets:h(o().trim().min(1)).default([]),outputArtifacts:h(o().trim().min(1)).default([]),targetRepoAssumptions:h(o().trim().min(1)).default([]),traceRefs:h(o().trim().min(1)).default([]),metadata:ca,createdAt:o().trim().min(1)}),n0=c({provider:w("github"),number:d().int().positive(),url:o().url(),state:b(["open","merged","closed"]),baseBranch:o().trim().min(1),headBranch:o().trim().min(1),mergeCommit:Fe,openedAt:o().trim().min(1),updatedAt:o().trim().min(1)}),uP=c({baseBranch:o().trim().min(1),baseCommit:o().trim().min(1),branch:o().trim().min(1),headCommit:Fe,remoteName:o().trim().min(1).default("origin"),remoteUrl:Fe,worktreePath:Fe,changedPaths:h(o().trim().min(1)).default([]),diffStat:Fe,pullRequest:n0.nullable().default(null)}),mP=c({id:o().trim().min(1),target:cp,status:b(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:uP.nullable().default(null),parentCandidateId:Fe.default(null),tasksetRef:t0.nullable().default(null),authoringModelRef:Fe.default(null),allowedPaths:h(o().trim().min(1)).default([]),sourceRefs:h(o().trim().min(1)).default([]),artifactRefs:h(o().trim().min(1)).default([]),checkRefs:h(o().trim().min(1)).default([]),evaluationReceiptRefs:h(o().trim().min(1)).default([]),createdAt:o().trim().min(1),updatedAt:o().trim().min(1),metadata:ca}),pP=c({id:o().trim().min(1),candidateId:Fe,target:cp,evaluatorKind:b(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:b(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:Fe.default(null),sourceBranch:Fe.default(null),tasksetId:Fe.default(null),tasksetHash:Fe.default(null),taskAttemptRefs:h(o().trim().min(1)).default([]),status:b(["pending","passed","failed","blocked"]),publishGate:b(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:c({total:d().int().nonnegative(),passed:d().int().nonnegative(),failed:d().int().nonnegative()}).nullable().default(null),evalRefs:h(o().trim().min(1)).default([]),artifactRefs:h(o().trim().min(1)).default([]),summary:Fe,createdAt:o().trim().min(1),metadata:ca}),fP=c({mode:b(["foreground","background"]).default("background"),pauseAllowed:C().default(!0),cancellationAllowed:C().default(!0)}),hP=c({mode:b(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:d().int().min(1).max(20).default(1),currentAttempt:d().int().min(0).max(20).default(0)}),gP=c({kind:b(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:o().trim().min(1),status:Fe,metadata:ca}),bP=c({status:b(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Fe,profileTag:Fe,releaseReceiptRef:Fe,pullRequest:n0.nullable().default(null),updatedAt:Fe}),Os=c({schemaVersion:w("openpond.createImprove.run.v1"),id:o().trim().min(1),revision:d().int().nonnegative(),operation:XA,surface:YA,command:e0,objective:o().trim().min(1),state:QA,adapter:eP,actor:tP,scope:nP,context:ss,target:cp,evidenceSnapshots:h(aP).default([]),tasksetRef:t0.nullable().default(null),targetSelection:c({status:b(["open","recommended","confirmed"]),preselectedKind:om.nullable(),confirmedKind:om.nullable()}).nullable().default(null),plan:iP.nullable(),workflowCapture:dP.nullable(),executionPolicy:fP.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:hP.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:h(o().trim().min(1)).default([]),questionIds:h(o().trim().min(1)).default([]),questions:h(cP).default([]),candidates:h(mP).default([]),evaluationReceipts:h(pP).default([]),checkRefs:h(o().trim().min(1)).default([]),sourceRefs:h(o().trim().min(1)).default([]),externalExecutionRefs:h(gP).default([]),localProfileCommit:Fe,hostedSourceCommit:Fe,hostedSourceRef:Fe,releaseOutcome:bP.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Fe,appliedActionIds:h(o().trim().min(1)).max(200).default([]),metadata:ca,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),Ta={runId:o().trim().min(1),expectedRevision:d().int().nonnegative(),actionId:o().trim().min(1)};dn("type",[c({...Ta,type:w("answer_question"),questionId:o().trim().min(1),value:o().trim().min(1)}),c({...Ta,type:w("approve_plan")}),c({...Ta,type:w("revise_plan"),revision:o().trim().min(1)}),c({...Ta,type:w("cancel"),reason:Fe.optional().default(null)}),c({...Ta,type:w("pause")}),c({...Ta,type:w("resume")}),c({...Ta,type:w("open_pull_request"),candidateId:o().trim().min(1)}),c({...Ta,type:w("apply_candidate"),candidateId:o().trim().min(1)}),c({...Ta,type:w("reject_candidate"),candidateId:o().trim().min(1),reason:Fe.optional().default(null)}),c({...Ta,type:w("reconcile_pull_request"),candidateId:o().trim().min(1)})]);c({schemaVersion:w("openpond.createImprove.runList.v1"),runs:h(Os),generatedAt:o().trim().min(1)});function SV(e){const t=rP.safeParse(e?.actionShape);return t.success?t.data:null}const tr=c({source:b(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}),vP=c({ref:tr,revision:o().nullable(),sourceHash:o()}),yP=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SP=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function xP(e){const t=typeof e=="string"?new TextEncoder().encode(e):e,n=Math.ceil((t.byteLength+9)/64)*64,a=new Uint8Array(n);a.set(t),a[t.byteLength]=128;const r=t.byteLength*8,i=new DataView(a.buffer);i.setUint32(n-8,Math.floor(r/4294967296),!1),i.setUint32(n-4,r>>>0,!1);const s=new Uint32Array(yP),l=new Uint32Array(64);for(let p=0;p<n;p+=64){for(let z=0;z<16;z+=1)l[z]=i.getUint32(p+z*4,!1);for(let z=16;z<64;z+=1){const N=l[z-15],x=l[z-2],I=Ea(N,7)^Ea(N,18)^N>>>3,P=Ea(x,17)^Ea(x,19)^x>>>10;l[z]=l[z-16]+I+l[z-7]+P>>>0}let m=s[0],f=s[1],S=s[2],y=s[3],k=s[4],R=s[5],A=s[6],D=s[7];for(let z=0;z<64;z+=1){const N=k&R^~k&A,x=m&f^m&S^f&S,I=Ea(m,2)^Ea(m,13)^Ea(m,22),P=Ea(k,6)^Ea(k,11)^Ea(k,25),j=D+P+N+SP[z]+l[z]>>>0,T=I+x>>>0;D=A,A=R,R=k,k=y+j>>>0,y=S,S=f,f=m,m=j+T>>>0}s[0]=s[0]+m>>>0,s[1]=s[1]+f>>>0,s[2]=s[2]+S>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+k>>>0,s[5]=s[5]+R>>>0,s[6]=s[6]+A>>>0,s[7]=s[7]+D>>>0}return Array.from(s,p=>p.toString(16).padStart(8,"0")).join("")}function Ea(e,t){return e>>>t|e<<32-t}const kP=2e3,a0=25e7,ne=o().trim().min(1).max(240),_e=o().regex(/^[a-f0-9]{64}$/),Qe=o().datetime({offset:!0}),wt=fe(o(),Se()).default({}),ce=c({id:ne,contentHash:_e}).strict(),Kn=c({id:ne,path:o().trim().min(1).max(kP).refine(wP),contentHash:_e,sizeBytes:d().int().nonnegative().max(a0),mediaType:o().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),Gn=c({id:ne,contentHash:_e,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:d().int().nonnegative().max(a0).nullable().default(null)}).strict(),fc=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function o0(e){return`${JSON.stringify(rm(e),null,2)}
124
- `}function _P(e){return xP(e)}function xt(e){return _P(o0(e))}function wP(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function rm(e){return Array.isArray(e)?e.map(rm):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,rm(n)]))}const ii=fe(o(),Se()).default({}),oa=d().int().nonnegative(),hc=o().trim().min(1).max(1e5),r0=c({kind:b(["personal","team"]),id:ne}).strict(),IP=c({name:ne,release:ce.nullable(),revision:oa}).strict();c({schemaVersion:w("openpond.harnessWorkspace.v1"),id:ne,ownerScope:r0,name:o().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:oa,dirty:C(),currentChannel:IP,createdAt:Qe,updatedAt:Qe,metadata:ii}).strict();const Gr=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),i0=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),s0=c({id:ne,route:Gr,operation:b(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),content:o().max(1e6).nullable(),contentHash:_e.nullable(),effects:h(i0).min(1).max(20)}).strict().superRefine((e,t)=>{if(e.operation==="delete"){(e.content!==null||e.contentHash!==null)&&t.addIssue({code:"custom",message:"delete edits cannot include replacement content",path:["content"]});return}if(e.content===null||e.contentHash===null){t.addIssue({code:"custom",message:"create and update edits require content and contentHash",path:["content"]});return}const n=xt(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),l0=c({workspaceId:ne,revision:oa,sourceRevision:o().trim().min(1).max(500),channelRevision:oa}).strict(),Za=c({id:ne,revision:oa,contentHash:_e}).strict(),CP=c({schemaVersion:w("openpond.harnessTurnSnapshot.v1"),workspaceId:ne,workspaceRevision:oa,sourceRevision:o().trim().min(1).max(500),channelName:ne,channelRevision:oa,harnessRelease:ce,toolCatalogHash:_e.nullable().optional(),overlay:Za.nullable().optional().default(null)}).strict(),RP=c({schemaVersion:w("openpond.harnessRunOverlay.v1"),id:ne,runId:ne,baseHarnessRelease:ce,workspace:l0,revision:oa,status:b(["active","frozen","abandoned"]),edits:h(s0).max(1e3),createdAt:Qe,updatedAt:Qe,metadata:ii}).strict();RP.extend({contentHash:_e}).strict();const c0=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:ne,contentHash:_e.nullable()}).strict(),d0=c({id:ne,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:hc,required:C()}).strict(),AP=c({schemaVersion:w("openpond.harnessImprovementProposal.v1"),id:ne,overlay:Za,baseHarnessRelease:ce,expectedWorkspace:l0,requestedScope:b(["personal","team","global"]),route:Gr,risk:b(["low","review","restricted"]),effects:h(i0).min(1).max(20),evidence:h(c0).min(1).max(1e3),edits:h(s0).min(1).max(1e3),validationPlan:h(d0).min(1).max(100),expectedOutcome:hc,createdAt:Qe,metadata:ii}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,r]of e.edits.entries()){r.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const i of r.effects)n.has(i)||t.addIssue({code:"custom",message:`edit effect ${i} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});AP.extend({contentHash:_e}).strict();const PP=c({schemaVersion:w("openpond.harnessTargetedValidationReceipt.v1"),id:ne,proposal:ce,validationId:ne,kind:d0.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:hc,evidenceRefs:h(c0).max(1e3),createdAt:Qe,metadata:ii}).strict();PP.extend({contentHash:_e}).strict();const TP=b(["advanced","retained","conflict","rolled_back"]),EP=c({schemaVersion:w("openpond.harnessAdvanceReceipt.v1"),id:ne,workspaceId:ne,ownerScope:r0,proposal:ce.nullable(),expectedWorkspaceRevision:oa,observedWorkspaceRevision:oa,previousChannelRevision:oa,nextChannelRevision:oa,previousRelease:ce.nullable(),nextRelease:ce.nullable(),validationReceipts:h(ce).max(100),decision:TP,reason:hc,rollbackOf:ce.nullable(),createdAt:Qe,metadata:ii}).strict().superRefine((e,t)=>{const n=e.nextChannelRevision===e.previousChannelRevision+1;["advanced","rolled_back"].includes(e.decision)!==n&&t.addIssue({code:"custom",message:"only successful advancement or rollback increments the channel revision",path:["nextChannelRevision"]}),e.decision==="rolled_back"&&e.rollbackOf===null&&t.addIssue({code:"custom",message:"rollback receipts require rollbackOf",path:["rollbackOf"]}),e.decision!=="rolled_back"&&e.rollbackOf!==null&&t.addIssue({code:"custom",message:"rollbackOf is only valid for rollback receipts",path:["rollbackOf"]})});EP.extend({contentHash:_e}).strict();const MP=c({schemaVersion:w("openpond.harnessOverlayMergeReceipt.v1"),id:ne,workspaceId:ne,baseHarnessRelease:ce,leftOverlay:Za,rightOverlay:Za,decision:b(["merged","conflict"]),mergedOverlay:Za.nullable(),conflictTargets:h(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:w(!0),createdAt:Qe,metadata:ii}).strict().superRefine((e,t)=>{e.decision==="merged"!=(e.mergedOverlay!==null)&&t.addIssue({code:"custom",message:"merged decisions require a merged overlay; conflicts cannot provide one",path:["mergedOverlay"]}),e.decision==="conflict"!=e.conflictTargets.length>0&&t.addIssue({code:"custom",message:"conflict decisions require conflict targets and merged decisions cannot include them",path:["conflictTargets"]})});MP.extend({contentHash:_e}).strict();const u0=b(["openpond.lab"]),im=c({id:o(),experience:lp.default(JA),provider:ri,modelRef:cn.nullable().optional(),openPondCommandAccessMode:Ms.default(Es),systemKind:u0.nullable().optional(),hiddenFromDefaultSidebar:C().optional(),parentSessionId:o().nullable().optional(),parentTurnId:o().nullable().optional(),subagentRunId:o().nullable().optional(),subagentRoleId:oi.nullable().optional(),subagentDelegationMode:lc.nullable().optional(),title:o(),appId:o().nullable(),appName:o().nullable(),workspaceKind:js.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:tr.nullable().optional(),metadata:fe(o(),Se()).optional(),cwd:o().nullable(),codexThreadId:o().nullable(),createdAt:o(),updatedAt:o(),status:b(["idle","active","failed","closed"]),runtimeSeconds:d().int().nonnegative().optional(),runtimeRunningSince:o().nullable().optional(),pinned:C(),savedForLater:C().optional(),archived:C(),order:d()});c({id:o(),sessionId:o(),providerTurnId:o().nullable(),modelRef:cn.nullable().optional(),prompt:o(),startedAt:o(),completedAt:o().nullable(),status:b(["in_progress","completed","failed","interrupted"]),error:o().nullable(),metadata:fe(o(),Se()).optional().default({}),createImproveRun:Os.nullable().optional().default(null),profileSnapshot:vP.nullable().optional(),harnessSnapshot:CP.nullable().optional()});const jP=c({id:o(),sessionId:o(),turnId:o().nullable(),providerRequestId:Cn([o(),d()]),kind:b(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:o(),detail:o(),status:b(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:o()}),OP=c({key:b(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:o(),status:b(["placeholder","available","error"]),summary:o()}),m0=c({id:o().trim().min(1).max(191),agentId:o().trim().min(1).max(191).optional().nullable(),sourcePath:o().trim().min(1).max(2e3).optional().nullable(),sourceActionId:o().trim().min(1).max(191).optional().nullable(),name:o().trim().min(1).max(191).optional().nullable(),label:o().trim().min(1).max(160).optional().nullable(),description:o().trim().max(1e3).optional().nullable(),visibility:o().trim().max(80).optional().nullable(),inputSchema:Cn([o().trim().max(191),fe(o(),Se())]).optional().nullable(),outputSchema:Cn([o().trim().max(191),fe(o(),Se())]).optional().nullable(),approvalPolicy:fe(o(),Se()).optional().nullable(),artifactPolicy:fe(o(),Se()).optional().nullable(),setupRequirements:h(fe(o(),Se())).optional(),mcp:fe(o(),Se()).optional().nullable(),schedulePolicy:fe(o(),Se()).optional().nullable(),trace:fe(o(),Se()).optional().nullable(),implementation:fe(o(),Se()).optional().nullable(),invokesModel:C().optional()}),NP=c({command:b(["inspect","build","validate","eval","traces","run"]),status:b(["passed","failed"]),checkedAt:o(),exitCode:d().nullable().optional(),sourceHead:o().nullable().optional()}),$P=c({id:o(),name:o(),path:o(),enabled:C()}),DP=c({name:o(),description:o(),path:o(),scope:w("profile"),enabled:C(),sourcePath:o(),charCount:d(),sourceHash:o(),validationStatus:b(["valid","warning","error"]),validationMessages:h(o()),resourceFiles:h(o()).optional().default([])}),LP=c({id:o(),name:o(),path:o(),agentId:o().nullable(),sourcePath:o()}),p0=c({path:o(),originalPath:o().nullable().optional(),indexStatus:o().nullable(),worktreeStatus:o().nullable(),status:o(),category:b(["added","modified","deleted","renamed","untracked","changed"])}),zP=c({isRepo:C(),branch:o().nullable(),head:o().nullable(),shortHead:o().nullable(),dirty:C(),upstream:o().nullable(),ahead:d().nullable(),behind:d().nullable(),remoteUrl:o().nullable(),files:h(p0),fileCount:d().int().nonnegative().optional(),error:o().nullable()}),UP=c({actionCount:d(),generatedAt:o().nullable(),manifestPath:o().nullable(),registryPath:o().nullable(),stale:C(),error:o().nullable()}),HP=c({skillCount:d(),generatedAt:o().nullable(),stale:C(),error:o().nullable()}),Ph=c({ref:o(),source:b(["action_catalog","source_upload_metadata"]),actionId:o().nullable(),kind:o().nullable(),label:o(),status:o(),required:C(),blocking:C()}),qP=c({status:b(["ready","setup_required","blocked"]),requirementCount:d(),blockingCount:d(),optionalMissingCount:d(),readyCount:d(),requirements:h(Ph),blockingRequirements:h(Ph)}),BP=c({changedAgents:h(o()),newAgents:h(o()),deletedAgents:h(o()),changedSkills:h(o()).optional().default([]),changedActions:h(o()),changedExtensions:h(o()),setupChanges:h(o()),envRequirementChanges:h(o()),files:h(p0),fileCount:d().int().nonnegative().optional()}),FP=c({status:o(),agentId:o().nullable().optional(),deployPlanStatus:o().nullable().optional(),canRun:C().nullable().optional(),canDeploy:C().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),setupCommands:h(o()).optional(),validationCommands:h(o()).optional(),requiredChecks:h(o()).optional(),evalNames:h(o()).optional(),blockedReasons:h(o()).optional(),staleReasons:h(o()).optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),traceArtifactRefs:h(o()).optional(),evalResultArtifactRefs:h(o()).optional(),validatorArtifactRefs:h(o()).optional(),checkedAt:o().nullable().optional(),error:o().nullable().optional()}),VP=c({status:o(),agentId:o().nullable().optional(),runtimeAgentId:o().nullable().optional(),projectId:o().nullable().optional(),sourceRoot:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),manifestSyncedAt:o().nullable().optional(),fileCount:d().nullable().optional(),totalBytes:d().nullable().optional(),generatedManifestPath:o().nullable().optional(),synthesizedOpenPondYaml:C().nullable().optional(),uploadMetadataPath:o().nullable().optional(),setupCommands:h(o()).optional(),validationCommands:h(o()).optional(),materializedAt:o().nullable().optional(),error:o().nullable().optional()}),WP=c({status:o(),agentId:o().nullable().optional(),snapshotId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),buildStatus:o().nullable().optional(),validationStatus:o().nullable().optional(),evalStatus:o().nullable().optional(),publishedAt:o().nullable().optional(),error:o().nullable().optional()}),KP=c({status:o(),agentId:o().nullable().optional(),runId:o().nullable().optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),setupGateStatus:o().nullable().optional(),setupRequirementRefs:h(o()).optional(),artifactRefs:h(o()).optional(),traceArtifactRefs:h(o()).optional(),evalArtifactRefs:h(o()).optional(),startedAt:o().nullable().optional(),completedAt:o().nullable().optional(),error:o().nullable().optional()}),GP=c({teamId:o().nullable(),projectId:o().nullable(),sourceRef:o().nullable(),sourceCommitSha:o().nullable(),lastPushedAt:o().nullable(),lastPushedLocalHead:o().nullable(),lastPushedHostedHead:o().nullable(),promotionStatus:o().nullable().optional().default(null),hostedRunStatus:o().nullable().optional().default(null),hostedRunAgentId:o().nullable().optional().default(null),hostedRunId:o().nullable().optional().default(null),hostedRunAt:o().nullable().optional().default(null),hostedSourceMaterialization:VP.nullable().optional().default(null),hostedSourceCheck:FP.nullable().optional().default(null),hostedPublish:WP.nullable().optional().default(null),hostedRun:KP.nullable().optional().default(null)}),ZP=c({state:b(["none","ready","dirty","pending_commit","error"]),message:o(),agentCount:d(),actionCount:d(),defaultAction:o().nullable(),checkFresh:C(),checkStaleReason:o().nullable(),localHead:o().nullable(),hostedHead:o().nullable()}),f0=c({mode:b(["none","local"]),repoPath:o().nullable(),activeProfile:o().nullable(),sourcePath:o().nullable(),manifestPath:o().nullable(),agents:h($P),skills:h(DP).optional().default([]),evals:h(LP).optional().default([]),git:zP.nullable(),catalog:UP,skillCatalog:HP.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:h(m0),sourceSetupRequirements:h(fe(o(),Se())),setupGate:qP,diff:BP,hosted:GP.nullable(),summary:ZP,lastCheck:NP.nullable(),error:o().nullable()}),JP=c({ref:tr,name:o(),repoPath:o(),sourcePath:o().nullable(),state:f0}),YP=c({lastUsed:tr.nullable(),profiles:h(JP)});function XP(){return{lastUsed:null,profiles:[]}}function QP(){return{mode:"none",repoPath:null,activeProfile:null,sourcePath:null,manifestPath:null,agents:[],skills:[],evals:[],git:null,catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:null},skillCatalog:{skillCount:0,generatedAt:null,stale:!0,error:null},actionCatalog:[],sourceSetupRequirements:[],setupGate:{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]},diff:{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]},hosted:null,summary:{state:"none",message:"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:"No active profile.",localHead:null,hostedHead:null},lastCheck:null,error:null}}const eT=c({name:o(),description:o(),path:o(),sourcePath:o(),enabled:C(),charCount:d().int().nonnegative(),sourceHash:o(),validationStatus:b(["valid","error"]),validationMessages:h(o()),resourceFiles:h(o()),updatedAt:o().nullable()}),tT=b(["codex","profile","extension"]);c({skillName:o(),scope:tT,path:o(),byteSize:d().int().nonnegative(),isBinary:C(),content:o().nullable()});const nT=[{name:"openpond-taskset-authoring",description:"Create, improve, inspect, test, or prepare an OpenPond Taskset from a capability, Profile Agent, consented evidence, or imported data.",path:"skills/openpond-taskset-authoring/SKILL.md",scope:"profile",enabled:!0,sourcePath:"bundled://openpond",charCount:0,sourceHash:"bundled",validationStatus:"valid",validationMessages:[],resourceFiles:["references/task-design.md","references/graders-and-rewards.md","references/method-selection.md","references/privacy-and-provenance.md"]},{name:"openpond-skill-authoring",description:"Create, copy, adapt, review, or update OpenPond Profile skill packages from slash commands or ordinary authoring requests.",path:"skills/openpond-skill-authoring/SKILL.md",scope:"profile",enabled:!0,sourcePath:"bundled://openpond",charCount:0,sourceHash:"bundled",validationStatus:"valid",validationMessages:[],resourceFiles:["references/skill-package-layout.md","references/copying-and-adaptation.md","references/validation-and-repair.md","scripts/validate-skill.mjs"]},{name:"openpond-agent-authoring",description:"Create, improve, review, or repair source-backed OpenPond Profile Agents and Agent SDK projects.",path:"skills/openpond-agent-authoring/SKILL.md",scope:"profile",enabled:!0,sourcePath:"bundled://openpond",charCount:0,sourceHash:"bundled",validationStatus:"valid",validationMessages:[],resourceFiles:["references/profile-layout.md","references/action-and-chat-design.md","references/integrations-and-setup.md","references/validation-and-repair.md"]},{name:"openpond-refiner-authoring",description:"Inspect, extend, validate, activate, or roll back the OpenPond Refiner Review Profile without changing the Refiner Core.",path:"skills/openpond-refiner-authoring/SKILL.md",scope:"profile",enabled:!0,sourcePath:"bundled://openpond",charCount:0,sourceHash:"bundled",validationStatus:"valid",validationMessages:[],resourceFiles:["references/review-profile.md","references/core-boundary.md","references/validation-and-activation.md"]}],aT=c({name:o(),description:o(),relativePath:o(),sourcePath:o(),charCount:d().int().nonnegative(),sourceHash:o(),resourceFiles:h(o()),validationStatus:b(["valid","error"]),validationMessages:h(o())}),h0=c({id:o(),source:w("github"),owner:o(),repo:o(),repositoryUrl:o().url(),requestedRef:o(),resolvedCommit:o(),sourcePath:o(),readmePath:o().nullable(),installedAt:o(),updatedAt:o(),packageHash:o(),skills:h(aT),validationStatus:b(["valid","error"]),validationMessages:h(o())});h0.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:cv()});const oT=c({rootPath:o(),registryPath:o(),extensions:h(h0),error:o().nullable()});c({source:o().trim().min(1),ref:o().trim().min(1).optional()});const rT=c({latestSequence:d().int().nonnegative(),oldestSequence:d().int().nonnegative(),totalEvents:d().int().nonnegative(),limit:d().int().nonnegative(),hasMoreBefore:C()});c({server:ZA,account:zA,codex:UA,preferences:Rh.optional().default(()=>Rh.parse({})),providers:Zf.optional().default(()=>Zf.parse({})),personalization:Ah.optional().default(()=>Ah.parse({soul:Qv[0].content,soulPath:null,updatedAt:null})),apps:h(GR),localProjects:h(QR).optional().default([]),cloudProjects:h(XR).optional().default([]),profile:f0.optional().default(QP),profileLibrary:YP.optional().default(XP),codexPersonalSkills:h(eT).optional().default([]),extensionCatalog:oT.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:h(im).optional().default([]),sidebarAppPreferences:MA,sidebarFileBookmarks:h(Yv).optional().default([]),appsError:o().nullable(),appsMeta:Ch,accountMeta:Ch,sessions:h(im),events:h(Jf),eventWindow:rT.optional(),approvals:h(jP),placeholders:h(OP),diagnostics:h(Jf)});const dp=b(["openpond_hosted","local_byok","codex_app_server","unknown"]),g0=b(["provider_usage","codex_context_usage","missing"]),iT=b(["provider_usage_body","provider_response_headers"]),sT=b(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),lT=b(["foreground","tool_loop","compaction","subagent","refiner","other"]),b0=b(["user_facing","background","system"]),v0=b(["started","completed","failed","interrupted"]),up=b(["composer_selection","prompt_parse","server_parser","model_tool","api"]),y0=b(["chat","settings","goal","create_improve","compaction","system"]),S0=b(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),cT=c({surface:y0,workflowKind:S0,sessionId:o().trim().min(1).nullable().default(null),turnId:o().trim().min(1).nullable().default(null),goalId:o().trim().min(1).nullable().default(null),subagentRunId:o().trim().min(1).nullable().default(null),subagentRoleId:o().trim().min(1).nullable().default(null),createImproveRunId:o().trim().min(1).nullable().default(null),commandName:o().trim().min(1).max(160).nullable().default(null),commandSource:up.nullable().default(null),appId:o().trim().min(1).nullable().default(null),workspaceKind:js.nullable().default(null),workspaceId:o().trim().min(1).nullable().default(null),localProjectId:o().trim().min(1).nullable().default(null),cloudProjectId:o().trim().min(1).nullable().default(null),sourceEventSequence:d().int().nonnegative().nullable().default(null)}),dT=c({surface:y0.optional(),workflowKind:S0.optional(),goalId:o().trim().min(1).nullable().optional(),subagentRunId:o().trim().min(1).nullable().optional(),subagentRoleId:o().trim().min(1).nullable().optional(),createImproveRunId:o().trim().min(1).nullable().optional(),commandName:o().trim().min(1).max(160).nullable().optional(),commandSource:up.nullable().optional()}).strict(),si=o().trim().min(1).max(160),uT=c({id:o().trim().min(1),requestId:o().trim().min(1),requestOrdinal:d().int().nonnegative(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable(),provider:si,model:o().trim().min(1),route:dp,source:g0,requestKind:sT,visibility:b0,status:v0,startedAt:o().trim().min(1),completedAt:o().trim().min(1).nullable(),durationMs:d().int().nonnegative().nullable(),firstTokenMs:d().int().nonnegative().nullable(),promptTokens:d().int().nonnegative().nullable(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheTelemetrySource:iT.nullable(),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),errorType:o().trim().min(1).max(160).nullable(),errorMessage:o().trim().min(1).max(2e3).nullable(),attribution:cT}),x0=c({from:o().trim().min(1),to:o().trim().min(1),bucket:b(["day","all_time"])}),mp=Cn([w("all"),b0]),pp=b(["all","started","completed","failed","interrupted","missing"]),mT=c({range:b(["7d","30d","90d","all"]).default("30d"),visibility:mp.default("all"),status:pp.default("all"),provider:si.optional(),model:o().trim().min(1).optional()});mT.extend({sessionId:o().trim().min(1).optional(),turnId:o().trim().min(1).optional(),limit:d().int().positive().max(500).default(100)});const nr=c({requests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failures:d().int().nonnegative(),failureRate:d().nonnegative(),firstSeenAt:o().trim().min(1),lastSeenAt:o().trim().min(1)}),pT=nr.extend({provider:si,model:o().trim().min(1),route:dp}),fT=nr.extend({sessionId:o().trim().min(1),title:o().trim().min(1).nullable(),workspaceKind:js.nullable(),workspaceId:o().trim().min(1).nullable()}),hT=nr.extend({commandName:o().trim().min(1),commandSource:up.nullable()}),gT=nr.extend({route:dp}),bT=nr.extend({status:v0}),vT=nr.extend({source:g0}),yT=nr.extend({cohort:lT}),ST=c({date:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative(),models:h(c({provider:si,model:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative()}))}),xT=c({requests:d().int().nonnegative(),completedRequests:d().int().nonnegative(),failedRequests:d().int().nonnegative(),missingUsageRequests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failureRate:d().nonnegative(),activeModelCount:d().int().nonnegative(),peakDailyTokens:d().int().nonnegative(),longestRequestMs:d().int().nonnegative().nullable(),activeDays:d().int().nonnegative(),currentStreakDays:d().int().nonnegative(),longestStreakDays:d().int().nonnegative()});c({generatedAt:o().trim().min(1),range:x0,filters:c({visibility:mp,status:pp,provider:si.nullable(),model:o().trim().min(1).nullable()}),totals:xT,daily:h(ST),models:h(pT),threads:h(fT),commands:h(hT),routes:h(gT),statuses:h(bT),sources:h(vT),cohorts:h(yT)});c({generatedAt:o().trim().min(1),range:x0,filters:c({visibility:mp,status:pp,provider:si.nullable(),model:o().trim().min(1).nullable(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable()}),limit:d().int().positive(),hasMore:C(),records:h(uT)});const kT=b(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:kT,title:o().trim().min(1),summary:o().trim().min(1),severity:b(["nit","concern","blocker"]),payload:fe(o(),Se()).default({})});const _T=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),wT=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),IT=b(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),CT=c({kind:w("integration"),provider:_T,appIds:h(wT).min(1).max(4),setupSurfaces:h(IT).min(1).max(4),connectionIds:h(o().trim().min(1)).max(8).optional(),capabilities:h(o().trim().min(1)).max(64).optional()}).strict(),Bo={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},RT=b(["image","text","file"]),AT=c({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(240),contentType:o().trim().min(1).max(160)}),PT=c({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(1024),contentType:o().trim().min(1).max(160)}),k0=c({id:o().trim().min(1),name:o().trim().min(1).max(240),mediaType:o().trim().min(1).max(160),sizeBytes:d().int().nonnegative().max(Bo.maxAttachmentBytes),kind:RT,lineCount:d().int().nonnegative().max(Bo.maxAttachmentBytes+1).optional(),relativePath:o().trim().min(1).max(1024).optional(),text:o().max(Bo.maxTextChars).optional(),contentsBase64:o().max(Bo.maxAttachmentBase64Chars).optional()}),TT=k0.omit({text:!0,contentsBase64:!0}).extend({imagePreview:AT.optional(),filePreview:PT.optional()});c({experience:lp.optional(),provider:ri.default(Zo),modelRef:cn.optional(),openPondCommandAccessMode:Ms.optional(),systemKind:u0.nullable().optional(),hiddenFromDefaultSidebar:C().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:oi.nullable().optional(),subagentDelegationMode:lc.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:js.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:tr.nullable().optional(),metadata:fe(o(),Se()).optional(),cwd:o().nullable().optional(),title:o().optional(),autoTitlePrompt:o().trim().min(1).max(2e4).optional()});c({teamId:o().trim().min(1),projectName:o().trim().min(1).max(120).optional(),branch:o().trim().min(1).max(120).optional(),chatSessionId:o().trim().min(1).max(200).optional(),displayPrompt:o().trim().min(1).max(2e3).optional()});c({branch:o().trim().min(1).max(120).optional()});c({prompt:o().min(1),metadata:fe(o(),Se()).optional(),usageAttribution:dT.optional().nullable(),cwd:o().nullable().optional(),model:o().nullable().optional(),modelRef:cn.optional(),mentionedAppIds:h(o().trim().min(1)).max(8).optional(),mentionedConnectedApps:h(CT).max(8).optional(),openPondActionCatalog:h(m0).max(100).optional(),attachments:h(k0).max(Bo.maxAttachments).optional(),createImproveRun:Os.optional().nullable(),approvalPolicy:b(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:b(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:ip.default("default"),codexReasoningEffort:pc.optional()});c({prompt:o().min(1),error:o().min(1),target:b(["cloud_workspace","hybrid_sandbox"])});c({reason:b(["manual"]).default("manual"),model:o().nullable().optional(),modelRef:cn.optional()});c({experience:lp.optional(),provider:ri.optional(),modelRef:cn.nullable().optional(),openPondCommandAccessMode:Ms.optional(),pinned:C().optional(),savedForLater:C().optional(),archived:C().optional(),order:d().optional(),title:o().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:oi.nullable().optional(),subagentDelegationMode:lc.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:js.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:tr.nullable().optional(),metadata:fe(o(),Se()).optional(),cwd:o().nullable().optional()});c({command:o().trim().min(1),cwd:o().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:d().int().min(1).max(3600).optional()});c({appIds:h(o()).min(1)});c({defaultChatProvider:ri.optional(),defaultChatModel:o().min(1).optional(),defaultChatModelRef:cn.nullable().optional(),subagents:hs.optional(),codexPermissionMode:ip.optional(),codexReasoningEffort:pc.optional(),openPondCommandAccessMode:Ms.optional(),defaultBranchPrefix:o().trim().max(48).optional(),defaultNewProjectDirectory:o().trim().max(4096).optional(),defaultTeamId:o().trim().max(191).nullable().optional(),advancedWorkspaceControls:C().optional(),contextCompaction:nm.optional(),training:am.optional(),sidebarWidth:d().int().min(244).max(560).optional(),diffPanelWidth:d().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:tm.optional(),editor:ql.optional()});c({message:o().trim().min(1).max(4e3),surface:o().trim().min(1).max(120).default("app"),stack:o().max(12e3).nullable().optional(),context:fe(o(),Se()).optional()}).strict();c({activeTemplateId:sp,templateName:o().trim().min(1).max(80),soul:o().trim().min(1).max(8e3),saveAsNew:C().optional().default(!1)});c({decision:b(["accept","acceptForSession","decline","cancel"])});c({branch:o().trim().min(1).max(240).nullable().optional(),surface:b(["desktop","terminal"])});c({handle:o().min(1),baseUrl:o().nullable().optional()});c({handle:o().min(1),baseUrl:o().nullable().optional()});c({handle:o().min(1).optional(),apiKey:o().min(1),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:C().optional()});c({handle:o().min(1),currentBaseUrl:o().nullable().optional(),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:C().optional()});c({appId:o(),exists:C(),configPath:o().nullable().optional(),envVar:o().nullable(),toolName:o().nullable(),version:Cn([o(),d()]).nullable(),source:b(["hosted_env","local_file","defaults","missing"]),currentConfig:fe(o(),Se()).nullable(),defaults:fe(o(),Se()).nullable(),schema:fe(o(),Se()).nullable(),error:o().nullable().optional(),updatedAt:o()}).passthrough();const Bl=b(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);c({action:Bl,args:fe(o(),Se()).optional().default({}),source:b(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:C(),action:Bl,appId:o().nullable().optional(),output:o(),data:Se().optional()});const Ns=c({id:o().trim().min(1).max(200),title:o().trim().min(1).max(240),sourceTaskId:o().trim().min(1).max(200),sourceTurnId:o().trim().min(1).max(200),revision:d().int().positive().default(1),createdAt:o().datetime()}),$s=c({kind:b(["structural","visual","test","user_review"]),status:b(["passed","failed","not_run"]),label:o().trim().min(1).max(240),detail:o().trim().max(4e3).nullable().optional(),ref:o().trim().max(4096).nullable().optional()}),_0=c({kind:w("local"),path:o().trim().min(1).max(4096),deviceId:o().trim().min(1).max(200)}),w0=c({kind:w("managed"),fileId:o().trim().min(1).max(200),downloadPath:o().trim().min(1).max(4096)}),ET=c({kind:w("external"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url().nullable()}),I0=Ns.extend({kind:w("file"),contentType:o().trim().min(1).max(200),sizeBytes:d().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),location:dn("kind",[_0,w0,ET]),validation:h($s).max(32).default([])}),MT=Ns.extend({kind:w("source_change"),projectId:o().trim().min(1).max(200),ref:o().trim().min(1).max(500),url:o().url().nullable(),validation:h($s).max(32).default([])}),jT=Ns.extend({kind:w("deployment"),deploymentId:o().trim().min(1).max(200),url:o().url(),validation:h($s).max(32).default([])}),OT=Ns.extend({kind:w("external_resource"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url(),contentType:o().trim().min(1).max(200).nullable(),validation:h($s).max(32).default([])}),C0=c({id:o().trim().min(1).max(191),label:o().trim().min(1).max(160).nullable(),description:o().trim().max(1e3).nullable(),inputSchema:fe(o(),Se()).nullable(),outputSchema:fe(o(),Se()).nullable(),schedulePolicy:fe(o(),Se()).nullable()}),R0=c({base:o().trim().min(1).max(200),resources:fe(o(),Se()),modelPolicy:fe(o(),Se()).nullable(),setup:fe(o(),Se()).nullable()}),NT=c({id:o().trim().min(1).max(200),kind:b(["sdk_validation","sdk_eval"]),status:b(["passed","failed"]),summary:o().trim().min(1).max(2e3),artifactPath:o().trim().min(1).max(4096),artifactSha256:o().regex(/^[a-f0-9]{64}$/)}),$T=c({path:o().trim().min(1).max(4096),sizeBytes:d().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),contentsBase64:o()});c({schema:w("openpond.agent-package.v1"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),title:o().trim().min(1).max(240),source:c({files:h($T).min(1).max(1e3),totalSizeBytes:d().int().nonnegative()}),manifest:fe(o(),Se()),actions:h(C0).min(1).max(256),runtimeRequirements:R0,receipts:h(NT).min(2).max(64)});const DT=Ns.extend({kind:w("agent_package"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),packageFileId:o().trim().min(1).max(200),manifestFileId:o().trim().min(1).max(200),actions:h(C0).min(1).max(256),runtimeRequirements:R0,validationReceiptIds:h(o().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:h(o().trim().min(1).max(200)).min(1).max(32),sourceFileCount:d().int().positive(),sourceSizeBytes:d().int().nonnegative(),location:dn("kind",[_0,w0]),validation:h($s).max(32).default([])}),xV=dn("kind",[I0,MT,jT,OT,DT]);c({outputs:h(I0)});const LT=b(["sandbox_template","sandbox","generic_git","plain_folder"]),zT=b(["sandbox_template"]).nullable();c({productKind:LT,actions:c({files:C(),git:C(),sandboxRuntime:C(),sandboxTemplate:C()}),checks:c({validate:Bl.nullable(),build:Bl.nullable(),postEdit:zT}),ui:c({showSandboxTemplateActions:C(),showSandboxRuntimeActions:C()})});const UT=c({id:o(),name:o(),dnsName:o().nullable(),os:o().nullable(),online:C(),active:C(),isSelf:C(),tailscaleIps:h(o()),lastSeen:o().nullable()}),HT=c({installed:C(),running:C(),version:o().nullable(),backendState:o().nullable(),tailnetName:o().nullable(),magicDnsSuffix:o().nullable(),machineName:o().nullable(),dnsName:o().nullable(),authUrl:o().nullable(),tailscaleIps:h(o()),health:h(o()),error:o().nullable(),peers:h(UT)}),qT=c({enabled:C(),reachable:C(),targetUrl:o().nullable(),httpsUrl:o().nullable(),httpsHost:o().nullable(),httpsPort:d().nullable(),setupUrl:o().nullable(),configText:o().nullable(),error:o().nullable()}),BT=c({localUrl:o(),localWebUrl:o(),remoteUrl:o().nullable(),remoteWebUrl:o().nullable(),tokenHash:o(),tailscaleUpCommand:o(),serveCommand:o(),disableCommand:o(),operatorCommand:o(),webUiAvailable:C(),updatedAt:o(),tailscale:HT,serve:qT});c({message:o(),status:BT});const A0=b(["github","openpond_git"]),P0=b(["private","public"]),FT=b(["actions","prompts","goals","evals","examples","tasksets","extensions"]),VT=c({agentIds:h(o().trim().min(1)).max(100),skillNames:h(o().trim().min(1)).max(200),optionalContent:h(FT).max(20).default([])}),T0=c({provider:A0,owner:o().trim().min(1).max(191).nullable().optional(),repository:o().trim().min(1).max(191),visibility:P0.default("private")}),WT=c({ref:tr,selection:VT,target:T0}),KT=c({path:o(),sizeBytes:d().int().nonnegative(),category:o()});c({sourceHash:o(),sourceRevision:o().nullable(),clean:C(),blockedReasons:h(o()),warnings:h(o()),files:h(KT),excludedFiles:h(o()),target:T0,replacesExisting:C()});WT.extend({expectedSourceHash:o().trim().min(1),confirmed:w(!0)});c({provider:A0,owner:o(),repository:o(),visibility:P0,remoteUrl:o(),webUrl:o(),revision:o()});const GT=b(["cron","rate"]),E0=b(["queued","running","succeeded","failed","skipped"]),M0=c({id:o(),localProjectId:o(),localProjectName:o(),agentRootPath:o(),agentName:o(),scheduleName:o(),scheduleType:GT,scheduleExpression:o(),timezone:o().nullable(),targetAction:o(),input:fe(o(),Se()).optional().default({}),enabledByDefault:C(),enabled:C(),sourceHash:o(),manifestHash:o().nullable(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:E0.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),createdAt:o(),updatedAt:o()}),j0=c({id:o(),scheduleId:o(),localProjectId:o(),scheduleName:o(),scheduledFor:o(),trigger:b(["schedule","manual"]),status:E0,targetAction:o(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),startedAt:o().nullable(),completedAt:o().nullable(),exitCode:d().int().nullable(),stdout:o().nullable(),stderr:o().nullable(),result:fe(o(),Se()).nullable(),traceArtifactRef:o().nullable(),error:o().nullable(),createdAt:o(),updatedAt:o()});c({schedules:h(M0),scheduler:c({running:C(),nextTickAt:o().nullable(),lastSyncAt:o().nullable(),scanRunning:C()})});c({runs:h(j0)});c({enabled:C().optional()});c({input:fe(o(),Se()).optional()});c({schedule:M0,run:j0});const ZT=b(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),fp=c({version:w(1),kind:b(["once","daily","weekdays","weekly","monthly"]),timeZone:o().trim().min(1).max(100),startDate:o().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:o().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:h(ZT).min(1).max(7).optional(),dayOfMonth:d().int().min(1).max(31).optional(),end:dn("kind",[c({kind:w("never")}),c({kind:w("on_date"),date:o().regex(/^\d{4}-\d{2}-\d{2}$/)}),c({kind:w("after_occurrences"),occurrences:d().int().min(1).max(1e5)})])}).superRefine((e,t)=>{e.kind==="weekly"&&!e.weekdays?.length&&t.addIssue({code:"custom",message:"Weekly recurrence requires at least one weekday.",path:["weekdays"]}),e.kind==="monthly"&&e.dayOfMonth===void 0&&t.addIssue({code:"custom",message:"Monthly recurrence requires a day of month.",path:["dayOfMonth"]})}),JT=c({id:o(),expression:o().nullable(),timeZone:o(),recurrence:fp.nullable(),configurationVersion:d().int(),enabled:C(),nextRunAt:o().nullable(),lastTriggeredAt:o().nullable(),delivery:fe(o(),Se()).default({})}),YT=c({id:o(),definitionKey:o(),version:d().int(),name:o(),prompt:o(),modelId:o(),schedules:h(JT)}),XT=c({id:o(),definitionId:o(),scheduleId:o().nullable(),definitionName:o(),definitionVersion:d().int(),conversationId:o(),triggerKind:b(["manual","schedule","webhook","retry"]),status:o(),notificationStatus:o(),deliveryStatus:o(),deliveryError:o().nullable(),createdAt:o()});c({definitions:h(YT),runs:h(XT),asOf:o(),webBaseUrl:o().url().optional()});c({clientRequestId:o().trim().min(1).max(191),sourceTurnId:o().trim().min(1).max(191).nullable().optional(),name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:fp,modelId:o().trim().min(1).max(191).default("openpond-chat")});Cn([c({enabled:C()}),c({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:fp})]);const hp=fe(o(),Se());c({userId:o(),role:b(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable()});const QT=c({userId:o(),role:b(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable(),lastReadSequence:d().int().nonnegative()}),eE=c({id:o(),messageId:o(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:hp,createdAt:o()}),O0=c({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:w("image"),name:o(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:b(["pending","ready","failed"]),createdAt:o(),readyAt:o().nullable()});c({attachment:O0,uploadUrl:o().url().nullable(),uploadHeaders:fe(o(),o()),expiresAt:o().nullable()});c({url:o().url(),expiresAt:o()});const gp=c({id:o(),threadId:o(),teamId:o(),clientRequestId:o().nullable(),authorType:b(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:d().int().nonnegative(),kind:b(["text","system","command_result"]),body:o(),metadata:hp,editedAt:o().nullable(),deletedAt:o().nullable(),createdAt:o(),refs:h(eE),attachments:h(O0)}),tE=c({id:o(),teamId:o(),kind:b(["general","dm","group","channel"]),title:o().nullable(),createdByUserId:o(),lastMessageId:o().nullable(),lastMessageSequence:d().int().nonnegative(),lastMessageAt:o(),createdAt:o(),updatedAt:o(),unreadCount:d().int().nonnegative(),pinnedAt:o().nullable(),mutedAt:o().nullable(),archivedAt:o().nullable(),participants:h(QT),lastMessage:gp.nullable()});c({thread:tE,messages:h(gp),hasMoreBefore:C()});c({threadId:o(),mutedAt:o().nullable()});const nE=b(["pending","running","completed","failed","interrupted","cancelled"]),Th=c({id:o(),conversationId:o(),threadId:o(),teamId:o(),requestedByUserId:o(),executorUserId:o().nullable(),providerId:o(),modelId:o(),clientRequestId:o(),baseMessageSequence:d().int().nonnegative(),status:nE,partialBody:o().nullable(),userMessageId:o(),assistantMessageId:o().nullable(),errorCode:o().nullable(),cancelledByUserId:o().nullable(),leaseExpiresAt:o().nullable(),heartbeatAt:o().nullable(),createdAt:o(),updatedAt:o()}),aE=c({id:o(),conversationId:o(),sequence:d().int().nonnegative(),role:b(["user","assistant","system","action"]),body:o(),createdByUserId:o().nullable(),createdAt:o()});c({conversationId:o(),parentThreadId:o(),parentMessageId:o(),teamId:o(),title:o().nullable(),providerId:o().nullable(),modelId:o(),createdByUserId:o(),messages:h(aE),turns:h(Th),activeTurn:Th.nullable(),createdAt:o(),updatedAt:o()});const N0=c({id:d().int().nonnegative(),teamId:o(),threadId:o(),conversationId:o().nullable(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:hp,createdAt:o()});c({events:h(N0),cursor:d().int().nonnegative(),hasMore:C()});c({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),teamId:o().min(1),userId:o().min(1)});const bp=fe(o(),Se()),ra=o().nullable(),oE=b(["draft","published","archived"]),vp=b(["owner","admin","member"]),$0=b(["active","left"]),D0=b(["mentions","all","none"]),L0=b(["public_preview","members"]),rE=b(["members","admins"]),iE=c({canPreview:C(),canJoin:C(),canLeave:C(),canRead:C(),canPost:C(),canUpload:C(),canMention:C(),canManage:C(),requiresRulesAcceptance:C(),currentRulesVersionId:o().nullable()}),z0=c({id:o(),communityId:o(),version:d().int().positive(),title:o(),requiresReacceptance:C(),publishedAt:o()}),sE=z0.extend({bodyMarkdown:o(),contentHash:o()}),lE=c({role:vp,status:$0,notificationMode:D0}),cE=c({id:o(),communityId:o(),userId:o(),role:vp,status:$0,notificationMode:D0,joinedAt:o(),leftAt:ra,createdAt:o(),updatedAt:o()}),U0=c({id:o(),slug:o(),displayName:o(),description:o(),imageUrl:o().nullable(),status:oE,visibility:b(["public","private"]),joinPolicy:b(["open","closed"]),historyVisibility:L0,featuredAt:ra,publishedAt:ra,archivedAt:ra,memberCount:d().int().nonnegative(),membership:lE.nullable(),capabilities:iE,currentRules:z0.nullable()});c({items:h(U0),nextCursor:o().nullable()});const H0=c({lastReadSequence:d().int().nonnegative(),lastReadAt:ra.optional(),mutedAt:ra,pinnedAt:ra}),yp=c({id:o(),communityId:o(),chatThreadId:o().nullable(),slug:o(),displayName:o(),topic:o(),position:d().int().nonnegative(),visibility:L0,postingPolicy:rE,isDefault:C(),archivedAt:ra,lastMessageSequence:d().int().nonnegative(),unreadCount:d().int().nonnegative(),readState:H0.nullable()});U0.omit({currentRules:!0}).extend({currentRules:sE.nullable(),channels:h(yp),previewMessageLimit:d().int().positive()});const dE=c({id:o(),messageId:o(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:bp,createdAt:o()}),q0=c({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:w("image"),name:o(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:b(["pending","ready","failed"]),createdAt:o(),readyAt:ra});c({attachment:q0,uploadUrl:o().url().nullable(),uploadHeaders:fe(o(),o()),expiresAt:ra});c({url:o().url(),expiresAt:o()});const B0=c({id:o(),threadId:o(),teamId:cv(),clientRequestId:o().nullable(),authorType:b(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:d().int().nonnegative(),kind:b(["text","system","command_result"]),body:o(),metadata:bp,editedAt:ra,deletedAt:ra,createdAt:o(),refs:h(dE),attachments:h(q0)});c({messages:h(B0),hasMoreBefore:C(),channelId:o(),readState:H0.omit({lastReadAt:!0}).nullable(),preview:C()});const uE=c({userId:o(),handle:o().nullable(),name:o().nullable(),role:vp});c({items:h(uE),nextCursor:o().nullable()});const F0=c({id:d().int().nonnegative(),communityId:o(),channelId:o(),threadId:o(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:bp,createdAt:o()});c({events:h(F0),cursor:d().int().nonnegative(),hasMore:C()});c({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),communityId:o().min(1),userId:o().min(1),channel:o().min(1)});c({membership:cE,channels:h(yp)});c({channels:h(yp)});const Wn=o().trim().min(1).max(240),uo=o().trim().min(1),V0=fe(o(),Se()).default({}),W0=b(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),K0=b(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),mE=c({id:Wn,kind:b(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:h(Wn).min(1).max(1e4),occurredAt:uo,signature:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(5e3),confidence:d().min(0).max(1),consented:C(),metadata:V0}),pE=c({frequency:d().min(0).max(1),businessValue:d().min(0).max(1),frontierCost:d().min(0).max(1),signalQuality:d().min(0).max(1),verifiability:d().min(0).max(1),repeatability:d().min(0).max(1),privacyRisk:d().min(0).max(1),overall:d().min(0).max(1)}),fE=c({tactic:K0,eligible:C(),reasons:h(o().trim().min(1).max(5e3)).min(1).max(100),blockers:h(o().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:h(o().trim().min(1).max(500)).max(100).default([]),generatedBy:b(["decision_table","baseline_reassessment"])}),G0=c({schemaVersion:w("openpond.taskCandidate.v1"),id:Wn,profileId:Wn,status:W0,fingerprint:o().trim().min(1).max(512),title:o().trim().min(1).max(500),summary:o().trim().min(1).max(1e4),workflowSignature:o().trim().min(1).max(2e3),evidence:h(mE).min(1).max(1e5),scorecard:pE,recommendation:fE,mergedIntoId:Wn.nullable(),createdAt:uo,updatedAt:uo,metadata:V0}),gc=c({schemaVersion:w("openpond.taskMinerConfig.v1"),enabled:C().default(!1),localOnly:C().default(!0),observationWindowDays:d().int().min(1).max(365).default(30),minimumRecurrence:d().int().min(2).max(100).default(3),clustering:w("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:C().default(!0)});c({items:h(G0),generatedAt:uo,config:gc});c({status:W0.optional(),mergeIntoId:Wn.nullable().optional()});c({profileId:Wn,sourceIds:h(Wn).max(1e5).default([]),sessionIds:h(Wn).max(1e5).default([]),config:gc.optional()});const hE=c({schemaVersion:w("openpond.taskMinerRun.v1"),id:Wn,profileId:Wn,status:b(["queued","running","cancelling","cancelled","succeeded","failed"]),config:gc,sourceIds:h(Wn).max(1e5),sessionIds:h(Wn).max(1e5).default([]),progress:c({stage:b(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:d().int().nonnegative(),totalSources:d().int().nonnegative(),candidatesFound:d().int().nonnegative(),skippedSources:d().int().nonnegative().default(0)}),candidateIds:h(Wn).max(1e5),cancelRequested:C(),error:o().trim().min(1).max(2e4).nullable(),createdAt:uo,startedAt:uo.nullable(),completedAt:uo.nullable(),updatedAt:uo}),ia=o().trim().min(1).max(240),Ja=o().trim().min(1),ho=o().trim().min(8).max(256),Z0=o().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),So=b(["train","validation","test","frozen_eval"]),gE=c({name:o().trim().min(1).max(500),semanticRole:b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:b(["string","integer","float","boolean","json","messages"]),nullable:C(),policy:b(["visible","privileged","metadata"])}),bE=c({schemaVersion:w("openpond.datasetSemanticSchema.v1"),fields:h(gE).min(1).max(1e4),schemaHash:ho}),vE=c({id:ia,split:So,path:Z0,contentHash:ho,schemaHash:ho,sizeBytes:d().int().nonnegative(),rowCount:d().int().positive(),rowGroupCount:d().int().positive()}),Sp=c({schemaVersion:w("openpond.datasetArtifact.v1"),id:ia,tasksetId:ia,tasksetRevision:d().int().positive(),contentHash:ho,format:w("parquet"),schema:bE,shards:h(vE).min(1).max(1e5),rowCount:d().int().positive(),splitCounts:fe(So,d().int().nonnegative()),sourceReceiptRefs:h(ia).min(1).max(1e5),mappingHash:ho,qualityReportHash:ho,createdAt:Ja}),yE=c({schemaVersion:w("openpond.datasetArtifactSummary.v1"),artifactId:ia,tasksetId:ia,tasksetRevision:d().int().positive(),format:w("parquet"),rowCount:d().int().positive(),splitCounts:fe(So,d().int().nonnegative()),sizeBytes:d().int().nonnegative(),contentHash:ho,available:C(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:Ja}),SE=c({schemaVersion:w("openpond.datasetCatalogItem.v1"),tasksetId:ia,tasksetRevision:d().int().positive(),artifactId:ia.nullable(),name:o().trim().min(1).max(500),status:b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:b(["inline","parquet"]),rowCount:d().int().nonnegative(),splitCounts:fe(So,d().int().nonnegative()),sizeBytes:d().int().nonnegative().nullable(),available:C(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:Ja,updatedAt:Ja});c({schemaVersion:w("openpond.datasetCatalog.v1"),profileId:ia,datasets:h(SE),generatedAt:Ja});c({schemaVersion:w("openpond.datasetArtifactRegistry.v1"),manifest:Sp,profileId:ia,storageRoot:o().trim().min(1).max(4e3),relativeManifestPath:Z0,available:C(),unavailableReason:o().trim().min(1).max(2e3).nullable(),verifiedAt:Ja.nullable(),createdAt:Ja,updatedAt:Ja});c({split:So.nullable().default(null),cursor:o().trim().min(1).max(2e3).nullable().default(null),limit:d().int().min(1).max(100).default(25),columns:h(o().trim().min(1).max(500)).max(100).default([])});c({schemaVersion:w("openpond.datasetRowPage.v1"),tasksetId:ia,tasksetRevision:d().int().positive(),artifactHash:ho,split:So.nullable(),rows:h(fe(o(),Se())).max(100),nextCursor:o().max(2e3).nullable(),totalRows:d().int().nonnegative(),returnedRows:d().int().nonnegative()});const xE=c({schemaVersion:w("openpond.datasetStorageSettings.v1"),datasetStorePath:o().trim().min(1).max(4e3),updatedAt:Ja}),kE=c({id:ia,label:o().trim().min(1).max(500),path:o().trim().min(1).max(4e3),datasetStorePath:o().trim().min(1).max(4e3),kind:b(["local","network","removable","cache"]),configured:C(),mounted:C(),writable:C(),totalBytes:d().int().nonnegative().nullable(),freeBytes:d().int().nonnegative().nullable()});c({schemaVersion:w("openpond.datasetStorageState.v1"),settings:xE,storageRoots:h(kE)});c({datasetStorePath:o().trim().min(1).max(4e3)});const sm=o().trim().min(1).max(240),_E=o().trim().min(1),bc=o().trim().min(8).max(256),wE=fe(o(),Se()).default({}),IE=o().trim().min(7).max(256),CE=b(["pending","approved","review","blocked"]),xp=c({id:sm,profileId:sm,title:o().trim().min(1).max(500),sourceHash:bc,occurredAt:_E,licensingStatus:CE,secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),metadata:wE}),RE=xp.extend({schemaVersion:w("openpond.huggingFaceDatasetSource.v1"),kind:w("huggingface"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),revision:IE,configuration:o().trim().min(1).max(500),upstreamSplits:h(o().trim().min(1).max(500)).min(1).max(1e3),gated:C(),private:C(),declaredLicense:o().trim().min(1).max(500).nullable(),sourceFileHashes:h(bc).min(1).max(1e5)}),AE=xp.extend({schemaVersion:w("openpond.uploadedFileDatasetSource.v1"),kind:w("uploaded_file"),originalFileNames:h(o().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:h(o().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:h(bc).min(1).max(1e3),totalBytes:d().int().nonnegative(),parserVersion:o().trim().min(1).max(200)}),PE=xp.extend({schemaVersion:w("openpond.generatedDatasetSource.v1"),kind:w("generated"),generatorId:sm,generatorVersion:o().trim().min(1).max(200),seed:d().int(),generatorHash:bc}),TE=dn("kind",[RE,AE,PE]),je=o().trim().min(1).max(240),Ve=o().regex(/^[a-f0-9]{64}$/),Nt=o().datetime({offset:!0}),it=c({id:je,contentHash:Ve}).strict(),Jo=it.extend({revision:d().int().positive()}).strict(),EE=c({id:je,purpose:o().trim().min(1).max(500),audience:b(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:C(),ttlSeconds:d().int().positive().max(86400),scopes:h(o().trim().min(1).max(500)).max(100).default([])}).strict(),ME=c({declarationId:je,leaseRef:o().trim().min(8).max(1e3),audience:EE.shape.audience,expiresAt:Nt}).strict(),jE=c({schemaVersion:w("openpond.harnessActionBinding.v1"),actionId:je,modelToolName:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(1e3),inputSchema:fe(o(),Se()),actionSchemaHash:Ve,agentRelease:it,implementationHash:Ve,runtimeBindingId:je,capabilityReceiptHash:Ve,sideEffect:b(["read","write"]),studentVisible:C(),timeoutMs:d().int().positive().max(36e5),episodeArgumentBindings:h(c({argument:je,source:w("case_id")}).strict()).max(20).default([])}).strict(),Ue=o().trim().min(1).max(240),Jt=o().trim().min(1),go=o().trim().min(8).max(256),vc=o().trim().regex(/^[a-f0-9]{64}$/),J0=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Rn=fe(o(),Se()).default({}),$n=Ue.nullable();function li(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function OE(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}const Zr=So,NE=b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),Y0=b(["general","benchmark"]),X0=c({schemaVersion:w("openpond.tasksetBenchmark.v1"),definitionId:Ue,releaseId:Ue,releaseHash:vc,managedReleasePath:o().trim().min(1).max(1e3).refine(li,"Benchmark release paths must remain relative."),adaptationSplit:Zr,evaluationSplit:Zr,primaryMetric:b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:b(["none","non_regression","all_pass"]),source:b(["builtin","imported"]),metadata:Rn}),Q0=c({schemaVersion:w("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:Ue,releaseHash:vc,publishedAt:Jt,metadata:Rn}),$E=b(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),DE=b(["defaults","customize"]),LE=b(["automated","manual"]),ey=b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),En=o().trim().max(1e5),ty=dn("kind",[c({kind:w("demonstrations"),behavior:En,examples:h(c({id:Ue,prompt:En,response:En})).max(1e3).default([])}),c({kind:w("preferences"),preference:En,pairs:h(c({id:Ue,prompt:En,chosen:En,rejected:En,rationale:En})).max(1e3).default([])}),c({kind:w("verifiable_reward"),task:En,rules:h(c({id:Ue,points:d().finite(),condition:En})).max(1e3).default([]),otherwisePoints:d().finite().default(0)}),c({kind:w("rubric"),task:En,criteria:h(c({id:Ue,label:o().trim().max(500),description:En})).max(1e3).default([]),positiveExample:En,negativeExample:En,boundaryExample:En})]),zE=c({status:b(["pending","granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session"]),grantedBy:$n,grantedAt:Jt.nullable(),purpose:w("task_authoring_and_evaluation")}),ny=c({schemaVersion:w("openpond.trainingSource.v1"),id:Ue,profileId:Ue,sessionId:Ue,turnIds:h(Ue).max(1e3).default([]),workspaceId:$n,sourceHash:go,clusterKey:Ue,title:o().trim().min(1).max(500),occurredAt:Jt,consent:zE,connectedAppIds:h(Ue).max(100).default([]),secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),licensingStatus:b(["pending","approved","review","blocked"]),metadata:Rn}),ay=Cn([ny,TE]);c({schemaVersion:w("openpond.trainingSourceEstimate.v1"),sessionId:Ue,messageCount:d().int().nonnegative(),estimatedTokens:d().int().nonnegative(),textBytes:d().int().nonnegative()});c({query:o().max(500).default(""),offset:d().int().nonnegative().default(0),limit:d().int().min(1).max(100).default(20),candidates:h(c({sessionId:Ue,title:o().trim().min(1).max(500),updatedAt:Jt})).max(500).default([])});const UE=c({sessionId:Ue,title:o().trim().min(1).max(500),updatedAt:Jt,snippet:o().max(2e3).nullable()});c({schemaVersion:w("openpond.trainingChatSearchResult.v1"),query:o(),offset:d().int().nonnegative(),limit:d().int().positive(),total:d().int().nonnegative(),hasMore:C(),indexedChats:d().int().nonnegative(),totalChats:d().int().nonnegative(),indexing:C(),entries:h(UE)});const kp=c({policyVisibleFields:h(Ue).max(1e3).default([]),privilegedFields:h(Ue).max(1e3).default([]),hiddenGraderRefs:h(Ue).max(100).default([]),connectedAppScopes:h(Ue).max(100).default([])}),HE=c({id:Ue,sourceRefId:Ue,artifactRef:o().trim().min(1).max(4e3).refine(li,"Task asset references must be safe relative paths."),fileName:o().trim().min(1).max(500).refine(OE,"Task asset file names must not contain path separators."),mediaType:o().trim().min(1).max(200),sha256:vc,sizeBytes:d().int().nonnegative().max(25e7),split:Zr,metadata:Rn}),qE=c({path:o().trim().min(1).max(1e3).refine(li,"Required output paths must stay inside the Work output directory."),mediaType:o().trim().min(1).max(200),schemaRef:Ue.nullable().optional(),maxBytes:d().int().positive().max(1e7).optional(),metadata:Rn}),oy=c({schemaVersion:w("openpond.taskData.v1"),id:Ue,clusterKey:Ue,split:Zr,input:fe(o(),Se()),expectedOutput:fe(o(),Se()).nullable(),policyVisibleContext:fe(o(),Se()).default({}),privilegedContextRef:$n,sourceRefs:h(Ue).min(1).max(100),assets:h(HE).max(1e3).optional(),resourceRefs:h(Ue).max(1e3).optional(),requiredOutputs:h(qE).max(100).optional(),tags:h(Ue).max(100).default([]),metadata:Rn}),BE=c({id:Ue,kind:b(["file","catalog","configuration","code_module"]),path:o().trim().min(1).max(1e3).refine(li,"Environment resource paths must remain relative."),mediaType:o().trim().min(1).max(200).nullable().optional(),visibility:b(["policy_visible","policy_hidden","privileged"]),required:C(),metadata:Rn}),ci=c({id:Ue,taskId:$n,sourceRefs:h(Ue).min(1).max(100),artifactRef:Ue,approved:C(),confidence:d().min(0).max(1),metadata:Rn}),ry=ci.extend({kind:w("demonstration"),prompt:o().max(1e5).nullable().default(null),response:o().max(2e5).nullable().default(null)}),iy=ci.extend({kind:w("preference"),prompt:o().max(1e5),chosen:o().max(2e5),rejected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),sy=ci.extend({kind:w("correction"),original:o().max(2e5),corrected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),ly=ci.extend({kind:w("feedback"),feedback:o().max(1e5),polarity:b(["positive","negative","mixed","neutral"])}),cy=ci.extend({kind:w("reward"),task:o().max(1e5),rules:h(c({id:Ue,points:d().finite(),condition:o().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:d().finite(),executable:C()}),dy=ci.extend({kind:w("label"),labelKind:w("rubric"),task:o().max(1e5),criteria:h(c({id:Ue,label:o().trim().min(1).max(500),description:o().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:c({positive:o().trim().min(1).max(2e5),negative:o().trim().min(1).max(2e5),boundary:o().trim().min(1).max(2e5)})});dn("kind",[ry,iy,sy,ly,cy,dy]);const uy=c({demonstrations:h(ry).max(1e5).default([]),preferences:h(iy).max(1e5).default([]),corrections:h(sy).max(1e5).default([]),feedback:h(ly).max(1e5).default([]),rewards:h(cy).max(1e5).default([]),labels:h(dy).max(1e5).default([])}),my=c({protocolVersion:w("openpond.taskEnvironment.v1"),kind:b(["chat","agent","program","stateful_harness","work"]),entrypoint:o().trim().min(1).max(1e3),stateful:C(),deterministicSeeds:C(),toolNames:h(Ue).max(200).default([]),actionBindings:h(jE).max(200).optional(),lifecycle:h(b(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:d().int().positive().max(36e5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),resources:h(BE).max(1e4).optional(),metadata:Rn}),_p=c({schemaVersion:w("openpond.tasksetCapabilities.v1"),taskKind:b(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:h(b(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:h(b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:h(b(["none","exact","deterministic","model_judge","human"])),requiresTools:C(),requiresState:C(),requiresPrivilegedGrading:C(),environmentPlacements:h(b(["local","remote","colocated","provider_native"])),exportable:C(),portabilityBlockers:h(o().trim().min(1).max(2e3)).default([])}),py=c({schemaVersion:w("openpond.tasksetMetricPolicy.v1"),primaryMetric:Ue,aggregation:b(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:b(["zero","exclude"]),customAggregator:c({module:o().trim().min(1).max(1e3).refine(li,"Custom metric modules must use a safe relative path."),exportName:J0,contentHash:vc,timeoutMs:d().int().positive().max(3e5),networkPolicy:w("none")}).nullable()}).superRefine((e,t)=>{e.aggregation==="custom"&&!e.customAggregator&&t.addIssue({code:"custom",message:"Custom metric aggregation requires a content-hashed module.",path:["customAggregator"]}),e.aggregation!=="custom"&&e.customAggregator&&t.addIssue({code:"custom",message:"Built-in metric aggregation cannot include a custom module.",path:["customAggregator"]})}),fy=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),yc=c({id:Ue,version:o().trim().min(1).max(100),label:o().trim().min(1).max(500),weight:d().min(0).max(1e3).default(1),hardGate:C().default(!1),rewardEligible:C().default(!1),privileged:C().default(!1),metadata:Rn}),FE=yc.extend({kind:b(["content","schema","file","diff","test","runtime_event","state"]),config:fe(o(),Se())}),VE=yc.extend({kind:w("model_judge"),rubric:o().trim().min(1).max(5e4),judge:cn,calibrationFixtureRefs:h(Ue).min(1).max(500),calibrationStatus:b(["pending","passed","failed"]),temperature:d().min(0).max(2).default(0)}),WE=yc.extend({kind:w("human"),rubric:o().trim().min(1).max(5e4),reviewerRole:o().trim().min(1).max(500)}),KE=yc.extend({kind:w("custom_verifier"),module:o().trim().min(1).max(1e3).refine(li,"Custom verifier modules must use a safe relative path."),exportName:J0,timeoutMs:d().int().positive().max(3e5),networkPolicy:w("none")}),wp=Cn([FE,VE,WE,KE]),Ip=b(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),hy=c({id:Ue,taskId:Ue,label:Ip,output:fe(o(),Se()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:C(),expectedRewardEligible:C(),metadata:Rn}),GE=c({id:Ue,taskIndex:d().int().nonnegative(),label:Ip,output:fe(o(),Se()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:C(),expectedRewardEligible:C(),metadata:Rn}),ZE=c({path:o().trim().min(1).max(1e3),role:b(["environment","verifier","fixture"]),content:o().max(25e4)}),JE=c({schemaVersion:w("openpond.taskAttempt.v1"),id:Ue,tasksetId:Ue,taskId:Ue,split:Zr,attempt:d().int().nonnegative(),seed:d().int(),modelRef:cn.nullable(),startedAt:Jt,completedAt:Jt,output:fe(o(),Se()),runtimeEventRefs:h(Ue).max(1e4).default([]),artifactRefs:h(Ue).max(1e4).default([]),privilegedOutcomeRef:$n,infrastructureError:o().trim().min(1).max(1e4).nullable(),costUsd:d().nonnegative().nullable(),latencyMs:d().int().nonnegative(),userInterventions:d().int().nonnegative().default(0),metadata:Rn}),YE=c({schemaVersion:w("openpond.taskAttemptArtifact.v1"),id:Ue,tasksetId:Ue,taskId:Ue,attemptId:Ue,kind:b(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:o().trim().min(1).max(4e3),mediaType:o().trim().min(1).max(200).nullable().optional(),sha256:go,sizeBytes:d().int().nonnegative(),createdAt:Jt,metadata:Rn}),XE=c({graderId:Ue,graderVersion:o().trim().min(1).max(100),score:d().min(0).max(1),passed:C(),hardGate:C(),rewardEligible:C(),feedback:o().trim().max(2e4).nullable(),evidenceRefs:h(Ue).max(1e4).default([]),judge:cn.nullable().optional().default(null),calibrationStatus:b(["not_applicable","pending","passed","failed"])}),QE=c({schemaVersion:w("openpond.gradeResult.v1"),id:Ue,attemptId:Ue,graderSetHash:go,score:d().min(0).max(1).nullable(),passed:C(),components:h(XE).min(1).max(1e3),failureClass:fy.nullable(),feedback:h(o().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:C(),createdAt:Jt});b(["stable_hash_top_n","rft_easy_curriculum_v1"]);const eM=c({schemaVersion:w("openpond.graderAuditReport.v1"),id:Ue,tasksetId:Ue,tasksetHash:go,fixtureRefs:h(Ue).min(1).max(1e5),gradeRefs:h(Ue).min(1).max(1e5),passed:C(),hackingChecksPassed:C(),leakageChecksPassed:C(),infrastructureSafetyPassed:C(),failures:h(c({fixtureId:Ue,label:Ip,gradeId:Ue,reason:o().trim().min(1).max(5e3)})).max(1e5),createdAt:Jt}),gy=c({primaryMethod:b(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:c({method:w("sft"),purpose:w("trajectory_bootstrap"),demonstrationRefs:h(Ue).min(1).max(1e5),limitations:h(o().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),by=b(["taskset_not_ready","demonstrations_missing","preference_pairs_missing","preference_pairs_invalid","executable_reward_missing","reward_not_calibrated","reward_model_missing","value_model_required","frozen_eval_missing"]),tM=c({method:b(["sft","dpo","grpo","ppo"]),status:b(["recommended","compatible","needs_dataset_work"]),reasonCodes:h(by).default([]),reasons:h(o().trim().min(1).max(5e3)).default([])}),vy=c({schemaVersion:w("openpond.tasksetReadiness.v1"),tasksetId:Ue,tasksetHash:go,ready:C(),recommendedMethod:b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:gy.nullable().default(null),methodReadiness:h(tM).default([]),compatibleDestinationClasses:h(b(["export","custom","hosted_managed"])),blockers:h(c({code:Ue,message:o().trim().min(1).max(5e3),path:o().trim().max(2e3).nullable()})).default([]),warnings:h(o().trim().min(1).max(5e3)).default([]),generatedAt:Jt}),nM=c({schemaVersion:w("openpond.capabilityDiagnosis.v1"),summary:o().trim().min(1).max(1e4),stableBehavior:h(o().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:h(o().trim().min(1).max(5e3)).max(100).default([]),requiredContext:h(o().trim().min(1).max(5e3)).max(100).default([]),requiredTools:h(Ue).max(100).default([]),intervention:K0,trainingEligible:C(),rationale:h(o().trim().min(1).max(5e3)).min(1).max(100),confidence:d().min(0).max(1)}),aM=c({id:Ue,sourceId:Ue,sourceTurnId:$n,split:Zr,origin:b(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:o().trim().min(1).max(1e5),expectedOutputText:o().trim().min(1).max(2e5).nullable(),rationale:o().trim().min(1).max(5e3)}),yy=c({attempt:d().int().positive(),summary:o().trim().min(1).max(5e3),createdAt:Jt}),oM=c({schemaVersion:w("openpond.taskAuthoringProvenance.v1"),model:cn.nullable(),modelConfig:Rn,skillHash:go,promptTemplateVersion:o().trim().min(1).max(200),buildIntent:ey.default("demonstrations"),buildSpecification:ty.nullable().default(null),evidenceHashes:h(go).max(1e5),tasksetSdkVersion:o().trim().min(1).max(100),sourceCommit:o().trim().min(1).max(256).nullable(),repairHistory:h(yy).max(1e3),createdAt:Jt}),Eh=c({schemaVersion:w("openpond.taskset.v1"),id:Ue,revision:d().int().positive().default(1),profileId:Ue,profileRelease:Jo.nullable().optional(),createImproveRunId:$n.default(null),name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),purpose:Y0.default("general"),benchmark:X0.nullable().default(null),preferenceComparison:Q0.nullable().default(null),status:NE,sourceRefs:h(ay).min(1).max(1e5),datasetArtifact:Sp.nullable().optional(),policy:kp,environment:my,capabilities:_p,metrics:py.optional(),tasks:h(oy).max(1e6),graders:h(wp).min(1).max(1e3),graderFixtures:h(hy).min(1).max(1e5),learningSignals:uy,authoringProvenance:oM,readiness:vy.nullable(),contentHash:go,createdAt:Jt,updatedAt:Jt,metadata:Rn}).superRefine((e,t)=>{e.purpose==="benchmark"&&!e.benchmark&&t.addIssue({code:"custom",message:"Benchmark Tasksets require an immutable benchmark binding.",path:["benchmark"]}),e.purpose!=="benchmark"&&e.benchmark&&t.addIssue({code:"custom",message:"Only benchmark Tasksets may carry a benchmark binding.",path:["benchmark"]}),e.datasetArtifact&&e.tasks.length>0&&t.addIssue({code:"custom",message:"Artifact-backed Tasksets may not duplicate canonical rows inline.",path:["tasks"]}),!e.datasetArtifact&&e.tasks.length===0&&t.addIssue({code:"custom",message:"A Taskset requires inline tasks or a Dataset artifact manifest.",path:["tasks"]})}),rM=c({schemaVersion:w("openpond.taskDesignProposal.v1"),id:Ue,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),diagnosis:nM.default({schemaVersion:"openpond.capabilityDiagnosis.v1",summary:"Reproduce the selected approved behavior.",stableBehavior:[],changingKnowledge:[],requiredContext:[],requiredTools:[],intervention:"sft",trainingEligible:!0,rationale:["The selected examples were supplied as demonstrations."],confidence:.5}),taskKind:_p.shape.taskKind,sourceIds:h(Ue).min(1).max(1e5),assumptions:h(o().trim().min(1).max(5e3)).max(1e3),successCriteria:h(o().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:h(wp).max(1e3).default([]),graderFixtures:h(GE).max(1e5).default([]),generatedFiles:h(ZE).max(1e3).default([]),proposedExamples:h(aM).max(1e5).default([]),proposedMethod:vy.shape.recommendedMethod,trainingPath:gy.nullable().default(null),policy:kp,warnings:h(o().trim().min(1).max(5e3)).default([]),createdAt:Jt}),iM=5;function kV(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,iM).join(" ")}const Ds=c({schemaVersion:w("openpond.baseModelPreference.v1"),modelId:Ue,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:$n,source:b(["managed","local","builtin"])}),sM=c({schemaVersion:w("openpond.taskCreationRequest.v1"),id:Ue,profileId:Ue,surface:$E,mode:DE,entryMode:LE.default("manual"),resourceIntent:b(["workproduct","dataset"]).default("workproduct"),buildIntent:ey.default("demonstrations"),buildSpecification:ty.nullable().default(null),objective:o().trim().min(1).max(2e4).nullable(),methodHint:b(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:Ue.nullable().default(null),preferredBaseModel:Ds.nullable().default(null),sourceIds:h(Ue).max(1e5),candidateId:$n,analysisModel:cn.nullable(),analysisReasoningEffort:pc.nullable().default(null),createImproveRunId:$n.default(null),targetIntent:c({kind:b(["agent","skill","extension","model","configuration"]).nullable(),id:$n,displayName:o().trim().min(1).max(500).nullable(),operation:b(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:c({status:b(["not_required","pending","approved","declined"]),content:w("raw_excerpts"),sourceIds:h(Ue).max(1e5),providerModel:cn.nullable(),approvalId:$n,approvedAt:Jt.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:Jt}),Sy=c({schemaVersion:w("openpond.taskCreationSnapshot.v1"),id:Ue,request:sM,state:b(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:rM.nullable(),materializedTasksetId:$n,disclosureApprovalId:$n,materializationApprovalId:$n,blockingQuestions:h(c({id:Ue,kind:b(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:o().trim().min(1).max(5e3),answer:o().trim().min(1).max(2e4).nullable()})).default([]),transcript:h(c({id:Ue,role:b(["user","assistant","system","tool"]),text:o().max(1e5),createdAt:Jt})).max(1e4).default([]),repairHistory:h(yy).max(1e3).default([]),blockedReason:o().trim().min(1).max(1e4).nullable(),createdAt:Jt,updatedAt:Jt});c({schemaVersion:w("openpond.taskCreationTranscript.v1"),creationId:Ue,profileId:Ue,messages:Sy.shape.transcript,updatedAt:Jt});function lM(e){return e.schemaVersion==="openpond.trainingSource.v1"}const us=o().trim().min(1).max(240),Mh=o().trim().min(1),cM=o().trim().min(8).max(256),dM=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),uM=fe(o(),Se()).default({});function jh(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const mM=oy.extend({sourceRefs:h(us).max(100).default([])}),pM=b(["draft","validating","needs_review","published"]),fM=c({enabled:C(),candidateCount:d().int().min(2).max(4),minimumSamples:d().int().min(1).max(1e4).default(100),allowTies:C(),allowRejectAll:C(),rubric:o().trim().max(5e4),criteria:h(c({id:us,label:o().trim().min(1).max(500),description:o().trim().max(1e4),weight:d().nonnegative().max(1e3)})).max(100)}),hM=c({mode:b(["text","structured_json","artifacts"]),jsonSchema:fe(o(),Se()).nullable(),renderer:c({module:o().trim().min(1).max(1e3).refine(jh,"Renderer modules must use a safe relative path."),exportName:dM,configRef:o().trim().min(1).max(1e3).refine(jh,"Renderer configuration must use a safe relative path.").nullable().default(null)}).nullable()}).superRefine((e,t)=>{e.mode==="structured_json"&&!e.jsonSchema&&t.addIssue({code:"custom",message:"Structured JSON output requires a JSON Schema.",path:["jsonSchema"]}),e.mode==="text"&&e.renderer&&t.addIssue({code:"custom",message:"Text output cannot configure an artifact renderer.",path:["renderer"]})}),gM=c({schemaVersion:w("openpond.tasksetDraft.v1"),id:us,revision:d().int().positive(),profileId:us,name:o().trim().max(500),objective:o().trim().max(2e4),purpose:Y0.default("general"),benchmark:X0.nullable().default(null),preferenceComparison:Q0.nullable().default(null),status:pM,sourceRefs:h(ay).max(1e5).default([]),datasetArtifact:Sp.nullable().optional(),policy:kp,environment:my,output:hM.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:_p,metrics:py,review:fM,tasks:h(mM).max(1e6).default([]),graders:h(wp).max(1e3).default([]),graderFixtures:h(hy).max(1e5).default([]),learningSignals:uy,publishedTasksetRef:c({id:us,revision:d().int().positive(),contentHash:cM}).nullable(),createdAt:Mh,updatedAt:Mh,metadata:uM}).superRefine((e,t)=>{e.purpose==="benchmark"&&!e.benchmark&&t.addIssue({code:"custom",message:"Benchmark drafts require an immutable benchmark binding.",path:["benchmark"]}),e.purpose!=="benchmark"&&e.benchmark&&t.addIssue({code:"custom",message:"Only benchmark drafts may carry a benchmark binding.",path:["benchmark"]}),e.datasetArtifact&&e.tasks.length>0&&t.addIssue({code:"custom",message:"Artifact-backed drafts may not duplicate canonical rows inline.",path:["tasks"]}),e.status==="published"&&!e.publishedTasksetRef&&t.addIssue({code:"custom",message:"Published drafts require an immutable Taskset reference.",path:["publishedTasksetRef"]})}),Dr=o().trim().min(1).max(240),Tl=o().trim().min(1),lm=o().trim().min(8).max(256),xy=fe(o(),Se()).default({}),bM=b(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),ky=c({schemaVersion:w("openpond.huggingFaceDatasetLocator.v1"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),requestedRevision:o().trim().min(1).max(256).nullable()}),vM=c({path:o().trim().min(1).max(1e3),logicalType:o().trim().min(1).max(500),nullable:C(),sampleValues:h(Se()).max(5)}),yM=c({configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),rowCount:d().int().nonnegative().nullable(),sizeBytes:d().int().nonnegative().nullable()}),SM=c({schemaVersion:w("openpond.huggingFaceDatasetInspection.v1"),id:Dr,locator:ky,resolvedRevision:o().trim().min(7).max(256),title:o().trim().min(1).max(500),description:o().max(2e4).nullable(),declaredLicense:o().trim().min(1).max(500).nullable(),gated:C(),private:C(),configurations:h(o().trim().min(1).max(500)).min(1).max(1e3),splits:h(yM).min(1).max(1e4),columns:h(vM).min(1).max(1e4),previewRows:h(fe(o(),Se())).max(25),sourceFiles:h(c({path:o().trim().min(1).max(2e3),configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),revision:o().trim().min(7).max(256),sizeBytes:d().int().nonnegative().nullable(),contentHash:lm.nullable()})).max(1e5),inspectedAt:Tl,metadata:xy}),xM=b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),kM=c({sourcePath:o().trim().min(1).max(1e3),target:xM,transform:b(["identity","string","json","messages","numeric","math_final_answer"]),policy:b(["visible","privileged","metadata"]),required:C()}),_y=c({schemaVersion:w("openpond.datasetImportMapping.v1"),sourceSchemaHash:lm,configuration:o().trim().min(1).max(500),upstreamSplits:h(o().trim().min(1).max(500)).min(1).max(1e3),preset:b(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:h(kM).min(1).max(1e4),nullPolicy:b(["reject","drop","preserve"]),invalidRowPolicy:b(["reject_import","drop_with_receipt"]),splitPolicy:c({seed:d().int(),assignments:fe(o(),So),validationPercent:d().min(0).max(100),frozenEvalPercent:d().min(0).max(100)}),importerVersion:o().trim().min(1).max(200),mappingHash:lm}),_M=c({phase:b(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:d().int().nonnegative(),totalBytes:d().int().nonnegative().nullable(),completedRows:d().int().nonnegative(),totalRows:d().int().nonnegative().nullable(),message:o().trim().min(1).max(2e3).nullable()}),wM=c({schemaVersion:w("openpond.datasetImportJob.v1"),id:Dr,profileId:Dr,sourceKind:b(["huggingface","uploaded_file"]),status:bM,locator:ky.nullable(),inspection:SM.nullable(),mapping:_y.nullable(),progress:_M,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),tasksetId:Dr.nullable(),tasksetRevision:d().int().positive().nullable(),artifactId:Dr.nullable(),error:o().trim().min(1).max(2e4).nullable(),cancellationRequested:C(),createdAt:Tl,updatedAt:Tl,completedAt:Tl.nullable(),metadata:xy});c({profileId:Dr,url:o().trim().min(1).max(2e3)});c({name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),mapping:_y,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),licenseApproved:C().default(!1)});var Vt=o().trim().min(1).max(500),Jr=o().regex(/^[a-f0-9]{64}$/),ya=o().datetime({offset:!0}),Fl=c({id:Vt,contentHash:Jr}).strict(),IM=Fl.extend({revision:d().int().positive()}).strict(),Sc=c({schemaVersion:w("openpond.baseModelPreference.v1"),modelId:Vt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:Vt.nullable(),source:b(["managed","local","builtin"])}).strict(),wy=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),CM=c({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:wy,parameterization:b(["lora","full"])}).catchall(Se()),Cp=c({tasksetRef:IM.nullable().default(null),tasksetRelease:Fl.nullable().default(null),harnessRelease:Fl.nullable().default(null),baseModel:Sc.nullable().default(null),method:wy.nullable().default(null),destinationId:Vt.nullable().default(null),managedRolloutPlacement:b(["local","remote"]).default("remote"),runPreset:b(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:CM.nullable().default(null),preferredMaximumSpendUsd:d().nonnegative().nullable().default(null),preferredRetentionDays:d().int().nonnegative().nullable().default(null)}).strict(),RM=c({schemaVersion:w("openpond.hostedModelProjectLink.v1"),teamId:Vt,projectId:Vt,portableProjectId:Vt,revision:d().int().positive(),etag:Jr,syncedSourceRevision:d().int().positive(),syncedAt:ya,tasksets:h(c({localTasksetId:Vt,releaseId:Vt,releaseRevision:d().int().positive(),releaseHash:Jr,hostedTasksetId:Vt,syncedAt:ya}).strict()).max(1e4).default([])}).strict(),AM=c({localTasksetId:Vt,releaseId:Vt,releaseRevision:d().int().positive(),releaseHash:Jr,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Vt.nullable().default(null),lastAttemptAt:ya,syncedAt:ya.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict(),PM=c({schemaVersion:w("openpond.modelProject.v2"),id:Vt,profileId:Vt,revision:d().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Sc.nullable(),defaultDestinationId:Vt.nullable(),trainingSetup:Cp,hosted:RM.nullable().default(null),tasksetSyncs:h(AM).max(1e4).default([]),createdAt:ya,updatedAt:ya}).strict();c({schemaVersion:w("openpond.hostedModelProjectSync.v2"),portableProjectId:Vt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Sc.nullable(),defaultDestinationId:Vt.nullable(),trainingSetup:Cp,sourceRevision:d().int().positive(),sourceUpdatedAt:ya,expectedEtag:Jr.nullable().default(null)}).strict();var TM=c({id:Vt,teamId:Vt,portableProjectId:Vt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Sc.nullable(),defaultDestinationId:Vt.nullable(),trainingSetup:Cp,sourceRevision:d().int().positive(),sourceUpdatedAt:ya,revision:d().int().positive(),etag:Jr,createdAt:ya,updatedAt:ya}).strict(),EM=c({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Fl,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:ya}).strict();c({project:TM,resources:h(EM).max(1e4),jobCount:d().int().nonnegative(),latestJobIds:h(Vt).max(100)}).strict();c({schemaVersion:w("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:C().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:fe(o(),Se()).default({})}).strict();const lo=je.nullable(),Fa=d().int().nonnegative(),MM=o().regex(/^[a-f0-9]{40}$/),jM=c({name:o().trim().min(1).max(160),startedAt:Nt,completedAt:Nt,durationMs:d().nonnegative(),clock:b(["monotonic","provider","wall"]),outcome:b(["succeeded","failed","cancelled"])}).strict(),OM=c({schemaVersion:w("openpond.correlatedTelemetryReceipt.v1"),stage:b(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:lo,modelVersionId:lo,policyVersion:Fa.nullable(),taskId:lo,rolloutGroupId:lo,providerResourceId:lo,deploymentId:lo,inferenceRequestId:lo}).strict(),spans:h(jM).max(1e4),usage:c({promptTokens:Fa.nullable(),generatedTokens:Fa.nullable(),gpuSeconds:d().nonnegative().nullable(),workerActiveSeconds:d().nonnegative().nullable(),optimizerSteps:Fa.nullable(),rolloutGroups:Fa.nullable(),successfulTrajectories:Fa.nullable(),failedTrajectories:Fa.nullable(),peakGpuMemoryBytes:Fa.nullable(),peakGpuUtilizationPercent:d().min(0).max(100).nullable()}).strict(),resource:c({provider:je,resourceIds:h(je).max(1e3),gpuType:o().trim().min(1).max(300).nullable(),gpuCount:Fa.nullable(),baseProfileId:lo,baseRepository:o().trim().min(1).max(512).nullable(),baseRevision:MM.nullable(),adapterContentHash:Ve.nullable()}).strict(),cost:c({currency:w("USD"),providerReportedUsd:d().nonnegative().nullable(),quotedHourlyUsd:d().nonnegative().nullable(),estimatedUsd:d().nonnegative().nullable(),methodologyVersion:o().trim().min(1).max(160),pricingInputs:fe(o().trim().min(1).max(160),d().finite()),unitEstimates:fe(o().trim().min(1).max(160),d().nonnegative())}).strict(),recordedAt:Nt,contentHash:Ve}).strict(),NM=b(["base_reference","lora_adapter"]),Iy=c({baseModel:c({source:w("huggingface"),repoId:je,revision:o().regex(/^[a-f0-9]{40}$/),configHash:Ve,tokenizerHash:Ve,licenseId:je,gated:C()}).strict(),processor:c({repository:je,revision:o().regex(/^[a-f0-9]{40}$/),configHash:Ve}).strict()}).strict().superRefine((e,t)=>{(e.baseModel.repoId!==e.processor.repository||e.baseModel.revision!==e.processor.revision)&&t.addIssue({code:"custom",path:["processor"],message:"Reward Model processor must match the pinned scorer base model."})}),$M=c({schemaVersion:w("openpond.modelVersion.v1"),id:je,modelId:je,profileId:je,version:d().int().nonnegative(),kind:NM,status:b(["available","failed"]),baseModel:Ds,taskset:Jo,releaseGraph:c({resolvedBundleHash:Ve,profileRelease:Jo,harnessRelease:it,agentRelease:it.nullable(),grader:c({id:je,contentHash:Ve}).strict()}).strict(),artifactLineageId:je.nullable(),adapterStatus:b(["not_trained","trained"]),createdAt:Nt,contentHash:Ve}).strict().superRefine((e,t)=>{e.kind==="base_reference"&&(e.version!==0||e.adapterStatus!=="not_trained"||e.artifactLineageId!==null)&&t.addIssue({code:"custom",message:"A base-reference Model Version must be version 0 without adapter lineage."}),e.kind==="lora_adapter"&&(e.version===0||e.adapterStatus!=="trained"||!e.artifactLineageId)&&t.addIssue({code:"custom",message:"A LoRA Model Version must be version 1+ with adapter lineage."})}),DM=c({schemaVersion:w("openpond.rewardModelVersion.v1"),id:je,modelId:je,profileId:je,version:d().int().positive(),role:w("reward"),status:b(["available","failed"]),scope:b(["synthetic_smoke","human_preference"]),baseModel:Ds,runtime:Iy.nullable().default(null),taskset:Jo,preferenceDatasetRelease:it,releaseGraph:c({resolvedBundleHash:Ve,profileRelease:Jo,harnessRelease:it,grader:c({id:je,contentHash:Ve}).strict()}).strict(),artifacts:c({checkpoint:it.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:h(c({path:o().trim().min(1).max(512),sizeBytes:d().int().positive(),sha256:Ve}).strict()).min(4).max(128)}).strict(),adapter:it,scalarHead:it,bucketHead:it.nullable(),processorRelease:it}).strict(),qualificationReport:it.nullable(),createdAt:Nt,contentHash:Ve}).strict(),LM=c({schemaVersion:w("openpond.rewardModelRunReceipt.v1"),provider:je,providerRunId:je,resolvedBundleHash:Ve,finalCheckpoint:it.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:it,scalarHead:it,bucketHead:it.nullable(),processorRelease:it,optimizerEvidence:it,managedExecutionReceipt:it.nullable().default(null),parameterDeltaHash:Ve,cleanup:c({computeReleased:C(),providerTerminalObserved:C()}).strict(),contentHash:Ve}).strict(),zM=UC(e=>{if(!e||typeof e!="object"||Array.isArray(e))return e;const t=e;if(t.tasksetRelease!==void 0)return e;const n=t.taskset;if(!n||typeof n!="object"||Array.isArray(n))return e;const a=n;return typeof a.id!="string"||typeof a.contentHash!="string"?e:{...t,tasksetRelease:{id:a.id,contentHash:a.contentHash}}},c({schemaVersion:w("openpond.rewardModelRun.v1"),id:je,rewardModelId:je,rewardModelVersionId:je.nullable(),profileId:je,role:w("reward"),scope:b(["synthetic_smoke","human_preference"]),status:b(["prepared","running","succeeded","failed","cancelled"]),taskset:Jo,tasksetRelease:it,preferenceDatasetRelease:it,recipeRelease:it,destinationId:je,quote:c({maximumSpendUsd:d().positive(),hourlyCostUsd:d().nonnegative().nullable()}).strict(),managedRunId:je.nullable(),progress:c({completedSteps:d().int().nonnegative(),totalSteps:d().int().positive(),latestLoss:d().finite().nullable()}).strict(),receipt:LM.nullable(),qualificationReport:it.nullable(),accruedSpendUsd:d().nonnegative().nullable(),failureOwner:b(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:Nt,completedAt:Nt.nullable(),updatedAt:Nt}).strict()).superRefine((e,t)=>{e.status==="succeeded"&&(!e.receipt||!e.qualificationReport)&&t.addIssue({code:"custom",message:"A successful Reward Model Run requires a canonical receipt and qualification report."}),e.status!=="succeeded"&&e.rewardModelVersionId!==null&&t.addIssue({code:"custom",message:"Only a successful Reward Model Run can publish a Reward Model Version."})}),UM=c({schemaVersion:w("openpond.modelRunReceipt.v1"),provider:je,providerRunId:je,assignmentHash:Ve,resultHash:Ve,transcriptHash:Ve,traceHash:Ve.nullable(),resolvedBundleHash:Ve,artifactPath:o().trim().min(1).max(2e3),cleanup:c({computeReleased:C(),tunnelClosed:C()}).strict(),telemetry:OM.nullable().default(null),contentHash:Ve}).strict(),Rr=c({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),costUsd:d().nonnegative().nullable()}).strict(),Oh=o().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Rp=c({phase:b(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:je,attemptId:je,sessionId:je.nullable(),turnId:je.nullable(),passed:C(),score:d().min(0).max(1).nullable(),failureClass:fy.nullable(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),latencyMs:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),startedAt:Nt}).strict(),Nh=c({targetTaskCount:d().int().nonnegative(),comparedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),lowerTaskCount:d().int().nonnegative(),higherTaskCount:d().int().nonnegative(),unchangedTaskCount:d().int().nonnegative()}).strict(),Cy=c({target:w("all_tasks_lower"),targetTaskCount:d().int().nonnegative(),comparedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),lowerTaskCount:d().int().nonnegative(),higherTaskCount:d().int().nonnegative(),unchangedTaskCount:d().int().nonnegative(),baselineTokens:d().int().nonnegative(),refinedTokens:d().int().nonnegative(),tokenDelta:d().int(),tokenDeltaPercent:d().finite().nullable(),complete:C(),passed:C(),cohorts:c({adaptation:Nh,heldOut:Nh}).strict()}).strict(),Ap=c({baseline:Rr,adaptation:Rr,candidateAdaptation:Rr,candidate:Rr,refiner:Rr,grader:Rr}).strict(),HM=c({usage:Ap,observedSpendUsd:d().nonnegative(),attempts:h(Rp).max(1e4)}).strict(),qM=c({id:je,contentHash:Ve,artifactPath:o().trim().min(1).max(2e3)}).strict(),BM=c({schemaVersion:w("openpond.modelEvaluationReceipt.v1"),benchmarkId:je,resultManifest:c({id:je,contentHash:Ve,artifactPath:o().trim().min(1).max(2e3)}).strict(),stages:c({baseline:it,adaptation:it,refiner:it,candidateAdaptation:it,candidate:it,comparison:it}).strict(),usage:Ap,quality:c({baselinePassRate:d().min(0).max(1),candidatePassRate:d().min(0).max(1),adaptationBaselinePassRate:d().min(0).max(1),adaptationCandidatePassRate:d().min(0).max(1),adaptationCandidatePassed:C(),heldOutCandidatePassed:C(),passed:C()}).strict(),foregroundTokenDelta:d().int(),foregroundTokenDeltaPercent:d().finite().nullable(),taskEfficiency:Cy.optional(),efficiency:c({grossForegroundTokenSavings:d().int(),overheadTokens:d().int().nonnegative(),firstPassNetTokenSavings:d().int(),breakEvenReuseCount:d().int().nonnegative().nullable(),amortizedTokenSavings:d().int(),amortizedReuseCount:d().int().positive()}).strict(),budget:c({maximumSpendUsd:d().nonnegative(),observedSpendUsd:d().nonnegative(),enforced:C()}).strict(),evidenceSnapshot:it,lineage:c({adaptationEvidenceHash:Ve,refinerInputHash:Ve,refinerOutcomeHash:Ve,validationHash:Ve,applyReceiptHash:Ve,candidateRelease:it,valid:C()}).strict(),invalidReasons:h(o().trim().min(1).max(2e3)).max(100),attempts:h(Rp).max(1e4).default([]),terminalClassification:b(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:o().trim().min(1).max(2e3),commit:Oh,baseCommit:Oh}).strict().nullable(),contentHash:Ve}).strict(),FM=c({schemaVersion:w("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:je,terminalClassification:w("inconclusive"),stopReason:b(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:o().trim().min(1).max(5e3),stoppedAfter:w("refiner"),baselineHarness:it,candidateHarness:it,refiner:c({id:je,contentHash:Ve,outcomeCount:d().int().nonnegative()}).strict(),usage:Ap,budget:c({maximumSpendUsd:d().nonnegative(),observedSpendUsd:d().nonnegative(),enforced:C()}).strict(),evidenceSnapshot:it,attempts:h(Rp).max(1e4),contentHash:Ve}).strict(),VM=c({benchmarkId:je,model:cn,upstreamModel:c({providerId:je,modelId:o().trim().min(1).max(300),revision:o().trim().min(1).max(300),pricing:c({version:o().trim().min(1).max(300),source:o().trim().min(1).max(300),effectiveAt:Nt,inputUsdPerMillionTokens:d().nonnegative(),cachedInputUsdPerMillionTokens:d().nonnegative(),outputUsdPerMillionTokens:d().nonnegative()}).strict().optional()}).strict(),reasoningEffort:o().trim().min(1).max(100).nullable(),seeds:h(d().int()).min(1).max(100),repetitions:d().int().positive().max(20),maximumSpendUsd:d().nonnegative(),attemptPlan:h(c({stage:b(["baseline","adaptation","candidate_adaptation","candidate"]),split:o().trim().min(1).max(100),taskIds:h(je).min(1).max(1e5),attemptCount:d().int().positive()}).strict()).length(4)}).strict(),WM=c({schemaVersion:w("openpond.modelRun.v1"),id:je,modelId:je,modelVersionId:je,profileId:je,kind:b(["rollout_smoke","training","evaluation"]),status:b(["prepared","running","succeeded","failed","cancelled"]),method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:je.nullable(),taskset:Jo,harnessRelease:it.nullable().optional(),quote:c({maximumSpendUsd:d().nonnegative(),hourlyCostUsd:d().nonnegative().nullable()}).strict().nullable(),evaluation:VM.nullable().default(null),evaluationProgress:c({stage:b(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:d().int().nonnegative(),totalAttempts:d().int().positive(),accounting:HM.nullable().default(null),evidenceSnapshot:qM.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:d(),components:fe(o(),d())}).strict().nullable(),receipt:Cn([UM,BM,FM]).nullable(),adapterArtifactLineageId:je.nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:Nt,completedAt:Nt.nullable(),updatedAt:Nt}).strict().superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Model Run requires a canonical receipt."}),e.kind==="evaluation"&&(e.method!==null||e.destinationId!==null||!e.evaluation||e.adapterArtifactLineageId!==null)&&t.addIssue({code:"custom",message:"An evaluation Model Run requires evaluation configuration and cannot claim training method, destination, or adapter lineage."}),e.kind==="evaluation"&&e.receipt&&e.receipt.schemaVersion!=="openpond.modelEvaluationReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelEvaluationStopReceipt.v1"&&t.addIssue({code:"custom",message:"An evaluation Model Run requires an evaluation receipt."}),e.kind!=="evaluation"&&(e.method===null||e.destinationId===null||e.quote===null)&&t.addIssue({code:"custom",message:"A training or rollout Model Run requires method, destination, and quote."}),e.kind==="rollout_smoke"&&e.adapterArtifactLineageId!==null&&t.addIssue({code:"custom",message:"A rollout smoke cannot claim adapter artifacts."})});function _V(e){const t=new Map;for(const R of e.attempts){const A=`${R.phase}\0${R.taskId}`,D=t.get(A);(!D||R.startedAt>D.startedAt||R.startedAt===D.startedAt&&R.attemptId>D.attemptId)&&t.set(A,R)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([R,A,D])=>{const z=new Map(n.filter(N=>N.phase===D).map(N=>[N.taskId,N]));return n.filter(N=>N.phase===A).flatMap(N=>{const x=z.get(N.taskId);return x?[{cohort:R,taskId:N.taskId,baseline:N,refined:x,tokenDelta:x.totalTokens-N.totalTokens}]:[]})}),r=new Set(n.filter(R=>R.phase==="baseline"||R.phase==="adaptation").map(R=>R.taskId)).size,i=e.targetTaskCount??r;if(!Number.isInteger(i)||i<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const s={adaptation:new Set(n.filter(R=>R.phase==="adaptation").map(R=>R.taskId)).size,held_out:new Set(n.filter(R=>R.phase==="baseline").map(R=>R.taskId)).size},l=(R,A)=>({targetTaskCount:A,comparedTaskCount:R.length,passedTaskCount:R.filter(D=>D.tokenDelta<0).length,failedTaskCount:R.filter(D=>D.tokenDelta>=0).length,lowerTaskCount:R.filter(D=>D.tokenDelta<0).length,higherTaskCount:R.filter(D=>D.tokenDelta>0).length,unchangedTaskCount:R.filter(D=>D.tokenDelta===0).length}),p=l(a,i),m=a.reduce((R,A)=>R+A.baseline.totalTokens,0),f=a.reduce((R,A)=>R+A.refined.totalTokens,0),S=f-m,y=a.length===i;return{summary:Cy.parse({target:"all_tasks_lower",...p,baselineTokens:m,refinedTokens:f,tokenDelta:S,tokenDeltaPercent:m>0?S/m*100:null,complete:y,passed:y&&p.passedTaskCount===i,cohorts:{adaptation:l(a.filter(R=>R.cohort==="adaptation"),s.adaptation),heldOut:l(a.filter(R=>R.cohort==="held_out"),s.held_out)}}),pairs:a}}const Na=o().trim().min(1).max(240),va=o().trim().min(8).max(256),Ry=b(["grpo","dapo","gspo-token"]),vs=c({id:Na,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:va}),KM=c({maxRollouts:d().int().positive().max(1e6),maxEnvironmentExecutions:d().int().positive().max(1e6),maxInputTokens:d().int().positive(),maxOutputTokens:d().int().positive(),maxOptimizerSteps:d().int().positive().max(1e6),wallTimeMs:d().int().positive(),maximumCostUsd:d().nonnegative().nullable()}),GM=c({method:w("grpo"),groupSize:d().int().min(2).max(128),normalization:w("group_standardized"),loss:Ry}),Ay=c({method:w("ppo"),valueModel:vs,gamma:d().min(0).max(1),gaeLambda:d().min(0).max(1),policyClip:d().positive().max(1),valueClip:d().positive().max(10),valueLossCoefficient:d().nonnegative().max(10),ppoEpochs:d().int().positive().max(100),minibatchSize:d().int().positive().max(1e5)}),ZM=dn("method",[GM,Ay]),Py=c({rewardModelVersion:c({id:Na,contentHash:va}).strict(),qualificationReport:c({id:Na,contentHash:va}).strict(),checkpoint:c({id:Na,contentHash:va,objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:h(c({path:o().trim().min(1).max(512),sizeBytes:d().int().positive(),sha256:va}).strict()).min(4).max(128)}).strict(),runtime:Iy,processorRelease:c({id:Na,contentHash:va}).strict(),rewardComposerRelease:c({id:Na,contentHash:va}).strict(),executionReceipt:c({id:Na,contentHash:va}).strict()}).strict(),Ty=c({schemaVersion:w("openpond.policyOptimization.v1"),policyModel:vs,referenceModel:vs,dataset:c({tasksetId:Na,tasksetHash:va,split:w("train"),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:d().int(),maxExamples:d().int().positive().max(1e5)}),sampler:c({temperature:d().min(0).max(2),topP:d().min(0).max(1),maxOutputTokens:d().int().positive().max(32768),maxTurns:d().int().positive().max(1e3),concurrency:d().int().positive().max(1e3)}),environment:c({id:Na,version:o().trim().min(1).max(256),toolContractHash:va}),reward:c({graderId:Na,graderHash:va,learnedPreference:Py.nullable().default(null)}),kl:c({coefficient:d().nonnegative().nullable(),referenceConstraint:w("fixed_reference")}),budgets:KM,checkpointEverySteps:d().int().positive(),seed:d().int(),evaluationSplit:w("frozen_eval"),optimizer:ZM}),Me=o().trim().min(1).max(240),kt=o().trim().min(1),pt=o().trim().min(8).max(256),Ls=fe(o(),Se()).default({}),Ey=c({schemaVersion:w("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:b(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:b(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:o().max(2e4).nullable().default(null),contextWindowTokens:d().int().min(128).max(32768).default(1024),maxOutputTokens:d().int().min(1).max(512).default(64),temperature:d().min(0).max(2).default(0),repetitionPenalty:d().min(.5).max(2).default(1.1),noRepeatNgramSize:d().int().min(0).max(10).default(3),compaction:b(["off","when_needed"]).default("when_needed"),keepWarmSeconds:d().int().min(0).max(3600).default(300),updatedAt:kt.nullable().default(null)}),JM=Ey.parse({}),YM=c({schemaVersion:w("openpond.managedAdapterServingProjection.v1"),teamId:Me.nullable().default(null),source:w("sandbox_managed_rl"),sourceRef:Me,canonicalArtifactId:Me.nullable(),canonicalArtifactState:b(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Me.nullable(),canonicalDeploymentState:b(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:b(["pending","imported","ready","failed"]),customerBindingAllowed:C().default(!1),artifactContentHash:pt.nullable().default(null),baseProfileId:Me.nullable().default(null),publishedAt:kt.nullable(),lastSyncedAt:kt,lastError:o().trim().min(1).max(5e3).nullable()});function wV(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function My(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function IV(e){if(e.promotable&&e.frozenEvaluationArtifactId)return{kind:"source_frozen_evaluation",evaluationArtifactId:e.frozenEvaluationArtifactId,canonicalArtifactId:null,canonicalDeploymentId:null};const t=e.managedServing;return t?.source==="sandbox_managed_rl"&&My(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function CV(e){const t=e.managedServing;return t?My(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Pp="openpond.crossSystemOperations.v1",RV="1.0.0",jy="openpond.crossSystemTools.v1",XM=["search_crm","query_billing","search_support","run_python"],QM=b(["train","validation","frozen_eval"]),ej=b(["easy","medium","hard"]),tj=b(["renewal_risk_v2"]);b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:d().int().nonnegative(),split:QM,difficulty:ej,scenarioProfile:tj.optional()});const hu={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},gu={type:"integer",minimum:1,maximum:50,default:25},Oy=[{name:"search_crm",description:"Search synthetic CRM accounts and contacts. Results are scoped, projected, paginated, and budgeted.",parameters:{type:"object",additionalProperties:!1,required:["query","fields","cursor","limit"],properties:{query:{type:"string",minLength:1,maxLength:500},fields:{type:"array",minItems:1,maxItems:12,uniqueItems:!0,items:{type:"string",enum:["account_id","name","aliases","contact_ids","contract_value_usd_cents","renewal_date","tier","active_contract_id","contract_term_months"]}},cursor:hu,limit:gu}}},{name:"query_billing",description:"Query synthetic invoices and payments for explicit account IDs and a bounded date range.",parameters:{type:"object",additionalProperties:!1,required:["account_ids","date_range","status","cursor","limit"],properties:{account_ids:{type:"array",minItems:1,maxItems:50,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:100}},date_range:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",format:"date"},to:{type:"string",format:"date"}}},status:{type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{type:"string",enum:["open","overdue","paid","disputed","scheduled","void"]}},cursor:hu,limit:gu}}},{name:"search_support",description:"Search synthetic support cases for explicit account IDs, severity, and state filters.",parameters:{type:"object",additionalProperties:!1,required:["account_ids","severity","state","cursor","limit"],properties:{account_ids:{type:"array",minItems:1,maxItems:50,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:100}},severity:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{type:"string",enum:["P1","P2","P3","P4"]}},state:{type:"array",minItems:1,maxItems:5,uniqueItems:!0,items:{type:"string",enum:["new","investigating","waiting_customer","resolved","closed"]}},cursor:hu,limit:gu}}},{name:"run_python",description:"Run standard-library-only Python in the persistent synthetic attempt sandbox with strict limits and no network.",parameters:{type:"object",additionalProperties:!1,required:["code"],properties:{code:{type:"string",minLength:1,maxLength:1e4}}}}],zs=mj({schemaVersion:jy,tools:Oy}),nj=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${zs}.`,"Treat every filter as exact. An overdue-only query_billing call returns invoice rows; payment rows are included only when paid is requested.","For cross-system joins, retrieve the bounded projected rows and use run_python for date filtering, set intersection, and arithmetic before answering.","Finish with ANSWER: JSON."].join(" "),aj=15;function oj(e="auto"){return[nj,"LOCAL TOOL PROTOCOL (strict):","Use only the registered functions below. Never invent, rename, or call any other tool.","For one tool call, output exactly one JSON object and no prose:",'{"type":"tool_call","name":"registered_name","arguments":{}}',"Tool results arrive as exactly one JSON object:",'{"type":"tool_result","name":"registered_name","ok":true,"result":{},"error":null}','After one tool result, either call one registered tool again or answer normally. A JSON final may use {"type":"final","content":"..."}.',`Tool choice: ${JSON.stringify(e)}. Maximum tool turns: ${aj}.`,`Registered tool signatures: ${Oy.map(rj).join("; ")}`].join(`
125
- `)}oj();function rj(e){const t=Vl(e.parameters),n=Vl(t.properties),a=Ny(t.required),r=Object.fromEntries(a.map(i=>[i,El(n[i])]));return`${e.name}(${JSON.stringify(r)})`}function El(e){const t=Vl(e),n=cm(t.anyOf);if(n.length)return n.map(El).join("|");const a=cm(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[El(t.items)];if(t.type==="object"){const r=Vl(t.properties),i=Ny(t.required);return Object.fromEntries(i.map(s=>[s,El(r[s])]))}return typeof t.type=="string"?t.type:"unknown"}function Vl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function cm(e){return Array.isArray(e)?e:[]}function Ny(e){return cm(e).filter(t=>typeof t=="string")}const Wl=b(XM),ij=dn("kind",[c({kind:w("model"),turn:d().int().nonnegative(),content:o().max(1e5)}),c({kind:w("tool_call"),turn:d().int().nonnegative(),callId:o().trim().min(1).max(240),name:Wl,arguments:fe(o(),Se())}),c({kind:w("tool_result"),turn:d().int().nonnegative(),callId:o().trim().min(1).max(240),name:Wl,ok:C(),result:Se(),rows:d().int().nonnegative(),bytes:d().int().nonnegative(),durationMs:d().int().nonnegative(),error:o().trim().min(1).max(2e4).nullable()}),c({kind:w("final"),turn:d().int().nonnegative(),content:o().max(1e5)})]),sj=c({schemaVersion:w(Pp),id:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),toolContractHash:w(zs),modelRef:c({providerId:o().trim().min(1),modelId:o().trim().min(1)}).nullable(),status:b(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:h(ij).max(1e3),startedAt:o().trim().min(1),completedAt:o().trim().min(1),infrastructureError:o().trim().min(1).max(2e4).nullable(),metadata:fe(o(),Se()).default({})}),lj=c({schemaVersion:w(Pp),trajectoryId:o().trim().min(1).max(240),outcome:b(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:d().min(0).max(1.15).nullable(),rewardEligible:C(),exactAnswer:C(),components:c({exactAnswer:d().min(0).max(1),efficiency:d().min(0).max(.1),conciseOutput:d().min(0).max(.05)}),metrics:c({toolCalls:d().int().nonnegative(),rowsRead:d().int().nonnegative(),bytesRead:d().int().nonnegative(),consecutiveRetrievalCalls:d().int().nonnegative(),wallTimeMs:d().int().nonnegative(),parseFailures:d().int().nonnegative(),budgetExhausted:C()}),parsedAnswer:Se().nullable(),feedback:h(o().trim().min(1).max(5e3)).max(100)}),cj=c({id:o().trim().min(1).max(240),type:w("function"),function:c({name:Wl,arguments:o().max(2e4)})}),$y=c({role:b(["system","user","assistant","tool"]),content:o().max(2e5).nullable(),tool_call_id:o().trim().min(1).max(240).optional(),tool_calls:h(cj).max(4).optional()});c({schemaVersion:w(Pp),id:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),trajectoryId:o().trim().min(1).max(240),toolContractHash:w(zs),approval:c({status:w("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1)}),messages:h($y).min(3).max(1e3)});const dj=c({tasksetTaskId:o().trim().min(1).max(240),environmentTaskId:o().trim().min(1).max(240),family:b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:o().trim().min(1).max(1e5),finalAnswer:o().trim().min(1).max(2e5),trajectoryId:o().trim().min(1).max(240),trajectoryHash:o().trim().min(8).max(256),toolNames:h(Wl).min(1).max(100),toolCallCount:d().int().positive(),messageCount:d().int().min(3),reward:d().min(0).max(1.15),messages:h($y).min(3).max(1e3)}),uj=c({status:w("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1),previewHash:o().trim().min(8).max(256),trajectoryCount:d().int().positive()});c({schemaVersion:w("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:o().trim().min(1).max(240),tasksetHash:o().trim().min(8).max(256),tasksetRevision:d().int().positive(),previewHash:o().trim().min(8).max(256),toolContractHash:w(zs),status:b(["ready_for_review","approved"]),approval:uj.nullable(),tasks:h(dj).min(1).max(100)});function mj(e){const t=dm(e);let n=2166136261,a=2654435769;for(let r=0;r<t.length;r+=1){const i=t.charCodeAt(r);n=Math.imul(n^i,16777619),a=Math.imul(a^i,2246822507)}return`${jy}:${$h(n)}${$h(a)}`}function dm(e){return Array.isArray(e)?`[${e.map(dm).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${dm(n)}`).join(",")}}`:JSON.stringify(e)}function $h(e){return(e>>>0).toString(16).padStart(8,"0")}const pj=c({schemaVersion:w("openpond.singleTurnPolicyTrajectory.v1"),id:Me,taskId:Me,status:b(["completed","infrastructure_failure"]),promptHash:pt,responseText:o().max(2e6),infrastructureError:o().trim().min(1).max(1e4).nullable(),startedAt:kt,completedAt:kt,metadata:Ls}),fj=c({schemaVersion:w("openpond.ppoTrajectory.v1"),id:Me,taskId:Me,policyModelId:Me,referenceModelId:Me,valueModelId:Me,steps:h(c({index:d().int().nonnegative(),observationHash:pt,actionTokenIds:h(d().int().nonnegative()).min(1),terminated:C(),truncated:C(),reward:d(),policyLogProbability:d(),referenceLogProbability:d(),valuePrediction:d(),return:d(),advantage:d(),mask:d().min(0).max(1)})).min(1).max(1e5),createdAt:kt}),hj=c({schemaVersion:w("openpond.exactAnswerVerifierResult.v1"),outcome:b(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:pt,score:d().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),expectedAnswerHash:pt,extractedAnswer:o().max(2e4).nullable(),feedback:h(o().trim().min(1).max(2e4)).max(1e3)}),gj=c({schemaVersion:w("openpond.rolloutTrajectoryReceipt.v1"),id:Me,jobId:Me,planId:Me,tasksetId:Me,tasksetHash:pt,taskId:Me,split:w("train"),correlationId:Me,provider:Me,providerTrace:c({invocationId:Me,experimentId:Me,rolloutId:Me,runId:Me,rowId:Me}),optimizerMethod:b(["grpo","ppo"]).default("grpo"),evidenceLevels:c({requested:b(["trajectory","aggregate","provider_reported"]),observed:b(["trajectory","aggregate","provider_reported"]),providerReported:b(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:c({rollouts:d().int().nonnegative(),environmentExecutions:d().int().nonnegative(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),optimizerSteps:d().int().nonnegative(),costUsd:d().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:c({id:Me,version:o().trim().min(1).max(256),worldId:Me,worldHash:pt,toolContractHash:pt}),policy:c({modelId:Me,checkpointId:Me.nullable(),completionParametersHash:pt}),status:b(["received","running","succeeded","failed"]),failureClass:b(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:c({eligible:C(),raw:d().min(0).max(1.15).nullable(),normalized:d().min(0).max(1).nullable(),components:fe(o(),d())}),trajectory:Cn([sj,pj,fj]).nullable(),verifier:Cn([lj,hj]).nullable(),providerStatus:fe(o(),Se()).default({}),receivedAt:kt,startedAt:kt.nullable(),completedAt:kt.nullable(),updatedAt:kt}),AV="dataset-exact-answer",PV="dataset-exact-answer-v1",TV="no-tools-v1",xo=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),xc=b(["lora","full"]),ar=b(["openpond_managed"]),bj=c({schemaVersion:w("openpond.sftRecipe.v1"),method:w("sft"),parameterization:w("lora"),baseModel:c({id:Me,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:pt}),dataset:c({trainSplit:w("train"),validationSplit:b(["validation","frozen_eval"]),completionOnly:C(),maxSequenceLength:d().int().positive().max(32768),maxExamples:d().int().positive().max(1e5).default(1e3),selectionStrategy:w("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:d().int().default(17)}),lora:c({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:h(Me).min(1).max(100)}),optimizer:c({learningRate:d().positive(),epochs:d().positive().max(100),maxSteps:d().int().positive().max(1e6),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int()}),resourceLimits:c({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})});c({id:Me,input:fe(o(),Se()),expectedOutput:fe(o(),Se()),tags:h(Me).max(100).default([])});c({id:Me,prompt:o().min(1).max(5e5),chosen:o().min(1).max(5e5),rejected:o().min(1).max(5e5),sourceRefs:h(Me).min(1).max(1e4)});c({id:Me,input:fe(o(),Se()),tags:h(Me).max(100).default([])});c({schemaVersion:w("openpond.rewardModelRecipe.v1"),method:w("reward_model"),parameterization:w("lora_with_scalar_head"),runScope:b(["synthetic_smoke","human_preference"]),baseModel:c({id:Me,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),processorRevision:o().trim().min(1).max(256),chatTemplateHash:pt}).strict(),tasksetRelease:it,preferenceDatasetRelease:it,processorRelease:it,input:c({kind:w("structured_text"),serialization:w("scenario_input_and_candidate_json_v1"),maxCharacters:d().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:c({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:h(Me).min(1).max(100)}).strict(),heads:c({scalar:w("pooled_hidden_state_linear"),bucket:b(["none","three_class"]).default("three_class")}).strict(),loss:c({ranking:w("bradley_terry"),rankingWeight:d().positive(),bucketWeight:d().nonnegative(),tieWeight:d().nonnegative()}).strict(),optimizer:c({learningRate:d().positive(),maxSteps:d().int().positive().max(1e5),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int(),checkpointEverySteps:d().int().positive().max(1e5)}).strict(),resourceLimits:c({wallTimeMs:d().int().positive().max(1440*60*1e3),maxExamples:d().int().positive().max(1e5),maxInputCharacters:d().int().positive().max(5e5).default(32e3),maxImagePixels:d().int().positive().max(1e8).optional(),maximumSpendUsd:d().nonnegative().max(1e5)}).strict()}).superRefine((e,t)=>{e.runScope==="synthetic_smoke"&&(e.optimizer.maxSteps>100||e.resourceLimits.maximumSpendUsd>10)&&t.addIssue({code:"custom",path:["resourceLimits"],message:"Synthetic-smoke Reward Model runs are limited to 100 steps and USD 10."})});const vj=c({schemaVersion:w("openpond.rftRecipe.v1"),method:w("grpo"),parameterization:w("lora"),baseModel:c({id:Me,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:pt}),dataset:c({trainSplit:w("train"),validationSplit:b(["validation","frozen_eval"]),maxPromptTokens:d().int().positive().max(32768),maxExamples:d().int().positive().max(1e5).default(1e3),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:c({rank:d().int().positive().max(256)}),rollout:c({groupSize:d().int().min(2).max(64),concurrency:d().int().positive().max(32),maxTurns:d().int().positive().max(100),maxOutputTokens:d().int().positive().max(8192),temperature:d().min(0).max(2),topP:d().positive().max(1),seed:d().int()}),optimizer:c({learningRate:d().positive(),maxSteps:d().int().positive().max(1e5)}),loss:c({method:Ry.default("grpo"),klBeta:d().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:c({graderId:Me,graderHash:pt,environmentId:Me,environmentVersion:o().trim().min(1).max(256),toolContractHash:pt,learnedPreference:Py.nullable().optional()}),resourceLimits:c({wallTimeMs:d().int().positive().max(1440*60*1e3),maxRollouts:d().int().positive().max(1e5),maxPayloadBytes:d().int().positive().max(10*1024*1024)}),policyOptimization:Ty.nullable().default(null)}),yj=c({schemaVersion:w("openpond.dpoRecipe.v1"),method:w("dpo"),parameterization:w("lora"),policyModel:vs,referenceModel:vs,dataset:c({trainSplit:w("train"),validationSplit:b(["validation","frozen_eval"]),maxPairs:d().int().positive().max(1e5),maxPromptTokens:d().int().positive().max(32768),maxCompletionTokens:d().int().positive().max(32768),selectionStrategy:w("stable_hash_top_n"),selectionSeed:d().int()}),lora:c({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:h(Me).min(1).max(100)}),loss:c({variant:w("sigmoid"),beta:d().positive().max(10),labelSmoothing:d().min(0).max(.5).default(0)}),optimizer:c({learningRate:d().positive(),epochs:d().positive().max(100),maxSteps:d().int().positive().max(1e6),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int()}),referenceLogprobs:c({cacheSchemaVersion:w("openpond.dpoReferenceLogprobs.v1"),cacheKey:pt,invalidationHash:pt}),resourceLimits:c({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})}),Sj=c({schemaVersion:w("openpond.ppoRecipe.v1"),method:w("ppo"),parameterization:w("lora"),policyOptimization:Ty.extend({optimizer:Ay}),lora:c({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:h(Me).min(1).max(100)}),valueHead:c({initialization:w("policy_hidden_state_linear"),optimizerLearningRate:d().positive(),artifactName:w("value_head.safetensors")}),policyLearningRate:d().positive(),resume:c({checkpointId:Me.nullable(),policyHash:pt,referenceHash:pt,valueModelHash:pt,optimizerStateHash:pt.nullable()}),resourceLimits:c({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})}),xj=c({schemaVersion:w("openpond.unsupportedRecipe.v1"),method:xo.exclude(["sft","dpo","grpo","ppo"]),parameterization:xc,unsupportedReason:o().trim().min(1).max(5e3)}),Dy=Cn([bj,yj,vj,Sj,xj]),kj=c({schemaVersion:w("openpond.trainingDestinationCapabilities.v1"),destinationId:ar,available:C(),methods:h(xo),parameterizations:h(xc),modelAllowlist:h(Me).default([]),maxDatasetBytes:d().int().nonnegative().nullable(),environmentPlacements:h(b(["none","local","remote","colocated","provider_native"])),nonProduction:C(),unavailableReason:o().trim().min(1).max(5e3).nullable(),checkedAt:kt}),_j=c({destinationId:ar,available:C(),methods:h(xo),parameterizations:h(xc),nonProduction:C(),unavailableReason:o().trim().min(1).max(5e3).nullable()}),wj=c({schemaVersion:w("openpond.baseModelCandidate.v1"),selectionKey:Me,label:o().trim().min(1).max(500),sourceLabel:o().trim().min(1).max(500),preference:Ds,available:C(),nonProduction:C(),unavailableReason:o().trim().min(1).max(5e3).nullable(),methods:h(xo),executionOptions:h(_j).min(1)}),Ij=c({code:Me,severity:b(["warning","error"]),path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}),Cj=c({schemaVersion:w("openpond.trainingCompatibility.v1"),compatible:C(),destinationId:ar,tasksetId:Me,recipeMethod:xo,issues:h(Ij),checkedAt:kt}),Rj=Cn([by,b(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);c({method:xo,state:b(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:h(Rj).default([]),reasons:h(o().trim().min(1).max(5e3)).default([]),destinationId:ar.nullable().default(null)});b(["small","standard","custom","small_experiment"]);const Aj=PM,Ly=c({schemaVersion:w("openpond.trainingPlan.v1"),id:Me,modelId:Me,tasksetId:Me,tasksetHash:pt,harnessRelease:it.nullable().optional(),modelImprovementQualification:it.nullable().optional(),destinationId:ar,recipe:Dy,environmentPlacement:b(["none","local","remote","colocated","provider_native"]),compatibility:Cj,dataPolicy:c({exportApproved:C(),approvedSourceIds:h(Me),retentionDays:d().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable()}),estimatedCostUsd:d().nonnegative().nullable(),createdAt:kt,contentHash:pt}),Pj=c({path:o().trim().min(1).max(2e3),sha256:pt,sizeBytes:d().int().nonnegative(),role:b(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),Tp=c({schemaVersion:w("openpond.trainingBundle.v1"),id:Me,planId:Me,tasksetId:Me,tasksetHash:pt,recipeHash:pt,files:h(Pj).min(1).max(1e6),totalSizeBytes:d().int().nonnegative(),sourceIds:h(Me),excludedSourceIds:h(Me),containsRawChats:w(!1),containsSecrets:w(!1),containsHiddenGraderAssets:w(!1),createdAt:kt,contentHash:pt});c({schemaVersion:w("openpond.trainingBundleExport.v1"),manifest:Tp,files:h(c({path:o().trim().min(1).max(2e3),sha256:pt,sizeBytes:d().int().nonnegative(),encoding:w("base64"),content:o()})).min(1),contentHash:pt});c({schemaVersion:w("openpond.trainingPreparedStart.v1"),plan:Ly,bundle:Tp,approvalActor:Me.nullable(),preparedAt:kt});c({schemaVersion:w("openpond.trainingApproval.v1"),id:Me,planId:Me,bundleHash:pt,harnessRelease:it.nullable().optional(),modelImprovementQualification:it.nullable().optional(),destinationId:ar,modelId:Me,method:xo,parameterization:xc,maximumCostUsd:d().nonnegative().nullable(),approvedBy:Me,approvedAt:kt});c({schemaVersion:w("openpond.trainingJobSourceSnapshot.v1"),modelProjectId:Me,sourceProjectRevision:d().int().positive(),profileId:Me,taskset:c({id:Me,revision:d().int().positive(),contentHash:pt}).strict(),tasksetRelease:it,harnessRelease:it,baseModel:Ds,method:xo}).strict();const Tj=b(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),zy=c({schemaVersion:w("openpond.trainingJob.v1"),id:Me,planId:Me,bundleHash:pt,approvalId:Me,destinationId:ar,status:Tj,nonProduction:C(),workerPid:d().int().positive().nullable(),startedAt:kt.nullable(),completedAt:kt.nullable(),error:o().trim().min(1).max(2e4).nullable(),createdAt:kt,updatedAt:kt,metadata:Ls}),Ej=c({schemaVersion:w("openpond.trainingJobEvent.v1"),id:Me,jobId:Me,sequence:d().int().nonnegative(),type:b(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:kt,payload:Ls}),Mj=c({schemaVersion:w("openpond.sftStepMetric.v1"),step:d().int().nonnegative(),maxSteps:d().int().positive(),timestamp:kt,epoch:d().nonnegative().nullable(),loss:d().nullable(),learningRate:d().nonnegative().nullable(),gradientNorm:d().nonnegative().nullable(),entropy:d().nonnegative().nullable(),meanTokenAccuracy:d().min(0).max(1).nullable(),preferenceAccuracy:d().min(0).max(1).nullable().default(null),preferenceMargin:d().nullable().default(null),chosenReward:d().nullable().default(null),rejectedReward:d().nullable().default(null),chosenLogProbability:d().nullable().default(null),rejectedLogProbability:d().nullable().default(null),reward:d().nullable().default(null),policyLoss:d().nullable().default(null),advantageLoss:d().nullable().default(null),inputTokensSeen:d().int().nonnegative().nullable(),memoryBytes:d().int().nonnegative().nullable(),elapsedSeconds:d().nonnegative().nullable()}),jj=c({schemaVersion:w("openpond.policyOptimizationMetric.v1"),method:b(["grpo","ppo"]),step:d().int().nonnegative(),timestamp:kt,learningRate:d().nonnegative().nullable().default(null),policyLoss:d().nullable(),valueLoss:d().nullable(),gradientNorm:d().nonnegative().nullable().default(null),meanReward:d().nullable(),meanReturn:d().nullable(),kl:d().nullable(),entropy:d().nullable(),policyClipFraction:d().min(0).max(1).nullable(),valueClipFraction:d().min(0).max(1).nullable(),explainedVariance:d().nullable(),rolloutLearnerLag:d().int().nonnegative().nullable(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),environmentExecutions:d().int().nonnegative(),trajectoryCount:d().int().nonnegative().nullable().default(null),costUsd:d().nonnegative().nullable()}),Oj=c({schemaVersion:w("openpond.managedTrainingRunEvidence.v1"),provider:Me,providerRunId:Me,state:Me,progress:c({targetOptimizerSteps:d().int().nonnegative(),committedOptimizerSteps:d().int().nonnegative()}),reward:c({finalMean:d().nullable(),trajectoryCount:d().int().nonnegative(),eligibleTrajectoryCount:d().int().nonnegative()}),usage:c({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),environmentExecutions:d().int().nonnegative()}),resource:c({provider:Me,gpuType:o().trim().min(1).max(300).nullable(),gpuCount:d().int().nonnegative().nullable(),hourlyCostUsd:d().nonnegative().nullable()}),cost:c({totalUsd:d().nonnegative().nullable()}),checkpoint:c({id:Me,policyVersion:d().int().nonnegative(),sha256:pt.nullable(),sizeBytes:d().int().nonnegative().nullable()}).nullable(),evaluations:h(c({kind:b(["baseline","candidate"]),policyVersion:d().int().nonnegative(),score:d().nullable(),threshold:d().nullable(),passed:C().nullable()})),canonicalPublication:c({state:Me.nullable(),artifactId:Me.nullable()}),syncedAt:kt}),Dh=c({count:d().int().nonnegative(),scoredCount:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable(),passedCount:d().int().nonnegative(),passRate:d().min(0).max(1).nullable()}),Lh=c({status:b(["scored","unavailable"]),score:d().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:h(o().trim().min(1).max(2e4)).max(1e3),components:h(c({graderId:Me,score:d().min(0).max(1),passed:C(),feedback:o().trim().max(2e4).nullable()})).max(1e3)}),Nj=c({taskId:Me,input:fe(o(),Se()),baseOutput:fe(o(),Se()).nullable(),trainedOutput:fe(o(),Se()).nullable(),baseGrade:Lh.nullable(),trainedGrade:Lh.nullable()}),$j=c({schemaVersion:w("openpond.trainingEvaluationSummary.v1"),jobId:Me,tasksetId:Me,base:Dh,trained:Dh,meanScoreDelta:d().min(-1).max(1).nullable(),examples:h(Nj).max(1e6)});c({schemaVersion:w("openpond.trainingRunDetail.v1"),job:zy,events:h(Ej),stepMetrics:h(Mj),policyMetrics:h(jj).default([]),managedEvidence:Oj.nullable().default(null),evaluation:$j.nullable(),generatedAt:kt});const Dj=c({schemaVersion:w("openpond.trainingArtifact.v1"),id:Me,jobId:Me,kind:b(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:o().trim().min(1).max(4e3),sha256:pt,sizeBytes:d().int().nonnegative(),baseModelId:Me.nullable(),baseModelRevision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:pt.nullable(),nonProduction:C(),createdAt:kt,metadata:Ls}),Lj=c({schemaVersion:w("openpond.modelArtifactLineage.v1"),id:Me,modelId:Me,artifactId:Me,jobId:Me,tasksetId:Me,tasksetHash:pt,graderHash:pt,planHash:pt,bundleHash:pt,recipeHash:pt,workerVersion:o().trim().min(1).max(256),trainerVersion:o().trim().min(1).max(256),importedAt:kt,frozenEvaluationArtifactId:Me.nullable(),promotable:C(),pinned:C().default(!1),status:b(["imported","rejected"]).default("imported"),rejectedAt:kt.nullable().default(null),rejectionReason:o().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:Ey.default(JM),managedServing:YM.nullable().default(null)}),zj=b(["chat_manual","agent","extension","authoring_optimizer"]),Uj=c({schemaVersion:w("openpond.modelBinding.v1"),id:Me,profileId:Me,role:zj,roleTargetId:Me,modelArtifactLineageId:Me,tasksetId:Me,evaluationArtifactId:Me.nullable(),status:b(["active","rolled_back"]),priorBindingId:Me.nullable(),rollbackTargetBindingId:Me.nullable(),promotedBy:Me,promotedAt:kt,rolledBackAt:kt.nullable(),metadata:Ls});c({schemaVersion:w("openpond.trainingActivity.v1"),profileId:Me,active:C(),activeCounts:c({jobs:d().int().nonnegative(),creations:d().int().nonnegative(),minerRuns:d().int().nonnegative(),datasetImports:d().int().nonnegative()}),revision:pt,generatedAt:kt});c({schemaVersion:w("openpond.tasksetOperationalState.v1"),tasksetId:Me,attempts:h(JE),artifacts:h(YE),grades:h(QE),generatedAt:kt});c({schemaVersion:w("openpond.trainingState.v1"),profileId:Me,sources:h(ny),creations:h(Sy),tasksetDrafts:h(gM).default([]),tasksets:h(Eh),benchmarkRuns:h(Ud()).default([]),benchmarkComparisons:h(Ud()).default([]),datasetImports:h(wM).default([]),datasetArtifacts:h(yE).default([]),graderAuditReports:h(eM),evaluationResults:h(Ud()).default([]),candidates:h(G0),minerConfig:gc,minerRuns:h(hE).default([]),modelProjects:h(Aj).default([]),modelVersions:h($M).default([]),modelRuns:h(WM).default([]),rewardModelVersions:h(DM).default([]),rewardModelRuns:h(zM).default([]),modelTasksets:h(Eh).default([]),plans:h(Ly),bundles:h(Tp),jobs:h(zy),artifacts:h(Dj),models:h(Lj),rolloutReceipts:h(gj).default([]),modelBindings:h(Uj).default([]),destinations:h(kj),baseModelCandidates:h(wj).default([]),activityRevision:pt.optional(),generatedAt:kt});var Wt=o().trim().min(1).max(500),Yr=o().regex(/^[a-f0-9]{64}$/),Sa=o().datetime({offset:!0}),zt=c({id:Wt,contentHash:Yr}).strict(),Uy=zt.extend({revision:d().int().positive()}).strict(),di=c({schemaVersion:w("openpond.baseModelPreference.v1"),modelId:Wt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:Wt.nullable(),source:b(["managed","local","builtin"])}).strict(),Hy=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),qy=c({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:Hy,parameterization:b(["lora","full"])}).catchall(Se()),Ep=c({tasksetRef:Uy.nullable().default(null),tasksetRelease:zt.nullable().default(null),harnessRelease:zt.nullable().default(null),baseModel:di.nullable().default(null),method:Hy.nullable().default(null),destinationId:Wt.nullable().default(null),managedRolloutPlacement:b(["local","remote"]).default("remote"),runPreset:b(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:qy.nullable().default(null),preferredMaximumSpendUsd:d().nonnegative().nullable().default(null),preferredRetentionDays:d().int().nonnegative().nullable().default(null)}).strict(),Hj=c({schemaVersion:w("openpond.hostedModelProjectLink.v1"),teamId:Wt,projectId:Wt,portableProjectId:Wt,revision:d().int().positive(),etag:Yr,syncedSourceRevision:d().int().positive(),syncedAt:Sa,tasksets:h(c({localTasksetId:Wt,releaseId:Wt,releaseRevision:d().int().positive(),releaseHash:Yr,hostedTasksetId:Wt,syncedAt:Sa}).strict()).max(1e4).default([])}).strict(),qj=c({localTasksetId:Wt,releaseId:Wt,releaseRevision:d().int().positive(),releaseHash:Yr,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Wt.nullable().default(null),lastAttemptAt:Sa,syncedAt:Sa.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict();c({schemaVersion:w("openpond.modelProject.v2"),id:Wt,profileId:Wt,revision:d().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:di.nullable(),defaultDestinationId:Wt.nullable(),trainingSetup:Ep,hosted:Hj.nullable().default(null),tasksetSyncs:h(qj).max(1e4).default([]),createdAt:Sa,updatedAt:Sa}).strict();c({schemaVersion:w("openpond.hostedModelProjectSync.v2"),portableProjectId:Wt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:di.nullable(),defaultDestinationId:Wt.nullable(),trainingSetup:Ep,sourceRevision:d().int().positive(),sourceUpdatedAt:Sa,expectedEtag:Yr.nullable().default(null)}).strict();var Bj=c({id:Wt,teamId:Wt,portableProjectId:Wt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:di.nullable(),defaultDestinationId:Wt.nullable(),trainingSetup:Ep,sourceRevision:d().int().positive(),sourceUpdatedAt:Sa,revision:d().int().positive(),etag:Yr,createdAt:Sa,updatedAt:Sa}).strict(),Fj=c({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:zt,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:Sa}).strict();c({project:Bj,resources:h(Fj).max(1e4),jobCount:d().int().nonnegative(),latestJobIds:h(Wt).max(100)}).strict();c({schemaVersion:w("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:C().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:fe(o(),Se()).default({})}).strict();var Sn=o().trim().min(1).max(500),ea=o().regex(/^[a-f0-9]{64}$/),xa=o().datetime({offset:!0});c({schemaVersion:w("openpond.trainingInputArtifactUpload.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:o().trim().min(1).max(500),sourceManifest:zt,payload:Se(),contentHash:ea}).strict();c({schemaVersion:w("openpond.trainingInputArtifact.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),sourceManifest:zt,artifactRef:o().trim().min(1).max(2e3),contentHash:ea,sizeBytes:d().int().positive(),createdAt:xa}).strict();var By=b(["reward_model_train","policy_optimize"]),Vj=b(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),Wj=c({id:Sn,version:o().trim().min(1).max(200).nullable().default(null),required:C().default(!0)}).strict(),Kj=c({modelProject:c({id:Sn,portableProjectId:Sn,revision:d().int().positive(),contentHash:ea}).strict(),harnessRunManifest:zt,harnessRelease:zt,taskset:Uy,tasksetRelease:zt,dataset:zt,evidenceSets:h(zt).max(1e4)}).strict(),Gj=c({kind:w("reward_model_train"),baseModel:di,preferenceDatasetRelease:zt,processorRelease:zt,recipe:c({schemaVersion:w("openpond.rewardModelRecipe.v1"),method:w("reward_model"),parameterization:w("lora_with_scalar_head")}).catchall(Se())}).strict(),Zj=c({kind:w("deterministic"),grader:zt,composer:zt.nullable().default(null)}).strict(),Jj=c({kind:w("learned_reward"),rewardModelVersion:zt,qualificationReport:zt.nullable(),scorerArtifact:c({artifactRef:o().trim().min(1).max(2e3),contentHash:ea,executionReceipt:zt}).strict(),processorRelease:zt,rewardComposerRelease:zt}).strict(),Yj=c({kind:w("policy_optimize"),baseModel:di,recipe:qy,rewardSource:dn("kind",[Zj,Jj]),resumeFrom:zt.nullable().default(null)}).strict(),Xj=dn("kind",[Gj,Yj]),Qj=c({approvalHash:ea,approvedAt:xa,exportApproved:C(),maximumSpendUsd:d().nonnegative(),retentionDays:d().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable().default(null)}).strict();c({schemaVersion:w("openpond.trainingJobSubmission.v2"),idempotencyKey:o().trim().min(1).max(500),name:o().trim().min(1).max(200),source:Kj,job:Xj,requestedCapabilities:h(Wj).max(1e3),budget:c({maximumSpendUsd:d().nonnegative(),maximumWallSeconds:d().int().positive()}).strict(),approval:Qj,contentHash:ea}).strict().superRefine((e,t)=>{e.approval.maximumSpendUsd!==e.budget.maximumSpendUsd&&t.addIssue({code:"custom",path:["approval","maximumSpendUsd"],message:"Approved spend must equal the immutable Job budget."})});var eO=c({schemaVersion:w("openpond.trainingJob.v2"),id:Sn,teamId:Sn,kind:By,modelProjectId:Sn,portableProjectId:Sn,sourceProjectRevision:d().int().positive(),submissionHash:ea,state:Vj,phase:o().trim().min(1).max(200),version:d().int().nonnegative(),progress:d().min(0).max(1),accruedSpendUsd:d().nonnegative(),terminalReason:o().trim().min(1).max(5e3).nullable(),createdAt:xa,updatedAt:xa,completedAt:xa.nullable()}).strict();c({schemaVersion:w("openpond.trainingJobPage.v2"),jobs:h(eO).max(1e3),nextCursor:o().trim().min(1).max(2e3).nullable()}).strict();c({schemaVersion:w("openpond.trainingJobEvent.v2"),id:Sn,jobId:Sn,sequence:d().int().nonnegative(),type:Sn,phase:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3).nullable(),data:fe(o(),Se()).default({}),createdAt:xa}).strict();c({schemaVersion:w("openpond.trainingJobLog.v2"),jobId:Sn,sequence:d().int().nonnegative(),level:b(["debug","info","warning","error"]),message:o().max(2e4),createdAt:xa}).strict();c({expectedVersion:d().int().nonnegative()}).strict();var tO=c({schemaVersion:w("openpond.trainingJobOutput.v2"),id:Sn,jobId:Sn,kind:b(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:o().trim().min(1).max(2e3),contentHash:ea,sizeBytes:d().int().nonnegative(),metadata:fe(o(),Se()).default({}),createdAt:xa}).strict(),nO=c({schemaVersion:w("openpond.trainingExecutionReceipt.v2"),id:Sn,teamId:Sn,jobId:Sn,submissionHash:ea,manifestHash:ea,recipeHash:ea,capabilityHash:ea,runtimeRelease:zt,inputs:h(zt).max(1e4),outputs:h(zt).max(1e4),spendUsd:d().nonnegative(),durationSeconds:d().nonnegative(),cleanupComplete:C(),issuer:Sn,issuedAt:xa,signature:o().trim().min(1).max(1e4).nullable()}).strict();c({schemaVersion:w("openpond.trainingJobOutputs.v2"),outputs:h(tO).max(1e4),receipt:nO.nullable()}).strict();c({schemaVersion:w("openpond.trainingApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:C().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:fe(o(),Se()).default({})}).strict();c({schemaVersion:w("openpond.trainingCapabilities.v2"),capabilityHash:ea,jobKinds:h(By),methods:h(o().trim().min(1).max(200)),placements:h(b(["local","remote","colocated","provider_native"])),controls:c({cancel:C(),stopAfterGroup:C(),resumeFromCheckpoint:C()}).strict(),limits:c({maximumSpendUsd:d().nonnegative(),maximumWallSeconds:d().int().positive(),maximumArtifactBytes:d().int().positive()}).strict(),checkedAt:xa,expiresAt:xa}).strict();const Ya=o().trim().min(1).max(1e5),aO=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),oO=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),Fy=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),Mp=c({kind:b(["personal","team"]),id:ne}).strict(),jp=c({policy:ce,state:b(["authorized","revoked","deleted","expired"]),checkedAt:Qe}).strict(),ys=c({evidence:ce,kind:Fy,sourceRef:ne,sourcePolicy:jp,occurrenceKey:_e,occurredAt:Qe}).strict(),rO=c({evidence:ce,sourcePolicy:jp.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),zh=c({cursor:_e,throughCreatedAt:Qe}).strict(),iO=c({fingerprint:_e,recurrenceFamily:o().trim().min(1).max(1e3),statement:Ya,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:d().int().positive().max(1e6),unresolvedOccurrences:d().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),Vy=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),sO=c({layer:Vy,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:Ya,evidenceRefs:h(ce).max(1e3)}).strict(),Wy=c({schemaVersion:w("openpond.harnessEvaluationReviewReceipt.v1"),id:ne,ownerScope:Mp,workspaceRef:ne,harnessRelease:ce,previousWatermark:zh.nullable(),nextWatermark:zh,selectedEvidence:h(ys).max(1e4),excludedEvidence:h(rO).max(1e4),claim:iO.nullable(),classification:aO,triage:h(sO).max(16),reason:Ya,nextAuthority:oO,maxEstimatedCostUsd:d().finite().nonnegative(),tasksetProposal:ce.nullable(),evaluation:ce.nullable(),trainingQualification:ce.nullable(),policyVersion:ne,createdAt:Qe,metadata:wt}).strict().superRefine((e,t)=>{const n=e.selectedEvidence.map(a=>`${a.evidence.id}:${a.evidence.contentHash}`);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"selected review evidence must be unique",path:["selectedEvidence"]}),e.selectedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"selected review evidence must be authorized at review time",path:["selectedEvidence"]}),e.classification==="no_action"?(e.nextAuthority!=="none"&&t.addIssue({code:"custom",message:"no-action review receipts require no next authority",path:["nextAuthority"]}),(e.tasksetProposal||e.evaluation||e.trainingQualification)&&t.addIssue({code:"custom",message:"no-action review receipts cannot carry downstream refs"})):(!e.claim||e.selectedEvidence.length===0)&&t.addIssue({code:"custom",message:"actionable review receipts require a claim and selected evidence"}),e.classification==="runtime"&&e.nextAuthority!=="runtime_service"&&t.addIssue({code:"custom",message:"runtime classifications route to runtime-service authority",path:["nextAuthority"]}),e.classification==="product"&&e.nextAuthority!=="product_team"&&t.addIssue({code:"custom",message:"product classifications route to product-team authority",path:["nextAuthority"]}),e.classification==="taskset"&&e.nextAuthority!=="human_review"&&t.addIssue({code:"custom",message:"Taskset classifications require human review"}),e.classification==="model_improvement"&&(!e.evaluation||!e.trainingQualification||!["human_review","training_system"].includes(e.nextAuthority))&&t.addIssue({code:"custom",message:"model-improvement classifications require Evaluation and qualification refs plus explicit authority"})}),lO=Wy.extend({contentHash:_e}).strict();function Us(e){const t=Wy.parse(e);return lO.parse({...t,contentHash:xt(t)})}c({id:ne,evidence:ce,kind:Fy,sourceRef:ne,occurredAt:Qe,payload:fe(o(),Se())}).strict();const cO=c({schemaVersion:w("openpond.harnessEvaluationReviewModelDecision.v2"),decision:w("no_action"),reason:Ya,ignoredEvidence:h(c({id:ne,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),dO=c({schemaVersion:w("openpond.harnessEvaluationReviewModelDecision.v2"),decision:w("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:h(ne).min(1).max(1e3),ignoredEvidence:h(c({id:ne,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:o().trim().min(1).max(1e3),statement:Ya,triageLayer:Vy,expectedOutcome:Ya,counterevidence:o().trim().max(1e4),confidence:d().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:Ya}).strict().superRefine((e,t)=>{e.classification==="harness_maintenance"!==(e.candidateDisposition!==null)&&t.addIssue({code:"custom",message:"Harness maintenance requires a candidate disposition; external routes require null",path:["candidateDisposition"]})}),uO=c({schemaVersion:w("openpond.harnessEvaluationReviewModelDecision.v2"),decision:w("resolve_candidate"),candidateId:ne,candidateFingerprint:_e,selectedEvidenceIds:h(ne).min(1).max(1e3),ignoredEvidence:h(c({id:ne,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:d().min(0).max(1),reason:Ya}).strict();dn("decision",[cO,dO,uO]);c({schemaVersion:w("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:h(ne).min(1).max(50),reason:Ya}).strict();const kc=c({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:fe(o(),Se()),inputSchemaHash:_e,sideEffect:b(["read","write"]),timeoutMs:d().int().positive().max(36e5)}).strict(),Op=c({id:ne,required:C(),scopes:h(o().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),mO=c({portable:C(),blockers:h(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:h(ne).max(1e4),hostPrivateAssetRefs:h(ne).max(1e4)}).strict(),pO=c({schemaVersion:w("openpond.agentSnapshot.v2"),id:ne,sourceRelease:ce.nullable(),instructions:h(Kn).max(1e4),skills:h(Kn).max(1e4),agents:h(Kn).max(1e4),toolDeclarations:h(kc).max(200),capabilityRequirements:h(Op).max(200),dependencyLock:Kn,portability:mO,metadata:wt}).strict();pO.extend({contentHash:_e}).strict();const Ky=c({create:w(!0),reset:w(!0),step:w(!0),collect:w(!0),destroy:w(!0),resetScope:b(["task","attempt"])}).strict(),Gy=c({visibleEvidence:h(ne).max(1e3),privilegedEvidence:h(ne).max(1e3),privateVerifierIsolation:C()}).strict(),fO=c({schemaVersion:w("openpond.harnessRelease.v2"),id:ne,agentSnapshot:ce,program:Kn,tools:h(kc).max(200),lifecycle:Ky,graderInterface:Gy,files:h(Kn).max(1e5),metadata:wt}).strict();fO.extend({contentHash:_e}).strict();const hO=c({id:ne,turn:d().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:ne.nullable(),arguments:fe(o(),Se()),content:o().max(1e6).nullable()}).strict(),gO=c({actionId:ne,turn:d().int().nonnegative(),terminal:C(),output:fe(o(),Se()),artifactRefs:h(Gn).max(1e5)}).strict(),bO=c({sequence:d().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:_e,metadata:wt}).strict();c({schemaVersion:w("openpond.harnessTrace.v1"),manifest:ce,taskId:ne,seed:o().trim().min(1).max(500),events:h(bO).max(1e6),actions:h(hO).max(1e5),observations:h(gO).max(1e5),terminal:C(),failureClass:fc.nullable(),output:fe(o(),Se()),contentHash:_e}).strict();const _c=o().trim().min(1).max(1e5),Hs=fe(o(),Se()).default({}),vO=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),Zy=c({kind:vO,eventSequence:d().int().nonnegative(),occurredAt:Qe}).strict(),Jy=c({id:ne,sequence:d().int().nonnegative().nullable(),contentHash:_e}).strict(),yO=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),SO=b(["open","recovered","terminal"]),xO=c({name:o().trim().min(1).max(500),invocationKey:_e}).strict(),kO=c({schemaVersion:w("openpond.improvementObservation.v1"),id:ne,runRef:ne,turnId:ne,harnessRelease:ce,overlay:Za.nullable(),eventRefs:h(Jy).min(1).max(100),kind:yO,state:SO,tool:xO.nullable(),deterministicClass:o().trim().min(1).max(500).nullable(),summary:_c,createdAt:Qe,metadata:Hs}).strict().superRefine((e,t)=>{new Set(e.eventRefs.map(n=>n.id)).size!==e.eventRefs.length&&t.addIssue({code:"custom",message:"observation event refs must be unique",path:["eventRefs"]}),["tool_failure","retry","recovery","completion_detour"].includes(e.kind)&&e.tool===null&&t.addIssue({code:"custom",message:`${e.kind} observations require a tool identity`,path:["tool"]})});kO.extend({contentHash:_e}).strict();const _O=c({schemaVersion:w("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:d().finite().nonnegative(),cooldownMs:d().int().nonnegative(),maxPendingPlans:d().int().min(1).max(100),maxEvidenceEvents:d().int().min(1).max(1e3),maxProposalEdits:d().int().min(1).max(1e3),maxProposalBytes:d().int().min(1).max(1e7)}).strict(),wO=b(["no_action","route_deterministically","queue_refiner"]),IO=c({schemaVersion:w("openpond.refinementTriggerDecision.v1"),id:ne,runRef:ne,turnId:ne,harnessRelease:ce,overlay:Za.nullable(),observations:h(ce).max(100),decision:wO,deterministicRoute:Gr.nullable(),suggestedRoutes:h(Gr).max(8),reason:_c,deduplicationKey:_e,policy:_O,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:Zy,cooldownUntil:Qe.nullable(),createdAt:Qe,metadata:Hs}).strict().superRefine((e,t)=>{e.estimatedMaxCostUsd>e.policy.maxEstimatedCostUsd&&t.addIssue({code:"custom",message:"estimated Refiner cost exceeds the trigger policy budget",path:["estimatedMaxCostUsd"]}),e.pendingPlanCount>e.policy.maxPendingPlans&&t.addIssue({code:"custom",message:"pending plan count exceeds the trigger policy limit",path:["pendingPlanCount"]}),e.observations.length>e.policy.maxEvidenceEvents&&t.addIssue({code:"custom",message:"trigger observations exceed the evidence budget",path:["observations"]}),e.decision==="route_deterministically"&&e.deterministicRoute===null&&t.addIssue({code:"custom",message:"deterministic decisions require a route",path:["deterministicRoute"]}),e.decision!=="route_deterministically"&&e.deterministicRoute!==null&&t.addIssue({code:"custom",message:"only deterministic decisions may declare a deterministic route",path:["deterministicRoute"]}),e.decision==="no_action"&&e.suggestedRoutes.length>0&&t.addIssue({code:"custom",message:"no-action decisions cannot suggest routes",path:["suggestedRoutes"]}),e.decision!=="no_action"&&e.observations.length===0&&t.addIssue({code:"custom",message:"actionable trigger decisions require observations",path:["observations"]})});IO.extend({contentHash:_e}).strict();const CO=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),RO=c({schemaVersion:w("openpond.improvementRouteDecision.v1"),id:ne,trigger:ce,route:Gr,authority:CO,automatic:C(),reason:_c,createdAt:Qe,metadata:Hs}).strict().superRefine((e,t)=>{e.automatic&&["human_review","evaluation_system","training_system"].includes(e.authority)&&t.addIssue({code:"custom",message:`${e.authority} routes cannot be marked automatic`,path:["automatic"]}),e.route==="training"&&e.automatic&&e.authority!=="training_system"&&t.addIssue({code:"custom",message:"automatic training routes require training-system authority",path:["authority"]})});RO.extend({contentHash:_e}).strict();const AO=c({schemaVersion:w("openpond.harnessRefinerOutcome.v1"),id:ne,trigger:ce,decision:b(["no_action","proposed"]),proposal:ce.nullable(),reason:_c,evidenceRefs:h(ce).max(100),estimatedCostUsd:d().finite().nonnegative(),createdAt:Qe,metadata:Hs}).strict().superRefine((e,t)=>{e.decision==="proposed"!=(e.proposal!==null)&&t.addIssue({code:"custom",message:"proposed Refiner outcomes require a proposal; no-action outcomes cannot include one",path:["proposal"]})});AO.extend({contentHash:_e}).strict();const PO=b(["applied","retained","declined","conflict","rolled_back"]),TO=c({schemaVersion:w("openpond.improvementApplyReceipt.v1"),id:ne,proposal:ce,beforeOverlay:Za,afterOverlay:Za.nullable(),decision:PO,boundary:Zy,validationRefs:h(ce).max(100),outcomeEvidenceRefs:h(Jy).max(1e3),rollbackOf:ce.nullable(),createdAt:Qe,metadata:Hs}).strict().superRefine((e,t)=>{e.decision==="applied"!=(e.afterOverlay!==null)&&t.addIssue({code:"custom",message:"applied receipts require an after-overlay; other decisions cannot include one",path:["afterOverlay"]}),e.decision==="rolled_back"!=(e.rollbackOf!==null)&&t.addIssue({code:"custom",message:"only rollback receipts require rollbackOf",path:["rollbackOf"]})});TO.extend({contentHash:_e}).strict();const or=c({provider:ne,model:ne,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:_e.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:_e.nullable().default(null)}).strict(),EO=b(["memory","prompt","skill","agent"]),MO=b(["runtime","product","taskset","training"]),jO=c({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),Yy=c({schemaVersion:w("openpond.refinerReviewProfile.v1"),id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:o().trim().min(1).max(120),name:o().trim().min(1).max(200),objective:o().trim().min(1).max(1e4),instructions:h(jO).max(100),allowedProposalRoutes:h(EO).max(4),allowedExternalRoutes:h(MO).max(4)}).strict().superRefine((e,t)=>{const n=e.instructions.map(a=>a.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"instruction IDs must be unique",path:["instructions"]}),new Set(e.allowedProposalRoutes).size!==e.allowedProposalRoutes.length&&t.addIssue({code:"custom",message:"proposal routes must be unique",path:["allowedProposalRoutes"]}),new Set(e.allowedExternalRoutes).size!==e.allowedExternalRoutes.length&&t.addIssue({code:"custom",message:"external routes must be unique",path:["allowedExternalRoutes"]})}),Uh=c({schemaVersion:w("openpond.refinerRelease.v1"),id:o().trim().min(1).max(240),coreVersion:o().trim().min(1).max(120),coreHash:_e,profile:Yy,profileHash:_e,composedPromptHash:_e,createdAt:Qe,contentHash:_e}).strict(),OO=c({schemaVersion:w("openpond.refinerBinding.v1"),channel:w("active"),revision:d().int().nonnegative(),release:ce,updatedAt:Qe}).strict(),NO=c({schemaVersion:w("openpond.refinerTransitionReceipt.v1"),id:o().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:C(),previousRelease:ce.nullable(),nextRelease:ce,actor:o().trim().min(1).max(240),reason:o().trim().min(1).max(1e4),authoringSkillHash:_e.nullable(),validation:c({valid:C(),messages:h(o().max(2e3)).max(100)}).strict(),createdAt:Qe,contentHash:_e}).strict(),$O=c({schemaVersion:w("openpond.localHarnessRefinerDecision.v1"),decision:w("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),DO=c({schemaVersion:w("openpond.localHarnessRefinerDecision.v1"),decision:w("route"),route:b(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip(),LO=c({schemaVersion:w("openpond.localHarnessRefinerDecision.v1"),decision:w("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),zO=dn("decision",[$O,DO,LO]),UO=zO,Np=c({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:h(o().trim().min(1).max(2e3)).min(1).max(100),counterevidence:h(o().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),HO=c({schemaVersion:w("openpond.localHarnessRefinerDecision.v2"),decision:w("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),qO=c({schemaVersion:w("openpond.localHarnessRefinerDecision.v2"),decision:w("route"),route:b(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),evidenceBasis:Np,expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict(),BO=c({schemaVersion:w("openpond.localHarnessRefinerDecision.v2"),decision:w("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),evidenceBasis:Np,createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),Xy=dn("decision",[HO,qO,BO]);Cn([UO,Xy]);const $p=c({memory:C(),prompt:C(),skill:C(),agent:C()}).strict(),Qy=b(["memory","instruction","skill","agent"]),Hh=c({path:o().trim().min(1).max(2e3),kind:Qy,content:o().max(6e4),loaded:C()}).strict(),qh=c({path:o().trim().min(1).max(2e3),kind:Qy,loaded:C()}).strict(),FO=c({capabilities:$p,trigger:fe(o(),Se()),observations:h(fe(o(),Se())).max(20),admissibleEvidenceIds:h(o().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),error:o().max(2100).nullable(),prompt:o().max(8100).nullable(),assistantOutput:o().max(8100).nullable(),assistantOutputLinkCount:d().int().nonnegative()}).strict(),priorConversation:h(c({turnId:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),prompt:o().max(3100).nullable(),assistantOutput:o().max(3100).nullable()}).strict()).max(3),timeline:h(fe(o(),Se())).max(60),artifacts:h(fe(o(),Se())).max(30),artifactDiagnostics:h(fe(o(),Se())).max(20),executionProfile:c({modelRequestCount:d().int().nonnegative(),failedModelRequestCount:d().int().nonnegative(),promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),toolFailureCount:d().int().nonnegative(),retryCount:d().int().nonnegative(),recoveryCount:d().int().nonnegative()}).strict(),priorIncidents:h(fe(o(),Se())).max(3),truncation:c({timelineEventCount:d().int().nonnegative(),includedTimelineEventCount:d().int().nonnegative(),timelineTruncated:C()}).strict()}).strict(),runtimeActivation:c({admittedRelease:ce,currentRelease:ce,rebasedOntoCurrent:C(),admittedSourceFiles:h(Hh).max(100),admittedSourceCatalog:h(qh).max(1e3)}).strict(),sourceFiles:h(Hh).max(100),sourceCatalog:h(qh).max(1e3),additionalEvidence:Se().nullable().optional()}).strict(),VO=c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),contentHash:_e}).strict();c({schemaVersion:w("openpond.hostedHarnessRefinerRequest.v2"),requestId:o().trim().min(1).max(240),idempotencyKey:o().trim().min(1).max(240),evidenceHash:_e,harness:c({admittedRelease:ce,currentRelease:ce,overlay:VO,workspace:c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:_e,channelRevision:d().int().nonnegative()}).strict(),capabilities:$p}).strict(),evidence:FO}).strict();const WO=c({promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative()}).strict();c({schemaVersion:w("openpond.hostedHarnessRefinerResponse.v2"),requestId:o().trim().min(1).max(240),evidenceHash:_e,admittedRelease:ce,currentRelease:ce,decision:Xy,serviceRevision:o().trim().min(1).max(240),usage:WO}).strict();const KO=o().trim().min(1).max(2e3),Dp=o().trim().min(1).max(1e5),GO=b(["create","update","delete"]),ZO=b(["memory","prompt","skill","agent"]),JO=b(["runtime","product","taskset","training"]),YO=b(["no_action","routed","applied","retained","failed"]),XO=b(["not_applicable","pending","passed","rejected","failed"]),QO=b(["not_applicable","pending","passed","failed"]),e2=c({schemaVersion:w("openpond.harnessRefinerActivityReceipt.v1"),id:ne,runRef:ne,turnId:ne,result:YO,decision:b(["no_action","route","propose"]).nullable(),route:Gr.nullable(),operation:GO.nullable(),target:o().trim().min(1).max(2e3).nullable(),summary:KO,evidenceBasis:Np.nullable(),critiqueStatus:XO,validationStatus:QO,trigger:ce,outcome:ce.nullable(),proposal:ce.nullable(),applyReceipt:ce.nullable(),inputHarness:ce,outputHarness:ce.nullable(),createdAt:Qe}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?Bh(t,e,{decision:"no_action",route:null,operation:null,target:null,evidenceBasis:null,proposal:null,applyReceipt:null,outputHarness:null,critiqueStatus:"not_applicable",validationStatus:"not_applicable"}):e.result==="routed"?((e.decision!=="route"||!JO.safeParse(e.route).success||e.operation!==null||e.target!==null||e.evidenceBasis===null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"routed activity requires an external route and evidence basis without proposal state"}),Bh(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!ZO.safeParse(e.route).success||e.operation===null||e.target===null||e.evidenceBasis===null||e.proposal===null||e.applyReceipt===null)&&t.addIssue({code:"custom",message:"applied and retained activity requires complete proposal state"}),e.result==="applied"&&e.outputHarness===null&&t.addIssue({code:"custom",message:"applied activity requires the advanced Harness release",path:["outputHarness"]}),e.result==="applied"&&(e.critiqueStatus!=="passed"||e.validationStatus!=="passed")&&t.addIssue({code:"custom",message:"applied activity requires passed critique and validation"}),e.result==="retained"&&e.outputHarness!==null&&t.addIssue({code:"custom",message:"retained activity cannot report a new Harness release",path:["outputHarness"]})):(e.decision!==null||e.route!==null||e.operation!==null||e.target!==null||e.evidenceBasis!==null||e.outcome!==null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"failed activity cannot claim a decision, route, proposal, or release transition"}),e.result!=="failed"&&e.outcome===null&&t.addIssue({code:"custom",message:"terminal Refiner decisions require an outcome reference",path:["outcome"]})});e2.extend({contentHash:_e}).strict();const t2=b(["unresolved","confirmed","resolved","rejected","expired"]),n2=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Dp,evidenceRefs:h(ce).max(1e3),resolvedAt:Qe}).strict(),a2=c({schemaVersion:w("openpond.harnessRefinementCandidate.v1"),id:ne,ownerScope:Mp,workspaceRef:ne,fingerprint:_e,recurrenceFamily:o().trim().min(1).max(1e3),statement:Dp,status:t2,occurrences:h(ys).max(1e3),counterevidence:h(ys).max(1e3),sourceReviews:h(ce).min(1).max(100),relatedHarnessReleases:h(ce).max(100),firstSeenAt:Qe,lastSeenAt:Qe,lastReviewedAt:Qe,expiresAt:Qe,resolution:n2.nullable(),createdAt:Qe,updatedAt:Qe}).strict().superRefine((e,t)=>{Fo(t,e.occurrences,"occurrences"),Fo(t,e.counterevidence,"counterevidence"),Fo(t,e.sourceReviews,"sourceReviews"),Fo(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(r=>r.occurrenceKey));e.counterevidence.some(r=>n.has(r.occurrenceKey))&&t.addIssue({code:"custom",message:"supporting occurrences and counterevidence must be disjoint",path:["counterevidence"]});const a=e.status==="unresolved"||e.status==="confirmed";a&&e.occurrences.length===0&&t.addIssue({code:"custom",message:"actionable candidates require at least one supporting occurrence",path:["occurrences"]}),a&&[...e.occurrences,...e.counterevidence].some(r=>r.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"actionable candidates may contain only currently authorized evidence",path:["occurrences"]}),a!==(e.resolution===null)&&t.addIssue({code:"custom",message:"only resolved, rejected, or expired candidates require a resolution",path:["resolution"]}),e.status==="expired"&&e.resolution?.kind!=="expired"&&t.addIssue({code:"custom",message:"expired candidates require an expired resolution",path:["resolution","kind"]}),e.status==="rejected"&&e.resolution&&!["manual_rejection","source_revoked"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"rejected candidates require a rejection or revocation resolution",path:["resolution","kind"]}),e.status==="resolved"&&e.resolution&&!["applied_change","later_success"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"resolved candidates require applied-change or later-success evidence",path:["resolution","kind"]}),l2(t,e)});a2.extend({contentHash:_e}).strict();const o2=b(["created","merged","rejected","expired","reopened","resolved"]),r2=c({schemaVersion:w("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:ne,candidateId:ne,decision:o2,beforeCandidate:ce.nullable(),afterCandidate:ce,review:ce,addedEvidence:h(ys).max(1e3),removedEvidence:h(ce).max(1e3),reason:Dp,createdAt:Qe}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),Fo(t,e.addedEvidence,"addedEvidence"),Fo(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>um(a)));e.addedEvidence.some(a=>n.has(um(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});r2.extend({contentHash:_e}).strict();const i2=c({schemaVersion:w("openpond.harnessCrossRunRefinementRequest.v1"),id:ne,ownerScope:Mp,workspaceRef:ne,candidate:ce,candidateFingerprint:_e,review:ce,admittedHarness:ce,evidence:h(ys).min(1).max(1e3),capabilities:$p,deduplicationKey:_e,createdAt:Qe}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),Fo(t,e.evidence,"evidence"),Object.values(e.capabilities).some(Boolean)||t.addIssue({code:"custom",message:"cross-run refinement requires at least one available Harness capability",path:["capabilities"]});const n=s2(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});i2.extend({contentHash:_e}).strict();function s2(e){return xt({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function Bh(e,t,n){for(const[a,r]of Object.entries(n))t[a]!==r&&e.addIssue({code:"custom",message:`${a} must be ${String(r)}`,path:[a]})}function Fo(e,t,n){const a=t.map(r=>um(r));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function um(e){if(!e||typeof e!="object"||Array.isArray(e))return String(e);const t=e;if(typeof t.occurrenceKey=="string")return t.occurrenceKey;const n=t.evidence;if(n&&typeof n=="object"&&!Array.isArray(n)){const a=n;return`${String(a.id)}:${String(a.contentHash)}`}return`${String(t.id)}:${String(t.contentHash)}`}function l2(e,t){const n=[["firstSeenAt",t.firstSeenAt],["lastSeenAt",t.lastSeenAt],["lastReviewedAt",t.lastReviewedAt],["updatedAt",t.updatedAt],["expiresAt",t.expiresAt]];for(let a=1;a<n.length;a+=1){const r=n[a-1],i=n[a];Date.parse(r[1])<=Date.parse(i[1])||e.addIssue({code:"custom",message:`${i[0]} must not precede ${r[0]}`,path:[i[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}const c2=c({adapterId:ne,placement:b(["local","remote","colocated","provider_native"]),runtimeVersion:o().trim().min(1).max(200),capabilityReceipt:_e}).strict(),d2=c({maxTurns:d().int().positive().max(1e5),timeoutMs:d().int().positive().max(864e5),maxOutputBytes:d().int().positive().max(25e7),maximumSpendUsd:d().nonnegative().nullable()}).strict(),u2=c({schemaVersion:w("openpond.runManifest.v1"),id:ne,harnessRelease:ce,tasksetRelease:ce,model:or,runtimeTarget:c2,limits:d2,approval:c({id:ne,contentHash:_e}).strict().nullable(),createdAt:Qe,metadata:wt}).strict();u2.extend({contentHash:_e}).strict();const eS=c({schemaVersion:w("openpond.attemptReceipt.v1"),id:ne,runManifest:ce,taskId:ne,seed:o().trim().min(1).max(500),terminal:C(),failureClass:fc.nullable(),outputHash:_e.nullable(),traceHash:_e,artifactRefs:h(Gn).max(1e5),graderEvidenceRefs:h(Gn).max(1e4),startedAt:Qe,completedAt:Qe,latencyMs:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),legacyAttemptRef:ne.nullable().default(null),metadata:wt}).strict(),tS=eS.extend({contentHash:_e}).strict(),m2=c({schemaVersion:w("openpond.evaluationResult.v1"),id:ne,runManifest:ce,harnessRelease:ce,tasksetRelease:ce,model:or,receiptRefs:h(ce).min(1).max(1e6),attemptCount:d().int().positive(),rewardEligibleCount:d().int().nonnegative(),terminalCount:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable(),failureCounts:fe(fc,d().int().nonnegative()),metadata:wt}).strict();m2.extend({contentHash:_e}).strict();const p2=c({schemaVersion:w("openpond.harnessCompatibility.v1"),id:ne,baseHarnessRelease:ce,candidateHarnessRelease:ce,tasksetRelease:ce,environmentHash:_e,toolContractHash:_e,policyHash:_e,graderInterfaceHash:_e,metadata:wt}).strict();p2.extend({contentHash:_e}).strict();function f2(e){const t=tS.safeParse(e);if(!t.success)return!1;const{contentHash:n,...a}=t.data;return xt(eS.parse(a))===n}const Xr=b(["train","validation","test","frozen_eval"]),h2=c({path:o().trim().min(1).max(2e3).refine(w2),mediaType:o().trim().min(1).max(200),schemaRef:Kn.nullable().default(null),maxBytes:d().int().positive().max(25e7).nullable().default(null),metadata:wt}).strict(),g2=c({policyVisibleFields:h(ne).max(1e3).default([]),privilegedFields:h(ne).max(1e3).default([]),hiddenGraderRefs:h(ne).max(1e3).default([]),connectedAppScopes:h(ne).max(100).default([])}).strict(),nS=c({protocolVersion:w("openpond.environment.v1"),kind:b(["text","agent","work","custom_program"]),entrypoint:o().trim().min(1).max(1e3),stateful:C(),deterministicSeeds:C(),lifecycle:h(b(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:d().int().positive().max(36e5)}).strict(),wc=c({id:ne,version:o().trim().min(1).max(100),weight:d().nonnegative().max(1e3).default(1),hardGate:C().default(!1),rewardEligible:C().default(!1),privileged:C().default(!1)}),b2=wc.extend({kind:b(["content","schema","artifact","runtime_event","state"]),config:fe(o(),Se())}).strict(),v2=wc.extend({kind:w("model_judge"),rubricRef:Kn,calibrationStatus:b(["pending","passed","failed"])}).strict(),y2=wc.extend({kind:w("custom_verifier"),verifierRef:Kn,timeoutMs:d().int().positive().max(3e5),networkPolicy:w("none")}).strict(),S2=wc.extend({kind:w("human"),rubricRef:Kn,reviewerRole:o().trim().min(1).max(500)}).strict(),aS=Cn([b2,v2,y2,S2]),x2=c({id:ne,clusterKey:ne,split:Xr,input:fe(o(),Se()),expectedOutput:fe(o(),Se()).nullable(),policyVisibleContext:fe(o(),Se()).default({}),privilegedContextRef:ne.nullable(),artifactRefs:h(Kn).max(1e3).default([]),requiredOutputs:h(h2).max(1e3).optional(),tags:h(ne).max(100).default([])}).strict(),k2=c({schemaVersion:w("openpond.tasksetRelease.v2"),id:ne,revision:d().int().positive(),policy:g2,environment:nS,environmentRelease:c({id:ne,contentHash:_e}).strict().optional(),tools:h(kc).max(200),capabilities:h(Op).max(200),tasks:h(x2).min(1).max(1e6),graders:h(aS).min(1).max(1e3),verifierSetRelease:c({id:ne,contentHash:_e}).strict().optional(),metadata:wt}).strict(),_2=k2.extend({contentHash:_e}).strict();function w2(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}_2.parse({capabilities:[{id:"filesystem.workspace",portability:"host_adapter",required:!0,scopes:["inputs:read","work:read-write","outputs:write"]},{id:"network.web-read",portability:"host_adapter",required:!0,scopes:["search","fetch"]},{id:"artifact.pdf",portability:"host_adapter",required:!0,scopes:["create","render","inspect"]},{id:"artifact.spreadsheet",portability:"host_adapter",required:!0,scopes:["create","calculate","inspect"]}],contentHash:"20e247cec268ecb6380bc7af204abc9056f7eaa90e1e85aa5e11544f2506888d",environment:{defaultTimeoutMs:9e5,deterministicSeeds:!1,entrypoint:"openpond-work-v1",kind:"work",lifecycle:["create","reset","step","collect","destroy"],networkPolicy:"declared_read_only",protocolVersion:"openpond.environment.v1",stateful:!0},graders:[{hardGate:!0,id:"task-output-contract",kind:"custom_verifier",networkPolicy:"none",privileged:!0,rewardEligible:!0,timeoutMs:3e4,verifierRef:{contentHash:"31cda791adf4e55131ee49651431432b429f1404dbc4fa610a3fe1466574f270",id:"verifiers-taskset-output-verifier-mjs",mediaType:"text/javascript",path:"verifiers/taskset-output-verifier.mjs",sizeBytes:2994,visibility:"verifier"},version:"1",weight:1}],id:"harness-refiner-20260818-v2",metadata:{adaptationSplit:"validation",benchmark:"harness-refiner",frozenEvaluationSplit:"frozen_eval",modelJudgeRole:"supplementary_uncalibrated_not_executed",orderSeed:"harness-refiner-20260818-order-v1",primaryMetric:"paired_verified_reward",protocolVersion:"3",qualityPolicy:"complete_frozen_cohort",refinementMode:"sequential_product_lifecycle",resultSchemaVersion:"openpond.harnessRefinerPublicResult.v2",secondaryMetrics:["paired_foreground_provider_tokens"],supplementaryModelJudge:{calibrationStatus:"pending",executable:!1,id:"task-quality-judge",rewardEligible:!1,rubricRef:{contentHash:"455b3697c0617333a34b6521f167760fb8ae7e286059fa2ec327a5c97e66a2b3",id:"rubrics-task-quality-md",mediaType:"text/markdown",path:"rubrics/task-quality.md",sizeBytes:1496,visibility:"verifier"},version:"1"},toolDeclarationSource:"openpond-production-model-tool-definitions",trainingSideEffect:!1},policy:{connectedAppScopes:[],hiddenGraderRefs:["rubrics-task-quality-md","verifiers-taskset-output-verifier-mjs"],policyVisibleFields:["input"],privilegedFields:["expectedOutput"]},revision:2,schemaVersion:"openpond.tasksetRelease.v2",tasks:[{artifactRefs:[{contentHash:"8879f8e31a916f165724a3c3e3e57db5baa858cd170ac6799064aa49bc623aa4",id:"fixtures-adaptation-board-launch-md",mediaType:"text/markdown",path:"fixtures/adaptation-board-launch.md",sizeBytes:642,visibility:"policy"}],clusterKey:"northstar-launch-packet",expectedOutput:{deliverable:"pdf",deterministicContract:{},mustInclude:["three decision options","owners and dates","confirmed facts","open legal and finance gates"],mustNot:["present an open gate as approved","invent a recommended decision"],validation:["structural","visual"]},id:"adaptation-board-launch-brief",input:{attachments:["adaptation-board-launch.md"],prompt:"Please turn the attached Northstar launch packet into a polished two-page PDF decision brief for the executive meeting. Make the three options, owners, dates, confirmed facts, open gates, and risks easy to scan. The source records no final choice, so do not select, recommend, or imply a preferred option. Visually check the finished PDF before you send it back."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-adaptation-board-launch-brief",requiredOutputs:[{maxBytes:1e7,mediaType:"application/pdf",metadata:{validationKinds:["structural","visual"]},path:"adaptation-board-launch-brief.pdf",schemaRef:null}],split:"validation",tags:["artifact-verification","decision-brief","adaptation"]},{artifactRefs:[{contentHash:"a3d44bb123a242d78d0f60d4d8ad352e499bef677eaf816a19d07359a172743f",id:"fixtures-adaptation-latency-incident-md",mediaType:"text/markdown",path:"fixtures/adaptation-latency-incident.md",sizeBytes:733,visibility:"policy"}],clusterKey:"checkout-latency-incident-packet",expectedOutput:{deliverable:"pdf",deterministicContract:{},mustInclude:["incident window","confirmed impact","recovery","hypotheses labeled as hypotheses","unknowns","follow-up owners"],mustNot:["state either hypothesis as root cause","claim unresolved carts were recovered"],validation:["structural","visual"]},id:"adaptation-latency-incident-review",input:{attachments:["adaptation-latency-incident.md"],prompt:"Create a concise PDF incident review from the attached checkout latency packet. Clearly separate confirmed observations, recovery actions, hypotheses, unknowns, customer impact, and follow-up owners. Check that the rendered PDF is readable and complete."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-adaptation-latency-incident-review",requiredOutputs:[{maxBytes:1e7,mediaType:"application/pdf",metadata:{validationKinds:["structural","visual"]},path:"adaptation-latency-incident-review.pdf",schemaRef:null}],split:"validation",tags:["artifact-verification","incident-review","adaptation"]},{artifactRefs:[{contentHash:"63bca96753ae1491a45ba13e1a06cfb48973cfbe4f392e8f181e7b9648fd9db4",id:"fixtures-adaptation-program-budget-md",mediaType:"text/markdown",path:"fixtures/adaptation-program-budget.md",sizeBytes:649,visibility:"policy"}],clusterKey:"harbor-program-budget-packet",expectedOutput:{deliverable:"spreadsheet",deterministicContract:{},mustInclude:["summary sheet","detail sheet","formula-driven full-year forecast","formula-driven variance","owner column","overrun flag"],mustNot:["replace formulas with typed totals","reverse the variance sign"],validation:["structural","test"]},id:"adaptation-program-budget-workbook",input:{attachments:["adaptation-program-budget.md"],prompt:"Build an Excel workbook from the attached Harbor youth program budget. Include a one-page summary and a detail sheet with formulas for full-year forecast and variance, clearly flag forecast overruns, preserve the listed owners, and verify the calculations before returning it."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-adaptation-program-budget-workbook",requiredOutputs:[{maxBytes:1e7,mediaType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",metadata:{validationKinds:["structural","test"]},path:"adaptation-program-budget-workbook.xlsx",schemaRef:null}],split:"validation",tags:["artifact-verification","spreadsheet","adaptation"]},{artifactRefs:[],clusterKey:"northwind-invoice-correction-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["intentional error","deliberate error"],maxWords:130,requiredAny:[["no payment","not due"]],requiredText:["inv-1842","120","102","august 14","accounts@example.com"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","INV-1842","120 seats instead of 102","August 14","no payment due until corrected","accounts@example.com"],mustNot:["suggest the error was intentional","exceed 130 words","return only a checklist or file path instead of the message"],validation:[]},id:"adaptation-invoice-correction-email",input:{attachments:[],prompt:"Draft a courteous email to Northwind Labs explaining that invoice INV-1842 incorrectly lists 120 seats instead of 102. A corrected invoice will arrive by August 14, no payment is due until it arrives, and billing questions should go to accounts@example.com. Keep it under 130 words and do not suggest the error was intentional."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-invoice-correction-email",requiredOutputs:[],split:"validation",tags:["constraint-following","direct-deliverable","communication","adaptation"]},{artifactRefs:[],clusterKey:"nextjs-security-current-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["affected"],["fixed","patched"],["checked","as of"],["version and configuration","version or configuration","exact version"]]},mustInclude:["official advisory links","affected and fixed versions","date checked","limits on exposure inference"],mustNot:["declare exposure without project version and configuration","use an uncited vulnerability list"],validation:[]},id:"adaptation-nextjs-security-audit",input:{attachments:[],prompt:"Audit the currently supported Next.js release lines for security advisories published in the last twelve months. Use primary sources, explain which versions are affected and fixed, avoid inferring that a project is vulnerable without its exact version and configuration, and give me a concise linked report with the date checked."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-nextjs-security-audit",requiredOutputs:[],split:"validation",tags:["research-efficiency","primary-sources","security","adaptation"]},{artifactRefs:[],clusterKey:"juniper-workshop-reschedule-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["venue caused","venue's fault"],maxWords:120,requiredAny:[["facilitator","presenter"],["registration","registrations"]],requiredText:["september 10","2:00","et","recording","events@example.com"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","September 10","2:00 p.m. ET","facilitator unavailable","registrations carry over","recording","events@example.com"],mustNot:["blame the venue","exceed 120 words","return only a checklist or file path instead of the message"],validation:[]},id:"adaptation-workshop-reschedule-email",input:{attachments:[],prompt:"Draft a warm email to Juniper workshop registrants explaining that the September 3 session is moving to September 10 at 2:00 p.m. ET because the facilitator is unavailable. Existing registrations carry over, a recording will be shared, and questions should go to events@example.com. Keep it under 120 words and do not imply the venue caused the change."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-workshop-reschedule-email",requiredOutputs:[],split:"validation",tags:["constraint-following","direct-deliverable","communication","adaptation"]},{artifactRefs:[],clusterKey:"boston-dc-accessibility-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["wheelchair","accessible","accessibility"],["outbound"],["return"],["disruption","service alert"],["checked","as of"],["confirm","confirmation"]],requiredText:["september 17","september 19"]},mustInclude:["official operator sources","outbound and return plan","accessibility details","disruption check","time checked","items needing confirmation"],mustNot:["guarantee availability not confirmed by booking","hide access limitations"],validation:[]},id:"adaptation-accessible-boston-dc-plan",input:{attachments:[],prompt:"Plan a wheelchair-accessible train trip from Boston to Washington, DC for September 17, 2026, returning September 19. Verify accessibility and disruption information from official sources, distinguish facts from anything that still needs confirmation, include direct links and the time checked, and keep the answer practical and concise."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-accessible-boston-dc-plan",requiredOutputs:[],split:"validation",tags:["research-efficiency","current-information","travel","adaptation"]},{artifactRefs:[],clusterKey:"chatgpt-x-reddit-public-sample",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["positive"],["negative"],["anecdote","anecdotal"],["pattern","recurring"],["sampling","sample"],["limitation","access"]]},mustInclude:["links to public examples","dates","positive experiences","negative experiences","pattern versus anecdote","sampling limitations"],mustNot:["post or interact","represent a convenience sample as representative sentiment"],validation:[]},id:"adaptation-chatgpt-public-experiences",input:{attachments:[],prompt:"Research what people have publicly said about using ChatGPT on X and Reddit during the last thirty days. Give me a concise, linked summary of recurring positive and negative experiences, separate patterns from anecdotes, include dates, and explain any platform-access or sampling limitations. Do not post or interact with anyone."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-chatgpt-public-experiences",requiredOutputs:[],split:"validation",tags:["research-efficiency","current-information","social-research","adaptation"]},{artifactRefs:[],clusterKey:"acme-launch-delay-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["testing failed","test failed","compensation"],maxWords:140,requiredAny:[["accessibility testing","accessibility test"],["pilot access"]],requiredText:["august 27","august 22","pilot-support@example.com"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","August 27","accessibility testing incomplete","August 22 expectation","pilot access remains","support email"],mustNot:["say testing failed","exceed 140 words","invent compensation","return only a checklist or file path instead of the message"],validation:[]},id:"adaptation-launch-delay-email",input:{attachments:[],prompt:"Draft a calm email to the Acme pilot customers explaining that the August 20 launch is moving to August 27 because final accessibility testing is not complete. Testing is expected to finish August 22, existing pilot access remains available, and questions should go to pilot-support@example.com. Keep it under 140 words and do not imply the test has failed."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-launch-delay-email",requiredOutputs:[],split:"validation",tags:["constraint-following","direct-deliverable","communication","adaptation"]},{artifactRefs:[],clusterKey:"cirrus-service-window-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["zero interruption","no interruption"],maxWords:125,requiredAny:[["read-only","read only"],["alerts"],["no data loss"]],requiredText:["august 18","1:00","2:00","utc","status.example.com"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","August 18","1:00 to 2:00 UTC","dashboard read-only","alerts continue","no data loss expected","status.example.com"],mustNot:["promise zero interruption","exceed 125 words","return only a checklist or file path instead of the message"],validation:[]},id:"adaptation-service-window-email",input:{attachments:[],prompt:"Draft a calm email to Cirrus customers about planned maintenance on August 18 from 1:00 to 2:00 UTC. The dashboard will be read-only, alerts will continue, no data loss is expected, and updates will appear at status.example.com. Keep it under 125 words and do not promise that there will be zero interruption."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-service-window-email",requiredOutputs:[],split:"validation",tags:["constraint-following","direct-deliverable","communication","adaptation"]},{artifactRefs:[{contentHash:"cb3aec594b140129ebd872c427053ba63a303cc36d160448afc9ed1a0289d3ca",id:"fixtures-frozen-clinic-relocation-md",mediaType:"text/markdown",path:"fixtures/frozen-clinic-relocation.md",sizeBytes:652,visibility:"policy"}],clusterKey:"riverside-clinic-relocation-packet",expectedOutput:{deliverable:"pdf",deterministicContract:{},mustInclude:["three opening options","owners and dates","confirmed facts","permit and parking gates","delivery risk"],mustNot:["present either approval as complete","invent a chosen opening option"],validation:["structural","visual"]},id:"frozen-clinic-relocation-brief",input:{attachments:["frozen-clinic-relocation.md"],prompt:"Please turn the attached Riverside clinic relocation packet into a polished two-page PDF decision brief. Make the opening options, owners, dates, confirmed facts, unresolved approvals, and delivery risk easy to scan, and visually check the finished PDF before returning it."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-frozen-clinic-relocation-brief",requiredOutputs:[{maxBytes:1e7,mediaType:"application/pdf",metadata:{validationKinds:["structural","visual"]},path:"frozen-clinic-relocation-brief.pdf",schemaRef:null}],split:"frozen_eval",tags:["artifact-verification","decision-brief","frozen-eval"]},{artifactRefs:[{contentHash:"80aad04ac67682165f098884fd1a86e9fb3ef15d2da3124401308dd23884b612",id:"fixtures-frozen-payment-incident-md",mediaType:"text/markdown",path:"fixtures/frozen-payment-incident.md",sizeBytes:672,visibility:"policy"}],clusterKey:"subscription-renewal-incident-packet",expectedOutput:{deliverable:"pdf",deterministicContract:{},mustInclude:["incident window","attempt and timeout counts","recovery","hypothesis label","33 unresolved accounts","follow-up owners"],mustNot:["state the certificate hypothesis as confirmed","claim all accounts resolved"],validation:["structural","visual"]},id:"frozen-payment-incident-review",input:{attachments:["frozen-payment-incident.md"],prompt:"Create a concise PDF incident review from the attached subscription renewal incident packet. Separate confirmed impact and recovery from the root-cause hypothesis and unresolved customer accounts, preserve the owners, and check the rendered PDF for readability and completeness."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-frozen-payment-incident-review",requiredOutputs:[{maxBytes:1e7,mediaType:"application/pdf",metadata:{validationKinds:["structural","visual"]},path:"frozen-payment-incident-review.pdf",schemaRef:null}],split:"frozen_eval",tags:["artifact-verification","incident-review","frozen-eval"]},{artifactRefs:[{contentHash:"c58b740d57b031cfe22d475d30b39a1a49a43820f1840a1d8054731cef58c8e8",id:"fixtures-frozen-grant-budget-md",mediaType:"text/markdown",path:"fixtures/frozen-grant-budget.md",sizeBytes:661,visibility:"policy"}],clusterKey:"greenway-grant-budget-packet",expectedOutput:{deliverable:"spreadsheet",deterministicContract:{},mustInclude:["summary sheet","detail sheet","formula-driven full-year forecast","formula-driven variance","owner column","overrun flag"],mustNot:["replace formulas with typed totals","reverse the variance sign"],validation:["structural","test"]},id:"frozen-grant-budget-workbook",input:{attachments:["frozen-grant-budget.md"],prompt:"Build an Excel workbook from the attached Greenway community grant budget. Include a one-page summary and detail sheet with formulas for full-year forecast and variance, flag forecast overruns, preserve owners, and verify all calculations before returning it."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-frozen-grant-budget-workbook",requiredOutputs:[{maxBytes:1e7,mediaType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",metadata:{validationKinds:["structural","test"]},path:"frozen-grant-budget-workbook.xlsx",schemaRef:null}],split:"frozen_eval",tags:["artifact-verification","spreadsheet","frozen-eval"]},{artifactRefs:[],clusterKey:"beacon-shipping-delay-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["equipment is lost","shipment is lost"],maxWords:90,requiredAny:[["transfer window"],["installation","crew"]],requiredText:["august 21","august 22","morgan","logistics"],requireMessageBody:!0},mustInclude:["complete ready-to-post message copy","August 21","carrier missed transfer window","August 22 installation","Morgan","logistics channel"],mustNot:["say the equipment is lost","exceed 90 words","return only a checklist or file path instead of the message"],validation:[]},id:"frozen-shipping-delay-chat-message",input:{attachments:[],prompt:"Write a concise team chat message explaining that the Beacon equipment shipment is now expected August 21 instead of August 19 because the carrier missed its transfer window. The installation crew remains booked for August 22, Morgan owns the carrier follow-up, and the team should flag conflicts in the logistics channel. Keep it under 90 words and do not say the equipment is lost."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-shipping-delay-chat-message",requiredOutputs:[],split:"frozen_eval",tags:["constraint-following","direct-deliverable","communication","frozen-eval"]},{artifactRefs:[],clusterKey:"python-requests-security-current-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["affected"],["fixed","patched"],["checked","as of"],["dependency graph","exact dependency","usage"]]},mustInclude:["primary advisory links","affected and fixed versions","date checked","dependency and usage caveat"],mustNot:["declare deployment exposure without evidence","use an uncited vulnerability list"],validation:[]},id:"frozen-python-requests-security-audit",input:{attachments:[],prompt:"Audit the supported Python Requests release lines for security advisories published in the last eighteen months. Use primary sources, identify affected and fixed versions, avoid claiming a specific deployment is exposed without its exact dependency graph and usage, and provide a concise linked report with the date checked."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-python-requests-security-audit",requiredOutputs:[],split:"frozen_eval",tags:["research-efficiency","primary-sources","security","frozen-eval"]},{artifactRefs:[],clusterKey:"cobalt-refund-support-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["refund is approved","refund has been approved"],maxWords:110,requiredAny:[["original payment method"],["duplicate","charge"]],requiredText:["$48","august 16","five business days","cb-7714"],requireMessageBody:!0},mustInclude:["complete send-ready reply copy","$48 duplicate charge","August 16","original payment method","five business days","CB-7714"],mustNot:["state the refund is already approved","exceed 110 words","return only a checklist or file path instead of the message"],validation:[]},id:"frozen-refund-support-reply",input:{attachments:[],prompt:"Write a helpful support reply to a Cobalt customer whose duplicate $48 charge is being reviewed. The review should finish by August 16, any confirmed duplicate will be refunded to the original payment method within five business days, and the case number is CB-7714. Keep it under 110 words and do not state that the refund has already been approved."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-refund-support-reply",requiredOutputs:[],split:"frozen_eval",tags:["constraint-following","direct-deliverable","communication","frozen-eval"]},{artifactRefs:[],clusterKey:"chicago-stl-accessibility-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["wheelchair","accessible","accessibility"],["outbound"],["return"],["disruption","service alert"],["checked","as of"],["confirm","confirmation"]],requiredText:["october 8","october 10"]},mustInclude:["official operator sources","outbound and return plan","accessibility details","disruption check","time checked","items needing confirmation"],mustNot:["guarantee unconfirmed availability","hide access limitations"],validation:[]},id:"frozen-accessible-chicago-stl-plan",input:{attachments:[],prompt:"Plan a wheelchair-accessible train trip from Chicago to St. Louis for October 8, 2026, returning October 10. Verify accessibility and disruption information from official sources, distinguish confirmed facts from anything requiring booking confirmation, include direct links and the time checked, and keep it practical."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-accessible-chicago-stl-plan",requiredOutputs:[],split:"frozen_eval",tags:["research-efficiency","current-information","travel","frozen-eval"]},{artifactRefs:[],clusterKey:"new-jersey-youth-grant-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["new jersey","nj"],["eligibility","eligible"],["deadline","due"],["checked","as of"]]},mustInclude:["authoritative source links","eligibility evidence","deadlines","date checked","only realistic matches"],mustNot:["include closed grants","include grants without verified nonprofit and program eligibility","pad the list"],validation:[]},id:"frozen-new-jersey-youth-grants",input:{attachments:[],prompt:"Find currently open grants that a New Jersey nonprofit running after-school programs could realistically apply for, with deadlines between now and December 31, 2026. Use authoritative sources, link each opportunity, verify eligibility and deadline, omit weak matches instead of padding the list, and state when you checked."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-new-jersey-youth-grants",requiredOutputs:[],split:"frozen_eval",tags:["research-efficiency","current-information","funding","frozen-eval"]},{artifactRefs:[],clusterKey:"maple-maintenance-followup-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["sue","lawsuit","legal action"],maxWords:130,requiredAny:[["repair date","repair schedule"]],requiredText:["july 28","august 1","security","two business days"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","July 28","August 1 inspection","security concern","repair date within two business days"],mustNot:["make a legal threat","claim facts not supplied","exceed 130 words","return only a checklist or file path instead of the message"],validation:[]},id:"frozen-maintenance-followup-email",input:{attachments:[],prompt:"Draft a firm but courteous email to Maple Property Management following up on a bedroom window that has not closed securely since July 28. Maintenance inspected it August 1 but did not repair it. Ask for a repair date within two business days, mention the security concern, and keep the email under 130 words without making legal threats."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-maintenance-followup-email",requiredOutputs:[],split:"frozen_eval",tags:["constraint-following","direct-deliverable","communication","frozen-eval"]},{artifactRefs:[],clusterKey:"meridian-vendor-document-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["cancel the contract","contract cancellation"],maxWords:120,requiredAny:[["onboarding","cannot finish","blocked"]],requiredText:["insurance certificate","august 7","rosa","august 12"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","insurance certificate","August 7","onboarding blocked","Rosa","August 12"],mustNot:["threaten contract cancellation","exceed 120 words","return only a checklist or file path instead of the message"],validation:[]},id:"frozen-vendor-document-followup-email",input:{attachments:[],prompt:"Draft a firm but professional email to Meridian Freight following up on the insurance certificate promised for August 7. It has not arrived, carrier onboarding cannot finish without it, and Rosa needs the document or a confirmed delivery date by August 12. Keep it under 120 words and do not threaten to cancel the contract."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-vendor-document-followup-email",requiredOutputs:[],split:"frozen_eval",tags:["constraint-following","direct-deliverable","communication","frozen-eval"]}],tools:[{description:"Start Work compute only when it is needed, then return live sandbox status and the stable /workspace/inputs, /workspace/work, and /workspace/outputs layout.",inputSchema:{additionalProperties:!1,properties:{},type:"object"},inputSchemaHash:"042b35e50dd5dd505f0228e829f17a8aeaae50e49d865c4754cf9ba1edba9bd0",name:"work_environment",sideEffect:"write",timeoutMs:12e4},{description:"List files in the Work scratch, input, or completed-output area. This lazily starts Work compute.",inputSchema:{additionalProperties:!1,properties:{area:{enum:["inputs","work","outputs"],type:"string"},path:{description:"Optional relative path inside the selected area.",type:"string"},recursive:{type:"boolean"}},required:["area"],type:"object"},inputSchemaHash:"a3a68e8aeb4f23710aa21fe95d4a361a14c08bcbb61a2a959a60b7b00c82807f",name:"work_list_files",sideEffect:"read",timeoutMs:12e4},{description:"Read a bounded file from Work inputs, scratch space, or completed-output candidates.",inputSchema:{additionalProperties:!1,properties:{area:{enum:["inputs","work","outputs"],type:"string"},maxBytes:{maximum:1e6,minimum:1,type:"integer"},path:{minLength:1,type:"string"}},required:["area","path"],type:"object"},inputSchemaHash:"deb9cd248f2734751286054c381ac9572b248370181970ced6563a73c905a4f0",name:"work_read_file",sideEffect:"read",timeoutMs:12e4},{description:"Write a UTF-8 Work scratch file or completed-output candidate. Use area=outputs only for a finished result that is ready to validate and save.",inputSchema:{additionalProperties:!1,properties:{area:{enum:["work","outputs"],type:"string"},content:{type:"string"},path:{minLength:1,type:"string"}},required:["area","path","content"],type:"object"},inputSchemaHash:"6a19df98686e99a324564006b0b92082f185ac4b430e9285829f781251dd145b",name:"work_write_file",sideEffect:"write",timeoutMs:12e4},{description:"Edit a Work scratch file or output candidate by exact text replacement after reading it.",inputSchema:{additionalProperties:!1,properties:{area:{enum:["work","outputs"],type:"string"},newText:{type:"string"},oldText:{minLength:1,type:"string"},path:{minLength:1,type:"string"},replaceAll:{type:"boolean"}},required:["area","path","oldText","newText"],type:"object"},inputSchemaHash:"f507d9d9abbd8cf1556f6e925c159234295c3fa01800c5556767f96be8b011db",name:"work_edit_file",sideEffect:"write",timeoutMs:12e4},{description:"Run a bounded shell command from /workspace/work. Write finished deliverables to ../outputs and inspect them; the runtime preserves output files automatically when the turn ends.",inputSchema:{additionalProperties:!1,properties:{command:{minLength:1,type:"string"},timeoutSeconds:{maximum:3600,minimum:1,type:"integer"}},required:["command"],type:"object"},inputSchemaHash:"5ba3a52cddb3f575218bed855020e91eef14092d75922c963a24c6bc97fadeda",name:"work_exec",sideEffect:"write",timeoutMs:3e5},{description:"Explicitly copy one completed file from /workspace/outputs to durable OpenPond output storage before turn completion. Normal Work turns preserve output files automatically.",inputSchema:{additionalProperties:!1,properties:{path:{description:"Path relative to /workspace/outputs, for example report.md.",minLength:1,type:"string"},suggestedName:{maxLength:180,minLength:1,type:"string"},validation:{items:{additionalProperties:!1,properties:{detail:{maxLength:4e3,type:"string"},kind:{enum:["structural","visual","test","user_review"],type:"string"},label:{maxLength:240,minLength:1,type:"string"},ref:{maxLength:4096,type:"string"},status:{enum:["passed","failed","not_run"],type:"string"}},required:["kind","status","label"],type:"object"},maxItems:32,type:"array"}},required:["path"],type:"object"},inputSchemaHash:"ca853f64b300c74441b522db03facbcc9c5bb89c86189dae24182bab39510a83",name:"work_save_output",sideEffect:"write",timeoutMs:12e4},{description:"Stop Work compute after durable outputs have been saved. Saved OutputRefs remain available.",inputSchema:{additionalProperties:!1,properties:{},type:"object"},inputSchemaHash:"042b35e50dd5dd505f0228e829f17a8aeaae50e49d865c4754cf9ba1edba9bd0",name:"work_stop",sideEffect:"write",timeoutMs:12e4},{description:"Search the web for current or external information. The app renders clickable source pills automatically. Cite by source title or source name in prose by default; when the user explicitly requests URLs or linked evidence, use the result URLs in clickable Markdown links.",inputSchema:{additionalProperties:!1,properties:{domains:{description:"Optional domain filters.",items:{type:"string"},maxItems:10,type:"array"},limit:{description:"Maximum number of results to return.",maximum:10,minimum:1,type:"integer"},query:{description:"Search query.",minLength:1,type:"string"},recencyDays:{description:"Only return results from this many recent days when supported.",minimum:0,type:"integer"}},required:["query"],type:"object"},inputSchemaHash:"2a138bf9b526a624ac2442669fccb277fac2ba818821b3a2da1dd27d62954056",name:"web_search",sideEffect:"read",timeoutMs:12e4},{description:"Fetch and extract readable text from a known HTTP(S) URL. Use this when the user provides a URL or a search result has an exact page to inspect; use web_search when discovering unknown pages by query.",inputSchema:{additionalProperties:!1,properties:{maxBytes:{description:"Maximum UTF-8 bytes of extracted text to return. Defaults to 20000.",maximum:1e5,minimum:1,type:"integer"},url:{description:"HTTP or HTTPS URL to fetch.",minLength:1,type:"string"}},required:["url"],type:"object"},inputSchemaHash:"0afe31d8dbe05643e4a19ca0897c606e379f37d741b4f61816ad8ba4d48b61b3",name:"web_fetch",sideEffect:"read",timeoutMs:12e4}]});const oS=b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),rS=b(["baseline","candidate"]),I2=c({split:Xr,taskIds:h(ne).min(1).max(1e5),seeds:h(o().trim().min(1).max(500)).min(1).max(100),repetitions:d().int().positive().max(20),runtimeTargetHash:_e,environmentHash:_e,toolContractHash:_e,limitsHash:_e}).strict();c({schemaVersion:w("openpond.benchmarkDefinition.v1"),id:ne,title:o().trim().min(1).max(500),description:o().trim().min(1).max(5e3),tasksetRelease:ce,adaptationSplit:Xr,evaluationSplit:Xr,primaryMetric:oS,qualityGate:b(["none","non_regression","all_pass"]),caseCounts:c({adaptation:d().int().nonnegative(),evaluation:d().int().positive()}).strict(),metadata:wt}).strict();c({schemaVersion:w("openpond.benchmarkRunRequest.v1"),phase:rS,model:or,reasoningEffort:o().trim().min(1).max(100).nullable(),split:Xr,seeds:h(o().trim().min(1).max(500)).min(1).max(100),repetitions:d().int().positive().max(20),metadata:wt}).strict();const C2=c({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative()}).strict(),R2=c({schemaVersion:w("openpond.benchmarkRunSummary.v1"),id:ne,phase:rS,tasksetRelease:ce,harnessRelease:ce,evaluationResult:ce,model:or,reasoningEffort:o().trim().min(1).max(100).nullable(),protocol:I2,attemptCount:d().int().positive(),passedCount:d().int().nonnegative(),terminalCount:d().int().nonnegative(),usage:C2,costUsd:d().nonnegative().nullable(),latencyMs:d().int().nonnegative(),createdAt:Qe,metadata:wt}).strict();R2.extend({contentHash:_e}).strict();const A2=c({schemaVersion:w("openpond.benchmarkComparison.v1"),id:ne,baseline:ce,candidate:ce,tasksetRelease:ce,primaryMetric:oS,qualityPassed:C(),baselinePassRate:d().min(0).max(1),candidatePassRate:d().min(0).max(1),foregroundTokenDelta:d().int(),foregroundTokenDeltaPercent:d().finite().nullable(),improved:C(),createdAt:Qe,metadata:wt}).strict();A2.extend({contentHash:_e}).strict();const Lp=b(["scored","unscorable"]),Ic=b(["policy","environment","collector","verifier","provider","host","user","scheduler"]),iS=b(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),P2=c({schemaVersion:w("openpond.environmentRelease.v1"),id:ne,revision:d().int().positive(),contract:nS,actionSchemaRef:Kn.nullable(),observationSchemaRef:Kn.nullable(),stateSchemaRef:Kn.nullable(),artifactCollection:c({maxArtifacts:d().int().positive().max(1e5),maxTotalBytes:d().int().positive().max(1e10)}).strict(),adapterConformanceHashes:fe(ne,_e),metadata:wt}).strict();P2.extend({contentHash:_e}).strict();const T2=b(["collected","missing","skipped","failed"]),Fh=b(["not_requested","passed","failed"]),E2=c({requiredOutputPath:o().trim().min(1).max(2e3).nullable(),collectedPath:o().trim().min(1).max(4e3).nullable(),declaredMediaType:o().trim().min(1).max(200).nullable(),detectedMediaType:o().trim().min(1).max(200).nullable(),artifact:Gn.nullable(),status:T2,parseStatus:Fh,schemaStatus:Fh,errorCode:ne.nullable(),failureOwner:Ic.nullable(),evidenceRefs:h(Gn).max(1e4),metadata:wt}).strict(),M2=c({schemaVersion:w("openpond.artifactManifest.v1"),id:ne,attemptRef:ce,entries:h(E2).max(1e5),createdAt:Qe,metadata:wt}).strict();M2.extend({contentHash:_e}).strict();const j2=c({schemaVersion:w("openpond.verifierSetRelease.v1"),id:ne,revision:d().int().positive(),graders:h(aS).min(1).max(1e3),isolation:c({processBoundary:b(["same_process","isolated_process","container"]),networkPolicy:w("none"),defaultTimeoutMs:d().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:h(ce).max(1e4),metadata:wt}).strict();j2.extend({contentHash:_e}).strict();const O2=c({verifierId:ne,verifierVersion:o().trim().min(1).max(100),status:Lp,rawScore:d().finite().nullable(),normalizedScore:d().min(0).max(1).nullable(),weight:d().nonnegative().max(1e3),passed:C(),hardGate:C(),rewardEligible:C(),rewardContribution:d().min(0).max(1).nullable(),failureOwner:Ic.nullable(),feedback:h(o().max(2e4)).max(1e3),visibleEvidenceRefs:h(Gn).max(1e4),privilegedEvidenceRefs:h(Gn).max(1e4),metadata:wt}).strict().superRefine((e,t)=>{e.status==="scored"&&e.normalizedScore===null&&t.addIssue({code:"custom",message:"A scored component requires a normalized score.",path:["normalizedScore"]}),e.status==="unscorable"&&(e.normalizedScore!==null||e.rewardEligible)&&t.addIssue({code:"custom",message:"An unscorable component cannot contribute reward.",path:["status"]})}),sS=c({schemaVersion:w("openpond.rewardReceipt.v1"),id:ne,attemptRef:ce,verifierSetRef:ce,artifactManifestRef:ce,status:Lp,reward:d().min(0).max(1).nullable(),learningEligible:C(),passed:C(),outcomeClass:iS,failureOwner:Ic.nullable(),components:h(O2).min(1).max(1e4),visibleEvidenceRefs:h(Gn).max(1e5),privilegedEvidenceRefs:h(Gn).max(1e5),supersedes:ce.nullable(),createdAt:Qe,metadata:wt}).strict();function lS(e,t){e.status==="scored"&&(e.reward===null||!e.learningEligible)&&t.addIssue({code:"custom",message:"A scored receipt requires a reward and is learning-eligible.",path:["status"]}),e.status==="unscorable"&&(e.reward!==null||e.learningEligible)&&t.addIssue({code:"custom",message:"An unscorable receipt has null reward and is not learning-eligible.",path:["status"]})}sS.superRefine(lS);sS.extend({contentHash:_e}).strict().superRefine(lS);const N2="openpond.workEvidenceReceipt.v1",$2="openpond.workProcessTrace.v1",D2="openpond.workFeedbackReceipt.v1",cS="openpond.workEvidenceEligibility.v1",L2=o().regex(/^urn:openpond:work:[a-f0-9]{64}$/,"Work source references must be opaque SHA-256 URNs."),z2=o().regex(/^urn:openpond:workspace:[a-f0-9]{64}$/,"Workspace references must be opaque SHA-256 URNs."),U2=o().regex(/^urn:openpond:artifact:[a-f0-9]{64}$/,"Evidence artifacts must use content-addressed SHA-256 URNs."),wn=Gn.extend({id:U2}).strict().superRefine((e,t)=>{e.id!==fS(e.contentHash)&&t.addIssue({code:"custom",message:"Evidence artifact id must contain its content hash.",path:["id"]})}),H2=b(["tool","validation","state_transition","approval","question","artifact","cleanup"]),q2=b(["agent","environment"]),B2=b(["turn_started","turn_completed","turn_failed","turn_cancelled","turn_timed_out","tool_invoked","tool_completed","tool_failed","validation_completed","validation_failed","approval_requested","approval_resolved","question_asked","question_answered","question_dismissed","artifact_created","workspace_changed","environment_created","environment_reset","environment_destroyed","cleanup_completed","cleanup_failed"]),F2=b(["started","completed","failed","cancelled"]),V2=b(["filesystem","source_control","command","browser","connected_app","sandbox","agent","other"]),W2=b(["structural","visual","test","user_review","other"]),K2=b(["running","completed","failed","cancelled","timeout"]),G2=b(["requested","approved","denied","answered","dismissed"]),Z2=b(["policy","validation","environment","infrastructure","timeout","cancelled","unknown"]),J2=b(["missing_start","missing_terminal","source_truncated","unsupported_events_dropped","uncorrelated_environment_step","artifact_unavailable"]),Y2=c({sequence:d().int().nonnegative().max(1e6),timestamp:Qe,layer:q2,kind:H2,action:B2,status:F2,inputHash:_e.nullable(),outputHash:_e.nullable(),receiptHash:_e.nullable(),parentReceiptHash:_e.nullable(),artifactRefs:h(wn).max(1e3),attributes:c({toolCategory:V2.nullable(),validationKind:W2.nullable(),transitionState:K2.nullable(),interventionOutcome:G2.nullable(),artifactCount:d().int().nonnegative().max(1e5),exitCode:d().int().min(-1).max(255).nullable(),durationMs:d().int().nonnegative().max(31536e6).nullable(),cpuTimeMs:d().int().nonnegative().max(31536e6).nullable(),memoryPeakBytes:d().int().nonnegative().max(0x4000000000000).nullable(),errorClass:Z2.nullable()}).strict()}).strict().superRefine((e,t)=>{e.layer==="agent"&&e.parentReceiptHash!==null&&t.addIssue({code:"custom",message:"Agent-layer steps cannot have a parent environment correlation.",path:["parentReceiptHash"]}),e.layer==="environment"&&e.parentReceiptHash===null&&t.addIssue({code:"custom",message:"Environment steps must correlate to an Agent receipt.",path:["parentReceiptHash"]})}),dS=c({schemaVersion:w($2),sourceRevisionHash:_e,sanitationPolicyVersion:ne,incomplete:C(),incompleteReasons:h(J2).max(10),droppedEventCount:d().int().nonnegative().max(1e6),steps:h(Y2).max(1e5)}).strict().superRefine((e,t)=>{e.incomplete!==e.incompleteReasons.length>0&&t.addIssue({code:"custom",message:"incomplete must match the presence of incompleteReasons.",path:["incomplete"]});for(let n=0;n<e.steps.length;n+=1)e.steps[n].sequence!==n&&t.addIssue({code:"custom",message:"Process trace sequences must be contiguous and zero-based.",path:["steps",n,"sequence"]})}),X2=dS.safeExtend({contentHash:_e}).strict(),Q2=b(["policy_failure","validation_failure","model_failure","environment_failure","infrastructure_failure","timeout","cancelled","unknown"]),eN=c({status:b(["completed","failed","cancelled","timeout"]),failureClass:Q2.nullable()}).strict().superRefine((e,t)=>{e.status==="completed"&&e.failureClass!==null&&t.addIssue({code:"custom",message:"Completed Work cannot carry a failure class.",path:["failureClass"]}),e.status!=="completed"&&e.failureClass===null&&t.addIssue({code:"custom",message:"Non-completed Work requires a failure class.",path:["failureClass"]}),e.status==="cancelled"&&e.failureClass!=="cancelled"&&t.addIssue({code:"custom",message:"Cancelled Work must use the cancelled failure class.",path:["failureClass"]}),e.status==="timeout"&&e.failureClass!=="timeout"&&t.addIssue({code:"custom",message:"Timed-out Work must use the timeout failure class.",path:["failureClass"]})}),zp=c({schemaVersion:w(N2),id:o().regex(/^work-evidence-[a-f0-9]{24}$/),source:c({surface:b(["desktop","hosted"]),experience:b(["work","development"]),opaqueRef:L2,revisionHash:_e}).strict(),agentSnapshot:ce.nullable(),model:or,runtime:c({adapterId:ne,adapterVersion:ne,capabilityRef:wn.nullable()}).strict(),inputHash:_e,terminal:eN,trace:c({sanitizedRef:wn,traceHash:_e,sanitationPolicyVersion:ne,incomplete:C()}).strict(),outputRefs:h(wn).max(1e4),artifactRefs:h(wn).max(1e5),validationEvidenceRefs:h(wn).max(1e4),interventions:c({approvals:d().int().nonnegative().max(1e6),questions:d().int().nonnegative().max(1e6),steeringEvents:d().int().nonnegative().max(1e6),otherUserInterventions:d().int().nonnegative().max(1e6)}).strict(),timing:c({startedAt:Qe,completedAt:Qe,latencyMs:d().int().nonnegative().max(31536e6)}).strict(),usage:c({promptTokens:d().int().nonnegative().nullable(),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable()}).strict(),costUsd:d().nonnegative().max(1e6).nullable(),provenance:c({consentReceiptRef:wn,consentScope:w("work_process_and_artifacts"),consentGrantedAt:Qe,policyVersion:ne,projectorVersion:ne,disclosure:w("portable_sanitized"),ownershipScope:b(["personal","workspace"]),workspaceRef:z2.nullable(),participantPolicy:b(["creator_only","all_participants"]),retention:c({policy:w("source_bound"),deleteWithSource:w(!0),expiresAt:Qe.nullable()}).strict()}).strict()}).strict().superRefine((e,t)=>{e.trace.traceHash!==e.trace.sanitizedRef.contentHash&&t.addIssue({code:"custom",message:"Sanitized trace reference must bind traceHash.",path:["trace","traceHash"]});const n=Date.parse(e.timing.completedAt)-Date.parse(e.timing.startedAt);(n<0||n!==e.timing.latencyMs)&&t.addIssue({code:"custom",message:"latencyMs must equal completedAt minus startedAt.",path:["timing","latencyMs"]}),e.provenance.ownershipScope==="workspace"&&e.provenance.workspaceRef===null&&t.addIssue({code:"custom",message:"Workspace-owned evidence requires workspaceRef.",path:["provenance","workspaceRef"]}),e.provenance.ownershipScope==="personal"&&e.provenance.workspaceRef!==null&&t.addIssue({code:"custom",message:"Personal evidence cannot carry workspaceRef.",path:["provenance","workspaceRef"]}),bu(e.outputRefs,["outputRefs"],t),bu(e.artifactRefs,["artifactRefs"],t),bu(e.validationEvidenceRefs,["validationEvidenceRefs"],t)}),uS=zp.safeExtend({contentHash:_e}).strict(),tN=b(["accepted","needs_correction","not_useful"]),nN=b(["correct","complete","high_quality","incorrect","incomplete","wrong_format","unsafe","stale","irrelevant","other"]),mS=c({schemaVersion:w(D2),id:o().regex(/^work-feedback-[a-f0-9]{24}$/),evidenceReceiptRef:wn,outputRevisionRef:wn.nullable(),verdict:tN,reasonCodes:h(nN).max(16),correctionRef:wn.nullable(),correctedOutputRevisionRef:wn.nullable(),actor:w("user"),createdAt:Qe}).strict().superRefine((e,t)=>{new Set(e.reasonCodes).size!==e.reasonCodes.length&&t.addIssue({code:"custom",message:"Feedback reason codes must be unique.",path:["reasonCodes"]}),e.verdict!=="needs_correction"&&(e.correctionRef||e.correctedOutputRevisionRef)&&t.addIssue({code:"custom",message:"Only needs_correction feedback may bind correction artifacts.",path:["verdict"]})}),pS=mS.safeExtend({contentHash:_e}).strict();function fS(e){return`urn:openpond:artifact:${e}`}function aN(e){return`urn:openpond:work:${xt(e)}`}function qs(e){return wn.parse({id:fS(e.contentHash),contentHash:e.contentHash,mediaType:e.mediaType??null,sizeBytes:e.sizeBytes??null})}function hS(e){const t=dS.parse(e);return X2.parse({...t,contentHash:xt(t)})}function oN(e){const t=zp.parse(e);return uS.parse({...t,contentHash:xt(t)})}function gS(e,t){const n=mS.parse(e),a=pS.parse({...n,contentHash:xt(n)});return t&&sN(a,t),a}function rN(e){return lN(e,uS,zp)}function iN(e){return qs({contentHash:e.contentHash,mediaType:"application/vnd.openpond.work-evidence+json",sizeBytes:null})}function sN(e,t){if(e.evidenceReceiptRef.contentHash!==t.contentHash)throw new Error("Feedback targets a different Work evidence receipt.");if(e.outputRevisionRef&&!t.outputRefs.some(n=>n.contentHash===e.outputRevisionRef.contentHash))throw new Error("Feedback targets an output revision not bound by the Work evidence receipt.")}function lN(e,t,n){const a=t.safeParse(e);if(!a.success)return!1;const{contentHash:r,...i}=a.data;return xt(n.parse(i))===r}function bu(e,t,n){const a=e.map(r=>r.contentHash);new Set(a).size!==a.length&&n.addIssue({code:"custom",message:"Artifact content hashes must be unique.",path:t})}const cN=b(["active","revoked","deleted","expired"]);b(["discovery_only","eval_candidate","demonstration_candidate","preference_candidate","reward_candidate"]);const dN=b(["invalid_evidence_receipt","consent_revoked","source_deleted","retention_expired","trace_incomplete","terminal_not_completed","infrastructure_failure","agent_snapshot_missing","input_not_reconstructable","environment_not_reconstructable","output_missing","validation_evidence_missing","verifier_missing","accepted_feedback_missing","correction_pair_missing","attempt_receipt_missing","attempt_receipt_invalid","attempt_receipt_unbound","attempt_not_reward_eligible"]),Tr=c({eligible:C(),blockers:h(dN).max(32)}).strict().superRefine((e,t)=>{e.eligible===e.blockers.length>0&&t.addIssue({code:"custom",message:"Eligibility must be the inverse of blocker presence."})}),bS=c({schemaVersion:w(cS),evidenceReceiptHash:_e,policyState:cN,decisions:c({discovery_only:Tr,eval_candidate:Tr,demonstration_candidate:Tr,preference_candidate:Tr,reward_candidate:Tr}).strict()}).strict(),uN=bS.extend({contentHash:_e}).strict();function vS(e){const t=rN(e.evidence),n=(e.feedback??[]).filter(x=>{if(!pS.safeParse(x).success)return!1;try{return gS(pN(x),e.evidence),!0}catch{return!1}}),a=mN(e.policyState),r=[...t?[]:["invalid_evidence_receipt"],...a],i=[...r,...e.evidence.trace.incomplete?["trace_incomplete"]:[],...e.evidence.agentSnapshot?[]:["agent_snapshot_missing"],...e.reconstructability.input?[]:["input_not_reconstructable"],...e.reconstructability.environment?[]:["environment_not_reconstructable"],...e.evidence.outputRefs.length?[]:["output_missing"],...e.reconstructability.verifier?[]:["verifier_missing"]],s=e.evidence.terminal.status==="completed",l=n.some(x=>x.verdict==="accepted"),p=[...i,...s?[]:["terminal_not_completed"],...e.evidence.terminal.failureClass==="infrastructure_failure"?["infrastructure_failure"]:[],...e.evidence.validationEvidenceRefs.length?[]:["validation_evidence_missing"],...l?[]:["accepted_feedback_missing"]],m=new Set(n.filter(x=>x.verdict==="accepted").flatMap(x=>x.outputRevisionRef?.contentHash??[])),f=n.some(x=>x.verdict==="needs_correction"&&x.outputRevisionRef!==null&&x.correctedOutputRevisionRef!==null&&m.has(x.correctedOutputRevisionRef.contentHash)),S=[...i,...f?[]:["correction_pair_missing"]],y=e.replay??null,k=y?tS.safeParse(y.attemptReceipt):null,R=k?.success===!0&&f2(k.data),A=y?.sourceEvidenceReceiptHash===e.evidence.contentHash,D=R&&A&&y.attemptReceipt.terminal&&y.attemptReceipt.failureClass!=="infrastructure_failure"&&y.attemptReceipt.failureClass!=="timeout"&&y.attemptReceipt.failureClass!=="cancelled"&&y.attemptReceipt.metadata.rewardEligible===!0&&typeof y.attemptReceipt.metadata.score=="number",z=[...r,...y?[]:["attempt_receipt_missing"],...y&&!R?["attempt_receipt_invalid"]:[],...y&&!A?["attempt_receipt_unbound"]:[],...y&&R&&A&&!D?["attempt_not_reward_eligible"]:[]],N=bS.parse({schemaVersion:cS,evidenceReceiptHash:e.evidence.contentHash,policyState:e.policyState,decisions:{discovery_only:ts(r),eval_candidate:ts(i),demonstration_candidate:ts(p),preference_candidate:ts(S),reward_candidate:ts(z)}});return uN.parse({...N,contentHash:xt(N)})}function mN(e){return e==="revoked"?["consent_revoked"]:e==="deleted"?["source_deleted"]:e==="expired"?["retention_expired"]:[]}function ts(e){const t=[...new Set(e)];return Tr.parse({eligible:t.length===0,blockers:t})}function pN(e){const{contentHash:t,...n}=e;return n}c({schemaVersion:w("openpond.workEvidenceAuthoringInput.v1"),evidenceReceiptRef:wn,inputHash:_e,agentSnapshot:ce.nullable(),sanitizedTraceRef:wn,outputRefs:h(wn).max(1e4),validationEvidenceRefs:h(wn).max(1e4),incomplete:C(),evalCandidate:C(),blockerCodes:h(o().trim().min(1).max(120)).max(32)}).strict();const Ss="2026-08-04T12:00:00.000Z",yS="2026-08-04T12:00:02.500Z",mm=xt({fixture:"desktop-work",revision:1}),xs=qs({contentHash:xt("fixture output"),mediaType:"text/plain",sizeBytes:14}),SS=qs({contentHash:xt({kind:"test",status:"passed"}),mediaType:"application/json",sizeBytes:null}),fN=qs({contentHash:xt({scope:"work_process_and_artifacts",grantedAt:Ss}),mediaType:"application/json",sizeBytes:null}),Up=hS({schemaVersion:"openpond.workProcessTrace.v1",sourceRevisionHash:mm,sanitationPolicyVersion:"openpond.desktop-work-sanitizer.v1",incomplete:!1,incompleteReasons:[],droppedEventCount:1,steps:[Er(0,Ss,"agent","state_transition","turn_started","started",{transitionState:"running"}),Er(1,"2026-08-04T12:00:00.500Z","agent","tool","tool_invoked","started",{toolCategory:"filesystem",inputHash:xt({path:"hashed-only"}),receiptHash:xt("fixture-tool-call")}),Er(2,"2026-08-04T12:00:01.000Z","environment","artifact","artifact_created","completed",{outputHash:xs.contentHash,artifacts:[xs],receiptHash:xt("fixture-environment-operation"),parentReceiptHash:xt("fixture-tool-call")}),Er(3,"2026-08-04T12:00:01.500Z","environment","validation","validation_completed","completed",{validationKind:"test",outputHash:SS.contentHash,receiptHash:xt("fixture-validation"),parentReceiptHash:xt("fixture-tool-call")}),Er(4,yS,"agent","state_transition","turn_completed","completed",{transitionState:"completed"})]}),hN=new TextEncoder().encode(o0(Up)).byteLength,vu=qs({contentHash:Up.contentHash,mediaType:"application/vnd.openpond.work-process-trace+json",sizeBytes:hN}),Ko=oN({schemaVersion:"openpond.workEvidenceReceipt.v1",id:`work-evidence-${xt([mm,vu.contentHash]).slice(0,24)}`,source:{surface:"desktop",experience:"work",opaqueRef:aN(["fixture-session","fixture-turn"]),revisionHash:mm},agentSnapshot:{id:"fixture-agent-snapshot",contentHash:xt("fixture-agent")},model:{provider:"fixture",model:"scripted",revision:"1",artifactHash:null,tokenizerRevision:null,chatTemplateHash:null},runtime:{adapterId:"desktop-work",adapterVersion:"1",capabilityRef:null},inputHash:xt("fixture prompt"),terminal:{status:"completed",failureClass:null},trace:{sanitizedRef:vu,traceHash:vu.contentHash,sanitationPolicyVersion:Up.sanitationPolicyVersion,incomplete:!1},outputRefs:[xs],artifactRefs:[xs],validationEvidenceRefs:[SS],interventions:{approvals:0,questions:0,steeringEvents:0,otherUserInterventions:0},timing:{startedAt:Ss,completedAt:yS,latencyMs:2500},usage:{promptTokens:12,completionTokens:8,totalTokens:20},costUsd:0,provenance:{consentReceiptRef:fN,consentScope:"work_process_and_artifacts",consentGrantedAt:Ss,policyVersion:"openpond.work-evidence-policy.v1",projectorVersion:"openpond.desktop-work-evidence-projector.v1",disclosure:"portable_sanitized",ownershipScope:"personal",workspaceRef:null,participantPolicy:"creator_only",retention:{policy:"source_bound",deleteWithSource:!0,expiresAt:null}}}),xS=gS({schemaVersion:"openpond.workFeedbackReceipt.v1",id:`work-feedback-${xt([Ko.contentHash,"accepted"]).slice(0,24)}`,evidenceReceiptRef:iN(Ko),outputRevisionRef:xs,verdict:"accepted",reasonCodes:["correct","complete"],correctionRef:null,correctedOutputRevisionRef:null,actor:"user",createdAt:"2026-08-04T12:01:00.000Z"},Ko);hS({schemaVersion:"openpond.workProcessTrace.v1",sourceRevisionHash:xt({fixture:"incomplete",revision:1}),sanitationPolicyVersion:"openpond.desktop-work-sanitizer.v1",incomplete:!0,incompleteReasons:["missing_terminal","unsupported_events_dropped"],droppedEventCount:2,steps:[Er(0,Ss,"agent","state_transition","turn_started","started",{transitionState:"running"})]});vS({evidence:Ko,feedback:[xS],policyState:"active",reconstructability:{input:!0,environment:!0,verifier:!0}});vS({evidence:Ko,feedback:[xS],policyState:"revoked",reconstructability:{input:!0,environment:!0,verifier:!0}});({...Ko,source:{...Ko.source}});function Er(e,t,n,a,r,i,s){return{sequence:e,timestamp:t,layer:n,kind:a,action:r,status:i,inputHash:s.inputHash??null,outputHash:s.outputHash??null,receiptHash:s.receiptHash??null,parentReceiptHash:s.parentReceiptHash??null,artifactRefs:s.artifacts??[],attributes:{toolCategory:s.toolCategory??null,validationKind:s.validationKind??null,transitionState:s.transitionState??null,interventionOutcome:null,artifactCount:s.artifacts?.length??0,exitCode:null,durationMs:null,cpuTimeMs:null,memoryPeakBytes:null,errorClass:null}}}const gN=c({schemaVersion:w("openpond.graderEvidence.v1"),graderId:ne,graderVersion:o().trim().min(1).max(100),score:d().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),failureClass:fc.nullable(),feedback:h(o().max(2e4)).max(1e3),visibleEvidenceRefs:h(ne).max(1e4),privilegedEvidenceRefs:h(ne).max(1e4)}).strict();gN.extend({contentHash:_e}).strict();const bN=b(["calibration","training_reward","validation","frozen_eval"]);b(["human","model","deterministic","fixture"]);b(["production","synthetic_smoke"]);const vN=b(["markdown","text","code","json","image"]),yN=c({id:ne,label:o().trim().min(1).max(500),instruction:o().trim().min(1).max(1e4),weight:d().nonnegative().max(1e3)}).strict(),SN=c({source:b(["attempt_output","artifact"]),path:o().trim().min(1).max(2e3),renderer:vN}).strict(),xN=c({showTaskPrompt:C(),randomizeCandidateOrder:C(),hideModelIdentity:C(),parts:h(SN).min(1).max(20)}).strict().superRefine((e,t)=>{e.parts.some(n=>n.renderer==="markdown"||n.renderer==="text")||t.addIssue({code:"custom",path:["parts"],message:"A preference presentation must expose text or Markdown content."})}),kN=c({strategy:w("randomized_blinded_v1"),maxAssignmentsPerCandidate:d().int().positive().max(1e4)}).strict(),_N=c({algorithm:w("mean_pairwise_win_fraction_v1"),quorum:d().int().positive().max(100),rejectAllThreshold:d().min(.5).max(1)}).strict(),wN=c({algorithm:w("pairwise_win_fraction_v1"),verifierId:ne,verifierVersion:o().trim().min(1).max(100),weight:d().positive().max(1e3)}).strict(),IN=c({minimumSamples:d().int().positive().max(1e5),minimumOrderAgreement:d().min(0).max(1),minimumTieAgreement:d().min(0).max(1),minimumOrderSwapAgreement:d().min(0).max(1)}).strict(),CN=c({schemaVersion:w("openpond.preferenceComparisonRelease.v1"),id:ne,revision:d().int().positive(),tasksetRelease:ce,candidateCount:d().int().min(2).max(4),resultMode:w("ordered_tie_groups"),allowTies:C(),allowRejectAll:C(),presentation:xN,rubricRef:Gn,criteria:h(yN).max(20),assignment:kN,aggregation:_N,rewardProjection:wN,calibration:IN,metadata:wt}).strict().superRefine((e,t)=>{const n=e.criteria.map(a=>a.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["criteria"],message:"Preference criterion IDs must be unique."})});CN.extend({contentHash:_e}).strict();const RN=c({id:ne,contentHash:_e}).strict(),AN=c({tasksetRelease:ce,harnessReleases:h(ce).min(1).max(4),runManifestRefs:h(ce).min(1).max(4),harnessCompatibilityReceiptRefs:h(ce).max(6),environmentRelease:ce,verifierSetRelease:ce,toolContractHash:_e,policyHash:_e}).strict(),PN=c({attemptRef:ce,runManifestRef:ce,artifactManifestRef:ce,visibleArtifactIds:h(ne).max(1e5)}).strict().superRefine((e,t)=>{new Set(e.visibleArtifactIds).size!==e.visibleArtifactIds.length&&t.addIssue({code:"custom",path:["visibleArtifactIds"],message:"Visible artifact IDs must be unique per candidate."})}),TN=c({schemaVersion:w("openpond.comparisonAssignment.v1"),id:ne,comparisonRelease:ce,taskRef:RN,lineage:AN,candidates:h(PN).min(2).max(4),presentedCandidateOrder:h(ne).min(2).max(4),purpose:bN,createdAt:Qe,metadata:wt}).strict().superRefine((e,t)=>{const n=e.candidates.map(a=>a.attemptRef.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["candidates"],message:"An assignment cannot contain the same attempt twice."}),(new Set(e.presentedCandidateOrder).size!==e.presentedCandidateOrder.length||e.presentedCandidateOrder.length!==n.length||e.presentedCandidateOrder.some(a=>!n.includes(a)))&&t.addIssue({code:"custom",path:["presentedCandidateOrder"],message:"Presented candidate order must contain every assignment candidate exactly once."})});TN.extend({contentHash:_e}).strict().superRefine((e,t)=>{const n=e.candidates.map(a=>a.attemptRef.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["candidates"],message:"An assignment cannot contain the same attempt twice."})});const kS=h(h(ne).min(1).max(4)).max(4),EN=dn("kind",[c({kind:b(["human","model","deterministic"]),releaseRef:ce}).strict(),c({kind:w("fixture"),releaseRef:ce,fixtureRelease:ce,labelSource:w("synthetic"),qualificationEligibility:w("smoke_only")}).strict()]),MN=c({schemaVersion:w("openpond.preferenceReceipt.v1"),id:ne,assignmentRef:ce,reviewer:EN,order:kS,rejectAll:C(),criterionScores:fe(ne,fe(ne,d().finite().min(0).max(1))),feedbackArtifactRef:Gn.nullable(),startedAt:Qe,completedAt:Qe,metadata:wt}).strict().superRefine((e,t)=>{e.rejectAll&&e.order.length!==0&&t.addIssue({code:"custom",path:["order"],message:"A reject-all preference receipt cannot contain an order."}),!e.rejectAll&&e.order.length===0&&t.addIssue({code:"custom",path:["order"],message:"A non-reject preference receipt requires an ordered result."}),Date.parse(e.completedAt)<Date.parse(e.startedAt)&&t.addIssue({code:"custom",path:["completedAt"],message:"A preference receipt cannot complete before it starts."})});MN.extend({contentHash:_e}).strict();const jN=c({schemaVersion:w("openpond.preferenceAggregationReceipt.v1"),id:ne,assignmentRef:ce,comparisonRelease:ce,receiptRefs:h(ce).min(1).max(100),order:kS,rejectAll:C(),pairwiseWinFractions:fe(ne,d().min(0).max(1)),quorum:d().int().positive().max(100),createdAt:Qe,metadata:wt}).strict().superRefine((e,t)=>{e.rejectAll&&e.order.length!==0&&t.addIssue({code:"custom",path:["order"],message:"A reject-all aggregate cannot contain an order."})});jN.extend({contentHash:_e}).strict();const ON=c({schemaVersion:w("openpond.preferenceCalibrationReport.v1"),id:ne,comparisonRelease:ce,automatedReviewer:ce,humanReceiptRefs:h(ce).min(1).max(1e5),modelReceiptRefs:h(ce).min(1).max(1e5),sampleCount:d().int().positive().max(1e5),orderAgreement:d().min(0).max(1),tieAgreement:d().min(0).max(1),orderSwapAgreement:d().min(0).max(1),passed:C(),createdAt:Qe,metadata:wt}).strict();ON.extend({contentHash:_e}).strict();const NN=b(["reward_train","reward_validation","reward_qualification"]),$N=b(["human","synthetic_fixture"]),DN=b(["synthetic_smoke","human_heldout"]),LN=c({id:ne,assignmentRef:ce,scenarioRef:ce,scenarioSplit:b(["train","validation"]),preferenceResultRef:ce,receiptRefs:h(ce).min(1).max(100),attemptRefs:h(ce).min(2).max(4),artifactManifestRefs:h(ce).min(2).max(4),orderedBuckets:h(h(ne).min(1).max(4)).max(4),rejectAll:C(),partition:NN,metadata:wt}).strict().superRefine((e,t)=>{const n=e.attemptRefs.map(r=>r.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["attemptRefs"],message:"Preference dataset group Attempt refs must be unique."}),e.artifactManifestRefs.length!==e.attemptRefs.length&&t.addIssue({code:"custom",path:["artifactManifestRefs"],message:"Every preference dataset Attempt requires one Artifact Manifest ref."});const a=e.orderedBuckets.flat();e.rejectAll&&a.length>0&&t.addIssue({code:"custom",path:["orderedBuckets"],message:"A reject-all preference dataset group cannot contain ordered buckets."}),!e.rejectAll&&(a.length!==n.length||new Set(a).size!==a.length||a.some(r=>!n.includes(r)))&&t.addIssue({code:"custom",path:["orderedBuckets"],message:"Ordered buckets must contain every group Attempt exactly once."})}),zN=c({groupId:ne,preferredAttemptRef:ce,dispreferredAttemptRef:ce,relation:b(["preferred","tie"])}).strict().superRefine((e,t)=>{e.preferredAttemptRef.id===e.dispreferredAttemptRef.id&&e.preferredAttemptRef.contentHash===e.dispreferredAttemptRef.contentHash&&t.addIssue({code:"custom",message:"A derived preference pair must reference two different Attempts."})}),UN=c({schemaVersion:w("openpond.preferenceDatasetRelease.v1"),id:ne,revision:d().int().positive(),tasksetRelease:ce,comparisonRelease:ce,authority:$N,qualificationEligibility:b(["smoke_only","human_heldout"]),fixtureRelease:ce.nullable(),groups:h(LN).min(1).max(1e5),derivedPairs:h(zN).max(1e6),createdAt:Qe,metadata:wt}).strict().superRefine((e,t)=>{e.authority==="synthetic_fixture"&&(e.qualificationEligibility!=="smoke_only"||e.fixtureRelease===null)&&t.addIssue({code:"custom",path:["qualificationEligibility"],message:"Synthetic preference datasets require a fixture release and are smoke-only."}),e.authority==="human"&&(e.qualificationEligibility!=="human_heldout"||e.fixtureRelease!==null)&&t.addIssue({code:"custom",path:["authority"],message:"Human preference datasets must be human-heldout eligible and cannot bind a fixture release."});const n=e.groups.map(r=>r.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["groups"],message:"Preference dataset group IDs must be unique."});const a=new Map(e.groups.map(r=>[r.id,r]));for(const[r,i]of e.derivedPairs.entries()){const s=a.get(i.groupId);if(!s){t.addIssue({code:"custom",path:["derivedPairs",r,"groupId"],message:"Derived preference pairs must reference a group in the same release."});continue}const l=new Set(s.attemptRefs.map(p=>p.id));(!l.has(i.preferredAttemptRef.id)||!l.has(i.dispreferredAttemptRef.id))&&t.addIssue({code:"custom",path:["derivedPairs",r],message:"Derived preference pairs must reference Attempts in their source group."})}});UN.extend({contentHash:_e}).strict();const HN=c({sampleCount:d().int().positive(),finiteScoreRate:d().min(0).max(1),scoreVariance:d().nonnegative(),checkpointReloadPassed:C(),processorCompatibilityPassed:C(),invalidAttemptExclusionPassed:C(),orderedPairAccuracy:d().min(0).max(1).nullable(),bucketAccuracy:d().min(0).max(1).nullable(),tieAgreement:d().min(0).max(1).nullable()}).strict(),qN=c({schemaVersion:w("openpond.rewardModelQualificationReport.v1"),id:ne,kind:DN,rewardModelVersion:ce,preferenceDatasetRelease:ce,tasksetRelease:ce,processorRelease:ce,metrics:HN,passed:C(),productionRewardEligible:C(),createdAt:Qe,metadata:wt}).strict().superRefine((e,t)=>{e.kind==="synthetic_smoke"&&e.productionRewardEligible&&t.addIssue({code:"custom",path:["productionRewardEligible"],message:"Synthetic-smoke Reward Model qualification can never grant production reward eligibility."}),e.kind==="human_heldout"&&e.productionRewardEligible!==e.passed&&t.addIssue({code:"custom",path:["productionRewardEligible"],message:"Human-heldout reward eligibility must match the frozen qualification outcome."})});qN.extend({contentHash:_e}).strict();const BN=o().trim().min(1).max(1e5),FN=b(["no_training","sft","preference","rl"]),VN=c({kind:b(["none","demonstrations","chosen_rejected","scalar_reward"]),strength:b(["absent","weak","usable"]),calibrated:C(),confounded:C(),variance:d().finite().nonnegative().nullable(),evidenceRefs:h(ce).max(1e5)}).strict(),_S=c({schemaVersion:w("openpond.modelImprovementQualificationReceipt.v1"),id:ne,review:ce,harnessRelease:ce,tasksetRelease:ce.nullable(),baselineEvaluation:ce.nullable(),model:or,environmentHash:_e.nullable(),toolContractHash:_e.nullable(),permissionContractHash:_e.nullable(),policyHash:_e.nullable(),verifierRef:ce.nullable(),sourcePolicies:h(jp).max(1e4),trainingEvidenceRefs:h(ce).max(1e5),frozenEvaluationEvidenceRefs:h(ce).max(1e5),privacyApproval:ce.nullable(),budgetApproval:ce.nullable(),maximumCostUsd:d().finite().nonnegative(),signal:VN,decision:FN,reasons:h(BN).min(1).max(100),createdAt:Qe,metadata:wt}).strict().superRefine((e,t)=>{const n=new Set(e.trainingEvidenceRefs.map(Vh));if(e.frozenEvaluationEvidenceRefs.some(r=>n.has(Vh(r)))&&t.addIssue({code:"custom",message:"frozen Evaluation evidence cannot be used as training evidence",path:["frozenEvaluationEvidenceRefs"]}),e.decision==="no_training")return;(!e.tasksetRelease||!e.baselineEvaluation||!e.environmentHash||!e.toolContractHash||!e.permissionContractHash||!e.policyHash||!e.verifierRef||!e.privacyApproval||!e.budgetApproval||e.sourcePolicies.length===0||e.sourcePolicies.some(r=>r.state!=="authorized")||e.trainingEvidenceRefs.length===0||e.signal.strength!=="usable"||!e.signal.calibrated||e.signal.confounded)&&t.addIssue({code:"custom",message:"qualified model improvement requires frozen lineage, authorized signal, privacy, and budget gates"}),e.decision==="sft"&&e.signal.kind!=="demonstrations"&&t.addIssue({code:"custom",message:"SFT qualification requires demonstration signal",path:["signal","kind"]}),e.decision==="preference"&&e.signal.kind!=="chosen_rejected"&&t.addIssue({code:"custom",message:"preference qualification requires chosen/rejected signal",path:["signal","kind"]}),e.decision==="rl"&&(e.signal.kind!=="scalar_reward"||e.signal.variance===null||e.signal.variance<=0)&&t.addIssue({code:"custom",message:"RL qualification requires a usable scalar reward with variance",path:["signal"]})}),WN=_S.extend({contentHash:_e}).strict();function wS(e){const t=_S.parse(e);return WN.parse({...t,contentHash:xt(t)})}function Vh(e){return`${e.id}:${e.contentHash}`}const Bs="2026-08-08T12:00:00.000Z",IS=Xt("harness-release"),CS={policy:Xt("source-policy"),state:"authorized",checkedAt:Bs},Go=(e,t)=>({evidence:Xt(e),kind:t,sourceRef:`source-${e}`,sourcePolicy:CS,occurrenceKey:xt(`occurrence-${e}`),occurredAt:Bs}),KN={cursor:xt("review-watermark"),throughCreatedAt:Bs},Cc=(e,t=3)=>({fingerprint:xt(`claim-${e}`),recurrenceFamily:e,statement:`The ${e} behavior remains unresolved after smaller-layer triage.`,independentOccurrences:t,unresolvedOccurrences:t}),Rc=Us({schemaVersion:"openpond.harnessEvaluationReviewReceipt.v1",id:"review-no-action",ownerScope:{kind:"personal",id:"owner-1"},workspaceRef:"workspace-1",harnessRelease:IS,previousWatermark:null,nextWatermark:KN,selectedEvidence:[],excludedEvidence:[],claim:null,classification:"no_action",triage:[],reason:"The bounded evidence window contains no unresolved reusable claim.",nextAuthority:"none",maxEstimatedCostUsd:0,tasksetProposal:null,evaluation:null,trainingQualification:null,policyVersion:"harness-review-policy-v1",createdAt:Bs,metadata:{}});Us({...Fs(Rc),id:"review-runtime",selectedEvidence:[Go("runtime-failure","observation")],claim:Cc("runtime-transport-failure",1),classification:"runtime",triage:[{layer:"runtime",status:"unresolved",reason:"The adapter failed before model policy could affect the result.",evidenceRefs:[Xt("runtime-failure")]}],reason:"A deterministic runtime regression is the smallest correct fix.",nextAuthority:"runtime_service"});Us({...Fs(Rc),id:"review-product",selectedEvidence:[Go("product-routing","route_decision")],claim:Cc("product-routing-defect",1),classification:"product",triage:[{layer:"product",status:"unresolved",reason:"The product selected an unrelated Skill for an ordinary Work turn.",evidenceRefs:[Xt("product-routing")]}],reason:"Product routing must be corrected before behavioral Evaluation.",nextAuthority:"product_team"});const GN=Us({...Fs(Rc),id:"review-taskset",selectedEvidence:[Go("failure-1","work_outcome"),Go("failure-2","work_outcome"),Go("failure-3","work_outcome")],claim:Cc("search-budget-allocation"),classification:"taskset",triage:[{layer:"harness",status:"unresolved",reason:"The active research Skill did not resolve three independent failures.",evidenceRefs:[Xt("failure-1"),Xt("failure-2"),Xt("failure-3")]}],reason:"The repeated behavioral claim now needs controlled measurement.",nextAuthority:"human_review",tasksetProposal:Xt("taskset-proposal"),maxEstimatedCostUsd:2}),ZN=wS({schemaVersion:"openpond.modelImprovementQualificationReceipt.v1",id:"qualification-rl-blocked",review:pm(GN),harnessRelease:IS,tasksetRelease:Xt("taskset-release"),baselineEvaluation:Xt("baseline-evaluation"),model:JN(),environmentHash:xt("environment"),toolContractHash:xt("tools"),permissionContractHash:xt("permissions"),policyHash:xt("policy"),verifierRef:Xt("verifier"),sourcePolicies:[CS],trainingEvidenceRefs:[Xt("training-evidence")],frozenEvaluationEvidenceRefs:[Xt("frozen-evidence")],privacyApproval:Xt("privacy-approval"),budgetApproval:Xt("budget-approval"),maximumCostUsd:25,signal:{kind:"scalar_reward",strength:"weak",calibrated:!0,confounded:!1,variance:0,evidenceRefs:[Xt("reward-audit")]},decision:"no_training",reasons:["The observed reward is constant and cannot support RL."],createdAt:Bs,metadata:{blockedMethod:"rl"}}),Wh=wS({...Fs(ZN),id:"qualification-rl-qualified",signal:{kind:"scalar_reward",strength:"usable",calibrated:!0,confounded:!1,variance:.18,evidenceRefs:[Xt("reward-audit")]},decision:"rl",reasons:["The frozen baseline has usable variance and a calibrated sequential reward."]});Us({...Fs(Rc),id:"review-model-improvement",selectedEvidence:[Go("baseline-evaluation","evaluation"),Go("qualification-rl-qualified","training_qualification")],claim:Cc("search-budget-allocation"),classification:"model_improvement",triage:[{layer:"model",status:"unresolved",reason:"Harness, runtime, product, retrieval, and tool triage left a qualified sequential policy gap.",evidenceRefs:[Xt("baseline-evaluation"),pm(Wh)]}],reason:"The qualified claim may proceed to a separately approved managed-training plan.",nextAuthority:"training_system",tasksetProposal:Xt("taskset-proposal"),evaluation:Xt("baseline-evaluation"),trainingQualification:pm(Wh),maxEstimatedCostUsd:25});function Xt(e){return{id:e,contentHash:xt(e)}}function pm(e){return{id:e.id,contentHash:e.contentHash}}function Fs(e){const{contentHash:t,...n}=e;return n}function JN(){return{provider:"openpond",model:"openpond-chat",revision:"model-revision-1",artifactHash:xt("model-artifact"),tokenizerRevision:"tokenizer-1",chatTemplateHash:xt("chat-template")}}const RS=c({schemaVersion:w("openpond.optimizerTrainingSample.v1"),tokenIds:h(d().int().nonnegative()).min(2).max(32768),mask:h(C()).min(2).max(32768),logprobs:h(d().finite()).min(2).max(32768),temperatures:h(d().positive().finite()).min(2).max(32768),envName:o().trim().min(1).max(200),modelRequestId:o().trim().min(1).max(1e3),promptTokenCount:d().int().positive(),completionTokenCount:d().int().positive(),servedPolicyVersion:d().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,r]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])r.length!==n&&t.addIssue({code:"custom",path:[a],message:`${a} must align with tokenIds`});e.promptTokenCount+e.completionTokenCount!==n&&t.addIssue({code:"custom",path:["completionTokenCount"],message:"prompt and completion token counts must span tokenIds"}),e.mask.filter(a=>!a).length!==e.promptTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"promptTokenCount must equal the non-trainable mask count"}),e.mask.filter(Boolean).length!==e.completionTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"completionTokenCount must equal the trainable mask count"})}),YN=c({id:ne,environmentRelease:ce,status:b(["completed","failed","timed_out","cancelled"]),startedAt:Qe,completedAt:Qe,traceRefs:h(Gn).max(1e4),metadata:wt}).strict(),XN=c({receiptRef:ce,status:Lp,value:d().min(0).max(1).nullable(),learningEligible:C(),passed:C(),outcomeClass:iS,failureOwner:Ic.nullable(),components:fe(ne,d().min(0).max(1).nullable())}).strict(),AS=c({schemaVersion:w("openpond.canonicalRolloutRecord.v1"),id:ne,attemptRef:ce,artifactManifestRef:ce,tasksetRelease:ce,environmentRelease:ce,verifierSetRelease:ce,harnessRelease:ce,taskId:ne,split:Xr,model:or,seed:o().trim().min(1).max(500),reward:XN,traceRef:Gn,optimizerSample:RS.nullable(),environmentExecutions:h(YN).min(1).max(1e5),startedAt:Qe,completedAt:Qe,metadata:wt}).strict();function PS(e,t){e.reward.status==="scored"&&(e.reward.value===null||!e.reward.learningEligible)&&t.addIssue({code:"custom",path:["reward","status"],message:"A scored rollout requires a numeric, learning-eligible reward."}),e.reward.status==="unscorable"&&(e.reward.value!==null||e.reward.learningEligible)&&t.addIssue({code:"custom",path:["reward","status"],message:"An unscorable rollout has no reward and cannot be learning-eligible."})}AS.superRefine(PS);c({...AS.shape,contentHash:_e}).strict().superRefine(PS);c({schemaVersion:w("openpond.rolloutQualification.v1"),rolloutCount:d().int().nonnegative(),scoredCount:d().int().nonnegative(),optimizerEligibleCount:d().int().nonnegative(),unscorableCount:d().int().nonnegative(),zeroRewardCount:d().int().nonnegative(),rewardMean:d().min(0).max(1).nullable(),rewardVariance:d().nonnegative().nullable(),distinctRewardCount:d().int().nonnegative(),eligibleForRl:C(),reasons:h(o().trim().min(1).max(1e3)).max(100)}).strict();const QN="openpond.runTelemetryEvent.v1",e$="openpond.metricDefinition.v1",TS="openpond.metricObservation.v1",Hp=b(["policy_visible","team_visible","host_private"]),t$=b(["runtime","environment","grader","optimizer","control_plane","evaluation"]),n$=b(["run_started","run_state_changed","rollout_group_started","attempt_completed","grader_completed","reward_composed","optimizer_step_completed","checkpoint_committed","evaluation_completed","run_completed","run_failed","cleanup_completed"]),ES=c({modelProjectId:ne,runId:ne,modelVersionId:ne.nullable(),harnessReleaseHash:_e,tasksetReleaseHash:_e,environmentReleaseHash:_e.nullable(),checkpointId:ne.nullable(),step:d().int().nonnegative().nullable(),rolloutGroupId:ne.nullable(),attemptId:ne.nullable(),scenarioId:ne.nullable()}).strict(),MS=c({schemaVersion:w(QN),eventId:ne,sequence:d().int().nonnegative(),occurredAt:Qe,source:t$,type:n$,visibility:Hp,lineage:ES,attributes:wt}).strict(),a$=b(["gauge","counter","distribution"]),o$=b(["ratio","count","seconds","milliseconds","tokens","bytes","usd","scalar"]),r$=b(["higher","lower","neutral"]),i$=b(["last","sum","mean","min","max","p50","p95"]),jS=c({schemaVersion:w(e$),id:ne,displayName:o().trim().min(1).max(200),description:o().trim().min(1).max(2e3),valueType:a$,unit:o$,direction:r$,aggregation:i$,visibility:Hp,boundedDimensions:h(o().trim().min(1).max(100)).max(32)}).strict(),OS=c({schemaVersion:w(TS),observationId:ne,metricId:ne,eventId:ne,sequence:d().int().nonnegative(),observedAt:Qe,value:d().finite(),lineage:ES,dimensions:fe(o().trim().min(1).max(100),o().max(500))}).strict();c({schemaVersion:w("openpond.runTelemetryBatch.v1"),events:h(MS).max(1e3),observations:h(OS).max(1e4)}).strict().superRefine((e,t)=>{e.events.length+e.observations.length===0&&t.addIssue({code:"custom",message:"Telemetry batch cannot be empty."});const n=new Set;for(const a of[...e.events,...e.observations]){const r=a.schemaVersion===TS?a.observationId:a.eventId,i=`${a.lineage.runId}:${a.sequence}:${r}`;n.has(i)&&t.addIssue({code:"custom",message:"Telemetry batch contains a duplicate idempotency key."}),n.add(i)}});const an=e=>jS.parse({schemaVersion:"openpond.metricDefinition.v1",...e}),s$=[an({id:"reward.mean",displayName:"Mean reward",description:"Mean composed reward for the cohort.",valueType:"gauge",unit:"scalar",direction:"higher",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split","grader"]}),an({id:"reward.variance",displayName:"Reward variance",description:"Population variance of composed reward within a rollout group.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"reward.constant_group_rate",displayName:"Constant group rate",description:"Fraction of rollout groups with no reward variation.",valueType:"gauge",unit:"ratio",direction:"lower",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"attempt.valid_rate",displayName:"Valid attempt rate",description:"Fraction of attempts passing deterministic validity checks.",valueType:"gauge",unit:"ratio",direction:"higher",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split","failureOwner"]}),an({id:"attempt.failure_count",displayName:"Attempt failures",description:"Count of failed Attempts.",valueType:"counter",unit:"count",direction:"lower",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","failureOwner","failureClass"]}),an({id:"optimizer.loss",displayName:"Optimizer loss",description:"Policy optimizer loss after the step.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"optimizer.learning_rate",displayName:"Learning rate",description:"Optimizer learning rate after the step.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"last",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"optimizer.kl",displayName:"KL divergence",description:"Sampled KL divergence from the reference policy.",valueType:"gauge",unit:"scalar",direction:"lower",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"optimizer.entropy",displayName:"Policy entropy",description:"Observed policy entropy for trainable tokens.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"optimizer.gradient_norm",displayName:"Gradient norm",description:"Gradient norm reported by the optimizer.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"max",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"optimizer.clip_fraction",displayName:"Clip fraction",description:"Fraction of policy updates affected by clipping.",valueType:"gauge",unit:"ratio",direction:"neutral",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"output.duplicate_rate",displayName:"Duplicate output rate",description:"Fraction of outputs duplicated within the measured cohort.",valueType:"gauge",unit:"ratio",direction:"lower",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"output.unique_count",displayName:"Unique outputs",description:"Distinct output count in the measured cohort.",valueType:"gauge",unit:"count",direction:"higher",aggregation:"last",visibility:"team_visible",boundedDimensions:["split"]}),an({id:"tokens.input",displayName:"Input tokens",description:"Input tokens processed.",valueType:"counter",unit:"tokens",direction:"neutral",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","source"]}),an({id:"tokens.output",displayName:"Output tokens",description:"Output tokens generated.",valueType:"counter",unit:"tokens",direction:"neutral",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","source"]}),an({id:"runtime.latency_ms",displayName:"Runtime latency",description:"Wall-clock latency of the measured operation.",valueType:"distribution",unit:"milliseconds",direction:"lower",aggregation:"p95",visibility:"team_visible",boundedDimensions:["operation","provider"]}),an({id:"runtime.throughput",displayName:"Token throughput",description:"Tokens processed per second.",valueType:"gauge",unit:"scalar",direction:"higher",aggregation:"mean",visibility:"team_visible",boundedDimensions:["operation","provider"]}),an({id:"gpu.memory_bytes",displayName:"GPU memory",description:"Peak allocated GPU memory.",valueType:"gauge",unit:"bytes",direction:"neutral",aggregation:"max",visibility:"host_private",boundedDimensions:["provider","gpuType"]}),an({id:"gpu.utilization",displayName:"GPU utilization",description:"Observed GPU utilization ratio.",valueType:"gauge",unit:"ratio",direction:"neutral",aggregation:"mean",visibility:"host_private",boundedDimensions:["provider","gpuType"]}),an({id:"cost.usd",displayName:"Run cost",description:"Accrued hosted execution cost.",valueType:"counter",unit:"usd",direction:"lower",aggregation:"sum",visibility:"team_visible",boundedDimensions:["provider","resource"]})];new Map(s$.map(e=>[e.id,e]));const l$=h(jS).min(1).superRefine((e,t)=>{new Set(e.map(n=>n.id)).size!==e.length&&t.addIssue({code:"custom",message:"Metric catalog contains duplicate ids."})});c({checkpointIds:h(ne).max(1e3),steps:h(d().int().nonnegative()).max(1e4),scenarioIds:h(ne).max(1e5),rolloutGroupIds:h(ne).max(1e5),attemptIds:h(ne).max(1e6),splits:h(o().trim().min(1).max(100)).max(32),failureOwners:h(o().trim().min(1).max(100)).max(32),graders:h(o().trim().min(1).max(200)).max(1e3),rewardEligible:C().nullable()}).strict();const c$=c({id:ne,contentHash:_e,kind:b(["rollout","attempt","trace","grader","checkpoint","artifact"]),visibility:Hp}).strict(),d$=c({schemaVersion:w("openpond.telemetryEvidenceCompleteness.v1"),runId:ne,status:b(["complete","partial","missing"]),expectedEventTypes:h(o().trim().min(1).max(100)).max(100),observedEventTypes:h(o().trim().min(1).max(100)).max(100),missingEventTypes:h(o().trim().min(1).max(100)).max(100),lastSequence:d().int().nonnegative().nullable(),sequenceGaps:h(d().int().nonnegative()).max(1e4)}).strict(),u$=c({step:d().int().nonnegative().nullable(),observedAt:Qe,value:d().finite(),sampleCount:d().int().positive()}).strict();c({schemaVersion:w("openpond.runMetricSummary.v1"),runId:ne,metricId:ne,aggregation:b(["last","sum","mean","min","max","p50","p95"]),value:d().finite().nullable(),sampleCount:d().int().nonnegative(),series:h(u$).max(1e5)}).strict();const m$=c({schemaVersion:w("openpond.telemetryExportBundle.v1"),id:ne,runId:ne,exportedAt:Qe,definitions:l$,events:h(MS).max(1e6),observations:h(OS).max(1e7),evidenceRefs:h(c$).max(1e6),completeness:d$}).strict();m$.extend({contentHash:_e}).strict();const p$=b(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),f$=c({datasetRelease:it,harnessRelease:it,evidenceSetRelease:it.nullable(),profileRelease:it.nullable(),model:c({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:Ve.nullable()}).strict(),environmentHash:Ve,graderHash:Ve,toolContractHash:Ve,verificationReceiptHash:Ve.nullable()}).strict(),to=c({schemaVersion:w("openpond.learningSignal.v1"),id:je,taskId:je.nullable(),episodeId:je.nullable(),policyVersion:d().int().nonnegative().nullable(),lineage:f$,approved:C(),verifier:b(["deterministic","model_judge","human","none"]),createdAt:Nt,contentHash:Ve,metadata:fe(o(),Se()).default({})}).strict(),h$=to.extend({kind:w("trajectory"),payload:c({traceRef:o().trim().min(1).max(2e3),traceHash:Ve,terminal:C(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:RS.nullable().optional()}).strict()}).strict(),g$=to.extend({kind:w("reward"),payload:c({reward:d().finite(),components:fe(o(),d().finite()),eligible:C(),graderEvidenceRefs:h(je).max(1e3)}).strict()}).strict(),b$=to.extend({kind:w("demonstration"),payload:c({prompt:o().max(5e5),response:o().max(1e6)}).strict()}).strict(),v$=to.extend({kind:w("preference"),payload:c({prompt:o().max(5e5),chosen:o().max(1e6),rejected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),y$=to.extend({kind:w("correction"),payload:c({original:o().max(1e6),corrected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),S$=to.extend({kind:w("critique"),payload:c({response:o().max(1e6),critique:o().max(5e5),severity:b(["note","warning","error"])}).strict()}).strict(),x$=to.extend({kind:w("targeted_feedback"),payload:c({turnIndex:d().int().nonnegative(),target:b(["reasoning","tool","answer","policy"]),feedback:o().max(5e5)}).strict()}).strict(),k$=to.extend({kind:w("grader_evidence"),payload:c({graderId:je,score:d().finite().nullable(),passed:C(),privilegedArtifactRefs:h(o().trim().min(1).max(2e3))}).strict()}).strict(),_$=to.extend({kind:w("infrastructure_failure"),approved:w(!1),verifier:w("none"),payload:c({code:je,phase:je,retryable:C(),rewardEligible:w(!1)}).strict()}).strict(),NS=dn("kind",[h$,g$,b$,v$,y$,S$,x$,k$,_$]);c({schemaVersion:w("openpond.learningSignalBatch.v1"),manifestId:je,manifestHash:Ve,sequence:d().int().nonnegative(),signals:h(NS).min(1).max(1e5),contentHash:Ve}).strict();const qp=c({adapterId:je,placement:b(["local","remote","colocated","provider_native"]),capabilityReceipt:Ve,runtimeVersion:o().trim().min(1).max(200),dataPlane:c({provider:je,dataPlaneId:je,cellId:je,runnerPoolId:je,runtimeImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Ve}).strict().nullable()}).strict(),Bp=c({adapterId:je,kind:b(["local","ssh","managed","custom"]),deviceOrPool:o().trim().min(1).max(1e3),capabilityReceipt:Ve,provider:je.nullable()}).strict(),Fp=c({adapterId:je,workerVersion:o().trim().min(1).max(200),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:o().trim().min(1).max(500),capabilityReceipt:Ve}).strict(),w$=c({schemaVersion:w("openpond.harnessRunManifest.v1"),id:je,harnessRelease:it,datasetRelease:it,evidenceSets:h(it).max(1e4),model:c({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:Ve.nullable(),tokenizerRevision:o().trim().min(1).max(500),chatTemplateHash:Ve}).strict(),recipe:c({method:o().trim().min(1).max(100),version:o().trim().min(1).max(200),configHash:Ve}).strict(),runtimeTarget:qp,computeTarget:Bp,engine:Fp,resolvedBundleHash:Ve,secretLeaseRefs:h(ME).max(1e3),approval:c({approvalHash:Ve,approvedAt:Nt,maximumSpendUsd:d().nonnegative().nullable()}).strict(),createdAt:Nt}).strict(),I$=w$.extend({contentHash:Ve}).strict(),C$=c({schemaVersion:w("openpond.resolvedTrainingBundle.v1"),projection:w("trainer"),harnessRelease:it,datasetRelease:it,evidenceSetRelease:it.nullable(),files:h(c({path:o().trim().min(1).max(2e3),sha256:Ve,sizeBytes:d().int().nonnegative()}).strict()).max(1e5)}).strict();C$.extend({contentHash:Ve}).strict();const R$=c({id:je,turn:d().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:je.nullable(),arguments:fe(o(),Se()),content:o().max(1e6).nullable(),contentHash:Ve}).strict(),A$=c({actionId:je,turn:d().int().nonnegative(),terminal:C(),output:fe(o(),Se()),artifactRefs:h(o().trim().min(1).max(2e3)),contentHash:Ve}).strict(),P$=c({sequence:d().int().nonnegative(),type:b(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:Nt,payloadHash:Ve,metadata:fe(o(),Se()).default({})}).strict(),Kh=c({graderId:je,graderVersion:o().trim().min(1).max(200),score:d().finite().nullable(),passed:C(),rewardEligible:C(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:h(o().max(5e5)),visibleEvidenceRefs:h(o().trim().min(1).max(2e3)),privilegedEvidenceRefs:h(o().trim().min(1).max(2e3)),contentHash:Ve}).strict();c({schemaVersion:w("openpond.harnessRunTrace.v1"),manifest:it,taskId:je,seed:o().trim().min(1).max(500),events:h(P$).max(1e6),actions:h(R$).max(1e5),observations:h(A$).max(1e5),graderEvidence:h(Kh).max(1e4),learningSignals:h(NS).max(1e5),terminal:C(),failureClass:Kh.shape.failureClass,artifactHash:Ve,contentHash:Ve}).strict();const T$=o().trim().min(1).max(2e3).refine(e=>{const t=e.replaceAll("\\","/");return!t.startsWith("/")&&!t.includes("\0")&&!t.split("/").some(n=>!n||n==="."||n==="..")},"path must be a safe relative path"),E$=b(["instruction","skill","skill_resource","agent","dependency_lock","program","asset"]),M$=c({id:je,kind:E$,path:T$,parentId:je.nullable(),mediaType:o().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"]),portability:b(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});c({schemaVersion:w("openpond.harnessSourceManifest.v1"),name:o().trim().min(1).max(240),files:h(M$).min(2).max(1e5),toolDeclarations:h(kc).max(200),capabilityRequirements:h(Op).max(200),lifecycle:Ky,graderInterface:Gy,runtimeProtocol:o().trim().min(1).max(500),metadata:fe(o(),Se()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,r=new Set;for(const[i,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",i,"id"]}),r.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",i,"path"]}),n.add(s.id),a.set(s.id,s.kind),r.add(s.path);for(const[i,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",i,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",i,"parentId"]});e.files.filter(i=>i.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(i=>i.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});c({rootPath:o(),sourcePath:o(),binding:OO,currentRelease:Uh,releases:h(Uh),transitions:h(NO)}).strict();c({profile:Yy,activate:C().default(!0),reason:o().trim().min(1).max(1e4),actor:o().trim().min(1).max(240).default("local-user"),authoringSkillHash:o().regex(/^[a-f0-9]{64}$/).nullable().default(null)}).strict();c({release:ce,reason:o().trim().min(1).max(1e4),actor:o().trim().min(1).max(240).default("local-user")}).strict();const j$=c({schemaVersion:w("openpond.trainingEngineCapabilities.v1"),adapterId:je,available:C(),methods:h(o().trim().min(1).max(100)),signalKinds:h(p$),modelFamilies:h(o().trim().min(1).max(200)),precisions:h(b(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:h(o().trim().min(1).max(200)),workerProtocolVersion:o().trim().min(1).max(200),upstreamRevision:o().trim().min(1).max(500),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:Ve,checkedAt:Nt,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),O$=c({schemaVersion:w("openpond.computeTargetCapabilities.v1"),adapterId:je,kind:b(["local","ssh","managed","custom"]),provider:je.nullable(),available:C(),devices:h(c({id:je,kind:b(["cpu","gpu","accelerator"]),vendor:o().trim().min(1).max(200),name:o().trim().min(1).max(500),memoryBytes:d().int().nonnegative().nullable(),runtime:o().trim().min(1).max(200)}).strict()),supportsWorkerImages:C(),supportsArtifactTransfer:C(),supportsCancellation:C(),capabilityReceipt:Ve,checkedAt:Nt,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),N$=c({schemaVersion:w("openpond.harnessRuntimeCapabilities.v1"),adapterId:je,available:C(),placements:h(b(["local","remote","colocated","provider_native"])),lifecycle:h(b(["create","reset","step","grade","collect","destroy"])),deterministicReplay:C(),privilegedIsolation:C(),capabilityReceipt:Ve,checkedAt:Nt,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict();c({schemaVersion:w("openpond.resolvedTrainingPlan.v1"),manifest:I$,recipe:Dy,runtime:qp,compute:Bp,engine:Fp,execution:c({trainingPlanId:je,approvalId:je}).strict().nullable(),maximumSpendUsd:d().nonnegative().nullable(),approvalHash:Ve,contentHash:Ve}).strict().superRefine((e,t)=>{const n=[["runtime",e.runtime,e.manifest.runtimeTarget],["compute",e.compute,e.manifest.computeTarget],["engine",e.engine,e.manifest.engine]];for(const[a,r,i]of n)JSON.stringify(r)!==JSON.stringify(i)&&t.addIssue({code:"custom",path:[a],message:`${a} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:"custom",path:["recipe","method"],message:"Recipe method must match the Harness Run Manifest"}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:"custom",path:["approvalHash"],message:"Approval hash must match the Harness Run Manifest"}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumSpendUsd"],message:"Maximum spend must match the Harness Run Manifest"})});c({schemaVersion:w("openpond.adapterValidationReceipt.v1"),adapterId:je,valid:C(),issues:h(c({code:je,path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}).strict()),capabilityReceipt:Ve,planHash:Ve,createdAt:Nt,contentHash:Ve}).strict();c({runId:je,adapterId:je,protocolVersion:b(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:b(["training_v2","adapter_native"]).default("adapter_native"),routeId:je.optional(),providerJobId:o().trim().min(1).max(1e3).nullable(),tenantId:je.optional(),leaseId:je.nullable(),manifestHash:Ve.optional(),inputBundleHash:Ve.optional(),createdAt:Nt}).strict();c({runId:je,state:b(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:o().trim().min(1).max(200),progress:d().min(0).max(1).nullable(),updatedAt:Nt,errorCode:je.nullable()}).strict();c({runId:je,manifestHash:Ve,artifacts:h(c({kind:b(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:o().trim().min(1).max(2e3),sha256:Ve,sizeBytes:d().int().nonnegative()}).strict()),contentHash:Ve}).strict();const fm=b(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),$$=c({id:je,label:o().trim().min(1).max(500),description:o().trim().min(1).max(2e3),destinationId:je,computeAdapterId:je,runtimeAdapterId:je,engineAdapterId:je,methods:h(o().trim().min(1).max(100)),capabilityPills:h(o().trim().min(1).max(100)),executionMode:b(["local_worker","provider_native"]),approvalPolicy:c({providerId:er,providerLabel:o().trim().min(1).max(200),settingsActionLabel:o().trim().min(1).max(500).nullable(),exportApprovalRequired:C(),exportDescription:o().trim().min(1).max(2e3).nullable(),preparationRequired:C(),minimumSpendUsd:d().nonnegative(),maximumSpendUsd:d().positive(),defaultMaximumSpendUsd:d().positive(),minimumRetentionDays:d().int().positive(),maximumRetentionDays:d().int().positive(),defaultRetentionDays:d().int().positive(),methodRequirement:o().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:c({maximumSequenceLength:d().int().positive(),maximumOutputTokens:d().int().positive(),maximumTrainingExamples:d().int().positive().nullable()}).strict(),defaults:c({loraRank:d().int().positive(),maxSteps:d().int().positive(),rolloutGroupSize:d().int().min(2).max(32),rolloutConcurrency:d().int().positive().max(32),rolloutOutputTokens:d().int().positive()}).strict(),available:C(),unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),D$=c({selectionKey:je,label:o().trim().min(1).max(500),source:b(["local","builtin","huggingface","managed","search"]),modelId:o().trim().min(1).max(1e3),revision:o().trim().min(1).max(500).nullable(),tokenizerRevision:o().trim().min(1).max(500).nullable(),chatTemplateHash:Ve.nullable(),modelAssetId:je.nullable(),expectedBytes:d().int().nonnegative().nullable(),cached:C(),known:C(),searchResolved:C(),computeAdapterIds:h(je),engineAdapterIds:h(je),preparationState:fm,reason:o().trim().min(1).max(5e3).nullable(),compatibilities:h(c({targetId:je,methods:h(o().trim().min(1).max(100)),state:fm,reason:o().trim().min(1).max(5e3).nullable()}).strict())}).strict();c({schemaVersion:w("openpond.trainingCatalog.v1"),models:h(D$).max(1e5),engines:h(j$),compute:h(O$),runtimes:h(N$),targets:h($$),generatedAt:Nt,contentHash:Ve}).strict();c({schemaVersion:w("openpond.trainingPreparationPlan.v1"),modelRunId:je,state:fm,reason:o().trim().min(1).max(5e3).nullable(),runtime:qp.nullable(),compute:Bp.nullable(),engine:Fp.nullable(),downloads:h(c({kind:w("model"),label:o().trim().min(1).max(500),expectedBytes:d().int().nonnegative(),digest:o().trim().min(8).max(500),cached:C(),state:b(["ready","required","downloading","cancelled","failed"]),progress:d().min(0).max(1).nullable(),cancellable:C(),diskImpactBytes:d().int().nonnegative()}).strict()),dataMovement:h(c({direction:b(["upload","download","none"]),label:o().trim().min(1).max(500),bytes:d().int().nonnegative().nullable()}).strict()),quoteUsd:d().nonnegative().nullable(),maximumSpendUsd:d().nonnegative().nullable(),retentionDays:d().int().nonnegative().nullable(),sideEffectsStarted:w(!1),contentHash:Ve}).strict();function L$(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const r=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&r.searchParams.set("afterSequence",String(n)),{url:r.toString(),init:{headers:a,signal:t}}}function z$(e){return Math.min(500*2**Math.max(0,e),1e4)}async function U$(e,t,n,a){$S(e);const r=e.body.getReader(),i=new TextDecoder;let s="";for(;!a?.aborted;){const{done:l,value:p}=await r.read();if(l){s+=i.decode();break}s+=i.decode(p,{stream:!0});let m=s.indexOf(`
126
-
127
- `);for(;m>=0;){const f=s.slice(0,m);s=s.slice(m+2),Zh(f,t,n),m=s.indexOf(`
128
-
129
- `)}}!a?.aborted&&s.trim()&&Zh(s,t,n)}function $S(e){if(!e.ok)throw new Error(`event stream failed: ${e.status} ${e.statusText||"HTTP error"}`);if(!e.body)throw new Error("event stream did not return a response body")}function H$(e,t,n,a,r={}){const i=new AbortController,s=r.fetchImpl??fetch,l=r.reconnectDelayMs??z$;let p=Gh(r.afterSequence),m=!1;return(async()=>{let f=0;for(;!i.signal.aborted;)try{const S=L$(e,i.signal,p),y=await s(S.url,S.init);if($S(y),m=!0,f=0,await U$(y,k=>{const R=Gh(k.sequence);R>0&&R<=p||(R>0&&(p=R),t(k))},a,i.signal),m=!1,i.signal.aborted)break;throw new Error("event stream ended")}catch(S){if(m=!1,i.signal.aborted)break;n(S),await q$(l(f),i.signal),f+=1}})().catch(()=>{}),{close(){i.abort()},isOpen(){return m}}}function Gh(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function Zh(e,t,n){let a="message";const r=[];for(const i of e.split(`
130
- `))i.startsWith(":")||(i.startsWith("event: ")&&(a=i.slice(7).trim()),i.startsWith("data: ")&&r.push(i.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||r.length===0))try{t(JSON.parse(r.join(`
131
- `)))}catch{}}async function q$(e,t){e<=0||t.aborted||await new Promise(n=>{const a=globalThis.setTimeout(n,e);t.addEventListener("abort",()=>{globalThis.clearTimeout(a),n()},{once:!0})})}function Jh(e={}){const t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),t}async function B(e,t,n){const a=new Headers(n?.headers);a.set("Content-Type","application/json"),a.set("Authorization",`Bearer ${e.token}`);const r=await fetch(`${e.serverUrl}${t}`,{...n,headers:a});if(!r.ok){const i=await r.json().catch(()=>({})),s=i&&typeof i=="object"&&"error"in i?String(i.error):r.statusText;throw new Error(s)}return await r.json()}function EV(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function MV(e){return["openpond-terminal",`openpond-token.${F$(e.token)}`]}function B$(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const r=t.subarray(a,a+32768);n+=String.fromCharCode(...r)}return btoa(n)}function F$(e){return B$(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function V$(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)n[a]=t.charCodeAt(a);return new TextDecoder().decode(n)}const W$={teamInvitations:e=>B(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>B(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>B(e,"/v1/organizations"),createOrganization:(e,t)=>B(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},K$={sendTurn:(e,t,n)=>B(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>B(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>B(e,`/v1/create-improve-runs?${G$(t).toString()}`),getCreateImproveRun:(e,t)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t)=>B(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST"}),compactSession:(e,t,n={reason:"manual"})=>B(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>B(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function G$(e){const t=new URLSearchParams;return e.profileId&&t.set("profileId",e.profileId),e.conversationId&&t.set("conversationId",e.conversationId),e.targetKind&&t.set("targetKind",e.targetKind),e.targetId&&t.set("targetId",e.targetId),e.limit&&t.set("limit",String(e.limit)),t}const Z$={sandboxFiles:(e,t,n={})=>{const a=new URLSearchParams({list:"1"});return n.path&&a.set("path",n.path),n.recursive!==void 0&&a.set("recursive",String(n.recursive)),n.maxEntries!==void 0&&a.set("maxEntries",String(n.maxEntries)),B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const r=new URLSearchParams({path:n});a.offsetBytes!==void 0&&r.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&r.set("maxBytes",String(a.maxBytes));const i=await B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${r.toString()}`);return{...i,contents:i.file.isBinary?"":V$(i.file.contentsBase64)}}},J$={sandboxGitStatus:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},Y$={connectedAppStatus:(e,t={})=>{const n=Jh(t);return n.set("status",t.status??"all"),B(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=Jh(t);return t.status&&n.set("status",t.status),B(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},X$={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return B(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>B(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:r,...i}=n;return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(i)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return B(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>B(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>B(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>B(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},Q$={sandbox:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},eD={...Y$,...X$,...Q$,...J$,...Z$},tD={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),B(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const r=new URLSearchParams;return a.beforeSequence!=null&&r.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&r.set("limit",String(a.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${r.size?`?${r}`:""}`)},sendCommunityMessage:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,r)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:r})}),deleteCommunityMessage:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/mute`,{method:"POST",body:JSON.stringify({muted:a})}),searchCommunityMembers:(e,t,n={})=>{const a=new URLSearchParams;return n.query&&a.set("query",n.query),n.cursor&&a.set("cursor",n.cursor),n.limit!=null&&a.set("limit",String(n.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/notifications`,{method:"POST",body:JSON.stringify({mode:n})}),communityEvents:(e,t,n={})=>{const a=new URLSearchParams;return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},Vp="openpond-app-server-url",ks="openpond-app-token",nD=750;function DS(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function hm(e){const t=e.getItem(Vp)?.trim(),n=e.getItem(ks)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Kl(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Ar(e,t){e.setItem(Vp,t.serverUrl),e.setItem(ks,t.token)}function Yh(e,t){const n=hm(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(Vp),e.removeItem(ks))}function aD(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function oD(){const e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;const t=new URLSearchParams(e),n=t.get("openpondToken")?.trim(),a=t.get("openpondServerUrl")?.trim()||DS();return!a||!n?null:{serverUrl:a,token:n}}function rD(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function bl(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function iD(){const e=[],t=Kl(window.sessionStorage),n=Kl(window.localStorage),a=DS(),r=t?.getItem(ks)??n?.getItem(ks);return bl(e,null),bl(e,a&&r?{serverUrl:a,token:r.trim()}:null),bl(e,t?hm(t):null),bl(e,n?hm(n):null),e}async function yu(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),nD);try{const a=await fetch(`${e}/health`,{signal:t.signal}),r=await a.json().catch(()=>null);return a.ok&&r?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function sD(){if(window.openpond)return window.openpond.getConnection();const e=Kl(window.sessionStorage),t=Kl(window.localStorage),n=oD();if(n&&await yu(n.serverUrl))return t&&Ar(t,n),e&&Ar(e,n),rD(),{...n,platform:navigator.platform};const a=aD();if(a&&await yu(a.serverUrl))return t&&Ar(t,a),e&&Ar(e,a),{...a,platform:navigator.platform};const r=iD();for(const i of r){if(await yu(i.serverUrl))return t&&Ar(t,i),e&&Ar(e,i),{...i,platform:navigator.platform};e&&Yh(e,i),t&&Yh(t,i)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const J={...tD,bootstrap:e=>B(e,"/v1/bootstrap?refreshCodex=1"),localProjectActions:(e,t)=>B(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>B(e,"/v1/extensions"),extensionPreview:(e,t)=>B(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>B(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>B(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>B(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>B(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>B(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>B(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>B(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>B(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>B(e,`/v1/team-chat/realtime-session?teamId=${encodeURIComponent(t)}`),teamChatEvents:(e,t,n={})=>{const a=new URLSearchParams({teamId:t});return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),B(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>B(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>B(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const r=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&r.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&r.set("limit",String(a.limit)),B(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${r.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>B(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>B(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>B(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>B(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>B(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>B(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=Xh(t),a=n.size?`?${n.toString()}`:"";return B(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=Xh(t);t.sessionId&&n.set("sessionId",t.sessionId),t.turnId&&n.set("turnId",t.turnId),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return B(e,`/v1/usage/records${a}`)},runtimeEventsPage:(e,t={})=>{const n=new URLSearchParams;t.sessionId&&n.set("sessionId",t.sessionId),t.afterSequence!==void 0&&n.set("afterSequence",String(t.afterSequence)),t.beforeSequence!==void 0&&t.beforeSequence!==null&&n.set("beforeSequence",String(t.beforeSequence)),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return B(e,`/v1/events/page${a}`)},workOutputs:e=>B(e,"/v1/work/outputs"),harnessHistory:e=>B(e,"/v1/harness"),refinerHistory:e=>B(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>B(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>B(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>B(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>B(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>B(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>B(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>B(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>B(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>B(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>B(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>B(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>B(e,`/v1/training/activity?profileId=${encodeURIComponent(t)}`),portableTrainingCatalog:(e,t="",n)=>{const a=new URLSearchParams;return t.trim()&&a.set("query",t.trim()),n&&a.set("method",n),B(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>B(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t)=>B(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail`),trainingRequest:(e,t,n,a="POST")=>B(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>B(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>B(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>B(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>B(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({clientRequestId:n})}),localAgentSchedules:(e,t={})=>{const n=new URLSearchParams;t.localProjectId&&n.set("localProjectId",t.localProjectId);const a=n.size?`?${n.toString()}`:"";return B(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>B(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),localAgentScheduleRuns:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit));const r=a.size?`?${a.toString()}`:"";return B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${r}`)},refreshOpenPondAccounts:e=>B(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>B(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>B(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),saveOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>B(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>B(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>B(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>B(e,"/v1/providers"),loadProviderModels:(e,t,n={})=>{const a=new URLSearchParams;n.query?.trim()&&a.set("query",n.query.trim()),n.limit&&a.set("limit",String(n.limit));const r=a.size?`?${a.toString()}`:"";return B(e,`/v1/providers/${encodeURIComponent(t)}/models${r}`)},refreshProviderModels:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>B(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>B(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>B(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>B(e,"/v1/profile"),profileCatalog:e=>B(e,"/v1/profile/catalog"),profileSelect:(e,t)=>B(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>B(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>B(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>B(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>B(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>B(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>B(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>B(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>B(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>B(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>B(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>B(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>B(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>B(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>B(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>B(e,"/v1/remote-access"),enableRemoteAccess:e=>B(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>B(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:e=>B(e,"/v1/audio/transcriptions/status"),transcribeVoice:(e,t)=>B(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t)}),createSession:(e,t)=>B(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>B(e,`/v1/sessions/${t}`,{method:"PATCH",body:JSON.stringify(n)}),codexHistoryThread:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit)),n.tail&&a.set("tail","1");const r=a.size?`?${a.toString()}`:"";return B(e,`/v1/codex-history/${encodeURIComponent(t)}${r}`)},codexHistoryThreadIncremental:(e,t,n={})=>{const a=new URLSearchParams({incremental:"1"});return n.afterEventId&&a.set("afterEventId",n.afterEventId),n.limit!==void 0&&a.set("limit",String(n.limit)),n.revision&&a.set("revision",n.revision),n.tail&&a.set("tail","1"),B(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>B(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>B(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>B(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>B(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>B(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>B(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),workspaceFile:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>B(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>B(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>B(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>B(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>B(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>B(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...W$,...eD,createLocalProject:(e,t)=>B(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>B(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>B(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source`,{method:"POST",body:JSON.stringify(n)}),previewLocalProjectCloudSource:(e,t,n={})=>{const a=new URLSearchParams;n.branch?.trim()&&a.set("branch",n.branch.trim());const r=a.toString()?`?${a.toString()}`:"";return B(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${r}`)},deleteLocalProject:(e,t)=>B(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>B(e,"/v1/system/git"),installMacOSCommandLineTools:e=>B(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...K$,resolveApproval:(e,t,n)=>B(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function Xh(e){const t=new URLSearchParams;return e.range&&t.set("range",e.range),e.visibility&&t.set("visibility",e.visibility),e.status&&t.set("status",e.status),e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),t}const lD=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),cD=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),Qh=e=>{const t=cD(e);return t.charAt(0).toUpperCase()+t.slice(1)},LS=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),dD=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var uD={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const mD=g.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:r="",children:i,iconNode:s,...l},p)=>g.createElement("svg",{ref:p,...uD,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:LS("lucide",r),...!i&&!dD(l)&&{"aria-hidden":"true"},...l},[...s.map(([m,f])=>g.createElement(m,f)),...Array.isArray(i)?i:[i]]));const gt=(e,t)=>{const n=g.forwardRef(({className:a,...r},i)=>g.createElement(mD,{ref:i,iconNode:t,className:LS(`lucide-${lD(Qh(e))}`,`lucide-${e}`,a),...r}));return n.displayName=Qh(e),n};const pD=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],fD=gt("archive-restore",pD);const hD=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],gD=gt("arrow-left",hD);const bD=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],zS=gt("bookmark",bD);const vD=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]],US=gt("bookmark-x",vD);const yD=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]],eg=gt("book-open-text",yD);const SD=[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]],xD=gt("boxes",SD);const kD=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],_D=gt("calendar-clock",kD);const wD=[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]],gm=gt("chart-column-stacked",wD);const ID=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ho=gt("check",ID);const CD=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],HS=gt("circle-check",CD);const RD=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],bo=gt("chevron-down",RD);const AD=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Yo=gt("chevron-right",AD);const PD=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],TD=gt("circle-alert",PD);const ED=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Ac=gt("cloud",ED);const MD=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],jD=gt("credit-card",MD);const OD=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],ND=gt("download",OD);const $D=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Su=gt("external-link",$D);const DD=[["path",{d:"M4.226 20.925A2 2 0 0 0 6 22h12a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v3.127",key:"wfxp4w"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]],LD=gt("file-output",DD);const zD=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Wp=gt("file-text",zD);const UD=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],HD=gt("folder",UD);const qD=[["path",{d:"M18 19a5 5 0 0 1-5-5v8",key:"sz5oeg"}],["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]],qS=gt("folder-git-2",qD);const BD=[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]],FD=gt("github",BD);const VD=[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],BS=gt("earth",VD);const WD=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],KD=gt("circle-question-mark",WD);const GD=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],ZD=gt("list-filter",GD);const JD=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],YD=gt("loader-circle",JD);const XD=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],QD=gt("maximize-2",XD);const eL=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Pc=gt("message-square",eL);const tL=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Kp=gt("ellipsis",tL);const nL=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],FS=gt("panel-left",nL);const aL=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],bm=gt("panel-right",aL);const oL=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]],Gp=gt("pin",oL);const rL=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],Zp=gt("pin-off",rL);const iL=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],sL=gt("search",iL);const lL=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Jp=gt("settings",lL);const cL=[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]],dL=gt("shapes",cL);const uL=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],Yp=gt("square-pen",uL);const mL=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],VS=gt("square-terminal",mL);const pL=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],fL=gt("user-round",pL);const hL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],ui=gt("x",hL);function gL({platform:e}){return!Tc()||Xp(e)?null:v.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[v.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{xu("minimize")},children:v.jsx(bo,{size:14})}),v.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{xu("toggleMaximize")},children:v.jsx(QD,{size:12})}),v.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{xu("close")},children:v.jsx(ui,{size:13})})]})}function Xp(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function Tc(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function xu(e){const t=window.openpond;if(!(t&&(e==="minimize"?await t.minimizeWindow?.():e==="toggleMaximize"?await t.toggleMaximizeWindow?.():await t.closeWindow?.())!==!1)){if(e==="toggleMaximize"&&document.fullscreenEnabled){document.fullscreenElement?await document.exitFullscreen():await document.documentElement.requestFullscreen();return}if(e==="close"){window.close();return}console.warn("Window controls require the Electron desktop shell.")}}const bL=[{destination:"walkthroughs",icon:eg,label:"Walkthroughs"},{destination:"external",icon:eg,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:Wp,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:jD,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:BS,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:FD,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:Pc,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function vL({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=g.useState(!1),r=g.useRef(null);return g.useEffect(()=>{if(!n)return;function i(l){r.current?.contains(l.target)||a(!1)}function s(l){l.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",i),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("keydown",s)}},[n]),v.jsxs("div",{className:"sidebar-help-menu",ref:r,children:[v.jsx("button",{"aria-expanded":n,"aria-haspopup":"menu","aria-label":"Open docs and help menu",className:`sidebar-icon sidebar-help-trigger ${t?"active":""}`,"data-tooltip":"Help",onClick:()=>a(i=>!i),type:"button",children:v.jsx(KD,{size:17})}),n?v.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:bL.map(i=>{const s=i.icon,l=v.jsxs(v.Fragment,{children:[v.jsx(s,{size:15}),v.jsx("span",{children:i.label})]});return i.destination==="walkthroughs"?v.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:l},i.label):v.jsx("a",{className:"sidebar-help-item",href:i.url,onClick:p=>{p.preventDefault(),a(!1),yL(i.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},i.label)})}):null]})}async function yL(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const jV=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],ku=[{value:"chat",label:"Work",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"}];function WS(e){return e==="chat"?"New chat":"New task"}const SL=["overview","tasksets","evals","runs","serving"],tg=new Set(SL),xL={runs:new Set(["overview","metrics","evaluation","activity","artifacts"]),tasksets:new Set(["overview","scenarios","rewards","validation"]),evals:new Set(["overview","lineage","evaluation","activity"])},kL={evals:"evals",overview:"overview",rollouts:"runs",runs:"runs",serving:"serving",tasksets:"tasksets",training:"runs",versions:"evals"},_L={versions:"evals"},wL=new Set(["account","notifications","harness","harness-refiner","harness-continuous-review","harness-contents","harness-releases","profile","skills","defaults","context","training","subagents","editor","providers","dataset-storage","remote","usage","personalization","diagnostics"]),KS={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"},IL=new Map(Object.entries(KS).map(([e,t])=>[t,e])),Ml=new Set;let vl=!1,vm="",ng=null,ym="",ag=null;function ms(e){try{return decodeURIComponent(e)}catch{return e}}function CL(e){const t=e.lastIndexOf("models");if(t<0)return null;const[n,a,r,i,...s]=e.slice(t+1);if(!n)return{kind:"index"};if(tg.has(n))return null;if(!a)return{kind:"project",projectId:ms(n),section:"overview",resourceId:null,detailTab:null};const l=_L[a]??a;return!tg.has(l)||l==="overview"||s.length||l==="serving"&&(r||i)||i&&!xL[l]?.has(i)?null:{kind:"project",projectId:ms(n),section:l,resourceId:r?ms(r):null,detailTab:i??null}}function GS(e){const t=CL(e.pathname.split("/").filter(Boolean));if(t)return t;const n=new URLSearchParams(e.search??""),a=n.get("modelProjectId"),r=n.get("modelsTab");return!a&&!r?null:a?{kind:"project",projectId:a,section:r?kL[r]??"overview":"overview",resourceId:null,detailTab:null}:{kind:"index"}}function RL(e){if(e.kind==="index")return"/models";const t=["/models",encodeURIComponent(e.projectId)];return e.section==="overview"||(t.push(e.section),e.resourceId&&t.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&t.push(e.detailTab)),t.join("/")}function AL(e){const t=GS(e);if(t)return{kind:"models",route:t};const n=e.pathname.split("/").filter(Boolean);if(n[0]==="settings"&&n.length===2){const r=ms(n[1]);return wL.has(r)?{kind:"settings",section:r}:null}if(n[0]==="chat"&&n.length<=2)return{kind:"chat",sessionId:n[1]&&n[1]!=="new"?ms(n[1]):null};const a=IL.get(e.pathname);return a?{kind:"view",view:a}:null}function PL(e){return e.kind==="models"?RL(e.route):e.kind==="settings"?`/settings/${e.section}`:e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":KS[e.view]}function TL(e){return e.kind==="project"?e.section:"overview"}function EL(){if(typeof window>"u")return null;const e=`${window.location.pathname}${window.location.search}`;return e!==vm&&(vm=e,ng=GS(window.location)),ng}function ML(){if(typeof window>"u")return null;const e=`${window.location.pathname}${window.location.search}`;return e!==ym&&(ym=e,ag=AL(window.location)),ag}function Sm(){vm="",ym="";for(const e of Ml)e()}function ZS(e){return Ml.add(e),typeof window<"u"&&!vl&&(window.addEventListener("popstate",Sm),vl=!0),()=>{Ml.delete(e),vl&&Ml.size===0&&typeof window<"u"&&(window.removeEventListener("popstate",Sm),vl=!1)}}function jL(){return g.useSyncExternalStore(ZS,EL,()=>null)}function OL(){return g.useSyncExternalStore(ZS,ML,()=>null)}function Qt(e,t="push"){if(typeof window>"u")return;const n=PL(e);window.location.pathname===n&&!window.location.search||(window.history[t==="replace"?"replaceState":"pushState"](window.history.state,"",n),Sm())}function Fr(e,t="push"){Qt({kind:"models",route:e},t)}function og(e,t="overview"){return e?{kind:"project",projectId:e,section:t,resourceId:null,detailTab:null}:{kind:"index"}}function NL({experience:e="work",productArea:t="chat",beginNewChat:n,setSectionMenuOpen:a,setSelectedAppId:r,setSelectedProjectId:i,setSelectedSessionId:s,setView:l,view:p,modelProjects:m=[],modelTrainingActivityByProjectId:f={}}){const S=jL(),y=S?.kind==="project"?S.projectId:null,k=TL(S??{kind:"index"});function R(){r(null),i(null),s(null),a(null)}function A(x){R(),l("labs"),Fr(og(y,x))}function D(x){R(),l("labs"),Fr(og(x||null))}function z(x){R(),l(x),Qt({kind:"view",view:x})}const N=y?f[y]??null:null;return v.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[t==="models"?null:v.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{Qt({kind:"chat",sessionId:null}),n(null)},children:[v.jsx(Yp,{size:18}),v.jsx("span",{children:WS(e)})]}),t==="models"?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"sidebar-model-project-picker",children:v.jsx("select",{"aria-label":"Select Model Project",disabled:!m.length,value:y??m[0]?.id??"",onChange:x=>D(x.target.value),children:m.map(x=>v.jsx("option",{value:x.id,children:x.name},x.id))})}),y?v.jsxs(v.Fragment,{children:[v.jsxs("button",{className:`nav-command ${p==="labs"&&k==="overview"?"active":""}`,"aria-label":"Overview",type:"button",onClick:()=>A("overview"),children:[v.jsx(gm,{size:16}),v.jsx("span",{children:"Overview"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&k==="tasksets"?"active":""}`,"aria-label":"Tasksets",type:"button",onClick:()=>A("tasksets"),children:[v.jsx(xD,{size:16}),v.jsx("span",{children:"Tasksets"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&k==="evals"?"active":""}`,"aria-label":"Evals",type:"button",onClick:()=>A("evals"),children:[v.jsx(HS,{size:16}),v.jsx("span",{children:"Evals"})]}),v.jsxs("button",{className:`nav-command ${N?"nav-command-training-live ":""}${p==="labs"&&k==="runs"?"active":""}`,"aria-label":N?`Runs, ${N.label}`:"Runs",type:"button",onClick:()=>A("runs"),children:[v.jsx(gm,{size:16}),v.jsx("span",{children:"Runs"}),N?v.jsx("span",{className:"nav-command-training-status","aria-label":`Training ${N.label.toLowerCase()}`,title:`Training ${N.label.toLowerCase()}`,children:v.jsx("span",{className:"sidebar-running-dot","aria-hidden":"true"})}):null]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&k==="serving"?"active":""}`,"aria-label":"Serving",type:"button",onClick:()=>A("serving"),children:[v.jsx(Ac,{size:16}),v.jsx("span",{children:"Serving"})]})]}):null]}):null,t==="chat"?v.jsxs(v.Fragment,{children:[v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{z("scheduled")},children:[v.jsx(_D,{size:18}),v.jsx("span",{children:"Workflows"})]}),v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{z("outputs")},children:[v.jsx(LD,{size:18}),v.jsx("span",{children:"Outputs"})]}),v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{z("apps")},children:[v.jsx(dL,{size:18}),v.jsx("span",{children:"Apps"})]}),v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{z("projects")},children:[v.jsx(qS,{size:18}),v.jsx("span",{children:"Projects"})]})]}):null]})}function $L({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:r,view:i}){function s(){t(null),n(null),a(null),e(null),r("get-started"),Qt({kind:"view",view:"get-started"})}return v.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:v.jsx(vL,{onOpenWalkthroughs:s,walkthroughsActive:i==="get-started"})})}const jl=5,jn=15,xm=10,Rt={defaultChatProvider:Zo,subagents:cR(),codexPermissionMode:uc,codexReasoningEffort:mc,openPondCommandAccessMode:Es,defaultBranchPrefix:"feat/",defaultNewProjectDirectory:"",advancedWorkspaceControls:!1,contextCompaction:{autoEnabled:!0,triggerPercent:85,summaryModel:"same_model"},training:{defaultModelRef:null,creationMode:"customize",autoApproveEvidence:!1},sidebarWidth:332,diffPanelWidth:560,sidebarSectionsCollapsed:{pinned:!1,projects:!1,cloudProjects:!1,chats:!1,savedForLater:!0},editor:{languageServers:"auto",diagnosticsWhileEditing:!0,checkOnSave:!0,languages:{typescript:{mode:"auto",customCommand:""},python:{mode:"auto",customCommand:""},rust:{mode:"auto",customCommand:""}}}},OV={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},JS=[{value:Ts,label:"DeepSeek V4 Pro",description:"reasoning"},{value:"accounts/fireworks/models/kimi-k3",label:"Kimi K3",description:"reasoning"},{value:"accounts/fireworks/models/glm-5p2",label:"GLM-5.2",description:"reasoning"},{value:"accounts/fireworks/models/deepseek-v4-pro",label:"DeepSeek V4 Pro (Fireworks)",description:"reasoning"},{value:"accounts/fireworks/models/deepseek-v4-flash",label:"DeepSeek V4 Flash (Fireworks)",description:"reasoning"},{value:"accounts/fireworks/models/nemotron-lightning-3p5-30b-a3b",label:"Nemotron Lightning 3.5 30B A3B",description:"reasoning"},{value:"accounts/fireworks/models/minimax-m3",label:"MiniMax M3",description:"reasoning"}],_u=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],DL=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],LL=["openpond","codex",...DL],YS=new Set(LL),XS=[{value:rp,label:"GPT-5.6 Sol"},{value:"gpt-5.6-terra",label:"GPT-5.6 Terra"},{value:"gpt-5.6-luna",label:"GPT-5.6 Luna"},{value:"gpt-5.5",label:"GPT-5.5"},{value:"gpt-5.4",label:"GPT-5.4"},{value:"gpt-5.4-mini",label:"GPT-5.4 Mini"},{value:"gpt-5.3-codex",label:"GPT-5.3 Codex"},{value:"gpt-5.3-codex-spark",label:"GPT-5.3 Codex Spark"},{value:"gpt-5.2",label:"GPT-5.2"}],NV=[{value:"default",label:"Default permissions",shortLabel:"Default",description:"Workspace sandbox; asks before crossing boundaries."},{value:"auto-review",label:"Auto-review",description:"Workspace sandbox; reviewer handles eligible approvals."},{value:"full-access",label:"Full access",description:"No sandbox or approval prompts."}],$V=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],DV=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],LV=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],zV=[{value:"auto",label:"Auto",description:"Find the local executable automatically."},{value:"disabled",label:"Disabled",description:"Do not start this language server."},{value:"custom",label:"Custom",description:"Use a specific executable path or command name."}];function Qp(e){return e.kind==="local"}function zL(e){return e.kind==="cloud"}function ht(e,t){return`${e}:${t}`}function QS(e){const t=e?.trim();if(!t)return null;const n=t.indexOf(":");if(n<=0)return{kind:"local",id:t};const a=t.slice(0,n),r=t.slice(n+1);return(a==="local"||a==="cloud")&&r?{kind:a,id:r}:{kind:"local",id:t}}function Vo(e){return`${e.type}:${e.id}`}function Gl(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function Zl(e,t,n,a="before"){if(t===n)return e;const r=e.filter(s=>s!==t),i=r.indexOf(n);return i===-1?e:(r.splice(a==="after"?i+1:i,0,t),r)}function rg(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function UL(e,t){if(!t)return e;const n=new Map(e.map(i=>[i.key,i])),a=t.map(i=>n.get(i)).filter(i=>!!i),r=new Set(a.map(i=>i.key));return[...a,...e.filter(i=>!r.has(i.key))]}function ef(e,t){return e?.statuses?.[t]??null}function ex(e,t){return e?.providers?.[t]??null}function tx(e,t){return e?.modelCaches?.[t]??null}function HL(e){const t=[e.contextWindow?`${Math.round(e.contextWindow/1e3)}K context`:"",e.capabilities.reasoning?"reasoning":"",e.source].filter(Boolean);return{value:e.id,label:e.displayName||e.id,description:t.join(" · ")||void 0}}function qL(e){return e==="openpond"?JS:e==="codex"||e==="openai"?XS:[]}function BL(e){const t=new Set,n=[];for(const a of e)!a.value||t.has(a.value)||(t.add(a.value),n.push(a));return n}function UV(e){return YS.has(e)}function km(e,t={}){if(!e)return t.localOnly,_u;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,r=[];for(const i of Gm){if(!YS.has(i)||t.localOnly&&i==="openpond")continue;const s=ef(e,i);s&&(!n&&(i==="codex"&&!s.available&&!s.credential.connected||i!=="openpond"&&i!=="codex"&&!s.enabled)||a&&i!=="openpond"&&!s.enabled||a&&i==="codex"&&!s.available&&!s.credential.connected||r.push({value:i,label:i==="openpond"?"OpenPond Chat":s.displayName,description:i==="openpond"?void 0:s.available?"Connected":s.credential.connected?"Configured":s.routing.localByok?"Set up key":s.enabled?"Enabled":void 0}))}return r.length>0?r:_u}function _s(e,t){const a=(tx(t,e)?.models??[]).map(HL),r=ex(t,e),i=[...r?.modelOverrides??[],r?.defaultModel].filter(s=>!!s?.trim()).map(s=>({value:s,label:s}));return BL([...a,...i,...qL(e)])}function FL(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const r=tx(n,e)?.models.find(i=>i.id===a);return r?!!r.capabilities.reasoning:_s(e,n).some(i=>i.value===a&&/\breasoning\b/i.test(i.description??""))}function Jl(e,t){const n=ex(t,e)?.defaultModel?.trim();if(n)return n;const a=ef(t,e)?.defaultModel?.trim();if(a)return a;const r=_s(e,t)[0]?.value?.trim();return r||(e==="codex"?rp:e==="openpond"?Ts:"")}function ko(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return rp;const r=_s(e,n);return a&&r.some(i=>i.value===a)||a&&e!=="codex"&&r.length===0&&!n?a:Jl(e,n)}function nx(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:ko(n,e.modelRef?.modelId,t)}}function tf(e,t,n){return ko(e,t,n)||void 0}function ba(e,t,n){const a=tf(e,t,n);return a?{providerId:e,modelId:a}:void 0}function ig(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function Qn(e){const t=e?.defaultChatProvider??Rt.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:ko(t,e?.defaultChatModel),subagents:hs.parse(e?.subagents??Rt.subagents),codexPermissionMode:e?.codexPermissionMode??Rt.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Rt.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Rt.openPondCommandAccessMode,defaultBranchPrefix:ax(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Rt.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Rt.advancedWorkspaceControls,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Rt.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Rt.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Rt.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Rt.training.defaultModelRef,creationMode:e?.training?.creationMode??Rt.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Rt.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Rt.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Rt.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Rt.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Rt.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Rt.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Rt.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Rt.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Rt.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Rt.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Rt.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Rt.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Rt.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Rt.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Rt.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Rt.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Rt.editor.languages.rust.customCommand}}}}}function ax(e){const t=e?.trim()??Rt.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(r=>r.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function HV(e,t){return e==="openpond"?"OpenPond Chat":ef(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function qV(e,t,n){if(n){const a=_s(n,t).find(r=>r.value===e);if(a)return a.label}if(t)for(const a of Gm){const r=_s(a,t).find(i=>i.value===e);if(r)return r.label}return[...JS,...XS].find(a=>a.value===e)?.label??e}function VL(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function WL(e){return e.experience==="chat"?"Chat":"Work"}const nf="taskDraft";function ox(e){if(e?.experience!=="work")return null;const t=e.metadata?.[nf];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function ws(e){return ox(e)!==null}function KL(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function wu(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[nf]:a}}function GL(e){const t={...e??{}};return delete t[nf],t}function mo(e){const t=yl(e.metadata?.trainingTasksetId)??yl(e.metadata?.tasksetId);return t?{id:t,name:yl(e.metadata?.trainingTasksetName)??yl(e.metadata?.tasksetName)??ZL(t)}:null}function ZL(e){const n=e.replace(/[-_][a-f0-9]{8,}$/i,"").replace(/^(?:benchmark[-_])?taskset[-_]/i,"").replace(/^benchmark[-_]/i,"").split(/[-_]+/).filter(Boolean);return n.length===0?"Taskset":n.map(a=>/^[A-Z0-9]{2,}$/.test(a)?a:`${a.charAt(0).toUpperCase()}${a.slice(1)}`).join(" ")}function yl(e){return typeof e=="string"&&e.trim()?e.trim():null}const sg=[{value:"active",label:"Active"},{value:"in_progress",label:"In progress"},{value:"pinned",label:"Pinned"},{value:"saved_for_later",label:"Save for later"},{value:"tasksets",label:"Tasksets"},{value:"done",label:"Done"},{value:"all",label:"All"}],JL=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function lg(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(a=>!mo(a)));else if(e.filter==="all")t.push(...e.activeSessions.filter(a=>!mo(a)),...e.doneSessions.filter(a=>!mo(a)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(a=>cg(a,e.selectedTasksetId)),...e.doneSessions.filter(a=>cg(a,e.selectedTasksetId)));else for(const a of e.activeSessions)mo(a)||(e.filter==="active"?a.savedForLater||t.push(a):e.filter==="in_progress"?!a.savedForLater&&e.inProgressSessionIds.has(a.id)&&t.push(a):e.filter==="pinned"?a.pinned&&!a.savedForLater&&t.push(a):e.filter==="saved_for_later"&&a.savedForLater&&t.push(a));const n=e.previewSessionIds?new Map(e.previewSessionIds.map((a,r)=>[a,r])):null;return e.sort==="recent"?t.sort((a,r)=>ug(a,r,n)):t.sort((a,r)=>{const i=n?.get(a.id),s=n?.get(r.id);if(i!==void 0||s!==void 0){if(i===void 0)return 1;if(s===void 0)return-1;if(i!==s)return i-s}return a.order!==r.order?a.order-r.order:ug(a,r)})}function cg(e,t){const n=mo(e);return!!(n&&(!t||n.id===t))}function YL(e){return e.filter==="saved_for_later"||e.filter==="tasksets"?{count:Math.max(0,e.activeCount),label:"In Progress",targetFilter:"active",targetLabel:"active"}:{count:Math.max(0,e.savedForLaterCount),label:"Later",targetFilter:"saved_for_later",targetLabel:"saved for later"}}function XL(e,t){switch(e){case"active":return`No active ${t}`;case"in_progress":return"No work in progress";case"pinned":return`No pinned ${t}`;case"saved_for_later":return"Nothing saved for later";case"tasksets":return"No Taskset chats yet";case"done":return`No done ${t}`;case"all":return`No ${t}`}}function dg(e,t,n){const a=new Set(t);let r=0;return e.map(i=>{if(!a.has(i))return i;const s=n[r];return r+=1,s??i})}function ug(e,t,n=null){const a=Yl(e),r=Yl(t);if(a!==r)return a?-1:1;if(a&&r){const s=n?.get(e.id),l=n?.get(t.id);if(s!==void 0||l!==void 0){if(s===void 0)return 1;if(l===void 0)return-1;if(s!==l)return s-l}if(e.order!==t.order)return e.order-t.order}const i=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return i!==0?i:e.title.localeCompare(t.title)}function Yl(e){return e.pinned&&!e.savedForLater&&!e.archived}function rx(e){return`${e.kind}:${e.id}`}function Is(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function QL(e){return{kind:"session",id:e}}function ez(e){return{kind:"project",id:e}}function tz(e){return{kind:"draft",id:e}}function nz(e){return e.selectedSessionId?QL(e.selectedSessionId):e.selectedProjectId?ez(e.selectedProjectId):tz(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function az(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Is(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Is(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function BV(e,t){return e.filter(n=>Is(n.scope,t))}function FV(e,t){return!!(e&&Is(e.scope,t))}function oz(e){const t={};for(const n of e){const a=rx(n.scope),r=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};r.tabCount+=1,n.commandStatus==="running"&&(r.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(r.failedCount+=1),n.lastExitCode!==null&&(r.lastExitCode=n.lastExitCode),r.status=iz(r.status,n.status,n.commandStatus),t[a]=r}return t}function rz(e){return!e||e.status==="none"||e.tabCount===0?null:e.status==="running"?{status:"running",label:"Terminal running"}:e.status==="failed"?{status:"failed",label:"Terminal last command failed"}:e.status==="success"?{status:"success",label:"Terminal last command succeeded"}:e.status==="idle"?{status:"idle",label:"Terminal idle"}:{status:"unknown",label:"Terminal open"}}function iz(e,t,n){return n==="running"?"running":e==="running"?e:n==="failed"||t==="error"?"failed":e==="failed"?e:n==="success"?e==="none"||e==="unknown"||e==="idle"?"success":e:n==="idle"?e==="none"||e==="unknown"?"idle":e:e==="none"?"unknown":e}function ix(e,t){if(!e)return t?.path??"Use files on this machine";if(e.error)return"status unavailable";if(!e.initialized)return"not checked out";const a=[e.currentBranch??t?.branch??e.defaultBranch??"no branch"],r=lz(e),i=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return r?a.push(r):i?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(po("ahead",e.ahead)),e.behind>0&&a.push(po("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(po("ahead",e.ahead)),e.behind>0&&a.push(po("behind",e.behind))),e.changedFilesCount>0?a.push(`${e.changedFilesCount} changed`):e.dirty&&a.push("dirty"),e.untrackedFilesCount>0&&a.push(`${e.untrackedFilesCount} untracked`),a.length===1&&a.push("synced"),a.join(" / ")}function sx(e,t,n,a={}){const r=e?.linkedSandboxProject??null;if(!r?.projectId&&!t)return"upload required";if(r?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const i=r?.defaultBranch??t?.defaultBranch??"main",s=r?.manifestHash??null,l=e?.sandboxTemplate?.manifestHash??null,p=r?.syncedAt??t?.syncedAt??null,m=!!(s&&l&&s!==l),f=!!(r?.projectId&&n?.headCommit&&!r.lastUploadedCommit),S=cz(n);return S?`${i} / ${S}`:f?`${i} / upload required`:`${i} / ${m||!p?"needs sync":"setup ready"}`}function sz(e,t,n={}){if(!e)return"select a local project";if(e.linkedSandboxProject?.projectId&&n.cloudLinkTrusted===!1)return"sync to this account";if(!t)return e.linkedSandboxProject?"sync source to cloud":"push local source to cloud";if(t.error)return"repo status unavailable";if(!t.initialized)return"local repo unavailable";const a=[],r=t.aheadOfLinkedSource>0?t.aheadOfLinkedSource:t.ahead;return e.linkedSandboxProject?.projectId||a.push("upload required"),e.linkedSandboxProject?.projectId&&t.headCommit&&!e.linkedSandboxProject.lastUploadedCommit&&a.push("upload required"),r>0&&a.push(lx(r)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&r===0&&a.push("source changed"),t.changedFilesCount>0&&a.push(`${t.changedFilesCount} changed file${t.changedFilesCount===1?"":"s"}`),t.untrackedFilesCount>0&&a.push(`${t.untrackedFilesCount} untracked skipped`),a.length>0?a.join(" / "):"nothing to upload"}function lz(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?po("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?po("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function cz(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?po("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?po("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function po(e,t){return`${e} by ${lx(t)}`}function lx(e){return`${e} commit${e===1?"":"s"}`}function dz({size:e=14,className:t}){return v.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[v.jsx("path",{d:"M12 13v8"}),v.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),v.jsx("path",{d:"m8 17 4-4 4 4"})]})}function cx({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:r=15}){const i=e==="cloud"?"cloud":n?"folder-open":"folder";return v.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:v.jsxs("svg",{className:`lucide lucide-${i} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?v.jsx(pz,{}):n?v.jsx(mz,{}):v.jsx(uz,{}),t&&e==="local"?v.jsx(fz,{}):null]})})}function uz(){return v.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function mz(){return v.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function pz(){return v.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function fz(){return v.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[v.jsx("circle",{cx:"18",cy:"17",r:"5"}),v.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}function hz({session:e,onSave:t,onClose:n}){const[a,r]=g.useState(e.title),i=g.useRef(null);g.useEffect(()=>{const p=i.current;p&&(p.focus(),p.select())},[]),g.useEffect(()=>{function p(m){m.key==="Escape"&&n()}return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[n]);function s(){const p=a.trim();p&&(t(p),n())}function l(p){p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),s())}return v.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:v.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:p=>p.stopPropagation(),children:[v.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),v.jsx("textarea",{ref:i,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:p=>r(p.target.value),onKeyDown:l,"aria-label":"Chat title"}),v.jsxs("div",{className:"git-dialog-footer",children:[v.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),v.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const gz=24;function bz({title:e}){const t=g.useRef(e),[n,a]=g.useState(e);return g.useEffect(()=>{const r=t.current;if(t.current=e,!e){a("");return}if(r||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const i=Array.from(e);let s=0;a("");const l=window.setInterval(()=>{s+=1,a(i.slice(0,s).join("")),s>=i.length&&window.clearInterval(l)},gz);return()=>window.clearInterval(l)},[e]),v.jsx("span",{className:`sidebar-task-title-text${e?"":" pending"}`,"aria-label":e||"Creating title",children:n||" "})}const vz=2650,yz=304,Sz=260,xz=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),kz=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),_z=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function wz(){return{animationDelay:`${-(Date.now()%vz)}ms`}}function Iz(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),r=a>2;t.dataset.overflowing=String(r),t.style.setProperty("--sidebar-title-ticker-distance",`${-a}px`),t.style.setProperty("--sidebar-title-ticker-duration",`${Math.min(6.5,Math.max(2.8,a/42+2.4))}s`)}function mg({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:r,children:i,collapsed:s=!1,titleActive:l=!1,onTitleClick:p,onToggleCollapsed:m}){return v.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[v.jsxs("div",{className:"section-header",children:[v.jsxs("div",{className:"section-title-row",children:[p?v.jsxs("div",{className:"section-title-combo",children:[v.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:p,children:v.jsx("span",{children:e})}),m&&v.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:m,children:s?v.jsx(Yo,{size:13}):v.jsx(bo,{size:13})})]}):m?v.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:m,children:[v.jsx("span",{children:e}),s?v.jsx(Yo,{size:13}):v.jsx(bo,{size:13})]}):v.jsx("span",{children:e}),r]}),t&&v.jsx("div",{className:"section-actions",children:t})]}),!s&&v.jsx("div",{className:"sidebar-section-body",children:i})]})}function pg({children:e,expanded:t=!1,onClick:n}){return v.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Iu({session:e,selected:t,icon:n,archived:a=!1,hideIcon:r=!1,nested:i=!1,dragging:s,placeholder:l,running:p,goalRuntime:m,subagentRuntime:f,terminalIndicator:S,projectLabel:y,metadataPresentation:k,ariaDescribedBy:R,childSessionCount:A=0,childSessionsExpanded:D=!1,onSelect:z,onToggleChildSessions:N,onTogglePin:x,onToggleSaveForLater:I,onDockRight:P,onArchive:j,onDragStart:T,onDragEnd:F,onDragOver:q,onDrop:$,onRename:V}){const[re,X]=g.useState(!1),we=m?.status==="queued",ye=m?.tone==="active"&&!we,K=(f?.activeCount??0)>0,Ee=A>0&&!!N,xe=r&&!Ee,se=K||ye||!we&&(p??e.status==="active"),ke=K&&f?f.label:ye&&m?Rz(m):"Running",ee=k??(y?"hover-detail":"inline"),pe=ee==="hover-detail",ve=ee==="inline",qe=["sidebar-task-row",ws(e)?"is-draft":"",P?"actions-4":I?"actions-3":"",se?"has-running-dot":"",pe?"has-project-detail":""].filter(Boolean).join(" "),Re=g.useMemo(wz,[]),ie=v.jsxs("div",{className:`sidebar-row-actions${pe?" sidebar-task-inline-actions":""}`,children:[P?v.jsx(fo,{label:"Open in right panel",onClick:P,children:v.jsx(bm,{size:13})}):null,v.jsx(fo,{label:e.pinned?"Unpin chat":"Pin chat",onClick:x,children:e.pinned?v.jsx(Zp,{size:13}):v.jsx(Gp,{size:13})}),I?v.jsx(fo,{label:e.savedForLater?"Return to active":"Save for later",onClick:I,children:e.savedForLater?v.jsx(US,{size:13}):v.jsx(zS,{size:13})}):null,v.jsx(fo,{label:a?"Reopen":"Mark done",onClick:j,children:a?v.jsx(fD,{size:13}):v.jsx(Ho,{size:13})})]}),Ie=v.jsxs(af,{selected:t,dataSessionId:e.id,dragging:s,iconless:xe,nested:i,placeholder:l,className:qe||void 0,ariaExpanded:Ee?D:void 0,ariaDescribedBy:R,onSelect:z,onDragStart:T,onDragEnd:F,onDragOver:q,onDrop:$,onDoubleClick:V?()=>X(!0):void 0,children:[xe?null:Ee?v.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":D?"Hide subagent conversations":"Show subagent conversations","aria-label":`${D?"Hide":"Show"} ${A} subagent ${A===1?"conversation":"conversations"}`,"aria-expanded":D,onClick:Je=>{Je.stopPropagation(),N?.()},children:D?v.jsx(bo,{size:13}):v.jsx(Yo,{size:13})}):n??v.jsx(Pc,{size:15}),v.jsxs("span",{className:`row-label-shell${pe?" has-detail":""}`,children:[v.jsxs("span",{className:"sidebar-session-title-line",children:[v.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:Iz,children:v.jsx(bz,{title:e.title})}),ve?v.jsx(_m,{value:e.updatedAt}):null]}),pe?v.jsxs("span",{className:"sidebar-session-detail-line",children:[v.jsx("span",{className:"sidebar-session-project-label",children:y}),ie,v.jsx(_m,{value:e.updatedAt})]}):null]}),v.jsxs("div",{className:"row-meta",children:[v.jsxs("span",{className:"row-meta-status",children:[S?v.jsx(dx,{indicator:S}):null,se?v.jsx("span",{className:`sidebar-running-dot${K?" subagent":ye?" goal":""}`,style:Re,"aria-label":ke}):null]}),pe?null:ie]})]}),$e=re&&V?v.jsx(hz,{session:e,onSave:Je=>V(e,Je),onClose:()=>X(!1)}):null;return v.jsxs(v.Fragment,{children:[Ie,$e]})}function Cz({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:r,onToggleSaveForLater:i,onDragStart:s,onDragEnd:l,onDragOver:p,onDrop:m}){const f=e.path.split("/").at(-1)??e.path,S=`${e.workspaceName} · ${e.path}`;return v.jsxs(af,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:l,onDragOver:p,onDrop:m,children:[e.available?v.jsx(Wp,{size:15}):v.jsx(TD,{size:15}),v.jsx("span",{className:"row-label-shell",title:S,children:v.jsx("span",{className:"row-label",children:f})}),v.jsx("div",{className:"row-meta",children:v.jsxs("div",{className:"sidebar-row-actions",children:[v.jsx(fo,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:r,children:e.status==="pinned"?v.jsx(Zp,{size:13}):v.jsx(Gp,{size:13})}),v.jsx(fo,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:i,children:e.status==="saved_for_later"?v.jsx(US,{size:13}):v.jsx(zS,{size:13})})]})})]})}function Rz(e){return e.actionLabel}function Az({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:r=!1,disclosure:i=!0,workspaceState:s,cloudLinkTrusted:l=!0,cloudLinkWarning:p=null,placeholder:m,terminalIndicator:f,onSelect:S,onNewChat:y,onMoveToCloud:k,onWorkspaceTargetSelect:R,onTogglePin:A,onRemove:D,onDragStart:z,onDragEnd:N,onDragOver:x,onDrop:I}){const[P,j]=g.useState(!1),T=g.useRef(null),[F,q]=g.useState({}),$=!!k||!!D,V=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,re=g.useCallback(()=>{if(typeof window>"u")return;const ye=T.current?.getBoundingClientRect();if(!ye)return;const K=Math.max(12,window.innerWidth-yz-12),Ee=Math.max(12,window.innerHeight-Sz),xe=Math.max(12,Math.min(ye.right+10,K)),se=Math.max(12,Math.min(ye.top-4,Ee)),ke={"--sidebar-project-locations-left":`${Math.round(xe)}px`,"--sidebar-project-locations-top":`${Math.round(se)}px`};q(ee=>ee["--sidebar-project-locations-left"]===ke["--sidebar-project-locations-left"]&&ee["--sidebar-project-locations-top"]===ke["--sidebar-project-locations-top"]?ee:ke)},[]),X=g.useCallback(()=>{re(),S()},[S,re]);function we(){j(!1)}return v.jsxs("div",{ref:T,className:["sidebar-project-row-shell",P?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:re,onPointerEnter:re,children:[v.jsxs(af,{selected:a,placeholder:m,className:["sidebar-project-row",P?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:i?r:void 0,onSelect:X,onDragStart:z,onDragEnd:N,onDragOver:x,onDrop:I,children:[v.jsx(cx,{kind:e,linkedCloud:V,open:e==="local"&&r,className:"sidebar-row-icon",baseSize:15}),v.jsx("span",{className:"row-label-shell",children:v.jsxs("span",{className:"sidebar-project-title-line",children:[v.jsx("span",{className:"row-label",children:t.name}),v.jsx(_m,{value:t.updatedAt}),i?v.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:r?v.jsx(bo,{size:13}):v.jsx(Yo,{size:13})}):null]})}),v.jsxs("div",{className:"row-meta",children:[v.jsx("span",{className:"row-meta-status",children:f?v.jsx(dx,{indicator:f}):null}),v.jsxs("div",{className:"sidebar-row-actions",children:[v.jsx(fo,{label:n?"Unpin project":"Pin project",onClick:A,children:n?v.jsx(Zp,{size:13}):v.jsx(Gp,{size:13})}),$&&v.jsx(qz,{open:P,onToggleOpen:()=>j(ye=>!ye)}),v.jsx(fo,{label:"New task",onClick:y,children:v.jsx(Yp,{size:13})})]})]})]}),v.jsx(Tz,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:p,onWorkspaceTargetSelect:R,style:F}),P&&v.jsx(Bz,{onClose:we,onMoveToCloud:k?()=>{we(),k()}:void 0,onRemove:()=>{we(),D()}})]})}function _m({value:e}){const t=Pz(e);if(!t||!e)return null;const n=new Date(e);return v.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${_z.format(n)}`,children:t})}function Pz(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=kz.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${xz.format(n)} ${a}`}function dx({indicator:e}){return v.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:v.jsx(VS,{size:13})})}function Tz({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:r,onWorkspaceTargetSelect:i,style:s}){const l=jz(e,t,n,a,r);return v.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[v.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),v.jsx("div",{className:"sidebar-project-location-list",children:l.map(p=>{const m=["sidebar-project-location-row",p.tone??"",p.actionTarget?"clickable":""].filter(Boolean).join(" "),f=v.jsxs(v.Fragment,{children:[v.jsx("span",{className:["sidebar-project-location-icon",p.key].filter(Boolean).join(" "),"aria-hidden":"true",children:p.icon}),v.jsx("span",{className:"sidebar-project-location-copy",children:v.jsx(Ez,{value:p.value})})]});return p.actionTarget?v.jsx("button",{type:"button",className:m,"data-workspace-target":p.actionTarget,disabled:p.disabled||!i,title:p.disabledReason??void 0,onClick:S=>{S.stopPropagation(),!p.disabled&&i?.(p.actionTarget)},children:f},p.key):v.jsx("div",{className:m,children:f},p.key)})})]})}function Ez({value:e}){const t=Mz(e);return v.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),v.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,v.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function Mz(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function jz(e,t,n,a=!0,r=null){return e==="cloud"?Nz(t):Oz(t,n,a,r)}function Oz(e,t,n=!0,a=null){const r=$z(e,t,n),i=Dz(t),s=zz(e,n),l=n===!1&&a;return[{key:"local",value:r,tone:i?"attention":"local",icon:e.source==="git"?v.jsx(qS,{size:13}):v.jsx(HD,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?Uz(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:v.jsx(Ac,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function Nz(e){return[{key:"cloud",value:Hz(e),tone:e.syncedAt?"cloud":"attention",icon:v.jsx(Ac,{size:13}),actionTarget:"cloud"}]}function $z(e,t,n){const a=Lz(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?ix(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function Dz(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function Lz(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function zz(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function Uz(e,t,n){return sx(e,null,t,{cloudLinkTrusted:n})}function Hz(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function qz({open:e,onToggleOpen:t}){return v.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:v.jsx(Kp,{size:13})})}function Bz({onClose:e,onMoveToCloud:t,onRemove:n}){return v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),v.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&v.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[v.jsx(dz,{size:13}),v.jsx("span",{children:"Move to Cloud"})]}),v.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[v.jsx(ui,{size:13}),v.jsx("span",{children:"Remove from Projects"})]})]})]})}function af({children:e,className:t,dataSessionId:n,dragging:a,iconless:r=!1,nested:i=!1,placeholder:s=!1,selected:l,ariaExpanded:p,ariaDescribedBy:m,onSelect:f,onDragStart:S,onDragEnd:y,onDragOver:k,onDrop:R,onDoubleClick:A}){const D=!!S;return v.jsx("div",{className:["sidebar-row",t??"",l?"selected":"",a?"dragging":"",r?"iconless":"",i?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:D,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":p,"aria-describedby":m,onClick:f,onDoubleClick:A,onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),f())},onDragStart:S,onDragEnd:y,onDragEnter:z=>{k&&(z.preventDefault(),z.dataTransfer.dropEffect="move",k(z))},onDragOver:z=>{k&&(z.preventDefault(),z.dataTransfer.dropEffect="move",k(z))},onDrop:z=>{R&&(z.preventDefault(),R(z))},children:e})}function fo({children:e,label:t,onClick:n}){return v.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function Fz({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:r,onTasksetChange:i,onSortChange:s,openMenu:l,setOpenMenu:p,sort:m,selectedTasksetId:f,tasksets:S}){const[y,k]=g.useState(!1),A=S.find(N=>N.id===f)?.name??sg.find(N=>N.value===e)?.label??"Active",D=l==="tasks-filter",z=l==="chats";return v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"section-menu",children:[v.jsx("button",{type:"button",className:`section-icon ${z?"active":""}`,"aria-label":`Sort ${n}`,"aria-haspopup":"menu","aria-expanded":z,onClick:()=>p(N=>N==="chats"?null:"chats"),children:v.jsx(Kp,{size:14})}),z?v.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`Sort ${n}`,children:[n==="tasks"?v.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>r(!t),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?v.jsx(Ho,{size:13}):null}),v.jsx("span",{children:"Group by project"})]}):null,JL.map(N=>v.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":m===N.value,onClick:()=>{s(N.value),p(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:m===N.value?v.jsx(Ho,{size:13}):null}),v.jsx("span",{children:N.label})]},N.value))]}):null]}),v.jsxs("div",{className:"section-menu",children:[v.jsx("button",{type:"button",className:`section-icon ${D||e!=="active"?"active":""}`,"aria-label":`Filter ${n}: ${A}`,"aria-haspopup":"menu","aria-expanded":D,onClick:()=>p(N=>N==="tasks-filter"?null:"tasks-filter"),children:v.jsx(ZD,{size:14})}),D?v.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:sg.map(N=>v.jsxs(g.Fragment,{children:[N.value==="tasksets"?v.jsxs("button",{type:"button",role:"menuitem","aria-expanded":y,onClick:()=>k(x=>!x),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?v.jsx(bo,{size:13}):v.jsx(Yo,{size:13})}),v.jsx("span",{children:N.label})]}):v.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===N.value,onClick:()=>{a(N.value),p(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===N.value?v.jsx(Ho,{size:13}):null}),v.jsx("span",{children:N.label})]}),N.value==="tasksets"&&y?v.jsxs(v.Fragment,{children:[v.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!f,onClick:()=>{i(null),p(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!f?v.jsx(Ho,{size:13}):null}),v.jsx("span",{children:"All Tasksets"})]}),S.map(x=>v.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&f===x.id,onClick:()=>{i(x.id),p(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&f===x.id?v.jsx(Ho,{size:13}):null}),v.jsx("span",{children:x.name}),v.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:x.chatCount})]},x.id))]}):null]},N.value))}):null]})]})}const Vz=288,Wz=112;function Kz(e,t){const n=Math.max(12,t.width-Vz-12),a=Math.max(12,t.height-Wz-12);return{"--sidebar-task-detail-left":`${Math.round(Math.max(12,Math.min(e.right+10,n)))}px`,"--sidebar-task-detail-top":`${Math.round(Math.max(12,Math.min(e.top-4,a)))}px`}}function Gz({detail:e,onClose:t}){if(g.useEffect(()=>{if(!e||typeof window>"u")return;const r=l=>{l.key==="Escape"&&t()};let i=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),i=!0});return window.addEventListener("keydown",r),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",r),i&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"short"}).format(n);return v.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,"aria-label":`${e.title} details`,children:[v.jsx("div",{className:"sidebar-task-detail-title",children:e.title}),v.jsx("div",{className:"sidebar-task-detail-project",children:e.projectLabel}),v.jsx("time",{dateTime:e.updatedAt,children:a})]})}function Zz({children:e,expanded:t,groupKey:n,kind:a,label:r,onToggle:i,onNewTask:s,onOpenProject:l,onRemoveProject:p,project:m}){const f=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,S=a==="draft"?Wp:Pc,[y,k]=g.useState(!1),R=!!(s||l||p);return v.jsxs("section",{className:"sidebar-task-project-group",children:[v.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[v.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":f,"aria-expanded":t,onClick:()=>{k(!1),i()},children:[m?v.jsx(cx,{kind:m.kind,linkedCloud:!!(m.kind==="local"&&m.project.linkedSandboxProject?.projectId),open:m.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):v.jsx(S,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),v.jsx("span",{className:"sidebar-task-project-group-name",children:r}),v.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?v.jsx(bo,{size:13}):v.jsx(Yo,{size:13})})]}),m&&R?v.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||p?v.jsx("button",{type:"button",className:`sidebar-row-action${y?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":y,"aria-haspopup":"menu",onClick:()=>k(A=>!A),children:v.jsx(Kp,{size:13})}):null,s?v.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:v.jsx(Yp,{size:13})}):null]}):null,y?v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>k(!1)}),v.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?v.jsx("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),l()},children:v.jsx("span",{children:"Open project"})}):null,p?v.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),p()},children:[v.jsx(ui,{size:13}),v.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?v.jsx("div",{id:f,className:"sidebar-task-project-group-content",children:e}):null]})}const Jz={},Yz=new Map,Xz=new Map;function Qz(e,t){return Math.min(Math.max(e,jn)+xm,t)}function eU(e,t){const n=Math.max(jn,Math.min(e,t));if(n<=jn)return jn;const a=Math.ceil((n-jn)/xm);return Math.max(jn,jn+(a-1)*xm)}function tU(e,t){const n=new Map;for(const a of e){const r=t(a),i=n.get(r.key);i?i.sessions.push(a):n.set(r.key,{...r,sessions:[a]})}return[...n.values()]}function nU({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:r={},cloudProjectRows:i,beginProjectChat:s,commitTaskDrop:l,commitTaskPreviewDrop:p,dockSessionRight:m,experience:f="work",goalRuntimeBySessionId:S=Yz,localProjectRows:y,openSidebarFile:k,pinnedCollapsed:R,pinnedRows:A,previewTaskDrop:D,previewPinnedDrop:z,projectRows:N,renameSession:x,restoreSession:I,runningSessionIds:P,savedForLaterSessions:j,sectionMenuOpen:T,selectedProjectId:F,selectedSessionId:q,setChatRowsVisibleCount:$,setSectionMenuOpen:V,setSelectedAppId:re,setSelectedProjectId:X,setSelectedSessionId:we,setView:ye,sidebarProjectIdBySessionId:K,startTaskDrag:Ee,startPinnedDrag:xe,subagentRuntimeBySessionId:se=Xz,taskDragSessionId:ke,taskPreviewSessionIds:ee,terminalSummaries:pe=Jz,toggleSessionPinned:ve,toggleSessionSavedForLater:qe,view:Re,clearTaskDrag:ie,removeProject:Ie,toggleProjectPinned:$e,onTogglePinnedCollapsed:Je,setSidebarFileStatus:et,commitPinnedDrop:st,commitPinnedPreviewDrop:Be,clearSidebarDrag:He,dragItem:Ne}){const[E,U]=g.useState("active"),[G,me]=g.useState("recent"),[W,de]=g.useState(f!=="chat"),[he,We]=g.useState(null),[Ze,tt]=g.useState(()=>new Set),[at,Te]=g.useState(()=>new Map),[De,u]=g.useState(null),M=f==="chat"?"chats":"tasks",H=f==="chat"?"Chats":"Tasks",ae=g.useMemo(()=>e.filter(te=>mo(te)===null),[e]),O=g.useMemo(()=>j.filter(te=>mo(te)===null),[j]),Z=Math.max(0,ae.length-O.length),_=YL({activeCount:Z,filter:E,savedForLaterCount:O.length}),L=N??[...y,...i],oe=g.useMemo(()=>new Map(L.map(te=>[te.id,te.project.name])),[L]),Q=g.useMemo(()=>new Map(L.map(te=>[te.id,te])),[L]),Y=g.useMemo(()=>{const te=new Set(P);for(const Ke of e){const Ge=S.get(Ke.id),yt=se.get(Ke.id);(Ge?.tone==="active"&&Ge.status!=="queued"||(yt?.activeCount??0)>0||sn(Ke.id)?.status==="running")&&te.add(Ke.id)}return te},[e,S,P,se,pe]),ue=g.useMemo(()=>lg({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:Y,sort:"manual"}),[e,n,Y]),le=g.useMemo(()=>lg({activeSessions:e,doneSessions:n,filter:E,inProgressSessionIds:Y,selectedTasksetId:he,previewSessionIds:ee,sort:G}),[e,n,Y,he,E,ee,G]),ze=g.useMemo(()=>{const te=new Map;for(const Ke of[...e,...n]){const Ge=mo(Ke);if(!Ge)continue;const yt=te.get(Ge.id);yt?yt.chatCount+=1:te.set(Ge.id,{...Ge,chatCount:1})}return[...te.values()].sort((Ke,Ge)=>Ke.name.localeCompare(Ge.name))},[e,n]),Pe=g.useMemo(()=>le.filter(te=>!Yl(te)).slice(0,Math.max(jn,a)),[a,le]),Oe=g.useMemo(()=>tU(Pe,te=>{if(ws(te))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const Ke=K[te.id],Ge=Pt(te)??"No project";return{key:Ke?`project:${Ke}`:`projectless:${Ge}`,label:Ge,projectId:Ke??null,project:Ke?Q.get(Ke)??null:null,kind:Ke?"project":"projectless"}}),[oe,Q,K,Pe]),Ye=Pe.length<le.length,Le=Pe.length>jn,ut=g.useMemo(()=>new Set(Oe.filter(te=>te.sessions.some(Ke=>Ke.id===q||Y.has(Ke.id))).map(te=>te.key)),[Oe,Y,q]),Gt=ue.filter(te=>!Yl(te)).map(te=>te.id),gn=Pe.map(te=>te.id),bn=JSON.stringify(Object.entries(r).filter(([te,Ke])=>Ke.length>0&&(se.get(te)?.activeCount??0)>0).flatMap(([te,Ke])=>Ke.map(Ge=>[te,Ge.id])).sort(([te,Ke],[Ge,yt])=>te.localeCompare(Ge)||Ke.localeCompare(yt)));g.useEffect(()=>{const te=JSON.parse(bn);if(te.length===0)return;const Ke=new Set(te.map(([Ge])=>Ge));tt(Ge=>[...Ke].every(yt=>Ge.has(yt))?Ge:new Set([...Ge,...Ke]))},[bn]);function sn(te){return rz(pe[rx({kind:"session",id:te})])}function Pt(te){if(ws(te))return"Draft";const Ke=K[te.id];return Ke?oe.get(Ke)??te.workspaceName??"Project":WL(te)}function It(te){Qt({kind:"chat",sessionId:te.id}),we(te.id);const Ke=K[te.id]??null;re(Ke?null:te.appId),X(Ke),ye("chat")}function vn(te){return r[te.id]??[]}function Ct(te,Ke){return Ze.has(te.id)||Ke.some(Ge=>Ge.id===q)}function $t(te){tt(Ke=>{const Ge=new Set(Ke);return Ge.has(te)?Ge.delete(te):Ge.add(te),Ge})}function Bt(te){const Ke=vn(te);return Ke.length===0||!Ct(te,Ke)?null:v.jsx("div",{className:"sidebar-child-session-group",children:Ke.map(Ge=>v.jsx(Iu,{session:Ge,selected:Re==="chat"&&q===Ge.id,hideIcon:!0,nested:!0,running:Y.has(Ge.id),goalRuntime:S.get(Ge.id)??null,subagentRuntime:se.get(Ge.id)??null,terminalIndicator:sn(Ge.id),projectLabel:Pt(te),onSelect:()=>It(Ge),onTogglePin:()=>ve(Ge),onToggleSaveForLater:()=>qe(Ge),onDockRight:()=>m(Ge),onArchive:()=>Ge.archived?I(Ge):t(Ge),onRename:x},Ge.id))})}function Yt(te,Ke,Ge){typeof window>"u"||u({descriptionId:`sidebar-task-detail-${te.id}`,projectLabel:Ke,sessionId:te.id,title:te.title,updatedAt:te.updatedAt,style:Kz(Ge.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight})})}function en(te,Ke={}){const Ge=te.archived,yt=ke===te.id,mn=vn(te),ka="sidebar-session-group",Pn=G==="manual"?{onDragStart:Zt=>Ee(Zt,{allSessionIds:Gt,visibleSessionIds:gn,sessionId:te.id}),onDragEnd:ie,onDragOver:Zt=>{yt||D(Zt,te.id)},onDrop:Zt=>{yt?p():l(Zt,te.id)}}:{};return v.jsxs("div",{className:ka,onPointerEnter:Ke.metadataPresentation==="flyout"&&Ke.projectLabel?Zt=>Yt(te,Ke.projectLabel,Zt.currentTarget):void 0,onPointerLeave:Ke.metadataPresentation==="flyout"?()=>u(null):void 0,onFocusCapture:Ke.metadataPresentation==="flyout"&&Ke.projectLabel?Zt=>Yt(te,Ke.projectLabel,Zt.currentTarget):void 0,onBlurCapture:Ke.metadataPresentation==="flyout"?Zt=>{Zt.currentTarget.contains(Zt.relatedTarget)||u(null)}:void 0,children:[v.jsx(Iu,{session:te,selected:!Ge&&Re==="chat"&&q===te.id,archived:Ge,hideIcon:!0,placeholder:yt,running:Y.has(te.id),goalRuntime:S.get(te.id)??null,subagentRuntime:se.get(te.id)??null,terminalIndicator:sn(te.id),projectLabel:Ke.projectLabel===void 0?Pt(te):Ke.projectLabel,metadataPresentation:Ke.metadataPresentation,ariaDescribedBy:Ke.metadataPresentation==="flyout"&&De?.sessionId===te.id?De.descriptionId:void 0,childSessionCount:mn.length,childSessionsExpanded:Ct(te,mn),onToggleChildSessions:()=>$t(te.id),onSelect:()=>{u(null),Ge&&I(te),It(te)},onTogglePin:()=>ve(te),onToggleSaveForLater:()=>qe(te),onDockRight:()=>m(te),onArchive:()=>Ge?I(te):t(te),onRename:x,...Pn}),yt?null:Bt(te)]},te.id)}function un(te){te!=="tasksets"&&We(null),U(te),$(jn)}function An(te){We(te),U("tasksets"),$(jn)}function La(te){me(te),$(jn)}function Ft(){$(te=>Qz(te,le.length))}function Ln(){$(te=>eU(te,le.length))}function lt(te){const Ke={id:te.id,type:te.type};return{onDragStart:Ge=>xe(Ge,Ke),onDragEnd:He,onDragOver:Ge=>z(Ge,Ke),onDrop:Ge=>{Ne?.id===te.id&&Ne.type===te.type?Be():st(Ge,Ke)}}}function Dt(te){const Ke=lt(te),Ge=Ne?.id===te.id&&Ne.type===te.type;if(te.type==="project"){const mn=te.item;return v.jsx(Az,{kind:mn.kind,project:mn.project,pinned:!0,selected:Re==="chat"&&F===mn.id,expanded:!1,disclosure:!1,placeholder:Ge,onSelect:()=>{re(null),X(mn.id),we(null),ye("chat")},onNewChat:()=>s(mn.id),onTogglePin:()=>$e(mn),onRemove:()=>Ie(mn),...Ke},te.key)}if(te.type==="file")return v.jsx(Cz,{file:te.file,placeholder:Ge,onSelect:()=>k(te.file),onTogglePin:()=>et(te.file,"none"),onToggleSaveForLater:()=>et(te.file,"saved_for_later"),...Ke},te.key);const yt=te.session;return v.jsx(Iu,{session:yt,selected:Re==="chat"&&q===yt.id,hideIcon:!0,placeholder:Ge,running:Y.has(yt.id),goalRuntime:S.get(yt.id)??null,subagentRuntime:se.get(yt.id)??null,terminalIndicator:sn(yt.id),projectLabel:Pt(yt),metadataPresentation:"flyout",onSelect:()=>It(yt),onTogglePin:()=>ve(yt),onToggleSaveForLater:()=>qe(yt),onDockRight:()=>m(yt),onArchive:()=>t(yt),onRename:x,...Ke},te.key)}return v.jsxs("div",{className:"sidebar-scroll",children:[v.jsxs(mg,{label:H,className:`sidebar-task-section${f!=="chat"?" development":""}`,titleAccessory:f!=="chat"?v.jsx("div",{className:"sidebar-task-mode-buttons",children:v.jsxs("button",{type:"button",className:`section-icon sidebar-task-count-bubble${E==="saved_for_later"?" active":""}`,"aria-label":`Show ${_.count} ${_.targetLabel} ${_.count===1?"task":"tasks"}`,onClick:()=>un(_.targetFilter),children:[v.jsx("span",{children:_.label}),v.jsx("span",{className:"sidebar-task-count-badge","aria-hidden":"true",children:_.count>99?"99+":_.count})]})}):null,actionsVisible:T==="chats"||T==="tasks-filter",actions:v.jsx(Fz,{filter:E,groupByProject:W,noun:M,onFilterChange:un,onGroupByProjectChange:de,onTasksetChange:An,onSortChange:La,openMenu:T,setOpenMenu:V,sort:G,selectedTasksetId:he,tasksets:ze}),children:[A.length>0?v.jsx(mg,{label:"Pinned",className:"sidebar-pinned-section",collapsed:R,onToggleCollapsed:Je,children:A.map(Dt)}):null,W&&f!=="chat"?Oe.map(te=>{const Ke=ut.has(te.key)||at.get(te.key)!==!1;return v.jsx(Zz,{expanded:Ke,groupKey:te.key,kind:te.kind,label:te.label,onToggle:()=>{Te(Ge=>{const yt=new Map(Ge);return yt.set(te.key,!Ke),yt})},onNewTask:te.project?()=>s(te.project.id):void 0,onOpenProject:te.project?()=>{re(null),X(te.project.id),we(null),ye("chat")}:void 0,onRemoveProject:te.project?()=>Ie(te.project):void 0,project:te.project,children:te.sessions.map(Ge=>en(Ge,{metadataPresentation:"flyout",projectLabel:te.label}))},te.key)}):Pe.map(te=>en(te)),le.length===0?v.jsx("div",{className:"empty-row",children:XL(E,M)}):null,le.length>jn&&(Ye||Le)?v.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${Pe.length} of ${le.length} ${M}`,children:[Ye?v.jsx(pg,{onClick:Ft,children:"Show more"}):null,Le?v.jsx(pg,{onClick:Ln,children:"Show less"}):null]}):null]}),v.jsx(Gz,{detail:De,onClose:()=>u(null)})]})}const aU="./";function Vn(e){return`${aU}${e.replace(/^\.?\//,"")}`}const oU=Vn("openpond-icon.png"),rU=Vn("openpond-wordlogo-white.png"),VV=Vn("tutorials/what-is-an-openpond-agent-poster.png"),WV=Vn("tutorials/what-is-an-openpond-agent.vtt"),KV=Vn("tutorials/how-to-make-an-agent-poster.png"),GV=Vn("tutorials/how-to-make-an-agent.vtt");function ZV(e){return Vn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function JV(e){return Vn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const fg={github:Vn("connected-apps/github.svg"),google:Vn("connected-apps/google.svg"),microsoft_teams:Vn("connected-apps/microsoft.svg"),mcp:Vn("connected-apps/openpond-mcp.svg"),slack:Vn("connected-apps/slack.svg"),x:Vn("connected-apps/x.svg")};function YV(e){return fg[e]??fg.mcp}function iU({value:e,onChange:t}){const[n,a]=g.useState(!1),r=g.useRef(null),i=g.useRef(null),s=g.useRef(null),l=ku.find(y=>y.value===e)??ku[0];g.useEffect(()=>{if(!n)return;const y=R=>{R.target instanceof Node&&!r.current?.contains(R.target)&&a(!1)},k=()=>a(!1);return window.addEventListener("pointerdown",y),window.addEventListener("blur",k),()=>{window.removeEventListener("pointerdown",y),window.removeEventListener("blur",k)}},[n]);const p=y=>{window.requestAnimationFrame(()=>{const k=hg(s.current);if(!k.length)return;(y==="first"?k[0]:y==="last"?k.at(-1):k.find(A=>A.dataset.productArea===e))?.focus()})},m=y=>{a(!0),p(y)},f=y=>{y.key==="ArrowDown"?(y.preventDefault(),m("first")):y.key==="ArrowUp"&&(y.preventDefault(),m("last"))},S=y=>{const k=hg(s.current),R=k.findIndex(z=>z===document.activeElement);if(y.key==="Escape"){y.preventDefault(),a(!1),i.current?.focus();return}if(y.key==="Home"||y.key==="End"){y.preventDefault(),k[y.key==="Home"?0:k.length-1]?.focus();return}if(y.key!=="ArrowDown"&&y.key!=="ArrowUp")return;y.preventDefault();const A=y.key==="ArrowDown"?1:-1,D=R<0?0:(R+A+k.length)%k.length;k[D]?.focus()};return v.jsxs("div",{className:"sidebar-experience-menu",ref:r,children:[v.jsxs("button",{ref:i,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${l.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{a(y=>!y)},onKeyDown:f,children:[v.jsx("img",{className:"sidebar-wordmark",src:rU,alt:""}),v.jsx("span",{className:"sidebar-experience-label",children:l.label}),v.jsx(bo,{size:13,"aria-hidden":"true"})]}),n?v.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:S,children:ku.map(y=>{const k=y.value===e;return v.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":k,className:k?"active":"","data-product-area":y.value,onClick:()=>{a(!1),k||t(y.value)},children:[v.jsxs("span",{children:[v.jsx("strong",{children:y.label}),v.jsx("small",{children:y.description})]}),k?v.jsx(Ho,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function hg(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function sU(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function lU(e){const t=e?.accounts.find(s=>s.isActive)??null,n=e?.profile??null,a=e?.activeProfile?.handle??null;return{label:(e?.state==="signed_in"?sU(e?.label,n?.handle,n?.name,n?.email,t?.displayLabel,t?.handle,a,e?.email,"Signed in"):e?.state==="loading"||e?.state==="switching"?"Loading account":"Sign in")??"Account",image:e?.avatarUrl??n?.image??t?.avatarUrl??null}}function cU({account:e,onOpenActivity:t,onOpenSettings:n}){const[a,r]=g.useState(!1),i=g.useRef(null),s=g.useMemo(()=>lU(e),[e]),l=s.label.trim().slice(0,1).toUpperCase();return g.useEffect(()=>{if(!a)return;function p(f){i.current?.contains(f.target)||r(!1)}function m(f){f.key==="Escape"&&r(!1)}return document.addEventListener("pointerdown",p),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",p),document.removeEventListener("keydown",m)}},[a]),v.jsxs("div",{className:"user-auth-footer",ref:i,children:[v.jsxs("button",{type:"button",className:`user-auth-trigger ${a?"active":""}`,"aria-haspopup":"menu","aria-expanded":a,"aria-label":`${s.label} account menu`,onClick:()=>r(p=>!p),children:[v.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:s.image?v.jsx("img",{src:s.image,alt:""}):l?v.jsx("span",{children:l}):v.jsx(fL,{size:16})}),v.jsx("span",{className:"user-auth-name",children:s.label})]}),a?v.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[t?v.jsxs("a",{href:"/settings/usage",className:"user-auth-menu-link",role:"menuitem",onClick:p=>{p.preventDefault(),r(!1),t()},children:[v.jsx(gm,{size:15}),v.jsx("span",{children:"Activity"})]}):null,v.jsxs("a",{href:"/settings",className:"user-auth-menu-link",role:"menuitem",onClick:p=>{p.preventDefault(),r(!1),n()},children:[v.jsx(Jp,{size:15}),v.jsx("span",{children:"Settings"})]})]}):null]})}function gg(e){const t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e?.trim()??"");return t?[Number.parseInt(t[1],10),Number.parseInt(t[2],10),Number.parseInt(t[3],10)]:null}function dU(e,t){const n=gg(e),a=gg(t);if(!n||!a)return!1;for(let r=0;r<a.length;r+=1){if(a[r]>n[r])return!0;if(a[r]<n[r])return!1}return!1}function ux(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function uU(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function mU(e,t,n){const a=ux(t),r=uU(n);if(a==="mac"){const i=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return r==="arm64"?i.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:r==="x64"?i.find(s=>/-mac-x64\.zip$/i.test(s.name))??i.find(s=>/-mac-universal\.zip$/i.test(s.name))??null:i.find(s=>/-mac-universal\.zip$/i.test(s.name))??i.find(s=>/-mac-arm64\.zip$/i.test(s.name))??i[0]??null}if(a==="linux"){const i=e.filter(s=>/\.AppImage$/i.test(s.name));return r==="arm64"?i.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:r==="x64"?i.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??i[0]??null:i[0]??null}return null}function pU(e){if(!e.payload||typeof e.payload!="object")return null;const t=e.payload,a=(typeof t.tag_name=="string"?t.tag_name.trim():"").replace(/^v/,"");if(!dU(e.currentVersion,a))return null;const r=typeof t.html_url=="string"?t.html_url:"",s=(Array.isArray(t.assets)?t.assets:[]).flatMap(p=>{if(!p||typeof p!="object")return[];const m=p;return typeof m.name!="string"||typeof m.browser_download_url!="string"?[]:[{name:m.name,downloadUrl:m.browser_download_url}]}),l=mU(s,e.platform,e.arch);return!l||!r?null:{version:a,releaseUrl:r,assetName:l.name,downloadUrl:l.downloadUrl}}const fU=3600*1e3,hU="https://api.github.com/repos/openpond/openpond/releases/latest";function gU(e){const[t,n]=g.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",r=e.platform??"",i=e.arch??"",s=e.enabled&&!!a&&!!ux(r);return g.useEffect(()=>{if(!s){n({status:"idle",update:null,lastCheckedAt:null});return}let l=!1;async function p(){n(f=>({...f,status:f.update?"available":"checking"}));try{const f=await fetch(hU,{headers:{Accept:"application/vnd.github+json"}});if(!f.ok)throw new Error(`GitHub release check failed: ${f.status}`);const S=await f.json(),y=pU({payload:S,currentVersion:a,platform:r,arch:i});if(l)return;n({status:y?"available":"current",update:y,lastCheckedAt:Date.now()})}catch{if(l)return;n(f=>({status:f.update?"available":"error",update:f.update,lastCheckedAt:Date.now()}))}}p();const m=window.setInterval(()=>{p()},fU);return()=>{l=!0,window.clearInterval(m)}},[i,a,s,r]),t}const mx="openpond.sidebar.continuous-learning.dismissed.v1";function bU(e=px()){if(!e)return!1;try{return e.getItem(mx)==="true"}catch{return!1}}function vU(e=px()){if(e)try{e.setItem(mx,"true")}catch{}}function px(){return typeof window>"u"?null:window.localStorage}function yU({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[r,i]=g.useState(bU),s=g.useCallback(async()=>{if(!e){a(null);return}try{a(await J.harnessHistory(e))}catch{a(null)}},[e]);if(g.useEffect(()=>{s()},[s]),r||!e||!n?.workspace)return null;const l=n.evaluationReviewSchedule,p=l.activityEnabled?`${l.activityBatchSize} outcomes${l.enabled?` + ${l.cadence}`:""}`:l.enabled?l.cadence:"Manual";return v.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[v.jsxs("header",{children:[v.jsx("strong",{children:"Continuous learning"}),v.jsxs("div",{className:"sidebar-learning-notice-actions",children:[v.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:v.jsx(Jp,{size:14})}),v.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{i(!0),vU()},type:"button",children:v.jsx(ui,{size:14})})]})]}),v.jsxs("div",{className:"sidebar-learning-status",children:[v.jsx("strong",{children:"Refiner"}),v.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),v.jsxs("div",{className:"sidebar-learning-status",children:[v.jsx("strong",{children:"Continuous Review"}),v.jsx("span",{children:p})]})]})}function SU(e){const{beginNewChat:t,arch:n,currentVersion:a,experience:r,productArea:i,onProductAreaChange:s,onSidebarResizeStart:l,platform:p,setSectionMenuOpen:m,setSelectedAppId:f,setSelectedProjectId:S,setSelectedSessionId:y,setSidebarOpen:k,setSettingsSection:R,setView:A,view:D,modelProjects:z,modelTrainingActivityByProjectId:N}=e,x=gU({currentVersion:a,platform:p,arch:n,enabled:Tc()}),I=x.status==="available"?x.update:null;return v.jsxs("aside",{className:"sidebar",children:[v.jsxs("div",{className:"sidebar-toolbar",children:[v.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>k(!1),children:v.jsx(FS,{size:16})}),v.jsx(iU,{value:i,onChange:s}),I&&v.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${I.version}: ${I.assetName}`,"aria-label":`Download OpenPond ${I.version}`,onClick:()=>{xU(I.downloadUrl)},children:[v.jsx(ND,{size:14}),v.jsx("span",{children:"Update"})]})]}),v.jsx(NL,{productArea:i,experience:r,beginNewChat:t,setSectionMenuOpen:m,setSelectedAppId:f,setSelectedProjectId:S,setSelectedSessionId:y,setView:A,view:D,modelProjects:z,modelTrainingActivityByProjectId:N}),i==="models"?null:v.jsx(nU,{...e}),v.jsxs("div",{className:"sidebar-bottom-stack",children:[i==="models"?null:v.jsx(yU,{connection:e.connection,onOpenSettings:()=>{m(null),R("harness"),A("settings"),Qt({kind:"settings",section:"harness"})}}),v.jsxs("div",{className:"sidebar-footer-row",children:[v.jsx(cU,{account:e.account,onOpenActivity:()=>{m(null),R("usage"),A("settings"),Qt({kind:"settings",section:"usage"})},onOpenSettings:()=>{m(null),R("account"),A("settings"),Qt({kind:"settings",section:"account"})}}),v.jsx($L,{setSectionMenuOpen:m,setSelectedAppId:f,setSelectedProjectId:S,setSelectedSessionId:y,setView:A,view:D})]})]}),v.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:l})]})}async function xU(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const kU=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function fx(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?hx(a)?"Couldn’t connect to OpenPond.":a:t}function hx(e){const t=e.trim();return kU.some(n=>n.test(t))}const gx=g.createContext(null);function bg({children:e,showToast:t}){return v.jsx(gx.Provider,{value:t,children:e})}function _U(){return g.useContext(gx)}function vg(e,t={}){const n=_U(),a=g.useRef(null),r=t.enabled??!0,i=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${fx(e,i)}`;g.useEffect(()=>{if(!r||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error",{dismissible:!0}))},[r,l,n])}function wU({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(vg(e?.previewError,{prefix:"Upload preview"}),vg(e?.error,{prefix:"Cloud setup"}),!e)return null;const r=e.status==="uploading",i=e.status==="ready",s=e.status==="error",l=e.projectKind==="cloud",p=e.preview??null;return v.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:v.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[v.jsx("button",{className:"git-dialog-close",disabled:r,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:v.jsx(ui,{size:14})}),v.jsx("div",{className:"git-dialog-icon",children:i?v.jsx(HS,{size:18}):v.jsx(Ac,{size:18})}),v.jsx("h2",{children:i?"Cloud repo ready":"Set up Cloud coding"}),v.jsx("p",{children:i?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":l?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),v.jsxs("div",{className:"cloud-setup-summary",children:[v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Project"}),v.jsx("strong",{children:e.projectName})]}),v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Source"}),v.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Branch"}),v.jsx("strong",{children:p?.branch??e.branch??"main"})]}),!l&&v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Cloud project"}),v.jsx("strong",{children:p?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!i&&!l&&v.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:"Calculating upload preview"}),v.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:"Preview unavailable"}),v.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):p?v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:p.initializedEmptyProject?"Will initialize an empty project":`Will upload ${p.fileCount} files`}),v.jsx("span",{children:yg({byteCount:p.byteCount,skippedCount:p.skippedCount,headCommit:p.headCommit,targetProjectName:p.targetProjectName})})]}):v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:"Upload preview pending"}),v.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),r&&v.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[v.jsx(YD,{className:"cloud-setup-spinner",size:16}),v.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),i&&e.upload&&v.jsxs("div",{className:"cloud-setup-upload-result",children:[v.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),v.jsx("span",{children:yg({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),i&&e.setupUrl&&v.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?v.jsxs("span",{children:["Your repo is ready here:"," ",v.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:m=>Cu(m,e.projectUrl,n,{newTab:!0}),children:["Project page",v.jsx(Su,{size:13})]})]}):v.jsx("span",{children:"Your repo is ready. Next step:"}),v.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:m=>Cu(m,e.setupUrl,n),children:["Setup the Cloud sandbox",v.jsx(Su,{size:13})]})]}),v.jsxs("div",{className:"git-dialog-footer",children:[v.jsx("button",{className:"git-dialog-secondary",disabled:r,type:"button",onClick:t,children:i?"Done":"Cancel"}),i?e.setupUrl?v.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:m=>Cu(m,e.setupUrl,n),children:["Open setup",v.jsx(Su,{size:13})]}):null:v.jsx("button",{className:"git-dialog-primary",disabled:r,type:"button",onClick:a,children:r?"Uploading":s?"Try again":l?"Show setup link":"Upload source"})]})]})})}function Cu(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function IU(e){return!Number.isFinite(e)||e<=0?"0 B":e<1024?`${Math.round(e)} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function yg({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const r=[IU(e),`${t} skipped`],i=CU(n);return i&&r.push(`local ${i}`),r.push(a),r.join(" · ")}function CU(e){const t=e?.trim();return t?t.slice(0,7):null}const RU=g.lazy(()=>Xo(()=>import("./CommandMenu-Ct0Sx7yP.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),AU=g.lazy(()=>Xo(()=>import("./SettingsView-DB_zPHYY.js"),__vite__mapDeps([4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]),import.meta.url).then(e=>({default:e.SettingsView}))),PU=g.lazy(()=>Xo(()=>import("./NewProjectDialog-Cx8QcZm7.js"),__vite__mapDeps([27,1,2,8,16]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),TU=g.lazy(()=>Xo(()=>import("./WorkspaceGitDialogs-BnBRUYpS.js"),__vite__mapDeps([28,1,2,13,29,14,30,26]),import.meta.url).then(e=>({default:e.CommitDialog}))),EU=g.lazy(()=>Xo(()=>import("./WorkspaceGitDialogs-BnBRUYpS.js"),__vite__mapDeps([28,1,2,13,29,14,30,26]),import.meta.url).then(e=>({default:e.BranchDialog})));function MU({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:r,onError:i,onToast:s,onBack:l,onOpenSourceSession:p,onStartRefinerAuthoring:m,onAcceptEvaluationReview:f,onOpenSkill:S,onOpenExtension:y,teamChatCurrentUserId:k,teamChatEnabled:R,teamChatNotificationMode:A,teamChatThreads:D,onTeamChatNotificationModeChange:z,onTeamChatThreadMuteChange:N,diffPanelWidth:x,diffPanelResizing:I,diffPanelExpanded:P,onDiffPanelResizeStart:j,onDiffPanelExpandedChange:T}){return v.jsx(g.Suspense,{fallback:null,children:v.jsx(AU,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:r,onError:i,onToast:s,onBack:l,onOpenSourceSession:p,onStartRefinerAuthoring:m,onAcceptEvaluationReview:f,onOpenSkill:S,onOpenExtension:y,teamChatCurrentUserId:k,teamChatEnabled:R,teamChatNotificationMode:A,teamChatThreads:D,onTeamChatNotificationModeChange:z,onTeamChatThreadMuteChange:N,diffPanelWidth:x,diffPanelResizing:I,diffPanelExpanded:P,onDiffPanelResizeStart:j,onDiffPanelExpandedChange:T})})}function jU({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:r,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:p,expandProject:m,newProjectBusy:f,newProjectDialogOpen:S,newProjectDirectory:y,newProjectMode:k,newProjectName:R,newProjectPath:A,projectRows:D,query:z,searchOpen:N,visibleWorkspaceDiff:x,visibleWorkspaceState:I,workspaceBusy:P,appDispatch:j,beginNewChat:T,openDefaultsSettingsFromBranchDialog:F,setBranchDialogName:q,setBranchDialogOpen:$,setCommitDialogOpen:V,setCommitDraft:re,setCommitIncludeUnstaged:X,setCommitMessage:we,setCommitNextStep:ye,setNewProjectDialogOpen:K,setNewProjectName:Ee,setNewProjectPath:xe,setQuery:se,setSearchOpen:ke,submitCommitDialog:ee,submitCreateWorkspaceBranch:pe,submitNewProjectDialog:ve}){return v.jsxs(v.Fragment,{children:[N&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(RU,{open:N,query:z,projects:D,sessions:e,onQueryChange:se,onClose:()=>{ke(!1),se("")},onNewChat:()=>{ke(!1),se(""),T()},onOpenProject:qe=>{j({type:"selectProject",projectId:qe.id}),j({type:"patch",patch:{searchOpen:!1,query:""}}),m(qe.id)},onOpenSession:qe=>{j({type:"selectSession",sessionId:qe.id,appId:qe.appId,projectId:qe.workspaceKind==="local_project"&&qe.workspaceId?ht("local",qe.workspaceId):null}),j({type:"patch",patch:{searchOpen:!1,query:""}})}})}),S&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(PU,{open:S,mode:k,name:R,path:A,directory:y,busy:f,onNameChange:Ee,onPathChange:xe,onClose:()=>{f||K(!1)},onSubmit:ve})}),a&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(TU,{open:a,branch:I?.currentBranch??null,filesChanged:x?.filesChanged??I?.changedFilesCount??0,additions:x?.additions??0,deletions:x?.deletions??0,message:s,includeUnstaged:i,nextStep:l,draft:r,busy:P,canPush:!!I?.remoteUrl,canPublish:p,onMessageChange:we,onIncludeUnstagedChange:X,onNextStepChange:ye,onDraftChange:re,onClose:()=>{P||V(!1)},onSubmit:ee})}),n&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(EU,{open:n,branchName:t,busy:P,onBranchNameChange:q,onSetPrefix:F,onClose:()=>{P||$(!1)},onSubmit:pe})})]})}function bx({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction),a=!!(e.persistent||e.dismissible);return v.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[v.jsx("span",{className:"app-toast-message",children:e.message}),(n||a)&&v.jsxs("div",{className:"app-toast-actions",children:[n&&v.jsx("button",{type:"button",className:e.actionIcon?"app-toast-icon-action":void 0,"aria-label":e.actionLabel,title:e.actionIcon?e.actionLabel:void 0,onClick:()=>{t(),e.onAction?.()},children:e.actionIcon==="settings"?v.jsx(Jp,{size:15}):e.actionLabel}),a&&v.jsx("button",{type:"button",className:"app-toast-close","aria-label":"Dismiss notification",onClick:t,children:v.jsx(ui,{size:14})})]})]})}async function OU(e){if(!e)return!1;try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch(t){console.warn("Clipboard write failed",t)}try{const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.left="-1000px",t.style.top="-1000px",document.body.appendChild(t),t.select();const n=document.execCommand("copy");return t.remove(),n}catch(t){return console.warn("Clipboard fallback failed",t),!1}}function NU({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return v.jsxs("div",{className:"titlebar-collaboration-actions",children:[v.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:v.jsx(Pc,{size:16})}),v.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:v.jsx(BS,{size:16})})]})}const $U=g.lazy(()=>Xo(()=>import("./WorkspaceEnvironmentMenu-BTz9FISP.js"),__vite__mapDeps([31,1,2,29,22,32,10,33,14,6,30,34]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function DU({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:r,workspaceName:i,workspaceId:s,busy:l,workspaceState:p,workspaceKind:m,selectedApp:f,selectedProject:S,workspaceDiff:y,managedWorkspace:k,workspaceBusy:R,defaultTeamId:A,showDiffControls:D,diffPanelOpen:z,terminalOpen:N,rightSidebarAvailable:x=!1,rightSidebarOpen:I=!1,onToggleDiffPanel:P,onToggleRightSidebar:j,onOpenSearch:T,onToggleTerminal:F,onRunTerminalCommand:q,onWorkspaceToolAction:$,onOpenCommitDialog:V,onWorkspaceBranchChange:re,onWorkspaceBranchCreate:X,connection:we,onBootstrap:ye,onOpenSandboxWorkspace:K,onShowSidebar:Ee,onOpenTeamChat:xe,onDiscoverCommunities:se,collaborationView:ke=null,platform:ee,showWorkspaceControls:pe=!0}){const ve=y?.filesChanged??0,qe=Tc()&&!Xp(ee),Re=!!(xe||se)||pe||x||qe,[ie,Ie]=g.useState(null);g.useEffect(()=>{if(!ie)return;const et=()=>Ie(null);return window.addEventListener("pointerdown",et),window.addEventListener("blur",et),window.addEventListener("resize",et),()=>{window.removeEventListener("pointerdown",et),window.removeEventListener("blur",et),window.removeEventListener("resize",et)}},[ie]);const $e=et=>{et.preventDefault(),et.stopPropagation();const st=190,Be=n?76:42;Ie({x:Math.min(et.clientX,window.innerWidth-st-8),y:Math.min(et.clientY,window.innerHeight-Be-8)})},Je=et=>{OU(et),Ie(null)};return v.jsxs("header",{className:"app-titlebar",children:[v.jsxs("div",{className:"titlebar-left",children:[!e&&v.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Ee,children:v.jsx(FS,{size:16})}),r?v.jsx("button",{className:"titlebar-icon",type:"button","aria-label":r.label,title:r.label,onClick:r.onSelect,children:v.jsx(gD,{size:16})}):null,a?.length?v.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((et,st)=>{const Be=st===a.length-1;return v.jsxs("div",{className:"titlebar-breadcrumb-item",children:[et.onSelect&&!Be?v.jsx("button",{type:"button",onClick:et.onSelect,children:et.label}):v.jsx("strong",{children:et.label}),!Be&&v.jsx(Yo,{size:14})]},`${et.label}-${st}`)})}):v.jsxs("div",{className:"titlebar-title",children:[v.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:$e,children:t}),i&&v.jsx("span",{children:i})]})]}),Re&&v.jsxs("div",{className:"titlebar-right",children:[v.jsx(NU,{activeView:ke,onDiscoverCommunities:se,onOpenTeamChat:xe}),pe&&v.jsxs("div",{className:"titlebar-actions",children:[v.jsx(g.Suspense,{fallback:null,children:v.jsx($U,{mode:"topbar",busy:l,workspaceState:p,workspaceId:s,workspaceKind:m,selectedApp:f,selectedProject:S,workspaceBusy:R,defaultTeamId:A,workspaceDiff:y,managedWorkspace:k,showDiffControls:D,diffPanelOpen:z,onToggleDiffPanel:P,onRunTerminalCommand:q,onWorkspaceToolAction:$,onOpenCommitDialog:V,onWorkspaceBranchChange:re,onWorkspaceBranchCreate:X,connection:we,onBootstrap:ye,onOpenSandboxWorkspace:K})}),v.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:T,children:v.jsx(sL,{size:16})}),v.jsx("button",{type:"button",className:`titlebar-icon ${N?"active":""}`,title:`${N?"Hide":"Show"} terminal`,"aria-label":`${N?"Hide":"Show"} terminal`,"aria-pressed":N,onClick:F,children:v.jsx(VS,{size:16})}),D&&v.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar${ve?`, ${ve} changed files`:""}`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:P,children:v.jsx(bm,{size:16})})]}),x&&j&&!D?v.jsx("div",{className:"titlebar-actions",children:v.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:j,children:v.jsx(bm,{size:16})})}):null,v.jsx(gL,{platform:ee})]}),ie&&v.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:ie.x,top:ie.y},onPointerDown:et=>et.stopPropagation(),children:[v.jsx("button",{type:"button",role:"menuitem",onClick:()=>Je(t),children:"Copy title"}),n&&v.jsx("button",{type:"button",role:"menuitem",onClick:()=>Je(n),children:"Copy conversation ID"})]})]})}function LU(){const[e,t]=g.useState(null),n=g.useRef(null),a=g.useCallback(i=>new Promise(s=>{n.current?.resolve(!1);const l={...i,cancelLabel:i.cancelLabel??"Cancel",tone:i.tone??"default",resolve:s};n.current=l,t(l)}),[]),r=g.useCallback(i=>{const s=n.current;n.current=null,t(null),s?.resolve(i)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:r}}function zU({state:e,onResolve:t}){const n=g.useId(),a=g.useId();if(g.useEffect(()=>{if(!e)return;function i(s){s.key==="Escape"&&t(!1)}return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[t,e]),!e)return null;const r=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return v.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:v.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:i=>i.stopPropagation(),children:[v.jsx("h2",{id:n,children:e.title}),v.jsx("p",{id:a,children:e.body}),v.jsxs("div",{className:"git-dialog-footer",children:[v.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),v.jsx("button",{type:"button",className:r,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function UU(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=LU();return{confirmProjectAction:g.useCallback(r=>e({tone:"danger",...r}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function HU({state:e,onResolve:t}){return v.jsx(zU,{state:e,onResolve:t})}const Xl=new Map,qU=(e,t,n)=>{const a=Xl.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,Xl.set(e,a)};function BU({children:e,id:t}){return v.jsx(g.Profiler,{id:t,onRender:qU,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...Xl.entries()].map(([e,t])=>[e,{...t}])),reset:()=>Xl.clear()});const FU=g.lazy(()=>Xo(()=>import("./MainPane-StAOFINE.js").then(e=>e.M),__vite__mapDeps([35,1,2,13,5,36,32]),import.meta.url).then(e=>({default:e.MainPane})));function VU({className:e,style:t,sidebar:n,topBar:a,mainPane:r,cloudSetup:i,projectConfirm:s,lazyPanels:l,toast:p}){return v.jsxs("div",{className:e,style:t,children:[v.jsx(BU,{id:"sidebar",children:v.jsx(SU,{...n})}),v.jsxs("div",{className:"content-shell",children:[v.jsx(DU,{...a}),v.jsx(g.Suspense,{fallback:v.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:v.jsx(FU,{...r})})]}),v.jsx(wU,{...i}),v.jsx(HU,{...s}),v.jsx(jU,{...l}),v.jsx(bx,{...p})]})}function WU({settings:e,toast:t}){return v.jsxs(v.Fragment,{children:[v.jsx(MU,{...e}),v.jsx(bx,{...t})]})}const Ol="OpenPond".split("");function KU({visibleLetterCount:e=Ol.length}){const t=Ol.slice(0,Math.max(0,Math.min(e,Ol.length)));return v.jsxs("div",{className:"app-splash-lockup",children:[v.jsx("div",{className:"app-splash-mark",children:v.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:oU})}),v.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>v.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const Ru=Ol.length,GU=520,ZU=240;function Sg(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function JU({startup:e}){const[t,n]=g.useState(()=>Sg()?Ru:0);return g.useEffect(()=>{if(Sg()){n(Ru);return}const a=Array.from({length:Ru},(r,i)=>window.setTimeout(()=>n(i+1),GU+ZU*i));return()=>{a.forEach(r=>window.clearTimeout(r))}},[]),v.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[v.jsx(KU,{visibleLetterCount:t}),v.jsx("span",{className:"app-splash-status",children:e.label})]})}const of=5e3;function Ka(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const r of[...e,...t])n.has(r.id)||(n.add(r.id),a.push(r));return a}function Wa(e,t,n=of){return Nl(Ka(e,t),n)}function Nl(e,t=of){return e.length<=t?e:e.slice(e.length-t)}function YU(e,t,n){return n.length===0?e:{...e,[t]:Ka(e[t]??[],n)}}function XU(e,t){if(t.length===0)return Nl(e);if(e.length===0)return Nl(t);const n=new Map;let a=0;for(const r of[...e,...t])n.has(r.id)||n.set(r.id,{event:r,index:a}),a+=1;return Nl([...n.values()].sort((r,i)=>eH(r,i)).map(({event:r})=>r))}function Ql(e){let t=null;for(const n of e)typeof n.sequence=="number"&&(t=t===null?n.sequence:Math.max(t,n.sequence));return t}function QU(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function eH(e,t){const n=e.event.sequence,a=t.event.sequence;if(typeof n=="number"&&typeof a=="number"){const s=n-a;if(s!==0)return s}const r=Date.parse(e.event.timestamp),i=Date.parse(t.event.timestamp);if(Number.isFinite(r)&&Number.isFinite(i)){const s=r-i;if(s!==0)return s}return e.index-t.index}const tH="codex_history_";function Mt(e){return!!e?.startsWith(tH)}function vx(e){const t=[],n=new Set;for(const a of e)for(const r of[a.workspacePath,a.path]){const i=Ec(r);if(!i)continue;const s=`${a.id}:${i}`;n.has(s)||(n.add(s),t.push({projectId:a.id,path:i}))}return t.sort((a,r)=>r.path.length-a.path.length)}function nH(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return e.localProjectId;if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return e.workspaceId;if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=yx(e.cwd,n);if(i)return i}if(e.cloudProjectId&&a.has(e.cloudProjectId))return e.cloudProjectId;if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!Sx(e))return null;const r=Ec(e.cwd);if(!r)return null;for(const i of n)if(rf(r,i.path))return i.projectId;return null}function xg(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return ht("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return ht("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=yx(e.cwd,n);if(i)return ht("local",i)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return ht("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!Sx(e))return null;const r=Ec(e.cwd);if(!r)return null;for(const i of n)if(rf(r,i.path))return ht("local",i.projectId);return null}function yx(e,t){const n=Ec(e);if(!n)return null;for(const a of t)if(rf(n,a.path))return a.projectId;return null}function Sx(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Mt(e.id)}function Ec(e){const t=e?.trim();if(!t)return null;let n=t.replace(/^file:\/\/+/i,"/").replace(/\\/g,"/").replace(/\/+/g,"/");return/^[a-z]:/i.test(n)&&(n=n[0].toUpperCase()+n.slice(1)),n=n.replace(/\/+$/g,""),n||"/"}function rf(e,t){const n=kg(e),a=kg(t);return n===a||n.startsWith(`${a}/`)}function kg(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}function _g(e){if(e<1e3)return String(e);const t=e/1e3;return t>=10||Number.isInteger(t)?`${Math.round(t)}k`:`${t.toFixed(1)}k`}function aH(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function wg(e,t){const n=e?.triggerPercent??85;return e?.autoEnabled===!1?t>=n?"Auto compaction is off. Start a new chat or turn it on before the provider limit is reached.":"Auto compaction is off.":`Auto compacts at ${n}% context when supported.`}function oH(e){return e==="codex"}function rH(e){return e==="openpond"}function xx(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=qA.safeParse(n.data);if(a.success)return a.data}return null}function kx(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,r=Math.min(100,Math.round(e.snapshot.percentFull)),i=`${r}% full`,s=`${_g(n)} / ${_g(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:r,summary:i,tokensLabel:s,detail:wg(e.preferences,r),tooltip:`Context window: ${i} ${s}. ${wg(e.preferences,r)}`,tone:aH(r)}}if(oH(e.provider)){const n="Context is managed by Codex app-server.";return{usedTokens:0,maxTokens:null,percent:null,summary:"Managed externally",tokensLabel:"Codex app-server",detail:n,tooltip:`Context window: ${n}`,tone:"unknown"}}if(!rH(e.provider)){const n="Context pressure is unavailable until this provider has model context metadata.";return{usedTokens:0,maxTokens:null,percent:null,summary:"Limit unknown",tokensLabel:"Provider metadata unavailable",detail:n,tooltip:`Context window: ${n}`,tone:"unknown"}}const t="Send a message to measure hosted context.";return{usedTokens:0,maxTokens:null,percent:null,summary:"Not measured yet",tokensLabel:"Hosted context",detail:t,tooltip:`Context window: ${t}`,tone:"unknown"}}function sf(e){let t=!1;const n=_x(e);for(let a=e.length-1;a>=0;a-=1){const r=e[a];if(iH(r)){t=!0;continue}const i=Qr(r?.data);if(!(r?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared")return null;if(i.kind==="thread_goal"){const s=lf(Qr(i.goal),Bn(i.provider),n);if(s){const l=Cs(s);return t&&l.tone==="active"?null:l}}if(i.kind==="goal_context"){const s=Ix(r.output??"",Bn(i.provider)??"codex",n);if(s){const l=Cs(s);return t&&l.tone==="active"?null:l}}}}return null}function ec(e){const t=_x(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],r=Qr(a?.data);if(!(a?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared"&&r.synthetic!==!0)return null;if(r.kind==="thread_goal"){const i=lf(Qr(r.goal),Bn(r.provider),t);if(!i)continue;const s=Cs(i);return s.tone==="active"?s:null}if(r.kind==="goal_context"){const i=Ix(a.output??"",Bn(r.provider)??"codex",t);if(!i)continue;const s=Cs(i);return s.tone==="active"?s:null}}}return null}function Au(e){const t=Qr(Qr(e)?.codexGoalRuntime),n=lf(t,Bn(t?.provider)??"codex");if(!n)return null;const a=Cs(n);return a.tone==="active"?a:null}function iH(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Cs(e){const t=Cx(e.status),n=Px(e.timeUsedSeconds),a=`Goal ${n}`,r=e.tokensUsed===null?null:e.tokenBudget===null?`${Pu(e.tokensUsed)} tokens`:`${Pu(e.tokensUsed)} / ${Pu(e.tokenBudget)} tokens`,i=r?`${e.statusLabel} · ${r}`:e.statusLabel;return{objective:e.objective,status:e.status,timeUsedSeconds:e.timeUsedSeconds,tokensUsed:e.tokensUsed,tokenBudget:e.tokenBudget,actionLabel:t.actionLabel,timeLabel:n,label:a,detail:i,tooltip:`Goal runtime: ${Tx(e.timeUsedSeconds)}. ${i}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function sH(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=wx(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,r=Px(a);return{...e,timeUsedSeconds:a,timeLabel:r,label:`Goal ${r}`,tooltip:`Goal runtime: ${Tx(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function lf(e,t=null,n=null){if(!e)return null;const a=Bn(e.objective)??"Active goal",r=Bn(e.status)??"active";if((wm(t)??wm(Bn(e.provider)))!=="codex")return null;const s=n??Bn(e.updatedAt)??Bn(e.updated_at)??null,l=Pr(e.timeUsedSeconds)??Pr(e.time_used_seconds)??0,p=Bn(e.activeSinceAt)??Bn(e.active_since_at),m=Cx(r).tone==="active"?wx(p??Bn(e.createdAt)??Bn(e.created_at),s):0,f=p?l+m:Math.max(l,m),S=Pr(e.tokensUsed)??Pr(e.tokens_used),y=Pr(e.tokenBudget)??Pr(e.token_budget);return{objective:a,status:r,statusLabel:Ax(r),timeUsedSeconds:Math.max(0,Math.floor(f)),tokensUsed:S===null?null:Math.max(0,Math.floor(S)),tokenBudget:y===null?null:Math.max(0,Math.floor(y)),observedAt:s}}function _x(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t]?.timestamp;if(n&&Number.isFinite(Date.parse(n)))return n}return null}function wx(e,t){if(!e||!t)return 0;const n=Date.parse(e),a=Date.parse(t);return!Number.isFinite(n)||!Number.isFinite(a)||a<=n?0:Math.floor((a-n)/1e3)}function Ix(e,t=null,n=null){if(!e.trim()||wm(t)!=="codex")return null;const a=Rx(e,"Status")??"active",r=ns(e,"Tokens used"),i=ns(e,"Token budget"),s=ns(e,"Time used seconds")??ns(e,"Time spent pursuing goal")??ns(e,"Elapsed seconds")??0;return{objective:Ig(e,"objective")??Ig(e,"untrusted_objective")??"Active goal",status:a,statusLabel:Ax(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:r,tokenBudget:i,observedAt:n}}function Cx(e){switch(lH(e)){case"active":case"running":return{tone:"active",actionLabel:"Pursuing goal"};case"paused":return{tone:"paused",actionLabel:"Goal paused"};case"blocked":return{tone:"limited",actionLabel:"Goal blocked"};case"complete":case"completed":case"achieved":return{tone:"done",actionLabel:"Goal achieved"};case"failed":return{tone:"limited",actionLabel:"Goal failed"};case"cancelled":case"canceled":case"stopped":return{tone:"limited",actionLabel:"Goal cancelled"};case"budget_limited":return{tone:"limited",actionLabel:"Goal budget limited"};default:return{tone:"active",actionLabel:"Goal status unknown"}}}function lH(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function Rx(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function ns(e,t){const n=Rx(e,t);if(!n)return null;const a=n.replace(/,/g,""),r=/-?\d+(?:\.\d+)?/.exec(a);if(!r)return null;const i=Number(r[0]);return Number.isFinite(i)?i:null}function Ig(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function Ax(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function Px(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),a=t%60;return a>0?`${n}h ${a}m`:`${n}h`}function Tx(e){if(e<60)return`${e} ${e===1?"second":"seconds"}`;const t=Math.floor(e/60);if(t<60)return`${t} ${t===1?"minute":"minutes"}`;const n=Math.floor(t/60),a=t%60;return a===0?`${n} ${n===1?"hour":"hours"}`:`${n}h ${a}m`}function Pu(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${Cg(n,2)}M`:n<100?`${Cg(n,1)}M`:`${Math.round(n)}M`}const t=e/1e3;return t>=10||Number.isInteger(t)?`${Math.round(t)}k`:`${t.toFixed(1)}k`}function Cg(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function Qr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Bn(e){return typeof e=="string"&&e.trim()?e.trim():null}function wm(e){return e?.trim().toLowerCase()||null}function Pr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const cH=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),dH=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function Im(e){const t=Ex(e);return t?fH(t):null}function Ex(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=pH(yH(n.data));if(a)return a}return null}function uH(e){if(e.events)return Ex(e.events);const t=e.messages??[];for(let n=t.length-1;n>=0;n-=1){const a=t[n]?.createImproveRun??null;if(a)return a}return null}function mH(e,t){const n=e?.target.displayName?.trim()??"",a=n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();return n&&!/^(?:create|creating|improve|improving|new) (?:an )?agent$/.test(a)?n:t}function pH(e){const t=Os.safeParse(e?.createImproveRun);return t.success?t.data:null}function fH(e){const t=hH(e);if(!t)return null;const n=gH(e.createdAt,e.updatedAt),a=e.blockedReason??bH(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:vH(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function hH(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return cH.has(t)?{tone:"active",actionLabel:`${n} running`}:dH.has(t)?{tone:"active",actionLabel:`${n} awaiting input`}:t==="blocked"?{tone:"limited",actionLabel:`${n} blocked`}:t==="failed"?{tone:"limited",actionLabel:`${n} failed`}:t==="cancelled"?{tone:"limited",actionLabel:`${n} cancelled`}:t==="ready"||t==="ready_local"?{tone:"done",actionLabel:e.target.kind==="agent"?"Agent ready":"Workproduct ready"}:t==="published_hosted"?{tone:"done",actionLabel:e.target.kind==="agent"?"Agent published":"Workproduct published"}:null}function gH(e,t){const n=Date.parse(e),a=Date.parse(t);return!Number.isFinite(n)||!Number.isFinite(a)||a<n?0:Math.floor((a-n)/1e3)}function bH(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function vH(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),a=t%60;return a>0?`${n}h ${a}m`:`${n}h`}function yH(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Mx(e,t){if(!t)return null;const n=new Map,a=[];for(const I of e){if(!I.name.startsWith("subagent."))continue;const P=kH(I);P&&a.push(P);const j=xH(I);j?.parentSessionId===t&&n.set(j.id,j)}if(n.size===0)return null;const r=[...n.values()].sort((I,P)=>Mr(P).localeCompare(Mr(I))),i=r.filter(I=>I.status==="queued"||I.status==="running"),s=r.filter(I=>I.status==="completed"),l=r.filter(I=>I.status==="failed"),p=r.filter(I=>I.status==="cancelled"),m=r.filter(I=>I.status==="needs_resume"),f=[...s,...l,...p].sort((I,P)=>Mr(P).localeCompare(Mr(I))),S=r.reduce((I,P)=>{const j=ei(P.metadata?.usage);return I.totalTokens+=xl(j?.totalTokens),I.promptTokens+=xl(j?.promptTokens),I.completionTokens+=xl(j?.completionTokens),I.requestCount+=xl(j?.requestCount),I},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=r.flatMap(I=>jx([...I.report?.blockers??[],I.error,I.progress.currentBlocker]).map(P=>({runId:I.id,roleId:I.roleId,status:I.status,message:P}))),k=r.flatMap(I=>Ox([...I.report?.artifacts??[],I.report?.patchRef,I.report?.diffRef,...I.progress.patchRefs]).map(P=>({...P,runId:I.id,roleId:I.roleId}))),R=f.map(I=>SH(I,a)),A=r[0]??null,D=A?{runId:A.id,roleId:A.roleId,status:A.status,message:A.progress.latestMeaningfulActivity||A.report?.summary||A.objective,updatedAt:Mr(A)}:null,z=i.length>0?`${i.length} ${i.length===1?"child":"children"} running`:`${f.length} ${f.length===1?"child":"children"} finished`,N=[i.length?`${i.length} active`:null,s.length?`${s.length} completed`:null,l.length?`${l.length} failed`:null,p.length?`${p.length} cancelled`:null,m.length?`${m.length} paused`:null].filter(Boolean).join(" · "),x=D?`${IH(D.roleId)}: ${D.message}`:"";return{sessionId:t,runs:r,activeRuns:i,completedRuns:s,failedRuns:l,cancelledRuns:p,needsResumeRuns:m,terminalRuns:f,latestRun:A,latestMeaningfulUpdate:D,activeCount:i.length,completedCount:s.length,failedCount:l.length,cancelledCount:p.length,needsResumeCount:m.length,terminalCount:f.length,usage:S,blockers:y,evidenceRefs:k,finalResults:R,testsRunCount:r.reduce((I,P)=>I+P.progress.validationAttempts.length,0),label:z,tooltip:[N,x].filter(Boolean).join(". ")}}function SH(e,t){return{runId:e.id,roleId:e.roleId,status:e.status,objective:e.objective,summary:e.report?.summary||e.error||"Child conversation finished.",findings:e.report?.findings??[],changedFiles:e.progress.changedFiles,refs:Ox([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:jx([...e.report?.blockers??[],e.error]),confidence:e.report?.confidence??null,importantMessages:t.filter(n=>n.fromRunId===e.id).map(n=>({id:n.id,runId:e.id,fromRunId:n.fromRunId,kind:n.kind,body:n.body,createdAt:n.createdAt})),workspaceRetention:_H(e),updatedAt:Mr(e)}}function xH(e){const t=ei(e.data),n=[t?.run,ei(t?.message)?.run];for(const a of n){const r=xv.safeParse(a);if(r.success)return r.data}return null}function kH(e){const t=lR.safeParse(ei(e.data)?.message);return t.success?t.data:null}function _H(e){const t=ei(ei(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Sl(t.reason),retainedAt:Sl(t.retainedAt),expiresAt:Sl(t.expiresAt),retentionDays:wH(t.retentionDays),trigger:Sl(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Mr(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function jx(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function Ox(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function ei(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Sl(e){return typeof e=="string"&&e.trim()?e.trim():null}function xl(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function wH(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function IH(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const Cm=[];function Rm(e,t){return Nx(e,t,null)}function Nx(e,t,n){const a=n&&TH(n.events,e)?RH(n.indexes,n.events.length,e):CH(e),r=PH(t);return{...a,...r}}function CH(e){const t=new Map;for(const n of e){if(!n.sessionId)continue;const a=t.get(n.sessionId);a?a.push(n):t.set(n.sessionId,[n])}return AH(t)}function RH(e,t,n){const a=new Map(e.eventsBySessionId),r=new Map(e.latestContextUsageBySessionId),i=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),l=new Set(e.activeGoalSessionIds),p=new Set(e.activeSubagentSessionIds),m=new Set;for(let f=t;f<n.length;f+=1){const S=n[f];if(!S.sessionId)continue;if(m.has(S.sessionId)){a.get(S.sessionId).push(S);continue}const y=a.get(S.sessionId);a.set(S.sessionId,y?[...y,S]:[S]),m.add(S.sessionId)}for(const f of m){const S=a.get(f)??Cm,y=xx(S);y?r.set(f,y):r.delete(f);const k=Dx(S);k?(i.set(f,k),k.tone==="active"?l.add(f):l.delete(f)):(i.delete(f),l.delete(f));const R=Mx(S,f);R?(s.set(f,R),$x({sessionEvents:S,sessionId:f,latestGoalRuntimeBySessionId:i,activeGoalSessionIds:l}),R.activeCount>0?p.add(f):p.delete(f)):(s.delete(f),p.delete(f))}return{eventsBySessionId:a,latestContextUsageBySessionId:r,latestGoalRuntimeBySessionId:i,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:l,activeSubagentSessionIds:p}}function AH(e){const t=new Map,n=new Map,a=new Map,r=new Set,i=new Set;for(const[s,l]of e){const p=xx(l);p&&t.set(s,p);const m=Dx(l);m&&(n.set(s,m),m.tone==="active"&&r.add(s))}for(const[s,l]of e){const p=Mx(l,s);p&&(a.set(s,p),$x({sessionEvents:l,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:r}),p.activeCount>0&&i.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:r,activeSubagentSessionIds:i}}function $x(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=ec(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function Dx(e){return Im(e)??sf(e)??ec(e)}function PH(e){const t=new Map,n=new Map,a=new Map,r=new Map;for(const i of e){t.set(i.id,i);const s=n.get(i.status);if(s?s.push(i):n.set(i.status,[i]),i.status!=="pending")continue;const l=a.get(i.sessionId);l?l.push(i):a.set(i.sessionId,[i]);const p=r.get(i.sessionId);(!p||Rg(i.createdAt)>Rg(p.createdAt))&&r.set(i.sessionId,i)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:r}}function TH(e,t){return e===t?!0:e.length>t.length||e.length===t.length?!1:e.length===0?!0:e[0]===t[0]&&e[e.length-1]===t[e.length-1]}function Vs(e,t){return t?e.eventsBySessionId.get(t)??Cm:Cm}function Lx(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function zx(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function EH(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function MH(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function Rg(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function jH(e){const t=new Set;if(e.readmePath){const n=e.readmePath.replaceAll("\\","/").split("/").at(-1);n&&t.add(n)}for(const n of e.skills){t.add(n.relativePath);const a=n.relativePath.lastIndexOf("/"),r=a>=0?n.relativePath.slice(0,a):"";for(const i of n.resourceFiles)t.add(r?`${r}/${i}`:i)}return{name:`${e.owner}/${e.repo}`,description:`${e.skills.length} installed skill${e.skills.length===1?"":"s"} from GitHub.`,scope:"extension",packagePath:e.sourcePath,files:[...t]}}function OH(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function XV(e,t){return e.profiles.find(n=>OH(n.ref)===t)?.ref??null}function NH(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function QV(e,t){return e.profiles.find(n=>NH(n.ref,t))?.state??null}function $H(e,t){const n=new Map(nT.map(a=>[a.name,{...a,validationMessages:[...a.validationMessages],resourceFiles:[...a.resourceFiles]}]));for(const a of e?.skills??[])n.has(a.name)||n.set(a.name,a);for(const a of t?.extensions??[])if(a.validationStatus==="valid")for(const r of a.skills)r.validationStatus!=="valid"||n.has(r.name)||n.set(r.name,{name:r.name,description:r.description,path:r.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:r.charCount,sourceHash:r.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:r.resourceFiles});return[...n.values()].sort((a,r)=>a.name.localeCompare(r.name))}function DH(e){return{sourceTaskId:e.sourceTaskId,sourceExperience:e.sourceExperience,targetExperience:e.targetExperience,sourceMessageIds:[...e.sourceMessageIds??[]],sourceContext:e.sourceContext?.trim()||null,outputId:e.output?.id??null,outputRevision:e.output?.revision??null,createdAt:e.createdAt??new Date().toISOString(),checkoutMutation:"none"}}function eW(e,t){const n=`Continue from the attached Work output "${e.title}" (revision ${e.revision}).`;return t==="work"?`${n} Choose a Project or repository before making source changes; do not mutate a checkout until I choose it.`:n}const Ux="openpond:last-chat-task-mode";function LH(e,t){return e==="labs"?"models":"chat"}function zH(e){try{return e.getItem(Ux)==="work"?"work":"chat"}catch{return"chat"}}function Hx(){if(typeof window>"u")return"chat";try{return zH(window.localStorage)}catch{return"chat"}}function UH(e,t){try{e.setItem(Ux,t==="chat"?"chat":"work")}catch{}}function HH(e){if(!(typeof window>"u"))try{UH(window.localStorage,e)}catch{}}const qH="uploaded to a different account";function qx(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(r=>r.id===n.projectId&&r.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function sa(e,t){const n=qx(e,t);return n.state==="confirmed"?n.cloudProject:null}function BH(e,t){return qx(e,t).state==="different_account"?qH:null}function $a(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function Bx(e={}){return{...e,workspaceTarget:"hybrid"}}function FH(e={}){return{...e,workspaceTarget:"local"}}function Da(e){return e?.metadata?.workspaceTarget==="hybrid"}function VH(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function Fx({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,r=e?sa(n,e):null,i=t?.id??r?.id??(e?null:a?.projectId??null),s=t?.teamId??r?.teamId??(e?null:a?.teamId??null);return!i||!s?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:i,cloudTeamId:s,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??r?.name??a?.projectName??n?.name??"Hybrid workspace"}}function Vx({modelRef:e,provider:t,target:n,title:a}){return{provider:t,...e?{modelRef:e}:{},appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:n.workspaceName,localProjectId:n.localProjectId,cloudProjectId:n.cloudProjectId,cloudTeamId:n.cloudTeamId,metadata:Bx(),cwd:n.cwd,title:a}}function WH(e){return g.useEffect(()=>{const t=ox(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),g.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=KL(n);try{let r;const i=e.selectedSession;if(i&&ws(i))r=await J.patchSession(e.connection,i.id,{title:a,metadata:wu(i.metadata,n)}),e.setSessions(s=>s.map(l=>l.id===r.id?r:l));else{const s=i?.metadata?.workspaceTarget==="hybrid"?"hybrid":i?.metadata?.workspaceTarget==="local"?"local":null,l=i?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),p=i?.modelRef??(l==="openpond"?{providerId:"openpond",modelId:Ts}:{providerId:l,modelId:e.activeModel}),m=s?{workspaceTarget:s}:!i&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let f;if(!i&&e.workspaceTarget==="hybrid"){const S=Fx({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(S.kind!=="ready")throw new Error(S.message);const y=Vx({modelRef:p,provider:l,target:S,title:a});f={...y,experience:"work",metadata:wu(y.metadata,n)}}else f={experience:"work",provider:l,modelRef:p,openPondCommandAccessMode:i?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:i?.appId??null,appName:i?.appName??null,workspaceKind:i?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:i?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:i?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:i?.localProjectId??e.selectedProject?.id??null,cloudProjectId:i?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:i?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:i?.cwd??e.selectedProject?.workspacePath??null,metadata:wu(m,n),title:a};r=await J.createSession(e.connection,f),e.setSessions(S=>[r,...S])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(r){return e.showToast(r instanceof Error?r.message:"Could not save task draft.","error"),!1}},[e.activeExperience,e.activeModel,e.activeOpenPondCommandAccessMode,e.activeProvider,e.cloudProjects,e.composerDraftStore,e.connection,e.requestComposerFocus,e.selectedCloudProject,e.selectedProject,e.selectedSession,e.setMentionedAppId,e.setSelectedSessionId,e.setSessions,e.setView,e.showToast,e.workspaceTarget])}const KH=[];function GH({primary:e,secondary:t}){const[n,a]=g.useState(!1),r=OL(),{composerDraftStore:i,appDispatch:s,pendingTerminalCommand:l,setPendingTerminalCommand:p,terminalTabs:m,setTerminalTabs:f,trainingDetailTasksetId:S,setTrainingDetailTasksetId:y,mentionedAppId:k,setMentionedAppId:R,cloudSetupDialog:A,setCloudSetupDialog:D,rightPanelTabRequest:z,workspaceDiffPanelViewState:N,mainComposerFocusRequestId:x,requestMainComposerFocus:I,projectConfirmDialog:P,resolveProjectConfirmDialog:j,query:T,searchOpen:F,archivedChatsOpen:q,sectionMenuOpen:$,cloudProjectsExpanded:V,sidebarOpen:re,view:X,selectedAppId:we,selectedProjectId:ye,selectedSessionId:K,codexPermissionMode:Ee,codexReasoningEffort:xe,busy:se,diffPanelOpen:ke,diffPanelExpanded:ee,rightPanelMode:pe,activeExperience:ve,changeNewExperience:qe,terminalOpen:Re,settingsSection:ie,newProjectDialogOpen:Ie,newProjectMode:$e,newProjectName:Je,newProjectPath:et,newProjectBusy:st,commitDialogOpen:Be,commitMessage:He,commitIncludeUnstaged:Ne,commitNextStep:E,commitDraft:U,branchDialogOpen:G,branchDialogName:me,toast:W,labDetailNavigation:de,setQuery:he,setSearchOpen:We,setArchivedChatsOpen:Ze,setSectionMenuOpen:tt,setCloudProjectsExpanded:at,setChatRowsVisibleCount:Te,setSidebarOpen:De,setView:u,setSelectedAppId:M,setSelectedProjectId:H,setSelectedSessionId:ae,setPrompt:O,setDraftProvider:Z,setDraftModel:_,setDraftExperience:L,setDiffPanelOpen:oe,setDiffPanelExpanded:Q,setRightPanelMode:Y,setTerminalOpen:ue,setSettingsSection:le,setNewProjectDialogOpen:ze,setNewProjectName:Pe,setNewProjectPath:Oe,setCommitDialogOpen:Ye,setCommitMessage:Le,setCommitIncludeUnstaged:ut,setCommitNextStep:Gt,setCommitDraft:gn,setBranchDialogOpen:bn,setBranchDialogName:sn,setError:Pt,showToast:It,applyBootstrapPayload:vn,bootstrap:Ct,connection:$t,startup:Bt,training:Yt,pinnedCollapsed:en,cloudProjectsCollapsed:un,chatsCollapsed:An,savedForLaterCollapsed:La,sidebarWidth:Ft,sidebarResizing:Ln,diffPanelWidth:lt,diffPanelResizing:Dt,togglePinnedCollapsed:te,toggleCloudProjectsCollapsed:Ke,toggleChatsCollapsed:Ge,toggleSavedForLaterCollapsed:yt,startSidebarResize:mn,startDiffPanelResize:ka,selectedApp:Pn,selectedCloudProject:Zt,selectedProject:bt,selectedProjectLinkedApp:tn,selectedSession:St,sidebarSessions:ft,runtimeIndexes:Tt,runtimeEventStore:pn,chatMentionApps:zn,connectedAppMentions:Xe,pendingApproval:yn,pendingChatUserMessages:vt,account:fn,activeModel:Tn,activeProvider:xn,appDefaults:_a,startMessage:da,teamChatOrganization:ua,teamChatTeamId:ma,teamChat:ct,publishTeamProfileAgent:mi,communitySidebar:ta,communityView:wa,teamAiThreadId:wo,toggleTeamAiSidebar:rr,activeOpenPondCommandAccessMode:pa,viewWorkspaceAppId:pi,viewWorkspaceId:Io,viewWorkspaceKind:ir,viewWorkspaceName:sr,selectedActionCatalog:fi,expandedProjectIds:hi,expandProject:Ia,toggleProjectExpanded:gi,changeCodexPermissionMode:lr,changeCodexReasoningEffort:cr,changeOpenPondCommandAccessMode:dr,resolveApproval:bi,beginNewChat:na,beginNewChatWithTrainingModel:vi,dismissTrainingChatHandoff:yi,trainingChatHandoff:Si,selectTrainingChatTaskForComposer:xi,chatHistoryLoadStates:ur,loadMoreSelectedChatHistory:mr,selectedPagedSessionEvents:pr,activeSessions:no,archivedSessions:Co,pinnedSessions:za,savedForLaterSessions:Un,savedForLaterFiles:ki,sidebarFileBookmarks:_i,setSidebarFileStatus:nn,setSessions:Ro,projectRows:Hn,localProjectRows:fa,cloudProjectRows:Ao,projectSessionRowsByProjectId:Ca,childSessionRowsByParentId:wi,sidebarProjectIdBySessionId:Po,chatRows:Ii,visibleChatRows:To,chatRowsVisibleCount:fr,sessionEvents:Eo,goalRuntime:hr,subagentRuntime:Mo,visibleChatMessages:gr,activeTerminalScope:aa,terminalSummaries:ao,runningSessionIds:jo,selectedSessionRunning:Ua,sidebarGoalRuntimeBySessionId:br,sidebarSubagentRuntimeBySessionId:Ra,taskDragSessionId:vr,taskPreviewSessionIds:Ci,startTaskDrag:Oo,clearTaskDrag:yr,previewTaskDrop:Sr,commitTaskDrop:xr,commitTaskPreviewDrop:Ri,dragItem:kr,startPinnedDrag:_r,clearSidebarDrag:oo,previewPinnedDrop:Aa,commitPinnedDrop:Ai,commitPinnedPreviewDrop:Pi,commandProjectRows:Ti,contextWindowStatus:wr,pinnedRows:Pa,workspaceBusy:ro,diffBusy:Ei,visibleWorkspaceState:Ha,visibleWorkspaceDiff:No,refreshVisibleWorkspaceDiff:Jn,managedWorkspace:Mi,canSyncActiveWorkspace:ji,canPublishOpenPondProject:Oi,projectTarget:Ni,workspaceTarget:dt}=e,{title:jt,browserConversationId:qn,handleWorkspaceDiffPanelViewStateChange:hn,openSessionInChat:kn,changeProjectTarget:Yn,submitNewProjectDialog:Uc,changeWorkspaceBranch:Hc,openCommitDialog:qc,openCreateWorkspaceBranchDialog:$i,openDefaultsSettingsFromBranchDialog:Gs,runWorkspaceTool:Bc,submitCommitDialog:Fc,submitCreateWorkspaceBranch:Vc,syncWorkspaceLocally:Wc,answerCreateImproveQuestion:Kc,applyCreateImproveCandidate:Gc,approveCreateImproveRun:Zc,cancelCreateImproveRun:Jc,changeDraftProvider:Zs,openCreateImprovePullRequest:Yc,reconcileCreateImprovePullRequest:Xc,rejectCreateImproveCandidate:Js,pauseCreateImproveRun:Qc,resumeCreateImproveRun:ed,reviseCreateImproveRun:td,stopTurn:Di,archiveSession:Ys,restoreSession:nd,renameSession:ad,toggleSessionPinned:Xs,toggleProjectPinned:Li,toggleSessionSavedForLater:od,moveProjectToCloud:zi,startCloudSetupUpload:rd,changeWorkspaceTarget:Qs,sendPromptFromMainComposer:id,openSandboxWorkspace:Ui,openCloudProjectDialog:sd,openUrlInBrowserPanel:el,showBrowserPanel:ld,showChangesPanel:tl,showGoalSidebarTab:cd,rightChatTrainingLaunchRequest:dd,setRightChatTrainingLaunchRequest:nl,closeRightChatPanel:ud,openRightChatPanel:Hi,rightChatPanelViews:md,showRightChatPanel:pd,showRightPanelDiffTab:fd,submitRightChatPrompt:io,activateRightChatPanel:al,updateRightChatModel:hd,updateRightChatPrompt:gd,updateRightChatProvider:bd,updateRightChatScrollState:vd,openProfileSettings:yd,diagnosticEvents:Sd,toggleRightSidebar:ol,removeProject:xd}=t,rl=g.useCallback(Ce=>{M(null),H(Ce),ae(null),u("chat"),Ia(Ce),I()},[Ia,I,M,H,ae,u]),qi=ma??_a.defaultTeamId??null,kd=g.useMemo(()=>Hn.filter(Ce=>Ce.kind==="local"||qi!==null&&Ce.project.teamId===qi),[Hn,qi]),_d=g.useMemo(()=>{const Ce={};for(const ot of no){const _t=Po[ot.id];_t&&(Ce[_t]=(Ce[_t]??0)+1)}for(const ot of fa){if(ot.kind!=="local")continue;const _t=ot.project.linkedSandboxProject?.projectId;if(!_t||!ot.cloudLinkTrusted)continue;const ha=ht("cloud",_t);Ce[ot.id]=(Ce[ot.id]??0)+(Ce[ha]??0)}return Ce},[no,fa,Po]),[Bi,Fi]=g.useState(null),[Vi,Wi]=g.useState(null),wd=$H(Ct?.profile,Ct?.extensionCatalog),[Ki,Gi]=g.useState(null),[Zi,Ji]=g.useState(null),[Yi,Id]=g.useState(null),Cd=g.useCallback(()=>{M(null),H(null),ae(null),tt(null),u("team")},[tt,M,H,ae,u]),kf=g.useCallback(()=>{M(null),H(null),ae(null),tt(null),ta.discoverCommunities()},[ta.discoverCommunities,tt,M,H,ae]),$o=WH({activeExperience:ve,activeModel:Tn,activeOpenPondCommandAccessMode:pa,activeProvider:xn,cloudProjects:Ct?.cloudProjects??KH,composerDraftStore:i,connection:$t,requestComposerFocus:I,selectedCloudProject:Zt,selectedProject:bt,selectedSession:St,setMentionedAppId:R,setSelectedSessionId:ae,setSessions:Ro,setView:u,showToast:It,workspaceTarget:dt.value}),il=g.useCallback(async Ce=>{if(!$t)throw new Error("OpenPond is not connected.");let ot=xn,_t=Tn;ot==="codex"&&(ot=km(Ct?.providers,{enabledOnly:!0}).find(ln=>ln.value!=="codex")?.value??Zo,_t=Jl(ot,Ct?.providers)??bs);const ha=ft.find(ln=>ln.id===Ce.sourceSessionId),qa=await J.createSession($t,{experience:Ce.target,provider:ot,modelRef:{providerId:ot,modelId:_t},openPondCommandAccessMode:pa,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ha?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:DH({sourceTaskId:Ce.sourceSessionId,sourceExperience:ha?.experience??null,targetExperience:Ce.target,sourceMessageIds:Ce.sourceMessageIds??[],sourceContext:Ce.sourceContext,output:Ce.output})}});return Ro(ln=>[qa,...ln]),L(Ce.target),Z(ot),_(_t),i.set(Ce.prompt),Qt({kind:"chat",sessionId:qa.id}),s({type:"selectSession",sessionId:qa.id,appId:null,projectId:null}),M(null),H(null),ue(!1),u("chat"),Y("home"),oe(Ce.target==="work"),Q(!1),qa},[Tn,pa,xn,s,Ct?.providers,i,$t,Q,oe,L,_,Z,Y,M,H,Ro,ue,u,ft]),sl=g.useCallback(Ce=>{Gi(Ce),Ji(null),na(null),De(!0)},[na,De]),Rd=g.useCallback(Ce=>{na(null),L("work"),i.set(`$openpond-refiner-authoring ${Ce}`),u("chat"),De(!0)},[na,i,L,De,u]),Xi=g.useCallback(Ce=>{Ji(jH(Ce)),Gi(null),na(null),De(!0)},[na,De]);g.useEffect(()=>{!Ki&&!Zi||X!=="chat"||K||ye||we||(Fi(Ki),Wi(Zi),Gi(null),Ji(null),Y("home"),Q(!1),oe(!0))},[Ki,Zi,we,ye,K,Q,oe,Y,X]),g.useEffect(()=>{!Bi&&!Vi||X==="chat"&&ke&&pe==="home"||(Fi(null),Wi(null))},[ke,Vi,Bi,pe,X]);const Ad=g.useCallback(()=>{Fi(null),Wi(null),Q(!1),oe(!1)},[Q,oe]),ll=g.useCallback(Ce=>{if(Ce.workspaceKind==="local"){const ot=ht("local",Ce.workspaceId);M(null),H(ot),ae(null),Ia(ot),u("chat")}else{const ot=ft.find(_t=>_t.id===Ce.sourceSessionId||_t.workspaceId===Ce.workspaceId);if(!ot){It("This saved file's cloud chat is no longer available.","error");return}kn(ot.id)}Y("changes"),oe(!0),Id({id:Date.now(),file:Ce}),Ce.available||It(`File unavailable: ${Ce.path}`,"error")},[Ia,kn,oe,Y,M,H,ae,u,It,ft]);g.useEffect(()=>{if(!Yi)return;const Ce=window.setTimeout(()=>{Y("changes"),oe(!0)},0);return()=>window.clearTimeout(Ce)},[ye,K,oe,Y,Yi]);const Pd=LH(X);g.useEffect(()=>{if(r){if(r.kind==="models"){X!=="labs"&&u("labs");return}if(r.kind==="settings"){M(null),H(null),ae(null),le(r.section),X!=="settings"&&u("settings");return}if(r.kind==="view"){M(null),H(null),ae(null),X!==r.view&&u(r.view);return}M(null),H(null),ae(r.sessionId),X!=="chat"&&u("chat")}},[r,M,H,ae,le,u,X]);const Do=g.useCallback(Ce=>{if(tt(null),M(null),H(null),ae(null),Ce==="models"){Fr({kind:"index"}),u("labs");return}Ce==="chat"&&Qt({kind:"chat",sessionId:null}),qe(Hx())},[qe,Qt,tt,M,H,ae,u]),Td=g.useCallback(async(Ce,ot)=>{const _t=await Yt.actions.acceptHarnessReview(Ce,ot,{providerId:xn,modelId:Tn},xe);return _t?(y(_t.materializedTasksetId??null),Fr({kind:"index"}),u("labs"),!0):(It("Taskset review could not be opened.","error"),!1)},[Tn,xn,xe,Fr,y,u,It,Yt.actions]);if(!Bt.ready)return v.jsx(JU,{startup:Bt});if(X==="settings")return v.jsx(bg,{showToast:It,children:v.jsx(WU,{settings:{payload:Ct,connection:$t,diagnostics:Sd,initialSection:ie,onPayload:vn,onError:Pt,onToast:It,onOpenSourceSession:kn,onStartRefinerAuthoring:Rd,onAcceptEvaluationReview:Td,onOpenSkill:sl,onOpenExtension:Xi,teamChatCurrentUserId:ct.currentUserId,teamChatEnabled:ma!==null,teamChatNotificationMode:ct.notificationMode,teamChatThreads:ct.threads,onTeamChatNotificationModeChange:ct.setNotificationMode,onTeamChatThreadMuteChange:ct.setThreadMuted,diffPanelWidth:lt,diffPanelResizing:Dt,diffPanelExpanded:ee,onDiffPanelResizeStart:ka,onDiffPanelExpandedChange:Q,onBack:()=>{Qt({kind:"chat",sessionId:null}),u("chat"),De(!0)}},toast:{toast:W,onDismiss:()=>s({type:"field",key:"toast",value:null})}})});const Ed=Tc(),Qi=$t?.platform??navigator.platform,Md=Ed&&Xp(Qi),cl=aa,jd=Ha?.initialized?Ha.repoPath:St?.cwd??null,Od={"--sidebar-width":`${Ft}px`,"--diff-panel-width":`${lt}px`},dl=X==="chat"&&ve!=="chat"||X==="labs"||X==="scheduled"&&n||X==="team"&&!!wo,ul=["app-shell",Md?"platform-macos":"",re?"sidebar-open":"sidebar-closed",Ln?"sidebar-resizing":"",Dt?"diff-panel-resizing":""].filter(Boolean).join(" "),es=K?ur[K]:null,Nd=K?es?.cursorSequence??QU(Wa(pr,Vs(Tt,K))):null,$d=!!K&&!!$t&&(Mt(K)?!0:!!Ct?.eventWindow?.hasMoreBefore&&!!Nd)&&(es?.hasMore??!0),rt=!!es?.loading,Lt=(()=>{const Ce=Yt.payload;if(!Ce)return{};const ot=new Map(Ce.plans.map(ln=>[ln.id,ln])),_t=new Set(["queued","starting","running","cancelling","reconciling"]),ha={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},qa={};for(const ln of[...Ce.modelRuns].sort((ga,Ir)=>Ir.updatedAt.localeCompare(ga.updatedAt))){if(ln.kind==="evaluation"||!["prepared","running"].includes(ln.status))continue;const ga=Ce.jobs.filter(Dd=>Dd.metadata.modelRunId===ln.id).sort((Dd,Qk)=>Qk.updatedAt.localeCompare(Dd.updatedAt))[0];if(ga&&!_t.has(ga.status))continue;const Ir=ga?.status??(ln.status==="prepared"?"starting":"running");qa[ln.modelId]={label:ha[Ir]??"Running",status:Ir}}for(const ln of[...Ce.jobs].sort((ga,Ir)=>Ir.updatedAt.localeCompare(ga.updatedAt))){if(!_t.has(ln.status))continue;const ga=ot.get(ln.planId)?.modelId;!ga||qa[ga]||(qa[ga]={label:ha[ln.status]??"Active",status:ln.status})}return qa})();return v.jsx(bg,{showToast:It,children:v.jsx(VU,{className:ul,style:Od,sidebar:{productArea:Pd,modelProjects:(Yt.payload?.modelProjects??[]).filter(Ce=>Ce.hosted===null||Ce.hosted.teamId===(_a.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:Lt,onProductAreaChange:Do,experience:ve,view:X,selectedAppId:we,selectedProjectId:ye,selectedSessionId:K,selectedTeamThreadId:ct.selectedThreadId,teamChatEnabled:ma!==null,teamChatOrganization:ua,teamChatLoading:ct.loading,currentUserId:ct.currentUserId,teamMembers:ct.members,teamThreads:ct.threads,...ta,account:fn,connection:$t,profile:Ct?.profile,pinnedCollapsed:en,cloudProjectsCollapsed:un,chatsCollapsed:An,savedForLaterCollapsed:La,archivedChatsOpen:q,cloudProjectsExpanded:V,sectionMenuOpen:$,dragItem:kr,taskDragSessionId:vr,taskPreviewSessionIds:Ci,activeSessions:no,archivedSessions:Co,pinnedRows:Pa,pinnedSessions:za,savedForLaterSessions:Un,savedForLaterFiles:ki,projectRows:Hn,localProjectRows:fa,cloudProjectRows:Ao,projectSessionRowsByProjectId:Ca,childSessionRowsByParentId:wi,sidebarProjectIdBySessionId:Po,terminalSummaries:ao,runningSessionIds:jo,goalRuntimeBySessionId:br,subagentRuntimeBySessionId:Ra,visibleChatRows:To,chatRows:Ii,chatRowsVisibleCount:fr,expandedProjectIds:hi,currentVersion:Ct?.server.version??null,platform:Qi,arch:$t?.arch??null,onSidebarResizeStart:mn,setSidebarOpen:De,setView:u,setSelectedAppId:M,setSelectedProjectId:H,setSelectedSessionId:ae,setSearchOpen:We,setSectionMenuOpen:tt,setSettingsSection:le,onTogglePinnedCollapsed:te,onToggleCloudProjectsCollapsed:Ke,onToggleChatsCollapsed:Ge,onToggleSavedForLaterCollapsed:yt,setArchivedChatsOpen:Ze,setCloudProjectsExpanded:at,setChatRowsVisibleCount:Te,beginNewChat:na,beginProjectChat:rl,dockSessionRight:Hi,selectTeamThread:Ce=>{u("team"),ct.selectThread(Ce)},openTeamDm:Ce=>{u("team"),ct.openDm(Ce)},toggleSessionPinned:Xs,toggleProjectPinned:Li,toggleSessionSavedForLater:od,openSidebarFile:ll,setSidebarFileStatus:(Ce,ot)=>{nn(Ce,ot)},archiveSession:Ys,restoreSession:nd,renameSession:ad,removeProject:xd,expandProject:Ia,toggleProjectExpanded:gi,startPinnedDrag:_r,clearSidebarDrag:oo,previewPinnedDrop:Aa,commitPinnedDrop:Ai,commitPinnedPreviewDrop:Pi,startTaskDrag:Oo,clearTaskDrag:yr,previewTaskDrop:Sr,commitTaskDrop:xr,commitTaskPreviewDrop:Ri},topBar:{sidebarOpen:re,title:jt,backAction:de.backAction,breadcrumbs:de.breadcrumbs,conversationId:X==="chat"?K:null,workspaceName:sr,workspaceId:Io,busy:se,workspaceState:Ha,workspaceKind:ir,selectedApp:tn??Pn,selectedProject:bt,workspaceDiff:No,managedWorkspace:Mi,workspaceBusy:ro,defaultTeamId:_a.defaultTeamId,showDiffControls:X==="chat"&&ve==="development",diffPanelOpen:ke,terminalOpen:Re,rightSidebarAvailable:dl,rightSidebarOpen:X==="scheduled"?n:ke,onToggleDiffPanel:ol,onToggleRightSidebar:X==="scheduled"?()=>a(Ce=>!Ce):X==="team"&&wo?rr:ol,onOpenSearch:()=>{tt(null),We(!0)},onToggleTerminal:()=>ue(Ce=>!Ce),onRunTerminalCommand:Ce=>{p({id:Date.now(),scope:cl,command:Ce}),ue(!0)},onWorkspaceToolAction:Bc,onOpenCommitDialog:qc,onWorkspaceBranchChange:Hc,onWorkspaceBranchCreate:$i,connection:$t,onBootstrap:vn,onOpenSandboxWorkspace:Ui,onShowSidebar:()=>De(!0),onOpenTeamChat:Cd,onDiscoverCommunities:kf,collaborationView:X==="team"||X==="community"?X:null,platform:Qi,showWorkspaceControls:X!=="team"&&X!=="community"&&X!=="labs"&&X!=="scheduled"&&X!=="outputs"&&X!=="projects"&&(ve==="development"||ve==="work"&&!!(bt||St?.localProjectId||St?.cloudProjectId||St?.workspaceKind==="local_project"))},mainPane:{experience:ve,onNewExperienceChange:qe,view:X,teamChat:{currentUserId:ct.currentUserId,members:ct.members,agents:ct.agents,profile:Ct?.profile??null,teamId:ma,teamName:ua?.displayName??null,detail:ct.detail,aiThread:ct.aiThread,agentConversation:ct.agentConversation,loading:ct.loading,busy:ct.busy,error:ct.error,connection:$t,providerSettings:Ct?.providers??null,provider:xn,model:Tn,codexPermissionMode:Ee,codexReasoningEffort:xe,openPondCommandAccessMode:pa,contextWindowStatus:wr,showToast:It,onProviderChange:Zs,onModelChange:_,onCodexPermissionModeChange:lr,onCodexReasoningEffortChange:cr,onOpenPondCommandAccessModeChange:dr,onOpenProviderSettings:()=>{le("providers"),u("settings"),Qt({kind:"settings",section:"providers"})},onSendMessage:ct.sendMessage,onPublishProfileAgent:mi,onOpenAiThread:async Ce=>{await ct.openAiThread(Ce),Y("chat"),oe(!0)},onOpenAgentConversation:async Ce=>{await ct.openAgentConversation(Ce),Y("chat"),oe(!0)},onCloseAiThread:()=>oe(!1),onCloseAgentConversation:()=>{ct.closeAgentConversation(),oe(!1)},onSendAgentTurn:ct.sendAgentTurn,onSendAiTurn:ct.sendAiTurn,onStopAiTurn:ct.stopAiTurn,onEditMessage:ct.editMessage,onDeleteMessage:ct.deleteMessage,onRetryMessage:ct.retryMessage,onDismissFailedMessage:ct.dismissFailedMessage,onLoadMoreMessages:ct.loadMoreMessages,onRetryLoad:ct.refresh},community:wa,bootstrap:Ct,runtimeEvents:Eo,chatMessages:gr,pendingUserMessage:K?vt[K]??null:null,contextWindowStatus:wr,goalRuntime:hr,subagentRuntime:Mo,selectedSessionId:K,composerDraftStore:i,mainComposerFocusRequestId:x,labCloseDetailRequestId:de.closeDetailRequestId,labCloseDetailKind:de.closeDetailKind,sideChatTrainingLaunchRequest:dd,onSideChatTrainingLaunchHandled:Ce=>nl(ot=>ot?.id===Ce?null:ot),mentionApps:zn,connectedAppMentions:Xe,profileSkills:wd,selectedMentionAppId:k,busy:se,turnRunning:Ua,activeProvider:xn,activeModel:Tn,codexPermissionMode:Ee,codexReasoningEffort:xe,openPondCommandAccessMode:pa,pendingApproval:yn,activeWorkspaceAppId:pi,activeWorkspaceId:Io,activeWorkspaceKind:ir,projectTarget:Ni,actionCatalog:fi,workspaceTarget:dt,connection:$t,workspaceName:sr,workspaceState:Ha,workspaceDiff:No,workspaceBusy:ro,diffBusy:Ei,forceChatThread:Mt(K),diffPanelOpen:ke,diffPanelExpanded:ee,rightPanelMode:pe,rightPanelTabRequest:z,rightChatPanels:md,runtimeEventStore:pn,nativeSkillSidebar:Bi,extensionSkillSidebar:Vi,workspaceDiffPanelViewState:N,sidebarFileOpenRequest:Yi,sidebarFileBookmarks:_i,onSetSidebarFileStatus:(Ce,ot)=>{nn(Ce,ot)},browserConversationId:qn,terminalScope:cl,terminalTabs:m,terminalCwd:jd,pendingTerminalCommand:l,terminalOpen:Re,onToggleTerminal:()=>ue(Ce=>!Ce),onWorkspaceDiffPanelViewStateChange:hn,training:Yt,trainingSessions:ft,trainingChatHandoff:Si,trainingDetailTasksetId:S,onTrainingDetailTasksetIdChange:y,onTrainingChatTaskSelect:xi,onTrainingChatHandoffDismiss:yi,onOpenSession:kn,onExperienceHandoff:il,cloudProjects:Ct?.cloudProjects??[],projects:kd,projectsAccountBaseUrl:fn?.baseUrl??fn?.activeProfile?.baseUrl??null,projectsTeamName:ua?.displayName??null,projectTaskCounts:_d,onNewCloudProject:sd,onNewProjectTask:Ce=>rl(Ce.id),onToggleProjectPinned:Li,onUploadLocalProject:zi,chatHistoryHasMore:$d,chatHistoryLoading:rt,onDiffPanelResizeStart:ka,onToggleDiffPanelExpanded:()=>Q(Ce=>!Ce),onShowDiffPanel:tl,onShowBrowserPanel:ld,onShowFilesPanel:()=>fd("files"),onShowGoalSidebarTab:cd,onShowTrainingDraftPanel:()=>{Y("training"),oe(!0)},onShowRightChatPanel:pd,onAddRightChat:()=>Hi(null),onOpenRightChatForSession:(Ce,ot)=>{const _t=ot??ft.find(ha=>ha.id===Ce)??null;_t&&Hi(_t,{preserveView:!0})},onLabDetailOpenChange:de.onDetailOpenChange,scheduledDetailOpen:n,onScheduledDetailOpenChange:a,onTerminalTabsChange:f,onCloseRightChatPanel:ud,onCloseNativeSkillSidebar:Ad,onActivateRightChatPanel:al,onRightChatModelChange:hd,onRightChatPromptChange:gd,onRightChatScrollStateChange:vd,onRightChatProviderChange:bd,onSubmitRightChat:io,onStopRightChat:Ce=>Di(Ce),onCloseTerminal:()=>ue(!1),onLoadMoreChatHistory:mr,canSyncWorkspace:ji,startMessage:da,onPayload:vn,onError:Pt,setView:u,onOpenProfileSettings:yd,onOpenProviderSettings:()=>{le("providers"),u("settings"),Qt({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{le("training"),u("settings"),Qt({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{le("dataset-storage"),u("settings"),Qt({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Zs,changeProjectTarget:Yn,changeWorkspaceTarget:Qs,setDraftProvider:Z,setDraftModel:_,onBeginNewChatWithModel:vi,changeCodexPermissionMode:lr,changeCodexReasoningEffort:cr,changeOpenPondCommandAccessMode:dr,resolveApproval:bi,answerCreateImproveQuestion:Kc,applyCreateImproveCandidate:Gc,approveCreateImproveRun:Zc,cancelCreateImproveRun:Jc,openCreateImprovePullRequest:Yc,reconcileCreateImprovePullRequest:Xc,rejectCreateImproveCandidate:Js,pauseCreateImproveRun:Qc,resumeCreateImproveRun:ed,reviseCreateImproveRun:td,setMentionedAppId:R,showToast:It,onSaveTaskDraft:$o,sendPrompt:id,stopTurn:Di,syncWorkspaceLocally:Wc,refreshWorkspaceDiff:Jn},cloudSetup:{state:A,onClose:()=>D(null),onOpenBrowserUrl:el,onStart:()=>{rd()}},projectConfirm:{state:P,onResolve:j},lazyPanels:{activeSessions:no,branchDialogName:me,branchDialogOpen:G,commitDialogOpen:Be,commitDraft:U,commitIncludeUnstaged:Ne,commitMessage:He,commitNextStep:E,canPublishOpenPondProject:Oi,connection:$t,expandProject:Ia,newProjectBusy:st,newProjectDialogOpen:Ie,newProjectDirectory:_a.defaultNewProjectDirectory,newProjectMode:$e,newProjectName:Je,newProjectPath:et,projectRows:Ti,query:T,searchOpen:F,visibleWorkspaceDiff:No,visibleWorkspaceState:Ha,workspaceBusy:ro,appDispatch:s,beginNewChat:()=>na(null),openDefaultsSettingsFromBranchDialog:Gs,setBranchDialogName:sn,setBranchDialogOpen:bn,setCommitDialogOpen:Ye,setCommitDraft:gn,setCommitIncludeUnstaged:ut,setCommitMessage:Le,setCommitNextStep:Gt,setNewProjectDialogOpen:ze,setNewProjectName:Pe,setNewProjectPath:Oe,setPrompt:O,setQuery:he,setSearchOpen:We,submitCommitDialog:Fc,submitCreateWorkspaceBranch:Vc,submitNewProjectDialog:Uc},toast:{toast:W,onDismiss:()=>s({type:"field",key:"toast",value:null})}})})}const Lr=new Map,$l=new Map;function Am(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(r=>r.isActive)??null,n=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",a=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"";return[n,a,e.apiBaseUrl??"",e.chatApiBaseUrl??""].join("|")}function ZH(e){const t=e?.trim();if(!t)return null;const n=Lr.get(t);return n?.updatedAt?n.organizations:null}function JH(e,t){const n=e?.trim();if(n){Lr.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of $l.get(n)??[])a()}}function YH(e,t){const n=e?.trim();if(!n)return()=>{};const a=$l.get(n)??new Set;return a.add(t),$l.set(n,a),()=>{a.delete(t),a.size===0&&$l.delete(n)}}function Ag(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Lr.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(r=>(JH(t,r),r)).catch(r=>{const i=Lr.get(t);throw i?.promise===a&&Lr.set(t,{organizations:i.organizations,promise:null,updatedAt:i.updatedAt}),r});return Lr.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const tW="openpond.config.json";function nW(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function Wx(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function Tu(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function aW(e,t=null){const n=QH(e.openFilePaths.map(r=>Tg(r,t)).filter(Boolean)),a=e.selectedPath&&Tg(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function Pg(e,t){return e.activeTab===t.activeTab&&e.selectedPath===t.selectedPath&&e.openFilePaths.length===t.openFilePaths.length&&e.openFilePaths.every((n,a)=>n===t.openFilePaths[a])}function Tg(e,t=null){let n=XH(e);const a=t?.trim().replace(/\\/g,"/").replace(/\/+$/,"");if(!a)return n;if(n===a)return"";n.startsWith(`${a}/`)&&(n=n.slice(a.length+1));const r=a.split("/").filter(Boolean).at(-1);return r&&n.startsWith(`${r}/`)&&(n=n.slice(r.length+1)),n}function oW(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function rW(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function iW(e,t){const n=Eg(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const r=Eg(a);return!!(r&&r.startsWith(`${n}/`))})}function sW(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function lW(e){return/\.(?:doc|docx)$/i.test(e)}function XH(e){let t=e.trim().replace(/^['"`]+|['"`]+$/g,"");if(/^file:\/\//i.test(t))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.replace(/^file:\/\//i,"")}return t.replace(/\\/g,"/").replace(/^\.\/+/,"")}function QH(e){return Array.from(new Set(e))}function Eg(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function eq(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(l=>l.isActive)??null,n=e.profile?.id?.trim()??"",a=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",r=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",i=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,r,i,s].join("|")}function Kx(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function tq(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function Mc(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,r=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||Kx(a),name:t.name||a,displayName:a,role:t.role==="owner"||t.role==="admin"||t.role==="member"?t.role:"member",workspaceKind:t.workspaceKind==="personal"||t.workspaceKind==="shared"?t.workspaceKind:r?"personal":"shared",status:t.status==="disabled"||t.status==="archived"?t.status:"active",kind:t.kind==="personal_default"||t.kind==="managed_client"||t.kind==="team"?t.kind:void 0,isPersonalDefault:r,isManagedClient:t.isManagedClient===!0||t.kind==="managed_client",primaryContactEmail:t.primaryContactEmail??null,customDomain:t.customDomain??null,planKey:typeof t.planKey=="string"?t.planKey:null,effectiveAccessState:t.effectiveAccessState==="checkout_pending"||t.effectiveAccessState==="active"||t.effectiveAccessState==="grace"||t.effectiveAccessState==="suspended"||t.effectiveAccessState==="cancelling"||t.effectiveAccessState==="cancelled"?t.effectiveAccessState:null,canManageBilling:t.canManageBilling===!0||t.role==="owner",createdAt:t.createdAt??"",updatedAt:t.updatedAt??""}}function nq(e){return e.find(t=>t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default")??e.find(t=>t.name.trim().toLowerCase()==="default")??e.find(t=>t.isManagedClient!==!0&&t.kind!=="managed_client")??e[0]??null}function aq(e,t){const n=e.filter(r=>r.status==="active"&&r.workspaceKind==="shared"),a=t?.trim()??"";if(a){const r=n.find(i=>i.teamId===a);if(r)return r}return n.find(r=>r.role==="owner")??n.find(r=>r.role==="admin")??n[0]??null}function oq(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function rq({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const iq=[{value:"action:new-local-project",label:"New local project",detail:"Create a new project folder on this machine",kind:"action"},{value:"action:add-local-project",label:"Use existing folder",detail:"Choose a folder on this machine",kind:"action"},{value:"action:add-local-project-path",label:"Use existing folder path",detail:"Enter a local folder path manually",kind:"action"},{value:"action:new-cloud-project",label:"New cloud project",detail:"Create a project in OpenPond Cloud",kind:"action"},{value:"action:create-cloud-environment",label:"Create cloud environment",detail:"Set up compute for a cloud project",kind:"action"}];function sq(...e){return oq(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function lq(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return sq(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function cq({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:r,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:p,selectedSessionLinkedProject:m}){const f=l?.workspaceKind==="local_project"?l.workspaceId??null:m?.id??null,S=Mt(p)&&!l,y=l?$a(l.workspaceKind):!1,k=Da(l),R=l?VH(l):!1,A=l?.cwd&&(!y||k)?Gv(l.cwd):null,D=e?.providers??null,z=sa(s,e?.cloudProjects??[]),N=rq({draftProvider:n,hasSelectedCloudProject:!!i,selectedSessionHybridWorkspace:k}),x=ko(N,t,D),I=Qn(e?.preferences),P=S?null:l?y?l.workspaceKind??"sandbox":R?"sandbox":f?"local_project":l.workspaceKind??(l.appId?"sandbox_app":A?"local_project":null):i?"sandbox":s?"local_project":r?"sandbox_app":null,j=S?null:l?y&&!k||R?null:f||(l.workspaceId??l.appId??A):i?null:s?.id??r,T=S?null:l?y?l.workspaceId??null:R?null:f??l.workspaceId??l.appId??A:i?null:s?.id??r,F=e?.account??null,q=!e||F?.state==="loading"||F?.state==="switching",$=!q&&F?.state==="signed_out",V=q?null:$?"Sign in":F?.label??F?.activeProfile?.handle??"Account",re=lq(F),X=re?`Welcome, ${re}`:"Welcome",we=l?.workspaceName??l?.appName??i?.name??s?.name??a?.name??null,ye=$a(P)?"cloud":"local",K=s?.name??m?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",Ee=(ye==="cloud"?we:null)??i?.name??z?.name??s?.name??"Cloud workspace",xe=!!(i?.id||z?.id||l?.cloudProjectId||ye==="cloud");return{account:F,accountLabel:V,accountPending:q,accountSignedOut:$,activeModel:x,activeProvider:N,activeWorkspaceAppId:j,activeWorkspaceId:T,activeWorkspaceKind:P,activeWorkspaceLocation:ye,appDefaults:I,cloudLinked:xe,cloudTargetName:Ee,localTargetName:K,selectedCodexHistoryPending:S,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:A,selectedSessionPendingCloudStart:R,selectedSessionProjectId:f,startMessage:X,workspaceName:we}}function dq({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:r,cloudLinked:i,selectedCloudProject:s,selectedProject:l,selectedSession:p,pendingWorkspaceTarget:m,workspaceStates:f,workspaceBusy:S}){const y=sa(l,a?.cloudProjects??[]),R=!!!l?.linkedSandboxProject?.projectId||!!y,A=g.useMemo(()=>{const T=(a?.localProjects??[]).map(V=>({value:`local:${V.id}`,label:V.name,detail:V.workspacePath,kind:"local"})),F=(a?.cloudProjects??[]).map(V=>({value:`cloud:${V.id}`,label:V.name,detail:V.organizationName??V.sourceLabel??"OpenPond Cloud",kind:"cloud"})),q=l?`local:${l.id}`:s?`cloud:${s.id}`:"none",$=[...T,...F].find(V=>V.value===q)??null;return{value:q,label:$?.label??"Select Project",detail:$?.detail??"Choose a project for local or cloud work",busy:S||r,options:[...T,...F,...iq,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,r,s,l,S]),D=!!(i||l),z=!!(s?.id||y?.id||p?.cloudProjectId||Da(p)),N=l?f[l.id]??null:null,x=ix(N,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??p?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&R?!!l.linkedSandboxProject.lastUploadedCommit||!N?.headCommit:!0}),I=sx(l,s??y,N,{cloudLinkTrusted:R}),P=sz(l,N,{cloudLinkTrusted:R}),j=g.useMemo(()=>{const T={value:"local",label:l?"Local checkout":"Local",detail:l?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:l?x:"App-managed local task workspace",disabled:!1,disabledReason:null},F={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:z?I:"upload required",disabled:e||t||!z,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},q={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:l||s?I:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},$={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:P,disabled:e||t||!l,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},V=n==="cloud"?"local":"cloud",re=V==="local"?T:q;let X=n==="cloud"?q:T;return m==="cloud"?X=q:m==="local"?X=T:(Da(p)||m==="hybrid")&&(X=F),{value:X.value,label:X.label,detail:X.stateNote||X.detail,busy:S,action:{...re,label:V==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?$:null,options:[T,F,q]}},[n,e,t,i,D,I,z,x,m,l,p,P,S]);return{projectTarget:A,workspaceTarget:j}}function In(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function Gx(e){return In(e.name||e.gitRepo||e.id)}function cW(e){return`@${Gx(e)}`}function Zx(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>In(t[1]??"")).filter(Boolean)}function uq(e,t){const n=Zx(e);if(n.length===0)return!1;const a=new Set([In(t.id),Gx(t),t.gitRepo?In(t.gitRepo):""].filter(Boolean));return n.some(r=>a.has(r))}function Jx(e){return e.filter(t=>t.sandbox)}function mq(e,t){const n=Zx(e);if(n.length===0)return null;const a=new Map;for(const r of n){const i=t.find(s=>{const l=In(s.id),p=In(s.name),m=s.gitRepo?In(s.gitRepo):"";return r===l||r===p||r===m});i&&a.set(i.id,i)}return a.size===1?Array.from(a.values())[0]??null:null}function dW(e,t){const n=e.slice(0,t),a=n.match(/(?:^|\s)@([A-Za-z0-9_-]*)$/);if(!a||typeof a.index!="number")return null;const r=n.slice(a.index).indexOf("@");return r<0?null:{query:In(a[1]??""),start:a.index+r}}function pq(e){return new Set(e.map(t=>t.id))}function Mg(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function fq({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:r,sessions:i}){const s=g.useMemo(()=>e?.apps.find($=>$.id===r)??null,[e?.apps,r]),l=g.useMemo(()=>new Map((e?.localProjects??[]).map($=>[$.id,$])),[e?.localProjects]),p=g.useMemo(()=>new Map((e?.cloudProjects??[]).map($=>[$.id,$])),[e?.cloudProjects]),m=g.useMemo(()=>QS(n),[n]),f=g.useMemo(()=>m?.kind==="local"?l.get(m.id)??null:null,[l,m]),S=g.useMemo(()=>m?.kind==="cloud"?p.get(m.id)??null:null,[p,m]),y=g.useMemo(()=>pq(e?.apps??[]),[e?.apps]),k=g.useMemo(()=>Jx(e?.apps??[]),[e?.apps]),R=g.useMemo(()=>{const $=[];for(const V of e?.localProjects??[]){const re=Mg(V,y);re&&$.push([re.appId,V.id])}return new Map($)},[e?.localProjects,y]),A=g.useMemo(()=>new Set((e?.localProjects??[]).map($=>$.id)),[e?.localProjects]),D=g.useMemo(()=>vx(e?.localProjects??[]),[e?.localProjects]),z=g.useRef([]),N=g.useMemo(()=>hq(i,t,z.current),[t,i]),x=g.useMemo(()=>N.find($=>$.id===a)??null,[N,a]),I=g.useMemo(()=>{if(!x)return null;if(x.localProjectId)return l.get(x.localProjectId)??null;if(x.workspaceKind==="local_project")return x.workspaceId?l.get(x.workspaceId)??null:null;const $=nH(x,A,D);if($)return l.get($)??null;if(!x.appId)return null;const V=R.get(x.appId);return V?l.get(V)??null:null},[R,l,A,D,x]),P=g.useMemo(()=>x?.cloudProjectId?p.get(x.cloudProjectId)??null:null,[p,x]),j=f??I,T=S??P,F=g.useMemo(()=>Mg(j,y),[y,j]),q=g.useMemo(()=>F?e?.apps.find($=>$.id===F.appId)??null:null,[e?.apps,F]);return{cloudProjectById:p,currentAppIds:y,linkedProjectByAppId:R,localProjectById:l,mentionableSandboxApps:k,selectedApp:s,selectedCloudProject:T,selectedProject:j,selectedProjectLinkedApp:q,selectedProjectLinkedOpenPondApp:F,selectedSession:x,selectedSessionLinkedProject:I,sidebarSessions:N}}function hq(e,t,n){const a=new Map;for(const m of e){const f=jg(m);a.set(f,m)}for(const m of t){const f=jg(m),S=a.get(f);a.set(f,S?gq(S,m):m)}const r=Array.from(a.entries());if(!n)return r.sort((m,f)=>Og(m[1],f[1])).map(m=>m[1]);const i=[],s=new Set;for(const m of n){const f=a.get(m);f&&(i.push([m,f]),s.add(m))}const p=[...r.filter(([m])=>!s.has(m)).sort((m,f)=>Og(m[1],f[1])),...i];return n.splice(0,n.length,...p.map(([m])=>m)),p.map(m=>m[1])}function gq(e,t){return{...e,metadata:bq(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:vq(e.updatedAt,t.updatedAt)}}function jg(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function Og(e,t){const n=Ng(t)-Ng(e);return n!==0?n:e.title.localeCompare(t.title)}function bq(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function vq(e,t){const n=Date.parse(e);if(!Number.isFinite(n))return t;const a=Date.parse(t);return Number.isFinite(a)&&a>n?t:e}function Ng(e){const t=Date.parse(e.updatedAt);if(Number.isFinite(t))return t;const n=Date.parse(e.createdAt);return Number.isFinite(n)?n:0}function yq(e){return!!(e&&$a(e.workspaceKind)&&!Da(e)&&e.provider!=="openpond")}function Sq(e,t){const n=nx(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function xq({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:r,linkedProjectByAppId:i,providerSettings:s,selectedAppId:l,selectedSession:p,selectedSessionId:m,selectedSessionProjectId:f,setDiffPanelExpanded:S,setDraftModel:y,setDraftProvider:k,setError:R,setSelectedAppId:A,setSelectedProjectId:D,setSessions:z,setTerminalOpen:N,toast:x}){const I=g.useRef(null);g.useEffect(()=>{if(!l)return;const P=f??(m?null:i.get(l)??null);if(!P)return;const j=ht("local",P);A(null),D(j),r(j)},[r,i,l,m,f,A,D]),g.useEffect(()=>{if(!x||x.persistent)return;const P=window.setTimeout(()=>{n({type:"clearToast",toastId:x.id})},x.durationMs??(x.tone==="error"?7e3:3500));return()=>window.clearTimeout(P)},[n,x]),g.useEffect(()=>{function P(j){(j.metaKey||j.ctrlKey)&&j.key==="`"&&(j.preventDefault(),N(T=>!T))}return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[N]),g.useEffect(()=>{S(!1)},[e,t,S]),g.useEffect(()=>{if(!m){I.current=null;return}if(!p||p.id!==m)return;const P=Sq(p,s);if(I.current===P)return;I.current=P;const j=nx(p,s);k(j.provider),y(j.model)},[s,p,m,y,k]),g.useEffect(()=>{!a||!p||!yq(p)||J.patchSession(a,p.id,{provider:"openpond"}).then(P=>{z(j=>j.map(T=>T.id===P.id?P:T)),k("openpond"),y(j=>ko("openpond",j))}).catch(P=>{R(P instanceof Error?P.message:String(P))})},[a,p,y,k,R,z])}function kq({connection:e,setError:t}){return g.useCallback(async(n,a)=>{if(!e){const r=new Error("OpenPond App server is not connected.");throw t(r.message),r}t(null);try{await J.resolveApproval(e,n,{decision:a})}catch(r){const i=r instanceof Error?r.message:String(r);throw t(i),r}},[e,t])}function _q({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:r,pinnedProjects:i,projectRows:s,visibleProjectRows:l}){const p=g.useMemo(()=>UL(a,r),[a,r]),m=g.useMemo(()=>kx({provider:e,snapshot:n,preferences:t}),[e,t,n]),f=g.useMemo(()=>Array.from(new Set([...i,...l].filter(Qp).map(y=>y.project.id))),[i,l]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:m,pinnedRows:p,sidebarWorkspaceAppIds:f}}function wq({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:r,setMentionedAppId:i}){return g.useCallback((s=null)=>{r?.();const l=s?.id?n.get(s.id)??null:null;if(l){const p=ht("local",l);i(null),e({type:"selectProject",projectId:p}),t(p),a();return}i(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,r,a,i])}const Yx={slack:["slack"],microsoft_teams:["teams","microsoft-teams","microsoft_teams"],github:["github","gh"],google:["google","drive","google-drive","docs"],turnkey:["turnkey","agent-wallet","agent_wallet","wallet"],x:["x","twitter"],mcp:["mcp","openpond-mcp"]};function uW(e){return`@${e.token}`}function Iq(e){return`@${Tq(e)}`}function Cq(e){const t=new Map;for(const n of e){if(!n.connected||n.statusSource!=="integration_connection")continue;const a=t.get(n.providerFamily)??[];a.push(n),t.set(n.providerFamily,a)}return Array.from(t.entries()).map(([n,a])=>{const r=a[0],i=jr(a.flatMap(S=>S.capabilities.map(y=>y.id))),s=jr(a.flatMap(S=>S.capabilityLabels)),l=jr(a.flatMap(S=>S.connections.map(y=>y.id).filter(Mq))),p=jr(a.map(S=>S.id)),m=jr(a.map(S=>S.setupSurface)),f=Pq(n);return{provider:n,label:r.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):r.description,token:f,tokens:Aq(a),ref:{kind:"integration",provider:n,appIds:p,setupSurfaces:m,...l.length>0?{connectionIds:l}:{},...i.length>0?{capabilities:i}:{}}}})}function mW(e,t){const n=In(t);return e.filter(a=>n?a.tokens.some(r=>r.includes(n)):!0).slice(0,8)}function Rq(e,t){const n=Eq(e);if(n.length===0)return[];const a=new Map;for(const r of n){const i=t.find(s=>s.tokens.includes(r));i&&a.set(i.provider,i)}return Array.from(a.values())}function pW(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const r=a[1]??"",i=In(r);if(!i)continue;const s=t.find(S=>S.tokens.includes(i));if(!s)continue;const p=(a[0]??"").indexOf("@");if(p<0||typeof a.index!="number")continue;const m=a.index+p,f=`@${r}`;n.push({detail:s.detail,displayText:Iq(s),end:m+f.length,label:s.label,provider:s.provider,start:m,text:f})}return n}function Aq(e){return jr(e.flatMap(t=>[...Yx[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(In).filter(Boolean))}function Pq(e){return In(Yx[e][0]??e)}function Tq(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function Eq(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>In(t[1]??"")).filter(Boolean)}function jr(e){return Array.from(new Set(e))}function Mq(e){return typeof e=="string"&&e.length>0}function jq({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:r,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:p}){const m=g.useMemo(()=>{const R=new Map;for(const A of e?.cloudProjects??[]){const D=R.get(A.teamId)??[];D.push(A.id),R.set(A.teamId,D)}return R},[e?.cloudProjects]),S=!!(l||r||s||i)?[]:n,y=g.useMemo(()=>Cq(t),[t]),k=g.useMemo(()=>MH(a,p),[a,p]);return{chatMentionApps:S,cloudProjectIdsByTeam:m,connectedAppMentions:y,pendingApproval:k}}const Xx="openpond.codexPermissionMode",Qx="openpond.codexReasoningEffort";function Ws(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function Oq(e){return e==="default"||e==="auto-review"||e==="full-access"?e:null}function Nq(e){return e==="low"||e==="medium"||e==="high"||e==="xhigh"?e:null}function ek(e=Ws()){if(!e)return{};const t=Oq(e.getItem(Xx)),n=Nq(e.getItem(Qx));return{...t?{codexPermissionMode:t}:{},...n?{codexReasoningEffort:n}:{}}}function $q(e,t=Ws()){try{t?.setItem(Xx,e)}catch{}}function Dq(e,t=Ws()){try{t?.setItem(Qx,e)}catch{}}function $g(e,t=Ws()){const n=Qn(e),a=ek(t);return{codexPermissionMode:a.codexPermissionMode??n.codexPermissionMode??uc,codexReasoningEffort:a.codexReasoningEffort??n.codexReasoningEffort??mc}}function Lq(e,t=Ws()){const n=Qn(e),a=ek(t),r={};return a.codexPermissionMode&&a.codexPermissionMode!==n.codexPermissionMode&&(r.codexPermissionMode=a.codexPermissionMode),a.codexReasoningEffort&&a.codexReasoningEffort!==n.codexReasoningEffort&&(r.codexReasoningEffort=a.codexReasoningEffort),r}function zq({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:r}){const i=g.useCallback(l=>{n(l),$q(l),e&&J.savePreferences(e,{codexPermissionMode:l}).then(()=>{t(p=>p&&{...p,preferences:{...p.preferences,codexPermissionMode:l}})}).catch(p=>{r(p instanceof Error?p.message:String(p))})},[e,t,n,r]),s=g.useCallback(l=>{a(l),Dq(l),e&&J.savePreferences(e,{codexReasoningEffort:l}).then(()=>{t(p=>p&&{...p,preferences:{...p.preferences,codexReasoningEffort:l}})}).catch(p=>{r(p instanceof Error?p.message:String(p))})},[e,t,a,r]);return{changeCodexPermissionMode:i,changeCodexReasoningEffort:s}}const Uq=6e4;function cf(e,t){if(!e)return t;const n=qq(e.updatedAt,t.updatedAt)?{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,status:e.status,updatedAt:e.updatedAt}:t;return nk(e,n)?e:n}function Hq(e,t){const n=cf(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&nk(e,a)?e:a}function ls(e,t){let n=!1,a=!1;const r=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=cf(i,t);return s!==i&&(a=!0),s});return n?a?r:e:[t,...e]}function jc(e,t){let n=!1,a=!1;const r=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=Hq(i,t);return s!==i&&(a=!0),s});return n?a?r:e:[t,...e]}function Pm(e,t,n,a=Date.now()){const r=new Map(e.map(i=>[i.id,i]));return t.map(i=>{const s=r.get(i.id);if(s&&n){const l=Fq(s,i,n,a);if(l)return l}return cf(s,i)})}function Dg(e,t,n,a=Date.now()){const r=new Map(e.map(m=>[m.id,m])),i=new Map(Pm(e,t,n,a).map(m=>[m.id,m])),s=new Set(r.keys()),l=t.filter(m=>!s.has(m.id)).map(m=>i.get(m.id)??m),p=e.map(m=>{const f=i.get(m.id);return f||(tk(m,t)?m:null)}).filter(m=>!!m);return[...l,...p]}function tk(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=Bq(t);return a===null||n>=a}function Lg(e,t,n,a=Date.now()){const r=new Map(t.map(i=>[i.id,i]));for(const i of n){const s=r.get(i.id);s&&(ak(s,i)||(e[i.id]=a))}}function qq(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function nk(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Bq(e){let t=null;for(const n of e){const a=Date.parse(n.updatedAt);Number.isFinite(a)&&(t=t===null?a:Math.max(t,a))}return t}function Fq(e,t,n,a){const r=n[t.id];return r===void 0?null:a-r>Uq||ak(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function ak(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const ok=800,Vq=5e3,zg=5e4,Wq=16,Kq=3e4,Fn=new Map;function Gq(e,t){return Fn.get(ik(e,t))?.payload??null}async function rk(e,t,n={}){const a=ik(e,t),r=Fn.get(a),i=n.limit??ok,s=n.tail??!0;if(r?.promise)return r.promise;if(!n.force&&s&&r?.payload&&Date.now()-r.fetchedAt<=Kq)return Ug(a,r),r.payload;const l=!!(n.force&&s&&r?.payload),p=l?r?.payload?.events.at(-1)?.id:void 0,m=J.codexHistoryThreadIncremental(e,t,{afterEventId:p,limit:i,revision:l?r?.revision:void 0,tail:s}).then(f=>{const S=Fn.get(a)?.payload??r?.payload;if(f.unchanged){if(!S)throw new Error("Codex history revision matched without a cached thread.");return Fn.set(a,{fetchedAt:Date.now(),payload:S,revision:f.revision}),Ug(a,Fn.get(a)),S}const y={session:f.session,events:f.events},k=s&&S&&!f.reset?{...y,events:Zq(S.events,y.events)}:y;return Fn.set(a,{fetchedAt:Date.now(),payload:k,revision:f.revision}),Hg(),k}).catch(f=>{throw Fn.get(a)?.promise===m&&Fn.delete(a),f});return Fn.set(a,{fetchedAt:r?.fetchedAt??0,payload:r?.payload,promise:m,revision:r?.revision}),Hg(),m}function ik(e,t){return`${e.serverUrl}
132
- ${e.token}
133
- ${t}`}function Ug(e,t){Fn.delete(e),Fn.set(e,t)}function Hg(){for(;Fn.size>Wq;){const e=Fn.keys().next().value;if(!e)return;Fn.delete(e)}}function Zq(e,t){const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values())}const Jq=500,Yq=2500,Xq=15e3;function Qq(e){return e.active?Jq:e.surface==="thread"?Yq:Xq}function df(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function eB(e={}){const t={cachedPayload:e.cachedPayload??Gq,clearTimer:e.clearTimer??(m=>globalThis.clearTimeout(m)),loadPayload:e.loadPayload??rk,now:e.now??Date.now,setTimer:e.setTimer??((m,f)=>globalThis.setTimeout(m,f))},n=new Map;let a=1;function r(m){const f=nB(m.connection,m.sessionId);let S=n.get(f);S||(S={connection:m.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(m.connection,m.sessionId),nextRefreshAt:null,sessionId:m.sessionId,subscribers:new Map,timer:null},n.set(f,S));const y=a++;return S.subscribers.set(y,m),S.latestPayload&&m.onPayload(S.latestPayload),i(S,0),()=>{const k=n.get(f);if(k){if(k.subscribers.delete(y),k.subscribers.size>0){i(k,l(k));return}k.disposed=!0,p(k),n.delete(f)}}}function i(m,f){if(m.disposed||m.subscribers.size===0||m.inFlight)return;const S=t.now()+Math.max(0,f);m.timer&&m.nextRefreshAt!==null&&m.nextRefreshAt<=S||(p(m),m.nextRefreshAt=S,m.timer=t.setTimer(()=>{m.timer=null,m.nextRefreshAt=null,s(m)},Math.max(0,f)))}async function s(m){if(m.disposed||m.subscribers.size===0||m.inFlight)return;const f=t.loadPayload(m.connection,m.sessionId,{force:!!m.latestPayload});m.inFlight=f;try{const S=await f;if(m.disposed||S===m.latestPayload)return;m.latestPayload=S;for(const y of m.subscribers.values())y.onPayload(S)}catch(S){if(m.disposed)return;for(const y of m.subscribers.values())y.onError?.(S)}finally{m.inFlight===f&&(m.inFlight=null),m.disposed||i(m,l(m))}}function l(m){const f=[...m.subscribers.values()],S=f.some(k=>k.locallyActive||k.reportedActive)||m.latestPayload?.session.status==="active"||sf(m.latestPayload?.events??[])?.tone==="active",y=f.some(k=>k.surface==="thread")?"thread":"sidebar";return Qq({active:S,surface:y})}function p(m){m.timer&&t.clearTimer(m.timer),m.timer=null,m.nextRefreshAt=null}return{subscribe:r}}const tB=eB();function uf(e){return tB.subscribe(e)}function nB(e,t){return`${e.serverUrl}
134
- ${e.token}
135
- ${t}`}function aB({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:r,setError:i}){const[s,l]=g.useState({events:[],sessionId:null}),p=Mt(t)?t:null,m=p&&s.sessionId===p?s.events:[],f=g.useCallback(S=>{l(y=>{if(!p)return{events:[],sessionId:null};const k=y.sessionId===p?y.events:[];return{events:typeof S=="function"?S(k):S,sessionId:p}})},[p]);return g.useEffect(()=>{if(!e||!p){l(k=>k.sessionId===null&&k.events.length===0?k:{events:[],sessionId:null});return}i(k=>k==="Session not found"?null:k);const S=n;return uf({connection:e,locallyActive:S,onError:k=>i(k instanceof Error?k.message:String(k)),onPayload:k=>{const R=df(k,S);l(A=>A.sessionId!==p?{events:R.events,sessionId:p}:{events:Wa(A.events,R.events),sessionId:p}),i(A=>A==="Session not found"?null:A),r(A=>jc(A,R.session))},reportedActive:a==="active",sessionId:p,surface:"thread"})},[e,p,n,a,r,i]),{codexHistoryEvents:m,setCodexHistoryEvents:f}}function sk(e){const t=e.currentTarget,n=t.getBoundingClientRect(),a=t.cloneNode(!0);a.classList.add("sidebar-drag-preview"),a.style.width=`${n.width}px`,a.style.height=`${n.height}px`,a.style.position="fixed",a.style.top="-1000px",a.style.left="-1000px",a.style.pointerEvents="none",a.style.boxSizing="border-box",a.style.maxWidth="none",document.body.appendChild(a),e.dataTransfer.setDragImage(a,e.clientX-n.left,e.clientY-n.top),window.setTimeout(()=>a.remove(),0)}function oB({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:r,setCodexHistorySessions:i,setSessions:s,sidebarFileBookmarks:l,setSidebarFileBookmarks:p,setError:m}){const[f,S]=g.useState(null),[y,k]=g.useState(null),R=g.useRef(null),A=g.useRef(null);function D(j,T){j.dataTransfer.effectAllowed="move",j.dataTransfer.setData("text/plain",`${T.type}:${T.id}`),sk(j);const F=a.map(q=>q.key);R.current=T,A.current=F,S(T),k(F)}function z(){R.current=null,A.current=null,S(null),k(null)}function N(j,T){const F=R.current;if(!F)return;const q=Gl(j),$=A.current??a.map(re=>re.key),V=Zl($,Vo(F),Vo(T),q);rg($,V)||(A.current=V,k(V))}function x(j){if(!e)return;const T=a.map(ye=>ye.key),F=new Set(T),q=[...j.filter(ye=>F.has(ye)),...T.filter(ye=>!j.includes(ye))];if(rg(T,q))return;const $=t,V=new Map(n.map(ye=>[ye.id,ye])),re=l,X=new Map(a.map(ye=>[ye.key,ye]));r(ye=>{const K={...ye};return q.forEach((Ee,xe)=>{const se=X.get(Ee);se?.type==="project"&&(K[se.id]={...K[se.id]??{},pinned:!0,archived:!1,order:xe})}),K});const we=ye=>{const K=new Map(ye.map(se=>[se.id,se])),Ee=q.map((se,ke)=>{const ee=X.get(se),pe=ee?.type==="session"?K.get(ee.id):null;return pe?{...pe,order:ke}:null}).filter(se=>!!se),xe=new Map(Ee.map(se=>[se.id,se]));return ye.map(se=>xe.get(se.id)??se)};s(we),i(we),p(ye=>{const K=new Map;return q.forEach((Ee,xe)=>{const se=X.get(Ee);se?.type==="file"&&K.set(se.id,xe)}),ye.map(Ee=>{const xe=K.get(Ee.id);return xe===void 0?Ee:{...Ee,order:xe}})}),Promise.all(q.map((ye,K)=>{const Ee=X.get(ye);return Ee?Ee.type==="project"?J.patchSidebarAppPreference(e,Ee.id,{pinned:!0,archived:!1,order:K}):Ee.type==="session"?J.patchSession(e,Ee.id,{order:K}):J.patchSidebarFile(e,{workspaceKind:Ee.file.workspaceKind,workspaceId:Ee.file.workspaceId,workspaceName:Ee.file.workspaceName,path:Ee.file.path,status:"pinned",order:K,sourceSessionId:Ee.file.sourceSessionId}):Promise.resolve(null)})).catch(ye=>{m(ye instanceof Error?ye.message:String(ye)),r($);const K=Ee=>Ee.map(xe=>V.get(xe.id)??xe);s(K),i(K),p(re)})}function I(j,T){const F=R.current;if(F){const q=A.current??a.map(V=>V.key),$=Zl(q,Vo(F),Vo(T),Gl(j));x($)}z()}function P(){R.current&&x(A.current??a.map(T=>T.key)),z()}return{dragItem:f,pinnedPreviewKeys:y,startPinnedDrag:D,clearSidebarDrag:z,previewPinnedDrop:N,commitPinnedDrop:I,commitPinnedPreviewDrop:P}}function rB({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:r}){const[i,s]=g.useState(null),[l,p]=g.useState(null),m=g.useRef(null),f=g.useRef(null);function S(z,N){z.dataTransfer.effectAllowed="move",z.dataTransfer.setData("text/plain",`session:${N.sessionId}`),sk(z),m.current=N,f.current=N.visibleSessionIds,s(N.sessionId),p(N.visibleSessionIds)}function y(z,N){const x=m.current;if(!x)return;const I=f.current??x.visibleSessionIds,P=Zl(I,x.sessionId,N,Gl(z));iB(I,P)||(f.current=P,p(P))}function k(){m.current=null,f.current=null,s(null),p(null)}function R(z,N){const x=m.current;if(!x){k();return}const I=f.current??x.visibleSessionIds,P=Zl(I,x.sessionId,N,Gl(z));D(dg(x.allSessionIds,x.visibleSessionIds,P)),k()}function A(){const z=m.current;z&&D(dg(z.allSessionIds,z.visibleSessionIds,f.current??z.visibleSessionIds)),k()}function D(z){const N=new Map(z.map((j,T)=>[j,T])),x=new Map(t.map(j=>[j.id,j.order])),I=z.filter((j,T)=>x.get(j)!==T);if(I.length===0)return;const P=j=>j.map(T=>{const F=N.get(T.id);return F===void 0||F===T.order?T:{...T,order:F}});r(P),n(P),e&&Promise.all(I.map(j=>J.patchSession(e,j,{order:N.get(j)}))).catch(j=>{const T=F=>F.map(q=>{const $=x.get(q.id);return $===void 0||$===q.order?q:{...q,order:$}});r(T),n(T),a(j instanceof Error?j.message:String(j))})}return{clearTaskDrag:k,commitTaskDrop:R,commitTaskPreviewDrop:A,previewTaskDrop:y,startTaskDrag:S,taskDragSessionId:i,taskPreviewSessionIds:l}}function iB(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function qg({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const r=new Date().toISOString(),i=`pending_user_${a}_${r}_${Math.random().toString(36).slice(2,8)}`,s=sB(t);return{id:i,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:r,turnId:i,...s.length>0?{attachments:s}:{}}}function lk(e,t){return!t||ck(e,t)?e:[...e,t]}function ck(e,t){const n=t.afterMessageId?e.findIndex(i=>i.id===t.afterMessageId):-1,a=n>=0?n+1:0,r=Date.parse(t.timestamp);for(let i=a;i<e.length;i+=1){const s=e[i];if(s.role!=="user"||s.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const l=Date.parse(s.timestamp);if(!Number.isFinite(r)||!Number.isFinite(l)||l>=r)return!0}return!1}function sB(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function be(e,t){if(!e)return null;for(const n of t){const a=e[n];if(typeof a=="string"&&a.trim())return a}return null}function _o(e){const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}function Ae(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Xa(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function lB(e,t,n){if(t.name==="workspace_action_result"){const a=Xa(e,r=>r.role==="assistant"&&r.turnId===t.turnId&&r.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:Tm([...a.actionRun.refs,...n.refs]),childCalls:n.childCalls.length>0?n.childCalls:a.actionRun.childCalls};return}}e.push({id:t.id,role:"assistant",actionRun:n,timestamp:t.timestamp,turnId:t.turnId})}function cB(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Ae(e.data),n=Ae(e.args),a=be(n,["actionName"])??be(Ae(n?.input),["actionName"])??Eu(t)??Eu(Ae(t?.run))??Eu(Ae(t?.agentRun));if(!(e.action==="sandbox_run_action"||e.action==="profile_run_action"||!!a||t?.openPondActionRun===!0||t?.openPondProfileActionRun===!0)||!a)return null;const i=Ae(t?.run)??Ae(t?.agentRun),s=Ae(i?.metadata),l=Ae(t?.actionSummary)??Ae(i?.actionSummary)??Ae(s?.actionSummary),p=Ae(t?.action)??l??Ae(s?.selectedAction)??null,m=Ae(t?.responseSummary)??Ae(i?.responseSummary)??Ae(s?.responseSummary),f=Ae(t?.sourceSummary)??Ae(i?.sourceSummary)??Ae(s?.sourceSummary),S=Ae(t?.traceSummary)??Ae(i?.traceSummary)??Ae(s?.traceSummary),y=Ae(t?.evalSummary)??Ae(i?.evalSummary)??Ae(s?.evalSummary),k=Tm([...Va("artifact",t?.artifactRefs,"Artifact"),...Va("artifact",p?.artifactRefs,"Artifact"),...Va("artifact",l?.artifactRefs,"Artifact"),...Va("artifact",m?.artifactRefs,"Artifact"),...Va("trace",t?.traceArtifactRefs,"Trace"),...Va("trace",S?.artifactRefs,"Trace"),...Va("eval",t?.evalResultArtifactRefs,"Eval"),...Va("eval",y?.artifactRefs,"Eval"),...Va("output",t?.outputRefs,"Output")]),R=be(f,["sourceRef","ref"]);return R&&k.push({id:Em("source",R),kind:"source",label:"Source",target:R}),{actionName:a,title:be(p,["label","title","name"])??be(s,["selectedActionLabel"])??hB(a),status:dB(e,m,i),responseText:be(m,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:be(i,["id","runId"])??be(t,["runId","agentRunId"])??null,projectId:be(i,["projectId"])??be(t,["projectId"])??be(n,["projectId"])??null,agentId:be(i,["agentId"])??be(t,["agentId"])??be(n,["agentId"])??null,agentName:be(Ae(p?.implementation),["agentName"])??be(p,["agentName"])??be(s,["selectedAgentName"])??null,sandboxId:be(i,["sandboxId"])??be(t,["sandboxId"])??be(Ae(t?.sandbox),["id"])??be(Ae(t?.createdSandbox),["id"])??be(n,["sandboxId"])??null,runtimeId:be(i,["runtimeId"])??be(t,["runtimeId"])??null,implementationType:be(t,["implementationType"])??be(p,["implementationType","type","kind"])??be(Ae(p?.implementation),["type","kind"])??be(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:R,manifestHash:be(f,["manifestHash"])??be(t,["manifestHash"])??be(s,["manifestHash"])??null,refs:Tm(k),childCalls:mB(t,i,s)}}function Eu(e){return e?be(e,["actionName","name"])??be(Ae(e.action),["actionName","name"])??be(Ae(e.actionSummary),["actionName","name"])??be(Ae(e.selectedEntrypoint),["name"]):null}function dB(e,t,n){if(e.status==="failed")return"failed";const a=be(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const r=be(n,["status"]);return r==="failed"?"failed":r==="succeeded"||r==="completed"?"completed":r==="queued"||r==="running"||r==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function Va(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(r=>{const i=uB(e,r,n);return i?[i]:[]})}function uB(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:Em(e,s),kind:e,label:n,target:s}}const a=Ae(t);if(!a)return null;const r=be(a,["url","webUrl","artifactPath","path","ref"])??be(Ae(a.artifact),["url","webUrl","path","ref"]);if(!r)return null;const i=be(a,["label","title","name","type","kind"])??n;return{id:Em(e,r),kind:e,label:i,target:r}}function Tm(e){const t=new Set,n=[];for(const a of e){const r=`${a.kind}:${a.target}`;t.has(r)||(t.add(r),n.push(a))}return n}function Em(e,t){return`${e}:${t}`}function mB(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(r=>pB(r)).slice(0,6)}function pB(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const r=Ae(n);if(!r)return[];const i=be(r,["id","runId","callId"])??`child_${a+1}`,s=be(r,["label","title","actionName","name","tool"])??be(Ae(r.action),["label","name"])??"Implementation call",l=be(r,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:i,label:s,status:fB(r),detail:l}]})}function fB(e){const t=be(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function hB(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const gB=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function dk(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:gB.has(t.slice(n).toLowerCase())}function uk(e){return e.split("/").filter(Boolean).pop()??e}function bB(e){if(!jm(e))return;const t=Ae(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??Wo(e.data)??Wo(e.args)??Wo(e.output);if(!(!a||!dk(a)))return{path:a,appId:e.appId??null,title:uk(a)}}function vB(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return Mm(e.data,t,n),t.slice(0,12)}function Mm(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const l of e)Mm(l,t,n,a+1);return}const r=Ae(e);if(!r)return;const i=be(r,["path","artifactRef"]),s=be(r,["contentType","mimeType"]);i&&s&&!n.has(i)&&(n.add(i),t.push({path:i,title:be(r,["title","name"])??uk(i),contentType:s,sizeBytes:typeof r.sizeBytes=="number"?r.sizeBytes:null}));for(const l of Object.values(r))Mm(l,t,n,a+1)}function jm(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=Ae(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,be(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),be(Ae(t?.input),["tool","toolName","tool_name","name"]),be(Ae(t?.arguments),["tool","toolName","tool_name","name"]),be(Ae(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function Wo(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(Mu(n)&&dk(e.trim()))return e.trim();const r=_o(e);if(r!==null){const i=Wo(r,t+1,n);if(i)return i}return yB(e)}if(Array.isArray(e)){for(const r of e){const i=Wo(r,t+1,n);if(i)return i}return null}const a=Ae(e);if(!a)return null;for(const[r,i]of Object.entries(a)){if(!Mu(r))continue;const s=Wo(i,t+1,r);if(s)return s}for(const[r,i]of Object.entries(a)){if(Mu(r))continue;const s=Wo(i,t+1,r);if(s)return s}return null}function Mu(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function yB(e){const t=/(?:file:\/\/)?(?:\/|\.\/|[\w.-]+\/)[^\s"'`<>]+\.(?:avif|gif|jpe?g|png|webp)\b/i.exec(e);if(!t)return null;if(!t[0].startsWith("file://"))return t[0];try{return decodeURIComponent(new URL(t[0]).pathname)}catch{return t[0].replace(/^file:\/\//i,"")}}function SB(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return null;const t=e.action;if(t!=="connected_app_search"&&t!=="connected_app_read"&&t!=="connected_app_write")return null;const n=kB(e),a=e.status==="failed";return t==="connected_app_search"?e.name==="tool.started"?`${n} search`:a?`${n} search failed`:`${n} search`:t==="connected_app_read"?e.name==="tool.started"?`${n} lookup`:a?`${n} lookup failed`:`${n} lookup`:e.name==="tool.started"?`${n} update`:a?`${n} update failed`:`${n} update`}function xB(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=mk(e);return[t.providerOperation,t.operation&&t.operation!==t.providerOperation?t.operation:null,t.capabilityCount>0?`${t.capabilityCount} ${t.capabilityCount===1?"capability":"capabilities"}`:null].filter(a=>!!a).join(" / ")||t.providerLabel}function kB(e){return mk(e).providerLabel}function mk(e){const t=Ae(e.args),n=Ae(e.data),a=Ae(n?.result),r=dc(be(t,["provider"])??be(a,["provider"])??be(n,["provider"])??void 0),i=be(a,["providerLabel"])??be(n,["providerLabel"])??(r?op(r)?.label:null)??"connected app",s=be(t,["operation"]),l=be(a,["operation"])??be(n,["operation"]),p=ju(t?.capabilityIds)||ju(a?.capabilityIds)||ju(n?.capabilityIds);return{providerLabel:i,providerOperation:s,operation:l,capabilityCount:p}}function ju(e){return Array.isArray(e)?e.length:0}function pk(e){const t=e.trim(),n=/^<(goal_context|turn_aborted)>\s*([\s\S]*?)\s*<\/\1>$/.exec(t);if(n){const a=n[1];return{kind:a,text:n[2]?.trim()||Ou(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:Ou("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:Ou("goal_context")}:null}function Ou(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function Oc(e){return e.name==="diagnostic"&&Ae(e.data)?.kind==="goal_context"}function _B(e,t){if(!t.turnId)return;AB(e,t.turnId);const n=wB(t);if(!n)return;const a=RB(e,t.turnId);if(a){a.refinerActivity=n;return}const r={id:`${t.id}:work-refiner`,role:"activity_group",activities:[],timestamp:t.timestamp,turnId:t.turnId,traceState:"completed",traceStartedAt:t.timestamp,traceCompletedAt:t.timestamp,refinerActivity:n},i=e.findIndex(s=>s.role==="assistant"&&s.turnId===t.turnId);i>=0?e.splice(i,0,r):e.push(r)}function wB(e){const t=Ae(e.data),n=Ae(t?.activity);return n?IB(n,e):CB(e,t)}function fW(e){if(e.state==="running")return"Refiner · Reviewing for a reusable improvement";if(e.state==="failed")return"Refiner · Review failed";if(e.result==="no_action")return"Refiner · No reusable change";if(e.result==="routed")return`Refiner · ${MB(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function IB(e,t){const n=Oa(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":Oa(e.result,["no_action","routed","applied","retained"]),r=On(e.reason)??t.output??t.error??null;return{state:n,visibility:Oa(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:On(e.workspaceId),decision:Oa(e.decision,["no_action","route","propose"]),route:On(e.route),operation:Oa(e.operation,["create","update","delete"]),target:On(e.target),summary:On(e.summary)??fk(n,a),expectedOutcome:On(e.expectedOutcome),reason:r,evidenceBasis:PB(e.evidenceBasis),critiqueStatus:Oa(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:Oa(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:TB(e.validationReceipts),edits:EB(e.edits),refs:{trigger:ja(e.trigger),outcome:ja(e.outcome),proposal:ja(e.proposal),applyReceipt:ja(e.applyReceipt),advanceReceipt:ja(e.advanceReceipt),inputHarness:ja(e.inputHarness),outputHarness:ja(e.outputHarness)}}}function CB(e,t){if(!e.name.startsWith("harness.refiner."))return null;const n=e.name==="harness.refiner.failed"||e.status==="failed",a=e.name==="harness.refiner.completed",r=Ae(t?.outcome),i=Ae(t?.proposal),s=r?.routed===!0,l=On(t?.workspaceAdvance),p=n?"failed":a?i?l==="advanced"||/\bapplied\b/i.test(e.output??"")?"applied":"retained":s?"routed":"no_action":null;return{state:n?"failed":a?"completed":"running",visibility:"material_only",result:p,workspaceId:null,decision:i?"propose":s?"route":a?"no_action":null,route:On(r?.route),operation:null,target:null,summary:fk(n?"failed":a?"completed":"running",p),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:i?"passed":"not_applicable",validationStatus:i?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:ja(t?.trigger),outcome:ja(r),proposal:ja(i),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function RB(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.role==="activity_group"&&a.turnId===t&&!a.activities?.some(r=>r.subagentMessage))return a}return null}function AB(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a?.role==="status_divider"&&a.statusKind==="harness_refinement"&&a.turnId===t&&e.splice(n,1)}}function PB(e){const t=Ae(e),n=Oa(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:Bg(t.supportingEvidenceIds),counterevidence:Bg(t.counterevidence)}}function TB(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ae(t),a=On(n?.id),r=Oa(n?.status,["passed","failed","blocked","skipped"]),i=On(n?.summary);return a&&r&&i?[{id:a,status:r,summary:i}]:[]}):[]}function EB(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ae(t),a=On(n?.id),r=Oa(n?.operation,["create","update","delete"]),i=On(n?.target),s=On(n?.summary);return!a||!r||!i||!s?[]:[{id:a,operation:r,target:i,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function ja(e){const t=Ae(e),n=On(t?.id),a=On(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function Bg(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function On(e){return typeof e=="string"&&e.trim()?e.trim():null}function Oa(e,t){return typeof e=="string"&&t.includes(e)?e:null}function fk(e,t){return e==="running"?"Reviewing for a reusable improvement":e==="failed"?"Review failed":t==="no_action"?"No reusable change":t==="routed"?"Issue routed":"Harness change"}function MB(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const Fg=64*1024,Vg=8*1024;function Wg(e,t){const n=hk(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=jB(e,t.turnId);if(a){a.activities=$B(a.activities??[],t,n),a.timestamp=t.timestamp;return}Dl(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Dl(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(r=>r.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function jB(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.turnId!==t||a.role!=="activity_group")return null;if(!a.activities?.some(r=>r.subagentMessage))return a}return null}function Om(e,t,n){if(!t.turnId)return;const a=e.filter(l=>l.role==="activity_group"&&l.turnId===t.turnId&&!l.activities?.some(p=>p.subagentMessage)),r=a.filter(l=>l.traceState==="running"),i=r.length>0?r:a.length>0?[a[a.length-1]]:[];for(const l of i)l.traceState=n;const s=i.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function OB(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a?.turnId!==t.turnId||a.role!=="activity_group")continue;const r=a.activities?.filter(i=>i.controlKind!=="turn_aborted")??[];r.length!==a.activities?.length&&(r.length===0?e.splice(n,1):a.activities=r)}Om(e,t,"interrupted"),e.push({id:t.id,role:"status_divider",content:NB(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function NB(e){const t=e.output?.trim()||e.error?.trim();return t?/server shutting down|app restart|local app server stopped/i.test(t)?"Interrupted by app restart":/stopped by user|cancelled by user/i.test(t)?"Stopped by user":t:"Turn interrupted"}function $B(e,t,n=hk(t)){const a=[...e];return WB(a,t,n)||BB(a,t,n)||FB(a,t,n)||VB(a,t,n)?a:[...a,n]}function DB(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function LB(e,t){const n={id:t.id,role:"status_divider",content:zB(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:UB(t),statusTone:HB(t)};if(t.name!=="session.compaction.started"){const a=Xa(e,r=>r.role==="status_divider"&&r.statusKind==="compaction"&&r.statusState==="running"&&r.turnId===t.turnId);if(a){a.id=n.id,a.content=n.content,a.timestamp=n.timestamp,a.statusState=n.statusState,a.statusTone=n.statusTone;return}}e.push(n)}function zB(e){const t=qB(e);return e.name==="session.compaction.started"?t==="auto"?"Auto compacting context":"Compacting context":e.name==="session.compaction.completed"?t==="auto"?"Auto compacted context":"Compacted context":t==="auto"?"Auto compaction failed":"Context compaction failed"}function UB(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function HB(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function qB(e){return Ae(e.data)?.reason==="auto"?"auto":"manual"}function hk(e){const t=bB(e),n=e.name==="assistant.reasoning.delta"?"reasoning":nF(e),a=aF(e),r=iF(e),i=rF(e),s=sF(e),l=lF(e),p=vB(e);return{id:e.id,label:l?l.direction==="received"?"Child message received":"Child message sent":ZB(e),content:l?.summary??YB(e,t),timestamp:e.timestamp,...n?{kind:n}:{},...e.action?{action:e.action}:{},...a?{kind:"control",controlKind:a}:{},...e.name==="assistant.reasoning.delta"||e.name==="tool.started"||e.name==="tool.completed"||n==="command"?{callId:mf(e)??void 0}:{},...n&&e.name==="command.output"?{detail:Nm(e)}:{},...n==="command"?{terminal:fF(e)}:{},...i?{meta:i}:{},...r?{receipt:r}:{},...s?{openSession:s}:{},...l?{subagentMessage:l}:{},state:GB(e),...t?{imagePreview:t}:{},...p.length>0?{artifacts:p}:{}}}function BB(e,t,n){if(t.name==="tool.completed"){const a=Kg(e,t);if(!a)return!1;const r=hF(a.timestamp,t.timestamp);a.label=t.status==="failed"?"Failed":"Ran",a.state=n.state,a.timestamp=t.timestamp,a.artifacts=n.artifacts,a.terminal={...a.terminal,...n.terminal,...r!==null?{durationMs:r}:{}};const i=Nm(t);return i&&i!==a.content&&(a.detail=tc(a.detail,i)),!0}if(t.name==="command.output"){const a=Kg(e,t);if(!a)return!1;const r=Nm(t);return r&&(a.detail=tc(a.detail,r)),a.terminal={...a.terminal,...n.terminal},a.timestamp=t.timestamp,n.state==="failed"?a.state="failed":a.state!=="completed"&&a.state!=="failed"&&(a.state="running"),!0}return!1}function FB(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=mf(t),r=Xa(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!r)return!1;const i=n.content.trim();return r.id=n.id,r.label=n.label,r.timestamp=n.timestamp,r.state=n.state,i&&i!==r.content.trim()&&(r.content.trim()===r.action?r.content=i:r.detail=tc(r.detail,i)),n.detail&&(r.detail=tc(r.detail,n.detail)),r.meta=n.meta,r.receipt=n.receipt,r.imagePreview=n.imagePreview??r.imagePreview,r.artifacts=n.artifacts,!0}function VB(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=KB(e,t);return a?(a.id=n.id,a.label=n.label,a.content=n.content,a.timestamp=n.timestamp,a.state=n.state,a.detail=n.detail,a.meta=n.meta,a.receipt=n.receipt,a.imagePreview=n.imagePreview,!0):!1}function WB(e,t,n){if(t.name!=="assistant.reasoning.delta")return!1;const a=e[e.length-1];return!a||a.kind!=="reasoning"||n.kind!=="reasoning"||a.action!==n.action||(a.callId||n.callId)&&a.callId!==n.callId?!1:(a.content=`${a.content}${n.content}`,a.timestamp=t.timestamp,!0)}function Kg(e,t){const n=mf(t);if(n){const a=Xa(e,r=>r.kind==="command"&&r.callId===n);if(a)return a}return Xa(e,a=>a.kind==="command")}function KB(e,t){const n=t.action??"",a=gk[n]??{started:"Running workspace action"};return Xa(e,r=>r.state==="running"&&r.label===a.started&&r.kind!=="command"&&!r.controlKind)}function GB(e){if(e.name==="turn.interrupted"||e.status==="failed")return"failed";if(e.status==="pending"||e.name==="approval.requested")return"pending";if(e.name==="tool.started"||e.name==="workspace_action"||e.name==="command.output")return"running";if(e.name==="tool.completed"||e.name==="workspace_action_result")return"completed";if(e.status==="started")return"running";if(e.status==="completed")return"completed"}function ZB(e){if(e.name==="assistant.reasoning.delta")return be(Ae(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(Oc(e))return"Goal context";if(e.name==="turn.interrupted")return"Turn aborted";if(e.name==="subagent.started")return e.status==="started"?"Subagent running":"Started subagent";if(e.name==="subagent.reported")return"Subagent reported";if(e.name==="subagent.progress")return"Subagent progress";if(e.name==="subagent.completed")return"Subagent completed";if(e.name==="subagent.failed")return"Subagent failed";if(e.name==="subagent.workspace_retained")return"Subagent workspace retained";if(e.name==="subagent.archived")return"Subagent archived";if(e.name==="subagent.message")return"Subagent message";if(jm(e)&&e.name==="tool.started")return"Reading image";if(jm(e)&&e.name==="tool.completed")return"Read image";if(e.action==="resource_search"&&e.name==="tool.started")return"Searching resources";if(e.action==="resource_search"&&e.name==="tool.completed")return"Searched resources";if(e.action==="resource_read"&&e.name==="tool.started")return"Reading resource";if(e.action==="resource_read"&&e.name==="tool.completed")return"Read resource";if(e.action==="web_fetch"&&e.name==="tool.started")return"Fetching web page";if(e.action==="web_fetch"&&e.name==="tool.completed")return"Fetched web page";if(e.action==="web_search"&&e.name==="tool.started")return"Searching web";if(e.action==="web_search"&&e.name==="tool.completed")return"Searched web";if(e.action==="openpond_action_search"&&e.name==="tool.started")return"Searching actions";if(e.action==="openpond_action_search"&&e.name==="tool.completed")return"Searched actions";if(e.action==="openpond_action_run"&&e.name==="tool.started")return"Running OpenPond action";if(e.action==="openpond_action_run"&&e.name==="tool.completed")return"Ran OpenPond action";const t=SB(e);if(t)return t;const n=QB(e);if(n)return n;const a=XB(e);return a||(e.name==="skill.selected"?"Selected skill":e.name==="skill.loaded"?"Loaded skill":e.name==="skill.load_failed"?"Skill load failed":e.name==="tool.started"?"Started":e.name==="tool.completed"?"Ran":e.name==="command.output"?"Output":e.name==="workspace_action"||e.name==="workspace_action_result"?JB(e):e.name==="approval.requested"?"Approval requested":e.name==="session.compaction.started"?"Compacting context":e.name==="session.compaction.completed"?"Compacted conversation context":e.name==="session.compaction.failed"?"Context compaction failed":e.name.replace("."," "))}const gk={workspace_status:{started:"Checking workspace",completed:"Checked workspace"},resource_search:{started:"Searching resources",completed:"Searched resources"},resource_read:{started:"Reading resource",completed:"Read resource"},list_files:{started:"Listing files",completed:"Listed files"},read_files:{started:"Reading files",completed:"Read files"},search_files:{started:"Searching files",completed:"Searched files"},preview_write_files:{started:"Previewing files",completed:"Previewed files"},preview_write_file:{started:"Previewing file",completed:"Previewed file"},preview_edit_file:{started:"Previewing edit",completed:"Previewed edit"},preview_delete_file:{started:"Previewing delete",completed:"Previewed delete"},write_files:{started:"Editing files",completed:"Edited files",failed:"File checks failed"},write_file:{started:"Editing file",completed:"Edited file",failed:"File checks failed"},edit_file:{started:"Editing file",completed:"Edited file",failed:"File checks failed"},delete_file:{started:"Deleting file",completed:"Deleted file",failed:"File checks failed"},validate_sandbox_template:{started:"Validating template",completed:"Validated template",failed:"Template validation failed"},build_sandbox_template:{started:"Building template",completed:"Built template",failed:"Template build failed"},run_sandbox_template:{started:"Running sandbox template",pending:"Sandbox template log",completed:"Ran sandbox template",failed:"Sandbox template failed"},git_status:{started:"Checking git status",completed:"Checked git status"},git_fetch:{started:"Fetching git",completed:"Fetched git",failed:"Git fetch failed"},git_commit:{started:"Committing changes",completed:"Committed changes",failed:"Commit failed"},git_push:{started:"Pushing changes",completed:"Pushed changes",failed:"Push failed"},publish_openpond_repo:{started:"Publishing to OpenPond",completed:"Published to OpenPond",failed:"Publish failed"},upload_cloud_source:{started:"Uploading source",completed:"Uploaded source",failed:"Upload failed"},sandbox_create:{started:"Starting sandbox",completed:"Started sandbox",failed:"Sandbox start failed"},sandbox_status:{started:"Checking sandbox",completed:"Checked sandbox",failed:"Sandbox status failed"},sandbox_list_files:{started:"Listing sandbox files",completed:"Listed sandbox files",failed:"Sandbox file list failed"},sandbox_read_file:{started:"Reading sandbox file",completed:"Read sandbox file",failed:"Sandbox file read failed"},sandbox_search_files:{started:"Searching sandbox files",completed:"Searched sandbox files",failed:"Sandbox search failed"},sandbox_run_action:{started:"Running sandbox action",completed:"Ran sandbox action",failed:"Sandbox action failed"},sandbox_upload_file:{started:"Uploading file",completed:"Uploaded file",failed:"Upload failed"},sandbox_write_file:{started:"Writing sandbox file",completed:"Wrote sandbox file",failed:"Write failed"},sandbox_edit_file:{started:"Editing sandbox file",completed:"Edited sandbox file",failed:"Edit failed"},sandbox_delete_file:{started:"Deleting sandbox file",completed:"Deleted sandbox file",failed:"Delete failed"},sandbox_mkdir:{started:"Creating sandbox directory",completed:"Created sandbox directory",failed:"Directory create failed"},sandbox_move_file:{started:"Moving sandbox file",completed:"Moved sandbox file",failed:"Move failed"},sandbox_exec:{started:"Running sandbox command",completed:"Ran sandbox command",failed:"Sandbox command failed"},sandbox_git_status:{started:"Checking sandbox git",completed:"Checked sandbox git"},sandbox_git_diff:{started:"Reading sandbox diff",completed:"Read sandbox diff"},sandbox_git_export_patch:{started:"Exporting sandbox patch",completed:"Exported sandbox patch",failed:"Patch export failed"},sandbox_git_apply_patch_local:{started:"Applying sandbox patch locally",completed:"Applied locally",failed:"Apply locally failed"},sandbox_git_branch:{started:"Switching sandbox branch",completed:"Switched sandbox branch",failed:"Branch failed"},sandbox_git_commit:{started:"Committing sandbox changes",completed:"Committed sandbox changes",failed:"Commit failed"},sandbox_git_pull:{started:"Pulling sandbox changes",completed:"Pulled sandbox changes",failed:"Pull failed"},sandbox_git_push:{started:"Pushing sandbox changes",completed:"Pushed sandbox changes",failed:"Push failed"},sandbox_preserve_source:{started:"Preserving sandbox source",completed:"Preserved sandbox source",failed:"Preserve failed"},sandbox_promote_source:{started:"Promoting sandbox source",completed:"Promoted sandbox source",failed:"Promote failed"},sandbox_logs:{started:"Reading sandbox logs",completed:"Read sandbox logs",failed:"Sandbox logs failed"},sandbox_receipts:{started:"Reading sandbox receipts",completed:"Read sandbox receipts",failed:"Sandbox receipts failed"},sandbox_stop:{started:"Stopping sandbox",completed:"Stopped sandbox",failed:"Sandbox stop failed"},file_change:{started:"Editing files",completed:"Edited files"}};function JB(e){const t=e.action??"",n=gk[t]??{started:"Running workspace action",completed:"Workspace action completed",failed:"Workspace action failed"};return e.name==="workspace_action"?e.status==="pending"?n.pending??n.started:n.started:e.status==="failed"?n.failed??`${n.completed} failed`:n.completed}function YB(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=pk(e.output??"");if(n)return n.text;if(Oc(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=eF(e);if(a)return a;const r=tF(e);if(r)return r;const i=xB(e);if(i)return i;const s=bk(e);if(s)return s;if(e.name==="command.output")return yk(e.output??"");if(e.name==="tool.started"||e.name==="tool.completed"){const l=e.data;if(l&&typeof l=="object"){const p=l.command;if(typeof p=="string"&&p.trim())return p;const m=l.tool;if(typeof m=="string"&&m.trim())return m;const f=l.type;if(typeof f=="string"&&f.trim())return f}}return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"?e.error??e.output??"":e.output??e.action??""}function XB(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return null;const t=e.status==="failed";return e.action==="openpond_create_improve"?e.name==="tool.started"?"Starting Create Pipeline":t?"Create Pipeline failed":"Started Create Pipeline":null}function QB(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return null;const t=e.status==="failed",n=e.name==="tool.completed";switch(e.action){case"openpond_browser_open":return n?t?"Browser open failed":"Opened browser":"Opening browser";case"openpond_browser_snapshot":return n?t?"Browser capture failed":"Captured browser":"Capturing browser";case"openpond_browser_move_cursor":return n?t?"Cursor move failed":"Moved browser cursor":"Moving browser cursor";case"openpond_browser_click":return n?t?"Browser click failed":"Clicked browser":"Clicking browser";case"openpond_browser_type":return n?t?"Browser typing failed":"Typed in browser":"Typing in browser";case"openpond_browser_key":return n?t?"Browser key failed":"Pressed browser key":"Pressing browser key";case"openpond_browser_scroll":return n?t?"Browser scroll failed":"Scrolled browser":"Scrolling browser";default:return null}}function eF(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Ae(Ae(e.data)?.result),n=be(t,["output"]);if(n)return n;const a=Ae(_o(e.output??"")),r=be(a,["output"]);if(r)return r;const i=Ae(e.args),s=be(i,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function tF(e){if(e.action!=="openpond_create_improve")return null;const t=Ae(Ae(e.data)?.result),n=be(t,["nextStep"]);if(n)return n;const a=Ae(_o(e.output??"")),r=be(a,["output"]);if(r)return r;const i=Ae(e.args),s=be(i,["reason"]);if(s)return s;const l=be(i,["objective"]);return l||(e.error??null)}function nF(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Ae(e.data),n=be(t,["type"]),a=be(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||bk(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function aF(e){if(e.name==="turn.interrupted")return"turn_aborted";if(Oc(e))return"goal_context"}function bk(e){const t=Ae(e.data),n=be(t,["type"]),a=be(t,["tool","toolName","tool_name","name","functionName","function_name"]),r=Ae(t?.result),i=Ae(_o(e.output??"")),s=Ae(i?.data),l=be(t,["command","cmd"])??be(Ae(t?.input),["command","cmd"])??be(Ae(t?.arguments),["command","cmd"])??be(Ae(t?.args),["command","cmd"])??oF(be(t,["arguments","args","input"]))??be(Ae(e.args),["command","cmd"])??be(r,["command","cmd"])??be(s,["command","cmd"]);return l||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function oF(e){if(!e)return null;const t=_o(e),n=Ae(t);return be(n,["command","cmd"])}function mf(e){const t=Ae(e.data);return be(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function rF(e){const t=Ae(e.data);if(!t)return null;const n=[],a=Ae(t.workspaceToolTiming),r=typeof a?.durationMs=="number"?a.durationMs:null;r!==null&&n.push(uF(r));const i=Ae(t.workspaceExecutionTarget),s=be(i,["target"]);if(s==="sandbox"){const m=i?.hybrid===!0,f=be(i,["sandboxId","workspaceId"]);n.push(`${m?"Hybrid ":""}sandbox${f?` ${Gg(f)}`:""}`)}else s==="local"&&n.push("local workspace");const l=Ae(t.sourcePreservation);if(l?.attempted===!0)if(l.ok!==!0)n.push("checkpoint failed");else if(l.preserved===!0){const m=be(l,["preservedSha"]);n.push(m?`checkpoint ${pF(m)}`:"checkpoint saved")}else n.push("checkpoint clean");const p=vk(t);return p&&(n.push(`receipt ${Gg(p.id)}`),n.push(`${mF(p.totalUsd)} ${p.status}`)),n.length>0?n.join(" · "):null}function iF(e){const t=vk(Ae(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function sF(e){if(!e.name.startsWith("subagent."))return;const t=Ae(e.data),n=Ae(t?.run),a=be(t,["childSessionId"])??be(n,["childSessionId"]);if(!a)return;const r=be(n,["roleId"])??be(t,["roleId"]),i=be(n,["status"])??be(t,["status"]);return{sessionId:a,label:"Open conversation",...r?{roleId:r}:{},...i?{status:i}:{}}}function lF(e){if(e.name!=="subagent.message")return;const t=Ae(e.data),n=Ae(t?.message);if(!n)return;const a=be(n,["id"]),r=be(n,["kind"]),i=be(n,["fromRunId"]),s=be(n,["body"]);if(!a||!r||!i||!s)return;const l=Ae(t?.delivery??n.delivery),p=Ae(t?.modelRef),m=be(p,["providerId"]),f=be(p,["modelId"]),y=be(l,["deliveredParentSessionId"])===e.sessionId&&!i.startsWith("parent:")?"received":"sent",k=Array.isArray(n.refs)?n.refs.flatMap(R=>{const A=Ae(R),D=be(A,["kind"]),z=be(A,["id"]),N=be(A,["label"]);return D&&z&&N?[{kind:D,id:z,label:N}]:[]}):[];return{direction:y,summary:cF(s),body:s,messageId:a,kind:r,fromRunId:i,toRunId:be(n,["toRunId"]),toRole:be(n,["toRole"]),childSessionId:be(t,["childSessionId"]),roleId:be(t,["roleId"]),modelRef:m&&f?{providerId:m,modelId:f}:null,deliveryStatus:be(l,["status"]),wakeReason:be(l,["wakeParentReason"]),createdAt:be(n,["createdAt"]),refs:k}}function cF(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return dF(n,96)}function dF(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),r=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,r).trimEnd()}...`}function vk(e){const t=Ae(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const r=Ae(n[a]),i=be(r,["id"]),s=be(r,["status"]),l=be(r,["totalUsd","retailTotalUsd"]);if(i&&s&&l)return{id:i,status:s,totalUsd:l}}return null}function uF(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function mF(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function pF(e){return e.length>12?e.slice(0,12):e}function Gg(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function yk(e){let t=e.replace(/\r\n/g,`
136
- `).trim();if(!t)return"";const n=gF(t);if(n!==null)return Vr(n);const a=`
137
- Output:
138
- `,r=t.indexOf(a);return r>=0&&bF(t.slice(0,r))&&(t=t.slice(r+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),Vr(t.trim())}function Nm(e){const t=yk(e.output??"");if(t)return t;const n=Ae(Ae(e.data)?.result);return n?Vr(Sk(n)):""}function fF(e){const t=Ae(e.data),n=Ae(t?.result),a=Ae(_o(e.output??"")),r=Ae(a?.data),i=Ae(t?.workspaceToolTiming),s=[n?.exitCode,r?.exitCode,t?.exitCode].find(p=>typeof p=="number"),l=i?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof l=="number"?{durationMs:l}:{}}}function hF(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function gF(e){const t=Ae(_o(e)),n=typeof t?.action=="string"?t.action:"";if(!t||typeof t.ok!="boolean"||!n||typeof t.output!="string")return null;const a=Ae(t.data);return a?Sk(a,be(t,["output"])):typeof t.output=="string"?t.output.trim():""}function Sk(e,t=null){const n=be(e,["stdout"])?.replace(/\r\n/g,`
139
- `).trimEnd()??"",a=be(e,["stderr"])?.replace(/\r\n/g,`
140
- `).trimEnd()??"",r=[n,a].filter(Boolean);return r.length>0?r.join(`
141
- `):t?.replace(/\r\n/g,`
142
- `).trim()??""}function bF(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function tc(e,t){const n=e??"";if(!n)return Vr(t);if(n===t||n.includes(t))return n;if(t.includes(n))return Vr(t);const a=n.endsWith(`
143
- `)||t.startsWith(`
144
- `)?"":`
145
- `;return Vr(`${n}${a}${t}`)}function Vr(e){if(e.length<=Fg)return e;const t=`
146
-
147
- … output omitted from live view; full output remains in task history …
148
-
149
- `,n=Math.max(0,Fg-Vg-t.length);return`${e.slice(0,Vg)}${t}${e.slice(-n)}`}const vF=/\bopenpond\s+opchat\b/i,yF=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function xk(e){const t=e?.trim()||"Turn failed";return vF.test(t)&&yF.test(t)?"Server connection lost. Retry your message.":t}function SF(e,t){if((kl(t,"code")??kl(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(kl(a,"code")??kl(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const r=e??"";return/\bopchat_quota_exceeded\b/i.test(r)||/OpChat token allowance is exhausted/i.test(r)?"opchat_quota_exceeded":null}function kl(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function xF(e){const t=new Map,n=new Set;for(const a of e)a.turnId&&(a.role==="assistant"&&a.content?.trim()&&t.set(a.turnId,a.content),(a.role==="error"||a.role==="status_divider"&&a.statusState!=="running"||a.role==="activity_group"&&a.traceState!=="running")&&n.add(a.turnId));for(const a of e){if(a.role!=="activity_group"||!a.turnId||a.activities?.some(l=>l.subagentMessage))continue;const r=kF(a.activities??[]);if(r.length===0){a.deliverables=void 0;continue}const i=t.get(a.turnId)??"",s=i?_F(r,i):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[r[r.length-1]]:void 0}}function kF(e){const t=new Set(e.map(a=>a.imagePreview?.path).filter(a=>!!a)),n=new Map;for(const a of e)if(!a.imagePreview)for(const r of a.artifacts??[])t.has(r.path)||(n.delete(r.path),n.set(r.path,r));return[...n.values()]}function _F(e,t){const n=kk(t);return e.filter(a=>wF(a).some(r=>t.includes(r)||n.includes(r)))}function wF(e){const t=new Set;for(const n of[e.path,e.title,IF(e.path)]){const a=n.trim();a&&(t.add(a),t.add(kk(a)))}return[...t]}function IF(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function kk(e){try{return decodeURIComponent(e)}catch{return e}}const _k=8;function CF(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=Dm(e.data),n=e.output?Dm(_o(e.output)):null;return RF(t??n)}function $m(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const r of[...e??[],...t]){const i=wk(r.url);if(!(!i||a.has(i))&&(a.add(i),n.push(r),n.length>=_k))break}return n.length>0?n:void 0}function Dm(e,t=0){if(t>5)return null;const n=Ae(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:be(n,["url"])?[n]:null;if(a)return{provider:be(n,["provider"]),results:a};for(const r of["result","data","output"]){const i=Dm(n[r],t+1);if(i)return i}return null}function RF(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const r=AF(e.results[a],a,e.provider);if(!r)continue;const i=wk(r.url);if(!(!i||n.has(i))&&(n.add(i),t.push(r),t.length>=_k))break}return t}function AF(e,t,n){const a=Ae(e);if(!a)return null;const r=be(a,["url","href"]);if(!r||!PF(r))return null;const i=be(a,["title"])??Zg(r)??`Source ${t+1}`;return{id:be(a,["id"])??`source_${t+1}`,title:i,url:r,sourceName:be(a,["sourceName","source_name","source"])??Zg(r),snippet:be(a,["snippet","description"]),provider:n,faviconUrl:TF(be(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??EF(r),publishedAt:be(a,["publishedAt","published_at"]),updatedAt:be(a,["updatedAt","updated_at"])}}function PF(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function wk(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function TF(e){if(!e)return null;try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function EF(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function Zg(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const Jg=new WeakMap;function Nc(e){const t=Jg.get(e);if(t)return t;const n=MF(e);return Jg.set(e,n),n}function MF(e){const t=[],n=new Map;for(const a of e){if(a.name==="turn.started"){Dl(t,a);const r=$F(a.args);if(r){const i=pk(r);if(i){Wg(t,{...a,name:i.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:i.text,data:{...Ae(a.data)??{},kind:i.kind}});continue}t.push({id:a.id,role:"user",content:r,attachments:DF(a.args),timestamp:a.timestamp,turnId:a.turnId});const s=Xg(a.args);s&&t.push({id:`${a.id}:create-improve`,role:"assistant",timestamp:a.timestamp,turnId:a.turnId,createImproveRun:s})}continue}if(a.name==="create_improve.updated"){const r=Xg(a.data);if(!r)continue;const i=Xa(t,s=>s.turnId===a.turnId&&!!s.createImproveRun);i?(i.createImproveRun=r,i.timestamp=a.timestamp):t.push({id:`${a.id}:create-improve`,role:"assistant",timestamp:a.timestamp,turnId:a.turnId,createImproveRun:r});continue}if(a.name==="assistant.delta"){const r=a.output??"";if(!r)continue;Dl(t,a);const i=t[t.length-1];if(i?.role==="assistant"&&i.turnId===a.turnId&&!i.createImproveRun)i.content=`${i.content??""}${r}`,i.timestamp=a.timestamp,i.sources=$m(i.sources,Yg(n,a.turnId)??[]);else{const s=Yg(n,a.turnId);t.push({id:a.id,role:"assistant",content:r,timestamp:a.timestamp,turnId:a.turnId,...s?.length?{sources:s}:{}})}continue}if(a.name==="assistant.reasoning.delta"){const r=a.output??"";if(!r)continue;Dl(t,a);const i=t[t.length-1];i?.role==="assistant"&&i.turnId===a.turnId&&i.reasoningContent!==void 0&&!i.createImproveRun?(i.reasoningContent=`${i.reasoningContent}${r}`,i.timestamp=a.timestamp):i?.role==="assistant"&&i.turnId===a.turnId&&!i.reasoningContent&&!i.createImproveRun?(i.reasoningContent=r,i.timestamp=a.timestamp):t.push({id:a.id,role:"assistant",reasoningContent:r,timestamp:a.timestamp,turnId:a.turnId});continue}if(a.name==="user_question.asked"){const r=Ae(a.data),i=pR.safeParse(r?.question);if(!i.success)continue;t.push({id:a.id,role:"assistant",timestamp:a.timestamp,turnId:a.turnId,userQuestion:i.data});continue}if(a.name==="user_question.answered"||a.name==="user_question.dismissed"){const r=Ae(a.data),i=fR.safeParse(r?.resolution);if(!i.success)continue;const s=Xa(t,l=>l.userQuestion?.id===i.data.questionId);if(!s?.userQuestion||s.userQuestion.status!=="pending")continue;s.userQuestion={...s.userQuestion,status:i.data.action==="answer"?"answered":"dismissed",answer:i.data.action==="answer"?{optionId:i.data.optionId,text:i.data.text}:null,answeredAt:a.timestamp},s.timestamp=a.timestamp;continue}if(a.name==="turn.completed"){Om(t,a,"completed");continue}if(a.name==="turn.failed"){Om(t,a,"failed");const r=a.error??"Turn failed",i=SF(r,a.data);t.push({id:a.id,role:"error",content:xk(r),...i?{errorKind:i}:{},timestamp:a.timestamp,turnId:a.turnId});continue}if(a.name==="turn.interrupted"){OB(t,a);continue}if(DB(a)){LB(t,a);continue}if(a.name.startsWith("harness.refiner.")){_B(t,a);continue}if(a.name==="tool.started"||a.name==="tool.completed"||a.name==="skill.selected"||a.name==="skill.loaded"||a.name==="skill.load_failed"||a.name==="command.output"||a.name==="workspace_action"||a.name==="workspace_action_result"||a.name==="approval.requested"||a.name.startsWith("subagent.")||Oc(a)){if(OF(a))continue;const r=cB(a);if(r){lB(t,a,r);continue}const i=CF(a);i.length>0&&jF(t,n,a.turnId,i),Wg(t,a)}if(a.name==="workspace.diff"){const r=NF(a.data);if(!r||r.filesChanged===0)continue;const i=Xa(t,s=>s.role==="assistant"&&s.turnId===a.turnId);i&&(i.changeSummary=r,i.timestamp=a.timestamp)}}return xF(t),t}function jF(e,t,n,a){if(!n)return;const r=e[e.length-1];if(r?.role!=="assistant"||r.turnId!==n){t.set(n,$m(t.get(n),a));return}r.sources=$m(r.sources,a)}function Yg(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function OF(e){if(e.name!=="approval.requested")return!1;if(e.action==="create_plan")return!0;const t=Ae(e.data),n=Ae(t?.approval);return t?.kind==="create_plan"||n?.kind==="create_plan"}function NF(e){const t=RA.safeParse(e);return t.success?t.data:null}function $F(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function DF(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=TT.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function Xg(e){const t=Ae(e);if(!t)return null;const n=Os.safeParse(t.createImproveRun);return n.success?n.data:null}function hW(e){if(!e)return"";const t=new Date(e).getTime();if(Number.isNaN(t))return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const r=Math.floor(a/60);return r<48?`${r}h`:`${Math.floor(r/24)}d`}function gW(e){const t=Ik(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function bW(e){const t=Ik(e);return t?t.toLocaleString():""}function Ik(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function LF(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[r,i]=g.useState({}),s=g.useCallback(p=>{i(m=>({...m,[p.sessionId]:p}))},[]);g.useEffect(()=>{i(p=>{let m=p;for(const[f,S]of Object.entries(p)){const y=Nc(Vs(n,f));ck(y,S)&&(m===p&&(m={...p}),delete m[f])}return m})},[n]);const l=g.useMemo(()=>lk(t,a?r[a]:null),[t,r,a]);return{pendingChatUserMessages:r,recordPendingChatUserMessage:s,visibleChatMessages:l}}const Ck="openpond.commandAccessMode";function $c(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function zF(e){return e==="ask"||e==="full-access"||e==="disabled"?e:null}function Rk(e=$c()){if(!e)return{};const t=zF(e.getItem(Ck));return{...t?{openPondCommandAccessMode:t}:{}}}function UF(e,t=$c()){try{t?.setItem(Ck,e)}catch{}}function HF(e,t=$c()){const n=Qn(e);return{openPondCommandAccessMode:Rk(t).openPondCommandAccessMode??n.openPondCommandAccessMode??Es}}function qF(e,t=$c()){const n=Qn(e),a=Rk(t),r={};return a.openPondCommandAccessMode&&a.openPondCommandAccessMode!==n.openPondCommandAccessMode&&(r.openPondCommandAccessMode=a.openPondCommandAccessMode),r}function BF({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:r,setSessions:i}){return{changeOpenPondCommandAccessMode:g.useCallback((l,p=t)=>{r(l),UF(l);const m=p?.provider==="codex"?null:p;m&&i(f=>f.map(S=>S.id===m.id?{...S,openPondCommandAccessMode:l}:S)),e&&(J.savePreferences(e,{openPondCommandAccessMode:l}).then(()=>{n(f=>f&&{...f,preferences:{...f.preferences,openPondCommandAccessMode:l}})}).catch(f=>{a(f instanceof Error?f.message:String(f))}),m&&J.patchSession(e,m.id,{openPondCommandAccessMode:l}).then(f=>{i(S=>S.map(y=>y.id===f.id?f:y))}).catch(f=>{a(f instanceof Error?f.message:String(f))}))},[e,t,n,a,r,i])}}function FF({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:r,selectedSessionId:i,selectedProjectId:s,archivedChatsOpen:l,projectsExpanded:p,chatRowsVisibleCount:m,sidebarFileBookmarks:f=[]}){const S=g.useMemo(()=>e.filter(ie=>!ie.hiddenFromDefaultSidebar),[e]),y=g.useMemo(()=>n.filter(ie=>!ie.archived&&Qg(ie)),[n]),k=g.useMemo(()=>y.filter(ie=>ie.pinned),[y]),R=g.useMemo(()=>y.filter(ie=>!!ie.savedForLater),[y]),A=g.useMemo(()=>n.filter(ie=>ie.archived&&Qg(ie)),[n]),D=g.useMemo(()=>new Set(e.map(ie=>ie.id)),[e]),z=g.useMemo(()=>new Set(t.map(ie=>ie.id)),[t]),N=g.useMemo(()=>vx(e),[e]),x=g.useMemo(()=>{const ie={};for(const Ie of[...y,...A]){const $e=xg(Ie,D,N,z);$e&&(ie[Ie.id]=$e)}return ie},[y,A,z,D,N]),I=g.useMemo(()=>y.filter(ie=>!ie.pinned&&!ie.savedForLater&&!ie.appId&&!x[ie.id]),[y,x]),P=g.useMemo(()=>A.filter(ie=>!ie.appId&&!xg(ie,D,N,z)),[A,z,D,N]),j=g.useMemo(()=>{const ie={};for(const Ie of y){if(Ie.pinned||Ie.savedForLater)continue;const $e=x[Ie.id];if(!$e)continue;const Je=ie[$e];Je?Je.push(Ie):ie[$e]=[Ie]}return ie},[y,x]),T=g.useMemo(()=>{const ie={};for(const Ie of n){if(Ie.archived||!Ak(Ie))continue;const $e=ie[Ie.parentSessionId];$e?$e.push(Ie):ie[Ie.parentSessionId]=[Ie]}for(const Ie of Object.values(ie))Ie.sort(($e,Je)=>Date.parse(Je.updatedAt)-Date.parse($e.updatedAt));return ie},[n]),F=g.useMemo(()=>S.map((ie,Ie)=>{const $e=ht("local",ie.id),Je=BH(ie,t);return{id:$e,kind:"local",project:ie,pinned:!!r[$e]?.pinned,order:r[$e]?.order??Ie,cloudLinkTrusted:!Je,cloudLinkWarning:Je}}).sort(Nu),[r,t,S]),q=g.useMemo(()=>t.map((ie,Ie)=>{const $e=ht("cloud",ie.id);return{id:$e,kind:"cloud",project:ie,pinned:!!r[$e]?.pinned,order:r[$e]?.order??Ie,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(Nu),[r,t]),$=g.useMemo(()=>new Set(S.map(ie=>sa(ie,t)?.id??null).filter(ie=>!!ie)),[t,S]),V=g.useMemo(()=>q.filter(ie=>!$.has(ie.project.id)),[q,$]),re=g.useMemo(()=>[...F,...V].sort(Nu),[V,F]),X=g.useMemo(()=>re.filter(ie=>ie.pinned),[re]),we=g.useMemo(()=>f.filter(ie=>ie.status==="pinned"),[f]),ye=g.useMemo(()=>f.filter(ie=>ie.status==="saved_for_later"),[f]),K=re,Ee=g.useMemo(()=>VF(K,p,s),[K,p,s]),xe=g.useMemo(()=>[...X.map(ie=>({type:"project",key:Vo({type:"project",id:ie.id}),id:ie.id,item:ie,order:ie.order})),...k.map(ie=>({type:"session",key:Vo({type:"session",id:ie.id}),id:ie.id,session:ie,order:ie.order})),...we.map((ie,Ie)=>({type:"file",key:Vo({type:"file",id:ie.id}),id:ie.id,file:ie,order:ie.order??X.length+k.length+Ie}))].sort((ie,Ie)=>{if(ie.order!==Ie.order)return ie.order-Ie.order;if(ie.type!==Ie.type){const et={project:0,session:1,file:2};return et[ie.type]-et[Ie.type]}const $e=ie.type==="project"?ie.item.project.name:ie.type==="session"?ie.session.title:ie.file.path,Je=Ie.type==="project"?Ie.item.project.name:Ie.type==="session"?Ie.session.title:Ie.file.path;return $e.localeCompare(Je)}),[we,X,k]),se=g.useMemo(()=>l?[...I,...P]:I,[l,P,I]),ke=g.useMemo(()=>se.slice(0,Math.max(jn,m)),[se,m]),ee=g.useMemo(()=>Vs(a,i),[a,i]),pe=g.useMemo(()=>Nc(ee),[ee]),ve=Lx(a,i),qe=zx(a,i),Re=EH(a,i);return{activeSessions:y,pinnedSessions:k,savedForLaterSessions:R,pinnedFiles:we,savedForLaterFiles:ye,chatSessions:I,archivedSessions:A,pinnedProjects:X,pinnedItems:xe,projectRows:K,localProjectRows:F,visibleProjectRows:Ee,cloudProjectRows:V,projectSessionRowsByProjectId:j,childSessionRowsByParentId:T,sidebarProjectIdBySessionId:x,chatRows:se,visibleChatRows:ke,sessionEvents:ee,chatMessages:pe,contextUsage:ve,goalRuntime:qe,subagentRuntime:Re}}function Qg(e){return Ak(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function Ak(e){return!!(e.parentSessionId&&e.subagentRunId)}function Nu(e,t){return e.pinned!==t.pinned?e.pinned?-1:1:e.order!==t.order?e.order-t.order:e.project.name.localeCompare(t.project.name)}function VF(e,t,n){if(t||e.length<=jl)return e;const a=e.slice(0,jl);if(!n||a.some(i=>i.id===n))return a;const r=e.find(i=>i.id===n);return r?[...a.slice(0,jl-1),r]:a}function WF(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function Pk(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const r=e[a];if(r?.name==="turn.started"){t=a,n=r.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const r=e[a];if(!(!r||!WF(r))&&!(n&&r.turnId&&r.turnId!==n))return r.name==="turn.completed"?"completed":"blocked"}return"pending"}function eb(e,t){if(e.systemKind)return!1;const n=Vs(t,e.id);if(n.length===0)return!1;const a=Pk(n);return a==="pending"||a==="none"&&Tk(n)==="pending"}function tb(e,t){if(e.systemKind||e.status!=="active")return!1;const n=Vs(t,e.id);if(n.length===0)return!0;const a=Pk(n);return a==="pending"||a==="none"&&Tk(n)!=="terminal"}function Tk(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n){if(n.name==="turn.completed"||n.name==="turn.failed"||n.name==="turn.interrupted")return"terminal";if(n.name==="assistant.delta"||n.name==="assistant.reasoning.delta"||n.name==="tool.started"||n.name==="tool.completed"||n.name==="skill.selected"||n.name==="skill.loaded"||n.name==="skill.load_failed"||n.name==="approval.requested"||n.name==="approval.resolved"||n.name==="command.output"||n.name==="workspace_action"||n.name==="workspace_action_result")return"pending"}}return"none"}function KF({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:r,sidebarSessions:i,subagentRuntimeBySessionId:s}){const l=g.useMemo(()=>new Map(i.map(y=>[y.id,y])),[i]),p=g.useMemo(()=>{const y=new Set;for(const[k,R]of t??[]){const A=l.get(k);R.tone==="active"&&!A?.systemKind&&y.add(k)}for(const k of n.activeGoalSessionIds)l.get(k)?.systemKind||y.add(k);return r&&!a?.systemKind&&e?.tone==="active"&&y.add(r),y},[e,t,n,a,r,l]),m=g.useMemo(()=>{const y=new Set(p);for(const[k,R]of s??[]){const A=l.get(k);R.activeCount>0&&!A?.systemKind&&y.add(k)}for(const k of n.activeSubagentSessionIds)l.get(k)?.systemKind||y.add(k);for(const k of i)k.systemKind||eb(k,n)&&y.add(k.id);return a&&eb(a,n)&&y.add(a.id),y},[p,n,a,i,l,s]),f=g.useMemo(()=>{const y=new Set(m);for(const k of i)tb(k,n)&&y.add(k.id);return a&&tb(a,n)&&y.add(a.id),y},[m,n,a,i]),S=!!(a&&!a.systemKind&&m.has(a.id));return{runningSessionIds:f,selectedSessionRunning:S}}const GF=1e3;function ZF(e){const[t,n]=g.useState(()=>new Date().toISOString());return g.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const r=window.setInterval(a,GF);return()=>window.clearInterval(r)},[e]),t}function JF(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:r,goalRuntime:i,locallyActiveCodexHistorySessionIds:s,pinnedSessions:l,savedForLaterSessions:p,projectSessionRowsByProjectId:m,rightChatHistoryEvents:f,runtimeIndexes:S,selectedSession:y,selectedSessionId:k,serverId:R,setCodexHistorySessions:A,sidebarSessions:D,subagentRuntime:z,visibleChatRows:N,visibleProjectRows:x}=e,[I,P]=g.useState({});g.useEffect(()=>{P({})},[R]);const j=g.useMemo(()=>{const se=[],ke=new Set,ee=ve=>{!ve||ve.id===k||!Mt(ve.id)||ke.has(ve.id)||(ke.add(ve.id),se.push(ve.id))};for(const ve of n)(ve.status==="active"||s.has(ve.id))&&ee(ve);const pe=se.length;for(const ve of x)for(const qe of(m[ve.id]??[]).slice(0,2))ee(qe);for(const ve of r)for(const qe of(m[ve]??[]).slice(0,jl))ee(qe);for(const ve of l)ee(ve);for(const ve of p)ee(ve);for(const ve of N)ee(ve);return[...se.slice(0,pe),...se.slice(pe,pe+8)].join(`
150
- `)},[n,r,s,l,p,m,k,N,x]),T=g.useCallback(se=>{P(ke=>ke[se.session.id]===se.events?ke:{...ke,[se.session.id]:se.events}),A(ke=>jc(ke,se.session))},[A]),F=g.useMemo(()=>{if(!j)return"";const se=new Set(j.split(`
151
- `).filter(Boolean));return D.filter(ke=>se.has(ke.id)&&ke.status==="active").map(ke=>ke.id).join(`
152
- `)},[j,D]),q=g.useMemo(()=>j?j.split(`
153
- `).filter(se=>s.has(se)).join(`
154
- `):"",[j,s]);g.useEffect(()=>{!y||!k||!Mt(k)||t.length===0||T({session:y,events:t})},[T,t,y,k]),g.useEffect(()=>{if(!a||!j)return;const se=a,ke=j.split(`
155
- `).filter(Boolean),ee=new Set(F.split(`
156
- `).filter(Boolean)),pe=new Set(q.split(`
157
- `).filter(Boolean)),ve=ke.map(qe=>uf({connection:se,locallyActive:pe.has(qe),onPayload:Re=>T(df(Re,pe.has(qe))),reportedActive:ee.has(qe),sessionId:qe,surface:"sidebar"}));return()=>ve.forEach(qe=>qe())},[T,F,q,j,a]);const $=g.useMemo(()=>new Map(D.map(se=>[se.id,se])),[D]),V=g.useMemo(()=>{const se=new Map(S.latestGoalRuntimeBySessionId);for(const ke of D){const ee=ke.status==="active"?Au(ke.metadata):null;ee&&se.set(ke.id,ee)}for(const ke of[I,f])for(const[ee,pe]of Object.entries(ke)){const ve=$.get(ee),qe=ve?.status==="active"?Au(ve.metadata):null,Re=Im(pe)??sf(pe)??(ve?.status==="active"?ec(pe)??qe:null);Re?se.set(ee,Re):se.delete(ee)}if(k)if(i)se.set(k,i);else if(y?.status==="active"&&t.length>0){const ke=Im(t)??ec(t)??Au(y.metadata);ke?se.set(k,ke):se.delete(k)}else(!Mt(k)||t.length>0)&&se.delete(k);return se},[t.length,I,i,f,S.latestGoalRuntimeBySessionId,y?.status,y?.metadata,k,$,D]),re=g.useMemo(()=>[...V.values()].some(se=>se.tone==="active"&&!!se.observedAt),[V]),X=ZF(re),we=g.useMemo(()=>re?new Map([...V].map(([se,ke])=>[se,sH(ke,X)??ke])):V,[V,X,re]),ye=k?we.get(k)??i:i,K=g.useMemo(()=>{const se=new Map(S.latestSubagentRuntimeBySessionId);return k&&(z?se.set(k,z):se.delete(k)),se},[S.latestSubagentRuntimeBySessionId,k,z]),{runningSessionIds:Ee,selectedSessionRunning:xe}=KF({goalRuntime:ye,goalRuntimeBySessionId:we,runtimeIndexes:S,selectedSession:y,selectedSessionId:k,sidebarSessions:D,subagentRuntimeBySessionId:K});return{goalRuntime:ye,runningSessionIds:Ee,selectedSessionRunning:xe,sidebarGoalRuntimeBySessionId:we,sidebarSubagentRuntimeBySessionId:K}}function YF({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:r}){g.useEffect(()=>{const i=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(l=>!l);return}if(s.key==="Escape"&&e){s.preventDefault(),a(!1),r(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[e,t,r,a,n])}function XF({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:r,setError:i,onDisconnected:s}){g.useEffect(()=>{if(!n?.token||e===null)return;const l=n;let p=null,m=[],f=null,S=null,y=!1;const k=new Map;let R=0;const A=16;function D(){p!==null&&(window.clearTimeout(p),p=null)}function z(){i($=>$==="Event stream disconnected"?null:$)}function N(){f=null;const $=m;if(m=[],$.length===0)return;R=Date.now(),t($);const V=QF($);V.length>0&&r(re=>V.reduce(ls,re)),a(re=>{let X=re;for(const we of $)if(we.name==="approval.requested"&&we.data&&(X=[we.data,...X]),we.name==="approval.resolved"&&we.data&&typeof we.data=="object"){const ye=we.data;ye.approvalId&&(X=X.filter(K=>K.id!==ye.approvalId))}return X})}function x(){const $=Date.now()-R;if($>=A){f!==null&&(window.clearTimeout(f),f=null),N();return}f===null&&(f=window.setTimeout(N,A-$))}function I($){P($),m.push($),x()}function P($){if(!(!$.sessionId||!$.name.startsWith("harness.refiner."))){if($.name==="harness.refiner.completed"||$.name==="harness.refiner.failed"){k.delete($.sessionId);return}($.name==="harness.refiner.queued"||$.name==="harness.refiner.started")&&(k.set($.sessionId,typeof $.sequence=="number"?$.sequence:0),j())}}function j(){S!==null||k.size===0||(S=window.setTimeout(()=>{S=null,T()},1e3))}async function T(){if(!(y||k.size===0)){y=!0;try{await Promise.all([...k].map(async([$,V])=>{const re=await J.runtimeEventsPage(l,{sessionId:$,afterSequence:V,limit:100});for(const X of re.events){const we=X.event;k.set($,Math.max(k.get($)??0,X.sequence)),I(we)}}))}catch{}finally{y=!1,j()}}}function F(){f!==null&&(window.clearTimeout(f),f=null),N()}document.addEventListener("visibilitychange",F);const q=H$(n,$=>{D(),z(),I($)},()=>{D(),p=window.setTimeout(()=>{q.isOpen()||(i("Event stream disconnected"),s?.())},2e3)},()=>{D(),z()},{afterSequence:e});return()=>{D(),f!==null&&window.clearTimeout(f),S!==null&&window.clearTimeout(S),f=null,S=null,m=[],document.removeEventListener("visibilitychange",F),q.close()}},[e,t,n,s,a,i,r])}function QF(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const r=n.name==="session.started"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!r)continue;const i=im.safeParse(a[r]);i.success&&t.set(i.data.id,i.data)}return[...t.values()]}function $u(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function e5(e){return typeof e=="string"&&e.trim()?e.trim():null}function t5(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=$u(n.data),r=$u(a?.createImproveRun);if(r?.state!=="ready_local"&&r?.state!=="released"||$u(r.adapter)?.kind!=="local")continue;const s=e5(r.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const n5=332,nb=244,ab=560,a5=560,ob=320,rb=2400,o5=440;function Du(e){const t=typeof window>"u"?ab:Math.min(ab,Math.max(nb,window.innerWidth-420));return Math.min(t,Math.max(nb,Math.round(e)))}function Lu(e){const t=typeof window>"u"?rb:Math.min(rb,Math.max(ob,window.innerWidth-o5));return Math.min(t,Math.max(ob,Math.round(e)))}function r5(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const zr=new Map;function pf(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function Ek(e,t){const n=pf(e,t);if(!n)return null;const a=zr.get(n);return a?.updatedAt?a.agents:null}function i5(e,t,n){const a=pf(e,n);a&&zr.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function ff(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=pf(t,e.accountKey);if(!n)return Promise.resolve([]);const a=zr.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const r=e.fetchAgents(t).then(i=>(i5(t,i,e.accountKey),i)).catch(i=>{const s=zr.get(n);throw s?.promise===r&&zr.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),i});return zr.set(n,{agents:a?.agents??[],promise:r,updatedAt:a?.updatedAt??0}),r}const s5=6e4,l5=6e4,c5=6e4,hf=["pinned","projects","cloudProjects","chats","savedForLater"];function d5(e,t,n,a=Date.now()){for(const r of f5(t,n))Mk(t[r],n[r])||(e[r]=a)}function u5(e,t,n,a=Date.now()){const r={...t};for(const[i,s]of Object.entries(n)){if(a-s>s5){delete n[i];continue}const l=g5(e,i),p=e[i];!l||Mk(p,t[i])||(r[i]=p)}return r}function m5(e,t,n,a=Date.now()){for(const r of hf)t[r]!==n[r]&&(e[r]=a)}function p5(e,t,n,a=Date.now()){const r={...t};for(const i of hf){const s=n[i];if(s!==void 0){if(a-s>l5){delete n[i];continue}if(e[i]===t[i]){delete n[i];continue}r[i]=e[i]}}return h5(e,r)?e:r}function ib(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function sb(e,t,n=Date.now()){return t?n-t.changedAt>c5?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function f5(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function Mk(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function h5(e,t){return hf.every(n=>e[n]===t[n])}function g5(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const b5=5e4,co="\0openpond-unscoped-runtime-events",Ma=[];class v5{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=Ma;summaryEventsSnapshot=Ma;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=db(t.perSessionLimit??of,"perSessionLimit"),this.totalLimit=db(t.totalLimit??b5,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return cb();const n=new Map;let a=0;for(const m of t){if(this.eventKeyById.has(m.id)){a+=1;continue}const f=m.sessionId||co,S=n.get(f);S?S.push(m):n.set(f,[m]),this.eventKeyById.set(m.id,f)}if(n.size===0)return{...cb(),duplicateEventCount:a};const r=new Set;let i=0,s=0,l=!1;for(const[m,f]of n){f.some(ub)&&(l=!0);const S=this.entries.get(m),y=S?.snapshot.events??Ma,k=Math.max(0,Math.min(y.length,this.perSessionLimit-f.length)),R=f.length>this.perSessionLimit?f.slice(f.length-this.perSessionLimit):f,A=k===y.length?y:y.slice(y.length-k),D=A.length===0?R:[...A,...R],z=y.slice(0,y.length-A.length);z.some(ub)&&(l=!0);for(const I of z)this.eventKeyById.delete(I.id);for(const I of f.slice(0,f.length-R.length))this.eventKeyById.delete(I.id);const x={eventIds:new Set(D.map(I=>I.id)),lastTouched:++this.clock,retained:S?.retained??this.retainedKeys.has(m),snapshot:{events:D,latestSequence:Ql(D),revision:(S?.snapshot.revision??0)+1}};this.entries.set(m,x),this.eventCount+=D.length-y.length,i+=R.length,s+=z.length+f.length-R.length,r.add(m)}const p=this.enforceTotalLimit(r);return s+=p,this.publish(r,l||p>0),S5({acceptedEventCount:i,duplicateEventCount:a,evictedEventCount:s,changedKeys:r})}mergeBootstrap(t){const n=y5(t),a=new Set([...this.entries.keys(),...n.keys()]),r=[];for(const i of a){const s=n.get(i)??Ma,l=this.entries.get(i)?.snapshot.events??Ma;r.push(...XU(s,l))}return this.replace(r)}replace(t){const n=new Set(this.eventKeyById.keys()),a=new Set(this.entries.keys());this.entries.clear(),this.eventKeyById.clear(),this.eventCount=0,this.allEventsSnapshot=Ma,this.summaryEventsSnapshot=Ma;const r=this.append(t);for(const p of this.retainedKeys){const m=this.entries.get(p);m&&(m.retained=!0)}const i=this.eventKeyById;let s=0;for(const p of n)i.has(p)||(s+=1);const l=new Set([...a].filter(p=>!this.entries.has(p)));return l.size>0&&this.publish(l,!0),{...r,evictedEventCount:r.evictedEventCount+s,changedSessionIds:new Set([...r.changedSessionIds,...[...l].filter(p=>p!==co)]),unscopedEventsChanged:r.unscopedEventsChanged||l.has(co)}}clear(){if(this.entries.size===0)return;const t=new Set(this.entries.keys());this.entries.clear(),this.eventKeyById.clear(),this.eventCount=0,this.allEventsSnapshot=Ma,this.summaryEventsSnapshot=Ma,this.publish(t,!0)}retainSession(t,n=!0){n?this.retainedKeys.add(t):this.retainedKeys.delete(t);const a=this.entries.get(t);a&&(a.retained=n)}getSessionSnapshot=t=>t?this.entries.get(t)?.snapshot??lb:lb;getSessionEvents(t){return this.getSessionSnapshot(t).events}getAllEvents=()=>{if(this.allEventsSnapshot)return this.allEventsSnapshot;const t=[...this.entries.values()].flatMap(n=>n.snapshot.events);return t.sort(x5),this.allEventsSnapshot=t,t};getSummaryEvents=()=>this.summaryEventsSnapshot?this.summaryEventsSnapshot:(this.summaryEventsSnapshot=this.getAllEvents(),this.summaryEventsSnapshot);getStats(){let t=0;for(const[n,a]of this.entries)n!==co&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(co)?1:0),perSessionLimit:this.perSessionLimit,totalLimit:this.totalLimit}}subscribeAll=t=>(this.allListeners.add(t),()=>this.allListeners.delete(t));subscribeSummary=t=>(this.summaryListeners.add(t),()=>this.summaryListeners.delete(t));subscribeSession(t,n){let a=this.listenersByKey.get(t);return a||(a=new Set,this.listenersByKey.set(t,a)),a.add(n),()=>{a?.delete(n),a?.size===0&&this.listenersByKey.delete(t)}}enforceTotalLimit(t){let n=0;for(;this.eventCount>this.totalLimit&&this.entries.size>0;){const a=this.oldestEvictionCandidate(!1)??this.oldestEvictionCandidate(!0);if(!a)break;const[r,i]=a,s=this.eventCount-this.totalLimit;if(!i.retained||i.snapshot.events.length<=s){n+=i.snapshot.events.length,this.removeEntry(r),t.add(r);continue}const l=i.snapshot.events.slice(0,s),p=i.snapshot.events.slice(s);for(const m of l)this.eventKeyById.delete(m.id);i.eventIds=new Set(p.map(m=>m.id)),i.snapshot={events:p,latestSequence:Ql(p),revision:i.snapshot.revision+1},this.eventCount-=l.length,n+=l.length,t.add(r)}return n}oldestEvictionCandidate(t){let n=null;for(const a of this.entries)!t&&a[1].retained||(!n||a[1].lastTouched<n[1].lastTouched)&&(n=a);return n}removeEntry(t){const n=this.entries.get(t);if(n){for(const a of n.snapshot.events)this.eventKeyById.delete(a.id);this.eventCount-=n.snapshot.events.length,this.entries.delete(t)}}publish(t,n=!1){if(t.size!==0){this.allEventsSnapshot=null,n&&(this.summaryEventsSnapshot=null);for(const a of t)for(const r of this.listenersByKey.get(a)??[])r();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const lb=Object.freeze({events:Ma,latestSequence:null,revision:0});function y5(e){const t=new Map;for(const n of e){const a=n.sessionId||co,r=t.get(a);r?r.push(n):t.set(a,[n])}return t}function S5(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==co)),unscopedEventsChanged:e.changedKeys.has(co)}}function cb(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function x5(e,t){if(e.sequence!==void 0&&t.sequence!==void 0)return e.sequence-t.sequence;const n=Date.parse(e.timestamp)-Date.parse(t.timestamp);return Number.isFinite(n)&&n!==0?n:e.id.localeCompare(t.id)}function db(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function ub(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const k5=256,_5=15e3,w5=5e3,I5=3e4;class C5{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){R5(this.connection,t)||(this.connection=t,this.clear())}activateAccountScope(t){t!==this.accountScope&&(this.accountScope=t,this.clear())}get(t){const n=this.now(),a=this.entries.get(t);return a?this.expired(a,n)?(this.entries.delete(t),null):(a.lastAccessedAt=n,A5(this.entries,t,a),a.state==="ready"?a.url:null):null}load(t,n){const a=this.get(t);if(a)return Promise.resolve(a);const r=this.now(),i=this.entries.get(t);if(i?.state==="loading"&&!this.expired(i,r))return i.promise;if(i?.state==="failed"&&!this.expired(i,r))return Promise.resolve(null);const s=this.generation,l=n().then(p=>this.generation!==s?null:(this.entries.set(t,{state:"ready",url:p.url,expiresAt:p.expiresAt,lastAccessedAt:this.now()}),this.prune(),p.url)).catch(()=>{if(this.generation!==s)return null;const p=this.now();return this.entries.set(t,{state:"failed",expiresAt:p+(this.options.failureTtlMs??w5),lastAccessedAt:p}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:l,expiresAt:r+(this.options.loadingTtlMs??I5),lastAccessedAt:r}),this.prune(),l}clear(){this.generation+=1,this.entries.clear()}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,r]of this.entries)this.expired(r,t)&&this.entries.delete(a);const n=this.options.maxEntries??k5;for(;this.entries.size>n;){const a=this.entries.keys().next().value;if(!a)break;this.entries.delete(a)}}expired(t,n){const a=t.state==="ready"?this.options.expirySkewMs??_5:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const mb=new C5;function vW(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function R5(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function A5(e,t,n){e.delete(t),e.set(t,n)}const P5={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function T5(e){return{label:P5[e],ready:e==="ready",stage:e}}const E5=650,M5=1200,j5=6e4;function O5(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:r,setOpenPondCommandAccessMode:i,setError:s,setSelectedAppId:l,setSelectedProjectId:p,setSelectedSessionId:m}=e,[f,S]=g.useState(null),[y,k]=g.useState(null),[R]=g.useState(()=>new v5),A=g.useSyncExternalStore(R.subscribeSummary,R.getSummaryEvents,R.getSummaryEvents),D=g.useCallback(W=>{const de=R.getAllEvents(),he=typeof W=="function"?W(de):W;he!==de&&R.replace(he)},[R]),z=g.useCallback(W=>{R.append(W)},[R]),[N,x]=g.useState(null),[I,P]=g.useState([]),[j,T]=g.useState([]),[F,q]=g.useState([]),[$,V]=g.useState({}),[re,X]=g.useState("connecting"),we=Am(y?.account),ye=g.useRef({}),K=g.useRef({}),Ee=g.useRef({}),xe=g.useRef([]),se=g.useRef([]),ke=g.useRef(null),ee=g.useRef(null),pe=g.useRef(null),ve=g.useRef(null),qe=g.useRef(""),Re=g.useRef(!1),ie=g.useRef(Date.now()),Ie=g.useRef(null),$e=g.useRef(null);g.useEffect(()=>{mb.activateConnection(f),mb.activateAccountScope(we)},[f,we]);const Je=g.useCallback(W=>{Re.current||X(W)},[]),et=g.useCallback(W=>{V(de=>{const he=typeof W=="function"?W(de):W;return d5(ye.current,de,he),he})},[]),st=g.useCallback(W=>{P(de=>{const he=typeof W=="function"?W(de):W;return Lg(K.current,de,he),xe.current=he,he})},[]),Be=g.useCallback(W=>{T(de=>{const he=typeof W=="function"?W(de):W;return Lg(Ee.current,de,he),se.current=he,he})},[]),He=g.useCallback(()=>{if(Re.current||Ie.current!==null)return;const W=()=>{Ie.current=null,!Re.current&&(Re.current=!0,X("ready"))},de=Date.now()-ie.current,he=N5(de);if(he===0){W();return}Ie.current=window.setTimeout(W,he)},[]);g.useEffect(()=>()=>{Ie.current!==null&&window.clearTimeout(Ie.current)},[]);const Ne=g.useCallback(W=>{const de=ke.current,he=!de||de===W.server.id;ke.current=W.server.id,x(We=>We?.serverId===W.server.id?We:{afterSequence:W.eventWindow?.latestSequence??Ql(W.events)??0,serverId:W.server.id}),qe.current=W.preferences.defaultTeamId?.trim()??"",k(W),he?R.mergeBootstrap(W.events):R.replace(W.events),P(We=>{const Ze=he?Dg(We,W.sessions,K.current):Pm(We,W.sessions,K.current);return xe.current=Ze,Ze}),T(We=>{const Ze=he?Dg(We,W.codexHistorySessions??[],Ee.current):Pm(We,W.codexHistorySessions??[],Ee.current);return se.current=Ze,Ze}),q(W.approvals),V(We=>u5(We,W.sidebarAppPreferences,ye.current)),l(We=>We&&W.apps.some(Ze=>Ze.id===We)?We:null),p(We=>{if(!We)return null;const Ze=QS(We);return Ze?.kind==="local"&&W.localProjects.some(tt=>tt.id===Ze.id)?ht("local",Ze.id):Ze?.kind==="cloud"&&(W.cloudProjects??[]).some(tt=>tt.id===Ze.id)?ht("cloud",Ze.id):W.localProjects.some(tt=>tt.id===We)?ht("local",We):(W.cloudProjects??[]).some(tt=>tt.id===We)?ht("cloud",We):null}),m(We=>{if(!We)return null;const Ze=[...W.sessions,...W.codexHistorySessions??[]];if(Ze.some(at=>at.id===We&&!at.archived))return We;if(!he)return null;const tt=xe.current.find(at=>at.id===We)??se.current.find(at=>at.id===We)??null;return tt&&!tt.archived&&tk(tt,Ze)?We:null})},[R,l,p,m]),E=g.useCallback(W=>{qe.current=W.preferences.defaultTeamId?.trim()??"",k(de=>de&&{...de,preferences:W.preferences})},[]);g.useEffect(()=>{const W=Qn(y?.preferences);n(W.defaultChatProvider),t(W.defaultChatModel)},[y?.preferences.defaultChatProvider,y?.preferences.defaultChatModel,t,n]),g.useEffect(()=>{a($g(y?.preferences).codexPermissionMode)},[y?.preferences.codexPermissionMode,a]),g.useEffect(()=>{r($g(y?.preferences).codexReasoningEffort)},[y?.preferences.codexReasoningEffort,r]),g.useEffect(()=>{i(HF(y?.preferences).openPondCommandAccessMode)},[y?.preferences.openPondCommandAccessMode,i]),g.useEffect(()=>{if(!f||!y)return;const W=Lq(y.preferences),de=JSON.stringify(W);if(de==="{}"){ee.current=null;return}ee.current!==de&&(ee.current=de,J.savePreferences(f,W).then(E).catch(he=>{ee.current=null,s(he instanceof Error?he.message:String(he))}))},[E,y,y?.preferences.codexPermissionMode,y?.preferences.codexReasoningEffort,f,s]),g.useEffect(()=>{if(!f||!y)return;const W=qF(y.preferences),de=JSON.stringify(W);if(de==="{}"){pe.current=null;return}pe.current!==de&&(pe.current=de,J.savePreferences(f,W).then(E).catch(he=>{pe.current=null,s(he instanceof Error?he.message:String(he))}))},[E,y,y?.preferences.openPondCommandAccessMode,f,s]),g.useEffect(()=>{if(!f||!y){ve.current=null;return}if(y.account.state!=="signed_in"){ve.current=null,He();return}const W=Am(y.account);if(!W){ve.current=null,He();return}He(),Je("team");const de=y.preferences.defaultTeamId?.trim()??"",he=fb(W,de,y.accountMeta.asOf??"initial");if(ve.current===he)return;ve.current=he;let We=!1;const Ze=tt=>ff({teamId:tt,accountKey:W,fetchAgents:async at=>(await J.listSandboxAgents(f,{teamId:at})).agents}).catch(()=>{!We&&ve.current===he&&(ve.current=null)});return Ag({accountKey:W,force:!0,fetchOrganizations:()=>pb(f)}).then(async tt=>{if(We)return;if(tt.length===0){He();return}if(!!de&&tt.some(ae=>ae.teamId===de)){await Ze(de),He();return}const Te=nq(tt)?.teamId;if(!Te){He();return}const De=qe.current;if(De&&De!==de){He();return}const u=Ze(Te);ve.current=fb(W,Te,y.accountMeta.asOf??"initial");const M=await J.savePreferences(f,{defaultTeamId:Te});await u;const H=qe.current;if(We){H&&H!==Te&&J.savePreferences(f,{defaultTeamId:H}).then(E).catch(ae=>{s(ae instanceof Error?ae.message:String(ae))});return}if(H&&H!==Te){E(await J.savePreferences(f,{defaultTeamId:H})),He();return}We||(E(M),He())}).catch(tt=>{We||(ve.current=null,s(tt instanceof Error?tt.message:String(tt)),He())}),()=>{We=!0}},[Ne,E,y?.account,y?.accountMeta.asOf,y?.preferences.defaultTeamId,He,f,Je,s]),g.useEffect(()=>{if(!f||!we)return;let W=!1;const de=()=>{W||(W=!0,Ag({accountKey:we,force:!0,fetchOrganizations:()=>pb(f)}).catch(()=>{}).finally(()=>{W=!1}))},he=()=>{document.visibilityState==="visible"&&de()},We=window.setInterval(de,j5);return window.addEventListener("focus",de),document.addEventListener("visibilitychange",he),()=>{window.clearInterval(We),window.removeEventListener("focus",de),document.removeEventListener("visibilitychange",he)}},[f,we]);const U=g.useCallback(async()=>{Je("connecting"),x(null);const W=await sD();S(he=>r5(he,W)?he:W),Je("account");const de=await J.bootstrap(W);Ne(de),He(),s(he=>he&&(hx(he)||he==="Event stream disconnected")?null:he)},[Ne,He,Je,s]);g.useEffect(()=>{let W=!1,de=null;const he=async We=>{try{await U()}catch(Ze){if(W)return;s(Ze instanceof Error?Ze.message:String(Ze));const tt=Math.min(5e3,750+We*750);de=window.setTimeout(()=>{he(We+1)},tt)}};return he(0),()=>{W=!0,de!==null&&window.clearTimeout(de)}},[U,s]);const G=g.useCallback(()=>{U().catch(()=>{})},[U]);XF({afterSequence:N?.afterSequence??null,appendEvents:z,connection:f,setApprovals:q,setSessions:st,setError:s,onDisconnected:G}),g.useEffect(()=>{if(!f||!y){$e.current=null;return}const W=t5(A);!W||$e.current===W||($e.current=W,J.profileCurrent(f).then(de=>{k(he=>he&&{...he,profile:de})}).catch(de=>{$e.current=null,s(de instanceof Error?de.message:String(de))}))},[y,f,A,s]);const me=g.useCallback(()=>{f&&J.refreshOpenPondAccount(f).then(({account:W,accountMeta:de})=>{k(he=>he&&{...he,account:W,accountMeta:de})}).catch(W=>s(W instanceof Error?W.message:String(W)))},[f,s]);return{appPreferences:$,applyBootstrapPayload:Ne,approvals:F,bootstrap:y,codexHistorySessions:j,connection:f,events:A,runtimeEventStore:R,refreshOpenPondAccount:me,sessions:I,startup:T5(re),setAppPreferences:et,setBootstrap:k,setCodexHistorySessions:Be,setEvents:D,setSessions:st}}async function pb(e){return(await J.organizations(e)).organizations.map(Mc).filter(n=>!!n).filter(n=>n.status==="active")}function N5(e){return e>=M5?0:Math.max(0,E5-e)}function fb(e,t,n){return`${e}::${t||"none"}::${n}`}function $5({appDispatch:e,error:t,setErrorState:n}){const a=g.useRef(null),r=g.useRef(null),i=g.useRef(null),s=g.useRef(0),l=g.useCallback((f,S="info",y={})=>{const k=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:k,message:f,tone:S,...y}}),k},[e]),p=g.useCallback(()=>{e({type:"patch",patch:{settingsSection:"diagnostics",sidebarOpen:!0,view:"settings"}})},[e]),m=g.useCallback(f=>{const S=r.current,y=typeof f=="function"?f(S):f;if(Object.is(S,y))return;if(r.current=y,n(y),!y){i.current!==null&&(e({type:"clearToast",toastId:i.current}),i.current=null);return}i.current=l(D5(y),"error",{actionLabel:"Open diagnostics settings",actionIcon:"settings",onAction:p,dismissible:!0});const k=a.current;k&&J.recordClientDiagnostic(k,{message:y,surface:"app",context:{href:window.location.href}}).catch(R=>{console.warn("Unable to record client diagnostic.",R)})},[e,p,n,l]);return g.useEffect(()=>{r.current=t,!(t||i.current===null)&&(e({type:"clearToast",toastId:i.current}),i.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:l}}function D5(e){return fx(e)}const L5={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:jn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Zo,draftModel:bs,draftExperience:"chat",codexPermissionMode:uc,codexReasoningEffort:mc,openPondCommandAccessMode:Es,busy:!1,diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[],terminalOpen:!1,syncingWorkspaceAppId:null,settingsSection:"account",newProjectDialogOpen:!1,newProjectMode:"local",newProjectName:"",newProjectPath:"",newProjectBusy:!1,commitDialogOpen:!1,commitMessage:"",commitIncludeUnstaged:!0,commitNextStep:"commit",commitDraft:!0,branchDialogOpen:!1,branchDialogName:"",toast:null,error:null};function gf(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function nc(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...r}=e;return r}return e[t]===n?e:{...e,[t]:n}}function z5(e){return nc(e.promptDrafts,gf(e),e.prompt)}function as(e,t,n={}){const a={...e,...t},r=gf(a),i=z5(e),s=n.clearSelectedDraft?nc(i,r,""):n.preserveCurrentPrompt?nc(i,r,e.prompt):i;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[r]??""}}function U5(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function H5(e,t){switch(t.type){case"field":{const n=e[t.key],a=typeof t.value=="function"?t.value(n):t.value;if(Object.is(n,a))return e;if(t.key==="prompt"){const r=String(a);return{...e,prompt:r,promptDrafts:nc(e.promptDrafts,gf(e),r)}}return U5(t.key)?as(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return as(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return as(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return as(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return as(e,{selectedSessionId:null,selectedAppId:t.appId,selectedProjectId:null,error:null,view:"chat"},{clearSelectedDraft:!0});case"openCommitDialog":return{...e,commitMessage:"",commitIncludeUnstaged:!0,commitNextStep:t.nextStep,commitDraft:!0,commitDialogOpen:!0,error:null,view:"chat"};case"openBranchDialog":return{...e,branchDialogName:t.branchName,branchDialogOpen:!0,error:null,view:"chat"};case"showToast":return{...e,toast:t.toast};case"clearToast":return e.toast?.id===t.toastId?{...e,toast:null}:e;default:return e}}function mt(e,t){return n=>e({type:"field",key:t,value:n})}function q5(e){return{setQuery:mt(e,"query"),setSearchOpen:mt(e,"searchOpen"),setArchivedChatsOpen:mt(e,"archivedChatsOpen"),setSectionMenuOpen:mt(e,"sectionMenuOpen"),setProjectsExpanded:mt(e,"projectsExpanded"),setCloudProjectsExpanded:mt(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:mt(e,"chatRowsVisibleCount"),setSidebarOpen:mt(e,"sidebarOpen"),setView:mt(e,"view"),setSelectedAppId:mt(e,"selectedAppId"),setSelectedProjectId:mt(e,"selectedProjectId"),setSelectedSessionId:mt(e,"selectedSessionId"),setPrompt:mt(e,"prompt"),setDraftProvider:mt(e,"draftProvider"),setDraftModel:mt(e,"draftModel"),setDraftExperience:mt(e,"draftExperience"),setCodexPermissionMode:mt(e,"codexPermissionMode"),setCodexReasoningEffort:mt(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:mt(e,"openPondCommandAccessMode"),setBusy:mt(e,"busy"),setDiffPanelOpen:mt(e,"diffPanelOpen"),setDiffPanelExpanded:mt(e,"diffPanelExpanded"),setRightPanelMode:mt(e,"rightPanelMode"),setRightChatPanels:mt(e,"rightChatPanels"),setTerminalOpen:mt(e,"terminalOpen"),setSyncingWorkspaceAppId:mt(e,"syncingWorkspaceAppId"),setSettingsSection:mt(e,"settingsSection"),setNewProjectDialogOpen:mt(e,"newProjectDialogOpen"),setNewProjectMode:mt(e,"newProjectMode"),setNewProjectName:mt(e,"newProjectName"),setNewProjectPath:mt(e,"newProjectPath"),setNewProjectBusy:mt(e,"newProjectBusy"),setCommitDialogOpen:mt(e,"commitDialogOpen"),setCommitMessage:mt(e,"commitMessage"),setCommitIncludeUnstaged:mt(e,"commitIncludeUnstaged"),setCommitNextStep:mt(e,"commitNextStep"),setCommitDraft:mt(e,"commitDraft"),setBranchDialogOpen:mt(e,"branchDialogOpen"),setBranchDialogName:mt(e,"branchDialogName"),setToast:mt(e,"toast"),setError:mt(e,"error")}}function zu(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function B5(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,r=new Set,i=m=>{if(!Object.is(n,m)){n=m;for(const f of r)f()}},s=()=>{const m=zu(t);n?a.set(m,n):a.delete(m)},l=(m,f={})=>{const S=n;s(),t={...t,...m};const y=zu(t);if(f.clear&&a.delete(y),f.preserveCurrentDraft){S?a.set(y,S):a.delete(y),i(S);return}i(f.clear?"":a.get(y)??"")},p={getSnapshot:()=>n,subscribe(m){return r.add(m),()=>r.delete(m)},set(m){const f=typeof m=="function"?m(n):m;if(Object.is(n,f))return;const S=zu(t);f?a.set(S,f):a.delete(S),i(f)},applyAppAction(m){if(m.type==="field"){if(m.key==="prompt"){p.set(m.value);return}if(m.key==="selectedAppId"||m.key==="selectedProjectId"||m.key==="selectedSessionId"){const f=t[m.key],S=typeof m.value=="function"?m.value(f):m.value;Object.is(f,S)||l({[m.key]:S})}return}if(m.type==="patch"){const f={};"selectedAppId"in m.patch&&(f.selectedAppId=m.patch.selectedAppId),"selectedProjectId"in m.patch&&(f.selectedProjectId=m.patch.selectedProjectId),"selectedSessionId"in m.patch&&(f.selectedSessionId=m.patch.selectedSessionId),Object.keys(f).length>0&&l(f),"prompt"in m.patch&&typeof m.patch.prompt=="string"&&p.set(m.patch.prompt);return}if(m.type==="selectApp"){l({selectedAppId:m.appId,selectedProjectId:null,selectedSessionId:null});return}if(m.type==="selectProject"){l({selectedAppId:null,selectedProjectId:m.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(m.type==="selectSession"){const f=m.projectId??null;l({selectedSessionId:m.sessionId,selectedAppId:f?null:m.appId??null,selectedProjectId:f});return}m.type==="beginNewChat"&&l({selectedSessionId:null,selectedAppId:m.appId,selectedProjectId:null},{clear:!0})}};return p}function yW(e){return g.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function F5(e){return{...e,draftExperience:Hx()}}function V5(){const[e,t]=g.useReducer(H5,L5,F5),[n]=g.useState(()=>B5()),a=g.useCallback(i=>{n.applyAppAction(i),t(i)},[n]),r=g.useMemo(()=>({...q5(a),setPrompt:n.set}),[n,a]);return{composerDraftStore:n,dispatch:a,setters:r,state:e}}function W5(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function K5(e){const{connection:t,events:n,showToast:a}=e,r=g.useRef(new Set),i=g.useCallback(async()=>{if(t)try{const l=await J.installMacOSCommandLineTools(t);a(l.message,"info")}catch(l){a(l instanceof Error?l.message:String(l),"error")}},[t,a]),s=g.useCallback((l="OpenPond needs Git to create and sync local projects.")=>{a(l,"error",{actionLabel:"Install Tools",onAction:()=>{i()},persistent:!0})},[a,i]);g.useEffect(()=>{if(!t)return;let l=!1;return J.gitAvailability(t).then(p=>{l||p.ok||p.installAction!=="macos_command_line_tools"||s("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{l=!0}},[t,s]),g.useEffect(()=>{for(const l of n){if(r.current.has(l.id))continue;const p=l.error??l.output??null;l.name==="workspace_action_result"&&l.status==="failed"&&W5(p)&&(r.current.add(l.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function G5({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:r,setError:i}){const[s,l]=g.useState(()=>Qn().sidebarSectionsCollapsed),p=g.useRef(s),m=g.useRef({}),f=g.useRef(null),S=g.useRef(null),[y,k]=g.useState(n5),[R,A]=g.useState(!1),[D,z]=g.useState(a5),[N,x]=g.useState(!1),{pinned:I,projects:P,cloudProjects:j,chats:T,savedForLater:F}=s;g.useEffect(()=>{if(R)return;const ee=Du(Qn(t).sidebarWidth),pe=sb(ee,f.current);f.current=pe.localChange,k(pe.value)},[t,R]),g.useEffect(()=>{if(N)return;const ee=Lu(Qn(t).diffPanelWidth),pe=sb(ee,S.current);S.current=pe.localChange,z(pe.value)},[N,t]),g.useEffect(()=>{const ee=Qn(t).sidebarSectionsCollapsed;l(pe=>{const ve=p5(pe,ee,m.current);return p.current=ve,ve})},[t]);const q=g.useCallback(ee=>{r(pe=>pe&&{...pe,preferences:ee.preferences})},[r]),$=g.useCallback(async ee=>{if(e&&Du(Qn(t).sidebarWidth)!==ee)try{q(await J.savePreferences(e,{sidebarWidth:ee}))}catch(pe){i(pe instanceof Error?pe.message:String(pe))}},[e,t,i,q]),V=g.useCallback(async ee=>{if(e&&Lu(Qn(t).diffPanelWidth)!==ee)try{q(await J.savePreferences(e,{diffPanelWidth:ee}))}catch(pe){i(pe instanceof Error?pe.message:String(pe))}},[e,t,i,q]),re=g.useCallback(async ee=>{if(!e)return;const pe=Qn(t).sidebarSectionsCollapsed;if(!Z5(pe,ee))try{q(await J.savePreferences(e,{sidebarSectionsCollapsed:ee}))}catch(ve){i(ve instanceof Error?ve.message:String(ve))}},[e,t,i,q]),X=g.useCallback(ee=>{const pe=p.current;m5(m.current,pe,ee),p.current=ee,l(ee),re(ee)},[re]),we=g.useCallback(()=>{const ee=p.current;X({...ee,pinned:!ee.pinned})},[X]),ye=g.useCallback(()=>{const ee=p.current;X({...ee,projects:!ee.projects})},[X]),K=g.useCallback(()=>{const ee=p.current;X({...ee,cloudProjects:!ee.cloudProjects})},[X]),Ee=g.useCallback(()=>{const ee=p.current;X({...ee,chats:!ee.chats})},[X]),xe=g.useCallback(()=>{const ee=p.current;X({...ee,savedForLater:!ee.savedForLater})},[X]),se=g.useCallback(ee=>{if(!n)return;ee.preventDefault();const pe=ee.clientX,ve=y;let qe=ve;A(!0);function Re(Ie){qe=Du(ve+Ie.clientX-pe),k(qe)}function ie(){window.removeEventListener("pointermove",Re),window.removeEventListener("pointerup",ie);const Ie=ib(ve,qe);Ie&&(f.current=Ie),A(!1),$(qe)}window.addEventListener("pointermove",Re),window.addEventListener("pointerup",ie,{once:!0})},[$,n,y]),ke=g.useCallback(ee=>{if(a)return;ee.preventDefault();const pe=ee.clientX,ve=D;let qe=ve;x(!0);function Re(Ie){qe=Lu(ve-(Ie.clientX-pe)),z(qe)}function ie(){window.removeEventListener("pointermove",Re),window.removeEventListener("pointerup",ie);const Ie=ib(ve,qe);Ie&&(S.current=Ie),x(!1),V(qe)}window.addEventListener("pointermove",Re),window.addEventListener("pointerup",ie,{once:!0})},[a,D,V]);return{pinnedCollapsed:I,projectsCollapsed:P,cloudProjectsCollapsed:j,chatsCollapsed:T,savedForLaterCollapsed:F,sidebarWidth:y,sidebarResizing:R,diffPanelWidth:D,diffPanelResizing:N,togglePinnedCollapsed:we,toggleProjectsCollapsed:ye,toggleCloudProjectsCollapsed:K,toggleChatsCollapsed:Ee,toggleSavedForLaterCollapsed:xe,startSidebarResize:se,startDiffPanelResize:ke}}function Z5(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function J5(e){const[t,n]=g.useState({id:0,kind:null}),[a,r]=g.useState(null),i=g.useCallback((m=null)=>{n(f=>({id:f.id+1,kind:m}))},[]),s=g.useCallback(m=>{r(m)},[]),l=null,p=g.useMemo(()=>{if(e)return Y5(a,i)},[e,a,i]);return{backAction:l,breadcrumbs:p,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function Y5(e,t){return e?e.kind==="dataset"?[{label:"Models",onSelect:()=>t(null)},{label:"Tasksets",onSelect:()=>t("dataset")},...e.workproductLabel?[{label:e.workproductLabel,onSelect:e.workproductOnSelect}]:[],...e.segments]:[{label:"Models",onSelect:()=>t(null)},{label:e.kindLabel,onSelect:e.kindOnSelect??(()=>t(e.kind==="model"?null:e.kind))},...e.workproductLabel?[{label:e.workproductLabel,onSelect:e.workproductOnSelect}]:[],...e.segments]:[{label:"Models"}]}function X5(e){const{connection:t,profileId:n}=e,[a,r]=g.useState(null),[i,s]=g.useState(!1),[l,p]=g.useState(null),[m,f]=g.useState(null),S=g.useRef(null),y=g.useRef(null),k=g.useCallback(()=>{if(!t)return Promise.resolve(null);if(S.current)return S.current;s(!0);const x=J.trainingState(t,n).then(I=>(y.current=I.activityRevision??null,r(I),f(null),I)).catch(I=>(f(Lo(I)),null)).finally(()=>{S.current===x&&(S.current=null,s(!1))});return S.current=x,x},[t,n]),R=g.useCallback(async()=>(S.current&&await S.current,k()),[k]),A=g.useCallback(async(x,I,P,j="POST",T={})=>{if(!t)return null;T.silent||p(x);try{const F=await J.trainingRequest(t,I,P,j);return await R(),T.silent||f(null),F}catch(F){return T.silent||f(Lo(F)),null}finally{T.silent||p(null)}},[t,R]);g.useEffect(()=>{if(y.current=null,!t){r(null);return}k()},[t,n,k]);const D=a?[a.jobs.some(x=>["queued","starting","running","cancelling","reconciling"].includes(x.status)),a.creations.some(x=>["planning","materializing","validating"].includes(x.state)),a.minerRuns.some(x=>["queued","running","cancelling"].includes(x.status)),a.datasetImports.some(x=>["inspecting","materializing","validating","cancelling"].includes(x.status))].some(Boolean):!1;g.useEffect(()=>{if(!t)return;let x=!0,I=null;const P=D?500:3e4,j=async()=>{let T=P;try{const F=await J.trainingActivity(t,n);T=F.active?500:3e4,(y.current===null||y.current!==F.revision)&&await k()}catch(F){f(Lo(F))}x&&(I=window.setTimeout(()=>{j()},T))};return I=window.setTimeout(()=>{j()},P),()=>{x=!1,I!==null&&window.clearTimeout(I)}},[t,D,n,k]);const z=g.useMemo(()=>({saveModelProject:x=>A("save-model-project","/models",x,"PUT"),syncModelProject:x=>A("sync-model-project",`/models/${encodeURIComponent(x)}/sync`,{}),publishModelProjectTaskset:(x,I)=>A("publish-model-project-taskset",`/models/${encodeURIComponent(x)}/tasksets/${encodeURIComponent(I)}/publish`,{}),createTasksetDraft:(x="")=>A("create-taskset-draft","/taskset-drafts",{profileId:n,name:x}),saveTasksetDraft:x=>A("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(x.id)}`,x,"PUT"),tasksetDraftWorkspace:async x=>{if(!t)return null;try{return await J.trainingRequest(t,`/taskset-drafts/${encodeURIComponent(x)}/workspace`,{},"GET")}catch(I){return f(Lo(I)),null}},publishTasksetDraft:(x,I)=>A("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(x)}/publish`,{modelId:I??null}),deleteTasksetDraft:x=>A("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(x)}`,{},"DELETE"),inspectHuggingFaceDataset:x=>A("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:x}),materializeDatasetImport:(x,I)=>A("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/materialize`,I),cancelDatasetImport:x=>A("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/cancel`,{}),datasetRows:(x,I={})=>{if(!t)return Promise.resolve(null);const P=new URLSearchParams;I.split&&P.set("split",I.split),I.cursor&&P.set("cursor",I.cursor),P.set("limit",String(I.limit??25));for(const j of I.columns??[])P.append("column",j);return J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/rows?${P}`,{},"GET")},addSource:(x,I)=>A("add-source","/sources",{profileId:n,sessionId:x,turnIds:I}),addSources:x=>A("add-sources","/sources/batch",{profileId:n,sessionIds:x}),estimateSources:x=>t?J.trainingRequest(t,"/sources/estimate",{sessionIds:x}):Promise.resolve([]),searchChats:(x,I,P=0,j=20)=>t?J.trainingRequest(t,"/sources/search",{query:x,candidates:I,offset:P,limit:j}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:x,offset:P,limit:j,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:x=>A("remove-source",`/sources/${encodeURIComponent(x)}`,{},"DELETE"),deleteTaskset:x=>A("delete-model",`/tasksets/${encodeURIComponent(x)}`,{},"DELETE"),runBenchmark:(x,I,P,j)=>A(`run-benchmark-${I}`,`/tasksets/${encodeURIComponent(x)}/benchmark-runs`,{phase:I,model:P,reasoningEffort:j,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(x,I,P)=>A("run-harness-refiner-benchmark",`/models/${encodeURIComponent(x)}/harness-refiner-benchmark`,{profileId:n,model:I,reasoningEffort:P,maximumSpendUsd:10}),acceptHarnessReview:(x,I,P=null,j=null)=>A("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:x,reviewRef:I,analysisModel:P,analysisReasoningEffort:j}),startCreation:(x,I={})=>A("create-taskset","/task-creations",{profileId:n,sourceIds:x,surface:I.surface??"training_page",mode:I.mode??"defaults",entryMode:I.entryMode??"manual",resourceIntent:I.resourceIntent??"workproduct",buildIntent:I.buildIntent??"demonstrations",buildSpecification:I.buildSpecification??null,objective:I.objective??null,methodHint:I.methodHint??null,preferredBaseModelId:I.preferredBaseModel?.modelId??null,preferredBaseModel:I.preferredBaseModel??null,candidateId:I.candidateId??null,analysisModel:I.analysisModel??null,analysisReasoningEffort:I.analysisReasoningEffort??null,createImproveRunId:I.createImproveRunId??null,targetIntent:I.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(x,I)=>A("create-model","/models/from-taskset",{profileId:n,tasksetId:x,preferredBaseModelId:I.modelId,preferredBaseModel:I}),scanBaseModels:async()=>{if(!t)return null;p("scan-base-models");try{const x=await k();return f(null),x}catch(x){return f(Lo(x)),null}finally{p(null)}},approveDisclosure:(x,I)=>A("approve-disclosure",`/task-creations/${encodeURIComponent(x)}/disclosure`,{approved:I}),retryCreation:x=>A("retry-creation",`/task-creations/${encodeURIComponent(x)}/retry`,{}),answerQuestions:(x,I)=>A("answer-questions",`/task-creations/${encodeURIComponent(x)}/questions`,{answers:I}),materialize:(x,I)=>A("materialize",`/task-creations/${encodeURIComponent(x)}/materialize`,{approved:I}),chatCreation:(x,I)=>A("task-creator-chat",`/task-creations/${encodeURIComponent(x)}/chat`,{message:I}),renameCreation:(x,I)=>A("rename-creation",`/task-creations/${encodeURIComponent(x)}/name`,{name:I},"PATCH"),cancelCreation:x=>A("cancel-creation",`/task-creations/${encodeURIComponent(x)}/cancel`,{}),runMiner:(x=[],I=[],P)=>A("run-miner","/miner/run",{profileId:n,sourceIds:x,sessionIds:I,config:P}),cancelMinerRun:x=>A("cancel-miner-run",`/miner/runs/${encodeURIComponent(x)}/cancel`,{}),configureMiner:x=>A("configure-miner","/miner/config",{profileId:n,config:x},"PUT"),patchCandidate:(x,I)=>A("candidate",`/candidates/${encodeURIComponent(x)}`,I,"PATCH"),createCandidate:(x,I,P,j)=>A("create-candidate",`/candidates/${encodeURIComponent(x)}/create`,{mode:I,analysisModel:P??null,analysisReasoningEffort:j??null}),auditGraders:x=>A("audit-graders","/audit-graders",{tasksetId:x}),executeTasksetAttempt:(x,I,P)=>A("execute-taskset-attempt",`/tasksets/${encodeURIComponent(x)}/attempts`,{taskId:I,model:P,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:x=>A("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(x.tasksetId)}/synthetic-preference-collection`,x),tasksetOperationalState:x=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:x=>A("calibrate-judges","/calibrate-judges",{tasksetId:x}),nextPreferenceComparison:(x,I)=>A("next-preference-comparison",`/tasksets/${encodeURIComponent(x)}/preference-comparisons/next`,{reviewerKey:I}),submitPreferenceComparison:x=>A("submit-preference-comparison",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/submit`,x),submitSyntheticFixturePreference:x=>A("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/fixture-submit`,{...x,id:crypto.randomUUID()}),listPreferenceDatasets:x=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:x=>A("materialize-preference-dataset",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-datasets`,{...x,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:x=>A("launch-reward-model-run",`/tasksets/${encodeURIComponent(x.tasksetId)}/reward-model-runs`,{...x,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:x=>A("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(x.tasksetId)}/learned-preference-reward-binding`,x),retryRewardModelQualification:x=>A("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(x.runId)}/retry-qualification`,x),cancelRewardModelRun:x=>A("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(x)}/cancel`,{}),markPreferenceComparisonUnreviewable:x=>A("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/unreviewable`,x),preferenceCalibrationStatus:(x,I,P)=>{if(!t)return Promise.resolve(null);const j=new URLSearchParams({reviewerKey:I});return P&&j.set("comparisonReleaseId",P),J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-comparisons/calibration/status?${j}`,{},"GET")},startPreferenceCalibrationBatch:x=>A("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches`,{...x,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:x=>A("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(x.jobId)}/sync`,x),reviewPreferenceComparisonWithModel:x=>A("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/model-review`,{...x,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:x=>A("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...x,id:crypto.randomUUID()}),savePreferenceCalibration:x=>A("save-preference-calibration",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/report`,{...x,id:crypto.randomUUID()}),preferenceArtifactUrl:async x=>{if(!t)return null;const I=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!I.ok)throw new Error(await I.text());return URL.createObjectURL(await I.blob())},readiness:x=>A("readiness","/readiness",{tasksetId:x}),previewExpertBootstrap:x=>A("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(x,I)=>A("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/approve`,{previewHash:I}),createPlan:x=>A("create-plan","/plans",{...x,tasksetId:x.tasksetId}),buildBundle:x=>A("build-bundle","/bundles",{planId:x}),approveTraining:(x,I)=>A("approve-training","/approvals",{planId:x,bundleId:I}),launch:(x,I)=>A("launch","/launch",{planId:x,approvalId:I}),prepareTraining:x=>A("prepare-training","/prepare",x),prepareModelRun:(x,I)=>A("prepare-model-run",`/model-projects/${encodeURIComponent(x)}/training/prepare`,I),startModelRun:(x,I)=>A("start-model-run",`/model-projects/${encodeURIComponent(x)}/training/start`,I),startPreparedTraining:x=>A("start-prepared-training","/start/prepared",x),startTraining:x=>A("start-training","/start",x),cancelJob:x=>A("cancel-job",`/jobs/${encodeURIComponent(x)}/cancel`,{}),rejectModel:(x,I)=>A("reject-model",`/models/${encodeURIComponent(x)}/reject`,{reason:I}),bindModel:(x,I,P)=>A("bind-model",`/models/${encodeURIComponent(x)}/bind`,{profileId:n,role:I,roleTargetId:P,promotedBy:n}),rollbackModelBinding:x=>A("rollback-model-binding",`/bindings/${encodeURIComponent(x)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(x,I)=>A("update-model-configuration",`/models/${encodeURIComponent(x)}/configuration`,I,"PATCH",{silent:!0}),setModelPinned:(x,I)=>A("pin-model-version",`/models/${encodeURIComponent(x)}/pin`,{pinned:I},"PATCH"),downloadArtifact:async x=>{if(!t)return!1;p("download-artifact");try{const I=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!I.ok)throw new Error(await I.text());const P=I.headers.get("content-disposition")??"",j=/filename="([^"]+)"/.exec(P)?.[1]??"openpond-model-artifact",T=URL.createObjectURL(await I.blob()),F=document.createElement("a");return F.href=T,F.download=j,F.click(),URL.revokeObjectURL(T),!0}catch(I){return f(Lo(I)),!1}finally{p(null)}},downloadModelPackage:async x=>N(`/models/${encodeURIComponent(x)}/download`,`${x}.openpond-lora.tar`),downloadBundle:async x=>N(`/bundles/${encodeURIComponent(x)}/download`,"openpond-model-improvement-bundle.json")}),[t,A,n,k]);async function N(x,I){if(!t)return!1;p("download-bundle");try{const P=await fetch(`${t.serverUrl}/v1/training${x}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());const j=P.headers.get("content-disposition")??"",T=/filename="([^"]+)"/.exec(j)?.[1]??I,F=URL.createObjectURL(await P.blob()),q=document.createElement("a");return q.href=F,q.download=T,q.click(),URL.revokeObjectURL(F),!0}catch(P){return f(Lo(P)),!1}finally{p(null)}}return{connection:t,payload:a,loading:i,busyAction:l,error:m,refresh:k,actions:z}}function Lo(e){return e instanceof Error?e.message:String(e)}function SW({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===zs?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?n4(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:a4(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function Or(e){return e?.tasks.length?e.tasks[Nk(e,e.selectedTaskIndex)]??null:null}function jk(e,t){return{...e,selectedTaskIndex:Nk(e,t)}}function Q5(e){return jk(e,e.selectedTaskIndex+1)}function e4(e,t,n){if(!e||Ok(e,n))return null;const a=Or(e);return!a||t.trim()!==a.prompt.trim()?null:{...e.taskRuntime==="cross_system"?{crossSystemTaskId:a.generatedTaskId}:{trainingHarnessTaskId:a.generatedTaskId},trainingTasksetId:e.tasksetId,trainingTasksetName:e.tasksetName,source:"training_model_chat_handoff"}}function Ok(e,t){return!e?.sourceProjectId||e.sourceProjectId===t?null:"This generated Taskset question is bound to its source Cross-System Operations project. Return to Models and choose Chat again to restore the correct project."}async function t4({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function n4(e,t){const n=new Set;return e.tasks.flatMap(a=>{const r=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,i=typeof r=="string"?r.trim():"",s=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!i||!s||n.has(i)?[]:(n.add(i),[{authoredTaskId:a.id,generatedTaskId:i,prompt:s,split:a.split}])})}function a4(e){const t=new Set(e.sourceRefs.filter(lM).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function Nk(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function o4({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:r,connection:i,requestComposerFocus:s,selectedLocalProjectId:l,selectedSessionId:p,selectLocalProject:m,setDraftModel:f,setDraftProvider:S,setError:y,view:k}){const[R,A]=g.useState(null),D=g.useCallback(T=>{T.sourceProjectId?m(T.sourceProjectId):a(null)},[a,m]),z=g.useCallback(T=>{if(!R)return;const F={...jk(R,T),sessionId:R.sessionId?null:R.sessionId},q=Or(F);A(F),q&&(R.sessionId&&D(F),r.set(q.prompt),s())},[D,r,R,s]),N=g.useCallback(()=>{const T=Or(R);T&&r.getSnapshot().trim()===T.prompt.trim()&&r.set(""),A(null)},[r,R]),x=g.useCallback(T=>{const F=T.model;t4({model:F,connection:i,loadBootstrap:J.bootstrap,applyBootstrap:n}).then(()=>{const q={...T,selectedTaskIndex:0,sessionId:null};S(F.providerId),f(F.modelId),A(q.tasks.length?q:null),D(q);const $=Or(q);$&&r.set($.prompt)}).catch(y)},[n,D,r,i,f,S,y]),I=g.useCallback(T=>{const F=!!(R&&R.model.providerId===t&&R.model.modelId===e);return{active:F,error:F?Ok(R,l):null,metadata:F?e4(R,T,l):null}},[e,t,R,l]),P=g.useCallback(T=>{A(F=>F&&{...F,sessionId:T})},[]),j=g.useCallback(()=>{if(!R)return;const T={...Q5(R),sessionId:null},F=Or(T);A(T),F&&(D(T),r.set(F.prompt),s())},[D,r,R,s]);return g.useEffect(()=>{const T=Or(R);!T||k!=="chat"||p||r.set(F=>F.trim()?F:T.prompt)},[r,R,l,p,k]),g.useEffect(()=>{R&&p&&R.sessionId!==p&&A(null)},[R?.sessionId,p]),{advanceAfterTurn:j,begin:x,bindSession:P,dismiss:N,handoff:R,prepareTurn:I,selectTask:z}}const os=[],Uu=500;function r4(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:r,runtimeIndexes:i,runtimeEventStore:s,selectedSessionId:l,serverId:p,setCodexHistoryEvents:m,setCodexHistorySessions:f,setError:S}=e,[y,k]=g.useState({}),[R,A]=g.useState({}),D=g.useRef(new Set);g.useEffect(()=>{k({}),A({}),D.current.clear()},[p]);const z=g.useCallback(async()=>{if(!a||!l||D.current.has(l))return!1;const j=R[l];if(j?.hasMore===!1)return!1;if(Mt(l)){const q=Math.max(j?.totalMatchingEvents??0,n.length,ok),$=Math.min(zg,Math.max(Vq,q*2));D.current.add(l),A(V=>({...V,[l]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:V[l]?.totalMatchingEvents??n.length}}));try{const V=await rk(a,l,{force:!0,limit:$,tail:!1});return m(V.events),f(re=>jc(re,V.session)),A(re=>({...re,[l]:{cursorSequence:null,hasMore:V.events.length>=$&&$<zg,loading:!1,totalMatchingEvents:$}})),V.events.length>n.length}catch(V){return S(V instanceof Error?V.message:String(V)),A(re=>({...re,[l]:{cursorSequence:null,hasMore:re[l]?.hasMore??!0,loading:!1,totalMatchingEvents:re[l]?.totalMatchingEvents??n.length}})),!1}finally{D.current.delete(l)}}const T=Ka(y[l]??os,s.getSessionEvents(l)),F=j?.cursorSequence??i4(T);if(!F)return!1;D.current.add(l),A(q=>({...q,[l]:{cursorSequence:q[l]?.cursorSequence??F,hasMore:q[l]?.hasMore??!0,loading:!0,totalMatchingEvents:q[l]?.totalMatchingEvents??null}}));try{const q=await J.runtimeEventsPage(a,{sessionId:l,beforeSequence:F,limit:Uu}),$=q.events.map(V=>V.event);return k(V=>({...V,[l]:Ka($,V[l]??os)})),A(V=>({...V,[l]:{cursorSequence:q.previousSequence,hasMore:q.hasMore,loading:!1,totalMatchingEvents:q.totalMatchingEvents}})),$.length>0}catch(q){return S(q instanceof Error?q.message:String(q)),A($=>({...$,[l]:{cursorSequence:$[l]?.cursorSequence??F,hasMore:$[l]?.hasMore??!0,loading:!1,totalMatchingEvents:$[l]?.totalMatchingEvents??null}})),!1}finally{D.current.delete(l)}},[R,n.length,a,y,s,l,m,f,S]),N=l?y[l]??os:os,x=g.useMemo(()=>s.getSessionEvents(l).length,[s,l]),I=g.useRef(null);g.useEffect(()=>{if(!a||!l||Mt(l)||D.current.has(l)||N.length>0||x>0)return;const j=r;if(!j)return;const T=l,F=j+1;D.current.add(T),A(q=>({...q,[T]:{cursorSequence:q[T]?.cursorSequence??F,hasMore:q[T]?.hasMore??!0,loading:!0,totalMatchingEvents:q[T]?.totalMatchingEvents??null}})),J.runtimeEventsPage(a,{sessionId:T,beforeSequence:F,limit:Uu}).then(q=>{const $=q.events.map(V=>V.event);k(V=>({...V,[T]:Ka($,V[T]??os)})),A(V=>({...V,[T]:{cursorSequence:q.previousSequence,hasMore:q.hasMore,loading:!1,totalMatchingEvents:q.totalMatchingEvents}}))}).catch(q=>{S(q instanceof Error?q.message:String(q)),A($=>({...$,[T]:{cursorSequence:$[T]?.cursorSequence??F,hasMore:$[T]?.hasMore??!0,loading:!1,totalMatchingEvents:$[T]?.totalMatchingEvents??null}}))}).finally(()=>{D.current.delete(T)})},[r,a,N.length,x,l,S]),g.useEffect(()=>{if(!a||!l||Mt(l)||D.current.has(l)||!r)return;const j=Ka(N,s.getSessionEvents(l)),T=Ql(j);if(!T||T>=r)return;const F=`${l}:${T}:${r}`;if(I.current===F)return;I.current=F;let q=!1;return J.runtimeEventsPage(a,{sessionId:l,afterSequence:T,limit:Uu}).then($=>{if(q)return;const V=$.events.map(re=>re.event);V.length!==0&&k(re=>YU(re,l,V))}).catch($=>{q||(I.current=null,S($ instanceof Error?$.message:String($)))}),()=>{q=!0}},[r,a,s,N,l,S]);const P=g.useMemo(()=>Mt(l)?Rm(n,[]):!l||N.length===0?i:Rm(Ka(N,s.getSessionEvents(l)),t),[t,n,i,N,l]);return{chatHistoryLoadStates:R,loadMoreSelectedChatHistory:z,selectedPagedSessionEvents:N,selectedRuntimeIndexes:P}}function i4(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function s4(e,t){const n=g.useRef(null);return g.useMemo(()=>{const a=Nx(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Ur(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Hu(e){return Array.isArray(e)?e.filter(t=>!!Ur(t)):[]}function Uo(e){return typeof e=="string"&&e.trim()?e.trim():null}function hb(e){return Uo(e)??Ur(e)}function l4(e){if(!e)return[];const t=Ur(e.sandboxActionRegistry),n=Ur(e.sandboxManifest),a=new Map;for(const r of[...Hu(n?.actionCatalog),...Hu(t?.actions),...Hu(n?.actions)]){const i=Uo(r.id)??Uo(r.name);if(!i)continue;const s=a.get(i);a.set(i,{id:i,name:Uo(r.name)??s?.name??i,label:Uo(r.label)??s?.label??c4(i),description:Uo(r.description)??s?.description??null,visibility:Uo(r.visibility)??s?.visibility??"default",inputSchema:hb(r.inputSchema)??s?.inputSchema??null,outputSchema:hb(r.outputSchema)??s?.outputSchema??null,implementation:Ur(r.implementation)??s?.implementation??null,mcp:Ur(r.mcp)??s?.mcp??null,invokesModel:typeof r.invokesModel=="boolean"?r.invokesModel:s?.invokesModel})}return Array.from(a.values()).filter(r=>r.visibility!=="internal"&&r.visibility!=="debug")}function c4(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function $k(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:ht("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?sa(e.selectedProject,e.cloudProjects):null;return e.cloudProjects&&!n?null:{id:n?.id??t.projectId,teamId:n?.teamId??t.teamId,name:n?.name??t.projectName??e.selectedProject?.name??"Cloud Project",selectionKey:ht("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const Dk="openpond-agent",Lk="openpond-profile-action";function Dc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ga(e){return typeof e=="string"&&e.trim()?e.trim():null}function bf(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function d4(e){const t=Dc(e),n=Ga(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:Ga(t?.name)}}function u4(e){const t=Ga(e);return t!=="readonly"&&t!=="attempt"&&t!=="feature"&&t!=="rollout"&&t!=="replay"&&t!=="template_build"&&t!=="scheduled_run"&&t!=="patch_only"&&t!=="hotfix"&&t!=="multi_feature_batch"?null:t}function m4(e,t=null){return{id:`agent:${e.id}`,name:e.slug||e.name,label:e.name,description:e.description||(t?`Agent for ${t}`:"OpenPond Agent"),visibility:"default",inputSchema:null,outputSchema:null,implementation:{type:Dk,agentId:e.id,agentName:e.name,teamId:e.teamId,projectId:e.projectId,projectName:t,selectedEntrypoint:e.selectedEntrypoint,workflowMode:e.defaultWorkflowMode},mcp:null,invokesModel:!0}}function p4(e){const t=Dc(e.implementation);if(t?.type!==Dk)return null;const n=Ga(t.agentId),a=Ga(t.teamId),r=Ga(t.projectId),i=d4(t.selectedEntrypoint),s=u4(t.workflowMode);return!n||!a||!r||!i||!s?null:{agentId:n,agentName:Ga(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:r,projectName:Ga(t.projectName),selectedEntrypoint:i,workflowMode:s}}function f4(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...Dc(e.implementation)??{},type:Lk,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function h4(e){if(!e)return[];const t=new Map(e.agents.filter(n=>n.enabled).map(n=>[n.id,n.name]));return e.actionCatalog.filter(n=>!n.agentId||t.has(n.agentId)).map(n=>f4(n,{agentName:n.agentId?t.get(n.agentId):null}))}function xW(e){return!!(e&&vf(e))}function kW(e){return!!(e&&vf(e)&&e.sourceActionId==="chat")}function vf(e){const t=Dc(e.implementation);if(t?.type!==Lk)return null;const n=Ga(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function g4({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:r}){return{action:e.actionId,input:{prompt:a,message:a,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedActionId:e.actionId,selectedActionLabel:e.actionLabel,selectedBy:bf({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...r?{sessionId:r}:{}}}}function b4({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:r}){return{teamId:r,triggerType:"manual",entrypoint:{scope:"action",name:e.id},input:{prompt:a,message:a,actionName:e.id,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedActionId:e.id,selectedActionLabel:e.label??e.name??e.id,selectedBy:bf({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function v4({agent:e,attachments:t=[],displayPrompt:n,prompt:a}){return{teamId:e.teamId,triggerType:"manual",entrypoint:e.selectedEntrypoint,input:{prompt:a,message:a,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedAgentId:e.agentId,selectedAgentName:e.agentName,selectedActionId:`agent:${e.agentId}`,selectedActionLabel:e.agentName,selectedBy:bf({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Hr=new Map;function yf(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function y4(e,t){const n=yf(e,t);if(!n)return null;const a=Hr.get(n);return a?.updatedAt?a.projects:null}function S4(e,t,n){const a=yf(e,n);a&&Hr.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function x4(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=yf(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Hr.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const r=e.fetchProjects(t).then(i=>(S4(t,i,e.accountKey),i)).catch(i=>{const s=Hr.get(n);throw s?.promise===r&&Hr.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),i});return Hr.set(n,{projects:a?.projects??[],promise:r,updatedAt:a?.updatedAt??0}),r}function qu(e){const t=new Map;for(const n of e)n.archivedAt||n.status!=="active"||t.set(n.id,n);return[...t.values()].sort((n,a)=>n.name.localeCompare(a.name))}function k4({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:r,localProjects:i,profile:s,selectedCloudProject:l,selectedProject:p,reportError:m}){const[f,S]=g.useState(null),[y,k]=g.useState([]),[R,A]=g.useState([]),D=g.useMemo(()=>{const T=new Set;a&&T.add(a);for(const F of t)T.add(F.teamId);for(const F of i){const q=t.find($=>$.id===F.linkedSandboxProject?.projectId&&$.teamId===F.linkedSandboxProject?.teamId);q?.teamId&&T.add(q.teamId)}return[...T].sort()},[t,a,i]),z=D.join("\0"),N=g.useMemo(()=>$k({cloudProjects:t,selectedCloudProject:l,selectedProject:p}),[t,l,p]);g.useEffect(()=>{if(!n||D.length===0){A([]);return}let T=!1;const F=D.flatMap(q=>Ek(q,r)??[]);return A(qu(F)),Promise.all(D.map(q=>ff({teamId:q,accountKey:r,fetchAgents:async $=>(await J.listSandboxAgents(n,{teamId:$})).agents}))).then(q=>{T||A(qu(q.flat()))}).catch(()=>{T||A(qu(F))}),()=>{T=!0}},[r,n,z]),g.useEffect(()=>{if(!n||!N){S(null);return}const T=y4(N.teamId,r);T&&S(T.find(q=>q.id===N.id)??null);let F=!1;return x4({teamId:N.teamId,accountKey:r,fetchProjects:async q=>(await J.listSandboxProjects(n,{teamId:q})).projects}).then(q=>{F||S(q.find($=>$.id===N.id)??null)}).catch(()=>{F||S(null)}),()=>{F=!0}},[r,n,N?.id,N?.teamId]),g.useEffect(()=>{if(!n||!p){k([]);return}let T=!1;return J.localProjectActions(n,p.id).then(F=>{T||k(F.actions)}).catch(F=>{T||(k([]),m?.(`Could not load Project Actions for ${p.name}: ${F instanceof Error?F.message:String(F)}`))}),()=>{T=!0}},[n,m,p?.id,p?.name,p?.updatedAt]);const x=g.useMemo(()=>{const T=new Map;for(const F of l4(f))T.set(F.id,F);for(const F of y)T.set(F.id,F);return[...T.values()]},[y,f]),I=g.useMemo(()=>h4(s),[s]),P=g.useMemo(()=>[...R.map(T=>m4(T,e.get(T.projectId)?.name??null)),...I,...x],[e,I,x,R]);return{openPondActionCatalog:g.useMemo(()=>[...I,...x],[I,x]),selectedActionCatalog:P,selectedProjectActionCatalog:x}}function _4({selectedProjectId:e}){const[t,n]=g.useState(()=>new Set),a=g.useCallback(i=>{n(s=>{if(s.has(i))return s;const l=new Set(s);return l.add(i),l})},[]),r=g.useCallback(i=>{n(s=>{const l=new Set(s);return l.has(i)?l.delete(i):l.add(i),l})},[]);return g.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:r,setExpandedProjectIds:n}}function w4(){const e=new Map;function t(r,i){const s=e.get(r);if(s)return s.consumers+=1,n(r,s,!0);const l=new AbortController,p={controller:l,consumers:1,settled:!1,promise:Promise.resolve().then(()=>i(l.signal)).finally(()=>{p.settled=!0,e.get(r)===p&&e.delete(r)})};return e.set(r,p),n(r,p,!1)}function n(r,i,s){let l=!1;return{key:r,promise:i.promise,shared:s,release:()=>{l||(l=!0,i.consumers=Math.max(0,i.consumers-1),i.consumers===0&&!i.settled&&i.controller.abort())}}}function a(){for(const r of e.values())r.consumers=0,r.settled||r.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function Bu(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function I4(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function Fu(e){return e instanceof Error&&e.name==="AbortError"}function C4({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:r,setError:i}){const[s,l]=g.useState(null),[p,m]=g.useState({}),[f,S]=g.useState(null),[y,k]=g.useState(!1),[R,A]=g.useState(!1),D=g.useRef(new Set),z=g.useRef(new Set),N=g.useRef(w4()),x=t?p[t]??(s?.appId===t?s:null):null,I=f?.appId===t?f:null,P=n==="chat"||n==="labs",j=g.useCallback(q=>{D.current.add(q.appId),l(q),m($=>({...$,[q.appId]:q}))},[]),T=g.useCallback(async(q,$=!1)=>{if(!e||!q)return l(null),null;k(!0);const V=N.current.request(Bu(e,q,$),re=>J.workspaceStatus(e,q,$,{signal:re}));try{const re=await V.promise;return j(re),$&&re.error?i(`Workspace sync failed: ${re.error}`):$&&i(null),re}catch(re){return Fu(re)||(l(null),i(re instanceof Error?re.message:String(re))),null}finally{V.release(),k(!1)}},[e,j,i]),F=g.useCallback(async(q=t,$={})=>{if(!e||!q)return S(null),null;$.silent||A(!0);const V=N.current.request(I4(e,q),re=>J.workspaceDiff(e,q,{signal:re}));try{const re=await V.promise;return S(re),re}catch(re){return Fu(re)||(S(null),i(re instanceof Error?re.message:String(re))),null}finally{V.release(),$.silent||A(!1)}},[t,e,i]);return g.useEffect(()=>{if(!e||!t||!P){l(null),S(null),k(!1);return}let q=!1;const $=N.current.request(Bu(e,t,!1),V=>J.workspaceStatus(e,t,!1,{signal:V}));return k(!0),$.promise.then(V=>{q||(j(V),V.initialized||S(re=>re?.appId===V.appId?null:re))}).catch(V=>{Fu(V)||q||(l(null),i(V instanceof Error?V.message:String(V)))}).finally(()=>{$.release(),q||k(!1)}),()=>{q=!0,$.release()}},[t,e,j,i,P]),g.useEffect(()=>{if(!e||!t||!P){S(null);return}if(!x?.initialized){x&&!x.initialized&&S(q=>q?.appId===t?null:q);return}a&&F(t)},[t,e,F,a,P,x?.dirty,x?.initialized]),g.useEffect(()=>{if(!e||r.length===0)return;const q=r.filter(re=>!D.current.has(re)&&!z.current.has(re));if(q.length===0)return;q.forEach(re=>z.current.add(re));let $=!1;const V=q.map(re=>({appId:re,request:N.current.request(Bu(e,re,!1),X=>J.workspaceStatus(e,re,!1,{signal:X}))}));return Promise.all(V.map(({appId:re,request:X})=>X.promise.then(we=>({appId:re,state:we})).catch(()=>({appId:re,state:null})).finally(()=>{X.release(),z.current.delete(re)}))).then(re=>{if(!$)for(const X of re)X.state&&j(X.state)}),()=>{$=!0,V.forEach(({appId:re,request:X})=>{X.release(),z.current.delete(re)})}},[e,j,r]),g.useEffect(()=>()=>N.current.cancelAll(),[]),{workspaceState:s,workspaceStates:p,workspaceDiff:f,workspaceBusy:y,diffBusy:R,visibleWorkspaceState:x,visibleWorkspaceDiff:I,rememberWorkspaceState:j,refreshWorkspace:T,refreshWorkspaceDiff:F,setWorkspaceBusy:k}}const R4=1,A4=15e3,P4=15e3,zk=5*6e4,T4=5e3,E4=1e4;function Uk(e,t=(a,r)=>new WebSocket(a,r),n={}){const a=new M4(e,t,n.reconnectDelayMs??j4);return a.open(),{close:()=>a.close()}}class M4{constructor(t,n,a){this.input=t,this.webSocketFactory=n,this.reconnectDelayMs=a}input;webSocketFactory;reconnectDelayMs;socket=null;closed=!1;generation=0;reconnectAttempt=0;reconnectTimer=null;connectionAckTimer=null;subscriptionAckTimer=null;keepAliveTimer=null;keepAliveTimeoutMs=zk;lastKeepAliveAt=Date.now();ready=!1;subscriptionChannels=new Map;acknowledgedSubscriptions=new Set;open(){this.connect()}close(){if(this.closed)return;this.closed=!0,this.clearTimers();const t=this.socket;if(this.socket=null,!!t){if(t.readyState===R4)for(const n of this.subscriptionChannels.keys())t.send(JSON.stringify({type:"unsubscribe",id:n}));t.onclose=null,t.onerror=null,t.onmessage=null,t.onopen=null,t.close(1e3,"Client closed")}}connect(){if(this.closed)return;const t=++this.generation;this.subscriptionChannels.clear(),this.acknowledgedSubscriptions.clear(),this.ready=!1,this.clearConnectionTimers();let n;try{n=this.webSocketFactory(this.input.realtimeUrl,["aws-appsync-event-ws",`header-${O4(JSON.stringify({Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host}))}`])}catch(a){this.reportError(a),this.scheduleReconnect();return}this.socket=n,n.onopen=()=>{this.isCurrent(n,t)&&(n.send(JSON.stringify({type:"connection_init"})),this.connectionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime connection acknowledgement timed out."))},A4))},n.onmessage=a=>{this.isCurrent(n,t)&&this.handleMessage(n,a)},n.onerror=()=>{this.isCurrent(n,t)&&this.failConnection(new Error("Team chat realtime socket failed."),!1)},n.onclose=a=>{this.isCurrent(n,t)&&(this.socket=null,this.clearConnectionTimers(),this.closed||((a.code===4401||a.code===4403)&&this.reportError(new Error("Team chat realtime authorization expired.")),this.scheduleReconnect()))}}handleMessage(t,n){if(typeof n.data!="string")return;let a;try{const i=JSON.parse(n.data);if(!i||typeof i!="object"||Array.isArray(i))return;a=i}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const r=typeof a.type=="string"?a.type:"";if(r==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=$4(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(r==="ka"){this.lastKeepAliveAt=Date.now();return}if(r==="subscribe_success"){const i=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(i))return;this.acknowledgedSubscriptions.add(i),this.markReadyWhenSubscribed();return}if(r==="data"){if(this.lastKeepAliveAt=Date.now(),typeof a.event!="string")return;try{this.input.onEvent(JSON.parse(a.event))}catch{this.reportError(new Error("Team chat realtime returned an invalid event."))}return}if(r==="connection_error"||r==="subscribe_error"){const i=D4(a);if(this.reportError(i),r==="connection_error")this.failConnection(i,!1);else{const s=typeof a.id=="string"?a.id:"";this.subscriptionChannels.delete(s),this.acknowledgedSubscriptions.delete(s),this.markReadyWhenSubscribed()}}}subscribe(t){const n={Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host};for(const a of Array.from(new Set(this.input.channels))){const r=N4();this.subscriptionChannels.set(r,a),t.send(JSON.stringify({type:"subscribe",id:r,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},P4)}startKeepAliveMonitor(){this.keepAliveTimer&&clearInterval(this.keepAliveTimer),this.keepAliveTimer=setInterval(()=>{Date.now()-this.lastKeepAliveAt<=this.keepAliveTimeoutMs||this.failConnection(new Error("Team chat realtime connection became stale."))},T4)}markReadyWhenSubscribed(){this.ready||this.subscriptionChannels.size===0||this.acknowledgedSubscriptions.size!==this.subscriptionChannels.size||(this.ready=!0,this.subscriptionAckTimer&&clearTimeout(this.subscriptionAckTimer),this.subscriptionAckTimer=null,this.reconnectAttempt=0,this.input.onReady?.())}failConnection(t,n=!0){if(this.closed)return;n&&this.reportError(t);const a=this.socket;if(this.clearConnectionTimers(),!a){this.scheduleReconnect();return}a.close(4e3,"Reconnect")}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;const t=Math.max(0,Math.floor(this.reconnectDelayMs(this.reconnectAttempt)));this.reconnectAttempt+=1,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},t)}reportError(t){this.input.onError?.(t)}isCurrent(t,n){return!this.closed&&this.socket===t&&this.generation===n}clearConnectionTimers(){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.subscriptionAckTimer&&clearTimeout(this.subscriptionAckTimer),this.keepAliveTimer&&clearInterval(this.keepAliveTimer),this.connectionAckTimer=null,this.subscriptionAckTimer=null,this.keepAliveTimer=null}clearTimers(){this.clearConnectionTimers(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null}}function j4(e){const t=Math.min(E4,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function O4(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function N4(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function $4(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:zk}function D4(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,r=typeof a.errorType=="string"?a.errorType:"RealtimeError",i=typeof a.message=="string"?a.message:"Request failed";return new Error(`${r}: ${i}`)}return new Error("Team chat realtime request failed.")}function L4(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(r=>`/team-chat/threads/${r}`)];return Uk({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:r=>{const i=N0.safeParse(r);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function z4(e){return e.refs.find(t=>t.refType==="message_reply")??null}function U4(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function _W(e,t){const n=z4(e);if(!n)return null;const a=t.get(n.refId);return a?U4(a):q4(n)}function H4(e){const t=e.body.slice(0,500);return{authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:t,truncated:t.length<e.body.length}}function wW(e,t){return e.authorUserId?t.get(e.authorUserId)?.name??"Team member":e.authorType==="agent"||e.authorAgentId?"Agent":e.authorType==="system"?"System":"Team member"}function IW(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function q4(e){const t=e.preview;return{id:e.refId,authorType:B4(t.authorType),authorUserId:typeof t.authorUserId=="string"?t.authorUserId:null,authorAgentId:typeof t.authorAgentId=="string"?t.authorAgentId:null,body:typeof t.body=="string"?t.body:"",deleted:t.deleted===!0}}function B4(e){return e==="agent"||e==="system"?e:"user"}function gb(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function F4(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:Ks([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function Vu(e,t){const n=Array.from(t.values()).filter(r=>r.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const r of n)a=ti(a,r,"message.created",!0,r.authorUserId);return{...e,thread:a,messages:Ks([...e.messages,...n])}}function V4(e,t){const n=new Set(e.map(r=>r.lastMessage?.clientRequestId).filter(r=>!!r)),a=new Map;for(const r of t.values()){if(r.clientRequestId&&n.has(r.clientRequestId))continue;const i=a.get(r.threadId)??[];i.push(r),a.set(r.threadId,i)}return e.map(r=>{let i=r;for(const s of a.get(r.id)??[])i=ti(i,s,"message.created",!0,s.authorUserId);return i}).sort((r,i)=>i.lastMessageAt.localeCompare(r.lastMessageAt))}function Wu(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function Ku(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function bb(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function Ks(e){const t=new Map,n=new Set(e.filter(a=>!a.id.startsWith("pending:")).map(a=>a.clientRequestId).filter(a=>!!a));for(const a of e)a.id.startsWith("pending:")&&a.clientRequestId&&n.has(a.clientRequestId)||t.set(a.id,a);return Array.from(t.values()).sort((a,r)=>a.sequence!==r.sequence?a.sequence-r.sequence:a.createdAt.localeCompare(r.createdAt))}function Hk(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:gp.safeParse(e.payload.message).data??null}function qk(e,t,n){const a=Hk(t);if(a){const r=e.selectedThreadId===a.threadId,i=e.detail?.thread.id===a.threadId?{...e.detail,thread:ti(e.detail.thread,a,t.type,r,n),messages:Ks([...e.detail.messages,a])}:e.detail,l=e.threads.some(p=>p.id===a.threadId)?e.threads.map(p=>p.id===a.threadId?ti(p,a,t.type,r,n):p).sort((p,m)=>m.lastMessageAt.localeCompare(p.lastMessageAt)):e.threads;return{...e,detail:i,threads:l,error:null}}if(t.type==="read.updated"){const r=typeof t.payload.userId=="string"?t.payload.userId:null,i=Number(t.payload.sequence);if(!r||!Number.isSafeInteger(i)||i<0)return e;const s=l=>({...l,participants:l.participants.map(p=>p.userId===r?{...p,lastReadSequence:Math.max(p.lastReadSequence,i)}:p)});return{...e,threads:e.threads.map(l=>l.id===t.threadId?s(l):l),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:s(e.detail.thread)}:e.detail}}return e}function ti(e,t,n,a,r){const i=n==="message.created",s=t.sequence>=e.lastMessageSequence;return{...e,lastMessageId:s?t.id:e.lastMessageId,lastMessageSequence:Math.max(e.lastMessageSequence,t.sequence),lastMessageAt:s?t.createdAt:e.lastMessageAt,updatedAt:s?t.createdAt:e.updatedAt,lastMessage:s?t:e.lastMessage,unreadCount:a||t.authorUserId===r?0:i?e.unreadCount+1:e.unreadCount}}function W4(e){const t=new Date().toISOString(),n=`pending:${e.clientRequestId}`;return{id:n,threadId:e.threadId,teamId:e.teamId,clientRequestId:e.clientRequestId,authorType:"user",authorUserId:e.userId,authorAgentId:null,sequence:e.sequence,kind:"text",body:e.body,metadata:{deliveryStatus:"sending",mentionUserIds:e.mentionUserIds,localAttachmentPreviews:e.attachments.map(a=>({id:a.id,url:`data:${a.mediaType};base64,${a.contentsBase64}`}))},editedAt:null,deletedAt:null,createdAt:t,refs:e.replyToMessage?[{id:`pending-reply:${e.clientRequestId}`,messageId:n,refType:"message_reply",refId:e.replyToMessage.id,preview:H4(e.replyToMessage),createdAt:t}]:[],attachments:e.attachments.map(a=>({id:a.id,messageId:null,clientAttachmentId:a.id,kind:"image",name:a.name,mediaType:a.mediaType,sizeBytes:a.sizeBytes,status:"pending",createdAt:t,readyAt:null}))}}function K4(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:ti(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:Ks([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?ti(a,t,"message.created",!0,t.authorUserId):a).sort((a,r)=>r.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function vb(e,t,n){return qk(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function G4(e,t){return Lm(e,t,"failed")}function Lm(e,t,n){const a=r=>r.clientRequestId===t&&r.id.startsWith("pending:")?{...r,metadata:{...r.metadata,deliveryStatus:n}}:r;return{...e,detail:e.detail?{...e.detail,thread:{...e.detail.thread,lastMessage:e.detail.thread.lastMessage?a(e.detail.thread.lastMessage):null},messages:e.detail.messages.map(a)}:null,threads:e.threads.map(r=>({...r,lastMessage:r.lastMessage?a(r.lastMessage):null}))}}function yb(e,t,n){const a=r=>r.clientRequestId===t&&r.id.startsWith("pending:")?{...r,metadata:{...r.metadata,uploadProgress:n}}:r;return{...e,detail:e.detail?{...e.detail,thread:{...e.detail.thread,lastMessage:e.detail.thread.lastMessage?a(e.detail.thread.lastMessage):null},messages:e.detail.messages.map(a)}:null,threads:e.threads.map(r=>({...r,lastMessage:r.lastMessage?a(r.lastMessage):null}))}}function Z4(e,t){const n=e.detail?.messages.filter(i=>i.id!==t)??[],a=n.at(-1)??null,r=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?Sb(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:r,threads:e.threads.map(i=>i.lastMessageId===t?Sb(i,a):i)}}function J4(e){if(e.length>Bo.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!Y4(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Bo.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function Sb(e,t){return{...e,lastMessageId:t?.id??null,lastMessageSequence:t?.sequence??0,lastMessageAt:t?.createdAt??e.createdAt,updatedAt:t?.createdAt??e.createdAt,lastMessage:t}}function Y4(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const X4={team_chat_team_not_found:"You no longer have access to this workspace.",workspace_membership_required:"You no longer have access to this workspace.",team_chat_billing_inactive:"Workspace chat is unavailable while its subscription is inactive. Ask the workspace owner to review billing.",workspace_billing_suspended:"Workspace billing is suspended. Ask the workspace owner to update billing.",workspace_billing_cancelled:"This workspace subscription is cancelled. Ask the workspace owner to reactivate it.",workspace_checkout_pending:"Workspace checkout is still pending. Ask the workspace owner to finish setup.",member_paid_usage_disabled:"The workspace owner has not enabled paid model usage for your account.",member_spend_cap_exceeded:"You reached your workspace member spending limit. Ask the workspace owner to adjust it.",member_opchat_quota_exceeded:"You reached your workspace member OpChat limit. Ask the workspace owner to adjust it.",member_search_quota_exceeded:"You reached your workspace member Search limit. Ask the workspace owner to adjust it.",workspace_prepaid_credit_required:"This workspace needs more prepaid credits. Ask the workspace owner to add credits.",workspace_spend_cap_exceeded:"This workspace reached its spend cap. Ask the workspace owner to review billing.",opchat_workspace_quota_exceeded:"This workspace reached its included OpChat limit for the period.",search_workspace_quota_exceeded:"This workspace reached its included Search limit for the period."};function Q4(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,r]of Object.entries(X4))if(n.includes(a))return r;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":xk(t)}const Bk="openpond.team-chat.notification-mode";function Fk(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function e3(e=Fk()){const t=e?.getItem(Bk);return t==="direct_mentions"||t==="none"?t:"all"}function t3(e,t=Fk()){try{t?.setItem(Bk,e)}catch{}}function n3(e){return e.mode==="none"||!e.currentUserId||!e.thread||e.thread.mutedAt||e.message.deletedAt||e.message.authorUserId===e.currentUserId?!1:e.mode==="all"||e.thread.kind==="dm"?!0:(Array.isArray(e.message.metadata.mentionUserIds)?e.message.metadata.mentionUserIds:[]).includes(e.currentUserId)}function a3(e){const t=e.message.authorUserId?e.members.find(s=>s.userId===e.message.authorUserId)?.name??"Team member":e.message.authorType==="agent"?"Agent":"Team",n=e.thread.title?.trim()||(e.thread.kind==="general"?"general":"conversation"),a=e.thread.kind==="dm"?t:`${t} in #${n}`,i=e.message.body.replace(/\s+/g," ").trim()||(e.message.attachments.length===1?"Sent an image":e.message.attachments.length>1?`Sent ${e.message.attachments.length} images`:"New message");return{eventId:e.eventId,threadId:e.message.threadId,title:a,body:i.length>160?`${i.slice(0,157)}…`:i}}const xb={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function _l(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function wl(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function o3(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function r3(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function kb(e,t=J.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function i3(e){const[t,n]=g.useState(xb),a=g.useRef(t);a.current=t;const[r,i]=g.useState(e3),[s,l]=g.useState(null),p=g.useRef(null),m=g.useRef(null),f=g.useRef(0),S=g.useRef(new Map),y=g.useRef(new Map),k=g.useRef(0),R=g.useRef(null),A=g.useRef(0),D=g.useRef(new Set),z=g.useRef(0),N=g.useRef(!1),x=g.useRef(new Map),I=g.useRef(new Map),[P,j]=g.useState(null),[T,F]=g.useState(null),q=g.useCallback(E=>{i(E),t3(E)},[]),$=g.useCallback(E=>{l(U=>U?.eventId===E?null:U)},[]),V=g.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const E=await J.teamChatThreads(e.connection,e.teamId),U=V4(E.threads,x.current);return n(G=>({...G,threads:U})),U},[e.connection,e.teamId]),re=g.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[E,U]=await Promise.all([J.teamChatMembers(e.connection,e.teamId),J.teamChatAgents(e.connection,e.teamId)]);return n(G=>({...G,members:E.members,agents:U.agents})),{members:E.members,agents:U.agents}},[e.connection,e.teamId]),X=g.useCallback(async E=>{const U=E??p.current;if(!e.connection||!e.teamId||!U)return null;const G=(y.current.get(U)??0)+1;y.current.set(U,G);const me=await J.teamChatThread(e.connection,e.teamId,U);Wu(me.messages,x.current,I.current);const W=Vu(me,x.current);return y.current.get(U)!==G||(n(de=>de.selectedThreadId===U?{...de,threads:_l(de.threads,U),detail:wl(F4(de.detail,W))}:de),p.current===U&&W.thread.lastMessageSequence>0&&await J.markTeamChatRead(e.connection,U,e.teamId,W.thread.lastMessageSequence).catch(()=>{})),W},[e.connection,e.teamId]),we=g.useCallback(async E=>{const U=E??m.current;if(!e.connection||!e.teamId||!U)return null;const G=(S.current.get(U)??0)+1;S.current.set(U,G);const me=await J.teamChatAiThread(e.connection,e.teamId,U);return S.current.get(U)===G&&m.current===U&&n(W=>gb(W,me,m.current)),me},[e.connection,e.teamId]),ye=g.useCallback(async E=>{const U=E??R.current;if(!e.connection||!e.teamId||!U)return null;const G=await J.teamChatAgentConversation(e.connection,e.teamId,U);return n(me=>me.agentConversation?.run.id===U?{...me,agentConversation:G}:me),G},[e.connection,e.teamId]);g.useEffect(()=>{p.current=t.selectedThreadId},[t.selectedThreadId]),g.useEffect(()=>{R.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),g.useEffect(()=>{const E=t.agentConversation?.run.status;if(!E||!["pending","queued","running"].includes(E))return;const U=window.setInterval(()=>{ye().catch(G=>{n(me=>({...me,error:on(G)}))})},2500);return()=>window.clearInterval(U)},[ye,t.agentConversation?.run.status]),g.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(xb),j(null),F(null),I.current.clear(),x.current.clear(),y.current.clear(),S.current.clear(),k.current+=1,l(null),D.current.clear(),z.current=0,A.current=0;return}let E=!1;return m.current=null,f.current+=1,k.current+=1,j(null),F(null),I.current.clear(),x.current.clear(),D.current.clear(),z.current=0,n(U=>({...U,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const U=await J.teamChatEvents(e.connection,e.teamId);if(E)return;A.current=U.cursor;const G=J.teamChatMembers(e.connection,e.teamId),me=J.teamChatAgents(e.connection,e.teamId),W=await J.teamChatGeneral(e.connection,e.teamId),[de,he,We]=await Promise.all([G,me,J.teamChatThreads(e.connection,e.teamId)]);if(E)return;const Ze=p.current&&We.threads.some(Te=>Te.id===p.current)?p.current:W.thread.id,tt=Ze===W.thread.id?W:await J.teamChatThread(e.connection,e.teamId,Ze);if(E)return;const at=wl(tt);n(Te=>({...Te,members:de.members,agents:he.agents,threads:_l(We.threads,Ze),selectedThreadId:Ze,detail:at,loading:!1,error:null})),kb({connection:e.connection,teamId:e.teamId,threadId:Ze,lastMessageSequence:at?.thread.lastMessageSequence??0}),F(e.teamId)}catch(U){if(E)return;n(G=>({...G,loading:!1,error:on(U)}))}})(),()=>{E=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const K=g.useCallback(E=>{if(D.current.has(E.id))return;if(D.current.add(E.id),D.current.size>2e3){const G=D.current.values().next().value;typeof G=="number"&&D.current.delete(G)}const U=Hk(E);if(U&&E.type==="message.created"){const G=a.current,me=G.threads.find(de=>de.id===U.threadId)??(G.detail?.thread.id===U.threadId?G.detail.thread:null),W=de=>{E.id<=z.current||n3({mode:r,currentUserId:e.currentUserId,message:U,thread:de})&&(z.current=E.id,l(a3({eventId:E.id,message:U,thread:de,members:G.members})))};me?W(me):V().then(de=>{const he=de.find(We=>We.id===U.threadId);he&&W(he)}).catch(()=>{})}U?.clientRequestId&&!U.id.startsWith("pending:")&&(x.current.delete(U.clientRequestId),I.current.delete(U.clientRequestId)),n(G=>qk(G,E,e.currentUserId)),E.type==="thread.created"&&V().catch(G=>{n(me=>({...me,error:on(G)}))}),(E.type==="ai_thread.created"||E.type==="ai_turn.updated")&&(X(E.threadId).catch(G=>{n(me=>({...me,error:on(G)}))}),E.conversationId===m.current&&we(E.conversationId).catch(G=>{n(me=>({...me,error:on(G)}))})),U&&E.type==="message.created"&&p.current===U.threadId&&U.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&J.markTeamChatRead(e.connection,U.threadId,e.teamId,U.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,r,we,X,V]),Ee=g.useCallback(async()=>{if(!(!e.connection||!e.teamId||N.current)){N.current=!0;try{let E=!0;for(;E;){const U=await J.teamChatEvents(e.connection,e.teamId,{after:A.current,limit:250});for(const G of U.events)K(G);A.current=U.cursor,E=U.hasMore}}finally{N.current=!1}}},[K,e.connection,e.teamId]);g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;let E=!1,U=null;const G=async()=>{try{const me=await J.teamChatRealtimeSession(e.connection,e.teamId);if(E||(await Ee(),E))return;j(me);const W=Math.max(3e4,new Date(me.expiresAt).getTime()-Date.now()-3e4);U=window.setTimeout(()=>{G()},W)}catch{E||(Ee().catch(()=>{}),U=window.setTimeout(()=>{G()},1e4))}};return G(),()=>{E=!0,U!==null&&window.clearTimeout(U),j(null)}},[Ee,e.connection,e.teamId,T]);const xe=t.threads.map(E=>E.id).sort().join(",");g.useEffect(()=>{if(!P)return;const E=L4({session:P,threadIds:xe?xe.split(","):[],onEvent:K,onReady:()=>{Ee().catch(U=>{n(G=>({...G,error:on(U)}))})},onError:()=>{Ee().catch(()=>{})}});return()=>{E.close()}},[K,Ee,P,xe]),g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;const E=window.setInterval(()=>{Ee().catch(()=>{})},15e3);return()=>window.clearInterval(E)},[Ee,e.connection,e.teamId,T]);const se=g.useCallback(async E=>{if(!e.connection||!e.teamId)return;const U=k.current+1;k.current=U;const G=p.current!==E;p.current=E,G&&(f.current+=1,m.current=null),n(me=>({...me,threads:_l(me.threads,E),selectedThreadId:E,detail:me.detail?.thread.id===E?wl(me.detail):null,aiThread:G?null:me.aiThread,agentConversation:G?null:me.agentConversation,loading:!0,error:null}));try{const me=await J.teamChatThread(e.connection,e.teamId,E);if(k.current!==U||p.current!==E)return;Wu(me.messages,x.current,I.current);const W=Vu(me,x.current);n(de=>({...de,threads:_l(de.threads,E),detail:wl(W),loading:!1})),await J.markTeamChatRead(e.connection,E,e.teamId,W.thread.lastMessageSequence).catch(()=>{})}catch(me){if(k.current!==U)return;n(W=>({...W,loading:!1,error:on(me)}))}},[e.connection,e.teamId]),ke=g.useCallback(async E=>{if(!e.connection||!e.teamId)return null;const U=k.current+1;k.current=U,n(G=>({...G,busy:!0,error:null}));try{const G=await J.teamChatDm(e.connection,e.teamId,E);if(k.current!==U)return null;Wu(G.messages,x.current,I.current);const me=Vu(G,x.current),W=p.current!==me.thread.id;return p.current=me.thread.id,W&&(f.current+=1,m.current=null),n(de=>({...de,selectedThreadId:me.thread.id,detail:me,aiThread:W?null:de.aiThread,agentConversation:W?null:de.agentConversation,busy:!1})),await kb({connection:e.connection,teamId:e.teamId,threadId:me.thread.id,lastMessageSequence:me.thread.lastMessageSequence}),await V(),me}catch(G){return k.current!==U||n(me=>({...me,busy:!1,error:on(G)})),null}},[e.connection,e.teamId,V]),ee=g.useCallback(async()=>{const E=t.detail,U=E?.messages[0]?.sequence;if(!e.connection||!e.teamId||!E||!E.hasMoreBefore||U==null)return!1;n(G=>({...G,loading:!0,error:null}));try{const G=await J.teamChatThread(e.connection,e.teamId,E.thread.id,{beforeSequence:U,limit:50});return n(me=>{if(me.detail?.thread.id!==E.thread.id)return me;const W=[...G.messages,...me.detail.messages];return{...me,loading:!1,detail:{...me.detail,messages:Ks(W),hasMoreBefore:G.hasMoreBefore}}}),!0}catch(G){return n(me=>({...me,loading:!1,error:on(G)})),!1}},[e.connection,e.teamId,t.detail]),pe=g.useCallback(async E=>{const U=p.current,G=J4(E.attachments??[]);if(!G)return n(de=>({...de,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!U||!E.body.trim()&&G.length===0)return!1;if(E.replyToMessage&&(E.replyToMessage.threadId!==U||E.replyToMessage.teamId!==e.teamId||E.replyToMessage.id.startsWith("pending:")||E.replyToMessage.deletedAt))return n(de=>({...de,error:"That message is no longer available to reply to."})),!1;if(E.useModel){if(G.length>0)return n(he=>({...he,error:"Images can be sent to the team thread with Use model turned off."})),!1;const de=f.current;n(he=>({...he,busy:!0,error:null}));try{const he=await J.createTeamChatAiThread(e.connection,U,{teamId:e.teamId,body:E.body.trim(),clientRequestId:crypto.randomUUID(),providerId:E.providerId,modelId:E.modelId}),We=f.current===de&&p.current===U;return We&&(f.current+=1,m.current=he.conversationId),n(Ze=>({...Ze,aiThread:We?he:Ze.aiThread})),he.activeTurn&&await J.executeTeamChatAiTurn(e.connection,he.activeTurn.id,e.teamId),await Promise.all([X(U),V()]),n(Ze=>({...Ze,busy:!1})),!0}catch(he){return n(We=>({...We,busy:!1,error:on(he)})),!1}}const me=crypto.randomUUID();if(E.selectedActionKey){if(G.length>0)return n(de=>({...de,error:"Agent invocations do not support image attachments yet."})),!1;n(de=>({...de,busy:!0,error:null}));try{return await J.createTeamChatAgentRun(e.connection,U,r3({teamId:e.teamId,body:E.body,clientRequestId:me,selectedActionKey:E.selectedActionKey,approvalId:E.approvalId})),await Promise.all([X(U),V()]),n(de=>({...de,busy:!1})),!0}catch(de){return n(he=>({...he,busy:!1,error:on(de)})),!1}}I.current.set(me,{inputs:G,uploaded:null});const W=W4({clientRequestId:me,threadId:U,teamId:e.teamId,userId:e.currentUserId,body:E.body.trim(),mentionUserIds:E.mentionUserIds??[],attachments:G,replyToMessage:E.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});x.current.set(me,W),n(de=>K4(de,W));try{const de=[];for(const[Ze,tt]of G.entries())de.push(await J.uploadTeamChatAttachment(e.connection,U,{teamId:e.teamId,attachment:tt})),bb(x.current,me,`${Ze+1} of ${G.length}`),n(at=>yb(at,me,`${Ze+1} of ${G.length}`));const he=I.current.get(me);he&&(he.uploaded=de);const We=await J.sendTeamChatMessage(e.connection,U,{teamId:e.teamId,body:E.body.trim(),clientRequestId:me,mentionUserIds:E.mentionUserIds,attachmentIds:de.map(Ze=>Ze.id),replyToMessageId:E.replyToMessage?.id??null});return I.current.delete(me),x.current.delete(me),n(Ze=>vb(Ze,We,e.currentUserId)),!0}catch(de){return Ku(x.current,me,"failed"),n(he=>({...G4(he,me),error:on(de)})),!1}},[e.connection,e.currentUserId,e.teamId,X,V,t.detail?.thread.lastMessageSequence]),ve=g.useCallback(async E=>{if(!(!e.connection||!e.teamId)){f.current+=1,m.current=E,n(U=>({...U,aiThread:U.aiThread?.conversationId===E?U.aiThread:null,busy:!0,error:null}));try{const U=await J.teamChatAiThread(e.connection,e.teamId,E);if(m.current!==E)return;n(G=>({...G,aiThread:U,busy:!1}))}catch(U){if(m.current!==E)return;n(G=>({...G,busy:!1,error:on(U)}))}}},[e.connection,e.teamId]),qe=g.useCallback(async E=>{if(!(!e.connection||!e.teamId)){R.current=E,n(U=>({...U,busy:!0,error:null}));try{const U=await J.teamChatAgentConversation(e.connection,e.teamId,E);n(G=>({...G,agentConversation:U,busy:!1}))}catch(U){n(G=>({...G,busy:!1,error:on(U)}))}}},[e.connection,e.teamId]),Re=g.useCallback(()=>{R.current=null,n(E=>({...E,agentConversation:null}))},[]),ie=g.useCallback(async E=>{const U=p.current,G=t.agentConversation;if(!e.connection||!e.teamId||!U||!G||!E.body.trim())return!1;n(me=>({...me,busy:!0,error:null}));try{const me=await J.createTeamChatAgentRun(e.connection,U,o3({teamId:e.teamId,body:E.body,clientRequestId:E.clientRequestId,conversation:G}));R.current=me.run.id;const[W]=await Promise.all([J.teamChatAgentConversation(e.connection,e.teamId,me.run.id),X(U),V()]);return n(de=>({...de,agentConversation:W,busy:!1})),!0}catch(me){return n(W=>({...W,busy:!1,error:on(me)})),!1}},[e.connection,e.teamId,X,V,t.agentConversation]),Ie=g.useCallback(()=>{f.current+=1,m.current=null,n(E=>({...E,aiThread:null}))},[]),$e=g.useCallback(async E=>{const U=m.current;if(!e.connection||!e.teamId||!U||!E.body.trim())return!1;n(G=>({...G,busy:!0,error:null}));try{const G=await J.sendTeamChatAiTurn(e.connection,U,{teamId:e.teamId,body:E.body.trim(),clientRequestId:crypto.randomUUID(),providerId:E.providerId,modelId:E.modelId});return n(me=>({...gb(me,G,m.current),busy:!1})),G.activeTurn&&await J.executeTeamChatAiTurn(e.connection,G.activeTurn.id,e.teamId),!0}catch(G){return n(me=>({...me,busy:!1,error:on(G)})),!1}},[e.connection,e.teamId]),Je=g.useCallback(async()=>{const E=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!E?!1:(await J.cancelTeamChatAiTurnExecution(e.connection,E,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),et=g.useCallback(async(E,U)=>{if(!e.connection||!e.teamId)return!1;try{return await J.editTeamChatMessage(e.connection,E.threadId,E.id,{teamId:e.teamId,body:U}),await X(E.threadId),!0}catch(G){return n(me=>({...me,error:on(G)})),!1}},[e.connection,e.teamId,X]),st=g.useCallback(async E=>{if(!e.connection||!e.teamId)return!1;try{return await J.deleteTeamChatMessage(e.connection,E.threadId,E.id,e.teamId),await X(E.threadId),!0}catch(U){return n(G=>({...G,error:on(U)})),!1}},[e.connection,e.teamId,X]),Be=g.useCallback(async E=>{if(!e.connection||!e.teamId||!E.clientRequestId||!E.id.startsWith("pending:"))return!1;const U=Array.isArray(E.metadata.mentionUserIds)?E.metadata.mentionUserIds.filter(W=>typeof W=="string"):[],G=I.current.get(E.clientRequestId),me=E.refs.find(W=>W.refType==="message_reply");Ku(x.current,E.clientRequestId,"sending"),n(W=>Lm(W,E.clientRequestId,"sending"));try{let W=G?.uploaded??[];if(G&&!G.uploaded){W=[];for(const[he,We]of G.inputs.entries())W.push(await J.uploadTeamChatAttachment(e.connection,E.threadId,{teamId:e.teamId,attachment:We})),bb(x.current,E.clientRequestId,`${he+1} of ${G.inputs.length}`),n(Ze=>yb(Ze,E.clientRequestId,`${he+1} of ${G.inputs.length}`));G.uploaded=W}const de=await J.sendTeamChatMessage(e.connection,E.threadId,{teamId:e.teamId,body:E.body,clientRequestId:E.clientRequestId,mentionUserIds:U,attachmentIds:W.map(he=>he.id),replyToMessageId:me?.refId??null});return I.current.delete(E.clientRequestId),x.current.delete(E.clientRequestId),n(he=>vb(he,de,e.currentUserId)),!0}catch(W){return Ku(x.current,E.clientRequestId,"failed"),n(de=>({...Lm(de,E.clientRequestId,"failed"),error:on(W)})),!1}},[e.connection,e.currentUserId,e.teamId]),He=g.useCallback(E=>{E.id.startsWith("pending:")&&(E.clientRequestId&&I.current.delete(E.clientRequestId),E.clientRequestId&&x.current.delete(E.clientRequestId),n(U=>Z4(U,E.id)))},[]),Ne=g.useCallback(async(E,U)=>{if(!e.connection||!e.teamId)return!1;try{const G=await J.setTeamChatThreadMuted(e.connection,E,e.teamId,U),me=W=>W.id===G.threadId?{...W,mutedAt:G.mutedAt}:W;return n(W=>({...W,threads:W.threads.map(me),detail:W.detail?.thread.id===G.threadId?{...W.detail,thread:me(W.detail.thread)}:W.detail,error:null})),!0}catch(G){return n(me=>({...me,error:on(G)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:r,incomingNotification:s,setNotificationMode:q,dismissIncomingNotification:$,setThreadMuted:Ne,selectThread:se,openDm:ke,loadMoreMessages:ee,sendMessage:pe,openAiThread:ve,openAgentConversation:qe,closeAgentConversation:Re,sendAgentTurn:ie,closeAiThread:Ie,sendAiTurn:$e,stopAiTurn:Je,editMessage:et,deleteMessage:st,retryMessage:Be,dismissFailedMessage:He,refreshDirectory:re,refresh:async()=>{await Promise.all([re(),V(),X(),we(),ye()])}}}function on(e){return Q4(e)}const Vk="local-profile-agent";function CW(e){const t=e.profile;if(!t||t.mode!=="local")return e.hostedActions;const n=new Set(e.hostedActions.flatMap(s=>{const l=s.implementation;return l?.type!=="openpond-agent"||l.profileName!==t.activeProfile?[]:[qo(l.agentName),qo(s.name),qo(s.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,r=new Set(e.hostedActions.map(s=>s.implementation?.agentId).filter(s=>typeof s=="string")),i=t.agents.flatMap(s=>s.enabled?a?.agentId===s.id&&!!(a.runtimeAgentId&&r.has(a.runtimeAgentId))||n.has(qo(s.name))||n.has(qo(s.id))?[]:[c3(t,s)]:[]);return[...e.hostedActions,...i]}function RW(e){return e?.implementation?.type===Vk}function AW(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function s3(e,t){if(!e||e.mode!=="local")return"Load a local OpenPond profile before publishing an agent to Team.";const n=e.agents.find(a=>a.id===t);return n?n.enabled?e.git?.head?e.git.dirty?`Commit your profile changes before publishing ${n.name} to Team.`:e.setupGate.blockingCount>0?`${n.name} has ${e.setupGate.blockingCount} blocking setup requirement${e.setupGate.blockingCount===1?"":"s"}. Complete setup before publishing it to Team.`:null:`Commit ${n.name} before publishing it to Team.`:`${n.name} is disabled in the active profile.`:`Profile agent not found: ${t}`}function l3(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",r=qo(t.agentName);return e.find(i=>{const s=i.implementation;return s?.type!=="openpond-agent"?!1:n&&typeof s.agentId=="string"&&s.agentId===n?!0:!!(a&&s.profileName===a&&r&&[s.agentName,i.name,i.label].some(l=>qo(l)===r))})??null}function c3(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:d3(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:Vk,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function d3(e){return e.git?.head?e.git.dirty?"My Agent · Commit profile changes before publishing to this Team":e.setupGate.blockingCount>0?"My Agent · Complete required setup before publishing to this Team":"My Agent · Publishes to this Team on first use":"My Agent · Commit the profile before publishing to this Team"}function qo(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const _b=5;function u3(e){return g.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await J.profileCheck(e.connection,{kind:"all"}),a=s3(n,t);if(a)throw new Error(a);const r=n?.agents.find(m=>m.id===t);if(!r)throw new Error(`Profile agent not found: ${t}`);const s=(await J.profilePush(e.connection,{teamId:e.teamId,ensureHosted:!0,hostedSourceAgentId:t,message:null})).localProfile?.hosted?.hostedSourceMaterialization,l=s?.agentId===t?s.runtimeAgentId:null;e.applyBootstrapPayload(await J.bootstrap(e.connection));let p=null;for(let m=0;m<_b;m+=1){const f=await e.refreshDirectory();if(p=l3(f.agents,{runtimeAgentId:l,profileName:n.activeProfile,agentName:r.name}),p)break;m<_b-1&&await m3(200*(m+1))}if(!p)throw new Error(`${r.name} was published, but the Team agent directory has not refreshed yet. Retry the mention in a moment.`);return p},[e.applyBootstrapPayload,e.connection,e.refreshDirectory,e.teamId])}function m3(e){return new Promise(t=>{setTimeout(t,e)})}function p3(e){g.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:r}=e.notification;e.showToast(`${a}: ${r}`,"info",{actionLabel:"Open",onAction:()=>{e.setView("team"),e.selectThread(n)},dismissible:!0,durationMs:6500,placement:"top-right"}),e.dismiss(t)},[e.dismiss,e.notification,e.selectThread,e.setView,e.showToast])}function f3(e){const{connection:t,refreshToken:n=null}=e,[a,r]=g.useState([]),[i,s]=g.useState(null),[l,p]=g.useState(null),[m,f]=g.useState(null),[S,y]=g.useState(!1),[k,R]=g.useState(!1),[A,D]=g.useState(!1),[z,N]=g.useState(null),[x,I]=g.useState(null),[P,j]=g.useState(null),[T,F]=g.useState(0),q=g.useRef(0),$=g.useMemo(()=>a.find(ee=>ee.id===l)??null,[a,l]),V=g.useCallback(async()=>{if(!t)return!1;y(!0),N(null);try{const ee=await J.communities(t);return r(ee.items),s(ee.nextCursor),p(pe=>pe&&ee.items.some(ve=>ve.id===pe)?pe:null),!0}catch(ee){return N(Ll(ee)),!1}finally{y(!1)}},[t]),re=g.useCallback(async()=>{if(!t||!i||S)return!1;y(!0),N(null);try{const ee=await J.communities(t,i);return r(pe=>h3(pe,ee.items)),s(ee.nextCursor),!0}catch(ee){return N(Ll(ee)),!1}finally{y(!1)}},[t,S,i]),X=g.useCallback(async ee=>{if(!t)return null;const pe=++q.current;R(!0),I(null);try{const ve=await J.communityPreview(t,ee.slug);return q.current===pe&&f(ve),ve}catch(ve){return q.current===pe&&I(Ll(ve)),null}finally{q.current===pe&&R(!1)}},[t]),we=g.useCallback(ee=>{const pe=a.find(ve=>ve.id===ee);pe&&(p(pe.id),f(ve=>ve?.id===pe.id?ve:null),j(null),X(pe))},[a,X]),ye=g.useCallback(()=>{q.current+=1,p(null),f(null),I(null),j(null)},[]);g.useEffect(()=>{if(!t){r([]),f(null),p(null);return}V()},[t,V,n]),g.useEffect(()=>{!$||m?.id===$.id||k||X($)},[X,m?.id,k,$]);const K=g.useCallback(async()=>{const ee=$;await V(),ee&&await X(ee)},[X,V,$]),Ee=g.useCallback(async()=>{if(!t||!m?.currentRules||A)return!1;D(!0),j(null);try{return await J.joinCommunity(t,m.id,m.currentRules.id),F(ee=>ee+1),await K(),!0}catch(ee){const pe=Il(ee);return j(pe),pe.kind==="rules_stale"&&await K(),!1}finally{D(!1)}},[t,A,m,K]),xe=g.useCallback(async()=>{if(!t||!m?.currentRules||A)return!1;D(!0),j(null);try{return await J.acceptCommunityRules(t,m.id,m.currentRules.id),F(ee=>ee+1),await K(),!0}catch(ee){const pe=Il(ee);return j(pe),pe.kind==="rules_stale"&&await K(),!1}finally{D(!1)}},[t,A,m,K]),se=g.useCallback(async()=>{if(!t||!m||A)return!1;D(!0),j(null);try{return await J.leaveCommunity(t,m.id),F(ee=>ee+1),await K(),!0}catch(ee){return j(Il(ee)),!1}finally{D(!1)}},[t,A,m,K]),ke=g.useCallback(async ee=>{if(!t||!m||A)return!1;D(!0),j(null);try{return await J.updateCommunityNotifications(t,m.id,ee),r(pe=>pe.map(ve=>ve.id===m.id&&ve.membership?{...ve,membership:{...ve.membership,notificationMode:ee}}:ve)),f(pe=>pe?.id===m.id&&pe.membership?{...pe,membership:{...pe.membership,notificationMode:ee}}:pe),!0}catch(pe){return j(Il(pe)),!1}finally{D(!1)}},[t,A,m]);return{items:a,nextCursor:i,selectedCommunityId:l,selectedSummary:$,preview:m,discoveryLoading:S,previewLoading:k,membershipBusy:A,discoveryError:z,previewError:x,membershipError:P,membershipVersion:T,refresh:V,loadMore:re,showDiscovery:ye,selectCommunity:we,join:Ee,acceptRules:xe,leave:se,updateNotifications:ke,clearMembershipError:()=>j(null)}}function h3(e,t){const n=new Map(e.map(a=>[a.id,a]));for(const a of t)n.set(a.id,a);return[...n.values()]}function Ll(e){return e instanceof Error?e.message:String(e)}function Il(e){const t=Ll(e);return t.includes("community_rules_version_stale")?{kind:"rules_stale",message:"The community rules changed. Review the newest version and try again."}:t.includes("community_membership_required")?{kind:"membership_lost",message:"Your community membership is no longer active."}:t.includes("community_join_closed")||t.includes("community_invalid_request")?{kind:"join_conflict",message:"The community could not be joined in its current state."}:{kind:"unknown",message:t}}function g3(e,t,n){return Uk({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const r=F0.safeParse(a);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function b3(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:r}=e,i=n?.id??null,s=n?.membership?.status==="active",l=!n?.capabilities.requiresRulesAcceptance,[p,m]=g.useState([]),[f,S]=g.useState(null),[y,k]=g.useState({}),[R,A]=g.useState([]),[D,z]=g.useState(!1),[N,x]=g.useState(!1),[I,P]=g.useState(!1),[j,T]=g.useState(!1),[F,q]=g.useState(null),[$,V]=g.useState(null),[re,X]=g.useState(null),[we,ye]=g.useState(null),[K,Ee]=g.useState(!1),[xe,se]=g.useState(null),[ke,ee]=g.useState(null),pe=g.useRef(null),ve=g.useRef([]),qe=g.useRef("mentions"),Re=g.useRef(0),ie=g.useRef({}),Ie=g.useRef(new Set),$e=g.useMemo(()=>p.find(Te=>Te.id===f)??null,[p,f]),Je=f?y[f]??null:null;g.useEffect(()=>{pe.current=f},[f]),g.useEffect(()=>{ve.current=p},[p]),g.useEffect(()=>{qe.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const et=g.useCallback(async()=>{if(!t||!i)return!1;z(!0),q(null);try{const Te=await J.communityChannels(t,i);return m(Te.channels),S(De=>De&&Te.channels.some(u=>u.id===De)?De:Te.channels.find(u=>u.isDefault)?.id??Te.channels[0]?.id??null),Ee(!1),!0}catch(Te){const De=Xn(Te);return q(De),rs(De)&&Ee(!0),!1}finally{z(!1)}},[i,t]),st=g.useCallback(async Te=>{if(!t||!i)return!1;const De=++Re.current;x(!0),V(null);try{const u=await J.communityMessages(t,i,Te,{limit:50});return De!==Re.current?!1:(k(M=>({...M,[Te]:{items:u.messages,hasMoreBefore:u.hasMoreBefore,preview:u.preview}})),Ee(!1),!0)}catch(u){if(De!==Re.current)return!1;const M=Xn(u);return V(M),rs(M)&&Ee(!0),!1}finally{De===Re.current&&x(!1)}},[i,t]);g.useEffect(()=>{m(n?.channels??[]),k({}),S(n?.channels.find(Te=>Te.isDefault)?.id??n?.channels[0]?.id??null),q(null),V(null),X(null),Ee(!1),Ie.current.clear(),i&&et()},[i,et,r]),g.useEffect(()=>{f&&st(f)},[st,f]);const Be=g.useCallback(async(Te,De)=>{if(!t||!i||!s||!l||De<=0)return!1;if((ie.current[Te]??0)>=De)return!0;ie.current[Te]=De;try{const u=await J.markCommunityRead(t,i,Te,De);return m(M=>M.map(H=>H.id===Te?{...H,unreadCount:0,readState:H.readState?{...H.readState,lastReadSequence:u.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:u.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:H)),!0}catch(u){const M=Xn(u);return rs(M)&&Ee(!0),!1}},[i,t,s,l]);g.useEffect(()=>{const Te=Je?.items.at(-1)?.sequence??0;f&&Te>0&&Be(f,Te)},[Be,f,Je?.items]);const He=g.useCallback(Te=>{if(Te.communityId!==i||Ie.current.has(Te.id))return;Ie.current.add(Te.id);const De=B0.safeParse(Te.payload.message);if(De.success&&Te.type!=="read.updated"){const u=De.data;if(k(M=>{const H=M[Te.channelId];if(!H)return M;const O=H.items.some(Z=>Z.id===u.id)?H.items.map(Z=>Z.id===u.id?u:Z):[...H.items,u].sort((Z,_)=>Z.sequence-_.sequence);return{...M,[Te.channelId]:{...H,items:O}}}),m(M=>M.map(H=>H.id===Te.channelId?{...H,lastMessageSequence:Math.max(H.lastMessageSequence,u.sequence),unreadCount:pe.current===Te.channelId||u.authorUserId===a?0:Math.max(H.unreadCount+(Te.type==="message.created"?1:0),0)}:H)),Te.type==="message.created"&&u.authorUserId!==a){const M=ve.current.find(O=>O.id===Te.channelId),H=v3(u).includes(a??""),ae=qe.current;!M?.readState?.mutedAt&&(ae==="all"||ae==="mentions"&&H)&&ee({communityId:Te.communityId,channelId:Te.channelId,message:u})}pe.current===Te.channelId&&Be(Te.channelId,u.sequence);return}Te.type==="read.updated"&&Te.payload.userId===a&&et()},[i,a,et,Be]);g.useEffect(()=>{if(!t||!i||!s||!l)return;let Te=!1,De=null;return X(null),Promise.all([J.communityRealtimeSession(t,i),J.communityEvents(t,i)]).then(async([u,M])=>{if(Te)return;const H=async()=>{let O=M.cursor;for(;;){const Z=await J.communityEvents(t,i,{after:O,limit:200});if(Te)return;for(const _ of Z.events)He(_);if(O=Z.cursor,!Z.hasMore)return}},ae=g3({session:u,onEvent:He,onReady:()=>{X(null),H().catch(O=>X(Xn(O)))},onError:O=>X(Xn(O))});De=()=>ae.close(),await H()}).catch(u=>{if(!Te){const M=Xn(u);X(M),rs(M)&&Ee(!0)}}),()=>{Te=!0,De?.()}},[He,i,t,s,r,l]);const Ne=g.useCallback(async()=>{if(!t||!i||!f||I)return!1;const Te=y[f],De=Te?.items[0]?.sequence;if(!Te?.hasMoreBefore||De==null)return!1;P(!0),V(null);try{const u=await J.communityMessages(t,i,f,{beforeSequence:De,limit:50});return k(M=>{const H=M[f]??Te,ae=new Set(H.items.map(O=>O.id));return{...M,[f]:{...H,items:[...u.messages.filter(O=>!ae.has(O.id)),...H.items],hasMoreBefore:u.hasMoreBefore}}}),!0}catch(u){return V(Xn(u)),!1}finally{P(!1)}},[i,t,y,I,f]),E=g.useCallback(async Te=>{if(!t||!i||!f||j)return!1;T(!0),ye(null),se(null);try{const De=await Promise.all(Te.attachments.map(M=>J.uploadCommunityAttachment(t,i,f,M))),u=await J.sendCommunityMessage(t,i,f,{body:Te.body,clientRequestId:Te.clientRequestId,mentionUserIds:Te.mentionUserIds,attachmentIds:De.map(M=>M.id),replyToMessageId:Te.replyToMessageId});return k(M=>{const H=M[f]??{items:[],hasMoreBefore:!1,preview:!1};return H.items.some(ae=>ae.id===u.id)?M:{...M,[f]:{...H,items:[...H.items,u]}}}),await Be(f,u.sequence),!0}catch(De){const u=Xn(De);return ye(u),se({...Te,message:u}),rs(u)&&Ee(!0),!1}finally{T(!1)}},[i,t,Be,f,j]),U=g.useCallback(Te=>E({body:Te.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Te.mentionUserIds??[],attachments:Te.attachments??[],replyToMessageId:Te.replyToMessageId??null}),[E]),G=g.useCallback(async(Te,De)=>{if(!t||!i||!f)return!1;ye(null);try{const u=await J.editCommunityMessage(t,i,f,Te,De);return wb(k,f,u),!0}catch(u){return ye(Xn(u)),!1}},[i,t,f]),me=g.useCallback(async Te=>{if(!t||!i||!f)return!1;ye(null);try{const De=await J.deleteCommunityMessage(t,i,f,Te);return wb(k,f,De),!0}catch(De){return ye(Xn(De)),!1}},[i,t,f]),W=g.useCallback(async(Te,De)=>{if(!t||!i)return!1;ye(null);try{const u=await J.setCommunityChannelMuted(t,i,Te,De);return m(M=>M.map(H=>H.id===Te&&H.readState?{...H,readState:{...H.readState,mutedAt:u.mutedAt}}:H)),!0}catch(u){return ye(Xn(u)),!1}},[i,t]),de=g.useCallback(async(Te="")=>{if(!t||!i||!s)return[];try{const De=await J.searchCommunityMembers(t,i,{query:Te,limit:50});return A(u=>y3(u,De.items)),De.items}catch(De){return ye(Xn(De)),[]}},[i,t,s]);g.useEffect(()=>{s&&l?de():A([])},[s,l,de]);const he=g.useCallback(async Te=>{if(!t||!i||!f)return!1;try{const De=await J.communityAttachmentDownload(t,i,f,Te);return window.open(De.url,"_blank","noopener,noreferrer"),!0}catch(De){return ye(Xn(De)),!1}},[i,t,f]),We=g.useCallback(()=>f?st(f):Promise.resolve(!1),[st,f]),Ze=g.useCallback(()=>xe?E(xe):Promise.resolve(!1),[xe,E]),tt=g.useCallback(()=>se(null),[]),at=g.useCallback(()=>ee(null),[]);return{channels:p,selectedChannelId:f,selectedChannel:$e,messages:Je?.items??[],hasMoreBefore:Je?.hasMoreBefore??!1,previewMode:Je?.preview??!s,members:R,channelsLoading:D,messagesLoading:N,olderMessagesLoading:I,sending:j,channelsError:F,messagesError:$,realtimeError:re,actionError:we,lostMembership:K,failedSend:xe,incomingNotification:ke,selectChannel:S,loadChannels:et,loadMessages:We,loadOlder:Ne,sendMessage:U,retrySend:Ze,dismissFailedSend:tt,editMessage:G,deleteMessage:me,setMuted:W,searchMembers:de,downloadAttachment:he,dismissIncomingNotification:at}}function wb(e,t,n){e(a=>{const r=a[t];return r?{...a,[t]:{...r,items:r.items.map(i=>i.id===n.id?n:i)}}:a})}function v3(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function y3(e,t){const n=new Map(e.map(a=>[a.userId,a]));for(const a of t)n.set(a.userId,a);return[...n.values()].slice(-200)}function rs(e){return e.includes("community_membership_required")||e.includes("community_rules")}function Xn(e){return e instanceof Error?e.message:String(e)}function S3(e){const t=f3({connection:e.connection,refreshToken:e.refreshToken}),n=b3({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,r=t.items,i=n.channels,s=t.selectCommunity,l=n.selectChannel,p=n.dismissIncomingNotification,{setView:m,showToast:f}=e,S=g.useCallback(()=>{t.showDiscovery(),m("community")},[t.showDiscovery,m]),y=g.useCallback(R=>{t.selectCommunity(R),m("community")},[t.selectCommunity,m]),k=g.useCallback(R=>{n.selectChannel(R),m("community")},[n.selectChannel,m]);return g.useEffect(()=>{if(!a)return;const R=r.find(D=>D.id===a.communityId),A=i.find(D=>D.id===a.channelId);f(`${R?.displayName??"Community"} · #${A?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),l(a.channelId),m("community")},placement:"top-right"}),p()},[i,r,p,a,l,s,m,f]),{communities:t,chat:n,sidebar:{communityItems:t.items,communityChannels:n.channels,communityLoading:t.discoveryLoading,communityError:t.discoveryError,selectedCommunityId:t.selectedCommunityId,selectedCommunityChannelId:n.selectedChannelId,discoverCommunities:S,selectCommunity:y,selectCommunityChannel:k},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const x3=[];function k3(e){const t=g.useCallback(a=>YH(e,a),[e]),n=g.useCallback(()=>ZH(e)??x3,[e]);return g.useSyncExternalStore(t,n,n)}function _3(e){const[t,n]=g.useState(()=>fu());return g.useEffect(()=>{let a=!0;return e?(J.connectedAppStatus(e,{status:"all"}).then(r=>{a&&n(r.apps)}).catch(r=>{console.warn("Unable to load connected app mention status.",r),a&&n(fu())}),()=>{a=!1}):(n(fu()),()=>{a=!1})},[e]),t}function w3(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=V5(),[r,i]=g.useState(null),[s,l]=g.useState([]),[p,m]=g.useState(null),[f,S]=g.useState(null),[y,k]=g.useState([]),[R,A]=g.useState(null),[D,z]=g.useState(null),[N,x]=g.useState(Wx),[I,P]=g.useState({}),[j,T]=g.useState(()=>new Set),F=g.useCallback((rt,Lt)=>{T(Ce=>{if(Ce.has(rt)===Lt)return Ce;const ot=new Set(Ce);return Lt?ot.add(rt):ot.delete(rt),ot})},[]),[q,$]=g.useState(0),[V,re]=g.useState(null),X=g.useRef(null),{confirmProjectAction:we,projectConfirmDialog:ye,resolveProjectConfirmDialog:K}=UU(),{query:Ee,searchOpen:xe,archivedChatsOpen:se,sectionMenuOpen:ke,projectsExpanded:ee,cloudProjectsExpanded:pe,chatRowsVisibleCount:ve,sidebarOpen:qe,view:Re,selectedAppId:ie,selectedProjectId:Ie,selectedSessionId:$e,draftProvider:Je,draftModel:et,draftExperience:st,codexPermissionMode:Be,codexReasoningEffort:He,openPondCommandAccessMode:Ne,busy:E,diffPanelOpen:U,diffPanelExpanded:G,rightPanelMode:me,rightChatPanels:W,terminalOpen:de,settingsSection:he,newProjectDialogOpen:We,newProjectMode:Ze,newProjectName:tt,newProjectPath:at,newProjectBusy:Te,commitDialogOpen:De,commitMessage:u,commitIncludeUnstaged:M,commitNextStep:H,commitDraft:ae,branchDialogOpen:O,branchDialogName:Z,toast:_,error:L}=a,oe=J5(Re==="labs"),{setQuery:Q,setSearchOpen:Y,setArchivedChatsOpen:ue,setSectionMenuOpen:le,setProjectsExpanded:ze,setCloudProjectsExpanded:Pe,setChatRowsVisibleCount:Oe,setSidebarOpen:Ye,setView:Le,setSelectedAppId:ut,setSelectedProjectId:Gt,setSelectedSessionId:gn,setPrompt:bn,setDraftProvider:sn,setDraftModel:Pt,setDraftExperience:It,setCodexPermissionMode:vn,setCodexReasoningEffort:Ct,setOpenPondCommandAccessMode:$t,setDiffPanelOpen:Bt,setDiffPanelExpanded:Yt,setRightPanelMode:en,setRightChatPanels:un,setTerminalOpen:An,setSyncingWorkspaceAppId:La,setSettingsSection:Ft,setNewProjectDialogOpen:Ln,setNewProjectMode:lt,setNewProjectName:Dt,setNewProjectPath:te,setNewProjectBusy:Ke,setCommitDialogOpen:Ge,setCommitMessage:yt,setCommitIncludeUnstaged:mn,setCommitNextStep:ka,setCommitDraft:Pn,setBranchDialogOpen:Zt,setBranchDialogName:bt,setError:tn}=n,{connectionRef:St,setError:ft,showToast:Tt}=$5({appDispatch:t,error:L,setErrorState:tn}),{appPreferences:pn,applyBootstrapPayload:zn,bootstrap:Xe,codexHistorySessions:yn,connection:vt,events:fn,runtimeEventStore:Tn,approvals:xn,sessions:_a,startup:da,setAppPreferences:ua,setBootstrap:ma,setCodexHistorySessions:ct,setEvents:mi,setSessions:ta}=O5({setDraftModel:Pt,setDraftProvider:sn,setCodexPermissionMode:vn,setCodexReasoningEffort:Ct,setOpenPondCommandAccessMode:$t,setError:ft,setSelectedAppId:ut,setSelectedProjectId:Gt,setSelectedSessionId:gn});St.current=vt,g.useEffect(()=>{Xe&&k(Xe.sidebarFileBookmarks??[])},[Xe?.sidebarFileBookmarks]);const wa=g.useMemo(()=>[...fn].reverse().find(rt=>rt.name==="tool.completed"&&rt.action==="manage_sidebar_file")??null,[fn]),wo=g.useRef(null);g.useEffect(()=>{!vt||!wa||wo.current===wa.id||(wo.current=wa.id,J.sidebarFiles(vt).then(rt=>k(rt.items)).catch(rt=>ft(rt instanceof Error?rt.message:String(rt))))},[vt,wa,ft]);const rr=g.useCallback(async(rt,Lt)=>{if(!vt)return;const Ce=y;k(ot=>Lt==="none"?ot.filter(_t=>_t.id!==rt.id):ot.some(_t=>_t.id===rt.id)?ot.map(_t=>_t.id===rt.id?{..._t,status:Lt}:_t):[...ot,{...rt,status:Lt}]);try{const ot=await J.patchSidebarFile(vt,{workspaceKind:rt.workspaceKind,workspaceId:rt.workspaceId,workspaceName:rt.workspaceName,path:rt.path,status:Lt,sourceSessionId:rt.sourceSessionId});k(ot.items)}catch(ot){k(Ce),ft(ot instanceof Error?ot.message:String(ot))}},[vt,ft,y]),pa=_3(vt),pi=X5({connection:vt,profileId:Xe?.profile?.activeProfile??"default"}),{pinnedCollapsed:Io,projectsCollapsed:ir,cloudProjectsCollapsed:sr,chatsCollapsed:fi,savedForLaterCollapsed:hi,sidebarWidth:Ia,sidebarResizing:gi,diffPanelWidth:lr,diffPanelResizing:cr,togglePinnedCollapsed:dr,toggleProjectsCollapsed:bi,toggleCloudProjectsCollapsed:na,toggleChatsCollapsed:vi,toggleSavedForLaterCollapsed:yi,startSidebarResize:Si,startDiffPanelResize:xi}=G5({connection:vt,preferences:Xe?.preferences,sidebarOpen:qe,diffPanelExpanded:G,setBootstrap:ma,setError:ft}),{cloudProjectById:ur,linkedProjectByAppId:mr,localProjectById:pr,mentionableSandboxApps:no,selectedApp:Co,selectedCloudProject:za,selectedProject:Un,selectedProjectLinkedApp:ki,selectedProjectLinkedOpenPondApp:_i,selectedSession:nn,selectedSessionLinkedProject:Ro,sidebarSessions:Hn}=fq({bootstrap:Xe,codexHistorySessions:yn,selectedAppId:ie,selectedProjectId:Ie,selectedSessionId:$e,sessions:_a}),fa=nn?.experience??st;g.useEffect(()=>{HH(fa)},[fa]);const Ao=g.useMemo(()=>VL(Hn,fa),[fa,Hn]),Ca=s4(fn,xn),{chatMentionApps:wi,connectedAppMentions:Po,pendingApproval:Ii}=jq({bootstrap:Xe,connectedAppRows:pa,mentionableSandboxApps:no,runtimeIndexes:Ca,selectedApp:Co,selectedCloudProject:za,selectedProject:Un,selectedSession:nn,selectedSessionId:$e}),{codexHistoryEvents:To,setCodexHistoryEvents:fr}=aB({connection:vt,selectedSessionId:$e,selectedSessionLocallyActive:!!($e&&j.has($e)),selectedSessionStatus:nn?.status,setCodexHistorySessions:ct,setError:ft}),{account:Eo,accountPending:hr,accountSignedOut:Mo,activeModel:gr,activeProvider:aa,activeWorkspaceAppId:ao,activeWorkspaceId:jo,activeWorkspaceKind:Ua,activeWorkspaceLocation:br,appDefaults:Ra,cloudLinked:vr,selectedCodexHistoryPending:Ci,selectedSessionProjectId:Oo,startMessage:yr,workspaceName:Sr}=cq({bootstrap:Xe,draftModel:et,draftProvider:Je,selectedApp:Co,selectedAppId:ie,selectedCloudProject:za,selectedProject:Un,selectedSession:nn,selectedSessionId:$e,selectedSessionLinkedProject:Ro}),xr=g.useMemo(()=>eq(Xe?.account??null),[Xe?.account]),Ri=g.useMemo(()=>Am(Xe?.account??null),[Xe?.account]),kr=k3(Ri),_r=g.useMemo(()=>aq(kr,Ra.defaultTeamId),[Ra.defaultTeamId,kr]),oo=_r?.teamId??null,Aa=i3({connection:vt,teamId:oo,currentUserId:Eo?.profile?.id??null,refreshToken:Xe?.accountMeta.asOf??null}),Ai=u3({connection:vt,teamId:oo,applyBootstrapPayload:zn,refreshDirectory:Aa.refreshDirectory});p3({notification:Aa.incomingNotification,dismiss:Aa.dismissIncomingNotification,selectThread:Aa.selectThread,setView:Le,showToast:Tt});const{communities:Pi,sidebar:Ti,view:wr}=S3({connection:vt,currentUserId:Eo?.profile?.id??null,refreshToken:Xe?.accountMeta.asOf??null,setView:Le,showToast:Tt}),Pa=Aa.aiThread?.conversationId??null,ro=Re==="team"&&!!Pa&&U&&me==="chat";g.useEffect(()=>{if(Re==="team"){if(Pa){en("chat"),Bt(!0);return}me==="chat"&&Bt(!1)}},[me,Bt,en,Pa,Re]);const Ei=g.useCallback(()=>{if(Pa){if(ro){Bt(!1);return}en("chat"),Bt(!0)}},[Bt,en,ro,Pa]),Ha=g.useMemo(()=>sa(Un,Xe?.cloudProjects??[]),[Xe?.cloudProjects,Un]),No=nn?.provider==="codex"?Ne:nn?.openPondCommandAccessMode??Ne,Jn=ao,Mi=jo,ji=Ua,Oi=Sr,{openPondActionCatalog:Ni,selectedActionCatalog:dt}=k4({cloudProjectById:ur,cloudProjects:Xe?.cloudProjects??[],connection:vt,defaultTeamId:Ra.defaultTeamId,accountScopeKey:xr,localProjects:Xe?.localProjects??[],profile:Xe?.profile,selectedCloudProject:za,selectedProject:Un,reportError:ft}),{expandedProjectIds:jt,expandProject:qn,toggleProjectExpanded:hn,setExpandedProjectIds:kn}=_4({selectedProjectId:Ie});xq({activeWorkspaceId:jo,activeWorkspaceKind:Ua,appDispatch:t,connection:vt,expandProject:qn,linkedProjectByAppId:mr,providerSettings:Xe?.providers??null,selectedAppId:ie,selectedSession:nn,selectedSessionId:$e,selectedSessionProjectId:Oo,setDiffPanelExpanded:Yt,setDraftModel:Pt,setDraftProvider:sn,setError:ft,setSelectedAppId:ut,setSelectedProjectId:Gt,setSessions:ta,setTerminalOpen:An,toast:_});const{changeCodexPermissionMode:Yn,changeCodexReasoningEffort:Uc}=zq({connection:vt,setBootstrap:ma,setCodexPermissionMode:vn,setCodexReasoningEffort:Ct,setError:ft}),{changeOpenPondCommandAccessMode:Hc}=BF({connection:vt,selectedSession:nn,setBootstrap:ma,setError:ft,setOpenPondCommandAccessMode:$t,setSessions:ta}),qc=kq({connection:vt,setError:ft}),$i=g.useCallback(()=>{$(rt=>rt+1)},[]),Gs=wq({appDispatch:t,expandProject:qn,linkedProjectByAppId:mr,requestComposerFocus:$i,onBeginNewChat:()=>{Qt({kind:"chat",sessionId:null}),re(null),It(rt=>rt==="development"?"work":rt)},setMentionedAppId:S}),Bc=g.useCallback(rt=>{const Lt=ht("local",rt);t({type:"selectProject",projectId:Lt}),qn(Lt)},[t,qn]),{advanceAfterTurn:Fc,begin:Vc,bindSession:Wc,dismiss:Kc,handoff:Gc,prepareTurn:Zc,selectTask:Jc}=o4({activeModel:gr,activeProvider:aa,applyBootstrapPayload:zn,beginNewChat:Gs,composerDraftStore:e,connection:vt,requestComposerFocus:$i,selectedLocalProjectId:Un?.id??null,selectedSessionId:$e,selectLocalProject:Bc,setDraftModel:Pt,setDraftProvider:sn,setError:ft,view:Re});K5({connection:vt,events:fn,showToast:Tt}),YF({searchOpen:xe,sectionMenuOpen:ke,setSectionMenuOpen:le,setSearchOpen:Y,setQuery:Q}),g.useEffect(()=>{P({})},[Xe?.server.id]);const{chatHistoryLoadStates:Zs,loadMoreSelectedChatHistory:Yc,selectedPagedSessionEvents:Xc,selectedRuntimeIndexes:Js}=r4({approvals:xn,codexHistoryEvents:To,connection:vt,latestServerSequence:Xe?.eventWindow?.latestSequence,runtimeIndexes:Ca,runtimeEventStore:Tn,selectedSessionId:$e,serverId:Xe?.server.id,setCodexHistoryEvents:fr,setCodexHistorySessions:ct,setError:ft}),{activeSessions:Qc,archivedSessions:ed,pinnedProjects:td,pinnedSessions:Di,savedForLaterSessions:Ys,pinnedFiles:nd,savedForLaterFiles:ad,pinnedItems:Xs,projectRows:Li,localProjectRows:od,visibleProjectRows:zi,cloudProjectRows:rd,projectSessionRowsByProjectId:Qs,childSessionRowsByParentId:id,sidebarProjectIdBySessionId:Ui,chatRows:sd,visibleChatRows:el,sessionEvents:ld,chatMessages:tl,contextUsage:cd,goalRuntime:dd,subagentRuntime:nl}=FF({localProjects:Xe?.localProjects??[],cloudProjects:Xe?.cloudProjects??[],sessions:Ao,runtimeIndexes:Js,appPreferences:pn,selectedSessionId:$e,selectedProjectId:Ie,archivedChatsOpen:se,projectsExpanded:ee,chatRowsVisibleCount:ve,sidebarFileBookmarks:y}),ud=g.useCallback(rt=>{It(rt);const Lt=[...Ao].filter(Ce=>rt==="work"?Ce.experience==="work"||Ce.experience==="development":Ce.experience===rt).sort((Ce,ot)=>ot.updatedAt.localeCompare(Ce.updatedAt))[0]??[...Hn].filter(Ce=>Ce.experience===rt).sort((Ce,ot)=>ot.updatedAt.localeCompare(Ce.updatedAt))[0]??null;if(Lt)t({type:"selectSession",sessionId:Lt.id,appId:rt!=="chat"?Lt.appId:null,projectId:rt!=="chat"?Ui[Lt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),rt==="chat"&&aa==="codex"){const Ce=km(Xe?.providers,{enabledOnly:!0}).find(ot=>ot.value!=="codex")?.value??Zo;sn(Ce),Pt(Jl(Ce,Xe?.providers)??bs)}rt==="chat"&&(An(!1),Yt(!1),en("home")),Le("chat")},[t,aa,Xe?.providers,Ao,Yt,It,Pt,sn,en,An,Le,Ui,Hn]),Hi=g.useCallback(rt=>{const Lt=e.getSnapshot();if(It(rt),($e||ie||Ie)&&(t({type:"beginNewChat",appId:null}),Lt&&e.set(Lt)),rt==="chat"&&aa==="codex"){const Ce=km(Xe?.providers,{enabledOnly:!0}).find(ot=>ot.value!=="codex")?.value??Zo;sn(Ce),Pt(Jl(Ce,Xe?.providers)??bs)}rt==="chat"&&(An(!1),Yt(!1),en("home")),Le("chat")},[aa,t,Xe?.providers,e,ie,Ie,$e,Yt,It,Pt,sn,en,An,Le]),{pendingChatUserMessages:md,recordPendingChatUserMessage:pd,visibleChatMessages:fd}=LF({chatMessages:tl,runtimeIndexes:Js,selectedSessionId:$e}),io=g.useMemo(()=>nz({selectedAppId:ie,selectedProjectId:Ie,selectedSessionId:$e}),[ie,Ie,$e]),al=g.useRef(null);g.useEffect(()=>{const rt=al.current;al.current=io,!(!rt||rt.kind!=="draft"||io.kind!=="session")&&(Is(rt,io)||l(Lt=>{const Ce=az({tabs:Lt,previousScope:rt,activeScope:io});return Ce.some((_t,ha)=>_t!==Lt[ha])?Ce:Lt}))},[io]);const hd=g.useMemo(()=>oz(s),[s]),{goalRuntime:gd,runningSessionIds:bd,selectedSessionRunning:vd,sidebarGoalRuntimeBySessionId:yd,sidebarSubagentRuntimeBySessionId:Sd}=JF({codexHistoryEvents:To,codexHistorySessions:yn,connection:vt,expandedProjectIds:jt,goalRuntime:dd,locallyActiveCodexHistorySessionIds:j,pinnedSessions:Di,savedForLaterSessions:Ys,projectSessionRowsByProjectId:Qs,rightChatHistoryEvents:I,runtimeIndexes:Ca,selectedSession:nn,selectedSessionId:$e,serverId:Xe?.server.id,setCodexHistorySessions:ct,sidebarSessions:Hn,subagentRuntime:nl,visibleChatRows:el,visibleProjectRows:zi}),{dragItem:ol,pinnedPreviewKeys:xd,startPinnedDrag:rl,clearSidebarDrag:qi,previewPinnedDrop:kd,commitPinnedDrop:_d,commitPinnedPreviewDrop:Bi}=oB({connection:vt,appPreferences:pn,sessions:Hn,pinnedItems:Xs,setAppPreferences:ua,setCodexHistorySessions:ct,setSessions:ta,sidebarFileBookmarks:y,setSidebarFileBookmarks:k,setError:ft}),{clearTaskDrag:Fi,commitTaskDrop:Vi,commitTaskPreviewDrop:Wi,previewTaskDrop:wd,startTaskDrag:Ki,taskDragSessionId:Gi,taskPreviewSessionIds:Zi}=rB({connection:vt,sessions:Hn,setCodexHistorySessions:ct,setError:ft,setSessions:ta}),{commandProjectRows:Ji,contextWindowStatus:Yi,pinnedRows:Id,sidebarWorkspaceAppIds:Cd}=_q({activeProvider:aa,contextCompaction:Ra.contextCompaction,contextUsage:cd,pinnedItems:Xs,pinnedPreviewKeys:xd??[],pinnedProjects:td,projectRows:Li,visibleProjectRows:zi}),$o=!!(Jn&&(Re==="chat"||Re==="labs")&&(De||U&&(me==="changes"||me==="goal"))),{workspaceStates:il,workspaceBusy:sl,diffBusy:Rd,visibleWorkspaceState:Xi,visibleWorkspaceDiff:Ad,rememberWorkspaceState:ll,refreshWorkspace:Pd,refreshWorkspaceDiff:Do,setWorkspaceBusy:Td}=C4({connection:vt,activeWorkspaceAppId:Jn,view:Re,shouldLoadWorkspaceDiff:$o,sidebarWorkspaceAppIds:Cd,setError:ft});X.current=ll;const Ed=g.useCallback((rt=Jn)=>!rt||rt!==Jn||!$o?Promise.resolve(null):Do(rt),[Do,$o,Jn]),Qi=g.useCallback(async(rt={})=>{!Jn||!$o||await Do(Jn,rt)},[Do,$o,Jn]),Md=!1,cl=!!(nn?.provider==="codex"&&nn.cwd&&!$a(nn.workspaceKind)),jd=!!(Xi&&!Xi.initialized&&Ua!=="local_project"&&aa!=="codex"&&!cl&&!Ci),Od=Ua==="local_project"&&!!Un?.sandboxTemplate?.detected&&!Un?.linkedOpenPondApp?.appId,[dl,ul]=g.useState(null),[es,Nd]=g.useState(null),{projectTarget:_f,workspaceTarget:$d}=dq({accountPending:hr,accountSignedOut:Mo,activeWorkspaceLocation:br,bootstrap:Xe,busy:E,cloudLinked:vr,selectedCloudProject:za,selectedProject:Un,selectedSession:nn,pendingWorkspaceTarget:dl,workspaceStates:il,workspaceBusy:sl});return g.useEffect(()=>{ul(null)},[nn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:r,setPendingTerminalCommand:i,terminalTabs:s,setTerminalTabs:l,trainingDetailTasksetId:p,setTrainingDetailTasksetId:m,mentionedAppId:f,setMentionedAppId:S,cloudSetupDialog:R,setCloudSetupDialog:A,rightPanelTabRequest:D,setRightPanelTabRequest:z,workspaceDiffPanelViewState:N,setWorkspaceDiffPanelViewState:x,rightChatHistoryEvents:I,setRightChatHistoryEvents:P,locallyActiveCodexHistorySessionIds:j,setCodexHistoryTurnLocallyActive:F,mainComposerFocusRequestId:q,requestMainComposerFocus:$i,draftSubagentDelegationMode:V,setDraftSubagentDelegationMode:re,confirmProjectAction:we,projectConfirmDialog:ye,resolveProjectConfirmDialog:K,query:Ee,searchOpen:xe,archivedChatsOpen:se,sectionMenuOpen:ke,projectsExpanded:ee,cloudProjectsExpanded:pe,sidebarOpen:qe,view:Re,selectedAppId:ie,selectedProjectId:Ie,selectedSessionId:$e,draftProvider:Je,draftModel:et,draftExperience:st,activeExperience:fa,changeExperience:ud,changeNewExperience:Hi,codexPermissionMode:Be,codexReasoningEffort:He,openPondCommandAccessMode:Ne,busy:E,diffPanelOpen:U,diffPanelExpanded:G,rightPanelMode:me,rightChatPanels:W,terminalOpen:de,settingsSection:he,newProjectDialogOpen:We,newProjectMode:Ze,newProjectName:tt,newProjectPath:at,newProjectBusy:Te,commitDialogOpen:De,commitMessage:u,commitIncludeUnstaged:M,commitNextStep:H,commitDraft:ae,branchDialogOpen:O,branchDialogName:Z,toast:_,error:L,labDetailNavigation:oe,setQuery:Q,setSearchOpen:Y,setArchivedChatsOpen:ue,setSectionMenuOpen:le,setProjectsExpanded:ze,setCloudProjectsExpanded:Pe,setChatRowsVisibleCount:Oe,setSidebarOpen:Ye,setView:Le,setSelectedAppId:ut,setSelectedProjectId:Gt,setSelectedSessionId:gn,setPrompt:bn,setDraftProvider:sn,setDraftModel:Pt,setDraftExperience:It,setDiffPanelOpen:Bt,setDiffPanelExpanded:Yt,setRightPanelMode:en,setRightChatPanels:un,setTerminalOpen:An,setSyncingWorkspaceAppId:La,setSettingsSection:Ft,setNewProjectDialogOpen:Ln,setNewProjectMode:lt,setNewProjectName:Dt,setNewProjectPath:te,setNewProjectBusy:Ke,setCommitDialogOpen:Ge,setCommitMessage:yt,setCommitIncludeUnstaged:mn,setCommitNextStep:ka,setCommitDraft:Pn,setBranchDialogOpen:Zt,setBranchDialogName:bt,setError:ft,showToast:Tt,appPreferences:pn,applyBootstrapPayload:zn,approvals:xn,bootstrap:Xe,connection:vt,events:fn,runtimeEventStore:Tn,sessions:_a,startup:da,setAppPreferences:ua,setCodexHistorySessions:ct,setEvents:mi,setSessions:ta,training:pi,pinnedCollapsed:Io,projectsCollapsed:ir,cloudProjectsCollapsed:sr,chatsCollapsed:fi,savedForLaterCollapsed:hi,sidebarWidth:Ia,sidebarResizing:gi,diffPanelWidth:lr,diffPanelResizing:cr,togglePinnedCollapsed:dr,toggleProjectsCollapsed:bi,toggleCloudProjectsCollapsed:na,toggleChatsCollapsed:vi,toggleSavedForLaterCollapsed:yi,startSidebarResize:Si,startDiffPanelResize:xi,cloudProjectById:ur,localProjectById:pr,selectedApp:Co,selectedCloudProject:za,selectedProject:Un,selectedProjectLinkedApp:ki,selectedProjectLinkedOpenPondApp:_i,selectedSession:nn,sidebarSessions:Hn,runtimeIndexes:Ca,chatMentionApps:wi,connectedAppMentions:Po,pendingApproval:Ii,codexHistoryEvents:To,setCodexHistoryEvents:fr,account:Eo,accountPending:hr,accountSignedOut:Mo,activeModel:gr,activeProvider:aa,activeWorkspaceAppId:ao,activeWorkspaceId:jo,activeWorkspaceKind:Ua,activeWorkspaceLocation:br,appDefaults:Ra,selectedSessionProjectId:Oo,startMessage:yr,workspaceName:Sr,accountScopeKey:xr,teamChatOrganization:_r,teamChatTeamId:oo,teamChat:Aa,publishTeamProfileAgent:Ai,communities:Pi,communitySidebar:Ti,communityView:wr,teamAiThreadId:Pa,toggleTeamAiSidebar:Ei,selectedProjectConfirmedCloudProject:Ha,activeOpenPondCommandAccessMode:No,viewWorkspaceAppId:Jn,viewWorkspaceId:Mi,viewWorkspaceKind:ji,viewWorkspaceName:Oi,openPondActionCatalog:Ni,selectedActionCatalog:dt,expandedProjectIds:jt,expandProject:qn,toggleProjectExpanded:hn,setExpandedProjectIds:kn,changeCodexPermissionMode:Yn,changeCodexReasoningEffort:Uc,changeOpenPondCommandAccessMode:Hc,resolveApproval:qc,beginNewChat:Gs,advanceTrainingModelChatAfterTurn:Fc,beginNewChatWithTrainingModel:Vc,bindTrainingModelChatSession:Wc,dismissTrainingChatHandoff:Kc,trainingChatHandoff:Gc,prepareTrainingModelChatTurn:Zc,selectTrainingChatTaskForComposer:Jc,chatHistoryLoadStates:Zs,loadMoreSelectedChatHistory:Yc,selectedPagedSessionEvents:Xc,activeSessions:Qc,archivedSessions:ed,pinnedSessions:Di,savedForLaterSessions:Ys,pinnedFiles:nd,savedForLaterFiles:ad,sidebarFileBookmarks:y,setSidebarFileStatus:rr,projectRows:Li,localProjectRows:od,visibleProjectRows:zi,cloudProjectRows:rd,projectSessionRowsByProjectId:Qs,childSessionRowsByParentId:id,sidebarProjectIdBySessionId:Ui,chatRows:sd,visibleChatRows:el,chatRowsVisibleCount:ve,sessionEvents:ld,chatMessages:tl,goalRuntime:gd,subagentRuntime:nl,pendingChatUserMessages:md,recordPendingChatUserMessage:pd,visibleChatMessages:fd,activeTerminalScope:io,terminalSummaries:hd,runningSessionIds:bd,selectedSessionRunning:vd,sidebarGoalRuntimeBySessionId:yd,sidebarSubagentRuntimeBySessionId:Sd,taskDragSessionId:Gi,taskPreviewSessionIds:Zi,startTaskDrag:Ki,clearTaskDrag:Fi,previewTaskDrop:wd,commitTaskDrop:Vi,commitTaskPreviewDrop:Wi,dragItem:ol,startPinnedDrag:rl,clearSidebarDrag:qi,previewPinnedDrop:kd,commitPinnedDrop:_d,commitPinnedPreviewDrop:Bi,commandProjectRows:Ji,contextWindowStatus:Yi,pinnedRows:Id,workspaceStates:il,workspaceBusy:sl,diffBusy:Rd,visibleWorkspaceState:Xi,visibleWorkspaceDiff:Ad,rememberWorkspaceState:ll,refreshWorkspace:Pd,refreshWorkspaceDiff:Do,setWorkspaceBusy:Td,refreshWorkspaceDiffWhenNeeded:Ed,refreshVisibleWorkspaceDiff:Qi,managedWorkspace:Md,canSyncActiveWorkspace:jd,canPublishOpenPondProject:Od,pendingWorkspaceTarget:dl,setPendingWorkspaceTarget:ul,pendingSidebarWorkspaceTarget:es,setPendingSidebarWorkspaceTarget:Nd,projectTarget:_f,workspaceTarget:$d}}const I3=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,C3=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function R3(e,t={}){const n=e.trim().replace(/^['"`]+|['"`]+$/g,"");if(!n||/\s/.test(n))return null;const a=n.toLowerCase();return a.startsWith("javascript:")||a.startsWith("data:")?null:/^https?:\/\//i.test(n)?Cl(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?Cl(n,new Set(["file:"])):null:I3.test(n)?Cl(`http://${n}`,new Set(["http:"])):C3.test(n)?Cl(`https://${n}`,new Set(["https:"])):null}function Cl(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function A3(e){const t=R3(e.href,{explicitFile:e.explicitFile});if(!t)return!1;const n=window.openpond?.browser;return n?(e.newTab?await n.newTab({conversationId:e.conversationId,url:t,explicitFile:e.explicitFile}):await n.open({conversationId:e.conversationId,url:t,explicitFile:e.explicitFile}),!0):(window.open(t,"_blank","noopener,noreferrer"),!0)}const P3="openpond-coding-core-v1",T3="feature";function zm(e){const t=new URL("/sandboxes",Sf(e.accountBaseUrl));return t.searchParams.set("teamId",e.teamId),t.searchParams.set("create","sandbox"),t.searchParams.set("intent","cloud-coding"),t.searchParams.set("source",e.source),t.searchParams.set("projectId",e.projectId),t.searchParams.set("workflowMode",T3),t.searchParams.set("runtimeProfileId",P3),e.projectName?.trim()&&t.searchParams.set("projectName",e.projectName.trim()),e.baseBranch?.trim()&&t.searchParams.set("baseBranch",e.baseBranch.trim()),e.localProjectId?.trim()&&t.searchParams.set("localProjectId",e.localProjectId.trim()),t.toString()}function PW(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Sf(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function Ib(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Sf(e.accountBaseUrl)).toString()}function Sf(e){const t=e?.trim();if(!t)return"https://openpond.ai";try{const n=new URL(t);return`${n.protocol}//${n.host}`}catch{return"https://openpond.ai"}}function E3({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:r,rightPanelMode:i,selectedProjectId:s,setDiffPanelOpen:l,setNewProjectDialogOpen:p,setNewProjectMode:m,setNewProjectName:f,setRightPanelMode:S}){const y=g.useCallback(()=>{S("changes"),l(!0)},[l,S]),k=g.useCallback(()=>{if(r&&i==="changes"){l(!1);return}y()},[r,i,l,y]),R=g.useCallback(()=>{S("browser"),l(!0)},[l,S]),A=g.useCallback(()=>{S("goal"),l(!0)},[l,S]),D=g.useCallback((I,P)=>{A3({conversationId:t,href:I,explicitFile:P?.explicitFile,newTab:P?.newTab}).then(j=>{j&&R()})},[t,R]),z=g.useCallback(()=>{m("cloud"),f(""),p(!0)},[p,m,f]),N=g.useCallback(I=>{const P=n.get(I);P&&D(zm({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:P.teamId,projectId:P.id,projectName:P.name,baseBranch:P.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,D]);return{createCloudEnvironmentFromSidebar:g.useCallback(()=>{const I=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(I){N(I);return}z()},[a,z,s,N]),openCloudProjectDialog:z,openUrlInBrowserPanel:D,showBrowserPanel:R,showChangesPanel:y,showGoalSidebarTab:A,toggleChangesPanel:k}}function M3(e){const t=e.requestConversationId.trim();return t?t===e.currentConversationId?{reveal:!0,sessionIdToOpen:null}:new Set(e.sessionIds).has(t)?{reveal:!0,sessionIdToOpen:t}:{reveal:!1,sessionIdToOpen:null}:{reveal:!1,sessionIdToOpen:null}}function j3({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){g.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(i=>{const s=M3({currentConversationId:e,requestConversationId:i.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const O3="chat",N3=["help me","please","can you","could you","make","create","build"],$3=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function Cb(e){const t=Gu(e.label);if(t&&!Um(t))return Rb(t);const n=Gu(e.name);if(n&&!Um(n))return Rb(n);const a=Gu(e.actionId)?.replace(/\.chat$/i,"")??"";return D3(a||t||"Profile Agent")}function Um(e){return e.trim().toLowerCase()===O3}function D3(e){const t=L3(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(r=>r.replace(/[^a-z0-9]/g,"")).filter(r=>r&&!$3.has(r)).slice(0,3);return Wk(a.length?a.join(" "):t||e)}function Rb(e){return Wk(e).split(/\s+/).slice(0,4).join(" ")}function L3(e){let t=e.trim();for(const n of N3)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function Gu(e){return typeof e=="string"&&e.trim()?e.trim():null}function Wk(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const z3="openpond-profile-action";function U3(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Rl(e){return typeof e=="string"&&e.trim()?e.trim():null}function H3(e){const t=U3(e.implementation);if(t?.type!==z3)return null;const n=Rl(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=Rl(e.label);if(a&&!Um(a))return Cb({label:a,description:e.description});const r=Rl(t.agentName)??Rl(e.name);return Cb({actionId:n,description:e.description,name:r})}function q3(e){const t=H3(e);return t||e.label?.trim()||e.name?.trim()||e.id}function Kk(e){const t=typeof e.implementation?.type=="string"?e.implementation.type:null;return t==="openpond-agent"?"OpenPond Agent":t==="openpond-profile-action"&&(e.sourceActionId==="chat"||e.id==="chat"||e.id.endsWith(".chat"))?"Profile agent":t==="workflow"?"Workflow-backed action":t==="agent"?"Agent-backed action":t==="remote-agent"?"Remote-agent action":t==="chat"||t==="intent-router"?"Chat action":e.id}const B3=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function Gk(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ni(e){return typeof e=="string"&&e.trim()?e.trim():null}function qr(e,t,n={}){const a=ni(t)?In(String(t)):"";a&&(!n.generic&&B3.has(a)||e.add(a))}function Al(e,t){const n=ni(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))qr(e,a)}function F3(e,t){const n=ni(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||qr(e,a)}function Zk(e){const t=new Set,n=Gk(e.implementation),a=ni(n?.actionId);return qr(t,e.id,{generic:!0}),Al(t,e.id),qr(t,a,{generic:!0}),Al(t,a),qr(t,e.name,{generic:!0}),Al(t,e.name),qr(t,e.label,{generic:!0}),Al(t,e.label),F3(t,e.description),t}function V3(e){const t=Gk(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",ni(t?.actionId)??"",ni(t?.agentName)??"",Kk(e),...Array.from(Zk(e))].join(" ").toLowerCase()}function TW(e,t,n=8){const a=In(t);return e.length===0?[]:e.filter(r=>a?V3(r).includes(a):!0).slice(0,n)}function W3(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>In(t[1]??"")).filter(Boolean)}function K3(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function G3(e,t){const n=W3(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const i of n)for(const s of t)Zk(s).has(i)&&a.set(s.id,{action:s,mention:i});if(a.size!==1)return null;const r=Array.from(a.values())[0];return{action:r.action,mention:r.mention,prompt:K3(e,r.mention)}}function EW(e){return q3(e)}function MW(e){return e.description||Kk(e)}const xf=[{id:"agent",command:"/agent",label:"Author Agent",description:"Create or improve a Profile Agent in a normal skill-backed turn.",subcommands:["create","improve","help"]},{id:"skill",command:"/skill",label:"Manage skills",description:"Create, edit, and use reusable skills for the selected provider.",subcommands:["create","edit","list","help"]},{id:"goal",command:"/goal",label:"Codex goal",description:"Use Codex-native Goal mode."},{id:"submit-issue",command:"/submit-issue",label:"Submit issue",description:"File a GitHub issue in openpond/openpond through the connected GitHub app."},{id:"train",command:"/train",label:"Create training task",description:"Create a training plan from this chat or select chats in Training."},{id:"sync-cloud",command:"/sync-cloud",label:"Upload/sync to Cloud",description:"Start a chat-visible source upload for the selected Project."}];function Z3(e){return xf.filter(t=>t.id!=="goal"||e==="codex")}function Jk(e,t){return t==="work"?e.id==="submit-issue":t==="chat"?e.id!=="sync-cloud":!0}function jW(e,t){return Z3(e).filter(n=>Jk(n,t))}const J3=new Set(xf.map(e=>e.id));function OW(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function Y3(e){return[e.id,e.command,e.label,e.description].join(" ")}function X3(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function Q3(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return J3.has(n)?{command:n,args:t[2]?.trim()??""}:null}function e6(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function NW({commands:e=xf,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const r=e.filter(l=>l.id.startsWith(a));if(r.length>0)return r.slice(0,n);const i=e.filter(l=>Y3(l).toLowerCase().includes(a));return(i.length>0?i:e.filter(l=>X3(l).toLowerCase().includes(a))).slice(0,n)}function $W(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function Lc(e){return e?.role==="owner"||e?.role==="admin"}function DW(e){const t=zc(e.organizations,e.defaultTeamId),n=Lc(t),a=e.localProject??null;if(!a)return t6("Open a local project to set up an Agent.");const r=n6(a,e.projects),i=a6(a,r,e.agents),s=!!a.sandboxTemplate?.detected,l=t&&!n?"Ask an owner or admin to connect this project.":null;return s?r?o6(a,r)?Pl({state:"needs_sync",actionLabel:"Sync Project",project:r,agent:i,canManage:n,actionBlockedReason:l}):i?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:r,agent:i}:Pl({state:"needs_agent",actionLabel:"Create Agent",project:r,agent:null,canManage:n,actionBlockedReason:l}):Pl({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:l}):Pl({state:"missing_config",actionLabel:"Add Agent config",project:r,agent:i,canManage:n,actionBlockedReason:l})}function Pl(e){return e.canManage?{state:e.state,actionLabel:e.actionLabel,canAct:!0,reason:null,project:e.project,agent:e.agent}:{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e.actionBlockedReason,project:e.project,agent:e.agent}}function t6(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function zc(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(r=>r.teamId===n);if(a)return a}return e.length===1?e[0]??null:e.find(a=>a.role==="owner")??e.find(a=>a.role==="admin")??e[0]??null}function n6(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function a6(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const r=n.find(i=>i.id===a&&i.projectId===t.id);if(r)return r}return n.find(r=>r.projectId===t.id)??null}function o6(e,t){if(t.sandboxManifestError||!t.sandboxManifestSyncedAt||!t.sandboxManifestHash)return!0;if(e.sandboxTemplate?.manifestHash&&t.sandboxManifestHash)return e.sandboxTemplate.manifestHash!==t.sandboxManifestHash;if(e.linkedSandboxProject?.manifestHash&&t.sandboxManifestHash)return e.linkedSandboxProject.manifestHash!==t.sandboxManifestHash;const n=e.sandboxTemplate?.manifestPath;return n&&t.sandboxManifestPath?!n.endsWith(t.sandboxManifestPath):!1}const zo=e=>e.slice(0,2e4);function r6({model:e,provider:t,providerSettings:n}){return{model:tf(t,e,n),modelRef:ba(t,e,n)}}function i6(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function s6(e,t){const n=new Date().toISOString(),a=`codex_history_optimistic_${n}_${Math.random().toString(36).slice(2,8)}`;return{id:a,sessionId:e,turnId:`${a}_turn`,name:"turn.started",timestamp:n,source:"chat_action",args:{prompt:t},status:"started"}}function l6(e,t){return{id:`${e.id}_failed`,sessionId:e.sessionId,turnId:e.turnId,name:"turn.failed",timestamp:new Date().toISOString(),source:"server",status:"failed",error:t instanceof Error?t.message:String(t)}}function Ab({action:e,prompt:t,runPayload:n,sessionId:a}){const r=new Date().toISOString(),i=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${i}_user`,sessionId:a,turnId:i,name:"turn.started",timestamp:r,source:"chat_action",args:{prompt:t}},{id:`${i}_result`,sessionId:a,turnId:i,name:"workspace_action_result",timestamp:n.run.updatedAt??r,source:"chat_action",action:"sandbox_run_action",appId:null,status:s,output:s==="completed"?`Ran ${e.label??e.name??e.id}`:`Started ${e.label??e.name??e.id}`,data:{openPondActionRun:!0,action:{name:e.id,label:e.label??e.name??e.id,implementation:e.implementation},agent:n.agent,run:n.run,sandbox:n.sandbox??null,actionSummary:n.run.actionSummary??null,responseSummary:n.run.responseSummary??null,traceSummary:n.run.traceSummary??null,evalSummary:n.run.evalSummary??null,sourceSummary:n.run.sourceSummary??null}}]}function c6({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:r,draftModel:i,draftProvider:s,experience:l,expandProject:p,ensureCloudSessionReady:m,getPrompt:f,bootstrap:S,chatMessages:y,apps:k,connectedAppMentions:R,mentionedAppId:A,refreshWorkspace:D,refreshWorkspaceDiff:z,selectedApp:N,selectedActionCatalog:x,openPondActionCatalog:I,cloudProjects:P,accountScopeKey:j,selectedCloudProject:T,selectedProject:F,selectedProjectLinkedOpenPondApp:q,selectedSession:$,workspaceTarget:V,subagentDelegationMode:re,setDraftModel:X,setDraftProvider:we,setError:ye,setPrompt:K,setMentionedAppId:Ee,setCodexHistoryEvents:xe,setCodexHistorySessions:se,onCodexHistoryTurnActivityChange:ke,onCodexHistoryTurnPayload:ee,onPendingUserMessage:pe,setEvents:ve,setSelectedAppId:qe,setSelectedProjectId:Re,setSelectedSessionId:ie,setSessions:Ie,setView:$e,setWorkspaceBusy:Je}){const et=g.useRef(new Set),st=S?.providers??null;function Be(O,Z){return O==="codex"?void 0:Z}function He(O){return!!(O&&O.provider!=="codex"&&(O.workspaceKind==="local_project"&&O.cwd?.trim()||(O.workspaceKind==="sandbox"||O.workspaceKind==="sandbox_template"||O.workspaceKind==="sandbox_app")&&O.workspaceId))}function Ne(O){we(O),X(Z=>ko(O,Z,st)),$e("chat")}async function E(O,Z){return(Ek(Z,j)??await ff({teamId:Z,accountKey:j,fetchAgents:async oe=>(await J.listSandboxAgents(t,{teamId:oe})).agents})).find(oe=>oe.projectId===O)??null}async function U(){if(!t)throw new Error("OpenPond App server is not connected.");if(S?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const O=await J.organizations(t),Z=zc(O.organizations.map(Mc).filter(_=>!!_).filter(_=>_.status==="active"),S?.preferences.defaultTeamId??null);if(!Z)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!Lc(Z))throw new Error(`You need owner or admin access to create projects in ${Z.displayName}.`);return Z}async function G(O){if(!t)return!1;const Z=F;if(!Z)throw new Error("Select a local Project before using /sync-cloud.");const _=await U(),L=Z.linkedSandboxProject?.defaultBranch?.trim()||"main",oe=ht("local",Z.id),Q=sa(Z,P),Y=await J.createSession(t,{provider:"openpond",modelRef:ba("openpond",Ts,st),openPondCommandAccessMode:Be("openpond",r),appId:null,appName:null,workspaceKind:"local_project",workspaceId:Z.id,workspaceName:Z.name,localProjectId:Z.id,cloudProjectId:Q?.id??null,cloudTeamId:Q?.teamId??null,cwd:Z.workspacePath,title:`Sync ${Z.name} to Cloud`});Ie(ue=>[Y,...ue]),O.onSessionCreated?.(Y),O.selectSession&&(ie(Y.id),Re(oe),qe(null),$e("chat"),p(oe)),O.clearPromptForTurn(),Je(!0);try{const ue=await J.uploadLocalProjectCloudSource(t,Z.id,{teamId:_.teamId,projectName:Z.name,branch:L,chatSessionId:Y.id,displayPrompt:O.displayPrompt});return e(ue.bootstrap),p(oe),p(ht("cloud",ue.project.id)),!0}catch(ue){const le=await J.bootstrap(t).catch(()=>null);throw le&&e(le),ue}finally{Je(!1)}}async function me(O){if(!t||O.providerForTurn==="codex"||O.selectedSessionForTurn?.provider==="codex")return!1;let Z=He(O.selectedSessionForTurn)?O.selectedSessionForTurn:null;if(!Z&&O.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!Z)if(T){const L=ht("cloud",T.id),oe=O.providerForTurn;Z=await J.createSession(t,{provider:oe,modelRef:ba(oe,O.modelForTurnValue,st),openPondCommandAccessMode:Be(oe,O.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:T.id,workspaceName:T.name,localProjectId:null,cloudProjectId:T.id,cloudTeamId:T.teamId,cwd:null,autoTitlePrompt:zo(O.command)}),Ie(Q=>[Z,...Q]),O.onSessionCreated?.(Z),O.selectSession&&(ie(Z.id),Re(L),qe(null),$e("chat"),p(L))}else{const L=F;if(!L)throw new Error("Select a project to use this.");const oe=sa(L,P),Q=ht("local",L.id),Y=O.providerForTurn;Z=await J.createSession(t,{provider:Y,modelRef:ba(Y,O.modelForTurnValue,st),openPondCommandAccessMode:Be(Y,O.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:L.id,workspaceName:L.name,localProjectId:L.id,cloudProjectId:oe?.id??null,cloudTeamId:oe?.teamId??null,cwd:L.workspacePath,autoTitlePrompt:zo(O.command)}),Ie(ue=>[Z,...ue]),O.onSessionCreated?.(Z),O.selectSession&&(ie(Z.id),Re(Q),qe(null),$e("chat"),p(Q))}if(!Z)throw new Error("Select a project to use this.");O.clearPromptForTurn();const _=await J.runSessionCommand(t,Z.id,{command:O.command,cwd:Z.cwd});return Ie(L=>ls(L,_.session)),ve(L=>Wa(L,_.events)),!0}async function W(O=[],Z=null,_,L={}){const oe=_??f();let Q=oe.trim()||(O.length>0?"Please review the attached files.":"");if(!t||!Q)return!1;const Y=L.displayPrompt?.trim()||Q,ue=L.provider??s,le=L.model??i,ze=L.openPondCommandAccessMode??r,Pe=L.session!==void 0,Oe=Pe?L.session??null:$,Ye=L.experience??Oe?.experience??l,Le=Ye==="development"||Ye==="work"&&(Oe?.workspaceKind==="local_project"||!!Oe?.localProjectId||!!Oe?.cloudProjectId||!Pe&&!!(F||T||N||V==="hybrid"||V==="local")),ut=Pe||!Le?null:N,Gt=Pe||!Le?null:F,gn=Pe||!Le?null:T,bn=Pe||!Le?null:q,sn=!Pe&&Le&&V==="hybrid",Pt=L.selectSession??!0,It=L.chatMessages??y,vn=L.session!==void 0?null:A,Ct=L.clearPrompt===void 0?()=>{K(""),Ee(null)}:L.clearPrompt,$t=Z?null:G3(Q,x),Bt=Z??$t?.action??null,Yt=$t?.prompt||Q,en=Le&&!Bt?e6(Q):null,un=Bt||en?null:Q3(Q),An=un&&!Jk({id:un.command},Ye)?un:null,La=L.usageAttribution??(un?{surface:"chat",workflowKind:"slash_command",commandName:`/${un.command}`,commandSource:"prompt_parse"}:void 0);ye(null);let Ft=null,Ln=null;try{if(!Le&&ue==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(An)throw new Error(`/${An.command} isn't available in ${Ye}.`);if(en&&ue!=="codex"&&Oe?.provider!=="codex"){if(O.length>0)throw new Error("Direct commands do not accept attachments.");return await me({command:en.command,clearPromptForTurn:Ct,modelForTurnValue:le,onSessionCreated:L.onSessionCreated,openPondCommandAccessModeForTurn:ze,providerForTurn:ue,selectedSessionForTurn:Oe,selectSession:Pt})}if(!Pe&&un?.command==="sync-cloud")return await G({clearPromptForTurn:Ct,displayPrompt:Y,onSessionCreated:L.onSessionCreated,selectSession:Pt});if(Bt){const bt=p4(Bt);if(bt){let Xe=Oe;if(!Xe||Xe.cloudProjectId!==bt.projectId){Xe=await J.createSession(t,{provider:"openpond",modelRef:ba("openpond",le,st),openPondCommandAccessMode:Be("openpond",ze),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:bt.projectId,workspaceName:bt.projectName??bt.agentName,localProjectId:null,cloudProjectId:bt.projectId,cloudTeamId:bt.teamId,cwd:null,autoTitlePrompt:zo(Y)}),Ie(Tn=>[Xe,...Tn]),L.onSessionCreated?.(Xe),Pt&&ie(Xe.id);const fn=ht("cloud",bt.projectId);Pt&&Re(fn),Pt&&p(fn)}const yn=await J.runSandboxAgent(t,bt.agentId,v4({agent:bt,attachments:O,displayPrompt:Y,prompt:Yt})),vt=await J.bootstrap(t);return e(vt),Ct(),ve(fn=>Wa(fn,Ab({action:Bt,prompt:Y,runPayload:yn,sessionId:Xe.id}))),!0}const tn=vf(Bt);if(tn){let Xe=Oe;(!Xe||Xe.provider!=="openpond")&&(Xe=await J.createSession(t,{provider:"openpond",modelRef:ba("openpond",le,st),openPondCommandAccessMode:Be("openpond",ze),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:zo(Y)}),Ie(vt=>[Xe,...vt]),L.onSessionCreated?.(Xe),Pt&&ie(Xe.id)),await J.runProfileAction(t,g4({action:tn,attachments:O,displayPrompt:Y,prompt:Yt,sessionId:Xe.id}));const yn=await J.bootstrap(t);return e(yn),Ct(),!0}const St=$k({cloudProjects:P,selectedCloudProject:T,selectedProject:F});if(!St)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let ft=Oe;(!ft||ft.cloudProjectId!==St.id)&&(ft=await J.createSession(t,{provider:"openpond",modelRef:ba("openpond",le,st),openPondCommandAccessMode:Be("openpond",ze),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:St.id,workspaceName:St.name,localProjectId:St.localProjectId,cloudProjectId:St.id,cloudTeamId:St.teamId,cwd:null,autoTitlePrompt:zo(Y)}),Ie(Xe=>[ft,...Xe]),L.onSessionCreated?.(ft),Pt&&(ie(ft.id),Re(St.selectionKey),p(St.selectionKey)));const Tt=await E(St.id,St.teamId);if(!Tt)throw new Error("No OpenPond Agent is available for this Project.");Ct();const pn=await J.runSandboxAgent(t,Tt.id,b4({action:Bt,attachments:O,displayPrompt:Y,prompt:Yt,teamId:St.teamId})),zn=await J.bootstrap(t);return e(zn),ve(Xe=>Wa(Xe,Ab({action:Bt,prompt:Y,runPayload:pn,sessionId:ft.id}))),!0}let lt=Oe;if(lt&&Mt(lt.id)){Ln=qg({afterMessageId:It.at(-1)?.id??null,attachments:O,content:Q,sessionId:lt.id}),Ct(),Ft=lt.id,et.current.add(Ft),pe?.(Ln),ke?.(Ft,!0);const bt=s6(lt.id,Q),tn=Tt=>{(!Pe||$?.id===lt.id)&&xe(pn=>i6(pn,Tt)),L.onCodexHistoryOptimisticEvent?.(Tt)};tn(bt),se(Tt=>Tt.map(pn=>pn.id===lt.id?{...pn,status:"active"}:pn));const St=await J.sendCodexHistoryTurn(t,lt.id,{prompt:Q,attachments:O.length>0?O:void 0,model:tf("codex",le,st),modelRef:ba("codex",le,st),...ig(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(Tt=>{throw tn(l6(bt,Tt)),Tt});(!Pe||$?.id===lt.id)&&xe(Tt=>Wa(Tt,St.events)),se(Tt=>ls(Tt,St.session)),ee?.(St);const ft=await J.bootstrap(t);return e(ft),!0}const te=(vn?k.find(bt=>bt.id===vn&&uq(oe,bt)&&bt.sandbox)??null:null)??mq(oe,Jx(k)),Ke=Ye==="chat"?[]:Rq(oe,R).map(bt=>bt.ref);if(!lt){const bt=bn?.appId??ut?.id??null,tn=bn?.appName??ut?.name??null,St=gn,ft=Pe?null:sa(Gt,P),Tt=sn?Fx({cloudProjects:P,selectedCloudProject:St,selectedProject:Gt}):null;if(Tt?.kind==="missing_cloud_project")throw new Error(Tt.message);const pn=Tt?.kind==="ready",zn=pn?ue:St?"openpond":ue,Xe=ba(zn,le,st),yn=Be(zn,ze),vt=pn?Vx({modelRef:Xe,provider:zn,target:Tt,title:Q.slice(0,64)}):null;lt=await J.createSession(t,vt?{...vt,subagentDelegationMode:re,metadata:{...vt.metadata,...L.sessionMetadata??{}},...yn?{openPondCommandAccessMode:yn}:{},autoTitlePrompt:zo(Q)}:{experience:Ye,provider:zn,modelRef:Xe,subagentDelegationMode:re,...yn?{openPondCommandAccessMode:yn}:{},appId:bt,appName:tn,workspaceKind:St?"sandbox":Gt?"local_project":ut?"sandbox_app":void 0,workspaceId:Gt?.id??(ut?bt:void 0),workspaceName:St?.name??Gt?.name??tn,localProjectId:Gt?.id??null,cloudProjectId:St?.id??ft?.id??null,cloudTeamId:St?.teamId??ft?.teamId??null,...!St&&!Gt&&!ut&&V==="local"?{metadata:{...FH(),...L.sessionMetadata??{}}}:{cwd:Gt?Gt.workspacePath:null,...L.sessionMetadata?{metadata:L.sessionMetadata}:{}},autoTitlePrompt:zo(Q)}),Ie(fn=>[lt,...fn]),L.onSessionCreated?.(lt),Pt&&(ie(lt.id),St&&Re(ht("cloud",St.id)),lt.workspaceKind==="local_project"&&lt.workspaceId&&p(ht("local",lt.workspaceId)),St&&p(ht("cloud",St.id)))}if(Pb(lt)&&$a(lt.workspaceKind)&&lt.provider!=="openpond"&&!Da(lt))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(Pb(lt)&&$a(lt.workspaceKind)&&m)try{lt=await m(lt)}catch(bt){const tn=bt instanceof Error?bt.message:String(bt);throw await J.recordPreflightTurnFailure(t,lt.id,{prompt:Q,error:tn,target:Da(lt)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),bt}Ln=qg({afterMessageId:It.at(-1)?.id??null,attachments:O,content:Q,sessionId:lt.id}),Ct(),Ft=lt.id,et.current.add(Ft),pe?.(Ln),Ie(bt=>bt.map(tn=>tn.id===Ft?{...tn,status:"active"}:tn));const Ge=ue,yt=r6({provider:Ge,model:le,providerSettings:st}),mn=FL(Ge,yt.model??le,st),ka=Ge==="codex"?ig(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await J.sendTurn(t,lt.id,{prompt:Q,metadata:L.turnMetadata,attachments:O.length>0?O:void 0,mentionedAppIds:te?[te.id]:void 0,mentionedConnectedApps:Ke.length>0?Ke:void 0,openPondActionCatalog:I.length>0?I:void 0,usageAttribution:La,...yt,...ka,codexPermissionMode:Ge==="codex"?n:"default",codexReasoningEffort:mn?a:void 0});const Pn=await J.bootstrap(t);e(Pn);const Zt=lt.workspaceId??lt.appId;return Zt&&lt.workspaceKind!=="sandbox"&&lt.workspaceKind!=="sandbox_template"&&D(Zt,!1).then(bt=>{bt?.initialized&&z(Zt)}),!0}catch(lt){return ye(lt instanceof Error?lt.message:String(lt)),!1}finally{Ft&&et.current.delete(Ft),Ft&&Mt(Ft)&&ke?.(Ft,!1),Ft&&(Mt(Ft)?se(lt=>lt.map(Dt=>Dt.id===Ft&&Dt.status==="active"?{...Dt,status:"idle"}:Dt)):Ie(lt=>lt.map(Dt=>Dt.id===Ft&&Dt.status==="active"?{...Dt,status:"idle"}:Dt)))}}async function de(O){const Z=et.current.values().next().value??null,_=O??$?.id??Z;if(!t||!_)return!1;if(ye(null),Mt(_))try{const L=await J.interruptCodexHistoryTurn(t,_);if(!L.interrupted){if(L.reason==="no_active_openpond_turn"){const Q=await J.codexHistoryThread(t,_,{tail:!0}),Y={...Q.session,status:"idle"};return $?.id===_&&xe(ue=>Wa(ue,Q.events)),se(ue=>ls(ue,Y)),ye("OpenPond no longer has a live interrupt handle for this Codex history turn. The chat was marked idle so you can send again."),!0}return ye("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const oe=await J.codexHistoryThread(t,_,{tail:!0});return $?.id===_&&xe(Q=>Wa(Q,oe.events)),se(Q=>ls(Q,oe.session)),!0}catch(L){const oe=L instanceof Error?L.message:String(L);return ye(oe==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":oe),!1}try{await J.interruptTurn(t,_);const L=await J.bootstrap(t);return e(L),!0}catch(L){return ye(L instanceof Error?L.message:String(L)),!1}}async function he(O,Z){if(!t){ye("OpenPond App server is not connected.");return}ye(null),await J.applyCreateImproveAction(t,O.id,{...Z,runId:O.id,expectedRevision:O.revision,actionId:`web:${Z.type}:${crypto.randomUUID()}`});const _=await J.bootstrap(t);e(_)}async function We(O){await he(O.run,{type:"approve_plan"})}async function Ze(O){await he(O.run,{type:"cancel",reason:null})}async function tt(O,Z){await he(O.run,{type:"revise_plan",revision:Z})}async function at(O,Z,_){await he(O.run,{type:"answer_question",questionId:Z,value:_})}async function Te(O){await he(O.run,{type:"pause"})}async function De(O){await he(O.run,{type:"resume"})}async function u(O,Z){await he(O.run,{type:"open_pull_request",candidateId:Z})}async function M(O,Z){await he(O.run,{type:"apply_candidate",candidateId:Z})}async function H(O,Z){await he(O.run,{type:"reject_candidate",candidateId:Z,reason:null})}async function ae(O,Z){await he(O.run,{type:"reconcile_pull_request",candidateId:Z})}return{answerCreateImproveQuestion:at,approveCreateImproveRun:We,applyCreateImproveCandidate:M,cancelCreateImproveRun:Ze,changeDraftProvider:Ne,openCreateImprovePullRequest:u,pauseCreateImproveRun:Te,reconcileCreateImprovePullRequest:ae,rejectCreateImproveCandidate:H,resumeCreateImproveRun:De,reviseCreateImproveRun:tt,sendPrompt:W,stopTurn:de}}function Pb(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function d6({branch:e,connection:t,session:n}){if(!$a(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await J.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await J.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function u6(e){return Da(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function m6(e,t){if(e==="already_running")return null;const n=Da(t)?"Hybrid sandbox":"Cloud workspace";return e==="waited_for_creating"?`${n} is ready.`:e==="started"?`Started ${n}.`:e==="resumed"?`Resumed ${n}.`:e==="restored"?`Restored ${n}.`:`Recreated ${n}.`}function p6(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function f6({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:r,selectedProject:i,setWorkspaceBusy:s,showToast:l,visibleWorkspaceState:p}){return g.useCallback(async m=>{if(!n)throw new Error("OpenPond App server is not connected.");const f=i??(m.localProjectId?a.get(m.localProjectId)??null:null);if(m.cloudProjectId&&m.cloudTeamId&&!p6(m,t))throw new Error("This Cloud session belongs to a different OpenPond account. Sync or select a Project in the current account.");m.workspaceId||l(u6(m),"info"),s(!0);try{const S=await d6({branch:i?.linkedSandboxProject?.defaultBranch??r?.defaultBranch??p?.currentBranch??null,connection:n,localProject:f,session:m,source:Da(m)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});S.bootstrap&&e(S.bootstrap);const y=m6(S.status,m);return y&&l(y,"success"),S.session}finally{s(!1)}},[e,t,n,a,r,i,s,l,p?.currentBranch])}function h6(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function g6(e){return e.keepOpen?b6():h6()}function b6(){return{diffPanelOpen:!0,diffPanelExpanded:!1,rightPanelMode:"home",rightChatPanels:[]}}function v6(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function Tb(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function y6(e,t){return e.diffPanelOpen!==t.diffPanelOpen||e.diffPanelExpanded!==t.diffPanelExpanded||e.rightPanelMode!==t.rightPanelMode||e.rightChatPanels.length!==t.rightChatPanels.length?!1:e.rightChatPanels.every((n,a)=>{const r=t.rightChatPanels[a];return!!(r&&n.id===r.id&&n.activationVersion===r.activationVersion&&n.sessionId===r.sessionId&&n.prompt===r.prompt&&n.provider===r.provider&&n.model===r.model&&n.scrollTop===r.scrollTop&&n.stickyToBottom===r.stickyToBottom)})}function S6(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function x6(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:r,rightPanelMode:i,selectedAppId:s,selectedCloudProject:l,selectedProjectId:p,selectedSession:m,selectedSessionId:f,setWorkspaceDiffPanelViewState:S,view:y,viewWorkspaceAppId:k,viewWorkspaceId:R,viewWorkspaceKind:A,workspaceDiffPanelViewState:D}=e,z=g.useRef(new Map),N=g.useRef(new Map),x=g.useRef(null),I=g.useRef(null),P=f??`draft:${p??s??l?.id??"general"}`,j=g.useMemo(()=>R?`${A??"workspace"}:${R}`:k?`app:${k}`:m?.cwd&&!$a(m.workspaceKind)?`cwd:${m.cwd}`:"none",[m?.cwd,m?.workspaceKind,y,k,R,A]),T=S6({conversationId:P,workspaceSourceKey:j}),F=g.useMemo(()=>v6({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:r,rightPanelMode:i}),[n,a,r,i]);g.useEffect(()=>{const $=x.current;$&&z.current.set($,Tb(F))},[P,F]),g.useEffect(()=>{if(x.current===P)return;x.current=P;const V=z.current.get(P)??g6({keepOpen:F.diffPanelOpen});y6(F,V)||t({type:"patch",patch:Tb(V)})},[P,F]),g.useEffect(()=>{const $=I.current;$&&N.current.set($,Tu(D))},[T,D]),g.useEffect(()=>{if(I.current===T)return;I.current=T;const V=N.current.get(T)??Wx();S(re=>Pg(re,V)?re:Tu(V))},[T]);const q=g.useCallback($=>{S(V=>Pg(V,$)?V:Tu($))},[]);return{browserConversationId:P,handleWorkspaceDiffPanelViewStateChange:q}}function k6({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:r,appDispatch:i,applyBootstrapPayload:s,busy:l,cloudSetupDialog:p,cloudProjects:m,connection:f,defaultTeamId:S,expandProject:y,localProjectById:k,selectedCloudProject:R,selectedProject:A,selectedSession:D,selectedSessionProjectId:z,setCloudSetupDialog:N,setDiffPanelOpen:x,setError:I,setSessions:P,setWorkspaceBusy:j,showToast:T,visibleWorkspaceState:F,workspaceBusy:q}){const $=e?.baseUrl??e?.activeProfile?.baseUrl??null,V=g.useCallback(async(K,Ee)=>{if(f)try{const xe=await J.previewLocalProjectCloudSource(f,K.id,{branch:Ee});N(se=>!se||se.status!=="confirm"||se.localProjectId!==K.id||se.branch!==Ee?se:{...se,branch:xe.preview.branch,cloudProjectId:xe.preview.targetProjectId,preview:xe.preview,previewLoading:!1,previewError:null})}catch(xe){const se=xe instanceof Error?xe.message:String(xe);N(ke=>!ke||ke.status!=="confirm"||ke.localProjectId!==K.id||ke.branch!==Ee?ke:{...ke,preview:null,previewLoading:!1,previewError:se})}},[f,N]),re=g.useCallback(async()=>{const K=p;if(!K||K.status==="uploading")return;if(K.projectKind==="cloud"){N(ke=>ke&&{...ke,status:"ready",error:null});return}if(!f){N(ke=>ke&&{...ke,status:"error",error:"OpenPond App server is not connected."});return}const Ee=K.localProjectId??"",xe=k.get(Ee);if(!xe){N(ke=>ke&&{...ke,status:"error",error:"Project is no longer available."});return}j(!0);const se=sa(xe,m);N(ke=>ke&&{...ke,status:"uploading",error:null,previewLoading:!1});try{const ke=await J.organizations(f),ee=zc(ke.organizations.map(Mc).filter($e=>!!$e).filter($e=>$e.status==="active"),S);if(!ee)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!Lc(ee))throw new Error(`You need owner or admin access to create projects in ${ee.displayName}.`);const pe=K.branch||xe.linkedSandboxProject?.defaultBranch||"main",ve=ht("local",xe.id),qe=await J.createSession(f,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:xe.id,workspaceName:xe.name,localProjectId:xe.id,cloudProjectId:se?.id??null,cloudTeamId:se?.teamId??null,cwd:xe.workspacePath,title:`Sync ${xe.name} to Cloud`});P($e=>[qe,...$e]),i({type:"selectSession",sessionId:qe.id,projectId:ve}),y(ve);const Re=await J.uploadLocalProjectCloudSource(f,xe.id,{teamId:ee.teamId,projectName:xe.name,branch:pe,chatSessionId:qe.id,displayPrompt:`/sync-cloud ${xe.name}`});s(Re.bootstrap),y(ve),y(ht("cloud",Re.project.id));const ie=zm({accountBaseUrl:$,teamId:Re.project.teamId,projectId:Re.project.id,projectName:Re.project.name,baseBranch:Re.upload.branch,localProjectId:xe.id,source:"openpond-app"}),Ie=Ib({accountBaseUrl:$,organizationSlug:Re.project.organizationSlug,projectSlug:Re.project.slug});N({status:"ready",localProjectId:xe.id,cloudProjectId:Re.project.id,teamId:Re.project.teamId,projectName:Re.project.name,projectKind:"local",projectUrl:Ie,setupUrl:ie,branch:Re.upload.branch,preview:K.preview??null,previewLoading:!1,previewError:null,upload:{branch:Re.upload.branch,headCommit:Re.upload.headCommit,fileCount:Re.upload.fileCount,byteCount:Re.upload.byteCount,skippedCount:Re.upload.skippedCount,initializedEmptyProject:Re.upload.initializedEmptyProject},error:null}),T("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(ke){const ee=ke instanceof Error?ke.message:String(ke),pe=f?await J.bootstrap(f).catch(()=>null):null;pe&&s(pe),I(ee),N(ve=>ve&&{...ve,status:"error",error:ee})}finally{j(!1)}},[$,i,s,p,m,f,S,y,k,N,I,P,j,T]),X=g.useCallback((K,Ee)=>{if(!f){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}const xe=Ee||K.linkedSandboxProject?.defaultBranch||"main";N({status:"confirm",localProjectId:K.id,projectName:K.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:xe,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),V(K,xe)},[t,n,f,V,N,T]),we=g.useCallback(async K=>{if(K===r||q||l)return;if(I(null),K==="upload_cloud"){if(!A){T("Select a local Project before uploading source.","error");return}X(A,F?.currentBranch??null);return}if(K==="local"){const se=D?.localProjectId??A?.id??z??null,ke=se?k.get(se)??null:null;if(!ke){T("No linked local workspace for this Cloud chat.","error");return}if($a(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ee=ht("local",ke.id);i({type:"selectProject",projectId:ee}),y(ee),x(!1),T(`Switched to Local: ${ke.name}`,"info");return}if(!f){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}if(R){N({status:"ready",cloudProjectId:R.id,teamId:R.teamId,projectName:R.name,projectKind:"cloud",projectUrl:Ib({accountBaseUrl:$,organizationSlug:R.organizationSlug,projectSlug:R.slug}),setupUrl:zm({accountBaseUrl:$,teamId:R.teamId,projectId:R.id,projectName:R.name,baseBranch:R.defaultBranch,source:"openpond-app"}),branch:R.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const Ee=A;if(!Ee){T("Select a Project before Cloud coding.","error");return}const xe=F?.currentBranch||Ee.linkedSandboxProject?.defaultBranch||"main";X(Ee,xe)},[$,t,n,a,r,i,l,f,m,y,k,X,R,A,D,z,N,x,I,T,F?.currentBranch,q]),ye=g.useCallback(K=>{Qp(K)&&X(K.project)},[X]);return{changeWorkspaceTarget:we,moveProjectToCloud:ye,openCloudSetupForLocalProject:X,startCloudSetupUpload:re}}function _6({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:r,prepareTrainingTurn:i,sendPrompt:s,setMentionedAppId:l,showToast:p}){return g.useCallback(async(m=[],f=null,S,y={})=>{const k=S??n.getSnapshot(),R=i(k);if(R.active&&k.trim()&&!R.metadata)return p(R.error??"Load the selected generated Taskset question before sending, or close the generated-question handoff to write a normal prompt.","error"),!1;const A=await s(m,f,S,{clearPrompt:y.preservePrompt?()=>{}:void 0,displayPrompt:y.displayPrompt,onSessionCreated:D=>{a(D),R.metadata&&t(D.id)},turnMetadata:R.metadata||y.turnMetadata?{...R.metadata??{},...y.turnMetadata??{}}:void 0,sessionMetadata:R.metadata?{trainingTasksetId:R.metadata.trainingTasksetId,trainingTasksetName:R.metadata.trainingTasksetName}:void 0});return A&&await r?.(),A&&R.metadata&&e(),A},[e,t,n,a,r,i,s,l,p])}function w6({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:r,setSessions:i,setView:s}){return g.useCallback(async l=>{if(!t)return;const p=n.find(S=>!S.archived&&S.workspaceKind==="sandbox"&&S.workspaceId===l.sandboxId);if(p){e({type:"selectSession",sessionId:p.id,appId:null,projectId:null}),r("changes"),a(!0),s("chat");return}const m=l.name??`Sandbox ${l.sandboxId.slice(0,8)}`,f=await J.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:l.sandboxId,workspaceName:m,cwd:null,title:m});i(S=>[f,...S]),e({type:"selectSession",sessionId:f.id,appId:null,projectId:null}),r("changes"),a(!0),s("chat")},[e,t,n,a,r,i,s])}function I6({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:r,openExistingProjectDialog:i,applyBootstrapPayload:s,expandProject:l,setExpandedProjectIds:p,setSelectedAppId:m,setSelectedProjectId:f,setSelectedSessionId:S,setError:y,setView:k,showToast:R}){function A(P){const j=ht("local",P.id);m(null),f(j),S(null),k("chat"),l(j)}async function D(P){if(!e)return!1;y(null);const j=P.trim();if(!j)return!1;try{const T=await J.createLocalProject(e,{path:j});return s(T.bootstrap),A(T.project),R(T.created===!1?`Opened ${T.project.name}`:`Added ${T.project.name}`,"success"),!0}catch(T){return y(T instanceof Error?T.message:String(T)),R("Project folder could not be added","error"),!1}}async function z(){if(e){if(y(null),window.openpond?.selectFolder){const P=await window.openpond.selectFolder();if(P.canceled||!P.path)return;await D(P.path);return}i()}}async function N(P){if(!e)return!1;const j=P.trim();if(!j)return!1;y(null);try{const T=await J.createLocalProject(e,{createNew:!0,name:j});return s(T.bootstrap),A(T.project),R(`Created ${T.project.name}`,"success"),!0}catch(T){return y(T instanceof Error?T.message:String(T)),R("Project could not be created","error"),!1}}async function x(P){if(!e)return!1;const j=P.trim();if(!j)return!1;y(null);try{const T=await J.organizations(e),F=zc(T.organizations.map(Mc).filter(X=>!!X).filter(X=>X.status==="active"),t);if(!F)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!Lc(F))throw new Error(`You need owner or admin access to create projects in ${F.displayName}.`);const q=`${Kx(j)}-${Date.now().toString(36)}`;let $=(await J.upsertSandboxProject(e,{teamId:F.teamId,name:j,sourceType:"internal_repo",normalizedSourceIdentity:q,internalRepoPath:q,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:q},metadata:{source:"openpond-app-new-cloud-project"}})).project;$=(await J.uploadSandboxProjectSource(e,$.id,{teamId:F.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:tq(`# ${j}
158
-
159
- Created in OpenPond Cloud.
160
- `)}]})).project;const V=await J.bootstrap(e);s(V);const re=ht("cloud",$.id);return m(null),f(re),S(null),k("chat"),l(re),R(`Created Cloud Project: ${$.name}`,"success"),!0}catch(T){const F=T instanceof Error?T.message:String(T);return y(F),R(F,"error"),!1}}async function I(P){if(!e)return;if(zL(P)){const q=`Archive ${P.project.name} in OpenPond Cloud?`;if(!(r?await r({title:"Archive Cloud Project",body:`${P.project.name} will be archived in OpenPond Cloud. Existing task history stays available through Cloud history.`,confirmLabel:"Archive project"}):window.confirm(q)))return;y(null);try{await J.archiveSandboxProject(e,P.project.id,{teamId:P.project.teamId}),s(await J.bootstrap(e)),p(V=>{const re=new Set(V);return re.delete(P.id),re}),a===P.id&&(f(null),S(null)),R(`Archived ${P.project.name}`,"success")}catch(V){y(V instanceof Error?V.message:String(V)),R("Cloud Project could not be archived","error")}return}if(!Qp(P))return;const j=P.project,T=`Remove ${j.name} from Projects? The folder will not be deleted.`;if(r?await r({title:"Remove Project",body:`${j.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(T)){y(null);try{const q=await J.deleteLocalProject(e,j.id);s(q),p($=>{const V=new Set($);return V.delete(P.id),V}),a===P.id&&(f(null),S($=>{const V=n.find(re=>re.id===$);return V?.workspaceKind==="local_project"&&V.workspaceId===j.id?null:$})),R(`Removed ${j.name}`,"success")}catch(q){y(q instanceof Error?q.message:String(q)),R("Project could not be removed","error")}}}return{addProjectFolder:z,addProjectFolderPath:D,createCloudProjectFromScratch:x,createProjectFromScratch:N,removeProject:I}}function C6({addProjectFolder:e,addProjectFolderPath:t,appDispatch:n,busy:a,cloudProjectById:r,createCloudProjectFromScratch:i,createProjectFromScratch:s,expandProject:l,localProjectById:p,onCreateCloudEnvironment:m,onNewCloudProject:f,onNewLocalProject:S,onUseExistingFolderPath:y,newProjectBusy:k,newProjectMode:R,newProjectName:A,newProjectPath:D,projectTargetValue:z,setDiffPanelOpen:N,setDraftModel:x,setDraftProvider:I,setError:P,setNewProjectBusy:j,setNewProjectDialogOpen:T,setNewProjectName:F,setNewProjectPath:q,showToast:$,workspaceBusy:V}){const re=g.useCallback(we=>{if(we===z||a||V)return;if(P(null),we==="action:new-local-project"){S();return}if(we==="action:add-local-project"){e();return}if(we==="action:add-local-project-path"){y();return}if(we==="action:new-cloud-project"){f();return}if(we==="action:create-cloud-environment"){m();return}if(we==="none"){n({type:"selectProject",projectId:null}),N(!1),$("Started a chat without project files.","info");return}const ye=we.indexOf(":"),K=ye>=0?we.slice(0,ye):"",Ee=ye>=0?we.slice(ye+1):"";if(K==="local"){const xe=p.get(Ee);if(!xe){$("Project is no longer available.","error");return}const se=ht("local",xe.id);n({type:"selectProject",projectId:se}),l(se),N(!1);return}if(K==="cloud"){const xe=r.get(Ee);if(!xe){$("Cloud Project is no longer available.","error");return}const se=ht("cloud",xe.id);n({type:"selectProject",projectId:se}),l(se),I("openpond"),x(ke=>ko("openpond",ke)),N(!1)}},[e,n,a,r,l,p,m,f,S,y,z,N,x,I,P,$,V]),X=g.useCallback(async()=>{const we=A.trim(),ye=D.trim();if(!k&&!(R==="existing-local"?!ye:!we)){j(!0);try{(R==="cloud"?await i(we):R==="existing-local"?await t(ye):await s(we))&&(T(!1),F(""),q(""))}finally{j(!1)}}},[t,i,s,k,R,A,D,j,T,F,q]);return{changeProjectTarget:re,submitNewProjectDialog:X}}function R6(e){return{id:`right-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,activationVersion:1,sessionId:e.sessionId,prompt:e.prompt??"",provider:e.provider,model:e.model,scrollTop:0,stickyToBottom:!0}}function LW(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function A6(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const r=e.map(i=>i.id!==t?i:(a=!0,{...i,activationVersion:n}));return a?r:[...e]}function P6(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const r=e.map(i=>i.sessionId!==t.sessionId?i:(a=!0,{...i,activationVersion:n,prompt:t.prompt??i.prompt}));return a?r:[...e]}function Yk(e){return!!(e.parentSessionId&&e.subagentRunId)}function T6(e){const t=e.sessions.filter(Yk);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function E6(e,t){const n=new Set(e.map(r=>r.sessionId).filter(Boolean)),a=t.filter(Yk).filter(r=>!n.has(r.id)).map(r=>({id:`right-subagent-${r.id}`,activationVersion:1,sessionId:r.id,prompt:"",provider:r.provider,model:r.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const Eb="openpond/openpond",M6="github.issue.write";function j6(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(M6))}function zW(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
161
- `)}function O6(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${Eb}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${Eb}, a concise title, and a complete issue body that preserves the request.`,"This slash command is the user's explicit intent to create the issue.","Before creating, search open issues in the repository for an obvious duplicate. If a clear duplicate exists, do not create a new issue; report the existing issue instead.","",`Issue request:
162
- ${t}`].join(`
163
- `)}function N6(e,t){const n=t.trim();switch(e.id){case"agent":return{kind:"send_prompt",prompt:`/agent ${n}`,requiresInstructions:!0};case"skill":return{kind:"send_prompt",prompt:`/skill ${n}`,requiresInstructions:!1};case"goal":return{kind:"send_prompt",prompt:`/goal ${n}`,requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:O6(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const Mb=[];function $6(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:r,rightChatHistoryEvents:i,rightChatPanels:s,runningSessionIds:l,selectedSessionId:p,sidebarSessions:m}=e;return g.useMemo(()=>{const f=new Map(m.map(y=>[y.id,y])),S=D6(t);return s.map(y=>{const k=y.sessionId?f.get(y.sessionId)??null:null,R=Mt(y.sessionId),A=R?(y.sessionId?i[y.sessionId]:void 0)??(y.sessionId===p?n:Mb):Mb,D=Rm(A,[]),z=y.sessionId?S.get(y.sessionId)??null:null,N=!!(k&&l.has(k.id)),x=R?uH({events:A}):null,I=k?.cwd??null,P=k?.appId??k?.localProjectId??(k?.workspaceKind==="local_project"?k.workspaceId??null:null)??(k?.cwd&&!$a(k.workspaceKind)?Gv(k.cwd):null),j=y.sessionId?r[y.sessionId]??null:null;return{...y,session:k,title:mH(x,k?.title??"New task"),messages:R?lk(Nc(A),j):[],createImproveRun:x,contextWindowStatus:kx({provider:y.provider,snapshot:Lx(D,y.sessionId),preferences:a}),goalRuntime:zx(D,y.sessionId),pendingApproval:z,running:N,workspaceRootPath:I,activeWorkspaceAppId:P,pendingUserMessage:j,runtimeSource:R?"history":"live"}})},[t,n,a,r,i,s,l,p,m])}function D6(e){const t=new Map;for(const n of e){if(n.status!=="pending")continue;const a=t.get(n.sessionId);(!a||Date.parse(n.createdAt)>Date.parse(a.createdAt))&&t.set(n.sessionId,n)}return t}function L6(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:r,sessions:i,setError:s}=e,l=g.useMemo(()=>{const f=new Set,S=[];for(const y of r)!Mt(y.sessionId)||!y.sessionId||f.has(y.sessionId)||(f.add(y.sessionId),S.push(y.sessionId));return S.join(`
164
- `)},[r]),p=g.useMemo(()=>{if(!l)return"";const f=new Set(l.split(`
165
- `).filter(Boolean));return i.filter(S=>f.has(S.id)&&S.status==="active").map(S=>S.id).join(`
166
- `)},[l,i]),m=g.useMemo(()=>l?l.split(`
167
- `).filter(f=>a.has(f)).join(`
168
- `):"",[a,l]);g.useEffect(()=>{if(!n||!l)return;const f=l.split(`
169
- `).filter(Boolean),S=new Set(p.split(`
170
- `).filter(Boolean)),y=new Set(m.split(`
171
- `).filter(Boolean)),k=f.map(R=>uf({connection:n,locallyActive:y.has(R),onError:A=>s(A instanceof Error?A.message:String(A)),onPayload:A=>t(df(A,y.has(R))),reportedActive:S.has(R),sessionId:R,surface:"thread"}));return()=>k.forEach(R=>R())},[p,t,n,m,l,s])}const jb=[];function z6(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:r,codexHistoryEvents:i,connectedAppMentions:s,connection:l,contextCompaction:p,openLabTraining:m,locallyActiveCodexHistorySessionIds:f,openPondCommandAccessMode:S,pendingChatUserMessages:y,providerSettings:k,rightChatHistoryEvents:R,rightChatPanels:A,rightPanelMode:D,runtimeIndexes:z,runtimeEventStore:N,runningSessionIds:x,selectedSession:I,selectedSessionId:P,sendPrompt:j,setDiffPanelOpen:T,setError:F,setRightChatHistoryEvents:q,setRightChatPanels:$,setRightPanelMode:V,setRightPanelTabRequest:re,setView:X,showChangesPanel:we,showToast:ye,sidebarSessions:K,startupReady:Ee}=e,xe=g.useRef(null),se=g.useRef(new Map),ke=g.useRef(new Set);g.useEffect(()=>{if(!l)return;const Be=A.flatMap(He=>He.sessionId&&!Mt(He.sessionId)?[He.sessionId]:[]);for(const He of Be)Object.hasOwn(R,He)||ke.current.has(He)||(ke.current.add(He),J.runtimeEventsPage(l,{sessionId:He,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(Ne=>{const E=Ne.events.map(U=>U.event);q(U=>({...U,[He]:Ka(U[He]??jb,E)}))}).catch(Ne=>{F(Ne instanceof Error?Ne.message:String(Ne))}).finally(()=>{ke.current.delete(He)}))},[l,R,A,F,q]);const ee=g.useCallback(Be=>{re(He=>({id:(He?.id??0)+1,tab:Be})),we()},[we]),pe=g.useCallback((Be=null,He={})=>{const Ne=Be?.id?A.find(U=>U.sessionId===Be.id)??null:null;if(Ne)return $(U=>P6(U,{sessionId:Be.id,prompt:He.prompt})),T(!0),V("chat"),He.preserveView||X("chat"),Ne.id;const E=R6({sessionId:Be?.id??null,provider:Be?.provider??n,model:Be?.modelRef?.modelId??t,prompt:He.prompt});return $(U=>[...U,E]),T(!0),V("chat"),He.preserveView||X("chat"),E.id},[t,n,A,T,$,V,X]);g.useEffect(()=>{if(!Ee)return;const Be=xe.current;if(!Be){xe.current=new Set(K.filter(U=>!!(U.parentSessionId&&U.subagentRunId)).map(U=>U.id));return}const He=T6({sessions:K,knownSessionIds:Be});xe.current=He.knownSessionIds;for(const U of He.newSessions)se.current.set(U.id,U);const Ne=I?.parentSessionId??I?.id??null;if(!Ne)return;const E=[...se.current.values()].filter(U=>U.parentSessionId===Ne);if(E.length!==0){for(const U of E)se.current.delete(U.id);$(U=>E6(U,E)),T(!0),V("chat")}},[I?.id,I?.parentSessionId,T,$,V,K,Ee]);const ve=g.useCallback(()=>{if(A.length===0){pe(null);return}T(!0),V("chat"),X("chat")},[pe,A.length,T,V,X]),qe=g.useCallback(Be=>{const He=A.length<=1&&A.some(E=>E.id===Be),Ne=()=>{$(E=>E.filter(U=>U.id!==Be))};if(He&&D==="chat"){if(ee("files"),typeof window>"u"){Ne();return}window.requestAnimationFrame(Ne);return}Ne()},[A,D,$,ee]),Re=g.useCallback((Be,He)=>{$(Ne=>Ne.map(E=>E.id===Be?{...E,prompt:He}:E))},[$]),ie=g.useCallback(Be=>{$(He=>A6(He,Be))},[$]),Ie=g.useCallback((Be,He)=>{$(Ne=>Ne.map(E=>E.id===Be?{...E,...He}:E))},[$]),$e=g.useCallback((Be,He)=>{$(Ne=>Ne.map(E=>E.id===Be?{...E,model:He}:E))},[$]),Je=g.useCallback((Be,He)=>{$(Ne=>Ne.map(E=>E.id===Be?{...E,provider:He,model:ko(He,E.model,k)}:E))},[k,$]);L6({applyPayload:r,connection:l,locallyActiveSessionIds:f,panels:A,sessions:K,setError:F});const et=$6({approvals:a,codexHistoryEvents:i,contextCompaction:p,pendingChatUserMessages:y,rightChatHistoryEvents:R,rightChatPanels:A,runningSessionIds:x,selectedSessionId:P,sidebarSessions:K}),st=g.useCallback(async(Be,He=[],Ne=null,E=null,U={})=>{const G=A.find(at=>at.id===Be);if(!G)return!1;const me=U.promptOverride??G.prompt,W=E?N6(E,me):null;if(W?.kind==="open_training")return He.length>0?(ye("/train uses this chat; add other chats from Models.","error"),!1):(m({objective:W.objective,sessionId:G.sessionId}),U.preservePrompt||Re(Be,""),!0);if(E&&W?.kind==="send_prompt"&&W.requiresInstructions&&!me.trim())return ye(`Add instructions after ${E.command}.`,"info"),!1;if(E&&He.length>0)return ye(`${E.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(E?.id==="submit-issue"&&!j6(s))return ye("Connect the GitHub app before using /submit-issue.","error"),!1;const de=G.sessionId?K.find(at=>at.id===G.sessionId)??null:null,he=G.provider==="codex"?S:de?.openPondCommandAccessMode??S,We=W?.kind==="send_prompt"?W.prompt:me,Ze=Mt(G.sessionId)?(G.sessionId?R[G.sessionId]:void 0)??(G.sessionId===P?i:jb):N.getSessionEvents(G.sessionId),tt=Mt(G.sessionId)&&G.sessionId?at=>{const Te=G.sessionId;q(De=>({...De,[Te]:Ka(De[Te]??Ze,[at])}))}:void 0;return j(He,Ne,We,{session:de,selectSession:!1,provider:G.provider,model:G.model,openPondCommandAccessMode:he,chatMessages:Nc(Ze),displayPrompt:U.displayPrompt,turnMetadata:U.turnMetadata,usageAttribution:E?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:E.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:tt,clearPrompt:U.preservePrompt?()=>{}:()=>Re(Be,""),onSessionCreated:at=>{$(Te=>Te.map(De=>De.id===Be?{...De,sessionId:at.id,provider:at.provider,model:at.modelRef?.modelId??De.model}:De))}})},[i,s,R,A,z,N,P,m,S,j,$,X,K,ye,Re]);return{activateRightChatPanel:ie,closeRightChatPanel:qe,openRightChatPanel:pe,rightChatPanelViews:et,showRightChatPanel:ve,showRightPanelDiffTab:ee,submitRightChatPrompt:st,updateRightChatModel:$e,updateRightChatPrompt:Re,updateRightChatProvider:Je,updateRightChatScrollState:Ie}}function U6(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:r,setCodexHistorySessions:i,setError:s,setSelectedSessionId:l,setSessions:p}=e;async function m(z,N){if(!n)return;const x=t[z]??{},I={...x,...N,archived:N.pinned?!1:N.archived??x.archived};r(P=>({...P,[z]:I}));try{const P=await J.patchSidebarAppPreference(n,z,N);r(j=>({...j,[z]:P}))}catch(P){s(P instanceof Error?P.message:String(P)),r(j=>({...j,[z]:x}))}}function f(z){m(z.id,{pinned:!z.pinned,archived:!1})}async function S(z,N){if(!n)return;const x=Mt(z.id)?i:p,I={...z,...N};x(P=>P.some(j=>j.id===z.id)?P.map(j=>j.id===z.id?I:j):[I,...P]);try{const P=await J.patchSession(n,z.id,N);x(j=>j.some(T=>T.id===P.id)?j.map(T=>T.id===P.id?P:T):[P,...j])}catch(P){s(P instanceof Error?P.message:String(P)),x(j=>j.map(T=>T.id===z.id?z:T))}}function y(z){S(z,{pinned:!1,savedForLater:!z.savedForLater,archived:!1})}function k(z){S(z,{pinned:!z.pinned,savedForLater:!1,archived:!1})}function R(z){S(z,{pinned:!1,savedForLater:!1,archived:!0}),a===z.id&&l(null)}function A(z){S(z,{archived:!1})}function D(z,N){const x=N.trim();!x||x===z.title||S(z,{title:x})}return{archiveSession:R,renameSession:D,restoreSession:A,toggleProjectPinned:f,toggleSessionPinned:k,toggleSessionSavedForLater:y}}function H6(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function q6({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:r,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,draftModel:p,draftProvider:m,cloudProjects:f,selectedApp:S,selectedProject:y,selectedProjectLinkedOpenPondApp:k,selectedSession:R,sessions:A,title:D,visibleWorkspaceDiff:z,visibleWorkspaceState:N,workspaceBusy:x,workspaceName:I,appDispatch:P,applyBootstrapPayload:j,expandProject:T,refreshWorkspace:F,refreshWorkspaceDiff:q,rememberWorkspaceState:$,setBranchDialogOpen:V,setCommitDialogOpen:re,setError:X,setSessions:we,setSettingsSection:ye,setSyncingWorkspaceAppId:K,setView:Ee,setWorkspaceBusy:xe,showToast:se}){function ke(){return`${ax(n.defaultBranchPrefix)}${H6(I??D??"new-branch")}`}function ee(){return I?`Update ${I}`:(z?.filesChanged??N?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function pe(Ne="commit"){P({type:"openCommitDialog",nextStep:Ne})}function ve(){P({type:"openBranchDialog",branchName:ke()})}function qe(){x||V(!1),ye("defaults"),Ee("settings"),Qt({kind:"settings",section:"defaults"})}async function Re(Ne){if(!(!e||!t)){xe(!0),X(null);try{const E=await J.checkoutWorkspaceBranch(e,t,{branch:Ne});$(E),E.initialized&&q(t)}catch(E){X(E instanceof Error?E.message:String(E))}finally{xe(!1)}}}async function ie(){if(!e||!t)return;const Ne=r.trim();if(Ne){xe(!0),X(null);try{const E=await J.createWorkspaceBranch(e,t,{branch:Ne});$(E),E.initialized&&q(t),V(!1),se(`Checked out ${Ne}`,"success")}catch(E){X(E instanceof Error?E.message:String(E))}finally{xe(!1)}}}async function Ie(Ne){K(Ne);const E=a?.apps.find(U=>U.id===Ne)?.name??a?.localProjects.find(U=>U.id===Ne)?.name??"Workspace";try{const U=await F(Ne,!0);U?.initialized&&Ne===t&&q(Ne),U?.initialized&&!U.error?se(`${E} synced locally`,"success"):U?.error&&se("Workspace sync failed","error")}finally{K(U=>U===Ne?null:U)}}async function $e(){t&&await Ie(t)}async function Je(Ne,E,U={}){if(!e)return null;const G=R&&!Mt(R.id)?R:null;if(W6(E,G,U)||G&&B6(G,y,S))return G;const me=G?await et(G):null;if(me)return me;const W=F6(A,y,S);if(W){const Ze=W.workspaceKind==="local_project"&&W.workspaceId?ht("local",W.workspaceId):null;return P({type:"selectSession",sessionId:W.id,appId:W.appId,projectId:Ze}),W.workspaceKind==="local_project"&&W.workspaceId&&T(ht("local",W.workspaceId)),W}const de=sa(y,f),he=await J.createSession(e,{provider:m,modelRef:ba(m,p,a?.providers??null),appId:k?.appId??S?.id??null,appName:k?.appName??S?.name??null,workspaceKind:y?"local_project":S?"sandbox_app":void 0,workspaceId:y?.id??S?.id??null,workspaceName:y?.name??S?.name??null,localProjectId:y?.id??null,cloudProjectId:de?.id??null,cloudTeamId:de?.teamId??null,cwd:y?y.workspacePath:null,title:Ne});we(Ze=>[he,...Ze]);const We=he.workspaceKind==="local_project"&&he.workspaceId?ht("local",he.workspaceId):null;return P({type:"selectSession",sessionId:he.id,appId:he.appId,projectId:We}),he.workspaceKind==="local_project"&&he.workspaceId&&T(ht("local",he.workspaceId)),he}async function et(Ne){if(!e||!y||!k?.appId||Mt(Ne.id)||Ne.workspaceKind==="local_project"||Ne.appId!==k.appId)return null;const E=sa(y,f),U=await J.patchSession(e,Ne.id,{appId:k.appId,appName:k.appName,workspaceKind:"local_project",workspaceId:y.id,workspaceName:y.name,localProjectId:y.id,cloudProjectId:E?.id??null,cloudTeamId:E?.teamId??null,cwd:y.workspacePath});return we(G=>G.map(me=>me.id===U.id?U:me)),P({type:"selectSession",sessionId:U.id,appId:U.appId,projectId:ht("local",y.id)}),T(ht("local",y.id)),U}async function st(Ne,E={}){if(!e)return null;const U=await Je(I?`${I} workspace`:"Workspace action",Ne,E);if(!U)return null;const G=await J.workspaceTool(e,U.id,{action:Ne,args:E,source:"ui_button"});se(G.output,G.ok?"success":"error"),j(await J.bootstrap(e));const me=G.appId??V6(U);return me&&(await F(me,!1))?.initialized&&await q(me),G}async function Be(Ne,E={}){if(Ne==="git_commit"&&typeof E.message!="string")return pe("commit"),null;xe(!0),X(null);try{return await st(Ne,E)}catch(U){return X(U instanceof Error?U.message:String(U)),null}finally{xe(!1)}}async function He(){const Ne=s.trim()||ee(),E=l==="commit_publish",U=E&&!!N?.remoteUrl;if(!(U&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){xe(!0),X(null);try{if(!(await st("git_commit",{message:Ne,includeUnstaged:i}))?.ok||l==="commit_push"&&!(await st("git_push",{runChecks:!1}))?.ok||E&&!(await st("publish_openpond_repo",{replaceOrigin:U}))?.ok)return;re(!1)}catch(G){X(G instanceof Error?G.message:String(G))}finally{xe(!1)}}}return{changeWorkspaceBranch:Re,openCommitDialog:pe,openCreateWorkspaceBranchDialog:ve,openDefaultsSettingsFromBranchDialog:qe,runWorkspaceTool:Be,submitCommitDialog:He,submitCreateWorkspaceBranch:ie,syncWorkspaceLocally:$e,syncWorkspaceLocallyForApp:Ie}}function B6(e,t,n){return!t&&!n?!0:Xk(e,t,n)}function F6(e,t,n){if(!t&&!n)return null;let a=null,r=Number.NEGATIVE_INFINITY;for(const i of e){if(i.archived||!Xk(i,t,n))continue;const s=Date.parse(i.updatedAt),l=Number.isFinite(s)?s:0;(!a||l>r)&&(a=i,r=l)}return a}function Xk(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function V6(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function W6(e,t,n={}){return(K6(e)||Z6(e,n))&&G6(t)}function K6(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function G6(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function Z6(e,t){if(e!=="sandbox_create")return!1;const n=t.runtime;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.runtimeId=="string"&&n.runtimeId.trim())}function J6(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const Y6=[];function X6(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:r,cloudSetupDialog:i,setCloudSetupDialog:s,setRightPanelTabRequest:l,workspaceDiffPanelViewState:p,setWorkspaceDiffPanelViewState:m,rightChatHistoryEvents:f,setRightChatHistoryEvents:S,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:k,draftSubagentDelegationMode:R,setDraftSubagentDelegationMode:A,confirmProjectAction:D,view:z,selectedAppId:N,selectedProjectId:x,selectedSessionId:I,draftProvider:P,draftModel:j,activeExperience:T,codexPermissionMode:F,codexReasoningEffort:q,openPondCommandAccessMode:$,busy:V,diffPanelOpen:re,diffPanelExpanded:X,rightPanelMode:we,rightChatPanels:ye,newProjectMode:K,newProjectName:Ee,newProjectPath:xe,newProjectBusy:se,commitMessage:ke,commitIncludeUnstaged:ee,commitNextStep:pe,branchDialogName:ve,setSectionMenuOpen:qe,setView:Re,setSelectedAppId:ie,setSelectedProjectId:Ie,setSelectedSessionId:$e,setPrompt:Je,setDraftProvider:et,setDraftModel:st,setDiffPanelOpen:Be,setRightPanelMode:He,setRightChatPanels:Ne,setSyncingWorkspaceAppId:E,setSettingsSection:U,setNewProjectDialogOpen:G,setNewProjectMode:me,setNewProjectName:W,setNewProjectPath:de,setNewProjectBusy:he,setCommitDialogOpen:We,setBranchDialogOpen:Ze,setError:tt,showToast:at,appPreferences:Te,applyBootstrapPayload:De,approvals:u,bootstrap:M,connection:H,events:ae,runtimeEventStore:O,sessions:Z,startup:_,setAppPreferences:L,setCodexHistorySessions:oe,setEvents:Q,setSessions:Y,cloudProjectById:ue,localProjectById:le,selectedApp:ze,selectedCloudProject:Pe,selectedProject:Oe,selectedProjectLinkedOpenPondApp:Ye,selectedSession:Le,sidebarSessions:ut,runtimeIndexes:Gt,connectedAppMentions:gn,codexHistoryEvents:bn,setCodexHistoryEvents:sn,account:Pt,accountPending:It,accountSignedOut:vn,activeModel:Ct,activeProvider:$t,activeWorkspaceAppId:Bt,activeWorkspaceKind:Yt,activeWorkspaceLocation:en,appDefaults:un,selectedSessionProjectId:An,workspaceName:La,accountScopeKey:Ft,teamChat:Ln,communities:lt,selectedProjectConfirmedCloudProject:Dt,activeOpenPondCommandAccessMode:te,viewWorkspaceAppId:Ke,viewWorkspaceId:Ge,viewWorkspaceKind:yt,openPondActionCatalog:mn,selectedActionCatalog:ka,expandProject:Pn,setExpandedProjectIds:Zt,advanceTrainingModelChatAfterTurn:bt,bindTrainingModelChatSession:tn,prepareTrainingModelChatTurn:St,chatMessages:ft,pendingChatUserMessages:Tt,recordPendingChatUserMessage:pn,runningSessionIds:zn,workspaceBusy:Xe,visibleWorkspaceState:yn,visibleWorkspaceDiff:vt,rememberWorkspaceState:fn,refreshWorkspace:Tn,setWorkspaceBusy:xn,refreshWorkspaceDiffWhenNeeded:_a,setPendingWorkspaceTarget:da,pendingSidebarWorkspaceTarget:ua,setPendingSidebarWorkspaceTarget:ma,projectTarget:ct,workspaceTarget:mi}=e,ta=z==="apps"?"Apps":z==="get-started"?"Walkthroughs":z==="labs"?"Models":z==="scheduled"?"Workflows":z==="outputs"?"Outputs":z==="projects"?"Projects":z==="team"?Ln.detail?J6(Ln.detail.thread,Ln.currentUserId):"Team Chat":z==="community"?lt.preview?.displayName??"Communities":Le?.title??WS(T),{browserConversationId:wa,handleWorkspaceDiffPanelViewStateChange:wo}=x6({appDispatch:n,diffPanelExpanded:X,diffPanelOpen:re,rightChatPanels:ye,rightPanelMode:we,selectedAppId:N,selectedCloudProject:Pe,selectedProjectId:x,selectedSession:Le,selectedSessionId:I,setWorkspaceDiffPanelViewState:m,view:z,viewWorkspaceAppId:Ke,viewWorkspaceId:Ge,viewWorkspaceKind:yt,workspaceDiffPanelViewState:p}),rr=g.useCallback(dt=>{Qt({kind:"chat",sessionId:dt}),$e(dt),ie(null),Ie(null),Re("chat")},[ie,Ie,$e,Re]),pa=g.useCallback(()=>{me("existing-local"),W(""),de(""),G(!0)},[G,me,W,de]),pi=g.useCallback(()=>{me("local"),W(""),de(""),G(!0)},[G,me,W,de]),{addProjectFolder:Io,addProjectFolderPath:ir,createCloudProjectFromScratch:sr,createProjectFromScratch:fi,removeProject:hi}=I6({connection:H,defaultTeamId:un.defaultTeamId,sessions:Z,selectedProjectId:x,confirmProjectAction:D,openExistingProjectDialog:pa,applyBootstrapPayload:De,expandProject:Pn,setExpandedProjectIds:Zt,setSelectedAppId:ie,setSelectedProjectId:Ie,setSelectedSessionId:$e,setError:tt,setView:Re,showToast:at}),{changeWorkspaceBranch:Ia,openCommitDialog:gi,openCreateWorkspaceBranchDialog:lr,openDefaultsSettingsFromBranchDialog:cr,runWorkspaceTool:dr,submitCommitDialog:bi,submitCreateWorkspaceBranch:na,syncWorkspaceLocally:vi}=q6({connection:H,activeWorkspaceAppId:Bt,appDefaults:un,bootstrap:M,branchDialogName:ve,commitIncludeUnstaged:ee,commitMessage:ke,commitNextStep:pe,draftModel:j,draftProvider:P,cloudProjects:M?.cloudProjects??[],selectedApp:ze,selectedProject:Oe,selectedProjectLinkedOpenPondApp:Ye,selectedSession:Le,sessions:Z,title:ta,visibleWorkspaceDiff:vt,visibleWorkspaceState:yn,workspaceBusy:Xe,workspaceName:La,appDispatch:n,applyBootstrapPayload:De,expandProject:Pn,refreshWorkspace:Tn,refreshWorkspaceDiff:_a,rememberWorkspaceState:fn,setBranchDialogOpen:Ze,setCommitDialogOpen:We,setError:tt,setSessions:Y,setSettingsSection:U,setSyncingWorkspaceAppId:E,setView:Re,setWorkspaceBusy:xn,showToast:at}),yi=f6({applyBootstrapPayload:De,cloudProjects:M?.cloudProjects??[],connection:H,localProjectById:le,selectedCloudProject:Pe,selectedProject:Oe,setWorkspaceBusy:xn,showToast:at,visibleWorkspaceState:yn}),Si=M?.preferences.subagents.delegationMode??"manual",xi=Le?.subagentDelegationMode??R,ur=!!(T==="development"&&M?.preferences.subagents.enabled&&$t!=="codex"&&!Mt(I)&&!Le?.subagentRunId),mr=g.useCallback(dt=>{if(!Le){A(dt);return}if(!H||Mt(Le.id)||Le.subagentRunId)return;const jt=Le.id,qn=Le.subagentDelegationMode??null;Y(hn=>hn.map(kn=>kn.id===jt?{...kn,subagentDelegationMode:dt}:kn)),J.patchSession(H,jt,{subagentDelegationMode:dt}).then(hn=>{Y(kn=>kn.map(Yn=>Yn.id===hn.id?hn:Yn))}).catch(hn=>{Y(kn=>kn.map(Yn=>Yn.id===jt?{...Yn,subagentDelegationMode:qn}:Yn)),tt(hn instanceof Error?hn.message:String(hn))})},[H,Le,tt,Y]),pr=g.useCallback(dt=>{S(jt=>jt[dt.session.id]===dt.events?jt:{...jt,[dt.session.id]:dt.events}),oe(jt=>jc(jt,dt.session))},[oe]),{answerCreateImproveQuestion:no,applyCreateImproveCandidate:Co,approveCreateImproveRun:za,cancelCreateImproveRun:Un,changeDraftProvider:ki,openCreateImprovePullRequest:_i,reconcileCreateImprovePullRequest:nn,rejectCreateImproveCandidate:Ro,pauseCreateImproveRun:Hn,resumeCreateImproveRun:fa,reviseCreateImproveRun:Ao,sendPrompt:Ca,stopTurn:wi}=c6({applyBootstrapPayload:De,bootstrap:M,chatMessages:ft,connection:H,codexPermissionMode:F,codexReasoningEffort:q,openPondCommandAccessMode:te,draftModel:j,draftProvider:P,experience:T,expandProject:Pn,getPrompt:t.getSnapshot,apps:M?.apps??[],connectedAppMentions:gn,mentionedAppId:a,ensureCloudSessionReady:yi,refreshWorkspace:Tn,refreshWorkspaceDiff:_a,selectedApp:ze,selectedActionCatalog:ka,openPondActionCatalog:mn,cloudProjects:M?.cloudProjects??[],accountScopeKey:Ft,selectedCloudProject:Pe,selectedProject:Oe,selectedProjectLinkedOpenPondApp:Ye,selectedSession:Le,sessions:Z,workspaceTarget:mi.value,subagentDelegationMode:Le?.subagentDelegationMode??R,setDraftModel:st,setDraftProvider:et,setError:tt,setPrompt:Je,setMentionedAppId:r,setCodexHistoryEvents:sn,setCodexHistorySessions:oe,onCodexHistoryTurnActivityChange:k,onCodexHistoryTurnPayload:pr,onPendingUserMessage:pn,setEvents:Q,setSelectedAppId:ie,setSelectedProjectId:Ie,setSelectedSessionId:$e,setSessions:Y,setView:Re,setWorkspaceBusy:xn}),{archiveSession:Po,restoreSession:Ii,renameSession:To,toggleProjectPinned:fr,toggleSessionPinned:Eo,toggleSessionSavedForLater:hr}=U6({appPreferences:Te,connection:H,selectedSessionId:I,setAppPreferences:L,setCodexHistorySessions:oe,setError:tt,setSelectedSessionId:$e,setSessions:Y}),{changeWorkspaceTarget:Mo,moveProjectToCloud:gr,startCloudSetupUpload:aa}=k6({account:Pt,accountPending:It,accountSignedOut:vn,activeWorkspaceKind:Yt,activeWorkspaceLocation:en,appDispatch:n,applyBootstrapPayload:De,busy:V,cloudSetupDialog:i,cloudProjects:M?.cloudProjects??[],connection:H,defaultTeamId:un.defaultTeamId,expandProject:Pn,localProjectById:le,selectedCloudProject:Pe,selectedProject:Oe,selectedSession:Le,selectedSessionProjectId:An,setCloudSetupDialog:s,setDiffPanelOpen:Be,setError:tt,setSessions:Y,setWorkspaceBusy:xn,showToast:at,visibleWorkspaceState:yn,workspaceBusy:Xe}),ao=g.useCallback(async dt=>{if(T==="work"&&!Le){if(dt==="local"){da("local"),at(Oe?`Next task will use the local ${Oe.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(dt==="cloud"&&!Oe&&!Pe){if(It){at("Checking OpenPond account. Try again in a moment.","info");return}if(vn){at("Add an OpenPond account before using Hosted.","error");return}da("cloud"),at("Next task will use Hosted without a Project.","info");return}}if(dt==="hybrid"){const jt=Pe?.id??Dt?.id??Le?.cloudProjectId??null,qn=Pe?.teamId??Dt?.teamId??Le?.cloudTeamId??null;if(It){at("Checking OpenPond account. Try again in a moment.","info");return}if(vn){at("Add an OpenPond account before using Hybrid.","error");return}if(!jt||!qn){da(null),at("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Le&&!Mt(Le.id)){if(Da(Le))return;if(!H){at("OpenPond App server is not connected.","error");return}const hn=await J.patchSession(H,Le.id,{provider:P,modelRef:ba(P,j,M?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Pe?.name??Dt?.name??Oe?.name??Le.workspaceName??"Hybrid workspace",localProjectId:Oe?.id??Le.localProjectId??null,cloudProjectId:jt,cloudTeamId:qn,metadata:Bx(Le.metadata),cwd:Oe?.workspacePath??Le.cwd??null});Y(kn=>kn.map(Yn=>Yn.id===hn.id?hn:Yn)),da(null),at("Hybrid will use your selected model with hosted sandbox edits.","info");return}da("hybrid"),at("Next message will use Hybrid with a hosted sandbox.","info");return}da(null),await Mo(dt)},[It,vn,T,M?.providers,Mo,H,j,P,Pe?.id,Pe?.name,Pe?.teamId,Oe?.id,Dt?.id,Dt?.name,Dt?.teamId,Oe?.name,Oe?.workspacePath,Le,da,Y,at]),jo=g.useCallback((dt,jt)=>{ie(null),Ie(dt),$e(null),Re("chat"),Pn(dt),ma({projectId:dt,target:jt})},[Pn,ie,Ie,$e,Re]);g.useEffect(()=>{if(!ua||z!=="chat"||x!==ua.projectId||I!==null)return;const dt=ua.target;ma(null),ao(dt)},[ao,ua,x,I,z]);const Ua=_6({advanceTrainingTurn:bt,bindTrainingSession:tn,composerDraftStore:t,onSessionCreated:dt=>{Qt({kind:"chat",sessionId:dt.id}),A(null)},onSubmitted:async()=>{const dt=Le;if(!(!H||!dt||!ws(dt)))try{const jt=await J.patchSession(H,dt.id,{metadata:GL(dt.metadata)});Y(qn=>qn.map(hn=>hn.id===jt.id?jt:hn))}catch(jt){at(jt instanceof Error?`Task started, but its Draft label could not be cleared: ${jt.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:St,sendPrompt:Ca,setMentionedAppId:r,showToast:at}),br=w6({appDispatch:n,connection:H,sessions:Z,setDiffPanelOpen:Be,setRightPanelMode:He,setSessions:Y,setView:Re}),{createCloudEnvironmentFromSidebar:Ra,openCloudProjectDialog:vr,openUrlInBrowserPanel:Ci,showBrowserPanel:Oo,showChangesPanel:yr,showGoalSidebarTab:Sr}=E3({account:Pt,browserConversationId:wa,cloudProjectById:ue,cloudProjects:M?.cloudProjects??[],diffPanelOpen:re,rightPanelMode:we,selectedProjectId:x,setDiffPanelOpen:Be,setNewProjectDialogOpen:G,setNewProjectMode:me,setNewProjectName:W,setRightPanelMode:He}),{changeProjectTarget:xr,submitNewProjectDialog:Ri}=C6({addProjectFolder:Io,addProjectFolderPath:ir,appDispatch:n,busy:V,cloudProjectById:ue,createCloudProjectFromScratch:sr,createProjectFromScratch:fi,expandProject:Pn,localProjectById:le,newProjectBusy:se,newProjectMode:K,newProjectName:Ee,newProjectPath:xe,onCreateCloudEnvironment:Ra,onNewCloudProject:vr,onNewLocalProject:pi,onUseExistingFolderPath:pa,projectTargetValue:ct.value,setDiffPanelOpen:Be,setDraftModel:st,setDraftProvider:et,setError:tt,setNewProjectBusy:he,setNewProjectDialogOpen:G,setNewProjectName:W,setNewProjectPath:de,showToast:at,workspaceBusy:Xe}),kr=g.useMemo(()=>Z.map(dt=>dt.id),[Z]);j3({browserConversationId:wa,sessionIds:kr,onOpenSession:rr,onShowBrowserPanel:Oo});const[_r,oo]=g.useState(null),Aa=g.useCallback(dt=>{oo({id:Date.now(),objective:dt.objective,initialSessionIds:dt.sessionId?[dt.sessionId]:[]}),Fr({kind:"index"}),Re("labs")},[Re]),{activateRightChatPanel:Ai,closeRightChatPanel:Pi,openRightChatPanel:Ti,rightChatPanelViews:wr,showRightChatPanel:Pa,showRightPanelDiffTab:ro,submitRightChatPrompt:Ei,updateRightChatModel:Ha,updateRightChatPrompt:No,updateRightChatProvider:Jn,updateRightChatScrollState:Mi}=z6({activeModel:Ct,activeProvider:$t,approvals:u,applyRightCodexHistoryPayload:pr,codexHistoryEvents:bn,connectedAppMentions:gn,connection:H,contextCompaction:un.contextCompaction,openLabTraining:Aa,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:$,pendingChatUserMessages:Tt,providerSettings:M?.providers??null,rightChatHistoryEvents:f,rightChatPanels:ye,rightPanelMode:we,runtimeIndexes:Gt,runtimeEventStore:O,runningSessionIds:zn,selectedSession:Le,selectedSessionId:I,sendPrompt:Ca,setDiffPanelOpen:Be,setError:tt,setRightChatHistoryEvents:S,setRightChatPanels:Ne,setRightPanelMode:He,setRightPanelTabRequest:l,setView:Re,showChangesPanel:yr,showToast:at,sidebarSessions:ut,startupReady:_.ready}),ji=g.useCallback(()=>{qe(null),U("profile"),Re("settings"),Qt({kind:"settings",section:"profile"})},[qe,U,Re]),Oi=g.useMemo(()=>Wa(M?.diagnostics??Y6,ae.filter(dt=>dt.name==="diagnostic")),[M?.diagnostics,ae]),Ni=g.useCallback(()=>{if(re){Be(!1);return}if(z==="labs"){He("changes"),l({id:Date.now(),tab:"summary"}),Be(!0);return}He("home"),Be(!0)},[re,Be,He,l,z]);return{title:ta,browserConversationId:wa,handleWorkspaceDiffPanelViewStateChange:wo,openSessionInChat:rr,openExistingProjectPathDialog:pa,addProjectFolder:Io,removeProject:hi,changeProjectTarget:xr,submitNewProjectDialog:Ri,changeWorkspaceBranch:Ia,openCommitDialog:gi,openCreateWorkspaceBranchDialog:lr,openDefaultsSettingsFromBranchDialog:cr,runWorkspaceTool:dr,submitCommitDialog:bi,submitCreateWorkspaceBranch:na,syncWorkspaceLocally:vi,subagentDelegationDefaultMode:Si,subagentDelegationMode:xi,subagentDelegationAvailable:ur,changeSubagentDelegationMode:mr,answerCreateImproveQuestion:no,applyCreateImproveCandidate:Co,approveCreateImproveRun:za,cancelCreateImproveRun:Un,changeDraftProvider:ki,openCreateImprovePullRequest:_i,reconcileCreateImprovePullRequest:nn,rejectCreateImproveCandidate:Ro,pauseCreateImproveRun:Hn,resumeCreateImproveRun:fa,reviseCreateImproveRun:Ao,sendPrompt:Ca,stopTurn:wi,archiveSession:Po,restoreSession:Ii,renameSession:To,toggleProjectPinned:fr,toggleSessionPinned:Eo,toggleSessionSavedForLater:hr,moveProjectToCloud:gr,startCloudSetupUpload:aa,changeWorkspaceTarget:ao,switchProjectWorkspaceTarget:jo,sendPromptFromMainComposer:Ua,openSandboxWorkspace:br,createCloudEnvironmentFromSidebar:Ra,openCloudProjectDialog:vr,openUrlInBrowserPanel:Ci,showBrowserPanel:Oo,showChangesPanel:yr,showGoalSidebarTab:Sr,rightChatTrainingLaunchRequest:_r,setRightChatTrainingLaunchRequest:oo,closeRightChatPanel:Pi,openRightChatPanel:Ti,rightChatPanelViews:wr,showRightChatPanel:Pa,showRightPanelDiffTab:ro,submitRightChatPrompt:Ei,activateRightChatPanel:Ai,updateRightChatModel:Ha,updateRightChatPrompt:No,updateRightChatProvider:Jn,updateRightChatScrollState:Mi,openProfileSettings:ji,diagnosticEvents:Oi,toggleRightSidebar:Ni}}function Q6(){const e=w3(),t=X6(e);return v.jsx(GH,{primary:e,secondary:t})}const UW=Object.freeze(Object.defineProperty({__proto__:null,App:Q6},Symbol.toStringTag,{value:"Module"}));export{Ka as $,gD as A,eg as B,bo as C,mW as D,NW as E,HD as F,FD as G,ko as H,jW as I,km as J,HV as K,dW as L,uq as M,zW as N,oU as O,Q3 as P,kW as Q,cW as R,VS as S,uW as T,yW as U,BU as V,ba as W,ui as X,uH as Y,Or as Z,Mt as _,Yo as a,hV as a$,lk as a0,QV as a1,$H as a2,h4 as a3,XV as a4,xW as a5,f4 as a6,Qn as a7,$a as a8,Jk as a9,LV as aA,zV as aB,QC as aC,NH as aD,OH as aE,qS as aF,BS as aG,YD as aH,Gm as aI,UV as aJ,qV as aK,HS as aL,gm as aM,bV as aN,op as aO,OU as aP,OV as aQ,Tc as aR,Xp as aS,Qt as aT,bm as aU,gL as aV,gV as aW,Ym as aX,Xm as aY,xD as aZ,Su as a_,j6 as aa,O6 as ab,A3 as ac,eW as ad,sL as ae,Yp as af,zL as ag,Gp as ah,zS as ai,Pc as aj,hW as ak,Qp as al,vg as am,Jp as an,LU as ao,Am as ap,nq as aq,$W as ar,ZH as as,Ag as at,Mc as au,zU as av,ff as aw,ax,TD as ay,ND as az,MF as b,vW as b$,DW as b0,zc as b1,QD as b2,SV as b3,dc as b4,Zp as b5,US as b6,Kp as b7,nW as b8,sW as b9,kV as bA,CV as bB,IV as bC,wV as bD,_V as bE,oy as bF,lM as bG,zs as bH,RV as bI,TV as bJ,PV as bK,AV as bL,jL as bM,TL as bN,Fr as bO,og as bP,RL as bQ,_D as bR,ZD as bS,Ib as bT,R3 as bU,Rm as bV,zx as bW,kx as bX,Lx as bY,LW as bZ,mb as b_,lW as ba,Tg as bb,oW as bc,Tu as bd,iW as be,rW as bf,dk as bg,aW as bh,Pg as bi,tW as bj,Rt as bk,OA as bl,yV as bm,Wx as bn,xV as bo,jV as bp,fu as bq,vV as br,Vn as bs,KV as bt,GV as bu,ZV as bv,JV as bw,VV as bx,WV as by,SW as bz,gt as c,Cb as c0,Um as c1,fW as c2,uk as c3,gW as c4,bW as c5,PW as c6,jD as c7,IW as c8,_W as c9,wW as ca,U4 as cb,J6 as cc,CW as cd,RW as ce,AW as cf,fL as cg,KD as ch,rx as ci,BV as cj,Is as ck,EV as cl,MV as cm,FV as cn,UW as co,Ho as d,Ac as e,$V as f,pW as g,YV as h,Wp as i,q3 as j,EW as k,OW as l,Kk as m,MW as n,J as o,FL as p,NV as q,DV as r,_s as s,Jl as t,Eb as u,Bo as v,xf as w,In as x,TW as y,Gx as z};